blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
e8ad35ac9befd37afc2bb135844874e0db80fb8a
54cacc105d6bacdcfc37b10d57016bdd67067383
/trunk/source/level/physics/ForceGeneratorRegistry.h
97b9d01db333aaa0a6515803715ac585bf185d98
[]
no_license
galek/hesperus
4eb10e05945c6134901cc677c991b74ce6c8ac1e
dabe7ce1bb65ac5aaad144933d0b395556c1adc4
refs/heads/master
2020-12-31T05:40:04.121180
2009-12-06T17:38:49
2009-12-06T17:38:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,096
h
/*** * hesperus: ForceGeneratorRegistry.h * Copyright Stuart Golodetz, 2009. All rights reserved. ***/ #ifndef H_HESP_FORCEGENERATORREGISTRY #define H_HESP_FORCEGENERATORREGISTRY #include <map> #include <string> #include <boost/shared_ptr.hpp> using boost::shared_ptr; namespace hesp { //#################### FORWARD DECLARATIONS #################### typedef shared_ptr<const class ForceGenerator> ForceGenerator_CPtr; class ForceGeneratorRegistry { //#################### TYPEDEFS #################### public: typedef std::map<std::string,ForceGenerator_CPtr> ForceGenerators; //#################### PRIVATE VARIABLES #################### private: std::map<int,ForceGenerators> m_generators; //#################### PUBLIC METHODS #################### public: void deregister_id(int id); const ForceGenerators& generators(int id) const; void register_id(int id); void remove_generator(int id, const std::string& forceName); void set_generator(int id, const std::string& forceName, const ForceGenerator_CPtr& generator); }; } #endif
[ "sgolodetz@gxstudios.net" ]
sgolodetz@gxstudios.net
e17fc4a194a5e03b818ec0bec169498432d200c4
9f5289c0bb0d3d7a91d1003a4ae7564576cb169e
/Source/BansheeEngine/Include/BsScriptManager.h
575d3198f774ee28a37f6c5bdd82310461ecca1b
[]
no_license
linuxaged/BansheeEngine
59fa82828ba0e38841ac280ea1878c9f1e9bf9bd
12cb86711cc98847709f702e11a577cc7c2f7913
refs/heads/master
2021-01-11T00:04:23.661733
2016-10-10T13:18:44
2016-10-10T13:18:44
70,758,880
3
3
null
2016-10-13T01:57:56
2016-10-13T01:57:55
null
UTF-8
C++
false
false
1,711
h
//********************************** Banshee Engine (www.banshee3d.com) **************************************************// //**************** Copyright (c) 2016 Marko Pintera (marko.pintera@gmail.com). All rights reserved. **********************// #pragma once #include "BsPrerequisites.h" #include "BsModule.h" namespace BansheeEngine { /** @addtogroup Script-Internal * @{ */ /** Abstraction that handles a specific set of script libraries. */ class BS_EXPORT ScriptLibrary { public: virtual ~ScriptLibrary() { } /** Called when the script system is being activated. */ virtual void initialize() = 0; /** Called when the script libraries should be reloaded (for example when they are recompiled). */ virtual void reload() = 0; /** Called when the script system is being destroyed. */ virtual void destroy() = 0; }; /** Handles initialization of a scripting system. */ class BS_EXPORT ScriptManager : public Module<ScriptManager> { public: ScriptManager() { } ~ScriptManager() { } /** Initializes the currently active script library loading the scripts contained within. */ void initialize(); /** * Reloads any scripts in the currently active library. Should be called after some change to the scripts was made * (for example project was changed, or scripts were recompiled). */ void reload(); /** Sets the active script library that controls what kind and which scripts are loaded. */ void _setScriptLibrary(const SPtr<ScriptLibrary>& library); private: /** @copydoc ScriptManager::onShutDown */ void onShutDown() override; SPtr<ScriptLibrary> mScriptLibrary; }; /** @} */ }
[ "bearishsun@gmail.com" ]
bearishsun@gmail.com
c910844a0795806662c5853bd31b9164242f76d8
76bb2f1b416d78c2b4c951f071657b93e8f915c1
/sdl/exparse/expsyn.h
5142899c70acd9c5d88720f417dd93f06270c35c
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
pcxod/olex2
2f48c06da586fb47d308defe9915bf63be5c8f4d
17d2718d09ad61ad961b98e966d981bb50663e3e
refs/heads/master
2023-08-11T20:01:31.660209
2023-07-21T10:55:35
2023-07-21T10:55:35
219,048,584
9
0
null
null
null
null
UTF-8
C++
false
false
1,323
h
/****************************************************************************** * Copyright (c) 2004-2011 O. Dolomanov, OlexSys * * * * This file is part of the OlexSys Development Framework. * * * * This source file is distributed under the terms of the licence located in * * the root folder. * ******************************************************************************/ #ifndef __olx_sdl_exparse_syntax_H #define __olx_sdl_exparse_syntax_H #include "funcwrap.h" BeginEsdlNamespace() namespace exparse { struct iloop { }; struct exe_block { TPtrList<IEvaluable> lines; }; struct conditional : public exe_block { IEvaluable *condition; }; struct function : public exe_code { }; struct syn_if : public conditional { exe_block else_body; TPtrList<conditional> elifs; }; struct syn_for : public conditional { IEvaluable *pre, *post; }; struct syn_while : public conditional { IEvaluable *condition; }; }; // namespace exparse EndEsdlNamespace() #endif
[ "pcxod@273b6b03-9602-4203-8103-cbef60d4472e" ]
pcxod@273b6b03-9602-4203-8103-cbef60d4472e
4e76d1ca2484fe6b6bc805583eb14dec50cc7ba7
8a2f3bb64e8feb3ccff65eb3edf86a47d62b0b10
/FancyTable/ccustomheaderview.h
7de8bf1bd918bc15d2e4b70246864a155cf5bfe0
[]
no_license
GLDsuh-a/qt-1
010489a59a26a62747eaadddf37e4b0d80546460
0a642fa56f71d94e7f815305a806173c8e586ddb
refs/heads/master
2021-01-17T06:59:12.293528
2015-08-28T03:08:13
2015-08-28T03:08:22
41,582,969
7
2
null
2015-08-29T06:18:11
2015-08-29T06:18:11
null
UTF-8
C++
false
false
1,000
h
#ifndef CCUSTOMHEADERVIEW_H #define CCUSTOMHEADERVIEW_H #include <QHeaderView> #include "crect.h" class cCustomHeaderView : public QHeaderView { Q_OBJECT public: enum HeaderDataModelRoles { HorizontalHeaderDataRole = Qt::UserRole, VerticalHeaderDataRole = Qt::UserRole + 1 }; explicit cCustomHeaderView(QWidget *parent = 0); QModelIndex indexAt(const QPoint &pos) const; int sectionSizes(); int sectionSizes(int lIndex, int sectionCount); void setHoverIndex(const QPersistentModelIndex &index); protected: QSize sectionSizeFromContents(int logicalIndex) const; void paintEvent(QPaintEvent *e); bool viewportEvent(QEvent *event); void mouseMoveEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *e); bool event(QEvent *e); private: QList<cRect> m_RectList; QModelIndex mHover; public slots: void onSectionResized(int logicalIndex, int oldSize, int newSize); }; #endif // CCUSTOMHEADERVIEW_H
[ "ltz121320@163.com" ]
ltz121320@163.com
e1bafd9b3cca6024ddcebc2a214228ad49777f17
30d9b03693849c4929975669960ce967b81b15a6
/Source/SequenoeEditorExtensions/Private/PropertyTrackEditors/NamePropertyTrackEditor.h
83afa8b21e7e3f66dccfb7b86b6785ff3430562b
[ "MIT" ]
permissive
Pseudo-Game-Tech/SequenoeMoreExtensions
5fd5099d3a1457f3afaae8dfd93f2c4acb0aa301
05d4e810dd0a75b095909fcf4a4d5074e1929ac0
refs/heads/master
2022-03-01T03:52:21.828443
2019-10-25T07:49:35
2019-10-25T07:49:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,462
h
#pragma once #include "CoreMinimal.h" #include "Misc/Guid.h" #include "ISequencer.h" #include "ISequencerSection.h" #include "ISequencerTrackEditor.h" #include "PropertyTrackEditor.h" #include "PropertyTracks/MovieSceneNameTrack.h" #include "PropertyTracks/MovieSceneNameSection.h" /** * A property track editor for strings. */ class FNamePropertyTrackEditor : public FPropertyTrackEditor<UMovieSceneNameTrack> { public: /** * Constructor. * * @param InSequencer The sequencer instance to be used by this tool. */ FNamePropertyTrackEditor(TSharedRef<ISequencer> InSequencer) : FPropertyTrackEditor(InSequencer, GetAnimatedPropertyTypes()) { } /** * Retrieve a list of all property types that this track editor animates */ static TArray<FAnimatedPropertyKey, TInlineAllocator<1>> GetAnimatedPropertyTypes() { return TArray<FAnimatedPropertyKey, TInlineAllocator<1>>({ FAnimatedPropertyKey::FromPropertyTypeName(NAME_NameProperty) }); } /** * Creates an instance of this class (called by a sequencer). * * @param OwningSequencer The sequencer instance to be used by this tool * @return The new instance of this class */ static TSharedRef<ISequencerTrackEditor> CreateTrackEditor(TSharedRef<ISequencer> OwningSequencer); protected: //~ FPropertyTrackEditor interface virtual void GenerateKeysFromPropertyChanged(const FPropertyChangedParams& PropertyChangedParams, FGeneratedTrackKeys& OutGeneratedKeys) override; };
[ "672619410@qq.com" ]
672619410@qq.com
0d22acf2001d5c98b89889114bd72639c6c9f168
14c8b0ef6bf15f29bd5787c8136e0e382d74adea
/Cage2d/include/Cage2d/Manager.hpp
7e3fb4cd7966562ef03be86705ec4f65ff5a160f
[]
no_license
zerodarkzone/Cage2D
ff6d83518ffd859826c7f4ddeeb5bd66fe8d1e1e
ddb4b2b4c2bd7500bdbf420791dd483d3d3bf04d
refs/heads/master
2020-12-10T04:30:08.391378
2017-03-02T06:44:34
2017-03-02T06:44:34
83,633,973
0
0
null
null
null
null
UTF-8
C++
false
false
196
hpp
#pragma once namespace Cage2d { class Manager { public: virtual ~Manager( ) = 0; virtual void DrawAll( ) const = 0; virtual void UpdateAll( ) = 0; }; inline Manager::~Manager( ) {} }
[ "zerodarkzone@gmail.com" ]
zerodarkzone@gmail.com
77108b4a629e03d4ba09555c22330e290fb88d07
bd9c1a7c6ee0d4ce9bb2e86c6176b28e4c911067
/Ray Tracing Project/task6/ray.h
024cd4ed9f9b60024b589daca94a759904cd115c
[]
no_license
melihkurtaran/Computer_Graphics
0c4e694b411fa162fed32dcd15879473c0ff763c
36d991df993488b40f8fac0b96c96063b70d1bae
refs/heads/main
2023-02-20T01:43:23.708085
2021-01-24T10:25:55
2021-01-24T10:25:55
332,414,002
0
0
null
null
null
null
UTF-8
C++
false
false
651
h
// Created by Melih Kurtaran on 30/10/2020. // Copyright © 2020 melihkurtaran. All rights reserved. // #ifndef ray_h #define ray_h #include "vec3.h" class ray { public: ray() {} ray(const point3& origin, const vec3& direction, double time = 0.0) : orig(origin), dir(direction), tm(time) {} point3 origin() const { return orig; } vec3 direction() const { return dir; } double time() const { return tm; } point3 at(double t) const { return orig + t*dir; } public: point3 orig; vec3 dir; double tm; }; #endif /* ray_h */
[ "melihkurtaran@sabanciuniv.edu" ]
melihkurtaran@sabanciuniv.edu
5e37ec796390745eb1d19aceb1d45c576ce879be
7e0ec0e32282307dd5bf051602cc6c2ea268452c
/src/rads/chomp/include/chomp/homology/known.h
f1700d26d1b9c493f3e04541e9e93a630c995475
[]
no_license
caosuomo/rads
03a31936715da2a9131a73ae80304680c5c3db7e
71cab0d6f0711cfab67e8277e1e025b0fc2d8346
refs/heads/master
2021-01-20T10:18:58.222894
2018-05-24T02:18:58
2018-05-24T02:18:58
1,039,029
1
1
null
null
null
null
UTF-8
C++
false
false
3,967
h
/// @addtogroup homology /// @{ ///////////////////////////////////////////////////////////////////////////// /// /// @file known.h /// /// This file contains the definition of a tabulated set of configurations /// of full cubical neighborhood used for reducing full cubical sets /// in the homology computation procedures. /// /// @author Pawel Pilarczyk /// ///////////////////////////////////////////////////////////////////////////// // Copyright (C) 1997-2010 by Pawel Pilarczyk. // // This file is part of the Homology Library. This library is free software; // you can redistribute it and/or modify it under the terms of the GNU // General Public License as published by the Free Software Foundation; // either version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this software; see the file "license.txt". If not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, // MA 02111-1307, USA. // Started in January 2002. Last revision: June 2, 2007. #ifndef _CHOMP_HOMOLOGY_KNOWN_H_ #define _CHOMP_HOMOLOGY_KNOWN_H_ #include "chomp/system/config.h" #include "chomp/system/textfile.h" #include "chomp/struct/bitfield.h" namespace chomp { namespace homology { // -------------------------------------------------- // ------------------- BitFields -------------------- // -------------------------------------------------- /// This class defines a simple table of bit fields with very limited /// functionality that is used for storing the information /// on the verified combinations of cubes' neighbors. class BitFields { public: /// The default constructor. BitFields (); /// The destructor. ~BitFields (); /// Sets the limit for the number of kilobytes used for BitFields. /// The limit applied to dimension < 0 is copied to all the /// others and can be retrieved as the limit for dimension 0. /// The limit for dim. 0 is the default if not defined otherwise. void setkblimit (int limit = -1, int dim = -1); /// Returns the current limit for the given dimension. int getkblimit (int dim = 0) const; /// Returns the corresponding bit field set and allocates it if not /// used so far. If no bit field set is in use, returns 0. SetOfBitFields *operator [] (int dim); /// Forgets the given bit field set or all the sets. void forget (int dim = -1); private: /// The table of bit field sets for each dimension. SetOfBitFields **tab; /// The length of the currently allocated table. int len; /// The memory limit for each table (in kilobytes), -1 for none. int *maxkb; /// Extends the table to the given length if necessary. void extend (int n); /// Allocates the specific bit field set. void allocate (int dim); }; /* class BitFields */ // -------------------------------------------------- inline BitFields::BitFields () { tab = NULL; len = 0; maxkb = NULL; return; } /* BitFields::BitFields */ inline SetOfBitFields *BitFields::operator [] (int dim) { // make sure the dimension is positive if (dim <= 0) throw "Trying to get a bit field set of non-positive dim."; // extend the tables if necessary if (dim >= len) extend (dim + 1); // allocate the bit field set if necessary if (!tab [dim] && maxkb [dim]) allocate (dim); // return the pointer to the requested bit field set return tab [dim]; } /* BitFields::operator [] */ // -------------------------------------------------- /// The global table of BitFields which store the acyclicity information /// for reducing full cubical sets. extern BitFields knownbits; } // namespace homology } // namespace chomp #endif // _CHOMP_HOMOLOGY_KNOWN_H_ /// @}
[ "jberwald@gmail.com" ]
jberwald@gmail.com
c040f6c8ef8846adf1a28eaf401e6a553e6159bd
f28fab080d21139d72ab91dcb2537f15b9e40522
/jerq/src/jraw/dots.h
6f23cac6ba840f1424ae80871932d9f93ea9dccc
[]
no_license
Alhadis/Research-Unix-v8
20358db19a70108c9cdef93215ed7e225f9747d9
389623b76d5b6e195361f0705b1826b00ae14d19
refs/heads/master
2020-05-27T00:20:19.409031
2019-05-24T11:33:35
2019-05-24T11:33:35
188,419,943
9
0
null
null
null
null
UTF-8
C++
false
false
372
h
#ifndef DOT_H #define DOT_H #include "list.h" class Dots:public List { public: Dots(Point p) {P = Q = p; sel = 12; mod = DOTHIT; draw(&display,F_XOR);} Dots(Rectangle r) {R = r; sel = 15;} void put(FILE *f) {fprintf(f,"d %d %d %d %d\n",X,Y,U,V);} List *copy(); int down(Point); int selleck(Rectangle); void draw(Bitmap *, int); List *unsel(int, List *); }; #endif
[ "gardnerjohng@gmail.com" ]
gardnerjohng@gmail.com
600393fc84d533ac8927240c16f1f7544b3ea736
28125dc1d0090d864c3414472b0794d3939ff728
/rectanglecutting.cpp
896fd9957a43ac2ac77698bbec4baf71d6676202
[]
no_license
Wadshah/c-codeforces
d4baeac02ef26ef8ccf4e3add92ecd4094ace582
8ea16f66e64910a2076d48aea7b2e9c7892bd55e
refs/heads/main
2023-08-03T16:22:12.213406
2021-09-18T09:00:39
2021-09-18T09:00:39
407,808,949
0
0
null
null
null
null
UTF-8
C++
false
false
931
cpp
#include<bits/stdc++.h> #include<iostream> using namespace std; #define ll long long int #define inf 1e18 #define mod 1000000007 const int N=1e5+5; void file_i_o(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("inputf.in", "r", stdin); freopen("outputf.in", "w", stdout); #endif } int main(int argc ,char const *argv[]){ clock_t begin =clock(); file_i_o(); int a,b; cin>>a>>b; vector<vector<int>>dp(a+1,vector<int>(b+1,INT_MAX)); for(int i=0;i<=a;i++){ for(int j=0;j<=b;j++){ if(i==j) dp[i][j]=0; else{ for(int k=1;k<=i-1;k++){ dp[i][j]=min(dp[i][j],1+dp[k][j]+dp[i-k][j]); } for(int k=1;k<=j-1;k++){ dp[i][j]=min(dp[i][j],1+dp[i][k]+dp[i][j-k]); } } } } cout<<dp[a][b]; #ifndef ONLINE_JUDGE clock_t end =clock(); cout<<"\n\nExecuted In: "<<double(end - begin) / CLOCKS_PER_SEC*1000<<" ms"; #endif return 0; }
[ "wadshahg13139@gmail.com" ]
wadshahg13139@gmail.com
9d4b8f24ef5e207b18a6f926868c8247a4a349cd
c365d25ee2237b3c260198827b33b0253d43eaf4
/codeforces/699-a.cpp
6a453b380e8b64c24f5b6629fc47c6ab5bab4e80
[]
no_license
germanohn/competitive-programming
fb1249910ce951fe290e9a5be3876d3870ab8aa3
fab9dc0e2998dd395c1b9d6639f8c187cf637669
refs/heads/master
2021-06-12T08:17:52.907705
2021-03-17T19:06:19
2021-03-17T19:06:19
58,595,999
0
0
null
null
null
null
UTF-8
C++
false
false
750
cpp
#include <bits/stdc++.h> #define ff first #define ss second #define pb push_back #define mp make_pair #define debug(args...) fprintf (stderr, args) using namespace std; typedef long long ll; typedef pair<int, int> pii; // ATENCAO: cuidado com as variaveis dadas no exercicio, nao as reutilize const int MAX = 200005; int n; char dir[MAX]; int v[MAX]; int main () { scanf ("%d", &n); for (int i = 0; i < n; i++) scanf (" %c", &dir[i]); for (int i = 0; i < n; i++) scanf ("%d", &v[i]); int ans = INT_MAX; for (int i = 0; i < n-1; i++) { if (dir[i] == 'R' && dir[i+1] == 'L') ans = min (ans, (v[i+1]-v[i])/2); } if (ans == INT_MAX) printf ("-1\n"); else printf ("%d\n", ans); }
[ "germanohn@hotmail.com" ]
germanohn@hotmail.com
d45c590033f93d3d93ab4dcb6e4e8913c1bd9e15
fb9a4933b0d12ee01ff6fceee250957e9e9a3b8e
/Engine/Engine/cameraclass.cpp
cbb3dcb13463449b2018c6a124829e5c34debb15
[]
no_license
KeiranMillar/Procedural-Generation-Methods
5283cd4a054c3c7997a1cf17d547748f84a0546f
709ebb106130ba2cba25a8711779205e2130e159
refs/heads/master
2020-05-23T07:01:09.550640
2019-05-14T17:38:06
2019-05-14T17:38:06
186,670,850
0
0
null
null
null
null
UTF-8
C++
false
false
5,528
cpp
//////////////////////////////////////////////////////////////////////////////// // Filename: cameraclass.cpp //////////////////////////////////////////////////////////////////////////////// #include "cameraclass.h" CameraClass::CameraClass() { m_positionX = 0.0f; m_positionY = 0.0f; m_positionZ = 0.0f; m_rotationX = 0.0f; m_rotationY = 0.0f; m_rotationZ = 0.0f; D3DXVECTOR3 up, position, lookAt; up.x = 0.0f; up.y = 1.0f; up.z = 0.0f; position.x = 0.0f; position.y = 0.0f; position.z = -10.0f; lookAt.x = 0.0f; lookAt.x = 0.0f; lookAt.x = 0.0f; D3DXMatrixLookAtLH(&m_orthoMatrix, &position, &lookAt, &up); } CameraClass::CameraClass(const CameraClass& other) { } CameraClass::~CameraClass() { } void CameraClass::SetPosition(float x, float y, float z) { m_positionX = x; m_positionY = y; m_positionZ = z; return; } void CameraClass::SetRotation(float x, float y, float z) { m_rotationX = x; m_rotationY = y; m_rotationZ = z; return; } D3DXVECTOR3 CameraClass::GetPosition() { return D3DXVECTOR3(m_positionX, m_positionY, m_positionZ); } D3DXVECTOR3 CameraClass::GetRotation() { return D3DXVECTOR3(m_rotationX, m_rotationY, m_rotationZ); } void CameraClass::Render() { D3DXVECTOR3 up, position, lookAt; float yaw, pitch, roll; D3DXMATRIX rotationMatrix; // Setup the vector that points upwards. up.x = 0.0f; up.y = 1.0f; up.z = 0.0f; // Setup the position of the camera in the world. position.x = m_positionX; position.y = m_positionY; position.z = m_positionZ; // Setup where the camera is looking by default. lookAt.x = 0.0f; lookAt.y = 0.0f; lookAt.z = 1.0f; // Set the yaw (Y axis), pitch (X axis), and roll (Z axis) rotations in radians. pitch = m_rotationX * 0.0174532925f; yaw = m_rotationY * 0.0174532925f; roll = m_rotationZ * 0.0174532925f; // Create the rotation matrix from the yaw, pitch, and roll values. D3DXMatrixRotationYawPitchRoll(&rotationMatrix, yaw, pitch, roll); // Transform the lookAt and up vector by the rotation matrix so the view is correctly rotated at the origin. D3DXVec3TransformCoord(&lookAt, &lookAt, &rotationMatrix); D3DXVec3TransformCoord(&up, &up, &rotationMatrix); // Translate the rotated camera position to the location of the viewer. lookAt = position + lookAt; // Finally create the view matrix from the three updated vectors. D3DXMatrixLookAtLH(&m_viewMatrix, &position, &lookAt, &up); return; } void CameraClass::GetViewMatrix(D3DXMATRIX& viewMatrix) { viewMatrix = m_viewMatrix; return; } void CameraClass::GetOrthoMatrix(D3DXMATRIX& orthoMatrix) { orthoMatrix = m_orthoMatrix; return; } void CameraClass::GenerateBaseViewMatrix() { D3DXVECTOR3 up, position, lookAt; float yaw, pitch, roll; D3DXMATRIX rotationMatrix; // Setup the vector that points upwards. up.x = 0.0f; up.y = 1.0f; up.z = 0.0f; // Setup the position of the camera in the world. position.x = m_positionX; position.y = m_positionY; position.z = m_positionZ; // Setup where the camera is looking by default. lookAt.x = 0.0f; lookAt.y = 0.0f; lookAt.z = 1.0f; // Set the yaw (Y axis), pitch (X axis), and roll (Z axis) rotations in radians. pitch = m_rotationX * 0.0174532925f; yaw = m_rotationY * 0.0174532925f; roll = m_rotationZ * 0.0174532925f; // Create the rotation matrix from the yaw, pitch, and roll values. D3DXMatrixRotationYawPitchRoll(&rotationMatrix, yaw, pitch, roll); // Transform the lookAt and up vector by the rotation matrix so the view is correctly rotated at the origin. D3DXVec3TransformCoord(&lookAt, &lookAt, &rotationMatrix); D3DXVec3TransformCoord(&up, &up, &rotationMatrix); // Translate the rotated camera position to the location of the viewer. lookAt = position + lookAt; // Finally create the view matrix from the three updated vectors. D3DXMatrixLookAtLH(&m_baseViewMatrix, &position, &lookAt, &up); return; } void CameraClass::GetBaseViewMatrix(D3DXMATRIX& viewMatrix) { viewMatrix = m_baseViewMatrix; return; } void CameraClass::RenderReflection(float height) { D3DXVECTOR3 up, position, lookAt; float yaw, pitch, roll; D3DXMATRIX rotationMatrix; // Setup the vector that points upwards. up.x = 0.0f; up.y = 1.0f; up.z = 0.0f; // Setup the position of the camera in the world. For planar reflection invert the Y position of the camera. position.x = m_positionX; position.y = -m_positionY + (height * 2.0f); position.z = m_positionZ; // Setup where the camera is looking by default. lookAt.x = 0.0f; lookAt.y = 0.0f; lookAt.z = 1.0f; // Set the yaw (Y axis), pitch (X axis), and roll (Z axis) rotations in radians. Invert the X rotation for reflection. pitch = -m_rotationX * 0.0174532925f; yaw = m_rotationY * 0.0174532925f; roll = m_rotationZ * 0.0174532925f; // Create the rotation matrix from the yaw, pitch, and roll values. D3DXMatrixRotationYawPitchRoll(&rotationMatrix, yaw, pitch, roll); // Transform the lookAt and up vector by the rotation matrix so the view is correctly rotated at the origin. D3DXVec3TransformCoord(&lookAt, &lookAt, &rotationMatrix); D3DXVec3TransformCoord(&up, &up, &rotationMatrix); // Translate the rotated camera position to the location of the viewer. lookAt = position + lookAt; // Finally create the reflection view matrix from the three updated vectors. D3DXMatrixLookAtLH(&m_reflectionViewMatrix, &position, &lookAt, &up); return; } void CameraClass::GetReflectionViewMatrix(D3DXMATRIX& viewMatrix) { viewMatrix = m_reflectionViewMatrix; return; }
[ "keiranmillar@gmail.com" ]
keiranmillar@gmail.com
ed60c96f84676ea651cccd81a13fccc2c03526c1
88ae8695987ada722184307301e221e1ba3cc2fa
/ui/ozone/platform/drm/gpu/gbm_surface_factory.h
84e3bf18460007ee8f82bda1280297f5f5f6391d
[ "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
4,040
h
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_OZONE_PLATFORM_DRM_GPU_GBM_SURFACE_FACTORY_H_ #define UI_OZONE_PLATFORM_DRM_GPU_GBM_SURFACE_FACTORY_H_ #include <stdint.h> #include <map> #include <memory> #include <vector> #include "base/memory/raw_ptr.h" #include "base/threading/thread_checker.h" #include "gpu/vulkan/buildflags.h" #include "ui/gl/gl_implementation.h" #include "ui/gl/gl_surface.h" #include "ui/ozone/common/gl_ozone_egl.h" #include "ui/ozone/public/surface_factory_ozone.h" namespace ui { class DrmThreadProxy; class GbmSurfaceless; class GbmOverlaySurface; class GbmSurfaceFactory : public SurfaceFactoryOzone { public: explicit GbmSurfaceFactory(DrmThreadProxy* drm_thread_proxy); GbmSurfaceFactory(const GbmSurfaceFactory&) = delete; GbmSurfaceFactory& operator=(const GbmSurfaceFactory&) = delete; ~GbmSurfaceFactory() override; void RegisterSurface(gfx::AcceleratedWidget widget, GbmSurfaceless* surface); void UnregisterSurface(gfx::AcceleratedWidget widget); GbmSurfaceless* GetSurface(gfx::AcceleratedWidget widget) const; // SurfaceFactoryOzone: std::vector<gl::GLImplementationParts> GetAllowedGLImplementations() override; GLOzone* GetGLOzone(const gl::GLImplementationParts& implementation) override; #if BUILDFLAG(ENABLE_VULKAN) std::unique_ptr<gpu::VulkanImplementation> CreateVulkanImplementation( bool use_swiftshader, bool allow_protected_memory) override; scoped_refptr<gfx::NativePixmap> CreateNativePixmapForVulkan( gfx::AcceleratedWidget widget, gfx::Size size, gfx::BufferFormat format, gfx::BufferUsage usage, VkDevice vk_device, VkDeviceMemory* vk_device_memory, VkImage* vk_image) override; #endif std::unique_ptr<OverlaySurface> CreateOverlaySurface( gfx::AcceleratedWidget window) override; std::unique_ptr<SurfaceOzoneCanvas> CreateCanvasForWidget( gfx::AcceleratedWidget widget) override; scoped_refptr<gfx::NativePixmap> CreateNativePixmap( gfx::AcceleratedWidget widget, gpu::VulkanDeviceQueue* device_queue, gfx::Size size, gfx::BufferFormat format, gfx::BufferUsage usage, absl::optional<gfx::Size> framebuffer_size = absl::nullopt) override; void CreateNativePixmapAsync(gfx::AcceleratedWidget widget, gpu::VulkanDeviceQueue* device_queue, gfx::Size size, gfx::BufferFormat format, gfx::BufferUsage usage, NativePixmapCallback callback) override; scoped_refptr<gfx::NativePixmap> CreateNativePixmapFromHandle( gfx::AcceleratedWidget widget, gfx::Size size, gfx::BufferFormat format, gfx::NativePixmapHandle handle) override; void SetGetProtectedNativePixmapDelegate( const GetProtectedNativePixmapCallback& get_protected_native_pixmap_callback) override; scoped_refptr<gfx::NativePixmap> CreateNativePixmapForProtectedBufferHandle( gfx::AcceleratedWidget widget, gfx::Size size, gfx::BufferFormat format, gfx::NativePixmapHandle handle) override; std::vector<gfx::BufferFormat> GetSupportedFormatsForTexturing() const override; private: scoped_refptr<gfx::NativePixmap> CreateNativePixmapFromHandleInternal( gfx::AcceleratedWidget widget, gfx::Size size, gfx::BufferFormat format, gfx::NativePixmapHandle handle); std::unique_ptr<GLOzone> egl_implementation_; base::ThreadChecker thread_checker_; const raw_ptr<DrmThreadProxy, ExperimentalAsh> drm_thread_proxy_; std::map<gfx::AcceleratedWidget, GbmSurfaceless*> widget_to_surface_map_; GetProtectedNativePixmapCallback get_protected_native_pixmap_callback_; base::WeakPtrFactory<GbmSurfaceFactory> weak_factory_{this}; }; } // namespace ui #endif // UI_OZONE_PLATFORM_DRM_GPU_GBM_SURFACE_FACTORY_H_
[ "jengelh@inai.de" ]
jengelh@inai.de
d8b8eb99be52c487e7b74e0c419b8e3b6d9da32a
aade1e73011f72554e3bd7f13b6934386daf5313
/Contest/Europe/CERC/2016/C.cpp
f7b1069b057a1b69254323bf0ec6b655cb609b9d
[]
no_license
edisonhello/waynedisonitau123
3a57bc595cb6a17fc37154ed0ec246b145ab8b32
48658467ae94e60ef36cab51a36d784c4144b565
refs/heads/master
2022-09-21T04:24:11.154204
2022-09-18T15:23:47
2022-09-18T15:23:47
101,478,520
34
6
null
null
null
null
UTF-8
C++
false
false
1,043
cpp
#include<bits/stdc++.h> using namespace std; double ans; void circle(int d){ if(!d){ ans+=acos(-1)/2; return; } // cout<<"circle "<<d<<endl; ans+=d+0.5+1; double x=d; double y=sqrt(3)/2-0.5; double t=hypot(x,y); double tt=sqrt(t*t-0.25); double o=acos((t*t+0.25-tt*tt)/(2*0.5*t)); o+=acos((t*t+d*d-y*y)/(2*t*d)); o=acos(-1)/2-o; ans+=tt+o*0.5; } void square(int d){ if(!d){ ans+=2; return; } // cout<<"square "<<d<<endl; ans+=d+0.5+1+0.5; double x=d-0.5; double y=1-sqrt(3)/2; ans+=hypot(x,y); } int main(){ int n; cin>>n; string s; cin>>s; s=" "+s; int L=1,R=n; while(L<=n && s[L]=='T')++L; while(R>=1 && s[R]=='T')--R; if(R<L){ // all triangle ans+=n; ans+=n-1; ans+=2; } else{ ans+=(R-L)*2; if(s[L]=='C')circle(L-1); else square(L-1); if(s[R]=='C')circle(n-R); else square(n-R); } cout<<fixed<<setprecision(20)<<ans<<endl; }
[ "tu.da.wei@gmail.com" ]
tu.da.wei@gmail.com
cc287b3040193a7fee94f330cbe3ca8c5672160b
ed1b1e2f35e18569aa19b63568431c65493b4fbe
/archsim/inc/core/thread/ThreadManager.h
679d531377a50363c2d505957f3c1e78f8a850dd
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yczheng-hit/gensim
cd215c6efc6357f1e375a90d7bda003e8288ed55
1c2c608d97ef8a90253b6f0567b43724ba553c6b
refs/heads/master
2022-12-31T21:00:50.851259
2020-10-16T11:52:19
2020-10-16T11:52:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
789
h
/* This file is Copyright University of Edinburgh 2018. For license details, see LICENSE. */ /* * File: ThreadManager.h * Author: harry * * Created on 10 April 2018, 16:14 */ #ifndef THREADMANAGER_H #define THREADMANAGER_H #include <arch/ArchDescription.h> namespace archsim { /** * This class manages the execution of threads for a single guest * architecture. These threads might be from the same core or different * cores, or from cores in different configurations. * * This class mainly exists to bridge the gap between guest thread * instances and execution engines. */ class ThreadManager { public: private: std::vector<ThreadInstance*> thread_instances_; gensim::arch::ArchDescription &arch_descriptor_; }; } #endif /* THREADMANAGER_H */
[ "harry.wagstaff@gmail.com" ]
harry.wagstaff@gmail.com
c54854f58e45e0a88581bfe301a09c5c97163c5d
d14b5d78b72711e4614808051c0364b7bd5d6d98
/third_party/llvm-10.0/llvm/lib/CodeGen/LiveRangeUtils.h
0e6bfeb0d4a59eb7fff3bf2c5d99c5a81cecf7dd
[ "Apache-2.0" ]
permissive
google/swiftshader
76659addb1c12eb1477050fded1e7d067f2ed25b
5be49d4aef266ae6dcc95085e1e3011dad0e7eb7
refs/heads/master
2023-07-21T23:19:29.415159
2023-07-21T19:58:29
2023-07-21T20:50:19
62,297,898
1,981
306
Apache-2.0
2023-07-05T21:29:34
2016-06-30T09:25:24
C++
UTF-8
C++
false
false
2,172
h
//===-- LiveRangeUtils.h - Live Range modification utilities ----*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // /// This file contains helper functions to modify live ranges. // //===----------------------------------------------------------------------===// #ifndef LLVM_LIB_CODEGEN_LIVERANGEUTILS_H #define LLVM_LIB_CODEGEN_LIVERANGEUTILS_H #include "llvm/CodeGen/LiveInterval.h" namespace llvm { /// Helper function that distributes live range value numbers and the /// corresponding segments of a master live range \p LR to a list of newly /// created live ranges \p SplitLRs. \p VNIClasses maps each value number in \p /// LR to 0 meaning it should stay or to 1..N meaning it should go to a specific /// live range in the \p SplitLRs array. template<typename LiveRangeT, typename EqClassesT> static void DistributeRange(LiveRangeT &LR, LiveRangeT *SplitLRs[], EqClassesT VNIClasses) { // Move segments to new intervals. typename LiveRangeT::iterator J = LR.begin(), E = LR.end(); while (J != E && VNIClasses[J->valno->id] == 0) ++J; for (typename LiveRangeT::iterator I = J; I != E; ++I) { if (unsigned eq = VNIClasses[I->valno->id]) { assert((SplitLRs[eq-1]->empty() || SplitLRs[eq-1]->expiredAt(I->start)) && "New intervals should be empty"); SplitLRs[eq-1]->segments.push_back(*I); } else *J++ = *I; } LR.segments.erase(J, E); // Transfer VNInfos to their new owners and renumber them. unsigned j = 0, e = LR.getNumValNums(); while (j != e && VNIClasses[j] == 0) ++j; for (unsigned i = j; i != e; ++i) { VNInfo *VNI = LR.getValNumInfo(i); if (unsigned eq = VNIClasses[i]) { VNI->id = SplitLRs[eq-1]->getNumValNums(); SplitLRs[eq-1]->valnos.push_back(VNI); } else { VNI->id = j; LR.valnos[j++] = VNI; } } LR.valnos.resize(j); } } // End llvm namespace #endif
[ "bclayton@google.com" ]
bclayton@google.com
f279a501e41ea0fcf79e58d6ac0398188f770c29
34c06ba03e6f7d43f2a26a3c83fbe661a659f14d
/Scheduler.h
0f46e1d2af98f12ec1b0a7b50d49efa91c083948
[]
no_license
masaraksh79/pyxnet
56b32eb4e0674a9c5cbe94afeb962fdde0ca9506
0e743ddc8aff9e8b026a1524577835d6003ae507
refs/heads/master
2021-01-22T05:50:58.433110
2017-10-21T10:31:33
2017-10-21T10:31:33
81,716,547
0
0
null
null
null
null
UTF-8
C++
false
false
1,967
h
// // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // #ifndef SCHEDULER_H_ #define SCHEDULER_H_ #include <omnetpp.h> namespace pyxis { #define MAX_ALLOCATIONS 25 typedef struct { int pid; int frames; int sfr; // sticky frames, same as .frames just not nullified by ->allocate } req_t; typedef struct { int pid; int frames; } alc_t; class Scheduler { public: Scheduler(int, int, int, int ); /* args: hosts, cycle slots, access slots (AR+1), max PGBK allowed */ virtual ~Scheduler(); void addDataRequest(int pid, int frames, double rng, char* eve); void clearRequests(int CS, int AS); void clearAllocations(); int getNumOfAllocated(); int getAllocatedPID(int id); int getAllocatedFrames(int id); int getNeededDataFrames(); void allocate(); int getNumOfAllocatedFrames(); int getNumOfRequestedFrames(); bool emptyRequests(); int getPGBKCnt(int pid); private: int numHosts; int numReqFrames, numAlcFrames; int *numPGBK; int numMiniSlots; int numFrames; // number of frames requested from start of AR int maxFrames; int maxPGBK; req_t* requests; alc_t* allocations; int reqPLeft, reqPRight; // requests operations bool allocateItem(int r); }; } /* namespace pyxis */ #endif /* SCHEDULER_H_ */
[ "yakir.m@gmail.com" ]
yakir.m@gmail.com
bfb33ed282a19b1b06b94aafd420d380ef6cb66e
942bc7a374ced8f96a139feac1a01148cc4e60d7
/indy/C4/IdLogBase.hpp
4f1e80dd8c5c88b4e6de245f41e6e0d8626e69d6
[]
no_license
p-ameline/Episodus
915b0dfa324a0b9374b887f0fc9fd74a599b9ae3
8bba0a26e267cff40a7669c6ae47647c68a30834
refs/heads/master
2022-04-07T12:39:09.224028
2020-03-06T09:20:03
2020-03-06T09:20:03
119,287,108
1
3
null
null
null
null
UTF-8
C++
false
false
2,283
hpp
// Borland C++ Builder // Copyright (c) 1995, 1999 by Borland International // All rights reserved // (DO NOT EDIT: machine generated header) 'IdLogBase.pas' rev: 4.00 #ifndef IdLogBaseHPP #define IdLogBaseHPP #pragma delphiheader begin #pragma option push -w- #include <IdSocketHandle.hpp> // Pascal unit #include <IdIntercept.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Idlogbase { //-- type declarations ------------------------------------------------------- class DELPHICLASS TIdLogBase; #pragma pack(push, 4) class PASCALIMPLEMENTATION TIdLogBase : public Idintercept::TIdConnectionIntercept { typedef Idintercept::TIdConnectionIntercept inherited; protected: bool FActive; bool FLogTime; bool FReplaceCRLF; bool FStreamedActive; virtual void __fastcall Close(void); virtual void __fastcall LogStatus(const AnsiString AText) = 0 ; virtual void __fastcall LogReceivedData(const AnsiString AText, const AnsiString AData) = 0 ; virtual void __fastcall LogSentData(const AnsiString AText, const AnsiString AData) = 0 ; virtual void __fastcall Open(void); virtual void __fastcall SetActive(const bool AValue); virtual void __fastcall Loaded(void); public: virtual void __fastcall Connect(Classes::TComponent* AConnection); __fastcall virtual TIdLogBase(Classes::TComponent* AOwner); virtual void __fastcall Receive(Classes::TStream* ABuffer); virtual void __fastcall Send(Classes::TStream* ABuffer); __fastcall virtual ~TIdLogBase(void); virtual void __fastcall Disconnect(void); __published: __property bool Active = {read=FActive, write=SetActive, default=0}; __property bool LogTime = {read=FLogTime, write=FLogTime, default=1}; __property bool ReplaceCRLF = {read=FReplaceCRLF, write=FReplaceCRLF, default=1}; }; #pragma pack(pop) //-- var, const, procedure --------------------------------------------------- } /* namespace Idlogbase */ #if !defined(NO_IMPLICIT_NAMESPACE_USE) using namespace Idlogbase; #endif #pragma option pop // -w- #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // IdLogBase
[ "philippe.ameline@free.fr" ]
philippe.ameline@free.fr
f4cf5d6214f0de6981d66269b42eaaee7e412e3a
abe141e3a19b885c33edd932dfa0b9de13c14882
/src/main_components/aspif_rule_statement.cpp
65dd00b4c0ef73e6fda3a32eed1db400733c820e
[]
no_license
kwrx/ASP-Solving-Input-Optimizer
fcca8cd6a684c7ec2375dc0822c7e717b4b67ccf
43235ea6e5edbe67e71b0ec7bdff345bd7419a1d
refs/heads/master
2022-09-13T20:52:29.171603
2020-05-31T19:21:35
2020-05-31T19:21:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,953
cpp
#include "../../include/main_components/aspif_rule_statement.h" using namespace aspsio; AspifRuleStatement::AspifRuleStatement():head_type(Disjunction), lower_bound(-1){} // Print the new rule structure into the input encoding data void AspifRuleStatement::DoOutput(){ if(!useless){ std::string newline = "1 "; newline += std::to_string(head_type) + " " + std::to_string(head.size()) + " "; for (auto it = head.begin(); it != head.end(); it++) { newline += std::to_string(it->GetLiteral()->GetId()) + " "; } newline += std::to_string(body_type) + " "; if(body_type == WeightBody) newline += std::to_string(lower_bound) + " "; newline += std::to_string(body.size()) + " "; for (auto it = body.begin(); it != body.end(); it++) { int multipl; if(it->IsPositive()) multipl = 1; else multipl = -1; newline += std::to_string(it->GetLiteral()->GetId() * multipl) + " "; if(body_type == WeightBody) newline += std::to_string(it->GetWeight()) + " "; } *encoding_line = newline; } else { *encoding_line = ""; } } std::shared_ptr<AspifStatement> AspifRuleStatement::Clone(){ std::shared_ptr<AspifRuleStatement> new_rule(new AspifRuleStatement()); new_rule->SetBodyType(body_type); new_rule->SetHeadType(head_type); new_rule->SetLowerBound(lower_bound); for (auto it = head.begin(); it != head.end(); it++) { new_rule->AddInHead(it->GetLiteral()); } for (auto it = body.begin(); it != body.end(); it++) { if(it->HasWeight()) new_rule->AddInBody(it->GetLiteral(), it->GetWeight(), it->IsPositive()); else new_rule->AddInBody(it->GetLiteral(), it->IsPositive()); } return new_rule; }
[ "antony_97-@hotmail.it" ]
antony_97-@hotmail.it
c89da6724f45acd1cc051326897683208a367a62
4d7ff773dbcd29530baf4e04d74136bde30252b6
/Libraries/libraries/Ultrassonic/Ultrassonic.cpp
839d7d2ca74a23441d7123811f0b3750e8ab978e
[ "MIT" ]
permissive
JoeVogel/Arduino-TrekkingRobot
7b845e0f753bbcbd9ec6c2b062616d69f066a129
b06ad38e630818b81c498e7f42e2fe79e35d62d0
refs/heads/master
2020-05-17T17:37:18.689949
2014-09-02T00:13:56
2014-09-02T00:13:56
21,040,464
0
1
null
null
null
null
UTF-8
C++
false
false
1,713
cpp
#include "Arduino.h" #include "Ultrassonic_h" void Ultrassonic::defineSonar(int URTRIG, int URPWM, char positionSensor){ switch(positionSensor){ case 'f': this->URTRIG_f = URTRIG; this->URPWM_f = URPWM; pinMode(this->URTRIG_f,OUTPUT); digitalWrite(this->URTRIG_f,HIGH); pinMode(this->URPWM_f, INPUT); break; case 'r': this->URTRIG_r = URTRIG; this->URPWM_r = URPWM; pinMode(this->URTRIG_r,OUTPUT); pinMode(this->URPWM_r, INPUT); break; case 'l': this->URTRIG_l = URTRIG; this->URPWM_l = URPWM; pinMode(this->URTRIG_l,OUTPUT); pinMode(this->URPWM_l, INPUT); break; } } long Ultrassonic::getFrontDistance(){ digitalWrite(this->URTRIG_f, LOW); digitalWrite(this->URTRIG_f, HIGH); long DistanceMeasured= pulseIn(this->URPWM_f,LOW); if(DistanceMeasured>200000){ return 200000; } else{ return (DistanceMeasured/50); } } long Ultrassonic::getLeftDistance(){ digitalWrite(this->URTRIG_l, LOW); delayMicroseconds(2); digitalWrite(this->URTRIG_l, HIGH); delayMicroseconds(10); digitalWrite(this->URTRIG_l, LOW); long duration = pulseIn(this->URPWM_l,HIGH); if (duration > 200000) { return 200000 }else{ return duration /29 / 2 ; } } long Ultrassonic::getRightDistance(){ digitalWrite(this->URTRIG_r, LOW); delayMicroseconds(2); digitalWrite(this->URTRIG_r, HIGH); delayMicroseconds(10); digitalWrite(this->URTRIG_r, LOW); long duration = pulseIn(this->URPWM_r,HIGH); if (duration > 200000) { return 200000; }else{ return duration /29 / 2 ; } }
[ "joe_vogel@live.com" ]
joe_vogel@live.com
3a29920983a3b92bd5f1b701be2b6bb4ce5b1e18
1c33a7c60cf567dd4a4a3853b015fac477cd46f0
/BFS_100/2234_성곽.cpp
701c3273ec05bfa784644228eb58c5ea7531b2e1
[]
no_license
su-hyunieee/vs_code_copy
4635b66146d26d9dc4524daa6beaabdd61b3ae62
a4b4c10c29b9850ee7ffeef6c46def9da32df572
refs/heads/main
2023-05-31T09:44:47.721381
2021-06-03T06:04:39
2021-06-03T06:04:39
373,041,727
0
0
null
null
null
null
UTF-8
C++
false
false
97
cpp
#include<iostream> #include<queue> #include<algorithm> using namespace std; int main(){ }
[ "tn123gus@naver.com" ]
tn123gus@naver.com
ed2a8b99d9d83c89270d11bac834e50be50c9ab8
63367b8560e8a86ba5b26602d666800b7978756c
/code/graph/graph.cc
7baec1ecd83e5d5cdacc119eafad19fbbfc43962
[]
no_license
IAmBullsaw/Graph
0342360f67636165bbd981d1a5d5b1f55271b8ca
d99d89e2aca34d41b592e9c083b52876f25e79f9
refs/heads/master
2021-07-15T15:45:17.364580
2017-10-22T20:45:48
2017-10-22T20:45:48
107,901,121
3
0
null
null
null
null
UTF-8
C++
false
false
2,426
cc
#include <iostream> #include "graph.h" #include <fstream> #include <sstream> #include <functional> using namespace std; Graph::Graph() :size{0},nodes{} {} Graph::~Graph() { for (Node* n: nodes) { delete n; n = nullptr; } } void Graph::add_node(Node* n) { bool add{true}; for (Node* node: nodes) { if (*node == *n) { add = false; break; } } if (add) { nodes.push_back(n); ++size; } } unsigned Graph::get_size() const { return size; } void Graph::print() const { for (Node* const node: nodes) { cout << *node << endl; } } void Graph::for_each_node(std::function<void(Node*)> fun) { for (Node* node: nodes){ fun(node); } } vector<Node*> Graph::get_nodes() const { return nodes; } Node* Graph::get_node_by_name(string name) { for (Node* node: nodes) { if (node->get_name() == name) { return node; } } throw out_of_range("No node with name '" + name + "'."); } void Graph::load_from_file(string const& filename) { fstream f{filename,fstream::in}; string line; stringstream ss; while (getline(f,line)) { string name; ss.str(line); ss >> name; if (name == "#") {continue;} // comment in file else if (name == "NODES") { load_nodes(f,name); } else if (name == "CONNECTIONS") { connect_nodes(f,ss,name,line); } ss.clear(); } f.close(); } void Graph::load_nodes(fstream & f, string name){ while (getline(f, name)) { if (name == "STOP") { break; } else if (name == "#") { continue; } else { add_node(new Node(name)); } } } void Graph::connect_nodes(fstream & f, stringstream & ss, string name, string line){ while (getline(f, line)) { ss.clear(); ss.str(line); name.clear(); ss >> name; bool mutual{false}; int cost{0}; if (name == "STOP") { break;} else if (name == "#") {continue;} else if (name == "m") { ss >> name; // Update to actual name mutual = true; } Node* n = get_node_by_name(name); while (ss >> name >> cost) { if (mutual) { Node* c = get_node_by_name(name); n->mutual_connect(c, cost); } else { n->connect(get_node_by_name(name), cost); } } } } int Graph::get_cost(std::string const& n1, std::string const& n2) { Node* n = get_node_by_name(n1); Node* o = get_node_by_name(n2); return n->get_cost(o); }
[ "oskja067@student.liu.se" ]
oskja067@student.liu.se
241752949387b8bf75df13dd8fda6ebf8b52967f
9f7ae044ec7e6fab9bd27e81b636ea242d3dfa1d
/framework/include/gmsec/secure/Policy.h
be124e7b3678de9bb1d5389bfb22d806c1292a8f
[]
no_license
barbaroony/GMSEC_API
9ced39b6d6847a14db386264be907403acc911da
85f806c2519104f5e527dab52331c974d590145a
refs/heads/master
2022-12-18T20:52:36.877566
2020-09-25T12:27:13
2020-09-25T12:27:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,598
h
/* * Copyright 2007-2020 United States Government as represented by the * Administrator of The National Aeronautics and Space Administration. * No copyright is claimed in the United States under Title 17, U.S. Code. * All Rights Reserved. */ #ifndef gmsec_secure_Policy_h #define gmsec_secure_Policy_h #include <gmsec/util/Deprecated.h> #include <gmsec/util/wdllexp.h> #include <gmsec/secure/Access.h> #include <gmsec/secure/Cipher.h> #include <gmsec/secure/Signer.h> #include <gmsec/secure/Random.h> namespace gmsec { class Connection; namespace secure { using gmsec::Status; using gmsec::Config; using gmsec::Connection; const char SEC_POLICY[] = "SEC-POLICY"; const char POLICY_ACCESS[] = "SEC-AUTH"; const char POLICY_CIPHER[] = "SEC-CIPHER"; const char POLICY_SIGNER[] = "SEC-SIGNER"; const char POLICY_RANDOM[] = "SEC-RANDOM"; const char FULLY_QUALIFIED_POLICY[] = "SEC-POLICY-PATH-QUALIFIED"; const char FIELD_CONTENT[] = "SEC-CONTENT"; const char VAL_SUB[] = "SEC-VAL-SUB"; // validate topics? const char VAL_SUB_LENIENT[] = "SEC-VAL-SUB-LENIENT"; // go easy on 'em ? const char ENCODE_HEADER[] = "SEC-ENCODE-HEADER"; // encode header fields? const char ENCODE_XML[] = "SEC-ENCODE-XML"; //MEH - legacy parameter for encode as xml const char GMSEC_ENCODE_XML[] = "GMSEC-ENCODE-XML"; const char GMSEC_ENCODE_JSON[] = "GMSEC-ENCODE-JSON"; const char POL_COMPRESS[] = "POL-COMPRESS"; // use data compression? class AbstractPolicy; class GMSEC_API Policy { public: /** parameters: SEC-AUTH SEC-AUTH-ID SEC-AUTH-KEY SEC-AUTH-<PARAM> SEC-AUTH-KEYDIR? SEC-CIPHER SEC-CIPHER-<PARAM> SEC-SIGNER SEC-SIGNER-<PARAM> */ GMSEC_DEPRECATED Policy (); ~Policy (); Status initialize (const Config &config); Access &getAccess (); Cipher &getCipher (); Random &getRandom (); Signer &getSigner (); /** @method isValidSubject (const char *subject) */ bool isValidSubject (const char *subject); /** @method isValidSubscription (const char *subject) */ bool isValidSubscription (const char *subject); // authenticate/checkSubscribe/checkSend use the GMSEC-provided // security service. If the middleware-specific version is being // employed, they will return /** @method authenticate Authenticate the connection. */ Status authenticate (Connection &conn); /** @method checkSubscribe Validate permission to subscribe to subject. If enabled, this will first validate the subscription. If access is not middleware controlled, Access.canSubscribe */ Status checkSubscribe (const char *subject); /** @method checkSend (const char *subject); Validate permission to send (publish/request/reply) to subject. If enabled, this will first validate the subject. If access is not middleware controlled, Access.canSend */ Status checkSend (const char *subject); /** @fn encode */ Status encode (Message &message, DataBuffer &content); /** @fn decode(...) */ Status decode(Message &message, const DataBuffer &in); /** @fn package * Applies encoding/compression/encryption/signing according to policy. */ Status package (Message &message, DataBuffer &content, ValueMap &meta); /** @fn unpackage(...) * Inverts package. */ Status unpackage (Message &message, const DataBuffer &in, ValueMap &meta); private: // Declared, but not implemented. Policy (const Policy &other); Policy &operator= (const Policy &other); friend class AbstractPolicy; AbstractPolicy * ptr; }; // TODO: hide class GMSEC_API AbstractPolicy { public: void setExternal (Policy &policy); virtual ~AbstractPolicy(); virtual Status initialize (const Config &config) = 0; virtual Access &getAccess (); virtual Cipher &getCipher (); virtual Random &getRandom (); virtual Signer &getSigner (); virtual bool isValidSubject (const char *subject) = 0; virtual bool isValidSubscription (const char *subject) = 0; virtual Status authenticate (Connection &conn) = 0; virtual Status checkSubscribe (const char *subject) = 0; virtual Status checkSend (const char *subject) = 0; virtual Status encode (Message &message, DataBuffer &content) = 0; virtual Status decode(Message &message, const DataBuffer &in) = 0; virtual Status package (Message &message, DataBuffer &content, ValueMap &meta) = 0; virtual Status unpackage (Message &message, const DataBuffer &in, ValueMap &meta) = 0; protected: Status baseInitialize (const Config &localConfig); private: Config config; Access access; Cipher cipher; Random random; Signer signer; }; class GMSEC_API API3Policy : public AbstractPolicy { public: GMSEC_DEPRECATED API3Policy (); virtual Status initialize (const Config &localConfig); virtual bool isValidSubject (const char *subject); virtual bool isValidSubscription (const char *subject); virtual Status authenticate (Connection &connection); virtual Status checkSubscribe (const char *subject); virtual Status checkSend (const char *subject); virtual Status encode (Message &message, DataBuffer &content); virtual Status decode(Message &message, const DataBuffer &in); virtual Status package (Message &message, DataBuffer &content, ValueMap &meta); virtual Status unpackage (Message &message, const DataBuffer &in, ValueMap &meta); bool useCompression() const; private: // Declared, but not implemented. API3Policy(const API3Policy &); API3Policy &operator=(const API3Policy &); Status fStatus; bool fValidateSubjects; bool fLenientSubjects; bool fEncodeHeader; bool fEncodeXml; bool fEncodeJson; bool fCompress; }; /* Refuses to proceed on any operation. */ class GMSEC_API InvalidPolicy : public AbstractPolicy { public: GMSEC_DEPRECATED InvalidPolicy (const Status &status); virtual Status initialize (const Config &localConfig); virtual bool isValidSubject (const char *subject); virtual bool isValidSubscription (const char *subject); virtual Status authenticate (Connection &connection); virtual Status checkSubscribe (const char *subject); virtual Status checkSend (const char *subject); virtual Status encode (Message &message, DataBuffer &out); virtual Status decode (Message &message, const DataBuffer &encoded); virtual Status package (Message &message, DataBuffer &content, ValueMap &meta); virtual Status unpackage (Message &message, const DataBuffer &in, ValueMap &meta); private: // Declared, but not implemented. InvalidPolicy(const InvalidPolicy &); InvalidPolicy &operator=(const InvalidPolicy &); Status fStatus; }; } // namespace secure } // namespace gmsec #endif /* gmsec_secure_Policy_h */
[ "david.m.whitney@nasa.gov" ]
david.m.whitney@nasa.gov
4e5cf8c95f9fb21cde28b1524e0c0e8823c63094
835881ade89eaff933f81d186e69fcf9695d9392
/src/representation/dmp/src/EigenHelpers.h
eff835e01f25e6c2ecec0385310064c66d3259d4
[ "BSD-3-Clause" ]
permissive
MMKrell/bolero
9e056a88aa89332762c0f06d4f8e43fc4ac64018
0e011de35f2b364bb3bb7509bc38491762026643
refs/heads/master
2021-01-21T15:19:20.012273
2017-05-19T13:38:47
2017-05-19T13:38:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,792
h
#include <Eigen/Core> namespace dmp { using Eigen::ArrayXd; using Eigen::MatrixXd; using Eigen::ArrayXXd; struct EigenHelpers { static inline ArrayXd toEigen(std::vector<double> data){ ArrayXd eig; eig.resize(data.size()); for(unsigned int i=0; i<data.size(); i++) eig[i] = data[i]; return eig; } static inline MatrixXd toEigen(std::vector<std::vector<double> > data){ MatrixXd eig; if(data.size() == 0) eig.resize(0,0); else eig.resize(data.size(), data[0].size()); for(unsigned int i=0; i<data.size(); i++){ for(unsigned int j=0; j<data[i].size(); j++){ eig(i,j) = data[i][j]; } } return eig; } static inline std::vector<double> toStdVec(ArrayXd data){ std::vector<double> vect(data.rows()); for(unsigned int i=0; i<data.rows(); i++){ vect[i] = data[i]; } return vect; } static inline std::vector<std::vector<double> > toStdVec(MatrixXd data){ std::vector<std::vector<double> >vect(data.rows()); for(unsigned int i=0; i<data.rows(); i++){ vect[i].resize(data.cols()); for(unsigned int j=0; j<data.cols(); j++){ vect[i][j] = data(i,j); } } return vect; } /** * Calculates the gradient function for \p in, e.g. the derivation. * The gradient is computed using central differences in the interior * and first differences at the boundaries. * The returned gradient hence has the same shape as the input array. * * \param dt distance between two points. * * @note this is the same as python's numpy.gradient() */ static inline void gradient( const ArrayXXd& in, ArrayXXd& out, const double dt, bool allowFinalVelocity = true) { assert(in.cols() > 1); out.resize(in.rows(), in.cols()); // Special case for first element: assume gradient to be zero out.col(0).setZero(); const int end = in.cols(); for(int i = 1; i < end; ++i) {// Difference quotient for each following element out.col(i) = (in.col(i) - in.col(i - 1))/dt; } if(!allowFinalVelocity) out.col(end - 1).setZero(); } static inline void integrate( const ArrayXd& start, const ArrayXXd& in, ArrayXXd& out, const double dt) { assert(in.cols() > 1); out.resize(in.rows(), in.cols()); // Special case for first element: assume gradient to be zero out.col(0) = start; const int end = in.cols(); for(int i = 1; i < end; ++i) {// Difference quotient for each following element out.col(i) = out.col(i - 1) + in.col(i) * dt; } } static inline void assertNonNanInf(const Eigen::ArrayXd& data) { for(unsigned i = 0; i < data.size(); ++i) { assert(!isnan(data[i])); assert(!isinf(data[i])); } } }; }
[ "afabisch@informatik.uni-bremen.de" ]
afabisch@informatik.uni-bremen.de
8681a1e97dc034e25202ae66024034bf9007350e
393994afe703f4053aa3182d7e6237b3bf7121d3
/core_qui/quidateselect.cpp
cb77fda8c29ae360d3e7285cf33663333d476ad3
[ "LicenseRef-scancode-mulanpsl-1.0-en", "MulanPSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
xiaohai1998/QWidgetDemo
9bc4630c7eb1e196eeefc8e1b02c89265883faae
a0855f95d2b075bd43550a505c7ccdb902d36b37
refs/heads/master
2023-06-01T19:45:18.020743
2021-06-24T09:39:01
2021-06-24T09:39:01
375,033,368
0
0
NOASSERTION
2021-06-24T09:39:02
2021-06-08T14:11:29
null
UTF-8
C++
false
false
9,407
cpp
#include "quidateselect.h" QScopedPointer<QUIDateSelect> QUIDateSelect::self; QUIDateSelect *QUIDateSelect::Instance() { if (self.isNull()) { static QMutex mutex; QMutexLocker locker(&mutex); if (self.isNull()) { self.reset(new QUIDateSelect); } } return self.data(); } QUIDateSelect::QUIDateSelect(QWidget *parent) : QDialog(parent) { this->initControl(); this->initForm(); } QUIDateSelect::~QUIDateSelect() { delete widgetMain; } void QUIDateSelect::showEvent(QShowEvent *) { QUIHelper::setIconBtn(btnOk, ":/image/btn_ok.png", 0xf00c); QUIHelper::setIconBtn(btnClose, ":/image/btn_close.png", 0xf00d); QUIHelper::setFormInCenter(this); this->activateWindow(); } bool QUIDateSelect::eventFilter(QObject *watched, QEvent *event) { static QPoint mousePoint; static bool mousePressed = false; QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event); if (mouseEvent->type() == QEvent::MouseButtonPress) { if (mouseEvent->button() == Qt::LeftButton) { mousePressed = true; mousePoint = mouseEvent->globalPos() - this->pos(); return true; } } else if (mouseEvent->type() == QEvent::MouseButtonRelease) { mousePressed = false; return true; } else if (mouseEvent->type() == QEvent::MouseMove) { if (mousePressed) { this->move(mouseEvent->globalPos() - mousePoint); return true; } } return QWidget::eventFilter(watched, event); } void QUIDateSelect::initControl() { this->setObjectName(QString::fromUtf8("QUIDateSelect")); verticalLayout = new QVBoxLayout(this); verticalLayout->setSpacing(0); verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); verticalLayout->setContentsMargins(1, 1, 1, 1); widgetTitle = new QWidget(this); widgetTitle->setObjectName(QString::fromUtf8("widgetTitle")); QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(widgetTitle->sizePolicy().hasHeightForWidth()); widgetTitle->setSizePolicy(sizePolicy); horizontalLayout1 = new QHBoxLayout(widgetTitle); horizontalLayout1->setSpacing(0); horizontalLayout1->setObjectName(QString::fromUtf8("horizontalLayout1")); horizontalLayout1->setContentsMargins(0, 0, 0, 0); labIco = new QLabel(widgetTitle); labIco->setObjectName(QString::fromUtf8("labIco")); QSizePolicy sizePolicy1(QSizePolicy::Minimum, QSizePolicy::Preferred); sizePolicy1.setHorizontalStretch(0); sizePolicy1.setVerticalStretch(0); sizePolicy1.setHeightForWidth(labIco->sizePolicy().hasHeightForWidth()); labIco->setSizePolicy(sizePolicy1); labIco->setAlignment(Qt::AlignCenter); horizontalLayout1->addWidget(labIco); labTitle = new QLabel(widgetTitle); labTitle->setObjectName(QString::fromUtf8("labTitle")); QSizePolicy sizePolicy2(QSizePolicy::Expanding, QSizePolicy::Preferred); sizePolicy2.setHorizontalStretch(0); sizePolicy2.setVerticalStretch(0); sizePolicy2.setHeightForWidth(labTitle->sizePolicy().hasHeightForWidth()); labTitle->setSizePolicy(sizePolicy2); labTitle->setAlignment(Qt::AlignLeading | Qt::AlignLeft | Qt::AlignVCenter); horizontalLayout1->addWidget(labTitle); widgetMenu = new QWidget(widgetTitle); widgetMenu->setObjectName(QString::fromUtf8("widgetMenu")); sizePolicy1.setHeightForWidth(widgetMenu->sizePolicy().hasHeightForWidth()); widgetMenu->setSizePolicy(sizePolicy1); horizontalLayout = new QHBoxLayout(widgetMenu); horizontalLayout->setSpacing(0); horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout")); horizontalLayout->setContentsMargins(0, 0, 0, 0); btnMenu_Close = new QPushButton(widgetMenu); btnMenu_Close->setObjectName(QString::fromUtf8("btnMenu_Close")); QSizePolicy sizePolicy3(QSizePolicy::Minimum, QSizePolicy::Expanding); sizePolicy3.setHorizontalStretch(0); sizePolicy3.setVerticalStretch(0); sizePolicy3.setHeightForWidth(btnMenu_Close->sizePolicy().hasHeightForWidth()); btnMenu_Close->setSizePolicy(sizePolicy3); btnMenu_Close->setCursor(QCursor(Qt::ArrowCursor)); btnMenu_Close->setFocusPolicy(Qt::NoFocus); btnMenu_Close->setFlat(true); horizontalLayout->addWidget(btnMenu_Close); horizontalLayout1->addWidget(widgetMenu); verticalLayout->addWidget(widgetTitle); widgetMain = new QWidget(this); widgetMain->setObjectName(QString::fromUtf8("widgetMainQUI")); verticalLayout1 = new QVBoxLayout(widgetMain); verticalLayout1->setSpacing(6); verticalLayout1->setObjectName(QString::fromUtf8("verticalLayout1")); verticalLayout1->setContentsMargins(6, 6, 6, 6); frame = new QFrame(widgetMain); frame->setObjectName(QString::fromUtf8("frame")); frame->setFrameShape(QFrame::Box); frame->setFrameShadow(QFrame::Sunken); gridLayout = new QGridLayout(frame); gridLayout->setObjectName(QString::fromUtf8("gridLayout")); labStart = new QLabel(frame); labStart->setObjectName(QString::fromUtf8("labStart")); labStart->setFocusPolicy(Qt::TabFocus); gridLayout->addWidget(labStart, 0, 0, 1, 1); btnOk = new QPushButton(frame); btnOk->setObjectName(QString::fromUtf8("btnOk")); btnOk->setMinimumSize(QSize(85, 0)); btnOk->setCursor(QCursor(Qt::PointingHandCursor)); btnOk->setFocusPolicy(Qt::StrongFocus); gridLayout->addWidget(btnOk, 0, 2, 1, 1); btnOk->setDefault(true); labEnd = new QLabel(frame); labEnd->setObjectName(QString::fromUtf8("labEnd")); labEnd->setFocusPolicy(Qt::TabFocus); gridLayout->addWidget(labEnd, 1, 0, 1, 1); btnClose = new QPushButton(frame); btnClose->setObjectName(QString::fromUtf8("btnClose")); btnClose->setMinimumSize(QSize(85, 0)); btnClose->setCursor(QCursor(Qt::PointingHandCursor)); btnClose->setFocusPolicy(Qt::StrongFocus); gridLayout->addWidget(btnClose, 1, 2, 1, 1); dateStart = new QDateTimeEdit(frame); dateStart->setObjectName(QString::fromUtf8("dateStart")); QSizePolicy sizePolicy4(QSizePolicy::Expanding, QSizePolicy::Fixed); sizePolicy4.setHorizontalStretch(0); sizePolicy4.setVerticalStretch(0); sizePolicy4.setHeightForWidth(dateStart->sizePolicy().hasHeightForWidth()); dateStart->setSizePolicy(sizePolicy4); dateStart->setCalendarPopup(true); gridLayout->addWidget(dateStart, 0, 1, 1, 1); dateEnd = new QDateTimeEdit(frame); dateEnd->setObjectName(QString::fromUtf8("dateEnd")); sizePolicy4.setHeightForWidth(dateEnd->sizePolicy().hasHeightForWidth()); dateEnd->setSizePolicy(sizePolicy4); dateEnd->setCalendarPopup(true); gridLayout->addWidget(dateEnd, 1, 1, 1, 1); verticalLayout1->addWidget(frame); verticalLayout->addWidget(widgetMain); QWidget::setTabOrder(labStart, labEnd); QWidget::setTabOrder(labEnd, dateStart); QWidget::setTabOrder(dateStart, dateEnd); QWidget::setTabOrder(dateEnd, btnOk); QWidget::setTabOrder(btnOk, btnClose); labTitle->setText("日期时间选择"); labStart->setText("开始时间"); labEnd->setText("结束时间"); btnOk->setText("确 定"); btnClose->setText("关 闭"); dateStart->setDate(QDate::currentDate()); dateEnd->setDate(QDate::currentDate().addDays(1)); dateStart->calendarWidget()->setGridVisible(true); dateEnd->calendarWidget()->setGridVisible(true); dateStart->calendarWidget()->setLocale(QLocale::Chinese); dateEnd->calendarWidget()->setLocale(QLocale::Chinese); setFormat("yyyy-MM-dd"); connect(btnOk, SIGNAL(clicked()), this, SLOT(on_btnOk_clicked())); connect(btnClose, SIGNAL(clicked()), this, SLOT(on_btnMenu_Close_clicked())); connect(btnMenu_Close, SIGNAL(clicked()), this, SLOT(on_btnMenu_Close_clicked())); } void QUIDateSelect::initForm() { QUIHelper::setFramelessForm(this, widgetTitle, labIco, btnMenu_Close); this->setWindowTitle(this->labTitle->text()); this->setFixedSize(QUIDialogMinWidth + 50, QUIDialogMinHeight); QList<QPushButton *> btns = this->frame->findChildren<QPushButton *>(); foreach (QPushButton *btn, btns) { btn->setMinimumWidth(QUIBtnMinWidth); btn->setIconSize(QSize(QUIIconWidth, QUIIconHeight)); } this->installEventFilter(this); } void QUIDateSelect::on_btnOk_clicked() { if (dateStart->dateTime() > dateEnd->dateTime()) { QUIHelper::showMessageBoxError("开始时间不能大于结束时间!", 3); return; } startDateTime = dateStart->dateTime().toString(format); endDateTime = dateEnd->dateTime().toString(format); done(QMessageBox::Ok); close(); } void QUIDateSelect::on_btnMenu_Close_clicked() { done(QMessageBox::Cancel); close(); } QString QUIDateSelect::getStartDateTime() const { return this->startDateTime; } QString QUIDateSelect::getEndDateTime() const { return this->endDateTime; } void QUIDateSelect::setIconMain(int icon, quint32 size) { IconHelper::setIcon(this->labIco, icon, size); } void QUIDateSelect::setFormat(const QString &format) { this->format = format; this->dateStart->setDisplayFormat(format); this->dateEnd->setDisplayFormat(format); }
[ "feiyangqingyun@163.com" ]
feiyangqingyun@163.com
c5c0df09d8f6ceec7ac17d18f0025afe2122e5a8
50f8c138da0165fa140c3241291aa2b0a8a14f99
/bombs and bills.cpp
34b87991d4d08a196bc2955084e9e8130690360a
[]
no_license
Priybhanu99/My-Codes
c5da0821348939d75498e2751bc6c63d5e572294
4dc2e93fb941c4166b3b687a76358a1f309cc976
refs/heads/master
2021-05-19T12:22:09.830851
2021-01-17T15:22:23
2021-01-17T15:22:23
251,694,773
2
0
null
null
null
null
UTF-8
C++
false
false
2,241
cpp
#include <bits/stdc++.h> using namespace std; int main(int argc, char *argv[]) { // このコードは標準入力と標準出力を用いたサンプルコードです。 // このコードは好きなように編集・削除してもらって構いません。 // --- // This is a sample code to use stdin and stdout. // Edit and remove this code as you like. #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif int n,m,k; cin>>n>>m>>k; char a[n][m]; vector<int> rows,cols; for(int i=0;i<n;i++){ for(int j= 0;j<m;j++){ cin>>a[i][j]; if(a[i][j]=='B'){ rows.push_back(i); cols.push_back(j); } } } set<pair<int,int>> set; for(auto i:rows){ for(int j=0;j<m;j++){ if(a[i][j]!='B'){ set.insert(make_pair(i,j)); } } } for(auto i:cols){ for(int j=0;j<n;j++){ if(a[j][i]!='B'){ set.insert(make_pair(j,i)); } } } // cout<<"set: \n"; // for(auto i:set){ // cout<<i.first<<" "<<i.second<<"\n"; // } // cout<<"\n"; priority_queue<int,vector<int>, greater<int> > safe; for (int i = 0; i < n; ++i) { for(int j=0;j<m;j++){ if(a[i][j]!='B' && set.count(make_pair(i,j))==0){ // cout<<a[i][j]<<","; safe.push(a[i][j]-'0'); } } } // cout<<"safe: \n"; // for(auto i:safe){ // cout<<i<<" "; // } // cout<<"\n"; int ans = 0; priority_queue<int> temp; for(auto i:set){ temp.push((a[i.first][i.second])-'0'); } while(k--){ //if there is a value in temp which is greater than safe then swap them. if(temp.size()==0 || safe.size()==0){ break; } int num1 = temp.top(); int num2 = safe.top(); if(num1<=num2){ break; } if(num1>num2){ temp.pop(); safe.pop(); safe.push(num1); } } while(!safe.empty()){ // cout<<safe.top()<<" "; ans += safe.top(); safe.pop(); } cout<<ans; // sort(bombline.begin(),bombline.end()); // unique(bombline.begin(),bombline.end()); // for(auto i:set){ // cout<<i.first<<" "<<i.second<<" "<<a[i.first][i.second]<<" \n"; // } return 0; }
[ "bhanuyadav1999.by@gmail.com" ]
bhanuyadav1999.by@gmail.com
2529773627ec1c162b47bd417c23d82a2fc9f7ae
d85b1f3ce9a3c24ba158ca4a51ea902d152ef7b9
/testcases/CWE762_Mismatched_Memory_Management_Routines/s05/CWE762_Mismatched_Memory_Management_Routines__new_array_free_int_81a.cpp
cf685d04455e07c573a9ca2ce9e4ea38cae8505b
[]
no_license
arichardson/juliet-test-suite-c
cb71a729716c6aa8f4b987752272b66b1916fdaa
e2e8cf80cd7d52f824e9a938bbb3aa658d23d6c9
refs/heads/master
2022-12-10T12:05:51.179384
2022-11-17T15:41:30
2022-12-01T15:25:16
179,281,349
34
34
null
2022-12-01T15:25:18
2019-04-03T12:03:21
null
UTF-8
C++
false
false
3,197
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__new_array_free_int_81a.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_array_free.label.xml Template File: sources-sinks-81a.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: Allocate data using new [] * GoodSource: Allocate data using malloc() * Sinks: * GoodSink: Deallocate data using delete [] * BadSink : Deallocate data using free() * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference * * */ #include "std_testcase.h" #include "CWE762_Mismatched_Memory_Management_Routines__new_array_free_int_81.h" namespace CWE762_Mismatched_Memory_Management_Routines__new_array_free_int_81 { #ifndef OMITBAD void bad() { int * data; /* Initialize data*/ data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */ data = new int[100]; const CWE762_Mismatched_Memory_Management_Routines__new_array_free_int_81_base& o = CWE762_Mismatched_Memory_Management_Routines__new_array_free_int_81_bad(); o.action(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { int * data; /* Initialize data*/ data = NULL; /* FIX: Allocate memory from the heap using malloc() */ data = (int *)malloc(100*sizeof(int)); if (data == NULL) {exit(-1);} const CWE762_Mismatched_Memory_Management_Routines__new_array_free_int_81_base& baseObject = CWE762_Mismatched_Memory_Management_Routines__new_array_free_int_81_goodG2B(); baseObject.action(data); } /* goodB2G uses the BadSource with the GoodSink */ static void goodB2G() { int * data; /* Initialize data*/ data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */ data = new int[100]; const CWE762_Mismatched_Memory_Management_Routines__new_array_free_int_81_base& baseObject = CWE762_Mismatched_Memory_Management_Routines__new_array_free_int_81_goodB2G(); baseObject.action(data); } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE762_Mismatched_Memory_Management_Routines__new_array_free_int_81; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "Alexander.Richardson@cl.cam.ac.uk" ]
Alexander.Richardson@cl.cam.ac.uk
45fa7f217703c30045e8c773fd08e741db5a7f84
40523a22fdbe5d111c9601a52cf4ceb3e231dc8e
/src/Shader.h
ea1780a7d7610f0b271d0d82ece9c60c1f6c3c49
[]
no_license
antaires/3D-OpenGL-Engine
dab3bbb454be406e2d96fddb68676c0b38ce743f
391815b253e75aeb69e77ac805ab1bc7ff8aa86a
refs/heads/master
2023-08-18T13:18:32.357756
2020-12-07T07:14:04
2020-12-07T07:14:04
281,370,334
1
1
null
2021-09-28T13:02:29
2020-07-21T10:45:38
C++
UTF-8
C++
false
false
1,004
h
#pragma once #include "Math.h" #include <GL/glew.h> #include <string> class Shader { private: // store the shader object IDs GLuint m_ShaderProgram; GLuint m_VertexShader; GLuint m_FragShader; std::string name; public: Shader(std::string& name); ~Shader(); // load vertex/ fragment shaders bool Load(const std::string& vertName, const std::string& fragName); void Unload(); void SetActive(); void SetMatrixUniform(const char* name, const Matrix4& matrix); void SetMatrixUniforms(const char* name, Matrix4* matrices, unsigned count); void SetVectorUniform(const char* name, const Vector3& vector); void SetFloatUniform(const char* name, float value); const std::string& GetShaderName() const; private: // compile specified shader bool CompileShader(const std::string& fileName, GLenum shaderType, GLuint& outShader); // test if compiled successfully bool IsCompiled(GLuint shader); // tests whether vertex / fragment programs link bool IsValidProgram(); };
[ "11vdlo@gmail.com" ]
11vdlo@gmail.com
8ad10dcd3b3fdb128a829611b43d441a3e63a492
d81451ac2511d3438de7baf375b5c855ea24305a
/CPP/rent.cpp
2e2c1bbed086dfc64b9a8dddc2ff279c2a794c0e
[]
no_license
ToF-/Rent
2bcd84b46066c6709df72509865ca0f01b111d21
b0dd5e5513e31c63ccaf680ccce70fe5fb5d279b
refs/heads/master
2021-05-25T09:04:10.168494
2021-05-02T08:47:34
2021-05-02T08:47:34
13,162,992
0
0
null
null
null
null
UTF-8
C++
false
false
2,603
cpp
// rent.cpp //#define SPOJ // uncomment this line to make spoj #include <iostream> #include "rent.h" #include "assert.h" #include "stdio.h" #include <cstdlib> using namespace std; Scheduler::Scheduler() { max_orders = 0; } Order Scheduler::next_compatible_order(int k, Order order) { int l = k+1; int h = max_orders; int end_time = order.start_time + order.duration; int result; while(l <= h) { int m = l + (h - l) / 2; if(orders[m].start_time < end_time) l = m + 1; else { result = m; h = m - 1; } } return orders[result]; } int compareOrders (const void * a, const void * b) { Order orderA = *(Order *)a; Order orderB = *(Order *)b; return orderA.start_time - orderB.start_time; } void Scheduler::set_limit() { orders[max_orders].start_time = MAX_START_TIME; orders[max_orders].duration = 0; orders[max_orders].amount = 0; } void Scheduler::sort_orders() { qsort (orders, max_orders, sizeof(Order), compareOrders); } void Sheduler::compute_revenue() { for(int i = max_orders-1; i>=0; i--) { Order current = orders[i]; Order next = orders[i+1]; Order compatible = next_compatible_order(i, current); int comp_amount = current.amount + compatible.amount; current.amount = next.amount > comp_amount ? next.amount : comp_amount; } } int Scheduler::get_revenue() { set_limit(); sort_orders(); compute_revenue(); return orders[0].amount; } void Scheduler::add_order(int start, int duration, int amount) { assert(max_orders<MAX_ORDERS-1); orders[max_orders].start_time = start; orders[max_orders].duration = duration; orders[max_orders].amount = amount; max_orders++; } Order OrderReader::read() { Order order; input >> order.start_time >> order.duration >> order.amount ; return order; } void RevenueWriter::write(int revenue) { output << revenue << endl; } Session::Session(istream &input, ostream &output) : input(input), output(output) { } void Session::process() { int max_cases, max_orders; OrderReader reader = OrderReader(input); RevenueWriter writer = RevenueWriter(output); input >> max_cases; for(int k=0; k < max_cases; k++) { Scheduler scheduler; input >> max_orders; for(int i=0; i<max_orders; i++) { Order order = reader.read(); scheduler.add_order(order.start_time, order.duration, order.amount); } writer.write(scheduler.get_revenue()); } }
[ "cthibaut@octo.com" ]
cthibaut@octo.com
8f92a7d8fdfbe1546ba37299dd223daf05c1fbed
f59592f0554401fe887246519e08513fcfdae74a
/src/DeviceException.hpp
f13d920d0d4cd8f3fe9d48051954d840238ebc37
[]
no_license
sanjay900/SanPIE
587828a5d9a2293024285c13918f884cecdee1ed
b8e5c858a17e1d73ec245a6403f98a2bd3206e40
refs/heads/master
2023-02-24T11:40:58.740712
2023-02-14T03:01:49
2023-02-14T03:01:49
139,983,607
0
0
null
null
null
null
UTF-8
C++
false
false
417
hpp
// // Created by sanjay on 4/07/18. // #ifndef WEJOY_CONTROLLEREXCEPTION_H #define WEJOY_CONTROLLEREXCEPTION_H #include <exception> #include <string> #include <utility> class DeviceException: public std::exception { private: const std::string message_; public: explicit DeviceException(std::string message); virtual const char* what() const noexcept { return message_.c_str(); } }; #endif
[ "sanjay.govind9@gmail.com" ]
sanjay.govind9@gmail.com
d224ff90144a78cfba47aa79e535a09b8b48a965
c50c60c7b8614767a4125afc5d71e8864d604560
/unused/IntensityCalibrationDataFilter.cpp
803052011ded38b4a4f605d9339502dc04733fdd
[]
no_license
whigg/spc
12a797650185577ea0bd6e3848f9908f1c3a3956
818a2737aab1e2c83a056a6a80b1d6c0e388bda0
refs/heads/master
2020-09-02T06:31:46.286449
2017-11-30T11:30:57
2017-11-30T11:30:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
44
cpp
#include "IntensityCalibrationDataFilter.h"
[ "luca.penasa@gmail.com" ]
luca.penasa@gmail.com
757c931a106f23c70a8c5d009932567f327b9ed7
7dfb3a15943620097f11f3e2aa3e06fc56d05a18
/Autolabor/driver/lidar/wr_fslidar/src/serial.cpp
8ce0a3b28059ec19101febc539430a9dd6ce5adc
[]
no_license
StPaulImp/Autolabor
737356909f179939a357eb3abec790d5f3d9e7be
8a06a168d19c4cc6837cc447e321a6f5813a3264
refs/heads/master
2023-04-08T06:09:08.617007
2021-04-19T10:44:34
2021-04-19T10:44:34
297,869,076
1
2
null
null
null
null
UTF-8
C++
false
false
2,927
cpp
#include <iostream> #include <unistd.h> #include "serial.h" using namespace std; Serial::Serial() { fd = -1; } bool Serial::openUp(const char *dev) { struct termios termios_old; fd = open(dev, O_RDWR | O_NOCTTY | O_NDELAY ); if (fd < 0){ return false; } tcgetattr(fd , &termios_old); return true; } bool Serial::closeOff() { struct termios termios_old; if(fd > 0){ tcsetattr(fd, TCSADRAIN, &termios_old); close(fd); } return true; } bool Serial::setOption() { tcflush(fd, TCIOFLUSH); int n = fcntl(fd, F_GETFL, 0); /* struct termios termios_old; if (tcgetattr(fd, &termios_old) != 0) { return false; } */ struct termios termios_new; cfsetispeed(&termios_new, B460800); cfsetospeed(&termios_new, B460800); // cfsetispeed(&termios_new, B230400); // cfsetospeed(&termios_new, B230400); termios_new.c_cflag &= ~CSIZE; termios_new.c_cflag |= CS8; termios_new.c_cflag &= ~PARENB; termios_new.c_cflag &= ~CSTOPB; termios_new.c_cflag &= ~CRTSCTS; //termios_new.c_iflag &= ~(IXON|IXOFF|IXANY); termios_new.c_iflag &= ~ISTRIP; termios_new.c_iflag |= IGNBRK; termios_new.c_cflag |= CLOCAL; termios_new.c_cflag |= CREAD; termios_new.c_cc[VTIME] = 0; termios_new.c_cc[VMIN] = 1; termios_new.c_oflag = 0; termios_new.c_lflag = 0; if (tcsetattr(fd, TCSANOW, &termios_new) != 0) { return false; } int mcs = 0; ioctl(fd, TIOCMGET, &mcs); mcs |= TIOCM_RTS; ioctl(fd, TIOCMSET, &mcs); return true; /* bzero(&termios_new, sizeof(termios_new)); cfmakeraw(&termios_new); termios_new.c_cflag = B230400; termios_new.c_cflag |= CLOCAL | CREAD; termios_new.c_cflag &= ~CSIZE; termios_new.c_cflag |= CS8; termios_new.c_cflag &= ~CSTOPB; termios_new.c_cflag &= ~PARENB; tcflush(fd, TCIFLUSH); tcflush(fd, TCOFLUSH); termios_new.c_cc[VTIME] = 1; termios_new.c_cc[VMIN] = 1; tcflush(fd, TCIFLUSH); tcsetattr(fd, TCSANOW, &termios_new); return true; */ } int Serial::send(const char *data, int length) { int len = 0, total_len = 0; if(fd <0) { return -1; } for (total_len=0;total_len<length;) { len = write(fd, &data[total_len], length-total_len); if (len > 0) { total_len += len; } else if(len <= 0) { len = -1; break; } } return len; } int Serial::recv(char *data, int length) { //cout << "ok2" << endl; if (fd < 0) { return -1; } int len = 0; while((len = read(fd, data, length))<=0) { usleep(1000); } //printf("%02x ", (unsigned char)*data); //printf("read ok: %d, %02x\n", len, (unsigned char)*data); return len; } bool Serial::isOpen() { return (fd>=0)?true:false; }
[ "wangqi@shtdtech.com" ]
wangqi@shtdtech.com
b0902df7a1f219d797002d9cd8961f56fb18199a
7f4430f70911ddc552956ac1b7874a88d8b0edad
/hash/HashTable.cpp
5915859434b4215f8faca06e14c15447bc47e4f5
[]
no_license
tylercross/algorithm
404689c701655515cc7608a45b8d1d8257dd2bb8
44171627a592f0a91c0a8dbf8c97f034d92ee40c
refs/heads/master
2020-04-29T11:34:00.306675
2019-09-10T16:06:04
2019-09-10T16:06:04
176,103,341
3
0
null
null
null
null
UTF-8
C++
false
false
2,531
cpp
//***************************************************************** // HashTable.cpp // HashTable // // Created by Karlina Beringer on June 18, 2014. // // This header file contains the Hash Table class definition. // Hash Table array elements consist of Linked List objects. //***************************************************************** #include "HashTable.h" // Constructs the empty Hash Table object. // Array length is set to 13 by default. HashTable::HashTable( int tableLength ) { array = new LinkedList[tableLength]; length = tableLength; } // Returns an array location for a given item key. int HashTable::hash( string itemKey ) { int h=0; for(int i=0;i<4;i++) { h=itemKey[i]*32+h; } return h%length; } // Adds an item to the Hash Table. void HashTable::insertItem( Item * newItem ) { array[hash(newItem->key)].insertItem(newItem); } // Deletes an Item by key from the Hash Table. // Returns true if the operation is successful. bool HashTable::removeItem( string itemKey ) { int index = hash(itemKey); return array[index].removeItem(itemKey); } // Returns an item from the Hash Table by key. // If the item isn't found, a null pointer is returned. Item * HashTable::getItemByKey( string itemKey ) { int index= hash(itemKey); return array[index].getItem(itemKey); } // Display the contents of the Hash Table to console window. void HashTable::printTable() { cout << "\nHash Table:\n"; for (int i = 0; i < length; i++) { cout << "Bucket " << i+1 << ": "; array[i].printList(); } } // Prints a histogram illustrating the Item distribution. void HashTable::printHistogram() { cout << "\n\nHash Table Contains "; cout << getNumberOfItems() << " Items total\n"; for (int i = 0; i < length; i++) { cout << i + 1 << ":\t"; for (int j = 0; j < array[i].getLength(); j++) cout << " X"; cout << "\n"; } } // Returns the number of locations in the Hash Table. int HashTable::getLength() { return length; } // Returns the number of Items in the Hash Table. int HashTable::getNumberOfItems() { int itemCount = 0; for (int i = 0; i < length; i++) itemCount += array[i].getLength(); return itemCount; } // De-allocates all memory used for the Hash Table. HashTable::~HashTable() { delete [] array; } //***************************************************************** // End of File //*****************************************************************
[ "fanwenjin@tju.edu.cn" ]
fanwenjin@tju.edu.cn
08346e4a8b113bc34366546eb4dbcfcde0526472
b1e730e22510b7d296f372de39c2ffda44d1001b
/189A-Cut_Ribbon.cpp
228fd078d643bf164acdc8f112f0115b98266456
[]
no_license
KieranHorgan/Codeforces-Problems
7f28ed654a7b142086bb25c2f8b98fc2c66bf7a2
9e87ccea355208044343be857b005530f228a445
refs/heads/master
2021-01-19T19:44:35.895339
2017-05-09T20:12:02
2017-05-09T20:12:02
88,438,604
0
0
null
null
null
null
UTF-8
C++
false
false
544
cpp
#include <iostream> using namespace std; #define ll long long ll n, m, ans; ll a, b, c; ll dp[10000]; int main() { cin >> n; ll abc[3]; cin >> abc[0] >> abc[1] >> abc[2]; for(int i = 1; i < n+2; i++) { dp[i] = -1; } dp[0] = 0; for(int i = 0; i < n; i++) { // cout << dp[i] << " "; if(dp[i] >= 0) for(int j = 0; j < 3; j++) { dp[i+abc[j]] = max(dp[i+abc[j]], dp[i]+1); } } cout << dp[n]; return 0; }
[ "kieranhorganmallow@gmail.com" ]
kieranhorganmallow@gmail.com
b321357010fa791e687c7070e11c5fe1dcde043e
7903ac347c1d15a4d5e5d6abf31912a33c1d51d9
/src/Bullet.h
8f498fbfc009d3244519ae2393d141f3774ba03a
[]
no_license
esialb/arduboy-shmup
d0da6f933a48308dd0db11662fe854777590d2be
9fe95dc082841298fca2d109247d0b1b42876a7b
refs/heads/master
2020-06-11T10:09:39.095178
2017-08-24T01:14:08
2017-08-24T01:14:08
75,697,170
0
0
null
null
null
null
UTF-8
C++
false
false
422
h
/* * Bullet.h * * Created on: Dec 6, 2016 * Author: robin */ #ifndef SRC_BULLET_H_ #define SRC_BULLET_H_ #include <Arduboy2.h> #include "ShmupSprites.h" class Bullet { public: Bullet(); virtual ~Bullet(); void Draw(); void Tick(); bool Collides(int x, int y, const uint8_t* mask); bool active = false; uint8_t x = 0, y = 0; int8_t dx = 0, dy = 0, fm = 0; }; #endif /* SRC_BULLET_H_ */
[ "robin.kirkman@gmail.com" ]
robin.kirkman@gmail.com
8e903246b54e67ff425f3d0041a93dba2d739145
c097c09c748cb8294d83d4763d744957501cd67c
/ProyectoVHMVCSpa/Principal.cpp
a284f9c4d774c6999af5a4a79f06335dce5c15b1
[]
no_license
PeterGabrielVE/CPlusPlus
afd9af5c4b5507fe0eb16793bea76f4ba76dc247
b82a3df577570cc1e8deac2aa14c7baf494dc158
refs/heads/master
2021-05-11T04:03:03.054773
2018-04-01T02:50:01
2018-04-01T02:50:01
117,926,636
0
0
null
null
null
null
UTF-8
C++
false
false
4,448
cpp
/* * Principal.cpp * * Created on: 26/05/2014 * Author: Pedro Gabriel Leal * *PLANTEAMIENTO: La empresa AMANON SPA se encuentra ubicada en la zona Este de Barquisimeto y se encarga de tratar el cuerpo, la mente y el espíritu como un todo, para alcanzar la armonía, el equilibrio y el bienestar entre ellos. Esto se logra a través de una diversidad de tratamientos (tratamientos corporales, tratamientos faciales, tratamientos combinados, etc) y cada uno está compuesto de varias terapias. En este momento dicha empresa necesita que se procesen las terapias que fueron aplicadas durante la semana, de tal manera que se pueda generar ciertas estadísticas y para ello el gerente suministra la siguiente información. Actualmente, la empresa tiene registrada por cada terapia los siguientes datos: código (dato de tipo string), descripción (Masaje Corporal, Masaje Relajante, Depilación, Mesoterapia, etc), precio y tipo de tratamiento al que pertenece la misma (dato de tipo entero). La empresa por los momentos solo trabaja con determinados tipos tratamientos y por cada uno maneja la siguiente información: Tipo de tratamiento (nro. del 1 al 6), descripción y un estatus que indica si el tratamiento está en promoción; para manejar ésta última información, se considera que si el status toma el valor de 1  el tratamiento está en promoción y si toma el valor de 0  no lo está. En la siguiente tabla se muestra la respectiva información. Tipo Descripción del Tratamiento Promoción 1 Tratamiento de Balneoterapia 1 2 Tratamientos Corporales 1 3 Tratamientos Faciales 1 4 Estética Profesional 0 5 Amanon para Caballeros 0 6 Tratamientos Combinados 1 Es importante resaltar que el precio de la terapia tendrá un descuento del 10%, si pertenece a algún tratamiento de los que está en promoción. Elabore un programa usando POO, MVC, Herencia y Vectores que presente un MENÚ con las siguientes opciones: 1. Registrar información de los tratamientos del Spa 2. Registrar información de las terapias. 3. Procesar Servicios Prestados. 4. Reporte Estadístico. 5. Finalizar. Opción 1. (Registrar información de los tratamientos del Spa): Esta opción permite que se cargue por teclado, la información de los tipos de tratamientos ofrecidos por el Spa. Opción 2. (Registrar información de las terapias): Esta opción permite que se cargue por teclado, la información de las terapias que son ofrecidas por el Spa. Opción 3. (Procesar Servicios Prestados): Esta opción permite procesar la información de cada una de las terapias que fueron realizadas durante la semana, para ello debe leer por el teclado el código de la terapia y realizar los respectivos procesos que permitirán generar los requerimientos solicitados. Recuerde que debe realizar todas las validaciones. Opción 4. (Reporte Estadístico): Esta opción muestra a nivel de pantalla, un listado que contiene información relacionada con las terapias aplicadas en cada tratamiento. Recuerde que debe realizar las respectivas validaciones. A continuación se muestra un ejemplo del reporte REPORTE ESTADÍSTICO POR LAS TERAPIAS APLICADAS A CADA CLIENTE CEDULA MONTO A PAGAR XXXXXX XXXX XXXXXX XXXX .. ... .. ... XXXXX XXX Monto Total Ingresado al SPA por terapias realizadas: xxx Opción 5. (Finalizar) * * */ #include "Controlador.h" int main() { int opc; VGeneral vg; Controlador c; do { vg.Limpiar(); vg.ImprimirLineasBlanco(3); vg.ImprimirEncabezado(" M E N U O P C I O N E S"," ======= ===============\n\n"); vg.ImprimirMensaje(" 1. Registrar inf. de los Tratamientos\n"); vg.ImprimirMensaje(" 2. Registrar inf.Terapias\n" ); vg.ImprimirMensaje(" 3. Procesar Terapias a los Clientes\n" ); vg.ImprimirMensaje(" 4. Reporte Estadistico\n"); vg.ImprimirMensaje(" 5. Salir\n\n"); opc = vg.LeerValidarNro(" SELECCIONE SU OPCION : ",1,5); switch (opc) { case 1: c.RegistrarTratamientos(); break; case 2: c.RegistrarTerapias(); break; case 3: c.ProcesarTerapiasClientes(); break; case 4: c.Reporte(); break; } } while(opc != 5); return 0; }
[ "gaboleal123@gmail.com" ]
gaboleal123@gmail.com
de73da16737884b14812568270c69c89a249838f
b53433a087a326afa053b924c045d9d8d9d14b2d
/439A - Devu, the Singer and Churu, the Joker/17714054_15MS_2000K.cpp
54e7bf53a8822a14acf9138283d7492385d73de7
[ "MIT" ]
permissive
cloudzfy/codeforces
cc372049384077d00cad8260ad29c05378cd21e1
d409574c1a4218419aa6e9ddc02fddb7b83455d8
refs/heads/master
2021-01-01T05:21:08.768864
2016-09-27T05:24:00
2016-09-27T05:24:00
57,424,154
1
0
null
null
null
null
UTF-8
C++
false
false
574
cpp
#include <stdio.h> #include <iostream> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> #include <cstring> #include <algorithm> #include <map> #include <stack> using namespace std; int main(int argc, const char * argv[]) { int n, d, t; int sum = 0; int count = 0; cin>>n>>d; for (int i = 0; i < n; i++) { cin>>t; sum += t; if (i != 0) { sum += 10; count += 2; } } if (sum > d) cout<<-1<<endl; else cout<<count + (d - sum) / 5<<endl; return 0; }
[ "cloudzfy@users.noreply.github.com" ]
cloudzfy@users.noreply.github.com
86b0f1a35c24b99bfa70fb6571cbff3698c6881d
15aaa722445ea5088f81fdc09aaebb7188a3489a
/lintcodeStudy/lintcodeStudy/aAddBpro.cpp
e9ad681250a41c25f9ca69a24393140751ad65fb
[]
no_license
testZyhGitHub/mysqlExpert
e98596a5abfedb46a3e99047a7f0d8f873a6fcd3
80dace9fe165f1d23b92e5207e1111124e2f5adf
refs/heads/master
2020-03-27T12:54:37.523447
2019-03-15T09:46:17
2019-03-15T09:46:17
146,577,483
0
0
null
null
null
null
GB18030
C++
false
false
3,747
cpp
#include <stdio.h> // A + B 问题 /* 描述 给出两个整数 aa 和 bb , 求他们的和。 你不需要从输入流读入数据,只需要根据aplusb的两个参数a和b,计算他们的和并返回就行。 说明 a和b都是 32位 整数么? 是的 我可以使用位运算符么? 当然可以 样例 如果 a=1 并且 b=2,返回3。 挑战 显然你可以直接 return a + b,但是你是否可以挑战一下不这样做?(不使用+等算数运算符) */ int aplusb(int aa, int bb) { return aa+bb; } /* 杭电ACM-A+B problem topic: */ /* ACM入门之输入输出格式 A+B for Input-Output Practice (I) */ /* ACM新手之八大输入输出格式 在ACM题库中, 不管是文件输出(输入), 还是标准输出(输入), 都有着一定的格式, 下面我就以杭电1089-----1096为例子, 简单的介绍一下。 */ /* 第一种: A+B for Input-Output Practice (I) 【输入】有多组输入数据, 但没有具体的告诉你有多少组, 只是让你对应每组输入, 应该怎样输出? 【输出】有多组输出,对应着每组输入,每组输出占一行。 */ void aADDb1() { int m = 0; int n = 0; while (EOF != scanf("%d%d", &m, &n)) { m += n; printf("%d\n", m); } } /* 第二种:A+B for Input-Output Practice (II) 【输入】先输入一个整数, 告诉我们接下来有多少组数据, 然后在输入每组数据的具体值。 【输出】有多组输出, 对应着每组输入, 每组输出占一行。 这也是一种常见的输入形式,简单的代码,我们可以先用scanf函数输入第一个整数来确定有多少行,然后在用for循环一组一组的输入。 */ void aADDb2() { int n; int x; int y; int i; scanf("%d", &n); for (i = 1; i <= n; i++) { scanf("%d%d", &x, &y); x += y; printf("%d\n", x); } } /* 第三种: A+B for Input-Output Practice (III) 【输入】有多组输入数据,没有具体的告诉你有多少组,但是题目却告诉你遇见什么结束。 【输出】有多组输出,没对应一组输入都有相应的输出,结束标记不用管! 【代码】这种类型的题目和第一种差不多,但是有一点值得注意,就是要加上结束条件。 你也可以将条件写在while循环的内部,条件满足时break即可。 */ void aADDb3() { int numX = 0; int numY = 0; while (scanf("%d%d", &numX, &numY) && (!(numX==0 && numY==0))) { printf("%d\n", numX+numY); } printf("Out the while loop......\n"); } /* 第四种:A+B for Input-Output Practice (IV) 【输入】输入有多组,并且题目告诉你每组输入遇见什么结束,与第三种不同之处在于,每组输入都有相应的细化。 【输出】没有什么变化,只需要对应输出即可。 这类题目的代码是在第三种代码的基础之上,对于每种输入都进行第二种的精确输入。 */ void aADDb4() { int i = 0; int s = 0; int m = 0; int n = 0; while (scanf("%d", &n) != EOF && n != 0) { s = 0; //for (i = 0; i < n; i++) for (i = 1; i <= n; i++) { scanf("%d", &m); s += m; } printf("%d\n", s); } } /* 根据上边介绍的八种输入输出,我们可以归纳出如下内容: 对于输入,如果没有告诉你有多少组,我们常用while。如果告诉你有多少组,我们用for。 对于输出,输入用while,我们常常判断是否为第一个输出样例,来指定特殊的输出格式。 输入用for,我们常常判断是否为最后的输出样例,来指定特殊的输出格式。 当然输入输出的格式远远不止上边的八种,但它们却是最常见的,特别是前三种是一定要掌握的。 */
[ "zyhnanau86@163.com" ]
zyhnanau86@163.com
3aba178246b875e5ccfea992c9c8638087d8e829
0019f0af5518efe2144b6c0e63a89e3bd2bdb597
/antares/headers/os/support/StopWatch.h
ff1a39d3c98f5cd8366b9409bbf533b499cacc34
[]
no_license
mmanley/Antares
5ededcbdf09ef725e6800c45bafd982b269137b1
d35f39c12a0a62336040efad7540c8c5bce9678a
refs/heads/master
2020-06-02T22:28:26.722064
2010-03-08T21:51:31
2010-03-08T21:51:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
714
h
/* * Copyright 2001-2007, Antares, Inc. All Rights Reserved. * Distributed under the terms of the MIT License. */ #ifndef _STOP_WATCH_H #define _STOP_WATCH_H #include <BeBuild.h> #include <SupportDefs.h> class BStopWatch { public: BStopWatch(const char* name, bool silent = false); virtual ~BStopWatch(); void Suspend(); void Resume(); bigtime_t Lap(); bigtime_t ElapsedTime() const; void Reset(); const char* Name() const; private: virtual void _ReservedStopWatch1(); virtual void _ReservedStopWatch2(); bigtime_t fStart; bigtime_t fSuspendTime; bigtime_t fLaps[10]; int32 fLap; const char* fName; uint32 _reserved[2]; bool fSilent; }; #endif // _STOP_WATCH_H
[ "michael@Inferno.(none)" ]
michael@Inferno.(none)
6446d4a3b7a4fb9587d9dc143fe7d05deb2d4587
775acebaa6559bb12365c930330a62365afb0d98
/external/server/tools/omniORB-4.1.5/include/omniORB4/internal/giopMonitor.h
f269b5124cf135e6340954584c5b8672a1049df1
[]
no_license
Al-ain-Developers/indesing_plugin
3d22c32d3d547fa3a4b1fc469498de57643e9ee3
36a09796b390e28afea25456b5d61597b20de850
refs/heads/main
2023-08-14T13:34:47.867890
2021-10-05T07:57:35
2021-10-05T07:57:35
339,970,603
1
1
null
2021-10-05T07:57:36
2021-02-18T07:33:40
C++
UTF-8
C++
false
false
2,088
h
// -*- Mode: C++; -*- // Package : omniORB // giopMonitor.h Created on: 23 July 2001 // Author : Sai Lai Lo (sll) // // Copyright (C) 2001 AT&T Laboratories Cambridge // // This file is part of the omniORB library // // The omniORB library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free // Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA // // // Description: // *** PROPRIETORY INTERFACE *** // /* $Log$ Revision 1.1.2.2 2002/08/21 06:23:15 dgrisby Properly clean up bidir connections and ropes. Other small tweaks. Revision 1.1.2.1 2001/07/31 16:28:02 sll Added GIOP BiDir support. */ #ifndef __GIOPMONITOR_H__ #define __GIOPMONITOR_H__ OMNI_NAMESPACE_BEGIN(omni) class giopMonitor : public omniTask, public giopServer::Link { public: giopMonitor(giopActiveCollection* c, giopServer* s) : omniTask(omniTask::ImmediateDispatch), pd_collection(c), pd_server(s) { } void execute(); void deactivate() { pd_collection->deactivate(); } giopActiveCollection* collection() const { return pd_collection; } static void notifyReadable(void*,giopConnection*); private: giopActiveCollection* pd_collection; giopServer* pd_server; giopMonitor(); giopMonitor(const giopMonitor&); giopMonitor& operator=(const giopMonitor&); }; OMNI_NAMESPACE_END(omni) #endif // __GIOPRENDEZVOUSER_H__
[ "75730278+Tarekhesham10@users.noreply.github.com" ]
75730278+Tarekhesham10@users.noreply.github.com
31e16c526d6e6920fc6e9df834579ad23f66f7b8
2f43d57de1573954cde75b87fde88647fbdc619c
/main/NodeFactory.cpp
c006fa0209eb409218b0028eb8d1a60a317c2a32
[]
no_license
rafey111/open-cv-sift
c7620127787825ab3bec59af86a4bbe7fd89c9f5
6974a0308a596d4d8a65ceed3fa957f05014f24c
refs/heads/master
2021-01-14T14:11:54.216317
2013-10-16T15:10:07
2013-10-16T15:10:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
134
cpp
#include "NodeFactory.hpp" Node* NodeFactory::createNode(Point* pPoint, bool isVertical) { return new Node(pPoint, isVertical); }
[ "tomasz.kaminski@lincoln.ox.ac.uk" ]
tomasz.kaminski@lincoln.ox.ac.uk
e684b7928f2e61c8ba6785b1f6db4a83a08bfb91
82815230eeaf24d53f38f2a3f144dd8e8d4bc6b5
/Airfoil/wingMotion/wingMotion2D_pimpleFoam/1.9/uniform/time
306dbc77a186e48827d2608aebe45709f5e30015
[ "MIT" ]
permissive
ishantja/KUHPC
6355c61bf348974a7b81b4c6bf8ce56ac49ce111
74967d1b7e6c84fdadffafd1f7333bf533e7f387
refs/heads/main
2023-01-21T21:57:02.402186
2020-11-19T13:10:42
2020-11-19T13:10:42
312,429,902
0
0
null
null
null
null
UTF-8
C++
false
false
1,015
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v1912 | | \\ / A nd | Website: www.openfoam.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "1.9/uniform"; object time; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value 1.90000000000000013; name "1.9"; index 105250; deltaT 1.727115717e-05; deltaT0 1.727115717e-05; // ************************************************************************* //
[ "ishantamrakat24@gmail.com" ]
ishantamrakat24@gmail.com
34c56e702b2ad05eaea865b5e26faa7842dd6045
454f2125c2d49b6be8113e756f5f68fd75678b84
/ZetCodeQt5Exmaple/EventsAndSignals/timer.h
2432ae2aa866632886d4cdc9cf625b1c9ae9f204
[]
no_license
JackLovel/excuise-
c8a6977c96b8d6e41a937212f8e7dfc606328b4b
60418044c9387868043982c071ea1365b0d24057
refs/heads/master
2021-06-27T17:06:16.708054
2020-10-24T03:27:31
2020-10-24T03:27:31
164,762,577
0
0
null
2020-07-17T01:14:39
2019-01-09T01:27:43
JavaScript
UTF-8
C++
false
false
242
h
#ifndef TIMER_H #define TIMER_H #include <QWidget> #include <QLabel> class Timer : public QWidget { public: Timer(QWidget *parent = 0); protected: void timerEvent(QTimerEvent *e); private: QLabel *label; }; #endif // TIMER_H
[ "2101721230@qq.com" ]
2101721230@qq.com
8ecb4c06dbfba8ec4c734462d33c032cefa524cd
0b9178ff7d3db16e6d28106f33c52298d8c04f81
/source/problem/SWE/discretization_IHDG/dist_boundary_conditions/ihdg_swe_dbc_distributed.hpp
479b0836015d2498987ba4a2741dbe6f37606a22
[ "Apache-2.0", "MIT" ]
permissive
bremerm31/dgswemv2
440d3999fd76632e2631d0993509a0adde090762
5ddddfdf1b5f51e9dbc348f2e69f187546649957
refs/heads/master
2021-07-13T05:59:42.005455
2020-04-06T13:45:34
2020-04-06T13:45:34
132,520,141
0
0
MIT
2018-06-27T13:53:49
2018-05-07T21:50:47
C++
UTF-8
C++
false
false
1,979
hpp
#ifndef IHDG_SWE_DBC_DISTRIBUTED_HPP #define IHDG_SWE_DBC_DISTRIBUTED_HPP #include "communication/db_data_exchanger.hpp" namespace SWE { namespace IHDG { namespace DBC { class Distributed { public: DBDataExchanger exchanger; public: Distributed(DBDataExchanger exchanger); template <typename DistributedBoundaryType> void Initialize(DistributedBoundaryType& dbound); template <typename EdgeDistributedType> void ComputeInitTrace(EdgeDistributedType& edge_dbound, const HybMatrix<double, SWE::n_variables>& q_ex); template <typename EdgeDistributedType> void ComputeGlobalKernels(EdgeDistributedType& edge_dbound); }; Distributed::Distributed(DBDataExchanger exchanger) : exchanger(std::move(exchanger)) {} template <typename DistributedBoundaryType> void Distributed::Initialize(DistributedBoundaryType& dbound) {} template <typename EdgeDistributedType> void Distributed::ComputeInitTrace(EdgeDistributedType& edge_dbound, const HybMatrix<double, SWE::n_variables>& q_ex) { auto& dbound = edge_dbound.boundary; auto& boundary = dbound.data.boundary[dbound.bound_id]; auto& edge_state = edge_dbound.edge_data.edge_state; auto& edge_internal = edge_dbound.edge_data.edge_internal; // Our definition of numerical flux implies q_hat = 0.5 * (q_in + q_ex) edge_internal.q_hat_at_gp = (boundary.q_at_gp + q_ex) / 2.0; edge_state.q_hat = edge_dbound.L2Projection(edge_internal.q_hat_at_gp); } template <typename EdgeDistributedType> void Distributed::ComputeGlobalKernels(EdgeDistributedType& edge_dbound) { auto& edge_internal = edge_dbound.edge_data.edge_internal; auto& boundary = edge_dbound.boundary.data.boundary[edge_dbound.boundary.bound_id]; boundary.delta_global_kernel_at_gp = boundary.dF_hat_dq_at_gp; edge_internal.delta_hat_global_kernel_at_gp = boundary.dF_hat_dq_hat_at_gp; edge_internal.rhs_global_kernel_at_gp = boundary.F_hat_at_gp; } } } } #endif
[ "kazbek@ices.utexas.edu" ]
kazbek@ices.utexas.edu
208319e19fa9c18588147b6863fefa133829d845
184b05b1cd272ed2f5c3e9ab76766da81679ed65
/absolute-c++/c05-arrays/selftests/e16.cpp
68c03e14da90fd13dab0b75eefdc00534c765230
[]
no_license
j0sht/csci161
93e1b4db82d65d30ec4c9edcf963646208f0158a
ba1301541ec2a5d19e1c10874fbfdd6caa2590d5
refs/heads/master
2021-03-16T09:42:11.169638
2018-04-29T23:30:20
2018-04-29T23:30:20
117,606,586
0
0
null
null
null
null
UTF-8
C++
false
false
1,059
cpp
/* * Write a function named outOfOrder that takes as parameters an array * of double and an int parameter named size and returns a value of * type int. * * This function will test this array for being out of order, meaning * that the array violates the following condition: * a[0] <= a[1] <= a[2] <= ... * * The function returns -1 if the elements are not out of order; otherwise, * it will return the index of the first element of the array that is * out of order. */ #include <iostream> using namespace std; int outOfOrder(double a[], int size); int main() { double a[10] = {1.2, 2.1, 3.3, 2.5, 4.5, 7.9, 5.4, 8.7, 9.9, 1.0}; double b[4] = { 1.0, 2.0, 3.0, 4.0 }; int index = outOfOrder(a, 10); cout << "index = 3? " << (index == 3) << endl; index = outOfOrder(b, 4); cout << "index = -1? " << (index == -1) << endl; return 0; } int outOfOrder(double a[], int size) { double first = a[0]; for (int i = 1; i < size; i++) { if (first > a[i]) return i; first = a[i]; } return -1; }
[ "jmtate@icloud.com" ]
jmtate@icloud.com
5f62f552e389837c1de26c5326e8e43940b9c61e
7f16b8fca08125c77daead7d1b6e5f9b0541a55d
/VirtualWallet/logic/src/control/releasemapper.cpp
f9c953ec23850d7db4960874d018ef90565bc435
[ "MIT" ]
permissive
joaovicentesouto/INE5417
7497677550a026ecce6e105eb5d6cbb5762fee5a
a238fe248fb6451b5706b4587cfed48f07846ac4
refs/heads/master
2021-01-15T19:04:03.490693
2017-12-11T20:58:14
2017-12-11T20:58:14
99,802,520
0
5
null
2017-11-05T00:43:16
2017-08-09T11:51:12
C++
UTF-8
C++
false
false
4,104
cpp
#include "releasemapper.h" namespace project { ReleaseMapper::ReleaseMapper(QSqlDatabase & _conn, WalletMapper * _walletMapper, BankAccountMapper * _bankAccountMapper, ReleaseTypeMapper * _releaseTypeMapper) : conn(_conn), walletMapper(_walletMapper), bankAccountMapper(_bankAccountMapper), releaseTypeMapper(_releaseTypeMapper) { } ReleaseMapper::~ReleaseMapper() { } Release * ReleaseMapper::getById(int id) { QSqlQuery query(conn); query.exec("SELECT * FROM RLS WHERE ID = " + QString::number(id)); if(query.size() == 0) return nullptr; query.next(); double value = query.value(1).toDouble(); string payment = query.value(4).toString().toStdString(); string op = query.value(5).toString().toStdString(); string date = query.value(6).toString().toStdString(); string desc = query.value(7).toString().toStdString(); ReleaseType * type = releaseTypeMapper->getById(query.value(3).toInt()); Account * acc = walletMapper->getById(query.value(2).toInt()); if (acc == nullptr) acc = bankAccountMapper->getById(query.value(2).toInt()); return new Release(id, value, acc, type, payment, desc, op, date, acc->getUserId()); } list<Release*> ReleaseMapper::getAllReleases(int _userId) { QSqlQuery query(conn); query.exec("SELECT * FROM RLS WHERE USER_ID = " + QString::number(_userId)); list<Release*> releases; while (query.next()) { int id = query.value(0).toInt(); double value = query.value(1).toDouble(); string payment = query.value(4).toString().toStdString(); string op = query.value(5).toString().toStdString(); string date = query.value(6).toString().toStdString(); string desc = query.value(7).toString().toStdString(); ReleaseType * type = releaseTypeMapper->getById(query.value(3).toInt()); Account * acc = walletMapper->getById(query.value(2).toInt()); if (acc == nullptr) acc = bankAccountMapper->getById(query.value(2).toInt()); releases.push_front(new Release(id, value, acc, type, payment, desc, op, date, acc->getUserId())); } return releases; } void ReleaseMapper::put(Release * release) { Release * _release = getById(release->getId()); QSqlQuery query(conn); if (_release != nullptr) { QString cmd("UPDATE RLS SET VALUE = " + QString::number(release->getValue()) + ", ACC_ID = " + QString::number(release->getAccount()->getId()) + ", REL_TYPE = " + QString::number(release->getReleaseType()->getId()) + ", PAY_TYPE = '" + QString::fromStdString(release->getPaymentType()) + "', OP = '" + QString::fromStdString(release->getOperation()) + "', DATE = '" + QString::fromStdString(release->getDate()) + "', DESCP = '" + QString::fromStdString(release->getDescription()) + "' WHERE ID = " + QString::number(_release->getId())); query.exec(cmd); } else { QString cmd("INSERT INTO RLS (VALUE, ACC_ID, REL_TYPE, PAY_TYPE, OP, DATE, DESCP, USER_ID) "); QString cmd2("VALUES(" + QString::number(release->getValue()) + ", " + QString::number(release->getAccount()->getId()) + ", " + QString::number(release->getReleaseType()->getId()) + ", '" + QString::fromStdString(release->getPaymentType()) + "', '" + QString::fromStdString(release->getOperation()) + "', '" + QString::fromStdString(release->getDate()) + "', '" + QString::fromStdString(release->getDescription()) + "', " + QString::number(release->getUserId()) + ");"); query.exec(cmd + cmd2); } delete _release; } void ReleaseMapper::remove(int id) { QSqlQuery query(conn); query.exec("DELETE FROM RLS WHERE ID = " + QString::number(id)); } } // namespace
[ "joaovicentesouto@gmail.com" ]
joaovicentesouto@gmail.com
bc75bb346af98c9d25df24517ec9d42d0f0e94ae
0fbb8295d1c82a18fbb336be916750f6222a2728
/ListOfPoint.hpp
4c882982c18862615635f0cced52d3841092db7d
[]
no_license
sharok007/Airplane-control
58ef57cbbcc7d36aa02fc9eb1796261aca07994e
e2809f7836724b3ac7ac12ea8f4ab0ad0c4bc73d
refs/heads/master
2020-12-30T12:44:27.131324
2017-05-19T00:01:13
2017-05-19T00:01:13
91,238,497
0
0
null
2017-05-14T11:22:00
2017-05-14T11:22:00
null
UTF-8
C++
false
false
392
hpp
#pragma once #include <vector> #include "Point.hpp" class ListOfPoint{ private: std::vector<Point> vecPoint; unsigned int numbOfPoint; public: ListOfPoint(std::vector<Point> _vecP,unsigned int nop); void appened(); void remove(); void setVecPoint(std::vector<Point> _vecP,unsigned int numb); std::vector<Point> getVecPoint(); unsigned int getNumbPoint(); };
[ "smirnovmaksim10@mail.ru" ]
smirnovmaksim10@mail.ru
6d09bb3aca011a44b273dd15fb7c41ae2251b816
6224636e5a771a1fc6be6466aa92433de0ed005e
/OpenFrameworks/LightPaintingApp/src/Main/main.cpp
a5bf3f52a6ba38314dbd5d7c15ec2b4d4c8b9494
[ "MIT" ]
permissive
undessens/LightPainting
17861f69e0e52d170d5e2f43bfc1f551ce500b8d
6342198c1e37ffe223423e5c4c1b62d47ea82332
refs/heads/master
2020-09-20T08:49:03.411673
2019-08-09T17:33:50
2019-08-09T17:33:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
368
cpp
#include "ofMain.h" #include "LightPaintingApp.h" //======================================================================== int main( ){ ofSetupOpenGL(1024,768, OF_WINDOW); // <-------- setup the GL context // this kicks off the running of my app // can be OF_WINDOW or OF_FULLSCREEN // pass in width and height too: ofRunApp( new LightPaintingApp()); }
[ "yo@imanolgomez.net" ]
yo@imanolgomez.net
dacc37c2007e2607de9bfaed7f2fb63a71dd4e69
5cc88e2032cffb4f562a643fcb677efee36d0da5
/Source/Fonts.h
e59498fe52df694d9759df64f2c91b1c302d3a99
[]
no_license
guorenxu/StarnightRPGPrototype
fa56f62281c612b9d8eb9161ed932574e9d6da0e
bf4ed4e902d237655f1f79e365539444135cddf1
refs/heads/master
2021-01-10T10:57:47.819464
2016-01-09T02:09:24
2016-01-09T02:09:24
49,306,683
0
0
null
null
null
null
UTF-8
C++
false
false
580
h
#ifndef _FONTS_H #define _FONTS_H 1 #include "CString" #include <cstdlib> #include <stdio.h> #include <string> using namespace std; class Font { public: Font(int Size, int Alpha, int Type); ~Font(){}; void Prepare(); //Initialize Font void Font::Draw(int Alpha, int R, int G, int B, int LF, int TP, int BM, int RT, char* String, int Draw_Number, int Style); LPD3DXFONT ffont; //Font Holders int ftype; //Font type, eg. Arial int fb_alpha; int f_alpha; int fo_alpha; int fsize; }; #endif
[ "guoren.xu@loop.colum.edu" ]
guoren.xu@loop.colum.edu
fcdf346d86e372d8488a11a78f6ab676ae1cda8d
99ed5156c9b83d22dcd7c8a29937825694f4f36d
/dll/ALL/Demo示例/1-MFC综合示例(人脸库、人脸底图)/Config/DomeState.cpp
3f6f320f7fcc1e9618fa98a8a6a8319f96b69f22
[ "MIT" ]
permissive
zyx030613/algorithm_its
73e862988f375a73e517db4f39b8f9005a819609
eae3628a498d2bd9d61487b53b9cdde23b99e314
refs/heads/master
2020-04-25T07:53:45.586587
2019-12-03T06:37:26
2019-12-03T06:37:26
172,627,700
0
1
null
null
null
null
UTF-8
C++
false
false
5,298
cpp
// DomeState.cpp : implementation file // #include "stdafx.h" #include "NetClientDemo.h" #include "DomeState.h" #define NORMAL_STATE 0 #define FAIL_STATE 1 #define NORMAL "Normal" #define FAIL "Not Normal" // CLS_DomeState dialog IMPLEMENT_DYNAMIC(CLS_DomeState, CDialog) CLS_DomeState::CLS_DomeState(CWnd* pParent /*=NULL*/) : CLS_BasePage(CLS_DomeState::IDD, pParent) { m_iLogonID = -1; m_iChannelNo = 0; m_iStreamNO = 0; } CLS_DomeState::~CLS_DomeState() { } void CLS_DomeState::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_EDIT_CAMERA_STATE, m_edtCameraState); DDX_Control(pDX, IDC_EDIT_HLimit, m_edtHLimit); DDX_Control(pDX, IDC_EDIT_VLimit, m_edtVLimit); DDX_Control(pDX, IDC_EDIT_Interface, m_edtInterface); DDX_Control(pDX, IDC_EDIT_TSensor, m_edtTmpSensor); DDX_Control(pDX, IDC_EDIT_Temp, m_edtTemperature); DDX_Control(pDX, IDC_EDIT_TempScale, m_edtTmpScale); DDX_Control(pDX, IDC_EDIT_PublishData, m_edtPublishDate); } BEGIN_MESSAGE_MAP(CLS_DomeState, CDialog) ON_BN_CLICKED(IDC_BUTTON_ASK_DOME_STATE, &CLS_DomeState::OnBnClickedButtonAskDomeState) ON_WM_SHOWWINDOW() END_MESSAGE_MAP() // CLS_DomeState message handlers BOOL CLS_DomeState::OnInitDialog() { CLS_BasePage::OnInitDialog(); UI_UpdateDialog(); UpdatePageUI(); // TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CLS_DomeState::OnChannelChanged( int _iLogonID,int _iChannelNo,int _iStreamNo ) { m_iLogonID = _iLogonID; if (_iChannelNo < 0) { m_iChannelNo = 0; } else { m_iChannelNo = _iChannelNo; } if (_iStreamNo < 0) { m_iStreamNO = 0; } else { m_iStreamNO = _iStreamNo; } } void CLS_DomeState::OnLanguageChanged( int _iLanguage ) { UI_UpdateDialog(); UpdatePageUI(); } void CLS_DomeState::UpdatePageUI() { if (m_iLogonID == -1 || m_iChannelNo == -1) { return; } TSystemState str = {0}; TSystemState* pstrTSystemState = &str; pstrTSystemState->iSize = sizeof(TSystemState); int iRet = NetClient_GetDeviceState(m_iLogonID, m_iChannelNo, DEVICE_STATE_SYSTEM ,(int*)(pstrTSystemState)); if (iRet < 0) { AddLog(LOG_TYPE_FAIL, "", "[CLS_DomeState::NetClient_GetDeviceState] Get fail,error = %d", GetLastError()); } else { if (NORMAL_STATE == pstrTSystemState->iCamera) { SetDlgItemTextEx(IDC_EDIT_CAMERA_STATE, IDS_NORMAL); } else { SetDlgItemTextEx(IDC_EDIT_CAMERA_STATE, IDS_ABNORMAL); } if (NORMAL_STATE == pstrTSystemState->iHLimit) { SetDlgItemTextEx(IDC_EDIT_HLimit, IDS_NORMAL); } else { SetDlgItemTextEx(IDC_EDIT_HLimit, IDS_ABNORMAL); } if (NORMAL_STATE == pstrTSystemState->iVLimit) { SetDlgItemTextEx(IDC_EDIT_VLimit, IDS_NORMAL); } else { SetDlgItemTextEx(IDC_EDIT_VLimit, IDS_ABNORMAL); } if (NORMAL_STATE == pstrTSystemState->iInterface) { SetDlgItemTextEx(IDC_EDIT_Interface, IDS_NORMAL); } else { SetDlgItemTextEx(IDC_EDIT_Interface, IDS_ABNORMAL); } if (NORMAL_STATE == pstrTSystemState->iTSensor) { SetDlgItemTextEx(IDC_EDIT_TSensor, IDS_NORMAL); } else { SetDlgItemTextEx(IDC_EDIT_TSensor, IDS_ABNORMAL); } int iTemperature = pstrTSystemState->temperature; SetDlgItemInt(IDC_EDIT_Temp, iTemperature); if (0 == pstrTSystemState->itemperatureScale) { m_edtTmpScale.SetWindowText(GetTextEx(IDS_Centigrade)); } else if (1 == pstrTSystemState->itemperatureScale) { m_edtTmpScale.SetWindowText(GetTextEx(IDS_Fahrenheit)); } else { m_edtTmpScale.SetWindowText(GetTextEx(IDS_Kelvin)); } CString strPublishDate; strPublishDate.Format("%d:%d:%d:%d:%d:%d", pstrTSystemState->strPublishData.iYear , pstrTSystemState->strPublishData.iMonth, pstrTSystemState->strPublishData.iDay , pstrTSystemState->strPublishData.iHour, pstrTSystemState->strPublishData.iMinute , pstrTSystemState->strPublishData.iSecond); m_edtPublishDate.SetWindowText(strPublishDate); } } void CLS_DomeState::OnParamChangeNotify(int _iLogonID, int _iChannelNo, int _iParaType,void* _pPara,int _iUserData) { switch(_iParaType) { case PARA_DOME_SYETEM: UpdatePageUI(); break; default: break; } } void CLS_DomeState::UI_UpdateDialog() { SetDlgItemTextEx(IDC_STATIC_PublishData, IDS_PUBILSH_DATE); SetDlgItemTextEx(IDC_STATIC_CAMERA_STATE, IDS_CAMERA_STATUS); SetDlgItemTextEx(IDC_STATIC_HLimit, IDS_LEVEL_LIMIT); SetDlgItemTextEx(IDC_STATIC_VLimit, IDS_VERTICAL_LIMIT); SetDlgItemTextEx(IDC_STATIC_INTERFACE, IDS_INTERFACE); SetDlgItemTextEx(IDC_STATIC_TSensor, IDS_SENSOR); SetDlgItemTextEx(IDC_STATIC_TEMP, IDS_TEMPERATURE); SetDlgItemTextEx(IDC_BUTTON_ASK_DOME_STATE, IDS_DOME_STATUS_INFO); } void CLS_DomeState::OnBnClickedButtonAskDomeState() { // TODO: Add your control notification handler code here int iRet = NetClient_CheckDeviceState(m_iLogonID, m_iChannelNo, DEVICE_STATE_SYSTEM); if (iRet<0) { AddLog(LOG_TYPE_FAIL, "", "[CLS_DomeState::OnBnClickedButtonAskDomeState]NetClient_CheckDeviceState(LogonID=%d,ChanNo=%d)", m_iLogonID, m_iChannelNo); } } void CLS_DomeState::OnShowWindow(BOOL bShow, UINT nStatus) { CLS_BasePage::OnShowWindow(bShow, nStatus); // TODO: Add your message handler code here UpdatePageUI(); }
[ "orchidaroma@126.com" ]
orchidaroma@126.com
3c8824625a1457bc97f769cf46217944bd962e75
14bfb426c44212109a49a0bd4047fb85ce2bbba8
/숙제1/EBR_LF/EBR_LF/LFSKIPLIST.cpp
9e83ed0c0b7eabe6a9a98e5fd963da9fc7937933
[]
no_license
jayong93/2020IssueOfParallelProcessing
f84375888b12608fdd22699f1716bfeaf80a59ab
fbdef80cb151c80f65b7b61f572d4f656ade8c37
refs/heads/master
2021-05-17T11:14:35.168928
2020-06-22T15:04:47
2020-06-22T15:04:47
250,751,022
0
0
null
null
null
null
UTF-8
C++
false
false
14,642
cpp
#include <mutex> #include <thread> #include <iostream> #include <chrono> #include <vector> #include <mutex> #include <memory> #include <atomic> using namespace std; using namespace chrono; static const int NUM_TEST = 4000000; static const int RANGE = 1000; static const int MAX_LEVEL = 10; constexpr unsigned MAX_THREAD = 32; class LFSKNode; struct EpochNode { LFSKNode* ptr; unsigned long long epoch; EpochNode(LFSKNode* ptr, unsigned long long epoch) : ptr{ ptr }, epoch{ epoch } {} }; atomic_ullong g_epoch; atomic_ullong* t_epochs[MAX_THREAD]; thread_local vector<EpochNode> retired_list; thread_local unsigned tid; thread_local unsigned counter; constexpr unsigned epoch_freq = 20; constexpr unsigned empty_freq = 10; void retire(LFSKNode* node) { retired_list.emplace_back(node, g_epoch.load(memory_order_relaxed)); ++counter; if (counter % epoch_freq == 0) { g_epoch.fetch_add(1, memory_order_relaxed); } if (counter % empty_freq == 0) { auto min_epoch = ULLONG_MAX; for (auto& epoch : t_epochs) { auto e = epoch->load(memory_order_relaxed); if (min_epoch > e) { min_epoch = e; } } auto removed_it = remove_if(retired_list.begin(), retired_list.end(), [min_epoch](auto& r_node) { if (r_node.epoch < min_epoch) { delete r_node.ptr; return true; } return false; }); retired_list.erase(removed_it, retired_list.end()); } } void start_op() { t_epochs[tid]->store(g_epoch.load(memory_order_relaxed), memory_order_relaxed); } void end_op() { t_epochs[tid]->store(ULLONG_MAX, memory_order_relaxed); } bool Marked(LFSKNode* curr) { int add = reinterpret_cast<int> (curr); return ((add & 0x1) == 0x1); } LFSKNode* GetReference(LFSKNode* curr) { int addr = reinterpret_cast<int> (curr); return reinterpret_cast<LFSKNode*>(addr & 0xFFFFFFFE); } LFSKNode* Get(LFSKNode* curr, bool* marked) { int addr = reinterpret_cast<int> (curr); *marked = ((addr & 0x01) != 0); return reinterpret_cast<LFSKNode*>(addr & 0xFFFFFFFE); } LFSKNode* AtomicMarkableReference(LFSKNode* node, bool mark) { int addr = reinterpret_cast<int>(node); if (mark) addr = addr | 0x1; else addr = addr & 0xFFFFFFFE; return reinterpret_cast<LFSKNode*>(addr); } LFSKNode* Set(LFSKNode* node, bool mark) { int addr = reinterpret_cast<int>(node); if (mark) addr = addr | 0x1; else addr = addr & 0xFFFFFFFE; return reinterpret_cast<LFSKNode*>(addr); } class LFSKNode { public: int key; LFSKNode* volatile next[MAX_LEVEL]; int topLevel; atomic_uint ref_count; // 보초노드에 관한 생성자 LFSKNode() : ref_count{ MAX_LEVEL } { for (int i = 0; i < MAX_LEVEL; i++) { next[i] = AtomicMarkableReference(NULL, false); } topLevel = MAX_LEVEL; } LFSKNode(int myKey) : ref_count{ MAX_LEVEL } { key = myKey; for (int i = 0; i < MAX_LEVEL; i++) { next[i] = AtomicMarkableReference(NULL, false); } topLevel = MAX_LEVEL; } // 일반노드에 관한 생성자 LFSKNode(int x, int height) : ref_count{ height + 1 } { key = x; for (int i = 0; i < MAX_LEVEL; i++) { next[i] = AtomicMarkableReference(NULL, false); } topLevel = height; } void InitNode() { key = 0; for (int i = 0; i < MAX_LEVEL; i++) { next[i] = AtomicMarkableReference(NULL, false); } topLevel = MAX_LEVEL; } void InitNode(int x, int top) { key = x; for (int i = 0; i < MAX_LEVEL; i++) { next[i] = AtomicMarkableReference(NULL, false); } topLevel = top; ref_count.store(top + 1, memory_order_relaxed); } bool CompareAndSet(int level, LFSKNode* old_node, LFSKNode* next_node, bool old_mark, bool next_mark) { int old_addr = reinterpret_cast<int>(old_node); if (old_mark) old_addr = old_addr | 0x1; else old_addr = old_addr & 0xFFFFFFFE; int next_addr = reinterpret_cast<int>(next_node); if (next_mark) next_addr = next_addr | 0x1; else next_addr = next_addr & 0xFFFFFFFE; return atomic_compare_exchange_strong((atomic_int*)(&next[level]), &old_addr, next_addr); //int prev_addr = InterlockedCompareExchange(reinterpret_cast<long *>(&next[level]), next_addr, old_addr); //return (prev_addr == old_addr); } }; class LFSKSET { public: LFSKNode* head; LFSKNode* tail; LFSKSET() { head = new LFSKNode(0x80000000); tail = new LFSKNode(0x7FFFFFFF); for (int i = 0; i < MAX_LEVEL; i++) { head->next[i] = AtomicMarkableReference(tail, false); } } void Init() { LFSKNode* curr = head->next[0]; while (curr != tail) { LFSKNode* temp = curr; curr = GetReference(curr->next[0]); delete temp; } for (int i = 0; i < MAX_LEVEL; i++) { head->next[i] = AtomicMarkableReference(tail, false); } } bool Find(int x, LFSKNode* preds[], LFSKNode* succs[]) { int bottomLevel = 0; bool marked = false; bool snip; LFSKNode* pred = NULL; LFSKNode* curr = NULL; LFSKNode* succ = NULL; retry: while (true) { pred = head; for (int level = MAX_LEVEL - 1; level >= bottomLevel; level--) { curr = GetReference(pred->next[level]); while (true) { succ = curr->next[level]; while (Marked(succ)) { //표시되었다면 제거 snip = pred->CompareAndSet(level, curr, succ, false, false); if (!snip) goto retry; // if (level == bottomLevel) freelist.free(curr); /* * reference counting 방식이 아니라면 오류가 발생할 수 밖에 없다 * 만약 * 1. A thread가 x값에 대해 Add하려고 시도하면서 Find 호출 도중 level 1에서 * pred와 succ(x 값을 가진 노드)를 찾음 * 2. A thread가 잠시 멈춘 사이에 B thread가 x 노드에 대해 Remove를 하면서 * 전부 marking 하고 정지. * 3. A thread가 다시 깨어나 level 0 에서 x 노드를 찾는데, marking 된 것을 * 확인하고 CAS로 자료구조에서 제거하고 retire까지 시킴 * 4. 그 뒤 A thread가 이어서 x 값에 대한 새로운 노드를 자료구조에 끼워 넣는데 * level 1에서는 retire된 x 노드의 포인터가 아직 남아있고, 이 주소가 새로운 * x 노드의 next로 설정됨. * 5. 결과적으로 retire된 노드의 주소값이 아직 자료구조에 남은 상태로 존재하게 됨. */ int ref_count = curr->ref_count.fetch_sub(1, memory_order_relaxed); if (ref_count == 1) { retire(curr); } else if (ref_count == 0) { fprintf(stderr, "Node's ref count was 0\n"); exit(-1); } curr = GetReference(pred->next[level]); succ = curr->next[level]; } // 표시 되지 않은 경우 // 키값이 현재 노드의 키값보다 작다면 pred전진 if (curr->key < x) { pred = curr; curr = GetReference(succ); // 키값이 그렇지 않은 경우 // curr키는 대상키보다 같거나 큰것이므로 pred의 키값이 // 대상 노드의 바로 앞 노드가 된다. } else { break; } } preds[level] = pred; succs[level] = curr; } return (curr->key == x); } } bool Add(int x) { start_op(); int topLevel = 0; while ((rand() % 2) == 1) { topLevel++; if (topLevel >= MAX_LEVEL - 1) break; } int bottomLevel = 0; LFSKNode* preds[MAX_LEVEL]; LFSKNode* succs[MAX_LEVEL]; LFSKNode* newNode = new LFSKNode; while (true) { bool found = Find(x, preds, succs); // 대상 키를 갖는 표시되지 않은 노드를 찾으면 키가 이미 집합에 있으므로 false 반환 if (found) { end_op(); delete newNode; return false; } else { newNode->InitNode(x, topLevel); for (int level = bottomLevel; level <= topLevel; level++) { LFSKNode* succ = succs[level]; // 현재 새노드의 next는 표시되지 않은 상태, find()가 반환반 노드를 참조 newNode->next[level] = Set(succ, false); } //find에서 반환한 pred와 succ의 가장 최하층을 먼저 연결 LFSKNode* pred = preds[bottomLevel]; LFSKNode* succ = succs[bottomLevel]; newNode->next[bottomLevel] = Set(succ, false); //pred->next가 현재 succ를 가리키고 있는지 않았는지 확인하고 newNode와 참조설정 if (!pred->CompareAndSet(bottomLevel, succ, newNode, false, false)) // 실패일경우는 next값이 변경되었으므로 다시 호출을 시작 continue; for (int level = bottomLevel + 1; level <= topLevel; level++) { while (true) { pred = GetReference(preds[level]); succ = GetReference(succs[level]); // 최하층 보다 높은 층들을 차례대로 연결 // 연결을 성공할경우 다음단계로 넘어간다 while (true) { bool mark; LFSKNode* t = Get(newNode->next[level], &mark); if (true == newNode->CompareAndSet(level, t, succ, mark, mark)) break; } if (pred->CompareAndSet(level, succ, newNode, false, false)) break; Find(x, preds, succs); /* 아래는 이전에 시도했던 해결법(by 소윤)인데 문제가 있다. Add thread가 첫번째 CAS(marking이 됐는지 확인하는 CAS)에 성공한 직후 잠깐 멈췄을 때, Remove thread가 이 노드의 모든 층에 marking하고 Find를 호출해서 retire까지 했을 수 있다. 그리고 다시 깨어난 Add thread가 두번째 CAS(실제 자료구조에 newNode를 삽입하는 CAS)에 성공할 수 있다. 이 level에서는 pred의 next가 바뀌지 않았을 수도 있기 때문. 그렇게 되면 뒷처리를 위해 Add thread가 Find를 호출하기 전에 다른 thread가 새로운 epoch으로 method를 시작해서 이미 retire된 이 노드를 볼 수 있고, 그 포인터가 local하게 저장됐을 수도 있다. 그러면 이미 늦어서 Add thread가 Find를 호출해서 뒷정리하고 끝내면 이 노드의 메모리는 할당 해제된다. 즉, 새로운 epoch으로 method를 시작한 thread는 delete된 메모리 주소를 참조할 수 있다. */ //auto new_next = newNode->next[level]; //if (true == newNode->CompareAndSet(level, new_next, succ, false, false)) { // if (true == pred->CompareAndSet(level, succ, newNode, false, false)) // break; // Find(x, preds, succs); //} //else { // Find(x, preds, succs); // end_op(); // return true; //} } } Find(x, preds, succs); //모든 층에서 연결되었으면 true반환 end_op(); return true; } } } bool Remove(int x) { start_op(); int bottomLevel = 0; LFSKNode* preds[MAX_LEVEL]; LFSKNode* succs[MAX_LEVEL]; LFSKNode* succ; while (true) { bool found = Find(x, preds, succs); if (!found) { //최하층에 제거하려는 노드가 없거나, 짝이 맞는 키를 갖는 노드가 표시 되어 있다면 false반환 end_op(); return false; } else { LFSKNode* nodeToRemove = succs[bottomLevel]; //최하층을 제외한 모든 노드의 next와 mark를 읽고 AttemptMark를 이용하여 연결에 표시 for (int level = nodeToRemove->topLevel; level >= bottomLevel + 1; level--) { succ = nodeToRemove->next[level]; // 만약 연결이 표시되어있으면 메서드는 다음층으로 이동 // 그렇지 않은 경우 다른 스레드가 병행을 햇다는 뜻이므로 현재 층의 연결을 다시 읽고 // 연결에 다시 표시하려고 시도한다. while (!Marked(succ)) { nodeToRemove->CompareAndSet(level, succ, succ, false, true); succ = nodeToRemove->next[level]; } } //이부분에 왔다는 것은 최하층을 제외한 모든 층에 표시했다는 의미 bool marked = false; succ = nodeToRemove->next[bottomLevel]; while (true) { //최하층의 next참조에 표시하고 성공했으면 Remove()완료 bool iMarkedIt = nodeToRemove->CompareAndSet(bottomLevel, succ, succ, false, true); succ = succs[bottomLevel]->next[bottomLevel]; if (iMarkedIt) { Find(x, preds, succs); end_op(); return true; } else if (Marked(succ)) { end_op(); return false; } } } } } bool Contains(int x) { start_op(); int bottomLevel = 0; bool marked = false; LFSKNode* pred = head; LFSKNode* curr = NULL; LFSKNode* succ = NULL; for (int level = MAX_LEVEL - 1; level >= bottomLevel; level--) { curr = GetReference(pred->next[level]); while (true) { succ = curr->next[level]; while (Marked(succ)) { curr = GetReference(curr->next[level]); succ = curr->next[level]; } if (curr->key < x) { pred = curr; curr = GetReference(succ); } else { break; } } } auto retval = (curr->key == x); end_op(); return retval; } void Dump() { LFSKNode* curr = head; printf("First 20 entries are : "); for (int i = 0; i < 20; ++i) { curr = curr->next[0]; if (NULL == curr) break; printf("%d(%d), ", curr->key, curr->topLevel); } printf("\n"); } }; LFSKSET my_set; void benchmark(int num_thread, int thread_id) { tid = thread_id; for (int i = 0; i < NUM_TEST / num_thread; ++i) { // if (0 == i % 100000) cout << "."; switch (rand() % 3) { case 0: my_set.Add(rand() % RANGE); break; case 1: my_set.Remove(rand() % RANGE); break; case 2: my_set.Contains(rand() % RANGE); break; default: cout << "ERROR!!!\n"; exit(-1); } } } int main() { for (auto& epoch : t_epochs) { epoch = new atomic_ullong{ ULLONG_MAX }; } vector <thread> worker; for (int num_thread = 1; num_thread <= MAX_THREAD; num_thread *= 2) { g_epoch.store(0, memory_order_relaxed); for (auto& epoch : t_epochs) { epoch->store(ULLONG_MAX, memory_order_relaxed); } my_set.Init(); worker.clear(); auto start_t = high_resolution_clock::now(); for (int i = 0; i < num_thread; ++i) worker.push_back(thread{ benchmark, num_thread, i }); for (auto& th : worker) th.join(); auto du = high_resolution_clock::now() - start_t; my_set.Dump(); cout << num_thread << " Threads, Time = "; cout << duration_cast<milliseconds>(du).count() << " ms\n"; } }
[ "jayong93@gmail.com" ]
jayong93@gmail.com
b752801bde877b9719aee25dceb397bf87849142
1180641c135909710837767ac5d12ff9aafc1626
/PC1/CodeblockPC1/Time/Serial.h
2f7ee300195cbe5e106deee86ab9347bd25c9acb
[]
no_license
hiiamtin/DataCom_Asm61_EZ
a46f97d05e9ca51e6a932bf38c2496a72c86e9f7
163778fec31b3ab16fac7844237b00457fa74b71
refs/heads/master
2020-04-06T18:33:19.255915
2018-11-15T12:06:38
2018-11-15T12:06:38
157,702,579
1
2
null
2018-11-15T12:01:06
2018-11-15T11:47:49
C++
UTF-8
C++
false
false
5,456
h
#ifndef SERIALCLASS_H_INCLUDED #define SERIALCLASS_H_INCLUDED #define ARDUINO_WAIT_TIME 2000 #include <windows.h> #include <stdio.h> #include <stdlib.h> class Serial { private: //Serial comm handler HANDLE hSerial; //Connection status bool connected; //Get various information about the connection COMSTAT status; //Keep track of last error DWORD errors; public: //Initialize Serial communication with the given COM port Serial(const char *portName); //Close the connection ~Serial(); //Read data in a buffer, if nbChar is greater than the //maximum number of bytes available, it will return only the //bytes available. The function return -1 when nothing could //be read, the number of bytes actually read. int ReadData(char *buffer, unsigned int nbChar); //Writes data from a buffer through the Serial connection //return true on success. bool WriteData(const char *buffer, unsigned int nbChar); //Check if we are actually connected bool IsConnected(); }; #endif // SERIALCLASS_H_INCLUDED Serial::Serial(const char *portName) { //We're not yet connected this->connected = false; //Try to connect to the given port throuh CreateFile this->hSerial = CreateFileA(portName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); //Check if the connection was successfull if(this->hSerial==INVALID_HANDLE_VALUE) { //If not success full display an Error if(GetLastError()==ERROR_FILE_NOT_FOUND){ //Print Error if neccessary printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName); } else { printf("ERROR!!!"); } } else { //If connected we try to set the comm parameters DCB dcbSerialParams = {0}; //Try to get the current if (!GetCommState(this->hSerial, &dcbSerialParams)) { //If impossible, show an error printf("failed to get current serial parameters!"); } else { //Define serial connection parameters for the arduino board dcbSerialParams.BaudRate=CBR_115200; dcbSerialParams.ByteSize=8; dcbSerialParams.StopBits=ONESTOPBIT; dcbSerialParams.Parity=NOPARITY; //Setting the DTR to Control_Enable ensures that the Arduino is properly //reset upon establishing a connection dcbSerialParams.fDtrControl = DTR_CONTROL_ENABLE; //Set the parameters and check for their proper application if(!SetCommState(hSerial, &dcbSerialParams)) { printf("ALERT: Could not set Serial Port parameters"); } else { //If everything went fine we're connected this->connected = true; //Flush any remaining characters in the buffers PurgeComm(this->hSerial, PURGE_RXCLEAR | PURGE_TXCLEAR); //We wait 2s as the arduino board will be reseting Sleep(ARDUINO_WAIT_TIME); } } } } Serial::~Serial() { //Check if we are connected before trying to disconnect if(this->connected) { //We're no longer connected this->connected = false; //Close the serial handler CloseHandle(this->hSerial); } } int Serial::ReadData(char *buffer, unsigned int nbChar) { //Number of bytes we'll have read DWORD bytesRead; //Number of bytes we'll really ask to read unsigned int toRead; //Use the ClearCommError function to get status info on the Serial port ClearCommError(this->hSerial, &this->errors, &this->status); //Check if there is something to read if(this->status.cbInQue>0) { //If there is we check if there is enough data to read the required number //of characters, if not we'll read only the available characters to prevent //locking of the application. if(this->status.cbInQue>nbChar) { toRead = nbChar; } else { toRead = this->status.cbInQue; } //Try to read the require number of chars, and return the number of read bytes on success if(ReadFile(this->hSerial, buffer, toRead, &bytesRead, NULL) ) { return bytesRead; } } //If nothing has been read, or that an error was detected return 0 return 0; } bool Serial::WriteData(const char *buffer, unsigned int nbChar) { DWORD bytesSend; //Try to write the buffer on the Serial port if(!WriteFile(this->hSerial, (void *)buffer, nbChar, &bytesSend, 0)) { //In case it don't work get comm error and return false ClearCommError(this->hSerial, &this->errors, &this->status); return false; } else return true; } bool Serial::IsConnected() { //Simply return the connection status return this->connected; }
[ "60010866@kmitl.ac.th" ]
60010866@kmitl.ac.th
6dea0cbdd04db20e7b15edd10b81d7f7979ae506
6cf49b15039dbe8c65af72d044ef28c7d6170db9
/Bingo/Testing/MenuOptionTester.h
33a74fa8e4ac2fd4d1bffd9402fcd1fa4ef59657
[]
no_license
drakeaharper/cs1440
cd0d529d049d010b1a41cda7687d5d65b3b82df6
373d65ffbb6214f12b13dec58e4b64f47e78b737
refs/heads/master
2021-01-11T14:54:02.260140
2017-04-30T00:43:17
2017-04-30T00:43:17
80,245,002
0
0
null
null
null
null
UTF-8
C++
false
false
235
h
// // Created by Stephen Clyde on 2/20/17. // #ifndef BINGO_MENU_OPTION_TESTER_H #define BINGO_MENU_OPTION_TESTER_H class MenuOptionTester { public: void testConstructorAndGetter(); }; #endif //BINGO_MENU_OPTION_TESTER_H
[ "drakeaharper@gmail.com" ]
drakeaharper@gmail.com
a5bb968ca02914566f7d151b643cede7ac041e09
2d13a41436ad89c3f743748c4a3691b71a48c5f1
/arduino/Blink/Blink.ino
698534618028c2b7bb02e9eb2d6bb3001135db79
[]
no_license
chadondata/charpsberry_piduino
8a6625414cb1024d5afd32a6504a6762b8117e27
b4dc1cb8259dcef2142faac89da7d1f4c869d331
refs/heads/master
2020-05-19T01:49:25.875867
2019-10-22T17:00:17
2019-10-22T17:00:17
184,766,516
0
0
null
null
null
null
UTF-8
C++
false
false
1,243
ino
/* Blink Turns an LED on for one second, then off for one second, repeatedly. Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to the correct LED pin independent of which board is used. If you want to know what pin the on-board LED is connected to on your Arduino model, check the Technical Specs of your board at: https://www.arduino.cc/en/Main/Products modified 8 May 2014 by Scott Fitzgerald modified 2 Sep 2016 by Arturo Guadalupi modified 8 Sep 2016 by Colby Newman This example code is in the public domain. http://www.arduino.cc/en/Tutorial/Blink */ // the setup function runs once when you press reset or power the board void setup() { // initialize digital pin LED_BUILTIN as an output. pinMode(LED_BUILTIN, OUTPUT); } // the loop function runs over and over again forever void loop() { digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(random(1000)); // wait for a second digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW delay(random(1000)); // wait for a second }
[ "chad.harper@gmail.com" ]
chad.harper@gmail.com
a00d1a4ee5ab964fa6720af0348fe5a5344eb757
26254025c6550405b3e80fe190face2fd281dc16
/BasicDataAbstractions/QueueAndStack/LinkedStack.h
1b65a008c018434395490eeeea2f276001c5d8a7
[]
no_license
wfei26/DataStructure
8331fef0eb49380ff90af25496cd0067d0bb9a44
eb9eab49096d901c485fc5c4bd8df0dcf91ed100
refs/heads/master
2018-12-07T02:14:37.927264
2018-09-21T07:40:24
2018-09-21T07:40:24
107,227,227
0
0
null
null
null
null
UTF-8
C++
false
false
1,153
h
/* Author: Wei Fei * KUID: 2538810 * Date: 11/01/13 * FileName: LinkedStack.h * Description: the header file of LinkedStack.cpp. */ #ifndef LINKED_STACK #define LINKED_STACK #include "StackInterface.h" #include "Node.h" /** * Stack class */ template<class ItemType> class LinkedStack : public StackInterface<ItemType> { private: /** * Top node of the stack */ Node<ItemType> *top; public: /** * Default constructor */ LinkedStack(); /** * Destructor */ virtual ~LinkedStack(); /** * Determines whether the stack is empty or not * * @return true if the stack is empty and false otherwise */ bool isEmpty() const; /** * Pushes an item to the stack * * @param item the item to be pushed */ void push(const ItemType& item) throw (PrecondViolatedExcep); /** * Pops a node from the stack */ void pop() throw (PrecondViolatedExcep); /** * Returns the top item * * @return top item in the stack */ ItemType peek() const throw (PrecondViolatedExcep); }; #include "LinkedStack.cpp" #endif
[ "weifei6441@gmail.com" ]
weifei6441@gmail.com
6efda1006a869002b106c1e1978dc2d53d71d671
49514076e57cd43a723b3ce54237e01197c59cab
/graphics/draw_text.cpp
3c1d8c2c0a5c37f8dd693e55b1cca1bc12676f46
[]
no_license
isaacph/sc2clone
0649d76c7f73a00eeefe5516ae145db5205906bf
35abde5c919f670f9916175531976af41388e4e7
refs/heads/master
2023-02-07T20:45:44.060281
2020-12-28T22:44:00
2020-12-28T22:44:00
266,593,507
0
0
null
null
null
null
UTF-8
C++
false
false
19,032
cpp
// // Created by isaac on 9/27/2019. // #include <iostream> #include "draw.h" #include <ft2build.h> #include <glm/gtc/type_ptr.hpp> #include FT_FREETYPE_H #include "shader_util.h" #include "gl_config.h" DrawText::DrawText() : vao(-1), vbo(-1), ftLibrary() { std::string vsource = "ILLEGAL", fsource = "ILLEGAL"; int posAttrib, texAttrib; try { vsource = VERTEX_SHADER; fsource = FRAGMENT_SHADER; posAttrib = GLOBAL_ATTRIBUTE_LOCATIONS.at("position"); texAttrib = GLOBAL_ATTRIBUTE_LOCATIONS.at("texture"); assert(posAttrib >= 0); assert(texAttrib >= 0); assert(!vsource.empty()); assert(!fsource.empty()); } catch(std::out_of_range& err) { std::cout << "Resource not found! " << err.what() << std::endl; return; } shaderProgram = createShaderProgram(vsource, fsource, "", {"position", "texture"}); uniformMatrix = glGetUniformLocation(shaderProgram, "matrix"); uniformSampler = glGetUniformLocation(shaderProgram, "sampler"); uniformColor = glGetUniformLocation(shaderProgram, "color"); glGenBuffers(1, &vbo); glGenVertexArrays(1, &vao); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, nullptr, GL_DYNAMIC_DRAW); glEnableVertexAttribArray(posAttrib); glEnableVertexAttribArray(texAttrib); glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), nullptr); glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (void*) (2 * sizeof(GLfloat))); if (FT_Init_FreeType(&ftLibrary)) std::cerr << "draw_text.cpp: freetype init failure" << std::endl; } void DrawText::initFont(const std::string& name, int size) { std::string file = FONT_BASE_PATH + name + ".ttf"; //std::cout << file << std::endl; Font& font = fonts[name][size]; if(!font.init) { FT_Face face; if (FT_New_Face(ftLibrary, file.c_str(), 0, &face)) std::cerr << "draw_text.cpp: Could not load font file " << file << std::endl; FT_Set_Pixel_Sizes(face, 0, size); if (FT_Load_Char(face, 'X', FT_LOAD_RENDER)) std::cerr << "draw_text.cpp: Could not load font character for " << file << std::endl; glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // Disable byte-alignment restriction for (GLubyte c = 0; c < 128; c++) { // Load character glyph if (FT_Load_Char(face, c, FT_LOAD_RENDER)) { std::cout << "draw_text.cpp: Could not load font glyph " << c << std::endl; continue; } GLuint texture; glGenTextures(1, &texture); // Generate texture glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D( GL_TEXTURE_2D, 0, GL_RED, face->glyph->bitmap.width, face->glyph->bitmap.rows, 0, GL_RED, GL_UNSIGNED_BYTE, face->glyph->bitmap.buffer ); // Set texture options glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Now store character for later use Character character = { texture, glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows), glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top), (GLuint) face->glyph->advance.x }; font.characters.insert(std::pair<GLchar, Character>(c, character)); } FT_Done_Face(face); font.init = true; } } void DrawText::drawFont(glm::mat4 matrix, glm::vec4 color, const std::string& name, int size, std::string text, bool allowNewLines) { Font &font = fonts[name][size]; if (!font.init) { std::cerr << "draw_text.cpp: Font not initialized and tried to render: " << name << " (" << size << ")"; std::cerr << std::endl; } float x = 0, y = 0; float sx = x; //float ox = x; float scale = 1.0f; // Activate corresponding render state glUseProgram(shaderProgram); glUniform4f(uniformColor, color.x, color.y, color.z, color.w); glUniform1i(uniformSampler, 0); glUniformMatrix4fv(uniformMatrix, 1, false, glm::value_ptr(matrix)); glActiveTexture(GL_TEXTURE0); glBindVertexArray(vao); // Iterate through all characters std::string::const_iterator c; for (c = text.begin(); c != text.end(); c++) { auto* ch = &font.characters[*c]; if (*c == '\n') { if(allowNewLines) { y -= (float) size; x = sx; } else { ch = &font.characters[' ']; } continue; } if(*c == '\r') { continue; } GLfloat xpos = x + ch->Bearing.x * scale; GLfloat ypos = y - (float) (ch->Size.y - ch->Bearing.y) * scale; GLfloat w = ch->Size.x * scale; GLfloat h = ch->Size.y * scale; // Update VBO for each character glBindBuffer(GL_ARRAY_BUFFER, vbo); GLfloat vertices[6][4] = { {xpos, ypos + h, 0.0, 0.0}, {xpos, ypos, 0.0, 1.0}, {xpos + w, ypos, 1.0, 1.0}, {xpos, ypos + h, 0.0, 0.0}, {xpos + w, ypos, 1.0, 1.0}, {xpos + w, ypos + h, 1.0, 0.0} }; // Render glyph texture over quad glBindTexture(GL_TEXTURE_2D, ch->TextureID); // Update content of VBO memory glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices); // Render quad glDrawArrays(GL_TRIANGLES, 0, 6); // Now advance cursors for next glyph (note that advance is number of 1/64 pixels) x += (ch->Advance >> (GLuint) 6) * scale; // Bitshift by 6 to get value in pixels (2^6 = 64) } } float DrawText::textWidth(const std::string& name, int size, std::string text, bool allowNewLines) { Font& font = fonts[name][size]; float maxX = 0; float x = 0; float sx = x; float lastCharAdvance = 0, lastCharWidth = 0; //float ox = x; // Iterate through all characters std::string::const_iterator c; for (c = text.begin(); c != text.end(); c++) { auto* ch = &font.characters[*c]; if(*c == '\n') { if(allowNewLines) { maxX = std::max(x - lastCharAdvance + lastCharWidth, maxX); x = sx; continue; } else { ch = &font.characters[' ']; } } if(*c == '\r') { continue; } // Update VBO for each character // Now advance cursors for next glyph (note that advance is number of 1/64 pixels) x += (ch->Advance >> (GLuint) 6); // Bitshift by 6 to get value in pixels (2^6 = 64) lastCharAdvance = (ch->Advance >> (GLuint) 6); lastCharWidth = ch->Size.x; } maxX = std::max(x - lastCharAdvance + lastCharWidth, maxX); return maxX; } int DrawText::textBeforeWidth(const std::string& name, int size, std::string text, float width, bool allowNewLines) { Font& font = fonts[name][size]; float maxX = 0; float x = 0; float sx = x; float lastCharAdvance = 0, lastCharWidth = 0; //float ox = x; // Iterate through all characters for (int i = 0; i < text.size(); ++i) { auto* ch = &font.characters[text[i]]; if(text[i] == '\n') { if(allowNewLines) { return i + 1; } else { ch = &font.characters[' ']; } } // Update VBO for each character // Now advance cursors for next glyph (note that advance is number of 1/64 pixels) x += (ch->Advance >> (GLuint) 6); // Bitshift by 6 to get value in pixels (2^6 = 64) lastCharAdvance = (ch->Advance >> (GLuint) 6); lastCharWidth = ch->Size.x; if(x - lastCharAdvance + lastCharWidth > width) { return i; } } return text.size(); } DrawText::~DrawText() { FT_Done_FreeType(ftLibrary); for(const auto& pair1 : fonts) { for(const auto& pair2 : pair1.second) { for(auto character : pair2.second.characters) { auto c = character.second; glDeleteTextures(1, &c.TextureID); } } } fonts.clear(); glDeleteProgram(shaderProgram); glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); } #ifdef RENDER_0 namespace draw::unique::text { GLint shaderProgram; GLint uniformMatrix; GLint uniformSampler; GLint uniformColor; GLuint vao, vbo; FT_Library ftLibrary; struct Character { GLuint TextureID; // ID handle of the glyph texture glm::ivec2 Size; // Size of glyph glm::ivec2 Bearing; // Offset from baseline to left/top of glyph GLuint Advance; // Offset to advance to next glyph }; struct Font { std::map<GLchar, Character> characters; }; std::map<std::string, std::map<int, Font>> storedFonts; bool textRenderingInit = false; void initTextRendering(); } using namespace draw::unique::text; void draw::unique::text::initTextRendering() { if(textRenderingInit) { return; } textRenderingInit = true; std::string vsource = "ILLEGAL", fsource = "ILLEGAL"; int posAttrib = -1, texAttrib = -1; try { vsource = draw::RESOURCES.at("shaders/text_v"); fsource = draw::RESOURCES.at("shaders/text_f"); posAttrib = draw::GLOBAL_ATTRIBUTE_LOCATIONS.at("position"); texAttrib = draw::GLOBAL_ATTRIBUTE_LOCATIONS.at("texture"); assert(posAttrib >= 0); } catch(std::out_of_range& err) { std::cout << "Resource not found! " << err.what() << std::endl; return; } shaderProgram = createShaderProgram(vsource, fsource, "", {"position", "texture"}); uniformMatrix = glGetUniformLocation(shaderProgram, "matrix"); uniformSampler = glGetUniformLocation(shaderProgram, "sampler"); uniformColor = glGetUniformLocation(shaderProgram, "color"); glGenBuffers(1, &vbo); glGenVertexArrays(1, &vao); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, nullptr, GL_DYNAMIC_DRAW); glEnableVertexAttribArray(posAttrib); glEnableVertexAttribArray(texAttrib); glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), nullptr); glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (void*) (2 * sizeof(GLfloat))); if (FT_Init_FreeType(&ftLibrary)) std::cerr << "draw_text.cpp: freetype init failure" << std::endl; } void draw::initFont(const std::string& fontName, const int &size) { auto filePair = draw::RESOURCES.find("fonts"); assert(filePair != draw::RESOURCES.end() && "draw_text.cpp: Could not find fonts path in RESOURCES map"); std::string file = filePair->second + fontName + ".ttf"; file = "./res/fonts/arial.ttf"; std::cout << file << std::endl; initTextRendering(); Font* font = nullptr; auto storedFontsPairPair = storedFonts.find(fontName); if(storedFontsPairPair == storedFonts.end()) { auto storedFontsSizeMap = storedFonts.insert({fontName, {{size, Font()}}}); font = &storedFontsSizeMap.first->second.at(size); std::cout << "Font name map and size map for " << fontName << " (" << size << ")" << std::endl; } else { auto storedFontsPair = storedFontsPairPair->second.find(size); if(storedFontsPair == storedFontsPairPair->second.end()) { auto insertion = storedFontsPairPair->second.insert({size, Font()}); font = &insertion.first->second; std::cout << "Font size map for " << fontName << " (" << size << ")" << std::endl; } else { font = &storedFontsPair->second; std::cerr << fontName << " (" << size << ") already exists. Attempted to reinitialize." << std::endl; return; } } FT_Face face; if (FT_New_Face(ftLibrary, file.c_str(), 0, &face)) std::cerr << "draw_text.cpp: Could not load font file " << file << std::endl; FT_Set_Pixel_Sizes(face, 0, size); if (FT_Load_Char(face, 'X', FT_LOAD_RENDER)) std::cerr << "draw_text.cpp: Could not load font character for " << file << std::endl; glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // Disable byte-alignment restriction for (GLubyte c = 0; c < 128; c++) { // Load character glyph if (FT_Load_Char(face, c, FT_LOAD_RENDER)) { std::cout << "draw_text.cpp: Could not load font glyph " << c << std::endl; } GLuint texture; glGenTextures(1, &texture); // Generate texture glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D( GL_TEXTURE_2D, 0, GL_RED, face->glyph->bitmap.width, face->glyph->bitmap.rows, 0, GL_RED, GL_UNSIGNED_BYTE, face->glyph->bitmap.buffer ); // Set texture options glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Now store character for later use Character character = { texture, glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows), glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top), (GLuint) face->glyph->advance.x }; font->characters.insert(std::pair<GLchar, Character>(c, character)); } FT_Done_Face(face); } void draw::text(const std::string& fontName, const int& size, const std::string& text, const glm::mat4& matrix, const glm::vec4& color) { auto storedFontsPairPair = storedFonts.find(fontName); if(storedFontsPairPair == storedFonts.end()) { std::cerr << "Font tried to draw when not defined: " << fontName << " (further undefined: " << size << ")" << std::endl; return; } auto storedFontsPair = storedFontsPairPair->second.find(size); if(storedFontsPair == storedFontsPairPair->second.end()) { std::cerr << "Font tried to draw when not defined: " << fontName << " (" << size << ")" << std::endl; return; } Font* font = &storedFontsPair->second; float x = 0, y = 0; float sx = x; //float ox = x; float scale = 1.0f; // Activate corresponding render state glUseProgram(shaderProgram); glUniform4f(uniformColor, color.x, color.y, color.z, color.w); glUniform1i(uniformSampler, 0); glUniformMatrix4fv(uniformMatrix, 1, false, glm::value_ptr(matrix)); glActiveTexture(GL_TEXTURE0); glBindVertexArray(vao); // Iterate through all characters std::string::const_iterator c; for (c = text.begin(); c != text.end(); c++) { if(*c == '\n') { y += size; x = sx; continue; } Character ch = font->characters[*c]; GLfloat xpos = x + ch.Bearing.x * scale; GLfloat ypos = y - (float) (ch.Size.y - ch.Bearing.y) * scale; GLfloat w = ch.Size.x * scale; GLfloat h = ch.Size.y * scale; // Update VBO for each character glBindBuffer(GL_ARRAY_BUFFER, vbo); GLfloat vertices[6][4] = { { xpos, ypos + h, 0.0, 0.0 }, { xpos, ypos, 0.0, 1.0 }, { xpos + w, ypos, 1.0, 1.0 }, { xpos, ypos + h, 0.0, 0.0 }, { xpos + w, ypos, 1.0, 1.0 }, { xpos + w, ypos + h, 1.0, 0.0 } }; // Render glyph texture over quad glBindTexture(GL_TEXTURE_2D, ch.TextureID); // Update content of VBO memory glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices); // Render quad glDrawArrays(GL_TRIANGLES, 0, 6); // Now advance cursors for next glyph (note that advance is number of 1/64 pixels) x += (ch.Advance >> (GLuint) 6) * scale; // Bitshift by 6 to get value in pixels (2^6 = 64) } } float draw::textWidth(const std::string &fontName, const int &size, const std::string &text) { auto storedFontsPairPair = storedFonts.find(fontName); if(storedFontsPairPair == storedFonts.end()) { std::cerr << "Font tried to calc width when not defined: " << fontName << " (further undefined: " << size << ")" << std::endl; return 0; } auto storedFontsPair = storedFontsPairPair->second.find(size); if(storedFontsPair == storedFontsPairPair->second.end()) { std::cerr << "Font tried to calc width when not defined: " << fontName << " (" << size << ")" << std::endl; return 0; } Font* font = &storedFontsPair->second; float maxX = 0; float x = 0; float sx = x; float lastCharAdvance = 0, lastCharWidth = 0; //float ox = x; // Iterate through all characters std::string::const_iterator c; for (c = text.begin(); c != text.end(); c++) { if(*c == '\n') { maxX = std::max(x - lastCharAdvance + lastCharWidth, maxX); x = sx; continue; } Character ch = font->characters[*c]; // Update VBO for each character // Now advance cursors for next glyph (note that advance is number of 1/64 pixels) x += (ch.Advance >> (GLuint) 6); // Bitshift by 6 to get value in pixels (2^6 = 64) lastCharAdvance = (ch.Advance >> (GLuint) 6); lastCharWidth = ch.Size.x; } maxX = std::max(x - lastCharAdvance + lastCharWidth, maxX); return maxX; } void draw::destroyAllText() { FT_Done_FreeType(ftLibrary); for(const auto& pair1 : storedFonts) { for(const auto& pair2 : pair1.second) { for(auto character : pair2.second.characters) { auto c = character.second; glDeleteTextures(1, &c.TextureID); } } } storedFonts.clear(); glDeleteProgram(shaderProgram); glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); } #endif
[ "ihuffman@umich.edu" ]
ihuffman@umich.edu
6e74ad1fe7a7eb92a42f7d752357974136fdf0c9
dbca341204a5bdeb732a2006437529187db18cce
/DSTR_Project/GFX/MaterialMap.h
4a3e0b6ae97330c0b6f4f4182ffc493cb74e1cbe
[]
no_license
FiskNi/DSTR_Project
58621284fae168a4e94c789a34cd3218f04535d3
d3883c7b22511a346532ba5c5c18057dd6650576
refs/heads/master
2022-12-07T23:27:03.055755
2020-08-27T13:54:06
2020-08-27T13:54:06
275,875,228
7
1
null
null
null
null
UTF-8
C++
false
false
573
h
#ifndef _MATERIALMAP_h #define _MATERIALMAP_h #include <Pch/Pch.h> #include <Mesh/MeshFormat.h> class MaterialMap { public: static MaterialMap* GetInstance(); void cleanUp(); bool existsWithName(std::string name); void useByName(std::string name); Material* getMaterial(std::string name); Material* GetFirst(); Material* createMaterial(std::string name, Material material); Material* createMaterial(std::string name); void destroy(); private: MaterialMap(); static MaterialMap* m_materialMapInstance; std::map<std::string, Material*> m_Material; }; #endif
[ "JerryRonnegren@hotmail.com" ]
JerryRonnegren@hotmail.com
c81b1fa8137221d045f3172b276c869d07ab384b
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/AtCoder/agc007/F/1366437.cpp
086debb2722551e74f25749114f2b7cec6e032ad
[]
no_license
Kawser-nerd/CLCDSA
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
aee32551795763b54acb26856ab239370cac4e75
refs/heads/master
2022-02-09T11:08:56.588303
2022-01-26T18:53:40
2022-01-26T18:53:40
211,783,197
23
9
null
null
null
null
UTF-8
C++
false
false
2,008
cpp
//#pragma GCC optimize(2) #include<cstdio> #define L 1<<23 #define C (c=*A++) #define ENS //__attribute__((optimize("-O2"))) #define NES //__attribute__((optimize("-O2"))) __inline__ __attribute__((always_inline)) #define N 1000001 int MAPLE,n,l[N],r[N],cnt,last,wt,ss[19];char fl[L],*A=fl,s[N],t[N];bool fg=true; NES void read(int&x){char c;for(x=0;'0'>C||c>'9';);while('0'<=c&&c<='9')x=(x<<3)+(x<<1)+c-48,C;}NES void print(int x){if(!x)putchar(48);else{for(wt=0;x;ss[++wt]=x%10,x/=10);for(;wt;putchar(ss[wt--]+48));}} ENS int main() {int i,j;char c; for(fl[fread(fl,1,L,stdin)]=EOF,read(n);'a'>C||c>'z';);for(i=1;i<=n;s[i]=c,C,i++);while('a'>C||c>'z');for(i=1;i<=n;t[i]=c,C,i++); for(last=i=n,j=n+1;i;fg&=s[i]==t[i],i--) if(t[i]!=t[i-1]) {if((--j)>i)j=i; for(;j&&s[j]!=t[i];j--);if(!j)return puts("-1"),0; l[++cnt]=j,r[cnt]=last,last=i-1; }if(fg)return puts("0"),0;for(l[0]=n+1,i=1;i<=cnt;i++)for(;l[i-MAPLE]<r[i]+MAPLE;MAPLE++);print(MAPLE); } ./Main.cpp:10:51: warning: for loop has empty body [-Wempty-body] NES void read(int&x){char c;for(x=0;'0'>C||c>'9';);while('0'<=c&&c<='9')x=(x<<3)+(x<<1)+c-48,C;}NES void print(int x){if(!x)putchar(48);else{for(wt=0;x;ss[++wt]=x%10,x/=10);for(;wt;putchar(ss[wt--]+48));}} ^ ./Main.cpp:10:51: note: put the semicolon on a separate line to silence this warning ./Main.cpp:10:173: warning: for loop has empty body [-Wempty-body] NES void read(int&x){char c;for(x=0;'0'>C||c>'9';);while('0'<=c&&c<='9')x=(x<<3)+(x<<1)+c-48,C;}NES void print(int x){if(!x)putchar(48);else{for(wt=0;x;ss[++wt]=x%10,x/=10);for(;wt;putchar(ss[wt--]+48));}} ^ ./Main.cpp:10:173: note: put the semicolon on a separate line to silence this warning ./Main.cpp:17:27: warning: for loop has empty body [-Wempty-body] ...
[ "kwnafi@yahoo.com" ]
kwnafi@yahoo.com
e7a06c3414441306460fcc948859c29c0609dbb9
0f999b675ddb9433441a854206532cfdace06d88
/include/csv.h
7ce72394b215cb0deba247f601cbddf45db69474
[ "BSD-3-Clause", "MIT" ]
permissive
fsxfreak/Bitrecal
13e37bbc6e24691f2dd454975426f72d4e5d6eba
badb260ef579ebd789749106db2a68abba879a51
refs/heads/master
2021-01-13T02:11:41.002397
2014-04-14T03:36:17
2014-04-14T03:36:17
17,810,167
4
3
null
null
null
null
UTF-8
C++
false
false
25,429
h
#ifndef CSV_H #define CSV_H #include <vector> #include <string> #include <cstring> #include <algorithm> #include <utility> #include <cstdio> #include <exception> #ifndef CSV_IO_NO_THREAD #include <future> #endif #include <cassert> #include <cerrno> namespace io{ //////////////////////////////////////////////////////////////////////////// // LineReader // //////////////////////////////////////////////////////////////////////////// namespace error{ struct base : std::exception{ virtual void format_error_message()const = 0; const char*what()const throw(){ format_error_message(); return error_message_buffer; } mutable char error_message_buffer[256]; }; const int max_file_name_length = 255; struct with_file_name{ with_file_name(){ std::memset(file_name, 0, max_file_name_length+1); } void set_file_name(const char*file_name){ std::strncpy(this->file_name, file_name, max_file_name_length); this->file_name[max_file_name_length] = '\0'; } char file_name[max_file_name_length+1]; }; struct with_file_line{ with_file_line(){ file_line = -1; } void set_file_line(int file_line){ this->file_line = file_line; } int file_line; }; struct with_errno{ with_errno(){ errno = 0; } void set_errno(int errno_value){ this->errno_value = errno_value; } int errno_value; }; struct can_not_open_file : base, with_file_name, with_errno{ void format_error_message()const{ if(errno_value != 0) std::snprintf(error_message_buffer, sizeof(error_message_buffer), "Can not open file \"%s\" because \"%s\"." , file_name, std::strerror(errno_value)); else std::snprintf(error_message_buffer, sizeof(error_message_buffer), "Can not open file \"%s\"." , file_name); } }; struct line_length_limit_exceeded : base, with_file_name, with_file_line{ void format_error_message()const{ std::snprintf(error_message_buffer, sizeof(error_message_buffer), "Line number %d in file \"%s\" exceeds the maximum length of 2^24-1." , file_line, file_name); } }; } class LineReader{ private: static const int block_len = 1<<24; #ifndef CSV_IO_NO_THREAD std::future<int>bytes_read; #endif FILE*file; char*buffer; int data_begin; int data_end; char file_name[error::max_file_name_length+1]; unsigned file_line; void open_file(const char*file_name){ // We open the file in binary mode as it makes no difference under *nix // and under Windows we handle \r\n newlines ourself. file = std::fopen(file_name, "rb"); if(file == 0){ int x = errno; // store errno as soon as possible, doing it after constructor call can fail. error::can_not_open_file err; err.set_errno(x); err.set_file_name(file_name); throw err; } } void init(){ file_line = 0; // Tell the std library that we want to do the buffering ourself. std::setvbuf(file, 0, _IONBF, 0); try{ buffer = new char[3*block_len]; }catch(...){ std::fclose(file); throw; } data_begin = 0; data_end = std::fread(buffer, 1, 2*block_len, file); // Ignore UTF-8 BOM if(data_end >= 3 && buffer[0] == '\xEF' && buffer[1] == '\xBB' && buffer[2] == '\xBF') data_begin = 3; #ifndef CSV_IO_NO_THREAD if(data_end == 2*block_len){ bytes_read = std::async(std::launch::async, [=]()->int{ return std::fread(buffer + 2*block_len, 1, block_len, file); }); } #endif } public: LineReader() = delete; LineReader(const LineReader&) = delete; LineReader&operator=(const LineReader&) = delete; LineReader(const char*file_name, FILE*file): file(file){ set_file_name(file_name); init(); } LineReader(const std::string&file_name, FILE*file): file(file){ set_file_name(file_name.c_str()); init(); } explicit LineReader(const char*file_name){ set_file_name(file_name); open_file(file_name); init(); } explicit LineReader(const std::string&file_name){ set_file_name(file_name.c_str()); open_file(file_name.c_str()); init(); } void set_file_name(const std::string&file_name){ set_file_name(file_name.c_str()); } void set_file_name(const char*file_name){ strncpy(this->file_name, file_name, error::max_file_name_length); this->file_name[error::max_file_name_length] = '\0'; } const char*get_truncated_file_name()const{ return file_name; } void set_file_line(unsigned file_line){ this->file_line = file_line; } unsigned get_file_line()const{ return file_line; } char*next_line(){ if(data_begin == data_end) return 0; ++file_line; assert(data_begin < data_end); assert(data_end <= block_len*2); if(data_begin >= block_len){ std::memcpy(buffer, buffer+block_len, block_len); data_begin -= block_len; data_end -= block_len; #ifndef CSV_IO_NO_THREAD if(bytes_read.valid()) #endif { #ifndef CSV_IO_NO_THREAD data_end += bytes_read.get(); #else data_end += std::fread(buffer + 2*block_len, 1, block_len, file); #endif std::memcpy(buffer+block_len, buffer+2*block_len, block_len); #ifndef CSV_IO_NO_THREAD bytes_read = std::async(std::launch::async, [=]()->int{ return std::fread(buffer + 2*block_len, 1, block_len, file); }); #endif } } int line_end = data_begin; while(buffer[line_end] != '\n' && line_end != data_end){ ++line_end; } if(line_end - data_begin + 1 > block_len){ error::line_length_limit_exceeded err; err.set_file_name(file_name); err.set_file_line(file_line); throw err; } if(buffer[line_end] == '\n'){ buffer[line_end] = '\0'; }else{ // some files are missing the newline at the end of the // last line ++data_end; buffer[line_end] = '\0'; } // handle windows \r\n-line breaks if(line_end != data_begin && buffer[line_end-1] == '\r') buffer[line_end-1] = '\0'; char*ret = buffer + data_begin; data_begin = line_end+1; return ret; } ~LineReader(){ #ifndef CSV_IO_NO_THREAD // GCC needs this or it will crash. if(bytes_read.valid()) bytes_read.get(); #endif delete[] buffer; std::fclose(file); } }; //////////////////////////////////////////////////////////////////////////// // CSV // //////////////////////////////////////////////////////////////////////////// namespace error{ const int max_column_name_length = 63; struct with_column_name{ with_column_name(){ std::memset(column_name, 0, max_column_name_length+1); } void set_column_name(const char*column_name){ std::strncpy(this->column_name, column_name, max_column_name_length); this->column_name[max_column_name_length] = '\0'; } char column_name[max_column_name_length+1]; }; const int max_column_content_length = 63; struct with_column_content{ with_column_content(){ std::memset(column_content, 0, max_column_content_length+1); } void set_column_content(const char*column_content){ std::strncpy(this->column_content, column_content, max_column_content_length); this->column_content[max_column_content_length] = '\0'; } char column_content[max_column_content_length+1]; }; struct extra_column_in_header : base, with_file_name, with_column_name{ void format_error_message()const{ std::snprintf(error_message_buffer, sizeof(error_message_buffer), "Extra column \"%s\" in header of file \"%s\"." , column_name, file_name); } }; struct missing_column_in_header : base, with_file_name, with_column_name{ void format_error_message()const{ std::snprintf(error_message_buffer, sizeof(error_message_buffer), "Missing column \"%s\" in header of file \"%s\"." , column_name, file_name); } }; struct duplicated_column_in_header : base, with_file_name, with_column_name{ void format_error_message()const{ std::snprintf(error_message_buffer, sizeof(error_message_buffer), "Duplicated column \"%s\" in header of file \"%s\"." , column_name, file_name); } }; struct header_missing : base, with_file_name{ void format_error_message()const{ std::snprintf(error_message_buffer, sizeof(error_message_buffer), "Header missing in file \"%s\"." , file_name); } }; struct too_few_columns : base, with_file_name, with_file_line{ void format_error_message()const{ std::snprintf(error_message_buffer, sizeof(error_message_buffer), "Too few columns in line %d in file \"%s\"." , file_line, file_name); } }; struct too_many_columns : base, with_file_name, with_file_line{ void format_error_message()const{ std::snprintf(error_message_buffer, sizeof(error_message_buffer), "Too many columns in line %d in file \"%s\"." , file_line, file_name); } }; struct escaped_string_not_closed : base, with_file_name, with_file_line{ void format_error_message()const{ std::snprintf(error_message_buffer, sizeof(error_message_buffer), "Escaped string was not closed in line %d in file \"%s\"." , file_line, file_name); } }; struct integer_must_be_positive : base, with_file_name, with_file_line, with_column_name, with_column_content{ void format_error_message()const{ std::snprintf(error_message_buffer, sizeof(error_message_buffer), "The integer \"%s\" must be positive or 0 in column \"%s\" in file \"%s\" in line \"%d\"." , column_content, column_name, file_name, file_line); } }; struct no_digit : base, with_file_name, with_file_line, with_column_name, with_column_content{ void format_error_message()const{ std::snprintf(error_message_buffer, sizeof(error_message_buffer), "The integer \"%s\" contains an invalid digit in column \"%s\" in file \"%s\" in line \"%d\"." , column_content, column_name, file_name, file_line); } }; struct integer_overflow : base, with_file_name, with_file_line, with_column_name, with_column_content{ void format_error_message()const{ std::snprintf(error_message_buffer, sizeof(error_message_buffer), "The integer \"%s\" overflows in column \"%s\" in file \"%s\" in line \"%d\"." , column_content, column_name, file_name, file_line); } }; struct integer_underflow : base, with_file_name, with_file_line, with_column_name, with_column_content{ void format_error_message()const{ std::snprintf(error_message_buffer, sizeof(error_message_buffer), "The integer \"%s\" underflows in column \"%s\" in file \"%s\" in line \"%d\"." , column_content, column_name, file_name, file_line); } }; struct invalid_single_character : base, with_file_name, with_file_line, with_column_name, with_column_content{ void format_error_message()const{ std::snprintf(error_message_buffer, sizeof(error_message_buffer), "The content \"%s\" of column \"%s\" in file \"%s\" in line \"%d\" is not a single character." , column_content, column_name, file_name, file_line); } }; } typedef unsigned ignore_column; static const ignore_column ignore_no_column = 0; static const ignore_column ignore_extra_column = 1; static const ignore_column ignore_missing_column = 2; template<char ... trim_char_list> struct trim_chars{ private: constexpr static bool is_trim_char(char c){ return false; } template<class ...OtherTrimChars> constexpr static bool is_trim_char(char c, char trim_char, OtherTrimChars...other_trim_chars){ return c == trim_char || is_trim_char(c, other_trim_chars...); } public: static void trim(char*&str_begin, char*&str_end){ while(is_trim_char(*str_begin, trim_char_list...) && str_begin != str_end) ++str_begin; while(is_trim_char(*(str_end-1), trim_char_list...) && str_begin != str_end) --str_end; *str_end = '\0'; } }; struct no_comment{ static bool is_comment(const char*line){ return false; } }; template<char ... comment_start_char_list> struct single_line_comment{ private: constexpr static bool is_comment_start_char(char c){ return false; } template<class ...OtherCommentStartChars> constexpr static bool is_comment_start_char(char c, char comment_start_char, OtherCommentStartChars...other_comment_start_chars){ return c == comment_start_char || is_comment_start_char(c, other_comment_start_chars...); } public: static bool is_comment(const char*line){ return is_comment_start_char(*line, comment_start_char_list...); } }; template<char sep> struct no_quote_escape{ static const char*find_next_column_end(const char*col_begin){ while(*col_begin != sep && *col_begin != '\0') ++col_begin; return col_begin; } static void unescape(char*&col_begin, char*&col_end){ } }; template<char sep, char quote> struct double_quote_escape{ static const char*find_next_column_end(const char*col_begin){ while(*col_begin != sep && *col_begin != '\0') if(*col_begin != quote) ++col_begin; else{ do{ ++col_begin; while(*col_begin != quote){ if(*col_begin == '\0') throw error::escaped_string_not_closed(); ++col_begin; } ++col_begin; }while(*col_begin == quote); } return col_begin; } static void unescape(char*&col_begin, char*&col_end){ if(col_end - col_begin >= 2){ if(*col_begin == quote && *(col_end-1) == quote){ ++col_begin; --col_end; char*out = col_begin; for(char*in = col_begin; in!=col_end; ++in){ if(*in == quote && *(in+1) == quote){ continue; } *out = *in; ++out; } col_end = out; *col_end = '\0'; } } } }; struct throw_on_overflow{ template<class T> static void on_overflow(T&){ throw error::integer_overflow(); } template<class T> static void on_underflow(T&){ throw error::integer_underflow(); } }; struct ignore_overflow{ template<class T> static void on_overflow(T&){} template<class T> static void on_underflow(T&){} }; struct set_to_max_on_overflow{ template<class T> static void on_overflow(T&x){ x = std::numeric_limits<T>::max(); } template<class T> static void on_underflow(T&x){ x = std::numeric_limits<T>::min(); } }; namespace detail{ template<class quote_policy> void chop_next_column( char*&line, char*&col_begin, char*&col_end ){ assert(line != nullptr); col_begin = line; // the col_begin + (... - col_begin) removes the constness col_end = col_begin + (quote_policy::find_next_column_end(col_begin) - col_begin); if(*col_end == '\0'){ line = nullptr; }else{ *col_end = '\0'; line = col_end + 1; } } template<class trim_policy, class quote_policy> void parse_line( char*line, char**sorted_col, const std::vector<int>&col_order ){ for(std::size_t i=0; i<col_order.size(); ++i){ if(line == nullptr) throw io::error::too_few_columns(); char*col_begin, *col_end; chop_next_column<quote_policy>(line, col_begin, col_end); if(col_order[i] != -1){ trim_policy::trim(col_begin, col_end); quote_policy::unescape(col_begin, col_end); sorted_col[col_order[i]] = col_begin; } } if(line != nullptr) throw io::error::too_many_columns(); } template<unsigned column_count, class trim_policy, class quote_policy> void parse_header_line( char*line, std::vector<int>&col_order, const std::string*col_name, ignore_column ignore_policy ){ col_order.clear(); bool found[column_count]; std::fill(found, found + column_count, false); while(line){ char*col_begin,*col_end; chop_next_column<quote_policy>(line, col_begin, col_end); trim_policy::trim(col_begin, col_end); quote_policy::unescape(col_begin, col_end); for(unsigned i=0; i<column_count; ++i) if(col_begin == col_name[i]){ if(found[i]){ error::duplicated_column_in_header err; err.set_column_name(col_begin); throw err; } found[i] = true; col_order.push_back(i); col_begin = 0; break; } if(col_begin){ if(ignore_policy & io::ignore_extra_column) col_order.push_back(-1); else{ error::extra_column_in_header err; err.set_column_name(col_begin); throw err; } } } if(!(ignore_policy & io::ignore_missing_column)){ for(unsigned i=0; i<column_count; ++i){ if(!found[i]){ error::missing_column_in_header err; err.set_column_name(col_name[i].c_str()); throw err; } } } } template<class overflow_policy> void parse(char*col, char &x){ if(!*col) throw error::invalid_single_character(); x = *col; ++col; if(*col) throw error::invalid_single_character(); } template<class overflow_policy> void parse(char*col, std::string&x){ x = col; } template<class overflow_policy> void parse(char*col, const char*&x){ x = col; } template<class overflow_policy> void parse(char*col, char*&x){ x = col; } template<class overflow_policy, class T> void parse_unsigned_integer(const char*col, T&x){ x = 0; while(*col != '\0'){ if('0' <= *col && *col <= '9'){ T y = *col - '0'; if(x > (std::numeric_limits<T>::max()-y)/10){ overflow_policy::on_overflow(x); return; } x = 10*x+y; }else throw error::no_digit(); ++col; } } template<class overflow_policy>void parse(char*col, unsigned char &x) {parse_unsigned_integer<overflow_policy>(col, x);} template<class overflow_policy>void parse(char*col, unsigned short &x) {parse_unsigned_integer<overflow_policy>(col, x);} template<class overflow_policy>void parse(char*col, unsigned int &x) {parse_unsigned_integer<overflow_policy>(col, x);} template<class overflow_policy>void parse(char*col, unsigned long &x) {parse_unsigned_integer<overflow_policy>(col, x);} template<class overflow_policy>void parse(char*col, unsigned long long &x) {parse_unsigned_integer<overflow_policy>(col, x);} template<class overflow_policy, class T> void parse_signed_integer(const char*col, T&x){ if(*col == '-'){ ++col; x = 0; while(*col != '\0'){ if('0' <= *col && *col <= '9'){ T y = *col - '0'; if(x < (std::numeric_limits<T>::min()+y)/10){ overflow_policy::on_underflow(x); return; } x = 10*x-y; }else throw error::no_digit(); ++col; } return; }else if(*col == '+') ++col; parse_unsigned_integer<overflow_policy>(col, x); } template<class overflow_policy>void parse(char*col, signed char &x) {parse_signed_integer<overflow_policy>(col, x);} template<class overflow_policy>void parse(char*col, signed short &x) {parse_signed_integer<overflow_policy>(col, x);} template<class overflow_policy>void parse(char*col, signed int &x) {parse_signed_integer<overflow_policy>(col, x);} template<class overflow_policy>void parse(char*col, signed long &x) {parse_signed_integer<overflow_policy>(col, x);} template<class overflow_policy>void parse(char*col, signed long long &x) {parse_signed_integer<overflow_policy>(col, x);} template<class T> void parse_float(const char*col, T&x){ bool is_neg = false; if(*col == '-'){ is_neg = true; ++col; }else if(*col == '+') ++col; x = 0; while('0' <= *col && *col <= '9'){ int y = *col - '0'; x *= 10; x += y; ++col; } if(*col == '.'|| *col == ','){ ++col; T pos = 1; while('0' <= *col && *col <= '9'){ pos /= 10; int y = *col - '0'; ++col; x += y*pos; } } if(*col == 'e' || *col == 'E'){ ++col; int e; parse_signed_integer<set_to_max_on_overflow>(col, e); if(e != 0){ T base; if(e < 0){ base = 0.1; e = -e; }else{ base = 10; } while(e != 1){ if((e & 1) == 0){ base = base*base; e >>= 1; }else{ x *= base; --e; } } x *= base; } }else{ if(*col != '\0') throw error::no_digit(); } if(is_neg) x = -x; } template<class overflow_policy> void parse(char*col, float&x) { parse_float(col, x); } template<class overflow_policy> void parse(char*col, double&x) { parse_float(col, x); } template<class overflow_policy> void parse(char*col, long double&x) { parse_float(col, x); } template<class overflow_policy, class T> void parse(char*col, T&x){ // GCC evalutes "false" when reading the template and // "sizeof(T)!=sizeof(T)" only when instantiating it. This is why // this strange construct is used. static_assert(sizeof(T)!=sizeof(T), "Can not parse this type. Only buildin integrals, floats, char, char*, const char* and std::string are supported"); } } template<unsigned column_count, class trim_policy = trim_chars<' ', '\t'>, class quote_policy = no_quote_escape<','>, class overflow_policy = throw_on_overflow, class comment_policy = no_comment > class CSVReader{ private: LineReader in; char*(row[column_count]); std::string column_names[column_count]; std::vector<int>col_order; template<class ...ColNames> void set_column_names(std::string s, ColNames...cols){ column_names[column_count-sizeof...(ColNames)-1] = std::move(s); set_column_names(std::forward<ColNames>(cols)...); } void set_column_names(){} public: CSVReader() = delete; CSVReader(const CSVReader&) = delete; CSVReader&operator=(const CSVReader&); template<class ...Args> explicit CSVReader(Args...args):in(std::forward<Args>(args)...){ std::fill(row, row+column_count, nullptr); col_order.resize(column_count); for(unsigned i=0; i<column_count; ++i) col_order[i] = i; for(unsigned i=1; i<=column_count; ++i) column_names[i-1] = "col"+std::to_string(i); } template<class ...ColNames> void read_header(ignore_column ignore_policy, ColNames...cols){ static_assert(sizeof...(ColNames)>=column_count, "not enough column names specified"); static_assert(sizeof...(ColNames)<=column_count, "too many column names specified"); try{ set_column_names(std::forward<ColNames>(cols)...); char*line; do{ line = in.next_line(); if(!line) throw error::header_missing(); }while(comment_policy::is_comment(line)); detail::parse_header_line <column_count, trim_policy, quote_policy> (line, col_order, column_names, ignore_policy); }catch(error::with_file_name&err){ err.set_file_name(in.get_truncated_file_name()); throw; } } template<class ...ColNames> void set_header(ColNames...cols){ static_assert(sizeof...(ColNames)>=column_count, "not enough column names specified"); static_assert(sizeof...(ColNames)<=column_count, "too many column names specified"); set_column_names(std::forward<ColNames>(cols)...); std::fill(row, row+column_count, nullptr); col_order.resize(column_count); for(unsigned i=0; i<column_count; ++i) col_order[i] = i; } bool has_column(const std::string&name) const { return col_order.end() != std::find( col_order.begin(), col_order.end(), std::find(std::begin(column_names), std::end(column_names), name) - std::begin(column_names)); } void set_file_name(const std::string&file_name){ in.set_file_name(file_name); } void set_file_name(const char*file_name){ in.set_file_name(file_name); } const char*get_truncated_file_name()const{ return in.get_truncated_file_name(); } void set_file_line(unsigned file_line){ in.set_file_line(file_line); } unsigned get_file_line()const{ return in.get_file_line(); } private: void parse_helper(std::size_t r){} template<class T, class ...ColType> void parse_helper(std::size_t r, T&t, ColType&...cols){ if(row[r]){ try{ try{ row[r] = row[r]; io::detail::parse<overflow_policy>(row[r], t); }catch(error::with_column_content&err){ err.set_column_content(row[r]); throw; } }catch(error::with_column_name&err){ err.set_column_name(column_names[r].c_str()); throw; } } parse_helper(r+1, cols...); } public: template<class ...ColType> bool read_row(ColType& ...cols){ static_assert(sizeof...(ColType)>=column_count, "not enough columns specified"); static_assert(sizeof...(ColType)<=column_count, "too many columns specified"); try{ try{ char*line; do{ line = in.next_line(); if(!line) return false; }while(comment_policy::is_comment(line)); detail::parse_line<trim_policy, quote_policy> (line, row, col_order); parse_helper(0, cols...); }catch(error::with_file_name&err){ err.set_file_name(in.get_truncated_file_name()); throw; } }catch(error::with_file_line&err){ err.set_file_line(in.get_file_line()); throw; } return true; } }; } #endif
[ "me@leoncheung.com" ]
me@leoncheung.com
c198f08627213539bad6de07c9fa7044f9696f13
5456502f97627278cbd6e16d002d50f1de3da7bb
/chrome/browser/chromeos/policy/user_network_configuration_updater_factory.h
67657c78eb7fc7bebd7c1c8938a06a6858301907
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/Chromium_7C66
72d108a413909eb3bd36c73a6c2f98de1573b6e5
c8649ab2a0f5a747369ed50351209a42f59672ee
refs/heads/master
2023-03-16T12:51:40.231959
2017-12-20T10:38:26
2017-12-20T10:38:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,950
h
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_CHROMEOS_POLICY_USER_NETWORK_CONFIGURATION_UPDATER_FACTORY_H_ #define CHROME_BROWSER_CHROMEOS_POLICY_USER_NETWORK_CONFIGURATION_UPDATER_FACTORY_H_ #include "base/compiler_specific.h" #include "base/macros.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" namespace base { template <typename T> struct DefaultSingletonTraits; } // namespace base class Profile; namespace policy { class UserNetworkConfigurationUpdater; // Factory to create UserNetworkConfigurationUpdater. class UserNetworkConfigurationUpdaterFactory : public BrowserContextKeyedServiceFactory { public: // Returns an existing or creates a new UserNetworkConfigurationUpdater for // |profile|. Will return NULL if this service isn't allowed for |profile|, // i.e. for all but the primary user's profile. static UserNetworkConfigurationUpdater* GetForProfile(Profile* profile); static UserNetworkConfigurationUpdaterFactory* GetInstance(); private: friend struct base::DefaultSingletonTraits< UserNetworkConfigurationUpdaterFactory>; UserNetworkConfigurationUpdaterFactory(); ~UserNetworkConfigurationUpdaterFactory() override; // BrowserContextKeyedServiceFactory: content::BrowserContext* GetBrowserContextToUse( content::BrowserContext* context) const override; bool ServiceIsCreatedWithBrowserContext() const override; bool ServiceIsNULLWhileTesting() const override; KeyedService* BuildServiceInstanceFor( content::BrowserContext* context) const override; DISALLOW_COPY_AND_ASSIGN(UserNetworkConfigurationUpdaterFactory); }; } // namespace policy #endif // CHROME_BROWSER_CHROMEOS_POLICY_USER_NETWORK_CONFIGURATION_UPDATER_FACTORY_H_
[ "lixiaodonglove7@aliyun.com" ]
lixiaodonglove7@aliyun.com
9277634ac6bbd9e9a36cf83b433f0817eca97493
fbbe424559f64e9a94116a07eaaa555a01b0a7bb
/pytorch/source/torch/lib/include/ATen/LegacyTHDispatcher.h
73f1f490b6bf86f79298714f3538e3b6fb442ee6
[ "MIT" ]
permissive
ryfeus/lambda-packs
6544adb4dec19b8e71d75c24d8ed789b785b0369
cabf6e4f1970dc14302f87414f170de19944bac2
refs/heads/master
2022-12-07T16:18:52.475504
2022-11-29T13:35:35
2022-11-29T13:35:35
71,386,735
1,283
263
MIT
2022-11-26T05:02:14
2016-10-19T18:22:39
Python
UTF-8
C++
false
false
313
h
#pragma once #include <c10/core/TensorTypeIdRegistration.h> namespace at { struct CAFFE2_API LegacyTHDispatcher { explicit LegacyTHDispatcher(TensorTypeId type_id, bool is_undefined) : type_id_(type_id) {} virtual ~LegacyTHDispatcher() {} protected: TensorTypeId type_id_; }; } // namespace th
[ "ryfeus@gmail.com" ]
ryfeus@gmail.com
87e2ba86a8ed149604a31279296e5bd0d516a2ae
ea401c3e792a50364fe11f7cea0f35f99e8f4bde
/released_plugins/v3d_plugins/bigneuron_AmosSironi_PrzemyslawGlowacki_SQBTree_plugin/libs/boost_1_58_0/boost/heap/fibonacci_heap.hpp
4397d565eee26c9471ad19a881035434343bcd0f
[ "MIT" ]
permissive
Vaa3D/vaa3d_tools
edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9
e6974d5223ae70474efaa85e1253f5df1814fae8
refs/heads/master
2023-08-03T06:12:01.013752
2023-08-02T07:26:01
2023-08-02T07:26:01
50,527,925
107
86
MIT
2023-05-22T23:43:48
2016-01-27T18:19:17
C++
UTF-8
C++
false
false
24,820
hpp
// boost heap: fibonacci heap // // Copyright (C) 2010 Tim Blechmann // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_HEAP_FIBONACCI_HEAP_HPP #define BOOST_HEAP_FIBONACCI_HEAP_HPP #include <algorithm> #include <utility> #include <vector> #include <boost/array.hpp> #include <boost/assert.hpp> #include <boost/heap/detail/heap_comparison.hpp> #include <boost/heap/detail/heap_node.hpp> #include <boost/heap/detail/stable_heap.hpp> #include <boost/heap/detail/tree_iterator.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif #ifndef BOOST_DOXYGEN_INVOKED #ifdef BOOST_HEAP_SANITYCHECKS #define BOOST_HEAP_ASSERT BOOST_ASSERT #else #define BOOST_HEAP_ASSERT(expression) #endif #endif namespace boost { namespace heap { namespace detail { typedef parameter::parameters<boost::parameter::optional<tag::allocator>, boost::parameter::optional<tag::compare>, boost::parameter::optional<tag::stable>, boost::parameter::optional<tag::constant_time_size>, boost::parameter::optional<tag::stability_counter_type> > fibonacci_heap_signature; template <typename T, typename Parspec> struct make_fibonacci_heap_base { static const bool constant_time_size = parameter::binding<Parspec, tag::constant_time_size, boost::mpl::true_ >::type::value; typedef typename detail::make_heap_base<T, Parspec, constant_time_size>::type base_type; typedef typename detail::make_heap_base<T, Parspec, constant_time_size>::allocator_argument allocator_argument; typedef typename detail::make_heap_base<T, Parspec, constant_time_size>::compare_argument compare_argument; typedef marked_heap_node<typename base_type::internal_type> node_type; typedef typename allocator_argument::template rebind<node_type>::other allocator_type; struct type: base_type, allocator_type { type(compare_argument const & arg): base_type(arg) {} type(type const & rhs): base_type(static_cast<base_type const &>(rhs)), allocator_type(static_cast<allocator_type const &>(rhs)) {} type & operator=(type const & rhs) { base_type::operator=(static_cast<base_type const &>(rhs)); allocator_type::operator=(static_cast<allocator_type const &>(rhs)); return *this; } #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES type(type && rhs): base_type(std::move(static_cast<base_type&>(rhs))), allocator_type(std::move(static_cast<allocator_type&>(rhs))) {} type & operator=(type && rhs) { base_type::operator=(std::move(static_cast<base_type&>(rhs))); allocator_type::operator=(std::move(static_cast<allocator_type&>(rhs))); return *this; } #endif }; }; } /** * \class fibonacci_heap * \brief fibonacci heap * * The template parameter T is the type to be managed by the container. * The user can specify additional options and if no options are provided default options are used. * * The container supports the following options: * - \c boost::heap::stable<>, defaults to \c stable<false> * - \c boost::heap::compare<>, defaults to \c compare<std::less<T> > * - \c boost::heap::allocator<>, defaults to \c allocator<std::allocator<T> > * - \c boost::heap::constant_time_size<>, defaults to \c constant_time_size<true> * - \c boost::heap::stability_counter_type<>, defaults to \c stability_counter_type<boost::uintmax_t> * */ #ifdef BOOST_DOXYGEN_INVOKED template<class T, class ...Options> #else template <typename T, class A0 = boost::parameter::void_, class A1 = boost::parameter::void_, class A2 = boost::parameter::void_, class A3 = boost::parameter::void_, class A4 = boost::parameter::void_ > #endif class fibonacci_heap: private detail::make_fibonacci_heap_base<T, typename detail::fibonacci_heap_signature::bind<A0, A1, A2, A3, A4>::type >::type { typedef typename detail::fibonacci_heap_signature::bind<A0, A1, A2, A3, A4>::type bound_args; typedef detail::make_fibonacci_heap_base<T, bound_args> base_maker; typedef typename base_maker::type super_t; typedef typename super_t::size_holder_type size_holder; typedef typename super_t::internal_type internal_type; typedef typename base_maker::allocator_argument allocator_argument; template <typename Heap1, typename Heap2> friend struct heap_merge_emulate; private: #ifndef BOOST_DOXYGEN_INVOKED struct implementation_defined: detail::extract_allocator_types<typename base_maker::allocator_argument> { typedef T value_type; typedef typename detail::extract_allocator_types<typename base_maker::allocator_argument>::size_type size_type; typedef typename detail::extract_allocator_types<typename base_maker::allocator_argument>::reference reference; typedef typename base_maker::compare_argument value_compare; typedef typename base_maker::allocator_type allocator_type; typedef typename allocator_type::pointer node_pointer; typedef typename allocator_type::const_pointer const_node_pointer; typedef detail::heap_node_list node_list_type; typedef typename node_list_type::iterator node_list_iterator; typedef typename node_list_type::const_iterator node_list_const_iterator; typedef typename base_maker::node_type node; typedef detail::value_extractor<value_type, internal_type, super_t> value_extractor; typedef typename super_t::internal_compare internal_compare; typedef detail::node_handle<node_pointer, super_t, reference> handle_type; typedef detail::recursive_tree_iterator<node, node_list_const_iterator, const value_type, value_extractor, detail::list_iterator_converter<node, node_list_type> > iterator; typedef iterator const_iterator; typedef detail::tree_iterator<node, const value_type, allocator_type, value_extractor, detail::list_iterator_converter<node, node_list_type>, true, true, value_compare > ordered_iterator; }; typedef typename implementation_defined::node node; typedef typename implementation_defined::node_pointer node_pointer; typedef typename implementation_defined::node_list_type node_list_type; typedef typename implementation_defined::node_list_iterator node_list_iterator; typedef typename implementation_defined::node_list_const_iterator node_list_const_iterator; typedef typename implementation_defined::internal_compare internal_compare; #endif public: typedef T value_type; typedef typename implementation_defined::size_type size_type; typedef typename implementation_defined::difference_type difference_type; typedef typename implementation_defined::value_compare value_compare; typedef typename implementation_defined::allocator_type allocator_type; typedef typename implementation_defined::reference reference; typedef typename implementation_defined::const_reference const_reference; typedef typename implementation_defined::pointer pointer; typedef typename implementation_defined::const_pointer const_pointer; /// \copydoc boost::heap::priority_queue::iterator typedef typename implementation_defined::iterator iterator; typedef typename implementation_defined::const_iterator const_iterator; typedef typename implementation_defined::ordered_iterator ordered_iterator; typedef typename implementation_defined::handle_type handle_type; static const bool constant_time_size = base_maker::constant_time_size; static const bool has_ordered_iterators = true; static const bool is_mergable = true; static const bool is_stable = detail::extract_stable<bound_args>::value; static const bool has_reserve = false; /// \copydoc boost::heap::priority_queue::priority_queue(value_compare const &) explicit fibonacci_heap(value_compare const & cmp = value_compare()): super_t(cmp), top_element(0) {} /// \copydoc boost::heap::priority_queue::priority_queue(priority_queue const &) fibonacci_heap(fibonacci_heap const & rhs): super_t(rhs), top_element(0) { if (rhs.empty()) return; clone_forest(rhs); size_holder::set_size(rhs.size()); } #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES /// \copydoc boost::heap::priority_queue::priority_queue(priority_queue &&) fibonacci_heap(fibonacci_heap && rhs): super_t(std::move(rhs)), top_element(rhs.top_element) { roots.splice(roots.begin(), rhs.roots); rhs.top_element = NULL; } /// \copydoc boost::heap::priority_queue::operator=(priority_queue &&) fibonacci_heap & operator=(fibonacci_heap && rhs) { clear(); super_t::operator=(std::move(rhs)); roots.splice(roots.begin(), rhs.roots); top_element = rhs.top_element; rhs.top_element = NULL; return *this; } #endif /// \copydoc boost::heap::priority_queue::operator=(priority_queue const &) fibonacci_heap & operator=(fibonacci_heap const & rhs) { clear(); size_holder::set_size(rhs.size()); static_cast<super_t&>(*this) = rhs; if (rhs.empty()) top_element = NULL; else clone_forest(rhs); return *this; } ~fibonacci_heap(void) { clear(); } /// \copydoc boost::heap::priority_queue::empty bool empty(void) const { if (constant_time_size) return size() == 0; else return roots.empty(); } /// \copydoc boost::heap::priority_queue::size size_type size(void) const { if (constant_time_size) return size_holder::get_size(); if (empty()) return 0; else return detail::count_list_nodes<node, node_list_type>(roots); } /// \copydoc boost::heap::priority_queue::max_size size_type max_size(void) const { return allocator_type::max_size(); } /// \copydoc boost::heap::priority_queue::clear void clear(void) { typedef detail::node_disposer<node, typename node_list_type::value_type, allocator_type> disposer; roots.clear_and_dispose(disposer(*this)); size_holder::set_size(0); top_element = NULL; } /// \copydoc boost::heap::priority_queue::get_allocator allocator_type get_allocator(void) const { return *this; } /// \copydoc boost::heap::priority_queue::swap void swap(fibonacci_heap & rhs) { super_t::swap(rhs); std::swap(top_element, rhs.top_element); roots.swap(rhs.roots); } /// \copydoc boost::heap::priority_queue::top value_type const & top(void) const { BOOST_ASSERT(!empty()); return super_t::get_value(top_element->value); } /** * \b Effects: Adds a new element to the priority queue. Returns handle to element * * \b Complexity: Constant. * * \b Note: Does not invalidate iterators. * * */ handle_type push(value_type const & v) { size_holder::increment(); node_pointer n = allocator_type::allocate(1); new(n) node(super_t::make_node(v)); roots.push_front(*n); if (!top_element || super_t::operator()(top_element->value, n->value)) top_element = n; return handle_type(n); } #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) /** * \b Effects: Adds a new element to the priority queue. The element is directly constructed in-place. Returns handle to element. * * \b Complexity: Constant. * * \b Note: Does not invalidate iterators. * * */ template <class... Args> handle_type emplace(Args&&... args) { size_holder::increment(); node_pointer n = allocator_type::allocate(1); new(n) node(super_t::make_node(std::forward<Args>(args)...)); roots.push_front(*n); if (!top_element || super_t::operator()(top_element->value, n->value)) top_element = n; return handle_type(n); } #endif /** * \b Effects: Removes the top element from the priority queue. * * \b Complexity: Logarithmic (amortized). Linear (worst case). * * */ void pop(void) { BOOST_ASSERT(!empty()); node_pointer element = top_element; roots.erase(node_list_type::s_iterator_to(*element)); finish_erase_or_pop(element); } /** * \b Effects: Assigns \c v to the element handled by \c handle & updates the priority queue. * * \b Complexity: Logarithmic if current value < v, Constant otherwise. * * */ void update (handle_type handle, const_reference v) { if (super_t::operator()(super_t::get_value(handle.node_->value), v)) increase(handle, v); else decrease(handle, v); } /** \copydoc boost::heap::fibonacci_heap::update(handle_type, const_reference) * * \b Rationale: The lazy update function is a modification of the traditional update, that just invalidates * the iterator to the object referred to by the handle. * */ void update_lazy(handle_type handle, const_reference v) { handle.node_->value = super_t::make_node(v); update_lazy(handle); } /** * \b Effects: Updates the heap after the element handled by \c handle has been changed. * * \b Complexity: Logarithmic. * * \b Note: If this is not called, after a handle has been updated, the behavior of the data structure is undefined! * */ void update (handle_type handle) { node_pointer n = handle.node_; node_pointer parent = n->get_parent(); if (parent) { n->parent = NULL; roots.splice(roots.begin(), parent->children, node_list_type::s_iterator_to(*n)); } add_children_to_root(n); consolidate(); } /** \copydoc boost::heap::fibonacci_heap::update (handle_type handle) * * \b Rationale: The lazy update function is a modification of the traditional update, that just invalidates * the iterator to the object referred to by the handle. * */ void update_lazy (handle_type handle) { node_pointer n = handle.node_; node_pointer parent = n->get_parent(); if (parent) { n->parent = NULL; roots.splice(roots.begin(), parent->children, node_list_type::s_iterator_to(*n)); } add_children_to_root(n); } /** * \b Effects: Assigns \c v to the element handled by \c handle & updates the priority queue. * * \b Complexity: Constant. * * \b Note: The new value is expected to be greater than the current one * */ void increase (handle_type handle, const_reference v) { handle.node_->value = super_t::make_node(v); increase(handle); } /** * \b Effects: Updates the heap after the element handled by \c handle has been changed. * * \b Complexity: Constant. * * \b Note: If this is not called, after a handle has been updated, the behavior of the data structure is undefined! * */ void increase (handle_type handle) { node_pointer n = handle.node_; if (n->parent) { if (super_t::operator()(n->get_parent()->value, n->value)) { node_pointer parent = n->get_parent(); cut(n); cascading_cut(parent); } } if (super_t::operator()(top_element->value, n->value)) { top_element = n; return; } } /** * \b Effects: Assigns \c v to the element handled by \c handle & updates the priority queue. * * \b Complexity: Logarithmic. * * \b Note: The new value is expected to be less than the current one * */ void decrease (handle_type handle, const_reference v) { handle.node_->value = super_t::make_node(v); decrease(handle); } /** * \b Effects: Updates the heap after the element handled by \c handle has been changed. * * \b Complexity: Logarithmic. * * \b Note: The new value is expected to be less than the current one. If this is not called, after a handle has been updated, the behavior of the data structure is undefined! * */ void decrease (handle_type handle) { update(handle); } /** * \b Effects: Removes the element handled by \c handle from the priority_queue. * * \b Complexity: Logarithmic. * */ void erase(handle_type const & handle) { node_pointer element = handle.node_; node_pointer parent = element->get_parent(); if (parent) parent->children.erase(node_list_type::s_iterator_to(*element)); else roots.erase(node_list_type::s_iterator_to(*element)); finish_erase_or_pop(element); } /// \copydoc boost::heap::priority_queue::begin iterator begin(void) const { return iterator(roots.begin()); } /// \copydoc boost::heap::priority_queue::end iterator end(void) const { return iterator(roots.end()); } /** * \b Effects: Returns an ordered iterator to the first element contained in the priority queue. * * \b Note: Ordered iterators traverse the priority queue in heap order. * */ ordered_iterator ordered_begin(void) const { return ordered_iterator(roots.begin(), roots.end(), top_element, super_t::value_comp()); } /** * \b Effects: Returns an ordered iterator to the end of the priority queue. * * \b Note: Ordered iterators traverse the priority queue in heap order. * */ ordered_iterator ordered_end(void) const { return ordered_iterator(NULL, super_t::value_comp()); } /** * \b Effects: Merge with priority queue rhs. * * \b Complexity: Constant. * * */ void merge(fibonacci_heap & rhs) { size_holder::add(rhs.get_size()); if (!top_element || (rhs.top_element && super_t::operator()(top_element->value, rhs.top_element->value))) top_element = rhs.top_element; roots.splice(roots.end(), rhs.roots); rhs.top_element = NULL; rhs.set_size(0); super_t::set_stability_count((std::max)(super_t::get_stability_count(), rhs.get_stability_count())); rhs.set_stability_count(0); } /// \copydoc boost::heap::d_ary_heap_mutable::s_handle_from_iterator static handle_type s_handle_from_iterator(iterator const & it) { node * ptr = const_cast<node *>(it.get_node()); return handle_type(ptr); } /// \copydoc boost::heap::priority_queue::value_comp value_compare const & value_comp(void) const { return super_t::value_comp(); } /// \copydoc boost::heap::priority_queue::operator<(HeapType const & rhs) const template <typename HeapType> bool operator<(HeapType const & rhs) const { return detail::heap_compare(*this, rhs); } /// \copydoc boost::heap::priority_queue::operator>(HeapType const & rhs) const template <typename HeapType> bool operator>(HeapType const & rhs) const { return detail::heap_compare(rhs, *this); } /// \copydoc boost::heap::priority_queue::operator>=(HeapType const & rhs) const template <typename HeapType> bool operator>=(HeapType const & rhs) const { return !operator<(rhs); } /// \copydoc boost::heap::priority_queue::operator<=(HeapType const & rhs) const template <typename HeapType> bool operator<=(HeapType const & rhs) const { return !operator>(rhs); } /// \copydoc boost::heap::priority_queue::operator==(HeapType const & rhs) const template <typename HeapType> bool operator==(HeapType const & rhs) const { return detail::heap_equality(*this, rhs); } /// \copydoc boost::heap::priority_queue::operator!=(HeapType const & rhs) const template <typename HeapType> bool operator!=(HeapType const & rhs) const { return !(*this == rhs); } private: #if !defined(BOOST_DOXYGEN_INVOKED) void clone_forest(fibonacci_heap const & rhs) { BOOST_HEAP_ASSERT(roots.empty()); typedef typename node::template node_cloner<allocator_type> node_cloner; roots.clone_from(rhs.roots, node_cloner(*this, NULL), detail::nop_disposer()); top_element = detail::find_max_child<node_list_type, node, internal_compare>(roots, super_t::get_internal_cmp()); } void cut(node_pointer n) { node_pointer parent = n->get_parent(); roots.splice(roots.begin(), parent->children, node_list_type::s_iterator_to(*n)); n->parent = 0; n->mark = false; } void cascading_cut(node_pointer n) { node_pointer parent = n->get_parent(); if (parent) { if (!parent->mark) parent->mark = true; else { cut(n); cascading_cut(parent); } } } void add_children_to_root(node_pointer n) { for (node_list_iterator it = n->children.begin(); it != n->children.end(); ++it) { node_pointer child = static_cast<node_pointer>(&*it); child->parent = 0; } roots.splice(roots.end(), n->children); } void consolidate(void) { if (roots.empty()) return; static const size_type max_log2 = sizeof(size_type) * 8; boost::array<node_pointer, max_log2> aux; aux.assign(NULL); node_list_iterator it = roots.begin(); top_element = static_cast<node_pointer>(&*it); do { node_pointer n = static_cast<node_pointer>(&*it); ++it; size_type node_rank = n->child_count(); if (aux[node_rank] == NULL) aux[node_rank] = n; else { do { node_pointer other = aux[node_rank]; if (super_t::operator()(n->value, other->value)) std::swap(n, other); if (other->parent) n->children.splice(n->children.end(), other->parent->children, node_list_type::s_iterator_to(*other)); else n->children.splice(n->children.end(), roots, node_list_type::s_iterator_to(*other)); other->parent = n; aux[node_rank] = NULL; node_rank = n->child_count(); } while (aux[node_rank] != NULL); aux[node_rank] = n; } if (super_t::operator()(top_element->value, n->value)) top_element = n; } while (it != roots.end()); } void finish_erase_or_pop(node_pointer erased_node) { add_children_to_root(erased_node); erased_node->~node(); allocator_type::deallocate(erased_node, 1); size_holder::decrement(); if (!empty()) consolidate(); else top_element = NULL; } mutable node_pointer top_element; node_list_type roots; #endif }; } /* namespace heap */ } /* namespace boost */ #undef BOOST_HEAP_ASSERT #endif /* BOOST_HEAP_FIBONACCI_HEAP_HPP */
[ "amos.sironi@gmail.com" ]
amos.sironi@gmail.com
e59ac7e0fe9c53516bf88de66f9f37d2c447f38b
1e0bc6367affd3b4b79aaa1a48259657f740acbe
/include/audioManager.hpp
806d39b4c52e0f16313461c0ac7c0ee6fd302804
[ "MIT" ]
permissive
theKlanc/Z5
2e6cd562d419e202c0238acecb17e43c6427ae63
97c28f31483d1d5c8c7d1aa61155b256b3d4094a
refs/heads/master
2022-02-08T00:53:28.693412
2022-01-25T13:56:46
2022-01-25T13:56:46
173,024,498
5
0
null
null
null
null
UTF-8
C++
false
false
408
hpp
#pragma once #include "HI2.hpp" #include <unordered_map> class audioManager { public: audioManager() = default; ~audioManager(); bool isAudioLoaded(std::string audioFile) const; HI2::Audio* loadAudio(std::string fileName); void freeAudio(std::string audioName); HI2::Audio* getAudio(std::string audioName); void freeAllAudio(); private: std::unordered_map<std::string, HI2::Audio> audioAtlas; };
[ "clank201@gmail.com" ]
clank201@gmail.com
885fd38b821c10a6161dc46210b04fbbf8d664ef
fb227e3635b5c06e49bad48928f7b6d3254c4dca
/codeforces/gym/tamuFall19/e.cpp
781dc676be71535751f78378d9537ae6f57ebb46
[]
no_license
BryanValeriano/marathon
5be2ab354e49187c865f0296f7dfb5ab3c3d6c9b
8dadfad7d1a6822f61ba5ed4a06e998541515634
refs/heads/master
2022-09-11T00:06:14.982588
2022-09-03T17:01:30
2022-09-03T17:01:30
141,581,750
0
0
null
null
null
null
UTF-8
C++
false
false
1,186
cpp
#include <bits/stdc++.h> using namespace std; #define fr(i,n) _back #define pb push_back #define eb emplace_back #define mk make_pair #define fi first #define se second #define endl '\n' typedef long long ll; typedef pair<int,int> ii; typedef vector<ii> vii; const int INF = 0x3f3f3f3f; const double PI = acos(-1.0); const int T = 1e5 + 3; int n,k; string s; int next[T]; unordered_set<int> inis; int t = 1; int main() { ios_base::sync_with_stdio(false); cin >> n >> k >> s; s += '$'; char ok = s[0]; char prox = (s.size() > t? s[t] : '#'); for(int i = 0; i < s.size(); i++) if(s[i] == ok) inis.insert(i); while(inis.size() >= k) { t++; ok = prox; prox = (s.size() > t? s[t] : '#'); vector<int> del; for(auto w : inis) if(s[w+t-1] != ok) del.pb(w); //cout << inis.size() << " " << del.size() << endl; if(inis.size() - del.size() < k) break; for(int i = 0; i < del.size(); i++) inis.erase(del[i]); } if(inis.size() < k) { cout << "NO IDEA" << endl; } else { for(int i = 0; i < t-1; i++) cout << s[i]; cout << endl; } return 0; }
[ "bryan.b.valeriano@gmail.com" ]
bryan.b.valeriano@gmail.com
d185ecbaf12b0795089f1bf8a3f7f55ab723b123
4b19135464a032c1d5271cd1ae58afb21df38584
/Samples/C++/DirectInput/DIConfig/cdiacpage.h
6b2bb29fe67d1cce4e530e59d963e5e8f20e15d8
[]
no_license
sjk7/DX90SDK
f47cebbba53133923880004bc6e3a33cff1fe895
dd155425badb2cd3993c27f869efc007764e599b
refs/heads/master
2021-08-26T07:47:03.826451
2021-08-12T05:03:03
2021-08-12T05:03:03
253,911,891
3
1
null
null
null
null
UTF-8
C++
false
false
6,188
h
//----------------------------------------------------------------------------- // File: cdiacpage.h // // Desc: CDIDeviceActionConfigPage implements the page object used by the UI. // A page covers the entire UI minus the device tabs and the bottons at // the bottom. The information window, player combo-box, genre combo- // box, action list tree, and device view window are all managed by // the page. // // Copyright (C) Microsoft Corporation. All Rights Reserved. //----------------------------------------------------------------------------- #ifdef FORWARD_DECLS class CDIDeviceActionConfigPage; #else // FORWARD_DECLS #ifndef __CDIACPAGE_H__ #define __CDIACPAGE_H__ // For WINMM.DLL typedef MMRESULT (WINAPI *FUNCTYPE_timeSetEvent)(UINT, UINT, LPTIMECALLBACK, DWORD_PTR, UINT); extern HINSTANCE g_hWinMmDLL; extern FUNCTYPE_timeSetEvent g_fptimeSetEvent; //implementation class class CDIDeviceActionConfigPage : public IDIDeviceActionConfigPage, public CDeviceUINotify, public CFlexWnd { public: //IUnknown fns STDMETHOD (QueryInterface) (REFIID iid, LPVOID *ppv); STDMETHOD_(ULONG, AddRef) (); STDMETHOD_(ULONG, Release) (); //IDirectInputActionConfigPage STDMETHOD (Create) (DICFGPAGECREATESTRUCT *pcs); STDMETHOD (Show) (LPDIACTIONFORMATW lpDiActFor); STDMETHOD (Hide) (); // layout edit mode STDMETHOD (SetEditLayout) (BOOL bEditLayout); // Set the info box text STDMETHOD (SetInfoText) (int iCode); // Unacquire and Reacquire the device for page's purposes // (the configwnd needs to do this around SetActionMap() calls) STDMETHOD (Unacquire) (); STDMETHOD (Reacquire) (); //construction/destruction CDIDeviceActionConfigPage(); ~CDIDeviceActionConfigPage(); // dialog window message handlers /* BOOL OnInitDialog(HWND hWnd, HWND hwndFocus); BOOL OnCommand(WPARAM wParam, LPARAM lParam); LRESULT OnNotify(WPARAM wParam, LPARAM lParam); void OnPaint(HDC hDC); void OnClick(POINT point, WPARAM, BOOL bLeft);*/ protected: virtual void OnInit(); virtual void OnPaint(HDC hDC); virtual void OnClick(POINT point, WPARAM fwKeys, BOOL bLeft); virtual void OnMouseOver(POINT point, WPARAM fwKeys); virtual LRESULT WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); private: enum CONFIGSTATE {CFGSTATE_NORMAL, CFGSTATE_ASSIGN}; // HWND m_hWnd; // handle to the page dialog window LONG m_cRef; //reference count LPDIACTIONFORMATW m_lpDiac; DIDEVICEINSTANCEW m_didi; LPDIRECTINPUTDEVICE8W m_lpDID; CUIGlobals *m_puig; IDIConfigUIFrameWindow *m_pUIFrame; CONFIGSTATE m_State; // device ui CDeviceUI *m_pDeviceUI; CDeviceControl *m_pCurControl; virtual void DeviceUINotify(const DEVICEUINOTIFY &); virtual BOOL IsControlMapped(CDeviceControl *); // ui logic void SetCurrentControl(CDeviceControl *pControl); void NullAction(LPDIACTIONW lpac); void UnassignControl(CDeviceControl *pControl); friend void CallUnassignControl(CDeviceControl *pControl, LPVOID pVoid, BOOL bFixed); void UnassignAction(LPDIACTIONW lpac); void UnassignSpecificAction(LPDIACTIONW lpac); void UnassignActionsAssignedTo(const GUID &guidInstance, DWORD dwOffset); void AssignCurrentControlToAction(LPDIACTIONW lpac); void ActionClick(LPDIACTIONW lpac); void EnterAssignState(); void ExitAssignState(); void UnassignCallout(); void SetAppropriateDefaultText(); void GlobalUnassignControlAt(const GUID &, DWORD); void SetControlAssignments(); void ShowCurrentControlAssignment(); CBitmap *m_pbmRelAxesGlyph; CBitmap *m_pbmAbsAxesGlyph; CBitmap *m_pbmButtonGlyph; CBitmap *m_pbmHatGlyph; CBitmap *m_pbmCheckGlyph; CBitmap *m_pbmCheckGlyphDark; CBitmap *m_pbmIB; CBitmap *m_pbmIB2; void InitResources(); void FreeResources(); RECT m_rectIB; RECT m_rectIBLeft; RECT m_rectIBRight; LPTSTR m_tszIBText; POINT m_ptIBOffset; POINT m_ptIBOffset2; RECT m_rectIBText; void InitIB(); CViewSelWnd m_ViewSelWnd; void DoViewSel(); CFlexTree m_Tree; CFTItem *m_pRelAxesParent, *m_pAbsAxesParent, *m_pButtonParent, *m_pHatParent, *m_pUnknownParent; void ClearTree(); void InitTree(BOOL bForceInit = FALSE); DWORD m_dwLastControlType; CFTItem *GetItemForActionAssignedToControl(CDeviceControl *pControl); int GetNumItemLpacs(CFTItem *pItem); LPDIACTIONW GetItemLpac(CFTItem *pItem, int i = 0); typedef CArray<LPDIACTIONW, LPDIACTIONW &> RGLPDIACW; // GetItemWithActionNameAndSemType returns an item with the specified action name and semantic type. NULL if none. CFTItem *GetItemWithActionNameAndSemType(LPCWSTR acname, DWORD dwSemantic); BOOL IsActionAssignedHere(int index); // quick fix for offset->objid change: void SetInvalid(LPDIACTIONW); DWORD GetOffset(LPDIACTIONW); void SetOffset(LPDIACTIONW, DWORD); bidirlookup<DWORD, DWORD> offset_objid; HRESULT InitLookup(); // dropdowns CFlexComboBox m_UserNames, m_Genres; // Information window CFlexInfoBox m_InfoBox; // Sort Assigned check box for keyboard devices CFlexCheckBox m_CheckBox; // device control DWORD m_cbDeviceDataSize; DWORD *m_pDeviceData[2]; int m_nOnDeviceData; BOOL m_bFirstDeviceData; void InitDevice(); void DeviceTimer(); static void CALLBACK DeviceTimerProc(UINT uID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2); void DeviceDelta(DWORD *pData, DWORD *pOldData); void AxisDelta(const DIDEVICEOBJECTINSTANCEW &doi, BOOL data, BOOL old); void ButtonDelta(const DIDEVICEOBJECTINSTANCEW &doi, DWORD data, DWORD old); void PovDelta(const DIDEVICEOBJECTINSTANCEW &doi, DWORD data, DWORD old); void ActivateObject(const DIDEVICEOBJECTINSTANCEW &doi); void DeactivateObject(const DIDEVICEOBJECTINSTANCEW &doi); bidirlookup<DWORD, int> objid_avai; typedef CArray<int, int &> AxisValueArray; CArray<AxisValueArray, AxisValueArray &> m_AxisValueArray; void StoreAxisDeltaAndCalcSignificance(const DIDEVICEOBJECTINSTANCEW &doi, DWORD data, DWORD olddata, BOOL &bSig, BOOL &bOldSig); // page index int m_nPageIndex; }; #endif //__CDIACPAGE_H__ #endif // FORWARD_DECLS
[ "radiowebmasters@gmail.com" ]
radiowebmasters@gmail.com
ae9f00121f0686b4819843b3b2ef0f43d883a059
e1bf2321802ffeec65485e310d0c49932f59f83e
/src/keyboard_unix.cpp
be2bbfa654731287a7c88b4af0f47c4d4bbeba84
[ "MIT" ]
permissive
perara-libs/FakeInput
13a0ff4c4340d775eedbd9a9f93cfb9149a07e93
13d7b260634c33ced95d9e3b37780705e4036ab5
refs/heads/master
2023-01-10T16:11:23.055678
2020-11-07T15:42:04
2020-11-07T15:42:04
310,302,651
0
0
MIT
2020-11-05T13:11:11
2020-11-05T13:09:56
null
UTF-8
C++
false
false
1,724
cpp
/** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka <uiii.dev@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "keyboard.hpp" #include <X11/Xlib.h> #include <X11/extensions/XTest.h> #include "display_unix.hpp" #include <iostream> namespace FakeInput { void Keyboard::sendKeyEvent_(Key key, bool isPress) { if(key.keysym() == NoSymbol) { std::cerr << "Cannot send <no key> event" << std::endl; } else { XTestFakeKeyEvent(display(), key.code(), isPress, CurrentTime); XFlush(display()); } } }
[ "uiii.dev@gmail.com" ]
uiii.dev@gmail.com
556ec435ef05c44fbae80a688568fc4a18a46867
87c61caaf03578a9e5f6a70e6d8d8e62978c884c
/app/src/main/cpp/ITMLib/Engines/Visualisation/ITMMultiVisualisationEngineFactory.h
89e275381cfb6c91c0a17f6a1941b7ac68c5cc24
[]
no_license
kismeter/InfiniTAM-Android
7ee316533a9d161e7084013c538ec4c59cb61236
46442f060549233b161ecd56f4bcc06e45196061
refs/heads/master
2023-01-02T12:31:08.679921
2020-11-02T13:38:44
2020-11-02T13:38:44
309,376,783
0
0
null
null
null
null
UTF-8
C++
false
false
1,465
h
// Copyright 2014-2017 Oxford University Innovation Limited and the authors of InfiniTAM #pragma once #include "CPU/ITMMultiVisualisationEngine_CPU.h" #ifndef COMPILE_WITHOUT_CUDA #include "CUDA/ITMMultiVisualisationEngine_CUDA.h" #endif #ifdef COMPILE_WITH_METAL //#include "Metal/ITMMultiVisualisationEngine_Metal.h" #endif namespace ITMLib { /** * \brief This struct provides functions that can be used to construct visualisation engines. */ struct ITMMultiVisualisationEngineFactory { //#################### PUBLIC STATIC MEMBER FUNCTIONS #################### /** * \brief Makes a visualisation engine. * * \param deviceType The device on which the visualisation engine should operate. */ template <typename TVoxel, typename TIndex> static ITMMultiVisualisationEngine<TVoxel, TIndex> *MakeVisualisationEngine(ORUtils::DeviceType deviceType) { ITMMultiVisualisationEngine<TVoxel, TIndex> *visualisationEngine = NULL; switch (deviceType) { case ORUtils::DEVICE_CPU: visualisationEngine = new ITMMultiVisualisationEngine_CPU<TVoxel, TIndex>; break; case ORUtils::DEVICE_CUDA: #ifndef COMPILE_WITHOUT_CUDA visualisationEngine = new ITMMultiVisualisationEngine_CUDA<TVoxel, TIndex>; #endif break; case ORUtils::DEVICE_METAL: #ifdef COMPILE_WITH_METAL visualisationEngine = new ITMMultiVisualisationEngine_CPU<TVoxel, TIndex>; #endif break; } return visualisationEngine; } }; }
[ "zhuijun.bao@gmail.com" ]
zhuijun.bao@gmail.com
77d8b345dd5bdb298a4aebe6dc23b5d2b32a597c
4dbaea97b6b6ba4f94f8996b60734888b163f69a
/POJ & HDU/Wash.cpp
6d520158b1d6bea4919956383962c64af3999669
[]
no_license
Ph0en1xGSeek/ACM
099954dedfccd6e87767acb5d39780d04932fc63
b6730843ab0455ac72b857c0dff1094df0ae40f5
refs/heads/master
2022-10-25T09:15:41.614817
2022-10-04T12:17:11
2022-10-04T12:17:11
63,936,497
2
0
null
null
null
null
GB18030
C++
false
false
1,668
cpp
#include <iostream> #include <algorithm> #include <stdio.h> #include <string.h> #define MAX 1000005 #include <queue> using namespace std; struct node { long long base; long long seg; bool operator<(const node &b) const { return seg > b.seg; } }; long long w[MAX], d[MAX], time[MAX]; int main() { int ca, l, n, m; node tmp1; scanf("%d", &ca); for(int j = 1; j <= ca; j++) { priority_queue<node> q1, q2; scanf("%d%d%d", &l, &n, &m); for(int i = 0; i < n; i++) scanf("%lld", &w[i]); for(int i = 0; i < m; i++) scanf("%lld", &d[i]); for(int i = 0; i < n; i++) { tmp1.base = w[i]; tmp1.seg = w[i]; q1.push(tmp1); } for(int i = 0; i < m; i++) { tmp1.base = d[i]; tmp1.seg = d[i]; q2.push(tmp1); } for(int i = 0; i < l; i++) { tmp1 = q1.top(); q1.pop(); ///第i个的结束时间 time[i] = tmp1.seg; tmp1.seg += tmp1.base; q1.push(tmp1); } long long ans = 0; ///烘干过程倒着走和洗衣服过程一样 ///从最晚结束洗衣开始,就是最早倒着完成烘干 for(int i = l-1; i >= 0; i--) { tmp1 = q2.top(); q2.pop(); ans = max(ans, time[i] + tmp1.seg); tmp1.seg += tmp1.base; q2.push(tmp1); } printf("Case #%d: %lld\n", j, ans); } return 0; }
[ "54panguosheng@gmail.com" ]
54panguosheng@gmail.com
1beeeaea0ea746a0ba282862a9b13ccf4d501509
831d755a50762a567047f9ea399d7c1b1dcd56e3
/GraphicsStuff/Vulkan/VulkanDevice.cpp
2955eaf09b3f60c192fa94d9508733c96adfb241
[]
no_license
TheJelmega/GraphicsStuff
a295af829fe72582ce663aa63d5da83ba6d33b5b
587c63e95791d7a6c72623cdb28274a907803c7c
refs/heads/master
2020-04-23T18:14:39.299361
2019-02-28T20:17:39
2019-03-01T01:53:28
171,359,935
0
0
null
null
null
null
UTF-8
C++
false
false
13,888
cpp
#include "VulkanDevice.h" #include "VulkanContext.h" #include "VulkanPhysicalDevice.h" #include "VulkanQueue.h" #include "VulkanInstance.h" namespace Vulkan { VulkanDevice::VulkanDevice() : m_pContext() , m_pPhysicalDevice(nullptr) , m_pAllocCallbacks(nullptr) , m_Device(VK_NULL_HANDLE) { } VulkanDevice::~VulkanDevice() { } VkResult VulkanDevice::Init(VulkanContext* pContext, VulkanPhysicalDevice* pPhysicalDevice, const std::vector<const char*>& requestedExtensions, const std::vector<const char*>& requestedLayers, const VkPhysicalDeviceFeatures& features, const std::vector<VkDeviceQueueCreateInfo>& deviceQueues) { m_pContext = pContext; m_pAllocCallbacks = m_pContext->GetAllocationCallbacks(); m_pPhysicalDevice = pPhysicalDevice; m_EnabledExtensions = requestedExtensions; m_EnabledLayers = requestedLayers; VkPhysicalDeviceFeatures devFeatures = features; VkDeviceCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; createInfo.enabledExtensionCount = u32(m_EnabledExtensions.size()); createInfo.ppEnabledExtensionNames = m_EnabledExtensions.data(); createInfo.enabledLayerCount = u32(m_EnabledLayers.size()); createInfo.ppEnabledLayerNames = m_EnabledLayers.data(); createInfo.pEnabledFeatures = &devFeatures; createInfo.queueCreateInfoCount = u32(deviceQueues.size()); createInfo.pQueueCreateInfos = deviceQueues.data(); VkResult vkres =::vkCreateDevice(m_pPhysicalDevice->GetPhysicalDevice(), &createInfo, m_pAllocCallbacks, &m_Device); if (vkres != VK_SUCCESS) { //g_Logger.LogFormat(LogVulkanRHI(), LogLevel::Fatal, "Failed to create the vulkan device (VkResult: %s)!", Helpers::GetResultstd::string(vkres)); return vkres; } return VK_SUCCESS; } void VulkanDevice::Destroy() { if (m_Device) { vkDestroyDevice(m_Device, m_pAllocCallbacks); } } b8 VulkanDevice::WaitIdle() { VkResult vkres =::vkDeviceWaitIdle(m_Device); return vkres == VK_SUCCESS; } b8 VulkanDevice::IsExtensionAvailable(const std::string& extension) { return m_pPhysicalDevice->IsExtensionAvailable(extension); } b8 VulkanDevice::IsLayerAvailable(const std::string& layer) { return m_pPhysicalDevice->IsLayerAvailable(layer); } b8 VulkanDevice::IsExtensionEnabled(const std::string& extension) { for (const char* name : m_EnabledExtensions) { if (name == extension) return true; } return false; } b8 VulkanDevice::IsLayerEnabled(const std::string& layer) { for (const char* name : m_EnabledLayers) { if (name == layer) return true; } return false; } std::vector<RHI::Queue*>& VulkanDevice::CreateQueues(const std::vector<RHI::QueueInfo>& deviceQueues) {; for (const RHI::QueueInfo& info : deviceQueues) { for (u32 i = 0; i < info.count; ++i) { VulkanQueue* pQueue = new VulkanQueue(); b8 res = pQueue->Init(m_pContext, info.type, i, info.priority); if (!res) { //g_Logger.LogError(LogVulkanRHI(), "Failed to initialize queue!"); } m_Queues.push_back(pQueue); } } return m_Queues; } VkQueue VulkanDevice::vkGetQueue(u32 family, u32 index) { VkQueue queue; vkGetDeviceQueue(m_Device, family, index, &queue); return queue; } u32 VulkanDevice::GetQueueFamily(RHI::QueueType type) { return m_pPhysicalDevice->GetQueueFamily(type); } RHI::Queue* VulkanDevice::GetPresentQueue() { for (RHI::Queue* pQueue : m_Queues) { if ((pQueue->GetQueueType() & RHI::QueueType::Graphics) != RHI::QueueType::Unknown) return pQueue; } return nullptr; } //////////////////////////////////////////////////////////////////////////////// VkResult VulkanDevice::vkCreateSwapchain(const VkSwapchainCreateInfoKHR& createInfo, VkSwapchainKHR& swapchain) { return ::vkCreateSwapchainKHR(m_Device, &createInfo, m_pAllocCallbacks, &swapchain); } void VulkanDevice::vkDestroySwapchain(VkSwapchainKHR swapchain) { ::vkDestroySwapchainKHR(m_Device, swapchain, m_pAllocCallbacks); } VkResult VulkanDevice::vkGetSwapchainImages(VkSwapchainKHR swapchain, u32& imageCount, VkImage* pImages) { return ::vkGetSwapchainImagesKHR(m_Device, swapchain, &imageCount, pImages); } VkResult VulkanDevice::vkAquireNextImage(VkSwapchainKHR swapchain, u32& nextImageIndex, VkSemaphore semaphore, VkFence fence, u64 timeout) { return ::vkAcquireNextImageKHR(m_Device, swapchain, timeout, semaphore, fence, &nextImageIndex); } VkResult VulkanDevice::vkCreateImage(const VkImageCreateInfo& createInfo, VkImage& image) { return ::vkCreateImage(m_Device, &createInfo, m_pAllocCallbacks, &image); } void VulkanDevice::vkDestroyImage(VkImage image) { ::vkDestroyImage(m_Device, image, m_pAllocCallbacks); } VkResult VulkanDevice::vkCreateImageView(const VkImageViewCreateInfo& createInfo, VkImageView& imageView) { return ::vkCreateImageView(m_Device, &createInfo, m_pAllocCallbacks, &imageView); } void VulkanDevice::vkDestroyImageView(VkImageView imageView) { ::vkDestroyImageView(m_Device, imageView, m_pAllocCallbacks); } void VulkanDevice::vkGetImageMemoryRequirements(VkImage image, VkMemoryRequirements& requirements) { ::vkGetImageMemoryRequirements(m_Device, image, &requirements); } VkResult VulkanDevice::vkBindImageMemory(VkImage image, VkDeviceMemory memory, VkDeviceSize offset) { return ::vkBindImageMemory(m_Device, image, memory, offset); } VkResult VulkanDevice::vkCreateSampler(const VkSamplerCreateInfo& createInfo, VkSampler& sampler) { return ::vkCreateSampler(m_Device, &createInfo, m_pAllocCallbacks, &sampler); } void VulkanDevice::vkDestroySampler(VkSampler sampler) { ::vkDestroySampler(m_Device, sampler, m_pAllocCallbacks); } VkResult VulkanDevice::vkCreateShaderModule(const VkShaderModuleCreateInfo& createInfo, VkShaderModule& shaderModule) { return ::vkCreateShaderModule(m_Device, &createInfo, m_pAllocCallbacks, &shaderModule); } void VulkanDevice::vkDestroyShaderModule(VkShaderModule shaderModule) { ::vkDestroyShaderModule(m_Device, shaderModule, m_pAllocCallbacks); } VkResult VulkanDevice::vkCreatePipelineLayout(const VkPipelineLayoutCreateInfo& createInfo, VkPipelineLayout& pipelineLayout) { return ::vkCreatePipelineLayout(m_Device, &createInfo, m_pAllocCallbacks, &pipelineLayout); } void VulkanDevice::vkDestroyPipelineLayout(VkPipelineLayout pipelineLayout) { ::vkDestroyPipelineLayout(m_Device, pipelineLayout, m_pAllocCallbacks); } VkResult VulkanDevice::vkCreatePipeline(const VkGraphicsPipelineCreateInfo& createInfo, VkPipeline& pipeline, VkPipelineCache cache) { return ::vkCreateGraphicsPipelines(m_Device, cache, 1, &createInfo, m_pAllocCallbacks, &pipeline); } VkResult VulkanDevice::vkCreatePipeline(const VkComputePipelineCreateInfo& createInfo, VkPipeline& pipeline, VkPipelineCache cache) { return ::vkCreateComputePipelines(m_Device, cache, 1, &createInfo, m_pAllocCallbacks, &pipeline); } void VulkanDevice::vkDestroyPipeline(VkPipeline pipeline) { ::vkDestroyPipeline(m_Device, pipeline, m_pAllocCallbacks); } VkResult VulkanDevice::vkCreateRenderPass(const VkRenderPassCreateInfo& createInfo, VkRenderPass& renderPass) { return ::vkCreateRenderPass(m_Device, &createInfo, m_pAllocCallbacks, &renderPass); } void VulkanDevice::vkDestroyRenderPass(VkRenderPass renderPass) { ::vkDestroyRenderPass(m_Device, renderPass, m_pAllocCallbacks); } VkResult VulkanDevice::vkCreateFramebuffer(const VkFramebufferCreateInfo& createInfo, VkFramebuffer& framebuffer) { return ::vkCreateFramebuffer(m_Device, &createInfo, m_pAllocCallbacks, &framebuffer); } void VulkanDevice::vkDestroyFramebuffer(VkFramebuffer framebuffer) { ::vkDestroyFramebuffer(m_Device, framebuffer, m_pAllocCallbacks); } VkResult VulkanDevice::vkCreateCommandPool(const VkCommandPoolCreateInfo& createInfo, VkCommandPool& commandPool) { return ::vkCreateCommandPool(m_Device, &createInfo, m_pAllocCallbacks, &commandPool); } void VulkanDevice::vkDestroyCommandPool(VkCommandPool commandPool) { ::vkDestroyCommandPool(m_Device, commandPool, m_pAllocCallbacks); } VkResult VulkanDevice::VkAllocateCommandBuffer(const VkCommandBufferAllocateInfo& allocInfo, VkCommandBuffer* pCommandBuffers) { assert(allocInfo.commandBufferCount == 1); return ::vkAllocateCommandBuffers(m_Device, &allocInfo, pCommandBuffers); } void VulkanDevice::vkFreeCommandBuffers(VkCommandPool commandPool, VkCommandBuffer commandBuffer) { ::vkFreeCommandBuffers(m_Device, commandPool, 1, &commandBuffer); } void VulkanDevice::vkFreeCommandBuffers(VkCommandPool commandPool, const std::vector<VkCommandBuffer> commandBuffers) { ::vkFreeCommandBuffers(m_Device, commandPool, u32(commandBuffers.size()), commandBuffers.data()); } VkResult VulkanDevice::vkAllocateMemory(const VkMemoryAllocateInfo& allocInfo, VkDeviceMemory& memory) { return ::vkAllocateMemory(m_Device, &allocInfo, m_pAllocCallbacks, &memory); } void VulkanDevice::vkFreeMemory(VkDeviceMemory memory) { ::vkFreeMemory(m_Device, memory, m_pAllocCallbacks); } VkResult VulkanDevice::VkMapMemory(VkDeviceMemory memory, VkDeviceSize offset, VkDeviceSize size, void** ppData) { // Flags are 0, since until 1.1.73, flags are reserved return ::vkMapMemory(m_Device, memory, offset, size, 0, ppData); } void VulkanDevice::VkUnmapMemory(VkDeviceMemory memory) { ::vkUnmapMemory(m_Device, memory); } VkResult VulkanDevice::vkFlushMappedMemoryRanges(const VkMappedMemoryRange& range) { return ::vkFlushMappedMemoryRanges(m_Device, 1, &range); } VkResult VulkanDevice::vkFlushMappedMemoryRanges(const std::vector<VkMappedMemoryRange>& ranges) { return ::vkFlushMappedMemoryRanges(m_Device, u32(ranges.size()), ranges.data()); } VkResult VulkanDevice::vkInvalidateMappedMemoryRanges(const VkMappedMemoryRange& range) { return ::vkInvalidateMappedMemoryRanges(m_Device, 1, &range); } VkResult VulkanDevice::vkInvalidateMappedMemoryRanges(const std::vector<VkMappedMemoryRange>& ranges) { return ::vkInvalidateMappedMemoryRanges(m_Device, u32(ranges.size()), ranges.data()); } VkResult VulkanDevice::vkCreateBuffer(const VkBufferCreateInfo& createInfo, VkBuffer& buffer) { return ::vkCreateBuffer(m_Device, &createInfo, m_pAllocCallbacks, &buffer); } void VulkanDevice::vkDestroyBuffer(VkBuffer buffer) { ::vkDestroyBuffer(m_Device, buffer, m_pAllocCallbacks); } VkResult VulkanDevice::vkCreateBufferView(const VkBufferViewCreateInfo& createInfo, VkBufferView& bufferView) { return ::vkCreateBufferView(m_Device, &createInfo, m_pAllocCallbacks, &bufferView); } void VulkanDevice::vkDestroyBufferView(VkBufferView bufferView) { ::vkDestroyBufferView(m_Device, bufferView, m_pAllocCallbacks); } void VulkanDevice::vkGetBufferMemoryRequirements(VkBuffer buffer, VkMemoryRequirements& requirements) { ::vkGetBufferMemoryRequirements(m_Device, buffer, &requirements); } VkResult VulkanDevice::vkBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, VkDeviceSize offset) { return ::vkBindBufferMemory(m_Device, buffer, memory, offset); } VkResult VulkanDevice::vkCreateDescriptorSetLayout(const VkDescriptorSetLayoutCreateInfo& createInfo, VkDescriptorSetLayout& descriptorSetLayout) { return ::vkCreateDescriptorSetLayout(m_Device, &createInfo, m_pAllocCallbacks, &descriptorSetLayout); } void VulkanDevice::vkDestroyDescriptorSetLayout(VkDescriptorSetLayout descriptorSetLayout) { ::vkDestroyDescriptorSetLayout(m_Device, descriptorSetLayout, m_pAllocCallbacks); } VkResult VulkanDevice::vkCreateDescriptorPool(const VkDescriptorPoolCreateInfo& createInfo, VkDescriptorPool& descriptorPool) { return ::vkCreateDescriptorPool(m_Device, &createInfo, m_pAllocCallbacks, &descriptorPool); } void VulkanDevice::vkDestroyDescriptorPool(VkDescriptorPool descriptorPool) { ::vkDestroyDescriptorPool(m_Device, descriptorPool, m_pAllocCallbacks); } VkResult VulkanDevice::vkAllocateDescriptorSet(const VkDescriptorSetAllocateInfo& allocInfo, VkDescriptorSet& descriptorPool) { assert(allocInfo.descriptorSetCount == 1); return ::vkAllocateDescriptorSets(m_Device, &allocInfo, &descriptorPool); } void VulkanDevice::vkFreeDescriptorSet(VkDescriptorPool pool, VkDescriptorSet set) { ::vkFreeDescriptorSets(m_Device, pool, 1, &set); } void VulkanDevice::vkUpdateDescriptorSets(u32 numWrites, VkWriteDescriptorSet* writes, u32 numCopies, VkCopyDescriptorSet* copies) { ::vkUpdateDescriptorSets(m_Device, numWrites, writes, numCopies, copies); } VkResult VulkanDevice::vkCreateSemapore(const VkSemaphoreCreateInfo& createInfo, VkSemaphore& semaphore) { return ::vkCreateSemaphore(m_Device, &createInfo, m_pAllocCallbacks, &semaphore); } void VulkanDevice::vkDestroySemaphore(VkSemaphore semaphore) { ::vkDestroySemaphore(m_Device, semaphore, m_pAllocCallbacks); } VkResult VulkanDevice::vkCreateFence(const VkFenceCreateInfo& createInfo, VkFence& fence) { return ::vkCreateFence(m_Device, &createInfo, m_pAllocCallbacks, &fence); } void VulkanDevice::vkDestroyFence(VkFence fence) { ::vkDestroyFence(m_Device, fence, m_pAllocCallbacks); } VkResult VulkanDevice::vkResetFence(VkFence fence) { return ::vkResetFences(m_Device, 1, &fence); } VkResult VulkanDevice::vkResetFences(std::vector<VkFence>& fences) { return ::vkResetFences(m_Device, u32(fences.size()), fences.data()); } VkResult VulkanDevice::vkWaitForFence(VkFence fence, u64 timeout) { return ::vkWaitForFences(m_Device, 1, &fence, true, timeout); } VkResult VulkanDevice::vkWaitForFences(std::vector<VkFence>& fences, b8 waitForAll, u64 timeout) { return ::vkWaitForFences(m_Device, u32(fences.size()), fences.data(), waitForAll, timeout); } VkResult VulkanDevice::vkGetFenceStatus(VkFence& fence) { return ::vkGetFenceStatus(m_Device, fence); } }
[ "jelmega@gmail.com" ]
jelmega@gmail.com
1ff653efc9717deec53af5ae1e2faf0a4e1156ad
518021080c38cc9fe24a26bc2c950460e83245b3
/A_2/A_2/Line.h
024e49a04a9ff38d4955e21ce3d0f8131fa81cf3
[]
no_license
DV1537/assignment-a2-Rozemes
93d3a157e907fd2c46928e88655ce7eabe98dfe9
11c4da10bf4a745ccce999a8a28bad3dd0dd6ecc
refs/heads/master
2020-04-08T08:46:29.600608
2019-02-01T22:08:55
2019-02-01T22:08:55
159,193,387
0
0
null
null
null
null
UTF-8
C++
false
false
223
h
#ifndef LINE #define LINE #include "Shape.h" class Line : public Shape { public: Line(Coord *vertices, int size) : Shape(vertices, size) {}; ~Line() {}; string getType() const override { return "Line"; }; }; #endif
[ "jones.t@live.se" ]
jones.t@live.se
54b57340d954e89faf8f849a413f8ce79b380751
a586d503c0abcae6e61a62c78fff39806863ddad
/d04/ex02/ISquad.hpp
ad5473d747ff902454c941c92f4753b4306a6818
[]
no_license
akolomoi/cpp_pool
b18952428e2f62172d79b50c5b0a1d496b72c6c1
7f372f9ac683dd3da740098d1c33aaddf26f764b
refs/heads/master
2022-04-05T17:01:17.164350
2020-02-03T14:10:01
2020-02-03T14:10:01
237,979,179
0
0
null
null
null
null
UTF-8
C++
false
false
1,147
hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ISquad.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: akolomoi <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/12/07 20:42:00 by akolomoi #+# #+# */ /* Updated: 2019/12/07 20:42:01 by akolomoi ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef ISQUAD_H # define ISQUAD_H # include "./ISpaceMarine.hpp" class ISquad { public: virtual ~ISquad() {} virtual int getCount() const = 0; virtual ISpaceMarine* getUnit(int i) const = 0; virtual int push(ISpaceMarine* m) = 0; }; #endif
[ "akolomoi@e1r4p1.unit.ua" ]
akolomoi@e1r4p1.unit.ua
58813bb467dcf947120d0633edd3af5675b101e2
44c9ff011eca8449e7fa4d7d8ab42115d9d0670e
/friendsmodel.h
a68f1984764ebe4efbce5dd393fd3a64706d8958
[]
no_license
Katerinaaaa/171-341_Golovchenko_MobDev
78988a15eff75df4ecaf91cd15bebcaab6d3abba
873ee0539c46f7648166f237417ffc4b8e094371
refs/heads/master
2020-05-01T06:34:17.305154
2019-06-10T07:43:17
2019-06-10T07:43:17
177,333,246
0
0
null
null
null
null
UTF-8
C++
false
false
1,647
h
#ifndef FRIENDSMODEL_H #define FRIENDSMODEL_H #include <QVariant> #include <QObject> #include <QList> #include <QModelIndex> #include <QAbstractListModel> class FriendsObject { public: FriendsObject(const QString &p_name, const QString &p_surname, const QUrl &p_photo, const int &p_friend_id); // QString getName() const; QString getSurname() const; QUrl getPhoto() const; int getId() const; // прочие get-методы для выдачи ID, URL фотографии и др. private: QString m_name; QString m_surname; QUrl m_photo; int m_friend_id; // прочие свойства для хранения ID, URL фотографии и др. }; class FriendsModel : public QAbstractListModel{ Q_OBJECT public: enum enmRoles { FriendName = Qt::UserRole + 1, FriendSurname, FriendPhoto, Friend_id }; FriendsModel(QObject *parent = nullptr); void addItem(const FriendsObject & newItem); int rowCount(const QModelIndex & parent = QModelIndex()) const; QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const; // возвращает по индексу переменную (импользуется в ЛР 8) QVariantMap get(int idx) const; void clear(); protected: QHash<int, QByteArray> roleNames() const; // ключ - значение // нужен, чтобы строковые имена приводить в соответствие к полям френда private: QList<FriendsObject> m_items; }; #endif // FRIENDSMODEL_H
[ "tigerkaterina@gmail.com" ]
tigerkaterina@gmail.com
cccef95293f41dd97e8c2dba9ca7455389121111
47285fb3007f4493486b6db790c599265b23763d
/activation_fun/Tanh.cpp
6ca4db5794a6383be2ce8f186fecc2106375115b
[ "MIT" ]
permissive
navneel99/image_processing_library
a207258fa1dfbdc1f656c0b753e1ffad9075fa5e
c4a13be8a9c7b2d7b1f6373bc6b3707d0d01be76
refs/heads/master
2020-04-15T18:15:27.524210
2019-02-22T07:42:32
2019-02-22T07:42:32
164,907,199
0
0
null
null
null
null
UTF-8
C++
false
false
349
cpp
#include "tanh.hpp" vector<vector<float> > Tanh(vector<vector<float> > v){ vector<float> row; float ele; for (int it = 0; it < v.size(); it++){ row = v.at(it); for (int it2 = 0;it2 < row.size(); it2++){ ele = row.at(it2); row[it2] = tanh(ele); } v[it] = row; } return v; }
[ "navneel99@gmail.com" ]
navneel99@gmail.com
2255169968f74b6752f697d9de769a9c6e2a0f5d
5931a1d149e21295c00ab9103ddede9ad80da258
/edges.h
8ef5ef03c6cac86f2a9ad870513f9c591fce7b3e
[]
no_license
Annakarolczak/grafy
f6c18fec23fbe0f1006dacb88bde03a2e4572a20
d024055752f271fecf46c13267fd41d8302002c7
refs/heads/master
2020-12-24T13:00:39.089802
2017-02-07T14:30:19
2017-02-07T14:30:19
66,551,110
0
0
null
null
null
null
UTF-8
C++
false
false
338
h
#ifndef EDGES_H #define EDGES_H #include <QMainWindow> #include <QObject> #include <QWidget> #include "vertex.h" class Edges { public: Edges(); Edges(Vertex &p_, Vertex &k_, double weight_ = 1.0, bool skier = false); double waga; unsigned long p_id, k_id; QColor kolor; bool skierowana; }; #endif // EDGES_H
[ "akarolczak-bandurska@egnyte.com" ]
akarolczak-bandurska@egnyte.com
33ebc7ba585507646a0c603cbc88957130a6a554
c8a04cea9afde109e8f7ffce09bde1c616c1bb2e
/maximize-sum-of-array-after-k-negations/maximize-sum-of-array-after-k-negations.cpp
b0fb597e7265ed86774adc0bc51d66708ed31f36
[ "MIT" ]
permissive
JanaSabuj/Leetcode-solutions
956fea8538b3d87b999d0c65ef158ad8500b61c7
68464fc54c18ec6d7d72e862c1c75e8309314198
refs/heads/master
2022-09-12T13:32:13.884649
2022-08-15T06:21:34
2022-08-15T06:21:34
165,518,391
17
5
null
2020-04-17T13:26:01
2019-01-13T14:59:56
C++
UTF-8
C++
false
false
940
cpp
class Solution { public:    int largestSumAfterKNegations(vector<int>& A, int K) {        sort(A.begin(), A.end());        int n = A.size();        int absum=0;        int neg = 0;        int mn = INT_MAX;        for(auto x: A){            absum += abs(x);            if(x < 0)                neg++;            mn = min(mn, abs(x));       }                int sum=0;        if(K <= neg){                        for(int i = 0; i < K; i++)                sum += abs(A[i]);            for(int i = K; i < n; i++)                sum += A[i];                   }else{            int e = K - neg;            sum = absum;            if(e & 1)                sum -= 2*mn;                               }                return sum;               } };
[ "sabujlovescoding@gmail.com" ]
sabujlovescoding@gmail.com
ac2cdb993f965b49f2d1f6a161dac4276c12161c
32f0212af6c615868940f44b2e57686f9d755d57
/Judge/BaekjoonOnline/baekjoon11659_v2.cpp
21999a4436b5c973975ae54a2ba6cfa32bcd3337
[]
no_license
micMalloc/Algorithm
9aa3c47b492fe7be2239a14501aac4fd9efc5a47
766626bea64af6c681803efc153eaf23a7c305a2
refs/heads/master
2021-06-11T18:42:35.917637
2020-07-01T15:25:48
2020-07-01T15:25:48
93,248,063
1
0
null
null
null
null
UTF-8
C++
false
false
1,311
cpp
#include <cstdio> #include <cmath> #include <vector> using namespace std; int init_segment_tree (int, int, int); int get_sum (int, int, int, int, int); vector<int> data; vector<int> segment_tree; int main (int argc, char** argv) { int n, m; int h, tree_size; int l, r; scanf("%d %d", &n, &m); data.resize(n + 1, 0); h = (int)ceil(log(n) / log(2)); tree_size = (1 << (h + 1)); segment_tree.resize(tree_size, 0); for (int i = 1; i <= n; ++ i) { scanf("%d", &data[i]); } init_segment_tree(1, 1, n); while (m --) { scanf("%d %d", &l, &r); printf("%d\n", get_sum(1, l, r, 1, n)); } return 0; } int init_segment_tree (int node, int start, int end) { int mid; if (start == end) { segment_tree[node] = data[start]; } else { mid = (start + end) / 2; segment_tree[node] += init_segment_tree(node * 2, start, mid); segment_tree[node] += init_segment_tree(node * 2 + 1, mid + 1, end); } return segment_tree[node]; } int get_sum (int node, int left, int right, int start, int end) { int mid; int sum = 0; if (left > end || right < start) { return 0; } if (left <= start && end <= right) { return segment_tree[node]; } mid = (start + end) / 2; sum += get_sum(node * 2, left, right, start, mid); sum += get_sum(node * 2 + 1, left, right, mid + 1, end); return sum; }
[ "hesue615@naver.com" ]
hesue615@naver.com
10ffdcdc4f1ed5b63ce5eedc585f0ded2a5f7b69
ea1f28cfc724f71b893e7d22b227d23981a6b6eb
/docker-ramcloud/ramcloud/src/LoggerTest.cc
6fcd2e9b8dd979258e3364d00c601d949f927673
[ "ISC" ]
permissive
khasm/seasky
cfd84a123b23f9bbbb2760d9366d02058e9d0101
b14abf3c252ca6f9e491b5db5fe1680470858724
refs/heads/master
2021-01-18T20:00:56.620765
2017-04-17T10:43:32
2017-04-17T10:43:32
68,630,307
0
0
null
null
null
null
UTF-8
C++
false
false
20,474
cc
/* Copyright (c) 2010-2016 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <regex> #include <sys/types.h> #include "TestUtil.h" #include "TestLog.h" #include "ShortMacros.h" #include "StringUtil.h" namespace RAMCloud { class LoggerTest : public ::testing::Test { public: static const uint32_t numLogLevels = static_cast<uint32_t>(NUM_LOG_LEVELS); struct timespec testTime; Logger logger; Logger* loggerUnderTest; LoggerTest() : testTime({3, 500000000}) , logger(WARNING) , loggerUnderTest(&logger) { logger.testingLogTime = &testTime; logger.setLogFile("__test.log"); } ~LoggerTest() { unlink("__test.log"); } // Given a string, read the log file in __test.log and return everything // in that file starting with the given string. If the string doesn't appear // in the log file, then return the entire file. string logSuffix(const char* s) { loggerUnderTest->sync(); string output = TestUtil::readFile("__test.log"); size_t pos = output.find(s); if (pos != string::npos) { return output.substr(pos); } return output; } // Read the log file from disk (waiting for any buffered data to be // output). string getLog(const char* fileName, bool sanitizeLineNumber = false) { loggerUnderTest->sync(); string result = TestUtil::readFile(fileName); if (sanitizeLineNumber) { std::regex exp("\\.cc:[[:digit:]]{1,4} "); result = std::regex_replace(result, exp, ".cc:xxx "); } return result; } // Configure and use the shared logger in the test. Only used in test // cases involving log macros where Logger::get() is hardcoded. void useSharedLogger() { Logger& sharedLogger = Logger::get(); sharedLogger.reset(); sharedLogger.testingLogTime = &testTime; sharedLogger.setLogFile("__test.log"); loggerUnderTest = &sharedLogger; } DISALLOW_COPY_AND_ASSIGN(LoggerTest); }; TEST_F(LoggerTest, constructor) { Logger l(WARNING); EXPECT_EQ(WARNING, l.logLevels[0]); } TEST_F(LoggerTest, destructor) { // Make sure the print thread exits TestLog::Enable _; Tub<Logger> l; l.construct(WARNING); l.destroy(); EXPECT_EQ("printThreadMain: print thread exiting", TestLog::get()); } TEST_F(LoggerTest, setLogFile_basics) { logger.setLogLevels(NOTICE); logger.setLogFile("__test.log"); logger.logMessage(false, DEFAULT_LOG_MODULE, NOTICE, HERE, "message 1\n"); EXPECT_TRUE(TestUtil::matchesPosixRegex("message 1", getLog("__test.log"))); logger.setLogFile("__test.log", false); logger.logMessage(false, DEFAULT_LOG_MODULE, NOTICE, HERE, "message 2"); EXPECT_TRUE(TestUtil::matchesPosixRegex("message 1.*message 2", getLog("__test.log"))); logger.setLogFile("__test.log", true); logger.logMessage(false, DEFAULT_LOG_MODULE, NOTICE, HERE, "message 3"); EXPECT_TRUE(TestUtil::doesNotMatchPosixRegex("message 1", getLog("__test.log"))); EXPECT_TRUE(TestUtil::matchesPosixRegex("message 3", getLog("__test.log"))); } TEST_F(LoggerTest, setLogFile_cantOpenFile) { Logger l(NOTICE); string message("no exception"); try { l.setLogFile("__gorp/__xyz/__foo"); } catch (Exception& e) { message = e.message; } EXPECT_EQ("couldn't open log file '__gorp/__xyz/__foo': " "No such file or directory", message); } TEST_F(LoggerTest, setLogLevel) { Logger l(WARNING); l.setLogLevel(DEFAULT_LOG_MODULE, NOTICE); EXPECT_EQ(NOTICE, l.logLevels[DEFAULT_LOG_MODULE]); } TEST_F(LoggerTest, setLogLevel_int) { Logger l(WARNING); l.setLogLevel(DEFAULT_LOG_MODULE, -1); EXPECT_EQ(0, l.logLevels[DEFAULT_LOG_MODULE]); l.setLogLevel(DEFAULT_LOG_MODULE, numLogLevels); EXPECT_EQ(numLogLevels - 1, downCast<unsigned>(l.logLevels[DEFAULT_LOG_MODULE])); l.setLogLevel(DEFAULT_LOG_MODULE, 0); EXPECT_EQ(0, l.logLevels[DEFAULT_LOG_MODULE]); l.setLogLevel(DEFAULT_LOG_MODULE, numLogLevels - 1); EXPECT_EQ(numLogLevels - 1, downCast<unsigned>(l.logLevels[DEFAULT_LOG_MODULE])); } TEST_F(LoggerTest, setLogLevel_string) { Logger l(WARNING); l.setLogLevel("default", "-1"); EXPECT_EQ(0, l.logLevels[DEFAULT_LOG_MODULE]); l.setLogLevel("default", "1"); EXPECT_EQ(1, l.logLevels[DEFAULT_LOG_MODULE]); l.setLogLevel("default", "NOTICE"); EXPECT_EQ(NOTICE, l.logLevels[DEFAULT_LOG_MODULE]); l.setLogLevel("transport", "1"); EXPECT_EQ(1, l.logLevels[TRANSPORT_MODULE]); TestLog::Enable _; l.setLogLevel("stabYourself", "1"); l.setLogLevel("default", ""); l.setLogLevel("default", "junk"); EXPECT_EQ( "setLogLevel: Ignoring bad log module name: stabYourself | " "setLogLevel: Ignoring bad log module level: | " "setLogLevel: Ignoring bad log module level: junk", TestLog::get()); } TEST_F(LoggerTest, changeLogLevel) { Logger l(WARNING); l.changeLogLevel(DEFAULT_LOG_MODULE, -1); EXPECT_EQ(ERROR, l.logLevels[DEFAULT_LOG_MODULE]); l.changeLogLevel(DEFAULT_LOG_MODULE, 1); EXPECT_EQ(WARNING, l.logLevels[DEFAULT_LOG_MODULE]); } TEST_F(LoggerTest, setLogLevels) { Logger l(WARNING); l.setLogLevels(NOTICE); for (int i = 0; i < NUM_LOG_MODULES; i++) EXPECT_EQ(NOTICE, l.logLevels[i]); } TEST_F(LoggerTest, setLogLevels_int) { Logger l(WARNING); l.setLogLevels(-1); for (int i = 0; i < NUM_LOG_MODULES; i++) EXPECT_EQ(0, l.logLevels[i]); l.setLogLevels(numLogLevels); for (int i = 0; i < NUM_LOG_MODULES; i++) EXPECT_EQ(numLogLevels - 1, downCast<unsigned>(l.logLevels[i])); l.setLogLevels(0); for (int i = 0; i < NUM_LOG_MODULES; i++) EXPECT_EQ(0, l.logLevels[i]); l.setLogLevels(numLogLevels - 1); for (int i = 0; i < NUM_LOG_MODULES; i++) EXPECT_EQ(numLogLevels - 1, downCast<unsigned>(l.logLevels[i])); } TEST_F(LoggerTest, setLogLevels_string) { Logger l(WARNING); l.setLogLevels("-1"); for (int i = 0; i < NUM_LOG_MODULES; i++) EXPECT_EQ(0, l.logLevels[i]); l.setLogLevels("2"); for (int i = 0; i < NUM_LOG_MODULES; i++) EXPECT_EQ(2, l.logLevels[i]); l.setLogLevels("NOTICE"); for (int i = 0; i < NUM_LOG_MODULES; i++) EXPECT_EQ(NOTICE, l.logLevels[i]); TestLog::Enable _; l.setLogLevels("oral trauma"); EXPECT_EQ( "setLogLevels: Ignoring bad log module level: oral trauma", TestLog::get()); } TEST_F(LoggerTest, changeLogLevels) { Logger l(WARNING); l.changeLogLevels(-1); for (int i = 0; i < NUM_LOG_MODULES; i++) EXPECT_EQ(ERROR, l.logLevels[i]); l.changeLogLevels(1); for (int i = 0; i < NUM_LOG_MODULES; i++) EXPECT_EQ(WARNING, l.logLevels[i]); } TEST_F(LoggerTest, isLogging) { Logger l(WARNING); EXPECT_TRUE(l.isLogging(DEFAULT_LOG_MODULE, ERROR)); EXPECT_TRUE(l.isLogging(DEFAULT_LOG_MODULE, WARNING)); EXPECT_TRUE(!l.isLogging(DEFAULT_LOG_MODULE, NOTICE)); } TEST_F(LoggerTest, logMessage_basics) { logger.setLogFile("__test.log", true); for (int i = 0; i < 3; i++) { logger.logMessage(false, RAMCLOUD_CURRENT_LOG_MODULE, ERROR, CodeLocation("file", 99, "func", "pretty"), "first "); } EXPECT_EQ("0000000003.500000000 file:99 in func ERROR[1]: first " "0000000003.500000000 file:99 in func ERROR[1]: first " "0000000003.500000000 file:99 in func ERROR[1]: first ", getLog("__test.log")); } TEST_F(LoggerTest, logMessage_collapseDuplicates) { logger.collapseIntervalMs = 2; // Log a message several times; only the first should be printed. for (int i = 0; i < 5; i++) { logger.logMessage(true, RAMCLOUD_CURRENT_LOG_MODULE, ERROR, CodeLocation("file", 99, "func", "pretty"), "first "); } EXPECT_EQ("0000000003.500000000 file:99 in func ERROR[1]: first ", getLog("__test.log")); // Log a different message; it should be printed immediately. testTime.tv_nsec += 1000000; logger.setLogFile("__test.log", true); logger.logMessage(true, RAMCLOUD_CURRENT_LOG_MODULE, ERROR, CodeLocation("file", 100, "func", "pretty"), "second "); EXPECT_EQ("0000000003.501000000 file:100 in func ERROR[1]: second ", getLog("__test.log")); // Wait a while and log the original message; one more copy should appear. testTime.tv_nsec += 2000000; logger.setLogFile("__test.log", true); for (int i = 0; i < 3; i++) { logger.logMessage(true, RAMCLOUD_CURRENT_LOG_MODULE, ERROR, CodeLocation("file", 99, "func", "pretty"), "first "); } EXPECT_EQ("0000000003.503000000 file:99 in func ERROR[1]: " "(4 duplicates of this message were skipped) first ", getLog("__test.log")); // Wait another while and log the original message; one more copy // should appear. testTime.tv_nsec += 2000000; logger.setLogFile("__test.log", true); for (int i = 0; i < 2; i++) { logger.logMessage(true, RAMCLOUD_CURRENT_LOG_MODULE, ERROR, CodeLocation("file", 99, "func", "pretty"), "first "); } EXPECT_EQ("0000000003.505000000 file:99 in func ERROR[1]: " "(2 duplicates of this message were skipped) first ", getLog("__test.log")); // Wait another while, then call collapseDuplicates to clean // things up. testTime.tv_nsec += 2000000; logger.setLogFile("__test.log", true); logger.cleanCollapseMap(testTime); EXPECT_EQ("0000000003.507000000 file:99 in func ERROR[1]: " "(1 duplicates of this message were skipped) first ", getLog("__test.log")); } TEST_F(LoggerTest, logMessage_restrictSizeOfCollapseMap) { logger.collapseIntervalMs = 2; logger.maxCollapseMapSize = 2; logger.logMessage(true, RAMCLOUD_CURRENT_LOG_MODULE, ERROR, CodeLocation("file", 97, "func", "pretty"), "first "); logger.logMessage(true, RAMCLOUD_CURRENT_LOG_MODULE, ERROR, CodeLocation("file", 98, "func", "pretty"), "second "); logger.logMessage(true, RAMCLOUD_CURRENT_LOG_MODULE, ERROR, CodeLocation("file", 99, "func", "pretty"), "third "); EXPECT_EQ(2U, logger.collapseMap.size()); } TEST_F(LoggerTest, logMessage_discardEntriesBecauseOfOverflow) { logger.collapseIntervalMs = 2; logger.maxCollapseMapSize = 2; logger.nextToInsert = 0; logger.nextToPrint = 10; logger.logMessage(false, RAMCLOUD_CURRENT_LOG_MODULE, ERROR, CodeLocation("file", 97, "func", "pretty"), "first "); logger.logMessage(false, RAMCLOUD_CURRENT_LOG_MODULE, ERROR, CodeLocation("file", 98, "func", "pretty"), "second "); EXPECT_EQ(2, logger.discardedEntries); logger.nextToPrint = 0; EXPECT_EQ("", getLog("__test.log")); logger.logMessage(false, RAMCLOUD_CURRENT_LOG_MODULE, ERROR, CodeLocation("file", 99, "func", "pretty"), "third "); EXPECT_EQ(0, logger.discardedEntries); EXPECT_EQ("0000000003.500000000 Logger.cc:xxx in logMessage " "WARNING[1]: 2 log messages lost because of buffer overflow\n" "0000000003.500000000 file:99 in func ERROR[1]: third ", getLog("__test.log", true)); } TEST_F(LoggerTest, logMessage_messageTooLong) { // This test exercises all of the code to handle log messages that // are too long for the variable "buffer". logger.collapseIntervalMs = 2; // Overflow happens during warning about discarded entries. logger.discardedEntries = 3; logger.testingBufferSize = 20; logger.setLogFile("__test.log", true); logger.logMessage(true, RAMCLOUD_CURRENT_LOG_MODULE, ERROR, CodeLocation("file", 95, "func", "pretty"), "this is a %s", "fairly long message body"); EXPECT_EQ("0000000003.50000000... (170 chars truncated)\n", getLog("__test.log")); // Overflow happens during standard prefix. logger.discardedEntries = 3; logger.testingBufferSize = 140; logger.setLogFile("__test.log", true); logger.logMessage(true, RAMCLOUD_CURRENT_LOG_MODULE, ERROR, CodeLocation("file", 96, "func", "pretty"), "this is a %s", "fairly long message body"); EXPECT_EQ("0000000003.500000000 Logger.cc:xxx in logMessage " "WARNING[1]: 3 log messages lost because of buffer overflow\n" "0000000003.500000000 file:96 in... (50 chars truncated)\n", getLog("__test.log", true)); // Overflow happens during warning the caller's log message. logger.discardedEntries = 3; logger.testingBufferSize = 188; logger.setLogFile("__test.log", true); logger.logMessage(true, RAMCLOUD_CURRENT_LOG_MODULE, ERROR, CodeLocation("file", 97, "func", "pretty"), "this is a %s", "fairly long message body"); EXPECT_EQ("0000000003.500000000 Logger.cc:xxx in logMessage " "WARNING[1]: 3 log messages lost because of buffer overflow\n" "0000000003.500000000 file:97 in func ERROR[1]: this is a fairly " "long message bo... (2 chars truncated)\n", getLog("__test.log", true)); // No overflow: everything just barely fits. logger.discardedEntries = 3; logger.testingBufferSize = 190; logger.setLogFile("__test.log", true); logger.logMessage(true, RAMCLOUD_CURRENT_LOG_MODULE, ERROR, CodeLocation("file", 98, "func", "pretty"), "this is a %s", "fairly long message body"); EXPECT_EQ("0000000003.500000000 Logger.cc:xxx in logMessage " "WARNING[1]: 3 log messages lost because of buffer overflow\n" "0000000003.500000000 file:98 in func ERROR[1]: this is a fairly " "long message body", getLog("__test.log", true)); // Overflow happens during warning about collapsed entries. for (int i = 0; i < 5; i++) { logger.logMessage(true, RAMCLOUD_CURRENT_LOG_MODULE, ERROR, CodeLocation("file", 98, "func", "pretty"), "this is a %s", "fairly long message body"); } testTime.tv_nsec += 10000000; logger.testingBufferSize = 70; logger.setLogFile("__test.log", true); logger.logMessage(true, RAMCLOUD_CURRENT_LOG_MODULE, ERROR, CodeLocation("file", 98, "func", "pretty"), "this is a %s", "fairly long message body"); EXPECT_EQ("0000000003.510000000 file:98 in func ERROR[1]: " "(5 duplicates of this ... (56 chars truncated)\n", getLog("__test.log")); } TEST_F(LoggerTest, cleanCollapseMap_deleteEntries) { logger.collapseMap[std::make_pair("LoggerTest.cc", 1)] = Logger::SkipInfo({1, 200000000}, 0, "message1\n"); logger.collapseMap[std::make_pair("LoggerTest.cc", 2)] = Logger::SkipInfo({1, 400000000}, 0, "message2\n"); logger.collapseMap[std::make_pair("LoggerTest.cc", 3)] = Logger::SkipInfo({1, 600000000}, 0, "message3\n"); logger.cleanCollapseMap({1, 600000000}); EXPECT_EQ("", getLog("__test.log")); EXPECT_EQ(0U, logger.collapseMap.size()); EXPECT_EQ(1001, logger.nextCleanTime.tv_sec); EXPECT_EQ(600000000, logger.nextCleanTime.tv_nsec); } TEST_F(LoggerTest, cleanCollapseMap_print) { auto pair1 = std::make_pair("LoggerTest.cc", 1); auto pair2 = std::make_pair("LoggerTest.cc", 2); auto pair3 = std::make_pair("LoggerTest.cc", 3); logger.collapseMap[pair1] = Logger::SkipInfo({1, 200000000}, 0, "0000000001.000000001 WARNING[1]: message1\n"); logger.collapseMap[pair2] = Logger::SkipInfo({1, 400000000}, 8, "0000000001.000000002 WARNING[1]: message2\n"); logger.collapseMap[pair3] = Logger::SkipInfo({1, 600000000}, 0, "0000000001.000000003 WARNING[1]: message3\n"); logger.cleanCollapseMap({1, 500000000}); EXPECT_EQ("0000000001.500000000 WARNING[1]: " "(8 duplicates of this message were skipped) message2\n", getLog("__test.log")); EXPECT_EQ(2U, logger.collapseMap.size()); EXPECT_EQ(6, logger.collapseMap[pair2].nextPrintTime.tv_sec); EXPECT_EQ(500000000U, logger.collapseMap[pair2].nextPrintTime.tv_nsec); EXPECT_EQ(1U, logger.nextCleanTime.tv_sec); EXPECT_EQ(600000000U, logger.nextCleanTime.tv_nsec); } TEST_F(LoggerTest, addToBuffer) { logger.testingNoNotify = true; logger.nextToPrint = 15; logger.nextToInsert = logger.bufferSize - 20; logger.messageBuffer[logger.bufferSize - 5] = 'x'; // First append: new characters all fit at the end of the buffer EXPECT_TRUE(logger.addToBuffer("abcdefghijklmno", 15)); EXPECT_EQ(logger.bufferSize - 5, logger.nextToInsert); string check(logger.messageBuffer + logger.bufferSize - 20, 16); EXPECT_EQ("abcdefghijklmnox", check); // Second append: must wrap around. EXPECT_TRUE(logger.addToBuffer("0123456789ABCD", 14)); EXPECT_EQ(9, logger.nextToInsert); check.assign(logger.messageBuffer + logger.bufferSize - 5, 5); EXPECT_EQ("01234", check); check.assign(logger.messageBuffer, 9); EXPECT_EQ("56789ABCD", check); // Third append: not enough space. EXPECT_FALSE(logger.addToBuffer("EFGHIJ", 6)); EXPECT_EQ(9, logger.nextToInsert); } TEST_F(LoggerTest, printThreadMain_exit) { Tub<Logger> logger; TestLog::Enable _; logger.construct(NOTICE); TestLog::reset(); logger.destroy(); EXPECT_EQ("printThreadMain: print thread exiting", TestLog::get()); } TEST_F(LoggerTest, printThreadMain_wrapAround) { logger.nextToInsert = logger.nextToPrint = logger.bufferSize - 10; logger.addToBuffer("abcdefghijklmnop", 16); EXPECT_EQ("abcdefghijklmnop", getLog("__test.log")); EXPECT_EQ(0, logger.nextToPrint); EXPECT_EQ(0, logger.nextToInsert); } // The following test is normally disabled, since it generates output // on stderr. #if 0 TEST_F(LoggerTest, printThreadMain_error) { logger.fd = 99; logger.logMessage(true, RAMCLOUD_CURRENT_LOG_MODULE, ERROR, CodeLocation("file", 98, "func", "pretty"), "simple message"); usleep(10000); EXPECT_EQ(0, logger.nextToPrint); EXPECT_EQ(0, logger.nextToInsert); } #endif TEST_F(LoggerTest, LOG) { useSharedLogger(); LOG(DEBUG, "x"); EXPECT_EQ("", getLog("__test.log")); LOG(ERROR, "rofl: %d", 3); const char* pattern = "^0000000003.500000000 " "LoggerTest.cc:[[:digit:]]\\{1,4\\} in TestBody " "ERROR\\[1\\]: rofl: 3\n$"; EXPECT_TRUE(TestUtil::matchesPosixRegex(pattern, getLog("__test.log"))); } TEST_F(LoggerTest, DIE) { useSharedLogger(); try { DIE("rofl: %d", 3); } catch (RAMCloud::FatalError& e) { EXPECT_TRUE(TestUtil::contains(getLog("__test.log"), "rofl: 3")); EXPECT_EQ("rofl: 3", e.message); return; } EXPECT_STREQ("", "FatalError not thrown"); } TEST_F(LoggerTest, assertionError) { useSharedLogger(); string exceptionMessage("No exception"); try { logger.assertionError("assertion info", "file", 99, "function"); } catch (RAMCloud::FatalError& e) { exceptionMessage = e.message; } EXPECT_EQ("Assertion `assertion info' failed at file:99 in function", exceptionMessage); EXPECT_TRUE(TestUtil::contains(getLog("__test.log"), "Assertion `assertion info' failed at file:99 in function")); } } // namespace RAMCloud
[ "jliborio@live.com" ]
jliborio@live.com
f172d409aa54296025dd407ef9156fd349ebf4d4
625c43dfe5b3e65e013935847cc666e2c938b565
/2018C/hq9/hq9.cpp
533d0d0c51823dbe1252e138d5ce8f9c23fd84b6
[]
no_license
OliverHuang1220/My-first-program
be7b48c7276e77a40db355e63360c8d93139a9ca
9966d6da2445955bad64beecb68d9cf7b6bb28e4
refs/heads/main
2023-07-17T09:17:08.510378
2021-08-29T05:54:53
2021-08-29T05:54:53
400,961,932
1
0
null
null
null
null
GB18030
C++
false
false
626
cpp
// hq9.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include<stdio.h> #include<conio.h> #include<stdlib.h> int main(int argc, char* argv[]) { char str[100]; int Num=0; char ch; do {printf("请输入一个整数"); gets(str); int AFloatArray[Num]; AFloatArray[Num]=atof(str); Num++; printf("继续输入吗?[y/Y]\n"); ch=getch(); } while(ch=='y'||ch=='Y'); printf("下面%d个数,然后数后面打回车\n",Num); int index; float Sum=0.0; for(index=0;index<Num;index++) { Sum=Sum+AFloatArray[Num]; } printf("Sum=%f\n",Sum); return 0; }
[ "374198786@qq.com" ]
374198786@qq.com
afc632cfe32a360fb0a9bf5a93001cac85766375
5e6943ef0183cc59ab8392060472ccc561700c24
/src/brick/build_time.cc
42cf6458c4424f822a0c3752f53702fc6103cd62
[]
no_license
israel-Liu/brick
88b7ea62c79fc0fc250a60a482d81543c48ec795
9b4e4011df7c0bdede945d98bcd1e0a5ac535773
refs/heads/master
2022-04-20T10:00:47.049834
2020-04-24T03:32:07
2020-04-24T03:32:07
96,489,912
0
0
null
null
null
null
UTF-8
C++
false
false
740
cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "brick/build_time.h" // Imports the generated build date, i.e. BUILD_DATE. #include "brick/generated_build_date.h" #include "brick/logging.h" #include "brick/time/time.h" namespace base { Time GetBuildTime() { Time integral_build_time; // BUILD_DATE is exactly "Mmm DD YYYY HH:MM:SS". // See //build/write_build_date_header.py. "HH:MM:SS" is normally expected to // be "05:00:00" but is not enforced here. bool result = Time::FromUTCString(BUILD_DATE, &integral_build_time); DCHECK(result); return integral_build_time; } } // namespace base
[ "israel.liu.theForger@gmail.com" ]
israel.liu.theForger@gmail.com
53f78a96ef0cfb1cb17f9f716d910016c56bf00d
2d9fe07b3c4f3aaee3bcd08b6ec2c7f11b566bff
/magicPayOrderServer/include/magicServerDb.h
629fc693322e35cbbe075b72319937f372d98ada
[]
no_license
wantao/myMagicServerLocal
d668a7b063ebc19ee4d2f35ad4128680b804a3ae
caf8e58894b5af26e8c0a1fbb26edc64b7248141
refs/heads/master
2016-09-05T12:33:04.116861
2014-02-21T06:21:21
2014-02-21T06:21:21
null
0
0
null
null
null
null
GB18030
C++
false
false
702
h
#ifndef MAGICSERVERDB_H #define MAGICSERVERDB_H #include <iostream> #include "common.h" #include "MysqlQuery.h" #include "MysqlDB.h" #include "../include/MagicCard.pb.h" using namespace std; class cMagicServerDb:public MysqlDB { public: cMagicServerDb(); ~cMagicServerDb(); bool Init(); //从数据库实例化 bool DbReadInit(); void unInit(); //数据库连接保活 void mysqlKeepAlive(int u_Type); //防止主从同步延迟造成的从从库取不到数据的情况 MysqlQuery master_slave_exQuery(const string& strSql); protected: private: //数据库连接开关 bool m_bConnect; }; extern cMagicServerDb g_cMagicServerDb; extern cMagicServerDb g_cMagicServerDbRead; #endif
[ "461969382@qq.com" ]
461969382@qq.com
a9b239d3477a16aaa34cd20f9b04ec3fa1e72a97
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/ModelsC/AlcoaSpMdl/AlcoaSpMdl.cpp
f1d6d9edcb48f2bf5b32f00f6d9f547d07c8daf6
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,994
cpp
// AlcoaSpMdl.cpp : Defines the initialization routines for the DLL. // #include "stdafx.h" #include <afxdllx.h> #define __ALCOASPMDL_CPP #include "sc_defs.h" #include "scdver.h" #include "AlcoaSpMdl.h" #include "Models.h" #include "sfe_srvr.h" //=========================================================================== // // Visual C++ Stuff // //=========================================================================== #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif static AFX_EXTENSION_MODULE AlcoaSpMdlDLL = { NULL, NULL }; extern "C" int APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { if (dwReason == DLL_PROCESS_ATTACH) { TRACE1("AlcoaSpMdl.DLL Initializing %08x!\n", hInstance); // Extension DLL one-time initialization if (!AfxInitExtensionModule(AlcoaSpMdlDLL, hInstance)) return 0; // Insert this DLL into the resource chain new CDynLinkLibrary(AlcoaSpMdlDLL); if (!MakeVersionOK("AlcoaSpMdl.DLL", _MAKENAME, SCD_VERINFO_V0, SCD_VERINFO_V1, SCD_VERINFO_V2, SCD_VERINFO_V3)) return 0; // ForceLoadModelLibrary(); } else if (dwReason == DLL_PROCESS_DETACH) { TRACE0("AlcoaSpMdl.DLL Terminating!\n"); AfxTermExtensionModule(AlcoaSpMdlDLL); } return 1; // ok } //--------------------------------------------------------------------------- #define DLLEXPORT __declspec( dllexport ) //--------------------------------------------------------------------------- extern "C" DLLEXPORT BOOL FilterDllMsg(LPMSG lpMsg) { return AfxGetApp()->PreTranslateMessage(lpMsg); } //--------------------------------------------------------------------------- extern "C" DLLEXPORT void ProcessDllIdle() { // flush it all at once long lCount = 0; while (AfxGetApp()->OnIdle(lCount)) lCount++; } //--------------------------------------------------------------------------- extern "C" DLLEXPORT BOOL IsFlowLibDLL() { return TRUE; } //--------------------------------------------------------------------------- extern "C" DLLEXPORT BOOL GetDLLInfo(MDLLInfo* pDLLInfo) { pDLLInfo->iPriority = 5; pDLLInfo->sName = "AlcoaSpMdl"; pDLLInfo->AddDependentDLL("MdlBase"); return TRUE; } //--------------------------------------------------------------------------- extern "C" DLLEXPORT CMdlCfgBase* GetCfgPropPg(int iPage, CMdlCfgSheet * pSheet) { return NULL; }; //=========================================================================== // // // //=========================================================================== void ForceLoad_AlcoaSpMdl() { // Dummy Function to allow other libraries to force load this one } //=========================================================================== // // // //===========================================================================
[ "paul.hannah@syscad.net" ]
paul.hannah@syscad.net
1891b73c0334b3164b3c55e24e0971bdae66296b
b8906afecca06f48f2cd289a9997f670b26c4721
/platform/shared/qt/rhodes/oldVersion/qtscroller.h
c00ffa64991e9262d48a266e9d11e986f301ceb4
[ "MIT" ]
permissive
rhomobile/rhodes
51bd88921c51bd618948f9a557de17fc297e7cc2
fc8409c9c281684a49d7ff6805ddc565de09a6d5
refs/heads/master
2023-09-01T17:45:36.149868
2023-08-31T20:56:06
2023-08-31T20:56:06
54,084
504
155
MIT
2023-09-12T00:14:29
2008-09-18T21:55:16
C
UTF-8
C++
false
false
4,071
h
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QTSCROLLER_H #define QTSCROLLER_H #include <QtCore/QObject> #include <QtCore/QPointF> #include "qtscrollerproperties.h" class QWidget; class QtScrollerPrivate; class QtScrollerProperties; class QtFlickGestureRecognizer; class QtScroller : public QObject { Q_OBJECT Q_PROPERTY(State state READ state NOTIFY stateChanged) Q_PROPERTY(QtScrollerProperties scrollerProperties READ scrollerProperties WRITE setScrollerProperties NOTIFY scrollerPropertiesChanged) Q_ENUMS(State) public: enum State { Inactive, Pressed, Dragging, Scrolling }; enum ScrollerGestureType { TouchGesture, LeftMouseButtonGesture, RightMouseButtonGesture, MiddleMouseButtonGesture }; enum Input { InputPress = 1, InputMove, InputRelease }; static bool hasScroller(QObject *target); static QtScroller *scroller(QObject *target); static const QtScroller *scroller(const QObject *target); static Qt::GestureType grabGesture(QObject *target, ScrollerGestureType gestureType = TouchGesture); static Qt::GestureType grabbedGesture(QObject *target); static void ungrabGesture(QObject *target); static QList<QtScroller *> activeScrollers(); QObject *target() const; State state() const; bool handleInput(Input input, const QPointF &position, qint64 timestamp = 0); void stop(); QPointF velocity() const; QPointF finalPosition() const; QPointF pixelPerMeter() const; QtScrollerProperties scrollerProperties() const; void setSnapPositionsX( const QList<qreal> &positions ); void setSnapPositionsX( qreal first, qreal interval ); void setSnapPositionsY( const QList<qreal> &positions ); void setSnapPositionsY( qreal first, qreal interval ); public Q_SLOTS: void setScrollerProperties(const QtScrollerProperties &prop); void scrollTo(const QPointF &pos); void scrollTo(const QPointF &pos, int scrollTime); void ensureVisible(const QRectF &rect, qreal xmargin, qreal ymargin); void ensureVisible(const QRectF &rect, qreal xmargin, qreal ymargin, int scrollTime); void resendPrepareEvent(); Q_SIGNALS: void stateChanged(QtScroller::State newstate); void scrollerPropertiesChanged(const QtScrollerProperties &); private: QtScrollerPrivate* d_ptr; QtScroller(QObject *target); virtual ~QtScroller(); Q_DISABLE_COPY(QtScroller) Q_DECLARE_PRIVATE(QtScroller) friend class QtFlickGestureRecognizer; }; #endif // QTSCROLLER_H
[ "krybas@tau-technologies.com" ]
krybas@tau-technologies.com
f777ac8c9da2efe6125f64f46b8b6626dfb0420f
18dc828ecac141107d32a41e3063b2c8f4880667
/tom_1/chapter_16/22/tvector.h
b1c5c5eeb95dce1517af8c9e14ca35c0577eba22
[]
no_license
novikov-ilia-softdev/thinking_cpp
4ffde847627b6cfdabcead8d833c24408314792d
bfa0348eaa89b2c24639a3f76d385dbc834b913d
refs/heads/master
2021-09-19T05:59:06.310055
2018-07-24T06:20:21
2018-07-24T06:20:21
70,487,830
0
0
null
null
null
null
UTF-8
C++
false
false
427
h
#ifndef TVECTOR_H #define TVECTOR_H #include <vector> typedef std::vector<void*> vectorVoid; template<class T> class TVector: public vectorVoid{ public: void push_back( T* strPtr) { std::cout << "TVector::push_back" << std::endl; vectorVoid::push_back( strPtr); } T* operator[]( int index) { std::cout << "TVector::operator[]" << std::endl; return (T*)vectorVoid::operator[]( index); } }; #endif //TVECTOR_H
[ "smartnlg.ilia.novikov@gmail.com" ]
smartnlg.ilia.novikov@gmail.com
fc48e838b12c94511fe986f5a23b54dcbce8d517
3fe692c3ebf0b16c0a6ae9d8633799abc93bd3bb
/Contests/JZOJ-B-Jul-13/A.cpp
312a7dff805f34e9b447c1f5e5dc4cd7c0bf9e37
[]
no_license
kaloronahuang/KaloronaCodebase
f9d297461446e752bdab09ede36584aacd0b3aeb
4fa071d720e06100f9b577e87a435765ea89f838
refs/heads/master
2023-06-01T04:24:11.403154
2023-05-23T00:38:07
2023-05-23T00:38:07
155,797,801
14
1
null
null
null
null
UTF-8
C++
false
false
1,221
cpp
// A.cpp #include <bits/stdc++.h> using namespace std; string rev, revk; int T, k; int main() { freopen("game.in", "r", stdin); freopen("game.out", "w", stdout); scanf("%d", &T); while (T--) { rev = ""; cin >> k >> rev; stringstream ss; ss << k; revk = ss.str(), reverse(revk.begin(), revk.end()); // starts to compare; if (revk.length() > rev.length()) { puts("Yes"); continue; } else if (revk.length() == rev.length()) { bool flag = true; for (int i = revk.length() - 1; i >= 0; i--) if (revk[i] > rev[i]) break; else if (revk[i] < rev[i]) { flag = false; break; } if (flag) { puts("Yes"); continue; } } // general compare; int d = 0; for (int i = 0; i < rev.length(); i++) d = (d * 10 + rev[i] - '0') % (k + 1); if (d == 0) printf("No\n"); else printf("Yes\n"); } return 0; }
[ "kaloronahuang@gmail.com" ]
kaloronahuang@gmail.com
f2ced78bbe6b25dbe9d3f61bc72f3231855b90b4
c71af56951d1c661a5819db72da1caccd9130df2
/cpp/problems/dp/dp12.cpp
d276ecc386767afbecc493877f84ea38b8f44191
[]
no_license
adrianpoplesanu/personal-work
2940a0dc4e4e27e0cc467875bae3fdea27dd0d31
adc289ecb72c1c6f98582f3ea9ad4bf2e8e08d29
refs/heads/master
2023-08-23T06:56:49.363519
2023-08-21T17:20:51
2023-08-21T17:20:51
109,451,981
0
1
null
2022-10-07T04:53:24
2017-11-03T23:36:21
Python
UTF-8
C++
false
false
1,460
cpp
// http://info.mcip.ro/?cap=Programare%20dinamica ; ex #406 #include <fstream> #include <iostream> #include <ctime> using namespace std; int main(int argc, char *argv[]) { clock_t start = clock(); int n; string names[100], names2[100]; int a[100]; int dp[100]; int drum[100]; ifstream in("dp12.in"); ofstream out("dp12.out"); in >> n; for (int i = 0; i < n; i++) in >> names[i]; for (int i = 0; i < n; i++) in >> names2[i]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (names[i] == names2[j]) a[j] = i; } } for (int i = 0; i < n; i++) cout << a[i] << " "; cout << endl; dp[0] = 1; drum[0] = -1; for (int i = 1; i < n; i++) { dp[i] = 1; drum[i] = -1; for (int j = 0; j < i; j++) { if (a[j] < a[i]) { if (dp[j] + 1 > dp[i]) { dp[i] = dp[j] + 1; drum[i] = j; } } } } /*int poz = n - 1, val = dp[n - 1]; cout << max << endl; while (poz > 0) { while(dp[poz] == val) poz--; }*/ for (int i = 0; i < n; i++) cout << dp[i] << " "; cout << endl; for (int i = 0; i < n; i++) cout << drum[i] << " "; cout << endl; in.close(); out.close(); clock_t end = clock(); cout << "ran for " << double(end - start) / CLOCKS_PER_SEC << "secs" << endl; return 0; }
[ "adrian.poplesanu@yahoo.com" ]
adrian.poplesanu@yahoo.com
5036316271307220dcbd8dcfbd0e8d9a6410995d
6ced41da926682548df646099662e79d7a6022c5
/aws-cpp-sdk-forecast/include/aws/forecast/model/ErrorMetric.h
de9df30f07e1cf82a5bbdfaa963307c2134af766
[ "Apache-2.0", "MIT", "JSON" ]
permissive
irods/aws-sdk-cpp
139104843de529f615defa4f6b8e20bc95a6be05
2c7fb1a048c96713a28b730e1f48096bd231e932
refs/heads/main
2023-07-25T12:12:04.363757
2022-08-26T15:33:31
2022-08-26T15:33:31
141,315,346
0
1
Apache-2.0
2022-08-26T17:45:09
2018-07-17T16:24:06
C++
UTF-8
C++
false
false
5,225
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/forecast/ForecastService_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace ForecastService { namespace Model { /** * <p> Provides detailed error metrics to evaluate the performance of a predictor. * This object is part of the <a>Metrics</a> object. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/forecast-2018-06-26/ErrorMetric">AWS * API Reference</a></p> */ class AWS_FORECASTSERVICE_API ErrorMetric { public: ErrorMetric(); ErrorMetric(Aws::Utils::Json::JsonView jsonValue); ErrorMetric& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p> The Forecast type used to compute WAPE, MAPE, MASE, and RMSE. </p> */ inline const Aws::String& GetForecastType() const{ return m_forecastType; } /** * <p> The Forecast type used to compute WAPE, MAPE, MASE, and RMSE. </p> */ inline bool ForecastTypeHasBeenSet() const { return m_forecastTypeHasBeenSet; } /** * <p> The Forecast type used to compute WAPE, MAPE, MASE, and RMSE. </p> */ inline void SetForecastType(const Aws::String& value) { m_forecastTypeHasBeenSet = true; m_forecastType = value; } /** * <p> The Forecast type used to compute WAPE, MAPE, MASE, and RMSE. </p> */ inline void SetForecastType(Aws::String&& value) { m_forecastTypeHasBeenSet = true; m_forecastType = std::move(value); } /** * <p> The Forecast type used to compute WAPE, MAPE, MASE, and RMSE. </p> */ inline void SetForecastType(const char* value) { m_forecastTypeHasBeenSet = true; m_forecastType.assign(value); } /** * <p> The Forecast type used to compute WAPE, MAPE, MASE, and RMSE. </p> */ inline ErrorMetric& WithForecastType(const Aws::String& value) { SetForecastType(value); return *this;} /** * <p> The Forecast type used to compute WAPE, MAPE, MASE, and RMSE. </p> */ inline ErrorMetric& WithForecastType(Aws::String&& value) { SetForecastType(std::move(value)); return *this;} /** * <p> The Forecast type used to compute WAPE, MAPE, MASE, and RMSE. </p> */ inline ErrorMetric& WithForecastType(const char* value) { SetForecastType(value); return *this;} /** * <p> The weighted absolute percentage error (WAPE). </p> */ inline double GetWAPE() const{ return m_wAPE; } /** * <p> The weighted absolute percentage error (WAPE). </p> */ inline bool WAPEHasBeenSet() const { return m_wAPEHasBeenSet; } /** * <p> The weighted absolute percentage error (WAPE). </p> */ inline void SetWAPE(double value) { m_wAPEHasBeenSet = true; m_wAPE = value; } /** * <p> The weighted absolute percentage error (WAPE). </p> */ inline ErrorMetric& WithWAPE(double value) { SetWAPE(value); return *this;} /** * <p> The root-mean-square error (RMSE). </p> */ inline double GetRMSE() const{ return m_rMSE; } /** * <p> The root-mean-square error (RMSE). </p> */ inline bool RMSEHasBeenSet() const { return m_rMSEHasBeenSet; } /** * <p> The root-mean-square error (RMSE). </p> */ inline void SetRMSE(double value) { m_rMSEHasBeenSet = true; m_rMSE = value; } /** * <p> The root-mean-square error (RMSE). </p> */ inline ErrorMetric& WithRMSE(double value) { SetRMSE(value); return *this;} /** * <p>The Mean Absolute Scaled Error (MASE)</p> */ inline double GetMASE() const{ return m_mASE; } /** * <p>The Mean Absolute Scaled Error (MASE)</p> */ inline bool MASEHasBeenSet() const { return m_mASEHasBeenSet; } /** * <p>The Mean Absolute Scaled Error (MASE)</p> */ inline void SetMASE(double value) { m_mASEHasBeenSet = true; m_mASE = value; } /** * <p>The Mean Absolute Scaled Error (MASE)</p> */ inline ErrorMetric& WithMASE(double value) { SetMASE(value); return *this;} /** * <p>The Mean Absolute Percentage Error (MAPE)</p> */ inline double GetMAPE() const{ return m_mAPE; } /** * <p>The Mean Absolute Percentage Error (MAPE)</p> */ inline bool MAPEHasBeenSet() const { return m_mAPEHasBeenSet; } /** * <p>The Mean Absolute Percentage Error (MAPE)</p> */ inline void SetMAPE(double value) { m_mAPEHasBeenSet = true; m_mAPE = value; } /** * <p>The Mean Absolute Percentage Error (MAPE)</p> */ inline ErrorMetric& WithMAPE(double value) { SetMAPE(value); return *this;} private: Aws::String m_forecastType; bool m_forecastTypeHasBeenSet; double m_wAPE; bool m_wAPEHasBeenSet; double m_rMSE; bool m_rMSEHasBeenSet; double m_mASE; bool m_mASEHasBeenSet; double m_mAPE; bool m_mAPEHasBeenSet; }; } // namespace Model } // namespace ForecastService } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
352ff3bd194ce796a28ad7605ac2facf1d587965
443d23e6e74d07902f817cf08819a0d241815a2e
/Activity.h
8cd4cf7ffe5ef2446dbce5e76476ae818c32618d
[]
no_license
Catalinul/Faculty-Model
03c7a40b5c4aab53d137542eddb1f5ec176e7eac
a0039148a7e17bc165b548f2d1af74a51f68b57f
refs/heads/master
2020-04-09T03:01:17.052953
2019-02-18T10:43:09
2019-02-18T10:43:09
159,965,467
0
0
null
null
null
null
UTF-8
C++
false
false
551
h
#ifndef ACTIVITY_H_INCLUDED #define ACTIVITY_H_INCLUDED #include <string> #include "Room.h" #include "Person.h" class Activity { public: Activity(){}; Activity(Room*, Person*, std::string); Room* getRoom() const; Person* getOwner() const; std::string getDescription() const; friend std::istream& operator >> (std::istream &read, Activity& obj); friend std::ostream& operator << (std::ostream &write, const Activity& obj); private: Room* mLocation; Person* mOwner; std::string mDescription; }; #endif // ACTIVITY_H_INCLUDED
[ "pirvu.catalin15@yahoo.com" ]
pirvu.catalin15@yahoo.com
4f866b59257a0d7c099195887eb3bbd4d30bfe42
067ec1ed80b38e4da2da728784fb6a14cc808774
/test/Import/for-stmt/test.cpp
a926a9f489b3594a217078fbe7fb025ea213278c
[ "NCSA" ]
permissive
Nathaniel100/clang
12e40919562e9e3f14fac4cf4a1ad617a1942660
21522df485be99f247a18c13827e525bda74e362
refs/heads/master
2023-04-07T13:43:02.020211
2018-08-19T22:23:42
2018-08-19T22:23:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
795
cpp
// RUN: clang-import-test -dump-ast -import %S/Inputs/F.cpp -expression %s | FileCheck %s // CHECK: ForStmt // CHECK-NEXT: <<NULL>> // CHECK-NEXT: <<NULL>> // CHECK-NEXT: <<NULL>> // CHECK-NEXT: <<NULL>> // CHECK-NEXT: NullStmt // CHECK: ForStmt // CHECK-NEXT: DeclStmt // CHECK-NEXT: VarDecl // CHECK-NEXT: IntegerLiteral // CHECK-NEXT: <<NULL>> // CHECK-NEXT: <<NULL>> // CHECK-NEXT: <<NULL>> // CHECK-NEXT: ContinueStmt // CHECK: ForStmt // CHECK-NEXT: DeclStmt // CHECK-NEXT: VarDecl // CHECK-NEXT: IntegerLiteral // CHECK-NEXT: <<NULL>> // CHECK-NEXT: BinaryOperator // CHECK-NEXT: ImplicitCastExpr // CHECK-NEXT: DeclRefExpr // CHECK-NEXT: IntegerLiteral // CHECK-NEXT: UnaryOperator // CHECK-SAME: '++' // CHECK-NEXT: DeclRefExpr // CHECK-NEXT: CompoundStmt void expr() { f(); }
[ "teemperor@gmail.com" ]
teemperor@gmail.com
2ca0987ae9eb26f2c3e34cbf77471685f5f8e05d
fb381224be13ed84e8e63bd7bf013dd10d58d924
/Code/Engine/Texture/DirectXTex/DirectXTexNormalMaps.cpp
58089fc882a9b6b90c891203b44086343bc8c13f
[ "MIT" ]
permissive
bethau/ezEngine
1b768f95801dd2367dc30675f8febb5cbb625819
059684c8d9ed7e33f8e68f218ff42a7decf668ee
refs/heads/master
2022-08-22T06:48:55.549276
2020-02-11T23:36:43
2020-02-11T23:36:43
247,667,175
0
0
MIT
2020-03-16T09:57:54
2020-03-16T09:57:53
null
UTF-8
C++
false
false
12,512
cpp
#include <TexturePCH.h> #if EZ_ENABLED(EZ_PLATFORM_WINDOWS_DESKTOP) //------------------------------------------------------------------------------------- // DirectXTexNormalMaps.cpp // // DirectX Texture Library - Normal map operations // // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 //------------------------------------------------------------------------------------- #include "DirectXTexp.h" using namespace DirectX; namespace { #pragma prefast(suppress : 25000, "FXMVECTOR is 16 bytes") inline float EvaluateColor(_In_ FXMVECTOR val, _In_ DWORD flags) { XMFLOAT4A f; static XMVECTORF32 lScale = { { { 0.2125f, 0.7154f, 0.0721f, 1.f } } }; static_assert(CNMAP_CHANNEL_RED == 0x1, "CNMAP_CHANNEL_ flag values don't match mask"); switch (flags & 0xf) { case 0: case CNMAP_CHANNEL_RED: return XMVectorGetX(val); case CNMAP_CHANNEL_GREEN: return XMVectorGetY(val); case CNMAP_CHANNEL_BLUE: return XMVectorGetZ(val); case CNMAP_CHANNEL_ALPHA: return XMVectorGetW(val); case CNMAP_CHANNEL_LUMINANCE: { XMVECTOR v = XMVectorMultiply(val, lScale); XMStoreFloat4A(&f, v); return f.x + f.y + f.z; } default: assert(false); return 0.f; } } void EvaluateRow( _In_reads_(width) const XMVECTOR* pSource, _Out_writes_(width + 2) float* pDest, size_t width, DWORD flags) { assert(pSource && pDest); assert(width > 0); for (size_t x = 0; x < width; ++x) { pDest[x + 1] = EvaluateColor(pSource[x], flags); } if (flags & CNMAP_MIRROR_U) { // Mirror in U pDest[0] = EvaluateColor(pSource[0], flags); pDest[width + 1] = EvaluateColor(pSource[width - 1], flags); } else { // Wrap in U pDest[0] = EvaluateColor(pSource[width - 1], flags); pDest[width + 1] = EvaluateColor(pSource[0], flags); } } HRESULT ComputeNMap(_In_ const Image& srcImage, _In_ DWORD flags, _In_ float amplitude, _In_ DXGI_FORMAT format, _In_ const Image& normalMap) { if (!srcImage.pixels || !normalMap.pixels) return E_INVALIDARG; const DWORD convFlags = _GetConvertFlags(format); if (!convFlags) return E_FAIL; if (!(convFlags & (CONVF_UNORM | CONVF_SNORM | CONVF_FLOAT))) return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); const size_t width = srcImage.width; const size_t height = srcImage.height; if (width != normalMap.width || height != normalMap.height) return E_FAIL; // Allocate temporary space (4 scanlines and 3 evaluated rows) ScopedAlignedArrayXMVECTOR scanline(static_cast<XMVECTOR*>(_aligned_malloc((sizeof(XMVECTOR)*width * 4), 16))); if (!scanline) return E_OUTOFMEMORY; ScopedAlignedArrayFloat buffer(static_cast<float*>(_aligned_malloc(((sizeof(float) * (width + 2)) * 3), 16))); if (!buffer) return E_OUTOFMEMORY; uint8_t* pDest = normalMap.pixels; if (!pDest) return E_POINTER; XMVECTOR* row0 = scanline.get(); XMVECTOR* row1 = row0 + width; XMVECTOR* row2 = row1 + width; XMVECTOR* target = row2 + width; float* val0 = buffer.get(); float* val1 = val0 + width + 2; float* val2 = val1 + width + 2; const size_t rowPitch = srcImage.rowPitch; const uint8_t* pSrc = srcImage.pixels; // Read first scanline row into 'row1' if (!_LoadScanline(row1, width, pSrc, rowPitch, srcImage.format)) return E_FAIL; // Setup 'row0' if (flags & CNMAP_MIRROR_V) { // Mirror first row memcpy_s(row0, rowPitch, row1, rowPitch); } else { // Read last row (Wrap V) if (!_LoadScanline(row0, width, pSrc + (rowPitch * (height - 1)), rowPitch, srcImage.format)) return E_FAIL; } // Evaluate the initial rows EvaluateRow(row0, val0, width, flags); EvaluateRow(row1, val1, width, flags); pSrc += rowPitch; for (size_t y = 0; y < height; ++y) { // Load next scanline of source image if (y < (height - 1)) { if (!_LoadScanline(row2, width, pSrc, rowPitch, srcImage.format)) return E_FAIL; } else { if (flags & CNMAP_MIRROR_V) { // Use last row of source image if (!_LoadScanline(row2, width, srcImage.pixels + (rowPitch * (height - 1)), rowPitch, srcImage.format)) return E_FAIL; } else { // Use first row of source image (Wrap V) if (!_LoadScanline(row2, width, srcImage.pixels, rowPitch, srcImage.format)) return E_FAIL; } } // Evaluate row EvaluateRow(row2, val2, width, flags); // Generate target scanline XMVECTOR *dptr = target; for (size_t x = 0; x < width; ++x) { // Compute normal via central differencing float totDelta = (val0[x] - val0[x + 2]) + (val1[x] - val1[x + 2]) + (val2[x] - val2[x + 2]); float deltaZX = totDelta * amplitude / 6.f; totDelta = (val0[x] - val2[x]) + (val0[x + 1] - val2[x + 1]) + (val0[x + 2] - val2[x + 2]); float deltaZY = totDelta * amplitude / 6.f; XMVECTOR vx = XMVectorSetZ(g_XMNegIdentityR0, deltaZX); // (-1.0f, 0.0f, deltaZX) XMVECTOR vy = XMVectorSetZ(g_XMNegIdentityR1, deltaZY); // (0.0f, -1.0f, deltaZY) XMVECTOR normal = XMVector3Normalize(XMVector3Cross(vx, vy)); // Compute alpha (1.0 or an occlusion term) float alpha = 1.f; if (flags & CNMAP_COMPUTE_OCCLUSION) { float delta = 0.f; float c = val1[x + 1]; float t = val0[x] - c; if (t > 0.f) delta += t; t = val0[x + 1] - c; if (t > 0.f) delta += t; t = val0[x + 2] - c; if (t > 0.f) delta += t; t = val1[x] - c; if (t > 0.f) delta += t; // Skip current pixel t = val1[x + 2] - c; if (t > 0.f) delta += t; t = val2[x] - c; if (t > 0.f) delta += t; t = val2[x + 1] - c; if (t > 0.f) delta += t; t = val2[x + 2] - c; if (t > 0.f) delta += t; // Average delta (divide by 8, scale by amplitude factor) delta *= 0.125f * amplitude; if (delta > 0.f) { // If < 0, then no occlusion float r = sqrtf(1.f + delta*delta); alpha = (r - delta) / r; } } // Encode based on target format if (convFlags & CONVF_UNORM) { // 0.5f*normal + 0.5f -or- invert sign case: -0.5f*normal + 0.5f XMVECTOR n1 = XMVectorMultiplyAdd((flags & CNMAP_INVERT_SIGN) ? g_XMNegativeOneHalf : g_XMOneHalf, normal, g_XMOneHalf); *dptr++ = XMVectorSetW(n1, alpha); } else if (flags & CNMAP_INVERT_SIGN) { *dptr++ = XMVectorSetW(XMVectorNegate(normal), alpha); } else { *dptr++ = XMVectorSetW(normal, alpha); } } if (!_StoreScanline(pDest, normalMap.rowPitch, format, target, width)) return E_FAIL; // Cycle buffers float* temp = val0; val0 = val1; val1 = val2; val2 = temp; pSrc += rowPitch; pDest += normalMap.rowPitch; } return S_OK; } } //===================================================================================== // Entry points //===================================================================================== //------------------------------------------------------------------------------------- // Generates a normal map from a height-map //------------------------------------------------------------------------------------- _Use_decl_annotations_ HRESULT DirectX::ComputeNormalMap( const Image& srcImage, DWORD flags, float amplitude, DXGI_FORMAT format, ScratchImage& normalMap) { if (!srcImage.pixels || !IsValid(format)) return E_INVALIDARG; static_assert(CNMAP_CHANNEL_RED == 0x1, "CNMAP_CHANNEL_ flag values don't match mask"); switch (flags & 0xf) { case 0: case CNMAP_CHANNEL_RED: case CNMAP_CHANNEL_GREEN: case CNMAP_CHANNEL_BLUE: case CNMAP_CHANNEL_ALPHA: case CNMAP_CHANNEL_LUMINANCE: break; default: return E_INVALIDARG; } if (IsCompressed(format) || IsCompressed(srcImage.format) || IsTypeless(format) || IsTypeless(srcImage.format) || IsPlanar(format) || IsPlanar(srcImage.format) || IsPalettized(format) || IsPalettized(srcImage.format)) return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); // Setup target image normalMap.Release(); HRESULT hr = normalMap.Initialize2D(format, srcImage.width, srcImage.height, 1, 1); if (FAILED(hr)) return hr; const Image *img = normalMap.GetImage(0, 0, 0); if (!img) { normalMap.Release(); return E_POINTER; } hr = ComputeNMap(srcImage, flags, amplitude, format, *img); if (FAILED(hr)) { normalMap.Release(); return hr; } return S_OK; } _Use_decl_annotations_ HRESULT DirectX::ComputeNormalMap( const Image* srcImages, size_t nimages, const TexMetadata& metadata, DWORD flags, float amplitude, DXGI_FORMAT format, ScratchImage& normalMaps) { if (!srcImages || !nimages || !IsValid(format)) return E_INVALIDARG; if (IsCompressed(format) || IsCompressed(metadata.format) || IsTypeless(format) || IsTypeless(metadata.format) || IsPlanar(format) || IsPlanar(metadata.format) || IsPalettized(format) || IsPalettized(metadata.format)) return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); static_assert(CNMAP_CHANNEL_RED == 0x1, "CNMAP_CHANNEL_ flag values don't match mask"); switch (flags & 0xf) { case 0: case CNMAP_CHANNEL_RED: case CNMAP_CHANNEL_GREEN: case CNMAP_CHANNEL_BLUE: case CNMAP_CHANNEL_ALPHA: case CNMAP_CHANNEL_LUMINANCE: break; default: return E_INVALIDARG; } normalMaps.Release(); TexMetadata mdata2 = metadata; mdata2.format = format; HRESULT hr = normalMaps.Initialize(mdata2); if (FAILED(hr)) return hr; if (nimages != normalMaps.GetImageCount()) { normalMaps.Release(); return E_FAIL; } const Image* dest = normalMaps.GetImages(); if (!dest) { normalMaps.Release(); return E_POINTER; } for (size_t index = 0; index < nimages; ++index) { assert(dest[index].format == format); const Image& src = srcImages[index]; if (IsCompressed(src.format) || IsTypeless(src.format)) { normalMaps.Release(); return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } if (src.width != dest[index].width || src.height != dest[index].height) { normalMaps.Release(); return E_FAIL; } hr = ComputeNMap(src, flags, amplitude, format, dest[index]); if (FAILED(hr)) { normalMaps.Release(); return hr; } } return S_OK; } #endif EZ_STATICLINK_FILE(Texture, Texture_DirectXTex_DirectXTexNormalMaps);
[ "jan@krassnigg.de" ]
jan@krassnigg.de
0e57c236a027b9c6d16bae2c0b6b6300d18e3863
3423eae27a6120181b8be2f13ec3964a79862582
/code/05_DP/概率DP/poj 2096 概率DP入门题(期望).cpp
b6d37659ebb0a8a285d25b52a842b736ecbe11b6
[]
no_license
mazicwong/ACM_code
610b3e8a3b42227dca81bba12c3885080d7dad9e
b4e774e8fb2087c89c607688600318a7ee6d4571
refs/heads/master
2023-04-03T11:04:40.590242
2021-04-09T10:35:23
2021-04-09T10:35:23
82,206,980
51
4
null
null
null
null
GB18030
C++
false
false
1,656
cpp
/* http://www.cnblogs.com/kuangbin/archive/2012/10/02/2710606.html dp求期望 逆着递推求解 题意:n种bug,s个子系统。每天随机找一个bug,种类随机,来自系统随机。 问找齐n种bug,且每个子系统至少有一个bug的期望天数。 dp[i][j]表示已找到i种bug,且j个系统有bug,达到目标状态的天数的期望。 它可以由四个状态推到: ① dp[i][j],发现一个bug属于已经有的i个分类和j个系统。概率为(i/n)*(j/s); ② dp[i][j+1],发现一个bug属于已有的分类,不属于已有的系统.概率为 (i/n)*(s-j)/s; ③ dp[i+1][j],发现一个bug属于已有的系统,不属于已有的分类,概率为 (n-i)/n*(j/s); ④ dp[i+1][j+1],发现一个bug不属于已有的系统,不属于已有的分类,概率为 (n-i)/n*(s-j)/s; 整理便得到转移方程 划重点!! 由于是求期望,所以要逆推,dp[n][s]=0, ans=dp[0][0] */ #include <iostream> #include <cstring> #include <string> #include <cstdio> using namespace std; const int maxn = 1010; double dp[maxn][maxn]; int main() { int n, s; while (scanf("%d%d", &n, &s) != EOF) { dp[n][s] = 0; for (int i = n; i >= 0; i--) { for (int j = s; j >= 0; j--) { if (i == n&&j == s) continue; double p2 = (double(s - j)*i) / n / s; double p3 = (double(n - i)*j) / n / s; double p4 = (double(n - i)*(s - j)) / n / s; double p1 = 1.0 - (double(i*j)) / n / s; dp[i][j] = p2*dp[i][j + 1] + p3*dp[i + 1][j] + p4*dp[i + 1][j + 1] + 1;//离散型,概率乘以对应值再求和 dp[i][j] /= p1; } } printf("%.4lf\n", dp[0][0]); } return 0; }
[ "mazicwong@gmail.com" ]
mazicwong@gmail.com
de2168faf24c9d23b6283ece5646f77525041a5c
570150546b2c2ba928074c362cb0211dfe92b215
/.vs/OOPS/tut04.cpp
7f2d9a2cfbea45d87bf303f15aeb8f3be41786cf
[]
no_license
gutaussehend-Harshal/CPP-and-DSA-practice-questions
391782ce20a3c1b9ab69d651482518694fabff31
0d6c4500ecad6295683c9c2753482e74131b443c
refs/heads/main
2023-07-18T05:48:24.158391
2021-09-05T04:36:43
2021-09-05T04:36:43
403,214,869
0
0
null
null
null
null
UTF-8
C++
false
false
1,790
cpp
#include <bits/stdc++.h> using namespace std; // What is inheritance --> class YouTubeChannel { private: string Name; int SubscribersCount; list<string> PublishedVideoTitles; protected: string OwnerName; public: YouTubeChannel(string name, string ownerName) { Name = name; OwnerName = ownerName; SubscribersCount = 0; } void GetInfo() { cout << "Name: " << Name << endl; cout << "OwnerName: " << OwnerName << endl; cout << "SubscribersCount: " << SubscribersCount << endl; cout << "Videos: " << endl; for (string VideoTitle : PublishedVideoTitles) { cout << VideoTitle << endl; } } void Subscribe() { SubscribersCount++; } void Unsubscribe() { if (SubscribersCount > 0) { SubscribersCount--; } } void PublishVideo(string title) { PublishedVideoTitles.push_back(title); } }; class CookingYoutubeChannel : public YouTubeChannel { public: CookingYoutubeChannel(string name, string ownerName) : YouTubeChannel(name, ownerName) { } void Practice() { cout << OwnerName << " is Practicing cooking, learning new recipes, experimenting with spices..." << endl; } }; int main() { system("CLS"); CookingYoutubeChannel CookingYtChannel("Amy's kitchen", "Amy"); CookingYoutubeChannel CookingYtChannel2("John's kitchen", "John"); // CookingYtChannel.PublishVideo("Apple pie"); // CookingYtChannel.PublishVideo("Chocolate cake"); // CookingYtChannel.Subscribe(); // CookingYtChannel.Subscribe(); // CookingYtChannel.GetInfo(); CookingYtChannel.Practice(); CookingYtChannel2.Practice(); return 0; }
[ "harshal.patil@gmail.com" ]
harshal.patil@gmail.com
6bb18e25b3548ab6ce122a755173607902d4de45
4b8395650140f76c84e1fe5fef9fff13cff6d772
/Pyrogenesis/source/graphics/tests/test_TextureManager.cpp
2c08172e85d7584650f8002dda7628772acc7382
[]
no_license
Valvador/PyroSpaceFork
7ec549e71e35c629ae0cfc4e2a14835e94779698
f499d58551bb007f3265e2c540f1a70e2c67e1b5
refs/heads/master
2021-01-18T22:15:19.135700
2014-01-28T16:11:39
2014-01-28T16:11:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,518
cpp
/* Generated file, do not edit */ #ifndef CXXTEST_RUNNING #define CXXTEST_RUNNING #endif #define _CXXTEST_HAVE_STD #define _CXXTEST_HAVE_EH #include "precompiled.h" #include <cxxtest/TestListener.h> #include <cxxtest/TestTracker.h> #include <cxxtest/TestRunner.h> #include <cxxtest/RealDescriptions.h> #include "..\..\..\source\graphics\tests\test_TextureManager.h" static TestTextureManager suite_TestTextureManager; static CxxTest::List Tests_TestTextureManager = { 0, 0 }; CxxTest::StaticSuiteDescription suiteDescription_TestTextureManager( "..\\..\\..\\source\\graphics\\tests\\test_TextureManager.h", 29, "TestTextureManager", suite_TestTextureManager, Tests_TestTextureManager ); static class TestDescription_TestTextureManager_test_load_basic : public CxxTest::RealTestDescription { public: TestDescription_TestTextureManager_test_load_basic() : CxxTest::RealTestDescription( Tests_TestTextureManager, suiteDescription_TestTextureManager, 60, "test_load_basic" ) {} void runTest() { suite_TestTextureManager.test_load_basic(); } } testDescription_TestTextureManager_test_load_basic; static class TestDescription_TestTextureManager_test_load_formats : public CxxTest::RealTestDescription { public: TestDescription_TestTextureManager_test_load_formats() : CxxTest::RealTestDescription( Tests_TestTextureManager, suiteDescription_TestTextureManager, 104, "test_load_formats" ) {} void runTest() { suite_TestTextureManager.test_load_formats(); } } testDescription_TestTextureManager_test_load_formats;
[ "val.v.gorbunov@gmail.com" ]
val.v.gorbunov@gmail.com
92c183baee2e7a8ccf3d1499c7b81bc2ee4a313e
25366a29d1aed5bde9d799f3c4fc0eb5269d3db1
/Plugins/MKDatabaseEdit/Source/MKDatabaseEdit/Public/MKDatabaseFunctionLibrary.h
75e51d7c1429e1b8213cb71882bf6d20c0494d13
[]
no_license
MarkLu20/SqlitePlugin
c2772312c67bce7b8c455b35ab0fc0c3acf22e04
7acccd917db8b1f5a187b5e5e0d2940b8aae2604
refs/heads/master
2021-09-10T00:20:21.862426
2018-03-20T10:27:46
2018-03-20T10:27:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
519
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Kismet/BlueprintFunctionLibrary.h" #include "MKDBConnection.h" #include "MKDatabaseFunctionLibrary.generated.h" /** * */ UCLASS() class MKDATABASEEDIT_API UMKDatabaseFunctionLibrary : public UBlueprintFunctionLibrary { GENERATED_BODY() UFUNCTION(BlueprintCallable, Category = "MKDatabaseLibrary") static UMKDBConnection* OpenDatabase(FString OpenString, FString DatabaseType); };
[ "1145230944@qq.com" ]
1145230944@qq.com
4b176da1229e0cc9d631325711420973a09d4928
a2e72048ac50778feb1244be86bb3bfc330ee855
/src/hero.cpp
071867897d98502aa89cdfb8777e3780dcc3fcaf
[]
no_license
calebpalmer/topdown
b62ee73540e11051895c8892d5c6c24196ec1bd6
21c63ab75b2d794a4b9c3585f5e3fed4d52dfaee
refs/heads/master
2016-08-04T19:34:41.034624
2013-07-26T10:39:45
2013-07-26T10:39:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,808
cpp
#include "hero.h" #include <stdexcept> using namespace TopDown; using namespace CapEngine; using namespace std; Hero::Hero(const string& filePath){ spriteSheet.filepath = filePath; spriteSheet.width = 32; spriteSheet.height = 32; spriteSheet.rows = 3; spriteSheet.cols = 2; //face the player right by default direction.x = 1.0; direction.y = 0.0; direction.z = 0.0; // update current sprite currentSpriteColumn = 0; currentSpriteRow = 0; animationSpeed = 6.0; currentState = HERO_STILL; } Hero::~Hero(){ if(surface != nullptr){ VideoManager& videoManager = VideoManager::getInstance(); if(videoManager.initialized){ videoManager.closeSurface(surface); } } } Rectangle Hero::getBoundingRectangle() const{ Rectangle rect; rect.x = position.x; rect.y = position.y; rect.width = spriteSheet.width; rect.height = spriteSheet.height; return rect; } Surface* Hero::getSpriteSurface(int& x, int& y, int& w, int& h ) const{ if(surface == nullptr){ throw runtime_error("Hero has not been initialized"); } x = currentSpriteColumn * spriteSheet.width; y = currentSpriteRow * spriteSheet.height; w = spriteSheet.width; h = spriteSheet.height; return surface; } void Hero::initialize(){ VideoManager& videoManager = VideoManager::getInstance(); if(!videoManager.initialized){ throw CapEngineException("Unable to load surface. Video not initialized"); } // check existence of file path if(!fileExists(spriteSheet.filepath)){ throw CapEngineException("Invalid path: " + spriteSheet.filepath); } surface = videoManager.loadImage(spriteSheet.filepath); } // This function currently just updates which frame from the spritesheet is currently active void Hero::update(real timestep){ if(timestep < 0){ return; } // update current frame row if moving if(currentState == HERO_WALKING){ int walkFrames = 3; real elapsedTime = timestep + lastFrameSwitch; int frames = static_cast<int>((elapsedTime / 1000.0 * animationSpeed)) % walkFrames; lastFrameSwitch = elapsedTime; if(frames > 0){ lastFrameSwitch = 0.0; currentSpriteRow = (currentSpriteRow + frames) % walkFrames; } // update frame column if(direction.x == 1.0){ // sprite 1 looking left currentSpriteColumn = 1; } else if(direction.x == -1.0){ // sprite 2 looking left currentSpriteColumn = 0; } else{ throw runtime_error("Hero has invalid direction"); } } } void Hero::setState(HeroState state){ currentState = state; if(currentState == HERO_WALKING and state == HERO_STILL){ lastFrameSwitch = 0.0; } } int Hero::getWidth() const{ return spriteSheet.width; } int Hero::getHeight() const{ return spriteSheet.height; }
[ "palmer.caleb@gmail.com" ]
palmer.caleb@gmail.com
253a8271b82c0601d9c8bd501d8665858c25cec5
9f05e53255dd6fc4d6d626c79321b96c2b73116e
/Exception8/Exception8/Exception8.cpp
fd6e124717686d8f2fe1e5c9252661a3b67fea93
[]
no_license
frbgd/al2
c11ba81a178649723b2489f86091e9942b0b87b3
a681b5dad4119d1b34b74334688ded10763c3e57
refs/heads/master
2021-09-28T18:59:58.349769
2018-11-19T14:59:21
2018-11-19T14:59:21
158,241,649
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
554
cpp
// пример повторной генерации исключения #include <iostream> using namespace std; void Xhandler() { try { throw "hello"; // генерация char * } catch (const char *) { // перехват char * cout << "Caught char * inside Xhandler\n"; throw; // повторная генерация char * извне функции } } int main() { cout << "Start\n"; try { Xhandler(); } catch (const char *) { cout << "Caught char * inside main\n"; } cout << "End" << endl; system("pause"); return 0; }
[ "kap17597@gmail.com" ]
kap17597@gmail.com
4b11f816b343d8804609a715aadd1d2a41e42b64
230b7714d61bbbc9a75dd9adc487706dffbf301e
/ash/magnifier/docked_magnifier_controller_impl_unittest.cc
74b2dcc3a44495beb7df621f949a0333ef6c35a0
[ "BSD-3-Clause" ]
permissive
byte4byte/cloudretro
efe4f8275f267e553ba82068c91ed801d02637a7
4d6e047d4726c1d3d1d119dfb55c8b0f29f6b39a
refs/heads/master
2023-02-22T02:59:29.357795
2021-01-25T02:32:24
2021-01-25T02:32:24
197,294,750
1
2
BSD-3-Clause
2019-09-11T19:35:45
2019-07-17T01:48:48
null
UTF-8
C++
false
false
32,788
cc
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/magnifier/docked_magnifier_controller_impl.h" #include <memory> #include <vector> #include "ash/accessibility/accessibility_controller_impl.h" #include "ash/display/display_util.h" #include "ash/display/window_tree_host_manager.h" #include "ash/host/ash_window_tree_host.h" #include "ash/magnifier/magnifier_test_utils.h" #include "ash/public/cpp/ash_pref_names.h" #include "ash/public/cpp/ash_switches.h" #include "ash/session/session_controller_impl.h" #include "ash/session/test_session_controller_client.h" #include "ash/shelf/shelf_constants.h" #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "ash/test/ash_test_helper.h" #include "ash/wm/overview/overview_controller.h" #include "ash/wm/splitview/split_view_controller.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "ash/wm/window_state.h" #include "base/command_line.h" #include "base/test/scoped_feature_list.h" #include "components/prefs/pref_service.h" #include "components/session_manager/session_manager_types.h" #include "components/viz/common/features.h" #include "ui/aura/window.h" #include "ui/compositor/layer.h" #include "ui/display/display.h" #include "ui/display/manager/managed_display_info.h" #include "ui/events/test/event_generator.h" #include "ui/views/widget/widget.h" #include "ui/wm/core/coordinate_conversion.h" namespace ash { namespace { constexpr char kUser1Email[] = "user1@dockedmagnifier"; constexpr char kUser2Email[] = "user2@dockedmagnifier"; // Returns the magnifier area height given the display height. int GetMagnifierHeight(int display_height) { return (display_height / DockedMagnifierControllerImpl::kScreenHeightDivisor) + DockedMagnifierControllerImpl::kSeparatorHeight; } class DockedMagnifierTest : public NoSessionAshTestBase, public ::testing::WithParamInterface<bool> { public: DockedMagnifierTest() { if (IsUsingLayerMirroring()) feature_list_.InitAndEnableFeature(features::kVizDisplayCompositor); else feature_list_.InitAndDisableFeature(features::kVizDisplayCompositor); } ~DockedMagnifierTest() override = default; DockedMagnifierControllerImpl* controller() const { return Shell::Get()->docked_magnifier_controller(); } PrefService* user1_pref_service() { return Shell::Get()->session_controller()->GetUserPrefServiceForUser( AccountId::FromUserEmail(kUser1Email)); } PrefService* user2_pref_service() { return Shell::Get()->session_controller()->GetUserPrefServiceForUser( AccountId::FromUserEmail(kUser2Email)); } // AshTestBase: void SetUp() override { // Explicitly enable --ash-constrain-pointer-to-root to be able to test // mouse cursor confinement outside the magnifier viewport. base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kAshConstrainPointerToRoot); NoSessionAshTestBase::SetUp(); // Create user 1 session and simulate its login. SimulateUserLogin(kUser1Email); // Create user 2 session. GetSessionControllerClient()->AddUserSession(kUser2Email); // Place the cursor in the first display. GetEventGenerator()->MoveMouseTo(gfx::Point(0, 0)); } void SwitchActiveUser(const std::string& email) { GetSessionControllerClient()->SwitchActiveUser( AccountId::FromUserEmail(email)); } // Tests that when the magnifier layer's transform is applied on the point in // the |root_window| coordinates that corresponds to the // |point_of_interest_in_screen|, the resulting point is at the center of the // magnifier viewport widget. void TestMagnifierLayerTransform( const gfx::Point& point_of_interest_in_screen, const aura::Window* root_window) { // Convert to root coordinates. gfx::Point point_of_interest_in_root = point_of_interest_in_screen; ::wm::ConvertPointFromScreen(root_window, &point_of_interest_in_root); // Account for point of interest being outside the minimum height threshold. // Do this in gfx::PointF to avoid rounding errors. gfx::PointF point_of_interest_in_root_f(point_of_interest_in_root); const float min_pov_height = controller()->GetMinimumPointOfInterestHeightForTesting(); if (point_of_interest_in_root_f.y() < min_pov_height) point_of_interest_in_root_f.set_y(min_pov_height); const ui::Layer* magnifier_layer = controller()->GetViewportMagnifierLayerForTesting(); // The magnifier layer's transform, when applied to the point of interest // (in root coordinates), should take it to the point at the center of the // viewport widget (also in root coordinates). magnifier_layer->transform().TransformPoint(&point_of_interest_in_root_f); const views::Widget* viewport_widget = controller()->GetViewportWidgetForTesting(); const gfx::Point viewport_center_in_root = viewport_widget->GetNativeWindow() ->GetBoundsInRootWindow() .CenterPoint(); EXPECT_EQ(viewport_center_in_root, gfx::ToFlooredPoint(point_of_interest_in_root_f)); } void TouchPoint(const gfx::Point& touch_point_in_screen) { // TODO(oshima): Currently touch event doesn't update the // event dispatcher in the event generator. Fix it and use // touch event insteead. auto* generator = GetEventGenerator(); generator->GestureTapAt(touch_point_in_screen); } protected: bool IsUsingLayerMirroring() const { return GetParam(); } private: base::test::ScopedFeatureList feature_list_; DISALLOW_COPY_AND_ASSIGN(DockedMagnifierTest); }; INSTANTIATE_TEST_SUITE_P(, DockedMagnifierTest, ::testing::Bool()); // Tests that the Fullscreen and Docked Magnifiers are mutually exclusive. // TODO(afakhry): Update this test to use ash::MagnificationController once // refactored. https://crbug.com/817157. TEST_P(DockedMagnifierTest, MutuallyExclusiveMagnifiers) { // Start with both magnifiers disabled. EXPECT_FALSE(controller()->GetEnabled()); EXPECT_FALSE(controller()->GetFullscreenMagnifierEnabled()); // Enabling one disables the other. controller()->SetEnabled(true); EXPECT_TRUE(controller()->GetEnabled()); EXPECT_FALSE(controller()->GetFullscreenMagnifierEnabled()); controller()->SetFullscreenMagnifierEnabled(true); EXPECT_FALSE(controller()->GetEnabled()); EXPECT_TRUE(controller()->GetFullscreenMagnifierEnabled()); controller()->SetEnabled(true); EXPECT_TRUE(controller()->GetEnabled()); EXPECT_FALSE(controller()->GetFullscreenMagnifierEnabled()); controller()->SetEnabled(false); EXPECT_FALSE(controller()->GetEnabled()); EXPECT_FALSE(controller()->GetFullscreenMagnifierEnabled()); } // Tests the changes in the magnifier's status, user switches. TEST_P(DockedMagnifierTest, TestEnableAndDisable) { // Enable for user 1, and switch to user 2. User 2 should have it disabled. controller()->SetEnabled(true); EXPECT_TRUE(controller()->GetEnabled()); SwitchActiveUser(kUser2Email); EXPECT_FALSE(controller()->GetEnabled()); // Switch back to user 1, expect it to be enabled. SwitchActiveUser(kUser1Email); EXPECT_TRUE(controller()->GetEnabled()); } // Tests the magnifier's scale changes. TEST_P(DockedMagnifierTest, TestScale) { // Scale changes are persisted even when the Docked Magnifier is disabled. EXPECT_FALSE(controller()->GetEnabled()); controller()->SetScale(5.0f); EXPECT_FLOAT_EQ(5.0f, controller()->GetScale()); // Scale values are clamped to a minimum of 1.0f (which means no scale). controller()->SetScale(0.0f); EXPECT_FLOAT_EQ(1.0f, controller()->GetScale()); // Switch to user 2, change the scale, then switch back to user 1. User 1's // scale should not change. SwitchActiveUser(kUser2Email); controller()->SetScale(6.5f); EXPECT_FLOAT_EQ(6.5f, controller()->GetScale()); SwitchActiveUser(kUser1Email); EXPECT_FLOAT_EQ(1.0f, controller()->GetScale()); } // Tests that updates of the Docked Magnifier user prefs from outside the // DockedMagnifierControllerImpl (such as Settings UI) are observed and applied. TEST_P(DockedMagnifierTest, TestOutsidePrefsUpdates) { EXPECT_FALSE(controller()->GetEnabled()); user1_pref_service()->SetBoolean(prefs::kDockedMagnifierEnabled, true); EXPECT_TRUE(controller()->GetEnabled()); user1_pref_service()->SetDouble(prefs::kDockedMagnifierScale, 7.3f); EXPECT_FLOAT_EQ(7.3f, controller()->GetScale()); user1_pref_service()->SetBoolean(prefs::kDockedMagnifierEnabled, false); EXPECT_FALSE(controller()->GetEnabled()); } // Tests that the workareas of displays are adjusted properly when the Docked // Magnifier's viewport moves from one display to the next. TEST_P(DockedMagnifierTest, DisplaysWorkAreas) { UpdateDisplay("800x600,800+0-400x300"); const auto root_windows = Shell::GetAllRootWindows(); ASSERT_EQ(2u, root_windows.size()); // Place the cursor in the first display. GetEventGenerator()->MoveMouseTo(gfx::Point(0, 0)); // Before the magnifier is enabled, the work areas of both displays are their // full size minus the shelf height. const display::Display& display_1 = display_manager()->GetDisplayAt(0); const gfx::Rect disp_1_bounds(0, 0, 800, 600); EXPECT_EQ(disp_1_bounds, display_1.bounds()); gfx::Rect disp_1_workarea_no_magnifier = disp_1_bounds; disp_1_workarea_no_magnifier.Inset(0, 0, 0, ShelfConstants::shelf_size()); EXPECT_EQ(disp_1_workarea_no_magnifier, display_1.work_area()); // At this point, normal mouse cursor confinement should be used. AshWindowTreeHost* host1 = Shell::Get() ->window_tree_host_manager() ->GetAshWindowTreeHostForDisplayId(display_1.id()); EXPECT_EQ(host1->GetLastCursorConfineBoundsInPixels(), gfx::Rect(gfx::Point(0, 0), disp_1_bounds.size())); const display::Display& display_2 = display_manager()->GetDisplayAt(1); const gfx::Rect disp_2_bounds(800, 0, 400, 300); EXPECT_EQ(disp_2_bounds, display_2.bounds()); gfx::Rect disp_2_workarea_no_magnifier = disp_2_bounds; disp_2_workarea_no_magnifier.Inset(0, 0, 0, ShelfConstants::shelf_size()); EXPECT_EQ(disp_2_workarea_no_magnifier, display_2.work_area()); AshWindowTreeHost* host2 = Shell::Get() ->window_tree_host_manager() ->GetAshWindowTreeHostForDisplayId(display_2.id()); EXPECT_EQ(host2->GetLastCursorConfineBoundsInPixels(), gfx::Rect(gfx::Point(0, 0), disp_2_bounds.size())); // Enable the magnifier and the check the workareas. controller()->SetEnabled(true); EXPECT_TRUE(controller()->GetEnabled()); const views::Widget* viewport_1_widget = controller()->GetViewportWidgetForTesting(); ASSERT_NE(nullptr, viewport_1_widget); EXPECT_EQ(root_windows[0], viewport_1_widget->GetNativeView()->GetRootWindow()); // Since the cursor is in the first display, the height of its workarea will // be further shrunk from the top by 1/4th of its full height + the height of // the separator layer. gfx::Rect disp_1_workspace_with_magnifier = disp_1_workarea_no_magnifier; const int disp_1_magnifier_height = GetMagnifierHeight(disp_1_bounds.height()); disp_1_workspace_with_magnifier.Inset(0, disp_1_magnifier_height, 0, 0); EXPECT_EQ(disp_1_bounds, display_1.bounds()); EXPECT_EQ(disp_1_workspace_with_magnifier, display_1.work_area()); // The first display should confine the mouse movement outside of the // viewport. const gfx::Rect disp_1_confine_bounds( 0, disp_1_magnifier_height, disp_1_bounds.width(), disp_1_bounds.height() - disp_1_magnifier_height); EXPECT_EQ(host1->GetLastCursorConfineBoundsInPixels(), disp_1_confine_bounds); // The second display should remain unaffected. EXPECT_EQ(disp_2_bounds, display_2.bounds()); EXPECT_EQ(disp_2_workarea_no_magnifier, display_2.work_area()); EXPECT_EQ(host2->GetLastCursorConfineBoundsInPixels(), gfx::Rect(gfx::Point(0, 0), disp_2_bounds.size())); // Now, move mouse cursor to display 2, and expect that the workarea of // display 1 is restored to its original value, while that of display 2 is // shrunk to fit the Docked Magnifier's viewport. GetEventGenerator()->MoveMouseTo(gfx::Point(800, 0)); const views::Widget* viewport_2_widget = controller()->GetViewportWidgetForTesting(); ASSERT_NE(nullptr, viewport_2_widget); EXPECT_NE(viewport_1_widget, viewport_2_widget); // It's a different widget. EXPECT_EQ(root_windows[1], viewport_2_widget->GetNativeView()->GetRootWindow()); EXPECT_EQ(disp_1_bounds, display_1.bounds()); EXPECT_EQ(disp_1_workarea_no_magnifier, display_1.work_area()); // Display 1 goes back to the normal mouse confinement. EXPECT_EQ(host1->GetLastCursorConfineBoundsInPixels(), gfx::Rect(gfx::Point(0, 0), disp_1_bounds.size())); EXPECT_EQ(disp_2_bounds, display_2.bounds()); gfx::Rect disp_2_workspace_with_magnifier = disp_2_workarea_no_magnifier; const int disp_2_magnifier_height = GetMagnifierHeight(disp_2_bounds.height()); disp_2_workspace_with_magnifier.Inset(0, disp_2_magnifier_height, 0, 0); EXPECT_EQ(disp_2_workspace_with_magnifier, display_2.work_area()); // Display 2's mouse is confined outside the viewport. const gfx::Rect disp_2_confine_bounds( 0, disp_2_magnifier_height, disp_2_bounds.width(), disp_2_bounds.height() - disp_2_magnifier_height); EXPECT_EQ(host2->GetLastCursorConfineBoundsInPixels(), disp_2_confine_bounds); // Now, disable the magnifier, and expect both displays to return back to // their original state. controller()->SetEnabled(false); EXPECT_FALSE(controller()->GetEnabled()); EXPECT_EQ(disp_1_bounds, display_1.bounds()); EXPECT_EQ(disp_1_workarea_no_magnifier, display_1.work_area()); EXPECT_EQ(disp_2_bounds, display_2.bounds()); EXPECT_EQ(disp_2_workarea_no_magnifier, display_2.work_area()); // Normal mouse confinement for both displays. EXPECT_EQ(host1->GetLastCursorConfineBoundsInPixels(), gfx::Rect(gfx::Point(0, 0), disp_1_bounds.size())); EXPECT_EQ(host2->GetLastCursorConfineBoundsInPixels(), gfx::Rect(gfx::Point(0, 0), disp_2_bounds.size())); } // Test that we exit overview mode when enabling the docked magnifier. TEST_P(DockedMagnifierTest, DisplaysWorkAreasOverviewMode) { std::unique_ptr<aura::Window> window( CreateTestWindowInShell(SK_ColorWHITE, 100, gfx::Rect(0, 0, 200, 200))); wm::GetWindowState(window.get())->Maximize(); // Enable overview mode followed by the magnifier. auto* overview_controller = Shell::Get()->overview_controller(); overview_controller->StartOverview(); EXPECT_TRUE(overview_controller->InOverviewSession()); controller()->SetEnabled(true); EXPECT_TRUE(controller()->GetEnabled()); // Expect that overview mode is exited, the display's work area is updated, // and the window's bounds are updated to be equal to the new display's work // area bounds. EXPECT_FALSE(overview_controller->InOverviewSession()); const display::Display& display = display_manager()->GetDisplayAt(0); gfx::Rect workarea = display.bounds(); const int magnifier_height = GetMagnifierHeight(display.bounds().height()); workarea.Inset(0, magnifier_height, 0, ShelfConstants::shelf_size()); EXPECT_EQ(workarea, display.work_area()); EXPECT_EQ(workarea, window->bounds()); EXPECT_TRUE(wm::GetWindowState(window.get())->IsMaximized()); } // Test that we exist split view and over view modes when a single window is // snapped and the other snap region is hosting overview mode. TEST_P(DockedMagnifierTest, DisplaysWorkAreasSingleSplitView) { // Verify that we're in tablet mode. Shell::Get()->tablet_mode_controller()->SetEnabledForTest(true); EXPECT_TRUE(Shell::Get()->tablet_mode_controller()->InTabletMode()); std::unique_ptr<aura::Window> window( CreateTestWindowInShell(SK_ColorWHITE, 100, gfx::Rect(0, 0, 200, 200))); wm::GetWindowState(window.get())->Maximize(); auto* split_view_controller = Shell::Get()->split_view_controller(); EXPECT_EQ(split_view_controller->state(), SplitViewState::kNoSnap); EXPECT_EQ(split_view_controller->InSplitViewMode(), false); // Simulate going into split view, by enabling overview mode, and snapping // a window to the left. auto* overview_controller = Shell::Get()->overview_controller(); overview_controller->StartOverview(); EXPECT_TRUE(overview_controller->InOverviewSession()); split_view_controller->SnapWindow(window.get(), SplitViewController::LEFT); EXPECT_EQ(split_view_controller->state(), SplitViewState::kLeftSnapped); EXPECT_EQ(split_view_controller->left_window(), window.get()); EXPECT_TRUE(overview_controller->InOverviewSession()); // Enable the docked magnifier and expect that both overview and split view // modes are exited, and the window remains maximized, and its bounds are // updated to match the new display's work area. controller()->SetEnabled(true); EXPECT_TRUE(controller()->GetEnabled()); EXPECT_FALSE(overview_controller->InOverviewSession()); EXPECT_EQ(split_view_controller->state(), SplitViewState::kNoSnap); EXPECT_EQ(split_view_controller->InSplitViewMode(), false); const display::Display& display = display_manager()->GetDisplayAt(0); const int magnifier_height = GetMagnifierHeight(display.bounds().height()); gfx::Rect work_area = display.bounds(); work_area.Inset(0, magnifier_height, 0, ShelfConstants::shelf_size()); EXPECT_EQ(work_area, display.work_area()); EXPECT_EQ(work_area, window->bounds()); EXPECT_TRUE(wm::GetWindowState(window.get())->IsMaximized()); } // Test that we don't exit split view with two windows snapped on both sides // when we enable the docked magnifier, but rather their bounds are updated. TEST_P(DockedMagnifierTest, DisplaysWorkAreasDoubleSplitView) { // Verify that we're in tablet mode. Shell::Get()->tablet_mode_controller()->SetEnabledForTest(true); EXPECT_TRUE(Shell::Get()->tablet_mode_controller()->InTabletMode()); std::unique_ptr<aura::Window> window1( CreateTestWindowInShell(SK_ColorWHITE, 100, gfx::Rect(0, 0, 200, 200))); std::unique_ptr<aura::Window> window2( CreateTestWindowInShell(SK_ColorWHITE, 200, gfx::Rect(0, 0, 200, 200))); auto* overview_controller = Shell::Get()->overview_controller(); overview_controller->StartOverview(); EXPECT_TRUE(overview_controller->InOverviewSession()); auto* split_view_controller = Shell::Get()->split_view_controller(); EXPECT_EQ(split_view_controller->InSplitViewMode(), false); split_view_controller->SnapWindow(window1.get(), SplitViewController::LEFT); split_view_controller->SnapWindow(window2.get(), SplitViewController::RIGHT); EXPECT_EQ(split_view_controller->InSplitViewMode(), true); EXPECT_EQ(split_view_controller->state(), SplitViewState::kBothSnapped); // Snapping both windows should exit overview mode. EXPECT_FALSE(overview_controller->InOverviewSession()); // Enable the docked magnifier, and expect that split view does not exit, and // the two windows heights are updated to be equal to the height of the // updated display's work area. controller()->SetEnabled(true); EXPECT_TRUE(controller()->GetEnabled()); EXPECT_EQ(split_view_controller->InSplitViewMode(), true); EXPECT_EQ(split_view_controller->state(), SplitViewState::kBothSnapped); const display::Display& display = display_manager()->GetDisplayAt(0); const int magnifier_height = GetMagnifierHeight(display.bounds().height()); gfx::Rect work_area = display.bounds(); work_area.Inset(0, magnifier_height, 0, ShelfConstants::shelf_size()); EXPECT_EQ(work_area, display.work_area()); EXPECT_EQ(work_area.height(), window1->bounds().height()); EXPECT_EQ(work_area.height(), window2->bounds().height()); } // Tests that the Docked Magnifier follows touch events. TEST_P(DockedMagnifierTest, TouchEvents) { UpdateDisplay("800x600,800+0-400x300"); const auto root_windows = Shell::GetAllRootWindows(); ASSERT_EQ(2u, root_windows.size()); controller()->SetEnabled(true); EXPECT_TRUE(controller()->GetEnabled()); controller()->SetScale(4.0f); // Generate some touch events in both displays and expect the magnifier // viewport moves accordingly. gfx::Point touch_point(200, 350); TouchPoint(touch_point); const views::Widget* viewport_widget = controller()->GetViewportWidgetForTesting(); EXPECT_EQ(root_windows[0], viewport_widget->GetNativeView()->GetRootWindow()); TestMagnifierLayerTransform(touch_point, root_windows[0]); // Touch a new point in the other display. touch_point = gfx::Point(900, 200); TouchPoint(touch_point); // New viewport widget is created in the second display. ASSERT_NE(viewport_widget, controller()->GetViewportWidgetForTesting()); viewport_widget = controller()->GetViewportWidgetForTesting(); EXPECT_EQ(root_windows[1], viewport_widget->GetNativeView()->GetRootWindow()); TestMagnifierLayerTransform(touch_point, root_windows[1]); } // Tests the behavior of the magnifier when displays are added or removed. TEST_P(DockedMagnifierTest, AddRemoveDisplays) { // Start with a single display. const auto disp_1_info = display::ManagedDisplayInfo::CreateFromSpecWithID( "0+0-600x800", 101 /* id */); std::vector<display::ManagedDisplayInfo> info_list; info_list.push_back(disp_1_info); display_manager()->OnNativeDisplaysChanged(info_list); auto root_windows = Shell::GetAllRootWindows(); ASSERT_EQ(1u, root_windows.size()); // Enable the magnifier, and validate the state of the viewport widget. controller()->SetEnabled(true); EXPECT_TRUE(controller()->GetEnabled()); const views::Widget* viewport_widget = controller()->GetViewportWidgetForTesting(); ASSERT_NE(nullptr, viewport_widget); EXPECT_EQ(root_windows[0], viewport_widget->GetNativeView()->GetRootWindow()); const int viewport_1_height = 800 / DockedMagnifierControllerImpl::kScreenHeightDivisor; EXPECT_EQ(gfx::Rect(0, 0, 600, viewport_1_height), viewport_widget->GetWindowBoundsInScreen()); // Adding a new display should not affect where the viewport currently is. const auto disp_2_info = display::ManagedDisplayInfo::CreateFromSpecWithID( "600+0-400x600", 102 /* id */); info_list.push_back(disp_2_info); display_manager()->OnNativeDisplaysChanged(info_list); root_windows = Shell::GetAllRootWindows(); ASSERT_EQ(2u, root_windows.size()); // Same viewport widget in same root window. EXPECT_EQ(viewport_widget, controller()->GetViewportWidgetForTesting()); EXPECT_EQ(root_windows[0], viewport_widget->GetNativeView()->GetRootWindow()); EXPECT_EQ(gfx::Rect(0, 0, 600, viewport_1_height), viewport_widget->GetWindowBoundsInScreen()); // Move the cursor to the second display, expect the viewport widget to get // updated accordingly. GetEventGenerator()->MoveMouseTo(gfx::Point(800, 0)); // New viewport widget is created. ASSERT_NE(viewport_widget, controller()->GetViewportWidgetForTesting()); viewport_widget = controller()->GetViewportWidgetForTesting(); EXPECT_EQ(root_windows[1], viewport_widget->GetNativeView()->GetRootWindow()); const int viewport_2_height = 600 / DockedMagnifierControllerImpl::kScreenHeightDivisor; EXPECT_EQ(gfx::Rect(600, 0, 400, viewport_2_height), viewport_widget->GetWindowBoundsInScreen()); // Now, remove display 2 ** while ** the magnifier viewport is there. This // should cause no crashes, the viewport widget should be recreated in // display 1. info_list.clear(); info_list.push_back(disp_1_info); display_manager()->OnNativeDisplaysChanged(info_list); // We need to spin this run loop to wait for a new mouse event to be // dispatched so that the viewport widget is re-created. base::RunLoop().RunUntilIdle(); root_windows = Shell::GetAllRootWindows(); ASSERT_EQ(1u, root_windows.size()); viewport_widget = controller()->GetViewportWidgetForTesting(); ASSERT_NE(nullptr, viewport_widget); EXPECT_EQ(root_windows[0], viewport_widget->GetNativeView()->GetRootWindow()); EXPECT_EQ(gfx::Rect(0, 0, 600, viewport_1_height), viewport_widget->GetWindowBoundsInScreen()); } // Tests various magnifier layer transform in the simple cases (i.e. no device // scale factors or screen rotations). TEST_P(DockedMagnifierTest, TransformSimple) { UpdateDisplay("800x800"); const auto root_windows = Shell::GetAllRootWindows(); ASSERT_EQ(1u, root_windows.size()); controller()->SetEnabled(true); const float scale1 = 2.0f; controller()->SetScale(scale1); EXPECT_TRUE(controller()->GetEnabled()); EXPECT_FLOAT_EQ(scale1, controller()->GetScale()); const views::Widget* viewport_widget = controller()->GetViewportWidgetForTesting(); ASSERT_NE(nullptr, viewport_widget); EXPECT_EQ(root_windows[0], viewport_widget->GetNativeView()->GetRootWindow()); const int viewport_height = 800 / DockedMagnifierControllerImpl::kScreenHeightDivisor; EXPECT_EQ(gfx::Rect(0, 0, 800, viewport_height), viewport_widget->GetWindowBoundsInScreen()); // Move the cursor to the center of the screen. gfx::Point point_of_interest(400, 400); GetEventGenerator()->MoveMouseTo(point_of_interest); TestMagnifierLayerTransform(point_of_interest, root_windows[0]); // Move the cursor to the bottom right corner. point_of_interest = gfx::Point(799, 799); GetEventGenerator()->MoveMouseTo(point_of_interest); TestMagnifierLayerTransform(point_of_interest, root_windows[0]); // Tricky: Move the cursor to the top right corner, such that the cursor is // over the magnifier viewport. The transform should be such that the viewport // doesn't show itself. point_of_interest = gfx::Point(799, 0); GetEventGenerator()->MoveMouseTo(point_of_interest); TestMagnifierLayerTransform(point_of_interest, root_windows[0]); // In this case, our point of interest is changed to be at the bottom of the // separator, and it should go to the center of the top *edge* of the viewport // widget. point_of_interest.set_y(viewport_height + DockedMagnifierControllerImpl::kSeparatorHeight); const gfx::Point viewport_center = viewport_widget->GetNativeWindow()->GetBoundsInRootWindow().CenterPoint(); gfx::Point viewport_top_edge_center = viewport_center; viewport_top_edge_center.set_y(0); const ui::Layer* magnifier_layer = controller()->GetViewportMagnifierLayerForTesting(); magnifier_layer->transform().TransformPoint(&point_of_interest); EXPECT_EQ(viewport_top_edge_center, point_of_interest); // The minimum height for the point of interest is the bottom of the viewport // + the height of the separator + half the height of the viewport when scaled // back to the non-magnified space. EXPECT_FLOAT_EQ(viewport_height + DockedMagnifierControllerImpl::kSeparatorHeight + (viewport_center.y() / scale1), controller()->GetMinimumPointOfInterestHeightForTesting()); // Leave the mouse cursor where it is, and only change the magnifier's scale. const float scale2 = 5.3f; controller()->SetScale(scale2); EXPECT_FLOAT_EQ(scale2, controller()->GetScale()); // The transform behaves exactly as above even with a different scale. point_of_interest = gfx::Point(799, 0); TestMagnifierLayerTransform(point_of_interest, root_windows[0]); point_of_interest.set_y(viewport_height + DockedMagnifierControllerImpl::kSeparatorHeight); magnifier_layer->transform().TransformPoint(&point_of_interest); EXPECT_EQ(viewport_top_edge_center, point_of_interest); EXPECT_FLOAT_EQ(viewport_height + DockedMagnifierControllerImpl::kSeparatorHeight + (viewport_center.y() / scale2), controller()->GetMinimumPointOfInterestHeightForTesting()); } // Tests that the magnifier viewport follows text fields focus and input caret // bounds changes events. TEST_P(DockedMagnifierTest, TextInputFieldEvents) { UpdateDisplay("600x900"); const auto root_windows = Shell::GetAllRootWindows(); ASSERT_EQ(1u, root_windows.size()); MagnifierTextInputTestHelper text_input_helper; text_input_helper.CreateAndShowTextInputView(gfx::Rect(500, 400, 80, 80)); // Enable the docked magnifier. controller()->SetEnabled(true); const float scale1 = 2.0f; controller()->SetScale(scale1); EXPECT_TRUE(controller()->GetEnabled()); EXPECT_FLOAT_EQ(scale1, controller()->GetScale()); // Focus on the text input field. text_input_helper.FocusOnTextInputView(); // The text input caret center point will be our point of interest. When it // goes through the magnifier layer transform, it should end up being in the // center of the viewport. gfx::Point caret_center(text_input_helper.GetCaretBounds().CenterPoint()); TestMagnifierLayerTransform(caret_center, root_windows[0]); // Simulate typing by pressing some keys while focus is in the text field. The // transformed caret center should always go to the viewport center. GetEventGenerator()->PressKey(ui::VKEY_A, 0); GetEventGenerator()->ReleaseKey(ui::VKEY_A, 0); gfx::Point new_caret_center(text_input_helper.GetCaretBounds().CenterPoint()); TestMagnifierLayerTransform(new_caret_center, root_windows[0]); } TEST_P(DockedMagnifierTest, FocusChangeEvents) { UpdateDisplay("600x900"); const auto root_windows = Shell::GetAllRootWindows(); ASSERT_EQ(1u, root_windows.size()); MagnifierFocusTestHelper focus_test_helper; focus_test_helper.CreateAndShowFocusTestView(gfx::Point(70, 500)); // Enable the docked magnifier. controller()->SetEnabled(true); const float scale = 2.0f; controller()->SetScale(scale); EXPECT_TRUE(controller()->GetEnabled()); EXPECT_FLOAT_EQ(scale, controller()->GetScale()); // Focus on the first button and expect the magnifier to be centered around // its center. focus_test_helper.FocusFirstButton(); gfx::Point button_1_center( focus_test_helper.GetFirstButtonBoundsInRoot().CenterPoint()); TestMagnifierLayerTransform(button_1_center, root_windows[0]); // Similarly if we focus on the second button. focus_test_helper.FocusSecondButton(); gfx::Point button_2_center( focus_test_helper.GetSecondButtonBoundsInRoot().CenterPoint()); TestMagnifierLayerTransform(button_2_center, root_windows[0]); } // Tests that viewport layer is inverted properly when the status of the High // Contrast mode changes. TEST_P(DockedMagnifierTest, HighContrastMode) { // This test is not relevant when layer mirroring is used. if (IsUsingLayerMirroring()) return; UpdateDisplay("600x900"); // Enable the docked magnifier. DockedMagnifierControllerImpl* magnifier = controller(); magnifier->SetEnabled(true); EXPECT_TRUE(magnifier->GetEnabled()); // Expect that the magnifier layer is not inverted. const ui::Layer* viewport_layer = magnifier->GetViewportMagnifierLayerForTesting(); ASSERT_TRUE(viewport_layer); EXPECT_FALSE(viewport_layer->layer_inverted()); // Enable High Contrast mode, and expect the viewport layer to be inverted. Shell::Get()->accessibility_controller()->SetHighContrastEnabled(true); EXPECT_TRUE( Shell::Get()->accessibility_controller()->high_contrast_enabled()); EXPECT_TRUE(viewport_layer->layer_inverted()); // Disable High Contrast, the layer should be updated accordingly. Shell::Get()->accessibility_controller()->SetHighContrastEnabled(false); EXPECT_FALSE( Shell::Get()->accessibility_controller()->high_contrast_enabled()); EXPECT_FALSE(viewport_layer->layer_inverted()); // Now, disable the Docked Magnifier, enable High Contrast, and then re-enable // the Docked Magnifier. The newly created viewport layer should be inverted. magnifier->SetEnabled(false); EXPECT_FALSE(magnifier->GetEnabled()); Shell::Get()->accessibility_controller()->SetHighContrastEnabled(true); EXPECT_TRUE( Shell::Get()->accessibility_controller()->high_contrast_enabled()); magnifier->SetEnabled(true); EXPECT_TRUE(magnifier->GetEnabled()); const ui::Layer* new_viewport_layer = magnifier->GetViewportMagnifierLayerForTesting(); ASSERT_TRUE(new_viewport_layer); EXPECT_NE(new_viewport_layer, viewport_layer); EXPECT_TRUE(new_viewport_layer->layer_inverted()); } // TODO(afakhry): Expand tests: // - Test magnifier viewport's layer transforms with screen rotation, // multi display, and unified mode. // - Test adjust scale using scroll events. } // namespace } // namespace ash
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
739829bfa95a83a24cf6e8f561ecf20bdbbb49a3
57c57dcf23c4be2fe8b8dbe89507682fc58dc087
/clases/gestor/ciudad.h
6622e3c78f31df2a23cc2acaa5c25b3f439651f0
[]
no_license
makoki13/qtSatrapiaGUI
84846cbf29cdaef57ad2d1baa08a1ecd319b24e9
abbf5fbdd13b06ad2e0766b9576338c847f26e3e
refs/heads/master
2022-10-21T09:46:12.262369
2020-06-11T13:30:48
2020-06-11T13:30:48
264,948,086
0
0
null
null
null
null
UTF-8
C++
false
false
872
h
/** Una ciudad tiene varios edificios que son gestionados por el Palacio (o la alcadía (eso en proyecto)) La ciudad tiene una posicion y un nombre Hay una única ciudad que alberga el palacio. */ #ifndef CIUDAD_H #define CIUDAD_H #include <QString> #include "palacio.h" class Palacio; class Ciudad { private: bool es_capital; QString nombre; Posicion posicion; Palacio *palacio; //TODO crear ayuntamiento public: Ciudad(); Ciudad(bool esCapital, Posicion posicion); static Ciudad* creaCiudad(QString nombre, bool esCapital, Posicion posicion); void setNombre(QString nombre); QString getNombre(); void setCapital(bool valor); bool esCapital(); void setPosicion(Posicion pos); Posicion getPosicion(); void setPalacio(Palacio* palacio); Palacio* getPalacio(); }; #endif // CIUDAD_H
[ "pablo.makoki@gmail.com" ]
pablo.makoki@gmail.com
e3532315b1a3a5ac3945248b72d38ed9e476672b
cdb29c7fecbf48e5b5c5c2c72960c0643d36d161
/ToyBox/HalfMesh.cpp
39e356242eda2fb8d02a80b4082dcbace212e32b
[ "MIT" ]
permissive
hafewa/MoonEngine
31397dd71d6807b170fee847e5fe09e6f8f16a91
b6d8464cdf87c2045b5d4ecce348dc76815b7ff1
refs/heads/master
2023-06-09T11:36:34.044483
2021-07-01T07:42:19
2021-07-01T07:42:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,512
cpp
#include "HalfMesh.h" #include "SceneMgr.h" namespace MOON { void HalfMesh::SetupMesh() { glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); UpdateMesh(); // set the vertex attribute pointers // vertex Positions glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); // vertex normals glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Normal)); // vertex texture coords glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, UV)); // vertex tangent glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Tangent)); // vertex bitangent glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Bitangent)); glBindVertexArray(0); } void HalfMesh::ClearSelection(const int& type) { if (type == VERT) MOON_InputManager::Selector::ClearSelectionPrototype(vertices, selected_verts); else if (type == EDGE) MOON_InputManager::Selector::ClearSelectionPrototype(edges, selected_edges); else if (type == FACE) MOON_InputManager::Selector::ClearSelectionPrototype(faces, selected_faces); else { MOON_InputManager::Selector::ClearSelectionPrototype(vertices, selected_verts); MOON_InputManager::Selector::ClearSelectionPrototype(edges, selected_edges); MOON_InputManager::Selector::ClearSelectionPrototype(faces, selected_faces); } } void HalfMesh::Select(const Element& type, const unsigned int ID) { if (type == VERT) MOON_InputManager::Selector::SelectPrototype(vertices, selected_verts, ID); else if (type == EDGE) MOON_InputManager::Selector::SelectPrototype(edges, selected_edges, ID); else if (type == FACE) MOON_InputManager::Selector::SelectPrototype(faces, selected_faces, ID); } void HalfMesh::Select_Append(const Element& type, unsigned int ID, const bool& autoInvertSelect) { if (type == VERT) MOON_InputManager::Selector::Select_AppendPrototype( vertices, selected_verts, ID, autoInvertSelect ); else if (type == EDGE) MOON_InputManager::Selector::Select_AppendPrototype( edges, selected_edges, ID, autoInvertSelect ); else if (type == FACE) MOON_InputManager::Selector::Select_AppendPrototype( faces, selected_faces, ID, autoInvertSelect ); } }
[ "hztmailbox@gmail.com" ]
hztmailbox@gmail.com
e922a1688d21640a5fa7f52be3c75051f9aa8041
751d837b8a4445877bb2f0d1e97ce41cd39ce1bd
/codingtrain/35_1-traveling-salesperson.cpp
be24d739795631a6ea04147b7238e325da2382e0
[ "MIT" ]
permissive
qeedquan/challenges
d55146f784a3619caa4541ac6f2b670b0a3dd8ba
56823e77cf502bdea68cce0e1221f5add3d64d6a
refs/heads/master
2023-08-11T20:35:09.726571
2023-08-11T13:02:43
2023-08-11T13:02:43
115,886,967
2
1
null
null
null
null
UTF-8
C++
false
false
5,099
cpp
#include <cstdio> #include <cstdlib> #include <cmath> #include <cstdarg> #include <cstdint> #include <chrono> #include <algorithm> #include <vector> #include <random> #include <SDL.h> #include <cairo.h> using namespace std; struct App { SDL_Window *window; SDL_Renderer *renderer; SDL_Texture *texture; cairo_surface_t *canvas; cairo_t *cr; vector<SDL_FPoint> best; float record; vector<SDL_FPoint> cities; size_t num_cities; int width, height; uint32_t start; bool paused; void resize(int new_width, int new_height); void init(); void reset(); float calc_distance(const vector<SDL_FPoint> &points); void gen_cities(); void next_tour(); void event(); void update(); void draw_tour(); void upload(); void draw(); }; [[noreturn]] void fatal(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, "\n"); exit(1); } float unlerp(float t, float a, float b) { return (t - a) / (b - a); } float linear_remap(float x, float a, float b, float c, float d) { return lerp(c, d, unlerp(x, a, b)); } void App::resize(int new_width, int new_height) { width = new_width; height = new_height; if (texture) SDL_DestroyTexture(texture); if (canvas) { cairo_surface_destroy(canvas); cairo_destroy(cr); } texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, width, height); if (!texture) fatal("Failed to create texture: %s", SDL_GetError()); canvas = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height); cr = cairo_create(canvas); } void App::init() { if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0) fatal("Failed to init SDL: %s", SDL_GetError()); width = 800; height = 600; auto wflag = SDL_WINDOW_RESIZABLE; if (SDL_CreateWindowAndRenderer(width, height, wflag, &window, &renderer) < 0) fatal("Failed to create a window: %s", SDL_GetError()); SDL_SetWindowTitle(window, "Traveling Salesman Problem"); resize(width, height); num_cities = 10; } void App::reset() { start = SDL_GetTicks(); gen_cities(); } float App::calc_distance(const vector<SDL_FPoint> &points) { auto sum = 0.0; for (auto i = 0u; i < points.size() - 1; i++) sum += hypot(points[i].x - points[i + 1].x, points[i].y - points[i + 1].y); return sum; } void App::gen_cities() { auto seed = chrono::system_clock::now().time_since_epoch().count(); default_random_engine generator(seed); uniform_real_distribution<float> x_distribution(0.0, width); uniform_real_distribution<float> y_distribution(0.0, height); cities.resize(num_cities); for (auto i = 0u; i < cities.size(); i++) cities[i] = { x_distribution(generator), y_distribution(generator) }; record = calc_distance(cities); best = cities; printf("%zu cities\n", num_cities); } void App::next_tour() { auto seed = chrono::system_clock::now().time_since_epoch().count(); default_random_engine generator(seed); uniform_int_distribution<> distribution(0, cities.size() - 1); auto i = distribution(generator); auto j = distribution(generator); swap(cities[i], cities[j]); auto dist = calc_distance(cities); if (dist < record) { record = dist; best = cities; } } void App::event() { SDL_Event ev; while (SDL_PollEvent(&ev)) { switch (ev.type) { case SDL_QUIT: exit(0); case SDL_KEYDOWN: switch (ev.key.keysym.sym) { case SDLK_ESCAPE: exit(0); case SDLK_RETURN: paused = !paused; break; case SDLK_SPACE: reset(); break; case SDLK_LEFT: if (num_cities > 1) num_cities--; gen_cities(); break; case SDLK_RIGHT: num_cities++; gen_cities(); break; } break; case SDL_WINDOWEVENT: switch (ev.window.event) { case SDL_WINDOWEVENT_RESIZED: case SDL_WINDOWEVENT_SIZE_CHANGED: resize(ev.window.data1, ev.window.data2); break; } break; } } } void App::update() { auto now = SDL_GetTicks(); if (now - start < 500) return; if (!paused) next_tour(); start = now; } void App::draw_tour() { cairo_set_source_rgb(cr, 0, 0, 0); cairo_paint(cr); cairo_set_source_rgb(cr, 1, 1, 1); cairo_set_line_width(cr, 2); for (auto city : cities) cairo_line_to(cr, city.x, city.y); cairo_stroke(cr); cairo_set_source_rgb(cr, 1, 0, 1); cairo_set_line_width(cr, 4); for (auto city : best) cairo_line_to(cr, city.x, city.y); cairo_stroke(cr); cairo_set_source_rgb(cr, 1, 1, 1); for (auto city : cities) { cairo_arc(cr, city.x, city.y, 8, 0, 2 * M_PI); cairo_fill(cr); } } void App::upload() { void *pixels, *data; int pitch; SDL_LockTexture(texture, NULL, &pixels, &pitch); data = cairo_image_surface_get_data(canvas); memcpy(pixels, data, pitch * height); SDL_UnlockTexture(texture); } void App::draw() { SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); draw_tour(); upload(); SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); } int main() { auto app = new App(); app->init(); app->reset(); for (;;) { app->event(); app->update(); app->draw(); } return 0; }
[ "qeed.quan@gmail.com" ]
qeed.quan@gmail.com
f1337c0f3f49b32e35176e6a1749f216e4048b8a
a8d58a208a58a4dc9bf3499383787168f77b280c
/School/Test.h
68acbef8f059501f20b29e0458408cbad3006be3
[]
no_license
zruslan2/SchoolProject
e5fed44d2bf71ad03e473df6cdf39e807ab553e6
dbb9f680840d13d037b297ba39158bcea1d06819
refs/heads/master
2020-04-10T18:44:11.035459
2018-12-14T17:11:13
2018-12-14T17:11:13
161,210,821
0
0
null
null
null
null
UTF-8
C++
false
false
1,081
h
#pragma once #include "Question.h" #include <fstream> class Test { static int seqIdTest; int idTest; int quesNum = 0; string testName; map<int, Question> testQuestions; int testMaxResult; int idCreator; public: Test(string testName); Test()=default; void setIdTest(int idTest); int getIdTest()const { return this->idTest; } void setTestName(string testName); string getTestName()const { return testName; } void setTestMaxResult(int testMaxResult); int getTestMaxResult()const { return testMaxResult; } void setIdCreator(int idCreator); int getIdCreator()const { return idCreator; } Question& operator[](int number); void addQuestion(Question& ques); void addQuestionFromString(string& str); void delQuestion(int number); int getCntTestQuestions()const { return testQuestions.size(); } auto getBeginTestQuestions()const { return begin(testQuestions); } auto getEndTestQuestions()const { return end(testQuestions); } string convertToString(); void readFromFile(int id); void writeToFile(); //++ int sumRightAnswers()const; //++ void print()const; };
[ "Ruslan@RUSLAN-PC" ]
Ruslan@RUSLAN-PC