blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
117
path
stringlengths
3
268
src_encoding
stringclasses
34 values
length_bytes
int64
6
4.23M
score
float64
2.52
5.19
int_score
int64
3
5
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
text
stringlengths
13
4.23M
download_success
bool
1 class
7bda7602b8f899e0a0848bc690e8d987e896fee6
C++
ccebinger/SWPSoSe14
/rail-interpreter/src/Board.h
UTF-8
570
2.78125
3
[]
no_license
// Board.h #ifndef BOARD_H_RAIL_1 #define BOARD_H_RAIL_1 #include "Vec.h" class Board { public: Board(); ~Board(); Board(std::string const & newName, std::list<std::string> const & newData); void reset(std::string const &newName, std::list<std::string> const & newData); char at(Vec pos) const; std::string const & getName(void) const; int getMinX(void) const; int getMaxX(void) const; int getMinY(void) const; int getMaxY(void) const; private: std::string name; std::vector<std::string> data; int maxX; int maxY; }; #endif
true
a4fc8d2c62b607501281026b9dc2dc4f2c99ff30
C++
ivk-jsc/broker
/libs/libupmq/decaf/util/StringTokenizer.h
UTF-8
5,001
3.09375
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2014-present IVK JSC. 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 _DECAF_UTIL_STRINGTOKENIZER_H_ #define _DECAF_UTIL_STRINGTOKENIZER_H_ #include <decaf/util/Config.h> #include <decaf/util/NoSuchElementException.h> #include <string> #include <vector> namespace decaf { namespace util { /** * Class that allows for parsing of string based on Tokens. * * @since 1.0 */ class DECAF_API StringTokenizer { private: // String to tokenize std::string str; // The delimiter string std::string delim; // The current pos in the string std::string::size_type pos; // Are we returning delimiters bool returnDelims; public: /** * Constructs a string tokenizer for the specified string. All * characters in the delim argument are the delimiters for separating * tokens. * * If the returnDelims flag is true, then the delimiter characters are * also returned as tokens. Each delimiter is returned as a string of * length one. If the flag is false, the delimiter characters are * skipped and only serve as separators between tokens. * * Note that if delim is "", this constructor does not throw an * exception. However, trying to invoke other methods on the resulting * StringTokenizer may result in an Exception. * @param str_ - The string to tokenize * @param delim_ - String containing the delimiters * @param returnDelims_ - boolean indicating if the delimiters are returned as tokens */ StringTokenizer(const std::string &str_, const std::string &delim_ = " \t\n\r\f", bool returnDelims_ = false); virtual ~StringTokenizer(); /** * Calculates the number of times that this tokenizer's nextToken * method can be called before it generates an exception. The current * position is not advanced. * @return Count of remaining tokens */ virtual int countTokens() const; /** * Tests if there are more tokens available from this tokenizer's * string. * @return true if there are more tokens remaining */ virtual bool hasMoreTokens() const; /** * Returns the next token from this string tokenizer. * * @return string value of next token * * @throws NoSuchElementException if there are no more tokens in this string. */ virtual std::string nextToken(); /** * Returns the next token in this string tokenizer's string. First, * the set of characters considered to be delimiters by this * StringTokenizer object is changed to be the characters in the * string delim. Then the next token in the string after the current * position is returned. The current position is advanced beyond the * recognized token. The new delimiter set remains the default after * this call. * * @param aDelim * The string containing the new set of delimiters. * * @return next string in the token list * * @throws NoSuchElementException if there are no more tokens in this string. */ virtual std::string nextToken(const std::string &aDelim); /** * Grab all remaining tokens in the String and return them * in the vector that is passed in by reference. * @param array - vector to place token strings in * @return number of string placed into the vector */ virtual unsigned int toArray(std::vector<std::string> &array); /** * Resets the Tokenizer's position in the String to the Beginning * calls to countToken and nextToken now start back at the beginning. * This allows this object to be reused, the caller need not create * a new instance every time a String needs tokenizing. * * * If set the string param will reset the string that this Tokenizer * is working on. If set to "" no change is made. * * If set the delim param will reset the string that this Tokenizer * is using to tokenizer the string. If set to "", no change is made * * If set the return Delims will set if this Tokenizer will return * delimiters as tokens. Defaults to false. * * @param aStr * New String to tokenize or "", defaults to "" * @param aDelim * New Delimiter String to use or "", defaults to "" * @param isReturnDelims * Should the Tokenizer return delimiters as Tokens, default false */ virtual void reset(const std::string &aStr = "", const std::string &aDelim = "", bool isReturnDelims = false); }; } // namespace util } // namespace decaf #endif /*_DECAF_UTIL_STRINGTOKENIZER_H_*/
true
715e5b7038136947b882263edf3d32d850d02540
C++
gwanhyeon/algorithm_study
/beakjoon_algorithm/beakjoon_algorithm/브루트포스/NM시리즈(4) 중복조합.cpp
UTF-8
1,047
2.578125
3
[]
no_license
// // NM시리즈(4).cpp // beakjoon_algorithm // // Created by kgh on 01/10/2019. // Copyright © 2019 kgh. All rights reserved. // #include <stdio.h> #include <iostream> #include <vector> using namespace std; int n,m; vector<int> v; int check[10]; void go(int cnt){ if(cnt == m){ bool tf = false; if(m == 1){ tf = true; }else{ for(int i=0; i<v.size()-1; i++){ if(v[i] > v[i+1]){ tf = false; }else if(v[i] < v[i+1]){ tf = true; } } } if(tf == true){ for(int i=0; i<v.size(); i++){ cout << v[i] << ' '; } cout << '\n'; } return; } for(int i=0; i<n; i++){ v.push_back(i+1); go(cnt+1); v.pop_back(); } } //중복 조합이다 int main(void){ ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> n >> m; go(0); }
true
50ed2ca553b59cb31cf4484557672b8192d4ac40
C++
SylwiaNowak/homeBudgetPlaner
/HomeFinanceCalculator.cpp
UTF-8
3,583
3.4375
3
[]
no_license
#include "HomeFinanceCalculator.h" bool HomeFinanceCalculator::isTheUserLoggedIn() { userManager.isTheUserLoggedIn(); } char HomeFinanceCalculator::chooseOptionFromTheMainMenu() { userManager.chooseOptionFromTheMainMenu(); } char HomeFinanceCalculator::chooseOptionFromTheUserMenu() { userManager.chooseOptionFromTheUserMenu(); } void HomeFinanceCalculator::userRegistration() { userManager.userRegistration(); } void HomeFinanceCalculator::logInTheUser() { userManager.logInTheUser(); if (userManager.isTheUserLoggedIn()) { incomesManager = new IncomesManager(NAME_OF_FILE_WITH_INCOMES, userManager.getIdOfTheLoggedInUser()); expensesManager = new ExpensesManager(NAME_OF_FILE_WITH_EXPENSES, userManager.getIdOfTheLoggedInUser()); } } void HomeFinanceCalculator::changeThePasswordOfTheLoggedInUser() { userManager.changeThePasswordOfTheLoggedInUser(); } void HomeFinanceCalculator::logOutTheUser() { userManager.logOutTheUser(); delete incomesManager; incomesManager = NULL; delete expensesManager; expensesManager = NULL; } void HomeFinanceCalculator::addIncome() { incomesManager -> addIncome(); } void HomeFinanceCalculator::addExpense() { expensesManager -> addExpense(); } void HomeFinanceCalculator::balanceOfTheCurrentMonth() { double amountOfBalance = 0; incomesManager -> balanceOfTheIncomesInTheCurrentMonth(); expensesManager -> balanceOfTheExpensesInTheCurrentMonth(); amountOfBalance = (incomesManager -> getIncomesAmount()) - (expensesManager -> getExpensesAmount()); cout << endl << endl << "Balance of the current month is: " << amountOfBalance << endl; getchar();getchar(); } void HomeFinanceCalculator::balanceOfThePreviousMonth() { double amountOfBalance = 0; incomesManager -> balanceOfTheIncomesInThePreviousMonth(); expensesManager -> balanceOfTheExpensesInThePreviousMonth(); amountOfBalance = (incomesManager -> getIncomesAmount()) - (expensesManager -> getExpensesAmount()); cout << endl << endl << "Balance of the previous month is: " << amountOfBalance << endl; getchar();getchar(); } void HomeFinanceCalculator::balanceOfTheSelectedTime() { AuxiliaryMethods auxiliaryMethods; string startingDate = "", endDate = ""; double amountOfBalance = 0; system("cls"); cout << "Enter date from which one you need to generate balance (in format yyyy-mm-dd): "; cin >> startingDate; if (auxiliaryMethods.checkIfTheDateIsCorrect(startingDate) == true) { cout << "Enter end date for which one you need to generate balance (in format yyyy-mm-dd): "; cin >> endDate; if (auxiliaryMethods.checkIfTheDateIsCorrect(endDate) == true) { incomesManager -> balanceOfTheIncomesInTheSelectedTime(startingDate, endDate); expensesManager -> balanceOfTheExpensesInTheSelectedTime(startingDate, endDate); } else { cout << "The end date format is incorrect. You come back to \"user menu\"." << endl; getchar();getchar(); userManager.chooseOptionFromTheUserMenu(); } } else { cout << "The end date format is incorrect. You come back to \"user menu\"." << endl; getchar();getchar(); userManager.chooseOptionFromTheUserMenu(); } amountOfBalance = (incomesManager -> getIncomesAmount()) - (expensesManager -> getExpensesAmount()); cout << endl << endl << "Balance from: " << startingDate << " to: " << endDate << " is: " << amountOfBalance << endl; getchar();getchar(); }
true
57be0b0b48e150e903da0648d8ae7e2077f31ad6
C++
BSU2015gr09/Motolov
/semester_1/2-3naibcifra.cpp
UTF-8
369
2.6875
3
[]
no_license
#include<iostream> #include<clocale> using std::cout; using std::cin; int max3(int n, int m, int p){ int result = n; if (result < m){ result = m } if (result < p) { result = p; retyrn result; } } int main(){ setlocale(LC_ALL, "Russian"); int a = 0, b = 0, c = 0, max; cin >> a >> b >> c; rez = max3(a, b, c); cout << "максимум=" << rez; }
true
ae20c2515ee517f378ecb056284d991cbe0116ef
C++
ronistone/Maratonas
/URI online/2589.cpp
UTF-8
482
2.625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef long long int ll; vector<ll> primos; bool prime[1000000002]; void sieve(){ //memset(prime,true, sizeof(prime)); primos.clear(); prime[1] = true; ll i,j; for(i=2;i<=1000000001;i++){ if(!prime[i]){ primos.push_back(i); for(j=i*i;j<=1000000001;j+=i) prime[j] = true; } } } main(){ sieve(); cout << primos.size() << endl; //for(int i=0;i<primos.size();i++) // cout << primos[i] << ", "; cout << endl; }
true
7957121c410ed819120c20c747295b764f12aa57
C++
ishika-patel/Data-Structures
/HW3/arrayDouble.cpp
UTF-8
855
3.71875
4
[]
no_license
#include <iostream> using namespace std; bool append(string* &str_arr, string s, int &numEntries, int &arraySize){ bool check = false; string *tempArray = NULL; int numberDoubled = 0; if(numEntries == arraySize) { //Increase the capacity by two times arraySize = arraySize *2; //Dynamically allocate an array of size capacity tempArray = str_arr; str_arr = new string[arraySize]; //Copy all data from oldArray to newArray for(int i=0; i< arraySize/2; i++) { str_arr[i] = tempArray[i]; } // Free the memory associated with oldArray delete [] tempArray; numberDoubled++; str_arr[numEntries] = s; numEntries++; check = true; } else { str_arr[numEntries] = s; numEntries++; } return check; }
true
beb8709a5cb0c09c177d2861c6621cf7342c957a
C++
seesealonely/leetcode
/greedy/2592.MaximizeGreatnessofanArray.cc
UTF-8
1,153
3.671875
4
[]
no_license
/* You are given a 0-indexed integer array nums. You are allowed to permute nums into a new array perm of your choosing. We define the greatness of nums be the number of indices 0 <= i < nums.length for which perm[i] > nums[i]. Return the maximum possible greatness you can achieve after permuting nums. Example 1: Input: nums = [1,3,5,2,1,3,1] Output: 4 Explanation: One of the optimal rearrangements is perm = [2,5,1,3,3,1,1]. At indices = 0, 1, 3, and 4, perm[i] > nums[i]. Hence, we return 4. Example 2: Input: nums = [1,2,3,4] Output: 3 Explanation: We can prove the optimal perm is [2,3,4,1]. At indices = 0, 1, and 2, perm[i] > nums[i]. Hence, we return 3. Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 109 */ #include"head.h" class Solution { public: int maximizeGreatness(vector<int>& nums) { sort(nums.begin(),nums.end()); int res=0,n=nums.size(); for(int i=0;i<n;i++) if(nums[i]>nums[res]) res++; return res; } }; int main() { Solution s; vector<int> v={1,3,5,2,1,3,1}; cout<<s.maximizeGreatness(v)<<endl; v.clear();v={1,2,3,4}; cout<<s.maximizeGreatness(v)<<endl; return 0; }
true
d48d97b2350990c3ec20c7549277ba160c806fba
C++
chen82508/Zeorjudge
/原創or不分類題庫/CPP/a160.cpp
WINDOWS-1252
2,766
3.078125
3
[]
no_license
/****************************************************************************** * * The purpose of using row index - column index + the number of Queens 2 - 1 * to set value of slash is to prevent the repeat of the index of diagonal from * top left to bottom right which might result in judgment error. * * The judgment error means sometime it might put a queen on the position where * is the attack route of other queens. * ******************************************************************************/ #include <iostream> #include <cmath> void DFS ( int ) ; bool onRoute ( int, int ) ; void PrintResult ( int ) ; int N, solution ; bool Queens [ 30 ] [ 30 ], R_Diagonal [ 30 ], L_Diabonal [ 30 ] ; using namespace std ; int main () { while ( cin >> N ) { if ( N == 0 ) break ; solution = 0 ; DFS ( 0 ) ; cout << solution << "\n" ; } return 0 ; } // Index i is used to record the current row //------------------------------------------------------------------------ void DFS ( int row ) { for ( int column = 0 ; column < N ; column ++ ) // If there is no queen on the attack route, continue finding //------------------------------------------------------------------------ if ( !onRoute ( row, column ) ) { int slash = ( row < column ) ? ( row - column + N * 2 ) : ( row - column ) ; if ( row == N - 1 ) { Queens [ row ] [ column ] = R_Diagonal [ row + column ] = L_Diabonal [ slash ] = 1 ; PrintResult ( N ) ; solution ++ ; Queens [ row ] [ column ] = R_Diagonal [ row + column ] = L_Diabonal [ slash ] = 0 ; } else { Queens [ row ] [ column ] = R_Diagonal [ row + column ] = L_Diabonal [ slash ] = 1 ; DFS ( row + 1 ) ; Queens [ row ] [ column ] = R_Diagonal [ row + column ] = L_Diabonal [ slash ] = 0 ; } } } // Judge if there is any other queen on the route of the queen which on the coordinate (i, j) //------------------------------------------------------------------------ bool onRoute ( int i, int j ) { int slash = ( i < j ) ? ( i - j + N * 2 ) : ( i - j ) ; bool flag = false ; for ( int k = 0 ; k < N ; k ++ ) { if ( Queens [ i ] [ k ] || Queens [ k ] [ j ] || R_Diagonal [ i + j ] || L_Diabonal [ slash ] ) flag = true ; if ( flag ) break ; } return flag ; } void PrintResult ( int N ) { for ( int row = 0 ; row < N ; row ++ ) { for ( int column = 0 ; column < N ; column ++ ) cout << ( Queens [ row ] [ column ] ? "Q" : "x" ) ; cout << "\n" ; } cout << "\n" ; }
true
d6baf5cbb7400f83dd2dfbb9da5e1145142de407
C++
firearasi/raytracingbasicscuda
/lib/sphere.h
UTF-8
627
2.578125
3
[]
no_license
#ifndef SPHEREH #define SPHEREH #include "hitable.h" #include <stdlib.h> #include <math.h> #include "material.h" void get_sphere_uv(const vec3&p, float&u, float& v); class sphere: public hitable { public: sphere() {} sphere(vec3 cen, float r, material *m): center(cen), radius(r), mat(m) {}; virtual void free(){} virtual bool hit(const ray& r, float t_min, float t_max, hit_record & rec) const; virtual bool bounding_box(float t0, float t1, aabb& box) const { box = aabb(center-vec3(radius,radius,radius), center+vec3(radius,radius,radius)); return true; } vec3 center; float radius; material *mat; }; #endif
true
d878d5e2216d116ae6a01fc93f9f6bd0d6c668cf
C++
andyyu/web-steganographer
/Compressor.cpp
UTF-8
3,526
3
3
[]
no_license
#include "provided.h" #include "HashTable.h" #include <string> #include <vector> #include <iostream> using namespace std; unsigned int computeHash(string key) { if (key.length()!= 0) return key[0] + 11; return 0; } unsigned int computeHash(unsigned short key) { return (key+3)/(key+1); } void Compressor::compress(const string& s, vector<unsigned short>& numbers) { int n = int(s.length()); int c = 0; unsigned short temp; if (n/2 + 512 < 16384) c = n/2 + 512; else c = 16384; HashTable <string, unsigned short> *hashtable = new HashTable<string, unsigned short>(c/0.5, c); for (int i = 0; i < 256; i++) hashtable->set(*new string(1, static_cast<char>(i)), i, true); unsigned short nextFreeID = 256; string runSoFar = ""; vector<unsigned short> v; for (int i = 0; i < s.length(); i++) { string expandedRun = runSoFar + s[i]; if (hashtable->get(expandedRun, temp)) { runSoFar = expandedRun; continue; } else { hashtable->get(runSoFar, temp); v.push_back(temp); hashtable->touch(runSoFar); runSoFar = ""; hashtable->get(*new string(1, static_cast<char>(s[i])), temp); v.push_back(temp); if (!hashtable->isFull()) { hashtable->set(expandedRun, nextFreeID); nextFreeID++; } else { string str = ""; unsigned short id = 0; hashtable->discard(str, id); hashtable->set(expandedRun, id); } } } if (runSoFar.length()!= 0) { hashtable->get(runSoFar, temp); v.push_back(temp); } v.push_back(c); numbers = v; // This compiles, but may not be correct } bool Compressor::decompress(const vector<unsigned short>& numbers, string& s) { unsigned short c = numbers[numbers.size()-1]; HashTable <unsigned short, string> *hashtable = new HashTable<unsigned short, string>(c/0.5, c); for (int i = 0; i < 255; i++) { hashtable->set(i, *new string(1, static_cast<char>(i))); } unsigned short nextFreeID = 256; string runSoFar = ""; string output; for (int i = 0; i < numbers.size()-1; i++) { unsigned short us = numbers[i]; string temp = ""; if (us <= 255) { hashtable->get(us, temp); output+= temp; if (runSoFar.length() == 0) { runSoFar = temp; continue; } else { string expandedRun = runSoFar + temp; if (!hashtable->isFull()) { hashtable->set(nextFreeID, expandedRun); nextFreeID++; } else { unsigned short sh; string str; hashtable->discard(sh, str); hashtable->set(sh, expandedRun); } runSoFar = ""; continue; } } else { string temp = ""; if (!hashtable->get(us, temp)) return false; else { hashtable->touch(us); output += temp; runSoFar = temp; } } } s = output; return true; // This compiles, but may not be correct }
true
de34ee4691829d9f2da5372aa8d0ebbc084a1a97
C++
SiLeader/cluster-manager
/include/cluster/detail/cluster.hpp
UTF-8
1,061
3.21875
3
[ "Apache-2.0" ]
permissive
// // Created by cerussite on 2019/11/16. // #pragma once #include <cstdint> #include <string> #include <string_view> namespace cluster { class Cluster final { private: std::string _host; std::uint16_t _port; public: Cluster(std::string_view host, std::uint16_t port) : _host(host) , _port(port) {} Cluster() : _host() , _port() {} Cluster(const Cluster &) = default; Cluster(Cluster &&) = default; Cluster &operator=(const Cluster &) = default; Cluster &operator=(Cluster &&) = default; ~Cluster() = default; public: [[nodiscard]] const std::string &host() const { return _host; } [[nodiscard]] std::uint16_t port() const noexcept { return _port; } public: bool operator==(const Cluster &rhs) const { return port() == rhs.port() && host() == rhs.host(); } bool operator!=(const Cluster &rhs) const { return !((*this) == rhs); } }; } // namespace cluster
true
48d1de928a111aa7d17f28dd0dae7aac678006d8
C++
amanr11314/PLACEMENT-PREPARATION
/Placement Preparation-II/Arrays/jump_game_II.cpp
UTF-8
1,958
3.53125
4
[]
no_license
/** * Given an array of non-negative integers nums, you are initially positioned at the first index of the array. * Each element in the array represents your maximum jump length at that position. * Your goal is to reach the last index in the minimum number of jumps. * You can assume that you can always reach the last index. * * Pretty Easy Greedy Solution if you understand it :p 😁 * * Problem Link: https://leetcode.com/problems/jump-game-ii/ * * Modified question from GFG: https://www.geeksforgeeks.org/minimum-number-jumps-reach-endset-2on-solution/ * * Awesome Explanation: https://www.youtube.com/watch?v=vBdo7wtwlXs * **/ #include <bits/stdc++.h> using namespace std; int minimum_jumps(vector<int> arr) { size_t n = arr.size(); //no jump required for single sized array if (n <= 1) return 0; //always keep chosing maxlength ladder int ladder = arr[0]; //when stairs end from current ladder and no the end of array and still ladder goes till end set stairs of that ladder int stairs = arr[0]; //required jump(s) to reach the end of array int jumps = 1; for (int i = 1; i < n; ++i) { //if alreday end return jumps if (i == n - 1) return jumps; //chose biggest ladder ladder = max(ladder, i + arr[i]); //stairs decrease as we move ahead stairs--; //no stairs left if (stairs == 0) { //means need to jump from 1 ladder to another ++jumps; //if actually ladder is big enough (in case 0 stairs on some ladder) if (i < ladder) { stairs = ladder - i; } else { //we ladder isn't big enough to reach till this end of stair that we've already got on return -1; } } } //lastly if we don't make it to end return -1; }
true
b62c92c0d06dcb7a7cfe1d9e71bbdd7c9273b620
C++
rgmelko/VB_qmc
/melko/LOOPS/2dmaybe/ratioloop/loop_main.cpp
UTF-8
2,802
2.703125
3
[]
no_license
//Jan 18, 2010 --- starting loop code #include "header.h" #include "loop_header.h" int main(){ cout.precision(10); // read in parameters: system dimensions, number of bond operators, // filenames, iterations per loop, number of loops, a random seed int dim1, dim2; int ratioflip; long long its_per_loop=10000, loops=100; long long initialization; double bops_per_site=10; bool OBC=0; long long ranseed=43289841; string enerfilename, entrofilename, bondopfilename; ifstream fin("param.txt"); fin >> enerfilename >> entrofilename >> bondopfilename >> dim1 >> dim2 >> ratioflip >> its_per_loop >> loops >> bops_per_site >> OBC >> ranseed >> initialization; fin.close(); int total_bops = dim1*dim2*bops_per_site; cout << dim1 << " x " << dim2 << " system, N = " << dim1*dim2 << " sites \n" << bops_per_site << " bops/site, " << total_bops << " bops total" << endl; cout << "------------------------------------------------ \n"; if(dim1==2|dim2==2){cout<<"warning! nnbonds get screwed up for a x 2 \n";} LOOPS system (dim1, dim2, ratioflip, total_bops, OBC, its_per_loop, ranseed, bondopfilename); // create initial VB config and initial spin config system.nnbondlist(); system.Nnnbondlist(); system.read_bops(); //checks if file has bops, otherwise generates new ones for(int jj=0; jj<initialization; jj++){ system.create_Vlinks(); system.create__Hlinks(); system.make_flip_loops(); system.change__operators(); } for(int kk=0; kk<loops; kk++){ for(int jk=0; jk<its_per_loop; jk++){ // cout << "1" << endl; system.create_Vlinks(); //build vertical LL from init VBs and operators // cout << "2" << endl; system.create__Hlinks(); //build horizontal linked list from operators // cout << "3" << endl; system.make_flip_loops(); //generate loops and flip w/ prob 0.5 // cout << "4" << endl; system.take_measurement(); // cout << "measure" << endl; system.swaperator(); // cout << "5" << endl; system.change__operators(); //Change the diagonal operators } system.calculate_stuff(); ofstream energy_out(enerfilename.c_str(),ios::app); ofstream entrpy_out(entrofilename.c_str(),ios::app); energy_out.precision(10); entrpy_out.precision(10); cout << left << setw(12) << system.energy << " "; energy_out << system.energy << endl; cout << system.entropy_final[dim1-2] << endl; energy_out.close(); for(int i=0; i<system.entropy_final.size(); i++){ entrpy_out << setw(18) << system.entropy_final[i]; } entrpy_out << endl; entrpy_out.close(); system.print_bops(); } return 0; }
true
4bf56f992e51b999d375ffd533e0f0a79b9708a4
C++
killbug2004/TASDK
/TribesAscendSDK/DynamicClasses.h
UTF-8
6,967
2.578125
3
[]
no_license
class NameProperty { DWORD offset_; uintptr_t thisptr_; public: NameProperty( void *thisptr, DWORD offset, DWORD bit_mask ) { thisptr_ = ( uintptr_t )( thisptr ); offset_ = offset; } operator ScriptName*() { return ( *( ScriptName** )( thisptr_ + offset_ ) ); } }; class StrProperty { DWORD offset_; uintptr_t thisptr_; public: StrProperty( void *thisptr, DWORD offset, DWORD bit_mask ) { thisptr_ = ( uintptr_t )( thisptr ); offset_ = offset; } operator wchar_t*() { return ( ( ScriptArray< wchar_t >* )( thisptr_ + offset_ ) )->data(); } }; template< class T > class ArithmeticProperty { DWORD offset_; uintptr_t thisptr_; public: ArithmeticProperty( void *thisptr, DWORD offset, DWORD bit_mask ) { thisptr_ = ( uintptr_t )( thisptr ); offset_ = offset; } void operator =( T new_val ) { *( T* )( thisptr_ + offset_ ) = new_val; } operator T() { return *( T* )( thisptr_ + offset_ ); } void operator +=( T val ) { *( T* )( thisptr_ + offset_ ) += val; } void operator -=( T val ) { *( T* )( thisptr_ + offset_ ) -= val; } void operator /=( T val ) { *( T* )( thisptr_ + offset_ ) /= val; } void operator *=( T val ) { *( T* )( thisptr_ + offset_ ) *= val; } T operator +( T val ) { return *( T* )( thisptr_ + offset_ ) + val; } T operator -( T val ) { return *( T* )( thisptr_ + offset_ ) - val; } T operator /( T val ) { return *( T* )( thisptr_ + offset_ ) / val; } T operator *( T val ) { return *( T* )( thisptr_ + offset_ ) * val; } }; template< class T > class NonArithmeticProperty { DWORD offset_; uintptr_t thisptr_; public: NonArithmeticProperty( void *thisptr, DWORD offset, DWORD bit_mask ) { thisptr_ = ( uintptr_t )( thisptr ); offset_ = offset; } void operator =( T new_val ) { *( T* )( thisptr_ + offset_ ) = new_val; } operator T() { return *( T* )( thisptr_ + offset_ ); } }; class BoolProperty { DWORD offset_; uintptr_t thisptr_; DWORD bit_mask_; public: BoolProperty( void *thisptr, DWORD offset, DWORD bit_mask ) { thisptr_ = ( uintptr_t )( thisptr ); offset_ = offset; bit_mask_ = bit_mask; } void operator =( bool new_val ) { if( new_val ) *( DWORD* )( thisptr_ + offset_ ) |= bit_mask_; else *( DWORD* )( thisptr_ + offset_ ) &= ~bit_mask_; } operator bool() { return ( *( DWORD* )( thisptr_ + offset_ ) & bit_mask_ ) != 0; } }; typedef ArithmeticProperty< byte > ByteProperty; typedef ArithmeticProperty< int > IntProperty; typedef ArithmeticProperty< float > FloatProperty; class RotatorProperty { DWORD offset_; uintptr_t thisptr_; inline Rotator *GetRotator() { return ( Rotator* )( thisptr_ + offset_ ); } public: RotatorProperty( void *thisptr, DWORD offset, DWORD bit_mask ) { thisptr_ = ( uintptr_t )( thisptr ); offset_ = offset; } void operator =( Rotator new_val ) { *GetRotator() = new_val; } operator Rotator() { return *GetRotator(); } Rotator operator *( float num ) { return Rotator( ( int )( num * GetRotator()->pitch ), ( int )( num * GetRotator()->yaw ), ( int )( num * GetRotator()->roll ) ); } Rotator operator *=( float num ) { GetRotator()->pitch = ( int )( num * GetRotator()->pitch ); GetRotator()->yaw = ( int )( num * GetRotator()->yaw ); GetRotator()->roll = ( int )( num * GetRotator()->roll ); return *GetRotator(); } Rotator operator /( float num ) { return Rotator( ( int )( ( 1.0f / num ) * GetRotator()->pitch ), ( int )( ( 1.0f / num ) * GetRotator()->yaw ), ( int )( ( 1.0f / num ) * GetRotator()->roll ) ); } Rotator operator /=( float num ) { GetRotator()->pitch = ( int )( ( 1.0f / num ) * GetRotator()->pitch ); GetRotator()->yaw = ( int )( ( 1.0f / num ) * GetRotator()->yaw ); GetRotator()->roll = ( int )( ( 1.0f / num ) * GetRotator()->roll ); return *GetRotator(); } Rotator operator +( const Rotator &rot ) { return Rotator( ( int )( GetRotator()->pitch + rot.pitch ), ( int )( GetRotator()->yaw + rot.yaw ), ( int )( GetRotator()->roll + rot.roll ) ); } Rotator operator +=( const Rotator &rot ) { GetRotator()->pitch += rot.pitch; GetRotator()->yaw += rot.yaw; GetRotator()->roll += rot.roll; return *GetRotator(); } Rotator operator -( const Rotator &rot ) { return Rotator( GetRotator()->pitch - rot.pitch, GetRotator()->yaw - rot.yaw, GetRotator()->roll - rot.roll ); } Rotator operator -=( const Rotator &rot ) { GetRotator()->pitch -= rot.pitch; GetRotator()->yaw -= rot.yaw; GetRotator()->roll -= rot.roll; return *GetRotator(); } Vector GetForward() { return GetRotator()->GetForward(); } Vector GetRight() { return GetRotator()->GetForward(); } Vector GetUp() { return GetRotator()->GetForward(); } }; class VectorProperty { DWORD offset_; uintptr_t thisptr_; inline Vector *GetVector() { return ( Vector* )( thisptr_ + offset_ ); } public: VectorProperty( void *thisptr, DWORD offset, DWORD bit_mask ) { thisptr_ = ( uintptr_t )( thisptr ); offset_ = offset; } void operator =( Vector new_val ) { *GetVector() = new_val; } operator Vector() { return *GetVector(); } Vector operator *( float num ) { return Vector( GetVector()->x * num, GetVector()->y * num, GetVector()->z * num ); } Vector operator *=( float num ) { GetVector()->x = num * GetVector()->x; GetVector()->y = num * GetVector()->y; GetVector()->z = num * GetVector()->z; return *GetVector(); } Vector operator /( float num ) { return Vector( GetVector()->x / num, GetVector()->y / num, GetVector()->z / num ); } Vector operator /=( float num ) { GetVector()->x = GetVector()->x / num; GetVector()->y = GetVector()->y / num; GetVector()->z = GetVector()->z / num; return *GetVector(); } Vector operator +( const Vector &vec ) { return Vector( GetVector()->x + vec.x, GetVector()->y + vec.y, GetVector()->z + vec.z ); } Vector operator +=( const Vector &vec ) { GetVector()->x += vec.x; GetVector()->y += vec.y; GetVector()->z += vec.z; return *GetVector(); } Vector operator -( const Vector &vec ) { return Vector( GetVector()->x - vec.x, GetVector()->y - vec.y, GetVector()->z - vec.z ); } Vector operator -=( const Vector &vec ) { GetVector()->x -= vec.x; GetVector()->y -= vec.y; GetVector()->z -= vec.z; return *GetVector(); } float Length() { return GetVector()->Length(); } float DotProduct( const Vector &vec ) { return GetVector()->DotProduct( vec ); } Vector CrossProduct( const Vector &vec ) { return GetVector()->CrossProduct( vec ); } }; template< class T > class ObjectProperty { DWORD offset_; uintptr_t thisptr_; public: ObjectProperty( void *thisptr, DWORD offset ) { thisptr_ = ( uintptr_t )( thisptr ); offset_ = offset; } void operator =( void *new_val ) { *( T** )( thisptr_ + offset_ ) = new_val; } operator T*() { return *( T** )( thisptr_ + offset_ ); } T* object() { return *( T** )( thisptr_ + offset_ ); } };
true
c3755933896c665dda0564e8da9d5a014b46976c
C++
JackOKITC/Brake-Point-Racing
/Joint_Project/include/Sfe/StreamSelection.hpp
UTF-8
2,043
2.5625
3
[]
no_license
/* * StreamSelection.hpp * sfeMovie project * * Copyright (C) 2010-2015 Lucas Soltic * lucas.soltic@orange.fr * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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 * */ #ifndef SFEMOVIE_STREAM_SELECTION_HPP #define SFEMOVIE_STREAM_SELECTION_HPP #include <Sfe/Visibility.hpp> #include <string> #include <vector> namespace sfe { enum MediaType { Audio, Subtitle, Video, Unknown }; /** Structure that allows both knowing metadata about each stream, and identifying streams * for selection through Movie::selectStream() */ struct SFE_API StreamDescriptor { /** Return a stream descriptor that identifies no stream. This allows disabling a specific stream kind * * @param type the stream kind (audio, video...) to disable * @return a StreamDescriptor that can be used to disable the given stream kind */ static StreamDescriptor NoSelection(MediaType type); MediaType type; //!< Stream kind: video, audio or subtitle int identifier; //!< Internal stream identifier in the media, used for choosing which stream to enable std::string language; //!< Language code defined by ISO 639-2, if set by the media }; typedef std::vector<StreamDescriptor> Streams; } #endif
true
813e5d14d108b7aac718c419a71f7b0c59ad3b34
C++
bdonkey/DataStructures-Algorithms
/DSA Crack Sheet/solutions/57. Permutations of a Given String.cpp
UTF-8
743
3.390625
3
[ "MIT" ]
permissive
// using STL #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { string s; cin >> s; sort(s.begin(), s.end()); do { cout << s << " "; } while (next_permutation(s.begin(), s.end())); cout << endl; } return 0; } /* =================================== */ #include <bits/stdc++.h> using namespace std; void print(string a, int l, int r) { if (l == r) cout << a << " "; else { for (int i = l; i <= r; i++) { swap(a[l], a[i]); print(a, l + 1, r); swap(a[l], a[i]); } } } int main() { int t; cin >> t; while (t--) { string s; cin >> s; print(s, 0, s.size() - 1); cout << endl; } return 0; }
true
92480d682a77a62f3a1a3d2627f18f15a00164e3
C++
Casket/marsh-game-files
/Marsh/Marsh/Attack.cpp
UTF-8
8,326
2.78125
3
[]
no_license
#include "Main.h" Attack::Attack(int x, int y, int vel, int vel_d, Sprite* img, int base_damage, int penetration, int range, int tree_depth, int exp_date, int charge_time) :iDrawable(x, y, vel, vel_d, img) { this->base_damage = base_damage; this->penetration = penetration; this->range = range; this->tree_depth_level = tree_depth; this->expiration_date = exp_date; this->charge_time = charge_time; this->my_type = Wallop; this->distance_traveled = 0; this->death_timer = 0; this->mana_cost = 0; this->x_adjustment = 0; this->y_adjustment = 0; this->target = NULL; } Attack::Attack(int x, int y, int vel, int vel_d, Sprite* img, AttackStatistics stats) :iDrawable(x, y, vel, vel_d, img) { this->base_damage = stats.base_damage; this->penetration = stats.penetration; this->range = stats.range; this->tree_depth_level = stats.tree_depth; this->expiration_date = stats.exp_date; this->charge_time = stats.charge_time; this->my_type = Wallop; this->mana_cost = 0; this->distance_traveled = 0; this->death_timer = 0; this->x_adjustment = 0; this->y_adjustment = 0; this->target = NULL; } Attack::~Attack(void) { } void Attack::set_position_adjustment(int x, int y){ this->x_adjustment = x; this->y_adjustment = y; } Attack* Attack::fetch_me_as_attack(void){ return this; } int Attack::get_mana_cost(void){ return this->mana_cost; } void Attack::set_mana_cost(int m){ this->mana_cost = m; } void Attack::update(void){ this->get_image()->update(); if (!this->alive){ if (++this->death_timer >= this->expiration_date){ this->death_timer = 0; this->get_world()->remove_entity(this); } return; } if (this->distance_traveled >= this->range){ //this->start_death_sequence(); this->get_world()->remove_entity(this); } if (!this->detect_collisions()){ this->update_position(); } } void Attack::update_position(void){ if (++this->movement_counter >= this->velocity_delay){ this->distance_traveled += this->velocity; switch(this->get_image()->get_facing()){ case N: this->set_y_pos(this->get_y_pos() - this->velocity); break; case S: this->set_y_pos(this->get_y_pos() + this->velocity); break; case W: this->set_x_pos(this->get_x_pos() - this->velocity); break; case E: this->set_x_pos(this->get_x_pos() + this->velocity); break; case NE: this->set_x_pos(this->get_x_pos() + (int) (this->velocity * ANGLE_SHIFT)); this->set_y_pos(this->get_y_pos() - (int) (this->velocity * ANGLE_SHIFT)); break; case SE: this->set_x_pos(this->get_x_pos() + (int) (this->velocity * ANGLE_SHIFT)); this->set_y_pos(this->get_y_pos() + (int) (this->velocity * ANGLE_SHIFT)); break; case SW: this->set_x_pos(this->get_x_pos() - (int) (this->velocity * ANGLE_SHIFT)); this->set_y_pos(this->get_y_pos() + (int) (this->velocity * ANGLE_SHIFT)); break; case NW: this->set_x_pos(this->get_x_pos() - (int) (this->velocity * ANGLE_SHIFT)); this->set_y_pos(this->get_y_pos() - (int) (this->velocity * ANGLE_SHIFT)); break; } } } bool Attack::detect_collisions(void){ std::list<iDrawable*>* entities = this->get_world()->get_active_entities(); int my_x = this->get_reference_x(); int my_y = this->get_reference_y(); int my_width = this->get_bounding_width(); int my_height = this->get_bounding_height(); int check_x, check_y, check_width, check_height; std::list<iDrawable*>::iterator iter; std::list<iDrawable*>::iterator end = entities->end(); for (iter = entities->begin(); iter != end; iter++){ iDrawable* check = (*iter); if (check == this) continue; if (check == this->my_caster) continue; if (check->my_type == this->my_caster->my_type) continue; if (check->my_type == Wallop){ Attack* check_attack = check->fetch_me_as_attack(); if (check_attack->my_caster == this->my_caster) continue; /*if (check_attack->my_caster->my_type == this->my_caster->my_type) continue;*/ } check_x = check->get_reference_x(); check_y = check->get_reference_y(); check_width = check->get_bounding_width(); check_height = check->get_bounding_height(); if (check_width == 0 && check_height == 0) continue; if (detect_hit(my_x, my_y, my_height, my_width, check_x, check_y, check_width, check_height)){ this->attack_target((*iter)); return true; } } return false; } void Attack::attack_target(iDrawable* target){ target->deal_with_attack(this); } bool Attack::detect_hit(int my_x, int my_y, int my_height, int my_width, int check_x, int check_y, int check_width, int check_height){ if (my_y <= (check_y + check_height) && (my_y) >= check_y){ if (check_x <= (my_x + my_width) && check_x >= (my_x)){ return true; } else if ((my_x) <= (check_x + check_width) && my_x >= (check_x)){ return true; } } if ((my_y + my_height) >= (check_y) && (my_y + my_width) <= (check_y + check_height)){ if (check_x <= (my_x + my_width) && check_x >= (my_x)){ return true; } else if ((my_x) <= (check_x + check_width) && my_x >= (check_x)){ return true; } } if ((my_x ) <= (check_x + check_width) && (my_x ) >= check_x){ if (check_y <= (my_y + my_height) && check_y >= (my_y)){ return true; } else if ((my_y) <= (check_y + check_height) && my_y >= (check_y)){ return true; } } if ((my_x + my_width) >= (check_x) && (my_x + my_width) <= (check_x + check_width)){ if (check_y <= (my_y + my_height) && check_y >= (my_y)){ return true; } else if ((my_y) <= (check_y + check_height) && my_y >= (check_y)){ return true; } } return false; } void Attack::start_death_sequence(void){ this->alive = false; this->death_timer = 0; this->get_image()->casting_update(); } void Attack::set_my_caster(Combat* caster){ this->my_caster = caster; } Combat* Attack::get_my_caster(void){ return this->my_caster; } void Attack::deal_with_attack(Attack* attack){ if (!this->alive || !attack->alive) return; // which attack should die? if (this->tree_depth_level == attack->tree_depth_level){ // kill both dem this->start_death_sequence(); attack->start_death_sequence(); } else if(this->tree_depth_level > attack->tree_depth_level){ // kill that attack this->base_damage -= attack->base_damage; if (this->base_damage <= 0) this->start_death_sequence(); attack->start_death_sequence(); } else { // i die yo attack->base_damage -= this->base_damage; if (attack->base_damage <= 0) attack->start_death_sequence(); this->start_death_sequence(); } } int Attack::get_charge_time(void){ int charge = this->charge_time - FOCUS_EFFECT * this->my_caster->focus; if (charge < 0) return 0; return charge; } iDrawable* Attack::get_above_target(void){ return this->my_caster; } Attack* Attack::clone(int x, int y, Direction dir){ int damage, penetrate, charge; damage = this->base_damage; penetrate = this->penetration; charge = this->charge_time; Sprite* image = this->get_image()->clone(dir); Attack* result = new Attack(x, y, this->velocity, this->velocity_delay, image, damage, penetrate, this->range, this->tree_depth_level, this->expiration_date, charge); int image_width = this->get_image()->get_current_frame()->w; switch(dir){ case N: result->set_boundary_value(this->get_bounding_height(), this->get_bounding_width(), this->reference_horizontal, this->reference_vertical); y -= this->y_adjustment + this->get_bounding_height(); break; case S: result->set_boundary_value(this->get_bounding_height(), this->get_bounding_width(), this->reference_horizontal, this->reference_vertical); y += this->y_adjustment; break; case W: result->set_boundary_value(this->get_bounding_width(), this->get_bounding_height(), this->reference_horizontal, this->reference_vertical); x -= this->x_adjustment + this->get_bounding_width(); y -= this->y_adjustment; break; case E: result->set_boundary_value(this->get_bounding_width(), this->get_bounding_height(), this->reference_horizontal, this->reference_vertical); y -= this->y_adjustment; break; } result->set_x_pos(x); result->set_y_pos(y); result->set_my_caster(this->my_caster); result->my_type = Wallop; result->spell_id = this->spell_id; result->set_position_adjustment(this->x_adjustment, this->y_adjustment); return result; }
true
addd5c7b4a4d05c27ef7cea728e6a7fc3a5280d0
C++
jeffbahns/scheme-to-cpp
/CodeGenerator.h
UTF-8
1,215
2.734375
3
[]
no_license
#ifndef CODEGENERATOR_H #define CODEGENERATOR_H #include <iostream> #include <fstream> #include <vector> using namespace std; class CodeGenerator { public: CodeGenerator(char * filename); ~CodeGenerator(); void write(string code_to_write); void define(string function_name); void end_define(); void param(string param); void end_param(); void stmt_ident(string ident, bool return_val); // rule 8 void num_literal(string lit, bool return_val); // rule 7->10 void quoted_literal(string lit, bool return_val); // rule 11 /* ACTIONS, grouped by similar structure*/ void if_begin(); // rule 19 void if_cond_end(); void if_else_part(); void if_else_part_end(); void action_begin(string to_write, bool return_val); // rules 20->41, 43 void action_end(bool return_val, bool is_nested); /**/ void display(); // rule 42 void endDisplay(); /**/ private: bool middle_param; // if in middle of param list use ',' to separate params bool main_function; // to check if we are in middle of generating main file, has differnent return type pretty much string current_op; ofstream cppfile; }; #endif
true
f207a7532c4e111c9c0904fa252cd289695b8c81
C++
WenYang-Lai/NCTU_Homework
/AdvencedUnixPrograming/hw3/include/jobs.h
UTF-8
894
2.671875
3
[]
no_license
#ifndef __JOBS__ #define __JOBS__ #include <stdio.h> #include <stdlib.h> #include <map> using namespace std; struct Process{ struct Process *next; char **argv; int pid; bool completed; bool stopped; Process(int i_pid, char** i_argv){ next = NULL; pid = i_pid; argv = i_argv; completed = false; stopped = false; } }; struct Job{ Process *first_process; bool background; int pgid; int id; Job(int i_id, int i_pgid, Process* p, bool i_background) { background = i_background; id = i_id; pgid = i_pgid; first_process = p; } }; extern map< int, Job* > job_list; void make_job_continue(Job *j); void make_job_stop(Job *j); bool job_is_completed(Job *j); Job* find_job(int pgid); bool job_is_stopped (Job *j); bool job_is_stopped (Job *j); Process* job_find_process(Job *j, int pid); void job_dump_process(Job *j); #endif
true
b3cc9f9649fa1aac4ee3601e939f1caa28a9e03e
C++
rahulroshan96/placement
/Amazon/isLands.cpp
UTF-8
910
3.203125
3
[]
no_license
#include <iostream> #include <string.h> using namespace std; #define ROW 4 #define COL 4 bool isSafe(int a[][COL], bool M[][COL], int i, int j) { return ( (i>=0 && i<ROW) && (j>=0 && j<COL) && a[i][j] && !M[i][j]); } void DFS(int a[][COL], bool M[][COL],int i, int j) { int rowNbr[] = {-1, -1, -1, 0, 0, 1, 1, 1}; int colNbr[] = {-1, 0, 1, -1, 1, -1, 0, 1}; M[i][j] = true; for(int k=0;k<8;k++) { if(isSafe(a,M,i+rowNbr[k],j+colNbr[k])) DFS(a, M, i+rowNbr[k], j+colNbr[k]); } } int findIslands(int a[][COL]) { int count = 0; bool M[ROW][COL]; memset(M, false, sizeof(M)); for(int i=0;i<ROW;i++) for(int j=0;j<COL;j++) { if(a[i][j] && !M[i][j]) { DFS(a,M,i,j); count++; } } return count; } int main() { int a[ROW][COL]; for(int i=0;i<ROW;i++) { for(int j=0;j<COL;j++) { cin>>a[i][j]; } } cout<<findIslands(a); return 0; }
true
390919b8f04b2f9585a94cd7ccbd2602138f7fa4
C++
JonasRock/ARXML_LanguageServer
/src/messageParser.cpp
UTF-8
2,687
2.640625
3
[ "Apache-2.0" ]
permissive
#include "messageParser.hpp" #include "lspExceptions.hpp" void lsp::MessageParser::register_response_callback(const uint32_t id, response_callback callback) { if(callback) response_callbacks_[id] = callback; } void lsp::MessageParser::register_notification_callback(const std::string &notification, jsonrpcpp::notification_callback callback) { if(callback) notification_callbacks_[notification] = callback; } void lsp::MessageParser::register_request_callback(const std::string &request, jsonrpcpp::request_callback callback) { if(callback) request_callbacks_[request] = callback; } jsonrpcpp::entity_ptr lsp::MessageParser::parse(const std::string &json_str) { jsonrpcpp::entity_ptr entity = do_parse(json_str); if (entity && entity->is_notification()) { jsonrpcpp::notification_ptr notification = std::dynamic_pointer_cast<jsonrpcpp::Notification>(entity); if (notification_callbacks_.find(notification->method()) != notification_callbacks_.end()) { jsonrpcpp::notification_callback callback = notification_callbacks_[notification->method()]; if (callback) { callback(notification->params()); } return nullptr; } } else if (entity && entity->is_request()) { jsonrpcpp::request_ptr request = std::dynamic_pointer_cast<jsonrpcpp::Request>(entity); if (request_callbacks_.find(request->method()) != request_callbacks_.end()) { jsonrpcpp::request_callback callback = request_callbacks_[request->method()]; if (callback) { jsonrpcpp::response_ptr response = callback(request->id(), request->params()); if (response) return response; } else { jsonrpcpp::Error err("MethodNotFound", -32601); jsonrpcpp::Response(request->id(), err); } } } else if (entity && entity->is_response()) { jsonrpcpp::response_ptr response = std::dynamic_pointer_cast<jsonrpcpp::Response>(entity); if (response_callbacks_.find(response->id().int_id()) != response_callbacks_.end()) { response_callback callback = response_callbacks_[response->id().int_id()]; if (callback) { //Remove the callback for this id response_callbacks_.erase(response->id().int_id()); callback(response->result()); return nullptr; } } } throw lsp::badEntityException(); return nullptr; }
true
cb8393ab05269820d0e5d420e32c78f229f09362
C++
opensourceyouthprogramming/h5vcc
/external/angle/samples/angle/Resource_Tracking/resource_tracking.cc
UTF-8
3,339
2.546875
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Note that this sample is incomplete in that it gives a snippet of code // that demonstrates a use case of eglSetResourceTrackerANGLE(), but does not // have any driving main() method. #include <assert.h> #include <iostream> #include <sstream> #include <string> #include <d3d11.h> #include <EGL/eglext.h> #include <wrl.h> EGLDisplay g_display; bool GetDebugName(ID3D11Resource* resource, std::string* name) { char data[512]; UINT data_size = 512; if (SUCCEEDED(resource->GetPrivateData(WKPDID_D3DDebugObjectName, &data_size, data))) { name->assign(data, data_size); return true; } return false; } void GetResourceData(const EGLResourceTrackerDataAngle *data, std::stringstream *stream) { const char* op = (data->iOpType == EGL_ANGLE_TRACK_OPTYPE_CREATE) ? "+" : "-"; (*stream) << " " << op << (data->iSize >> 10) << "KB;"; if (data->iOpType == EGL_ANGLE_TRACK_OPTYPE_DESTROY) { // data->pResource should be treated as invalid during resource // deallocation events return; } ComPtr<IUnknown> unk(reinterpret_cast<IUnknown*>(data->pResource)); switch (data->iType) { case EGL_ANGLE_TRACK_TYPE_TEX2D: { ComPtr<ID3D11Texture2D> tex; assert(SUCCEEDED(unk.As(&tex))); D3D11_TEXTURE2D_DESC desc; tex->GetDesc(&desc); (*stream) << " Tex2D: " << desc.Width << "x" << desc.Height << ";"; std::string name; if (GetDebugName(tex.Get(), &name)) (*stream) << " " << name << ";"; break; } case EGL_ANGLE_TRACK_TYPE_BUFFER: { ComPtr<ID3D11Buffer> buf; assert(SUCCEEDED(unk.As(&buf))); D3D11_BUFFER_DESC desc; buf->GetDesc(&desc); (*stream) << " Buffer:"; if (desc.BindFlags & D3D11_BIND_VERTEX_BUFFER) { (*stream) << " VB"; } if (desc.BindFlags & D3D11_BIND_INDEX_BUFFER) { (*stream) << " IB"; } if (desc.BindFlags & D3D11_BIND_CONSTANT_BUFFER) { (*stream) << " CB"; } (*stream) << ";"; std::string name; if (GetDebugName(buf.Get(), &name)) (*stream) << " " << name << ";"; break; } case EGL_ANGLE_TRACK_TYPE_SWAPCHAIN: { ComPtr<IDXGISwapChain> swap_chain; assert(SUCCEEDED(unk.As(&swap_chain))); DXGI_SWAP_CHAIN_DESC desc; swap_chain->GetDesc(&desc); (*stream) << " SwapChain: " << desc.BufferDesc.Width << "x" << desc.BufferDesc.Height << ";"; break; } default: (*stream) << " Unknown resource;"; } } void ResourceTracker(const EGLResourceTrackerDataAngle *data, void *user_data) { static int mem_count; static int hit_countes; if (data->iOpType == EGL_ANGLE_TRACK_OPTYPE_CREATE) { mem_count += data->iSize; } else { mem_count -= data->iSize; } std::stringstream info; GetResourceData(data, &info); std::cout << "VMem: " << (mem_count >> 20) << "MB" << info.str(); } void InitializeMemoryTracking() { PFNEGLSETRESOURCETRACKERANGLEPROC eglSetResourceTrackerANGLE = reinterpret_cast<PFNEGLSETRESOURCETRACKERANGLEPROC>(eglGetProcAddress( "eglSetResourceTrackerANGLE")); assert(eglSetResourceTrackerANGLE); eglSetResourceTrackerANGLE(g_display, &ResourceTracker, this); }
true
0352c2cf9f09f70834abfd595f067c3ed8ebe8eb
C++
lexoux/rayTracer
/projet3D/BBox.h
UTF-8
684
2.5625
3
[]
no_license
// // BBox.h // projet3D // // Created by Julien Philip on 14/04/2015. // Copyright (c) 2015 Julien Philip. All rights reserved. // #ifndef projet3D_BBox_h #define projet3D_BBox_h #include "Vec3.h" class BBox{ public : inline BBox(){ xL=0; yL=0; zL=0; coin=Vec3f(0,0,0); }; inline BBox(float _xL,float _yL,float _zL,Vec3f _coin){ xL=_xL; yL=_yL; zL=_zL; coin=_coin; }; int maxAxis() { if (xL>yL && xL>zL) { return 0; } else if (yL>zL) return 1; else return 2; } float xL,yL,zL; Vec3f coin; }; #endif
true
aac1cdeabd89ca35375cf1d3226d3ebc92ecbfad
C++
Yippie-Calle/CS165
/Projects/Skeet/birds.cpp
UTF-8
1,050
2.90625
3
[]
no_license
#include "birds.h" #include "uiDraw.h" NormalBird::NormalBird(const Point& point) : Bird(point) { float dx = random(3, 6); float dy = random(0, 4); if (point.getY() > 0) { dy *= -1; } Velocity newVelocity; newVelocity.setDx(dx); newVelocity.setDy(dy); setVelocity(newVelocity); } ToughBird::ToughBird(const Point& point) : Bird(point) { health = Points_Tough_Bird_Kill; float dx = random(3, 6); float dy = random(0, 4); if (point.getY() > 0) { dy *= -1; } Velocity newVelocity; newVelocity.setDx(dx); newVelocity.setDy(dy); setVelocity(newVelocity); }; void NormalBird::draw() { if (alive) { drawCircle(point, Birds_Radius); } } int NormalBird::hit() { kill(); return Points_Normal_Bird; } void ToughBird::draw() { if (alive) { drawCircle(point, Birds_Radius); } } int ToughBird::hit() { health--; if (health == 0) kill(); return Points_Tough_Bird; } void SacredBird::draw() { if (alive) { drawCircle(point, Birds_Radius); } } int SacredBird::hit() { kill(); return Points_Sacred_Bird; }
true
607a38ef0163aa5f15921cc813b8cda70fde2e60
C++
ontario-tech-pw-II/a7-shayne-lewis
/Part-1/SavingsAccount.cpp
UTF-8
755
3.40625
3
[]
no_license
#include "SavingsAccount.h" using namespace std; // constructor initializes balance and interest rate SavingsAccount::SavingsAccount( double initialBalance, double rate ) : Account( initialBalance ) { // your code if( rate >= 0.0 ) interestRate = rate*100; else interestRate = 0.0; } double SavingsAccount::calculateInterest() { // your code double bal = getBalance(); double interestbal = 0; interestbal = bal * interestRate; return interestbal; } void SavingsAccount::display(ostream & os) const { // your code //Account type: Saving //Balance: $ 400.00 //Interest Rate (%): 12.00 os << "Account type: Saving" << endl; os << "Balance: $ " << getBalance() << endl; os << "Interest Rate (%): " << interestRate << ".0" << endl; }
true
585e6209127596a9ee97e904e417ab344cd6e2e1
C++
KarlaRivera/Programacion_Sistemas
/Segundo Parcial/Parcial2/Arreglos/main.cpp
UTF-8
377
3.03125
3
[]
no_license
#include <iostream> #include <string> using namespace std; int int_array[5]; void arreglo (int int_array[]) { for (int i=0; i<5; i++) { cout<<"Ingresar numero :"; cin>>int_array[i]; } for (int i=0; i<5; i++) { cout<<"Numero :"<<int_array[i]<<"\n"; } } int main() { arreglo(int_array); return 0; }
true
9cdad12c6970ad2f9a43d46e64aeb64893fdc25d
C++
ptrv/SimpleSceneGraph
/src/Rotate.cpp
UTF-8
891
2.6875
3
[]
no_license
/* * Rotate.cpp * Szenegraph * * Created by peter on 03.06.08. * Copyright 2008 __MyCompanyName__. All rights reserved. * */ #include "Rotate.h" #define foreach( i, c )\ typedef __typeof__( c ) c##_CONTAINERTYPE;\ for( c##_CONTAINERTYPE::iterator i = c.begin(); i != c.end(); ++i ) Rotate::Rotate(const std::string& name, const float winkel, const float rx, const float ry, const float rz) : Transform(name), winkel_(winkel), rx_(rx), ry_(ry), rz_(rz) { } Rotate::~Rotate() { } //getter and setter void Rotate::set_degree(float deg) { this->winkel_= deg; } float Rotate::get_degree() { return this->winkel_; } //apply transformation matrix void Rotate::transform(void) { glRotatef(this->winkel_, this->rx_, this->ry_, this->rz_); } //apply inverse transfomation void Rotate::apply_inverse() { glRotatef(-this->winkel_, -this->rx_, -this->ry_, -this->rz_); }
true
d8cd31d4743e845003f42e54b4dfc431c90efca5
C++
mayfes-ar/game
/ar2016/src/game/single_game_player.cpp
UTF-8
31,635
2.609375
3
[]
no_license
#include "game/single_player_game.h" #include <typeinfo.h> std::shared_ptr<SinglePlayerGame::Teresa> SinglePlayerGame::makeTeresa(int x = 0, int y = 0, double size = 1.0) { if (x == 0 && y == 0) { x = rand() % (WIDTH - 100) + 50; y = rand() % (HEIGHT - 100) + 50; } auto enemy = std::make_shared<Teresa>(x, y, *this, size); if (player->isContacted(enemy)) { enemy = std::make_shared<Teresa>(x, y - 200, *this, size); } enemySubList.push_back(enemy); drawList.push_back(enemy); return enemy; } std::shared_ptr<SinglePlayerGame::RocketWanwan> SinglePlayerGame::makeRocketWanwan(int x, int y, double size = 1.0) { auto enemy = std::make_shared<RocketWanwan>(x, y, *this, size); if (player->isContacted(enemy)) { enemy = std::make_shared<RocketWanwan>(x, y - 200, *this, size); } enemySubList.push_back(enemy); drawList.push_back(enemy); return enemy; } std::shared_ptr<SinglePlayerGame::Inundation> SinglePlayerGame::makeInundation() { auto enemy = std::make_shared<Inundation>(0, HEIGHT+200, *this, 1); enemySubList.push_back(enemy); drawList.push_back(enemy); return enemy; } std::shared_ptr<SinglePlayerGame::Ghorst> SinglePlayerGame::makeGhorst(int x, int y, double size = 1.0) { auto enemy = std::make_shared<Ghorst>(x, y, *this, size); enemySubList.push_back(enemy); drawList.push_back(enemy); return enemy; } std::shared_ptr<SinglePlayerGame::Switch> SinglePlayerGame::makeSwitch(int x, int y, double size = 1.0) { auto enemy = std::make_shared<Switch>(x, y, *this, size); if (player->isContacted(enemy)) { enemy = std::make_shared<Switch>(x, y - 200, *this, size); } enemySubList.push_back(enemy); drawList.push_back(enemy); return enemy; } std::shared_ptr<SinglePlayerGame::Ufo> SinglePlayerGame::makeUfo(int x, int y, double size = 1.0) { auto enemy = std::make_shared<Ufo>(x, y, *this, size); enemySubList.push_back(enemy); drawList.push_back(enemy); return enemy; } std::shared_ptr<SinglePlayerGame::Ray> SinglePlayerGame::makeRay(int x, int y, double size = 1.0) { auto enemy = std::make_shared<Ray>(x, y, *this, size); enemySubList.push_back(enemy); drawList.push_back(enemy); return enemy; } std::shared_ptr<SinglePlayerGame::Cloud> SinglePlayerGame::makeCloud(int x, int y, double size = 1.0) { auto enemy = std::make_shared<Cloud>(x, y, *this, size); enemySubList.push_back(enemy); drawList.push_back(enemy); return enemy; } std::shared_ptr<SinglePlayerGame::Drop> SinglePlayerGame::makeDrop(int x, int y, double size = 1.0) { auto enemy = std::make_shared<Drop>(x, y, *this, size); enemySubList.push_back(enemy); drawList.push_back(enemy); return enemy; } std::shared_ptr<SinglePlayerGame::Eagle> SinglePlayerGame::makeEagle(int x, int y, double size = 1.0) { auto enemy = std::make_shared<Eagle>(x, y, *this, size); if (player->isContacted(enemy)) { enemy = std::make_shared<Eagle>(x, y - 200, *this, size); } enemySubList.push_back(enemy); drawList.push_back(enemy); return enemy; } std::shared_ptr<SinglePlayerGame::Heiho> SinglePlayerGame::makeHeiho(int x, int y, double size = 1.0) { auto enemy = std::make_shared<Heiho>(x, y, *this, size); if (player->isContacted(enemy)) { enemy = std::make_shared<Heiho>(x, y - 200, *this, size); } enemySubList.push_back(enemy); drawList.push_back(enemy); return enemy; } std::shared_ptr<SinglePlayerGame::Fire> SinglePlayerGame::makeFire(int x, int y, double size = 1.0) { auto enemy = std::make_shared<Fire>(x, y, *this, size); enemySubList.push_back(enemy); drawList.push_back(enemy); return enemy; } std::shared_ptr<SinglePlayerGame::tutoHeiho> SinglePlayerGame::maketutoHeiho(int x, int y, double size = 1.0) { auto enemy = std::make_shared<tutoHeiho>(x, y, *this, size); if (tutoplayer->isContacted(enemy)) { enemy = std::make_shared<tutoHeiho>(x, y - 200, *this, size); } enemySubList.push_back(enemy); drawList.push_back(enemy); return enemy; } std::shared_ptr<SinglePlayerGame::tutoFire> SinglePlayerGame::maketutoFire(int x, int y, double size = 1.0) { auto enemy = std::make_shared<tutoFire>(x, y, *this, size); enemySubList.push_back(enemy); drawList.push_back(enemy); return enemy; } bool SinglePlayerGame::onStart() { using namespace std; fps.isShow = true; srand((unsigned int)time(NULL)); // INTRO mode.setMode([this]() { class Title : public Object { Difficulty& difficulty; public: Title(Difficulty& difficulty_) : difficulty(difficulty_) { layer = 50; } bool draw() { DrawExtendGraph(0, 0, WIDTH, HEIGHT, imgHandles["s_game_background"], true); // DrawExtendGraph(WIDTH / 2 - 429 / 2, 30, WIDTH / 2 + 429 / 2, 30 + 47, imgHandles["s_game_op_title"], true); // DrawExtendGraph(WIDTH/2-50, 400, WIDTH/2+50, 400+150, imgHandles["s_game_player"], true); SetFontSize(32); SetFontThickness(9); DrawString(200, 150, "EASY", difficulty == EASY ? GetColor(255,0,0) : GetColor(0, 0, 0)); DrawString(200, 250, "HARD", difficulty == HARD ? GetColor(255, 0, 0) : GetColor(0, 0, 0)); DrawString(200, 350, "NIGHTMARE", difficulty == NIGHTMARE ? GetColor(255, 0, 0) : GetColor(0, 0, 0)); SetFontSize(24); SetFontThickness(6); switch (difficulty) { case EASY: { DrawString(450, 150, "←おすすめ", GetColor(255, 0, 0)); break; } case HARD: { DrawString(450, 250, "←べてらん向け", GetColor(255, 0, 0)); break; } case NIGHTMARE: { DrawString(450, 350, "←じごく", GetColor(255, 0, 0)); break; } default: break; } DrawExtendGraph(760, 200, 760+Player::width*3, 200+Player::height*3, imgHandles[difficulty == EASY ? "s_game_player" : difficulty == HARD ? "s_game_player_damage" : "s_game_player_over"], true); return true; } }; drawList.clear(); drawList.push_back(make_shared<Title>(difficulty)); drawList.push_back(make_shared<CurtainObject>(true)); bgm = make_shared<BGM>(0); bgm->start(); }, -1); // TUTORIAL mode.setMode([this]() { drawList.clear(); // maxPlayerDamage = difficulty == EASY ? 5 : difficulty == HARD ? 10 : 20; tutoplayer = std::make_shared<tutoPlayer>(WIDTH / 2 - 100 / 2, HEIGHT / 2 - 150 / 2, tutoPlayer::width, tutoPlayer::height, "s_game_player", maxPlayerDamage, *this); auto makeBlock = [this](int x, int y, int width, int height) { auto block = make_shared<SingleGameBlockObject>(x, y, width, height, true); blockList.push_back(block); drawList.push_back(block); }; makeBlock(0 - 200, 650, 200, 200); makeBlock(0, 650, 200, 200); makeBlock(0 + 200, 650, 200, 200); makeBlock(0 + 400, 650, 200, 200); makeBlock(0 + 600, 650, 200, 200); makeBlock(0 + 800, 650, 200, 200); makeBlock(0 + 1000, 650, 200, 200); makeBlock(0 + 1200, 650, 200, 200); makeBlock(0 + 1400, 650, 200, 200); makeBlock(0 - 400, 0, 250, HEIGHT); makeBlock(WIDTH + 150, 0, 250, HEIGHT); drawList.push_back(tutoplayer); drawList.push_back(make_shared<Background>(share.handle)); drawList.push_back(make_shared<CurtainObject>(true)); share.rectMutex.lock(); markerList.clear(); markerList.shrink_to_fit(); for (int i = 0; i < share.rects.size(); i++) { auto marker = std::make_shared<Marker>(share.rects[i], false, i, *this); markerList.push_back(marker); drawList.push_back(marker); } share.rectMutex.unlock(); class Title : public Object { bool start = false; int timer = 0; std::shared_ptr<SinglePlayerGame::tutoHeiho> tutoenemy; Tutorial *tutorial; std::string tutosen1 = "あ、危ない!!"; std::string tutosen2 = "お姫様に火の玉が当たりそうです!!"; std::string tutosen3 = "お姫様を守るために盾を使ってみましょう"; std::string tutosen4 = "マーカーを火の玉に当ててみてください"; std::string tutosen5 = "剣を使えば敵を倒すこともできます"; std::string tutosen6 = "盾と剣を使ってお姫様を敵から守りましょう!!"; std::string tutosen7 = "これでチュートリアルを終了します"; std::string tutosen0 = "チュートリアルをスキップするにはSを押してください"; public: Title(std::shared_ptr<SinglePlayerGame::tutoHeiho> &tutoenemy_, SinglePlayerGame& game_) { layer = 50; tutoenemy = tutoenemy_; tutorial = &game_.tutorial; } void update() { if (tutoenemy->childfire != NULL) { if (tutoenemy->childfire->getIsFreezed() && start == false) { start = true; } if (start == true) { timer++; } } } bool draw() { update(); UINT w, h; getPngSize("img/s_game/tuto0.png",&w,&h); DrawExtendGraph(WIDTH - w/2, 30, WIDTH, 30 + h/2, imgHandles["s_game_tuto0"], true); //DrawString(WIDTH - 700, 30, std::to_string(w).c_str(), GetColor(0, 0, 0)); if (timer <= FPS * 2/3) { } else if (timer <= FPS * 2) { getPngSize("img/s_game/tuto1.png", &w, &h); //DrawString(550, 350, tutosen1.c_str(), GetColor(0, 0, 0)); DrawGraph(WIDTH/2-w/2, HEIGHT/2-h/2, imgHandles["s_game_tuto1"], true); } else if (timer <= FPS * 4) { getPngSize("img/s_game/tuto2.png", &w, &h); //DrawString(550, 350, tutosen2.c_str(), GetColor(0, 0, 0)); DrawGraph(WIDTH / 2 - w / 2, HEIGHT / 2 - h / 2, imgHandles["s_game_tuto2"], true); } else if (timer <= FPS * 6) { getPngSize("img/s_game/tuto3.png", &w, &h); //DrawString(550, 350, tutosen3.c_str(), GetColor(0, 0, 0)); DrawGraph(WIDTH / 2 - w / 2, HEIGHT / 2 - h / 2, imgHandles["s_game_tuto3"], true); } else if (timer <= FPS * 8) { *tutorial = BEATFIRE; getPngSize("img/s_game/tuto4.png", &w, &h); //DrawString(550, 350, tutosen4.c_str(), GetColor(0, 0, 0)); DrawGraph(WIDTH / 2 - w / 2, HEIGHT / 2 - h / 2, imgHandles["s_game_tuto4"], true); if (timer == FPS * 8 && tutoenemy->childfire->getIsAlive()) { timer--; } } else if (timer <= FPS * 10) { *tutorial = BEATHEIHO; getPngSize("img/s_game/tuto5.png", &w, &h); //DrawString(550, 350, tutosen5.c_str(), GetColor(0, 0, 0)); DrawGraph(WIDTH / 2 - w / 2, HEIGHT / 2 - h / 2, imgHandles["s_game_tuto5"], true); if (timer == FPS * 10 && tutoenemy->getIsAlive()) { timer--; } } else if (timer <= FPS * 12) { getPngSize("img/s_game/tuto6.png", &w, &h); //DrawString(550, 350, tutosen6.c_str(), GetColor(0, 0, 0)); DrawGraph(WIDTH / 2 - w / 2, HEIGHT / 2 - h / 2, imgHandles["s_game_tuto6"], true); } else if (timer <= FPS * 14) { getPngSize("img/s_game/tuto7.png", &w, &h); //DrawString(550, 350, tutosen7.c_str(), GetColor(0, 0, 0)); DrawGraph(WIDTH / 2 - w / 2, HEIGHT / 2 - h / 2, imgHandles["s_game_tuto7"], true); } else { *tutorial = END; } return true; } /** * PNGファイルの画像サイズを取得する */ bool getPngSize(const char* path, UINT* width, UINT* height) { FILE* f; fopen_s(&f, path,"rb"); if (!f) return false; BYTE header[8];// PNGファイルシグネチャ if (fread(header, sizeof(BYTE), 8, f) < 8) { fclose(f); return false; } const static BYTE png[] = { 0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a }; if (memcmp(header, png, 8) != 0) { fclose(f); return false; } BYTE ihdr[25];// IHDRチャンク(イメージヘッダ) if (fread(ihdr, sizeof(BYTE), 25, f) < 25) { fclose(f); return false; } // length = 13 (0x0D) const static BYTE length[] = { 0x00, 0x00, 0x00, 0x0D }; if (memcmp(ihdr, length, 4) != 0) { fclose(f); return false; } // IHDR if (memcmp(ihdr + 4, "IHDR", 4) != 0) { fclose(f); return false; } BYTE* p; DWORD w; p = (BYTE*)&w; p[0] = ihdr[8 + 3]; p[1] = ihdr[8 + 2]; p[2] = ihdr[8 + 1]; p[3] = ihdr[8 + 0]; DWORD h; p = (BYTE*)&h; p[0] = ihdr[12 + 3]; p[1] = ihdr[12 + 2]; p[2] = ihdr[12 + 1]; p[3] = ihdr[12 + 0]; *width = (UINT)w; *height = (UINT)h; fclose(f); return true; } /*typedef struct { int w, h; } Size; Size GetJpegSize(const char *png) { Size ret = { 0, 0 }; unsigned char buf[8]; FILE *f; fopen_s(&f, png, "rb"); while (f && fread(buf, 1, 2, f) == 2 && buf[0] == 0xff) { if (buf[1] == 0xc0 && fread(buf, 1, 7, f) == 7) { ret.h = buf[3] * 256 + buf[4]; ret.w = buf[5] * 256 + buf[6]; } else if (buf[1] == 0xd8 || (fread(buf, 1, 2, f) == 2 && !fseek(f, buf[0] * 256 + buf[1] - 2, SEEK_CUR))) continue; break; } if (f) fclose(f); return ret; }*/ }; if (tutorial == END) { } tutoenemy = maketutoHeiho(WIDTH, 300, 1); drawList.push_back(make_shared<Title>(tutoenemy, *this)); }, -1); // GAME mode.setMode([this]() { drawList.clear(); drawList.push_back(make_shared<CurtainObject>(true)); maxPlayerDamage = difficulty == EASY ? 10 : difficulty == HARD ? 10 : 20; player = std::make_shared<Player>(WIDTH / 2 - 100 / 2, HEIGHT / 2 - 150 / 2, Player::width, Player::height, "s_game_player", maxPlayerDamage, *this); auto makeBlock = [this](int x, int y, int width, int height) { auto block = make_shared<SingleGameBlockObject>(x, y, width, height, true); blockList.push_back(block); drawList.push_back(block); }; makeBlock(0 - 200, 650, 200, 200); makeBlock(0, 650, 200, 200); makeBlock(0 + 200, 650, 200, 200); makeBlock(0 + 400, 650, 200, 200); makeBlock(0 + 600, 650, 200, 200); makeBlock(0 + 800, 650, 200, 200); makeBlock(0 + 1000, 650, 200, 200); makeBlock(0 + 1200, 650, 200, 200); makeBlock(0 + 1400, 650, 200, 200); makeBlock(0 - 400, 0, 250, HEIGHT); makeBlock(WIDTH + 150, 0, 250, HEIGHT); drawList.push_back(player); drawList.push_back(make_shared<Background>(share.handle)); /* makeEffect("s_game_coin", 200, 200, 50, 50, true); makeEffect("s_game_coin", 250, 200, 50, 50, true, 150, 1, 3); makeEffect("s_game_coin", 300, 200, 50, 50, true, 150, 2); makeEffect("s_game_coin", 350, 200, 50, 50, true, 150, 2, 3); makeEffect("s_game_koumori", 400, 200, 50, 50, true); makeEffect("s_game_koumori", 450, 200, 50, 50, true, 150, 2); makeEffect("s_game_koumori", 500, 200, 50, 50, true, 150, 3); makeEffect("s_game_koumori", 550, 200, 50, 50, true, 150, 4); makeEffect("s_game_hit", 600, 200, 50, 50, true, 150, 2); makeEffect("s_game_enemy_over", 650, 200, 50, 50, true, 150, 3); makeEffect("s_game_sword", 700, 200, 50, 50, true, 150, 2); */ share.rectMutex.lock(); markerList.clear(); markerList.shrink_to_fit(); for (int i = 0; i < share.rects.size(); i++) { auto marker = std::make_shared<Marker>(share.rects[i], false, i, *this); markerList.push_back(marker); drawList.push_back(marker); } share.rectMutex.unlock(); bgm = make_shared<BGM>(1); bgm->start(); class Title : public Object { bool start = false; int timer = 0; int *gametimer; public: Title(int *gametimer_,SinglePlayerGame& game_) { layer = 50; gametimer = gametimer_; } void update() { timer++; (*gametimer)++; } bool draw() { UINT w, h; if (timer <= FPS * 6) { update(); } if (timer <= FPS * 2 / 3) { } else if (timer <= FPS * 2) { getPngSize("img/s_game/countdown_3.png", &w, &h); DrawGraph(WIDTH / 2 - w / 2, HEIGHT / 2 - h / 2, imgHandles["s_game_countdown3"], true); } else if (timer <= FPS * 2 + FPS * 4/3) { getPngSize("img/s_game/countdown_2.png", &w, &h); DrawGraph(WIDTH / 2 - w / 2, HEIGHT / 2 - h / 2, imgHandles["s_game_countdown2"], true); } else if (timer <= FPS * 2 + FPS * 8/3) { getPngSize("img/s_game/countdown_1.png", &w, &h); DrawGraph(WIDTH / 2 - w / 2, HEIGHT / 2 - h / 2, imgHandles["s_game_countdown1"], true); } else if (timer <= FPS * 6) { getPngSize("img/s_game/s.png", &w, &h); DrawGraph(WIDTH / 2 - 5 * w / 2, HEIGHT / 2 - h / 2, imgHandles["s_game_s"], true); DrawGraph(WIDTH / 2 - 3 * w / 2, HEIGHT / 2 - h / 2, imgHandles["s_game_t"], true); DrawGraph(WIDTH / 2 - w / 2, HEIGHT / 2 - h / 2, imgHandles["s_game_a"], true); DrawGraph(WIDTH / 2 + w / 2, HEIGHT / 2 - h / 2, imgHandles["s_game_r"], true); DrawGraph(WIDTH / 2 + 3 * w / 2, HEIGHT / 2 - h / 2, imgHandles["s_game_t"], true); } return true; } /** * PNGファイルの画像サイズを取得する */ bool getPngSize(const char* path, UINT* width, UINT* height) { FILE* f; fopen_s(&f, path, "rb"); if (!f) return false; BYTE header[8];// PNGファイルシグネチャ if (fread(header, sizeof(BYTE), 8, f) < 8) { fclose(f); return false; } const static BYTE png[] = { 0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a }; if (memcmp(header, png, 8) != 0) { fclose(f); return false; } BYTE ihdr[25];// IHDRチャンク(イメージヘッダ) if (fread(ihdr, sizeof(BYTE), 25, f) < 25) { fclose(f); return false; } // length = 13 (0x0D) const static BYTE length[] = { 0x00, 0x00, 0x00, 0x0D }; if (memcmp(ihdr, length, 4) != 0) { fclose(f); return false; } // IHDR if (memcmp(ihdr + 4, "IHDR", 4) != 0) { fclose(f); return false; } BYTE* p; DWORD w; p = (BYTE*)&w; p[0] = ihdr[8 + 3]; p[1] = ihdr[8 + 2]; p[2] = ihdr[8 + 1]; p[3] = ihdr[8 + 0]; DWORD h; p = (BYTE*)&h; p[0] = ihdr[12 + 3]; p[1] = ihdr[12 + 2]; p[2] = ihdr[12 + 1]; p[3] = ihdr[12 + 0]; *width = (UINT)w; *height = (UINT)h; fclose(f); return true; } }; drawList.push_back(make_shared<Title>(&timer,*this)); }, -1); // RESULT mode.setMode([this]() { drawList.clear(); drawList.push_back(make_shared<CurtainObject>(true)); class Title : public Object { bool hasPlayerWon = true; std::shared_ptr<SinglePlayerGame::Player> player; int maxTime; int timer; public: Title(bool hasPlayerWon_, std::shared_ptr<SinglePlayerGame::Player> player_, int maxTime_, int timer_) { layer = 50; hasPlayerWon = hasPlayerWon_; player = player_; maxTime = maxTime_; timer = timer_; } //クリアの文 const std::string clear1 = "おめでとうございます。"; const std::string clear2 = "見事お姫様を守り抜くことができました。"; const std::string clear3 = "彼女はあなたを”好き”になったようです。"; const std::string clear4 = "あなたはどうですか。"; const std::string clear5 = "姫を守るために取った”剣”の重さ"; const std::string clear6 = "どうか覚えていてくださいね。"; const std::string clear7 = "遊んでくれてありがとうございました。"; //ゲームオーバーの文 const std::string dead1 = "「姫」を守り切ることはできませんでした。"; const std::string dead2 = "この悲劇は、たかが「ゲーム」でしょうか。"; const std::string dead3 = "いいえ、「姫」は確かにいました。"; const std::string dead4 = "「あなた」という現実、「姫」という物語"; const std::string dead5 = "二人は、いつでも会うことができるのです。"; const std::string dead6 = "次からは、ちゃんと守ってくださいね。"; const std::string dead7 = "遊んでくれてありがとうございました。"; bool draw() { if (HEIGHT - rect.y > 60) { rect.y += 1;//文章スクロール用 } if (hasPlayerWon) { //********勝利画面 //画像 DrawExtendGraph(0, 0, WIDTH, HEIGHT, imgHandles["s_game_result_background1"], true); DrawExtendGraph(650, 450, 650 + 320, 450 + 311, imgHandles["s_game_result_castle"], true); DrawExtendGraph(900, 170, WIDTH-80, 380, imgHandles["s_game_result_frame_star"], true); DrawExtendGraph(820, 20, WIDTH, 230, imgHandles["s_game_result_rainbow"], true); DrawExtendGraph(1100, 1046 / 3 + 100, 1100 + 621 / 3, 1046 / 3 + 1046 / 3 + 100, imgHandles["s_game_player"], true); DrawExtendGraph(10, 20, WIDTH/2-20, HEIGHT-10, imgHandles["s_game_result_background_gameover1"], true); //スクロール文章 DrawExtendGraph(50, HEIGHT-rect.y, WIDTH / 2 - 40, HEIGHT - rect.y +HEIGHT -60, imgHandles["s_game_result_clear1"], true); /* DrawString(50, HEIGHT - rect.y, clear1.c_str(), GetColor(25, 25, 25)); DrawString(50, HEIGHT + 150 - rect.y, clear2.c_str(), GetColor(25, 25, 25)); DrawString(50, HEIGHT + 300 - rect.y, clear3.c_str(), GetColor(25, 25, 25)); DrawString(50, HEIGHT + 450 - rect.y, clear4.c_str(), GetColor(25, 25, 25)); DrawString(50, HEIGHT + 600 - rect.y, clear5.c_str(), GetColor(25, 25, 25)); DrawString(50, HEIGHT + 750 - rect.y, clear6.c_str(), GetColor(25, 25, 25)); DrawString(50, HEIGHT + 900 - rect.y, clear7.c_str(), GetColor(25, 25, 25)); */ //スコア std::string clearScore = "得点 : " + std::to_string(maxTime + (player->getMaxDamage() - player->getPlayerDamage()) * 50); DrawString(940, 230, clearScore.c_str(), GetColor(225, 225, 225)); std::string damage = ("受けたダメージ : " + std::to_string(player->getPlayerDamage())); DrawString(940, 300, damage.c_str(), GetColor(255, 225, 225)); } else { //******ゲームオーバー画面 //画像・ゲームオーバー DrawExtendGraph(0, 0, WIDTH, HEIGHT, imgHandles["s_game_result_background2"], true); DrawExtendGraph(170, 300, 170 + 1600 / 5, HEIGHT, imgHandles["s_game_result_sketch"], true); DrawExtendGraph(621 / 3 - 50, 450, 621 / 3 + 621 / 4 - 50, HEIGHT, imgHandles["s_game_player_drowned"], true); DrawExtendGraph(0, 0, WIDTH, HEIGHT, imgHandles["s_game_result_stage1"], true); DrawExtendGraph(220, 100, 520, 320, imgHandles["s_game_result_frame_blackstar"], true); DrawExtendGraph(550, HEIGHT - rect.y, WIDTH - 140, HEIGHT - rect.y + HEIGHT - 10, imgHandles["s_game_result_dead1"], true); /* //スクロール文章・ゲームオーバー DrawString(600, HEIGHT - rect.y, dead1.c_str(), GetColor(225, 225, 225)); DrawString(600, HEIGHT+150 - rect.y, dead2.c_str(), GetColor(225, 225, 225)); DrawString(600, HEIGHT+300 - rect.y, dead3.c_str(), GetColor(225, 225, 225)); DrawString(600, HEIGHT+450 - rect.y, dead4.c_str(), GetColor(225, 225, 225)); DrawString(600, HEIGHT+600 - rect.y, dead5.c_str(), GetColor(225, 225, 225)); DrawString(600, HEIGHT + 750 - rect.y, dead6.c_str(), GetColor(225, 225, 225)); DrawString(600, HEIGHT + 900 - rect.y, dead7.c_str(), GetColor(225, 225, 225)); */ //スコア std::string deadScore = "得点 : " + std::to_string(maxTime - timer); std::string playTime = "記録 : " + std::to_string((maxTime - timer) / 30) + "秒"; DrawString(270, 170, deadScore.c_str(), GetColor(225, 225, 225)); DrawString(270, 230, playTime.c_str(), GetColor(225, 225, 225)); } return true; } }; drawList.push_back(make_shared<Title>(hasPlayerWon, player, maxTime, timer)); //yu if (hasPlayerWon) { //勝利画面のエフェクト・リザルト makeEffect("s_game_result_hanabi", 400, 100, 500, 500, true, 50, 3, 8); makeEffect("s_game_result_hanabi", 700, 50, 300, 300, true, 50, 3, 0); } else { //ゲームオーバーのエフェクト・リザルト makeEffect("s_game_result_kirakira", 150, 270, 500, 500, false, 150, 1, 0); } bgm->stop(); bgm = make_shared<BGM>(2, hasPlayerWon); bgm->start(); }, -1); return Game::onStart(); } bool SinglePlayerGame::onUpdate() { willFinishMode = false; switch (mode.getMode()) { case INTRO: { // イントロダクション if (counterForWait == 0) { counterForWait = 5; if (key[KEY_INPUT_RETURN]) { willFinishMode = true; //drawList.clear(); } else if (key[KEY_INPUT_1]) { difficulty = EASY; } else if (key[KEY_INPUT_2]) { difficulty = HARD; } else if (key[KEY_INPUT_3]) { difficulty = NIGHTMARE; } else if (key[KEY_INPUT_UP]) { difficulty = difficulty == EASY ? NIGHTMARE : difficulty == HARD ? EASY : HARD; } else if (key[KEY_INPUT_DOWN]) { difficulty = difficulty == EASY ? HARD : difficulty == HARD ? NIGHTMARE : EASY; } else { counterForWait = 0; } } else if (counterForWait > 0) { counterForWait--; } break; } case TUTORIAL: { if (tutorial != START) { // 認識したマーカーを描画 share.rectMutex.lock(); for (auto marker : markerList) { marker->setRect(share.rects[marker->getIndex()]); } share.rectMutex.unlock(); } switch (tutorial) { case START: { if (heihoFreezeTimeRemain >= 0) { heihoFreezeTimeRemain--; } if(heihoFreezeTimeRemain == FPS*4 +5){ } if (heihoFreezeTimeRemain == 0) { tutoenemy->freeze(); tutoenemy->childfire->freeze(); } break; } case BEATFIRE: {//Titleクラス if (tutoenemy->childfire->getIsAlive()) { tutoenemy->childfire->deathDecision(); } break; } case BEATHEIHO: {//Titleクラス if (tutoenemy->getIsAlive()) { tutoenemy->deathDecision(); } break; } case END: {//Titleクラス willFinishMode = true; //makeEffect("s_game_curtain_close", 0, 0, WIDTH, HEIGHT, false, 150, 2, 1); break; } } if (key[KEY_INPUT_S]) { willFinishMode = true; } for (auto enemy : enemyList) { enemy->update(); } for (auto enemy : enemySubList) { enemyList.push_back(enemy); } enemySubList.clear(); enemySubList.shrink_to_fit(); tutoplayer->update(key); break; } case GAME: { // playing tutoenemy->setIsDead(); if (tutoenemy->childfire != NULL) { tutoenemy->childfire->setIsDead(); } timer -= 1; if (timer <= 0) { willFinishMode = true; } // 認識したマーカーを描画 share.rectMutex.lock(); for (auto marker : markerList) { marker->setRect(share.rects[marker->getIndex()]); } share.rectMutex.unlock(); player->update(key); for (auto enemy : enemyList) { enemy->deathDecision(); enemy->update(); } for (auto enemy : enemySubList) { enemyList.push_back(enemy); } enemySubList.clear(); enemySubList.shrink_to_fit(); if (hasPlayerWon && player->deathDecision(enemyList)) { hasPlayerWon = false; bgm->stop(); willFinishMode = true; } // 敵の出現を管理する switch (difficulty) { case EASY: { switch (maxTime - timer) { case 100: { makeEagle(0, 0, 1); break; } case 600: { makeRocketWanwan(-RocketWanwan::width / 2, HEIGHT / 2 + 50); break; } case 800: { makeCloud(0, 50, 1); break; } case 1000: { makeInundation(); } case 2000: { makeHeiho(WIDTH, 300, 1); break; } case 2300: { makeUfo(0, 50, 1); break; } case 2800: { makeCloud(0, 50, 1); break; } case 3400: { makeHeiho(WIDTH, 300, 1); break; } default: { } } // 定期的に実行する場合など if (timer < 2500 && (maxTime - timer) % 50 == 0) { makeTeresa(); } break; } case HARD: { switch (maxTime - timer) { case 100: { makeRocketWanwan(-RocketWanwan::width / 2, HEIGHT / 2 + 50); break; } case 200: { makeInundation(); makeEagle(0, 0, 1); makeEagle(200, 0, 1); makeEagle(400, 0, 1); makeEagle(600, 0, 1); break; } case 300: { makeUfo(0, 50, 1); makeRocketWanwan(WIDTH - RocketWanwan::width / 2, HEIGHT / 2 + 50); makeRocketWanwan(WIDTH - RocketWanwan::width / 2, HEIGHT / 2 + 50 + RocketWanwan::height); break; } case 600: { makeEagle(0, 0, 1); makeEagle(200, 0, 1); makeEagle(400, 0, 1); makeEagle(600, 0, 1); makeCloud(0, 50, 1); makeCloud(200, 50, 1); makeCloud(800, 50, 1); break; } case 900: { makeInundation(); makeUfo(0, 50, 1); makeRocketWanwan(-RocketWanwan::width / 2, HEIGHT / 2 + 50); makeRocketWanwan(-RocketWanwan::width / 2, HEIGHT / 2 + 50 + RocketWanwan::height); break; } case 1200: { makeEagle(0, 0, 1); makeEagle(200, 0, 1); makeHeiho(WIDTH, 300, 1); break; } case 1500: { makeCloud(0, 50, 1); makeCloud(200, 50, 1); makeCloud(800, 50, 1); makeRocketWanwan(WIDTH - RocketWanwan::width / 2, HEIGHT / 2 + 50); makeHeiho(WIDTH, 300, 1); break; } case 1600: { makeUfo(0, 50, 1); break; } case 1800: { makeInundation(); makeEagle(0, 0, 1); makeEagle(200, 0, 1); makeEagle(400, 0, 1); makeEagle(600, 0, 1); break; } case 2100: { makeUfo(0, 50, 1); makeRocketWanwan(-RocketWanwan::width, HEIGHT / 2 + 50); makeEagle(0, 0, 1); makeCloud(200, 50, 1); break; } case 2400: { makeHeiho(WIDTH, 300, 1); break; } case 2700: { makeCloud(0, 50, 1); makeCloud(200, 50, 1); makeCloud(800, 50, 1); break; } case 3000: { makeInundation(); makeEagle(0, 0, 1); makeEagle(200, 0, 1); break; } case 3300: { makeUfo(0, 50, 1); makeRocketWanwan(WIDTH - RocketWanwan::width / 2, HEIGHT / 2 + 50); makeRocketWanwan(WIDTH - RocketWanwan::width / 2, HEIGHT / 2 + 50 + RocketWanwan::height); break; } default: { } } // 定期的に実行する場合など if (timer < 150 && (maxTime - timer) % 5 == 0) { makeTeresa(); } break; } case NIGHTMARE: { switch (maxTime - timer) { case 400: case 700: case 1000: case 1200: case 1400: case 100: { makeInundation(); } default: { } } // 定期的に実行する場合など if (timer < 150 && (maxTime - timer) % 3 == 0) { makeTeresa(); } else if ((maxTime - timer) % 30 == 0){ makeTeresa(); } if ((maxTime - timer) % 10 == 0 && rand()%2 == 0) { makeHeiho(WIDTH, 250 + rand()%100, 1); } if ((maxTime - timer) % 30 == 0 && rand() % 3 == 0) { makeRocketWanwan(rand()%2 == 0 ? -RocketWanwan::width : WIDTH+RocketWanwan::width, HEIGHT / 2 + 50); } if ((maxTime - timer) % 30 == 0 && rand() % 3 == 0) { if (rand() % 10 == 0) { makeEagle(-1000, -1000, 10); } else { makeEagle(-600, 0, 1); makeEagle(-400, 0, 1); makeEagle(-200, 0, 1); makeEagle(0, 0, 1); makeEagle(200, 0, 1); makeEagle(400, 0, 1); makeEagle(600, 0, 1); } } if ((maxTime - timer) % 100 == 0 && rand() % 2 == 0) { makeCloud(0, 50, 1); } if ((maxTime - timer) % 100 == 0 && rand() % 2 == 0) { makeUfo(WIDTH, 100, 1); } break; } } break; } case RESULT: { // リザルト画面 result_timer -= 1; if (key[KEY_INPUT_RETURN]) { willFinishMode = true; } break; } default: break; } if (key[KEY_INPUT_ESCAPE]) { share.willFinish = true; } if (key[KEY_INPUT_N] && waitNCounter == 0) { willFinishMode = true; waitNCounter = FPS / 3; } if (waitNCounter > 0) { waitNCounter--; } for (auto& itr = enemyList.begin(); itr != enemyList.end();) { if ((*itr)->getIsAlive()) { ++itr; } else { itr = enemyList.erase(itr); } } if (willFinishMode && !isChangingMode) { isChangingMode = true; drawList.push_back(make_shared<CurtainObject>(false)); funcTimer.set([this]() { isChangingMode = false; mode.goNext(); }, FPS*2); } funcTimer.update(); return Game::onUpdate(); } bool SinglePlayerGame::onFinish() { bgm->stop(); thread.join(); return true; }
true
13ac30cbc33acd24fe37519eddbd033b7525ba58
C++
Wevan/untitled3
/main.cpp
UTF-8
6,916
3.09375
3
[]
no_license
#include <iostream> #include <stdio.h> #include <pthread.h> #include <cstdlib> #include <unistd.h> #include <semaphore.h> #define BUFFER_SIZE 10//缓冲区大小为10 #define N_WRITER 20 //写者数目 #define N_READER 5 //读者数目 #define W_SLEEP 1 //控制写频率 #define R_SLEEP 1 //控制读频率 #define P(S) sem_wait(S) #define V(S) sem_post(S) pthread_rwlock_t rwlock;//define write and read lock pthread_t wid[N_WRITER], rid[N_READER]; int readerCnt = 0, writerCnt = 0; sem_t sem_read; sem_t sem_write; pthread_mutex_t write_mutex; pthread_mutex_t read_mutex; //生产者消费者问题 char *buffer; sem_t *mutex, *empty, *full;//三个信号量,互斥信号量mutex,技术信号量empty和full int x, y;//生产者和消费者在buffer中下标 void output()//输出buffer数组 { for (int i = 0; i < BUFFER_SIZE; i++) { printf("%c", buffer[i]); printf(" "); } printf("\n"); } void *produce(void *pVoid)//生产者函数 { int j = 0; do { P(empty); P(mutex); printf("%lu%s", pthread_self(), " ——————生产—————— ");//输出当前线程的id号,以及正在执行的次数 buffer[(x++) % BUFFER_SIZE] = 'P';//生产就赋值A output();//输出buffer j++; V(mutex); V(full); } while (j != 30);//每个线程可以做30次 } void *consume(void *pVoid)//消费者函数 { int j; j = 0; do { P(full); P(mutex); printf("%lu%s", pthread_self(), " ------消费------ "); buffer[(y++) % BUFFER_SIZE] = 'C';//消费时,赋值为B output();//输出buffer值 j++; V(mutex); V(empty); } while (j != 30);//每个线程可以消费30次 } void ConAndPro() { int i; x = 0; y = 0; buffer = (char *) malloc(BUFFER_SIZE * sizeof(char *)); mutex = static_cast<sem_t *>(malloc(sizeof(sem_t *))); empty = static_cast<sem_t *>(malloc(sizeof(sem_t *))); full = static_cast<sem_t *>(malloc(sizeof(sem_t *))); for (i = 0; i < BUFFER_SIZE; i++)//初始化buffer数组,默认为N { buffer[i] = 'N'; } //semaphore sem_init(mutex, 1, 1);//初始化互斥信号量mutex为1 sem_init(empty, 0, BUFFER_SIZE);//初始化计数信号量empty为BUFFER_SIZE sem_init(full, 0, 0);//初始化计数信号量full为0 //multipthread pthread_t tid[10]; pthread_attr_t attr; pthread_attr_init(&attr); //创建5个生产者线程和5个消费者线程 for (i = 0; i < 5; i++) { pthread_create(&tid[i], &attr, consume, NULL); pthread_create(&tid[i + 5], &attr, produce, NULL); } //让每个线程在主线程main执行前全部执行完毕。 for (i = 0; i < 10; i++) { pthread_join(tid[i], NULL); } } //读者优先 void *reader(void *arg) { printf("编号为%d的读者进入等待中。。。\n", pthread_self()); sem_wait(&sem_read); readerCnt++; if (readerCnt == 1) { pthread_mutex_lock(&write_mutex); } sem_post(&sem_read); printf("编号为%d的读者开始读\n", pthread_self()); printf("编号为%d的读者读完\n", pthread_self()); printf("-----------------------\n"); sem_wait(&sem_read); readerCnt--; if (readerCnt == 0) { pthread_mutex_unlock(&write_mutex); } sem_post(&sem_read); sleep(R_SLEEP); pthread_exit((void *) 0); } void *writer(void *arg) { //let the reader run first printf("写者%d线程进入等待中...\n", pthread_self()); pthread_mutex_lock(&write_mutex); printf("写者%d开始写文件\n", pthread_self()); printf("写者%d结束写文件\n", pthread_self()); printf("-----------------------\n"); pthread_mutex_unlock(&write_mutex); sleep(W_SLEEP); pthread_exit((void *) 0); } void readerFirst() { readerCnt = 0, writerCnt = 0; printf("多线程,读者优先\n"); pthread_mutex_init(&write_mutex, NULL); pthread_mutex_init(&read_mutex, NULL); sem_init(&sem_read, 0, 1); int i = 0; for (i = 0; i < N_WRITER; i++) { pthread_create(&wid[i], NULL, writer, NULL); } for (i = 0; i < N_READER; i++) { pthread_create(&rid[i], NULL, reader, NULL); } sleep(1); } //写者优先 void *mywriter(void *arg) { printf("写者%d线程进入等待中...\n", pthread_self()); sem_wait(&sem_write); writerCnt++; if(writerCnt==1){ pthread_mutex_lock(&read_mutex); } sem_post(&sem_write); //执行写操作 pthread_mutex_lock(&write_mutex); printf("写者%d开始写文件\n", pthread_self()); printf("写者%d结束写文件\n", pthread_self()); printf("---------------------\n"); pthread_mutex_unlock(&write_mutex); //写完以后,写着退出 sem_wait(&sem_write); writerCnt--; if (writerCnt==0){ pthread_mutex_unlock(&read_mutex); } sem_post(&sem_write); } void *myreader(void *arg) { printf("编号为%d的读者进入等待中。。。\n", pthread_self()); pthread_mutex_lock(&read_mutex); sem_wait(&sem_read); readerCnt++; if (readerCnt == 1) { pthread_mutex_lock(&write_mutex); } sem_post(&sem_read); printf("编号为%d的读者开始读\n", pthread_self()); printf("编号为%d的读者读完\n", pthread_self()); printf("---------------------\n"); pthread_mutex_unlock(&read_mutex); sem_wait(&sem_read); readerCnt--; if (readerCnt==0){ pthread_mutex_unlock(&write_mutex); } sem_post(&sem_read); sleep(R_SLEEP); pthread_exit((void *) 0); } void writerFirst() { readerCnt=0; writerCnt=0; printf("多线程,写者优先\n"); pthread_mutex_init(&write_mutex, NULL); pthread_mutex_init(&read_mutex, NULL); sem_init(&sem_write, 0, 1); int i = 0; for (i = 0; i < N_READER; i++) { pthread_create(&rid[i], NULL, myreader, NULL); } for (i = 0; i < N_WRITER; i++) { pthread_create(&wid[i], NULL, mywriter, NULL); } sleep(1); } void menu() { printf("======================================\n"); printf("15140A01 第一组 基于Linux的线程与进程控制\n"); printf("1.生产者消费者\n"); printf("2.读者写者问题之读者优先\n"); printf("3.读者写者问题之写者优先\n"); printf("4.退出程序\n"); printf("======================================\n"); printf("请输入选项:"); int a; std::cin >> a; switch (a) { case 1: ConAndPro(); menu(); break; case 2: readerFirst(); menu(); break; case 3: writerFirst(); menu(); break; case 4: printf("谢谢使用"); exit(0); } } int main() { menu(); return 0; }
true
670996905aaee889336ee15688496bcc23f4891f
C++
cristiandonosoc/rothko
/rothko/math/math.cc
UTF-8
15,773
2.859375
3
[ "BSD-2-Clause" ]
permissive
// Copyright 2019, Cristián Donoso. // This code has a BSD license. See LICENSE. #include "rothko/math/math.h" #include <cassert> #include <cmath> #include "rothko/logging/logging.h" #include "rothko/utils/strings.h" namespace rothko { // Math Functions ================================================================================== float Sqrt(float f) { return std::sqrt(f); } float Sin(float radian_angle) { return std::sin(radian_angle); } float Asin(float radian_angle) { return std::asin(radian_angle); } float Cos(float radian_angle) { return std::cos(radian_angle); } float Acos(float radian_angle) { return std::acos(radian_angle); } float Tan(float radian_angle) { return std::tan(radian_angle); } float Atan(float radian_angle) { return std::atan(radian_angle); } float Atan2(float x, float y) { return std::atan2f(x, y); } //Vectors ========================================================================================== // Vec2 -------------------------------------------------------------------------------------------- Vec2 Normalize(const Vec2& v) { Vec2 result = {}; float length = Length(v); if (length != 0.0f) { result.x = v.x / length; result.y = v.y / length; } return result; } // Vec3 -------------------------------------------------------------------------------------------- Vec3 Normalize(const Vec3& v) { Vec3 result = {}; float length = Length(v); if (length != 0.0f) { result.x = v.x / length; result.y = v.y / length; result.z = v.z / length; } return result; } // Vec4 -------------------------------------------------------------------------------------------- Vec4 Normalize(const Vec4& v) { Vec4 result = {}; float length = Length(v); if (length != 0.0f) { result.x = v.x / length; result.y = v.y / length; result.z = v.z / length; result.w = v.w / length; } return result; } // Matrices ======================================================================================== // Mat3 -------------------------------------------------------------------------------------------- float Determinant(const Mat3& m) { // clang-format off float a = m.get(0, 0); float b = m.get(0, 1); float c = m.get(0, 2); float d = m.get(1, 0); float e = m.get(1, 1); float f = m.get(1, 2); float g = m.get(2, 0); float h = m.get(2, 1); float i = m.get(2, 2); return a*(e*i - f*h) - b*(d*i - f*g) + c*(d*h-e*g); // clang-format on } Mat3 Transpose(const Mat3& m) { Mat3 result; result.cols[0] = m.row(0); result.cols[1] = m.row(1); result.cols[2] = m.row(2); return result; } // Mat4 -------------------------------------------------------------------------------------------- namespace { // The indices are the rows and columns to ignore. Mat3 GetAdjugateSubMatrix(const Mat4& m, int ignore_x, int ignore_y) { int current_x = 0; int current_y = 0; Mat3 result = {}; for (int y = 0; y < 4; y++) { if (y == ignore_y) continue; current_x = 0; for (int x = 0; x < 4; x++) { if (x == ignore_x) continue; result.set(current_x, current_y, m.get(x, y)); current_x++; } current_y++; } return result; } } // namespace Mat4 Adjugate(const Mat4& m) { Mat4 adjugate = {}; for (int y = 0; y < 4; y++) { for (int x = 0; x < 4; x++) { int multiplier = IS_EVEN((x + 1) + (y + 1)) ? 1 : -1; Mat3 sub_matrix = GetAdjugateSubMatrix(m, x, y); float determinant = Determinant(sub_matrix); float res = multiplier * determinant; /* adjugate.set(x, y, res); */ adjugate.elements[x][y] = res; } } return adjugate; } float Determinant(const Mat4& m) { // clang-format off Vec3 r0 = {m.get(0, 1), m.get(0, 2), m.get(0, 3)}; Vec3 r1 = {m.get(1, 1), m.get(1, 2), m.get(1, 3)}; Vec3 r2 = {m.get(2, 1), m.get(2, 2), m.get(2, 3)}; Vec3 r3 = {m.get(3, 1), m.get(3, 2), m.get(3, 3)}; Mat3 m0(r1, r2, r3); Mat3 m1(r0, r2, r3); Mat3 m2(r0, r1, r3); Mat3 m3(r0, r1, r2); float d0 = Determinant(m0); float d1 = Determinant(m1); float d2 = Determinant(m2); float d3 = Determinant(m3); return d0 * m.get(0, 0) - d1 * m.get(1, 0) + d2 * m.get(2, 0) - d3 * m.get(3, 0); // clang-format on } Mat4 Inverse(const Mat4& m) { float determinant = Determinant(m); assert(determinant != 0); float one_over_det = 1.0f / determinant; Mat4 adjugate = Adjugate(m); return adjugate * one_over_det; } Vec3 PositionFromTransformMatrix(const Mat4& m) { Vec3 position; position.x = m.get(0, 3); position.y = m.get(1, 3); position.z = m.get(2, 3); return position; } Vec3 RotationFromTransformMatrix(const Mat3& m) { Vec3 rotation; rotation.x = -Atan2(m.get(2, 1), m.get(2, 2)); rotation.y = -Atan2(-m.get(2, 0), Sqrt(m.get(2, 1) * m.get(2, 1) + m.get(2, 2) * m.get(2, 2))); rotation.z = -Atan2(m.get(1, 0), m.get(0, 0)); return rotation; } Vec3 RotationFromTransformMatrix(const Mat4& m) { return RotationFromTransformMatrix(ToMat3(m)); } Vec3 ScaleFromTransformMatrix(const Mat4& m) { Vec3 scale; scale.x = Length(ToVec3(m.row(0))); scale.y = Length(ToVec3(m.row(1))); scale.z = Length(ToVec3(m.row(2))); return scale; } void DecomposeTransformMatrix(const Mat4& m, Vec3* position, Vec3* rotation, Vec3* scale) { *position = PositionFromTransformMatrix(m); *rotation = RotationFromTransformMatrix(m); *scale = ScaleFromTransformMatrix(m); } Mat4 Transpose(const Mat4& m) { Mat4 result; result.cols[0] = m.row(0); result.cols[1] = m.row(1); result.cols[2] = m.row(2); result.cols[3] = m.row(3); return result; } // Frames (axis) =================================================================================== AxisFrame GetAxisFrame(Vec3 direction) { Vec3 forward = Normalize(direction); Vec3 up, right; if (forward.y == 1.0f) { up = {1, 0, 0}; right = {0, 0, 1}; } if (forward.y == -1.0f) { up = {-1, 0, 0}; right = {0, 0, 1}; } else { // Use the up trick to find the frame of reference of the normal. Vec3 temp_up = Vec3::Up(); right = Normalize(Cross(forward, temp_up)); up = Normalize(Cross(right, forward)); } return {forward, up, right}; } // Transformation Matrices ========================================================================= Mat4 FromRows(Vec3 x, Vec3 y, Vec3 z) { return {{x.x, x.y, x.z, 0}, {y.x, y.y, y.z, 0}, {z.x, z.y, z.z, 0}, { 0, 0, 0, 1}}; } Mat4 FromColumns(Vec3 x, Vec3 y, Vec3 z) { return {{x.x, y.y, z.z, 0}, {x.x, y.y, z.z, 0}, {x.x, y.y, z.z, 0}, { 0, 0, 0, 1}}; } Mat4 Translate(const Vec3& v) { // clang-format off return Mat4({ 1, 0, 0, v.x}, { 0, 1, 0, v.y}, { 0, 0, 1, v.z}, { 0, 0, 0, 1}); // clang-format on } Mat4 Rotate(const Vec3& v, float radian_angle) { float sin = Sin(radian_angle); float cos = Cos(radian_angle); float cosm = (1 - cos); // The angle has to be normalized. Vec3 u = Normalize(v); // clang-format off return Mat4( { cos + u.x * u.x * cosm, u.x * u.y * cosm + u.z * sin, u.x * u.z * cosm - u.y * sin, 0}, {u.y * u.x * cosm - u.z * sin, cos + u.y * u.y * cosm, u.y * u.z * cosm + u.x * sin, 0}, {u.z * u.x * cosm + u.y * sin, u.z * u.y * cosm - u.x * sin, cos + u.z * u.z * cosm, 0}, { 0, 0, 0, 1}); // clang-format on } Vec3 Rotate(Vec3 pos, float radian_x, float radian_y) { if (radian_x != 0) { pos = RotateX(pos, radian_x); } if (radian_y != 0) { pos = RotateY(pos, radian_y); } return pos; } Mat4 Scale(const Vec3& v) { // clang-format on return {{ v.x, 0, 0, 0}, { 0, v.y, 0, 0}, { 0, 0, v.z, 0}, { 0, 0, 0, 1}}; // clang-format off } Mat4 LookAt(Vec3 pos, Vec3 target, Vec3 hint_up) { // We calculate the new axis for the coordinate system. Vec3 forward = Normalize(pos - target); // Z: Point into the target. Vec3 right = Normalize(Cross(hint_up, forward)); // X: Right to the new Z axis. Vec3 up = Cross(forward, right); // Y: Simply cross Z and X. // Comes out normalized. // NOTE: Each field in this matrix is pre-calculated to be the new matrix that transform the // world to view-space. In reality, this is the result of a two step process: // 1. Rotate the world to the new coordinate system (forward, up, right). // 2. Translate the world to the camera position. // Then this would result in the following matrix multiplication: // // [r.x, r.y, r.z, 0] [ 1, 0, 0, 0] // [u.x, u.y, u.z, 0] * [ 0, 1, 0, 0] // [f.x, f.y, f.z, 0] [ 0, 0, 1, 0] // [ 0, 0, 0, 1] [-p.x, -p.y, -p.z, 0] // // Thus explaining the final row with the dot products. // // NOTE2: The translation is negative because the camera Z axis *points in* the forward // direction, thus making the camera *look in* it's negative -Z axis. // NOTE3: f = forward, u = up, r = right, p = pos. // clang-format off return {{ right.x, right.y, right.z, -Dot(right, pos)}, { up.x, up.y, up.z, -Dot(up, pos)}, { forward.x, forward.y, forward.z, -Dot(forward, pos)}, { 0, 0, 0, 1}}; // clang-format on } Mat4 Frustrum(float l, float r, float b, float t, float n, float f) { // clang-format off return {{ 2 * n / (r - l), 0, 0, 0}, { 0, 2 * n / (t - b), 0, 0}, {(r + l) / (r - l), (t + b) / (t - b), -(f + n) / (f - n), -2 * f * n / (f - n)}, { 0, 0, -1, 0}}; // clang-format on } Mat4 Ortho(float l, float r, float b, float t) { // clang-format off return {{ 2 / (r - l), 0, 0, -(r + l) / (r - l)}, { 0, 2 / (t - b), 0, -(t + b) / (t - b)}, { 0, 0, -1, 0}, { 0, 0, 0, 1}}; // clang-format on } Mat4 Ortho(float l, float r, float b, float t, float n, float f) { // clang-format off return {{ 2 / (r - l), 0, 0, -(r + l) / (r - l)}, { 0, 2 / (t - b), 0, -(t + b) / (t - b)}, { 0, 0, -2 / (f - n), -(f + n) / (f - n)}, { 0, 0, 0, 1}}; // clang-format on } Mat4 Perspective(float fov, float aspect_ratio, float near, float far) { float left, right, top, bottom = {}; top = near * Tan(fov / 2.0f); bottom = -top; right = top * aspect_ratio; left = -right; return Frustrum(left, right, bottom, top, near, far); } // Printing ======================================================================================== std::string ToString(const Int2& v) { return StringPrintf("(%d, %d)", v.x, v.y); } std::string ToString(const Vec2& v) { return StringPrintf("(%f, %f)", v.x, v.y); } std::string ToString(const Int3& v) { return StringPrintf("(%d, %d, %d)", v.x, v.y, v.z); } std::string ToString(const Vec3& v) { return StringPrintf("(%f, %f, %f)", v.x, v.y, v.z); } std::string ToString(const Int4& v) { return StringPrintf("(%d, %d, %d, %d)", v.x, v.y, v.z, v.w); } std::string ToString(const Vec4& v) { return StringPrintf("(%f, %f, %f, %f)", v.x, v.y, v.z, v.w); } std::string ToString(const Mat2& m) { auto& e = m.elements; // clang-format off return StringPrintf("(%f, %f), (%f, %f)", e[0][0], e[0][1], e[1][0], e[1][1]); // clang-format on } std::string ToString(const Mat3& m) { auto& e = m.elements; // clang-format off return StringPrintf("(%f, %f, %f), (%f, %f, %f), (%f, %f, %f)", e[0][0], e[0][1], e[0][2], e[1][0], e[1][1], e[1][2], e[2][0], e[2][1], e[2][2]); // clang-format on } std::string ToString(const Mat4& m) { auto& e = m.elements; // clang-format off return StringPrintf("(%f, %f, %f, %f), (%f, %f, %f, %f), (%f, %f, %f, %f), (%f, %f, %f, %f)", e[0][0], e[0][1], e[0][2], e[0][3], e[1][0], e[1][1], e[1][2], e[1][3], e[2][0], e[2][1], e[2][2], e[2][3], e[3][0], e[3][1], e[3][2], e[3][3]); // clang-format on } std::string ToString(const Quaternion& q) { return ToString(q.elements); } // Euler Angles ==================================================================================== Vec3 DirectionFromEuler(float pitch, float yaw) { Vec3 direction; direction.x = Cos(pitch) * Cos(yaw); direction.y = Sin(pitch); direction.z = Cos(pitch) * Sin(yaw); return Normalize(direction); } Vec2 EulerFromDirection(const Vec3& direction) { Vec2 result; // Pitch. result.x = Asin(direction.y); // Yaw. result.y = Atan2(direction.z, direction.x); return result; } // Quaternion ====================================================================================== Quaternion Slerp(const Quaternion& q1, const Quaternion& q2, float t) { float cos_angle = Dot(q1, q2); float angle = Acos(cos_angle); float s1 = Sin((1.0f - t) * angle); float s2 = Sin(t * angle); float i = 1.0f / Sin(angle); Quaternion left = q1 * s1; Quaternion right = q2 * s2; Quaternion res = left + right; res *= i; return res; } Mat3 ToTransformMatrix(const Quaternion& q) { Quaternion n = Normalize(q); float xx = n.x * n.x; float yy = n.y * n.y; float zz = n.z * n.z; float xy = n.x * n.y; float xz = n.x * n.z; float yz = n.y * n.z; float xw = n.x * n.w; float yw = n.y * n.w; float zw = n.z * n.w; // clang-format off return Mat3({1 - 2 * yy - 2 * zz, 2 * xy - 2 * zw, 2 * xz + 2 * yw}, { 2 * xy + 2 * zw, 1 - 2 * xx - 2 * zz, 2 * yz - 2 * xw}, { 2 * xz - 2 * yw, 2 * yz + 2 * xw, 1 - 2 * xx - 2 * yy}); // clang-format on } // NOTE: THIS CODE IS WRONG! /* Vec3 ToEuler(const Quaternion& q) { */ /* float pitch = 0; */ /* float yaw = 0; */ /* float roll = 0; */ /* float test = q.x * q.y + q.z * q.w; */ /* if (test > 0.499) { // singularity at north pole */ /* yaw = 2 * Atan2(q.x, q.w); */ /* pitch = kPI / 2; */ /* roll = 0; */ /* } */ /* if (test < -0.499) { // singularity at south pole */ /* yaw = -2 * Atan2(q.x, q.w); */ /* pitch = -kPI / 2; */ /* roll = 0; */ /* } else { */ /* float sqx = q.x * q.x; */ /* float sqy = q.y * q.y; */ /* float sqz = q.z * q.z; */ /* yaw = Atan2(2 * q.y * q.w - 2 * q.x * q.z, 1 - 2 * sqy - 2 * sqz); */ /* pitch = Asin(2 * test); */ /* roll = Atan2(2 * q.x * q.w - 2 * q.y * q.z, 1 - 2 * sqx - 2 * sqz); */ /* } */ /* return {pitch, yaw, roll}; */ /* } */ Vec3 ToEuler(const Quaternion& q) { // TODO(Cristian): This is very unefficient! We should obtain the angles directly! Mat3 rot = ToTransformMatrix(q); return RotationFromTransformMatrix(rot); } } // namespace rothko
true
583e8fc4555249a59ae400dc71cc96c47f599f71
C++
edwinpadron/Cpp-Primer
/chapter07/7.57.cpp
UTF-8
1,173
3.796875
4
[]
no_license
/* * Exercise 7.57: Write your own version of the Account class. * * by Faisal Saadatmand */ #include <iostream> #include <string> class Account { public: Account() = default; Account(std::string name) : owner(name) {} Account(std::string name, double amt) : owner(name), amount(amt) {} void calculate() { amount += amount * interestRate; } double debt() const { return amount; } static double rate() { return interestRate; } static void rate(double); private: std::string owner; double amount; static double interestRate; static double initRate(); }; // define and initialize static member interestRate double Account::interestRate = initRate(); double Account::initRate() { return 0.03; // 3 percent } void Account::rate(double newRate) { interestRate = newRate; } int main() { std::cout << "Initial rate: " << Account::rate() << '\n'; Account house("faisal", 345000); house.calculate(); std::cout << "Amount: " << house.debt() << " interest rate: " << house.rate() << '\n'; Account::rate(0.025); house.calculate(); std::cout << "Amount: " << house.debt() << " interest rate: " << house.rate() << '\n'; return 0; }
true
0541ce6a07a77759dbb07d53368a2cab8eb15ac1
C++
ExpLife/Norton_AntiVirus_SourceCode
/Consumer/r12.0.6/src/Engine/SND/GRENLEAF/OBJNAME.H
UTF-8
6,992
2.5625
3
[]
no_license
//************************************************************************ // // $Header: S:/GRENLEAF/VCS/OBJNAME.H_v 1.0 12 Mar 1998 12:13:16 DCHI $ // // Description: // Greenleaf ArchiveLib 2.0 // //************************************************************************ // $Log: S:/GRENLEAF/VCS/OBJNAME.H_v $ // // Rev 1.0 12 Mar 1998 12:13:16 DCHI // Initial revision. // //************************************************************************ /* * OBJNAME.H * * Header file for ArchiveLib 2.0 * * Copyright (c) 1994-1996 Greenleaf Software, Inc. * All Rights Reserved * * DESCRIPTION * * This file contains the class definition for ALName. Most of the time * this class is used to contain file names. * * CLASS DEFINITIONS: * * ALName * * REVISION HISTORY * * May 26, 1994 1.0A : First release * * February 14, 1996 2.0A : New release */ #ifndef _OBJNAME_H #define _OBJNAME_H #if defined( __cplusplus ) #include <string.h> #include <iostream> using namespace std; /* * class ALName * * DESCRIPTION * * Object names are mostly used for names of storage objects. * There are enough things that I do with these guys to justify * a class of their own. Having all the object name functions in their * own class also cuts back on the number of functions in ALStorage, * which is already cluttered. * * Besides serving as the mName member in ALStorage, this class is * also pressed into service in ALWildCardExpander, where it is very * handy. * * DATA MEMBERS * * mszName : A pointer to the name associated with this object. * This pointer can be a null pointer. The object is * responsible for deleting this guy in the ALName * destructor, along with the next member, mszOldName. * * mszOldName : A pointer to the last name associated with this * object. When you assign a new name to one of these * objects, the old name gets stored here. This makes * it easy to revert to the old name in case of trouble. * * mCase : One of AL_UPPER, AL_LOWER, or AL_MIXED. If the value * is AL_UPPER or AL_LOWER, the name is forced to all * upper or lower case whenever it is assigned to the * object. * * MEMBER FUNCTIONS * * ALName(const ALName &) : The copy constructor. * ALName(const char *) : Constructor that initializes with a char *. * operator=(const ALName&) : Assignment operator. * operator=(const char *) : Assignment operator for char *. * ~ALName() : Destructor, has to clean up dynamic storage. * operator new() : Memory allocation operatory, only used * when the library is inside the DLL. Be * aware that this operator allocates space for * the object itself, not the strings that it * will contain. * Strcpy() : A protected member function, copies and * converts to the appropriate case if necessary. * GetName() : Returns a pointer to the name string, might * be 0. * GetOldName() : Returns a pointer to the previous name * string, might be 0. * GetSafeName() : Returns a pointer to the name string, but * is guaranteed not to return 0. * GetSafeOldName() : Returns a pointer to the old name string, but * is guaranteed not to return 0. * ChangeExtension() : Change a filename extension to a new one. * ChangeTrailingChar() : Change the trailing character in the filename. * StripFileName() : Remove the filename, leaving the path and drive. * StripPath() : Remove path and drive, leaving the filename. * WildCardMatch() : Test for a match against a regular expression. * operator const char *() : Return a char *. * operator+() : Append a string to this string. * * REVISION HISTORY * * May 26, 1994 1.0A : First release * */ /* * Microsoft won't let me create a cast operator for char _far *. * But they will let me cast to this typedef. Ugly, but it works. */ typedef char AL_DLL_FAR * STRINGF; class AL_CLASS_TYPE ALName { /* Tag public class */ /* * Constructors, destructors, assignment operator, and friends */ public : AL_PROTO ALName( const ALName AL_DLL_FAR & ); AL_PROTO ALName( const char AL_DLL_FAR *s = "", ALCase name_case = AL_MIXED ); ALName AL_DLL_FAR & AL_PROTO operator = ( const ALName AL_DLL_FAR & rhs ); ALName AL_DLL_FAR & AL_PROTO operator = ( const char AL_DLL_FAR * rhs ); AL_PROTO ~ALName(); #if defined( AL_USING_DLL ) || defined( AL_BUILDING_DLL ) void AL_DLL_FAR * AL_PROTO operator new( size_t size ); #endif /* * Note that I don't have the normal prohibition against a copy constructor * or an assignment operator in this class, because I support them here. */ /* * Member Functions */ protected : void AL_PROTO Strcpy( const char AL_DLL_FAR *s ); public : const char AL_DLL_FAR * AL_PROTO GetName() const; const char AL_DLL_FAR * AL_PROTO GetOldName() const; const char AL_DLL_FAR * AL_PROTO GetSafeName() const; const char AL_DLL_FAR * AL_PROTO GetSafeOldName() const; ALName AL_DLL_FAR & AL_PROTO ChangeExtension( const char AL_DLL_FAR *new_extension = ".bak" ); ALName AL_DLL_FAR & AL_PROTO ChangeTrailingChar( char new_char = '@' ); ALName AL_DLL_FAR & AL_PROTO StripFileName(); ALName AL_DLL_FAR & AL_PROTO StripPath(); int AL_PROTO WildCardMatch( const char AL_DLL_FAR *pattern ); /* * Operators */ public : #if defined( AL_MICROSOFT ) && ( AL_MICROSOFT < 800 ) && ( defined( AL_BUILDING_DLL ) || defined( AL_USING_DLL ) ) /*??? DON'T ASK ME WHY */ AL_PROTO operator STRINGF() const; #else AL_PROTO operator const STRINGF() const; #endif ALName AL_PROTO operator + ( const char AL_DLL_FAR *rhs ); /* * Data members */ protected : char AL_DLL_FAR * mszName; char AL_DLL_FAR * mszOldName; public : const ALCase mCase; AL_CLASS_TAG( _ALNameTag ); }; #include "objname.inl" #else /* #if defined( __cplusplus ) ... */ AL_LINKAGE char AL_DLL_FAR * AL_FUNCTION StripPath( char AL_DLL_FAR *filename ); AL_LINKAGE char AL_DLL_FAR * AL_FUNCTION StripFileName( char AL_DLL_FAR *filename ); #endif /* #if defined( __cplusplus ) ... #else ... */ #endif /* #ifndef _OBJNAME_H */
true
fc53c97cc45036e190e4fcd0125715b9c03801c7
C++
mkalenska/task29
/main.cpp
UTF-8
406
3.046875
3
[]
no_license
#include <iostream> #include <thread> #include <random> #include <chrono> #include <string> #include "thread_pool.hpp" using namespace std; void sum(string text) { cout << text << endl; } int main() { ThreadPool pool(2); pool.runAsync([](int a){ cout << "It's Lambda with parameter a = " << a << endl; }, 10); string x = "Privet"; pool.runAsync(&sum, x); return 0; }
true
ca0762c17eba3165285f48623b97a7300083af85
C++
officerobody/legend-of-zelda
/LOZ/CameraControl.cpp
UTF-8
3,911
3.1875
3
[]
no_license
#include "CameraControl.h" #include <stdlib.h> #include <stdio.h> #include <math.h> #include <glut.h> #include <gl/gl.h> float angle=-(3.14/2); float angley=0.0; void CameraControl::kbd(unsigned char key, int x, int y,float direction[3],float eye[3]) { // if the "w" key is pressed rotate the camera to look upwards if(key == 'w' || key == 'W') { if (angley<1.5){ angley = angley +0.1; direction[1] = sin(angley); } } // if the "a" key is pressed rotate the camera to look left if(key == 'a' || key == 'A') { angle = angle -0.1; direction[0] = sin(angle); direction[2] = - cos(angle); } // if the "s" key is pressed rotate the camera to look downwards if(key == 's' || key == 'S') { if (angley>-1.5){ angley = angley -0.1; direction[1] = sin(angley); } } // if the "d" key is pressed rotate the camera to look right if(key == 'd' || key == 'D') { angle = angle + 0.1; direction[0] = sin(angle); direction[2] = -cos(angle); } if(key == 27){ // If the Esc key is pressed, exit the program. exit(0); } } //Function for when the arrow keys are pressed void CameraControl::specialKbd(int key, int x, int y,float direction[3],float eye[3],Terrain terrain,bool inCave) { float zoom = 0.5; //If the up arrow key is pressed, move forward if(key == GLUT_KEY_UP) { eye[0] += direction[0]*zoom; eye[1] += direction[1]*zoom; eye[2] += direction[2]*zoom; //Checks to see if user is walking into part of the terrain, and if so restricting their movement if (!inCave){ int x2=eye[0]; int y2=eye[2]; if (direction[0]!=0){ x2 = (int)(eye[0]+ 2*(direction[0]/abs(direction[0]))); } if (direction[2]!=0){ y2 = (int)(eye[2]+2*(direction[2]/abs(direction[2]))); } if (terrain.hMapArray[x2][y2]!=0){ eye[0] -= direction[0]*zoom; eye[1] -= direction[1]*zoom; eye[2] -= direction[2]*zoom; } } } //If the left arrow key is pressed, strafe left if(key == GLUT_KEY_LEFT) { eye[0] += sin(angle-3.14/2)*zoom; eye[2] += -cos(angle-3.14/2)*zoom; //Checks to see if user is walking into part of the terrain, and if so restricting their movement if (!inCave){ int x = (int)(eye[0]+ 2*((sin(angle-3.14/2))/abs(sin(angle-3.14/2)))); int y = (int)(eye[2]+2*((-cos(angle-3.14/2))/abs(-cos(angle-3.14/2)))); if (terrain.hMapArray[x][y]!=0){ eye[0] -= sin(angle-3.14/2)*zoom; eye[2] -= -cos(angle-3.14/2)*zoom; } } } //If the down arrow key is pressed, move backward if(key == GLUT_KEY_DOWN) { eye[0] -= direction[0]*zoom; eye[1] -= direction[1]*zoom; eye[2] -= direction[2]*zoom; //Checks to see if user is walking into part of the terrain, and if so restricting their movement if (!inCave){ int x2=eye[0]; int y2=eye[2]; if (direction[0]!=0){ x2 = (int)(eye[0]- 2*(direction[0]/abs(direction[0]))); } if (direction[2]!=0){ y2 = (int)(eye[2]-2*(direction[2]/abs(direction[2]))); } if (terrain.hMapArray[x2][y2]!=0){ eye[0] += direction[0]*zoom; eye[1] += direction[1]*zoom; eye[2] += direction[2]*zoom; } } } //If the right arrow key is pressed, strafe right if(key ==GLUT_KEY_RIGHT) { eye[0] -= sin(angle-3.14/2)*zoom; eye[2] -= -cos(angle-3.14/2)*zoom; //Checks to see if user is walking into part of the terrain, and if so restricting their movement if (!inCave){ int x = (int)(eye[0]- 2*((sin(angle-3.14/2))/abs(sin(angle-3.14/2)))); int y = (int)(eye[2]-2*((-cos(angle-3.14/2))/abs(-cos(angle-3.14/2)))); if (terrain.hMapArray[x][y]!=0){ eye[0] += sin(angle-3.14/2)*zoom; eye[2] += -cos(angle-3.14/2)*zoom; } } } } //Initialize the values at teh beginning of the game void CameraControl::initializeValues(float direction[3], float eye[3]){ eye[0] = 150.0; eye[1] = 0; eye[2] = 115; direction[0] = -1.0; direction[1] = 0; direction[2] = 0; }
true
12a537b28c90c7e8d721d9355f8a9a81945e22b1
C++
Anehta/AGE-lua
/src/render/age_animationset.cpp
UTF-8
1,638
2.640625
3
[]
no_license
#include <../include/age_animationset.h> #include <qfile.h> namespace AGE2D { AAnimationSet::AAnimationSet(QString fileName) { QFile file(fileName); QDomDocument doc("superdick"); file.open( QIODevice::ReadOnly ); doc.setContent (&file); file.close(); QDomElement root = doc.documentElement();//获得根节点 //遍历添加animation QDomElement child=root.firstChildElement (); while(!child.isNull ()) { AAnimation animation(child.attribute (QString("name"))); addAnimationFromFile (&animation,child); m_animationlist.push_back (animation); child=child.nextSiblingElement (); } } AAnimation *AAnimationSet::findAnimation(QString animationName) { for(list<AAnimation>::iterator i= m_animationlist.begin ();i!=m_animationlist.end ();i++) { if(i->getName ().compare (animationName)==0)//找寻指定的animation { return &(*i); } } } void AAnimationSet::addAnimationFromFile(AAnimation *animation, QDomElement node) { //加入帧 QDomElement child =node.firstChildElement (); while(!child.isNull ()) { QDomElement rect=child.firstChildElement (); //左下角 double bl_x= rect.attribute (QString("x")).toDouble (); double bl_y= rect.attribute (QString("y")).toDouble (); AVector2D bl(bl_x,bl_y); //qDebug()<<" bottom left is"<<bl; rect=rect.nextSiblingElement (); //右上角 double tr_x=rect.attribute (QString("x")).toDouble (); double tr_y=rect.attribute (QString("y")).toDouble (); AVector2D tr(tr_x,tr_y); //qDebug()<<" top right is"<<tr; //添加一帧 animation->addFrame(AFrame(bl,tr)); child=child.nextSiblingElement (); } } }
true
a99a34475ea5d8853044b5d41315127ae6f165d6
C++
rutsky/semester07
/Computer_graphics/wine_task1.2/Src/application/xvertex.h
UTF-8
840
2.609375
3
[]
no_license
// xvertex.h // Common DirectX vertices structures definitions. // Vladimir Rutsky <altsysrq@gmail.com> // 09.09.2009 #ifndef XVERTEX_H #define XVERTEX_H #include "xvertex_fwd.h" #include "point_fwd.h" #include "color_fwd.h" #include <d3dx9.h> namespace xcg { // Common vertex with a lot of parameters. struct vertex { float x, y, z, rhw; DWORD color; }; DWORD const VERTEX_FVF = (D3DFVF_XYZRHW | D3DFVF_DIFFUSE); } // End of namespace 'xcg' // TODO: Move to separate file. namespace xcg { vertex & set_vertex_position( vertex &v, cg::point_4f const &p ) { v.x = p.x; v.y = p.y; v.z = p.z; v.rhw = p.w; return v; } vertex & set_vertex_color( vertex &v, cg::color_4b const &c ) { v.color = D3DCOLOR_ARGB(c.a, c.r, c.g, c.b); return v; } } // End of namespace 'xcg' #endif // XVERTEX_H
true
14990393e60fe0169f9833f36886a8c9936d04df
C++
HelloWoori/AlgorithmStudyWithBaekjoon
/ExhaustiveSearch/Alphabet.cpp
UTF-8
1,868
3.25
3
[]
no_license
/* 알파벳 https://www.acmicpc.net/problem/1987 */ #include <iostream> #include <vector> #define SIZE 4 using namespace std; // 전역으로 사용할 변수 선언 int leftRight[SIZE] = {-1, 1, 0, 0}; int upDown[SIZE] = {0, 0, -1, 1}; int calc(vector<vector<char>>& board, vector<bool>& check, int currX, int currY); int main() { int row(0), col(0); cin >> row >> col; vector<vector<char>> board(row, vector<char>(col)); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { cin >> board[i][j]; } } // 재귀에서 사용할 변수 선언 vector<bool> check(26); // A ~ Z, 총 26개의 알파벳 // 1행 1열은 이미 말이 놓여있으므로, 사용했음 처리 int idx = board[0][0] - 'A'; // ex) 'C' 가 저장되어있다면 'C'(99) - 'A'(97) = 2 check[idx] = true; // 재귀 시작 cout << calc(board, check, 0, 0) << '\n'; return 0; } int calc(vector<vector<char>>& board, vector<bool>& check, int currX, int currY) { int answer = 0; for (int n = 0; n < SIZE; n++) { int nextX = currX + leftRight[n]; int nextY = currY + upDown[n]; // 주어진 행과 열이 범위 내에 있고 아직 방문하지 않았다면 재귀를 돌 수 있다 if(nextX >= 0 && nextX < board.size() && nextY >= 0 && nextY < board[0].size()) { int idx = board[nextX][nextY] - 'A'; if (check[idx] == false) { check[idx] = true; int cnt = calc(board, check, nextX, nextY); if (answer < cnt) { answer = cnt; } check[idx] = false; } } } return answer + 1; }
true
5305ebb3c9c9916fee9580b05b4487b899bfdf5c
C++
cgokmen/nin10kit
/shared/cmd-line-parser-helper.cpp
UTF-8
2,642
2.765625
3
[ "Apache-2.0" ]
permissive
#include "cmd-line-parser-helper.hpp" #include "scanner.hpp" #include "logger.hpp" #include <algorithm> bool CmdLineParserHelper::GetSwitch(const std::string& param) { return parser.Found(param); } bool CmdLineParserHelper::GetBoolean(const std::string& param, bool def_value) { long ret; if (!parser.Found(param, &ret)) return def_value; return ret != 0; } int CmdLineParserHelper::GetInt(const std::string& param, int def_value, int min, int max) { long ret; if (!parser.Found(param, &ret)) return def_value; int val = ret; if (val < min || val > max) { WarnLog("Invalid value given for %s range [%d %d] given %d ignoring", param.c_str(), min, max, val); val = def_value; } return val; } int CmdLineParserHelper::GetHexInt(const std::string& param, int def_value, int min, int max) { wxString hex; if (!parser.Found(param, &hex)) return def_value; long ret; if (!hex.ToLong(&ret, 16)) { WarnLog("Could not parse %s into hex ignoring", param.c_str()); return def_value; } int val = ret; if (val < min || val > max) { WarnLog("Invalid value given for %s range [%d %d] given %d ignoring", param.c_str(), min, max, val); val = def_value; } return val; } long CmdLineParserHelper::GetLong(const std::string& param, long def_value, long min, long max) { long ret = std::max(std::min(def_value, max), min); parser.Found(param, &ret); return ret; } std::string CmdLineParserHelper::GetString(const std::string& param, const std::string& def_value) { wxString ret; return parser.Found(param, &ret) ? ret.ToStdString() : def_value; } std::vector<int> CmdLineParserHelper::GetListInt(const std::string& param, const std::vector<int>& def_value) { wxString list; if (!parser.Found(param, &list)) return def_value; std::vector<int> ret; Scanner scan(list.ToStdString(), ","); while (scan.HasMoreTokens()) { int var; if (!scan.Next(var)) FatalLog("Error parsing param %s", param.c_str()); ret.push_back(var); } return ret; } std::vector<std::string> CmdLineParserHelper::GetListString(const std::string& param, const std::vector<std::string>& def_value) { wxString list; if (!parser.Found(param, &list)) return def_value; std::vector<std::string> ret; Scanner scan(list.ToStdString(), ","); while (scan.HasMoreTokens()) { std::string var; if (!scan.Next(var)) FatalLog("Error parsing param %s", param.c_str()); ret.push_back(var); } return ret; }
true
b8ef75808f90937636e491d7879aea157561f8f8
C++
YYYHHHSSS/Learn-C
/Task/6/Homework6-7.cpp
GB18030
942
3.046875
3
[]
no_license
#include<stdio.h> #define STOP '|' int main() { char c; // ǰַ char prev; //ǰһַ long n_chars = 0; // ַ int n_lines = 0; // int n_words = 0; // int p_lines = 0; // int inword = 0; // ǰַcһУinword1 //printf("Enter text to be analyzed( | to terminate):\n"); prev = '\n'; // ʶ while ((c = getchar()) != STOP) { // ͳַ if (c != ' ' && c != '\n' && c != '\t') n_chars++; if (c == '\n') n_lines++; if (c == ' '||c=='\n') inword = 0; if (inword == 0 && c != '\n') { inword = 1; n_words++; } prev = c; } if (prev != '\n') p_lines = 1; printf(" characters = %ld, words = %d, lines = %d, partial lines = %d\n", n_chars, n_words, n_lines, p_lines); return 0; }
true
ddf30a27b8dcfae84dcde508817b50a60e1c4582
C++
DatabaseGroup/tree-similarity
/src/label/json_label_impl.h
UTF-8
2,249
2.796875
3
[ "MIT" ]
permissive
// The MIT License (MIT) // Copyright (c) 2020 Thomas Huetter. // // 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. /// \file label/json_label_impl.h /// /// \details /// Contains the implementation of the JSONLabel class. #pragma once JSONLabel::JSONLabel(const std::string& label) { label_ = label; // Set type to 0 in case of an object. An object is indicated by opening // and closing curly braces. if (label.compare("\\{\\}") == 0) { type_ = 0; } // Set type to 1 in case of an array. An array is indicated by opening // and closing brackets. else if (label.compare("[]") == 0) { type_ = 1; } // Set type to 2 in case of an key. A key is indicated by a colon after // the key itself. else if (label.length() >= 2 && label[label.length() - 1] == ':') { type_ = 2; } // Otherwise, set type to 3 in case of a value. else { type_ = 3; } } unsigned int JSONLabel::get_type() const { return type_; } const std::string& JSONLabel::get_label() const { return label_; } bool JSONLabel::operator==(const JSONLabel& other) const { return (type_ == other.get_type() && label_.compare(other.get_label()) == 0); } const std::string& JSONLabel::to_string() const { return label_; }
true
aea4a066e26384d32a9391985c786d722881b5ca
C++
WilliamQf-AI/mork
/test/testUtil.cpp
UTF-8
2,087
2.84375
3
[]
no_license
#include "../mork/util/Util.h" #include "../mork/util/Time.h" #include "../mork/util/File.h" #include "../mork/core/Log.h" #include <gtest/gtest.h> using mork::debug_logger; class UtilTest : public ::testing::Test { protected: UtilTest(); virtual ~UtilTest(); // Code here will be called immediately after the constructor (right // before each test). virtual void SetUp(); // Code here will be called immediately after each test (right // before the destructor). virtual void TearDown(); }; UtilTest::UtilTest() { } UtilTest::~UtilTest() { } void UtilTest::SetUp() { } void UtilTest::TearDown() { } TEST_F(UtilTest, Test) { std::string test = mork::random_string(45); ASSERT_EQ(test.length(), 45); } TEST_F(UtilTest, Test2) { std::string test = mork::random_string(12); debug_logger(test); ASSERT_EQ(test.length(), 12); } TEST_F(UtilTest, TestString2Vec3d) { mork::vec3d v = mork::string2vec3d("1,2,3"); ASSERT_EQ(v, mork::vec3d(1, 2, 3)); v = mork::string2vec3d("1, 2, 3"); ASSERT_EQ(v, mork::vec3d(1, 2, 3)); v = mork::string2vec3d("-1, 2.34567, 3.12567"); ASSERT_EQ(v, mork::vec3d(-1, 2.34567, 3.12567)); v = mork::string2vec3d("-1.0e4, 2.34567e-4, 3.12567e0"); ASSERT_EQ(v, mork::vec3d(-1.0e4, 2.34567e-4, 3.12567e0)); ASSERT_THROW(v = mork::string2vec3d("7000,3, 1.0, 1.0"), std::invalid_argument); ASSERT_THROW(v = mork::string2vec3d("1,2"), std::invalid_argument); ASSERT_THROW(v = mork::string2vec3d("1,a, 3"), std::invalid_argument); } TEST_F(UtilTest, TestTime01) { auto t = std::chrono::system_clock::now(); mork::operator<<(std::cout,t) << std::endl; } TEST_F(UtilTest, TestFile01) { auto t = mork::getLastModifiedTime("ex12.json"); mork::operator<<(std::cout,t) << std::endl; } TEST_F(UtilTest, TestFile02) { mork::info_logger("The following error is expected"); ASSERT_THROW( { auto t = mork::getLastModifiedTime("/no/such/file.json"); }, std::runtime_error); }
true
925d5d5cd9389e0ef00fa3d84d2b97f70551e641
C++
ayrtoncg20/practica6AEDA
/src/main.cpp
UTF-8
7,634
2.75
3
[]
no_license
#include <iostream> #include <cstdlib> //rand() #include <ctime> #include "../include/DNI.hpp" #include "../include/nodo.hpp" #include "../include/arbol.hpp" #include <ctime> #include <iomanip> using namespace std; int main (void){ ABB_t<dni_t> arbol; int opcion; int opcion1; int opcion2; do { cout << endl; cout << "-------------------MENU-----------------" << endl; cout << "- INTRODUCE UN 1 PARA EL MODO DEMOSTRACION" << endl; cout << "- INTRODUCE UN 2 PARA EL MODO ESTADISTICA" << endl; cout << "- INTRODUCE UN 0 PARA SALIR" << endl; cout << "- OPCION -> "; cin >> opcion; cout << endl; switch(opcion){ case 1: do { cout << endl; cout << "-------------------MENU-----------------" << endl; cout << "- INTRODUCE UN 1 PARA INSERTAR CLAVE" << endl; cout << "- INTRODUCE UN 2 PARA ELIMINAR CLAVE" << endl; cout << "- INTRODUCE UN 3 PARA SALIR" << endl; cout << "- OPCION -> "; cin >> opcion1; cout << endl; switch(opcion1){ case 1: { dni_t D; int dni; cout << "INTRODUZCA UN DNI -> "; cin >> dni; cout << endl; D.set_dni(dni); arbol.insertar(D); arbol.mostrar(); } break; case 2: { dni_t D; int dni; cout << "INTRODUZCA EL DNI QUE DESEAR ELIMINAR -> "; cin >> dni; cout << endl; D.set_dni(dni); // buscar el elemento antes de eliminar, si no esta no se elimina arbol.eliminar(D); arbol.mostrar(); } break; } }while(opcion1 != 3); break; case 2: { ABB_t<dni_t> valores_dni; int size_arbol; int numero_de_pruebas; cout << "INTRODUZCA EL TAMAÑO DEL ÁRBOL -> "; cin >> size_arbol; cout << endl; cout << "INTRODUZCA EL NUMERO DE PRUEBAS A REALIZAR -> "; cin >> numero_de_pruebas; dni_t* banco_dni = new dni_t[2*size_arbol]; // VECTOR -> BANCO DE PRUEBAS DE LOS DNI dni_t D; // crea las matriculas aleatoriamente dni_t* aux; aux = D.crear_dni_aleatorios(2*size_arbol); // insertar valores generados en el banco de pruebas for(int i = 0; i < 2*size_arbol; i++){ banco_dni[i] = aux[i]; } // insertar elementos en el árbol for(int i = 0; i < size_arbol; i++){ valores_dni.insertar(banco_dni[i]); } //----------------------------------- BUSQUEDA ---------------------------------- // valores_dni.inicializar_contadores(); for(int i = 0; i < numero_de_pruebas; i++){ int pos1 = rand()% size_arbol; D.reiniciar_contador(); // busqueda uno de los elementos de los primos N elementos del banco de pruebas valores_dni.buscar(banco_dni[pos1]); if (D.contador_ > valores_dni.cont_max){ valores_dni.cont_max = D.contador_; } if (D.contador_ < valores_dni.cont_min){ valores_dni.cont_min = D.contador_; } valores_dni.suma = valores_dni.suma + D.contador_; } float media1 = valores_dni.resultado(numero_de_pruebas); cout << setw(33) << "NUMERO DE COMPARACIONES" << endl; cout << setw(16) << "NUMERO" << setw(10) << "PRUEBAS" << setw(10) << "MINIMO" << setw(10) << "MEDIA" << setw(10) << "MAXIMO" << endl; cout << "BUSQUEDA" << setw(6) << size_arbol << setw(9) << numero_de_pruebas << setw(10) << valores_dni.cont_min << setw(11) << media1 << setw(10) << valores_dni.cont_max << endl; // Podar el árbol valores_dni.podar_arbol(); //-----------------------------------INSERCIÓN----------------------------------------// // insertar N primeros elementos en el árbol for(int i = size_arbol; i < 2*size_arbol ; i++){ valores_dni.insertar(banco_dni[i]); } //valores_.mostrar(); valores_dni.inicializar_contadores(); for(int i = 0; i < numero_de_pruebas; i++){ int pos = (rand() % size_arbol) + size_arbol; D.reiniciar_contador(); // insertar(buscar) N ultimos elementos en el árbol valores_dni.buscar(banco_dni[i]); if (D.contador_ > valores_dni.cont_max){ valores_dni.cont_max = D.contador_; } if (D.contador_ < valores_dni.cont_min){ valores_dni.cont_min = D.contador_; } valores_dni.suma = valores_dni.suma + D.contador_; } float media2 = valores_dni.resultado(numero_de_pruebas); cout << "INSERCION" << setw(5) << size_arbol << setw(9) << numero_de_pruebas << setw(10) << valores_dni.cont_min << setw(11) << media2 << setw(10) << valores_dni.cont_max << endl; } break; } }while(opcion != 0); }
true
ccfbd57b9760fad97e0bcab721fd46fa9982fff7
C++
Absenths/Arduino
/laserShot.ino
UTF-8
1,928
2.828125
3
[]
no_license
#include "FastLED.h" //LEDS #define NUM_STRIPS 3 #define NUM_LEDS_PER_STRIP 15 CRGB leds[NUM_STRIPS][NUM_LEDS_PER_STRIP]; int sensorPin = A4; int relay = 4; int sens = 0; int sensorLimit = 500; int lsrLvl = 0; int shotTime = 2000; int fillUpSpeed = 400; int lsr[15]; void setup() { // declare the ledPin as an OUTPUT: Serial.begin(9600); pinMode(relay, OUTPUT); digitalWrite(relay,HIGH); // For mirroring strips, all the "special" stuff happens just in setup. We // just addLeds multiple times, once for each strip // tell FastLED there's 60 NEOPIXEL leds on pin 10 FastLED.addLeds<NEOPIXEL, 10>(leds[0], NUM_LEDS_PER_STRIP); // tell FastLED there's 60 NEOPIXEL leds on pin 11 FastLED.addLeds<NEOPIXEL, 11>(leds[1], NUM_LEDS_PER_STRIP); // tell FastLED there's 60 NEOPIXEL leds on pin 12 FastLED.addLeds<NEOPIXEL, 12>(leds[2], NUM_LEDS_PER_STRIP); } void loop() { // read the value from the sensor: while(lsrLvl<15){ sens = analogRead(sensorPin); if(sens>sensorLimit){ lsrLvl++; } else if(lsrLvl!=0){ lsrLvl--; } Serial.println(sens); for(int x = 0; x < NUM_STRIPS; x++) { for(int i = 0; i < lsrLvl; i++) { leds[x][i] = CRGB::Red; } } FastLED.show(); delay(fillUpSpeed); allLedsBlack(); } if(lsrLvl=15){ Serial.println("Bose in coming!"); allLedsGreen(); FastLED.show(); digitalWrite(relay,LOW); delay(shotTime); digitalWrite(relay,HIGH); allLedsBlack(); FastLED.show(); lsrLvl = 0; } } void allLedsBlack(){ for(int x = 0; x < NUM_STRIPS; x++) { for(int i = 0; i < NUM_LEDS_PER_STRIP; i++) { leds[x][i] = CRGB::Black; } } } void allLedsGreen(){ for(int x = 0; x < NUM_STRIPS; x++) { for(int i = 0; i < NUM_LEDS_PER_STRIP; i++) { leds[x][i] = CRGB::Green; } } }
true
0fbdc68092389af5fc1e401b52638d51aca7093a
C++
gbelmonte/GBEmu
/logger.cpp
UTF-8
752
2.828125
3
[]
no_license
#include "logger.hpp" using namespace std; Logger::Logger() { } Logger::~Logger() { } bool Logger::logEnabled = false; void Logger::InitLogger(bool enable = false) { logEnabled = enable; if (enable == true) { freopen("log.txt", "w", stdout); } } void Logger::LogOpcode(BYTE opcode) { if (logEnabled == true) { cout << hex << "0x" << (int)opcode << " ="; } } void Logger::LogPC(WORD pc) { if (logEnabled == true) { cout << hex << "0x" << (int)pc << ": "; } } void Logger::LogInstruction(string name, string dParam, string rParam) { if (logEnabled == true) { cout << hex << " " << name << " " << dParam << ", " << rParam << endl; } } void Logger::Log(string log) { if (logEnabled == true) { cout << hex << log << endl; } }
true
c0eca03a70dee2e307e9f1c0168fa76d665ea2a1
C++
naman3112/pep-coding-imp-quest
/Arrays/Container-with-most-water.cpp
UTF-8
423
3.015625
3
[]
no_license
class Solution { public: int maxArea(vector<int>& height) { int maxAns=-1; int start=0, end=height.size()-1; while(start<end){ int area= ((end-start) * min(height[start],height[end])); maxAns=max(maxAns,area); if(height[start]<height[end]){ start++; }else{ end--; } } return maxAns; } };
true
b64767958c97e584708b986ab7876634b137638f
C++
georgidimov/sdp
/homework1/homework1/main.cpp
UTF-8
679
2.671875
3
[]
no_license
#include <QCoreApplication> #include <iostream> #include <fstream> #include <string> #include <math.h> #include <stack.h> #include <operators.h> #include <parser.h> //int main(int argc, char ** argv){ int main(){ char filePath[] = "../homework1/files/simpleTest"; Operators operationSet(filePath); // Parser<double> p(argv[1]); Parser<double> p(filePath); Stack<double> numbers; Stack<char> operations; char input[] = "3 + 5 * ( 6 - 9 ) - 8 * 2" ; try{ std :: cout << p.calculateExpression(input) << std :: endl; }catch(std :: exception & exc){ std :: cout << "Error: " << exc.what() << std :: endl; } return 0; }
true
4531fd1947fcf0a6d2c4709ab1d544e2e3529971
C++
dietotter/cpp-learning
/tests/classes/quiz/MonsterGenerator.h
UTF-8
1,023
3.46875
3
[]
no_license
#pragma once #include "Monster.h" #include <array> class MonsterGenerator { private: // Generate a random number between min and max (inclusive) // Assumes std::srand() has already been called // Assumes max - min <= RAND_MAX // IMPORTANT: for now moved this method's definition to header file // (because can't define the static private outside of class definition) // just so I have the example of such thing // But it would probs be better to separate declaration from definition // and just make getRandomNumber public (as it seems that compile times have gotten larger) static int getRandomNumber(int min, int max) { static constexpr double fraction{ 1.0 / (static_cast<double>(RAND_MAX) + 1.0) }; // static used for efficiency, so we only calculate this value once // evenly distribute the random number across our range return static_cast<int>(std::rand() * fraction * (max - min + 1) + min); } public: static Monster generateMonster(); };
true
5e666ea6799924129ca5079349417f624b4ead9a
C++
AlexitoReyes54/GrafoDinamicos
/menu.cpp
UTF-8
10,661
2.796875
3
[]
no_license
#include <iostream> //#include <windows.h> #include "grafo_Estructura.cpp" using namespace std; int main() { Grafo G; G.Inicializa(); int opc; /* G.InsertaVertice("TIJ"); G.InsertaVertice("MTY"); G.InsertaVertice("MZT"); G.InsertaVertice("BJX"); G.InsertaVertice("GDL"); G.InsertaVertice("SAN"); G.InsertaVertice("TAM"); G.InsertaVertice("MEX"); G.InsertaVertice("CUN"); G.InsertaVertice("MID"); G.InsertaArista(G.GetVertice("TIJ"), G.GetVertice("MTY"), 800); G.InsertaArista(G.GetVertice("MZT"), G.GetVertice("TIJ"), 400); G.InsertaArista(G.GetVertice("MZT"), G.GetVertice("BJX"), 300); G.InsertaArista(G.GetVertice("MTY"), G.GetVertice("BJX"), 700); G.InsertaArista(G.GetVertice("BJX"), G.GetVertice("SAN"), 900); G.InsertaArista(G.GetVertice("BJX"), G.GetVertice("TAM"), 400); G.InsertaArista(G.GetVertice("BJX"), G.GetVertice("MEX"), 350); G.InsertaArista(G.GetVertice("GDL"), G.GetVertice("MZT"), 500); G.InsertaArista(G.GetVertice("GDL"), G.GetVertice("MTY"), 450); G.InsertaArista(G.GetVertice("GDL"), G.GetVertice("BJX"), 250); G.InsertaArista(G.GetVertice("GDL"), G.GetVertice("MEX"), 500); G.InsertaArista(G.GetVertice("SAN"), G.GetVertice("MID"), 1200); G.InsertaArista(G.GetVertice("TAM"), G.GetVertice("MID"), 450); G.InsertaArista(G.GetVertice("MEX"), G.GetVertice("MID"), 450); G.InsertaArista(G.GetVertice("MEX"), G.GetVertice("CUN"), 650); G.InsertaArista(G.GetVertice("CUN"), G.GetVertice("GDL"), 650); */ do { system("cls"); cout<<"1. Ingresar Vertice"<<endl; cout<<"2. Ingresar arista"<<endl; cout<<"3. Lista de adyacencia"<<endl; cout<<"4. Tama�o"<<endl; cout<<"5. Eliminar vertice"<<endl; cout<<"6. Eliminar arista"<<endl; cout<<"7. Anular"<<endl; cout<<"8. Recorrido en anchura"<<endl; cout<<"9. Recorrido en profundidad"<<endl; cout<<"10. Primero en anchura"<<endl; cout<<"11. Primero en profundidad"<<endl; cout<<"12. Primero el mejor"<<endl; cout<<"13. Salir"<<endl; cout<<endl<<"Elija una opcion: "; cin>>opc; switch(opc) { case 1: { string nombre; system("cls"); cout<<"Ingrese el nombre del vertice: "; cin.ignore(); getline(cin, nombre, '\n'); G.InsertaVertice(nombre); cin.get(); cin.get(); break; } case 2: { string origen, destino; int peso; system("cls"); if(G.Vacio()) { cout<<"El grafo esta vacio"<<endl; } else { cout<<"Ingrese del nombre del vertice origen: "; cin.ignore(); getline(cin, origen, '\n'); cout<<"Ingrese el nombre del vertice destino: "; getline(cin, destino, '\n'); cout<<"Ingrese el peso: "; cin>>peso; if(G.GetVertice(origen) == NULL || G.GetVertice(destino) == NULL) { cout<<"Uno de los vertices no es valido"<<endl; } else { G.InsertaArista(G.GetVertice(origen), G.GetVertice(destino), peso); } } cin.get(); cin.get(); break; } case 3: { system("cls"); if(G.Vacio()) { cout<<"El grafo esta vacio"<<endl; } else { G.ListaAdyacencia(); } cin.get(); cin.get(); break; } case 4: { system("cls"); if(G.Vacio()) { cout<<"El grafo esta vacio"<<endl; } else { cout<<"Tamano: "<<G.Tamano()<<endl; } cin.get(); cin.get(); break; } case 5: { string nombre; system("cls"); if(G.Vacio()) { cout<<"El grafo esta vacio"<<endl; } else { cout<<"Ingrese el nombre del vertice a eliminar: "; cin.ignore(); getline(cin, nombre, '\n'); if(G.GetVertice(nombre) == NULL) { cout<<"Vertice invalido"<<endl; } else { //G.EliminarVertice(G.GetVertice(nombre)); } } cin.get(); cin.get(); break; } case 6: { string origen, destino; system("cls"); if(G.Vacio()) { cout<<"El grafo esta vacio"<<endl; } else { cout<<"Ingrese del nombre del vertice origen: "; cin.ignore(); getline(cin, origen, '\n'); cout<<"Ingrese el nombre del vertice destino: "; getline(cin, destino, '\n'); if(G.GetVertice(origen) == NULL || G.GetVertice(destino) == NULL) { cout<<"Vertices no validos"<<endl; } else { //G.EliminarArista(G.GetVertice(origen), G.GetVertice(destino)); } } cin.get(); cin.get(); break; } case 7: { system("cls"); if(G.Vacio()) { cout<<"El grafo esta vacio"<<endl; } else { G.Anular(); } cin.get(); cin.get(); break; } case 8: { string nombre; system("cls"); if(G.Vacio()) { cout<<"El grafo esta vacio"<<endl; } else { cout<<"Ingrese el nombre del vertice inicial: "; cin.ignore(); getline(cin, nombre, '\n'); if(G.GetVertice(nombre) == NULL) { cout<<"Ese vertice es invalido"<<endl; } else { //G.RecorridoAnchura(G.GetVertice(nombre)); } } cin.get(); cin.get(); break; } case 9: { string nombre; system("cls"); if(G.Vacio()) { cout<<"El grafo esta vacio"<<endl; } else { cout<<"Ingrese el nombre del vertice inicial: "; cin.ignore(); getline(cin, nombre, '\n'); if(G.GetVertice(nombre) == NULL) { cout<<"Ese vertice es invalido"<<endl; } else { //G.RecorridoProfundidad(G.GetVertice(nombre)); } } cin.get(); cin.get(); break; } case 10: { string origen, destino; system("cls"); if(G.Vacio()) { cout<<"El grafo esta vacio"<<endl; } else { cout<<"Ingrese el nombre del vertice origen: "; cin.ignore(); getline(cin, origen, '\n'); cout<<"Ingrese el nombre del vertice destino: "; getline(cin, destino, '\n'); if(G.GetVertice(origen) == NULL || G.GetVertice(destino) == NULL) { cout<<"Vertices invalidos"<<endl; } else { //G.PrimeroAnchura(G.GetVertice(origen), G.GetVertice(destino)); } } cin.get(); cin.get(); break; } case 11: { string origen, destino; system("cls"); if(G.Vacio()) { cout<<"El grafo esta vacio"<<endl; } else { cout<<"Ingrese el nombre del vertice origen: "; cin.ignore(); getline(cin, origen, '\n'); cout<<"Ingrese el nombre del vertice destino: "; getline(cin, destino, '\n'); if(G.GetVertice(origen) == NULL || G.GetVertice(destino) == NULL) { cout<<"Vertices invalidos"<<endl; } else { //G.PrimeroProfundidad(G.GetVertice(origen), G.GetVertice(destino)); } } cin.get(); cin.get(); break; } case 12: { string origen, destino; system("cls"); if(G.Vacio()) { cout<<"El grafo esta vacio"<<endl; } else { cout<<"Ingrese el nombre del vertice origen: "; cin.ignore(); getline(cin, origen, '\n'); cout<<"Ingrese el nombre del vertice destino: "; getline(cin, destino, '\n'); if(G.GetVertice(origen) == NULL || G.GetVertice(destino) == NULL) { cout<<"Vertices invalidos"<<endl; } else { //G.PrimeroMejor(G.GetVertice(origen), G.GetVertice(destino)); } } cin.get(); cin.get(); break; } case 13: { break; } default: { cout<<"Elija una opcion valida"<<endl; } } } while(opc != 13); return 0; }
true
6f5ae5378e4c568cf41cb99b32b7a217f5079f9a
C++
Asia292/OOP2905
/Shapes/src/main.cpp
UTF-8
2,287
3.421875
3
[]
no_license
/*! \mainpage Lab Book 1 - Shapes * * This program creates and draws a set of shapes from scratch * * The shapes are split into a number of classes to make creating them easier * * Transformations are also applied to the shapes */ /*! \file main.cpp * \brief Main file for the application * * Contains the entry point of the application * * Defines the paramaters for all the shapes and the transformations * * Creates the SFML window and draws the shapes to it */ #include "SFML/Graphics.hpp" #include "dot.h" #include "line.h" #include "form.h" int n = 0; int main() //!< Entry point for the application { sf::RenderWindow window(sf::VideoMode(1024, 800), "Lab Book 1 - Shapes"); window.setFramerateLimit(60); //// passes the values into the corresponding classes allowing the shapes to be created //// dot Dot(sf::Vector2f(50.0, 50.0)); line Line(sf::Vector2f(100.0, 100.0), sf::Vector2f(100.0, 200.0)); form Triangle(sf::Vector2f(500.0, 300.0), 100, 100, 0, 360, 3); form Square(sf::Vector2f (300.0, 300.0), 100, 100, 45, 360, 4); form Rectangle(sf::Vector2f(800.0, 300.0), 100, 50, 45, 360, 4); form Circle(sf::Vector2f(300.0, 500.0), 100, 100, 0, 360, 30); form Arc(sf::Vector2f(550.0, 500.0), 100, 100, 45, 120, 30); form Elipse(sf::Vector2f(800.0, 500.0), 100, 50, 0, 360, 30); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } } Rectangle.rotate(1); //rotates the rectangle 1 degree at a time if (n < 10) //if n < 10 then it decreases the scale of the circle { Circle.scale(0.5, 0.5); n++; } if (n > 10 && n < 20) //if n > 10 and n < 20 it increases the scale of the circle { Circle.scale(2, 2); n++; if (n == 20) n = 0; //sets n back to 0 when it reaches 20 to start the cycle over again } Triangle.move(sf::Vector2f(600.0, 100.0)); //moves the lines starting position to this coordinate window.clear(); //// draws all the shapes //// window.draw(Dot); window.draw(Line); window.draw(Square); window.draw(Triangle); window.draw(Rectangle, Rectangle.getStates()); window.draw(Circle, Circle.getStates()); window.draw(Arc); window.draw(Elipse); window.display(); } }
true
b51903795badfc338468a668e84133904f1d5042
C++
AleKiller21/Tiny-C
/ast/expressions/cast/cast_expression.h
UTF-8
542
2.6875
3
[]
no_license
#ifndef CAST_EXPRESSION #define CAST_EXPRESSION #include "../expression.h" #include "../../declarations/abstract_declarator.h" class cast_expression : public expression { private: expression* expr; abstract_declarator* type; public: cast_expression(abstract_declarator* type, expression* expr, int position) : expression(position) { this->expr = expr; this->type = type; lvalue = false; } string to_string(); int get_kind(); type_attributes get_type(); }; #endif // CAST_EXPRESSION
true
e9af6812cb06199a8e8f2bafbdd31966c1b50de7
C++
lgsvl/chromium-src
/url/origin.h
UTF-8
7,584
2.65625
3
[ "BSD-3-Clause" ]
permissive
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef URL_ORIGIN_H_ #define URL_ORIGIN_H_ #include <stdint.h> #include <string> #include "base/strings/string16.h" #include "base/strings/string_piece.h" #include "url/scheme_host_port.h" #include "url/third_party/mozilla/url_parse.h" #include "url/url_canon.h" #include "url/url_constants.h" #include "url/url_export.h" class GURL; namespace url { // An Origin is a tuple of (scheme, host, port), as described in RFC 6454. // // TL;DR: If you need to make a security-relevant decision, use 'url::Origin'. // If you only need to extract the bits of a URL which are relevant for a // network connection, use 'url::SchemeHostPort'. // // STL;SDR: If you aren't making actual network connections, use 'url::Origin'. // // 'Origin', like 'SchemeHostPort', is composed of a tuple of (scheme, host, // port), but contains a number of additional concepts which make it appropriate // for use as a security boundary and access control mechanism between contexts. // // This class ought to be used when code needs to determine if two resources // are "same-origin", and when a canonical serialization of an origin is // required. Note that some origins are "unique", meaning that they are not // same-origin with any other origin (including themselves). // // There are a few subtleties to note: // // * Invalid and non-standard GURLs are parsed as unique origins. This includes // non-hierarchical URLs like 'data:text/html,...' and 'javascript:alert(1)'. // // * GURLs with schemes of 'filesystem' or 'blob' parse the origin out of the // internals of the URL. That is, 'filesystem:https://example.com/temporary/f' // is parsed as ('https', 'example.com', 443). // // * Unique origins all serialize to the string "null"; this means that the // serializations of two unique origins are identical to each other, though // the origins themselves are not "the same". This means that origins' // serializations must not be relied upon for security checks. // // * GURLs with a 'file' scheme are tricky. They are parsed as ('file', '', 0), // but their behavior may differ from embedder to embedder. // // * The host component of an IPv6 address includes brackets, just like the URL // representation. // // Usage: // // * Origins are generally constructed from an already-canonicalized GURL: // // GURL url("https://example.com/"); // url::Origin origin(url); // origin.scheme(); // "https" // origin.host(); // "example.com" // origin.port(); // 443 // origin.unique(); // false // // * To answer the question "Are |this| and |that| "same-origin" with each // other?", use |Origin::IsSameOriginWith|: // // if (this.IsSameOriginWith(that)) { // // Amazingness goes here. // } class URL_EXPORT Origin { public: // Creates a unique Origin. Origin(); // Creates an Origin from |url|, as described at // https://url.spec.whatwg.org/#origin, with the following additions: // // 1. If |url| is invalid or non-standard, a unique Origin is constructed. // 2. 'filesystem' URLs behave as 'blob' URLs (that is, the origin is parsed // out of everything in the URL which follows the scheme). // 3. 'file' URLs all parse as ("file", "", 0). explicit Origin(const GURL& url); // Creates an Origin from a |scheme|, |host|, |port| and |suborigin|. All the // parameters must be valid and canonicalized. Do not use this method to // create unique origins. Use Origin() for that. // // This constructor should be used in order to pass 'Origin' objects back and // forth over IPC (as transitioning through GURL would risk potentially // dangerous recanonicalization); other potential callers should prefer the // 'GURL'-based constructor. static Origin UnsafelyCreateOriginWithoutNormalization( base::StringPiece scheme, base::StringPiece host, uint16_t port, base::StringPiece suborigin); // Creates an origin without sanity checking that the host is canonicalized. // This should only be used when converting between already normalized types, // and should NOT be used for IPC. Method takes std::strings for use with move // operators to avoid copies. static Origin CreateFromNormalizedTupleWithSuborigin( std::string scheme, std::string host, uint16_t port, std::string suborigin); ~Origin(); // For unique origins, these return ("", "", 0). const std::string& scheme() const { return tuple_.scheme(); } const std::string& host() const { return tuple_.host(); } uint16_t port() const { return tuple_.port(); } // Note that an origin without a suborgin will return the empty string. const std::string& suborigin() const { return suborigin_; } bool unique() const { return unique_; } // An ASCII serialization of the Origin as per Section 6.2 of RFC 6454, with // the addition that all Origins with a 'file' scheme serialize to "file://". // If the Origin has a suborigin, it will be serialized per // https://w3c.github.io/webappsec-suborigins/#serializing. std::string Serialize() const; // Returns the physical origin for Origin. If the suborigin is empty, this // will just return a copy of the Origin. If it has a suborigin, will return // the Origin of just the scheme/host/port tuple, without the suborigin. See // https://w3c.github.io/webappsec-suborigins/. Origin GetPhysicalOrigin() const; // Two Origins are "same-origin" if their schemes, hosts, and ports are exact // matches; and neither is unique. If either of the origins have suborigins, // the suborigins also must be exact matches. bool IsSameOriginWith(const Origin& other) const; bool operator==(const Origin& other) const { return IsSameOriginWith(other); } // Same as above, but ignores suborigins if they exist. bool IsSamePhysicalOriginWith(const Origin& other) const; // Efficiently returns what GURL(Serialize()) would without re-parsing the // URL. This can be used for the (rare) times a GURL representation is needed // for an Origin. // Note: The returned URL will not necessarily be serialized to the same value // as the Origin would. The GURL will have an added "/" path for Origins with // valid SchemeHostPorts and file Origins. // // Try not to use this method under normal circumstances, as it loses type // information. Downstream consumers can mistake the returned GURL with a full // URL (e.g. with a path component). GURL GetURL() const; // Same as GURL::DomainIs. If |this| origin is unique, then returns false. bool DomainIs(base::StringPiece canonical_domain) const; // Allows Origin to be used as a key in STL (for example, a std::set or // std::map). bool operator<(const Origin& other) const; private: Origin(base::StringPiece scheme, base::StringPiece host, uint16_t port, base::StringPiece suborigin, SchemeHostPort::ConstructPolicy policy); Origin(std::string scheme, std::string host, uint16_t port, std::string suborigin, SchemeHostPort::ConstructPolicy policy); SchemeHostPort tuple_; bool unique_; std::string suborigin_; }; URL_EXPORT std::ostream& operator<<(std::ostream& out, const Origin& origin); URL_EXPORT bool IsSameOriginWith(const GURL& a, const GURL& b); URL_EXPORT bool IsSamePhysicalOriginWith(const GURL& a, const GURL& b); } // namespace url #endif // URL_ORIGIN_H_
true
ae2197ee9807969ab1f184e04f2515628c9c10fb
C++
sidorovis/cpp_craft_1013
/solutions/ivan_sidarau/trade_processor_project/tests/multicast_communication_tests/market_datafeed_writer_tests.cpp
UTF-8
1,859
2.5625
3
[]
no_license
#include "test_registrator.h" #include <market_datafeed_writer.h> namespace multicast_communication { namespace tests_ { namespace detail { class market_datafeed_writer_test_helper : virtual protected boost::noncopyable { market_datafeed_writer writer_; public: explicit market_datafeed_writer_test_helper( const std::string& filename ); void write( trade_message_ptr& trade ); void write( quote_message_ptr& quote ); }; } } } multicast_communication::tests_::detail::market_datafeed_writer_test_helper::market_datafeed_writer_test_helper( const std::string& filename ) : writer_( filename ) { } void multicast_communication::tests_::detail::market_datafeed_writer_test_helper::write( trade_message_ptr& trade ) { writer_.new_trade( trade ); } void multicast_communication::tests_::detail::market_datafeed_writer_test_helper::write( quote_message_ptr& quote ) { writer_.new_quote( quote ); } void multicast_communication::tests_::market_datafeed_writer_tests() { BOOST_CHECK_NO_THROW ({ market_datafeed_writer writer( BINARY_DIR "/test_file_name.txt" ); }); BOOST_CHECK_EQUAL( boost::filesystem::exists( BINARY_DIR "/test_file_name.txt" ), true ); boost::filesystem::remove( BINARY_DIR "/test_file_name.txt" ); { detail::market_datafeed_writer_test_helper writer( BINARY_DIR "/test_file_name.txt" ); trade_message_ptr tmp( new trade_message() ); writer.write( tmp ); quote_message_ptr qmp( new quote_message() ); writer.write( qmp ); } BOOST_CHECK_EQUAL( boost::filesystem::exists( BINARY_DIR "/test_file_name.txt" ), true ); BOOST_CHECK_EQUAL( boost::filesystem::file_size( BINARY_DIR "/test_file_name.txt" ) <= 20ul, true ); BOOST_CHECK_EQUAL( boost::filesystem::file_size( BINARY_DIR "/test_file_name.txt" ) >= 18ul, true ); boost::filesystem::remove( BINARY_DIR "/test_file_name.txt" ); }
true
b09dddd49570cfaa6b39d737f0138995c535f34f
C++
waynejo/android-ndk-m4a-writer
/memUtils.cpp
UTF-8
286
2.90625
3
[ "MIT" ]
permissive
#include "memUtils.h" void memcpy_r(void* dst, void* src, uint32_t size) { uint8_t* srcEnd = (uint8_t*)src; uint8_t* srcPtr = (uint8_t*)src + size; uint8_t* dstPtr = (uint8_t*)dst + size; for (; srcEnd != srcPtr; --srcPtr, --dstPtr) { *dstPtr = *srcPtr; } *dstPtr = *srcPtr; }
true
ae341ee0d2d0e2be49dc02189d4ef0a9cad0e1af
C++
pgmatev/C-
/GTA/water_vehicle.cc
UTF-8
222
2.859375
3
[]
no_license
#include "water_vehicle.hh" #include <iostream> void WaterVehicle::accelerate(){ float change = displacement/weight; speed+=acceleration*change; std::cout << "The vehicle accelerated on water!" << std::endl; }
true
3290a857a4e31e72df2c577130df8c2d0206f0fd
C++
SubAquaticsROV/squeaky-rov
/src/rov/camera.ino
UTF-8
477
3.078125
3
[]
no_license
int camera_pins[4]; void set_camera_pins(int pin1, int pin2, int pin3, int pin4) { camera_pins[0] = pin1; camera_pins[1] = pin2; camera_pins[2] = pin3; camera_pins[3] = pin4; for (int i = 0; i < 4; ++i) { pinMode(camera_pins[i], OUTPUT); } } void switch_camera(int camera) { digitalWrite(camera_pins[0], camera & B0001); digitalWrite(camera_pins[1], camera & B0010); digitalWrite(camera_pins[2], camera & B0100); digitalWrite(camera_pins[3], camera & B1000); }
true
f3dbd2f8e6e6c4d02d6bce65e2e6ebc88f920e27
C++
Noverish/codingtest-cpp
/src/baekjoon/1149 - RGB거리.cpp
UTF-8
880
2.859375
3
[]
no_license
#include <algorithm> #include <iostream> #include <string> #include <vector> #include <cmath> using namespace std; template <typename T> ostream& operator<<(ostream& out, const vector<T>& v) { out << "{"; size_t last = v.size() - 1; for (size_t i = 0; i < v.size(); ++i) { out << v[i]; if (i != last) out << ", "; } out << "}"; return out; } int main() { ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); int N; cin >> N; vector<int> r(N + 1); vector<int> g(N + 1); vector<int> b(N + 1); for(int i = 1; i <= N; i++) { cin >> r[i]; cin >> g[i]; cin >> b[i]; r[i] += min(g[i - 1], b[i - 1]); g[i] += min(r[i - 1], b[i - 1]); b[i] += min(r[i - 1], g[i - 1]); } cout << min({r[N], g[N], b[N]}) << "\n"; return 0; }
true
a75c238b5357f71147597a6004c5f4cb51d6c667
C++
windhooked/mpi-afis
/Parallel/ParallelHandler.h
UTF-8
14,648
2.859375
3
[ "Apache-2.0" ]
permissive
/** * \file ParallelHandler.h * \author Daniel Peralta <dperalta@decsai.ugr.es> * \version 1.0 * * \section DESCRIPTION * * Header file for the ParallelHandler class. */ #ifndef PARALLEL_HANDLER_H #define PARALLEL_HANDLER_H #include "Fingerprint.h" #include <string> #include <vector> #include "omp.h" #include "mpi.h" #include "Score.h" /** * \class ParallelHandler * * The ParallelHandler class handles the parallel structure of the fingerprint recognizer. * It encapsulates some of the common processing for both master and slave processes processes. */ class ParallelHandler { public: typedef enum {STOP_YES = 1, STOP_NO, STOP_MAX, STOP_ALL, STOP_RANKING} stop_t; typedef enum {FP_UNKNOWN, FP_JIANG, FP_MCC} fingerprint_t; typedef enum {FUSION_SUM,FUSION_MAX,FUSION_MIN,FUSION_PROD} fusion_t; typedef enum {DPDDFF_SS,DPDDFF_SD,DPDDFF_DS,DPDDFF_DD} variant_t; static const unsigned int MASTER_ID = 0; /** Default constructor */ ParallelHandler(); /** Default destructor */ virtual ~ParallelHandler(); /** * Changes the threshold for the search in the database * \param t New threshold */ void setThreshold(float t); /** * Changes the ranking for the search in the database * \param r New ranking */ void setRanking(unsigned int r); /** * Changes the used matching algorithm * \param fp New fingerprint type * \param argc Number of arguments for the fingeprint matcher * \param argv Arguments for the fingeprint matcher * \param finger Index of the finger */ void setFingerprintType(fingerprint_t fp, int argc, char *argv[], int finger = 0); /** * Changes the used matching algorithm * \param fp Vector of new fingerprint type (one type per finger) * \param argc Number of arguments for the fingeprint matcher * \param argv Arguments for the fingeprint matcher */ void setFingerprintType(const std::vector<fingerprint_t> &fp, int argc, char *argv[]); /** * Returns the used matching algorithm * \param finger Index of the finger * \return Fingerprint type */ fingerprint_t getFingerprintType(int finger = 0) const; /** * Returns the used matching algorithms * \return Vector of fingerprint types */ std::vector<fingerprint_t> getFingerprintTypes() const; /** * Changes the stop mode for the search in the database * \param s New stop mode */ void setStopMode(stop_t s); /** * Get the number of processes * \return Number of MPI processes */ static int getProcesses(); /** * Get the number of threads * \return Number of OpenMP threads */ int getThreads() const; /** * Get the number of performed matches in the search, i.e. the number of fingeprints in the database that have been explored * \return Number of explored fingerprints */ int getExplored() const; /** * Get the size of the fingerprint database * \return Size of the fingerprint database */ int getDBSize() const; /** * Get the penetration rate, as the number of explored fingeprints (\a getExplored()) divided by the size of the database (\a getDBSize()) * \return Penetration rate */ virtual float getPenetrationRate() const; /** * Get the number of the current process * \return MPI ID of the current process. This ID can go from 0 to \a getProcesses(). */ static int getProcessID(); /** * Get the iteration number (i.e. the number of fingerprints that have been searched in the database since the program started) * \return Iteration number */ int getIteration() const; /** * Get the average matching time per fingerprint * \return Average matching time in seconds */ double getAvgMatchingTime() const; /** * Resets the iteration number to zero (i.e. the number of fingerprints that have been searched in the database since the program started) */ void resetIteration(); /** * Determines if the current process is the master process * \return true if the current process is the master processMPI ID of the current process, false otherwise */ bool isMaster() const; /** * Initialize MPI and OpenMP * \param threads Number of OpenMP threads * \param classification Indicates whether classification is performed * \param level Required parallelism level for MPI * \return A pointer to the subclass of ParallelHandler * \post This pointer is allocated dynamically with new, so it must be deallocated with delete */ static ParallelHandler *getHandler(int threads, bool classification = false, int level = MPI_THREAD_FUNNELED); /** * Exits the program, showing an error message and calling MPI::Finalize() * \param message Error message to be shown in the standard error output. * \param status Number that is returned to the SO */ static void exit(const std::string & message, int status = 0); /** * Main loop of the process, that explores the database looking for the fingerprint. * The behavior differs depending on the process type (master or slave) * \param newF Fingerprint to be found in the database * \param v Vector of matches * \returns The vector of found matches in \p v */ virtual void run(Fingerprint *newF, std::vector< Score > &v) = 0; /** * Main loop of the process, that explores the database looking for the fingerprint. * The behavior differs depending on the process type (master or slave) * \param vinput Vector with the input fingerprints for a user * \param v Vector of matches * \returns The vector of found matches in \p v */ virtual void run(std::vector<Fingerprint *> &vinput, std::vector< Score > &v) = 0; /** * Explores the database looking for the fingerprint, using only the fingerprints signaled in \p candidates * The behavior differs depending on the process type (master or slave) * \param newF Fingerprint to be found in the database * \param candidates Vector of candidates * \param v Vector of matches * \returns The vector of found matches in \p v */ virtual void runSecond(Fingerprint *newF, const std::vector< Score > &candidates, std::vector< Score > &v) = 0; /** * Explores the database looking for the fingerprint, using only the fingerprints signaled in \p candidates * The behavior differs depending on the process type (master or slave) * \param vinput Vector with the input fingerprints for a user * \param candidates Vector of candidates * \param v Vector of matches * \returns The vector of found matches in \p v */ virtual void runSecond(std::vector<Fingerprint *> &vinput, const std::vector< Score > &candidates, std::vector< Score > &v) = 0; /** * Creates a fingerprint of the appropriate type, according to the information set in \a setFingerprintType * \param finger Index of the finger * \return Pointer to a subclass of \a Fingerprint * \post The returned pointer is allocated with new, so it must be deallocated with delete */ virtual Fingerprint *newFingerprint(int finger = 0) const; /** * Aggregates the scores according to the type of fusion in \a fusion * \param fscore Vector of scores * \return Fused score */ float aggregateScores(const std::vector<float> &fscore) const; /** * Every slave process sends its database size to the master, that sums them up. */ void calculateDBSize(); /** * Reads the database part to be processed by the process * \param filename Name of the database file * \param quality Minium quality for the read minutiae. It is an integer in the range [1,100] */ virtual void loadDBFile(const std::string &filename, unsigned int quality); /** * Reads the database part to be processed by the process * \param filelists Vector with the names of the database files for each fingerprint * \param quality Minium quality for the read minutiae. It is an integer in the range [1,100] */ virtual void loadDBFile(const std::vector<std::string> &filelists, unsigned int quality) = 0; /** * Reads the database part to be processed by the process. * \param filename Name of the database file * \param classfile Name of the file that contains the class for each fingerprint in \p filename. If empty, no classification is performed. * \param quality Minimum quality for the read minutiae. It is an integer in the range [0,100] */ virtual void loadDBFile(const std::string &filename, const std::string &classfile, unsigned int quality) = 0; /** * Reads the database part to be processed by the process. * \param filelists Vector with the names of the database files for each fingerprint * \param classfiles Name of the file that contains the class for each fingerprint in \p filename. If empty, no classification is performed. * \param quality Minimum quality for the read minutiae. It is an integer in the range [0,100] */ virtual void loadDBFile(const std::vector<std::string> &filelists, const std::vector<std::string> &classfiles, unsigned int quality); /** * Reads and initializes the database part to be processed by the process * \param filename Name of the database file * \param quality Minium quality for the read minutiae. It is an integer in the range [1,100] */ virtual void loadInitializeDBFile(const std::string &filename, unsigned int quality); /** * Reads and initializes the database part to be processed by the process * \param filelists Vector with the names of the database files for each fingerprint * \param quality Minium quality for the read minutiae. It is an integer in the range [1,100] */ virtual void loadInitializeDBFile(const std::vector<std::string> &filelists, unsigned int quality) = 0; /** * Reads and initializes the database part to be processed by the process. * \param filename Name of the database file * \param classfile Name of the file that contains the class for each fingerprint in \p filename. If empty, no classification is performed. * \param quality Minimum quality for the read minutiae. It is an integer in the range [0,100] */ virtual void loadInitializeDBFile(const std::string &filename, const std::string &classfile, unsigned int quality) = 0; /** * Reads and initializes the database part to be processed by the process. * \param filelists Vector with the names of the database files for each fingerprint * \param classfiles Name of the file that contains the class for each fingerprint in \p filename. If empty, no classification is performed. * \param quality Minimum quality for the read minutiae. It is an integer in the range [0,100] */ virtual void loadInitializeDBFile(const std::vector<std::string> &filelists, const std::vector<std::string> &classfiles, unsigned int quality); /** * Set the fusion type for the fingerprint database * \param fus New fusion type */ void setFusion(fusion_t fus); /** * Returns the number of fingers or the number of matchers. This is the dimension of the * input vector for \a run. * \return Number of fingers or matchers */ virtual unsigned int getNumFingers() const; /** * Every slave process sends the number of explored fingerprints to the master, which sums them up. */ void calculateExplored(); protected: static const int TAG_FOUND = 0; static const int TAG_BOUNDARIES = 1; static const int TAG_MATCH = 2; static const int TAG_OFFSET = 3; std::vector<MPI::Request> stop_requests; //!< Set of stop requests from each slave. Used with when the seach is stopped when a score threshold is reached. stop_t stop; //!< Stopping criterion for the search. float threshold; //!< Threshold to stop the search or select candidates. unsigned int ranking; //!< Ranking to stop the search or select candidates. int iteration; //!< Number of input fingerprints searched. int explored; //!< Number of matchings performed in the last seach. int totalsize; //!< Total number of fingerprints (in this node or in all nodes) double avgmatchingtime; //!< Average matching time, in seconds unsigned int numfingers; //!< Number of fingers per identity fusion_t fusion; //!< Fusion type std::vector<fingerprint_t> template_fp; //!< Matcher used for each finger MPI::Datatype mpi_pair_t; //!< MPI Datatype for the scores /** * Frees all the requests in the \a stop_requests vector. */ virtual void freeRequests(); private: /** * Copy constructor * \param other Object to copy from */ ParallelHandler(const ParallelHandler& other) {}; /** * Assignment operator * \param other Object to assign from * \return A reference to this object */ virtual ParallelHandler& operator=(const ParallelHandler& other) {return *this;}; }; inline unsigned int ParallelHandler::getNumFingers() const {return numfingers;} inline void ParallelHandler::setThreshold(float t) {threshold = t;} inline void ParallelHandler::setRanking(unsigned int r) {ranking = r;} inline std::vector<ParallelHandler::fingerprint_t> ParallelHandler::getFingerprintTypes() const {return template_fp;} inline ParallelHandler::fingerprint_t ParallelHandler::getFingerprintType(int finger) const {return template_fp[finger];} inline void ParallelHandler::setStopMode(stop_t s) {stop = s;} inline int ParallelHandler::getProcesses() {return MPI::COMM_WORLD.Get_size();} inline int ParallelHandler::getThreads() const {return omp_get_num_threads();} inline int ParallelHandler::getProcessID() {return MPI::COMM_WORLD.Get_rank();} inline int ParallelHandler::getIteration() const {return iteration;} inline void ParallelHandler::resetIteration() {iteration = 0;} inline int ParallelHandler::getExplored() const {return explored;} inline int ParallelHandler::getDBSize() const {return totalsize;} inline double ParallelHandler::getAvgMatchingTime() const {return avgmatchingtime;} inline bool ParallelHandler::isMaster() const {return (getProcessID() == MASTER_ID);} inline void ParallelHandler::loadDBFile(const std::string &filename, unsigned int quality) { loadDBFile(std::vector<std::string>(1, filename), quality); } inline void ParallelHandler::loadDBFile(const std::string &filename, const std::string &classfile, unsigned int quality) { loadDBFile(std::vector<std::string>(1, filename), quality); } inline void ParallelHandler::loadInitializeDBFile(const std::string &filename, unsigned int quality) { loadInitializeDBFile(std::vector<std::string>(1, filename), quality); } inline void ParallelHandler::loadInitializeDBFile(const std::string &filename, const std::string &classfile, unsigned int quality) { loadInitializeDBFile(std::vector<std::string>(1, filename), quality); } inline float ParallelHandler::getPenetrationRate() const { return ((float)explored)/totalsize; } inline void ParallelHandler::setFusion(ParallelHandler::fusion_t fus) {fusion = fus;} #endif // PARALLEL_HANDLER_H
true
f6d5b444c240563d483004bceed30ba60ea6df83
C++
zhang-peixiang/c_class_code
/stack、queue/stack、queue/test.cpp
UTF-8
669
3.109375
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS 1 #include <iostream> using namespace std; #include <queue> #include <stack> // stack void Test1() { stack<int> s; s.push(1); s.push(2); s.push(3); s.push(4); s.push(5); cout << s.size() << endl; cout << s.top() << endl; s.pop(); cout << s.size() << endl; cout << s.top() << endl; } // queue void Test2() { queue<int> q; q.push(1); q.push(2); q.push(3); q.push(4); q.push(5); cout << q.front() << endl; cout << q.back() << endl; cout << q.size() << endl; q.pop(); q.pop(); cout << q.front() << endl; cout << q.back() << endl; cout << q.size() << endl; } int main() { // Test1(); Test2(); return 0; }
true
cc0da17da0142850441e29e417be483ec69f93e8
C++
akira2009999/NetAnalyzer-analise-de-trafego
/NetAnalyzer/src/compression/QuickLZDecompress.cpp
UTF-8
1,734
2.671875
3
[]
no_license
#ifdef WITH_QUICKLZ #include "QuickLZDecompress.h" #include "Data.h" #include "../Debug.h" #include <cstdlib> #include <cstring> #define DBG_QUICKLZ "QLZ_DEC" QuickLZDecompress::QuickLZDecompress() { reset(); } QuickLZDecompress::~QuickLZDecompress() { delete decompressState; decompressState = nullptr; } Decompressor* QuickLZDecompress::create() const { auto* ptr = new QuickLZDecompress(); return ptr; } bool QuickLZDecompress::append(const Data& toDecompress, std::vector<uint8_t>& result) { if (toDecompress.length == 0) { return true; } // pointer and size of the data to be decompressed const char* srcData = (char*)toDecompress.data; // make room the the uncompressed chunk of data const size_t sizeDecompr = qlz_size_decompressed(srcData); const size_t oldResultSize = result.size(); result.resize(oldResultSize + sizeDecompr); // pointer to the buffer the data will be decompressed into char* destData = (char*)result.data() + oldResultSize; // does not take any kind of srcSize argument because the information about // that should be encoded at the beginning of srcData. be sure to always // use the same settings for compression that will be used for decompression! const size_t retSizeDecompr = qlz_decompress(srcData, destData, decompressState); if (retSizeDecompr != sizeDecompr) { error(DBG_QUICKLZ, "the actual size of the decompressed data does not match the expected size"); } return true; } void QuickLZDecompress::reset() { // delete the current state if it exists delete decompressState; // allocate a new state and initialize it decompressState = new qlz_state_decompress; std::memset(decompressState, 0, sizeof(qlz_state_decompress)); } #endif // WITH_QUICKLZ
true
ad63daf5d1b510ad5f73bafce5552a067f2a8b8a
C++
Ckkk112138/Demo-6.2-Simple-Chat
/Demo6.1 Very Simple Telnet Server.cpp
UTF-8
1,362
2.703125
3
[]
no_license
// Demo6.1 Very Simple Telnet Server.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <iostream> #include "SocketLib.h" using namespace std; using namespace SocketLib; int main() { ListeningSocket lsock; DataSocket dsock; char buffer[128]; int size = 0; int received; lsock.Listen(5098); dsock = lsock.Accept(); dsock.Send("Hello!\r\n", 8); while (true) { received = dsock.Receive(buffer + size, 128 - size); size += received; if (buffer[size - 1] == '\n') { cout << size << endl; dsock.Send(buffer, size); size = 0; } } } // 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单 // 调试程序: F5 或调试 >“开始调试”菜单 // 入门使用技巧: // 1. 使用解决方案资源管理器窗口添加/管理文件 // 2. 使用团队资源管理器窗口连接到源代码管理 // 3. 使用输出窗口查看生成输出和其他消息 // 4. 使用错误列表窗口查看错误 // 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目 // 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
true
13ab562eb0f0750eaa1ce2a86deadf5772d09c2c
C++
Tempoblink/cxxp
/ch16_Templates_and_GenericProgramming/exercise_16_61.cpp
UTF-8
449
3.578125
4
[]
no_license
/* * 定义你自己版本的make_shared。 */ #include <iostream> #include <memory> #include <string> #include <utility> template<typename T, typename... Args> std::shared_ptr<T> make_shared(Args &&...args) { return std::shared_ptr<T>(new T(std::forward<Args>(args)...)); } int main(int argc, char const *argv[]) { std::shared_ptr<std::string> sp = make_shared<std::string>(10, 'c'); std::cout << *sp << std::endl; return 0; }
true
a7b50a3097c3046ba39dce1e82dd201d0c40b1d4
C++
jennkryst/HSpace-5
/hsfuel.h
UTF-8
884
2.59375
3
[]
no_license
#ifndef __HSFUEL_INCLUDED__ #define __HSFUEL_INCLUDED__ #include "hstypes.h" #include "hseng.h" // Types of fuel. enum HS_FUELTYPE { FL_BURNABLE = 0, FL_REACTABLE, }; // This is derived an engineering system, // even though it is quite different. // // The CHSFuelSystem handles fuel storage, transfer, // etc. class CHSFuelSystem : public CHSEngSystem { public: CHSFuelSystem(void); int GetMaxFuel(HS_FUELTYPE type=FL_BURNABLE); float ExtractFuelUnit(float, HS_FUELTYPE type=FL_BURNABLE); float GetFuelRemaining(HS_FUELTYPE type=FL_BURNABLE); BOOL SetAttributeValue(char *, char *); char *GetAttributeValue(char *, BOOL); void SaveToFile(FILE *); void GiveSystemInfo(int); CHSEngSystem *Dup(void); protected: float m_burnable_fuel; float m_reactable_fuel; // Overridables int *m_max_burnable_fuel; int *m_max_reactable_fuel; }; #endif // __HSFUEL_INCLUDED__
true
a1a0a99e1e906fd52a1cbff212512f0ab56c1ec2
C++
OldKrab/AffineTransforms
/src/Figure/TriangleMeshFigure.h
UTF-8
957
2.90625
3
[]
no_license
#pragma once #include "BaseFigure.h" #include "Math/Triangle.h" class TriangleMeshFigure :public BaseFigure { public: struct TriangleInxs { size_t firstInx, secondInx, thirdInx; }; TriangleMeshFigure(Matrix<float> dots); TriangleMeshFigure(Matrix<float> dots, std::vector<TriangleInxs> trianglesInxs, sf::Color color); void SetTriangle(size_t firstInx, size_t secondInx, size_t thirdInx); void SetColor(uint8_t r, uint8_t g, uint8_t b); const Matrix<float>& GetDots() const; Matrix<float> GetTransformedDots() const; void GetTrianglesAndColors(std::vector<Triangle>& triangles, std::vector<sf::Color> & colors, const Transform& trans) const; const std::vector<TriangleInxs>& GetTrianglesInxs() const; TriangleMeshFigure Combine(TriangleMeshFigure other) const; void Draw(sf::RenderTarget& target, const Transform& trans) const override; private: Matrix<float> dots_; std::vector<TriangleInxs> trianglesInxs_; sf::Color color_; };
true
b33a2feb379464989388bbf231c8e17527558df8
C++
hardcodder/computer_graphics_console
/Vectorscantheory_project.cpp
UTF-8
2,482
2.765625
3
[]
no_license
void fun_call_theory_handler(); void vectroescan() { char chosevs ; char cvs; system("clear") ; cout<<"\033[32m * Vector scan display directly traces out only the desired lines on CRT.\033[0m\n"<<endl; cout<<"\033[32m * If we want line between point p1 & p2 then we directly drive the beam deflection\n circuitry which focus beam directly from point p1 to p2. \033[0m\n"<<endl; cout<<"\033[32m * If we do not want to display line from p1 to p2 and just move then we can blank\n the beam as we move it. \033[0m\n"<<endl; cout<<"\033[32m * To move the beam across the CRT, the information about both magnitude and direction is required.\033[0m\n "<<endl; cout<<"\033[32m * This information is generated with the help of vector graphics generator.\033[0m\n "<<endl; cout<<"\033[32m * Architecture of vector display consists of:-/n 1. display controller\n 2. CPU\n 3. display buffer memory\n 4. CRT. \033[0m\n"<<endl; cin.get(cvs) ; cin.get(cvs) ; cout<<"\033[32m * Display controller is connected as an I/O peripheral to the CPU. \033[0m\n"<<endl; cout<<"\033[32m * Display buffer stores computer produced display list or display program. \033[0m\n"<<endl; cout<<"\033[32m * The Program contains point & line plotting commands with end point co-ordinates\n as well as character plotting commands. \033[0m\n"<<endl; cout<<"\033[32m * Display controller interprets command and sends digital and point co-ordinates\n to a vector generator. \033[0m\n"<<endl; cout<<"\033[32m * Vector generator then converts the digital co-ordinate value to analog voltages\n for beam deflection circuits that displace an electron beam which points on the CRT’s screen. \033[0m\n"<<endl; cout<<"\033[32m * In this technique beam is deflected from end point to end point hence this techniques\n is also called random scan. \033[0m\n"<<endl; cin.get(cvs) ; cout<<"\033[32m * We know as beam strikes phosphors coated screen it emits light but that light decays\n after few milliseconds.\033[0m\n "<<endl; cout<<"\033[32m * Therefore it is necessary to repeat through the display list to refresh the screen at\n least 30 times per second to avoid flicker. \033[0m\n"<<endl; cout<<"\033[32m * As display buffer is used to store display list and used to refreshing, it is also called\n refresh buffer. \033[0m\n"<<endl; cout << endl << endl << " \033[95mPress any key to go back \033[0m\n" << endl ; cin.get(chosevs) ; cin.get(chosevs) ; fun_call_theory_handler() ; }
true
0b1ee6dd94b89d275781d15e4002e6ad5044e721
C++
gianzav/terminal-emulator
/pty2.cpp
UTF-8
2,185
3.234375
3
[]
no_license
#include <iostream> #include <pty.h> #include <string> #include <sys/wait.h> #include <unistd.h> using namespace std; void openpty_demo(const char *output_size) { int master; int slave; openpty(&master, &slave, NULL, NULL, NULL); // Temporarily redirect stdout to the slave, so that the command executed in // the subprocess will write to the slave. int _stdout = dup(STDOUT_FILENO); dup2(slave, STDOUT_FILENO); pid_t pid = fork(); if (pid == 0) { // We use // // head -c $output_size /dev/zero // // as the command for our demo. const char *argv[] = {"head", "-c", output_size, "/dev/zero", NULL}; execvp(argv[0], const_cast<char *const *>(argv)); } fd_set rfds; struct timeval tv{0, 0}; char buf[4097]; ssize_t size; size_t count = 0; // Read from master as we wait for the child process to exit. // // We don't wait for it to exit and then read at once, because otherwise the // command being executed could potentially saturate the slave's buffer and // stall. while (1) { if (waitpid(pid, NULL, WNOHANG) == pid) { break; } FD_ZERO(&rfds); FD_SET(master, &rfds); if (select(master + 1, &rfds, NULL, NULL, &tv)) { size = read(master, buf, 4096); buf[size] = '\0'; count += size; } } // Child process terminated; we flush the output and restore stdout. fsync(STDOUT_FILENO); dup2(_stdout, STDOUT_FILENO); // Read until there's nothing to read, by which time we must have read // everything because the child is long gone. while (1) { FD_ZERO(&rfds); FD_SET(master, &rfds); if (!select(master + 1, &rfds, NULL, NULL, &tv)) { // No more to read. break; } size = read(master, buf, 4096); buf[size] = '\0'; count += size; } // Close both ends of the pty. close(master); close(slave); cout << "Total characters read: " << count << endl; } int main(int argc, const char *argv[]) { openpty_demo(argv[1]); }
true
4dc0a0ccdd5f4994d51a2a8e4a3a38e0c51fad27
C++
victor-hernandez/Basketduino
/PushButtonRedRing.h
UTF-8
500
2.765625
3
[]
no_license
/* PushButtonRedRing.h - Biblioteca para controlar un boton del tipo push button con un anillo iluminado de color rojo @author: Victor Hernandez Bermejo, Gabriel Rodriguez Polaina, Diego Sepulveda Blanco @version: 1.0 */ #ifndef PushButtonRedRing_h #define PushButtonRedRing_h #include "Arduino.h" class PushButtonRedRing { public: PushButtonRedRing (int salida); PushButtonRedRing (int led, int salida); void encender (); void apagar (); bool presionado (); private: int _led; int _salida; boolean _tieneLed; }; #endif
true
6c50b7f3954326912101fb89bb47f757f4fe14a1
C++
Prabhu001-dot/SIT210
/8.1.ino
UTF-8
1,302
3.53125
4
[]
no_license
// Include the Wire library for I2C #include <Wire.h> // LED on pin 13 const int yellow = 13; const int green = 12; const int red = 5; void setup() { // Join I2C bus as slave with address 9 Wire.begin(0x9); // Call onRecieving when data received Wire.onReceive(onRecieving); // Setup pin 13 as output and turn LED off pinMode(yellow, OUTPUT); digitalWrite(yellow, LOW); pinMode(green, OUTPUT); digitalWrite(green, LOW); pinMode(red, OUTPUT); digitalWrite(red, LOW); } // Function that executes whenever data is received from master void onRecieving(int input) { while (Wire.available()) { // loop through all but the last char c = Wire.read(); // receive byte as a character if(c == 0) { digitalWrite(yellow, 0); digitalWrite(green, 0); digitalWrite(red, 0); } else if(c == 1) { digitalWrite(yellow, 1); digitalWrite(green, 0); digitalWrite(red, 0); } else if(c == 2) { digitalWrite(yellow, 0); digitalWrite(green, 1); digitalWrite(red, 0); } else if(c == 3) { digitalWrite(yellow, 0); digitalWrite(green, 0); digitalWrite(red, 1); } } } void loop() { delay(100); }
true
11499aa6a8ce7c3b6f23189183d3071af902959d
C++
fravera/ArduinoChessTimer
/ChessTimer.ino
UTF-8
4,334
2.65625
3
[]
no_license
#include "Button.h" #include "Definitions.h" #include "LiquidCrystalDisplay.h" #include "Timer.h" #include "Switch.h" #include <stdio.h> #include <stdlib.h> LiquidCrystalDisplay theLCD(PIN_LCD_RS, PIN_LCD_EN, PIN_LCD_D4, PIN_LCD_D5, PIN_LCD_D6, PIN_LCD_D7); Timer timerWhite(10); Timer timerBlack(10); Button buttonUp (PIN_BUTTON_UP ); Button buttonDown (PIN_BUTTON_DOWN ); Button buttonLeft (PIN_BUTTON_LEFT ); Button buttonRight (PIN_BUTTON_RIGHT); Button buttonEnter (PIN_BUTTON_ENTER); Switch playerSwitch(PIN_PLAYER_SWITCH); StateMachineStates theState = StateMachineStates::INITIALIZING; uint32_t timerLenght = 0; void waitForAnyBottomToBePressed() { while(!buttonEnter.isPressed() && !buttonUp.isPressed() && !buttonDown.isPressed() && !buttonLeft.isPressed() && !buttonRight.isPressed()) {} } void waitForBottomToBePressed(Button theBottom) { while(!theBottom.isPressed()) {} } void setup() { // code interrupt generated every TIMER0_COMPA reaches 0xAF OCR0A = 0xAF; TIMSK0 |= _BV(OCIE0A); } SIGNAL(TIMER0_COMPA_vect) { if(theState == StateMachineStates::RUNNING) { if(playerSwitch.isWhiteTurn()) timerWhite.updateTimer(); else timerBlack.updateTimer(); } } void loop() { switch(theState) { case StateMachineStates::INITIALIZING: { theLCD.initialize(); theLCD.firstLine(); theLCD.appendWord (" Chess Timer "); theLCD.secondLine(); theLCD.appendWord (" press a button "); waitForAnyBottomToBePressed(); theState = StateMachineStates::CONFIGURING; break; } case StateMachineStates::CONFIGURING: { uint32_t theTimerLength = theLCD.setTimerSetting(buttonUp, buttonDown, buttonLeft, buttonRight, buttonEnter); if(theTimerLength == 0) { theLCD.secondLine(); theLCD.appendWord ("Error, timer = 0"); delay(3000); break; } timerWhite.setTimer(theTimerLength); timerBlack.setTimer(theTimerLength); theLCD.writeWord (timerWhite.getTimerString(true )); theLCD.appendWord( " " ); theLCD.appendWord(timerBlack.getTimerString(false)); playerSwitch.waitForStart(); theState = StateMachineStates::RUNNING; break; } case StateMachineStates::RUNNING: { if(timerWhite.isTimeOver() || timerBlack.isTimeOver()) theState = StateMachineStates::STOPPING; if(buttonEnter.isPressed()) theState = StateMachineStates::PAUSING; theLCD.writeWord (timerWhite.getTimerString(true )); theLCD.appendWord( " " ); theLCD.appendWord(timerBlack.getTimerString(false)); // if(timerWhite.isTimeOver() || timerBlack.isTimeOver()) theState = StateMachineStates::STOPPING; break; } case StateMachineStates::PAUSING: { theLCD.secondLine(); theLCD.appendWord ("< resume stop >"); bool isLeftPressed = false; bool isRightPressed = false; do{ isLeftPressed=buttonLeft.isPressed(); isRightPressed=buttonRight.isPressed(); }while(!isLeftPressed && !isRightPressed); if(isLeftPressed) theState = StateMachineStates::RESUMING; else theState = StateMachineStates::STOPPING; break; } case StateMachineStates::RESUMING: { theLCD.secondLine(); theLCD.appendWord ("White Black"); theState = StateMachineStates::RUNNING; break; } case StateMachineStates::STOPPING: { theLCD.secondLine(); theLCD.appendWord (" press a button "); waitForAnyBottomToBePressed(); theState = StateMachineStates::CONFIGURING; break; } default: { theLCD.writeWord ("Error"); theLCD.appendWord (" press a button "); waitForAnyBottomToBePressed(); theState = StateMachineStates::INITIALIZING; break; } } }
true
cae76e53276b9c00c9ed43370f43b0de4c64f3d5
C++
opendarkeden/server
/src/Core/EffectInfo.cpp
UHC
3,151
3.078125
3
[]
no_license
////////////////////////////////////////////////////////////////////// // // Filename : EffectInfo.cpp // Written By : elca@ewestsoft.com // Description : Ʈ Ʈ . // ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // include files ////////////////////////////////////////////////////////////////////// #include "EffectInfo.h" #include "SocketInputStream.h" #include "SocketOutputStream.h" ////////////////////////////////////////////////////////////////////// // constructor ////////////////////////////////////////////////////////////////////// EffectInfo::EffectInfo () { __BEGIN_TRY m_ListNum = 0; __END_CATCH } ////////////////////////////////////////////////////////////////////// // destructor ////////////////////////////////////////////////////////////////////// EffectInfo::~EffectInfo () { __BEGIN_TRY __END_CATCH } ////////////////////////////////////////////////////////////////////// // Է½Ʈ()κ Ÿ о Ŷ ʱȭѴ. ////////////////////////////////////////////////////////////////////// void EffectInfo::read ( SocketInputStream & iStream ) { __BEGIN_TRY // ȭ ۾ ũ⸦ ϵ Ѵ. iStream.read( m_ListNum ); WORD m_Value; for( int i = 0; i < m_ListNum * 2 ; i++ ) { iStream.read( m_Value ); m_EList.push_back(m_Value); } __END_CATCH } ////////////////////////////////////////////////////////////////////// // ½Ʈ() Ŷ ̳ʸ ̹ . ////////////////////////////////////////////////////////////////////// void EffectInfo::write ( SocketOutputStream & oStream ) const { __BEGIN_TRY // ȭ ۾ ũ⸦ ϵ Ѵ. oStream.write( m_ListNum ); for ( list<WORD>:: const_iterator itr = m_EList.begin(); itr!= m_EList.end(); itr++) { oStream.write(*itr); } __END_CATCH } ////////////////////////////////////////////////////////////////////// // // EffectInfo::addListElement() // // ( ȭ, ȭġ ) Ʈ ֱ Լ. // ////////////////////////////////////////////////////////////////////// void EffectInfo::addListElement( EffectID_t EffectID , WORD Value ) { __BEGIN_TRY // ϴ List ִ´. m_EList.push_back( EffectID ); // ϴ ġ List ִ´. m_EList.push_back( Value ); // ȭ ϳ Ų. m_ListNum++; __END_CATCH } ////////////////////////////////////////////////////////////////////// // // get packet's debug string // ////////////////////////////////////////////////////////////////////// string EffectInfo::toString () const { __BEGIN_TRY StringStream msg; msg << "EffectInfo( " << ",ListNum: " << (int)m_ListNum << " ListSet(" ; for ( list<WORD>::const_iterator itr = m_EList.begin(); itr!= m_EList.end() ; itr++ ) { msg << (int)(*itr) << ","; } msg << ")"; return msg.toString(); __END_CATCH }
true
1d6132530fbb9697b02ce1b6c4cde043614cf538
C++
graphffiti/PopHead
/tests/Physics/CollisionHandlers/testStaticCollisionHandler.cpp
UTF-8
4,590
3.015625
3
[ "MIT" ]
permissive
#include <catch.hpp> #include "Physics/CollisionHandlers/staticCollisionHandler.hpp" #include "Physics/CollisionBody/collisionBody.hpp" namespace ph { TEST_CASE("Static collision is properly handled", "[Physics][StaticCollisionHandler]") { StaticCollisionHandler staticCollisionHandler; CollisionBody kinematicBody({0, 0, 10, 10}, 25); kinematicBody.actionsAtTheEndOfPhysicsLoopIteration(); SECTION("After moving right") { kinematicBody.move({10, 0}); CollisionBody staticBody({15, -10, 20, 30}, 0); staticCollisionHandler(kinematicBody, staticBody); CHECK(Approx(kinematicBody.getPosition().x).margin(0.001f) == 5.f); CHECK(Approx(kinematicBody.getPosition().y).margin(0.001f) == 0.f); } SECTION("After moving left") { kinematicBody.move({-10, 0}); CollisionBody staticBody({-25, -10, 20, 30}, 0); staticCollisionHandler(kinematicBody, staticBody); CHECK(Approx(kinematicBody.getPosition().x).margin(0.001f) == -5.f); CHECK(Approx(kinematicBody.getPosition().y).margin(0.001f) == 0.f); } SECTION("After moving down") { kinematicBody.move({0, 10}); CollisionBody staticBody({-10, 15, 30, 20}, 0); staticCollisionHandler(kinematicBody, staticBody); CHECK(Approx(kinematicBody.getPosition().x).margin(0.001f) == 0.f); CHECK(Approx(kinematicBody.getPosition().y).margin(0.001f) == 5.f); } SECTION("After moving up") { kinematicBody.move({0, -10}); CollisionBody staticBody({-10, -25, 30, 20}, 0); staticCollisionHandler(kinematicBody, staticBody); CHECK(Approx(kinematicBody.getPosition().x).margin(0.001f) == 0.f); CHECK(Approx(kinematicBody.getPosition().y).margin(0.001f) == -5.f); } SECTION("After moving diagonally down right (wall is to the right from kinematic body)") { kinematicBody.move({10, 10}); CollisionBody staticBody({15, -10, 20, 30}, 0); staticCollisionHandler(kinematicBody, staticBody); CHECK(Approx(kinematicBody.getPosition().x).margin(0.001f) == 5.f); CHECK(Approx(kinematicBody.getPosition().y).margin(0.001f) == 10.f); } SECTION("After moving diagonally up right (wall is to the right from kinematic body)") { kinematicBody.move({10, -10}); CollisionBody staticBody({15, -10, 20, 30}, 0); staticCollisionHandler(kinematicBody, staticBody); CHECK(Approx(kinematicBody.getPosition().x).margin(0.001f) == 5.f); CHECK(Approx(kinematicBody.getPosition().y).margin(0.001f) == -10.f); } SECTION("After moving diagonally down left (wall is to the left from kinematic body)") { kinematicBody.move({-10, 10}); CollisionBody staticBody({-25, -10, 20, 30}, 0); staticCollisionHandler(kinematicBody, staticBody); CHECK(Approx(kinematicBody.getPosition().x).margin(0.001f) == -5.f); CHECK(Approx(kinematicBody.getPosition().y).margin(0.001f) == 10.f); } SECTION("After moving diagonally up left (wall is to the left from kinematic body)") { kinematicBody.move({-10, -10}); CollisionBody staticBody({-25, -10, 20, 30}, 0); staticCollisionHandler(kinematicBody, staticBody); CHECK(Approx(kinematicBody.getPosition().x).margin(0.001f) == -5.f); CHECK(Approx(kinematicBody.getPosition().y).margin(0.001f) == -10.f); } SECTION("After moving diagonally down left (wall is down from kinematic body)") { kinematicBody.move({-10, 10}); CollisionBody staticBody({-10, 15, 30, 20}, 0); staticCollisionHandler(kinematicBody, staticBody); CHECK(Approx(kinematicBody.getPosition().x).margin(0.001f) == -10.f); CHECK(Approx(kinematicBody.getPosition().y).margin(0.001f) == 5.f); } SECTION("After moving diagonally down right (wall is down from kinematic body)") { kinematicBody.move({10, 10}); CollisionBody staticBody({-10, 15, 30, 20}, 0); staticCollisionHandler(kinematicBody, staticBody); CHECK(Approx(kinematicBody.getPosition().x).margin(0.001f) == 10.f); CHECK(Approx(kinematicBody.getPosition().y).margin(0.001f) == 5.f); } SECTION("After moving diagonally up left (wall is up from kinematic body)") { kinematicBody.move({-10, -10}); CollisionBody staticBody({-10, -25, 30, 20}, 0); staticCollisionHandler(kinematicBody, staticBody); CHECK(Approx(kinematicBody.getPosition().x).margin(0.001f) == -10.f); CHECK(Approx(kinematicBody.getPosition().y).margin(0.001f) == -5.f); } SECTION("After moving diagonally up right (wall is up from kinematic body)") { kinematicBody.move({10, -10}); CollisionBody staticBody({-10, -25, 30, 20}, 0); staticCollisionHandler(kinematicBody, staticBody); CHECK(Approx(kinematicBody.getPosition().x).margin(0.001f) == 10.f); CHECK(Approx(kinematicBody.getPosition().y).margin(0.001f) == -5.f); } } }
true
1adec6b3f3e07564fc01b03cfb0494c0c1789576
C++
daiseyj15/4346AI
/AStarWithHeuristicFunctions/h5.cpp
UTF-8
959
2.6875
3
[]
no_license
float heuristicFunction_H5(Node* s, AStar* t) { //h5(n) = {Go around the edge of the board, i.e., //omit the center square, count the number of pairs //of tiles that are "inverted" compared to the goal position, and return this number} float pairsInverted = 0; int** currentpuzzle = s->getPuzzle(); if(currentpuzzle[0][0] == (currentpuzzle[0][1]+1)) pairsInverted += 1; if(currentpuzzle[0][1] == (currentpuzzle[0][2]+1)) pairsInverted += 1; if(currentpuzzle[0][2] == (currentpuzzle[1][2]+1)) pairsInverted += 1; if(currentpuzzle[1][2] == (currentpuzzle[2][2]+1)) pairsInverted += 1; if(currentpuzzle[2][2] == (currentpuzzle[2][1]+1)) pairsInverted += 1; if(currentpuzzle[2][1] == (currentpuzzle[2][0]+1)) pairsInverted += 1; if(currentpuzzle[2][0] == (currentpuzzle[1][0]+1)) pairsInverted += 1; return pairsInverted; }
true
c0597e32d0d7ff97731df466e6be9bb94110f21a
C++
manish1596/DS_and_Algo_Library
/Sorting Algorithms/Merge_sort.cpp
UTF-8
1,182
2.96875
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; void merg_e(int a[], int p, int q, int r) { int i,j,k; j=0; k=0; int l[q-p+1]; int m[r-q]; for(i=0; i<q-p+1; i++) l[i]=a[p+i]; for(i=0; i<r-q; i++) m[i]=a[q+1+i]; if(r>p) { for(i=0;i<r-p+1;i++) { if(j>=q-p+1) { a[p+i]=m[k]; k++; continue; } if(k>=r-q) { a[p+i]=l[j]; j++; continue; } if(l[j]<=m[k]) { a[p+i]=l[j]; j++; } else { a[p+i]=m[k]; k++; } } } } void merge_sort(int b[], int p, int q) { int mid; mid=(p+q)/2; if(p<q) { merge_sort(b, p, mid); merge_sort(b, mid+1, q); } merg_e(b, p, mid, q); } int main() { int n; cin >> n; int arr[n]; for(int i=0; i<n; i++) { cin >> arr[i]; } merge_sort(arr,0,n-1); for(int i=0; i<n; i++) { cout << arr[i] << " "; } return 0; }
true
e8fe5f98f16aa2b05e134e82c1bf51a5b39b5410
C++
AsAsgard/BigBlackHole
/CppUniversityTasks/Task4/print_tuple/print_tuple_ver.1/print_tuple.h
UTF-8
1,273
3.515625
4
[]
no_license
#ifndef PRINT_TUPLE_H #define PRINT_TUPLE_H #include <iostream> #include <sstream> #include <tuple> class TPrinterPrivate{ std::stringstream ss; template<std::size_t N, typename... Types> friend class TPrinter; template<typename... Types> friend std::ostream& operator<<(std::ostream& out, const std::tuple<Types...>& t); public: TPrinterPrivate() : ss("") {} template<typename... Types> TPrinterPrivate(Types... Args) = delete; }; static TPrinterPrivate pr; template<std::size_t N, typename... Types> class TPrinter { public: static void print_tuple(const std::tuple<Types...> &t) { TPrinter<N-1, Types...>::print_tuple(t); pr.ss << ", " <<std::get<N-1>(t); } }; template<typename... Types> class TPrinter<1, Types...> { public: static void print_tuple(const std::tuple<Types...> &t) { pr.ss << std::get<0>(t); } }; template<typename... Types> class TPrinter<0, Types...> { public: static void print_tuple(const std::tuple<Types...> &t) {} }; template<typename... Types> std::ostream& operator<<(std::ostream& out, const std::tuple<Types...>& t) { pr.ss.str(""); TPrinter<sizeof...(Types), Types...>::print_tuple(t); out << pr.ss.str(); return out; } #endif // PRINT_TUPLE_H
true
f6e14414dbf5cc5c60f4abfae7a3aae85b3bea09
C++
ramtw/CompetitiveProgramming
/StringsAndArrays/stringCompression.cpp
UTF-8
983
3.8125
4
[]
no_license
/* Implement basic compression using counts of repeated characters if result string is shorter than original */ #include <iostream> #include <string> using namespace std; int newLength(string s){ int count = 0; for(int i = 0; i < s.length(); i++){ if(s[i+1] == s[i]) continue; else count++; } return count * 2; } string compression(string s){ string newString ; if(newLength(s) >= s.size()) return s; else { int count = 1; for(int i = 0; i < s.size(); i++){ if(s[i+1] == s[i]) count++; else { newString += s[i];// + a; newString += to_string(count); count = 1; } } } return newString ; } int main() { string s1 = "aaaaaaaaaaaaaabcccdeeee"; cout << compression(s1) << endl; string s2 = "aabcccde"; cout << compression(s2) << endl; return 0; }
true
5505b5e53637436a7627ea409f4b1ad931e78916
C++
Garcia-Christophe/NavalBattle
/src/CBateau.cpp
UTF-8
7,083
3.515625
4
[]
no_license
#include "CBateau.h" /** * Constructeur de CBateau par défaut. Il initialise le nom du bateau à "néant", sa taille et ses * positions à 0, et son tableau de dégâts à NULL. */ CBateau::CBateau() { m_nom = "neant"; m_taille = 0; m_position.first = 0; m_position.second = 0; m_pDegats = NULL; } /** * Constructeur de CBateau avec paramètres. Ces paramètres perttent d'initialiser le bateau en lui donnant * son nom, sa taille et ses positions. Son tableau de dégâts est rempli de valeurs booléennes "false". * * @param n le nom du bateau * @param p les positions du bateau * @param t la taille du bateau * * @pre Si la taille passée en paramètre est positive, si le nom (non null) correspond à un nom connu et si * la taille correspond au nom du bateau */ CBateau::CBateau(string n, pair<int,int> p, int t) { // Pré-condition if (t <= 0) { range_error e ("Taille incorrecte pour un bateau."); throw e; } else if (p.second + t - 1 > TAILLE_GRILLE - 2) { range_error e ("La taille du bateau est trop grande."); throw e; } else if (n != "porte-avion" && n != "croiseur" && n != "contre-torpilleur" && n != "sous-marin" && n != "torpilleur") { logic_error e ("Le bateau doit avoir un nom connu (porte-avion, croiseur, contre-torpilleur, sous-marin, torpilleur)."); throw e; } else if ((n == "porte-avion" && t != 5) || (n == "croiseur" && t != 4) || (n == "contre-torpilleur" && t != 3) || (n == "sous-marin" && t != 2) || (n == "torpilleur" && t != 1)) { logic_error e ("La taille du bateau doit correspondre au nom (porte-avion : 5, croiseur : 4, contre-torpilleur : 3, sous-marin : 2, torpilleur : 1)."); throw e; } m_nom = n; m_taille = t; m_pDegats = new bool[m_taille]; setPosition(p.first, p.second); for (int i = 0; i < m_taille; i++) { m_pDegats[i] = false; } } /** * Le copy-constructeur copie profondément le bateau passé en paramètre. * * @param theB le bateau à copier */ CBateau::CBateau(const CBateau& theB) { m_nom = theB.m_nom; m_taille = theB.m_taille; m_pDegats = new bool[m_taille]; setPosition(theB.m_position.first, theB.m_position.second); for (int i = 0; i < theB.m_taille; i++) { m_pDegats[i] = theB.m_pDegats[i]; } } /** * Redéfinit l'opérateur =. * * @param theB le bateau qui récupère les valeurs de ce bateau * * @return la bateau avec les nouvelles données */ CBateau CBateau::operator= (CBateau& theB) { theB.m_nom = m_nom; theB.m_taille = m_taille; theB.m_pDegats = m_pDegats; theB.setPosition(m_position.first, m_position.second); return theB; } /** * Retourne l'état de la partie du bateau correspondant à l'index passé en paramètre. "true" signifie que * partie a été touchée par l'ennemi, "false" signifie qu'elle est toujours intacte. * * @param i la position d'une partie du bateau * * @pre Si le paramètre est positif et inférieur à la taille du bateau * * @return vrai si la partie du bateau est coulée, faux sinon */ bool CBateau::getDegats(int i) { // Pré-condition if (i < 0 || i >= m_taille) { out_of_range e ("L'index doit être positif et inférieur à la taille du bateau."); throw e; } bool degats = false; // Si le bateau n'est pas le neant if (m_taille > 0) { degats = m_pDegats[i]; } return degats; } /** * Retourne le nom du bateau. * * @return le nom du bateau */ string CBateau::getNom() { return m_nom; } /** * Retourne la taille du bateau. * * @return la taille du bateau */ int CBateau::getTaille() { return m_taille; } /** * Retourne les positions du bateau. * * @return les positions du bateau */ pair<int,int> CBateau::getPosition() { return m_position; } /** * Définit les positions du bateau. * * @param i la ligne du point d'encrage du bateau * @param j la colonne du point d'encrage du bateau * * @pre Si les paramètres rentrent bien dans la grille et que la taille ne fait pas dépasser * le nouveau point d'encrage */ void CBateau::setPosition(int i, int j) { // Pré-condition if (i < 0 || i > TAILLE_GRILLE - 2 || j < 0 || j > TAILLE_GRILLE - 2) { out_of_range e ("Le bateau dépasse la grille."); throw e; } else if (j + m_taille - 1 > TAILLE_GRILLE - 2) { out_of_range e ("Le nouveau point d'encrage fait dépasser le bateau de la grille."); throw e; } m_position.first = i; m_position.second = j; } /** * Retourne l'état du bateau. "true" signifie que toutes les parties du bateau ont été touchées par * l'ennemi, "false" signifie qu'une partie est toujours intacte. * * @return vrai si le bateau est coulé, faux sinon */ bool CBateau::estCoule() { bool estCoule = true; int i = 0; // Le bateau est coulé si toutes ses cases ont été touchées while (estCoule && i < m_taille) { if (!m_pDegats[i]) { estCoule = false; } i++; } return estCoule; } /** * Retourne l'état du tir adverse. "true" signifie que l'ennemi vient de toucher une partie du bateau * qui était encore restée intacte, "false" signifie que le tir a manqué le bateau. * * @param p la position du tir adverse * * @return vrai si le tir adverse touche le bateau, faux sinon */ bool CBateau::tirAdverse(pair<int,int> p) { bool tirReussi = false; // Si le tir touche une case du bateau if (p.first == m_position.first && p.second >= m_position.second && p.second < m_position.second + m_taille) { // Si la case n'a pas déjà été touchée if (!m_pDegats[p.second - m_position.second]) { tirReussi = true; m_pDegats[p.second - m_position.second] = true; } } return tirReussi; } /** * Affiche à l'écran les caractéristiques du bateau. * * @param os la sortie de l'affichage * @param theB le bateau à afficher * * @return l'affichage des caractéristiques du bateau */ ostream& operator<< (ostream& os, CBateau& theB) { os << "Nom : " << theB.m_nom << endl; os << "Taille : " << theB.m_taille << endl; if (theB.m_taille > 0) { os << "Positions : " << endl; for (int i = 0; i < theB.m_taille; i++) { string touchePasTouche; if (theB.m_pDegats[i]) { touchePasTouche = " : touche"; } else { touchePasTouche = " : pas touche"; } os << "- " << theB.m_position.first << "," << (theB.m_position.second + i) << touchePasTouche << endl; } } return os; } /** * Desctructeur de CBateau. */ CBateau::~CBateau() { delete[] m_pDegats; }
true
e3cfdf73c6b8ac068ca7df5f2c70528c3a6e4336
C++
xSeditx/Native-API
/nativeAPI/main.cpp
UTF-8
2,050
2.796875
3
[]
no_license
#include"Threading/native_thread.h" #include<vector> //https://c9x.me/x86/html/file_module_x86_id_26.html native::mutex Mtx; std::vector<uint32_t> ThreadVector; void Thread_TestFunction() { //Print("Active Thread: " << native::thread::ActiveThread()); //Print("Get Thread: " << native::thread::GetThread()); std::mutex A; A.lock(); Print("Hello"); A.unlock(); Print("Stack Size: " << native::thread::get_StackSize() / 1024 << " In Thread" << native::thread::ActiveThread()); for (uint32_t i{ 0 }; i < 100; ++i) { Mtx.lock(); ThreadVector.push_back(ThreadVector.back() + 1); Mtx.unlock(); } } int main() { ThreadVector.push_back(1); native::thread Thread0(Thread_TestFunction); /* */ native::thread Thread1(Thread_TestFunction); /* Spawn a Number of Threads */ native::thread Thread2(Thread_TestFunction); /* */ native::thread Thread3(Thread_TestFunction); /* */ native::thread Thread4(Thread_TestFunction); /* */ native::thread Thread5(Thread_TestFunction); /* */ Thread0.wait(); /* Make sure they */ Thread1.wait(); /* are Finished */ Thread2.wait(); /* */ Thread3.wait(); /* */ Thread4.wait(); /* */ Thread5.wait(); /* */ for (int i{ 1 }; i < ThreadVector.size(); ++i) /* Test Order to Ensure Functionality */ { if (ThreadVector[i] != ThreadVector[i - 1] + 1) { THREAD_ERROR("Threading Test Failed. Elements Out Of Order "); } } } #include<shared_mutex> #include<future> #include<mutex>
true
c21c81cb1d46ac1584ee366ff7ad54786e269b7d
C++
simonlindholm/otterduck
/src/client/anim.h
UTF-8
632
2.890625
3
[]
no_license
#pragma once #include "resources.h" // An animation. class Anim { public: Anim(Resources::Img start, unsigned int len, unsigned int delay); // Initialize Anim with an empty state. Calls to getImage will get // undefined results until operator= or resetFromDifferent is called. Anim(); // Assign to this animation from another, resetting animation state // if it differs. void resetFromDifferent(const Anim& other); // Get the current image. Resources::Img getImage() const; // Step the animation. void step(unsigned int delay); private: Resources::Img start; int len, frame; int fdelay, left; };
true
ccec9d6bba5d08daed9bbe03d9378ec0e2449ff4
C++
kyawawa/procon
/atcoder/ABC/abc127/src/f.cpp
UTF-8
1,417
2.828125
3
[]
no_license
#include <iostream> #include <cstdio> #include <cmath> #include <vector> #include <string> #include <algorithm> #include <set> using namespace std; // あるxを大きくするか小さくするかで距離が縮まるaが多い方向に進めていく // queryが // 奇数 => 真ん中 // 偶数 => 真ん中2つの内の小さい方 // どちらも(num_query - 1) / 2 // 偶数->奇数の時、abs(新しい中央 - 追加された数)だけ増える // 奇数->偶数の時、abs(元の中央 - 追加された数)だけ増える int main() { cin.tie(0); ios::sync_with_stdio(false); int Q; cin >> Q; int minimum = -1e9; int maximum = 1e9; int num_query = 0; long long ans = 0; multiset<int> a_list; multiset<int>::iterator center; for (int i = 0; i < Q; ++i) { int kind_query; cin >> kind_query; if (kind_query == 1) { int new_a, b; cin >> new_a >> b; ++num_query; int center_num; if (num_query % 2 == 0) center_num = *center; a_list.insert(new_a); center = a_list.cbegin(); advance(center, (num_query - 1) / 2); if (num_query % 2 == 1) center_num = *center; ans += abs(center_num - new_a) + b; } else { cout << *center << " " << ans << "\n"; } } cout << flush; return 0; }
true
ec0eca1998c134e6dfcc26f12d09f127836fd52c
C++
Krstar233/krits-code-workplace
/Old-Code/题解代码/acm/求共同元素(数组).cpp
UTF-8
990
2.5625
3
[]
no_license
#include <stdio.h> #include <algorithm> using namespace std; int main() { int t; int num[3][100],com[100]; int n[3]; scanf("%d",&t); while (t--) { int i,j,k,q; int x; int flag1,flag2; int c_com=0; for (i=0;i<3;i++) { scanf ("%d",&n[i]); for (j=0;j<n[i];j++) { scanf ("%d",&num[i][j]); } } for (i=0;i<n[0];i++) { flag1=flag2=0; x=num[0][i]; for (j=0;j<n[1];j++) { if (x==num[1][j]) { for (q=0;q<c_com;q++) { if (x==com[q]) break; } if (q==c_com) { flag1=1; } } } for (k=0;k<n[2];k++) { if (x==num[2][k]) { for (q=0;q<c_com;q++) { if (x==com[q]) break; } if (q==c_com) { flag2=1; } } } if (flag1==1&&flag2==1) { com[c_com]=x; c_com++; } } sort(com,com+c_com); printf ("%d:",c_com); for (i=0;i<c_com;i++) { printf ("%d",com[i]); if (i!=c_com-1) printf (" "); } printf ("\n"); } }
true
a0a74c223249f42bcf60cd3d04e72e74946d8170
C++
caetanosauer/foster-btree
/src/encoding.h
UTF-8
18,532
2.71875
3
[ "MIT" ]
permissive
/* * MIT License * * Copyright (c) 2016 Caetano Sauer * * 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. */ #ifndef FOSTER_BTREE_ENCODING_H #define FOSTER_BTREE_ENCODING_H /** * \file encoding.h * * Classes and utilities to encode objets, tuples, or arbitrary key-value pairs into the format * accepted by the lower-level slot array, which supports fixed-length keys (usually a poor man's * normalized key) and uninterpreted byte sequences as payloads. * * Encoding and decoding functionality is implemented with the Encoder policy, which supports both * stateless and stateful encoding. The former does not maintain any internal buffers or metadata, * and always performs encoding/decoding on-the-fly. The latter allows for more complex * serialization schemes, where an intermediate buffer is required; this would be useful to encode * arbitrary tuples or objects, for instance. * * These functions only support scalar types for fixed-length keys and payloads and string for * variable length. Other variable-length types like vector result in a compilation error due to a * static assertion failure. This is not considered a serious restriction though, as strings can * easily be used to encode binary data in C++. */ #include <climits> #include <type_traits> #include <cstdint> #include <cstring> #include <string> #include <tuple> #include "assertions.h" using std::string; namespace foster { /** * \brief Utility function to swap the endianness of an arbitrary input variable. * * Credit due to stackoverflow user alexandre-c */ template <typename T> T swap_endianness(T u) { static_assert (CHAR_BIT == 8, "CHAR_BIT != 8"); union { T u; unsigned char u8[sizeof(T)]; } source, dest; source.u = u; for (size_t k = 0; k < sizeof(T); k++) { dest.u8[k] = source.u8[sizeof(T) - k - 1]; } return dest.u; } /** * \brief Dummy prefixing function that returns its input unaltered. */ template <class K> struct NoPrefixing { K operator()(const K& key) { return key; } }; /** * \brief Function object used for prefixing, i.e., extracting a poor man's normalized key. * * Takes a key K, which must be of a scalar type, and extracts the appropriate poor man's normalized * key of type PMNK_Type. * * There are two possible behaviors with respect to endianness: * 1. If K and PMNK_Type are of the same size, no endianness conversion is performed. In this case, * the function basically behaves as a cast that maintains the same byte representation. For * example, a simple cast from a float 27.5 into an int would yield 27, which does not have the same * byte representation. * 2. If K is larger than PMNK_Type (as per sizeof), then the endianness must be swapped twice: * first to extract the sizeof(PMNK_Type) most significant bytes of the key, and then to restore the * original little-endian representation used for comparisons. This overhead my be substantial. * However, scalar keys with smaller PMNK type is not a situation for which we aim to optimize at * the moment. It might be best to simply use an 8-byte PMNK for an 8-byte key, for instance. This * also saves the overhead of encoding the rest of the key on the payload area of the slot array. */ template <class K, class PMNK_Type> struct PoormanPrefixing { static_assert(std::is_scalar<K>::value, "Encoding with poor man's normalized keys requires scalar or string key types"); static_assert(sizeof(K) >= sizeof(PMNK_Type), "The type of a poor man's normalized key cannot be larger than the type of the original key"); PMNK_Type operator()(const K& key) { union { K swapped; PMNK_Type prefix; }; if (sizeof(K) >= sizeof(PMNK_Type)) { swapped = swap_endianness<K>(key); prefix = swap_endianness<PMNK_Type>(prefix); } else { // same size -- do nothing swapped = key; } if (std::is_signed<K>::value && std::is_unsigned<PMNK_Type>::value) { // when normalizing singed integer into unsigned, most significant bit must be flipped return prefix ^ (1 << (sizeof(PMNK_Type) * 8 - 1)); } return prefix; } }; /** * \brief Specialization of PoormanPrefixing for string keys. * * This is probably the common case, where keys are of variable length. In this case, the first * sizeof(PMNK_Type) bytes are extracted and converted into little-endian representation. */ template <class PMNK_Type> struct PoormanPrefixing<string, PMNK_Type> { PMNK_Type operator()(const string& key) { union { unsigned char bytes[sizeof(PMNK_Type)]; PMNK_Type prefix; }; size_t amount = sizeof(PMNK_Type); if (key.length() < amount) { prefix = 0; amount = key.length(); } memcpy(&bytes, key.data(), amount); prefix = swap_endianness<PMNK_Type>(prefix); return prefix; } }; template <class T> class DummyEncoder { public: using Type = T; /** \brief Returns encoded length of a decoded value */ static size_t get_payload_length(const T&) { return 0; } /** \brief Returns length of an encoded value */ static size_t get_payload_length(void*) { return 0; } /** \brief Dummy encoding == do nothing */ static char* encode(char* p, const T&) { return p; } /** \brief Dummy decoding == do nothing */ static const char* decode(const char* p, T*) { return p; } }; // template <class T> // class AssignmentEncoder // { // public: // using Type = T; // /** \brief Returns encoded length of a decoded value */ // static size_t get_payload_length(const T&) { return sizeof(T); } // /** \brief Returns length of an encoded value */ // static size_t get_payload_length(void*) { return sizeof(T); } // /** \brief Encodes a given value into a given address using the assignment operator */ // static char* encode(char* dest, const T& value) // { // new (dest) T {value}; // // T* value_p = reinterpret_cast<T*>(dest); // // *value_p = value; // return dest + sizeof(T); // } // /** // * \brief Decodes a given memory area into a key-value pair // * // * A key or value argument given as a nullptr is not decoded. If both are nullptr, the function // * does nothing. // */ // static const char* decode(const char* src, T* value_p) // { // const T* value_src = reinterpret_cast<const T*>(src); // if (value_p) { // *value_p = *value_src; // } // return src + sizeof(T); // } // }; template <class T> class InlineEncoder { public: using Type = T; static size_t get_payload_length(const T&) { return sizeof(T); } static size_t get_payload_length(void*) { return sizeof(T); } static char* encode(char* dest, const T& value) { memcpy(dest, &value, sizeof(T)); return dest + sizeof(T); } static const char* decode(const char* src, T* value_p) { if (value_p) { memcpy(value_p, src, sizeof(T)); } return src + sizeof(T); } }; template <> class InlineEncoder<string> { public: using Type = string; using LengthType = uint16_t; /** \brief Returns encoded length of a decoded value */ static size_t get_payload_length(const string& value) { return sizeof(LengthType) + value.length(); } /** \brief Returns length of an encoded value */ static size_t get_payload_length(void* ptr) { return *(reinterpret_cast<LengthType*>(ptr)) + sizeof(LengthType); } /** \brief Encodes a string using a length field followed by the contents */ static char* encode(char* dest, const string& value) { LengthType length = static_cast<LengthType>(value.length()); *(reinterpret_cast<LengthType*>(dest)) = length; dest += sizeof(LengthType); memcpy(dest, value.data(), value.length()); dest += value.length(); return dest; } /** * \brief Decodes a given memory area into a key-value pair * * A key or value argument given as a nullptr is not decoded. If both are nullptr, the function * does nothing. */ static const char* decode(const char* src, string* value_p) { LengthType length = *(reinterpret_cast<const LengthType*>(src)); if (value_p) { value_p->assign(src + sizeof(LengthType), length); } return src + sizeof(LengthType) + length; } }; /** * Helper calss to encode a tuple by applying a given encoder to each field * recursively. Encodes field N of tuple and all the following ones in * a recursive call. Recursion stops when N equals the tuple size. * * This is stolen from Stroustrup's book seciton 28.6.4, 4th ed. */ template <template <typename T> class FieldEncoder, size_t N = 0> struct TupleEncodingHelper { using NextEncoder = TupleEncodingHelper<FieldEncoder, N+1>; template <size_t K, typename... T> using FieldEnc = FieldEncoder<typename std::tuple_element<K, std::tuple<T...>>::type>; template <typename... T> static typename std::enable_if<(N < sizeof...(T)), size_t>::type get_payload_length(const std::tuple<T...>& t) // non-empty tuple { return NextEncoder::get_payload_length(t) + FieldEnc<N, T...>::get_payload_length(std::get<N>(t)); } template <typename... T> static typename std::enable_if<!(N < sizeof...(T)), size_t>::type get_payload_length(const std::tuple<T...>&) // empty tuple { return 0; } template <typename... T> static typename std::enable_if<(N < sizeof...(T)), size_t>::type get_payload_length(void* ptr) // non-empty tuple { size_t flen = FieldEnc<N, T...>::get_payload_length(ptr); char* charptr = reinterpret_cast<char*>(ptr) + flen; return NextEncoder::get_payload_length(charptr); } template <typename... T> static typename std::enable_if<!(N < sizeof...(T)), size_t>::type get_payload_length(void*) // empty tuple { return 0; } template <typename... T> static typename std::enable_if<(N < sizeof...(T)), char*>::type encode(char* dest, const std::tuple<T...>& t) // non-empty tuple { char* next = FieldEnc<N, T...>::encode(dest, std::get<N>(t)); return NextEncoder::encode(next, t); } template <typename... T> static typename std::enable_if<!(N < sizeof...(T)), char*>::type encode(char* dest, const std::tuple<T...>&) // non-empty tuple { return dest; } template <typename... T> static typename std::enable_if<(N < sizeof...(T)), const char*>::type decode(const char* src, std::tuple<T...>* t) // non-empty tuple { // We can't skip decoding a tuple because we don't know the length // of the whole tuple before hand if (!t) { t = new std::tuple<T...>{}; } const char* next = FieldEnc<N, T...>::decode(src, &std::get<N>(*t)); return NextEncoder::decode(next, t); } template <typename... T> static typename std::enable_if<!(N < sizeof...(T)), const char*>::type decode(const char* src, std::tuple<T...>*) // non-empty tuple { return src; } }; template <size_t N, template <typename T> class FieldEncoder, typename... Types> struct VariadicEncodingHelper { // generic case -- never instantiated }; template <template <typename T> class FieldEncoder, typename... Types> struct VariadicEncodingHelper<0, FieldEncoder, Types...> { static size_t get_payload_length() { return 0; } static size_t get_payload_length(void*) { return 0; } static char* encode(char* dest) { return dest; } static const char* decode(const char* src) { return src; } }; template <size_t N, template <typename T> class FieldEncoder, typename T, typename... Types> struct VariadicEncodingHelper<N, FieldEncoder, T, Types...> { using NextEncoder = VariadicEncodingHelper<N-1, FieldEncoder, Types...>; static size_t get_payload_length(const T& head, const Types&... tail) { return FieldEncoder<T>::get_payload_length(head) + NextEncoder::get_payload_length(tail...); } static size_t get_payload_length(void* ptr) { size_t flen = FieldEncoder<T>::get_payload_length(ptr); char* nextptr = reinterpret_cast<char*>(ptr) + flen; return flen + NextEncoder::get_payload_length(nextptr); } static char* encode(char* dest, const T& head, const Types&... tail) { char* nextptr = FieldEncoder<T>::encode(dest, head); return NextEncoder::encode(nextptr, tail...); } static const char* decode(const char* src, T* head, Types*... tail) { const char* nextptr = FieldEncoder<T>::decode(src, head); return NextEncoder::decode(nextptr, tail...); } }; template <template <typename T> class FieldEncoder, typename... Types> using VariadicEncoder = VariadicEncodingHelper<sizeof...(Types), FieldEncoder, Types...>; template <typename... Types> class InlineEncoder<std::tuple<Types...>> { public: using Tuple = std::tuple<Types...>; using Helper = TupleEncodingHelper<InlineEncoder>; static size_t get_payload_length(const Tuple& value) { return Helper::get_payload_length(value); } static size_t get_payload_length(void* ptr) { return Helper::get_payload_length(ptr); } static char* encode(char* dest, const Tuple& value) { return Helper::encode(dest, value); } static const char* decode(const char* src, Tuple* value_p) { return Helper::decode(src, value_p); } }; /** * \brief Base class of all encoders which use a common PMNK extraction mechanism. */ template <class K, class PMNK_Type = K> class PMNKEncoder { public: /** * The function is picked at compile time based on the type parameters. If key and PMNK are of * the same type, no conversion is required and the dummy NoPrefixing is used. Otherwise, * PoormanPrefixing, the default PMNK extractor, is chosen. */ using PrefixingFunction = typename std::conditional<std::is_same<PMNK_Type, K>::value, NoPrefixing<K>, PoormanPrefixing<K, PMNK_Type>>::type; static PMNK_Type get_pmnk(const K& key) { // TODO: compiler should be able to inline this -- verify! return PrefixingFunction{}(key); } }; template <class KeyEncoder, class ValueEncoder, class PMNK_Type = typename KeyEncoder::Type> class CompoundEncoder : public PMNKEncoder<typename KeyEncoder::Type, PMNK_Type> { public: using K = typename KeyEncoder::Type; using V = typename ValueEncoder::Type; using PMNK = PMNK_Type; using ActualKeyEncoder = typename std::conditional<std::is_same<K, PMNK_Type>::value, DummyEncoder<K>, KeyEncoder>::type; /** \brief Returns encoded length of a key-value pair */ static size_t get_payload_length(const K& key, const V& value) { return ActualKeyEncoder::get_payload_length(key) + ValueEncoder::get_payload_length(value); } /** \brief Returns length of an encoded payload */ static size_t get_payload_length(void* addr) { size_t ksize = ActualKeyEncoder::get_payload_length(addr); char* p = reinterpret_cast<char*>(addr) + ksize; size_t vsize = ValueEncoder::get_payload_length(p); return ksize + vsize; } /** \breif Encodes a given key-value pair into a given memory area */ static void encode(void* dest, const K& key, const V& value) { char* p = reinterpret_cast<char*>(dest); p = ActualKeyEncoder::encode(p, key); ValueEncoder::encode(p, value); } /** * \brief Decodes a given memory area into a key-value pair * * A key or value argument given as a nullptr is not decoded. If both are nullptr, the function * does nothing. */ static void decode(const void* src, K* key, V* value = nullptr, const PMNK_Type* pmnk = nullptr) { const char* p = reinterpret_cast<const char*>(src); p = decode_key(src, key, pmnk); decode_value(p, value); } static char* decode_key(const void* src, K* key, const PMNK_Type* pmnk = nullptr) { const char* p = reinterpret_cast<const char*>(src); p = ActualKeyEncoder::decode(p, key); // If we are not encoding key explicitly, but just reusing PMNK, we assign it here if (key && std::is_same<K, PMNK_Type>::value) { assert<1>(pmnk, "PMNK required to decode this key"); *key = *pmnk; } return const_cast<char*>(p); } static void decode_value(const char* src, V* value) { ValueEncoder::decode(src, value); } }; template <class K, class V, class PMNK_Type = K> using DefaultEncoder = CompoundEncoder<InlineEncoder<K>, InlineEncoder<V>, PMNK_Type>; /** * Helper type function to get a 2-argument encoder template from a 3-argument one. * This means that we specify only the PMNK type and let the user pick whatever K and V * they want. */ template <typename PMNK_Type> struct GetEncoder { template <typename K, typename V> struct type : foster::DefaultEncoder<K, V, PMNK_Type> {}; }; } // namespace foster #endif
true
30eecc69ea7a408e1619fb8d83c684791ee38d44
C++
qjatn0120/algorithm_open_seminar
/2. Search/source_code/10819.cpp
UTF-8
523
2.609375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int N, A[10], ans; vector <int> v; int main(){ cin.tie(nullptr), ios::sync_with_stdio(false); cin >> N; for(int i = 0; i < N; i++) cin >> A[i]; sort(A, A + N); // 처음 순열로 만듦 do{ int sum = 0; for(int i = 1; i < N; i++) sum += abs(A[i - 1] - A[i]); // 주어진 식 계산 ans = max(ans, sum); // ans를 최댓값으로 갱신 }while(next_permutation(A, A + N)); // 마지막 순열까지 반복 cout << ans; }
true
0f42a1e0f646df63c1b2603d9f4d0d56460c2e9d
C++
alexandraback/datacollection
/solutions_2692487_1/C++/absmurf/1B1.cpp
UTF-8
936
2.5625
3
[]
no_license
#include<iostream> #include<stdio.h> #include<algorithm> #include<vector> #include<limits.h> using namespace std; int main() { int T,i,j; scanf("%d",&T); for(int c=1;c<=T;c++) { int A,N; scanf("%d", &A); scanf("%d", &N); int mote[N]; for(i=0;i<N;i++) scanf("%d", &mote[i]); sort(mote,mote+N); long long D[N+1][N+1]; //max size reachable in i-mote no. j-no of moves for(i=0;i<=N;i++) for(j=0;j<=N;j++) D[i][j]=-1; D[0][0]=A; for(j=1;j<=N;j++) { D[0][j]=2*D[0][j-1]-1; } for(i=1;i<=N;i++) { for(j=0;j<=N;j++) { if(j>0&&D[i][j-1]>=0) D[i][j]=2*D[i][j-1]-1; if(D[i-1][j]>mote[i-1]) D[i][j]=max(D[i][j],D[i-1][j]+mote[i-1]); if(j>0) D[i][j]=max(D[i][j],D[i-1][j-1]); //cout<<D[i][j]<<" "; } //cout<<endl; }for(j=0;j<=N;j++) if(D[N][j]>=0) break; //cout<<D[0][N-1]<<endl; printf("Case #%d: %d\n",c,j); } return 0; }
true
c58edcf0ef522a1a8d0aaa37c2ee2f7662f62032
C++
ydiz/contraction
/defs.h
UTF-8
3,425
2.78125
3
[]
no_license
#pragma once #include <iostream> #include <string> #include <vector> #include <algorithm> #include <assert.h> int factorial(int n); // sym.cc enum class Sym {u, uBar, d, dBar, s, sBar, a, b, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, alpha, beta, s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, w, x, y, z, v, g5, gmu, gnu, gL, gR, Pu, Pd, Ps}; bool isQuark(Sym sym); bool isNotQuark(Sym sym); bool isProp(Sym sym); Sym propToQuark(Sym prop); Sym bar(Sym q); Sym prop(Sym q); Sym get_color(); // get the next available color index Sym get_spin(); // get the next available spin index std::ostream& operator<<(std::ostream &out, Sym sym); std::string str(Sym sym); std::string str(const std::vector<Sym> &syms); // elem.cc struct Elem { Sym sym; std::vector<Sym> pos; std::vector<Sym> color; std::vector<Sym> spin; Elem(); Elem(Sym _sym); Elem(Sym _sym, Sym _pos, Sym _color, Sym _spin); // for quark Elem(Sym _sym, std::vector<Sym> _spin); // for gamma matrix Elem(Sym _sym, std::vector<Sym> _pos, std::vector<Sym> _color, std::vector<Sym> _spin); // for propagator std::string str() const; // string representation }; std::ostream& operator<<(std::ostream &out, const Elem &e); // terms.cc struct Term : public std::vector<Elem> { double coef; std::vector<int> spinSingletDelimiter; // mark the initial position of a new spin singlet in the contracted expression of propagators if there are multiple spin singlets Term() : coef(1.0) {} }; Term operator*(const Term &term1, const Term &term2); std::ostream& operator<<(std::ostream &out, const Term &term); std::ostream& operator<<(std::ostream &out, const std::vector<Term> &terms); // operator.cc struct Op : public std::vector<Term> {}; // to distinguish between Op and vector<Term> std::vector<Term> operator*(const Op &op1, const Op &op2); std::vector<Term> operator*(const std::vector<Term> &terms, const Op &op); std::vector<Term> operator*(const Op &op, const std::vector<Term> &terms); std::ostream& operator<<(std::ostream &out, const Op &op); Op Pi0(Sym pos); Op Eta(Sym pos); Op UBar_g5_u(Sym pos); Op DBar_g5_d(Sym pos); Op K0(Sym pos); Op K0bar(Sym pos); Op sBar_d(Sym pos); Op dBar_s(Sym pos); Op Jmu_no_s(Sym pos); Op Jnu_no_s(Sym pos); Op Jmu(Sym pos); Op Jnu(Sym pos); Op Q1(Sym pos); Op Q1bar(Sym pos); Op Q2_mixed(Sym pos); Op Q2_unmixed(Sym pos); Op Q2bar_mixed(Sym pos); Op Q2bar_unmixed(Sym pos); Op Q3(Sym pos); // contract.cc std::vector<Term> contract(const Term &term, bool allowDisconnected = false); std::vector<Term> contract(const std::vector<Term> &terms, bool allowDisconnected = false, bool verbose = false); // simplify.cc void removeJmuSelfConnected(std::vector<Term> &terms); void combine_u_d_prop(std::vector<Term> &terms); // toLatex.cc void generateLatex(const std::vector<Term> &terms, const std::string &outFile, bool showPDF = true); std::string generateLatexMath(const Term &term); ///////////////////////////////////////////////// // misc template <class T> std::ostream& operator<<(std::ostream &out, const std::vector<T> &vec) { if(vec.empty()) { out << "{}"; return out; } out << "{"; for(int i=0; i<vec.size()-1; ++i) out << vec[i] << ","; out << vec[vec.size()-1] << "}"; return out; } template <class T, class U> std::ostream& operator<<(std::ostream &out, const std::pair<T, U> &p) { out << "(" << p.first << ", " << p.second << ")"; return out; }
true
97fe9c8eb28d0da957ab3b8ff83ed2eb4b4c5ad0
C++
cristiano-xw/c-homework
/homework/提取字符串的数字.cpp
GB18030
1,452
3.921875
4
[]
no_license
/* ʱ: 2020/08/20 Ŀģȡַе ܣӶַ˽⣬жַ νһΪһ洢 */ #include<stdio.h> void search(char*); int main() { char str[10000]; printf("ַ"); gets(str); search(str); return 0; } void search(char *str){ int i,j=0,flag=0,t=0,a[20]; for(i=0;str[i]!='\0';i++){ if(str[i]>='0'&&str[i]<='9'&&flag==0){//жDzǵһ flag=1; t=(int)str[i]-'0';//ַǿתΪͶ-'0' } else if(str[i]>='0'&&str[i]<='9'&&flag!=0)//жDzǰһֺ t=t*10+(int)str[i]-'0'; else if(flag!=0){ a[j]=t; j++; flag=0; } } if(str[i-1]>='0'&&str[i-1]<='9'){//һַҲԽ a[j]=t; j++; } printf("%dֱǣ\n",j); for(i=0;i<j;i++) printf("%d\t",a[i]); } /* ܽ᣺һַΪflag0Ϊһ һַΪflag0ôǰһֵ ----------------------- devΪ ַA123x456 17960302tab5876 5ֱǣ 123 456 17960 302 5876 ȷ ----------------------- */
true
1b053eb4dc5ed2b3973e074f02ff28bfb4b1c1d5
C++
ReCodEx/worker
/src/helpers/config.h
UTF-8
1,798
2.90625
3
[ "MIT" ]
permissive
#ifndef RECODEX_WORKER_HELPERS_CONFIG_H #define RECODEX_WORKER_HELPERS_CONFIG_H #include <memory> #include <yaml-cpp/yaml.h> #include "config/job_metadata.h" #include "config/task_metadata.h" namespace helpers { /** * From given configuration in yaml it build job_metadata structure and its tasks. * @param conf YAML representation of job configuration * @return pointer on job_metadata class */ std::shared_ptr<job_metadata> build_job_metadata(const YAML::Node &conf); /** * From given string parse suitable task_type enum. * @param type textual representation of task type * @return enum with task types */ task_type get_task_type(const std::string &type); /** * From given configuration in yaml get bind directories config for sandbox. * @param lim YAML representation of bind directories element * @return triplet of source, destination and mount point permissions */ std::vector<std::tuple<std::string, std::string, sandbox_limits::dir_perm>> get_bind_dirs(const YAML::Node &lim); /** * Special exception for config helper functions/classes. */ class config_exception : public std::exception { public: /** * Generic constructor. */ config_exception() : what_("Generic config exception") { } /** * Constructor with specified cause. * @param what cause of this exception */ config_exception(const std::string &what) : what_(what) { } /** * Stated for completion. */ ~config_exception() override = default; /** * Returns description of exception. * @return c-style string */ const char *what() const noexcept override { return what_.c_str(); } protected: /** Textual description of error. */ std::string what_; }; } // namespace helpers #endif // RECODEX_WORKER_HELPERS_CONFIG_H
true
484cd3bdcb36c25e1c7e53362ca90120db66c7a1
C++
Alex-Falk/CSC8503
/Build/Examples_Cuda/BallPoolScene.h
UTF-8
2,730
2.59375
3
[]
no_license
#pragma once #include <ncltech\Scene.h> #include <ncltech\CommonUtils.h> #include <ncltech\SoftBody.h> #define NUM_BALLS 300 #define RAND (rand() % 101) / 100.0f //Fully striped back scene to use as a template for new scenes. class BallPoolScene : public Scene { public: BallPoolScene(const std::string& friendly_name) : Scene(friendly_name) { } virtual ~BallPoolScene() { } virtual void OnInitializeScene() override { Scene::OnInitializeScene(); // Floor this->AddGameObject(CommonUtils::BuildCuboidObject( "Ground", Vector3(0.0f, 0.0f, 0.0f), Vector3(10.0f, 1.0f, 10.0f), true, 0.0f, true, false, Vector4(0.2f, 0.5f, 1.0f, 1.0f))); // Wall 1 GameObject * wall1 = CommonUtils::BuildCuboidObject( "Wall1", Vector3(10.0f, 3.0f-1.5f, 0.0f), Vector3(1.0f, 4.0f, 10.0f), true, 0.0f, true, false, Vector4(0.2f, 0.5f, 1.0f, 1.0f)); wall1->Physics()->SetOrientation(Quaternion::AxisAngleToQuaterion(Vector3(0.0f, 0.0f, 1.0f), -45.0f)); this->AddGameObject(wall1); // Wall 2 GameObject * wall2 = CommonUtils::BuildCuboidObject( "Wall2", Vector3(-10.0f, 3.0f - 1.5f, 0.0f), Vector3(1.0f, 4.0f, 10.0f), true, 0.0f, true, false, Vector4(0.2f, 0.5f, 1.0f, 1.0f)); wall2->Physics()->SetOrientation(Quaternion::AxisAngleToQuaterion(Vector3(0.0f, 0.0f, 1.0f), 45.0f)); this->AddGameObject(wall2); // Wall 3 GameObject * wall3 = CommonUtils::BuildCuboidObject( "Wall3", Vector3(0.0f, 3.0f - 1.5f, 10.0f), Vector3(10.0f, 4.0f, 1.0f), true, 0.0f, true, false, Vector4(0.2f, 0.5f, 1.0f, 1.0f)); wall3->Physics()->SetOrientation(Quaternion::AxisAngleToQuaterion(Vector3(1.0f, 0.0f, 0.0f), 45.0f)); this->AddGameObject(wall3); // Wall 4 GameObject * wall4 = CommonUtils::BuildCuboidObject( "Wall4", Vector3(0.0f, 3.0f - 1.5f, -10.0f), Vector3(10.0f, 4.0f, 1.0f), true, 0.0f, true, false, Vector4(0.2f, 0.5f, 1.0f, 1.0f)); wall4->Physics()->SetOrientation(Quaternion::AxisAngleToQuaterion(Vector3(1.0f, 0.0f, 0.0f), -45.0f)); this->AddGameObject(wall4); for (int i = 0; i < NUM_BALLS; ++i) { this->AddGameObject(CommonUtils::BuildSphereObject("spawned_sphere", Vector3(RAND*20.0f-10.0f,RAND*2.0f+3.0f,RAND*20.0f-10.0f), 0.5f, //Radius true, //Has Physics Object 1.0f / 4.0f, //Inverse Mass true, //Has Collision Shape true, //Dragable by the user CommonUtils::GenColor(RAND, 0.8f))); //Color } Scene::OnInitializeScene(); PhysicsEngine::Instance()->SetOctreeMinSize(1.0f); PhysicsEngine::Instance()->SetLimits(Vector3(-20, -5, -20), Vector3(20, 15, 20)); } private: GLuint tex; };
true
df73960a4401b102dab38d733b4706d08d0aab1d
C++
sniperswang/dev
/leetcode/L247/test.cpp
UTF-8
1,667
3.4375
3
[]
no_license
#include <iostream> #include <vector> #include <map> using namespace std; class Solution { public: void helper(vector <string> &res, vector<char> &e, string str, int pos, int n) { if ( (pos > n/2 && n % 2 != 0) || (pos >= n/2 && n % 2 ==0) ) { res.push_back(str); return; } if ( (n == 1 && pos == 0 ) || ( n % 2 != 0 && (pos == n/2))) { for (int i = 0; i < e.size(); i++) { if (e[i] != '6' && e[i] != '9') { str[pos] = e[i]; helper(res,e,str,pos+1,n); } } } else { for (int i = 0; i < e.size(); i++) { str[pos] = e[i]; if (e[i] == '6') { str[n-1-pos] = '9'; } else if (e[i] == '9') { str[n-1-pos] = '6'; } else { str[n-1-pos] = e[i]; } helper(res,e,str,pos+1,n); } } return; } vector<string> findStrobogrammatic(int n) { vector <string> res; if (n == 0) return res; vector<char> element; element.push_back('0'); element.push_back('1'); element.push_back('6'); element.push_back('8'); element.push_back('9'); int hLen = int(n/2); string s(n,' '); if (n == 1) helper(res,element,s,0,n); else { for (int i = 1; i < element.size(); i++) { s[0] = element[i]; if (element[i] == '6') { s[n-1] = '9'; } else if (element[i] == '9') { s[n-1] = '6'; } else { s[n-1] = element[i]; } helper(res,element,s,1,n); } } return res; } }; int main() { vector <string> res; Solution s; res = s.findStrobogrammatic(3); for (int i = 0; i < res.size(); i++) { cout << res[i] << endl; } return 0; }
true
d6eb4cf4c984a1051be716299c703aca982b5a92
C++
jwvg0425/boj
/solutions/5704/5704.cpp14.cpp
UTF-8
541
2.9375
3
[]
no_license
#include<stdio.h> #include<vector> #include<iostream> #include<string> #include<algorithm> #include <set> #include <queue> #include <memory.h> int main() { while (true) { int counts[26] = { 0, }; std::string str; std::getline(std::cin, str); if (str == "*") break; for (auto& c : str) { if (c == ' ') continue; counts[c - 'a']++; } bool pangram = true; for (int i = 0; i < 26; i++) { if (counts[i] == 0) { pangram = false; } } printf("%c\n", pangram ? 'Y' : 'N'); } return 0; }
true
8dcd4c88206cec6a95abd529f294ce18991d6115
C++
istoney/POJCode
/1002.cpp
UTF-8
1,553
3.3125
3
[]
no_license
//Memory:624K Time:1250MS //2013-08-08 00:05:00 #include<iostream> #include<string> using namespace std; unsigned tele_check(string); void tele_print(unsigned); int tele_compare(const void *a, const void *b) { return *(unsigned *)a - *(unsigned *)b; } int main() { unsigned num =0,un_tmp; string str_tmp; cin>>num; unsigned *teles = (unsigned *)malloc(sizeof(unsigned)*num); for(int i=0;i<num;i++) { cin>>str_tmp; un_tmp = tele_check(str_tmp); teles[i] = un_tmp; } qsort(teles, num, sizeof(unsigned), tele_compare); int flag=0; for(int i=0;i<num;) { int j; for(j=i+1;teles[j]==teles[i];j++) {} if(j>i+1) { flag=1; tele_print(teles[i]); cout<<" "<<j-i<<endl; } i=j; } if(!flag) cout<<"No duplicates."<<endl; delete teles; return 0; } unsigned tele_check(string tele_str) { unsigned tele_int = 0; for(int i=0;i<tele_str.size();i++) { if('0'<=tele_str[i] && tele_str[i]<='9'){ tele_int = tele_int*10; tele_int += tele_str[i]-'0'; } else if('A'<=tele_str[i] && tele_str[i]<='P'){ tele_int = tele_int*10; tele_int += (tele_str[i] - 'A')/3 +2; } else if('R'<=tele_str[i] && tele_str[i]<='Y'){ tele_int = tele_int*10; tele_int += (tele_str[i]-'Q')/3 + 7; } } return tele_int; } void tele_print(unsigned tele) { cout<< tele/1000000; tele = tele%1000000; cout<< tele/100000 ; tele = tele%100000; cout<< tele/10000 <<'-'; tele = tele%10000; cout<< tele/1000 ; tele = tele%1000; cout<< tele/100 ; tele = tele%100; cout<< tele/10 ; tele = tele%10; cout<< tele ; }
true
13eefdaf24cce00844296d0fb75b968fc8f0533d
C++
yutaka-watanobe/problem-solving
/AOJ/0147/saito.cpp
UTF-8
2,922
3.0625
3
[]
no_license
#include <iostream> #include <queue> #include <cassert> using namespace std; enum EventType{ LEAVE, ARRIVE }; class Event{ public: int time; EventType type; int gid; Event(int time, EventType type, int gid) : time(time), type(type), gid(gid){ } bool operator<(const Event &e) const{ if(time == e.time) return type > e.type; return time > e.time; } }; const int SEAT_NUM = 17; int n; int used[SEAT_NUM]; priority_queue<Event> eq; queue<int> gq; bool countStart; void seat(int id, int num){ int cnt = 0; for(int i = 0; i < SEAT_NUM; ++i){ if(used[i] == -1) ++cnt; else cnt = 0; if(cnt == num){ for(int j = 0; j < num; ++j) used[i-j] = id; break; } } } void unseat(int id){ for(int i = 0; i < SEAT_NUM; ++i) if(used[i] == id) used[i] = -1; } bool canSeat(int num){ int cnt = 0; for(int i = 0; i < SEAT_NUM; ++i){ if(used[i] == -1) ++cnt; else cnt = 0; if(cnt == num) return true; } return false; } void arrive(int time, int id){ int number = (id % 5 == 1 ? 5 : 2); if(gq.empty() && canSeat(number)){ seat(id, number); int finishTime = time + 17*(id%2) + 3*(id%3) + 19; #ifdef DEBUG cout << " they finished eating at " << finishTime << endl; #endif eq.push(Event(finishTime, LEAVE, id)); } else{ #ifdef DEBUG cout << " couldn't seat" << endl; #endif if(id == n-1) countStart = true; gq.push(id); } } void leave(int time, int id){ unseat(id); while(!gq.empty()){ int gid = gq.front(); int number = (gid % 5 == 1 ? 5 : 2); if(canSeat(number)){ if(gid == n-1) countStart = false; seat(gid, number); gq.pop(); eq.push(Event(time + 17*(gid&1) + 3*(gid%3) + 19 + 1, LEAVE, gid)); } else break; } } int compute(void){ int ans = 0, curr = 0; countStart = false; while(!eq.empty()){ Event e = eq.top(); eq.pop(); if(countStart) ans += e.time - curr; curr = e.time; #ifdef DEBUG cout << "Event : " << e.time << ' ' << (e.type == ARRIVE ? "arrive " : "leave ") << e.gid << endl; #endif if(e.type == ARRIVE) arrive(e.time, e.gid); else if(e.type == LEAVE) leave(e.time, e.gid); else assert(false); #ifdef DEBUG cout <<" "; for(int i = 0; i < SEAT_NUM; ++i) if(used[i] == -1) cout << "_ "; else cout << used[i] << ' ' ; cout << endl; #endif } return ans; } void init(void){ fill(used, used+SEAT_NUM, -1); } int main(void){ while( cin >> n ){ ++n; init(); for(int i = 0; i < n; ++i) eq.push(Event(i*5, ARRIVE, i)); cout << compute() << endl; } return 0; }
true
3bb37a87fb8ebe2c0fd69955e34ec77361b38d7f
C++
true-bear/cpp_server_study_projects_Pub
/codes_book_onlinegameserver/NetLib/Thread.cpp
UTF-8
1,538
2.65625
3
[ "MIT" ]
permissive
#include "Precompile.h" #include "Thread.h" #include "Log.h" Thread::Thread(void) { m_hThread = NULL; m_bIsRun = false; m_dwWaitTick = 0; m_dwTickCount = 0; m_hQuitEvent = CreateEvent( NULL , TRUE , FALSE , NULL ); } Thread::~Thread(void) { CloseHandle( m_hQuitEvent ); if( m_hThread ) CloseHandle( m_hThread ); } unsigned int WINAPI CallTickThread(LPVOID p) { Thread* pTickThread = (Thread*) p; pTickThread->TickThread(); return 1; } bool Thread::CreateThread( DWORD dwWaitTick ) { unsigned int uiThreadId = 0; m_hThread = (HANDLE)_beginthreadex(NULL, 0, &CallTickThread, this , CREATE_SUSPENDED , &uiThreadId); if(m_hThread == NULL) { LOG( LOG_ERROR_NORMAL , " SYSTEM | Thread::CreateTickThread() | TickThread 생성 실패 : Error(%u) " , GetLastError() ); return false; } m_dwWaitTick = dwWaitTick; return true; } void Thread::Run() { if( false == m_bIsRun ) { m_bIsRun = true; ResumeThread( m_hThread ); } } void Thread::Stop() { if( true == m_bIsRun ) { m_bIsRun = false; SuspendThread( m_hThread ); } } void Thread::TickThread() { while( true ) { DWORD dwRet = WaitForSingleObject( m_hQuitEvent, m_dwWaitTick ); if( WAIT_OBJECT_0 == dwRet ) break; else if( WAIT_TIMEOUT == dwRet ) { m_dwTickCount++; OnProcess(); } } } void Thread::DestroyThread() { Run(); SetEvent( m_hQuitEvent ); WaitForSingleObject( m_hThread , INFINITE ); }
true
c6c4ea1d688f0099a437c9c01a67d10201f9f751
C++
mmaxim2710/OOP
/oop_exercise_04/vertex.h
UTF-8
1,339
3.453125
3
[]
no_license
#ifndef VERTEX_H #define VERTEX_H #include <iostream> #include <type_traits> #include <cmath> template<class T> struct vertex { T x; T y; vertex<T>& operator=(vertex<T> A); }; template<class T> std::istream& operator>>(std::istream& is, vertex<T>& p) { is >> p.x >> p.y; return is; } template<class T> std::ostream& operator<<(std::ostream& os, vertex<T> p) { os << '(' << p.x << ", " << p.y << ')'; return os; } template<class T> vertex<T> operator+(const vertex<T>& A, const vertex<T>& B) { vertex<T> res; res.x = A.x + B.x; res.y = A.y + B.y; return res; } template<class T> vertex<T>& vertex<T>::operator=(const vertex<T> A) { this->x = A.x; this->y = A.y; return *this; } template<class T> vertex<T> operator+=(vertex<T> &A, const vertex<T> &B) { A.x += B.x; A.y += B.y; return A; } template<class T> vertex<T> operator/=(vertex<T>& A, const double B) { A.x /= B; A.y /= B; return A; } template<class T> double length(vertex<T>& A, vertex<T>& B) { double res = sqrt( pow(B.x - A.x, 2) + pow(B.y - A.y, 2) ); return res; } template<class T> struct is_vertex : std::false_type {}; template<class T> struct is_vertex<vertex<T>> : std::true_type {}; #endif //VERTEX_H
true
454ad5750ce9f98fc6b5c04b2ba958af6499bbed
C++
j0ntan/Project-Euler-plus-plus
/solutions/001-050/Problem049.cpp
UTF-8
1,602
3.453125
3
[]
no_license
/* Prime permutations * The arithmetic sequence, 1487, 4817, 8147, in which each * of the terms increases by 3330, is unusual in two ways: * (i) each of the three terms are prime, and, (ii) each of * the 4-digit numbers are permutations of one another. * * There are no arithmetic sequences made up of three 1-, 2-, * or 3-digit primes, exhibiting this property, but there is * one other 4-digit increasing sequence. * * What 12-digit number do you form by concatenating the three * terms in this sequence? */ #include <iostream> #include <vector> #include <algorithm> #include "../../utils/utils.h" bool isSeqPrimes(unsigned num); bool isSeqPermutations(unsigned num); int main() { auto num = 1487u; bool foundSequence = false; while( !foundSequence && ++num <= 3339 ) foundSequence = isSeqPrimes(num) && isSeqPermutations(num); std::cout << "result: " << std::to_string(num) << std::to_string(num+3330) << std::to_string(num+6660) << std::endl; } bool isSeqPermutations(unsigned num) { auto digits1 = projEuler::getDigits(num); auto digits2 = projEuler::getDigits(num+3330); auto digits3 = projEuler::getDigits(num+6660); return std::is_permutation( digits2.begin(), digits2.end() , digits1.begin()) && std::is_permutation( digits3.begin(), digits3.end() , digits1.begin()); } bool isSeqPrimes(unsigned num) { using projEuler::isPrime; return isPrime(num) && isPrime(num+3330) && isPrime(num+6660); }
true
de80d715105f18e00fbaa9b54eef0ff23554d10e
C++
per-gron/rapidcheck
/include/rapidcheck/gen/Distinct.hpp
UTF-8
994
2.890625
3
[ "BSD-2-Clause" ]
permissive
#pragma once namespace rc { namespace gen { namespace detail { template <typename Value> class DistinctPredicate { public: template <typename ValueArg, typename = typename std::enable_if< !std::is_same<Decay<ValueArg>, DistinctPredicate>::value>::type> DistinctPredicate(ValueArg &&value) : m_value(std::forward<ValueArg>(value)) {} template <typename T> bool operator()(const T &other) const { return !(other == m_value); } private: Value m_value; }; } // namespace detail template <typename T, typename Value> Gen<T> distinctFrom(Gen<T> gen, Value &&value) { return gen::suchThat( std::move(gen), detail::DistinctPredicate<Decay<Value>>(std::forward<Value>(value))); } template <typename Value> Gen<Decay<Value>> distinctFrom(Value &&value) { return gen::suchThat( gen::arbitrary<Decay<Value>>(), detail::DistinctPredicate<Decay<Value>>(std::forward<Value>(value))); } } // namespace gen } // namespace rc
true
c7b7963912be7c99d44f8cd7f23f70f4e888ede1
C++
MichaelxhJiang/LeetCode
/LowestCommonAncestor.cpp
UTF-8
1,318
3.34375
3
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { TreeNode* lca; dfs(root, p, q, &lca); return lca; } pair<bool, bool> dfs(TreeNode* node, TreeNode* p, TreeNode* q, TreeNode** lca) { if (node == nullptr) { return {false, false}; } pair<bool, bool> found = {false, false}; if (node->val == p->val) { found.first = true; } else if (node->val == q->val) { found.second =true; } pair<bool, bool> left = dfs(node->left, p, q, lca); found.first |= left.first; found.second |= left.second; pair<bool, bool> right = dfs(node->right, p, q, lca); found.first |= right.first; found.second |= right.second; if (left.first && left.second) return found; // already found lca if (right.first && right.second) return found; // already found lca if (found.first && found.second) { //update lca *lca = node; } return found; } };
true
42dc900322d30d5cef11eca9eb433218d6577c8f
C++
zhangbaochong/LearnOpenGL
/LearnOpenGL/src/utils/MainCamera.cpp
UTF-8
285
2.515625
3
[]
no_license
#include "MainCamera.h" MainCamera* MainCamera::s_instance = nullptr; MainCamera::MainCamera(glm::vec3 position) : Camera(position) { } MainCamera* MainCamera::getInstance() { if (s_instance == nullptr) { s_instance = new MainCamera(); } return s_instance; }
true
500387707f291bad8133c1aa7e7537e0d82fa15e
C++
pandian4github/competitive-programming
/spojnew/fibosum.cpp
UTF-8
1,002
2.625
3
[ "Apache-2.0" ]
permissive
#include<stdio.h> #include<math.h> long int mod=1000000007; void multiply(long long int F[][2],long long int M[][2]) { long long int x = F[0][0]*M[0][0] + F[0][1]*M[1][0]; long long int y = F[0][0]*M[0][1] + F[0][1]*M[1][1]; long long int z = F[1][0]*M[0][0] + F[1][1]*M[1][0]; long long int w = F[1][0]*M[0][1] + F[1][1]*M[1][1]; F[0][0] = x%mod; F[0][1] = y%mod; F[1][0] = z%mod; F[1][1] = w%mod; } void power(long long int F[][2],long long int n) { if(n==0||n==1) return; long long int M[2][2]={{1LL,1LL},{1LL,0LL}}; power(F,n/2); multiply(F,F); if(n%2!=0) multiply(F,M); } long long int fibo(long long int n) { long long int F[2][2]={{1LL,1LL},{1LL,0LL}}; if(n==0) return 0; power(F,n-1); return F[0][0]; } int main() { int t; long long int n,m,M,N; scanf("%d",&t); while(t--) { scanf("%lld %lld",&m,&n); M=fibo(m+1); N=fibo(n+2); printf("%lld\n",(mod+N-M)%mod); } return 0; }
true
9017c52e46a196adab52a6d7512cf97883f44a95
C++
arbor-sim/arbor-sonata
/sonata/include/sonata/hdf5_lib.hpp
UTF-8
7,985
3
3
[]
no_license
#pragma once #include <iostream> #include <fstream> #include <string> #include <hdf5.h> namespace sonata { /// Class for reading from hdf5 datasets /// Datasets are opened and closed every time they are read class h5_dataset { public: // Constructor from parent (hdf5 group) id and dataset name - finds size of the dataset h5_dataset(hid_t parent, std::string name); // Constructor from parent (hdf5 group) id and dataset name - creates andf writes dataset `data` h5_dataset(hid_t parent, std::string name, std::vector<int> data); h5_dataset(hid_t parent, std::string name, std::vector<double> data); h5_dataset(hid_t parent, std::string name, std::vector<std::vector<int>> data); h5_dataset(hid_t parent, std::string name, std::vector<std::vector<double>> data); // returns name of dataset std::string name(); // returns number of elements in a dataset int size(); // Read all dataset template <typename T> auto get(); // Read at index `i`; throws exception if out of bounds template <typename T> auto get(const int i); // Read range between indices `i` and `j`; throws exception if out of bounds template <typename T> auto get(const int i, const int j); private: // id of parent group hid_t parent_id_; // name of dataset std::string name_; // First dimension of dataset size_t size_; }; /// Class for keeping track of what's in an hdf5 group (groups and datasets with pointers to each) class h5_group { public: // Constructor from parent (hdf5 group) id and group name // Builds tree of groups, each with it's own sub-groups and datasets h5_group(hid_t parent, std::string name); // Returns name of group std::string name(); // Add a new group std::shared_ptr<h5_group> add_group(std::string name); // Add a new int dataset template <typename T> void add_dataset(std::string name, std::vector<T> dset); // hdf5 groups belonging to group std::vector<std::shared_ptr<h5_group>> groups_; // hdf5 datasets belonging to group std::vector<std::shared_ptr<h5_dataset>> datasets_; private: // RAII to handle recursive opening/closing groups struct group_handle { group_handle(hid_t parent_id, std::string name): name(name) { if (H5Lexists(parent_id, name.c_str(), H5P_DEFAULT)) { id = H5Gopen(parent_id, name.c_str(), H5P_DEFAULT); } else { id = H5Gcreate(parent_id, name.c_str(), H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); } } ~group_handle() { H5Gclose(id); } hid_t id; std::string name; }; // id of parent group hid_t parent_id_; // name of group std::string name_; // Handles group opening/closing group_handle group_h_; }; /// Class for an hdf5 file, holding a pointer to the top level group in the file class h5_file { private: // RAII to handle opening/closing files struct file_handle { file_handle(std::string file, bool new_file = false): name(file) { if (new_file) { id = H5Fcreate(file.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); } else { id = H5Fopen(file.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT); } } ~file_handle() { H5Fclose(id); } hid_t id; std::string name; }; // name of file std::string name_; // Handles file opening/closing file_handle file_h_; public: // Constructor from file name h5_file(std::string name, bool new_file=false); // Returns file name std::string name(); // Debugging function void print(); // Pointer to top level group in file std::shared_ptr<h5_group> top_group_; }; /// Class that wraps an h5_group /// Provides direct read access to datasets in the group /// Provides access to sub-groups of the group class h5_wrapper { public: h5_wrapper(); h5_wrapper(const std::shared_ptr<h5_group>& g); // Returns number of sub-groups in the wrapped h5_group int size(); // Returns index of sub-group with name `name`; returns -1 if sub-group not found int find_group(std::string name) const; // Returns index of dataset with name `name`; returns -1 if dataset not found int find_dataset(std::string name) const; // Returns size of dataset with name `name`; returns -1 if dataset not found int dataset_size(std::string name) const; // Returns value at index i of dataset with name `name`; throws exception if dataset not found template <typename T> T get(std::string name, unsigned i) const; // Returns values between indices i and j of dataset with name `name`; throws exception if dataset not found template <typename T> T get(std::string name, unsigned i, unsigned j) const; // Returns full content of 1D dataset with name `name`; throws exception if dataset not found template <typename T> T get(std::string name) const; // Returns h5_wrapper of group at index i in members_ const h5_wrapper& operator[] (unsigned i) const; // Returns h5_wrapper of group with name `name` in members_ const h5_wrapper& operator[] (std::string name) const; // Returns name of the wrapped h5_group std::string name() const; private: // Pointer to the h5_group wrapped in h5_wrapper std::shared_ptr<h5_group> ptr_; // Vector of h5_wrappers around sub_groups of the h5_group std::vector<h5_wrapper> members_; // Map from name of dataset to index in vector of datasets in wrapped h5_group std::unordered_map<std::string, unsigned> dset_map_; // Map from name of sub-group to index in vector of sub-groups in wrapped h5_group std::unordered_map<std::string, unsigned> member_map_; }; struct local_element{ std::string pop_name; unsigned el_id; }; /// Class that stores sonata specific information about a collection of hdf5 files class h5_record { public: h5_record(const std::vector<std::shared_ptr<h5_file>>& files); // Verifies that the hdf5 files contain sonata edge information bool verify_edges(); // Verifies that the hdf5 files contain sonata node information bool verify_nodes(); // If gid < num_elements, return population and local id in population, otherwise return empty struct local_element localize(unsigned gid) const; // Given a population and local id in it, return gid unsigned globalize(local_element n) const; // Returns total number of nodes/edges int num_elements() const; // Returns the population with name `name` in populations_ const h5_wrapper& operator [](std::string name) const; // Returns the population at index `i` in populations_ const h5_wrapper& operator [](int i) const; // Returns true if `name` present in map_ bool find_population(std::string name) const; // Returns names of all populations_ std::vector<std::string> pop_names() const; // Returns all populations std::vector<h5_wrapper> populations() const; // Returns partitioned sizes of every population in the h5_record std::vector<unsigned> partitions() const; // Returns map_ std::unordered_map<std::string, unsigned> map() const; private: // Total number of nodes/ edges int num_elements_ = 0; // Keep the original hdf5 files, to guarantee they remain open for the lifetime of a record std::vector<std::shared_ptr<h5_file>> files_; // Population names std::vector<std::string> pop_names_; // Partitioned sizes of the populations std::vector<unsigned> partition_; // Wrapped h5_group representing the top levels of every population std::vector<h5_wrapper> populations_; // Map from population name to index in populations_ std::unordered_map<std::string, unsigned> map_; }; } // namespace sonata
true
d1bb8caf4c43352edadea8bf96fb573e2a72be78
C++
Jaddori/BScPCG
/BScPCG/BScPCG/Assets.cpp
UTF-8
2,005
2.890625
3
[]
no_license
#include "Assets.h" using namespace Utilities; using namespace std; namespace Assets { AssetManager::AssetManager() { } AssetManager::~AssetManager() { } int AssetManager::loadModel(const std::string& path) { int result = find(modelPaths, path); if(result < 0) { Model model; if(model.load(path)) { model.upload(); result = models.getSize(); models.add(model); modelPaths.add(path); } } return result; } void AssetManager::renderModel(int index, int instances) { models[index].render(instances); } int AssetManager::loadTexture(const std::string& path) { int result = find(texturePaths, path); if(result < 0) { Texture texture; if(texture.load(path)) { texture.upload(); result = textures.getSize(); textures.add(texture); texturePaths.add(path); } } return result; } void AssetManager::bindTexture(int index) { textures[index].bind(); } Font* AssetManager::loadFont(const std::string& path) { Font* result = nullptr; int index = find(fontPaths, path); if(index < 0) { Font font; if(font.load(path)) { index = fonts.getSize(); fonts.add(font); fontPaths.add(path); result = &fonts[index]; } } return result; } void AssetManager::unload() { for(int i=0; i<models.getSize(); i++) { models[i].unload(); } for(int i=0; i<textures.getSize(); i++) { textures[i].unload(); } for(int i=0; i<fonts.getSize(); i++) { fonts[i].unload(); } models.clear(); modelPaths.clear(); textures.clear(); texturePaths.clear(); fonts.clear(); fontPaths.clear(); } int AssetManager::find(Array<string>& paths, const string& path) { int result = -1; for(int i=0; i<paths.getSize() && result < 0; i++) { if(paths[i] == path) { result = i; } } return result; } }
true