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
d96da599145c7032ddab96424db6911bf4ecb98e
C++
Newbie-W/ProgrammerAlgorithmInterview
/01 链表/11 如何判断两个单链表(无环)是否相交/题目/3.cpp
UTF-8
2,238
3.671875
4
[]
no_license
/* 单链表相交指的是两个链表存在完全重合的部分(两链表 从中间某个位置到最终是一样的)。要求判断两个链表是否相交,如果相交,那么找出相交处的结点。 思路步骤: 如果两个链表相交,那么两个链表从相交点到链表结束都是相同的结点,必然是Y字形,所以判断两个链表的最后一个结点是不是相同即可。即, (1)先遍历一个链表,直到尾部; (2)再遍历另外一个链表,如果也可以走到同样的结尾点,则两个链表相交 (3)若相交,记下两个链表的长度n1、n2; (4)再遍历一次,长链表结点先出发前进|n1-n2|步,之后两个链表同时前进,每次一步,相遇的第一点即为两个链表相交的第一个点<br> 时间复杂度 O(n1+n2)( 假设这两个链表长度分别为n1、n2,重叠结点个数为L(0<L<min(n1, n2)),则总共对链表进行遍历的次数为n1+n2+L+n1-L+n2-L = 2(n1+n2)-L ) 空间复杂度 O(1)(常数个额外指针变量) */ /* 函数功能:判断两个链表是否相交,如果相交找出相交点 输入参数: head1、head2:分别为两个链表的头结点 返回值:如果不相交返回NULL,如果相交返回相交结点 */ LNode* isIntersect(LinkList head1, LinkList head2) { if (head==NULL || head->next==NULL head==NULL || head->next==NULL || head1==head2) return NULL; LNode* temp1 = head1->next; LNode* temp2 = head2->next; int n1 = 0, n2 = 0; // 遍历head1,找到尾结点,同时记录head1的长度 while (temp1->next) { temp1 = temp1->next; ++n1; } // 遍历head2,找到尾结点,同时记录head2的长度 while (temp2->next) { temp2 = temp2->next; ++n2; } // head1与head2有相同的尾结点 if (temp1 == temp2) { // 长链表先走|n1-n2|步 if (n1 > n2) { while (n1 - n2 > 0) { head1 = head1->next; --n1; } } if (n2 > n1) { while (n2 - n1 > 0) { head2 = head2->next; --n2; } } // 两个链表同时前进,找出相同的结点 while (head1 != head2) { head1 == head1->next; head2 == head2->next; } return head1; } // head1与head2没有相同的尾结点 else return NULL; }
true
cbf76efabcb9c90c3bb08035dd399d4684432d3f
C++
wertkh32/MetalKitten
/perfmon.h
UTF-8
773
2.84375
3
[]
no_license
#pragma once #include <windows.h> typedef struct { LARGE_INTEGER start; LARGE_INTEGER stop; } stopWatch; class perfmon { stopWatch timer; LARGE_INTEGER frequency; float LIToMSecs( LARGE_INTEGER & L) { return ((float)L.QuadPart /(float)frequency.QuadPart) * 1000 ; } public: perfmon(void) { timer.start.QuadPart=0; timer.stop.QuadPart=0; QueryPerformanceFrequency( &frequency ) ; } void startTimer( ) { QueryPerformanceCounter(&timer.start) ; } void stopTimer( ) { QueryPerformanceCounter(&timer.stop) ; } float getElapsedTime() { LARGE_INTEGER time; time.QuadPart = timer.stop.QuadPart - timer.start.QuadPart; return LIToMSecs( time) ; } void print() { printf("%f\n",getElapsedTime()); } };
true
c25fa7cf4e16a219c726a89d6acae66347c07f7f
C++
hausp/falk
/include/ast/declaration.hpp
UTF-8
786
2.84375
3
[]
no_license
#ifndef AST_DECLARATION_HPP #define AST_DECLARATION_HPP #include "node.hpp" namespace ast { // Captures behavior of declarations. // Basically, constructs a node with any data and // add other node as subnode. // Does not allow operations and provides a explicit // method to extract the node. template<typename Analyser> class declaration { using node = ast::node<Analyser>; using node_ptr = std::shared_ptr<node>; using empty = ast::empty_node<Analyser>; public: declaration(); template<typename T> declaration(const T&, node_ptr = std::make_shared<empty>()); node_ptr extract(); private: node_ptr object; }; } #include "declaration.ipp" #endif /* AST_DECLARATION_HPP */
true
58b5ef60a4e9c46bb9efb99ee30e7f7368771ad0
C++
Jeffrey-W23/AIE-Assignment-GameProject
/project2D/GameState.h
UTF-8
3,303
3.03125
3
[ "MIT" ]
permissive
// #include, using, etc #pragma once #include "State.h" #include "Texture.h" class ObjectPool; //-------------------------------------------------------------------------------------- // GameState object. Inheritance from State. //-------------------------------------------------------------------------------------- class GameState : public State { public: //-------------------------------------------------------------------------------------- // Default Constructor. //-------------------------------------------------------------------------------------- GameState(); //-------------------------------------------------------------------------------------- // Default Destructor //-------------------------------------------------------------------------------------- ~GameState(); //-------------------------------------------------------------------------------------- // onEnter: A virtual function from state that runs first when a state is loaded. // // Param: // pMachine: a pointer to StateMachine. //-------------------------------------------------------------------------------------- void onEnter(StateMachine* pMachine); //-------------------------------------------------------------------------------------- // onUpdate: A virtual function from state to update objects. // // Param: // deltaTime: Pass in deltaTime. A number that updates per second. // pMachine: a pointer to StateMachine. //-------------------------------------------------------------------------------------- void onUpdate(float deltaTime, StateMachine* pMachine); //-------------------------------------------------------------------------------------- // onDraw: A virtual function from state to render (or "draw") objects to the screen. // // Param: // renderer2D: a pointer to Renderer2D for rendering objects to screen. //-------------------------------------------------------------------------------------- void onDraw(Renderer2D* m_2dRenderer); //-------------------------------------------------------------------------------------- // onExit: A virtual function from state that runs on state exit. // // Param: // pMachine: a pointer to StateMachine. //-------------------------------------------------------------------------------------- void onExit(StateMachine* pMachine); private: //-------------------------------------------------------------------------------------- // A pointer to a ObjectPool for dirt. //-------------------------------------------------------------------------------------- ObjectPool* objectPool; //-------------------------------------------------------------------------------------- // A pointer to a Texture m_background. //-------------------------------------------------------------------------------------- Texture* m_background; //-------------------------------------------------------------------------------------- // A pointer to a Texture m_map. //-------------------------------------------------------------------------------------- Texture* m_map; //-------------------------------------------------------------------------------------- // A pointer to a Texture m_player. //-------------------------------------------------------------------------------------- Texture* m_player; };
true
d0eeb617abddf013320b2e07d0c89df442bc1400
C++
punisher21maximum/Data-structures
/LinkList_Stack_Queue/count_nodes.cpp
UTF-8
3,154
3.578125
4
[]
no_license
#include<stdio.h> #include<stdlib.h> struct Node { int data; struct Node * next; }; void display(struct Node * head) { struct Node * temp; temp = head; printf("\n"); while(temp) { printf("%d ", temp->data); temp=temp->next; } } void insert(struct Node ** head, int data, int insert_index) { //temp node struct Node * temp = NULL; temp=(struct Node *)malloc(sizeof(struct Node)); //new node struct Node * new_node = NULL; new_node=(struct Node *)malloc(sizeof(struct Node)); new_node->data = data; new_node->next = NULL; //at start : index == 0 if(insert_index==0) { if( (*head)==NULL ) { (*head) = new_node; } else { new_node->next = (*head); (*head) = new_node; } } else if(insert_index==-1) { if( (*head)==NULL ) { (*head) = new_node; } else { temp=(*head); while(temp->next) { temp=temp->next; } temp->next=new_node; } } else if(insert_index>0) { temp = (*head); for(int i=0; i<insert_index-1; i++) { if(temp->next) temp = temp->next; else { printf("\nIndex greate than the list size. list size is : %d", i+1); return; } } if(temp->next)//if true : temp is not last node new_node->next = temp->next; else new_node->next = NULL; temp->next = new_node; } } void del_by_index(struct Node ** head, int del_index) { //temp struct Node * temp = (struct Node *)malloc(sizeof(struct Node)); if((*head)==NULL) { printf("\nList empty"); } else if(del_index==0) { temp = (*head); (*head) = (*head)->next; free(temp); } else if(del_index==-1) { temp=(*head); while(temp->next->next) temp = temp->next; free(temp->next); temp->next = NULL; } else if(del_index>0) { temp = (*head); for(int i=0; i<del_index-1; i++) { if(temp->next) temp = temp->next; else { printf("Index out of range, List size : %d", i+1); break; } } if (temp->next == NULL) { printf("Index 1 greater than list size."); } else { if(temp->next->next) { temp->next = temp->next->next; } else { temp->next = NULL; } } } else printf("Enter index greate than -1"); } int main() { // struct Node * head = NULL; // struct Node * second = NULL; // struct Node * third = NULL; // head = (struct Node *)malloc(sizeof(struct Node)); // second = (struct Node *)malloc(sizeof(struct Node)); // third = (struct Node *)malloc(sizeof(struct Node)); // head->data = 1; // head->next = second; // // second->data = 2; // second->next = third; // // third->data = 3; // third->next = NULL; struct Node * head = NULL; display(head); for(int i=0; i<10; i++) { insert(&head, i, -1); } // display(head); // del(&head, 0); // display(head); // del(&head, 0); // display(head); // del(&head, 0); // display(head); // del(&head, -1); // del(&head, 3); display(head); del_by_index(&head, 0); del_by_val(&head, 5); display(head); return 0; }
true
a43d0017014b556b1bc4cb47d811d7a1c073d724
C++
MasterGeneiJin/ProjectEuler
/ProjectEuler/Euler_42.cpp
UTF-8
340
2.65625
3
[]
no_license
#include "Euler.h" int Euler::CodedTriangleNumbers() { std::vector<std::string> names = EulerUtility::openWordFile("E:\\Euler Resources\\Euler 42.txt"); int count = 0; for (std::string name : names) { int total = 0; for (char n : name) total += n - 64; if (EulerUtility::isTriangle(total)) ++count; } return count; }
true
3e50c6aab16de415f1760af4474d5be7ea403cfd
C++
marsp0/Starfighter
/src/Grid.cpp
UTF-8
2,556
3.109375
3
[]
no_license
#include "Grid.hpp" #include <set> Grid::Grid() : m_objects(10, std::vector<Cell>()) { // The grid is composed of a vector of vectors // it is a 10 x 10. 80px wide and 60px high for (int i=0 ; i < 10 ; i++) { for (int j = 0; j < 10 ; j++) { m_objects[i].push_back(Cell(i*80,j*60, i*80 + 80, j*60+60)); } } } void Grid::Render(sf::RenderWindow& l_window) { // Renders each cell - for now its only the boundries for debugging purposes for (int i = 0; i < m_objects.size(); i++) { for (int j=0; j < m_objects[i].size(); j++) { m_objects[i][j].Render(l_window); } } } std::set<std::shared_ptr<GameObject> > Grid::GetCollisions(std::shared_ptr<GameObject> l_gameObject){ // Gets the list of elements that might be colliding with the passed object. Usually a bullet, but it can be extended later // cells is a vector containig the positions(indices) of the cells that contain the passed game object std::set<std::pair<int,int> > cells{GetIndices(l_gameObject)}; std::set<std::shared_ptr<GameObject> > result; for (auto i = cells.begin() ; i != cells.end(); i++) { if ((*i).second > -1 && (*i).second < 10 && (*i).first > -1 && (*i).first < 10) { result.insert(m_objects[(*i).second][(*i).first].m_objects.begin(), m_objects[(*i).second][(*i).first].m_objects.end() ); } } return result; } void Grid::Insert(std::shared_ptr<GameObject> l_gameObject) { std::set<std::pair<int,int> > indices{GetIndices(l_gameObject)}; for (auto i = indices.begin(); i != indices.end() ; i++) { m_objects[(*i).second][(*i).first].Insert(l_gameObject); } } void Grid::Remove(std::shared_ptr<GameObject> l_gameObject) { std::set<std::pair<int,int> > indices{GetIndices(l_gameObject)}; for (auto i = indices.begin(); i != indices.end() ; i++){ m_objects[(*i).second][(*i).first].Remove(l_gameObject); } } std::set<std::pair<int,int> > Grid::GetIndices(std::shared_ptr<GameObject> l_gameObject) { // This might happen when the entire object is in one cell std::set<std::pair<int,int> > result; result.insert(std::make_pair(l_gameObject->Left() / 80, l_gameObject->Top() / 60)); result.insert(std::make_pair(l_gameObject->Right()/ 80, l_gameObject->Top() / 60)); result.insert(std::make_pair(l_gameObject->Right()/ 80, l_gameObject->Bottom()/ 60)); result.insert(std::make_pair(l_gameObject->Left() / 80, l_gameObject->Bottom()/ 60)); return result; }
true
8c1743e112d2f73aee3a8c8122f82a73004717e3
C++
Brilliantrocks/leetcodelib
/72.编辑距离.cpp
UTF-8
2,891
3.25
3
[]
no_license
/* * @lc app=leetcode.cn id=72 lang=cpp * * [72] 编辑距离 */ // @lc code=start #include <string> #include <vector> using namespace std; class Solution { public: int minDistance(string word1, string word2) { int m = word1.size(), n =word2.size(); vector<vector<int>> dp(m+1,vector<int>(n+1,0)); for(int i = 0; i <=n;++i) dp[0][i] = i; for(int i = 0; i <=m;++i) dp[i][0] = i; for (int i =1; i <=m; ++i){ for(int j =1; j<=n; ++j){ // 统计所有操作,找到最少步骤 // 修改:dp[i-1][j-1] + 1 在字符相同时不增加 // 增删:dp[i-1][j]+1或者dp[i][j-1]+1 dp[i][j] = min(dp[i-1][j-1] + ((word1[i-1]==word2[j-1]) ? 0 : 1) , min(dp[i-1][j],dp[i][j-1])+1); } } return dp[m][n]; } }; // @lc code=end // class Solution { // public: // int minDistance(string word1, string word2) { // int dp[word1.size()][word2.size()]; // if(word1.size()==0||word2.size()==0) // return max(word1.size(),word2.size()); // for(int i=0;i<word1.size();i++){ // for(int j=0;j<word2.size();j++){ // if(i==0 && j== 0 ){ // dp[i][j] = word1[i]!=word2[j]; // continue; // } // else if(i==0){ // dp[i][j] = word1[i] == word2[j]? j : dp[i][j-1]+1; // continue; // } // else if(j==0){ // dp[i][j] = word1[i] == word2[j]? i : dp[i-1][j]+1; // continue; // } // if(word1[i] == word2[j]){ // dp[i][j] = min(min(dp[i-1][j-1],dp[i-1][j]+1),dp[i][j-1]+1); // } // else{ // dp[i][j] = min(min(dp[i-1][j-1],dp[i-1][j]),dp[i][j-1])+1; // } // } // } // return dp[word1.size()-1][word2.size()-1]; // } // }; // class Solution { // public: // int minDistance(string word1, string word2) { // int m = word1.size(), n =word2.size(); // vector<vector<int>> dp(m+1,vector<int>(n+1,0)); // for(int i = 0; i <=n;++i) dp[0][i] = i; // for(int i = 0; i <=m;++i) dp[i][0] = i; // for (int i =1; i <=m; ++i){ // for(int j =1; j<=n; ++j){ // // 统计所有操作,找到最少步骤 // // 修改:dp[i-1][j-1] + 1 在字符相同时不增加 // // 增删:dp[i-1][j]+1或者dp[i][j-1]+1 // dp[i][j] = min(dp[i-1][j-1] + ((word1[i-1]==word2[j-1]) ? 0 : 1) , // min(dp[i-1][j],dp[i][j-1])+1); // } // } // return dp[m][n]; // } // };
true
08d52e05cadfb89c31085a887e67ffa5eb3f6c7f
C++
dawsbot/dataStructures
/hangman_project/SOLOYOLO/code/hangman.hpp
UTF-8
2,182
3.390625
3
[]
no_license
/*=================================================================================== Author: Dawson Botsford Student ID: 102003505 *I was the one who talked to you about splitting off from my group because I did not believe the project was big enough for a group of 5 people. So here goes nothing solo-style! Thanks. Date: 4/22/2013 Purpose: Final Game project for CSCI-2400 with Gabe Johnson At CU Boulder Spring Semester 2013 Description: This is the classic hangman game. One user enters the word which they would like their friend to be guessing and for the rest of the game the friend tries to guess one character at a time until he has won ====================================================================================*/ #ifndef HANGMAN_HPP_ #define HANGMAN_HPP_ #include <string> #include <vector> using namespace std; //The master class for the Hangman manipulation class Hangman{ //private and public declarations private: public: Hangman();//class constructor //Member variables int wrong_answers;//the amount of wrong answers the user has guessed int max_wrong;//the max amount of wrong answers we are going to allow int len_guess;//the length of the string to guess int num_correct;//the amount of correct guesses thusfar string answer;//the user's word they are attempting to guess char guess;//the user's current guess bool dead;//whether the user has used all of it's guesses bool it_contains;//used within contains to loop through until all instances of the char //have been examined bool in_wrong_guesses;//whether the user has tried that letter before or not vector<char>blanked_out;//holds the current progress of guessing (start's as _ _ _ _...) vector<char>wrong_guesses;//letters guessed so far //Member functions //Takes in the user input, updates blanked_out, add's it to guessed vector void runGameLoop(); bool contains();//returns whether the char guess is found within string answer void printVector(vector<char>my_vector);//prints out the user inputted vector by iterating through void buildBlankedOut();//builds the blanked_out variable empty with just "_"'s }; #endif
true
d51fbb5b885b13317c3579385f2debb2b661254a
C++
lilelr/LeecodeProblemsSolutionsByC-
/dp/create_maximum_number_321.cpp
UTF-8
5,991
3.46875
3
[]
no_license
// // Created by YuXiao on 5/14/18. //https://leetcode.com/problems/create-maximum-number/description/ // https://leetcode.com/problems/create-maximum-number/discuss/77300/C++-DP+greedy-Solution-should-be-easy-to-understand #include <string> #include <iostream> #include <vector> #include <cstdio> using namespace std; // Here is the idea: //Let's consider a similar but simple version of this problem: if there is only one array arr of which length is m, how to find the k digits of it to create maximum number preserving the order? //So here comes to my DP solution: DP[ i ][ j ] means that the maximum number that has i digits we can get when the jth digits is the last one of this number. Thus the formula is as follows: // //dp[ i ] [ j ] = max(dp[ i ][ j ], max(dp[ i - 1 ][ 0 ... j - 1 ])) //Ok. We apply this formula to the two given arrays and then get two DP arrays DP1 and DP2 where DP[ i ] means the largest number with i digits. // //Back to our problem: Choose k digits of these two arrays/strings to create the maximum number. Now here is the greedy solution: // //For every pair of i and j where i + j == k and i is the number of digits used from array1 and j is the number of digits used from array2, we have to combine to create a new number so that it is the largest of all combinations. Remember a similar greedy problem? The trick here is that we use two pointers for each array and in each iteration, pick up pointers pointing to the larger digit or the larger substring. Then the number created is the largest from the given two arrays/strings. // //Still confused? Plsz read the code below: //Question //Given two arrays of length m and n with digits 0-9 representing two numbers. Create the maximum number of length k <= m + n from digits of the two. The relative order of the digits from the same array must be preserved. Return an array of the k digits. You should try to optimize your time and space complexity. //Example 1: //nums1 = [3, 4, 6, 5] //nums2 = [9, 1, 2, 5, 8, 3] //k = 5 //return [9, 8, 6, 5, 3] // //Example 2: //nums1 = [6, 7] //nums2 = [6, 0, 4] //k = 5 //return [6, 7, 6, 0, 4] // //Example 3: //nums1 = [3, 9] //nums2 = [8, 9] //k = 3 //return [9, 8, 9] class Solution { public: vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) { vector<int> ans; if(!nums1.size() && !nums2.size() || !k) return ans; ans.resize(k); int n = nums1.size(), m = nums2.size(); vector<string> dp1(min(k, n)), dp2(min(k, m)); vector<string> dpprev1(n), dpcur1(n), dpprev2(m), dpcur2(m); for(int i = 0; i < dp1.size(); ++ i){ string tmpval(i + 1, 0); dp1[i] = tmpval; if(!i){ for(int j = 0; j < n; ++ j){ dpprev1[j] = ""; dpprev1[j] += (char)(nums1[j] + '0'); dp1[i] = max(dp1[i], dpprev1[j]); if(j) dpprev1[j] = max(dpprev1[j], dpprev1[j - 1]); } }else{ for(int j = i; j < n; ++ j){ dpcur1[j] = tmpval; dpcur1[j] = max(dpcur1[j], dpprev1[j - 1] + (char)(nums1[j] + '0')); dp1[i] = max(dp1[i], dpcur1[j]); if(j >= i) dpcur1[j] = max(dpcur1[j], dpcur1[j - 1]); } dpprev1 = dpcur1; } } for(int i = 0; i < dp2.size(); ++ i){ string tmpval(i + 1, 0); dp2[i] = tmpval; if(!i){ for(int j = 0; j < m; ++ j){ dpprev2[j] = ""; dpprev2[j] += (char)(nums2[j] + '0'); dp2[i] = max(dp2[i], dpprev2[j]); if(j) dpprev2[j] = max(dpprev2[j], dpprev2[j - 1]); } }else{ for(int j = i; j < m; ++ j){ dpcur2[j] = tmpval; dpcur2[j] = max(dpcur2[j], dpprev2[j - 1] + (char)(nums2[j] + '0')); dp2[i] = max(dp2[i], dpcur2[j]); if(j >= i) dpcur2[j] = max(dpcur2[j], dpcur2[j - 1]); } dpprev2 = dpcur2; } } string tmpans(k, 0), v = ""; if(!dp1.size()){ getAns(v, dp2[k - 1], ans, tmpans); }else{ for(int i = 0; i <= min(k, (int)dp1.size()); ++ i){ if(i == 0){ if(dp2.size() >= k) getAns(v, dp2[k - 1], ans, tmpans); }else if(i < k){ if(dp2.size() >= k - i) getAns(dp1[i - 1], dp2[k - i - 1], ans, tmpans); }else{ if(dp1.size() >= k) getAns(dp1[k - 1], v, ans, tmpans); } } } return ans; } private: void getAns(string &s1, string &s2, vector<int> &ans, string &tmpans){ string res; if(!s1.size()) res = s2; else if(!s2.size()) res = s1; else{ int id1 = 0, id2 = 0; while(id1 < s1.size() && id2 < s2.size()){ if(s1[id1] > s2[id2]){ res += s1[id1 ++]; }else if(s1[id1] < s2[id2]){ res += s2[id2 ++]; }else{ if(s1.substr(id1) >= s2.substr(id2)) res += s1[id1 ++]; else res += s2[id2 ++]; } } while(id1 < s1.size()) res += s1[id1 ++]; while(id2 < s2.size()) res += s2[id2 ++]; } if(res > tmpans){ tmpans = res; for(int i = 0; i < res.size(); ++ i) ans[i] = (res[i] - '0'); } } };
true
a2fffbb578aeee2c3a63b54183aad1a8d5d3f7b4
C++
wanttobeno/gb
/gb_ini_test/gb_ini_test.cpp
GB18030
1,588
2.71875
3
[ "LicenseRef-scancode-public-domain" ]
permissive
/* test_ini_handler Ӧʼշ1Ϊڵֵ½ж name=QQ version=8.0.16954.0 [license] name=Copyright (C) 1999-2015 Tencent. All Rights Reserved [author] name=Tencent */ #define GB_INI_CPP #define GB_INI_IMPLEMENTATION #include "gb_ini.h" #include <stdio.h> #include <stdlib.h> struct Library { char const *name; int version; char const *license; char const *author; }; // The below macro expands to this: static gbIniHRT test_ini_handler(void *data, char const *section, char const *name, char const *value) //static GB_INI_HANDLER(test_ini_handler) { Library* lib = (Library*)data; #define TEST(s, n) (strcmp(section, s) == 0 && strcmp(name, n) == 0) if (TEST("", "name")) lib->name = strdup(value); else if (TEST("", "version")) lib->version = atoi(value); else if (TEST("license", "name")) lib->license = strdup(value); else if (TEST("author", "name")) lib->author = strdup(value); else return 1; #undef TEST return 1; } int main(int argc, char** argv) { Library lib = {}; using namespace gb; Ini_Error err = ini_parse("test.ini", &test_ini_handler, &lib); if (err.type != INI_ERROR_NONE) { if (err.line_num > 0) printf("Line (%d): ", err.line_num); printf("%s\n", ini_error_string(err)); return 1; } printf("Name : %s\n", lib.name); // Name : gb_init.h printf("Version : %d\n", lib.version); // Version : 90 printf("License : %s\n", lib.license); // License : Public Domain printf("Author : %s\n", lib.author); // Author : Ginger Bill return 0; }
true
08529bb71e784dfc74f1257139c6651f56942fb0
C++
RonanQuill96/Portfolio
/Ray Tracing/Ray Tracing/ImageData.h
UTF-8
1,433
3.40625
3
[]
no_license
#pragma once #include "Vector3.h" #include <algorithm> #include <filesystem> #include <fstream> #include <iostream> #include <mutex> template<size_t width, size_t height> class ImageData { public: void Write(Vector3 item, size_t x, size_t y) { std::lock_guard<std::mutex> lockguard(mutex); data[y][x] = item; currentPixelsComplete++; if (currentPixelsComplete % 10000 == 0) { std::cout << currentPixelsComplete << "/" << totalPixelCount << "\n"; } } Vector3 Read(size_t x, size_t y) { std::lock_guard<std::mutex> lockguard(mutex); return data[y][x]; } void WriteImageDataToFile(std::filesystem::path filepath, size_t ns) { std::ofstream file(filepath); if (file.is_open()) { std::lock_guard<std::mutex> lockguard(mutex); file << "P3\n" << width << " " << height << "\n255\n"; for (const auto& row : data) { for (Vector3 colour : row) { //Gamma correction colour /= static_cast<float>(ns); colour = Vector3(std::sqrt(colour.x), std::sqrt(colour.y), std::sqrt(colour.z)); int ir = static_cast<int>(255.99 * colour.x); int ig = static_cast<int>(255.99 * colour.y); int ib = static_cast<int>(255.99 * colour.z); file << ir << " " << ig << " " << ib << "\n"; } } } } private: std::array<std::array<Vector3, width>, height> data; std::mutex mutex; size_t totalPixelCount = width * height; size_t currentPixelsComplete = 0; };
true
68e89ac65632011e20e8c973de3789366013ed3c
C++
soumaya-nheri/Smart-parental-monitoring-system-2A28
/electromenager.cpp
UTF-8
5,362
2.9375
3
[]
no_license
#include "electromenager.h" #include <QSqlQuery> #include <QDebug> #include <QtDebug> #include <QObject> electromenager::electromenager() { matricule_machine=0; type_machine=""; etat_machine=0; emplacement_machine=""; } electromenager::electromenager(int matricule_machine, QString type_machine, int etat_machine, QString emplacement_machine) {this->matricule_machine=matricule_machine; this->type_machine=type_machine; this->etat_machine=etat_machine; this->emplacement_machine=emplacement_machine;} int electromenager::getmatricule_machine(){return matricule_machine;} QString electromenager::gettype_machine(){return type_machine;} int electromenager::getetat_machine(){return etat_machine;} QString electromenager::getemplacement_machine(){return emplacement_machine;} void electromenager::setmatricule_machine(int matricule_machine){this->matricule_machine=matricule_machine;} void electromenager::settype_machine(QString type_machine){this->type_machine=type_machine;} void electromenager::setetat_machine(int etat_machine){this->etat_machine=etat_machine;} void electromenager::setemplacement_machine(QString emplacement_machine){this->emplacement_machine=emplacement_machine;} bool electromenager::ajouter_machine() { bool test1=true; QSqlQuery query; QString matricule_machine_string= QString::number(matricule_machine); QString etat_machine_string= QString::number(etat_machine); query.prepare("INSERT INTO electromenager (matricule_machine, type_machine, etat_machine, emplacement_machine) " "VALUES (:matricule_m, :type, :etat, :emplacement)"); query.bindValue(":matricule_m", matricule_machine_string); query.bindValue(":type", type_machine); query.bindValue(":etat", etat_machine_string); query.bindValue(":emplacement", emplacement_machine); query.exec(); return test1; } QSqlQueryModel* electromenager::afficher_machine() { QSqlQueryModel* model=new QSqlQueryModel(); model->setQuery("SELECT* FROM electromenager"); model->setHeaderData(0, Qt::Horizontal, QObject::tr("Matricule")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("Type")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("Etat")); model->setHeaderData(3, Qt::Horizontal, QObject::tr("Emplacement")); return model; } bool electromenager::supprimer_machine(int matricule_machine) { QSqlQuery query; QString matricule_machine_string= QString::number(matricule_machine); QString etat_machine_string= QString::number(etat_machine); query.prepare("Delete from electromenager where matricule_machine=:matricule_m"); query.bindValue(":matricule_m", matricule_machine); return query.exec(); } bool electromenager::modifier_machine() { QSqlQuery query; QString matricule_machine_string= QString::number(matricule_machine); QString etat_machine_string= QString::number(etat_machine); query.prepare("UPDATE ELECTROMENAGER SET type_machine=:type, etat_machine=:etat, emplacement_machine=:emplacement WHERE matricule_machine=:matricule_m"); query.bindValue(":matricule_m",matricule_machine); query.bindValue(":type",type_machine); query.bindValue(":etat",etat_machine); query.bindValue(":emplacement",emplacement_machine); return query.exec(); } QSqlQueryModel * electromenager::trier_etatM() { QSqlQueryModel * model=new QSqlQueryModel(); model->setQuery("SELECT * FROM ELECTROMENAGER ORDER BY etat_machine"); model->setHeaderData(0,Qt::Horizontal,QObject::tr("Matricule")); model->setHeaderData(1,Qt::Horizontal,QObject::tr("Type")); model->setHeaderData(2,Qt::Horizontal,QObject::tr("Etat")); model->setHeaderData(3,Qt::Horizontal,QObject::tr("Emplacement")); return model; } QSqlQueryModel * electromenager::trier_emplacementM() { QSqlQueryModel * model=new QSqlQueryModel(); model->setQuery("SELECT * FROM ELECTROMENAGER ORDER BY emplacement_machine"); model->setHeaderData(0,Qt::Horizontal,QObject::tr("Matricule")); model->setHeaderData(1,Qt::Horizontal,QObject::tr("Type")); model->setHeaderData(2,Qt::Horizontal,QObject::tr("Etat")); model->setHeaderData(3,Qt::Horizontal,QObject::tr("Emplacement")); return model; } QSqlQueryModel * electromenager::trier_typeM() { QSqlQueryModel * model=new QSqlQueryModel(); model->setQuery("SELECT * FROM ELECTROMENAGER ORDER BY type_machine"); model->setHeaderData(0,Qt::Horizontal,QObject::tr("Matricule")); model->setHeaderData(1,Qt::Horizontal,QObject::tr("Type")); model->setHeaderData(2,Qt::Horizontal,QObject::tr("Etat")); model->setHeaderData(3,Qt::Horizontal,QObject::tr("Emplacement")); return model; } QSqlQueryModel * electromenager::rechercher_machine(const QString &b) { QSqlQueryModel * model = new QSqlQueryModel(); model->setQuery("SELECT TYPE_MACHINE, ETAT_MACHINE, EMPLACEMENT_MACHINE FROM ELECTROMENAGER WHERE (type_machine || etat_machine || emplacement_machine) LIKE '%"+b+"%'"); model->setHeaderData(0,Qt::Horizontal,QObject::tr("Matricule")); model->setHeaderData(1,Qt::Horizontal,QObject::tr("Type")); model->setHeaderData(2,Qt::Horizontal,QObject::tr("Etat")); model->setHeaderData(3,Qt::Horizontal,QObject::tr("Emplacement")); return model; }
true
c452f9c0b6a6cfe0a9f3432695a7f9fece8bc421
C++
piratjocke/Project-Flight-School
/ProjectFlightSchool/ProjectFlightSchool/Game.cpp
UTF-8
3,475
2.796875
3
[]
no_license
#include "Game.h" /////////////////////////////////////////////////////////////////////////////// // PRIVATE /////////////////////////////////////////////////////////////////////////////// void Game::ServerInit( std::string port ) { if( !mServerIsActive ) { mServer = new Server(); if ( mServer->Initialize( port ) && mServer->Connect() ) { mServerThread = std::thread( &Server::Run, mServer ); mServerIsActive = true; } else { IEventPtr E1( new Event_Connection_Failed( "EVENT: Unable to start server." ) ); EventManager::GetInstance()->QueueEvent( E1 ); mServer->Release(); SAFE_DELETE( mServer ); } } ClientInit( "localhost", port ); } void Game::ClientInit( std::string ip, std::string port ) { mClient = new Client(); if ( mClient->Initialize( ip, port ) && mClient->Connect() ) { IEventPtr E1( new Event_Change_State( PLAY_STATE ) ); EventManager::GetInstance()->QueueEvent( E1 ); mClientThread = std::thread( &Client::Run, mClient ); } else if( mServerIsActive ) { IEventPtr E1( new Event_Connection_Failed( "EVENT: Unable to start client even though server is running." ) ); EventManager::GetInstance()->QueueEvent( E1 ); mServer->Release(); SAFE_DELETE( mServer ); mServerThread.join(); mServerIsActive = false; mClient->Release(); SAFE_DELETE( mClient ); } else { IEventPtr E1( new Event_Connection_Failed( "EVENT: Unable to start client." ) ); EventManager::GetInstance()->QueueEvent( E1 ); mClient->Release(); SAFE_DELETE( mClient ); if( mClientThread.joinable() ) mClientThread.join(); } } void Game::EventListener( IEventPtr newEvent ) { if( newEvent->GetEventType() == Event_Start_Server::GUID ) { std::shared_ptr<Event_Start_Server> data = std::static_pointer_cast<Event_Start_Server>( newEvent ); std::string s_port = data->Port(); ServerInit( s_port ); } else if( newEvent->GetEventType() == Event_Start_Client::GUID ) { std::shared_ptr<Event_Start_Client> data = std::static_pointer_cast<Event_Start_Client>( newEvent ); std::string s_ip = data->IP(); std::string s_port = data->Port(); ClientInit( s_ip, s_port ); } } /////////////////////////////////////////////////////////////////////////////// // PUBLIC /////////////////////////////////////////////////////////////////////////////// HRESULT Game::Update( float deltaTime ) { mStateMachine->Update( deltaTime ); EventManager::GetInstance()->Update(); RenderManager::GetInstance()->Update( deltaTime ); return S_OK; } HRESULT Game::Render() { mStateMachine->Render(); return S_OK; } HRESULT Game::Initialize() { mStateMachine = new StateMachine(); mStateMachine->Initialize(); EventManager::GetInstance()->AddListener( &Game::EventListener, this, Event_Start_Server::GUID ); EventManager::GetInstance()->AddListener( &Game::EventListener, this, Event_Start_Client::GUID ); mServerIsActive = false; return S_OK; } void Game::Release() { EventManager::GetInstance()->Release(); mClient->Release(); SAFE_DELETE( mClient ); if ( mServerIsActive ) mServer->Release(); SAFE_DELETE( mServer ); if ( mClientThread.joinable() ) { mClientThread.join(); } if ( mServerThread.joinable() ) { mServerThread.join(); } mStateMachine->Release(); SAFE_DELETE( mStateMachine ); } Game::Game() { mStateMachine = nullptr; mClientThread = std::thread(); mServerThread = std::thread(); mClient = nullptr; mServer = nullptr; } Game::~Game() { }
true
1dcc2627e92db955ed4e8d3573b3b79e2f751382
C++
themathgeek13/OpenGLPractice
/checkpoints/4_blending.cpp
UTF-8
1,475
2.84375
3
[]
no_license
// // Created by rohan on 8/15/20. // #include <string> #include <sstream> #include <functional> #include <iostream> #include <GLFW/glfw3.h> #include <glm/vec3.hpp> #include <glm/matrix.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "GraphicsManager.hpp" #include "Mesh.hpp" void draw_box() { glBegin(GL_TRIANGLES); glVertex3f(-0.5f, -0.5f, 0); glVertex3f(-0.5f, 0.5f, 0); glVertex3f(0.5f, -0.5f, 0); glVertex3f(-0.5f, 0.5f, 0); glVertex3f(0.5f, 0.5f, 0); glVertex3f(0.5f, -0.5f, 0); glEnd(); } void render(double current_time, GraphicsManager *gm) { /** Drawing Code Goes Here! **/ /** 4. Blend modes **/ glEnable(GL_BLEND); // Alpha blending (more on this in later lectures!) // Final color evaluates to [s.rgb * s.a + d.rgb * (1 - s.a)] glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPushMatrix(); glScalef(0.5f, 0.5f, 0.5f); glPushMatrix(); glColor4f(1.0f, 0, 0, 0.5f); glTranslatef(-0.1f, -0.1f, 0); draw_box(); glPopMatrix(); glColor4f(0, 0, 1.0f, 0.5f); glTranslatef(0.1f, 0.1f, 0); draw_box(); glPopMatrix(); glDisable(GL_BLEND); } int main(int argc, char** argv) { std::string title = "OpenGL Tutorial"; std::function<void(double, GraphicsManager*)> pass = &render; GraphicsManager *gm = new GraphicsManager(title, pass); gm->set_gl_version(2, 1); gm->execute(); return 0; }
true
469a7f5cf3ed33f3f1da449c50066caf5619518a
C++
zzcym/NEUQ-ACM-Solution
/week2/李轩屹/7-3 归并排序.cpp
UTF-8
785
2.65625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; const int maxn=1e5+10; void merge(int *a,int l,int r){ if(l==r) return; else if(l==r-1){ int temp; if(a[l]>a[r]) temp=a[l],a[l]=a[r],a[r]=temp; return ; } else{ int mid=(l+r)/2; merge(a,l,mid); merge(a,mid+1,r); int p=l,q=mid+1,b[maxn]; for(int i=l;i<=r;i++) b[i]=a[i]; for(int i=l;i<=r;i++){ if(p>mid){ b[i]=a[q]; q++; } else if(q>r){ b[i]=a[p]; p++; } else if(a[p]>a[q]){ b[i]=a[q]; q++; } else{ b[i]=a[p]; p++; } } for(int i=l;i<=r;i++) a[i]=b[i]; } } int main(){ int n,a[maxn]; cin>>n; for(int i=0;i<n;i++) cin>>a[i]; merge(a,0,n-1); for(int i=0;i<n;i++) cout<<a[i]<<" "; return 0; }
true
f2dbd8f0357a87be20a0e730cf552485ce8132b8
C++
RMoraffah/hippo-postgresql
/src/include/izenelib/include/util/driver/Request.h
UTF-8
2,622
2.6875
3
[ "Apache-2.0", "PostgreSQL" ]
permissive
#ifndef IZENELIB_DRIVER_REQUEST_H #define IZENELIB_DRIVER_REQUEST_H /** * @file izenelib/driver/Request.h * @author Ian Yang * @date Created <2010-06-10 14:37:01> */ #include "Value.h" #include "RestrictedObjectValue.h" #include "Keys.h" #include <string> namespace izenelib { namespace driver { class Request : public RestrictedObjectValue { public: static const std::string kDefaultAction; enum kCallType { FromAPI = 0, FromDistribute, FromOtherShard, FromPrimaryWorker, FromLog, }; Request(); Request(const Request& other); Request& operator=(const Request& other); Value& header() { return *header_; } const Value& header() const { return *header_; } void swap(Request& other) { using std::swap; RestrictedObjectValue::swap(other); swap(controller_, other.controller_); swap(action_, other.action_); swap(aclTokens_, other.aclTokens_); swap(calltype_, other.calltype_); updateHeaderPtr(); other.updateHeaderPtr(); } void assignTmp(Value& value) { RestrictedObjectValue::assignTmp(value); updateHeaderPtr(); parseHeader(); } /// @brief Parse header controller, action and acl tokens. void parseHeader(); /// @brief Table field in header. /// /// It is not automatically updated. It is parsed when call assignTmp() or /// parseHeader(). const Value::StringType& controller() const { return controller_; } /// @brief Action field in header. /// /// It is not automatically updated. It is parsed when call assignTmp() or /// parseHeader(). const Value::StringType& action() const { return action_; } /// @brief comma separated user tokens /// It is not automatically updated. It is parsed when call assignTmp() or /// parseHeader(). const Value::StringType& aclTokens() const { return aclTokens_; } void setCallType(kCallType calltype) { calltype_ = calltype; } kCallType callType() const { return calltype_; } private: void updateHeaderPtr() { header_ = &((*this)[Keys::header]); } /// @brief shortcuts to header object value Value* header_; Value::StringType controller_; Value::StringType action_; Value::StringType aclTokens_; kCallType calltype_; }; inline void swap(Request& a, Request& b) { a.swap(b); } }} // namespace izenelib::driver #endif // IZENELIB_DRIVER_REQUEST_H
true
4096df244383ba57b0845e3154e87854f77da647
C++
sandeepshiven/cpp-practice
/Tree/Binary Tree/Count Nodes in a Complete Binary Tree/myBetter.cpp
UTF-8
1,332
3.3125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; #define null NULL class Node{ public: int key; Node *left; Node *right; Node(int k){ key = k; left = right = null; } }; int isComplete(Node *root){ if(root == null){ return 0; } int lh = isComplete(root->left)+1; int rh = isComplete(root->right)+1; if(lh == rh){ return lh; } else{ return INT_MIN; } } int countNodes(Node *root){ if(root == null){ return 0; } int isCompleteCount = isComplete(root); if(isCompleteCount != INT_MIN){ return pow(2, isCompleteCount)-1; } else{ return (countNodes(root->left)+countNodes(root->right)+1); } } int main(){ Node *root = new Node(10); root->left = new Node(20); root->left->left = new Node(40); root->left->left->left = new Node(80); root->left->left->right = new Node(90); root->left->right = new Node(50); root->left->right->left = new Node(100); root->right = new Node(30); root->right->right = new Node(70); root->right->left = new Node(60); // root->right->right = new Node(7); // root->right->right->left = new Node(6); cout << countNodes(root); cout <<'\n'; return 0; }
true
2fa3ba3aa952d06b4a43dce85c5c8162fa166c75
C++
alexthorne90/msc_robot_arm
/src/ldc1614.h
UTF-8
2,746
2.796875
3
[ "MIT" ]
permissive
/** * @file ldc1614.h * @author Alex Thorne * @version 1.0 */ #ifndef LDC1614_H #define LDC1614_H #include <Arduino.h> #include <Wire.h> class Ldc1614 { public: Ldc1614(); //Functionality void AttachComms(void); uint8_t WriteReg(uint8_t reg, uint16_t value); uint16_t ReadReg(uint8_t reg); bool TestConnection(void); //LDC1614 register addresses // Data const uint8_t DATA_MSB_CH0 = 0x00; const uint8_t DATA_LSB_CH0 = 0x01; const uint8_t DATA_MSB_CH1 = 0x02; const uint8_t DATA_LSB_CH1 = 0x03; const uint8_t DATA_MSB_CH2 = 0x04; const uint8_t DATA_LSB_CH2 = 0x05; const uint8_t DATA_MSB_CH3 = 0x06; const uint8_t DATA_LSB_CH3 = 0x07; // Reference count const uint8_t RCOUNT_CH0 = 0x08; const uint8_t RCOUNT_CH1 = 0x09; const uint8_t RCOUNT_CH2 = 0x0A; const uint8_t RCOUNT_CH3 = 0x0B; // Offset value const uint8_t OFFSET_CH0 = 0x0C; const uint8_t OFFSET_CH1 = 0x0D; const uint8_t OFFSET_CH2 = 0x0E; const uint8_t OFFSET_CH3 = 0x0F; // Settling referece count const uint8_t SETTLECOUNT_CH0 = 0x10; const uint8_t SETTLECOUNT_CH1 = 0x11; const uint8_t SETTLECOUNT_CH2 = 0x12; const uint8_t SETTLECOUNT_CH3 = 0x13; // Reference and sensor divider settings const uint8_t CLK_DIVIDERS_CH0 = 0x14; const uint8_t CLK_DIVIDERS_CH1 = 0x15; const uint8_t CLK_DIVIDERS_CH2 = 0x16; const uint8_t CLK_DIVIDERS_CH3 = 0x17; // Device status report const uint8_t STATUS_REG = 0x18; // Error reporting config const uint8_t ERROR_CONFIG = 0x19; // Conversion config const uint8_t CONFIG_REG = 0x1A; // Channel multiplexing config const uint8_t MUX_CONFIG_REG = 0x1B; // Reset device const uint8_t RESET_DEV_REG = 0x1C; // Sensor current drive configuration const uint8_t DRIVE_CURRENT_CH0 = 0x1E; const uint8_t DRIVE_CURRENT_CH1 = 0x1F; const uint8_t DRIVE_CURRENT_CH2 = 0x20; const uint8_t DRIVE_CURRENT_CH3 = 0x21; // Sensor current drive configuration const uint8_t MANUFACT_ID_REG = 0x7E; const uint8_t DEVICE_ID_REG = 0x7F; private: //LDC1614 bus address const uint8_t LDC_BUS_ADDR = 0x2A; //LDC1614 IDs const uint16_t LDC1614_MANUFACT_ID = 0x5449; const uint16_t LDC1614_DEVICE_ID = 0x3055; }; #endif
true
d132b9727401389cf5aa825a284fd05d34b3a951
C++
TristinL/C-plus-plus
/double_int_function.cpp
UTF-8
243
3.453125
3
[]
no_license
// Double integer function #include<iostream> int doublenumber (int); int main(){ int x; std::cout<<"Enter a number: "; std::cin>>x; doublenumber(x); } int doublenumber(int a){ a = a*2; std::cout<<a<<std::endl; }
true
1550c112286bed54dfb3b7f7a86f213ba146475a
C++
khaled3ttia/openmp-accessors
/examples/vec_add_base.cpp
UTF-8
798
2.796875
3
[ "MIT" ]
permissive
#include <random> #include <iostream> #include <omp.h> #include "utils.h" constexpr int NROWS = 1; constexpr int NCOLS = 10; int main(){ int* a = new int[NROWS * NCOLS]; int* b = new int[NROWS * NCOLS]; int* c = new int[NROWS * NCOLS]; generateIntMatrix(NROWS, NCOLS, 0.7, a); std::cout << "A: " ; printVector(a, 0, NROWS*NCOLS); generateIntMatrix(NROWS, NCOLS, 0.2, b); std::cout << "B: " ; printVector(b, 0, NROWS*NCOLS); #pragma omp target teams distribute parallel for map (to:a[0:NROWS*NCOLS], b[0:NROWS*NCOLS]) map(from:c[0:NROWS*NCOLS]) for (int i = 0; i < NROWS * NCOLS; i++){ c[i] = a[i] + b[i]; } std::cout << "C: " ; printVector(c, 0, NROWS*NCOLS); delete [] a; delete [] b; delete [] c; }
true
45b5e87ae6b09784d6d17c1f4120135b8b69151b
C++
pfaltynek/advent-of-code-2017-cpp
/day12/main.cpp
UTF-8
3,290
2.734375
3
[]
no_license
#include <fstream> #include <iostream> #include <map> #include <regex> #include <vector> #define TEST 0 std::regex line_template("^(\\d+) <-> (\\d+)(, \\d+)*$"); std::regex parts_template("^(\\d+) <-> (.+)$"); std::vector<int> Split(std::string to_split, const std::string &delimiter) { std::vector<int> result; size_t pos; result.clear(); pos = to_split.find(delimiter, 0); while (pos != std::string::npos) { if (pos) { result.push_back(stoi(to_split.substr(0, pos))); } to_split = to_split.substr(pos + delimiter.size(), std::string::npos); pos = to_split.find(delimiter, 0); } if (to_split.size()) { result.push_back(stoi(to_split)); } return result; } bool ParseLine(std::string line, std::map<int, std::vector<int>> &programs) { std::smatch sm; int prog; if (!regex_match(line, sm, line_template)) { return false; } else { regex_match(line, sm, parts_template); } prog = stoi(sm.str(1)); programs[prog] = Split(sm.str(2), ", "); return true; } int GetProgGroupSize(int prg_grp_id, std::map<int, std::vector<int>> progs) { std::vector<int> group, queue; int id; group.clear(); queue.clear(); queue.push_back(prg_grp_id); while (queue.size()) { id = queue.back(); queue.pop_back(); if (std::find(group.begin(), group.end(), id) == group.end()) { group.push_back(id); for (unsigned int i = 0; i < progs[id].size(); i++) { queue.push_back(progs[id][i]); } } } return group.size(); } int GetProgGroupsCount(std::map<int, std::vector<int>> progs) { std::vector<int> queue, prg_list, groups; std::vector<int>::iterator itv; int id; prg_list.clear(); groups.clear(); for (auto it = progs.begin(); it != progs.end(); it++) { prg_list.push_back(it->first); } queue.clear(); while (prg_list.size()) { queue.push_back(prg_list[0]); groups.push_back(prg_list[0]); prg_list.erase(prg_list.begin()); while (queue.size()) { id = queue.back(); queue.pop_back(); itv = std::find(prg_list.begin(), prg_list.end(), id); if (itv != prg_list.end()) { prg_list.erase(itv); } for (unsigned int i = 0; i < progs[id].size(); i++) { if (std::find(prg_list.begin(), prg_list.end(), progs[id][i]) != prg_list.end()) { if (std::find(queue.begin(), queue.end(), progs[id][i]) == queue.end()) { queue.push_back(progs[id][i]); } } } } } return groups.size(); } int main(void) { int result1 = 0, result2 = 0, cnt = 0; std::ifstream input; std::string line; std::map<int, std::vector<int>> programs; std::cout << "=== Advent of Code 2017 - day 12 ====" << std::endl; std::cout << "--- part 1 ---" << std::endl; #if TEST input.open("input-test.txt", std::ifstream::in); #else input.open("input.txt", std::ifstream::in); #endif if (input.fail()) { std::cout << "Error opening input file.\n"; return -1; } while (std::getline(input, line)) { cnt++; if (!ParseLine(line, programs)) { std::cout << "Invalid program info on line " << cnt << std::endl; } } if (input.is_open()) { input.close(); } result1 = GetProgGroupSize(0, programs); result2 = GetProgGroupsCount(programs); std::cout << "Result is " << result1 << std::endl; std::cout << "--- part 2 ---" << std::endl; std::cout << "Result is " << result2 << std::endl; }
true
88b738ac411d19eef51e74b2f611b326a9b64852
C++
alex-torregrosa/TheGame
/newDijkstra.cc
UTF-8
1,603
2.53125
3
[]
no_license
#include "Player.hh" // Search comparisons enum cmpSearch { CMP_CITY, CMP_ENEMY }; pair<Dir, Dir> dijkstra(const Pos& pos, cmpSearch ct, const Unit& u) { intMat prices(rows(), intV(cols(), -1)); posMat parents(rows(), posV(cols())); boolMat visited(rows(), boolV(cols(), false)); PosPQ pq; pq.push(dPos(pos, 0)); Pos p = pos; while (not found and not pq.empty()) { p = pq.top().p; pq.pop(); if (not visited[p.i][p.j]) { if (p != pos and hasBeefyEnemy(c, u)) visited[p.i][p.j] = true; else if (cmp_search(ct, c, u)) found = true; else { visited[p.i][p.j] = true; posV res; veins(p, res, u); for (Pos v : res) { int c = 1 + 8 * cost(cell(v.i, v.j).type); if (prices[v.i][v.j] == -1 or prices[v.i][v.j] > prices[p.i][p.j] + c) { prices[v.i][v.j] = prices[p.i][p.j] + c; parents[v.i][v.j] = p; pq.push(dPos(v, prices[v.i][v.j])); } } } } } // Not found if (p == pos) return make_pair(Dir(NONE), Dir(NONE)); Pos lastp = p; pair<Dir, Dir> dp; // Calculate the first 2 positions while (parents[p.i][p.j] != pos) { lastp = p; p = parents[p.i][p.j]; } // First direction for (int d = 0; d != DIR_SIZE; ++d) { if (pos + Dir(d) == p) { dp.first = Dir(d); break; // Aaaargh!!!!!! (TODO: pensar algo mejor) } } // Second dir for (int d = 0; d != DIR_SIZE; ++d) { if (p + Dir(d) == lastp) { dp.second = Dir(d); return dp; } } _unreachable(); }
true
3b94613a964b18d688200059388d6d9eb81294ad
C++
iAmtheSystem/hopfenlicht
/Fade/Fade.ino
UTF-8
4,360
3.234375
3
[]
no_license
const int LED1 = 11; const int LED2 = 10; const int LED3 = 9; const int LED4 = 6; const int SPEEDFAKTOR = 1; // Setting up the system void setup() { pinMode(LED1, OUTPUT); pinMode(LED2, OUTPUT); pinMode(LED3, OUTPUT); pinMode(LED4, OUTPUT); Serial.begin(9600); // to communicate with the PC } void allLights(int value){ analogWrite(LED1, value); analogWrite(LED2, value); analogWrite(LED3, value); analogWrite(LED4, value); } void fadeAll(int led1, int led2, int led3, int led4, int fadeInTime, int durationOn, int fadeOutTime, int durationOff){ // Speeed durationOn = durationOn/SPEEDFAKTOR; durationOff = durationOff/SPEEDFAKTOR; fadeInTime = fadeInTime/SPEEDFAKTOR; fadeOutTime = fadeOutTime/SPEEDFAKTOR; // printing Serial.print("\n*** Starting a fade ***\n"); Serial.print("durationOn = "); Serial.print(durationOn); Serial.print("\tdurationOff = "); Serial.print(durationOff); Serial.print("\tfadeInTime = "); Serial.print(fadeInTime); Serial.print("\tfadeOutTime = "); Serial.print(fadeOutTime); Serial.print("\n"); // start condition analogWrite(led1, 0); analogWrite(led2, 0); analogWrite(led3, 0); analogWrite(led4, 0); // fading on int fadeValue = 0; int fadeStep = 5; int timeUntilNextFadeStep = (int) fadeInTime*fadeStep/255; Serial.print("Fading all "); Serial.print(timeUntilNextFadeStep); Serial.print(" ms up\n"); while(fadeValue <= 255){ delay(timeUntilNextFadeStep); analogWrite(led1, fadeValue); analogWrite(led2, fadeValue); analogWrite(led3, fadeValue); analogWrite(led4, fadeValue); fadeValue += fadeStep; } // all lights are on analogWrite(led1, 255); analogWrite(led2, 255); analogWrite(led3, 255); analogWrite(led4, 255); delay(durationOn); // fading off // fading on fadeValue = 255; timeUntilNextFadeStep = (int) fadeOutTime*fadeStep/255; Serial.print("Fading all "); Serial.print(timeUntilNextFadeStep); Serial.print(" ms down\n"); while(fadeValue >= 0){ delay(timeUntilNextFadeStep); analogWrite(led1, fadeValue); analogWrite(led2, fadeValue); analogWrite(led3, fadeValue); analogWrite(led4, fadeValue); fadeValue -= fadeStep; } allLights(0); delay(durationOff); } void trickledownandupFade(){ Serial.write("Lets do a trickledownandupFade!\n"); fadeAll(LED1,LED1,LED1,LED1,2000,3000,2000,500); fadeAll(LED2,LED2,LED2,LED2,2000,3000,2000,500); fadeAll(LED3,LED3,LED3,LED3,2000,3000,2000,500); fadeAll(LED4,LED4,LED4,LED4,2000,3000,2000,500); fadeAll(LED3,LED3,LED3,LED3,2000,3000,2000,500); fadeAll(LED2,LED2,LED2,LED2,2000,3000,2000,500); } // the loop routine runs over and over again forever: // so gehts: fadeAll(int led1, int led2, int led3, int led4, int fadeInTime, int durationOn, int fadeOutTime, int durationOff) void loop() { fadeAll(LED1,LED1,LED1,LED1,3000,2000,4000,500); fadeAll(LED1,LED2,LED3,LED3,3000,2000,4000,500); } // Beispiel void trickledownandupSimple(){ Serial.write("Lets do a trickledownandupSimple!\n"); blinkAll(LED1,LED1,LED1,LED1,3000,500,1); blinkAll(LED2,LED2,LED2,LED2,3000,500,1); blinkAll(LED3,LED3,LED3,LED3,3000,500,1); blinkAll(LED4,LED4,LED4,LED4,3000,500,1); blinkAll(LED3,LED3,LED3,LED3,3000,500,1); blinkAll(LED2,LED2,LED2,LED2,3000,500,1); } void crossoverSimple(){ Serial.write("Lets do a crossoverSimple!\n"); blinkAll(LED1,LED1,LED3,LED3,3000,500,1); blinkAll(LED2,LED2,LED4,LED4,3000,500,1); blinkAll(LED1,LED1,LED3,LED3,3000,500,1); blinkAll(LED2,LED2,LED4,LED4,3000,500,1); } void hopscotchSimple(){ Serial.write("Lets do a hopscotchSimple!\n"); blinkAll(LED1,LED1,LED4,LED4,3000,500,1); blinkAll(LED2,LED2,LED3,LED3,3000,500,1); blinkAll(LED1,LED1,LED4,LED4,3000,500,1); blinkAll(LED2,LED2,LED3,LED3,3000,500,1); } // the loop function runs over and over again forever void loop() { Serial.write("Hello master Carina! Lets looooop!\n"); trickledownandupSimple(); trickledownandupSimple(); trickledownandupSimple(); trickledownandupSimple(); blinkAll(LED1,LED1,LED1,LED1,3000,500,1); blinkAll(LED1,LED2,LED3,LED4,5000,500,5); crossoverSimple(); crossoverSimple(); blinkAll(LED1,LED2,LED3,LED4,5000,500,5); hopscotchSimple(); hopscotchSimple(); blinkAll(LED1,LED2,LED3,LED4,5000,500,5); }
true
f5cec1d2b51cd56a8b90d515f81481a0e52fe484
C++
PetricaP/Renderel
/include/Transform.hpp
UTF-8
1,278
2.796875
3
[ "MIT" ]
permissive
#ifndef TRANSFORM_HPP #define TRANSFORM_HPP #include "math/Mat4.hpp" #include "math/Quaternion.hpp" #include "math/Vec3.hpp" namespace renderel { template <typename T = float> class Transform { private: math::Vec3<T> m_Position; math::Quaternion<T> m_Rotation; math::Vec3<T> m_Scale; public: Transform(const math::Vec3<T> &position = math::Vec3<T>(), const math::Quaternion<T> &rotation = math::Quaternion<T>(), const math::Vec3<T> &scale = math::Vec3<T>(1.0f)) : m_Position(position), m_Rotation(rotation), m_Scale(scale) {} math::Mat4<T> GetModel() const { math::Mat4<T> positionMatrix = math::Mat4<T>::Translation(m_Position); math::Mat4<T> scaleMatrix = math::Mat4<T>::Scale(m_Scale); math::Mat4<T> rotationMatrix = m_Rotation.ToRotationMatrix(); return positionMatrix * rotationMatrix * scaleMatrix; } math::Vec3<T> &GetPosition() { return m_Position; } math::Quaternion<T> &GetRotation() { return m_Rotation; } math::Vec3<T> &GetScale() { return m_Scale; } void SetPosition(const math::Vec3<T> position) { m_Position = position; } void SetRotation(const math::Quaternion<T> rotation) { m_Rotation = rotation; } void SetScale(const math::Vec3<T> scale) { m_Scale = scale; } }; } // namespace renderel #endif // TRANSFORM_HPP
true
35d3096fdce4c3ae2b9af228f10d5b36c7b7b17d
C++
SergiuPalc/IEPPROJ
/Server/outputpin.cpp
UTF-8
703
2.640625
3
[]
no_license
#include "outputpin.h" #include "bcm2835.h" #include "Pin.h" OutputPin::~OutputPin(void) { } void OutputPin::settoPin(uint8_t level) { if (level) bcm2835_gpio_set(level); else bcm2835_gpio_clr(level); } OutputPin::OutputPin(int id, int direction) :Pin(id, direction) { //set pin as output in register. we made this every time when a new output object is created volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPFSEL0 / 4 + (id / 10); uint8_t shift = (id % 10) * 3; uint32_t mask = BCM2835_GPIO_FSEL_MASK << shift; uint32_t value = BCM2835_GPIO_FSEL_INPT << shift; bcm2835_peri_set_bits(paddr, value, mask); } int OutputPin::getDirection() { return direction; }
true
195753e566c6ec6457676d89dd79d3e952d0d29f
C++
dvpashnev/RestaurantWinAPI
/RestaurantWinAPI_1_2/Dish.cpp
UTF-8
5,735
3
3
[]
no_license
#include"header.h" Dish::Dish(const wstring& title /*= "N/A"*/, double price /*= 0.0*/, int portion /*= 0*/, TypeDish type /*= COLD*/, TimeDay tDD /*= MORNING*/, const wstring& description /*= "N/A"*/, const wstring& picPath /*= "N/A"*/, int num /*= 1*/) : title_(title), price_(price), portion_(portion), type_(type), timeDay_(tDD), description_(description), picPath_(picPath), number_(num) {} Dish::Dish(const Dish& obj) : title_(obj.title_), price_(obj.price_), portion_(obj.portion_), type_(obj.type_), timeDay_(obj.timeDay_), description_(obj.description_), picPath_(obj.picPath_), number_(obj.number_) {} Dish::~Dish() {} void Dish::setTitle(const wstring& title) { title_ = title; } void Dish::setPrice(double price) { price_ = price; } void Dish::setPortion(int portion) { portion_ = portion; } void Dish::setType(TypeDish type) { type_ = type; } void Dish::setTime(TimeDay tDD) { timeDay_ = tDD; } void Dish::setDescription(const wstring& description) { description_ = description; } void Dish::setPicPath(const wstring& picPath) { picPath_ = picPath; } void Dish::setNumber(int num) { number_ = num; } void Dish::setDish(const wstring& title, double price, int portion, TypeDish type, TimeDay tDD, const wstring& description, const wstring& picPath, int num) { title_ = title; price_ = price; portion_ = portion; type_ = type; timeDay_ = tDD; description_ = description; picPath_ = picPath; number_ = num; } wstring Dish::getTitle() const { return title_; } double Dish::getPrice() const { return price_; } int Dish::getPortion() const { return portion_; } wstring Dish::getPriceStr() const { TCHAR buf[10]; swprintf_s(buf, 10, L"%.2lf", price_); return buf; } wstring Dish::getPortionStr() const { TCHAR buf[10]; wsprintf(buf, L"%d", portion_); return buf; } TypeDish Dish::getType() const { return type_; } TimeDay Dish::getTime() const { return timeDay_; } wstring Dish::getTypeStr() const { wstring str; switch (type_) { case COLD : str = TEXT("Холодное блюдо"); break; case HOT: str = TEXT("Горячее блюдо"); break; case DESERT: str = TEXT("Десерт"); break; } return str; } wstring Dish::getTimeStr() const { wstring str; switch (timeDay_) { case ALL: str = TEXT("Любое время"); break; case MORNING: str = TEXT("Утро"); break; case AFTERNOON: str = TEXT("День"); break; case EVENING: str = TEXT("Вечер"); break; } return str; } wstring Dish::getDescription() const { return description_; } wstring Dish::getPicPath() const { return picPath_; } int Dish::getNumber() const { return number_; } wstring Dish::getNumberStr() const { TCHAR buf[10]; wsprintf(buf, L"%d", number_); return buf; } wstring Dish::getTotalsStr() const { TCHAR buf[10]; swprintf_s(buf, 10, L"%.2lf", (double)number_*price_); return buf; } wostream& operator<<(wostream& os, const Dish& obj) { os.imbue(locale("rus_rus.866")); os << obj.title_ << endl; os << obj.price_ << endl; os << obj.portion_ << endl; os << (int)obj.type_ << endl; os << (int)obj.timeDay_ << endl; os << obj.description_ << endl; os << obj.picPath_ << endl; os << obj.number_ << endl; return os; } wistream& operator>>(wistream& is, Dish& obj) { is.imbue(locale("rus_rus.866")); getline(is, obj.title_); is >> obj.price_; is >> obj.portion_; int pro; is >> pro; obj.type_ = (TypeDish)pro; (is >> pro).get(); obj.timeDay_ = (TimeDay)pro; getline(is, obj.description_); getline(is, obj.picPath_); (is >> obj.number_).get(); return is; } bool Dish::operator==(const Dish& obj) { return (title_ == obj.title_ && price_ == obj.price_ && portion_ == obj.portion_ && type_ == obj.type_ && timeDay_ == obj.timeDay_ && description_ == obj.description_ && picPath_ == obj.picPath_ && number_ == obj.number_); } Dish& Dish::operator=(const Dish& obj) { if (this == &obj) return *this; title_ = obj.title_; price_ = obj.price_; portion_ = obj.portion_; type_ = obj.type_; timeDay_ = obj.timeDay_; description_ = obj.description_; picPath_ = obj.picPath_; number_ = obj.number_; return *this; } bool operator<(const Dish& el1, const Dish& el2) {//Для сравнения при сортировке по алфавиту int length = WideCharToMultiByte(CP_ACP, 0, el1.title_.c_str(), -1, NULL, 0, 0, 0); char *ptr = new char[length]; WideCharToMultiByte(CP_ACP, 0, el1.title_.c_str(), -1, ptr, length, 0, 0); string sMb1 = ptr; delete ptr; length = WideCharToMultiByte(CP_ACP, 0, el2.title_.c_str(), -1, NULL, 0, 0, 0); ptr = new char[length]; WideCharToMultiByte(CP_ACP, 0, el2.title_.c_str(), -1, ptr, length, 0, 0); string sMb2 = ptr; delete ptr; transform(sMb1.begin(), sMb1.end(), sMb1.begin(), tolower); //независимо transform(sMb2.begin(), sMb2.end(), sMb2.begin(), tolower); //от регистра return (sMb1 < sMb2); //больше по алфавиту. } bool operator>(const Dish& el1, const Dish& el2) {//В обратном порядке алфавита int length = WideCharToMultiByte(CP_ACP, 0, el1.title_.c_str(), -1, NULL, 0, 0, 0); char *ptr = new char[length]; WideCharToMultiByte(CP_ACP, 0, el1.title_.c_str(), -1, ptr, length, 0, 0); string sMb1 = ptr; delete ptr; length = WideCharToMultiByte(CP_ACP, 0, el2.title_.c_str(), -1, NULL, 0, 0, 0); ptr = new char[length]; WideCharToMultiByte(CP_ACP, 0, el2.title_.c_str(), -1, ptr, length, 0, 0); string sMb2 = ptr; delete ptr; transform(sMb1.begin(), sMb1.end(), sMb1.begin(), tolower); transform(sMb2.begin(), sMb2.end(), sMb2.begin(), tolower); return (sMb1 > sMb2); }
true
60cfea530cd3336322e4ce7cc1db053b14264bbb
C++
MikePopoloski/slang
/include/slang/util/Iterator.h
UTF-8
16,941
3.15625
3
[ "MIT" ]
permissive
//------------------------------------------------------------------------------ //! @file Iterator.h //! @brief Helper classes for working with iterators // // SPDX-FileCopyrightText: Michael Popoloski // SPDX-License-Identifier: MIT //------------------------------------------------------------------------------ #pragma once #include <concepts> #include <iterator> #include <type_traits> namespace slang { // Implementation is based on the blog post here: // https://vector-of-bool.github.io/2020/06/13/cpp20-iter-facade.html namespace detail { template<typename T> struct arrow_proxy { T object; constexpr T* operator->() noexcept { return &object; } constexpr const T* operator->() const noexcept { return &object; } constexpr T& operator*() noexcept { return object; } constexpr const T& operator*() const noexcept { return object; } constexpr operator T*() noexcept { return &object; } constexpr operator T const*() const noexcept { return &object; } }; template<typename T> struct inferred_value_type { using type = std::remove_cvref_t<decltype(*std::declval<T&>())>; }; template<typename T> requires requires { typename T::value_type; } struct inferred_value_type<T> { using type = typename T::value_type; }; template<typename T> using inferred_value_type_t = typename inferred_value_type<T>::type; template<typename T> concept has_increment = requires(T& it) { it.increment(); }; template<typename T> concept has_nothrow_increment = requires(T& it) { { it.increment() } noexcept; }; template<typename T> concept has_decrement = requires(T& it) { it.decrement(); }; template<typename T> concept has_nothrow_decrement = requires(T& it) { { it.decrement() } noexcept; }; template<typename T, typename It = T> concept has_distance_to = requires(const It& it, const T& other) { it.distance_to(other); }; template<typename T, typename It = T> concept has_nothrow_distance_to = requires(const It& it, const T& other) { { it.distance_to(other) } noexcept; }; template<typename> struct inferred_difference_type { using type = std::ptrdiff_t; }; template<has_distance_to T> struct inferred_difference_type<T> { static const T& it; using type = decltype(it.distance_to(it)); }; template<typename T> using inferred_difference_type_t = typename inferred_difference_type<T>::type; template<typename T, typename Diff = inferred_difference_type_t<T>> concept has_advance = requires(T& it, Diff offset) { it.advance(offset); }; template<typename T, typename Diff = inferred_difference_type_t<T>> concept has_nothrow_advance = requires(T& it, Diff offset) { { it.advance(offset) } noexcept; }; template<typename T, typename It = T> concept equality_comparable = requires(const T& sentinel, const It& it) { { it.equals(sentinel) } -> std::convertible_to<bool>; }; template<typename T, typename It = T> concept nothrow_equality_comparable = requires(const T& sentinel, const It& it) { { it.equals(sentinel) } noexcept -> std::convertible_to<bool>; }; template<typename T> concept has_nothrow_dereference = requires(const T& it) { { it.dereference() } noexcept; }; template<typename T> concept lvalue_reference = std::is_lvalue_reference_v<T>; template<typename T> concept dereferences_lvalue = requires(const T& it) { { it.dereference() } -> lvalue_reference; }; // We can meet "random access" if it provides // both .advance() and .distance_to() template<typename T> concept meets_random_access = has_advance<T> && has_distance_to<T>; // We meet `bidirectional` if we are random_access, OR we have .decrement() template<typename T> concept meets_bidirectional = meets_random_access<T> || has_decrement<T>; template<typename T> concept decls_contiguous = requires { { T::contiguous_iterator } -> std::convertible_to<bool>; } && T::contiguous_iterator; template<typename Arg, typename Iter> concept difference_type_arg = std::convertible_to<Arg, inferred_difference_type_t<Iter>>; template<typename Arg, typename Iter> concept advance_type_arg = difference_type_arg<Arg, Iter> && has_advance<Iter, Arg>; template<typename T> concept incrementable = has_increment<T> || has_advance<T> || requires(T& it) { { ++it } -> std::common_reference_with<std::remove_cvref_t<T>>; }; template<typename Iter> using iterator_category_t = std::conditional_t<meets_random_access<Iter>, // We meet the requirements of random-access: std::random_access_iterator_tag, // We don't: std::conditional_t<meets_bidirectional<Iter>, // We meet requirements for bidirectional usage: std::bidirectional_iterator_tag, // We don't: std::conditional_t<equality_comparable<Iter>, // equality equality_comparable // satisfies forward iterator std::forward_iterator_tag, // Otherwise we are an input iterator: std::input_iterator_tag>>>; // contiguous_iterator is a special case of random_access and output iterator is deduced by STL template<typename T> concept satisfies_contiguous = meets_random_access<T> && decls_contiguous<T> && dereferences_lvalue<T>; template<typename Iter> using iterator_concept_t = std::conditional_t<satisfies_contiguous<Iter>, std::contiguous_iterator_tag, iterator_category_t<Iter>>; template<typename T> constexpr T& arrow_helper(T& t) noexcept { return t; } template<typename T> requires(!std::is_lvalue_reference_v<T>) constexpr arrow_proxy<std::remove_cvref_t<T>> arrow_helper(T&& t) noexcept( std::is_nothrow_move_constructible_v<std::remove_cvref_t<T>>) { return {std::move(t)}; } } // namespace detail /// @brief Iterator facade which infers iterator types and functionality /// @tparam Derived iterator subclass type which implements: <br> /// /// Input iterator (required): <br> /// * <code>reference dereference() const </code> <br> /// * <code>void increment() </code> <br> /// /// Forward: <br> /// * <code>bool equals(T|sentinel) const </code> <br> /// /// Bidirectional: <br> /// * <code>void decrement() </code> <br> /// /// Random access: <br> /// * <code>difference_type distance_to(T|sized_sentinel) const </code> /// (can replace equal) <br> /// * <code>void advance(difference_type) </code> /// (can replace increment/decrement) <br> /// /// @tparam Contiguous true if the derived iterator is contiguous, /// otherwise false (since it cannot be inferred). /// template<typename Derived, bool Contiguous = false> class iterator_facade { public: using self_type = Derived; constexpr static bool contiguous_iterator = Contiguous; private: // cannot add any type aliases as Derived is incomplete at this point, can only rely on // decltype(auto) in declarations friend Derived; [[nodiscard]] constexpr self_type& self() noexcept { return static_cast<self_type&>(*this); } [[nodiscard]] constexpr const self_type& self() const noexcept { return static_cast<const self_type&>(*this); } public: /// @brief Dereference operator /// @return decltype(Derived{}.dereference()) constexpr decltype(auto) operator*() const noexcept(detail::has_nothrow_dereference<self_type>) { return self().dereference(); } /// @brief Arrow operator /// @return Pointer or arrow proxy to the return value of /// <code>Derived::dereference() const</code> constexpr decltype(auto) operator->() const noexcept( (detail::has_nothrow_dereference<self_type>&& noexcept(detail::arrow_helper(**this)))) { if constexpr (detail::dereferences_lvalue<self_type>) { return std::addressof(**this); } else { return detail::arrow_helper(**this); } } /// @brief Equality comparison operator, the default overload which requires /// <code>Derived::equals(T) const</code> template<detail::equality_comparable<self_type> T> [[nodiscard]] constexpr bool friend operator==(const self_type& lhs, const T& rhs) noexcept( detail::nothrow_equality_comparable<T, self_type>) { return lhs.equals(rhs); } /// @brief Fallback equality comparison operator when <code>Derived::equals(T) const</code> is /// not available, but <code>Derived::distance_to(T) const</code> is. template<detail::has_distance_to<self_type> T> requires(!detail::equality_comparable<T, self_type>) [[nodiscard]] constexpr bool friend operator==(const self_type& lhs, const T& rhs) noexcept( detail::has_nothrow_distance_to<T, self_type>) { return lhs.distance_to(rhs) == 0; } /// @brief Default pre-increment operator, requires <code>Derived::increment()</code> template<typename T = self_type> requires(detail::has_increment<T>) constexpr self_type& operator++() noexcept(detail::has_nothrow_increment<self_type>) { self().increment(); return self(); } /// @brief Fallback pre-increment operator when <code>Derived::increment()</code> is not /// available, requires <code>Derived::advance(1)</code> to be valid template<typename T = self_type> requires(!detail::has_increment<T> && detail::has_advance<T, int>) constexpr self_type& operator++() noexcept(detail::has_nothrow_advance<self_type, int>) { self().advance(1); return self(); } /// @brief Post-increment operator, requires <code>Derived::increment()</code> or /// <code>Derived::advance(1)</code> template<typename T = self_type> requires(detail::has_increment<T> || detail::has_advance<T, int>) constexpr self_type operator++(int) noexcept( std::is_nothrow_copy_constructible_v<self_type>&& noexcept(++(*this))) { auto copy = self(); ++(*this); return copy; } /// @brief Default pre-decrement operator, requires <code>Derived::decrement()</code> template<typename T = self_type> requires(detail::has_decrement<T>) constexpr self_type& operator--() noexcept(detail::has_nothrow_decrement<self_type>) { self().decrement(); return self(); } /// @brief Fallback pre-decrement operator when <code>Derived::decrement()</code> is not /// available, requires <code>Derived::advance(-1)</code> to be valid template<typename T = self_type> requires(!detail::has_decrement<T> && detail::has_advance<T, int>) constexpr self_type& operator--() noexcept(detail::has_nothrow_advance<self_type, int>) { self().advance(-1); return self(); } /// @brief Post-decrement operator, requires <code>Derived::decrement()</code> or /// <code>Derived::advance(-1)</code> template<typename T = self_type> requires(detail::has_decrement<T> || detail::has_advance<T, int>) constexpr self_type operator--(int) noexcept( std::is_nothrow_copy_constructible_v<self_type>&& noexcept(--(*this))) { auto copy = self(); ++(*this); return copy; } /// @brief operator+=, requires <code>Derived::advance()</code> template<detail::advance_type_arg<self_type> D> friend constexpr self_type& operator+=(self_type& self, D offset) noexcept( detail::has_nothrow_advance<self_type, D>) { self.advance(offset); return self; } /// @brief operator+, requires <code>Derived::advance()</code> template<detail::advance_type_arg<self_type> D> [[nodiscard]] friend constexpr self_type operator+(self_type left, D off) noexcept( detail::has_nothrow_advance<self_type, D>) { return left += off; } /// @brief operator+, requires <code>Derived::advance()</code> template<detail::advance_type_arg<self_type> D> [[nodiscard]] friend constexpr auto operator+(D off, self_type right) noexcept( detail::has_nothrow_advance<self_type, D>) -> self_type { return right += off; } /// @brief operator-, requires <code>Derived::advance()</code> template<detail::advance_type_arg<self_type> D> [[nodiscard]] friend constexpr self_type operator-(self_type left, D off) noexcept( detail::has_nothrow_advance<self_type, D>) { return left + -off; } /// @brief operator-=, requires <code>Derived::advance()</code> template<detail::advance_type_arg<self_type> D> friend constexpr self_type& operator-=(self_type& left, D off) noexcept( detail::has_nothrow_advance<self_type, D>) { return left = left - off; } /// @brief Random access operator, requires <code>Derived::advance()</code> template<typename T = self_type, detail::advance_type_arg<T> D> [[nodiscard]] constexpr decltype(auto) operator[](D off) const noexcept( detail::has_nothrow_advance<self_type, D>&& detail::has_nothrow_dereference<self_type>) { return (self() + off).dereference(); } /// @brief Distance between two iterators or iterator and sentinel pair, /// requires <code>Derived::distance_to()</code> template<detail::has_distance_to<self_type> T> [[nodiscard]] friend constexpr decltype(auto) operator-( const T& left, const self_type& right) noexcept(detail::has_nothrow_distance_to<T, self_type>) { return right.distance_to(left); } /// @brief Distance between an iterator and a sentinel, /// requires <code>Derived::distance_to()</code> template<detail::has_distance_to<self_type> Sentinel> [[nodiscard]] friend constexpr decltype(auto) operator-( const self_type& left, const Sentinel& right) noexcept(detail::has_nothrow_distance_to<Sentinel, self_type>) { return -(right - left); } /// @brief Three way comparison operator, requires <code>Derived::distance_to()</code> template<detail::has_distance_to<self_type> Sentinel> [[nodiscard]] friend constexpr auto operator<=>( const self_type& left, const Sentinel& right) noexcept(detail::has_nothrow_distance_to<Sentinel, self_type>) { return -left.distance_to(right) <=> 0; } }; namespace detail { template<typename Derived> class is_base_of_facade { private: template<typename T, bool B> static std::true_type derives(const iterator_facade<T, B>&); static std::false_type derives(...); public: constexpr static bool value = decltype(derives(std::declval<Derived>()))::value; }; template<typename T> concept iterator_facade_subclass = is_base_of_facade<T>::value; template<typename NewFirst, typename T> struct replace_first_param { using type = T; }; template<typename NewFirst, template<typename, typename...> typename T, typename First, typename... Rest> struct replace_first_param<NewFirst, T<First, Rest...>> { using type = T<NewFirst, Rest...>; }; template<typename T, typename Other, typename = void> struct rebind_alias { using type = typename replace_first_param<Other, T>::type; }; template<typename T, typename Other> struct rebind_alias<T, Other, std::void_t<typename T::template rebind<Other>>> { using type = typename T::template rebind<Other>; }; } // namespace detail } // namespace slang template<slang::detail::iterator_facade_subclass Iter> struct std::iterator_traits<Iter> { using reference = decltype(*std::declval<Iter&>()); using pointer = decltype(std::declval<Iter&>().operator->()); using difference_type = slang ::detail::inferred_difference_type_t<Iter>; using value_type = slang ::detail::inferred_value_type_t<Iter>; using iterator_category = slang ::detail::iterator_category_t<Iter>; using iterator_concept = slang ::detail::iterator_concept_t<Iter>; }; // specialization for contiguous iterators since the standard implementation // causes a compile error if Iter is not a template template<slang::detail::iterator_facade_subclass Iter> requires(slang::detail::satisfies_contiguous<Iter>) struct std::pointer_traits<Iter> { using pointer = Iter; using element_type = std::iter_value_t<Iter>; using difference_type = std::iter_difference_t<Iter>; template<typename Other> using rebind = typename slang::detail::rebind_alias<Iter, Other>::type; using reference = std::conditional_t<std::is_void_v<element_type>, char, element_type>&; static pointer pointer_to(reference value) noexcept(noexcept(Iter::pointer_to(value))) { return Iter::pointer_to(value); } };
true
2e26cbdca2a13d541fc0b63b8961111a4e688461
C++
matheusmso/code
/uri/1068.cpp
UTF-8
653
2.84375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main(){ stack<char> s; char c; bool bad = false; do { c = getchar(); if (c == '(') s.push(c); if (c == ')') { if (s.size() > 0 && s.top() == '(') s.pop(); else bad = true; } if (c == '\n'){ if(!bad && s.size() == 0) printf("correct\n"); else { printf("incorrect\n"); bad = false; } while (s.size() > 0) s.pop(); } } while (c != EOF); return 0; }
true
28c36c020ac7d7596dea87110d40ccbba45062e0
C++
Andreskammerath/Competitive_Programming
/UVa judge/Uva11450.cpp
UTF-8
1,484
3.046875
3
[]
no_license
#include <bits/stdc++.h> #include <iostream> using namespace std; int minimo(int a,int b) { int min = a; if(b < a) min = b; return min; } int shop(int money, int C, map<pair<int,int>,int> &my_map, vector<vector<int> > &v, int i, int j) { int min = 0;//numer to return map<pair<int,int>,int>:: iterator it = my_map.find(make_pair(money-v[i][j],i)); if( it != my_map.end() ) { min = it->second; } else if(money - v[i][j] < 0) { min = 10000; my_map[make_pair(money,i)] = min; } else if(i == C) { min = money; my_map[make_pair(money,i)] = money; } else if(j == 19) { min = shop(money,C,my_map,v,i+1,0); } else { min = minimo(shop(money - v[i][j],C,my_map,v,i+1,0),shop(money,C,my_map,v,i,j+1)); } return min; } void reset_table(vector<vector<int> > &v) { for (int i = 0; i < 20; ++i) { for (int j = 0; j < 20; ++j) { v[i][j] = 100; } } } int main() { int N = 0; //number of testcases cin >> N; int money = 0; vector<int> v(20); vector<vector<int> > table(20,v); map< pair<int,int>, int> my_map; int C = 0; // number of garment must buy int K = 0; int M = 0; for (int i = 0; i < N; ++i) { reset_table(table); cin >> money >> C; M = money; for (int i = 0; i < C; ++i) { cin >> K; for (int j = 0; j < K; ++j) { cin >> table[i][j]; } } cout << M - shop(money,C,my_map,table,0,0) << endl; } }
true
7d63bb036a4788fc6ce36e9a452738432905ef0a
C++
NCCA/FilesAndParsing
/FileIO/ReadLine.cpp
UTF-8
610
3.125
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <cstdlib> int main(int argc, char *argv[]) { if (argc <=1) { std::cout <<"Usage FileRead [filename] \n"; exit(EXIT_FAILURE); } std::fstream fileIn; fileIn.open(argv[1],std::ios::in); if (!fileIn.is_open()) { std::cout <<"File : "<<argv[1]<<" Not found Exiting \n"; exit(EXIT_FAILURE); } std::string lineBuffer; unsigned int lineNumber=1; while(!fileIn.eof()) { getline(fileIn,lineBuffer,'\n'); std::cout <<lineNumber<<" : "<<lineBuffer<<'\n'; ++lineNumber; } fileIn.close(); return EXIT_SUCCESS; }
true
56af9ded47d4b333c1b82824736daf6be1747850
C++
artiumdominus/hierarchical-heavy-hitters
/tratador_redutor.cpp
UTF-8
2,380
2.71875
3
[]
no_license
/* Trata um arquivo gerado por tcpdump filtrando as linhas que se encaixam no padrao: IP x.y.z.w.v > m.n.o.p.q: tcp s e as resumindo para o padrao: x.y.z.w m.n.o.p s Assim gerando uma entrada formatada para o algoritimo Overlap_Offline. */ #include <iostream> #include <fstream> #include <string> #include <string.h> #include <sstream> #include <list> #include "lattice.cpp" using namespace std; int main(int argc, char *argv[]) { char filename[30]; if(argc < 2) { cout << "Entre com o nome do arquivo: "; cin >> filename; } else { strcpy(filename, argv[1]); } ifstream file; file.open(filename); if(file.is_open()) { char linha[100]; string s; stringstream line; char IP[5], dot, arrow, colon, tcp[5]; int number[11]; list<Tuple> S, R; ip source, destination; double count; Tuple tuple; list<Tuple>::iterator e; bool found; while(getline(file, s)) { line << s; line >> IP >> number[0] >> dot >> number[1] >> dot >> number[2] >> dot >> number[3] >> dot >> number[4] >> arrow >> number[5] >> dot >> number[6] >> dot >> number[7] >> dot >> number[8] >> dot >> number[9] >> colon >> tcp >> number[10]; if(!strcmp(IP, "IP") && !strcmp(tcp, "tcp") && number[10] > 0) { source.byte[0] = number[0]; source.byte[1] = number[1]; source.byte[2] = number[2]; source.byte[3] = number[3]; destination.byte[0] = number[5]; destination.byte[1] = number[6]; destination.byte[2] = number[7]; destination.byte[3] = number[8]; count = number[10]; tuple = Tuple(source, destination, Label(4,4),count); found = false; for(e = S.begin(); e != S.end(); ++e) { if(tuple.equals(*e)) { e->count += tuple.count; found = true; break; } } if(!found) { S.push_back(tuple); } } line.clear(); } file.close(); int x; for(e = S.begin(); e != S.end(); ++e) { for(int i = 0; i < 4; ++i) { x = e->source.byte[i]; if(x >= 0) { cout << x; } else { cout << x+256; } if(i < 3) { cout << "."; } } cout << " "; for(int i = 0; i < 4; ++i) { x = e->destination.byte[i]; if(x >= 0) { cout << x; } else { cout << x+256; } if(i < 3) { cout << "."; } } cout << " " << e->count << endl; } } else { cout << "Unable to open file :C"; } return 0; }
true
8f7e4aba24e05e4e33406a190dd253ef6f2f1e1c
C++
omar-mohamed/OnlineJudges-solutions
/UVA-problems/Hello Recursion.cpp
UTF-8
412
3.125
3
[]
no_license
//#include<iostream> //using namespace std; //int arr[105]; //int Summation(int length) //{ // if(length==0) // return 0; // else // return arr[length-1]+Summation(length-1); //} // //int main() //{ // int cases,length; // cin>>cases; // for(int i=1;i<=cases;i++) // { // cin>>length; // for(int j=0;j<length;j++) // cin>>arr[j]; // cout<<"Case "<<i<<": "<<Summation(length)<<endl; // } // return 0; //}
true
823ed603965aa42f862a66199139feee52e0ee5f
C++
Canopius/School-Tasks
/OtherCode/Input Validation/Input Validation/Source.cpp
UTF-8
897
3.515625
4
[]
no_license
#include <iostream> #include <string> class Response { public: int age; std::string name; std::string emailAddress; }; bool checkAge(int age) { if (age < 16 || age > 100) { std::cout << std::endl << "Age is not within the valid range!"; return true; } else { return false; } } int requestAge() { int age; bool noAge = true; std::cout << "Please enter your age: "; std::cin >> age; noAge = checkAge(age); while (std::cin.fail() || (noAge)) { std::cout << std::endl << "Please enter your age: "; std::cin.clear(); std::cin.ignore(256, '\n'); std::cin >> age; noAge = checkAge(age); } return age; } int main() { Response newResponse; std::cout << "Please enter your name: "; std:: cin >> newResponse.name newResponse = requestAge() return 0; }
true
4143ac8d374266c811bf8a4b61f55ae6836b8206
C++
Ezibenroc/satsolver
/src/structures/graph.h
UTF-8
571
2.9375
3
[ "MIT" ]
permissive
#ifndef STRUCTURES_GRAPH_H #define STRUCTURES_GRAPH_H #include <set> namespace graphsolver { class Graph { private: int nodes_count; int *values; std::set<int> **adjacency; public: Graph(int nodes_count, int default_value); Graph(const Graph&); Graph& operator=(const Graph&); ~Graph(); void set_value(int node_id, int value); void add_edge(int first, int second); int get_nodes_count() const; std::set<int>* get_lower_adjacent_nodes(int node_id) const; }; } #endif
true
1b0c5efe0d8ecf178f9fe3fac5f4d52d8ce788a7
C++
yzhaiustc/PP-CNN
/pp_cnn/src/cnn/conv2d.hpp
UTF-8
1,351
2.546875
3
[ "Apache-2.0" ]
permissive
#pragma once #include "layer.hpp" using std::size_t; const string CONV2D_CLASS_NAME = "Conv2D"; class Conv2D : public Layer { public: Conv2D(const string& name, const size_t& in_height, const size_t& in_width, const size_t& in_channels, const size_t& filter_size, const size_t& filter_height, const size_t& filter_width, const size_t& stride_height, const size_t& stride_width, const string& padding, const string& activation, const Plaintext4D& plain_filters, const vector<Plaintext>& plain_biases); ~Conv2D(); const size_t& out_height() const { return out_height_; } const size_t& out_width() const { return out_width_; } const size_t& out_channels() const { return out_channels_; } void printInfo() const override; bool isOutOfRangeInput(const int& target_x, const int& target_y) const; void forward(Ciphertext3D& input) const; private: size_t in_height_; size_t in_width_; size_t in_channels_; size_t filter_size_; size_t filter_height_; size_t filter_width_; size_t stride_height_; size_t stride_width_; string padding_; string activation_; size_t out_height_; size_t out_width_; size_t out_channels_; size_t pad_top_; size_t pad_bottom_; size_t pad_left_; size_t pad_right_; Plaintext4D plain_filters_; vector<Plaintext> plain_biases_; };
true
f98dba85872daa599ad8af3be5d6b8fde6d5681f
C++
38609/cpp_lab_3
/player.cpp
UTF-8
1,070
3.59375
4
[]
no_license
#include <iostream> #include <vector> #include "player.h" Player::Player(string firstName, string lastName, int growth, vector<string> skills) { this->firstName = firstName; this->lastName = lastName; this->growth = growth; this->skills = skills; } string Player::getFirstName() { return this->firstName; } string Player::getLastName() { return this->lastName; } double Player::getGrowth() { return this->growth; } string Player::getSkills() { string result; for (auto const &s : skills) { result += s + " "; } return result; } string Player::getDetails() { string details; details += "First name: " + this->getFirstName() + "\n"; details += "Last name: " + this->getLastName() + "\n"; details += "Growth: " + to_string(this->getGrowth()) + "cm\n"; details += "Skills: " + this->getSkills() + "\n"; return details; } void Player::changeData(string firstName, string lastName, int growth) { this->firstName = firstName; this->lastName = lastName; this->growth = growth; }
true
ab60b2930c98affbd35553082cf2f3966535162f
C++
anchor-huang/Snapmaker2-DialMeshLeveling
/arduino_dial_indictor_reader/src/main.cpp
UTF-8
3,475
2.640625
3
[]
no_license
#include <Arduino.h> #include <Wire.h> /* I2C Bus Slave */ #define I2C_ADDRESS 0x32 #define READ_SENSOR_CMD 0x01 #define INVALID_CMD 0x00 /* Hardware pins */ const uint8_t ledPin = 13; // the number of the LED pin const uint8_t clkPin = 10; const uint8_t dataPin = 8; const uint8_t readyPin = 1; /* Constants */ const int ANALOG_READ_RESOLUTION = 8; // Define analog reading 8 bit resolution. Max=256 const int LOGIC_THRESHOLD = 55; // Define Logic state. Set to High when analog read larger than this value const int SIGN_BIT=20; const int INCH_BIT=23; unsigned long PATTERN_GAP=10000; // #10 milli second uint8_t read_logic(uint8_t pin){ return analogRead(pin)>LOGIC_THRESHOLD? HIGH: LOW; } void wait_pattern_start(){ unsigned long last_faling_edge=micros(); uint8_t last_value=read_logic(clkPin); uint8_t curr_value; unsigned long now; while(true){ curr_value=read_logic(clkPin); if(last_value==HIGH && curr_value==LOW){ now=micros(); if(now-last_faling_edge>PATTERN_GAP){ break; } } last_value=curr_value; last_faling_edge=now; delayMicroseconds(20); } } void wait_clk_rising(){ uint8_t last_value=read_logic(clkPin); uint8_t curr_value; while(true){ curr_value=read_logic(clkPin); if(last_value==LOW && curr_value==HIGH){ break; } last_value=curr_value; delayMicroseconds(10); } } int16_t read_dial_indicitor(){ wait_pattern_start(); digitalWrite(readyPin, HIGH); uint32_t data=0; for(uint8_t i=0;i<24;++i){ // Read 24 bits wait_clk_rising(); bitWrite(data, i, read_logic(dataPin)); } digitalWrite(readyPin, LOW); bool is_inch=bitRead(data, INCH_BIT); bool is_neg=bitRead(data, SIGN_BIT); bitClear(data, INCH_BIT); bitClear(data, SIGN_BIT); int16_t result=data; result=is_inch?result*1.27:result; result=is_neg?-result:result; if(is_inch) Serial.println("Inch"); Serial.println(String("Dial Indictor:")+result); return(result); } uint8_t CMD=INVALID_CMD; uint16_t sensor_result; boolean data_ready; void i2c_handle_receive(int numBytes){ //Serial.println(String(": OnReceive:")+numBytes); if(numBytes>0 and Wire.available()){ CMD=Wire.read(); data_ready=false; /* Clear Data Ready */ digitalWrite(readyPin, HIGH); //Serial.print("Rec CMD: "); //Serial.println(CMD); } } void i2c_handle_request(){ uint8_t *buf; Serial.println(": OnRequest:"); if(data_ready){ buf=(uint8_t*)&sensor_result; Serial.print("Response Sensor Read: "); Serial.println(sensor_result, HEX); Wire.write(buf, 2); } else { Serial.println("Data not ready"); } } void setup() { // put your setup code here, to run once: Serial.begin(115200); pinMode(ledPin, OUTPUT); pinMode(readyPin, OUTPUT); pinMode(clkPin, INPUT); pinMode(dataPin, INPUT); analogReadResolution(ANALOG_READ_RESOLUTION); Wire.begin(I2C_ADDRESS); Wire.onReceive(i2c_handle_receive); Wire.onRequest(i2c_handle_request); CMD=INVALID_CMD; digitalWrite(readyPin, HIGH); data_ready=false; } void loop() { // put your main code here, to run repeatedly: switch(CMD){ case READ_SENSOR_CMD: sensor_result=read_dial_indicitor(); digitalWrite(readyPin, LOW); data_ready=true; CMD=INVALID_CMD; break; default: /* Ignore */ delay(10); } }
true
9b0e71484820800aacf46385dc18d99e82f3ae26
C++
jameskkk/BlueScreenOfDeath
/BlueScreenOfDeath/BlueScreenOfDeath.cpp
UTF-8
2,327
2.75
3
[]
no_license
// BlueScreenOfDeath.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <Windows.h> #include <winternl.h> #include <iostream> #include <cstdlib> #pragma comment(lib, "ntdll.lib") using namespace std; EXTERN_C NTSTATUS NTAPI RtlAdjustPrivilege(ULONG, BOOLEAN, BOOLEAN, PBOOLEAN); EXTERN_C NTSTATUS NTAPI NtSetInformationProcess(HANDLE, ULONG, PVOID, ULONG); // Let user's PC go to BSOD int RunBlueScreenOfDeath1() { BOOLEAN bl; int isCritical = 1; UINT BreakOnTermination = 0x1D; if (!NT_SUCCESS(RtlAdjustPrivilege(20, TRUE, FALSE, &bl))) { printf("Unable to enable SeDebugPrivilege. Make sure you are running this program as administrator."); return -1; } // setting the BreakOnTermination = 1 for the current process NTSTATUS status = NtSetInformationProcess(GetCurrentProcess(), BreakOnTermination, &isCritical, sizeof(ULONG)); if (status != 0) { printf("Error: Unable to cancel critical process status. NtSetInformationProcess failed with status %#lx\n", status); } else { printf("Successfully canceled critical process status.\n"); } return 0; } typedef NTSTATUS(NTAPI *pdef_NtRaiseHardError)(NTSTATUS ErrorStatus, ULONG NumberOfParameters, ULONG UnicodeStringParameterMask OPTIONAL, PULONG_PTR Parameters, ULONG ResponseOption, PULONG Response); typedef NTSTATUS(NTAPI *pdef_RtlAdjustPrivilege)(ULONG Privilege, BOOLEAN Enable, BOOLEAN CurrentThread, PBOOLEAN Enabled); int RunBlueScreenOfDeath2() { BOOLEAN bEnabled; ULONG uResp; LPVOID lpFuncAddress = reinterpret_cast<LPVOID>(GetProcAddress(LoadLibrary(L"ntdll.dll"), "RtlAdjustPrivilege")); LPVOID lpFuncAddress2 = reinterpret_cast<LPVOID>(GetProcAddress(GetModuleHandle(L"ntdll.dll"), "NtRaiseHardError")); pdef_RtlAdjustPrivilege NtCall = reinterpret_cast<pdef_RtlAdjustPrivilege>(lpFuncAddress); pdef_NtRaiseHardError NtCall2 = reinterpret_cast<pdef_NtRaiseHardError>(lpFuncAddress2); NTSTATUS NtRet = NtCall(19, TRUE, FALSE, &bEnabled); NtCall2(static_cast<long>(STATUS_FLOAT_MULTIPLE_FAULTS), 0, 0, nullptr, 6, &uResp); cout << "BlueScreen() NtRet = " << NtRet; return 0; } int _tmain(int argc, _TCHAR* argv[]) { printf("Enter any key to blue screen of death!\n"); system("PAUSE"); printf("Good bye!\n"); RunBlueScreenOfDeath1(); //RunBlueScreenOfDeath2(); return 0; }
true
b3ac5bfd2e66cb89df854e35d77e26c82f594240
C++
JoeAltmaier/Odyssey
/Odyssey/SSAPI_Server/ManagedObjects/StorageElement.h
UTF-8
1,817
2.609375
3
[]
no_license
//****************************************************************************** // FILE: StorageElement.cpp // // PURPOSE: Implements the class that will serve as an bastract base class // for storage elements in the O2K that can be used for creation // of other storage elements. //****************************************************************************** #ifndef __STORAGE_ELEMENT_H__ #define __STORAGE_ELEMENT_H__ #include "StorageElementBase.h" class StorageManager; #ifdef WIN32 #pragma pack(4) #endif class StorageElement : public StorageElementBase{ protected: //****************************************************************************** // StorageElement: // // PURPOSE: The default constructor //****************************************************************************** StorageElement( ListenManager *pListenManager, U32 objectClassType, ObjectManager *pManager ); public: //****************************************************************************** // ~StorageElement: // // PURPOSE: The destructor //****************************************************************************** virtual ~StorageElement(); //************************************************************************ // GetCoreTableMask: // // PURPOSE: The methods returns the integer mask of the core table // withing the StorageManager. The core table for a storage // element is the table which defines the very existance // of the storage element. // Before, we only had one such table -- the StorageRollCall // table. Now, there is another one - the DeviceDescriptor. //************************************************************************ virtual U32 GetCoreTableMask( ); }; #endif // __STORAGE_ELEMENT_H__
true
a24f40bf30ae18f8f6ca478accd6c561a696a0c9
C++
jaronho/sdk
/base/cxx/algorithm/algorithm/sm3/sm3.h
UTF-8
2,789
2.859375
3
[]
no_license
#pragma once #ifdef __cplusplus namespace algorithm { extern "C" { #endif /** * @brief SM3 context structure */ typedef struct { unsigned long total[2]; /* number of bytes processed */ unsigned long state[8]; /* intermediate digest state */ unsigned char buffer[64]; /* data block being processed */ unsigned char ipad[64]; /* HMAC: inner padding */ unsigned char opad[64]; /* HMAC: outer padding */ } sm3_context_t; /** * @brief SM3 context setup * @param ctx context to be initialized */ void sm3Start(sm3_context_t* ctx); /** * @brief SM3 process buffer * @param ctx SM3 context * @param input buffer holding the data * @param ilen length of the input data */ void sm3Update(sm3_context_t* ctx, const unsigned char* input, int ilen); /** * @brief SM3 final digest * @param ctx SM3 context */ void sm3Finish(sm3_context_t* ctx, unsigned char output[32]); /** * @brief Output = SM3(input buffer) * @param input buffer holding the data * @param ilen length of the input data * @param output SM3 checksum result */ void sm3Sign(const unsigned char* input, int ilen, unsigned char output[32]); /** * @brief Output = SM3(file contents) * @param path input file name * @param output SM3 checksum result * @return 0-if successful, 1-if fopen failed, 2-if fread failed */ int sm3File(char* path, unsigned char output[32]); /** * @brief SM3 HMAC context setup * @param ctx HMAC context to be initialized * @param key HMAC secret key * @param keylen length of the HMAC key */ void sm3HmacStart(sm3_context_t* ctx, const unsigned char* key, int keylen); /** * @brief SM3 HMAC process buffer * @param ctx HMAC context * @param input buffer holding the data * @param ilen length of the input data */ void sm3HmacUpdate(sm3_context_t* ctx, const unsigned char* input, int ilen); /** * @brief SM3 HMAC final digest * @param ctx HMAC context * @param output SM3 HMAC checksum result */ void sm3HmacFinish(sm3_context_t* ctx, unsigned char output[32]); /** * @brief Output = HMAC-SM3(hmac key, input buffer) * @param key HMAC secret key * @param keylen length of the HMAC key * @param input buffer holding the data * @param ilen length of the input data * @param output HMAC-SM3 result */ void sm3Hmac(unsigned char* key, int keylen, const unsigned char* input, int ilen, unsigned char output[32]); #ifdef __cplusplus } } // namespace algorithm #endif
true
5641c41a74b0597c2a34e86a7c178da47b5f351e
C++
bhusingh/C--Programs
/C--Programs/linkedListAltrev.cpp
UTF-8
576
3.578125
4
[]
no_license
#include<iostream> using namespace std; struct node { int data; struct node *link; }; void addAtBeg(struct node **head,int data) { struct node *temp = new node; temp->data = data; temp->link = *head; *head = temp; } void printList(struct node *head) { while(head) { cout<<head->data<<endl; head = head->link; } } int main() { struct node *head = NULL; addAtBeg(&head,3); addAtBeg(&head,5); addAtBeg(&head,7); addAtBeg(&head,1); addAtBeg(&head,2); addAtBeg(&head,8); addAtBeg(&head,6); addAtBeg(&head,4); addAtBeg(&head,9); printList(head); return 0; }
true
62fd9ced6abbb24d65b1473e6370dc19d8455df3
C++
isac322/BOJ
/8932/8932.cpp
UTF-8
510
2.578125
3
[ "MIT" ]
permissive
#include <cstdio> #include <cmath> using namespace std; const double a[] = {9.23076, 1.84523, 56.0211, 4.99087, 0.188807, 15.9803, 0.11193}; const double b[] = {26.7, 75, 1.5, 42.5, 210, 3.8, 254}; const double c[] = {1.835, 1.348, 1.05, 1.81, 1.41, 1.04, 1.88}; int main() { int n, tmp; scanf("%d", &n); for (int i = 0; i < n; ++i) { int sum = 0; for (int j = 0; j < 7; ++j) { scanf("%d", &tmp); sum += int(a[j] * pow((j % 3 ? tmp - b[j] : b[j] - tmp), c[j])); } printf("%d\n", sum); } }
true
735bc655710f87ead4d855514bd648586c3aa411
C++
manofmountain/LeetCode
/147_InsertionSortList.cpp
UTF-8
831
3.1875
3
[]
no_license
//28.3% /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* insertionSortList(ListNode* head) { if(!head || !head -> next) return head; ListNode *curr(head -> next), *prev(head); while(curr){ ListNode *start(head), *preStart(NULL); while(start -> val < curr -> val){ preStart = start; start = start -> next; } if(start != curr){ prev -> next = curr -> next; if(preStart){ preStart -> next = curr; curr -> next = start; }else{ head = curr; curr -> next = start; } curr = prev -> next; }else{ prev = curr; curr = curr -> next; } } return head; } };
true
cdeb9ab24cd21a06a3c43cf870c810d2073cf4f2
C++
ZachHirst-HighSchoolCodingClasses/Chapter-4-5
/RomanNumeralTranslator/RomanNumeralTranslator/Source.cpp
UTF-8
1,156
3.53125
4
[]
no_license
// Author Zach Hirst // 4/11/18 // Hawkeye Challenge Problem #include<iostream> int main() { //variables int V = 5; int X = 10; int I = 1; double numI; double numX; double numV; double total; //user input std::cout << " Welcome to the Roman Numeral translator \n What can I translate for you today? " << std::endl; std::cout << " Please enter how many I are in your Numeral " << std::endl; std::cin >> numI; std::cout << " Please enter how many X are in your Numeral " << std::endl; std::cin >> numX; std::cout << " Please enter how many V are in your Numeral " << std::endl; std::cin >> numV; do { if (numV > 1) { std::cout << " I'm sorry you can only have one V " << std::endl; std::cout << " Please enter how many V are in your Numeral " << std::endl; std::cin >> numV; } } while (numV > 1); //process total = (numI * I) + (numX * X) + (numV * V); //output std::cout << " You had " << numI << " I in your Numeral \n You had " << numX << " X in your Numeral \n You had " << numV << " in your Numeral " << std::endl; std::cout << " Your numeral translated is " << total << std::endl; system("pause"); return 0; }
true
2a3b45b51be09350f203e7c780f16d0a414642ad
C++
hvariant/hackerrank
/cpp/lc-tree-zigzag/main.cpp
UTF-8
1,641
3.5625
4
[]
no_license
#define CATCH_CONFIG_FAST_COMPILE #define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include <vector> #include <queue> namespace { struct TreeNode { int val; TreeNode *left{nullptr}; TreeNode *right{nullptr}; TreeNode(int x) : val(x) {} }; } class Solution { public: std::vector<std::vector<int>> zigzagLevelOrder(const TreeNode* root) { if(root == nullptr) return {}; std::vector<std::vector<int>> levels; std::queue<std::pair<const TreeNode*, size_t>> Q; Q.push({root, 0}); while(!Q.empty()) { auto top_pair = Q.front(); Q.pop(); auto cur = top_pair.first; auto level = top_pair.second; if(levels.size() < level+1) { levels.resize(level+1); } levels[level].push_back(cur->val); if(cur->left) { Q.push({cur->left, level+1}); } if(cur->right) { Q.push({cur->right, level+1}); } } for(size_t i=1;i<levels.size();i+=2) { std::reverse(levels[i].begin(), levels[i].end()); } return levels; } }; TEST_CASE("null 1") { TreeNode* r = new TreeNode{0}; CHECK(Solution().zigzagLevelOrder(r) == std::vector<std::vector<int>>{{0}}); } TEST_CASE("null 2") { CHECK(Solution().zigzagLevelOrder(nullptr) == std::vector<std::vector<int>>{}); } TEST_CASE("example 1") { TreeNode* root = new TreeNode{3}; root->left = new TreeNode{9}; root->right = new TreeNode{20}; root->right->left = new TreeNode{15}; root->right->right = new TreeNode{7}; CHECK(Solution().zigzagLevelOrder(root) == std::vector<std::vector<int>>{{3}, {20, 9}, {15, 7}}); }
true
4df9ada5680c8095b5757abaef2261c0971eb0b4
C++
f-nely/estrutura-dados-estacio
/estrutura_dados/pilha_exemplo_01.cpp
UTF-8
1,337
3.65625
4
[]
no_license
#include <iostream> #define TAM 2 using namespace std; void empilhar(int p[], int &t, int v); int desempilha(int p[], int &t, int &v); void acessoTopo(int p[], int &t); void exibirElementos(int p[]); int main() { int pilha[TAM], topo = -1, val, resp; for (int i = 0; i < TAM; i++) { cout << "Digite o valor a ser empilhado:\n "; cin >> val; empilhar(pilha, topo, val); } /*for (int i = 0; i < TAM; i++) { cout << pilha[i] << endl; }*/ exibirElementos(pilha); resp = desempilha(pilha, topo, val); if (resp == 0) { cout << "\nAtenção. Pilha vazia\n"; } else { cout << "\nValor removido: " << val; } acessoTopo(pilha, topo); return 0; } void empilhar(int p[], int &t, int v) { if (t == TAM-1) { cout << "\nAtenção. Pilha cheia\n"; } else { t++; p[t] = v; } } int desempilha(int p[], int &t, int &v) { if (t == -1) { return 0; } else { v = p[t]; t--; return 1; } } void acessoTopo(int p[], int &t) { if (t == -1) cout << "\nAtenção. Pilha vazia\n"; else cout << "\nElemento do topo da pilha: " << p[t] << "\n"; } void exibirElementos(int p[]) { for (int i = 0; i < TAM; i++) { cout << p[i] << endl; } }
true
da5b7eedd7fa2651a3aa62f5885534a782af04cb
C++
msanchezzg/UVaOnlineJudge
/12000-12999/12750/keepRafaAtChelsea_12750.cpp
UTF-8
515
2.8125
3
[]
no_license
#include <iostream> using namespace std; int main(){ int cases, games, cont, loseCont; char result; bool out; cin >> cases; for(int i=1; i<=cases; i++) { cin >> games; cont = 0; loseCont = 0; out = false; for(int j=0; j<games; j++) { cin >> result; if (out) continue; cont++; if (result != 'W') loseCont++; else loseCont = 0; if (loseCont >= 3) out = true; } printf("Case %d: ", i); out ? cout << cont << '\n' : cout << "Yay! Mighty Rafa persists!\n"; } return 0; }
true
443c9bd8bc76d1ff8bc8770d87e2bb2a48ff5d90
C++
DylanGuedes/uva-problems
/627.cpp
UTF-8
2,009
2.9375
3
[]
no_license
#include <iostream> #include <vector> #include <sstream> #include <queue> #include <cstring> using namespace std; #define FOR(i, j, k) for(int i=j; i < k; ++i) #define MEMSET(i) memset(i, 0, sizeof i) vector<int> graph[325]; int father[325]; int visited[325]; void print_fathers(int idx) { if (father[idx] == idx) printf("%d", idx); else { print_fathers(father[idx]); printf(" %d", idx); } } void bfs(int origin, int destiny) { printf("bfs\n"); queue<int> myq; myq.push(origin); while (not myq.empty()) { int idx = myq.front(); printf("idx: %d\n", idx); myq.pop(); visited[idx] = 1; if (idx == destiny) { printf("achei sol\n"); print_fathers(idx); printf("\n"); return; } for (auto it : graph[idx]) { if (visited[it] == 0) { father[it] = idx; myq.push(it); } } } printf("connection impossible\n"); } int main() { int n; string mystring; int m, origin, destiny; while (cin >> n) { mystring.clear(); FOR(i, 0, n+2) { graph[i].clear(); } FOR(i, 0, n) { getline(cin, mystring); istringstream iss(mystring); char char_buf; iss >> origin; iss >> char_buf; while (iss >> destiny) { iss >> char_buf; graph[origin].push_back(destiny); graph[destiny].push_back(origin); } } cin >> m; printf("m: %d\n", m); printf("-----\n"); cin.clear(); FOR(i, 0, m) { cin >> origin >> destiny; scanf("%d%d", &origin, &destiny); MEMSET(visited); FOR(i, 0, n+2) { father[i] = i; } bfs(origin, destiny); } printf("-----\n"); } return 0; }
true
d1eef005bf7598d632bb6ebf6b485adec456df88
C++
vvancak/ir
/follower/motor.cpp
UTF-8
429
2.96875
3
[]
no_license
#include "motor.hpp" Motor::Motor(int max_update) { _max_update = max_update; _current_speed = 0; } void Motor::set_speed(int percentage) { int diff = percentage - _current_speed; if (diff > _max_update) diff = _max_update; if (diff < -_max_update) diff = -_max_update; _current_speed += diff; go(_current_speed); } void Motor::go(int percentage) { writeMicroseconds(1500 + percentage * 2); }
true
87c3924075ea08fa79183d4b05b135104e24e133
C++
Shada/Wanshift
/StortSpelprojekt/NonaNode.h
UTF-8
2,078
2.6875
3
[]
no_license
#pragma once #include "CullingNode.h" //#include "PlayerContainer.h" //#include "TerrainContainer.h" #define QUADSIZE 20 #define CHUNKSIZE 256 #define TINYSPLITTING 15 //the amount of sub-chunks per axis in a small chunk (eg, 15 means there are 15x15 sub-chunks in the chunk) #define MEDIUMSPLITTING 3 //the amount of sub-chunks per axis in a medium chunk (eg, 3 means there are 3x3 sub-chunks in the chunk) #define LARGESPLITTING 3 //the amount of sub-chunks per axis in a large chunk (eg, 3 means there are 3x3 sub-chunks in the chunk) typedef unsigned int uint; //a chunk of the terrain template < uint X, uint Y > struct Chunk { static const uint size_x = X; //width of the chunk static const uint size_y = Y; //height of the chunk static const uint size = X * Y; //overall size of the chunk glm::vec3 position; //position of the chunk in the top left corner uint bufferStartID; //the start index in the vertex buffer uint bufferAmount; //the vertex amount for this chunk uint iBufferStartID; //the start index in the index buffer uint iBufferAmount; //the index amount for this chunk uint heightsID; int heightmapShaderResource; int grassBlendShaderResource; /* 1: small, 2: medium, 3:large */ int level; }; class NonaNode :public CullingNode { private: const Chunk<CHUNKSIZE, CHUNKSIZE> *chunk; public: std::vector<int> *tesselationchunks; //child nodes std::vector<NonaNode*> children; /* constructor #_graphics is a pointer to the renderer*/ NonaNode(RenderInterface *_graphics, std::vector<int> *_tesselationchunks); /* detects children or draws stuff #_frustum is a pointer to the generated frustum from the camera*/ void draw(Frustum *_frustum); /* adds a child node #_child is the node to be added*/ void addNode(NonaNode *_child); /* adds a chunk of terrain to the node #_chunk is the chunk to be added to this node */ void addChunk(Chunk<CHUNKSIZE, CHUNKSIZE> *_chunk); /*returns the index in question */ int getChunkVStartIndex(); /*returns the chunk buffer amount */ int getChunkVSize(); ~NonaNode(); };
true
ce8b9eb4904215e465198ce1eda7b798d621ef01
C++
skilincer/C-Alistirma
/5.soru.cpp
ISO-8859-9
436
2.90625
3
[]
no_license
#include<stdio.h> #include<conio.h> main(){ int x, *isaret; x = 10; isaret = &x; printf("x in degeri = %d\n",x); // bunlar bilgilendirme amal printf("x in adresi = %x\n",isaret); // pointer mantg burdan incelenebilir. printf("x in deeri = %d\n",*isaret); printf("x in adresi = %x\n",&x); int dizi[]={2,3,1,5,7,5,2,6,8,6}; for(int i=0;i<10;i++) { printf("dizinin %d.adresi = %x\n",i,&dizi[i]); } }
true
96348c122c5a1d86f1e0256adc3b49979bef1193
C++
TakuyaKimura/Leetcode
/283 Move Zeroes/283.cpp
UTF-8
658
3.765625
4
[]
no_license
/* Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. Note: You must do this in-place without making a copy of the array. Minimize the total number of operations. */ #include <vector> using namespace std; class Solution { public: void moveZeroes(vector<int>& nums) { int n = nums.size(), j = 0; for (int i = 0; i < n; ++i) if (nums[i]) nums[j++] = nums[i]; while (j < n) nums[j++] = 0; } };
true
6df7ee2b2e037ce2b97f7457b6cacc785f71fa52
C++
face4/AOJ
/Volume05/0567.cpp
UTF-8
572
2.953125
3
[]
no_license
#include<iostream> #include<algorithm> using namespace std; int main(){ int n, a, b, c; cin >> n >> a >> b >> c; int topping[n]; for(int i = 0; i < n; i++) cin >> topping[i]; sort(topping, topping+n); reverse(topping, topping+n); int cal = c, cost = a; for(int i = 0; i < n; i++){ int ncal = cal + topping[i]; int ncost = cost + b; if((double)ncal/ncost >= (double)cal/cost){ cal = ncal, cost = ncost; }else{ break; } } cout << cal/cost << endl; return 0; }
true
f39fa834bda1320540fed7b1b7e94f9b7da4f1ca
C++
dimitarkole/CPlusPlusTasks
/C++/skola/sum.cpp
UTF-8
239
2.703125
3
[]
no_license
#include<iostream> using namespace std; int main() { int ch1,ch2,ch3; cin>>ch1>>ch2>>ch3; if((ch1==ch2)&&(ch1==ch3)) cout<<ch1<<ch2<<ch3; else if(ch2==ch3)cout<<ch1<<ch2<<ch3<<ch1; else cout<<ch1<<ch2<<ch3<<ch2<<ch1; }
true
afc8a351affa53f8f520e92f3ac10bda3f6eec4a
C++
AbeleMM/Algorithmic-Problems
/School/Clasa a VIII-a/Ianuarie 2014/porumb1/main.cpp
UTF-8
535
2.75
3
[ "MIT" ]
permissive
#include <iostream> #include <fstream> using namespace std; ifstream in("porumb1.in"); ofstream out("porumb1.out"); int nr,n,nra,x,ult,nt; int main() { in>>n>>x; nr=n; nra=0; ult=1; nt=1; if(n%2==0) out<<n/2<<"\n"; else out<<n/2+1<<"\n"; while(nr>0) { nr=nr/2; nra=nra+1; } out<<nra<<"\n"; while(x%2==0) { x=x/2; nt=nt+1; } out<<nt<<"\n"; while(2*ult<n) { ult=ult*2; } out<<ult; return 0; }
true
b5789fbbed59e7627440a46c9a8a5452c9289374
C++
thuynh02/relationGame
/src/ofCharacter.cpp
UTF-8
5,217
2.9375
3
[]
no_license
// // ofCharacter.cpp // relationGame // // Created by Emrys on 6/20/14. // #include "ofCharacter.h" #define PROBTIME 5 // Default Constructor - Used to create a character ofCharacter::ofCharacter( string name, string introduction, string bodyPath, string basePath, string eyesPath, string hairPath, string shoesPath, string topsPath, string bottomsPath, float x, float y, float speedX, float speedY ) : name(name), introduction( introduction), x(x), y(y), imgX(0), currentPos(4), dirX(0), dirY(0), speedX( speedX ), speedY( speedY ), range( ofRandom( 1, 5 ) ), isWalking( true ) { charImage.loadImage( bodyPath ); baseImage.loadImage( basePath ); eyesImage.loadImage( eyesPath ); hairImage.loadImage( hairPath ); shoesImage.loadImage( shoesPath ); topsImage.loadImage( topsPath ); bottomsImage.loadImage( bottomsPath ); footSpace =charImage.getHeight() / 5; footRect = ofRectangle(x, y + MAPHEIGHT - footSpace, MAPWIDTH, footSpace ); startTime = ofGetElapsedTimeMillis(); } ofCharacter::~ofCharacter(){}; bool ofCharacter::operator<(ofCharacter& rhs) { return y < (&rhs)->y;} // Update Method - Used to refresh character's properties void ofCharacter::update( bool player){ if ( player ){ if( x < 0 ){ x = 0 ;} else if (x + MAPWIDTH > (ofGetWidth() / 4) * 3 ) { x = (ofGetWidth() / 4) * 3 - MAPWIDTH; } if( y < 0 ){ y = 0 ;} else if (y + MAPHEIGHT > ofGetHeight() ) { y = ofGetHeight() - MAPHEIGHT; } x += dirX * speedX; y += dirY * speedY; } else{ // Every PROBTIME seconds, check if it is time to alter between walking and standing if( ofGetElapsedTimeMillis() - startTime > PROBTIME * 1000 ){ cout << "TIME!" << endl; if( ofRandom( -1, 1 ) > 0 ) { isWalking = !isWalking; } startTime = ofGetElapsedTimeMillis(); } if( isWalking ) { if( x < 0 ){ x = 0; speedX *= ofRandom(-1.5, -0.5); } else if( x + MAPWIDTH > (ofGetWidth() / 4) * 3 ){ x = (ofGetWidth() / 4) * 3 - MAPWIDTH; speedX *= ofRandom(-1.5, -0.5); } if( y < 0 ){ y = 0; speedY *= ofRandom(-1.5, -0.5); } else if( y + MAPHEIGHT > ofGetHeight() ){ y = ofGetHeight() - MAPHEIGHT; speedY *= ofRandom(-1.5, -0.5); } x += speedX; y += speedY; if( speedX > 0 ) { dirX = 1; } else if( speedX == 0 ) { dirX = 0; } else if( speedX < 0 ) { dirX = -1; } if( speedY > 0 ) { dirY = 1; } else if( speedY == 0 ) { dirY = 0; } else if( speedY < 0 ) { dirY = -1; } } } if( isWalking ){ // LEFT: X = -1, Y = 0 if( dirX == -1 ){ animateWalkLeft(); } // RIGHT: X = 1, Y = 0 else if( dirX == 1 ){ animateWalkRight(); } // UP: X = 0, Y = -1 else if( dirY == -1 ){ animateWalkBackward(); } // DOWN: X = 0, Y = 1 else if( dirY == 1 ){ animateWalkForward(); } } footRect.setPosition(x, y + MAPHEIGHT - footSpace ); } bool ofCharacter::timeToTransition(){ if( ofGetElapsedTimeMillis() - targetTime > 100 ){ targetTime = ofGetElapsedTimeMillis(); return true; } return false; } void ofCharacter::animateWalkLeft(){ if( timeToTransition() ){ currentPos++; if( currentPos >= 4 ) { currentPos = 0; } } } void ofCharacter::animateWalkForward(){ if( timeToTransition() ){ currentPos++; if( currentPos >= 8 ) { currentPos = 4; } } } void ofCharacter::animateWalkRight(){ if( timeToTransition() ){ currentPos++; if( currentPos >= 12 ) { currentPos = 8; } } } void ofCharacter::animateWalkBackward(){ if( timeToTransition() ){ currentPos++; if( currentPos >= 16 ) { currentPos = 12; } } } // Update Method - Used to refresh character's properties void ofCharacter::draw(){ ofSetColor( 120, 120, 120, 100 ); ofEllipse( x + MAPWIDTH/2, y + MAPHEIGHT, range * (MAPHEIGHT) / 2, range * (MAPHEIGHT) / 4 ); ofSetColor( 197, 151, 117); charImage.drawSubsection( x, y, MAPWIDTH, MAPHEIGHT, MAPWIDTH * currentPos, 0); baseImage.drawSubsection( x, y, MAPWIDTH, MAPHEIGHT, MAPWIDTH * currentPos, 0); eyesImage.drawSubsection( x, y, MAPWIDTH, MAPHEIGHT, MAPWIDTH * currentPos, 0); shoesImage.drawSubsection( x, y, MAPWIDTH, MAPHEIGHT, MAPWIDTH * currentPos, 0); bottomsImage.drawSubsection( x, y, MAPWIDTH, MAPHEIGHT, MAPWIDTH * currentPos, 0); topsImage.drawSubsection( x, y, MAPWIDTH, MAPHEIGHT, MAPWIDTH * currentPos, 0); hairImage.drawSubsection( x, y, MAPWIDTH, MAPHEIGHT, MAPWIDTH * currentPos, 0); ofSetColor( 255, 255, 255, 100 ); ofRect(footRect.x, footRect.y, footRect.width, footRect.height ); }
true
c81cb568581abd5b9cdaa1a0aa6cc3855d915c1b
C++
habrade/epics-wb
/src/ewbbridge/EWBBridge.h
UTF-8
2,069
3.09375
3
[]
no_license
/* * EWBBridge.h * * Created on: Jun 15, 2015 * Author: Benoit Rat (benoit<AT>sevensols.com) */ #ifndef EWBBRIDGE_H_ #define EWBBRIDGE_H_ #include <stdlib.h> #include <stdint.h> #include <string> /** * Polymorphic & abstract class memory bridge to a EWB device. * * The inherited class: * - must overload single access to the memory * - might overload DMA access to the memory * * The child class will be defined for each type of physical driver used to access to our EWB board. */ class EWBBridge { public: //! The type of the overridden class enum Type { TFILE=0, //!< Connector to a test file X1052, //!< Connector to the X1052 driver RAWRABBIT, //!< Connector to the RawRabbit driver ETHERBONE //!< Connector to the Etherbone driver }; //! Constructor where we only give the type EWBBridge(int type,const std::string &name =""): type(type),name(name),block_busy(false) {}; //! Empty destructor virtual ~EWBBridge() {}; //! Return true if the handler of the overridden class if true, otherwise false. virtual bool isValid() { return false; } //! Generic single access to the wishbone memory of the device virtual bool mem_access(uint32_t addr, uint32_t *data, bool to_dev)=0; //! Retrieve the internal read/write buffer and its size virtual uint32_t get_block_buffer(uint32_t **hBuff, bool to_dev) { return 0; }; //! Generic block access to the wishbone memory of the device virtual bool mem_block_access(uint32_t dev_addr, uint32_t nsize, bool to_dev) { return false; }; //! Return which type of EWBBrdige overridden class we are using (force casting) int getType() { return type; } //! Return true if the block access is busy. bool isBlockBusy() { return block_busy; } virtual const std::string& getName() const { return name; } virtual const std::string& getVer() const { return ver; } virtual const std::string& getDesc() const { return desc; } protected: int type; //!< type of the overridden class. std::string name; std::string desc; std::string ver; bool block_busy; }; #endif /* EWBBRIDGE_H_ */
true
d2a07b2ce067caa324115b4c13f412cdd336e50c
C++
derekzhang79/Algorithm-Training
/C/decoding.cpp
UTF-8
1,445
2.875
3
[]
no_license
#include<stdio.h> #include<string.h> int readchar(){ for(;;){ int ch = getchar(); if(ch != '\n' && ch !='\r') return ch;//一直读取到非换行符为止 } } int readint(int c){ int v = 0; while(c--) v = v * 2 + readchar() - '0'; return v; } int code[8][1<<8]; void printcodes(){ for(int len=1;len<=7;len++) for(int i=0;i<(1<<len)-1;i++){ if(code[len][i] == 0) return; printf("code[%d][%d] = %c\n",len,i,code[len][i]); } } int readcodes(){ memset(code,0,sizeof(code));//清空数组 code[1][0] = readchar();//直接调到下一行开始读取。如果输入已经结束,会读到EOF for(int len=2;len<=7;len++){ for(int i=0;i<(1<<len)-1;i++){ int ch = getchar(); if(ch == EOF) return 0; if(ch =='\n' || ch == '\r') return 1; code[len][i] = ch; } } return 1; } int main(){ //freopen("d.in","r",stdin); while(readcodes()){//无法读取更多编码头时退出 //printcodes(); for(;;){ int len = readint(3); if(len == 0) break; //printf("len = %d",len); for(;;){ int v = readint(len); //printf("v = %d\n",v); if(v == (1 << len) - 1) break; putchar(code[len][v]); } } putchar('\n'); } return 0; }
true
2ad7ce88ebe4857d03ca689db2030f82b242c61d
C++
NewLewis/LeetCode
/leetcode328.cpp
UTF-8
712
3.15625
3
[]
no_license
#include <iostream> #include "MyList.h" using namespace std; class Solution { public: ListNode* oddEvenList(ListNode* head) { if(!head || !head->next) return head; ListNode *L1 = NULL,*L2 = NULL; ListNode *P = head,*res1,*res2; int k = 1; while(P){ if(k%2 == 1){ if(!L1){ L1 = P; res1 = L1; }else{ L1->next = P; L1 = L1->next; } }else{ if(!L2){ L2 = P; res2 = L2; }else{ L2->next = P; L2 = L2->next; } } k++; P = P->next; } L1->next = res2; L2->next = NULL; return res1; } }; int main(){ }
true
2481cc297cbc34636fc6b52c4580bf1be2e259ff
C++
AlexTahiata/Apprendre_Cpp
/TPPolymorphisme/segment.cpp
UTF-8
840
3.15625
3
[]
no_license
#include "segment.h" Segment::Segment(int _numero, int _vitesse, const double _longueur, const double _angle): Element(_numero, _vitesse), longueur(_longueur), angle(_angle) { } void Segment::Afficher() { cout << "SEGMENT L = " << longueur; cout << " " << "A = " << angle; cout << " " << "V = " << vitesse << endl; } double Segment::ObtenirLongueur() { return longueur; //cout << "\nLongueur totale du parcours = " << longueurTotale << endl; } void Segment::ObtenirDuree() { /*int duree; int vitesseTotale; vitesseTotale = leSegment.vitesse + leSegment2.vitesse; duree = (longueurTotale / vitesseTotale); cout << "Durée totale du parcours = " << duree << endl;*/ } void Segment::ObtenirVecteurArivee() { //x = longueur * cos(angle); //y = longueur * sin(angle); }
true
0333c3272e874c943939193115c3945e1326f46e
C++
TamoghnaChattop/EE-569---Digital-Image-Processing
/Project 3/Source Code_EE_569_Hw_Assignment_3_8541324935_Chattopadhyay/HW3Prob1b.cpp
UTF-8
10,396
3.03125
3
[]
no_license
// EE569 Homework Assignment #3 // Date: March 7, 20018 // Name: Tamoghna Chattopadhyay // ID: 8541324935 // email: tchattop@usc.edu #include <stdio.h> #include <iostream> #include <fstream> #include <math.h> #include <algorithm> #include <stdlib.h> #include <time.h> class image { public: int size1,size2,BytesPerPixel; unsigned char * Image1 = new unsigned char [1000000l]; float * Image = new float [10000000]; image();//default constructor image(int x,int y, int z); //parameterized constructor ~image(); //destructor unsigned char * readfile( char*[],int,int,int,int); unsigned char * MemAlloc(int,int,int); void writefile( char*[],unsigned char *,int,int,int,int); void print(float **,int,int,int,int); float ** conv1D2D(float *,int,int,int); double feature_ext(unsigned char *, float *,int); float *filter_segment(unsigned char *,int,int,int,int); float energy(float *,int,int,int,int,int,int,int); }; image :: image() {}; //default constructor image :: image(int x,int y,int z) { //parameterized constructor size1=y; size2=x; BytesPerPixel=z; } image :: ~image() { //destructor } unsigned char * image::MemAlloc(int size1,int size2,int BytesPerPixel) { unsigned char * ImagePointer=new unsigned char [size1*size2*BytesPerPixel]; return ImagePointer; } unsigned char * image::readfile( char *argv[],int index,int size1,int size2,int BytesPerPixel) { FILE *file; unsigned char *Image=MemAlloc(size1,size2,BytesPerPixel); if (!(file=fopen(argv[index],"rb"))) { std::cout << "Cannot open file: " << argv[index] <<std::endl; exit(1); } fread(Image, sizeof(unsigned char), size1*size2*BytesPerPixel, file); fclose(file); return Image; } float **image:: conv1D2D(float * feature_vector, int size1,int size2,int h) { float** f_vector = new float*[size1*size2]; for(int i = 0; i < size1*size2; ++i) { f_vector[i] = new float[h]; } for(int i=0;i<size1;i++) { for(int j=0;j<size2;j++) { for(int f=0;f<h;f++) { f_vector[((i*size2)+j)][f]=feature_vector[((i*size2)+j)*h + f]; } } } return f_vector; } void image:: print(float **f_vector,int size1,int size2,int BytesPerPixel,int f) { std::cout<<"\tThe feature vectors are:"<<std::endl; for(int i=0;i<size1;i++) { for(int j=0;j<size2;j++) { std::cout<<"Pixel: "<<(i*size2)+j; for(int h=0;h<f;h++) { std::cout<<"\t"<<f_vector[((i*size2)+j)][h]; } std::cout<<std::endl; } } } //pixel value calculation double image:: feature_ext(unsigned char *image, float *filter,int op) { double pixel_value=0.0; switch(op) { case 1: { for (int i=0;i<25;i++) { pixel_value = pixel_value + (image[i]*filter[i]); } break; } case 2: { for (int i=0;i<9;i++) { pixel_value = pixel_value + (image[i]*filter[i]); } break; } } return pixel_value; } float *image::filter_segment(unsigned char *image,int size1,int size2,int BytesPerPixel,int op) { float *temp = new float [size1*size2*BytesPerPixel]; unsigned char image_arr[9]={0}; int x=0,p=0,q=0; for(int rgb=0;rgb<BytesPerPixel;rgb++) { for (int i=0;i<size1;i++) { for(int j=0;j<size2;j++) { x=0; for(int m=i-1;m<=i+1;m++) { for(int n=j-1;n<=j+1;n++) { if(m<0) { p=abs(m); } else if(m>=size1) { int pp=m-(size1-1); p=(size1-1)-pp; } else { p=m; } if(n<0) { q=abs(n); } else if(n>=size2) { int qq=n-(size2-1); q=(size2-1)-qq; } else { q=n; } image_arr[x++]=image[((p*size2)+q)*BytesPerPixel +rgb]; } } switch(op) { case 1: { float filter[9]={1.0/4,0,1.0/4,0,0,0,-1.0/4,0,1.0/4}; temp[((i*size2)+j)*BytesPerPixel +rgb] = feature_ext(image_arr, filter,2); break; } case 2: { float filter[9]={1.0/4,0,-1.0/4,-2.0/4,0,2.0/4,1.0/4,0,-1.0/4}; temp[((i*size2)+j)*BytesPerPixel +rgb] = feature_ext(image_arr, filter,2); break; } case 3: { float filter[9]={-1.0/12,0,1.0/12,-2.0/12,0,2.0/12,-1.0/12,0,1.0/12}; temp[((i*size2)+j)*BytesPerPixel +rgb] = feature_ext(image_arr, filter,2); break; } case 4: { float filter[9]={1.0/4,-2.0/4,-1.0/4,0,0,0,-1.0/4,2.0/4,1.0/4}; temp[((i*size2)+j)*BytesPerPixel +rgb] = feature_ext(image_arr, filter,2); break; } case 5: { float filter[9]={1.0/4,-2.0/4,-1.0/4,-2.0/4,4.0/4,2.0/4,-1.0/4,2.0/4,1.0/4}; temp[((i*size2)+j)*BytesPerPixel +rgb] = feature_ext(image_arr, filter,2); break; } case 6: { float filter[9]={1.0/12,-2.0/12,-1.0/12,-2.0/12,4.0/12,2.0/12,-1.0/12,2.0/12,1.0/12}; temp[((i*size2)+j)*BytesPerPixel +rgb] = feature_ext(image_arr, filter,2); break; } case 7: { float filter[9]={-1.0/12,-2.0/12,-1.0/12,0,0,0,1.0/12,2.0/12,1.0/12}; temp[((i*size2)+j)*BytesPerPixel +rgb] = feature_ext(image_arr, filter,2); break; } case 8: { float filter[9]={-1.0/12,-2.0/12,-1.0/12,2.0/12,4.0/12,2.0/12,-1.0/12,-2.0/12,-1.0/12}; temp[((i*size2)+j)*BytesPerPixel +rgb] = feature_ext(image_arr, filter,2); break; } case 9: { float filter[9]={1.0/36,2.0/36,1.0/36,2.0/36,4.0/36,2.0/36,-1.0/36,-2.0/36,-1.0/36}; temp[((i*size2)+j)*BytesPerPixel +rgb] = feature_ext(image_arr, filter,2); break; } } } } } return temp; } float image:: energy(float * temp,int size1,int size2,int i, int j,int ByterPerPixel,int w,int f) { int p=0,q=0; float average=0.0; for(int m=i-w;m<=i+w;m++) { for(int n=j-w;n<=j+w;n++) { if(m<0) { p=abs(m); } else if(m>=size1) { int pp=m-(size1-1); p=(size1-1)-pp; } else { p=m; } if(n<0) { q=abs(n); } else if(n>=size2) { int qq=n-(size2-1); q=(size2-1)-qq; } else { q=n; } average = average + pow(temp[((p*size2)+q)*ByterPerPixel],2); } } average = average/pow(((2*w)+1),2); return average; } using namespace std; int main(int argc, char *argv[]) { FILE* file; int size1 = 600; int size2 = 450; int BytesPerPixel = 1; int i, j, f, im=1, window=6;; image object1(size1,size2,BytesPerPixel); image ob[9],object_op[9]; for(i=0;i<12;i++) { //copying attributes to each object ob[i]=object1; object_op[i]=object1; } //for calculating the feature vector float *feature_vector = new float [size1*size2*9]; //using feature vector for k-means calculation float** f_vector = new float*[size1*size2]; for(int i = 0; i < size1*size2; ++i) { f_vector[i] = new float[9]; } unsigned char* ImageData = new unsigned char[size1*size2*BytesPerPixel]; if (!(file=fopen(argv[1],"rb"))) { cout << "Cannot open file: " << argv[1] <<endl; exit(1); } fread(ImageData, sizeof(unsigned char), size1*size2*BytesPerPixel, file); fclose(file); cout << "File " << argv[1] << " has been read successfully! " << endl; for(f=0;f<9;f++) { ob[f].Image=ob[f].filter_segment(ImageData,object1.size1,object1.size2,object1.BytesPerPixel,f+1); for(i=0;i<object1.size1;i++) { for(j=0;j<object1.size2;j++) { feature_vector[((i*ob[f].size2)+j)*9 + f]= ob[f].energy(ob[f].Image,ob[f].size1,ob[f].size2,i,j,object1.BytesPerPixel,window,f); } } } f_vector=object1.conv1D2D(feature_vector,object1.size1,object1.size2,9); object1.print(f_vector,object1.size1,object1.size2,object1.BytesPerPixel,9); return 0; }
true
0d0d8d1af1e8eba69e480cd98398a2990b98bd67
C++
shudipta/competitve-programming
/online-judges/leetcode/289.game-of-life.cpp
UTF-8
1,144
2.765625
3
[]
no_license
/* * @lc app=leetcode id=289 lang=cpp * * [289] Game of Life */ // @lc code=start class Solution { int R[8] = {-1, -1, -1, 0, 1, 1, 1, 0}; int C[8] = {-1, 0, 1, 1, 1, 0, -1, -1}; public: void gameOfLife(vector<vector<int>>& board) { int n = board.size(); int m = board[0].size(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int liveCnt = 0; for (int k = 0; k < 8; k++) { int ii = i + R[k]; int jj = j + C[k]; liveCnt += ii >= 0 && ii < n && jj >= 0 && jj < m && (board[ii][jj] > 3 ? 0 : board[ii][jj] > 1 ? 1 : board[ii][jj]); } if (board[i][j]) board[i][j] = (liveCnt == 2 || liveCnt == 3) ? 2 : 3; else board[i][j] = (liveCnt == 3) ? 4 : 5; } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { board[i][j] = board[i][j] == 2 || board[i][j] == 4; } } } }; // @lc code=end
true
b8d4997c616927b4a62111009f13869a9b6dd349
C++
IgnacioAlmeida/DatalogInterpreter
/Relation.cpp
UTF-8
6,450
2.921875
3
[]
no_license
// // Created by Ignacio R. de Almeida on 5/22/21. // #include "Relation.h" std::string Relation::ToString() { std::string output; for (const Tuple& t : rows){ std::vector<std::string> values = t.GetValues(); for(unsigned int i = 0; i < header.GetAttributes().size(); i++){ if(i != 0){ output += ", "; } else{ output += " "; } if(header.GetAttributes().at(i).at(0) != '\''){ output += header.GetAttributes().at(i) + "=" + values.at(i); } } output += "\n"; } return output; } void Relation::AddTuple(const Tuple& tuple) { rows.insert(tuple); } Relation Relation::Select(int columnIndex, std::string value) { //Create empty relation Relation relation(name, header); //We only include tuples with matching values at given column for(const Tuple& t : rows){ if(t.GetValues().at(columnIndex) == value){ relation.AddTuple(t); } } return relation; } Relation Relation::Select(int columnIndex, int columnIndexB){ Relation relation(name, header); //We only include tuples with matching values for(const Tuple& t : rows){ if(t.GetValues().at(columnIndex) == t.GetValues().at(columnIndexB)){ relation.AddTuple(t); } } return relation; } Relation Relation::Project(std::vector<int>& indices){ //Look at all the tuples and keep the desired indices std::vector<std::string> columns; for(unsigned int i = 0; i < indices.size(); i++){ columns.push_back(header.GetAttributes().at(indices.at(i))); } Header newHeader = Header(columns); Relation relation(name, newHeader); for(const Tuple& t : rows){ std::vector<std::string> values; for(unsigned int i = 0; i < indices.size(); i++){ values.push_back(t.GetValues().at(indices.at(i))); } Tuple tuple(values); relation.AddTuple(tuple); } return relation; } Relation Relation::Rename(std::vector<std::string> attributes){ std::vector<std::string> columns; for(unsigned int i = 0; i < attributes.size(); i++){ columns.push_back(attributes.at(i)); } Header newHeader = Header(columns); Relation relation(name, newHeader); for(const Tuple& t : rows){ if(t.GetValues().size() > 0 || t.GetValues().size() == 0){ relation.AddTuple(t.GetValues()); } } return relation; } void Relation::Rename(int i, std::string attribute){ header.GetAttributes().at(i) = attribute; } Header Relation::CombineHeaders(std::vector<std::string>firstHeader, std::vector<std::string>secondHeader){ std::vector<std::string> combinedHeaders = firstHeader; //Stores all the matching column names for(unsigned int i = 0; i < firstHeader.size(); i++){ for(unsigned int j = 0; j < secondHeader.size(); j++) { if (firstHeader.at(i) == secondHeader.at(j)) { matchedColumns.insert(std::pair<int, int>(j, i)); } } } //add new headers from secondHeader to fistHeader for(unsigned int i = 0; i < secondHeader.size(); i++){ std::map<int,int>::iterator it = matchedColumns.find(i); if(it == matchedColumns.end()){ combinedHeaders.push_back(secondHeader.at(i)); } } Header combinedHeader = Header(combinedHeaders); return combinedHeader; //1) Make a vector of strings and put everything from h1 //2) make two nested for loops (Outside is h2 and inside h1) //3)loop through each header and try to find out where they are overlapping //4)if they match, push back j and i to the map (pay attention to j and i order) // 5) bool add = false (inbtwn of nested loop) //6) if they don't match add = true //7) after the inner loop ) if add then vector of strings.push back h2.at(i); //may need to adjust combinetuples and isjoinable functions } bool Relation::isJoinable(const Tuple& firstTuple, const Tuple& secondTuple){ if(!matchedColumns.empty()){ for(std::map<int, int>::iterator it = matchedColumns.begin(); it != matchedColumns.end(); it++){ if(secondTuple.GetValues().at(it->first) != firstTuple.GetValues().at(it->second)) return false; } } return true; } Tuple Relation::CombineTuples(const Tuple& firstTuple, const Tuple& secondTuple){ std::vector<std::string> combinedTuples = firstTuple.GetValues(); std::vector<std::string> secondTupleValues = secondTuple.GetValues(); for(unsigned int i = 0; i < secondTupleValues.size(); i++){ std::map<int, int>::iterator it = matchedColumns.find(i); if(it == matchedColumns.end()){ combinedTuples.push_back(secondTupleValues.at(i)); } } Tuple combinedTuple = Tuple(combinedTuples); return combinedTuple; } Relation Relation::Join(Relation& toJoin){ Header firstHeader = Header(GetHeader()); Header secondHeader = toJoin.GetHeader(); Header combinedHeader = CombineHeaders(firstHeader.GetAttributes(), secondHeader.GetAttributes()); //make a new empty relation using combined header Relation relation = Relation("empty", combinedHeader); //Go through every pair of tuples //a) See if you can combine the tuples. Does every column that is supposed to match actually match? //b) If the tuples can be combined, then combine them for (const Tuple& t1 : rows){ for (const Tuple& t2 : toJoin.GetRows()){ if(isJoinable(t1, t2)){ relation.AddTuple(CombineTuples(t1, t2)); } } } return relation; } Relation Relation::Union(Relation& givenRelation){ for(std::set<Tuple>::iterator it = givenRelation.GetRows().begin(); it != givenRelation.GetRows().end(); it++){ int firstSize = GetRowsSize(); AddTuple(*it); Tuple tuple = *it; if(GetRowsSize() != firstSize){ std::cout << " "; for(unsigned int i = 0; i < header.GetAttributes().size(); i++){ std::cout << header.GetAttributes().at(i) << "=" << tuple.GetValues().at(i); if((std::size_t)i < header.GetAttributes().size() - 1){ std::cout << ", "; } } std::cout << std::endl; } } return *this; }
true
ab6f1a8b2ccf0982e299edf69c397d93cf0601e5
C++
trushton/advancedGraphics
/Final/src/ps_update_tech.cpp
UTF-8
2,112
2.625
3
[]
no_license
// // Created by trushton on 7/28/15. // #include "ps_update_tech.h" PSUpdate::PSUpdate() { } void PSUpdate::init(){ //load and compile shaders loadShaders(); //link all shaders together initShaderProgram(); //get the variables from the shaders initShaderLocations(); //create the VAO glUseProgram(program); } void PSUpdate::enable(){ glUseProgram(program); } void PSUpdate::loadShaders() { shaders[0] = loadShader("../shaders/particleVS.glsl", GL_VERTEX_SHADER); shaders[1] = loadShader("../shaders/particleGS.glsl", GL_GEOMETRY_SHADER); //shaders[2] = loadShader("../shaders/particleFS.glsl", GL_FRAGMENT_SHADER); } void PSUpdate::initShaderProgram() { program = glCreateProgram(); glAttachShader(program, shaders[0]); glAttachShader(program, shaders[1]); //glAttachShader(program, shaders[2]); const GLchar* Varyings[4]; Varyings[0] = "Type1"; Varyings[1] = "Position1"; Varyings[2] = "Velocity1"; Varyings[3] = "Age1"; glTransformFeedbackVaryings(program, 4, Varyings, GL_INTERLEAVED_ATTRIBS); glLinkProgram(program); GLint shader_status; glGetProgramiv(program, GL_LINK_STATUS, &shader_status); if (!shader_status) { std::cerr << "Unable to create shadevoid billboard_tech::initShaderLocations()"; char buffer[512]; glGetProgramInfoLog(program, 512, NULL, buffer); // inserts the error into the buffer std::cerr << buffer << std::endl; exit(1); } } void PSUpdate::initShaderLocations() { glUseProgram(program); locations["gDeltaTime"] = glGetAttribLocation(program, "gDeltaTime"); locations["gTime"] = glGetUniformLocation(program, "gTime"); locations["gRandomTexture"] = glGetUniformLocation(program, "gRandomTexture"); locations["gLauncherLife"] = glGetUniformLocation(program, "gLauncherLife"); locations["gShellLife"] = glGetUniformLocation(program, "gShellLife"); locations["gSecondaryLife"] = glGetUniformLocation(program, "gSecondaryLife"); } void PSUpdate::bind() { } void PSUpdate::unbind() { }
true
1f16cb5e89d975a844a2c38db1acffaaa3c2f364
C++
VolodymyrIvanov/Udacity-Path-Planning-Project
/src/car.cpp
UTF-8
1,878
3.109375
3
[]
no_license
/* * car.cpp * * Created on: 15.01.2018 * Author: VIvanov */ #include "car.h" Car::Car():Car(0.0, 0.0, 0.0) { } Car::Car(double s, double speed, double d) { init(s, speed, d); this->avg_steps = COSTS_AVERAGE_STEPS; this->target_lane = -1; } Car::~Car() { } void Car::init(double s, double speed, double d) { this->s = s; this->speed = speed; this->d = d; this->lane_width = DEFAULT_LANE_WIDTH; this->current_lane = get_current_lane(); this->avg_costs.insert(pair<Car_State, double>(CHANGE_TO_LEFT, 0.0)); this->avg_costs.insert(pair<Car_State, double>(KEEP_LANE, 0.0)); this->avg_costs.insert(pair<Car_State, double>(CHANGE_TO_RIGHT, 0.0)); } void Car::update(double s, double speed, double d) { this->s = s; this->speed = speed; this->d = d; this->current_lane = get_current_lane(); //First update if (this->target_lane < 0) { this->target_lane = this->current_lane; } } int Car::get_current_lane() { return this->lane_width != 0 ? this->d / this->lane_width : 0; } bool Car::is_on_target_lane() { return is_on_lane_center(target_lane); } bool Car::is_on_lane_center(int lane) { double center_line = lane * DEFAULT_LANE_WIDTH + DEFAULT_LANE_WIDTH / 2.0; return fabs(d - center_line) < CENTER_LANE_THRESHOLD; } void Car::add_costs(map<Car_State, double> costs) { for (auto& cost : costs) { double avg = avg_costs.at(cost.first); avg = (avg * avg_steps) - avg; avg += cost.second; avg /= avg_steps; avg_costs.at(cost.first) = avg; } } Car_State Car::get_min_cost_state() { pair<Car_State, double> min = *min_element(avg_costs.begin(), avg_costs.end(), &Car::compare_cost); return min.first; } bool Car::compare_cost(pair<Car_State, double> c1, pair<Car_State, double> c2) { return c1.second < c2.second; }
true
e7fa63d331a6141cd740a2302d627c725052795e
C++
cs09g/AVL
/AVL.cpp
UHC
3,583
3.375
3
[]
no_license
// Զ inorder // Ʈ̵ , ȸ ʿ 쿡 ȸ (LL LR RR RL) ǥ. #include <iostream> #include <string> #define KEYTYPE string using namespace std; class Node{ public: KEYTYPE k; Node *left, *right; }; typedef Node Node; enum R_type{ LL, LR, RR, RL }; KEYTYPE in[] = { "k", "o", "m", "i", "n", "u", "v", "e", "r", "s", "t", "y", "c", "d", "a", "b" }; Node *getTreeNode(); // Լ Node *insertAVL(Node *, KEYTYPE n_key); // AVL Ʈ Լ Node *rotateLL(Node *); Node *rotateLR(Node *); Node *rotateRR(Node *); Node *rotateRL(Node *); Node *balanceFactor(Node *); // Node *findRoot(Node *); // ֻ 带 ã Լ void Inorder(Node *); // inorder Լ int countDepth(Node *B); // ϴ Լ int R; // ȸ Ÿ void main() { Node *Tree=NULL; for (int i = 0; i < sizeof(in) / sizeof(in[0]); i++){ R = 4; Tree = insertAVL(Tree, in[i]); cout << "in " << in[i] <<" : "; Inorder(Tree); cout << "/ depth : " << countDepth(Tree); switch (R){ case LL: cout << " / rotation " << "LL"; break; case LR: cout << " / rotation " << "LR"; break; case RR: cout << " / rotation " << "RR"; break; case RL: cout << " / rotation " << "RL"; break; default: break; } cout << endl; } } Node *getTreeNode() { Node *newNode = new Node[sizeof(Node)]; return newNode; } Node *insertAVL(Node *B, KEYTYPE n_key) { // Ʈ if (B == NULL){ B = getTreeNode(); B->k = n_key; B->left = NULL; B->right = NULL; } // Ű Ű ũ ʿ else if (n_key > B->k){ B->right = insertAVL(B->right, n_key); // bf ؼ ȸ B = balanceFactor(B); } else{ B->left = insertAVL(B->left, n_key); B = balanceFactor(B); } return B; } Node *rotateLL(Node *parent) { Node *child = parent->left; parent->left = child->right; child->right = parent; return child; } Node *rotateLR(Node *parent) { Node *child = parent->left; parent->left = rotateRR(child); return rotateLL(parent); } Node *rotateRR(Node *parent) { Node *child = parent->right; parent->right = child->left; child->left = parent; return child; } Node *rotateRL(Node *parent) { Node *child = parent->right; parent->right = rotateLL(child); return rotateRR(parent); } Node *balanceFactor(Node *B) { // ¿ ڽ ̸ bf Ѵ. int bf = countDepth(B->left) - countDepth(B->right); int c_bf; // bf 1 ũ Ʈ ̰ Ƿ, // ڽ bf Ѵ. if (bf > 1){ c_bf = countDepth(B->left->left) - countDepth(B->left->right); // ڽ bf ⿡ LL, LR ȸ Ѵ. if (c_bf > 0){ R = LL; B = rotateLL(B); } else{ R = LR; B = rotateLR(B); } } // bf -1 Ʈ ̰ Ƿ, // ڽ bf Ѵ. else if (bf < -1){ c_bf = countDepth(B->right->left) - countDepth(B->right->right); if (c_bf > 0){ R = RL; B = rotateRL(B); } else{ R = RR; B = rotateRR(B); } } return B; } void Inorder(Node *B) { if (B == NULL) return; Inorder(B->left); cout << B->k << ' '; Inorder(B->right); } int countDepth(Node *B) { int depth = 0; if (B != NULL){ if (countDepth(B->left) > countDepth(B->right)) depth = 1 + countDepth(B->left); else depth = 1 + countDepth(B->right); } return depth; }
true
0b5e2de3851ada1486fee593954a7d758c255f55
C++
hjaremko/asciinem
/src/server/domain/weapon.cpp
UTF-8
882
2.796875
3
[ "MIT" ]
permissive
#include "server/domain/weapon.hpp" #include "server/domain/player.hpp" #include <utility> namespace asciinem::server::domain { weapon::weapon( std::string name, double value, int level, int attack ) : item( std::move( name ), value, level ), attack_( attack ) { } auto weapon::get_attack() const -> int { return attack_; } void weapon::set_attack( int attack ) { attack_ = attack; } void weapon::use( player& p ) { if ( get_level() <= p.get_level() ) { if ( p.has( *this ) ) { p.take_from_backpack( shared_from_this() ); if ( p.get_weapon() ) { if ( *p.get_weapon() != *this ) { p.add_to_backpack( p.get_weapon() ); } } } p.set_weapon( shared_from_this() ); } } } // namespace asciinem::server::domain
true
4c537f4f604802654d06671d4ba1b7a34ed2261d
C++
harouwu/Mini-OS
/code/threads/threadtest.cc
UTF-8
12,021
3.078125
3
[ "MIT-Modern-Variant" ]
permissive
// threadtest.cc // Simple test case for the threads assignment. // // Create two threads, and have them context switch // back and forth between themselves by calling Thread::Yield, // to illustratethe inner workings of the thread system. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "system.h" #include "thread.h" #include "synch.h" #include <sysdep.h> // testnum is set in main.cc int testnum = 1; //---------------------------------------------------------------------- // checkCMD // check user's command, only support 'ts' currently //---------------------------------------------------------------------- void checkCMD() { char cmd[100]; printf("Please input the command:\n"); scanf("%s", cmd); if ((cmd[0] == 't' || cmd[0] == 'T') && (cmd[1] == 's' || cmd[1] == 'S')) { for (int i = 0; i < MAX_THREAD_NUM; ++i) if (threadTable[i] != NULL) threadTable[i]->Print(); } else if ((cmd[0] == 'l' || cmd[0] == 'L') && (cmd[1] == 'T' || cmd[1] == 't')) { printf("lastScheduleTime: %d, currentTime: %d, main's tickCount: %d, TimeQuantum: %d\n", lastScheduleTime, stats->totalTicks, currentThread->getTickCount(), currentThread->getTimeQuantum()); if (threadTable[1] != NULL) printf("Priority: main %d, t1 %d\n", currentThread->getPriority(), threadTable[1]->getPriority()); } else if ((cmd[0] == 'l' || cmd[0] == 'L') && (cmd[1] == 'P' || cmd[1] == 'p')) { for (int i = 0; i < MAX_THREAD_NUM; ++i) if (threadTable[i] != NULL) printf("Thread \"%s\" (tid: %d) has priority %d\n", threadTable[i]->getName(), threadTable[i]->getTID(), threadTable[i]->getPriority()); } } //---------------------------------------------------------------------- // SimpleThread // Loop 5 times, yielding the CPU to another ready thread // each iteration. // // "which" is simply a number identifying the thread, for debugging // purposes. //---------------------------------------------------------------------- void SimpleThread(int which) { int num; for (num = 0; num < 10; num++) { printf("*** thread \"%s\" (uid: %d, tid: %d) looped %d times\n", currentThread->getName(), currentThread->getUID(), currentThread->getTID(), num); interrupt->OneTick(); //currentThread->Yield(); } } //---------------------------------------------------------------------- // ThreadTest1 // Set up a ping-pong between two threads, by forking a thread // to call SimpleThread, and then calling SimpleThread ourselves. //---------------------------------------------------------------------- void ThreadTest1() { DEBUG('t', "Entering ThreadTest1"); Thread *t = new Thread("forked thread"); t->Fork(SimpleThread, 1); SimpleThread(0); } //---------------------------------------------------------------------- // ThreadTest2 // Set up 200 threads to test the limitation of threads' number //---------------------------------------------------------------------- void ThreadTest2() { for (int i = 0; i < 200; ++i) { Thread *t = new Thread("testcase"); if (t->getTID() == -1) { printf("Error: Cannot create new thread (Exceed the threshold)\n"); delete t; } else { printf("Create thread successfully (uid: %d, tid: %d)\n", t->getUID(), t->getTID()); t->Fork(SimpleThread, 0); } } // main thread loop infinitely, checking user's command // while (1) // { // checkCMD(); // currentThread->Yield(); // } } void ThreadTest3() { Thread *t1 = new Thread("t1"); Thread *t2 = new Thread("t2"); Thread *t3 = new Thread("t3"); t1->setPriority(6); t2->setPriority(30); t3->setPriority(100); t1->Fork(SimpleThread, 0); t2->Fork(SimpleThread, 0); t3->Fork(SimpleThread, 0); currentThread->setTimeQuantum(8); // main thread loop infinitely, checking user's command while (1) { checkCMD(); interrupt->OneTick(); } } int readcnt = 0; Semaphore *mutex, *w; int sharedValue; void Reader(int which) { for (int i = 0; i < 40; ++i) { mutex->P(); readcnt++; if (readcnt == 1) w->P(); mutex->V(); // read the data printf("Thread \"%s\" (tid: %d) is reading. sharedValue: %d\n", currentThread->getName(), currentThread->getTID(), sharedValue); mutex->P(); readcnt--; if (readcnt == 0) w->V(); mutex->V(); currentThread->Yield(); } } void Writer(int which) { for (int i = 0; i < 20; ++i) { w->P(); // write the data sharedValue = Random() % 1000; printf("Thread \"%s\" (tid: %d) is writing. sharedValue: %d\n", currentThread->getName(), currentThread->getTID(), sharedValue); w->V(); currentThread->Yield(); } } void ReaderAndWriter() { mutex = new Semaphore("mutex", 1); w = new Semaphore("w", 1); sharedValue = 100; Thread *t; for (int i = 0; i < 3; ++i) { t = new Thread("Writer"); t->setPriority(Random() % 20); t->Fork(Writer, 0); } for (int i = 0; i < 10; ++i) { t = new Thread("Reader"); t->setPriority(Random() % 20); t->Fork(Reader, 0); } } #define PRODUCER_NUM 10 #define CONSUMER_NUM 10 #define MAX_NUM 4 Lock *lock; Condition *full, *empty; int buffer[MAX_NUM] = {0}; int sum; void Producer(int which) { lock->Acquire(); while (sum == MAX_NUM) { printf("Thread \"%s\" (tid: %d) sleeping. (No available slot)\n", currentThread->getName(), currentThread->getTID()); empty->Wait(lock); } for (int i = 0; i < MAX_NUM; ++i) if (buffer[i] == 0) { buffer[i] = 1; printf("Thread \"%s\" (tid: %d) put an item at buffer %d.\n", currentThread->getName(), currentThread->getTID(), i); break; } sum++; full->Signal(lock); lock->Release(); } void Consumer(int which) { lock->Acquire(); while (sum == 0) { printf("Thread \"%s\" (tid: %d) sleeping. (No available item)\n", currentThread->getName(), currentThread->getTID()); full->Wait(lock); } for (int i = 0; i < MAX_NUM; ++i) if (buffer[i] == 1) { buffer[i] = 0; printf("Thread \"%s\" (tid: %d) consume an item at buffer %d.\n", currentThread->getName(), currentThread->getTID(), i); break; } sum--; empty->Signal(lock); lock->Release(); } void ProducerAndConsumer() { lock = new Lock("lock"); full = new Condition("full"); empty = new Condition("empty"); sum = 0; Thread *t; currentThread->setTimeQuantum(200); for (int i = 0; i < PRODUCER_NUM; ++i) { t = new Thread("Producer"); t->setPriority(Random() % 20); t->Fork(Producer, 0); } for (int i = 0; i < CONSUMER_NUM; ++i) { t = new Thread("Consumer"); t->setPriority(Random() % 20); t->Fork(Consumer, 0); } } Barrier *b; void NaiveThread(int which) { b->Wait(); printf("Thread \"%s\" (tid: %d) running\n", currentThread->getName(), currentThread->getTID()); } void TestBarrier() { b = new Barrier("test", 5); Thread *t; for (int i = 0; i < 20; ++i) { t = new Thread("Naive"); t->Fork(NaiveThread, 0); t->setPriority(Random() % 20); } } RWlock *rwlock; void NewReader(int which) { for (int i = 0; i < 40; ++i) { rwlock->rdlock(); // read the data printf("Thread \"%s\" (tid: %d) is reading. sharedValue: %d\n", currentThread->getName(), currentThread->getTID(), sharedValue); rwlock->unlock(); currentThread->Yield(); } } void NewWriter(int which) { for (int i = 0; i < 20; ++i) { rwlock->wrlock(); // write the data sharedValue = Random() % 1000; printf("Thread \"%s\" (tid: %d) is writing. sharedValue: %d\n", currentThread->getName(), currentThread->getTID(), sharedValue); rwlock->unlock(); currentThread->Yield(); } } void NewReaderAndWriter() { rwlock = new RWlock("rwlock"); sharedValue = 100; Thread *t; for (int i = 0; i < 3; ++i) { t = new Thread("Writer"); t->setPriority(Random() % 20); t->Fork(NewWriter, 0); } for (int i = 0; i < 10; ++i) { t = new Thread("Reader"); t->setPriority(Random() % 20); t->Fork(NewReader, 0); } // while (1) // { // checkCMD(); // currentThread->Yield(); // } } #ifdef USER_PROGRAM extern void StartProcess(char *filename); void usertest1(int which) { char *filename = "test/d"; StartProcess(filename); } void usertest2(int which) { char *filename = "test/e"; StartProcess(filename); } void doubleUserTest() { Thread *t1 = new Thread("t1"); Thread *t2 = new Thread("t2"); t1->Fork(usertest1, 1); t2->Fork(usertest2, 1); } #endif //---------------------------------------------------------------------- // ThreadTest // Invoke a test routine. //---------------------------------------------------------------------- void postMsgThread(int which) { int qid = currentThread->applyMessageQueue(); currentThread->postMsg(qid, "hello"); currentThread->postMsg(qid, "world!"); } void getMsgThread(int which) { char msg[100]; currentThread->getMsg(0, msg); printf("%s\n", msg); currentThread->getMsg(0, msg); printf("%s\n", msg); } void ThreadTest4() { Thread *t1 = new Thread("t1"); Thread *t2 = new Thread("t2"); t1->setPriority(30); t1->Fork(postMsgThread, 0); t2->Fork(getMsgThread, 0); } Lock *lock1, *lock2, *lock3; void getLock1First(int which) { lock1->Acquire(); printf("%s get Lock1\n", currentThread->getName()); currentThread->Yield(); printf("%s trying to get lock2\n", currentThread->getName()); lock2->Acquire(); printf("%s get Lock2\n", currentThread->getName()); lock2->Release(); lock1->Release(); } void getLock2First(int which) { lock2->Acquire(); printf("%s get Lock2\n", currentThread->getName()); currentThread->Yield(); printf("%s trying to get lock3\n", currentThread->getName()); lock3->Acquire(); printf("%s get Lock3\n", currentThread->getName()); lock3->Release(); lock2->Release(); } void getLock3First(int which) { lock3->Acquire(); printf("%s get Lock3\n", currentThread->getName()); currentThread->Yield(); printf("%s trying to get lock1\n", currentThread->getName()); lock1->Acquire(); printf("%s get Lock1\n", currentThread->getName()); lock1->Release(); // lock3->Release(); } void DeadLockTest() { lock1 = new Lock("lock1"); lock2 = new Lock("lock2"); lock3 = new Lock("lock3"); Thread *t1 = new Thread("t1"); Thread *t2 = new Thread("t2"); Thread *t3 = new Thread("t3"); t1->setPriority(30); t2->setPriority(30); t3->setPriority(30); t1->Fork(getLock1First, 0); t2->Fork(getLock2First, 0); t3->Fork(getLock3First, 0); // currentThread->Yield(); // currentThread->Yield(); // if (DeadLockDetect()) // printf("DeadLock occurs!!\n"); // else // printf("No DeadLock\n"); } void ThreadTest() { switch (testnum) { case 1: DeadLockTest(); break; default: printf("No test specified.\n"); break; } }
true
2780c761cb03ed5eaacc0679944c8cd1ed9e20f8
C++
boyplus/competitive-programming
/codeforces/max.cpp
UTF-8
374
2.625
3
[]
no_license
#include <cstdio> #include <algorithm> using namespace std; int arr[100000]; int main(){ int n,k; scanf("%d %d",&n,&k); for(int i=0;i<n;i++){ scanf("%d",&arr[i]); } sort(arr,arr+n); int min = 2e9,c=0; for(int i=k-1;i<n;i++){ int temp = arr[i] - arr[c]; //printf("in %d %d\n",i,c); if(temp < min){ min = temp; } c++; } printf("%d\n",min); return 0; }
true
36f4a1214d48b85c7e60f203e90410f0a4a3eca7
C++
AnastasiyaNovikovaa/Laba-4.1
/Laba 4.1/Main.cpp
UTF-8
3,182
3.390625
3
[]
no_license
//#include "pch.h" #include <iostream> #include "LinkedList.h" #include "LinkedList.cpp" int main() { setlocale(LC_ALL, "Russian"); cout << "Hello! Laboratory work #1 \n"; cout << "by Novikova Anastasiya 7302\n"; cout << "You are welcome!"; cout << endl; LinkedList<int> lst; lst.push_back(4); lst.push_back(1); lst.push_back(5); lst.push_back(7); lst.push_front(2); cout << "------------------------------------------------------------------"; cout << endl; cout << "The first list:\n"; cout << lst; cout << endl; cout << "Size of list= " << lst.get_size(); cout << endl; lst.pop_front(); cout << "list after deleting the first item:\n"; for (size_t i = 0; i < lst.get_size(); i++) { cout << lst.at(i) << " "; } cout << endl; cout << "List output without using the AT function:\n"; lst.print_to_console(); cout << endl; lst.pop_back(); cout << "list after deleting last item:\n"; for (size_t i = 0; i < lst.get_size(); i++) { cout << lst.at(i) << " "; } cout << endl; lst.insert(2, -1); cout << "the list after adding the number -1 at index 2 :\n"; for (size_t i = 0; i < lst.get_size(); i++) { cout << lst.at(i) << " "; } cout << endl; lst.remove(1); cout << "the list after deleting the number at index 5 :\n"; for (size_t i = 0; i < lst.get_size(); i++) { cout << lst.at(i) << " "; } cout << endl; lst.set(2, 2); cout << "list after replacing the number of 2 positions on the number 2:\n"; for (size_t i = 0; i < lst.get_size(); i++) { cout << lst.at(i) << " "; } cout << endl; cout << "Deleting first list\n"; lst.clear(); cout << endl; cout << "------------------------------------------------------------------"; cout << endl; LinkedList<char> lst2; lst2.push_back('a'); lst2.push_back('b'); lst2.push_back('h'); lst2.push_back('t'); lst2.push_front('y'); cout << "The second list:\n"; for (size_t i = 0; i < lst2.get_size(); i++) { cout << lst2.at(i) << " "; } cout << endl; cout << "Size of list2= " << lst2.get_size(); cout << endl; lst2.pop_front(); cout << "list2 after deleting the first item:\n"; for (size_t i = 0; i < lst2.get_size(); i++) { cout << lst2.at(i) << " "; } cout << endl; cout << "List2 output without using the AT function:\n"; lst2.print_to_console(); cout << endl; lst2.pop_back(); cout << "List2 after deleting last item:\n"; for (size_t i = 0; i < lst2.get_size(); i++) { cout << lst2.at(i) << " "; } cout << endl; lst2.insert(2, 'z'); cout << "The list2 after adding the number z at index 2 :\n"; for (size_t i = 0; i < lst2.get_size(); i++) { cout << lst2.at(i) << " "; } cout << endl; lst2.remove(1); cout << "The list after deleting the number at index 1 :\n"; for (size_t i = 0; i < lst2.get_size(); i++) { cout << lst2.at(i) << " "; } cout << endl; lst2.set(1, 'e'); cout << "List after replacing the number of 1 positions on the symbol e:\n"; for (size_t i = 0; i < lst2.get_size(); i++) { cout << lst2.at(i) << " "; } cout << endl; cout << "Deleting second list\n"; lst2.clear(); cout << endl; cout << "List is empty"; cout << endl; cout << "Bye, Have a nice day!\n"; cout << endl; system("pause"); }
true
41174b1d6a2757de1c3263b5cfde5063647dce6b
C++
Ezibenroc/satsolver
/src/structures/formula.h
UTF-8
8,339
2.703125
3
[ "MIT" ]
permissive
#ifndef STRUCTURES_FORMULA_H #define STRUCTURES_FORMULA_H #include <vector> #include <string> #include <memory> #include <stack> #include <unordered_set> #include "solvers/abstract_assistant.h" #include "structures/clause.h" #include "structures/affectation.h" #include "structures/deductions.h" #include "structures/CL_proof.h" namespace satsolver { // Deux foncteurs utilisés pour l'ensemble to_do. struct Equal { bool operator() (const std::pair<int,unsigned int> &a, const std::pair<int,unsigned int> &b) const { return (a.first == b.first); } }; struct Hash { size_t operator() (const std::pair<int,unsigned int> &a) const { return a.first ; } }; class Formula { private : Affectation *aff ; std::vector<std::shared_ptr<satsolver::Clause>> clauses ; int nb_variables ; std::vector<std::pair<int,bool>> mem ; // littéraux dans l'ordre où on les affecte (vrai si déduit, faux si parié) std::unordered_set<std::pair<int,unsigned int>,Hash,Equal> to_do ; // utilisé dans WL, littéraux déduits pas encore affectés (d’autres opérations sont « en cours ») // le second entier est l'indice de la clause ayant permi de déduire le littéral Deductions *ded ; // graphe orienté représentant les déductions unsigned int ded_depth ; // profondeur courante de l'arbre de déductions // Affectation d'un litéral x // Si WITH_WL, renvoie faux ssi un conflit est généré // Si WITH_WL et un conflit est généré, alors clause1 et clause2 sont mis à jour avec les indices des clauses en conflit (ainsi que literal) // si création d'un état inconsistant, clause1 est mis à jour avec l'indice de la clause apprise (clause2 est mis à -1) // si création d'un état inconsistant, clause_assistant est mis à jour avec l'indice de la clause apprise, sinon avec -1 bool set_true(int x, int *clause1, int *clause2, int *literal, theorysolver::AbstractAssistant *assistant, int *clause_assistant) ; public : Formula(std::vector<std::shared_ptr<satsolver::Clause>> v, int nb_variables) ; Formula(std::vector<std::shared_ptr<satsolver::Clause>> v, int nb_variables, std::vector<unsigned int> *affected_literals) ; Formula(const Formula&); Formula& operator=(const Formula &that); ~Formula() ; // Renvoie la représentation textuelle de la formule std::string to_string() ; std::string to_string2() ; // Renvoie un ensemble d'ensembles d'entiers, selon l'affectation // Chaque ensemble de cet ensemble représente une clause // Une clause vraie ne sera pas mise dans l'ensemble // Une clause fausse sera un ensemble vide // Les clauses ne contiendront que des littéraux indeterminés std::set<std::set<int> > to_set() ; std::set<Clause*> to_clauses_set() const; std::vector<std::shared_ptr<Clause>>& to_clauses_vector() ; // Ajoute une clause, et renvoie son index dans la formule. unsigned int add_clause(std::shared_ptr<satsolver::Clause> clause); // Déduction de l'affectation d'un littéral // Si WITH_WL, renvoie faux ssi conflit // Sinon, renvoie faux ssi x est déjà affecté, à faux // claude_id est l'indice de la clause qui est l'origine de cette déduction // pas de clause origine si clause_id = -1 (survient lors des déductions des littéraux isolés) // clause1 et clause2 sont mis à jour avec les indices des clauses en conflit // si création d'un état inconsistant, clause1 est mis à jour avec l'indice de la clause apprise (clause2 est mis à -1) // si création d'un état inconsistant, clause_assistant est mis à jour avec l'indice de la clause apprise, sinon avec -1 bool deduce_true(int x, int clause_id, int *clause1, int *clause2, int *literal, theorysolver::AbstractAssistant *assistant, int *clause_assistant) ; bool deduce_false(int x, int clause_id, theorysolver::AbstractAssistant *assistant, int *clause_assistant) ; // Pari sur l'affectation d'un littéral // Si WITH_WL, renvoie faux ssi conflit // Sinon, renvoie faux ssi x est déjà affecté, à faux // clause1 et clause2 sont mis à jour avec les indices des clauses en conflit // si création d'un état inconsistant, clause1 est mis à jour avec l'indice de la clause apprise (clause2 est mis à -1) // si création d'un état inconsistant, clause_assistant est mis à jour avec l'indice de la clause apprise, sinon avec -1 bool bet_true(int x, int *clause1, int *clause2, int *literal, theorysolver::AbstractAssistant *assistant, int *clause_assistant) ; bool bet_false(int x, int *clause1, int *clause2, int *literal, theorysolver::AbstractAssistant *assistant, int *clause_assistant) ; // Retourne en arrière jusqu'au dernier pari // Renvoie le dernier littéral parié (0 si inexistant) int back(theorysolver::AbstractAssistant *assistant) ; // Fait plusieurs backtrack, jusqu'à obtenir la profondeur de déduction donnée int back(theorysolver::AbstractAssistant *assistant, unsigned int depth) ; // Renvoie un monome de la formule (0 si inexistant) int monome(int *clause_id) ; // Renvoie un litéral isolé de la formule (0 si inexistant) int isolated_literal(int *clause_id) ; // Renvoie vrai ssi la formule ne contient pas de clauses bool is_empty() const; // Renvoie le nombre de variables int get_nb_variables() const; // Renvoie la taille de la formule ; long unsigned int get_size() const ; // Renvoie vrai ssi la formule contient une clause vide bool contains_empty_clause() const; // Determines whether one of the clauses is evaluated to false. bool contains_false_clause(int *clause_id) const; // Determines whether all the clauses are evaluated to true. bool only_true_clauses(int *clause_id) const; // Supprime toute les clauses contenant d'autres clauses // Affecte tous les monomes // Assez lourd (nombre de clauses au carré fois le nombre de variables) // À utiliser seulement à l'initialisation void clean(std::vector<unsigned int> *affected_literals) ; // Renvoie la pile d'affectations // Ne pas utiliser en dehors des tests unitaires std::vector<std::pair<int,bool>> get_mem() ; // Renvoie l'affectation // Ne pas utiliser en dehors des tests unitaires, ou de la fin de DPLL Affectation *get_aff() ; // Renvoie les déductions Deductions *get_ded() ; // Renvoie la profondeur de déduction int get_ded_depth() ; // Renvoie un vecteur de littéraux inconnus std::vector<int> get_unknown_literals (void) const ; // Renvoie un littéral de la formule // Pré-condition : la formule n'est pas vide, et n'est pas le monome clause vide int choose_literal_dumb() const; // Choisis un littéral aléatoirement dans la formule // Pré-condition : le générateur pseudo-aléatoire a été initialisé correctement int choose_literal_random() const ; // Choisis un littéral avec l'heuristique MOMS int choose_literal_moms() const ; // Choisis un littéral avec l'heuristique DLIS (variante) int choose_literal_dlis() const ; // Choisis un littéral selon l'heuristique spécifiée int choose_literal(int choice) ; // Apprentissage d'une clause // Le littéral donné doit être en conflis dans la clause d'indice donné // Clause_id est mis à jour avec l'indice de la clause apprise // New_depth est mis à jour avec la profondeur vers laquelle backtracker // Renvoie un littéral l que l'on doit déduire après le backtrack (sans déduire le dernier littéral backtracké) int learn_clause(CLProof *proof, int *clause_id, unsigned int *new_depth, int literal, Clause *learned_clause) ; // Renvoie le dernier paris int last_bet() ; }; } #endif
true
ddc8b3443858902a4e1e8522b5cc31bfa2f2034e
C++
ronee12/Uva-Solutions
/rtable10195.cpp
UTF-8
379
2.84375
3
[]
no_license
#include<stdio.h> #include<math.h> int main() { double r,s,p,a,b,c; while(scanf("%lf%lf%lf",&a,&b,&c)!=EOF) { if(a!=0&&b!=0&&c!=0) { s=(a+b+c)/2; if(a<=s&&b<=s&&c<=s) { p=s*(s-a)*(s-b)*(s-c); r=sqrt(p)/s; printf("The radius of the round table is: %.3lf\n",r); } } else printf("The radius of the round table is: 0.000\n"); } return 0; }
true
5cc6b30d9207cd480edac6c53fe5d74c7e3bd432
C++
FrankenRom/android_frameworks_base
/tools/aapt2/java/AnnotationProcessor.h
UTF-8
2,132
2.546875
3
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef AAPT_JAVA_ANNOTATIONPROCESSOR_H #define AAPT_JAVA_ANNOTATIONPROCESSOR_H #include <sstream> #include <string> #include "androidfw/StringPiece.h" namespace aapt { /** * Builds a JavaDoc comment from a set of XML comments. * This will also look for instances of @SystemApi and convert them to * actual Java annotations. * * Example: * * Input XML: * * <!-- This is meant to be hidden because * It is system api. Also it is @deprecated * @SystemApi * --> * * Output JavaDoc: * * /\* * * This is meant to be hidden because * * It is system api. Also it is @deprecated * *\/ * * Output Annotations: * * @Deprecated * @android.annotation.SystemApi * */ class AnnotationProcessor { public: /** * Adds more comments. Since resources can have various values with different * configurations, * we need to collect all the comments. */ void AppendComment(const android::StringPiece& comment); void AppendNewLine(); /** * Writes the comments and annotations to the stream, with the given prefix * before each line. */ void WriteToStream(std::ostream* out, const android::StringPiece& prefix) const; private: enum : uint32_t { kDeprecated = 0x01, kSystemApi = 0x02, }; std::stringstream comment_; std::stringstream mAnnotations; bool has_comments_ = false; uint32_t annotation_bit_mask_ = 0; void AppendCommentLine(std::string& line); }; } // namespace aapt #endif /* AAPT_JAVA_ANNOTATIONPROCESSOR_H */
true
52294f7658b768392814afbcbd00be2140a08c9f
C++
zhaishuai/ERASuffixTree
/tree/iterators/TreeNodeNodeIterator.hpp
UTF-8
1,059
2.875
3
[]
no_license
#pragma once #include <iterator> #include "../TreeNodeAccessor.hpp" #include "../TreeEdgeAccessor.hpp" #include "TreeNodeEdgeIterator.hpp" class TreeNodeNodeIterator : public std::iterator<std::forward_iterator_tag, TreeNode*> { public: TreeNodeNodeIterator(const TreeNodeNodeIterator& it) : edgeIt(it.edgeIt) { } TreeNodeNodeIterator(TreeNodeEdgeIterator edgeIt) : edgeIt(edgeIt) { } TreeNodeNodeIterator& operator++() { edgeIt++; return *this; }; TreeNodeNodeIterator operator++(int) { TreeNodeNodeIterator tmp(*this); edgeIt++; return tmp; }; bool operator==(const TreeNodeNodeIterator& other) const { return edgeIt == other.edgeIt; } bool operator!=(const TreeNodeNodeIterator& other) const { return !(*this == other); } bool isDefined() const { return edgeIt.isDefined(); } TreeNodeAccessor getAccessor() const; TreeNode* operator->() const; private: TreeNodeEdgeIterator edgeIt; };
true
272c0bc40311fac2bc6b68cbf6dd2729530bae85
C++
sinisaabramovic/cpp_ogl
/RegocFX/source/window/Window.cpp
UTF-8
4,015
2.5625
3
[]
no_license
// // Window.cpp // RegocFX // // Created by Sinisa Abramovic on 04/09/2018. // Copyright © 2018 Sinisa Abramovic. All rights reserved. // #include "Window.hpp" Window::Window(const GLint &windowWidth, const GLint &windowHeight) : width(windowWidth), height(windowHeight), mouseFirstMoved(true) { xChange = 0.0f; yChange = 0.0f; for (size_t i = 0; i < 1024; i++) { keys[i] = 0; } } Window::Window() : width(WND_CONST_WIDTH), height(WND_CONST_HEIGHT), mouseFirstMoved(true) { xChange = 0.0f; yChange = 0.0f; for (size_t i = 0; i < 1024; i++) { keys[i] = 0; } } int Window::windowInitialise() { // Initialise GLFW if (!glfwInit()) { printf("GLFW initialisation failed!"); glfwTerminate(); return 1; } glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X #endif // Create the window mainWindowContext = glfwCreateWindow(width, height, "Regoc : Test OpenGL ", NULL, NULL); if (!mainWindowContext) { printf("GLFW window creation failed!"); glfwTerminate(); return 1; } // Get Buffer Size information glfwGetFramebufferSize(mainWindowContext, &bufferWidth, &bufferHeight); // Set context for GLEW to use glfwMakeContextCurrent(mainWindowContext); // Handle key and mouse input createInputCallbacks(); glfwSetInputMode(mainWindowContext, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // Allow modern extension features glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { printf("GLEW initialisation failed!"); glfwDestroyWindow(mainWindowContext); glfwTerminate(); return 1; } glEnable(GL_DEPTH_TEST); glfwSetWindowUserPointer(mainWindowContext, this); // Setup Viewport size // Setup Viewport size glViewport(0, 0, bufferWidth, bufferHeight); return 1; } Window::~Window() { glfwDestroyWindow(mainWindowContext); glfwTerminate(); } void Window::handleKeys(GLFWwindow *window, int key, int keycode, int action, int mode) { Window* castWindow = static_cast<Window*>(glfwGetWindowUserPointer(window)); if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS){ glfwSetWindowShouldClose(window, GL_TRUE); } if(key >= 0 && key < 1024){ if(action == GLFW_PRESS){ castWindow->keys[key] = true; //printf("Pressed: %d\n", key); }else if (action == GLFW_RELEASE){ castWindow->keys[key] = false; //printf("Released: %d\n", key); } } } void Window::createInputCallbacks() { glfwSetKeyCallback(mainWindowContext, handleKeys); glfwSetCursorPosCallback(mainWindowContext, handleMouse); } void Window::handleMouse(GLFWwindow *window, double xPos, double yPos) { Window* castWindow = static_cast<Window*>(glfwGetWindowUserPointer(window)); if(castWindow->mouseFirstMoved){ castWindow->lastX = xPos; castWindow->lastY = yPos; castWindow->mouseFirstMoved = false; } castWindow->xChange = xPos - castWindow->lastX; // For invert y cordinates //castWindow->yChange = yPos - castWindow->lastY; castWindow->yChange = castWindow->lastY - yPos; castWindow->lastX = xPos; castWindow->lastY = yPos; //printf("X:%.6f, Y:%.6f\n", castWindow->xChange, castWindow->yChange); } GLfloat Window::getYChanged() { GLfloat theChange = yChange; yChange = 0.0f; return theChange; } GLfloat Window::getXChanged() { GLfloat theChange = xChange; xChange = 0.0f; return theChange; }
true
3c2e115183913bd0c83881c5d5b5aa859cc9e97b
C++
VetalosUA-KR/WDP
/do-1-kolosa/recursion/WDI.cpp
KOI8-R
640
3.125
3
[]
no_license
#include<iostream> /// using namespace std; int fun_1_1(int n) { if(n == 0) return 3; else return 3 * fun_1_1(n-1) + 2; } int fun_1_2(int n) { if(n == 1) return -5; else return (fun_1_2(n-1)*2)-1; } int fun_1_3(int n) { if(n == 0) return 11; else return (fun_1_3(n-1)+1)/n; } int fun_1_4(int n) { if(n == 0) return fun_1_4(1); else if (n == 1) return 4; else return (3 * fun_1_4(n-1)) + (2 * fun_1_4(n-2)); } int fun_1_5(int n) { if(n == 0) return 2; else if (n == 1) return 3; else return (2 * fun_1_5(n-1)) - (fun_1_5(n-2)+1); } int main () { return 0; }
true
d884a03c564541436fc7bde8a9f1f6fdf06ad288
C++
eayvali/ROS_projects
/Chase_a_Ball/catkin_ws/src/ball_chaser/src/process_image.cpp
UTF-8
3,711
3.125
3
[ "MIT" ]
permissive
#include "ros/ros.h" #include "ball_chaser/DriveToTarget.h" #include <sensor_msgs/Image.h> // Define a global client that can request services ros::ServiceClient client; // This function calls the command_robot service to drive the robot in the specified direction void drive_robot(float lin_x, float ang_z) { // Request a service and pass the velocities to it to drive the robot ROS_INFO_STREAM("Commanding the robot to chase the ball"); ball_chaser::DriveToTarget srv; srv.request.linear_x = lin_x; srv.request.angular_z = ang_z; // Call the command_robot service and pass the requested velocities if (!client.call(srv)) ROS_ERROR("Failed to call service command_robot"); } // This callback function continuously executes and reads the image data void process_image_callback(const sensor_msgs::Image img) { int white_pixel = 255; int num_channels =3; //RGB bool ball_in_view = false; //img: 1D array [[R00,G00,B00],...,[R0r,G0r,0r], [R10,G10,B10],..] int col=0; // x-pixel coordinate int ball_col=0; //detected ball position (x-pixel) int ball_dia=0;// ball diameter in pixels int col_cnt[img.width]={0}; // count white pixels along each row ( max column sum is proxy for ball center) int max_cnt=0; float lin_x=0; float ang_z=0; //ROS_INFO("height: %d, width: %d, step: %d", img.height, img.width, img.step); //800,800,2400 // Loop through each pixel in the image and check if there's a bright white one for (int i = 0; i < img.height * img.step; i += 3) { if(img.data[i]==white_pixel && img.data[i+1]==white_pixel && img.data[i+2]==white_pixel) { col=(i % img.step)/num_channels; col_cnt[col]+=1; } } //Find ball_col: column with the max white pixels for (int i=0;i<img.width;i++){ if (col_cnt[i]>max_cnt){ max_cnt=col_cnt[i]; ball_col=i; //assign ball column in pixels ball_dia=max_cnt; //ball diameter in pixels } } //Need at least 10 white pixels to define a ball if ((ball_dia>10) && (ball_dia<0.75*img.height)){ ball_in_view=true; ROS_INFO("Ball detected!"); // Identify if this pixel falls in the left, mid, or right side of the image // Depending on the white ball position, call the drive_bot function and pass velocities to it lin_x=std::min(0.1*(img.height/ball_dia),0.5); ang_z=1.0; if (ball_col < img.width/3){ drive_robot(lin_x, ang_z); ROS_INFO("Ball pos: left"); } else if (ball_col < 2*img.width/3){ drive_robot(lin_x, 0.0); ROS_INFO("Ball pos: center"); } else { drive_robot(lin_x, -ang_z); ROS_INFO("Ball pos: right"); } } // Request a stop when there's no white ball seen by the camera if (ball_in_view==false){ drive_robot(0.0,0.0); } ROS_INFO("ball_in_view: %d ,ball_column: %d, ball_diameter: %d",ball_in_view, ball_col, ball_dia); ROS_INFO("Commands: lin_x: %f, ang_z: %f", lin_x, ang_z); } int main(int argc, char** argv) { // Initialize the process_image node and create a handle to it ros::init(argc, argv, "process_image"); ros::NodeHandle n; // Define a client service capable of requesting services from command_robot client = n.serviceClient<ball_chaser::DriveToTarget>("/ball_chaser/command_robot"); // Subscribe to /camera/rgb/image_raw topic to read the image data inside the process_image_callback function ros::Subscriber sub1 = n.subscribe("/camera/rgb/image_raw", 10, process_image_callback); // Handle ROS communication events ros::spin(); return 0; }
true
62d98a120f2119edcd2d513e773ee6674377bcdb
C++
SumitNagpal94/MCA
/C++/CollegeCodes/learn_conversion1.cpp
UTF-8
367
3.390625
3
[]
no_license
#include<iostream> using namespace std; class B { public: int a,b; void display() { cout<<"a is "<<a<<" and b is "<<b; } }; class A { int a,b; public: A(int x,int y) { a=x; b=y; } operator B() { B x; x.a=a; x.b=b; return x; } }; int main() { B b; A a(3,4); b=a; b.display(); return 0; }
true
76e5385c694cb34943869970e53c3bd58dff32ae
C++
taivop/eth-algolab
/chunks/cgal/elementary/predicates.cpp
UTF-8
1,991
3.125
3
[]
no_license
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <iostream> using namespace std; typedef CGAL::Exact_predicates_inexact_constructions_kernel K; int main() { cout << "CGAL PREDICATES" << endl; // Documentation under 'Global kernel functions': http://doc.cgal.org/latest/Kernel_23/group__kernel__global__function.html cout << "---- In-circle test: are points x_i inside the circle defined by {p, q, r}? ----" << endl; // http://doc.cgal.org/latest/Kernel_23/group__side__of__bounded__circle__grp.html K::Point_2 p(0, 0), q(1,1), r(2,0); K::Point_2 x1(-1, -1); K::Point_2 x2(0, 0); K::Point_2 x3(0, 1); K::Point_2 x4(1, 4); K::Point_2 x5(1, -1); K::Point_2 x6(1, 0); cout << "x1 side: " << side_of_bounded_circle(p, q, r, x1) << endl; cout << "x2 side: " << side_of_bounded_circle(p, q, r, x2) << endl; cout << "x3 side: " << side_of_bounded_circle(p, q, r, x3) << endl; cout << "x4 side: " << side_of_bounded_circle(p, q, r, x4) << endl; cout << "x5 side: " << side_of_bounded_circle(p, q, r, x5) << endl; cout << "x6 side: " << side_of_bounded_circle(p, q, r, x6) << endl; cout << "---- Orientation test (left-turn/right-turn/collinear) ----" << endl; // http://doc.cgal.org/latest/Kernel_23/group__orientation__grp.html K::Point_2 a1(0, 0), a2(1, 1); K::Point_2 b1(0, 0); K::Point_2 b2(2, 2); K::Point_2 b3(-1, -1); K::Point_2 b4(-1, 0); K::Point_2 b5(1, 0); K::Point_2 b6(0, 1); cout << "b1 orientation: " << CGAL::orientation(a1, a2, b1) << endl; cout << "b2 orientation: " << CGAL::orientation(a1, a2, b2) << endl; cout << "b3 orientation: " << CGAL::orientation(a1, a2, b3) << endl; cout << "b4 orientation: " << CGAL::orientation(a1, a2, b4) << endl; cout << "b5 orientation: " << CGAL::orientation(a1, a2, b5) << endl; cout << "b6 orientation: " << CGAL::orientation(a1, a2, b6) << endl; cout << "b5 is a right turn (should be!): " << (CGAL::orientation(a1, a2, b5) == CGAL::RIGHT_TURN) << endl; return 0; }
true
301e1e929d9f4c0356446bfc5f6acd8ec91430d0
C++
3s1d/fanet-base
/Src/fanet/frame/fname.cpp
UTF-8
716
2.609375
3
[]
no_license
/* * fname.cpp * * Created on: Sep 21, 2018 * Author: sid */ #include <string.h> #include "fname.h" int16_t FanetFrameName::serialize(uint8_t*& buffer) { const char *name = "todo"; /* prepare storage */ if(payload != nullptr) delete [] payload; payloadLength = strlen(name); payload = new uint8_t[payloadLength]; /* copy pilot name */ //note: zero termination not required memcpy(payload, name, payloadLength * sizeof(char)); return FanetFrame::serialize(buffer); } void FanetFrameName::decode(const uint8_t *payload, const uint16_t len, FanetNeighbor *neighbor) { if(len == 0 || payload == nullptr || neighbor == nullptr) return; neighbor->setName((const char *)payload, len); }
true
cac9f5e931a481ea37723f5b8ccc64b239046b57
C++
nhitran-tuni/programming2
/student/02/mean/main.cpp
UTF-8
687
3.96875
4
[]
no_license
#include <iostream> using namespace std; void mean ( int count_number) { int i = 1; float sum = 0.0; while ( i < count_number + 1) { cout << "Input " << i << ". number: "; float num; cin >> num; sum = sum + num; i ++; } if (count_number <= 0) { cout << "Cannot count mean value from 0 numbers" << endl; } else { cout << "Mean value of the given numbers is " << sum / count_number << endl; } } // Write here a function counting the mean value int main() { cout << "From how many integer numbers you want to count the mean value? "; int count_number; cin >> count_number; mean (count_number); return EXIT_SUCCESS; }
true
f140beded94c12b7e6630beb7090164ff97c9b96
C++
Ckins/Learning-Notes
/leetcode/681.cpp
UTF-8
1,547
3
3
[]
no_license
class Solution { public: string nextClosestTime(string time) { int delta = 1440; unordered_set<char> s; for (auto c:time) { if (c != ':') s.insert(c); } string res = time; dfs(time, time, delta, 0, s, res); return res; } void dfs(string time, string &target, int &delta, int pos, unordered_set<char> &dict, string &res) { for (int i = pos; i < time.size(); i++) { if (i == 2) continue; for (auto &c : dict) { time[i] = c; if (isValid(time)) { int tmp_delta = calc(target, time); if (tmp_delta < delta) { res = time; delta = tmp_delta; } dfs(time, target, delta, pos+1, dict, res); } } } } int calc(string now, string next) { int delta = strToMi(next) - strToMi(now); return delta > 0 ? delta : delta + 1440; } bool isValid(string time) { string hr = time.substr(0, 2); string mi = time.substr(3, 2); int i_hr = atoi(hr.c_str()); int i_mi = atoi(mi.c_str()); return i_hr >= 0 && i_hr <= 23 && i_mi >= 0 && i_mi <= 59; } int strToMi(string time) { string hr = time.substr(0, 2); string mi = time.substr(3, 2); int i_hr = atoi(hr.c_str()); int i_mi = atoi(mi.c_str()); return i_hr * 60 + i_mi; } };
true
1618d69c3b93444f8e2e7ab4b6e55410c2f0539f
C++
Aniket1102/Maze-King
/Main.cpp
UTF-8
772
3.0625
3
[]
no_license
// // Main.cpp // // CS 115 Assignment // // #include <string> #include <iostream> #include <fstream> #include "Direction.h" #include "Game.h" using namespace std; int main() { char newPosition; Game game("map5.txt"); do { game.printDescription(); cout <<"Next?"; cin >> newPosition; switch (newPosition) { case 'n': game.move(NORTH); break; case 's': game.move(SOUTH); break; case 'e': game.move(EAST); break; case 'w': game.move(WEST); break; default: cout << " " << endl; } } while (newPosition != 'q'); // wait for user to confirm quit cout << "Press [ENTER] to continue..."; string dummy; getline(cin, dummy); return 0; }
true
3955102b6722e9333a440e0267b5d2a8e198968c
C++
jamesu/xtal-language
/src/xtal/xtal_ch.h
UTF-8
1,070
3.03125
3
[ "Zlib", "MIT" ]
permissive
/** \file src/xtal/xtal_ch.h * \brief src/xtal/xtal_ch.h */ #ifndef XTAL_CH_H_INCLUDE_GUARD #define XTAL_CH_H_INCLUDE_GUARD #pragma once namespace xtal{ uint_t edit_distance(const void* data1, uint_t size1, const void* data2, uint_t size2); /** * \brief マルチバイト文字を組み立てるためのユーティリティクラス */ class ChMaker{ public: ChMaker() :pos_(0), len_(-1){ buf_[0] = 0; } ~ChMaker(){ } bool is_completed(){ if(pos_>8){ return true; } return pos_==len_; } void add(char_t ch){ buf_[pos_++] = ch; if(pos_==1){ len_ = ch_len(ch); } else if(pos_ == -len_){ len_ = ch_len2(buf_); } } const IDPtr& to_s(){ return temp_ = intern(&buf_[0], pos_); } int_t pos(){ return pos_; } char_t at(int_t i){ return buf_[i]; } const char_t* data(){ return buf_; } void clear(){ pos_ = 0; len_ = -1; } private: int_t pos_; int_t len_; char_t buf_[16]; IDPtr temp_; }; } #endif // XTAL_CH_H_INCLUDE_GUARD
true
e6a37ec4b955ed855d5ed7f0d83cb99b6ed32c92
C++
onewordstudios/sweetspace
/cugl/lib/2d/CUSlider.cpp
UTF-8
19,029
2.625
3
[]
no_license
// // CUSlider.cpp // Cornell University Game Library (CUGL) // // This module provides support for a slider, which allows the user to drag // a knob to select a value. The slider can be spartan (a circle on a line), // or it can have custom images. // // The slider can track its own state, relieving you of having to manually // check mouse presses. However, it can only do this when the slider is part // of a scene graph, as the scene graph maps mouse coordinates to screen // coordinates. // // This class uses our standard shared-pointer architecture. // // 1. The constructor does not perform any initialization; it just sets all // attributes to their defaults. // // 2. All initialization takes place via init methods, which can fail if an // object is initialized more than once. // // 3. All allocation takes place via static constructors which return a shared // pointer. // // CUGL MIT License: // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not // be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // // Author: Walker White and Enze Zhou // Version: 1/8/18 // #include <cugl/input/cu_input.h> #include <cugl/2d/cu_2d.h> #include <cugl/assets/CUSceneLoader.h> #include <cugl/assets/CUAssetManager.h> using namespace cugl; /** String for managing unknown JSON values */ #define UNKNOWN_STR "<unknown>" /** The line weight of the default path node */ #define LINE_WEIGHT 2.0f /** The number of line segments in the knob "circle" */ #define KNOB_SEGS 32 #pragma mark - #pragma mark Constructors /** * Creates an uninitialized slider. You must initialize it before use. * * NEVER USE A CONSTRUCTOR WITH NEW. If you want to allocate a Node on the * heap, use one of the static constructors instead. */ Slider::Slider() : _range(Vec2::ZERO), _bounds(RectCugl::ZERO), _adjust(RectCugl::ZERO), _tick(0), _value(0), _snap(false), _active(false), _mouse(false), _knob(nullptr), _path(nullptr), _listener(nullptr) { _name = "Slider"; } /** * Initializes a slider with given bounds. * * The slider visuals will be interpretted from bounds. The knob will be * a circle whose radius is the maximum of x and y, where (x,y) is the * bounds origin. The path will be a simple line, but it will be surrounded * by a transparent "track" which tightly fits the knob. * * The range is the slider value range. The x value is the minimum value * (corresponding to the bottom left corner of bounds) and the y value is * the maximum value (corresponding to the top right corner of bounds). * The slider will start at the middle value. * * @param range The slider value range * @param bounds The slider path * * @return true if the slider is initialized properly, false otherwise. */ bool Slider::init(const Vec2& range, const RectCugl& bounds) { _range = range; _bounds = bounds; placePath(nullptr); placeKnob(nullptr); _value = (_range.y+_range.x)/2.0f; reconfigure(); return true; } /** * Initializes a slider with given scene graph nodes. * * The slider visuals will be taken from the scene graph nodes knob and path. * The rectangle bounds should define an interior region of path. The * knob graph node can be slid from the origing of bounds to the top right * corner. * * The range is the slider value range. The x value is the minimum value * (corresponding to the bottom left corner of bounds) and the y value is * the maximum value (corresponding to the top right corner of bounds). * The slider will start at the middle value. * * @param range The slider value range * @param bounds The slider path * @param path The scene graph node for the path * @param knob The scene graph node for the knob * * @return true if the slider is initialized properly, false otherwise. */ bool Slider::initWithUI(const Vec2& range, const RectCugl& bounds, const std::shared_ptr<Node>& path, const std::shared_ptr<Button>& knob) { _range = range; _bounds = bounds; placePath(path); placeKnob(knob); _value = (_range.y+_range.x)/2.0f; reconfigure(); return true; } /** * Initializes a node with the given JSON specificaton. * * This initializer is designed to receive the "data" object from the * JSON passed to {@link SceneLoader}. This JSON format supports all * of the attribute values of its parent class. In addition, it supports * the following additional attributes: * * "bounds": A 4-element array of numbers (x,y,width,height) * "range": A 2-element array of numbers (min,max) * "value': A number representing the initial value * "tick': A number greater than 0, representing the tick period * "snap": A boolean indicating whether to snap to a nearest tick * "knob": A JSON object defining a scene graph node * "path": A JSON object defining a scene graph node OR * * The attribute 'bounds' is REQUIRED. All other attributes are optional. * * @param loader The scene loader passing this JSON file * @param data The JSON object specifying the node * * @return true if initialization was successful. */ bool Slider::initWithData(const SceneLoader* loader, const std::shared_ptr<JsonValue>& data) { if (!data) { return init(); } else if (!Node::initWithData(loader,data)) { return false; } // All of the code that follows can corrupt the position. Vec2 coord = getPosition(); if (data->has("bounds")) { JsonValue* bound = data->get("bounds").get(); CUAssertLog(bound->size() == 4, "Attribute 'bounds' must be a four element array"); _bounds.origin.x = bound->get(0)->asFloat(0.0f); _bounds.origin.y = bound->get(1)->asFloat(0.0f); _bounds.size.width = bound->get(2)->asFloat(0.0f); _bounds.size.height= bound->get(3)->asFloat(0.0f); } else { CUAssertLog(false, "JSON is missing a required 'bounds' rectangle"); return false; } if (data->has("path")) { std::shared_ptr<JsonValue> path = data->get("path"); placePath(loader->build("path",path)); } else { placePath(nullptr); } if (data->has("knob")) { std::shared_ptr<JsonValue> knob = data->get("knob"); placeKnob(std::dynamic_pointer_cast<Button>(loader->build("knob",knob))); } else { placeKnob(nullptr); } if (data->has("range")) { JsonValue* range = data->get("range").get(); CUAssertLog(range->size() == 2, "Attribute 'range' must be a two element array"); _range.x = range->get(0)->asFloat(DEFAULT_MIN); _range.y = range->get(1)->asFloat(DEFAULT_MAX); } _value = data->getFloat("value",(_range.y+_range.x)/2.0f); _tick = data->getFloat("tick",0); _snap = data->getBool("snap",false); reconfigure(); // Now redo the position setPosition(coord); return true; } /** * Disposes all of the resources used. * * A disposed slider can be safely reinitialized. Any child will * be released. They will be deleted if no other object owns them. * * It is unsafe to call this on a slider that is still currently * inside of a scene graph. */ void Slider::dispose() { if (_active) { deactivate(); } _value = 0; _tick = 0; _snap = false; _range = Vec2::ZERO; _bounds = RectCugl::ZERO; _adjust = RectCugl::ZERO; _active = false; _mouse = false; _knob = nullptr; _path = nullptr; _listener = nullptr; Node::dispose(); } #pragma mark - #pragma mark Appearance /** * Sets the scene graph node for the knob. * * If this value is nullptr, the method will construct a default knob * scene graph consisting of a simple circle. * * Unlike {@link setKnob()}, this does not resize the bounding box. * * @param knob The new scene graph node for the knob. */ void Slider::placeKnob(const std::shared_ptr<Button>& knob) { if (_knob) { removeChild(_knob); } if (knob == nullptr) { float radius = std::max(_bounds.origin.x,_bounds.origin.y); Poly2 poly; Poly2::createEllipse(Vec2(radius,radius), Size(2*radius,2*radius), KNOB_SEGS, &poly); std::shared_ptr<PolygonNode> circ = PolygonNode::alloc(poly); circ->setColor(Color4::GRAY); _knob = Button::alloc(circ); } else { _knob = knob; } addChild(_knob); } /** * Sets the scene graph node for the path. * * If this value is nullptr, the method will construct a default path * scene graph consisting of a simple line and a semi-transparent track. * * Unlike {@link setPath()}, this does not resize the bounding box. * * @param path The new scene graph node for the path. */ void Slider::placePath(const std::shared_ptr<Node>& path) { if (_knob) { removeChild(_knob); } // Always need knob on top if (_path) { removeChild(_path); } if (path == nullptr) { Size psize; psize.width = (_bounds.size.width > 0 ? _bounds.size.width : _bounds.size.width)+_bounds.origin.x; psize.height = (_bounds.size.height > 0 ? _bounds.size.height : _bounds.size.height)+_bounds.origin.y; float radius = std::max(_bounds.origin.x,_bounds.origin.y); _path = Node::allocWithBounds(psize); Poly2 poly; Poly2::createLine(_bounds.origin, _bounds.origin+_bounds.size, &poly); auto track = PathNode::allocWithPoly(poly,radius,PathJoint::NONE,PathCap::ROUND); track->setColor(Color4(255,255,255,32)); track->setAnchor(Vec2::ANCHOR_BOTTOM_LEFT); track->setPosition(_bounds.origin); _path->addChild(track); auto line = PathNode::allocWithPoly(poly,LINE_WEIGHT,PathJoint::NONE,PathCap::ROUND); line->setColor(Color4::BLACK); line->setAnchor(Vec2::ANCHOR_BOTTOM_LEFT); line->setPosition(_bounds.origin); _path->addChild(line); } else { _path = path; } addChild(_path); if (_knob) { addChild(_knob); } } #pragma mark - #pragma mark Listeners /** * Activates this slider to enable dragging. * * This method attaches a listener to either the {@link Mouse} or * {@link Touchscreen} inputs to monitor when the slider is dragged. * The slider will favor the mouse, but will use the touch screen * if no mouse input is active. If neither input is active, this method * will fail. * * When active, the slider will change its value on its own, without * requiring the user to use {@link setValue(float)}. If there is a * {@link Listener} attached, it will call that function upon any * state changes. * * @param key The listener key for the input device * * @return true if the slider was successfully activated */ bool Slider::activate(Uint32 key) { if (_active) { return false; } Mouse* mouse = Input::get<Mouse>(); Touchscreen* touch = Input::get<Touchscreen>(); CUAssertLog(mouse || touch, "Neither mouse nor touch input is enabled"); if (mouse) { _mouse = true; // Add the mouse listeners bool down = mouse->addPressListener(key, [=](const MouseEvent& event, Uint8 clicks, bool focus) { if (_knob->containsScreen(event.position)) { _dragpos = this->screenToNodeCoords(event.position); _knob->setDown(true); } }); bool up = false; if (down) { up = mouse->addReleaseListener(key, [=](const MouseEvent& event, Uint8 clicks, bool focus) { if (_knob->isDown()) { _knob->setDown(false); } }); if (!up) { mouse->removePressListener(key); } } bool drag = false; if (up && down) { drag = mouse->addDragListener(key, [=](const MouseEvent& event, const Vec2& previous, bool focus) { if (_knob->isDown()) { dragKnob(event.position); } }); if (!drag) { mouse->removePressListener(key); mouse->removeReleaseListener(key); } } _active = up && down && drag; } else { _mouse = false; // Add the mouse listeners bool down = touch->addBeginListener(key, [=](const TouchEvent& event, bool focus) { if (_knob->containsScreen(event.position)) { _dragpos = this->screenToNodeCoords(event.position); _knob->setDown(true); } }); bool up = false; if (down) { up = touch->addEndListener(key, [=](const TouchEvent& event, bool focus) { if (_knob->isDown()) { _knob->setDown(false); } }); if (!up) { touch->removeBeginListener(key); } } bool drag = false; if (up && down) { drag = touch->addMotionListener(key, [=](const TouchEvent& event, const Vec2& previous, bool focus) { if (_knob->isDown()) { dragKnob(event.position); } }); if (!drag) { mouse->removePressListener(key); mouse->removeReleaseListener(key); } } _active = up && down && drag; touch->requestFocus(key); } _inputkey = _active ? key : 0; return _active; } /** * Deactivates this slider, unable to drag from then on. * * This method removes its internal listener from either the {@link Mouse} * or {@link Touchscreen}. * * When deactivated, the slider will no longer change value on its own. * However, the user can still change manually with the {@link setValue(float)} * method. In addition, any {@link Listener} attached will still * respond to manual state changes. * * @return true if the slider was successfully deactivated */ bool Slider::deactivate() { if (!_active) { return false; } bool success = false; if (_mouse) { Mouse* mouse = Input::get<Mouse>(); CUAssertLog(mouse, "Mouse input is no longer enabled"); success = mouse->removePressListener(_inputkey); success = mouse->removeReleaseListener(_inputkey) && success; success = mouse->removeDragListener(_inputkey) && success; } else { Touchscreen* touch = Input::get<Touchscreen>(); CUAssertLog(touch, "Touch input is no longer enabled"); success = touch->removeBeginListener(_inputkey); success = touch->removeEndListener(_inputkey) && success; success = touch->removeMotionListener(_inputkey) && success; } _active = false; _inputkey = 0; _mouse = false; return success; } #pragma mark - #pragma mark Internal Helpers /** * Returns the correct value nearest the given one. * * This method is used to snap values to the grid of ticks, as well as * keep the value in range. * * @param value The candidate value * * @return the nearest correct value. */ float Slider::validate(float value) const { float result = value; if (_snap && _tick > 0) { float actual = (result - _range.x)/_tick; actual = std::round(actual); result = actual*_tick+_range.x; } return std::max(std::min(result,_range.y),_range.x); } /** * Resizes the node and arranges the position of the knob and path. * * This method is called whenever the bounds or scene graph changes. */ void Slider::reconfigure() { // Master node must be large enough to contain knob AND path. Size ksize = _knob->getSize(); Size psize = _path->getSize(); // Compute the left and right padding necessary. Vec2 left, rght; if (ksize.width/2.0f > _bounds.origin.x) { left.x = ksize.width/2.0f - _bounds.origin.x; } if (ksize.height/2.0f > _bounds.origin.x) { left.y = ksize.height/2.0f - _bounds.origin.y; } if (ksize.width/2.0f > psize.width-_bounds.size.width-_bounds.origin.x) { rght.x = ksize.width/2.0f-psize.width+_bounds.size.width+_bounds.origin.x; } if (ksize.height/2.0f > psize.height-_bounds.size.height-_bounds.origin.y) { rght.y = ksize.height/2.0f-psize.height+_bounds.size.height+_bounds.origin.y; } // Using padding on each end to compute a symmetric padding. Vec2 offset; offset.x = std::max(left.x,rght.x); offset.y = std::max(left.y,rght.y); // Set size and adjust the slider track. Size size = _path->getSize()+2*offset; _adjust = _bounds; _adjust.origin += offset; setContentSize(size); _path->setAnchor(Vec2::ANCHOR_CENTER); _path->setPosition(size/2.0f); reposition(); } /** * Repositions the knob to reflect a change in value. * * This method is called whenever the value or its range changes. */ void Slider::reposition() { Vec2 pos = _adjust.origin + _adjust.size * ((_value-_range.x) / (_range.y-_range.x)); _knob->setAnchor(Vec2::ANCHOR_CENTER); _knob->setPosition(pos); if (_listener != nullptr) { _listener(getName(),_value); } } /** * Drags the knob to the given position. * * This method is called by the touch listeners and assumes that an * initial drag anchor has been set. The position defines a drag * vector that is projected on to the sliding bounds. * * @param pos The position to drag to (if in the sliding bounds) */ void Slider::dragKnob(const Vec2& pos) { Vec2 off = screenToNodeCoords(pos); Vec2 line = (Vec2)_adjust.size; Vec2 drag = off-_dragpos; Vec2 prog = drag.getProjection(line); float param = (line.x != 0 ? prog.x/line.x : prog.y/line.y); if (param == 0) { return; } // Compute how much we can move. float result = validate(_value+param*(_range.y-_range.x)); // Remember the remainder and restore the drag. double remain = (result-_value)/(_range.y-_range.x); drag *= (float)(remain/param); _dragpos += drag; _value = result; reposition(); }
true
c5e787a6c4e7da89019cbd4ffc69ec0fb33d2f93
C++
robbykraft/Face
/src/SceneManager.cpp
UTF-8
3,343
2.546875
3
[]
no_license
// // SceneManager.cpp // sceneSwitcher // // Created by Robby on 5/6/16. // // #include "SceneManager.h" #include "appConstants.h" #include "ConicsScene.h" #include "hypercubeScene.h" #include "CirclesScene.h" #include "ArcsScene.h" #define NUM_SCENES 3 //----------------------------------------------------------------------------------- void SceneManager::setup(){ SCENE_INTERVAL = 16; FADE_DURATION = 3.0; scenes.push_back(new CirclesScene()); scenes.push_back(new ConicsScene()); scenes.push_back(new HypercubeScene()); sceneFbo.allocate(RESOLUTION_SCENE_WIDTH, RESOLUTION_SCENE_HEIGHT, GL_RGBA, 4); for (auto scene : scenes){ scene->setup(); } currentScene = 0; scenes[currentScene]->reset(); masterFade = 0.0; faceFound = false; faceLeftEye = ofPoint(0, 0); faceRightEye = ofPoint(0, 0); faceMouth = ofPoint(0, 0); faceNose = ofPoint(0, 0); } void SceneManager::resetSequence(){ currentScene = 0; masterLoopStartTime = ofGetElapsedTimef(); sceneTransitionStartTime = 0; } //----------------------------------------------------------------------------------- void SceneManager::update(){ if(faceFound) masterFade = masterFade * .95 + .05; else masterFade = masterFade * .95; if(ofGetElapsedTimef() - masterLoopStartTime > sceneTransitionStartTime + SCENE_INTERVAL - FADE_DURATION){ // begin fade transition sceneTransitionStartTime = ofGetElapsedTimef() - masterLoopStartTime; isSceneTransition = true; } if(isSceneTransition){ sceneTransitionTween = (ofGetElapsedTimef() - masterLoopStartTime - sceneTransitionStartTime) / FADE_DURATION; if(sceneTransitionTween > 1.0) sceneTransitionTween = 1.0; if(sceneTransitionTween < 0.0) sceneTransitionTween = 0.0; if(ofGetElapsedTimef() - masterLoopStartTime > sceneTransitionStartTime + FADE_DURATION){ // increment to the next scene currentScene = (currentScene + 1)%NUM_SCENES; sceneTransitionStartTime = ofGetElapsedTimef() - masterLoopStartTime; isSceneTransition = false; scenes[currentScene]->reset(); } } scenes[currentScene]->faceLeftEye = faceLeftEye; scenes[currentScene]->faceRightEye = faceRightEye; scenes[currentScene]->faceMouth = faceMouth; scenes[currentScene]->faceNose = faceNose; scenes[currentScene]->faceCenterSmooth = faceCenterSmooth; scenes[currentScene]->faceScaleSmooth = faceScaleSmooth; scenes[currentScene]->faceScaleMatrix = faceScaleMatrix; scenes[currentScene]->update(); } //----------------------------------------------------------------------------------- void SceneManager::draw(){ // FILL BUFFERS sceneFbo.begin(); ofClear(255,0); ofSetColor(255,255); ofPushStyle(); scenes[currentScene]->draw(); ofPopStyle(); sceneFbo.end(); // DRAW THE SCENES ofSetColor(255, 255 * masterFade); if(isSceneTransition){ // draw scene fading out ofSetColor(255, masterFade * 255*(1-sceneTransitionTween) ); } sceneFbo.draw(-RESOLUTION_WINDOW_WIDTH * .5, -RESOLUTION_WINDOW_HEIGHT * .5, RESOLUTION_WINDOW_WIDTH, RESOLUTION_WINDOW_HEIGHT); }
true
f4bdf33fd69677c00067d1ca2882081e614f6a4a
C++
Roshan2121/C-files
/Object Oriented Programming in C++/Class1.cpp
UTF-8
670
4.1875
4
[]
no_license
/* Defifnig a Class and its object. Initializing the objects of a class and how to use them. */ #include<iostream> using namespace std; class Practice { public: int age; string name; long salary; void printer() { cout<<"A preson with name "<<name<<" is aged "<<age<<" and earns a salary of "<<salary<<" per month "; } }; int main() { Practice roshan; cin>>roshan.age; //You can use cin or uniform initialization or assignment method.... cin>>roshan.name; // roshan{19, "Roshan", 2800000}; or roshan = {19, "Roshan", 2800000}; cin>>roshan.salary; cout<<roshan.age<<"\n"; roshan.printer(); return 0; }
true
01580002a6c66e9088d1ca2e8fcf5179e740932c
C++
wenmingxing1/offer_code_for_github
/21_MinInStack.cpp
UTF-8
524
2.875
3
[]
no_license
class Solution { public: std::stack<int> stack_data, min_data; void push(int value) { stack_data.push(value); if (min_data.empty()) min_data.push(value); if (value < min_data.top()){ min_data.push(value); } else { min_data.push(min_data.top()); } } void pop() { stack_data.pop(); min_data.pop(); } int top() { return stack_data.top(); } int min() { return min_data.top(); } };
true
6dcc9cd7683f50a10fa0e1fd6e1beeb69ca3228d
C++
pedro-esteves-pinto/mcbridge
/src/main.cpp
UTF-8
5,728
2.671875
3
[ "MIT" ]
permissive
#include "client/Client.h" #include "client/ClientConfig.h" #include "common/common.h" #include "server/Server.h" #include "test/Test.h" #include <CLI11/CLI11.hpp> #include <iostream> #include <string> #include <vector> using namespace mcbridge; uint32_t resolve_interface_ip(std::string const &interface_name) { auto ip = get_interface_ip(interface_name); if (ip) return ip.value(); else { LOG(fatal) << "Invalid interface name: " << interface_name; exit(-1); } } std::set<EndPoint> read_groups_from_file(std::string const &groups_file) { std::set<EndPoint> result; std::ifstream f(groups_file); while (!f.eof()) { std::string ip_port; f >> std::skipws >> ip_port; if (ip_port.size()) { EndPoint ep(ip_port); result.insert(ep); } } return result; } int main(int argc, char **argv) { using namespace mcbridge; CLI::App app{"Bridges multicast traffic over a TCP/IP connection"}; app.require_subcommand(1); mcbridge::log logging_verbosity = mcbridge::log::info; uint16_t port = 30000; std::string interface; uint32_t max_in_flight_datagrams = 1000; // client auto client_cmd = app.add_subcommand("client", "Acts a client"); std::string server_addr; client_cmd->add_option("-s,--server-address", server_addr, "Server address") ->required(); client_cmd->add_option("-l,--logging-verbosity", logging_verbosity, "Logging verbosity (0 to 4)"); bool auto_discover_groups = false; client_cmd->add_flag("-d,--discover-groups", auto_discover_groups, "Automatically discover joined groups"); std::string auto_discover_mask; client_cmd->add_option("-m,--network-mask", auto_discover_mask, "Filter out discovered groups that do not match " "network mask. Masks are of the form ip/mask."); std::string groups_file; client_cmd ->add_option("-f,--groups-file", groups_file, "Read multicast groups to join from file") ->check(CLI::ExistingFile); std::vector<std::string> groups; client_cmd->add_option("-g,--group", groups, "Multicast groups to join in the form ip:port"); client_cmd->add_option("-p,--server-port", port, "Server port", 30000); client_cmd->add_option("-i,--interface", interface, "Interface to use for outbound multicast"); client_cmd->add_option( "-x,--max-in-flight-datagrams", max_in_flight_datagrams, "Maximum number of inflight datagrams per multicast group", 1000); // server auto server_cmd = app.add_subcommand("server", "Acts as a server"); server_cmd->add_option("-l,--logging-verbosity", logging_verbosity, "Logging verbosity (0 to 4)"); server_cmd->add_option("-p,--port", port, "Port to bind to", 30000); server_cmd->add_option("-i,--interface", interface, "Interface to use for inbound multicast"); server_cmd->add_option( "-x,--max-in-flight-datagrams", max_in_flight_datagrams, "Maximum number of inflight datagrams per client", 5000); // test_send auto test_send = app.add_subcommand( "test_send", "Send a small multicast packet every few seconds"); std::string group_s = "224.0.255.255:30000"; test_send->add_option("-g,--group", group_s, "Multicast group to send to", "224.0.255.255:30000"); test_send->add_option("-i,--interface", interface, "Interface to use for outbound multicast"); auto test_recv = app.add_subcommand( "test_recv", "Receive multicast and print a few bytes to screen"); std::string group_c = "224.0.255.255:30000"; test_recv->add_option("-g,--group", group_c, "Multicast group to join", "224.0.255.255:30000"); test_recv->add_option("-i,--interface", interface, "Interface to use for inbound multicast"); CLI11_PARSE(app, argc, argv); set_log_level(logging_verbosity); try { auto interface_ip = 0; if (interface.size()) interface_ip = resolve_interface_ip(interface); if (*client_cmd) { ClientConfig cfg; cfg.auto_discover_groups = auto_discover_groups; if (auto_discover_mask.size()) { auto nm = parse_net_mask(auto_discover_mask); if (!nm) { LOG(fatal) << "Invalid network mask: " << auto_discover_mask; exit(-1); } else cfg.auto_discover_mask = nm.value(); } cfg.outbound_interface = interface_ip; if (groups_file.size()) cfg.groups_to_join = read_groups_from_file(groups_file); for (auto &g : groups) cfg.groups_to_join.insert({g}); auto server = resolve_host_name(server_addr); if (server == 0) { LOG(fatal) << "Unknown host: " << server_addr; exit(-1); } cfg.server_address = {server, port}; cfg.max_in_flight_datagrams_per_group = max_in_flight_datagrams; return Client{cfg}.run(); } else if (*server_cmd) { ServerConfig cfg; cfg.port = port; cfg.inbound_interface = interface_ip; cfg.max_in_flight_datagrams_per_connection = max_in_flight_datagrams; return Server{cfg}.run(); } else if (*test_send) return Test::send(group_s, interface_ip); else if (*test_recv) return Test::recv(group_c, interface_ip); } catch (std::runtime_error const &e) { LOG(fatal) << e.what(); exit(-1); } return -1; }
true
f7c26948cd219085a38076886227f36962acc67c
C++
Dies1rae/PYTHON
/lexer.h
UTF-8
12,338
2.9375
3
[]
no_license
#pragma once #include <iosfwd> #include <optional> #include <sstream> #include <stdexcept> #include <string> #include <variant> #include <vector> #include <algorithm> namespace parse { namespace token_type { struct Number { int value; }; struct Id { std::string value; }; struct Char { char value; }; struct String { std::string value; }; struct Class {}; struct Return {}; struct If {}; struct Else {}; struct Def {}; struct Newline {}; struct Print {}; struct Indent {}; struct Dedent {}; struct Eof {}; struct And {}; struct Or {}; struct Not {}; struct Eq {}; struct NotEq {}; struct LessOrEq {}; struct GreaterOrEq {}; struct None {}; struct True {}; struct False {}; } // namespace token_type using TokenBase = std::variant<token_type::Number, token_type::Id, token_type::Char, token_type::String, token_type::Class, token_type::Return, token_type::If, token_type::Else, token_type::Def, token_type::Newline, token_type::Print, token_type::Indent, token_type::Dedent, token_type::And, token_type::Or, token_type::Not, token_type::Eq, token_type::NotEq, token_type::LessOrEq, token_type::GreaterOrEq, token_type::None, token_type::True, token_type::False, token_type::Eof>; struct Token : TokenBase { using TokenBase::TokenBase; template <typename T> [[nodiscard]] bool Is() const { return std::holds_alternative<T>(*this); } template <typename T> [[nodiscard]] const T& As() const { return std::get<T>(*this); } template <typename T> [[nodiscard]] const T* TryAs() const { return std::get_if<T>(this); } }; bool operator==(const Token& lhs, const Token& rhs); bool operator!=(const Token& lhs, const Token& rhs); std::ostream& operator<<(std::ostream& os, const Token& rhs); class LexerError : public std::runtime_error { public: using std::runtime_error::runtime_error; }; class Lexer { public: explicit Lexer(std::istream& input); [[nodiscard]] const Token& CurrentToken() const; Token NextToken(); template <typename T> const T& Expect() const { using namespace std::literals; if (this->CurrentToken().Is<T>()) { return this->CurrentToken().As<T>(); } throw LexerError("Lexer part error not expected"); } template <typename T, typename U> void Expect(const U& value) const { using namespace std::literals; this->Expect<T>(); if ((this->root_[this->token_ctr_].As<T>().value != value)) { throw LexerError("Lexer part error in values"); } } template <typename T> const T& ExpectNext() { using namespace std::literals; this->token_ctr_++; if (this->token_ctr_ < this->root_.size()) { return this->Expect<T>(); } } template <typename T, typename U> void ExpectNext(const U& value) { using namespace std::literals; this->token_ctr_++; if (this->token_ctr_ < this->root_.size()) { return this->Expect<T>(value); } } private: bool LineEmpty(const std::string& s) { for (const auto& c : s) { if (c != ' ' && c != '#'){ return false; } if (c == '#') { break; } } return true; } bool IsAlphabet(const char& c) { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c == '_')) { return true; } return false; } bool IsNumber(const std::string& s) { std::string::const_iterator it = s.begin(); s[0] == '-' ? it += 1 : it += 0; while (it != s.end() && std::isdigit(*it)) ++it; return !s.empty() && it == s.end(); } bool IsNumber(const char& c) { return std::isdigit(c); } bool IsOperation(const std::string& c) { if (c == "==" || c == ">=" || c == "<=" || c == "!="){ return true; } return false; } bool IsChar(const std::string& c) { if (c == "." || c == "," || c == "(" || c == "+" || c == ")" || c == "-" || c == "*" || c == "/" || c == ":" || c == "@" || c == "%" || c == "$" || c == "^" || c == "&" || c == ";" || c == "?" || c == "=" || c == "<" || c == ">" || c == "!" || c == "{" || c == "}" || c == "[" || c == "]") { return true; } return false; } bool IsChar(const char c) { if (c == '.' || c == ',' || c == '(' || c == '+' || c == ')' || c == '-' || c == '*' || c == '/' || c == ':' || c == '@' || c == '%' || c == '$' || c == '^' || c == '&' || c == ';' || c == '?' || c == '=' || c == '<' || c == '>' || c == '!' || c == '{' || c == '}' || c == '[' || c == ']') { return true; } return false; } std::string ReadNumber(std::istream& input) { char ch; std::string num; while (this->IsNumber(input.peek())) { input >> ch; num += ch; } return num; } std::string ReadString(std::istream& input) { std::string result; char quote; input >> std::noskipws >> quote; char ch; while (true) { if (input >> std::noskipws >> ch) { if (ch == quote) { break; } else if (ch == '\\') { char escaped_char; if (input >> escaped_char) { switch (escaped_char) { case 'n': result.push_back('\n'); break; case 't': result.push_back('\t'); break; case '"': result.push_back('"'); break; case '\'': result.push_back('\''); break; case '\\': result.push_back('\\'); break; default: throw LexerError("Unrecognized escape sequence \\" + escaped_char); } } else { throw LexerError("Unexpected end of line"); } } else if (ch == '\n' || ch == '\r') { throw LexerError("Unexpected end of line"); } else { result.push_back(ch); } } else { throw LexerError("Unexpected end of line"); } } return result; } std::string ReadId(std::istream& input) { char ch; std::string id; while (this->IsAlphabet(input.peek()) || this->IsNumber(input.peek())) { input >> ch; id += ch; } return id; } std::string ReadCharOperation(std::istream& input) { char ch; input >> ch; std::string id; return id; } void IndentDedentParser(int now, int last) { if (now > last) { if (now % 2 != 0) { return; } while (now > last) { this->root_.push_back( { (token_type::Indent()) }); now -= 2; } } else if (last > now) { if (last % 2 != 0) { return; } while (last > now) { this->root_.push_back({ (token_type::Dedent()) }); last -= 2; } } return; } Token LoadNumber(const std::string input) { token_type::Number token = { std::stoi(input) }; return token; } Token LoadString(const std::string& input) { std::string tmp_in = input; if (tmp_in.find_first_of('\'') != tmp_in.find_last_of('\'')) { tmp_in.erase(std::remove(tmp_in.begin(), tmp_in.end(), '\\'), tmp_in.end()); } if (tmp_in.find_first_of('\"') != tmp_in.find_last_of('\"')) { tmp_in.erase(std::remove(tmp_in.begin(), tmp_in.end(), '\\'), tmp_in.end()); } token_type::String token = { tmp_in }; return token; } Token LoadChar(const char& input) { token_type::Char token = { input }; return token; } Token LoadId(const std::string& input) { if (input == "class") { token_type::Class token = {}; return token; } else if (input == "if") { token_type::If token = {}; return token; } else if (input == "else") { token_type::Else token = {}; return token; } else if (input == "def") { token_type::Def token = {}; return token; } else if (input == "\n") { token_type::Newline token = {}; return token; } else if (input == "print") { token_type::Print token = {}; return token; } else if (input == "ident") { token_type::Indent token = {}; return token; } else if (input == "dedent") { token_type::Dedent token = {}; return token; } else if (input == "&&" || input == "and") { token_type::And token = {}; return token; } else if (input == "||" || input == "or") { token_type::Or token = {}; return token; } else if (input == "not") { token_type::Not token = {}; return token; } else if (input == "==") { token_type::Eq token = {}; return token; } else if (input == "!=") { token_type::NotEq token = {}; return token; } else if (input == "<=") { token_type::LessOrEq token = {}; return token; } else if (input == ">=") { token_type::GreaterOrEq token = {}; return token; } else if (input == "None") { token_type::None token = {}; return token; } else if (input == "True") { token_type::True token = {}; return token; } else if (input == "False") { token_type::False token = {}; return token; } else if (input == "eof") { token_type::Eof token = {}; return token; } else if (input == "return") { token_type::Return token = {}; return token; } else { token_type::Id token = {input}; return token; } } size_t token_ctr_ = 0; std::vector<Token> root_; }; } // namespace parse
true
0905700d4796d83ebe2130059e992bfd31540a9a
C++
taruvar-mittal/DSA-Solutions
/Graphs/reorder paths to make all cities reach to city 0.cpp
UTF-8
2,363
3.5
4
[]
no_license
/* Leetcode 1466. Reorder Routes to Make All Paths Lead to the City Zero ques:- There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. Roads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi. This year, there will be a big event in the capital (city 0), and many people want to travel to this city. Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed. It's guaranteed that each city can reach city 0 after reorder. Example 1: Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]] Output: 3 Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital). Example 2: Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]] Output: 2 Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital). Example 3: Input: n = 3, connections = [[1,0],[2,0]] Output: 0 Constraints: 2 <= n <= 5 * 104 connections.length == n - 1 connections[i].length == 2 0 <= ai, bi <= n - 1 ai != bi */ class Solution { public: int minReorder(int n, vector<vector<int>> &connections) { vector<vector<int>> forward(n); vector<vector<int>> back(n); int output = 0; vector<bool> visited(n, false); for (auto v : connections) { forward[v[0]].push_back(v[1]); back[v[1]].push_back(v[0]); } queue<int> pendingNodes; pendingNodes.push(0); while (!pendingNodes.empty()) { int curr = pendingNodes.front(); pendingNodes.pop(); visited[curr] = true; for (auto v : forward[curr]) { if (!visited[v]) { output++; pendingNodes.push(v); } } for (auto v : back[curr]) { if (!visited[v]) { pendingNodes.push(v); } } } return output; } };
true
642ba8de72aa499f3e8e60b73236c44b8cf2c6c3
C++
LeeJehwan/Baekjoon-Online-Judge
/code/01212_8진수 2진수.cpp14.cpp
UTF-8
491
2.9375
3
[]
no_license
#include <iostream> using namespace std; char arr[340000]; char *str[] = { "000","001","010","011","100","101","110","111" }; char *str2[] = { "0","1","10","11","100","101","110","111" }; void solve(int len) { int num; for (int i = 0; i < len; i++) { num = arr[i]-48; if (i == 0) { cout << str2[num]; continue; } cout << str[num]; } cout << endl; } int main() { cin >> arr; int len=0; for (int i = 0;; i++) { if (arr[i] == '\0') break; len++; } solve(len); }
true
6b2aa883ae42719fe222befdfd84436a7a0e9fa0
C++
grtwall/kigs
/framework/Core/Sources/CoreItem.cpp
UTF-8
9,149
2.546875
3
[ "MIT" ]
permissive
#include "PrecompiledHeaders.h" #include "CoreItem.h" #include "CoreVector.h" #include "CoreMap.h" #include "maCoreItem.h" #include <type_traits> CoreItemSP CoreItemIteratorBase::operator*() const { if (mPos == 0) { return mAttachedCoreItem; } return CoreItemSP(nullptr); } CoreItemIteratorBase& CoreItemIteratorBase::operator=(const CoreItemIteratorBase& other) { mAttachedCoreItem = other.mAttachedCoreItem; mPos = other.mPos; return *this; } CoreItemSP CoreItemIterator::operator*() const { return get()->operator*(); } CoreItemIterator& CoreItemIterator::operator=(const CoreItemIterator& other) { SmartPointer<CoreItemIteratorBase>::operator=(other); return *this; } CoreItemIterator& CoreItemIterator::operator+(const int decal) { get()->operator+(decal); return *this; } CoreItemIterator& CoreItemIterator::operator++() { get()->operator++(); return *this; } CoreItemIterator CoreItemIterator::operator++(int) { CoreItemIterator tmp(get()->clone()); get()->operator++(); return tmp; } bool CoreItemIterator::operator==(const CoreItemIterator& other) const { return (*get()) == *(other.get()); } bool CoreItemIterator::operator!=(const CoreItemIterator& other) const { return (*get()) != *(other.get()); } bool CoreItemIterator::getKey(kstl::string& returnedkey) { return get()->getKey(returnedkey); } bool CoreItemIterator::getKey(usString& returnedkey) { return get()->getKey(returnedkey); } CoreItemSP::CoreItemSP(const bool& value) { *this = MakeCoreValue(value); } CoreItemSP::CoreItemSP(const float& value) { *this = MakeCoreValue(value); } CoreItemSP::CoreItemSP(const double& value) { *this = MakeCoreValue(value); } CoreItemSP::CoreItemSP(const s32& value) { *this = MakeCoreValue(value); } CoreItemSP::CoreItemSP(const u32& value) { *this = MakeCoreValue(value); } CoreItemSP::CoreItemSP(const s64& value) { *this = MakeCoreValue(value); } CoreItemSP::CoreItemSP(const u64& value) { *this = MakeCoreValue(value); } CoreItemSP::CoreItemSP(const v2f& value) { *this = MakeCoreValue(value); } CoreItemSP::CoreItemSP(const v3f& value) { *this = MakeCoreValue(value); } CoreItemSP::CoreItemSP(const v4f& value) { *this = MakeCoreValue(value); } CoreItemSP::CoreItemSP(const std::string& value, CoreModifiable* owner) { *this = MakeCoreValue(value, owner); } CoreItemSP::CoreItemSP(const char* value, CoreModifiable* owner) { *this = MakeCoreValue(value, owner); } CoreItemSP::CoreItemSP(const usString& value, CoreModifiable* owner) { *this = MakeCoreValue(value, owner); } // operator [] needs to be overloaded on vectors and maps CoreItemSP CoreItem::operator[](int i) { if (i == 0) { return SharedFromThis(); } return CoreItemSP(nullptr); } CoreItemSP CoreItem::operator[](const kstl::string& key) { return CoreItemSP(nullptr); } CoreItemSP CoreItem::operator[](const usString& key) { return CoreItemSP(nullptr); } CoreItemSP CoreNamedItem::operator[](const kstl::string& key) { if (key == mName) { return SharedFromThis(); } return CoreItemSP(nullptr); } CoreItemSP CoreNamedItem::operator[](const usString& key) { if (key.ToString() == mName) { return SharedFromThis(); } return CoreItemSP(nullptr); } CoreItem::operator bool() const { KIGS_ERROR("cast operator called on base CoreItem", 2); return false; } CoreItem::operator kfloat() const { KIGS_ERROR("cast operator called on base CoreItem", 2); return 0.0f; } CoreItem::operator double() const { KIGS_ERROR("cast operator called on base CoreItem", 2); return 0.0; } CoreItem::operator int() const { KIGS_ERROR("cast operator called on base CoreItem", 2); return 0; } CoreItem::operator s64() const { KIGS_ERROR("cast operator called on base CoreItem", 2); return 0; } CoreItem::operator unsigned int() const { KIGS_ERROR("cast operator called on base CoreItem", 2); return 0; } CoreItem::operator u64() const { KIGS_ERROR("cast operator called on base CoreItem", 2); return 0; } CoreItem::operator kstl::string() const { KIGS_ERROR("cast operator called on base CoreItem", 2); return ""; } CoreItem::operator usString() const { KIGS_ERROR("cast operator called on base CoreItem", 2); return usString(""); } CoreItem::operator Point2D() const { Point2D result; KIGS_ERROR("cast operator called on base CoreItem", 2); return result; } CoreItem::operator Vector4D() const { Vector4D result; KIGS_ERROR("cast operator called on base CoreItem", 2); return result; } CoreItem::operator Point3D() const { Point3D result; KIGS_ERROR("cast operator called on base CoreItem", 2); return result; } CoreItemSP MakeCoreNamedMap(const std::string& name) { return std::make_shared<CoreNamedMap<std::string>>(name); } CoreItemSP MakeCoreMap() { return std::make_shared<CoreMap<std::string>>(); } CoreItemSP MakeCoreMapUS() { return std::make_shared<CoreMap<usString>>(); } CoreItemSP MakeCoreNamedMapUS(const std::string& name) { return std::make_shared<CoreNamedMap<usString>>(name); } CoreItemSP MakeCoreVector() { return std::make_shared<CoreVector>(); } CoreItemSP MakeCoreNamedVector(const std::string& name) { return std::make_shared<CoreNamedVector>(name); } #define IMPLEMENT_MAKE_COREVALUE(type) CoreItemSP MakeCoreValue(type value)\ {\ return std::make_shared<CoreValue<std::decay_t<type>>>(value);\ }\ CoreItemSP MakeCoreNamedValue(type value, const std::string& name)\ {\ return std::make_shared<CoreNamedValue<std::decay_t<type>>>(value, name);\ } IMPLEMENT_MAKE_COREVALUE(const bool&) IMPLEMENT_MAKE_COREVALUE(const s32&) IMPLEMENT_MAKE_COREVALUE(const u32&) IMPLEMENT_MAKE_COREVALUE(const s64&) IMPLEMENT_MAKE_COREVALUE(const u64&) IMPLEMENT_MAKE_COREVALUE(const float&) IMPLEMENT_MAKE_COREVALUE(const double&) CoreItemSP MakeCoreValue(const char* value, CoreModifiable* owner) { // check eval if (AttributeNeedEval(value)) { maCoreItemValue tmpVal; tmpVal.InitWithJSON(value, owner); return tmpVal.item; } else return std::make_shared<CoreValue<std::string>>(value); } CoreItemSP MakeCoreNamedValue(const char* value, const std::string& name) { return std::make_shared<CoreNamedValue<std::string>>(value, name); } CoreItemSP MakeCoreValue(const std::string& value, CoreModifiable* owner) { // check eval if (AttributeNeedEval(value)) { maCoreItemValue tmpVal; tmpVal.InitWithJSON(value, owner); return tmpVal.item; } else return std::make_shared<CoreValue<std::string>>(value); } CoreItemSP MakeCoreNamedValue(const std::string& value, const std::string& name) { return std::make_shared<CoreNamedValue<std::string>>(value, name); } CoreItemSP MakeCoreValue(const usString& value, CoreModifiable* owner) { if (AttributeNeedEval(value.ToString())) { maCoreItemValue tmpVal; tmpVal.InitWithJSON(value.ToString(), owner); return tmpVal.item; } else return std::make_shared<CoreValue<usString>>(value); } CoreItemSP MakeCoreNamedValue(const usString& value, const std::string& name) { return std::make_shared<CoreNamedValue<usString>>(value, name); } CoreItemSP MakeCoreValue(const v2f& value) { auto vector = MakeCoreVector(); vector->set("", MakeCoreValue(value.x)); vector->set("", MakeCoreValue(value.y)); return vector; } CoreItemSP MakeCoreValue(const v3f& value) { auto vector = MakeCoreVector(); vector->set("", MakeCoreValue(value.x)); vector->set("", MakeCoreValue(value.y)); vector->set("", MakeCoreValue(value.z)); return vector; } CoreItemSP MakeCoreValue(const v4f& value) { auto vector = MakeCoreVector(); vector->set("", MakeCoreValue(value.x)); vector->set("", MakeCoreValue(value.y)); vector->set("", MakeCoreValue(value.z)); vector->set("", MakeCoreValue(value.w)); return vector; } // empty assignement with value CoreItem& CoreItem::operator=(const bool& other) { KIGS_WARNING("trying to assign base CoreItem with value", 2); return *this; } CoreItem& CoreItem::operator=(const kfloat& other) { KIGS_WARNING("trying to assign base CoreItem with value", 2); return *this; } CoreItem& CoreItem::operator=(const int& other) { KIGS_WARNING("trying to assign base CoreItem with value", 2); return *this; } CoreItem& CoreItem::operator=(const unsigned int& other) { KIGS_WARNING("trying to assign base CoreItem with value", 2); return *this; } CoreItem& CoreItem::operator=(const s64& other) { KIGS_WARNING("trying to assign base CoreItem with value", 2); return *this; } CoreItem& CoreItem::operator=(const u64& other) { KIGS_WARNING("trying to assign base CoreItem with value", 2); return *this; } CoreItem& CoreItem::operator=(const kstl::string& other) { KIGS_WARNING("trying to assign base CoreItem with value", 2); return *this; } CoreItem& CoreItem::operator=(const usString& other) { KIGS_WARNING("trying to assign base CoreItem with value", 2); return *this; } CoreItem& CoreItem::operator=(const Point2D& other) { KIGS_WARNING("trying to assign base CoreItem with value", 2); return *this; } CoreItem& CoreItem::operator=(const Point3D& other) { KIGS_WARNING("trying to assign base CoreItem with value", 2); return *this; } CoreItem& CoreItem::operator=(const Vector4D& other) { KIGS_WARNING("trying to assign base CoreItem with value", 2); return *this; }
true
331f405107770a01df8872ed783c73d098929999
C++
seokwoongchoi/angelscript-homework
/Framework/Math/Vector4.h
UTF-8
836
3.28125
3
[]
no_license
#pragma once class Vector4 final { public: Vector4() : x(0.0f), y(0.0f), z(0.0f), w(0.0f) {} Vector4(const float& x, const float& y, const float& z, const float& w) : x(x), y(y), z(z), w(w) {} Vector4(const Vector4& rhs) : x(rhs.x), y(rhs.y), z(rhs.z), w(rhs.w) {} Vector4(const float& f) : x(f), y(f), z(f), w(w) {} Vector4(class Vector3& rhs); Vector4(class Vector3& rhs, const float& w); ~Vector4() {} const float* Data() const { return &x; } operator float*() { return static_cast<float*>(&x); } operator const float*() const { return static_cast<const float*>(&x); } const bool operator==(const Vector4& rhs) const { return x == rhs.x && y == rhs.y && z == rhs.z && w == rhs.w; } const bool operator!=(const Vector4& rhs) const { return !(*this == rhs); } public: float x; float y; float z; float w; };
true
324ca0a05486b22a2457de058705a01415a35a2a
C++
whycoding126/zircon
/system/ulib/perftest/include/perftest/perftest.h
UTF-8
4,308
2.984375
3
[ "BSD-3-Clause", "MIT" ]
permissive
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #pragma once #include <stdint.h> #include <fbl/function.h> #include <perftest/results.h> // This is a library for writing performance tests. It supports // performance tests that involve running an operation repeatedly, // sequentially, and recording the times taken by each run of the // operation. (It does not yet support other types of performance test, // such as where we run an operation concurrently in multiple threads.) // // There are two ways to implement a test: // // 1) For tests that don't need to reuse any test fixtures across each run, // use RegisterSimpleTest(): // // bool TestFooOp() { // FooOp(); // The operation that we are timing. // return true; // Indicate success. // } // void RegisterTests() { // perftest::RegisterSimpleTest<TestFooOp>("FooOp"); // } // PERFTEST_CTOR(RegisterTests); // // 2) For tests that do need to reuse test fixtures across each run, use // the more general RegisterTest(): // // bool TestFooObjectOp(perftest::RepeatState* state) { // FooObject obj; // Fixture that is reused across test runs. // while (state->KeepRunning()) { // obj.FooOp(); // The operation that we are timing. // } // return true; // Indicate success. // } // void RegisterTests() { // perftest::RegisterTest("FooObjectOp", TestFooObjectOp); // } // PERFTEST_CTOR(RegisterTests); // // Test registration is done using function calls in order to make it easy // to instantiate parameterized tests multiple times. // // Background: The "KeepRunning()" interface is based on the interface used // by the gbenchmark library (https://github.com/google/benchmark). namespace perftest { // This object is passed to the test function. It controls the iteration // of test runs and records the times taken by test runs. // // This is a pure virtual interface so that one can potentially use a test // runner other than the one provided by this library. class RepeatState { public: // KeepRunning() should be called by test functions using a "while" // loop shown above. A call to KeepRunning() indicates the start or // end of a test run, or both. KeepRunning() returns a bool indicating // whether the caller should do another test run. virtual bool KeepRunning() = 0; }; typedef bool TestFunc(RepeatState* state); typedef bool SimpleTestFunc(); void RegisterTest(const char* name, fbl::Function<TestFunc> test_func); // Convenience routine for registering parameterized perf tests. template <typename Func, typename Arg, typename... Args> void RegisterTest(const char* name, Func test_func, Arg arg, Args... args) { auto wrapper_func = [=](RepeatState* state) { return test_func(state, arg, args...); }; RegisterTest(name, wrapper_func); } // Convenience routine for registering a perf test that is specified by a // function. This is for tests that don't set up any fixtures that are // shared across invocations of the function. // // This takes the function as a template parameter rather than as a value // parameter in order to avoid the potential cost of an indirect function // call. template <SimpleTestFunc test_func> void RegisterSimpleTest(const char* test_name) { auto wrapper_func = [](RepeatState* state) { while (state->KeepRunning()) { if (!test_func()) { return false; } } return true; }; RegisterTest(test_name, fbl::move(wrapper_func)); } // Entry point for the perf test runner that a test executable should call // from main(). This will run the registered perf tests and/or unit tests, // based on the command line arguments. (See the "--help" output for more // details.) int PerfTestMain(int argc, char** argv); } // namespace perftest // This calls func() at startup time as a global constructor. This is // useful for registering perf tests. This is similar to declaring func() // with __attribute__((constructor)), but portable. #define PERFTEST_CTOR(func) \ namespace { \ struct FuncCaller_##func { \ FuncCaller_##func() { func(); } \ } global; \ }
true
84aa6de0f636a05bae8ad7f20732de2da230631e
C++
warycat/uva
/488/488.cpp
UTF-8
479
2.9375
3
[]
no_license
#include <cstdio> #include <iostream> using namespace std; void printWave(int h) { int i; int j; for(i=1;i<=h;i++){ for(j=0;j<i;j++) printf("%d",i); printf("\n"); } for(i=h-1;i>=1;i--){ for(j=0;j<i;j++) printf("%d",i); printf("\n"); } } int main() { int n; scanf("%d",&n); int i; for(i=0;i<n;i++){ int h; int f; scanf("%d%d",&h,&f); int j; if(i)printf("\n"); for(j=0;j<f;j++) { if(j) printf("\n"); printWave(h); } } return 0; }
true
5e4fc85b147e99deb53c964f46006fb946d79b98
C++
YufeiHu/CS130-Software-Engineering
/src/proxy_handler.cc
UTF-8
4,082
2.796875
3
[ "MIT" ]
permissive
// // Author: JMAC // ~~~~~~~~~~~~ // #include "proxy_handler.h" std::unique_ptr<RequestHandler> ProxyHandler::create(const ConfigOptions* options) { std::unique_ptr<RequestHandler> proxy_handler(new ProxyHandler(options)); return proxy_handler; } std::unique_ptr<Reply> ProxyHandler::HandleRequest(const Request& http_request) { std::string destination = options->path_proxy.at(http_request.url_root); std::string request_query = http_request.url_path; std::unique_ptr<Reply> http_response = this->Redirect(destination, request_query); return http_response; } std::unique_ptr<Reply> ProxyHandler::Redirect(std::string destination, std::string request_query) { std::unique_ptr<Reply> http_response(new Reply()); // parse destination for IP address and port number if given std::string portNum = "80"; int indexOfColon = destination.find(":"); if (indexOfColon != -1) { portNum = destination.substr(indexOfColon + 1); destination = destination.substr(0, indexOfColon); } BOOST_LOG_TRIVIAL(info) << "ProxyHandler::Redirect->Destination = " << destination << ", Port Number = " << portNum; // adapted example from https://stackoverflow.com/questions/28728347/sending-http-get-request-using-boostasio-similar-to-curl try { boost::asio::io_service io_service; tcp::resolver resolver(io_service); tcp::resolver::query query(destination.c_str(), portNum); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); tcp::socket socket(io_service); boost::asio::connect(socket, endpoint_iterator); boost::asio::streambuf request; std::ostream request_stream(&request); request_stream << "GET " << request_query.c_str() << " HTTP/1.1\r\n"; request_stream << "Host: " << destination.c_str() << "\r\n"; request_stream << "Accept: */*\r\n"; request_stream << "Connection: close\r\n\r\n"; boost::asio::write(socket, request); boost::asio::streambuf response; // read status line boost::asio::read_until(socket, response, "\r\n"); std::istream response_stream(&response); std::string http_version; response_stream >> http_version; unsigned int status_code; response_stream >> status_code; std::string status_message; std::getline(response_stream, status_message); // read headers boost::asio::read_until(socket, response, "\r\n\r\n"); std::string header; std::string header_buf; while (std::getline(response_stream, header) && header != "\r") { header_buf += header + "\r\n"; if (status_code / 100 == 3) { if (header.find("Location: ") != std::string::npos) { std::string location = header.substr(10, std::string::npos); std::string url = location.substr(location.find("://") + 3); int split_index = url.find("/"); std::string dest = url.substr(0, split_index); std::string req_query = url.substr(split_index); return Redirect(dest, req_query); } } } std::ostringstream response_content; if (response.size() > 0) { response_content << &response; } boost::system::error_code error; while (boost::asio::read(socket, response, boost::asio::transfer_at_least(1), error)) { response_content << &response; } if (error != boost::asio::error::eof) { throw boost::system::system_error(error); } http_response->status_code = status_code; http_response->headers = header_buf; http_response->content = response_content.str(); http_response->headers += RequestHandlerUtil::GetContentLength(http_response->content); BOOST_LOG_TRIVIAL(info) << "ProxyHandler::Redirect-> response_code: " \ << http_response->status_code << ", " \ << http_response->mime_type << ", " \ << http_response->headers; return http_response; } catch (std::exception& e) { http_response->status_code = 500; http_response->content = "Error serving proxy content!"; return http_response; } }
true
ca47d5d32038839313cec58de5be61c021b79b03
C++
ravikiranc07/PGJQP_RAVIKIRAN
/assignment 3/palindrome.cpp
UTF-8
592
3.5625
4
[]
no_license
#include<iostream> using namespace std; class Palindrome { int rev=0,rem,num,n; public : void display() { cout<<"enter the number"; cin>>num; n=num; while(num>0) { rem=num%10; rev=rev*10+rem; num=num/10; } cout<<"reverse:"<<rev<<"\n"; if(rev==n) { cout<<"it is a palindrome"; } else { cout<<"it is not a palindrome"; } } }; int main() { Palindrome p1; p1.display(); }
true
c3cd13c77eb97f35187ce03ff88655c14305339a
C++
zxkyjimmy/zerojudge
/d368.cpp
UTF-8
323
2.5625
3
[]
no_license
#include <iostream> using namespace std; class chess { public: uint64_t P, N, B, R, Q, K; uint64_t p, n, b, r, q, k; uint64_t e; char str[65]; void read() { for(int i = 0; i < 64; i++) { cin >> str[i]; } } }; int main() { return 0; }
true