blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
fcb2c00ad8ebd6ea2a0a1aded9aecf7a9d104605
a25610811f2fb34a3d8d2512affdf5be44e6e45b
/include/OpenCLCopy.hpp
7f0db3a7077ea9d69e6bba0ce29c54547d109045
[ "BSD-3-Clause" ]
permissive
pavanky/forge
e712cfb5716bcc9b09f6b3bb42b72ba4d6b06f17
e40b30a0330a492f54757b5efeee1ecdfa573cf3
refs/heads/master
2021-01-24T23:12:38.145290
2015-11-12T18:47:38
2015-11-12T18:47:38
36,021,004
2
0
null
2015-05-21T15:29:32
2015-05-21T15:29:32
null
UTF-8
C++
false
false
1,740
hpp
OpenCLCopy.hpp
/******************************************************* * Copyright (c) 2015-2019, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #ifndef __OPENCL_DATA_COPY_H__ #define __OPENCL_DATA_COPY_H__ namespace fg { static void copy(fg::Image& out, const cl::Buffer& in, const cl::CommandQueue& queue) { cl::BufferGL pboMapBuffer(queue.getInfo<CL_QUEUE_CONTEXT>(), CL_MEM_WRITE_ONLY, out.pbo(), NULL); std::vector<cl::Memory> shared_objects; shared_objects.push_back(pboMapBuffer); glFinish(); queue.enqueueAcquireGLObjects(&shared_objects); queue.enqueueCopyBuffer(in, pboMapBuffer, 0, 0, out.size(), NULL, NULL); queue.finish(); queue.enqueueReleaseGLObjects(&shared_objects); } /* * Below functions takes any renderable forge object that has following member functions * defined * * `unsigned Renderable::vbo() const;` * `unsigned Renderable::size() const;` * * Currently fg::Plot, fg::Histogram objects in Forge library fit the bill */ template<class Renderable> void copy(Renderable& out, const cl::Buffer& in, const cl::CommandQueue& queue) { cl::BufferGL vboMapBuffer(queue.getInfo<CL_QUEUE_CONTEXT>(), CL_MEM_WRITE_ONLY, out.vbo(), NULL); std::vector<cl::Memory> shared_objects; shared_objects.push_back(vboMapBuffer); glFinish(); queue.enqueueAcquireGLObjects(&shared_objects); queue.enqueueCopyBuffer(in, vboMapBuffer, 0, 0, out.size(), NULL, NULL); queue.finish(); queue.enqueueReleaseGLObjects(&shared_objects); } } #endif //__OPENCL_DATA_COPY_H__
9308d0a2cd06a7035f9726c19edd26a2841f0547
5bbaeac40717a0bd16ba8ba8faf3fbfb29c5b7c9
/src/fastqpattern.h
ceeafac7f29ea30888a11ec1a9f6fbc2b9867e50
[ "MIT" ]
permissive
LaoZZZZZ/bartender-1.1
46bbbd91c824216a211aa9f3b5a132d77c59c0c1
439b1a23a21ad035468fb6c00a9efaa21ec4045a
refs/heads/master
2023-04-27T16:29:29.410121
2023-04-27T02:44:33
2023-04-27T02:44:33
50,738,171
29
10
MIT
2023-09-05T15:52:47
2016-01-30T18:23:06
C++
UTF-8
C++
false
false
480
h
fastqpattern.h
/* * Copyright 2014, Lu Zhao <luzhao1986@gmail.com> * * This file is part of suffix matching project. */ #ifndef FASTQPATTERN_H #define FASTQPATTERN_H #include "patternparser.h" namespace barcodeSpace{ class fastqPattern : public patternParser { public: fastqPattern(const std::string&); private: void parseImp(Sequence& read, bool& success, bool& done); private: bool first_; }; } #endif // FASTQPATTERN_H
d525a3ac5fe2e58b64a35aa2a0bbc123fed6cf27
9473aca2ebeaa77bcf9275171866597e10507691
/src/apkworkstation/ui/toolbar.h
f913814ec8dbfba75dac220e7542a3bc6d6c286f
[]
no_license
redlee90/APKWorkstation
5aec3c5af0c84dfe4764d2c7632c57e04e6201b7
ca4caddc3582d060f8cb9f18d19edf4f7f56c105
refs/heads/master
2020-04-14T08:57:23.004717
2015-04-13T22:17:09
2015-04-13T22:17:09
33,635,361
0
0
null
null
null
null
UTF-8
C++
false
false
2,123
h
toolbar.h
#ifndef VPZ_APKSTUDIO_UI_TOOLBAR_H #define VPZ_APKSTUDIO_UI_TOOLBAR_H #include <QAction> #include <QIcon> #include <QObject> #include <QToolBar> #include <QWidget> #include "../utility/resource.h" namespace UI { class Toolbar : public QToolBar { Q_OBJECT public: // Action QAction *_directory; QAction *_apk; QAction *_build; QAction *_decompile; QAction *_decompile_dex; QAction *_decompile_res; QAction *_dex2jar; QAction *_showjava; QAction *_print; QAction *_shell; // Resource static QIcon icon(const char *name) { return Utility::Resource::icon("toolbar", name); } static QString text(const char *key) { return Utility::Resource::text("toolbar", key); } private slots: void __apk() { emit action(APK); } void __build() { emit action(BUILD); } void __decompile() { emit action(DECOMPILE); } void __decompile_dex() { emit action(DECOMPILE_DEX); } void __decompile_res() { emit action(DECOMPILE_RES); } void __dex2jar() { emit action(DEX2JAR); } void __showjava() { emit action(SHOW_JAVA); } void __directory() { emit action(DIRECTORY); } void __print() { emit action(PRINT); } void __shell() { emit action(SHELL); } public: // Constructor Toolbar(QWidget *parent = 0); // Destructor ~Toolbar() { } // Enum enum Action { APK = 30, BUILD, DECOMPILE, DECOMPILE_DEX, DECOMPILE_RES, DEX2JAR, SHOW_JAVA, DIRECTORY, PRINT, SHELL, }; // Function void enable(const int, const bool); void disable(const int, const bool); QAction * get(const int); void reset(); void toggle(const int, const bool, const bool = false); signals: void action(int); }; } // namespace UI #endif // VPZ_APKSTUDIO_UI_TOOLBAR_H
49a98afca57a8ff46eb3dba743ca3c0c641c3f6e
6bf780488942d14c601944ddac0cc39983ba3c67
/src/Basis/SpatialIntegrator/GaussLaguerreIntegrator.h
93ae9894a50eab234770e4a78b97498ea5ff2177
[]
no_license
sigvebs/StandardCI
cd7411ce22c296188b676e20f928fd813e7ce9da
9c3420d2349a9a3b7865d52a0fb56ff6d3fcf4f5
refs/heads/master
2016-08-03T15:53:31.638783
2013-01-28T11:43:46
2013-01-28T11:43:46
7,647,665
0
1
null
null
null
null
UTF-8
C++
false
false
650
h
GaussLaguerreIntegrator.h
/* * File: GaussLaguerreIntegrator.h * Author: sigve * * Created on January 9, 2013, 8:54 PM */ #ifndef GAUSSLAGUERREINTEGRATOR_H #define GAUSSLAGUERREINTEGRATOR_H #include "SpatialIntegrator.h" class GaussLaguerreIntegrator: public SpatialIntegrator { public: GaussLaguerreIntegrator(Config *cfg, WaveFunction *wf); GaussLaguerreIntegrator(const GaussLaguerreIntegrator& orig); virtual ~GaussLaguerreIntegrator(); virtual double integrate(const vec &p, const vec &q, const vec &r, const vec &s); private: vec x_, y_; int N; double L; double *x; double *w1; }; #endif /* GAUSSLAGUERREINTEGRATOR_H */
f0de9bab6efe7f63ec4189826faa63b84e6e1f53
88b130d5ff52d96248d8b946cfb0faaadb731769
/vespalib/src/vespa/vespalib/util/typify.h
3df59f488e511fc283d0542faef8b4e4ed299705
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
vespa-engine/vespa
b8cfe266de7f9a9be6f2557c55bef52c3a9d7cdb
1f8213997718c25942c38402202ae9e51572d89f
refs/heads/master
2023-08-16T21:01:12.296208
2023-08-16T17:03:08
2023-08-16T17:03:08
60,377,070
4,889
619
Apache-2.0
2023-09-14T21:02:11
2016-06-03T20:54:20
Java
UTF-8
C++
false
false
4,301
h
typify.h
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include "traits.h" #include <cstddef> #include <utility> namespace vespalib { //----------------------------------------------------------------------------- /** * Typification result for values resolving into actual types. Using * this exact template is not required, but the result type must have * the name 'type' for the auto-unwrapping performed by typify_invoke * to work. **/ template <typename T> struct TypifyResultType { using type = T; }; /** * Typification result for values resolving into non-types. Using this * exact template is not required, but is supplied for * convenience. The resolved compile-time value should be called * 'value' for consistency across typifiers. **/ template <typename T, T VALUE> struct TypifyResultValue { static constexpr T value = VALUE; }; /** * Typification result for values resolving into simple templates * (templated on one type). Using this exact template is not required, * but is supplied for convenience and as example. The resolved * template should be called 'templ' for consistency across typifiers. **/ template <template<typename> typename TT> struct TypifyResultSimpleTemplate { template <typename T> using templ = TT<T>; }; /** * A Typifier is able to take a run-time value and resolve it into a * type, non-type constant value or a template. The resolve result is * passed to the specified function in the form of a thin result * wrapper. **/ struct TypifyBool { template <bool VALUE> using Result = TypifyResultValue<bool, VALUE>; template <typename F> static decltype(auto) resolve(bool value, F &&f) { if (value) { return f(Result<true>()); } else { return f(Result<false>()); } } }; //----------------------------------------------------------------------------- /** * Template used to combine individual typifiers into a typifier able * to resolve multiple types. **/ template <typename ...Ts> struct TypifyValue : Ts... { using Ts::resolve...; }; //----------------------------------------------------------------------------- template <size_t N, typename Typifier, typename Target, typename ...Rs> struct TypifyInvokeImpl { static decltype(auto) select() { static_assert(sizeof...(Rs) == N); return Target::template invoke<Rs...>(); } template <typename T, typename ...Args> static decltype(auto) select(T &&value, Args &&...args) { if constexpr (N == sizeof...(Rs)) { return Target::template invoke<Rs...>(std::forward<T>(value), std::forward<Args>(args)...); } else { return Typifier::resolve(value, [&](auto t)->decltype(auto) { using X = decltype(t); if constexpr (has_type_type<X>) { return TypifyInvokeImpl<N, Typifier, Target, Rs..., typename X::type>::select(std::forward<Args>(args)...); } else { return TypifyInvokeImpl<N, Typifier, Target, Rs..., X>::select(std::forward<Args>(args)...); } }); } } }; /** * Typify the N first parameters using 'Typifier' (typically an * instantiation of the TypifyValue template) and forward the * remaining parameters to the Target::invoke template function with * the typification results from the N first parameters as template * parameters. Note that typification results that are types are * unwrapped before being used as template parameters while * typification results that are non-types or templates are kept in * their wrappers when passed as template parameters. Please refer to * the unit test for examples. **/ template <size_t N, typename Typifier, typename Target, typename ...Args> decltype(auto) typify_invoke(Args && ...args) { static_assert(N > 0); return TypifyInvokeImpl<N,Typifier,Target>::select(std::forward<Args>(args)...); } //----------------------------------------------------------------------------- }
1552b2001c91ad71caada8d36e622517919072dd
d203c273c79cc3e728003f61988c3e116ba6d044
/Binary Tree - Max num formed from root to Leaf.cpp
2c9164dc2cf31ed4c495090e2a25284063315847
[]
no_license
Pulkit1080/Imp-DS-ALGO-Ques
84299f2d1188d44e6a146304aebdb336ca6b0b53
ec6574f8846d5c3d8d2b9d8818f1d09bfe215478
refs/heads/main
2023-01-13T06:29:20.052430
2020-11-19T07:59:19
2020-11-19T07:59:19
313,989,677
0
0
null
null
null
null
UTF-8
C++
false
false
2,211
cpp
Binary Tree - Max num formed from root to Leaf.cpp
#include<bits/stdc++.h> using namespace std; class node { public: int data; node*left; node*right; node(int d) { data = d; left = right = nullptr; } }; node*buildTree() { int d; cin>>d; if(d == -1) return nullptr; node*root = new node(d); root->left = buildTree(); root->right = buildTree(); return root; } void bfs(node*root) { if(root == nullptr) return; queue<node*>q; q.push(root); q.push(nullptr); while(!q.empty()) { node*f = q.front(); q.pop(); if(f == nullptr) { cout<<endl; if(!q.empty()) q.push(nullptr); else break; } else { cout<<f->data<<" "; if(f->left) q.push(f->left); if(f->right) q.push(f->right); } } } int max_num_in_nodes_1(node* root, int sum) { if(root == nullptr) return 0; if(root->left == nullptr && root->right == nullptr) return sum * 10 + root->data; return max(max_num_in_nodes_1(root->left, sum*10 + root->data), max_num_in_nodes_1(root->right, sum*10 + root->data)); } class Pair { public: int data; int height; }; Pair max_num_in_nodes_2(node* root) { Pair p; if(root == nullptr) { p.data = p.height = 0; return p; } else if(root->left == nullptr && root->right == nullptr) { p.data = root->data; p.height = 1; return p; } Pair left = max_num_in_nodes_2(root->left); Pair right = max_num_in_nodes_2(root->right); p.height = max(left.height, right.height) + 1; p.data = (root->data * pow(10, p.height - 1) ) + max(left.data, right.data); return p; } int main() { node*root = buildTree(); //bfs(root); cout<<max_num_in_nodes_1(root, 0); cout<<endl; cout<<max_num_in_nodes_2(root).data; } /* 1 2 4 -1 -1 5 -1 -1 3 6 -1 8 -1 -1 7 -1 9 -1 -1 3 4 -1 6 -1 -1 5 1 -1 -1 -1 8 10 1 -1 -1 6 9 -1 -1 7 -1 -1 3 -1 14 13 -1 -1 -1 */
225d862c5bd81908a1e1cccd3111ca6527a88284
6fee5fd1b5412e65a3a6c4df3edfa608c885f11b
/Cpp/12289 one two three.cpp
73ba56c7d15902eaebbc262eeaece70ef94b5802
[]
no_license
PrinceCuet77/UVa
d47f000ae6c05465b5582c77626a7d9f2942eb71
d45e0d895bf56696d5bb0c331a517249b7ba6ef1
refs/heads/master
2020-12-15T00:39:33.049648
2020-05-31T07:52:21
2020-05-31T07:52:21
234,930,506
0
0
null
null
null
null
UTF-8
C++
false
false
501
cpp
12289 one two three.cpp
#include<iostream> #include<string.h> using namespace std; int main() { int test,len; char letter[15]; cin>>test; while(test--){ cin>>letter; len=strlen(letter); if(len==5) cout<<"3"<<endl; else{ if((letter[0]=='o' && letter[2]=='e') || (letter[0]=='o' && letter[1]=='n') || (letter[1]=='n' && letter[2]=='e')) cout<<"1"<<endl; else cout<<"2"<<endl; } } return 0; }
caba98209b6c991af4c7bf03e921b20e0fb5f696
b603a14c383ad30eab1d6db79db7f333b3b9d839
/src/Antonova/Task5/Plane.h
f3b515c6d0881a944ddcffe92969687e0f468d85
[ "MIT" ]
permissive
sadads1337/fit-gl
37d66fff2c44664e67b8b43061f48dc18deace2e
88d9ae1f1935301d71ae6e090aff24e6829a7580
refs/heads/master
2023-05-03T17:23:25.170430
2021-05-23T18:26:56
2021-05-24T04:59:44
334,793,424
2
9
MIT
2021-05-24T06:55:24
2021-02-01T01:03:08
C++
UTF-8
C++
false
false
294
h
Plane.h
#pragma once #include "Hittable.h" class Plane : public Hittable { public: Plane(QVector3D p, QVector3D n) : position(p), normal(n){}; virtual ~Plane() = default; virtual std::optional<Hit> intersect(const Ray &ray) const override; public: QVector3D position; QVector3D normal; };
e08ad27e5f20e54dcaec56879bb344fdddc4c4d2
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/multimedia/directx/dplay/dplay8/sp/wsock/unk.cpp
03c083f106b748c8a4323a01a6b17066ce17e818
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
20,579
cpp
unk.cpp
/*========================================================================== * * Copyright (C) 1998-2002 Microsoft Corporation. All Rights Reserved. * * File: Unk.cpp * Content: IUnknown implementation * History: * Date By Reason * ==== == ====== * 08/06/00 RichGr IA64: Use %p format specifier in DPFs for 32/64-bit pointers and handles. ***************************************************************************/ #include "dnwsocki.h" #ifndef DPNBUILD_NOIPX #define DPN_REG_LOCAL_WSOCK_IPX_ROOT L"\\DPNSPWinsockIPX" #endif // ! DPNBUILD_NOIPX #ifndef DPNBUILD_NOIPV6 #define DPN_REG_LOCAL_WSOCK_IPV6_ROOT L"\\DPNSPWinsockIPv6" #endif // ! DPNBUILD_NOIPV6 #define DPN_REG_LOCAL_WSOCK_TCPIP_ROOT L"\\DPNSPWinsockTCP" #if ((! defined(WINCE)) && (! defined(_XBOX))) #define MAX_RESOURCE_STRING_LENGTH _MAX_PATH HRESULT LoadAndAllocString( UINT uiResourceID, wchar_t **lpswzString ); #endif // ! WINCE and ! _XBOX #undef DPF_MODNAME #define DPF_MODNAME "DNWsockInit" BOOL DNWsockInit(HANDLE hModule) { DNASSERT( hModule != NULL ); #ifdef _XBOX XDP8STARTUP_PARAMS * pStartupParams; XNetStartupParams xnsp; int iResult; // // The instance handle is actually a pointer to the startup parameters. // pStartupParams = (XDP8STARTUP_PARAMS*) hModule; // // Initialize the Xbox networking layer, unless we were forbidden. // if (! (pStartupParams->dwFlags & XDP8STARTUP_BYPASSXNETSTARTUP)) { memset(&xnsp, 0, sizeof(xnsp)); xnsp.cfgSizeOfStruct = sizeof(xnsp); #pragma TODO(vanceo, "Does this actually do anything?") if (pStartupParams->dwFlags & XDP8STARTUP_BYPASSSECURITY) { xnsp.cfgFlags |= XNET_STARTUP_BYPASS_SECURITY; } DPFX(DPFPREP, 1, "Initializing Xbox networking layer."); iResult = XNetStartup(&xnsp); if (iResult != 0) { DPFX(DPFPREP, 0, "Couldn't start XNet (err = %i)!", iResult); return FALSE; } g_fStartedXNet = TRUE; } #else // ! _XBOX #ifndef WINCE DNASSERT( g_hDLLInstance == NULL ); g_hDLLInstance = (HINSTANCE) hModule; #endif // ! WINCE #endif // ! _XBOX // // attempt to initialize process-global items // if ( InitProcessGlobals() == FALSE ) { DPFX(DPFPREP, 0, "Failed to initialize globals!" ); #ifdef _XBOX if (g_fStartedXNet) { XNetCleanup(); } #endif // _XBOX return FALSE; } #ifdef DPNBUILD_LIBINTERFACE // // Attempt to load Winsock. // if ( LoadWinsock() == FALSE ) { DPFX(DPFPREP, 0, "Failed to load winsock!" ); DeinitProcessGlobals(); #ifdef _XBOX if (g_fStartedXNet) { XNetCleanup(); } #endif // _XBOX return FALSE; } #endif // DPNBUILD_LIBINTERFACE #ifdef DPNBUILD_PREALLOCATEDMEMORYMODEL // // Pre-allocate a threadpool object. // if ( g_ThreadPoolPool.Preallocate( 1, NULL ) < 1 ) { DPFX(DPFPREP, 0, "Failed to preallocate a threadpool object!" ); #ifdef DPNBUILD_LIBINTERFACE UnloadWinsock(); #endif // DPNBUILD_LIBINTERFACE DeinitProcessGlobals(); #ifdef _XBOX if (g_fStartedXNet) { XNetCleanup(); } #endif // _XBOX return FALSE; } #endif // DPNBUILD_PREALLOCATEDMEMORYMODEL return TRUE; } #undef DPF_MODNAME #define DPF_MODNAME "DNWsockDeInit" void DNWsockDeInit() { DPFX(DPFPREP, 5, "Deinitializing Wsock SP"); #if ((! defined(WINCE)) && (! defined(_XBOX))) DNASSERT( g_hDLLInstance != NULL ); g_hDLLInstance = NULL; #endif // ! WINCE and ! _XBOX #ifdef DPNBUILD_LIBINTERFACE // // Unload Winsock. // UnloadWinsock(); #endif // DPNBUILD_LIBINTERFACE DeinitProcessGlobals(); #ifdef _XBOX // // Clean up the Xbox networking layer if we started it. // if (g_fStartedXNet) { DPFX(DPFPREP, 1, "Cleaning up Xbox networking layer."); #ifdef DBG DNASSERT(XNetCleanup() == 0); #else // ! DBG XNetCleanup(); #endif // ! DBG g_fStartedXNet = FALSE; } #endif // _XBOX } #ifndef DPNBUILD_NOCOMREGISTER #undef DPF_MODNAME #define DPF_MODNAME "DNWsockRegister" BOOL DNWsockRegister(LPCWSTR wszDLLName) { HRESULT hr = S_OK; BOOL fReturn = TRUE; CRegistry creg; #if ((! defined(WINCE)) && (! defined(_XBOX))) WCHAR *wszFriendlyName = NULL; #endif // ! WINCE and ! _XBOX #ifndef DPNBUILD_NOIPX if( !CRegistry::Register( L"DirectPlay8SPWSock.IPX.1", L"DirectPlay8 WSock IPX Provider Object", wszDLLName, &CLSID_DP8SP_IPX, L"DirectPlay8SPWSock.IPX") ) { DPFERR( "Could not register dp8 IPX object" ); fReturn = FALSE; } #endif // ! DPNBUILD_NOIPX if( !CRegistry::Register( L"DirectPlay8SPWSock.TCPIP.1", L"DirectPlay8 WSock TCPIP Provider Object", wszDLLName, &CLSID_DP8SP_TCPIP, L"DirectPlay8SPWSock.TCPIP") ) { DPFERR( "Could not register dp8 IP object" ); fReturn = FALSE; } #ifndef DPNBUILD_NOIPX if( !creg.Open( HKEY_LOCAL_MACHINE, DPN_REG_LOCAL_SP_SUBKEY DPN_REG_LOCAL_WSOCK_IPX_ROOT, FALSE, TRUE ) ) { DPFERR( "Cannot create IPX sub-area!" ); fReturn = FALSE; } else { #if ((! defined(WINCE)) && (! defined(_XBOX))) hr = LoadAndAllocString( IDS_FRIENDLYNAME_IPX, &wszFriendlyName ); if( FAILED( hr ) ) { DPFX(DPFPREP, 0, "Could not load IPX name! hr=0x%x", hr ); fReturn = FALSE; } else { // Load from resource file creg.WriteString( DPN_REG_KEYNAME_FRIENDLY_NAME, wszFriendlyName ); delete [] wszFriendlyName; creg.WriteGUID( DPN_REG_KEYNAME_GUID, CLSID_DP8SP_IPX ); } #else // ! WINCE and ! _XBOX // Don't use the resource, just do it directly creg.WriteString( DPN_REG_KEYNAME_FRIENDLY_NAME, L"DirectPlay8 IPX Service Provider" ); creg.WriteGUID( DPN_REG_KEYNAME_GUID, CLSID_DP8SP_IPX ); #endif // ! WINCE and ! _XBOX creg.Close(); } #endif // ! DPNBUILD_NOIPX if( !creg.Open( HKEY_LOCAL_MACHINE, DPN_REG_LOCAL_SP_SUBKEY DPN_REG_LOCAL_WSOCK_TCPIP_ROOT, FALSE, TRUE ) ) { DPFERR( "Cannot create TCPIP sub-area!" ); fReturn = FALSE; } else { #if ((! defined(WINCE)) && (! defined(_XBOX))) hr = LoadAndAllocString( IDS_FRIENDLYNAME_TCPIP, &wszFriendlyName ); if( FAILED( hr ) ) { DPFX(DPFPREP, 0, "Could not load IPX name! hr=0x%x", hr ); fReturn = FALSE; } else { // Load from resource file creg.WriteString( DPN_REG_KEYNAME_FRIENDLY_NAME, wszFriendlyName ); delete [] wszFriendlyName; creg.WriteGUID( DPN_REG_KEYNAME_GUID, CLSID_DP8SP_TCPIP ); } #else // ! WINCE and ! _XBOX // Don't use the resource, just do it directly creg.WriteString( DPN_REG_KEYNAME_FRIENDLY_NAME, L"DirectPlay8 TCP/IP Service Provider" ); creg.WriteGUID( DPN_REG_KEYNAME_GUID, CLSID_DP8SP_TCPIP ); #endif // ! WINCE and ! _XBOX creg.Close(); } return fReturn; } #undef DPF_MODNAME #define DPF_MODNAME "DNWsockUnRegister" BOOL DNWsockUnRegister() { HRESULT hr = S_OK; BOOL fReturn = TRUE; #ifndef DPNBUILD_NOIPX if( !CRegistry::UnRegister(&CLSID_DP8SP_IPX) ) { DPFX(DPFPREP, 0, "Failed to unregister IPX object" ); fReturn = FALSE; } #endif // ! DPNBUILD_NOIPX if( !CRegistry::UnRegister(&CLSID_DP8SP_TCPIP) ) { DPFX(DPFPREP, 0, "Failed to unregister IP object" ); fReturn = FALSE; } CRegistry creg; if( !creg.Open( HKEY_LOCAL_MACHINE, DPN_REG_LOCAL_SP_SUBKEY, FALSE, TRUE ) ) { DPFERR( "Cannot remove app, does not exist" ); } else { #ifndef DPNBUILD_NOIPX if( !creg.DeleteSubKey( &(DPN_REG_LOCAL_WSOCK_IPX_ROOT)[1] ) ) { DPFERR( "Cannot remove IPX sub-key, could have elements" ); } #endif // ! DPNBUILD_NOIPX #pragma TODO(vanceo, "Uncomment IPv6 when ready") /* #ifndef DPNBUILD_NOIPV6 if( !creg.DeleteSubKey( &(DPN_REG_LOCAL_WSOCK_IPV6_ROOT)[1] ) ) { DPFERR( "Cannot remove IPv6 sub-key, could have elements" ); } #endif // ! DPNBUILD_NOIPV6 */ if( !creg.DeleteSubKey( &(DPN_REG_LOCAL_WSOCK_TCPIP_ROOT)[1] ) ) { DPFERR( "Cannot remove TCPIP sub-key, could have elements" ); } } return fReturn; } #endif // ! DPNBUILD_NOCOMREGISTER #ifndef DPNBUILD_LIBINTERFACE #undef DPF_MODNAME #define DPF_MODNAME "DNWsockGetRemainingObjectCount" DWORD DNWsockGetRemainingObjectCount() { return g_lOutstandingInterfaceCount; } #endif // ! DPNBUILD_LIBINTERFACE //********************************************************************** // Constant definitions //********************************************************************** #ifdef __MWERKS__ #define EXP __declspec(dllexport) #else #define EXP #endif // __MWERKS__ //********************************************************************** // Macro definitions //********************************************************************** //********************************************************************** // Structure definitions //********************************************************************** //********************************************************************** // Variable definitions //********************************************************************** //********************************************************************** // Function prototypes //********************************************************************** STDMETHODIMP DNSP_QueryInterface( IDP8ServiceProvider *lpDNSP, REFIID riid, LPVOID * ppvObj); #define NOTSUPPORTED(parm) (HRESULT (__stdcall *) (struct IDP8ServiceProvider *, parm)) DNSP_NotSupported //********************************************************************** // Function definitions //********************************************************************** // these are the vtables for the various WSock service providers One or the // other is used depending on what is passed to DoCreateInstance. #ifndef DPNBUILD_NOIPX static IDP8ServiceProviderVtbl ipxInterface = { DNSP_QueryInterface, DNSP_AddRef, DNSP_Release, DNSP_Initialize, DNSP_Close, DNSP_Connect, DNSP_Disconnect, DNSP_Listen, DNSP_SendData, DNSP_EnumQuery, DNSP_EnumRespond, DNSP_CancelCommand, NOTSUPPORTED(PSPENUMMULTICASTSCOPESDATA), // EnumMulticastScopes NOTSUPPORTED(PSPSHAREENDPOINTINFODATA), // ShareEndpointInfo NOTSUPPORTED(PSPGETENDPOINTBYADDRESSDATA), // GetEndpointByAddress DNSP_Update, DNSP_GetCaps, DNSP_SetCaps, DNSP_ReturnReceiveBuffers, DNSP_GetAddressInfo, #ifdef DPNBUILD_LIBINTERFACE NOTSUPPORTED(PSPISAPPLICATIONSUPPORTEDDATA), // IsApplicationSupported #else // ! DPNBUILD_LIBINTERFACE DNSP_IsApplicationSupported, #endif // ! DPNBUILD_LIBINTERFACE #ifdef DPNBUILD_ONLYONEADAPTER NOTSUPPORTED(PSPENUMADAPTERSDATA), // EnumAdapters #else // ! DPNBUILD_ONLYONEADAPTER DNSP_EnumAdapters, #endif // ! DPNBUILD_ONLYONEADAPTER #ifdef DPNBUILD_SINGLEPROCESS NOTSUPPORTED(PSPPROXYENUMQUERYDATA), // ProxyEnumQuery #else // ! DPNBUILD_SINGLEPROCESS DNSP_ProxyEnumQuery #endif // ! DPNBUILD_SINGLEPROCESS }; #endif // DPNBUILD_NOIPX #ifndef DPNBUILD_NOIPV6 static IDP8ServiceProviderVtbl ipv6Interface = { DNSP_QueryInterface, DNSP_AddRef, DNSP_Release, DNSP_Initialize, DNSP_Close, DNSP_Connect, DNSP_Disconnect, DNSP_Listen, DNSP_SendData, DNSP_EnumQuery, DNSP_EnumRespond, DNSP_CancelCommand, #ifdef DPNBUILD_NOMULTICAST NOTSUPPORTED(PSPENUMMULTICASTSCOPESDATA), // EnumMulticastScopes NOTSUPPORTED(PSPSHAREENDPOINTINFODATA), // ShareEndpointInfo NOTSUPPORTED(PSPGETENDPOINTBYADDRESSDATA), // GetEndpointByAddress #else // ! DPNBUILD_NOMULTICAST DNSP_EnumMulticastScopes, DNSP_ShareEndpointInfo, DNSP_GetEndpointByAddress, #endif // ! DPNBUILD_NOMULTICAST DNSP_Update, DNSP_GetCaps, DNSP_SetCaps, DNSP_ReturnReceiveBuffers, DNSP_GetAddressInfo, #ifdef DPNBUILD_LIBINTERFACE NOTSUPPORTED(PSPISAPPLICATIONSUPPORTEDDATA), // IsApplicationSupported #else // ! DPNBUILD_LIBINTERFACE DNSP_IsApplicationSupported, #endif // ! DPNBUILD_LIBINTERFACE #ifdef DPNBUILD_ONLYONEADAPTER NOTSUPPORTED(PSPENUMADAPTERSDATA), // EnumAdapters #else // ! DPNBUILD_ONLYONEADAPTER DNSP_EnumAdapters, #endif // ! DPNBUILD_ONLYONEADAPTER #ifdef DPNBUILD_SINGLEPROCESS NOTSUPPORTED(PSPPROXYENUMQUERYDATA), // ProxyEnumQuery #else // ! DPNBUILD_SINGLEPROCESS DNSP_ProxyEnumQuery #endif // ! DPNBUILD_SINGLEPROCESS }; #endif // DPNBUILD_NOIPV6 static IDP8ServiceProviderVtbl ipInterface = { DNSP_QueryInterface, DNSP_AddRef, DNSP_Release, DNSP_Initialize, DNSP_Close, DNSP_Connect, DNSP_Disconnect, DNSP_Listen, DNSP_SendData, DNSP_EnumQuery, DNSP_EnumRespond, DNSP_CancelCommand, #ifdef DPNBUILD_NOMULTICAST NOTSUPPORTED(PSPENUMMULTICASTSCOPESDATA), // EnumMulticastScopes NOTSUPPORTED(PSPSHAREENDPOINTINFODATA), // ShareEndpointInfo NOTSUPPORTED(PSPGETENDPOINTBYADDRESSDATA), // GetEndpointByAddress #else // ! DPNBUILD_NOMULTICAST DNSP_EnumMulticastScopes, DNSP_ShareEndpointInfo, DNSP_GetEndpointByAddress, #endif // ! DPNBUILD_NOMULTICAST DNSP_Update, DNSP_GetCaps, DNSP_SetCaps, DNSP_ReturnReceiveBuffers, DNSP_GetAddressInfo, #ifdef DPNBUILD_LIBINTERFACE NOTSUPPORTED(PSPISAPPLICATIONSUPPORTEDDATA), // IsApplicationSupported #else // ! DPNBUILD_LIBINTERFACE DNSP_IsApplicationSupported, #endif // ! DPNBUILD_LIBINTERFACE #ifdef DPNBUILD_ONLYONEADAPTER NOTSUPPORTED(PSPENUMADAPTERSDATA), // EnumAdapters #else // ! DPNBUILD_ONLYONEADAPTER DNSP_EnumAdapters, #endif // ! DPNBUILD_ONLYONEADAPTER #ifdef DPNBUILD_SINGLEPROCESS NOTSUPPORTED(PSPPROXYENUMQUERYDATA), // ProxyEnumQuery #else // ! DPNBUILD_SINGLEPROCESS DNSP_ProxyEnumQuery #endif // ! DPNBUILD_SINGLEPROCESS }; //********************************************************************** // ------------------------------ // DNSP_QueryInterface - query for interface // // Entry: Pointer to current interface // GUID of desired interface // Pointer to pointer to new interface // // Exit: Error code // ------------------------------ #undef DPF_MODNAME #define DPF_MODNAME "DNSP_QueryInterface" STDMETHODIMP DNSP_QueryInterface( IDP8ServiceProvider *lpDNSP, REFIID riid, LPVOID * ppvObj) { HRESULT hr = S_OK; #ifndef DPNBUILD_LIBINTERFACE // hmmm, switch would be cleaner... if ((! IsEqualIID(riid, IID_IUnknown)) && (! IsEqualIID(riid, IID_IDP8ServiceProvider))) { *ppvObj = NULL; hr = E_NOINTERFACE; } else #endif // ! DPNBUILD_LIBINTERFACE { #ifdef DPNBUILD_LIBINTERFACE DNASSERT(! "Querying SP interface when using DPNBUILD_LIBINTERFACE!"); #endif // DPNBUILD_LIBINTERFACE *ppvObj = lpDNSP; DNSP_AddRef(lpDNSP); } return hr; } //********************************************************************** #ifndef DPNBUILD_NOIPX //********************************************************************** // ------------------------------ // CreateIPXInterface - create an IPX interface // // Entry: Pointer to pointer to SP interface // Pointer to pointer to associated SP data // // Exit: Error code // ------------------------------ #undef DPF_MODNAME #define DPF_MODNAME "CreateIPXInterface" #ifdef DPNBUILD_PREALLOCATEDMEMORYMODEL HRESULT CreateIPXInterface( const XDP8CREATE_PARAMS * const pDP8CreateParams, IDP8ServiceProvider **const ppiDP8SP ) #else // ! DPNBUILD_PREALLOCATEDMEMORYMODEL HRESULT CreateIPXInterface( IDP8ServiceProvider **const ppiDP8SP ) #endif // ! DPNBUILD_PREALLOCATEDMEMORYMODEL { HRESULT hr; CSPData *pSPData; DNASSERT( ppiDP8SP != NULL ); // // initialize // hr = DPN_OK; pSPData = NULL; *ppiDP8SP = NULL; // // create main data class // hr = CreateSPData( &pSPData, AF_IPX, #ifdef DPNBUILD_PREALLOCATEDMEMORYMODEL pDP8CreateParams, #endif // DPNBUILD_PREALLOCATEDMEMORYMODEL &ipxInterface ); if ( hr != DPN_OK ) { DNASSERT( pSPData == NULL ); DPFX(DPFPREP, 0, "Problem creating SPData!" ); DisplayDNError( 0, hr ); goto Failure; } DNASSERT( pSPData != NULL ); *ppiDP8SP = pSPData->COMInterface(); Exit: return hr; Failure: if ( pSPData != NULL ) { pSPData->DecRef(); pSPData = NULL; } goto Exit; } //********************************************************************** #endif // ! DPNBUILD_NOIPX //********************************************************************** // ------------------------------ // CreateIPInterface - create an IP interface // // Entry: Pointer to pointer to SP interface // // Exit: Error code // ------------------------------ #undef DPF_MODNAME #define DPF_MODNAME "CreateIPInterface" #ifdef DPNBUILD_PREALLOCATEDMEMORYMODEL HRESULT CreateIPInterface( const XDP8CREATE_PARAMS * const pDP8CreateParams, IDP8ServiceProvider **const ppiDP8SP ) #else // ! DPNBUILD_PREALLOCATEDMEMORYMODEL HRESULT CreateIPInterface( IDP8ServiceProvider **const ppiDP8SP ) #endif // ! DPNBUILD_PREALLOCATEDMEMORYMODEL { HRESULT hr; CSPData *pSPData; DNASSERT( ppiDP8SP != NULL ); // // initialize // hr = DPN_OK; pSPData = NULL; *ppiDP8SP = NULL; // // create main data class // hr = CreateSPData( &pSPData, #if ((! defined(DPNBUILD_NOIPX)) || (! defined(DPNBUILD_NOIPV6))) AF_INET, #endif // ! DPNBUILD_NOIPX or ! DPNBUILD_NOIPV6 #ifdef DPNBUILD_PREALLOCATEDMEMORYMODEL pDP8CreateParams, #endif // DPNBUILD_PREALLOCATEDMEMORYMODEL &ipInterface ); if ( hr != DPN_OK ) { DNASSERT( pSPData == NULL ); DPFX(DPFPREP, 0, "Problem creating SPData!" ); DisplayDNError( 0, hr ); goto Failure; } DNASSERT( pSPData != NULL ); *ppiDP8SP = pSPData->COMInterface(); Exit: return hr; Failure: if ( pSPData != NULL ) { pSPData->DecRef(); pSPData = NULL; } goto Exit; } //********************************************************************** #ifndef DPNBUILD_LIBINTERFACE //********************************************************************** // ------------------------------ // DoCreateInstance - create an instance of an interface // // Entry: Pointer to class factory // Pointer to unknown interface // Refernce of GUID of desired interface // Reference to another GUID? // Pointer to pointer to interface // // Exit: Error code // ------------------------------ #undef DPF_MODNAME #define DPF_MODNAME "DoCreateInstance" HRESULT DoCreateInstance( LPCLASSFACTORY This, LPUNKNOWN pUnkOuter, REFCLSID rclsid, REFIID riid, LPVOID *ppvObj ) { HRESULT hr; DNASSERT( ppvObj != NULL ); // // initialize // *ppvObj = NULL; // // we can either create an IPX instance or an IP instance // if (IsEqualCLSID(rclsid, CLSID_DP8SP_TCPIP)) { hr = CreateIPInterface( reinterpret_cast<IDP8ServiceProvider**>( ppvObj ) ); } #ifndef DPNBUILD_NOIPX else if (IsEqualCLSID(rclsid, CLSID_DP8SP_IPX)) { hr = CreateIPXInterface( reinterpret_cast<IDP8ServiceProvider**>( ppvObj ) ); } #endif // ! DPNBUILD_NOIPX else { // this shouldn't happen if they called IClassFactory::CreateObject correctly DPFX(DPFPREP, 0, "Got unexpected CLSID!"); hr = E_UNEXPECTED; } return hr; } //********************************************************************** #endif // ! DPNBUILD_LIBINTERFACE #if ((! defined(WINCE)) && (! defined(_XBOX))) #define MAX_RESOURCE_STRING_LENGTH _MAX_PATH #undef DPF_MODNAME #define DPF_MODNAME "LoadAndAllocString" HRESULT LoadAndAllocString( UINT uiResourceID, wchar_t **lpswzString ) { int length; HRESULT hr; TCHAR szTmpBuffer[MAX_RESOURCE_STRING_LENGTH]; length = LoadString( g_hDLLInstance, uiResourceID, szTmpBuffer, MAX_RESOURCE_STRING_LENGTH ); if( length == 0 ) { hr = GetLastError(); DPFX(DPFPREP, 0, "Unable to load resource ID %d error 0x%x", uiResourceID, hr ); *lpswzString = NULL; return DPNERR_GENERIC; } else { *lpswzString = new wchar_t[length+1]; if( *lpswzString == NULL ) { DPFX(DPFPREP, 0, "Alloc failure" ); return DPNERR_OUTOFMEMORY; } #ifdef UNICODE wcscpy( *lpswzString, szTmpBuffer ); #else // !UNICODE if( STR_jkAnsiToWide( *lpswzString, szTmpBuffer, length+1 ) != DPN_OK ) { hr = GetLastError(); delete[] *lpswzString; *lpswzString = NULL; DPFX(DPFPREP, 0, "Unable to upconvert from ansi to unicode hr=0x%x", hr ); return DPNERR_GENERIC; } #endif // !UNICODE return DPN_OK; } } #endif // !WINCE and ! _XBOX
c095c9faf3ae31a516598a65ec226f667981a4b9
4b53076dd75ff8bed7b8cafd64a2add306a00761
/src/client.hpp
82502b23048697a83cc8312433a7fb4a89f6095b
[]
no_license
nesro/NCursesGomoku
c184d366c53e2d3d582ed8d597872437aeb40aa4
d37c1252a44189b488600c4d01d4bb6af8a04e78
refs/heads/master
2021-01-10T07:06:45.845198
2015-03-23T14:42:30
2015-03-23T14:42:30
8,541,243
2
0
null
null
null
null
UTF-8
C++
false
false
919
hpp
client.hpp
/** * @file client.hpp * @brief Header file for network opponent as client. * * @author Tomas Nesrovnal nesro@nesro.cz * @version 1.0 */ #include "local.hpp" #include "board.hpp" #include "network.hpp" #include "game.hpp" /******************************************************************************/ #ifndef __CLIENT_HPP__ /** * For safety about multiple include */ #define __CLIENT_HPP__ /** * @brief Network opponent as client. */ class CClient : public CPlayer, public CNetwork { public: /** * Initialize a client netwok conection * @param board Game board * @param mark Player mark * @param game Game object */ CClient(CBoard * board, char mark, CGame * game); /** * Close the network connection. */ ~CClient(void); /** * Wait for move of a network opponent. */ virtual void nextMove(void); }; #endif /* __CLIENT_HPP__ */
ecd7668ba75329a7b451dcc7cbfb7dae09c4dd27
d899d124b02eed2c7f1786805286113ec6960c24
/Hmwk/Assignment 4/Ch13 pg1/Date.cpp
570d1d051c2a4c4fb009579c701f84b0a376574b
[]
no_license
AyinDJ/He_Xiaojun_CSC17A_48096
cd30267f6f9e836b886515b844779755ee1774b8
d29cafa946a37d40e62e233f5bf7f0fcfca0b143
refs/heads/master
2020-04-11T00:43:04.782496
2016-12-09T03:04:31
2016-12-09T03:04:31
68,043,238
0
0
null
null
null
null
UTF-8
C++
false
false
1,572
cpp
Date.cpp
/* * File: Date.cpp * Author: Jimmy * * Created on November 17, 2016, 7:30 PM */ #include "Date.h" #include <iostream> #include <string> using namespace std; Date::Date(int year, int month, int day) { this->year=year; this->month=month; this->day=day; } void Date::setDay(int day) { bool invalid=false; int dyInMth[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; if(day<1||day>dyInMth[month]) invalid=true; if(month==2&&day==29&&(year%400==0||(year%4==0&&year%100!=0))) invalid=false; if(!invalid) this->day=day; else cout<<"Invalid input for day"<<endl; } void Date::setMonth(int month) { if(month>0&&month<=12) this->month=month; else cout<<"Invalid input for month"<<endl; } void Date::setYear(int year) { this->year=year; } void Date::pntDate() { string months=""; switch(month) { case 1: months="January"; break; case 2: months="February"; break; case 3: months="March"; break; case 4: months="April"; break; case 5: months="May"; break; case 6: months="June"; break; case 7: months="July"; break; case 8: months="August"; break; case 9: months="September"; break; case 10: months="October"; break; case 11: months="November"; break; case 12: months="December"; break; default:; } cout<<endl; cout<<month<<"/"<<day<<"/"<<year<<endl; cout<<month<<" "<<day<<", "<<year<<endl; cout<<day<<" "<<month<<" "<<year<<endl; }
a9b75651a8ea986089bc1049c851c052fe2df6b7
efb16fa1079141fad502b532844237a8f75d8229
/MST/generateRandomGraph.cxx
7014cbb4911f31289bb76dbbfe9f0437cdf86465
[]
no_license
demikandr/homework
77f3f42ed671ab30d44223a7aac8ca2e894e39b0
155efdc65dea7c34e1aa8c5c864b6a4ecdee79c2
refs/heads/master
2021-01-10T11:55:58.135538
2016-02-25T20:07:18
2016-02-25T20:07:18
52,553,396
0
0
null
null
null
null
UTF-8
C++
false
false
2,308
cxx
generateRandomGraph.cxx
#include <vector> #include <iostream> #include <random> #include <set> typedef std::mt19937 RNG; RNG rng; std::uniform_int_distribution<int> uint_dist; std::uniform_real_distribution<long double> ureal_dist(0.0, 1.0); int countOfVerticles, counter=0; class DisjointSet { public: std::vector<int> parent, rank; DisjointSet(size_t sizeOfSource): parent(sizeOfSource), rank(sizeOfSource) { for ( size_t i = 0; i < sizeOfSource; ++i) { parent[i] = i; } } int getRoot(int element) { if (parent[element] == element) { return element; } return element = getRoot(parent[element]); } bool isEqual(int first, int second) { return (getRoot(first) == getRoot(second)); } void unionSets(int first, int second) { first = getRoot(first); second = getRoot(second); if (first == second) { return; } counter++; if (rank[first] == rank[second]) { ++rank[second]; } if (rank[first] > rank[second]) { parent[second] = first; } else { parent[first] = second; } } }; struct Edge { int from; int to; long double weight; bool operator<(Edge other) const { return (std::make_pair(from, to) < std::make_pair(other.from, other.to)) ; } }; std::set < Edge> edges; Edge getRandomEdge(int countOfVerticles) { Edge edge; edge.from=uint_dist(rng)%countOfVerticles; edge.to=uint_dist(rng)%countOfVerticles; edge.weight=ureal_dist(rng); return edge; } bool notExists(Edge edge) { return (edges.find(edge)==edges.end()); } void add(Edge edge) { edges.insert(edge); std::cout << edge.from << ' ' << edge.to << ' ' << edge.weight << std::endl; } int main(int argc, char **argv) { int percentOfEdges, countOfEdges; rng.seed(((argc==2)?std::atoi(argv[1]):0)); std::cin >> countOfVerticles >> percentOfEdges; countOfEdges=countOfVerticles*(countOfVerticles-1)*percentOfEdges/200; std::cout << countOfVerticles << std::endl; DisjointSet verticles(countOfVerticles); Edge newEdge; for (int i = 0; i < countOfEdges || counter< countOfVerticles-1; ++i) { while(1) { newEdge=getRandomEdge(countOfVerticles); if (notExists(newEdge)) { add(newEdge); verticles.unionSets(newEdge.from, newEdge.to); break; } } } return 0; }
6e83a844876cde71a0ffef56c7ebd55f2849e0df
4867181d10768e7dc3f6b82716d04f0e4a5bcad7
/xReference.h
324d6d7d9e4a416bb4c770b7345dec2a6f978386
[]
no_license
AllanCh/MeshMem
e3d4d3bac265284857fcbd4dbcfacbbdc2d2591b
06fe8823ad81ccb93c5134e4da339ca400594eef
refs/heads/master
2020-09-11T11:45:11.287543
2016-10-08T00:12:35
2016-10-08T00:12:35
67,572,001
0
0
null
null
null
null
UTF-8
C++
false
false
1,028
h
xReference.h
// // Created by dilan on 11/09/16. // #ifndef MESH_MEM_XREFERENCE_H #define MESH_MEM_XREFERENCE_H #include <typeinfo> #include<iostream> #include<string> using namespace std; template <typename T> class xReference { private: T tipo; int Size; string datoalmacenado; public: string ID; xReference(string id, int size,T type){ ID=id; Size=size; tipo=type; } xReference(string id, int size, T type,string dato){ datoalmacenado=dato; ID=id; Size=size; } T getTipo(){ return this->tipo; } const char* getTypeName(){ return typeid(T).name(); } T& operator*(){ } bool operator==(xReference &D){ if(ID.compare(D.ID)==0){ return true; }else{ return false; } } bool operator!=(xReference &D){ if(ID.compare(D.ID)==0){ return false; }else{ return true; } } }; #endif //MESH_MEM_XREFERENCE_H
48cfaf6529cc8aa80679816389510bc1f72cc0e2
b93fecee400e9490aa742660f3fc6e32b2f1de47
/my_controllers/src/patrol2.cpp
9e32ba62a521390f3c2ac479ff6fffcd7011adaf
[ "MIT" ]
permissive
WardAlshalabi/DAS_UAV_Sim
a5e51ba1d53e7b872a6685499ad5f2fc8c2c2e43
fa223f5666da6d9d43d6df73ff449b6a2acf643a
refs/heads/master
2020-03-10T19:52:59.595634
2018-05-03T20:01:48
2018-05-03T20:01:48
129,557,869
1
0
null
null
null
null
UTF-8
C++
false
false
11,881
cpp
patrol2.cpp
#include <ros/ros.h> #include <nav_msgs/Odometry.h> #include <geometry_msgs/Twist.h> #include <geometry_msgs/Point.h> #include <tf/transform_datatypes.h> #include <tf/transform_broadcaster.h> #include <std_msgs/Int16MultiArray.h> #include <std_msgs/Float32.h> #include <std_msgs/Empty.h> #include <sensor_msgs/Range.h> #include <sensor_msgs/BatteryState.h> #include "Graduation_Trakya/graph.h" #include <ros/time.h> #include <std_msgs/Empty.h> #include "my_controllers/go2point.h" #include "my_controllers/goalReached.h" #include "my_controllers/start_landing.h" #include <cstdlib> #define GRAPH_DIMENSION 15 //remember to edit this number of you change the arena and the number of points #define num_of_uav 3 #define Battery_Low_Treshold 25 #define Battery_High_Treshold 90 //Global variables to access within the callbacks: int uav_id; //ros::Publisher *comm_pub_ptr; bool send_goal = true; bool example_publish = false; bool battery_low=false; bool UAV_sent2station=false; bool landing_started=false; int uav_targets[]={0,0,0}; //initial vertex of drones and targets of them int visit_counter[GRAPH_DIMENSION]={0}; //for each vertex count how many times has been visited while recieving communication float d; //the bigger number in the decision array float time_vertex[GRAPH_DIMENSION]={0}; //time at each vertex since last visiting int callback_counter=0; //Callback triggered everytime this robot reaches a goal (or aborts its goals): //void goalDoneCallback(const actionlib::SimpleClientGoalState &state, const move_base_msgs::MoveBaseResultConstPtr &result){ // // if(state.state_ == actionlib::SimpleClientGoalState::SUCCEEDED){ // ROS_INFO("Robot %d successfully reached goal.", robot_id); // send_goal = true; //go inside the loop again // example_publish = true; // }else{ // ROS_INFO("Robot %d could not reach goal. Gave up!", robot_id); // }} bool goalreached_callback(my_controllers::goalReached::Request &req, my_controllers::goalReached::Response &res) { send_goal = true; //go inside the loop again callback_counter++; if(callback_counter>1000){callback_counter=2;} res.received = true; ROS_INFO("The goal reached by the controller"); if(UAV_sent2station)landing_started=true; return true; } //Callback triggered everytime that this robot's goal becomes active: //void goalActiveCallback(){ // ROS_INFO("Drone %d goal is active.", uav_id); //} //Callback triggered continuously when a goal is given to the robot: //void goalFeedbackCallback(const move_base_msgs::MoveBaseFeedbackConstPtr &feedback){ // ROS_INFO("Robot %d is moving towards a goal.", robot_id); //} //Callback triggered everytime you receive a msg from another robot: void ReceiveCommunicationsCB(const std_msgs::Int16MultiArray::ConstPtr& msg) { //Remeber that the format of this message is an array of integers (Int16MultiArray): int other_uav_id = msg->data[0]; int other_uav_vertex = msg->data[1]; uav_targets[msg->data[0]]=msg->data[1]; visit_counter[msg->data[1]]++; //count that a specific vertex has been visited for once time_vertex[msg->data[1]]=ros::Time::now().toSec();//update the time of vertex //filter out your own messages: if(uav_id != other_uav_id){ // ROS_INFO("Drone %d received this message from Drone %d: [%d,%d]", uav_id, other_uav_id, msg->data[0], msg->data[1]); } } void battery_callback(const sensor_msgs::BatteryState::ConstPtr& msg) { //Remeber that the format of this message is an array of integers (Int16MultiArray): int Charge = msg->charge; if(battery_low) { if (Charge>Battery_High_Treshold) {battery_low=false;UAV_sent2station=false;} } else { if(Charge<Battery_Low_Treshold) battery_low=true; } } //A utility function for publishing a message in the "/communication" topic //void publish_message(int vertex){ //In this example we will publish an array of 2 integers like this: [robot_id, vertex] //feel free to modify this function to suit your needs (e.g. publish more information, etc.) // std_msgs::Int16MultiArray msg; // msg.data.clear(); // msg.data.push_back(uav_id); // msg.data.push_back(vertex); // comm_pub_ptr->publish(msg); // ROS_INFO("Drone %d published: [%d,%d]", uav_id, msg.data[0], msg.data[1]); //} int main(int argc, char** argv){ // ROS Setup: ros::init(argc, argv, "patrol2"); ros::NodeHandle n; ros::NodeHandle p("~"); //for private parameters //Parsing the private parameters passed on to the node: p.param("uav_id", uav_id, 0); //if you don't pass the "robot_id" argument, it will default as "0". std::stringstream id_stream; id_stream << uav_id; std::string goal_reached_topic = "/uav" + id_stream.str() + "/goal_reached"; std::string go_to_topic = "/uav" + id_stream.str() + "/go_to"; // for(int number_of_uav=0;number_of_uav<num_of_uav;number_of_uav++) // { // id_stream << number_of_uav; // std::string first_target_vertex = "uav" + id_stream.str() + "_first_target_vertex"; //p.param("uav0_first_target_vertex", uav_targets[0], 0); //p.param("uav1_first_target_vertex", uav_targets[1], 1); //p.param("uav2_first_target_vertex", uav_targets[2], 2); for(int f=0;f<num_of_uav;f++) { uav_targets[f]=f; } // } for (int t=0;t<GRAPH_DIMENSION;t++) //time initialization { time_vertex[t]=ros::Time::now().toSec(); } //wait for the action server to become ready: //while(!ac.waitForServer(ros::Duration(5.0))){ // ROS_INFO("Waiting for the move_base action server to come up"); //} //A small sleep of 2.0 seconds for synchronization: //ros::Duration(2.2).sleep(); //Define a publisher to the "/communication" topic as an array of integers (to send data to other robots): ros::Publisher go_to_pub = n.advertise<geometry_msgs::Point>(go_to_topic,100); ros::Publisher comm_pub = n.advertise<std_msgs::Int16MultiArray>("/communication", 100); //comm_pub_ptr = &comm_pub; //Define a "/communication" subscriber (to receive data from other robots) in the "/communication" topic: ros::Subscriber comm_sub = n.subscribe<std_msgs::Int16MultiArray>("/communication", 100, ReceiveCommunicationsCB ); std::string Battery_topic_name = "/uav" + id_stream.str() + "/Battery_state"; ros::Subscriber battery_sub = n.subscribe<sensor_msgs::BatteryState>(Battery_topic_name, 100, battery_callback ); //Initialization Services std::string go2point_service_name = "/uav" + id_stream.str() + "/go2point"; std::string goal_reached_server = "/uav" + id_stream.str() + "/goalReached"; std::string start_landing_service_name = "/uav" + id_stream.str() + "/start_landing"; ros::ServiceServer service = n.advertiseService(goal_reached_server, goalreached_callback); ros::ServiceClient client = n.serviceClient<my_controllers::go2point>(go2point_service_name); my_controllers::go2point srv; ros::ServiceClient client1 = n.serviceClient<my_controllers::start_landing>(start_landing_service_name); my_controllers::start_landing srv1; //Navigation goal object: geometry_msgs::Point goal; //Structure with the Graph Info: vertex_set *graph; graph = new vertex_set [GRAPH_DIMENSION]; load_graph(graph); //have a look at "graph.cpp" . //x,y targets double target_x; //in m double target_y; //in m double target_z; double target_angle_yaw = 0.0; //in rads int target_vertex=uav_targets[uav_id]; float D[GRAPH_DIMENSION]={}; //decision array float L[GRAPH_DIMENSION]={}; //neighbor array bool notzero; time_vertex[uav_targets[uav_id]]=ros::Time::now().toSec(); int loop_counter=0; //control variables: ros::Time GoalTime; ros::Rate loop_rate(50); //explicitly define while loop_rate at 50Hz (this will drastically decrease your CPU load) while(ros::ok()){ loop_counter++; if(loop_counter>1000){loop_counter=3;} if (send_goal&&(battery_low==false)){ notzero=false; for (int i1=0;i1<GRAPH_DIMENSION;i1++) //update the visits for each vertex { graph[i1].visits=graph[i1].visits+visit_counter[i1]; } for (int i2=0;i2<GRAPH_DIMENSION;i2++) //reset the visit counter { visit_counter[i2]=0; } for (int i3=0;i3<GRAPH_DIMENSION;i3++) //Update time differences { D[i3]=(float)(ros::Time::now().toSec())-(float)time_vertex[i3]; } for (int i4=0;i4<num_of_uav;i4++) // make the places of robots (the same robot's old target "where it is now" is included) targets in the D array zero. { D[uav_targets[i4]]=0.0; //ROS_INFO("vertex(zero) time is %f.", D[i4]); } for (int i5=0;i5<GRAPH_DIMENSION;i5++) //reset the neighbor array { L[i5]=0; } for (int i6=0;i6<graph[uav_targets[uav_id]].num_neigh;i6++) //1 for neighbor vertex and 0 for non-neighbor { L[graph[uav_targets[uav_id]].id_neigh[i6]]=1.0; } for (int i7=0;i7<GRAPH_DIMENSION;i7++) //calculate the decision array { D[i7]=(float)D[i7]*(float)L[i7]; } for (int z1=0;z1<GRAPH_DIMENSION;z1++) //test that there is at least one non-zero value { if(D[z1]!=0){notzero=true;break;} } if(notzero){ d=D[0]; //find the index of the bigger number for (int i8=0;i8<GRAPH_DIMENSION;i8++) { if(D[i8]>d){d=D[i8];} } for (int k=0;k<GRAPH_DIMENSION;k++) //find the index of the smallest non-zero number (if all the numbers are zeros so target will stay the same and the robot will stay in it's same place) { if(D[k]==d){target_vertex=k;break;} } } send_goal = false; //only send one goal. example_publish = true;// send the goal point to controller } if (send_goal&&battery_low&&(UAV_sent2station==false)) { target_vertex=uav_id; send_goal=false; example_publish =true; UAV_sent2station=true; } if(landing_started) { landing_started=false; //send landing request srv1.request.start_landing = true; if (client1.call(srv1)) { ROS_INFO("Landing command sent to UAV_ID:%d",uav_id); } else { ROS_ERROR("could not send start_landing service."); } } //publishing a message in the "/communication" topic 10 seconds after sending a goal if( example_publish) //&& ros::Time::now() > GoalTime + ros::Duration(10.0) ) { //ROS_INFO("Target_y is %f.", target_y); //ROS_INFO("Target_z is %f.", target_z); //Example of sending a goal: //goal.target_pose.header.frame_id = "map"; //GoalTime = ros::Time::now(); //goal.target_pose.header.stamp = GoalTime; //geometry_msgs::Quaternion angle_quat = tf::createQuaternionMsgFromYaw(target_angle_yaw); //A quaternion must be created to send a goal. //goal.target_pose.pose.position.x = target_x; //goal.target_pose.pose.position.y = target_y; //goal.target_pose.pose.orientation = angle_quat; ROS_INFO("Sending goal to uav %d.", uav_id); srv.request.goal_x = graph[target_vertex].x; srv.request.goal_y = graph[target_vertex].y; srv.request.goal_z = uav_id+1; //graph[target_vertex].z; if (client.call(srv)) { ROS_INFO("The target has successfully sent to controller."); } else { ROS_ERROR("could not send target to controller."); } std_msgs::Int16MultiArray msg; msg.data.clear(); msg.data.push_back(uav_id); msg.data.push_back(target_vertex); comm_pub.publish(msg); ROS_INFO("Drone %d published: [%d,%d]", uav_id, msg.data[0], msg.data[1]); example_publish = false; //only publishes once. send_goal=false; } ros::spinOnce(); //needed to make sure that all your callbacks are triggered. loop_rate.sleep(); } delete graph; return 0; } /////
630f9ef130a24f36bec911e87a03235425a58858
b6d19d7a76556a67d5af0df84676473c594379e6
/MusicSynth/DemoEnvelopes.cpp
b45f3220fb755b832da5724cfe5ebcdf6749f1db
[]
no_license
wesleygriffin/MusicSynth
8df6886cda8c9d678abde645d03f098b91c299f5
a7712bb72fe451c6f656ef0109ca20831d365646
refs/heads/master
2020-04-18T12:55:12.711447
2016-07-05T16:26:49
2016-07-05T16:26:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,269
cpp
DemoEnvelopes.cpp
//-------------------------------------------------------------------------------------------------- // DemoEnvelopes.cpp // // Logic for the demo of the same name // //-------------------------------------------------------------------------------------------------- #include "DemoMgr.h" #include <algorithm> namespace DemoEnvelopes { enum EEnvelope { e_envelopeMinimal, e_envelopeBell, e_envelopeReverseBell, e_envelopeFlute, }; const char* EnvelopeToString (EEnvelope envelope) { switch (envelope) { case e_envelopeMinimal: return "Sine"; case e_envelopeBell: return "Bell"; case e_envelopeReverseBell: return "Reverse Bell"; case e_envelopeFlute: return "Flute"; } return "???"; } struct SNote { SNote(float frequency, EEnvelope envelope) : m_frequency(frequency) , m_envelope(envelope) , m_age(0) , m_dead(false) , m_wantsKeyRelease(false) , m_releaseAge(0) {} float m_frequency; EEnvelope m_envelope; size_t m_age; bool m_dead; bool m_wantsKeyRelease; size_t m_releaseAge; }; std::vector<SNote> g_notes; std::mutex g_notesMutex; EEnvelope g_currentEnvelope; //-------------------------------------------------------------------------------------------------- void OnInit() { } //-------------------------------------------------------------------------------------------------- void OnExit() { } //-------------------------------------------------------------------------------------------------- inline float GenerateEnvelope_Minimal (SNote& note, float ageInSeconds) { // note lifetime static const float c_noteLifeTime = 0.25f; // envelope point calculations static const float c_noteEnvelope = 0.05f; static const float c_envelopePtA = 0.0f; static const float c_envelopePtB = c_noteEnvelope; static const float c_envelopePtC = c_noteLifeTime - c_noteEnvelope; static const float c_envelopePtD = c_noteLifeTime; // put a small envelope on the front and back float envelope = Envelope4Pt( ageInSeconds, c_envelopePtA, 0.0f, c_envelopePtB, 1.0f, c_envelopePtC, 1.0f, c_envelopePtD, 0.0f ); // kill notes that are too old if (ageInSeconds > c_noteLifeTime) note.m_dead = true; return envelope; } //-------------------------------------------------------------------------------------------------- inline float GenerateEnvelope_Bell (SNote& note, float ageInSeconds) { // note lifetime static const float c_noteLifeTime = 1.00f; // use an envelope that sounds "bell like" float envelope = Envelope3Pt( ageInSeconds, 0.0f , 0.0f, 0.003f, 1.0f, c_noteLifeTime, 0.0f ); // kill notes that are too old if (ageInSeconds > c_noteLifeTime) note.m_dead = true; return envelope; } //-------------------------------------------------------------------------------------------------- inline float GenerateEnvelope_ReverseBell (SNote& note, float ageInSeconds) { // note lifetime static const float c_noteLifeTime = 1.00f; // use an envelope that sounds "bell like" but reversed in time float envelope = Envelope3Pt( ageInSeconds, 0.0f, 0.0f, c_noteLifeTime-0.003f, 1.0f, c_noteLifeTime, 0.0f ); // kill notes that are too old if (ageInSeconds > c_noteLifeTime) note.m_dead = true; return envelope; } //-------------------------------------------------------------------------------------------------- inline float GenerateEnvelope_Flute (SNote& note, float ageInSeconds, float sampleRate) { /* We do an ADSR envelope for flute: Attack, Decay, Sustain, Release. When the note is pressed, it always does an attack and decay envelope. Attack takes it from 0 volume to full volume, then Decay takes it down to the decay volume level. Then, as long as the key is held down, it will play at the decay volume. When the key is released, it will then do the decay envelope back to silence and then kill the note. A /\ D S / --------\ / \ 0 R (0) */ // length of envelope sections static const float c_attackTime = 0.1f; static const float c_decayTime = 0.05f; static const float c_releaseTime = 0.1f; static const float c_noteInitialTime = c_attackTime + c_decayTime; // envelope volumes static const float c_attackVolume = 1.0f; static const float c_decayVolume = 0.4f; float envelope = 0.0f; // if the key isn't yet released if (note.m_releaseAge == 0) { // release the key if it wants to be released and has done the attack and decay if (note.m_wantsKeyRelease && ageInSeconds > c_noteInitialTime) { note.m_releaseAge = note.m_age; } // else do the attack and decay envelope else { envelope = Envelope3Pt( ageInSeconds, 0.0f, 0.0f, c_attackTime, c_attackVolume, c_noteInitialTime, c_decayVolume ); } } // if the key has been released, apply the release if (note.m_releaseAge != 0) { float releaseAgeInSeconds = float(note.m_releaseAge) / sampleRate; float secondsInRelease = ageInSeconds - releaseAgeInSeconds; envelope = Envelope2Pt( secondsInRelease, 0.0f, c_decayVolume, c_releaseTime, 0.0f ); // kill the note when the release is done if (secondsInRelease > c_releaseTime) note.m_dead = true; } return envelope; } //-------------------------------------------------------------------------------------------------- inline float GenerateNoteSample (SNote& note, float sampleRate) { float envelope = 0.0f; // calculate our age in seconds and advance our age in samples, by 1 sample float ageInSeconds = float(note.m_age) / sampleRate; ++note.m_age; // do the envelope specific behavior switch (note.m_envelope) { case e_envelopeMinimal: envelope = GenerateEnvelope_Minimal(note, ageInSeconds); break; case e_envelopeBell: envelope = GenerateEnvelope_Bell(note, ageInSeconds); break; case e_envelopeReverseBell: envelope = GenerateEnvelope_ReverseBell(note, ageInSeconds); break; case e_envelopeFlute: envelope = GenerateEnvelope_Flute(note, ageInSeconds, sampleRate); break; } // generate the sine value for the current time. // Note that it is ok that we are basing audio samples on age instead of phase, because the // frequency never changes and we envelope the front and back to avoid popping. return std::sinf(ageInSeconds*note.m_frequency*2.0f*c_pi) * envelope; } //-------------------------------------------------------------------------------------------------- void GenerateAudioSamples (float *outputBuffer, size_t framesPerBuffer, size_t numChannels, float sampleRate) { // get a lock on our notes vector std::lock_guard<std::mutex> guard(g_notesMutex); // for every sample in our output buffer for (size_t sample = 0; sample < framesPerBuffer; ++sample, outputBuffer += numChannels) { // add up all notes to get the final value. float value = 0.0f; std::for_each( g_notes.begin(), g_notes.end(), [&value, sampleRate](SNote& note) { value += GenerateNoteSample(note, sampleRate); } ); // copy the value to all audio channels for (size_t channel = 0; channel < numChannels; ++channel) outputBuffer[channel] = value; } // remove notes that have died auto iter = std::remove_if( g_notes.begin(), g_notes.end(), [] (const SNote& note) { return note.m_dead; } ); if (iter != g_notes.end()) g_notes.erase(iter); } //-------------------------------------------------------------------------------------------------- void StopFluteNote (float frequency) { // get a lock on our notes vector std::lock_guard<std::mutex> guard(g_notesMutex); // Any note that is a flute note of this frequency should note that it wants to enter released // state. std::for_each( g_notes.begin(), g_notes.end(), [frequency] (SNote& note) { if (note.m_envelope == e_envelopeFlute && note.m_frequency == frequency) { note.m_wantsKeyRelease = true; } } ); } //-------------------------------------------------------------------------------------------------- void ReportParams() { printf("Envelope: %s\r\n", EnvelopeToString(g_currentEnvelope)); } //-------------------------------------------------------------------------------------------------- void OnKey (char key, bool pressed) { // pressing numbers switch envelopes if (pressed) { switch (key) { case '1': g_currentEnvelope = e_envelopeMinimal; ReportParams(); return; case '2': g_currentEnvelope = e_envelopeBell; ReportParams(); return; case '3': g_currentEnvelope = e_envelopeReverseBell; ReportParams(); return; case '4': g_currentEnvelope = e_envelopeFlute; ReportParams(); return; } } // figure out what frequency to play float frequency = 0.0f; switch (key) { // QWERTY row case 'Q': frequency = NoteToFrequency(3, 0); break; case 'W': frequency = NoteToFrequency(3, 1); break; case 'E': frequency = NoteToFrequency(3, 2); break; case 'R': frequency = NoteToFrequency(3, 3); break; case 'T': frequency = NoteToFrequency(3, 4); break; case 'Y': frequency = NoteToFrequency(3, 5); break; case 'U': frequency = NoteToFrequency(3, 6); break; case 'I': frequency = NoteToFrequency(3, 7); break; case 'O': frequency = NoteToFrequency(3, 8); break; case 'P': frequency = NoteToFrequency(3, 9); break; case -37: frequency = NoteToFrequency(3, 10); break; // ASDF row case 'A': frequency = NoteToFrequency(2, 0); break; case 'S': frequency = NoteToFrequency(2, 1); break; case 'D': frequency = NoteToFrequency(2, 2); break; case 'F': frequency = NoteToFrequency(2, 3); break; case 'G': frequency = NoteToFrequency(2, 4); break; case 'H': frequency = NoteToFrequency(2, 5); break; case 'J': frequency = NoteToFrequency(2, 6); break; case 'K': frequency = NoteToFrequency(2, 7); break; case 'L': frequency = NoteToFrequency(2, 8); break; case -70: frequency = NoteToFrequency(2, 9); break; case -34: frequency = NoteToFrequency(2, 10); break; // ZXCV row case 'Z': frequency = NoteToFrequency(1, 0); break; case 'X': frequency = NoteToFrequency(1, 1); break; case 'C': frequency = NoteToFrequency(1, 2); break; case 'V': frequency = NoteToFrequency(1, 3); break; case 'B': frequency = NoteToFrequency(1, 4); break; case 'N': frequency = NoteToFrequency(1, 5); break; case 'M': frequency = NoteToFrequency(1, 6); break; case -68: frequency = NoteToFrequency(1, 7); break; case -66: frequency = NoteToFrequency(1, 8); break; case -65: frequency = NoteToFrequency(1, 9); break; case -95: frequency = NoteToFrequency(1, 10); break; // right shift // left shift = low freq case 16: frequency = NoteToFrequency(0, 5); break; // left shift = low freq case -94: frequency = NoteToFrequency(0, 0); break; default: { return; } } // if releasing a note, we want to do nothing in most modes. // in flute mode, we need to find and kill the flute note of the same frequency if (!pressed) { if (g_currentEnvelope == e_envelopeFlute) { StopFluteNote(frequency); } return; } // get a lock on our notes vector and add the new note std::lock_guard<std::mutex> guard(g_notesMutex); g_notes.push_back(SNote(frequency, g_currentEnvelope)); } //-------------------------------------------------------------------------------------------------- void OnEnterDemo () { g_currentEnvelope = e_envelopeMinimal; printf("Letter keys to play notes.\r\nleft shift / control is super low frequency.\r\n"); printf("1 = minimal\r\n"); printf("2 = bell\r\n"); printf("3 = reverse bell\r\n"); printf("4 = flute\r\n"); printf("\r\nInstructions:\r\n"); printf("Play the different instruments.\r\nmention all sine waves with envelopes on slide.\r\n"); // clear all the notes out std::lock_guard<std::mutex> guard(g_notesMutex); g_notes.clear(); } }
083149d56342ebfe417b5bfba186380d7bf46438
23c4109411bb6490d76430d485c19152c56e037a
/llvm/lib/Target/AMDGPU/BBSchedStrategy.h
2a6f059e2f6a714da6d29cd736a9ff22dcd86921
[]
no_license
AlexErf/GPUProject
f9a060e63caec0c07584aa2a2826432dc6cfc0b5
c2740b6ca052436a73d05564187c473a37f362b9
refs/heads/main
2023-02-02T05:41:53.330592
2020-12-14T03:04:19
2020-12-14T03:04:19
310,434,160
2
0
null
null
null
null
UTF-8
C++
false
false
5,808
h
BBSchedStrategy.h
//===-- BBSchedStrategy.h - BB Scheduler Strategy -*- 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 // //===----------------------------------------------------------------------===// // /// \file // //===----------------------------------------------------------------------===// #ifndef LLVM_LIB_TARGET_AMDGPU_BBSCHEDSTRATEGY_H #define LLVM_LIB_TARGET_AMDGPU_BBSCHEDSTRATEGY_H #include "GCNRegPressure.h" #include "llvm/CodeGen/MachineScheduler.h" namespace llvm { class SIMachineFunctionInfo; class SIRegisterInfo; class GCNSubtarget; struct node { std::vector<node*> preds; std::vector<int> predsLatencies; std::vector<node*> succs; std::vector<int> succsLatencies; /// a helper function to get the succ latency int getSuccLatency(node* succ) { auto it = find(succs.begin(), succs.end(), succ); if (it != succs.end()) { int index = it - succs.begin(); return succsLatencies[index]; } return -1; } /// a helper function to get the pred latency int getPredLatency(node* pred) { auto it = find(preds.begin(), preds.end(), pred); if (it != preds.end()) { int index = it - preds.begin(); return predsLatencies[index]; } return -1; } }; /// This is a minimal scheduler strategy. The main difference between this /// and the GenericScheduler is that GCNSchedStrategy uses different /// heuristics to determine excess/critical pressure sets. Its goal is to /// maximize kernel occupancy (i.e. maximum number of waves per simd). class GCNMaxOccupancySchedStrategy final : public GenericScheduler { friend class GCNScheduleDAGMILive; SUnit *pickNodeBidirectional(bool &IsTopNode); void pickNodeFromQueue(SchedBoundary &Zone, const CandPolicy &ZonePolicy, const RegPressureTracker &RPTracker, SchedCandidate &Cand); void initCandidate(SchedCandidate &Cand, SUnit *SU, bool AtTop, const RegPressureTracker &RPTracker, const SIRegisterInfo *SRI, unsigned SGPRPressure, unsigned VGPRPressure); std::vector<unsigned> Pressure; std::vector<unsigned> MaxPressure; unsigned SGPRExcessLimit; unsigned VGPRExcessLimit; unsigned SGPRCriticalLimit; unsigned VGPRCriticalLimit; unsigned TargetOccupancy; MachineFunction *MF; public: GCNMaxOccupancySchedStrategy(const MachineSchedContext *C); SUnit *pickNode(bool &IsTopNode) override; void initialize(ScheduleDAGMI *DAG) override; void setTargetOccupancy(unsigned Occ) { TargetOccupancy = Occ; } }; class GCNScheduleDAGMILive final : public ScheduleDAGMILive { enum : unsigned { Collect, InitialSchedule, UnclusteredReschedule, ClusteredLowOccupancyReschedule, LastStage = ClusteredLowOccupancyReschedule }; const GCNSubtarget &ST; SIMachineFunctionInfo &MFI; // Occupancy target at the beginning of function scheduling cycle. unsigned StartingOccupancy; // Minimal real occupancy recorder for the function. unsigned MinOccupancy; // Scheduling stage number. unsigned Stage; // Current region index. size_t RegionIdx; // Vector of regions recorder for later rescheduling SmallVector<std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>, 32> Regions; // Records if a region is not yet scheduled, or schedule has been reverted, // or we generally desire to reschedule it. BitVector RescheduleRegions; // Region live-in cache. SmallVector<GCNRPTracker::LiveRegSet, 32> LiveIns; // Region pressure cache. SmallVector<GCNRegPressure, 32> Pressure; // Temporary basic block live-in cache. DenseMap<const MachineBasicBlock*, GCNRPTracker::LiveRegSet> MBBLiveIns; DenseMap<MachineInstr *, GCNRPTracker::LiveRegSet> BBLiveInMap; DenseMap<MachineInstr *, GCNRPTracker::LiveRegSet> getBBLiveInMap() const; // Return current region pressure. GCNRegPressure getRealRegPressure() const; // Compute and cache live-ins and pressure for all regions in block. void computeBlockPressure(const MachineBasicBlock *MBB); void occupancyPass(SmallVector<SUnit*, 8> topRoots, SmallVector<SUnit*, 8> bottomRoots, unsigned targetPressure); void ilpPass(SmallVector<SUnit*, 8> topRoots, std::vector<SUnit* > scheduleInst, int targetPressure); unsigned enumerate(SmallVector<SUnit*, 8> TopRoots, SmallVector<SUnit*, 8> BottomRoots, unsigned targetLength, unsigned targetAPRP, bool isOccupanyPass); void scheduleInst(MachineInstr* MI); int satisfyLatency(std::vector<SUnit*> schedule); void restoreLatencies(SmallVector<llvm::SUnit *, 8> &topRoots, std::map<SUnit*, node*> mapSUnitToNode); std::map<SUnit*, int> estart; std::map<SUnit*, int> lstart; std::map<SUnit*, node*> setLatenciesToOne(SmallVector<llvm::SUnit *, 8> &topRoots); void computeEstart(SmallVector<SUnit*, 8> topRoots); void computeLstart(SmallVector<SUnit*, 8> bottomRoots, int maxEstart); unsigned computeDLB(std::map<int, SUnit*> scheduleSoFar); bool checkNode(SUnit* node, const std::map<int, SUnit*>& scheduleSoFar, const std::vector<SUnit*>& currentScheduledInstructions, unsigned targetLength, unsigned targetAPRP, unsigned enumBestAPRP, bool isOccupancyPass); public: GCNScheduleDAGMILive(MachineSchedContext *C, std::unique_ptr<MachineSchedStrategy> S); void schedule() override; void finalizeSchedule() override; }; } // End namespace llvm #endif // BBSCHEDSTRATEGY_H
f86deb73ee4561b82ea4134dbb7e1db2c3e0262a
42f82a4d6f768687989832ec980820ac565360fa
/main.cpp
439c83a3209ee82b57a17b280f0b7174c2524ab0
[]
no_license
jogi91/ballrecognition
d498c4fe7db3ab3fb3f2c0fe164e947a84613ee9
975faf4fbfb685f7070f6e90f986b481b3c28112
refs/heads/master
2016-09-06T15:26:50.791372
2011-04-08T16:54:06
2011-04-08T16:54:06
1,161,350
0
0
null
null
null
null
ISO-8859-1
C++
false
false
9,628
cpp
main.cpp
#include <stdio.h> #include "cv.h" #include "highgui.h" #include <iostream> #include <fstream> #include <math.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <signal.h> using namespace std; #define LINKS 2 #define RECHTS 1 #define BEIDE 3 //Globale Variablen fuer die Referenzbilder, momentan wird nur refFlipsDown verwendet IplImage *refFlipsDown = 0; IplImage *refRightFlipUp = 0; IplImage *refLeftFlipUp = 0; IplImage *refBothFlipsUp =0; //Schiesst, wartet delay millisekunden, und lŠsst dann wieder los, und das alles mit den gewŸnschten Flipperfingern void shoot(int delay, int flips){ cout << flips << delay << endl; //cout wird in den Shooterprozess umgeleitet, siehe unden im Prozesshandling } //nimmt fuer jeden zustand ein Referenzbild auf, und speichert es in den globalen Variablen //Im Moment wird nur das Referenzbild mit beiden Flippern unten aufgenommen, also nur case 0 erreicht. //case 1 ff. sind dazu gedacht, von ausgelšsten Flippern Referenzbilder zu schiessen. int takeRefShot(IplImage * frame, int& counter){ switch (counter) { case 0 : refFlipsDown = frame; cerr << "Referenzbild erfolgreich aufgenommen"; counter++; return 0; case 1: refBothFlipsUp = frame; cerr << "Bitte zwei Bälle auf die Flipper legen, damit die Mitte bestimmt werden kann" << endl; cerr << "Bei einem beliebigen tastendruck wird die Mitte dann berechnet" << endl; counter++; return 0; case 2: // zwei Bälle erkennen, mitte berechnen return 364; } } //Signalhandler fŸr das Beenden durch den Nutzer void SIGINT_handler (int signum) { assert (signum == SIGINT); cerr << "Signal interrupt empfangen" << endl; cout << "exit" << endl; // cerr << "vorwait" << endl; wait(); cerr << "nachwait" << endl; exit(0); } //Signalhandler fŸr abstŸrze void SIGTERM_handler (int signum) { assert (signum == SIGTERM); cerr << "SITGTERM empfangen, vermutlich verursacht durch fehlerhaften DV-Stream" << endl; cerr << "Bitte versuche erneut, das Programm zu starten" << endl; cout << "exit"; exit(1); } // Alte Shoot-Version mit nur 1 Prozess //Der Flipper soll delay millisekunden oben bleiben und nur die entsprechenden Flips sollen aktiviert werden. // Zuordnoung ist binaer: 01: rchter flipper, 10, linker flipper, 11 beide /*void shoot(int delay, int flips){ switch (flips) { case 1: system("echo -n 1 >> /dev/ttyUSB0"); break; case 2: system("echo -n 2 >> /dev/ttyUSB0"); break; case 3: system("echo -n 3 >> /dev/ttyUSB0"); break; default: break; } usleep(delay*1000); system("echo -n 0 >> /dev/ttyUSB0"); cerr << "Funktion Shoot ausgeführt" << endl; }*/ int main(){ // http://www.cs.wustl.edu/~schmidt/signal-patterns.html // http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_21.html struct sigaction sa; sigemptyset (&sa.sa_mask); sa.sa_flags = 0; /* Register the handler for SIGINT. */ sa.sa_handler = SIGINT_handler; sigaction (SIGINT, &sa, 0); /* Register the handler for SIGTERM. */ sa.sa_handler = SIGTERM_handler; sigaction (SIGTERM, &sa, 0); //Fork, inspiriert nach http://www.gidforums.com/t-3369.html pid_t pid; int commpipe[2]; /* This holds the fd for the input & output of the pipe */ /* Setup communication pipeline first */ if(pipe(commpipe)){ fprintf(stderr,"Pipe error!\n"); exit(1); } //forking if( (pid=fork()) == -1){ fprintf(stderr,"Fork error. Exiting.\n"); /* something went wrong */ exit(1); } if(pid){ /* A positive (non-negative) PID indicates the parent process */ dup2(commpipe[1],1); /* Replace stdout with out side of the pipe */ close(commpipe[0]); /* Close unused side of pipe (in side) */ setvbuf(stdout,(char*)NULL,_IONBF,0); /* Set non-buffered output on stdout */ //Flipper sagt hallo shoot(100, BEIDE); shoot(100, LINKS); shoot(100, RECHTS); shoot(100, LINKS); shoot(1000, RECHTS); shoot(2000, BEIDE); shoot(2000, BEIDE); CvMemStorage* cstorage = cvCreateMemStorage(0); //Stream laden CvCapture* capture = cvCaptureFromFile("/home/jogi/Documents/matura/ballrecognition/camfifo"); //CvCapture* capture = cvCaptureFromCAM(-1); if( !capture ) { fprintf( stderr, "ERROR: capture is NULL \n" ); getchar(); return -1; } //Fenster erstellen cvNamedWindow( "ball", CV_WINDOW_AUTOSIZE ); int height, width, step, channels, i, j; int counter = 0; int mittelxkoordinate; uchar *data; //Einen Frame im Voraus abrufen // Get one frame IplImage* frame = cvQueryFrame( capture ); if( !frame ) { fprintf( stderr, "ERROR: frame is null...\n" ); getchar(); } height = frame->height; width = frame->width; step = frame->widthStep; channels = frame->nChannels; data = (uchar *)frame->imageData; IplImage *referenz = cvCreateImage(cvSize(width, height), 8, 1); IplImage *workingcopy = cvCreateImage(cvSize(width, height), 8, 1); //Warten auf befehl zum Referenzbilder aufnehmen, Esc beginnt die Prozedur while (1) { // Get one frame frame = cvQueryFrame( capture ); if( !frame ) { fprintf( stderr, "ERROR: frame is null... hiho\n" ); getchar(); break; } // Fadenkreuz cvCircle(frame, cvPoint(width/2,height/2), 20, cvScalar(0,255,0), 1); cvLine(frame, cvPoint(0, height/2), cvPoint(width, height/2), cvScalar(0,255,0), 1); cvLine(frame, cvPoint(0, 3*height/4), cvPoint(width, 3*height/4), cvScalar(0,255,0), 1); cvLine(frame, cvPoint(width/2, height), cvPoint(width/2, 0), cvScalar(0,255,0), 1); cvWaitKey(1); cvShowImage( "ball", frame ); // Do not release the frame! //If ESC key pressed, take Refshot if( (cvWaitKey(10) & 255) == 27 ) { takeRefShot(frame, counter); cvDestroyAllWindows(); cerr << "Window closed" << endl; break; } } cvCvtColor(refFlipsDown, referenz, CV_BGR2GRAY); cvSmooth(referenz, referenz, CV_GAUSSIAN, 17,17 ); cvWaitKey(250); //Positionsbestimmung des Balls int xkoordinate, ykoordinate, xkoordinatealt, ykoordinatealt, speedx, speedy; ykoordinatealt = 0; xkoordinatealt = 0; xkoordinate = 0; ykoordinate = 0; counter = 0; speedx = 0; speedy = 0; while (1) { //neuer Frame frame = cvQueryFrame( capture ); if( !frame ) { fprintf( stderr, "ERROR: frame is null...heyhey\n" ); break; } //Position vom Ball bestimmen cvCvtColor(frame, workingcopy, CV_BGR2GRAY); //Der abgerufene frame wird in die Variable workingcopy kopiert und dabei in GRaustufen konvertiert cvSmooth(workingcopy, workingcopy, CV_GAUSSIAN, 15, 15); //Gausscher weichzeichner //Bild mit nicht XOR verknŸpfen for (i = 0; i<height; i++) { for (j = 0; j<width; j++) { if ( j == 0 && i < 10) { } ((uchar *)(workingcopy->imageData + i*workingcopy->widthStep))[j] = ~(((uchar *)(workingcopy->imageData + i*workingcopy->widthStep))[j] ^ ((uchar *)(referenz->imageData + i*referenz->widthStep))[j]); } } //Ball suchen cvSmooth(workingcopy, workingcopy, CV_GAUSSIAN, 15, 15); cvThreshold(workingcopy, workingcopy, 125, 255, CV_THRESH_BINARY); //cvWaitKey(10); //cvShowImage("ball", workingcopy); //Kreise Finden CvSeq* circles = cvHoughCircles( workingcopy, cstorage, CV_HOUGH_GRADIENT, 1, workingcopy->height/50, 12, 10,4,50 ); //cerr << "Anzahl Gefundener Kreise:" << circles->total << endl; //cerr << "Zielkoordinate: " << 375 << endl; xkoordinatealt = xkoordinate; ykoordinatealt = ykoordinate; if (circles->total < 10 and circles->total != 0 and counter > 6) { xkoordinate = 0; ykoordinate = 0; //Wenn es weniger als 10 Kreise hat, Bild analysieren. for (i=0; i<circles->total; i++) { float* p = (float*)cvGetSeqElem(circles, i); xkoordinate += cvRound(p[0]); ykoordinate += cvRound(p[1]); } //mttlere koordinaten berechnen xkoordinate = xkoordinate/circles->total; ykoordinate = ykoordinate/circles->total; cerr << "Koordinaten: " << xkoordinate << "/" << ykoordinate << endl; //Geschwindigkeit berechnen speedx = xkoordinate - xkoordinatealt; //positiv ist bewegung nach rechts speedy = ykoordinate - ykoordinatealt; //positiv ist bewegung nach unten //eingefŸgt, um zu prŸfen, ob das gleiche Bild evtl. mehrmals ausgewertet wird. /*if (ykoordinate == ykoordinatealt) { cerr << "Y-KOORDINATEN GLEICH!!!!" << endl; } if (xkoordinate == xkoordinatealt) { cerr << "Y-KOORDINATEN GLEICH!!!!" << endl; }*/ //Wenn sich die Kugel in der heissen Zone befindet, schiessen, oder wenn sie sich mit der Bewegung in einer heisseren Zone befinden wird, schiessen //horizontale bewegungen werden noch nicht vorausberechnet if (ykoordinate > 375 or ykoordinate+speedy > 450) { cerr << "ausgelöst" << endl; counter = 0; if (xkoordinate > width/2 ){ shoot(100, RECHTS); } else { shoot(100, LINKS); } } } else { counter++; cerr << counter; } } } //ende des Hauptprozesses else{ /* A zero PID indicates that this is the child process */ dup2(commpipe[0],0); /* Replace stdin with the in side of the pipe */ close(commpipe[1]); /* Close unused side of pipe (out side) */ /* Replace the child fork with a new process */ if(execl("shooter","shooter",NULL) == -1){ fprintf(stderr,"execl Error!"); exit(1); } } return 0; }
5a72a5b51dddde73ee739d607ead2fcb0c3ab763
b95739405a1468d6a693175b54bbabf2b6afde9a
/abxy/GL/GLShader.cpp
aa4f4533ee6142bf0932a45a869e5b04963fca1b
[]
no_license
xymostech/abxy
02304d4d33e442792f93ef2f05b7fa2fee87e675
0d13b34f021ee2583cf56feacf22a9e6a5fd4a21
refs/heads/master
2020-05-29T13:18:54.851817
2013-03-25T02:58:55
2013-03-25T02:58:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
793
cpp
GLShader.cpp
#include <abxy/GL/GLShader.hpp> #include <stdexcept> #include <abxy/util/File.hpp> GLShader::GLShader(std::string file, GLenum shader_type) : shader(shader_type) { std::string file_data = Util::Read(file); shader.SetSource(file_data); shader.Compile(); if (shader.GetParam(GL_COMPILE_STATUS) == GL_FALSE) { std::string log = shader.GetInfoLog(); std::string shader_name; if (shader.GetType() == GL_VERTEX_SHADER) { shader_name = "vertex"; } else { shader_name = "fragment"; } throw std::runtime_error("Error compiling " + shader_name + " shader: " + log); } } void GLShader::AttachTo(GLuint program) { shader.AttachTo(program); } void GLShader::DetachFrom(GLuint program) { shader.DetachFrom(program); } GLShaderRef &GLShader::GetRef() { return shader; }
f591a0088b205b4c0d86e369582483fd0b16ed89
20d024bd04ace59987ba05f864d6d9dece72fbab
/ACdream/9-24 数论/C.CPP
6dcb4b6d70889bf02e34dcb613bef51f566783e9
[]
no_license
Yeluorag/ACM-ICPC-Code-Library
8837688c23bf487d4374a76cf0656cb7adc751b0
77751c79549ea8ab6f790d55fac3738d5b615488
refs/heads/master
2021-01-20T20:18:43.366920
2016-08-12T08:08:38
2016-08-12T08:08:38
64,487,659
0
0
null
null
null
null
UTF-8
C++
false
false
1,360
cpp
C.CPP
#include <algorithm> #include <iostream> #include <sstream> #include <cstring> #include <cstdio> #include <vector> #include <string> #include <queue> #include <stack> #include <cmath> #include <set> #include <map> using namespace std; typedef long long LL; #define mem(a, n) memset(a, n, sizeof(a)) #define rep(i, n) for(int i = 0; i < (n); i ++) #define REP(i, t, n) for(int i = (t); i < (n); i ++) #define FOR(i, t, n) for(int i = (t); i <= (n); i ++) #define ALL(v) v.begin(), v.end() #define si(a) scanf("%d", &a) #define sii(a, b) scanf("%d%d", &a, &b) #define siii(a, b, c) scanf("%d%d%d", &a, &b, &c) #define pb push_back const int inf = 0x3f3f3f3f, N = 1e3 + 5, MOD = 1e9 + 7; int T, cas = 0; int n, m; // Imp bool isPrime(int n) { int m = sqrt(n + 0.5); FOR(i, 2, m) { if(n % i == 0) return false; } return true; } int cal(int n) { int m = sqrt(n + 0.5), ret = 0; FOR(i, 2, m) if(n % i == 0) { while(n % i == 0) { ret += i; n /= i; } }if(n > 1) ret += n; return ret; } int work(int n) { while(1) { if(isPrime(n)) return n; else { int t = cal(n); if(n == t) return -1; n = t; } } return -1; } int main(){ #ifdef LOCAL freopen("/Users/apple/input.txt", "r", stdin); // freopen("/Users/apple/out.txt", "w", stdout); #endif while(si(n) != EOF) { printf("%d\n", work(n)); } return 0; }
434209f8d4bed635e0c5e5bd9ca5e0b11ed23959
6279ea52416d92f1642322e61a597a6dba852497
/main.cpp
4eff05d61a3b9728746dc0c912ad41a05d2f4de3
[]
no_license
owong1/Complex
1da58c63bffd293667dcba597c674589e6e8ee4c
451358e99d7f18160b6520a8937d4571ce62fc03
refs/heads/master
2021-01-21T11:11:03.374392
2017-03-01T08:32:23
2017-03-01T08:32:23
83,531,333
0
0
null
null
null
null
UTF-8
C++
false
false
537
cpp
main.cpp
#include <iostream> #include "Complex.h" using namespace std; int main(){ Complex<int> c1(3, 2); Complex<int> c2(6, 4); Complex<int> ans; cout << "complex 1: " << c1 << endl; cout << "complex 2: " << c2 << endl; cout << endl; ans = c1 + c2; cout << c1 << " + " << c2 << " = " << ans << endl; ans = c1 - c2; cout << c1 << " - " << c2 << " = " << ans << endl; ans = c1 * c2; cout << c1 << " * " << c2 << " = " << ans << endl; ans = c2 / c1; cout << c2 << " / " << c1 << " = " << ans << endl; getchar(); return 0; }
07c553cc3fd11a5b2189a63ba02817bcbe4b95ff
8a36111745077e680b3c60a1aa61e2137a288fa3
/WindowsNetworkServer/Main.cpp
9dee44f6199eec9ad14d16c6ab71b3d68ee0a688
[]
no_license
SamuelLouisCampbell/WindowsNetworkServer
fb09545b174cdf339cd8009c4432f4af1a3f382e
16c176091c2f6c0fc3260f0cb5f87efe49a98bec
refs/heads/master
2022-04-21T15:56:18.402938
2020-04-21T11:22:57
2020-04-21T11:22:57
257,570,593
0
0
null
null
null
null
UTF-8
C++
false
false
2,101
cpp
Main.cpp
#define PORT 7000 #define IP_ADDRESS 127.0.0.1 #include <algorithm> #include<io.h> #include<stdio.h> #include<winsock2.h> #pragma comment(lib,"ws2_32.lib") //Winsock Library int main(int argc, char* argv[]) { WSADATA wsa; SOCKET s, new_socket; struct sockaddr_in server, client; int c; const char* message; const int maxC_Message = 512; char clientMessage[maxC_Message]; int recv_size; printf("\nInitialising Winsock... "); if (WSAStartup(MAKEWORD(2, 2), & wsa) != 0) { printf("Failed.Error Code : % d " , WSAGetLastError()); return 1; } printf("Initialised.\n "); //Create a socket if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) { printf("Could not create socket : % d ", WSAGetLastError()); } printf("\n>>>Socket created.\n"); //Prepare the sockaddr_in structure server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons(PORT); //Bind if (bind(s, (struct sockaddr*) & server, sizeof(server)) == SOCKET_ERROR) { printf("Bind failed with error code : % d ", WSAGetLastError()); exit(EXIT_FAILURE); } puts(">>>Bind complete\n"); //Listen to incoming connections listen(s, 3); //Accept and incoming connection puts("Waiting for incoming connections..."); c = sizeof(struct sockaddr_in); while ((new_socket = accept(s, (struct sockaddr*) & client, & c)) != INVALID_SOCKET) { puts("\nConnection accepted "); if ((recv_size = recv(new_socket, clientMessage, maxC_Message, 0)) == SOCKET_ERROR) { puts("No messages...\n"); } else { puts("\nWe got this from the client:"); if (recv_size > maxC_Message) { clientMessage[maxC_Message - 1] = '\0'; } else { clientMessage[recv_size] = '\0'; } puts(clientMessage); } //Reply to the client message = "Hello Client, I have received your connection.But I have to go now, bye\n"; send(new_socket, message, strlen(message), 0); } if (new_socket == INVALID_SOCKET) { printf("accept failed with error code : % d ", WSAGetLastError()); return 1; } closesocket(s); WSACleanup(); return 0; }
d7d0a7856c6fca42227a8f417985eaeecc955c5b
b33a9177edaaf6bf185ef20bf87d36eada719d4f
/qtxmlpatterns/src/xmlpatterns/schema/qxsdinstancereader.cpp
9c7337c38cd43f372019e26668113c395d0555b1
[ "LGPL-2.0-or-later", "LGPL-3.0-only", "GPL-3.0-only", "LGPL-2.1-or-later", "GPL-1.0-or-later", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "GFDL-1.3-only", "Qt-LGPL-exception-1.1", "LGPL-2.1-only", "LicenseRef-scancode-digia-qt-preview", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-generic-exception" ]
permissive
wgnet/wds_qt
ab8c093b8c6eead9adf4057d843e00f04915d987
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
refs/heads/master
2021-04-02T11:07:10.181067
2020-06-02T10:29:03
2020-06-02T10:34:19
248,267,925
1
0
Apache-2.0
2020-04-30T12:16:53
2020-03-18T15:20:38
null
UTF-8
C++
false
false
5,836
cpp
qxsdinstancereader.cpp
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the QtXmlPatterns module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** 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 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qxsdinstancereader_p.h" QT_BEGIN_NAMESPACE using namespace QPatternist; XsdInstanceReader::XsdInstanceReader(const QAbstractXmlNodeModel *model, const XsdSchemaContext::Ptr &context) : m_context(context) , m_model(model->iterate(model->root(QXmlNodeModelIndex()), QXmlNodeModelIndex::AxisChild)) { } bool XsdInstanceReader::atEnd() const { return (m_model.current() == AbstractXmlPullProvider::EndOfInput); } void XsdInstanceReader::readNext() { m_model.next(); if (m_model.current() == AbstractXmlPullProvider::StartElement) { m_cachedAttributes = m_model.attributes(); m_cachedAttributeItems = m_model.attributeItems(); m_cachedSourceLocation = m_model.sourceLocation(); m_cachedItem = QXmlItem(m_model.index()); } } bool XsdInstanceReader::isStartElement() const { return (m_model.current() == AbstractXmlPullProvider::StartElement); } bool XsdInstanceReader::isEndElement() const { return (m_model.current() == AbstractXmlPullProvider::EndElement); } bool XsdInstanceReader::hasChildText() const { const QXmlNodeModelIndex index = m_model.index(); QXmlNodeModelIndex::Iterator::Ptr it = index.model()->iterate(index, QXmlNodeModelIndex::AxisChild); QXmlNodeModelIndex currentIndex = it->next(); while (!currentIndex.isNull()) { if (currentIndex.kind() == QXmlNodeModelIndex::Text) return true; currentIndex = it->next(); } return false; } bool XsdInstanceReader::hasChildElement() const { const QXmlNodeModelIndex index = m_model.index(); QXmlNodeModelIndex::Iterator::Ptr it = index.model()->iterate(index, QXmlNodeModelIndex::AxisChild); QXmlNodeModelIndex currentIndex = it->next(); while (!currentIndex.isNull()) { if (currentIndex.kind() == QXmlNodeModelIndex::Element) return true; currentIndex = it->next(); } return false; } QXmlName XsdInstanceReader::name() const { return m_model.name(); } QXmlName XsdInstanceReader::convertToQName(const QString &name) const { const int pos = name.indexOf(QLatin1Char(':')); QXmlName::PrefixCode prefixCode = 0; QXmlName::NamespaceCode namespaceCode; QXmlName::LocalNameCode localNameCode; if (pos != -1) { prefixCode = m_context->namePool()->allocatePrefix(name.left(pos)); namespaceCode = m_cachedItem.toNodeModelIndex().namespaceForPrefix(prefixCode); localNameCode = m_context->namePool()->allocateLocalName(name.mid(pos + 1)); } else { prefixCode = StandardPrefixes::empty; namespaceCode = m_cachedItem.toNodeModelIndex().namespaceForPrefix(prefixCode); if (namespaceCode == -1) namespaceCode = StandardNamespaces::empty; localNameCode = m_context->namePool()->allocateLocalName(name); } return QXmlName(namespaceCode, localNameCode, prefixCode); } bool XsdInstanceReader::hasAttribute(const QXmlName &name) const { return m_cachedAttributes.contains(name); } QString XsdInstanceReader::attribute(const QXmlName &name) const { Q_ASSERT(m_cachedAttributes.contains(name)); return m_cachedAttributes.value(name); } QSet<QXmlName> XsdInstanceReader::attributeNames() const { return m_cachedAttributes.keys().toSet(); } QString XsdInstanceReader::text() const { const QXmlNodeModelIndex index = m_model.index(); QXmlNodeModelIndex::Iterator::Ptr it = index.model()->iterate(index, QXmlNodeModelIndex::AxisChild); QString result; QXmlNodeModelIndex currentIndex = it->next(); while (!currentIndex.isNull()) { if (currentIndex.kind() == QXmlNodeModelIndex::Text) { result.append(Item(currentIndex).stringValue()); } currentIndex = it->next(); } return result; } QXmlItem XsdInstanceReader::item() const { return m_cachedItem; } QXmlItem XsdInstanceReader::attributeItem(const QXmlName &name) const { return m_cachedAttributeItems.value(name); } QSourceLocation XsdInstanceReader::sourceLocation() const { return m_cachedSourceLocation; } QVector<QXmlName> XsdInstanceReader::namespaceBindings(const QXmlNodeModelIndex &index) const { return index.namespaceBindings(); } QT_END_NAMESPACE
ed3803b7eacb15c6ab0eb34905fefd802468f5cb
cf7750ded027a1f9ff38efc3f7e525277987f424
/src/read_buffer.h
632a923fe3a2a63a6633124fe6200c3d6b556b8b
[]
no_license
MeiK2333/blog
47d3ddae9dd0a2a707814ce039f7f7d42ccf8001
5ae8a75756d98d5e134e6abb8741a9a54eecec67
refs/heads/master
2020-03-23T18:15:00.080248
2018-08-16T11:44:59
2018-08-16T11:44:59
141,897,343
1
0
null
null
null
null
UTF-8
C++
false
false
263
h
read_buffer.h
#ifndef BLOG_READ_BUFFER_H #define BLOG_READ_BUFFER_H class ReadBuffer { public: ReadBuffer(int); ~ReadBuffer(); int Read(); char *buffer; bool End(); private: int fd; int offset; int size; void resize(int); }; #endif
2dcd2be4807dadbee3df42d27fb631c4cf671c3b
cabbfaf53165be9c1c4a9def4a8697bd4a8e648c
/src/Chunk.cpp
557dfe419e3e98b9728be18861dbb2a6d539934a
[ "Apache-2.0" ]
permissive
yurirocha15/Gradius
c285eef1ff49c7361cacb00ca76bb539d6a0746d
9c033a2b79823283ca901023bf485ed16bb8d5b4
refs/heads/master
2021-04-27T00:09:20.894641
2018-03-04T06:59:37
2018-03-04T06:59:37
123,757,711
1
0
Apache-2.0
2020-01-17T03:15:02
2018-03-04T04:47:37
C++
UTF-8
C++
false
false
387
cpp
Chunk.cpp
/* * Chunk.cpp * * Created on: 27/06/2013 * Author: yuri */ #include "Chunk.h" Chunk::Chunk() { // TODO Auto-generated constructor stub chunk = NULL; } Chunk::~Chunk() { // TODO Auto-generated destructor stub Mix_FreeChunk(chunk); } void Chunk::loadFile(string path) { chunk = Mix_LoadWAV(path.c_str()); } void Chunk::playSound() { Mix_PlayChannel(-1, chunk, 0); }
8b729a58a961f17228f9c53458849292cc393b7e
bf634993187db67766662c635879caf545b10d3d
/deep500/frameworks/reference/custom_operators/cpp/operators/reshape_op.cpp
3e99cafc115318f0840933c2bcd5a358a1ecc859
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
deep500/deep500
e94b1fa067466adf7b6b4a2d7bba06a6f9a07a3c
cd9b21ec9d494388d5e44ac1057d9bedea44d9ba
refs/heads/master
2022-06-02T19:26:10.368021
2022-05-23T12:01:31
2022-05-23T12:01:31
153,253,963
93
28
BSD-3-Clause
2022-05-23T12:01:32
2018-10-16T08:53:53
Python
UTF-8
C++
false
false
2,252
cpp
reshape_op.cpp
#include <deque> #include "deep500/deep500.h" #include "../utility/tensor/copy_data.hpp" #include "../utility/tensor/set_all.hpp" template<typename T> class ReshapeLayer : public deep500::CustomOperator{ protected: std::deque<uint32_t> m_input_shape; uint32_t m_input_size; int64_t m_output_rank; public: //constructor ReshapeLayer(const std::deque<uint32_t> input_shape, const int64_t output_rank) { m_input_shape = input_shape; //compute numpber of elements in input m_input_size = 1; for(const auto& elem: input_shape) m_input_size *= elem; m_output_rank = output_rank; } //copy constructor //destructor virtual ~ReshapeLayer() {} //member functions virtual bool supports_cuda() { return false; } void forward(const T *input_tensor, const int64_t *input_tensor2, T *output_tensor) { /* ONNX notation: data = input reshaped = output */ utilityTensor::copy_data(m_input_size, input_tensor, output_tensor); return; } void backward( const T *nextop_grad, const T *fwd_input_tensor, const int64_t *fwd_input_tensor2, const T *fwd_output_tensor, T *input_tensor_grad, int64_t *input_tensor2_grad) { utilityTensor::copy_data(m_input_size, nextop_grad, input_tensor_grad); utilityTensor::set_all_zero(m_output_rank, input_tensor2_grad); return; } }; D500_EXPORTED void *create_new_op(deep500::tensor_t *input_descriptors, int num_inputs, deep500::tensor_t *param_descriptors, int num_params, deep500::tensor_t *output_descriptors, int num_outputs) { std::deque<uint32_t> input_tensor_shape( input_descriptors[0].sizes, input_descriptors[0].sizes + input_descriptors[0].dims ); int64_t output_tensor_rank = input_descriptors[1].sizes[0]; return new ReshapeLayer<DTYPE>(input_tensor_shape, output_tensor_rank); } D500_REGISTER_OP(ReshapeLayer<DTYPE>);
8f6fd2a412d5dae07ed7bffa91fd5081363d1a61
1063f7e13f50fa0fee6723a77dc533d786e3082f
/trunk/tools/ProduceTester/ProduceTester/DT6000功能性测试/DT6000被测设备端/PC端/FunctionTest/SerialPortTest.cpp
bc41365431dfa2178a62e367d0f93a6dc582fc26
[]
no_license
zjm1060/HandSet
9e9b8af71ee57a7b90a470473edb72ef7b03c336
59a896e38996fe9f9b549316974bf82ffa046e1e
refs/heads/master
2022-12-21T19:52:10.349284
2017-03-10T08:20:14
2017-03-10T08:20:14
112,681,985
0
0
null
2020-09-25T01:00:09
2017-12-01T01:50:46
C++
GB18030
C++
false
false
9,410
cpp
SerialPortTest.cpp
#include <Windows.h> #include <atlstr.h> #include "connect.h" #include "testBase.h" #include "testManager.h" #include "SerialPortTest.h" #include "assertMsg.h" //将全功能串口的各功能线编号 enum SIGNAL_LINE_INDEX { LINE_DCD=0, LINE_DTR, LINE_DSR, LINE_RTS, LINE_CTS, LINE_RI, LINE_RXD, LINE_TXD, }; //按SIGNAL_LINE_INDEX编号排列的信号线的名称 const WCHAR *szPinName[8] = {L"(1)DCD", L"(4)DTR", L"(6)DSR", L"(7)RTS", L"(8)CTS",L"(9)RI", L"RXD", L"(3)TXD"}; //定义串口测试在通信线路上传递的数据包 #pragma pack(push) #pragma pack(1) typedef struct __SERIAL_CMD_PACK { UINT32 uiSingalMask; //表征测试信号线的掩码 BYTE pData[256]; //如果是发送功能表征的是需要测试串口发送的数据 }SerialCmdPacket; #pragma pack(pop) CSerialPortTest::CSerialPortTest(): m_iTestStepCount(0), m_iTestStep(SERIAL_PORT_TEST_CTL_LINE) { } CSerialPortTest::~CSerialPortTest() { } BOOL CSerialPortTest::Init(const WCHAR *strIniFile, int index,CTestManager *pManager) { WCHAR strSection[]=L"SERIALTest_\0\0"; strSection[11]=L'1'+index; //读取测试项的名字 int nRet; nRet=GetPrivateProfileString(strSection,L"TestName",L"串口1", m_strTestName,31,strIniFile); m_pManager=pManager; m_uiCmd=index+CMD_TEST_SERIAL1; //读取本地串口号 m_iLocalPort=GetPrivateProfileInt(strSection,L"LocalPort",0,strIniFile); //读取CE端要测试的串口类型 m_iSerialType=GetPrivateProfileInt(strSection,L"SerialType",0,strIniFile); //读取串口传输的数据包长度 m_iDataLen=GetPrivateProfileInt(strSection,L"DataLen",100,strIniFile); m_iBraudRate =GetPrivateProfileInt(strSection,L"BraudRate",CBR_115200,strIniFile); return TRUE; } TEST_STATUS CSerialPortTest::OnBeginTest(CConnect *pConnect) { BOOL bClientSucess=FALSE; //客户端串口打开是否成功 if(m_iSerialType ==0) { m_iTestStep=SERIAL_PORT_TEST_RECV; m_iTestStepCount=0; } else { m_iTestStep=SERIAL_PORT_TEST_CTL_LINE; m_iTestStepCount=0; } m_uiErrMask=0; __try { if (!m_xCom.Open(m_iLocalPort+1,m_iBraudRate) ) { WCHAR str[256]; swprintf(str,L"打开本机串口%d失败",m_iLocalPort+1); m_pManager->MessageBox(str,L"串口测试",MB_OK|MB_ICONERROR); return TEST_ERROR; } PACKET pa={m_uiCmd,SERIAL_PORT_TEST_OPEN}; int nRet=pConnect->SendAPacket(&pa); if (nRet >0) { nRet=pConnect->RecvAPacket(&pa,10000); if (nRet >0) { TEST_INFO_TRANSFER *pInfoT=(TEST_INFO_TRANSFER *)pa.pData; if (pInfoT ->bError) { TEST_INFO ti; TestInfoTransferToLocal(&ti,pInfoT); m_pManager->MessageBox(ti.strErr,L"串口测试",MB_OK|MB_ICONERROR); return TEST_ERROR; } bClientSucess=TRUE; return TEST_NORMAL; } } return TEST_CONNECTDOWN; } __finally { if (!bClientSucess) { m_xCom.CloseCom(); } } } TEST_STATUS CSerialPortTest::OnEndTest(CConnect *pConnect) { PACKET pa={m_uiCmd,SERIAL_PORT_TEST_CLOSE}; m_xCom.CloseCom(); int nRet=pConnect->SendAPacket(&pa); if (m_uiErrMask !=0) { //输出错误信息 int index=0; CString strError=_T("检测到不正常的线有:"); for (;index <=(int)LINE_TXD;index++ ) { if (m_uiErrMask & (1<<(int)index) ) { strError+=L" "; strError+=szPinName[(int)index ]; } } m_pManager->WriteLog(this,strError); m_pManager->MessageBox(strError,L"串口测试",MB_OK); } if (nRet >0) { nRet=pConnect->RecvAPacket(&pa,5000); if (nRet >0) { TEST_INFO_TRANSFER *pInfoT=(TEST_INFO_TRANSFER *)pa.pData; if (pInfoT ->bError) { TEST_INFO ti; TestInfoTransferToLocal(&ti,pInfoT); m_pManager->MessageBox(ti.strErr,L"串口测试",MB_OK|MB_ICONERROR); return TEST_ERROR; } return TEST_NORMAL; } } return TEST_CONNECTDOWN; } TEST_STATUS CSerialPortTest::ExcuteOneTest(CConnect *pConnect) { switch (m_iTestStep) { case SERIAL_PORT_TEST_CTL_LINE: return ExcuteOneCTLLinTest(pConnect); case SERIAL_PORT_TEST_RECV: return ExcuteOneRecvTest(pConnect); case SERIAL_PORT_TEST_SEND: return ExcuteOneSendTest(pConnect); default: return TEST_NORMAL; } return TEST_NORMAL; } int CSerialPortTest::GetShouldTestTimes()const { assertMsg(m_iSerialType ==SERIAL_PORT_TYPE_SIMPLE || m_iSerialType ==SERIAL_PORT_TYPE_FULL_FUNC, L"串口类型不支持") if (m_iSerialType ==SERIAL_PORT_TYPE_FULL_FUNC) { return 12; } else { return 6; } } TEST_STATUS CSerialPortTest::ExcuteOneRecvTest(CConnect *pConnect) { SerialCmdPacket scp; PACKET pa; scp.uiSingalMask=0; for (int i=0;i<m_iDataLen;i++) { scp.pData[i]=rand(); } int nRet=pConnect->SendAPacket(m_uiCmd,SERIAL_PORT_TEST_RECV,sizeof(scp), (BYTE *)&scp); if (nRet >0) { nRet=pConnect->RecvAPacket(&pa,5000); if (nRet >0) { m_xCom.WriteNByte(scp.pData,m_iDataLen); nRet=pConnect->RecvAPacket(&pa,15000); if (nRet >0) { m_uiTestCount++; m_iTestStepCount++; if (m_iTestStepCount >=3) { m_iTestStepCount=0; m_iTestStep=SERIAL_PORT_TEST_SEND; } TEST_INFO_TRANSFER *pInfo=(TEST_INFO_TRANSFER *)pa.pData; if (pInfo ->bError) { //出现了错误 TEST_INFO ti; TestInfoTransferToLocal(&ti,pInfo); m_uiTestErrCount++; m_pManager->WriteLog(this,ti.strErr); m_uiErrMask |=1<<LINE_RXD; return TEST_ERROR; } else { //校验数据 if (memcmp(scp.pData,pInfo->strErr,m_iDataLen) !=0) { m_uiTestErrCount++; m_pManager->WriteLog(this,L"数据校验错误"); m_uiErrMask |=1<<LINE_RXD; return TEST_ERROR; } return TEST_NORMAL; } } } } return TEST_CONNECTDOWN; } TEST_STATUS CSerialPortTest::ExcuteOneSendTest(CConnect *pConnect) { SerialCmdPacket scp; PACKET pa; scp.uiSingalMask=0; for (int i=0;i<m_iDataLen;i++) { scp.pData[i]=rand(); } m_xCom.ClearRecv(); DWORD Err; COMSTAT stat; m_xCom.ClearCommError(&Err,&stat); int nRet=pConnect->SendAPacket(m_uiCmd,SERIAL_PORT_TEST_SEND,sizeof(scp), (BYTE *)&scp); if (nRet >0) { nRet=pConnect->RecvAPacket(&pa,1500); } if (nRet <=0) { return TEST_CONNECTDOWN; } BYTE buf[256]; size_t siReturn=0; m_uiTestCount++; m_iTestStepCount++; if (m_iTestStepCount >=3) { m_iTestStepCount=0; m_iTestStep=SERIAL_PORT_TEST_CTL_LINE; } if (!m_xCom.ReadNByteTimeOut(buf,m_iDataLen,5000, &siReturn)) { if (siReturn>0) { m_pManager->WriteLog(this,L"串口发送的数据出现丢失"); } else { m_pManager->WriteLog(this,L"未收到串口发送的数据"); } m_uiTestErrCount++; m_uiErrMask |=1<<LINE_TXD; return TEST_ERROR; } //校验数据 if (memcmp(scp.pData,buf,m_iDataLen) !=0) { m_uiTestErrCount++; m_pManager->WriteLog(this,L"数据校验错误"); m_uiErrMask |=1<<LINE_TXD; return TEST_ERROR; } return TEST_NORMAL; } TEST_STATUS CSerialPortTest::ExcuteOneCTLLinTest(CConnect *pConnect) { TEST_INFO_TRANSFER *pTit; PACKET pa; UINT32 t=m_iTestStepCount; m_iTestStepCount++; if (m_iTestStepCount >6) { m_iTestStep=SERIAL_PORT_TEST_RECV; m_iTestStepCount=0; } int nRet=pConnect->SendAPacket(m_uiCmd,SERIAL_PORT_TEST_CTL_LINE, sizeof(t),(BYTE *)&t); if (nRet >0) { nRet =pConnect->RecvAPacket(&pa,3000); if (nRet >0) { m_uiTestCount++; pTit=(TEST_INFO_TRANSFER *)pa.pData; if (pTit->bError) { m_uiTestErrCount++; m_uiErrMask |=1<<t; return TEST_ERROR; } return TEST_NORMAL; } } return TEST_CONNECTDOWN; }
f72ba03e521640638ab0a344d55e9ec3c987e600
e79cb86744b9cc5d46912f2f9acdb5ffd434f745
/src/dpl/src/Grid.cpp
02647d5bd3fe93a8e122fa10a57f9a1a194a6bda
[ "BSD-3-Clause", "MPL-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
The-OpenROAD-Project/OpenROAD
555cbb00ec250bb09b9e4f9a7d1454e7ac7a01ab
1f6ccc9066e7df4509ed391d87b01eadb4b3b197
refs/heads/master
2023-08-31T05:35:25.363354
2023-08-31T05:04:27
2023-08-31T05:04:27
218,110,222
979
461
BSD-3-Clause
2023-09-14T21:51:36
2019-10-28T17:48:14
Verilog
UTF-8
C++
false
false
23,057
cpp
Grid.cpp
///////////////////////////////////////////////////////////////////////////// // Original authors: SangGi Do(sanggido@unist.ac.kr), Mingyu // Woo(mwoo@eng.ucsd.edu) // (respective Ph.D. advisors: Seokhyeong Kang, Andrew B. Kahng) // Rewrite by James Cherry, Parallax Software, Inc. // // Copyright (c) 2019, The Regents of the University of California // Copyright (c) 2018, SangGi Do and Mingyu Woo // All rights reserved. // // BSD 3-Clause License // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. /////////////////////////////////////////////////////////////////////////////// #include <boost/polygon/polygon.hpp> #include <cmath> #include <limits> #include "dpl/Opendp.h" #include "odb/dbTransform.h" #include "utl/Logger.h" namespace dpl { using std::max; using std::min; using utl::DPL; using odb::dbBox; using odb::dbTransform; void Opendp::initGridLayersMap() { int grid_index = 0; grid_info_map_.clear(); grid_info_vector_.clear(); for (auto db_row : block_->getRows()) { if (db_row->getSite()->getClass() == odb::dbSiteClass::PAD) { continue; } int row_height = db_row->getSite()->getHeight(); if (grid_info_map_.find(row_height) == grid_info_map_.end()) { grid_info_map_.emplace( db_row->getSite()->getHeight(), GridInfo{ getRowCount(row_height), db_row->getSiteCount(), grid_index++}); } else { auto& grid_info = grid_info_map_.at(row_height); grid_info.site_count = divFloor(core_.dx(), db_row->getSite()->getWidth()); } } grid_info_vector_.resize(grid_info_map_.size()); for (auto& [row_height, grid_info] : grid_info_map_) { grid_info_vector_[grid_info.grid_index] = &grid_info; } debugPrint(logger_, DPL, "grid", 1, "grid layers map initialized"); } void Opendp::initGrid() { // the number of layers in the grid is the number of unique row heights // the map key is the row height, the value is a pair of row count and site // count if (grid_info_map_.empty()) { initGridLayersMap(); } // Make pixel grid if (grid_.empty()) { grid_.resize(grid_info_map_.size()); for (auto& [row_height, grid_info] : grid_info_map_) { int layer_row_count = grid_info.row_count; int index = grid_info.grid_index; grid_[index].resize(layer_row_count); } } for (auto& [row_height, grid_info] : grid_info_map_) { const int layer_row_count = grid_info.row_count; const int layer_row_site_count = grid_info.site_count; const int index = grid_info.grid_index; grid_[index].resize(layer_row_count); for (int j = 0; j < layer_row_count; j++) { grid_[index][j].resize(layer_row_site_count); for (int k = 0; k < layer_row_site_count; k++) { Pixel& pixel = grid_[index][j][k]; pixel.cell = nullptr; pixel.group_ = nullptr; pixel.util = 0.0; pixel.is_valid = false; pixel.is_hopeless = false; } } } namespace gtl = boost::polygon; using namespace gtl::operators; std::vector<gtl::polygon_90_set_data<int>> hopeless; hopeless.resize(grid_info_map_.size()); for (auto [row_height, grid_info] : grid_info_map_) { hopeless[grid_info.grid_index] += gtl::rectangle_data<int>{ 0, 0, grid_info.site_count, grid_info.row_count}; } // Fragmented row support; mark valid sites. for (auto db_row : block_->getRows()) { if (db_row->getSite()->getClass() == odb::dbSiteClass::PAD) { continue; } int current_row_height = db_row->getSite()->getHeight(); int current_row_site_count = db_row->getSiteCount(); int current_row_count = grid_info_map_.at(current_row_height).row_count; int current_row_grid_index = grid_info_map_.at(current_row_height).grid_index; if (db_row->getSite()->getClass() == odb::dbSiteClass::PAD) { continue; } int orig_x, orig_y; db_row->getOrigin(orig_x, orig_y); const int x_start = (orig_x - core_.xMin()) / db_row->getSite()->getWidth(); const int x_end = x_start + current_row_site_count; const int y_row = (orig_y - core_.yMin()) / current_row_height; for (int x = x_start; x < x_end; x++) { Pixel* pixel = gridPixel(current_row_grid_index, x, y_row); if (pixel == nullptr) { continue; } pixel->is_valid = true; pixel->orient_ = db_row->getOrient(); } // The safety margin is to avoid having only a very few sites // within the diamond search that may still lead to failures. const int safety = 20; int max_row_site_count = divFloor(core_.dx(), db_row->getSite()->getWidth()); const int xl = std::max(0, x_start - max_displacement_x_ + safety); const int xh = std::min(max_row_site_count, x_end + max_displacement_x_ - safety); const int yl = std::max(0, y_row - max_displacement_y_ + safety); const int yh = std::min(current_row_count, y_row + max_displacement_y_ - safety); hopeless[current_row_grid_index] -= gtl::rectangle_data<int>{xl, yl, xh, yh}; } std::vector<gtl::rectangle_data<int>> rects; for (auto& grid_layer : grid_info_map_) { rects.clear(); int h_index = grid_layer.second.grid_index; hopeless[h_index].get_rectangles(rects); for (const auto& rect : rects) { for (int y = gtl::yl(rect); y < gtl::yh(rect); y++) { for (int x = gtl::xl(rect); x < gtl::xh(rect); x++) { Pixel& pixel = grid_[h_index][y][x]; pixel.is_hopeless = true; } } } } } void Opendp::deleteGrid() { grid_.clear(); } Pixel* Opendp::gridPixel(int grid_idx, int grid_x, int grid_y) const { if (grid_idx < 0 || grid_idx >= grid_info_vector_.size()) { return nullptr; } GridInfo* grid_info = grid_info_vector_[grid_idx]; if (grid_x >= 0 && grid_x < grid_info->site_count && grid_y >= 0 && grid_y < grid_info->row_count) { return const_cast<Pixel*>(&grid_[grid_idx][grid_y][grid_x]); } return nullptr; } //////////////////////////////////////////////////////////////// void Opendp::findOverlapInRtree(bgBox& queryBox, vector<bgBox>& overlaps) const { overlaps.clear(); regions_rtree.query(boost::geometry::index::intersects(queryBox), std::back_inserter(overlaps)); } //////////////////////////////////////////////////////////////// void Opendp::visitCellPixels( Cell& cell, bool padded, const std::function<void(Pixel* pixel)>& visitor) const { dbInst* inst = cell.db_inst_; dbMaster* master = inst->getMaster(); auto obstructions = master->getObstructions(); bool have_obstructions = false; int site_width, row_height; if (isStdCell(&cell)) { site_width = getSiteWidth(&cell); row_height = getRowHeight(&cell); } else { site_width = site_width_; row_height = row_height_; } for (dbBox* obs : obstructions) { if (obs->getTechLayer()->getType() == odb::dbTechLayerType::Value::OVERLAP) { have_obstructions = true; Rect rect = obs->getBox(); dbTransform transform; inst->getTransform(transform); transform.apply(rect); int x_start = gridX(rect.xMin() - core_.xMin(), site_width); int x_end = gridEndX(rect.xMax() - core_.xMin(), site_width); int y_start = gridY(rect.yMin() - core_.yMin(), row_height); int y_end = gridEndY(rect.yMax() - core_.yMin(), row_height); // Since there is an obstruction, we need to visit all the pixels at all // layers (for all row heights) int grid_idx = 0; for (const auto& [layer_row_height, grid_info] : grid_info_map_) { int layer_y_start = map_coordinates(y_start, row_height, layer_row_height); int layer_y_end = map_coordinates(y_end, row_height, layer_row_height); if (layer_y_end == layer_y_start) { ++layer_y_end; } for (int x = x_start; x < x_end; x++) { for (int y = layer_y_start; y < layer_y_end; y++) { Pixel* pixel = gridPixel(grid_idx, x, y); if (pixel) { visitor(pixel); } } } grid_idx++; } } } if (!have_obstructions) { int x_start = padded ? gridPaddedX(&cell, site_width) : gridX(&cell, site_width); int x_end = padded ? gridPaddedEndX(&cell, site_width) : gridEndX(&cell, site_width); int y_start = gridY(&cell, row_height); int y_end = gridEndY(&cell, row_height); for (auto layer_it : grid_info_map_) { int layer_x_start = map_coordinates(x_start, site_width, site_width); int layer_x_end = map_coordinates(x_end, site_width, site_width); int layer_y_start = map_coordinates(y_start, row_height, layer_it.first); int layer_y_end = map_coordinates(y_end, row_height, layer_it.first); if (layer_y_end == layer_y_start) { ++layer_y_end; } if (layer_x_end == layer_x_start) { ++layer_x_end; } for (int x = layer_x_start; x < layer_x_end; x++) { for (int y = layer_y_start; y < layer_y_end; y++) { Pixel* pixel = gridPixel(layer_it.second.grid_index, x, y); if (pixel) { visitor(pixel); } } } } } } void Opendp::visitCellBoundaryPixels( Cell& cell, bool padded, const std::function< void(Pixel* pixel, odb::Direction2D edge, int x, int y)>& visitor) const { dbInst* inst = cell.db_inst_; int site_width = getSiteWidth(&cell); int row_height = getRowHeight(&cell); GridInfo grid_info = grid_info_map_.at(row_height); const int index_in_grid = grid_info.grid_index; dbMaster* master = inst->getMaster(); auto obstructions = master->getObstructions(); bool have_obstructions = false; for (dbBox* obs : obstructions) { if (obs->getTechLayer()->getType() == odb::dbTechLayerType::Value::OVERLAP) { have_obstructions = true; Rect rect = obs->getBox(); dbTransform transform; inst->getTransform(transform); transform.apply(rect); int x_start = gridX(rect.xMin() - core_.xMin(), site_width); int x_end = gridEndX(rect.xMax() - core_.xMin(), site_width); int y_start = gridY(rect.yMin() - core_.yMin(), row_height); int y_end = gridEndY(rect.yMax() - core_.yMin(), row_height); for (int x = x_start; x < x_end; x++) { Pixel* pixel = gridPixel(index_in_grid, x, y_start); if (pixel) { visitor(pixel, odb::Direction2D::North, x, y_start); } pixel = gridPixel(index_in_grid, x, y_end - 1); if (pixel) { visitor(pixel, odb::Direction2D::South, x, y_end - 1); } } for (int y = y_start; y < y_end; y++) { Pixel* pixel = gridPixel(index_in_grid, x_start, y); if (pixel) { visitor(pixel, odb::Direction2D::West, x_start, y); } pixel = gridPixel(index_in_grid, x_end - 1, y); if (pixel) { visitor(pixel, odb::Direction2D::East, x_end - 1, y); } } } } if (!have_obstructions) { int x_start = padded ? gridPaddedX(&cell) : gridX(&cell); int x_end = padded ? gridPaddedEndX(&cell) : gridEndX(&cell); int y_start = gridY(&cell, row_height); int y_end = gridEndY(&cell, row_height); for (int x = x_start; x < x_end; x++) { Pixel* pixel = gridPixel(index_in_grid, x, y_start); if (pixel) { visitor(pixel, odb::Direction2D::North, x, y_start); } pixel = gridPixel(index_in_grid, x, y_end - 1); if (pixel) { visitor(pixel, odb::Direction2D::South, x, y_end - 1); } } for (int y = y_start; y < y_end; y++) { Pixel* pixel = gridPixel(index_in_grid, x_start, y); if (pixel) { visitor(pixel, odb::Direction2D::West, x_start, y); } pixel = gridPixel(index_in_grid, x_end - 1, y); if (pixel) { visitor(pixel, odb::Direction2D::East, x_end - 1, y); } } } } void Opendp::setFixedGridCells() { for (Cell& cell : cells_) { if (isFixed(&cell)) { visitCellPixels( cell, true, [&](Pixel* pixel) { setGridCell(cell, pixel); }); } } } void Opendp::setGridCell(Cell& cell, Pixel* pixel) { pixel->cell = &cell; pixel->util = 1.0; if (isBlock(&cell)) { // Try the is_hopeless strategy to get off of a block pixel->is_hopeless = true; } } void Opendp::groupAssignCellRegions() { for (Group& group : groups_) { int64_t site_count = 0; int site_width = site_width_; int row_height = row_height_; if (!group.cells_.empty()) { site_width = getSiteWidth(group.cells_.at(0)); int max_row_site_count = divFloor(core_.dx(), site_width); row_height = getRowHeight(group.cells_.at(0)); int row_count = divFloor(core_.dy(), row_height); auto grid_info = grid_info_map_.at(row_height); for (int x = 0; x < max_row_site_count; x++) { for (int y = 0; y < row_count; y++) { Pixel* pixel = gridPixel(grid_info.grid_index, x, y); if (pixel->is_valid && pixel->group_ == &group) { site_count++; } } } } int64_t site_area = site_count * site_width * row_height; int64_t cell_area = 0; for (Cell* cell : group.cells_) { cell_area += cell->area(); for (Rect& rect : group.regions) { if (isInside(cell, &rect)) { cell->region_ = &rect; } } if (cell->region_ == nullptr) { cell->region_ = &group.regions[0]; } } group.util = static_cast<double>(cell_area) / site_area; } } void Opendp::groupInitPixels2() { for (auto& layer : grid_info_map_) { int row_height = layer.first; GridInfo& grid_info = layer.second; int row_count = divFloor(core_.dy(), row_height); int row_site_count = divFloor(core_.dx(), site_width_); for (int x = 0; x < row_site_count; x++) { for (int y = 0; y < row_count; y++) { Rect sub; // TODO: Site width here is wrong if multiple site widths are supported! sub.init(x * site_width_, y * row_height, (x + 1) * site_width_, (y + 1) * row_height); Pixel* pixel = gridPixel(grid_info.grid_index, x, y); for (Group& group : groups_) { for (Rect& rect : group.regions) { if (!isInside(sub, rect) && checkOverlap(sub, rect)) { pixel->util = 0.0; pixel->cell = &dummy_cell_; pixel->is_valid = false; } } } } } } } /* static */ bool Opendp::isInside(const Rect& cell, const Rect& box) { return cell.xMin() >= box.xMin() && cell.xMax() <= box.xMax() && cell.yMin() >= box.yMin() && cell.yMax() <= box.yMax(); } bool Opendp::checkOverlap(const Rect& cell, const Rect& box) { return box.xMin() < cell.xMax() && box.xMax() > cell.xMin() && box.yMin() < cell.yMax() && box.yMax() > cell.yMin(); } void Opendp::groupInitPixels() { for (const auto& layer : grid_info_map_) { const GridInfo& grid_info = layer.second; for (int x = 0; x < grid_info.site_count; x++) { for (int y = 0; y < grid_info.row_count; y++) { Pixel* pixel = gridPixel(grid_info.grid_index, x, y); pixel->util = 0.0; } } } for (Group& group : groups_) { if (group.cells_.empty()) { logger_->warn(DPL, 42, "No cells found in group {}. ", group.name); continue; } int row_height = group.cells_[0]->height_; int site_width = getSiteWidth(group.cells_[0]); GridInfo& grid_info = grid_info_map_[row_height]; int grid_index = grid_info.grid_index; for (Rect& rect : group.regions) { debugPrint(logger_, DPL, "detailed", 1, "Group {} region [x{} y{}] [x{} y{}]", group.name, rect.xMin(), rect.yMin(), rect.xMax(), rect.yMax()); int row_start = divCeil(rect.yMin(), row_height); int row_end = divFloor(rect.yMax(), row_height); for (int k = row_start; k < row_end; k++) { int col_start = divCeil(rect.xMin(), site_width); int col_end = divFloor(rect.xMax(), site_width); for (int l = col_start; l < col_end; l++) { Pixel* pixel = gridPixel(grid_index, l, k); pixel->util += 1.0; } if (rect.xMin() % site_width != 0) { Pixel* pixel = gridPixel(grid_index, col_start, k); pixel->util -= (rect.xMin() % site_width) / static_cast<double>(site_width); } if (rect.xMax() % site_width != 0) { Pixel* pixel = gridPixel(grid_index, col_end - 1, k); pixel->util -= ((site_width - rect.xMax()) % site_width) / static_cast<double>(site_width); } } } for (Rect& rect : group.regions) { int row_start = divCeil(rect.yMin(), row_height); int row_end = divFloor(rect.yMax(), row_height); for (int k = row_start; k < row_end; k++) { int col_start = divCeil(rect.xMin(), site_width); int col_end = divFloor(rect.xMax(), site_width); // Assign group to each pixel. for (int l = col_start; l < col_end; l++) { Pixel* pixel = gridPixel(grid_index, l, k); if (pixel->util == 1.0) { pixel->group_ = &group; pixel->is_valid = true; pixel->util = 1.0; } else if (pixel->util > 0.0 && pixel->util < 1.0) { pixel->cell = &dummy_cell_; pixel->util = 0.0; pixel->is_valid = false; } } } } } } void Opendp::erasePixel(Cell* cell) { if (!(isFixed(cell) || !cell->is_placed_)) { int row_height = getRowHeight(cell); int site_width = getSiteWidth(cell); int x_end = gridPaddedEndX(cell, site_width); int y_end = gridEndY(cell, row_height); int y_start = gridY(cell, row_height); for (auto [layer_row_height, grid_info] : grid_info_map_) { int layer_y_start = map_coordinates(y_start, row_height, layer_row_height); int layer_y_end = map_coordinates(y_end, row_height, layer_row_height); if (layer_y_end == layer_y_start) { ++layer_y_end; } for (int x = gridPaddedX(cell, site_width); x < x_end; x++) { for (int y = layer_y_start; y < layer_y_end; y++) { Pixel* pixel = gridPixel(grid_info.grid_index, x, y); if (nullptr == pixel) { continue; } pixel->cell = nullptr; pixel->util = 0; } } } cell->is_placed_ = false; cell->hold_ = false; } } int Opendp::map_coordinates(int original_coordinate, int original_step, int target_step) const { return divFloor(original_step * original_coordinate, target_step); } void Opendp::paintPixel(Cell* cell, int grid_x, int grid_y) { assert(!cell->is_placed_); int x_end = grid_x + gridPaddedWidth(cell); int grid_height = gridHeight(cell); int y_end = grid_y + grid_height; int site_width = getSiteWidth(cell); int row_height = getRowHeight(cell); GridInfo grid_info = grid_info_map_.at(row_height); const int index_in_grid = grid_info.grid_index; setGridPaddedLoc(cell, grid_x, grid_y, site_width, row_height); cell->is_placed_ = true; for (int x = grid_x; x < x_end; x++) { for (int y = grid_y; y < y_end; y++) { Pixel* pixel = gridPixel(index_in_grid, x, y); if (pixel->cell) { logger_->error( DPL, 13, "Cannot paint grid because it is already occupied."); } else { pixel->cell = cell; pixel->util = 1.0; } } } for (const auto& layer : grid_info_map_) { if (layer.first == row_height) { continue; } int layer_x = map_coordinates(grid_x, site_width, site_width); int layer_x_end = map_coordinates(x_end, site_width, site_width); int layer_y = map_coordinates(grid_y, row_height, layer.first); int layer_y_end = map_coordinates(y_end, row_height, layer.first); if (layer_x_end == layer_x) { ++layer_x_end; } if (layer_y_end == layer_y) { ++layer_y_end; } for (int x = layer_x; x < layer_x_end; x++) { for (int y = layer_y; y < layer_y_end; y++) { Pixel* pixel = gridPixel(layer.second.grid_index, x, y); if (pixel->cell) { // Checks that the row heights of the found cell match the row height // of this layer. If they don't, it means that this pixel is partially // filled by a single-height or shorter cell, which is allowed. // However, if they do match, it means that we are trying to overwrite // a double-height cell placement, which is an error. pair<int, GridInfo> grid_info_candidate = getRowInfo(pixel->cell); if (grid_info_candidate.first == layer.first) { // Occupied by a multi-height cell this should not happen. logger_->error( DPL, 41, "Cannot paint grid because another layer is already occupied."); } else { // We might not want to overwrite the cell that's already here. continue; } } pixel->cell = cell; pixel->util = 1.0; } } } cell->orient_ = gridPixel(index_in_grid, grid_x, grid_y)->orient_; } } // namespace dpl
11ad9fb451ed40b27fa259955ace4e9c332eaf87
288142619cbcc38de32f5ab0344b375c0e460dd7
/src/Game/Gameplay/Objects/Portal.cpp
c1da40afe6eca2e75fb541bb290cd0771df4888b
[]
no_license
Mati365/Rectangle-Adventures
80b443beff88d830548c4a68c9bf5e83a59d4cae
fd4d161c5207980d80755dab54fa60e3749f51f6
refs/heads/master
2020-07-06T13:22:35.198154
2013-11-03T10:56:19
2013-11-03T10:56:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,590
cpp
Portal.cpp
/* * Portal.cpp * * Created on: 09-09-2013 * Author: mateusz */ #include "Objects.hpp" #include "../Gameplay.hpp" using namespace Gameplay; Portal::Portal(float _x, float _y, usint _orientation, usint _flag) : Body(_x, _y, 32, 1), linked(nullptr), teleport_procent(0.f) { body_inside = {nullptr, _flag}; orientation = _orientation; /** BACKGROUND nie obsluguje kolizji dlatego FLYING */ type = Body::PORTAL; state = Body::FLYING; /** Obrot wymiarow platformy */ if(isHorizontalDir(_orientation)) { xor_swap<int>((int*)&w, (int*)&h); } } /** Linkowanie */ void Portal::linkTo(Portal* _linked) { linked = _linked; /** Linkowanie samego siebie */ linked->linked = this; linked->body_inside.flag = body_inside.flag == PortalBody::BODY_BEGIN ? PortalBody::BODY_END : PortalBody::BODY_BEGIN; } /** Pobieranie pozycji stencil buffora */ Rect<float> Portal::getStencilTexCoord() { Rect<float> pos; Body* _body = body_inside.body; if (!_body) { return pos; } /** Uaktualnianie wymiarow */ pos.w = _body->w; pos.h = _body->h; /** Centrowanie obiektu dla poziomych */ if (orientation == pEngine::DOWN || orientation == pEngine::UP) { pos.x = x + w / 2 - _body->w / 2; _body->x = pos.x; /** * Znajac procent mozna obliczyc zaglebienie sie * obiektu i wynurzenie po przeciwnej stronie * portalu */ switch (body_inside.flag) { /** Poczatek ciala */ case PortalBody::BODY_BEGIN: if (orientation == pEngine::UP) { /** Obiekt grawitacja wciagany w dol */ pos.h = (1.f - teleport_procent) * body_inside.body_bounds.h; /** Uaktualnianie pozycji */ pos.y = y - pos.h; _body->y = pos.y; } else { /** Wyciaganie obiektu w gore */ pos.h = body_inside.body_bounds.h; _body->y = y - teleport_procent * body_inside.body_bounds.h; pos.y = y; } break; /** Koniec ciala */ case PortalBody::BODY_END: if (orientation == pEngine::DOWN) { /** Wypadanie obiektu z gory */ _body->y = y - body_inside.body_bounds.h * (1.f - teleport_procent); pos.h = body_inside.body_bounds.h; pos.y = y; } else { /** Wysuwanie obiektu z gory */ pos.h = body_inside.body_bounds.h - (1.f - teleport_procent) * body_inside.body_bounds.h; _body->y = y - teleport_procent * body_inside.body_bounds.h; pos.y = _body->y; } break; }; } /** Centrowanie obiektu dla Pionowych */ if (orientation == pEngine::LEFT || orientation == pEngine::RIGHT) { pos.y = y - h / 2 + _body->h / 2; _body->y = pos.y; /** * Znajac procent mozna obliczyc zaglebienie sie * obiektu i wynurzenie po przeciwnej stronie * portalu */ switch (body_inside.flag) { /** Poczatek ciala */ case PortalBody::BODY_BEGIN: if (orientation == pEngine::RIGHT) { /** Obiekt grawitacja wciagany w lewo */ pos.w = body_inside.body_bounds.w; /** Uaktualnianie pozycji */ pos.x = x; _body->x = pos.x - teleport_procent * body_inside.body_bounds.w; } else { /** Wciaganie w prawo strone */ pos.w = (1.f - teleport_procent) * body_inside.body_bounds.w; pos.x = x - pos.w; _body->x = pos.x; } break; /** Koniec ciala */ case PortalBody::BODY_END: if (orientation == pEngine::LEFT) { /** Obiekt grawitacja wciagany w lewo */ pos.w = body_inside.body_bounds.w - (1.f - teleport_procent) * body_inside.body_bounds.w; /** Uaktualnianie pozycji */ pos.x = x - teleport_procent * body_inside.body_bounds.w; _body->x = pos.x; } else { /** Obiekt wyciagany w prawo */ pos.w = body_inside.body_bounds.w; /** Uaktualnianie pozycji */ pos.x = x; _body->x = x - (1.f - teleport_procent) * body_inside.body_bounds.w; } break; }; } // return pos; } /** Rysowanie */ void Portal::drawObject(Window*) { if (!linked) { return; } /** Glowny rendering */ beginStroke(0xF0F0); glLineWidth(2.f); if (body_inside.flag == PortalBody::BODY_BEGIN) { glColor3ub(255.f, 255.f, 255.f); } else { glColor3ub(155.f, 155.f, 155.f); } glBegin(GL_LINE_STRIP); glVertex2f(x, y); glVertex2f(x, linked->y); glVertex2f(linked->x, linked->y); glEnd(); endStroke(); oglWrapper::drawRect( x, y, w, h, body_inside.flag == PortalBody::BODY_END ? oglWrapper::RED : oglWrapper::GREEN, 2.f); /** Rysowanie portalu */ Body* _body = body_inside.body; if (!_body) { return; } /** Odswiezanie obiektu wewnatrz */ updateBodyInside(); Rect<float> stencil_pos = getStencilTexCoord(); /** Stencil buffer */ glEnable(GL_STENCIL_TEST); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glStencilFunc(GL_NEVER, 1, 0xFF); glStencilOp(GL_REPLACE, GL_KEEP, GL_KEEP); glStencilMask(0xFF); // ustawienie maski tego co ma być malowane glClear(GL_STENCIL_BUFFER_BIT); // czyszczenie tablicy /** Rysowanie szablonu */ glBegin(GL_QUADS); glVertex2f(stencil_pos.x, stencil_pos.y); glVertex2f(stencil_pos.x + stencil_pos.w, stencil_pos.y); glVertex2f(stencil_pos.x + stencil_pos.w, stencil_pos.y + stencil_pos.h); glVertex2f(stencil_pos.x, stencil_pos.y + stencil_pos.h); glEnd(); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glStencilMask(0x00); glStencilFunc(GL_EQUAL, 1, 0xFF); /** Rysowanie ciala */ _body->drawObject(nullptr); glDisable(GL_STENCIL_TEST); } /** Reset - wychodzenie ciala */ void Portal::exitBody() { if (!body_inside.body) { return; } Body* _body = body_inside.body; if (body_inside.flag == PortalBody::BODY_END) { /** Nowa pozycja */ Rect<float> new_pos = getStencilTexCoord(); _body->x = new_pos.x; _body->y = new_pos.y; _body->velocity.x = _body->velocity.y = 0; _body->setState(Body::NONE); /** Odpychanie ciala */ dodgeBody(_body, invertDir(orientation), 4.f); } body_inside.body = nullptr; teleport_procent = 0; if (linked) { linked->exitBody(); } } /** Odsiwezanie ciala wewnatrz */ void Portal::updateBodyInside() { if (!linked || !body_inside.body) { return; } Body* _body = body_inside.body; if (teleport_procent < 0) { exitBody(); } else if (teleport_procent < 1) { float speed_proc = 0.f; /** Wyliacznie procentu z predkosci wpadania */ if (isVertical()) { speed_proc = (float) _body->velocity.y / (float) _body->h; } else { speed_proc = (float) _body->velocity.x / (float) _body->w; } if (speed_proc < .001f) { speed_proc = .2f; } /** Dodawanie procentu */ teleport_procent += abs(speed_proc / 3); } else { /** Zerowanie */ exitBody(); Camera::getFor().scrollTo(nullptr); } /** Synchronizacja */ linked->teleport_procent = teleport_procent; } /** Wchodzenie do portalu */ bool Portal::enter(Body* body, usint _dir) { if (_dir == orientation || teleport_procent != 0 || body_inside.body || !linked || !body) { return false; } /** Odwrocenie portalu w strone obiektu */ if ((isVertical() && !isHorizontalDir(_dir)) || (isHorizontal() && isHorizontalDir(_dir))) { orientation = invertDir(_dir); body_inside.flag = PortalBody::BODY_BEGIN; linked->body_inside.flag = PortalBody::BODY_END; } /** Dolaczanie obiektu do portali */ Rect<float> body_bounds(body->x, body->y, body->w, body->h); body_inside = {body, PortalBody::BODY_BEGIN, body_bounds}; linked->body_inside = {body, PortalBody::BODY_END, body_bounds}; /** Cialo zostaje wylaczone z praw fizyki */ body_inside.body->setState(Body::FLYING | Body::HIDDEN); // return true; }
b26bb2bfd54411d9c348d5e0fbbf32d502dad84d
c7feda8bb2b63bb0b1e346d9019f261e5e5a88e2
/leetcode/621.cpp
da4054ed59ecf9fbb42894fac4a37b46bcf6dc6d
[]
no_license
EcutDavid/oj-practices
f6f05ee179b53fca436d6be33ef873033c72d895
831502fe83f7611d2031365663e8409919e2b0b0
refs/heads/master
2021-06-30T23:47:04.197213
2020-11-13T10:53:37
2020-11-13T10:53:37
152,569,918
1
0
null
null
null
null
UTF-8
C++
false
false
877
cpp
621.cpp
#include <vector> using namespace std; class Solution { public: int leastInterval(vector<char>& tasks, int n) { vector<pair<int, int>> tL(26); for (char t : tasks) { tL[t - 'A'].first++; } int ret = 0; int round = tasks.size(); while (round--) { int c = -1; for (int i = 0; i < 26; i++) { if (tL[i].first == 0) continue; bool noChoice = c == -1; bool isQuicker = !noChoice && tL[i].second < tL[c].second; bool isMore = !noChoice && tL[i].second == tL[c].second && tL[i].first > tL[c].first; if (noChoice || isQuicker || isMore) { c = i; } } int cost = tL[c].second + 1; ret += cost; for (int i = 0; i < 26; i++) { tL[i].second = max(0, tL[i].second - cost); } tL[c].second = n; tL[c].first--; } return ret; } };
ac83224cd87c68a74b1e7217a10ec883a95b9e9d
19f1daea6861f2e4f08c76f07ac0f84306d240c8
/Tools/WebServer/include/Tools/WebServer/RedirectService.h
937c761472b508042ad64e463da7363507f6ffaa
[]
no_license
erdoukki/PraeTor
e1ded122c51c45fdacf1f8733173ae509bcdd106
42173cfa97612c05a99b9913929e13f5f549e126
refs/heads/master
2021-12-23T16:29:22.260165
2017-11-18T11:22:16
2017-11-18T11:22:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
735
h
RedirectService.h
#pragma once #include <map> #include <string> #include "Tools/WebServer/IWebService.h" namespace Tools { namespace WebServer { class RedirectService : public Tools::WebServer::IWebService { public: RedirectService(const std::string &from, const std::string &to, int httpStatus); ~RedirectService(); virtual void operator()(Tools::WebServer::ConnectionContextPtr contextPtr); virtual void start(void); virtual void stop(void); private: const std::string &getStatusMessage(unsigned statusCode) const; const std::string m_from; const std::string m_to; const int m_httpStatus; std::map<unsigned, std::string> m_httpStatusMessage; }; } /* namespace WebServer */ } /* namespace Tools */
3abbb5bc5af79232def86d82a055f3aebfbbf73a
528ec322ee4552897c73c685baacff7c8afd2dce
/include/bud_cleanup.inc
82a9d09e8fdf7c8201c474052ba652f081171a69
[ "MIT" ]
permissive
siesta-project/buds
c0a1bfe9b90715c351013dff97dc1dd3570144b8
f82fa8d80fb78b46d0baf3ef215b36716e9abd41
refs/heads/master
2021-06-26T13:08:28.848172
2020-11-13T19:41:41
2020-11-13T19:41:41
51,718,630
7
0
null
null
null
null
UTF-8
C++
false
false
1,044
inc
bud_cleanup.inc
! Here we clean up a mixture of preprocessor ! statements that are defined in the ! include/[inc] files ! Excluding the _utils.inc file! ! These flags are generic #undef BUD_MOD_NAME #undef BUD_MOD_NAME_STR #undef BUD_TYPE_NAME #undef BUD_TYPE_NAME_ #undef BUD_TYPE_NAME_STR ! bud_finitestack.inc #undef BUD_FSTACK_TYPE ! bud_coll.inc #undef BUD_COLL_1 #undef BUD_COLL_2 #undef BUD_COLL_3 #undef BUD_COLL_4 #undef BUD_COLL_5 #undef BUD_COLL_6 #undef BUD_COLL_ALL_SAME ! bud_llist.inc #undef BUD_LIST_DOUBLY #undef BUD_LINKED_LIST_NAME ! bud_item #undef BUD_ITEM_TYPE ! These flags control the input sequence #undef BUD_COMMON_DECLARATIONS_H ! project-buds -- local file settings ! Anything below this line may be overwritten by scripts ! Below are non-editable settings ! Local Variables: ! mode: f90 ! f90-if-indent: 2 ! f90-type-indent: 2 ! f90-associate-indent: 2 ! f90-continuation-indent: 2 ! f90-structure-indent: 2 ! f90-critical-indent: 2 ! f90-program-indent: 2 ! f90-do-indent: 2 ! End:
63ab5368bc1e8f186c284312705fb05eb6953eba
4aa4f304b7ed19e6534c9974e323cc872ea77a06
/FriendGraph.hpp
55ffcbfa8daa38bb4a4ab784be634e5be70efaf5
[]
no_license
p2phan/6-degrees-of-Kevin-Bacon
005a752d222f00a93acf989a98833352eab58407
4f1f52c6223b49de3d73fed5287c7e9986f1da0d
refs/heads/master
2021-05-08T06:27:22.448712
2017-03-15T06:56:23
2017-03-15T06:56:23
106,618,130
0
0
null
null
null
null
UTF-8
C++
false
false
9,774
hpp
FriendGraph.hpp
/** * FriendGraph.hpp * Author: Peter Phan, A13042904 cs100wdh * Dephanie Ho A12705618 cs100wam * * Date: 03/14/2017 * * Implements a graph that shows a network of friends on Facebook. */ #ifndef FRIENDGRAPH_HPP #define FRIENDGRAPH_HPP #include <iostream> #include <fstream> #include <sstream> #include <limits> #include <queue> #include <vector> #include <unordered_set> #include <unordered_map> using namespace std; /* * class to implement nodes and contains ID of a user */ class User { private: int ID; //id of the user public: User(int id) : ID(id), dist(std::numeric_limits<int>::max()), searched(0), hits(0){} int hits; //used to store number of hits int dist; //will be used in a BFS search bool searched; //check if user node has been searched unordered_set<int> friends; //list of the user's friends /** Getter to return ID of user */ int getID() const; /** * Less-than comparison, so User will work in std::priority_queue * Parameter - other - User being compared */ bool operator<(const User& other); }; /** A 'function class' for use as the Compare class in a * priority_queue<ActorNode*>. * We will make it so that highest distance * has the highest priority */ class UserPtrComp { public: bool operator()(User*& lhs, User*& rhs) const { return *lhs < *rhs; } }; class FriendGraph { protected: unordered_map<int, User*> networks; //friend network of the user private: /** * Helper method for destructor */ void deleteAll(); int min; //smallest id int max; //largest id public: /** * Constructor */ FriendGraph(void) : min(std::numeric_limits<int>::max()), max(std::numeric_limits<int>::min()) {} /** * Destructor */ ~FriendGraph(); /** * Load the graph from a tab-delimited file of user->friend relationships * * Parameter: infilename - input file * * Return true if file was loaded successfully, false otherwise */ bool loadFromFile(const char* infilename); /** Does a BFS search to find suggestions * Parameter: user - the user from which to start the BFS * suggestions - the queue to store suggestions * */ void BFS(priority_queue<User*, vector<User*>, UserPtrComp>* q, User* user); /** Prints out the given suggestions * * Parameter: id - user to give suggestions to * v - list of suggested friends * outfilename - outfile to write to */ void printSuggestions(int id, vector<User*>* v, const char * outfilename); /** * Returns a list of suggested friends * * Parameter: user - user to search friend network from * numSuggestions - number of friends suggested to return */ void SuggestFriends(const char * outfilename); }; /* * Getter to return the user ID */ int User::getID() const { return ID; } /* * Comparison class to return the from highest hits to lowest * in the priority queue * Parameter: other - user node to compare to */ bool User::operator<(const User& other) { //Bigger hit is higher prioirty if(hits != other.hits) { return hits < other.hits; } //if number of hits are the same then lower ID //get priority return other.getID() < getID(); } /** * Load the graph from a tab-delimited file of user->friend relationships * * Parameter: infilename - input file * * Return true if file was loaded successfully, false otherwise */ bool FriendGraph::loadFromFile(const char* infilename) { //Initialize the file stream ifstream infile(infilename); //Keep reading lines until the end of file is reached while(infile) { string s; if(!getline( infile, s)) break; istringstream ss( s ); vector<string> record; //get actors that are delimited by space while(ss) { string next; //Get the next string before hitting a space //and put it in 'next' if(!getline(ss, next, ' ')) break; record.push_back(next); } if(record.size() != 2) { //we should have exactly 2 columns continue; } //Retrieve users int id1 = stoi(record[0]); int id2 = stoi(record[1]); //updates lowest and highest user id if(id1 < min) min = id1; if(id2 < min) min = id2; if(max < id1) max = id1; if(max < id2) max = id2; //If network does not already have the id, add user if(networks.find(id1) == networks.end()) { networks.insert(pair<int, User*>(id1, new User(id1) )); } if(networks.find(id2) == networks.end()) { networks.insert(pair<int, User*>(id2, new User(id2) )); } //Connect the users and their corresponding friendships User* user1 = networks[id1]; User* user2 = networks[id2]; if(user1->friends.find(id2) == user1->friends.end()) { user1->friends.insert(id2); } if(user2->friends.find(id1) == user2->friends.end()) { user2->friends.insert(id1); } } if (!infile.eof()) { cerr << "Failed to read " << infilename << "!\n"; return false; } infile.close(); return true; } /** Does a BFS search to find suggestions * * Parameter: user - the user from which to start the BFS * suggestions - the queue to store suggestion */ void FriendGraph::BFS(priority_queue<User*, vector<User*>, UserPtrComp>* q, User* user) { //Makes queue to store path user->dist = 0; queue<User*> toExplore; toExplore.push(user); //BFS runs until queue is empty while(!toExplore.empty()) { //pops to explore User* curr = toExplore.front(); toExplore.pop(); if(curr->dist == 2) break; //Checks through all the neighbors of current user auto it = curr->friends.begin(); for( ; it != curr->friends.end(); it++) { User* neighbor = networks[(*it)]; neighbor->hits++; if(neighbor->searched || neighbor == curr){ continue; } if(curr->dist+1 < neighbor->dist) { neighbor->searched = true; neighbor->dist = curr->dist+1; toExplore.push(neighbor); //Store the neighbor if the suggested friend dist is within 2 if(neighbor->dist == 2) { q->push(neighbor); } } } } } /** * Print suggested friend list * * Parameter: id - user to give suggestions to * suggest - vector that holds list of suggested friends * outfilename - outfile to write info to */ void FriendGraph::printSuggestions(int id, vector<User*>* suggest, const char* outfilename) { //initializes out file stream ofstream outfile(outfilename); outfile << "For user " << id << ", we suggest the following friends " << "in order of number of mutual friends:" << endl; //prints out sugestions in order of most common mutuals for(int i = 0; i < suggest->size(); i++) { User* user = suggest->at(i); outfile << user->getID() << " have " << user->hits << " mutuals" << endl; } } /** * Returns a list of suggested friends * * Parameter: user - user to search friend network from * numSuggestions - number of friends suggested to return */ void FriendGraph::SuggestFriends(const char * outfilename) { int numSuggestions; //number of suggestions to print int id; // the ID to search for //Prompt the program to give a user do { cout << "Please enter an ID from " << min << "-" << max << " to find suggestions. -1 to quit" << endl; cin >> id; if(id == -1){ return; } } while(id <= min && max < id); //Prompt the program to give the number of suggestions do { cout << "Please enter the number of suggestions you would like " << "between 1 and 50 inclusive. -1 to quit" << endl << "We will try to get as many suggestions as possible :)" << endl; cin >> numSuggestions; if(numSuggestions== -1){ return;} } while(id <= 0 && 50 < id); if(networks.find(id) == networks.end()) { cout << "User " << id << " does not exist" << endl; return; } //initilizes data structures User* user = networks[id]; priority_queue<User*, vector<User*>, UserPtrComp> q; vector<User*> suggest; //uses to print out suggestions BFS(&q, user); //Put suggested users in priority queue to pop out the most hits user int counter = 0; while(!q.empty() && counter < numSuggestions) { User* curr = q.top(); q.pop(); suggest.push_back(curr); counter++; } //print the suggested list of friends to the outfile printSuggestions(id, &suggest, outfilename); } /** * Helper method for destructor */ void FriendGraph::deleteAll() { for(auto it = networks.begin(); it != networks.end(); it++) { delete (*it).second; } } /* Destructor */ FriendGraph::~FriendGraph(){deleteAll();} #endif //FRIENDGRAPH_HPP
8fd38394ae90c36b55d2b5516784b50133e35e6d
231fa411e61ad9564e7e75f9d55713b5ea259506
/ppl1(w2).cpp
da6915cc6fa99f55f29e4bc7a93ccb31fd948042
[]
no_license
ujjwal56/principal-of-programming-languages
8d4f6345e17c1da9a4e30275a6d5bf35171bbc64
4541a685503518720783770e694362b11f358431
refs/heads/master
2020-04-19T22:52:10.005194
2019-03-28T07:08:46
2019-03-28T07:08:46
168,481,291
0
0
null
null
null
null
UTF-8
C++
false
false
215
cpp
ppl1(w2).cpp
#include<iostream> using namespace std; int main() { int sum=0,num,d=0; cout<<"enter the number"; cin>>num; while( num != 0) { d=num%10; sum=sum+d; num=num/10; } cout<<"result is"<<sum; }
c74764cfd4bb71400b42e8b03a98db51359381a3
c44fb0847f55d5a9a187e6e9518c1fa28957c480
/AdvancedLib/CompileLib/AbstractSyntaxTree/IST2ASTConverter.cpp
d9c0535086cc7cc25ea1ce613cb1beff43ebbde1
[]
no_license
Spritutu/hiquotion_cpp
54567d5d0e62c36415d94f851ef9631932480e33
39e35053f979f7b613075c6a582fe58333c95dff
refs/heads/master
2022-03-29T13:08:54.752069
2020-01-21T05:00:19
2020-01-21T05:00:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
549
cpp
IST2ASTConverter.cpp
// IST2ASTConverter.cpp: implementation of the IST2ASTConverter class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "IST2ASTConverter.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// IST2ASTConverter::IST2ASTConverter() { } IST2ASTConverter::~IST2ASTConverter() { }
32a35e1a3b80615ed78b2f9b156de2c66ebf9663
73186061592adaab2f8b2e79f072609b28af51b1
/DiploidEngine/DiploidEngine/src/header/GraphicsFunction/Graphics.h
b58b0173b7925faf49f469dc6ba282bffe297ad0
[]
no_license
Keioh/openFrameworks
09a5b4d4cb9d8dda62ce0d4d79555ac05a4f9a9e
bbd8c15413c2533edac07c97c29ed2e5f177c575
refs/heads/master
2020-04-06T03:51:55.773795
2018-06-23T12:06:54
2018-06-23T12:06:54
83,141,813
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
188
h
Graphics.h
//グラフィクス管理クラス #pragma once #include "ofMain.h" #include "GraphicsFunction/GraphicsLoader.h" class Graphics { private: public: GraphicsLoader graphics_loader; };
8a090278a600e1e7bae81c27dc6566ad01ad003f
0e5fbe9927923daba7173e6ef39c2fddc01b2e60
/stl/list/public.h
e39825fd8ddd10f09b99b072d587f91edf01d76c
[]
no_license
easyfun/cplusplus_exercise
cd7737a6b2382da28c034a792a960c93ae7f8cd8
e27def85d98943a0608c3da7c06f3dff9d41f24c
refs/heads/master
2020-04-08T19:56:06.407366
2015-03-30T00:17:58
2015-03-30T00:17:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
489
h
public.h
#ifndef _PUBLIC_H #define _PUBLIC_H #include<list> #include<iostream> using namespace std; //显示整型list元素 void PrintListContents(const list<int>& listInput) { if(listInput.size()>0) { cout<<"{ "; list<int>::const_iterator ci; for (ci=listInput.begin(); ci!=listInput.end(); ci++) { cout<<*ci<<" "; } cout<<"}"<<endl<<endl; } else cout<<"list is empty"<<endl; } #endif
9227b2bb83a44563f281bc4a5b3e61591cc32e00
b8765e762b1087505189506a35cffce43638fba7
/question/CCF/2013_12/2/x.cpp
f81b24c042ee8a47e5cd6a9f3d2f2659da66446c
[]
no_license
yaoling1997/desktop
0d0782f44cca18ac97e806e919fc7c6446872a00
1053d1a30b1e45e82ceec90cfd3b31eec361c1e2
refs/heads/master
2022-02-17T12:50:54.349782
2019-05-18T06:13:03
2019-05-18T06:13:03
120,167,243
0
0
null
null
null
null
UTF-8
C++
false
false
649
cpp
x.cpp
#include<cstdio> #include<cstdlib> #include<algorithm> #include<string> #define pb push_back using namespace std; const int maxn= 1e5; string s; char t[maxn]; char c; char getSbm(string s){ int i,re= 0; for (i= 0;i<9;i++) re= re+(i+1)*(s[i]-'0'); re%= 11; if (re==10) return 'X'; else return '0'+re; } int main() { //freopen("1.in","r",stdin); //freopen("1.out","w",stdout); scanf("%s",t); s= ""; s.pb(t[0]); s.pb(t[2]); s.pb(t[3]); s.pb(t[4]); s.pb(t[6]); s.pb(t[7]); s.pb(t[8]); s.pb(t[9]); s.pb(t[10]); s.pb(t[12]); c= getSbm(s); if (c==t[12]) printf("Right"); else { t[12]= c; printf("%s",t); } return 0; }
464e39a9d5fdf86f5c35cb21c913ff941cfce701
a05e6ce8088ffb946c6e7278f271ef7cd9ee5f55
/UVA-10226.cpp
6ba4c0cd76ba2428e9d651707e15675b139d2d44
[]
no_license
workat60474/UVA
3b2ae74e9ab5bd60d75a3efb96f52e38f724592e
39b2b638f2bb541d098710e1ca9ddf86c3cce35c
refs/heads/master
2021-06-18T05:10:05.154130
2017-06-17T06:00:46
2017-06-17T06:00:46
84,585,517
1
0
null
null
null
null
UTF-8
C++
false
false
702
cpp
UVA-10226.cpp
#include<cstdio> #include<string> #include<iostream> #include<map> using namespace std; int main() { int test_num; map<string,int>::iterator iter; while(scanf("%d",&test_num)!=EOF) { //printf("test=%d\n",test_num); getchar(); string tree_name; getline(cin,tree_name); //cout<<"tree_name="<<tree_name<<endl; int sum=0; for(int i=0;i<test_num;i++) { sum=0; if(i>0) printf("\n"); map<string,int>treeset; while(getline(cin,tree_name) && tree_name!="") { treeset[tree_name]++; sum++; } for(iter=treeset.begin();iter!=treeset.end();iter++) { cout<<iter->first; printf(" %.4f\n",(double)iter->second/sum*100); } treeset.clear(); } } return 0; }
99870dec97d496457320c3e4112947e94747f07e
3001fcfe996fb82ad6cfb1843a71e54434975373
/2013/03/cfr169/e.cpp
42d638c4583a337f625b4a5e12e0fadde24a72ff
[]
no_license
niyaznigmatullin/nncontests
751d8cde9c18feae165dd7d1b0ea2cf1f075d39c
59748ce96f521e832c5a511ba849a523e35ad469
refs/heads/master
2022-07-14T08:33:27.055971
2022-06-28T17:58:23
2022-06-28T17:58:23
36,932,376
7
1
null
null
null
null
UTF-8
C++
false
false
2,918
cpp
e.cpp
#include <cstdio> const int MAXN = 222222; const int MAXF = 222222; int ss[MAXN], ff[MAXN], md[MAXN], vv[MAXN], id[MAXN], de[MAXN]; int fcaca[MAXN * 10]; int * f[MAXN]; int * allf; int getSum(int * f, int m, int x) { int ret = 0; for (int i = x; i >= 0; i = (i & (i + 1)) - 1) { ret += f[i]; } return ret; } void add2(int * f, int m, int x, int y) { for (int i = x; i < m; i |= i + 1) { f[i] += y; } } void addValue(int * f, int m, int x, int y) { for (int i = x; i >= 0; i = (i & (i + 1)) - 1) { f[i] += y; } } int getValue(int * f, int m, int x) { int ret = 0; for (int i = x; i < m; i |= i + 1) { ret += f[i]; } return ret; } int main() { int n, q; scanf("%d %d", &n, &q); for (int i = 0; i <= n; i++) ss[i] = ff[i] = -1; int cf = 0; for (int i = 0; i + 1 < n; i++) { int v, u; scanf("%d %d", &v, &u); if (v != 1) { if (ss[v] >= 0) ff[v] = u; else ss[v] = u; } else { vv[cf++] = u; } if (u != 1) { if (ss[u] >= 0) ff[u] = v; else ss[u] = v; } else { vv[cf++] = v; } } int * fca = fcaca; allf = fca; fca = fca + (2 * MAXF); for (int it = 0; it < cf; it++) { int i = vv[it]; int last = 1; int cnt = 1; while (i >= 0) { id[i] = it; de[i] = cnt++; int j = ss[i] ^ ff[i] ^ last; last = i; i = j; } md[it] = cnt + 1; f[it] = fca; fca = fca + cnt + 1; } for (int i = 0; i < q; i++) { int type, v; scanf("%d %d", &type, &v); if (type == 0) { int add, d; scanf("%d %d", &add, &d); if (v == 1) { add2(allf, MAXF, MAXF - d - 1, add); } else if (de[v] > d) { addValue(f[id[v]], md[id[v]], de[v] - d - 1, -add); int till = de[v] + d; if (till > md[id[v]] - 1) till = md[id[v]] - 1; addValue(f[id[v]], md[id[v]], till, add); } else { addValue(f[id[v]], md[id[v]], 0, -add); int till = de[v] + d; if (till > md[id[v]] - 1) till = md[id[v]] - 1; addValue(f[id[v]], md[id[v]], till, add); add2(allf, MAXF, MAXF - (d - de[v]) - 1, add); till = d - de[v]; if (till > md[id[v]] - 1) till = md[id[v]] - 1; addValue(f[id[v]], md[id[v]], till, -add); } } else { int ans = v == 1 ? 0 : getValue(f[id[v]], md[id[v]], de[v]); printf("%d\n", ans + getSum(allf, MAXF, MAXF - de[v] - 1)); } } }
86369d5deef18758bd4ed84be992ae0f9a8fef98
05cdd8362ba8686fe1dd4f2d1c47b337d94ce923
/Google Kickstart 2020/Round-A/Plates.cpp
445b9d1e680b0edd3e95fa5e2655127b5d395218
[]
no_license
vismit2000/compCode-II
162411aed8483cf0f3c7cc67488aed4b78aeb3a5
eaad7d1475d2314de533df9017d5788e9a30b0b2
refs/heads/master
2022-12-23T04:54:21.431142
2022-12-17T04:51:15
2022-12-17T04:51:15
191,161,603
2
1
null
null
null
null
UTF-8
C++
false
false
1,612
cpp
Plates.cpp
// Approach: Brute Force (That's why only small testcase passed, not the large one) #include <bits/stdc++.h> using namespace std; #define ll long long #define INF 0x3f3f3f3f #define MOD 1000000007 #define boost ios_base ::sync_with_stdio(0); cin.tie(0); int main() { boost; int t; cin >> t; for(int q = 1; q <= t; q++) { cout << "Case #" << q << ": "; ll n, k, p; cin >> n >> k >> p; vector < vector < ll > > plates(n, vector < ll > (k+1, 0)); for(int i = 0; i < n; i++) { for(int j = 1; j <= k; j++) { cin >> plates[i][j]; plates[i][j] += plates[i][j-1]; } } if(n == 1) { cout << plates[0][p] << endl; } else if(n == 2) { int j; ll ans = 0; for(int i = 0; i <= k; i++) { j = p-i; if(j > k || j < 0) continue; ans = max(ans, plates[0][i] + plates[1][j]); } cout << ans << endl; } else if(n == 3) { int u; ll ans = 0; for(int i = 0; i <= k; i++) { for(int j = 0; j <= k; j++) { u = p - i - j; if(u > k || u < 0) continue; ans = max(ans, plates[0][i] + plates[1][j] + plates[2][u]); } } cout << ans << endl; } } return 0; }
4de6a4547275c935e7b310ed9c1411a624ecd453
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_2692487_1/C++/aechavarria/a2.cpp
1e933ea2fefbb12c18ed9ade2a22f18a7291c25f
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,447
cpp
a2.cpp
using namespace std; #include <algorithm> #include <iostream> #include <iterator> #include <numeric> #include <sstream> #include <fstream> #include <cassert> #include <climits> #include <cstdlib> #include <cstring> #include <string> #include <cstdio> #include <vector> #include <cmath> #include <queue> #include <deque> #include <stack> #include <list> #include <map> #include <set> #define foreach(x, v) for (typeof (v).begin() x=(v).begin(); x !=(v).end(); ++x) #define For(i, a, b) for (int i=(a); i<(b); ++i) #define D(x) cout << #x " is " << x << endl const int MAXN = 105; const int MAXS = 1000006; const int INF = 1 << 25; int a[MAXN]; int dp[MAXN]; int main(){ int cases; cin >> cases; for (int run = 1; run <= cases; ++run){ int size, n; cin >> size >> n; for (int i = 1; i <= n; ++i) cin >> a[i]; sort(a+1, a+n+1); dp[0] = 0; int best = n; long long j = size; for (int i = 1; i <= n; ++i){ //D(a[i]); dp[i] = dp[i-1]; while (a[i] >= j){ if (j == 1){ dp[i] = INF; break; } j += j-1; dp[i]++; } assert(a[i] < j or j == 1); if (j != 1) j += a[i]; best = min(best, n-i + dp[i]); } printf("Case #%d: %d\n", run, best); } return 0; }
a65c9db3eec85cb5deedcc874bf0dca2d8d2fba7
fe30b3d8b24c6b026bc1c9b0cc6f7df6a9df2e33
/untitled1/X.cpp
0b30b81b26d611b2e3f8456e004ec4ccd97ddc3f
[]
no_license
qiang-dai/cplusplus
de1ac861269c4cd5384690f5dcd5bf065c8891e7
de6b2b86f3e0fb7800de4517ff57e97ea6dee249
refs/heads/master
2020-04-13T18:34:51.565671
2019-01-16T15:45:34
2019-01-16T15:45:34
163,378,716
0
0
null
null
null
null
UTF-8
C++
false
false
61
cpp
X.cpp
// // Created by xinmei365 on 2018/12/28. // #include "X.h"
4ab5cd6e153425fd52564fa98f5b70d92e261c51
1d18bbc37229f905e105a65e295f627f8417823b
/BaconBox/Audio/SDL/SDLMixerBackgroundMusic.h
d072dacff909cb2aca4fa49b33c2b1487a247027
[]
no_license
anhero/BaconBox
57b82a889fe12f5524267a9bb5035973d054706d
afa4b97d86be876f8375f3898667aabb3610c52c
refs/heads/develop
2021-01-17T09:35:05.986399
2017-04-07T04:36:43
2017-04-07T04:36:43
22,391,368
1
0
null
2015-03-12T19:21:30
2014-07-29T18:49:08
C++
UTF-8
C++
false
false
5,409
h
SDLMixerBackgroundMusic.h
/** * @file * @ingroup Audio */ #ifndef BB_SDL_MIXER_BACKGROUND_MUSIC_H #define BB_SDL_MIXER_BACKGROUND_MUSIC_H #include "BaconBox/PlatformFlagger.h" #include <stdint.h> #include <SDL2/SDL_mixer.h> #include <sigly.h> #include "BaconBox/Audio/BackgroundMusic.h" namespace BaconBox { /** * SDL_mixer implementation for background musics. * @ingroup Audio */ class SDLMixerBackgroundMusic : public BackgroundMusic, public sigly::HasSlots<SIGLY_DEFAULT_MT_POLICY> { friend class SDLMixerEngine; friend class sigly::Signal1<unsigned int>; public: /** * Callback function given to SDL_mixer that gets called when a music * is halted or is done playing. */ static void stoppedCurrentMusic(); /** * Sets SDL's music volume taking into account the global music volume. * @param newBaconBoxVolume BaconBox volume to set to SDL after taking * into account the global music volume. */ static void setSDLMusicVolume(int newBaconBoxVolume); /** * Sets SDL's music volume taking into account the global music volume. * @param newSDLVolume SDL volume to set to SDL after taking * into account the global music volume. */ static void setSDLMusicVolumeNoConvert(int newSDLVolume); /** * Plays the sound a given number of times. * @param nbTimes Number of times the sound will be played in loop. A * negative number is for infinite looping. */ void play(int nbTimes); /** * Stops the sound. Cannot be resumed and next time it will be played * it will start from the beginning. */ void stop(); /** * Pauses the sound. Remembers where it was paused so it can resume when * calling the resume method. */ void pause(); /** * Resumes the sound. Will only resume if the sound has been paused. */ void resume(); /** * Checks if the sound is currently playing infinitely. * @return True if the sound is currently playing infinitely. */ bool isLooping(); /** * Sets the music's volume level. * @param newVolume New volume level. If the new volume is out of * bounds, it will be set to the closest bound (minimum if it's under 0 * or maximum if it's over 100). * @see BaconBox::Sound::volume */ void setVolume(int newVolume); /** * Gets the sound's current state. Used to know if it is at its initial * state, currently playing, paused, etc. * @return Sound's current state. * @see BaconBox::AudioState::Enum */ AudioState::type getCurrentState() const; /** * Play the music with a fade in effect. * @param nbTimes Number of times to play the music in loop. Negative * value for infinite looping. * @param fadeIn Time the fade in effect will last (in seconds). */ void play(int nbTimes, double fadeIn); /** * Stops the music with a fade out effect. Cannot be resumed and next * time it will be played it will start from the beginning. * @param fadeOut Time the fade out effect will last (in seconds). */ void stop(double fadeOut); /** * Pauses the music with a fade out effect. Remembers where it was * paused so it can resume when calling the resume method. * @param fadeOut Time the fade out effect will last (in seconds). */ void pause(double fadeOut); /** * Resumes the music with a fade in effect. Will only resume if the * sound has been paused. * @param fadeIn Time the fade in effect will last (in seconds). */ void resume(double fadeIn); private: /** * Used by the fadeType boolean to mean the music is fading out on * pause. */ static const bool FADE_OUT = true; /** * Used by the fadeType boolean to mean the music is fading in on * pause. */ static const bool FADE_IN = false; /// Pointer to the current music being played. static SDLMixerBackgroundMusic *currentMusic; /// Set to true if the current music is on pause. static bool isBeingPaused; /// Pointer to the music to play. Mix_Music *music; /// Set to true if the music is infinitely looping. bool looping; /** * Set to true if the music has not been played at least once. So it * means that it is in its initial state. */ bool neverPlayed; /// Set to true if the music is currently fading in our out of pause. bool pauseResumeFading; /** * Set to true if it is fading out into pause, or false if it is * fading in to resume. */ bool fadeType; /// Time the pause/resume fading has to take. unsigned int fadeTime; /// Time at which the pause/resume fading started. unsigned int fadeStart; /** * Default constructor. Musics can only be created by the resource * manager or the music engine. */ SDLMixerBackgroundMusic(); /** * Destructor. */ ~SDLMixerBackgroundMusic(); /** * Sets the music. * @param newMusic Pointer to the music to set. */ void load(Mix_Music *newMusic); /** * Slot called when a pause/resume fading is to be updated. SDL_mixer * doesn't support fading to pause or resume a music. So we simulate * it manually. Every 100 ms, the audio engine will call this method * when the music is fading in or out to pause or resume. When the * fading is done, we ask the engine to not be called anymore on * fade updates. */ void fadeUpdate(unsigned int ticks); /** * Resets the pause and resume fading. */ void resetPauseResumeFade(); }; } #endif
109f8d0dfa0dbaca241b788be2cd334b45f0cf03
1f6526b7b35e89cfc266299b4324f6fa915cbae5
/Common/src/bin/CommThreadTest/CommThreadTest.cpp
e879700920554fb7e32e8651f39453ac21699db3
[]
no_license
gordoneill/PiBox
f850c0f41d283ef677e6142f8458c2945d008395
cb9ef7597ed23ad52cf3eb478a716680317565b5
refs/heads/master
2020-07-30T04:21:12.688533
2019-12-05T01:13:51
2019-12-05T01:13:51
210,084,062
1
0
null
null
null
null
UTF-8
C++
false
false
3,299
cpp
CommThreadTest.cpp
#include "WMsg_encoder.h" #include "msgQueueConst.h" #include "LogMgr.h" #include <string.h> #include <iostream> #include <mqueue.h> #include <stdlib.h> #include <signal.h> #include <stdio.h> enum eSystemType { CONSOLE, CONTROLLER }; mqd_t sendBox, recvBox; static void recvBoxOnData(union sigval sv) { struct mq_attr MQStat; if(mq_getattr(recvBox, &MQStat) == ERROR) { perror("mq_getattr"); return; } printf("On Entering MQStat.mq_curmsgs: %ld\n", MQStat.mq_curmsgs); WMessage msgIn; while (errno != EAGAIN) { mq_receive(recvBox, (char *) &msgIn, 8192 , NULL); // DO SOMETHING WITH THE MSG } if(mq_getattr(recvBox, &MQStat) == ERROR) { perror("mq_getattr"); return; } printf("On Exiting MQStat.mq_curmsgs: %ld\n", MQStat.mq_curmsgs); struct sigevent signal; signal.sigev_notify = SIGEV_THREAD; signal.sigev_notify_function = recvBoxOnData; signal.sigev_notify_attributes = NULL; if(mq_notify(recvBox, &signal) == ERROR) { perror("mq_notify"); return; } return; } int main(int argc, char *argv[]) { bool okay = true; eSystemType systemType = eSystemType::CONSOLE; if (argc > 1) { std::string inputSystem(argv[1]); if (inputSystem == "CONTROLLER" || inputSystem == "controller") { systemType = eSystemType::CONTROLLER; } } LogMgr logger; okay = okay && logger.setLogfile("Logs/CommThreadTest.log"); struct mq_attr attr; attr.mq_flags = 0; attr.mq_maxmsg = MAX_MESSAGES; attr.mq_msgsize = MAX_MQ_MSG_SIZE; attr.mq_curmsgs = 0; // mailbox of messages to be sent over bluetooth sendBox = mq_open(sendQueueName, O_RDWR, QUEUE_PERMISSIONS, attr); // mailbox of messges received over bluetooth recvBox = mq_open(recvQueueName, O_RDWR|O_NONBLOCK, QUEUE_PERMISSIONS, attr); if (sendBox == ERROR) { mq_unlink("/sendBox"); okay = false; logger.logEvent(eLevels::FATAL, "sendBox opening failed!"); std::cerr << "sendBox opening failed!" << std::endl; } if (recvBox == ERROR) { mq_unlink("/recvBox"); okay = false; logger.logEvent(eLevels::FATAL, "recvBox opening failed!"); std::cerr << "recvBox opening failed!" << std::endl; } struct sigevent signal; signal.sigev_notify = SIGEV_THREAD; signal.sigev_notify_function = recvBoxOnData; signal.sigev_notify_attributes = NULL; if(mq_notify(recvBox, &signal) == ERROR) { perror("mq_notify"); okay = false; } uint32_t x_dir = 0; uint32_t y_dir = 50; while (okay) { WMessage msgOut; if (systemType == eSystemType::CONTROLLER) { msgOut.type = eMsgTypes::DIRECTION; msgOut.x_dir = x_dir++; msgOut.y_dir = y_dir++; } else { msgOut.type = eMsgTypes::STATUS; } okay = okay && mq_send(sendBox, (const char *) &msgOut, sizeof(msgOut), 0) == OK; logger.logEvent(eLevels::INFO, "Placed something in sendBox. okay: %d", okay); sleep(0.5); } mq_unlink(sendQueueName); mq_unlink(recvQueueName); mq_close(sendBox); mq_close(recvBox); }
6ef8e5c477774d529e4df308ca1731e9b2c67a2e
38dc0dea190777d43bc8d2fb2ea76dd1a1ace41f
/code/25_recursion_bag.cpp
a9e6e0b5d50151f3fb159a744726be001a58ce8d
[]
no_license
chenkeshuai/algorithom
07f149be2a7711010eaa9b769f9b08a3b695cb35
740a4df01fc28a01a337a25438787d098fe32872
refs/heads/master
2023-02-10T11:02:28.601794
2021-01-12T16:58:07
2021-01-12T16:58:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,284
cpp
25_recursion_bag.cpp
#include<iostream> #include<queue> #include<stack> #include<unordered_set> #include<algorithm>//max #include<cmath>//abs using namespace std; //给定两个长度都为N的数组weights和values,weights[i]和values[i]分别代表 i号物品的重量和价值。 //给定一个正数bag,表示一个载重bag的袋子,你装的物品不能超过这个重量。返回你能装下最多的价值是多少? class Solution{ public: //===========暴力递归 int getMaxValue(vector<int>w, vector<int>v, int bag) { return process(w, v, 0, bag); } // w[index] 当前货物的重量 // v[index] 当前货物的价值 // rest:在0..index-1已经做的决定之下,当前袋子还有多少空间 // bag:袋子的总重量 // index ....后续所有货物自由选择,返回最大的价值 int process(vector<int>w, vector<int>v, int index, int rest) { if (rest < 0) { return -1; } // 重量没超 if (index == w.size()) { return 0; } // 不要当前index的货物 int p1 = process(w, v, index + 1, rest); // 要当前货物,p2next为后续得到的价值 int p2next = process(w, v, index + 1, rest - w[index]); int p2 = -1; if (p2next != -1) {//若后续失效,则p2保持失效的初值 p2 = v[index] + p2next; } return max(p1, p2); } //====================DP==================== int getMaxValueDP(vector<int>w, vector<int>v, int bag) { int n = w.size(); vector<vector<int>>dp(n+1, vector<int>(bag+1)); //dp[index][rest]表示w[index..]上选择,容纳最大重量为rest,可得到的最大价值。 for(int index=n-1; index>=0; index--){ for(int rest=0; rest<=bag; rest++){ if(rest-w[index]<0){ dp[index][rest] = dp[index+1][rest];//dp[n][rest]默认是0 } else{ dp[index][rest] = max(dp[index+1][rest], v[index] + dp[index+1][rest-w[index]]); } } } return dp[0][bag]; } }; int main(){ Solution solu; cout<<"最大价值:"<<solu.getMaxValue({3,2,5},{2,3,3},7)<<"\n"; cout<<"最大价值:"<<solu.getMaxValue({30,20,50},{2,3,3},7)<<"\n"; cout<<"最大价值:"<<solu.getMaxValueDP({3,2,5},{2,3,3},7)<<"\n"; cout<<"最大价值:"<<solu.getMaxValueDP({30,20,50},{2,3,3},7); return 0; }
00f2bd5fa8e42557b5479a05ab7324d39e0db7aa
2d9579fca8df884176077ec4d49c40e7840762e8
/dquery.cpp
685558d8952e49a76550968b774689fc54e24e60
[]
no_license
Princu7/SPOJ
20377e5a741616218d36f33ac0c50ef0f608342a
26123aa3f8d53d886f686d3b90dfa093e33794bb
refs/heads/master
2020-04-06T06:28:40.949103
2016-10-26T03:46:40
2016-10-26T03:46:40
69,349,856
0
1
null
2016-10-26T03:46:40
2016-09-27T11:29:21
C++
UTF-8
C++
false
false
2,070
cpp
dquery.cpp
# include <iostream> # include <cstdio> # include <math.h> # include <algorithm> using namespace std; int counter=0,blockSize=0,answer=0,a[30009]; struct queries { int left,right,index; }Q[200003]; int freq[1000009]={0}; bool funcSort(const queries& a,const queries& b) { if(a.left/blockSize<b.left/blockSize) return true; else if(a.left/blockSize>b.left/blockSize) return false; return a.right<b.right; } void display() { for(int i=0;i<counter;i++) printf("%d %d\n",Q[i].left,Q[i].right); } inline void addElem(int position) { freq[a[position]]++; if(freq[a[position]]==1) answer++; } inline void removeElem(int position) { freq[a[position]]--; if(freq[a[position]]==0) answer--; } int n,q; /*void displayfreq() { bool seen[10]={0}; for(int i=0;i<n;i++) { if(!seen[a[i]]) { printf("elem=%d freq=%d\n",a[i],freq[a[i]]); seen[a[i]]=1; } } }*/ int main(void) { scanf("%d",&n); blockSize=sqrt(n); for(int i=0;i<n;i++) scanf("%d",a+i); scanf("%d",&q); int left,right; while(q--) { scanf("%d%d",&left,&right); Q[counter].left=left-1; Q[counter].right=right-1; Q[counter].index=counter; counter++; } //cout<<endl; sort(Q,Q+counter,funcSort); //display(); int currentR=0,currentL=0,l,r; int ans[200004]; for(int i=0;i<counter;i++) { l=Q[i].left,r=Q[i].right; while(currentL<l) { removeElem(currentL); currentL++; } while(currentL>l) { addElem(currentL-1); currentL--; } while(currentR<=r) { addElem(currentR); currentR++; } while(currentR>r+1) { removeElem(currentR-1); currentR--; } ans[Q[i].index]=answer; //displayfreq(); } for(int i=0;i<counter;i++) printf("%d\n",ans[i]); return 0; }
2ddb05888171c01a0a43585f1e927377b796da7b
2d1716576d0342fe5f6a184046e3ceb5bf474cdd
/openCv/program4/src/program4.cpp
3ca91f151bf621593fc5529315899933b90c5922
[]
no_license
zuza3012/cpp_nauka
580aa438e884b49de1878729081e07c98bdd4ed8
feb7a4bb420fcd889551d1e0d4832a0a9f8b0c10
refs/heads/master
2020-04-12T17:10:26.547603
2019-01-09T20:55:55
2019-01-09T20:55:55
162,636,930
0
1
null
2018-12-20T23:46:21
2018-12-20T22:18:01
C++
UTF-8
C++
false
false
5,686
cpp
program4.cpp
#include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/imgcodecs.hpp> #include <string> #include <iostream> using namespace std; using namespace cv; const int alpha_slider_max = 100; int alpha_slider; double alpha; double beta1; Mat src1, src2, dst; static void on_trackbar (int , void* ){ alpha = (double) alpha_slider/alpha_slider_max; beta1 = (1.0 - alpha); addWeighted (src1, alpha, src2, beta1, 0.0, dst); imshow("Linear Blend", dst); } int main (int argc, char** argv){ if (argc == 1) { cerr << "Nieprawidlowa ilosc argumentow " << endl; return 1; } bool koniec = false; while (!koniec){ int a; cout << "Co chcesz zrobic? " << endl; cout << "1 - wyświetlenie zdjec w oryginale" << endl; cout << "2 - zmiana koloru zdjec na szare" << endl; cout << "3 - zmiana rozmiaru" << endl; cout << "4 - przyblizanie i oddalanie zdjecia pierwszego" << endl; cout << "5 - Histogram Equalization (zmiana intensywnosci zdjecia)" << endl; cout << "6 - Trackbar" << endl; cout << "0 - wyjscie z opcji " << endl; cin >> a; switch(a) { case 1: { for (int i = 1; i < argc; i++){ Mat zdjecie; string nazwaZdjecia = argv[i]; zdjecie = imread (nazwaZdjecia, 1); namedWindow (nazwaZdjecia, WINDOW_AUTOSIZE); imshow (nazwaZdjecia, zdjecie); waitKey(0); destroyWindow(nazwaZdjecia); } break; } case 2: { int licznik = 0; for(int i = 1; i< argc; i++){ Mat zdjecie; string nazwaZdjecia = argv[i]; zdjecie = imread (nazwaZdjecia, 1); Mat szare; cvtColor(zdjecie, szare, CV_RGB2GRAY ); cout << "Czy zapisac zdjecie nr " << i << " osobno?" << endl; string odp; cin >> odp; if (odp == "tak"){ string zapiszZdjecie = "./zdj_" + to_string(++licznik) + ".jpg"; imwrite (zapiszZdjecie, szare); cout << "Zmieniono na skale szarosci dla obrazu nr " << i << endl << endl; }else if (odp == "nie"){ cout << "Zmieniono zdjecie nr " << i << "w oryginalne" << endl; imwrite (nazwaZdjecia, szare); cout << "Zmieniono na skale szarosci dla obrazu nr " << i << endl << endl; }else{ cout << "Uzytkowniku, zdecyduj sie !!! " << endl; break; } } break; } case 3: { int licznik = 0; cout << "Podaj doclowy rozmiar zdjecia (szer x dl)" << endl << endl; int a, b; cin >> a >> b; for (int i = 1; i < argc; i++){ Mat zdjecie; string zapiszZdjecie = "./zdj_" + to_string(++licznik) + ".jpg"; string nazwaZdjecia = argv[i]; zdjecie = imread( nazwaZdjecia, 1); Mat zdj_pomn; resize (zdjecie, zdj_pomn, Size(a,b), 0, 0, CV_INTER_LINEAR); imwrite (zapiszZdjecie, zdj_pomn); cout << "Zmiana rozdzielczosci obrazu nr" << i << endl; } } case 4: { Mat src, dst, tmp; string nazwaOkna = "Piramida Demo"; cout << "zoom In-Out Demo" << endl; cout << "u - zoom in" << endl; cout << "d - zoom out" << endl; cout << "esc lub enter - wyjscie" << endl; src = imread (argv[1], 1); if (src.empty()){ cout << "Brak zdjecia w bazie !!!" << endl; return 1; } tmp = src; dst = tmp; imshow( nazwaOkna, dst); for(;;){//nieskonczona petla char znak = (char)waitKey(0); if(znak == 27 ) //13-enter, 27-esc break; //if ( znak == 13) // break; if(znak == 'u'){ pyrUp(tmp, dst, Size (tmp.cols*2, tmp.rows*2)); cout << "Powiekszono" << endl; } if(znak == 'd'){ pyrDown(tmp, dst, Size(tmp.cols/2, tmp.rows/2)); cout << "Pomniejszono" << endl; } imshow(nazwaOkna, dst); tmp = dst; } break; } case 5: { Mat src, dst; for(int i=1; i< argc; i++){ string nazwaOkna = argv[i]; string nazwaOkna2 = "Okno wyostreznie"; src = imread (nazwaOkna, 1); if (src.empty()){ cerr << "Blad !!!" << endl; return 1; } cvtColor(src, src, CV_RGB2GRAY); equalizeHist(src, dst); namedWindow(nazwaOkna, WINDOW_AUTOSIZE); namedWindow(nazwaOkna2, WINDOW_AUTOSIZE); imshow(nazwaOkna, src); imshow(nazwaOkna2, dst); waitKey(0); } } case 6: { /* const int alpha_slider_max = 100; int alpha_slider; double alpha; double beta; Mat src1, src2, dst; //funkcja ponizej static void on_trackbar (int , void* ){ alpha = (double) alpha_slider/alpha_slider_max; beta = (1.0 - alpha); addWeighted (src1, alpha, src2, beta, 0.0, dst); imshow("Linear Blend", dst); } */ /* //https://docs.opencv.org/3.2.0/da/d6a/tutorial_trackbar.html src1 = imread (argv[1], 1); src2 = imread (argv[2], 1); if(src1.empty()){ cerr << "Blad w czytaniu zdjecia" << endl; return 1; } if(src2.empty()){ cerr << "Blad w czytaniu zdjecia" << endl; return 1; } alpha_slider = 0; namedWindow ("Linear Blend", WINDOW_AUTOSIZE); char TrackbarName[50]; sprintf(TrackbarName, "Alpha x %d", alpha_slider_max);//Write formatted data to string createTrackbar(TrackbarName, "Linear Blend", &alpha_slider, alpha_slider_max, on_trackbar); on_trackbar(alpha_slider, 0); waitKey(0); */ } case 0: { koniec = true; break; } default://cos innego niz liczba { cout << "Nieprawidlowo podano wartosc " << endl; break; } } } //system("pause"); return 0; }
ba34a15970afa07c2a4e8aa1d63baec12873891f
6ac980a4b545f5409b742160c04167d0aaf23902
/Game.h
4de19bf03c2d26c68ca105a5d08c8d12fe17a556
[]
no_license
haydenmc/SDLHelloWorld
9d1e74e2e455b7b2d27ab68ec6c3722a851ec010
7c80a21731fb31b4b59d1f8d06445673141710c6
refs/heads/master
2020-11-25T07:32:21.315991
2019-12-28T22:29:12
2019-12-29T00:53:24
228,558,172
0
0
null
null
null
null
UTF-8
C++
false
false
732
h
Game.h
#pragma once #include "Graphic.h" #include <chrono> #include <memory> #include <SDL.h> #include <SDL_image.h> #include <vector> class Game { public: Game(int w, int h, int frameRateLimit = 0); void Start(); private: // Private methods void initialize(); void update(std::chrono::nanoseconds deltaTime); void draw(); void close(); // SDL members SDL_Window* sdlWindow = nullptr; SDL_Renderer* sdlWindowRenderer = nullptr; // Graphics std::vector<std::unique_ptr<Graphic>> graphics; // Misc members bool isInitialized = false; int windowWidth; int windowHeight; int frameRateLimit; std::chrono::nanoseconds timePerFrame; int logoX; int logoY; };
053b407649554acf5482ccccb5bf95358c4926f3
68be1b49e9625b5cf010389af16fb08b4dcf7926
/src/Game.cpp
b4e7df63aedb008decf0874d24932f1874bdef7b
[ "ISC" ]
permissive
12o3-design/open-space-project
3022ac03627129254fd1d327e950f523335cc27c
4f50e0f317b0be83a3c30ebe6d62c4930783bb8f
refs/heads/master
2021-01-13T01:07:03.429084
2016-05-09T18:46:41
2016-05-09T18:46:41
51,089,855
1
1
null
2016-02-11T03:53:08
2016-02-04T16:43:57
C++
UTF-8
C++
false
false
2,574
cpp
Game.cpp
#include "Game.h" #include "Player.h" #include "DrawComponent.h" #include <stdio.h> #include <SDL2/SDL.h> bool Game::inst_ = false; Game::Game() { if (!inst_) { window_ = NULL; renderer_ = NULL; entities_ = new Entity*[numEntities_]; for (int i = 0; i < numEntities_; i++) { entities_[i] = NULL; } running_ = false; inst_ = true; } } Game::~Game() { printf("Deleting draw component\n"); delete drawComponent_; printf("Deleting input component\n"); delete inputComponent_; printf("deleting entities\n"); delete[] entities_; SDL_DestroyWindow(window_); } bool Game::setup(const char* title, int xPos, int yPos, int width, int height, int flags) { if(SDL_Init(SDL_INIT_EVERYTHING) < 0) { printf("SDL could not initialize"); return false; } else { window_ = SDL_CreateWindow( title, xPos, yPos, width, height, flags ); if (window_ == NULL) { printf("SDL Window not initialized"); return false; } else { renderer_ = SDL_CreateRenderer(window_, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (renderer_ == NULL) { printf("SDL Renderer not initialized"); return false; } drawComponent_ = new DrawComponent(renderer_); inputComponent_ = new InputComponent(); //test code pls delete SDL_SetRenderDrawColor(renderer_, 0,0,0,255); running_ = true; printf("making the player.\n"); entities_[0] = new Player(drawComponent_); entities_[0]->setup(); printf("player made.\n"); return true; } } } void Game::handleInput() { SDL_Event event; while (SDL_PollEvent(&event) != 0) { if (event.type == SDL_QUIT) { running_ = false; } else if (event.key.repeat == 0) { Command* command = inputComponent_->handleInput(event); // if key is pushed, start event if (event.type == SDL_KEYDOWN) { command->execute(entities_[0]); } // if key released, end event else if (event.type == SDL_KEYUP) { command->release(entities_[0]); } } } } void Game::update() { for (int i = 0; i < numEntities_; i++) { if (entities_[i] != NULL) { entities_[i]->update(); } } } void Game::draw() { SDL_RenderClear(renderer_); for (int i = 0; i < numEntities_; i++) { if (entities_[i] != NULL) { entities_[i]->draw(); } } SDL_RenderPresent(renderer_); } void Game::clean() { }
943f4fc8b35f9339ad37015158334211e7e096b5
d0d0ae6bb5a300fe15b075b6857834def9435a89
/Sort a Stack Using Recursion/main.cpp
c954ad7df7a862060414c7d93dc0cb12781a915a
[]
no_license
gagan86nagpal/Interview-prep
4664eaaea3ac3e00215d3d7ac4945c25050785eb
0548575edf81e9de3b7324fcf16c8b52ccb0ec71
refs/heads/master
2021-01-16T18:17:56.974517
2017-11-04T02:08:39
2017-11-04T02:08:39
100,056,019
4
1
null
null
null
null
UTF-8
C++
false
false
1,030
cpp
main.cpp
#include <iostream> using namespace std; class Stack{ private: int top=-1; static const int max=1000; int a[1000]; public: void push(int c) { a[++top]=c; } int pop() { return a[top--]; } bool isEmpty() { return top==-1; } int getTop() { return a[top]; } void print() { int temp=top; cout<<"Stack: "; while(temp>=0) cout<<a[temp--]<<" "; cout<<"\n"; } }; void sortedInsert(Stack & st,int x) { if(!st.isEmpty() && st.getTop() > x) { int a= st.pop(); sortedInsert(st,x); st.push(a); } else { st.push(x); } } void sortStack(Stack &st) { if(!st.isEmpty()) { int x = st.pop(); sortStack(st); sortedInsert(st,x); } } int main() { Stack st; st.push(30); st.push(-5); st.push(18); st.push(14); st.push(-3); st.print(); sortStack(st); st.print(); return 0; }
c8240f4baad8eb0dbc7d408093d3545f35853796
85dceead425044850dd53bedba5cfc47e2798fea
/strtype.cpp
ecae43763751d7a1ab60656450b346d751ee9bcd
[]
no_license
goshabog/study
2d0ce16ad285bb5ca732b39fcf198e71c053b6ae
68a53836e0662f4131a845b684a8071cec342b9d
refs/heads/master
2023-08-22T07:00:59.182484
2021-10-24T18:34:16
2021-10-24T18:34:16
113,469,681
0
0
null
null
null
null
UTF-8
C++
false
false
1,223
cpp
strtype.cpp
#include <iostream> #include <cstring> using namespace std; class strtype { char *str; int len; public: strtype(char *s); strtype(int l); strtype(); ~strtype(); void show() { cout << str << endl;} strtype operator+(strtype s2); strtype &operator=(strtype s2); }; strtype::strtype(char *s) { len = strlen(s); str = new char[len +1]; strcpy(str, s); } strtype::strtype(int l) { len = l; str = new char[len +1]; } strtype::strtype() { len = 0; str = NULL; } strtype::~strtype() { delete [] str; } strtype strtype::operator+(strtype s2) { strtype temp(len + s2.len); strcpy(temp.str, str); strcpy(temp.str+len, s2.str); cout << temp.str << endl; return temp; } strtype &strtype::operator=(strtype s2) { if (len != s2.len) { if (str != NULL) delete [] str; str = new char[s2.len +1]; len = s2.len; } strcpy(str, s2.str); return *this; } int main() { char* c1 = (char*)"Hello "; char* c2 = (char*)"word!"; strtype s1(c1), s2(c2), s3; cout << "s1: "; s1.show(); cout << "s2: "; s2.show(); s3 = s1 + s2; cout << "s3: "; s3.show(); return 0; }
76948be23df91621fc4a2ad9f33d6f2ff2ca1deb
1b90be9561c10508eea59cb36c1f1665d0ef947f
/test/unit/math/mix/fun/rows_dot_self_test.cpp
4693dba707ca744ad5b68bdfb2a546dd72ae6839
[ "BSD-3-Clause", "GPL-2.0-only", "Apache-2.0" ]
permissive
stan-dev/math
473e7c1eaf11f84eaf2032c2455e12ba65feef39
bdf281f4e7f8034f47974d14dea7f09e600ac02a
refs/heads/develop
2023-08-31T09:02:59.224115
2023-08-29T15:17:01
2023-08-29T15:17:01
38,388,440
732
240
BSD-3-Clause
2023-09-14T19:44:20
2015-07-01T18:40:54
C++
UTF-8
C++
false
false
1,849
cpp
rows_dot_self_test.cpp
#include <test/unit/math/test_ad.hpp> TEST(MathMixMatFun, rowsDotSelf) { auto f = [](const auto& x) { return stan::math::rows_dot_self(x); }; Eigen::MatrixXd a00(0, 0); Eigen::VectorXd v0(0); Eigen::RowVectorXd rv0(0); stan::test::expect_ad(f, a00); stan::test::expect_ad_matvar(f, a00); stan::test::expect_ad(f, v0); stan::test::expect_ad_matvar(f, v0); stan::test::expect_ad(f, rv0); stan::test::expect_ad_matvar(f, rv0); Eigen::MatrixXd a11(1, 1); a11 << 2; stan::test::expect_ad(f, a11); stan::test::expect_ad_matvar(f, a11); Eigen::MatrixXd a12(1, 2); a12 << 2, 3; stan::test::expect_ad(f, a12); stan::test::expect_ad_matvar(f, a12); Eigen::MatrixXd a22(2, 2); a22 << 2, 3, 4, 5; stan::test::expect_ad(f, a22); stan::test::expect_ad_matvar(f, a22); Eigen::VectorXd u3(3); u3 << 1, 3, -5; Eigen::VectorXd v3(3); v3 << 4, -2, -1; stan::test::expect_ad(f, u3); stan::test::expect_ad_matvar(f, u3); Eigen::RowVectorXd ru3 = u3; stan::test::expect_ad(f, ru3); stan::test::expect_ad_matvar(f, ru3); Eigen::MatrixXd a33(3, 3); a33 << 1, 1, 1, 3, 3, 3, -5, -5, -5; Eigen::MatrixXd b33(3, 3); b33 << 4, 4, 4, -2, -2, -2, -1, -1, -1; stan::test::expect_ad(f, a33); stan::test::expect_ad_matvar(f, a33); stan::test::expect_ad(f, b33); stan::test::expect_ad_matvar(f, b33); Eigen::MatrixXd c32(3, 2); c32 << 1, 2, 3, 4, 5, 6; Eigen::MatrixXd d32(3, 2); d32 << -1, -2, -3, -4, -5, -6; stan::test::expect_ad(f, c32); stan::test::expect_ad_matvar(f, c32); stan::test::expect_ad(f, d32); stan::test::expect_ad_matvar(f, d32); Eigen::MatrixXd c23 = c32.transpose(); Eigen::MatrixXd d23 = d32.transpose(); stan::test::expect_ad(f, c23); stan::test::expect_ad_matvar(f, c23); stan::test::expect_ad(f, d23); stan::test::expect_ad_matvar(f, d23); }
2be6f817796e1695dd7e60a80f42661e77f2760c
c4b84b41e2de66623d08f9c57ffb05e1ba22b1a1
/stage_2/src/loginwindow.h
596c080da7dd4a7074407d68464ac922c45b6f59
[ "MIT" ]
permissive
FerrisChi/E-trading-platform
986dc5a833986f20aefc326a318d74dbf56bb59b
c00fce8415c9254433a1d50b3db18fb9f1421dfc
refs/heads/main
2023-08-29T10:14:21.550642
2021-10-29T09:42:05
2021-10-29T09:42:05
371,100,852
0
0
null
null
null
null
UTF-8
C++
false
false
632
h
loginwindow.h
#ifndef LOGINWINDOW_H #define LOGINWINDOW_H #include <QMainWindow> #include <QValidator> #include "product.h" #include"user.h" namespace Ui { class LoginWindow; } class LoginWindow : public QMainWindow { Q_OBJECT public: explicit LoginWindow(QWidget *parent = nullptr); ~LoginWindow(); signals: void sigLogIn(Customer customer); void sigLogIn(Shop shop); void sigSignUp(Customer customer); void sigSignUp(Shop shop); private slots: void on_okButton_clicked(); void on_cancelButton_clicked(); void on_signButton_clicked(); private: Ui::LoginWindow *ui; }; #endif // LOGINWINDOW_H
2b9417142268f650b2251cf14e7f5f77c75c3b66
ece990e9a519b09dca33f1820a2e5ea9f094683e
/src/Network/Algorithm/base64.cpp
de13d4f1dc19380f8dc4de72cb3e9d38bb40faa3
[]
no_license
rodRigocaU/Final-Proyect-Redes
9b5ed56bb4b224fa18d5472155a3ca7289b807a0
59dc888d55d43df69693ca813793d58738e768d9
refs/heads/main
2023-06-16T13:02:46.254676
2021-07-13T19:35:19
2021-07-13T19:35:19
371,067,421
0
5
null
2021-07-13T02:17:10
2021-05-26T14:40:26
C++
UTF-8
C++
false
false
1,314
cpp
base64.cpp
#include "Network/Algorithm/base64.hpp" #include <bitset> #include <iostream> #include <sstream> const int8_t base64_chars[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/+"; int32_t getIdxBase64(const int8_t& c){ for(int32_t letter = 0; letter < 65; ++letter) if(c == base64_chars[letter]) return letter; return -1; } std::string crypto::encodeBase64(const std::string& contentNormal){ std::string rawEncodedContent, encodedContent; for(int8_t letter : contentNormal){ rawEncodedContent += std::bitset<8>(int32_t(letter)).to_string(); } while(rawEncodedContent.length() % 6 != 0) rawEncodedContent.push_back('0'); for(std::size_t idx = 0; idx < rawEncodedContent.length(); idx += 6){ encodedContent.push_back(base64_chars[std::bitset<8>(rawEncodedContent.substr(idx, 6)).to_ulong()]); } return encodedContent; } std::string crypto::decodeBase64(const std::string& contentB64){ std::string rawDecodedContent, decodedContent; for(int8_t letter : contentB64){ rawDecodedContent += std::bitset<6>(getIdxBase64(letter)).to_string(); } for(std::size_t idx = 0; idx < rawDecodedContent.length(); idx += 8){ decodedContent += static_cast<int8_t>(std::bitset<8>(rawDecodedContent.substr(idx, 8)).to_ulong()); } return decodedContent; }
1b223f790a4c22cf68bf6b7f08738bef454985f2
84111e5fadf24303d6dfad2aa8113a396eed6f89
/examples/FIR/src/main.cpp
248a03ed71dc76aa442ee675640cbea37156a9de
[]
no_license
yrasik/SystemC_AMS_Lua
dcc8f1a90bcb80cc04ceed2dfb601be47054e411
771c50e58c42ac67236231ac607eda2465054734
refs/heads/main
2023-02-16T20:41:49.670505
2021-01-16T19:38:31
2021-01-16T19:38:31
321,004,655
1
0
null
null
null
null
UTF-8
C++
false
false
1,820
cpp
main.cpp
/* * This file is part of the "SystemC AMS Lua" distribution (https://github.com/yrasik/SystemC_AMS_Lua). * Copyright (c) 2020 Yuri Stepanenko. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <systemc-ams.h> #include "SCA_TDF_Lua.h" #include "SCA_TDF_Module__FIR.h" const int16_t B[55] = { 2785, -1584, -1470, -1444, -1392, -1227, -915, -457, 79, 599, 999, 1175, 1064, 653, 1, -776, -1513, -2022, -2131, -1713, -718, 811, 2739, 4852, 6888, 8582, 9703, 10095, 9703, 8582, 6888, 4852, 2739, 811, -718, -1713, -2131, -2022, -1513, -776, 1, 653, 1064, 1175, 999, 599, 79, -457, -915, -1227, -1392, -1444, -1470, -1584, 2785 }; #define FIR_ORDER ((int)(sizeof(B)/sizeof(int16_t))) int sc_main ( int argc, char *argv[] ) { sca_signal<double> node_01; sca_signal<double> node_02; Source_Lua<double, 1> Source("Source", "./from_wave.lua", 1, 20.8333/*(1/48000)*/, SC_US ); Source.out[0](node_01); FIR_Filter_to_mcu FIR("FIR", B, FIR_ORDER, 1, 16); FIR.in(node_01); FIR.out(node_02); Sink_Lua<double, 1> Sink_01("Sink_01", "./to_wave_and_table.lua"); Sink_01.in[0](node_02); sc_start(30000, SC_MS); return 0; }
6567eab96e47e8984bbc17eea82b8effd008ecb5
ca33ef9ad2e3149a9e441ba5b2ac4557ccd94150
/assignment-05-alhusseindev/task-02/main.cpp
0fd60484189cd35d32c23797809607b499826f84
[]
no_license
alhusseindev/C-Plus-Plus
f5a89bf75cb9654bf4f40393dde420bc7b028a93
9aee0bb306346137734e3d612c0198eb263e46cc
refs/heads/main
2023-02-11T07:25:52.887614
2021-01-02T19:30:54
2021-01-02T19:30:54
324,780,703
0
0
null
null
null
null
UTF-8
C++
false
false
1,328
cpp
main.cpp
#include <iostream> #include <vector> #include <random> #include <fmt/format.h> #include <cmath> #include <ruc-sci-comp/plot.hpp> using namespace std; int main(int argc, char **argv){ auto max_count = std::stoi(argv[1]); if(argc < 2){ cerr << "Invalid number of arguments - you must specify how many random points to generate!" << endl; return 1; } if(max_count < 1){ cerr << "Invalid number of points specified - you must provide a positive integer!" << endl; return 2; } //creating 2 vectors std::vector <double> xs; std::vector <double> ys; //create a random number generator std::uniform_real_distribution <double> dis(-1.0, 1.0); //create the engine mt19937_64 engine(1337); int count = 0; for(double i = 0; i < max_count; ++i){ double x = dis(engine); xs.push_back(x); double y = dis(engine); ys.push_back(y); //computing distance from origin (hypotenuse) if(std::hypot(x,y) <= 1.0){ ++count; } } //printing std::cout << fmt::format("pi ~ {:.10f}", 4.0 * count / max_count) << std::endl; //plotting plot_data(xs, ys); }
5212ccafa94c5f4c510c154633edcc76dd48f2b4
50bf585579f799a3055f8676b1b275f50be6150a
/Project/car/car/usr/inc/motor.h
15de8b7f4de019ab0148961ae85758e6a7d87687
[]
no_license
15712311828/diansaicamera
c73814d04f967c5e2479075dd97642430b49b6ed
efb5a61f4c91a3063eaf61a3aaa8eb6b76e6770a
refs/heads/master
2022-04-11T06:56:45.065106
2017-08-14T13:27:46
2017-08-14T13:27:46
100,270,605
0
1
null
2020-03-08T10:02:28
2017-08-14T13:28:25
C
UTF-8
C++
false
false
741
h
motor.h
#ifndef _MOTOR_H_ #define _MOTOR_H_ #include"common.h" #include"ftm.h" #define MOTOR_HZ (10*1000) #define PWM_EN PTC0 #define PWM_EN_INSTANCE HW_GPIOC #define PWM_EN_PIN 0 #define MOTOR_FTM HW_FTM0 #define MOTOR1_PWM HW_FTM_CH0 #define MOTOR2_PWM HW_FTM_CH1 #define MOTOR3_PWM HW_FTM_CH2 #define MOTOR4_PWM HW_FTM_CH3 #define MOTOR1_PWM_io FTM0_CH0_PC01 #define MOTOR2_PWM_io FTM0_CH1_PC02 #define MOTOR3_PWM_io FTM0_CH2_PC03 #define MOTOR4_PWM_io FTM0_CH3_PC04 //#define MOTOR1_PWM_io FTM0_CH3_PA06 //#define MOTOR2_PWM_io FTM0_CH4_PA07 //#define MOTOR3_PWM_io FTM0_CH5_PD05 //#define MOTOR4_PWM_io FTM0_CH6_PD06 class Motor{ public: Motor(); void start(); void duty(int duty1,int duty2); void stop(); }; #endif //MOTOR
6678806b26ec7fff49596713de4e7a356a3df61f
55aec4540ef7dcd52c26aa04e4557e5d9aa72771
/generateData.cc
0efe2d475fa269a096bd5e9d11e6e9e0009cccd9
[]
no_license
SridharaDasu/UltraFastSim
255f91a309b125f00d11a6edc127208bde4d67c7
321bbd49f64d07d812fa9c543ebc188dc378dde3
refs/heads/master
2021-01-21T11:45:04.056423
2016-03-06T02:35:58
2016-03-06T02:35:58
11,505,448
1
0
null
null
null
null
UTF-8
C++
false
false
5,480
cc
generateData.cc
// This simple program generates various signal processes for // various physics processes. // It includes the mixing of required level of pileup. // It then takes pythia output and runs it through very simplistic // detector simulation using parameterizations, including making // isolated light leptons, photons, composite tau, jet and b-tagged // jet objects. // It saves the output in root format for later analysis. #include <string> #include <iostream> using namespace std; #include <math.h> #include "Pythia8/Pythia.h" using namespace Pythia8; #include "UltraFastSim.h" #include "UFSDataStore.h" #include "UFSFilter.h" int poisson(double mean, Rndm *rndmPtr) { static double oldMean = -1; static double g; if(mean != oldMean) { oldMean = mean; if(mean == 0) { g = 0; } else { g = exp(-mean); } } double em = -1; double t = 1; do { em++; t *= rndmPtr->flat(); } while(t > g); return em; } int main(int argc, char **argv) { // Generator. Process selection. LHC initialization. Histogram. Pythia pythia; if(argc >= 2) pythia.readFile(argv[1]); else { cerr << "Command syntax: " << argv[0] << " <command file name> [<numberOfEvents>] [<runNumber>==<randomNumberSeed>] [<meanPileUpLevel>] [<filterFileName>]" << endl; exit(1); } // Get default parameters from the pythia cards file int nEvents = pythia.mode("Main:numberOfEvents"); int nList = pythia.mode("Main:numberToList"); int nShow = pythia.mode("Main:timesToShow"); int nAbort = pythia.mode("Main:timesAllowErrors"); bool showCS = pythia.flag("Main:showChangedSettings"); bool showAS = pythia.flag("Main:showAllSettings"); bool showCPD = pythia.flag("Main:showChangedParticleData"); bool showAPD = pythia.flag("Main:showAllParticleData"); // Overwrite with command line options, when appropriate if(argc >= 3) nEvents = atoi(argv[2]); int runNumber = 0; if(argc >= 4) runNumber = atoi(argv[3]); float meanPileupEventCount = 0; if(argc >= 5) meanPileupEventCount = atof(argv[4]); UFSFilter* filter = 0; if(argc == 6) filter = new UFSFilter(argv[5]); // Initialize pythia pythia.init(); const int beamA = pythia.info.idA(); const int beamB = pythia.info.idB(); const double cmEnergy = pythia.info.eCM(); // List settings. if (showCS) pythia.settings.listChanged(); if (showAS) pythia.settings.listAll(); // List particle data. if (showCPD) pythia.particleData.listChanged(); if (showAPD) pythia.particleData.listAll(); Rndm * rndmPtr = &pythia.rndm; rndmPtr->init(runNumber); // Pileup pythia for proton beams Pythia *pileupPythia; if(beamA == 2212 && beamB == 2212) { pileupPythia = new Pythia(); pileupPythia->init(); // Use beamA = beamB = 2212 and cmEnergy = Hard Interaction cmEnergy pileupPythia->readString("SoftQCD:minBias = on"); cout << "beam A, B, s" << beamA << ", " << beamB << ", " << cmEnergy << endl; pileupPythia->readString("Beams:idA = 2212"); pileupPythia->readString("Beams:idB = 2212"); std::stringstream ss; ss << "Beams:eCM = " << cmEnergy; pileupPythia->readString(ss.str()); pileupPythia->rndm.init(runNumber); } // Setup analysis class string hFileName(argv[1]); hFileName.erase(hFileName.rfind(".")); // Ultra Fast Simulator UltraFastSim ufs; UFSDataStore dataStore(hFileName.c_str(), &ufs); // Begin event loop for (int iEvent = 0, iAbort = 0; iEvent < nEvents; ) { // Generate event. Skip if error. Unless, errors are too many. if (!pythia.next()) { iAbort++; if(iAbort > nAbort) { cerr << "Too many aborted events = " << nAbort << endl; exit(1); } continue; } // Filter if requested if(filter != 0) { if(!filter->doFilter(&pythia)) continue; } // List first few events, both hard process and complete events. if (iEvent < nList) { pythia.info.list(); pythia.process.list(); pythia.event.list(); } // Add pileup for proton beams if(beamA == 2212) { int pileupEventCount = 0; if(meanPileupEventCount > 0) pileupEventCount = poisson(meanPileupEventCount, rndmPtr); for (int puEvent = 0; puEvent < pileupEventCount; ) { if(!pileupPythia->next()) continue; double vx = rndmPtr->gauss()*2.; // Mean beam spread is 2 mm in x-y and 75 mm in z double vy = rndmPtr->gauss()*2.; double vz = rndmPtr->gauss()*75.; for(int i = 0; i < pileupPythia->event.size(); i++) { Particle& particle = pileupPythia->event[i]; particle.xProd(vx+particle.xProd()); particle.yProd(vy+particle.yProd()); particle.zProd(vz+particle.zProd()); if(particle.status() > 0) { if(particle.isVisible()) { if(particle.pT() > 0.5) { pythia.event.append(particle); } } } } puEvent++; } } // Ultra fast simulation of detector effects if(!ufs.run(pythia.event, rndmPtr)) { cerr << "Ultra fast simulation failed - aborting" << endl; exit(2); } // Store data if(!dataStore.run()) { cerr << "Failed to store data" << endl; exit(3); } // End of event loop. Statistics. Histogram. Done. if(!(iEvent % 100)) cout << "Processed event " << iEvent << endl; iEvent++; } // Save output pythia.stat(); if(beamA == 2212) { pileupPythia->stat(); } if(filter != 0) delete filter; return 0; }
c1d20a264402154a7c15d6224ce8b5c1199e0fa3
6667a25d9b41bd8487848a0c7721f97cd301b8eb
/embeddedgmetric.h
20015d472cb9f55a6edeef5f574097a94aa8ae80
[]
no_license
dionysusxie/gmetric
b882b9f280bf8539d8822fc896ec40de62ddf505
820b5b181536418490515bd179facfccbcfa679c
refs/heads/master
2020-04-05T23:41:11.651294
2013-07-05T06:08:09
2013-07-05T06:08:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,398
h
embeddedgmetric.h
/** * This is the MIT LICENSE * http://www.opensource.org/licenses/mit-license.php * * Copyright (c) 2007 Nick Galbreath * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** \file embbededmetric.h * * A very simple "gmetric" UDP interface * * more doco here. * * basic useage might be: * \code * gmetric g; * gmetric_message msg; * gmetric_create(&g); * if (!gmetric_open(g, "localhost", 8649)) { * exit(1); * } * foreach metric { * msg.type = GMETRIC_VALUE_STRING; * msg.name = "foo"; * msg.value.v_string = "bar"; * msg.unit = "no units"; * msg.slope = GMETRIC_SLOPE_BOTH; * msg.tmax = 120; * msg.dmax = 0; * gmetric_send(&g, &msg); * } * gmetric_close(g); * \endcode * */ #ifndef COM_MODP_EMBEDDED_GMETRIC_H #define COM_MODP_EMBEDDED_GMETRIC_H #include <stdint.h> #include <arpa/inet.h> #include <netinet/in.h> #include <sys/types.h> #include <sys/socket.h> namespace allyes { namespace gmetric { #define GMETRIC_MAX_MESSAGE_LEN (512) enum gmetric_value_t { GMETRIC_VALUE_UNKNOWN = 0, GMETRIC_VALUE_STRING, GMETRIC_VALUE_UNSIGNED_SHORT, GMETRIC_VALUE_SHORT, GMETRIC_VALUE_UNSIGNED_INT, GMETRIC_VALUE_INT, GMETRIC_VALUE_FLOAT, GMETRIC_VALUE_DOUBLE, GMETRIC_VALUE_MAX }; enum gmetric_slope_t { GMETRIC_SLOPE_ZERO = 0, GMETRIC_SLOPE_POSITIVE, GMETRIC_SLOPE_NEGATIVE, GMETRIC_SLOPE_BOTH, GMETRIC_SLOPE_UNSPECIFIED, GMETRIC_SLOPE_MAX }; /** * Control structure and shared buffers */ struct gmetric_t { struct sockaddr_in sa; int s; }; /** * message structure */ struct gmetric_message_t { gmetric_value_t type; const char* name; const char* units; const char* typestr; gmetric_slope_t slope; uint32_t tmax; uint32_t dmax; union { const char* v_string; unsigned short v_ushort; short v_short; unsigned int v_uint; int v_int; float v_float; double v_double; } value; }; /** \brief "constructor" * */ void gmetric_create(gmetric_t* g); /** \brief open a UDP socket * * open up a socket. Needs to be done before calling gmetric_send. * * THIS MAY BE THREAD UNSAFE since it calls gethostbyname. * * \param[in] addr the hostname to connect to, e.g. "mygmond.com" or "127.0.0.1" * \param[in] port the port to connect to, in HOST order * \return 1 if ok, 0 if false (boolean) */ int gmetric_open(gmetric_t* g, const char* addr, int port); /** \brief Raw interface to open a gmetric socket that skips gethostbyname_X * * \param[in] ip the ip address IN NETWORK ORDER * \param[in] port IN HOST order (e.g. "8649") * \return 1 if ok, 0 if false (boolean) */ int gmetric_open_raw(gmetric_t* g, uint32_t ip, int port); /** \brief send a metric to the socket * * Must have called gmetric_create, gmetric_open first! * * This just wraps a call around gmetric_message_create_xdr and * gmetric_send_xdr. * * \param[in] g the socket to use * \param[in] msg the message to send * \return -1 on error, number of bytes sent on success * */ int gmetric_send(gmetric_t* g, const gmetric_message_t* msg); /** \brief Send a raw XDR buffer to gmond * * "normally" you shouldn't have to use this but it may aid in making * optimized batch calls where one can recycle a buffer. * * \param[in] g the gmetric socket to use * \param[in] buf the xdr buffer * \param[in] len the length of data * \return -1 on error, number of bytes sent on success. */ int gmetric_send_xdr(gmetric_t* g, const char* buf, int len); /** \brief "destructor" * * \param[in] g the gmetric to close */ void gmetric_close(gmetric_t* g); /** \brief struct to XDR message * * Internal function but you may find it useful * for testing and experimenting * * \param[out] buffer * \param[in] len length of buffer * \param[in] msg the gmetric_message to convert * \return -1 on error, length of message on success */ int gmetric_message_create_xdr(char* buffer, uint len, const gmetric_message_t* msg); /** \brief clear out a gmetric_message to know defaults * */ void gmetric_message_clear(gmetric_message_t* msg); /** \brief validate a gmetric message * * \return 1 if ok, 0 if bad */ int gmetric_message_validate(const gmetric_message_t* msg); } /* namespace gmetric */ } /* namespace allyes */ #endif
7471cab642195702542e9db7c9794bdc82ccb477
8bc5715e9fb0a18cb4c70a271b22dc108fdfe4f8
/Test1/turn_right.ino
32fc6e45e7c760605c8b28515566d6a4bf441be1
[]
no_license
ossilampe/PCB-Projekte
f2c8fd85ee67a5c2eace2e35d7f48481efd394b3
f07ad613103d3a10ed10fa0b44190b0359f76f91
refs/heads/master
2020-05-29T15:11:18.245514
2017-10-30T17:50:03
2017-10-30T17:50:03
60,724,086
0
0
null
null
null
null
UTF-8
C++
false
false
898
ino
turn_right.ino
void TurnRight() { int SLEEP=350; // Lift Leg1 leg3 leg5 LEG1_B180(); LEG1_C0(); LEG3_B180(); LEG3_C0(); LEG5_B180(); LEG5_C0(); delay(SLEEP); // Turn leg1 leg3 and leg5 and body to the right (leg2 leg4 leg6) LEG1_A180(); LEG3_A0(); LEG5_A0(); LEG2_A0(); LEG4_A0(); LEG6_A180(); delay(SLEEP); // Drop down leg1 leg3 and leg5 LEG1_B90(); LEG1_C90(); LEG3_B90(); LEG3_C90(); LEG5_B90(); LEG5_C90(); delay(SLEEP); // Lift Leg2 leg4 leg6 LEG2_B180(); LEG2_C0(); LEG4_B180(); LEG4_C0(); LEG6_B180(); LEG6_C0(); delay(SLEEP); // Turn leg2 leg4 and leg6 and body to the right (leg1 leg3 leg5) LEG2_A180(); LEG4_A180(); LEG6_A0(); LEG1_A0(); LEG3_A180(); LEG5_A180(); delay(SLEEP); // Drop down leg2 leg4 and leg6 LEG2_B90(); LEG2_C90(); LEG4_B90(); LEG4_C90(); LEG6_B90(); LEG6_C90(); delay(SLEEP); }
260d021916f4186fd9e6885ac1316f66891ed068
80e206a65755fc516cd4e76ef0dc32569785132f
/include/detectclass.hpp
45f17f99f6e9ead5e532a6e6f1e8711097dcbace
[]
no_license
sakshi-s/Ground_based_people_detection
ddeb45066177fbdfaa83422c49c2b53a846f9818
1d9de90fdfa156428472df0792a292f3b0676b1c
refs/heads/master
2020-06-28T21:20:03.211219
2019-08-03T07:22:13
2019-08-03T07:22:13
200,344,973
0
0
null
null
null
null
UTF-8
C++
false
false
13,975
hpp
detectclass.hpp
#ifndef _MY_DETECT_CLASS_HPP_ #define _MY_DETECT_CLASS_HPP_ #include "detectpeople.h" template <typename PointT> GroundBasedPeopleDetectionApp_M<PointT>::GroundBasedPeopleDetectionApp_M () { rgb_image_ = pcl::PointCloud<pcl::RGB>::Ptr(new pcl::PointCloud<pcl::RGB>); // set default values for optional parameters: sampling_factor_ = 1; voxel_size_ = 0.06; vertical_ = false; head_centroid_ = true; min_fov_ = 0; max_fov_ = 50; min_height_ = 1.3; max_height_ = 2.3; min_width_ = 0.1; max_width_ = 8.0; updateMinMaxPoints (); heads_minimum_distance_ = 0.3; // set flag values for mandatory parameters: sqrt_ground_coeffs_ = std::numeric_limits<float>::quiet_NaN(); ground_coeffs_set_ = false; intrinsics_matrix_set_ = false; person_classifier_set_flag_ = false; // set other flags transformation_set_ = false; } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::setInputCloud (PointCloudPtr& cloud) { cloud_ = cloud; } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::setTransformation (const Eigen::Matrix3f& transformation) { if (!transformation.isUnitary()) { PCL_ERROR ("[GroundBasedPeopleDetectionApp_M::setCloudTransform] The cloud transformation matrix must be an orthogonal matrix!\n"); } transformation_ = transformation; transformation_set_ = true; applyTransformationGround(); applyTransformationIntrinsics(); } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::setBackground (bool background_subtraction, float background_octree_resolution, PointCloudPtr& background_cloud) { this->background_subtraction = background_subtraction; background_octree_ = new pcl::octree::OctreePointCloud<PointT>(background_octree_resolution); background_octree_->defineBoundingBox(-max_distance_/2, -max_distance_/2, 0.0, max_distance_/2, max_distance_/2, max_distance_); background_octree_->setInputCloud (background_cloud); background_octree_->addPointsFromInputCloud (); } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::setGround (Eigen::VectorXf& ground_coeffs) { ground_coeffs_ = ground_coeffs; ground_coeffs_set_ = true; sqrt_ground_coeffs_ = (ground_coeffs - Eigen::Vector4f(0.0f, 0.0f, 0.0f, ground_coeffs(3))).norm(); applyTransformationGround(); } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::setSamplingFactor (int sampling_factor) { sampling_factor_ = sampling_factor; } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::setVoxelSize (float voxel_size) { voxel_size_ = voxel_size; updateMinMaxPoints (); } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::setIntrinsics (Eigen::Matrix3f intrinsics_matrix) { intrinsics_matrix_ = intrinsics_matrix; intrinsics_matrix_set_ = true; applyTransformationIntrinsics(); } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::setClassifier (pcl::people::PersonClassifier<pcl::RGB> person_classifier) { person_classifier_ = person_classifier; person_classifier_set_flag_ = true; } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::setFOV (float min_fov, float max_fov) { min_fov_ = min_fov; max_fov_ = max_fov; } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::setSensorPortraitOrientation (bool vertical) { vertical_ = vertical; } template<typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::updateMinMaxPoints () { min_points_ = (int) (min_height_ * min_width_ / voxel_size_ / voxel_size_); max_points_ = (int) (max_height_ * max_width_ / voxel_size_ / voxel_size_); } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::setPersonClusterLimits (float min_height, float max_height, float min_width, float max_width) { min_height_ = min_height; max_height_ = max_height; min_width_ = min_width; max_width_ = max_width; updateMinMaxPoints (); } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::setMinimumDistanceBetweenHeads (float heads_minimum_distance) { heads_minimum_distance_= heads_minimum_distance; } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::setHeadCentroid (bool head_centroid) { head_centroid_ = head_centroid; } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::getPersonClusterLimits (float& min_height, float& max_height, float& min_width, float& max_width) { min_height = min_height_; max_height = max_height_; min_width = min_width_; max_width = max_width_; } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::getDimensionLimits (int& min_points, int& max_points) { min_points = min_points_; max_points = max_points_; } template <typename PointT> float GroundBasedPeopleDetectionApp_M<PointT>::getMinimumDistanceBetweenHeads () { return (heads_minimum_distance_); } template <typename PointT> Eigen::VectorXf GroundBasedPeopleDetectionApp_M<PointT>::getGround () { if (!ground_coeffs_set_) { PCL_ERROR ("[GroundBasedPeopleDetectionApp_M::getGround] Floor parameters have not been set or they are not valid!\n"); } return (ground_coeffs_); } template <typename PointT> typename GroundBasedPeopleDetectionApp_M<PointT>::PointCloudPtr GroundBasedPeopleDetectionApp_M<PointT>::getFilteredCloud () { return (cloud_filtered_); } template <typename PointT> typename GroundBasedPeopleDetectionApp_M<PointT>::PointCloudPtr GroundBasedPeopleDetectionApp_M<PointT>::getNoGroundCloud () { return (no_ground_cloud_); } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::extractRGBFromPointCloud (PointCloudPtr input_cloud, pcl::PointCloud<pcl::RGB>::Ptr& output_cloud) { // Extract RGB information from a point cloud and output the corresponding RGB point cloud output_cloud->points.resize(input_cloud->height*input_cloud->width); output_cloud->width = input_cloud->width; output_cloud->height = input_cloud->height; pcl::RGB rgb_point; for (uint32_t j = 0; j < input_cloud->width; j++) { for (uint32_t i = 0; i < input_cloud->height; i++) { rgb_point.r = (*input_cloud)(j,i).r; rgb_point.g = (*input_cloud)(j,i).g; rgb_point.b = (*input_cloud)(j,i).b; (*output_cloud)(j,i) = rgb_point; } } } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::swapDimensions (pcl::PointCloud<pcl::RGB>::Ptr& cloud) { pcl::PointCloud<pcl::RGB>::Ptr output_cloud(new pcl::PointCloud<pcl::RGB>); output_cloud->points.resize(cloud->height*cloud->width); output_cloud->width = cloud->height; output_cloud->height = cloud->width; for (uint32_t i = 0; i < cloud->width; i++) { for (uint32_t j = 0; j < cloud->height; j++) { (*output_cloud)(j,i) = (*cloud)(cloud->width - i - 1, j); } } cloud = output_cloud; } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::applyTransformationPointCloud () { if (transformation_set_) { Eigen::Transform<float, 3, Eigen::Affine> transform; transform = transformation_; pcl::transformPointCloud(*cloud_, *cloud_, transform); } } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::applyTransformationGround () { if (transformation_set_ && ground_coeffs_set_) { Eigen::Transform<float, 3, Eigen::Affine> transform; transform = transformation_; ground_coeffs_transformed_ = transform.matrix() * ground_coeffs_; } else { ground_coeffs_transformed_ = ground_coeffs_; } } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::applyTransformationIntrinsics () { if (transformation_set_ && intrinsics_matrix_set_) { intrinsics_matrix_transformed_ = intrinsics_matrix_ * transformation_.transpose(); } else { intrinsics_matrix_transformed_ = intrinsics_matrix_; } } template <typename PointT> void GroundBasedPeopleDetectionApp_M<PointT>::filter () { cloud_filtered_ = PointCloudPtr (new PointCloud); pcl::VoxelGrid<PointT> grid; grid.setInputCloud(cloud_); grid.setLeafSize(voxel_size_, voxel_size_, voxel_size_); grid.setFilterFieldName("z"); grid.setFilterLimits(min_fov_, max_fov_); grid.filter(*cloud_filtered_); } template <typename PointT> bool GroundBasedPeopleDetectionApp_M<PointT>::compute (std::vector<pcl::people::PersonCluster<PointT> >& clusters) { // Check if all mandatory variables have been set: if (!ground_coeffs_set_) { PCL_ERROR ("[GroundBasedPeopleDetectionApp_M::compute] Floor parameters have not been set or they are not valid!\n"); return (false); } if (cloud_ == nullptr) { PCL_ERROR ("[GroundBasedPeopleDetectionApp_M::compute] Input cloud has not been set!\n"); return (false); } if (!intrinsics_matrix_set_) { PCL_ERROR ("[GroundBasedPeopleDetectionApp_M::compute] Camera intrinsic parameters have not been set!\n"); return (false); } if (!person_classifier_set_flag_) { PCL_ERROR ("[GroundBasedPeopleDetectionApp_M::compute] Person classifier has not been set!\n"); return (false); } // Fill rgb image: rgb_image_->points.clear(); // clear RGB pointcloud extractRGBFromPointCloud(cloud_, rgb_image_); // fill RGB pointcloud // Downsample of sampling_factor in every dimension: if (sampling_factor_ != 1) { PointCloudPtr cloud_downsampled(new PointCloud); cloud_downsampled->width = (cloud_->width)/sampling_factor_; cloud_downsampled->height = (cloud_->height)/sampling_factor_; cloud_downsampled->points.resize(cloud_downsampled->height*cloud_downsampled->width); cloud_downsampled->is_dense = cloud_->is_dense; for (uint32_t j = 0; j < cloud_downsampled->width; j++) { for (uint32_t i = 0; i < cloud_downsampled->height; i++) { (*cloud_downsampled)(j,i) = (*cloud_)(sampling_factor_*j,sampling_factor_*i); } } (*cloud_) = (*cloud_downsampled); } applyTransformationPointCloud(); filter(); // Ground removal and update: pcl::IndicesPtr inliers(new std::vector<int>); typename pcl::SampleConsensusModelPlane<PointT>::Ptr ground_model (new pcl::SampleConsensusModelPlane<PointT> (cloud_filtered_)); ground_model->selectWithinDistance(ground_coeffs_transformed_, 2 * voxel_size_, *inliers); no_ground_cloud_ = PointCloudPtr (new PointCloud); pcl::ExtractIndices<PointT> extract; extract.setInputCloud(cloud_filtered_); extract.setIndices(inliers); extract.setNegative(true); extract.filter(*no_ground_cloud_); if (inliers->size () >= (300 * 0.06 / voxel_size_ / std::pow (static_cast<double> (sampling_factor_), 2))) ground_model->optimizeModelCoefficients (*inliers, ground_coeffs_transformed_, ground_coeffs_transformed_); else PCL_INFO ("No groundplane update!\n"); // Euclidean Clustering: std::vector<pcl::PointIndices> cluster_indices; typename pcl::search::KdTree<PointT>::Ptr tree (new pcl::search::KdTree<PointT>); tree->setInputCloud(no_ground_cloud_); pcl::EuclideanClusterExtraction<PointT> ec; ec.setClusterTolerance(2 * voxel_size_); ec.setMinClusterSize(min_points_); ec.setMaxClusterSize(max_points_); ec.setSearchMethod(tree); ec.setInputCloud(no_ground_cloud_); ec.extract(cluster_indices); // Head based sub-clustering // pcl::people::HeadBasedSubclustering<PointT> subclustering; subclustering.setInputCloud(no_ground_cloud_); subclustering.setGround(ground_coeffs_transformed_); subclustering.setInitialClusters(cluster_indices); subclustering.setHeightLimits(min_height_, max_height_); subclustering.setMinimumDistanceBetweenHeads(heads_minimum_distance_); subclustering.setSensorPortraitOrientation(vertical_); subclustering.subcluster(clusters); // Person confidence evaluation with HOG+SVM: if (vertical_) // Rotate the image if the camera is vertical { swapDimensions(rgb_image_); } for(typename std::vector<pcl::people::PersonCluster<PointT> >::iterator it = clusters.begin(); it != clusters.end(); ++it) { //Evaluate confidence for the current PersonCluster: Eigen::Vector3f centroid = intrinsics_matrix_transformed_ * (it->getTCenter()); centroid /= centroid(2); Eigen::Vector3f top = intrinsics_matrix_transformed_ * (it->getTTop()); top /= top(2); Eigen::Vector3f bottom = intrinsics_matrix_transformed_ * (it->getTBottom()); bottom /= bottom(2); it->setPersonConfidence(person_classifier_.evaluate(rgb_image_, bottom, top, centroid, vertical_)); } return (true); } template <typename PointT> GroundBasedPeopleDetectionApp_M<PointT>::~GroundBasedPeopleDetectionApp_M () { // TODO Auto-generated destructor stub } #endif
4bb52bb7b4a0d369fa9a5f8e5fb35cd93e4b3444
11525b5baa183425c555212d96fa8d03f10544b4
/src/gamemachineqt/src/gamemachinewidget.cpp
8873b54886d6481736ea476dee5c19e24ed3ada0
[]
no_license
heusunduo/gamemachine
4f9e19f7900b43b75061db7295130d967dd9ef82
a3b1082519c8526855ec862af3378e46de335f93
refs/heads/master
2023-03-17T23:17:04.231411
2020-10-14T02:28:06
2020-10-14T02:28:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,614
cpp
gamemachinewidget.cpp
#include "stdafx.h" #include "gamemachinewidget.h" namespace { using namespace gm; bool g_isGameMachineInited = false; IWindow* createGameMachineChildWindow(IGameHandler* handler, float renderWidth, float renderHeight, HWND hContainer, IFactory* factory) { IWindow* window = NULL; factory->createWindow(NULL, 0, &window); GM_ASSERT(window); window->setHandler(handler); GMWindowDesc wndAttrs; wndAttrs.createNewWindow = false; wndAttrs.existWindowHandle = hContainer; wndAttrs.rc = { 0, 0, renderWidth, renderHeight }; window->create(wndAttrs); return window; } GMAtomic<GMsize_t>& getGameMachineRefCount() { static GMAtomic<GMsize_t> s_gmrefcnt; return s_gmrefcnt; } } namespace gm { GM_PRIVATE_OBJECT_UNALIGNED(GameMachineWidget) { const IRenderContext* context = nullptr; bool gamemachineSet = false; }; GameMachineWidget::GameMachineWidget(QWidget* parent /*= nullptr*/, Qt::WindowFlags f /*= Qt::WindowFlags()*/) : QWidget(parent, f) { GM_CREATE_DATA(); } GameMachineWidget::~GameMachineWidget() { D(d); if (d->gamemachineSet) { if (!--getGameMachineRefCount()) GM.finalize(); } } void GameMachineWidget::setGameMachine(const GMGameMachineDesc& desc, float renderWidth, float renderHeight, IGameHandler* handler) { D(d); if (!g_isGameMachineInited) { GMGameMachineDesc tmpDesc = desc; tmpDesc.runningMode = GMGameMachineRunningMode::ApplicationMode; GM.init(desc); GM.startGameMachineWithoutMessageLoop(); g_isGameMachineInited = true; } IWindow* gamemachineWindow = createGameMachineChildWindow(handler, renderWidth, renderHeight, (HWND)winId(), desc.factory); GM.addWindow(gamemachineWindow); setRenderContext(gamemachineWindow->getContext()); setAttribute(Qt::WA_PaintOnScreen, true); setAttribute(Qt::WA_NativeWindow, true); GM.handleMessages(); d->gamemachineSet = true; ++getGameMachineRefCount(); } void GameMachineWidget::setRenderContext(const IRenderContext* context) { D(d); d->context = context; } bool GameMachineWidget::event(QEvent* e) { // 是否需要在所有Event时都来handle messages? if (g_isGameMachineInited) GM.handleMessages(); return QWidget::event(e); } QPaintEngine* GameMachineWidget::paintEngine() const { // 返回nullptr,因为我们不需要QT替我们绘制。 return nullptr; } void GameMachineWidget::paintEvent(QPaintEvent *event) { D(d); if (d->context) GM.renderFrame(d->context->getWindow()); } }
0d062018111706b3c436c606d6f51827eb16957f
9b6eced5d80668bd4328a8f3d1f75c97f04f5e08
/bluetooth/btstack/avdtp/avdtpLogicalChannelFactory.h
6e621294843e58ec567a43c38a729a98900d5329
[]
no_license
SymbianSource/oss.FCL.sf.os.bt
3ca94a01740ac84a6a35718ad3063884ea885738
ba9e7d24a7fa29d6dd93808867c28bffa2206bae
refs/heads/master
2021-01-18T23:42:06.315016
2010-10-14T10:30:12
2010-10-14T10:30:12
72,765,157
1
0
null
null
null
null
UTF-8
C++
false
false
16,199
h
avdtpLogicalChannelFactory.h
// Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies). // All rights reserved. // This component and the accompanying materials are made available // under the terms of "Eclipse Public License v1.0" // which accompanies this distribution, and is available // at the URL "http://www.eclipse.org/legal/epl-v10.html". // // Initial Contributors: // Nokia Corporation - initial contribution. // // Contributors: // // Description: // Defines the avdtp logical channel factory // which creates the logical (L2CAP) channels for transport and signalling channels // // /** @file @internalComponent */ #include <bt_sock.h> #include <es_prot.h> #ifndef AVDTPLOGICALCHANNELFACTORY_H #define AVDTPLOGICALCHANNELFACTORY_H #include "avdtpAllocators.h" class XLogicalChannelFactoryClient; class CManagedLogicalChannel; class CProtocolBase; struct TLogicalChannelRecord; class CLogicalChannelFactory; class CBluetoothProtocolBase; const TInt KInitialSequenceNumber = 1; const TInt KAvdtpChannelArraySize = 3; typedef TInt8 TLogicalChannelFactoryRequestId; NONSHARABLE_CLASS(TRequestIdManager) : public TBitFieldAllocator { public: inline TInt GetId(TLogicalChannelFactoryRequestId& aId); inline void FreeId(TLogicalChannelFactoryRequestId aId); }; // abstract NONSHARABLE_CLASS(CLogicalChannelFactoryRequest) : public CBase { friend class CLogicalChannelFactory; protected: CLogicalChannelFactoryRequest(XLogicalChannelFactoryClient& aClient, TLogicalChannelFactoryRequestId aId); XLogicalChannelFactoryClient& iClient; TSglQueLink iFactoryQLink; TLogicalChannelFactoryRequestId iId; TInt iNumChannelsRequired; // those left to connect }; // abstract NONSHARABLE_CLASS(CLogicalChannelFactoryPassiveRequest) : public CLogicalChannelFactoryRequest { public: ~CLogicalChannelFactoryPassiveRequest(); protected: CLogicalChannelFactoryPassiveRequest(XLogicalChannelFactoryClient& aClient, TLogicalChannelFactoryRequestId aId, CBluetoothProtocolBase& aAvdtp); void BaseConstructL(); private: CBluetoothProtocolBase& iAvdtp; }; NONSHARABLE_CLASS(CExpectSignallingLogicalChannel) : public CLogicalChannelFactoryPassiveRequest { public: static CExpectSignallingLogicalChannel* NewL(XLogicalChannelFactoryClient& aClient, TLogicalChannelFactoryRequestId aId, CBluetoothProtocolBase& aAvdtp); private: void ConstructL(); CExpectSignallingLogicalChannel(XLogicalChannelFactoryClient& aClient, TLogicalChannelFactoryRequestId aId, CBluetoothProtocolBase& aAvdtp); }; /** Use to tell factory to expect explicitly sequenced logical channels, typically used for Direct Transport channels */ NONSHARABLE_CLASS(CExpectSessionLogicalChannels) : public CLogicalChannelFactoryPassiveRequest { public: static CExpectSessionLogicalChannels* NewL(XLogicalChannelFactoryClient& aClient, TLogicalChannelFactoryRequestId aId, TInt aNumRequired, CBluetoothProtocolBase& aAvdtp); private: void ConstructL(); CExpectSessionLogicalChannels(XLogicalChannelFactoryClient& aClient, TLogicalChannelFactoryRequestId aId, TInt aNumRequired, CBluetoothProtocolBase& aAvdtp); }; /** For clients to issue requests to the ChannelFactory */ NONSHARABLE_CLASS(CLogicalChannelFactoryActiveRequest) : public CLogicalChannelFactoryRequest { friend class CLogicalChannelFactory; public: ~CLogicalChannelFactoryActiveRequest(); protected: CLogicalChannelFactoryActiveRequest(const TBTDevAddr& aAddr, XLogicalChannelFactoryClient& aClient, TLogicalChannelFactoryRequestId aId); protected: TFixedArray<CManagedLogicalChannel*, KAvdtpChannelArraySize> iLogicalChannels; TBTDevAddr iRemoteDev; }; NONSHARABLE_CLASS(CCreateSignallingLogicalChannel) : public CLogicalChannelFactoryActiveRequest { public: static CCreateSignallingLogicalChannel* NewL(const TBTDevAddr&, XLogicalChannelFactoryClient& aClient, TLogicalChannelFactoryRequestId aId, CLogicalChannelFactory& aLogicalChannelFactory); static CCreateSignallingLogicalChannel* NewLC(const TBTDevAddr&, XLogicalChannelFactoryClient& aClient, TLogicalChannelFactoryRequestId aId, CLogicalChannelFactory& aLogicalChannelFactory); private: CCreateSignallingLogicalChannel(const TBTDevAddr&, XLogicalChannelFactoryClient& aClient, TLogicalChannelFactoryRequestId aId); void ConstructL(CLogicalChannelFactory& aLogicalChannelFactory); }; /** To create n logical channels */ NONSHARABLE_CLASS(CCreateSessionLogicalChannels) : public CLogicalChannelFactoryActiveRequest { public: static CCreateSessionLogicalChannels* NewL(const TBTDevAddr& aAddr, XLogicalChannelFactoryClient& aClient, TLogicalChannelFactoryRequestId aId, TInt aNumRequired); static CCreateSessionLogicalChannels* NewLC(const TBTDevAddr& aAddr, XLogicalChannelFactoryClient& aClient, TLogicalChannelFactoryRequestId aId, TInt aNumRequired); private: CCreateSessionLogicalChannels(const TBTDevAddr& aAddr, XLogicalChannelFactoryClient& aClient, TLogicalChannelFactoryRequestId aId, TInt aNumRequired); }; /** To close logical channels */ NONSHARABLE_CLASS(CCloseSessionLogicalChannels) : public CLogicalChannelFactoryRequest { friend class CLogicalChannelFactory; public: static CCloseSessionLogicalChannels* NewL(XLogicalChannelFactoryClient& aClient, TLogicalChannelFactoryRequestId aId); static CCloseSessionLogicalChannels* NewLC(XLogicalChannelFactoryClient& aClient, TLogicalChannelFactoryRequestId aId); ~CCloseSessionLogicalChannels(); void StartJob(TInt aTimeout); void ChannelClosed(CManagedLogicalChannel* aChannel); private: CCloseSessionLogicalChannels(XLogicalChannelFactoryClient& aClient, TLogicalChannelFactoryRequestId aId); static TInt WatchdogBarked(TAny* aCloseLogicalChannels); void CloseChannels(TBool aNotifyCompletion); private: TFixedArray<CManagedLogicalChannel*, KAvdtpChannelArraySize> iLogicalChannels; TDeltaTimerEntry iTimerEntry; }; #ifdef _DEBUG #define DEBUG_STORE_FACTORY_REQUEST iChannelFactoryRequest = &\ #else #define DEBUG_STORE_FACTORY_REQUEST #endif /** Class representing the job the factory has undertaken This is always returned synchronously - the client should inspect if the job has been completed synchronously via the State() method. If the job is process asynchronously then a new one is returned upon completion */ NONSHARABLE_CLASS(TLogicalChannelFactoryTicket) { friend class CLogicalChannelFactory; public: enum TLogicalChannelFactoryRequestState { ERequestIdle, ERequestOutstanding, ERequestComplete, ERequestErrored }; TLogicalChannelFactoryTicket(CLogicalChannelFactory* aFactory, TLogicalChannelFactoryRequestId aId); TLogicalChannelFactoryTicket(); TLogicalChannelRecord GetLogicalChannel(TInt aSequenceNumber=1); inline TLogicalChannelFactoryRequestState State() const { return iState; } inline TLogicalChannelFactoryRequestId Id() const { return iId; } private: void SetState(TLogicalChannelFactoryRequestState aNewState); private: CLogicalChannelFactory* iFactory; // non-owned, cannot be reference in default ctor TLogicalChannelFactoryRequestId iId; TLogicalChannelFactoryRequestState iState; }; /* The class provides a callback for someone that asked for logical channels @note this is an X class (see Programming DB) as it is effectively an M-class but must have a member to be que-able. */ NONSHARABLE_CLASS(XLogicalChannelFactoryClient) { public: virtual void LogicalChannelFactoryRequestComplete(TLogicalChannelFactoryTicket, TInt aResult)=0; TSglQueLink iFactoryQLink; }; /** Knows about ordering of L2CAP channels Hands ownership of newly established channels to clients Provides them with the TransportSession to a) remind them b) to assert it's ok The use of this class will to some extent be by someone who additionally knows (or is implcitily designed as such) of the channel order - for we cannot go adding a reporting bearer merely to obtain a recovery bearer....(presumably :o) Once ownership is transferred the caller will synchronously have to set itself as the SocketNotify of the L2CAP SAP @internalComponent */ class CDirectChannel; NONSHARABLE_CLASS(CLogicalChannelFactory) : public CBase, public MSocketNotify, public XLogicalChannelFactoryClient { friend class TLogicalChannelFactoryTicket; public: static CLogicalChannelFactory* NewL(CBluetoothProtocolBase& iProtocol, CProtocolBase& aSAPFactory); TLogicalChannelFactoryTicket CreateSignallingLogicalChannelL(const TBTDevAddr& aAddr, XLogicalChannelFactoryClient& aClient); TLogicalChannelFactoryTicket CreateSessionLogicalChannelsL(const TBTDevAddr& aAddr, XLogicalChannelFactoryClient& aClient, TInt aNumRequired); void CloseSessionLogicalChannelsL(TArray<CDirectChannel*>& aChannels, TInt aTimeout); TLogicalChannelFactoryTicket ExpectSignallingLogicalChannelL(XLogicalChannelFactoryClient& aClient); TLogicalChannelFactoryTicket ExpectSessionLogicalChannelsL(XLogicalChannelFactoryClient& aClient, TInt aNumRequired); void LogicalChannelLost(CManagedLogicalChannel* aChannel); void Cancel(TLogicalChannelFactoryTicket& aJobSpec); ~CLogicalChannelFactory(); inline CProtocolBase& SAPFactory() const; TInt BearerConnectComplete(const TBTDevAddr& /*aAddr*/, CServProviderBase* aSAP); // forward from AVDTP protocol when listen complete private: // from MSocketNotify virtual void NewData(TUint aCount); virtual void CanSend(); virtual void ConnectComplete(); virtual void ConnectComplete(const TDesC8& aConnectData); virtual void ConnectComplete(CServProviderBase& aSSP); virtual void ConnectComplete(CServProviderBase& aSSP,const TDesC8& aConnectData); virtual void CanClose(TDelete aDelete=EDelete); virtual void CanClose(const TDesC8& aDisconnectData,TDelete aDelete=EDelete); virtual void Error(TInt aError,TUint aOperationMask=EErrorAllOperations); virtual void Disconnect(); virtual void Disconnect(TDesC8& aDisconnectData); virtual void IoctlComplete(TDesC8* aBuf); virtual void NoBearer(const TDesC8& aConnectionInfo); virtual void Bearer(const TDesC8& aConnectionInfo); private: // from XLogicalChannelFactoryClient virtual void LogicalChannelFactoryRequestComplete(TLogicalChannelFactoryTicket, TInt aResult); private: CLogicalChannelFactory(CBluetoothProtocolBase& iProtocol, CProtocolBase& aSAPFactory); void ConstructL(); void DoObtainChannelL(); static TInt TryNextJob(TAny* aAny); void TryNextActiveJob(); TBool CheckActiveJobComplete(CLogicalChannelFactoryActiveRequest& aJob); void CompleteActiveJob(TInt aError); void NotifyComplete(TInt aError, CLogicalChannelFactoryRequest& aRequest); void SetId(CLogicalChannelFactoryActiveRequest& aRequest); static void FreeId(TAny* aId); void DeleteRequest(CLogicalChannelFactoryRequest *aRequest); TLogicalChannelRecord ClaimLogicalChannel(TInt aSequenceNumber, TLogicalChannelFactoryRequestId aId, TBool& aFinished); CManagedLogicalChannel* FindUnclaimedLogicalChannel(const TBTDevAddr& aAddr, TInt aSequenceNumber, TLogicalChannelFactoryRequestId& aId); TInt TryToTakeConnection(const TBTDevAddr& aRemote, CServProviderBase* aSAP, TSglQue<CLogicalChannelFactoryPassiveRequest>& aJobQueue); private: CBluetoothProtocolBase& iProtocol; //AVDTP CProtocolBase& iBearerSAPFactory; //L2CAP TDblQue<CManagedLogicalChannel> iUnclaimedLogicalChannels; TSglQue<CLogicalChannelFactoryActiveRequest> iPendingActiveJobs; TSglQue<CLogicalChannelFactoryPassiveRequest> iPendingPassiveSignallingJobs; TSglQue<CLogicalChannelFactoryPassiveRequest> iPendingPassiveSessionJobs; TSglQue<CCloseSessionLogicalChannels> iCloseChannelJobs; CLogicalChannelFactoryActiveRequest* iCurrentActiveJob; TBool iCurrentJobCancelled; TRequestIdManager iIdManager; TLogicalChannelFactoryRequestId iId; // used for cleaning up if the got (getid) is to be lost due to a leave CAsyncCallBack* iAsyncTryNextJob; }; NONSHARABLE_CLASS(CManagedLogicalChannel) : public CBase, public MSocketNotify /** for queuing inbound unclaimed SAPs. needs to be a socket so that SAP can declare newdata, disconnection etc. */ { friend class CLogicalChannelFactory; //for quing public: static CManagedLogicalChannel* NewL(CLogicalChannelFactory& aFactory, const TBTDevAddr& aAddr, TInt aSequenceNumber, TLogicalChannelFactoryRequestId aId, CServProviderBase* aSAP = NULL); static CManagedLogicalChannel* NewL(CLogicalChannelFactory& aFactory, TLogicalChannelFactoryRequestId aId); ~CManagedLogicalChannel(); void Shutdown(); private: // from MSocketNotify virtual void NewData(TUint aCount); virtual void CanSend(); virtual void ConnectComplete(); virtual void ConnectComplete(const TDesC8& aConnectData); virtual void ConnectComplete(CServProviderBase& aSSP); virtual void ConnectComplete(CServProviderBase& aSSP,const TDesC8& aConnectData); virtual void CanClose(TDelete aDelete=EDelete); virtual void CanClose(const TDesC8& aDisconnectData,TDelete aDelete=EDelete); virtual void Error(TInt aError,TUint aOperationMask=EErrorAllOperations); virtual void Disconnect(); virtual void Disconnect(TDesC8& aDisconnectData); virtual void IoctlComplete(TDesC8* aBuf); virtual void NoBearer(const TDesC8& aConnectionInfo); virtual void Bearer(const TDesC8& aConnectionInfo); private: CManagedLogicalChannel(CLogicalChannelFactory& aFactory, const TBTDevAddr& aAddr, TInt aSequenceNumber, TLogicalChannelFactoryRequestId aId); CManagedLogicalChannel(CLogicalChannelFactory& aFactory, TLogicalChannelFactoryRequestId aId); void ConstructL(CServProviderBase* aPrecreatedSAP); CServProviderBase* ObtainSAP(); void ProvideSAP(CServProviderBase* aSAP); private: CLogicalChannelFactory& iFactory; TBTDevAddr iRemoteAddress; TInt iSequenceNumber; // for sequence creations/MCs CServProviderBase* iLogicalChannelSAP; TUint iDataCount; TBool iEndOfData; // bit annoying, but safer that bittwiddling on iDataCount TDblQueLink iFactoryQLink; TLogicalChannelFactoryRequestId iId; // the request this was part of }; inline TInt TRequestIdManager::GetId(TLogicalChannelFactoryRequestId& aId) { TInt val, res; res = Get(val, 30, 1); // 0 is "invalid" aId = static_cast<TLogicalChannelFactoryRequestId>(val); return res; } inline void TRequestIdManager::FreeId(TLogicalChannelFactoryRequestId aId) { Free(aId); } inline CProtocolBase& CLogicalChannelFactory::SAPFactory() const { return iBearerSAPFactory; } NONSHARABLE_CLASS(TLogicalChannelRecord) /* Effectively a struct for transferring ownership of resulting logical channels Binds together the SAP, and any data count that has appeared whilst the logical channel lay unclaimed. */ { public: inline TLogicalChannelRecord(); inline void Reset(); public: CServProviderBase* iLogicalChannelSAP; // non-owned TUint iDataCount; TBool iEndOfData; // bit annoying, but safer that bittwiddling on iDataCount }; /** To help claim logical channels */ NONSHARABLE_CLASS(TLogicalChannelFactoryTicketInspector) { public: TLogicalChannelFactoryTicketInspector(TLogicalChannelFactoryTicket& aTicket, TBool aRequireReporting, TBool aRequireRecovery, TBool aMuxed); TLogicalChannelRecord GetLogicalChannel(TAvdtpTransportSessionType aType); private: TLogicalChannelFactoryTicket& iTicket; const TInt iSignallingSequenceNumber; const TInt iMediaSequenceNumber; // always first whether muxed or not TInt iReportingSequenceNumber; TInt iRecoverySequenceNumber; TLogicalChannelRecord iCachedRecord; // eg for Reporting which is the same LC as media TBool iCached; #ifdef _DEBUG TBool iRequireReporting; TBool iRequireRecovery; #endif }; inline TLogicalChannelRecord::TLogicalChannelRecord() { Reset(); } inline void TLogicalChannelRecord::Reset() { iLogicalChannelSAP = NULL; iDataCount = 0; iEndOfData = EFalse; } #endif //AVDTPLOGICALCHANNELFACTORY_H
c9d57c3f4fd428d4b044293cc903a66707de95c8
b08a4eeabc5495d24f309d9a9ea6da7104277f4a
/All Them Pixels/All Them Pixels/MontoneChain.cpp
8b5c34c81e985f2366b4cd257cc91c249e635ad1
[]
no_license
Kanel/AllThemPixels
f776b49005eeff7cb99e32184c86dfcea55c2339
61be150419c46ac2a832a06f95f3bdc3af3c7125
refs/heads/master
2021-01-10T19:32:32.066249
2013-09-22T17:07:52
2013-09-22T17:07:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,137
cpp
MontoneChain.cpp
#include "MonotoneChain.h" bool MonotoneChain::compare(Vector2f a, Vector2f b) { return (a.x < b.x) || (a.x == b.x && a.y < b.y); } float MonotoneChain::cross(std::vector<Vector2f> verticies, Vector2f next) { Vector2f o = verticies[verticies.size() - 2]; Vector2f a = verticies[verticies.size() - 1]; Vector2f b = next; return Vector2fMath::cross(a - o, b - o); } void MonotoneChain::clean(std::vector<Vector2f> &verticies, Vector2f next) { while (verticies.size() >= 2 && cross(verticies, next) <= 0) { verticies.pop_back(); } } ConvexHull MonotoneChain::getConvexHull(std::vector<Vector2f> verticies) { std::vector<Vector2f> upper; std::vector<Vector2f> lower; std::sort(verticies.begin(), verticies.end(), compare); for (int i = 0; i < verticies.size(); i++) { clean(lower, verticies[i]); lower.push_back(verticies[i]); } for (int i = verticies.size() - 1; i >= 0; i--) { clean(upper, verticies[i]); upper.push_back(verticies[i]); } upper.pop_back(); lower.pop_back(); lower.insert(lower.end(), upper.begin(), upper.end()); return lower; }
56c45ee0f236b77bcc3481d87c3922b3c122075e
1e229c70a50309e6082abe7266eb53d6021d6433
/src/octreeliquid/scenetester3.cpp
b00b2f593ccab1200eabdd6c386d0e96f69752cd
[]
no_license
ryichando/shiokaze
e3d8a688c25a5aabb4eac6576bcc4510436d181d
62e25b38882a1676c4a84181aa8eedaf716a0d0e
refs/heads/master
2022-06-21T04:10:44.898687
2022-06-13T11:04:55
2022-06-13T11:04:55
149,598,476
57
5
null
null
null
null
UTF-8
C++
false
false
3,937
cpp
scenetester3.cpp
/* ** scenetester3.cpp ** ** This is part of Shiokaze, a research-oriented fluid solver for computer graphics. ** Created by Ryoichi Ando <rand@nii.ac.jp> on January 10, 2020. ** ** 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 <shiokaze/ui/drawable.h> #include <shiokaze/math/shape.h> #include <shiokaze/core/dylibloader.h> #include <shiokaze/utility/utility.h> #include <shiokaze/core/console.h> // SHKZ_USING_NAMESPACE // class scenetester3 : public drawable { public: // LONG_NAME("Scene Tester 3D") ARGUMENT_NAME("SceneTester") // virtual void load( configuration &config ) override { // std::string name("waterdrop3"); config.get_string("Name",name,"Scene file name"); m_dylib.open_library(filesystem::resolve_libname(name)); m_dylib.load(config); m_dylib.overwrite(config); } // virtual void configure( configuration &config ) override { // m_dylib.configure(config); // config.get_unsigned("ResolutionX",m_shape[0],"Resolution towards X axis"); config.get_unsigned("ResolutionY",m_shape[1],"Resolution towards Y axis"); config.get_unsigned("ResolutionZ",m_shape[2],"Resolution towards Y axis"); // double resolution_scale (1.0); config.get_double("ResolutionScale",resolution_scale,"Resolution doubling scale"); // double view_scale (1.0); config.get_double("ViewScale",view_scale,"View scale"); // m_shape *= resolution_scale; m_dx = view_scale * m_shape.dx(); // set_environment("shape",&m_shape); set_environment("dx",&m_dx); } // virtual void post_initialize( bool initialized_from_file ) override { // auto initialize_func = reinterpret_cast<void(*)(const shape3 &m_shape, double m_dx)>(m_dylib.load_symbol("initialize")); if( initialize_func ) { initialize_func(m_shape,m_dx); } m_draw_func = reinterpret_cast<void(*)(graphics_engine &,double)>(m_dylib.load_symbol("draw")); m_camera->set_bounding_box(vec3d().v,m_shape.box(m_dx).v); // m_time0 = utility::get_seconds(); } // virtual bool keyboard( int key, int action, int mods ) override { return false; } // virtual void draw( graphics_engine &g ) const override { // const float seconds = utility::get_seconds()-m_time0; // if( m_draw_func ) { m_draw_func(g,seconds); } g.set_2D_coordinate(0.0,1.0,0,1.0); g.color4(1.0,1.0,1.0,1.0); static double test (0.1); std::string str = console::format_str("Time: %.2f seconds",seconds); g.draw_string(vec2d(0.02,0.95).v,str,18); } // virtual void setup_window( std::string &name, int &width, int &height ) const override { double ratio = m_shape[1] / (double) m_shape[0]; height = ratio * width; } // shape3 m_shape {32,32,32}; double m_dx; double m_time0; // std::function<void(graphics_engine &,double)> m_draw_func; dylibloader m_dylib; }; // extern "C" module * create_instance() { return new scenetester3; } // extern "C" const char *license() { return "MIT"; } //
872550023280d1c3253f4def71525f55e6ff7074
39e0e92f15cea8203df588d420b466cad1c92927
/include/db/collection.hpp
cbf4908071bc323cf9ce441726e7ccbef6568f49
[]
no_license
hellodoge/dbson
8a4941b74d57b34ce6aa6fe20d1a9309c6b38779
7630def26c56a8a80b0faa3c13e6f43401c8f040
refs/heads/master
2023-07-17T17:53:50.877128
2021-08-10T13:53:09
2021-08-10T13:53:09
393,194,194
1
0
null
null
null
null
UTF-8
C++
false
false
622
hpp
collection.hpp
#ifndef DBSON_COLLECTION_HPP #define DBSON_COLLECTION_HPP #include <map> #include <chrono> #include <string> #include <string_view> #include <boost/optional.hpp> #include "db/object.hpp" #include "binary_json/object.hpp" using namespace std::chrono_literals; namespace db { struct Collection { Object &addObject(std::string key, Object val); Object &getObject(std::string_view key); void setGlobalDeleteAfter(time_units da); private: time_units global_delete_after = 0s; std::map<std::string, Object, std::less<>> values{}; }; } #endif //DBSON_COLLECTION_HPP
112c4d6b529114f812d4adc0601e61b95464875f
2340859cdfd21ecf9bf5dd3d4dc3304b89ebf115
/dogpack-developer/lib/tests/test_dog_math.cpp
f07df298e89367b673fcfc941baa603aeaca1baf
[]
no_license
smoe1/ThesisCode
56c97c440f7f8182f5be7dba76848741dcf9a9d6
bd535bc99d0add16787524bd2ac5c4a53f2d86ee
refs/heads/master
2021-01-24T07:18:55.455846
2017-06-07T02:15:40
2017-06-07T02:15:40
93,338,238
0
1
null
null
null
null
UTF-8
C++
false
false
1,532
cpp
test_dog_math.cpp
#include "dog_math.h" #include "dogdefs.h" void test_minmod() { double a[3]; double b[3]; a[2] = 2.; a[1] = 1.; a[0] = 0.; b[2] = -2.; b[1] = -1.; b[0] = -0.; for(int i=0;i<3;i++) { printf( " signbit(a[%d]) = %d" " signbit(b[%d]) = %d\n", i, signbit(a[i]), i, signbit(b[i]) ); for(int j=0;j<3;j++) { printf( " minmod(a[%d],b[%d]) = %f " " minmod(a[%d],a[%d]) = %f " " minmod(b[%d],b[%d]) = %f " " minmod(b[%d],a[%d]) = %f \n", i,j, minmod(a[i],b[j]), i,j, minmod(a[i],a[j]), i,j, minmod(b[i],b[j]), i,j, minmod(b[i],a[j]) ); } } for(int i=0;i<3;i++) for(int j=0;j<3;j++) for(int k=0;k<3;k++) { printf( " minmod(a[%d],a[%d],a[%d]) = %f " " minmod(b[%d],b[%d],b[%d]) = %f \n", i,j,k, minmod(a[i],a[j],a[k]), i,j,k, minmod(b[i],b[j],b[k])); } for(int i=0;i<3;i++) for(int j=0;j<3;j++) { printf( " minmod(a[ 0],a[%d],a[%d]) = %f " " minmod(a[%d],a[ 0],a[%d]) = %f " " minmod(a[%d],a[%d],a[ 0]) = %f " " minmod(b[ 0],b[%d],b[%d]) = %f " " minmod(b[%d],b[ 0],b[%d]) = %f " " minmod(b[%d],b[%d],b[ 0]) = %f \n", i,j, minmod(a[ 0],a[ i],a[ j]), i,j, minmod(a[ i],a[ 0],a[ j]), i,j, minmod(a[ i],a[ j],a[ 0]), i,j, minmod(b[ 0],b[ i],b[ j]), i,j, minmod(b[ i],b[ 0],b[ j]), i,j, minmod(b[ i],b[ j],b[ 0])); } } main() { test_minmod(); }
48fc7be9c6be80f2f75eb1e5fa38af9128c65a79
b9a94bff810960060dcfcf3bce367b1068122d15
/lab10_circbuf.cpp
c4ce1792b0fc2fcf86dea2f3608f3a93216fe19c
[]
no_license
woodnat3/cse_232
982b19c16f6d87feb8c0ad6eff10b8027305092a
1e71f6fb968b08eda4ccb3f857715891cbd7567d
refs/heads/master
2021-02-07T09:42:06.564209
2020-02-29T17:33:47
2020-02-29T17:33:47
244,010,718
0
0
null
null
null
null
UTF-8
C++
false
false
1,784
cpp
lab10_circbuf.cpp
//Nate Wood #include "lab10_circbuf.h" #include<exception> using std::runtime_error; CircBuf::CircBuf(size_t s){ sz_ = static_cast<int>(s); buf_.resize(s); } CircBuf::CircBuf(initializer_list<long> l, size_t n){ try{ if (l.size() < n){ buf_.resize(n); copy(l.begin(), l.end(), buf_.begin()); } else{ throw runtime_error("wrong size"); } } catch(runtime_error& e){ } } long CircBuf::front() const{ try{ if (empty()){ throw runtime_error("no value"); } else{ return buf_[head_]; } } catch(runtime_error& e){ return 0; } } long CircBuf::back() const{ try{ if (empty()){ throw runtime_error("no value"); } else{ return buf_[tail_ - 1]; } } catch(runtime_error& e){ return 0; } } bool CircBuf::full() const{ if (cnt_ == sz_){ return true; } else{ return false; } } bool CircBuf::empty() const{ if (cnt_ == 0){ return true; } else{ return false; } } void CircBuf::add(long num){ try{ if (full() == false){ buf_[tail_] = num; tail_ = (tail_ + 1) % sz_; } else{ throw runtime_error("full"); } } catch(runtime_error& e){ } } void CircBuf::remove(){ try{ if (empty() == false){ head_ = (head_ + 1) % sz_; } else{ throw runtime_error("empty"); } } catch(runtime_error& e){ } } friend ostream& operator<<(ostream &out, const CircBuf &cb){ out << buf_[head_] << " " << buf_[tail_ - 1]; }
400c821932e2dbcf835949db4dc964432448c057
8787c0542d1c4aa970453664f478a5b11ab811c7
/squirrel_planning_execution/src/FinalReviewRedux.cpp
700d17a9ba643a4598e8b92986bc6852d9c1c71e
[]
no_license
squirrel-project/squirrel_planning
fc065daec981ba046953ebea17ca299046230b69
270e8e6f2906fe310699d14bb5d77fd48b309581
refs/heads/indigo_dev
2021-01-20T10:46:22.638661
2018-03-12T08:49:31
2018-03-12T08:49:31
19,309,294
0
10
null
2018-03-12T09:00:21
2014-04-30T09:52:18
C++
UTF-8
C++
false
false
19,345
cpp
FinalReviewRedux.cpp
/** * Main function for the final review. * * It is a loop that selects what goals to plan for, givent the current state. Options are: * * - Explore the room to find objects to identify. * - Examine objects. * - Tidy examined objects. * * These can be used within a single planning problem. All the while the robot keeps track * of its current battery power and frustration level. These influence the way the robot * interacts with its surroundings. If the frustration is very high, then it will ask children * for help when it comes to grasping tasks or identification tasks. * * If the power level is very low then it will look for batteries and ask children to give it * the battery. */ #include <map> #include <string> #include <vector> #include <tf/tf.h> #include <tf/transform_listener.h> #include <ros/ros.h> #include <actionlib/client/simple_action_client.h> #include <rosplan_knowledge_msgs/KnowledgeItem.h> #include <rosplan_dispatch_msgs/PlanGoal.h> #include <rosplan_dispatch_msgs/PlanAction.h> #include <squirrel_object_perception_msgs/SceneObject.h> #include <squirrel_waypoint_msgs/ExamineWaypoint.h> #include <squirrel_planning_execution/KnowledgeBase.h> #include <squirrel_planning_execution/ConfigReader.h> #include "squirrel_planning_execution/ViewConeGenerator.h" //#include "pddl_actions/ExploreAreaPDDLAction.h" #include "pddl_actions/AttemptToExamineObjectPDDLAction.h" // All service clients. ros::ServiceClient classify_object_waypoint_client; KCL_rosplan::ViewConeGenerator* view_cone_generator_; bool setupLumps(KCL_rosplan::KnowledgeBase& kb, mongodb_store::MessageStoreProxy& message_store) { std::vector< boost::shared_ptr<squirrel_object_perception_msgs::SceneObject> > sceneObjects_results; message_store.query<squirrel_object_perception_msgs::SceneObject>(sceneObjects_results); unsigned int nr_lumps_found = 0; ROS_INFO("KCL: (SetupLumps) Found %lu lumps.", sceneObjects_results.size()); // Check if this fact actually exists, or is a leftover (this is bad!). std::vector<rosplan_knowledge_msgs::KnowledgeItem> all_facts; kb.getFacts(all_facts, "object_at"); for (std::vector< boost::shared_ptr<squirrel_object_perception_msgs::SceneObject> >::const_iterator ci = sceneObjects_results.begin(); ci != sceneObjects_results.end(); ++ci) { const squirrel_object_perception_msgs::SceneObject& lump = **ci; const std::string& lump_name = lump.id; std::string lump_waypoint; ROS_INFO("KCL: (SetupLumps) Process the lump %s.", lump_name.c_str()); // Check if we know where this lump is, if not we cannot process it. for (std::vector<rosplan_knowledge_msgs::KnowledgeItem>::const_iterator ci = all_facts.begin(); ci != all_facts.end(); ++ci) { const rosplan_knowledge_msgs::KnowledgeItem& ki = *ci; std::string s = kb.toString(ki); std::string object_name; std::string object_waypoint; for (unsigned int i = 0; i < ki.values.size(); ++i) { if (ki.values[i].key == "o") object_name = ki.values[i].value; else if (ki.values[i].key == "wp") object_waypoint = ki.values[i].value; } if (object_name == lump_name) { ROS_INFO("KCL: (SetupLumps) Process lump is in the Knowledge base: %s.", s.c_str()); lump_waypoint = object_waypoint; break; } } if (lump_waypoint == "") continue; // Check if this lump has already been examined, if so then we are done. std::map<std::string, std::string> parameters; parameters["o"] = lump_name; bool is_examined = kb.isFactTrue("examined", parameters, true); // If it is not examined, we create waypoints around the lump from where the lump can be examined. if (is_examined) continue; ROS_INFO("KCL: (SetupLumps) %s has not been examined yet, time to examine lumps!", lump_name.c_str()); squirrel_waypoint_msgs::ExamineWaypoint getTaskPose; // fetch position of object from message store std::vector< boost::shared_ptr<squirrel_object_perception_msgs::SceneObject> > results; if(message_store.queryNamed<squirrel_object_perception_msgs::SceneObject>(lump_name, results)) { if(results.size()<1) { ROS_ERROR("KCL: (SetupLumps) aborting waypoint request; no matching obID %s", lump_name.c_str()); return false; } } else { ROS_ERROR("KCL: (SetupLumps) could not query message store to fetch object pose of %s", lump_name.c_str()); return false; } // request classification waypoints for object squirrel_object_perception_msgs::SceneObject &obj = *results[0]; getTaskPose.request.object_pose.header = obj.header; getTaskPose.request.object_pose.pose = obj.pose; if (!classify_object_waypoint_client.call(getTaskPose)) { ROS_ERROR("KCL: (SetupLumps) Failed to recieve classification waypoints for %s.", lump_name.c_str()); // Remove this object, as we cannot get to it! std::map<std::string, std::string> parameters; parameters["o"] = lump_name; parameters["wp"] = lump_waypoint; if (!kb.removeFact("object_at", parameters, true, KCL_rosplan::KnowledgeBase::KB_REMOVE_KNOWLEDGE)) { ROS_ERROR("KCL: (SetupLumps) Failed to remove (object_at %s %s) from the knowledge base!", lump_name.c_str(), lump_waypoint.c_str()); exit(-1); } } ROS_INFO("KCL: (SetupLumps) Found %lu observation poses", getTaskPose.response.poses.size()); // Add all the waypoints to the knowledge base. for(int i = 0; i < getTaskPose.response.poses.size(); i++) { std::stringstream ss; ss << lump_name << "_observation_wp" << i; ROS_INFO("KCL: (SetupLumps) Process observation pose: %s", ss.str().c_str()); kb.addInstance("waypoint", ss.str()); std::map<std::string, std::string> parameters; parameters["wp1"] = ss.str(); parameters["wp2"] = lump_waypoint; kb.addFact("near", parameters, true, KCL_rosplan::KnowledgeBase::KB_ADD_KNOWLEDGE); const geometry_msgs::PoseWithCovarianceStamped& pwcs = getTaskPose.response.poses[i]; geometry_msgs::PoseStamped ps; ps.header= pwcs.header; ps.header.frame_id = "/map"; ps.pose = pwcs.pose.pose; std::string near_waypoint_mongodb_id(message_store.insertNamed(ss.str(), ps)); // Add as goal to examine this object from each possible waypoint. parameters.clear(); parameters["o"] = lump_name; parameters["wp"] = ss.str(); kb.addFact("observed-from", parameters, true, KCL_rosplan::KnowledgeBase::KB_ADD_GOAL); ++nr_lumps_found; if (nr_lumps_found > 5) return true; } } return nr_lumps_found > 0; } bool setupToysToTidy(KCL_rosplan::KnowledgeBase& kb, mongodb_store::MessageStoreProxy& message_store, const std::vector<rosplan_knowledge_msgs::KnowledgeItem>& all_facts) { // Check if there are objects that need to be tidied. std::vector<std::string> objects_to_tidy; std::map<std::string, std::string> object_tidy_locations; for (std::vector<rosplan_knowledge_msgs::KnowledgeItem>::const_iterator ci = all_facts.begin(); ci != all_facts.end(); ++ci) { const rosplan_knowledge_msgs::KnowledgeItem& fact = *ci; if (fact.attribute_name == "object_at") { for (std::vector<diagnostic_msgs::KeyValue>::const_iterator ci = fact.values.begin(); ci != fact.values.end(); ++ci) { const diagnostic_msgs::KeyValue& kv = *ci; if (kv.key == "o") { const std::string object = kv.value; ROS_INFO("KCL: (SetupGoals) Add the object %s to the list of objects to tidy.", object.c_str()); objects_to_tidy.push_back(object); } } } else if (fact.attribute_name == "belongs_in") { std::string object; std::string box; for (std::vector<diagnostic_msgs::KeyValue>::const_iterator ci = fact.values.begin(); ci != fact.values.end(); ++ci) { const diagnostic_msgs::KeyValue& kv = *ci; if (kv.key == "o") { object = kv.value; } else if (kv.key == "b") { box = kv.value; } } ROS_INFO("KCL: (SetupGoals) %s belongs in %s.", object.c_str(), box.c_str()); object_tidy_locations[object] = box; } } // Create a goal for every object of which we know its tidy location. bool found_a_toy_to_tidy = false; for (std::vector<std::string>::const_iterator ci = objects_to_tidy.begin(); ci != objects_to_tidy.end(); ++ci) { const std::string& object = *ci; ROS_INFO("KCL: (SetupGoals) Do know where %s belongs?", object.c_str()); if (object_tidy_locations.find(object) == object_tidy_locations.end()) { ROS_INFO("KCL: (SetupGoals) Do not know where to tidy %s, ask someone for help!.", object.c_str()); continue; } const std::string& box = object_tidy_locations[object]; // Now create a goal for this object. std::map<std::string, std::string> parameters; parameters["b"] = box; parameters["o"] = object; if (!kb.addFact("in_box", parameters, true, KCL_rosplan::KnowledgeBase::KB_ADD_GOAL)) { ROS_ERROR("KCL: (SetupGoals) Failed to add (in_box %s %s) as a goal!", object.c_str(), box.c_str()); exit(-1); } found_a_toy_to_tidy = true; } return found_a_toy_to_tidy; } void setupViewCones(KCL_rosplan::KnowledgeBase& kb, mongodb_store::MessageStoreProxy& message_store) { static std::map<std::string, std::string> db_name_map; std::vector<rosplan_knowledge_msgs::KnowledgeItem> all_facts; if (!kb.getFacts(all_facts, "explored")) { ROS_INFO("KCL: (ExploreAreaPDDLAction) Failed to get all actions!"); exit(-1); } // Remove all explored facts, otherwise subsequent calls will fail. for (std::vector<rosplan_knowledge_msgs::KnowledgeItem>::const_iterator ci = all_facts.begin(); ci != all_facts.end(); ++ci) { const rosplan_knowledge_msgs::KnowledgeItem& ki = *ci; kb.removeFact(ki, KCL_rosplan::KnowledgeBase::KB_REMOVE_KNOWLEDGE); } // Cleanup any previous waypoints from MongoDB. for (std::map<std::string, std::string>::const_iterator ci = db_name_map.begin(); ci != db_name_map.end(); ++ci) { ROS_INFO("KCL: (SetupViewCones) Remove the waypoint: %s, MongoDB id: %s!", ci->first.c_str(), ci->second.c_str()); kb.removeInstance("waypoint", ci->first); message_store.deleteID(db_name_map[ci->second]); } db_name_map.clear(); // Reset the robot back to the default waypoint. all_facts.clear(); if (!kb.getFacts(all_facts, "robot_at")) { ROS_INFO("KCL: (ExploreAreaPDDLAction) Failed to get all actions!"); exit(-1); } for (std::vector<rosplan_knowledge_msgs::KnowledgeItem>::const_iterator ci = all_facts.begin(); ci != all_facts.end(); ++ci) { const rosplan_knowledge_msgs::KnowledgeItem& ki = *ci; kb.removeFact(ki, KCL_rosplan::KnowledgeBase::KB_REMOVE_KNOWLEDGE); } std::map<std::string, std::string> params; params["v"] = "robot"; params["wp"] = "kenny_waypoint"; if (!kb.addFact("robot_at", params, true, KCL_rosplan::KnowledgeBase::KB_ADD_KNOWLEDGE) || !kb.addInstance("waypoint", "kenny_waypoint")) { ROS_INFO("KCL: (ExploreAreaPDDLAction) Failed to reset the waypoint of the robot!"); exit(-1); } // Locate the location of the robot. tf::StampedTransform transform; tf::TransformListener tfl; try { tfl.waitForTransform("/map","/base_link", ros::Time::now(), ros::Duration(1.0)); tfl.lookupTransform("/map", "/base_link", ros::Time(0), transform); } catch ( tf::TransformException& ex ) { ROS_ERROR("KCL: (ExploreAreaPDDLAction) Error find the transform between /map and /base_link."); return; } geometry_msgs::PoseStamped robot_pose; robot_pose.header.frame_id = "/map"; robot_pose.pose.position.x = transform.getOrigin().getX(); robot_pose.pose.position.y = transform.getOrigin().getY(); robot_pose.pose.position.z = transform.getOrigin().getZ(); robot_pose.pose.orientation.x = transform.getRotation().getX(); robot_pose.pose.orientation.y = transform.getRotation().getY(); robot_pose.pose.orientation.z = transform.getRotation().getZ(); robot_pose.pose.orientation.w = transform.getRotation().getW(); std::string robot_id(message_store.insertNamed("kenny_waypoint", robot_pose)); db_name_map["kenny_waypoint"] = robot_id; ROS_INFO("KCL: (setupViewCones) Store the location of kenny."); // Create the view cones. tf::Vector3 p1(transform.getOrigin().getX() - 5.0f, transform.getOrigin().getY() - 5.0f, 0.00); tf::Vector3 p2(transform.getOrigin().getX() + 5.0f, transform.getOrigin().getY() - 5.0f, 0.00); tf::Vector3 p3(transform.getOrigin().getX() + 5.0f, transform.getOrigin().getY() + 5.0f, 0.00); tf::Vector3 p4(transform.getOrigin().getX() + 5.0f, transform.getOrigin().getY() - 5.0f, 0.00); std::vector<tf::Vector3> bounding_box; bounding_box.push_back(p1); bounding_box.push_back(p3); bounding_box.push_back(p4); bounding_box.push_back(p2); std::vector<geometry_msgs::Pose> view_poses; view_cone_generator_->createViewCones(view_poses, bounding_box, 1, 5, 30.0f, 2.0f, 100, 0.5f); // Add these poses to the knowledge base. unsigned int waypoint_number = 0; for (std::vector<geometry_msgs::Pose>::const_iterator ci = view_poses.begin(); ci != view_poses.end(); ++ci) { std::stringstream ss; ss << "explore_wp" << waypoint_number; if (!kb.addInstance("waypoint", ss.str())) { ROS_ERROR("KCL: (ExploreAreaPDDLAction) Could not add an explore wayoint to the knowledge base."); exit(-1); } // add waypoint to MongoDB geometry_msgs::PoseStamped pose; pose.header.frame_id = "/map"; pose.pose = *ci; std::string id(message_store.insertNamed(ss.str(), pose)); db_name_map[ss.str()] = id; std::map<std::string, std::string> parameters; parameters["wp"] = ss.str(); if (!kb.addFact("explored", parameters, true, KCL_rosplan::KnowledgeBase::KB_ADD_GOAL)) { ROS_ERROR("KCL: (ExploreAreaPDDLAction) Could not add the goal (explored %s) to the knowledge base.", ss.str().c_str()); exit(-1); } ++waypoint_number; } ROS_INFO("KCL: (ExploreAreaPDDLAction) Added %u waypoints to the knowledge base.", waypoint_number); } void setupGoals(KCL_rosplan::KnowledgeBase& kb, mongodb_store::MessageStoreProxy& message_store) { kb.removeAllGoals(); // Figure out what facts are true, so know what goals to set for this iteration. std::vector<rosplan_knowledge_msgs::KnowledgeItem> all_facts; kb.getAllFacts(all_facts); bool found_a_toy_to_tidy = false; if (setupToysToTidy(kb, message_store, all_facts)) { found_a_toy_to_tidy = true; } if (setupLumps(kb, message_store)) { found_a_toy_to_tidy = true; } // If no toys were found to tidy and no lumps exist, then we need to explore the room. if (!found_a_toy_to_tidy) { setupViewCones(kb, message_store); } // Update the distance between any pair of waypoints. std::vector<std::string> waypoints; kb.getInstances(waypoints, "waypoint"); for (int i = 0; i < waypoints.size() - 1; ++i) { const std::string& wp = waypoints[i]; std::vector< boost::shared_ptr<geometry_msgs::PoseStamped> > results; if (!message_store.queryNamed<geometry_msgs::PoseStamped>(wp, results) || results.size() < 1) continue; geometry_msgs::PoseStamped &wp_pose = *results[0]; for (int j = i + 1; j < waypoints.size(); ++j) { const std::string& other_wp = waypoints[j]; std::vector< boost::shared_ptr<geometry_msgs::PoseStamped> > other_results; if (!message_store.queryNamed<geometry_msgs::PoseStamped>(other_wp, other_results) || other_results.size() < 1) continue; geometry_msgs::PoseStamped &other_wp_pose = *other_results[0]; float distance = sqrt((wp_pose.pose.position.x - other_wp_pose.pose.position.x) * (wp_pose.pose.position.x - other_wp_pose.pose.position.x) + (wp_pose.pose.position.y - other_wp_pose.pose.position.y) * (wp_pose.pose.position.y - other_wp_pose.pose.position.y)); std::map<std::string, std::string> parameters; parameters["wp1"] = wp; parameters["wp2"] = other_wp; kb.addFunction("distance", parameters, distance, KCL_rosplan::KnowledgeBase::KB_ADD_KNOWLEDGE); parameters["wp1"] = other_wp; parameters["wp2"] = wp; kb.addFunction("distance", parameters, distance, KCL_rosplan::KnowledgeBase::KB_ADD_KNOWLEDGE); } } } void startPlanning(ros::NodeHandle& nh) { // Start the planning process. std::string data_path; nh.getParam("/data_path", data_path); std::string planner_path; nh.getParam("/planner_path", planner_path); std::string domain_path; nh.getParam("/rosplan/domain_path", domain_path); std::stringstream ss; ss << data_path << "final-review_redux_problem.pddl"; std::string problem_path = ss.str(); std::string planner_command; nh.getParam("/rosplan_planning_system/planner_command", planner_command); rosplan_dispatch_msgs::PlanGoal psrv; psrv.domain_path = domain_path; psrv.problem_path = problem_path; psrv.data_path = data_path; psrv.planner_command = planner_command; psrv.start_action_id = 0; ROS_INFO("KCL: (FinalReview) Start plan action"); actionlib::SimpleActionClient<rosplan_dispatch_msgs::PlanAction> plan_action_client("/kcl_rosplan/start_planning", true); plan_action_client.waitForServer(); ROS_INFO("KCL: (FinalReview) Start planning server found"); // send goal plan_action_client.sendGoal(psrv); ROS_INFO("KCL: (FinalReview) Goal sent"); ros::Rate rate(1.0f); while (plan_action_client.getState() == actionlib::SimpleClientGoalState::ACTIVE || plan_action_client.getState() == actionlib::SimpleClientGoalState::PENDING) { rate.sleep(); ros::spinOnce(); } } void initialiseKnowledgeBase(KCL_rosplan::KnowledgeBase& kb) { kb.addInstance("robot", "robot"); std::map<std::string, std::string> params; params["v"] = "robot"; params["wp"] = "kenny_waypoint"; kb.addFact("robot_at", params, true, KCL_rosplan::KnowledgeBase::KB_ADD_KNOWLEDGE); params.clear(); kb.addFact("not_busy", params, true, KCL_rosplan::KnowledgeBase::KB_ADD_KNOWLEDGE); kb.addFact("not_flashing_lights", params, true, KCL_rosplan::KnowledgeBase::KB_ADD_KNOWLEDGE); kb.addFact("not_playing_sound", params, true, KCL_rosplan::KnowledgeBase::KB_ADD_KNOWLEDGE); kb.addFact("not_gazing", params, true, KCL_rosplan::KnowledgeBase::KB_ADD_KNOWLEDGE); params["v"] = "robot"; kb.addFact("gripper_empty", params, true, KCL_rosplan::KnowledgeBase::KB_ADD_KNOWLEDGE); } int main(int argc, char **argv) { ros::init(argc, argv, "FinalReviewPlanning"); ros::NodeHandle nh; // Setup all services. classify_object_waypoint_client = nh.serviceClient<squirrel_waypoint_msgs::ExamineWaypoint>("/squirrel_perception_examine_waypoint"); std::string occupancyTopic("/map"); nh.param("occupancy_topic", occupancyTopic, occupancyTopic); view_cone_generator_ = new KCL_rosplan::ViewConeGenerator(nh, occupancyTopic); // Setup the knowledge base. mongodb_store::MessageStoreProxy message_store(nh); KCL_rosplan::KnowledgeBase knowledge_base(nh, message_store); // Initialise the context for this planning task. std::string config_file; nh.getParam("/scenario_setup_file", config_file); KCL_rosplan::ConfigReader reader(nh, message_store); reader.readConfigurationFile(config_file); // Create all PDDL actions that we might need during execution. // KCL_rosplan::ExploreAreaPDDLAction explore_area_action(nh, knowledge_base); KCL_rosplan::AttemptToExamineObjectPDDLAction attempt_to_examine_action(nh, knowledge_base, message_store); initialiseKnowledgeBase(knowledge_base); // Keep running forever. while (true) { ros::spinOnce(); setupGoals(knowledge_base, message_store); startPlanning(nh); } return 0; }
70d24672b6a9ee3528cb980861a00c6366f3949b
1b6631fdb38955bcce9df1fe1f96945c0582daf7
/development/c/msg/2.05/DISE/YYYYMMDDhhmm.h
85f68452f3bd2403e3ad8709b2de33af176d6f2b
[]
no_license
ARPASMR/elab_msg_rss
3720212fb4e5b26c6513417f788f509841ab3ee9
d75d89e20c2090b61b52ddc7e3770f9581252fba
refs/heads/master
2020-03-15T06:09:50.384136
2018-05-30T08:41:45
2018-05-30T08:41:45
132,001,628
0
0
null
null
null
null
UTF-8
C++
false
false
3,494
h
YYYYMMDDhhmm.h
#ifndef YYYYMMDDhhmm_included #define YYYYMMDDhhmm_included /******************************************************************************* TYPE: Free functions. PURPOSE: Conversion of a CMSGTime object from/to a 'YYYYMMDDhhmm'- or 'YYYYMMDDhhmmss'-formatted string. FUNCTION: Conversion of a CMSGTime object from/to a 'YYYYMMDDhhmm'- or 'YYYYMMDDhhmmss'-formatted string. INTERFACES: See 'INTERFACES:' in the module declaration below. RESOURCES: None. REFERENCES: None. PROCESSING: See below. DATA: See 'DATA:' in the class header below. LOGIC: - *******************************************************************************/ #include <string> #include "ErrorHandling.h" // Util #include "Types.h" namespace DISE { // Description: Converts a 'YYYYMMDDhhmm'-formatted time string into a CMSGTime object. // Returns: A CMSGTime object. inline SYSTIME YYYYMMDDhhmm ( const std::string& i_Time ) { try { PRECONDITION(i_Time.size() >= 12); unsigned int year = (i_Time[ 0] - '0') * 1000 + (i_Time[ 1] - '0') * 100 + (i_Time[ 2] - '0') * 10 + (i_Time[ 3] - '0') * 1; unsigned int month = (i_Time[ 4] - '0') * 10 + (i_Time[ 5] - '0') * 1; unsigned int day = (i_Time[ 6] - '0') * 10 + (i_Time[ 7] - '0') * 1; unsigned int hour = (i_Time[ 8] - '0') * 10 + (i_Time[ 9] - '0') * 1; unsigned int minute = (i_Time[10] - '0') * 10 + (i_Time[11] - '0') * 1; return SYSTIME(year, month, day, hour, minute); } catch (...) { LOGCATCHANDTHROW; } } // Description: Converts a CMSGTime object into a 'YYYYMMDDhhmm'-formatted string. // Returns: Time value as a YYYYMMDDhhmm'-formatted string. inline std::string YYYYMMDDhhmm ( SYSTIME& i_Time ) { try { #ifdef WIN32 return i_Time.FormatDate("yyyyMMdd") + i_Time.FormatTime("HHmm"); #else return i_Time.Format("yyyyMMddHHmm"); #endif } catch (...) { LOGCATCHANDTHROW; } } // Description: Converts a 'YYYYMMDDhhmmss'-formatted time string into a CMSGTime object. // Returns: A CMSGTime object. inline SYSTIME YYYYMMDDhhmmss ( const std::string& i_Time ) { try { PRECONDITION(i_Time.size() >= 14); unsigned int year = (i_Time[ 0] - '0') * 1000 + (i_Time[ 1] - '0') * 100 + (i_Time[ 2] - '0') * 10 + (i_Time[ 3] - '0') * 1; unsigned int month = (i_Time[ 4] - '0') * 10 + (i_Time[ 5] - '0') * 1; unsigned int day = (i_Time[ 6] - '0') * 10 + (i_Time[ 7] - '0') * 1; unsigned int hour = (i_Time[ 8] - '0') * 10 + (i_Time[ 9] - '0') * 1; unsigned int minute = (i_Time[10] - '0') * 10 + (i_Time[11] - '0') * 1; unsigned int second = (i_Time[12] - '0') * 10 + (i_Time[13] - '0') * 1; return SYSTIME(year, month, day, hour, minute, second); } catch (...) { LOGCATCHANDTHROW; } } // Description: Converts a CMSGTime object into a 'YYYYMMDDhhmmss'-formatted string. // Returns: Time value as a YYYYMMDDhhmmss'-formatted string. inline std::string YYYYMMDDhhmmss ( SYSTIME& i_Time ) { try { #ifdef WIN32 return i_Time.FormatDate("yyyyMMdd") + i_Time.FormatTime("HHmm"); #else return i_Time.Format("yyyyMMddHHmm"); #endif } catch (...) { LOGCATCHANDTHROW; } } } // end namespace #endif
5a2082da1ba575885e7b50064983608055ac591c
c0c44b30d6a9fd5896fd3dce703c98764c0c447f
/cpp/Shared/NavGzipUtil.cpp
04c9b813694a94761052e693885b21abdb0caa1e
[ "BSD-3-Clause" ]
permissive
wayfinder/Wayfinder-CppCore-v2
59d703b3a9fdf4a67f9b75fbbf4474933aeda7bf
f1d41905bf7523351bc0a1a6b08d04b06c533bd4
refs/heads/master
2020-05-19T15:54:41.035880
2010-06-29T11:56:03
2010-06-29T11:56:03
744,294
1
0
null
null
null
null
UTF-8
C++
false
false
4,710
cpp
NavGzipUtil.cpp
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "NavGzipUtil.h" #if defined( HAVE_ZLIB ) || defined(__SYMBIAN32__) #if defined __SYMBIAN32__ && !defined NAV2_CLIENT_UIQ3 #include <ezlib.h> #else #include <zlib.h> #endif // For EOF //#include <stdio.h> int NavGzipUtil::gzip(unsigned char* p_outBuffer, int p_outlen, const unsigned char* p_inBuffer, int p_inlen, int compressionLevel) { // Using zlib types. uLong outLen = p_outlen; Byte* outData = p_outBuffer; // Zlib starts int err; int pos = 0; bool ok = true; int level = Z_DEFAULT_COMPRESSION; //Z_BEST_SPEED // Set level according to in-value if it is within bounds. if ( compressionLevel >= Z_NO_COMPRESSION && compressionLevel <= Z_BEST_COMPRESSION ) { level = compressionLevel; } int strategy = Z_DEFAULT_STRATEGY; z_stream s; uLong crc = crc32( 0L, Z_NULL, 0); static const int gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */ #define OS_CODE 0x03 /* Default Unix */ #define MEM_LEVEL 8 s.next_in = s.next_out = Z_NULL; s.avail_in = s.avail_out = 0; s.msg = 0; s.zalloc = (alloc_func)0; s.zfree = (free_func)0; s.opaque = (voidpf)0; // windowBits is passed < 0 to suppress zlib header // Undocumented feature! err = deflateInit2( &s, level, Z_DEFLATED, -MAX_WBITS, MEM_LEVEL, strategy ); if ( err != Z_OK ) { ok = false; } // Set indata s.next_in = (Byte*)p_inBuffer; s.avail_in = p_inlen; uLong outPos = 0L; if ( outLen >= 10 ) { // Make gzip header outData[ 0 ] = gz_magic[0]; outData[ 1 ] = gz_magic[1]; outData[ 2 ] = Z_DEFLATED; outData[ 3 ] = 0; /*flags*/ outData[ 4 ] = 0; /*time*/ outData[ 5 ] = 0; outData[ 6 ] = 0; outData[ 7 ] = 0; outData[ 8 ] = 0; /*xflags*/ outData[ 9 ] = OS_CODE; outPos = 10L; } else { ok = false; } // Set outbuff s.next_out = outData + outPos; s.avail_out = outLen - outPos; // Compress err = deflate( &(s), Z_FINISH ); // Finnish as in flush to outbuff if ( err != Z_OK && err != Z_STREAM_END ) { ok = false; } // Update crc crc = crc32(crc, p_inBuffer, p_inlen); // Append gzip end (crc+uncompressed length) if ( s.avail_out >= 8 ) { *s.next_out++ = crc; *s.next_out++ = crc>>8; *s.next_out++ = crc>>16; *s.next_out++ = crc>>24; s.total_out += 4; int tot = s.total_in; *s.next_out++ = tot; *s.next_out++ = tot>>8; *s.next_out++ = tot>>16; *s.next_out++ = tot>>24; s.total_out += 4; } else { ok = false; s.next_out = outData + outLen; } pos = s.total_in; outPos = (s.next_out - outData); // Clean zlib stream err = deflateEnd ( &s ); if ( err != Z_OK ) { } if ( ok ) { return outPos; } else { return -1; } } #else int NavGzipUtil::gzip(unsigned char* p_outBuffer, int p_outlen, const unsigned char* p_inBuffer, int p_inlen, int compressionLevel) { return -1; } #endif // HAVE_ZLIB
cb60b196b2c0c1f0ec2becbc760784cdce313b73
c8bc7f4de1543b4a5d5f0d50ef75b1afd995c47b
/main.cpp
b861f95fe7534d9787dd362290e5c65a3109d426
[]
no_license
AGlass0fMilk/ep-example-ble-serial
74942c25cdcc6ae572ff7dea0f002f19433fbd2d
f1cbc7a321fa1617e2f0de96684e399038e0f0ea
refs/heads/master
2023-01-03T22:44:10.040503
2020-10-19T20:44:49
2020-10-19T20:44:49
305,508,939
0
0
null
null
null
null
UTF-8
C++
false
false
4,534
cpp
main.cpp
/* mbed Microcontroller Library * Copyright (c) 2017-2019 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include "platform/Callback.h" #include "platform/NonCopyable.h" #include "platform/mbed_stats.h" #include "ble/GattServer.h" #include "BLEProcess.h" #include "UARTService.h" #include "rtos/Thread.h" #include "rtos/ThisThread.h" #include "rtos/Queue.h" #include "rtos/EventFlags.h" #include "rtos/Mutex.h" #include "events/EventQueue.h" #include "mbed_trace.h" #include <memory> #include <string> #include "ChainableGattServerEventHandler.h" #include "ChainableGapEventHandler.h" #define TRACE_GROUP "main" using namespace std::chrono; UARTService uart_service; static volatile ble::connection_handle_t connection = 0; mbed::SharedPtr<UARTService::BleSerial> ser; static rtos::Thread ble_thread; #define EVENT_FLAGS_CONNECTED 0x0001 static rtos::EventFlags flags; static PlatformMutex tr_mutex; void trace_mutex_wait(void) { tr_mutex.lock(); } void trace_mutex_release(void) { tr_mutex.unlock(); } void trace_init(void) { mbed_trace_mutex_wait_function_set(trace_mutex_wait); mbed_trace_mutex_release_function_set(trace_mutex_release); mbed_trace_init(); } // Works for simple single-connection use cases class ConnectionManager : public Gap::EventHandler { public: virtual ~ConnectionManager() { } void onConnectionComplete(const ble::ConnectionCompleteEvent &event) { connection = event.getConnectionHandle(); flags.set(EVENT_FLAGS_CONNECTED); } }; ChainableGapEventHandler gap_eh; void ble_main(void) { BLE &ble_interface = BLE::Instance(); events::EventQueue ble_queue; BLEProcess ble_process(ble_queue, ble_interface); static ChainableGattServerEventHandler eh; eh.addEventHandler(&uart_service); ble_interface.gattServer().setEventHandler(&eh); static ConnectionManager conn_mgr; gap_eh.addEventHandler(&conn_mgr); gap_eh.addEventHandler(&uart_service); // TODO - rework this, ble process currently adds itself and sets Gap handler ble_process.on_init(callback(&uart_service, &UARTService::start)); // TESTING //ble_queue.call_every(3s, mbed::callback(test_write)); // bind the event queue to the ble interface, initialize the interface // and start advertising ble_process.start(); } void print_heap_stats(void) { mbed_stats_heap_t stats; mbed_stats_heap_get(&stats); tr_info("heap stats:\r\n" "current size: %lu\r\n" "max size: %lu\r\n" "total size: %lu\r\n" "reserved size: %lu\r\n" "alloc cnt: %lu\r\n" "alloc fail cnt: %lu\r\n" "overhead size: %lu\r\n", stats.current_size, stats.max_size, stats.total_size, stats.reserved_size, stats.alloc_cnt, stats.alloc_fail_cnt, stats.overhead_size); } int main() { trace_init(); ble_thread.start(mbed::callback(ble_main)); while(true) { // Print heap stats before print_heap_stats(); // Wait until we're connected flags.wait_any_for(EVENT_FLAGS_CONNECTED, rtos::Kernel::wait_for_u32_forever); tr_info("connected, getting BleSerial handle"); ser = uart_service.get_ble_serial_handle(connection); // Print heap stats after print_heap_stats(); while(!ser->is_shutdown()) { // Read 10 bytes and echo them back... uint8_t c = 0; ssize_t result = ser->read(&c, 10); // echo it back if(result == -ESHUTDOWN) { tr_info("BleSerial shutdown while reading!"); ser = nullptr; } else { result = ser->write(&c, result); if(result == -ESHUTDOWN) { tr_info("BleSerial shutdown while writing!"); ser = nullptr; } } } } }
527f14c91ccf60f602acb8b4d9f439ab7a47f7e6
80c1f66a145ea8f37191d7df5e3893ca9826c7b6
/Source.cpp
c37d3f2c13fa5eb0a9a41851992b75463c5871d7
[ "MIT" ]
permissive
AneesMuzzafer/21-Flags
beba10bad25b273aa1af2e0708b6c97d42facfd8
dca29c219a75400621a1756148cf1846ef581b3a
refs/heads/master
2021-08-08T04:20:45.169208
2017-11-09T15:10:57
2017-11-09T15:10:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,466
cpp
Source.cpp
#include<stdio.h> int main() { int a[21]; int i, j = 0; int p1, p2, t; for (i=0;i<21; i++) { a[i] = 21-i; } printf("\n\n\n\t\t\t\t21 FLAGS\n\n\t\t\t\tInstructions.\nThere are 21 flags. Each player can take 1,2 or 3 flags in each turn.The player to take the last flag wins.\n\n\t\t\t|"); for (i = 0; i<21; i++) { if (a[i] == 0) { printf("*|"); } else printf("%d|", a[i]); } printf("\n\n\t\tYou have to play this game against the computer. Are you smarter than a Machine?\n\t\tPress 1 if you want to start or press 2 if you want the computer to start.\n"); scanf_s("%d", &t); if (t == 2) { while (1) { if ((21 - j) <= 3) { printf("\n\n\t\t\t\tCOMPUTER WINS."); break; } p1 = (21 - j) % 4; for (i = 0; i<p1; i++) a[j++] = 0; printf("\nComp took %d flags.\n\n\t\t\t\t |", p1); for (i = 0; i<21; i++) { if (a[i] == 0) { printf("*|"); } else printf("%d|", a[i]); } if ((21 - j) <= 3) { printf("\n\n\n\t\t\t\tYOU WIN."); break; } printf("\n\nEnter your choice:"); while (1) { scanf_s("%d", &p2); if (p2 == 1 || p2 == 2 || p2 == 3) break; printf("\nInvalid choice. Enter again:"); } for (i = 0; i<p2; i++) { a[j++] = 0; } printf("\n\t\t\t\t"); for (i = 0; i<21; i++) { if (a[i] == 0) { printf("*|"); } else printf("%d|", a[i]); } printf("\n\nComputer's turn"); } } else if (t == 1) { while (1) { if ((21 - j) <= 3) { printf("\n\n\t\t\t\tYOU WIN."); break; } printf("\nEnter your choice:"); scanf_s("%d", &p2); for (i = 0; i<p2; i++) { a[j++] = 0; } printf("\n\t\t\t |"); for (i = 0; i<21; i++) { if (a[i] == 0) { printf("*|"); } else printf("%d|", a[i]); } //printf("\n\nComputers turn:press n key"); if ((21 - j) <= 3) { printf("\n\n\t\t\t\tCOMPUTER WINS."); break; } if (((21 - j) % 4) == 0) p1 = 1; else p1 = (21 - j) % 4; for (i = 0; i<p1; i++) a[j++] = 0; printf("\n\n Computer took %d flags.\n", p1); printf("\n\n\t\t\t |"); for (i = 0; i<21; i++) { if (a[i] == 0) { printf("*|"); } else printf("%d|", a[i]); } } } getchar(); getchar(); }
f1a7c2a3352ee218effc618c84b64f16810d0c96
a5ad5f4fcbc5dcc8423f04f587b50a11d38441de
/AllProject/All.ino
1689a19a3319c6b14b23277067a3ae74c6959abd
[]
no_license
mananssnay/SuperAlcoholDispenser
677a81848c808f6265e872874f79b50660d2e36a
e80e39201306700b9af8b868edaf81601807f735
refs/heads/master
2022-11-10T09:46:54.294930
2020-06-26T03:51:39
2020-06-26T03:51:39
272,053,839
0
0
null
null
null
null
UTF-8
C++
false
false
1,894
ino
All.ino
#include <Servo.h> Servo myservo; #include <Wire.h> #include <Adafruit_MLX90614.h> #include <LiquidCrystal_I2C.h> Adafruit_MLX90614 mlx = Adafruit_MLX90614(); LiquidCrystal_I2C lcd(0x27, 16, 2); int trigPin = 13; int echoPin = 12; int servoPin = 9; long duration, distance, average; long aver[13]; double temp_amb; double temp_obj; void setup(){ Serial.begin(9600); myservo.attach(servoPin); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); myservo.write(0); delay(100); myservo.detach(); Serial.println("Temperature Sensor MLX90614"); lcd.init(); lcd.backlight(); mlx.begin(); } int sensor = 0; void loop(){ digitalWrite(10,HIGH); digitalWrite(trigPin,LOW); delayMicroseconds(5); digitalWrite(trigPin,HIGH); delayMicroseconds(15); digitalWrite(trigPin,LOW); pinMode(echoPin,INPUT); duration = pulseIn(echoPin,HIGH); distance = duration * 0.034 / 2; for (int sensor=0; sensor<=2; sensor++){ aver[sensor] = distance; delay(10); } if (distance<=50){ myservo.attach(servoPin); delay(1); myservo.write(0); delay(500); myservo.write(180); delay(500); myservo.detach(); } Serial.print(distance); temp_amb = mlx.readAmbientTempC(); temp_obj = mlx.readObjectTempC(); lcd.setCursor(0,0); lcd.print("Room Temp :"); lcd.setCursor(10,0); lcd.print(temp_amb); lcd.setCursor(15,0); lcd.write(1); lcd.setCursor(0,1); lcd.print("Object :"); lcd.setCursor(10,1); lcd.print(temp_obj); lcd.setCursor(15,1); lcd.write(1); Serial.print("Room Temp = "); Serial.print(temp_amb); Serial.print("Object Temp = "); Serial.print(temp_obj); Serial.println(); delay(500); }
5fa960e45473005c66af39a485c522dee8b3c226
b39dba38a99bc970d7c861517ab82bb92f5fc548
/mptrack/MPTrackUtilWine.h
bae1d38edc2cf13c0e550598ab93d0f25e81af5d
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
OpenMPT/openmpt
711aef385c6a098a9a2aaefa25f6563e4501d2e8
41c5bde364ed61afb414ac38792715ee9433c01c
refs/heads/master
2023-09-01T21:37:18.329917
2023-09-01T10:10:22
2023-09-01T10:10:22
82,913,630
501
87
BSD-3-Clause
2023-07-14T08:47:12
2017-02-23T10:04:01
C++
UTF-8
C++
false
false
1,129
h
MPTrackUtilWine.h
/* * MPTrackUtilWine.h * ----------------- * Purpose: Wine utility functions. * Notes : (currently none) * Authors: OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #pragma once #include "openmpt/all/BuildSettings.hpp" #include "../misc/mptWine.h" OPENMPT_NAMESPACE_BEGIN namespace Util { namespace Wine { mpt::Wine::ExecResult ExecutePosixShellScript(mpt::Wine::Context & wine, std::string script, FlagSet<mpt::Wine::ExecFlags> flags, std::map<std::string, std::vector<char> > filetree, std::string title, std::string status); class Dialog { private: bool m_Terminal; std::string m_Title; private: std::string DialogVar() const; public: Dialog(std::string title, bool terminal); std::string Title() const; std::string Detect() const; std::string Status(std::string text) const; std::string MessageBox(std::string text) const; std::string YesNo(std::string text) const; std::string TextBox(std::string filename) const; std::string Progress(std::string text) const; }; } // namespace Wine } // namespace Util OPENMPT_NAMESPACE_END
0fa7a69b5c5bfcbe80611079b7c0833cb00eb911
f3f1c3fdd9054ad5cef148f82d401a238f27a305
/PT STG/stage.cpp
f2fb1d3b593d37aae0673c312e786de006ca08c6
[]
no_license
handmanp/PT-STG
1c1ae2d4c1babd8993b23a0251c6691bebdc8064
5b02d2ea336a659ba4fabc58c2836bb84ffec8c7
refs/heads/master
2021-08-27T22:21:47.015652
2017-11-14T21:13:49
2017-11-14T21:13:49
107,426,721
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
13,626
cpp
stage.cpp
#include "global.h" using namespace std; // ステージの初期化 // sx:ステージ幅 sy:ステージ高さ void my_Stage::init(int sx, int sy) { // クラス用再定義 stage_size_x = sx; //サイズ stage_size_y = sy; // 3次元配列の動的確保(カッコイイ) stage_size = new int*[stage_size_x]; for (int i = 0; i < stage_size_x; i++) { stage_size[i] = new int[stage_size_y]; } // 初期化 for (int i = 0; i < stage_size_x; i++) { for (int j = 0; j < stage_size_y; j++) { stage_size[i][j] = -1; } } memset(enemy_count, 0, sizeof(enemy_count)); } // メタ入力 true = 多分成功してる, false = 多分失敗してる // *------------------------------------------------------------------------------------* void my_Stage::io_LoadMetaData(char *path) { FILE *fp_meta; fopen_s(&fp_meta, path, "r"); STAGE_METAS meta; fread_s(&meta, sizeof(STAGE_METAS), sizeof(STAGE_METAS), 1, fp_meta); stage_size_x = meta.x; stage_size_y = meta.y; } // 入力 true = 多分成功してる, false = 多分失敗してる // *------------------------------------------------------------------------------------* bool my_Stage::io_MapdataFileLoad() { char paths[128]; sprintf_s(paths, 128, "data/maps/stage_%d/mapmeta.txt", 1); io_LoadMetaData(paths); init(stage_size_x, stage_size_y); char path[128]; //sprintf_s(path, 128, "data/editor/saves/0%d/mapdata.txt", map_slot); sprintf_s(path, 128, "data/maps/stage_%d/mapdata.txt", 1); ifstream ifs; ifs.open(path); for (int i = 0; i < stage_size_x; ++i) { for (int j = 0; j < stage_size_y; ++j) { ifs >> stage_size[i][j]; } } ifs.close(); return true; } // ステージの破棄 // ※コレ通さないと死ぬから注意 void my_Stage::del_Stage() { for (int i = 0; i < stage_size_x; i++) { delete[] stage_size[i]; } delete[] stage_size; //delete[] stage_data; } // ステージの移動 // s:移動スピート r:移動角度 void my_Stage::move(int s, int r) { // スピードをメンバに追加 speed = s; //ラジアンにする move_rad = (DX_PI_F / 180.0f) * r; // 移動処理 x += sinf(move_rad) * s * frame_Time; y += cosf(move_rad) * s * frame_Time; } // ステージを描画 void my_Stage::draw() { for (int i = 0; i < stage_size_x; i++) { for (int j = 0; j < stage_size_y; j++) { if (stage_size[i][j] != -1) { //ブロックの相対座標 int dpx = (i * STAGE_TIP_SIZE) - x; int dpy = (j * STAGE_TIP_SIZE) - y; //面内のみ描画 if (dpx >= -STAGE_TIP_SIZE && dpx <= WINDOW_SIZE_X + STAGE_TIP_SIZE && dpy >= -STAGE_TIP_SIZE && dpy <= WINDOW_SIZE_Y + STAGE_TIP_SIZE) { DrawGraph(dpx, dpy, maptip_img[stage_size[i][j]], TRUE); // ステージと自機との当たり判定 if (abs((dpx + (STAGE_TIP_SIZE / 2)) - ship.x) < (STAGE_TIP_SIZE + 80) / 2 && abs((dpy + (STAGE_TIP_SIZE / 2)) - ship.y) < (STAGE_TIP_SIZE + 15) / 2) { if (ship.stat == 0) { ship.stat = -1; ship.x = -120.f; ship.y = 340.f; ship.left -= 1; } } } } } } /*for (int i = 0; i < enemy_max; i++) { DrawFormatString(10, 100 + (i * 20), GetColor(200, 200, 200), "%d, %d, %d, %d, %d, %d, %d", stage_data[i].start_x, stage_data[i].enemy_type, stage_data[i].var_1, stage_data[i].var_2, stage_data[i].var_3, stage_data[i].var_4, stage_data[i].var_5, stage_data[i].var_6, stage_data[i].var_7); }*/ } // ステージの位置を移動する void my_Stage::set_StagePos(float sx, float sy) { x = sx; y = sy; } // ステージの進行 void my_Stage::stage_Progression() { // *================ CSV解析部 ==================* // for (int i = 0; i < enemy_max; i++) { // 登場X座標を迎えたら if ((int)x >= stage_data[i].start_x && stage_data[i].stat != -1) { stage_data[i].stat = -1; // 敵のインスタンス作成 switch (stage_data[i].enemy_type) { // *------------------------ Stage 1 ------------------------* // [0] ナッツ OK case EneNuts: nuts[enemy_count[EneNuts]].init(stage_data[i].var_1, stage_data[i].var_2, stage_data[i].var_3, stage_data[i].var_4, stage_data[i].var_5); enemy_count[EneNuts]++; break; // [1] エダマメン wip case EneEdamamen: // wip break; // [2] ウニズ case EneUnis: unis[enemy_count[EneUnis]].init(stage_data[i].var_1, stage_data[i].var_2, stage_data[i].var_3, stage_data[i].var_4, stage_data[i].var_5); enemy_count[EneUnis]++; break; // [3] ジェノサイドバナナ case EneBanana: banana[enemy_count[EneBanana]].init(stage_data[i].var_1, stage_data[i].var_2, stage_data[i].var_3, stage_data[i].var_4); enemy_count[EneBanana]++; break; // [4] ピネ case EnePine: pine[enemy_count[EnePine]].init(stage_data[i].var_1, stage_data[i].var_2, stage_data[i].var_3, stage_data[i].var_4, stage_data[i].var_5); enemy_count[EnePine]++; break; // [5] カイ OK case EneKai: shell[enemy_count[EneKai]].init(stage_data[i].var_1, stage_data[i].var_2, stage_data[i].var_3, stage_data[i].var_4); enemy_count[EneKai]++; break; // [6] タケノコン wip case EneTakenokon: break; // [7] キノコン wip case EneKinokon: break; // *------------------------ Stage 2 ------------------------* // [8] クワガタン case EneKuwagatan: kuwagatan[enemy_count[EneKuwagatan]].init(stage_data[i].var_1, stage_data[i].var_2, stage_data[i].var_3, stage_data[i].var_4); enemy_count[EneKuwagatan]++; break; // [9] ミートボールスパム case EneMeatball: meat[enemy_count[EneMeatball]].init(stage_data[i].var_1, stage_data[i].var_2, stage_data[i].var_3, stage_data[i].var_4); enemy_count[EneMeatball]++; break; // [10] 胞子 case EneHoushi: houshi[enemy_count[EneHoushi]].init(stage_data[i].var_1, stage_data[i].var_2, stage_data[i].var_3, stage_data[i].var_4); enemy_count[EneHoushi]++; break; // [11] ワーム case EneWarm: worm[enemy_count[EneWarm]].init(stage_data[i].var_1, stage_data[i].var_2, stage_data[i].var_3, stage_data[i].var_4); enemy_count[EneWarm]++; break; // [12] ツタン case EneTutan: ivy[enemy_count[EneTutan]].init(stage_data[i].var_1, stage_data[i].var_2, stage_data[i].var_3, stage_data[i].var_4); enemy_count[EneTutan]++; break; // [13] ムービングスタチュー case EneStatue: statue[enemy_count[EneStatue]].init(stage_data[i].var_1, stage_data[i].var_2, stage_data[i].var_3, stage_data[i].var_4); enemy_count[EneStatue]++; break; // *------------------------ Stage 3 ------------------------* // [14] キモ箱 wip case EneKimobako: break; // [15] デテクルーノ(花) wip case EneDetekuruno: detecrew[enemy_count[EneDetekuruno]].init(stage_data[i].var_1, stage_data[i].var_2, stage_data[i].var_3, stage_data[i].var_4); enemy_count[EneDetekuruno]++; break; // [16] デテクルーノ(茎) wip case EneDetekuki: break; // [17] シンダーラタマウツ case EneTamautsu: sindarla[enemy_count[EneTamautsu]].init(stage_data[i].var_1, stage_data[i].var_2, stage_data[i].var_3, stage_data[i].var_4); enemy_count[EneTamautsu]++; break; // [18] 戦艦ジェノサイド case EneGenocide: genocide[enemy_count[EneGenocide]].init(stage_data[i].var_1, stage_data[i].var_2, stage_data[i].var_3, stage_data[i].var_4); enemy_count[EneGenocide]++; break; // *------------------------ Stage 3 ------------------------* // [19] タコス wip case BossTacos: break; // [20] ノウミソン wip case BossNoumison: brain[enemy_count[BossNoumison]].init(stage_data[i].var_1, stage_data[i].var_2, stage_data[i].var_3, stage_data[i].var_4); enemy_count[BossNoumison]++; break; // [21] ワーミン wip case BossWarmin: break; // 100 マップの移動速度・角度変更 case 100: to_stage_scroll_speed = stage_data[i].var_1; to_stage_scroll_rad = stage_data[i].var_2; break; // 100 マップの座標移動 case 101: test.set_StagePos(stage_data[i].var_1, stage_data[i].var_2); break; // 110 楽曲の再生 case 110: PlaySoundMem(game_bgmhnd[stage_data[i].var_1], DX_PLAYTYPE_BACK, TRUE); break; } } } } void my_Stage::stage_EnemyMove() { // *------------------------ Stage 1 ------------------------* for (int i = 0; i < enemy_count[EneNuts]; i++) { nuts[i].move(); } for (int i = 0; i < enemy_count[EneEdamamen]; i++) { //edamamen[i].move(); wip } for (int i = 0; i < enemy_count[EneUnis]; i++) { unis[i].move(); } for (int i = 0; i < enemy_count[EneBanana]; i++) { banana[i].move(); } for (int i = 0; i < enemy_count[EnePine]; i++) { pine[i].move(); } for (int i = 0; i < enemy_count[EneKai]; i++) { shell[i].move(); } for (int i = 0; i < enemy_count[EneTakenokon]; i++) { //takenokon[i].move(); wip } for (int i = 0; i < enemy_count[EneKinokon]; i++) { //nokonoko[i].move(); wip } // *------------------------ Stage 2 ------------------------* for (int i = 0; i < enemy_count[EneKuwagatan]; i++) { kuwagatan[i].move(); } for (int i = 0; i < enemy_count[EneMeatball]; i++) { meat[i].move(); } for (int i = 0; i < enemy_count[EneHoushi]; i++) { houshi[i].move(); } for (int i = 0; i < enemy_count[EneWarm]; i++) { worm[i].move(); } for (int i = 0; i < enemy_count[EneTutan]; i++) { ivy[i].move(); } for (int i = 0; i < enemy_count[EneStatue]; i++) { statue[i].move(); } // *------------------------ Stage 3 ------------------------* for (int i = 0; i < enemy_count[EneKimobako]; i++) { //kimobako[i].move(); wip } for (int i = 0; i < enemy_count[EneDetekuruno]; i++) { //detekuruno[i].move(); wip } for (int i = 0; i < enemy_count[EneDetekuki]; i++) { //detekuki[i].move(); wip } for (int i = 0; i < enemy_count[EneTamautsu]; i++) { sindarla[i].move(); } for (int i = 0; i < enemy_count[EneGenocide]; i++) { genocide[i].move(); } // *------------------------ Stage 3 ------------------------* for (int i = 0; i < enemy_count[BossNoumison]; i++) { brain[i].move(); } } // CSV読み込み void my_Stage::io_StageDataLoad() { for (int i = 0; i < 300; i++) { stage_data[i].start_x = -1; stage_data[i].enemy_type = -1; stage_data[i].var_1 = 0; stage_data[i].var_2 = 0; stage_data[i].var_3 = 0; stage_data[i].var_4 = 0; stage_data[i].var_5 = 0; stage_data[i].var_6 = 0; stage_data[i].var_7 = 0; stage_data[i].stat = 0; } // たりなさそうなら適時増やす const int BufMax = 128; char buf[BufMax]; FILE *fp = NULL; int line_count = 0; char (*data)[BufMax]; // CSVを開く errno_t err; err = fopen_s(&fp, _T("data/maps/stage_1/stagedata.csv"), "r"); if (err == 0) { while (fgets(buf, sizeof(buf), fp) != NULL){ line_count++; } } // 今後のループ用に enemy_max = line_count; fclose(fp); fp = NULL; // CSVを開く(読み込まないとFPのポインタが初期化されなくてなんかうまくいかないけど汚いよね) err = fopen_s(&fp, _T("data/maps/stage_1/stagedata.csv"), "r"); // 格納時に使う変数初期化 int c; int col = 1; int row = 0; memset(buf, 0, sizeof(buf)); // ここから先は結構マジック // ヘッダ読み飛ばし //while (fgetc(fp) != '\n'); while (1) { while (1) { c = fgetc(fp); // 末尾ならループを抜ける。 if (c == EOF) goto LOOP_OUT; // カンマか改行でなければ、文字としてつなげる if (c != ',' && c != '\n') { strcat_s(buf, (const char*)&c); } // カンマか改行ならループ抜ける。 else { break; } } // ここに来たということは、1セル分の文字列が出来上がったということ switch (col) { // インスタンス生成X座標 case 1: stage_data[row].start_x = atoi(buf); break; // 敵の種類 case 2: stage_data[row].enemy_type = atoi(buf); break; // 各インスタンスの引数 case 3: stage_data[row].var_1 = atoi(buf); break; case 4: stage_data[row].var_2 = atoi(buf); break; case 5: stage_data[row].var_3 = atoi(buf); break; case 6: stage_data[row].var_4 = atoi(buf); break; case 7: stage_data[row].var_5 = atoi(buf); break; case 8: stage_data[row].var_6 = atoi(buf); break; case 9: stage_data[row].var_7 = atoi(buf); break; } // バッファを初期化 memset(buf, 0, sizeof(buf)); // 列数を足す col++; // もし読み込んだ文字が改行だったら列数を初期化して行数を増やす if (c == '\n') { col = 1; row++; } } LOOP_OUT: // ループパス用のラベル fclose(fp); } /* // 文字列を分割する vector<string> split(string& input, char delimiter){ istringstream stream(input); string field; vector<string> result; while (getline(stream, field, delimiter)) { result.push_back(field); } return result; } */
3a8098732613ac7c762ffa554788ee2f23fdc1ec
45ff2429af133fc2e36803a2a8e1492be5b73dc9
/Question9/9_2.cpp
fdb64ce8c926566a4e3a355d140a05675aa58dd8
[]
no_license
piyushkandpal/CrackingTheCodingInterview
f663d7398a88201df43d44134abecb0cd5e03e1e
a5afb5ee3b5dc6b859141ed7d13a8e47c67d6d4f
refs/heads/master
2016-09-06T21:29:16.629512
2015-05-10T19:02:13
2015-05-10T19:02:13
35,383,539
0
0
null
null
null
null
UTF-8
C++
false
false
2,142
cpp
9_2.cpp
#include<iostream> #include<vector> #include<map> using namespace std; class Point { private: int x,y; public: Point(int x,int y) { this->x = x; this->y = y; } friend bool operator<(const Point& lhs,const Point& rhs); /* OR we can also keep */ bool operator<(Point const& other) { return (this->x < other.x && this->y < other.y); } int getX() const { return x;} int getY() const { return y;} friend ostream& operator<<(ostream& os,const Point&p); }; ostream& operator<<(ostream& os,const Point&p) { return os<<"("<<p.getX()<<","<<p.getY()<<")"; } bool operator<(const Point& lhs,const Point& rhs) { return (lhs.x < rhs.x || lhs.y < rhs.y); } bool isFree(int x, int y) { return 1; } i bool getAllPaths(int x,int y) { vector<Point> path; vector<vector<Point> > vpath; map<Point,bool> mapPoints; getPath(3,3,vpath,mapPoints); vector<vector<Point> >::iterator vit; <vector<Point>::iterator it; for (vit=vpath.begin();vit!=vpath.end();vit++) for (it=(*vit).begin();it!=(*vit).end();it++) cout<<*it; cout<<endl; } bool getPath(int x,int y,vector<vector<Point>>& vpath, map<Point,bool>& cache) { Point *p= new Point(x,y); map<Point,bool>::iterator mIter = cache.find(*p); vector<Point>::iterator it; vector<vector<Point> >::iterator vit; // if already visited this cell if(mIter!=cache.end()) { return mIter->second; // *miter is a pair } if (x==0 && y ==0) { vpath.push_back(path) return true; } bool success = false; if(x >= 1 && isFree(x-1,y)) { //Try right success = getPath(x-1,y,path,cache);//Free .. go right } if(success) { path.push_back(*p); } if(y>=1 && isFree(x,y-1)) {// Try down success = getPath(x,y-1,path,cache);//Free .. go down cout<<endl; } if(success) { path.push_back(*p); } cache[*p] = success; return success; } int main() { getAllPaths(3,3); }
4d1ad0ad9cd68e1d64c09d43eaafd4f5906a9b3d
2dbb600c36513e2a43aed48e83403fd20dbb4507
/ND_A2WR/asr_ftc_local_planner/include/ftc_local_planner/join_costmap.h
e6cd72c385118ad15aadbf3e2a1120f03e3f738d
[ "Unlicense", "BSD-3-Clause" ]
permissive
Nurullahdmrly/autonomous2wvehicle_rl_nc
5cf5c652c8d067e2bb400c7d883cd3f5ac8b4e38
45bcc2e201f8d4028f1baa24962b6021baa8e437
refs/heads/main
2023-02-09T17:16:54.472107
2021-01-07T08:04:41
2021-01-07T08:04:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,645
h
join_costmap.h
/** Copyright (c) 2016, Marek Felix All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef FTC_LOCAL_PLANNER_JOIN_COSTMAP_H_ #define FTC_LOCAL_PLANNER_JOIN_COSTMAP_H_ #include <costmap_2d/costmap_2d_ros.h> #include <tf/transform_listener.h> #include <Eigen/Core> #include <vector> using std::vector; namespace ftc_local_planner { class JoinCostmap { public: /** * @brief JoinCostmap constructor. */ JoinCostmap(); /** * @brief initialize the two costmaps and check if resolution global costmap > resolution local costmap. With is neseccary. * @param local_costmap_ros * @param global_costmap_ros */ void initialize(costmap_2d::Costmap2DROS* local_costmap_ros, costmap_2d::Costmap2DROS* global_costmap_ros); /** * @brief joinMaps join the local costmap in the global costmap. */ void joinMaps(); private: costmap_2d::Costmap2DROS* global_costmap_ros_; costmap_2d::Costmap2DROS* local_costmap_ros_; //Vector with all costvalues from the original global costmap. vector<vector<int> > global; //Is initialization true. bool init; }; } #endif
17dc23c76aeaa2035d22b791a289265ccb42412e
b2e3a31147b8dd73890287a53b6ae7c2923adaf9
/cicada/base/fd.cc
3675a94984f67155d60fa65af3e63fea1cb96d83
[ "BSD-2-Clause" ]
permissive
ivanallen/cicada
ca3a5dbc09ee9333c30955cd6a6da2ab82a0dc2c
0842d6133612d15d8867d0696d88251885a7c628
refs/heads/main
2023-07-29T17:18:11.839905
2021-09-05T15:54:33
2021-09-05T15:56:17
403,044,546
0
0
null
null
null
null
UTF-8
C++
false
false
928
cc
fd.cc
// Author: allen #include "cicada/base/fd.h" #include <fcntl.h> #include <unistd.h> #include "cicada/base/macro.h" namespace cicada::base { Fd::Fd(int fd) : _fd(fd) { } Fd::Fd() { } Fd::~Fd() { reset(-1); } void Fd::set_block() { int fd = _fd; int flags = fcntl(fd, F_GETFL, 0); if (flags < 0) { CICADA_ABORT(); } int r = fcntl(fd, F_SETFL, flags & ~O_NONBLOCK); if (r < 0) { CICADA_ABORT(); } } void Fd::set_nonblock() { int fd = _fd; int flags = fcntl(fd, F_GETFL, 0); if (flags < 0) { CICADA_ABORT(); } int r = fcntl(fd, F_SETFL, flags | O_NONBLOCK); if (r < 0) { CICADA_ABORT(); } } int Fd::value() const { return _fd; } int Fd::release() { int fd = _fd; _fd = -1; return fd; } void Fd::reset(int fd) { if (_fd >= 0) { ::close(_fd); } _fd = fd; } } // namespace cicada::base
011dbf203ebf28d26fe655d1c90bcab762c1342f
2787a95f57672d5519d8f14549abe05af31ceeb2
/src/enemy.h
99d8c173c5db65617f416f92b48fc17266e8e285
[]
no_license
cm4233/CppND-Pacman-Game
77105f38ffd2f898e4a04adcf5483107766b065b
96dcefcc43a82559555f6ec47d26f48618c44a9f
refs/heads/master
2022-07-12T20:59:20.743953
2020-05-18T15:09:44
2020-05-18T15:09:44
264,972,007
0
0
null
null
null
null
UTF-8
C++
false
false
1,462
h
enemy.h
#pragma once #include "grid.h" #include "player.h" #include <vector> #include <memory> #include <future> class Enemy{ public: // constructor Enemy(int a, int b): x(a), y(b){} // position int x; int y; // virtual function to move enemy virtual void AI_Move(Grid& grid, Player& player, std::promise<void>&& prms) = 0; }; // blue enemy uses random algorithm to move class BlueEnemy : public Enemy{ public: BlueEnemy(int a, int b): Enemy(a, b){} void AI_Move(Grid& grid, Player& player, std::promise<void>&& prms) override; private: int prev_x = 0; int prev_y = 0; void RunRandomAlgorithmAndMove(Grid& grid); bool Random_valid_cell(int x, int y, Grid& grid); }; // red enemy uses a-star search (player chase) to move class RedEnemy : public Enemy{ public: RedEnemy(int a, int b): Enemy(a, b){} void AI_Move(Grid& grid, Player& player, std::promise<void>&& prms) override; // node for a-star search algorithm struct Node{ int x; int y; int g; int h; std::shared_ptr<Node> parent = nullptr; }; // save the ai path for the renderer to show std::vector<std::vector<int>> ai_path; // frame for render animation int frame = 0; private: // functions for a-star algorithm void RunAStarSearchAndMove(int start_x, int start_y, int goal_x, int goal_y, Grid& grid); int Heuristic(int x1, int y1, int x2, int y2); bool AStar_CheckValidCell(int x, int y, Grid& grid, int(&visited_nodes)[19][23]); };
06f5deb43133eb3807473eda01bdf4c436da7605
ab4e13ab16da57d8a15afc7d43be74bf98cc1d4d
/stat_moses/tools/moses/moses/LM/oxlm/Mapper.cpp
f1363ccf0cbeea68f9d1b88d7707321648b1f793
[ "Apache-2.0" ]
permissive
Deependra-Patel/cs626_project
48c77c30acf2dc27e75cfdd5f603cac5fa767071
4d456e9b41ab63f642b0cb10ee0e2e67c35c3cf3
refs/heads/master
2020-03-09T06:48:56.529079
2014-11-16T23:57:15
2014-11-16T23:57:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,442
cpp
Mapper.cpp
#include "Mapper.h" #include "moses/FactorCollection.h" using namespace std; namespace Moses { OXLMMapper::OXLMMapper(const oxlm::Dict& dict) : dict(dict) { for (int i = 0; i < dict.size(); ++i) { const string &str = dict.Convert(i); FactorCollection &fc = FactorCollection::Instance(); const Moses::Factor *factor = fc.AddFactor(str, false); moses2lbl[factor] = i; //add(i, TD::Convert()); } kUNKNOWN = this->dict.Convert("<unk>"); } int OXLMMapper::convert(const Moses::Factor *factor) const { Coll::const_iterator iter; iter = moses2lbl.find(factor); if (iter == moses2lbl.end()) { return kUNKNOWN; } else { int ret = iter->second; return ret; } } std::vector<int> OXLMMapper::convert(const Phrase &phrase) const { size_t size = phrase.GetSize(); vector<int> ret(size); for (size_t i = 0; i < size; ++i) { const Moses::Factor *factor = phrase.GetFactor(i, 0); int id = convert(factor); ret[i] = id; } return ret; } void OXLMMapper::convert(const std::vector<const Word*> &contextFactor, std::vector<int> &ids, int &word) const { size_t size = contextFactor.size(); ids.resize(size - 1); for (size_t i = 0; i < size - 1; ++i) { const Moses::Factor *factor = contextFactor[i]->GetFactor(0); int id = convert(factor); ids[i] = id; } std::reverse(ids.begin(), ids.end()); const Moses::Factor *factor = contextFactor.back()->GetFactor(0); word = convert(factor); } } // namespace
7572ee729c343548b8b1a2f0dd1d3d0b2fe303c5
0f73598c7fd6bcb55d83a26353c809b2651e7b44
/hpp/TimeFormat.hpp
e7caeda6f92b35eea2cd7b1b646615f421629d04
[ "MIT" ]
permissive
soft9000/era
5ef5ab45b7216de6bc610593f9ba7a2d652f0733
213f6eea2974b7c0f17a4b6bac18763518bd879c
refs/heads/master
2023-07-10T03:45:05.967994
2023-06-24T16:52:05
2023-06-24T16:52:05
86,218,896
0
0
null
null
null
null
UTF-8
C++
false
false
367
hpp
TimeFormat.hpp
#ifndef TimeFormat_hpp1 #define TimeFormat_hpp1 #include "era.hpp" namespace era01 { enum FormatType { ftGlobal, ftLocal }; class TimeFormat { public: static TimeStruct Parse(string str); static string Format(const TimeStruct& time, FormatType ft); static string Format(const TimeGlobal& time); static string Format(const TimeLocal& time); }; } #endif
7655c6695379896f0d31a03b43c31be8c68bb031
5cfc68d4a24e7969e78bb15e124fa579400e810d
/Design_Patterns/Smart_pointer.cpp
d016ad9959c878cc5386ad2e74b631ad40984545
[]
no_license
Pavankumar46/GNP_PROG
8e7566cd196c991211d58ff30f51d3b057cee5ea
82ce027595168901e63bebf3d5c70e4df6330d75
refs/heads/master
2021-12-31T08:14:24.840944
2021-09-24T10:35:04
2021-09-24T10:35:04
204,048,305
0
0
null
null
null
null
UTF-8
C++
false
false
865
cpp
Smart_pointer.cpp
#include <iostream> using namespace std; // A generic smart pointer class class abc { public: int a; }; class bcd { public: int b; }; template <class T> class SmartPtr { T* ptr; // Actual pointer public: // Constructor explicit SmartPtr(T* p = NULL) { ptr = p; } // Destructor ~SmartPtr() { delete (ptr); } // Overloading dereferncing operator T& operator*() { return *ptr; } // Overloading arrow operator so that // members of T can be accessed // like a pointer (useful if T represents // a class or struct or union type) T* operator->() { return ptr; } }; int main() { SmartPtr<abc> ptr(new abc()); ptr->a = 20; cout << ptr->a<<endl; SmartPtr<bcd> ptr1(new bcd()); ptr1->b = 20; cout << ptr1->b; return 0; }
97dd0bb8469be840bc6a22885df221843120f394
070e501345cb31b04f9bee9c437d6e374522081f
/Playstation4/Playstation4/Data.cpp
1d918d68f018dd1ff472280b0d73af9629936899
[]
no_license
WallacePereira/Playstation4
5e06d3ae1a318dbc8a88ef3c8ffb0a0662d7ed43
50eb4df7759fc665b02d0e07e362e5352145a235
refs/heads/master
2021-01-12T02:03:44.014950
2017-02-06T21:25:24
2017-02-06T21:25:24
78,463,741
0
0
null
null
null
null
UTF-8
C++
false
false
1,020
cpp
Data.cpp
#include "Data.h" #include "Playstation4.h" #include <iostream> using namespace std; Data::Data(int dia, int mes, int ano) { this->mes = mes; this->ano = ano; this->dia = checarDia(dia); } Data::Data(const Data &novaData) { this->mes = novaData.mes; this->ano = novaData.ano; this->dia = novaData.dia; } Data::~Data() { } void Data::setData(int dia, int mes, int ano) { this->mes = mes; this->ano = ano; this->dia = checarDia(dia); } int Data::getDia() { return this->dia; } int Data::getMes() { return this->mes; } int Data::getAno() { return this->ano; } int Data::checarDia(int dia) const { static const int diasPorMes[13] = {0, 31, 28, 31, 30, 30, 31, 31, 30, 31, 30, 31}; if(dia > 0 && dia <= diasPorMes[mes]) return dia; if (mes == 2 && dia == 29 && (ano % 400 == 0 || (ano % 4 == 0 && ano % 100 != 0))) return dia; cout << "\nDia invalido\n"; cout << "Digite novamente: \n\n"; return dia=-9999; }
dfbfbfbdd95c94437254d7da6eddc2fb200dd3b8
35cbe063788fbeb956b1c9f26e12eacf5bbe1d00
/src/builtins/eval_file.hpp
9ff072bea739a24a7645f201dabf7b6c62553173
[]
no_license
cbosoft/lisp-interpreter
fcdf8ce5fd1e912cc89926a07e2574ed9981d520
a9a8b3fefa4bceff22ca731f3f6a90da122dbc35
refs/heads/master
2020-09-07T07:40:19.790415
2020-06-23T22:02:55
2020-06-23T22:02:55
220,708,112
0
0
null
null
null
null
UTF-8
C++
false
false
1,218
hpp
eval_file.hpp
#pragma once #include "../types.hpp" #include "../util/formatter.hpp" #include "../util/debug.hpp" #include "../util/exception.hpp" #include "../util/exception_check.hpp" #include "../object/object.hpp" #include "../list/list.hpp" #include "../atom/atom.hpp" #include "../parser/parser.hpp" #include "builtin.hpp" extern LispParser parser; // Boo: global var class LispFunc_eval_file : public virtual LispBuiltin { private: inline static const std::string name = "eval-file"; inline static const std::string doc = "(eval-file path)"; public: LispFunc_eval_file() { } const std::string repr() const { return "Func(" + this->name + ",builtin)"; } const std::string get_doc() const { return this->doc; } LispObject_ptr eval(LispList_ptr arg, LispEnvironment_ptr env) const { (void) env; narg_check(arg, 1, this->repr(), "path"); LispObject_ptr path_obj = arg->next(true); type_check(path_obj, LISPATOM_STRING, this->repr(), "path"); LispAtom_ptr path_atom = path_obj->get_value_atom(); LispList_ptr root = parser.parse_file(path_atom->get_value_string()); return root->eval_each(env); } };
3d3bd8d260c6f838f0ec3daa289999488b1534b4
cbbd486d6bbc1b7c2ace1249412f5240db6efbe0
/sw_study/1767.cpp
3c9dcd5802c7475072f86935d15ac70f848ce6fd
[]
no_license
Cafemug/baekjoon-cpp
f383708e17affbaf3be3ed797c8dac14771e1cc8
cb5452f8d08d071b2f3535009b545555c6a92190
refs/heads/master
2021-10-21T02:18:44.017457
2021-10-18T12:10:50
2021-10-18T12:10:50
116,027,319
3
0
null
null
null
null
UTF-8
C++
false
false
586
cpp
1767.cpp
#include <iostream> #include <cstring> using namespace std; long long mod = 1000001; long long n,m,k; long long d[101][101][101]; long long go(long long x, long long y, long long cnt){ if(cnt ==0) return 1; if(x<=0 || y<=0 || cnt<0) return 0; long long &ans = d[x][y][cnt]; if(ans !=-1) return ans; ans=0; ans += go(x-1,y,cnt); ans += go(x-1,y-1,cnt-1)*y; ans += go(x-1,y-2,cnt-2)*y*(y-1)/2; ans += go(x-2,y-1,cnt-2)*y*(x-1); ans %= mod; return ans; } int main(){ cin>>n>>m>>k; memset(d, -1, sizeof(d)); cout<<go(n,m,k)<<"\n"; }
f040c30436c631ff2d935f17547398f976a069eb
8e63e4fd669ced86bf07b20be364da5a06bce70d
/UVA/12024 - Hats.cpp
552e08749804a1fa6846d0b9f4832554b6f14ba5
[]
no_license
AliOsm/CompetitiveProgramming
00a1e75a2635532651fcdfb0e478c009adf84032
af25b7f806e9c22a2176bfd05a1406ce5f1492c3
refs/heads/master
2023-03-07T01:17:25.555911
2023-02-10T09:09:17
2023-02-10T09:09:17
70,904,119
125
58
null
2021-02-27T13:13:18
2016-10-14T11:29:55
C++
UTF-8
C++
false
false
934
cpp
12024 - Hats.cpp
/* Idea: - We can solve this problem using Dynamic programming and bit masking. - For each query start with mask contains zeros only and where are we now in the mask. - In each state try to put each number i (0 <= i <= n - 1) in the current mask if the i_th bit is not set and the idx does not equal i. */ #include <bits/stdc++.h> using namespace std; int t, n, dp[(1 << 13)][13]; int rec(int msk, int idx) { if(idx == -1) return 1; int &ret = dp[msk][idx]; if(ret != -1) return ret; ret = 0; for(int i = 0; i < n; ++i) if(i != idx && ((msk >> i) & 1) == 0) ret += rec(msk | (1 << i), idx - 1); return ret; } int main() { memset(dp, -1, sizeof dp); long long facts[20] = {1}; for(int i = 1; i < 20; ++i) facts[i] = facts[i - 1] * i; cin >> t; while(t-- != 0) { cin >> n; cout << rec(0, n - 1) << '/' << facts[n] << endl; } return 0; }
98ea5903dba743f530de335ea17467fe75501b76
e46f94683c2b48f4b0b79ca1fbe82d3151e95992
/SmartBin/SmartBin_1/AirQual_TGS26xx/AirQual_TGS26xx.cpp
ef8e6d62df9feb9d28750d46004c9d47fea1427e
[]
no_license
martinosecchi/PervasiveProject
f8a298559bef2c0dc3ebf3217cdba761688d73dd
e4d569557045230575f062669a2d6d64605baf8e
refs/heads/master
2021-01-15T09:14:33.334357
2016-12-13T11:39:13
2016-12-13T11:39:13
68,688,450
0
0
null
null
null
null
UTF-8
C++
false
false
2,571
cpp
AirQual_TGS26xx.cpp
/** AirQual_TGS26xx.h - Library for interfacing with the Figaro TGS26xx series of sensors. Created by Ivan Naumovski, inau @ github.com. **/ #include "Arduino.h" #include <SPI.h> #include <Wire.h> #include "AirQual_TGS26xx.h" int TGS26xx::GetGasPercentage(int gas_id) { float rs_ro_ratio; float ro; //= Ro; if (_type == SEN_00){ ro = Ro3; rs_ro_ratio = MQRead(Ro3); }else if (_type == SEN_02){ ro = Ro6; rs_ro_ratio = MQRead(Ro6); }else return 0; if (_type == SEN_00 ){ if ( gas_id == GAS_C2H5OH ) { return MQGetPercentage(rs_ro_ratio,ro,C2H5OH_terCurve); //TGS2600 } else if ( gas_id == GAS_C4H10 ) { return MQGetPercentage(rs_ro_ratio,ro,C4H10Curve); //TGS2600 } else if ( gas_id == GAS_H2 ) { return MQGetPercentage(rs_ro_ratio,ro,H2_terCurve); //TGS2600 } } if (_type == SEN_02 ){ if ( gas_id == GAS_C7H8 ) { return MQGetPercentage(rs_ro_ratio,ro,C7H8Curve); //TGS2602 } else if ( gas_id == GAS_H2S ) { return MQGetPercentage(rs_ro_ratio,ro,H2S_Curve); //TGS2602 } else if ( gas_id == GAS_NH3 ) { return MQGetPercentage(rs_ro_ratio,ro,NH3_Curve); //TGS2602 } else if ( gas_id == GAS_C2H5OH ) { return MQGetPercentage(rs_ro_ratio,ro,C2H5OH_quarCurve); //TGS2602 } } return 0; } float TGS26xx::MQReadRoRS(){ float ro = MQGetRo(); return MQRead(ro); } float TGS26xx::MQGetRo(){ if (_type == SEN_00){ return Ro3; }else if (_type == SEN_02){ return Ro6; }else return 0; } int TGS26xx::MQGetPercentage(float rs_ro_ratio, float ro, float *pcurve) { return (double)(pcurve[0] * pow(((double)rs_ro_ratio/ro), pcurve[1])); } float TGS26xx::MQCalibration(int mq_pin, double ppm, double rl_value, float *pcurve) { int i; float val=0; for (i=0;i<CALIBRATION_SAMPLE_TIMES;i++) { //take multiple samples val += MQResistanceCalculation(analogRead(mq_pin),rl_value); delay(CALIBRATION_SAMPLE_INTERVAL); } val = val/CALIBRATION_SAMPLE_TIMES; //calculate the average value //Ro = Rs * sqrt(a/ppm, b) = Rs * exp( ln(a/ppm) / b ) return (long)val*exp((log(pcurve[0]/ppm)/pcurve[1])); } float TGS26xx::MQResistanceCalculation(int raw_adc,float rl_value) { return (long)((long)(1024*1000*(long)rl_value)/raw_adc-(long)rl_value); } float TGS26xx::MQRead(float rl_value) { int i; float rs=0; for (i=0;i<READ_SAMPLE_TIMES;i++) { rs += MQResistanceCalculation(analogRead(_pin),rl_value); delay(READ_SAMPLE_INTERVAL); } rs = rs/READ_SAMPLE_TIMES; return rs; }
0c3d9346fcfd03c38856966c880043cb9bd3a1ab
d04b8c80334da2e0882db40480e7f7e418306abd
/image_encode.cpp
f784070fbd3bc5253ea94dce4f444e510b1d194d
[]
no_license
ankitvi/stego-crypto
9733525a2714f5bb64b326c659222e4c48c2e448
18147f9a40d6db57b81118f5b5137a3d44144c37
refs/heads/master
2020-12-11T07:47:58.113208
2015-12-13T10:50:28
2015-12-13T10:50:28
47,881,592
0
0
null
2015-12-12T14:39:54
2015-12-12T14:39:54
null
UTF-8
C++
false
false
2,627
cpp
image_encode.cpp
#include "stegosecure.h" int im_encoder(char *ip,char *hidedata,char *stegokey) { IplImage *input,*hide,*output; uchar *outdata,*indata,*hdata; //input of images - cover and secret images input=cvLoadImage(ip,-1); hide=cvLoadImage(hidedata,-1); int in_height,in_width,in_channels,dataPos=0,h_height,h_width,h_channels; in_height=input->height; in_width=input->width; in_channels=input->nChannels; h_height=hide->height; h_width=hide->width; h_channels=hide->nChannels; if( in_height*in_width*in_channels < h_height*h_width*h_channels + 40) { printf("secret image size too large."); exit(2); } indata=(uchar *)input->imageData; hdata=(uchar *)hide->imageData; //now we will make an empty image of same size as original output=cvCreateImage(cvSize(in_width,in_height),IPL_DEPTH_8U,3); outdata=(uchar *)output->imageData; //find the next prime to generate discrete logarithms long key=atol(stegokey); //long keypr=nextPrime(key); long keypr=key; int x=digSum(key); int a=2*x,h,p,bit_inp,bit_msg; //now we are storing height in the cover image first for( int i=0;i<20;i++) { h=(a*x)%key; p=h%7+1; bit_inp=getBit(indata[dataPos],p); bit_msg=getBit(h_height,i); if(bit_inp==bit_msg) { outdata[dataPos]=indata[dataPos] | 1; } else { outdata[dataPos]=indata[dataPos] & 254; } x=h; dataPos++; } //now we store the width in the cover image for( int i=0;i<20;i++) { h=(a*x)%key; p=h%7+1; bit_inp=getBit(indata[dataPos],p); bit_msg=getBit(h_width,i); if(bit_inp==bit_msg) { outdata[dataPos]=indata[dataPos] | 1; } else { outdata[dataPos]=indata[dataPos] & 254; } x=h; dataPos++; } //now that we have stored the dimensions of the image, we can store our secret image for( int i=0;i<h_height*h_width*h_channels;i++) { for( int j=0;j<8;j++) { h=(a*x)%key; p=h%7+1; bit_inp=getBit(indata[dataPos],p); bit_msg=getBit(hdata[i],j); if(bit_inp==bit_msg) { outdata[dataPos]=indata[dataPos] | 1; } else { outdata[dataPos]=indata[dataPos] & 254; } x=h; dataPos++; } } //now the remaining pixels are simply equal to input image for (int i=dataPos;i<in_height*in_width*in_channels;i++) { outdata[i]=indata[i]; } cvSaveImage("hidden_image.png",output,0); cvNamedWindow("stego image",CV_WINDOW_AUTOSIZE); cvShowImage("stego image",output); cvWaitKey(0); cvDestroyWindow("stego image"); cvReleaseImage(&output); cvReleaseImage(&input); return 0; }
ad5347b57920c74afffd25cc3a7adc1fc23dbaf6
a76a99161691abccc664e52ed1c855fac3768427
/PlayFabSDK/ExampleProject/Plugins/PlayFab/Source/PlayFab/Private/PlayFabMatchmakerModelDecoder.cpp
e44766102af4b3676c31bdacc2e43426bb383cff
[ "Apache-2.0" ]
permissive
PlayFabTim/UnrealBlueprintSDK
b52f1abcd642a8b80bc53a3b3e3d1588ace58fa3
dc45d7fdb0e56b641f6e2c2e46aebc5c17a1f2ba
refs/heads/master
2021-01-21T01:06:18.159938
2016-02-12T06:45:37
2016-02-12T06:45:37
50,624,164
0
1
null
2016-01-29T00:14:24
2016-01-29T00:14:24
null
UTF-8
C++
false
false
3,968
cpp
PlayFabMatchmakerModelDecoder.cpp
////////////////////////////////////////////////////////////////////////////////////////////// // Automatically generated cpp file for the play fab models // // API: Matchmaker // SDK Version: 0.0.160125 ////////////////////////////////////////////////////////////////////////////////////////////// #include "PlayFabPrivatePCH.h" #include "PlayFabMatchmakerModelDecoder.h" ////////////////////////////////////////////////////////////////////////// // Generated PlayFab Matchmaker API Functions ////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////// // Matchmaking APIs ////////////////////////////////////////////////////// FMatchmakerAuthUserResponse UPlayFabMatchmakerModelDecoder::decodeAuthUserResponseResponse(UPlayFabJsonObject* response) { // Temp ustruct FMatchmakerAuthUserResponse tempStruct; /** Boolean indicating if the user has been authorized to use the external match-making service. */ tempStruct.Authorized = response->GetObjectField("data")->GetBoolField("Authorized"); /** PlayFab unique identifier of the account that has been authorized. */ tempStruct.PlayFabId = response->GetObjectField("data")->GetStringField("PlayFabId"); return tempStruct; } FMatchmakerPlayerJoinedResponse UPlayFabMatchmakerModelDecoder::decodePlayerJoinedResponseResponse(UPlayFabJsonObject* response) { // Temp ustruct FMatchmakerPlayerJoinedResponse tempStruct; return tempStruct; } FMatchmakerPlayerLeftResponse UPlayFabMatchmakerModelDecoder::decodePlayerLeftResponseResponse(UPlayFabJsonObject* response) { // Temp ustruct FMatchmakerPlayerLeftResponse tempStruct; return tempStruct; } FMatchmakerStartGameResponse UPlayFabMatchmakerModelDecoder::decodeStartGameResponseResponse(UPlayFabJsonObject* response) { // Temp ustruct FMatchmakerStartGameResponse tempStruct; /** Unique identifier for the lobby in the new Game Server Instance. */ tempStruct.GameID = response->GetObjectField("data")->GetStringField("GameID"); /** IP address of the new Game Server Instance. */ tempStruct.ServerHostname = response->GetObjectField("data")->GetStringField("ServerHostname"); /** Port number for communication with the Game Server Instance. */ tempStruct.ServerPort = int(response->GetObjectField("data")->GetNumberField("ServerPort")); return tempStruct; } FMatchmakerUserInfoResponse UPlayFabMatchmakerModelDecoder::decodeUserInfoResponseResponse(UPlayFabJsonObject* response) { // Temp ustruct FMatchmakerUserInfoResponse tempStruct; /** PlayFab unique identifier of the user whose information was requested. */ tempStruct.PlayFabId = response->GetObjectField("data")->GetStringField("PlayFabId"); /** PlayFab unique user name. */ tempStruct.Username = response->GetObjectField("data")->GetStringField("Username"); /** Title specific display name, if set. */ tempStruct.TitleDisplayName = response->GetObjectField("data")->GetStringField("TitleDisplayName"); /** Array of inventory items in the user's current inventory. */ tempStruct.Inventory = response->GetObjectField("data")->GetObjectArrayField("Inventory"); /** Array of virtual currency balance(s) belonging to the user. */ tempStruct.VirtualCurrency = response->GetObjectField("data")->GetObjectField("VirtualCurrency"); /** Array of remaining times and timestamps for virtual currencies. */ tempStruct.VirtualCurrencyRechargeTimes = response->GetObjectField("data")->GetObjectField("VirtualCurrencyRechargeTimes"); /** Boolean indicating whether the user is a developer. */ tempStruct.IsDeveloper = response->GetObjectField("data")->GetBoolField("IsDeveloper"); /** Steam unique identifier, if the user has an associated Steam account. */ tempStruct.SteamId = response->GetObjectField("data")->GetStringField("SteamId"); return tempStruct; }
7a06cd5ac40543490d76c9480ffeba2467b30de1
e14ec17704daafa8bc7945613603a727f0c63aa9
/CSCPatterns/include/EmulationTreeCreator.h
ac75f063b4ad1e5e9529570ff3e0b3bf359eeebb
[]
no_license
sidhari/CSCUCLA
ec2bf5f866776bb87da388bd7e53d00f09bbf24e
cd82a7f5185efa1360e9ea664e6970a0dde9685e
refs/heads/master
2020-05-23T09:02:47.452758
2019-11-18T19:18:12
2019-11-18T19:18:12
186,700,179
0
0
null
2019-05-14T21:03:54
2019-05-14T21:03:54
null
UTF-8
C++
false
false
403
h
EmulationTreeCreator.h
/* * EmulationTreeCreator.h * * Created on: July 9, 2019 * Author: Siddharth Hariprakash */ #ifndef CSCPATTERNS_INCLUDE_EmulationTreeCreator_H_ #define CSCPATTERNS_INCLUDE_EmulationTreeCreator_H_ #include "../include/Processor.h" class EmulationTreeCreator : public Processor { int run(std::string inputfile, std::string outputfile, int start=0, int end=-1); }; #endif
4294535edf0a5b67ff13e07eaa3c96c0f198eb95
a5cdba8139aa6800601b9f7794050dcd39e81c39
/Gunfire/src/gun/Timer.cpp
6a0309565083b1d0813cd15df0217bc73d317f26
[]
no_license
dsc5085/Gunfire
d17c0119937a10c8971292a170bc467f7e5c56e1
f4f0c84153a154c2249547a690ac5269acabca50
refs/heads/master
2021-01-23T15:08:21.652624
2014-10-18T03:14:08
2014-10-18T03:14:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
674
cpp
Timer.cpp
#include "Timer.h" gun::Timer::Timer() : is_running_(true), max_time_(0), current_time_(0) { } gun::Timer::Timer(double max_time) : is_running_(true), max_time_(max_time), current_time_(max_time) { } gun::Timer::Timer(double max_time, double current_time) : is_running_(true), max_time_(max_time), current_time_(current_time) { } void gun::Timer::Start() { is_running_ = true; } void gun::Timer::Stop() { is_running_ = false; } bool gun::Timer::Check() { bool is_time = this->is_time(); if(is_time) { current_time_ = 0; } return is_time; } void gun::Timer::Update(double dt) { if(is_running_ && current_time_ < max_time_) { current_time_ += dt; } }
e8a5592c962130f19840385c594a9a4b2b4a0cca
a533446d05eb182521869a9bea731280e031c293
/shogi/shogilib/Notation/Sfen.h
77a281a77bef295a8d91e5c14f93e00b9bff9ba0
[]
no_license
ai5/shogi_repeat
be0eb6b03b3cedb0ca38c523f41a508a026a9b0b
09336dd33b0d37aea5b4912c465e6e3612d6aa9a
refs/heads/master
2021-01-18T21:24:48.085244
2016-05-23T09:39:40
2016-05-23T09:39:40
49,412,900
6
3
null
2018-04-22T23:40:00
2016-01-11T08:38:36
C++
UTF-8
C++
false
false
1,682
h
Sfen.h
#pragma once #ifndef SHOGI_SFEN_H_ #define SHOGI_SFEN_H_ #include <string> #include "types.h" #include "Move.h" class Notation; class Position; class Sfen { private: static const PieceType handPieceType[]; public: Sfen(); ~Sfen(); void Load(Notation& notation, const std::string& filename); void Save(Notation& notation, const std::string& filename); bool CanRead(const std::string& str); void LoadFromString(Notation& notation, const std::string& sfen); std::string SaveToString(const Notation& notation); static void LoadNotation(Notation& notation, const std::string& sfen); static void LoadPosition(Position& position, const std::string& sfen); static std::string PositionToString(const Position& position, int num); static std::string MovesToString(const Notation& notation); static std::string MoveToString(const Move& move); static bool IsSfen(std::string str); static Move ParseMove(const Position& position, const std::string& move); static PieceType ConvPieceTypeFromChar(char ch); private: static void ReadNotation(Notation& notation, const std::string& sfen); static void ReadPosition(Position& position, const std::string& sfen); static void WriteNotation(const Notation& notation, std::ostream& wr); static void WritePosition(const Position& pos, std::ostream& wr, int number); static void WriteMoves(const Notation& notation, std::ostream& wr); static void WriteMove(const Move& move, std::ostream& wr); static void WriteMoves(const Notation& notation, std::ostream& wr, int number); static char ConvCharFromPieceType(PieceType pieceType); static File FileFromChar(char ch); static Rank RankFromChar(char ch); }; #endif
5d5d3608a444089e240bb8878387c4854fb26434
d266eb7b6ba92c7658b563975c14b64d4e5d50cc
/libs/guicore/solverdef/solverdefinitiongridattributeintegeroptioncell.h
dcdc3783f4a349d1ed93df96112c16f267bcb76a
[]
no_license
scharlton2/prepost-gui
5c0a7d45c1f7156513d63e915d19f71233f15f88
007fdfcaf4d3e42b606e8edad8285b6de2bfd440
refs/heads/master
2023-08-31T01:54:11.798622
2022-12-26T01:51:06
2022-12-26T01:51:06
68,759,445
0
0
null
2020-05-14T22:28:47
2016-09-20T22:47:28
C++
UTF-8
C++
false
false
931
h
solverdefinitiongridattributeintegeroptioncell.h
#ifndef SOLVERDEFINITIONINTEGEROPTIONCELLGRIDATTRIBUTE_H #define SOLVERDEFINITIONINTEGEROPTIONCELLGRIDATTRIBUTE_H #include "solverdefinitiongridattributeintegercell.h" #include "integerenumloader.h" class SolverDefinitionGridAttributeIntegerOptionCell : public SolverDefinitionGridAttributeIntegerCell, public IntegerEnumLoader { public: SolverDefinitionGridAttributeIntegerOptionCell(const QDomElement& elem, SolverDefinition* solverDef, int order); GridAttributeStringConverter* stringConverter() const override; GridAttributeEditWidget* editWidget(QWidget* parent) override; GridAttributeVariationEditWidget* variationEditWidget(QWidget* parent) override; ScalarsToColorsEditWidget* createScalarsToColorsEditWidget(QWidget* parent) const override; ScalarsToColorsContainer* createScalarsToColorsContainer(ProjectDataItem* d) override; }; #endif // SOLVERDEFINITIONINTEGEROPTIONCELLGRIDATTRIBUTE_H
7e96108d1a84c0b14008383fa23448487caba300
c76e78581983830158b2a6f56b807e37132f4bba
/CSES/p1629.cpp
c38a9dbc562f89bd7739fadf57cb5f3a35f23e87
[]
no_license
itslinotlie/competitive-programming-solutions
7f72e27bbc53046174a95246598c3c9c2096b965
b639ebe3c060bb3c0b304080152cc9d958e52bfb
refs/heads/master
2021-07-17T17:48:42.639357
2021-05-29T03:07:47
2021-05-29T03:07:47
249,599,291
2
1
null
null
null
null
UTF-8
C++
false
false
815
cpp
p1629.cpp
// 03/15/2021 // https://cses.fi/problemset/task/1629 #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> pii; #define CLR(a) memset(a, 0, sizeof(a)) #define REP(i, n) for(int i=0;i<n;i++) #define FOR(i, n) for(int i=1;i<=n;i++) #define F first #define S second inline ll gcd(ll a, ll b) {return b==0? a:gcd(b, a%b);} inline ll lcm(ll a, ll b) {return a*b/gcd(a, b);} int n, val, ans; vector<pii> vec; int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> n; vec.resize(n); for(auto &x:vec) cin >> x.F >> x.S; sort(vec.begin(), vec.end(), [](pii a, pii b) -> bool { if(a.S==b.S) return a.F<b.F; return a.S<b.S; }); REP(i, n) { if(vec[i].F>=val) { val = vec[i].S; ans++; } } cout << ans << endl; }
46a957092905a5af5275c3341dee9fb1ec13396a
0d39f41dfa42bb9164309700d21ab7fed00264d1
/phoenix/vkw/With_Pipeline/WithDynamicStates.h
80ae0f7de925eca06a14e92dcaa39f5c52b887a6
[]
no_license
qnope/Phoenix
832dc271dcf445a9b78d75e50e402789e7aaaf75
f4259bc625f6b2150e1c823078c80e3be9fd79c6
refs/heads/master
2021-07-09T15:17:53.975985
2020-07-26T17:45:18
2020-07-26T17:50:55
166,474,743
0
0
null
2020-06-24T22:31:19
2019-01-18T21:28:18
C++
UTF-8
C++
false
false
2,101
h
WithDynamicStates.h
#pragma once #include "../vulkan.h" #include <ltl/Tuple.h> #include <ltl/ltl.h> #include <ltl/traits.h> namespace phx { namespace dynamic_state { struct DynamicState { protected: constexpr DynamicState() = default; }; struct DynamicViewport : DynamicState { static constexpr auto state = vk::DynamicState::eViewport; }; struct DynamicScissor : DynamicState { static constexpr auto state = vk::DynamicState::eScissor; }; constexpr DynamicScissor dynamic_scissor{}; constexpr DynamicViewport dynamic_viewport{}; } // namespace dynamic_state template <typename... DynamicStates> struct WithDynamicStates { static constexpr ltl::type_list_t<DynamicStates...> dynamic_state_types{}; static constexpr auto numberDynamicStates = dynamic_state_types.length; auto hasDynamicViewport() { using namespace ltl; return contains_type(dynamic_state_types, type_v<dynamic_state::DynamicViewport>); } auto hasDynamicScissor() { using namespace ltl; return contains_type(dynamic_state_types, type_v<dynamic_state::DynamicScissor>); } auto getDynamicStates() { return std::array{DynamicStates::state...}; } constexpr WithDynamicStates(DynamicStates...) { using namespace ltl; typed_static_assert_msg(numberDynamicStates > 0_n, "If you specify a WithDynamicStates, you must have " "at least one dynamic state"); typed_static_assert_msg(all_of_type(dynamic_state_types, is_derived_from(type_v<dynamic_state::DynamicState>)), "All dynamic states must be DynamicStates values"); typed_static_assert_msg(count_type(dynamic_state_types, type_v<dynamic_state::DynamicViewport>) <= 1_n && count_type(dynamic_state_types, type_v<dynamic_state::DynamicScissor>) <= 1_n, "You cannot specify several times the same dynamic state"); } }; LTL_MAKE_IS_KIND(WithDynamicStates, is_with_dynamic_states, IsWithDynamicStates, typename); } // namespace phx
940839fba6a5a9cb50ac87a5fdbc29674cdcd02c
c923e1055b70ee24b120a7e5e5aa44de3fd98306
/ms5611_log.cpp
8c5e1bcff5886f737378a69fefc65f7363dc3645
[]
no_license
jdfin/baro
10dbe1064418bb1dfd6f9f53fda3f7a577aeac47
06149fc089a3c2733bfd4fc667e456cd915d2b48
refs/heads/master
2021-01-11T02:24:31.065364
2016-10-15T04:35:43
2016-10-15T04:35:43
70,966,407
1
0
null
null
null
null
UTF-8
C++
false
false
3,660
cpp
ms5611_log.cpp
#include <cassert> #include <cmath> #include <cstring> #include <ctime> #include <chrono> #include <iomanip> #include <iostream> #include <thread> #include <unistd.h> #include "ms5611.h" using namespace std; const char *dev_name = "/dev/spidev0.0"; constexpr unsigned spi_clk = 20000000; constexpr unsigned log_interval_s = 1; static double pressure_to_altitude(double p, double t) { // http://keisan.casio.com/exec/system/1224585971 double p0 = 1013.25; // pressure at sea level return ((pow(p0 / p, 1 / 5.257) - 1) * (t + 273.15)) / 0.0065; } static void show_csv_hdr() { cout << "date, time, " << "adc_temp_dec, adc_temp_hex, adc_pres_dec, adc_pres_hex, " << "temp_c, pres_mbar, alt_m" << endl; } static void show_csv(const MS5611 &ms5611, chrono::system_clock::time_point now_time, uint32_t adc_temp, uint32_t adc_pres) { int32_t temp, pres; ms5611.get_pressure(adc_temp, adc_pres, temp, pres); double alt = pressure_to_altitude(pres / 100.0, temp / 100.0); time_t t = chrono::system_clock::to_time_t(now_time); struct tm t_tm; localtime_r(&t, &t_tm); char t_str[80]; memset(t_str, 0, sizeof(t_str)); strftime(t_str, 79, "%F, %T, ", &t_tm); cout.setf(ios::fixed, ios::floatfield); cout.precision(2); cout << t_str << dec << setw(0) << adc_temp << ", " << hex << setw(8) << setfill('0') << adc_temp << ", " << dec << setw(0) << adc_pres << ", " << hex << setw(8) << setfill('0') << adc_pres << ", " << temp / 100.0 << ", " << pres / 100.0 << ", " << alt << endl; } static void usage(const char *prog_name) { printf("usage: %s [-d] [-i N]\n", prog_name); printf(" -d dump calibration parameters (no)\n"); printf(" -i N log interval, seconds (1)\n"); exit(1); } int main(int argc, char *argv[]) { bool dump_cal = false; unsigned long interval_s = 1; int c; while ((c = getopt(argc, argv, "di:?")) != -1) { switch (c) { case 'd': dump_cal = true; break; case 'i': interval_s = strtoul(optarg, NULL, 0); if (interval_s == 0) usage(argv[0]); break; default: usage(argv[0]); break; } } auto next_time = chrono::system_clock::now(); auto interval = chrono::seconds(interval_s); tzset(); MS5611 ms5611(dev_name, spi_clk); if (dump_cal) ms5611.dump_prom(); show_csv_hdr(); while (true) { next_time += interval; this_thread::sleep_until(next_time); auto sleep_interval = chrono::milliseconds(10); // temperature if (ms5611.start_convert_temp()) { this_thread::sleep_for(sleep_interval); uint32_t adc_temp; if (ms5611.read_adc(adc_temp)) { // pressure if (ms5611.start_convert_pres()) { this_thread::sleep_for(sleep_interval); uint32_t adc_pres; if (ms5611.read_adc(adc_pres)) { show_csv(ms5611, next_time, adc_temp, adc_pres); } else { cerr << "read adc error (pressure)" << endl; } } else { cerr << "start convert error (pressure)" << endl; } } else { cerr << "read adc error (temperature)" << endl; } } else { cerr << "start convert error (temperature)" << endl; } } return 0; }
b09227b02e4dca7662d76daaab0def1d5d1dbb24
ec8f4cf382d7033dd8ba0042a28a5559997920f5
/interviewCode/src/others/sqrtx/sqrtx.cpp
5c546a26801f86a32ca82a55cadbf712022809ab
[]
no_license
jiguosong/coding_practice
7d5b008fbf0cb4181497020fef97e68669f969b0
4313bd943c7755ed8127626cad194d7a60d05a14
refs/heads/master
2020-12-14T06:09:52.598169
2016-12-31T21:40:26
2016-12-31T21:40:26
68,734,717
0
1
null
null
null
null
UTF-8
C++
false
false
317
cpp
sqrtx.cpp
#include "sqrtx.h" void sqrtx::dummy() { } unsigned int sqrtx::sqrt(unsigned int x) { int left = 0; int right = x; while(left < right) { int mid = left + (right-left)/2; long long sqrt = mid*mid; if(sqrt == x) return mid; else if (sqrt < x) left = mid + 1; else right = mid-1; } return right; }
4211ca13bf65becd7c7cdef6f8a12cde9368a07c
2825baf383c78b235d7786aec58289415dc17053
/src/Monster.cpp
08498712bfc8e4c4cc9fcb58ed04ee2b26e3d126
[]
no_license
johnlihello/CardGame
1ef2910da5d3bc763449819b0b822921342deb63
3596a32e9b941942e9e73a01c378fb03063fa36b
refs/heads/main
2023-06-06T10:41:13.588069
2021-06-23T05:16:44
2021-06-23T05:16:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,029
cpp
Monster.cpp
#include "Monster.h" #include "Player.h" void Monster::attack(Player* victim){ vector<Monster*> &monsterList = victim->getMonsterList(); if(monsterList.size() != 0){ vector<Monster*>::iterator it = monsterList.begin(); bool isDead; isDead = decreaseMonsterBlood((*it),attackValue); //delete this monster deleteDeadMonster() } else{ cout << "ATTACK PLAYER!" << endl; decreasePlayerBlood(victim, attackValue); } } void Monster::decreasePlayerBlood(Player* victim, unsigned int attackValue){ cout << "Player blood: "<< victim->getBlood() << " -> " << (int)(victim->getBlood()-attackValue) <<endl; victim->setBlood(victim->getBlood() - attackValue); } bool Monster::decreaseMonsterBlood(Monster* monster, unsigned int attackValue) { monster->blood -= attackValue; cout << "ATTACK MONSTER! Name is:" << monster->name << ", blood:" << (int)(monster->blood+attackValue) << " -> " << monster->blood << endl; return monster->blood <= 0; }
974865bfd5c95e2967e6a10dacc4080eb715bd8a
a6a2239f454639d7a79bacf8a961abfa3fc94528
/lib.h
12186e992e6ca138cabf767c36ddb87db52942b8
[]
no_license
AngieHoo/peerster
2d243adaedf3bbc57dad679ea896afa955d26705
3a4ee355eab039591539dbf0c905385c7038030c
refs/heads/master
2021-07-25T21:34:14.005153
2017-10-06T21:20:42
2017-10-06T21:20:42
105,475,268
0
0
null
null
null
null
UTF-8
C++
false
false
444
h
lib.h
#ifndef LIB_H #define LIB_H namespace peerster{ const QString DEST = "Dest"; const QString ORIGIN = "Origin"; const QString CHAT_TEXT= "ChatText"; const QString HOP_LIMIT = "HopLimit"; const QString SEQ_NO = "SeqNo"; const QString WANT = "Want"; const QString LAST_IP = "LastIP"; const QString LAST_PORT = "LastPort"; const int FLIP_COIN = 5; enum messageType { CHAT_MESSAGE, ROUT_MESSAGE, STATUS_MESSAGE }; } #endif // LIB_H