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
459c0370004f250fb46b73267af05e54d7e82d39
52896a1d66e157f966105bee46cf8a7e48c26df2
/src/player.cpp
bb93c9c3b92382482d579ea600408d66f2bed505
[]
no_license
AntonHakansson/c_physics
9b86027263a1d3c2900806069308e7ecc5ca4c5b
fc8a71f7ba04287c9f69010af633ecfc1a995602
refs/heads/main
2023-08-19T10:08:41.625908
2021-09-23T16:34:48
2021-09-23T16:40:52
349,856,320
2
0
null
null
null
null
UTF-8
C++
false
false
1,589
cpp
player.cpp
#include "player.h" #include <raylib.h> #include <raymath.h> #include "language_layer.h" #include "physics.h" Player PlayerInit(physics::World *world) { Player p = {0}; p.acc = 25.0f; p.jump_acc = 300.0f; p.speed_max = 5.0f; p.body = physics::AddBody(world, {1.0f, 4.0f}, {1.0f, 1.5f}, 50.0f); p.body->friction = 1.0f; p.body->lock_rotation = true; return p; } void PlayerUpdate(Player *p) { if (p->body->is_grounded) { p->body->friction = 1.0f; p->last_grounded_timestamp_s = GetTime(); } else { p->body->friction = 0.0f; } if (IsKeyPressed(KEY_SPACE)) { f64 time_elapsed_since_grounded_s = GetTime() - p->last_grounded_timestamp_s; if (time_elapsed_since_grounded_s <= 0.2) { p->body->force.y = p->jump_acc * p->body->mass; } } if (IsKeyDown(KEY_D)) { if (p->body->velocity.x <= p->speed_max) { p->body->force.x = p->acc * p->body->mass; } } if (IsKeyDown(KEY_A)) { if (p->body->velocity.x >= -p->speed_max) { p->body->force.x = -p->acc * p->body->mass; } } } void PlayerDraw(Player *p) { v2 h = p->body->width * 0.5f; PushRect(&game->renderer, p->body->position, p->body->width, DARKBLUE); f32 facing_direction = Sign(p->body->velocity.x); f32 eye_radius = 0.2f; v2 eye = p->body->position; eye.y += h.y * 0.70; eye.x += h.x * 0.55 * facing_direction; PushCircle(&game->renderer, eye, eye_radius, WHITE); v2 pupil = eye; pupil.x += facing_direction * 0.1; pupil.y += -p->body->velocity.y*0.01; PushCircle(&game->renderer, pupil, eye_radius*0.35, BLACK); }
80ff9a1ba988221d4daf5b587f737a9e1c2d2bee
6c40203055fe652f238fb5f3befaa0d04a788d65
/src/armnn/backends/ClWorkloads/ClBatchNormalizationFloat32Workload.cpp
dabd495d59ea6054def9b07a3785bd3c1b0002ba
[ "MIT" ]
permissive
Air000/armnn_s32v
9243f2e8d63b9691b9c7873a54b29ac5a79d2b14
ec3ee60825d6b7642a70987c4911944cef7a3ee6
refs/heads/master
2020-03-27T15:32:37.975405
2018-09-01T14:11:34
2018-09-01T14:11:34
146,724,624
1
1
null
null
null
null
UTF-8
C++
false
false
1,824
cpp
ClBatchNormalizationFloat32Workload.cpp
// // Copyright © 2017 Arm Ltd. All rights reserved. // See LICENSE file in the project root for full license information. // #include "ClBatchNormalizationFloat32Workload.hpp" #include "backends/ClTensorHandle.hpp" #include "backends/CpuTensorHandle.hpp" #include "backends/ArmComputeTensorUtils.hpp" namespace armnn { using namespace armcomputetensorutils; ClBatchNormalizationFloat32Workload::ClBatchNormalizationFloat32Workload( const BatchNormalizationQueueDescriptor& descriptor, const WorkloadInfo& info) : Float32Workload<BatchNormalizationQueueDescriptor>(descriptor, info) { BuildArmComputeTensor(m_Mean, m_Data.m_Mean->GetTensorInfo()); BuildArmComputeTensor(m_Variance, m_Data.m_Variance->GetTensorInfo()); BuildArmComputeTensor(m_Gamma, m_Data.m_Gamma->GetTensorInfo()); BuildArmComputeTensor(m_Beta, m_Data.m_Beta->GetTensorInfo()); m_Data.ValidateInputsOutputs("ClBatchNormalizationFloat32Workload", 1, 1); arm_compute::ICLTensor& input = static_cast<IClTensorHandle*>(m_Data.m_Inputs[0])->GetTensor(); arm_compute::ICLTensor& output = static_cast<IClTensorHandle*>(m_Data.m_Outputs[0])->GetTensor(); m_Layer.configure(&input, &output, &m_Mean, &m_Variance, &m_Beta, &m_Gamma, m_Data.m_Parameters.m_Eps); InitialiseArmComputeClTensorData(m_Mean, m_Data.m_Mean->GetConstTensor<float>()); InitialiseArmComputeClTensorData(m_Variance, m_Data.m_Variance->GetConstTensor<float>()); InitialiseArmComputeClTensorData(m_Beta, m_Data.m_Beta->GetConstTensor<float>()); InitialiseArmComputeClTensorData(m_Gamma, m_Data.m_Gamma->GetConstTensor<float>()); } void ClBatchNormalizationFloat32Workload::Execute() const { ARMNN_SCOPED_PROFILING_EVENT(Compute::GpuAcc, "ClBatchNormalizationFloat32Workload_Execute"); m_Layer.run(); } } //namespace armnn
acdec389cd1977fbecdd5adaa3331f6d25b44d9e
2c91e03a32caececdbfa2e2fcd821049bb66f97f
/main.cc
7bfacfe9c2911e29ff0c035bc087c068a8dea5f6
[]
no_license
Philosoph228/sdl200521
91bb7163503d98914c0ee07dc94679835300213e
f794e7665527e0ad2a65a333f3f66655ab3a6bee
refs/heads/master
2022-07-21T09:28:34.075465
2020-05-22T05:33:07
2020-05-22T05:33:07
266,026,978
0
0
null
null
null
null
UTF-8
C++
false
false
3,034
cc
main.cc
/* * File: main.cc * Description: This is a main entry point for application * * sdl200521 * Copyright 2020 (c) Philosoph228 <philosoph228@gmail.com> * */ #define SDL_MAIN_HANDLED #include <SDL2/SDL.h> int main(int argc, char* argv[]) { // Init SDL SDL_Init(SDL_INIT_VIDEO); SDL_Window* window = SDL_CreateWindow("sdl200521", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN); SDL_Surface* screenSurface = SDL_GetWindowSurface(window); // Init rect SDL_Rect rect(0, 0, 4, 4); float x_speed = 0; float y_speed = 0; float pos_x = 0; float pos_y = 0; // Main loop reusable objects SDL_Event event{}; bool bRunning = true; uint32_t then = SDL_GetTicks(); // Main loop itself while (bRunning) { // Uncomment to simulate CPU lags: // SDL_Delay(10); SDL_PollEvent(&event); uint32_t now = SDL_GetTicks(); float delta = now - then; then = now; if (event.type == SDL_QUIT) { bRunning = false; } else if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_LEFT) { x_speed = -1.f; } else if (event.key.keysym.sym == SDLK_RIGHT) { x_speed = 1.f; } else if (event.key.keysym.sym == SDLK_UP) { y_speed = -1.f; } else if (event.key.keysym.sym == SDLK_DOWN) { y_speed = 1.f; } } else if (event.type == SDL_KEYUP) { if (event.key.keysym.sym == SDLK_LEFT || event.key.keysym.sym == SDLK_RIGHT) { // Set horizontal movement speed to 0 if key has been unpressed x_speed = 0.f; } else if (event.key.keysym.sym == SDLK_UP || event.key.keysym.sym == SDLK_DOWN) { y_speed = 0.f; } } /* // Switch statement approach switch (event.type) { case SDL_QUIT: bRunning = false; break; case SDL_KEYDOWN: { switch (event.key.keysym.sym) { case SDLK_LEFT: x_speed = -1.f; break; case SDLK_RIGHT: x_speed = 1.f; break; case SDLK_UP: y_speed = -1.f; break; case SDLK_DOWN: y_speed = 1.f; break; } } break; case SDL_KEYUP: switch (event.key.keysym.sym) { case SDLK_LEFT: case SDLK_DOWN: x_speed = 0.f; break; case SDLK_UP: case SDLK_RIGHT: y_speed = 0.f; break; } break; } */ // As your time-based delta is a REAL number, to avoid precision stripping // you need to store your coordinates as real number too pos_x += delta * x_speed; pos_y += delta * y_speed; // Then apply real value coordinates to natural one rect.x = pos_x; rect.y = pos_y; SDL_FillRect(screenSurface, &rect, SDL_MapRGB(screenSurface->format, 0xFF, 0x00, 0x00)); SDL_UpdateWindowSurface(window); } SDL_Quit(); return 0; }
37175d013f661ed6d7b748a6c8e5129737b068af
0d1c82ab85d11f7476e6c539baaa50143ebd3084
/SII-2020/SII-2020/Error.h
63edcd8b2a045f227d58e334b990fc1fd0e543d9
[]
no_license
Selevn/SII-2020
4f7a047a83afee4463d84a8220d661306b3d562b
e7a5df5d3131117ce0d8a05fba16e6a383205165
refs/heads/master
2023-02-07T21:08:43.665487
2020-12-14T18:17:45
2020-12-14T18:17:45
314,994,906
0
0
null
null
null
null
UTF-8
C++
false
false
1,264
h
Error.h
#pragma once #define ERROR_THROW(id) Error::geterror(id); #define ERROR_THROW_IN(id, l, c) Error::geterrorin(id, l, c); //id строка колонка #define ERROR_ENTRY(id, m) {id, m,{-1, -1}} //элемент таблицы ошибок #define ERROR_MAXSIZE_MESSAGE 200 #define ERROR_ENTRY_NODEF(id) ERROR_ENTRY(-id,"Неопределенная ошибка") //1 неопределенный элемент таблицы ошибок #define ERROR_ENTRY_NODEF10(id) ERROR_ENTRY_NODEF(id+0),ERROR_ENTRY_NODEF(id+1),ERROR_ENTRY_NODEF(id+2),ERROR_ENTRY_NODEF(id+3),ERROR_ENTRY_NODEF(id+4),ERROR_ENTRY_NODEF(id+5),ERROR_ENTRY_NODEF(id+6),ERROR_ENTRY_NODEF(id+7),ERROR_ENTRY_NODEF(id+8),ERROR_ENTRY_NODEF(id+9) #define ERROR_ENTRY_NODEF100(id) ERROR_ENTRY_NODEF10(id+0),ERROR_ENTRY_NODEF10(id+10),ERROR_ENTRY_NODEF10(id+20),ERROR_ENTRY_NODEF10(id+30),ERROR_ENTRY_NODEF10(id+40),ERROR_ENTRY_NODEF10(id+50),ERROR_ENTRY_NODEF10(id+60),ERROR_ENTRY_NODEF10(id+70),ERROR_ENTRY_NODEF10(id+80),ERROR_ENTRY_NODEF10(id+90) #define ERROR_MAX_ENTRY 1000 namespace Error { struct ERROR { int id; char message[ERROR_MAXSIZE_MESSAGE]; struct IN { short line; short col; } inext; }; ERROR geterror(int id); ERROR geterrorin(int id,int line,int col); }
d6e4eca781d193131dae02ece68b65bd5a1f2e38
cce3bf9356f1a2a0b4e6c61353a098ab63bd9802
/BasicLibrary/ProtocolConnector.h
7ed573b40525a9d91bfd5f25a2f8ddd5c684378d
[]
no_license
k06a/RitM
ff98a1282c582fce53fa1f4e1a01615f7c95c90c
31bb0b8a91ada54d4832a083daf295d2c01d2449
refs/heads/master
2020-03-12T00:25:39.644330
2018-04-20T11:45:07
2018-04-20T11:45:07
130,348,755
1
0
null
null
null
null
UTF-8
C++
false
false
1,000
h
ProtocolConnector.h
#ifndef PROTOCOLCONNECTOR_H #define PROTOCOLCONNECTOR_H #include <map> #include <deque> #include "CommonInclude.h" #include "AbstractConnector.h" namespace RitM { class ProtocolConnector : public AbstractConnector { typedef std::multimap<Protocol,ProcessorPtr> MyMap; MyMap procMap; public: ProtocolConnector(); ProtocolConnector(const MyDeque & d); virtual ProcessorPtr CreateCopy() const; virtual void ping(ProcessorPtr prevProcessor); virtual ProcessingStatus forwardProcess(Protocol proto, PacketPtr packet, unsigned offset); virtual void addNextProcessor(ProcessorPtr processor); virtual void removeNextProcessor(ProcessorPtr processor); virtual const std::deque<ProcessorPtr> & nextProcessors(); }; // class ProtocolConnector typedef SharedPointer<ProtocolConnector>::Type ProtocolConnectorPtr; } // namespace RitM #endif // PROTOCOLCONNECTOR_H
c4347c5e31cfcde7aecea6bc937675e83459ab4f
da9d2fb0cfe3d92b45d52615e8d95d8192ca67ad
/string tokensation using strtok functn.cpp
e13ff5416445bf3b8e0e3777decac5445ff8300a
[]
no_license
Hack-sham/CODING-BLOCKS-COMPETITIVE-CODING-COURSE
dde7fc17586efbb381ba7aef862b96a9bb3fce16
1703495f71c545371d1326b8b9e13edb0fb01b36
refs/heads/main
2023-06-04T23:10:36.426639
2021-06-22T10:04:47
2021-06-22T10:04:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
672
cpp
string tokensation using strtok functn.cpp
//string tokanisation using strtok function #include<iostream> #include<bits/stdc++.h> #include<algorithm> #include<cstring> using namespace std; int main() { // strtok -> inbuild function // function declaration -> char *strtok(char *S,char * delimeter) // this function returns a token on every function call // on first call function should be passed with string 's' // on subsequent calls we should pass the string argument as null char s[10000]=" today , is a rainy , day , indeed."; char *ptr = strtok(s,","); cout<<ptr<<"\n"; while(ptr!=NULL) { char *ptr = strtok(NULL,","); cout<<ptr<<"\n"; } return 0; }
76682f8eccfe095a7e154c65bf073d1691bd8fbc
814f8db05beb9253f5f06b5fee8961e57c08006a
/Classes/Context/point_3d.cpp
e45fbc69b793dcbddb0c21b41eb718f270f8b579
[]
no_license
Fviramontes8/UNMECE231Code
2fec990299eed355d858e2b35b671afe02ebfa05
f7b6644fa089c84ca6c6611c505a4c4791f1ebf5
refs/heads/main
2023-02-19T19:23:40.455661
2021-01-25T05:15:21
2021-01-25T05:15:21
331,788,397
1
1
null
null
null
null
UTF-8
C++
false
false
578
cpp
point_3d.cpp
#include <iostream> struct _point_3d { double x; double y; double z; void (*init) (struct _point_3d *, double, double, double); void (*print) (struct _point_3d *); }; typedef struct _point_3d Point3D; void set_point(Point3D *p, double p_x, double p_y, double p_z) { p->x = p_x; p->y = p_y; p->z = p_z; } void print_point(Point3D *p) { std::cout << "x: " << p->x << " y: " << p->y << " z: " << p->z << '\n'; } int main() { Point3D p; p.init = set_point; p.print = print_point; p.init(&p, 3, 7, 12); p.print(&p); p.init(3, 7, 12); p.print(); return 0; }
10086820930da7488a7f40290bf702232734ba9e
7d3ce1906ae6d8cf82cbafbfbef8e68467d196ef
/test/test_Matrix.cpp
d33c114d389c85cde97f9620bc9bb7cbb7e030ab
[]
no_license
kienvuong/cpp-schoolopdr
57e5d075013a9a3ffec3935eb18015c4f0470f97
2d31477b61445d7751db749149227f2dff0c144c
refs/heads/master
2022-04-20T16:49:51.017681
2020-04-22T14:10:38
2020-04-22T14:10:38
242,740,464
0
0
null
null
null
null
UTF-8
C++
false
false
2,982
cpp
test_Matrix.cpp
#include <Catch2/catch.hpp> #include "Matrix.hpp" #include "RowVector.hpp" TEST_CASE("Matrix can be added/subtracted with another") { Matrix matrixA( RowVector(1, 2, 3), RowVector(4, 5, 6), RowVector(7, 8, 9) ); Matrix matrixB( RowVector(-1, 2, 3), RowVector(-4, 5, 6), RowVector(-7, 8, 9) ); SECTION("Addition using +") { Matrix actual = matrixA + matrixB; Matrix expected( RowVector(0, 4, 6), RowVector(0, 10, 12), RowVector(0, 16, 18) ); REQUIRE(actual == expected); } SECTION("Subtraction using -") { Matrix actual = matrixA - matrixB; Matrix expected( RowVector(2, 0, 0), RowVector(8, 0, 0), RowVector(14, 0, 0) ); REQUIRE(actual == expected); } } TEST_CASE("Matrix can be multiplied with another") { SECTION("2x2 * 2x3") { Matrix matrixA( RowVector(1, 2), RowVector(4, 3) ); Matrix matrixB( RowVector(1, 2, 3), RowVector(3, -4, 7) ); /** * B = | 1 2 3 | * | 3 -4 7 | * * | 1 2 | 7 -6 17 * A = | 4 3 | 13 -4 33 * */ Matrix actual = matrixA * matrixB; Matrix expected( RowVector(7, -6, 17), RowVector(13, -4, 33) ); REQUIRE(actual == expected); } SECTION("2x3 * 3x2") { Matrix matrixA( RowVector(1, 2, 3), RowVector(3, -4, 7) ); Matrix matrixB( RowVector(1, 2), RowVector(4, 3), RowVector(0, 5) ); /** * | 1 2 | * B = | 4 3 | * | 0 5 | * * A = | 1 2 3 | 9 23 * | 3 -4 7 | -13 29 * */ Matrix actual = matrixA * matrixB; Matrix expected( RowVector(9, 23), RowVector(-13, 29) ); REQUIRE(actual == expected); } } TEST_CASE("Matrix can be multiplied with scalar") { Matrix matrixA( RowVector(1, 2, 3), RowVector(4, 5, 6), RowVector(7, 8, 9) ); SECTION("Multiplication using *") { Matrix actual = matrixA * 2; Matrix expected( RowVector(2, 4, 6), RowVector(8, 10, 12), RowVector(14, 16, 18) ); REQUIRE(actual == expected); } } TEST_CASE("Matrix can be transposed") { Matrix matrixA( RowVector(1, 2, 3), RowVector(4, 5, 6), RowVector(7, 8, 9) ); Matrix expected( RowVector(1, 4, 7), RowVector(2, 5, 8), RowVector(3, 6, 9) ); Matrix actual = matrixA.transpose(); REQUIRE(actual == expected); }
871c6be8032f97c361d29dbd10e836bf359b6a6d
a14f3e72909cd389da6f485bf8f266de3be39f0d
/interface/omni/core/model/type.hpp
d062b0d0ebc2b00879c81036dad6bb6ab02d9b89
[ "MIT" ]
permissive
daniel-kun/omni
6334c493536a638944e2acda3e9dd75adeddb6c0
ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18
refs/heads/master
2021-05-16T02:18:05.886357
2017-12-07T19:11:55
2017-12-07T19:11:55
10,886,593
33
2
null
2016-03-05T13:04:25
2013-06-23T15:09:26
C++
UTF-8
C++
false
false
2,534
hpp
type.hpp
#ifndef OMNI_CORE_TYPE_HPP #define OMNI_CORE_TYPE_HPP #include <omni/core/core.hpp> #include <omni/core/model/entity.hpp> #include <omni/core/model/type_class.hpp> #ifndef Q_MOC_RUN #include <boost/noncopyable.hpp> #endif namespace llvm { class Type; } namespace omni { namespace core { namespace model { /** @class type type.hpp omni/core/model/type.hpp @brief A type defines the properties of types that can be used for variables, function-parameters, function-return-values, etc. <b>Important:</b> Always use type::sharedBasicType or context::sharedBasicType to get a type-object for any builtin-types. The type_class differentiates between a few basic built-in types and user-defined types (classes). (Currently, classes are not yet implemented for omni. Once they will be implemented, a new class class_type will be derived from type that implements various functionality and properties that classes offer.) A type is always strictly coupled with a context and, in contrast to most entities, can not exist without a context. Builtin-types are not defined in any module, hence getModule () always returns nullptr. Likely, builtin-classes do not have parents, hence getParent () always returns nullptr, too. **/ class OMNI_CORE_API type : public entity, public boost::noncopyable { public: type (context & context, type_class typeClass, unsigned int indirectionLevel = 0); virtual ~ type (); static meta_info & getStaticMetaInfo (); meta_info & getMetaInfo () const override; std::string toString (bool fullyQualified = true); static std::string toString (type_class typeClass, bool fullyQualified = true); context * getContext () override; const context * getContext () const override; domain getDomain () const override; module * getModule () override; const module * getModule () const override; void setComponent (domain domain, std::string name, std::shared_ptr <entity> entity) override; type_class getTypeClass () const; unsigned int getIndirectionLevel () const; static std::shared_ptr <type> sharedBasicType(context & context, type_class typeClass, unsigned int indirectionLevel = 0); llvm::Type * llvmType (); private: context & _context; type_class _typeClass; unsigned int _indirectionLevel; }; } // namespace model } // namespace core } // namespace omni #endif // include guard
1f5decb3e643a04e90ddf22b423c85f045903c63
2285679c052989a92ecfe8d895535e0e67bd1722
/GraphicsProject/GraphicsProject/Mesh.h
ac08058a1a1e8ba5e4e8cfa917845dd19b6a143d
[]
no_license
aaronderstine/Graphics
7e4202ca4bc12e1c3566f966367dfcd71a1c0e0e
8a7b5224e45c3aba4b207e315b31401c0d5e47f6
refs/heads/master
2021-01-23T07:26:52.661743
2014-04-29T19:12:46
2014-04-29T19:12:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
899
h
Mesh.h
/****************************************************/ /* Author: Aaron Derstine */ /* Course: COMP 361, Computer Graphics */ /* Date: March 29, 2014 */ /* Name: Mesh.h */ /* Description: This file defines the a basic mesh. */ /* It inherits from geometry so it can be */ /* used in a scene graph. It is only built */ /* using the MeshBuilder class and is */ /* created from a config file. */ /****************************************************/ #pragma once #include "Geometry.h" #include <QtCore\QString> class Mesh : public Geometry { public: Mesh(); ~Mesh(); // draw method virtual void draw(glm::mat4 model); void setSourceFile(QString filename); QString getSourceFilename(); private: QString sourceFile; };
40b33e9be8735510bc1fd18961d9a94bde6b6ce4
200c11e3c0669a25dd1dfc1b121bd0dc118abc61
/任务管理器/MFCApplication2/myduimodo.h
252ff44ae05f891b09d86be906912770d8ed158c
[]
no_license
haidragon/taskmanager
ef1c2e6502c18c06900cd543785299798c4c1a6c
abd8d04b64a92a1e867e94a2451caff557c3878d
refs/heads/master
2021-04-12T09:35:46.500894
2018-10-21T13:27:01
2018-10-21T13:27:01
126,572,019
0
3
null
null
null
null
GB18030
C++
false
false
529
h
myduimodo.h
#pragma once #include "afxcmn.h" // myduimodo 对话框 class myduimodo : public CDialogEx { DECLARE_DYNAMIC(myduimodo) public: myduimodo(CWnd* pParent = NULL); // 标准构造函数 virtual ~myduimodo(); DWORD pid; bool Enumheap(DWORD PID); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_DIALOG3 }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() afx_msg void OnPaint(); public: CListCtrl myduictrl; };
37b6a073cdad6fe1e9459536960cec1b52a8c9cb
d902097ef3e8a61949141617ca4d4f81e1844f0c
/PAT甲级题解/1102.cpp
9d9c21f0d187a74d21df934b250c23c575b34b8c
[]
no_license
ddNTP/My-Code
1acfd60f03bc2b0d3444891eb2d321d0078dd273
65ffe5439c0ce7607b4108860df3f18916dc570e
refs/heads/master
2022-09-04T07:40:47.458205
2022-08-08T07:21:35
2022-08-08T07:21:35
244,831,100
0
0
null
null
null
null
UTF-8
C++
false
false
1,376
cpp
1102.cpp
#include<iostream> #include<string> #include<queue> using namespace std; string s[10]; bool have[10]; int lev[100]; int in[100]; struct node { int data; node *lc, *rc; }; node *create(int root) { node *r = new node; r->data = root; if (s[root][0] != '-') r->rc = create(s[root][0] - '0'); else r ->rc = NULL; if (s[root][2] != '-') r ->lc = create(s[root][2] - '0'); else r->lc = NULL; return r; } int cnt = 0; void levelorder(node *root) { queue<node*>q; q.push(root); while (!q.empty()) { node*t = q.front(); q.pop(); lev[cnt++] = t->data; if (t->lc != NULL)q.push(t->lc); if (t->rc != NULL)q.push(t->rc); } } int cnt1 = 0; void inorder(node*root) { if (root == NULL)return; inorder(root->lc); in[cnt1++] = root->data; inorder(root->rc); } int main() { int n; cin >> n; getchar(); for (int i = 0; i < n; i++) { getline(cin, s[i]); if (s[i][0] != '-') have[s[i][0] - '0'] = true; if (s[i][2] != '-') have[s[i][2] - '0'] = true; } int root; for (root = 0; root < n; root++) if (!have[root])break; node *r = create(root); levelorder(r); inorder(r); printf("%d", lev[0]); for (int i = 1; i < cnt; i++) printf(" %d", lev[i]); cout << endl; printf("%d", in[0]); for (int i = 1; i < cnt1; i++) printf(" %d", in[i]); system("pause"); return 0; }
ac6c8d245651cddd212dbfbcda5ec58ae248ceee
89b10aa13567d49a2e106a07d328fd24e5860f4d
/BTVN_21_05_16/b3.cpp
d0c28402b9aad59bb8c76e7bc6b3c1ec7d990155
[]
no_license
winvp1999/BTVN_Genetic
036f59932e00106b610d70e0ce914043ae7f61f6
85c3b9d1a41a9cdeaf4e946c3c8c527977be0538
refs/heads/main
2023-07-30T19:46:49.433149
2021-09-21T03:39:49
2021-09-21T03:39:49
369,939,308
0
0
null
null
null
null
UTF-8
C++
false
false
470
cpp
b3.cpp
//Bai 3. Viet chuong trinh in mot so nguyen, mot so thuc, // mot ky tu da duoc dinh nghia truoc #include <iostream> using namespace std; void b3() { //Input int SoNguyen = 69; float SoThuc = 99.69; char Character = '@'; //Output cout << "\nBien so nguyen\t: " << SoNguyen << "\nBien so thuc\t: " << SoThuc << "\nKy tu\t\t: " << Character; } int main() { system("cls"); fflush(stdin); b3(); return 1; }
0ecdeab2459a3b5c0328f10de97fc360a67adac1
d55efb53fa2b318b1edd9f7c0cc97d34c5c09d2c
/AtCoder/D - Anything Goes to Zero.cpp
a0c52f1f2fc391589cbc770bc167bd10aab55690
[]
no_license
obaydullahmhs/Programming-Contest
deea362d6140b817c905a2653b98ba05a41636e1
e52975c6b1373606655a174e7fff4a4316327aad
refs/heads/master
2022-09-14T17:20:22.698937
2022-09-03T18:02:06
2022-09-03T18:02:06
238,995,288
1
0
null
null
null
null
UTF-8
C++
false
false
4,212
cpp
D - Anything Goes to Zero.cpp
/**বিসমিল্লাহির রহমানির রহীম **/ #include<bits/stdc++.h> #define pi acos(-1.0) #define eps 1e-9 #define ff first #define ss second #define nl '\n' #define CLR(a) memset(a,0,sizeof(a)) #define SET(a) memset(a,-1,sizeof(a)) #define all(x) x.begin(),x.end() #define allr(x) x.rbegin(),x.rend() #define sz(x) (int)(x).size() #define Fast_Read ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); #define Precision(x) cout.setf(ios::fixed); cout.precision(x); using namespace std; int dx[]={0,0,1,-1,-1,-1,1,1}; int dy[]={1,-1,0,0,-1,1,1,-1}; typedef long long ll; template < class T> inline T bitOn(T n,T pos){return n |((T)1<<pos);} template < class T> inline T bitOff(T n,T pos){return n & ~((T)1<<pos);} template < class T> inline T isOn(T n,T pos){return (bool)(n & ((T)1<<pos));} template < class T> inline T lcm(T a, T b){return (a/__gcd(a, b)) * b;} template<class T> istream& operator>>(istream& is, vector<T>& input){ for(T& in:input) is >> in; return is; } template<class T> ostream& operator<<(ostream& os, const vector<T> &input){ bool isFirst=true;for(const T& out:input){if(isFirst){os<<out;isFirst=false;}else os<<" "<<out;}return os; } ///******************************************START****************************************** class FrontHash{ /// For Front Hash private: long long base, M, len; vector<long long> hashing, P; /// P for base power table public: void init(const string& s, const long long& _base, const long long _M){ /// 0 based this->base = _base; this->M = _M; this->len = s.size(); this->P.assign(len + 5, 0); this->hashing.assign(len + 5, 0); long long calculateHash = 0; P[0] = 1; for(int i = 1; i <=len; i++) P[i] = (P[i - 1] * this->base) % this->M; /// Power of base for(int i = 0; i < len; i++){ ///front hashing array of string s calculateHash = (calculateHash * this->base) + s[i] - '0'; calculateHash %= this->M; this->hashing[i] = calculateHash; } } long long getFrontHash(int l, int r){ ///0 based if(r < l) return 0; long long ret = this->hashing[r]; if(l > 0){ ret = (ret - this->P[r - l + 1] * this->hashing[l - 1]) % this->M; /// (r - l + 1) length of the substring if(ret < 0) ret += this->M; } return ret; } long long merge(int x1, int y1, int x2, int y2, int c, int len){ ll r1 = getFrontHash(x1, y1); ll r2 = getFrontHash(x2, y2); ll ans = r1*2 + c; ans %= M; ans = (ans * P[len] + r2) % M; return ans; } }; void solve(){ int n; cin >> n; string s; cin >> s; FrontHash f1, f2; int cnt = count(all(s), '1'); if(cnt - 1 > 0) f1.init(s, 2, cnt - 1); f2.init(s, 2, cnt + 1); for(int i = 0; i < n; i++){ int nn = cnt; if(s[i] == '0') ++nn; else --nn; if(nn == 0) cout << 0 << "\n"; else if(nn == cnt + 1){ ll ret = f2.merge(0, i - 1, i + 1, n - 1, (s[i] =='0'? 1:0), n - i -1); ll ans = 1; while(ret){ ++ans; ret %= __builtin_popcountll(ret); } cout << ans << "\n"; } else{ ll ret = f1.merge(0, i - 1, i + 1, n - 1, (s[i] =='0'? 1:0), n - i -1); ll ans = 1; while(ret){ ++ans; ret %= __builtin_popcountll(ret); } cout << ans << "\n"; } } } int main(){ Fast_Read Precision(10) #ifdef obaydullah double start_time = clock(); ///freopen ("output.txt","w",stdout); ///freopen ("input.txt","r",stdin); #endif int tc = 1; //cin >> tc; while(tc--){ solve(); } #ifdef obaydullah double end_time = clock(); cerr<<"Time = "<<fixed<<setprecision(10)<<(end_time - start_time) / CLOCKS_PER_SEC<<'\n'; #endif return 0; } /** **/
85166c44da471529f379a0412d08725bc547ef8c
462d56087539769a099c4f0faa4bc144e393cde9
/leetcode/word_ladder.cpp
3203ff546fbc54df6fcd4d76e7861c0a009a3575
[]
no_license
rahulsbisen/interview
be0b0be6ef7120806a5bfdc26bf355a4f08cdb12
3e52bfb101287bda5b327009a8177d447dab9c18
refs/heads/master
2018-05-14T02:07:22.979216
2013-09-28T06:46:47
2013-09-28T06:46:47
48,376,051
1
0
null
2015-12-21T14:28:00
2015-12-21T14:27:59
null
UTF-8
C++
false
false
994
cpp
word_ladder.cpp
class Solution { public: int ladderLength(string start, string end, unordered_set<string> &dict) { // Start typing your C/C++ solution below // DO NOT write int main() function queue<pair<string, int>> q; q.push(pair<string, int>(start, 1)); int l = start.length(); while (!q.empty()) { string current = q.front().first; int step = q.front().second; q.pop(); for (int i = 0; i < l; ++i) { string tmp = current; for (char c = 'a'; c <= 'z'; ++c) { if (tmp[i] != c) { tmp[i] = c; if (tmp == end) return step + 1; if (dict.count(tmp) > 0) { q.push(pair<string, int>(tmp, step + 1)); dict.erase(tmp); } } } } } return 0; } };
2f230f1e7a8563e91a750b5f46fb84248827ef0c
a0ecaf557fad395a6c8a44a92505fbb17e328910
/dynawo/sources/Solvers/Common/DYNSolverFactory.cpp
e10a32cbd10e5a8b2cbf4256aceffdb807fa32ee
[]
no_license
koukiMohamed/ModalAnalysis
ab310c05545a95390e92dd8ab85bc106c84ce545
3b8b3b9319a732ca196ae4a1b60484e1bc860770
refs/heads/master
2022-12-20T06:44:59.274346
2020-09-28T14:50:37
2020-09-28T14:50:37
299,256,112
0
0
null
null
null
null
UTF-8
C++
false
false
129
cpp
DYNSolverFactory.cpp
version https://git-lfs.github.com/spec/v1 oid sha256:45c0a283e176a1efe5179362b6c1ecd4edd3dd5dd160629a8455caf511d3ebfb size 3749
2214191d1b85bfb5b0a262cc095a849f895d1b5f
511de588d62ab3b3125902e807d2ef2c1512aef8
/ejercicio1/PoligonoIrreg.cpp
256f596fe04d3dbc960936a3d3e32c87492f808e
[]
no_license
olaaldi/sistemas-distribuidos
0fe799be2f071841f0699c292cddcdb9db1ae1e6
216f3d23217f3ae71bf38201f4bd89326dafc4d0
refs/heads/master
2020-09-05T08:48:50.799041
2018-06-16T20:37:48
2018-06-16T20:37:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
721
cpp
PoligonoIrreg.cpp
#include "PoligonoIrreg.h" #include "Coordenada.h" #include <iostream> #include <algorithm> using namespace std; PoligonoIrreg::PoligonoIrreg(int n){ vertices.reserve(n); } bool PoligonoIrreg::comparacion(Coordenada a, Coordenada b) { return a.get_magnitud() < b.get_magnitud(); } void PoligonoIrreg::anadeVertice(Coordenada c) { vertices.push_back(c); } void PoligonoIrreg::imprimeVertices() { cout << "Vértices: \n"; for(int i=0; i<vertices.size(); i++){ cout << "(" << vertices[i].obtenerX() <<", " << vertices[i].obtenerY() << "), distancia al origen: "<< vertices[i].get_magnitud() <<"\n"; } } void PoligonoIrreg::ordenarVertices() { sort(vertices.begin(), vertices.end(), comparacion); }
3404db6e99e3e0c691c56b2832f5aff45725d812
ae72e35a44ffebe62cb19fba8a3105a9c944055a
/trunk/src/athena/Configuration.h
98d9f2b4d90b0b83bf5c13d01e52275b6fb82a5e
[]
no_license
RitchieLab/athena
7113e32d6ce3c060cbff6f19c944b85d921b4157
9294ea9cc2776c686cea96fd37c4b09eef6de446
refs/heads/master
2020-03-09T19:40:43.144918
2020-02-12T21:01:00
2020-02-12T21:01:00
128,963,752
2
0
null
null
null
null
UTF-8
C++
false
false
7,231
h
Configuration.h
/* Copyright Marylyn Ritchie 2011 This file is part of ATHENA. ATHENA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ATHENA 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 ATHENA. If not, see <http://www.gnu.org/licenses/>. */ /* * File: Configuration.h * Author: dudeksm * * Created on November 5, 2008, 4:59 PM */ #ifndef _CONFIGURATION_H #define _CONFIGURATION_H #include <map> #include <string> #include <vector> #include "AthenaExcept.h" #include "Structs.h" #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef HAVE_CXX_MPI #include <mpi.h> #endif /// holds parameters and name of the Algorithm struct AlgorithmParams{ std::map<std::string, std::string> params; std::string name; }; /// /// Contains configuration parameters for running HEMANN /// class Configuration{ public: /// Constructor Configuration(); std::string getDataSetType(){return dataType;} void setDataSetType(std::string dtype){dataType = dtype;} std::string getOutputName(){return outName;} void setOutputName(std::string oname){outName = oname;} std::string getMapName(){return mapName;} void setMapName(std::string mname){mapName = mname;} int getMissingValue(){return missValue;} void setMissingValue(int mval, std::string id=""){ if(mval >= 0 && mval <= 2) throw AthenaExcept("The missing value " + id +" cannot be between 0 and 2 inclusive."); missValue = mval; } float getStatusMissingValue(){return statMissValue;} void setStatusMissingValue(float val){statMissValue = val;} int getRandSeed(){return randSeed;} void setRandSeed(int rseed){randSeed = rseed;} int getNumCV(){return nCV;} void setNumCV(int numCV, std::string id=""){ if(numCV < 1) throw AthenaExcept("Number of cv " + id + " must be greater than zero"); nCV = numCV; } std::string getDataSetName(){return dataFile;} void setDataSetName(std::string dname){dataFile = dname;} void addAlgorithmParam(AlgorithmParams alg){algParams.push_back(alg);} std::vector<AlgorithmParams> getAlgorithmParams(){return algParams;} std::string getContinFileName(){return continFile;} void setContinFileName(std::string cname){continFile = cname;} bool getIDinData(){return idIncluded;} void setIDinData(bool id){idIncluded = id;} float getContinMiss(){return continMiss;} void setContinMiss(float val){continMiss = val;} bool getOttEncoded(){return ottDummyEncoded;} void setOttEncoded(bool ott){ottDummyEncoded = ott;} int getNumExchanges(){return numExchanges;} void setNumExchanges(int numEx, std::string id=""){ if(numEx < 0) throw AthenaExcept("Number of exchanges " + id + " must be greater than or equal to zero"); numExchanges = numEx; } void setCVOutput(bool val){cvOut = val;} bool getCVOutput(){return cvOut;} void setStatusAdjust(std::string statChange){statusChange=statChange;} std::string getStatusAdjust(){return statusChange;} void setContinAdjust(std::string cChange){continChange=cChange;} std::string getContinAdjust(){return continChange;} void setIndOutput(bool io){indsOutput = io;} bool getIndOutput(){return indsOutput;} void setOutputAllNodesBest(bool val){allNodesOut = val;} bool outputAllNodesBest(){return allNodesOut;} std::string getTrainFile(){return trainFile;} void setTrainFile(std::string filename){trainFile = filename;} std::string getTestFile(){return testFile;} void setTestFile(std::string filename){testFile = filename;} void setContinTestFile(std::string filename){continTest = filename;} std::string getContinTestFile(){return continTest;} void setContinTrainFile(std::string filename){continTrain = filename;} std::string getContinTrainFile(){return continTrain;} void setBioFilterFile(std::string filename){bioFilterFile = filename;} std::string getBioFilterFile(){return bioFilterFile;} void setBioGeneFile(std::string filename){bioGeneFile = filename;} std::string getBioGeneFile(){return bioGeneFile;} void setBioArchiveFile(std::string filename){bioArchiveFile = filename;} std::string getBioArchiveFile(){return bioArchiveFile;} void setBioFileType(std::string filetype){biofilterFileType = filetype;} std::string getBioFileType(){return biofilterFileType;} void setContinMapName(std::string filename){continMap=filename;} std::string getContinMapName(){return continMap;} void setSelectBestModel(bool tf){selectBest=tf;} bool selectBestModel(){return selectBest;} void setMultiCategory(bool tf){multiCat=tf;} bool getMultiCategory(){return multiCat;} void setSplitFile(std::string filename){splitFile = filename;} std::string getSplitFile(){return splitFile;} void setStartCV(int cv){startCV=cv;} int getStartCV(){return startCV;} inline std::string getImgWriter(){return imgWriter;} inline void setImgWriter(std::string executable){imgWriter=executable;} inline std::string getValidationSumFile(){return validationSumFile;} inline void setValidationSumFile(std::string filename){validationSumFile=filename;} /// throws an exception if parameters are in error void checkConfig(); // enum DataEncodeType{ // None, // OttDummy, // StephenDummy // }; enum SummaryType{ True, False, Best, All, Suppress }; inline void setSummaryOnly(std::string val){ std::map<std::string, SummaryType>::iterator iter = summaryMap.find(val); if(iter != summaryMap.end()){ summaryOnly = iter->second; } else{ throw AthenaExcept(val + " is not a valid parameter for summary type"); } } SummaryType getSummaryOnly(){return summaryOnly;} inline void setEncodeType(std::string encodeType){ encodeName = encodeType; } inline string getEncodeType(){return encodeName;} inline void setLogType(std::string logType){ std::map<std::string, LogType>::iterator iter = logTypeMap.find(logType); if(iter != logTypeMap.end()) logTypeSelected = iter->second; else throw AthenaExcept(logType + " is not a valid parameter for log type selection"); } inline LogType getLogType(){return logTypeSelected;} private: void initialize(); std::map<std::string, SummaryType> summaryMap; LogType logTypeSelected; std::map<std::string, LogType> logTypeMap; std::string dataType, outName, mapName, dataFile, continFile, statusChange, trainFile, testFile, continTest, continTrain, bioFilterFile, biofilterFileType, bioArchiveFile, bioGeneFile, continMap, splitFile, continChange, encodeName, imgWriter, validationSumFile; int missValue, nCV, randSeed, numExchanges, startCV; float continMiss, statMissValue; bool idIncluded, ottDummyEncoded, cvOut, indsOutput, allNodesOut, selectBest, multiCat; std::vector<AlgorithmParams> algParams; SummaryType summaryOnly; }; #endif /* _CONFIGURATION_H */
7c03d257a34d94f04274f7d77f5500c711af7592
c20c3cb1699f726fc285a6917d0ee673915f5b06
/WagonWar/Libraries/gpg.framework/Versions/A/Headers/quest_manager.h
4324d21e1277bf2487fe92d18554e62e8c034d30
[ "MIT", "CC-BY-3.0", "CC-BY-4.0", "Apache-2.0" ]
permissive
zoozooll/MyExercise
35a18c0ead552d5be45f627066a5066f6cc8c99b
1be14e0252babb28e32951fa1e35fc867a6ac070
refs/heads/master
2023-04-04T04:24:14.275531
2021-04-18T15:01:03
2021-04-18T15:01:03
108,665,215
2
0
null
null
null
null
UTF-8
C++
false
false
16,273
h
quest_manager.h
/** * @file gpg/quest_manager.h * @copyright Copyright 2014 Google Inc. All Rights Reserved. * @brief Entry points for Play Games Quest functionality. */ #ifndef GPG_QUEST_MANAGER_H_ #define GPG_QUEST_MANAGER_H_ #ifndef __cplusplus #error Header file supports C++ only #endif // __cplusplus #include <functional> #include <memory> #include <string> #include <vector> #include "gpg/common.h" #include "gpg/game_services.h" #include "gpg/quest.h" #include "gpg/types.h" namespace gpg { /** * Gets and sets various quest-related data. * @ingroup Managers */ class GPG_EXPORT QuestManager { public: /** * Constructs a <code>QuestManager</code> from a * <code>GameServicesImpl</code>. This function is not intended to be called * by consumers of this API. Instead, an app should retrieve the * <code>QuestManager</code> via the * <code>GameServices::QuestManager</code> call. */ explicit QuestManager(GameServicesImpl *game_services_impl); ~QuestManager(); /** * Holds data for a quest, along with a response status. * @ingroup ResponseType */ struct FetchResponse { /** * Can be one of the values enumerated in {@link ResponseStatus}. */ ResponseStatus status; /** * Data associated with this app. */ Quest data; }; /** * Defines a callback type that receives a <code>FetchResponse</code>. This * callback type is provided to the <code>Fetch(*)</code> functions below. * @ingroup Callbacks */ typedef std::function<void(FetchResponse const &)> FetchCallback; /** * Asynchronously loads data for a specific achievement for the currently * signed-in player. * Calls the provided <code>FetchCallback</code> upon operation completion. * Not specifying <code>data_source</code> makes this function call * equivalent to calling * <code>Fetch(DataSource data_source, std::string const &quest_id, </code> * <code>FetchCallback callback)</code>, with <code>data_source</code> * specified as <code>CACHE_OR_NETWORK</code>. */ void Fetch(std::string const &quest_id, FetchCallback callback); /** * Asynchronously loads quest data for the currently signed-in player. * Calls the provided <code>FetchCallback</code> upon operation completion. * Specify <code>data_source</code> as <code>CACHE_OR_NETWORK</code> or * <code>NETWORK_ONLY</code>. */ void Fetch(DataSource data_source, std::string const &quest_id, FetchCallback callback); /** * Synchronously loads quest data for the currently signed-in player, * directly returning the <code>FetchResponse</code>. Specifying neither * <code>data_source</code> nor <code>timeout</code> makes this function * call equivalent to calling * <code>FetchResponse FetchBlocking(DataSource data_source, </code> * <code>Timeout timeout)</code>, * with <code>data_source</code> specified as <code>CACHE_OR_NETWORK</code> * and <code>timeout</code> specified as 10 years. */ FetchResponse FetchBlocking(std::string const &quest_id); /** * Synchronously loads all quest data for the currently signed-in player, * directly returning the <code>FetchResponse</code>. Specify * <code>data_source</code> as <code>CACHE_OR_NETWORK</code> or * <code>NETWORK_ONLY</code>. Not specifying timeout makes this * function call equivalent to calling * <code>FetchResponse FetchBlocking(DataSource data_source, </code> * <code>Timeout timeout)</code>, with your specified value for * <code>data_source</code>, and <code>timeout</code> specified as 10 * years. */ FetchResponse FetchBlocking(DataSource data_source, std::string const &quest_id); /** * Synchronously loads quest data for the currently signed-in player, * directly returning the <code>FetchResponse</code>. Specify * <code>timeout</code> as an arbitrary number of milliseconds. Not * specifying <code>data_source</code> makes this function call equivalent to calling * <code>FetchResponse FetchBlocking(DataSource data_source, </code> * <code>Timeout timeout)</code>, * with <code>data_source</code> specified as * <code>CACHE_OR_NETWORK</code>, and <code>timeout</code> containing the * value you specified. */ FetchResponse FetchBlocking(Timeout timeout, std::string const &quest_id); /** * Synchronously loads quest data for the currently signed-in player. * directly returning the <code>FetchResponse</code>. Specify * <code>data_source</code> as <code>CACHE_OR_NETWORK</code> or * <code>NETWORK_ONLY</code>. Specify <code>timeout</code> as an arbitrary * number of milliseconds. */ FetchResponse FetchBlocking(DataSource data_source, Timeout timeout, std::string const &quest_id); /** * Contains data and response statuses for all quests. * @ingroup ResponseType */ struct FetchAllResponse { /** * Can be one of the values enumerated in {@link ResponseStatus}. */ ResponseStatus status; /** * A vector containing all quest data: */ std::vector<Quest> data; }; /** * Defines a callback type that receives a <code>FetchAllResponse</code>. * This callback type is provided to the <code>FetchAll(*)</code> functions * below. * @ingroup Callbacks */ typedef std::function<void(FetchAllResponse const &)> FetchAllCallback; /** * Asynchronously loads data for all quests of certain states for the * currently signed-in player. * Not specifying <code>data_source</code> makes this function call * equivalent to calling * <code>FetchAll(DataSource data_source, FetchAllCallback callback)</code>, * with <code>data_source</code> specified as <code>CACHE_OR_NETWORK</code>. */ void FetchAll(FetchAllCallback callback, int32_t fetch_flags); /** * Asynchronously loads data for all quests of certain states for the * currently signed-in player. * Specify <code>data_source</code> as <code>CACHE_OR_NETWORK</code> or * <code>NETWORK_ONLY</code>. */ void FetchAll(DataSource data_source, FetchAllCallback callback, int32_t fetch_flags); /** * Synchronously loads data for all quests of certain states for the * currently signed-in player, directly returning the * <code>FetchAllResponse</code>. Specifying neither * <code>data_source</code> nor <code>timeout</code> makes this function * call equivalent to calling * <code>FetchAllResponse FetchAllBlocking (DataSource data_source, </code> * <code>Timeout timeout)</code>, with <code>data_source</code> specified as * <code>CACHE_OR_NETWORK</code>, and <code>timeout</code> specified as 10 * years. */ FetchAllResponse FetchAllBlocking(int32_t fetch_flags); /** * Synchronously loads data for all quests of certain states for the * currently signed-in player, directly returning the * <code>FetchAllResponse</code>. Specify <code>data_source</code> as * <code>CACHE_OR_NETWORK</code> or <code>NETWORK_ONLY</code>. Not * specifying <code>timeout</code> makes this function call equivalent to * calling * <code>FetchAllResponse FetchAllBlocking(DataSource data_source, </code> * <code>Timeout timeout)</code>, * with your specified <code>data_source<code> value, and * <code>timeout</code> specified as 10 years. */ FetchAllResponse FetchAllBlocking(DataSource data_source, int32_t fetch_flags); /** * Synchronously loads data for all quests of certain states for the currently * signed-in player, directly returning the <code>FetchAllResponse</code>. * Specify <code>timeout</code> as an arbitrary number of milliseconds. Not * specifying <code>data_source</code> makes * this function call equivalent to calling * <code>FetchAllResponse FetchAllBlocking(DataSource data_source, </code> * <code>Timeout timeout)</code>, with <code>data_source</code> specified * as <code>CACHE_OR_NETWORK</code>, and <code>timeout</code> containing the * value you specified. */ FetchAllResponse FetchAllBlocking(Timeout timeout, int32_t fetch_flags); /** * Synchronously loads data for all quests of certain states for the * currently signed-in player, directly returning the * <code>FetchAllResponse</code>. Specify <code>data_source</code> as * <code>CACHE_OR_NETWORK</code> or <code>NETWORK_ONLY</code>. Specify * <code>timeout</code> as an arbitrary number of milliseconds. */ FetchAllResponse FetchAllBlocking(DataSource data_source, Timeout timeout, int32_t fetch_flags); /** * Asynchronously loads data for all quests, regardless of state, for the * currently signed-in player. * Not specifying <code>data_source</code> makes this function call * equivalent to calling * <code>FetchAll(DataSource data_source, FetchAllCallback callback)</code>, * with <code>data_source</code> specified as <code>CACHE_OR_NETWORK</code>. */ void FetchAll(FetchAllCallback callback); /** * Asynchronously loads data for all quests, regardless of state, for the * currently signed-in player. * Specify <code>data_source</code> as <code>CACHE_OR_NETWORK</code> * or <code>NETWORK_ONLY</code>. */ void FetchAll(DataSource data_source, FetchAllCallback callback); /** * Synchronously loads data for all quests, regardless of state, for the * currently signed-in player, directly returning the * <code>FetchAllResponse</code>. * Specifying neither <code>data_source</code> nor <code>timeout</code> * makes this function call equivalent to calling * <code>FetchAllResponse FetchAllBlocking (DataSource data_source, <code> * <code>Timeout timeout)</code>, with <code>data_source</code> specified as * <code>CACHE_OR_NETWORK</code>, and <code>timeout</code> specified as 10 * years. */ FetchAllResponse FetchAllBlocking(); /** * Synchronously loads data for all quests, regardless of state, for the * currently signed-in player, directly returning the * <code>FetchAllResponse</code>. * Specify <code>data_source</code> as <code>CACHE_OR_NETWORK</code> or * <code>NETWORK_ONLY</code>. Not specifying <code>timeout</code> makes * this function call equivalent to calling * <code>FetchAllResponse FetchAllBlocking(DataSource data_source, </code> * <code>Timeout timeout)</code>, * with your specified <code>data_source</code> value, and * <code>timeout</code> specified as 10 years. */ FetchAllResponse FetchAllBlocking(DataSource data_source); /** * Synchronously loads data for all quests, regardless of state, for the * currently signed-in player, directly returning the * <code>FetchAllResponse</code>. * Specify <code>timeout</code> as an arbitrary number of milliseconds. Not * specifying <code>data_source</code> makes this function call equivalent * to calling * <code>FetchAllResponse FetchAllBlocking(DataSource data_source, </code> * <code>Timeout timeout)</code>, * with <code>data_source</code> specified as <code>CACHE_OR_NETWORK</code>, * and <code>timeout</code> containing the value you specified. */ FetchAllResponse FetchAllBlocking(Timeout timeout); /** * Synchronously loads data for all quests, regardless of state, for the * currently signed-in player, directly returning the * <code>FetchAllResponse</code>. * Specify <code>data_source</code> as <code>CACHE_OR_NETWORK</code> or * <code>NETWORK_ONLY</code>. Specify <code>timeout</code> as * an arbitrary number of milliseconds. */ FetchAllResponse FetchAllBlocking(DataSource data_source, Timeout timeout); /** * Defines a callback that can be used to receive an * <code>AcceptQuestStatus</code>. Used by the <code>Accept*</code> functions. */ typedef std::function<void(QuestAcceptStatus)> AcceptCallback; /** * Asynchronously accept a quest. The quest must have a state * <code>QuestState::OPEN</code>. Incrementing the associated events will * start tracking progress toward the milestone goal. */ void Accept(Quest const &quest, AcceptCallback callback); /** * Synchronously accept a quest. The quest must have a state * <code>QuestState::OPEN</code>. Incrementing the associated events will * start tracking progress toward the milestone goal. * Not specifying timeout makes this function call equivalent to calling * <code>QuestAcceptStatus AcceptBlocking(Timeout timeout, </code> * <code> std::string const &quest_id), * </code>, with <code>timeout</code> specified as 10 years. */ QuestAcceptStatus AcceptBlocking(Quest const &quest); /** * Synchronously accept a quest. The quest must have a state * <code>QuestState::OPEN</code>. Incrementing the associated events will * start tracking progress toward the milestone goal. * Specify <code>timeout</code> as an arbitrary number of milliseconds. */ QuestAcceptStatus AcceptBlocking(Timeout timeout, Quest const &quest); /** * Defines a callback which can be used to receive a * <code>QuestClaimMilestoneStatus</code>.Used by the * <code>ClaimMilestone*</code> functions. */ typedef std::function<void(QuestClaimMilestoneStatus)> ClaimMilestoneCallback; /** * Asynchronously claims the milestone. Doing so calls the server, marking * the milestone as completed, enforcing (TODO (erickrk) "enforces," * not "ensures"?) that the milestone is currently claimable, and that it * hasn't been claimed already on this or another device. If this call * returns true for <code>QuestClaimMilestoneStatus::VALID</code>, you (as * developer) must still reward the player. Use the milestone * <code>CompletionRewardData</code> to do so. */ void ClaimMilestone(QuestMilestone const &milestone, ClaimMilestoneCallback callback); /** * Synchronously claim the milestone. Doing so calls the server, marking the * milestone as completed. It also enforces (TODO (erickrk) "enforces," * not "ensures"?) that the milestone is currently claimable, and that it * hasn't been claimed already on this or another device. If this call * returns true for <code>QuestClaimMilestoneStatus::VALID</code>, you (as * developer) must still reward the player. Use the milestone * <code>CompletionRewardData</code> to do so. * Not specifying <code>timeout</code> makes this function call equivalent * to calling <code>QuestClaimMilestoneStatus</code> * ClaimMilestoneBlocking( * Timeout timeout, * std::string const &quest_id, * std::string const &milestone_id); * with <code>timeout</code> specified as 10 years. */ QuestClaimMilestoneStatus ClaimMilestoneBlocking( QuestMilestone const &milestone); /** * Synchronously claim the milestone. Doing so will call the server, marking * the milestone as completed. It also enforces (TODO (ericrk): same * question as above) that the milestone is * currently claimable, and that it hasn't been claimed already on one or * another device. If this call returns true for * <code>QuestClaimMilestoneStatus::VALID</code>, you (as developer) must * still reward the player. Use the milestone * <code>CompletionRewardData</code> to do so. * Specify <code>timeout</code> as an arbitrary number of milliseconds. */ QuestClaimMilestoneStatus ClaimMilestoneBlocking( Timeout timeout, QuestMilestone const &milestone); /** * Presents to the user a UI that displays information about all quests. * Returns when the user has dismissed the UI. */ void ShowAllUI(); /** * Presents to the user a UI that displays information about a specific * quest. Returns when the user has dismissed the UI. */ void ShowUI(std::string const &quest_id); private: QuestManager(QuestManager const &) = delete; QuestManager &operator=(QuestManager const &) = delete; GameServicesImpl *const impl_; }; } // namespace gpg #endif // GPG_QUEST_MANAGER_H_
625a36dfa922f728c250cb0c199cd72fe4d06a6c
70466af3857ffb031450606be1a38fef5f929ff4
/electric_heater/electric_heater.ino
871f2284eb5d1dd55899cb0ca6863ffefbb65489
[]
no_license
marwaelfeqy/electric-heater-iot
a944a57b550143ed143639129ae0b33088de4025
6e83da1483da08c7801f176ab458bf14f8e7b8cb
refs/heads/master
2022-12-30T00:34:14.003205
2020-10-17T09:53:14
2020-10-17T09:53:14
304,846,494
0
0
null
null
null
null
UTF-8
C++
false
false
13,132
ino
electric_heater.ino
#include <ESP8266WiFi.h> #include <Ticker.h> #include "UbidotsESPMQTT.h" #include <ESP8266WiFi.h> #define u8 unsigned char #define On LOW #define Off HIGH #define b_on_off D5 #define b_up D6 #define b_down D7 #define power D2 #define testp D8 //#define TOKEN "BBFF-eg2hA0fhc4wDWzqHMDtyNnbtYe2O6m"//F //#define TOKEN "BBFF-VZg1gPgNY5U3v8dryETYu9ig70Dk2B" //C Your Ubidots TOKEN #define TOKEN "BBFF-MPR5uxfVSfRPzO75NgUayUW7O5x4zl" #define WIFINAME "Marwa" // Your SSID #define WIFIPASS "00000000" // Your Wifi Pass Ubidots client(TOKEN); String data; int onoroff =0; #define MAX_TASKS 4 u8 TaskCount = 0; const byte cooler = 2; const byte heater = 16; void ICACHE_RAM_ATTR ISR(void); typedef enum states {off, initial, temp_setting, check_state, heat, cool, sat} states; typedef enum buttons{ On_OFF_Button, Up_Button, Down_Button, none} buttons; states Current_State = off; buttons Button = none; int init_set_temp = 0; int sensor_temp = 0; int last_init_set_temp = 0; int set_temp_create = false; int counter =0; String rec_data; void Wifi_Init(void) { client.setDebug(true); // Pass a true or false bool value to activate debug messages client.wifiConnection(WIFINAME, WIFIPASS); client.begin(callback); client.ubidotsSubscribe("demo", "on_off"); // Insert the dataSource and Variable's Labels client.ubidotsSubscribe("demo", "num"); } void callback(char* topic, byte* payload, unsigned int length) { Serial.println("Message arrived "); data =""; rec_data = ""; rec_data =topic; for(int i =0; i<length-2; i++) { data += (char)payload[i]; } Serial.println(data); if (rec_data.indexOf("on_off")>= 0) { int x=data.toInt(); if (Current_State ==off && x==1) { onoroff = x; } else if (Current_State !=off && x==0) { onoroff = x; } } else if (rec_data.indexOf("num")>= 0 && Current_State != off && Current_State != temp_setting) { Serial.print("temp"); init_set_temp = data.toInt(); } } void heater_off(void) { digitalWrite(heater,Off); digitalWrite(cooler,Off); digitalWrite(power,LOW); client.add("on_off", 0); client.add("num", 0); client.add("initial-state", 0); client.add("sat-state", 0); client.ubidotsPublish("demo"); client.add("cool-state", 0); client.add("heat-state", 0); client.add("set-temp-state", 0); client.ubidotsPublish("demo"); onoroff=0; } typedef struct { void (*Ptr2Fun)(void) ; int Period ; int dly ; int runme ; }stask ; static stask Tasks[MAX_TASKS]; void Temp_Mode_Check(void); void Sched_vInit(void){ for (u8 count = 0 ; count < MAX_TASKS ; count ++ ){ Tasks[count].Ptr2Fun = NULL ; Tasks[count].dly = 0 ; Tasks[count].Period = 0 ; Tasks[count].runme = 0 ; } timer1_attachInterrupt(ISR); timer1_enable(TIM_DIV16, TIM_EDGE,TIM_SINGLE); timer1_write(125000); } void Sched_vCreatTask(void (*Ptr2Task)(void) , int Periodicity , int dly) { if ( MAX_TASKS >TaskCount ) { Tasks[TaskCount].Ptr2Fun = Ptr2Task ; Tasks[TaskCount].Period = Periodicity ; Tasks[TaskCount].dly = dly ; Tasks[TaskCount].runme = 0 ; TaskCount ++ ; } else { //tasks list is full } } void Sched_Disp(void) { for (u8 i =0 ; i<MAX_TASKS; i++) { if(Tasks[i].runme > 0) { Tasks[i].Ptr2Fun() ; Tasks[i].runme -= 1 ; if (Tasks[i].Period ==0) { Delete_Task(i); } } } } void Delete_Task(u8 index) { Tasks[index].Ptr2Fun=NULL ; Tasks[index].runme = 0 ; TaskCount--; } void ICACHE_RAM_ATTR ISR(void) { //update for (u8 i =0 ; i<MAX_TASKS; i++) { if(Tasks[i].Ptr2Fun) { if(Tasks[i].dly==0) { Tasks[i].runme+=1; if(Tasks[i].Period) { Tasks[i].dly = Tasks[i].Period -1; } } else { Tasks[i].dly--; } } } timer1_write(125000); } void Heater_Control_Update (void) { Serial.print(Current_State); if (Current_State == off) { if (Button == On_OFF_Button) { Current_State = initial; init_set_temp = 60; digitalWrite(power,HIGH); client.add("on_off", 1); client.add("num", init_set_temp); client.ubidotsPublish("demo"); onoroff=1; } else{ } } else if (Current_State == initial) { if (Button == On_OFF_Button) { Current_State = off; init_set_temp = 0; heater_off(); } else if (Button == Up_Button) { Current_State = temp_setting; } else if (Button ==Down_Button) { Current_State = temp_setting; } else {} } else if (Current_State == temp_setting) { if (Button == On_OFF_Button) { Current_State = off; init_set_temp = 0; heater_off(); } else if (Button == Up_Button) { if (init_set_temp <= 70) { init_set_temp += 5; Serial.println(); Serial.println(init_set_temp); } else {} } else if (Button == Down_Button) { if (init_set_temp >= 20) //40 { init_set_temp -= 5; Serial.println(); Serial.println(init_set_temp); } else {} } else {if (init_set_temp != last_init_set_temp) { client.add("num", init_set_temp); client.ubidotsPublish("demo"); last_init_set_temp = init_set_temp; }} } else if (Current_State == check_state) { if(Button == On_OFF_Button) { Current_State = off; init_set_temp = 0; heater_off(); } else if (Button == Up_Button) { Current_State = temp_setting; } else if (Button == Down_Button) { Current_State = temp_setting; } else{ if (init_set_temp -5 > sensor_temp) { Current_State = heat; } else if (init_set_temp +5 < sensor_temp) { Current_State = cool; } else { Current_State = sat; } } } else if (Current_State == heat) { if(Button == On_OFF_Button) { Current_State = off; init_set_temp = 0; heater_off(); } else if (Button == Up_Button ||Button == Down_Button) { Current_State = temp_setting; } else { digitalWrite(heater,On); digitalWrite(cooler,Off); Current_State = check_state; } } else if (Current_State == cool) { if(Button == On_OFF_Button) { Current_State = off; init_set_temp = 0; heater_off(); } else if (Button == Up_Button) { Current_State = temp_setting; } else if (Button == Down_Button) { Current_State = temp_setting; } else { digitalWrite(heater,Off); digitalWrite(cooler,On); Current_State = check_state; } } else if (Current_State == sat) { if(Button == On_OFF_Button) { Current_State = off; init_set_temp = 0; heater_off(); } else if (Button == Up_Button) { Current_State = temp_setting; } else if (Button == Down_Button) { Current_State = temp_setting; } else { digitalWrite(heater,Off); digitalWrite(cooler,Off); Current_State = check_state; } } else{} Button = none; } void Button_Update(void) { static u8 current_onof = 0; static u8 current_up = 0; static u8 current_down = 0; counter++; if(!digitalRead(b_down)||current_down)// if pressed { current_down = 1; if(digitalRead(b_down)) { Button = Down_Button; current_down = 0; } counter =0; } else { //Button = none; } if(! digitalRead(b_up) || current_up) { current_up = 1; if(digitalRead(b_up)) { Button = Up_Button; current_up = 0; } counter =0; } else { //Button = none; } if(!digitalRead(b_on_off)|| current_onof)// if pressed { current_onof = 1; if(digitalRead(b_on_off)) { Button = On_OFF_Button; current_onof = 0; } counter =0; } else { //Button = none; } if (Current_State == temp_setting || Current_State == initial) // 5sec passed { if(Button == none ) //without any pressed buttons { if(counter == 200)//5seconds { Current_State = check_state; counter = 0; } } }else{counter = 0; } } void Dashboard_Update(void) { static states Last_State = off; if (!client.connected()) { client.reconnect(); client.ubidotsSubscribe("demo", "on_off"); // Insert the dataSource and Variable's Labels client.ubidotsSubscribe("demo", "num"); } client.loop(); if(Current_State == off && onoroff == 1 && Button!= On_OFF_Button ) { Button = On_OFF_Button; counter =0; Last_State = Current_State; } else if(Current_State != off && onoroff == 0 &&Current_State != Last_State ) { Button = On_OFF_Button; counter =0; Last_State = Current_State; } else{} static int last_sensor_read = 0; if (sensor_temp != last_sensor_read) { last_sensor_read = sensor_temp; client.add("sensor", last_sensor_read); client.ubidotsPublish("demo"); } if(Current_State != Last_State && Current_State != check_state ) { if (Current_State == initial) { client.add("initial-state", 1); client.add("sat-state", 0); client.add("cool-state", 0); client.add("heat-state", 0); client.add("set-temp-state", 0); client.ubidotsPublish("demo"); } else if (Current_State == temp_setting) { client.add("initial-state", 0); client.add("sat-state", 0); client.add("cool-state", 0); client.add("heat-state", 0); client.add("set-temp-state", 2); client.ubidotsPublish("demo"); } else if (Current_State == heat) { client.add("initial-state", 0); client.add("sat-state", 0); client.add("cool-state", 0); client.add("heat-state", 4); client.add("set-temp-state", 0); client.ubidotsPublish("demo"); } else if (Current_State == cool) { client.add("initial-state", 0); client.add("sat-state", 0); client.add("cool-state", 5); client.add("heat-state", 0); client.add("set-temp-state", 0); client.ubidotsPublish("demo"); } else if (Current_State == sat) { client.add("initial-state", 0); client.add("sat-state", 6); client.add("cool-state", 0); client.add("heat-state", 0); client.add("set-temp-state", 0); client.ubidotsPublish("demo"); } Last_State = Current_State; } } void Sensor_Update (void) { if (Current_State == check_state) { sensor_temp = ((analogRead(A0)*3.3*100)/1024); Serial.println(); Serial.print("read temp: "); Serial.println(sensor_temp); } else {} } void setup() { Serial.begin(115200); pinMode(cooler, OUTPUT); pinMode(heater, OUTPUT); pinMode(power, OUTPUT); pinMode(b_on_off, INPUT_PULLUP); pinMode(b_up, INPUT_PULLUP); pinMode(b_down, INPUT_PULLUP); digitalWrite(cooler,Off); digitalWrite(heater,Off); digitalWrite(power,LOW); Sched_vInit(); //tick interval = 50ms Sched_vCreatTask( Heater_Control_Update , 4 , 0) ; Sched_vCreatTask( Button_Update , 1 , 0 ) ; Sched_vCreatTask( Dashboard_Update , 4 , 0 ) ; Sched_vCreatTask( Sensor_Update , 4 , 0 ) ; Wifi_Init(); } void loop() { Sched_Disp(); }
1b6a294834a009cf74ed093130999724a509e850
93981396be6e4bcb79c25f5aa96cf921ca390f77
/AsyncECS/Game/Logic/Hierarchy/HierarchySystem.cpp
a9dcdc21e3bf1323d9544a5e0ec7b91489f303b8
[]
no_license
JeppeNielsen/AsyncECS
bf256b99603eb40d339ad89a615ac8dbffebfa6b
f7faa305efeac5d2aa44f31e2980f6b8dbe1cfde
refs/heads/master
2020-09-01T19:53:23.084488
2020-08-31T19:11:56
2020-08-31T19:11:56
219,041,593
0
1
null
null
null
null
UTF-8
C++
false
false
1,655
cpp
HierarchySystem.cpp
// // AssignChildrenSystem.cpp // AsyncECS // // Created by Jeppe Nielsen on 23/02/2020. // Copyright © 2020 Jeppe Nielsen. All rights reserved. // #include "HierarchySystem.hpp" using namespace Game; using namespace AsyncECS; void HierarchySystem::Update(GameObject gameObject, Hierarchy& hierarchy) { auto previousParent = hierarchy.previousParent; auto currentParent = hierarchy.parent; if (previousParent != GameObjectNull) { GetComponents(previousParent, [gameObject](Hierarchy& hierarchy) { auto& children = hierarchy.children; children.erase(std::find(children.begin(), children.end(), gameObject)); }); } if (currentParent != GameObjectNull) { GetComponents(currentParent, [gameObject](Hierarchy& hierarchy) { hierarchy.children.push_back(gameObject); }); } hierarchy.previousParent = currentParent; } void HierarchySystem::GameObjectRemoved(GameObject gameObject) { GetComponents(gameObject, [gameObject, this](Hierarchy& hierarchy) { if (hierarchy.parent != GameObjectNull && !IsGameObjectRemoved(hierarchy.parent)) { GetComponents(hierarchy.parent, [gameObject, this](Hierarchy& parentHierarchy) { auto it = std::find(parentHierarchy.children.begin(), parentHierarchy.children.end(), gameObject); parentHierarchy.children.erase(it); }); hierarchy.parent = GameObjectNull; hierarchy.previousParent = GameObjectNull; } for (auto child : hierarchy.children) { RemoveGameObject(child); } }); }
0232bfb27689fc242f8eaefc9cf5b7e1a92286ba
bed3ac926beac0f4e0293303d7b2a6031ee476c9
/Modules/IO/Meta/src/itkMetaImageIO.cxx
600c3c9c3ecb63efe3fd96ec455c4966ecc655b9
[ "IJG", "Zlib", "LicenseRef-scancode-proprietary-license", "SMLNJ", "BSD-3-Clause", "BSD-4.3TAHOE", "LicenseRef-scancode-free-unknown", "Spencer-86", "LicenseRef-scancode-llnl", "FSFUL", "Libpng", "libtiff", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-hdf5", "MIT", "NTP", "LicenseRef-scancode-mit-old-style", "GPL-1.0-or-later", "LicenseRef-scancode-unknown-license-reference", "MPL-2.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
InsightSoftwareConsortium/ITK
ed9dbbc5b8b3f7511f007c0fc0eebb3ad37b88eb
3eb8fd7cdfbc5ac2d0c2e5e776848a4cbab3d7e1
refs/heads/master
2023-08-31T17:21:47.754304
2023-08-31T00:58:51
2023-08-31T14:12:21
800,928
1,229
656
Apache-2.0
2023-09-14T17:54:00
2010-07-27T15:48:04
C++
UTF-8
C++
false
false
44,118
cxx
itkMetaImageIO.cxx
/*========================================================================= * * Copyright NumFOCUS * * 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 * * https://www.apache.org/licenses/LICENSE-2.0.txt * * 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 "itkMetaImageIO.h" #include "itkSpatialOrientationAdapter.h" #include "itkIOCommon.h" #include "itksys/SystemTools.hxx" #include "itkMath.h" #include "itkSingleton.h" #include "itkMakeUniqueForOverwrite.h" namespace itk { // Explicitly set std::numeric_limits<double>::max_digits10 this will provide // better accuracy when writing out floating point number in MetaImage header. itkGetGlobalValueMacro(MetaImageIO, unsigned int, DefaultDoublePrecision, 17); unsigned int * MetaImageIO::m_DefaultDoublePrecision; MetaImageIO::MetaImageIO() { itkInitGlobalsMacro(DefaultDoublePrecision); m_FileType = IOFileEnum::Binary; m_SubSamplingFactor = 1; if (MET_SystemByteOrderMSB()) { m_ByteOrder = IOByteOrderEnum::BigEndian; } else { m_ByteOrder = IOByteOrderEnum::LittleEndian; } this->AddSupportedWriteExtension(".mha"); this->AddSupportedWriteExtension(".mhd"); this->AddSupportedReadExtension(".mha"); this->AddSupportedReadExtension(".mhd"); // set behavior of MetaImageIO independently of the default value in MetaImage this->SetDoublePrecision(GetDefaultDoublePrecision()); this->Self::SetCompressor(""); this->Self::SetMaximumCompressionLevel(9); this->Self::SetCompressionLevel(2); } MetaImageIO::~MetaImageIO() = default; void MetaImageIO::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); m_MetaImage.PrintInfo(); os << indent << "SubSamplingFactor: " << m_SubSamplingFactor << '\n'; } void MetaImageIO::SetDataFileName(const char * filename) { m_MetaImage.ElementDataFileName(filename); } // This method will only test if the header looks like a // MetaImage. Some code is redundant with ReadImageInformation // a StateMachine could provide a better implementation bool MetaImageIO::CanReadFile(const char * filename) { // First check the extension std::string fname = filename; if (fname.empty()) { itkDebugMacro("No filename specified."); return false; } return m_MetaImage.CanRead(filename); } void MetaImageIO::ReadImageInformation() { if (!m_MetaImage.Read(m_FileName.c_str(), false)) { itkExceptionMacro("File cannot be read: " << this->GetFileName() << " for reading." << std::endl << "Reason: " << itksys::SystemTools::GetLastSystemError()); } if (m_MetaImage.BinaryData()) { this->SetFileType(IOFileEnum::Binary); } else { this->SetFileType(IOFileEnum::ASCII); } this->SetNumberOfComponents(m_MetaImage.ElementNumberOfChannels()); // Set default value this->SetComponentType(IOComponentEnum::UNKNOWNCOMPONENTTYPE); itk::MetaDataDictionary & thisMetaDict = this->GetMetaDataDictionary(); switch (m_MetaImage.ElementType()) { default: case MET_OTHER: case MET_NONE: this->SetPixelType(IOPixelEnum::UNKNOWNPIXELTYPE); this->SetComponentType(IOComponentEnum::UNKNOWNCOMPONENTTYPE); break; case MET_CHAR: case MET_ASCII_CHAR: this->SetPixelType(IOPixelEnum::SCALAR); this->SetComponentType(IOComponentEnum::CHAR); break; case MET_CHAR_ARRAY: case MET_STRING: this->SetPixelType(IOPixelEnum::VECTOR); this->SetComponentType(IOComponentEnum::CHAR); break; case MET_UCHAR: this->SetPixelType(IOPixelEnum::SCALAR); this->SetComponentType(IOComponentEnum::UCHAR); break; case MET_UCHAR_ARRAY: this->SetPixelType(IOPixelEnum::VECTOR); this->SetComponentType(IOComponentEnum::UCHAR); break; case MET_SHORT: this->SetPixelType(IOPixelEnum::SCALAR); this->SetComponentType(IOComponentEnum::SHORT); break; case MET_SHORT_ARRAY: this->SetPixelType(IOPixelEnum::VECTOR); this->SetComponentType(IOComponentEnum::SHORT); break; case MET_USHORT: this->SetPixelType(IOPixelEnum::SCALAR); this->SetComponentType(IOComponentEnum::USHORT); break; case MET_USHORT_ARRAY: this->SetPixelType(IOPixelEnum::VECTOR); this->SetComponentType(IOComponentEnum::USHORT); break; case MET_INT: this->SetPixelType(IOPixelEnum::SCALAR); if (sizeof(int) == MET_ValueTypeSize[MET_INT]) { this->SetComponentType(IOComponentEnum::INT); } else if (sizeof(long) == MET_ValueTypeSize[MET_INT]) { this->SetComponentType(IOComponentEnum::LONG); } break; case MET_INT_ARRAY: this->SetPixelType(IOPixelEnum::VECTOR); if (sizeof(int) == MET_ValueTypeSize[MET_INT]) { this->SetComponentType(IOComponentEnum::INT); } else if (sizeof(long) == MET_ValueTypeSize[MET_INT]) { this->SetComponentType(IOComponentEnum::LONG); } break; case MET_UINT: this->SetPixelType(IOPixelEnum::SCALAR); if (sizeof(unsigned int) == MET_ValueTypeSize[MET_UINT]) { this->SetComponentType(IOComponentEnum::UINT); } else if (sizeof(unsigned long) == MET_ValueTypeSize[MET_UINT]) { this->SetComponentType(IOComponentEnum::ULONG); } break; case MET_UINT_ARRAY: this->SetPixelType(IOPixelEnum::VECTOR); if (sizeof(int) == MET_ValueTypeSize[MET_INT]) { this->SetComponentType(IOComponentEnum::UINT); } else if (sizeof(long) == MET_ValueTypeSize[MET_INT]) { this->SetComponentType(IOComponentEnum::ULONG); } break; case MET_LONG: this->SetPixelType(IOPixelEnum::SCALAR); if (sizeof(long) == MET_ValueTypeSize[MET_LONG]) { this->SetComponentType(IOComponentEnum::LONG); } else if (sizeof(int) == MET_ValueTypeSize[MET_LONG]) { this->SetComponentType(IOComponentEnum::INT); } break; case MET_LONG_ARRAY: this->SetPixelType(IOPixelEnum::VECTOR); if (sizeof(long) == MET_ValueTypeSize[MET_LONG]) { this->SetComponentType(IOComponentEnum::LONG); } else if (sizeof(int) == MET_ValueTypeSize[MET_LONG]) { this->SetComponentType(IOComponentEnum::INT); } break; case MET_ULONG: this->SetPixelType(IOPixelEnum::SCALAR); if (sizeof(unsigned long) == MET_ValueTypeSize[MET_ULONG]) { this->SetComponentType(IOComponentEnum::ULONG); } else if (sizeof(unsigned int) == MET_ValueTypeSize[MET_ULONG]) { this->SetComponentType(IOComponentEnum::UINT); } break; case MET_ULONG_ARRAY: this->SetPixelType(IOPixelEnum::VECTOR); if (sizeof(unsigned long) == MET_ValueTypeSize[MET_ULONG]) { this->SetComponentType(IOComponentEnum::ULONG); } else if (sizeof(unsigned int) == MET_ValueTypeSize[MET_ULONG]) { this->SetComponentType(IOComponentEnum::UINT); } break; case MET_LONG_LONG: this->SetPixelType(IOPixelEnum::SCALAR); if (sizeof(long long) == MET_ValueTypeSize[MET_LONG_LONG]) { this->SetComponentType(IOComponentEnum::LONGLONG); } else if (sizeof(int) == MET_ValueTypeSize[MET_LONG_LONG]) { this->SetComponentType(IOComponentEnum::INT); } else if (sizeof(long) == MET_ValueTypeSize[MET_LONG_LONG]) { this->SetComponentType(IOComponentEnum::LONG); } break; case MET_LONG_LONG_ARRAY: this->SetPixelType(IOPixelEnum::VECTOR); if (sizeof(long long) == MET_ValueTypeSize[MET_LONG_LONG]) { this->SetComponentType(IOComponentEnum::LONGLONG); } else if (sizeof(int) == MET_ValueTypeSize[MET_LONG_LONG]) { this->SetComponentType(IOComponentEnum::INT); } else if (sizeof(long) == MET_ValueTypeSize[MET_LONG_LONG]) { this->SetComponentType(IOComponentEnum::LONG); } break; case MET_ULONG_LONG: this->SetPixelType(IOPixelEnum::SCALAR); if (sizeof(unsigned long long) == MET_ValueTypeSize[MET_ULONG_LONG]) { this->SetComponentType(IOComponentEnum::ULONGLONG); } else if (sizeof(unsigned int) == MET_ValueTypeSize[MET_ULONG_LONG]) { this->SetComponentType(IOComponentEnum::UINT); } else if (sizeof(unsigned long) == MET_ValueTypeSize[MET_ULONG_LONG]) { this->SetComponentType(IOComponentEnum::ULONG); } break; case MET_ULONG_LONG_ARRAY: this->SetPixelType(IOPixelEnum::VECTOR); if (sizeof(unsigned long long) == MET_ValueTypeSize[MET_ULONG_LONG]) { this->SetComponentType(IOComponentEnum::ULONGLONG); } else if (sizeof(unsigned int) == MET_ValueTypeSize[MET_ULONG_LONG]) { this->SetComponentType(IOComponentEnum::UINT); } else if (sizeof(unsigned long) == MET_ValueTypeSize[MET_ULONG_LONG]) { this->SetComponentType(IOComponentEnum::ULONG); } break; case MET_FLOAT: this->SetPixelType(IOPixelEnum::SCALAR); if (sizeof(float) == MET_ValueTypeSize[MET_FLOAT]) { this->SetComponentType(IOComponentEnum::FLOAT); } else if (sizeof(double) == MET_ValueTypeSize[MET_FLOAT]) { this->SetComponentType(IOComponentEnum::DOUBLE); } break; case MET_FLOAT_ARRAY: this->SetPixelType(IOPixelEnum::VECTOR); if (sizeof(float) == MET_ValueTypeSize[MET_FLOAT]) { this->SetComponentType(IOComponentEnum::FLOAT); } else if (sizeof(double) == MET_ValueTypeSize[MET_FLOAT]) { this->SetComponentType(IOComponentEnum::DOUBLE); } break; case MET_DOUBLE: this->SetPixelType(IOPixelEnum::SCALAR); this->SetComponentType(IOComponentEnum::DOUBLE); if (sizeof(double) == MET_ValueTypeSize[MET_DOUBLE]) { this->SetComponentType(IOComponentEnum::DOUBLE); } else if (sizeof(float) == MET_ValueTypeSize[MET_DOUBLE]) { this->SetComponentType(IOComponentEnum::FLOAT); } break; case MET_DOUBLE_ARRAY: this->SetPixelType(IOPixelEnum::VECTOR); if (sizeof(double) == MET_ValueTypeSize[MET_DOUBLE]) { this->SetComponentType(IOComponentEnum::DOUBLE); } else if (sizeof(float) == MET_ValueTypeSize[MET_DOUBLE]) { this->SetComponentType(IOComponentEnum::FLOAT); } break; case MET_FLOAT_MATRIX: this->SetPixelType(IOPixelEnum::VECTOR); if (sizeof(float) == MET_ValueTypeSize[MET_FLOAT]) { this->SetComponentType(IOComponentEnum::FLOAT); } else if (sizeof(double) == MET_ValueTypeSize[MET_FLOAT]) { this->SetComponentType(IOComponentEnum::DOUBLE); } this->SetNumberOfComponents(m_NumberOfComponents * m_NumberOfComponents); break; } // BUG: 8732 // The above use to MET_*_ARRAY may not be correct, as this MetaIO // ElementType was not designed to indicate vectors, but something // else // // if the file has multiple components then we default to a vector // pixel type, support could be added to MetaIO format to define // different pixel types if (m_MetaImage.ElementNumberOfChannels() > 1) { this->SetPixelType(IOPixelEnum::VECTOR); } this->SetNumberOfDimensions(m_MetaImage.NDims()); unsigned int i; for (i = 0; i < m_NumberOfDimensions; ++i) { this->SetDimensions(i, m_MetaImage.DimSize(i) / m_SubSamplingFactor); this->SetSpacing(i, m_MetaImage.ElementSpacing(i) * m_SubSamplingFactor); this->SetOrigin(i, m_MetaImage.Position(i)); } // // Read direction cosines // const double * transformMatrix = m_MetaImage.TransformMatrix(); vnl_vector<double> directionAxis(this->GetNumberOfDimensions()); for (unsigned int ii = 0; ii < this->GetNumberOfDimensions(); ++ii) { for (unsigned int jj = 0; jj < this->GetNumberOfDimensions(); ++jj) { directionAxis[jj] = transformMatrix[ii * this->GetNumberOfDimensions() + jj]; } this->SetDirection(ii, directionAxis); } std::string classname(this->GetNameOfClass()); EncapsulateMetaData<std::string>(thisMetaDict, ITK_InputFilterName, classname); // // save the metadatadictionary in the MetaImage header. // NOTE: The MetaIO library only supports typeless strings as metadata int dictFields = m_MetaImage.GetNumberOfAdditionalReadFields(); for (int f = 0; f < dictFields; ++f) { std::string key(m_MetaImage.GetAdditionalReadFieldName(f)); std::string value(m_MetaImage.GetAdditionalReadFieldValue(f)); EncapsulateMetaData<std::string>(thisMetaDict, key, value); } // // Read some metadata // MetaDataDictionary & metaDict = this->GetMetaDataDictionary(); // Look at default metaio fields if (m_MetaImage.DistanceUnits() != MET_DISTANCE_UNITS_UNKNOWN) { EncapsulateMetaData<std::string>(metaDict, ITK_VoxelUnits, std::string(m_MetaImage.DistanceUnitsName())); } if (strlen(m_MetaImage.AcquisitionDate()) > 0) { EncapsulateMetaData<std::string>(metaDict, ITK_ExperimentDate, std::string(m_MetaImage.AcquisitionDate())); } } void MetaImageIO::Read(void * buffer) { const unsigned int nDims = this->GetNumberOfDimensions(); // this will check to see if we are actually streaming // we initialize with the dimensions of the file, since if // largestRegion and ioRegion don't match, we'll use the streaming // path since the comparison will fail ImageIORegion largestRegion(nDims); for (unsigned int i = 0; i < nDims; ++i) { largestRegion.SetIndex(i, 0); largestRegion.SetSize(i, this->GetDimensions(i)); } if (largestRegion != m_IORegion) { const auto indexMin = make_unique_for_overwrite<int[]>(nDims); const auto indexMax = make_unique_for_overwrite<int[]>(nDims); for (unsigned int i = 0; i < nDims; ++i) { if (i < m_IORegion.GetImageDimension()) { indexMin[i] = m_IORegion.GetIndex()[i]; indexMax[i] = indexMin[i] + m_IORegion.GetSize()[i] - 1; } else { indexMin[i] = 0; // this is zero since this is a (size - 1) indexMax[i] = 0; } } if (!m_MetaImage.ReadROI(indexMin.get(), indexMax.get(), m_FileName.c_str(), true, buffer, m_SubSamplingFactor)) { itkExceptionMacro("File cannot be read: " << this->GetFileName() << " for reading." << std::endl << "Reason: " << itksys::SystemTools::GetLastSystemError()); } m_MetaImage.ElementByteOrderFix(m_IORegion.GetNumberOfPixels()); } else { if (!m_MetaImage.Read(m_FileName.c_str(), true, buffer)) { itkExceptionMacro("File cannot be read: " << this->GetFileName() << " for reading." << std::endl << "Reason: " << itksys::SystemTools::GetLastSystemError()); } // since we are not streaming m_IORegion may not be set, so m_MetaImage.ElementByteOrderFix(this->GetImageSizeInPixels()); } } MetaImage * MetaImageIO::GetMetaImagePointer() { return &m_MetaImage; } bool MetaImageIO::CanWriteFile(const char * name) { const std::string filename = name; if (filename.empty()) { return false; } return this->HasSupportedWriteExtension(name, true); } void MetaImageIO::WriteImageInformation() { MetaDataDictionary & metaDict = this->GetMetaDataDictionary(); std::string metaDataStr; // Look at default metaio fields if (ExposeMetaData<std::string>(metaDict, ITK_VoxelUnits, metaDataStr)) { // Handle analyze style unit string if (metaDataStr == "um. ") { m_MetaImage.DistanceUnits(MET_DISTANCE_UNITS_UM); } else if (metaDataStr == "mm. ") { m_MetaImage.DistanceUnits(MET_DISTANCE_UNITS_MM); } else if (metaDataStr == "cm. ") { m_MetaImage.DistanceUnits(MET_DISTANCE_UNITS_CM); } else { m_MetaImage.DistanceUnits(metaDataStr.c_str()); } } if (ExposeMetaData<std::string>(metaDict, ITK_ExperimentDate, metaDataStr)) { m_MetaImage.AcquisitionDate(metaDataStr.c_str()); } // Save out the metadatadictionary key/value pairs as part of // the metaio header. std::vector<std::string> keys = metaDict.GetKeys(); std::vector<std::string>::const_iterator keyIt; for (keyIt = keys.begin(); keyIt != keys.end(); ++keyIt) { if (*keyIt == ITK_ExperimentDate || *keyIt == ITK_VoxelUnits) { continue; } // try for common scalar types std::ostringstream strs; double dval = 0.0; float fval = 0.0F; long lval = 0L; unsigned long ulval = 0L; long long llval = 0LL; unsigned long long ullval = 0uLL; int ival = 0; unsigned int uval = 0; short shval = 0; unsigned short ushval = 0; char cval = 0; unsigned char ucval = 0; bool bval = false; std::vector<double> vval(0); std::string value = ""; if (ExposeMetaData<std::string>(metaDict, *keyIt, value)) { strs << value; } else if (ExposeMetaData<double>(metaDict, *keyIt, dval)) { strs << dval; } else if (ExposeMetaData<float>(metaDict, *keyIt, fval)) { strs << fval; } else if (ExposeMetaData<long>(metaDict, *keyIt, lval)) { strs << lval; } else if (ExposeMetaData<unsigned long>(metaDict, *keyIt, ulval)) { strs << ulval; } else if (ExposeMetaData<long long>(metaDict, *keyIt, llval)) { strs << llval; } else if (ExposeMetaData<unsigned long long>(metaDict, *keyIt, ullval)) { strs << ullval; } else if (ExposeMetaData<int>(metaDict, *keyIt, ival)) { strs << ival; } else if (ExposeMetaData<unsigned int>(metaDict, *keyIt, uval)) { strs << uval; } else if (ExposeMetaData<short>(metaDict, *keyIt, shval)) { strs << shval; } else if (ExposeMetaData<unsigned short>(metaDict, *keyIt, ushval)) { strs << ushval; } else if (ExposeMetaData<char>(metaDict, *keyIt, cval)) { strs << cval; } else if (ExposeMetaData<unsigned char>(metaDict, *keyIt, ucval)) { strs << ucval; } else if (ExposeMetaData<bool>(metaDict, *keyIt, bval)) { strs << bval; } else if (ExposeMetaData<std::vector<double>>(metaDict, *keyIt, vval)) { unsigned int i = 0; while (i < vval.size() - 1) { strs << vval[++i] << ' '; } strs << vval[i]; } else if (WriteMatrixInMetaData<1>(strs, metaDict, *keyIt) || WriteMatrixInMetaData<2>(strs, metaDict, *keyIt) || WriteMatrixInMetaData<3>(strs, metaDict, *keyIt) || WriteMatrixInMetaData<4>(strs, metaDict, *keyIt) || WriteMatrixInMetaData<5>(strs, metaDict, *keyIt) || WriteMatrixInMetaData<6>(strs, metaDict, *keyIt)) { // Nothing to do, everything is done in WriteMatrixInMetaData } value = strs.str(); if (value.empty()) { // if the value is an empty string then the resulting entry in // the header will not be able to be read by the metaIO // library, which results is an unreadable/corrupt file. itkWarningMacro("Unsupported or empty metaData item " << *keyIt << " of type " << metaDict[*keyIt]->GetMetaDataObjectTypeName() << "found, won't be written to image file"); // so this entry should be skipped. continue; } // Rolling this back out so that the tests pass. // The meta image AddUserField requires control of the memory space. m_MetaImage.AddUserField(keyIt->c_str(), MET_STRING, static_cast<int>(value.size()), value.c_str(), true, -1); } } /** * */ void MetaImageIO::Write(const void * buffer) { const unsigned int numberOfDimensions = this->GetNumberOfDimensions(); bool binaryData = true; if (this->GetFileType() == IOFileEnum::ASCII) { binaryData = false; } int nChannels = this->GetNumberOfComponents(); MET_ValueEnumType eType = MET_OTHER; switch (m_ComponentType) { default: case IOComponentEnum::UNKNOWNCOMPONENTTYPE: eType = MET_OTHER; break; case IOComponentEnum::CHAR: eType = MET_CHAR; break; case IOComponentEnum::UCHAR: eType = MET_UCHAR; break; case IOComponentEnum::SHORT: eType = MET_SHORT; break; case IOComponentEnum::USHORT: eType = MET_USHORT; break; case IOComponentEnum::LONG: if (sizeof(long) == MET_ValueTypeSize[MET_LONG]) { eType = MET_LONG; } else if (sizeof(long) == MET_ValueTypeSize[MET_INT]) { eType = MET_INT; } else if (sizeof(long) == MET_ValueTypeSize[MET_LONG_LONG]) { eType = MET_LONG_LONG; } break; case IOComponentEnum::ULONG: if (sizeof(long) == MET_ValueTypeSize[MET_LONG]) { eType = MET_ULONG; } else if (sizeof(long) == MET_ValueTypeSize[MET_INT]) { eType = MET_UINT; } else if (sizeof(long) == MET_ValueTypeSize[MET_LONG_LONG]) { eType = MET_ULONG_LONG; } break; case IOComponentEnum::LONGLONG: if (sizeof(long long) == MET_ValueTypeSize[MET_LONG_LONG]) { eType = MET_LONG_LONG; } break; case IOComponentEnum::ULONGLONG: if (sizeof(long long) == MET_ValueTypeSize[MET_ULONG_LONG]) { eType = MET_ULONG_LONG; } break; case IOComponentEnum::INT: eType = MET_INT; if (sizeof(int) == MET_ValueTypeSize[MET_INT]) { eType = MET_INT; } else if (sizeof(int) == MET_ValueTypeSize[MET_LONG]) { eType = MET_LONG; } break; case IOComponentEnum::UINT: if (sizeof(int) == MET_ValueTypeSize[MET_INT]) { eType = MET_UINT; } else if (sizeof(int) == MET_ValueTypeSize[MET_LONG]) { eType = MET_ULONG; } break; case IOComponentEnum::FLOAT: if (sizeof(float) == MET_ValueTypeSize[MET_FLOAT]) { eType = MET_FLOAT; } else if (sizeof(float) == MET_ValueTypeSize[MET_DOUBLE]) { eType = MET_DOUBLE; } break; case IOComponentEnum::DOUBLE: if (sizeof(double) == MET_ValueTypeSize[MET_DOUBLE]) { eType = MET_DOUBLE; } else if (sizeof(double) == MET_ValueTypeSize[MET_FLOAT]) { eType = MET_FLOAT; } break; } const auto dSize = make_unique_for_overwrite<int[]>(numberOfDimensions); const auto eSpacing = make_unique_for_overwrite<double[]>(numberOfDimensions); const auto eOrigin = make_unique_for_overwrite<double[]>(numberOfDimensions); for (unsigned int ii = 0; ii < numberOfDimensions; ++ii) { dSize[ii] = this->GetDimensions(ii); eSpacing[ii] = this->GetSpacing(ii); eOrigin[ii] = this->GetOrigin(ii); } m_MetaImage.InitializeEssential( numberOfDimensions, dSize.get(), eSpacing.get(), eType, nChannels, const_cast<void *>(buffer)); m_MetaImage.Position(eOrigin.get()); m_MetaImage.BinaryData(binaryData); // Write the image Information this->WriteImageInformation(); if (numberOfDimensions == 3) { using SpatialOrientations = SpatialOrientationEnums::ValidCoordinateOrientations; SpatialOrientations coordOrient = SpatialOrientations::ITK_COORDINATE_ORIENTATION_INVALID; std::vector<double> dirx, diry, dirz; SpatialOrientationAdapter::DirectionType dir; dirx = this->GetDirection(0); diry = this->GetDirection(1); dirz = this->GetDirection(2); for (unsigned int ii = 0; ii < 3; ++ii) { dir[ii][0] = dirx[ii]; dir[ii][1] = diry[ii]; dir[ii][2] = dirz[ii]; } coordOrient = SpatialOrientationAdapter().FromDirectionCosines(dir); switch (coordOrient) { default: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RPI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RPS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RAI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RAS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RIA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RIP: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RSA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RSP: { m_MetaImage.AnatomicalOrientation(0, MET_ORIENTATION_RL); break; } case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LPI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LPS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LAI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LAS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LIA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LIP: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LSA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LSP: { m_MetaImage.AnatomicalOrientation(0, MET_ORIENTATION_LR); break; } case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ALI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ALS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ARI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ARS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_AIL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_AIR: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ASL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ASR: { m_MetaImage.AnatomicalOrientation(0, MET_ORIENTATION_AP); break; } case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PLI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PLS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PRI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PRS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PIL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PIR: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PSL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PSR: { m_MetaImage.AnatomicalOrientation(0, MET_ORIENTATION_PA); break; } case SpatialOrientations::ITK_COORDINATE_ORIENTATION_IPL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_IPR: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_IAL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_IAR: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ILA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ILP: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_IRA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_IRP: { m_MetaImage.AnatomicalOrientation(0, MET_ORIENTATION_IS); break; } case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SPL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SPR: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SAL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SAR: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SLA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SLP: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SRA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SRP: { m_MetaImage.AnatomicalOrientation(0, MET_ORIENTATION_SI); break; } } switch (coordOrient) { case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PRI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PRS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ARI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ARS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_IRA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_IRP: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SRA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SRP: { m_MetaImage.AnatomicalOrientation(1, MET_ORIENTATION_RL); break; } case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PLI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PLS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ALI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ALS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ILA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ILP: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SLA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SLP: { m_MetaImage.AnatomicalOrientation(1, MET_ORIENTATION_LR); break; } case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LAI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LAS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RAI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RAS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_IAL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_IAR: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SAL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SAR: { m_MetaImage.AnatomicalOrientation(1, MET_ORIENTATION_AP); break; } default: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LPI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LPS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RPI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RPS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_IPL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_IPR: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SPL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SPR: { m_MetaImage.AnatomicalOrientation(1, MET_ORIENTATION_PA); break; } case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PIL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PIR: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_AIL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_AIR: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LIA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LIP: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RIA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RIP: { m_MetaImage.AnatomicalOrientation(1, MET_ORIENTATION_IS); break; } case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PSL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PSR: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ASL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ASR: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LSA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LSP: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RSA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RSP: { m_MetaImage.AnatomicalOrientation(1, MET_ORIENTATION_SI); break; } } switch (coordOrient) { case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PIR: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PSR: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_AIR: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ASR: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_IAR: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_IPR: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SAR: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SPR: { m_MetaImage.AnatomicalOrientation(2, MET_ORIENTATION_RL); break; } case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PIL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PSL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_AIL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ASL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_IAL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_IPL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SAL: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SPL: { m_MetaImage.AnatomicalOrientation(2, MET_ORIENTATION_LR); break; } case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LIA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LSA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RIA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RSA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ILA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_IRA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SLA: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SRA: { m_MetaImage.AnatomicalOrientation(2, MET_ORIENTATION_AP); break; } case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LIP: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LSP: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RIP: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RSP: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ILP: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_IRP: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SLP: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_SRP: { m_MetaImage.AnatomicalOrientation(2, MET_ORIENTATION_PA); break; } default: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PLI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PRI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ALI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ARI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LAI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LPI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RAI: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RPI: { m_MetaImage.AnatomicalOrientation(2, MET_ORIENTATION_IS); break; } case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PLS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_PRS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ALS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_ARS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LAS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_LPS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RAS: case SpatialOrientations::ITK_COORDINATE_ORIENTATION_RPS: { m_MetaImage.AnatomicalOrientation(2, MET_ORIENTATION_SI); break; } } } // Propagage direction cosine information. auto * transformMatrix = static_cast<double *>(malloc(numberOfDimensions * numberOfDimensions * sizeof(double))); if (transformMatrix) { for (unsigned int ii = 0; ii < numberOfDimensions; ++ii) { for (unsigned int jj = 0; jj < numberOfDimensions; ++jj) { transformMatrix[ii * numberOfDimensions + jj] = this->GetDirection(ii)[jj]; } } m_MetaImage.TransformMatrix(transformMatrix); free(transformMatrix); } m_MetaImage.CompressedData(m_UseCompression); m_MetaImage.CompressionLevel(this->GetCompressionLevel()); // this is a check to see if we are actually streaming // we initialize with m_IORegion to match dimensions ImageIORegion largestRegion(m_IORegion); for (unsigned int ii = 0; ii < numberOfDimensions; ++ii) { largestRegion.SetIndex(ii, 0); largestRegion.SetSize(ii, this->GetDimensions(ii)); } if (m_UseCompression && (largestRegion != m_IORegion)) { std::cout << "Compression in use: cannot stream the file writing" << std::endl; } else if (largestRegion != m_IORegion) { const auto indexMin = make_unique_for_overwrite<int[]>(numberOfDimensions); const auto indexMax = make_unique_for_overwrite<int[]>(numberOfDimensions); for (unsigned int ii = 0; ii < numberOfDimensions; ++ii) { // the dimensions of m_IORegion should match out requested // dimensions, but ImageIORegion will throw an // exception if out of bounds indexMin[ii] = m_IORegion.GetIndex()[ii]; indexMax[ii] = m_IORegion.GetIndex()[ii] + m_IORegion.GetSize()[ii] - 1; } if (!m_MetaImage.WriteROI(indexMin.get(), indexMax.get(), m_FileName.c_str())) { itkExceptionMacro("File ROI cannot be written: " << this->GetFileName() << std::endl << "Reason: " << itksys::SystemTools::GetLastSystemError()); } } else { if (!m_MetaImage.Write(m_FileName.c_str())) { itkExceptionMacro("File cannot be written: " << this->GetFileName() << std::endl << "Reason: " << itksys::SystemTools::GetLastSystemError()); } } } /** Given a requested region, determine what could be the region that we can * read from the file. This is called the streamable region, which will be * smaller than the LargestPossibleRegion and greater or equal to the * RequestedRegion */ ImageIORegion MetaImageIO::GenerateStreamableReadRegionFromRequestedRegion(const ImageIORegion & requestedRegion) const { // // The default implementations determines that the streamable region is // equal to the largest possible region of the image. // ImageIORegion streamableRegion(this->m_NumberOfDimensions); if (!m_UseStreamedReading) { for (unsigned int i = 0; i < this->m_NumberOfDimensions; ++i) { streamableRegion.SetSize(i, this->m_Dimensions[i]); streamableRegion.SetIndex(i, 0); } } else { streamableRegion = requestedRegion; } return streamableRegion; } unsigned int MetaImageIO::GetActualNumberOfSplitsForWriting(unsigned int numberOfRequestedSplits, const ImageIORegion & pasteRegion, const ImageIORegion & largestPossibleRegion) { if (this->GetUseCompression()) { // we can not stream or paste with compression if (pasteRegion != largestPossibleRegion) { itkExceptionMacro("Pasting and compression is not supported! Can't write:" << this->GetFileName()); } else if (numberOfRequestedSplits != 1) { itkDebugMacro("Requested streaming and compression"); itkDebugMacro("Meta IO is not streaming now!"); } return 1; } if (!itksys::SystemTools::FileExists(m_FileName.c_str())) { // file doesn't exits so we don't have potential problems } else if (pasteRegion != largestPossibleRegion) { // we are going to be pasting (may be streaming too) // need to check to see if the file is compatible std::string errorMessage; Pointer headerImageIOReader = Self::New(); try { headerImageIOReader->SetFileName(m_FileName.c_str()); headerImageIOReader->ReadImageInformation(); } catch (...) { errorMessage = "Unable to read information from file: " + m_FileName; } // we now need to check that the following match: // 1)file is not compressed // 2)pixel type // 3)dimensions // 4)size/origin/spacing // 5)direction cosines // if (!errorMessage.empty()) { // 0) Can't read file } // 1)file is not compressed else if (headerImageIOReader->m_MetaImage.CompressedData()) { errorMessage = "File is compressed: " + m_FileName; } // 2)pixel type // this->GetPixelType() is not verified because the metaio file format // stores all multi-component types as arrays, so it does not // distinguish between pixel types. Also as long as the compoent // and number of compoents match we should be able to paste, that // is the numbers should be the same it is just the interpretation // that is not matching else if (headerImageIOReader->GetNumberOfComponents() != this->GetNumberOfComponents() || headerImageIOReader->GetComponentType() != this->GetComponentType()) { errorMessage = "Component type does not match in file: " + m_FileName; } // 3)dimensions/size else if (headerImageIOReader->GetNumberOfDimensions() != this->GetNumberOfDimensions()) { errorMessage = "Dimensions does not match in file: " + m_FileName; } else { for (unsigned int i = 0; i < this->GetNumberOfDimensions(); ++i) { // 4)size/origin/spacing if (headerImageIOReader->GetDimensions(i) != this->GetDimensions(i) || Math::NotExactlyEquals(headerImageIOReader->GetSpacing(i), this->GetSpacing(i)) || Math::NotExactlyEquals(headerImageIOReader->GetOrigin(i), this->GetOrigin(i))) { errorMessage = "Size, spacing or origin does not match in file: " + m_FileName; break; } // 5)direction cosines if (headerImageIOReader->GetDirection(i) != this->GetDirection(i)) { errorMessage = "Direction cosines does not match in file: " + m_FileName; break; } } } if (!errorMessage.empty()) { itkExceptionMacro("Unable to paste because pasting file exists and is different. " << errorMessage); } else if (headerImageIOReader->GetPixelType() != this->GetPixelType()) { // since there is currently poor support for pixel types in // MetaIO we will just warn when it does not match itkWarningMacro("Pixel types does not match file, but component type and number of components do."); } } else if (numberOfRequestedSplits != 1) { // we are going be streaming // need to remove the file incase the file doesn't match our // current header/meta data information if (!itksys::SystemTools::RemoveFile(m_FileName.c_str())) { itkExceptionMacro("Unable to remove file for streaming: " << m_FileName); } } return GetActualNumberOfSplitsForWritingCanStreamWrite(numberOfRequestedSplits, pasteRegion); } ImageIORegion MetaImageIO::GetSplitRegionForWriting(unsigned int ithPiece, unsigned int numberOfActualSplits, const ImageIORegion & pasteRegion, const ImageIORegion & itkNotUsed(largestPossibleRegion)) { return GetSplitRegionForWritingCanStreamWrite(ithPiece, numberOfActualSplits, pasteRegion); } void MetaImageIO::SetDefaultDoublePrecision(unsigned int precision) { itkInitGlobalsMacro(DefaultDoublePrecision); *m_DefaultDoublePrecision = precision; } unsigned int MetaImageIO::GetDefaultDoublePrecision() { itkInitGlobalsMacro(DefaultDoublePrecision); return *MetaImageIO::GetDefaultDoublePrecisionPointer(); } } // end namespace itk
308132eb9bd03d9e9a4376aa24c873a5a21d5f4e
32225ff4d01b520926e0538ede06e947d818527c
/matrix/dimension.h
f0d2ca908615c8cdd038cb8876ccf663414a9254
[]
no_license
lukasTolksdorf/cpp_ML
d0fd411121e24592c5e59974c69fc8865e39d5d2
bc3e3c9a8df9aaa3213da6bba4a8040ff52c8b7e
refs/heads/master
2020-03-07T18:44:32.661902
2018-04-01T18:00:04
2018-04-01T18:00:04
127,650,434
0
0
null
2018-04-01T18:00:05
2018-04-01T16:38:47
C++
UTF-8
C++
false
false
407
h
dimension.h
#ifndef DIMENSION_H_ #define DIMENSION_H_ namespace matr{ class Dimension{ public: Dimension(const int& rows,const int& columns); Dimension() = delete; // do not allow for this constructor to be called int getRows() const; int getColumns() const; void resize(const int& rows, const int& columns); bool operator==(const Dimension& rhs) const; private: int rows_; int columns_; }; } #endif
3817867ee249b46822c250d3731d621f1af1f481
c6748dbfac809e3a1e0fbf95710a42160f4d2a8a
/7_22_findNum/findNum.cpp
bdd76f15b0aa601ffde47780e1ae415a1c1bc0a2
[]
no_license
haohaosong/Review
5c60cc98021662d6bdc994f033cbb7a8497edc90
33bc2aa20999af04161fb14efee5718e0544d0bd
refs/heads/master
2020-04-05T14:12:56.226062
2017-08-10T03:04:18
2017-08-10T03:04:18
94,836,660
0
0
null
null
null
null
UTF-8
C++
false
false
685
cpp
findNum.cpp
/************************************************************************* > File Name: findNum.cpp > Author: haohaosong > Mail: haohaosong@yeah.net > Created Time: Sat 22 Jul 2017 02:30:32 PM CST ************************************************************************/ #include<iostream> using namespace std; int findNum(int* arr,size_t n) { int num = arr[0]; int count = 1; for(int i = 1; i<n; ++i) { if(num == arr[i]) { count++; continue; } if(--count == 0) { num = arr[i+1]; count = 1; } } return num; } int main() { int arr[] = {2,3,2,2,2,2,2,5,4,1,2,3}; int ret = findNum(arr,sizeof(arr)/sizeof(arr[0])); cout<<ret<<endl; return 0; }
55140bc37a74421c3b01e7b667cd02e3d55f521f
37d1ceacda69f6b904dcd1bf52e2b2242843ee49
/src/fdm_r44/r44_Aerodynamics.cpp
f962211d752a3661c913984e7de84af0982e3992
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
marek-cel/mscsim
7a85f42eb0b50840d713f87c33a065b4feec7d5c
04a739e770b04a334da30e09a8cf1c89fae02c34
refs/heads/master
2023-04-28T04:40:30.536671
2023-04-21T17:33:15
2023-04-21T17:33:15
164,319,941
271
38
NOASSERTION
2023-09-02T05:39:55
2019-01-06T15:27:44
C++
UTF-8
C++
false
false
6,532
cpp
r44_Aerodynamics.cpp
/****************************************************************************//* * Copyright (C) 2021 Marek M. Cel * * 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 <fdm_r44/r44_Aerodynamics.h> #include <fdm_r44/r44_Aircraft.h> #include <fdm/xml/fdm_XmlUtils.h> //////////////////////////////////////////////////////////////////////////////// using namespace fdm; //////////////////////////////////////////////////////////////////////////////// R44_Aerodynamics::R44_Aerodynamics( const R44_Aircraft *aircraft, Input *input ) : Aerodynamics( aircraft, input ), _aircraft ( aircraft ), _mainRotor ( FDM_NULLPTR ), _tailRotor ( FDM_NULLPTR ), _fuselage ( FDM_NULLPTR ), _stabHor ( FDM_NULLPTR ), _stabVer ( FDM_NULLPTR ) { _mainRotor = new R44_MainRotor(); _tailRotor = new R44_TailRotor(); _fuselage = new R44_Fuselage(); _stabHor = new R44_StabilizerHor(); _stabVer = new R44_StabilizerVer(); } //////////////////////////////////////////////////////////////////////////////// R44_Aerodynamics::~R44_Aerodynamics() { FDM_DELPTR( _mainRotor ); FDM_DELPTR( _tailRotor ); FDM_DELPTR( _fuselage ); FDM_DELPTR( _stabHor ); FDM_DELPTR( _stabVer ); } //////////////////////////////////////////////////////////////////////////////// void R44_Aerodynamics::readData( XmlNode &dataNode ) { if ( dataNode.isValid() ) { XmlNode nodeMainRotor = dataNode.getFirstChildElement( "main_rotor" ); XmlNode nodeTailRotor = dataNode.getFirstChildElement( "tail_rotor" ); XmlNode nodeFuselage = dataNode.getFirstChildElement( "fuselage" ); XmlNode nodeStabHor = dataNode.getFirstChildElement( "stab_hor" ); XmlNode nodeStabVer = dataNode.getFirstChildElement( "stab_ver" ); _mainRotor->readData( nodeMainRotor ); _tailRotor->readData( nodeTailRotor ); _fuselage->readData( nodeFuselage ); _stabHor->readData( nodeStabHor ); _stabVer->readData( nodeStabVer ); } else { XmlUtils::throwError( __FILE__, __LINE__, dataNode ); } } //////////////////////////////////////////////////////////////////////////////// void R44_Aerodynamics::initialize() { /////////////////////////// Aerodynamics::initialize(); /////////////////////////// } //////////////////////////////////////////////////////////////////////////////// void R44_Aerodynamics::computeForceAndMoment() { updateMatrices(); _mainRotor->computeForceAndMoment( _aircraft->getVel_BAS(), _aircraft->getOmg_BAS(), _aircraft->getAcc_BAS(), _aircraft->getEps_BAS(), _aircraft->getVel_air_BAS(), _aircraft->getOmg_air_BAS(), _aircraft->getGrav_BAS(), _aircraft->getEnvir()->getDensity() ); _tailRotor->computeForceAndMoment( _aircraft->getVel_air_BAS(), _aircraft->getOmg_air_BAS(), _aircraft->getEnvir()->getDensity() ); _fuselage->computeForceAndMoment( _aircraft->getVel_air_BAS(), _aircraft->getOmg_air_BAS(), _aircraft->getEnvir()->getDensity(), _mainRotor->getBeta1c(), _mainRotor->getWakeSkew() ); _stabHor->computeForceAndMoment( _aircraft->getVel_air_BAS(), _aircraft->getOmg_air_BAS(), _aircraft->getEnvir()->getDensity() ); _stabVer->computeForceAndMoment( _aircraft->getVel_air_BAS(), _aircraft->getOmg_air_BAS(), _aircraft->getEnvir()->getDensity() ); _for_bas = _mainRotor->getFor_BAS() + _tailRotor->getFor_BAS() + _fuselage->getFor_BAS() + _stabHor->getFor_BAS() + _stabVer->getFor_BAS(); _mom_bas = _mainRotor->getMom_BAS() + _tailRotor->getMom_BAS() + _fuselage->getMom_BAS() + _stabHor->getMom_BAS() + _stabVer->getMom_BAS(); // computing forces expressed in Aerodynamic Axes System // computing moments expressed in Stability Axes System _for_aero = _bas2aero * _for_bas; _mom_stab = _bas2stab * _mom_bas; if ( !_for_bas.isValid() || !_mom_bas.isValid() ) { Exception e; e.setType( Exception::UnexpectedNaN ); e.setInfo( "NaN detected in the aerodynamics model." ); FDM_THROW( e ); } } //////////////////////////////////////////////////////////////////////////////// void R44_Aerodynamics::update() { /////////////////////// Aerodynamics::update(); /////////////////////// _mainRotor->update( _aircraft->getProp()->getMainRotorOmega(), _aircraft->getProp()->getMainRotorPsi(), _aircraft->getCtrl()->getCollective(), _aircraft->getCtrl()->getCyclicLat(), _aircraft->getCtrl()->getCyclicLon() ); _tailRotor->update( _aircraft->getProp()->getTailRotorOmega(), _aircraft->getCtrl()->getTailPitch() ); }
0921d4fdce5cd16bec220a3ffbb0e00d25f636e6
9ad34dfad9ecc654a95045a2c03067510c2b0242
/Lab4/Llanta.h
ea965914ef460db07477850706d4611b22193510
[]
no_license
carlosvelaquez/Laboratorio4P3
482646383d4a783b70906d806579e34c76c20c27
dd7ea9d60c982658c210b35dd815db3240827931
refs/heads/master
2021-01-16T18:21:48.492086
2017-08-11T23:10:26
2017-08-11T23:10:26
100,063,302
0
0
null
null
null
null
UTF-8
C++
false
false
314
h
Llanta.h
#ifndef LLANTA_H #define LLANTA_H #include <string> using namespace std; class Llanta{ private: string material; float precio; string color; public: string getMaterial(); void setMaterial(string); string getColor(); void setColor(string); float getPrecio(); void setPrecio(float); }; #endif
23348cd0d18841f21d0dc12de6f575d81d707570
0681a9fd09f690149472c28587e2ed387c449ab5
/src/utils/msgbox.cpp
416200d88deaed69d5443436f88dd47fe73f186f
[]
no_license
zhzh2001/tnpquest
8b50c857cf5d6b8032d873d82bb0876dabd1f9ee
26d0e4540bbc9b309460f4a886e500856551193f
refs/heads/master
2022-09-09T10:16:29.394325
2022-08-28T03:55:12
2022-08-28T03:55:12
202,351,368
0
0
null
null
null
null
UTF-8
C++
false
false
2,844
cpp
msgbox.cpp
#include "msgbox.h" #include "utils.h" #ifdef _WIN32 #include "../pdcurses/curses.h" #else #include "../ncurses/ncurses.h" #endif #include <cstring> Board *MsgBox::board = nullptr; Cat *MsgBox::cat = nullptr; Game *MsgBox::game = nullptr; bool MsgBox::fallback = false; void MsgBox::initBoard(Board *b) { board = b; } void MsgBox::initCat(Cat *c) { cat = c; } void MsgBox::initGame(Game *g) { game = g; } void MsgBox::initFallback(bool f) { fallback = f; } void MsgBox::create(const char *msg, const char *msg2) { int width = strLen(msg) + 6; int height = 5; if (msg2) { width = std::max<int>(width, strLen(msg2) + 6); height++; } int starty = (ROWS - height) / 2; int startx = (COLS - width) / 2; WINDOW *win = newwin(height, width, starty, startx); if (fallback) wborder(win, '|', '|', '-', '-', '+', '+', '+', '+'); else box(win, 0, 0); // draw with UTF-8 characters wrefresh(win); mvwprintw(win, 1, (width - strLen(msg)) / 2, msg); if (msg2) mvwprintw(win, 2, (width - strLen(msg2)) / 2, msg2); wattron(win, A_REVERSE); // highlight the OK button mvwprintw(win, height - 2, width / 2 - 4, paddingMid("OK", false).c_str()); wattroff(win, A_REVERSE); wrefresh(win); for (int ch = getch(); ch != '\n' && ch != '\r'; ch = getch()) ; // wait for user to press enter wborder(win, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '); // clear border wrefresh(win); delwin(win); // render destoryed board and cat again #ifdef _WIN32 clear(); game->renderStatus(); #endif board->renderScreen(fallback); cat->renderAttributes(fallback); refresh(); } int MsgBox::create(const char *msg, const char *option1, const char *option2) { int width = strLen(msg) + 6; int height = 5; int starty = (ROWS - height) / 2; int startx = (COLS - width) / 2; WINDOW *win = newwin(height, width, starty, startx); if (fallback) wborder(win, '|', '|', '-', '-', '+', '+', '+', '+'); else box(win, 0, 0); wrefresh(win); int option = 1; for (;;) { mvwprintw(win, 1, 3, msg); if (option == 1) wattron(win, A_REVERSE); mvwprintw(win, height - 2, width / 8, paddingMid(option1, false).c_str()); wattroff(win, A_REVERSE); if (option == 2) wattron(win, A_REVERSE); mvwprintw(win, height - 2, width - width / 8 - 8, paddingMid(option2, false).c_str()); wattroff(win, A_REVERSE); wrefresh(win); int c = getch(); if (c == '\n' || c == '\r') break; else if (c == KEY_LEFT) option = 1; else if (c == KEY_RIGHT) option = 2; } wborder(win, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '); wrefresh(win); delwin(win); #ifdef _WIN32 clear(); game->renderStatus(); #endif board->renderScreen(fallback); cat->renderAttributes(fallback); refresh(); return option; }
701415feee4f494833a3f250cb4773f9f676f431
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/Codes/AC/2857.cpp
ef5938c8118d42d73ade558c7c09a8d1a35bd267
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
1,208
cpp
2857.cpp
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int N=2e6+5; int nxt1[N],nxt2[N],p[N]; char s[N],str[N]; void getnext(char *t,int len,int *nxt){ int i,j; i=0,j=nxt[0]=-1; while(i<len){ while(j!=-1&&t[i]!=t[j]) j=nxt[j]; nxt[++i]=++j; } } bool kmp(char *s,int len1,char *t,int len2){ int i,j; i=j=0; getnext(t,len2,nxt2); while(i<len1){ while(j!=-1&&s[i]!=t[j]) j=nxt2[j]; i++,j++; if(j==len2) return true; } return false; } int main(){ while(~scanf("%s",s)){ int len=strlen(s); getnext(s,len,nxt1); int t=nxt1[len]; int ans=0; while(t>0){ if(kmp(s+1,len-2,s,t)){ ans=t; break; } t=nxt1[t]; } if(ans!=0){ for(int i=0;i<ans;i++){ printf("%c",s[i]); } puts(""); } else puts("Just a legend"); } return 0; }
ed7de194f910125c3b0e679f154069e4e3737353
82bba04be05e518845b99d749a3293668725e9e7
/QHG3/regionizer/GRegion.h
29ba35803590123e94a2292d5704e3942b43cb35
[]
no_license
Achandroth/QHG
e914618776f38ed765da3f9c64ec62b983fc3df3
7e64d82dc3b798a05f2a725da4286621d2ba9241
refs/heads/master
2023-06-04T06:24:41.078369
2018-07-04T11:01:08
2018-07-04T11:01:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
936
h
GRegion.h
#ifndef __GREGION_H__ #define __GREGION_H__ #include <vector> #include <set> #include "types.h" typedef std::set<int> intset; class SCellGrid; class GRegion { public: GRegion(int iID, SCellGrid *pCG, int *piAgentsPerCell, int *piMarks); ~GRegion(); uint findNeighbors(); uint addCell(int iID); void showRegion(); int getTotal() { return m_iTotal;}; int getNumCells() { return m_vMembers.size();}; int getNumNeighbors() { return m_vCurNeighbors.size();}; intset &getNeighbors() { return m_vCurNeighbors;}; int removeFromNeighbors(intset &sRemove); uint addAllNeighbors(); uint addRandomNeighbor(); uint addSmallestNeighbor(); uint addLargestNeighbor(); protected: int m_iID; SCellGrid *m_pCG; int *m_piAgentsPerCell; int *m_piMarks; uint m_iTotal; intset m_vMembers; intset m_vCurNeighbors; }; #endif
6d1b5c2874a7230b2b45c3b32183c46885393bc8
d5366bd1fb08eff92e657fa4b73383ee0e09e744
/BigramSentenceGenerator/BigramSentenceGenerator/Main.cpp
cd53f5949c31dac9e9a2d016c2213c7fdcadeb75
[]
no_license
WerenskjoldH/Sentence-Generator
daf8a1a107ca788f1a5d6ad62696aa3ecc5244aa
f5c58b32ac1345da2936bb92341fd579b6fbe760
refs/heads/master
2021-09-17T15:04:54.975640
2018-07-03T06:05:54
2018-07-03T06:05:54
125,136,500
0
0
null
null
null
null
UTF-8
C++
false
false
6,288
cpp
Main.cpp
#include "stdafx.h" #include <string> #include <fstream> #include <sstream> #include <ctime> #include <iostream> #include <vector> #include <map> using namespace std; // Mad Lib Code ( Is Mad Lib copywritted? Should I change this? ) int sizeFileByLines(ifstream &FILE) { int z = 0; if (FILE.fail()) cout << "\nERROR: File could not open.\n"; string s; while (getline(FILE, s)) { z++; } FILE.clear(); FILE.seekg(0, ios::beg); return z; } string inputToOutput(int cnt, string in, ifstream &FILE) { srand(time(NULL)); int r = rand() % cnt; int ctr = 0; string line; while (getline(FILE, line)) { if (ctr == r) { return line; break; } ctr++; } FILE.clear(); FILE.seekg(0, ios::beg); } void madLib() { char cont; do { vector<string> input; vector<string> output; int x = 0; cout << "[-------------Input-------------]\n\n\tadj - adjectives\n\tadv - adverbs\n\tar - articles\n\tn - nouns\n\tv - verbs\n\tp - pronouns\n\tx - end sentence\n\n Ex: p n v adv x\n[--------------------------------]\n"; // Begin input step cout << "\nEnter Sentence: "; string inp; cin >> inp; do { input.push_back(inp); x++; cin >> inp; } while (inp.compare("x") != 0); // Open all the files ifstream adjFile("adjectives.txt"); ifstream advFile("adverbs.txt"); ifstream artFile("articles.txt"); ifstream nounsFile("nouns.txt"); ifstream verbsFile("verbs.txt"); ifstream pronounsFile("pronouns.txt"); // Initialize sizes of files int adjSize = 0, advSize = 0, artSize = 0, nounSize = 0, verbSize = 0, proSize = 0, c = 0; // Check if files openned and size files by number of lines adjSize = sizeFileByLines(adjFile); advSize = sizeFileByLines(advFile); artSize = sizeFileByLines(artFile); nounSize = sizeFileByLines(nounsFile); verbSize = sizeFileByLines(verbsFile); proSize = sizeFileByLines(pronounsFile); for (c = 0; c < x; c++) { string temp = input.at(c); if (temp.compare("adj") == 0) { output.push_back(inputToOutput(adjSize, temp, adjFile)); } else if (temp.compare("adv") == 0) { output.push_back(inputToOutput(advSize, temp, advFile)); } else if (temp.compare("ar") == 0) { output.push_back(inputToOutput(artSize, temp, artFile)); } else if (temp.compare("n") == 0) { output.push_back(inputToOutput(nounSize, temp, nounsFile)); } else if (temp.compare("v") == 0) { output.push_back(inputToOutput(verbSize, temp, verbsFile)); } else if (temp.compare("p") == 0) { output.push_back(inputToOutput(proSize, temp, pronounsFile)); } else { output.push_back(temp); } } adjFile.close(); advFile.close(); artFile.close(); nounsFile.close(); verbsFile.close(); cout << "\n\n"; for (c = 0; c < x; c++) { if (c + 1 < x && (output.at(c + 1).at(0) == '-')) { cout << output.at(c); output.at(c + 1).erase(0, 1); } else cout << output.at(c) << " "; } cout << "\n\n\nDo you want to continue(y/n)? \n"; cin >> cont; cout << "\n~Flushing Stream~\n" << flush; system("CLS"); } while (cont == 'y'); } // Bigram Code std::map<std::pair<std::string, std::string>, int> bigrams; int avgSentenceLength = 0; void bigramSentenceCreator() { char cont; do { // Bigram Creation Code int sentenceCount = 0; char fileScanCont; do { int cnt; cout << "\nEnter the name of the text file: "; string fileName; cin >> fileName; ifstream FILE(fileName); string line; while (getline(FILE, line)) { vector<pair<string, string>> bigramKey; istringstream iss(line); string tok; vector<string> sentenceToks; while (iss >> tok) sentenceToks.push_back(tok); for (auto it = cbegin(sentenceToks); it != prev(cend(sentenceToks)); ++it) { bigramKey.push_back(std::make_pair(*it, *next(it))); } for (const auto& e : bigramKey) { bigrams[e] = bigrams[e]++; } avgSentenceLength += sentenceToks.size(); sentenceCount++; } FILE.clear(); FILE.seekg(0, ios::beg); cout << "\nDo you have more files you would like to read?(y/n) "; cin >> fileScanCont; } while (fileScanCont == 'y'); cout << "\n~Flushing Stream~\n" << flush; system("CLS"); avgSentenceLength = avgSentenceLength / sentenceCount; cout << "The avg length of sentences is: " << avgSentenceLength; // Sentence Generation Code string startingWord; int sentenceLen; int numSentences; cout << "\nGive a starting word to generate a sentence(Type 'x' to stop): "; cin >> startingWord; if (startingWord != "x") { cout << "How long should the line be: "; cin >> sentenceLen; } srand(time(NULL)); while(startingWord != "x") { // Generate bigram sentence string curWord = startingWord; cout << "\n\nLine: "; for (int x = 0; x < sentenceLen; x++) { vector<pair<string, int>> nextOptions; for (std::map<std::pair<std::string, std::string>, int>::iterator iter = bigrams.begin(); iter != bigrams.end(); ++iter) { pair<string, string> k = iter->first; if (k.first == curWord) nextOptions.push_back(make_pair(k.second, bigrams[k])); } cout << curWord << " "; if (nextOptions.size() > 0) { curWord = nextOptions[rand() % nextOptions.size()].first; } else { // There were no connected words, so what ever, let's just guess auto it = bigrams.begin(); int randWord = rand() % bigrams.size(); advance(it, randWord); curWord = it->first.first; } } cout << "\n"; cout << "\nGive a starting word to generate a sentence(Type 'x' to stop): "; cin >> startingWord; if (startingWord != "x") { cout << "How long should the line be: "; cin >> sentenceLen; } } cout << "\n\n\nDo you want to reset and run the bigram code again?(y/n)? "; cin >> cont; cout << "\n~Flushing Stream~\n" << flush; system("CLS"); } while (cont == 'y'); } int main() { char inp; while (1 == 1) { cout << "Type 'b' to use bigram code or type 'm' to load madLib code: "; cin >> inp; if (inp == 'b' || inp == 'm') break; } if (inp == 'b') bigramSentenceCreator(); else madLib(); system("PAUSE"); return 0; }
5052b445133e4c24aefb7f67e953ab0c30f8d1cf
fffec3207a471ef56a596ea6f22b2ef8837a8302
/ACM-FPT/Test 2019-08-25/I_RacingAroundTheAlphabet.cpp
aeafdfc59cbd322a99cdc2b2e87b596512eb8882
[]
no_license
vietnakid/ACM-ICPC
c3561e942a82f18035d2bbf00a9123f526114b98
7258daf208806e0344cf55e1f023082500c62442
refs/heads/master
2020-03-09T01:46:41.984239
2020-02-15T03:57:28
2020-02-15T03:57:28
128,523,997
0
0
null
null
null
null
UTF-8
C++
false
false
1,710
cpp
I_RacingAroundTheAlphabet.cpp
#include <bits/stdc++.h> #include <unistd.h> using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector< vector<int> > vvi; typedef vector<ll> vl; typedef vector< vector<ll> > vvl; typedef pair<int, int> ii; typedef vector<ii> vii; typedef vector< vii> vvii; #define INF 1000000007 #define INFLL 1000000000000000000 #define esp 1e-9 #define PI 3.14159265 ll nMod = 1e9 + 7; inline ll GCD(ll a, ll b) {while (b != 0) {ll c = a % b; a = b; b = c;} return a;}; inline ll LCM(ll a, ll b) {return (a / GCD(a,b)) * b;}; int pos[256]; void init() { for (int i = 'A'; i <= 'Z'; i++) { pos[i] = i - 'A'; } pos[' '] = 26; pos['\''] = 27; } void vietnakid() { init(); int n; cin >> n; string s; getline(cin, s); double circumference = 30. * 2 * PI; double t = (circumference / 28.); for (int i = 0; i < n; i++) { getline(cin, s); int leng = s.size(); double totalLeng = 0; for (int i = 0; i < leng - 1; i++) { int _min = min(pos[s[i]], pos[s[i + 1]]); int _max = max(pos[s[i]], pos[s[i + 1]]); totalLeng += min(_max - _min, _min + 28 - _max); } double res = (totalLeng / 15.)*t + leng; printf("%.10lf\n", res); } } int main() { ios_base::sync_with_stdio(false); cin.tie(); #ifdef LOCAL_KID freopen("/Users/macbook/Desktop/MyCPPLibrary/input", "r", stdin); freopen("/Users/macbook/Desktop/MyCPPLibrary/output", "w", stdout); freopen("/Users/macbook/Desktop/MyCPPLibrary/error", "w", stderr); #else // online submission #endif vietnakid(); cerr << "\nTime elapsed: " << 1000 * clock() / CLOCKS_PER_SEC << "ms\n"; return 0; }
4c91486fdfb06457318bc4ce4419b82895a1cfd0
5cd6df5636d631e186b5b2aec616a19dc1952405
/Parser.cpp
956724268c88a602c328bebf565ab8a2b7ff7c3a
[]
no_license
KuomintanGG/OiAK_Project
02a2004b25308cc1319e1c76ad81741dc621b23b
d62bf439fbc3790b6a90d7f7c6c82ae82aa4f864
refs/heads/master
2020-03-09T18:27:58.552538
2018-04-09T20:49:03
2018-04-09T20:49:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
222
cpp
Parser.cpp
/* * Parser.cpp * * Created on: 9 kwi 2018 * Author: darek */ #include "Parser.h" Parser::Parser() { // TODO Auto-generated constructor stub } Parser::~Parser() { // TODO Auto-generated destructor stub }
6a3664582b73489a5c32c3eec8ca92f48c687d0c
82aa7e39cee87c475ecc92f2e11de46968091a40
/SwampAttack/Classes/GuideCompositeApposeModel.hpp
45f80993eebb92802a853fbe6180c63da07140e2
[]
no_license
weimingtom/CompanyWork
bc6bf8f07302748811c41ac76dba016dd51b3d44
249e0fde40c16117aaca05698cb073d1820d93be
refs/heads/master
2020-12-31T04:06:08.321405
2016-03-07T08:45:37
2016-03-07T08:45:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
478
hpp
GuideCompositeApposeModel.hpp
// // GuideCompositeApposeModel.hpp // SwampAttack // // Created by oceantech02 on 16/1/26. // // #ifndef GuideCompositeApposeModel_hpp #define GuideCompositeApposeModel_hpp #include "GuideCompositeModel.hpp" class GuideCompositeApposeModel: public GuideCompositeModel { private: public: GuideCompositeApposeModel(); ~GuideCompositeApposeModel(); void active(); void progress(); void finish(); }; #endif /* GuideCompositeApposeModel_hpp */
5f594af1d39d100eef66990514bbfbcf06de87f5
03a5169462e1fe4bc6216e1aeca3634902d95c08
/winPAApi/src/sharedmemory/pool/pa_dvr.cpp
698be21324a44b65e0d8ccfdca93ab3ef0983d11
[]
no_license
JulianaYuan/windows_com_qnx
4a30ec046eda2e0130d58516c5ee2c05d1e00e27
cbb7f482cf4fe70d3dce2f2db42c1504173c3a66
refs/heads/main
2023-03-27T23:08:16.300280
2021-04-08T10:28:17
2021-04-08T10:28:17
355,855,241
0
1
null
null
null
null
UTF-8
C++
false
false
84
cpp
pa_dvr.cpp
#include "pa_dvr.h" SharedMemory::Pool SharedMemoryPool_PA_Dvr{ "PA_Dvr", 65535 };
4d33a3f11fefe91253281779b08f102ce5755f89
a79b33d65f73b522d544d65ffa24d26c4812d095
/BitGrapher/encoding/ASCII8.h
69efa92ed7932c3ace562716f89783dedcbcf5a0
[]
no_license
nhurman/data-carving
0e84a57397766a9af8acee3a03f7760c8b77887a
88fcbdce2420940222397e0d2b6f38f97ee38f09
refs/heads/master
2016-08-06T15:53:55.487865
2014-06-26T15:33:07
2014-06-26T15:33:07
13,904,311
0
0
null
null
null
null
UTF-8
C++
false
false
449
h
ASCII8.h
#ifndef ASCII8_H #define ASCII8_H #include "core/BitString.h" #include "encoding/Encoding2.h" /*! * \class ASCII8 * \brief ASCII encoding over 8 bits * * \author Nicolas Hurman * \date 28/05/2014 */ class ASCII8 : public Encoding2 { public: ASCII8(); std::string getChunk(unsigned int index) const; virtual unsigned int bitsPerChunk() const; virtual std::string getName() const; }; #endif // ASCII8_H
38410a4c94515fc6e88b6adefdc5ac4cac38e561
6102a3d66ba7b629ad81137df5a27f8bb1b992ac
/common/SPhoenix/utils.h
c5d2decba85712b5b80c1752099a2af194238d2d
[]
no_license
Hielamon/OpenGLToys
5cebf6f9435e9b8c7ea83195b121d875f3043faa
e32d91abe5396eedacc51ee5fbfacc62317164c8
refs/heads/master
2021-01-20T01:51:39.237411
2018-01-30T10:04:30
2018-01-30T10:04:30
89,336,455
1
0
null
2018-01-30T10:04:31
2017-04-25T08:29:02
C++
UTF-8
C++
false
false
1,927
h
utils.h
#pragma once #include <memory> #include <algorithm> #include <fstream> #include <string> #include <vector> #include <map> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <SOIL.h> #include <glm\glm.hpp> #include <glm\gtc\matrix_transform.hpp> #include <glm\gtc\type_ptr.hpp> #include <glm\gtc\matrix_access.hpp> #include <glm/gtx/string_cast.hpp> #include <SPhoenix/global_macro.h> /**Get the resolution of primary screen*/ inline glm::u32vec2 GetScreenResolution() { const GLFWvidmode * mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); if (mode == NULL) { SP_CERR("cannot get the screen's resolution"); return glm::u32vec2(-1, -1); } return glm::u32vec2(mode->width, mode->height); } inline void RigidTransformLookAt(glm::mat4 &rigid, glm::vec3 &eye, glm::vec3 &center, glm::vec3 &up) { glm::mat4 translate = glm::translate(glm::mat4(1.0f), eye); glm::vec3 zDir = eye - center; glm::vec3 zAxis = glm::normalize(zDir); glm::vec3 xAxis = glm::normalize(glm::cross(up, zAxis)); glm::vec3 yAxis = glm::cross(zAxis, xAxis); glm::vec4 col1 = glm::vec4(xAxis, 0.0f); glm::vec4 col2 = glm::vec4(yAxis, 0.0f); glm::vec4 col3 = glm::vec4(zAxis, 0.0f); glm::vec4 col4 = glm::vec4(glm::vec3(0.0f), 1.0f); glm::mat4 rotate = glm::mat4(col1, col2, col3, col4); glm::mat4 Cam2World = translate * rotate; glm::vec4 eyeHomo(glm::vec3(0.0f), 1.0f); eye = glm::vec3(Cam2World * rigid * eyeHomo); float zDistance = glm::dot(zDir, zDir); zDistance = sqrtf(zDistance); glm::vec4 centerHomo(0.0f, 0.0f, -zDistance, 1.0f); center = glm::vec3(Cam2World * rigid * centerHomo); glm::vec4 upHomo(0.0f, 1.0f, 0.0f, 0.0f); up = glm::vec3(Cam2World * rigid * upHomo); /*glm::vec4 eyeHomo(eye, 1.0f); eye = glm::vec3(rigid * eyeHomo); glm::vec4 centerHomo(center, 1.0f); center = glm::vec3(rigid * centerHomo); glm::vec4 upHomo(up, 0.0f); up = glm::vec3(rigid * upHomo);*/ }
db0b12d5dafd6dca33822982f0803974eb176ee4
294776fc4e920e99d03e023838134dd7c10b7140
/fast_transformers/sparse_product/clustered_sparse_product_cpu.cpp
b68ec34f0e9df231940d3e4dbb7eecc11c83e81f
[ "MIT" ]
permissive
idiap/fast-transformers
1510559ad9bb4896460b615895d09231cc2db784
2ad36b97e64cb93862937bd21fcc9568d989561f
refs/heads/master
2023-08-02T15:36:58.835564
2023-03-09T08:51:59
2023-03-23T16:46:47
272,430,903
1,528
173
null
2023-03-22T10:17:39
2020-06-15T12:19:51
Python
UTF-8
C++
false
false
7,285
cpp
clustered_sparse_product_cpu.cpp
// // Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/ // Written by Angelos Katharopoulos <angelos.katharopoulos@idiap.ch>, // Apoorv Vyas <avyas@idiap.ch> // #include <torch/extension.h> inline float dot(float *a, float *b, int n) { float s = 0; for (int i=0; i<n; i++) { s += (*a) * (*b); a++; b++; } return s; } inline void add_scaled(float *a, float *b, float s, int n) { for (int i=0; i<n; i++) { (*a) += s * (*b); a++; b++; } } void clustered_sparse_dot_product( const torch::Tensor Q, const torch::Tensor K, const torch::Tensor groups, const torch::Tensor topk, torch::Tensor product ) { int N = Q.size(0); int H = Q.size(1); int L = Q.size(2); int E = Q.size(3); int k = topk.size(3); int S = K.size(2); int C = topk.size(2); float *queries = Q.data_ptr<float>(); float *keys = K.data_ptr<float>(); int64_t *topk_p = topk.data_ptr<int64_t>(); int *groups_p = groups.data_ptr<int>(); float *product_p = product.data_ptr<float>(); #pragma omp parallel for for (int n=0; n<N; n++) { for (int h=0; h<H; h++) { for (int l=0; l<L; l++) { float *query = queries + n*H*L*E + h*L*E + l*E; int g = groups_p[n*H*L + h*L + l]; if ((g > -1) && (g < C)) { for (int j=0; j<k; j++) { product_p[n*H*L*k + h*L*k + l*k + j] = dot( query, keys + n*H*S*E + h*S*E + topk_p[n*H*C*k + h*C*k + g*k + j]*E, E ); } } } } } } void clustered_sparse_dot_backward( const torch::Tensor Q, const torch::Tensor K, const torch::Tensor groups, const torch::Tensor topk, const torch::Tensor grad_out, torch::Tensor grad_Q, torch::Tensor grad_K ) { int N = Q.size(0); int H = Q.size(1); int L = Q.size(2); int E = Q.size(3); int k = topk.size(3); int S = K.size(2); int C = topk.size(2); float *queries = Q.data_ptr<float>(); float *keys = K.data_ptr<float>(); int64_t *topk_p = topk.data_ptr<int64_t>(); int *groups_p = groups.data_ptr<int>(); auto grad_out_a = grad_out.accessor<float, 4>(); float *grad_q = grad_Q.data_ptr<float>(); float *grad_k = grad_K.data_ptr<float>(); #pragma omp parallel for for (int n=0; n<N; n++) { for (int h=0; h<H; h++) { for (int l=0; l<L; l++) { float *grad_query = grad_q + n*H*L*E + h*L*E + l*E; float *query = queries + n*H*L*E + h*L*E + l*E; int g = groups_p[n*H*L + h*L + l]; if ((g > -1) && (g < C)) { for (int j=0; j<k; j++) { int key_idx = topk_p[n*H*C*k + h*C*k + g*k + j]; float g = grad_out_a[n][h][l][j]; add_scaled( grad_query, keys + n*H*S*E + h*S*E + key_idx*E, g, E ); add_scaled( grad_k + n*H*S*E + h*S*E + key_idx*E, query, g, E ); } } } } } } void clustered_sparse_weighted_average( const torch::Tensor weights, const torch::Tensor values, const torch::Tensor groups, const torch::Tensor topk, torch::Tensor output ) { int N = weights.size(0); int H = weights.size(1); int L = weights.size(2); int k = weights.size(3); int E = values.size(3); int C = topk.size(2); auto weights_a = weights.accessor<float, 4>(); auto values_a = values.accessor<float, 4>(); auto topk_a = topk.accessor<int64_t, 4>(); auto groups_a = groups.accessor<int, 3>(); auto output_a = output.accessor<float, 4>(); #pragma omp parallel for for (int n=0; n<N; n++) { for (int h=0; h<H; h++) { for (int l=0; l<L; l++) { float *out = &output_a[n][h][l][0]; int g = groups_a[n][h][l]; if ((g > -1) && (g < C)) { for (int j=0; j<k; j++) { int key_idx = topk_a[n][h][g][j]; add_scaled( out, &values_a[n][h][key_idx][0], weights_a[n][h][l][j], E ); } } } } } } void clustered_sparse_weighted_average_backward( const torch::Tensor weights, const torch::Tensor values, const torch::Tensor groups, const torch::Tensor topk, const torch::Tensor grad_out, torch::Tensor grad_weights, torch::Tensor grad_values ) { int N = weights.size(0); int H = weights.size(1); int L = weights.size(2); int k = weights.size(3); int E = values.size(3); int C = topk.size(2); auto weights_a = weights.accessor<float, 4>(); auto values_a = values.accessor<float, 4>(); auto topk_a = topk.accessor<int64_t, 4>(); auto groups_a = groups.accessor<int, 3>(); auto grad_out_a = grad_out.accessor<float, 4>(); auto grad_weights_a = grad_weights.accessor<float, 4>(); auto grad_values_a = grad_values.accessor<float, 4>(); #pragma omp parallel for for (int n=0; n<N; n++) { for (int h=0; h<H; h++) { for (int l=0; l<L; l++) { float *grad = &grad_out_a[n][h][l][0]; int g = groups_a[n][h][l]; if ((g > -1) && (g < C)) { for (int j=0; j<k; j++) { int key_idx = topk_a[n][h][g][j]; add_scaled( &grad_values_a[n][h][key_idx][0], grad, weights_a[n][h][l][j], E ); grad_weights_a[n][h][l][j] = dot( &values_a[n][h][key_idx][0], grad, E ); } } } } } } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def( "clustered_sparse_dot_product", &clustered_sparse_dot_product, "Compute the dot product only in the positions specified by topk." ); m.def( "clustered_sparse_dot_backward", &clustered_sparse_dot_backward, "Compute the gradients for the sparse dot product." ); m.def( "clustered_sparse_weighted_average", &clustered_sparse_weighted_average, "Average the values using the sparse attention." ); m.def( "clustered_sparse_weighted_average_backward", &clustered_sparse_weighted_average_backward, "Compute the gradients for the sparse weighted average." ); }
7ac322512affba52113ac6a04ef45fbedb2fe6b8
b293c80725c1e0d245a9dd6db01d9cd7750eddbd
/calc_ir_tilt/calc_ir_tilt.cpp
55aa0198a16125e9b069cd316de2e9ce7a153299
[]
no_license
Raylingogogo/calc_ir_tilt
e55c9a1b015917aa2c0a1040c030c9a3e4232953
17a60feb8ad338eb7f809db48606e9b0d68f8dde
refs/heads/master
2021-07-07T16:53:49.160889
2017-09-29T07:22:40
2017-09-29T07:22:40
104,896,560
0
0
null
null
null
null
UTF-8
C++
false
false
5,651
cpp
calc_ir_tilt.cpp
// calc_ir_tilt.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #define SIZE_640x480 307200 #define SIZE_352x352 123904 #define SIZE_416x416 173056 #define SKIP_LINES 50 #define X_OFFSET 40 // This parameter will remove the bios distance of Front and IR Cam. FILE *pFile1, *pFile2, *pFile3; // File1 = front, File2 = IR long lSize1, lSize2; char *buffer1, *buffer2; size_t result; char *file1_str; char *file2_str; int front_width, front_height, front_block_x, front_block_y; int ir_width, ir_height, ir_block_x, ir_block_y; unsigned int pixel_value; int valid_count = 0; int skip_pixels; bool front_block_found = 0, ir_block_found = 0; int criteria_x, criteria_y; char log_buf[250] = { 0 }; bool check_result; int version = 20170927; int main(int argc, char *argv[]) { if (argc < 5) { printf("Please follow format: calc_ir_tilt file1 file2 criteria_x criteria_y\n"); return 0; } file1_str = argv[1]; file2_str = argv[2]; criteria_x = atoi(argv[3]); criteria_y = atoi(argv[4]); printf("file1=%s, file2=%s\n", file1_str, file2_str); fopen_s(&pFile1, file1_str, "rb"); if (pFile1 == NULL) { fputs("File error1", stderr); return 1; } fopen_s(&pFile2, file2_str, "rb"); if (pFile2 == NULL) { fputs("File error2", stderr); return 1; } // File open for result fopen_s(&pFile3, "result_tilt.txt", "w+"); if (pFile1 == NULL) { fputs("File Result", stderr); return 1; } // obtain file size: fseek(pFile1, 0, SEEK_END); lSize1 = ftell(pFile1); rewind(pFile1); fseek(pFile2, 0, SEEK_END); lSize2 = ftell(pFile2); rewind(pFile2); // Check the file size to decide width and height // Front Cam if (lSize1 == SIZE_640x480) { front_width = 640; front_height = 480; } else { printf("[ERROR] Abnormal Front Cam file size\n"); return 1; } if (lSize2 == SIZE_416x416) { ir_width = 416; ir_height = 416; } else if (lSize2 == SIZE_352x352) { ir_width = 352; ir_height = 352; } else { printf("[ERROR] Abnormal IR Cam file size\n"); return 1; } // allocate memory to contain the whole file: buffer1 = (char*)malloc(sizeof(char)*lSize1); if (buffer1 == NULL) { fputs("Memory1 error", stderr); return 1; } buffer2 = (char*)malloc(sizeof(char)*lSize2); if (buffer2 == NULL) { fputs("Memory2 error", stderr); return 1; } // copy the file into the buffer: result = fread(buffer1, 1, lSize1, pFile1); if (result != lSize1) { fputs("Reading1 error", stderr); return 1; } result = fread(buffer2, 1, lSize2, pFile2); if (result != lSize2) { fputs("Reading2 error", stderr); return 1; } // While loop to check the black block location. Note: skip 50 lines to prevent corner case. // Handle Front Cam First skip_pixels = SKIP_LINES * front_width; valid_count = 0; for (int i= skip_pixels; i<lSize1 - skip_pixels; i++) { pixel_value = (unsigned char) *(buffer1 + i); if (pixel_value >= 254) // Criteria is below 10 { valid_count++; printf("%x\n", pixel_value); } else { if (valid_count > 0) // Should continue 5 pixel to be highter than criteria valid_count--; } if (valid_count > 10) // The block is found. Break { front_block_y = i / front_width; front_block_x = i % front_width; printf("Front Cam block position = [%d, %d], Center pos= [%d, %d]\n", front_block_x, front_block_y, front_width/2, front_height/2); front_block_found = 1; break; } } if (front_block_found == 0) { printf("[ERROR] Front Block is not found\n"); return 1; } // IR Cama skip_pixels = SKIP_LINES * ir_width; valid_count = 0; for (int i = skip_pixels; i<lSize2 - skip_pixels; i++) { pixel_value = (unsigned char) *(buffer2 + i); if (pixel_value >= 254) // Criteria is below 10 { valid_count++; //printf("%x\n", (int) *(buffer2 + i)); } else { if (valid_count > 0) // Should continue 5 pixel to be highter than criteria valid_count--; } if (valid_count > 10) // The block is found. Break { ir_block_y = i / ir_width; ir_block_x = i % ir_width; printf("IR Cam block pos = [%d, %d]. Center pos= [%d, %d]\n", ir_block_x, ir_block_y, ir_width/2, ir_height/2); ir_block_found = 1; break; } } if (ir_block_found == 0) { printf("[ERROR] IR Block is not found\n"); return 1; } // Check the PASS/FAIL. Criteria is that the relative position between center and block should be the same in between Front and IR. int front_diff_x = front_block_x - front_width / 2; int front_diff_y = front_block_y - front_height / 2; printf("Front to center Distance = [%d, %d]\n", front_diff_x, front_diff_y); int ir_diff_x = ir_block_x - ir_width / 2; int ir_diff_y = ir_block_y - ir_height / 2; printf("IR to center Distance = [%d, %d]\n", ir_diff_x, ir_diff_y); // If diff of front or ir is larger than criteria, then fail printf("Total Distance: RGB-IR = [%d, %d]. Criteria=[%d, %d] \n", front_diff_x- ir_diff_x - X_OFFSET, front_diff_y- ir_diff_y, criteria_x, criteria_y); if (abs(front_diff_x - ir_diff_x - X_OFFSET) < criteria_x && abs(front_diff_y - ir_diff_y) < criteria_y) { printf("Result: PASS\n"); check_result = 1; } else { printf("Result: FAIL\n"); check_result = 0; } sprintf_s(log_buf, "%s \nTotal Distance: RGB-IR = [%d, %d]. Criteria=[%d, %d] \nVersion = %d", check_result? "PASS":"FAIL", front_diff_x - ir_diff_x - X_OFFSET, front_diff_y - ir_diff_y, criteria_x, criteria_y, version); //sprintf_s(log_buf, "%s", (char *) VERSION); fwrite(log_buf, 1, sizeof(log_buf), pFile3); fclose(pFile3); free(buffer1); free(buffer2); fclose(pFile1); fclose(pFile2); return 0; }
513b1016bb6a0519f8f3b3817ca4d189cc166841
5cd1fa54038c95f179a90ff330946ee50b989da3
/sources/Virologist.cpp
afc865058c9b5ff1383fa8700c8e57fea8b20bf7
[]
no_license
Oimit/PandemicGame
45d8f90dec1b5ad2d28056b7f966addd2e757c77
337220a855e915c3d3e838201bf67e4ccf547fec
refs/heads/master
2023-05-11T05:37:25.409035
2023-05-08T07:14:59
2023-05-08T07:14:59
368,257,238
0
0
null
null
null
null
UTF-8
C++
false
false
567
cpp
Virologist.cpp
#include "Board.hpp" #include "City.hpp" #include "Color.hpp" #include "Player.hpp" #include "Virologist.hpp" using namespace std; using namespace pandemic; Player &Virologist::treat(City c) { if (c != mCurrentCity && mPlayerCards.find(c) == mPlayerCards.end()) { throw invalid_argument("cann't treat city that not contain in the cards"); } if (mBoard[c] == 0) { throw invalid_argument("There are 0 infections in that city."); } Color col = mBoard.getColor(c); if (mBoard.isCured(col)) { mBoard[c] = 0; } else { mBoard[c]--; } return *this; }
fb8026b129f3287298e66fcf25e8dccedd6b205e
04dc925359249447de99d3844fdc88d531288888
/Little Girl and Maximum XOR.cpp
0a0684713ab30a0cd1ebeade9e18d849bb368c8e
[]
no_license
SamarNegm/Problem-Solving
2e09bee084cc4d9e27867906a1f437bd8d02351d
28114c1b38c49f6106b543a2cad01b386f31899a
refs/heads/master
2022-09-12T13:55:18.072549
2020-05-30T00:21:56
2020-05-30T00:21:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
366
cpp
Little Girl and Maximum XOR.cpp
#include<bits/stdc++.h> using namespace std; long long pw(long long x,long long y) { long long ans=1; while (x--) { ans*=y; } return ans; } int main() { long long x,y,i=63,c=0; cin>>x>>y; for(i;i>=0;i--) { if((x>>i)!=(y>>i)) break; c++; } cout<<pw(i+1,2)-1; return 0; }
16793cbcce1e70dae54f321a7f12f58fa3dd1172
1e21a6c0354a3b3e660e65b320e9b86af528d504
/UniEngine/src/Mesh.cpp
138fc41d28919aa54e25c471f90ca5baf7bd5675
[ "MIT" ]
permissive
wangscript007/UniEngine-deprecated
ee1182f3dc028984dd39ca0aa52d08ef97f8d988
4b899980c280ac501c3b5fa2746cf1e71cfedd28
refs/heads/master
2023-06-08T19:55:43.892728
2021-06-20T00:07:27
2021-06-20T00:07:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,234
cpp
Mesh.cpp
#include "pch.h" #include "Mesh.h" using namespace UniEngine; void Mesh::OnGui() { ImGui::Text(("Name: " + m_name).c_str()); if (ImGui::BeginPopupContextItem(m_name.c_str())) { if (ImGui::BeginMenu("Rename")) { static char newName[256]; ImGui::InputText("New name", newName, 256); if (ImGui::Button("Confirm")) m_name = std::string(newName); ImGui::EndMenu(); } ImGui::EndPopup(); } } glm::vec3 UniEngine::Mesh::GetCenter() const { return m_bound.Center(); } Bound UniEngine::Mesh::GetBound() const { return m_bound; } UniEngine::Mesh::Mesh() { m_vao = std::make_shared<GLVAO>(); m_triangleSize = 0; m_bound = Bound(); m_name = "New mesh"; } void UniEngine::Mesh::SetVertices(const unsigned& mask, std::vector<Vertex>& vertices, std::vector<unsigned>& indices, const bool& store) { if(indices.size() % 3 != 0) { Debug::Error("Triangle size wrong!"); return; } std::vector<glm::uvec3> triangles; triangles.resize(indices.size() / 3); memcpy(triangles.data(), indices.data(), indices.size() * sizeof(unsigned)); SetVertices(mask, vertices, triangles, store); } void Mesh::SetVertices(const unsigned& mask, std::vector<Vertex>& vertices, std::vector<glm::uvec3>& triangles, const bool& store) { m_mask = mask; m_triangleSize = triangles.size(); m_verticesSize = vertices.size(); if (m_verticesSize == 0) { Debug::Log("Mesh: SetVertices empty!"); return; } if (!(mask & (unsigned)VertexAttribute::Position)) { Debug::Error("No Position Data!"); return; } auto positions = std::vector<glm::vec3>(); auto normals = std::vector<glm::vec3>(); auto tangents = std::vector<glm::vec3>(); auto colors = std::vector<glm::vec4>(); auto texcoords0s = std::vector<glm::vec2>(); auto texcoords1s = std::vector<glm::vec2>(); auto texcoords2s = std::vector<glm::vec2>(); auto texcoords3s = std::vector<glm::vec2>(); auto texcoords4s = std::vector<glm::vec2>(); auto texcoords5s = std::vector<glm::vec2>(); auto texcoords6s = std::vector<glm::vec2>(); auto texcoords7s = std::vector<glm::vec2>(); #pragma region DataAllocation size_t attributeSize = 3 * sizeof(glm::vec3); if (mask & (unsigned)VertexAttribute::Color) { attributeSize += sizeof(glm::vec4); } if (mask & (unsigned)VertexAttribute::TexCoord0) { attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord1) { attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord2) { attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord3) { attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord4) { attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord5) { attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord6) { attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord7) { attributeSize += sizeof(glm::vec2); } m_vao->SetData((GLsizei)(m_verticesSize * attributeSize), nullptr, GL_STATIC_DRAW); #pragma endregion #pragma region Copy glm::vec3 minBound = vertices.at(0).m_position; glm::vec3 maxBound = vertices.at(0).m_position; for (size_t i = 0; i < m_verticesSize; i++) { auto position = vertices.at(i).m_position; minBound = glm::vec3(glm::min(minBound.x, position.x), glm::min(minBound.y, position.y), glm::min(minBound.z, position.z)); maxBound = glm::vec3(glm::max(maxBound.x, position.x), glm::max(maxBound.y, position.y), glm::max(maxBound.z, position.z)); positions.push_back(vertices.at(i).m_position); if (mask & (unsigned)VertexAttribute::Normal) { normals.push_back(vertices.at(i).m_normal); } if (mask & (unsigned)VertexAttribute::Tangent) { tangents.push_back(vertices.at(i).m_tangent); } if (mask & (unsigned)VertexAttribute::Color) { colors.push_back(vertices.at(i).m_color); } if (mask & (unsigned)VertexAttribute::TexCoord0) { texcoords0s.push_back(vertices.at(i).m_texCoords0); } if (mask & (unsigned)VertexAttribute::TexCoord1) { texcoords1s.push_back(vertices.at(i).m_texCoords1); } if (mask & (unsigned)VertexAttribute::TexCoord2) { texcoords2s.push_back(vertices.at(i).m_texCoords2); } if (mask & (unsigned)VertexAttribute::TexCoord3) { texcoords3s.push_back(vertices.at(i).m_texCoords3); } if (mask & (unsigned)VertexAttribute::TexCoord4) { texcoords4s.push_back(vertices.at(i).m_texCoords4); } if (mask & (unsigned)VertexAttribute::TexCoord5) { texcoords5s.push_back(vertices.at(i).m_texCoords5); } if (mask & (unsigned)VertexAttribute::TexCoord6) { texcoords6s.push_back(vertices.at(i).m_texCoords6); } if (mask & (unsigned)VertexAttribute::TexCoord7) { texcoords7s.push_back(vertices.at(i).m_texCoords7); } } m_bound.m_max = maxBound; m_bound.m_min = minBound; #pragma endregion #pragma region ToGPU m_vao->SubData(0, m_verticesSize * sizeof(glm::vec3), &positions[0]); if (mask & (unsigned)VertexAttribute::Normal) m_vao->SubData(m_verticesSize * sizeof(glm::vec3), m_verticesSize * sizeof(glm::vec3), &normals[0]); else { RecalculateNormal(vertices, triangles); } if (mask & (unsigned)VertexAttribute::Tangent) { m_vao->SubData(m_verticesSize * 2 * sizeof(glm::vec3), m_verticesSize * sizeof(glm::vec3), &tangents[0]); } else { RecalculateTangent(vertices, triangles); } attributeSize = 3 * sizeof(glm::vec3); if (mask & (unsigned)VertexAttribute::Color) { m_vao->SubData(m_verticesSize * attributeSize, m_verticesSize * sizeof(glm::vec4), &colors[0]); attributeSize += sizeof(glm::vec4); } if (mask & (unsigned)VertexAttribute::TexCoord0) { m_vao->SubData(m_verticesSize * attributeSize, m_verticesSize * sizeof(glm::vec2), &texcoords0s[0]); attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord1) { m_vao->SubData(m_verticesSize * attributeSize, m_verticesSize * sizeof(glm::vec2), &texcoords1s[0]); attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord2) { m_vao->SubData(m_verticesSize * attributeSize, m_verticesSize * sizeof(glm::vec2), &texcoords2s[0]); attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord3) { m_vao->SubData(m_verticesSize * attributeSize, m_verticesSize * sizeof(glm::vec2), &texcoords3s[0]); attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord4) { m_vao->SubData(m_verticesSize * attributeSize, m_verticesSize * sizeof(glm::vec2), &texcoords4s[0]); attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord5) { m_vao->SubData(m_verticesSize * attributeSize, m_verticesSize * sizeof(glm::vec2), &texcoords5s[0]); attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord6) { m_vao->SubData(m_verticesSize * attributeSize, m_verticesSize * sizeof(glm::vec2), &texcoords6s[0]); attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord7) { m_vao->SubData(m_verticesSize * attributeSize, m_verticesSize * sizeof(glm::vec2), &texcoords7s[0]); attributeSize += sizeof(glm::vec2); } #pragma endregion #pragma region AttributePointer m_vao->EnableAttributeArray(0); m_vao->SetAttributePointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), 0); m_vao->EnableAttributeArray(1); m_vao->SetAttributePointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), (void*)(sizeof(glm::vec3) * m_verticesSize)); m_vao->EnableAttributeArray(2); m_vao->SetAttributePointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), (void*)(2 * sizeof(glm::vec3) * m_verticesSize)); attributeSize = 3 * sizeof(glm::vec3); if (mask & (unsigned)VertexAttribute::Color) { m_vao->EnableAttributeArray(3); m_vao->SetAttributePointer(3, 4, GL_FLOAT, GL_FALSE, sizeof(glm::vec4), (void*)(attributeSize * m_verticesSize)); attributeSize += sizeof(glm::vec4); } if (mask & (unsigned)VertexAttribute::TexCoord0) { m_vao->EnableAttributeArray(4); m_vao->SetAttributePointer(4, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), (void*)(attributeSize * m_verticesSize)); attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord1) { m_vao->EnableAttributeArray(5); m_vao->SetAttributePointer(5, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), (void*)(attributeSize * m_verticesSize)); attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord2) { m_vao->EnableAttributeArray(6); m_vao->SetAttributePointer(6, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), (void*)(attributeSize * m_verticesSize)); attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord3) { m_vao->EnableAttributeArray(7); m_vao->SetAttributePointer(7, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), (void*)(attributeSize * m_verticesSize)); attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord4) { m_vao->EnableAttributeArray(8); m_vao->SetAttributePointer(8, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), (void*)(attributeSize * m_verticesSize)); attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord5) { m_vao->EnableAttributeArray(9); m_vao->SetAttributePointer(9, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), (void*)(attributeSize * m_verticesSize)); attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord6) { m_vao->EnableAttributeArray(10); m_vao->SetAttributePointer(10, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), (void*)(attributeSize * m_verticesSize)); attributeSize += sizeof(glm::vec2); } if (mask & (unsigned)VertexAttribute::TexCoord7) { m_vao->EnableAttributeArray(11); m_vao->SetAttributePointer(11, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), (void*)(attributeSize * m_verticesSize)); attributeSize += sizeof(glm::vec2); } #pragma endregion m_vao->Ebo()->SetData((GLsizei)m_triangleSize * sizeof(glm::uvec3), triangles.data(), GL_STATIC_DRAW); m_localStored = store; if (store) { m_vertices.clear(); m_indices.clear(); m_vertices.insert(m_vertices.begin(), vertices.begin(), vertices.end()); m_indices.insert(m_indices.begin(), triangles.begin(), triangles.end()); } } size_t UniEngine::Mesh::GetVerticesAmount() const { return m_triangleSize; } size_t UniEngine::Mesh::GetTriangleAmount() const { return m_triangleSize; } void UniEngine::Mesh::RecalculateNormal(std::vector<Vertex>& vertices, std::vector<glm::uvec3>& indices) const { std::vector<std::vector<glm::vec3>> normalLists = std::vector<std::vector<glm::vec3>>(); auto size = vertices.size(); for (auto i = 0; i < size; i++) { normalLists.push_back(std::vector<glm::vec3>()); } for (size_t i = 0; i < m_triangleSize; i++) { const auto i1 = indices[i].x; const auto i2 = indices[i].y; const auto i3 = indices[i].z; auto v1 = vertices[i1].m_position; auto v2 = vertices[i2].m_position; auto v3 = vertices[i3].m_position; auto normal = glm::normalize(glm::cross(v1 - v2, v1 - v3)); normalLists[i1].push_back(normal); normalLists[i2].push_back(normal); normalLists[i3].push_back(normal); } std::vector<glm::vec3> normals = std::vector<glm::vec3>(); for (auto i = 0; i < size; i++) { auto normal = glm::vec3(0.0f); for (auto j : normalLists[i]) { normal += j; } normals.push_back(glm::normalize(normal)); vertices[i].m_normal = normal; } m_vao->SubData(size * sizeof(glm::vec3), size * sizeof(glm::vec3), &normals[0]); } void UniEngine::Mesh::RecalculateTangent(std::vector<Vertex>& vertices, std::vector<glm::uvec3>& indices) const { std::vector<std::vector<glm::vec3>> tangentLists = std::vector<std::vector<glm::vec3>>(); auto size = vertices.size(); for (auto i = 0; i < size; i++) { tangentLists.push_back(std::vector<glm::vec3>()); } for (size_t i = 0; i < m_triangleSize; i++) { const auto i1 = indices[i].x; const auto i2 = indices[i].y; const auto i3 = indices[i].z; auto& v1 = vertices[i1]; auto& v2 = vertices[i2]; auto& v3 = vertices[i3]; auto p1 = v1.m_position; auto p2 = v2.m_position; auto p3 = v3.m_position; auto uv1 = v1.m_texCoords0; auto uv2 = v2.m_texCoords0; auto uv3 = v3.m_texCoords0; auto e21 = p2 - p1; auto d21 = uv2 - uv1; auto e31 = p3 - p1; auto d31 = uv3 - uv1; float f = 1.0f / (d21.x * d31.y - d31.x * d21.y); auto tangent = f * glm::vec3( d31.y * e21.x - d21.y * e31.x, d31.y * e21.y - d21.y * e31.y, d31.y * e21.z - d21.y * e31.z); tangentLists[i1].push_back(tangent); tangentLists[i2].push_back(tangent); tangentLists[i3].push_back(tangent); } std::vector<glm::vec3> tangents = std::vector<glm::vec3>(); for (auto i = 0; i < size; i++) { auto tangent = glm::vec3(0.0f); for (auto j : tangentLists[i]) { tangent += j; } tangents.push_back(glm::normalize(tangent)); vertices[i].m_tangent = tangent; } m_vao->SubData(size * 2 * sizeof(glm::vec3), size * sizeof(glm::vec3), &tangents[0]); } std::shared_ptr<GLVAO> UniEngine::Mesh::Vao() const { return m_vao; } void UniEngine::Mesh::Enable() const { m_vao->Bind(); } std::vector<Vertex>& Mesh::UnsafeGetVertices() { return m_vertices; } std::vector<glm::uvec3>& Mesh::UnsafeGetTriangles() { return m_indices; }
04f598543519119f1d8a640bc9d960860853d851
317c048043d83a122ed8da045aaa663610a12d4a
/Exam 2 Practice Problems/Pointers_Problem1.cpp
216fe6ce7679dad69200606fbdea62737477d01c
[]
no_license
brettbar/CPSC122
c92122ae14f28d1542e64999f879d1f25a550e7c
a15af1927891700961314f5b7b757dcdaeb72320
refs/heads/master
2021-10-16T00:12:53.135615
2019-02-07T08:23:55
2019-02-07T08:23:55
169,539,994
0
0
null
null
null
null
UTF-8
C++
false
false
342
cpp
Pointers_Problem1.cpp
#include <iostream> #include <cstdlib> using namespace std; int* dynamicArrayAllocate(int n) { int* arr; arr = new int[n]; for (int i = 0; i<= n; i++) { arr[i] = rand() % 10; } return arr; } int main() { int* ptr = dynamicArrayAllocate(5); for (int i = 0; i <= 5; i++) { cout << ptr[i] << " "; } cout << endl; return 0; }
1c2c9f024cdefd9d2b3d427b77c83a5acc5d8846
c56e37397a7ef14ce0c00ace0084a62148ced993
/src/InputManager.cpp
fb76e48b1d906f5921936c37a44bb08167b87f07
[ "MIT" ]
permissive
fide/EmulationStation
878be25e4e54062f0ed7cc64f497d33c6a665844
8a2309378119efb44e9d31f5d079fafad00ef4ff
refs/heads/master
2020-12-03T00:35:17.185607
2014-07-15T18:39:58
2014-07-15T18:39:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,736
cpp
InputManager.cpp
#include "InputManager.h" #include "InputConfig.h" #include "Window.h" #include "Log.h" #include "pugiXML/pugixml.hpp" #include <boost/filesystem.hpp> #include "platform.h" #if defined(WIN32) || defined(_WIN32) #include <Windows.h> #endif namespace fs = boost::filesystem; //----- InputDevice ---------------------------------------------------------------------------- InputDevice::InputDevice(const std::string & deviceName, unsigned long vendorId, unsigned long productId) : name(deviceName), vendor(vendorId), product(productId) { } bool InputDevice::operator==(const InputDevice & b) const { return (name == b.name && vendor == b.vendor && product == b.product); } //----- InputManager --------------------------------------------------------------------------- InputManager::InputManager(Window* window) : mWindow(window), mJoysticks(NULL), mInputConfigs(NULL), mKeyboardInputConfig(NULL), mPrevAxisValues(NULL), mNumJoysticks(0), mNumPlayers(0), devicePollingTimer(NULL) { } InputManager::~InputManager() { deinit(); } std::vector<InputDevice> InputManager::getInputDevices() const { std::vector<InputDevice> currentDevices; //retrieve all input devices from system #if defined (__APPLE__) #error TODO: Not implemented for MacOS yet!!! #elif defined(__linux__) //open linux input devices file system const std::string inputPath("/dev/input"); fs::directory_iterator dirIt(inputPath); while (dirIt != fs::directory_iterator()) { //get directory entry std::string deviceName = (*dirIt).path().string(); //remove parent path deviceName.erase(0, inputPath.length() + 1); //check if it start with "js" if (deviceName.length() >= 3 && deviceName.find("js") == 0) { //looks like a joystick. add to devices. currentDevices.push_back(InputDevice(deviceName, 0, 0)); } ++dirIt; } //or dump /proc/bus/input/devices anbd search for a Handler=..."js"... entry #elif defined(WIN32) || defined(_WIN32) RAWINPUTDEVICELIST * deviceList = nullptr; UINT nrOfDevices = 0; //get number of input devices if (GetRawInputDeviceList(deviceList, &nrOfDevices, sizeof(RAWINPUTDEVICELIST)) != -1 && nrOfDevices > 0) { //get list of input devices deviceList = new RAWINPUTDEVICELIST[nrOfDevices]; if (GetRawInputDeviceList(deviceList, &nrOfDevices, sizeof(RAWINPUTDEVICELIST)) != -1) { //loop through input devices for (unsigned int i = 0; i < nrOfDevices; i++) { //get device name char * rawName = new char[2048]; UINT rawNameSize = 2047; GetRawInputDeviceInfo(deviceList[i].hDevice, RIDI_DEVICENAME, (void *)rawName, &rawNameSize); //null-terminate string rawName[rawNameSize] = '\0'; //convert to string std::string deviceName = rawName; delete [] rawName; //get deviceType RID_DEVICE_INFO deviceInfo; UINT deviceInfoSize = sizeof(RID_DEVICE_INFO); GetRawInputDeviceInfo(deviceList[i].hDevice, RIDI_DEVICEINFO, (void *)&deviceInfo, &deviceInfoSize); //check if it is a HID. we ignore keyboards and mice... if (deviceInfo.dwType == RIM_TYPEHID) { //check if the vendor/product already exists in list. yes. could be more elegant... std::vector<InputDevice>::const_iterator cdIt = currentDevices.cbegin(); while (cdIt != currentDevices.cend()) { if (cdIt->name == deviceName && cdIt->product == deviceInfo.hid.dwProductId && cdIt->vendor == deviceInfo.hid.dwVendorId) { //device already there break; } ++cdIt; } //was the device found? if (cdIt == currentDevices.cend()) { //no. add it. currentDevices.push_back(InputDevice(deviceName, deviceInfo.hid.dwProductId, deviceInfo.hid.dwVendorId)); } } } } delete [] deviceList; } #endif return currentDevices; } Uint32 InputManager::devicePollingCallback(Uint32 interval, void* param) { //this thing my be running in a different thread, so we're not allowed to call //any functions or change/allocate/delete stuff, but can send a user event SDL_Event event; event.user.type = SDL_USEREVENT; event.user.code = SDL_USEREVENT_POLLDEVICES; event.user.data1 = nullptr; event.user.data2 = nullptr; if (SDL_PushEvent(&event) != 0) { LOG(LogError) << "InputManager::devicePollingCallback - SDL event queue is full!"; } return interval; } void InputManager::init() { if(mJoysticks != NULL) deinit(); //get current input devices from system inputDevices = getInputDevices(); SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_TIMER); mNumJoysticks = SDL_NumJoysticks(); mJoysticks = new SDL_Joystick*[mNumJoysticks]; mInputConfigs = new InputConfig*[mNumJoysticks]; mPrevAxisValues = new std::map<int, int>[mNumJoysticks]; for(int i = 0; i < mNumJoysticks; i++) { mJoysticks[i] = SDL_JoystickOpen(i); mInputConfigs[i] = new InputConfig(i); for(int k = 0; k < SDL_JoystickNumAxes(mJoysticks[i]); k++) { mPrevAxisValues[i][k] = 0; } } mKeyboardInputConfig = new InputConfig(DEVICE_KEYBOARD); SDL_JoystickEventState(SDL_ENABLE); //start timer for input device polling startPolling(); loadConfig(); } void InputManager::startPolling() { if(devicePollingTimer != NULL) return; devicePollingTimer = SDL_AddTimer(POLLING_INTERVAL, devicePollingCallback, (void *)this); } void InputManager::stopPolling() { if(devicePollingTimer == NULL) return; SDL_RemoveTimer(devicePollingTimer); devicePollingTimer = NULL; } void InputManager::deinit() { stopPolling(); SDL_JoystickEventState(SDL_DISABLE); if(!SDL_WasInit(SDL_INIT_JOYSTICK)) return; if(mJoysticks != NULL) { for(int i = 0; i < mNumJoysticks; i++) { SDL_JoystickClose(mJoysticks[i]); delete mInputConfigs[i]; } delete[] mInputConfigs; mInputConfigs = NULL; delete[] mJoysticks; mJoysticks = NULL; delete mKeyboardInputConfig; mKeyboardInputConfig = NULL; delete[] mPrevAxisValues; mPrevAxisValues = NULL; } SDL_QuitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_TIMER); inputDevices.clear(); } int InputManager::getNumJoysticks() { return mNumJoysticks; } int InputManager::getButtonCountByDevice(int id) { if(id == DEVICE_KEYBOARD) return 120; //it's a lot, okay. else return SDL_JoystickNumButtons(mJoysticks[id]); } int InputManager::getNumPlayers() { return mNumPlayers; } void InputManager::setNumPlayers(int num) { mNumPlayers = num; } InputConfig* InputManager::getInputConfigByDevice(int device) { if(device == DEVICE_KEYBOARD) return mKeyboardInputConfig; else return mInputConfigs[device]; } InputConfig* InputManager::getInputConfigByPlayer(int player) { if(mKeyboardInputConfig->getPlayerNum() == player) return mKeyboardInputConfig; for(int i = 0; i < mNumJoysticks; i++) { if(mInputConfigs[i]->getPlayerNum() == player) return mInputConfigs[i]; } LOG(LogError) << "Could not find input config for player number " << player << "!"; return NULL; } bool InputManager::parseEvent(const SDL_Event& ev) { bool causedEvent = false; switch(ev.type) { case SDL_JOYAXISMOTION: //if it switched boundaries if((abs(ev.jaxis.value) > DEADZONE) != (abs(mPrevAxisValues[ev.jaxis.which][ev.jaxis.axis]) > DEADZONE)) { int normValue; if(abs(ev.jaxis.value) <= DEADZONE) normValue = 0; else if(ev.jaxis.value > 0) normValue = 1; else normValue = -1; mWindow->input(getInputConfigByDevice(ev.jaxis.which), Input(ev.jaxis.which, TYPE_AXIS, ev.jaxis.axis, normValue, false)); causedEvent = true; } mPrevAxisValues[ev.jaxis.which][ev.jaxis.axis] = ev.jaxis.value; return causedEvent; case SDL_JOYBUTTONDOWN: case SDL_JOYBUTTONUP: mWindow->input(getInputConfigByDevice(ev.jbutton.which), Input(ev.jbutton.which, TYPE_BUTTON, ev.jbutton.button, ev.jbutton.state == SDL_PRESSED, false)); return true; case SDL_JOYHATMOTION: mWindow->input(getInputConfigByDevice(ev.jhat.which), Input(ev.jhat.which, TYPE_HAT, ev.jhat.hat, ev.jhat.value, false)); return true; case SDL_KEYDOWN: if(ev.key.keysym.sym == SDLK_F4) { SDL_Event* quit = new SDL_Event(); quit->type = SDL_QUIT; SDL_PushEvent(quit); return false; } mWindow->input(getInputConfigByDevice(DEVICE_KEYBOARD), Input(DEVICE_KEYBOARD, TYPE_KEY, ev.key.keysym.sym, 1, false)); return true; case SDL_KEYUP: mWindow->input(getInputConfigByDevice(DEVICE_KEYBOARD), Input(DEVICE_KEYBOARD, TYPE_KEY, ev.key.keysym.sym, 0, false)); return true; case SDL_USEREVENT: if (ev.user.code == SDL_USEREVENT_POLLDEVICES) { //poll joystick / HID again std::vector<InputDevice> currentDevices = getInputDevices(); //compare device lists to see if devices were added/deleted if (currentDevices != inputDevices) { LOG(LogInfo) << "Device configuration changed!"; inputDevices = currentDevices; //deinit and reinit InputManager deinit(); init(); } return true; } } return false; } void InputManager::loadConfig() { if(!mJoysticks) { LOG(LogError) << "ERROR - cannot load InputManager config without being initialized!"; } std::string path = getConfigPath(); if(!fs::exists(path)) return; pugi::xml_document doc; pugi::xml_parse_result res = doc.load_file(path.c_str()); if(!res) { LOG(LogError) << "Error loading input config: " << res.description(); return; } mNumPlayers = 0; bool* configuredDevice = new bool[mNumJoysticks]; for(int i = 0; i < mNumJoysticks; i++) { mInputConfigs[i]->setPlayerNum(-1); configuredDevice[i] = false; } pugi::xml_node root = doc.child("inputList"); for(pugi::xml_node node = root.child("inputConfig"); node; node = node.next_sibling("inputConfig")) { std::string type = node.attribute("type").as_string(); if(type == "keyboard") { getInputConfigByDevice(DEVICE_KEYBOARD)->loadFromXML(node, mNumPlayers); mNumPlayers++; }else if(type == "joystick") { bool found = false; std::string devName = node.attribute("deviceName").as_string(); for(int i = 0; i < mNumJoysticks; i++) { if(!configuredDevice[i] && SDL_JoystickName(i) == devName) { mInputConfigs[i]->loadFromXML(node, mNumPlayers); mNumPlayers++; found = true; configuredDevice[i] = true; break; } } if(!found) { LOG(LogWarning) << "Could not find unconfigured joystick named \"" << devName << "\"! Skipping it.\n"; continue; } }else{ LOG(LogWarning) << "Device type \"" << type << "\" unknown!\n"; } } delete[] configuredDevice; if(mNumPlayers == 0) { LOG(LogInfo) << "No input configs loaded. Loading default keyboard config."; loadDefaultConfig(); } LOG(LogInfo) << "Loaded InputConfig data for " << getNumPlayers() << " devices."; } //used in an "emergency" where no configs could be loaded from the inputmanager config file //allows the user to select to reconfigure in menus if this happens without having to delete es_input.cfg manually void InputManager::loadDefaultConfig() { InputConfig* cfg = getInputConfigByDevice(DEVICE_KEYBOARD); mNumPlayers++; cfg->setPlayerNum(0); cfg->mapInput("up", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_UP, 1, true)); cfg->mapInput("down", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_DOWN, 1, true)); cfg->mapInput("left", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_LEFT, 1, true)); cfg->mapInput("right", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_RIGHT, 1, true)); cfg->mapInput("a", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_RETURN, 1, true)); cfg->mapInput("b", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_ESCAPE, 1, true)); cfg->mapInput("menu", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_F1, 1, true)); cfg->mapInput("select", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_F2, 1, true)); cfg->mapInput("pageup", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_RIGHTBRACKET, 1, true)); cfg->mapInput("pagedown", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_LEFTBRACKET, 1, true)); cfg->mapInput("mastervolup", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_PLUS, 1, true)); cfg->mapInput("mastervoldown", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_MINUS, 1, true)); cfg->mapInput("sortordernext", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_F7, 1, true)); cfg->mapInput("sortorderprevious", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_F8, 1, true)); } void InputManager::writeConfig() { if(!mJoysticks) { LOG(LogError) << "ERROR - cannot write config without being initialized!"; return; } std::string path = getConfigPath(); pugi::xml_document doc; pugi::xml_node root = doc.append_child("inputList"); mKeyboardInputConfig->writeToXML(root); for(int i = 0; i < mNumJoysticks; i++) { mInputConfigs[i]->writeToXML(root); } doc.save_file(path.c_str()); } std::string InputManager::getConfigPath() { std::string path = getHomePath(); path += "/.emulationstation/es_input.cfg"; return path; }
5a9a4985609918325965b7255fe523569fa26171
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/admin/wmi/wbem/sdk/activex/controls/msgdlg/dlgsingleview.cpp
484e037b33f4a41b793b0f73ed8cecc1226b8382
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
527
cpp
dlgsingleview.cpp
// Copyright (c) 1997-2001 Microsoft Corporation, All Rights Reserved #include "precomp.h" #include "wbemidl.h" #include "singleview.h" #include "dlgsingleview.h" IMPLEMENT_DYNCREATE(CDlgSingleView,CSingleView) BEGIN_MESSAGE_MAP(CDlgSingleView,CSingleView) //{{AFX_MSG_MAP(CBanner) ON_WM_CREATE() //}}AFX_MSG_MAP END_MESSAGE_MAP() int CDlgSingleView::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CWnd::OnCreate(lpCreateStruct) == -1) return -1; //CSingleView::SelectObjectByPointer(m_pErrorObject); return 0; }
c9a5c53ed376933df051deb9172d6b324d5316ba
268739a6efa958cda00192ab31d6d602468ed294
/day_04/04_security_through_obscurity.cpp
cc0415244e2248d574770c4612cb1e7abb5a048e
[]
no_license
Gusten/adventofcode2016
354dc9d06aa872692872a47d8387e3c4ed06b81b
b35df8c47a9bd4465142fafd7baf5e5632ff1a29
refs/heads/master
2020-06-12T21:28:52.305528
2016-12-04T20:46:25
2016-12-04T20:46:25
75,506,950
0
0
null
null
null
null
UTF-8
C++
false
false
979
cpp
04_security_through_obscurity.cpp
#include "04_security_through_obscurity.h" #include <string> #include <vector> #include <fstream> #include <iostream> namespace { // Split a string based on a delimiter and push them into the provided vector void split_by_and_remove_empty(const std::string &input, const std::string &delim, std::vector<std::string> &elems) { size_t index = 0; size_t next_delim_index; while ((next_delim_index = input.find(delim, index)) != std::string::npos) { std::string element = input.substr(index, next_delim_index - index); if (!element.empty()) { elems.push_back(input.substr(index, next_delim_index - index)); } index += next_delim_index - index + delim.size(); } elems.push_back(input.substr(index)); } } void Day04::solve() { std::ifstream input("day_04/input.txt"); if (input.is_open()) { std::string line; std::vector<std::string> line_elements; while (getline(input, line)) { split_by_and_remove_empty(line, "-", line_elements); } } }
00b8aa89c0cf54f6799d59ccb4a940d339345abd
a4c141f6bdac5c155339b8b0c00c7dc73a6f77ee
/Engine/Android/jni/Edit.cpp
5596d6a0abd3b32b38436f2469af3b863b2667b3
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-permissive" ]
permissive
chenfarong/EsenthelEngine
0b0f6df579d4fb82255c62d1c59ba1ba0b5a0e05
8a99f33e2c23d600c44d8c05ae7e58ab78ba307a
refs/heads/master
2023-07-11T10:01:46.797243
2021-06-24T08:26:36
2021-06-24T08:26:36
395,918,366
1
0
null
2021-08-14T06:46:16
2021-08-14T06:46:15
null
UTF-8
C++
false
false
221
cpp
Edit.cpp
#include "../../Source/Edit/Save Changes.cpp" #include "../../Source/Edit/Undo.cpp" #include "../../Source/Edit/Viewport4.cpp" #include "../../Source/Edit/Version.cpp" #include "../../Source/Edit/Editor Interface.cpp"
348a8dbf473bad980af15934aa1c8796fd538457
fded81a37e53d5fc31cacb9a0be86377825757b3
/buhg_g/pdokuosw.cpp
8c7fe63acb0a6ec6415f6a8d2a6f80a1d1bd11fa
[]
no_license
iceblinux/iceBw_GTK
7bf28cba9d994e95bab0f5040fea1a54a477b953
a4f76e1fee29baa7dce79e8a4a309ae98ba504c2
refs/heads/main
2023-04-02T21:45:49.500587
2021-04-12T03:51:53
2021-04-12T03:51:53
356,744,886
0
0
null
null
null
null
UTF-8
C++
false
false
5,820
cpp
pdokuosw.cpp
/*$Id: pdokuosw.c,v 1.7 2013/08/13 06:09:48 sasa Exp $*/ /*12.07.2015 12.01.2009 Белых А.И. pdokuosw.c Просмотр документа из подсистемы "Учёт основных средств" */ #include <errno.h> #include "buhg_g.h" extern double okrcn; /*Округление цены*/ extern SQL_baza bd; int pdokuosw(const char *datadok,const char *nomdok,int tipz,GtkWidget *wpredok) { short dd,md,gd; char strsql[512]; int kolstr=0; SQL_str row,row1; class SQLCURSOR cur,cur1; FILE *ff; char imaf[56]; class iceb_u_str naim(""); iceb_u_rsdat(&dd,&md,&gd,datadok,1); sprintf(strsql,"select * from Uosdok where datd='%04d-%02d-%02d' and nomd='%s' and tipz=%d", gd,md,dd,nomdok,tipz); if(iceb_sql_readkey(strsql,&row,&cur,wpredok) != 1) { sprintf(strsql,"%s\n%d.%d.%d %s %d",gettext("Не найден документ!"), dd,md,gd,nomdok,tipz); iceb_menu_soob(strsql,wpredok); return(1); } sprintf(imaf,"pdokuos%d.lst",getpid()); if((ff = fopen(imaf,"w")) == NULL) { iceb_er_op_fil(imaf,"",errno,wpredok); return(1); } fprintf(ff,"%s\n",gettext("Учёт основных средств")); if(tipz == 1) fprintf(ff,"%s\n",gettext("Приход")); if(tipz == 2) fprintf(ff,"%s\n",gettext("Расход")); fprintf(ff,"%s:%d.%d.%d %s:%s\n", gettext("Дата документа"),dd,md,gd, gettext("Номер документа"),nomdok); naim.new_plus(""); sprintf(strsql,"select naikon from Kontragent where kodkon='%s'",row[3]); if(iceb_sql_readkey(strsql,&row1,&cur1,wpredok) == 1) naim.new_plus(row1[0]); fprintf(ff,"%s:%s %s\n",gettext("Контрагент"),row[3],naim.ravno()); naim.new_plus(""); if(tipz == 1) sprintf(strsql,"select naik from Uospri where kod='%s'",row[2]); if(tipz == 2) sprintf(strsql,"select naik from Uosras where kod='%s'",row[2]); if(iceb_sql_readkey(strsql,&row1,&cur1,wpredok) == 1) naim.new_plus(row1[0]); fprintf(ff,"%s:%s %s\n",gettext("Код операции"),row[2],naim.ravno()); fprintf(ff,"%s:%s\n",gettext("Записал"),iceb_kszap(row[13],wpredok)); fprintf(ff,"%s:%s\n",gettext("Дата записи"),iceb_u_vremzap(row[14])); if(atoi(row[25]) == 0) fprintf(ff,"%s\n",gettext("Документ неоплачен")); if(atoi(row[25]) == 1) fprintf(ff,"%s\n",gettext("Документ оплачен")); naim.new_plus(""); sprintf(strsql,"select naik from Uospod where kod=%s",row[5]); if(iceb_sql_readkey(strsql,&row1,&cur1,wpredok) == 1) naim.new_plus(row1[0]); fprintf(ff,"%s:%s %s\n",gettext("Подразделение"),row[5],naim.ravno()); naim.new_plus(""); sprintf(strsql,"select naik from Uosol where kod=%s",row[6]); if(iceb_sql_readkey(strsql,&row1,&cur1,wpredok) == 1) naim.new_plus(row1[0]); fprintf(ff,"%s:%s %s\n",gettext("Материально-ответственный"),row[6],naim.ravno()); fprintf(ff,"%s:%s\n",gettext("Основание"),row[12]); if(row[15][0] != '\0') { fprintf(ff,"%s:%s ",gettext("Доверенность"),row[15]); fprintf(ff,"%s:%s\n",gettext("Дата"),iceb_u_datzap(row[16])); } if(row[20][0] != '\0') fprintf(ff,"%s:%s\n",gettext("Через кого"),row[20]); if(row[17][0] != '\0') { naim.new_plus(""); sprintf(strsql,"select naik from Foroplat where kod='%s'",row[17]); if(iceb_sql_readkey(strsql,&row1,&cur1,wpredok) == 1) naim.new_plus(row1[0]); fprintf(ff,"%s:%s %s\n",gettext("Форма оплаты"),row[17],naim.ravno()); } if(row[18][0] != '0') fprintf(ff,"%s:%s\n",gettext("Дата получения налоговой накладной"),iceb_u_datzap(row[18])); if(row[19][0] != '0') fprintf(ff,"%s:%s\n",gettext("Номер налоговой накладной"),row[19]); if(row[21][0] != '0') fprintf(ff,"%s:%s\n",gettext("Дата оплаты"),iceb_u_datzap(row[21])); /******** int mnds=atoi(row[22]); float pnds=atof(row[23]); **********/ fprintf(ff,"\ --------------------------------------------------------------------------------------\n"); fprintf(ff,"\ Инвентарн.| Наименование | Налоговый учёт |Бухгалтерский учёт |\n\ номер | |Бал.стоим.| Износ |Бал.стоим.| Износ |\n"); fprintf(ff,"\ --------------------------------------------------------------------------------------\n"); sprintf(strsql,"select innom,bs,iz,ktoz,vrem,bsby,izby from Uosdok1 where datd='%04d-%02d-%02d' and nomd='%s'",gd,md,dd,nomdok); if((kolstr=cur.make_cursor(&bd,strsql)) < 0) { iceb_msql_error(&bd,gettext("Ошибка создания курсора !"),strsql,wpredok); } double itogo[4]; memset(itogo,'\0',sizeof(itogo)); while(cur.read_cursor(&row) != 0) { naim.new_plus(""); sprintf(strsql,"select naim from Uosin where innom=%s",row[0]); if(iceb_sql_readkey(strsql,&row1,&cur1,wpredok) == 1) naim.new_plus(row1[0]); fprintf(ff,"%10s %-*.*s %10s %10s %10s %10s %s %s\n", row[0], iceb_u_kolbait(30,naim.ravno()), iceb_u_kolbait(30,naim.ravno()), naim.ravno(), row[1],row[2],row[5],row[6], iceb_u_vremzap(row[4]), iceb_kszap(row[3],wpredok)); if(iceb_u_strlen(naim.ravno()) > 30) fprintf(ff,"%10s %s\n","",iceb_u_adrsimv(30,naim.ravno())); itogo[0]+=atof(row[1]); itogo[1]+=atof(row[2]); itogo[2]+=atof(row[5]); itogo[3]+=atof(row[6]); } fprintf(ff,"\ --------------------------------------------------------------------------------------\n"); fprintf(ff,"%*s:%10.2f %10.2f %10.2f %10.2f\n", iceb_u_kolbait(41,gettext("Итого")), gettext("Итого"), itogo[0],itogo[1],itogo[2],itogo[3]); iceb_podpis(ff,wpredok); fclose(ff); iceb_prosf(imaf,wpredok); sleep(1); /*для того чтобы не удалился файл перед просмотром*/ unlink(imaf); return(0); }
34f241ebbdfaead61ead73b65f45b0ee45137676
e9f3369247da3435cd63f2d67aa95c890912255c
/problem131.cpp
2cf672737cfb2ebf80fd00d5ac856e739472e560
[]
no_license
panthitesh6410/problem-solving-C-
27b31a141669b91eb36709f0126be05f241dfb13
24b72fc795b7b5a44e22e5f6ca9faad462a097fb
refs/heads/master
2021-11-15T21:52:33.523503
2021-10-17T16:20:58
2021-10-17T16:20:58
248,523,681
0
0
null
null
null
null
UTF-8
C++
false
false
1,119
cpp
problem131.cpp
// Codechef April Lunchtime 2020 Div.2 : // Another Birthday Present : // #include<iostream> // using namespace std; // bool is_sorted(int arr[], int n) // { // int count=0; // for(int i=0;i<n-1;i++) // { // if(arr[i] < arr[i+1]) // count++; // } // if(count == n-1) // return true; // else // return false; // } // int main() // { // int t; // cin>>t; // for(int i=1;i<=t;i++) // { // int n, k, flag=0; // cin>>n>>k; // int arr[n]; // for(int j=0;j<n;j++) // cin>>arr[j]; // for(int j=0;j<n-1;j++) // { // if(is_sorted(arr, n)) // flag = 1; // else // { // if(arr[j] > arr[j+1]) // { // int temp = arr[j]; // arr[j] = arr[j+k]; // arr[j+k] = temp; // } // } // } // if(flag == 1) // cout<<"yes"<<endl; // else // cout<<"no"<<endl; // } // return 0; // }
ea0372516329594d650f20d4fded80631cd82027
d1cc319aeaab19e3a7aa6b40c9e08055f2b92858
/src/patchdll/Scan.cpp
bc2e255864b7e9d6f42a7c6ea6f1f7ad66e7804f
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
Warpten/hzdnptr
1a291f944b0ab23a00e59e8b6f7a9d884f7c2b23
0f34e87c67ed205da230f68d5dbf9a2245faf8c0
refs/heads/master
2022-12-06T18:26:43.731457
2020-09-08T13:14:20
2020-09-08T13:14:20
286,248,585
11
0
null
null
null
null
UTF-8
C++
false
false
391
cpp
Scan.cpp
#include "Scan.hpp" namespace Memory { DWORD Protect(uintptr_t offset, DWORD pageProtection) { MEMORY_BASIC_INFORMATION mbi; VirtualQuery(reinterpret_cast<LPVOID>(offset), &mbi, sizeof(mbi)); DWORD oldProtection; VirtualProtect(static_cast<LPVOID>(mbi.BaseAddress), mbi.RegionSize, pageProtection, &oldProtection); return oldProtection; } }
aa126eaf26ef6c307f62dae045497794e9495aab
683a90831bb591526c6786e5f8c4a2b34852cf99
/Strings/fundamentals/stringHashing/RabinKarp.cpp
f374cdfee34915a3bdf47038a0b2a29f2f1a600e
[]
no_license
dbetm/cp-history
32a3ee0b19236a759ce0a6b9ba1b72ceb56b194d
0ceeba631525c4776c21d547e5ab101f10c4fe70
refs/heads/main
2023-04-29T19:36:31.180763
2023-04-15T18:03:19
2023-04-15T18:03:19
164,786,056
8
0
null
null
null
null
UTF-8
C++
false
false
1,615
cpp
RabinKarp.cpp
#include <bits/stdc++.h> using namespace std; void rabinKarp(string &texto, string &patron, vector<int> &ocurrencias); int main() { string texto; string patron; cout << "Escribe el texto: " << endl; getline(cin, texto); cout << "Escribe el patrón a buscar" << endl; cin >> patron; vector<int> ocurrencias; rabinKarp(texto, patron, ocurrencias); cout << "Hay ocurrencias en las posiciones: " << endl; int n = ocurrencias.size(); for (int i = 0; i < n; i++) { cout << "i: " << ocurrencias[i] << endl; } return 0; } void rabinKarp(string &texto, string &patron, vector<int> &ocurrencias) { int t = texto.size(), s = patron.size(); long long p = 31, m = 1e9 + 9; // Calcular las potencias que se necesitan int n = max(t, s); long long potencias[n]; potencias[0] = 1; for (int i = 1; i < n; i++) { potencias[i] = (potencias[i-1] * p) % m; } // Calcular el hash del patrón s long long hashPatron = 0; for (int i = 0; i < s; i++) { hashPatron = (hashPatron + (patron[i] - 'a' + 1) * potencias[i]) % m; } // Calcular los hashes para cada prefijo del texto vector<long long> hashesTxt(t+1, 0); for (int i = 0; i < t; i++) { hashesTxt[i+1] = (hashesTxt[i] + (texto[i] - 'a' + 1) * potencias[i]) % m; } // Comparar long long hashActual; for (int i = 0; i < t - s + 1; i++) { hashActual = (hashesTxt[i + s] + m - hashesTxt[i]) % m; if(hashActual == (hashPatron * potencias[i] % m)) { ocurrencias.push_back(i); } } }
440dc139c9d66701df662236df80afaf9ce3a020
f1bd4d38d8a279163f472784c1ead12920b70be2
/xr_3da/xrGame/stalker_property_evaluator_alife.cpp
e5ffca2f57480c3124225689d3759984834381f5
[]
no_license
YURSHAT/stk_2005
49613f4e4a9488ae5e3fd99d2b60fd9c6aca2c83
b68bbf136688d57740fd9779423459ef5cbfbdbb
refs/heads/master
2023-04-05T16:08:44.658227
2021-04-18T09:08:18
2021-04-18T18:35:59
361,129,668
1
0
null
null
null
null
UTF-8
C++
false
false
529
cpp
stalker_property_evaluator_alife.cpp
//////////////////////////////////////////////////////////////////////////// // Module : stalker_property_evaluator_alife.cpp // Created : 25.03.2004 // Modified : 25.03.2004 // Author : Dmitriy Iassenev // Description : Stalker alife property evaluator //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "stalker_property_evaluator_alife.h" CStalkerPropertyEvaluatorALife::_value_type CStalkerPropertyEvaluatorALife::evaluate () { return (!!ai().get_alife()); }
0ba7e4c0537623acf03ff4ecffad3480910c4ecd
60a45660bc61351b8b585b61fa3e63cf22c0212c
/resource/unpackresfile.cc
ec30a8965189ec00bd7381f051451f84f361d641
[]
no_license
tomazos/sf5
196cc9e8af548313734f487378da49f78ec9115c
4e6b7fc9efd182ec0defb7f4c80e09e108e00d8b
refs/heads/master
2020-04-29T03:29:54.313056
2019-09-29T19:37:54
2019-09-29T19:37:54
175,811,968
0
0
null
null
null
null
UTF-8
C++
false
false
389
cc
unpackresfile.cc
#include "dvc/opts.h" #include "dvc/program.h" #include "resource/resource.h" std::filesystem::path DVC_OPTION(infile, i, dvc::required, "input resource file"); std::filesystem::path DVC_OPTION(outdir, o, dvc::required, "output directory"); int main(int argc, char** argv) { dvc::program program(argc, argv); ResourceReader(infile).unpack(outdir); }
a2dbe5626cd15c424c6a080f8370e3323526fc8c
6e6542d3e5c491570ae86ee40bd9424e4de6ecc1
/Data Structures Problems/Array Practice/Medium/rotate_image_without_extra_space/main.cpp
b3bc4bd6635d783bea76e2a58da5795865fda43e
[]
no_license
Ubaid-Manzoor/Interview_Practice
9b66a920dfdc934f50b171d990e45dbddd9d7b54
d1ae188123da060b31e4e537713a45349786835a
refs/heads/master
2023-02-10T15:52:02.851818
2020-12-26T14:58:43
2020-12-26T14:58:43
275,573,186
20
3
null
null
null
null
UTF-8
C++
false
false
1,038
cpp
main.cpp
#include <iostream> #include <vector> using namespace std; // NOT DONE YET WILL DONE SOON ENOUGH void printImage(const vector<vector<int>> &image){ for(int i = 0 ; i < image[0].size() ; i++){ for(int j = 0 ; j < image[0].size() ; j++){ cout<<image[i][j]<<" "; } cout<<endl; } cout<<endl; } void rotate_by_90(vector<vector<int>> &image){ for(int i = 0 ; i < (image.size()/2) ; i++){ int last_col = i + image.size() - 2 * i; int last_pixel = image[i][last_col]; for(int row=i,col=last_col - 1; col > 0 ; col--){ } } } int main(){ int tc;cin>>tc; for(int i = 0 ; i < tc; i++){ int size;cin>>size; vector<vector<int>> image(size,vector<int>(size)); for(int j=0,row=0,col=0; j < size*size ;col++,j++){ if(col == size){ col %= size; row++; } int value;cin>>value; image[row][col] = value; } printImage(image); } }
24b6a97be83a23e501587e8dd0d67da43e708195
5b8895f84d269ee0efd6e79b16ed518df2562c7b
/Lab7MyStack.cpp
35f4880945697a6a7888ba7185eec47ec61dbe26
[]
no_license
yikaip/Lab5
c3c86546d783b71d845490a3e809553e65bed7c1
1538c1471c99346cb2e3ffcb3a721dabb4884354
refs/heads/master
2020-04-02T08:45:58.809610
2018-10-23T04:05:01
2018-10-23T04:05:01
154,259,919
0
0
null
null
null
null
UTF-8
C++
false
false
593
cpp
Lab7MyStack.cpp
//Lab 5 //Lab7MyStack.cpp //Yikai Peng //Oct.21 #include "Lab7MyStack.h" MyStack::MyStack() { list<char>MyList; //construction } MyStack::~MyStack() { MyList.clear(); //destruction: clear the list } bool MyStack::isEmpty() const { return MyList.empty(); //if the list is empty returns true, otherwise false } void MyStack::push(char & c) { MyList.push_back(c); //push c to list in stack } char MyStack::pull() { char top = MyList.back(); //top element MyList.pop_back(); //pops the element onto mylist return top;//return the character }
a070285840ec1abc55cd033ce85aa7bb81f7fb33
470b1af4907395df375062dfef44c4e061ddb1e2
/src/cpd/cpd_factory.cpp
9979b58bfb7210fcee67b14c969736d89fcd9653
[]
no_license
ushadow/pdbntk
f93149145d1ae7b27284019b6d0f86535be0706e
640b9cb1e86220f3e3d422e473a637fa3d861ac3
refs/heads/master
2021-01-10T20:30:17.305779
2013-07-09T21:54:07
2013-07-09T21:54:07
10,912,923
5
1
null
null
null
null
UTF-8
C++
false
false
583
cpp
cpd_factory.cpp
#include "cpd_factory.h" #include "discrete/discretedensities.h" #include "discrete/discreteess.h" #include "gaussian/gaussiandensities.h" #include "gaussian/gaussianess.h" namespace pdbntk { CondProbDist* CPDFactory::NewDiscreteCPD(uint node_size) { return new CondProbDist(DISCRETE, new mocapy::DiscreteESS(), new mocapy::DiscreteDensities(node_size)); } CondProbDist* CPDFactory::NewGaussianCPD(uint dimension) { return new CondProbDist(GAUSSIAN, new mocapy::GaussianESS(), new mocapy::GaussianDensities(dimension)); } }
4a986261c77ac7d3c59050da5abc29641b04460e
449dad881ba4520f533b7c6c708fcf19a76002aa
/Implementación/Primer Contest/A.cpp
fd6fa3d5e2bd21b488477d38de5fb7cc4d6656a5
[]
no_license
AbrMa/Club-Intermedios
527d005a75a41357346540abeeca44406bef1fe8
5df354f0b64a38021ea95b6f99045a3ce04aa918
refs/heads/master
2020-07-14T05:37:23.079554
2020-05-08T00:46:32
2020-05-08T00:46:32
205,251,648
0
0
null
null
null
null
UTF-8
C++
false
false
406
cpp
A.cpp
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <math.h> using namespace std; int main() { int n; cin >> n; vector<long long int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; sort(a.begin(), a.end()); int i = 0, j = n - 1; long long int sum = 0; while (i < j) { sum += (a[i] + a[j])*(a[i] + a[j]); i++; j--; } cout << sum << endl; return 0; }
6ee124ae5647a65e42baea764321cbef96caea93
7d97cd36a83f4a633d3e37ba0649bb06e986eb6d
/MFC41401/MFC41401/MFC41401.h
8fe4be85075b9e7c0cb459c6644e7cf32fd31f7e
[]
no_license
Ms52527/MA
53215fb62b8bf083db10b25363fabb4a6d89e9e5
6e8d8d0885586e4363b777719600c51e5de15ef0
refs/heads/master
2021-02-15T11:23:01.432593
2020-07-05T12:33:41
2020-07-05T12:33:41
244,893,687
0
0
null
null
null
null
GB18030
C++
false
false
525
h
MFC41401.h
// MFC41401.h : MFC41401 应用程序的主头文件 // #pragma once #ifndef __AFXWIN_H__ #error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件" #endif #include "resource.h" // 主符号 // CMFC41401App: // 有关此类的实现,请参阅 MFC41401.cpp // class CMFC41401App : public CWinApp { public: CMFC41401App(); // 重写 public: virtual BOOL InitInstance(); virtual int ExitInstance(); // 实现 afx_msg void OnAppAbout(); DECLARE_MESSAGE_MAP() }; extern CMFC41401App theApp;
24b7a57ea0641cb314c08d8a224bea558371f9c2
22ebc3fa6240ba05ef67c2189c09e287765a31b1
/roam/cuda/dp_cuda.h
2f7c7622c5738b2e67f95f8ba5f9f304de12c223
[]
no_license
lulu1315/roam
95d16dbb3467127c817bd3cf781e428f7e7d893f
fb65eb7445a34eb50856b33dd1a3997939e4eece
refs/heads/master
2020-04-16T19:37:45.364076
2018-07-11T14:01:11
2018-07-11T14:01:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,144
h
dp_cuda.h
/* This is a source code of "ROAM: a Rich Object Appearance Model with Application to Rotoscoping" implemented by Ondrej Miksik and Juan-Manuel Perez-Rua. @inproceedings{miksik2017roam, author = {Ondrej Miksik and Juan-Manuel Perez-Rua and Philip H.S. Torr and Patrick Perez}, title = {ROAM: a Rich Object Appearance Model with Application to Rotoscoping}, booktitle = {CVPR}, year = {2017} } */ #pragma once #include <thrust/host_vector.h> #include <thrust/device_vector.h> #include "../include/Configuration.h" #include "../include/DynamicProgramming.h" #include "omp.h" #include "cuda_profiler_api.h" #ifdef __CUDACC__ #define CUDA_METHOD __host__ __device__ #else #define CUDA_METHOD #endif #include "math.h" namespace cuda_roam { // ------------------------------------------------------------------------------- FLOAT_TYPE CudaDPMinimize(const ROAM::DPTableUnaries& unary_costs, const ROAM::DPTablePairwises& pairwise_costs, std::vector<ROAM::label> &path); // ------------------------------------------------------------------------------- } // namespace cuda_roam
9f1f4650ab19f4c9b9267ae4394aa5fd305bdc45
f5039a61cd73c494688f69270b518579e2e5c07d
/Contests/2014.07.06CodeForces/b;.cpp
f9de3d54b7df19ef8928467bf49643dd462edd97
[]
no_license
Tedxz/Online-Judge-Archive
12e4f67dddb464e1e6e6c3b48f1d3bdf67db8c6d
fa6361f8cdf492b870bbf763628f1d7be092798b
refs/heads/master
2020-04-17T17:43:41.489639
2016-08-28T16:03:10
2016-08-28T16:03:10
66,775,944
0
0
null
null
null
null
UTF-8
C++
false
false
839
cpp
b;.cpp
#include <cstdio> #include <iostream> #include <algorithm> #include <map> using namespace std; pair<int, int> chem[100]; int react[100][100]; int n, m; int main() { cin >> n >> m; for (int i = 1; i <= n; ++i) chem[i].second = i; for (int i = 0; i < m; ++i) { int x, y; cin >> x >> y; ++chem[x].first; ++chem[y].first; react[x][y] = react[y][x] = 1; } sort(chem + 1, chem + n + 1); long long ans = 1; for (int i = 1; i < n; ++i) { int flag = false; for (int j = i + 1; j <= n; ++j) { if (react[chem[i].second][chem[j].second]) { flag = true; break; } } if (flag) ans = ans * (long long)2; } cout << ans << endl; return 0; }
4637c1ac30c4e7438687942badf414031cff0744
ea72f1de1efe691ed038e16ee4a6fc11ad504f3b
/JIGAI_2015SIM_E/src/main.cpp
0658f19b13367bf5a9c610445d6ed59be3609238
[]
no_license
gyf1214/OI
d358f27d1fc5861a26b2d0ac1abc3d68414429a2
7b4b33d422462bef8660521617f82a57ebd2ff9c
refs/heads/master
2020-05-21T23:27:33.052962
2019-10-18T22:40:09
2019-10-18T22:40:09
12,171,280
0
0
null
null
null
null
UTF-8
C++
false
false
939
cpp
main.cpp
//Created At: Fri Dec 11 16:20:31 CST 2015 //orz zyx //ntr czr //Author: gyf #include <cstdlib> #include <cstdio> #include <cstring> #include <string> #include <iostream> #include <algorithm> #define rep(i, a, b) for (int i = (a); i <= (b); ++i) #define clr(i, a) memset(i, (a), sizeof(i)) #define infi 0x7FFFFFFF #define mm 200 using namespace std; int map[mm][mm]; int dis[mm], n; int prim() { rep(i, 1, n - 1) { dis[i] = map[0][i]; } int ans = 0; rep(i, 1, n - 1) { int best = infi, k; rep(j, 0, n - 1) { if (dis[j] > 0 && dis[j] < best) { best = dis[j], k = j; } } ans += dis[k]; rep(j, 0, n - 1) { dis[j] = min(dis[j], map[k][j]); } } return ans; } bool pre() { if (scanf("%d", &n) == EOF) return false; rep(i, 0, n - 1) { rep(j, 0, n - 1) { scanf("%d", &map[i][j]); } } return true; } int main() { while(pre()) printf("%d\n", prim()); fclose(stdin); fclose(stdout); return 0; }
7e4575eadd1cbe7ddaa5f642e05c44985791dc20
cb531b5ea632d4c25f823250e41a011cb6b93485
/warm/map.cpp
69663369be9cdec63ed8bc07a34c64bbe669587d
[]
no_license
ktjr4596/WarmsGame
ae8724b048f97d6c1bc0f4ee8a7db2213214b832
af6b1c5b4be13ff66b63647f15ee085edd3285a6
refs/heads/master
2020-04-26T18:37:07.247948
2019-03-04T13:42:00
2019-03-04T13:42:00
173,749,868
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,378
cpp
map.cpp
#include "map.h" #include "gtxy.h" #include <iostream> #include <mutex> const char * blocks[] = {"¢É", " ", "¡á" ,"¡Û"}; std::mutex g_Mutex; Map::Map() { for (int i_index = 0; i_index < Height; ++i_index) { for (int j_index = 0; j_index < Width; ++j_index) { gtxy::gotoxy(j_index * 2, i_index); if (i_index == 0 || i_index == Width - 1 || j_index == 0 || j_index == Height - 1) { mMap[i_index][j_index] = WALL; } else { mMap[i_index][j_index] = BLANK; } } } GenerateMap(); } void Map::GenerateMap() { for (int i_index = 0; i_index < Height; ++i_index) { for (int j_index = 0; j_index < Width; ++j_index) { if (i_index == 0 || i_index == Width - 1 || j_index == 0 || j_index == Height - 1) { RedrawPoint(j_index, i_index,WALL); } else { RedrawPoint(j_index, i_index, BLANK); } } } } void Map::SetPointState(const Point & pos, const State new_state) { mMap[pos.yPos][pos.xPos] = new_state; RedrawPoint(pos, new_state); } void Map::RedrawPoint(const Point & pos, const State new_state) { g_Mutex.lock(); gtxy::gotoxy((pos.xPos + 1) * 2, pos.yPos + 1); puts(blocks[new_state]); g_Mutex.unlock(); } void Map::RedrawPoint(const int x_pos, const int y_pos, const State new_state) { g_Mutex.lock(); gtxy::gotoxy((x_pos+1)*2, y_pos+1); puts(blocks[new_state]); g_Mutex.unlock(); }
4cefc94d5c960ad8813df943e73af2d620fc8643
a0b5e342f4d28b495c7f53b95655490bb6de7a88
/srcs/player.cpp
4672a52c255541e55e31e833c880a269ace5cd64
[]
no_license
rambobinator/pacman_muse_headband
2d9a19f4e616dbbabd9d32867751fa0b5a7c525c
2b932d433ace603193a74cc877355f375ada8235
refs/heads/master
2021-01-20T19:08:43.459838
2015-05-24T10:08:38
2015-05-24T10:08:38
36,085,824
0
0
null
null
null
null
UTF-8
C++
false
false
614
cpp
player.cpp
#include "Player.hpp" Player::Player(int y, int x, Map *map) : x(x), y(y), map(map) { dir = 0; life = 3; } Player::~Player( void ) { } Player & Player::operator=( Player const & rhs ) { (void)rhs; return *this; } std::ostream & operator<<(std::ostream &o, Player const &rhs) { (void)rhs; o << ""; return o; } void Player::setDir(int new_dir) { dir = new_dir; } void Player::move(void) { int dirs[4][2] = { {-1, 0}, {0, 1}, {1, 0}, {0, -1} }; if (map->colision(y, (x + dirs[dir][1])) == '0') x += dirs[dir][1]; if (map->colision((y + dirs[dir][0]), x) == '0') y += dirs[dir][0]; }
b8a4349d1d5d9230ae4294c34a7fe8b660272621
b9b966952e88619c9c5d754fea0f0e25fdb1a219
/libcaf_core/caf/detail/default_mailbox.test.cpp
149ea8330e0838f2208667e291f815ba09e0339d
[]
permissive
actor-framework/actor-framework
7b152504b95b051db292696a803b2add6dbb484d
dd16d703c91e359ef421f04a848729f4fd652d08
refs/heads/master
2023-08-23T18:22:34.479331
2023-08-23T09:31:36
2023-08-23T09:31:36
1,439,738
2,842
630
BSD-3-Clause
2023-09-14T17:33:55
2011-03-04T14:59:50
C++
UTF-8
C++
false
false
2,591
cpp
default_mailbox.test.cpp
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #include "caf/detail/default_mailbox.hpp" #include "caf/test/caf_test_main.hpp" #include "caf/test/test.hpp" using namespace caf; using ires = intrusive::inbox_result; template <message_priority P = message_priority::normal> auto make_int_msg(int value) { return make_mailbox_element(nullptr, make_message_id(P), {}, make_message(value)); } TEST("a default-constructed mailbox is empty") { detail::default_mailbox uut; check(!uut.closed()); check(!uut.blocked()); check_eq(uut.size(), 0u); check_eq(uut.pop_front(), nullptr); check_eq(uut.size(), 0u); check(uut.try_block()); check(!uut.try_block()); } TEST("the first item unblocks the mailbox") { detail::default_mailbox uut; check(uut.try_block()); check_eq(uut.push_back(make_int_msg(1)), ires::unblocked_reader); check_eq(uut.push_back(make_int_msg(2)), ires::success); } TEST("a closed mailbox no longer accepts new messages") { detail::default_mailbox uut; uut.close(error{}); check_eq(uut.push_back(make_int_msg(1)), ires::queue_closed); } TEST("urgent messages are processed first") { detail::default_mailbox uut; check_eq(uut.push_back(make_int_msg(1)), ires::success); check_eq(uut.push_back(make_int_msg(2)), ires::success); check_eq(uut.push_back(make_int_msg<message_priority::high>(3)), ires::success); std::vector<message> results; for (auto ptr = uut.pop_front(); ptr != nullptr; ptr = uut.pop_front()) { results.emplace_back(ptr->content()); } if (check_eq(results.size(), 3u)) { check_eq(results[0].get_as<int>(0), 3); check_eq(results[1].get_as<int>(0), 1); check_eq(results[2].get_as<int>(0), 2); } } TEST("calling push_front inserts messages at the beginning") { detail::default_mailbox uut; check_eq(uut.push_back(make_int_msg(1)), ires::success); check_eq(uut.push_back(make_int_msg(2)), ires::success); uut.push_front(make_int_msg(3)); uut.push_front(make_int_msg(4)); std::vector<message> results; for (auto ptr = uut.pop_front(); ptr != nullptr; ptr = uut.pop_front()) { results.emplace_back(ptr->content()); } if (check_eq(results.size(), 4u)) { check_eq(results[0].get_as<int>(0), 4); check_eq(results[1].get_as<int>(0), 3); check_eq(results[2].get_as<int>(0), 1); check_eq(results[3].get_as<int>(0), 2); } } CAF_TEST_MAIN()
b49131b50c3c5108572c588a4372b079dbb492b5
eab2cd564e25896e1f89df4c02eedb95d8c5f5bc
/Arduino/Timer1.h
22191566163e4c7bdfcc050df580d2548043f86e
[]
no_license
ThibaultMollier/IHCcontroller
ff220d1c03bbbbbfd21000610441f644594eaaa0
3c66ad72e0a387375ccfcc1875139a6f94b8b560
refs/heads/master
2020-04-28T23:16:47.597344
2019-03-14T15:25:45
2019-03-14T15:25:45
175,649,143
0
0
null
null
null
null
UTF-8
C++
false
false
378
h
Timer1.h
// Timer1.h #ifndef _TIMER1_h #define _TIMER1_h #define t_4100us 0 #define t_300us 60735 #define t_600us 55935 #define t_450us 58335 #if defined(ARDUINO) && ARDUINO >= 100 #include "arduino.h" #else #include "WProgram.h" #endif class Timer1Class { protected: public: void init(); void time_to_OVF(unsigned int countervalue); }; extern Timer1Class Timer1; #endif
5d95baf56e26fd2a8aa18902244637236367a6c8
2aa4c7c94866e7a958e4787dd4487aa7c1eb8d61
/applications/IgaApplication/custom_utilities/node_surface_geometry_3d.h
b46303693def1aa05a82ce11fe522afd7d14e753
[ "BSD-3-Clause" ]
permissive
PFEM/Kratos
b48df91e6ef5a00edf125e6f5aa398505c9c2b96
796c8572e9fe3875562d77370fc60beeacca0eeb
refs/heads/master
2021-10-16T04:33:47.591467
2019-02-04T14:22:06
2019-02-04T14:22:06
106,919,267
1
0
null
2017-10-14T10:34:43
2017-10-14T10:34:43
null
UTF-8
C++
false
false
6,884
h
node_surface_geometry_3d.h
/* // KRATOS _____________ // / _/ ____/ | // / // / __/ /| | // _/ // /_/ / ___ | // /___/\____/_/ |_| Application // // Main authors: Thomas Oberbichler */ #if !defined(KRATOS_NODE_SURFACE_GEOMETRY_3D_H_INCLUDED) #define KRATOS_NODE_SURFACE_GEOMETRY_3D_H_INCLUDED // System includes // External includes // Project includes #include "includes/define.h" #include "includes/node.h" #include "includes/variables.h" #include "anurbs.h" #include "iga_application_variables.h" namespace Kratos { /// Spatial NURBS surface geometry with Kratos Nodes as control points. /** Unlike the ANurbs::SurfaceGeometry, this class does not use static Points as * control points but Finite Element Nodes. That means that the Geometry * changes whenever the Nodes are moving. */ class NodeSurfaceGeometry3D : public ANurbs::SurfaceGeometryBase<Kratos::array_1d<double, 3>> { protected: using NodePointer = typename Node<3>::Pointer; public: using NodeType = Node<3>; using SurfaceGeometryBaseType = SurfaceGeometryBase< Kratos::array_1d<double, 3>>; using typename SurfaceGeometryBaseType::KnotsType; using typename SurfaceGeometryBaseType::ScalarType; using typename SurfaceGeometryBaseType::VectorType; protected: ANurbs::Grid<NodePointer> mNodes; public: /** Creates a new NodeSurfaceGeometry3D. * * @param DegreeU Degree in u direction * @param DegreeV Degree in v direction * @param NumberOfNodesU Number of nodes in u direction * @param NumberOfNodesV Number of nodes in v direction */ NodeSurfaceGeometry3D( const int DegreeU, const int DegreeV, const int NumberOfNodesU, const int NumberOfNodesV) : SurfaceGeometryBaseType(DegreeU, DegreeV, NumberOfNodesU, NumberOfNodesV) , mNodes(NumberOfNodesU, NumberOfNodesV) { } /** Gets the Kratos node at a given index. * * @param IndexU Index in u direction * @param IndexV Index in v direction * * @return Kratos node at the given index. */ NodePointer GetNode( const int IndexU, const int IndexV) const { KRATOS_DEBUG_ERROR_IF(IndexU < 0 || NbPolesU() <= IndexU) << "IndexU out of range" << std::endl; KRATOS_DEBUG_ERROR_IF(IndexV < 0 || NbPolesV() <= IndexV) << "IndexV out of range" << std::endl; return mNodes(IndexU, IndexV); } /** Sets the Kratos node at a given index. * * @param IndexU Index in u direction * @param IndexV Index in v direction */ void SetNode( const int IndexU, const int IndexV, NodePointer Value) { KRATOS_DEBUG_ERROR_IF(IndexU < 0 || NbPolesU() <= IndexU) << "IndexU out of range" << std::endl; KRATOS_DEBUG_ERROR_IF(IndexV < 0 || NbPolesV() <= IndexV) << "IndexV out of range" << std::endl; mNodes.SetValue(IndexU, IndexV, Value); } /** Gets the location of the Kratos node at a given index. * * @param IndexU Index in u direction * @param IndexV Index in v direction * * @return Location of the Kratos node at the given index. */ VectorType Pole( const int IndexU, const int IndexV) const override { const NodeType& node = *GetNode(IndexU, IndexV); VectorType pole; for (std::size_t i = 0; i < 3; i++) { pole[i] = node[i]; } return pole; } /** Sets the location of the Kratos node at a given index. * * @param IndexU Index in u direction * @param IndexV Index in v direction * @param Value New location of the Kratos node */ void SetPole( const int IndexU, const int IndexV, const VectorType& Value) override { NodeType& node = *GetNode(IndexU, IndexV); for (std::size_t i = 0; i < 3; i++) { node[i] = Value[i]; } } /** Gets a value indicating whether or not the NURBS surface is rational. * * @return True whether the surface is rational, otherwise false. */ bool IsRational() const override { return true; } /** Gets the weight of the Kratos node at a given index. * * @param IndexU Index in u direction * @param IndexV Index in v direction * * @return Weight of the Kratos node at the given index. */ ScalarType Weight( const int IndexU, const int IndexV) const override { const NodeType& node = *GetNode(IndexU, IndexV); if (node.Has(Kratos::NURBS_CONTROL_POINT_WEIGHT)) { return node.GetValue(Kratos::NURBS_CONTROL_POINT_WEIGHT); } else { return 1; } } /** Sets the weight of the Kratos node at a given index. * * @param IndexU Index in u direction * @param IndexV Index in v direction * @param Value New weight of the Kratos node */ void SetWeight( const int IndexU, const int IndexV, const ScalarType Value) override { NodeType& node = *GetNode(IndexU, IndexV); node.SetValue(Kratos::NURBS_CONTROL_POINT_WEIGHT, Value); } /** Gets the value of a nodal Kratos variable on a point at the surface. * * @param Variable Kratos variable * @param U Surface parameter in u direction * @param V Surface parameter in v direction * * @return The value of the variable at the given surface point. */ template <typename TDataType, typename TVariableType = Variable<TDataType>> TDataType ValueAt( const TVariableType& Variable, const double U, const double V) const { return EvaluateAt<TDataType>([&](int i, int j) -> TDataType { return GetNode(i, j)->GetValue(Variable); }, U, V); } /** Gets the derivatives of a nodal Kratos variable on a point at the * surface. * * @param Variable Kratos variable * @param U Surface parameter in u direction * @param V Surface parameter in v direction * @param Order Order of the highest derivative to compute * * @return The value and the derivatives of the variable at the given * surface point. */ template <typename TDataType, typename TVariableType = Variable<TDataType>> std::vector<TDataType> ValueAt( const TVariableType& Variable, const double U, const double V, const int Order) const { return EvaluateAt<TDataType>([&](int i, int j) -> TDataType { return GetNode(i, j)->GetValue(Variable); }, U, V, Order); } }; using NodeSurface3D = ANurbs::Surface<NodeSurfaceGeometry3D>; } #endif // !defined(KRATOS_NODE_SURFACE_GEOMETRY_3D_H_INCLUDED)
10986c766abe96029c9d3b549921155a6e4f0a38
e7a76fa4e1edc0721a21d4dc16ec05f8b4f7e6de
/libwebwechat/libwebwx/config.h
b056609b933598a819d99cf2e235b69aaa6b58de
[ "Apache-2.0" ]
permissive
DeaglePC/QTWechat
81d6f3cbb9791e619906875233a06811b8713291
8359daf05d81d97f850bb4c3ae9ba99403ff855e
refs/heads/master
2020-04-14T16:49:22.343574
2019-01-19T09:23:16
2019-01-19T09:23:16
163,962,355
1
3
Apache-2.0
2019-01-09T12:54:17
2019-01-03T11:08:58
C++
UTF-8
C++
false
false
682
h
config.h
#ifndef CONFIG_H #define CONFIG_H #include <QHash> #include <QDir> #include "cwebwxwork.h" using hint_map = QHash<int, QString>; using hint_pv = std::pair<int, QString>; const hint_map HINT_MSG_MAP = {hint_pv(CWebwxWork::RET_MSG::LOGIN_SUCCESS, "登录成功"), hint_pv(CWebwxWork::RET_MSG::LOGIN_FAILED, "登录失败"), hint_pv(CWebwxWork::RET_MSG::HTTP_BAD_REQUEST, "请求失败"), hint_pv(CWebwxWork::RET_MSG::WX_INIT_SUCCESS, "初始化成功") }; const QString HEAD_LOCAL_PATH = QDir::homePath() + "/ddwx/head/"; #endif // CONFIG_H
f4275fcf58cd36b63c5e2be599b5d42a9d82fd27
42c7e42257a28022d6263aeb494f0200f4efca5f
/LuaItemAttribLoader.h
9bebbfad928e81e7ae5c2f898e18a2ece18ef0fb
[]
no_license
sryanyuan/circlebuffer
710c5cfc8c3ec68ad79303180853cbb1916bfbce
a5fb6a65a6604faa0ead82516fce3dac87c36edb
refs/heads/master
2021-01-18T18:50:10.796172
2018-07-17T08:41:49
2018-07-17T08:41:49
60,167,461
0
0
null
null
null
null
UTF-8
C++
false
false
697
h
LuaItemAttribLoader.h
#ifndef _INC_LUA_ITEM_ATTRIB_LOADER_ #define _INC_LUA_ITEM_ATTRIB_LOADER_ #include <map> #include "item.h" struct ItemFullAttrib; struct lua_State; #define pszDefaultItemFullAttribTableName "config_constItemAttrib" class LuaItemAttribLoader { public: static bool loadKeyInt(lua_State *L, const char *pKeyName, int &refValue); static bool loadKeyInt(lua_State *L, const char *pKeyName, char &refValue); static bool loadKeyInt(lua_State *L, const char *pKeyName, short &refValue); static bool loadKeyString(lua_State *L, const char *pKeyName, char *pBuf); static bool LoadItemAttrib(lua_State* L, const char *pKeyName, std::map<int, ItemFullAttrib> &refAttribs); }; #endif
c95f98b4370b29b21f764b4eb7667d902291e9b3
2001549fa84ca5ac0c1c3480ee3247c5c4bcb6f4
/RayTracer/MeshGroupCreator.cpp
702595ec1070b1613308ab9930f5d57308d16c27
[]
no_license
NightCreature/RayTracer
91b58a6f789cd7ee52ca6fbb13bbddd139c0862e
4e1fbc6d4a896223545f43b0346f9b7192922f56
refs/heads/master
2020-08-29T23:24:04.921136
2019-12-03T05:04:22
2019-12-03T05:04:22
218,200,525
1
0
null
null
null
null
UTF-8
C++
false
false
1,201
cpp
MeshGroupCreator.cpp
#include "MeshGroupCreator.h" #include "assert.h" ///----------------------------------------------------------------------------- ///! @brief TODO enter a description ///! @remark ///----------------------------------------------------------------------------- CreatedMeshGroup MeshGroupCreator::CreateMeshGroup(const CreationParams& params) { CreatedMeshGroup meshGroup; unsigned int m_nummultitexcoords = 1; //HACK FIX THIS meshGroup.meshGroup = new MeshGroup(); meshGroup.meshGroup->m_vertices.resize(params.m_vertices.size()); meshGroup.meshGroup->m_vertices.assign(params.m_vertices.begin(), params.m_vertices.end()); meshGroup.meshGroup->m_normals.resize(params.m_normals.size()); meshGroup.meshGroup->m_normals.assign(params.m_normals.begin(), params.m_normals.end()); //meshGroup.meshGroup->m_uvs.resize(m_nummultitexcoords * params.m_texcoords.size()); //Bounding box setup might be handy later //meshGroup.boundingBox.enclose(params.m_vertices[counter]); return meshGroup; } void MeshGroupCreator::normalizeNormals(std::vector<Vector3>& normals) { for (int i = 0; i < normals.size(); i++) { normals[i].normalize(); } }
08d89ddcad7dbf8ab5f6bf7ecea47e83b1191dcb
6fcde7a31a7896ad7f7760e4db522feb78cfb7ab
/Spectral/rnzMainRpk.cpp
6424cf3c4215bc4a570e1d15050321e6bcd74ab5
[ "MIT" ]
permissive
lsaravia/SpatialAnalysis
6cc4ff1b54875a9df2822574e980c952a852f5c2
899148a65407dc8807475a923b4a231984441301
refs/heads/master
2020-12-24T16:07:30.921477
2016-03-10T17:25:35
2016-03-10T17:25:35
5,533,498
0
0
null
null
null
null
UTF-8
C++
false
false
6,625
cpp
rnzMainRpk.cpp
#include "Spectral.h" #include "RWFile.h" #include "Randomizations.h" #include <iomanip> //#include "fortify.h" #include "ctype.h" int main(int argc, char * argv[]) { simplmat <double> data; simplmat <double> dout; SpectralAnalysis sa; // Do 199 Simulations and takes the 5 lowest and 5 highest values // to make the confidence envelopes. If the calculated value is // between these highest or lowest values it is significative at 5% level // int numSimul=199,numExtreme=5,windowPos=0,numExtremeT=5; char randz; double probConf=0.05; double probConfT=0.05; double probOrig=0.05; int bonfCorr=0,signif=0; // OJO Falta agregar en parametros int reaPer=0; string fType="BI"; if( argc <3 ) { cerr << "Usage: rnzSpectral inputFile.sed outFile fileType winPos{0,1,2,3} [R/A] [prob] [bonfCorr{0,1}] [numSimulations]" << endl; exit(1); } if( argc >= 4) { fType = argv[3]; windowPos = atoi(argv[4]); randz = toupper(argv[5][0]); // R=Randomizations, A=Asintotic chisqr. if( windowPos > 3 || windowPos <0 ) { cerr << "Out of range: 3 > windowPos > 0" << endl; exit(1); } } if( randz=='R' ) { if( argc == 9) { probOrig = atof(argv[6]); bonfCorr = atoi(argv[7]); numSimul = atoi(argv[8]); } else { cerr << "Invalid number of arguments" << endl; exit(1); } } else { if( argc == 8 ) { probOrig = atof(argv[6]); bonfCorr = atoi(argv[7]); } else { cerr << "Invalid number of arguments" << endl; exit(1); } } RWFile file; string fName = argv[1]; string outFName = argv[2]; if( fName.find(".sed")!=string::npos ) { if(!file.ReadSeed(fName.c_str(), data, fType.c_str() )) exit(1); } else if( fName.find(".img")!=string::npos ) { if(!file.ReadIdrisi(fName.c_str(), data)) exit(1); } else { cerr << "File type not supported: " << fName << endl; exit(1); } sa.Transpose(data); // Los datos leidos estan en formato (x,y) y las funciones // tienen (y,x) o sea (row,col) int rows=data.getRows(); int cols=data.getCols(); double var; int s,l; simplmat <double> origData(data); sa.SetPow2(data,origData,windowPos); int origRows = rows; int origCols = cols; rows=data.getRows(); cols=data.getCols(); var = sa.Spec2D(data,dout); // Calculates the periodogram usando FFT simplmat<double> rper; // Rearranged periodogram simplmat<double> polper; // Polar sa.Spekout(rows,cols,dout,rper); // Rearranges the periodogram ofstream fOut; if(reaPer) { string rperOut="r."+outFName; fOut.open(rperOut.c_str()); fOut << rper.getCols() << "\t" << rper.getRows() << endl; fOut << "Rearranged periodogram" << endl; for(l=0;l<rper.getRows();l++) { for(s=0;s<rper.getCols();s++) fOut.form("%10.6f",rper(l,s)) << "\t"; fOut << endl; } fOut.close(); } sa.Polar2D(rows,cols,rper,polper); // Calculates the Polar Spectrum // OJO modifica rper!!!!!!!!!!!! int d = int(0.5*sqrt(rows*rows + cols*cols)+1); // Outputs the rearranged periodogram // //string rperOut("rper."); //rperOut+=outFName; //if(!file.WriteSeed(rperOut.c_str(), rper)) // exit(1); fOut.open(outFName.c_str()); if( bonfCorr ) { probConf=probOrig/d; probConfT=probOrig/18; } else { probConf=probOrig; probConfT=probOrig; } numExtreme = 1+probConf*numSimul/2; if( numExtreme <=1 ) { cerr << "numExtreme <= 1" << endl; exit(1); } numExtremeT = 1+probConfT*numSimul/2; if( numExtremeT <=1 ) { cerr << "numExtremeT <= 1" << endl; exit(1); } Randomizations rz; simplmat<double> thetamin; simplmat<double> thetamax; simplmat<double> rmin; simplmat<double> rmax; simplmat<double> rpol; // Polar Spectrum for randomizations thetamin.resize(18,numExtremeT,1000.0); thetamax.resize(18,numExtremeT,0.0); rmin.resize(d,numExtreme,1000.0); rmax.resize(d,numExtreme,0.0); for(s=0; s<numSimul; s++) { rz.Randomize(origData); sa.SetPow2(data,origData); sa.Spec2D(data,dout); sa.Spekout(rows,cols,dout,rper); sa.Polar2D(rows,cols,rper,rpol); for(l=0;l<d;l++) { sa.spectMax(rpol(l,0),rmax,l,numExtreme); sa.spectMin(rpol(l,0),rmin,l,numExtreme); // cout << setw(2) << l+1 << "\t"; // cout.form("%8.5f", rpol(l,0)) << endl; } for(l=0;l<18;l++) { sa.spectMax(rpol(l,2),thetamax,l,numExtremeT); sa.spectMin(rpol(l,2),thetamin,l,numExtremeT); // cout << "\t\t" << setw(4) << l*10 << "\t"; // cout.form("%8.5f", rpol(l,2)) << endl; } } fOut << "R Spectrum " << "\t" << outFName << endl; fOut << "Randomizations: "<< "\t" << numSimul << "\t" << numExtreme << "\t" << probConf << endl; fOut << "Data dim:" << "\t" << origRows << "\t" << origCols << endl; fOut << "Window dim:" << "\t" << rows << "\t" << cols << "\tPosition:\t" << windowPos << endl; for(l=0;l<d;l++) { signif = 0; fOut << setw(2) << l+1 << "\t"; fOut.form("%8.5f", polper(l,0)) << "\t"; fOut.form("%8.5f", rmin(l,0)) << "\t"; fOut.form("%8.5f", rmax(l,0)) << "\t"; fOut.form("%8.5f", polper(l,1)) << "\t"; if( polper(l,0)<rmin(l,0) ) signif = -1; if( polper(l,0)>rmax(l,0) ) signif = 1; fOut << signif << endl; } fOut << "\nTheta Spectrum" << endl; fOut << "Randomizations: "<< "\t" << numSimul << "\t" << numExtremeT << "\t" << probConfT << endl; for(l=0;l<18;l++) { signif = 0; fOut << setw(4) << l*10 << "\t"; fOut.form("%8.5f", polper(l,2)) << "\t"; fOut.form("%8.5f", thetamin(l,0)) << "\t"; fOut.form("%8.5f", thetamax(l,0)) << "\t"; fOut.form("%8.5f", polper(l,3)) << "\t"; if( polper(l,2)<thetamin(l,0) ) signif = -1; if( polper(l,2)>thetamax(l,0) ) signif = 1; fOut << signif << endl; } return 0; } void spectMin(double const &pspect, simplmat<double> & pMin, int & l ) { if( pspect < pMin(l,0) ) { for(int k=4; k>=0; k--) { if( pspect < pMin(l,k) ) { for(int kk=1; kk<=k; kk++) pMin(l,kk-1) = pMin(l,kk); pMin(l,k) = pspect; break; } } } } void spectMax(double const &pspect, simplmat<double> & pMax, int & l ) { if( pspect > pMax(l,0) ) { for(int k=4; k>=0; k--) { if( pspect > pMax(l,k) ) { for(int kk=1; kk<=k; kk++) pMax(l,kk-1) = pMax(l,kk); pMax(l,k) = pspect; break; } } } }
2c46613e57c36c30c4ba8df1baa350521c4c308a
11193bb804b3ca7954b902096baa80a70b2bd154
/tests/auto/declarative/qsgview/tst_qsgview.cpp
f2913cbd63149a212cef8ce1cc97eee430802276
[]
no_license
richardeigenmann/qtdeclarative
e36347b973cc72619e373a6742ebc9ca38a81480
c5b56564667194b179ebfcc87608d38e9969fade
refs/heads/master
2020-07-23T17:02:02.169233
2011-08-11T11:58:53
2011-08-15T07:35:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,388
cpp
tst_qsgview.cpp
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QtTest/QSignalSpy> #include <QtDeclarative/qdeclarativecomponent.h> #include <QtDeclarative/qdeclarativecontext.h> #include <QtDeclarative/qsgview.h> #include <QtDeclarative/qsgitem.h> #include "../../../shared/util.h" #ifdef Q_OS_SYMBIAN // In Symbian OS test data is located in applications private dir #define SRCDIR "." #endif class tst_QSGView : public QObject { Q_OBJECT public: tst_QSGView(); private slots: void resizemodeitem(); void errors(); }; tst_QSGView::tst_QSGView() { } void tst_QSGView::resizemodeitem() { QWidget window; QSGView *canvas = new QSGView(&window); QVERIFY(canvas); canvas->setResizeMode(QSGView::SizeRootObjectToView); QCOMPARE(QSize(0,0), canvas->initialSize()); canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/resizemodeitem.qml")); QSGItem* item = qobject_cast<QSGItem*>(canvas->rootObject()); QVERIFY(item); window.show(); // initial size from root object QCOMPARE(item->width(), 200.0); QCOMPARE(item->height(), 200.0); QCOMPARE(canvas->size(), QSize(200, 200)); QCOMPARE(canvas->size(), canvas->sizeHint()); QCOMPARE(canvas->size(), canvas->initialSize()); // size update from view canvas->resize(QSize(80,100)); QCOMPARE(item->width(), 80.0); QCOMPARE(item->height(), 100.0); QCOMPARE(canvas->size(), QSize(80, 100)); QCOMPARE(canvas->size(), canvas->sizeHint()); canvas->setResizeMode(QSGView::SizeViewToRootObject); // size update from view disabled canvas->resize(QSize(60,80)); QCOMPARE(item->width(), 80.0); QCOMPARE(item->height(), 100.0); QCOMPARE(canvas->size(), QSize(60, 80)); // size update from root object item->setWidth(250); item->setHeight(350); QCOMPARE(item->width(), 250.0); QCOMPARE(item->height(), 350.0); QTRY_COMPARE(canvas->size(), QSize(250, 350)); QCOMPARE(canvas->size(), QSize(250, 350)); QCOMPARE(canvas->size(), canvas->sizeHint()); // reset canvas window.hide(); delete canvas; canvas = new QSGView(&window); QVERIFY(canvas); canvas->setResizeMode(QSGView::SizeViewToRootObject); canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/resizemodeitem.qml")); item = qobject_cast<QSGItem*>(canvas->rootObject()); QVERIFY(item); window.show(); // initial size for root object QCOMPARE(item->width(), 200.0); QCOMPARE(item->height(), 200.0); QCOMPARE(canvas->size(), canvas->sizeHint()); QCOMPARE(canvas->size(), canvas->initialSize()); // size update from root object item->setWidth(80); item->setHeight(100); QCOMPARE(item->width(), 80.0); QCOMPARE(item->height(), 100.0); QTRY_COMPARE(canvas->size(), QSize(80, 100)); QCOMPARE(canvas->size(), QSize(80, 100)); QCOMPARE(canvas->size(), canvas->sizeHint()); // size update from root object disabled canvas->setResizeMode(QSGView::SizeRootObjectToView); item->setWidth(60); item->setHeight(80); QCOMPARE(canvas->width(), 80); QCOMPARE(canvas->height(), 100); QCOMPARE(QSize(item->width(), item->height()), canvas->sizeHint()); // size update from view canvas->resize(QSize(200,300)); QCOMPARE(item->width(), 200.0); QCOMPARE(item->height(), 300.0); QCOMPARE(canvas->size(), QSize(200, 300)); QCOMPARE(canvas->size(), canvas->sizeHint()); delete canvas; // if we set a specific size for the view then it should keep that size // for SizeRootObjectToView mode. canvas = new QSGView(&window); canvas->resize(300, 300); canvas->setResizeMode(QSGView::SizeRootObjectToView); QCOMPARE(QSize(0,0), canvas->initialSize()); canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/resizemodeitem.qml")); item = qobject_cast<QSGItem*>(canvas->rootObject()); QVERIFY(item); window.show(); // initial size from root object QCOMPARE(item->width(), 300.0); QCOMPARE(item->height(), 300.0); QCOMPARE(canvas->size(), QSize(300, 300)); QCOMPARE(canvas->size(), canvas->sizeHint()); QCOMPARE(canvas->initialSize(), QSize(200, 200)); // initial object size delete canvas; } static void silentErrorsMsgHandler(QtMsgType, const char *) { } void tst_QSGView::errors() { QSGView *canvas = new QSGView; QVERIFY(canvas); QtMsgHandler old = qInstallMsgHandler(silentErrorsMsgHandler); canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/error1.qml")); qInstallMsgHandler(old); QVERIFY(canvas->status() == QSGView::Error); QVERIFY(canvas->errors().count() == 1); delete canvas; } QTEST_MAIN(tst_QSGView) #include "tst_qsgview.moc"
17cffba440113f264476e221a707e75d0fc463bf
309647935d0f8f507207ecf48d124102c1d7197f
/Utility/font/src/FileHeader.h
ce082f48ad1dbb9d4ee32b9602d4217734d75d68
[ "MIT" ]
permissive
ThomasChevalier/passwordWallet
6b59d8afd48c1bbdc89348798beebfa6ced87e7e
115dbde3e32f2be65071e6f298c4f03ddfe19b09
refs/heads/master
2021-03-27T20:00:34.594894
2020-04-19T17:03:49
2020-04-19T17:03:49
71,448,410
3
0
null
null
null
null
UTF-8
C++
false
false
557
h
FileHeader.h
#ifndef FILEHEADER_H #define FILEHEADER_H #pragma pack(1) class FileHeader { public: FileHeader(): fileSize(0), rsv(0), offsetImg(0) { reset(); } void reset() { signature[0] = '*'; signature[1] = '*'; fileSize = 0; rsv = 0; offsetImg = 0; } char signature[2]; // Signature caracter int fileSize; // Size of file int rsv; // 4 bytes to 0 int offsetImg; // Where the image begin }; #endif // FILEHEADER_H
a8495c8b82a139559541cfe1793c52714cde59b0
f1182b9c4d222f6914505cac8450e5d96ce4e4d1
/juce_1_44/juce/extras/audio plugins/wrapper/juce_AudioFilterBase.h
a9252408d456891952c623695b2b0d009ef5db8b
[]
no_license
GeorgeNs/mammut
b417ee2aee734f6fa6ac4d9425eb314e0e66559f
5346951da7ceced59b4d766c809f4546b95d3412
refs/heads/master
2020-03-28T08:54:36.395454
2018-09-10T04:21:32
2018-09-10T04:21:32
147,935,202
0
0
null
null
null
null
UTF-8
C++
false
false
23,837
h
juce_AudioFilterBase.h
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-7 by Raw Material Software ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License, as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. JUCE 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 JUCE; if not, visit www.gnu.org/licenses or write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ------------------------------------------------------------------------------ If you'd like to release a closed-source product which uses JUCE, commercial licenses are also available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ #ifndef __JUCE_AUDIOFILTERBASE_JUCEHEADER__ #define __JUCE_AUDIOFILTERBASE_JUCEHEADER__ #ifdef _MSC_VER #pragma pack (push, 8) #endif #include "../../../juce.h" #include "juce_AudioFilterEditor.h" #undef MemoryBlock //============================================================================== /** Base class for plugins written using JUCE. This is intended to act as a base class of plugin that is general enough to be wrapped as a VST, AU, RTAS, etc. Derive your filter class from this base class, and implement a global function called initialiseFilterInfo() which creates and returns a new instance of your subclass. */ class AudioFilterBase { protected: //============================================================================== /** Constructor. You can also do your initialisation tasks in the initialiseFilterInfo() call, which will be made after this object has been created. */ AudioFilterBase(); public: /** Destructor. */ virtual ~AudioFilterBase(); //============================================================================== /** Called before playback starts, to let the plugin prepare itself. The sample rate is the target sample rate, and will remain constant until playback stops. The estimatedSamplesPerBlock value is a HINT about the typical number of samples that will be processed for each callback, but isn't any kind of guarantee. The actual block sizes that the host uses may be different each time the callback happens, and may be more or less than this value. */ virtual void JUCE_CALLTYPE prepareToPlay (double sampleRate, int estimatedSamplesPerBlock) = 0; /** Called after playback has stopped, to let the plugin free up any resources it no longer needs. */ virtual void JUCE_CALLTYPE releaseResources() = 0; /** Renders the next block. The input and output buffers will have been prepared with the number of samples and channels required, and mustn't be resized. Note that these may both point to the same block of memory if accumulateOutput is true. There will always be the same number of samples in the input and output buffers, but the number of channels may not be the same. If accumulateOutput is true, then the output buffer will contain a copy of the input buffer (or may be physically the same memory - be careful!), and your filter's output should be added to (or may replace) whatever samples are already in the output buffer. If accumulateOutput is false then the contents of the output buffer are undefined and MUST ALL be overwritten with your plugin's output. Note that the number of samples in these buffers is NOT guaranteed to be the same for every callback, and may be more or less than the estimated value given to prepareToPlay(). Your code must be able to cope with variable-sized blocks, or you're going to get clicks and crashes! Your plugin must also not make any assumptions about the number of channels supplied in the input and output buffers - there could be any number of channels here, up to the maximum values specified in your JucePluginCharacteristics.h file. However, the number of channels will remain constant between the prepareToPlay() and releaseResources() calls. If the plugin has indicated that it needs midi input, then the midiMessages array will be filled with midi messages for this block. Each message's timestamp will indicate the message's time, as a number of samples from the start of the block. If the plugin has indicated that it produces midi output, then any messages remaining in the midiMessages array will be sent to the host after the processBlock method returns. This means that the plugin must be careful to clear any incoming messages out of the array if it doesn't want them to be passed-on. Be very careful about what you do in this callback - it's going to be called by the audio thread, so any kind of interaction with the UI is absolutely out of the question. If you change a parameter in here and need to tell your UI to update itself, the best way is probably to inherit from a ChangeBroadcaster, let the UI components register as listeners, and then call sendChangeMessage() inside the processBlock() method to send out an asynchronous message. You could also use the AsyncUpdater class in a similar way. */ virtual void JUCE_CALLTYPE processBlock (const AudioSampleBuffer& input, AudioSampleBuffer& output, const bool accumulateOutput, MidiBuffer& midiMessages) = 0; //============================================================================== /** Structure containing details of the playback position. @see AudioFilterBase::getCurrentPositionInfo */ struct CurrentPositionInfo { /** The tempo in BPM */ double bpm; /** Time signature numerator, e.g. the 3 of a 3/4 time sig */ int timeSigNumerator; /** Time signature denominator, e.g. the 4 of a 3/4 time sig */ int timeSigDenominator; /** The current play position, in seconds from the start of the edit. */ double timeInSeconds; /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */ double editOriginTime; /** The current play position in pulses-per-quarter-note. This is the number of quarter notes since the edit start. */ double ppqPosition; /** The position of the start of the last bar, in pulses-per-quarter-note. This is the number of quarter notes from the start of the edit to the start of the current bar. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If it's not available, the value will be 0. */ double ppqPositionOfLastBarStart; /** Frame rate types */ enum FrameRateType { fps24 = 0, fps25 = 1, fps2997 = 2, fps30 = 3, fps2997drop = 4, fps30drop = 5, fpsUnknown = 99 }; /** The video frame rate, if applicable. */ FrameRateType frameRate; /** True if the transport is currently playing. */ bool isPlaying; /** True if the transport is currently recording. (When isRecording is true, then isPlaying will also be true). */ bool isRecording; }; /** Asks the host to return the current playback position. You can call this from your processBlock() method to get info about the time of the start of the block currently being processed. If the host can't supply this for some reason, this will return false, otherwise it'll fill in the structure passed in. */ bool JUCE_CALLTYPE getCurrentPositionInfo (CurrentPositionInfo& info); /** Returns the current sample rate. This can be called from your processBlock() method - it's not guaranteed to be valid at any other time, and may return 0 if it's unknown. */ double JUCE_CALLTYPE getSampleRate() const throw() { return sampleRate; } /** Returns the current typical block size that is being used. This can be called from your processBlock() method - it's not guaranteed to be valid at any other time. Remember it's not the ONLY block size that may be used when calling processBlock, it's just the normal one. The actual block sizes used may be larger or smaller than this, and will vary between successive calls. */ int JUCE_CALLTYPE getBlockSize() const throw() { return blockSize; } /** Returns the number of input channels that the host will be sending the filter. In your JucePluginCharacteristics.h file, you specify the number of channels that your plugin would prefer to get, and this method lets you know how many the host is actually going to send. Note that this method is only valid during or after the prepareToPlay() method call. Until that point, the number of channels will be unknown. */ int JUCE_CALLTYPE getNumInputChannels() const throw() { return numInputChannels; } /** Returns the number of output channels that the host will be sending the filter. In your JucePluginCharacteristics.h file, you specify the number of channels that your plugin would prefer to get, and this method lets you know how many the host is actually going to send. Note that this method is only valid during or after the prepareToPlay() method call. Until that point, the number of channels will be unknown. */ int JUCE_CALLTYPE getNumOutputChannels() const throw() { return numOutputChannels; } /** Returns the name of one of the input channels, as returned by the host. The host might not supply very useful names for channels, and this might be something like "1", "2", "left", "right", etc. */ const String getInputChannelName (const int channelIndex) const; /** Returns the name of one of the output channels, as returned by the host. The host might not supply very useful names for channels, and this might be something like "1", "2", "left", "right", etc. */ const String getOutputChannelName (const int channelIndex) const; //============================================================================== /** This returns a critical section that will automatically be locked while the host is calling the processBlock() method. Use it from your UI or other threads to lock access to variables that are used by the process callback, but obviously be careful not to keep it locked for too long, because that could cause stuttering playback. If you need to do something that'll take a long time and need the processing to stop while it happens, use the suspendProcessing() method instead. @see suspendProcessing */ const CriticalSection& JUCE_CALLTYPE getCallbackLock() const throw() { return callbackLock; } /** Enables and disables the processing callback. If you need to do something time-consuming on a thread and would like to make sure the audio processing callback doesn't happen until you've finished, use this to disable the callback and re-enable it again afterwards. E.g. @code void loadNewPatch() { suspendProcessing (true); ..do something that takes ages.. suspendProcessing (false); } @endcode If the host tries to make an audio callback while processing is suspended, the filter will return an empty buffer, but won't block the audio thread like it would do if you use the getCallbackLock() critical section to synchronise access. @see getCallbackLock */ void JUCE_CALLTYPE suspendProcessing (const bool shouldBeSuspended); //============================================================================== /** Creates the plugin's UI. This can return 0 if you want a UI-less plugin. Otherwise, the component should be created and set to the size you want it to be before returning it. Remember not to do anything silly like allowing your plugin to keep a pointer to the component that gets created - this may be deleted later without any warning, so that pointer could become a dangler. Use the getActiveEditor() method instead. The correct way to handle the connection between an editor component and its plugin is to use something like a ChangeBroadcaster so that the editor can register itself as a listener, and be told when a change occurs. This lets them safely unregister themselves when they are deleted. Here are a few assumptions to bear in mind when writing an editor: - Initially there won't be an editor, until the user opens one, or they might not open one at all. Your plugin mustn't rely on it being there. - An editor object may be deleted and a replacement one created again at any time. - It's safe to assume that an editor will be deleted before its filter. */ virtual AudioFilterEditor* JUCE_CALLTYPE createEditor() = 0; //============================================================================== /** Returns the active editor, if there is one. Bear in mind this can return 0, even if an editor has previously been opened. */ AudioFilterEditor* JUCE_CALLTYPE getActiveEditor() const throw() { return activeEditor; } /** Returns the active editor, or if there isn't one, it will create one. This may call createEditor() internally to create the component. */ AudioFilterEditor* JUCE_CALLTYPE createEditorIfNeeded(); //============================================================================== /** This must return the correct value immediately after the object has been created, and mustn't change the number of parameters later. */ virtual int JUCE_CALLTYPE getNumParameters() = 0; /** Returns the name of a particular parameter. */ virtual const String JUCE_CALLTYPE getParameterName (int parameterIndex) = 0; /** Called by the host to find out the value of one of the plugin's parameters. The host will expect the value returned to be between 0 and 1.0. This could be called quite frequently, so try to make your code efficient. */ virtual float JUCE_CALLTYPE getParameter (int parameterIndex) = 0; /** Returns the value of a parameter as a text string. */ virtual const String JUCE_CALLTYPE getParameterText (int parameterIndex) = 0; /** The host will call this method to change the value of one of the plugin's parameters. The host may call this at any time, including during the audio processing callback, so the plugin has to process this very fast and avoid blocking. If you want to set the value of a parameter internally, e.g. from your plugin editor, then don't call this directly - instead, use the setParameterNotifyingHost() method, which will also send a message to the host telling it about the change. If the message isn't sent, the host won't be able to automate your parameters properly. The value passed will be between 0 and 1.0. */ virtual void JUCE_CALLTYPE setParameter (int parameterIndex, float newValue) = 0; /** Your plugin can call this when it needs to change one of its parameters. This could happen when the editor or some other internal operation changes a parameter. This method will call the setParameter() method to change the value, and will then send a message to the host telling it about the change. */ void JUCE_CALLTYPE setParameterNotifyingHost (int parameterIndex, float newValue); //============================================================================== /** Returns the number of preset programs the plugin supports. The value returned must be valid as soon as this object is created, and must not change over its lifetime. This value shouldn't be less than 1. */ virtual int JUCE_CALLTYPE getNumPrograms() = 0; /** Returns the number of the currently active program. */ virtual int JUCE_CALLTYPE getCurrentProgram() = 0; /** Called by the host to change the current program. */ virtual void JUCE_CALLTYPE setCurrentProgram (int index) = 0; /** Must return the name of a given program. */ virtual const String JUCE_CALLTYPE getProgramName (int index) = 0; /** Called by the host to rename a program. */ virtual void JUCE_CALLTYPE changeProgramName (int index, const String& newName) = 0; //============================================================================== /** The host will call this method when it wants to save the plugin's internal state. This must copy any info about the plugin's state into the block of memory provided, so that the host can store this and later restore it using setStateInformation(). Note that there's also a getCurrentProgramStateInformation() method, which only stores the current program, not the state of the entire filter. See also the helper function copyXmlToBinary() for storing settings as XML. @see getCurrentProgramStateInformation */ virtual void JUCE_CALLTYPE getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0; /** The host will call this method if it wants to save the state of just the plugin's current program. Unlike getStateInformation, this should only return the current program's state. Not all hosts support this, and if you don't implement it, the base class method just calls getStateInformation() instead. If you do implement it, be sure to also implement getCurrentProgramStateInformation. @see getStateInformation, setCurrentProgramStateInformation */ virtual void JUCE_CALLTYPE getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData); /** This must restore the plugin's state from a block of data previously created using getStateInformation(). Note that there's also a setCurrentProgramStateInformation() method, which tries to restore just the current program, not the state of the entire filter. See also the helper function getXmlFromBinary() for loading settings as XML. @see setCurrentProgramStateInformation */ virtual void JUCE_CALLTYPE setStateInformation (const void* data, int sizeInBytes) = 0; /** The host will call this method if it wants to restore the state of just the plugin's current program. Not all hosts support this, and if you don't implement it, the base class method just calls setStateInformation() instead. If you do implement it, be sure to also implement getCurrentProgramStateInformation. @see setStateInformation, getCurrentProgramStateInformation */ virtual void JUCE_CALLTYPE setCurrentProgramStateInformation (const void* data, int sizeInBytes); //============================================================================== /** @internal */ class FilterNativeCallbacks { public: virtual ~FilterNativeCallbacks() {} virtual bool JUCE_CALLTYPE getCurrentPositionInfo (CurrentPositionInfo& info) = 0; virtual void JUCE_CALLTYPE informHostOfParameterChange (int index, float newValue) = 0; }; //============================================================================== /** Not for public use - this is called by the wrapper code before deleting an editor component. */ void JUCE_CALLTYPE editorBeingDeleted (AudioFilterEditor* const editor); /** Not for public use - this is called by the wrapper code to initialised the filter. */ void JUCE_CALLTYPE initialiseInternal (FilterNativeCallbacks* const); //============================================================================== juce_UseDebuggingNewOperator protected: //============================================================================== /** Helper function that just converts an xml element into a binary blob. Use this in your plugin's getStateInformation() method if you want to store its state as xml. Then use getXmlFromBinary() to reverse this operation and retrieve the XML from a binary blob. */ static void JUCE_CALLTYPE copyXmlToBinary (const XmlElement& xml, JUCE_NAMESPACE::MemoryBlock& destData); /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return an XmlElement object that the caller must delete when no longer needed. */ static XmlElement* JUCE_CALLTYPE getXmlFromBinary (const void* data, const int sizeInBytes); private: friend class JuceVSTWrapper; friend class JuceAU; friend class JuceAUView; friend class AudioFilterEditor; friend class AudioFilterStreamer; friend class JucePlugInProcess; CriticalSection callbackLock; bool suspended; double sampleRate; int blockSize, numInputChannels, numOutputChannels; StringArray outputNames, inputNames; FilterNativeCallbacks* callbacks; AudioFilterEditor* activeEditor; }; //============================================================================== /** Somewhere in the code for an actual plugin, you need to implement this function and make it create an instance of the plugin subclass that you're building. */ extern AudioFilterBase* JUCE_CALLTYPE createPluginFilter(); #ifdef _MSC_VER #pragma pack (pop) #endif #endif // __JUCE_AUDIOFILTERBASE_JUCEHEADER__
19d4e7d3ee9051e78585ab6f1b65b1df2055a859
6674ecfc4a2c0a3a5bdc45b458e7f18e9b134092
/examples/ClientProject/SimpleFramework/appAccel.ino
26ca8637ac471609fa3accbb9f4d8ddd80d3180b
[ "MIT" ]
permissive
AlexGoodyear/TTGO_TWatch_Library
0ab8b76b0d96cadcf5982bafc028bdf0ad6a5ac4
d982092b2700ba2a4deba8be38bf338ffde855c1
refs/heads/master
2022-12-05T03:26:52.905530
2020-08-21T19:28:45
2020-08-21T19:28:45
276,957,141
5
0
MIT
2020-08-12T10:32:06
2020-07-03T17:46:09
C
UTF-8
C++
false
false
684
ino
appAccel.ino
// Show the accelerometer working void appAccel() { ttgo->bma->begin(); ttgo->bma->enableAccel(); ttgo->tft->fillScreen(TFT_BLACK); int16_t x, y; int16_t xpos, ypos; Accel acc; while (!ttgo->getTouch(x, y)) { // Wait for touch to exit ttgo->bma->getAccel(acc); xpos = acc.x; ypos = acc.y; ttgo->tft->fillCircle(xpos / 10 + 119, ypos / 10 + 119, 10, TFT_RED); // draw dot delay(100); ttgo->tft->fillCircle(xpos / 10 + 119, ypos / 10 + 119, 10, TFT_BLACK); // erase previous dot } while (ttgo->getTouch(x, y)) {} // Wait for release to return to the clock ttgo->tft->fillScreen(TFT_BLACK); // Clear screen }
88938e5e2151a215e64c5bab2d3b7a7458d036db
4391a2d87df2e3de7b7ba7498661c8103c9e4b04
/HelloMix/src/window.h
6cb2c23e00e6c4519a9dcc00c67cbbdc15c1409a
[ "MIT" ]
permissive
jaredtao/QtOpenGL
a387ffb0bad9abc8f69988f45e3fdb14cb69cf9a
18184b6163e7d6c496737de795fc63fe1879f010
refs/heads/master
2023-05-13T11:09:27.393127
2023-04-26T07:17:13
2023-04-26T07:17:13
84,802,479
89
33
null
null
null
null
UTF-8
C++
false
false
1,395
h
window.h
#ifndef WINDOW_H #define WINDOW_H #include <QMainWindow> #include <QOpenGLBuffer> #include <QOpenGLFunctions> #include <QOpenGLShader> #include <QOpenGLShaderProgram> #include <QOpenGLTexture> #include <QOpenGLWidget> #include <QTime> class Window : public QOpenGLWidget , protected QOpenGLFunctions { Q_OBJECT public: Window(QWidget* parent = 0); ~Window(); protected: void initializeGL() override; void paintGL() override; void resizeGL(int w, int h) override; void timerEvent(QTimerEvent*) override; void keyPressEvent(QKeyEvent* event) override; void keyReleaseEvent(QKeyEvent* event) override; void mousePressEvent(QMouseEvent* event) override; void mouseMoveEvent(QMouseEvent* event) override; void wheelEvent(QWheelEvent* event) override; void calcFPS(); void updateFPS(qreal); void paintFPS(); void checkKey(); private: void makeObject(); void initShader(); void initTexture(); QOpenGLShaderProgram* program; QVector<QVector3D> vertices; QVector<QVector3D> cubePositions; QVector<QVector2D> coords; QVector3D cameraPos; QVector3D cameraFront; QVector3D cameraUp; QMatrix4x4 modelMat, viewMat, projectMat; QOpenGLTexture *texture1, *texture2; int verticesHandle, coordHandle; qreal mixPara; QTime m_time; qreal fps; qreal elapsed; qreal yaw, pitch; qreal aspect; bool keys[1024]; QPoint last; }; #endif // WINDOW_H
8cacc95197fa07565b52d561aaa6b8c295d04173
48c9e9213fa56b2e9d1af8be67211082aa02ea5b
/prj/VM2/Optim2/VM_EA.cpp
507dd0bdf5ce807118a8df16e7556a5c1557cd45
[]
no_license
0xABADCAFE/ancient-extropia-amiga68k
35ffc3eb1559c50a27536bd5c526b31368faab17
be56f2c66d92e556518ea2e35441977ca2fc4a7b
refs/heads/master
2020-03-16T10:39:54.735743
2018-05-11T17:18:12
2018-05-11T17:18:12
132,636,978
0
0
null
null
null
null
UTF-8
C++
false
false
13,217
cpp
VM_EA.cpp
//*****************************************************************// //** Description: eXtropia XSF Codec Virtual Machine **// //** First Started: 2002-03-08 **// //** Last Updated: **// //** Author Karl Churchill **// //** Copyright: (C)1998-2002, eXtropia Studios **// //** Serkan YAZICI, Karl Churchill **// //** All Rights Reserved. **// //*****************************************************************// #include "VMClass.hpp" ///////////////////////////////////////////////////////////////////// // // Effective address calculation // // When the ea funcs are called, instPtr points to the current // opcode word. During evaluation, any literal data or extension // words cause instPtr to be incremented. // // Upon completion, instPtr points to the word following the last // extension word/literal data: // // Before // // [ opcd ] [ ea 1 ] [ ea 2 ] [ ea 3 ] <- instPtr // [ ea 1 extension word ] // [ ea 2 extension word ] // [ instruction specific data ] // [ opcd ] [ ea 1 ] [ ea 2 ] [ ea 3 ] // // After // // [ opcd ] [ ea 1 ] [ ea 2 ] [ ea 3 ] // [ ea 1 extension word ] // [ ea 2 extension word ] // [ instruction specific data ] <- instPtr // [ opcd ] [ ea 1 ] [ ea 2 ] [ ea 3 ] // // In most cases there will not be any instruction soecific data // and instPtr points to the subsequent instruction // ///////////////////////////////////////////////////////////////////// #define EAOFFSET() *((sint32*)(++This->instPtr)) #if (X_ENDIAN == XA_BIGENDIAN) #define GETLITERAL(n) (((uint8*)(++This->instPtr))+(4U-n)) #define IRRO_BASEREG This->gpRegs[((uint8*)(This->instPtr))[3]] #define IRRO_OFSTREG() This->gpRegs[((uint8*)(This->instPtr))[2]].ValS32() #else #define GETLITERAL(n) ((uint8*)(++This->instPtr)) #define IRRO_BASEREG This->gpRegs[((uint8*)(This->instPtr))[0]] #define IRRO_OFSTREG() This->gpRegs[((uint8*)(This->instPtr))[1]].ValS32() #endif void* VMCORE::fR0(EAFARGS) { return This->gpRegs[0].Data(s); } void* VMCORE::fR1(EAFARGS) { return This->gpRegs[1].Data(s); } void* VMCORE::fR2(EAFARGS) { return This->gpRegs[2].Data(s); } void* VMCORE::fR3(EAFARGS) { return This->gpRegs[3].Data(s); } void* VMCORE::fR4(EAFARGS) { return This->gpRegs[4].Data(s); } void* VMCORE::fR5(EAFARGS) { return This->gpRegs[5].Data(s); } void* VMCORE::fR6(EAFARGS) { return This->gpRegs[6].Data(s); } void* VMCORE::fR7(EAFARGS) { return This->gpRegs[7].Data(s); } void* VMCORE::fR8(EAFARGS) { return This->gpRegs[8].Data(s); } void* VMCORE::fR9(EAFARGS) { return This->gpRegs[9].Data(s); } void* VMCORE::fR10(EAFARGS) { return This->gpRegs[10].Data(s); } void* VMCORE::fR11(EAFARGS) { return This->gpRegs[11].Data(s); } void* VMCORE::fR12(EAFARGS) { return This->gpRegs[12].Data(s); } void* VMCORE::fR13(EAFARGS) { return This->gpRegs[13].Data(s); } void* VMCORE::fR14(EAFARGS) { return This->gpRegs[14].Data(s); } void* VMCORE::fR15(EAFARGS) { return This->gpRegs[15].Data(s); } void* VMCORE::fR16(EAFARGS) { return This->gpRegs[16].Data(s); } void* VMCORE::fR17(EAFARGS) { return This->gpRegs[17].Data(s); } void* VMCORE::fR18(EAFARGS) { return This->gpRegs[18].Data(s); } void* VMCORE::fR19(EAFARGS) { return This->gpRegs[19].Data(s); } void* VMCORE::fR20(EAFARGS) { return This->gpRegs[20].Data(s); } void* VMCORE::fR21(EAFARGS) { return This->gpRegs[21].Data(s); } void* VMCORE::fR22(EAFARGS) { return This->gpRegs[22].Data(s); } void* VMCORE::fR23(EAFARGS) { return This->gpRegs[23].Data(s); } void* VMCORE::fR24(EAFARGS) { return This->gpRegs[24].Data(s); } void* VMCORE::fR25(EAFARGS) { return This->gpRegs[25].Data(s); } void* VMCORE::fR26(EAFARGS) { return This->gpRegs[26].Data(s); } void* VMCORE::fR27(EAFARGS) { return This->gpRegs[27].Data(s); } void* VMCORE::fR28(EAFARGS) { return This->gpRegs[28].Data(s); } void* VMCORE::fR29(EAFARGS) { return This->gpRegs[29].Data(s); } void* VMCORE::fR30(EAFARGS) { return This->gpRegs[30].Data(s); } void* VMCORE::fR31(EAFARGS) { return This->gpRegs[31].Data(s); } void* VMCORE::fIR0(EAFARGS) { return This->gpRegs[0].PtrU8(); } void* VMCORE::fIR1(EAFARGS) { return This->gpRegs[1].PtrU8(); } void* VMCORE::fIR2(EAFARGS) { return This->gpRegs[2].PtrU8(); } void* VMCORE::fIR3(EAFARGS) { return This->gpRegs[3].PtrU8(); } void* VMCORE::fIR4(EAFARGS) { return This->gpRegs[4].PtrU8(); } void* VMCORE::fIR5(EAFARGS) { return This->gpRegs[5].PtrU8(); } void* VMCORE::fIR6(EAFARGS) { return This->gpRegs[6].PtrU8(); } void* VMCORE::fIR7(EAFARGS) { return This->gpRegs[7].PtrU8(); } void* VMCORE::fIR8(EAFARGS) { return This->gpRegs[8].PtrU8(); } void* VMCORE::fIR9(EAFARGS) { return This->gpRegs[9].PtrU8(); } void* VMCORE::fIR10(EAFARGS) { return This->gpRegs[10].PtrU8(); } void* VMCORE::fIR11(EAFARGS) { return This->gpRegs[11].PtrU8(); } void* VMCORE::fIR12(EAFARGS) { return This->gpRegs[12].PtrU8(); } void* VMCORE::fIR13(EAFARGS) { return This->gpRegs[13].PtrU8(); } void* VMCORE::fIR14(EAFARGS) { return This->gpRegs[14].PtrU8(); } void* VMCORE::fIR15(EAFARGS) { return This->gpRegs[15].PtrU8(); } void* VMCORE::fIR16(EAFARGS) { return This->gpRegs[16].PtrU8(); } void* VMCORE::fIR17(EAFARGS) { return This->gpRegs[17].PtrU8(); } void* VMCORE::fIR18(EAFARGS) { return This->gpRegs[18].PtrU8(); } void* VMCORE::fIR19(EAFARGS) { return This->gpRegs[19].PtrU8(); } void* VMCORE::fIR20(EAFARGS) { return This->gpRegs[20].PtrU8(); } void* VMCORE::fIR21(EAFARGS) { return This->gpRegs[21].PtrU8(); } void* VMCORE::fIR22(EAFARGS) { return This->gpRegs[22].PtrU8(); } void* VMCORE::fIR23(EAFARGS) { return This->gpRegs[23].PtrU8(); } void* VMCORE::fIR24(EAFARGS) { return This->gpRegs[24].PtrU8(); } void* VMCORE::fIR25(EAFARGS) { return This->gpRegs[25].PtrU8(); } void* VMCORE::fIR26(EAFARGS) { return This->gpRegs[26].PtrU8(); } void* VMCORE::fIR27(EAFARGS) { return This->gpRegs[27].PtrU8(); } void* VMCORE::fIR28(EAFARGS) { return This->gpRegs[28].PtrU8(); } void* VMCORE::fIR29(EAFARGS) { return This->gpRegs[29].PtrU8(); } void* VMCORE::fIR30(EAFARGS) { return This->gpRegs[30].PtrU8(); } void* VMCORE::fIR31(EAFARGS) { return This->gpRegs[31].PtrU8(); } void* VMCORE::fLIR0(EAFARGS) { return This->gpRegs[0].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR1(EAFARGS) { return This->gpRegs[1].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR2(EAFARGS) { return This->gpRegs[2].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR3(EAFARGS) { return This->gpRegs[3].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR4(EAFARGS) { return This->gpRegs[4].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR5(EAFARGS) { return This->gpRegs[5].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR6(EAFARGS) { return This->gpRegs[6].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR7(EAFARGS) { return This->gpRegs[7].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR8(EAFARGS) { return This->gpRegs[8].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR9(EAFARGS) { return This->gpRegs[9].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR10(EAFARGS) { return This->gpRegs[10].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR11(EAFARGS) { return This->gpRegs[11].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR12(EAFARGS) { return This->gpRegs[12].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR13(EAFARGS) { return This->gpRegs[13].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR14(EAFARGS) { return This->gpRegs[14].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR15(EAFARGS) { return This->gpRegs[15].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR16(EAFARGS) { return This->gpRegs[16].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR17(EAFARGS) { return This->gpRegs[17].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR18(EAFARGS) { return This->gpRegs[18].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR19(EAFARGS) { return This->gpRegs[19].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR20(EAFARGS) { return This->gpRegs[20].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR21(EAFARGS) { return This->gpRegs[21].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR22(EAFARGS) { return This->gpRegs[22].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR23(EAFARGS) { return This->gpRegs[23].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR24(EAFARGS) { return This->gpRegs[24].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR25(EAFARGS) { return This->gpRegs[25].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR26(EAFARGS) { return This->gpRegs[26].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR27(EAFARGS) { return This->gpRegs[27].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR28(EAFARGS) { return This->gpRegs[28].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR29(EAFARGS) { return This->gpRegs[29].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR30(EAFARGS) { return This->gpRegs[30].PtrU8() + EAOFFSET(); } void* VMCORE::fLIR31(EAFARGS) { return This->gpRegs[31].PtrU8() + EAOFFSET(); } void* VMCORE::fLUIR0(EAFARGS) { uint8* &p = This->gpRegs[0].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR1(EAFARGS) { uint8* &p = This->gpRegs[1].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR2(EAFARGS) { uint8* &p = This->gpRegs[2].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR3(EAFARGS) { uint8* &p = This->gpRegs[3].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR4(EAFARGS) { uint8* &p = This->gpRegs[4].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR5(EAFARGS) { uint8* &p = This->gpRegs[5].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR6(EAFARGS) { uint8* &p = This->gpRegs[6].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR7(EAFARGS) { uint8* &p = This->gpRegs[7].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR8(EAFARGS) { uint8* &p = This->gpRegs[8].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR9(EAFARGS) { uint8* &p = This->gpRegs[9].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR10(EAFARGS) { uint8* &p = This->gpRegs[10].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR11(EAFARGS) { uint8* &p = This->gpRegs[11].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR12(EAFARGS) { uint8* &p = This->gpRegs[12].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR13(EAFARGS) { uint8* &p = This->gpRegs[13].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR14(EAFARGS) { uint8* &p = This->gpRegs[14].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR15(EAFARGS) { uint8* &p = This->gpRegs[15].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR16(EAFARGS) { uint8* &p = This->gpRegs[16].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR17(EAFARGS) { uint8* &p = This->gpRegs[17].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR18(EAFARGS) { uint8* &p = This->gpRegs[18].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR19(EAFARGS) { uint8* &p = This->gpRegs[19].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR20(EAFARGS) { uint8* &p = This->gpRegs[20].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR21(EAFARGS) { uint8* &p = This->gpRegs[21].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR22(EAFARGS) { uint8* &p = This->gpRegs[22].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR23(EAFARGS) { uint8* &p = This->gpRegs[23].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR24(EAFARGS) { uint8* &p = This->gpRegs[24].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR25(EAFARGS) { uint8* &p = This->gpRegs[25].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR26(EAFARGS) { uint8* &p = This->gpRegs[26].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR27(EAFARGS) { uint8* &p = This->gpRegs[27].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR28(EAFARGS) { uint8* &p = This->gpRegs[28].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR29(EAFARGS) { uint8* &p = This->gpRegs[29].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR30(EAFARGS) { uint8* &p = This->gpRegs[30].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fLUIR31(EAFARGS) { uint8* &p = This->gpRegs[31].PtrU8(); p += EAOFFSET(); return p; } void* VMCORE::fIRRO(EAFARGS) { This->instPtr++; return IRRO_BASEREG.PtrU8() + IRRO_OFSTREG(); } void* VMCORE::fIRROU(EAFARGS) { This->instPtr++; uint8* &p = IRRO_BASEREG.PtrU8(); p += IRRO_OFSTREG(); return p; } void* VMCORE::fCLONE1ST(EAFARGS) { return This->op[0].u8; } void* VMCORE::fCLONE2ND(EAFARGS) { return This->op[1].u8; } void* VMCORE::fCTR(EAFARGS) { return &This->countReg; } void* VMCORE::fDS(EAFARGS) { return ((uint8*)This->dataSectPtr) + EAOFFSET(); } void* VMCORE::fCDS(EAFARGS) { return ((uint8*)This->constSectPtr) + EAOFFSET(); } void* VMCORE::fLITERAL(EAFARGS) { return GETLITERAL(s);} #undef EAOFFSET #undef GETLITERAL #undef IRRO_BASEREG #undef IRRO_OFSTREG
ef47e2385864c17d761fcf658ec0217bcb5277d1
c0513a1f708dc928f558a44a87bc547da2bdd6ad
/实验2.cpp
52500b67f4769a8b55dbc1176caa2fb6e60e252a
[]
no_license
hhhhhxx/hello-world
1df5164c3b5a6c7dbe26a14ff125080ca146567a
a8848b930f131e2ba4a5edc8c73f38501d38a54a
refs/heads/main
2023-07-27T04:52:02.417645
2021-09-13T14:28:37
2021-09-13T14:28:37
403,952,058
0
1
null
2021-09-13T13:09:45
2021-09-07T11:27:29
C++
UTF-8
C++
false
false
163
cpp
实验2.cpp
#include <iostream> int main() { std::cout<<"chen bing cheng"; std::cout<<"cai yun hai"; std::cout<<"13 chen ze hua"; std::cout<<"cai wen xi"; return 0; }
523f01de830da3a230a3074471da6580b0511098
c3beae4f831421af6e788648133d4a2f37bfc1da
/src/Circle.hpp
d355c2990589a7c9bc0c4bafafc94aa2c3c18f6b
[]
no_license
CallumHoward/CirclePacking
38479fe4fb5f06f258c34c32f080fe33f45d1d9f
07fd85226c3d2fa9fb3ec0d6697ef7ea6dfb0844
refs/heads/master
2020-06-01T02:47:04.751010
2017-06-13T04:30:50
2017-06-13T04:30:50
94,059,721
0
0
null
null
null
null
UTF-8
C++
false
false
634
hpp
Circle.hpp
// // Circle.hpp // CirclePacking // // Created by Callum Howard on 11/6/17. // // #ifndef Circle_hpp #define Circle_hpp namespace ch { using namespace ci; using namespace ci::app; class Circle { public: Circle(float radius, const vec2 &center) : radius_{radius}, center_{center} {} void draw() const; void setRadius(float radius) { radius_ = radius; } void setCenter(vec2 center) { center_ = center; } inline bool within(const Area& a) const { return a.contains(center_); } private: float radius_; vec2 center_; }; } #endif /* Circle_hpp */
162df01a6af02c9f2dad77148b04dbbe5f79725d
88f5b3e51526b09bd2b329f0375e89e0c98e33ef
/logic_dcdf_score/DuoCaiDuoFuCfg.cpp
45739185c1555250f7c2929be88fbf92a37d7540
[]
no_license
xeonye/dderverdd
61ec4b8dbf365603ee351a949f5d5c621a46b199
34dacdee0382184e924354d7304038a7c9bae58a
refs/heads/master
2020-06-21T07:56:56.588277
2019-06-07T07:35:44
2019-06-07T07:35:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,857
cpp
DuoCaiDuoFuCfg.cpp
 // // Created by okMan on 2018/11/5. // #include "DuoCaiDuoFuCfg.h" #include "glog_wrapper.h" CDCDFCfg::CDCDFCfg() { } CDCDFCfg::~CDCDFCfg() { } void CDCDFCfg::LoadCfg() { acl::string buf; if (acl::ifstream::load("./script/DCDF_GAME_CFG.xml", &buf) == false) { LOG(WARNING) << "load DCDF_GAME_CFG.xml error: " << acl::last_serror(); return ; } acl::xml1 xml; xml.update(buf); //加载基本信息 LOG(WARNING) << "-------------------------------load basic info -----------------------------\n"; LoadBasicInfo(xml); //赔率表 LOG(WARNING) << "-------------------------------load pay table -----------------------------\n"; LoadPayTable(xml); //赔率反馈表 LOG(WARNING) << "-------------------------------load pay notify -----------------------------\n"; LoadPayNotify(xml); //免费游戏类型配置 LOG(WARNING) << "-------------------------------load free game type -----------------------------\n"; LoadFreeGameTypeCfg(xml); //免费游戏类型配置 神秘精选(系统随机选中前4种组合的免费次数和框格大小,再组合成免费奖励) LOG(WARNING) << "-------------------------------load free mystery pick -----------------------------\n"; LoadFreeMysteryPickCfg(xml); //押注底分 与 底分总押注 LOG(WARNING) << "-------------------------------load stake -----------------------------\n"; LoadStakeCfg(xml); //游戏图标配置 LOG(WARNING) << "-------------------------------load game icon -----------------------------\n"; LoadGameIconCfg(xml); //集福聚宝配置--将池金币增加配置 LOG(WARNING) << "-------------------------------load bonus jackpot -----------------------------\n"; LoadBonusJackpotCfg(xml); //将池开奖配置 LOG(WARNING) << "-------------------------------load bonus active -----------------------------\n"; LoadBonusActiveCfg(xml); } void CDCDFCfg::LoadBasicInfo(acl::xml1& xml) { acl::xml_node* pRoot = xml.getFirstElementByTag("Root"); if (pRoot) { acl::xml_node* pChild = pRoot->first_child(); while (pChild) { const char *pChildTag = pChild->tag_name(); if (pChildTag == NULL) { pChild = pRoot->next_child(); continue; } if (strcmp("spinInterval", pChildTag) == 0) { const char* pSpinInterval = pChild->text(); m_wSpinInterval = (CT_WORD)atoi(pSpinInterval); LOG(WARNING) << "spinInterval: " << m_wSpinInterval; } pChild = pRoot->next_child(); } } } void CDCDFCfg::LoadPayTable(acl::xml1& xml) { acl::xml_node* pPayTable = xml.getFirstElementByTag("iconPayTable"); if (pPayTable) { acl::xml_node* child = pPayTable->first_child(); while (child) { tagPayTable payTable; memset(&payTable, 0, sizeof(tagPayTable)); const acl::xml_attr *attr = child->first_attr(); while (attr) { //printf("%s=\"%s\"\r\n", attr->get_name(), attr->get_value()); if (strcmp("iconID", attr->get_name()) == 0) { payTable.cbIconId = (CT_BYTE)atoi(attr->get_value()); } else if (strcmp("five", attr->get_name()) == 0) { payTable.wFivePayMult = (CT_WORD)atoi(attr->get_value()); } else if (strcmp("four", attr->get_name()) == 0) { payTable.wFourPayMult = (CT_WORD)atoi(attr->get_value()); } else if (strcmp("three", attr->get_name()) == 0) { payTable.wThreePayMult = (CT_WORD)atoi(attr->get_value()); } else { LOG(ERROR) << "get error icon pay table. attr name: " << attr->get_name(); attr = child->next_attr(); continue; } attr = child->next_attr(); } m_payTable[payTable.cbIconId - 1] = payTable; LOG(WARNING) << "pay icon id: " << (int) payTable.cbIconId << ", five: " << payTable.wFivePayMult << ", four: " << payTable.wFourPayMult << ", three: " << payTable.wThreePayMult; child = pPayTable->next_child(); } } } void CDCDFCfg::LoadPayNotify(acl::xml1& xml) { acl::xml_node* pPayNotify = xml.getFirstElementByTag("payNotify"); if (pPayNotify) { acl::xml_node* child = pPayNotify->first_child(); while (child) { tagPayNotify payNotify; const acl::xml_attr *attr = child->first_attr(); while (attr) { if (strcmp("id", attr->get_name()) == 0) { payNotify.cbNotifyId = (CT_BYTE)atoi(attr->get_value()); } else if (strcmp("payoutMin", attr->get_name()) == 0) { payNotify.dwPayoutMin = (CT_DWORD)atoi(attr->get_value()); } else if (strcmp("payOutMax", attr->get_name()) == 0) { payNotify.dwPayoutMax = (CT_DWORD)atoi(attr->get_value()); } else if (strcmp("desc", attr->get_name()) == 0) { //这个属性值不读取 } else { LOG(ERROR) << "get error pay notify. attr name: " << attr->get_name(); attr = child->next_attr(); continue; } attr = child->next_attr(); } m_vecPayNotify.push_back(payNotify); LOG(WARNING) << "pay notify, id: " << (int)payNotify.cbNotifyId << ", payoutMin: " << payNotify.dwPayoutMin << ", payOutMax: " << payNotify.dwPayoutMax; child = pPayNotify->next_child(); } } } void CDCDFCfg::LoadFreeGameTypeCfg(acl::xml1& xml) { acl::xml_node* pNode = xml.getFirstElementByTag("freeGameTypeCfg"); if (pNode) { m_mFreeTypeCfg.clear(); acl::xml_node* child = pNode->first_child(); while (child) { tagFreeGameTypeInfoCfg freeGameTypeInfoCfg; memset(&freeGameTypeInfoCfg, 0, sizeof(freeGameTypeInfoCfg)); const acl::xml_attr *attr = child->first_attr(); while (attr) { //printf("%s=\"%s\"\r\n", attr->get_name(), attr->get_value()); if (strcmp("cbFreeGameType", attr->get_name()) == 0) { freeGameTypeInfoCfg.cbFreeGameType = (CT_BYTE)atoi(attr->get_value()); } else if (strcmp("cbRows", attr->get_name()) == 0) { freeGameTypeInfoCfg.cbRows = (CT_BYTE)atoi(attr->get_value()); } else if (strcmp("dwFreeGameTimes", attr->get_name()) == 0) { freeGameTypeInfoCfg.dwFreeGameTimes = (CT_DWORD)atoi(attr->get_value()); } else { LOG(ERROR) << "get error icon pay table. attr name: " << attr->get_name(); attr = child->next_attr(); continue; } attr = child->next_attr(); } LOG(WARNING) << "cbFreeGameType: " << (int) freeGameTypeInfoCfg.cbFreeGameType << ", cbRows: " << (int)freeGameTypeInfoCfg.cbRows << ", dwFreeGameTimes: " << freeGameTypeInfoCfg.dwFreeGameTimes; m_mFreeTypeCfg.insert(std::make_pair(freeGameTypeInfoCfg.cbFreeGameType, freeGameTypeInfoCfg)); child = pNode->next_child(); } } } void CDCDFCfg::LoadFreeMysteryPickCfg(acl::xml1& xml) { acl::xml_node* pfreeGameCfg = xml.getFirstElementByTag("freeGameMysteryPick"); if (pfreeGameCfg) { m_vMysteryPickCfg.clear(); CT_WORD wTotalRowProba = 0; acl::xml_node* pItemRows= pfreeGameCfg->first_child(); while (pItemRows) { tagMysteryPickCfg mysteryPickCfg; memset(&mysteryPickCfg, 0, sizeof(mysteryPickCfg)); const char* pRows = pItemRows->attr_value("cbRows"); if (!pRows) { LOG(ERROR) << "LoadFreeMysteryPickCfg, can not find row"; break; } mysteryPickCfg.cbRows = (CT_BYTE)atoi(pRows); const char* pProba = pItemRows->attr_value("wProba"); if (!pProba) { LOG(ERROR) << "LoadFreeMysteryPickCfg, can not find Proba"; break; } mysteryPickCfg.wProba = (CT_WORD)atoi(pProba); LOG(WARNING) << "reeGameMysteryPick cbRows:" << (int)mysteryPickCfg.cbRows << " wProba: " << (int)mysteryPickCfg.wProba; wTotalRowProba += mysteryPickCfg.wProba; acl::xml_node* child = pItemRows->first_child(); CT_FLOAT fTotalTimesProba = 0; while (child) { tagMysteryPickTimesCfg pickTimesCfg; memset(&pickTimesCfg, 0, sizeof(pickTimesCfg)); const acl::xml_attr *attr = child->first_attr(); while (attr) { if (strcmp("cbTimes", attr->get_name()) == 0) { pickTimesCfg.cbTimes = (CT_BYTE)atoi(attr->get_value()); } else if (strcmp("fProba", attr->get_name()) == 0) { pickTimesCfg.fProba = (CT_FLOAT)atof(attr->get_value()); fTotalTimesProba += pickTimesCfg.fProba; } else { LOG(ERROR) << "get error pickTimesCfg case cfg. attr name: " << attr->get_name(); attr = child->next_attr(); continue; } attr = child->next_attr(); } LOG(WARNING) << "cbTimes:" << (int)pickTimesCfg.cbTimes << " fProba: " << pickTimesCfg.fProba; child = pItemRows->next_child(); mysteryPickCfg.vMysteryPickTimes.push_back(pickTimesCfg); } if((CT_WORD)fTotalTimesProba != 100) { LOG(ERROR) << "LoadFreeMysteryPickCfg cbTimes proba Sum != 100"; } m_vMysteryPickCfg.push_back(mysteryPickCfg); pItemRows = pfreeGameCfg->next_child(); } if(100 != wTotalRowProba) { LOG(ERROR) << "LoadFreeMysteryPickCfg cbRows proba Sum != 100"; } } } void CDCDFCfg::LoadStakeCfg(acl::xml1& xml) { acl::xml_node* pNode = xml.getFirstElementByTag("stakeTable"); if (pNode) { m_vStakeCfg.clear(); acl::xml_node* child = pNode->first_child(); while (child) { tagStakeCfg stakeCfg; memset(&stakeCfg, 0, sizeof(stakeCfg)); const acl::xml_attr *attr = child->first_attr(); while (attr) { //printf("%s=\"%s\"\r\n", attr->get_name(), attr->get_value()); if (strcmp("betIndex", attr->get_name()) == 0) { stakeCfg.cbBetIndex = (CT_BYTE)atoi(attr->get_value()); } else if (strcmp("betMultiplier", attr->get_name()) == 0) { stakeCfg.wBetMultiplier = (CT_WORD)atoi(attr->get_value()); } else if (strcmp("betBaseStake", attr->get_name()) == 0) { stakeCfg.wBetBaseStake = (CT_WORD)atoi(attr->get_value()); } else if (strcmp("betTotalStake", attr->get_name()) == 0) { stakeCfg.llBetTotalStake = atoll(attr->get_value()); } else { LOG(ERROR) << "get error icon tagStakeCfg. attr name: " << attr->get_name(); attr = child->next_attr(); continue; } attr = child->next_attr(); } LOG(WARNING) << "betIndex: " << (int) stakeCfg.cbBetIndex << ", betMultiplier: " << (int)stakeCfg.wBetMultiplier << ", betBaseStake: " << stakeCfg.wBetBaseStake << ", betTotalStake:" << stakeCfg.llBetTotalStake; m_vStakeCfg.push_back(stakeCfg); child = pNode->next_child(); } } } void CDCDFCfg::LoadGameIconCfg(acl::xml1& xml) { acl::xml_node* pGameIconCfg = xml.getFirstElementByTag("gameIconCfg"); if (pGameIconCfg) { m_mGameIconCfg.clear(); acl::xml_node* pGameItem= pGameIconCfg->first_child(); while (pGameItem) { int iReelIndex = INVALID_CHAIR; const char* pReelIndex = pGameItem->attr_value("reelIndex"); if (!pReelIndex) { LOG(ERROR) << "LoadGameIconCfg, can not find reelIndex"; break; } iReelIndex = (CT_BYTE)atoi(pReelIndex); acl::xml_node* child = pGameItem->first_child(); if(iReelIndex < 0 || iReelIndex > 4) { LOG(ERROR) << "LoadGameIconCfg, reelIndex error:" << iReelIndex; break; } std::vector<tagGameIconCfg> & vGameIcon = m_mGameIconCfg[iReelIndex]; while (child) { tagGameIconCfg gameIconCfg; memset(&gameIconCfg, 0, sizeof(gameIconCfg)); const acl::xml_attr *attr = child->first_attr(); std::vector<std::string> vecScatRatio; while (attr) { if (strcmp("StripColumnID", attr->get_name()) == 0) { gameIconCfg.cbStripColumnID = (CT_BYTE)atoi(attr->get_value()); } else if (strcmp("indexCounts", attr->get_name()) == 0) { gameIconCfg.wIndexCounts = (CT_WORD)atoi(attr->get_value()); } else if(strcmp("iconReelInfo", attr->get_name()) == 0) { vecScatRatio.clear(); stringSplit(attr->get_value(), ";", vecScatRatio); for (CT_DWORD i = 0; i < vecScatRatio.size(); ++i) { gameIconCfg.vIconIDInfo.push_back((CT_BYTE)atoi(vecScatRatio[i].c_str())); } } else { LOG(ERROR) << "get error LoadGameIconCfg case cfg. attr name: " << attr->get_name(); attr = child->next_attr(); continue; } attr = child->next_attr(); } child = pGameItem->next_child(); LOG(WARNING) << "iReelIndex: " << iReelIndex << ", StripColumnID: " << (int)gameIconCfg.cbStripColumnID << ", IndexCounts: " << (int)gameIconCfg.wIndexCounts << ", iconReelInfo-Len:" << vecScatRatio.size(); vGameIcon.push_back(gameIconCfg); } pGameItem = pGameIconCfg->next_child(); } } } void CDCDFCfg::LoadBonusJackpotCfg(acl::xml1& xml) { acl::xml_node* pNode = xml.getFirstElementByTag("bonusJackpot"); if (pNode) { const char* pBaseStake = pNode->attr_value("baseStake"); if (!pBaseStake) { LOG(ERROR) << "LoadBonusJackpotCfg, can not find baseStake"; return; } m_BonusJackpotCfg.cbBaseStake = (CT_BYTE) atoi(pBaseStake); const char* pBaseTotalStake = pNode->attr_value("baseTotalStake"); if (!pBaseTotalStake) { LOG(ERROR) << "LoadBonusJackpotCfg, can not find pBaseTotalStake"; return; } m_BonusJackpotCfg.wBaseTotalStake = (CT_BYTE) atoi(pBaseTotalStake); m_BonusJackpotCfg.vBonusInfo.clear(); acl::xml_node* child = pNode->first_child(); while (child) { tagBonusJackpotTable jackpotTable; memset(&jackpotTable, 0, sizeof(jackpotTable)); const acl::xml_attr *attr = child->first_attr(); while (attr) { //printf("%s=\"%s\"\r\n", attr->get_name(), attr->get_value()); if (strcmp("jackpotIndex", attr->get_name()) == 0) { jackpotTable.cbIndex = (CT_BYTE)atoi(attr->get_value()); } else if (strcmp("jackpotName", attr->get_name()) == 0) { strncmp(jackpotTable.szName, attr->get_value(), sizeof(jackpotTable.szName)); } else if (strcmp("baseValue", attr->get_name()) == 0) { jackpotTable.llBaseValue = atoll(attr->get_value()); } else if (strcmp("plusValue", attr->get_name()) == 0) { jackpotTable.fPlusValue = atof(attr->get_value()); } else { LOG(ERROR) << "get error icon LoadBonusJackpotCfg. attr name: " << attr->get_name(); attr = child->next_attr(); continue; } attr = child->next_attr(); } LOG(WARNING) << "jackpotIndex: " << (int) jackpotTable.cbIndex << ", jackpotName: " << jackpotTable.szName << ", baseValue: " << jackpotTable.llBaseValue << ", plusValue:" << jackpotTable.fPlusValue; m_BonusJackpotCfg.vBonusInfo.push_back(jackpotTable); child = pNode->next_child(); } } } void CDCDFCfg::LoadBonusActiveCfg(acl::xml1& xml) { acl::xml_node* pNode = xml.getFirstElementByTag("bonusActive"); if (pNode) { const char* pCollectCounts = pNode->attr_value("collectCounts"); if (!pCollectCounts) { LOG(ERROR) << "LoadBonusActiveCfg, can not find baseStake"; return; } m_BonusActiveCfg.dwCollectCounts = (CT_DWORD)atol(pCollectCounts); const char* pIsBless = pNode->attr_value("isBless"); if (!pIsBless) { LOG(ERROR) << "LoadBonusActiveCfg, can not find pIsBless"; return; } m_BonusActiveCfg.bIsBless = (CT_BOOL)atoi(pIsBless); const char* pTriggerProb = pNode->attr_value("triggerProb"); if (!pTriggerProb) { LOG(ERROR) << "LoadBonusActiveCfg, can not find pBaseTotalStake"; return; } m_BonusActiveCfg.fTriggerProb = atof(pTriggerProb); m_BonusActiveCfg.vBonusInfo.clear(); acl::xml_node* child = pNode->first_child(); while (child) { tagBonusActiveTable activeTable; memset(&activeTable, 0, sizeof(activeTable)); const acl::xml_attr *attr = child->first_attr(); while (attr) { //printf("%s=\"%s\"\r\n", attr->get_name(), attr->get_value()); if (strcmp("jackpotIndex", attr->get_name()) == 0) { activeTable.cbJackpotIndex = (CT_BYTE)atoi(attr->get_value()); } else if (strcmp("triggerWeight", attr->get_name()) == 0) { activeTable.wTriggerWeight = atoi(attr->get_value()); } else { LOG(ERROR) << "get error icon LoadBonusActiveCfg. attr name: " << attr->get_name(); attr = child->next_attr(); continue; } attr = child->next_attr(); } LOG(WARNING) << "jackpotIndex: " << (int) activeTable.cbJackpotIndex << ", triggerWeight: " << activeTable.wTriggerWeight; m_BonusActiveCfg.vBonusInfo.push_back(activeTable); child = pNode->next_child(); } } }
c1b21d253239cfb5c1560b678995d80d1c0d48d5
636c5faea1a509006e7730eaeb632246e7450b71
/Arduino Codes/AngleTimeCalibration/AngleTimeCalibration.ino
efa7122758753c08701533ca7547601909ef2204
[]
no_license
ahxmeds/bachelors-thesis-project
8896bc7b3b332fdb345aba10ceca759e7ecb5a96
0bd2703b680b4d73c011f7c4de9e76815a1ce2fd
refs/heads/master
2022-09-11T22:26:05.291845
2019-04-08T07:35:49
2019-04-08T07:35:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,180
ino
AngleTimeCalibration.ino
#include<AFMotor.h> AF_DCMotor LeftMotor(2); AF_DCMotor RightMotor(1); int velocity = 200; void setup() { Serial.begin(9600); randomSeed(analogRead(A0)); } int time = 700; void loop() { delay(1000); TurnLeft(time); delay(500000); } void TurnRight(int ThetaTime) { LeftMotor.setSpeed(255); RightMotor.setSpeed(255); LeftMotor.run(FORWARD); RightMotor.run(BACKWARD); delay(ThetaTime); LeftMotor.run(RELEASE); RightMotor.run(RELEASE); delay(10); } void TurnLeft(int ThetaTime) { LeftMotor.setSpeed(255); RightMotor.setSpeed(255); LeftMotor.run(BACKWARD); RightMotor.run(FORWARD); delay(ThetaTime); LeftMotor.run(RELEASE); RightMotor.run(RELEASE); delay(10); } void MoveForward(int DeltaTime) { LeftMotor.setSpeed(velocity); RightMotor.setSpeed(velocity); LeftMotor.run(FORWARD); RightMotor.run(FORWARD); delay(DeltaTime); LeftMotor.run(RELEASE); RightMotor.run(RELEASE); delay(10); } void MoveBackward() { LeftMotor.setSpeed(velocity); RightMotor.setSpeed(velocity); LeftMotor.run(BACKWARD); RightMotor.run(BACKWARD); delay(700); LeftMotor.run(RELEASE); RightMotor.run(RELEASE); delay(10); }
6b259117991c6199ed1e85f3ae711ea66df59415
7ee32ddb0cdfdf1993aa4967e1045790690d7089
/Tuenti Challenge/2013/Tuenti13Problem13.cpp
f2736bb1b655c7b9f1538ea8ccd40eb32d5b20d7
[]
no_license
ajimenezh/Programing-Contests
b9b91c31814875fd5544d63d7365b3fc20abd354
ad47d1f38b780de46997f16fbaa3338c9aca0e1a
refs/heads/master
2020-12-24T14:56:14.154367
2017-10-16T21:05:01
2017-10-16T21:05:01
11,746,917
1
2
null
null
null
null
UTF-8
C++
false
false
2,332
cpp
Tuenti13Problem13.cpp
#include <iostream> #include <sstream> #include <vector> #include <string> #include <algorithm> #include <utility> #include <set> #include <map> #include <deque> #include <queue> #include <cmath> #include <cstdlib> #include <ctime> #include <cstdio> #include <stdio.h> using namespace std; #define fo(i,n) for(int i=0; i<(int)n; i++) #define rep(it,s) for(__typeof((s).begin()) it=(s).begin();it!=(s).end();it++) #define mp(a,b) make_pair(a,b) #define pb(x) push_back(x) #define pii pair<int,int> #define MAXN 1000010 int tree[4*MAXN]; void update(int id, int l, int r, int ll, int rr, int val) { if (l>rr || r<ll) return; if (l>=ll && r<=rr) { tree[id] = val; return; } int h = (l+r)/2; update(2*id,l,h,ll,rr,val); update(2*id+1,h+1,r,ll,rr,val); tree[id] = max(tree[2*id],tree[2*id+1]); } int get(int id, int l, int r, int ll, int rr) { if (l>rr || r<ll || ll>rr) return -1; if (l>=ll && r<=rr) { return tree[id]; } int h = (l+r)/2; return max(get(2*id,l,h,ll,rr),get(2*id+1,h+1,r,ll,rr)); } int t; int n; int m; int v[MAXN]; int w[MAXN]; int l[MAXN]; int r[MAXN]; int main() { //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); cin>>t; for (int tt=0; tt<t; tt++) { scanf("%d%d",&n,&m); for (int i=0; i<n; i++) scanf("%d",v+i); for (int i=0; i<=4*n; i++) tree[i] = -1; for (int i=0; i<n; i++) { if (i!=0 && v[i]==v[i-1]) { w[i] = w[i-1] + 1; } else { w[i] = 1; } } for (int i=0; i<n; i++) update(1,1,n,i+1,i+1,w[i]); l[0] = 0; for (int i=1; i<n; i++) { if (v[i]==v[i-1]) { l[i] = l[i-1]; } else l[i] = i; } r[n-1] = n-1; for (int i=n-2; i>=0; i--) { if (v[i]==v[i+1]) { r[i] = r[i+1]; } else r[i] = i; } printf("Test case #%d\n",tt+1); for (int i=0; i<m; i++) { int a,b; scanf("%d%d",&a,&b); a--; b--; int k = get(1,1,n,r[a]+2,l[b]); k = max(k,r[a]-a+1); k = max(k,b-l[b]+1); printf("%d\n",k); } } return 0; }
603614cf749cc21bc494bcf33d13db6c247e9892
c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac
/src/Engine/Event/EventContainer.h
c89577fa8c221b862975c5b46b03c7026ce61556
[]
no_license
ptrefall/smn6200fluidmechanics
841541a26023f72aa53d214fe4787ed7f5db88e1
77e5f919982116a6cdee59f58ca929313dfbb3f7
refs/heads/master
2020-08-09T17:03:59.726027
2011-01-13T22:39:03
2011-01-13T22:39:03
32,448,422
1
0
null
null
null
null
UTF-8
C++
false
false
809
h
EventContainer.h
#pragma once #include "IEventManager.h" #include <ClanLib/src/API/core.h> #include <vector> namespace Engine { namespace Events { class EventContainer { public: EventContainer(IEventManager *EventMgr) : EventMgr(EventMgr) {} ~EventContainer() {} template<class Class, class Param1> void Connect(const CL_String &eventName, Class *self, void(Class::*func)(Param1)) { slots.push_back(EventMgr->GetEvent(eventName).connect(self, func)); } template<class Class, class Param1, class UserData> void Connect(const CL_String &eventName, Class *self, void(Class::*func)(Param1, UserData), UserData userData) { slots.push_back(EventMgr->GetEvent(eventName).connect(self, func, userData)); } private: std::vector<CL_Slot> slots; IEventManager *EventMgr; }; } }
4c462f1e66d06d760fe04ef96c5ee11c155f3310
a28c39e4198d9eb92c74fb20997d478e9f91b13c
/invModel/journal.cpp
5ff05f879d89dd3988bb6167bf658d9982b4c547
[]
no_license
MafuraG/inventory
2db57a621ba62653dacd5295e3f210e79e352959
d07f0ee611906a18a70b798c025474126cdcc8dc
refs/heads/master
2021-01-21T14:25:14.257270
2016-07-07T10:42:28
2016-07-07T10:42:28
59,742,343
0
0
null
null
null
null
UTF-8
C++
false
false
3,166
cpp
journal.cpp
#include "journal.h" #include <QDebug> Journal::Journal() { } unsigned int Journal::inventoryID() const { return m_inventoryID; } void Journal::setInventoryID(unsigned int inventoryID) { m_inventoryID = inventoryID; } QString Journal::date() const { return m_date; } void Journal::setDate(const QString &date) { m_date = date; } unsigned int Journal::statusID() const { return m_statusID; } void Journal::setStatusID(unsigned int statusID) { m_statusID = statusID; } QString Journal::comment() const { return m_comment; } void Journal::setComment(const QString &comment) { m_comment = comment; } QHash<QString, QVariant> Journal::dbValuesImplementation() { QHash <QString,QVariant> keyVals; keyVals[INVENTORYID] = inventoryID(); keyVals[DATE] = date(); keyVals[STATUSID] = statusID(); keyVals[Name] = name(); keyVals[ID] = id(); keyVals[COMMENT] = comment(); return keyVals; } QString Journal::getEntityNameImplementation() { return Journal::ENTITYNAME; } void Journal::setDbValuesImplementation(const QHash<QString, QVariant> &dbValues) { if (dbValues.count() > 0) { setId(dbValues[ID].toUInt()); qDebug()<<dbValues[ID]<<"to Uint"<<dbValues[ID].toUInt(); setName(dbValues[Name].toString()); setDate(dbValues[DATE].toString()); setInventoryID(dbValues[INVENTORYID].toUInt()); setStatusID(dbValues[STATUSID].toUInt()); setComment(dbValues[COMMENT].toString()); } } QVariant Journal::dataImplementation(const unsigned int col) { QHash<QString, QVariant> dBvalues = dbValues(); if (col == 0 ){ //ID return dBvalues[ID]; } if (col == 1 ){ //Name return dBvalues[Name]; } if (col == 2 ){ //Date return dBvalues[DATE]; } if (col == 3) { //Inventory ID return dBvalues[INVENTORYID]; } if (col == 4){ //Status ID return dBvalues[STATUSID]; } if (col == 5){ //COMMENT return dBvalues[COMMENT]; } return QVariant(); } bool Journal::setDataImplementation(const unsigned int col, QVariant value) { QHash<QString, QVariant> dBvalues = dbValues(); bool success = false; if (col == 0 ){ //ID dBvalues[ID] = value; success = true; } if (col == 1 ){ //Name dBvalues[Name] = value; success = true; } if (col == 2 ){ //Date dBvalues[DATE] = value; success = true; } if (col == 3) { //Inventory ID dBvalues[INVENTORYID] = value; success = true; } if (col == 4){ //Status ID dBvalues[STATUSID] = value; success = true; } if (col == 5){ //COMMENT dBvalues[COMMENT] = value; success = true; } if (success == true) { setDbValues(dBvalues); } return success; } QString Journal::COMMENT = "comment"; QString Journal::DATE = "date_"; QString Journal::INVENTORYID = "inventory_id"; QString Journal::STATUSID = "status_id"; QString Journal::ENTITYNAME = "journal";
7c711465d48be26fee4f4f1940909b038059d96d
12c51e72393d1adc42d6c0011e2dbd76335fb01e
/net_protocol.cpp
b87c2dd204e5fabb482a9ee884d7541bef51878b
[]
no_license
yifu/chess
f7b12d577930badad8f107e02847449a42ca02ff
89ff3cc3e4cc9cdd63e414455138bbfcab2393b9
refs/heads/master
2021-03-16T10:21:59.972559
2015-11-02T21:30:05
2015-11-02T21:30:05
41,814,353
0
0
null
null
null
null
UTF-8
C++
false
false
29
cpp
net_protocol.cpp
#include "net_protocol.hpp"
f2b53eebb7e4852ca33c94f9617a61f308277ddb
084a3f4b50c56c03657e6838b2f7e48b05f2fd2d
/_cpp_basic/cmake_example/message.cpp
3921d03b356a55f2a988687100cc12899a117427
[]
no_license
roytwu/cpp
e488c745979dd19abb45efb2fe68dc58656e9c33
feca92ecd32284d7598d59c6a576cf79cf611f09
refs/heads/master
2022-06-09T02:07:01.220096
2020-05-05T19:47:34
2020-05-05T19:47:34
134,349,163
0
0
null
null
null
null
UTF-8
C++
false
false
243
cpp
message.cpp
#include <iosfwd> #include <iostream> #include <string> #include "message.hpp" using std::ostream; using std::endl; ostream &Message::printObject(ostream &os) { os << "This is my very nice message..." << endl; os << message_; return os; }
aaed61fe3abd5765eb63dbb0917c3ca9f94161a8
a926ee00e68ea41e8a0821e261722428f433ced7
/inclusiveJetTrackCorrelation2015/jetShapeMacros/plotShapes.cxx
6ead7825a6f490f13977ce5bc08dcfca44b9705d
[]
no_license
Taburis/cmsProjects
57b4335afee551d8b44cdbdc4939496b8fcf71d8
0bec9c01cac099046b9f817e7fd6b1a763df9200
refs/heads/master
2021-01-12T10:16:21.514881
2018-12-13T16:59:42
2018-12-13T16:59:42
76,406,070
0
1
null
null
null
null
UTF-8
C++
false
false
4,875
cxx
plotShapes.cxx
#include "/Users/tabris/cmsProjects/Toolkit/stackHist.h" #include "hallie_input.h" bool donorm=0; void subplot( stackHist* st, int ii, int nf); TLatex tl = TLatex(); TString centLabel[] = {"Cent:0-10%", "Cent:10-30%", "Cent:30-50%", "Cent:50-100%"}; TString jetPtLabel[] = {"120<jetPt<150", "150<jetPt<200", "jetPt>200"}; TString legtxt[] = {"0.7<p_{T}^{assoc.}<1 GeV", "1<p_{T}^{assoc.}<2 GeV", "2<p_{T}^{assoc.}<3 GeV", "3<p_{T}^{assoc.}<4 GeV", "4<p_{T}^{assoc.}<8 GeV", "8<p_{T}^{assoc.}<12 GeV", "12<p_{T}^{assoc.}<16 GeV", "16<p_{T}^{assoc.}<20 GeV", "20<p_{T}^{assoc.}<999GeV"}; void plotShapes(){ getInput_Hallie(); TFile* f[3]; f[0] = TFile::Open("jetShapeSignal_jtPt120_150.root"); f[1] = TFile::Open("jetShapeSignal_jtPt150_200.root"); // f[2] = TFile::Open("jetShapeSignal_jtPtAbove200.root"); f[2] = TFile::Open("jetShapeSignal_alljtPt.root"); //f[2] = TFile::Open("jetShapeSignal_jtPt200_999_meptrig60.root"); stackHist *st[4][3]; TH1D* jetShape[4][9][3]; TH1D* jetShape_tot[4][3]; for(int i=0; i<3;++i){ for( int jcent=0; jcent<4;jcent++){ st[jcent][i] = new stackHist(Form("st%d_%d",jcent, i)); jetShape_tot[jcent][i]=(TH1D*)f[i]->Get(Form("jetShape_total_%d",jcent)); jetShape_tot[jcent][i]->SetName(Form("jetShape_total_%d_%d",jcent,i)); for(int jtrkpt=0;jtrkpt<9; jtrkpt++){ jetShape[jcent][jtrkpt][i]=(TH1D*)f[i]->Get(Form("jetShape_%d_%d",jcent,jtrkpt+1)); jetShape[jcent][jtrkpt][i]->SetName(Form("jetShape_%d_%d_%d",jcent,jtrkpt+1, i)); if(donorm) jetShape[jcent][jtrkpt][i]->Scale(1.0/jetShape_tot[jcent][i]->Integral("width")); jetShape[jcent][jtrkpt][i]->GetYaxis()->SetTitleSize(1); st[jcent][i]->addHist((TH1*) jetShape[jcent][jtrkpt][i]); } } } TCanvas* c_tot = new TCanvas("c_tot","",2400,1600); c_tot->Divide(5,4,0,0); tl.SetTextSize(0.07); for(int jc=2; jc<6;++jc) { int ii = 5-jc; c_tot->cd(jc); subplot(st[ii][0], ii, 0); tl.DrawLatexNDC(0.65,0.8, centLabel[ii]); } for(int jc=7; jc<11;++jc) { int ii = 10-jc; c_tot->cd(jc); subplot(st[ii][1], ii, 1); } for(int jc=12; jc<16;++jc) { int ii = 15-jc; c_tot->cd(jc); subplot(st[ii][2], ii, 2); } //draw the ratio Color_t color[3]; color[0]=kRed+1; color[1]=kAzure-3; color[2]=kGreen+3; TLegend *ll2 = new TLegend(0.1,0.2,0.7,0.8); TString legJetPt[3] = {"120<jetPt<150", "150<jetPt<200", "all jtpt"/*"jetPt>200"*/}; TLine* l1 = new TLine(0, 1, 1.2,1); l1->SetLineStyle(2); l1->SetLineColor(kBlack); l1->SetLineWidth(4); if(donorm){ for(int i=0;i<4;++i) jetShape_hallie[i]->Scale(1.0/jetShape_hallie[i]->Integral("width")); } for(int jc=17; jc<21;++jc) { c_tot->cd(jc); int ii = 20-jc; gPad->SetBottomMargin(0.2); for(int i=0; i<3;++i){ if( ii == 0)ll2->AddEntry(jetShape_tot[0][i], legJetPt[i]); if(donorm) jetShape_tot[ii][i]->Scale(1.0/jetShape_tot[ii][i]->Integral("width")); jetShape_tot[ii][i]->SetAxisRange(0, 0.9,"x"); jetShape_tot[ii][i]->Divide(jetShape_hallie[ii]); jetShape_tot[ii][i]->SetAxisRange(0.5, 2, "Y"); jetShape_tot[ii][i]->SetStats(0); jetShape_tot[ii][i]->SetMarkerSize(1.5); jetShape_tot[ii][i]->SetMarkerStyle(20); jetShape_tot[ii][i]->SetMarkerColor(color[i]); jetShape_tot[ii][i]->SetLineColorAlpha(color[i],0.7); jetShape_tot[ii][i]->SetLineWidth(5); jetShape_tot[ii][i]->GetXaxis()->SetTitleSize(0.09); jetShape_tot[ii][i]->GetXaxis()->SetLabelSize(0.07); jetShape_tot[ii][i]->GetXaxis()->SetTitle("#Delta r"); jetShape_tot[ii][i]->GetXaxis()->CenterTitle(); jetShape_tot[ii][i]->GetYaxis()->SetLabelSize(0); jetShape_tot[ii][i]->Draw("same"); l1->Draw("same"); } } //draw legend c_tot->cd(11); TLegend * ll = st[1][0]->makeLegend(legtxt, 0.1,1, 1,0); ll->Draw(); c_tot->cd(16); ll2->SetLineColorAlpha(kWhite, 0); ll2->SetFillColorAlpha(kWhite, 0); ll2->Draw(); //add fake axis TF1 *f3; if(donorm) f3=new TF1("f3","log10(x)",0.001,50); else f3=new TF1("f3","log10(x)",0.5,5000); TGaxis* ax = new TGaxis(1,0,1,1,"f3",505,"G"); ax->SetLabelSize(0.09); ax->SetTitleSize(0.1); ax->SetTitleOffset(1.3); ax->CenterTitle(); ax->SetTitle("#rho(#Delta r)"); c_tot->cd(1); ax->Draw(); c_tot->cd(6); ax->Draw(); c_tot->cd(11); ax->Draw(); c_tot->cd(16); TGaxis* ax2 = new TGaxis(1,0.2,1,1,0.5, 2); ax2->SetLabelSize(0.09); ax2->SetTitleSize(0.1); ax2->SetTitleOffset(1.3); ax2->CenterTitle(); ax2->SetTitle("jetPt/QM2017"); ax2->Draw(); if(donorm) c_tot->SaveAs("pt_jetShapesForDifferentJetPt_normalized.png"); else c_tot->SaveAs("pt_jetShapesForDifferentJetPt_perJet.png"); } void subplot( stackHist* st, int ii, int nf ){ gPad->SetLogy(); st->setRange(0,0.8,"x"); if(donorm)st->setRange(0.001,50,"y"); else st->setRange(0.5,5000,"y"); st->setLabelSize(0.,"y"); st->setLabelSize(0.); st->drawStack(); if(ii==3) tl.DrawLatexNDC( 0.2, 0.8,jetPtLabel[nf]); }
929ac7dfdc7b7603314a6c1145931751fc88a4d0
768908051da1b660d14b02050637633ba772eced
/src/move_validation.cpp
0456be1467b08e9dd73aa5a65f8724357eed7ee4
[ "MIT" ]
permissive
davidpownall/ChessRobot
5ac3943ac2c8abdc60db4283119206769d413268
a8041b9cff7cbae6952ec57690596ea6de9cb2f9
refs/heads/master
2020-04-15T00:44:35.396935
2019-03-31T20:13:58
2019-04-18T22:04:41
164,250,971
0
0
null
null
null
null
UTF-8
C++
false
false
6,393
cpp
move_validation.cpp
/* This file is responsible for the validation of chess moves */ #include <iostream> #include "util.h" #include "chessboard_defs.h" #include "chessboard.h" /** * Determines if the piece type at this location can make a valid move to the endIdx * * @param pt The piece type making the move * @param idxToAssess The index of the piece being checked * @param endIdx The index where the piece moved to * * @return True if the piece type at that location can actually make the move */ bool ChessBoard::IsValidMove(uint8_t pt, uint8_t idxToAssess, uint8_t endIdx) { int8_t temp; bool status; switch(pt % (NUM_PIECE_TYPES/2)) { // Pawn case 0: std::cout << "Pawn logic not implemented for IsValidMove!" << std::endl; status = false; break; // Rook case 1: status = ChessBoard::IsValidRookMove(this, idxToAssess, endIdx); break; // Knight case 2: status = ChessBoard::IsValidKnightMove(idxToAssess, endIdx); break; // Bishop case 3: status = ChessBoard::IsValidBishopMove(this, idxToAssess, endIdx); break; // Queen case 4: status = ChessBoard::IsValidRookMove(this, idxToAssess, endIdx) || ChessBoard::IsValidBishopMove(this, idxToAssess, endIdx); break; // King case 5: // Assuming a single king (which is always true) status = true; default: return false; } return true; } /** * Determine if the rook at idxToAssess can actually go to endIdx * * @param idxToAssess: The index of a given rook * @param endIdx: Where that rook would have to end up * * @return True if the rook could make that move */ bool ChessBoard::IsValidRookMove(ChessBoard *cb, uint8_t idxToAssess, uint8_t endIdx) { uint8_t mask, largerIdx, smallerIdx; if(cb == NULL) { return false; } if(endIdx > idxToAssess) { largerIdx = endIdx; smallerIdx = idxToAssess; } else { largerIdx = idxToAssess; smallerIdx = endIdx; } // Are we on the same rank or file AND are the indicies between these two // locations empty if(endIdx % 8 == idxToAssess % 8) // same column { // Now we have the column values for our occupied squares mask = cb->occupied & (COLUMN_MASK << endIdx % 8); mask &= ((COLUMN_MASK << endIdx % 8) >> 8*(8 - largerIdx/8)); mask &= ~((COLUMN_MASK << endIdx % 8) >> 8*(8 - smallerIdx/8 + 1)); // if our mask == 0 then the move is valid return (mask == 0); } else if(endIdx >> 3 == idxToAssess >> 3) { // Now we have the row masked mask = cb->occupied & (0xFF << (endIdx/8)); mask &= ~(BOARD_MASK << largerIdx); mask &= ~(BOARD_MASK >> (63 - smallerIdx)); return (mask == 0); } return false; } /** * Determine if the knight at idxToAssess can actually go to endIdx * * @param idxToAssess: The index of a given knight * @param endIdx: Where that knight would have to end up * * @return True if the knight could make that move */ bool ChessBoard::IsValidKnightMove(uint8_t idxToAssess, uint8_t endIdx) { if(endIdx > idxToAssess) { // Assess upwards vertical moves if(idxToAssess < NUM_BOARD_INDICES - 16) { // Can we up then left or right if((idxToAssess + 15 % 8 < idxToAssess % 8 && idxToAssess + 15 == endIdx) || (idxToAssess + 17 % 8 > idxToAssess % 8 && idxToAssess + 17 == endIdx)) { return true; } } // Assess horizontal upwards moves if(idxToAssess < NUM_BOARD_INDICES - 8) { // Can we move left then up or right then up if((idxToAssess % 8 >= 2 && idxToAssess + 6 < NUM_BOARD_INDICES && idxToAssess + 6 == endIdx) || (idxToAssess % 8 < 6 && idxToAssess + 10 < NUM_BOARD_INDICES && idxToAssess + 10 == endIdx)) { return true; } } } else if(idxToAssess > endIdx) { // Assess downwards vertical moves if(idxToAssess >= 16) { // Can we down then left or right if((idxToAssess - 15 % 8 < idxToAssess % 8 && idxToAssess - 15 == endIdx) || (idxToAssess - 17 % 8 > idxToAssess % 8 && idxToAssess - 17 == endIdx)) { return true; } } // Assess horizontal downwards moves if(idxToAssess >= 8) { // Can we move left then down or right then down if((idxToAssess % 8 >= 2 && idxToAssess - 6 < NUM_BOARD_INDICES && idxToAssess - 6 == endIdx) || (idxToAssess % 8 < 6 && idxToAssess - 10 < NUM_BOARD_INDICES && idxToAssess - 10 == endIdx)) { return true; } } } return false; } /** * Determine if the bishop at idxToAssess can actually go to endIdx * * @param idxToAssess: The index of a given bishop * @param endIdx: Where that bishop would have to end up * * @return True if the bishop could make that move */ bool ChessBoard::IsValidBishopMove(ChessBoard *cb, uint8_t idxToAssess, uint8_t endIdx) { int8_t temp; uint8_t largerIdx, smallerIdx; if(cb == NULL) { return false; } if(endIdx > idxToAssess) { largerIdx = endIdx; smallerIdx = idxToAssess; } else { largerIdx = idxToAssess; smallerIdx = endIdx; } // Are the start and end indicies on the same diagonal if(largerIdx - smallerIdx % 7 == 0) { temp = 7; } else if(largerIdx - smallerIdx & 9 == 0) { temp = 9; } else { return false; } smallerIdx += temp; // This will traverse the diagonal and search for impediments while(smallerIdx != largerIdx) { // There is something in the way if(((uint64_t) 1 << smallerIdx) & cb->occupied) { return false; } smallerIdx += temp; } return true; }
1d15b918e3f21eb6f0414179dcd6f3ebde17178e
7447629a7d91cdc2f382b9d946a8bfd84305bcdb
/src/enums/divmodestring.cc
99afac6cd33fe7b5f1be11f5129f3db92a279f21
[]
no_license
JosvanGoor/ScientificVisualisation
e801c9c74c79ab47c1026b7d7fb51a095c26bcc3
e815dfa0a00dad7d55188551ea892e20608aca4a
refs/heads/master
2020-04-22T22:14:35.721240
2019-04-10T18:14:17
2019-04-10T18:14:17
170,701,028
0
0
null
null
null
null
UTF-8
C++
false
false
288
cc
divmodestring.cc
#include "enums.ih" string divmode_string(DivMode mode) { switch (mode) { case DivMode::OFF: return "DivMode::OFF"; case DivMode::ON: return "DrawMode::ON"; default: return "Unknown or Modval DivMode"; } }
72f9d01d8571c1d0871e60111c8037a38112fc89
043cffc19d437c318915ffebde5d1ef5a054e1a4
/file_input/refptr.hh
0700dcd738ab8737213811ee12c49bb27f2da611
[]
no_license
e12exp/ucesb
125fe30cf546dfbd1ff04c7cf0d9e60aa9b19558
7243a48dd1feb3fa3ea6f8c69449b9c407942ff6
refs/heads/master
2022-11-30T06:45:34.837594
2022-11-25T13:55:02
2022-11-25T13:55:02
228,606,166
0
0
null
null
null
null
UTF-8
C++
false
false
878
hh
refptr.hh
#ifndef _REFPTR_H_ #define _REFPTR_H_ template<class T> class refptr { protected: T *ptr; int *refcount; void clear() { if(!refcount) return; (*refcount)--; if(*refcount == 0) { delete refcount; refcount = NULL; if(ptr != NULL) delete ptr; ptr = NULL; } } public: refptr() : ptr(NULL), refcount(NULL) {} refptr(const refptr<T> &other) : ptr(NULL), refcount(NULL) { operator=(other); } refptr<T>& operator=(const refptr<T> &other) { clear(); ptr = other.ptr; refcount = other.refcount; if(refcount != NULL) (*refcount)++; return *this; } ~refptr() { clear(); } T* operator->() const { return ptr; } refptr<T>& operator=(const T* obj) { clear(); refcount = new int; *refcount = 1; ptr = const_cast<T*>(obj); return *this; } operator T*() { return ptr; } }; #endif
e3deb8b91202d0b151534abd43554732ce69d64e
190948d6cb4f394d63152668116b0be2391d55c5
/simulator_win/main.cpp
75b3960c3563afa37f1281f773ce7fa3db80771e
[]
no_license
dawidk089/albedo
39b6c693b22b7967b7857844c77733c23f4471ed
1433b8d140ff423dc760ff8dc4f718a04bd1d09c
refs/heads/master
2016-09-05T09:22:49.688242
2015-08-31T18:51:35
2015-08-31T18:51:35
36,973,427
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
4,192
cpp
main.cpp
#include "Projekt_FS.h" int ilosc_poludnikow; int ilosc_rownoleznikow; double promien_ziemi; double pi; double szerokosc_kontowa_biegunow_przez_2; double stala_sloneczna; double stala_Stefana_Boltzmana; double wspulczynnik_reemisji;//globalne ocieplenie double wsp_dyf; int fun_slonce; int fun_emisja; int fun_wymiana_ciepla; double albedo_parametr_lad; double albedo_parametr_morze; int albedo_rodzaj; int ilosc_wywolan; double cieplo_wlasciwe_lad; double cieplo_wlasciwe_morze; int czyt_mape_swiata; bool fun_czytaj; int aargc; char ** aargv; int main (int argc,char ** argv) { aargc=argc; aargv=argv; ilosc_poludnikow=100; ilosc_rownoleznikow=100; promien_ziemi=6300; pi=3.1415; szerokosc_kontowa_biegunow_przez_2=0.1; stala_sloneczna=1300; stala_Stefana_Boltzmana=5.67*pow(10,-8); wspulczynnik_reemisji=0.52; wsp_dyf=300; fun_slonce=1; fun_emisja=1; fun_wymiana_ciepla=1; albedo_parametr_lad=0.34; albedo_parametr_morze=0.27; albedo_rodzaj=0; ilosc_wywolan=200; cieplo_wlasciwe_lad=100000; cieplo_wlasciwe_morze=300000; czyt_mape_swiata=1; fun_czytaj=0; if(argc>1)ilosc_poludnikow=atof(argv[1]); if(argc>2)ilosc_rownoleznikow=atof(argv[2]); if(argc>3)stala_sloneczna=atof(argv[3]); if(argc>4)wspulczynnik_reemisji=atof(argv[4]); if(argc>5)wsp_dyf=atof(argv[5]); if(argc>6)fun_slonce=atof(argv[6]); if(argc>7)fun_emisja=atof(argv[7]); if(argc>8)fun_wymiana_ciepla=atof(argv[8]); if(argc>9)albedo_parametr_lad=atof(argv[9]); if(argc>10)albedo_parametr_morze=atof(argv[10]); if(argc>11)albedo_rodzaj=atof(argv[11]); if(argc>12)ilosc_wywolan=atof(argv[12]); if(argc>13)cieplo_wlasciwe_lad=atof(argv[13]); if(argc>14)cieplo_wlasciwe_morze=atof(argv[14]); if(argc>15)czyt_mape_swiata=atof(argv[15]); if(argc>16)fun_czytaj=atof(argv[16]); const string nazwa_pliku="PLIKI_TXT\\plik_zapisu.txt"; Pole b_polnocny(0,0,0.31,cieplo_wlasciwe_lad,0.5,300,0),b_poludniowy(0,0,0.31,cieplo_wlasciwe_lad,0.5,300,0); b_polnocny.ref_pole_powiezchni()=pi*pow(promien_ziemi*sin(szerokosc_kontowa_biegunow_przez_2),2); b_poludniowy.ref_pole_powiezchni()=pi*pow(promien_ziemi*sin(szerokosc_kontowa_biegunow_przez_2),2); Tablica_Pol tab; Czas czas; if(czyt_mape_swiata) czytaj_mape_swiata("PLIKI_TXT\\swiat.txt",tab); //BARDZO WAŻNA FUNKCJA - DECYDYJE CZY ZCZYTUJE STAN POCZADKOWY Z JAKIEGOŚ PLIKU CZY ZACZYNA OD ZERA if(fun_czytaj) czytaj(nazwa_pliku,tab,b_polnocny,b_poludniowy,czas); else for(int j=0;j<60;++j) { akcja_w_min(tab,b_polnocny,b_poludniowy,czas,1); } int zapis_co_n=1; wspulczynnik_reemisji=0; for(int i=0;i<19;++i) { wspulczynnik_reemisji+=0.05; czytaj(nazwa_pliku,tab,b_polnocny,b_poludniowy,czas); for(int j=1;j<ilosc_wywolan;++j) { //if( j%10 == 0 )wspolcz-=1; //if( j%zapis_co_n == 0 )zapisuj_temperature_srednio_i_arg_wywolania("WYNIKI\\plik_do_wykresow.txt",tab,czas,j); //if( j%zapis_co_n == 0 )zapisuj_temperature_srednio_i_arg_wywolania("WYNIKI\\wykresy.txt",tab,czas,j); if( j%100 == 0 ){ cout<< "<status>" << j*100/ilosc_wywolan << "\%</status>\n"; } akcja_w_godz(tab,b_polnocny,b_poludniowy,czas,1); } zapisuj_temperature_srednio_i_arg_wywolania("WYNIKI\\temp_od_wsp_reemisji.txt",tab,czas,0); } cout<<czas.rok_dzien_godzina_minuta()<<endl; cout<<"temperatura minimalna: \t"<<"<min_temp>"<<tab.temperatura_min_max().first<<"</min_temp>"<<endl; cout<<"temperatura maksymalna:\t"<<"<max_temp>"<<tab.temperatura_min_max().second<<"</max_temp>"<<endl; cout<<"srednia temperatura: \t"<<"<avr_temp>"<<tab.srednia_temperatura()<<"</avr_temp>" << endl; cout<<"srednie albedo: \t"<<"<avr_albe>"<<tab.srednie_albedo()<<"</avr_albe>" << endl; //zapisz(nazwa_pliku,tab,b_polnocny,b_poludniowy,czas); rysuj_ziemie_jako_jajko("temperatura_0.txt",tab); //zapisuj_temperature_srednio_i_arg_wywolania("WYNIKI\\temp_od_wsp_reemisji.txt",tab,czas,0); //PLIKI /* "temperatura_0.txt" - mapa temperatur "plik_do_wykresow.txt" - zapisuje dane do wykresów "swiat.txt" - do zczytywania mapy świata "plik_zapisu.txt" - zapamientuje stan ostatniej symulacji "test.czytania_swiata.txt" - sprawdza czy mapa świata dobrze się wczytała "zapis_czasu.txt" - zapis czasu (do funkci słońce) ostatniej symulacji */ }
2d7e84b317c8b3214c5b76ece9c4fbf7444d53be
921137a0bc9ba19b51557b19ccfcfe376740a46c
/Qt/ANPR/anpr.h
963c14b1965545857816506186a4b27544035c6e
[]
no_license
Sugoshnr/ANPRS
475fb76f6d9d78a8480e04ac8c90ac47c74ba375
dfb61a748a8a50417896453d91bcbbe297766b71
refs/heads/master
2020-07-04T06:36:25.789352
2016-08-29T02:54:10
2016-08-29T02:54:10
66,789,070
2
1
null
null
null
null
UTF-8
C++
false
false
852
h
anpr.h
#ifndef ANPR_H #define ANPR_H #include <QMainWindow> #include "opencv2/opencv.hpp" #include "textloc.h" #include "textseg.h" #include "preproc.h" #include<iostream> #include<fstream> using namespace cv; using namespace std; namespace Ui { class ANPR; } class ANPR : public QMainWindow { Q_OBJECT public: QString path; explicit ANPR(QWidget *parent = 0); ~ANPR(); private slots: void on_openfile_clicked(); void on_textloc_clicked(); void on_textseg_clicked(); void on_textrec_clicked(); void on_textloc_2_clicked(); void on_preproc_clicked(); void on_preproc_lab_clicked(); private: Ui::ANPR *ui; textloc *TextLoc; textseg *TextSeg; preproc *PreProc; QImage ANPR::convertOpenCVMatToQtQImage(cv::Mat mat); }; #endif // ANPR_H
1ff70a60895edd4765c2221f7a6c59c3e9a241ac
19b3fee76039791b237f605850b173b6c3200fc9
/1090_2 Highest Price in Supply Chain (25 分)/1090 Highest Price in Supply Chain (25 分).cpp
269959d2b7cc5c541108a39fc58a6fc2e9be0e0f
[]
no_license
xuefrye/PAT-Advanced-Level-Practice
3b10aae6438e70f80288423f922c4af0860bd14e
b5df775d0f330d3fcdc91c682082889801257a23
refs/heads/master
2020-05-13T19:25:59.565431
2019-04-16T09:01:05
2019-04-16T09:01:05
181,653,087
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
864
cpp
1090 Highest Price in Supply Chain (25 分).cpp
/* 1090 Highest Price in Supply Chain £¨25 ·Ö£© */ #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<algorithm> #include<vector> #include<math.h> using namespace std; const int maxn = 100001; int n,fatherid,root; double p, r; vector<int> tree[maxn]; int templayer, maxlayer = 0, pathNum = 1; void dfs(int root,int layer) { if (tree[root].size() == 0) { if (layer > maxlayer) { maxlayer = layer; pathNum = 1; } else if (layer == maxlayer) pathNum++; return; } for (int i = 0; i < tree[root].size(); i++) dfs(tree[root][i], layer + 1); } int main() { scanf("%d %lf %lf", &n, &p, &r); for (int i = 0; i < n; i++) { scanf("%d", &fatherid); if (fatherid != -1) tree[fatherid].push_back(i); else if (fatherid == -1) root = i; } dfs(root, 1); printf("%.2lf %d", p*pow(1 + r / 100.0, maxlayer-1), pathNum); }
b50b7313ff28ff2aa02ca209f55ce86f949ebc68
32aa586bef7f8ae4a04cb18d4428b2a328a7bd51
/JsonParseError.cpp
3b3e1ddcb31a927942468365cfe47acbb7939056
[]
no_license
zooyer/cJSON
5c0442f408b16d2abd002473c3e56219732e4403
6b1e0cb2fb97b053667a14bb2c1798efd3551c9d
refs/heads/master
2020-03-27T07:15:13.883079
2018-08-26T11:43:11
2018-08-26T11:43:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
475
cpp
JsonParseError.cpp
#include "JsonParseError.h" JsonParseError::JsonParseError() { m_error = false; } JsonParseError::~JsonParseError() { } void JsonParseError::setJsonParseError(bool error, const string & errinfo) { m_error = error; m_errinfo = errinfo; } bool JsonParseError::isError() { return m_error; } void JsonParseError::printError() { if (m_error) { cout << "JsonParseError: " << m_errinfo << endl; } else { cout << "JsonParseError: " << "not error!" << endl; } }
f773b45191e8c8f044812f7465682c28c8fdf9be
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-datasync/include/aws/datasync/model/PhaseStatus.h
a77d9adf2b1536982d5fd1b839e6531de3b59c22
[ "Apache-2.0", "MIT", "JSON" ]
permissive
aws/aws-sdk-cpp
aff116ddf9ca2b41e45c47dba1c2b7754935c585
9a7606a6c98e13c759032c2e920c7c64a6a35264
refs/heads/main
2023-08-25T11:16:55.982089
2023-08-24T18:14:53
2023-08-24T18:14:53
35,440,404
1,681
1,133
Apache-2.0
2023-09-12T15:59:33
2015-05-11T17:57:32
null
UTF-8
C++
false
false
644
h
PhaseStatus.h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/datasync/DataSync_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace DataSync { namespace Model { enum class PhaseStatus { NOT_SET, PENDING, SUCCESS, ERROR_ }; namespace PhaseStatusMapper { AWS_DATASYNC_API PhaseStatus GetPhaseStatusForName(const Aws::String& name); AWS_DATASYNC_API Aws::String GetNameForPhaseStatus(PhaseStatus value); } // namespace PhaseStatusMapper } // namespace Model } // namespace DataSync } // namespace Aws
e36fb122ba7ebb973dc3ecee837c2d96cee33b33
becd5ee93440020322e3ad99926cebc0e71d786d
/src/meta/processors/admin/GetMetaDirInfoProcessor.cpp
cc16d2679b5ca0d4e77d701321d185e1f337db49
[ "Apache-2.0" ]
permissive
heyanlong/nebula
aa94f589a2d77d0cb6e40dcced1f5ee0a8e6a79c
07ccfde198c978b8c86b7091773e3238bfcdf454
refs/heads/master
2023-09-04T13:49:18.522506
2021-11-03T15:16:03
2021-11-03T15:16:03
424,433,008
1
0
null
null
null
null
UTF-8
C++
false
false
1,570
cpp
GetMetaDirInfoProcessor.cpp
/* Copyright (c) 2021 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #include "meta/processors/admin/GetMetaDirInfoProcessor.h" #include <boost/filesystem.hpp> #include "common/fs/FileUtils.h" namespace nebula { namespace meta { void GetMetaDirInfoProcessor::process(const cpp2::GetMetaDirInfoReq& req) { UNUSED(req); auto data_root = kvstore_->getDataRoot(); std::vector<std::string> realpaths; bool failed = false; std::transform(std::make_move_iterator(data_root.begin()), std::make_move_iterator(data_root.end()), std::back_inserter(realpaths), [&failed](auto f) { if (f[0] == '/') { return f; } else { auto result = nebula::fs::FileUtils::realPath(f.c_str()); if (!result.ok()) { failed = true; LOG(ERROR) << "Failed to get the absolute path of file: " << f; return f; } return std::string(result.value()); } }); if (failed) { resp_.set_code(nebula::cpp2::ErrorCode::E_GET_META_DIR_FAILURE); onFinished(); return; } nebula::cpp2::DirInfo dir; dir.set_data(realpaths); dir.set_root(boost::filesystem::current_path().string()); resp_.set_dir(std::move(dir)); resp_.set_code(nebula::cpp2::ErrorCode::SUCCEEDED); onFinished(); } } // namespace meta } // namespace nebula
f3024cff48e5e98a2bd05a26d958e44cde664513
17cc06546c0f84f1680cf3b6381ffd3f5c78e888
/Chess/src/Pieces/BoardMovePieces/BoardMovePiece.cpp
fc6b3190b2a34eb2f17318eb9eab541ebeecc0c2
[]
no_license
Same4254/The-Clive-Mind
f5f9afaa5558e78c83f97596c3d346dffe3e6a47
5faf39f71136ef70dbfbb5e13a77a258dffe99d7
refs/heads/master
2023-05-28T08:51:54.966337
2023-05-09T21:55:44
2023-05-09T21:55:44
200,430,644
2
0
null
2021-01-16T21:21:49
2019-08-03T23:41:31
C++
UTF-8
C++
false
false
1,456
cpp
BoardMovePiece.cpp
#include "Pieces/BoardMovePieces/BoardMovePiece.hpp" BoardMovePiece::BoardMovePiece(const PieceFunctionalityIndex piece, PieceFunctionalityIndex newPiece, const char renderCharacter) : PieceFunctionality(piece, renderCharacter, true), newPiece(newPiece) { } void BoardMovePiece::fillMoves(BoardState &boardState, std::array<Move, MAX_MOVES_PER_PIECE> &movesToFill, int &amtMovesFilled, const BoardPieceIndex boardRow, const BoardPieceIndex boardCol, const BoardPieceIndex boardPositionIndex) const { int newRow = 0, newCol = 0; for(int i = 0; i < moveOffsets.size(); i += BoardState::nRows - 1) { for(int j = i; j < i + BoardState::nRows - 1; j++) { newRow = boardRow + moveOffsets.at(j).first; newCol = boardCol + moveOffsets.at(j).second; if(newRow < 0 || newRow >= BoardState::nRows || newCol < 0 || newCol >= BoardState::nCols) break; //Can't take your own pieces if(boardState.pieces2D[newRow][newCol] != PIECES::EMPTY && boardState.pieces2D[newRow][newCol] % 2 == teamModularity) break; takeSquare(boardState, movesToFill[amtMovesFilled], amtMovesFilled, newPiece, boardRow, boardCol, newRow, newCol); //Can't jump over an enemy piece if(boardState.pieces2D[newRow][newCol] != PIECES::EMPTY && boardState.pieces2D[newRow][newCol] % 2 != teamModularity) break; } } }
fbd9453294f01e9a5018b6f38449812721aecc02
8b07e31d203b3d3102b29c73e0777713adcd64b6
/UVa/10656.cpp
a664a3b0f64b81a5f93dd67a93aa568cfbe041da
[]
no_license
rapel02/competitive-programming
70d193c17e0da447b76643d6d3818c3f5000df8f
27d39667ca4f3b4dde1cef6234cd847c23d82b5f
refs/heads/master
2020-06-04T16:18:39.018983
2019-06-15T16:34:06
2019-06-15T16:34:06
192,099,411
0
0
null
null
null
null
UTF-8
C++
false
false
447
cpp
10656.cpp
#include<bits/stdc++.h> using namespace std; int arr[1500]; int main() { int n; bool ff = true; while(scanf("%d",&n),n) { ff = false; int ll = -1; int rr = -2; for(int a=0;a<n;a++) { scanf("%d",&arr[a]); if(arr[a]!=0) { if(ll==-1) ll = a; rr = a; } } for(int b=ll;b<=rr;b++) { if(arr[b]==0) continue; if(b!=ll) printf(" "); printf("%d",arr[b]); } if(ll==-1) printf("0"); printf("\n"); } }
6779e7f32aafac5b8f3e2c9323d9dc77f5e85b3a
ead0b1c60e787f319242de5a56d246991d6e5464
/code/source/Events/Manager/PlayFabEventManagerApi.cpp
d0ef1690339c10eb0edac5f6ef0f244639c2d4bd
[]
no_license
jplafonta/XPlatCSdk
fbc9edcf7dadf88c5e20f26b6deaafa3bb512909
302c021dcfd7518959551b33c65499a45d7829de
refs/heads/main
2023-07-30T04:54:27.901376
2021-08-31T14:26:52
2021-08-31T14:26:52
347,189,117
0
0
null
2021-04-15T01:09:33
2021-03-12T20:26:17
C++
UTF-8
C++
false
false
7,003
cpp
PlayFabEventManagerApi.cpp
#include "stdafx.h" #include <playfab/PlayFabEventManagerApi.h> #include "Event.h" #include "Entity.h" using namespace PlayFab; using namespace PlayFab::EventManager; HRESULT PlayFabEventManagerEventCreate( _In_ PlayFabEventManagerEventType eventType, _In_ const char* eventName, _In_opt_ const char* eventNamespace, _In_opt_ const char* entityId, _In_opt_ const char* entityType, _Out_ PlayFabEventManagerEventHandle* eventHandle ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(eventHandle); auto event = MakeShared<Event>(eventType, eventName); if (eventNamespace) { event->SetNamespace(eventNamespace); } if (entityId) { event->SetEntity(entityId, entityType); } *eventHandle = MakeUnique<PlayFabEventManagerEvent>(event).release(); return S_OK; } HRESULT PlayFabEventManagerEventDuplicateHandle( _In_ PlayFabEventManagerEventHandle eventHandle, _Out_ PlayFabEventManagerEventHandle* duplicatedEventHandle ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(eventHandle); RETURN_HR_INVALIDARG_IF_NULL(duplicatedEventHandle); *duplicatedEventHandle = MakeUnique<PlayFabEventManagerEvent>(*eventHandle).release(); return S_OK; } void PlayFabEventManagerEventCloseHandle( _Out_ PlayFabEventManagerEventHandle eventHandle ) noexcept { UniquePtr<PlayFabEventManagerEvent>{ eventHandle }; } HRESULT PlayFabEventManagerEventSetNamespace( _In_ PlayFabEventManagerEventHandle eventHandle, _In_ const char* eventNamespace ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(eventHandle); RETURN_HR_INVALIDARG_IF_NULL(eventNamespace); eventHandle->event->SetNamespace(eventNamespace); return S_OK; } HRESULT PlayFabEventManagerEventSetEntity( _In_ PlayFabEventManagerEventHandle eventHandle, _In_ const char* entityId, _In_opt_ const char* entityType ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(eventHandle); RETURN_HR_INVALIDARG_IF_NULL(entityId); eventHandle->event->SetEntity(entityId, entityType); return S_OK; } template<typename T> HRESULT PlayFabEventManagerEventSetProperty( _In_ PlayFabEventManagerEventHandle eventHandle, _In_ const char* key, _In_ T value ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(eventHandle); RETURN_HR_INVALIDARG_IF_NULL(key); eventHandle->event->SetProperty(key, value); return S_OK; } HRESULT PlayFabEventManagerEventSetStringProperty( _In_ PlayFabEventManagerEventHandle eventHandle, _In_ const char* key, _In_ const char* value ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(value); return PlayFabEventManagerEventSetProperty(eventHandle, key, value); } HRESULT PlayFabEventManagerEventSetBooleanProperty( _In_ PlayFabEventManagerEventHandle eventHandle, _In_ const char* key, _In_ bool value ) noexcept { return PlayFabEventManagerEventSetProperty(eventHandle, key, value); } HRESULT PlayFabEventManagerEventSetIntProperty( _In_ PlayFabEventManagerEventHandle eventHandle, _In_ const char* key, _In_ int64_t value ) noexcept { return PlayFabEventManagerEventSetProperty(eventHandle, key, value); } HRESULT PlayFabEventManagerEventSetUintProperty( _In_ PlayFabEventManagerEventHandle eventHandle, _In_ const char* key, _In_ uint64_t value ) noexcept { return PlayFabEventManagerEventSetProperty(eventHandle, key, value); } HRESULT PlayFabEventManagerEventSetDoubleProperty( _In_ PlayFabEventManagerEventHandle eventHandle, _In_ const char* key, _In_ double value ) noexcept { return PlayFabEventManagerEventSetProperty(eventHandle, key, value); } HRESULT PlayFabEventManagerCustomizeEventPipelineSettings( _In_ PFEntityHandle entityHandle, _In_ PlayFabEventManagerPipelineType pipeline, _In_ XTaskQueueHandle queue, _In_ size_t* minimumBufferSizeBytes, _In_ size_t* maxItemsInBatch, _In_ uint32_t* maxBatchWaitTimeInSeconds, _In_ size_t* maxBatchesInFlight, _In_ uint32_t* pollDelayInMs ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(entityHandle); EventPipelineSettings settings; if (queue) { settings.queue = TaskQueue{ queue }; } if (minimumBufferSizeBytes) { settings.minimumBufferSizeInBytes = *minimumBufferSizeBytes; } if (maxItemsInBatch) { settings.maxItemsInBatch = *maxItemsInBatch; } if (maxBatchWaitTimeInSeconds) { settings.maxBatchWaitTimeInSeconds = *maxBatchWaitTimeInSeconds; } if (maxBatchesInFlight) { settings.maxBatchesInFlight = *maxBatchesInFlight; } if (pollDelayInMs) { settings.pollDelayInMs = *pollDelayInMs; } return entityHandle->entity->eventManagerAPI.CustomizePipelineSettings(pipeline, settings); } HRESULT PlayFabEventManagerWriteEventAsync( _In_ PFEntityHandle entityHandle, _In_ PlayFabEventManagerEventHandle eventHandle, _In_opt_ void* callbackContext, _In_opt_ PlayFabEventManagerWriteEventCompletionCallback* callback ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(entityHandle); RETURN_HR_INVALIDARG_IF_NULL(eventHandle); entityHandle->entity->eventManagerAPI.WriteEvent(eventHandle->event).Finally([ callbackContext, callback ](Result<String> result) { if (callback) { const char* assignedId{ nullptr }; if (Succeeded(result)) { assignedId = result.Payload().data(); } callback(callbackContext, result.hr, assignedId); } }); return S_OK; } HRESULT PlayFabEventManagerTerminate( _In_ PFEntityHandle entityHandle, _In_ bool wait, _In_opt_ void* callbackContext, _In_opt_ PlayFabEventManagerTerminatedCallback* callback ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(entityHandle); struct TerminationContext { void* callbackContext; PlayFabEventManagerTerminatedCallback* callback; std::mutex mutex; std::condition_variable cv; bool terminated{ false }; }; auto context = MakeShared<TerminationContext>(); context->callbackContext = callbackContext; context->callback = callback; HRESULT hr = entityHandle->entity->eventManagerAPI.Terminate([context](void) { if (context->callback) { context->callback(context->callbackContext); } std::lock_guard<std::mutex> lock{ context->mutex }; context->terminated = true; context->cv.notify_all(); }); RETURN_IF_FAILED(hr); if (wait) { std::unique_lock<std::mutex> lock{ context->mutex }; while (!context->terminated) { context->cv.wait(lock); } } return S_OK; }
8ee0fcb4e1da628233a72d36c354b19e67075656
ab64c72b421125590a9eb9449d678d7db4f7610a
/Hieroglyph3/Source/Events/EventManager.cpp
dc2657061bcf7174cfb434ec119af2da4a128d54
[ "MIT" ]
permissive
xzwang2005/DX11_tutorials_with_hieroglyph3
03220106c9d762bfccdbf098c42821bf25bb2b46
611e273dafe099875e86222e75420920ca2c49bf
refs/heads/master
2020-05-17T13:44:24.834766
2018-03-22T11:03:50
2018-03-22T11:03:50
28,190,906
5
3
null
null
null
null
UTF-8
C++
false
false
3,575
cpp
EventManager.cpp
//-------------------------------------------------------------------------------- // This file is a portion of the Hieroglyph 3 Rendering Engine. It is distributed // under the MIT License, available in the root of this distribution and // at the following URL: // // http://www.opensource.org/licenses/mit-license.php // // Copyright (c) Jason Zink //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- #include "PCH.h" #include "EventManager.h" #include "Log.h" //-------------------------------------------------------------------------------- using namespace Glyph3; //-------------------------------------------------------------------------------- EventManager* EventManager::m_spEventManager = 0; //-------------------------------------------------------------------------------- EventManager::EventManager() { if ( !m_spEventManager ) m_spEventManager = this; } //-------------------------------------------------------------------------------- EventManager::~EventManager() { // TODO: Detach any remaining event handlers that were being serviced for ( unsigned int e = 0; e < NUM_EVENTS; e++ ) { for ( unsigned int i = 0; i < m_EventHandlers[e].size(); i++ ) { m_EventHandlers[e][i]->SetEventManager( nullptr ); } } } //-------------------------------------------------------------------------------- EventManager* EventManager::Get() { return( m_spEventManager ); } //-------------------------------------------------------------------------------- bool EventManager::AddEventListener( eEVENT EventID, IEventListener* pListener ) { if ( EventID >= NUM_EVENTS ) return( false ); m_EventHandlers[EventID].push_back( pListener ); return( true ); } //-------------------------------------------------------------------------------- bool EventManager::DelEventListener( eEVENT EventID, IEventListener* pListener ) { if ( EventID >= NUM_EVENTS ) return( false ); bool bResult = false; int index = -1; for ( std::vector< IEventListener* >::iterator it = m_EventHandlers[EventID].begin(); it != m_EventHandlers[EventID].end(); ++it ) { if ( *it == pListener ) { m_EventHandlers[EventID].erase( it ); bResult = true; break; } } return( bResult ); } //-------------------------------------------------------------------------------- bool EventManager::ProcessEvent( EventPtr pEvent ) { if ( !pEvent ) return( false ); eEVENT e = pEvent->GetEventType(); unsigned int num = m_EventHandlers[e].size(); bool bHandled = false; for ( unsigned int i = 0; i < num; i++ ) { bHandled = m_EventHandlers[e][i]->HandleEvent( pEvent ); if ( bHandled ) break; } // The event will automatically be destroyed after exiting this method if no // other references to the event have been created. return( bHandled ); } //-------------------------------------------------------------------------------- bool EventManager::QueueEvent( EventPtr pEvent ) { // TODO: Events are currently not queued - they are handled immediately after // sending them. This will need to be addressed in the future... return( true ); } //-------------------------------------------------------------------------------- bool EventManager::ProcessEventQueue( ) { // TODO: Events are currently not queued - they are handled immediately after // sending them. This will need to be addressed in the future... return( true ); } //--------------------------------------------------------------------------------
586a9b712fdf4326d0848d7f52a355a96ab7cc6c
70418d8faa76b41715c707c54a8b0cddfb393fb3
/11648.cpp
fa66a961e7f1aaf7e4125525ae46c69d23f957fd
[]
no_license
evandrix/UVa
ca79c25c8bf28e9e05cae8414f52236dc5ac1c68
17a902ece2457c8cb0ee70c320bf0583c0f9a4ce
refs/heads/master
2021-06-05T01:44:17.908960
2017-10-22T18:59:42
2017-10-22T18:59:42
107,893,680
3
1
null
null
null
null
UTF-8
C++
false
false
751
cpp
11648.cpp
#include <bits/stdc++.h> using namespace std; double solve(double a, double b, double c) { double D = b * b - 4 * a * c; return (-b + sqrt(D)) / (2 * a); } int main() { double AB; double CD; double AD; double BC; double Height; double s; double S; double degree; int Land; scanf("%d", &Land); for (int i = 1; i <= Land; i++) { scanf("%lf %lf %lf %lf", &AB, &CD, &AD, &BC); degree = AB - CD; s = (AD + (degree) + BC) / 2; S = sqrt(s * (s - AD) * (s - (degree)) * (s - BC)); Height = S * 2 / (degree); S = (CD + AB) * Height / 2; S = S / 2; s = solve(degree, CD * Height * 2, -S * Height * 2); printf("Land #%d: %lf %lf\n", i, ((Height - s) * AD) / Height + 1e-7, ((Height - s) * BC) / Height + 1e-7); } return 0; }
9c7b99a592b65e89893079cca9cee7246d337ecd
13d137e453bd2e7e0a9a93069dbdb5b8954b68a0
/sorting-methods/quicksort/main.cpp
c0868ba21dc042e716ee5438e6af41f1464bdb2e
[]
no_license
devMatthes/PAMSI
04c41556816b818a549897f06105adbe4fea7ffd
c619046ef63b988645eaf19d0ebafec04694a34b
refs/heads/master
2020-05-07T10:00:58.274787
2019-06-17T16:06:51
2019-06-17T16:06:51
174,132,616
0
0
null
null
null
null
UTF-8
C++
false
false
1,286
cpp
main.cpp
#include <iostream> #include <cstdlib> #include <chrono> #include <array> #include <algorithm> #include <random> template <typename T> void quicksort(std::vector<T>& numbers, typename std::vector<T>::iterator p, typename std::vector<T>::iterator q) { if(p >= q) { return; } auto pivot = q; auto border = std::partition(p, q, [pivot](const auto& value){ return value < *pivot; }); if(border != q) { std::swap(*border, *q); } quicksort(numbers, p, border - 1); quicksort(numbers, border + 1, q); } template <typename T> void display(std::vector<T>& numbers) { for(const auto& i : numbers) { std::cout << i << ' '; } std::cout << std::endl; } int main() { std::vector<int> numbers(5000); std::generate(numbers.begin(), numbers.end(), [](){return std::rand() % 5000;}); //display(numbers); auto start = std::chrono::steady_clock::now(); quicksort(numbers, numbers.begin(), (numbers.end()-1)); auto end = std::chrono::steady_clock::now(); //display(numbers); std::cout << std::endl; std::cout << "Czas w sekundach: " << std::chrono::duration_cast<std::chrono::microseconds>(end-start).count() << std::endl; return 0; }