blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
960662ab132bd268920e761cc854db36cc3e0bf9
8efc7fd4ed561f048ce444ce79eea32bcc32c605
/Tree/iterative traversal using stack.cpp
c3763b98081642f626c222066b88543d2c047751
[]
no_license
nandinicodes1/My-DSA
6acec1d47134bb9447e0393341110b9ae3a8be47
78e7facd7b87a31567b0174b05538da341c172e8
refs/heads/master
2023-05-05T20:26:36.572168
2021-05-26T18:24:10
2021-05-26T18:24:10
371,131,578
0
0
null
null
null
null
UTF-8
C++
false
false
1,399
cpp
#include<iostream> using namespace std; class node{ public: int data; node*left; node*right; node(int data) { this->data=data; left=NULL; right=NULL; } }; node* buildTree() { int data; cin>>data; if(data==-1) { return NULL; } node* root=new node(data); root->left=buildTree(); root->right=buildTree(); return root; } //Iterative traversal preorder vector<int> pre(node* root,vector<int> &v){ stack<node*> s; while(1){ while(root){ v.push_back(root->data); s.push(root); root=root->left; } if(s.empty())break; root=s.top(); s.pop(); root=root->right; } return v; } vector<int> in(node* root,vector<int> &v){ stack<node*> s; while(1){ while(root){ s.push(root); root=root->left; } if(s.empty())break; root=s.top(); s.pop(); root=root->right; } return v; } vector<int> post(node* root,vector<int> &v){ if(root==NULL)return {}; stack<node*> s; s.push(root); while(!s.empty()){ node* topNode = s.top(); if(topNode->left){ s.push(topNode->left); topNode->left = NULL; continue; } if(topNode->right){ s.push(topNode->right); topNode->right = NULL; continue; } v.push_back(topNode->val); s.pop(); } return v; } int main() { node*root=buildTree(); printPre(root); cout<<endl; printIn(root); cout<<endl; printPost(root); return 0; }
45eaadddd2b53e65027ede561a021b3c9859ed3d
d93159d0784fc489a5066d3ee592e6c9563b228b
/DataFormats/HcalDigi/interface/HcalQIESample.h
c26c1b0c4ce9c61e01ceb5067a25f62f73929665
[]
permissive
simonecid/cmssw
86396e31d41a003a179690f8c322e82e250e33b2
2559fdc9545b2c7e337f5113b231025106dd22ab
refs/heads/CAallInOne_81X
2021-08-15T23:25:02.901905
2016-09-13T08:10:20
2016-09-13T08:53:42
176,462,898
0
1
Apache-2.0
2019-03-19T08:30:28
2019-03-19T08:30:24
null
UTF-8
C++
false
false
1,358
h
#ifndef DIGIHCAL_HCALQIESAMPLE_H #define DIGIHCAL_HCALQIESAMPLE_H #include <ostream> #include <boost/cstdint.hpp> /** \class HcalQIESample * Simple container packer/unpacker for a single QIE data word * * * \author J. Mans - Minnesota */ class HcalQIESample { public: HcalQIESample() { theSample=0; } HcalQIESample(uint16_t data) { theSample=data; } HcalQIESample(int adc, int capid, int fiber, int fiberchan, bool dv=true, bool er=false); /// get the raw word uint16_t raw() const { return theSample; } /// get the ADC sample int adc() const { return theSample&0x7F; } /// get the nominal FC (no calibrations applied) double nominal_fC() const; /// get the Capacitor id int capid() const { return (theSample>>7)&0x3; } /// is the Data Valid bit set? bool dv() const { return (theSample&0x0200)!=0; } /// is the error bit set? bool er() const { return (theSample&0x0400)!=0; } /// get the fiber number int fiber() const { return ((theSample>>13)&0x7)+1; } /// get the fiber channel number int fiberChan() const { return (theSample>>11)&0x3; } /// get the id channel int fiberAndChan() const { return (theSample>>11)&0x1F; } /// for streaming uint16_t operator()() { return theSample; } private: uint16_t theSample; }; std::ostream& operator<<(std::ostream&, const HcalQIESample&); #endif
4619defea4472b6a1d95ffb62a61305d71e2a880
c4360aa83fbd3fe988b5e2d6f073eac4cc8c49a8
/hello.cpp
4bfd72368e1683fd7bfe22889e19010ddc172e87
[]
no_license
lucken99/CompetitivePro
d9e66e14128c92a04f44fe484258a39fab88e0fe
3c88e944c62d3755873bdfe5919409b1fa283ea3
refs/heads/master
2023-08-21T17:43:01.414921
2021-10-03T16:07:44
2021-10-03T16:07:44
298,874,682
0
4
null
2021-10-03T16:07:45
2020-09-26T18:22:55
C++
UTF-8
C++
false
false
296
cpp
// Simple C++ program to display "Hello World" // Header file for input output functions #include<iostream> using namespace std; // main function - where the execution of program begins int main() { // Output cout<<"Hello World!"; return 0; }
fdf10c8046acc043cd909e130aac4ef4f0b63ef1
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE23_Relative_Path_Traversal/s02/CWE23_Relative_Path_Traversal__char_environment_ofstream_15.cpp
1cb090b820690d49105765e5f949f33628423197
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
4,236
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE23_Relative_Path_Traversal__char_environment_ofstream_15.cpp Label Definition File: CWE23_Relative_Path_Traversal.label.xml Template File: sources-sink-15.tmpl.cpp */ /* * @description * CWE: 23 Relative Path Traversal * BadSource: environment Read input from an environment variable * GoodSource: Use a fixed file name * Sink: ofstream * BadSink : Open the file named in data using ofstream::open() * Flow Variant: 15 Control flow: switch(6) * * */ #include "std_testcase.h" #ifdef _WIN32 #define BASEPATH "c:\\temp\\" #else #include <wchar.h> #define BASEPATH "/tmp/" #endif #define ENV_VARIABLE "ADD" #ifdef _WIN32 #define GETENV getenv #else #define GETENV getenv #endif #include <fstream> using namespace std; namespace CWE23_Relative_Path_Traversal__char_environment_ofstream_15 { #ifndef OMITBAD void bad() { char * data; char dataBuffer[FILENAME_MAX] = BASEPATH; data = dataBuffer; switch(6) { case 6: { /* Append input from an environment variable to data */ size_t dataLen = strlen(data); char * environment = GETENV(ENV_VARIABLE); /* If there is data in the environment variable */ if (environment != NULL) { /* POTENTIAL FLAW: Read data from an environment variable */ strncat(data+dataLen, environment, FILENAME_MAX-dataLen-1); } } break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; } { ofstream outputFile; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ outputFile.open((char *)data); outputFile.close(); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the switch to switch(5) */ static void goodG2B1() { char * data; char dataBuffer[FILENAME_MAX] = BASEPATH; data = dataBuffer; switch(5) { case 6: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; default: /* FIX: Use a fixed file name */ strcat(data, "file.txt"); break; } { ofstream outputFile; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ outputFile.open((char *)data); outputFile.close(); } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the switch */ static void goodG2B2() { char * data; char dataBuffer[FILENAME_MAX] = BASEPATH; data = dataBuffer; switch(6) { case 6: /* FIX: Use a fixed file name */ strcat(data, "file.txt"); break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; } { ofstream outputFile; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ outputFile.open((char *)data); outputFile.close(); } } void good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE23_Relative_Path_Traversal__char_environment_ofstream_15; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
00257f21a34f19adfa9e91e04e05112edbc388df
f49af15675a8528de1f7d929e16ded0463cb88e6
/C++/C++ Advanced/AdvancedClassMembers/00PitfalMissingConstOnOverloadForSTL/00PitfalMissingConstOnOverloadForSTL.cpp
4e4c45ea7aeecbde3f7ebcbacd2361bb65c6da5f
[]
no_license
genadi1980/SoftUni
0a5e207e0038fb7855fed7cddc088adbf4cec301
6562f7e6194c53d1e24b14830f637fea31375286
refs/heads/master
2021-01-11T18:57:36.163116
2019-05-18T13:37:19
2019-05-18T13:37:19
79,638,550
2
0
null
null
null
null
UTF-8
C++
false
false
1,435
cpp
// 00PitfalMissingConstOnOverloadForSTL.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "pch.h" #include <iostream> #include <set> class Fraction { int numerator; int denominator; public: Fraction(int num, int denom) : numerator(num), denominator(denom) {} int getNumerator() const { return this->numerator; } int getDenominator() const { return this->denominator; } bool operator<(const Fraction& other) const { return this->numerator * other.denominator < other.numerator * this->denominator; } }; int main() { std::set<Fraction> fractions{ Fraction{ 1, 3 }, Fraction{ 2, 10 }, Fraction{ 2, 6 } }; for (Fraction f : fractions) { std::cout << f.getNumerator() << "/" << f.getDenominator() << std::endl; } return 0; } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
95e993dc6506a3df5bce600b5458c1fe9084b113
debf2431df291d8c3ca266863472e13bb14d1e9e
/server/include/StartCommand.h
dfeffc16d6422319a2554817ce8ba5415b516ea5
[]
no_license
nagar-omer/reversi-java
e89756014c2646f330190a4d9b4e6838da78defa
65e5471e0cab8a113304416ac776a6764b36bc88
refs/heads/master
2023-06-22T21:30:57.431797
2018-01-25T08:53:31
2018-01-25T08:53:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,800
h
/***************************************************************************** * Student Name: Oved Nagar * * Id: 302824875 * * Student Name: Orly Paknahad * * Id: 315444646 * * Exercise name: Ex7 * ****************************************************************************/ #ifndef SERVER_STARTCOMMAND_H #define SERVER_STARTCOMMAND_H #include <algorithm> #include <iostream> #include <sstream> #include <unistd.h> #include <string> #include "Command.h" using namespace std; /***************************************************************************** * Class name: StartCommand inherite from Command * function name: execute * params: vector of string, player socket * operation: call the func addNewGame and add the game if not * exist ****************************************************************************/ class StartCommand: public Command { public: virtual void execute(vector<string> args, int player) { //remove "\n" from name of game args[1].erase(std::remove(args[1].begin(), args[1].end(), '\n'), args[1].end()); char * msg= "-1\n"; //check if the game exist- send the game name and player if(GameManager::getGameManager()->addNewGame(args[1],player) < 0) { cout << "the game is already exist- send to player -1" << endl; //the game is already exist- send to player -1 int n = write(player, "-1\n", strlen("-1\n")); } } }; #endif //SERVER_STARTCOMMAND_H
[ "[email protected] config --global user.email [email protected] config --global user.email [email protected]" ]
[email protected] config --global user.email [email protected] config --global user.email [email protected]
df939b728c1550430c17000dbb24674b93a0ce07
eb159429a128f7d9c639e6af1ea9f365bd1c7cc0
/125. Valid Palindrome.cpp
91ce14ecc4ab16e651b314bdbf9d53e6a0ec172e
[]
no_license
xanarry/leetcode
12dbd2729b336fb82ad8ef41394625369dce7294
19380e255c506a2b58831a7078d76db3955e41ef
refs/heads/master
2020-03-25T06:30:06.692407
2018-08-06T05:48:06
2018-08-06T05:48:06
143,506,008
0
0
null
null
null
null
UTF-8
C++
false
false
416
cpp
class Solution { public: bool isPalindrome(string s) { int i = 0, j = s.length() - 1; while (i < j) { while (i < j && !isalnum(s[i])) i++; while (i < j && !isalnum(s[j])) j--; cout << s[i] << "-" << s[j] << endl; if ((s[i] | 32) != (s[j] | 32)) return false; i++; j--; } return true; } };
4c4636febb9a3bac68fa285d7b5cd0a494745caf
6e59c9389347ffa86eb839a6d7bc9cab7b79871f
/C++ Applications/RobotSimulator/labs/lab07/src/circular_obstacle.h
8b326b19b1c20ace6e2808b3ec6d231ab1c89bb2
[]
no_license
JonnySunny/Courses-Project
e1b2c22bc4d97969dbac82386cc800a8fa145514
5ca8cb01650fd02da4e936759a0e5b85e62a792b
refs/heads/master
2020-03-27T23:45:56.273304
2018-09-04T12:57:04
2018-09-04T12:57:04
147,344,676
1
0
null
null
null
null
UTF-8
C++
false
false
1,492
h
/** * @file circular_obstacle.h * * @copyright 2017 3081 Staff, All rights reserved. */ #ifndef SRC_CIRCULAR_OBSTACLE_H_ #define SRC_CIRCULAR_OBSTACLE_H_ /******************************************************************************* * Includes ******************************************************************************/ #include <string> #include "src/arena_immobile_entity.h" /******************************************************************************* * Namespaces ******************************************************************************/ NAMESPACE_BEGIN(csci3081); /******************************************************************************* * Class Definitions ******************************************************************************/ /** * @brief A class that represents are circular, immobile entity within the * arena, which we are defining as an "obstacle". * */ class CircularObstacle: public ArenaImmobileEntity { public: explicit CircularObstacle(double radius); CircularObstacle(double radius, const Position& pos, const nanogui::Color& color); /** * @brief Get the name of circular obstacle, for use in visualization and * debugging */ std::string get_name(void) const override { return "Circular Obstacle" + std::to_string(id_); } private: static uint next_id_; int id_; }; NAMESPACE_END(csci3081); #endif /* SRC_CIRCULAR_OBSTACLE_H_ */
c6139cb67c9888caf1e5dfbfa4c7f7ce8dbd72be
ccb9a8752eb5a5bc70305c65a1611736836a3e45
/test/test_checked_right_shift.cpp
6d37aea9822d1618ea27116fe99936a6bb52d7ca
[ "BSL-1.0" ]
permissive
boostorg/safe_numerics
5a1a8d903edbf312731345462dbf39d7fa39469d
13ca3d6dd36db1aac2d6b5caca2c281d15c881ad
refs/heads/develop
2023-08-18T20:08:56.199185
2022-06-07T01:22:59
2022-06-07T01:22:59
5,021,752
132
32
BSL-1.0
2022-09-16T13:19:51
2012-07-13T16:14:14
C++
UTF-8
C++
false
false
3,827
cpp
// Copyright (c) 2012 Robert Ramey // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <iostream> #include <boost/core/demangle.hpp> #include <boost/safe_numerics/checked_result.hpp> #include <boost/safe_numerics/checked_result_operations.hpp> #include <boost/safe_numerics/checked_integer.hpp> // note: T should be of tyme checked_result<R> for some integer type R template<class T> bool test_checked_right_shift( T v1, T v2, char expected_result ){ using namespace boost::safe_numerics; const T result = v1 >> v2; std::cout << v1 << " >> " << v2 << " -> " << result << std::endl; switch(expected_result){ case '.': if(result.exception()){ std::cout << "erroneously detected error in right shift " << std::endl; v1 >> v2; return false; } return true; case '-': if(safe_numerics_error::negative_overflow_error == result.m_e) return true; break; case '+': if(safe_numerics_error::positive_overflow_error == result.m_e) return true; break; case '!': if(safe_numerics_error::range_error == result.m_e) return true; break; case 'n': // n negative_shift if(safe_numerics_error::negative_shift == result.m_e) return true; break; case 's': // s negative_value_shift if(safe_numerics_error::negative_value_shift == result.m_e) return true; break; case 'l': // l shift_too_large if(safe_numerics_error::shift_too_large == result.m_e) return true; break; default: assert(false); } std::cout << "failed to detect error in right shift " << std::hex << result << "(" << std::dec << result << ")" << " != "<< v1 << " >> " << v2 << std::endl; v1 >> v2; return false; } #include "test_checked_right_shift.hpp" template<typename T, typename First, typename Second> struct test_signed_pair { bool operator()() const { std::size_t i = First(); std::size_t j = Second(); std::cout << std::dec << i << ',' << j << ',' << "testing " << boost::core::demangle(typeid(T).name()) << ' '; return test_checked_right_shift( signed_values<T>[i], signed_values<T>[j], signed_right_shift_results[i][j] ); }; }; template<typename T, typename First, typename Second> struct test_unsigned_pair { bool operator()() const { std::size_t i = First(); std::size_t j = Second(); std::cout << std::dec << i << ',' << j << ',' << "testing " << boost::core::demangle(typeid(T).name()) << ' '; return test_checked_right_shift( unsigned_values<T>[i], unsigned_values<T>[j], unsigned_right_shift_results[i][j] ); }; }; #include <boost/mp11/algorithm.hpp> int main(){ using namespace boost::mp11; bool rval = true; std::cout << "*** testing signed values\n"; mp_for_each< mp_product< test_signed_pair, signed_test_types, signed_value_indices, signed_value_indices > >([&](auto I){ rval &= I(); }); std::cout << "*** testing unsigned values\n"; mp_for_each< mp_product< test_unsigned_pair, unsigned_test_types, unsigned_value_indices, unsigned_value_indices > >([&](auto I){ rval &= I(); }); std::cout << (rval ? "success!" : "failure") << std::endl; return rval ? 0 : 1; }
b0b6b7f0dc51466d6f4d38f59414ceeaa9cfe953
d2f4ac4a36a6416c56a7eb1bef463ec82f333381
/SnakeGame.hpp
76713dd0ae8755528e7ad9806b837f64dcc8e084
[]
no_license
scott9600/-
e6c9ed0c04b6c769ab9c24933017141ede020324
7489aa2a6193b3b1f6a1d7772abe060d415f8525
refs/heads/master
2020-10-01T22:18:50.731418
2019-12-12T18:14:23
2019-12-12T18:14:23
227,635,648
0
0
null
null
null
null
UTF-8
C++
false
false
5,715
hpp
#pragma once #include <iostream> #include <string> #include <list> #include <cstdio> #include <cstdlib> #include <ctime> #include <cassert> // 윈도우 및 리눅스 호환성을 위한 헤더 파일 #ifdef _WIN32 #include <Windows.h> #else #endif // 맵 크기 설정 #define MAP_SIZE_X 81 #define MAP_SIZE_Y 21 // 콘솔에 표시되는 모양 설정 #define SHAPE_WALL '#' #define SHAPE_SNAKE '@' #define SHAPE_FEED 'F' // 뱀 이동 방향 상수 #define UP 0 #define DOWN 1 #define LEFT 2 #define RIGHT 3 class Point { public: int x; int y; Point() { this->x = 0; this->y = 0; } Point(int x, int y) { this->x = x; this->y = y; } bool operator==(const Point& p) { return this->x == p.x && this->y == p.y; } bool operator!=(const Point& p) { return !(*this == p); } Point operator+(const Point& p) { return Point(this->x + p.x, this->y + p.y); } Point operator-(const Point& p) { return Point(this->x - p.x, this->y - p.y); } }; class SnakeGame { private: char map[MAP_SIZE_Y][MAP_SIZE_X + 1]; std::list<Point> snake; std::size_t length; int direction; Point feedPos; void gotoConsoleCursor(int x, int y); public: SnakeGame(); void addSnake(); void moveSnake(); void setDirection(int direction); bool checkEatFeed(); bool checkCollision(); void createFeed(); void printMap(); }; //================================================== // Private //================================================== // 콘솔의 커서 좌표 이동 void SnakeGame::gotoConsoleCursor(int x, int y) { #ifdef _WIN32 COORD cursor; cursor.X = x; cursor.Y = y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cursor); #else printf("\033[%dd\033[%dG", y, x); #endif } //================================================== // Public //================================================== // 생성자 SnakeGame::SnakeGame() { // 맵 공백으로 초기화 for (int y = 0; y < MAP_SIZE_Y; y++) { for (int x = 0; x < MAP_SIZE_X; x++) { this->map[y][x] = ' '; } } // 맵 틀 그리기 for (int x = 0; x < MAP_SIZE_X; x++) { this->map[0][x] = this->map[MAP_SIZE_Y - 1][x] = SHAPE_WALL; } for (int y = 0; y < MAP_SIZE_Y; y++) { this->map[y][0] = this->map[y][MAP_SIZE_X - 1] = SHAPE_WALL; } // 맵 NULL 추가 (게임과는 관련이 없으며 오직 콘솔에 출력하기 위한 용도) for (int y = 0; y < MAP_SIZE_Y; y++) { this->map[y][MAP_SIZE_X] = NULL; } // 뱀 초기 길이 설정 this->length = 5; // 뱀 초기 위치 설정 (중앙에서 시작) for (std::size_t i = 0; i < this->length; i++) { int x = MAP_SIZE_X / 2 - this->length / 2 + i; int y = MAP_SIZE_Y / 2; this->snake.push_back(Point(x, y)); this->map[y][x] = SHAPE_SNAKE; } // 뱀 초기 방향 설정 (왼쪽으로 시작) this->direction = LEFT; // 랜덤 시드 설정 srand((unsigned int)time(NULL)); // 먹이 생성 createFeed(); } // 뱀 길이 1 증가 void SnakeGame::addSnake() { Point snakeTail = this->snake.back(); Point addTail; // 추가할 수 있는 위치 계산 if (this->map[snakeTail.y][snakeTail.x - 1] == ' ') { addTail.x = snakeTail.x - 1; addTail.y = snakeTail.y; } else if (this->map[snakeTail.y][snakeTail.x + 1] == ' ') { addTail.x = snakeTail.x + 1; addTail.y = snakeTail.y; } else if (this->map[snakeTail.y - 1][snakeTail.x] == ' ') { addTail.x = snakeTail.x; addTail.y = snakeTail.y - 1; } else if (this->map[snakeTail.y + 1][snakeTail.x] == ' ') { addTail.x = snakeTail.x; addTail.y = snakeTail.y + 1; } // 뱀 꼬리 추가 this->snake.push_back(addTail); this->length++; this->map[addTail.y][addTail.x] = SHAPE_SNAKE; } // 뱀 이동 void SnakeGame::moveSnake() { Point dp; // 좌표 변화량 설정 switch (this->direction) { case UP: dp.x = 0; dp.y = -1; break; case DOWN: dp.x = 0; dp.y = 1; break; case LEFT: dp.x = -1; dp.y = 0; break; case RIGHT: dp.x = 1; dp.y = 0; break; } // 뱀 머리 추가 Point snakeHead = this->snake.front() + dp; this->snake.push_front(snakeHead); this->map[snakeHead.y][snakeHead.x] = SHAPE_SNAKE; // 뱀 꼬리 제거 Point snakeTail = this->snake.back(); this->snake.pop_back(); this->map[snakeTail.y][snakeTail.x] = ' '; } // 뱀 이동 방향 설정 void SnakeGame::setDirection(int direction) { assert(direction == UP || direction == DOWN || direction == LEFT || direction == RIGHT); this->direction = direction; } // 먹이를 먹었으면 true, 아니면 false 반환 bool SnakeGame::checkEatFeed() { return this->snake.front() == this->feedPos; } // 벽이나 자기 자신에게 부딪쳤으면 true, 아니면 false 반환 bool SnakeGame::checkCollision() { Point snakeHead = this->snake.front(); // 벽에 부딪쳤는지 체크 if (snakeHead.x <= 0 || snakeHead.x >= MAP_SIZE_X - 1) { return true; } if (snakeHead.y <= 0 || snakeHead.y >= MAP_SIZE_Y - 1) { return true; } // 자기 자신에게 부딪쳤는지 체크 std::list<Point>::iterator it = this->snake.begin(); it++; while (it != this->snake.end()) { if (*it == snakeHead) { return true; } it++; } return false; } // 먹이를 랜덤한 위치에 생성 void SnakeGame::createFeed() { int x; int y; // 뱀과 충돌하지 않도록 좌표 생성 do { x = rand() % (MAP_SIZE_X - 1) + 1; y = rand() % (MAP_SIZE_Y - 1) + 1; } while (this->map[y][x] != ' '); // 먹이 설정 feedPos = Point(x, y); this->map[y][x] = SHAPE_FEED; } // 맵 출력 void SnakeGame::printMap() { // 덮어쓰기를 위한 콘솔의 커서 좌표 이동 gotoConsoleCursor(0, 0); // 맵 출력 for (int y = 0; y < MAP_SIZE_Y; y++) { puts(this->map[y]); } }
89b842a15a6954aee330bc9b8aec8964a108b1c1
dd4ea6c4dc8c99d6553de987c5915de31b3d21d2
/be/src/pipeline/exec/hashjoin_probe_operator.h
54105e7f8b7cd37ed6c1a0e8825470a32e047572
[ "BSD-3-Clause", "PSF-2.0", "GPL-2.0-only", "Apache-2.0", "LicenseRef-scancode-public-domain", "dtoa", "MIT", "LicenseRef-scancode-facebook-patent-rights-2", "bzip2-1.0.6", "OpenSSL" ]
permissive
caiconghui/incubator-doris
ac6036e5162e1204dce59facc0f868f3026d4be6
dd869077f8ce3c2b19f29b3048c4e7e62ac31050
refs/heads/master
2023-08-31T20:57:15.392015
2023-01-19T07:56:51
2023-01-19T07:56:51
211,771,485
0
2
Apache-2.0
2019-09-30T03:57:01
2019-09-30T03:57:00
null
UTF-8
C++
false
false
1,571
h
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #pragma once #include "operator.h" namespace doris { namespace vectorized { class HashJoinNode; } namespace pipeline { class HashJoinProbeOperatorBuilder final : public OperatorBuilder<vectorized::HashJoinNode> { public: HashJoinProbeOperatorBuilder(int32_t, ExecNode*); OperatorPtr build_operator() override; }; class HashJoinProbeOperator final : public StatefulOperator<HashJoinProbeOperatorBuilder> { public: HashJoinProbeOperator(OperatorBuilderBase*, ExecNode*); // if exec node split to: sink, source operator. the source operator // should skip `alloc_resource()` function call, only sink operator // call the function Status open(RuntimeState*) override { return Status::OK(); } }; } // namespace pipeline } // namespace doris
b6576a7008a3bd87933f75c3fca5f2223aef50c2
d633caa9febaa29d496eaf92312ae341a38c9466
/mp_proxyserv/proxy_parse.cpp
2dd0c42d9bc92795e81af27dcf9c7fb9659db22c
[]
no_license
h1mal1a1/hiimparhelia
46b40cbd8032275e913513cfe8c0ec4461b4333e
23f17b9d8d182e99ba9b23458c4dcd34de86d206
refs/heads/master
2021-11-27T11:18:26.486946
2018-12-11T22:17:52
2018-12-11T22:17:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,506
cpp
#include <cstdlib> #include "proxy_parse.h" #define DEFAULT_NHDRS 8 //использую va_list, для того, чтобы передавать неизвестное кол-во параметров void debug(const char* format, ...) { va_list args; if(DEBUG) { va_start(args,format); vfprintf(stderr,format,args); va_end(args); } } int ParsedHeader_set(struct ParsedRequest* pr,const char* key, const char* value) { struct ParsedHeader* ph; ParsedHeader_remove(pr,key); if(pr->headerslen <= pr->headersused+1) { pr->headerslen=pr->headerslen*2; pr->headers=(struct ParsedHeader *)realloc(pr->headers,pr->headerslen*sizeof(struct ParsedHeader)); if(!pr->headers) return -1; ph = pr->headers+pr->headersused; pr->headersused+=1; ph->key=(char*)malloc(strlen(key)+1); memcpy(ph->key,key,strlen(key)); ph->key[strlen(key)]='\0'; ph->value=(char*)malloc(strlen(value)+1); memcpy(ph->value,value,strlen(value)); ph->value[strlen(value)] = '\0'; ph->keylen = strlen(key)+1; ph->valuelen = strlen(value)+1; return 0; } } /* Создаёт структуру заголовка */ void ParsedHeader_create(struct ParsedRequest* pr) { pr->headers = (struct ParsedHeader*)malloc(sizeof(struct ParsedHeader)*DEFAULT_NHDRS);//Выделяем память размером struct ParsedHeader * дефолтные значения заголовка pr->headerslen = DEFAULT_NHDRS; pr->headersused = 0; } struct ParsedHeader* ParsedHeader_get(struct ParsedRequest* pr, const char* key) { } //удаляет указанный ключ из parsedHeader int ParsedHeader_remove(struct ParsedRequest* pr, const char* key)//2 { struct ParsedHeader* tmp; tmp = ParsedHeader_get(pr,key); if(tmp == NULL) return -1; free(tmp->key); free(tmp->value); tmp->key=NULL; return 0; } /* size_t ParsedHeader_headersLen(struct ParsedRequest* pr) { } void ParsedRequest_destroy(struct ParsedRequest* pr) { } */ //создаём структуру PR struct ParsedRequest* ParsedRequest_create() { struct ParsedRequest *pr; pr = (struct ParsedRequest*)malloc(sizeof(struct ParsedRequest)); if(pr != NULL) { ParsedHeader_create(pr); pr->buf = NULL; pr->method = NULL; pr->protocol = NULL; pr->host = NULL; pr->path = NULL; pr->version = NULL; pr->buf = NULL; pr->buflen = 0; } return pr; } int ParsedHeader_parse(struct ParsedRequest* pr,char* line) { char* key; char* value; char* index1; char* index2; index1=index(line,':'); if(index1==NULL) { debug("No colon found\n"); return -1; } key=(char*)malloc((index1-line+1)*sizeof(char)); memcpy(key,line,index1-line); key[index1-line]='\0'; index1+=2; index2=strstr(index1,"\r\n"); memcpy(value,index1,(index2-index1)); value[index2-index1]='\0'; ParsedHeader_set(pr,key,value); free(key); free(value); return 0; } int ParsedRequest_unparse(struct ParsedRequest* pr,char* buf, size_t buflen) { } int ParsedRequest_unparse_headers(struct ParsedRequest* pr,char* buf, size_t buflen) { } size_t ParsedRequest_totalLen(struct ParsedRequest* pr) { } int ParsedRequest_parse(struct ParsedRequest* parse, const char* buf, int buflen) { }
d33bc2df43742e5f8eed19735dd35e213dfbd109
8dc84558f0058d90dfc4955e905dab1b22d12c08
/components/autofill/core/browser/webdata/autocomplete_sync_bridge.h
2b53c23779da6612db62630e82fdf8ce7102a622
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
3,480
h
// Copyright 2016 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 COMPONENTS_AUTOFILL_CORE_BROWSER_WEBDATA_AUTOCOMPLETE_SYNC_BRIDGE_H_ #define COMPONENTS_AUTOFILL_CORE_BROWSER_WEBDATA_AUTOCOMPLETE_SYNC_BRIDGE_H_ #include <memory> #include <string> #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/optional.h" #include "base/scoped_observer.h" #include "base/supports_user_data.h" #include "components/autofill/core/browser/webdata/autofill_change.h" #include "components/autofill/core/browser/webdata/autofill_webdata_service_observer.h" #include "components/sync/model/metadata_change_list.h" #include "components/sync/model/model_error.h" #include "components/sync/model/model_type_change_processor.h" #include "components/sync/model/model_type_sync_bridge.h" namespace autofill { class AutofillTable; class AutofillWebDataBackend; class AutofillWebDataService; class AutocompleteSyncBridge : public base::SupportsUserData::Data, public syncer::ModelTypeSyncBridge, public AutofillWebDataServiceObserverOnDBSequence { public: AutocompleteSyncBridge(); AutocompleteSyncBridge( AutofillWebDataBackend* backend, std::unique_ptr<syncer::ModelTypeChangeProcessor> change_processor); ~AutocompleteSyncBridge() override; static void CreateForWebDataServiceAndBackend( AutofillWebDataService* web_data_service, AutofillWebDataBackend* web_data_backend); static base::WeakPtr<syncer::ModelTypeSyncBridge> FromWebDataService( AutofillWebDataService* web_data_service); // syncer::ModelTypeSyncBridge implementation. std::unique_ptr<syncer::MetadataChangeList> CreateMetadataChangeList() override; base::Optional<syncer::ModelError> MergeSyncData( std::unique_ptr<syncer::MetadataChangeList> metadata_change_list, syncer::EntityChangeList entity_data) override; base::Optional<syncer::ModelError> ApplySyncChanges( std::unique_ptr<syncer::MetadataChangeList> metadata_change_list, syncer::EntityChangeList entity_changes) override; void GetData(StorageKeyList storage_keys, DataCallback callback) override; void GetAllData(DataCallback callback) override; std::string GetClientTag(const syncer::EntityData& entity_data) override; std::string GetStorageKey(const syncer::EntityData& entity_data) override; // AutofillWebDataServiceObserverOnDBSequence implementation. void AutofillEntriesChanged(const AutofillChangeList& changes) override; private: // Returns the table associated with the |web_data_backend_|. AutofillTable* GetAutofillTable() const; // Respond to local autofill entries changing by notifying sync of the // changes. void ActOnLocalChanges(const AutofillChangeList& changes); // Synchronously load sync metadata from the autofill table and pass it to the // processor so that it can start tracking changes. void LoadMetadata(); base::ThreadChecker thread_checker_; // AutocompleteSyncBridge is owned by |web_data_backend_| through // SupportsUserData, so it's guaranteed to outlive |this|. AutofillWebDataBackend* const web_data_backend_; ScopedObserver<AutofillWebDataBackend, AutocompleteSyncBridge> scoped_observer_; DISALLOW_COPY_AND_ASSIGN(AutocompleteSyncBridge); }; } // namespace autofill #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_WEBDATA_AUTOCOMPLETE_SYNC_BRIDGE_H_
2f8f2b69b7f7c9da0f57de446e3c638bc5c5f4ad
7bd5ca970fbbe4a3ed0c7dadcf43ba8681a737f3
/aoj/intro/ALDS/ALDS1_6_C.cpp
5190fa6dc4ee1605a8c5864eee6f82e1fa1028e3
[]
no_license
roiti46/Contest
c0c35478cd80f675965d10b1a371e44084f9b6ee
c4b850d76796c5388d2e0d2234f90dc8acfaadfa
refs/heads/master
2021-01-17T13:23:30.551754
2017-12-10T13:06:42
2017-12-10T13:06:42
27,001,893
0
0
null
null
null
null
UTF-8
C++
false
false
1,857
cpp
#include <iostream> #include <string> using namespace std; struct Card {char suit; int val; }; const int MAX = 100000, SENTINEL = 2100000000; Card L[MAX / 2 + 2], R[MAX / 2 + 2]; int cnt; void merge(Card A[], int n, int left, int mid, int right) { int n1 = mid - left; int n2 = right - mid; for (int i = 0; i < n1; i++) L[i] = A[left + i]; for (int i = 0; i < n2; i++) R[i] = A[mid + i]; L[n1].val = R[n2].val = SENTINEL; int i = 0, j = 0; for (int k = left; k < right; k++) { cnt++; if (L[i].val <= R[j].val) { A[k] = L[i++]; } else { A[k] = R[j++]; } } } void msort(Card A[], int n, int left, int right) { if (left + 1 < right) { int mid = (left + right) / 2; msort(A, n, left, mid); msort(A, n, mid, right); merge(A, n, left, mid, right); } } int partition(Card A[], int p, int r) { Card x = A[r]; int i = p - 1; for (int j = p; j < r; j++) { if (A[j].val <= x.val) { i++; swap(A[i], A[j]); } } swap(A[i + 1], A[r]); return i + 1; } void qsort(Card A[], int n, int p, int r) { if (p < r) { int q = partition(A, p, r); qsort(A, n, p, q - 1); qsort(A, n, q + 1, r); } } int main(void) { int n; Card A[MAX], B[MAX]; cin >> n; string s; int v; for (int i = 0; i < n; i++) { cin >> s >> v; A[i].suit = B[i].suit = s[0]; A[i].val = B[i].val = v; } msort(A, n, 0, n); qsort(B, n, 0, n - 1); int stable = 1; for (int i = 0; i < n; i++) { if (A[i].suit != B[i].suit) stable = 0; } cout << (stable ? "Stable" : "Not stable") << endl; for (int i = 0; i < n; i++) { cout << B[i].suit << " " << B[i].val << endl; } return 0; }
9038df451de7628d31d026bb113dc443ce8bbd57
6ae9c3fe53201557ad63b68cbfb3fbfc11cf390d
/src/logconsole.cpp
a2e88fe8c271712c239cd72bf49fa5841d916927
[]
no_license
BackupTheBerlios/qtex-svn
90cd46b7dc9f8a46568a2a1bbe570ea278830a15
efad541bd493e832dbe99b47bb688b74d0f7dede
refs/heads/master
2020-04-06T03:44:00.887807
2008-03-31T14:57:01
2008-03-31T14:57:01
40,806,234
0
0
null
null
null
null
UTF-8
C++
false
false
3,180
cpp
#include "logconsole.h" LogConsole::LogConsole(QWidget *parent) : QTextEdit(parent) { setReadOnly(true); m_errorFormat.setForeground(Qt::red); m_badBoxFormat.setForeground(Qt::darkGray); } void LogConsole::keyPressEvent(QKeyEvent *event) { event->ignore(); } void LogConsole::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { QTextBlock block = cursorForPosition(event->pos()).block(); if (block.isValid()) { QString text = block.text().trimmed(); if (text.endsWith(tr(" (No line found)"))) { return; } int startIndex = text.indexOf(QString(":")) + 2, endIndex = text.indexOf(QString(":"), startIndex); int line = text.mid(startIndex, endIndex - startIndex).trimmed().toInt(); m_editor->gotoLine(line); } } } void LogConsole::parse(QString cmd, QString str, int exitCode) { int errorCount = 0, badBoxCount = 0; QString file; if (m_editor != 0) { file = m_editor->getFilename(); file = "." + file.mid(file.lastIndexOf(QDir::separator())); } clear(); append("[" + cmd + "]" + tr(" Finished with exitcode ") + QString::number(exitCode)); QTextDocument doc(str); for (QTextBlock block = doc.begin(); block.isValid(); block = block.next()) { QString text = block.text(); if (text.startsWith(QString("!"))) { setCurrentCharFormat(m_errorFormat); append(file + ": " + parseError(block)); errorCount++; } else if (text.startsWith(QString("Underfull")) || text.startsWith(QString("Overfull"))) { setCurrentCharFormat(m_badBoxFormat); append(file + ": " + parseBadbox(block)); badBoxCount++; } } setCurrentCharFormat(m_normalFormat); QString endMessage; if (errorCount == 0) { endMessage = tr("Done. ") + QString::number(errorCount) + tr(" Error(s), ") + QString::number(badBoxCount) + tr(" BadBox(es)."); } else { endMessage = QString::number(errorCount) + tr(" Error(s), ") + QString::number(badBoxCount) + tr(" BadBox(es)."); } append(endMessage); } QString LogConsole::parseBadbox(QTextBlock block) { QString text = block.text().trimmed(); int index = text.lastIndexOf(QString("at line")) ; QString message = text.mid(0, index - 1).trimmed(); QString line = text.mid(text.indexOf(QString(" "), index + 4)).trimmed(); if (line.contains(QString("--"))) { line = line.mid(0, line.indexOf(QString("--"))); } return line + ": " + message; } QString LogConsole::parseError(QTextBlock block) { QString errorCommand, errorLine, errorMessage = block.text().mid(1).trimmed(); for (block = block.next(); block.isValid(); block = block.next()) { QString text = block.text().trimmed(); if (text.startsWith("l.")) { errorLine = text.mid(2, text.indexOf(QString(" ")) - 2).trimmed(); errorCommand = text.mid(2 + errorLine.length()).trimmed(); break; } } if (errorLine.isEmpty() || errorLine.isNull()) { return errorMessage + tr(" (No line found)"); } return errorLine + ": " + errorMessage + " " + errorCommand; } void LogConsole::setCurrentEditor(Editor *editor) { m_editor = editor; }
[ "m_scha26@e9368703-4046-0410-a5d1-c0970dff0443" ]
m_scha26@e9368703-4046-0410-a5d1-c0970dff0443
5ce644f2a5e32a8e997f3e05d28def4e450d1379
a3d06f60f827f043b169d8edc8e35ce81b95be55
/Main.cpp
011020e606a4cb7e5746e358334392134fe07015
[]
no_license
H4RDY-develop/ResChangingOpenCV
be7742fa0053b7dbfaadd9f7dc7644a772ebea5e
61b38a69fe60d0bee188cbe37b27fe185b7f871f
refs/heads/master
2023-06-14T08:42:22.323602
2021-07-10T14:26:25
2021-07-10T14:26:25
384,548,183
0
0
null
null
null
null
UTF-8
C++
false
false
1,265
cpp
#define GetCurrentDir _getcwd #include <iostream> #include <opencv2/opencv.hpp> #include <string> #include <Windows.h> #include <dirent.h> #include <sys/types.h> #include <vector> #include <stdio.h> #include <direct.h> // Adding libraries | May be extended using namespace std; using namespace cv; int value; int Direct() { char buff[FILENAME_MAX]; GetCurrentDir(buff, FILENAME_MAX); char* current_working_dir(buff); cout << current_working_dir << "\n"; // Findind current working DIR struct dirent* entry; DIR* dir = opendir(current_working_dir); // Actual directory vector<string> dirlist; // An array which can increase in size if (dir == NULL) { cout << "!"; return 0; } while ((entry = readdir(dir)) != NULL) { cout << entry->d_name << endl; dirlist.push_back(entry->d_name); } for (int i = 0; i < value; i++) { string NameList = dirlist[i]; if (NameList.substr(NameList.find_last_of(".") + 1) == "jpg") { cout << "Well done."; Mat image = imread(NameList); imshow("Original Image", image); int up_width = 600; int up_height = 400; } else { cout << "!"; } } cin >> value; closedir(dir); return 0; } void ChangeRes() { } int main(int argc, char * argv[]) { cin >> value; Direct(); }
f74db0a4a428130d32b1343633911a76b3f5f3c9
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/ckafka/include/tencentcloud/ckafka/v20190819/model/InquiryBasePrice.h
2a9622bffb2724e8286a77a7a2994955ea4c08b6
[ "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
15,427
h
/* * 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. */ #ifndef TENCENTCLOUD_CKAFKA_V20190819_MODEL_INQUIRYBASEPRICE_H_ #define TENCENTCLOUD_CKAFKA_V20190819_MODEL_INQUIRYBASEPRICE_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Ckafka { namespace V20190819 { namespace Model { /** * 询价返回参数 */ class InquiryBasePrice : public AbstractModel { public: InquiryBasePrice(); ~InquiryBasePrice() = default; void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const; CoreInternalOutcome Deserialize(const rapidjson::Value &value); /** * 获取单位原价 注意:此字段可能返回 null,表示取不到有效值。 * @return UnitPrice 单位原价 注意:此字段可能返回 null,表示取不到有效值。 * */ double GetUnitPrice() const; /** * 设置单位原价 注意:此字段可能返回 null,表示取不到有效值。 * @param _unitPrice 单位原价 注意:此字段可能返回 null,表示取不到有效值。 * */ void SetUnitPrice(const double& _unitPrice); /** * 判断参数 UnitPrice 是否已赋值 * @return UnitPrice 是否已赋值 * */ bool UnitPriceHasBeenSet() const; /** * 获取折扣单位价格 注意:此字段可能返回 null,表示取不到有效值。 * @return UnitPriceDiscount 折扣单位价格 注意:此字段可能返回 null,表示取不到有效值。 * */ double GetUnitPriceDiscount() const; /** * 设置折扣单位价格 注意:此字段可能返回 null,表示取不到有效值。 * @param _unitPriceDiscount 折扣单位价格 注意:此字段可能返回 null,表示取不到有效值。 * */ void SetUnitPriceDiscount(const double& _unitPriceDiscount); /** * 判断参数 UnitPriceDiscount 是否已赋值 * @return UnitPriceDiscount 是否已赋值 * */ bool UnitPriceDiscountHasBeenSet() const; /** * 获取合计原价 注意:此字段可能返回 null,表示取不到有效值。 * @return OriginalPrice 合计原价 注意:此字段可能返回 null,表示取不到有效值。 * */ double GetOriginalPrice() const; /** * 设置合计原价 注意:此字段可能返回 null,表示取不到有效值。 * @param _originalPrice 合计原价 注意:此字段可能返回 null,表示取不到有效值。 * */ void SetOriginalPrice(const double& _originalPrice); /** * 判断参数 OriginalPrice 是否已赋值 * @return OriginalPrice 是否已赋值 * */ bool OriginalPriceHasBeenSet() const; /** * 获取折扣合计价格 注意:此字段可能返回 null,表示取不到有效值。 * @return DiscountPrice 折扣合计价格 注意:此字段可能返回 null,表示取不到有效值。 * */ double GetDiscountPrice() const; /** * 设置折扣合计价格 注意:此字段可能返回 null,表示取不到有效值。 * @param _discountPrice 折扣合计价格 注意:此字段可能返回 null,表示取不到有效值。 * */ void SetDiscountPrice(const double& _discountPrice); /** * 判断参数 DiscountPrice 是否已赋值 * @return DiscountPrice 是否已赋值 * */ bool DiscountPriceHasBeenSet() const; /** * 获取折扣(单位是%) 注意:此字段可能返回 null,表示取不到有效值。 * @return Discount 折扣(单位是%) 注意:此字段可能返回 null,表示取不到有效值。 * */ double GetDiscount() const; /** * 设置折扣(单位是%) 注意:此字段可能返回 null,表示取不到有效值。 * @param _discount 折扣(单位是%) 注意:此字段可能返回 null,表示取不到有效值。 * */ void SetDiscount(const double& _discount); /** * 判断参数 Discount 是否已赋值 * @return Discount 是否已赋值 * */ bool DiscountHasBeenSet() const; /** * 获取商品数量 注意:此字段可能返回 null,表示取不到有效值。 * @return GoodsNum 商品数量 注意:此字段可能返回 null,表示取不到有效值。 * */ int64_t GetGoodsNum() const; /** * 设置商品数量 注意:此字段可能返回 null,表示取不到有效值。 * @param _goodsNum 商品数量 注意:此字段可能返回 null,表示取不到有效值。 * */ void SetGoodsNum(const int64_t& _goodsNum); /** * 判断参数 GoodsNum 是否已赋值 * @return GoodsNum 是否已赋值 * */ bool GoodsNumHasBeenSet() const; /** * 获取付费货币 注意:此字段可能返回 null,表示取不到有效值。 * @return Currency 付费货币 注意:此字段可能返回 null,表示取不到有效值。 * */ std::string GetCurrency() const; /** * 设置付费货币 注意:此字段可能返回 null,表示取不到有效值。 * @param _currency 付费货币 注意:此字段可能返回 null,表示取不到有效值。 * */ void SetCurrency(const std::string& _currency); /** * 判断参数 Currency 是否已赋值 * @return Currency 是否已赋值 * */ bool CurrencyHasBeenSet() const; /** * 获取硬盘专用返回参数 注意:此字段可能返回 null,表示取不到有效值。 * @return DiskType 硬盘专用返回参数 注意:此字段可能返回 null,表示取不到有效值。 * */ std::string GetDiskType() const; /** * 设置硬盘专用返回参数 注意:此字段可能返回 null,表示取不到有效值。 * @param _diskType 硬盘专用返回参数 注意:此字段可能返回 null,表示取不到有效值。 * */ void SetDiskType(const std::string& _diskType); /** * 判断参数 DiskType 是否已赋值 * @return DiskType 是否已赋值 * */ bool DiskTypeHasBeenSet() const; /** * 获取购买时长 注意:此字段可能返回 null,表示取不到有效值。 * @return TimeSpan 购买时长 注意:此字段可能返回 null,表示取不到有效值。 * */ int64_t GetTimeSpan() const; /** * 设置购买时长 注意:此字段可能返回 null,表示取不到有效值。 * @param _timeSpan 购买时长 注意:此字段可能返回 null,表示取不到有效值。 * */ void SetTimeSpan(const int64_t& _timeSpan); /** * 判断参数 TimeSpan 是否已赋值 * @return TimeSpan 是否已赋值 * */ bool TimeSpanHasBeenSet() const; /** * 获取购买时长单位("m"按月, "h"按小时) 注意:此字段可能返回 null,表示取不到有效值。 * @return TimeUnit 购买时长单位("m"按月, "h"按小时) 注意:此字段可能返回 null,表示取不到有效值。 * */ std::string GetTimeUnit() const; /** * 设置购买时长单位("m"按月, "h"按小时) 注意:此字段可能返回 null,表示取不到有效值。 * @param _timeUnit 购买时长单位("m"按月, "h"按小时) 注意:此字段可能返回 null,表示取不到有效值。 * */ void SetTimeUnit(const std::string& _timeUnit); /** * 判断参数 TimeUnit 是否已赋值 * @return TimeUnit 是否已赋值 * */ bool TimeUnitHasBeenSet() const; /** * 获取购买数量 注意:此字段可能返回 null,表示取不到有效值。 * @return Value 购买数量 注意:此字段可能返回 null,表示取不到有效值。 * */ int64_t GetValue() const; /** * 设置购买数量 注意:此字段可能返回 null,表示取不到有效值。 * @param _value 购买数量 注意:此字段可能返回 null,表示取不到有效值。 * */ void SetValue(const int64_t& _value); /** * 判断参数 Value 是否已赋值 * @return Value 是否已赋值 * */ bool ValueHasBeenSet() const; private: /** * 单位原价 注意:此字段可能返回 null,表示取不到有效值。 */ double m_unitPrice; bool m_unitPriceHasBeenSet; /** * 折扣单位价格 注意:此字段可能返回 null,表示取不到有效值。 */ double m_unitPriceDiscount; bool m_unitPriceDiscountHasBeenSet; /** * 合计原价 注意:此字段可能返回 null,表示取不到有效值。 */ double m_originalPrice; bool m_originalPriceHasBeenSet; /** * 折扣合计价格 注意:此字段可能返回 null,表示取不到有效值。 */ double m_discountPrice; bool m_discountPriceHasBeenSet; /** * 折扣(单位是%) 注意:此字段可能返回 null,表示取不到有效值。 */ double m_discount; bool m_discountHasBeenSet; /** * 商品数量 注意:此字段可能返回 null,表示取不到有效值。 */ int64_t m_goodsNum; bool m_goodsNumHasBeenSet; /** * 付费货币 注意:此字段可能返回 null,表示取不到有效值。 */ std::string m_currency; bool m_currencyHasBeenSet; /** * 硬盘专用返回参数 注意:此字段可能返回 null,表示取不到有效值。 */ std::string m_diskType; bool m_diskTypeHasBeenSet; /** * 购买时长 注意:此字段可能返回 null,表示取不到有效值。 */ int64_t m_timeSpan; bool m_timeSpanHasBeenSet; /** * 购买时长单位("m"按月, "h"按小时) 注意:此字段可能返回 null,表示取不到有效值。 */ std::string m_timeUnit; bool m_timeUnitHasBeenSet; /** * 购买数量 注意:此字段可能返回 null,表示取不到有效值。 */ int64_t m_value; bool m_valueHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_CKAFKA_V20190819_MODEL_INQUIRYBASEPRICE_H_
1f22cb2f1cc76420410e2379aa127b1b9159bf53
3bc3f080f46a6897c6d88f036c784c63b3673979
/src/mame/includes/deco32.h
de3fa7c131eb957562d9188a9d294e1df669900b
[]
no_license
vikke/mame_0145
bec0f81aba918c8ca5579a13f72e3c8efc7d0065
e9b4636543b017c2a6cdd6cddeab4afc02740241
refs/heads/master
2021-07-04T03:00:14.861010
2021-06-02T10:07:17
2021-06-02T10:07:17
4,586,522
0
0
null
null
null
null
UTF-8
C++
false
false
2,631
h
#include "audio/decobsmt.h" class deco32_state : public driver_device { public: deco32_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag), m_maincpu(*this, "maincpu"), m_decobsmt(*this, "decobsmt") { } required_device<cpu_device> m_maincpu; optional_device<decobsmt_device> m_decobsmt; UINT32 *m_ram; int m_raster_enable; timer_device *m_raster_irq_timer; UINT8 m_nslasher_sound_irq; int m_strobe; int m_tattass_eprom_bit; int m_lastClock; char m_buffer[32]; int m_bufPtr; int m_pendingCommand; int m_readBitCount; int m_byteAddr; int m_ace_ram_dirty; int m_has_ace_ram; UINT32 *m_ace_ram; UINT8 *m_dirty_palette; int m_pri; bitmap_ind16 *m_tilemap_alpha_bitmap; UINT16 m_spriteram16[0x1000]; UINT16 m_spriteram16_buffered[0x1000]; UINT16 m_spriteram16_2[0x1000]; UINT16 m_spriteram16_2_buffered[0x1000]; UINT16 m_pf1_rowscroll[0x1000]; UINT16 m_pf2_rowscroll[0x1000]; UINT16 m_pf3_rowscroll[0x1000]; UINT16 m_pf4_rowscroll[0x1000]; // we use the pointers below to store a 32-bit copy.. UINT32 *m_pf1_rowscroll32; UINT32 *m_pf2_rowscroll32; UINT32 *m_pf3_rowscroll32; UINT32 *m_pf4_rowscroll32; device_t *m_deco_tilegen1; device_t *m_deco_tilegen2; UINT8 m_irq_source; }; class dragngun_state : public deco32_state { public: dragngun_state(const machine_config &mconfig, device_type type, const char *tag) : deco32_state(mconfig, type, tag) { } UINT32 *m_dragngun_sprite_layout_0_ram; UINT32 *m_dragngun_sprite_layout_1_ram; UINT32 *m_dragngun_sprite_lookup_0_ram; UINT32 *m_dragngun_sprite_lookup_1_ram; UINT32 m_dragngun_sprite_ctrl; int m_dragngun_lightgun_port; }; /*----------- defined in video/deco32.c -----------*/ VIDEO_START( captaven ); VIDEO_START( fghthist ); VIDEO_START( dragngun ); VIDEO_START( lockload ); VIDEO_START( nslasher ); SCREEN_VBLANK( captaven ); SCREEN_VBLANK( dragngun ); SCREEN_UPDATE_IND16( captaven ); SCREEN_UPDATE_RGB32( fghthist ); SCREEN_UPDATE_RGB32( dragngun ); SCREEN_UPDATE_RGB32( nslasher ); WRITE32_HANDLER( deco32_pf1_data_w ); WRITE32_HANDLER( deco32_pf2_data_w ); WRITE32_HANDLER( deco32_pf3_data_w ); WRITE32_HANDLER( deco32_pf4_data_w ); WRITE32_HANDLER( deco32_nonbuffered_palette_w ); WRITE32_HANDLER( deco32_buffered_palette_w ); WRITE32_HANDLER( deco32_palette_dma_w ); WRITE32_HANDLER( deco32_pri_w ); WRITE32_HANDLER( dragngun_sprite_control_w ); WRITE32_HANDLER( dragngun_spriteram_dma_w ); WRITE32_HANDLER( deco32_ace_ram_w );
3a9c17744ef9936dc2f36bdad4a8ba1ec271d00c
9222f818abb402120fb24f61ac8ac24c483de393
/question/minimum-path-sum最小路径和.cpp
6e2e10b4d585a597c2c85bb0877192a9b8eaf19c
[]
no_license
bobzhw/question
56fd04d17f7607376446582ed37fc330f011594d
4d4bcb673e414e16ce72bd4609bedc9a7ad31e14
refs/heads/master
2020-05-23T20:59:22.185165
2019-06-04T13:31:49
2019-06-04T13:31:49
186,942,633
2
0
null
null
null
null
UTF-8
C++
false
false
786
cpp
#include<vector> #include<iostream> using namespace std; class Solution { public: int minPathSum(vector<vector<int> > &grid) { if (grid.empty()) return 0; int m = grid.size(); int n = grid[0].size(); vector<vector<int>> vv(m, vector<int>(n, 0)); for (int i = 0; i < grid.size(); i++) { for (int j = 0; j < grid[0].size(); j++) { if (i == 0 && j != 0) { vv[i][j] = vv[i][j - 1] + grid[i][j]; } else if (j == 0 && i != 0) { vv[i][j] = vv[i - 1][j] + grid[i][j]; } else if (i != 0 && j != 0) { vv[i][j] = min(vv[i - 1][j], vv[i][j - 1]) + grid[i][j]; } else vv[i][j] = grid[i][j]; } } return vv[m - 1][n - 1]; } private: inline int min(int lhs, int rhs) { return lhs <= rhs ? lhs : rhs; } };
[ "zhouwei@DESKTOP-1D7SFF0" ]
zhouwei@DESKTOP-1D7SFF0
143d46934ee7b958a6c15b6d5482a82fd5ea105a
46fdede0d13cf14bdd8ef9c2a04e3d04401659dd
/libSimOn/src/SysFsHelper.cpp
0aa4ad7a1365bc9cec9647d92b39312fbb1a8a73
[]
no_license
patgauvingeek/PiProjects
13897801afa0c705b2d2b1f84da3d35ea6348fcc
6c053d6b81641c55f78647c0f94dca7946314b0d
refs/heads/master
2021-01-01T19:50:08.648573
2019-09-09T01:55:05
2019-09-09T01:55:05
98,699,421
0
0
null
null
null
null
UTF-8
C++
false
false
909
cpp
#include "SysFsHelper.h" #include <fstream> #include <sstream> #include <stdexcept> namespace SimOn { void SysFsHelper::writeData(std::string const &filename, std::string const &data, std::string const &action, std::string const &item) { std::ofstream fileStream(filename); if (fileStream.is_open() == false) { std::stringstream msg; msg << "OPERATION FAILED: Unable to " << action << " " << item << "."; throw std::runtime_error(msg.str()); } fileStream << data; } void SysFsHelper::readData(std::string const &filename, std::string &data, std::string const &action, std::string const &item) { std::ifstream fileStream(filename); if (fileStream.is_open() == false) { std::stringstream msg; msg << "OPERATION FAILED: Unable to " << action << item << "."; throw std::runtime_error(msg.str()); } fileStream >> data; } }
64da568f8ca80a418b135183553e1d80e08baafe
5a792582ff0d79d9fb9f1ed6750f84a7e3787507
/trunk/opt/qnx660/target/qnx6/usr/include/unicode/measunit.h
aa18f9ce8056c93c34ac2c425e964c09ccae3250
[]
no_license
jjzhang166/QNX-SDP
faeffb2bfa80ea41f06230d9cc4e33cacde821de
74d96ca4ffb547a8ac4ec71803b31d452507b3d0
refs/heads/master
2023-03-22T03:02:25.466107
2018-01-19T08:14:56
2018-01-19T08:14:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,846
h
/* ********************************************************************** * Copyright (c) 2004-2006, International Business Machines * Corporation and others. All Rights Reserved. ********************************************************************** * Author: Alan Liu * Created: April 26, 2004 * Since: ICU 3.0 ********************************************************************** */ #ifndef __MEASUREUNIT_H__ #define __MEASUREUNIT_H__ #include "unicode/utypes.h" #if !UCONFIG_NO_FORMATTING #include "unicode/fmtable.h" /** * \file * \brief C++ API: A unit for measuring a quantity. */ U_NAMESPACE_BEGIN /** * A unit such as length, mass, volume, currency, etc. A unit is * coupled with a numeric amount to produce a Measure. * * <p>This is an abstract class. * * @author Alan Liu * @stable ICU 3.0 */ class U_I18N_API MeasureUnit: public UObject { public: /** * Return a polymorphic clone of this object. The result will * have the same class as returned by getDynamicClassID(). * @stable ICU 3.0 */ virtual UObject* clone() const = 0; /** * Destructor * @stable ICU 3.0 */ virtual ~MeasureUnit(); /** * Equality operator. Return true if this object is equal * to the given object. * @stable ICU 3.0 */ virtual UBool operator==(const UObject& other) const = 0; protected: /** * Default constructor. * @stable ICU 3.0 */ MeasureUnit(); }; U_NAMESPACE_END // NOTE: There is no measunit.cpp. For implementation, see measure.cpp. [alan] #endif // !UCONFIG_NO_FORMATTING #endif // __MEASUREUNIT_H__ #if defined(__QNXNTO__) && defined(__USESRCVERSION) #include <sys/srcversion.h> __SRCVERSION("$URL: http://svn/product/branches/6.6.0/trunk/lib/icu/dist/source/i18n/unicode/measunit.h $ $Rev: 680336 $") #endif
b08e16e3c3d34d8cd9cf5705cca2394b1b585a9a
5e604b4a033e49d06588e3545837435b2ea3f651
/CPP04/ex00/Victim.hpp
1333653561b635ea79c9d4a1cbe3e42975377868
[]
no_license
lucasmln/Piscine_CPP
7519d4c4f1327c26e2dd887a0b6f2f4c22d1d38e
39fc0a025fc06b118d3cbcfdd3ee76760f1a1cf7
refs/heads/master
2023-02-19T19:18:46.283923
2021-01-22T10:46:01
2021-01-22T10:46:01
322,577,685
0
0
null
null
null
null
UTF-8
C++
false
false
1,296
hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Victim.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lmoulin <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/06/15 16:10:43 by lmoulin #+# #+# */ /* Updated: 2020/06/15 17:27:56 by lmoulin ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef VICTIM_HPP # define VICTIM_HPP #include <iostream> #include <ostream> class Victim { protected: Victim(); std::string name; public: Victim(std::string _name); Victim(const Victim &v); Victim &operator=(const Victim &v); ~Victim(); virtual void getPolymorphed() const; const std::string getName() const; }; std::ostream &operator<<(std::ostream &out, Victim &v); #endif
d9649ffb888378afe0cb7f3fcea8994a40847204
f90920085074e79a37048155750b80e5e884c5d2
/tsrc/MMCTestDriver/MCETester/inc/TCmdSendHoldSession.h
f6d9be4107ebc3d2a58b3b91b6e66e73af0e1ec4
[]
no_license
piashishi/mce
fec6847fc9b4e01c43defdedf62ef68f55deba8e
8c0f20e0ebd607fb35812fd02f63a83affd37d74
refs/heads/master
2021-01-25T06:06:18.042653
2016-08-13T15:38:09
2016-08-13T15:38:09
26,538,858
1
1
null
null
null
null
UTF-8
C++
false
false
1,586
h
/* * Copyright (c) 2005 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: See class definition below. * */ #ifndef __TCmdSendHoldSession_H__ #define __TCmdSendHoldSession_H__ // INCLUDES #include "TTcMceCommandBase.h" // CLASS DEFINITION /** * Command class responsible for "SendAnswer" functionality. */ class TCmdSendHoldSession : public TTcMceCommandBase { public: // Constructors and destructor /** * Constructor. * * @param aContext MCE Test case context */ TCmdSendHoldSession( MTcTestContext& aContext ) : TTcMceCommandBase( aContext ) {}; public: // From TTcMceCommandBase void ExecuteL(); public: // New methods /** * Static function for matching the name of this command to * a function identifier. * * @param aId An initialized identifier containing a function name. * @return ETrue if this command matches the specified name. */ static TBool Match( const TTcIdentifier& aId ); /** * Static fuction for creating an instance of this class * * @param aContext MCE Test case context * @return An initialized instance of this class. */ static TTcCommandBase* CreateL( MTcTestContext& aContext ); }; #endif // __TCmdSendHoldSession_H__
8be57f2d9931bec744da6e71c6abdda0d41d3251
75417c19c179ca8519149a7ea72755a6b8ab8b95
/ECS/include/Systems/ControlSystem.hpp
310c0df8cf852724346746216db2d90445deaabc
[]
no_license
ChrisMelling/ECS
8d458fdd603dd2f14d4fb8a430f9db3cbe2a97f5
47b2eb2f5d80fc03d1ca6cc13577117c1df39da4
refs/heads/master
2020-04-08T07:38:49.293702
2014-01-08T00:57:08
2014-01-08T00:57:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
565
hpp
#ifndef CONTROLSYSTEM_HPP #define CONTROLSYSTEM_HPP //STD #include <vector> //3RD #include <SFML/Graphics.hpp> //SELF #include "Constants.hpp" #include "EntityManager.hpp" #include "Entity.hpp" #include "Components/Movement.hpp" #include "Components/Display.hpp" #include "Components/Flags.hpp" #include "Utility/Vector.hpp" #include "Systems\BaseSystem.h" class ControlSystem : public BaseSystem { public: ControlSystem(); void Update(float deltaTime); private: std::vector<std::shared_ptr<Entity>> m_Ents; EntityManager m_EntMan; }; #endif
b43b81c206010a10d7c4d27e0cee237b8e084c88
b5277b9f7e82da01c1f31368492e50d21e798303
/testboost/function_and_callback/ref_example.cpp
59c73111b556a3451edbca70fad7e0c924c8e04a
[]
no_license
tantaijin/testBoost
3646ac55eda4e71b7f60295d262a94778f9f2637
86763e8b6505f47d0608c0355b1fdef2b0bd5634
refs/heads/master
2021-05-07T01:23:03.342499
2018-02-01T15:04:44
2018-02-01T15:04:44
110,249,460
0
0
null
null
null
null
UTF-8
C++
false
false
726
cpp
#include "stdafx.h" #include "ref_example.h" #include "boost\ref.hpp" #include "boost\typeof\typeof.hpp" #include "assert.h" void test_ref() { int x = 10; boost::reference_wrapper<int> rw(x); assert(rw == x); (int&)rw = 100; assert(x == 100); boost::reference_wrapper<int> rw2(rw); assert(rw2 == 100); std::string str; boost::reference_wrapper<std::string> rws(str); *rws.get_pointer() = "hello world"; cout << rws.get().c_str() << endl; // hello world double d = 3.14; BOOST_AUTO(dref, boost::cref(d)); cout << typeid(dref).name() << endl; // class boost::reference_wrapper<double const > std::set<int> s; BOOST_AUTO(rwset, boost::ref(s)); boost::unwrap_ref(rwset).insert(12); assert(s.size() == 1); }
f5e5289f587a0db70b180ef5845e50e9bee660d6
1e549b5aa71ed3700b6f8d0e3347923b1c431a6e
/terceira entrega/LAIGvs10/src/SceneCylinder.h
7b139cb84483bf96b172086641d2ac956b20fbd8
[]
no_license
PMRocha/Laig
1f5783cef0b5cb75a0f1a46abe9d777155b18285
6d4201937670b95f9a1bea633d1f25ffd54e9585
refs/heads/master
2021-01-22T01:04:33.672143
2015-01-09T11:57:55
2015-01-09T11:57:55
24,503,398
0
0
null
null
null
null
UTF-8
C++
false
false
658
h
#ifndef _SCENECYLINDER_H_ #define _SCENECYLINDER_H_ #include "SceneObject.h" #include <vector> #include <iostream> #include <math.h> #include "Point.h" using namespace std; class SceneCylinder:public SceneObject { private: float top; float base; float height; int slices; int stacks; float deltaRadius; vector <vector<Point>> points; vector <vector<Point>> normals; vector <vector<Point>> texts; public: SceneCylinder(float base,float top,float height,int slices,int stacks); ~SceneCylinder(void); void normalsCalc(); Point normalCalc(int i,int j); void textsCalc(); Point textCalc(int i, int j,float angle); void draw(void); }; #endif
3a82632d77bd2e5a9a5e2c93528c6c58c0bb0e0e
99a87a793240e11085e9ac5fad51580922c83d04
/p2p/option.hpp
0fe092983937393e263a1e76c84ecccc5f6b665b
[]
no_license
xiaoshzx/p2p
85834fe4b761c16144d85622cb886be0f8c01040
8594bd7d497f25620fc1f2949552898194c0e9f9
refs/heads/master
2022-10-11T01:13:50.737666
2020-06-03T03:42:00
2020-06-03T03:42:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
624
hpp
#ifndef OPTION_H #define OPTION_H #include <cstdint> // fec percentage: 5%, 10%, 20% ... static const int OPT_SET_FEC_PERC = 0x01; static const int OPT_SET_PACKET_LOSS_PERC = 0x02; class Option { public: virtual void SetOption(int opt, int value) { switch (opt) { case OPT_SET_FEC_PERC: fec_perc_ = value; use_fec_ = (fec_perc_ > 0) ? 1 : 0; break; case OPT_SET_PACKET_LOSS_PERC: packet_loss_perc_ = value; break; default: break; } } protected: uint32_t fec_perc_ = 0; uint32_t use_fec_ = 0; uint32_t packet_loss_perc_ = 0; }; #endif
df47450dbdb355aeacd486596e76a10630b62ed8
6a53ebf648fe736ca9f83ce09d0716a63938a7eb
/busca_Serial.cpp
a99fd8b4686a7d57380cf4d2a9e5bfa50a85d22f
[]
no_license
JhonMarques/Arquivo-Sequencial-em-C-
84644223cee4f6cb7339ae28d61222a309b87be3
9840dad72d51a581e6058ab8ae364ac9157f2b7a
refs/heads/master
2020-09-27T16:49:37.668319
2016-09-04T19:38:40
2016-09-04T19:38:40
67,364,575
2
0
null
null
null
null
ISO-8859-1
C++
false
false
13,164
cpp
#include <iostream> #include <conio2.h> #include <iomanip> using namespace std; const int N = 20; struct tNo{ int cod; string nome; string endereco; string cidade; string uf; }; tNo Cliente[N] = {{1, "Almir", "AV. Rui Barbosa 83", "Assis", "SP"}, {2, "Lucas", "R. São paulo 98", "Cândido Mota", "SP"}, {3, "Jhonatas", "R. Gaspar Ricardo 83","Brasília", "DF"}, {4, "Natan", "AV. Oliveira Pires 110","Tarumã", "SP"}, {5, "Wilian", "AV. Assis 54","Paraguaçu", "SP"}, {6, "Bruno", "R. São Paulo 93", "Assis", "SP"}, {0, "", "", "", ""}, {0, "", "", "", ""}, {0, "", "", "", ""}}; tNo val; int cod = 0; int meio = 0; int id; int i = 0; int fim = 0; int total = 6; bool exclui = false; int cont = 0; int impressao = total; void Serial(); void Aleatoria(); void Inclui_Registro(); void Exclui_Registro(); void Imprimir(); int main(){ //Menu de Entrada setlocale(LC_ALL,"PTB"); textbackground(BLACK); fim = -1; int op = -1; textbackground(CYAN); while (op != 0){ clrscr(); textcolor (WHITE); gotoxy(30,1); cout<<"Arquivo Sequencial"; gotoxy(30, 2); cout<<"------------------"; gotoxy(27,4); cout<<"Opções:"; gotoxy(27,6); cout<<" 1 - Busca Serial"; gotoxy(27,8); cout<<" 2 - Busca Aleatória"; gotoxy(27,10); cout<<" 3 - Inclusão de Registros"; gotoxy(27,12); cout<<" 4 - Exclusão de Registros"; gotoxy(27,14); cout<<" 5 - Imprimir Registros"; gotoxy(27,16); cout<<" 0 - Sair"; gotoxy(27,18); cout<<"Escolha uma Opção: "; cin>>op; switch (op){ case 0: { clrscr(); gotoxy(32,6); cout << "Bom Descanso...\n\n"; getch(); break; } case 1: Serial(); break; case 2: Aleatoria(); break; case 3: Inclui_Registro(); break; case 4: Exclui_Registro(); break; case 5: Imprimir();break; default: { cout << "\n\n\t\t\t Opcao Invalida...\n"; getch(); break;} } } } void Serial(){ clrscr(); setlocale(LC_ALL,"PTB"); fim = 0; gotoxy(30, 2); cout<<"Busca Serial"; gotoxy(28, 6); cout<<"ID do Cliente: "; cin>> id; while(Cliente[fim].cod < id && fim < N ) { fim++; } if(Cliente[fim].cod == id) { gotoxy(28,8); cout<<"Cliente: "<< Cliente[fim].nome; gotoxy(28, 10); cout<<"End: "<<Cliente[fim].endereco; gotoxy(28, 12); cout<<"Cidade: "<<Cliente[fim].cidade; gotoxy(28, 14); cout<<"Uf: "<<Cliente[fim].uf; } else { gotoxy(26, 9); cout<<"Cliente Não Encotrado!!!"; } getch(); gotoxy(26, 25); } void Aleatoria(){ int inicio = 0; int fim = total; int meio = (inicio + fim) / 2; clrscr(); gotoxy(29 , 2); cout<<"BUSCA ALEATÓRIA"; gotoxy(29 , 3); cout<<"---------------"; gotoxy(28 , 5); cout<<"Código Procurado: "; cin >> id; while ( inicio <= fim && id != Cliente[meio].cod ) { if(Cliente[meio].cod > id) { fim = meio - 1; } else { inicio = meio + 1; } meio = (fim + inicio)/2; } if (Cliente[meio].cod == id) { gotoxy(28, 7); cout<<"Cliente: "<< Cliente[meio].nome; gotoxy(28, 9); cout<<"End: "<<Cliente[meio].endereco; gotoxy(28, 11); cout<<"Cidade: "<<Cliente[meio].cidade; gotoxy(28, 13); cout<<"Uf: "<<Cliente[meio].uf; } else { gotoxy(29, 9); cout<<"Não Encontrado!"; } getch(); } void Inclui_Registro(){ struct T { int cod; string nome; string endereco; string cidade; string uf; }Tab_T[N]; struct A { int cod; string nome; string endereco; string cidade; string uf; }Tab_A[N]; clrscr(); char incluir = 'S'; char confirma; int ultimo = 0; int j = 0; int p = 0; int i = 0; fim = 0; ultimo = total + 1; if (ultimo <= N){ while (incluir == 'S'){ gotoxy(26 , 2); cout << "Inclusão de Registros"; gotoxy(26 , 3); cout << "---------------------"; gotoxy(26 , 5); cout << "Cod: "; cin >> Tab_T[i].cod; for (int r = 0; r < total; r++) { while (Tab_T[i].cod == Cliente[r].cod) { gotoxy(23, 9); cout<<"Código já exitente informe outro código"; getch(); clrscr(); gotoxy(26 , 2); cout << "Inclusão de Registros"; gotoxy(26 , 3); cout << "---------------------"; gotoxy(26 , 5); cout << "Cod: "; cin >> Tab_T[i].cod; } } gotoxy(26 , 7 ); cout<<"Cliente: "; cin >> Tab_T[i].nome; gotoxy(26, 9); cout<<"End: "; cin >>Tab_T[i].endereco; gotoxy(26, 11); cout<<"Cidade: "; cin >>Tab_T[i].cidade; gotoxy(26, 13); cout<<"Uf: "; cin >>Tab_T[i].uf; i++; total++; gotoxy(26, 15); cout <<"Deseja Incluir Mais Registros S/N: "; cin >> incluir; incluir = toupper(incluir); clrscr(); } gotoxy(29, 8); cout<< "Digite S para Salvar: "; cin>>confirma; confirma = toupper(confirma); i = 0; j = 0; p = 0; if(confirma == 'S'){ while (j <= total && p <= total) // total = tanto de registros existentes e não tamanho total da lista { if (Cliente[j].cod < Tab_T[p].cod && Cliente[j].cod > 0 && Tab_T[p].cod > 0) { Tab_A[i].cod = Cliente[j].cod; Tab_A[i].nome = Cliente[j].nome; Tab_A[i].endereco = Cliente[j].endereco; Tab_A[i].cidade = Cliente[j].cidade; Tab_A[i].uf= Cliente[j].uf; j++; i++; } else { Tab_A[i].cod = Tab_T[p].cod; Tab_A[i].nome = Tab_T[p].nome; Tab_A[i].endereco = Tab_T[p].endereco; Tab_A[i].cidade = Tab_T[p].cidade; Tab_A[i].uf = Tab_T[p].uf; p++; i++; } } while (j <= total) { Tab_A[i].cod = Cliente[j].cod; Tab_A[i].nome = Cliente[j].nome; Tab_A[i].endereco = Cliente[j].endereco; Tab_A[i].cidade = Cliente[j].cidade; Tab_A[i].uf= Cliente[j].uf; j++; i++; } while (p <= total) { Tab_A[i].cod = Tab_T[p].cod; Tab_A[i].nome = Tab_T[p].nome; Tab_A[i].endereco = Tab_T[p].endereco; Tab_A[i].cidade = Tab_T[p].cidade; Tab_A[i].uf = Tab_T[p].uf; p++; i++; } while (i < N) { Cliente[i].cod = 0; Cliente[i].nome = " "; Cliente[i].endereco = " "; Cliente[i].cidade = " "; Cliente[i].uf = " "; i++; } i = 0; while (i <= total) { Cliente[i].cod = Tab_A[i].cod; Cliente[i].nome = Tab_A[i].nome; Cliente[i].cidade = Tab_A[i].cidade; Cliente[i].endereco = Tab_A[i].endereco; Cliente[i].uf = Tab_A[i].uf; i++; } gotoxy(27,10); cout<<"Operação realizada com sucesso!!!"; }else { gotoxy(26,18); cout<< "Dados Não Confirmados!"; total = 6; } }else { clrscr(); gotoxy(30, 8); cout<< "Lista cheia!!!"; getch(); } impressao = total; getch(); } void Exclui_Registro(){ clrscr(); struct T { int cod; string nome; string endereco; string cidade; string uf; }Tab_T[N]; struct A { int cod; string nome; string endereco; string cidade; string uf; }Tab_A[N]; int j; int L = 6; int qtd = 0; int k; const int I = N; char continuar = 'S'; char confirma; cont = 0; gotoxy(29, 2); cout<<"Exclusão de Registros"; gotoxy(29, 3); cout<<"---------------------"; gotoxy(23, 5); cout<<"Informe os Códigos que Deseja Excluir: "; for (j = 0; continuar == 'S' && j < N; j++, L++){ gotoxy(35, L+2); cout<<qtd+1 <<"° Cód: "; cin>> Tab_T[j].cod; impressao++; gotoxy(26, L+5); cout<<"Deseja Excluir Mais Registros S/N: "; cin>> continuar; gotoxy(24, L+5); cout<<" "; continuar = toupper(continuar); qtd ++; } clrscr(); gotoxy(29, 2); cout<<"Exclusão de Registros"; gotoxy(29, 3); cout<<"---------------------"; for (i = 0; i<qtd; i++ ) { gotoxy(19 , L++); cout<<"Cod: "<< Tab_T[i].cod << " Nome: "<< Cliente[Tab_T[i].cod-1].nome <<" End: "<< Cliente[Tab_T[i].cod-1].endereco; } gotoxy(18, 5); cout<<"Deseja Realmente Excluir Os Registros Informados S/N: "; cin >> confirma; confirma = toupper(confirma); k = 0; j = 0; i = 0; if (confirma == 'S') { gotoxy(26, 14); cout<<"Remoção Efetuada Com Sucesso!"; while(i < N) { if(Cliente[i].cod != Tab_T[k].cod) { Tab_A[j].cod = Cliente[i].cod; Tab_A[j].nome = Cliente[i].nome; Tab_A[j].endereco = Cliente[i].endereco; Tab_A[j].cidade = Cliente[i].cidade; Tab_A[j].uf = Cliente[i].uf; j++; } else k++; i++; } while (i < N) { Cliente[i].cod = 0; Cliente[i].nome = " "; Cliente[i].endereco = " "; Cliente[i].cidade = " "; Cliente[i].uf = " "; i++; } i = 0; while (i <= j) { Cliente[i].cod = Tab_A[i].cod; Cliente[i].nome = Tab_A[i].nome; Cliente[i].cidade = Tab_A[i].cidade; Cliente[i].endereco = Tab_A[i].endereco; Cliente[i].uf = Tab_A[i].uf; i++; } }else { impressao = 6; gotoxy(26, 14); cout<<"Remoção Não Confirmada!"; } getch(); } void Imprimir(){ clrscr(); gotoxy(35 , 1); cout<<"Registros"; gotoxy(35 , 2); cout<<"---------"; int L = 4; for(int i = 0; i < impressao; i++, L++) { gotoxy(2 , L++); cout<<"Cod: "<< Cliente[i].cod << " Nome: "<< Cliente[i].nome <<" End: "<< Cliente[i].endereco <<" Cidade: "<<Cliente[i].cidade << " UF: "<< Cliente[i].uf; cout<<"\n--------------------------------------------------------------------------------"; } getch(); }
007528ce54325af8b952b6e10183dca1da083e5f
7dde994e7272996ae7d8bffbf04bdccab7683313
/WebServer_v4.0/util.h
8573633438cadf5a65ad325e19e89874dbe0c7b0
[]
no_license
guyongpu/WebServerProject
b08ff019b548a41df2f5d3ddacbcd13c68f4c30f
d91872cac1ffd90023f57f6a505c91610d8629d8
refs/heads/master
2020-07-28T14:57:20.350963
2020-02-14T05:54:47
2020-02-14T05:54:47
209,445,018
1
0
null
null
null
null
UTF-8
C++
false
false
452
h
// // Created by yongpu on 2019/12/17. // #ifndef WEBSERVER_V2_0_UTIL_H #define WEBSERVER_V2_0_UTIL_H #include <cstdlib> #include <iostream> #include <unistd.h> #include <fcntl.h> #include <signal.h> #include <errno.h> #include <string.h> using namespace std; ssize_t readn(int fd, void *buff, size_t n); ssize_t writen(int fd, void *buff, size_t n); void handle_for_sigpipe(); int setSocketNonBlocking(int fd); #endif //WEBSERVER_V2_0_UTIL_H
fd971e33912debcd7d6e7c5f1f069e882e22f97b
51f985e90ba3ad44e3ad5722c65078220477e48f
/PhotoKit-master/PhotoKit-master/src/ImageProvider.cpp
18199babcac029856ab967addd1d8683f8c0e1c2
[]
no_license
jason-lv-meng/study
9444e7c4dfcd2871a232f4df9ae9acf467da89bf
2b115a9b2eee5ccfdd92bda755bb302d99ef7aa9
refs/heads/master
2020-09-20T17:48:34.866238
2019-11-28T23:45:01
2019-11-28T23:45:01
224,551,756
0
0
null
null
null
null
UTF-8
C++
false
false
1,552
cpp
/****************************************************************************** ImageProvider: base class for image filtering Copyright (C) 2012 Wang Bin <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ******************************************************************************/ #include "ImageProvider.h" #include "ImageProvider_p.h" namespace PhotoKit { ImageProvider::ImageProvider(QObject *parent) :QObject(parent),d_ptr(new ImageProviderPrivate) { } ImageProvider::ImageProvider(ImageProviderPrivate &d, QObject *parent) :QObject(parent),d_ptr(&d) { } ImageProvider::~ImageProvider() { if (d_ptr) { delete d_ptr; d_ptr = 0; } } void ImageProvider::setNameFilter(const QString &filter) { Q_D(ImageProvider); d->nameFilter = filter; d->page = 0; //reset for a new search } bool ImageProvider::canFetchMore() const { return true; } } //namespace PhotoKit
004ecb123569bcd653d30013e1888ab79ed92992
f5f5eee680e3c27a98a892a5c01dfc3bd0fd68c1
/Lab1-210/TimeDriver.cpp
ec64943e2d6ead98e2c6fd4ea35f7fe94fcc6ce1
[]
no_license
mmonitto2/Comsc---210
dd48f84d7d5f60c8bba0461915401faa54e98398
5bda042709bdd8c599fad56adc73454803e4d9c1
refs/heads/master
2020-05-18T16:19:26.224078
2014-08-17T00:32:37
2014-08-17T00:32:37
23,029,837
0
1
null
null
null
null
UTF-8
C++
false
false
3,660
cpp
// Lab 1b // Programmer: Michael Monitto // Editor(s) used: Visual C++ 2010 Express // Compiler(s) used: VC++ 2010 Express //RoadDriver.cpp, by Michael Monitto (0985765) #include <iostream> using namespace std; //Extra includes #include <cassert> #include "Time.h" #include "Time.h" //testing ifndef int main() { cout << "Programmer: Michael Monitto\n"; cout << "Description: This program uses getters and setters to obtain" << endl; cout << "hours minutes and seconds"; cout << " then determines the full seconds" << endl; cout << "minutes and hours." << endl; cout << "Its is demostrated in a driver test program." << endl; cout << endl; Time time; //declare object //hard coded testing values time.setHours(1); time.setMinutes(40); time.setSeconds(30); //declared variables to function values double time_Hours = time.timeInHours(); double time_Minutes = time.timeInMinutes(); double time_Seconds = time.timeInSeconds(); //assert used for testing the values are true //Needed to compare double numbers due to rounding error //Not sure if the is substantial, would like some input assert(time_Hours <= 1.675 || time_Hours >= 1.675); assert(time_Minutes == 100.5); assert(time_Seconds == 6030); cout << "Hours = expect 1.675, " << "actual = " << time_Hours << " hours"<< endl; cout << "Minutes = expect 100.5, " << "actual = " << time_Minutes << " minutes" << endl; cout << "Seconds = expect 6030, " << "actual = " << ((int)time_Seconds) << " seconds" << endl; //object copy testing, with assignment UPON declaration { cout << "\nObject copy testing, with assignment UPON declaration" << endl; Time copy = time; //declare copy of object //declare new copy members time_Hours = copy.timeInHours(); time_Minutes = copy.timeInMinutes(); time_Seconds = copy.timeInSeconds(); //assert used for testing the values are true //Needed to compare double numbers due to rounding error //Not sure if the is substantial, if there is another way please let me know assert(time_Hours <= 1.675 || time_Hours >= 1.675); assert(time_Minutes == 100.5); assert(time_Seconds == 6030); //make sure value is true //assert used for testing the values are true cout << "Hours = expect 1.675, " << "actual = " << time_Hours << " hours"<< endl; cout << "Minutes = expect 100.5, " << "actual = " << time_Minutes << " minutes" << endl; cout << "Seconds = expect 6030, " << "actual = " << ((int)time_Seconds) << " seconds" << endl; } //object copy testing, with assignment AFTER declaration { cout << "\nObject copy testing, with assignment AFTER declaration" << endl; Time copy; copy = time; //declare copy of copy object //declare copy members time_Hours = copy.timeInHours(); time_Minutes = copy.timeInMinutes(); time_Seconds = copy.timeInSeconds(); //assert used for testing the values are true //Needed to compare double numbers due to rounding error //Not sure if the is substantial, if there is another way please let me know assert(time_Hours <= 1.675 || time_Hours >= 1.675); assert(time_Minutes == 100.5); assert(time_Seconds == 6030); //make sure value is true //assert used for testing the values are true cout << "Hours = expect 1.675, " << "actual = " << time_Hours << " hours"<< endl; cout << "Minutes = expect 100.5, " << "actual = " << time_Minutes << " minutes" << endl; cout << "Seconds = expect 6030, " << "actual = " << ((int)time_Seconds) << " seconds" << endl; } cout << endl; cout <<"Press ENTER to continue..." << endl; cin.get(); }
2f1102123a241276ef6671c365109b34a2641507
dce4b6e007e214a57d533590411e5c2d83aa64e6
/YahooKeyKey-Source-1.1.2528/ModulePackages/YKAFOneKey/YKAFOneKey.cpp
3aa015e7e14d8853318d5b1dd3aa69e5c22b26a5
[ "BSD-3-Clause", "CC-BY-2.5" ]
permissive
zonble/KeyKey
ebae0efc73828c5b28c44ac969e64e67e3386a01
80e6883ecc1f307f21c04a3db2d05d51409fbafb
refs/heads/master
2020-12-24T23:19:58.876765
2019-01-14T16:06:38
2019-01-14T16:06:38
7,112,217
2
0
null
null
null
null
UTF-8
C++
false
false
20,355
cpp
/* Copyright (c) 2012, Yahoo! Inc. All rights reserved. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ #include <sstream> #include "YKAFOneKey.h" using namespace OpenVanilla; class OneKeyStringTable : public OVLocalizationStringTable { public: OneKeyStringTable() { "Query:"; "Type ENTER to send; ESC to cancel"; "OneKey Service Canceled"; "OneKey Services"; "No query input, canceled"; #ifndef _MSC_VER add("zh_TW", "One Key Services", "一點通"); add("zh_CN", "One Key Services", "一点通"); add("zh_TW", "Query:", "查詢字串"); add("zh_CN", "Query:", "查询字串"); add("zh_TW", "Type ENTER to send; ESC to cancel", "按下 ENTER 送出:按下ESC 取消。"); add("zh_CN", "Type ENTER to send; ESC to cancel", "按下 ENTER 送出:按下ESC 取消。"); add("zh_TW", "OneKey Service Canceled", "取消使用一點通服務"); add("zh_CN", "OneKey Service Canceled", "取消使用一点通服务"); add("zh_TW", "OneKey Services", "一點通服務"); add("zh_CN", "OneKey Services", "一点通服务"); add("zh_TW", "No query input, canceled", "沒有輸入內容,取消一點通查詢。"); add("zh_CN", "No query input, canceled", "没有输入内容,取消一点通查询。"); #else add("zh_TW", "One Key Services", "\xe4\xb8\x80\xe9\xbb\x9e\xe9\x80\x9a"); add("zh_CN", "One Key Services", "\xe4\xb8\x80\xe7\x82\xb9\xe9\x80\x9a"); add("zh_TW", "Query:", "\xe6\x9f\xa5\xe8\xa9\xa2\xe5\xad\x97\xe4\xb8\xb2"); add("zh_CN", "Query:", "\xe6\x9f\xa5\xe8\xaf\xa2\xe5\xad\x97\xe4\xb8\xb2"); add("zh_TW", "Type ENTER to send; ESC to cancel", "\xe6\x8c\x89\xe4\xb8\x8b ENTER \xe9\x80\x81\xe5\x87\xba\xef\xbc\x9a\xe6\x8c\x89\xe4\xb8\x8b ESC \xe5\x8f\x96\xe6\xb6\x88\xe3\x80\x82"); add("zh_CN", "Type ENTER to send; ESC to cancel", "\xe6\x8c\x89\xe4\xb8\x8b ENTER \xe9\x80\x81\xe5\x87\xba\xef\xbc\x9a\xe6\x8c\x89\xe4\xb8\x8b ESC \xe5\x8f\x96\xe6\xb6\x88\xe3\x80\x82"); add("zh_TW", "OneKey Service Canceled", "\xe5\x8f\x96\xe6\xb6\x88\xe4\xbd\xbf\xe7\x94\xa8\xe4\xb8\x80\xe9\xbb\x9e\xe9\x80\x9a\xe6\x9c\x8d\xe5\x8b\x99\x22"); add("zh_CN", "OneKey Service Canceled", "\xe5\x8f\x96\xe6\xb6\x88\xe4\xbd\xbf\xe7\x94\xa8\xe4\xb8\x80\xe7\x82\xb9\xe9\x80\x9a\xe6\x9c\x8d\xe5\x8a\xa1"); add("zh_TW", "OneKey Services", "\xe4\xb8\x80\xe9\xbb\x9e\xe9\x80\x9a\xe6\x9c\x8d\xe5\x8b\x99"); add("zh_CN", "OneKey Services", "\xe4\xb8\x80\xe7\x82\xb9\xe9\x80\x9a\xe6\x9c\x8d\xe5\x8a\xa1"); add("zh_TW", "No query input, canceled", "\xe6\xb2\x92\xe6\x9c\x89\xe8\xbc\xb8\xe5\x85\xa5\xe5\x85\xa7\xe5\xae\xb9\xef\xbc\x8c\xe5\x8f\x96\xe6\xb6\x88\xe4\xb8\x80\xe9\xbb\x9e\xe9\x80\x9a\xe6\x9f\xa5\xe8\xa9\xa2\xe3\x80\x82"); add("zh_CN", "No query input, canceled", "\xe6\xb2\xa1\xe6\x9c\x89\xe8\xbe\x93\xe5\x85\xa5\xe5\x86\x85\xe5\xae\xb9\xef\xbc\x8c\xe5\x8f\x96\xe6\xb6\x88\xe4\xb8\x80\xe7\x82\xb9\xe9\x80\x9a\xe6\x9f\xa5\xe8\xaf\xa2\xe3\x80\x82"); #endif } }; typedef OVLocalization<OneKeyStringTable> OKL; YKAFOneKeyContext::YKAFOneKeyContext(YKAFOneKey* module) : m_module(module) , m_oneKeyData(0) , m_loggingUserInput(false) { } YKAFOneKeyContext::~YKAFOneKeyContext() { if (m_oneKeyData) { delete m_oneKeyData; } } void YKAFOneKeyContext::clear(OVLoaderService* loaderService) { m_loggingUserInput = false; m_invokingFeature = 0; m_loggingText.clear(); m_loggingTextCursor = 0; loaderService->setPrompt(""); loaderService->setPromptDescription(""); loaderService->setLog(""); } void YKAFOneKeyContext::startSession(OVLoaderService* loaderService) { if (m_oneKeyData) { delete m_oneKeyData; m_oneKeyData = 0; } void* data = loaderService->loaderSpecificDataObjectForName("OneKeyDataCopy"); if (data) { m_oneKeyData = reinterpret_cast<PVPlistValue*>(data); // loaderService->logger("YKAFOneKeyContext") << "We have data!" << endl << *m_oneKeyData << endl; } clear(loaderService); } void YKAFOneKeyContext::stopSession(OVLoaderService* loaderService) { if (m_oneKeyData) { delete m_oneKeyData; m_oneKeyData = 0; } clear(loaderService); } bool YKAFOneKeyContext::handleDirectText(const vector<string>& segments, OVTextBuffer* readingText, OVTextBuffer* composingText, OVCandidateService* candidateService, OVLoaderService* loaderService) { if (!m_oneKeyData) { return false; } if (m_loggingUserInput && m_invokingFeature) { if (!m_invokingFeature->isKeyTrue("RecordsKeyStrokeOnly")) { m_loggingText += OVStringHelper::Join(segments); loaderService->setLog(m_loggingText); } return true; } return false; } bool YKAFOneKeyContext::handleKey(OVKey* key, OVTextBuffer* readingText, OVTextBuffer* composingText, OVCandidateService* candidateService, OVLoaderService* loaderService) { // cerr << "handleKey " << key->keyCode() << ", logging? " << m_loggingUserInput << ", invoking feature? " << hex << (unsigned int)m_invokingFeature << dec << endl; if (!m_oneKeyData) { return false; } if (composingText->composedText().length()) { return false; } if (readingText->composedText().length()) { return false; } if ((key->keyCode() == OVKeyCode::Left || key->keyCode() == OVKeyCode::Right) && m_loggingUserInput) { if (composingText->isEmpty() && readingText->isEmpty()) { loaderService->beep(); return true; } } if (key->keyCode() == m_module->m_cfgShortcutKey && !key->isCombinedFunctionKey() && !m_loggingUserInput) { bool suppressed = (bool)loaderService->loaderSpecificDataObjectForName("ServerSideUIDisabled"); if (suppressed) { loaderService->beep(); return true; } PVPlistValue* farray = m_oneKeyData->valueForKey("Features"); if (!farray) { return true; } size_t fc = farray->arraySize(); if (!fc) { return true; } // scan the keys first set<char> usedShortcutKeys; size_t vendorFeatures = 0; vector<pair<char, size_t> > collectedFeatures; for (size_t i = 0 ; i < fc ; i++) { PVPlistValue* feature = farray->arrayElementAtIndex(i); if (feature->isKeyTrue("IsVendorFeature") && vendorFeatures < 10) { char key = (vendorFeatures != 9 ? ('1' + (char)vendorFeatures) : '0'); usedShortcutKeys.insert(key); collectedFeatures.push_back(pair<char, size_t>(key, i)); vendorFeatures++; } else { char key = 0; string sk = feature->stringValueForKey("ShortcutKey"); if (sk.size()) { key = tolower(sk[0] & 0x7f); if (key < 'a' || key > 'z') { key = 0; } } if (key) { usedShortcutKeys.insert(key); } collectedFeatures.push_back(pair<char, size_t>(key, i)); } } string unassignedKeys = "abcdefghijklmnopqrstuvwxyz"; string::iterator uki = unassignedKeys.begin(); for (vector<pair<char, size_t> >::iterator cfi = collectedFeatures.begin() ; cfi != collectedFeatures.end() ; ++cfi) { if ((*cfi).first) { continue; } while (uki != unassignedKeys.end()) { if (usedShortcutKeys.find(*uki) == usedShortcutKeys.end()) { break; } uki++; } if (uki != unassignedKeys.end()) { (*cfi).first = *uki; uki++; } } OVOneDimensionalCandidatePanel* panel = candidateService->useVerticalCandidatePanel(); OVCandidateList* list = panel->candidateList(); list->clear(); // now we collect the features string shortcutKey; for (vector<pair<char, size_t> >::iterator cfi = collectedFeatures.begin() ; cfi != collectedFeatures.end() ; ++cfi) { if ((*cfi).first) { // loaderService->logger("OneKey") << "key " << (*cfi).first << ", feature: " << (*cfi).second << endl; shortcutKey += string(1, (*cfi).first); list->addCandidate(localizedFeatureTitleAtIndex((*cfi).second)); } } composingText->clear(); composingText->updateDisplay(); readingText->clear(); readingText->updateDisplay(); loaderService->setLog(""); panel->setCandidatesPerPage(shortcutKey.size()); panel->setCandidateKeys(shortcutKey, loaderService); panel->updateDisplay(); panel->show(); panel->yieldToCandidateEventHandler(); return true; } if (!m_loggingUserInput || !m_invokingFeature) { return false; } if ((key->keyCode() == m_module->m_cfgShortcutKey || key->keyCode() == OVKeyCode::Esc) && !key->isCombinedFunctionKey()) { loaderService->notify(OKL::S("OneKey Service Canceled")); composingText->clear(); composingText->updateDisplay(); readingText->clear(); readingText->updateDisplay(); clear(loaderService); return true; } if (key->keyCode() == OVKeyCode::Space) { if (m_loggingText.size()) { m_loggingText += " "; loaderService->setLog(m_loggingText); return true; } else { loaderService->beep(); return true; } } if (key->keyCode() == OVKeyCode::Backspace) { vector<string> codepoints = OVUTF8Helper::SplitStringByCodePoint(m_loggingText); if (codepoints.size()) { codepoints.pop_back(); } else { loaderService->beep(); return true; } m_loggingText = OVStringHelper::Join(codepoints); loaderService->setLog(m_loggingText); return true; } if (key->keyCode() == OVKeyCode::Return || key->keyCode() == OVKeyCode::Enter) { if (!m_loggingText.length()) { loaderService->notify(OKL::S("No query input, canceled")); } else { PVPlistValue* action = m_invokingFeature->valueForKey("Action"); string actionString = action ? action->stringValue() : string(); PVPlistValue* tracker = m_invokingFeature->valueForKey("Tracker"); string trackerString = tracker ? tracker->stringValue() : string(); if (trackerString.size()) { loaderService->callLoaderFeature("SendTrackerRequest", trackerString); // loaderService->logger("OneKey") << trackerString << endl; } if (actionString == "OpenDictionary") { loaderService->lookupInDefaultDictionary(m_loggingText); } else if (actionString == "OpenURL") { // re-encode the string string reencodedString = m_loggingText; PVPlistValue* encoding = m_invokingFeature->valueForKey("PlaceHolderEncoding"); if (encoding) { string encodingString = encoding->stringValue(); if (!encodingString.length()) { encodingString = "UTF-8"; } OVEncodingService* encodingService = loaderService->encodingService(); if (encodingService) { pair<bool, string> result = encodingService->convertEncoding("UTF-8", encodingString, m_loggingText); if (result.first) { reencodedString = result.second; } } } string URLString = localizedStringForKeyInPlist(m_invokingFeature->valueForKey("ActionURL")); PVPlistValue* placeholder = m_invokingFeature->valueForKey("InputPlaceHolder"); if (placeholder) { string placeholderString = placeholder->stringValue(); if (placeholderString.length()) { if (URLString.size()) { reencodedString = OVStringHelper::PercentEncode(reencodedString); URLString = OVStringHelper::StringByReplacingOccurrencesOfStringWithString(URLString, placeholderString, reencodedString); } } } if (URLString.length()) { loaderService->openURL(URLString); } } else if (actionString == "LaunchApp") { string placeHolder = m_invokingFeature->stringValueForKey("InputPlaceHolder"); string appName = m_invokingFeature->stringValueForKey("LaunchAppName"); string appArgs = m_invokingFeature->stringValueForKey("LaunchAppArguments"); vector<string> aa; if (appName.length()) { aa.push_back(appName); if (appArgs.length()) { if (placeHolder.length()) { appArgs = OVStringHelper::StringByReplacingOccurrencesOfStringWithString(appArgs, placeHolder, m_loggingText); } aa.push_back(appArgs); } loaderService->callLoaderFeature("LaunchApp", OVStringHelper::Join(aa, "\t")); } } } readingText->clear(); readingText->updateDisplay(); composingText->clear(); composingText->updateDisplay(); clear(loaderService); return true; } if (m_invokingFeature->isKeyTrue("RecordsKeyStrokeOnly")) { if (key->isDirectTextKey() || key->isCapsLockOn()) { m_loggingText += string(1, toupper((char)key->keyCode())); } else { m_loggingText += string(1, (char)key->keyCode()); } loaderService->setLog(m_loggingText); return true; } return false; } bool YKAFOneKeyContext::candidateSelected(OVCandidateService* candidateService, const string& text, size_t index, OVTextBuffer* readingText, OVTextBuffer* composingText, OVLoaderService* loaderService) { readingText->clear(); readingText->updateDisplay(); composingText->clear(); composingText->updateDisplay(); // see if we need to log PVPlistValue* farray = m_oneKeyData->valueForKey("Features"); if (!farray) { return true; } m_invokingFeature = farray->arrayElementAtIndex(index); if (!m_invokingFeature) { return true; } if (!m_invokingFeature->isKeyTrue("RequiresInput")) { string action = m_invokingFeature->stringValueForKey("Action"); if (action == "LaunchApp") { string appName = m_invokingFeature->stringValueForKey("LaunchAppName"); string appArgs = m_invokingFeature->stringValueForKey("LaunchAppArguments"); vector<string> aa; if (appName.length()) { aa.push_back(appName); if (appArgs.length()) { aa.push_back(appArgs); } loaderService->callLoaderFeature("LaunchApp", OVStringHelper::Join(aa, "\t")); } } else if (action == "OpenURL") { string url = m_invokingFeature->stringValueForKey("ActionURL"); if (url.length()) { loaderService->openURL(url); } } // invoke the feature, and returns m_invokingFeature = 0; return true; } m_loggingUserInput = true; string lstr; lstr = localizedStringForKeyInPlist(m_invokingFeature->valueForKey("InputPrompt"), OKL::S("Query:")); lstr = OVStringHelper::StringByReplacingOccurrencesOfStringWithString(lstr, "\\n", "\n"); loaderService->setPrompt(lstr); lstr = localizedStringForKeyInPlist(m_invokingFeature->valueForKey("InputPromptDescription"), OKL::S("Type ENTER to send; ESC to cancel")); lstr = OVStringHelper::StringByReplacingOccurrencesOfStringWithString(lstr, "\\n", "\n"); loaderService->setPromptDescription(lstr); return true; } void YKAFOneKeyContext::candidateCanceled(OVCandidateService* candidateService, OVTextBuffer* readingText, OVTextBuffer* composingText, OVLoaderService* loaderService) { loaderService->notify(OKL::S("OneKey Service Canceled")); composingText->clear(); composingText->updateDisplay(); clear(loaderService); } bool YKAFOneKeyContext::candidateNonPanelKeyReceived(OVCandidateService* candidateService, const OVKey* key, OVTextBuffer* readingText, OVTextBuffer* composingText, OVLoaderService* loaderService) { if (key->keyCode() == m_module->m_cfgShortcutKey && !key->isCombinedFunctionKey()) { // OVOneDimensionalCandidatePanel* panel = candidateService->useOneDimensionalCandidatePanel(); OVOneDimensionalCandidatePanel* panel = candidateService->useVerticalCandidatePanel(); panel->hide(); panel->cancelEventHandler(); clear(loaderService); composingText->clear(); composingText->updateDisplay(); loaderService->notify(OKL::S("OneKey Service Canceled")); return true; } OVOneDimensionalCandidatePanel* panel = candidateService->useVerticalCandidatePanel(); panel->updateDisplay(); loaderService->beep(); return true; } size_t YKAFOneKeyContext::featureCount() { PVPlistValue* farray = m_oneKeyData->valueForKey("Features"); if (!farray) { return 0; } return farray->arraySize(); } const string YKAFOneKeyContext::localizedFeatureTitleAtIndex(size_t index) { PVPlistValue* farray = m_oneKeyData->valueForKey("Features"); if (!farray) { return string(); } if (index >= farray->arraySize()) { return string(); } PVPlistValue* feature = farray->arrayElementAtIndex(index); if (feature->type() != PVPlistValue::Dictionary) { return string(); } PVPlistValue* name = feature->valueForKey("ServiceName"); string defaultTitle = name ? name->stringValue() : string(); return localizedStringForKeyInPlist(feature->valueForKey("Title"), defaultTitle); } const string YKAFOneKeyContext::localizedStringForKeyInPlist(PVPlistValue* dict, const string& defaultValue) { if (!dict) { return defaultValue; } if (dict->type() == PVPlistValue::String) { return dict->stringValue(); } PVPlistValue* value = dict->valueForKey(m_module->m_locale); if (!value) { value = dict->valueForKey("en"); } if (!value) { vector<string> keys = dict->dictionaryKeys(); if (keys.size()) { value = dict->valueForKey(keys[0]); } } if (!value) { return defaultValue; } if (value->type() != PVPlistValue::String) { return defaultValue; } return value->stringValue(); } const string YKAFOneKey::localizedName(const string& locale) { return OKL::S(locale, "OneKey Services"); } OVEventHandlingContext* YKAFOneKey::createContext() { return new YKAFOneKeyContext(this); } bool YKAFOneKey::initialize(OVPathInfo* pathInfo, OVLoaderService* loaderService) { m_cfgShortcutKey = '`'; m_locale = loaderService->locale(); OKL::SetDefaultLocale(m_locale); return true; } const string YKAFOneKey::identifier() const { return "OneKey"; } int YKAFOneKey::suggestedOrder() const { return -10000; } void YKAFOneKey::loadConfig(OVKeyValueMap* moduleConfig, OVLoaderService* loaderService) { if (moduleConfig->hasKey("ShortcutKey")) { string v = moduleConfig->stringValueForKey("ShortcutKey"); if (v.size()) m_cfgShortcutKey = v[0]; } m_locale = loaderService->locale(); } void YKAFOneKey::saveConfig(OVKeyValueMap* moduleConfig, OVLoaderService* loaderService) { moduleConfig->setKeyStringValue("ShortcutKey", string(1, m_cfgShortcutKey)); }
9b43d715022d8740d9b60c435969c42fbab5e005
b86d4fe35f7e06a1981748894823b1d051c6b2e5
/UVa/10815 Andy’s First Dictionary 1.cpp
f8f715945756f315b2a57b88d45f635736d2bb7b
[]
no_license
sifat-mbstu/Competitive-Programming
f138fa4f7a9470d979106f1c8106183beb695fd2
c6c28979edb533db53e9601073b734b6b28fc31e
refs/heads/master
2021-06-26T20:18:56.607322
2021-04-03T04:52:20
2021-04-03T04:52:20
225,800,602
1
0
null
null
null
null
UTF-8
C++
false
false
993
cpp
#include<bits/stdc++.h> using namespace std; #define FI freopen ("input.txt", "r", stdin); #define FO freopen ("output.txt", "w", stdout); struct Dic{ string s[200]; } book[1000100],temp; int main() { FI; set <string> myset; set <string>:: iterator it; int i = 0,j = 0,k; bool t = 0; char c; while(scanf("%c",&c)==1) { if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { if(c < 97){c += 32;} t =1; book[i].s.push_back(c); j++; } else { //book[i].s[j] = '\0'; myset.insert(book[i].s[j]); if(t) {i++; t = 0;} j = 0; } } //str_sort(i); for(k = 0; k < i; k++) { if(k > 0){j = k-1; //while(strcmp(book[j].s,book[k].s)==0) k++;} for(it = myset.begin(); it != myset.end(); it++) cout << *it <<endl; //printf("%s\n",book[k].s); cout << } }
f3b07071b452a86c7768dceef9f5a63057b315ef
34dbe8f7576fc69b7a1cfc5eb31cff6d9ed817e5
/HW7/vp/platform/GaussianBlur1.h
237f6daec851fc2db95aecf9767a6bdf4deb19b6
[]
no_license
NickshihU7/EE6470
e586ebdfbbe3ea66ef432ab0fbecad15b5c7f914
8657777f8dc0966647cc9c0feeaef1b3fbdbb916
refs/heads/main
2023-06-12T12:46:33.226532
2021-07-04T02:22:26
2021-07-04T02:22:26
349,443,176
1
0
null
null
null
null
UTF-8
C++
false
false
3,513
h
#define SOBEL_FILTER_H_ #define SOBEL_FILTER_H_ #include <systemc> #include <cmath> #include <iomanip> using namespace sc_core; #include <tlm> #include <tlm_utils/simple_target_socket.h> #include "filter_def.h" struct GaussianBlur1 : public sc_module { tlm_utils::simple_target_socket<GaussianBlur1> tsock; sc_fifo<unsigned char> i_r; sc_fifo<unsigned char> i_g; sc_fifo<unsigned char> i_b; sc_fifo<int> o_red; sc_fifo<int> o_green; sc_fifo<int> o_blue; SC_HAS_PROCESS(GaussianBlur1); GaussianBlur1(sc_module_name n): sc_module(n), tsock("t_skt"), base_offset(0) { tsock.register_b_transport(this, &GaussianBlur1::blocking_transport); SC_THREAD(do_filter); } ~GaussianBlur1() { } unsigned int base_offset; void do_filter(){ { wait(CLOCK_PERIOD, SC_NS); } while (true) { double red = 0; double green = 0; double blue = 0; for (unsigned int v = 0; v < MASK_Y; ++v) { for (unsigned int u = 0; u < MASK_X; ++u) { red += i_r.read() * mask1[v][u]; green += i_g.read() * mask1[v][u]; blue += i_b.read() * mask1[v][u]; wait(CLOCK_PERIOD, SC_NS); } } o_red.write(red); o_green.write(green); o_blue.write(blue); } } void blocking_transport(tlm::tlm_generic_payload &payload, sc_core::sc_time &delay){ wait(delay); // unsigned char *mask_ptr = payload.get_byte_enable_ptr(); // auto len = payload.get_data_length(); tlm::tlm_command cmd = payload.get_command(); sc_dt::uint64 addr = payload.get_address(); unsigned char *data_ptr = payload.get_data_ptr(); addr -= base_offset; // cout << (int)data_ptr[0] << endl; // cout << (int)data_ptr[1] << endl; // cout << (int)data_ptr[2] << endl; word buffer; switch (cmd) { case tlm::TLM_READ_COMMAND: // cout << "READ" << endl; switch (addr) { case SOBEL_FILTER_RESULT_ADDR1: buffer.uint = o_red.read(); break; case SOBEL_FILTER_RESULT_ADDR2: buffer.uint = o_green.read(); break; case SOBEL_FILTER_RESULT_ADDR3: buffer.uint = o_blue.read(); break; default: std::cerr << "READ Error! GaussianBlur1::blocking_transport: address 0x" << std::setfill('0') << std::setw(8) << std::hex << addr << std::dec << " is not valid" << std::endl; } data_ptr[0] = buffer.uc[0]; data_ptr[1] = buffer.uc[1]; data_ptr[2] = buffer.uc[2]; data_ptr[3] = buffer.uc[3]; break; case tlm::TLM_WRITE_COMMAND: // cout << "WRITE" << endl; switch (addr) { case SOBEL_FILTER_R_ADDR: i_r.write(data_ptr[0]); i_g.write(data_ptr[1]); i_b.write(data_ptr[2]); break; default: std::cerr << "WRITE Error! GaussianBlur1::blocking_transport: address 0x" << std::setfill('0') << std::setw(8) << std::hex << addr << std::dec << " is not valid" << std::endl; } break; case tlm::TLM_IGNORE_COMMAND: payload.set_response_status(tlm::TLM_GENERIC_ERROR_RESPONSE); return; default: payload.set_response_status(tlm::TLM_GENERIC_ERROR_RESPONSE); return; } payload.set_response_status(tlm::TLM_OK_RESPONSE); // Always OK } }; //#endif
e006ebe035c7059bd9e74a70dddb40070616f296
cb51541a2b8f5912778cc11951dc54be60173d93
/Last_Digit_of_the_Sum_of_Squares_of_Fibonacci_Numbers.cc
63d7e9a7d41f7bb61a5435869af827f4a9316dab
[]
no_license
dev-gupta01/C-Programs
1bc1b4919af098fa456ea9a896d3d6ec91b5bacd
d3b214864046f581a6fdeac64d3d8f8fc38a3598
refs/heads/master
2021-05-24T17:39:18.674849
2020-04-07T09:22:32
2020-04-07T09:22:32
253,680,969
1
0
null
null
null
null
UTF-8
C++
false
false
552
cc
#include<bits/stdc++.h> using namespace std; int get_fibonacci_last_digit_fast(long long n) { if(n<=1) return n; int f1=0,f2=1,f3; for(int i=0; i<n-1;i++){ f3=(f1+f2)%10; f1=f2%10; f2=f3%10; } return f3; } int fibonacci_sum_fast(long long n) { int new_last_n = get_fibonacci_last_digit_fast(n%60); int new_last_m = get_fibonacci_last_digit_fast((n+1)%60); return (new_last_m*new_last_n)%10; } int main(){ long long int n; cin>>n; int ans=fibonacci_sum_fast(n); cout<<ans<<"\n"; }
1e15910275e3a005d65b70794368e4491fe4d595
d82234e36bad9a22166879888cbf0cddc9123006
/sprout/compost/effects/reverbed.hpp
265231a49272b5740a896ea5c44db65f318f4a6f
[ "BSL-1.0" ]
permissive
pasberth/Sprout
62229150bd399720f68d9de97bc3d60c2e7f335f
12e12373d0f70543eac5f2ecfbec8f5112765f98
refs/heads/master
2021-01-14T11:51:48.254846
2014-01-20T04:09:54
2014-01-20T04:09:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,364
hpp
/*============================================================================= Copyright (c) 2011-2014 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout 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) =============================================================================*/ #ifndef SPROUT_COMPOST_EFFECTS_REVERBED_HPP #define SPROUT_COMPOST_EFFECTS_REVERBED_HPP #include <cstddef> #include <iterator> #include <sprout/config.hpp> #include <sprout/utility/forward.hpp> #include <sprout/math/constants.hpp> #include <sprout/math/pow.hpp> #include <sprout/range/adaptor/transformed.hpp> #include <sprout/range/adaptor/outdirected.hpp> #include <sprout/range/adaptor/indexed.hpp> namespace sprout { namespace compost { // // reverb_outdirected_value // template<typename Value, typename IntType> struct reverb_outdirected_value { public: typedef Value value_type; typedef IntType int_type; private: value_type attenuation_; value_type delay_; std::size_t repeat_; int_type samples_per_sec_; private: template<typename Outdirected> SPROUT_CONSTEXPR typename std::iterator_traits<Outdirected>::value_type calc_1(Outdirected const& x, std::size_t i, typename Outdirected::index_type m) const { return m >= 0 ? sprout::math::pow(attenuation_, i) * x[m - x.index()] : 0 ; } template<typename Outdirected> SPROUT_CONSTEXPR typename std::iterator_traits<Outdirected>::value_type calc(Outdirected const& x, std::size_t i = 1) const { return i <= repeat_ ? calc_1(x, i, static_cast<typename Outdirected::index_type>(x.index() - i * delay_ * samples_per_sec_)) + calc(x, i + 1) : 0 ; } public: SPROUT_CONSTEXPR reverb_outdirected_value( value_type const& attenuation, value_type const& delay, std::size_t repeat = 2, int_type samples_per_sec = 44100 ) : attenuation_(attenuation), delay_(delay), repeat_(repeat), samples_per_sec_(samples_per_sec) {} template<typename Outdirected> SPROUT_CONSTEXPR typename std::iterator_traits<Outdirected>::value_type operator()(Outdirected const& x) const { return *x + calc(x); } }; namespace effects { // // reverb_holder // template<typename T, typename IntType = int> class reverb_holder { public: typedef T value_type; typedef IntType int_type; private: value_type attenuation_; value_type delay_; std::size_t repeat_; int_type samples_per_sec_; public: SPROUT_CONSTEXPR reverb_holder() SPROUT_DEFAULTED_DEFAULT_CONSTRUCTOR_DECL reverb_holder(reverb_holder const&) = default; SPROUT_CONSTEXPR reverb_holder( value_type const& attenuation, value_type const& delay, std::size_t repeat = 2, int_type samples_per_sec = 44100 ) : attenuation_(attenuation), delay_(delay), repeat_(repeat), samples_per_sec_(samples_per_sec) {} SPROUT_CONSTEXPR value_type const& attenuation() const { return attenuation_; } SPROUT_CONSTEXPR value_type const& delay() const { return delay_; } SPROUT_CONSTEXPR std::size_t const& repeat() const { return repeat_; } SPROUT_CONSTEXPR int_type const& samples_per_sec() const { return samples_per_sec_; } }; // // reverbed_forwarder // class reverbed_forwarder { public: template<typename T, typename IntType> SPROUT_CONSTEXPR sprout::compost::effects::reverb_holder<T, IntType> operator()(T const& attenuation, T const& delay, std::size_t repeat, IntType samples_per_sec) const { return sprout::compost::effects::reverb_holder<T, IntType>(attenuation, delay, repeat, samples_per_sec); } template<typename T> SPROUT_CONSTEXPR sprout::compost::effects::reverb_holder<T> operator()(T const& attenuation, T const& delay, std::size_t repeat = 2) const { return sprout::compost::effects::reverb_holder<T>(attenuation, delay, repeat); } }; // // reverbed // namespace { SPROUT_STATIC_CONSTEXPR sprout::compost::effects::reverbed_forwarder reverbed = {}; } // anonymous-namespace // // operator| // template<typename Range, typename T, typename IntType> inline SPROUT_CONSTEXPR auto operator|(Range&& lhs, sprout::compost::effects::reverb_holder<T, IntType> const& rhs) -> decltype( sprout::forward<Range>(lhs) | sprout::adaptors::indexed | sprout::adaptors::outdirected | sprout::adaptors::transformed( sprout::compost::reverb_outdirected_value<T, IntType>( rhs.attenuation(), rhs.delay(), rhs.repeat(), rhs.samples_per_sec() ) ) ) { return sprout::forward<Range>(lhs) | sprout::adaptors::indexed | sprout::adaptors::outdirected | sprout::adaptors::transformed( sprout::compost::reverb_outdirected_value<T, IntType>( rhs.attenuation(), rhs.delay(), rhs.repeat(), rhs.samples_per_sec() ) ) ; } } // namespace effects using sprout::compost::effects::reverbed; } // namespace compost } // namespace sprout #endif // #ifndef SPROUT_COMPOST_EFFECTS_REVERBED_HPP
ce4e714a56fede3778b74613e18711c653fd0afe
18e06cdf38eced8b6bea24958a36f68a4684db16
/native/distributed/include/angel/pytorch/lr.h
56ea0f1c1430fb1b9f36e23759820baa8aa37866
[]
no_license
leleyu/graph
3836bf8e168c4f2e9fd86002db587fe993ab399c
87466146d99cfb2910aeebc9df847655c91ba6ee
refs/heads/master
2020-03-29T21:47:12.503609
2019-05-06T07:02:37
2019-05-06T07:02:37
150,387,447
2
2
null
2019-03-14T07:55:39
2018-09-26T07:39:07
Gherkin
UTF-8
C++
false
false
649
h
// // Created by leleyu on 2019-05-05. // #ifndef PYTORCH_LR_H #define PYTORCH_LR_H #include <iostream> #include <torch/torch.h> #include <torch/script.h> namespace angel { class LogisticRegression { public: explicit LogisticRegression(const std::string &path); at::Tensor forward(std::vector<torch::jit::IValue> inputs); void backward(at::Tensor batch_size, at::Tensor index, at::Tensor feats, at::Tensor values, at::Tensor bias, at::Tensor weights, at::Tensor targets); private: std::shared_ptr<torch::jit::script::Module> module_; }; } // namespace angel #endif //PYTORCH_LR_H
67d7081e1bee7a47f9636a7b55ea33bab5dd70da
5101c3ce5a4a02e9c270bd59337937d18406a7e1
/DatabaseManager.cpp
acf5331fea3eefbb6543ef0375c785df2b4d7a37
[]
no_license
NichHarris/real-estate-database-manager
5bbc6daca83f7cd9cfb5600c60a0d443e937a97e
859aa997d230aa764365073d8432be950987ed2a
refs/heads/master
2020-08-28T17:11:41.820542
2019-11-13T21:40:03
2019-11-13T21:40:03
217,765,311
0
0
null
null
null
null
UTF-8
C++
false
false
7,310
cpp
// Nicholas Harris - 40111093 // [email protected] // Vejay Tham. - 40112236 // [email protected] #include <iostream> #include"Client.h" #include"RealEstateAgent.h" #include"RealEstateManager.h" #include"LandSale.h" #include"HouseSale.h" #include"ApartmentSale.h" int main() { // Creating an agent std::cout << "----- Creating an agent using RealEstateAgent class -----" << std::endl; RealEstateAgent* r1; r1 = new RealEstateAgent; r1->setName("Emy Lafond"); r1->setAddress("20 Bugle Call"); Date hiredate(12, 21, 2012); r1->setHireDate(hiredate); r1->setID(1337); r1->print(); // Creating a person std::cout << "----- Creating a person using Person class -----" << std::endl; Person* p1; p1 = new Person; p1->setName("Theo Perring"); p1->setAddress("10 rosemount"); p1->print(); std::cout<<std::endl; // Creating a client std::cout << "----- Creating a client using Client class -----" << std::endl; Client* c1; c1 = new Client; c1->setName("Nick Harris"); c1->setAddress("2456 ascot park"); c1->setSIN("17750"); c1->print(); std::cout << std::endl; // Creating client using Person std::cout << "----- Creating a client using Person class -----" << std::endl; Client* c2; c2 = new Client; c2->setName(p1->getName()); c2->setAddress(p1->getAddress()); c2->setSIN("90210"); c2->print(); std::cout << std::endl; // Person 2 std::cout << "Person 2: " << std::endl; Person* p2; Date emptydate; p2 = new Person("Matthew Vallieres", "10 Yacht Club road", emptydate); p2->print(); std::cout << std::endl; // Realestate agent 2 std::cout << "Agent 2 using Person 2" << std::endl; RealEstateAgent* r2; Date hiredate2(5, 26, 2014); r2 = new RealEstateAgent; r2->setName(p2->getName()); r2->setAddress(p2->getAddress()); r2->setHireDate(hiredate2); r2->setID(1738); r2->print(); std::cout << std::endl; // Creating Properties using Property class std::cout << "----- Creating properties using Property class -----" << std::endl << std::endl; Property* prop1; prop1 = new Property; prop1->setAddress(c1->getAddress()); prop1->setCity("St-Lazare"); prop1->setSeller(c1); prop1->setAgent(r1); Date list_date(10, 26, 2019); prop1->setlistdate(list_date); prop1->print(); std::cout << std::endl; // Creating property2 using Property Class Property* prop2; Date list_date2(5, 21, 2018); std::string client2addr; client2addr = c2->getAddress(); prop2 = new Property(client2addr, "Westmount", c2, r2, list_date2); prop2->print(); std::cout << std::endl; // Property 3 Date list_date3(10, 11, 2019); Client* c3; c3 = new Client; c3->setAddress("9120 Venne"); c3->setName("Olivia Valcourt"); c3->setSIN("65845"); Property* prop3; prop3 = new Property; prop3->setAddress(c3->getAddress()); prop3->setCity("Pierrefonds"); prop3->setSeller(c3); prop3->setAgent(r2); prop3->setlistdate(list_date3); // Creating land for sale using LandSale class std::cout << "----- Creating land for sale using LandSale class using property3 -----" << std::endl; LandSale land1; land1.setAddress(prop3->getAddress()); land1.setCity(prop3->getCity()); land1.setSeller(c3); land1.setAgent(r2); land1.setlistdate(prop3->getlistdate()); land1.setArea(1500); land1.setPrice(550000); land1.print(); std::cout << std::endl; // Creating house for sale using HouseSale class std::cout << "----- Creating house for sale using HouseSale class and property2 -----" << std::endl; HouseSale house1; house1.setAddress(prop2->getAddress()); house1.setCity(prop2->getCity()); house1.setSeller(c2); house1.setAgent(r2); house1.setlistdate(prop2->getlistdate()); house1.setAge(1965); house1.setRooms(8); house1.setPrice(1200000); house1.print(); std::cout << std::endl; // Creating an apartment using ApartmentSale class std::cout << "----- Creating an apartment using ApartmentSale class and property1 -----" << std::endl; ApartmentSale apart1; apart1.setAddress(prop1->getAddress()); apart1.setCity(prop1->getCity()); apart1.setSeller(c1); apart1.setAgent(r1); apart1.setlistdate(prop1->getlistdate()); apart1.setAge(1998); apart1.setRooms(4); apart1.setPrice(110000); apart1.setFee(1100); apart1.print(); std::cout << std::endl; // Testing RealEstateManager //Testing boolinsertAgent std::cout << "----- Adding r1 and r2 to agentRecordsArray using insertAgent function -----" << std::endl; RealEstateManager manager; if (manager.insertAgent(*r1)) { std::cout << "Agent: " << r1->getName() << " succesfully added." << std::endl; } if (manager.insertAgent(*r2)) { std::cout << "Agent: " << r2->getName() << " succesfully added." << std::endl; } std::cout << "\n----- Testing adding same agent twice -----\n"; manager.insertAgent(*r1); std::cout << "\n----- Testing adding too many agents (using empty agents) -----\n"; RealEstateAgent* agents = new RealEstateAgent[30]; for (int i = 0; i < 30; i++) { if (manager.insertAgent(agents[i])) { std::cout << "Added test agent " << i+1 << std::endl; } } if (manager.insertProperty(prop1)) { std::cout << "Property at address: " << prop1->getAddress() << " succesfully added to listing.\n"; } if (manager.insertProperty(prop2)) { std::cout << "Property at address: " << prop2->getAddress() << " succesfully added to lsiting.\n"; } if (manager.insertProperty(prop3)) { std::cout << "Property at address: " << prop3->getAddress() << " succesfully added listing.\n\n"; } std::cout << "*----- Testing adding the same property twice -----" << std::endl; manager.insertProperty(prop1); std::cout << "----- Testing adding too many properties -----" << std::endl; Property* properties = new Property[1000]; for (int i = 0; i < 1000; i++) { manager.insertProperty(&properties[i]); } std::cout << "\n----- Testing propertySold function from RealEstateManager class -----\n"; std::cout << "----- Comparing prop1 and archiveRecordsArray after propertySold runs -----" << std::endl; prop1->print(); manager.propertySold(*prop1, *c2); std::cout << "\nBuyer of property at address " << prop1->getAddress() << ": " << prop1->getBuyer().getName() << std::endl; std::cout << "\n----- Property 1 updated info: -----" << std::endl; prop1->print(); std::cout << std::endl; // Using findHousesCity to output all the propertys in a given city. std::cout << "\n----- Testing findHousesCity function from RealEstateManager class -----\n\n"; std::cout << "Changing prop3 city to 'Westmount' for the test\n"; prop3->setCity("Westmount"); manager.findHousesCity("Westmount"); // Using findPropertiesAgent to output all the listings of the given agent // prop1 has Emy Lafond (r1) as agent, but since it has been sold it is on the archiveRecordsArray // and therefore won't show up under findPropertiesAgent for agent r1 prop2->setAgent(r1); std::cout << "\n------ Testing findPropertiesAgent function from RealEstateManager class ------\n\n"; manager.findPropertiesAgent(*r1); std::cout << std::endl; manager.findPropertiesAgent(*r2); std::cout << "\n\n\n"; }
28fe90b795bf5d2c6c5a491597ecc2ebfc2943b9
8ddd2ca4b49c138980fc4220e0ca907bda5952ee
/library/gameTheory/wythoffGame.cpp
76ff31b2b5c384029559becb34d580c3dce10221
[ "Unlicense" ]
permissive
bluedawnstar/algorithm_study
b7b08e2fca31ecfc87bafa3a9734627245f16ad5
d5aec7035e65d8f5386a0791c26d59340fd09ef5
refs/heads/master
2023-06-24T19:47:57.640559
2023-06-14T14:43:01
2023-06-14T14:43:01
76,085,991
45
8
Unlicense
2023-06-14T14:43:03
2016-12-10T02:41:35
C++
UTF-8
C++
false
false
835
cpp
#include <vector> #include <algorithm> using namespace std; #include "wythoffGame.h" /////////// For Testing /////////////////////////////////////////////////////// #include <time.h> #include <cassert> #include <string> #include <vector> #include <numeric> #include <iostream> #include "../common/iostreamhelper.h" #include "../common/profile.h" void testWythoffGame() { //return; //TODO: if you want to test, make this line a comment. cout << "--- Wythoff's game --------------------------" << endl; { vector<pair<int, int>> gt{ { 0, 0 }, { 1, 2 }, { 3, 5 }, { 4, 7 }, { 6, 10 }, { 8, 13 }, { 9, 15 }, { 11, 18 }, { 12, 20 } }; for (int i = 0; i < int(gt.size()); i++) { assert(WythoffGame::find(i) == gt[i]); } } cout << "OK!" << endl; }
a2b05112948766440bd6fa05fe0c34a52fabc12f
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/086/139/CWE191_Integer_Underflow__short_rand_sub_82_goodG2B.cpp
eedafff752029fad36621fbcfbb4a6255c8bba50
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
1,070
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE191_Integer_Underflow__short_rand_sub_82_goodG2B.cpp Label Definition File: CWE191_Integer_Underflow.label.xml Template File: sources-sinks-82_goodG2B.tmpl.cpp */ /* * @description * CWE: 191 Integer Underflow * BadSource: rand Set data to result of rand() * GoodSource: Set data to a small, non-zero number (negative two) * Sinks: sub * GoodSink: Ensure there will not be an underflow before subtracting 1 from data * BadSink : Subtract 1 from data, which can cause an Underflow * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer * * */ #ifndef OMITGOOD #include "std_testcase.h" #include "CWE191_Integer_Underflow__short_rand_sub_82.h" namespace CWE191_Integer_Underflow__short_rand_sub_82 { void CWE191_Integer_Underflow__short_rand_sub_82_goodG2B::action(short data) { { /* POTENTIAL FLAW: Subtracting 1 from data could cause an underflow */ short result = data - 1; printIntLine(result); } } } #endif /* OMITGOOD */
a7aec34dfb323d3e95d5f2707f089aaccc3b6bb2
3fe1f29c4cc3766cae3df919c2dd87489588e8a1
/include/OpenCVGoodFeatureExtractor.h
0a87b73cb09d42f304f220ef14dc7cc9c98fbefa
[]
no_license
JeanElsner/practical-multi-view
307d0fd6bc753b45c2244d1d237c012284767608
4f830863501e6e76b395bbca830760aba1af2ee7
refs/heads/master
2021-09-09T13:50:19.307725
2018-03-16T18:06:27
2018-03-16T18:06:27
111,742,609
9
1
null
null
null
null
UTF-8
C++
false
false
596
h
#ifndef OPENCV_GOOD_FEATURE_EXTRACTOR_H #define OPENCV_GOOD_FEATURE_EXTRACTOR_H #include "BaseFeatureExtractor.h" class OpenCVGoodFeatureExtractor: public BaseFeatureExtractor { public: // Minimum quality of features, in order to be selected double quality = 0.01; // Minimum distance between features, in order to be considered separate double min_distance = 5; OpenCVGoodFeatureExtractor() { } OpenCVGoodFeatureExtractor(double quality, double min_distance): quality(quality), min_distance(min_distance) { } std::vector<Feature> extractFeatures(Frame& src, int max); }; #endif
b57b2064ea3f87385f241c04e3c39083556a7b86
bb608853d87c1b51e6cc8a71d037b8480855b6aa
/SrcGame/src/HoBaram/HoMinMax.h
f0a2000d16a0af2560edaad1f55211f3fb939a34
[]
no_license
tobiasquinteiro/Source-GothicPT
9b8373f9025b82b4bf5d37e53de610e2ad5bef51
6542d5c6ab8b797cb6d83f66bde5ea0cd663d0e6
refs/heads/master
2022-12-31T04:43:21.159375
2020-10-26T00:26:34
2020-10-26T00:26:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,040
h
#ifndef _HO_MIN_MAX_H #define _HO_MIN_MAX_H #include <vector> #include <string> #ifndef D3D_OVERLOADS #define D3D_OVERLOADS #endif using namespace std; inline void MakeUpperCase(std::string &str) { for(std::string::iterator i = str.begin(); i != str.end(); i++) { *i = toupper(*i); } } inline std::string RemoveQuotes(std::string &str) { for(std::string::iterator i = str.begin(); i != str.end(); i++) { if(*i == '\"') { i = str.erase(i); if(i == str.end()) break; } } return(str); } int RandomNumber(int iMin, int iMax); float RandomNumber(float fMin, float fMax); D3DXVECTOR3 RandomNumber(D3DXVECTOR3 vMin, D3DXVECTOR3 vMax); D3DCOLORVALUE RandomNumber(D3DCOLORVALUE Min, D3DCOLORVALUE Max); template <class T> class HoMinMax { public: HoMinMax() { Min = T(); Max = T(); } HoMinMax(T tMin, T tMax) { Min = tMin; Max = tMax; } ~HoMinMax() { } T Min; T Max; T GetRandomNumInRange(void) { return(RandomNumber(Min, Max)); } T GetRange(void) { return(abs(Max - Min)); } }; #endif
162c1bdcf1bc2368842de614805400728ecd2eec
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/clang/lib/AST/InheritViz.cpp
3d64310dc56b6458fe432c20a03a780c41995e29
[ "MIT", "NCSA" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
5,247
cpp
//===- InheritViz.cpp - Graphviz visualization for inheritance --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements CXXRecordDecl::viewInheritance, which // generates a GraphViz DOT file that depicts the class inheritance // diagram and then calls Graphviz/dot+gv on it. // //===----------------------------------------------------------------------===// #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/TypeOrdering.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/GraphWriter.h" #include "llvm/Support/raw_ostream.h" #include <map> #include <set> using namespace llvm; namespace clang { /// InheritanceHierarchyWriter - Helper class that writes out a /// GraphViz file that diagrams the inheritance hierarchy starting at /// a given C++ class type. Note that we do not use LLVM's /// GraphWriter, because the interface does not permit us to properly /// differentiate between uses of types as virtual bases /// vs. non-virtual bases. class InheritanceHierarchyWriter { ASTContext& Context; raw_ostream &Out; std::map<QualType, int, QualTypeOrdering> DirectBaseCount; std::set<QualType, QualTypeOrdering> KnownVirtualBases; public: InheritanceHierarchyWriter(ASTContext& Context, raw_ostream& Out) : Context(Context), Out(Out) { } void WriteGraph(QualType Type) { Out << "digraph \"" << DOT::EscapeString(Type.getAsString()) << "\" {\n"; WriteNode(Type, false); Out << "}\n"; } protected: /// WriteNode - Write out the description of node in the inheritance /// diagram, which may be a base class or it may be the root node. void WriteNode(QualType Type, bool FromVirtual); /// WriteNodeReference - Write out a reference to the given node, /// using a unique identifier for each direct base and for the /// (only) virtual base. raw_ostream& WriteNodeReference(QualType Type, bool FromVirtual); }; void InheritanceHierarchyWriter::WriteNode(QualType Type, bool FromVirtual) { QualType CanonType = Context.getCanonicalType(Type); if (FromVirtual) { if (KnownVirtualBases.find(CanonType) != KnownVirtualBases.end()) return; // We haven't seen this virtual base before, so display it and // its bases. KnownVirtualBases.insert(CanonType); } // Declare the node itself. Out << " "; WriteNodeReference(Type, FromVirtual); // Give the node a label based on the name of the class. std::string TypeName = Type.getAsString(); Out << " [ shape=\"box\", label=\"" << DOT::EscapeString(TypeName); // If the name of the class was a typedef or something different // from the "real" class name, show the real class name in // parentheses so we don't confuse ourselves. if (TypeName != CanonType.getAsString()) { Out << "\\n(" << CanonType.getAsString() << ")"; } // Finished describing the node. Out << " \"];\n"; // Display the base classes. const CXXRecordDecl *Decl = static_cast<const CXXRecordDecl *>(Type->getAs<RecordType>()->getDecl()); for (CXXRecordDecl::base_class_const_iterator Base = Decl->bases_begin(); Base != Decl->bases_end(); ++Base) { QualType CanonBaseType = Context.getCanonicalType(Base->getType()); // If this is not virtual inheritance, bump the direct base // count for the type. if (!Base->isVirtual()) ++DirectBaseCount[CanonBaseType]; // Write out the node (if we need to). WriteNode(Base->getType(), Base->isVirtual()); // Write out the edge. Out << " "; WriteNodeReference(Type, FromVirtual); Out << " -> "; WriteNodeReference(Base->getType(), Base->isVirtual()); // Write out edge attributes to show the kind of inheritance. if (Base->isVirtual()) { Out << " [ style=\"dashed\" ]"; } Out << ";"; } } /// WriteNodeReference - Write out a reference to the given node, /// using a unique identifier for each direct base and for the /// (only) virtual base. raw_ostream& InheritanceHierarchyWriter::WriteNodeReference(QualType Type, bool FromVirtual) { QualType CanonType = Context.getCanonicalType(Type); Out << "Class_" << CanonType.getAsOpaquePtr(); if (!FromVirtual) Out << "_" << DirectBaseCount[CanonType]; return Out; } /// viewInheritance - Display the inheritance hierarchy of this C++ /// class using GraphViz. void CXXRecordDecl::viewInheritance(ASTContext& Context) const { QualType Self = Context.getTypeDeclType(this); int FD; SmallString<128> Filename; error_code EC = sys::fs::createTemporaryFile(Self.getAsString(), "dot", FD, Filename); if (EC) { llvm::errs() << "Error: " << EC.message() << "\n"; return; } llvm::errs() << "Writing '" << Filename << "'... "; llvm::raw_fd_ostream O(FD, true); InheritanceHierarchyWriter Writer(Context, O); Writer.WriteGraph(Self); llvm::errs() << " done. \n"; O.close(); // Display the graph DisplayGraph(Filename); } }
317c220ced4c3bf9cbd47147c17a4fa7c04f9288
7ea0ee06c76bac889ab514d6f434bfc45ff2cdee
/src/chrono_models/vehicle/man/MAN_5t_Vehicle.cpp
4c906a6c0328889c2504b0db1d4edfc7f165aae2
[ "BSD-3-Clause" ]
permissive
zzhou292/chrono-collision
94772decb392bb054ed69d7ed2987e2cd7033c28
c2a20e171bb0eb8819636d370887aa32d68547c6
refs/heads/master
2023-02-09T18:07:27.819855
2021-01-07T03:59:55
2021-01-07T03:59:55
324,093,881
1
1
null
null
null
null
UTF-8
C++
false
false
10,904
cpp
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban, Asher Elmquist, Evan Hoerl, Shuo He, Rainer Gericke // ============================================================================= // // MAN 5t full vehicle model. // // ============================================================================= #include "chrono/assets/ChSphereShape.h" #include "chrono/assets/ChTriangleMeshShape.h" #include "chrono/utils/ChUtilsInputOutput.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_vehicle/wheeled_vehicle/suspension/ChSolidAxle.h" #include "chrono_models/vehicle/man/MAN_5t_Vehicle.h" #include "chrono_models/vehicle/man/MAN_5t_Chassis.h" #include "chrono_models/vehicle/man/MAN_5t_BrakeSimple.h" #include "chrono_models/vehicle/man/MAN_5t_BrakeShafts.h" #include "chrono_models/vehicle/man/MAN_5t_Solid3LinkAxle.h" #include "chrono_models/vehicle/man/MAN_5t_BellcrankSolid3LinkAxle.h" #include "chrono_models/vehicle/man/MAN_5t_RotaryArm.h" #include "chrono_models/vehicle/man/MAN_5t_Driveline4WD.h" #include "chrono_models/vehicle/man/MAN_5t_SimpleDriveline.h" #include "chrono_models/vehicle/man/MAN_5t_Wheel.h" namespace chrono { namespace vehicle { namespace man { // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- MAN_5t_Vehicle::MAN_5t_Vehicle(const bool fixed, BrakeType brake_type, ChContactMethod contact_method, CollisionType chassis_collision_type, bool useShaftDrivetrain) : ChWheeledVehicle("MAN_5t", contact_method), m_omega({0, 0, 0, 0}), m_use_shafts_drivetrain(useShaftDrivetrain) { Create(fixed, brake_type, chassis_collision_type); } MAN_5t_Vehicle::MAN_5t_Vehicle(ChSystem* system, const bool fixed, BrakeType brake_type, CollisionType chassis_collision_type, bool useShaftDrivetrain) : ChWheeledVehicle("MAN_5t", system), m_omega({0, 0, 0, 0}), m_use_shafts_drivetrain(useShaftDrivetrain) { Create(fixed, brake_type, chassis_collision_type); } void MAN_5t_Vehicle::Create(bool fixed, BrakeType brake_type, CollisionType chassis_collision_type) { // Create the chassis subsystem m_chassis = chrono_types::make_shared<MAN_5t_Chassis>("Chassis", fixed, chassis_collision_type); // Create the axle subsystems (suspension + wheels + brakes) m_axles.resize(2); m_axles[0] = chrono_types::make_shared<ChAxle>(); m_axles[1] = chrono_types::make_shared<ChAxle>(); m_axles[0]->m_suspension = chrono_types::make_shared<MAN_5t_BellcrankSolid3LinkAxle>("FrontSusp"); m_axles[1]->m_suspension = chrono_types::make_shared<MAN_5t_Solid3LinkAxle>("RearSusp"); m_axles[0]->m_wheels.resize(2); m_axles[0]->m_wheels[0] = chrono_types::make_shared<MAN_5t_Wheel>("Wheel_FL"); m_axles[0]->m_wheels[1] = chrono_types::make_shared<MAN_5t_Wheel>("Wheel_FR"); m_axles[1]->m_wheels.resize(2); m_axles[1]->m_wheels[0] = chrono_types::make_shared<MAN_5t_Wheel>("Wheel_RL"); m_axles[1]->m_wheels[1] = chrono_types::make_shared<MAN_5t_Wheel>("Wheel_RR"); switch (brake_type) { case BrakeType::SIMPLE: m_axles[0]->m_brake_left = chrono_types::make_shared<MAN_5t_BrakeSimple>("Brake_FL"); m_axles[0]->m_brake_right = chrono_types::make_shared<MAN_5t_BrakeSimple>("Brake_FR"); m_axles[1]->m_brake_left = chrono_types::make_shared<MAN_5t_BrakeSimple>("Brake_RL"); m_axles[1]->m_brake_right = chrono_types::make_shared<MAN_5t_BrakeSimple>("Brake_RR"); break; case BrakeType::SHAFTS: m_axles[0]->m_brake_left = chrono_types::make_shared<MAN_5t_BrakeShafts>("Brake_FL"); m_axles[0]->m_brake_right = chrono_types::make_shared<MAN_5t_BrakeShafts>("Brake_FR"); m_axles[1]->m_brake_left = chrono_types::make_shared<MAN_5t_BrakeShafts>("Brake_RL"); m_axles[1]->m_brake_right = chrono_types::make_shared<MAN_5t_BrakeShafts>("Brake_RR"); break; } // Create the steering subsystem m_steerings.resize(1); m_steerings[0] = chrono_types::make_shared<MAN_5t_RotaryArm>("Steering"); // Create the driveline if (m_use_shafts_drivetrain) m_driveline = chrono_types::make_shared<MAN_5t_Driveline4WD>("Driveline"); else m_driveline = chrono_types::make_shared<MAN_5t_SimpleDriveline>("Driveline"); } MAN_5t_Vehicle::~MAN_5t_Vehicle() {} // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void MAN_5t_Vehicle::Initialize(const ChCoordsys<>& chassisPos, double chassisFwdVel) { // Initialize the chassis subsystem. m_chassis->Initialize(m_system, chassisPos, chassisFwdVel, WheeledCollisionFamily::CHASSIS); // Initialize the steering subsystem (specify the steering subsystem's frame relative to the chassis reference // frame). ChVector<> offset = ChVector<>(0, 0, 0.0); // 0.4 0 0.4 ChQuaternion<> rotation = ChQuaternion<>(1, 0, 0, 0); m_steerings[0]->Initialize(m_chassis, offset, rotation); // Initialize the axle subsystems. m_axles[0]->Initialize(m_chassis, nullptr, m_steerings[0], ChVector<>(0, 0, 0), ChVector<>(0), 0.0, m_omega[0], m_omega[1]); const double twin_tire_dist = 0.0; // Michelin for 305/85 R22.5 m_axles[1]->Initialize(m_chassis, nullptr, nullptr, ChVector<>(-4.5, 0, 0), ChVector<>(0), twin_tire_dist, m_omega[2], m_omega[3]); // Initialize the driveline subsystem (RWD) std::vector<int> driven_susp_indexes; driven_susp_indexes.resize(2); driven_susp_indexes[0] = 0; driven_susp_indexes[1] = 1; m_driveline->Initialize(m_chassis, m_axles, driven_susp_indexes); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- double MAN_5t_Vehicle::GetSpringForce(int axle, VehicleSide side) const { return std::static_pointer_cast<ChSolidAxle>(m_axles[axle]->m_suspension)->GetSpringForce(side); } double MAN_5t_Vehicle::GetSpringLength(int axle, VehicleSide side) const { return std::static_pointer_cast<ChSolidAxle>(m_axles[axle]->m_suspension)->GetSpringLength(side); } double MAN_5t_Vehicle::GetSpringDeformation(int axle, VehicleSide side) const { return std::static_pointer_cast<ChSolidAxle>(m_axles[axle]->m_suspension)->GetSpringDeformation(side); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- double MAN_5t_Vehicle::GetShockForce(int axle, VehicleSide side) const { return std::static_pointer_cast<ChSolidAxle>(m_axles[axle]->m_suspension)->GetShockForce(side); } double MAN_5t_Vehicle::GetShockLength(int axle, VehicleSide side) const { return std::static_pointer_cast<ChSolidAxle>(m_axles[axle]->m_suspension)->GetShockLength(side); } double MAN_5t_Vehicle::GetShockVelocity(int axle, VehicleSide side) const { return std::static_pointer_cast<ChSolidAxle>(m_axles[axle]->m_suspension)->GetShockVelocity(side); } // ----------------------------------------------------------------------------- // Log the hardpoint locations for the front-right and rear-right suspension // subsystems (display in inches) // ----------------------------------------------------------------------------- void MAN_5t_Vehicle::LogHardpointLocations() { GetLog().SetNumFormat("%7.3f"); GetLog() << "\n---- FRONT suspension hardpoint locations (LEFT side)\n"; std::static_pointer_cast<ChSolidAxle>(m_axles[0]->m_suspension)->LogHardpointLocations(ChVector<>(0, 0, 0), false); GetLog() << "\n---- REAR suspension hardpoint locations (LEFT side)\n"; std::static_pointer_cast<ChSolidAxle>(m_axles[1]->m_suspension)->LogHardpointLocations(ChVector<>(0, 0, 0), false); GetLog() << "\n\n"; GetLog().SetNumFormat("%g"); } // ----------------------------------------------------------------------------- // Log the spring length, deformation, and force. // Log the shock length, velocity, and force. // Log constraint violations of suspension joints. // // Lengths are reported in inches, velocities in inches/s, and forces in lbf // ----------------------------------------------------------------------------- void MAN_5t_Vehicle::DebugLog(int what) { GetLog().SetNumFormat("%10.2f"); if (what & OUT_SPRINGS) { GetLog() << "\n---- Spring (front-left, front-right, rear-left, rear-right)\n"; GetLog() << "Length [m] " << GetSpringLength(0, LEFT) << " " << GetSpringLength(0, RIGHT) << " " << GetSpringLength(1, LEFT) << " " << GetSpringLength(1, RIGHT) << "\n"; GetLog() << "Deformation [m] " << GetSpringDeformation(0, LEFT) << " " << GetSpringDeformation(0, RIGHT) << " " << GetSpringDeformation(1, LEFT) << " " << GetSpringDeformation(1, RIGHT) << "\n"; GetLog() << "Force [N] " << GetSpringForce(0, LEFT) << " " << GetSpringForce(0, RIGHT) << " " << GetSpringForce(1, LEFT) << " " << GetSpringForce(1, RIGHT) << "\n"; } if (what & OUT_SHOCKS) { GetLog() << "\n---- Shock (front-left, front-right, rear-left, rear-right)\n"; GetLog() << "Length [m] " << GetShockLength(0, LEFT) << " " << GetShockLength(0, RIGHT) << " " << GetShockLength(1, LEFT) << " " << GetShockLength(1, RIGHT) << "\n"; GetLog() << "Velocity [m/s] " << GetShockVelocity(0, LEFT) << " " << GetShockVelocity(0, RIGHT) << " " << GetShockVelocity(1, LEFT) << " " << GetShockVelocity(1, RIGHT) << "\n"; GetLog() << "Force [N] " << GetShockForce(0, LEFT) << " " << GetShockForce(0, RIGHT) << " " << GetShockForce(1, LEFT) << " " << GetShockForce(1, RIGHT) << "\n"; } if (what & OUT_CONSTRAINTS) { // Report constraint violations for all joints LogConstraintViolations(); } GetLog().SetNumFormat("%g"); } } // namespace man } // end namespace vehicle } // end namespace chrono
0ea581812e156967bf70b1c96ad65cc50adec1aa
9c6b6b6aa676ee0b42a12d433a808be5e82a9109
/src/Camera.cpp
5b2535d4ed0e258c4aa51b840045dab94177ff4a
[]
no_license
vsian/PetTracer
8a766f3f1b073728e44dee7ca7088db2380b0ca7
bea0f7b766be02d106112a1ae30bc45035d699a0
refs/heads/master
2023-03-08T15:04:51.074582
2021-02-22T13:50:21
2021-02-22T13:50:21
336,226,245
0
0
null
null
null
null
UTF-8
C++
false
false
141
cpp
#include "Camera.h" Ray :: Ray camera :: getRay(float u, float v) { return Ray :: Ray(origin, lower_f + u * horizontal + v * vertical); }
fb5aae230547ca8e9562c466c19403e78e7b8dbb
63d66888933b428798cbb732455c1f42513532b2
/Examples/Include/Publish/ILine.h
47f13e71894afdfba5234951ab76b0ca0e9ff9d1
[]
no_license
LLuMM/Aspose.Cells-for-C
eac76ca4cc197f45fa6e4ba6def95e811d17e945
541ef8e35624ac243c639dac871607e1f0176b8b
refs/heads/master
2020-05-29T08:22:38.637825
2018-07-25T13:34:37
2018-07-25T13:34:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,192
h
#pragma once #include "System/Object.h" #include "System/Drawing/Color.h" #include "System/Double.h" namespace Aspose { namespace Cells { namespace Drawing { enum MsoLineStyle; enum MsoLineDashStyle; enum LineCapType; enum LineJoinType; enum MsoArrowheadStyle; enum MsoArrowheadLength; enum MsoArrowheadWidth; enum LineType; enum WeightType; class IGradientFill; } } } namespace Aspose { namespace Cells { namespace Charts { enum ChartLineFormattingType; } } } namespace Aspose{ namespace Cells{ namespace Drawing{ /// <summary> /// Encapsulates the object that represents the line format. /// </summary> class ASPOSE_CELLS_API ILine : public Aspose::Cells::System::Object { public: /// <summary> /// Specifies the compound line type /// </summary> virtual Aspose::Cells::Drawing::MsoLineStyle GetCompoundType()=0; /// <summary> /// Specifies the compound line type /// </summary> virtual void SetCompoundType(Aspose::Cells::Drawing::MsoLineStyle value)=0; /// <summary> /// Specifies the dash line type /// </summary> virtual Aspose::Cells::Drawing::MsoLineDashStyle GetDashType()=0; /// <summary> /// Specifies the dash line type /// </summary> virtual void SetDashType(Aspose::Cells::Drawing::MsoLineDashStyle value)=0; /// <summary> /// Specifies the ending caps. /// </summary> virtual Aspose::Cells::Drawing::LineCapType GetCapType()=0; /// <summary> /// Specifies the ending caps. /// </summary> virtual void SetCapType(Aspose::Cells::Drawing::LineCapType value)=0; /// <summary> /// Specifies the joining caps. /// </summary> virtual Aspose::Cells::Drawing::LineJoinType GetJoinType()=0; /// <summary> /// Specifies the joining caps. /// </summary> virtual void SetJoinType(Aspose::Cells::Drawing::LineJoinType value)=0; /// <summary> /// Specifies an arrowhead for the begin of a line. /// </summary> virtual Aspose::Cells::Drawing::MsoArrowheadStyle GetBeginType()=0; /// <summary> /// Specifies an arrowhead for the begin of a line. /// </summary> virtual void SetBeginType(Aspose::Cells::Drawing::MsoArrowheadStyle value)=0; /// <summary> /// Specifies an arrowhead for the end of a line. /// </summary> virtual Aspose::Cells::Drawing::MsoArrowheadStyle GetEndType()=0; /// <summary> /// Specifies an arrowhead for the end of a line. /// </summary> virtual void SetEndType(Aspose::Cells::Drawing::MsoArrowheadStyle value)=0; /// <summary> /// Specifies the length of the arrowhead for the begin of a line. /// </summary> virtual Aspose::Cells::Drawing::MsoArrowheadLength GetBeginArrowLength()=0; /// <summary> /// Specifies the length of the arrowhead for the begin of a line. /// </summary> virtual void SetBeginArrowLength(Aspose::Cells::Drawing::MsoArrowheadLength value)=0; /// <summary> /// Specifies the length of the arrowhead for the end of a line. /// </summary> virtual Aspose::Cells::Drawing::MsoArrowheadLength GetEndArrowLength()=0; /// <summary> /// Specifies the length of the arrowhead for the end of a line. /// </summary> virtual void SetEndArrowLength(Aspose::Cells::Drawing::MsoArrowheadLength value)=0; /// <summary> /// Specifies the width of the arrowhead for the begin of a line. /// </summary> virtual Aspose::Cells::Drawing::MsoArrowheadWidth GetBeginArrowWidth()=0; /// <summary> /// Specifies the width of the arrowhead for the begin of a line. /// </summary> virtual void SetBeginArrowWidth(Aspose::Cells::Drawing::MsoArrowheadWidth value)=0; /// <summary> /// Specifies the width of the arrowhead for the end of a line. /// </summary> virtual Aspose::Cells::Drawing::MsoArrowheadWidth GetEndArrowWidth()=0; /// <summary> /// Specifies the width of the arrowhead for the end of a line. /// </summary> virtual void SetEndArrowWidth(Aspose::Cells::Drawing::MsoArrowheadWidth value)=0; /// <summary> /// Represents the <see cref="System.Drawing.Color" /> /// of the line. /// </summary> virtual intrusive_ptr<Aspose::Cells::System::Drawing::Color> GetColor()=0; /// <summary> /// Represents the <see cref="System.Drawing.Color" /> /// of the line. /// </summary> virtual void SetColor(intrusive_ptr<Aspose::Cells::System::Drawing::Color> value)=0; /// <summary> /// Returns or sets the degree of transparency of the line as a value from 0.0 (opaque) through 1.0 (clear). /// </summary> virtual Aspose::Cells::System::Double GetTransparency()=0; /// <summary> /// Returns or sets the degree of transparency of the line as a value from 0.0 (opaque) through 1.0 (clear). /// </summary> virtual void SetTransparency(Aspose::Cells::System::Double value)=0; /// <summary> /// Represents the style of the line. /// </summary> virtual Aspose::Cells::Drawing::LineType GetStyle()=0; /// <summary> /// Represents the style of the line. /// </summary> virtual void SetStyle(Aspose::Cells::Drawing::LineType value)=0; /// <summary> /// Gets the <see cref="WeightType" /> /// of the line. /// </summary> virtual Aspose::Cells::Drawing::WeightType GetWeight()=0; /// <summary> /// Sets the <see cref="WeightType" /> /// of the line. /// </summary> virtual void SetWeight(Aspose::Cells::Drawing::WeightType value)=0; /// <summary> /// Gets the weight of the line in unit of points. /// </summary> virtual Aspose::Cells::System::Double GetWeightPt()=0; /// <summary> /// Sets the weight of the line in unit of points. /// </summary> virtual void SetWeightPt(Aspose::Cells::System::Double value)=0; /// <summary> /// Gets the weight of the line in uni of pixels. /// </summary> virtual Aspose::Cells::System::Double GetWeightPx()=0; /// <summary> /// Sets the weight of the line in uni of pixels. /// </summary> virtual void SetWeightPx(Aspose::Cells::System::Double value)=0; /// <summary> /// Gets format type. /// </summary> virtual Aspose::Cells::Charts::ChartLineFormattingType GetFormattingType()=0; /// <summary> /// Sets format type. /// </summary> virtual void SetFormattingType(Aspose::Cells::Charts::ChartLineFormattingType value)=0; /// <summary> /// Indicates whether the color of line is auotmatic assigned. /// </summary> virtual bool IsAutomaticColor()=0; /// <summary> /// Represents whether the line is visible. /// </summary> virtual bool IsVisible()=0; /// <summary> /// Represents whether the line is visible. /// </summary> virtual void SetVisible(bool value)=0; /// <summary> /// Indicates whether this line style is auto assigned. /// </summary> virtual bool IsAuto()=0; /// <summary> /// Indicates whether this line style is auto assigned. /// </summary> virtual void SetAuto(bool value)=0; /// <summary> /// Represents gradient fill. /// </summary> virtual intrusive_ptr<Aspose::Cells::Drawing::IGradientFill> GetIGradientFill()=0; }; } } }
db2b5dcddb911f960c0cf0d86a105efa5338abcc
b312fd00fdf4e629189b1e282d4cda4fd10b0752
/usespace/xmlconf-3.2/core/portmirrormgr.cc
8d14a2b534d15129c3580690b812c36496643eb0
[]
no_license
wfqGithubHome/dailycode
1ee7b2c9087f6de1a54988ea535a71eee7c9b980
4b893bda0aa2b2190ef00129b47cda2cc3cf03e7
refs/heads/master
2021-01-20T21:09:07.317993
2016-06-15T14:01:29
2016-06-15T14:01:29
59,886,894
0
0
null
null
null
null
UTF-8
C++
false
false
2,608
cc
#include "portmirror.h" #include "portmirrormgr.h" #include "../global.h" #include <sstream> namespace maxnet{ int PortMirrorMgr::max_bridge_id = 0; PortMirrorMgr::PortMirrorMgr(){ } PortMirrorMgr::~PortMirrorMgr(){ #if 1 PortMirror * rule = NULL; for(unsigned int i=0; i < node_list.size(); i++){ rule = (PortMirror *)node_list.at(i); delete rule; } node_list.clear(); #endif return; } int PortMirrorMgr::getMaxBridgeID() { return this->max_bridge_id; } int PortMirrorMgr::getBridgeIDbyName(std::string bridge_id_string) { int id; std::stringstream bridge_id; bridge_id << bridge_id_string; bridge_id >> id; if(id < 0 || id >= MAX_BRIDGE_ID) return 0; if(id > this->max_bridge_id) { this->max_bridge_id = id; } return id; } void PortMirrorMgr::setEnable(std::string bridge_id_string, int enable){ std::stringstream limit_num; int bridge_id = getBridgeIDbyName(bridge_id_string); if(bridge_id < 0 || bridge_id >= MAX_BRIDGE_ID) return; this->enable[bridge_id] = enable; } int PortMirrorMgr::getEnable(int bridge_id){ if(bridge_id < 0 || bridge_id >= MAX_BRIDGE_ID) return 0; return this->enable[bridge_id]; } void PortMirrorMgr::add(std::string name, std::string bridge_id, std::string src_addr, std::string dst_addr, std::string proto, std::string action, std::string comment,bool disabled){ PortMirror * rule = new PortMirror(); if(src_addr.compare("") == 0) { src_addr="any"; } if(dst_addr.compare("") == 0) { dst_addr="any"; } if(action.compare("") == 0 || (action.compare("in") != 0 && action.compare("out") != 0 && action.compare("all") != 0 &&action.compare("in_discard") != 0 && action.compare("out_discard") != 0 && action.compare("all_discard") != 0)) { action = "all"; } rule->setName(name); rule->setBridgeIDbyString(bridge_id); rule->setSrcAddr(src_addr); rule->setDstAddr(dst_addr); rule->setProto(proto); rule->setAction(action); rule->setComment(comment); rule->setGroup(false); rule->setDisabled(disabled); if(rule->isVaild()){ addNode(rule); } else{ delete rule; } return; } void PortMirrorMgr::output(){ #if 1 PortMirror * rule = NULL; std::cout << std::endl << "# port mirror rules, max bridge id: " << max_bridge_id << std::endl; for(int i = 0; i < max_bridge_id + 1; i++) { std::cout << "# ENABLE[" << i << "] = " << enable[i] << std::endl; } for(unsigned int i=0; i < node_list.size(); i++){ rule = (PortMirror *)node_list.at(i); rule->output(); } #endif return; } }
231d3d0b44dbc43b4415b200c5911d2230764aad
728de43d34e192c677916365696e96af5e992b19
/A-STD/src/FeatureCollector.h
99ce9ba2b88307e23552b1d58fe4017a6e288d93
[]
no_license
majineu/Parser
a8a8b497e51410f1c7739c83668a0e24c3f5f0d6
ed7548a7bfe72a57deebbee631eb555e161ee713
refs/heads/master
2020-05-18T06:14:10.149277
2015-06-06T08:08:37
2015-06-06T08:08:37
22,898,740
0
1
null
null
null
null
UTF-8
C++
false
false
1,566
h
#ifndef __FEATURE_COLLECTOR_H__ #define __FEATURE_COLLECTOR_H__ #include <map> #include <vector> #include <algorithm> #include "DepTree.h" #include "Pool.h" #include "State.h" #include "Template.h" using std::map; class CFeatureCollector { public: CFeatureCollector(bool insertMode);//, bool useDis); ~CFeatureCollector(); bool ReadTemplate(const string & strFile); void ExtractKernels(vector<int> &vKernels); void GetFeatures(vector<int> &vFIDs); bool SaveTemplateFile(const string &strPath); bool SaveFeatures(const string &strPath); bool LoadFeatures(const string &strPath); vector<_TPLT *> &GetTemps() {return m_vTemps;} _SENTENCE * GetSen() {return m_pSen;} bool GetMode() {return m_iMode;} bool Verbose() {return m_verbose;} void SetSen(_SENTENCE *pSen) {m_pSen = pSen, m_nSenLen = pSen->Length();} void SetState(CState *pStat) {m_pState = pStat;} void SetMode(bool insertMode) {m_iMode = insertMode; } void SetVerbose(bool v) {m_verbose = v;} void ResetMem() {m_pool.Recycle();} private: map<string, int> m_mapK2idx; // kernel to kernelID vector<string> m_kerVec; // kernel feature vector vector<_TPLT*> m_vTemps; bool m_iMode; // insert mode bool m_verbose; int m_nSenLen; int m_nKernel; int m_gID; CPool m_pool; _SENTENCE *m_pSen; CState *m_pState; static const int MAX_BUF_LEN = 256; static const wchar_t *pNull, *pSigEnd; }; #endif /*__FEATURE_COLLECTOR_H__*/
3666e4b501608526c78aeac2a24a6e9851d56824
99f2afe3d5091e1f88baa95cd8fcd99f991760b1
/tests/flt.cpp
5a7ed6a73b153aaabd4f4303a19b9a3b37fbcfad
[ "MIT" ]
permissive
dantamont/zorder_knn
18044ec7a809d3095b5ee30665e2810dc60607a3
a8f4cb9c41d7c903f5dd4374ea2219192a80b970
refs/heads/master
2023-05-27T10:20:43.557023
2021-05-22T19:59:17
2021-05-22T20:03:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,515
cpp
// This file is part of zorder_knn. // // Copyright(c) 2010, 2021 Sebastian Lipponer // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include <zorder_knn/less.hpp> #include <gtest/gtest.h> #include <cmath> #include <limits> TEST(FloatToUint, Zero) { EXPECT_EQ(zorder_knn::detail::FloatToUInt(0.0f), 0x0u); EXPECT_EQ(zorder_knn::detail::FloatToUInt(-0.0f), 0x80000000u); EXPECT_EQ(zorder_knn::detail::FloatToUInt(0.0), 0x0ll); EXPECT_EQ(zorder_knn::detail::FloatToUInt(-0.0), 0x8000000000000000ll); } TEST(FloatToUInt, Infinity) { constexpr auto inff = std::numeric_limits<float>::infinity(); EXPECT_EQ(zorder_knn::detail::FloatToUInt(inff), 0x7f800000u); EXPECT_EQ(zorder_knn::detail::FloatToUInt(-inff), 0xff800000u); constexpr auto infd = std::numeric_limits<double>::infinity(); EXPECT_EQ(zorder_knn::detail::FloatToUInt(infd), 0x7ff0000000000000ll); EXPECT_EQ(zorder_knn::detail::FloatToUInt(-infd), 0xfff0000000000000ll); } TEST(FloatToUInt, NaN) { auto nanf_uint = zorder_knn::detail::FloatToUInt( std::numeric_limits<float>::signaling_NaN()); EXPECT_GT(nanf_uint & 0x7fffffu, 0x0u); EXPECT_EQ(nanf_uint & 0x7f800000u, 0x7f800000u); auto nand_uint = zorder_knn::detail::FloatToUInt( std::numeric_limits<double>::signaling_NaN()); EXPECT_GT(nand_uint & 0xfffffffffffffll, 0x0u); EXPECT_EQ(nand_uint & 0x7ff0000000000000ll, 0x7ff0000000000000llu); } TEST(FloatExp, PowerOfTwo) { for (int exp(-126); exp < 128; ++exp) { auto f_uint = zorder_knn::detail::FloatToUInt(static_cast<float>( std::pow(2.0f, exp))); EXPECT_EQ(zorder_knn::detail::FloatExp(f_uint), exp); } for (int exp(-1022); exp < 1024; ++exp) { auto d_uint = zorder_knn::detail::FloatToUInt( std::pow(2.0, exp)); EXPECT_EQ(zorder_knn::detail::FloatExp(d_uint), exp); } } TEST(FloatSig, OneOverPowerOfTwo) { for (int i(23); i > 0; --i) { auto f_uint = zorder_knn::detail::FloatToUInt(1.0f + static_cast<float>( std::pow(2.0f, -i))); EXPECT_EQ(zorder_knn::detail::FloatSig(f_uint), 0x1u << (23 - i)); } for (int i(52); i > 0; --i) { auto d_uint = zorder_knn::detail::FloatToUInt(1.0f + std::pow(2.0, -i)); EXPECT_EQ(zorder_knn::detail::FloatSig(d_uint), 0x1ll << (52 - i)); } }
9e9144dfa14abd5fc0701666e74b6d1d3033f717
c95fea72ffeaa3faba64c6837fc61928cf63e568
/src/octomap_to_table.cpp
d366ef62e730358bf22ed6a6f0ef7c68b5b34c5a
[]
no_license
kingjin94/filter_octomap
871b2c99025e0cbd1ca8f469a91f9b512f66e763
0bb079bf49ab630b203819834d6de2910b588274
refs/heads/master
2020-07-01T07:13:12.095706
2019-11-13T14:03:06
2019-11-13T14:03:06
201,085,744
0
0
null
null
null
null
UTF-8
C++
false
false
15,857
cpp
/* * Copyright (C) 2008, Morgan Quigley and Willow Garage, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ // %Tag(FULLTEXT)% #include "ros/ros.h" //#include "std_msgs/String.h" #include "octomap_msgs/Octomap.h" #include <octomap/octomap.h> #include <octomap/OcTree.h> #include <octomap_msgs/conversions.h> // deserialize octreemsg withh msgToMap #include <math.h> #include "moveit_msgs/PlanningScene.h" #include <stack> #include "std_msgs/Float64.h" #include <assert.h> #include <iostream> #include "filter_octomap/table.h" #include <assert.h> #include <algorithm> #include <octomap/ColorOcTree.h> #define COLOR_OCTOMAP_SERVER 1 #define TABLE_THRESHOLD 250 /* Debuging*/ //#define DEBUG_COUT 1 #define DEBUG 1 #ifdef DEBUG #include "visualization_msgs/Marker.h" #include "geometry_msgs/Point.h" #define STEPS_X 75 // Right now we have 50 Steps / m #define STEPS_Y 150 #define STEPS_Z 100 #define START_X 0. // in m #define START_Y -1.5 // in m #define START_Z -0.1 // in m #define STEP_SIZE 0.02 // Size of cells on lowest level ros::Publisher vis_pub; visualization_msgs::Marker table_marker; #else /*Deploy*/ #define STEPS_X 75 // Right now we have 50 Steps / m #define STEPS_Y 150 #define STEPS_Z 100 #define START_X 0. // in m #define START_Y -1.5 // in m #define START_Z -0.1 // in m #define STEP_SIZE 0.02 // Size of cells on lowest level #endif ros::Publisher tablePublisher; #include "octomap_to_x_helper.hxx" inline double tableScore(RGBVoxelgrid& map, VoxelIndex index, const Size3D size) { // Returns tableness at position (x,y,z) in map // Tableness is determined in a 5x5 neighbourhood // The top is assumed in positive z direction // A table is free above the surface (-2. for z+1 and z+2 // occupied on the surface (3.5 for z) // unknown bellow the surface (0 for z-1) // and occupied on the lower side (3.5 for z-2) double result = 0; //std::cout << "Am at " << index << " with map of size " << size << std::endl; size_t neg_x = std::min(index.x, (size_t) 2); size_t pos_x = std::min(size.x-index.x, (size_t) 2); size_t neg_y = std::min(index.y, (size_t) 2); size_t pos_y = std::min(size.y-index.y, (size_t) 2); //std::cout << "Wanted offsets: " << neg_x << "," << pos_x << "," << neg_y << "," << pos_y << std::endl; for(int i = index.x-neg_x; i < index.x+pos_x; i++) // over x { for(int j = index.y-neg_y; j < index.y+pos_y; j++) // over y { //std::cout << "Looking at " << i << "," << j << std::endl; if(index.z>=2) result += 3.5*std::get<0>(map(i,j,index.z-2)); result += 3.5*std::get<0>(map(i,j,index.z)); if(index.z<size.z-1) result += -2.*std::get<0>(map(i,j,index.z+1)); if(index.z<size.z-2) result += -2.*std::get<0>(map(i,j,index.z+2)); } } return result; } void floodfill(Array3D<double>& map, int x, int y, int z, Array3D<int>& explored, double threshold) { //// Marks all places in explored true which are above the threshold in map and are connected to the first x,y,z via 6-Neighbourhood //#ifdef DEBUG_COUT //std::cout << "Starting at " << x << "," << y << "," << z << "\n"; //#endif //std::stack<std::tuple<int,int,int>> posToLookAt; //posToLookAt.emplace(x,y,z); //while(!posToLookAt.empty()) { //std::tuple<int,int,int> here = posToLookAt.top(); //double x = std::get<0>(here); //double y = std::get<1>(here); //double z = std::get<2>(here); //#ifdef DEBUG_COUT //std::cout << "\nStack size: " << posToLookAt.size() << "\n"; //std::cout << "Looking at " << x << "," << y << "," << z << "\n"; //#endif //posToLookAt.pop(); //if(explored(x,y,z)!=0) continue; //else { //explored(x,y,z) = 1; //#ifdef DEBUG_COUT //std::cout << "Is new; set to " << explored(x,y,z) << "; local tableness: " << map(x,y,z) << "\n"; //#endif //// Test neighbours and call floodfill if tableness high enough //if(x>0) { //if(map(x-1,y,z) > threshold) { //posToLookAt.emplace(x-1,y,z); //#ifdef DEBUG_COUT //std::cout << "-x inserted "; //#endif //} //} //if(y>0) { //if(map(x,y-1,z) > threshold) { //posToLookAt.emplace(x,y-1,z); //#ifdef DEBUG_COUT //std::cout << "-y inserted "; //#endif //} //} //if(z>0) { //if(map(x,y,z-1) > threshold) { //posToLookAt.emplace(x,y,z-1); //#ifdef DEBUG_COUT //std::cout << "-z inserted "; //#endif //} //} //if(x<STEPS_X-4-1) { //if(map(x+1,y,z) > threshold) { //posToLookAt.emplace(x+1,y,z); //#ifdef DEBUG_COUT //std::cout << "+x inserted "; //#endif //} //} //if(y<STEPS_Y-4-1) { //if(map(x,y+1,z) > threshold) { //posToLookAt.emplace(x,y+1,z); //#ifdef DEBUG_COUT //std::cout << "+y inserted "; //#endif //} //} //if(z<STEPS_Z-4-1) { //if(map(x,y,z+1) > threshold) { //posToLookAt.emplace(x,y,z+1); //#ifdef DEBUG_COUT //std::cout << "+z inserted "; //#endif //} //} //} //} } double generateTableMap(Array3D<double>& map, Array3D<double>& tableness, int& max_i, int& max_j, int& max_k) { //double maxTableness = -100000; //for(int i = 0; i < STEPS_X-4; i++) // over x //{ //#ifdef DEBUG_COUT //std::cout << "\nj | i: "; //std::cout << i; //std::cout << "\n"; //#endif //for(int j = 0; j < STEPS_Y-4; j++) // over y //{ //#ifdef DEBUG_COUT //std::cout << std::setw(3) << j; //std::cout << ": "; //#endif //for(int k = 0; k < STEPS_Z-4; k++) // over z //{ //tableness(i,j,k) = convolveOneTable(map, i+2, j+2, k+2); //if(tableness(i,j,k) > maxTableness) { //maxTableness = tableness(i,j,k); //max_i = i; //max_j = j; //max_k = k; //} //#ifdef DEBUG_COUT //std::cout << std::setw( 6 ) << std::setprecision( 4 ) << tableness(i,j,k); //std::cout << " "; //#endif //} //#ifdef DEBUG_COUT //std::cout << "\n"; //#endif //} //} //std::cout << "Best tableness (" << maxTableness << ") found at (" << max_i << "," << max_j << "," << max_k << ")\n"; //return maxTableness; } void findTable(RGBVoxelgrid& map, const Size3D& size) { // Where in map could tables be? VoxelindexToScore candidates; generateCandidates(map, candidates, size, tableScore, TABLE_THRESHOLD); #ifdef DEBUG // Display table candidates resetMarker(); table_marker.type = visualization_msgs::Marker::POINTS; table_marker.id = 0; for (auto& it: candidates) { geometry_msgs::Point p; p.x = START_X + it.first.x * STEP_SIZE; p.y = START_Y + it.first.y * STEP_SIZE; p.z = START_Z + it.first.z * STEP_SIZE; table_marker.points.push_back(p); } table_marker.ns = "Candidates"; table_marker.header.stamp = ros::Time(); vis_pub.publish( table_marker ); std::cout << "Table markers ..."; #endif double best_table_score = -1.; VoxelList best_table; octomath::Vector3 best_centroid(0.,0.,0.); octomath::Vector3 best_min(1000.,1000.,1000.); octomath::Vector3 best_max(-1000.,-1000.,-1000.); while(!candidates.empty()) { std::cout << "Best node at: " << getMax(candidates) << " with score " << candidates[getMax(candidates)] << std::endl; VoxelList table; floodfill(candidates, getMax(candidates), table); //double min_x=1000, max_x=-1000, min_y=1000, max_y=-1000, min_z=1000, max_z=-1000; octomath::Vector3 centroid(0.,0.,0.); octomath::Vector3 min(1000.,1000.,1000.); octomath::Vector3 max(-1000.,-1000.,-1000.); double score = 0; u_int32_t N = 0; for (auto& it: table) { // Go over this table candidate double x = START_X+STEP_SIZE*(it.x-0.5); double y = START_Y+STEP_SIZE*(it.y-0.5); double z = START_Z+STEP_SIZE*(it.z-0.5); octomath::Vector3 here(x,y,z); N++; centroid+=here; if(x < min.x()) min.x() = x; if(y < min.y()) min.y() = y; if(z < min.z()) min.z() = z; if(x > max.x()) max.x() = x; if(y > max.y()) max.y() = y; if(z > max.z()) max.z() = z; score += tableScore(map, it, size); } centroid/=N; #ifdef DEBUG std::cout << "Found " << N << " table points\n"; std::cout << "Table middle at: " << centroid << "\n"; std::cout << "Minima: (" << min.x() << "," << min.y() << "," << min.z() << "); maxima: (" << max.x() << "," << max.y() << "," << max.z() << ")\n"; std::cout << "Table score: " << score << "\n"; #endif if(score > best_table_score) { best_table_score = score; best_table = table; best_centroid = centroid; best_min = min; best_max = max; } } #ifdef DEBUG std::cout << "============\n" << "Best Table: \n"; std::cout << "Table middle at: " << best_centroid << "\n"; std::cout << "Minima: " << best_min << "; maxima: "<< best_max << "\n"; std::cout << "Table score: " << best_table_score << "\n"; // Display best table points resetMarker(); table_marker.type = visualization_msgs::Marker::POINTS; table_marker.id = 1; for (auto& it: best_table) { geometry_msgs::Point p; p.x = START_X + it.x * STEP_SIZE; p.y = START_Y + it.y * STEP_SIZE; p.z = START_Z + it.z * STEP_SIZE; table_marker.points.push_back(p); } table_marker.ns = "Best Table points"; table_marker.header.stamp = ros::Time(); vis_pub.publish( table_marker ); resetMarker(); table_marker.type = visualization_msgs::Marker::CUBE; table_marker.id = 2; table_marker.scale.x = best_max.x() - best_min.x(); table_marker.scale.y = best_max.y() - best_min.y(); table_marker.scale.z = best_max.z() - best_min.z(); table_marker.pose.position.x = (best_max.x() + best_min.x())/2; table_marker.pose.position.y = (best_max.y() + best_min.y())/2; table_marker.pose.position.z = (best_max.z() + best_min.z())/2; table_marker.header.stamp = ros::Time(); table_marker.ns = "SurfaceCube"; vis_pub.publish( table_marker ); #endif // plane fitting, assuming n_z = 1 (should be the case for a table), see: https://www.ilikebigbits.com/2015_03_04_plane_from_points.html double xx=0, xy=0, xz=0, yy=0, yz=0, zz=0; for (auto& it: best_table) { octomath::Vector3 r(START_X + it.x * STEP_SIZE, START_Y + it.y * STEP_SIZE, START_Z + it.z * STEP_SIZE); r = r - best_centroid; xx += r.x() * r.x(); xy += r.x() * r.y(); xz += r.x() * r.z(); yy += r.y() * r.y(); yz += r.y() * r.z(); zz += r.z() * r.z(); } double det_z = xx*yy - xy*xy; octomath::Vector3 normal = octomath::Vector3(xy*yz - xz*yy, xy*xz - yz*xx, det_z); normal.normalize(); std::cout << "Table normal: " << normal << "\n"; filter_octomap::table table_msg; table_msg.header.stamp = ros::Time::now(); table_msg.header.frame_id = "world"; table_msg.centroid_position.x = best_centroid.x(); table_msg.centroid_position.y = best_centroid.y(); table_msg.centroid_position.z = best_centroid.z(); table_msg.normal.x = normal.x(); table_msg.normal.y = normal.y(); table_msg.normal.z = normal.z(); table_msg.max.x = best_max.x(); table_msg.max.y = best_max.y(); table_msg.max.z = best_max.z(); table_msg.min.x = best_min.x(); table_msg.min.y = best_min.y(); table_msg.min.z = best_min.z(); table_msg.score = best_table_score; tablePublisher.publish(table_msg); } /** * A subscriber to octomap msg, following https://github.com/OctoMap/octomap_rviz_plugins/blob/kinetic-devel/src/occupancy_grid_display.cpp */ // %Tag(CALLBACK)% void chatterCallback(const octomap_msgs::Octomap::ConstPtr& msg) { // Test if right message type ROS_INFO("Received message number %d", msg->header.seq); if(!((msg->id == "OcTree")||(msg->id == "ColorOcTree"))) { ROS_INFO("Non supported octree type"); return; } // creating octree octomap::ColorOcTree* octomap = NULL; octomap::AbstractOcTree* tree = octomap_msgs::msgToMap(*msg); if (tree){ #ifdef COLOR_OCTOMAP_SERVER octomap = dynamic_cast<octomap::ColorOcTree*>(tree); #else octomap = dynamic_cast<octomap::OcTree*>(tree); #endif if(!octomap){ ROS_INFO("Wrong octomap type. Use a different display type."); return; } } else { ROS_INFO("Failed to deserialize octree message."); return; } const Size3D size = {STEPS_X+1, STEPS_Y+1, STEPS_Z+1}; RGBVoxelgrid grid(size, std::make_tuple(-2., 0, 0, 0)); // Default to known occupied octomath::Vector3 lower_vertex(START_X, START_Y, START_Z); // Define boundary of cube to search in octomath::Vector3 upper_vertex(START_X+STEPS_X*STEP_SIZE, START_Y+STEPS_Y*STEP_SIZE, START_Z+STEPS_Z*STEP_SIZE); changeToGrid(octomap, grid, lower_vertex, upper_vertex); findTable(grid, size); // free memory delete tree; } int main(int argc, char **argv) { //// Load old map //octomap::OcTree* octomap = NULL; //octomap::AbstractOcTree* tree = octomap::AbstractOcTree::read("/home/catkin_ws/test.ot"); //if (tree){ //octomap = dynamic_cast<octomap::OcTree*>(tree); //if(!octomap){ //ROS_INFO("Wrong octomap type. Use a different display type."); //return -1; //} //} else { //ROS_INFO("Failed to deserialize octree message."); //return -1; //} //// call processor //Array3D<double> grid(STEPS_X, STEPS_Y, STEPS_Z); //changeToGrid(octomap, grid); //findTable(grid); //// terminate //return 0; ros::init(argc, argv, "findTable"); ros::NodeHandle n; ROS_INFO("Node searching for table init"); #ifdef DEBUG // see http://wiki.ros.org/rviz/DisplayTypes/Marker#Example_Usage_.28C.2B-.2B-.2BAC8-roscpp.29 vis_pub = n.advertise<visualization_msgs::Marker>( "debug/table_marker", 0, true); table_marker; table_marker.header.frame_id = "world"; table_marker.ns = "my_namespace"; table_marker.id = 0; table_marker.type = visualization_msgs::Marker::POINTS; table_marker.action = visualization_msgs::Marker::ADD; table_marker.pose.orientation.x = 0.0; table_marker.pose.orientation.y = 0.0; table_marker.pose.orientation.z = 0.0; table_marker.pose.orientation.w = 1.0; table_marker.scale.x = 0.01; table_marker.scale.y = 0.01; table_marker.scale.z = 0.01; table_marker.color.a = 1.0; // Don't forget to set the alpha! table_marker.color.r = 0.0; table_marker.color.g = 1.0; table_marker.color.b = 0.0; table_marker.lifetime = ros::Duration(10.); #endif tablePublisher = n.advertise<filter_octomap::table>("octomap_new/table", 10, true); ROS_INFO("Node searching for table publisher done"); ros::Subscriber sub = n.subscribe("/octomap_full", 10, chatterCallback); ROS_INFO("Node searching for table sub done"); ros::spin(); return 0; }
057fe32779e96ef78dd3af5e3814f605333a2076
29f86350525cf6d81113f103906e39ae9d655d5c
/Data_Structures/Stack_and_Queue/Down_to_Zero_II.cpp
06e5cd1461b14f5a07532daadd7eadd3478083d4
[]
no_license
mkltaneja/HackerRank
a6d3155c1396339f4964bd39d1ac4cc44a9edf84
a55791b0cb4c87d48fc789be21b279b51f71a931
refs/heads/master
2022-12-06T14:39:59.965792
2020-08-19T19:27:27
2020-08-19T19:27:27
278,747,088
0
0
null
null
null
null
UTF-8
C++
false
false
2,976
cpp
#include <bits/stdc++.h> using namespace std; /* * Complete the downToZero function below. */ // Method 1 (using DP) --> O(n*sqrt(n)) // TLE void operations(int n, vector<int> &dp) { for (int n=2;n<dp.size();n++) { dp[n] = dp[n-1] + 1; for (int i=sqrt(n);i>=2;i--) { if (n % i == 0) { dp[n] = min(dp[n], dp[n/i]+1); } } } } int downToZero(int n) { vector<int> dp(n+1, 0); dp[1] = 1; operations(n, dp); return dp[n]; } // OR // Method 2 (using DP) --> O(n*logn) // TLE void operations(int N, vector<int> &dp) { for (int n=2;n<dp.size();n++) { dp[n] = min(dp[n], dp[n-1] + 1); for (int j = 1; j <= n && n*j <= N; j++) dp[n*j] = min(dp[n*j], dp[n]+1); } } int downToZero(int n) { vector<int> dp(n+1, INT_MAX); dp[1] = 1; operations(n, dp); return dp[n]; } // Method 3 (using queue and map - level wise) // TLE int downToZero(int n) { if (n == 0) return 0; if (n == 1) return 1; queue<int> que; que.push(n); unordered_map<int, bool> m; m[n] = true; int level = 0; while (!que.empty()) { int size = que.size(); while (size--) { int top = que.front(); que.pop(); if (top == 2) return level + 2; if (!m[top-1]) que.push(top-1); for (int i = 2; i*i <= top; i++) { if (top % i == 0) { int gfac = top / i; if (!m[gfac]) que.push(gfac); } } } level++; } return 0; } // Method 4 (using queue and array) // AC int downToZero(int n) { if (n == 0) return 0; if (n == 1) return 1; vector<int> dist(n+1, 0); dist[n] = 1; queue<int> que; que.push(n); while (!que.empty()) { int top = que.front(); que.pop(); if (top == 2) return dist[top] + 1; if (dist[top - 1] == 0) { dist[top-1] = dist[top] + 1; que.push(top-1); } for (int i = 2; i*i <= top; i++) { if (top % i == 0) { int gfac = top / i; if (dist[gfac] == 0) { dist[gfac] = dist[top] + 1; que.push(gfac); } } } } return 0; } int main() { ofstream fout(getenv("OUTPUT_PATH")); int q; cin >> q; cin.ignore(numeric_limits<streamsize>::max(), '\n'); for (int q_itr = 0; q_itr < q; q_itr++) { int n; cin >> n; cin.ignore(numeric_limits<streamsize>::max(), '\n'); int result = downToZero(n); fout << result << "\n"; } fout.close(); return 0; }
d7e9b45d7f587b673e5cbf9172cdd9e70a82d542
63ec994c38f21ef5eb7ab28473b65c3fb9be4144
/src/Program.cpp
c64ac0066bcb9ab18734ae31005fe2d0c20c643c
[]
no_license
moneil113/Breaker
a6c0466484d09e0bbdd968fd6c6fd42bb21e03c8
60c5d615dce3d037062587947adcedb910080977
refs/heads/master
2020-08-30T20:57:48.438193
2017-04-17T22:32:57
2017-04-17T22:32:57
94,391,951
0
0
null
null
null
null
UTF-8
C++
false
false
2,517
cpp
#include "Program.h" #include <iostream> #include <cassert> #include "GLSL.h" using namespace std; Program::Program() : vShaderName(""), fShaderName(""), pid(0), verbose(true) { } Program::~Program() { } void Program::setShaderNames(const string &v, const string &f) { vShaderName = v; fShaderName = f; } bool Program::init() { GLint rc; // Create shader handles GLuint VS = glCreateShader(GL_VERTEX_SHADER); GLuint FS = glCreateShader(GL_FRAGMENT_SHADER); // Read shader sources const char *vshader = GLSL::textFileRead(vShaderName.c_str()); const char *fshader = GLSL::textFileRead(fShaderName.c_str()); glShaderSource(VS, 1, &vshader, NULL); glShaderSource(FS, 1, &fshader, NULL); // Compile vertex shader glCompileShader(VS); glGetShaderiv(VS, GL_COMPILE_STATUS, &rc); if(!rc) { if(isVerbose()) { GLSL::printShaderInfoLog(VS); cout << "Error compiling vertex shader " << vShaderName << endl; } return false; } // Compile fragment shader glCompileShader(FS); glGetShaderiv(FS, GL_COMPILE_STATUS, &rc); if(!rc) { if(isVerbose()) { GLSL::printShaderInfoLog(FS); cout << "Error compiling fragment shader " << fShaderName << endl; } return false; } // Create the program and link pid = glCreateProgram(); glAttachShader(pid, VS); glAttachShader(pid, FS); glLinkProgram(pid); glGetProgramiv(pid, GL_LINK_STATUS, &rc); if(!rc) { if(isVerbose()) { GLSL::printProgramInfoLog(pid); cout << "Error linking shaders " << vShaderName << " and " << fShaderName << endl; } return false; } GLSL::checkError(GET_FILE_LINE); return true; } void Program::bind() { glUseProgram(pid); } void Program::unbind() { glUseProgram(0); } void Program::addAttribute(const string &name) { attributes[name] = glGetAttribLocation(pid, name.c_str()); } void Program::addUniform(const string &name) { uniforms[name] = glGetUniformLocation(pid, name.c_str()); } GLint Program::getAttribute(const string &name) const { map<string,GLint>::const_iterator attribute = attributes.find(name.c_str()); if(attribute == attributes.end()) { if(isVerbose()) { cout << name << " is not an attribute variable" << endl; } return -1; } return attribute->second; } GLint Program::getUniform(const string &name) const { map<string,GLint>::const_iterator uniform = uniforms.find(name.c_str()); if(uniform == uniforms.end()) { if(isVerbose()) { cout << name << " is not a uniform variable" << endl; } return -1; } return uniform->second; }
82ddcf1a2a0cfb394e59ab01d3ff8b10ca391c54
cb6fca75b78ef4c7140378713a27a8d26ed5f5ac
/397/b/b.cpp
2d82f1372e4a75be7626787ddfe551df1c959da8
[]
no_license
shpsi/uva
3d89466f54b81bc0411458413a41d0e3cd93ce57
647a0d0f0de3aa1f13b91e9060e2738d128a879e
refs/heads/master
2020-08-10T16:21:50.617613
2020-02-03T10:01:59
2020-02-03T10:01:59
214,375,814
1
1
null
null
null
null
UTF-8
C++
false
false
1,309
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef pair<string, int> psi; typedef pair<string, string> pss; #define pb push_back #define PI acos(-1.0) #define EPS 1e-4 #define mp make_pair #define all(x) x.begin(), x.end() #define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) #define fout(S,x) cout<<fixed<<setprecision(x)<<(S)<<endl #define present(c,x) ((c).find(x) != (c).end()) #define T() ll t;cin>>t;while(t--) #define mem(input,b) memset(input,b,sizeof(input)) #define ff first #define ss second #define fread(input) freopen("input","r",stdin) #define fwrite(b) freopen("b","w",stdout) #define trace(...) __f(#__VA_ARGS__, __VA_ARGS__) #define FOREACH(i,c) for (__typeof ((c).begin()) i = (c).begin() ; i != (c).end() ; i++) template <typename Arg1> void __f(const char* name, Arg1&& arg1){ cerr << name << " : " << arg1 << std::endl; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args){ const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...); } int main(){ fastio; int t,n,l,r; for(cin>>t;t--;) cin>>n>>l>>r,cout<<((n/l*1LL*r<n)?"No":"Yes")<<endl; return 0; }
9f7cab4706c1e220f28d90c6a699ef9f6b42be5b
57e2faf5f1df52fd0992b16471437a402000f866
/Codes(since 12-01)/[2018湖南集训]gift.cpp
4a3561fa8159fe0cde6c21822cce7b28d391059b
[]
no_license
1592063346/Codes
694dac4ac8c2e7c9a068d0b517e5e895962d1c48
711782c5e1c5d329d306f7e864c1d3d3e2af388c
refs/heads/master
2020-04-13T17:15:14.784201
2019-06-29T02:46:18
2019-06-29T02:46:18
163,342,851
0
0
null
null
null
null
UTF-8
C++
false
false
3,373
cpp
#include<bits/stdc++.h> using namespace std; const int N = 2345, mod = 998244353; void add(int& x, int y) { x += y; if (x >= mod) { x -= mod; } } int mul(int x, int y) { return (long long) x * y % mod; } int n, a[N], b[N], pa[N], pb[N], binom[N][N], s[N][N], fac[N], f[N], g[N], h[N], result[N], new_result[N]; bool visita[N], visitb[N]; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n; for (int i = 1; i <= n; ++i) { cin >> a[i]; pa[a[i]] = i; } for (int i = 1; i <= n; ++i) { cin >> b[i]; pb[b[i]] = i; } int x = 0, y = 0, z = 0, w = 0; for (int i = 1; i <= n; ++i) { if (!a[i] && !b[i]) { ++z; } else if (!visita[i] && !visitb[i]) { bool foo, bar, loop = false; int j = i; while (1) { if (a[j]) { if (visita[j]) { loop = true; break; } visita[j] = true; if (pb[a[j]]) { visitb[pb[a[j]]] = true; j = pb[a[j]]; } else { foo = true; break; } } else { foo = false; break; } } if (loop) { ++w; continue; } j = i; while (1) { if (b[j]) { visitb[j] = true; if (pa[b[j]]) { visita[pa[b[j]]] = true; j = pa[b[j]]; } else { bar = true; break; } } else { bar = false; break; } } if (!b[i]) { if (foo) { ++y; } else { ++z; } } else if (!a[i]) { if (bar) { ++x; } else { ++z; } } else { if (!foo && !bar) { ++z; } if (foo && !bar) { ++y; } if (!foo && bar) { ++x; } } } } binom[0][0] = s[0][0] = fac[0] = 1; for (int i = 1; i <= n; ++i) { fac[i] = mul(fac[i - 1], i); binom[i][0] = 1; for (int j = 1; j <= i; ++j) { binom[i][j] = (binom[i - 1][j] + binom[i - 1][j - 1]) % mod; s[i][j] = (s[i - 1][j - 1] + mul(s[i - 1][j], i - 1)) % mod; } } for (int i = 0; i <= x; ++i) { for (int j = i; j <= x; ++j) { add(f[i], mul(mul(binom[x][j], s[j][i]), x - j ? mul(binom[x - j + z - 1][x - j], fac[x - j]) : 1)); } } for (int i = 0; i <= y; ++i) { for (int j = i; j <= y; ++j) { add(g[i], mul(mul(binom[y][j], s[j][i]), y - j ? mul(binom[y - j + z - 1][y - j], fac[y - j]) : 1)); } } for (int i = 0; i <= z; ++i) { h[i] = mul(fac[z], s[z][i]); } memset(new_result, 0, sizeof new_result); for (int i = 0; i <= x; ++i) { result[i] = f[i]; for (int j = 0; j <= y; ++j) { add(new_result[i + j], mul(result[i], g[j])); } } memcpy(result, new_result, sizeof new_result); memset(new_result, 0, sizeof new_result); for (int i = 0; i <= x + y; ++i) { for (int j = 0; j <= z; ++j) { add(new_result[i + j], mul(result[i], h[j])); } } for (int i = 0; i < n; ++i) { cout << (n - i - w >= 0 ? new_result[n - i - w] : 0) << " \n"[i + 1 == n]; } return 0; }
17e44018e1b17882309eab43774c816705d26583
ec4aafac303320d3d86c30766e28980598e338eb
/Source/main.cpp
2f5b1009c145df1e386e19c506677245798d23df
[]
no_license
brianwong1103/Portable-Text-Editor
c51d61aa3f47d1a3a274e7f8cbf7daba3dc452b1
a58cef9f9579f6dbda7594e9fef26a6eb330c3fe
refs/heads/master
2020-03-19T16:10:32.891024
2018-06-16T12:35:22
2018-06-16T12:35:22
136,703,792
0
0
null
null
null
null
BIG5
C++
false
false
5,346
cpp
#include <windows.h> #include "main.h" BOOL LoadFile(HWND hEdit, LPSTR pszFileName) { HANDLE hFile; BOOL bSuccess = FALSE; hFile = CreateFile(pszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0); if(hFile != INVALID_HANDLE_VALUE) { DWORD dwFileSize; dwFileSize = GetFileSize(hFile, NULL); if(dwFileSize != 0xFFFFFFFF) { LPSTR pszFileText; pszFileText = (LPSTR)GlobalAlloc(GPTR, dwFileSize + 1); if(pszFileText != NULL) { DWORD dwRead; if(ReadFile(hFile, pszFileText, dwFileSize, &dwRead, NULL)) { pszFileText[dwFileSize] = 0; // Null terminator if(SetWindowText(hEdit, pszFileText)) bSuccess = TRUE; // It worked! } GlobalFree(pszFileText); } } CloseHandle(hFile); } return bSuccess; } BOOL SaveFile(HWND hEdit, LPSTR pszFileName) { HANDLE hFile; BOOL bSuccess = FALSE; hFile = CreateFile(pszFileName, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if(hFile != INVALID_HANDLE_VALUE) { DWORD dwTextLength; dwTextLength = GetWindowTextLength(hEdit); if(dwTextLength > 0) { LPSTR pszText; pszText = (LPSTR)GlobalAlloc(GPTR, dwTextLength + 1); if(pszText != NULL) { if(GetWindowText(hEdit, pszText, dwTextLength + 1)) { DWORD dwWritten; if(WriteFile(hFile, pszText, dwTextLength, &dwWritten, NULL)) bSuccess = TRUE; } GlobalFree(pszText); } } CloseHandle(hFile); } return bSuccess; } BOOL DoFileOpenSave(HWND hwnd, BOOL bSave) { OPENFILENAME ofn; char szFileName[MAX_PATH]; ZeroMemory(&ofn, sizeof(ofn)); szFileName[0] = 0; ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = hwnd; ofn.lpstrFilter = "布萊恩文字檔案\Brian Text Format (*.bwt)\0*.bwt\0普通檔案格式\Normal Text File (*.txt)\0*.txt\0隱藏RTF/Secret RTF (*.rtf)\0*.rtf\0\0"; ofn.lpstrFile = szFileName; ofn.nMaxFile = MAX_PATH; ofn.lpstrDefExt = "txt"; if(bSave) { ofn.Flags = OFN_EXPLORER|OFN_PATHMUSTEXIST|OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT; if(GetSaveFileName(&ofn)) { if(!SaveFile(GetDlgItem(hwnd, IDC_MAIN_TEXT), szFileName)) { MessageBox(hwnd, "Save file failed.", "Error",MB_OK|MB_ICONEXCLAMATION); return FALSE; } } } else { ofn.Flags = OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_HIDEREADONLY; if(GetOpenFileName(&ofn)) { if(!LoadFile(GetDlgItem(hwnd, IDC_MAIN_TEXT), szFileName)) { MessageBox(hwnd, "Load of file failed.", "Error",MB_OK|MB_ICONEXCLAMATION); return FALSE; } } } return TRUE; } LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch(Message) { case WM_CREATE: CreateWindow("EDIT", "",WS_CHILD|WS_VISIBLE|WS_HSCROLL|WS_VSCROLL|ES_MULTILINE|ES_WANTRETURN,CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,hwnd, (HMENU)IDC_MAIN_TEXT, GetModuleHandle(NULL), NULL); SendDlgItemMessage(hwnd, IDC_MAIN_TEXT, WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT), MAKELPARAM(TRUE,0)); break; case WM_SIZE: if(wParam != SIZE_MINIMIZED) MoveWindow(GetDlgItem(hwnd, IDC_MAIN_TEXT), 0, 0, LOWORD(lParam),HIWORD(lParam), TRUE); break; case WM_SETFOCUS: SetFocus(GetDlgItem(hwnd, IDC_MAIN_TEXT)); break; case WM_COMMAND: switch(LOWORD(wParam)) { case CM_FILE_OPEN: DoFileOpenSave(hwnd, FALSE); break; case CM_FILE_SAVEAS: DoFileOpenSave(hwnd, TRUE); break; case CM_FILE_EXIT: PostMessage(hwnd, WM_CLOSE, 0, 0); break; case CM_ABOUT: MessageBox (NULL, "File Editor for Windows!\nCreated using the Win32 API" , "About...", 0); break; case CM_LINK: system("start https://brianwong1103.blogspot.com"); break; case CM_DLLWS: system("start https://github.download"); break; } break; case WM_CLOSE: DestroyWindow(hwnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, Message, wParam, lParam); } return 0; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX wc; HWND hwnd; MSG Msg; wc.cbSize = sizeof(WNDCLASSEX); wc.style = 0; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszMenuName = "MAINMENU"; wc.lpszClassName = "WindowClass"; wc.hIconSm = LoadIcon(hInstance,"A"); /* A is name used by project icons */ if(!RegisterClassEx(&wc)) { MessageBox(0,"Window Registration Failed!","Error!",MB_ICONEXCLAMATION|MB_OK|MB_SYSTEMMODAL); return 0; } hwnd = CreateWindowEx(WS_EX_CLIENTEDGE,"WindowClass","便攜式文件編輯工具/Protable Text Edit Tool Ver.1.0",WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 320,240, NULL, NULL, hInstance, NULL); if(hwnd == NULL) { MessageBox(0, "Window Creation Failed!", "Error!",MB_ICONEXCLAMATION|MB_OK|MB_SYSTEMMODAL); return 0; } ShowWindow(hwnd,1); UpdateWindow(hwnd); while(GetMessage(&Msg, NULL, 0, 0) > 0) { TranslateMessage(&Msg); DispatchMessage(&Msg); } return Msg.wParam; }
7665d7db10347bf2ab48ad0620ce26cbd886ed8b
cde72953df2205c2322aac3debf058bb31d4f5b9
/win10.19042/SysWOW64/KBDSORS1.DLL.cpp
c3b9cda46883be65505525171e3f96f6125ac161
[]
no_license
v4nyl/dll-exports
928355082725fbb6fcff47cd3ad83b7390c60c5a
4ec04e0c8f713f6e9a61059d5d87abc5c7db16cf
refs/heads/main
2023-03-30T13:49:47.617341
2021-04-10T20:01:34
2021-04-10T20:01:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
94
cpp
#print comment(linker, "/export:KbdLayerDescriptor=\"C:\\Windows\\SysWOW64\\KBDSORS1.DLL\"")
7dcf7d1ad559737ace20440996699697d36abe0a
931f826a7968d721de0caa4d43aff7a4f0586a5d
/yandex_course/task_2.cpp
8e7bc9f4f3183683629012a005bd90929d35a21a
[]
no_license
Poltorola/Playground
7ebfcf01927c4ea297dbf8d8288cd8b9c634ff39
903571d7350c03d430d91d48765cf186d82f82e5
refs/heads/main
2023-01-10T21:10:48.856563
2020-11-13T12:49:57
2020-11-13T12:49:57
302,155,575
0
0
null
null
null
null
UTF-8
C++
false
false
328
cpp
// simple example of cast made in gnu nano // haven't recieved clion license on my new laptop yet :( #include <iostream> #include <cmath> int main() { double n; std::cin >> n; //here comes nice green space) std::cout << n - (int)n << std:: endl; return 0; }
cff312eff42f6b8252e4d579bdf2ae56ab82236c
ca4fe6ea9f61faf113d14db513ad6805a5d112b7
/libamqpprox/amqpprox_backendstore.cpp
2ea155cab7dcb5363da015d86665e2ca83a2aad6
[ "Apache-2.0" ]
permissive
tokheim/amqpprox
3613c9cad6b9cdeaf6be02886e083ed3d1821e8b
ff3e60372b24631739af8421ef62a9744917f607
refs/heads/main
2023-08-22T01:05:03.372402
2021-09-29T17:10:13
2021-09-29T17:10:13
423,238,449
0
0
NOASSERTION
2021-10-31T19:11:41
2021-10-31T19:11:40
null
UTF-8
C++
false
false
2,485
cpp
/* ** Copyright 2020 Bloomberg Finance L.P. ** ** 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 <amqpprox_backendstore.h> #include <iostream> namespace Bloomberg { namespace amqpprox { BackendStore::BackendStore() : d_backends() , d_backendAddresses() { } int BackendStore::insert(const Backend &backend) { auto namedBackend = lookup(backend.name()); auto addrBackend = lookup(backend.ip(), backend.port()); if (namedBackend || addrBackend) { return 1; } std::lock_guard<std::mutex> lg(d_mutex); d_backends.insert(std::make_pair(backend.name(), backend)); auto addrKey = std::make_pair(backend.ip(), backend.port()); d_backendAddresses.insert( std::make_pair(addrKey, &d_backends[backend.name()])); return 0; } int BackendStore::remove(const std::string &name) { auto backend = lookup(name); if (!backend) { return 1; } std::lock_guard<std::mutex> lg(d_mutex); auto addrKey = std::make_pair(backend->ip(), backend->port()); d_backendAddresses.erase(addrKey); d_backends.erase(name); return 0; } const Backend *BackendStore::lookup(const std::string &ip, int port) const { std::lock_guard<std::mutex> lg(d_mutex); auto addrKey = std::make_pair(ip, port); auto it = d_backendAddresses.find(addrKey); if (it == d_backendAddresses.end()) { return nullptr; } else { return it->second; } } const Backend *BackendStore::lookup(const std::string &name) const { std::lock_guard<std::mutex> lg(d_mutex); auto it = d_backends.find(name); if (it == d_backends.end()) { return nullptr; } else { return &(it->second); } } void BackendStore::print(std::ostream &os) const { std::lock_guard<std::mutex> lg(d_mutex); for (const auto &backend : d_backends) { os << backend.second << std::endl; } } } }
d0a76c41fdb7f5612e01d3380d9f4bdb168f1e51
ec0c10f6c207a3ad1832fabe824767f406a992e0
/1976.cpp
13f54fe4f06d9e679bf1b6a5d78d309ab8918a4f
[]
no_license
luck2901/Algorithm
5f8e88f6fa6d49e11ce880a2550d5ed8c4c57b05
3462c77d1aa6af3da73c4f10b6dd7bb7a8e8a9b4
refs/heads/main
2023-07-14T09:32:33.963583
2021-08-26T02:10:09
2021-08-26T02:10:09
339,104,020
1
0
null
null
null
null
UTF-8
C++
false
false
1,135
cpp
#include <iostream> #include <vector> #include <algorithm> #include <cmath> #include <queue> #include <string.h> using namespace std; #define endl "\n" int N, M; int parent[201]; vector<int> v; int find(int u) { if(parent[u]==u) return u; else return parent[u] = find(parent[u]); } void Union(int u, int v) { u = find(u); v = find(v); parent[u] = v; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> N >> M; for (int i = 1; i <= N; i++) { parent[i] = i; } for (int i = 1; i <= N; i++) for (int j = 1; j <= N; j++) { int num; cin >> num; if(num==1) Union(i, j); } for (int i = 0; i < M; i++) { int num; cin >> num; v.push_back(num); } int tmp = v[0]; for (int i = 1; i < M; i++) { tmp = find(tmp); int tmp2 = find(v[i]); if (tmp != tmp2) { cout << "NO" << endl; return 0; } tmp = v[i]; } cout << "YES" << endl; }
935953e7042cb06233ce7fb6c73800ae4b7875a3
5004f0c1f7eba48acf74630eb0baf296fb2a3a51
/Atcoder/Grand039/B.cpp
989bb374adfa6d5bfca196558407af46ebab8f77
[]
no_license
shash42/Competitive-Programming
80ab2611764f2f615568f2011088c1f651f26dcc
f069e8de37f42dba9fb77941b297b33161c2d401
refs/heads/master
2021-03-17T17:30:38.242207
2020-07-21T18:24:13
2020-07-21T18:24:13
276,369,049
1
1
null
null
null
null
UTF-8
C++
false
false
1,052
cpp
#include<bits/stdc++.h> #define int long long #define pii pair<int, int> #define pb push_back #define mp make_pair using namespace std; const int N=202; int n, ans, lvl[N]; char mat[N][N]; queue<int> q; signed main() { cin >> n; for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { cin >> mat[i][j]; } } for(int i = 1; i <= n; i++) { bool flag=true; for(int j = 1; j <= n; j++) { lvl[j]=N; } while(q.size()) q.pop(); lvl[i]=1; q.push(i); while(q.size()) { int u = q.front(); for(int j = 1; j <= n; j++) { if(mat[u][j]=='1') { if(lvl[j]==N) { lvl[j]=lvl[u]+1; q.push(j); } else if(lvl[j]!=lvl[u]-1 && lvl[j]!=lvl[u]+1) { // cout << i << " - " << u << " " << j << endl; flag=false; break; } } } q.pop(); if(!flag) break; } if(!flag) continue; for(int j = 1; j <= n; j++) { if(lvl[j]==N) break; ans=max(ans, lvl[j]); } // cout << i << " - " << ans << endl; } if(ans==0) cout << -1; else cout << ans; }
cbe41b82970bcebd54698567a63ca6a4c1c64a71
1537e3009b826ec67d9ed46b7054fa0412da770e
/lib/date/test/iso_week/op_div_survey.pass.cpp
1c70c7cb51da7c4b7371b01259f99c505e628797
[ "MIT" ]
permissive
TommyB123/pawn-chrono
403f385ebb74f4aa4b35395ee13485bdb0e4cce7
9e3a9237bff75c3191f5b1123c74abca07e11935
refs/heads/master
2022-12-06T16:11:09.456520
2020-08-12T12:17:58
2020-08-12T12:17:58
287,005,396
0
0
MIT
2020-08-12T12:15:34
2020-08-12T12:15:33
null
UTF-8
C++
false
false
11,196
cpp
// The MIT License (MIT) // // Copyright (c) 2015, 2016 Howard Hinnant // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "iso_week.h" #include <type_traits> template <class I, class J, class K> constexpr auto test(I i, J j, K k) -> decltype(i/j/k) { return i/j/k; } void test(...) { } int main() { using std::is_same; using namespace iso_week; static_assert(is_same<decltype(test( 1, 1, 1)), int>{}, ""); static_assert(is_same<decltype(test( 1, 1, mon)), void>{}, ""); static_assert(is_same<decltype(test( 1, 1, 1_w)), void>{}, ""); static_assert(is_same<decltype(test( 1, 1, 1_y)), void>{}, ""); static_assert(is_same<decltype(test( 1, 1, last)), void>{}, ""); static_assert(is_same<decltype(test( 1, mon, 1)), void>{}, ""); static_assert(is_same<decltype(test( 1, mon, mon)), void>{}, ""); static_assert(is_same<decltype(test( 1, mon, 1_w)), void>{}, ""); static_assert(is_same<decltype(test( 1, mon, 1_y)), void>{}, ""); static_assert(is_same<decltype(test( 1, mon, last)), void>{}, ""); static_assert(is_same<decltype(test( 1, 1_w, 1)), void>{}, ""); static_assert(is_same<decltype(test( 1, 1_w, mon)), void>{}, ""); static_assert(is_same<decltype(test( 1, 1_w, 1_w)), void>{}, ""); static_assert(is_same<decltype(test( 1, 1_w, 1_y)), void>{}, ""); static_assert(is_same<decltype(test( 1, 1_w, last)), void>{}, ""); static_assert(is_same<decltype(test( 1, 1_y, 1)), void>{}, ""); static_assert(is_same<decltype(test( 1, 1_y, mon)), void>{}, ""); static_assert(is_same<decltype(test( 1, 1_y, 1_w)), void>{}, ""); static_assert(is_same<decltype(test( 1, 1_y, 1_y)), void>{}, ""); static_assert(is_same<decltype(test( 1, 1_y, last)), void>{}, ""); static_assert(is_same<decltype(test( 1, last, 1)), void>{}, ""); static_assert(is_same<decltype(test( 1, last, mon)), void>{}, ""); static_assert(is_same<decltype(test( 1, last, 1_w)), void>{}, ""); static_assert(is_same<decltype(test( 1, last, 1_y)), void>{}, ""); static_assert(is_same<decltype(test( 1, last, last)), void>{}, ""); static_assert(is_same<decltype(test( mon, 1, 1)), year_weeknum_weekday>{}, ""); static_assert(is_same<decltype(test( mon, 1, mon)), void>{}, ""); static_assert(is_same<decltype(test( mon, 1, 1_w)), void>{}, ""); static_assert(is_same<decltype(test( mon, 1, 1_y)), year_weeknum_weekday>{}, ""); static_assert(is_same<decltype(test( mon, 1, last)), void>{}, ""); static_assert(is_same<decltype(test( mon, mon, 1)), void>{}, ""); static_assert(is_same<decltype(test( mon, mon, mon)), void>{}, ""); static_assert(is_same<decltype(test( mon, mon, 1_w)), void>{}, ""); static_assert(is_same<decltype(test( mon, mon, 1_y)), void>{}, ""); static_assert(is_same<decltype(test( mon, mon, last)), void>{}, ""); static_assert(is_same<decltype(test( mon, 1_w, 1)), year_weeknum_weekday>{}, ""); static_assert(is_same<decltype(test( mon, 1_w, mon)), void>{}, ""); static_assert(is_same<decltype(test( mon, 1_w, 1_w)), void>{}, ""); static_assert(is_same<decltype(test( mon, 1_w, 1_y)), year_weeknum_weekday>{}, ""); static_assert(is_same<decltype(test( mon, 1_w, last)), void>{}, ""); static_assert(is_same<decltype(test( mon, 1_y, 1)), void>{}, ""); static_assert(is_same<decltype(test( mon, 1_y, mon)), void>{}, ""); static_assert(is_same<decltype(test( mon, 1_y, 1_w)), void>{}, ""); static_assert(is_same<decltype(test( mon, 1_y, 1_y)), void>{}, ""); static_assert(is_same<decltype(test( mon, 1_y, last)), void>{}, ""); static_assert(is_same<decltype(test( mon, last, 1)), year_lastweek_weekday>{}, ""); static_assert(is_same<decltype(test( mon, last, mon)), void>{}, ""); static_assert(is_same<decltype(test( mon, last, 1_w)), void>{}, ""); static_assert(is_same<decltype(test( mon, last, 1_y)), year_lastweek_weekday>{}, ""); static_assert(is_same<decltype(test( mon, last, last)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, 1, 1)), year_weeknum_weekday>{}, ""); static_assert(is_same<decltype(test( 1_w, 1, mon)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, 1, 1_w)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, 1, 1_y)), year_weeknum_weekday>{}, ""); static_assert(is_same<decltype(test( 1_w, 1, last)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, mon, 1)), year_weeknum_weekday>{}, ""); static_assert(is_same<decltype(test( 1_w, mon, mon)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, mon, 1_w)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, mon, 1_y)), year_weeknum_weekday>{}, ""); static_assert(is_same<decltype(test( 1_w, mon, last)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, 1_w, 1)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, 1_w, mon)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, 1_w, 1_w)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, 1_w, 1_y)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, 1_w, last)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, 1_y, 1)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, 1_y, mon)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, 1_y, 1_w)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, 1_y, 1_y)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, 1_y, last)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, last, 1)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, last, mon)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, last, 1_w)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, last, 1_y)), void>{}, ""); static_assert(is_same<decltype(test( 1_w, last, last)), void>{}, ""); static_assert(is_same<decltype(test( 1_y, 1, 1)), year_weeknum_weekday>{}, ""); static_assert(is_same<decltype(test( 1_y, 1, mon)), year_weeknum_weekday>{}, ""); static_assert(is_same<decltype(test( 1_y, 1, 1_w)), void>{}, ""); static_assert(is_same<decltype(test( 1_y, 1, 1_y)), void>{}, ""); static_assert(is_same<decltype(test( 1_y, 1, last)), void>{}, ""); static_assert(is_same<decltype(test( 1_y, mon, 1)), void>{}, ""); static_assert(is_same<decltype(test( 1_y, mon, mon)), void>{}, ""); static_assert(is_same<decltype(test( 1_y, mon, 1_w)), void>{}, ""); static_assert(is_same<decltype(test( 1_y, mon, 1_y)), void>{}, ""); static_assert(is_same<decltype(test( 1_y, mon, last)), void>{}, ""); static_assert(is_same<decltype(test( 1_y, 1_w, 1)), year_weeknum_weekday>{}, ""); static_assert(is_same<decltype(test( 1_y, 1_w, mon)), year_weeknum_weekday>{}, ""); static_assert(is_same<decltype(test( 1_y, 1_w, 1_w)), void>{}, ""); static_assert(is_same<decltype(test( 1_y, 1_w, 1_y)), void>{}, ""); static_assert(is_same<decltype(test( 1_y, 1_w, last)), void>{}, ""); static_assert(is_same<decltype(test( 1_y, 1_y, 1)), void>{}, ""); static_assert(is_same<decltype(test( 1_y, 1_y, mon)), void>{}, ""); static_assert(is_same<decltype(test( 1_y, 1_y, 1_w)), void>{}, ""); static_assert(is_same<decltype(test( 1_y, 1_y, 1_y)), void>{}, ""); static_assert(is_same<decltype(test( 1_y, 1_y, last)), void>{}, ""); static_assert(is_same<decltype(test( 1_y, last, 1)), year_lastweek_weekday>{}, ""); static_assert(is_same<decltype(test( 1_y, last, mon)), year_lastweek_weekday>{}, ""); static_assert(is_same<decltype(test( 1_y, last, 1_w)), void>{}, ""); static_assert(is_same<decltype(test( 1_y, last, 1_y)), void>{}, ""); static_assert(is_same<decltype(test( 1_y, last, last)), void>{}, ""); static_assert(is_same<decltype(test(last, 1, 1)), year_lastweek_weekday>{}, ""); static_assert(is_same<decltype(test(last, 1, mon)), void>{}, ""); static_assert(is_same<decltype(test(last, 1, 1_w)), void>{}, ""); static_assert(is_same<decltype(test(last, 1, 1_y)), year_lastweek_weekday>{}, ""); static_assert(is_same<decltype(test(last, 1, last)), void>{}, ""); static_assert(is_same<decltype(test(last, mon, 1)), year_lastweek_weekday>{}, ""); static_assert(is_same<decltype(test(last, mon, mon)), void>{}, ""); static_assert(is_same<decltype(test(last, mon, 1_w)), void>{}, ""); static_assert(is_same<decltype(test(last, mon, 1_y)), year_lastweek_weekday>{}, ""); static_assert(is_same<decltype(test(last, mon, last)), void>{}, ""); static_assert(is_same<decltype(test(last, 1_w, 1)), void>{}, ""); static_assert(is_same<decltype(test(last, 1_w, mon)), void>{}, ""); static_assert(is_same<decltype(test(last, 1_w, 1_w)), void>{}, ""); static_assert(is_same<decltype(test(last, 1_w, 1_y)), void>{}, ""); static_assert(is_same<decltype(test(last, 1_w, last)), void>{}, ""); static_assert(is_same<decltype(test(last, 1_y, 1)), void>{}, ""); static_assert(is_same<decltype(test(last, 1_y, mon)), void>{}, ""); static_assert(is_same<decltype(test(last, 1_y, 1_w)), void>{}, ""); static_assert(is_same<decltype(test(last, 1_y, 1_y)), void>{}, ""); static_assert(is_same<decltype(test(last, 1_y, last)), void>{}, ""); static_assert(is_same<decltype(test(last, last, 1)), void>{}, ""); static_assert(is_same<decltype(test(last, last, mon)), void>{}, ""); static_assert(is_same<decltype(test(last, last, 1_w)), void>{}, ""); static_assert(is_same<decltype(test(last, last, 1_y)), void>{}, ""); static_assert(is_same<decltype(test(last, last, last)), void>{}, ""); }
2843060f092780dbc66474df9d9c8e591ccb80c8
03a957f10754ae97d998b9a5af01e0ec43a36409
/src/chrome/browser/sync_file_system/drive_backend/sync_worker.cc
ca3f5cdcaa6bc4065a40a141f2b96b5d8f946782
[ "BSD-3-Clause" ]
permissive
xph906/TrackingFree
e5d39ced8909380ec29a38f0776814f762389aea
41540f0bdc8e146630f680d835a4107e7b8fd2c4
refs/heads/master
2021-01-19T11:43:34.409514
2014-05-21T01:54:24
2014-05-21T01:54:24
19,993,612
1
1
null
null
null
null
UTF-8
C++
false
false
24,164
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync_file_system/drive_backend/sync_worker.h" #include <vector> #include "base/bind.h" #include "base/memory/weak_ptr.h" #include "base/threading/sequenced_worker_pool.h" #include "base/values.h" #include "chrome/browser/drive/drive_api_service.h" #include "chrome/browser/drive/drive_notification_manager.h" #include "chrome/browser/drive/drive_notification_manager_factory.h" #include "chrome/browser/drive/drive_service_interface.h" #include "chrome/browser/drive/drive_uploader.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/sync_file_system/drive_backend/callback_helper.h" #include "chrome/browser/sync_file_system/drive_backend/conflict_resolver.h" #include "chrome/browser/sync_file_system/drive_backend/drive_backend_constants.h" #include "chrome/browser/sync_file_system/drive_backend/list_changes_task.h" #include "chrome/browser/sync_file_system/drive_backend/local_to_remote_syncer.h" #include "chrome/browser/sync_file_system/drive_backend/metadata_database.h" #include "chrome/browser/sync_file_system/drive_backend/register_app_task.h" #include "chrome/browser/sync_file_system/drive_backend/remote_change_processor_on_worker.h" #include "chrome/browser/sync_file_system/drive_backend/remote_change_processor_wrapper.h" #include "chrome/browser/sync_file_system/drive_backend/remote_to_local_syncer.h" #include "chrome/browser/sync_file_system/drive_backend/sync_engine_context.h" #include "chrome/browser/sync_file_system/drive_backend/sync_engine_initializer.h" #include "chrome/browser/sync_file_system/drive_backend/sync_task.h" #include "chrome/browser/sync_file_system/drive_backend/uninstall_app_task.h" #include "chrome/browser/sync_file_system/file_status_observer.h" #include "chrome/browser/sync_file_system/logger.h" #include "chrome/browser/sync_file_system/syncable_file_system_util.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" #include "components/signin/core/browser/signin_manager.h" #include "content/public/browser/browser_thread.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/extension_system_provider.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/common/extension.h" #include "google_apis/drive/drive_api_url_generator.h" #include "google_apis/drive/gdata_wapi_url_generator.h" #include "webkit/common/blob/scoped_file.h" #include "webkit/common/fileapi/file_system_util.h" namespace sync_file_system { class RemoteChangeProcessor; namespace drive_backend { namespace { void EmptyStatusCallback(SyncStatusCode status) {} void QueryAppStatusOnUIThread( const base::WeakPtr<ExtensionServiceInterface>& extension_service_ptr, const std::vector<std::string>* app_ids, SyncWorker::AppStatusMap* status, const base::Closure& callback) { ExtensionServiceInterface* extension_service = extension_service_ptr.get(); if (!extension_service) { callback.Run(); return; } for (std::vector<std::string>::const_iterator itr = app_ids->begin(); itr != app_ids->end(); ++itr) { const std::string& app_id = *itr; if (!extension_service->GetInstalledExtension(app_id)) (*status)[app_id] = SyncWorker::APP_STATUS_UNINSTALLED; else if (!extension_service->IsExtensionEnabled(app_id)) (*status)[app_id] = SyncWorker::APP_STATUS_DISABLED; else (*status)[app_id] = SyncWorker::APP_STATUS_ENABLED; } callback.Run(); } } // namespace scoped_ptr<SyncWorker> SyncWorker::CreateOnWorker( const base::FilePath& base_dir, Observer* observer, const base::WeakPtr<ExtensionServiceInterface>& extension_service, scoped_ptr<SyncEngineContext> sync_engine_context, leveldb::Env* env_override) { scoped_ptr<SyncWorker> sync_worker( new SyncWorker(base_dir, extension_service, sync_engine_context.Pass(), env_override)); sync_worker->AddObserver(observer); sync_worker->Initialize(); return sync_worker.Pass(); } SyncWorker::~SyncWorker() {} void SyncWorker::Initialize() { DCHECK(!task_manager_); task_manager_.reset(new SyncTaskManager( weak_ptr_factory_.GetWeakPtr(), 0 /* maximum_background_task */)); task_manager_->Initialize(SYNC_STATUS_OK); PostInitializeTask(); net::NetworkChangeNotifier::ConnectionType type = net::NetworkChangeNotifier::GetConnectionType(); network_available_ = type != net::NetworkChangeNotifier::CONNECTION_NONE; } void SyncWorker::RegisterOrigin( const GURL& origin, const SyncStatusCallback& callback) { if (!GetMetadataDatabase() && GetDriveService()->HasRefreshToken()) PostInitializeTask(); scoped_ptr<RegisterAppTask> task( new RegisterAppTask(context_.get(), origin.host())); if (task->CanFinishImmediately()) { context_->GetUITaskRunner()->PostTask( FROM_HERE, base::Bind(callback, SYNC_STATUS_OK)); return; } // TODO(peria): Forward |callback| to UI thread. task_manager_->ScheduleSyncTask( FROM_HERE, task.PassAs<SyncTask>(), SyncTaskManager::PRIORITY_HIGH, callback); } void SyncWorker::EnableOrigin( const GURL& origin, const SyncStatusCallback& callback) { // TODO(peria): Forward |callback| to UI thread. task_manager_->ScheduleTask( FROM_HERE, base::Bind(&SyncWorker::DoEnableApp, weak_ptr_factory_.GetWeakPtr(), origin.host()), SyncTaskManager::PRIORITY_HIGH, callback); } void SyncWorker::DisableOrigin( const GURL& origin, const SyncStatusCallback& callback) { // TODO(peria): Forward |callback| to UI thread. task_manager_->ScheduleTask( FROM_HERE, base::Bind(&SyncWorker::DoDisableApp, weak_ptr_factory_.GetWeakPtr(), origin.host()), SyncTaskManager::PRIORITY_HIGH, callback); } void SyncWorker::UninstallOrigin( const GURL& origin, RemoteFileSyncService::UninstallFlag flag, const SyncStatusCallback& callback) { // TODO(peria): Forward |callback| to UI thread. task_manager_->ScheduleSyncTask( FROM_HERE, scoped_ptr<SyncTask>( new UninstallAppTask(context_.get(), origin.host(), flag)), SyncTaskManager::PRIORITY_HIGH, callback); } void SyncWorker::ProcessRemoteChange( const SyncFileCallback& callback) { RemoteToLocalSyncer* syncer = new RemoteToLocalSyncer(context_.get()); task_manager_->ScheduleSyncTask( FROM_HERE, scoped_ptr<SyncTask>(syncer), SyncTaskManager::PRIORITY_MED, base::Bind(&SyncWorker::DidProcessRemoteChange, weak_ptr_factory_.GetWeakPtr(), syncer, callback)); } void SyncWorker::SetRemoteChangeProcessor( RemoteChangeProcessorOnWorker* remote_change_processor_on_worker) { context_->SetRemoteChangeProcessor(remote_change_processor_on_worker); } RemoteServiceState SyncWorker::GetCurrentState() const { if (!sync_enabled_) return REMOTE_SERVICE_DISABLED; return service_state_; } void SyncWorker::GetOriginStatusMap( RemoteFileSyncService::OriginStatusMap* status_map) { DCHECK(status_map); if (!GetMetadataDatabase()) return; std::vector<std::string> app_ids; GetMetadataDatabase()->GetRegisteredAppIDs(&app_ids); for (std::vector<std::string>::const_iterator itr = app_ids.begin(); itr != app_ids.end(); ++itr) { const std::string& app_id = *itr; GURL origin = extensions::Extension::GetBaseURLFromExtensionId(app_id); (*status_map)[origin] = GetMetadataDatabase()->IsAppEnabled(app_id) ? "Enabled" : "Disabled"; } } scoped_ptr<base::ListValue> SyncWorker::DumpFiles(const GURL& origin) { if (!GetMetadataDatabase()) return scoped_ptr<base::ListValue>(); return GetMetadataDatabase()->DumpFiles(origin.host()); } scoped_ptr<base::ListValue> SyncWorker::DumpDatabase() { if (!GetMetadataDatabase()) return scoped_ptr<base::ListValue>(); return GetMetadataDatabase()->DumpDatabase(); } void SyncWorker::SetSyncEnabled(bool enabled) { if (sync_enabled_ == enabled) return; RemoteServiceState old_state = GetCurrentState(); sync_enabled_ = enabled; if (old_state == GetCurrentState()) return; FOR_EACH_OBSERVER( Observer, observers_, UpdateServiceState( GetCurrentState(), enabled ? "Sync is enabled" : "Sync is disabled")); } SyncStatusCode SyncWorker::SetDefaultConflictResolutionPolicy( ConflictResolutionPolicy policy) { default_conflict_resolution_policy_ = policy; return SYNC_STATUS_OK; } SyncStatusCode SyncWorker::SetConflictResolutionPolicy( const GURL& origin, ConflictResolutionPolicy policy) { NOTIMPLEMENTED(); default_conflict_resolution_policy_ = policy; return SYNC_STATUS_OK; } ConflictResolutionPolicy SyncWorker::GetDefaultConflictResolutionPolicy() const { return default_conflict_resolution_policy_; } ConflictResolutionPolicy SyncWorker::GetConflictResolutionPolicy( const GURL& origin) const { NOTIMPLEMENTED(); return default_conflict_resolution_policy_; } void SyncWorker::ApplyLocalChange( const FileChange& local_change, const base::FilePath& local_path, const SyncFileMetadata& local_metadata, const fileapi::FileSystemURL& url, const SyncStatusCallback& callback) { LocalToRemoteSyncer* syncer = new LocalToRemoteSyncer( context_.get(), local_metadata, local_change, local_path, url); task_manager_->ScheduleSyncTask( FROM_HERE, scoped_ptr<SyncTask>(syncer), SyncTaskManager::PRIORITY_MED, base::Bind(&SyncWorker::DidApplyLocalChange, weak_ptr_factory_.GetWeakPtr(), syncer, callback)); } void SyncWorker::MaybeScheduleNextTask() { if (GetCurrentState() == REMOTE_SERVICE_DISABLED) return; // TODO(tzik): Notify observer of OnRemoteChangeQueueUpdated. // TODO(tzik): Add an interface to get the number of dirty trackers to // MetadataDatabase. MaybeStartFetchChanges(); } void SyncWorker::NotifyLastOperationStatus( SyncStatusCode status, bool used_network) { UpdateServiceStateFromSyncStatusCode(status, used_network); if (GetMetadataDatabase()) { FOR_EACH_OBSERVER( Observer, observers_, OnPendingFileListUpdated(GetMetadataDatabase()->CountDirtyTracker())); } } void SyncWorker::OnNotificationReceived() { if (service_state_ == REMOTE_SERVICE_TEMPORARY_UNAVAILABLE) UpdateServiceState(REMOTE_SERVICE_OK, "Got push notification for Drive."); should_check_remote_change_ = true; MaybeScheduleNextTask(); } void SyncWorker::OnReadyToSendRequests(const std::string& account_id) { if (service_state_ == REMOTE_SERVICE_OK) return; UpdateServiceState(REMOTE_SERVICE_OK, "Authenticated"); if (!GetMetadataDatabase() && !account_id.empty()) { GetDriveService()->Initialize(account_id); PostInitializeTask(); return; } should_check_remote_change_ = true; MaybeScheduleNextTask(); } void SyncWorker::OnRefreshTokenInvalid() { UpdateServiceState( REMOTE_SERVICE_AUTHENTICATION_REQUIRED, "Found invalid refresh token."); } void SyncWorker::OnNetworkChanged( net::NetworkChangeNotifier::ConnectionType type) { bool new_network_availability = type != net::NetworkChangeNotifier::CONNECTION_NONE; if (network_available_ && !new_network_availability) { UpdateServiceState(REMOTE_SERVICE_TEMPORARY_UNAVAILABLE, "Disconnected"); } else if (!network_available_ && new_network_availability) { UpdateServiceState(REMOTE_SERVICE_OK, "Connected"); should_check_remote_change_ = true; MaybeStartFetchChanges(); } network_available_ = new_network_availability; } drive::DriveServiceInterface* SyncWorker::GetDriveService() { return context_->GetDriveService(); } drive::DriveUploaderInterface* SyncWorker::GetDriveUploader() { return context_->GetDriveUploader(); } MetadataDatabase* SyncWorker::GetMetadataDatabase() { return context_->GetMetadataDatabase(); } SyncTaskManager* SyncWorker::GetSyncTaskManager() { return task_manager_.get(); } void SyncWorker::AddObserver(Observer* observer) { observers_.AddObserver(observer); } SyncWorker::SyncWorker( const base::FilePath& base_dir, const base::WeakPtr<ExtensionServiceInterface>& extension_service, scoped_ptr<SyncEngineContext> sync_engine_context, leveldb::Env* env_override) : base_dir_(base_dir), env_override_(env_override), service_state_(REMOTE_SERVICE_TEMPORARY_UNAVAILABLE), should_check_conflict_(true), should_check_remote_change_(true), listing_remote_changes_(false), sync_enabled_(false), default_conflict_resolution_policy_( CONFLICT_RESOLUTION_POLICY_LAST_WRITE_WIN), network_available_(false), extension_service_(extension_service), context_(sync_engine_context.Pass()), weak_ptr_factory_(this) {} void SyncWorker::DoDisableApp(const std::string& app_id, const SyncStatusCallback& callback) { if (GetMetadataDatabase()) { GetMetadataDatabase()->DisableApp(app_id, callback); } else { context_->GetUITaskRunner()->PostTask( FROM_HERE, base::Bind(callback, SYNC_STATUS_OK)); } } void SyncWorker::DoEnableApp(const std::string& app_id, const SyncStatusCallback& callback) { if (GetMetadataDatabase()) { GetMetadataDatabase()->EnableApp(app_id, callback); } else { context_->GetUITaskRunner()->PostTask( FROM_HERE, base::Bind(callback, SYNC_STATUS_OK)); } } void SyncWorker::PostInitializeTask() { DCHECK(!GetMetadataDatabase()); // This initializer task may not run if MetadataDatabase in context_ is // already initialized when it runs. SyncEngineInitializer* initializer = new SyncEngineInitializer(context_.get(), base_dir_.Append(kDatabaseName), env_override_); task_manager_->ScheduleSyncTask( FROM_HERE, scoped_ptr<SyncTask>(initializer), SyncTaskManager::PRIORITY_HIGH, base::Bind(&SyncWorker::DidInitialize, weak_ptr_factory_.GetWeakPtr(), initializer)); } void SyncWorker::DidInitialize(SyncEngineInitializer* initializer, SyncStatusCode status) { if (status != SYNC_STATUS_OK) { if (GetDriveService()->HasRefreshToken()) { UpdateServiceState(REMOTE_SERVICE_TEMPORARY_UNAVAILABLE, "Could not initialize remote service"); } else { UpdateServiceState(REMOTE_SERVICE_AUTHENTICATION_REQUIRED, "Authentication required."); } return; } scoped_ptr<MetadataDatabase> metadata_database = initializer->PassMetadataDatabase(); if (metadata_database) context_->SetMetadataDatabase(metadata_database.Pass()); UpdateRegisteredApp(); } void SyncWorker::UpdateRegisteredApp() { MetadataDatabase* metadata_db = GetMetadataDatabase(); DCHECK(metadata_db); scoped_ptr<std::vector<std::string> > app_ids(new std::vector<std::string>); metadata_db->GetRegisteredAppIDs(app_ids.get()); AppStatusMap* app_status = new AppStatusMap; base::Closure callback = base::Bind(&SyncWorker::DidQueryAppStatus, weak_ptr_factory_.GetWeakPtr(), base::Owned(app_status)); context_->GetUITaskRunner()->PostTask( FROM_HERE, base::Bind(&QueryAppStatusOnUIThread, extension_service_, base::Owned(app_ids.release()), app_status, RelayCallbackToTaskRunner( context_->GetWorkerTaskRunner(), FROM_HERE, callback))); } void SyncWorker::DidQueryAppStatus(const AppStatusMap* app_status) { MetadataDatabase* metadata_db = GetMetadataDatabase(); DCHECK(metadata_db); // Update the status of every origin using status from ExtensionService. for (AppStatusMap::const_iterator itr = app_status->begin(); itr != app_status->end(); ++itr) { const std::string& app_id = itr->first; GURL origin = extensions::Extension::GetBaseURLFromExtensionId(app_id); if (itr->second == APP_STATUS_UNINSTALLED) { // Extension has been uninstalled. // (At this stage we can't know if it was unpacked extension or not, // so just purge the remote folder.) UninstallOrigin(origin, RemoteFileSyncService::UNINSTALL_AND_PURGE_REMOTE, base::Bind(&EmptyStatusCallback)); continue; } FileTracker tracker; if (!metadata_db->FindAppRootTracker(app_id, &tracker)) { // App will register itself on first run. continue; } DCHECK(itr->second == APP_STATUS_ENABLED || itr->second == APP_STATUS_DISABLED); bool is_app_enabled = (itr->second == APP_STATUS_ENABLED); bool is_app_root_tracker_enabled = (tracker.tracker_kind() == TRACKER_KIND_APP_ROOT); if (is_app_enabled && !is_app_root_tracker_enabled) EnableOrigin(origin, base::Bind(&EmptyStatusCallback)); else if (!is_app_enabled && is_app_root_tracker_enabled) DisableOrigin(origin, base::Bind(&EmptyStatusCallback)); } } void SyncWorker::DidProcessRemoteChange(RemoteToLocalSyncer* syncer, const SyncFileCallback& callback, SyncStatusCode status) { if (syncer->is_sync_root_deletion()) { MetadataDatabase::ClearDatabase(context_->PassMetadataDatabase()); PostInitializeTask(); callback.Run(status, syncer->url()); return; } if (status == SYNC_STATUS_OK) { if (syncer->sync_action() != SYNC_ACTION_NONE && syncer->url().is_valid()) { FOR_EACH_OBSERVER( Observer, observers_, OnFileStatusChanged( syncer->url(), SYNC_FILE_STATUS_SYNCED, syncer->sync_action(), SYNC_DIRECTION_REMOTE_TO_LOCAL)); } if (syncer->sync_action() == SYNC_ACTION_DELETED && syncer->url().is_valid() && fileapi::VirtualPath::IsRootPath(syncer->url().path())) { RegisterOrigin(syncer->url().origin(), base::Bind(&EmptyStatusCallback)); } should_check_conflict_ = true; } callback.Run(status, syncer->url()); } void SyncWorker::DidApplyLocalChange(LocalToRemoteSyncer* syncer, const SyncStatusCallback& callback, SyncStatusCode status) { if ((status == SYNC_STATUS_OK || status == SYNC_STATUS_RETRY) && syncer->url().is_valid() && syncer->sync_action() != SYNC_ACTION_NONE) { fileapi::FileSystemURL updated_url = syncer->url(); if (!syncer->target_path().empty()) { updated_url = CreateSyncableFileSystemURL(syncer->url().origin(), syncer->target_path()); } FOR_EACH_OBSERVER(Observer, observers_, OnFileStatusChanged(updated_url, SYNC_FILE_STATUS_SYNCED, syncer->sync_action(), SYNC_DIRECTION_LOCAL_TO_REMOTE)); } if (status == SYNC_STATUS_UNKNOWN_ORIGIN && syncer->url().is_valid()) { RegisterOrigin(syncer->url().origin(), base::Bind(&EmptyStatusCallback)); } if (syncer->needs_remote_change_listing() && !listing_remote_changes_) { task_manager_->ScheduleSyncTask( FROM_HERE, scoped_ptr<SyncTask>(new ListChangesTask(context_.get())), SyncTaskManager::PRIORITY_HIGH, base::Bind(&SyncWorker::DidFetchChanges, weak_ptr_factory_.GetWeakPtr())); should_check_remote_change_ = false; listing_remote_changes_ = true; time_to_check_changes_ = base::TimeTicks::Now() + base::TimeDelta::FromSeconds(kListChangesRetryDelaySeconds); } if (status == SYNC_STATUS_OK) should_check_conflict_ = true; callback.Run(status); } void SyncWorker::MaybeStartFetchChanges() { if (GetCurrentState() == REMOTE_SERVICE_DISABLED) return; if (!GetMetadataDatabase()) return; if (listing_remote_changes_) return; base::TimeTicks now = base::TimeTicks::Now(); if (!should_check_remote_change_ && now < time_to_check_changes_) { if (!GetMetadataDatabase()->HasDirtyTracker() && should_check_conflict_) { should_check_conflict_ = false; task_manager_->ScheduleSyncTaskIfIdle( FROM_HERE, scoped_ptr<SyncTask>(new ConflictResolver(context_.get())), base::Bind(&SyncWorker::DidResolveConflict, weak_ptr_factory_.GetWeakPtr())); } return; } if (task_manager_->ScheduleSyncTaskIfIdle( FROM_HERE, scoped_ptr<SyncTask>(new ListChangesTask(context_.get())), base::Bind(&SyncWorker::DidFetchChanges, weak_ptr_factory_.GetWeakPtr()))) { should_check_remote_change_ = false; listing_remote_changes_ = true; time_to_check_changes_ = now + base::TimeDelta::FromSeconds(kListChangesRetryDelaySeconds); } } void SyncWorker::DidResolveConflict(SyncStatusCode status) { if (status == SYNC_STATUS_OK) should_check_conflict_ = true; } void SyncWorker::DidFetchChanges(SyncStatusCode status) { if (status == SYNC_STATUS_OK) should_check_conflict_ = true; listing_remote_changes_ = false; } void SyncWorker::UpdateServiceStateFromSyncStatusCode( SyncStatusCode status, bool used_network) { switch (status) { case SYNC_STATUS_OK: if (used_network) UpdateServiceState(REMOTE_SERVICE_OK, std::string()); break; // Authentication error. case SYNC_STATUS_AUTHENTICATION_FAILED: UpdateServiceState(REMOTE_SERVICE_AUTHENTICATION_REQUIRED, "Authentication required"); break; // OAuth token error. case SYNC_STATUS_ACCESS_FORBIDDEN: UpdateServiceState(REMOTE_SERVICE_AUTHENTICATION_REQUIRED, "Access forbidden"); break; // Errors which could make the service temporarily unavailable. case SYNC_STATUS_SERVICE_TEMPORARILY_UNAVAILABLE: case SYNC_STATUS_NETWORK_ERROR: case SYNC_STATUS_ABORT: case SYNC_STATUS_FAILED: if (GetDriveService()->HasRefreshToken()) { UpdateServiceState(REMOTE_SERVICE_TEMPORARY_UNAVAILABLE, "Network or temporary service error."); } else { UpdateServiceState(REMOTE_SERVICE_AUTHENTICATION_REQUIRED, "Authentication required"); } break; // Errors which would require manual user intervention to resolve. case SYNC_DATABASE_ERROR_CORRUPTION: case SYNC_DATABASE_ERROR_IO_ERROR: case SYNC_DATABASE_ERROR_FAILED: UpdateServiceState(REMOTE_SERVICE_DISABLED, "Unrecoverable database error"); break; default: // Other errors don't affect service state break; } } void SyncWorker::UpdateServiceState(RemoteServiceState state, const std::string& description) { RemoteServiceState old_state = GetCurrentState(); service_state_ = state; if (old_state == GetCurrentState()) return; util::Log(logging::LOG_VERBOSE, FROM_HERE, "Service state changed: %d->%d: %s", old_state, GetCurrentState(), description.c_str()); FOR_EACH_OBSERVER( Observer, observers_, UpdateServiceState(GetCurrentState(), description)); } } // namespace drive_backend } // namespace sync_file_system
a5aa4517417b279ea1baeecec7d10b564833056b
7916582c6d99379b39ac39bddb48435b8c88662b
/code/Modules/IO/Core/schemeRegistry.cc
1e18b42f0bab6203db85e3c59ef862058c0a6254
[ "MIT" ]
permissive
numericalBoy/oryol
b8e0f8163b2b76c5ab804263457c077f0e0bdc2c
76a2dc7b4a06396295825b3eef26ab7119211968
refs/heads/master
2021-05-31T14:48:13.759321
2015-12-28T11:39:48
2015-12-28T11:39:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,213
cc
//------------------------------------------------------------------------------ // schemeRegistry.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "schemeRegistry.h" #include "IO/FS/FileSystem.h" #include "Core/Core.h" namespace Oryol { namespace _priv { //------------------------------------------------------------------------------ schemeRegistry::schemeRegistry() { // empty } //------------------------------------------------------------------------------ schemeRegistry::~schemeRegistry() { // empty } //------------------------------------------------------------------------------ void schemeRegistry::RegisterFileSystem(const StringAtom& scheme, std::function<Ptr<FileSystem>()> fsCreator) { this->rwLock.LockWrite(); o_assert(!this->registry.Contains(scheme)); this->registry.Add(scheme, fsCreator); this->rwLock.UnlockWrite(); // create temp FileSystem object on main-thread to call the Init method this->CreateFileSystem(scheme); } //------------------------------------------------------------------------------ void schemeRegistry::UnregisterFileSystem(const StringAtom& scheme) { this->rwLock.LockWrite(); o_assert(this->registry.Contains(scheme)); this->registry.Erase(scheme); this->rwLock.UnlockWrite(); } //------------------------------------------------------------------------------ bool schemeRegistry::IsFileSystemRegistered(const StringAtom& scheme) const { this->rwLock.LockRead(); bool result = this->registry.Contains(scheme); this->rwLock.UnlockRead(); return result; } //------------------------------------------------------------------------------ Ptr<FileSystem> schemeRegistry::CreateFileSystem(const StringAtom& scheme) const { this->rwLock.LockRead(); o_assert(this->registry.Contains(scheme)); Ptr<FileSystem> fileSystem(this->registry[scheme]()); if (Core::IsMainThread()) { fileSystem->Init(); } else { fileSystem->InitLane(); } this->rwLock.UnlockRead(); return fileSystem; } } // namespace _priv } // namespace Oryol
801e22f726d7a45d80e251a1aa6ed502a5f0cd9f
9640114af546d4ca3641cd395b88207f9c737ee8
/samples/linear_road/output/pcapplusplus/linear_road_pos_report.h
ad511b8cb0e6692528bc0b058ccb7cabd0bebadf
[ "MIT" ]
permissive
MischMetal/p4-traffictool
fcb3f0e4609532e15c0082fcafd010c1c9cca953
761263bf6d911432f5a102fcf987095dc90afab2
refs/heads/master
2022-12-07T13:58:19.356237
2020-05-09T14:11:38
2020-05-09T14:20:01
290,684,078
0
0
MIT
2020-08-27T05:25:39
2020-08-27T05:25:38
null
UTF-8
C++
false
false
1,626
h
//Template for addition of new protocol 'pos_report' #ifndef P4_POS_REPORT_LAYER #define P4_POS_REPORT_LAYER #include <cstring> #include "Layer.h" #include "uint24_t.h" #include "uint40_t.h" #include "uint48_t.h" #if defined(WIN32) || defined(WINx64) #include <winsock2.h> #elif LINUX #include <in.h> #endif namespace pcpp{ #pragma pack(push,1) struct pos_reporthdr{ uint16_t time; uint32_t vid; uint8_t spd; uint8_t xway; uint8_t lane; uint8_t dir; uint8_t seg; }; #pragma pack(pop) class Pos_reportLayer: public Layer{ public: Pos_reportLayer(uint8_t* data, size_t dataLen, Layer* prevLayer, Packet* packet): Layer(data, dataLen, prevLayer, packet) {m_Protocol = P4_POS_REPORT;} Pos_reportLayer(){ m_DataLen = sizeof(pos_reporthdr); m_Data = new uint8_t[m_DataLen]; memset(m_Data, 0, m_DataLen); m_Protocol = P4_POS_REPORT; } // Getters and Setters for fields uint16_t getTime(); void setTime(uint16_t value); uint32_t getVid(); void setVid(uint32_t value); uint8_t getSpd(); void setSpd(uint8_t value); uint8_t getXway(); void setXway(uint8_t value); uint8_t getLane(); void setLane(uint8_t value); uint8_t getDir(); void setDir(uint8_t value); uint8_t getSeg(); void setSeg(uint8_t value); inline pos_reporthdr* getPos_reportHeader() { return (pos_reporthdr*)m_Data; } void parseNextLayer(); inline size_t getHeaderLen() { return sizeof(pos_reporthdr); } void computeCalculateFields() {} std::string toString(); OsiModelLayer getOsiModelLayer() { return OsiModelApplicationLayer; } }; } #endif
8901adadfea04c3c2de262378d9061305d187ee2
04b1803adb6653ecb7cb827c4f4aa616afacf629
/net/proxy_resolution/proxy_resolver_v8_tracing.cc
3f7b5e810a5a6f2da2f3c22c71cae0780103b4f7
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
35,666
cc
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/proxy_resolution/proxy_resolver_v8_tracing.h" #include <map> #include <set> #include <string> #include <utility> #include <vector> #include "base/bind.h" #include "base/macros.h" #include "base/single_thread_task_runner.h" #include "base/strings/stringprintf.h" #include "base/synchronization/cancellation_flag.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" #include "base/threading/thread_checker.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "net/base/ip_address.h" #include "net/base/net_errors.h" #include "net/base/network_interfaces.h" #include "net/base/trace_constants.h" #include "net/log/net_log_with_source.h" #include "net/proxy_resolution/proxy_host_resolver.h" #include "net/proxy_resolution/proxy_info.h" #include "net/proxy_resolution/proxy_resolve_dns_operation.h" #include "net/proxy_resolution/proxy_resolver_error_observer.h" #include "net/proxy_resolution/proxy_resolver_v8.h" // The intent of this class is explained in the design document: // https://docs.google.com/a/chromium.org/document/d/16Ij5OcVnR3s0MH4Z5XkhI9VTPoMJdaBn9rKreAmGOdE/edit // // In a nutshell, PAC scripts are Javascript programs and may depend on // network I/O, by calling functions like dnsResolve(). // // This is problematic since functions such as dnsResolve() will block the // Javascript execution until the DNS result is availble, thereby stalling the // PAC thread, which hurts the ability to process parallel proxy resolves. // An obvious solution is to simply start more PAC threads, however this scales // poorly, which hurts the ability to process parallel proxy resolves. // // The solution in ProxyResolverV8Tracing is to model PAC scripts as being // deterministic, and depending only on the inputted URL. When the script // issues a dnsResolve() for a yet unresolved hostname, the Javascript // execution is "aborted", and then re-started once the DNS result is // known. namespace net { class ScopedAllowThreadJoinForProxyResolverV8Tracing : public base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope {}; namespace { // Upper bound on how many *unique* DNS resolves a PAC script is allowed // to make. This is a failsafe both for scripts that do a ridiculous // number of DNS resolves, as well as scripts which are misbehaving // under the tracing optimization. It is not expected to hit this normally. const size_t kMaxUniqueResolveDnsPerExec = 20; // Approximate number of bytes to use for buffering alerts() and errors. // This is a failsafe in case repeated executions of the script causes // too much memory bloat. It is not expected for well behaved scripts to // hit this. (In fact normal scripts should not even have alerts() or errors). const size_t kMaxAlertsAndErrorsBytes = 2048; // The Job class is responsible for executing GetProxyForURL() and // creating ProxyResolverV8 instances, since both of these operations share // similar code. // // The DNS for these operations can operate in either blocking or // non-blocking mode. Blocking mode is used as a fallback when the PAC script // seems to be misbehaving under the tracing optimization. // // Note that this class runs on both the origin thread and a worker // thread. Most methods are expected to be used exclusively on one thread // or the other. // // The lifetime of Jobs does not exceed that of the ProxyResolverV8TracingImpl // that spawned it. Destruction might happen on either the origin thread or the // worker thread. class Job : public base::RefCountedThreadSafe<Job>, public ProxyResolverV8::JSBindings { public: struct Params { Params( const scoped_refptr<base::SingleThreadTaskRunner>& worker_task_runner, int* num_outstanding_callbacks) : v8_resolver(nullptr), worker_task_runner(worker_task_runner), num_outstanding_callbacks(num_outstanding_callbacks) {} ProxyResolverV8* v8_resolver; scoped_refptr<base::SingleThreadTaskRunner> worker_task_runner; int* num_outstanding_callbacks; }; // |params| is non-owned. It contains the parameters for this Job, and must // outlive it. Job(const Params* params, std::unique_ptr<ProxyResolverV8Tracing::Bindings> bindings); // Called from origin thread. void StartCreateV8Resolver(const scoped_refptr<PacFileData>& script_data, std::unique_ptr<ProxyResolverV8>* resolver, CompletionOnceCallback callback); // Called from origin thread. void StartGetProxyForURL(const GURL& url, ProxyInfo* results, CompletionOnceCallback callback); // Called from origin thread. void Cancel(); // Called from origin thread. LoadState GetLoadState() const; private: typedef std::map<std::string, std::string> DnsCache; friend class base::RefCountedThreadSafe<Job>; enum Operation { CREATE_V8_RESOLVER, GET_PROXY_FOR_URL, }; struct AlertOrError { bool is_alert; int line_number; base::string16 message; }; ~Job() override; void CheckIsOnWorkerThread() const; void CheckIsOnOriginThread() const; void SetCallback(CompletionOnceCallback callback); void ReleaseCallback(); ProxyResolverV8* v8_resolver(); const scoped_refptr<base::SingleThreadTaskRunner>& worker_task_runner(); ProxyHostResolver* host_resolver(); // Invokes the user's callback. void NotifyCaller(int result); void NotifyCallerOnOriginLoop(int result); void Start(Operation op, bool blocking_dns, CompletionOnceCallback callback); void ExecuteBlocking(); void ExecuteNonBlocking(); int ExecuteProxyResolver(); // Implementation of ProxyResolverv8::JSBindings bool ResolveDns(const std::string& host, ProxyResolveDnsOperation op, std::string* output, bool* terminate) override; void Alert(const base::string16& message) override; void OnError(int line_number, const base::string16& error) override; bool ResolveDnsBlocking(const std::string& host, ProxyResolveDnsOperation op, std::string* output); bool ResolveDnsNonBlocking(const std::string& host, ProxyResolveDnsOperation op, std::string* output, bool* terminate); bool PostDnsOperationAndWait(const std::string& host, ProxyResolveDnsOperation op, bool* completed_synchronously) WARN_UNUSED_RESULT; void DoDnsOperation(); void OnDnsOperationComplete(int result); void ScheduleRestartWithBlockingDns(); bool GetDnsFromLocalCache(const std::string& host, ProxyResolveDnsOperation op, std::string* output, bool* return_value); void SaveDnsToLocalCache(const std::string& host, ProxyResolveDnsOperation op, int net_error, const std::vector<IPAddress>& addresses); // Makes a key for looking up |host, op| in |dns_cache_|. Strings are used for // convenience, to avoid defining custom comparators. static std::string MakeDnsCacheKey(const std::string& host, ProxyResolveDnsOperation op); void HandleAlertOrError(bool is_alert, int line_number, const base::string16& message); void DispatchBufferedAlertsAndErrors(); void DispatchAlertOrErrorOnOriginThread(bool is_alert, int line_number, const base::string16& message); // The thread which called into ProxyResolverV8TracingImpl, and on which the // completion callback is expected to run. scoped_refptr<base::SingleThreadTaskRunner> origin_runner_; // The Parameters for this Job. // Initialized on origin thread and then accessed from both threads. const Params* const params_; std::unique_ptr<ProxyResolverV8Tracing::Bindings> bindings_; // The callback to run (on the origin thread) when the Job finishes. // Should only be accessed from origin thread. CompletionOnceCallback callback_; // Flag to indicate whether the request has been cancelled. base::CancellationFlag cancelled_; // The operation that this Job is running. // Initialized on origin thread and then accessed from both threads. Operation operation_; // The DNS mode for this Job. // Initialized on origin thread, mutated on worker thread, and accessed // by both the origin thread and worker thread. bool blocking_dns_; // Used to block the worker thread on a DNS operation taking place on the // origin thread. base::WaitableEvent event_; // Map of DNS operations completed so far. Written into on the origin thread // and read on the worker thread. DnsCache dns_cache_; // The job holds a reference to itself to ensure that it remains alive until // either completion or cancellation. scoped_refptr<Job> owned_self_reference_; // ------------------------------------------------------- // State specific to CREATE_V8_RESOLVER. // ------------------------------------------------------- scoped_refptr<PacFileData> script_data_; std::unique_ptr<ProxyResolverV8>* resolver_out_; // ------------------------------------------------------- // State specific to GET_PROXY_FOR_URL. // ------------------------------------------------------- ProxyInfo* user_results_; // Owned by caller, lives on origin thread. GURL url_; ProxyInfo results_; // --------------------------------------------------------------------------- // State for ExecuteNonBlocking() // --------------------------------------------------------------------------- // These variables are used exclusively on the worker thread and are only // meaningful when executing inside of ExecuteNonBlocking(). // Whether this execution was abandoned due to a missing DNS dependency. bool abandoned_; // Number of calls made to ResolveDns() by this execution. int num_dns_; // Sequence of calls made to Alert() or OnError() by this execution. std::vector<AlertOrError> alerts_and_errors_; size_t alerts_and_errors_byte_cost_; // Approximate byte cost of the above. // Number of calls made to ResolveDns() by the PREVIOUS execution. int last_num_dns_; // Whether the current execution needs to be restarted in blocking mode. bool should_restart_with_blocking_dns_; // --------------------------------------------------------------------------- // State for pending DNS request. // --------------------------------------------------------------------------- // Handle to the outstanding request in the ProxyHostResolver, or NULL. // This is mutated and used on the origin thread, however it may be read by // the worker thread for some DCHECKS(). std::unique_ptr<ProxyHostResolver::Request> pending_dns_; // Indicates if the outstanding DNS request completed synchronously. Written // on the origin thread, and read by the worker thread. bool pending_dns_completed_synchronously_; // These are the inputs to DoDnsOperation(). Written on the worker thread, // read by the origin thread. std::string pending_dns_host_; ProxyResolveDnsOperation pending_dns_op_; }; class ProxyResolverV8TracingImpl : public ProxyResolverV8Tracing { public: ProxyResolverV8TracingImpl(std::unique_ptr<base::Thread> thread, std::unique_ptr<ProxyResolverV8> resolver, std::unique_ptr<Job::Params> job_params); ~ProxyResolverV8TracingImpl() override; // ProxyResolverV8Tracing overrides. void GetProxyForURL(const GURL& url, ProxyInfo* results, CompletionOnceCallback callback, std::unique_ptr<ProxyResolver::Request>* request, std::unique_ptr<Bindings> bindings) override; class RequestImpl : public ProxyResolver::Request { public: explicit RequestImpl(scoped_refptr<Job> job); ~RequestImpl() override; LoadState GetLoadState() override; private: scoped_refptr<Job> job_; }; private: // The worker thread on which the ProxyResolverV8 will be run. std::unique_ptr<base::Thread> thread_; std::unique_ptr<ProxyResolverV8> v8_resolver_; std::unique_ptr<Job::Params> job_params_; // The number of outstanding (non-cancelled) jobs. int num_outstanding_callbacks_; THREAD_CHECKER(thread_checker_); DISALLOW_COPY_AND_ASSIGN(ProxyResolverV8TracingImpl); }; Job::Job(const Job::Params* params, std::unique_ptr<ProxyResolverV8Tracing::Bindings> bindings) : origin_runner_(base::ThreadTaskRunnerHandle::Get()), params_(params), bindings_(std::move(bindings)), event_(base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED), last_num_dns_(0) { CheckIsOnOriginThread(); } void Job::StartCreateV8Resolver(const scoped_refptr<PacFileData>& script_data, std::unique_ptr<ProxyResolverV8>* resolver, CompletionOnceCallback callback) { CheckIsOnOriginThread(); resolver_out_ = resolver; script_data_ = script_data; // Script initialization uses blocking DNS since there isn't any // advantage to using non-blocking mode here. That is because the // parent ProxyResolutionService can't submit any ProxyResolve requests until // initialization has completed successfully! Start(CREATE_V8_RESOLVER, true /*blocking*/, std::move(callback)); } void Job::StartGetProxyForURL(const GURL& url, ProxyInfo* results, CompletionOnceCallback callback) { CheckIsOnOriginThread(); url_ = url; user_results_ = results; Start(GET_PROXY_FOR_URL, false /*non-blocking*/, std::move(callback)); } void Job::Cancel() { CheckIsOnOriginThread(); // There are several possibilities to consider for cancellation: // (a) The job has been posted to the worker thread, however script execution // has not yet started. // (b) The script is executing on the worker thread. // (c) The script is executing on the worker thread, however is blocked inside // of dnsResolve() waiting for a response from the origin thread. // (d) Nothing is running on the worker thread, however the host resolver has // a pending DNS request which upon completion will restart the script // execution. // (e) The worker thread has a pending task to restart execution, which was // posted after the DNS dependency was resolved and saved to local cache. // (f) The script execution completed entirely, and posted a task to the // origin thread to notify the caller. // (g) The job is already completed. // // |cancelled_| is read on both the origin thread and worker thread. The // code that runs on the worker thread is littered with checks on // |cancelled_| to break out early. // If the job already completed, there is nothing to be cancelled. if (callback_.is_null()) return; cancelled_.Set(); ReleaseCallback(); // Note we only mutate |pending_dns_| if it is non-null. If it is null, the // worker thread may be about to request a new DNS resolution. This avoids a // race condition with the DCHECK in PostDnsOperationAndWait(). // See https://crbug.com/699562. if (pending_dns_) pending_dns_.reset(); // The worker thread might be blocked waiting for DNS. event_.Signal(); bindings_.reset(); owned_self_reference_ = nullptr; } LoadState Job::GetLoadState() const { CheckIsOnOriginThread(); if (pending_dns_) return LOAD_STATE_RESOLVING_HOST_IN_PAC_FILE; return LOAD_STATE_RESOLVING_PROXY_FOR_URL; } Job::~Job() { DCHECK(!pending_dns_); DCHECK(callback_.is_null()); DCHECK(!bindings_); } void Job::CheckIsOnWorkerThread() const { DCHECK(params_->worker_task_runner->BelongsToCurrentThread()); } void Job::CheckIsOnOriginThread() const { DCHECK(origin_runner_->BelongsToCurrentThread()); } void Job::SetCallback(CompletionOnceCallback callback) { CheckIsOnOriginThread(); DCHECK(callback_.is_null()); (*params_->num_outstanding_callbacks)++; callback_ = std::move(callback); } void Job::ReleaseCallback() { CheckIsOnOriginThread(); CHECK_GT(*params_->num_outstanding_callbacks, 0); (*params_->num_outstanding_callbacks)--; callback_.Reset(); // For good measure, clear this other user-owned pointer. user_results_ = nullptr; } ProxyResolverV8* Job::v8_resolver() { return params_->v8_resolver; } const scoped_refptr<base::SingleThreadTaskRunner>& Job::worker_task_runner() { return params_->worker_task_runner; } ProxyHostResolver* Job::host_resolver() { return bindings_->GetHostResolver(); } void Job::NotifyCaller(int result) { CheckIsOnWorkerThread(); origin_runner_->PostTask( FROM_HERE, base::BindOnce(&Job::NotifyCallerOnOriginLoop, this, result)); } void Job::NotifyCallerOnOriginLoop(int result) { CheckIsOnOriginThread(); if (cancelled_.IsSet()) return; DispatchBufferedAlertsAndErrors(); // This isn't the ordinary execution flow, however it is exercised by // unit-tests. if (cancelled_.IsSet()) return; DCHECK(!callback_.is_null()); DCHECK(!pending_dns_); if (operation_ == GET_PROXY_FOR_URL) { *user_results_ = results_; } CompletionOnceCallback callback = std::move(callback_); ReleaseCallback(); std::move(callback).Run(result); bindings_.reset(); owned_self_reference_ = nullptr; } void Job::Start(Operation op, bool blocking_dns, CompletionOnceCallback callback) { CheckIsOnOriginThread(); operation_ = op; blocking_dns_ = blocking_dns; SetCallback(std::move(callback)); owned_self_reference_ = this; worker_task_runner()->PostTask( FROM_HERE, blocking_dns_ ? base::Bind(&Job::ExecuteBlocking, this) : base::Bind(&Job::ExecuteNonBlocking, this)); } void Job::ExecuteBlocking() { CheckIsOnWorkerThread(); DCHECK(blocking_dns_); if (cancelled_.IsSet()) return; NotifyCaller(ExecuteProxyResolver()); } void Job::ExecuteNonBlocking() { CheckIsOnWorkerThread(); DCHECK(!blocking_dns_); if (cancelled_.IsSet()) return; // Reset state for the current execution. abandoned_ = false; num_dns_ = 0; alerts_and_errors_.clear(); alerts_and_errors_byte_cost_ = 0; should_restart_with_blocking_dns_ = false; int result = ExecuteProxyResolver(); if (should_restart_with_blocking_dns_) { DCHECK(!blocking_dns_); DCHECK(abandoned_); blocking_dns_ = true; ExecuteBlocking(); return; } if (abandoned_) return; NotifyCaller(result); } int Job::ExecuteProxyResolver() { TRACE_EVENT0(NetTracingCategory(), "Job::ExecuteProxyResolver"); int result = ERR_UNEXPECTED; // Initialized to silence warnings. switch (operation_) { case CREATE_V8_RESOLVER: { std::unique_ptr<ProxyResolverV8> resolver; result = ProxyResolverV8::Create(script_data_, this, &resolver); if (result == OK) *resolver_out_ = std::move(resolver); break; } case GET_PROXY_FOR_URL: { result = v8_resolver()->GetProxyForURL( url_, // Important: Do not write directly into |user_results_|, since if the // request were to be cancelled from the origin thread, must guarantee // that |user_results_| is not accessed anymore. &results_, this); break; } } return result; } bool Job::ResolveDns(const std::string& host, ProxyResolveDnsOperation op, std::string* output, bool* terminate) { if (cancelled_.IsSet()) { *terminate = true; return false; } if ((op == ProxyResolveDnsOperation::DNS_RESOLVE || op == ProxyResolveDnsOperation::DNS_RESOLVE_EX) && host.empty()) { // a DNS resolve with an empty hostname is considered an error. return false; } return blocking_dns_ ? ResolveDnsBlocking(host, op, output) : ResolveDnsNonBlocking(host, op, output, terminate); } void Job::Alert(const base::string16& message) { HandleAlertOrError(true, -1, message); } void Job::OnError(int line_number, const base::string16& error) { HandleAlertOrError(false, line_number, error); } bool Job::ResolveDnsBlocking(const std::string& host, ProxyResolveDnsOperation op, std::string* output) { CheckIsOnWorkerThread(); // Check if the DNS result for this host has already been cached. bool rv; if (GetDnsFromLocalCache(host, op, output, &rv)) { // Yay, cache hit! return rv; } if (dns_cache_.size() >= kMaxUniqueResolveDnsPerExec) { // Safety net for scripts with unexpectedly many DNS calls. // We will continue running to completion, but will fail every // subsequent DNS request. return false; } if (!PostDnsOperationAndWait(host, op, nullptr)) return false; // Was cancelled. CHECK(GetDnsFromLocalCache(host, op, output, &rv)); return rv; } bool Job::ResolveDnsNonBlocking(const std::string& host, ProxyResolveDnsOperation op, std::string* output, bool* terminate) { CheckIsOnWorkerThread(); if (abandoned_) { // If this execution was already abandoned can fail right away. Only 1 DNS // dependency will be traced at a time (for more predictable outcomes). return false; } num_dns_ += 1; // Check if the DNS result for this host has already been cached. bool rv; if (GetDnsFromLocalCache(host, op, output, &rv)) { // Yay, cache hit! return rv; } if (num_dns_ <= last_num_dns_) { // The sequence of DNS operations is different from last time! ScheduleRestartWithBlockingDns(); *terminate = true; return false; } if (dns_cache_.size() >= kMaxUniqueResolveDnsPerExec) { // Safety net for scripts with unexpectedly many DNS calls. return false; } DCHECK(!should_restart_with_blocking_dns_); bool completed_synchronously; if (!PostDnsOperationAndWait(host, op, &completed_synchronously)) return false; // Was cancelled. if (completed_synchronously) { CHECK(GetDnsFromLocalCache(host, op, output, &rv)); return rv; } // Otherwise if the result was not in the cache, then a DNS request has // been started. Abandon this invocation of FindProxyForURL(), it will be // restarted once the DNS request completes. abandoned_ = true; *terminate = true; last_num_dns_ = num_dns_; return false; } bool Job::PostDnsOperationAndWait(const std::string& host, ProxyResolveDnsOperation op, bool* completed_synchronously) { // Post the DNS request to the origin thread. It is safe to mutate // |pending_dns_host_| and |pending_dns_op_| because there cannot be another // DNS operation in progress or scheduled. DCHECK(!pending_dns_); pending_dns_host_ = host; pending_dns_op_ = op; origin_runner_->PostTask(FROM_HERE, base::BindOnce(&Job::DoDnsOperation, this)); event_.Wait(); event_.Reset(); if (cancelled_.IsSet()) return false; if (completed_synchronously) *completed_synchronously = pending_dns_completed_synchronously_; return true; } void Job::DoDnsOperation() { CheckIsOnOriginThread(); DCHECK(!pending_dns_); if (cancelled_.IsSet()) return; bool is_myip_request = pending_dns_op_ == ProxyResolveDnsOperation::MY_IP_ADDRESS || pending_dns_op_ == ProxyResolveDnsOperation::MY_IP_ADDRESS_EX; pending_dns_ = host_resolver()->CreateRequest( is_myip_request ? GetHostName() : pending_dns_host_, pending_dns_op_); int result = pending_dns_->Start(base::BindOnce(&Job::OnDnsOperationComplete, this)); pending_dns_completed_synchronously_ = result != ERR_IO_PENDING; // Check if the request was cancelled as a side-effect of calling into the // HostResolver. This isn't the ordinary execution flow, however it is // exercised by unit-tests. if (cancelled_.IsSet()) return; if (pending_dns_completed_synchronously_) { OnDnsOperationComplete(result); } // Else OnDnsOperationComplete() will be called by host resolver on // completion. if (!blocking_dns_) { // The worker thread always blocks waiting to see if the result can be // serviced from cache before restarting. event_.Signal(); } } void Job::OnDnsOperationComplete(int result) { CheckIsOnOriginThread(); DCHECK(!cancelled_.IsSet()); SaveDnsToLocalCache(pending_dns_host_, pending_dns_op_, result, pending_dns_->GetResults()); pending_dns_.reset(); if (blocking_dns_) { event_.Signal(); return; } if (!blocking_dns_ && !pending_dns_completed_synchronously_) { // Restart. This time it should make more progress due to having // cached items. worker_task_runner()->PostTask( FROM_HERE, base::BindOnce(&Job::ExecuteNonBlocking, this)); } } void Job::ScheduleRestartWithBlockingDns() { CheckIsOnWorkerThread(); DCHECK(!should_restart_with_blocking_dns_); DCHECK(!abandoned_); DCHECK(!blocking_dns_); abandoned_ = true; // The restart will happen after ExecuteNonBlocking() finishes. should_restart_with_blocking_dns_ = true; } bool Job::GetDnsFromLocalCache(const std::string& host, ProxyResolveDnsOperation op, std::string* output, bool* return_value) { CheckIsOnWorkerThread(); DnsCache::const_iterator it = dns_cache_.find(MakeDnsCacheKey(host, op)); if (it == dns_cache_.end()) return false; *output = it->second; *return_value = !it->second.empty(); return true; } void Job::SaveDnsToLocalCache(const std::string& host, ProxyResolveDnsOperation op, int net_error, const std::vector<IPAddress>& addresses) { CheckIsOnOriginThread(); // Serialize the result into a string to save to the cache. std::string cache_value; if (net_error != OK) { cache_value = std::string(); } else if (op == ProxyResolveDnsOperation::DNS_RESOLVE || op == ProxyResolveDnsOperation::MY_IP_ADDRESS) { // dnsResolve() and myIpAddress() are expected to return a single IP // address. cache_value = addresses.front().ToString(); } else { // The *Ex versions are expected to return a semi-colon separated list. for (auto iter = addresses.begin(); iter != addresses.end(); ++iter) { if (!cache_value.empty()) cache_value += ";"; cache_value += iter->ToString(); } } dns_cache_[MakeDnsCacheKey(host, op)] = cache_value; } std::string Job::MakeDnsCacheKey(const std::string& host, ProxyResolveDnsOperation op) { return base::StringPrintf("%d:%s", op, host.c_str()); } void Job::HandleAlertOrError(bool is_alert, int line_number, const base::string16& message) { CheckIsOnWorkerThread(); if (cancelled_.IsSet()) return; if (blocking_dns_) { // In blocking DNS mode the events can be dispatched immediately. origin_runner_->PostTask( FROM_HERE, base::BindOnce(&Job::DispatchAlertOrErrorOnOriginThread, this, is_alert, line_number, message)); return; } // Otherwise in nonblocking mode, buffer all the messages until // the end. if (abandoned_) return; alerts_and_errors_byte_cost_ += sizeof(AlertOrError) + message.size() * 2; // If there have been lots of messages, enqueing could be expensive on // memory. Consider a script which does megabytes worth of alerts(). // Avoid this by falling back to blocking mode. if (alerts_and_errors_byte_cost_ > kMaxAlertsAndErrorsBytes) { alerts_and_errors_.clear(); ScheduleRestartWithBlockingDns(); return; } AlertOrError entry = {is_alert, line_number, message}; alerts_and_errors_.push_back(entry); } void Job::DispatchBufferedAlertsAndErrors() { CheckIsOnOriginThread(); for (size_t i = 0; i < alerts_and_errors_.size(); ++i) { const AlertOrError& x = alerts_and_errors_[i]; DispatchAlertOrErrorOnOriginThread(x.is_alert, x.line_number, x.message); } } void Job::DispatchAlertOrErrorOnOriginThread(bool is_alert, int line_number, const base::string16& message) { CheckIsOnOriginThread(); if (cancelled_.IsSet()) return; if (is_alert) { // ------------------- // alert // ------------------- VLOG(1) << "PAC-alert: " << message; bindings_->Alert(message); } else { // ------------------- // error // ------------------- if (line_number == -1) VLOG(1) << "PAC-error: " << message; else VLOG(1) << "PAC-error: " << "line: " << line_number << ": " << message; bindings_->OnError(line_number, message); } } ProxyResolverV8TracingImpl::ProxyResolverV8TracingImpl( std::unique_ptr<base::Thread> thread, std::unique_ptr<ProxyResolverV8> resolver, std::unique_ptr<Job::Params> job_params) : thread_(std::move(thread)), v8_resolver_(std::move(resolver)), job_params_(std::move(job_params)), num_outstanding_callbacks_(0) { job_params_->num_outstanding_callbacks = &num_outstanding_callbacks_; } ProxyResolverV8TracingImpl::~ProxyResolverV8TracingImpl() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); // Note, all requests should have been cancelled. CHECK_EQ(0, num_outstanding_callbacks_); // Join the worker thread. See http://crbug.com/69710. ScopedAllowThreadJoinForProxyResolverV8Tracing allow_thread_join; thread_.reset(); } ProxyResolverV8TracingImpl::RequestImpl::RequestImpl(scoped_refptr<Job> job) : job_(std::move(job)) {} ProxyResolverV8TracingImpl::RequestImpl::~RequestImpl() { job_->Cancel(); } LoadState ProxyResolverV8TracingImpl::RequestImpl::GetLoadState() { return job_->GetLoadState(); } void ProxyResolverV8TracingImpl::GetProxyForURL( const GURL& url, ProxyInfo* results, CompletionOnceCallback callback, std::unique_ptr<ProxyResolver::Request>* request, std::unique_ptr<Bindings> bindings) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(!callback.is_null()); scoped_refptr<Job> job = new Job(job_params_.get(), std::move(bindings)); request->reset(new RequestImpl(job)); job->StartGetProxyForURL(url, results, std::move(callback)); } class ProxyResolverV8TracingFactoryImpl : public ProxyResolverV8TracingFactory { public: ProxyResolverV8TracingFactoryImpl(); ~ProxyResolverV8TracingFactoryImpl() override; void CreateProxyResolverV8Tracing( const scoped_refptr<PacFileData>& pac_script, std::unique_ptr<ProxyResolverV8Tracing::Bindings> bindings, std::unique_ptr<ProxyResolverV8Tracing>* resolver, CompletionOnceCallback callback, std::unique_ptr<ProxyResolverFactory::Request>* request) override; private: class CreateJob; void RemoveJob(CreateJob* job); std::set<CreateJob*> jobs_; DISALLOW_COPY_AND_ASSIGN(ProxyResolverV8TracingFactoryImpl); }; class ProxyResolverV8TracingFactoryImpl::CreateJob : public ProxyResolverFactory::Request { public: CreateJob(ProxyResolverV8TracingFactoryImpl* factory, std::unique_ptr<ProxyResolverV8Tracing::Bindings> bindings, const scoped_refptr<PacFileData>& pac_script, std::unique_ptr<ProxyResolverV8Tracing>* resolver_out, CompletionOnceCallback callback) : factory_(factory), thread_(new base::Thread("Proxy Resolver")), resolver_out_(resolver_out), callback_(std::move(callback)), num_outstanding_callbacks_(0) { // Start up the thread. base::Thread::Options options; options.timer_slack = base::TIMER_SLACK_MAXIMUM; CHECK(thread_->StartWithOptions(options)); job_params_.reset( new Job::Params(thread_->task_runner(), &num_outstanding_callbacks_)); create_resolver_job_ = new Job(job_params_.get(), std::move(bindings)); create_resolver_job_->StartCreateV8Resolver( pac_script, &v8_resolver_, base::Bind( &ProxyResolverV8TracingFactoryImpl::CreateJob::OnV8ResolverCreated, base::Unretained(this))); } ~CreateJob() override { if (factory_) { factory_->RemoveJob(this); DCHECK(create_resolver_job_); create_resolver_job_->Cancel(); StopWorkerThread(); } DCHECK_EQ(0, num_outstanding_callbacks_); } void FactoryDestroyed() { factory_ = nullptr; create_resolver_job_->Cancel(); create_resolver_job_ = nullptr; StopWorkerThread(); } private: void OnV8ResolverCreated(int error) { DCHECK(factory_); if (error == OK) { job_params_->v8_resolver = v8_resolver_.get(); resolver_out_->reset(new ProxyResolverV8TracingImpl( std::move(thread_), std::move(v8_resolver_), std::move(job_params_))); } else { StopWorkerThread(); } factory_->RemoveJob(this); factory_ = nullptr; create_resolver_job_ = nullptr; std::move(callback_).Run(error); } void StopWorkerThread() { // Join the worker thread. See http://crbug.com/69710. ScopedAllowThreadJoinForProxyResolverV8Tracing allow_thread_join; thread_.reset(); } ProxyResolverV8TracingFactoryImpl* factory_; std::unique_ptr<base::Thread> thread_; std::unique_ptr<Job::Params> job_params_; scoped_refptr<Job> create_resolver_job_; std::unique_ptr<ProxyResolverV8> v8_resolver_; std::unique_ptr<ProxyResolverV8Tracing>* resolver_out_; CompletionOnceCallback callback_; int num_outstanding_callbacks_; DISALLOW_COPY_AND_ASSIGN(CreateJob); }; ProxyResolverV8TracingFactoryImpl::ProxyResolverV8TracingFactoryImpl() = default; ProxyResolverV8TracingFactoryImpl::~ProxyResolverV8TracingFactoryImpl() { for (auto* job : jobs_) { job->FactoryDestroyed(); } } void ProxyResolverV8TracingFactoryImpl::CreateProxyResolverV8Tracing( const scoped_refptr<PacFileData>& pac_script, std::unique_ptr<ProxyResolverV8Tracing::Bindings> bindings, std::unique_ptr<ProxyResolverV8Tracing>* resolver, CompletionOnceCallback callback, std::unique_ptr<ProxyResolverFactory::Request>* request) { std::unique_ptr<CreateJob> job(new CreateJob( this, std::move(bindings), pac_script, resolver, std::move(callback))); jobs_.insert(job.get()); *request = std::move(job); } void ProxyResolverV8TracingFactoryImpl::RemoveJob( ProxyResolverV8TracingFactoryImpl::CreateJob* job) { size_t erased = jobs_.erase(job); DCHECK_EQ(1u, erased); } } // namespace // static std::unique_ptr<ProxyResolverV8TracingFactory> ProxyResolverV8TracingFactory::Create() { return std::make_unique<ProxyResolverV8TracingFactoryImpl>(); } } // namespace net
8fca3c33c698d77aebd750198eb9879fac6bee09
25ee3becee33b6b2e77f325fb35cda90e563530b
/luogu/2.cpp
9a09acdfd9d32d9d301090c1169869c7af6386ff
[]
no_license
roy4801/solved_problems
fe973d8eb13ac4ebbb3bc8504a10fb1259da8d7a
b0de694516823a3ee8af88932452f40c287e9d10
refs/heads/master
2023-08-16T21:43:11.108043
2023-08-16T14:25:12
2023-08-16T14:25:12
127,760,119
5
1
null
null
null
null
UTF-8
C++
false
false
2,504
cpp
#include <iostream> #include <algorithm> #include <cstdio> using namespace std; enum Gacha_type { G_SINGLE, G_MULTI }; enum State { S_NONE, S_SINGLE, S_MULTI }; bool judge(int perm[], const int size, const int contiSingle, const int singleGacha, const int multiGacha, const int numMulti) { int single = 0; int state = S_NONE; bool pass = true; for(int i = 0; i < size; i++) { if(perm[i] == G_SINGLE) { single++; state = S_SINGLE; } else if(perm[i] == G_MULTI) { if(state == S_SINGLE) { if(single > contiSingle) { pass = false; break; } single = 0; } state = S_MULTI; } } if(single > contiSingle) pass = false; return pass; } int main(int argc, char const *argv[]) { #ifdef DBG freopen("2.in", "r", stdin); freopen("2.out", "w", stdout); #endif int multiGacha, numMulti; int singleGacha, contiSingle; while(scanf("%d %d %d %d", &multiGacha, &singleGacha, &numMulti, &contiSingle) != EOF) { const int c = multiGacha * numMulti + singleGacha; int europe[c]; // Input europe points for(int i = 0; i < c && scanf("%d", &europe[i]) != EOF; i++); #if 0 // for(int i = 0; i < c && (~printf("%d ", europe[i])); i++); // putchar('\n'); #endif const int size = singleGacha + numMulti; int max = 0; int first[numMulti]; int perm[size]; // init perm array for(int i = 0; i < singleGacha; i++) perm[i] = G_SINGLE; for(int i = singleGacha; i < numMulti + singleGacha; i++) perm[i] = G_MULTI; // Find comb that is max europe point do { if(judge(perm, size, contiSingle, singleGacha, multiGacha, numMulti)) { int tmp = 0, tmpIdx[numMulti], now = 0, nowMulti = 0; // Gacha! for(int i = 0; i < size; i++) { // printf("%d %d %d \n", perm[i], europe[now], now); if(perm[i] == G_SINGLE) { tmp += europe[now++]; } else if(perm[i] == G_MULTI) { tmp += europe[now]; tmpIdx[nowMulti++] = now+1; now += multiGacha; } } #if 0 for(int i = 0; i < size; i++) printf(i != size-1 ? "%d " : "%d\n", perm[i]); printf("%d\n\n", tmp); #endif if(max < tmp) { max = tmp; for(int i = 0; i < numMulti; i++) { first[i] = tmpIdx[i]; } } } } while(next_permutation(perm, perm + size)); // print max europe point printf("%d\n", max); for(int i = 0; i < numMulti; i++) printf(i != numMulti-1 ? "%d " : "%d\n", first[i]); } return 0; }
5f11e7a9cdc6846f0d6e08ff8b830fbe85e4db61
be2744f43865b43c3e9983a02e13426129b283c4
/Source/Engine/Graphics/Graphics_DX11PointerTypes.cpp
d17f71381cfb8d6ec62fa863497e071e4bea234d
[]
no_license
BryanRobertson/Alba
e94ef8f2b68c6f97023cbcf9ba977056fd38e739
cba532d0c7ef2631a240f70f07bf1d258867bb3a
refs/heads/master
2023-02-20T08:22:59.884655
2021-01-23T00:50:15
2021-01-23T00:50:15
112,042,539
0
0
null
null
null
null
UTF-8
C++
false
false
122
cpp
#include "Graphics_Precompile.hpp" #include "Graphics_DX11PointerTypes.hpp" namespace Alba { namespace Graphics { } }
3c2822a1a76e62a34e057409b79af928ce379001
99d1a4d39b57b132824bc0a17b962673e92caaa1
/CSacademy/CS Round 59/B.cpp
08e40899b9097ba7b8058dd21d128342b95a06e9
[]
no_license
SarotBu/SaBuZaContestStorage
3ef1fc128de3ec2b22d00a57bd94f4ffed53cad8
5533de541f5247e460056e6758d5ce80b5c458de
refs/heads/master
2021-08-23T02:50:42.935907
2017-12-02T17:53:04
2017-12-02T17:53:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
687
cpp
#include <bits/stdc++.h> using namespace std; #define MAXN 100005 int G1,G2,P1,P2; int bsearch(int l,int r,int w1){ int ret =0; while (l<=r){ int mid = (l+r)/2; int tmp = (100*w1 + 100*mid)/G2; if (tmp < P2){ l = mid + 1; }else if (tmp > P2){ r = mid - 1; }else{ ret = mid; l = mid + 1; } } return ret; } int main(){ int ans = 0; scanf ("%d%d%d%d",&G1,&P1,&G2,&P2); for (int i=0;i<=G1;i++){ if ((100*i)/G1 == P1){ int tmp = bsearch(0,G2 - G1,i); ans = max(ans,tmp); } } printf ("%d\n",ans); return 0; }
a6d4441cf621a68d102229b344d72ed56eb76c33
a55ef49d93a6251ba1a7c62fa3b738849ff1cb5a
/src/controller/renderer/LightRenderer.cpp
40d3d62c5a7801e54482e26f7119aff4bd047b99
[]
no_license
cansik/deep-vision-installation
b130c0e9a7d88a46a3d995e2ff21e6cc1c009568
197f801fbf0b6af1163dc33cb375a1da21eb0a7f
refs/heads/master
2021-06-27T09:15:45.288995
2020-12-29T12:16:02
2020-12-29T12:16:02
184,307,584
2
0
null
null
null
null
UTF-8
C++
false
false
982
cpp
// // Created by Florian on 06.12.17. // #include <model/light/Led.h> #include "LightRenderer.h" #include "../../util/MathUtils.h" LightRenderer::LightRenderer(Installation *installation, unsigned long frameRate) : TimeBasedController(frameRate, FRAMES_PER_SECOND) { this->installation = installation; } void LightRenderer::setup() { TimeBasedController::setup(); } void LightRenderer::timedLoop() { TimeBasedController::timedLoop(); for (auto i = 0; i < installation->getSize(); i++) { auto portal = installation->getSlice(i); render(portal); } } void LightRenderer::render(SlicePtr slice) { // send out data } float LightRenderer::mapToGlobalBrightnessRange(float value) { return MathUtils::map(value, LED_MIN_BRIGHTNESS, LED_MAX_BRIGHTNESS, installation->getSettings()->getMinBrightness(), installation->getSettings()->getMaxBrightness()); }
d7aadf395193ceaac198f5041fab38605972a696
232411e5462f43b38abd3f0e8078e9acb5a9fde7
/devel/.private/rotors_comm/include/rotors_comm/OctomapRequest.h
708e76a42289e9a2db766fa1435872d4727b8637
[]
no_license
Fengaleng/feng_ws
34d8ee5c208f240c24539984bc9d692ddf1808f9
a9fa2e871a43146a3a85a0c0a9481793539654eb
refs/heads/main
2023-03-29T17:25:42.110485
2021-03-30T14:50:24
2021-03-30T14:50:24
353,034,507
0
0
null
null
null
null
UTF-8
C++
false
false
7,038
h
// Generated by gencpp from file rotors_comm/OctomapRequest.msg // DO NOT EDIT! #ifndef ROTORS_COMM_MESSAGE_OCTOMAPREQUEST_H #define ROTORS_COMM_MESSAGE_OCTOMAPREQUEST_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <geometry_msgs/Point.h> #include <geometry_msgs/Point.h> namespace rotors_comm { template <class ContainerAllocator> struct OctomapRequest_ { typedef OctomapRequest_<ContainerAllocator> Type; OctomapRequest_() : bounding_box_origin() , bounding_box_lengths() , leaf_size(0.0) , publish_octomap(false) , filename() { } OctomapRequest_(const ContainerAllocator& _alloc) : bounding_box_origin(_alloc) , bounding_box_lengths(_alloc) , leaf_size(0.0) , publish_octomap(false) , filename(_alloc) { (void)_alloc; } typedef ::geometry_msgs::Point_<ContainerAllocator> _bounding_box_origin_type; _bounding_box_origin_type bounding_box_origin; typedef ::geometry_msgs::Point_<ContainerAllocator> _bounding_box_lengths_type; _bounding_box_lengths_type bounding_box_lengths; typedef double _leaf_size_type; _leaf_size_type leaf_size; typedef uint8_t _publish_octomap_type; _publish_octomap_type publish_octomap; typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _filename_type; _filename_type filename; typedef boost::shared_ptr< ::rotors_comm::OctomapRequest_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::rotors_comm::OctomapRequest_<ContainerAllocator> const> ConstPtr; }; // struct OctomapRequest_ typedef ::rotors_comm::OctomapRequest_<std::allocator<void> > OctomapRequest; typedef boost::shared_ptr< ::rotors_comm::OctomapRequest > OctomapRequestPtr; typedef boost::shared_ptr< ::rotors_comm::OctomapRequest const> OctomapRequestConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::rotors_comm::OctomapRequest_<ContainerAllocator> & v) { ros::message_operations::Printer< ::rotors_comm::OctomapRequest_<ContainerAllocator> >::stream(s, "", v); return s; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator==(const ::rotors_comm::OctomapRequest_<ContainerAllocator1> & lhs, const ::rotors_comm::OctomapRequest_<ContainerAllocator2> & rhs) { return lhs.bounding_box_origin == rhs.bounding_box_origin && lhs.bounding_box_lengths == rhs.bounding_box_lengths && lhs.leaf_size == rhs.leaf_size && lhs.publish_octomap == rhs.publish_octomap && lhs.filename == rhs.filename; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator!=(const ::rotors_comm::OctomapRequest_<ContainerAllocator1> & lhs, const ::rotors_comm::OctomapRequest_<ContainerAllocator2> & rhs) { return !(lhs == rhs); } } // namespace rotors_comm namespace ros { namespace message_traits { template <class ContainerAllocator> struct IsFixedSize< ::rotors_comm::OctomapRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::rotors_comm::OctomapRequest_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::rotors_comm::OctomapRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::rotors_comm::OctomapRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::rotors_comm::OctomapRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::rotors_comm::OctomapRequest_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::rotors_comm::OctomapRequest_<ContainerAllocator> > { static const char* value() { return "75da936d054df9de7938d7041a8a6ef2"; } static const char* value(const ::rotors_comm::OctomapRequest_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x75da936d054df9deULL; static const uint64_t static_value2 = 0x7938d7041a8a6ef2ULL; }; template<class ContainerAllocator> struct DataType< ::rotors_comm::OctomapRequest_<ContainerAllocator> > { static const char* value() { return "rotors_comm/OctomapRequest"; } static const char* value(const ::rotors_comm::OctomapRequest_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::rotors_comm::OctomapRequest_<ContainerAllocator> > { static const char* value() { return "\n" "geometry_msgs/Point bounding_box_origin\n" "\n" "geometry_msgs/Point bounding_box_lengths\n" "\n" "float64 leaf_size\n" "\n" "bool publish_octomap\n" "\n" "string filename\n" "\n" "================================================================================\n" "MSG: geometry_msgs/Point\n" "# This contains the position of a point in free space\n" "float64 x\n" "float64 y\n" "float64 z\n" ; } static const char* value(const ::rotors_comm::OctomapRequest_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::rotors_comm::OctomapRequest_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.bounding_box_origin); stream.next(m.bounding_box_lengths); stream.next(m.leaf_size); stream.next(m.publish_octomap); stream.next(m.filename); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct OctomapRequest_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::rotors_comm::OctomapRequest_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::rotors_comm::OctomapRequest_<ContainerAllocator>& v) { s << indent << "bounding_box_origin: "; s << std::endl; Printer< ::geometry_msgs::Point_<ContainerAllocator> >::stream(s, indent + " ", v.bounding_box_origin); s << indent << "bounding_box_lengths: "; s << std::endl; Printer< ::geometry_msgs::Point_<ContainerAllocator> >::stream(s, indent + " ", v.bounding_box_lengths); s << indent << "leaf_size: "; Printer<double>::stream(s, indent + " ", v.leaf_size); s << indent << "publish_octomap: "; Printer<uint8_t>::stream(s, indent + " ", v.publish_octomap); s << indent << "filename: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.filename); } }; } // namespace message_operations } // namespace ros #endif // ROTORS_COMM_MESSAGE_OCTOMAPREQUEST_H
e22971c2d70ea79e40b59754401c71819ee93ea2
9b7821a450ea0f44000a3316fe79af3e61496bef
/MS5803.cpp
3d501db04f3388a9a54248bb7c7e47060ae81f40
[]
no_license
tdnet12434/arduino_baro_spi_library
e7b179a227920376c719da5b124cb0b43a59f3af
383498fe6b19f2688f662cc272a659975ad6cfd5
refs/heads/master
2020-12-31T07:20:36.059356
2016-05-20T09:49:45
2016-05-20T09:49:45
59,283,554
0
0
null
null
null
null
UTF-8
C++
false
false
12,113
cpp
// // MS5803.cpp // // This library is for reading and writing to the MS5803 pressure/temperature sensor. // // Created by Victor Konshin on 4/10/13. // // // Copyright (c) 2013, Victor Konshin, [email protected] // for the DIY Dive Computer project www.diydivecomputer.com // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Ayerware Publishing 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 <COPYRIGHT HOLDER> 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. #include "MS5803.h" #include <SPI.h> // Sensor constants: #define SENSOR_CMD_RESET 0x1E #define SENSOR_CMD_ADC_READ 0x00 #define SENSOR_CMD_ADC_CONV 0x40 #define SENSOR_CMD_ADC_D1 0x00 #define SENSOR_CMD_ADC_D2 0x10 #define SENSOR_CMD_ADC_256 0x00 #define SENSOR_CMD_ADC_512 0x02 #define SENSOR_CMD_ADC_1024 0x04 #define SENSOR_CMD_ADC_2048 0x06 #define SENSOR_CMD_ADC_4096 0x08 #define SENSOR_I2C_ADDRESS 0x76 // If the CSB Pin (pin 3) is high, then the address is 0x76, if low, then it's 0x77 static unsigned int sensorCoefficients[8]; // calibration coefficients static unsigned long D1 = 0; // Stores uncompensated pressure value static unsigned long D2 = 0; // Stores uncompensated temperature value static float deltaTemp = 0; // These three variable are used for the conversion. static float sensorOffset = 0; static float sensitivity = 0; // Constructor when using SPI. MS5803::MS5803(uint8_t cs) { _cs = cs; interface = true; } // Constructor when using i2c. MS5803::MS5803() { interface = false; } boolean MS5803::initalizeSensor() { // Start the appropriate interface. pinMode( _cs, OUTPUT ); digitalWrite( _cs, HIGH ); SPI.begin(_cs); SPI.setBitOrder(_cs, MSBFIRST ); SPI.setClockDivider( _cs, SPI_CLOCK_DIV2 ); // Go fast or go home... // resetting the sensor on startup is important resetSensor(); // Read sensor coefficients - these will be used to convert sensor data into pressure and temp data for (int i = 0; i < 8; i++ ){ sensorCoefficients[ i ] = ms5803ReadCoefficient( i ); // read coefficients //Serial.print("Coefficient = "); //Serial.println(sensorCoefficients[ i ]); delay(10); } unsigned char p_crc = sensorCoefficients[ 7 ]; unsigned char n_crc = ms5803CRC4( sensorCoefficients ); // calculate the CRC _s_D1 = 0; _s_D2 = 0; _d1_count = 0; _d2_count = 0; timer=millis(); // If the calculated CRC does not match the returned CRC, then there is a data integrity issue. // Check the connections for bad solder joints or "flakey" cables. // If this issue persists, you may have a bad sensor. if ( p_crc != n_crc ) { return false; } return true; } void MS5803::readSensor() { /*const static int SIZE = 20; static float stack_time[20]; static int i=0;*/ // If power or speed are important, you can change the ADC resolution to a lower value. // Currently set to SENSOR_CMD_ADC_4096 - set to a lower defined value for lower resolution. //SerialUSB.println(state); if(state < 3) { D1 = ms5803CmdAdc( SENSOR_CMD_ADC_D1 + SENSOR_CMD_ADC_4096 ); // read uncompensated pressure //if(D1==0) {state=0; return;} /*_s_D1 += D1; _d1_count++; if (_d1_count == 128) { // we have summed 128 values. This only happens // when we stop reading the barometer for a long time // (more than 1.2 seconds) _s_D1 >>= 1; _d1_count = 64; }*/ } if(state >= 3) { D2 = ms5803CmdAdc( SENSOR_CMD_ADC_D2 + SENSOR_CMD_ADC_4096 ); // read uncompensated temperature //if(D2==0) {state=3; return;} /*_d2_count++; _s_D2 += D2; if (_d2_count == 32) { // we have summed 32 values. This only happens // when we stop reading the barometer for a long time // (more than 1.2 seconds) _s_D2 >>= 1; _d2_count = 16; }*/ } if(state==6) { /*uint32_t sD1, sD2; uint8_t d1count, d2count; sD1 = _s_D1; _s_D1 = 0; sD2 = _s_D2; _s_D2 = 0; d1count = _d1_count; _d1_count = 0; d2count = _d2_count; _d2_count = 0; if (d1count != 0) { D1 = ((float)sD1) / d1count; } if (d2count != 0) { D2 = ((float)sD2) / d2count; }*/ // calculate 1st order pressure and temperature correction factors (MS5803 1st order algorithm). deltaTemp = D2 - sensorCoefficients[5] * 256; sensorOffset = sensorCoefficients[2] * 65536 + ( deltaTemp * sensorCoefficients[4] )*0.0078125; sensitivity = sensorCoefficients[1] * 32768 + ( deltaTemp * sensorCoefficients[3] ) *0.00390625f; /*unsigned long time_now = millis(); stack_time[i]=time_now-last_cal_timer; i= (i+1)%SIZE;*/ //if(time_now-last_cal_timer < 200 || last_cal_timer==0) { // calculate 2nd order pressure and temperature (MS5803 2st order algorithm) temp = ( 2000 + (deltaTemp * sensorCoefficients[6] ) *1.1920929e-7 )*0.01; press = ( ( ( ( D1 * sensitivity ) *4.76837158e-7 - sensorOffset) *0.00003051757 ) *0.1 ); //} /*last_cal_timer=time_now;*/ //SerialUSB.print(stack_time[i]); /*deltaTemp = D2 - sensorCoefficients[5] * pow( 2, 8 ); sensorOffset = sensorCoefficients[2] * pow( 2, 16 ) + ( deltaTemp * sensorCoefficients[4] ) / pow( 2, 7 ); sensitivity = sensorCoefficients[1] * pow( 2, 15 ) + ( deltaTemp * sensorCoefficients[3] ) / pow( 2, 8 ); // calculate 2nd order pressure and temperature (MS5803 2st order algorithm) temp = ( 2000 + (deltaTemp * sensorCoefficients[6] ) / pow( 2, 23 ) ) / 100; press = ( ( ( ( D1 * sensitivity ) / pow( 2, 21 ) - sensorOffset) / pow( 2, 15 ) ) / 10 );*/ state=0; //SerialUSB.println("s"); } } // Sends a power on reset command to the sensor. // Should be done at powerup and maybe on a periodic basis (needs to confirm with testing). void MS5803::resetSensor() { SPI.setDataMode( SPI_MODE3 ); digitalWrite( _cs, LOW ); SPI.transfer( _cs,SENSOR_CMD_RESET , SPI_CONTINUE); delay( 10 ); digitalWrite( _cs, HIGH ); delay( 5 ); } // These sensors have coefficient values stored in ROM that are used to convert the raw temp/pressure data into degrees and mbars. // This method reads the coefficient at the index value passed. Valid values are 0-7. See datasheet for more info. unsigned int MS5803::ms5803ReadCoefficient(uint8_t index) { unsigned int result = 0; // result to return SPI.setDataMode(_cs, SPI_MODE3 ); digitalWrite( _cs, LOW ); // send the device the coefficient you want to read: SPI.transfer( _cs, 0xA0 + ( index * 2 ) , SPI_CONTINUE); // send a value of 0 to read the first byte returned: result = SPI.transfer(_cs, 0x00 , SPI_CONTINUE); result = result << 8; result |= SPI.transfer(_cs, 0x00 , SPI_CONTINUE); // and the second byte // take the chip select high to de-select: digitalWrite( _cs, HIGH ); return( result ); } // Coefficient at index 7 is a four bit CRC value for verifying the validity of the other coefficients. // The value returned by this method should match the coefficient at index 7. // If not there is something works with the sensor or the connection. unsigned char MS5803::ms5803CRC4(unsigned int n_prom[]) { int cnt; unsigned int n_rem; unsigned int crc_read; unsigned char n_bit; n_rem = 0x00; crc_read = sensorCoefficients[7]; sensorCoefficients[7] = ( 0xFF00 & ( sensorCoefficients[7] ) ); for (cnt = 0; cnt < 16; cnt++) { // choose LSB or MSB if ( cnt%2 == 1 ) n_rem ^= (unsigned short) ( ( sensorCoefficients[cnt>>1] ) & 0x00FF ); else n_rem ^= (unsigned short) ( sensorCoefficients[cnt>>1] >> 8 ); for ( n_bit = 8; n_bit > 0; n_bit-- ) { if ( n_rem & ( 0x8000 ) ) { n_rem = ( n_rem << 1 ) ^ 0x3000; } else { n_rem = ( n_rem << 1 ); } } } n_rem = ( 0x000F & ( n_rem >> 12 ) );// // final 4-bit reminder is CRC code sensorCoefficients[7] = crc_read; // restore the crc_read to its original place return ( n_rem ^ 0x00 ); // The calculated CRC should match what the device initally returned. } // Use this method to send commands to the sensor. Pretty much just used to read the pressure and temp data. unsigned long MS5803::ms5803CmdAdc(char cmd) { unsigned int result = 0; unsigned long returnedData = 0; if(state==0 || state==3) { SPI.setDataMode( _cs, SPI_MODE3 ); digitalWrite( _cs, LOW ); SPI.transfer( _cs, SENSOR_CMD_ADC_CONV + cmd , SPI_CONTINUE); digitalWrite( _cs, HIGH ); ++state; timer=millis(); } /*switch ( cmd & 0x0f ) { case SENSOR_CMD_ADC_256 : delay( 1 ); break; case SENSOR_CMD_ADC_512 : delay( 3 ); break; case SENSOR_CMD_ADC_1024: delay( 4 ); break; case SENSOR_CMD_ADC_2048: delay( 6 ); break; case SENSOR_CMD_ADC_4096: delay( 10 ); break; }*/ if(state==1 || state==4) { //if(MS5803_Ready(10)) { // timer=millis(); ++state; //} } if(state==2 || state==5) if(MS5803_Ready(13)) { digitalWrite( _cs, LOW ); SPI.transfer( _cs,SENSOR_CMD_ADC_READ , SPI_CONTINUE); returnedData = SPI.transfer( _cs, 0x00 , SPI_CONTINUE); result = 65536 * returnedData; returnedData = SPI.transfer( _cs, 0x00 , SPI_CONTINUE); result = result + 256 * returnedData; returnedData = SPI.transfer(_cs, 0x00 , SPI_CONTINUE); result = result + returnedData; digitalWrite( _cs, HIGH ); if(state==2) result_old[0] = result; if(state==5) result_old[1] = result; ++state; timer=millis(); }else{ if(state==2) result = result_old[0]; //for press if(state==5) result = result_old[1]; //for temp } /*else{ restate(); return result; }*/ return result; } void MS5803::restate() { state=0; timer=millis(); } uint8_t MS5803::MS5803_Ready(uint8_t wait) { unsigned long time_diff = millis()-timer; return((time_diff > wait /*&& time_diff < timeout*/) ? 1 : 0); }
4649b3d9701d0e7bb1ea56d230696220f36a5a84
d99cf41a7a1733d8c9302a085eb0d67ff5c1e5a1
/fourthsemester/lab7/OutOfRange.h
7a60ff8f72397267ae1ea2ddb1a3336d59b377da
[]
no_license
Brouney/cpp_uniwersity
b86c87b314d1e6ed195b78048dbe6638149d220d
e11ba813fa30c2105e19596520eb0ffec8fc7cae
refs/heads/master
2021-06-16T19:34:40.516355
2021-02-17T18:02:41
2021-02-17T18:02:41
162,703,106
0
0
null
2020-06-18T18:49:55
2018-12-21T10:51:37
C++
UTF-8
C++
false
false
355
h
#pragma once #include <iostream> #include <string> class Factory; #include "Factory.h" class OutOfRange{ public: OutOfRange(Factory* fact,double val,std::string str); void CleanFactory(); friend std::ostream& operator <<(std::ostream& ostr,OutOfRange& exception); Factory* factory; double value; std::string text; };
e1afca5a354a70ef5ff8fa02e29e1b181cf216a6
adc9a2c50d35bfb90a2de0db6b578e95633ce624
/Lab_12_3/Lab_12_3/lab_12.cpp
9d4964b584a72ce4bbff4ce8cf0db5712ab9a20d
[]
no_license
eugene-elk/C_Labs
a14f5b801b0e8c41d9ec3d3d2896b77354c9da46
1d1f43a500848bafbbbfd167885bad3455cc29b2
refs/heads/master
2023-03-31T21:22:15.168164
2019-01-08T16:22:30
2019-01-08T16:22:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
548
cpp
#include<stdio.h> // Course: Programming (C) // Lab 12. Input and output operations // Student: Lositsky E.I. Group: M3105 // Teacher: Povyshev V.V. // Created 29.11.2016 // Description: use the command line, read from a file int main(int argc, char** argv) { if (argc == 1) scanf("%s", argv[1]); FILE *in = fopen(argv[1], "r"); char c[100]; int i = 0; if(in != NULL) { while(fgets(c, 100, in) != NULL) { i++; if((i % 2) == 0) printf("%s", c); } fclose(in); printf("\n"); } else printf("\nerror\n"); return 0; }
ba38411a272d9bbd3386530cb70ba8fd83d57fb7
d14b5d78b72711e4614808051c0364b7bd5d6d98
/third_party/llvm-16.0/llvm/include/llvm/DebugInfo/PDB/Native/NativeSourceFile.h
c6653368bc0cee73ef4bb98ea1da2fafc01c44e4
[ "Apache-2.0" ]
permissive
google/swiftshader
76659addb1c12eb1477050fded1e7d067f2ed25b
5be49d4aef266ae6dcc95085e1e3011dad0e7eb7
refs/heads/master
2023-07-21T23:19:29.415159
2023-07-21T19:58:29
2023-07-21T20:50:19
62,297,898
1,981
306
Apache-2.0
2023-07-05T21:29:34
2016-06-30T09:25:24
C++
UTF-8
C++
false
false
1,382
h
//===- NativeSourceFile.h - Native source file implementation ---*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef LLVM_DEBUGINFO_PDB_NATIVE_NATIVESOURCEFILE_H #define LLVM_DEBUGINFO_PDB_NATIVE_NATIVESOURCEFILE_H #include "llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h" #include "llvm/DebugInfo/PDB/IPDBSourceFile.h" #include "llvm/DebugInfo/PDB/PDBTypes.h" namespace llvm { namespace pdb { class PDBSymbolCompiland; template <typename ChildType> class IPDBEnumChildren; class NativeSession; class NativeSourceFile : public IPDBSourceFile { public: explicit NativeSourceFile(NativeSession &Session, uint32_t FileId, const codeview::FileChecksumEntry &Checksum); std::string getFileName() const override; uint32_t getUniqueId() const override; std::string getChecksum() const override; PDB_Checksum getChecksumType() const override; std::unique_ptr<IPDBEnumChildren<PDBSymbolCompiland>> getCompilands() const override; private: NativeSession &Session; uint32_t FileId; const codeview::FileChecksumEntry Checksum; }; } // namespace pdb } // namespace llvm #endif
fc728e0d923a340eb4760d5227f2539552b90106
668ebb505f4d8932e67dfdd1b24a99edcd4d880e
/10864.cpp
217d11d767b126e65bf5d1ab580c66ee26ddbe96
[]
no_license
jpark1607/baekjoon_Cplusplus
06df940723ffb18ad142b267bae636e78ac610d8
8a1f4749d946bc256998ef9903098c8da6da1926
refs/heads/master
2021-07-13T03:47:29.002547
2021-07-11T14:01:10
2021-07-11T14:01:10
51,923,768
0
0
null
null
null
null
UTF-8
C++
false
false
275
cpp
#include <stdio.h> int main(void) { int nArr[1001] = {0, }; int N, M, i; int x, y; scanf("%d %d", &N, &M); for(i = 0; i < M; i++) { scanf("%d %d", &x, &y); nArr[x] += 1; nArr[y] += 1; } for(i = 1; i <= N; i++) { printf("%d\n", nArr[i]); } return 0; }
35d9d72b2207585e52e05f61d7d54b4b176bc73f
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_repos_function_2861_httpd-2.3.6.cpp
c2432cf461d6a5f218881057564398d56db0329e
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,474
cpp
static const char *include_config (cmd_parms *cmd, void *dummy, const char *name) { ap_directive_t *conftree = NULL; const char *conffile, *error; unsigned *recursion; int optional = cmd->cmd->cmd_data ? 1 : 0; void *data; apr_pool_userdata_get(&data, "ap_include_sentinel", cmd->pool); if (data) { recursion = data; } else { data = recursion = apr_palloc(cmd->pool, sizeof(*recursion)); *recursion = 0; apr_pool_userdata_setn(data, "ap_include_sentinel", NULL, cmd->pool); } if (++*recursion > AP_MAX_INCLUDE_DEPTH) { *recursion = 0; return apr_psprintf(cmd->pool, "Exceeded maximum include depth of %u, " "There appears to be a recursion.", AP_MAX_INCLUDE_DEPTH); } conffile = ap_server_root_relative(cmd->pool, name); if (!conffile) { *recursion = 0; return apr_pstrcat(cmd->pool, "Invalid Include path ", name, NULL); } error = ap_process_fnmatch_configs(cmd->server, conffile, &conftree, cmd->pool, cmd->temp_pool, optional); if (error) { *recursion = 0; return error; } *(ap_directive_t **)dummy = conftree; /* recursion level done */ if (*recursion) { --*recursion; } return NULL; }
0b3ff97653ff43ad47b5082f53d4df7a31e2ee7c
fae551eb54ab3a907ba13cf38aba1db288708d92
/chrome/browser/ash/borealis/borealis_disk_manager_dispatcher.cc
9a0edcaf9a39c2dbe0f6033a564ad8402c7b42af
[ "BSD-3-Clause" ]
permissive
xtblock/chromium
d4506722fc6e4c9bc04b54921a4382165d875f9a
5fe0705b86e692c65684cdb067d9b452cc5f063f
refs/heads/main
2023-04-26T18:34:42.207215
2021-05-27T04:45:24
2021-05-27T04:45:24
371,258,442
2
1
BSD-3-Clause
2021-05-27T05:36:28
2021-05-27T05:36:28
null
UTF-8
C++
false
false
3,193
cc
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/borealis/borealis_disk_manager_dispatcher.h" #include "chrome/browser/ash/borealis/borealis_disk_manager.h" #include "chrome/browser/ash/borealis/borealis_util.h" namespace borealis { // TODO(b/188863477): stop hardcoding these values once they're more // accessible. constexpr char kBorealisVmName[] = "borealis"; constexpr char kBorealisContainerName[] = "penguin"; BorealisDiskManagerDispatcher::BorealisDiskManagerDispatcher() : disk_manager_delegate_(nullptr) {} void BorealisDiskManagerDispatcher::GetDiskInfo( const std::string& origin_vm_name, const std::string& origin_container_name, base::OnceCallback<void(Expected<BorealisDiskManager::GetDiskInfoResponse, std::string>)> callback) { std::string error = ValidateRequest(origin_vm_name, origin_container_name); if (!error.empty()) { std::move(callback).Run( Expected<BorealisDiskManager::GetDiskInfoResponse, std::string>::Unexpected(std::move(error))); return; } disk_manager_delegate_->GetDiskInfo(std::move(callback)); } void BorealisDiskManagerDispatcher::RequestSpace( const std::string& origin_vm_name, const std::string& origin_container_name, uint64_t bytes_requested, base::OnceCallback<void(Expected<uint64_t, std::string>)> callback) { std::string error = ValidateRequest(origin_vm_name, origin_container_name); if (!error.empty()) { std::move(callback).Run( Expected<uint64_t, std::string>::Unexpected(std::move(error))); return; } disk_manager_delegate_->RequestSpace(bytes_requested, std::move(callback)); } void BorealisDiskManagerDispatcher::ReleaseSpace( const std::string& origin_vm_name, const std::string& origin_container_name, uint64_t bytes_to_release, base::OnceCallback<void(Expected<uint64_t, std::string>)> callback) { std::string error = ValidateRequest(origin_vm_name, origin_container_name); if (!error.empty()) { std::move(callback).Run( Expected<uint64_t, std::string>::Unexpected(std::move(error))); return; } disk_manager_delegate_->ReleaseSpace(bytes_to_release, std::move(callback)); } std::string BorealisDiskManagerDispatcher::ValidateRequest( const std::string& origin_vm_name, const std::string& origin_container_name) { if (origin_vm_name != kBorealisVmName || origin_container_name != kBorealisContainerName) { return "request does not originate from Borealis"; } if (!disk_manager_delegate_) { return "disk manager delegate not set, Borealis probably isn't running"; } return ""; } void BorealisDiskManagerDispatcher::SetDiskManagerDelegate( BorealisDiskManager* disk_manager) { DCHECK(!disk_manager_delegate_); disk_manager_delegate_ = disk_manager; } void BorealisDiskManagerDispatcher::RemoveDiskManagerDelegate( BorealisDiskManager* disk_manager) { DCHECK(disk_manager == disk_manager_delegate_); disk_manager_delegate_ = nullptr; } } // namespace borealis
a2938ea628946db0ccc44d2ebd39ea8f03464bc9
70b9b1c5a60179f6a6a16b02feef638bfe8f9445
/opencv/MFCApplication2.cpp
420574d34f7a8d846573e5fa3cfc211c64a987d5
[]
no_license
eddie9712/c-c-
d731e7410df1e3d4d53f86b32a6c460411c98839
46d15709965f3db42eba90f27fef808ecb4eab68
refs/heads/master
2020-03-28T22:28:09.095233
2020-02-27T12:37:41
2020-02-27T12:37:41
149,234,960
1
0
null
null
null
null
BIG5
C++
false
false
3,016
cpp
// MFCApplication2.cpp : 定義應用程式的類別行為。 // #include "stdafx.h" #include "MFCApplication2.h" #include "MFCApplication2Dlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMFCApplication2App BEGIN_MESSAGE_MAP(CMFCApplication2App, CWinApp) ON_COMMAND(ID_HELP, &CWinApp::OnHelp) END_MESSAGE_MAP() // CMFCApplication2App 建構 CMFCApplication2App::CMFCApplication2App() { // 支援重新啟動管理員 m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART; // TODO: 在此加入建構程式碼, // 將所有重要的初始設定加入 InitInstance 中 } // 僅有的一個 CMFCApplication2App 物件 CMFCApplication2App theApp; // CMFCApplication2App 初始設定 BOOL CMFCApplication2App::InitInstance() { // 假如應用程式資訊清單指定使用 ComCtl32.dll 6 (含) 以後版本, // 來啟動視覺化樣式,在 Windows XP 上,則需要 InitCommonControls()。 // 否則任何視窗的建立都將失敗。 INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // 設定要包含所有您想要用於應用程式中的 // 通用控制項類別。 InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); AfxEnableControlContainer(); // 建立殼層管理員,以防對話方塊包含 // 任何殼層樹狀檢視或殼層清單檢視控制項。 CShellManager *pShellManager = new CShellManager; // 啟動 [Windows 原生] 視覺化管理員可啟用 MFC 控制項中的主題 CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows)); // 標準初始設定 // 如果您不使用這些功能並且想減少 // 最後完成的可執行檔大小,您可以 // 從下列程式碼移除不需要的初始化常式, // 變更儲存設定值的登錄機碼 // TODO: 您應該適度修改此字串 // (例如,公司名稱或組織名稱) SetRegistryKey(_T("本機 AppWizard 所產生的應用程式")); CMFCApplication2Dlg dlg; m_pMainWnd = &dlg; INT_PTR nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: 在此放置於使用 [確定] 來停止使用對話方塊時 // 處理的程式碼 } else if (nResponse == IDCANCEL) { // TODO: 在此放置於使用 [取消] 來停止使用對話方塊時 // 處理的程式碼 } else if (nResponse == -1) { TRACE(traceAppMsg, 0, "警告: 對話方塊建立失敗,因此,應用程式意外終止。\n"); TRACE(traceAppMsg, 0, "警告: 如果您要在對話方塊上使用 MFC 控制項,則無法 #define _AFX_NO_MFC_CONTROLS_IN_DIALOGS。\n"); } // 刪除上面所建立的殼層管理員。 if (pShellManager != NULL) { delete pShellManager; } #ifndef _AFXDLL ControlBarCleanUp(); #endif // 因為已經關閉對話方塊,傳回 FALSE,所以我們會結束應用程式, // 而非提示開始應用程式的訊息。 return FALSE; }
e5de6595b43aa7564a36de914fcd8cd36f4682c0
03c6ce32026cbc90d4fdf1fa34c219bbf795bccc
/VDraw/ordering/vNode.h
d0f56344d03fcbc7848545458fd1abb1f6bfc365
[]
no_license
zhangbo-tj/DynamicSketching
570d4f03608e1e7b910bc8bd9299d0b6a4537274
75b96b4484b08c13602ac81686981720d292a34c
refs/heads/master
2020-12-29T00:30:20.969954
2013-04-29T07:23:54
2013-04-29T07:23:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,086
h
#ifndef VNODE_H_351342151617124325 #define VNODE_H_351342151617124325 #include "Vec.h" #include <vector> #include <queue> #include "..\vCurve.h" // to draw #include <opencv/cv.h> #include <opencv/cxcore.h> // graph #ifndef Q_MOC_RUN #include "boost/graph/adjacency_list.hpp" #endif class vGraph; class vNode{ private: void init(); std::vector<int> v; // index const std::vector<vec>* vertices; // mesh data, stored elsewhere; one time use for now vCurve* stroke; // the stroke the node represent: elementary node float Dist(vec2 uc, vec2 u, vec2 v); float Dist(vec2 uc, vec2 u, vec2 vc, vec2 v); // distances between two line segments u and v public: int segmentID; // -2 for global (sim Hull) std::vector<int> coveredSegments; vec center; //vec2 controlPoint; //float lengthAlpha; int hsv_h; bool flag_pose;// for pose construction bool visited; // ============= leaf property ======================= bool isLeaf; // use supernode or not double entropy; double information; static float beta; static float lamda; static float fieldSize; double voting; // sperially for content reference (exsc approximates) // ============= supernode property ======================= // make super node, how to make two files include each other // seems working, use some forward declaration trick // and include .h in the other's cpp file vGraph* superNode; vNode(); vNode(int _segID); ~vNode(); void push_vertex_index(int); void setVertices(const std::vector<vec>* _vertices); void setCurve(vCurve*); vCurve* getCurve(); void computeCenter(); void draw(IplImage* img, CvScalar color, int rate=4, int LOD=10, bool output = false); // entropy double computeCurEntropy(const vGraph& ); double computeInformation(); double megaForce( vCurve* c1, vCurve* c2); double updateVoting(vGraph&); // if the node is chosen to put into the order, it needs to update the content reference's voting -> incremental entropy //void computeControlPoint();//--------------------new-----compute----------------------- void setH(int h); int getH(); }; #endif
3fc05cdbe1e47e3b0960a975afe7042f8a69d749
c8687d68998dd09ed8949fe0ef5e4f0b0dd3ad4a
/HordeMode/Source/HordeMode/Private/States/SPlayerState.cpp
28d01685083b9b1bc7b4458247551f05abf36dd3
[]
no_license
jamiea483/HordeGame
8f6751c2baecf8a080d198d11dac4d951f032269
67ffb4f8bc8ea0f6a1d23d387df6bb4aa0f14789
refs/heads/master
2021-08-06T18:15:21.879094
2020-09-24T19:34:04
2020-09-24T19:34:04
213,255,205
0
0
null
null
null
null
UTF-8
C++
false
false
347
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "States/SPlayerState.h" #include "Net/UnrealNetwork.h" void ASPlayerState::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(ASPlayerState, Kills); }
8b2640cf2faf0f4c6259302f7c6b83b3fa045ede
b5002ee01603c8bc033e2650faba777c944dd9c7
/source/ui/sidebar/inference.cpp
051063f450f778ab1f641c57bb6ea62d138327db
[ "Apache-2.0", "MIT" ]
permissive
zhiayang/peirce-alpha
826b4783eb53d1f292aa643ddcc6efbf31eef3b3
49931a234ba173ed7ea4bdcca9949f28d64d7b4f
refs/heads/master
2023-04-15T04:31:39.575268
2021-05-04T18:53:12
2021-05-04T18:53:12
350,060,638
1
0
null
null
null
null
UTF-8
C++
false
false
4,783
cpp
// inference.cpp // Copyright (c) 2021, zhiayang // Licensed under the Apache License Version 2.0. #include "ui.h" #include "alpha.h" #include "imgui/imgui.h" namespace imgui = ImGui; using namespace alpha; namespace ui { Styler flash_style(int button); char* get_prop_name(); size_t get_prop_capacity(); Styler disabled_style(bool disabled); Styler toggle_enabled_style(bool enabled); Styler disabled_style_but_dont_disable(bool disabled); zbuf::str_view insert_prop_button(int shortcut_num, bool enabled); static bool use_prop_name = false; bool insert_with_prop_name() { return use_prop_name; } void inferModeChanged(Graph* graph, bool active) { (void) graph; (void) active; } void perform_insertion(Graph* graph, Item* parent) { if(use_prop_name) { auto prop = zbuf::str_view(get_prop_name(), strlen(get_prop_name())); if(prop.length() == 0) return; alpha::insertAtOddDepth(graph, parent, Item::var(prop)); } else { if(!alpha::haveIterationTarget(graph)) return; auto thing = graph->iteration_target->clone(); alpha::insertAtOddDepth(graph, parent, thing); } } void inference_tools(Graph* graph) { imgui::PushID("__scope_infer"); auto geom = geometry::get(); auto& theme = ui::theme(); auto& sel = selection(); imgui::Text("inference"); imgui::Dummy(lx::vec2(4)); imgui::Indent(); { { auto s = disabled_style(!alpha::canInsert(graph, get_prop_name(), insert_with_prop_name())); auto ss = flash_style(SB_BUTTON_INSERT); bool insert = imgui::Button("1 \uf055 insert "); imgui::Indent(14); { s.pop(); ss.pop(); { auto ss = disabled_style_but_dont_disable(use_prop_name); if(imgui::RadioButtonEx("iter target", !use_prop_name, 11)) use_prop_name = false; } { auto ss = disabled_style_but_dont_disable(!use_prop_name); if(imgui::RadioButtonEx("fresh: ", use_prop_name, 11)) use_prop_name = true; imgui::SameLine(); auto s = Styler(); imgui::SetNextItemWidth(64); s.push(ImGuiCol_FrameBg, theme.textFieldBg); imgui::InputTextWithHint("", " prop", get_prop_name(), get_prop_capacity()); } } imgui::Unindent(14); if(insert && sel.count() == 1) perform_insertion(graph, sel[0]); } // insert anything into an odd depth #if 0 if(auto prop = insert_prop_button(1, alpha::canInsert(graph, get_prop_name())); !prop.empty() || alpha::haveIterationTarget(graph)) { alpha::insertAtOddDepth(graph, /* parent: */ sel.empty() ? graph->iteration_target : sel[0], Item::var(prop)); } #endif { // fa-minus-circle auto s = disabled_style(!alpha::canErase(graph)); auto ss = flash_style(SB_BUTTON_ERASE); if(imgui::Button("2 \uf056 erase ")) alpha::eraseFromEvenDepth(graph, sel[0]); } } imgui::Unindent(); imgui::NewLine(); imgui::Text("double cut"); imgui::Dummy(lx::vec2(4)); imgui::Indent(); { { auto s = disabled_style(!alpha::canInsertDoubleCut(graph)); auto ss = flash_style(SB_BUTTON_DBL_ADD); if(imgui::Button("3 \uf5ff add ")) alpha::insertDoubleCut(graph, sel); } { auto s = disabled_style(!alpha::canRemoveDoubleCut(graph)); auto ss = flash_style(SB_BUTTON_DBL_DEL); if(imgui::Button("4 \uf5fe remove ")) alpha::removeDoubleCut(graph, sel); } } imgui::Unindent(); imgui::NewLine(); imgui::Text("iteration"); imgui::Dummy(lx::vec2(4)); imgui::Indent(); { { bool desel = (sel.count() == 0 && graph->iteration_target != nullptr); // crosshairs auto s = disabled_style(!alpha::canSelect(graph)); auto ss = flash_style(SB_BUTTON_SELECT); if(imgui::Button(desel ? "5 \uf05b deselect " : "5 \uf05b select ")) alpha::selectTargetForIteration(graph, sel.count() == 1 ? sel[0] : nullptr); } { // map-marker-plus auto s = disabled_style(!alpha::canIterate(graph)); auto ss = flash_style(SB_BUTTON_ITER); if(imgui::Button("6 \uf60a iterate ")) alpha::iterate(graph, sel[0]); } { // map-marker-minus auto s = disabled_style(!alpha::canDeiterate(graph)); auto ss = flash_style(SB_BUTTON_DEITER); if(imgui::Button("7 \uf609 deiterate ")) alpha::deiterate(graph, sel[0]); } } imgui::Unindent(); if(alpha::haveIterationTarget(graph)) { auto curs = imgui::GetCursorPos(); imgui::SetCursorPos(lx::vec2(curs.x, geom.sidebar.size.y - 56)); imgui::TextUnformatted("iteration target"); } if(sel.count() == 1) { auto curs = imgui::GetCursorPos(); imgui::SetCursorPos(lx::vec2(curs.x, geom.sidebar.size.y - 34)); imgui::TextUnformatted(zpr::sprint("depth: {}", sel[0]->depth()).c_str()); } imgui::PopID(); } }
6c8906bb06131ea2e031654c63425a49bf0bc9bb
e858606ccacb9a78bfb48ca90b56d9469cff7a09
/RImageBook/src/thirdparty/x64/VTK/include/vtkShaderCodeLibrary.h
1f2f302a06646f176b0d5f2e81e618011c4b1fc4
[]
no_license
tkatsuki/rimagebook
51f41166e98d442f7b9e2226b65046586f95dfc8
d26a1502faf39804bf8cb06d1699de24e6d53d58
refs/heads/master
2021-01-19T17:59:07.539596
2015-06-29T21:12:57
2015-06-29T21:12:57
38,264,836
1
2
null
null
null
null
UTF-8
C++
false
false
2,599
h
/*========================================================================= Program: Visualization Toolkit Module: vtkShaderCodeLibrary.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkShaderCodeLibrary - Library for Hardware Shaders. // .SECTION Description // This class provides the hardware shader code. // .SECTION Thanks // Shader support in VTK includes key contributions by Gary Templet at // Sandia National Labs. #ifndef __vtkShaderCodeLibrary_h #define __vtkShaderCodeLibrary_h #include "vtkObject.h" class VTK_IO_EXPORT vtkShaderCodeLibrary : public vtkObject { public: static vtkShaderCodeLibrary* New(); vtkTypeMacro(vtkShaderCodeLibrary, vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Obtain the code for the shader with given name. // Note that Cg shader names are prefixed with CG and // GLSL shader names are prefixed with GLSL. // This method allocates memory. It's the responsibility // of the caller to free this memory. static char* GetShaderCode(const char* name); // Description: // Returns an array of pointers to char strings that are // the names of the shader codes provided by the library. // The end of the array is marked by a null pointer. static const char** GetListOfShaderCodeNames(); // Description: // Provides for registering shader code. This overrides the compiled in shader // codes. static void RegisterShaderCode(const char* name, const char* code); //BTX protected: vtkShaderCodeLibrary(); ~vtkShaderCodeLibrary(); private: vtkShaderCodeLibrary(const vtkShaderCodeLibrary&); // Not implemented. void operator=(const vtkShaderCodeLibrary&); // Not implemented. // vtkInternalCleanup is used to destroy Internal ptr when the application // exits. class vtkInternalCleanup { public: vtkInternalCleanup() {}; ~vtkInternalCleanup(); }; friend class vtkInternalCleanup; static vtkInternalCleanup Cleanup; // vtkInternal is used to maintain user registered shader codes. class vtkInternal; static vtkInternal* Internal; //ETX }; #endif
1d07bacdfc0fad95ad638fdcc975b8561aeef86e
1aa9e37e693d797bd72d29e29863fdc4c6667d01
/src/content/browser/renderer_host/media/video_capture_controller.h
1ab04ceb03832d167c6b1cc27e02f055cd81ba43
[ "Apache-2.0" ]
permissive
jgj212/osv-free
d22a6b27c7bee399873d8d53db711a5ab0d831a5
b81fee48bc8898fdc641a2e3c227957ed7e6445e
refs/heads/master
2020-03-25T08:43:08.483119
2018-02-28T14:19:13
2018-02-28T14:19:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,534
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 CONTENT_BROWSER_RENDERER_HOST_MEDIA_VIDEO_CAPTURE_CONTROLLER_H_ #define CONTENT_BROWSER_RENDERER_HOST_MEDIA_VIDEO_CAPTURE_CONTROLLER_H_ #include <list> #include <memory> #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/process/process.h" #include "content/browser/renderer_host/media/video_capture_controller_event_handler.h" #include "content/browser/renderer_host/media/video_capture_provider.h" #include "content/common/content_export.h" #include "content/common/media/video_capture.h" #include "content/public/common/media_stream_request.h" #include "media/capture/video/video_frame_receiver.h" #include "media/capture/video_capture_types.h" namespace content { class VideoCaptureDeviceLaunchObserver; // Implementation of media::VideoFrameReceiver that distributes received frames // to potentially multiple connected clients. // A call to CreateAndStartDeviceAsync() asynchronously brings up the device. If // CreateAndStartDeviceAsync() has been called, ReleaseDeviceAsync() must be // called before releasing the instance. // Instances must be RefCountedThreadSafe, because an owner // (VideoCaptureManager) wants to be able to release its reference during an // (asynchronously executing) run of CreateAndStartDeviceAsync(). To this end, // the owner passes in the shared ownership as part of |done_cb| into // CreateAndStartDeviceAsync(). class CONTENT_EXPORT VideoCaptureController : public media::VideoFrameReceiver, public VideoCaptureDeviceLauncher::Callbacks, public base::RefCountedThreadSafe<VideoCaptureController> { public: VideoCaptureController( const std::string& device_id, MediaStreamType stream_type, const media::VideoCaptureParams& params, std::unique_ptr<VideoCaptureDeviceLauncher> device_launcher); base::WeakPtr<VideoCaptureController> GetWeakPtrForIOThread(); // Start video capturing and try to use the resolution specified in |params|. // Buffers will be shared to the client as necessary. The client will continue // to receive frames from the device until RemoveClient() is called. void AddClient(VideoCaptureControllerID id, VideoCaptureControllerEventHandler* event_handler, media::VideoCaptureSessionId session_id, const media::VideoCaptureParams& params); // Stop video capture. This will take back all buffers held by by // |event_handler|, and |event_handler| shouldn't use those buffers any more. // Returns the session_id of the stopped client, or // kInvalidMediaCaptureSessionId if the indicated client was not registered. int RemoveClient(VideoCaptureControllerID id, VideoCaptureControllerEventHandler* event_handler); // Pause the video capture for specified client. void PauseClient(VideoCaptureControllerID id, VideoCaptureControllerEventHandler* event_handler); // Resume the video capture for specified client. // Returns true if the client will be resumed. bool ResumeClient(VideoCaptureControllerID id, VideoCaptureControllerEventHandler* event_handler); int GetClientCount() const; // Return true if there is client that isn't paused. bool HasActiveClient() const; // Return true if there is client paused. bool HasPausedClient() const; // API called directly by VideoCaptureManager in case the device is // prematurely closed. void StopSession(int session_id); // Return a buffer with id |buffer_id| previously given in // VideoCaptureControllerEventHandler::OnBufferReady. // If the consumer provided resource utilization // feedback, this will be passed here (-1.0 indicates no feedback). void ReturnBuffer(VideoCaptureControllerID id, VideoCaptureControllerEventHandler* event_handler, int buffer_id, double consumer_resource_utilization); const base::Optional<media::VideoCaptureFormat> GetVideoCaptureFormat() const; bool has_received_frames() const { return has_received_frames_; } // Implementation of media::VideoFrameReceiver interface: void OnNewBufferHandle( int buffer_id, std::unique_ptr<media::VideoCaptureDevice::Client::Buffer::HandleProvider> handle_provider) override; void OnFrameReadyInBuffer( int buffer_id, int frame_feedback_id, std::unique_ptr< media::VideoCaptureDevice::Client::Buffer::ScopedAccessPermission> buffer_read_permission, media::mojom::VideoFrameInfoPtr frame_info) override; void OnBufferRetired(int buffer_id) override; void OnError() override; void OnLog(const std::string& message) override; void OnStarted() override; void OnStartedUsingGpuDecode() override; // Implementation of VideoCaptureDeviceLauncher::Callbacks interface: void OnDeviceLaunched( std::unique_ptr<LaunchedVideoCaptureDevice> device) override; void OnDeviceLaunchFailed() override; void OnDeviceLaunchAborted() override; void OnDeviceConnectionLost(); void CreateAndStartDeviceAsync(const media::VideoCaptureParams& params, VideoCaptureDeviceLaunchObserver* callbacks, base::OnceClosure done_cb); void ReleaseDeviceAsync(base::OnceClosure done_cb); bool IsDeviceAlive() const; void GetPhotoState( media::VideoCaptureDevice::GetPhotoStateCallback callback) const; void SetPhotoOptions( media::mojom::PhotoSettingsPtr settings, media::VideoCaptureDevice::SetPhotoOptionsCallback callback); void TakePhoto(media::VideoCaptureDevice::TakePhotoCallback callback); void MaybeSuspend(); void Resume(); void RequestRefreshFrame(); void SetDesktopCaptureWindowIdAsync(gfx::NativeViewId window_id, base::OnceClosure done_cb); int serial_id() const { return serial_id_; } const std::string& device_id() const { return device_id_; } MediaStreamType stream_type() const { return stream_type_; } const media::VideoCaptureParams& parameters() const { return parameters_; } private: friend class base::RefCountedThreadSafe<VideoCaptureController>; struct ControllerClient; typedef std::list<std::unique_ptr<ControllerClient>> ControllerClients; class BufferContext { public: BufferContext( int buffer_context_id, int buffer_id, media::VideoFrameConsumerFeedbackObserver* consumer_feedback_observer, mojo::ScopedSharedBufferHandle handle); ~BufferContext(); BufferContext(BufferContext&& other); BufferContext& operator=(BufferContext&& other); int buffer_context_id() const { return buffer_context_id_; } int buffer_id() const { return buffer_id_; } bool is_retired() const { return is_retired_; } void set_is_retired() { is_retired_ = true; } void set_frame_feedback_id(int id) { frame_feedback_id_ = id; } void set_consumer_feedback_observer( media::VideoFrameConsumerFeedbackObserver* consumer_feedback_observer) { consumer_feedback_observer_ = consumer_feedback_observer; } void set_read_permission( std::unique_ptr< media::VideoCaptureDevice::Client::Buffer::ScopedAccessPermission> buffer_read_permission) { buffer_read_permission_ = std::move(buffer_read_permission); } void RecordConsumerUtilization(double utilization); void IncreaseConsumerCount(); void DecreaseConsumerCount(); bool HasConsumers() const { return consumer_hold_count_ > 0; } mojo::ScopedSharedBufferHandle CloneHandle(); private: int buffer_context_id_; int buffer_id_; bool is_retired_; int frame_feedback_id_; media::VideoFrameConsumerFeedbackObserver* consumer_feedback_observer_; mojo::ScopedSharedBufferHandle buffer_handle_; double max_consumer_utilization_; int consumer_hold_count_; std::unique_ptr< media::VideoCaptureDevice::Client::Buffer::ScopedAccessPermission> buffer_read_permission_; }; ~VideoCaptureController() override; // Find a client of |id| and |handler| in |clients|. ControllerClient* FindClient(VideoCaptureControllerID id, VideoCaptureControllerEventHandler* handler, const ControllerClients& clients); // Find a client of |session_id| in |clients|. ControllerClient* FindClient(int session_id, const ControllerClients& clients); std::vector<BufferContext>::iterator FindBufferContextFromBufferContextId( int buffer_context_id); std::vector<BufferContext>::iterator FindUnretiredBufferContextFromBufferId( int buffer_id); void OnClientFinishedConsumingBuffer(ControllerClient* client, int buffer_id, double consumer_resource_utilization); void ReleaseBufferContext( const std::vector<BufferContext>::iterator& buffer_state_iter); using EventHandlerAction = base::Callback<void(VideoCaptureControllerEventHandler* client, VideoCaptureControllerID id)>; void PerformForClientsWithOpenSession(EventHandlerAction action); const int serial_id_; const std::string device_id_; const MediaStreamType stream_type_; const media::VideoCaptureParams parameters_; std::unique_ptr<VideoCaptureDeviceLauncher> device_launcher_; std::unique_ptr<LaunchedVideoCaptureDevice> launched_device_; VideoCaptureDeviceLaunchObserver* device_launch_observer_; std::vector<BufferContext> buffer_contexts_; // All clients served by this controller. ControllerClients controller_clients_; // Takes on only the states 'STARTING', 'STARTED' and 'ERROR'. 'ERROR' is an // absorbing state which stops the flow of data to clients. VideoCaptureState state_; int next_buffer_context_id_ = 0; // True if the controller has received a video frame from the device. bool has_received_frames_; base::Optional<media::VideoCaptureFormat> video_capture_format_; base::WeakPtrFactory<VideoCaptureController> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(VideoCaptureController); }; } // namespace content #endif // CONTENT_BROWSER_RENDERER_HOST_MEDIA_VIDEO_CAPTURE_CONTROLLER_H_
e2608376691790fe3c0f160f50446c88b24b47a3
d15b49fce4b3f1a5e5c39a29b8ef86936bd02112
/Math Show.cpp
36acbae4e1531daa88a4402db40acd8a142afdf0
[]
no_license
ailyanlu1/Competitive-Programming-Solutions
45ad3e6a7812f6cac126463f7c1391566f2d4ec7
9016c740e18928be38b67470e125359058c203a5
refs/heads/master
2020-03-26T13:03:47.201438
2018-08-15T04:10:59
2018-08-15T04:10:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
959
cpp
#include <bits/stdc++.h> #define ll long long #define INF 0x3f3f3f3f #define MAXN 110 #define pii pair<int, int> #define mp make_pair #define f first #define s second #define vi vector<int> #define pb push_back #define max(a, b) (a) < (b) ? (b) : (a) #define min(a, b) (a) < (b) ? (a) : (b) int n, k, M, t[MAXN]; ll amount, res, sum, ans = -INF; ll Greedy (int time) { amount = (k + 1) * time; res = (time * sum); if (res > M) return 0; else if (res <= M) { for (int i=0; i<k; i++) { for (int j=time + 1; j<=n; j++) { if (res + t[i] <= M) { amount++; res += t[i]; } } } } return amount; } ll Solve () { for (int i=0; i<=n; i++) { ll total = Greedy(i); ans = max(ans, total); } return ans; } int main () { std::cin.sync_with_stdio(0); std::cin.tie(0); std::cin >> n >> k >> M; for (int i=0; i<k; i++) { std::cin >> t[i]; sum += t[i]; } std::sort(t, t + k); std::cout << Solve() << "\n"; return 0; }
94b989b20dfd40a44693349e098d540638dbf0be
ff3c9c264eed5ea19da08825a4531d9ae975c09c
/_site/tutorial/cpp/exemplos/vetor2d.cpp
4fba8ce968d2fa97682afa2e378d702873f4d529
[ "MIT" ]
permissive
agostinhobritojr/agostinhobritojr.github.io
a9ca0562aa83679ac94a4232924fdcc5afe24c11
2778002c29f1f376adb12ed5f37e18990478a363
refs/heads/master
2023-05-26T15:32:39.258165
2023-05-22T18:17:35
2023-05-22T18:17:35
145,466,097
3
6
NOASSERTION
2023-02-01T22:32:39
2018-08-20T20:16:50
HTML
UTF-8
C++
false
false
233
cpp
#include <iostream> #include "vetor2d.hpp" using namespace std; void Vetor2d::setX(float x_){ x = x_; } float Vetor2d::getX(void){ return x; } void Vetor2d::setY(float y_){ y = y_; } float Vetor2d::getY(void){ return y; }
aa5e29481648cee35b93fe8a3960a178a5f37af6
141afafcbdd8eed80094dd7a827a75990f14e47d
/NQueens.cpp
aaf798d26d5c899932bfaf7d0667ca511b39a0a2
[]
no_license
iAbhyuday/playground
fb327843263e301e0053a45c63c68e60604a6539
1a8ee080fe60dac1e0449574a0a101e9cf456044
refs/heads/master
2022-03-28T08:52:00.428575
2020-01-12T15:17:34
2020-01-12T15:17:34
142,501,447
0
0
null
null
null
null
UTF-8
C++
false
false
1,275
cpp
#include<iostream> #include<vector> #include<list> #include<set> using namespace std; bool Safe(bool board[12][12] ,int r,int c ,int n){ // column check for(int row=0;row<r;row++){ if(board[row][c]) return false;} // left diagonal check int x=r,y=c; while(x>=0 && y>=0){ if(board[x][y]) return false; x--; y--; } // right diagonal check x=r; y=c; while(x>=0 && y<n){ if(board[x][y]) return false; x--; y++; } return true; } bool Solve(bool board[12][12],int i,int n){ if(i==n){ for(int g=0;g<n;g++){ for(int h=0;h<n;h++){ if(board[g][h]) cout<<"Q "; else cout<<"_ "; } cout<<"\n"; } cout<<"\n"; // false is returned to view all possible configs. return false; } for(int j=0;j<n;j++){ if(Safe(board,i,j,n)){ board[i][j]=true; bool nextQueen = Solve(board,i+1,n); // can next Queen be placed for this position if(nextQueen) return true; } board[i][j]=false; //BackTrack } return false; } int main() { int n; printf("Enter the size of board : "); scanf("%d",&n); bool board[12][12] ={false}; Solve(board,0,n); return 0; }
173676d4fb56624ebd0e31c0bde7524e1cff1e64
9185ec6429d843816ec90da8d2249e3ba18ac6f1
/SPS/adminPanal.cpp
64b5fcb03cb157b81e54bcbfbb74067f74f83038
[]
no_license
tarqmamdouh/StudentPrerequisiteSystem
e15f7b8f64930ee44199f8223dea352075db438e
5e7f7490da479714387e2b3bd40af8e7a9983a1e
refs/heads/master
2020-12-02T18:15:26.493714
2017-07-07T06:22:02
2017-07-07T06:22:02
96,505,329
0
0
null
null
null
null
UTF-8
C++
false
false
27
cpp
#include "adminPanal.h"
ccd908cc276e1d0a66f39b216175040026873e5e
50f29ccc5e88488650735ab0f79330b44ac1ba6b
/sodium/node.h
dca9f76db87301a406ba66c90082d32309206175
[]
no_license
clinuxrulz/na-cxx
ef35e3b8de2daef2d1a53d56726a240328e5b08a
20bea1a5880ac1429b8e0122ee0314c5da268237
refs/heads/master
2021-01-25T11:49:00.817170
2018-03-01T12:42:21
2018-03-01T12:42:21
123,433,491
0
0
null
null
null
null
UTF-8
C++
false
false
140
h
#ifndef _SODIUM_NODE_H_ #define _SODIUM_NODE_H_ namespace sodium { struct Source; struct Node; } // end namespace sodium #endif
87c53ed2cc7458d4ef3b6b2af25a22e97d9173c5
e862f48c627b8effec2a25b37c590ca4f2649fc0
/branches/ming_branches/spectrallibrary/MappedSpecnets.cpp
ae695fee56a0cc04abd889f57c22a9292d6b4007
[]
no_license
Bandeira/sps
ec82a77c315cf1aff9761c801d1dc63cb5c5e9f0
1809945c9e5a6836a753a434d2c8570941130021
refs/heads/master
2016-09-01T08:18:34.221603
2015-12-10T23:56:52
2015-12-10T23:56:52
47,741,477
0
0
null
null
null
null
UTF-8
C++
false
false
26,265
cpp
/* * MappedSpecnets.cpp * * Created on: Mar 2, 2011 * Author: aguthals */ #include "MappedSpecnets.h" namespace specnets { MappedSpecnets::MappedSpecnets(void) { contigs = new vector<MappedContig> ; spectra = new vector<MappedSpectrum> ; } MappedSpecnets::~MappedSpecnets(void) { delete contigs; delete spectra; } /** * Maps this SPS project to proteins * @param sps_contigs specnets contigs * @param sps_components contig component information detailing which * spectra and which peaks were included in each contig * @param star_spectra PRM spectra assembled into contigs * @param matchma_overlaps matchma output detailing where mapped * contigs overlap on their protein * @param matchma_prot_idx matchma output detailing which contigs are * mapped to which proteins * @param _proteins sequence of target proteins in same order as matchma * saw them * @param protein_spectra target proteins as PRM spectra * @param spectrum_ids sequence of PRM spectra annotations in same order * as in_star_spectra. Must be in specnets format * @param input_ion_types loaded MS2ScoringModel with b and y ion types * specified * @param in_peak_tol peak tolerance in Da * @return */ void MappedSpecnets::mapProt(SpecSet* sps_contigs, abinfo_t* sps_components, SpecSet* star_spectra, SpecSet* matchma_overlaps, vector<vector<int> >* matchma_prot_idx, vector<string>* _proteins, SpecSet* protein_spectra, vector<string>* spectrum_ids, MS2ScoringModel& input_ion_types, float peak_tol) { contigs->resize(sps_contigs->size()); spectra->resize(star_spectra->size()); proteins = _proteins; peptides = spectrum_ids; star_spectra->addZPMpeaks(peak_tol, 0, true); vector<bool> stars_reversed(star_spectra->size(), false); for (abinfo_t::iterator seqIt = sps_components->begin(); seqIt != sps_components->end(); seqIt++) { if (seqIt->second.second.size() == 0) continue; for (int j = 0; j < seqIt->second.second.size(); j++) { pair<vector<int> , vector<double> >* vert = &seqIt->second.second[j]; for (int k = 0; k < vert->first.size(); k++) { int specIdx = (*vert).first[k]; float mass = (*vert).second[k]; /*if (specIdx == 16299) { DEBUG_MSG("Contig " << seqIt->first << " peak=" << j << " spectrum " << specIdx << " w/ mass " << mass); }*/ int peakIdx = (*star_spectra)[specIdx].findClosest(mass); if (!MZRange::EqualWithinRange(mass, (*star_spectra)[specIdx][peakIdx][0], 0.01)) { /*if (specIdx == 16299) { DEBUG_MSG("Peak mass " << mass << " causing reversal of spectrum " << 11366 << " in contig " << seqIt->first); }*/ stars_reversed[specIdx] = true; } } } } for (int i = 0; i < spectra->size(); i++) { (*spectra)[i].mapProt(star_spectra, i, (*spectrum_ids)[i], proteins, stars_reversed[i], input_ion_types, peak_tol); } for (int i = 0; i < contigs->size(); i++) { (*contigs)[i].mapProt(sps_contigs, i, sps_components, matchma_overlaps, matchma_prot_idx, spectra, protein_spectra, peak_tol); } for (int p = 0; p < proteins->size(); p++) { if ((*proteins)[p].length() > 0) { target_prots.insert(p); } } } /** * @return number of contigs w/ > 0 peaks */ int MappedSpecnets::getNumContigs(void) { int count = 0; for (int i = 0; i < contigs->size(); i++) { count += ((*contigs)[i].length > 0) ? 1 : 0; } return count; } /** * @return number of spectra w/ > 0 peaks */ int MappedSpecnets::getNumSpectra(void) { int count = 0; for (int i = 0; i < spectra->size(); i++) { count += ((*spectra)[i].size() > 0) ? 1 : 0; } return count; } /** * @return number of identified spectra */ int MappedSpecnets::getNumSpecIdent(void) { int count = 0; for (int i = 0; i < spectra->size(); i++) { count += ((*spectra)[i].identified) ? 1 : 0; } return count; } /** * @return number of spectra mapped to target proteins */ int MappedSpecnets::getNumSpecMapped(int prot_idx) { int count = 0; for (int i = 0; i < spectra->size(); i++) { if (prot_idx < 0 && (*spectra)[i].mapped) { count++; } else if (prot_idx >= 0 && (*spectra)[i].residueIdxs.count(prot_idx) > 0) { count++; } } return count; } /** * @param prot_idx index of target protein or -1 to specify all proteins * @return number of contigs mapped to prot_idx by matchma or spectrum IDs */ int MappedSpecnets::getNumContigsMapped(int prot_idx) { int count = 0; for (int i = 0; i < contigs->size(); i++) { if ((*contigs)[i].length == 0) { continue; } if (prot_idx < 0 && (target_prots.count((*contigs)[i].vertProtIdx) > 0 || target_prots.count((*contigs)[i].starProtIdx) > 0)) { count++; } else if (prot_idx >= 0 && ((*contigs)[i].vertProtIdx == prot_idx || (*contigs)[i].starProtIdx == prot_idx)) { count++; } } return count; } /** * @param prot_idx index of target protein or -1 to specify all proteins * @return number of contigs mapped to prot_idx by matchma */ int MappedSpecnets::getNumContigsVertMapped(int prot_idx) { int count = 0; for (int i = 0; i < contigs->size(); i++) { if ((*contigs)[i].length == 0) { continue; } if (prot_idx < 0 && target_prots.count((*contigs)[i].vertProtIdx) > 0) { count++; } else if (prot_idx >= 0 && (*contigs)[i].vertProtIdx == prot_idx) { count++; } } return count; } /** * @param prot_idx index of target protein or -1 to specify all proteins * @return number of contigs mapped to prot_idx by spectrum IDs */ int MappedSpecnets::getNumContigsSpecMapped(int prot_idx) { int count = 0; for (int i = 0; i < contigs->size(); i++) { if ((*contigs)[i].length == 0) { continue; } if (prot_idx < 0 && target_prots.count((*contigs)[i].starProtIdx) > 0) { count++; } else if (prot_idx >= 0 && (*contigs)[i].starProtIdx == prot_idx) { count++; } } return count; } /** * @param prot_idx index of target protein or -1 to specify all proteins * @return number of contigs mapped to prot_idx by matchma and spectrum IDs */ int MappedSpecnets::getNumContigsVertSpecMapped(int prot_idx) { int count = 0; for (int i = 0; i < contigs->size(); i++) { if ((*contigs)[i].length == 0) { continue; } if (prot_idx < 0 && (target_prots.count((*contigs)[i].vertProtIdx) > 0 && target_prots.count((*contigs)[i].starProtIdx) > 0)) { count++; } else if (prot_idx >= 0 && ((*contigs)[i].vertProtIdx == prot_idx && (*contigs)[i].starProtIdx == prot_idx)) { count++; } } return count; } /** * @param prot_idx index of target protein or -1 to specify all proteins * @return percent of protein covered by identified spectra */ float MappedSpecnets::getPercSpecCov(int prot_idx) { vector<bool> deflt_vec(0); vector<vector<bool> > covered_bins(proteins->size(), deflt_vec); float numerator = 0; float denominator = 0; MappedSpectrum* spec; for (int p = 0; p < proteins->size(); p++) { if ((*proteins)[p].length() == 0 || (prot_idx >= 0 && p != prot_idx)) { continue; } covered_bins[p].resize((*proteins)[p].length(), false); denominator += (float) covered_bins[p].size(); for (int i = 0; i < spectra->size(); i++) { spec = &(*spectra)[i]; if (spec->size() == 0 || (!spec->mapped) || (spec->residueIdxs.count(p) == 0)) { continue; } for (list<int>::iterator startIt = spec->residueIdxs[p].begin(); startIt != spec->residueIdxs[p].end(); startIt++) { int start_idx = *startIt; int end_idx = start_idx + spec->AAPeptideSeq.length(); for (int r = start_idx; r < end_idx; r++) { if (!covered_bins[p][r]) { covered_bins[p][r] = true; numerator += 1.0; } } } } } return (numerator / denominator) * 100.0; } /** * @param prot_idx index of target protein or -1 to specify all proteins * @return percent of protein covered by matchma mapped contigs */ float MappedSpecnets::getPercSeqCov(int prot_idx) { vector<bool> deflt_vec(0); vector<vector<bool> > covered_bins(proteins->size(), deflt_vec); float numerator = 0; float denominator = 0; MappedContig* contig; set<int> prots_count; for (int p = 0; p < proteins->size(); p++) { if ((*proteins)[p].length() == 0 || (prot_idx >= 0 && p != prot_idx)) { continue; } covered_bins[p].resize((*proteins)[p].length(), false); prots_count.insert(p); //DEBUG_MSG("prot " << contig->vertProtIdx << " has size " << covered_bins[p].size()); denominator += (float) covered_bins[p].size(); } for (int i = 0; i < contigs->size(); i++) { contig = &(*contigs)[i]; if (contig->size() == 0 || (!contig->vertMapped) || (prots_count.count(contig->vertProtIdx) == 0)) { continue; } for (int r = contig->firstResidue; r <= contig->lastResidue; r++) { //if (r < 0 || r > covered_bins[contig->vertProtIdx].size()) { // DEBUG_MSG("invalid index " << r << " for prot " << contig->vertProtIdx); //} if (!covered_bins[contig->vertProtIdx][r]) { covered_bins[contig->vertProtIdx][r] = true; numerator += 1.0; } } } return (numerator / denominator) * 100.0; } /** * @param prot_idx index of target protein or -1 to specify all proteins * @return average number of contigs covering each covered residue */ float MappedSpecnets::getCovRedundancy(int prot_idx) { vector<bool> deflt_vec(0); vector<vector<bool> > covered_bins(proteins->size(), deflt_vec); float numerator = 0; float denominator = 0; set<int> prots_count; MappedContig* contig; for (int p = 0; p < proteins->size(); p++) { if ((*proteins)[p].length() == 0 || (prot_idx >= 0 && p != prot_idx)) { continue; } covered_bins[p].resize((*proteins)[p].length(), false); prots_count.insert(p); } for (int i = 0; i < contigs->size(); i++) { contig = &(*contigs)[i]; if ((!contig->vertMapped) || (prots_count.count(contig->vertProtIdx) == 0)) { continue; } for (int r = contig->firstResidue; r <= contig->lastResidue; r++) { if (!covered_bins[contig->vertProtIdx][r]) { covered_bins[contig->vertProtIdx][r] = true; denominator += 1.0; numerator += 1.0; } else { numerator += 1.0; } } } return numerator / denominator; } /** * @param prot_idx index of target protein or -1 to specify all proteins * @return number of spectra assembled into contigs mapping to protein by matchma or spectrum IDs */ int MappedSpecnets::getNumAssembledSpec(int prot_idx) { int count = 0; MappedContig* contig; for (int i = 0; i < contigs->size(); i++) { contig = &(*contigs)[i]; if (target_prots.count(contig->vertProtIdx) == 0 && target_prots.count(contig->starProtIdx) == 0) { continue; } if (prot_idx >= 0 && (contig->vertProtIdx != prot_idx) && (contig->starProtIdx != prot_idx)) { continue; } count += contig->numSpecs; } return count; } /** * @param prot_idx index of target protein or -1 to specify all proteins * @return average number of spectra per contig mapping to protein by matchma or spectrum IDs */ float MappedSpecnets::getSpecPerContig(int prot_idx) { float numerator = 0; float denominator = 0; MappedContig* contig; for (int i = 0; i < contigs->size(); i++) { contig = &(*contigs)[i]; if (target_prots.count(contig->vertProtIdx) == 0 && target_prots.count(contig->starProtIdx) == 0) { continue; } if (prot_idx >= 0 && (contig->vertProtIdx != prot_idx) && (contig->starProtIdx != prot_idx)) { continue; } numerator += (float) contig->numSpecs; denominator += 1.0; } return numerator / denominator; } /** * @param prot_idx index of target protein or -1 to specify all proteins * @return average number of peptides per contig mapping to protein by matchma or spectrum IDs */ float MappedSpecnets::getPepPerContig(int prot_idx) { float numerator = 0; float denominator = 0; MappedContig* contig; for (int i = 0; i < contigs->size(); i++) { contig = &(*contigs)[i]; if (target_prots.count(contig->vertProtIdx) == 0 && target_prots.count(contig->starProtIdx) == 0) { continue; } if (prot_idx >= 0 && (contig->vertProtIdx != prot_idx) && (contig->starProtIdx != prot_idx)) { continue; } numerator += (float) contig->numPeptides; denominator += 1.0; } return numerator / denominator; } /** * @param prot_idx index of target protein or -1 to specify all proteins * @return average Da of each contig mapping to protein by matchma or spectrum IDs */ float MappedSpecnets::getDaLengthPerContig(int prot_idx) { float numerator = 0; float denominator = 0; MappedContig* contig; for (int i = 0; i < contigs->size(); i++) { contig = &(*contigs)[i]; if (prot_idx < 0 && target_prots.count(contig->vertProtIdx) == 0 && target_prots.count(contig->starProtIdx) == 0) { continue; } if (prot_idx >= 0 && (contig->vertProtIdx != prot_idx) && (contig->starProtIdx != prot_idx)) { continue; } numerator += contig->abruijnVerts[contig->length - 1].getMass() - contig->abruijnVerts[0].getMass(); denominator += 1.0; } return numerator / denominator; } /** * @param prot_idx index of target protein or -1 to specify all proteins * @return average AA of each contig mapping to protein by matchma */ float MappedSpecnets::getAALengthPerContig(int prot_idx) { float numerator = 0; float denominator = 0; MappedContig* contig; for (int i = 0; i < contigs->size(); i++) { contig = &(*contigs)[i]; if (target_prots.count(contig->vertProtIdx) == 0) { continue; } if (prot_idx >= 0 && (contig->vertProtIdx != prot_idx)) { continue; } numerator += (float) (contig->lastResidue - contig->firstResidue + 1); denominator += 1.0; } return numerator / denominator; } /** * @param prot_idx index of target protein or -1 to specify all proteins * @return pair of longest contig (second) mapping to protein by matchma and its length (first) */ pair<int, int> MappedSpecnets::getLongestAAContig(int prot_idx) { int maxLength = -1; int maxIdx = -1; MappedContig* contig; for (int i = 0; i < contigs->size(); i++) { contig = &(*contigs)[i]; if (target_prots.count(contig->vertProtIdx) == 0) { continue; } if (prot_idx >= 0 && (contig->vertProtIdx != prot_idx)) { continue; } int length = contig->lastResidue - contig->firstResidue + 1; if (length > maxLength) { maxLength = length; maxIdx = i; } } return pair<int, int> (maxLength, maxIdx); } /** * @param prot_idx index of target protein or -1 to specify all proteins * @param label 0, 1, 2, or 3 * @return if label != 0, percent of abruijn vertices that have label out of * those that are annotated. if label == 0, percent of abruijn vertices * that have label out of those that are not annotated */ float MappedSpecnets::getPercVerts(int prot_idx, short label) { float numerator = 0; float denominator = 0; MappedContig* contig; for (int i = 0; i < contigs->size(); i++) { contig = &(*contigs)[i]; if (target_prots.count(contig->starProtIdx) == 0) { continue; } if (prot_idx >= 0 && (contig->starProtIdx != prot_idx)) { continue; } int checkC = 0; for (int j = 0; j < contig->length; j++) { if (label > 0 && contig->abruijnVerts[j].annotated) { denominator += 1.0; if (contig->abruijnVerts[j].label == label) { numerator += 1.0; checkC++; } } else if (label == 0) { denominator += 1.0; numerator += (contig->abruijnVerts[j].annotated) ? 0.0 : 1.0; } } /* if (label == 1 && checkC > 5) { DEBUG_MSG("Check contig " << i << " with " << checkC << " incorrect verts"); } */ } return (numerator / denominator) * 100.0; } /** * @param prot_idx index of target protein or -1 to specify all proteins * @return pair of percent b ions (first) and percent y ions (second) out * of all annotated vertices */ pair<float, float> MappedSpecnets::getPercBYVerts(int prot_idx) { float numeratorB = 0; float numeratorY = 0; float denominator = 0; MappedContig* contig; for (int i = 0; i < contigs->size(); i++) { contig = &(*contigs)[i]; if (target_prots.count(contig->starProtIdx) == 0) { continue; } if (prot_idx >= 0 && (contig->starProtIdx != prot_idx)) { continue; } for (int j = 0; j < contig->length; j++) { if (contig->abruijnVerts[j].annotated) { denominator += 1.0; if (contig->abruijnVerts[j].annotation.find("b") != string::npos) { numeratorB += 1.0; } else if (contig->abruijnVerts[j].annotation.find("y") != string::npos) { numeratorY += 1.0; } } } } return pair<float, float> ((numeratorB / denominator) * 100.0, (numeratorY / denominator) * 100.0); } /** * @param prot_idx index of target protein or -1 to specify all proteins * @param label 0, 1, or 2 * @return if label != 0, percent of abruijn gaps that have label out of * those that are annotated. if label == 0, percent of abruijn gaps * that have label out of those that are not annotated */ float MappedSpecnets::getPercGaps(int prot_idx, short label) { float numerator = 0; float denominator = 0; MappedContig* contig; for (int i = 0; i < contigs->size(); i++) { contig = &(*contigs)[i]; if (target_prots.count(contig->starProtIdx) == 0) { continue; } if (prot_idx >= 0 && (contig->starProtIdx != prot_idx)) { continue; } int checkC = 0; for (int j = 0; j < contig->length - 1; j++) { if (label > 0 && contig->abruijnGaps[j].annotated) { denominator += 1.0; if (contig->abruijnGaps[j].label == label) { checkC++; numerator += 1.0; } } else if (label == 0) { denominator += 1.0; numerator += (contig->abruijnGaps[j].annotated) ? 0.0 : 1.0; } } if (label == 1 && checkC > 2) { //DEBUG_MSG("See contig " << i << " with " << checkC << " incorrect gaps"); } } return (numerator / denominator) * 100.0; } /** * @param prot_idx index of target protein or -1 to specify all proteins * @return if prot_idx < 0, percent of all assembled spectra that are * identified. Otherwise, the percent of all assembled spectra in a contig * mapped to protein prot_idx that are identified. */ float MappedSpecnets::getPercAssemSpecIdent(int prot_idx) { float numerator = 0; float denominator = 0; MappedContig* contig; for (int i = 0; i < contigs->size(); i++) { contig = &(*contigs)[i]; if (prot_idx >= 0 && (!contig->vertMapped)) { continue; } if (prot_idx >= 0 && (contig->vertProtIdx != prot_idx)) { continue; } denominator += contig->numSpecs; for (int s = 0; s < contig->mappedSpectra.size(); s++) { numerator += (contig->mappedSpectra[s]->identified) ? 1.0 : 0; } } return (numerator / denominator) * 100.0; } /** * @param prot_idx index of target protein or -1 to specify all proteins * @return of all contigs mapped to prot_idx, the percent of all matchma * and inspect mapped abruijn vertices that assemble at least one * identified MS/MS b/y peak mapping to the same matchma residue index. */ float MappedSpecnets::getMatchmaAccuracy(int prot_idx) { float numerator = 0; float denominator = 0; MappedContig* contig; for (int i = 0; i < contigs->size(); i++) { contig = &(*contigs)[i]; if (!contig->vertMapped) { continue; } if (prot_idx >= 0 && (contig->vertProtIdx != prot_idx)) { continue; } int prot_idx_use = (prot_idx < 0) ? contig->vertProtIdx : prot_idx; if (target_prots.count(prot_idx_use) == 0) { continue; } for (int s = 0; s < contig->size(); s++) { if ((!contig->abruijnVerts[s].mapped) || (!contig->abruijnVerts[s].annotated)) { continue; } denominator += 1.0; int resIdx = contig->abruijnVerts[s].residueIdx; for (int v = 0; v < contig->abruijnVerts[s].starPeaks.size(); v++) { if (!contig->abruijnVerts[s].starPeaks[v]->mapped) { continue; } int specIdx = contig->abruijnVerts[s].starPeaks[v]->specIdx; int BpepIdx = contig->abruijnVerts[s].starPeaks[v]->BpeptideIdx; int YpepIdx = contig->abruijnVerts[s].starPeaks[v]->YpeptideIdx; if ((*spectra)[specIdx].residueIdxs.count(prot_idx_use) == 0) { continue; } bool broke = false; for (list<int>::iterator resIt = (*spectra)[specIdx].residueIdxs[prot_idx_use].begin(); resIt != (*spectra)[specIdx].residueIdxs[prot_idx_use].end(); resIt++) { if (BpepIdx >= 0 && (*resIt) + BpepIdx == resIdx) { numerator += 1.0; broke = true; break; } if (YpepIdx >= 0 && (*resIt) + YpepIdx == resIdx) { numerator += 1.0; broke = true; break; } } if (broke) { break; } } } } return (numerator / denominator) * 100.0; } /** * @param prot_idx index of target protein or -1 to specify all proteins * @param outValues output vector that, over all annotated contig gaps, * will contain a pair of integers for each index i where the first is * the number of annotated gaps at position i and the second is the * number of correct annotated gaps at position i. "position" is the * number of gaps between a gap and the closest end of the contig * sequence. * @param outputTable optional output data structure that, if specified, * will mirror 'outValues' but in a table format suitable for OutputTable.cpp * @return */ void MappedSpecnets::getGapAccVsPos(int prot_idx, vector<pair<int, int> >& outValues, vector<vector<pair<string, bool> > >* outputTable) { MappedContig* contig; outValues.resize(100, pair<int, int> (0, 0)); int largestPos = 0; for (int i = 0; i < contigs->size(); i++) { contig = &(*contigs)[i]; if (target_prots.count(contig->starProtIdx) == 0) { continue; } if (prot_idx >= 0 && (contig->starProtIdx != prot_idx)) { continue; } for (int j = 0; j < contig->length - 1; j++) { if (contig->abruijnGaps[j].annotated) { int pos = min(j, contig->length - 2 - j); if (pos >= outValues.size()) { outValues.resize(pos + 1, pair<int, int> (0, 0)); } largestPos = max(largestPos, pos); outValues[pos].first += 1; if (contig->abruijnGaps[j].label == 2) { outValues[pos].second += 1; } } } } outValues.resize(largestPos + 1); if (outputTable != 0) { outputTable->resize(outValues.size() + 1); pair<string, bool> cell; cell.first = "Position"; cell.second = true; (*outputTable)[0].resize(3); (*outputTable)[0][0] = cell; cell.first = "Annotated"; (*outputTable)[0][1] = cell; cell.first = "Accurate"; (*outputTable)[0][2] = cell; cell.second = false; for (int i = 0; i < outValues.size(); i++) { (*outputTable)[i + 1].resize(3); cell.first = parseInt(i + 1); (*outputTable)[i + 1][0] = cell; cell.first = parseInt(outValues[i].first); (*outputTable)[i + 1][1] = cell; cell.first = parseInt(outValues[i].second); (*outputTable)[i + 1][2] = cell; } } } }
[ "ming@localhost" ]
ming@localhost
facdf4864dca62b91b9e97829d9d2561c0a272ba
b7880e3193f43e1a2f67b254f16d76d485cf3f46
/src/urn_jaus_jss_mobility_LocalWaypointListDriver_1_0/Messages/Shutdown.cpp
5481188aa714b647d77d026dc256164e84f6a5e8
[]
no_license
davidhodo/libJAUS
49e09c860c58f615c9b4cf88844caf2257e51d99
b034c614555478540ac2565812af94db44b54aeb
refs/heads/master
2020-05-15T17:44:55.910342
2012-01-18T20:33:41
2012-01-18T20:33:41
3,209,499
0
0
null
null
null
null
UTF-8
C++
false
false
6,163
cpp
#include "urn_jaus_jss_mobility_LocalWaypointListDriver_1_0/Messages/Shutdown.h" namespace urn_jaus_jss_mobility_LocalWaypointListDriver_1_0 { void Shutdown::AppHeader::HeaderRec::setParent(AppHeader* parent) { m_parent = parent; } void Shutdown::AppHeader::HeaderRec::setParentPresenceVector() { if(m_parent != NULL ) { m_parent->setParentPresenceVector(); } } jUnsignedShortInteger Shutdown::AppHeader::HeaderRec::getMessageID() { return m_MessageID; } int Shutdown::AppHeader::HeaderRec::setMessageID(jUnsignedShortInteger value) { m_MessageID = value; setParentPresenceVector(); return 0; } /** * Returns the size of memory the used data members of the class occupies. * This is not necessarily the same size of memory the class actually occupies. * Eg. A union of an int and a double may occupy 8 bytes. However, if the data * stored is an int, this function will return a size of 4 bytes. * * @return */ const unsigned int Shutdown::AppHeader::HeaderRec::getSize() { unsigned int size = 0; size += sizeof(jUnsignedShortInteger); return size; } void Shutdown::AppHeader::HeaderRec::encode(unsigned char *bytes) { if (bytes == NULL) { return; } int pos = 0; jUnsignedShortInteger m_MessageIDTemp; m_MessageIDTemp = JSIDL_v_1_0::correctEndianness(m_MessageID); memcpy(bytes + pos, &m_MessageIDTemp, sizeof(jUnsignedShortInteger)); pos += sizeof(jUnsignedShortInteger); } void Shutdown::AppHeader::HeaderRec::decode(const unsigned char *bytes) { if (bytes == NULL) { return; } int pos = 0; jUnsignedShortInteger m_MessageIDTemp; memcpy(&m_MessageIDTemp, bytes + pos, sizeof(jUnsignedShortInteger)); m_MessageID = JSIDL_v_1_0::correctEndianness(m_MessageIDTemp); pos += sizeof(jUnsignedShortInteger); } Shutdown::AppHeader::HeaderRec &Shutdown::AppHeader::HeaderRec::operator=(const HeaderRec &value) { m_MessageID = value.m_MessageID; return *this; } bool Shutdown::AppHeader::HeaderRec::operator==(const HeaderRec &value) const { if (m_MessageID != value.m_MessageID) { return false; } return true; } bool Shutdown::AppHeader::HeaderRec::operator!=(const HeaderRec &value) const { return !((*this) == value); } Shutdown::AppHeader::HeaderRec::HeaderRec() { m_parent = NULL; m_MessageID = 0x0002; } Shutdown::AppHeader::HeaderRec::HeaderRec(const HeaderRec &value) { /// Initiliaze the protected variables m_parent = NULL; m_MessageID = 0x0002; /// Copy the values m_MessageID = value.m_MessageID; } Shutdown::AppHeader::HeaderRec::~HeaderRec() { } Shutdown::AppHeader::HeaderRec* const Shutdown::AppHeader::getHeaderRec() { return &m_HeaderRec; } int Shutdown::AppHeader::setHeaderRec(const HeaderRec &value) { m_HeaderRec = value; setParentPresenceVector(); return 0; } void Shutdown::AppHeader::setParentPresenceVector() { // Nothing needed here, placeholder function } /** * Returns the size of memory the used data members of the class occupies. * This is not necessarily the same size of memory the class actually occupies. * Eg. A union of an int and a double may occupy 8 bytes. However, if the data * stored is an int, this function will return a size of 4 bytes. * * @return */ const unsigned int Shutdown::AppHeader::getSize() { unsigned int size = 0; size += m_HeaderRec.getSize(); return size; } void Shutdown::AppHeader::encode(unsigned char *bytes) { if (bytes == NULL) { return; } int pos = 0; m_HeaderRec.encode(bytes + pos); pos += m_HeaderRec.getSize(); } void Shutdown::AppHeader::decode(const unsigned char *bytes) { if (bytes == NULL) { return; } int pos = 0; m_HeaderRec.decode(bytes + pos); pos += m_HeaderRec.getSize(); } Shutdown::AppHeader &Shutdown::AppHeader::operator=(const AppHeader &value) { m_HeaderRec = value.m_HeaderRec; m_HeaderRec.setParent(this); return *this; } bool Shutdown::AppHeader::operator==(const AppHeader &value) const { if (m_HeaderRec != value.m_HeaderRec) { return false; } return true; } bool Shutdown::AppHeader::operator!=(const AppHeader &value) const { return !((*this) == value); } Shutdown::AppHeader::AppHeader() { m_HeaderRec.setParent(this); /// No Initialization of m_HeaderRec necessary. } Shutdown::AppHeader::AppHeader(const AppHeader &value) { /// Initiliaze the protected variables m_HeaderRec.setParent(this); /// No Initialization of m_HeaderRec necessary. /// Copy the values m_HeaderRec = value.m_HeaderRec; m_HeaderRec.setParent(this); } Shutdown::AppHeader::~AppHeader() { } Shutdown::AppHeader* const Shutdown::getAppHeader() { return &m_AppHeader; } int Shutdown::setAppHeader(const AppHeader &value) { m_AppHeader = value; return 0; } /** * Returns the size of memory the used data members of the class occupies. * This is not necessarily the same size of memory the class actually occupies. * Eg. A union of an int and a double may occupy 8 bytes. However, if the data * stored is an int, this function will return a size of 4 bytes. * * @return */ const unsigned int Shutdown::getSize() { unsigned int size = 0; size += m_AppHeader.getSize(); return size; } void Shutdown::encode(unsigned char *bytes) { if (bytes == NULL) { return; } int pos = 0; m_AppHeader.encode(bytes + pos); pos += m_AppHeader.getSize(); } void Shutdown::decode(const unsigned char *bytes) { if (bytes == NULL) { return; } int pos = 0; m_AppHeader.decode(bytes + pos); pos += m_AppHeader.getSize(); } Shutdown &Shutdown::operator=(const Shutdown &value) { m_AppHeader = value.m_AppHeader; return *this; } bool Shutdown::operator==(const Shutdown &value) const { if (m_AppHeader != value.m_AppHeader) { return false; } return true; } bool Shutdown::operator!=(const Shutdown &value) const { return !((*this) == value); } Shutdown::Shutdown() { /// No Initialization of m_AppHeader necessary. m_IsCommand = true; } Shutdown::Shutdown(const Shutdown &value) { /// Initiliaze the protected variables /// No Initialization of m_AppHeader necessary. m_IsCommand = true; /// Copy the values m_AppHeader = value.m_AppHeader; } Shutdown::~Shutdown() { } }
6cdcc2eacde738cafd2a7a8e29e508f8c1172e85
e2a24d5eac51c7db68d99fde0e2f2155c2d25171
/src/function/SRT.hpp
e41c1cdc4aa2ee05f2c65beb4e38df19cf56b1b0
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
Alexxu1024/Backup_kanzi
d1638c4300b3f3264a873c3a84ea67475ca77404
441c6f5f05c65df3374009abc08dc418c3b741ab
refs/heads/master
2020-07-26T03:15:06.262106
2019-08-31T22:55:15
2019-08-31T22:55:15
208,516,855
0
0
null
null
null
null
UTF-8
C++
false
false
1,392
hpp
/* Copyright 2011-2017 Frederic Langlet 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 _SRT_ #define _SRT_ #include "../Function.hpp" namespace kanzi { // Sorted Rank Transform is typically used after a BWT to reduce the variance // of the data prior to entropy coding. class SRT : public Function<byte> { public: SRT() {} ~SRT() {} bool forward(SliceArray<byte>& pSrc, SliceArray<byte>& pDst, int length) THROW; bool inverse(SliceArray<byte>& pSrc, SliceArray<byte>& pDst, int length) THROW; int getMaxEncodedLength(int srcLen) const { return srcLen + HEADER_SIZE; } private: static const int HEADER_SIZE = 4 * 256; // freqs static int preprocess(int32 freqs[], uint8 symbols[]); static int encodeHeader(int32 freqs[], byte dst[]); static int decodeHeader(byte src[], int32 freqs[]); }; } #endif
b26f837fac011c9b4cf0da455fe76faaf9b5f4c7
424d9d65e27cd204cc22e39da3a13710b163f4e7
/services/network/quic_transport_unittest.cc
07243209c997ca2ee352b2a343ab83c0b393f5f1
[ "BSD-3-Clause" ]
permissive
bigben0123/chromium
7c5f4624ef2dacfaf010203b60f307d4b8e8e76d
83d9cd5e98b65686d06368f18b4835adbab76d89
refs/heads/master
2023-01-10T11:02:26.202776
2020-10-30T09:47:16
2020-10-30T09:47:16
275,543,782
0
0
BSD-3-Clause
2020-10-30T09:47:18
2020-06-28T08:45:11
null
UTF-8
C++
false
false
25,323
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/network/quic_transport.h" #include <set> #include <vector> #include "base/rand_util.h" #include "base/stl_util.h" #include "base/test/bind_test_util.h" #include "base/test/task_environment.h" #include "net/cert/mock_cert_verifier.h" #include "net/dns/mock_host_resolver.h" #include "net/log/test_net_log.h" #include "net/quic/crypto/proof_source_chromium.h" #include "net/test/test_data_directory.h" #include "net/third_party/quiche/src/quic/test_tools/crypto_test_utils.h" #include "net/tools/quic/quic_transport_simple_server.h" #include "net/url_request/url_request_context.h" #include "services/network/network_context.h" #include "services/network/network_service.h" #include "services/network/public/mojom/network_context.mojom.h" #include "services/network/test/fake_test_cert_verifier_params_factory.h" #include "testing/gtest/include/gtest/gtest.h" namespace network { namespace { // A clock that only mocks out WallNow(), but uses real Now() and // ApproximateNow(). Useful for certificate verification. class TestWallClock : public quic::QuicClock { public: quic::QuicTime Now() const override { return quic::QuicChromiumClock::GetInstance()->Now(); } quic::QuicTime ApproximateNow() const override { return quic::QuicChromiumClock::GetInstance()->ApproximateNow(); } quic::QuicWallTime WallNow() const override { return wall_now_; } void set_wall_now(quic::QuicWallTime now) { wall_now_ = now; } private: quic::QuicWallTime wall_now_ = quic::QuicWallTime::Zero(); }; class TestConnectionHelper : public quic::QuicConnectionHelperInterface { public: const quic::QuicClock* GetClock() const override { return &clock_; } quic::QuicRandom* GetRandomGenerator() override { return quic::QuicRandom::GetInstance(); } quic::QuicBufferAllocator* GetStreamSendBufferAllocator() override { return &allocator_; } TestWallClock& clock() { return clock_; } private: TestWallClock clock_; quic::SimpleBufferAllocator allocator_; }; mojom::NetworkContextParamsPtr CreateNetworkContextParams() { auto context_params = mojom::NetworkContextParams::New(); // Use a dummy CertVerifier that always passes cert verification, since // these unittests don't need to test CertVerifier behavior. context_params->cert_verifier_params = FakeTestCertVerifierParamsFactory::GetCertVerifierParams(); return context_params; } // We don't use mojo::BlockingCopyToString because it leads to deadlocks. std::string Read(mojo::ScopedDataPipeConsumerHandle readable) { std::string output; while (true) { char buffer[1024]; uint32_t size = sizeof(buffer); MojoResult result = readable->ReadData(buffer, &size, MOJO_READ_DATA_FLAG_NONE); if (result == MOJO_RESULT_SHOULD_WAIT) { base::RunLoop run_loop; base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop.QuitClosure()); run_loop.Run(); continue; } if (result == MOJO_RESULT_FAILED_PRECONDITION) { return output; } DCHECK_EQ(result, MOJO_RESULT_OK); output.append(buffer, size); } } class TestHandshakeClient final : public mojom::QuicTransportHandshakeClient { public: TestHandshakeClient(mojo::PendingReceiver<mojom::QuicTransportHandshakeClient> pending_receiver, base::OnceClosure callback) : receiver_(this, std::move(pending_receiver)), callback_(std::move(callback)) { receiver_.set_disconnect_handler(base::BindOnce( &TestHandshakeClient::OnMojoConnectionError, base::Unretained(this))); } ~TestHandshakeClient() override = default; void OnConnectionEstablished( mojo::PendingRemote<mojom::QuicTransport> transport, mojo::PendingReceiver<mojom::QuicTransportClient> client_receiver) override { transport_ = std::move(transport); client_receiver_ = std::move(client_receiver); has_seen_connection_establishment_ = true; receiver_.reset(); std::move(callback_).Run(); } void OnHandshakeFailed( const base::Optional<net::QuicTransportError>& error) override { has_seen_handshake_failure_ = true; receiver_.reset(); std::move(callback_).Run(); } void OnMojoConnectionError() { has_seen_handshake_failure_ = true; std::move(callback_).Run(); } mojo::PendingRemote<mojom::QuicTransport> PassTransport() { return std::move(transport_); } mojo::PendingReceiver<mojom::QuicTransportClient> PassClientReceiver() { return std::move(client_receiver_); } bool has_seen_connection_establishment() const { return has_seen_connection_establishment_; } bool has_seen_handshake_failure() const { return has_seen_handshake_failure_; } bool has_seen_mojo_connection_error() const { return has_seen_mojo_connection_error_; } private: mojo::Receiver<mojom::QuicTransportHandshakeClient> receiver_; mojo::PendingRemote<mojom::QuicTransport> transport_; mojo::PendingReceiver<mojom::QuicTransportClient> client_receiver_; base::OnceClosure callback_; bool has_seen_connection_establishment_ = false; bool has_seen_handshake_failure_ = false; bool has_seen_mojo_connection_error_ = false; }; class TestClient final : public mojom::QuicTransportClient { public: explicit TestClient( mojo::PendingReceiver<mojom::QuicTransportClient> pending_receiver) : receiver_(this, std::move(pending_receiver)) { receiver_.set_disconnect_handler(base::BindOnce( &TestClient::OnMojoConnectionError, base::Unretained(this))); } // mojom::QuicTransportClient implementation. void OnDatagramReceived(base::span<const uint8_t> data) override { received_datagrams_.push_back( std::vector<uint8_t>(data.begin(), data.end())); } void OnIncomingStreamClosed(uint32_t stream_id, bool fin_received) override { closed_incoming_streams_.insert(std::make_pair(stream_id, fin_received)); if (quit_closure_for_incoming_stream_closure_) { std::move(quit_closure_for_incoming_stream_closure_).Run(); } } void WaitUntilMojoConnectionError() { base::RunLoop run_loop; quit_closure_for_mojo_connection_error_ = run_loop.QuitClosure(); run_loop.Run(); } void WaitUntilIncomingStreamIsClosed(uint32_t stream_id) { while (!stream_is_closed_as_incoming_stream(stream_id)) { base::RunLoop run_loop; quit_closure_for_incoming_stream_closure_ = run_loop.QuitClosure(); run_loop.Run(); } } const std::vector<std::vector<uint8_t>>& received_datagrams() const { return received_datagrams_; } bool has_received_fin_for(uint32_t stream_id) { auto it = closed_incoming_streams_.find(stream_id); return it != closed_incoming_streams_.end() && it->second; } bool stream_is_closed_as_incoming_stream(uint32_t stream_id) { return closed_incoming_streams_.find(stream_id) != closed_incoming_streams_.end(); } bool has_seen_mojo_connection_error() const { return has_seen_mojo_connection_error_; } private: void OnMojoConnectionError() { has_seen_mojo_connection_error_ = true; if (quit_closure_for_mojo_connection_error_) { std::move(quit_closure_for_mojo_connection_error_).Run(); } } mojo::Receiver<mojom::QuicTransportClient> receiver_; base::OnceClosure quit_closure_for_mojo_connection_error_; base::OnceClosure quit_closure_for_incoming_stream_closure_; std::vector<std::vector<uint8_t>> received_datagrams_; std::map<uint32_t, bool> closed_incoming_streams_; bool has_seen_mojo_connection_error_ = false; }; quic::ParsedQuicVersion GetTestVersion() { quic::ParsedQuicVersion version = quic::DefaultVersionForQuicTransport(); quic::QuicEnableVersion(version); return version; } class QuicTransportTest : public testing::Test { public: QuicTransportTest() : QuicTransportTest( quic::test::crypto_test_utils::ProofSourceForTesting()) {} explicit QuicTransportTest(std::unique_ptr<quic::ProofSource> proof_source) : version_(GetTestVersion()), origin_(url::Origin::Create(GURL("https://example.org/"))), task_environment_(base::test::TaskEnvironment::MainThreadType::IO), network_service_(NetworkService::CreateForTesting()), network_context_remote_(mojo::NullRemote()), network_context_(network_service_.get(), network_context_remote_.BindNewPipeAndPassReceiver(), CreateNetworkContextParams()), server_(/* port= */ 0, {origin_}, std::move(proof_source)) { EXPECT_EQ(EXIT_SUCCESS, server_.Start()); cert_verifier_.set_default_result(net::OK); host_resolver_.rules()->AddRule("test.example.com", "127.0.0.1"); network_context_.url_request_context()->set_cert_verifier(&cert_verifier_); network_context_.url_request_context()->set_host_resolver(&host_resolver_); network_context_.url_request_context()->set_net_log(&net_log_); auto* quic_context = network_context_.url_request_context()->quic_context(); quic_context->params()->supported_versions.push_back(version_); quic_context->params()->origins_to_force_quic_on.insert( net::HostPortPair("test.example.com", 0)); } ~QuicTransportTest() override = default; void CreateQuicTransport( const GURL& url, const url::Origin& origin, const net::NetworkIsolationKey& key, std::vector<mojom::QuicTransportCertificateFingerprintPtr> fingerprints, mojo::PendingRemote<mojom::QuicTransportHandshakeClient> handshake_client) { network_context_.CreateQuicTransport( url, origin, key, std::move(fingerprints), std::move(handshake_client)); } void CreateQuicTransport( const GURL& url, const url::Origin& origin, mojo::PendingRemote<mojom::QuicTransportHandshakeClient> handshake_client) { CreateQuicTransport(url, origin, net::NetworkIsolationKey(), {}, std::move(handshake_client)); } void CreateQuicTransport( const GURL& url, const url::Origin& origin, std::vector<mojom::QuicTransportCertificateFingerprintPtr> fingerprints, mojo::PendingRemote<mojom::QuicTransportHandshakeClient> handshake_client) { CreateQuicTransport(url, origin, net::NetworkIsolationKey(), std::move(fingerprints), std::move(handshake_client)); } GURL GetURL(base::StringPiece suffix) { return GURL(quiche::QuicheStrCat("quic-transport://test.example.com:", server_.server_address().port(), suffix)); } const url::Origin& origin() const { return origin_; } const NetworkContext& network_context() const { return network_context_; } NetworkContext& mutable_network_context() { return network_context_; } net::RecordingTestNetLog& net_log() { return net_log_; } void RunPendingTasks() { base::RunLoop run_loop; base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop.QuitClosure()); run_loop.Run(); } private: QuicFlagSaver flags_; // Save/restore all QUIC flag values. quic::ParsedQuicVersion version_; const url::Origin origin_; base::test::TaskEnvironment task_environment_; std::unique_ptr<NetworkService> network_service_; mojo::Remote<mojom::NetworkContext> network_context_remote_; net::MockCertVerifier cert_verifier_; net::MockHostResolver host_resolver_; net::RecordingTestNetLog net_log_; NetworkContext network_context_; net::QuicTransportSimpleServer server_; }; TEST_F(QuicTransportTest, ConnectSuccessfully) { base::RunLoop run_loop_for_handshake; mojo::PendingRemote<mojom::QuicTransportHandshakeClient> handshake_client; TestHandshakeClient test_handshake_client( handshake_client.InitWithNewPipeAndPassReceiver(), run_loop_for_handshake.QuitClosure()); CreateQuicTransport(GetURL("/discard"), origin(), std::move(handshake_client)); run_loop_for_handshake.Run(); EXPECT_TRUE(test_handshake_client.has_seen_connection_establishment()); EXPECT_FALSE(test_handshake_client.has_seen_handshake_failure()); EXPECT_FALSE(test_handshake_client.has_seen_mojo_connection_error()); EXPECT_EQ(1u, network_context().NumOpenQuicTransports()); } TEST_F(QuicTransportTest, ConnectWithWrongOrigin) { base::RunLoop run_loop_for_handshake; mojo::PendingRemote<mojom::QuicTransportHandshakeClient> handshake_client; TestHandshakeClient test_handshake_client( handshake_client.InitWithNewPipeAndPassReceiver(), run_loop_for_handshake.QuitClosure()); CreateQuicTransport(GetURL("/discard"), url::Origin::Create(GURL("https://evil.com")), std::move(handshake_client)); run_loop_for_handshake.Run(); EXPECT_TRUE(test_handshake_client.has_seen_connection_establishment()); EXPECT_FALSE(test_handshake_client.has_seen_handshake_failure()); EXPECT_FALSE(test_handshake_client.has_seen_mojo_connection_error()); // Server resets the connection due to origin mismatch. TestClient client(test_handshake_client.PassClientReceiver()); client.WaitUntilMojoConnectionError(); EXPECT_EQ(0u, network_context().NumOpenQuicTransports()); } TEST_F(QuicTransportTest, SendDatagram) { base::RunLoop run_loop_for_handshake; mojo::PendingRemote<mojom::QuicTransportHandshakeClient> handshake_client; TestHandshakeClient test_handshake_client( handshake_client.InitWithNewPipeAndPassReceiver(), run_loop_for_handshake.QuitClosure()); CreateQuicTransport(GetURL("/echo"), url::Origin::Create(GURL("https://example.org/")), std::move(handshake_client)); run_loop_for_handshake.Run(); mojo::Remote<mojom::QuicTransport> transport_remote( test_handshake_client.PassTransport()); TestClient client(test_handshake_client.PassClientReceiver()); std::set<std::vector<uint8_t>> sent_data; // Both sending and receiving datagrams are flaky due to lack of // retransmission, and we cannot expect a specific message to be echoed back. // Instead, we expect one of sent messages to be echoed back. while (client.received_datagrams().empty()) { base::RunLoop run_loop_for_datagram; bool result; std::vector<uint8_t> data = { static_cast<uint8_t>(base::RandInt(0, 255)), static_cast<uint8_t>(base::RandInt(0, 255)), static_cast<uint8_t>(base::RandInt(0, 255)), static_cast<uint8_t>(base::RandInt(0, 255)), }; transport_remote->SendDatagram(base::make_span(data), base::BindLambdaForTesting([&](bool r) { result = r; run_loop_for_datagram.Quit(); })); run_loop_for_datagram.Run(); if (sent_data.empty()) { // We expect that the first data went to the network successfully. ASSERT_TRUE(result); } sent_data.insert(std::move(data)); } EXPECT_TRUE(base::Contains(sent_data, client.received_datagrams()[0])); } TEST_F(QuicTransportTest, SendToolargeDatagram) { base::RunLoop run_loop_for_handshake; mojo::PendingRemote<mojom::QuicTransportHandshakeClient> handshake_client; TestHandshakeClient test_handshake_client( handshake_client.InitWithNewPipeAndPassReceiver(), run_loop_for_handshake.QuitClosure()); CreateQuicTransport(GetURL("/discard"), url::Origin::Create(GURL("https://example.org/")), std::move(handshake_client)); run_loop_for_handshake.Run(); base::RunLoop run_loop_for_datagram; bool result; // The actual upper limit for one datagram is platform specific, but // 786kb should be large enough for any platform. std::vector<uint8_t> data(786 * 1024, 99); mojo::Remote<mojom::QuicTransport> transport_remote( test_handshake_client.PassTransport()); transport_remote->SendDatagram(base::make_span(data), base::BindLambdaForTesting([&](bool r) { result = r; run_loop_for_datagram.Quit(); })); run_loop_for_datagram.Run(); EXPECT_FALSE(result); } TEST_F(QuicTransportTest, EchoOnUnidirectionalStreams) { base::RunLoop run_loop_for_handshake; mojo::PendingRemote<mojom::QuicTransportHandshakeClient> handshake_client; TestHandshakeClient test_handshake_client( handshake_client.InitWithNewPipeAndPassReceiver(), run_loop_for_handshake.QuitClosure()); CreateQuicTransport(GetURL("/echo"), url::Origin::Create(GURL("https://example.org/")), std::move(handshake_client)); run_loop_for_handshake.Run(); ASSERT_TRUE(test_handshake_client.has_seen_connection_establishment()); TestClient client(test_handshake_client.PassClientReceiver()); mojo::Remote<mojom::QuicTransport> transport_remote( test_handshake_client.PassTransport()); mojo::ScopedDataPipeConsumerHandle readable_for_outgoing; mojo::ScopedDataPipeProducerHandle writable_for_outgoing; const MojoCreateDataPipeOptions options = { sizeof(options), MOJO_CREATE_DATA_PIPE_FLAG_NONE, 1, 4 * 1024}; ASSERT_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(&options, &writable_for_outgoing, &readable_for_outgoing)); uint32_t size = 5; ASSERT_EQ(MOJO_RESULT_OK, writable_for_outgoing->WriteData( "hello", &size, MOJO_WRITE_DATA_FLAG_NONE)); base::RunLoop run_loop_for_stream_creation; uint32_t stream_id; bool stream_created; transport_remote->CreateStream( std::move(readable_for_outgoing), /*writable=*/{}, base::BindLambdaForTesting([&](bool b, uint32_t id) { stream_created = b; stream_id = id; run_loop_for_stream_creation.Quit(); })); run_loop_for_stream_creation.Run(); ASSERT_TRUE(stream_created); // Signal the end-of-data. writable_for_outgoing.reset(); transport_remote->SendFin(stream_id); mojo::ScopedDataPipeConsumerHandle readable_for_incoming; uint32_t incoming_stream_id = stream_id; base::RunLoop run_loop_for_incoming_stream; transport_remote->AcceptUnidirectionalStream(base::BindLambdaForTesting( [&](uint32_t id, mojo::ScopedDataPipeConsumerHandle readable) { incoming_stream_id = id; readable_for_incoming = std::move(readable); run_loop_for_incoming_stream.Quit(); })); run_loop_for_incoming_stream.Run(); ASSERT_TRUE(readable_for_incoming); EXPECT_NE(stream_id, incoming_stream_id); std::string echo_back = Read(std::move(readable_for_incoming)); EXPECT_EQ("hello", echo_back); client.WaitUntilIncomingStreamIsClosed(incoming_stream_id); EXPECT_FALSE(client.has_received_fin_for(stream_id)); EXPECT_TRUE(client.has_received_fin_for(incoming_stream_id)); EXPECT_FALSE(client.has_seen_mojo_connection_error()); std::vector<net::NetLogEntry> resets_sent = net_log().GetEntriesWithType( net::NetLogEventType::QUIC_SESSION_RST_STREAM_FRAME_SENT); EXPECT_EQ(0u, resets_sent.size()); } // crbug.com/1129847: disabled because it is flaky. TEST_F(QuicTransportTest, DISABLED_EchoOnBidirectionalStream) { base::RunLoop run_loop_for_handshake; mojo::PendingRemote<mojom::QuicTransportHandshakeClient> handshake_client; TestHandshakeClient test_handshake_client( handshake_client.InitWithNewPipeAndPassReceiver(), run_loop_for_handshake.QuitClosure()); CreateQuicTransport(GetURL("/echo"), url::Origin::Create(GURL("https://example.org/")), std::move(handshake_client)); run_loop_for_handshake.Run(); ASSERT_TRUE(test_handshake_client.has_seen_connection_establishment()); TestClient client(test_handshake_client.PassClientReceiver()); mojo::Remote<mojom::QuicTransport> transport_remote( test_handshake_client.PassTransport()); mojo::ScopedDataPipeConsumerHandle readable_for_outgoing; mojo::ScopedDataPipeProducerHandle writable_for_outgoing; mojo::ScopedDataPipeConsumerHandle readable_for_incoming; mojo::ScopedDataPipeProducerHandle writable_for_incoming; const MojoCreateDataPipeOptions options = { sizeof(options), MOJO_CREATE_DATA_PIPE_FLAG_NONE, 1, 4 * 1024}; ASSERT_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(&options, &writable_for_outgoing, &readable_for_outgoing)); ASSERT_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(&options, &writable_for_incoming, &readable_for_incoming)); uint32_t size = 5; ASSERT_EQ(MOJO_RESULT_OK, writable_for_outgoing->WriteData( "hello", &size, MOJO_WRITE_DATA_FLAG_NONE)); base::RunLoop run_loop_for_stream_creation; uint32_t stream_id; bool stream_created; transport_remote->CreateStream( std::move(readable_for_outgoing), std::move(writable_for_incoming), base::BindLambdaForTesting([&](bool b, uint32_t id) { stream_created = b; stream_id = id; run_loop_for_stream_creation.Quit(); })); run_loop_for_stream_creation.Run(); ASSERT_TRUE(stream_created); // Signal the end-of-data. writable_for_outgoing.reset(); transport_remote->SendFin(stream_id); std::string echo_back = Read(std::move(readable_for_incoming)); EXPECT_EQ("hello", echo_back); client.WaitUntilIncomingStreamIsClosed(stream_id); EXPECT_FALSE(client.has_seen_mojo_connection_error()); EXPECT_TRUE(client.has_received_fin_for(stream_id)); EXPECT_TRUE(client.stream_is_closed_as_incoming_stream(stream_id)); } class QuicTransportWithCustomCertificateTest : public QuicTransportTest { public: QuicTransportWithCustomCertificateTest() : QuicTransportTest(CreateProofSource()) { auto helper = std::make_unique<TestConnectionHelper>(); // Set clock to a time in which quic-short-lived.pem is valid // (2020-06-05T20:35:00.000Z). helper->clock().set_wall_now( quic::QuicWallTime::FromUNIXSeconds(1591389300)); mutable_network_context() .url_request_context() ->quic_context() ->SetHelperForTesting(std::move(helper)); } ~QuicTransportWithCustomCertificateTest() override = default; static std::unique_ptr<quic::ProofSource> CreateProofSource() { auto proof_source = std::make_unique<net::ProofSourceChromium>(); base::FilePath certs_dir = net::GetTestCertsDirectory(); EXPECT_TRUE(proof_source->Initialize( certs_dir.AppendASCII("quic-short-lived.pem"), certs_dir.AppendASCII("quic-leaf-cert.key"), certs_dir.AppendASCII("quic-leaf-cert.key.sct"))); return proof_source; } }; TEST_F(QuicTransportWithCustomCertificateTest, WithValidFingerprint) { base::RunLoop run_loop_for_handshake; mojo::PendingRemote<mojom::QuicTransportHandshakeClient> handshake_client; TestHandshakeClient test_handshake_client( handshake_client.InitWithNewPipeAndPassReceiver(), run_loop_for_handshake.QuitClosure()); auto fingerprint = mojom::QuicTransportCertificateFingerprint::New( "sha-256", "ED:3D:D7:C3:67:10:94:68:D1:DC:D1:26:5C:B2:74:D7:1C:" "A2:63:3E:94:94:C0:84:39:D6:64:FA:08:B9:77:37"); std::vector<mojom::QuicTransportCertificateFingerprintPtr> fingerprints; fingerprints.push_back(std::move(fingerprint)); CreateQuicTransport(GetURL("/discard"), origin(), std::move(fingerprints), std::move(handshake_client)); run_loop_for_handshake.Run(); EXPECT_TRUE(test_handshake_client.has_seen_connection_establishment()); EXPECT_FALSE(test_handshake_client.has_seen_handshake_failure()); EXPECT_FALSE(test_handshake_client.has_seen_mojo_connection_error()); EXPECT_EQ(1u, network_context().NumOpenQuicTransports()); } TEST_F(QuicTransportWithCustomCertificateTest, WithInvalidFingerprint) { base::RunLoop run_loop_for_handshake; mojo::PendingRemote<mojom::QuicTransportHandshakeClient> handshake_client; TestHandshakeClient test_handshake_client( handshake_client.InitWithNewPipeAndPassReceiver(), run_loop_for_handshake.QuitClosure()); auto fingerprint = network::mojom::QuicTransportCertificateFingerprint::New( "sha-256", "00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:" "00:00:00:00:00:00:00:00:00:00:00:00:00:00:00"); std::vector<mojom::QuicTransportCertificateFingerprintPtr> fingerprints; fingerprints.push_back(std::move(fingerprint)); CreateQuicTransport(GetURL("/discard"), origin(), std::move(fingerprints), std::move(handshake_client)); run_loop_for_handshake.Run(); EXPECT_FALSE(test_handshake_client.has_seen_connection_establishment()); EXPECT_TRUE(test_handshake_client.has_seen_handshake_failure()); EXPECT_FALSE(test_handshake_client.has_seen_mojo_connection_error()); EXPECT_EQ(0u, network_context().NumOpenQuicTransports()); } } // namespace } // namespace network
caeafdb5470cb11794d579ccb29ee520361903ee
ddf8a06d056013ba77702bc10db26b58bac1c6fb
/Plane.cpp
818b79715d2fd758e5d0374a1233ea133cca400f
[]
no_license
HaoBruceLi/Ray-Tracer-in-Space
ece00d1176f541c727892ca24aea478404a42526
e47fbd07600ed365f29bf9b8ceaa85b362d62855
refs/heads/master
2022-12-17T16:10:49.821850
2020-09-13T03:31:04
2020-09-13T03:31:04
295,070,365
0
0
null
null
null
null
UTF-8
C++
false
false
1,945
cpp
/*---------------------------------------------------------- * COSC363 Ray Tracer * * The Plane class * This is a subclass of Object, and hence implements the * methods intersect() and normal(). -------------------------------------------------------------*/ #include "Plane.h" #include <math.h> /** * Checks if a point pt is inside the current polygon * Implement a point inclusion test using * member variables a, b, c, d. */ bool Plane::isInside(glm::vec3 pt) { //=== Complete this function ==== glm::vec3 ua = b - a; glm::vec3 ub = c - b; glm::vec3 uc = d - c; glm::vec3 ud = a - d; glm::vec3 va = pt - a; glm::vec3 vb = pt - b; glm::vec3 vc = pt - c; glm::vec3 vd = pt - d; glm::vec3 n = normal(pt); float quada = glm::dot(cross(ua, va), n); float quadb = glm::dot(cross(ub, vb), n); float quadc = glm::dot(cross(uc, vc), n); float quadd = glm::dot(cross(ud, vd), n); if(quada > 0 && quadb > 0 && quadc > 0 && quadd > 0) { return true; } else { return false; } } /** * Plane's intersection method. The input is a ray (pos, dir). */ float Plane::intersect(glm::vec3 posn, glm::vec3 dir) { glm::vec3 n = normal(posn); glm::vec3 vdif = a - posn; float vdotn = glm::dot(dir, n); if(fabs(vdotn) < 1.e-4) return -1; float t = glm::dot(vdif, n)/vdotn; if(fabs(t) < 0.0001) return -1; glm::vec3 q = posn + dir*t; if(isInside(q)) return t; else return -1; } /** * Returns the unit normal vector at a given point. * Compute the plane's normal vector using * member variables a, b, c, d. * The parameter pt is a dummy variable and is not used. */ glm::vec3 Plane::normal(glm::vec3 pt) { glm::vec3 n = glm::vec3(0); n = cross((b-a),(d-a)); n = glm::normalize(n); //=== Complete this function ==== return n; }
111a7ea7a5aa6667d28006fd3a4ba3a868198ad2
4b74bf216975b69cd829a15873ecc00a22cfa8d0
/RGFP/hardware/RFU/arith_PE.h
307f575ef5afc65721d16f02e994aadb451466bf
[]
no_license
GbuHti/Reconfigurable-DSP
b33315c14feba483bc62f4dd0879bf07eae559ef
e53194d8cb297630d2ffa70810cdc5c2d29b6c84
refs/heads/master
2021-07-17T11:49:14.829158
2020-06-02T05:56:12
2020-06-02T05:56:12
171,831,775
0
0
null
null
null
null
UTF-8
C++
false
false
3,926
h
#ifndef ARTITH_PE_H #define ARITH_PE_H #include "systemc.h" #include "tlm_utils/simple_target_socket.h" #include "tlm_utils/simple_initiator_socket.h" #include "tlm_utils/peq_with_get.h" #include "contextreg_if.h" #include "define.h" #include "slcs_if.h" #include <queue> using namespace std; using namespace sc_core; class Arith_PE : public sc_module , public contextreg_if { private: unsigned m_ID; unsigned m_op; unsigned m_op_aux; bool m_binocular; bool m_ini_done; unsigned m_pool_size; unsigned m_advance_computing; bool m_ready; float m_srca; float m_srcb; sc_event mCheckAdvanceComEvent; sc_event mProceedEvent; sc_event mExecuteEvent; sc_event mBeginResponseEvent; tlm_utils::peq_with_get<tlm::tlm_generic_payload> mSendPEQ; tlm_utils::peq_with_get<tlm::tlm_generic_payload> mSrc_a_PEQ; tlm_utils::peq_with_get<tlm::tlm_generic_payload> mSrc_b_PEQ; public: slcs_if * slcs; ///< the interface between Loader and Reconfiguration Controller tlm_utils::simple_target_socket_tagged<Arith_PE> tsock[2]; tlm_utils::simple_initiator_socket<Arith_PE> isock; Arith_PE ( sc_module_name name , unsigned id , bool binocular ); tlm::tlm_sync_enum nb_transport_fw ( int id , tlm::tlm_generic_payload &trans , tlm::tlm_phase &phase , sc_time &delay ); tlm::tlm_sync_enum nb_transport_bw ( tlm::tlm_generic_payload &trans , tlm::tlm_phase &phase , sc_time &delay ); void wait_data_thread(); void execute_thread(); void send_thread(); void monitor_advance_comp_thread(); void write_context_reg(slc context) override; void all_config() override; //{{{ tlm memory manager interface static const unsigned int m_txn_data_size = 4; // transaction size class tg_queue_c /// memory managed queue class : public tlm::tlm_mm_interface /// implements memory management IF { public: tg_queue_c /// tg_queue_c constructor ( void ) { } void enqueue /// enqueue entry (create) ( void ) { tlm::tlm_generic_payload *transaction_ptr = new tlm::tlm_generic_payload ( this ); /// transaction pointer unsigned char *data_buffer_ptr = new unsigned char [ m_txn_data_size ]; /// data buffer pointer transaction_ptr->set_data_ptr ( data_buffer_ptr ); m_queue.push ( transaction_ptr ); } tlm::tlm_generic_payload * /// transaction pointer dequeue /// dequeue entry ( void ) { tlm::tlm_generic_payload *transaction_ptr = m_queue.front (); m_queue.pop(); return transaction_ptr; } void release /// release entry ( tlm::tlm_generic_payload *transaction_ptr /// transaction pointer ) { transaction_ptr->release (); } bool /// true / false is_empty /// queue empty ( void ) { return m_queue.empty (); } size_t /// queue size size /// queue size ( void ) { return m_queue.size (); } void free /// return transaction ( tlm::tlm_generic_payload *transaction_ptr /// to the pool ) { transaction_ptr->reset(); m_queue.push ( transaction_ptr ); } private: std::queue<tlm::tlm_generic_payload*> m_queue; /// queue }; //}}} tg_queue_c m_transaction_queue; }; #endif
604c397acf4cce5042d6997b6306820eb57c23bf
88927308022e14eb42970ee5229fa70e033ff13e
/cropzoomwidget.cpp
bf38cafbd71ba47460961769ad2aafae9292a752
[]
no_license
AugusteBonnin/CRACKS
160734c75f68205bec12375c3134bc5b77594827
640bae01933ceb162c326147c6f5d0ba4836f3f7
refs/heads/master
2022-02-24T07:57:20.607051
2022-02-05T10:16:45
2022-02-05T10:16:45
73,822,848
0
0
null
null
null
null
UTF-8
C++
false
false
1,174
cpp
#include "cropzoomwidget.h" #include <QMouseEvent> CropZoomWidget::CropZoomWidget(Form *parent) : CropQuadWidget(parent) { connect(this,SIGNAL(POIchanged(QPoint)),this,SLOT(updatePOI(QPoint))); } QSize CropZoomWidget::sizeHint() const { return QSize(256,256); } QSize CropZoomWidget::minimumSizeHint() const { return QSize(256,256); } QSize CropZoomWidget::maximumSizeHint() const { return QSize(256,256); } void CropZoomWidget::setZoomImage(QImage &image) { background = image; imageToScreen = QTransform(16,0,0,16,width()>>1,height()>>1); screenToImage = imageToScreen.inverted() ; repaint() ; } void CropZoomWidget::updateSelection(int s) { selectedCorner = s ; repaint() ; } void CropZoomWidget::updatePOI(QPoint p) { imageToScreen = QTransform(16,0,0,16,(width()>>1)-16*p.x(),(height()>>1)-16*p.y()); screenToImage = imageToScreen.inverted() ; polygon[selectedCorner] = p ; repaint() ; } void CropZoomWidget::mouseMoveEvent(QMouseEvent *event) { int x,y; screenToImage.map(event->x(),event->y(),&x,&y); polygon[selectedCorner].setX(x); polygon[selectedCorner].setY(y); repaint() ; }
bfaff9d3eed7a7cfe623aeb9e6de3aa3e3858400
a2ad4dcbe9960f9acb87f7e5bbc4cb312e1644f9
/CF 705A - Hulk.cpp
a220997dfa96a99f4af417a20c5bc51a34e5fd8a
[]
no_license
shakib75bd/CF-easy-Solutions
4d5c2f85a5990ce8fa943b64d46968948459a923
6d6050443ea1e3029285c526e7ec11475d63e737
refs/heads/master
2022-12-20T12:12:52.031285
2020-10-27T08:22:52
2020-10-27T08:22:52
282,594,969
1
0
null
null
null
null
UTF-8
C++
false
false
672
cpp
// ––=‹‹BISMILLAHITR RAHMANIR RAHIM››=–– // Problem name: CF 705A - Hulk // Lang: C++ // ©: _Shakib Hossen Shanto _ CSE Dept__Begum Rokeya University,Rangpur #include<bits/stdc++.h> using namespace std; #define uns unsigned #define ll long long #define dl double #define st string #define ch char #define fxsp fixed<<setprecision int main() { int n; cin >> n; if(n==1) cout<<"I hate it"; else { cout<<"I hate "; for(int i=1;i<=(n-1);i++) { if(i%2>0) cout<<"that I love "; else cout<<"that I hate "; } cout<<"it\n"; } return 0; }
4364d4e2e518278757524d9366377407290793fa
fa826f1d5be334065f4699abd71c681475e2885e
/The 81 part 4/sum_of_distances_from_one_node_to_all_other_nodes.cpp
92defa7d384e5297885835cd3801a170a75e5530
[]
no_license
Touhidul121/All_code4
b66407b57c99154c54702322df73dc0570a84c09
c4671d09e02712dbaad4a64e2010bdbe5a612e86
refs/heads/main
2023-01-06T20:06:56.184895
2020-10-26T19:57:05
2020-10-26T19:57:05
307,488,246
0
0
null
null
null
null
UTF-8
C++
false
false
1,028
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxN = 2e5+1; vector<int>adj[maxN]; vector<ll>ans(maxN,0); vector<ll>cnt(maxN,1); int n; void dfs1(int node, int parent) { for(int child:adj[node]) { if (child != parent) { dfs1(child, node); cnt[node] += cnt[child]; //counting subtree size ans[node] += cnt[child] + ans[child]; //counting cost just root er khetre root theke sokol node a jaoar distance true } } } void dfs2(int node, int parent) { for (int child:adj[node]) { if (child != parent) { ans[child] = ans[node] - cnt[child] + n - cnt[child]; dfs2(child, node); } } } int main() { int a,b; cin>>n; for (int i = 1; i<=n-1; i++) { cin>>a>>b; adj[a].push_back(b); adj[b].push_back(a); } dfs1(1, -1); dfs2(1, -1); for(int i=1; i<=n; i++) cout<<ans[i]<<" "; cout<<"\n"; return 0; }
bef8e44c84cb75e28611c5d5e34e68ee2fdc1729
104a193527bc263482ea634842c15ec813a99c0f
/src/io/wavefront_mtl_io.cpp
d12f6551a3fdc5ad9a64730ce720aa50ab6e73f4
[ "MIT" ]
permissive
channotation/chap
d33b3a298ffd65b946a069c78baf8502c03271c9
1d137bfba9e0e9c4ed7dff016ccb0418834daac4
refs/heads/master
2022-10-26T16:45:56.138277
2022-03-02T22:33:51
2022-03-02T22:33:51
121,681,474
15
8
NOASSERTION
2022-10-05T23:43:00
2018-02-15T20:52:49
C++
UTF-8
C++
false
false
3,444
cpp
// CHAP - The Channel Annotation Package // // Copyright (c) 2016 - 2018 Gianni Klesse, Shanlin Rao, Mark S. P. Sansom, and // Stephen J. Tucker // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "io/wavefront_mtl_io.hpp" /*! * Constructs a material with the given name. */ WavefrontMtlMaterial::WavefrontMtlMaterial(std::string name) : name_(name) , ambientColour_(gmx::RVec(0.5, 0.5, 0.5)) , diffuseColour_(gmx::RVec(0.5, 0.5, 0.5)) , specularColour_(gmx::RVec(0.5, 0.5, 0.5)) { } /*! * Sets the materials ambient colour in RGB coordinates. */ void WavefrontMtlMaterial::setAmbientColour(gmx::RVec col) { ambientColour_ = col; } /*! * Sets the materials diffuse colour in RGB coordinates. */ void WavefrontMtlMaterial::setDiffuseColour(gmx::RVec col) { diffuseColour_ = col; } /*! * Sets the materials specular colour in RGB coordinates. */ void WavefrontMtlMaterial::setSpecularColour(gmx::RVec col) { specularColour_ = col; } /*! * Adds a material to the internal list of materials. */ void WavefrontMtlObject::addMaterial(WavefrontMtlMaterial material) { materials_.push_back(material); } /*! * Writes MTL object to file. */ void WavefrontMtlExporter::write(std::string fileName, WavefrontMtlObject object) { file_.open(fileName.c_str(), std::fstream::out); // loop over materials: for(auto material : object.materials_) { // write material specifications to file: writeMaterialName(material.name_); writeAmbientColour(material.ambientColour_); writeDiffuseColour(material.diffuseColour_); writeSpecularColour(material.specularColour_); } file_.close(); } /*! * Writes material name to MTL file. */ void WavefrontMtlExporter::writeMaterialName(std::string name) { file_<<"newmtl "<<name<<std::endl; } /*! * Writes ambient colour to MTL file. */ void WavefrontMtlExporter::writeAmbientColour(const gmx::RVec &col) { file_<<"Ka "<<col[XX]<<" "<<col[YY]<<" "<<col[ZZ]<<std::endl; } /*! * Writes diffuse colour to MTL file. */ void WavefrontMtlExporter::writeDiffuseColour(const gmx::RVec &col) { file_<<"Kd "<<col[XX]<<" "<<col[YY]<<" "<<col[ZZ]<<std::endl; } /*! * Writes specular colour to MTL file. */ void WavefrontMtlExporter::writeSpecularColour(const gmx::RVec &col) { file_<<"Ks "<<col[XX]<<" "<<col[YY]<<" "<<col[ZZ]<<std::endl; }
c353f808d3f9f42c22c7a7595476a6a132bb048e
ae9e57d255ffbbaf8cb4d3f61b4278eb4a2eccad
/MovSemantics2.cpp
abc392840f5165a20fd2449b639180d44136d118
[]
no_license
tv-sandeep/MoveSemantics
8a1d5cb1b70799b3081ed785801557c0bf8b1e99
3218564c6858a0a4921dcf6ef78bf50666eebd21
refs/heads/master
2022-12-02T02:15:14.552218
2020-08-14T19:00:37
2020-08-14T19:00:37
287,579,152
1
0
null
null
null
null
UTF-8
C++
false
false
876
cpp
#include "Header.h" class MyString1 { public: MyString1() = default; MyString1(const char* String) { printf("Created\n"); m_Size = strlen(String); m_data = new char[m_Size + 1]; strcpy_s(m_data, m_Size + 1, String); } MyString1(const MyString1& RHS) { printf("Copy constructor\n"); m_Size = RHS.m_Size; m_data = new char[m_Size + 1]; strcpy_s(m_data, m_Size + 1, RHS.m_data); } ~MyString1() { printf("Destroyed\n"); if (m_data) delete m_data; m_data = nullptr; m_Size = 0; } private: int m_Size; char* m_data; }; class Entity1 { public: Entity1(const MyString1& Name):m_name(Name)//This line calls copy constructor { } private: MyString1 m_name; }; void MoveSemantics2() { { Entity1 oEnt("Sandeep"); //To avoid calling copy constructor //we have to use move semantics printf(""); } printf(""); }
a5e8a2d5637bc35ccfa584a210dcc4b4de8eb928
21a9b7ce603e75f4211a7882141f128239bf169e
/src/cryptonote_basic/checkpoints.h
ec432a1ceff4fb5e647f9e76496dcd4f7f57a2f3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
bizunionchain/pango
5d6f31e5d02363f96686f93d1aa7bbac989d0e4b
a13ee7155de359d4b7ea6b070c5a34186ee37a08
refs/heads/master
2020-03-21T04:34:15.680618
2018-06-21T05:53:59
2018-06-21T05:53:59
138,115,385
0
0
null
null
null
null
UTF-8
C++
false
false
7,673
h
// Copyright (c) 2014-2017, The BUC Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #pragma once #include <map> #include <vector> #include "cryptonote_basic_impl.h" #include "misc_log_ex.h" #include "storages/portable_storage_template_helper.h" // epee json include #define ADD_CHECKPOINT(h, hash) CHECK_AND_ASSERT(add_checkpoint(h, hash), false); #define JSON_HASH_FILE_NAME "checkpoints.json" namespace cryptonote { /** * @brief A container for blockchain checkpoints * * A checkpoint is a pre-defined hash for the block at a given height. * Some of these are compiled-in, while others can be loaded at runtime * either from a json file or via DNS from a checkpoint-hosting server. */ class checkpoints { public: /** * @brief default constructor */ checkpoints(); /** * @brief adds a checkpoint to the container * * @param height the height of the block the checkpoint is for * @param hash_str the hash of the block, as a string * * @return false if parsing the hash fails, or if the height is a duplicate * AND the existing checkpoint hash does not match the new one, * otherwise returns true */ bool add_checkpoint(uint64_t height, const std::string& hash_str); /** * @brief checks if there is a checkpoint in the future * * This function checks if the height passed is lower than the highest * checkpoint. * * @param height the height to check against * * @return false if no checkpoints, otherwise returns whether or not * the height passed is lower than the highest checkpoint. */ bool is_in_checkpoint_zone(uint64_t height) const; /** * @brief checks if the given height and hash agree with the checkpoints * * This function checks if the given height and hash exist in the * checkpoints container. If so, it returns whether or not the passed * parameters match the stored values. * * @param height the height to be checked * @param h the hash to be checked * @param is_a_checkpoint return-by-reference if there is a checkpoint at the given height * * @return true if there is no checkpoint at the given height, * true if the passed parameters match the stored checkpoint, * false otherwise */ bool check_block(uint64_t height, const crypto::hash& h, bool& is_a_checkpoint) const; /** * @overload */ bool check_block(uint64_t height, const crypto::hash& h) const; /** * @brief checks if alternate chain blocks should be kept for a given height * * this basically says if the blockchain is smaller than the first * checkpoint then alternate blocks are allowed. Alternatively, if the * last checkpoint *before* the end of the current chain is also before * the block to be added, then this is fine. * * @param blockchain_height the current blockchain height * @param block_height the height of the block to be added as alternate * * @return true if alternate blocks are allowed given the parameters, * otherwise false */ bool is_alternative_block_allowed(uint64_t blockchain_height, uint64_t block_height) const; /** * @brief gets the highest checkpoint height * * @return the height of the highest checkpoint */ uint64_t get_max_height() const; /** * @brief gets the checkpoints container * * @return a const reference to the checkpoints container */ const std::map<uint64_t, crypto::hash>& get_points() const; /** * @brief checks if our checkpoints container conflicts with another * * A conflict refers to a case where both checkpoint sets have a checkpoint * for a specific height but their hashes for that height do not match. * * @param other the other checkpoints instance to check against * * @return false if any conflict is found, otherwise true */ bool check_for_conflicts(const checkpoints& other) const; /** * @brief loads the default main chain checkpoints * * @return true unless adding a checkpoint fails */ bool init_default_checkpoints(); /** * @brief load new checkpoints * * Loads new checkpoints from the specified json file, as well as * (optionally) from DNS. * * @param json_hashfile_fullpath path to the json checkpoints file * @param testnet whether to load testnet checkpoints or mainnet * @param dns whether or not to load DNS checkpoints * * @return true if loading successful and no conflicts */ bool load_new_checkpoints(const std::string json_hashfile_fullpath, bool testnet=false, bool dns=true); /** * @brief load new checkpoints from json * * @param json_hashfile_fullpath path to the json checkpoints file * * @return true if loading successful and no conflicts */ bool load_checkpoints_from_json(const std::string json_hashfile_fullpath); /** * @brief load new checkpoints from DNS * * @param testnet whether to load testnet checkpoints or mainnet * * @return true if loading successful and no conflicts */ bool load_checkpoints_from_dns(bool testnet = false); private: /** * @brief struct for loading a checkpoint from json */ struct t_hashline { uint64_t height; //!< the height of the checkpoint std::string hash; //!< the hash for the checkpoint BEGIN_KV_SERIALIZE_MAP() KV_SERIALIZE(height) KV_SERIALIZE(hash) END_KV_SERIALIZE_MAP() }; /** * @brief struct for loading many checkpoints from json */ struct t_hash_json { std::vector<t_hashline> hashlines; //!< the checkpoint lines from the file BEGIN_KV_SERIALIZE_MAP() KV_SERIALIZE(hashlines) END_KV_SERIALIZE_MAP() }; std::map<uint64_t, crypto::hash> m_points; //!< the checkpoints container }; }