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
4085e3869c0f591d6eb02a526fbe713a02e2cb7e
C++
RonakKhandelwal/Algorithim
/Lab/warshal.cpp
UTF-8
651
3.03125
3
[]
no_license
#include <iostream> using namespace std; void warshal(int a[][4],int n){ int sol[4][4]; for(int i=0;i<4;i++){ for(int j=0;j<4;j++){ sol[i][j]=a[i][j]; } } for(int i=0;i<4;i++){ for(int j=0;j<4;j++){ for(int k=0;k<4;k++){ sol[i][j]=sol[i][j] || (sol[i][k] && sol[k][j]); } } } for(int i=0;i<4;i++){ for(int j=0;j<4;j++){ cout<<sol[i][j]<<"\t"; } cout<<endl; } } int main(){ int graph[4][4] = { {1, 1, 0, 1}, {0, 1, 1, 0}, {0, 0, 1, 1}, {0, 0, 0, 1} }; warshal(graph,4); }
true
72753284a92dc16ec1009f2015c32b1297e8b3ca
C++
jxzhsiwuxie/cppPrimer
/chap02/exercises/ex_2.24.cpp
UTF-8
275
3.171875
3
[]
no_license
//练习 2.24:在下面这段代码中,为什么 p 合法而 lp 非法? //int i = 42; void *p = &i; long *lp = &i; /* p 是 void* 类型的指针,它可以用来存放任意类型的对象的地址。 lp 是 long 型的指针无法存放 int 型对象的地址。 */
true
073567a2310fe3f2b8468501f8017ff6ee8b2a79
C++
ArchivedPixLed/PixLedLanguage
/components/pixled/scene/scene.cpp
UTF-8
1,153
2.796875
3
[]
no_license
#include "scene.h" Scene::Scene() { this->localTime = std::shared_ptr<Integer>(new Integer(0)); ESP_LOGI("SEQ", "init %li", this->localTime.get()->get()); } void Scene::addLayer(std::shared_ptr<Layer> layer) { this->layers.push_back(layer); } void Scene::setStopCondition(std::shared_ptr<Condition> stopCondition) { this->stopCondition = stopCondition; } std::shared_ptr<Integer> Scene::getLocalTime() { return this->localTime; } void Scene::run(RenderingLayer* rendering_layer, std::shared_ptr<Integer> globalTime) { // Base layer while(!this->stopCondition.get()->yield()) { ESP_LOGD("SEQ", "gt: %li", globalTime.get()->get()); ESP_LOGD("SEQ", "lt: %li", this->localTime.get()->get()); for(std::shared_ptr<Layer> layer : this->layers) { ESP_LOGD("SEQ", "merging %p", layer.get()); rendering_layer->merge(layer.get()); } rendering_layer->render(); rendering_layer->show(); this->localTime.get()->increment(1); globalTime.get()->increment(1); } }; Scene::~Scene() { ESP_LOGI("SEQ", "Delete seq %p", this); /* for(int i = 0; i < this->layerCount; i++) { delete this->layers[i]; } delete this->layers; */ }
true
f1e8d9373907b10d55e9a77fb37ab372e26148c6
C++
NadanKim/Direct-3D-Study
/LabProjects/LabProject10/Timer.h
UHC
1,222
2.6875
3
[ "MIT" ]
permissive
#pragma once const ULONG MAX_SAMPLE_COUNT = 50; // 50ȸ óð Ͽ Ѵ. class CGameTimer { public: CGameTimer(); virtual ~CGameTimer(); void Tick(float fLockFPS = 0.0f); void Start(); void Stop(); void Reset(); unsigned long GetFrameRate(LPTSTR lpszString = NULL, int nCharacters = 0); float GetTimeElapsed(); float GetTotalTime(); private: bool m_bHardwareHasPerformanceCounter; // ǻͰ Performance Counter ִ° float m_fTimeScale; // Scale Counter float m_fTimeElapsed; // ð __int64 m_nCurrentTime; // ð __int64 m_nLastTime; // ð __int64 m_nBaseTime; __int64 m_nPausedTime; __int64 m_nStopTime; __int64 m_nPerformanceFrequency; // ǻ Performance Frequency float m_fFrameTime[MAX_SAMPLE_COUNT]; // ð ϱ 迭 ULONG m_nSampleCount; // Ƚ unsigned long m_nCurrentFrameRate; // Ʈ unsigned long m_nFramesPerSecond; // ʴ float m_fFPSTimeElapsed; // Ʈ ҿ ð bool m_bStopped; };
true
d5fe6d73f47f851f192dfbf84ede4a8dddb79a74
C++
mbryksin/stuff
/year2012/143grouptasks/sem-1/hometask-10/Task10_1/list.cpp
UTF-8
2,861
3.734375
4
[]
no_license
#include <stdlib.h> #include "list.h" #include <stdio.h> List *createList() { List *list = new List; list->head = NULL; return list; } bool isEmpty(List *list) { return list->head == NULL; } void destroyList(List *list) { while (! isEmpty(list)) { ListElement *temp = list->head; list->head = temp->next; delete temp; } } void addListElement(List *list, int degree, int factor) { if (isEmpty(list)) { ListElement *temp = new ListElement; temp->degree = degree; temp->factor = factor; temp->next = NULL; list->head = temp; } else if (degree < list->head->degree) { ListElement *temp = new ListElement; temp->next = list->head; temp->degree = degree; temp->factor = factor; list->head = temp; } else { ListElement *current = list->head; while ((current->next != NULL) && (current->next->degree <= degree)) { current = current->next; } if (current->degree == degree) { printf("%dth degree's already exist\n", degree); return; } ListElement *temp = new ListElement; temp->next = current->next; current->next = temp; temp->degree = degree; temp->factor = factor; } } void printList(List *list) { if (isEmpty(list)) { printf("No elements\n"); return; } ListElement *current = list->head; while (current != NULL) { printf("%d*x^%d ", current->factor, current->degree); current = current->next; } printf("\n"); } bool equals(List *p, List *q) { ListElement *tempP = p->head; ListElement *tempQ = q->head; while ((tempP != NULL) && (tempQ != NULL)) { if ((tempP->degree == tempQ->degree) && (tempP->factor == tempQ->factor)) { tempP = tempP->next; tempQ = tempQ->next; } else return false; } return (tempP == NULL) && (tempQ == NULL); } int value(List *list, int x) { if (isEmpty(list)) { return INT_MAX; } ListElement *current = list->head; int result = 0; while (current != NULL) { int temp = 1; for (int i = 0; i < current->degree; i++) { temp *= x; } result += temp * current->factor; current = current->next; } return result; } void addLists(List *p, List *q, List *r) { ListElement *tempP = p->head; ListElement *tempQ = q->head; while ((tempP != NULL) && (tempQ != NULL)) { if (tempP->degree < tempQ->degree) { addListElement(r, tempP->degree, tempP->factor); tempP = tempP->next; } else if (tempP->degree > tempQ->degree) { addListElement(r, tempQ->degree, tempQ->factor); tempQ = tempQ->next; } else { addListElement(r, tempQ->degree, tempP->factor + tempQ->factor); tempP = tempP->next; tempQ = tempQ->next; } } if (tempP == NULL) { while (tempQ != NULL) { addListElement(r, tempQ->degree, tempQ->factor); tempQ = tempQ->next; } } else { while (tempP != NULL) { addListElement(r, tempP->degree, tempP->factor); tempP = tempP->next; } } }
true
fadd52b3bd1833b826a49977eac415b146d10692
C++
abenito343/eclipse-workspace
/Ejerc3/src/Ejerc3.cpp
UTF-8
650
3.265625
3
[]
no_license
//============================================================================ // Name : Ejerc3.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; int main() { int a; cout <<"Ingrese 1 numero:"<< endl; cin >> a ; cout <<"La division real por 5 es: " << (double) a/5 << endl; cout <<"El resto de la division entera es: " << a%5 << endl; cout <<"La septima parte de la quinta parte es: " << (double) a/5/7 << endl; return 0; }
true
e23d13bb939098a616ab6d9a2cad6e8c8e23ebdc
C++
tech4me/ANN-RL-reversi
/reversi/Player.h
UTF-8
256
2.609375
3
[]
no_license
#pragma once #include "Piece.h" #include "Board.h" class Player { protected: color col; virtual ~Player() {}; public: color get_color() const; void init_player(bool _is_black); virtual void move(Board & board, bool & game_end) = 0; };
true
ceb50211b453aaa0f0ad79d1244634be13ab302d
C++
anthro2020/SPOJ-1
/3377. A Bug’s Life/BUGLIFE.cpp
UTF-8
1,412
2.6875
3
[]
no_license
#include <iostream> #include <cstdio> #include <vector> #include <cstring> #include <algorithm> #include <cmath> #include <sstream> #include <map> #include <list> #include <queue> using namespace std; int currentcolor; int color[2000]; bool visited[2000]; bool suspicious; queue<int> q; list<int> *adj; bool bfs(){ while(!q.empty()){ int temp; temp=q.front(); q.pop(); //cout<<temp<<endl; visited[temp]=true; currentcolor=abs(color[temp]-1); list<int>::iterator i; for(i=adj[temp].begin();i!=adj[temp].end();i++){ if(visited[*i]==true){ if(color[*i]==color[temp]) return true; } else{ color[*i]=currentcolor; q.push(*i); } } } return false; } int main(){ int t=0; scanf("%d",&t); for(int j=1;j<=t;j++){ memset(color,-1,sizeof(color)); memset(visited,false,sizeof(visited)); suspicious=true; int g,n; scanf("%d%d",&g,&n); adj=new list<int>[g]; for(int i=0;i<n;i++){ int v,w; scanf("%d%d",&v,&w); adj[v-1].push_back(w-1); adj[w-1].push_back(v-1); } printf("Scenario #%d:\n",j); for(int i=0;i<g;i++){ currentcolor=1; if(visited[i]==false){ suspicious=true; color[i]=currentcolor; q=queue<int>(); q.push(i); suspicious=bfs(); if(suspicious==true){ break; } } } if(suspicious) printf("Suspicious bugs found!\n"); else printf("No suspicious bugs found!\n"); } return 0; }
true
ba0f7fd965811c67b5167d72790e4b2e112f8826
C++
adong001/C-C-_NC_Day
/动态规划(1)/动态规划(1)/斐波那契数列.cpp
GB18030
606
3.546875
4
[]
no_license
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; //Ҷ֪쳲УҪһn //쳲еĵn0ʼ0Ϊ0 //n <= 39 class Solution { public: int Fibonacci(int n) { int fn = 1,fn_1 = 1, fn_2 = 1; if (n <= 0) { return 0; } if (n == 1 || n == 2) { return 1; } for (int i = 3; i <= n; i++) { fn_2 = fn_1; fn_1 = fn; fn = fn_1 + fn_2; } return fn; } }; int main1() { Solution t; cout << t.Fibonacci(5) << endl; system("pause"); return 0; }
true
656a25e610daac2945763d16c17aa3e993962ee0
C++
HeliumProject/Engine
/Source/Tools/EditorScene/Pick.h
UTF-8
11,490
2.640625
3
[ "BSD-3-Clause" ]
permissive
#pragma once #include "EditorScene/API.h" #include "Math/Line.h" #include "Math/Frustum.h" #include "Foundation/SmartPtr.h" #include "Foundation/Numeric.h" #include "Reflect/Object.h" #include "EditorScene/Visitor.h" namespace Helium { namespace Editor { class Camera; class PickHit; typedef Helium::SmartPtr<PickHit> PickHitPtr; typedef std::vector<PickHitPtr> V_PickHitSmartPtr; // // Pick is an encapsulation of a user interaction with the screen // namespace PickTypes { enum PickType { Line, Frustum, }; }; namespace PickFlags { enum PickFlag { IgnoreNormal = 1 << 0, IgnoreVertex = 1 << 1, IgnoreIntersection = 1 << 2, }; } typedef PickFlags::PickFlag PickFlag; class PickVisitor : public Visitor { protected: // flags uint32_t m_Flags; // required for construction const Editor::Camera* m_Camera; // the results of the picking V_PickHitSmartPtr m_PickHits; // the object that will be associated with the hits generated in Pick() functions Reflect::Object* m_CurrentObject; // matrices to map to and from world space and local space // - testing is performed in local space // - results are stored in global space) Matrix4 m_CurrentWorldTransform; Matrix4 m_CurrentInverseWorldTransform; public: PickVisitor(const Editor::Camera* camera); protected: PickVisitor(const PickVisitor& rhs) { } public: virtual const PickTypes::PickType GetPickType() const = 0; uint32_t GetFlags() const { return m_Flags; } bool HasFlags(uint32_t flags) const { return (m_Flags & flags) != 0; } void SetFlags(uint32_t flags) { m_Flags = flags; } void SetFlag(uint32_t flag, bool value) { if (value) { m_Flags |= flag; } else { m_Flags &= ~flag; } } const Editor::Camera* GetCamera() const { return m_Camera; } protected: PickHit* AddHit(); public: void AddHit (PickHit* pickHit) { m_PickHits.push_back (pickHit); } const V_PickHitSmartPtr& GetHits() const { return m_PickHits; } bool HasHits() const { return !m_PickHits.empty(); } void ClearHits() { m_PickHits.clear(); } size_t GetHitCount() const { return m_PickHits.size(); } void SetHitCount(size_t count) { HELIUM_ASSERT( count <= m_PickHits.size() ); m_PickHits.resize( count ); } void SetCurrentObject(Reflect::Object* object) { m_CurrentObject = object; } void SetCurrentObject(Reflect::Object* object, const Matrix4& worldSpaceTransform) { m_CurrentObject = object; m_CurrentWorldTransform = worldSpaceTransform; m_CurrentInverseWorldTransform = worldSpaceTransform.Inverted(); // working in local space Transform(); } void SetCurrentObject(Reflect::Object* object, const Matrix4& worldSpaceTransform, const Matrix4& inverseWorldSpaceTransform) { m_CurrentObject = object; m_CurrentWorldTransform = worldSpaceTransform; m_CurrentInverseWorldTransform = inverseWorldSpaceTransform; // working in local space Transform(); } virtual void Transform() = 0; // picking functions (produce hits) virtual bool PickPoint(const Vector3& p, const float err = HELIUM_LINEAR_INTERSECTION_ERROR) = 0; virtual bool PickSegment(const Vector3& p1,const Vector3& p2, const float err = HELIUM_LINEAR_INTERSECTION_ERROR) = 0; virtual bool PickTriangle(const Vector3& v0,const Vector3& v1,const Vector3& v2, const float err = HELIUM_LINEAR_INTERSECTION_ERROR) = 0; virtual bool PickSphere(const Vector3& center, const float radius) = 0; virtual bool PickBox(const AlignedBox& box) = 0; // testing functions (no hits) virtual bool IntersectsBox(const AlignedBox& box) const = 0; }; class LinePickVisitor : virtual public PickVisitor { protected: Line m_PickSpaceLine; Line m_WorldSpaceLine; public: LinePickVisitor(const Editor::Camera* camera, const int x, const int y); LinePickVisitor(const Editor::Camera* camera, const Line& line); protected: LinePickVisitor(const LinePickVisitor& rhs) : PickVisitor (rhs) { } public: virtual const PickTypes::PickType GetPickType() const override { return PickTypes::Line; } const Line& GetPickSpaceLine() const { return m_PickSpaceLine; } const Line& GetWorldSpaceLine() const { return m_WorldSpaceLine; } virtual void Transform() override; // picking functions (produce hits) virtual bool PickPoint(const Vector3& p, const float err = HELIUM_LINEAR_INTERSECTION_ERROR) override; virtual bool PickSegment(const Vector3& p1,const Vector3& p2, const float err = HELIUM_LINEAR_INTERSECTION_ERROR) override; virtual bool PickTriangle(const Vector3& v0,const Vector3& v1,const Vector3& v2, const float err = HELIUM_LINEAR_INTERSECTION_ERROR) override; virtual bool PickSphere(const Vector3& center, const float radius) override; virtual bool PickBox(const AlignedBox& box) override; // testing functions (no hits) virtual bool IntersectsBox(const AlignedBox& box) const override; protected: // hit adding functions bool AddHitPoint(const Vector3& p, Vector3& offset); bool AddHitSegment(const Vector3& p1,const Vector3& p2, float32_t mu, Vector3& offset); bool AddHitTriangle(const Vector3& v0,const Vector3& v1,const Vector3& v2, float32_t u, float32_t v, bool interior, Vector3& vertex, Vector3& intersection, float distance); bool AddHitTriangleClosestPoint(const Vector3& v0,const Vector3& v1,const Vector3& v2, const Vector3& point); bool AddHitBox(const AlignedBox& box, Vector3& intersection); }; class FrustumPickVisitor : virtual public PickVisitor { protected: Frustum m_PickSpaceFrustum; Frustum m_WorldSpaceFrustum; public: FrustumPickVisitor(const Editor::Camera* camera, const int pixelX, const int pixelY, const float pixelBoxSize = -1.0f); FrustumPickVisitor(const Editor::Camera* camera, const Frustum& worldSpaceFrustum); protected: FrustumPickVisitor(const FrustumPickVisitor& rhs) : PickVisitor (rhs) { } public: virtual const PickTypes::PickType GetPickType() const override { return PickTypes::Frustum; } const Frustum& GetPickSpaceFrustum() const { return m_PickSpaceFrustum; } const Frustum& GetWorldSpaceFrustum() const { return m_WorldSpaceFrustum; } virtual void Transform() override; // picking functions (produce hits) virtual bool PickPoint(const Vector3& p, const float err = HELIUM_LINEAR_INTERSECTION_ERROR) override; virtual bool PickSegment(const Vector3& p1,const Vector3& p2, const float err = HELIUM_LINEAR_INTERSECTION_ERROR) override; virtual bool PickTriangle(const Vector3& v0,const Vector3& v1,const Vector3& v2, const float err = HELIUM_LINEAR_INTERSECTION_ERROR) override; virtual bool PickSphere(const Vector3& center, const float radius) override; virtual bool PickBox(const AlignedBox& box) override; // testing functions (no hits) virtual bool IntersectsBox(const AlignedBox& box) const override; protected: // hit adding functions bool AddHitPoint(const Vector3& p); bool AddHitSegment(const Vector3& p1,const Vector3& p2); bool AddHitTriangle(const Vector3& v0,const Vector3& v1,const Vector3& v2); bool AddHitSphere(const Vector3& center); bool AddHitBox(const AlignedBox& box); }; class FrustumLinePickVisitor : virtual public LinePickVisitor, virtual public FrustumPickVisitor { public: FrustumLinePickVisitor(const Editor::Camera* camera, const int pixelX, const int pixelY, const float pixelBoxSize = -1.0f); FrustumLinePickVisitor(const Editor::Camera* camera, const Line& line, const Frustum& worldSpaceFrustum); protected: FrustumLinePickVisitor(const FrustumLinePickVisitor& rhs) : PickVisitor (rhs), LinePickVisitor (rhs), FrustumPickVisitor(rhs) { } public: virtual const PickTypes::PickType GetPickType() const override { return PickTypes::Frustum; } virtual void Transform() override; // picking functions (produce hits) virtual bool PickPoint(const Vector3& p, const float err = HELIUM_LINEAR_INTERSECTION_ERROR) override; virtual bool PickSegment(const Vector3& p1,const Vector3& p2, const float err = HELIUM_LINEAR_INTERSECTION_ERROR) override; virtual bool PickTriangle(const Vector3& v0,const Vector3& v1,const Vector3& v2, const float err = HELIUM_LINEAR_INTERSECTION_ERROR) override; virtual bool PickSphere(const Vector3& center, const float radius) override; virtual bool PickBox(const AlignedBox& box) override; // testing functions (no hits) virtual bool IntersectsBox(const AlignedBox& box) const override; }; // // PickHit encapsulates a hit of a pick with an object // namespace PickSortTypes { enum PickSortType { Intersection, // General intersection... allows for slop... nearest to camera the better Surface, // Must intersect a surface Vertex, // Find the nearest vertex }; } typedef PickSortTypes::PickSortType PickSortType; class PickHit : public Helium::RefCountBase<PickHit> { // // Object hit // private: Reflect::Object* m_HitObject; public: Reflect::Object* GetHitObject() const { return m_HitObject; } void SetHitObject(Reflect::Object* object) { m_HitObject = object; } // // Normal at intersection // private: bool m_HasNormal; Vector3 m_Normal; public: bool HasNormal() const { return m_HasNormal; } Vector3 GetNormal() const { return m_Normal; } void SetNormal(const Vector3& value) { m_Normal = value; m_HasNormal = true; } // // Vertex nearest intersection // private: bool m_HasVertex; float32_t m_VertexDistance; Vector3 m_Vertex; public: bool HasVertex() const { return m_HasVertex; } float32_t GetVertexDistance() const { return m_VertexDistance; } const Vector3& GetVertex() const { HELIUM_ASSERT(m_HasVertex); return m_Vertex; } void SetVertex(const Vector3& value, float32_t distance = NumericLimits<float32_t>::Maximum) { m_HasVertex = true; m_VertexDistance = distance; m_Vertex = value; } // // Location of intersection // private: bool m_HasIntersection; float32_t m_IntersectionDistance; Vector3 m_Intersection; public: bool HasIntersection() const { return m_HasIntersection; } float32_t GetIntersectionDistance() const { return m_IntersectionDistance; } Vector3 GetIntersection() const { HELIUM_ASSERT(m_HasIntersection); return m_Intersection; } void SetIntersection(const Vector3& value, float32_t distance = NumericLimits<float32_t>::Maximum) { m_Intersection = value; m_IntersectionDistance = distance; m_HasIntersection = true; } // // Implementation // PickHit(Reflect::Object* o) : m_HitObject (o) , m_HasNormal (false) , m_HasVertex (false) , m_VertexDistance (NumericLimits<float32_t>::Maximum) , m_HasIntersection (false) , m_IntersectionDistance (NumericLimits<float32_t>::Maximum) { } static void Sort(Editor::Camera* camera, const V_PickHitSmartPtr& hits, V_PickHitSmartPtr& sorted, PickSortType sortType); }; } }
true
19931c4e72c192fa3cde522f01e57f77fc39fe1d
C++
depp/terrestrial-collection-machine
/dev/loader.hpp
UTF-8
848
2.953125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
#pragma once #include <functional> #include <memory> #include <string> #include <vector> namespace tcm { // Change the current directory to the Bazel workspace root. void ChdirWorkspaceRoot(void); // Read the contents of a file into a vector. Returns 0 on success, or the error // code on failure. int ReadFile(const std::string &path, std::vector<char> *data); // A buffer containing the contents of a file. using DataBuffer = std::shared_ptr<const std::vector<char>>; // Callback for when a file changes. The function is passed the new contents of // the file, or nullptr if the file does not exist or could not be read. using WatchCallback = std::function<void(const DataBuffer &)>; // Watch for changes in the given file, and call a function when it changes. void WatchFile(std::string path, WatchCallback callback); } // namespace tcm
true
cb51e92fbdbc8f3b3559d7ec38224d2a2032ce40
C++
tangyiyong/coroutinecc
/test/test.cc
UTF-8
817
2.578125
3
[ "MIT" ]
permissive
#include <cstdio> #include "coroutine.h" using namespace Coroutinecc; using namespace std; struct args { int n; }; static void foo(Scheduler* s, void* ud) { args* arg = reinterpret_cast<args*>(ud); int start = arg->n; for(int i = 0; i < 5; i++) { ::printf("coroutine %d : %d\n", s->running(), start + i); s->yield(); } } static void test(Scheduler* s) { args arg1 = { 0 }; args arg2 = { 200 }; ptrdiff_t co1 = s->add(foo, &arg1); ptrdiff_t co2 = s->add(foo, &arg2); printf("main start\n"); while((*s)[co1] && (*s)[co2]) { if((*s)[co1]) s->resume(co1); if((*s)[co2]) s->resume(co2); } printf("main end\n"); } int main() { Scheduler* s = new Scheduler(); test(s); return 0; }
true
0d9e2439e0efc40896af1b6ef9cf517ac4f6f58c
C++
Momonyaro/RoguEngine
/olcRoguEngine/roguSrc/entities/entityManager.h
UTF-8
340
2.71875
3
[ "MIT" ]
permissive
#pragma once #include "entity.h" class EntityManager { public: ~EntityManager() { player->~Entity(); } inline Entity* getPlayer() { return player; } void setPlayer(Entity* playerEntity) { player = playerEntity; } private: Entity* player = new Entity("Player", { 1, 1 }, new rogu::Sprite({ 15, 0 }), 10, 10, 1); };
true
54aaa28760d976e7a6a9b375c49201f9d07373a4
C++
jhass/project_helix
/src/objects/Torus.h
UTF-8
1,293
2.8125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#ifndef PH_TORUS_H #define PH_TORUS_H #include <string> #include <osg/Geode> #include <osg/Geometry> using namespace std; using namespace osg; namespace ph { class Torus : public Geode { public: enum Style {NORMAL, FLAT}; Torus(const double iRadius, const double tRadius, const int iteration); void setStyle(const Style style); void setTexture(const int textureNumner, const string filename); private: double iRadius; // inner radius from origin to the object double tRadius; // radius of the torus-circle int iteration; // number of iterations for angle phi and theta //phi: angle of the torus-circle; theta: angle of the circle through the torus ref_ptr<Geometry> torus; Style style; // enum for normal or flat torus void compute(); void setCoordinates(); void setIndicies(); Vec3d calculateVertex(const double theta, const double phi); Vec3d calculateNormal(const double theta, const double phi); }; class FlatTorus : public Torus { public: FlatTorus(const double iRadius, const double tRadius, const int phiIteration); }; } #endif
true
7f1a632deeb8767e8de0c6b4e4cfe63adc0b3918
C++
orre1996/TankWarsNetworked
/network-protocol-CLIENT/source/TextString.h
UTF-8
597
2.515625
3
[]
no_license
#pragma once #include <vector> #include "FontManager.h" #include "TextTexture.h" class DrawManager; class TextString { public: void GenerateText(std::string p_text, int m_x, int m_y); void GenerateText(); void DrawText(); void SetText(std::string p_text); TextString(); ~TextString(); DrawManager* m_drawManager; std::string GetText(); void SetPosition(int p_x, int p_y); int GetX(); int GetY(); private: std::string m_text; TextTexture m_textTexture; SDL_Rect m_rect; FontManager m_font; SDL_Color m_color; int m_x; int m_y; };
true
c89373169423c2fdf28be3d70b6d62f99b35188c
C++
gbenga007/KinectCPP
/ServerClientComm/src/Client.cpp
UTF-8
6,035
3.078125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <pthread.h> #include <iostream> #include <string> #define MSG_SIZE 400 // Message size int n, sock; unsigned int length; struct sockaddr_in anybody, from; char buffer[MSG_SIZE]; // To store received messages or messages to be sent. // Get current date/time, format is YYYY-MM-DD.HH:mm:ss const std::string currentDateTime() { time_t now = time(0); struct tm tstruct; char buf[80]; tstruct = *localtime(&now); // Visit http://en.cppreference.com/w/cpp/chrono/c/strftime // for more information about date/time format strftime(buf, sizeof(buf), "%Y-%m-%d %X", &tstruct); return buf; } // Error Message // ------------- void error(const char *msg) { perror(msg); exit(0); } // Thread to receive all messages // ------------------------------ void *receiveSignals(void *ptr){ while(1){ // bzero: to "clean up" the buffer. bzero(buffer,MSG_SIZE); // receive message n = recvfrom(sock, buffer, MSG_SIZE, 0, (struct sockaddr *)&from, &length); if (n < 0) error("recvfrom"); printf("Message from %s is: %s\n", inet_ntoa(from.sin_addr), buffer); } pthread_exit(0); } // Display command line usage // -------------------------- void displayMessage(){ printf("\nThe messages should either on of the following\n"); printf("\tTest -- Test established link with all machines\n"); printf("\t&# Test -- Test with individual machine with last ip octate as #\n"); printf("\tKinect/Kill -- Turn ON/OFF all kinects\n"); printf("\t&# Kinect/Kill -- Turn ON/OFF individual kinect connected to machine " "ip(last octate) #\n\n"); } // Main program // ------------ int main(int argc, char *argv[]){ int boolval = 1; // for a socket option // if (argc != 2) // { // printf("usage: %s port\n", argv[0]); // exit(1); // } sock = socket(AF_INET, SOCK_DGRAM, 0); // Creates socket. Connectionless. if (sock < 0) error("socket"); // change socket permissions to allow broadcast if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &boolval, sizeof(boolval)) < 0) { printf("error setting socket options\n"); exit(-1); } anybody.sin_family = AF_INET; // Symbol constant for Internet domain // anybody.sin_port = htons(atoi(argv[1])); // Port field anybody.sin_port = htons(5000); // Port field anybody.sin_addr.s_addr = inet_addr("192.168.1.255"); // Broadcast address length = sizeof(struct sockaddr_in); // size of structure /* This variable is our reference to the second thread */ pthread_t sigThID; /* Create a second thread to receive messages from peers */ if(pthread_create(&sigThID, NULL, receiveSignals, NULL)){ fprintf(stderr, "Error creating thread\n"); return 1; } // Get the system date and time and send a system command to server which // can modify the date/time of the system the server running. In our case, // it will be the TK1's whose time will be updated. bzero(buffer,MSG_SIZE); // bzero: to "clean up" the buffer. std::string sysDateTime = currentDateTime(); // System date & time sprintf(buffer, "sudo date -s \"%s\"", sysDateTime.c_str()); n = sendto(sock, buffer, strlen(buffer), 0, (const struct sockaddr *)&anybody,length); if (n < 0) error("Sendto: While sending date and time"); do { // bzero: to "clean up" the buffer. bzero(buffer,MSG_SIZE); printf("Please enter the message (q to exit):\n"); fgets(buffer,MSG_SIZE-1,stdin); // MSG_SIZE-1 because a null character is added if (buffer[0] != 'q'){ if (buffer[0] == '&'){ // Send to Individual IP // Split strings into pieces (tokens) using strtok char *anybodyIP = NULL; anybodyIP = strtok(buffer, "&"); anybodyIP = strtok(anybodyIP, " "); // Get the IP char *msg = strtok(NULL, " "); // Get the message like Start/Stop msg = strtok(msg, "\n"); char anybodyIP_Full[15]; printf("The value of the last IP is: %s\n", anybodyIP); sprintf(anybodyIP_Full, "192.168.1.%d", atoi(anybodyIP)%256); printf("You will send the message \"%s\" to the IP: %s\n\n", msg, anybodyIP_Full); // Send the message anybody.sin_addr.s_addr = inet_addr(anybodyIP_Full); // Unicast address n = sendto(sock, msg, strlen(msg), 0, (const struct sockaddr *)&anybody,length); if (n < 0) error("Sendto: While sending mesaage to individual machine"); }else if((strncasecmp(buffer, "Kill", 4) == 0) || (strncasecmp(buffer, "Kinect", 6) == 0)|| (strncasecmp(buffer, "Test", 4) == 0)){ // Send to All IPs printf("You will send the message \"%s\" to all the IPs\n\n", strtok(buffer, "\n")); // Change the address to brodcast. anybody.sin_addr.s_addr = inet_addr("192.168.1.255"); // Broadcast address n = sendto(sock, buffer, strlen(buffer), 0, (const struct sockaddr *)&anybody,length); if (n < 0) error("Sendto: While broadcasting to all machines"); }else{ // Set it to the broadcast IP as it is the default. anybody.sin_addr.s_addr = inet_addr("192.168.1.255"); // Broadcast address displayMessage(); } } } while (buffer[0] != 'q'); close(sock); // Close Socket. return 0; }
true
dda2be8e1e28b3dd3beff44bda3e434b24fa1462
C++
UTD-MrPeterson/VirtualTest
/main.cpp
UTF-8
549
3.109375
3
[]
no_license
#include <iostream> #include "DerivedClass.h" using namespace std; void asBase(const BaseClass& baseObj) { cout << "\"Base\" object:" << endl; baseObj.nonVirtualMethod(); baseObj.virtualMethod(); baseObj.pureVirtualMethod(); } void asDerived(const DerivedClass& derivedObj) { cout << "Derived object:" << endl; derivedObj.nonVirtualMethod(); derivedObj.virtualMethod(); derivedObj.pureVirtualMethod(); } int main() { DerivedClass myDerived; asBase(myDerived); asDerived(myDerived); return 0; }
true
bfd8d579e5ed7dc75d184e0a318547a3728de7f9
C++
anguszxd/video-segmentation
/reference-code/ViBe/vibe C++代码/BackGroundModel.cpp
GB18030
14,340
2.53125
3
[ "BSD-2-Clause", "BSD-2-Clause-Views" ]
permissive
/************ Ķ˳ BackGroundModel::classificationMThreadǴ *************/ #include "StdAfx.h" #include "BackGroundModel.h" #include <iostream> #include <time.h> #include <fstream> #define MAX_THREAD 10 using namespace std; DWORD WINAPI ThreadClassification(LPVOID pParam) { ParameterClassification *param = (ParameterClassification *)pParam; int nWidth = param->m_nWidth; int nHeight = param->m_nHeight; int nRadius = param->m_nRadius; int nThreshold = param->m_nThreshold; int nModelSize = param->m_nModelSize; int nRowIndex = param->m_nRowIndex; int nRows = param->m_nRows; byte * pForeground = param->m_pForeground; byte * pIntensity = param->m_pIntensity; byte * pModel = param->m_pModel; int nImageSize = nWidth * nHeight; int nDifference = 0; int nOffset = 0; int nIntensityModel, nIntensityFrame; for(int n = 0; n < nWidth * nRows ; n++) { int nCount = 0; int bUpdate = false; // set to be foreground pForeground[n] = pIntensity[n]; for(int j = 0; j < nModelSize; j++) { // offset for the same pixel of the model nOffset = j * nImageSize + nRowIndex * nWidth + n; nIntensityModel = pModel[nOffset]; nIntensityFrame = pIntensity[n]; nDifference = nIntensityModel - nIntensityFrame; if(nDifference <= nRadius && nDifference >= -nRadius) { nCount++; } // classfiy as background if(nCount >= nThreshold) { pForeground[n] = 0; bUpdate = true; break; } } // ֱʱͿռ update a backround pixel; if(bUpdate) { //initialize random seed: srand ((unsigned int) time(NULL) ); //generate randaom number: int nIndex = rand() % nModelSize; // update randomly in time sequence nOffset = nIndex * nImageSize + nRowIndex * nWidth + n; pModel[nOffset] = pIntensity[n]; srand ((unsigned int) time(NULL) ); nIndex = rand() % 8; // update randomly in spatially nOffset = getOffset(nOffset, nWidth, nHeight, nIndex); if(nOffset > 0) { pModel[nOffset] = pIntensity[n]; } } } return 0; } BackGroundModel::BackGroundModel( int nWidth, int nHeight, int nModelSize, int nRadius, int nThreshold ) { try{ m_nWidth = nWidth; m_nHeight = nHeight; m_nModelSize = nModelSize; m_nRadius = nRadius; m_nForeBackThreshold = nThreshold; m_nInitCount = 0; m_bModelInitialized = false; initialModelMemory(); }catch(exception &e) { throw e; }; } BackGroundModel::~BackGroundModel(void) { if(m_pModel) { delete [] m_pModel; m_pModel = NULL; } } //void BackGroundModel::preprocess(byte * pIntensity, int nWidth, int nHeight) //{ // IplImage * pGrayImage = cvCreateImage(cvSize(nWidth,nHeight),8,1); // IplImage * pTmpImage = cvCreateImage(cvSize(nWidth,nHeight),8,1); // char * pTmp = pGrayImage->imageData; // pGrayImage->imageData = (char *) pIntensity; // cvSmooth(pGrayImage, pTmpImage, CV_MEDIAN, 3, 3); // //cvEqualizeHist(pTmpImage, pGrayImage); // pIntensity = (byte *)pTmpImage->imageData; // pTmpImage->imageData = pTmp; // cvReleaseImage(&pTmpImage); // cvReleaseImage(&pGrayImage); //} //void BackGroundModel::postprocess(byte * pForeground, int nWidth, int nHeight) //{ // IplImage * pGrayImage = cvCreateImage(cvSize(nWidth,nHeight),8,1); // IplImage * pTmpImage = cvCreateImage(cvSize(nWidth,nHeight),8,1); // char * pTmp = pGrayImage->imageData; // pGrayImage->imageData = (char *) pForeground; // cvDilate(pGrayImage, pTmpImage, NULL, 1); // cvErode( pTmpImage, pGrayImage, NULL, 2); // cvDilate(pGrayImage, pTmpImage, NULL, 3); // pForeground = (byte *) pTmpImage->imageData; // pTmpImage->imageData = pTmp; // cvReleaseImage(&pTmpImage); // cvReleaseImage(&pGrayImage); //} // //classificationMThread һΪ //ͼݣͼͼߣб int BackGroundModel::classificationMThread(byte * pIntensity, int nWidth, int nHeight, byte * pForeground) { try { //preprocess(pIntensity, nWidth, nHeight); //ʼģͣm_nModelSizeƣҪԤȶٷͼ //ݷm_pModel if(!m_bModelInitialized) { //ͼأߣʼ initialModelData(pIntensity, nWidth, nHeight, m_nInitCount); m_nInitCount++; //ʼΪ0¼ʼͼ֡ return 0; } if(!pIntensity || nWidth != m_nWidth || nHeight!= m_nHeight) { throw exception("Input intensity image is not correct"); } if(!pForeground) { throw exception("Foregrund is not initialized"); } //ʼ㷨 HANDLE hThread[MAX_THREAD]; int nDivision = nHeight / MAX_THREAD; //ͼΪ10飬10߳ͬʱ int nIndex = 0; ParameterClassification param[MAX_THREAD]; for(int i = 0; i < MAX_THREAD; i++) { param[i].m_nHeight = nHeight; param[i].m_nWidth = nWidth; param[i].m_nRadius = m_nRadius; param[i].m_nRowIndex = i * nDivision; int nIndex = i * nDivision * nWidth; //ʼ //ֹͼ߲ܱMAX_THREAD if( i == MAX_THREAD -1) { int nVal = nHeight % MAX_THREAD; if(nVal !=0) { nDivision = nVal; } } param[i].m_nRows = nDivision; param[i].m_nThreshold = m_nForeBackThreshold; param[i].m_nModelSize = m_nModelSize; // param[i].m_pModel = m_pModel; //ͼָ param[i].m_pIntensity = pIntensity + nIndex; param[i].m_pForeground = pForeground + nIndex; //CreateThread̺߳windows APIеĺ //ThreadClassificationԼдĺ /*CreateThread˵ lpThreadAttributesָSECURITY_ATTRIBUTES̬Ľṹָ롣 Windows 98кԸòWindows NTУΪNULLʾʹȱʡֵ dwStackSize̶߳ջСһ=0κ£WindowsҪ̬ӳջĴС lpStartAddressָָ̺߳룬ʽ@ûƣ DZʽ DWORD WINAPI ThreadProc (LPVOID lpParam) ʽȷ޷óɹ lpParameter̺߳ݵIJһָṹָ룬贫ݲʱΪNULL dwCreationFlags ̱߳־,ȡֵ 1CREATE_SUSPENDED-----һ̣߳ 20--------------------ʾ lpThreadId:̵߳id ֵ: ɹ߳̾ʧܷfalse */ hThread[i] = CreateThread(NULL,0,ThreadClassification,param + i,0,0); if (hThread[i] == NULL) { throw exception("Failed to create thread for classification"); } } //windowsAPIԵȴں˶ DWORD bRet = WaitForMultipleObjects(MAX_THREAD, hThread , TRUE, INFINITE); for(int i=0; i< MAX_THREAD; i++) { //ر߳ CloseHandle(hThread[i]); } //ԭϣһ˲ //postprocess(pForeground, nWidth, nHeight); return 0; }catch(exception &e) { throw e; } } // //int BackGroundModel::classificationMThreadIPP(byte * pIntensity, int nWidth, int nHeight, byte * pForeground) //{ // try // { // if(!m_bModelInitialized) // { // this->initialModelData(pIntensity, nWidth, nHeight, m_nInitCount); // m_nInitCount++; // return 0; // } // if(!pIntensity || nWidth != m_nWidth || nHeight!= m_nHeight) // { // throw exception("Input intensity image is not correct"); // } // if(!pForeground) // { // throw exception("Foregrund is not initialized"); // } // byte * pDifferenceModel = NULL; // if(!(pDifferenceModel = new byte[m_nArraySize])) // { // throw exception("Memory allocation failed"); // } // // calculate the abolute difference with IPP // IppStatus status; // IppiSize roiSize; // roiSize.width = nWidth; // roiSize.height = nHeight; // // for(int i = 0; i < m_nModelSize; i++) // { // int nIndex = i * m_nImageSize; // status = ippiAbsDiff_8u_C1R(m_pModel + nIndex, nWidth, pIntensity, nWidth, pDifferenceModel + nIndex, nWidth, roiSize); // } // HANDLE hThread[MAX_THREAD]; // int nDivision = nHeight / MAX_THREAD; // int nIndex = 0; // // ParameterClassification param[MAX_THREAD]; // for(int i = 0; i < MAX_THREAD; i++) // { // // param[i].m_nHeight = nHeight; // param[i].m_nWidth = nWidth; // param[i].m_nRadius = m_nRadius; // param[i].m_nRowIndex = i * nDivision; // int nIndex = i * nDivision * nWidth; // if( i == MAX_THREAD -1) // { // int nVal = nHeight % MAX_THREAD; // if(nVal !=0) // { // nDivision = nVal; // } // } // param[i].m_nRows = nDivision; // param[i].m_nThreshold = m_nForeBackThreshold; // param[i].m_nModelSize = m_nModelSize; // param[i].m_pModel = m_pModel; // param[i].m_pDifferenceModel = pDifferenceModel ; // param[i].m_pIntensity = pIntensity + nIndex; // param[i].m_pForeground = pForeground + nIndex; // // hThread[i] = CreateThread(NULL,0,ThreadClassificationIPP,param + i,0,0); // if (hThread[i] == NULL) // { // throw exception("Failed to create thread for classification"); // } // } // // DWORD bRet = WaitForMultipleObjects(MAX_THREAD, hThread , TRUE, INFINITE); // // for(int i=0; i< MAX_THREAD; i++) // { // CloseHandle(hThread[i]); // } // if(pDifferenceModel) // { // delete [] pDifferenceModel; // pDifferenceModel = NULL; // } // return 2; // }catch(exception &e) // { // throw e; // } //} int BackGroundModel::classification( byte * pIntensity, int nWidth, int nHeight, byte * pForeground) { try { if(!m_bModelInitialized) { this->initialModelData(pIntensity, nWidth, nHeight, m_nInitCount); m_nInitCount++; return 0; } if(!pIntensity || nWidth != m_nWidth || nHeight!= m_nHeight) { throw exception("Input intensity image is not correct"); } if(!pForeground) { throw exception("Foregrund is not initialized"); } // perform the classifiction int nDifference = 0; int nOffset = 0; for(int i = 0; i < m_nImageSize; i++) { int nCount = 0; int bUpdate = false; // set to be foreground pForeground[i] = 255; for(int j = 0; j < m_nModelSize; j++) { nOffset = j * m_nImageSize + i; nDifference = m_pModel[nOffset] - pIntensity[i]; if(nDifference <= m_nRadius && nDifference >= -m_nRadius) { nCount++; } // classfiy as background if(nCount >= m_nForeBackThreshold) { pForeground[i] = 0; bUpdate = true; break; } } // update a backround pixel; if(bUpdate) { // update randomly in time sequence //initialize random seed: srand ((unsigned int) time(NULL) ); //generate randaom number: int nIndex = rand() % m_nModelSize; nOffset = nIndex * m_nImageSize + i; m_pModel[nOffset] = pIntensity[i]; srand ((unsigned int) time(NULL) ); nIndex = rand() % 8; // update randomly in spatially nOffset = getOffset(nOffset, nWidth, nHeight, nIndex); if(nOffset > 0) { m_pModel[nOffset] = pIntensity[i]; } } } return 1; }catch(exception &e) { throw e; } } //ͼأߣʼ void BackGroundModel::initialModelData(byte * pIntensity, int nWidth, int nHeight, int nIndex) { try { // input validation if(!pIntensity) { throw exception("Image data is not correct"); } if(nWidth != m_nWidth || nHeight != m_nHeight) { throw exception("Input image width or height does not match model"); } if(nIndex > m_nModelSize || nIndex <0) { throw exception("Model index out of model size"); } //nOffsetһƫͼƬݶm_pModel int nOffset = m_nImageSize * nIndex; //srcַָΪʼַnֽڵݸƵdestַָΪʼַĿռ //void *memcpy(void *dest, const void *src, size_t n); memcpy(m_pModel + nOffset, pIntensity, m_nImageSize); // check if the model intializaed or not if(nIndex == m_nModelSize - 1) { m_bModelInitialized = true; } }catch(exception &e) { throw e; } } void BackGroundModel::initialModelMemory() { try { // Validation of model image width and height if(m_nWidth <= 0 || m_nHeight <= 0) { throw exception("Model image height and width not setting properly"); } // Validation of model size if(m_nModelSize <= 0) { throw exception("Model size not initialled properly"); } m_nImageSize = m_nWidth * m_nHeight; m_nArraySize = m_nImageSize * m_nModelSize; if(!(m_pModel = new byte[m_nArraySize])) { throw exception("Memory allocation failed"); } memset(m_pModel, 0, m_nArraySize); }catch(exception &e) { throw e; } } //԰ͨ int getOffset(int nIndex, int nWidth, int nHeight, int nRandom) { int s_size = nWidth * nHeight; int nOffset = -1; switch(nRandom) { case 0: if(nIndex - nWidth > 0) { nOffset = nIndex - nWidth; } break; case 1: if(nIndex - nWidth + 1 > 0) { nOffset = nIndex - nWidth + 1; } break; case 2: if(nIndex + 1 < s_size) { nOffset = nIndex + 1; } break; case 3: if(nIndex + nWidth + 1 < s_size) { nOffset = nIndex + nWidth + 1; } break; case 4: if(nIndex + nWidth < s_size) { nOffset = nIndex + nWidth; } break; case 5: if(nIndex + nWidth -1 < s_size) { nOffset = nIndex + nWidth - 1; } break; case 6: if(nIndex -1 > 0) { nOffset = nIndex - 1; } break; case 7: if(nIndex - nWidth - 1 > 0) { nOffset = nIndex - nWidth - 1; } break; } return nOffset; }
true
4fcc3d5ef76f5efdf214d3991ac05d79373c3b05
C++
rwhelan/Distance
/Distance.ino
UTF-8
1,560
3.03125
3
[]
no_license
// Output Pins, IN ORDER from LSB to MSB (hard coded currently to 10 pins) int Pins[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 16}; // Which Analog pin is the sensor on int SensorPin = 0; // Number of samples to keep const int numSamples = 10; int Samples[numSamples]; int idx = 0; // delay between readings const int loopDelay = 100; // Serial output of the values? const bool withSerial = false; void WriteOutInt(int num){ // This function takes an int and writes it out over the // output pins. LOW is HIGH and HIGH is LOW after the // logic shift in the IC connected to the output pins for (int i = 0; i < 10; i++){ if ( (num >> i) & 1 ){ digitalWrite(Pins[i], LOW); } else { digitalWrite(Pins[i], HIGH); } } } int sampleAvg(){ // Returns a floored avg of all the values in the Samples[] Array int total = 0; for (int i = 0; i < numSamples; i++) { total += Samples[i]; } return total / numSamples; } void setup() { if (withSerial) { Serial.begin(9600); } // Set all Pins[] as output pins and set them all HIGH // which is wired to be LOW for (int i = 0; i < 10; i++){ pinMode(Pins[i], OUTPUT); digitalWrite(Pins[i], HIGH); } } void loop() { if (idx >= numSamples) { idx = 0; } Samples[idx] = analogRead(SensorPin); idx += 1; if (withSerial) { for (int i = 0; i < numSamples; i++) { Serial.print(Samples[i]); Serial.print(" "); } Serial.print("- "); Serial.print(sampleAvg()); Serial.print("\n"); } WriteOutInt(sampleAvg()); delay(loopDelay); }
true
c1b87029f1bc7afa858e2244aac5efad99bacdb3
C++
yaoReadingCode/Uni_World
/2. adds/list/adds-pe.cpp
UTF-8
4,518
3.65625
4
[]
no_license
#include<iostream> using namespace std; /* General instructions: Please modify this file and submit the modified one via svn and then websubmission (under the entry "pracExam"). No design documents or header files are needed. You only need to submit one file, which is this one. This exam is marked out of 10 marks and is worth 20% of your overall marks. */ struct Node { int data; Node* next; }; int list_size(Node* head){ int sizeL = 0; Node* temp = head; while (temp != NULL){ sizeL = sizeL +1; temp = temp->next; } temp=NULL; delete temp; return sizeL; } void printNode(Node* head){ Node* temp = head; while (temp != NULL){ std::cout << temp->data << ", "; temp = temp->next; } std::cout<<std::endl; } /* Task 1: Implement the following function for adding a new node to the front of the given list with double the given value. input Nodes* head: a head pointer to a list int val: an integer that represent a value. return the head pointer of the new list after the insertion Example: add a node with given value 9 before HEAD->1->2->3->NULL after HEAD->18->1->2->3->NULL 3 marks(1 for style, 2 for functionality) */ Node* addDouble(Node* head, int val){ int valdouble = val*2; Node *newNode = new Node; newNode->data = valdouble; newNode->next = head; head = newNode; return head; } /* Task 2: Implement the following function for deleting the elements in the even position of the given list. Assume the head node is in position 1. input Nodes* head: a head pointer to a list return void output The list after the deletion Example: input HEAD->1->2->3->9->12->NULL output HEAD->1->3->12->NULL 3 marks(1 for style, 2 for functionality) */ void clearEven(Node* head){ Node* temp = head->next; Node* prev = head; int size = list_size(head); for (int i = 1; i< size; i++){ if (i % 2 != 0){ prev->next = temp->next; } prev = temp; temp = temp->next; } } /* Task 3: Implement the following function for printing the node with value greater than the threshold between Node n1 and Node n2. input Nodes* n1: a pointer to a node in a list Nodes* n2: a pointer to a node in the same list int threshold: a given value as threshold return void Example: input n1 points to the 1st node n2 points to the 5th node val = 2 before HEAD->1->2->3->9->12->NULL output F->3->9 (1 is smaller than 2) ------------------------------------ input n1 points to the 7th node n2 points to the 2nd node val = 4 before HEAD->2->8->9->1->4->7->12->NULL output 9->F->F->7 (1 and 4 are not greater than 4) 4 marks(1 for style, 3 for functionality) */ void printSeg(Node* n1, Node* n2, int val){ Node* current = n1->next; while ( current != n2 ) { if (current->data > val){ std::cout << current -> data; } else { std::cout << "F"; } if (current->next != n2) std::cout << "->" ; current = current->next; } std::cout << std::endl ; } // You are not supposed to change the main function int main() { Node* head = NULL; Node *p3, *p7; for(int i = 1; i < 10; i++) { head = addDouble(head, i); if (i==3) p3 = head; if (i==7) p7 = head; } // at this point, we have created the following list: HEAD->18->16->14->12->10->8->6->4->2->NULL // p3 now points to the node containing 6); p7 now points to the node containing 14) clearEven(head); // The resulting list is HEAD->18->14->10->6->2->NULL //You can uncomment this line to test. //the output should be: 10 //Please remember to comment this line out before submitting //printSeg(p3, p7, 0); head = addDouble(head, 16); head = addDouble(head, 20); // at this point, the list is: HEAD->40->32->18->14->10->6->2->NULL clearEven(p7); //In the list starting for p7, there are 4 nodes. //remove nodes 10 and 2. //The list after the function call is: HEAD->20->16->18->14->6->NULL printSeg(head, p3, 15); // the output should be: 16->18->F // free all nodes Node* tmp; while (head) { tmp = head; head = head->next; delete tmp; } return 0; }
true
95a5044cbcdb04e135489c363128c972654bb534
C++
DMU-XMU/PSR-MCTS-Offline
/POSyadmin/POMDP-MCTS/POMDP-MCTS-posy/src/planners/MDPutils.cpp
UTF-8
4,004
2.65625
3
[]
no_license
#include "MDPutils.h" #include "utils/utils.h" namespace MDPutils{ void policyEvaluation(uint S, uint A, bool rsas, double* P, double* R, double gamma, double epsilon, const uint* PI, double* V){ assert(gamma > 0); assert(gamma < 1); // != 1 to guarantee convergence uint SA = S*A; double sqeps = epsilon*epsilon; double* V0 = new double[S]; double* V1 = new double[S]; for(size_t l=0;l<S;++l) V1[l]=0.0; size_t z = 1; double* Vu; double* Vv; size_t ll; //size_t it = 0; do{ if(z==1){ Vu = V1;Vv = V0;z=0; } else{ Vu = V0;Vv = V1;z=1; } for(ll=0; ll<S; ++ll){ if(!rsas) Vv[ll] = R[ll*A+PI[ll]] + gamma*utils::inner_prod(P+ll*SA+PI[ll]*S,Vu,S); else{ Vv[ll] = 0; uint aS = PI[ll]*S; uint lSA = ll*SA; for(uint ss=0;ss<S;++ss) Vv[ll] += P[lSA+aS+ss]*(R[lSA+aS+ss] + gamma*Vu[ss]); } } //std::cout << ++it << " " << utils::sqnorm_2(V0,V1,S) << " " << sqeps << std::endl; } while(utils::sqnorm_2(V0,V1,S) > sqeps); memcpy(V,Vv,S*sizeof(double)); delete[] V0; delete[] V1; } void valueIteration(uint S, uint A, bool rsas, double* P, double* R, double gamma, double epsilon, uint* PI, double* V){ assert(gamma > 0); assert(gamma < 1); // != 1 to guarantee convergence uint SA = S*A; double sqeps = epsilon*epsilon; //Initialize value function //(Create 2 to avoid copying memory each iteration) double* V0 = new double[S]; double* V1 = new double[S]; for(size_t ll=0;ll<S;++ll) V1[ll]=0.0; size_t z = 1; double* Vu; double* Vv; double Q[S][A]; size_t ll,aa; do{ if(z==1){ Vu = V1;Vv = V0;z=0; } else{ Vu = V0;Vv = V1;z=1; } for(ll=0;ll<S;++ll){ PI[ll] = 0; Vv[ll] = -std::numeric_limits<double>::infinity(); uint lSA = ll*SA; for(aa=0;aa<A;++aa){ if(!rsas){ Q[ll][aa] = R[ll*A+aa] + gamma*utils::inner_prod(P+lSA+aa*S,Vu,S); } else{ Q[ll][aa] = 0; uint aS = aa*S; for(uint ss=0;ss<S;++ss){ Q[ll][aa] += P[lSA+aS+ss]*(R[lSA+aS+ss] + gamma*Vu[ss]); } } if(Q[ll][aa] > Vv[ll]){ PI[ll] = aa; Vv[ll] = Q[ll][aa]; } } } // std::cout << utils::sqnorm_2(V0,V1,S) << " " << std::flush; } while(utils::sqnorm_2(V0,V1,S) > sqeps); memcpy(V,Vv,S*sizeof(double)); delete[] V0; delete[] V1; } void valueIterationRmax(uint S, uint A, bool rsas, double* P, double* R, double gamma, double epsilon, uint* PI, double* V, const uint* counts, uint B){ assert(gamma > 0); assert(gamma < 1); // != 1 to guarantee convergence //TEMP: assumes rmax=1 double Vmax = 1/(1-gamma); uint SA = S*A; double sqeps = epsilon*epsilon; //Initialize value function //(Create 2 to avoid copying memory each iteration) double* V0 = new double[S]; double* V1 = new double[S]; for(size_t ll=0;ll<S;++ll) V1[ll]=0.0; size_t z = 1; double* Vu; double* Vv; double Q[S][A]; size_t ll,aa; do{ if(z==1){ Vu = V1;Vv = V0;z=0; } else{ Vu = V0;Vv = V1;z=1; } for(ll=0;ll<S;++ll){ PI[ll] = 0; Vv[ll] = -std::numeric_limits<double>::infinity(); uint lSA = ll*SA; for(aa=0;aa<A;++aa){ //TEMP super non-efficient uint sum = 0; for(uint ss=0;ss<S;++ss) sum += counts[lSA+aa*S+ss]; if(sum < B) Q[ll][aa] = R[ll*A+aa] + gamma*Vmax; //Transition to absorbing state with max reward at every step else if(!rsas) Q[ll][aa] = R[ll*A+aa] + gamma*utils::inner_prod(P+lSA+aa*S,Vu,S); else{ Q[ll][aa] = 0; uint aS = aa*S; for(uint ss=0;ss<S;++ss){ Q[ll][aa] += P[lSA+aS+ss]*(R[lSA+aS+ss] + gamma*Vu[ss]); } } if(Q[ll][aa] > Vv[ll]){ PI[ll] = aa; Vv[ll] = Q[ll][aa]; } } } } while(utils::sqnorm_2(V0,V1,S) > sqeps); memcpy(V,Vv,S*sizeof(double)); delete[] V0; delete[] V1; } }
true
55891dc28f6dcc3b1169c4703dda4ee6c43b5cd8
C++
Tsun4mii/SYO-2020
/SYO-2020/Generation/GenLib/GenLib.cpp
UTF-8
500
2.84375
3
[]
no_license
#include<iostream> extern "C" { int __stdcall outnum(int value) { std::cout << value; return 0; } int __stdcall outstr(char* ptr) { setlocale(LC_ALL, "RUSSIAN"); if (ptr == nullptr) { std::cout << std::endl; } for (int i = 0; ptr[i] != '\0'; i++) std::cout << ptr[i]; return 0; } int _stdcall sqroot(int i) { return (int)std::sqrt(i); } int _stdcall module(int i) { return (int)std::fabs(i); } int _stdcall input(int i) { std::cin >> i; return i; } }
true
a7bb1818ea6c89657de2852cd7e96655024d42e8
C++
kasuyaazura/FP2020
/LaboratoriosFunda/Guia 6/Ejercicio_1.cpp
UTF-8
1,060
3.34375
3
[]
no_license
#include "iostream" #include "string" #include "stdio.h" using namespace std; /* Ejercicio #1 */ int main(){ //declaramos el puntero para que el tamaño sea dinamico int * numeros = NULL; int datos,numero; cout << "Que cantidad de datos desea ingresar? " <<endl; cin >> datos; numeros = new int [datos]; for (size_t i = 0; i < datos; i++) { cout << "Ingrese el dato numero " << i+1 <<":"<<endl; cin>>numero; numeros[i]=numero; numero=0; } cout<<"\nDatos: "<<endl; for (size_t j = 0; j < datos; j++) { cout<< numeros[j]<<" "; } //liberamos memoria delete [] numeros; numeros = NULL; return 0; }
true
dad066e249396ef34a4c6a08a16ef03a06169c1d
C++
vsvipul11/Datastructres_CPP
/ARRAYS/Two_sum.cpp
UTF-8
652
2.984375
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> #include <algorithm> using namespace std; vector <int> sol(vector<int> &v , int target){ unordered_set<int> s; vector<int> ans; for(int i = 0 ; i < v.size() ; i++){ int x = target - v[i]; if(s.find(x) != s.end() ){ ans.push_back(x); ans.push_back(v[i]); return ans; } s.insert(v[i]); } } int main(){ vector<int> a{1, 4 ,2 ,5 ,3 ,9 ,8}; int target = 6; auto p = sol(a , target); for(int i = 0 ; i < p.size() ; i++){ cout<<p[i]<<" "; } return 0; }
true
bb2c08f3ec400f4a985a76314008a16463304352
C++
maashok/CS2
/spanning_tree/src/binaryHeap.hpp
UTF-8
2,804
3.796875
4
[]
no_license
#include "star.hpp" /** * A binary min-heap so that the stars with lowest distance to source * are at the top of the heap */ class BHeap { std::vector <Star *> bheap; public: BHeap(std::map<int, Star *> stars, Star *src) { // Distance from source to source is zero, all other // distances infinity src->distance = 0; src->previous = NULL; std::map<int, Star *>::iterator i; for (i = stars.begin(); i != stars.end(); i++) { Star *curr = i->second; if (curr->getID() != src->getID()) { curr->distance = std::numeric_limits<double>::infinity(); curr->previous = NULL; } this->insert(curr); } } // Insert a node into the binary heap void insert(Star *toInsert) { // Add node initially as a leaf to the end bheap.push_back(toInsert); int child = bheap.size() - 1; int parent = (child-1)/2; // While the child's distance is less than the parent's // distance move it up in the heap while (parent >= 0 && bheap[child]->distance < bheap[parent]->distance) { swap(child, parent); child = parent; parent = (child-1)/2; } } // Remove a node from the binary heap Star* remove() { // If only one element just remove it if (bheap.size() == 1) { Star *lastOne = bheap[0]; bheap.pop_back(); return lastOne; } // Otherwise, switch the first and last element for easier // removal and remove the one now at the end (the smallest value) swap(bheap.size() -1, 0); Star *toRemove = bheap[bheap.size() - 1]; bheap.pop_back(); int parent = 0; int child = 2*parent + 1; // If the parent is larger than the child, move it down while(child < bheap.size() && (bheap[parent]->distance > bheap[child]->distance || bheap[parent]->distance > bheap[child+1]->distance)){ if (bheap[child]->distance > bheap[child+1]->distance) { child++; } swap(parent, child); parent = child; child = 2*parent + 1; } return toRemove; } // Finding takes O(n) time int find(Star *toFind) { for (int i = 0; i < bheap.size(); i++) { if (toFind->getID() == bheap[i]->getID()) return i; } } // If you find the shortest distance to source for some star, // change it and move it up in the heap if necessary void changeDist(Star *toChange, double distToSource) { toChange->distance = distToSource; int child = find(toChange); int parent = (child-1)/2; while (bheap[child]->distance < bheap[parent]->distance) { swap(child, parent); child = parent; parent = (child-1)/2; } } // Swap two elements of the binary heap void swap(int swap1, int swap2) { Star *temp = bheap[swap1]; bheap[swap1] = bheap[swap2]; bheap[swap2] = temp; } bool empty() { return bheap.size() <= 0; } };
true
2635befd4abc0c7d3c6ef8e35b4977b1a3ebd721
C++
smzztx/Cpp_Concurrency_In_Action
/testcode/chrono_test.cpp
UTF-8
374
2.921875
3
[]
no_license
#include <iostream> #include <chrono> #include <unistd.h> int main() { auto start = std::chrono::high_resolution_clock::now(); sleep(1); auto end = std::chrono::high_resolution_clock::now(); std::cout << "in seconds time:"; std::chrono::duration<double,std::ratio<1,1>> duration_s(end-start); std::cout << duration_s.count() << " seconds" << std::endl; return 0; }
true
b8408e43e4e9b093ded896f6a465961ddb521751
C++
jsanchez97/Assignment-5-Abstract-Class-and-Command-Line-Parameters
/main.cpp
UTF-8
5,311
3.890625
4
[]
no_license
/****************************************************************************** * AUTHOR : Jesus Sanchez * STUDENT ID : 1024834 * ASSIGNMENT #5 : Abstract Classes and Command Line Parameters * CLASS : CS1C * SECTION : MW: 1:30pm * DUE DATE : 02/27/2017 * ****************************************************************************/ #include "Square.h" #include "Triangle.h" /****************************************************************************** * ABSTRACT CLASSES AND COMMAND LINE PARAMETERS * ---------------------------------------------------------------------------- * This program uses a Square class and a Triangle class that are derived from * an abstract class called Shape. The user is prompted to enter the sides of a * Square and a Triangle object respectively and the perimeter and area of the * shape are printed after the dimensions are entered. Then, the program uses * the second and third parameters in the command line which are previously * defined as a first and last name and prints the entire name and then the * second letter of each name. * ---------------------------------------------------------------------------- * INPUT: * side : Length of sides of a square. * side1, side2, side3 : Lengths of sides of a triangle. * * OUTPUT: * Perimeter and area of both shapes. * *****************************************************************************/ void PrintHeader(string labName, char labType, int labNum); int main(int argc, char *argv[]) { Square square; // Square object. Triangle triangle; // Triangle object. float side; // Length of sides of a Square. float side1, side2, side3; // Length of sides of a Triangle object. PrintHeader("Abstract Classes and Command Line Parameters", 'A', 5); cout << setw(30) << "----- PART 1 -----" << endl << endl; // Prompts the user to enter the length of a square's sides and ensures that // the value entered is positive. do { cout << "Enter the length of a side of the square: "; cin >> side; cin.ignore(1000, '\n'); if(side <= 0) { cout << endl << "Side cannot be negative!" << endl << endl; } }while(side <= 0); // Sets the length of the square's sides. square.SetSides(side); // Prints the perimeter of the square. PrintPerimeter(square); PrintArea(square); // Prompts the user for the lengths of the sides of the triangle and ensures // that the values entered are positive at each step. do { cout << "Enter the length of the first side of the triangle: "; cin >> side1; cin.ignore(1000, '\n'); if(side1 <= 0) { cout << endl << "Side cannot be negative!" << endl << endl; } }while(side1 <= 0); do { cout << "Enter the length of the second side of the triangle: "; cin >> side2; cin.ignore(1000, '\n'); if(side2 <= 0) { cout << endl << "Side cannot be negative!" << endl << endl; } }while(side2 <= 0); do { cout << "Enter the length of the third side of the triangle: "; cin >> side3; cin.ignore(1000, '\n'); if(side3 <= 0) { cout << endl << "Side cannot be negative!" << endl << endl; } }while(side3 <= 0); // Sets the values of the sides of the triangle. triangle.SetSides(side1, side2, side3); // Prints the perimeter and area of the triangle. PrintPerimeter(triangle); PrintArea(triangle); cout << setw(30) << "----- PART 2 -----" << endl << endl; cout << "My name is "; // Offsets the index of argv and outputs the remaining parameters in the // command line. for(int index = 1; index < argc; index++) { cout << argv[index]; if(index < argc - 1) { cout << " "; } else { cout << "." << endl << endl; } } // Offsets the address that argv is pointing to, dereferences that, and then // offsets the address one more time and dereferences that to print the // second character in the string it is pointing to. cout << "Second Letter in First Name: " << *(*(argv + 1) + 1) << endl << "Second Letter in Last Name: " << *(*(argv + 2) + 1) << endl; return 0; } /****************************************************************************** * PrintHeader * ---------------------------------------------------------------------------- * This function prints the project header. * ---------------------------------------------------------------------------- * PRE-CONDITIONS: * labName - Lab Name has to be preciously defined * labType - Lab Type has to be preciously defined * labNum - Lab Number has to be preciously defined * * POST-CONDITIONS: * This function will print the class heading. *****************************************************************************/ void PrintHeader(string labName, char labType, int labNum) { cout << left; cout << "***************************************************************\n"; cout << "* PROGRAMMED BY : Jesus Sanchez"; cout << "\n* " << setw(15) << "STUDENT ID" << ": 1024834" ; cout << "\n* " << setw(15) << "CLASS" << ": MW: 1:30pm - 2:50pm"; cout << "\n* "; if(toupper(labType) == 'L') { cout << "LAB #" << setw(9); } else { cout << "ASSIGNMENT #" << setw(2); } cout << labNum << " : " << labName; cout << "\n***************************************************************\n\n"; cout << right; }
true
9fa1fe675450d99feeac4d55d9de65d2e68348ae
C++
lauedoucet/BlackJack
/main.cpp
UTF-8
1,524
3.34375
3
[]
no_license
/* Copyright 2020, Laurence Doucet, All rights reserved */ #include "blackjack.h" using namespace std; int main() { cout << "\t Welcome to the COMP322 Blackjack game!" << endl << endl; /**************Game set up************************/ BlackJackGame game; HumanPlayer player = HumanPlayer(); ComputerPlayer casino = ComputerPlayer(); game.addPlayer(player); game.addCasino(casino); game.getPlayer().displayBalance(); cout << endl; game.getPlayer().requestBet(); /***************Game loop*************************/ bool play_again = true; char answer; while (play_again) { game.getPlayer().displayBalance(); game.getPlayer().displayBet(); cout << endl; game.play(); /*********Clear hands in case they want to play a new round*****************/ game.getCasino().getHand().clear(); game.getPlayer().getHand().clear(); cout << "Would you like another round? (y/n): "; cin >> answer; cout << endl << endl; if (answer == 'y') { cout << "Would you like to reset your bet? (y/n): "; cin >> answer; cout << endl; if (answer == 'y') { game.getPlayer().requestBet(); play_again = true; } } else { play_again = false; } } char goodbye; cout << "Game over!" << endl << "Press any key to say goodbye :)" << endl; cin >> goodbye; return 0; }
true
b17ec78a0ab337334d35990b49c30c91b9d0c03a
C++
chaidamu519/Algorithms
/C++/Character_Sequences/Project2/Project2/Source2.cpp
UTF-8
430
2.984375
3
[]
no_license
#include<iostream> #include<string.h> #include<ctype.h> using namespace std; int main() { char s1[80], s2[80]; char result; cin.getline(s1, 80); cin.getline(s2, 80); int i = 0; while (s1[i] != '\0' && (tolower(s1[i]) == tolower(s2[i]))) { i++; } if (tolower(s1[i]) > tolower(s2[i])) { result = '>'; } else if (tolower(s1[i]) < tolower(s2[i])) { result = '<'; } else { result = '='; } cout << result; }
true
f2ed6343f31bb0c47be3d842f880d9c8ca0fdd77
C++
mrowqa/siktacka
/common/network/UdpSocket.cpp
UTF-8
1,288
3.015625
3
[]
no_license
#include <common/network/UdpSocket.hpp> #include <cassert> constexpr std::size_t max_datagram_size = 512; Socket::Status UdpSocket::init(HostAddress::IpVersion ip_ver) noexcept { return Socket::init(ip_ver, SOCK_DGRAM); } Socket::Status UdpSocket::send(const std::string &data, const HostAddress &dst_addr) noexcept { auto addr_ptr = dst_addr.get(); assert(addr_ptr != nullptr); if (data.size() > max_datagram_size) { return Status::Error; } int sent = sendto(sockfd, data.c_str(), data.size(), 0, &addr_ptr->addr, addr_ptr->addrlen); if (sent < 0) { return get_error_status(); } return Status::Done; } Socket::Status UdpSocket::receive(std::string &buffer, HostAddress &src_addr) noexcept { buffer.resize(max_datagram_size); preallocated_sock_addr.clear(); preallocated_sock_addr.ip_version = ip_ver; int bytes_received = recvfrom(sockfd, &buffer[0], max_datagram_size, 0, &preallocated_sock_addr.addr, &preallocated_sock_addr.addrlen); if (bytes_received < 0) { return get_error_status(); } buffer.resize(bytes_received); src_addr.set(preallocated_sock_addr); return Status::Done; }
true
72d2b5b8ab09d257f8b2962c0a7dbb532472dfa6
C++
scintillavoy/baekjoon-online-judge
/2292.cc
UTF-8
202
2.65625
3
[]
no_license
#include <iostream> using namespace std; int main() { int N; cin >> N; --N; int distance; for (distance = 1; N > 0; ++distance) { N -= distance * 6; } cout << distance; return 0; }
true
5cdcb03e33db25b6638b1ba33dfabb82aefe2ca2
C++
zghanxiao/algorithm_finished_china
/advanced_algorithm/bytedance/SearchInRotatedArray_ck.cpp
UTF-8
1,379
3.515625
4
[]
no_license
class Solution { public: /** * @param A: an integer rotated sorted array * @param target: an integer to be searched * @return: an integer */ bool check(vector<int> & A, int index, int left, int right, int target) { if (A[left] > A[right]) { if (A[index] >= A[left]) { return target >= A[left] && target <= A[index]; } if (A[index] <= A[right]) { return !(target > A[index] && target <= A[right]); } return false; } else { return A[index] >= target; } } int biMinSearch(vector<int> &A, int left, int right, int target) { while(left < right) { int mid = left + (right - left) / 2; if (A[mid] == target &&(mid == 0 || A[mid] != A[mid - 1])) { return mid; } if (check(A, mid, left, right, target)) { right = mid; } else { left = mid + 1; } } return left == right && check(A, right, left, right, target) ? right : right + 1; } int search(vector<int> &A, int target) { // write your code here int size = A.size(); int res = biMinSearch(A, 0, size - 1, target); if (res >= 0 && res <= size - 1 && A[res] == target) { return res; } else { return -1; } } };
true
bf4f112406b4a2cc613665815121701727c84854
C++
haphuongn739/code
/baitapchuong3/unit1.cpp
UTF-8
806
3.703125
4
[]
no_license
/* Name : Nguyen Thi Ha Phuong Bai 1 : Viết chương trình đọc vào 2 số nguyên và in ra kết quả của phép (+), phép trừ (-), phép nhân (*), phép chia (/). Nhận xét kết quả chia 2 số nguyên. .... */ #include <iostream> using namespace std; void main() { //Khai bao bien int nNum1 = 0; int nNum2 = 0; int nTong = 0; int nHieu = 0; int nTich = 0; int nThuong = 0; //Nhap gia tri cout << " Nhap so thu 1: "; cin >> nNum1; cout << " Nhap so thu 2: "; cin >> nNum2; //Tinh nTong = nNum1 + nNum2; nHieu = nNum1 - nNum2; nTich = nNum1 * nNum2; nThuong = (float) nNum1 / nNum2; //In ra ket qua cout << "tong la: " <<nTong <<endl; cout << "hieu la: " <<nHieu <<endl; cout << "tich la: " <<nTich <<endl; cout << "thuong la: " <<nThuong <<endl; system ("pause"); }
true
4bd7075d48e1e9a9736c945a2500f0ee7c17cbcd
C++
kiddos/notes
/codeforces/1700~1799/1766/d.cc
UTF-8
951
2.71875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; constexpr int MAX_VAL = 1e7; vector<int> min_div(MAX_VAL+1); void precompute() { iota(min_div.begin(), min_div.end(), 0); for (int i = 2; i <= MAX_VAL; ++i) { if (min_div[i] != i) continue; for (int j = i*2; j <= MAX_VAL; j += i) { min_div[j] = i; } } } void solve() { int x = 0, y = 0; cin >> x >> y; int diff = y-x; if (diff == 1) { cout << "-1" << endl; return; } int z = diff; vector<int> div; while (z > 1) { if (div.empty() || div.back() != min_div[z]) { div.push_back(min_div[z]); } z /= min_div[z]; } int ans = numeric_limits<int>::max(); for (int d : div) { int c = (x + d - 1) / d; ans = min(ans, c * d - x); } cout << ans << endl; } int main(void) { ios::sync_with_stdio(false); cin.tie(0); precompute(); int T = 0; cin >> T; for (int t = 0; t < T; ++t) { solve(); } return 0; }
true
1fbf8ea52c219a55c8189e21cbd6e62ff3ed54c4
C++
lmh760008522/ProgrammingExercises
/校程序设计比赛/c_ans.cpp
GB18030
1,223
3.09375
3
[]
no_license
#include<iostream> #include<cstdio> using namespace std; int f[21][2001]; int n,a[21],b[21]; void input(){ cin>>n; for(int i=1;i<=n;++i){ cin>>a[i]>>b[i]; } } /* :n,ҪABɡÿABɣʱֱΪaibi еҪʱ䡣 ǿp(i,j)ʾǰiAjʱBp(i,j)ʱɡ ƷҲ޸ˣiɵi-1ƳģôiABɣ AɣУp(i,j) = p(i-1,j-Ai) (Bʱ䲻䣩 BɣУp(i, j) = p(i-1,j)+ Bi (Aʱ䲻䣩 */ int solve(){ int sum=0;f[0][0]=0; for(int i=1;i<=n;++i){ sum+=a[i]; for(int j=0;j<=sum;++j){ f[i][j]=f[i-1][j]+b[i];//b if(j>=a[i]) f[i][j]=min(f[i][j],f[i-1][j-a[i]]); } } int ans=sum+1; for(int i=1;i<=sum;++i) ans=min(ans,max(i,f[n][i])); return ans; } int main(int argc, char *argv[]) { int t; scanf("%d",&t); while(t-- >0){ input(); cout<<solve()<<endl; } return 0; }
true
33d6a3c972dc6a376737c4935a04e82fc9199628
C++
oMalyugina/olimpiad_programming
/olimpiads/19-20/1777.cpp
UTF-8
3,260
2.96875
3
[]
no_license
// // Created by Olga Malyugina on 05.02.21. // #include <iostream> #include <time.h> #include <random> #include <vector> using namespace std; void print(const vector<vector<int>> & map){ for (int i = 0; i < map.size(); ++i) { for (int j = 0; j < map[0].size(); ++j) { cout << map[i][j] << " "; } cout << endl; } } int how_bad(const vector<vector<int>> & map){ int res = 0; for (int l = 0; l < map.size() - 1; ++l) { for (int r = l+1; r < map.size(); ++r) { for (int down = 0; down < map[0].size()-1; ++down) { for (int up = down+1; up < map[0].size(); ++up) { if(map[r][down] == map[r][up] and map[r][down] == map[l][down] and map[r][down] == map[l][up]) res++; } } } } return res; } vector<vector<int>> change(const vector<vector<int>> & map, int c, float ratio = 0.3){ vector<vector<int>> res = map; for (int k = 0; k < int(map.size()*map[0].size()*ratio)+1; ++k) { int i = rand() %map.size(); int j = rand() %map[0].size(); res[i][j] = rand()%c+1; } return res; } vector<vector<int>> generate(int n, int m, int c){ vector<vector<int>> res (n, vector<int>(m, 0)); for (int i = 0; i < 1; ++i) { for (int j = 0; j < res[0].size(); ++j) { int c_i = rand()%c+1; res[i][j] = c_i; } } return res; } void solve(int n, int m, int c){ cout << "n" << n << "m" << m << "c" << c << endl; int max_iter = 1000; int iter = 0; vector<vector<int>> map = generate(n, m, c); int current_bad = how_bad(map); while(current_bad > 0) { if (iter >= max_iter){ vector<vector<int>> map = generate(n, m, c); current_bad = how_bad(map); iter = 0; cout << "change" << endl; } int new_bad = current_bad; vector<vector<int>> possible_map(n, vector<int>(m, 0)); while (new_bad >= current_bad) { iter++; possible_map = change(map, c, 0.03); new_bad = how_bad(possible_map); } current_bad = new_bad; map = possible_map; } print(map); } int main(){ srand(time(nullptr)); int n,m,c; // n = 2, m = 10, c = 2; // solve(n, m, c); // n = 3, m = 6, c = 2; // solve(n, m, c); // n = 4, m = 4, c = 2; // solve(n, m, c); // n = 4, m = 6, c = 2; // solve(n, m, c); // n = 5, m = 4, c = 2; // solve(n, m, c); // n = 2, m = 10, c = 3; // solve(n, m, c); // n = 3, m = 10, c = 3; // solve(n, m, c); // n = 4, m = 4, c = 3; // solve(n, m, c); // n = 4, m = 6, c = 3; // solve(n, m, c); // n = 4, m = 7, c = 3; // solve(n, m, c); // n = 4, m = 10, c = 3; // solve(n, m, c); // n = 5, m = 6, c = 3; // solve(n, m, c); // n = 5, m = 10, c = 3; // solve(n, m, c); // n = 6, m = 7, c = 3; // solve(n, m, c); // n = 6, m = 10, c = 3; // solve(n, m, c); // n = 7, m = 10, c = 3; // solve(n, m, c); // n = 8, m = 10, c = 3; // solve(n, m, c); n = 9, m = 10, c = 3; solve(n, m, c); n = 10, m = 10, c = 3; solve(n, m, c); return 0; }
true
da323dae51fd8e2355e49f2bc61edd6201f9f289
C++
m4yers/mini-apple-debugger
/include/MAD/Prompt.hpp
UTF-8
4,925
2.65625
3
[ "MIT" ]
permissive
#ifndef PROMPT_HPP_5CZETNAV #define PROMPT_HPP_5CZETNAV // Std #include <deque> #include <map> #include <memory> #include <string> #include <vector> // Prompt #include "args/args.hxx" #include "linenoise/linenoise.h" // MAD #include <MAD/Error.hpp> namespace mad { //------------------------------------------------------------------------------ // Commands //------------------------------------------------------------------------------ enum class PromptCmdGroup { MAD, PROCESS, BREAKPOINT }; static inline std::string PromptCmdGroupToString(PromptCmdGroup Group) { switch (Group) { case PromptCmdGroup::MAD: return "mad"; case PromptCmdGroup::PROCESS: return "process"; case PromptCmdGroup::BREAKPOINT: return "breakpoint"; } } enum class PromptCmdType { MAD_EXIT, MAD_HELP, BREAKPOINT_SET, PROCESS_RUN, PROCESS_CONTINUE }; static inline std::string PromptCmdTypeToString(PromptCmdType Type) { switch (Type) { case PromptCmdType::MAD_EXIT: return "exit"; case PromptCmdType::MAD_HELP: return "help"; case PromptCmdType::PROCESS_RUN: return "run"; case PromptCmdType::PROCESS_CONTINUE: return "continue"; case PromptCmdType::BREAKPOINT_SET: return "set"; } } class Prompt; class PromptCmd { friend Prompt; protected: Error Err; args::ArgumentParser Parser; args::HelpFlag Help{ Parser, "MAD_HELP", "Show command help.", {'h', "help"}}; PromptCmdGroup Group; PromptCmdType Type; std::string Name; std::string Shortcut; // Top-level shortcut std::string Desc; public: PromptCmd(PromptCmdGroup Group, PromptCmdType Type, std::string Name, std::string Shortcut = nullptr, std::string Desc = "") : Parser(Desc), Group(Group), Type(Type), Name(Name), Shortcut(Shortcut), Desc(Desc) {} bool Parse(std::deque<std::string> &Arguments); auto GetGroup() { return Group; } auto GetType() { return Type; } bool IsValid() { return Err.Success(); } void PrintHelp() {} }; //----------------------------------------------------------------------------- // MAD //----------------------------------------------------------------------------- class PromptCmdMadHelp : public PromptCmd { public: PromptCmdMadHelp() : PromptCmd(PromptCmdGroup::MAD, PromptCmdType::MAD_HELP, "help", "?") {} }; class PromptCmdMadExit : public PromptCmd { public: PromptCmdMadExit() : PromptCmd(PromptCmdGroup::MAD, PromptCmdType::MAD_EXIT, "exit", "e") {} }; //----------------------------------------------------------------------------- // Breakpoint //----------------------------------------------------------------------------- class PromptCmdBreakpointSet : public PromptCmd { public: args::Group TargetGroup{Parser, "One of these must be specified", args::Group::Validators::Xor}; args::ValueFlag<std::string> SymbolName{ TargetGroup, "SYMBOL", "Name of a symbol", {'n', "name"}}; args::ValueFlag<std::string> MethodName{ TargetGroup, "METHOD", "Name of a method", {'m', "method"}}; public: PromptCmdBreakpointSet() : PromptCmd(PromptCmdGroup::BREAKPOINT, PromptCmdType::BREAKPOINT_SET, "set", "b") {} }; //----------------------------------------------------------------------------- // Process //----------------------------------------------------------------------------- class PromptCmdProcessRun : public PromptCmd { public: PromptCmdProcessRun() : PromptCmd(PromptCmdGroup::PROCESS, PromptCmdType::PROCESS_RUN, "run", "r") {} }; class PromptCmdProcessContinue : public PromptCmd { public: PromptCmdProcessContinue() : PromptCmd(PromptCmdGroup::PROCESS, PromptCmdType::PROCESS_CONTINUE, "continue", "c") {} }; //------------------------------------------------------------------------------ // Prompt //------------------------------------------------------------------------------ class Prompt { std::string Name; std::vector<std::shared_ptr<PromptCmd>> Commands; std::map<std::string, std::shared_ptr<PromptCmd>> ShortcutToCommand; std::map<std::string, std::map<std::string, std::shared_ptr<PromptCmd>>> GroupToCommands; private: void AddCommand(std::shared_ptr<PromptCmd> Cmd) { if (Cmd->Shortcut.size()) { ShortcutToCommand.emplace(Cmd->Shortcut, Cmd); } GroupToCommands[PromptCmdGroupToString(Cmd->Group)][Cmd->Name] = Cmd; Commands.push_back(Cmd); } public: Prompt(std::string Name); std::shared_ptr<PromptCmd> Show(); void ShowCommands(); void ShowHelp(); template <typename T, typename... Ts> void Say(T &&p, Ts &&... ps) { std::cout << std::forward<T>(p) << " "; sout.print(std::forward<Ts>(ps)...); } template <typename T> void Say(T &&p) { std::cout << std::forward<T>(p) << std::endl; } }; } // namespace mad #endif /* end of include guard: PROMPT_HPP_5CZETNAV */
true
2536655a364488d9a6646237eec9db7cf5d38530
C++
SirRamEsq/LEngine
/Source/Engine/Components/CompPosition.cpp
UTF-8
9,834
2.984375
3
[ "Apache-2.0" ]
permissive
#include "CompPosition.h" #include "../Errorlog.h" #include "math.h" /////////// // MapNode// /////////// MapNode::MapNode() { mParent = NULL; } MapNode::~MapNode() {} void MapNode::SetParent(MapNode *parent) { if (mParent == NULL) { mParent = parent; if (parent == NULL) { return; } positionLocal = mParent->TranslateWorldToLocal(positionLocal); return; } Vec2 oldParentCoord, newParentcoord; // Set local coordinates to world positionLocal = mParent->TranslateLocalToWorld(positionLocal); mParent = parent; if (parent == NULL) { return; } // Convert world coordinates back to local // This time local being relative to the new parent positionLocal = mParent->TranslateWorldToLocal(positionLocal); } void MapNode::UpdateWorld() { // Component manager will ensure that the parents are run before the children // This guarantees that the parent's world position is up-to-date if (mParent == NULL) { // Set World Coordinates to Local Coordinates positionWorld = positionLocal; } // If this node has a parent, translate the world Coordinates by their world // coordinates else { positionWorld = positionLocal + mParent->positionWorld; } } MapNode *MapNode::GetRootNode() { // If this node doesn't have a parent, it is the root if (mParent == NULL) { return this; } // Recurse until Root is found return mParent->GetRootNode(); } Vec2 MapNode::TranslateLocalToWorld(const Vec2 &localCoordinates) { Vec2 worldCoordinates(localCoordinates); if (mParent == NULL) { return worldCoordinates; } // Translate coordinates by the local position of this node worldCoordinates = localCoordinates + positionLocal; // Translate coordinates by the local position of the parent node return mParent->TranslateLocalToWorld(worldCoordinates); } Vec2 MapNode::TranslateWorldToLocal(const Vec2 &worldCoordinates) { Vec2 localCoordinates(worldCoordinates); if (mParent == NULL) { return localCoordinates; } // Translate coordinates by the local position of this node localCoordinates = worldCoordinates - positionLocal; // Translate coordinates by the local position of the parent node return mParent->TranslateWorldToLocal(localCoordinates); } ///////////////////// // ComponentPosition// ///////////////////// ComponentPosition::ComponentPosition(EID id, MapNode *parent, ComponentPositionManager *manager) : BaseComponent(id, manager) { mEntityID = id; maximumSpeed = 15.0; mNode.SetParent(parent); } ComponentPosition::~ComponentPosition() {} void ComponentPosition::SetParent(BaseComponent *p) { parent = p; // If parent is null, then set the node parent to the root node owned by the // manager if (p == NULL) { mNode.SetParent(mNode.GetRootNode()); } // Set node's parent to the parent's node else { auto parentPosition = static_cast<ComponentPosition *>(p); mNode.SetParent(parentPosition->GetMapNode()); } } Vec2 ComponentPosition::GetPositionWorld() { return mNode.positionWorld; } Vec2 ComponentPosition::GetPositionLocal() { return mNode.positionLocal; } Vec2 ComponentPosition::GetMovement() { return mMovement; } Vec2 ComponentPosition::GetAcceleration() { return mAcceleration; } void ComponentPosition::Update() { // Clamp movement speed to maximum if (mMovement.x > maximumSpeed) { mMovement.x = maximumSpeed; } else if (mMovement.x < -maximumSpeed) { mMovement.x = -maximumSpeed; } if (mMovement.y > maximumSpeed) { mMovement.y = maximumSpeed; } else if (mMovement.y < -maximumSpeed) { mMovement.y = -maximumSpeed; } // Increment local position by movement speed mNode.positionLocal = mNode.positionLocal + mMovement; // Increment movement by acceleration mMovement = mMovement + mAcceleration; mNode.UpdateWorld(); } void ComponentPosition::IncrementPosition(Vec2 pos) { mNode.positionLocal = mNode.positionLocal + pos; mNode.positionWorld = mNode.positionWorld + pos; } void ComponentPosition::IncrementMovement(Vec2 mov) { mMovement = mMovement + mov; } void ComponentPosition::IncrementAcceleration(Vec2 accel) { mAcceleration = mAcceleration + accel; } void ComponentPosition::SetPositionLocal(Vec2 pos) { mNode.positionLocal = pos; mNode.UpdateWorld(); } void ComponentPosition::SetPositionLocalX(float x) { SetPositionLocal(Vec2(x, mNode.positionLocal.y)); } void ComponentPosition::SetPositionLocalY(float y) { SetPositionLocal(Vec2(mNode.positionLocal.x, y)); } void ComponentPosition::SetPositionWorld(Vec2 pos) { if (mNode.mParent == NULL) { mNode.positionWorld = pos; mNode.positionLocal = pos; return; } mNode.positionLocal = pos - mNode.mParent->positionWorld; mNode.UpdateWorld(); } void ComponentPosition::SetPositionWorldX(float x) { SetPositionWorld(Vec2(x, mNode.positionWorld.y)); } void ComponentPosition::SetPositionWorldY(float y) { SetPositionWorld(Vec2(mNode.positionWorld.x, y)); } void ComponentPosition::SetMovement(Vec2 mov) { mMovement = mov; } void ComponentPosition::SetMovementX(float x) { SetMovement(Vec2(x, mMovement.y)); } void ComponentPosition::SetMovementY(float y) { SetMovement(Vec2(mMovement.x, y)); } void ComponentPosition::SetAcceleration(Vec2 acl) { mAcceleration = acl; } void ComponentPosition::SetAccelerationX(float x) { SetAcceleration(Vec2(x, mAcceleration.y)); } void ComponentPosition::SetAccelerationY(float y) { SetAcceleration(Vec2(mAcceleration.x, y)); } Vec2 ComponentPosition::TranslateWorldToLocal(const Vec2 &world) { // Node is guarnteed to have a parent, if the component doesn't have a parent // then the node's parent is set to the rootNode owned by the Manager return mNode.mParent->TranslateWorldToLocal(world); } Vec2 ComponentPosition::TranslateLocalToWorld(const Vec2 &local) { // Node is guarnteed to have a parent, if the component doesn't have a parent // then the node's parent is set to the rootNode owned by the Manager return mNode.mParent->TranslateLocalToWorld(local); } MapNode *ComponentPosition::GetMapNode() { return &mNode; } //////////////////////////// // ComponentPositionManager// //////////////////////////// ComponentPositionManager::ComponentPositionManager(EventDispatcher *e) : BaseComponentManager_Impl(e) {} ComponentPositionManager::~ComponentPositionManager() {} std::unique_ptr<ComponentPosition> ComponentPositionManager::ConstructComponent( EID id, ComponentPosition *parent) { // Assign manager's root node as the node's parent by default // this is needed in case the parent is null, // in which case, the map node parent will be the root node auto pos = std::make_unique<ComponentPosition>(id, &mRootNode, this); // Change component's parent pos->SetParent(parent); return std::move(pos); } Vec2 ComponentPositionManager::GetWorld(EID id) { ComponentPosition *pos = GetComponent(id); if (pos == NULL) { return Vec2(0, 0); } return pos->GetPositionWorld(); } Vec2 ComponentPositionManager::GetMovement(EID id) { ComponentPosition *pos = GetComponent(id); if (pos == NULL) { return Vec2(0, 0); } return pos->GetMovement(); } MapNode *const ComponentPositionManager::GetRootNode() { return &mRootNode; } void ComponentPositionManager::ExposeLuaInterface(lua_State *state) { luabridge::getGlobalNamespace(state) .beginNamespace("CPP") .beginClass<BaseComponentManager_Impl<ComponentPosition>>( "BASE_COMP_IMPL_POS") .addFunction("SetParent", &BaseComponentManager_Impl<ComponentPosition>::SetParent) .endClass() .deriveClass<ComponentPositionManager, BaseComponentManager_Impl<ComponentPosition>>( "ComponentPositionManager") .addFunction("GetWorld", &ComponentPositionManager::GetWorld) .addFunction("GetMovement", &ComponentPositionManager::GetMovement) .endClass() .deriveClass<ComponentPosition, BaseComponent>("ComponentPosition") .addFunction("GetPositionLocal", &ComponentPosition::GetPositionLocal) .addFunction("GetPositionWorld", &ComponentPosition::GetPositionWorld) .addFunction("GetMovement", &ComponentPosition::GetMovement) .addFunction("GetAcceleration", &ComponentPosition::GetAcceleration) .addFunction("SetPositionLocal", &ComponentPosition::SetPositionLocal) .addFunction("SetPositionLocalX", &ComponentPosition::SetPositionLocalX) .addFunction("SetPositionLocalY", &ComponentPosition::SetPositionLocalY) .addFunction("SetPositionWorld", &ComponentPosition::SetPositionWorld) .addFunction("SetPositionWorldX", &ComponentPosition::SetPositionWorldX) .addFunction("SetPositionWorldY", &ComponentPosition::SetPositionWorldY) .addFunction("SetMovement", &ComponentPosition::SetMovement) .addFunction("SetMovementX", &ComponentPosition::SetMovementX) .addFunction("SetMovementY", &ComponentPosition::SetMovementY) .addFunction("SetAcceleration", &ComponentPosition::SetAcceleration) .addFunction("SetAccelerationX", &ComponentPosition::SetAccelerationX) .addFunction("SetAccelerationY", &ComponentPosition::SetAccelerationY) .addFunction("SetMaxSpeed", &ComponentPosition::SetMaxSpeed) .addFunction("IncrementPosition", &ComponentPosition::IncrementMovement) .addFunction("IncrementMovement", &ComponentPosition::IncrementMovement) .addFunction("IncrementAcceleration", &ComponentPosition::IncrementAcceleration) .addFunction("TranslateWorldToLocal", &ComponentPosition::TranslateWorldToLocal) .addFunction("TranslateLocalToWorld", &ComponentPosition::TranslateLocalToWorld) .endClass() .endNamespace(); }
true
103b0cf3c4b3bf958fe9df6792bd44b4e8d23075
C++
lyswty/nowcoder-solutions
/剑指offer/扑克牌顺子.cpp
UTF-8
436
2.9375
3
[]
no_license
class Solution { public: bool IsContinuous( vector<int> numbers ) { if (numbers.size() < 5) return false; int _max = 0, _min = 14; unordered_map<int, bool> vis; for (int x: numbers){ if (!x) continue; if (vis[x]) return false; vis[x] = true; if (x < _min) _min = x; if (x > _max) _max = x; } return _max - _min < 5; } };
true
eee42efffc18594533f66a9bc2731d1b47c0bfa3
C++
reznikovkg/nm-array
/include/nm-array-class.h
UTF-8
1,153
2.890625
3
[]
no_license
#ifndef IPN_ARRAY__CLASS_H /* Author: reznikovkg GitHub: https://github.com/reznikovkg Email: kosrez1@yandex.ru File: include/nm-array-class.h GitHub Repository: https://github.com/reznikovkg/nm-array */ #define IPN_ARRAY__CLASS_H #include <iostream> using namespace std; //class array for points on decard system [or other, not problem] class nm_Array { private: double** nmA; int iA; int jA; public: nm_Array() {} nm_Array(int ia, int ja) { iA = ia; jA = ja; nmA = new double*[iA]; for (int i = 0; i < iA; i++) { nmA[i] = new double[jA]; } } double getNMA(int ai, int aj) { return this->nmA[ai][aj]; } void setNMA(int ai, int aj, double ak) { nmA[ai][aj] = ak; } int getiA() { return this->iA; } void setiA(int ia) { this->iA = ia; } int getjA() { return this->jA; } void setjA(int ja) { this->jA = ja; } void printNMA() { for (int i = 0; i < iA; i++) { for (int j = 0; j < jA; j++) { cout << "[" << i << "][" << j << "] = " << nmA[i][j] << " "; } cout << '\n'; } } double** getNMA() { return nmA; } void setNMA(double **new_nmA) { nmA = new_nmA; } ~nm_Array() {} }; #endif IPN_ARRAY__CLASS_H
true
c6314c1f9d0b478adf91fc5da21b2065cd6f112a
C++
VasTsak/data-structures-algs
/CPP/foundations/basics/1.Basics/4_iomanip_module.cpp
UTF-8
395
3.6875
4
[]
no_license
#include<iostream> #include<iomanip> int main() { std::cout<<"\n The text without any formatting \n"; std::cout<<"Ints"<<"Floats"<<"Doubles"<<"\n"; std::cout<<"\n The text with setw(15):\n"; std::cout<<"Ints"<<std::setw(15)<<"Floats"<<std::setw(15)<<"Doubles"<<"\n"; std::cout<<"\n The text with tabs: \n"; std::cout<<"Ints\t"<<"Floats\t"<<"Doubles\n"; return 0; }
true
38e7185e34039beeaf40aa2b0b3582c9d744796c
C++
leejunwoo0202/1-2-CPLUSPLUS
/8-3/HMean.cpp
UHC
588
3.484375
3
[]
no_license
#include <iostream> using namespace std; double hmean(double a, double b) { if (a == -b) // throw "ȭ !"; return 2.0 * a * b / (a + b); } int main(int argc, char* argv[]) { double x, y, z; cout << " ԷϽÿ:"; while (cin >> x >> y) { try { z = hmean(x, y); } catch(const char* s){ // ó cout << s << endl; cout << "ٸ ԷϽÿ:"; continue; } cout << "ȭ = " << z << endl; cout << " ԷϽÿ(Q ):"; } return 0; }
true
09e07ddf6520d70b63c564a26952d9253d84b5d2
C++
baid14/MetodyObliczeniowe
/Metody_roznicowe_r_zwyczajne/Metody_roznicowe_r_zwyczajne/main.cpp
UTF-8
5,049
2.78125
3
[]
no_license
#include <iostream> #include <Windows.h> #include <fstream> #include <math.h> using namespace std; double wzor_analityczny( double t ) { return 1 - exp( -10.0 * ( t + atan( t ) ) ); } double metoda_bezposrednia_eulera( double krok, int N ) { double blad = 0.0, t = krok; double y = 0.0; //warunek poczatkowy y(0) = 0 double wart_dokladna; for ( int i = 0; i < N; i++ ) { wart_dokladna = wzor_analityczny( t ); y = y + krok *( -( ( 10.0 *t * t + 20.0 ) / ( t * t + 1.0 ) )*( y - 1.0 ) ); wart_dokladna = fabs( wart_dokladna - y ); if ( wart_dokladna > blad ) blad = wart_dokladna; t += krok; } return blad; } double metoda_posrednia_eulera( double krok, int N ) { double blad = 0.0, t = krok; double y = 0.0; //warunek poczatkowy y(0) = 0 double wart_dokladna, ulamek; for ( int i = 0; i < N; i++ ) { wart_dokladna = wzor_analityczny( t ); ulamek = ( 10.0 * ( t + krok ) * ( t + krok ) + 20.0 ) / ( ( t + krok ) * ( t + krok ) + 1.0 ); y = ( y + krok * ulamek ) / ( 1 + krok * ulamek ); wart_dokladna = fabs( wart_dokladna - y ); if ( wart_dokladna > blad ) blad = wart_dokladna; t += krok; } return blad; } double metoda_trapezow( double krok, int N ) { double blad = 0.0, t = krok; double y = 0.0; //warunek poczatkowy y(0) = 0 double wart_dokladna, ulamek_n, ulamek_n_plus; for ( int i = 0; i < N; i++ ) { wart_dokladna = wzor_analityczny( t ); ulamek_n = ( ( 10.0 * t * t + 20.0 ) / ( t * t + 1.0 ) ); ulamek_n_plus = ( 10.0 * ( t + krok ) * ( t + krok ) + 20.0 ) / ( ( t + krok ) * ( t + krok ) + 1.0 ); ; y = ( ( -krok / 2.0 ) * ( ulamek_n * ( y - 1.0 ) - ulamek_n_plus ) + y ) / ( 1.0 + ( krok / 2.0 ) * ulamek_n_plus ); wart_dokladna = fabs( wart_dokladna - y ); if ( wart_dokladna > blad ) blad = wart_dokladna; t += krok; } return blad; } double metoda_bezposrednia_eulera_rys( double krok, double tmax ) { double y = 0.0; //warunek poczatkowy y(0) = 0 for ( double i = 0.0; i < tmax; i += krok ) { y = y + krok *( -( ( 10.0 *i * i + 20.0 ) / ( i * i + 1.0 ) )*( y - 1.0 ) ); } return y; } double metoda_posrednia_eulera_rys( double krok, double tmax ) { double y = 0.0, ulamek; //warunek poczatkowy y(0) = 0 for ( double i = 0.0; i < tmax; i += krok ) { ulamek = ( 10.0 * ( i + krok ) * ( i + krok ) + 20.0 ) / ( ( i + krok ) * ( i + krok ) + 1.0 ); y = ( y + krok * ulamek ) / ( 1 + krok * ulamek ); } return y; } double metoda_trapezow_rys( double krok, double tmax ) { double y = 0.0, ulamek_n, ulamek_n_plus; //warunek poczatkowy y(0) = 0 for ( double i = 0.0; i < tmax; i += krok ) { ulamek_n = ( ( 10.0 * i * i + 20.0 ) / ( i * i + 1.0 ) ); ulamek_n_plus = ( 10.0 * ( i + krok ) * ( i + krok ) + 20.0 ) / ( ( i + krok ) * ( i + krok ) + 1.0 ); ; y = ( ( -krok / 2.0 ) * ( ulamek_n * ( y - 1.0 ) - ulamek_n_plus ) + y ) / ( 1.0 + ( krok / 2.0 ) * ulamek_n_plus ); } return y; } void metody_roznicowe( ) { double krok = 0.1, mbe_s, mbe_ns, mpe, mt, anl; const double t_max = 2.0; int N = 1000, i = 0; fstream bledy, dane_1, dane_2; bledy.open( "bledy.txt", fstream::out ); cout << endl << "Bledy" << endl; cout << " i | krok | mbe | mpe| mt |" << endl; cout << "-------------------------------------------------------------------" << endl; for ( krok ; krok > 1e-20; krok /= 2 ) { mbe_s = log10( metoda_bezposrednia_eulera( krok, N ) ); mpe = log10( metoda_posrednia_eulera( krok, N ) ); mt = log10( metoda_trapezow( krok, N ) ); bledy << log10( krok ) << " " << mbe_s << " " << mpe << " " << mt << endl; cout.width( 4 ); cout << i << "|"; cout.width( 15 ); cout << krok << "|"; cout.width( 15 ); cout << mbe_s << "|"; cout.width( 15 ); cout << mpe << "|"; cout.width( 15 ); cout << mt << "|" << endl; i++; } bledy.close( ); cout << endl << "Dane do a b c" << endl; //cout << " i | krok | anl | mpe | mt | mbe_s | mbe_ns |" << endl; //cout << "-------------------------------------------------------------------------------------------------------" << endl; dane_1.open( "dane.txt", fstream::out ); krok = 0.01; for ( double t = 0; t < 5; t += 0.01 ) { anl = wzor_analityczny( t ); mpe = metoda_posrednia_eulera_rys( krok, t ); mt = metoda_trapezow_rys( krok, t ); mbe_s = metoda_bezposrednia_eulera_rys( krok, t ); dane_1 << t << " " << anl << " " << mpe << " " << mt << " " << mbe_s << endl; /*cout.width( 4 ); cout << t << "|"; cout.width( 15 ); cout << anl << "|"; cout.width( 15 ); cout << mpe << "|"; cout.width( 15 ); cout << mt << "|" ; cout.width( 15 ); cout << mbe_s << "|" ; cout.width( 15 ); cout << mbe_ns << "|" << endl;*/ } dane_1.close( ); dane_2.open( "danee.txt", fstream::out ); for ( double t = 0; t < 5; t += 0.15 ) { mbe_ns = metoda_bezposrednia_eulera_rys( 0.15, t ); dane_2 << t << " " << mbe_ns << endl; } dane_2.close( ); } int main( ) { metody_roznicowe( ); system( "Pause" ); return 0; }
true
57f99f6ae6bde1e64e72917aa2cd06cc66be89f3
C++
RadioGeek/Fireball_v5
/morse.cpp
UTF-8
3,788
2.890625
3
[]
no_license
// ==========================================================================================// // Fireball v5.0 source code // Copyright 2015 by John Maca, AB5SS, all rights reserved. // ==========================================================================================// // // This module contains the functions to send the messages using Morse code. // #include <Arduino.h> #include "config.h" #include "morse.h" void dot() { digitalWrite (XMIT_PIN, HIGH); delay (dotLength); digitalWrite (XMIT_PIN, LOW); delay (dotLength); } void dash() { digitalWrite (XMIT_PIN, HIGH); delay (dashLength); digitalWrite (XMIT_PIN, LOW); delay (dotLength); } void EndOfChar() { delay (pauseChar); } void EndOfWord() { delay (pauseWord); } void SendMorse(char tmpChar) { if (isalpha(tmpChar)) { tmpChar = toupper(tmpChar); } switch (tmpChar) { case '0': { dash(); dash(); dash(); dash(); dash(); } break; case '1': { dot(); dash(); dash(); dash(); dash(); } break; case '2': { dot(); dot(); dash(); dash(); dash(); } break; case '3': { dot(); dot(); dot(); dash(); dash(); } break; case '4': { dot(); dot(); dot(); dot(); dash(); } break; case '5': { dot(); dot(); dot(); dot(); dot(); } break; case '6': { dash(); dot(); dot(); dot(); dot(); } break; case '7': { dash(); dash(); dot(); dot(); dot(); } break; case '8': { dash(); dash(); dash(); dot(); dot(); } break; case '9': { dash(); dash(); dash(); dash(); dot(); } break; case 'A': { dot(); dash(); } break; case 'B': { dash(); dot(); dot(); dot(); } break; case 'C': { dash(); dot(); dash(); dot(); } break; case 'D': { dash(); dot(); dot(); } break; case 'E': { dot(); } break; case 'F': { dot(); dot(); dash(); dot(); } break; case 'G': { dash(); dash(); dot(); } break; case 'H': { dot(); dot(); dot(); dot(); dot(); } break; case 'I': { dot(); dot(); } break; case 'J': { dot(); dash(); dash(); dash(); } break; case 'K': { dash(); dot(); dash(); } break; case 'L': { dot(); dash(); dot(); dot(); } break; case 'M': { dash(); dash(); } break; case 'N': { dash(); dot(); } break; case 'O': { dash(); dash(); dash(); } break; case 'P': { dot(); dash(); dash(); dot(); } break; case 'Q': { dash(); dash(); dot(); dash(); } break; case 'R': { dot(); dash(); dot(); } break; case 'S': { dot(); dot(); dot(); } break; case 'T': { dash(); } break; case 'U': { dot(); dash(); dash(); } break; case 'V': { dot(); dot(); dot(); dash(); } break; case 'W': { dot(); dash(); dash(); } break; case 'X': { dash(); dot(); dot(); dash(); } break; case 'Y': { dash(); dot(); dash(); dash(); } break; case 'Z': { dash(); dash(); dot(); dot(); } break; case ' ': { EndOfChar(); } break; case '-': { dash(); dot(); dot(); dot(); dot(); dash(); } break; case '.': { dot(); dash(); dot(); dash(); dot(); dash(); } break; case '/': { dash(); dot(); dot(); dash(); dot(); } break; case '?': { dot(); dot(); dash(); dash(); dot(); dot(); } break; default: { dot(); dot(); dash(); dash(); dot(); dot(); } } EndOfChar(); }
true
44a831dd6809c62926a7df12f8d02d487578ee72
C++
TopHK/LeetCode-Mine
/PalindromePartitioningII.cpp
UTF-8
2,169
3.15625
3
[]
no_license
/************************************************************************* > File Name: palindromePartitioning.cpp > Author: > Mail: > Created Time: 2015年06月27日 星期六 19时41分35秒 ************************************************************************/ #include<iostream> #include<vector> #include<string> #include<limits.h> using namespace std; /* class Solution { private: int count; public: bool isPalindrome(const string& str) { int size = str.size(); for(int i=0; i<(size>>1); ++i) if(str[i] != str[size-i-1]) return false; return true; } void partitionCore(string s, int start, vector<string>& oneResult) { if(start == s.size()) { if(oneResult.size() < count) count = oneResult.size(); return; } for(int i=s.size()-1; i>=start; --i) { string temp = s.substr(start, i-start+1); if(isPalindrome(temp)) { vector<string> tempStr(oneResult.begin(), oneResult.end()); tempStr.push_back(temp); partitionCore(s, i+1, tempStr); } } } int mincut(string s) { if(s.empty()) return 0; count = INT_MAX; vector<string> oneResult; partitionCore(s, 0, oneResult); return count; } }; void print(const vector<vector<string> >& str) { for(int i=0; i<str.size(); ++i) { for(int j=0; j<str[i].size(); ++j) cout<<str[i][j]<<" "; cout<<endl; } } */ int minCut(string s) { int size = s.size(); if(size <= 1) return 0; vector<int> count(size, 0); vector<vector<int> > dp(size, count); count.resize(size+1, 0); for(int i=size-1; i>=0; --i) { count[i] = INT_MAX; for(int j=i; j<size; ++j) { if(s[i]==s[j] && (j-i<2 || dp[i+1][j-1]==1)) { dp[i][j] = 1; count[i] = min(1+count[j+1], count[i]); } } } return count[0] - 1; } int main() { string str("aab"); cout<<minCut(str)<<endl; return 0; }
true
55d99fb4a3bfe337a878da3afc6614443db24dbd
C++
federicoemartinez/algo3-2008
/tp1/CD/ejercicio1/src/main.cpp
UTF-8
2,557
3.203125
3
[]
no_license
#include <iostream> #include <string> #include <fstream> #include <assert.h> #include <math.h> #include "FabricaCandidatos.h" using namespace std; void primoDeMayorPotencia(int n, int& primo, int& potencia) { assert(n > 1); int mejorPrimo = 1; int mejorPotencia = 0; FabricaCandidatos fab = FabricaCandidatos(); // primo actual es un abuso de notacion por decirlo de algun modo, ya que no necesariamente es primo int primoActual = fab.siguiente(); int potenciaActual = 0; int limite = n; while (n != 1 && primoActual*primoActual <= limite) { if (n % primoActual == 0) { potenciaActual++; n = n / primoActual; } else { // el primo no divide a n, hay que ver si hay que actualizar la potencia if (potenciaActual >= mejorPotencia) { mejorPrimo = primoActual; mejorPotencia = potenciaActual; } potenciaActual = 0; //nuevo candidato primoActual = fab.siguiente(); // actualizamos el limite limite = n; } } if (primoActual*primoActual > limite) { primoActual = n; potenciaActual = 1; } // vemos que ocurre con el ultimo primo if (potenciaActual >= mejorPotencia) { mejorPrimo = primoActual; mejorPotencia = potenciaActual; } primo = mejorPrimo; potencia = mejorPotencia; } void help() { cout << "Uso ./primos <infile> <outfile>" << endl; cout << " o ./primos (sin parametros)" << endl; cout << "En el caso de la llamada sin parametros se toman los archivos" << endl; cout << "Tp1Ej1.in y Tp1Ej1.out como valores por defecto." << endl; } int main(int argc, char* argv[]) { // leo los datos de entrada string ruta; if(argc >= 2) { ruta = argv[1]; } else { ruta="Tp1Ej1.in"; } fstream f (ruta.c_str()); if(!f.is_open()) { cout << endl << "ERROR: No se pudo abrir el archivo de entrada!" << endl << endl; help(); return 1; } // preparo el archivo de salida string salida; if(argc > 2) { salida = argv[2]; } else { salida = "Tp1Ej1.out"; } ofstream o (salida.c_str()); int primo, potencia; int n; f >> n; while (n != 0) { primoDeMayorPotencia(n, primo, potencia); o << n << " " << primo << " " << potencia << endl; f >> n; } return 0; }
true
7077ad704461a41b092352aeabe0b34a106cee3a
C++
lock19960613/SCL
/Daily/CPP/Leetcode575-分糖果.h
UTF-8
236
2.8125
3
[]
no_license
class Solution { public: int distributeCandies(vector<int>& candies) { unordered_set<int> candy; for(auto i:candies){ candy.insert(i); } return min(candy.size(),candies.size()/2); } };
true
45ba6fb65101b8ad898eea6f7164c7d5c4ed28b1
C++
harryking001/JZoo
/ArchiveFile.h
GB18030
3,176
3.25
3
[]
no_license
#pragma once #include <fstream> #include <sstream> #include <string> #include <vector> #include <iterator> #include "Zoo.h" using std::endl; using std::ifstream; using std::ofstream; using std::stringstream; using std::string; using std::size_t; /** * 浵ļ࣬ͱ涯԰Ϣ * Archieve file class which used to load and save zoo information */ class ArchiveFile { public: /** * @brief ĬϹ캯 * Default constructor function. * */ ArchiveFile(); /** * @brief 캯 * Constructor function. * @param strFile ļ * strFile file name */ ArchiveFile(const string& strFile); /** * @brief * Destructor function. * */ ~ArchiveFile(); /** * @brief ļ * Set the archive file name * @param strFile ļ * strFile file name * @return * void */ void SetFileName(const string& strFile); /** * @brief Ӵ浵ļ붯԰Ϣ * Load zoo information from archive file * @param z zoo z reference of the zoo object * @return bool ɹtrueʧfalse bool true if success, false if fail */ bool Load(Zoo& z); /** * @brief 涯԰Ϣ浵ļ * Save zoo information to archive file * @param z ԰ * z reference of the zoo object * @return bool ɹtrueʧfalse * bool true for success, false for fail */ bool Save(const Zoo& z); private: /** 浵ļ */ /** Archive file name */ string fileName; /** ļ */ /** input file stream */ ifstream infile; /** ļ */ /** output file stream */ ofstream outfile; /** * @brief ַضı־ֳַ * Split string into several sub string via a token * @param str1 Ҫַָ * str1 the string you want to split * @param str2 ־ * str2 token * @return ַ * vector<string> */ vector<string> SplitString(const string& str1, const string& str2); /** * @brief ַתUint * Convert vector string to vector Uint * @param sVec ַ * sVec vector string object * @return Uint * vector<Uint> */ vector<Uint> CvtStoUnVec(vector<string> sVec); /** * @brief ַתɲ * Convert vector string to vector bool * @param sVec ַ * sVec vector string object * @return * vector<bool> */ vector<bool> CvtStoBoolVec(vector<string> sVec); };
true
8fc9ebb4820340ba3f6c7c54f3c334f993a591e0
C++
viacheslavpleshkov/unit-factory-ucode-half-marathon-cpp
/sprint06/t00/app/src/AbstractWizard.h
UTF-8
1,083
3.28125
3
[ "MIT" ]
permissive
#pragma once #include "Food.h" #include <iostream> #include <map> class AbstractWizard { protected: virtual void deductFoodType(FoodType food) = 0; }; class MightyWizard : public AbstractWizard { public: MightyWizard(std::string &&name) : m_name(name) {}; void checkFood(FoodItem *foodPtr) { if (!foodPtr) deductFoodType(FoodType::Invalid); else deductFoodType(foodPtr->m_foodType); } void checkFood(const FoodItem &foodPtr) { deductFoodType(foodPtr.m_foodType); } void deductFoodType(FoodType food) override { static std::map<FoodType, std::string> mapFood = { {FoodType::HoneyNut, "Honey nut. Mmm, tasty!"}, {FoodType::Sweetroll, "Sweetroll. Mmm, tasty!"}, {FoodType::Invalid, "<wtf>. Ugh, not again!"}, {FoodType::ApplePie, "Apple pie. Ugh, not again!"}, {FoodType::PoisonedFood, "Poison. Ugh, not again!"}, }; std::cout << mapFood[food] << std::endl; } private: std::string m_name; };
true
8ae32f35cc2c1e766e275a75b7d97a4a517cf822
C++
s011075g/Playground
/WestWorld/Miner.h
UTF-8
961
2.671875
3
[]
no_license
#pragma once #include "Actor.h" #include "Locations.h" //Definition declared else where class State; #define COMFORT_LEVEL 5u; #define MAX_NUGGETS 3u; #define THIRST_LEVEL 5u; #define TIREDNESS_THRESHOLD 5u; class Miner : public Actor { private: State* _mCurrentState; Locations _mCurrentLocation; uint _mGold; uint _mGoldBanked; uint _mThirst; uint _mFatigue; public: Miner(); ~Miner(); void Update() override; void ChangeState(State* newState); //Location Locations Location() const; void ChangeLocation(const Locations location); //Gold uint GoldCarrying() const; void SetGold(const uint value); void AddToGold(const uint value); bool PocketsFull() const; //Saved uint Wealth() const; void SetWealth(const uint value); void AddtoWealth(const uint value); static uint GetComfortLevel(); //Fatigued bool Fatigued() const; void DecreaseFatigue(); void IncreaseFatigue(); //Thirst bool Thirsty() const; void ResetThirst(); };
true
974e63a65b4adfb480231c8304b1f0f7f837e3c6
C++
dimitarkole/CPlusPlusTasks
/C++/cake.cpp
UTF-8
898
2.8125
3
[]
no_license
#include<iostream> #include<iomanip> using namespace std; int main() { int height,width; cin>>height>>width; long scqire=height*width; //cout<<"scqire= "<<scqire<<endl; char ch; long letter; do{ cin>>ch; letter=ch-'0'; if ((letter>=0)&&(letter<=9)) { long number=ch-'0'; cin.get(ch); letter=ch-'0'; while(ch!='\n') { letter=ch-'0'; number=number*10+ letter; //cout<<" number= "<<number<<endl; cin.get(ch); } scqire=scqire-number; //cout<<" number= "<<number<<endl<<" scqire= "<<scqire<<endl; } else break; }while(scqire>-1); if(scqire>-1)cout<<scqire<<" pieces are left."; else cout<<"No more cake left! You need "<<scqire*(-1)<<" pieces more."; }
true
17b7feade9f9dfbfd7ccfcc1841dccf60bef9d9d
C++
Hana897TRX/Astrologia3D
/Moon.cpp
UTF-8
1,460
2.515625
3
[]
no_license
#include <windows.h> #include <GL/gl.h> #include <glut.h> #include <time.h> #include <math.h> //################### #include "Planet.h" #include "Moon.h" #include "Disk.h" //################### static RGBpixmap myText[1]; static GLuint name[1]; void Moon::SetTexture(char * file) { glGenTextures(1, name); myText[0].readBMPFile(file); myText[0].SetTexture(name[0]); } Moon::Moon() { yearInc = 0.1f; dayInc = 0.5f; year = 0.0; day = 0.0; space = 0; initialX = 0; initialY = 0; initialZ = 0; moon = new Sphere(1.0); moon->SetTexture(&name[0]); } void Moon::DrawMoon() { glPushMatrix(); if (seeOrbits) glutWireTorus(space, 0.0, 40, 1); glRotatef((GLfloat)year, 0.0, 1.0, 0.0); glTranslated(initialX, initialY, initialZ); glRotatef((GLfloat)day, 0.0, 1.0, 0.0); moon->HaSolidSphere(); glPopMatrix(); if (doAuto) { year = (GLfloat)(((GLint)(year * 100.f + yearInc * 100.f)) % 36000) / 100.0f; day = (GLfloat)(((GLint)(day * 100.f + dayInc * 100.f)) % 36000) / 100.0f; } } bool Moon::doAuto = false; bool Moon::seeOrbits = false; void Moon::ChangeInc(float _inc) { yearInc += _inc; dayInc += _inc; } void Moon::DoAuto(bool _doAuto) { doAuto = _doAuto; } void Moon::SeeOrbits(bool _seeOrbits) { seeOrbits = _seeOrbits; } void Moon::InitialPos(float _initialX, float _initialY, float _initialZ) { initialX = _initialX; initialY = _initialY; initialZ = _initialZ; } void Moon::Space(float _space) { space = _space; }
true
3d173592b6e9968362e3afb1733fd8ee38dfb975
C++
AvansMartijn/Game-Engine
/GameEngine/AbstractUiElement.h
UTF-8
1,428
2.703125
3
[]
no_license
#pragma once #ifdef GAMEENGINE_EXPORTS #define GAMEENGINE_AbstractUiElement __declspec(dllexport) #else #define GAMEENGINE_AbstractUiElement __declspec(dllimport) #endif #include "Window.h" #include "Rect.h" #include <functional> /// <summary> /// Element to be rendered on the screen. /// </summary> class Window; class AbstractGame; class GAMEENGINE_AbstractUiElement AbstractUiElement { public: AbstractUiElement(); ~AbstractUiElement(); /// <summary> /// prerender /// </summary> /// <param name="window"></param> virtual void preRender(const unique_ptr<Window>& window) = 0; /// <summary> /// Render the element on the screen. /// </summary> /// <param name="renderer">The renderer</param> virtual void render(const unique_ptr<Window>& window) = 0; /// <summary> /// Checks if the mouse is within the bounds of the element. /// </summary> /// <param name="mouseX">X coordinate of the mouse</param> /// <param name="mouseY">Y coordinate of the mouse</param> /// <returns></returns> virtual bool isInBound(int mouseX, int mouseY) = 0; /// <summary> /// Register the game to the element. /// </summary> /// <param name="game">The Game</param> virtual void registerGame(AbstractGame* game); /// <summary> /// The onclick function. This function needs to be changed so it calls a function. /// </summary> std::function<void(AbstractGame*)> onClick; Rect _rect; protected: AbstractGame* _game; };
true
4f7e755fe84a8f9c1d1bb44054de1a94085ea8fd
C++
ssynn/PAT_advanced
/1038. Recover the Smallest Number .cpp
UTF-8
676
2.671875
3
[]
no_license
#include"stdafx.h" #include<iostream> #include<string> #include<map> #include<string> #include<vector> #include<algorithm> #include<queue> using namespace std; bool cmp(string a, string b) { return a+b < b+a; } int main() { int n,i=0,flag=0; cin >> n; vector<string>val(n); for (int i = 0; i < n; i++) cin >> val[i]; sort(val.begin(), val.end(),cmp); for (i = 0; i < n; i++) { int j = 0; if (flag) cout << val[i]; else { for (j = 0; j < val[i].length(); j++) if (val[i][j] != '0') break; for (; j < val[i].length(); j++) { flag = 1; cout << val[i][j]; } } } if (!flag) cout << '0'; system("pause"); return 0; }
true
eccde9d2d66621c8264abad3c66986690d5964e8
C++
dcauz/opus
/elf/dis_2.h
UTF-8
10,653
2.78125
3
[]
no_license
const char * dis_20(const char * code, unsigned prefix) { std::string op1; std::string op2; if( ( prefix & VEX ) == 0 ) { if(code[1] == 0x25) code = imm_reg_ops( code, prefix, 0, 32, true, op1, op2 ); else code = mod_reg_rm_ops( code, prefix, OpRegs::AL, 0, op1, op2 ); printf( "and %s,%s\n", op1.c_str(), op2.c_str() ); } else { if( prefix & PRE_3A ) { int vvvv = prefix >> 28; vvvv = vvvv ^ 0xf; code = mod_reg_rm_ops( code, prefix, OpRegs::XMM0_AL, 0, op1, op2, -1, 32 ); char imm[12]; code = imm8( code, imm ); printf( "vpinsrb $%s,%s,%%xmm%d,%s\n", imm, op2.c_str(), vvvv, op1.c_str() ); } else { if( prefix & PRE_256 ) { code = mod_reg_rm_ops( code, prefix, OpRegs::YMM0_XMM0, 0, op1, op2 ); printf( "vpmovsxbw %s,%s\n", op2.c_str(), op1.c_str() ); } else { code = mod_reg_rm_ops( code, prefix, OpRegs::XMM0, 0, op1, op2 ); printf( "vpmovsxbw %s,%s\n", op2.c_str(), op1.c_str() ); } } } return code; } const char * dis_21(const char * code, unsigned prefix) { std::string op1; std::string op2; if( prefix & VEX ) { if( prefix & PRE_3A ) { int vvvv = prefix >> 28; vvvv = vvvv ^ 0xf; code = mod_reg_rm_ops( code, prefix, OpRegs::XMM0, 0, op1, op2 ); char imm[12]; code = imm8( code, imm ); printf( "vinsertps $%s,%s,%%xmm%d,%s\n", imm, op2.c_str(), vvvv, op1.c_str() ); } else { if( prefix & PRE_256 ) { code = mod_reg_rm_ops( code, prefix, OpRegs::YMM0_XMM0, 0, op1, op2 ); printf( "vpmovsxbd %s,%s\n", op2.c_str(), op1.c_str() ); } else { code = mod_reg_rm_ops( code, prefix, OpRegs::XMM0, 0, op1, op2 ); printf( "vpmovsxbd %s,%s\n", op2.c_str(), op1.c_str() ); } } } else { if( code[1] == 0x25) code = imm_reg_ops( code, prefix, 1, 32, true, op1, op2 ); else code = mod_reg_rm_ops( code, prefix, OpRegs::AL, 1, op1, op2 ); printf( "and %s,%s\n", op1.c_str(), op2.c_str() ); } return code; } const char * dis_22(const char * code, unsigned prefix) { std::string op1; std::string op2; if( ( prefix & VEX ) == 0 ) { if( code[1] == 0x25) code = imm_reg_ops( code, prefix, 1, 8, false, op1, op2 ); else code = mod_reg_rm_ops( code, prefix, OpRegs::AL, 0, op2, op1 ); printf( "and %s,%s\n", op1.c_str(), op2.c_str() ); } else { if( prefix & PRE_3A ) { int vvvv = prefix >> 28; vvvv = vvvv ^ 0xf; int opSize; char inst; if( prefix & REX_W ) { opSize = 64; inst = 'q'; } else { opSize = 32; inst = 'd'; } code = mod_reg_rm_ops( code, prefix, OpRegs::XMM0_AL, 0, op1, op2, -1, opSize ); char imm[12]; code = imm8( code, imm ); printf( "vpinsr%c $%s,%s,%%xmm%d,%s\n", inst, imm, op2.c_str(), vvvv, op1.c_str() ); } else { if( prefix & PRE_256 ) code = mod_reg_rm_ops( code, prefix, OpRegs::YMM0_XMM0, 0, op1, op2 ); else code = mod_reg_rm_ops( code, prefix, OpRegs::XMM0, 0, op1, op2 ); printf( "vpmovsxbq %s,%s\n", op2.c_str(), op1.c_str() ); } } return code; } const char * dis_23(const char * code, unsigned prefix) { std::string op1; std::string op2; if( prefix & VEX ) { if( prefix & PRE_256 ) code = mod_reg_rm_ops( code, prefix, OpRegs::YMM0_XMM0, 0, op1, op2 ); else code = mod_reg_rm_ops( code, prefix, OpRegs::XMM0, 0, op1, op2 ); printf( "vpmovsxwd %s,%s\n", op2.c_str(), op1.c_str() ); } else { if( code[1] == 0x25) code = imm_reg_ops( code, prefix, 1, 32, false, op1, op2 ); else code = mod_reg_rm_ops( code, prefix, OpRegs::AL, 1, op2, op1 ); printf( "and %s,%s\n", op1.c_str(), op2.c_str() ); } return code; } const char * dis_24(const char * code, unsigned prefix) { std::string op1; std::string op2; if( prefix & PRE_256 ) code = mod_reg_rm_ops( code, prefix, OpRegs::YMM0_XMM0, 0, op1, op2 ); else code = mod_reg_rm_ops( code, prefix, OpRegs::XMM0, 0, op1, op2 ); printf( "vpmovsxwq %s,%s\n", op2.c_str(), op1.c_str() ); return code; } const char * dis_25(const char * code, unsigned prefix) { std::string op1; std::string op2; if( prefix & PRE_256 ) code = mod_reg_rm_ops( code, prefix, OpRegs::YMM0_XMM0, 0, op1, op2 ); else code = mod_reg_rm_ops( code, prefix, OpRegs::XMM0, 0, op1, op2 ); printf( "vpmovsxdq %s,%s\n", op2.c_str(), op1.c_str() ); return code; } const char * dis_28(const char * code, unsigned prefix) { std::string op1; std::string op2; if( ( prefix & VEX ) == 0 ) { if(code[1] == 0x25) code = imm_reg_ops( code, prefix, 0, 32, true, op1, op2 ); else code = mod_reg_rm_ops( code, prefix, OpRegs::AL, 0, op1, op2 ); printf( "sub %s,%s\n", op1.c_str(), op2.c_str() ); } else { int vvvv = prefix >> 28; vvvv = vvvv ^ 0xf; if( prefix & PRE_256 ) { code = mod_reg_rm_ops( code, prefix, OpRegs::YMM0, 0, op1, op2 ); if(prefix & PRE_OS ) printf( "vmovapd %s,%s\n", op2.c_str(), op1.c_str() ); else printf( "vmovaps %s,%s\n", op2.c_str(), op1.c_str() ); } else { code = mod_reg_rm_ops( code, prefix, OpRegs::XMM0, 0, op1, op2 ); if(prefix & PRE_OS ) printf( "vmovapd %s,%s\n", op2.c_str(), op1.c_str() ); else printf( "vmovaps %s,%s\n", op2.c_str(), op1.c_str() ); } } return code; } const char * dis_29(const char * code, unsigned prefix) { std::string op1; std::string op2; if( ( prefix & VEX ) == 0 ) { if( code[1] == 0x25) code = imm_reg_ops( code, prefix, 1, 32, true, op1, op2 ); else code = mod_reg_rm_ops( code, prefix, OpRegs::AL, 1, op1, op2 ); printf( "sub %s,%s\n", op1.c_str(), op2.c_str() ); } else { int vvvv = prefix >> 28; vvvv = vvvv ^ 0xf; bool isCmp = (prefix & PRE_0F ); if( prefix & PRE_256 ) { code = mod_reg_rm_ops( code, prefix, OpRegs::YMM0, 0, op1, op2 ); if(isCmp) { if(prefix & PRE_38 ) printf( "vpcmpeqq %s,%%ymm%d,%s\n", op2.c_str(), vvvv, op1.c_str() ); else printf( "vmovapd %s,%s\n", op1.c_str(), op2.c_str() ); } else printf( "vmovaps %s,%s\n", op1.c_str(), op2.c_str() ); } else { code = mod_reg_rm_ops( code, prefix, OpRegs::XMM0, 0, op1, op2 ); if(isCmp) { if(prefix & PRE_38 ) printf( "vpcmpeqq %s,%%xmm%d,%s\n", op2.c_str(), vvvv, op1.c_str() ); else printf( "vmovapd %s,%s\n", op1.c_str(), op2.c_str() ); } else printf( "vmovaps %s,%s\n", op1.c_str(), op2.c_str() ); } } return code; } const char * dis_2a(const char * code, unsigned prefix) { std::string op1; std::string op2; if( ( prefix & VEX ) == 0 ) { if( code[1] == 0x25) code = imm_reg_ops( code, prefix, 1, 8, false, op1, op2 ); else code = mod_reg_rm_ops( code, prefix, OpRegs::AL, 0, op2, op1 ); printf( "sub %s,%s\n", op1.c_str(), op2.c_str() ); } else { int vvvv = prefix >> 28; vvvv = vvvv ^ 0xf; bool isCmp = (prefix & PRE_0F ); int m = mod( *code ); if( prefix & PRE_38 ) { if( prefix & PRE_256 ) code = mod_reg_rm_ops( code, prefix, OpRegs::YMM0, 0, op1, op2 ); else code = mod_reg_rm_ops( code, prefix, OpRegs::XMM0, 0, op1, op2 ); printf( "vmovntdqa %s,%s\n", op2.c_str(), op1.c_str() ); } else if( prefix & PRE_NE ) { code = mod_reg_rm_ops( code, prefix, OpRegs::XMM0_AL, 1, op1, op2 ); if( m == 3 ) printf( "vcvtsi2sd %s,%%xmm%d,%s\n", op2.c_str(), vvvv, op1.c_str() ); else { if( prefix & REX_W ) printf( "vcvtsi2sdq %s,%%xmm%d,%s\n", op2.c_str(), vvvv, op1.c_str() ); else printf( "vcvtsi2sdl %s,%%xmm%d,%s\n", op2.c_str(), vvvv, op1.c_str() ); } } else { code = mod_reg_rm_ops( code, prefix, OpRegs::XMM0_AL, 1, op1, op2 ); printf( "vcvtsi2ss %s,%%xmm%d,%s\n", op2.c_str(), vvvv, op1.c_str() ); } } return code; } const char * dis_2b(const char * code, unsigned prefix) { std::string op1; std::string op2; if( ( prefix & VEX ) == 0 ) { if( code[1] == 0x25) code = imm_reg_ops( code, prefix, 1, 32, false, op1, op2 ); else code = mod_reg_rm_ops( code, prefix, OpRegs::AL, 1, op2, op1 ); printf( "sub %s,%s\n", op1.c_str(), op2.c_str() ); } else if( prefix & PRE_38 ) { int vvvv = prefix >> 28; vvvv = vvvv ^ 0xf; if( prefix & PRE_256 ) { code = mod_reg_rm_ops( code, prefix, OpRegs::YMM0, 0, op1, op2 ); if( prefix & PRE_OS ) printf( "vpackusdw %s,%%ymm%d,%s\n", op2.c_str(), vvvv, op1.c_str() ); else printf( "vpackusdw %s,%%ymm%d,%s\n", op2.c_str(), vvvv, op1.c_str() ); } else { code = mod_reg_rm_ops( code, prefix, OpRegs::XMM0, 0, op1, op2 ); if( prefix & PRE_OS ) printf( "vpackusdw %s,%%xmm%d,%s\n", op2.c_str(), vvvv, op1.c_str() ); else printf( "vpackusdw %s,%%xmm%d,%s\n", op2.c_str(), vvvv, op1.c_str() ); } } else { if( prefix & PRE_256 ) code = mod_reg_rm_ops( code, prefix, OpRegs::YMM0, 0, op1, op2 ); else code = mod_reg_rm_ops( code, prefix, OpRegs::XMM0, 0, op1, op2 ); if( prefix & PRE_OS ) printf( "vmovntpd %s,%s\n", op1.c_str(), op2.c_str() ); else printf( "vmovntps %s,%s\n", op1.c_str(), op2.c_str() ); } return code; } const char * dis_2c(const char * code, unsigned prefix) { std::string op1; std::string op2; code = mod_reg_rm_ops( code, prefix, OpRegs::AL_XMM0, 1, op1, op2 ); if(prefix & PRE_NE ) printf( "vcvttsd2si %s,%s\n", op2.c_str(), op1.c_str() ); else printf( "vcvttss2si %s,%s\n", op2.c_str(), op1.c_str() ); return code; } const char * dis_2d(const char * code, unsigned prefix) { std::string op1; std::string op2; code = mod_reg_rm_ops( code, prefix, OpRegs::AL_XMM0, 1, op1, op2 ); if(prefix & PRE_NE ) printf( "vcvtsd2si %s,%s\n", op2.c_str(), op1.c_str() ); else printf( "vcvtss2si %s,%s\n", op2.c_str(), op1.c_str() ); return code; } const char * dis_2e(const char * code, unsigned prefix) { std::string op1; std::string op2; code = mod_reg_rm_ops( code, prefix, OpRegs::XMM0, 0, op1, op2 ); if( prefix & PRE_OS ) printf( "vucomisd %s,%s\n", op2.c_str(), op1.c_str() ); else printf( "vucomiss %s,%s\n", op2.c_str(), op1.c_str() ); return code; } const char * dis_2f(const char * code, unsigned prefix) { std::string op1; std::string op2; code = mod_reg_rm_ops( code, prefix, OpRegs::XMM0, 0, op1, op2 ); if( prefix & PRE_OS ) printf( "vcomisd %s,%s\n", op2.c_str(), op1.c_str() ); else printf( "vcomiss %s,%s\n", op2.c_str(), op1.c_str() ); return code; }
true
b3a83415db8fef400a19330a6cba37217e4dd51b
C++
YuliangCai/gmapping_navigation
/src/save_client.cpp
UTF-8
1,680
2.796875
3
[]
no_license
#include <ros/ros.h> #include <gmapping_navigation/mark_location.h> #include <iostream> #include <std_msgs/String.h> #include <std_msgs/Bool.h> //the code is to create a subscriber/sericeclient to save the input location and data //define a serviceclient pointer to use in the callback ros::ServiceClient *clientPtr; ros::Publisher *publishPtr; //subscriber callback void callback(const std_msgs::String::ConstPtr& msg) { std_msgs::Bool result; //create a service message object gmapping_navigation::mark_location srv; //send the user input to message srv.request.location = msg->data.c_str(); //put the service client in main here ros::ServiceClient client = (ros::ServiceClient)*clientPtr; //run the client and check status if(client.call(srv)) { std::cout << "mark location complete" << std::endl; srv.response.success = true; ros::Publisher publish = (ros::Publisher)*publishPtr; result.data = srv.response.success; publish.publish(result); ros::shutdown(); } else { ROS_ERROR("Failed"); ros::shutdown(); } } int main(int argc, char **argv) { //initialize a subscriber node and nodehandle ros::init(argc, argv, "location_client"); ros::NodeHandle n; //create a serviceclient ros::ServiceClient save_location = n.serviceClient<gmapping_navigation::mark_location>("/save_location"); //copy the address of service client to global variable clientPtr = & save_location; ros::Publisher pub = n.advertise<std_msgs::Bool>("/check_status", 1000); publishPtr = & pub; //create a subscriber to get the user input ros::Subscriber sub = n.subscribe<std_msgs::String>("/chatter", 1000, callback); ros::spin(); return 0; }
true
46055c7629d321b7f91d20663c37ed74598f87d1
C++
jonigata/caper
/caper/samples/cparser/Main.h
UTF-8
3,188
3.171875
3
[ "LicenseRef-scancode-public-domain", "BSD-3-Clause" ]
permissive
#ifndef MAIN_H_ #define MAIN_H_ //////////////////////////////////////////////////////////////////////////// // CR_DeqSet<ITEM_T> -- deque and set template <typename ITEM_T> class CR_DeqSet : public std::deque<ITEM_T> { public: CR_DeqSet() { } CR_DeqSet(const CR_DeqSet<ITEM_T>& vs) : std::deque<ITEM_T>(vs) { } void operator=(const CR_DeqSet<ITEM_T>& vs) { this->assign(vs.begin(), vs.end()); } virtual ~CR_DeqSet() { } void insert(const ITEM_T& item) { this->push_back(item); } bool Contains(const ITEM_T& item) const { const std::size_t siz = this->size(); for (std::size_t i = 0; i < siz; i++) { if (this->at(i) == item) return true; } return false; } std::size_t Find(const ITEM_T& item) const { const std::size_t siz = this->size(); for (std::size_t i = 0; i < siz; i++) { if (this->at(i) == item) return i; } return static_cast<std::size_t>(-1); } std::size_t Insert(const ITEM_T& item) { const std::size_t siz = this->size(); for (std::size_t i = 0; i < siz; i++) { if (this->at(i) == item) return i; } this->push_back(item); return this->size() - 1; } void AddHead(const CR_DeqSet<ITEM_T>& items) { std::deque<ITEM_T>::insert( std::deque<ITEM_T>::begin(), items.begin(), items.end()); } void AddTail(const CR_DeqSet<ITEM_T>& items) { std::deque<ITEM_T>::insert( std::deque<ITEM_T>::end(), items.begin(), items.end()); } std::size_t count(const ITEM_T& item) const { std::size_t count = 0; for (std::size_t i : *this) { if (this->at(i) == item) count++; } return count; } void sort() { std::sort(this->begin(), this->end()); } void unique() { std::unique(this->begin(), this->end()); } void erase(const ITEM_T& item) { std::size_t i, j; const std::size_t count = this->size(); for (i = j = 0; i < count; i++) { if (this->at(i) != item) { this->at(j++) = this->at(i); } } if (i != j) this->resize(j); } }; namespace std { template <typename ITEM_T> inline void swap(CR_DeqSet<ITEM_T>& vs1, CR_DeqSet<ITEM_T>& vs2) { vs1.swap(vs2); } } //////////////////////////////////////////////////////////////////////////// // CR_String typedef std::string CR_String; //////////////////////////////////////////////////////////////////////////// // CR_StringSet typedef CR_DeqSet<CR_String> CR_StringSet; //////////////////////////////////////////////////////////////////////////// // CR_Map<from, to>, CR_UnorderedMap<from, to> #define CR_Map std::map #define CR_UnorderedMap std::unordered_map //////////////////////////////////////////////////////////////////////////// #endif // ndef MAIN_H_
true
7147f909e8ea5d5ab80ebdc23336dda8458e07e3
C++
victor-timoshin/Switch
/src/Switch.System/include/Switch/System/Media/SystemSound.hpp
UTF-8
1,497
2.65625
3
[ "MIT" ]
permissive
/// @file /// @brief Contains Switch::System::Media::SystemSound class. #pragma once #include <Switch/Is.hpp> #include <Switch/Types.hpp> #include <Switch/System/Object.hpp> #include "../../SystemExport.hpp" /// @cond struct __opaque_sound_access__; /// @endcond /// @brief The Switch namespace contains all fundamental classes to access Hardware, Os, System, and more. namespace Switch { /// @brief The Switch::System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. namespace System { /// @brief The Switch::System::Media namespace contains classes for playing sound files and accessing sounds provided by the system. namespace Media { /// @brief Provides a collection of Cursor objects for use by a Windows Forms application. /// @par Library /// Switch.System class system_export_ SystemSound : public object { public: SystemSound() {} void Play() const; bool Equals(const object& obj) const override {return is<SystemSound>(obj) && Equals((const SystemSound&)obj);} bool Equals(const SystemSound& sound) const {return this->type == sound.type;} intptr Tag() const {return (intptr)this->type;} private: friend struct ::__opaque_sound_access__; explicit SystemSound(int32 type) : type(type) {} int32 type = 0; }; } } }
true
0ce137dbfb076cf9df7d66cabaae5cc6ec49c6d7
C++
riverraft/MCCI-Catena-HS300x
/src/Catena-HS300x.h
UTF-8
5,722
2.546875
3
[ "MIT" ]
permissive
/* Module: Catena-HS300x.h Function: Definitions for the Catena library for the IDT HS300x sensor family. Copyright and License: See accompanying LICENSE file. Author: Terry Moore, MCCI Corporation June 2019 */ #ifndef _CATENA_HS300X_H_ # define _CATENA_HS300X_H_ # pragma once #include <cstdint> #include <Wire.h> namespace McciCatenaHs300x { /****************************************************************************\ | | Version boilerplate | \****************************************************************************/ // create a version number for comparison static constexpr std::uint32_t makeVersion( std::uint8_t major, std::uint8_t minor, std::uint8_t patch, std::uint8_t local = 0 ) { return ((std::uint32_t)major << 24u) | ((std::uint32_t)minor << 16u) | ((std::uint32_t)patch << 8u) | (std::uint32_t)local; } // extract major number from version static constexpr std::uint8_t getMajor(std::uint32_t v) { return std::uint8_t(v >> 24u); } // extract minor number from version static constexpr std::uint8_t getMinor(std::uint32_t v) { return std::uint8_t(v >> 16u); } // extract patch number from version static constexpr std::uint8_t getPatch(std::uint32_t v) { return std::uint8_t(v >> 8u); } // extract local number from version static constexpr std::uint8_t getLocal(std::uint32_t v) { return std::uint8_t(v); } // version of library, for use by clients in static_asserts static constexpr std::uint32_t kVersion = makeVersion(0,2,0,0); /****************************************************************************\ | | The sensor class. | \****************************************************************************/ class cHS300x { private: // control result of isDebug(); use for compiling code in/out. static constexpr bool kfDebug = false; // the device i2c address. This is fixed by design. static constexpr std::int8_t kAddress = 0x44; // millisec to delay before reading. This is the datasheet "typical" // value of 16.9, rounded up a little. static constexpr std::uint32_t kMeasurementDelayMs = 40; // how many extra millis to wait before giving up on the data. static constexpr std::uint32_t kGetTemperatureTimeoutMs = 100; public: // constructor: cHS300x(TwoWire &wire) : m_wire(&wire) {} // neither copyable nor movable cHS300x(const cHS300x&) = delete; cHS300x& operator=(const cHS300x&) = delete; cHS300x(const cHS300x&&) = delete; cHS300x& operator=(const cHS300x&&) = delete; // convert raw temperature to celsius static constexpr float rawTtoCelsius(std::uint16_t tfrac) { return -40.0f + 165.0f * ((tfrac & 0xFFFC) / float(0xFFFC)); } // convert raw RH to percent. static constexpr float rawRHtoPercent(std::uint16_t rhfrac) { return 100.0f * ((rhfrac & 0xFFFC) / float(0xFFFC)); } // convert Celsius temperature to raw format. static constexpr std::uint16_t celsiusToRawT(float t) { t += 40.0f; if (t < 0.0f) return 0; else if (t > 165.0) return 0xFFFCu; else return (std::uint16_t) ((t / 165.0f) * float(0xFFFC)); } // convert RH as percentage to raw format. static constexpr std::uint16_t percentRHtoRaw(float rh) { if (rh > 100.0) return 0xFFFCu; else if (rh < 0.0) return 0; else return (std::uint16_t) (float(0xFFFC) * (rh / 100.0)); } // raw measurements as a collection. struct MeasurementsRaw { std::uint16_t TemperatureBits; std::uint16_t HumidityBits; void extract(std::uint16_t &a_t, std::uint16_t &a_rh) const { a_t = this->TemperatureBits; a_rh = this->HumidityBits; } }; // measurements, as a collection. struct Measurements { float Temperature; float Humidity; void set(const MeasurementsRaw &mRaw) { this->Temperature = rawTtoCelsius(mRaw.TemperatureBits); this->Humidity = rawRHtoPercent(mRaw.HumidityBits); } void extract(float &a_t, float &a_rh) const { a_t = this->Temperature; a_rh = this->Humidity; } }; // Start operation (return true if successful) bool begin(); // End operation void end(); // get temperature and humidity as normalized 16-bit fractions bool getTemperatureHumidityRaw(MeasurementsRaw &mRaw) const; // get temperature and humidity as floats in engineering units bool getTemperatureHumidity(Measurements &m) const; // start a measurement; return the millis to delay before expecting an answer std::uint32_t startMeasurement(void) const; // get asynch measurement results, if available. bool getMeasurementResults(Measurements &m) const; // get raw measurement results, if available. bool getMeasurementResultsRaw(MeasurementsRaw &mRaw) const; // return true if configured for debugging; compile-time constant. static constexpr bool isDebug() { return kfDebug; } // return the address; for compatibility. static constexpr std::int8_t getAddress() { return kAddress; } protected: // address the device and read an nBuf-byte response. bool readResponse(std::uint8_t *buf, size_t nBuf) const; private: // the I2C bus to use for communication. TwoWire *m_wire; }; } // namespace McciCatenaHs300x #endif /* _CATENA_HS300X_H_ */
true
9018d70e52a055f4de7fe37ee6d5c26d0f568a13
C++
AJAbanto/KinectXRobot
/arduino/Community_robot_firmware/robotArm_v0.41/byj_gripper.cpp
UTF-8
2,363
2.953125
3
[ "MIT" ]
permissive
#include "byj_gripper.h" #include <Arduino.h> BYJ_Gripper::BYJ_Gripper(int pin0, int pin1, int pin2, int pin3, int steps){ grip_steps = steps; byj_pin_0 = pin0; byj_pin_1 = pin1; byj_pin_2 = pin2; byj_pin_3 = pin3; step_cycle = 0; pinMode(byj_pin_0, OUTPUT); pinMode(byj_pin_1, OUTPUT); pinMode(byj_pin_2, OUTPUT); pinMode(byj_pin_3, OUTPUT); } void BYJ_Gripper::cmdOn() { direction = true; for (int i = 1; i <= grip_steps; i++) { moveSteps(); delay(1); } } void BYJ_Gripper::cmdOff() { direction = false; for (int i = 1; i <= grip_steps; i++) { moveSteps(); delay(1); } } void BYJ_Gripper::setDirection(){ if (direction == true) { step_cycle++; } if (direction == false) { step_cycle--; } if (step_cycle > 7) { step_cycle = 0; } if (step_cycle < 0) { step_cycle = 7; } } void BYJ_Gripper::moveSteps() { switch (step_cycle) { case 0: digitalWrite(byj_pin_0, LOW); digitalWrite(byj_pin_1, LOW); digitalWrite(byj_pin_2, LOW); digitalWrite(byj_pin_3, HIGH); break; case 1: digitalWrite(byj_pin_0, LOW); digitalWrite(byj_pin_1, LOW); digitalWrite(byj_pin_2, HIGH); digitalWrite(byj_pin_3, HIGH); break; case 2: digitalWrite(byj_pin_0, LOW); digitalWrite(byj_pin_1, LOW); digitalWrite(byj_pin_2, HIGH); digitalWrite(byj_pin_3, LOW); break; case 3: digitalWrite(byj_pin_0, LOW); digitalWrite(byj_pin_1, HIGH); digitalWrite(byj_pin_2, HIGH); digitalWrite(byj_pin_3, LOW); break; case 4: digitalWrite(byj_pin_0, LOW); digitalWrite(byj_pin_1, HIGH); digitalWrite(byj_pin_2, LOW); digitalWrite(byj_pin_3, LOW); break; case 5: digitalWrite(byj_pin_0, HIGH); digitalWrite(byj_pin_1, HIGH); digitalWrite(byj_pin_2, LOW); digitalWrite(byj_pin_3, LOW); break; case 6: digitalWrite(byj_pin_0, HIGH); digitalWrite(byj_pin_1, LOW); digitalWrite(byj_pin_2, LOW); digitalWrite(byj_pin_3, LOW); break; case 7: digitalWrite(byj_pin_0, HIGH); digitalWrite(byj_pin_1, LOW); digitalWrite(byj_pin_2, LOW); digitalWrite(byj_pin_3, HIGH); break; default: digitalWrite(byj_pin_0, LOW); digitalWrite(byj_pin_1, LOW); digitalWrite(byj_pin_2, LOW); digitalWrite(byj_pin_3, LOW); break; } setDirection(); }
true
fc9f5aee47a1f2c3cddb3f510c8c3286697fca06
C++
eddiebarry/cp_code
/saving_universe.cpp
UTF-8
4,183
2.671875
3
[]
no_license
#include<queue> #include<stack> #include<set> #include<iostream> #include<unordered_map> #include<vector> #include<list> #include<climits> #define INF 0x3f3f3f3f #define FOR(i, j, k, in) for (long i=j ; i<k ; i+=in) #define RFOR(i, j, k, in) for (long i=j ; i>=k ; i-=in) #define REP(i, j) FOR(i, 0, j, 1) #define RREP(i, j) RFOR(i, j, 0, 1) #define MOD 1000000007 using namespace std; int sI(){ int c = getchar_unlocked(); bool flag = true; if(c=='-'){ flag =false; c = getchar_unlocked(); } int n = 0; for( ; (c<48 || c>57); c = getchar_unlocked() ); for( ; (c>47 && c<58); c = getchar_unlocked() ){ n = (n<<1) + (n<<3) +c -48; } if(flag){ return n; } else{ return n*-1; } } long long score(char s[], int sz){ long long sc = 0; long long temp = 1; for(int i = 0; i <sz; i++){ if(s[i]=='C'){ temp*=2; } else{ sc+=temp; } } return sc; } int main(){ int t; cin>>t; REP(z,t){ long long D; string str; cin>>D>>str; int num_sz = str.size(); char str_arr[num_sz]; for(int i = 0; i < num_sz; i++){ str_arr[i]=str[i]; } long long scr = score(str_arr,num_sz); if(scr<=D){ cout<<"Case #"<<z+1<<": "<<0<<"\n"; } else{ int swaps = 0; bool flag = true; for(int i = num_sz-2; i>=0; i--){ if(str_arr[i]=='C'&&str_arr[i+1]=='S'&& i+1 != num_sz){ str_arr[i]^=str_arr[i+1]; str_arr[i+1]^=str_arr[i]; str_arr[i]^=str_arr[i+1]; swaps++; i+=2; } // REP(i,num_sz){ // cout<<str_arr[i]<<" "; // } // cout<<"\n"; scr = score(str_arr,num_sz); if(scr<=D){ cout<<"Case #"<<z+1<<": "<<swaps<<"\n"; flag = false; break; } } if(flag){ cout<<"Case #"<<z+1<<": IMPOSSIBLE\n"; } } // cout<<"scr is "<<scr<<"\n"; } } // //find first D that can be swapped and swap it // //find first swappable d // for(;temp<num_sz;temp++){ // if(str_arr[temp]=='C'&&str_arr[temp-1]=='S'){ // //swap // char tem = str_arr[temp]; // str_arr[temp]=str_arr[temp-1]; // str_arr[temp-1]=tem; // swaps++; // temp--; // break; // } // if(str_arr[temp]=='S'&&temp==num_sz-1){ // flag=false; // } // } // REP(i,num_sz){ // cout<<str_arr[i]<<" "; // } // cout<<"\n"; // scr = score(str_arr,num_sz); // cin>>D; // cout<<D<<"\n"; // string str; // cin>>str; // cout<<s<<"\n"; // int swaps = 0; // long long sc = score(s); // cout<<sc<<"\n"; // int temp = 1; // bool flag = true; // while (sc>D && flag) { // for(; temp < str.size(); temp++){ // if(temp==str.size()-1 && s[temp]=='S'){ // flag = false; // break; // } // if(s[temp]=='D' && s[temp-1]!='D'){ // break; // } // } // cout<<temp<<"\n"; // if(s[temp]=='D' && s[temp-1]!='D'){ // swaps++; // s[temp]='Z'; // s[temp-1]^=s[temp]; // s[temp]^=s[temp-1]; // temp-=2; // } // cout<<s<<"\n"; // sc = score(s); // cout<<"the changed score is "<<sc<<"\n"; // } // if(sc>D){ // cout<<"IMPOSSIBLE\n"; // } // else{ // cout<<swaps<<"\n"; // }
true
93a9cca5bb7a764366c8a903457d2f3cdcc7419a
C++
maverick439/DataStructures
/Greedy/MaxMin.cpp
UTF-8
531
2.78125
3
[]
no_license
//https://www.hackerrank.com/challenges/angry-children/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=greedy-algorithms #include <bits/stdc++.h> using namespace std; // Complete the maxMin function below. int maxMin(int k, vector<int> arr) { int n = arr.size(); sort(arr.begin(),arr.end()); int i=0,j=k-1; int diff=INT_MAX; while(j < n){ int x = arr[j] - arr[i]; if(x < diff) diff = x; i++; j++; } return diff; }
true
627c53523d908984f6722581681bf89fbee9ba40
C++
MeteorIOT/Equipo1
/Veleta/viento-veleta/viento-veleta.ino
UTF-8
843
2.578125
3
[]
no_license
int sumaVeleta=0; const byte pinDireccion = A2; //pin Analógico int direccion = 0; int tiempoEnvio=30; int leerDireccion(int suma){ suma=suma/tiempoEnvio; if(suma>=415 && suma< 440) return 0; if(suma>=440 && suma< 490) return 45; if(suma>=490 && suma< 510) return 90; if(suma>=540 && suma< 550) return 135; if(suma>=510 && suma< 525) return 18; if(suma>=525 && suma< 540) return 225; if(suma>=590 && suma< 615) return 270; if(suma>=615 && suma< 620) return 315; } void setup () { Serial.begin(9600); //iniciamos comunicación serial delay(200); } void loop () { for(int i=0;i<=tiempoEnvio;i++){ sumaVeleta+=analogRead(pinDireccion); delay(1000); } direccion=leerDireccion(sumaVeleta); sumaVeleta=0; Serial.print("dirección: "); Serial.println(direccion); }
true
d1e2433cbc48439db0219cb2e8c18d588abb7b7f
C++
juliocmontes/bcc_course
/Lab 1/lab1_distancebtwnpoints.cpp
UTF-8
811
3.84375
4
[]
no_license
/* Title: Lab 1 - Distance Between Points Author: Julio Montes Date: 08.29.19 Description: prints the distance between coordinates */ #include <iostream> #include <cmath> #include <sstream> using namespace std; int main() { int x1, x2, y1, y2, result; // comment in/out below to ask for input x1 = 2; x2 = 3; y1 = 8; y2 = -5; // cout << "Enter x1: "; // cin >> x1; // cout << "Enter y1: "; // cin >> y1; // cout << "Enter x2: "; // cin >> x2; // cout << "Enter y2: "; // cin >> y2; // multiples the values result = sqrt(pow((x1 - x2), 2) + pow((y1 - y2), 2)); // returns the result above cout << "The distance between " << "(" << x1 << ", " << y1 << ")" << " and " << "(" << x2 << "," << y2<< ") " << result <<endl; return 0 ; }
true
56f4c5ed86ffc5ea8ed443aa22e41686826779b5
C++
TraceIvan/backup-copy-of-my-acm-code
/TINA集训(九)/51Nod 1202 子序列个数.cpp
GB18030
1,018
2.640625
3
[]
no_license
//dp[i] = (dp[i - 1] * 2 + 1) % MOD; Ԫ״γ //dp[i] = (dp[i - 1] * 2 - dp[pos[val[i]] - 1] + MOD) % MOD; Ԫط״γ #include<iostream> using namespace std; const int maxn = 100010; const int MOD = 1e9 + 7; int num[maxn]; long long dp[maxn]; int vis[maxn]; int main() { int n; while (~scanf("%d",&n)) { for (int i = 1; i <= n; i++) scanf("%d", &num[i]); memset(dp, 0, sizeof(dp)); memset(vis, 0, sizeof(vis)); for (int i = 1; i <= n; i++) { if (!vis[num[i]])// Ԫûгֹ {// ǰiɵмiϵټϵiΪ dp[i] =( 2 * dp[i - 1]+1) % MOD; } else dp[i] = (dp[i - 1] * 2 - dp[vis[num[i]]-1]+MOD)%MOD;// ǰiɵмiϵмȥԪΪβĴ vis[num[i]] = i; } printf("%lld\n", dp[n]); } return 0; }
true
9bcf765cbc0f7bf50357cf73bd85ec077aa1b039
C++
MDOBreno/BMOAulasCpp28TheNewKeywordInCpp
/BMOAulasCpp28TheNewKeywordInCpp/main.cpp
UTF-8
2,483
4.1875
4
[]
no_license
// // main.cpp // BMOAulasCpp28TheNewKeywordInCpp // // Created by Breno Medeiros on 10/06/21. // #include <iostream> #include <string> //Lembrando que 'new' instancia em um construtor(outro escopo que não é o que o new está escrito), e retorna // um ponteiro pra instancia. Lembre-se tb que, como 'new' aloca no 'Heap', voce(desenvolvedor) é quem tem // que se lembrar de liberar a memoria posteriormente com 'delete'. // Obs1: Assim como o 'new' chama o construtor na alocacao, o 'delete' chama o destrutor na desalocacao. // Obs2: Se der 'new' em um array[ Por ex "... = new Entidade[50]();" ], a desalocacao fica 'delete[]'. using Texto = std::string; class Entidade { private: Texto m_Nome; //Cherno chuta q Texto tem cerca de 28 Bytes, mas o que importa é q o peso de Entidade==m_Nome public: Entidade(): m_Nome("Desconhecido") { } Entidade(const Texto& nome): m_Nome(nome) { } const Texto& GetNome() const { return m_Nome; } }; //Esta funcao é apenas para dar uma ideia, usa-la causara erros. void* novo(Entidade& e, int quantidadeNoArray){ int bytesParaAlocar = sizeof(e) * quantidadeNoArray; // 1400 Bytes = 28 ByterPorEntidade * 50 Entidades void* retorno = malloc(bytesParaAlocar); // A funcao 'malloc()' aloca os 1400 Bytes passados, e retorna o ponteiro for (int i=0; i<quantidadeNoArray; i++) { *(&retorno + (sizeof(e) * i)) = new Entidade(); //Aqui ele chaam o construtor para cada posicao } return retorno; } int main(int argc, const char * argv[]) { // insert code here... int a=2; int* b = new int; int* bArray = new int[50]; // Aloca: 200 Bytes = 4 BytesPorInt * 50 Ints //Obs: As duas linhas abaixo fazem sao iguais, exceto q so a primeira chama o contrutor, e por isso vc n devia a segunda: Entidade* eNew = new Entidade(); // Tambem funciona se nao escrever os '()' Entidade* eMalloc = (Entidade*)malloc(sizeof(Entidade)); // 'malloc()' aloca os Bytes passados e retorna o ponteiro Entidade* eArray = new Entidade[50](); // O bronca qnd se usa 'new' é q ele usa um bloco de 50*Entidade na memoria //Se fossemos escrever uma funcao do que 'new' esta fazendo na linha acima seria algo como: // Entidade* eArray = novo(Entidade &e, int quantidadeNoArray); //Descomentar essa linha causa erros. std::cout << "Hello, World!\n"; return 0; }
true
bf5dfb6158d8d6b623f742a03e4095701c10f5c2
C++
jsbien/rcin-index4djvu
/METS/fiszki/cards.cpp
UTF-8
3,906
2.671875
3
[]
no_license
#include "cards.h" Cards::Cards() { } void Cards::parse(const QString &filename) { Card card; if (card.parse(filename)) m_cards.append(card); else qDebug() << "Error parsing" << filename; } void Cards::sort() { qStableSort(m_cards); for (int i = 0; i < m_cards.count(); i++) m_cards[i].setSequence(i+1); } void Cards::setUniqueFiles() { QSet<QString> uniqueFilenames; QSet<QString> skipFilenames; for (int i = 0; i < m_cards.count(); i++) { QString unique = m_cards[i].filename().section('_', -1, -1).section('.', 0, 0); if (uniqueFilenames.contains(unique)) skipFilenames.insert(unique); else uniqueFilenames.insert(unique); } for (int i = 0; i < m_cards.count(); i++) { QString unique = m_cards[i].filename().section('_', -1, -1).section('.', 0, 0); if (!skipFilenames.contains(unique)) m_cards[i].setUniqueFilename(unique); } } bool Cards::readCsv(const QString &csvFile) { QFile file(csvFile); if (!file.open(QIODevice::ReadOnly)) return false; m_cards.clear(); QTextStream stream(&file); stream.setCodec("UTF-8"); stream.readLine(); while (!stream.atEnd()) { QString line = stream.readLine().trimmed(); Card card; if (card.parseCvsRow(line)) m_cards.append(card); } return m_cards.count() > 0; } bool Cards::saveCsv(const QString &csvFile) { QFile file(csvFile); if (!file.open(QIODevice::WriteOnly)) return false; QTextStream stream(&file); stream.setCodec("UTF-8"); stream << "Filename;Drawer;Base filename;First word;Last word;First word index;Last word index;Sequence;Error message\n"; for (int i = 0; i < m_cards.count(); i++) stream << m_cards[i].csvRow(); return true; } bool Cards::saveMaleks(const QString &maleksFile) { QFile file(maleksFile); if (!file.open(QIODevice::WriteOnly)) return false; QTextStream stream(&file); stream.setCodec("UTF-8"); for (int i = 0; i < m_cards.count(); i++) { stream << QString("$ %1\t%2\n").arg(m_cards[i].drawer()).arg(m_cards[i].uniqueFilename()); stream << "\t$from_names_djvu\t$all\n"; stream << "$end\n\n"; } return true; } bool Cards::saveSql(const QString &djvuIndexFile, const QString &sqlFilename) { QFile indexFile(djvuIndexFile); if (!indexFile.open(QIODevice::ReadOnly)) { qDebug() << "Failr"; return false; } QMap<QString, QString> fileMap; QTextStream indexStream(&indexFile); while (!indexStream.atEnd()) { QString line = indexStream.readLine().trimmed(); if (line.contains(',')) fileMap[line.section(',', 0, 0)] = line.section(',', 1); } qDebug() << "SQLout" << sqlFilename; QFile sqlFile(sqlFilename); if (!sqlFile.open(QIODevice::WriteOnly)) return false; QTextStream sqlStream(&sqlFile); sqlStream.setCodec("UTF-8"); foreach (Card card, m_cards) { QString index = card.uniqueFilename(); if (!fileMap.contains(index)) { qDebug() << QString("Index '%1' not found for drawer %2").arg(index).arg(card.drawer()); continue; } sqlStream << "#\n"; sqlStream << QString("# %1,%2\n").arg(index).arg(fileMap[index]); sqlStream << "#\n"; sqlStream << "# first fiche\n"; sqlStream << QString::fromUtf8("insert into actual_entries (fiche, entry, comment) " "values ('%1_0001', '%2', 'z opisu pudełka');\n").arg(index).arg(card.firstWord()); sqlStream << QString::fromUtf8("insert into original_entries (fiche, entry, comment) " "values ('%1_0001', '%2', 'z opisu pudełka');\n").arg(index).arg(card.firstWord()); sqlStream << "# last fiche\n"; QString baseFile = fileMap[index].section('.', -2); sqlStream << QString::fromUtf8("insert into actual_entries (fiche, entry, comment) " "values ('%1', '%2', 'z opisu pudełka');\n").arg(baseFile).arg(card.lastWord()); sqlStream << QString::fromUtf8("insert into original_entries (fiche, entry, comment) " "values ('%1', '%2', 'z opisu pudełka');\n").arg(baseFile).arg(card.lastWord()); } return true; }
true
09090df3d1b1962bf72a8a7558e6f1ce5b446acc
C++
bbb125/leetcode
/august-2021-challenge/max-product-of-splitted-binary-tree/main.cpp
UTF-8
2,985
3.53125
4
[]
no_license
#include <gtest/gtest.h> #include <gmock/gmock.h> /** * url: * https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/615/week-3-august-15th-august-21st/3903/ * problem: * Given the root of a binary tree, split the binary tree into two subtrees by * removing one edge such that the product of the sums of the subtrees is * maximized. * * Return the maximum product of the sums of the two subtrees. Since the answer * may be too large, return it modulo 109 + 7. * * Note that you need to maximize the answer before taking the mod and not after * taking it. * * Example 1: * Input: root = [1,2,3,4,5,6] * Output: 110 * Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. * Their product is 110 (11*10) * * Example 2: * Input: root = [1,null,2,3,4,null,null,5,6] * Output: 90 * Explanation: Remove the red edge and get 2 binary trees with sum 15 * and 6.Their product is 90 (15*6) * * Example 3: * Input: root = [2,3,9,10,7,8,6,5,4,11,1] * Output: 1025 * * Example 4: * Input: root = [1,1] * Output: 1 * * * Constraints: * The number of nodes in the tree is in the range [2, 5 * 10^4]. * * 1 <= Node.val <= 10^4 */ namespace { struct TreeNode { TreeNode(int x) : TreeNode(x, nullptr, nullptr) {} TreeNode(int x, TreeNode* _left, TreeNode* _right) : val{x} , left{_left} , right{_right} {} int val = 0; TreeNode* left = nullptr; TreeNode* right = nullptr; }; } // unnamed namespace class Solution { public: struct Impl { static constexpr auto modulo = static_cast<std::uint64_t>(1e9 + 7); int solve(TreeNode* root) { auto total = collectSums(root); if (std::size(sums_) <= 1) return 0; // max product is achieved when difference between two elements is the smallest auto min = *std::min_element(std::begin(sums_), std::end(sums_), [total](auto left, auto right) { auto absVal = [total](auto value) { value *= 2; return std::max(total, value) - std::min(total, value); }; return absVal(left) < absVal(right); }); return (std::uint64_t{min % modulo} * ((total - min) % modulo)) % modulo; } std::uint64_t collectSums(TreeNode* root) { if (!root) return 0; sums_.push_back(root->val + collectSums(root->left) + collectSums(root->right)); return sums_.back(); } std::vector<std::uint64_t> sums_; }; int maxProduct(TreeNode* root) { return Impl{}.solve(root); } }; namespace { TEST(SolutionTests, All) { // EXPECT_THAT(Solution{}.twoSum(example2, 6), ::testing::UnorderedElementsAre(1, 2)); } } // unnamed namespace
true
7de0dae6a7546d08201e902c99013b07450c93d7
C++
Phuocpr1998/HeDieuHanh
/Source/nachos-3.4/code/threads/FileManage.h
UTF-8
1,162
2.796875
3
[ "MIT-Modern-Variant" ]
permissive
#ifndef _FILEMANAGE_H #define _FILEMANAGE_H #include "copyright.h" #define MAXFILE 10 class OpenFile; struct FileCustom { OpenFile* file; int type; int pos; }; class FileManage { private: FileCustom** arrayFile; int size; public: FileManage(int maxFile); // trả về vị trí còn trống (ID) // nếu không còn vị trí trống trả về -1 int FindFreeSlot(); // thêm file mới vào vị trí id (được tìm ở trên) // type: 0 là readonly, 1 là read write // nếu thành công trả về true, ngược lại trả về false bool Add(int id, OpenFile *openFile, int type); // lấy con trỏ Open file tại vị trí id // nếu lỗi sẽ trả về null FileCustom* GetFile(int id); // chuyển vị trí đọc ghi // trả về vị trí thật đã dịch // nếu có lỗi trả về -1 int Seek(int id, int position); // nếu đóng thành công trả về true // ngược lại false bool CloseFile(int id); ~FileManage() { if (arrayFile != NULL) { for (int i = 0; i < size; i++) { if (arrayFile[i] != NULL) delete arrayFile; } delete[] arrayFile; } } }; #endif
true
e4848f84806b324587a36e04fc5bd83ba165e3f3
C++
hexu1985/Data.Structures.With.Cpp
/include/spooler.h
UTF-8
4,307
3.40625
3
[]
no_license
#include <iostream.h> // include the random number generator and LinkedList class #include "random.h" // simulate print times #include "link.h" // printer speed is 8 pages per minute const int PRINTSPEED = 8; // pages per minute // record containing information for each print job struct PrintJob { int number; char filename[20]; int pagesize; }; // the print spooler class class Spooler { private: // queue that holds print jobs and status LinkedList<PrintJob> jobList; // deltaTime holds a random value in the range 1 - 5 // minutes to simulate elapsed time // Job info is updated by the UpdateSpooler method int deltaTime; void UpdateSpooler(int time); RandomNumber rnd; public: // constructor Spooler(void); // add job to the spooler void AddJob(const PrintJob& J); // spooler evaluation methods void ListJobs(void); int CheckJob(int jobno); int NumberOfJobs(void); }; // construct; initialize deltaTime to 0 Spooler::Spooler(void): deltaTime(0) {} // spooler update. assumes time elapses during which pages // are printed. method deletes completed jobs and updates // the remaining pages for the current running job void Spooler::UpdateSpooler(int time) { PrintJob J; // number of pages that could print in the given time int printedpages = time*PRINTSPEED; // use value printedpages and scan list of jobs in queue. // update the print queue jobList.Reset(); while (!jobList.ListEmpty() && printedpages > 0) { // look at first job J = jobList.Data(); // if pages printed greater than pages for job, // update printed pages count and delete job if (printedpages >= J.pagesize) { printedpages -= J.pagesize; jobList.DeleteFront(); } // part of job complete; update remaining pages else { J.pagesize -= printedpages; printedpages = 0; jobList.Data() = J; // update info in node } } } // update spooler and add the new job; compute the random time // before the next spooler update event. void Spooler::AddJob(const PrintJob& J) { UpdateSpooler(deltaTime); deltaTime = 1 + rnd.Random(5); // range 1 - 5 minutes jobList.InsertRear(J); // add the new job } // update spooler and list all jobs currently in the spooler void Spooler::ListJobs(void) { PrintJob J; // update the print queue UpdateSpooler(deltaTime); // generate the time until the next event deltaTime = 1 + rnd.Random(5); // check for empty spooler before scanning of the list if (jobList.ListSize() == 0) cout << "Print queue is empty\n"; else { // reset to the beginning of list and use a // loop to scan the list of jobs. stop on end of list. // print information fields for each job for(jobList.Reset(); !jobList.EndOfList(); jobList.Next()) { J = jobList.Data(); cout << "Job " << J.number << ": " << J.filename; cout << " " << J.pagesize << " pages remaining" << endl; } } } // update spooler; scan list for job with the designated job // number; if found, return number of pages remaining to print int Spooler::CheckJob(int jobno) { PrintJob J; UpdateSpooler(deltaTime); deltaTime = 1 + rnd.Random(5); // use a sequential scan of the list with jobno as the key for(jobList.Reset();!jobList.EndOfList();jobList.Next()) { J = jobList.Data(); if (J.number == jobno) break; } // if match found. return number of remaining pages or 0 if (!jobList.EndOfList()) return J.pagesize; else return 0; } // retrieve the number of jobs currently in the spooler int Spooler::NumberOfJobs(void) { return jobList.ListSize(); }
true
e9fdff8b0a335a02d163213febffff6b976bf87f
C++
Muneeb147/Data-Structures
/PA4/check.cpp
UTF-8
9,672
2.984375
3
[]
no_license
#include <cstdio> #include <cstring> #include <ctime> #include <iostream> #include <vector> #include "list.cpp" #include <cstdlib> using namespace std; class HashC { protected: long int tableSize; int collisions; int a; public: List<long>*hashTable; HashC() { hashTable=new List<long>[tableSize]; for (int i = 0; i < tableSize; i++) { hashTable[i].head = NULL; } } }; ListItem<long> * merge (ListItem<long> *a ,ListItem<long> *b) { ListItem <long> * merged; while (a!=NULL || b!=NULL) { if (a->value<=b->value) { merged->value=a->value; a=a->next; } else { merged->value=b->value; b=b->next; } merged=merged->next; } if (a!=NULL) { while (a!=NULL) { merged->value=a->value; a=a->next; merged=merged->next; } } if (b!=NULL) { while (b!=NULL) { merged->value=b->value; b=b->next; merged=merged->next; } } return merged; // if (a==NULL) // return b; // if (b==NULL) // return a; // // if (a->value <= b->value) // { // node=a; // node->next=merge(a->next,b); // } // else // { // node=b; // node->next=merge(a,b->next); // } // return node; } void partition(ListItem<long> * head,ListItem<long> **front,ListItem<long> **back) { ListItem<long> * slow; ListItem<long> * fast; if (head==NULL || head->next==NULL) { *front=head; // first half of linked list *back=NULL; // second half of linked list } else { slow=head; fast=head->next; while (fast!=NULL) { fast=fast->next; if (fast!=NULL) { fast=fast->next; slow=slow->next; } } *front=head; // first half *back=slow->next; // second half slow->next=NULL; // breaking the contact } } void mergesort (ListItem<long> **node) { ListItem<long> * head=*node; ListItem<long> * temp=NULL; ListItem<long> * temp2=NULL; if (head==NULL || head->next==NULL) { return ; // base case } partition (head,&temp,&temp2); mergesort(&temp); mergesort(&temp2); *node=merge(temp,temp2); } vector<long> InsertionSort(vector<long> nums) { int k; long int size=nums.size(); long int my_array[size]; for (int i=0;i<size;i++) { my_array[i]=nums[i]; } for (int i=1;i<size;i++) { int key=my_array[i]; k=i-1; while(my_array[k]>key && k>=0) { my_array[k+1]=my_array[k]; k--; } my_array[k+1]=key; } // copying the elements into vector for (int i=0;i<size;i++) { nums.push_back(my_array[i]); } return nums; } vector<long> InsertSort(vector<long> nums) { int k; vector <long> sorted; long int size=nums.size(); long int my_array[size]; for (int i=0;i<size;i++) { my_array[i]=nums[i]; } for (int i=1;i<size;i++) { int key=my_array[i]; k=i; while(my_array[k-1]>key ) { my_array[k]=my_array[k-1]; k--; } my_array[k]=key; } // copying the elements into vector for (int i=0;i<size;i++) { sorted.push_back(my_array[i]); } return sorted; } vector<long> MergeSort(vector<long> nums) { List<long> mylist; vector <long> myvec; for (int i=0;i<nums.size();i++) mylist.insertAtHead(nums[i]); ListItem <long> * temp=mylist.getHead(); mergesort(&temp); mylist.setHead(temp); ListItem<long> * NEWHEAD=mylist.getHead(); for (int i=0;i<nums.size();i++) { myvec.push_back(NEWHEAD->value); NEWHEAD=NEWHEAD->next; } return myvec; } // QUICK SOrt K FUNC void SWAP(long a[],int index1,int index2) { int temp=a[index1]; a[index1]= a[index2]; a[index2]=temp; } void swap ( long* a, long* b ) { long t = *a; *a = *b; *b = t; } ListItem <long> * partitionLinkedlist (ListItem <long> **first,ListItem <long> ** end) { int pivot =(*end)->value; ListItem<long> * temp=(*first)->prev; ListItem<long> * i; for (i=*first;i!=*end;i=i->next) { if (i->value<= pivot) { temp=temp->next; //swapping temp and i k value swap(&(temp->value),&(i->value)); // int x=i->value; // i->value=temp->value; // temp->value=x; } } temp=temp->next; //int x=temp->value; //temp->value=end->value; //end->value=x; swap(&(temp->value),&((*end)->value)); return temp; } ListItem<long> ** quicksortlinkedlist (ListItem <long> ** head,ListItem<long> ** tail) { if ((*head)!=NULL && (*tail)!=NULL&& (*tail)->next!=NULL) { ListItem<long> * temp= partitionLinkedlist(head,tail); quicksortlinkedlist(head,&temp->prev); quicksortlinkedlist(&temp->next,tail); } else return head; } vector<long> QuickSortList(vector<long> nums) { List<long> mylist; vector <long> myvec; for (int i=0;i<nums.size();i++) mylist.insertAtHead(nums[i]); ListItem <long> * head=mylist.getHead(); ListItem <long> * tail=mylist.getTail(); ListItem <long> ** myhead=quicksortlinkedlist(&head,&tail); ListItem<long>* node=mylist.getHead(); for (int i=0;i<nums.size();i++) { myvec.push_back((*myhead)->value); (*myhead)=(*myhead)->next; } return myvec; } int find_median (long array[],int index1,int index2,int index3) { int k; int my_array[3]; my_array[0]=array[index1]; my_array[1]=array[index2]; my_array[2]=array[index3]; for (int i=1;i<3;i++) // insertion sor { int key=my_array[i]; k=i-1; while(my_array[k]>key && k>=0) { my_array[k+1]=my_array[k]; k--; } my_array[k+1]=key; } int median = my_array[1]; if (median==array[index1]) return index1; if (median==array[index2]) return index2; return index3; } int partitionQ(long myarray[], int start, int end,int select) // BAIG { srand (time(NULL)); if (select==1) { int pivot = myarray[end]; // selecting end as pivot int i = start - 1; for (int j=start ; j<end; j++) { if (myarray[j] <= pivot) { i++; SWAP(myarray,i,j); } } SWAP (myarray,i+1,end); return i + 1; } // index of pivot else if (select==2) { int pivot_index=start; // selecting start index pivot SWAP (myarray,pivot_index,end); int pivot=myarray[end]; int i = start - 1; for (int j=start ; j<end; j++) { if (myarray[j] <= pivot) { i++; SWAP(myarray,i,j); } } SWAP (myarray,i+1,end); return i + 1; } } void quicksortarray(long my_array [],int start,int end,int select) //BAIG { if (start<end) { int pivot_index=partitionQ(my_array,start,end,select); quicksortarray(my_array,start,pivot_index-1,select); quicksortarray(my_array,pivot_index+1,end,select); } } vector<long> QuickSortArray(vector<long> nums) // BAIG { vector <long> Nums; int select; cout << "press 1 for selecting pivot from end, 2 for start" << endl; cin >> select; long int size=nums.size(); long int my_array[size]; for (int i=0;i<size;i++) { my_array[i]=nums[i]; } int start=0,end=size-1; quicksortarray(my_array,start,end,select); for (int i=0;i<nums.size();i++) { Nums.push_back(my_array[i]); } return Nums; } void check_heap_prop(long myarray[],long size) { int p; int lchild; int rchild; for (int i=size/2;i>0;i--) { p=i; lchild=2*i; rchild=2*i+1; if (lchild<size && myarray[p]>myarray[lchild]) { if (myarray[lchild]>myarray[rchild]) p=rchild; else p=lchild; } if (rchild<size && myarray[p]>myarray[rchild]) { if (myarray[lchild]>myarray[rchild]) p=rchild; else p=lchild; } if (p!=i || p==lchild || p==rchild ) { long temp=myarray[i]; myarray[i]=myarray[p]; myarray[p]=temp; check_heap_prop(myarray,size); } } } vector <long> make_minheap(long heap [],long size) { vector <long> sorted; for (int i=size;i>1;i--) { check_heap_prop(heap,i); sorted.push_back(heap[1]); heap[1]=heap[i-1]; } cout << "size :" << sorted.size()<< endl; return sorted; } vector<long> HeapSort(vector<long> nums) { long size= nums.size()+1; long heaparray[size]; for (int i=0;i<=size;i++) { heaparray[i+1]=nums[i]; // copying the elements into the array } vector <long> sortedvector; for (int i=size;i>1;i--) { check_heap_prop(heaparray,i); sortedvector.push_back(heaparray[1]); heaparray[1]=heaparray[i-1]; } return sortedvector; } vector<long> BucketSort(vector<long> nums, int max) { HashC bucket; vector<long> sorted_vector; int tablesize=max; //HashC bucket(max); for (int i=0;i<nums.size();i++) { unsigned int key= nums[i] % tablesize; bucket.hashTable[key].insertAtHead(nums[i]); } for (int i=0;i<tablesize;i++) { if (bucket.hashTable[i].head!=NULL) { ListItem <long> * head= bucket.hashTable[i].getHead(); while (head!=NULL) { sorted_vector.push_back(head->value); head=head->next; } } } return sorted_vector; } int main () { List<int> mylist; vector <long> b,c; int size=14; int a[size]={0,-1,3,2,4,5,1,6,7,4,0,3,5,9}; for (int i=0;i<size;i++) // mylist.insertAtHead(a[i]); b.push_back(a[i]); cout << "list before sorting" << endl; for (int i=0;i<size;i++) { cout << b[i]<<endl; } // c=InsertSort(b); //c=HeapSort(b); c=MergeSort(b); cout << "AFTER SORTING" << endl; for (int i=0;i<c.size();i++) { cout <<"value :"<< c[i]<<endl; //cout << "key :" << c[i]%10 <<endl; } }
true
cec2d12237208eb678d2fa678d2cf936a458f0fa
C++
harmonilarrabee/C_Tutorials
/function/inputPower.cpp
UTF-8
588
3.78125
4
[]
no_license
#include <stdio.h> int power(int m, int n); /*computes exponential input in the form [single-digit, positive base]^[single-digit, positive exponent]*/ main() { int c, base, exp, i; c = getchar(); if (c >= '0' && c <= '9') base = c - '0'; else printf("invalid input\n"); c = getchar(); c = getchar(); if (c >= '0' && c <= '9') exp = c - '0'; else printf("invalid input"); printf("%d\n", power(base, exp)); return 0; } /*power: raise base to the exp power; exp >= 0*/ int power(int base, int exp) { int p; for (p = 1; exp > 0; --exp) p = p * base; return p; }
true
69db57b3e00c709fa8af94951aeb801bcba81404
C++
abersailbot-archive/bottleboat-boaty-mcboatface
/TheControlSystem/TheControlSystem.ino
UTF-8
2,209
2.9375
3
[]
no_license
#include <Wire.h> #include <Servo.h> int HMC6352Address = 0x42; int slaveAddress = HMC6352Address >> 1; int compassOffset = 120; const int MIDPOINT = 96; const int RANGE = 30; int DESIREDHEADING = 50; const int SPEED = 128; Servo rudder; void setup() { Serial.begin(9600); rudder.attach(9); Wire.begin(); delay(5000); DESIREDHEADING = wrapHeading(getCompassHeading()); delay(15000); analogWrite(5, SPEED); } int getCompassHeading() { Wire.beginTransmission(slaveAddress); Wire.write("A"); Wire.endTransmission(); delay(10); Wire.requestFrom(slaveAddress, 2); int compassValue = 0; if (Wire.available()) { compassValue = Wire.read() * 256; compassValue += Wire.read(); } return (compassValue / 10) - compassOffset ; } void setRudder(int rudderPos) { // constraints mimimum value if (rudderPos < MIDPOINT - RANGE) { rudderPos = MIDPOINT - RANGE; } // constraints maximum value if (rudderPos > MIDPOINT + RANGE) { rudderPos = MIDPOINT + RANGE; } rudder.write(rudderPos); } int getHeadingDiff (int firstHeading, int desiredHeading) { //function to find heading difference when compass heading switches between 0 and 360 if (firstHeading > 180) { return (360 - firstHeading) + desiredHeading; }else{ return desiredHeading - firstHeading; } } int control(int compassHeading, int desiredHeading){ static double integral = 0; static double pGain = 0.6; static double iGain = 0.1; double error = getHeadingDiff(compassHeading, desiredHeading); // prevents integral windup if (abs(error) < 10){ integral = integral + error; } else { integral = 0; } double p = error * pGain; double i = integral * iGain; return p + i; } int wrapHeading(int compassHeading) { if (compassHeading < 0) { return 360 + compassHeading; } else { return compassHeading; } } void loop() { int heading = wrapHeading(getCompassHeading()); int rudderpos = control(heading, DESIREDHEADING); setRudder(MIDPOINT + rudderpos); Serial.print("Compass heading "); Serial.println(heading); Serial.print("Rudder position "); Serial.println(rudderpos); delay(500); }
true
df00db8126d9cfbde4f648ebc9fc7358f5024f65
C++
Linzertorte/LeetCode
/RemoveDuplicatesFromSortedList.cpp
UTF-8
619
3.28125
3
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *deleteDuplicates(ListNode *head) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. ListNode *p,*q; p=q=head; while(q){ while(q && p->val==q->val) q=q->next; p->next=q; p=q; if(q)q=q->next; } if(p)p->next=NULL; return head; } };
true
faae200b4392af3182a450cd3bb9e8402715c04d
C++
KyleNBurke/openGLGame
/src/engine/math/quaternion.cpp
UTF-8
2,176
3.3125
3
[]
no_license
#include "quaternion.hpp" #include "vector3.hpp" #include "euler.hpp" #include <cmath> Quaternion::Quaternion() : Quaternion(0, 0, 0, 1) {} Quaternion::Quaternion(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) {} Quaternion::Quaternion(const Quaternion& q) : Quaternion(q.x, q.y, q.z, q.w) {} Quaternion::Quaternion(const Vector3& axis, float angle) { float halfAngle = angle / 2.0f; float s = sinf(halfAngle); x = axis.x * s; y = axis.y * s; z = axis.z * s; w = cosf(halfAngle); } Quaternion::Quaternion(const Euler& e) { float c1 = cosf(e.x / 2.0f); float c2 = cosf(e.y / 2.0f); float c3 = cosf(e.z / 2.0f); float s1 = sinf(e.x / 2.0f); float s2 = sinf(e.y / 2.0f); float s3 = sinf(e.z / 2.0f); switch (e.order) { case Euler::Order::xyz: x = s1 * c2 * c3 + c1 * s2 * s3; y = c1 * s2 * c3 - s1 * c2 * s3; z = c1 * c2 * s3 + s1 * s2 * c3; w = c1 * c2 * c3 - s1 * s2 * s3; break; case Euler::Order::xzy: x = s1 * c2 * c3 - c1 * s2 * s3; y = c1 * s2 * c3 - s1 * c2 * s3; z = c1 * c2 * s3 + s1 * s2 * c3; w = c1 * c2 * c3 + s1 * s2 * s3; break; case Euler::Order::yxz: x = s1 * c2 * c3 + c1 * s2 * s3; y = c1 * s2 * c3 - s1 * c2 * s3; z = c1 * c2 * s3 - s1 * s2 * c3; w = c1 * c2 * c3 + s1 * s2 * s3; break; case Euler::Order::yzx: x = s1 * c2 * c3 + c1 * s2 * s3; y = c1 * s2 * c3 + s1 * c2 * s3; z = c1 * c2 * s3 - s1 * s2 * c3; w = c1 * c2 * c3 - s1 * s2 * s3; break; case Euler::Order::zxy: x = s1 * c2 * c3 - c1 * s2 * s3; y = c1 * s2 * c3 + s1 * c2 * s3; z = c1 * c2 * s3 + s1 * s2 * c3; w = c1 * c2 * c3 - s1 * s2 * s3; break; case Euler::Order::zyx: x = s1 * c2 * c3 - c1 * s2 * s3; y = c1 * s2 * c3 + s1 * c2 * s3; z = c1 * c2 * s3 - s1 * s2 * c3; w = c1 * c2 * c3 + s1 * s2 * s3; break; } } Quaternion& Quaternion::operator*=(const Quaternion& q) { const Quaternion a(*this); const Quaternion& b = q; x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y; y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z; z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x; w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z; return *this; }
true
3279ddef0eb3fcc8738006062ea29659431bcacc
C++
micamarietta/assignment4
/queue.hpp
UTF-8
1,042
3.5
4
[]
no_license
#include <iostream> #include "DoublyLinkedList.hpp" using namespace std; template<typename t> class queue{ public: queue(){ //nothing yet } queue(int maxSize){ list = new DoublyLinkedList<t>[maxSize]; mSize = maxSize; front = 0; rear = -1; numElements = 0; } ~queue(){ delete list; } void insert(t data){ list->insertBack(data); cout << "here is the queue : " << endl; list->printList(); ++numElements; } t accessElement(int i){ return list->accessData(i); } t remove(){ //error checking //cout << "getting to line before enters DLL" << endl; --numElements; return list->removeFront(); } t peek(){ return list->front->data; } bool isFull(){ return (numElements == mSize); } bool isEmpty(){ return (numElements == 0); } int getSize(){ return numElements; } //vars int front;//aka head int rear; //aka tail int mSize; int numElements; char *myQueue; //array private: DoublyLinkedList<t> *list; };
true
cf939db323514fe76dddf7b917e8e36863ad2233
C++
skyleet/Arduino
/INO Codes/manish/manish.ino
UTF-8
1,106
2.578125
3
[]
no_license
const int numReadings = 10; int readings[numReadings]; int readIndex = 0; int total = 0; int average = 0; int inputPin = A0; unsigned long previousMillis = 0; const long interval = 1000; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(A0, INPUT); pinMode(13, OUTPUT); for (int thisReading = 0; thisReading < numReadings; thisReading++) { readings[thisReading] = 0; } } void loop() { total = total - readings[readIndex]; readings[readIndex] = analogRead(inputPin); total = total + readings[readIndex]; readIndex = readIndex + 1; if (readIndex >= numReadings) { readIndex = 0; } average = total / numReadings; Serial.println(average); delay(1); // put your main code here, to run repeatedly: if (average > 1000) { digitalWrite(13, HIGH); } else { digitalWrite(13, LOW); } unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; if (ledState == LOW) { ledState = HIGH; } else { ledState = LOW; } } }
true
b9ed1ce60f4c31fc4bd65efefdda21d2d0faebec
C++
daibiaoxuwu/PM3
/plane.cpp
UTF-8
1,097
2.5625
3
[]
no_license
#include "plane.h" #include <cmath> Plane::Plane() : Primitive() { } void Plane::Input( std::string var , std::stringstream& fin ) { if ( var == "N=" ) N.Input( fin ); N = N.GetUnitVector(); if ( var == "R=" ) fin >> R; if ( var == "Dx=" ) Dx.Input( fin ); if ( var == "Dy=" ) Dy.Input( fin ); Primitive::Input( var , fin ); } Collider Plane::Collide( Ray ray ) { Collider collider; double nomDi = N.Dot( ray.dir ); if ( fabs( nomDi ) <= EPS ) return collider; double tt=( - R -N.Dot( ray.pos ) )/nomDi;//double tt = ( N * R - ray.pos ).Dot( N ) / nomDi; if (tt <= EPS||tt >= INF) return collider; collider.crash = true; collider.I = ray.dir; collider.SetPrimitive(this); collider.dist = tt; collider.front = true;//( d < 0 ); collider.C = ray.pos + ray.dir * collider.dist; collider.N =N;// ( collider.front ) ? N : -N; return collider; } Color Plane::GetTexture(Vector3 C) { double u = C.Dot( Dx ) / Dx.Module2() + 0.5; double v = C.Dot( Dy ) / Dy.Module2() + 0.5; return material->texture->GetSmoothColor( u , v ); }
true
15a325a41819346f7cbe82fc67db975518103259
C++
codingsunchen/simpleChat
/ser/pthread.cpp
UTF-8
3,941
2.546875
3
[]
no_license
#include"pthread.h" #include "control.h" #include "public.h" #include <assert.h> #include <event.h> #include <jsoncpp/json/json.h> #include <stdio.h> #include <stdlib.h> #include <map> #include <iostream> #include <string.h> #include <functional> #include <algorithm> using namespace std; extern Control control_sever; void* pthread_run(void *arg); void socketpair_cb(int fd,short event,void *arg);//arg应该接收的是子线程的对象this指针 Pthread::Pthread(int sock_fd) { _socketpair_fd = sock_fd;//socketpair的1端 //启动线程 int n = pthread_create(&_pthread,NULL,pthread_run,this); //assert(n==0); if(0!=n) { perror("pthread_create error:"); return ; } } void* pthread_run(void *arg) { Pthread *This = (Pthread*)arg; //将sock_pair_1加入到libevent sock_pair_1_cb() This->_base = event_base_new(); //创建事件,绑定socketpair_fd的回调函数(socketpair_cb) struct event* listen_event = event_new(This->_base,This->_socketpair_fd,EV_READ|EV_PERSIST,socketpair_cb,This); assert(listen_event != NULL); event_add(listen_event,NULL);//将listen_fd加入到主线程的libevent中监听起来。若有事件发生就去调用回调函数。 event_base_dispatch(This->_base); } //对客户端请求的处理。 将客户端发过来的请求Json进行解析,得到消息类型,对不同类型的消息进行不同的处理方式。 //将消息交给controler进行管理 典型的观察者监听者模式(MVC),所有的消息都对应一个对象,每个对象都把自己关注的消息注册在 //controler中,然后controler对这些消息进行监听,当某种消息发生时,就会自动调用对象在这里注册时指定的处理方式。 void cli_cb(int clifd,short event,void *arg)//arg应该对应Pthread对象的指针this { //cout<<"cli_cb()"<<endl; Pthread *This = (Pthread*)arg; char buff[2048] = {0}; if(-1 == recv(clifd,buff,2047,0)) { perror("cli_cb recv fail:"); return ; } Json::Value root; Json::Reader read; read.parse(buff,root); //如果发现发过来的是客户端退出消息,那么在这个回调函数中救直接将_event_map表中存储这个客户端所生成的事件删除掉。 //因为后期也不会再用到了。 if(MSG_TYPE_EXIT == root["reason_type"].asInt()) { event_free(This->_event_map[clifd]); This->_event_map.erase(This->_event_map.find(clifd)); } //cout<<"begin control process"<<endl; control_sever.process(clifd,buff); //cout<<"success control process"<<endl; } //socketpair专门用于将主线程交给的客户端套接子监听起来,事件发生时调用回调函数进行处理。 void socketpair_cb(int fd,short event,void *arg)//arg应该接收的是子线程的对象this指针 { //struct event_base *_base = (struct event_base*)arg; Pthread *This = (Pthread*)arg; //接受主线程传送过来的客户端套接字 char buff[16] = {0}; if(-1 == recv(This->_socketpair_fd,buff,15,0)) { perror("recv error:"); return ; } int clifd = atoi(buff);//得到主线程传给子线程的客户端描述符。 //将客户端描述符构造为事件,交给子线程的libevent监听起来 struct event* listen_event = event_new(This->_base,clifd,EV_READ|EV_PERSIST,cli_cb,This); assert(listen_event != NULL); event_add(listen_event,NULL); //将这个客户端事件记录在map表中 This->_event_map.insert(make_pair(clifd,listen_event)); //回复主线程,现在子线程中监听了多少个客户端的事件了。 memset(buff,0,16); int listen_num = This->_event_map.size(); sprintf(buff,"%d",listen_num); send(This->_socketpair_fd,buff,strlen(buff),0); } /* sock_pair_1_cb(int fd,short event,void *arg) { //recv -> clien_fd //将client_fd加入到libevent client_cb() //给主线程回复当前监听的客户端数量 } client_cb(int fd,short event,void *arg) { //recv ->buff //将buff发给control control_sever.process(fd,buff) } */
true
f8b9f79e61a051ee3e68f66ef6360a18b309fa5c
C++
Xuchaoxiong/homework-of-data-structure
/作业/第五次专题实验之寻找指缝/pixelFunction.cpp
GB18030
3,005
3.03125
3
[ "Apache-2.0" ]
permissive
/* * pixelFunction.cpp * * Created on: 20141219 * Author: kohill * ȨûУӭð */ #include <cstddef> #include <stdint.h> #include <iostream> #include <windows.h> /*ͼ*/ typedef struct { uint32_t x; uint32_t y; } Coordinate; /* * @Function: findStartPixel * @Description:Ѱҿʼ * @param * @return ɹش׵ַΪNULL * @Call */ Coordinate *findStartPixel(Coordinate thumbFlag[], byte **image, uint32_t width, uint32_t heigth, uint32_t xStart, uint32_t yStart = 0) { assert((image!=NULL)&&(xStart<=width)&&(yStart<=heigth)); assert((image!=NULL)&&(xStart!=0)&&(yStart!=0)); for (uint32_t k = 0, j = xStart + 1; j < width - 1; j++) { for (uint32_t i = yStart + 1; i < heigth - 1; i++) { if ((image[i][j]) + (image[i - 1][j]) + (image[i][j - 1]) + (image[i - 1][j - 1]) + (image[i + 1][j]) + (image[i][j + 1]) + (image[i + 1][j + 1]) + (image[i + 1][j - 1]) + (image[i - 1][j + 1]) < 255 * 3) { thumbFlag[k].x = j; thumbFlag[k].y = i; k++; if (k == 4) { return thumbFlag; } i += 100; } } } return NULL; } /* * @Function: markPiexl * @Description:ԲοΪ׼ѰҸĺɫص * @param * @Call * @return ɹشĶά飬򷵻NULL */ byte** markPiexl(byte **image, uint32_t width, uint32_t heigth,Coordinate &start) { assert((image!=NULL)&&(&start!=NULL)); assert((start.y<heigth)&&(start.x<width)); uint32_t x= start.x; uint32_t y= start.y; for(uint32_t j=x-400;(j<x+800)&&(j<width);j++){ for(uint32_t i=y-20;(i<y+20)&&(i<heigth);i++){ if(image[i][j]==0){ image[i][j]=1; } } } return image; } /* * @Function: clearPiexl * @Description:ı־1,ص * @param * @return ɹشĶά飬򷵻NULL * @Call */ byte** clearPiexl( byte **image, uint32_t width, uint32_t heigth){ assert(image!=NULL); for(uint32_t i=0;i<heigth;i++){ for(uint32_t j=0;j<width;j++){ if(image[i][j]!=1){ image[i][j]=255; } } } return image; } /* * @Function: pixelRecognize * @Description:ļеʶͼеָ * @param * @return ɹشĶά飬򷵻NULL * @CallfindStartPixel, markPiexl,clearPiexl */ byte** pixelRecognize(byte **image, uint32_t width, uint32_t heigth, uint32_t xStart, uint32_t yStart = 0) { /*ȡ */ assert((image!=NULL)&&(xStart<=width)&&(yStart<=heigth)); assert((image!=NULL)&&(xStart!=0)&&(yStart!=0)); Coordinate thumbFlag[4]; findStartPixel(thumbFlag, image, width, heigth, xStart, yStart); markPiexl(image,width,heigth,thumbFlag[0]); markPiexl(image,width,heigth,thumbFlag[1]); markPiexl(image,width,heigth,thumbFlag[2]); markPiexl(image,width,heigth,thumbFlag[3]); clearPiexl(image,width,heigth); return image; }
true
7855aa04ee97851d27048a7eb49ee1db7493ff09
C++
IamFlowZ/Cracking-The-Coding-Interview-Anwsers
/Stacks&Queues/StackWithMin/StackWithMin/StackWithMin/Stack.cpp
UTF-8
642
3.21875
3
[]
no_license
#include "stdafx.h" #include "Stack.h" Stack::Stack() { } void Stack::push(Node n) { if (n.value < min_value->value) { min_value = &n; n.next = top; top = &n; count++; } else { top = &n; count++; } } Stack::Node Stack::pop() { Node temp = *top; if (top == min_value) { Node* new_min = temp.next; for (int i = 0; i < count; i++) { if (new_min->value < new_min->next->value) { new_min = new_min->next; } } min_value = new_min; } top = temp.next; count--; return temp; } Stack::Node Stack::min() { return *min_value; } bool Stack::isEmpty() { return top == nullptr; } Stack::~Stack() { }
true
42b383ce638c2e22283597f883e36953e061a074
C++
zxlwbi199101/ACM
/1003 Hangover.cpp
UTF-8
1,410
4.0625
4
[]
no_license
/* http://poj.org/problem?id=1003 Description How far can you make a stack of cards overhang a table? If you have one card, you can create a maximum overhang of half a card length. (We're assuming that the cards must be perpendicular to the table.) With two cards you can make the top card overhang the bottom one by half a card length, and the bottom one overhang the table by a third of a card length, for a total maximum overhang of 1/2 + 1/3 = 5/6 card lengths. In general you can make n cards overhang by 1/2 + 1/3 + 1/4 + ... + 1/(n + 1) card lengths, where the top card overhangs the second by 1/2, the second overhangs tha third by 1/3, the third overhangs the fourth by 1/4, etc., and the bottom card overhangs the table by 1/(n + 1). This is illustrated in the figure below. Input The input consists of one or more test cases, followed by a line containing the number 0.00 that signals the end of the input. Each test case is a single line containing a positive floating-point number c whose value is at least 0.01 and at most 5.20; c will contain exactly three digits. Output For each test case, output the minimum number of cards necessary to achieve an overhang of at least c card lengths. Use the exact output format shown in the examples. Sample Input 1.00 3.71 0.04 5.19 0.00 Sample Output 3 card(s) 61 card(s) 1 card(s) 273 card(s) */
true
70146c3eff0539ea868755af5485282a52fd86c2
C++
Fateha9106/Computer-Graphics
/home.cpp
UTF-8
1,227
2.6875
3
[]
no_license
#include <GL/gl.h> #include <GL/glut.h> void display(void) { /* clear all pixels */ glClear (GL_COLOR_BUFFER_BIT); /* draw white polygon (rectangle) with corners at * (0.25, 0.25, 0.0) and (0.75, 0.75, 0.0) */ glColor3ub (204,102,0); glBegin(GL_POLYGON); glVertex2d (150,800); glVertex2d (250,800); glVertex2d (250,900); glVertex2d (150,900); glEnd(); /* don't wait! * start processing buffered OpenGL routines */ glFlush (); } void init (void) { /* select clearing (background) color */ glClearColor (0,0,0,0); /* initialize viewing values */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,1000,0,1000); } /* * Declare initial window size, position, and display mode * (single buffer and RGBA). Open window with "hello" * in its title bar. Call initialization routines. * Register callback function to display graphics. * Enter main loop and process events. */ int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutInitWindowSize (500, 500); glutInitWindowPosition (100, 100); glutCreateWindow ("hello"); init (); glutDisplayFunc(display); glutMainLoop(); return 0; /* ISO C requires main to return int. */ }
true
b1065a8bc6ee4433c953d06eaffdefcaabdc295f
C++
sandeepshiven/cpp-practice
/hashing/count distinct/better.cpp
UTF-8
455
3.265625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main(){ int s,temp; cout << "Enter the size of the array: "; cin >> s; unordered_set<int> arr; cout << "Enter the elements of the array: "; for(int i=0; i < s; i++){ cin >> temp; arr.insert(temp); } cout<< "There are "<<arr.size()<<" disticnt elements\n"; // for(auto i: arr){ // cout << i << " "; // } return 0; }
true
fbabf75ba5d50626fe3310fc171d27bba46581af
C++
linuxmap/nazhiai
/shortvideo/MuxCleanService/Server/Configuration.h
UTF-8
616
2.578125
3
[]
no_license
#ifndef _CONFIGURATION_HEADER_H_ #define _CONFIGURATION_HEADER_H_ #include <string> class Configuration { public: static bool Load(std::string& err); static void Unload(); public: struct ActionInfo { int hostid = 0; std::string host = {}; std::string root = {}; int frequency = 60; int margin = 5; }; static ActionInfo action; struct DbInfo { std::string url = {}; }; static DbInfo db; private: Configuration(); Configuration(const Configuration&); Configuration& operator=(const Configuration&); }; #endif
true
c3856c73502f32f0c80e5c9dbcac867931401865
C++
CartoDB/mobile-sdk
/all/native/datasources/TileDownloadListener.h
UTF-8
1,387
2.671875
3
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Copyright (c) 2016 CartoDB. All rights reserved. * Copying and using this code is allowed only according * to license terms, as given in https://cartodb.com/terms/ */ #ifndef _CARTO_TILEDOWNLOADLISTENER_H_ #define _CARTO_TILEDOWNLOADLISTENER_H_ #include "core/MapTile.h" #include <memory> namespace carto { /** * Listener for tile downloader. */ class TileDownloadListener { public: virtual ~TileDownloadListener() { } /** * Listener method that is called before download has actually started to report the total tile count. * @param tileCount The number of tiles that will be downloaded (if not already in the cache). */ virtual void onDownloadStarting(int tileCount) { } /** * Listener method that is called to report about download progress. * @param progress The progress of the download, from 0 to 100. */ virtual void onDownloadProgress(float progress) { } /** * Listener method that is called when downloading has finished. */ virtual void onDownloadCompleted() { } /** * Listener method that is called when a tile download fails. * @param tile The tile that could not be downloaded. */ virtual void onDownloadFailed(const MapTile& tile) { } }; } #endif
true
5502c6484a630b3644c720231ea0d9e1697995bb
C++
carrascomj/disopred
/src/weights.cpp
UTF-8
1,072
2.546875
3
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain" ]
permissive
#include "weights.h" #include <cstdlib> #include <fstream> #include <iostream> using namespace std; const float Weights::A =-2.01; const float Weights::B =1.63; const float Weights::A2=-2.00; const float Weights::B2=2.1535; const float Weights::M2= 0.0783; const float Weights::C2= 0.104; long double* Weights::read_weight(const char* fileName, float& bias, int size) { long double* w= new long double[size]; ifstream infile(fileName); if(!infile) { cerr << "\nCould not find weight file : \n" << fileName << endl; exit(1); } infile >> bias; for(int i=0; i<size; i++) infile >> w[i]; infile.close(); return w; } long double* Weights::read_weight(const char* fileName, int size) { long double* w= new long double[size]; ifstream infile(fileName); if(!infile) { cerr << "\nCould not find weight file : \n" << fileName << endl; exit(1); } for(int i=0; i<size; i++) infile >> w[i]; infile.close(); return w; }
true
bc985219ef7100187fee073428021805877cb7b0
C++
Tiriree/TiriWhitney_TY
/allTESTcode/testingCode/capacitiveTouch/capacitiveTouch.ino
UTF-8
1,692
2.859375
3
[]
no_license
#include <ADCTouch.h> int ref0, ref1, ref2, ref3, ref4; //reference values to remove offset void setup() { // No pins to setup, pins can still be used regularly, although it will affect readings Serial.begin(9600); ref0 = ADCTouch.read(A0, 500); //create reference values to ref1 = ADCTouch.read(A1, 500); //account for the capacitance of the pad ref2 = ADCTouch.read(A2, 500); ref3 = ADCTouch.read(A3, 500); ref4 = ADCTouch.read(A4, 500); } void loop() { int value0 = ADCTouch.read(A0); //no second parameter int value1 = ADCTouch.read(A1); // --> 100 samples int value2 = ADCTouch.read(A2); int value3 = ADCTouch.read(A3); int value4 = ADCTouch.read(A4); value0 -= ref0; //remove offset value1 -= ref1; value2 -= ref2; value3 -= ref3; value4 -= ref4; Serial.print(value0 > 40); //send (boolean) pressed or not pressed Serial.print("\t"); //use if(value > threshold) to get the state of a button Serial.print(value1 > 40); Serial.print("\t"); Serial.print(value2 > 40); //send (boolean) pressed or not pressed Serial.print("\t"); Serial.print(value3 > 40); //send (boolean) pressed or not pressed Serial.print("\t"); Serial.print(value4 > 40); //send (boolean) pressed or not pressed Serial.print("\t\t"); Serial.print(value0); //send actual reading Serial.print("\t"); Serial.print(value1); //send actual reading Serial.print("\t"); Serial.print(value2); //send actual reading Serial.print("\t"); Serial.print(value3); //send actual reading Serial.print("\t"); Serial.println(value4); delay(100); }
true
208177b271160296fe3b048d1eb368644bd1f61c
C++
GabMeloche/Networking
/UDP/Main/Main.cpp
UTF-8
707
3.09375
3
[]
no_license
#include <Client.h> #include <Server.h> #define PORT 8755 int main() { std::string option; std::getline(std::cin, option); if (option == "s") { std::cout << "server selected\n"; Server* server = RunServer(); while (true) { std::string ip; std::getline(std::cin, ip); std::cout << "people connected: " << NumberOfConnections(server) << std::endl; } } else { std::cout << "client selected; enter IP address of server:\n"; std::string ip; std::getline(std::cin, ip); Client* client = RunClient(); while (true) { Send(client, 1.05f, 2.08f, 3.12f); std::string message; std::getline(std::cin, message); client->Send(message.c_str()); } } return 0; }
true
f628ec113cde31a5221705a4b35c5d20f3390960
C++
cgramming/Checkers
/main.cpp
UTF-8
1,456
2.5625
3
[]
no_license
#include <iostream> #include<conio.h> #include <windows.h> using namespace std; char a[33]={' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '}; int c[42]={8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,8,8,8,8,8,8,8,8}; int out1=12; int out2=12; // c[] values :::: 1 = player one plain coin 2 = player one queen // c[] values :::: 3 = player two plain coin 4 = player two queen // c[] values :::: 0 = not occupied. const char X ='X'; const char O ='O'; const char Q1 ='#'; const char Q2 ='Q'; #include"board.h" //int places = 14; int main() { int froms = 1; int tos =0; int player =1; int passmove; int moved; startB(); drawB(0); for (int i = 1; i>0; i++) { moved=0; cout<<"Player "<<player<<" Enter the coin box # : ";cin>>froms; system("cls"); drawB(froms); cout<<"Player "<<player<<" Enter the destination box # : ";cin>>tos; moved=singleM(player,froms,tos); if (moved==1) passmove=place(player,froms,tos); else if(doubleM(player,froms,tos)){passmove=place(player,froms,tos);} else {cout<<"\a\a"; continue;} if(out1 <=0) {cout<<"\a\a\a\a\a\a\a PLAYER 2 WON ******************* "; getch(); break;} if(out2 <=0) {cout<<"\a\a\a\a\a\a\a PLAYER 1 WON ******************* "; getch(); break;} system("cls"); drawB(tos); if (player == 1)player =2; else player = 1; } return 0; }
true
5806899b096a93763c1c40afc3663a80c7791286
C++
Caceresenzo/42
/CPP Modules/05/ex02/Bureaucrat.cpp
UTF-8
4,433
2.96875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Bureaucrat.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ecaceres <ecaceres@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/06/29 10:22:51 by ecaceres #+# #+# */ /* Updated: 2020/06/29 10:22:51 by ecaceres ### ########.fr */ /* */ /* ************************************************************************** */ #include <sstream> #include "Bureaucrat.hpp" #include "ShrubberyCreationForm.hpp" const int Bureaucrat::GRADE_HIGHEST = 1; const int Bureaucrat::GRADE_LOWEST = 150; Bureaucrat::Bureaucrat(void) : _name("?") { this->_grade = Bureaucrat::GRADE_HIGHEST; } Bureaucrat::Bureaucrat(const std::string name, int grade) : _name(name) { this->_grade = ensureGradeRange(grade); } Bureaucrat::~Bureaucrat(void) { } Bureaucrat::Bureaucrat(const Bureaucrat &other) : _name(other._name) { this->operator =(other); } Bureaucrat& Bureaucrat::operator=(const Bureaucrat &other) { if (this != &other) { this->_grade = ensureGradeRange(other._grade); } return (*this); } int Bureaucrat::ensureGradeRange(int grade) { if (grade < Bureaucrat::GRADE_HIGHEST) throw Bureaucrat::GradeTooHighException(); if (grade > Bureaucrat::GRADE_LOWEST) throw Bureaucrat::GradeTooLowException(); return (grade); } int Bureaucrat::promote() { return (this->_grade = ensureGradeRange(_grade - 1)); } int Bureaucrat::demote() { return (this->_grade = ensureGradeRange(_grade + 1)); } void Bureaucrat::signForm(Form &form) { bool alreadySigned = form.isSigned(); bool success = false; if (!alreadySigned) { try { form.beSigned(*this); success = true; } catch (std::exception &exception) { } } std::cout << _name; if (success) std::cout << " signs " << form.getName(); else std::cout << " cant signs " // << form.getName() // << " because " // << (alreadySigned ? "it was already signed" : "his grade is too low"); std::cout << std::endl; } void Bureaucrat::executeForm(Form const &form) { std::string error; bool success = false; try { form.execute(*this); success = true; } catch (ShrubberyCreationForm::IOException &e) { error = std::string("IO Error: ").append(e.what()); } catch (std::exception &e) { error = std::string(e.what()); } if (success) std::cout << this->_name << " executs " << form.getName() << std::endl; else std::cout << this->_name << " cant executs " << form.getName() << ": " << error << std::endl; } const std::string& Bureaucrat::getName() const { return (this->_name); } int Bureaucrat::getGrade() const { return (this->_grade); } Bureaucrat::GradeTooHighException::GradeTooHighException(void) : std::exception() { } Bureaucrat::GradeTooHighException::~GradeTooHighException(void) throw () { } Bureaucrat::GradeTooHighException::GradeTooHighException( const GradeTooHighException &other) { this->operator =(other); } Bureaucrat::GradeTooHighException& Bureaucrat::GradeTooHighException::operator=(const GradeTooHighException &other) { (void)other; return (*this); } const char* Bureaucrat::GradeTooHighException::what() const throw () { return "Grade is too high"; } Bureaucrat::GradeTooLowException::GradeTooLowException(void) : std::exception() { } Bureaucrat::GradeTooLowException::~GradeTooLowException(void) throw () { } Bureaucrat::GradeTooLowException::GradeTooLowException( const GradeTooLowException &other) { this->operator =(other); } Bureaucrat::GradeTooLowException& Bureaucrat::GradeTooLowException::operator=(const GradeTooLowException &other) { (void)other; return (*this); } const char* Bureaucrat::GradeTooLowException::what() const throw () { return "Grade is too low"; } std::ostream& operator<<(std::ostream &outStream, const Bureaucrat &bureaucrat) { return (outStream << bureaucrat.getName() // << ", bureaucrat grade " // << bureaucrat.getGrade()); }
true
10301780f4d0f8f846ce18d5fc29d86b17d6a9d8
C++
jk983294/CommonScript
/cpp/lib/protobuf/add_person.cc
UTF-8
2,002
2.828125
3
[]
no_license
#include <google/protobuf/util/time_util.h> #include <ctime> #include <fstream> #include <iostream> #include <string> #include "addressbook.pb.h" using namespace std; using google::protobuf::util::TimeUtil; // Main function: Reads the entire address book from a file, // adds one person based on user input, then writes it back out to the same file. int main(int argc, char* argv[]) { // Verify that the version of the library that we linked against is compatible GOOGLE_PROTOBUF_VERIFY_VERSION; tutorial::AddressBook address_book; const char* addressBookPath = "/tmp/address.book"; { // Read the existing address book. fstream input(addressBookPath, ios::in | ios::binary); if (!input) { cout << addressBookPath << ": File not found. Creating a new file." << endl; } else if (!address_book.ParseFromIstream(&input)) { cerr << "Failed to parse address book." << endl; return -1; } } // Add an address. tutorial::Person* person = address_book.add_people(); int id = 42; string name{"kun"}; string email{"fake@126.com"}; vector<string> phones{"123", "456"}; person->set_id(42); person->set_name(name); person->set_email(email); for (const auto& number : phones) { tutorial::Person::PhoneNumber* phone_number = person->add_phones(); phone_number->set_number(number); phone_number->set_type(tutorial::Person::MOBILE); } *person->mutable_last_updated() = TimeUtil::SecondsToTimestamp(time(NULL)); { // Write the new address book back to disk. fstream output(addressBookPath, ios::out | ios::trunc | ios::binary); if (!address_book.SerializeToOstream(&output)) { cerr << "Failed to write address book." << endl; return -1; } } // Optional: Delete all global objects allocated by libprotobuf. google::protobuf::ShutdownProtobufLibrary(); return 0; }
true
0c0c6e332a536ef327d61776c2b7cc89d6f35ea5
C++
juicyluv/Tanks
/Tanks/Entities/Tank.h
UTF-8
870
2.828125
3
[]
no_license
#ifndef TANK_H #define TANK_H #include "../States/State.h" #include "../Projectiles/StandartBullet.h" enum class TankType { Player = 0, Enemy }; class Tank : public Entity { public: Tank(ResourceHolder<sf::Texture, Textures>* textures, std::vector<Projectile*>* projectiles); virtual ~Tank(); virtual void render(sf::RenderTarget* target); virtual void shoot(const sf::Vector2f& velocity) = 0; ResourceHolder<sf::Texture, Textures>* textures; std::vector<Projectile*>* projectiles; // Tank objects sf::Sprite head; sf::Sprite body; Hitbox hb_body; Hitbox hb_head; // Stats float hp; float armor; float damage; float rotationSpeed; sf::Time attackSpeed; TankType type; void takeDamage(float dmg); void restartClock(); float getSpeed() const; bool canShoot() const; bool isAlive() const; protected: sf::Clock attackClock; }; #endif
true
4e22ea5b0fe50c853fa0729c3af2e4af423c6c7a
C++
Blizzard-Code/DateStruct
/8.cpp
UTF-8
406
3.109375
3
[]
no_license
#include <stdio.h> #include <string.h> struct Student { int sid; char name[200]; int age; }; void f(struct Student* pst) { (*pst).sid = 20; pst->age = 20; strcpy(pst->name, "zs"); } void g(struct Student* pst) { printf("%d %s %d", pst->age, pst->name, pst->sid); } int main() { struct Student st; f(&st); g(&st); // printf("%d %s %d",st.age,st.name,st.sid); }
true
1add6d1e44cab31e7cef9adff81e28dba17e1d5b
C++
ivanovdimitur00/programs
/Programs/zadachi praktikum 4/guess the card.cpp
UTF-8
384
3.046875
3
[]
no_license
#include <iostream> using namespace std; int main() { string Cards[13] = {"2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"}; string Paints[4] = {"Of Clubs","Of Diamonds","Of Hearts","Of Spades"}; int card_guess; cin>>card_guess; card_guess--; cout<<Cards[card_guess%13]<<" "; cout<<Paints[card_guess/13]; system("pause"); return 0; }
true
1d859032806ca4f19d7cdea9f365d5670280bd94
C++
mholtkamp/SuperKappaKatBallParty2Deluxe3D
/Source/Library.Desktop.Test/AttributedTest.cpp
UTF-8
13,107
2.59375
3
[]
no_license
#include "pch.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace FieaGameEngine; using namespace TestingUtilities; namespace LibraryDesktopTest { TEST_CLASS(AttributedTest) { public: TEST_METHOD_INITIALIZE(Initialize) { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF); _CrtMemCheckpoint(&sStartMemState); } TEST_METHOD_CLEANUP(Cleanup) { AttributedFoo::ClearPrescribedAttributes(); _CrtMemState endMemState, diffMemState; _CrtMemCheckpoint(&endMemState); if (_CrtMemDifference(&diffMemState, &sStartMemState, &endMemState)) { _CrtMemDumpStatistics(&diffMemState); Assert::Fail(L"Memory Leaks!"); } } TEST_METHOD(AttributedConstructor) { AttributedFoo attributed; Assert::IsTrue(attributed.IsAttribute(Attributed::sAttributedThisKey)); Assert::IsTrue(attributed.IsPrescribedAttribute(Attributed::sAttributedThisKey)); Assert::IsFalse(attributed.IsAuxiliaryAttribute(Attributed::sAttributedThisKey)); Assert::IsFalse(attributed.IsAttribute("Hi")); Assert::IsTrue(attributed[Attributed::sAttributedThisKey] == &attributed); Assert::AreEqual(1U, attributed[Attributed::sAttributedThisKey].Size()); } TEST_METHOD(AttributedDestructor) { std::string stringValue = "Howdy", nextStringValue = "Hi", thirdStringValue = "Hello"; AttributedFoo attributed; attributed.AppendAuxiliaryAttribute(stringValue) = stringValue; attributed.AppendAuxiliaryAttribute(nextStringValue) = nextStringValue; attributed.AppendAuxiliaryAttribute(thirdStringValue) = thirdStringValue; } TEST_METHOD(AttributedCopyConstructor) { std::string stringValue = "Howdy", nextStringValue = "Hi", thirdStringValue = "Hello"; AttributedFoo attributed; attributed.AppendAuxiliaryAttribute(stringValue) = stringValue; attributed.AppendAuxiliaryAttribute(nextStringValue) = nextStringValue; attributed.AppendAuxiliaryAttribute(thirdStringValue) = thirdStringValue; AttributedFoo otherAttributed(attributed); Assert::IsTrue(attributed == otherAttributed); Assert::IsTrue(otherAttributed.IsAuxiliaryAttribute(stringValue)); Assert::IsTrue(otherAttributed.IsAuxiliaryAttribute(nextStringValue)); Assert::IsTrue(otherAttributed.IsAuxiliaryAttribute(thirdStringValue)); Assert::IsTrue(otherAttributed[Attributed::sAttributedThisKey] == &otherAttributed); } TEST_METHOD(AttributedAssignmentOperator) { std::string stringValue = "Howdy", nextStringValue = "Hi", thirdStringValue = "Hello"; AttributedFoo attributed, otherAttributed; attributed.AppendAuxiliaryAttribute(stringValue) = stringValue; attributed.AppendAuxiliaryAttribute(nextStringValue) = nextStringValue; otherAttributed = attributed; Assert::IsTrue(attributed == otherAttributed); Assert::IsTrue(otherAttributed.IsAuxiliaryAttribute(stringValue)); Assert::IsTrue(otherAttributed.IsAuxiliaryAttribute(nextStringValue)); Assert::IsTrue(otherAttributed[Attributed::sAttributedThisKey] == &otherAttributed); attributed.AppendAuxiliaryAttribute(thirdStringValue) = thirdStringValue; otherAttributed = attributed; Assert::IsTrue(attributed == otherAttributed); Assert::IsTrue(otherAttributed.IsAuxiliaryAttribute(stringValue)); Assert::IsTrue(otherAttributed.IsAuxiliaryAttribute(nextStringValue)); Assert::IsTrue(otherAttributed.IsAuxiliaryAttribute(thirdStringValue)); Assert::IsTrue(otherAttributed[Attributed::sAttributedThisKey] == &otherAttributed); } TEST_METHOD(AttributedMoveConstructor) { std::string stringValue = "Howdy", nextStringValue = "Hi", thirdStringValue = "Hello"; AttributedFoo attributed; attributed.AppendAuxiliaryAttribute(stringValue) = stringValue; attributed.AppendAuxiliaryAttribute(nextStringValue) = nextStringValue; attributed.AppendAuxiliaryAttribute(thirdStringValue) = thirdStringValue; AttributedFoo otherAttributed = std::move(attributed); Assert::IsTrue(otherAttributed.IsAuxiliaryAttribute(stringValue)); Assert::IsTrue(otherAttributed.IsAuxiliaryAttribute(nextStringValue)); Assert::IsTrue(otherAttributed.IsAuxiliaryAttribute(thirdStringValue)); Assert::IsTrue(otherAttributed[Attributed::sAttributedThisKey] == &otherAttributed); } TEST_METHOD(AttributedMoveAssignmentOperator) { std::string stringValue = "Howdy", nextStringValue = "Hi", thirdStringValue = "Hello"; AttributedFoo attributed, otherAttributed; attributed.AppendAuxiliaryAttribute(stringValue) = stringValue; attributed.AppendAuxiliaryAttribute(nextStringValue) = nextStringValue; attributed.AppendAuxiliaryAttribute(thirdStringValue) = thirdStringValue; otherAttributed = std::move(attributed); Assert::IsTrue(otherAttributed.IsAuxiliaryAttribute(stringValue)); Assert::IsTrue(otherAttributed.IsAuxiliaryAttribute(nextStringValue)); Assert::IsTrue(otherAttributed.IsAuxiliaryAttribute(thirdStringValue)); Assert::IsTrue(otherAttributed[Attributed::sAttributedThisKey] == &otherAttributed); } TEST_METHOD(AttributedCopy) { std::string stringValue = "Howdy", nextStringValue = "Hi", thirdStringValue = "Hello", unknownStringValue = "Unknown"; AttributedFoo attributed, childOne, childTwo, childThree; attributed.Adopt(childOne, stringValue); attributed.Adopt(childTwo, nextStringValue); attributed.Adopt(childThree, thirdStringValue); Scope* copy = attributed.Copy(); Assert::IsTrue(*copy == attributed); Assert::IsTrue(copy->Find(stringValue)->Get<Scope&>().Is(AttributedFoo::TypeIdClass())); Assert::IsTrue(copy->Find(nextStringValue)->Get<Scope&>().Is(AttributedFoo::TypeIdClass())); Assert::IsTrue(copy->Find(thirdStringValue)->Get<Scope&>().Is(AttributedFoo::TypeIdClass())); delete(copy); } TEST_METHOD(AttributedEqualityOperator) { std::string stringValue = "Howdy", nextStringValue = "Hi", thirdStringValue = "Hello"; AttributedFoo attributed, otherAttributed; attributed.AppendAuxiliaryAttribute(stringValue) = stringValue; attributed.AppendAuxiliaryAttribute(nextStringValue) = nextStringValue; otherAttributed = attributed; Assert::IsTrue(attributed == otherAttributed); } TEST_METHOD(AttributedNotEqualOperator) { std::string stringValue = "Howdy", nextStringValue = "Hi", thirdStringValue = "Hello"; AttributedFoo attributed, otherAttributed; attributed.AppendAuxiliaryAttribute(stringValue) = stringValue; attributed.AppendAuxiliaryAttribute(nextStringValue) = nextStringValue; otherAttributed = attributed; Assert::IsFalse(attributed != otherAttributed); } TEST_METHOD(AttributedEquals) { std::string stringValue = "Howdy", nextStringValue = "Hi", thirdStringValue = "Hello"; AttributedFoo attributed, otherAttributed; attributed.AppendAuxiliaryAttribute(stringValue) = stringValue; attributed.AppendAuxiliaryAttribute(nextStringValue) = nextStringValue; otherAttributed = attributed; Assert::IsTrue(attributed.Equals(&otherAttributed)); Assert::IsFalse(attributed.Equals(nullptr)); } TEST_METHOD(AttributedFooInitializeSignatures) { AttributedFoo attributed; Assert::IsTrue(attributed.IsPrescribedAttribute("Int")); Assert::IsTrue(attributed.IsPrescribedAttribute("Float")); Assert::IsTrue(attributed.IsPrescribedAttribute("Vector")); Assert::IsTrue(attributed.IsPrescribedAttribute("Matrix")); Assert::IsTrue(attributed.IsPrescribedAttribute("String")); Assert::IsTrue(attributed.IsPrescribedAttribute("ExternalInt")); Assert::IsTrue(attributed.IsPrescribedAttribute("ExternalFloat")); Assert::IsTrue(attributed.IsPrescribedAttribute("ExternalVector")); Assert::IsTrue(attributed.IsPrescribedAttribute("ExternalMatrix")); Assert::IsTrue(attributed.IsPrescribedAttribute("ExternalString")); Assert::IsTrue(attributed.IsPrescribedAttribute("ExternalIntArray")); Assert::IsTrue(attributed.IsPrescribedAttribute("ExternalFloatArray")); Assert::IsTrue(attributed.IsPrescribedAttribute("ExternalVectorArray")); Assert::IsTrue(attributed.IsPrescribedAttribute("ExternalMatrixArray")); Assert::IsTrue(attributed.IsPrescribedAttribute("ExternalStringArray")); } TEST_METHOD(AttributedIsPrescribedAttribute) { std::string stringValue = "Howdy", nextStringValue = "Hi", thirdStringValue = "Hello"; AttributedFoo attributed; attributed.AppendAuxiliaryAttribute(stringValue) = stringValue; attributed.AppendAuxiliaryAttribute(nextStringValue) = nextStringValue; attributed.AppendAuxiliaryAttribute(thirdStringValue) = thirdStringValue; Assert::IsTrue(attributed.IsPrescribedAttribute(Attributed::sAttributedThisKey)); Assert::IsFalse(attributed.IsPrescribedAttribute(stringValue)); Assert::IsFalse(attributed.IsPrescribedAttribute(nextStringValue)); Assert::IsFalse(attributed.IsPrescribedAttribute(thirdStringValue)); } TEST_METHOD(AttributedIsAuxiliaryAttribute) { std::string stringValue = "Howdy", nextStringValue = "Hi", thirdStringValue = "Hello"; AttributedFoo attributed; attributed.AppendAuxiliaryAttribute(stringValue) = stringValue; attributed.AppendAuxiliaryAttribute(nextStringValue) = nextStringValue; attributed.AppendAuxiliaryAttribute(thirdStringValue) = thirdStringValue; Assert::IsFalse(attributed.IsAuxiliaryAttribute(Attributed::sAttributedThisKey)); Assert::IsTrue(attributed.IsAuxiliaryAttribute(stringValue)); Assert::IsTrue(attributed.IsAuxiliaryAttribute(nextStringValue)); Assert::IsTrue(attributed.IsAuxiliaryAttribute(thirdStringValue)); } TEST_METHOD(AttributedIsAttribute) { std::string stringValue = "Howdy", nextStringValue = "Hi", thirdStringValue = "Hello"; AttributedFoo attributed; attributed.AppendAuxiliaryAttribute(stringValue) = stringValue; attributed.AppendAuxiliaryAttribute(nextStringValue) = nextStringValue; Assert::IsTrue(attributed.IsAttribute(Attributed::sAttributedThisKey)); Assert::IsTrue(attributed.IsAttribute(stringValue)); Assert::IsTrue(attributed.IsAttribute(nextStringValue)); Assert::IsFalse(attributed.IsAttribute(thirdStringValue)); } TEST_METHOD(AttributedAppendAuxiliaryAttribute) { std::string stringValue = "Howdy", nextStringValue = "Hi", thirdStringValue = "Hello"; AttributedFoo attributed; attributed.AppendAuxiliaryAttribute(stringValue) = stringValue; attributed.AppendAuxiliaryAttribute(nextStringValue) = nextStringValue; attributed.AppendAuxiliaryAttribute(thirdStringValue) = thirdStringValue; auto AppendAuxiliaryAttributedPointer = [&attributed] { attributed.AppendAuxiliaryAttribute(Attributed::sAttributedThisKey); }; Assert::ExpectException<std::exception>(AppendAuxiliaryAttributedPointer); Assert::IsTrue(attributed.IsAttribute(stringValue)); Assert::IsTrue(attributed.IsAttribute(nextStringValue)); Assert::IsTrue(attributed.IsAttribute(thirdStringValue)); Assert::IsTrue(attributed.IsAuxiliaryAttribute(stringValue)); Assert::IsTrue(attributed.IsAuxiliaryAttribute(nextStringValue)); Assert::IsTrue(attributed.IsAuxiliaryAttribute(thirdStringValue)); } TEST_METHOD(AttributedCopyAuxiliaryAttributesInto) { std::string stringValue = "Howdy", nextStringValue = "Hi", thirdStringValue = "Hello"; AttributedFoo attributed, otherAttributed, thirdAttributed; attributed.AppendAuxiliaryAttribute(stringValue) = stringValue; attributed.AppendAuxiliaryAttribute(nextStringValue) = nextStringValue; attributed.CopyAuxiliaryAttributesInto(otherAttributed); Assert::IsTrue(otherAttributed.IsAuxiliaryAttribute(stringValue)); Assert::IsTrue(otherAttributed.IsAuxiliaryAttribute(nextStringValue)); Assert::IsFalse(otherAttributed.IsAuxiliaryAttribute(thirdStringValue)); attributed.AppendAuxiliaryAttribute(thirdStringValue) = thirdStringValue; attributed.CopyAuxiliaryAttributesInto(thirdAttributed); Assert::IsTrue(thirdAttributed.IsAuxiliaryAttribute(stringValue)); Assert::IsTrue(thirdAttributed.IsAuxiliaryAttribute(nextStringValue)); Assert::IsTrue(thirdAttributed.IsAuxiliaryAttribute(thirdStringValue)); } TEST_METHOD(AttributedRTTIMethods) { AttributedFoo attributed; Assert::IsTrue(attributed.Is(AttributedFoo::TypeIdClass())); Assert::IsTrue(attributed.Is(Attributed::TypeIdClass())); Assert::IsTrue(attributed.Is(AttributedFoo::TypeName())); Assert::IsTrue(attributed.Is(Attributed::TypeName())); Assert::AreEqual(AttributedFoo::TypeIdClass(), attributed.TypeIdInstance()); Assert::AreNotEqual(Attributed::TypeIdClass(), attributed.TypeIdInstance()); Assert::AreEqual(AttributedFoo::TypeName(), attributed.TypeName()); Assert::AreNotEqual(Attributed::TypeName(), attributed.TypeName()); RTTI* asRTTI = &attributed; Assert::IsFalse(nullptr == asRTTI->QueryInterface(AttributedFoo::TypeIdClass())); Assert::IsTrue(attributed == *(asRTTI->As<AttributedFoo>())); Assert::AreEqual(asRTTI->As<AttributedFoo>()->ToString(), attributed.ToString()); } private: static _CrtMemState sStartMemState; }; _CrtMemState AttributedTest::sStartMemState; }
true
5a9a6e34ad50b51dd6c40b3c9b9aaa0404cbc85e
C++
ztk4/NJIT
/cs356/p2/src/message_flow.cpp
UTF-8
7,499
2.84375
3
[]
no_license
#include "message_flow.h" #include <thread> #include <utility> using namespace std; using util::ThreadPool; using util::Timeout; using util::TimeoutFactory; namespace router { namespace { // RepeatedSend object for repeatedly sending on timeout if needed. class RepeatedSend { public: RepeatedSend(uint16_t router_id, const Message &m, unique_ptr<MessageIo> &&message_io, unique_ptr<Timeout> &&timeout) : router_id_(router_id), m_(m), message_io_(move(message_io)), timeout_(move(timeout)) { Send(); } // Disallow copy, move, and all assignment. RepeatedSend(const RepeatedSend &) = delete; RepeatedSend(RepeatedSend &&) = delete; RepeatedSend &operator=(const RepeatedSend &) = delete; RepeatedSend &operator=(RepeatedSend &&) = delete; bool IsActive() const { return static_cast<bool>(timeout_); } void Send() { message_io_->SendTo(m_, router_id_); if (timeout_) { timeout_->Start([this]() { Send(); }); } } private: uint16_t router_id_; Message m_; unique_ptr<MessageIo> message_io_; unique_ptr<Timeout> timeout_; }; // Keeps track of last used identifier atomic<uint16_t> last_used_id(0); // Maps message ids to RepeatedSend objects relevant to that id. map<uint16_t, RepeatedSend> sending; // Mutex for guarding the timeouts map. mutex sending_mutex; // GUARDS sending. // Internal implementation of send to. Will send m to router_id using // message_io at least once. If timeout is non-null, a RepeatedSend object will // be put into the sending map waiting for a response. This will repeatedly // send requests on timeout and should be deleted with the corresponding // response is received. void InternalSendTo(uint16_t router_id, const Message &m, unique_ptr<MessageIo> &&message_io, unique_ptr<Timeout> &&timeout = move(unique_ptr<Timeout>())) { lock_guard<mutex> sending_mutex_lock(sending_mutex); sending.erase(m.SourceId()); // Erase existing pair if needed. // Build RepeatedSend in map (nothing should be moved ever). if (timeout) { // Place in map to send repeatedly until cleaned. sending.emplace(piecewise_construct, forward_as_tuple(m.SourceId()), forward_as_tuple(router_id, m, move(message_io), move(timeout))); } else { // If not sending repeatedly, construct once on stack then destruct. RepeatedSend(router_id, m, move(message_io), move(timeout)); } } } // anonymous namespace // Static Storage function<void(uint16_t, map<uint16_t, int16_t>)> Server::receipt_cb_; mutex Server::receipt_cb_mutex_; function<map<uint16_t, int16_t>(void)> Server::request_cb_; mutex Server::request_cb_mutex_; // Resets above sending map. void ResetAll() { lock_guard<mutex> sending_mutex_lock(sending_mutex); sending.clear(); } // Client Implementation Client::Client(MessageIoFactory *message_io_factory, TimeoutFactory *timeout_factory, int max_threads) : message_io_factory_(message_io_factory), timeout_factory_(timeout_factory), pool_(max_threads) {} void Client::SendGetTableRequest(uint16_t router_id) { Message m(0, Message::REQUEST_TABLE, ++last_used_id); InternalSendTo(router_id, m, move(unique_ptr<MessageIo>(message_io_factory_->MakeMessageIo())), move(unique_ptr<Timeout>(timeout_factory_->MakeTimeout()))); } void Client::PushTableTo(uint16_t router_id, const map<uint16_t, int16_t> &table) { Message m(0, Message::PUSH_TABLE, ++last_used_id, table); InternalSendTo(router_id, m, move(unique_ptr<MessageIo>(message_io_factory_->MakeMessageIo())), move(unique_ptr<Timeout>(timeout_factory_->MakeTimeout()))); } void Client::BroadcastTable(set<uint16_t> neighbor_ids, const map<uint16_t, int16_t> &table) { // Blocks on completion. pool_.Map([this, table](uint16_t router_id) { PushTableTo(router_id, table); }, neighbor_ids.begin(), neighbor_ids.end()); } // Server Implementation Server::Server(MessageIoFactory *message_io_factory, TimeoutFactory *timeout_factory, int max_threads) : message_io_factory_(message_io_factory), timeout_factory_(timeout_factory), pool_(max_threads), active_(true) { // Dispatch max_threads for server, non-blocking. pool_.ExecuteAsync([this]() { // Thread claims ownership of transferred message_io unique_ptr<MessageIo> message_io(message_io_factory_->MakeMessageIo()); // While Server is active while (active_) { uint16_t router_id; bool status; Message m = message_io->ReceiveFrom(router_id, status); if (status) { switch (m.GetType()) { case Message::REQUEST_TABLE: GetRequestReceived(router_id, m); break; case Message::PUSH_TABLE: PushTableReceived(router_id, m); break; case Message::TABLE_RESPONSE: TableResponseReceived(router_id, m); break; case Message::ACK: AckReceived(router_id, m); break; case Message::UNKNOWN: break; } } this_thread::yield(); } }, max_threads); } Server::~Server() { // Notify threads the server is going down. active_ = false; // Wait on pool before invalidating captured pointer. pool_.JoinAll(); } void Server::OnTableReceipt( const function<void(uint16_t, map<uint16_t, int16_t>)> &callback) { lock_guard<mutex> receipt_cb_mutex_lock(receipt_cb_mutex_); receipt_cb_ = callback; } void Server::OnTableRequest( const function<map<uint16_t, int16_t>(void)> &callback) { lock_guard<mutex> request_cb_mutex_lock(request_cb_mutex_); request_cb_ = callback; } void Server::GetRequestReceived(uint16_t router_id, const Message &m) { map<uint16_t, int16_t> routing_table; { lock_guard<mutex> request_cb_mutex_lock(request_cb_mutex_); if (request_cb_) routing_table = request_cb_(); } Message resp(m.SourceId(), Message::TABLE_RESPONSE, ++last_used_id, routing_table); InternalSendTo(router_id, resp, move(unique_ptr<MessageIo>(message_io_factory_->MakeMessageIo())), move(unique_ptr<Timeout>(timeout_factory_->MakeTimeout()))); } void Server::PushTableReceived(uint16_t router_id, const Message &m) { Message resp(m.SourceId(), Message::ACK, ++last_used_id); InternalSendTo(router_id, resp, move(unique_ptr<MessageIo>(message_io_factory_->MakeMessageIo()))); { lock_guard<mutex> receipt_cb_mutex_lock(receipt_cb_mutex_); if (receipt_cb_) receipt_cb_(router_id, m.Table()); } } void Server::TableResponseReceived(uint16_t router_id, const Message &m) { { // Check in sending map for previous message lock_guard<mutex> sending_mutex_lock(sending_mutex); auto it = sending.find(m.DestinationId()); if (it != sending.end()) sending.erase(it); // Remove listing (mark receipt and stop sending). } Message resp(m.SourceId(), Message::ACK, m.DestinationId()); InternalSendTo(router_id, resp, move(unique_ptr<MessageIo>(message_io_factory_->MakeMessageIo()))); { lock_guard<mutex> receipt_cb_mutex_lock(receipt_cb_mutex_); if (receipt_cb_) receipt_cb_(router_id, m.Table()); } } void Server::AckReceived(uint16_t, const Message &m) { // Remove previous message from sending map if there lock_guard<mutex> sending_mutex_lock(sending_mutex); sending.erase(m.DestinationId()); } } // namespace router
true
bd68180a920625e9072f93566831b5be6b2688ef
C++
Laskina/3laba12
/file.h
WINDOWS-1251
1,827
2.765625
3
[]
no_license
#pragma once #include <string> #include <vector> #include <algorithm> #include <iterator> #include <fstream> #include <iostream> using namespace std; #define SECTOR 4; typedef struct date_time { int day; int month; int year; int hour; int mins; int sec; } date_time; enum attribute {open, read, hidden, systems}; class file { private: string directory; // string filename; // string extention; // date_time date_creation; attribute atr; // bool is_deleted; int num_sectors; public: string getDirectory(); void setDirectory(string d); string getFilename(); void setFilename(string f); string getExtention(); void setExtention(string e); date_time getDateTime(); void setDateTime(date_time d); string getAttributeAsStr(); attribute getAttribute(); void setAttribute(int a); void setAttribute(attribute a); bool getDeleted(); string getDeletedAsStr(); void setDeleted(bool i); int getNumSectors(); void setNumSectors(int n); void Input(); void Change(bool admin); void Save_to_binfile(ofstream &fout); bool Load_from_binfile(ifstream &fin); file(); file(string d, string f, string e, date_time dt, int a, int n); ~file(); }; void printNum(int num, int N); void printStr(string str, int N); void print_file(bool admin, file f); void print_header(); bool Load_File(ifstream &fin, file &f); void Save_File(ofstream &fout, file &f); // bool compare_direct(file &a,file &b); bool compare_name(file &a,file &b); bool compare_date(file &a,file &b); bool compare_del(file &a, file &b); int InputNum(string str, int min, int max); string InputStr(string str);
true
3f78fcd90f5d50f12a02554f131b0482e4e9bb4d
C++
joshkimmel16/scalable-clustering
/include/reporter.h
UTF-8
947
2.71875
3
[]
no_license
#ifndef REPORTER_H #define REPORTER_H #include <string> #include <iomanip> #include <vector> #include <algorithm> #include "clustergraph.h" class Reporter { public: Reporter(Config *c, ClusterGraph * g) { config = c; graph = g; threshold = c->GetThreshold(); } //used to compress,generate, and write report void CompressAndGenerateReport(std::vector<std::string> colNames); //only compresses cluster graph void CompressClusterGraph(); //sets reportedClusters and returns vector of clusters to be in report //must be called after CompressClusterGraph() std::vector<Cluster *> * GenerateReport(); private: Config * config; ClusterGraph * graph; double threshold; std::vector<Cluster *> reportedClusters; bool CompressClusterGraph(Cluster * cluster); void GenerateReport(Cluster* cluster); void WriteReport(std::vector<std::string> colNames); }; #endif
true
ec1718dda0b5b02d8869340c7788645cff497600
C++
epaqu/bio_data_structure
/HW2.cpp
UTF-8
5,108
3.625
4
[]
no_license
// homework2.cpp : Defines the entry point for the console application. // #include <iostream> #include <string> using namespace std; int size = 0; int firstOrSecond = 1; int **getpoly() { int **poly; int **temp; int term = 1; int order, coefficient; cout << "If you want to stop, please enter -1 for order."; if (firstOrSecond == 1) cout << "\nEnter the first polynomial."; else if (firstOrSecond == 2) cout << "\nNow enter your second polynomial."; cout << "\nPlease enter the order of Term #" << term << ": "; cin >> order; poly = new int*[2]; temp = new int*[2]; if (order != -1) { for (int i = 0; i < term; i++) { poly[0] = new int[i]; poly[1] = new int[i]; temp[0] = new int[i]; temp[1] = new int[i]; } cout << "\nPlease enter the coefficient of Term #" << term << ": "; cin >> coefficient; poly[0][0] = coefficient; poly[1][0] = order; term++; while(true) { cout << "\nPlease enter the order of Term #" << term << ": "; cin >> order; if (order == -1) break; cout << "\nPlease enter the coefficient of Term #" << term << ": "; cin >> coefficient; for (int i = 0; i < term-1; i++) { temp[0][i] = poly[0][i]; temp[1][i] = poly[1][i]; } for (int i = 0; i < term; i++) { poly[0] = new int[i]; poly[1] = new int[i]; } for (int i = 0; i < term-1; i++) { poly[0][i] = temp[0][i]; poly[1][i] = temp[1][i]; } poly[0][term-1] = coefficient; poly[1][term-1] = order; for (int i = 0; i < term; i++) { temp[0] = new int[i]; temp[1] = new int[i]; } term++; } } size = term; return poly; } void printpoly(int term, int **poly) { if (firstOrSecond == 1) cout << "Your first polynomial is: "; else if (firstOrSecond == 2) cout << "Your second polynomial is: "; else cout << "The multiplication of the two polynomials are: "; if (term == 1) cout << "" << endl; else { for (int i = 0; i < term-2; i++) { if (poly[0][i] != 1 && poly[0][i] != 0) { if (poly[1][i] != 1 && poly[1][i] != 0) cout << poly[0][i] << "x^" << poly[1][i] << " + "; else if (poly[1][i] == 1) cout << poly[0][i] << "x" << " + "; else if (poly[1][i] == 0) cout << poly[0][i] << " + "; } else if (poly[0][i] == 1) { if (poly[1][i] != 1 && poly[1][i] != 0) cout << "x^" << poly[1][i] << " + "; else if (poly[1][i] == 1) cout << "x" << " + "; else if (poly[1][i] == 0) cout << "1 + "; } } if (poly[0][term-2] != 1) { if (poly[1][term-2] != 1 && poly[1][term-2] != 0) cout << poly[0][term-2] << "x^" << poly[1][term-2]; else if (poly[1][term-2] == 1) cout << poly[0][term-2] << "x"; else if (poly[1][term-2] == 0) cout << poly[0][term-2]; } else if (poly[1][term-2] != 1 && poly[1][term-2] != 0) cout << "x^" << poly[1][term-2]; else if (poly[1][term-2] == 1) cout << "x"; else cout << poly[0][term-2]; cout << endl; cout << endl; cout << endl; } } int **sortDecreasing(int **poly, int size) { int largest, id; for (int i = 0; i< size; i++) { largest = poly[1][i]; id = poly[0][i]; for (int j = i; j < size; j++) { if (largest < poly[1][j]) { largest = poly[1][j]; poly[1][j] = poly[1][i]; poly[1][i] = largest; id = poly[0][j]; poly[0][j] = poly[0][i]; poly[0][i] = id; } } } return poly; } int main() { int **poly1 = getpoly(); int size1 = size; printpoly(size1, sortDecreasing(poly1, size1-1)); firstOrSecond++; int **poly2 = getpoly(); int size2 = size; printpoly(size2, sortDecreasing(poly2, size2-1)); int length = (size1-1) * (size2-1); firstOrSecond++; //done getting the polynomials int **multiplied; multiplied = new int*[2]; multiplied[0] = new int[length]; multiplied[1] = new int[length]; int index = 0; for (int i = 0; i < size1-1; i++) { for (int j = 0; j < size2-1; j++) { multiplied[0][index] = poly1[0][i] * poly2[0][j]; multiplied[1][index] = poly1[1][i] + poly2[1][j]; index++; } } //done multiplying int ind=0, temp; for (int i =1; i < length; i++) { temp = multiplied[1][ind]; for (int j =i; j < length; j++) if (multiplied[1][j] == temp) { multiplied[0][ind] += multiplied[0][j]; multiplied[0][j] = 0; multiplied[1][j] = 0; } ind++; } //done simplifying int unnecessary = 0; for (int j = 0; j < length; j++) if (multiplied[0][j] == 0) unnecessary++; sortDecreasing(multiplied, length); int new_length = length - unnecessary; int **result; result = new int*[2]; result[0] = new int[new_length]; result[1] = new int[new_length]; int index_new = 0; for (int i = 0; i < length; i++) { if (multiplied[0][i] != 0) { result[0][index_new] = multiplied[0][i]; result[1][index_new] = multiplied[1][i]; index_new++; } } printpoly(new_length+1, result); }
true