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
1f6320c193052c2c189e14986ca0ec795d291b97
5113c639dbdff970740dd82f7fcf31cbcf8484b8
/Amazoom (Anushka Trial)/web_server.cpp
b0334edab06d1269b3988a4fe80529f8babeb938
[]
no_license
SunnyChahal/Automated-Warehouse
8b35773f45802499c305da2537643d72d69df4ea
bbb6e272bf369f5b5e505fdbb771d51288a2d5d0
refs/heads/master
2021-04-06T16:50:27.626638
2018-10-13T23:49:04
2018-10-13T23:49:04
125,403,263
0
0
null
null
null
null
UTF-8
C++
false
false
6,158
cpp
web_server.cpp
#include "central_computer.h" #include <cpen333/process/shared_memory.h> #include <thread> #include <iostream> #include "safe_printf.h" //Testing for one item at one time right now int main(int argc, char* argv[]) { //Making no_items_present for each item in the inventory shared cpen333::process::shared_memory memory("movie1", sizeof(no_items_present)); no_items_present *data = (no_items_present*)memory.get(); cpen333::process::shared_object<SharedData> Memory("lab4_maze_runner");//shared memory for warehouse; initilaize it // Detect number of each item wanted from command line ; Will later change it to server and client int client_id = 0; //will be client id int no_item_wanted=0; //no of items requested by client //How many of each item is wanted ? if (argc > 1) { no_item_wanted = atoi(argv[1]); } // Detect item type from command line ItemType type = ItemType::CHOCOLATE_CHIP; if (argc > 2) { std::string ctype = argv[2]; // grab type as string if (ctype.compare("CHOCOLATE_CHIP") == 0) { type = ItemType::CHOCOLATE_CHIP; // Type =0 } else if (ctype.compare("ARDUINO") == 0) { //type =1 type = ItemType::ARDUINO; } else if (ctype.compare("GINGER_SNAP") == 0) { type = ItemType::GINGER_SNAP; //Type=2 } else if (ctype.compare("BRUSH") == 0) { //type =3 type = ItemType::BRUSH; } else if (ctype.compare("OATMEAL_RAISIN") == 0) { //type=4 type = ItemType::OATMEAL_RAISIN; } } //adding for client id if (argc > 3) { client_id = atoi(argv[3]); } //Declaring orderqueue( i.e. the queue in which order will added ) OrderQueue queue(ORDER_QUEUE_NAME, 256); int i = 0; //Check for each item if its available -> if available then push it to OrderQueue // else alert manager about low (keep in mind UI) if (type == 0) { if (no_item_wanted <= data->chocolate_chip) { //checking if it is present in stock or not while (i < no_item_wanted) { safe_printf("No of chocolate chip present in inventory is %d \n", data->chocolate_chip); safe_printf("No of chocolate chip wanted by customer is %d \n", no_item_wanted); safe_printf("Adding chocolate chip order to queue \n"); queue.push(Order(type, client_id, 0)); // no_items_added_to_queue++; data->chocolate_chip--; i++; } } else { safe_printf("No of chocolate chip present in inventory is %d \n", data->chocolate_chip); safe_printf("No of chocolate chip wanted by customer is %d \n", no_item_wanted); safe_printf("Not enough item chocolate chip -> Alert Manager \n"); Memory->Low_Stock_Chocolate_Chip = true; //Update in shared a boolen which will be accessed using UI } } else if (type == 1) { if (no_item_wanted < data->arduino) { while (i < no_item_wanted) { safe_printf("No of arduinos present in inventory is %d \n", data->arduino); safe_printf("No of arduinos wanted by customer is %d \n", no_item_wanted); safe_printf("Adding arduino order to queue \n"); queue.push(Order(type, client_id, 0)); // no_items_added_to_queue++; data->arduino--; i++; } } else { safe_printf("No of arduinos present in inventory is %d \n", data->arduino); safe_printf("No of arduinos wanted by customer is %d \n", no_item_wanted); safe_printf("Not enough item arduinos -> Alert Manager \n");; Memory->Low_Stock_Arduino = true; //Update in shared a boolen which will be accessed using UI } } else if (type == 2) { if (no_item_wanted < data->ginger_snap) { while (i < no_item_wanted) { safe_printf("No of ginger_snap present in inventory is %d \n", data->ginger_snap); safe_printf("No of ginger_snap wanted by customer is %d \n", no_item_wanted); safe_printf("Adding ginger_snap order to queue \n"); queue.push(Order(type, client_id, 0)); // no_items_added_to_queue++; data->ginger_snap--; i++; } //std::cout << "Poppinng order from queue to test " << std::endl; //Order order = queue.pop(); //TESTING IF IT WAS ADDED CORRECTLY //std::cout << "Item_added to queue is type " << order.type << std::endl; //std::cin.get(); } else { safe_printf("No of ginger_snap present in inventory is %d \n", data->ginger_snap); safe_printf("No of ginger_snap wanted by customer is %d \n", no_item_wanted); safe_printf("Not enough item arduinos -> Alert Manager \n");; Memory->Low_Stock_Ginger_Snap = true; //Update in shared a boolen which will be accessed using UI } } else if (type == 3) { if (no_item_wanted < data->brush) { while (i < no_item_wanted) { safe_printf("No of brush present in inventory is %d \n", data->brush); safe_printf("No of brush wanted by customer is %d \n", no_item_wanted); safe_printf("Adding brush order to queue \n"); queue.push(Order(type, client_id, 0)); // no_items_added_to_queue++; data->brush--; i++; } } else { safe_printf("No of brush present in inventory is %d \n", data->brush); safe_printf("No of brush wanted by customer is %d \n", no_item_wanted); safe_printf("Not enough item arduinos -> Alert Manager \n");; Memory->Low_Stock_brush = true; //Update in shared a boolen which will be accessed using UI } } else if (type == 4) { if (no_item_wanted < data->oatmeal) { while (i < no_item_wanted) { safe_printf("No of oatmeal present in inventory is %d \n", data->oatmeal); safe_printf("No of oatmeal wanted by customer is %d \n", no_item_wanted); safe_printf("Adding oatmeal order to queue \n"); queue.push(Order(type, client_id, 0)); // no_items_added_to_queue++; data->oatmeal--; i++; } } else { safe_printf("No of oatmeal present in inventory is %d \n", data->oatmeal); safe_printf("No of oatmeal wanted by customer is %d \n", no_item_wanted); safe_printf("Not enough item arduinos -> Alert Manager \n");; Memory->Low_Stock_Oatmeal_Raisins = true; //Update in shared a boolen which will be accessed using UI } } //std::cin.get(); return 0; }
896ff6bbbc1e9c8acdbb9da1b581bf1684f7a957
3ad5e5b30a4f32744ee237cab390cc8a0dff66f3
/leetcode_cpp/102_binary_tree_level_order_traverse.cpp
f6fa76ecd60fa6f6f9a359a532abd6d90aeaea16
[]
no_license
LeiShi1313/leetcode
721e41508eb244ec840ce593fedc3f8996050a0f
895790f2a2706bb727d535b7cc28047e17b1fb6a
refs/heads/master
2021-03-27T10:22:59.472077
2018-02-11T18:44:21
2018-02-11T18:44:21
94,644,211
1
0
null
null
null
null
UTF-8
C++
false
false
1,093
cpp
102_binary_tree_level_order_traverse.cpp
// // Created by Dicky Shi on 6/13/17. // #include <iostream> #include <vector> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <string> #include <ctime> #include "utils.h" using namespace std; class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> res; if (root == NULL) return res; int level = 1; firstOrderTraverse(root, res, level); return res; } private: void firstOrderTraverse(TreeNode *cur, vector<vector<int>> &res, int level) { if (level > res.size()) { vector<int> curLevel; res.push_back(curLevel); } res[level-1].push_back(cur->val); if (cur->left) { firstOrderTraverse(cur->left, res, level+1); } if (cur->right) { firstOrderTraverse(cur->right, res, level+1); } } }; int main() { vector<int> nums; nums = {3,9,20,INT_MIN,INT_MIN,15,7}; cout << Solution().levelOrder(TreeNode().getRoot(nums)) << endl; return 0; }
35b25032bf53c3d5b18898c71b46d33b67b72f9e
632a1f1fdd5381dd17ec30bed42e67c99bfe30db
/Animal.cpp
2eb4c16b2be2cfb3bad5bebf655a1925cdd34141
[]
no_license
hrmendoza96/HaroldMendoza-Examen2
692f02ec7bc8e61869d16440681bbb6ed4063d63
b1c95d98893083e448ee8051d12e59bca166da76
refs/heads/master
2021-01-13T13:40:36.884696
2017-01-20T20:22:46
2017-01-20T20:22:46
76,367,016
0
0
null
null
null
null
UTF-8
C++
false
false
546
cpp
Animal.cpp
#include <iostream> #include <string> #include <sstream> #include "Animal.h" using namespace std; Animal::Animal(){ } Animal::Animal(string nombre, string sonido){ this->nombre=nombre; this->sonido=sonido; } void Animal::setNombre(string nombre){ this->nombre=nombre; } string Animal::getNombre(){ return nombre; } void Animal::setSonido(string sonido){ this->sonido=sonido; } string Animal::getSonido(){ return sonido; } string Animal::toString(){ return ""; } string Animal::Sonido(){ return ""; } Animal::~Animal(){ }
6df76fa9014c536839fe688109881f56f5b4f6c7
4ca9c0ed3f2dbdf5f2097dfaad7e03c57ef1384f
/src/Main.cpp
10eaaf7d4faf0203aa69a03941c62da22a93829d
[]
no_license
AkiV/MazeGenerator
534e6ac00ce13d6df89a1f42a03a37d196c11f63
b217691768a7c2007592d1d600d28f602a31d82e
refs/heads/master
2021-01-13T00:46:04.355075
2015-10-06T12:20:19
2015-10-06T12:20:19
43,735,934
0
0
null
null
null
null
UTF-8
C++
false
false
928
cpp
Main.cpp
#include <SFML\Graphics.hpp> #include "MazeGenerator.h" #include "Application.h" #include "Player.h" #include <Windows.h> int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow) { int width = 640; int height = 640; int size = 21; Application application(width, height); MazeGenerator mazeGenerator; std::shared_ptr<Maze> maze = mazeGenerator.Create(size, size, width, height); sf::Vector2f playerSize = { static_cast<float>(width) / size, static_cast<float>(height) / size }; Player player(playerSize, maze); player.GotoStart(); maze->Solve(); while (application.Run()) { player.Update(); if (player.IsAtExit()) { maze = mazeGenerator.Create(size, size, width, height); player.SetMaze(maze); player.GotoStart(); maze->Solve(); } application.Draw(*maze); application.Draw(player); application.Display(); } return 0; }
edb4097df0eeeba5b4025f00f9e6f88931a92b2d
4e849c1d0518846419ed229a9194e20ae0eed0ce
/source/mips/msg.cpp
0f8cfa702c65dd5d25b6688df3fb96e7430cb0ba
[]
no_license
TimerChen/mips
c2e75f8b9fba0461f728a23b0eb5baf059d6b4d9
cd913bbf163a5813d2fda2e69f4dc14c4bcbca18
refs/heads/master
2021-01-23T08:21:58.806595
2017-07-07T06:53:18
2017-07-07T06:53:18
95,420,240
0
0
null
null
null
null
UTF-8
C++
false
false
329
cpp
msg.cpp
#include "msg.h" MsgIF::MsgIF(const char *Str) { add = 0; for( int i=0; i<12; ++i ) str[i] = Str[i]; } MsgID::MsgID() { opt = narg = 0; for( int i=0; i<5; ++i ) arg[i] = 0; } MsgEX::MsgEX() { opt = arg[0] = arg[1] = arg[2] = 0; } MsgMEM::MsgMEM() { opt = arg[0] = arg[1] = 0; } MsgWB::MsgWB() { opt = arg = 0; }
49f5380a81659eb969e5df48884fac2407dbb68b
ff443629c167f318d071f62886581167c51690c4
/src/crypto/chacha20poly1305.h
a847c258ef15271007d45411be7e92d16d7d104a
[ "MIT" ]
permissive
bitcoin/bitcoin
a618b2555d9fe5a2b613e5fec0f4b1eca3b4d86f
6f03c45f6bb5a6edaa3051968b6a1ca4f84d2ccb
refs/heads/master
2023-09-05T00:16:48.295861
2023-09-02T17:43:00
2023-09-02T17:46:33
1,181,927
77,104
33,708
MIT
2023-09-14T20:47:31
2010-12-19T15:16:43
C++
UTF-8
C++
false
false
5,550
h
chacha20poly1305.h
// Copyright (c) 2023 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CRYPTO_CHACHA20POLY1305_H #define BITCOIN_CRYPTO_CHACHA20POLY1305_H #include <cstddef> #include <stdint.h> #include <crypto/chacha20.h> #include <crypto/poly1305.h> #include <span.h> /** The AEAD_CHACHA20_POLY1305 authenticated encryption algorithm from RFC8439 section 2.8. */ class AEADChaCha20Poly1305 { /** Internal stream cipher. */ ChaCha20 m_chacha20; public: /** Expected size of key argument in constructor. */ static constexpr unsigned KEYLEN = 32; /** Expansion when encrypting. */ static constexpr unsigned EXPANSION = Poly1305::TAGLEN; /** Initialize an AEAD instance with a specified 32-byte key. */ AEADChaCha20Poly1305(Span<const std::byte> key) noexcept; /** Switch to another 32-byte key. */ void SetKey(Span<const std::byte> key) noexcept; /** 96-bit nonce type. */ using Nonce96 = ChaCha20::Nonce96; /** Encrypt a message with a specified 96-bit nonce and aad. * * Requires cipher.size() = plain.size() + EXPANSION. */ void Encrypt(Span<const std::byte> plain, Span<const std::byte> aad, Nonce96 nonce, Span<std::byte> cipher) noexcept { Encrypt(plain, {}, aad, nonce, cipher); } /** Encrypt a message (given split into plain1 + plain2) with a specified 96-bit nonce and aad. * * Requires cipher.size() = plain1.size() + plain2.size() + EXPANSION. */ void Encrypt(Span<const std::byte> plain1, Span<const std::byte> plain2, Span<const std::byte> aad, Nonce96 nonce, Span<std::byte> cipher) noexcept; /** Decrypt a message with a specified 96-bit nonce and aad. Returns true if valid. * * Requires cipher.size() = plain.size() + EXPANSION. */ bool Decrypt(Span<const std::byte> cipher, Span<const std::byte> aad, Nonce96 nonce, Span<std::byte> plain) noexcept { return Decrypt(cipher, aad, nonce, plain, {}); } /** Decrypt a message with a specified 96-bit nonce and aad and split the result. Returns true if valid. * * Requires cipher.size() = plain1.size() + plain2.size() + EXPANSION. */ bool Decrypt(Span<const std::byte> cipher, Span<const std::byte> aad, Nonce96 nonce, Span<std::byte> plain1, Span<std::byte> plain2) noexcept; /** Get a number of keystream bytes from the underlying stream cipher. * * This is equivalent to Encrypt() with plain set to that many zero bytes, and dropping the * last EXPANSION bytes off the result. */ void Keystream(Nonce96 nonce, Span<std::byte> keystream) noexcept; }; /** Forward-secure wrapper around AEADChaCha20Poly1305. * * This implements an AEAD which automatically increments the nonce on every encryption or * decryption, and cycles keys after a predetermined number of encryptions or decryptions. * * See BIP324 for details. */ class FSChaCha20Poly1305 { private: /** Internal AEAD. */ AEADChaCha20Poly1305 m_aead; /** Every how many iterations this cipher rekeys. */ const uint32_t m_rekey_interval; /** The number of encryptions/decryptions since the last rekey. */ uint32_t m_packet_counter{0}; /** The number of rekeys performed so far. */ uint64_t m_rekey_counter{0}; /** Update counters (and if necessary, key) to transition to the next message. */ void NextPacket() noexcept; public: /** Length of keys expected by the constructor. */ static constexpr auto KEYLEN = AEADChaCha20Poly1305::KEYLEN; /** Expansion when encrypting. */ static constexpr auto EXPANSION = AEADChaCha20Poly1305::EXPANSION; // No copy or move to protect the secret. FSChaCha20Poly1305(const FSChaCha20Poly1305&) = delete; FSChaCha20Poly1305(FSChaCha20Poly1305&&) = delete; FSChaCha20Poly1305& operator=(const FSChaCha20Poly1305&) = delete; FSChaCha20Poly1305& operator=(FSChaCha20Poly1305&&) = delete; /** Construct an FSChaCha20Poly1305 cipher that rekeys every rekey_interval operations. */ FSChaCha20Poly1305(Span<const std::byte> key, uint32_t rekey_interval) noexcept : m_aead(key), m_rekey_interval(rekey_interval) {} /** Encrypt a message with a specified aad. * * Requires cipher.size() = plain.size() + EXPANSION. */ void Encrypt(Span<const std::byte> plain, Span<const std::byte> aad, Span<std::byte> cipher) noexcept { Encrypt(plain, {}, aad, cipher); } /** Encrypt a message (given split into plain1 + plain2) with a specified aad. * * Requires cipher.size() = plain.size() + EXPANSION. */ void Encrypt(Span<const std::byte> plain1, Span<const std::byte> plain2, Span<const std::byte> aad, Span<std::byte> cipher) noexcept; /** Decrypt a message with a specified aad. Returns true if valid. * * Requires cipher.size() = plain.size() + EXPANSION. */ bool Decrypt(Span<const std::byte> cipher, Span<const std::byte> aad, Span<std::byte> plain) noexcept { return Decrypt(cipher, aad, plain, {}); } /** Decrypt a message with a specified aad and split the result. Returns true if valid. * * Requires cipher.size() = plain1.size() + plain2.size() + EXPANSION. */ bool Decrypt(Span<const std::byte> cipher, Span<const std::byte> aad, Span<std::byte> plain1, Span<std::byte> plain2) noexcept; }; #endif // BITCOIN_CRYPTO_CHACHA20POLY1305_H
c6ec65b86733dbbae726ef55fd5a18b45d1ed84d
2e5088011b47581d00f19321de701db460cf6aec
/practicas/0_pruebas/practica_3_ver_inicial.cpp
7ed94069a099e3cb0d0a0bfc8597d2cc081163f1
[]
no_license
nawjanimri/uned_fund_programacion
a4f4e1979dd050bb023c87260948637bdf76f913
82d4ec060a3b59a9e317792e52abde497c49313b
refs/heads/master
2020-04-03T09:35:44.208815
2019-01-10T15:48:40
2019-01-10T15:48:40
155,169,762
0
0
null
null
null
null
ISO-8859-1
C++
false
false
4,668
cpp
practica_3_ver_inicial.cpp
/* ************************************* * NOMBRE: #Jose Manuel# * PRIMER APELLIDO: #Alvarez# * SEGUNDO APELLIDO: #Bautista# * DNI: #29488955B# * EMAIL: #jalvarez1623@alumno.uned.es# ***************************************/ #include <stdio.h> int mes; /* Mes que se va a representar del calendario */ int anno; /* Año del Mes que se va a representar */ int bisiesto; /* 1 si es año bisiesto, 0 si no lo es*/ typedef char NombreMes[11]; /* Nombre de un mes, Ej. "Enero" */ typedef NombreMes TipoMes[13]; /* Meses de un año, de enero a diciembre */ const TipoMes meses = {"ENERO", "FEBRERO", "MARZO", "ABRIL", "MAYO", "JUNIO", "JULIO", "AGOSTO", "SEPTIEMBRE", "OCTUBRE", "DICIEMBRE"}; typedef char NombreDia[3]; /* Nombre de un día, Ej. "Lu" para lunes */ typedef NombreDia TipoSemana[8]; /* Días de una semana, de lunes a domingo */ const TipoSemana dias = {"LU", "MA", "MI", "JU", "VI", "SA", "DO"}; typedef int DiasMes[12]; const DiasMes diasmensuales = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int unoenero1601 = 0; /* Fué lunes, primer día de la semana, índice 0. */ void LeerMes(){ printf("¿Mes (1..12)?"); scanf("%2d", &mes); mes = mes-1; } void LeerAnno(){ printf("¿Anno (1601...3000)?"); scanf("%4d", &anno); } int EsBisiesto(int anno){ if (anno%4==0){ if (anno%100==0){ if(anno%400==0){ return 1; /* Sí es bisiesto */ } else{ return 0; /* No es bisiesto */ } } else{ return 1; /* Sí es bisiesto */ } } else{ return 0; /* No es bisiesto */ } } int NumeroBisiestosHasta(int anno){ int num_bisiestos = 0; /* Número de años bisiestos hasta el año indicado */ for (int i=1601; i<anno; i++){ num_bisiestos = num_bisiestos + EsBisiesto(i); } printf("Hasta el anno %4d hay %4d bisiestos \n", anno, num_bisiestos); return num_bisiestos; } int PrimerDiaDelMes(int mes, int anno){ int num_dias; /* Número de días que han trascurrido entre el 1 enero 1601 y el mes indicado */ /* Numero de días hasta el 1 de enero del año indicado */ int num_annos; int num_bisiestos; int num_dias_hasta_1_enero; int dia_del_1_enero; int dia_1_del_mes; int num_dias_hasta_mes; typedef char nombre[3]; num_bisiestos = NumeroBisiestosHasta(anno); num_annos = anno - 1601; num_dias_hasta_1_enero = num_annos*365 + num_bisiestos; printf("numero de dias hasta 1 enero de %4d = %5d \n", anno, num_dias_hasta_1_enero); /* El primer día de ese año cae en el día */ dia_del_1_enero = num_dias_hasta_1_enero%7; printf("Cae en el día de la semana = %s \n", dias[dia_del_1_enero]); /* Y el primer día de ese mes cae en el día */ num_dias_hasta_mes = 0; for (int i=0; i<mes; i++){ if (i==1){ if (EsBisiesto(anno)==1){ num_dias_hasta_mes = num_dias_hasta_mes+29; } else{ num_dias_hasta_mes = num_dias_hasta_mes+28; } } else{ num_dias_hasta_mes = num_dias_hasta_mes + diasmensuales[i]; } } printf("Número de días hasta mes %s = %3d \n", meses[mes], num_dias_hasta_mes); num_dias_hasta_mes = num_dias_hasta_1_enero + num_dias_hasta_mes; dia_1_del_mes = num_dias_hasta_mes%7; printf("Y el primer día del mes %s cae en el día de la semana = %s \n", meses[mes], dias[dia_1_del_mes]); return dia_1_del_mes; } void ImprimeMes(int mes, int anno, int primerdia){ int num_dias_mes; int dia_semana; num_dias_mes = diasmensuales[mes]; printf("%s %4d \n", meses[mes], anno); printf("===========================\n"); printf("LU MA MI JU VI | SA DO\n"); printf("===========================\n"); /* Días en blanco hasta el primer día del mes */ dia_semana = 0; /* Lunes */ for (int i=0; i<primerdia; i++){ printf(" . "); dia_semana = dia_semana+1; } /* Días del mes */ for (int i=1; i<num_dias_mes+1; i++){ dia_semana = dia_semana+1; printf(" %2d ", i); if(dia_semana==7){ printf("\n"); dia_semana = 0; } } /* Días en blanco hasta completar el mes */ for (int i=dia_semana; i<7; i++){ printf(" . "); dia_semana = dia_semana+1; } } /*===================*\ Programa principal \*===================*/ int main(){ int primerdia; LeerMes(); LeerAnno(); printf("Mes %s y anno %4d", meses[mes], anno); printf("\n"); if ((anno>1600)&&(anno<3001)){ bisiesto = EsBisiesto(anno); printf("¿Es bisiesto? = %1d \n", bisiesto); primerdia = PrimerDiaDelMes(mes, anno); ImprimeMes(mes, anno, primerdia); } }
505817a09d09a0d4909603cbc63600a0c6559e47
34e0a89e7c9ab88d80d6ee1435990bf873c26d58
/src/ui/Model.h
47e4d72c3503d8cf8a14093afd20d2061dd1713d
[]
no_license
dxinteractive/blend2-pedal
63becf70bd36d41f2f3d0671bdd92bd90d8581f4
b59b01cea65a6bce38878625ef1ba353a89fe09b
refs/heads/master
2022-06-19T08:44:04.940866
2019-06-10T10:32:07
2019-06-10T10:32:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,991
h
Model.h
/* * Blend^2 guitar pedal loop blender and router.\ * * Copyright (c) 2017 Damien Clarke * damienclarke.me | github.com/dxinteractive/Blend2 * * |~)| _ _ _| 2 * |_)|(/_| |(_| * */ #ifndef MODEL_H #define MODEL_H #include <Stackui.h> #include "../model/Blender.h" #include "../model/BlendPreset.h" #include "../model/Router.h" #include "../model/Shuffler.h" #include "../model/ShufflerData.h" class Model: public StackuiModel { public: Model(const BlendPreset* blendPresets, int blendPresetsTotal): StackuiModel(), blender(blendPresets, blendPresetsTotal) {} virtual ~Model() {} virtual void setup(); int getBlendPreset() const; int setBlendPreset(int presetId); int nextBlendPreset(); int prevBlendPreset(); char const* blendPresetName() const; float getBlendKeyframe(int ampId, int keyframe) const; float const* getBlendKeyframes() const; float setBlendKeyframe(int ampId, int keyframe, float value); float setBlendPosition(float blend); float getBlendedValue(int ampId) const; float getBlendedValue(int ampId, float blend) const; int getZPosition() const; int setZPosition(int newZPosition); int nextZPosition(); char const* getZPositionLabel() const; char const* getZPositionLabel(int zPosition) const; int getDryPosition() const; int setDryPosition(int newDryPosition); int nextDryPosition(); char const* getDryPositionLabel() const; char const* getDryPositionLabel(int dryPosition) const; int getPolarityOption() const; int setPolarityOption(int newPolarityOption); int nextPolarityOption(); char const* getPolarityOptionLabel() const; char const* getPolarityOptionLabel(int polarityOption) const; ShufflerData const* getShufflerData() const; void updateShuffler(); private: Blender blender; Router router; Shuffler shuffler; }; #endif
ec7805b661c6d26e11e5d76c4eb2db5dae84c6d9
223995abcbcbbb50daad4fcb66e280beb6eb0c0d
/day_6/[practice]_E.cpp
96281b972f87ac4ce1c9ae621821c9ad15c8b61a
[]
no_license
tksgo2582/SDS_algorithm
7bcb19bb5599f5993bd3d9627c0efd9a336980e5
1bd4b58fcc9f3ad4f1ee63353c8fe377ef46cfc3
refs/heads/master
2023-03-12T07:15:32.678765
2021-02-24T19:25:37
2021-02-24T19:25:37
327,844,378
2
0
null
null
null
null
UTF-8
C++
false
false
1,263
cpp
[practice]_E.cpp
//d위상 정렬 문제, #include <bits/stdc++.h> using namespace std; #define MAX 510 int N, M; vector<int> parent[MAX], child[MAX]; bool visited[MAX], rev_visited[MAX]; int cnt, rev_cnt, ans = 0;; /* 1. 체크인 2. 목적지에 도착했는가? 3. 연결된 곳을 순회 4. 갈 수 있는가? 5. 간다 6. 체크아웃 */ void dfs(int cur){ if(visited[cur]) return; visited[cur] = true; cnt++; for(int i =0 ; i < parent[cur].size(); i++){ int next = parent[cur][i]; dfs(next); } } void rev_dfs(int cur){ if(rev_visited[cur]) return; rev_visited[cur] = true; rev_cnt++; for(int i = 0; i < child[cur].size(); i ++){ int tmp = child[cur][i]; rev_dfs(tmp); } } int main(){ cin >> N >> M; for(int i =0 ; i < M; i++){ int a,b; cin >> a>> b; parent[a].push_back(b); // a--> 연결 child[b].push_back(a); } for(int i = 1 ; i <= N; i++){ cnt = 0; memset(visited, 0x00, sizeof(visited) ); dfs(i); rev_cnt = 0; memset(rev_visited, 0x00 , sizeof(rev_visited)); rev_dfs(i); if(cnt+rev_cnt == N -1) ans++; } cout << ans; }
7bb73441e35e94b1a7d774abc272ea0a57f078f3
08bd24caff7ebafe8946bb20a410a2adce23ccf9
/DrawGraph/aaa.cpp
d4544a54076ec6751764ae939dc63d088cc7808b
[]
no_license
UniqueOnly/DrawGraph
78831485830e0d224f57353a9164b038bbaff555
1f605c894ca834f36da40bf2bcb2bf74e2a2cb96
refs/heads/master
2016-09-03T07:36:51.303001
2014-08-11T10:25:35
2014-08-11T10:25:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,608
cpp
aaa.cpp
// aaa.cpp : implementation file // #include "stdafx.h" #include "te.h" #include "aaa.h" //#include "instrucments.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // aaa dialog aaa::aaa(CWnd* pParent /*=NULL*/) : CDialog(aaa::IDD, pParent) { //{{AFX_DATA_INIT(aaa) m_x1 = 0; m_y1 = 0; m_x2 = 0; m_y2 = 0; m_x3 = 0; m_y3 = 0; m_zChang = _T(""); m_mJi = _T(""); m_Len12 = _T(""); m_Len23 = _T(""); m_Len31 = _T(""); //}}AFX_DATA_INIT } /*aaa::aaa(CPoint p1,CPoint p2,CPoint p3) { m_x1 = p1.x; m_y1 = p1.y; m_x2 = p2.x; m_y2 = p2.y; m_x3 = p3.x; m_y3 = p3.y; }*/ void aaa::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(aaa) DDX_Control(pDX, IDC_BUTTON1, m_Cal); DDX_Text(pDX, IDC_EDIT1, m_x1); DDX_Text(pDX, IDC_EDIT2, m_y1); DDX_Text(pDX, IDC_EDIT3, m_x2); DDX_Text(pDX, IDC_EDIT4, m_y2); DDX_Text(pDX, IDC_EDIT5, m_x3); DDX_Text(pDX, IDC_EDIT6, m_y3); DDX_Text(pDX, IDC_EDIT7, m_zChang); DDX_Text(pDX, IDC_EDIT8, m_mJi); DDX_Text(pDX, IDC_EDIT9, m_Len12); DDX_Text(pDX, IDC_EDIT10, m_Len23); DDX_Text(pDX, IDC_EDIT11, m_Len31); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(aaa, CDialog) //{{AFX_MSG_MAP(aaa) ON_BN_CLICKED(IDC_BUTTON1, OnButton1) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // aaa message handlers void aaa::OnButton1() { UpdateData(TRUE); // TODO: Add your control notification handler code here double len12,len23,len31; double zhouC,mianJ; CString str_z,str_m,str_len12,str_len23,str_len31; len12=sqrt((m_x1-m_x2)*(m_x1-m_x2)+(m_y1-m_y2)*(m_y1-m_y2)); len23=sqrt((m_x2-m_x3)*(m_x2-m_x3)+(m_y2-m_y3)*(m_y2-m_y3)); len31=sqrt((m_x3-m_x1)*(m_x3-m_x1)+(m_y3-m_y1)*(m_y3-m_y1)); zhouC=len12+len23+len31; mianJ=fabs((m_x2-m_x1)*(m_y2+m_y1)+(m_x3-m_x2)*(m_y3+m_y2)-(m_x3-m_x1)*(m_y3+m_y1))/2; str_z.Format("%.2f",zhouC); m_zChang=str_z; // SetDlgItemText(IDC_EDIT7,str_z); // m_zChang=zhouC; str_m.Format("%.2f",mianJ); m_mJi=str_m; // SetDlgItemText(IDC_EDIT8,str_m); // m_mJi=mianJ; str_len12.Format("%.2f",len12); m_Len12=str_len12; str_len23.Format("%.2f",len23); m_Len23=str_len23; str_len31.Format("%.2f",len31); m_Len31=str_len31; UpdateData(FALSE); } /*void aaa::OnButton2() { // TODO: Add your control notification handler code here instrucments dg; dg.DoModal(); }*/
82ddd18b967ef9934d394af6701c7fac582e1aeb
659477b4e96ba1044b49e2272fe06f8c79ff1e87
/OpenGL_FrameWork/Codes/CollisionMgr.cpp
4bfa910c3eb1e651ff6e63d9f06840aad7ca8b0a
[]
no_license
ParkSeJun/2020_CG_Project
a64c9f431f0701950ed9dd29a8300565cd594271
c8bda82509b8a8d4714de731e290881da8eda368
refs/heads/master
2023-02-01T04:23:04.090963
2020-12-16T00:03:04
2020-12-16T00:03:04
321,635,529
0
1
null
null
null
null
UTF-8
C++
false
false
1,401
cpp
CollisionMgr.cpp
#include "pch.h" #include "..\Headers\CollisionMgr.h" #include "Transform.h" #include "Obj.h" #include "Food.h" _IMPLEMENT_SINGLETON(CCollisionMgr) CCollisionMgr::CCollisionMgr() { } CCollisionMgr::~CCollisionMgr() { } bool CCollisionMgr::Check_Collision(vector<CObj*> pTargetLst, vector<CObj*> pBulletLst) { _float fLenght = 0.f; for (auto& pTarget : pTargetLst) { for (auto& iter : pBulletLst) { fLenght = length(*pTarget->GetTransform()->Get_StateInfo(STATE_POSITION) - *iter->GetTransform()->Get_StateInfo(STATE_POSITION)); if (fLenght <= 1.5f) { vec3 center = vec3(63.f, 0.f, 63.f); pTarget->GetTransform()->Set_StateInfo(STATE_POSITION, &center); PlaySound(TEXT(RESTART_SOUND_FILE), NULL, SND_ASYNC); return true; } } } } bool IsFoodAllDie(vector<CObj*> pFoodLst) { for (auto& iter : pFoodLst) { CFood* food = dynamic_cast<CFood*>(iter); if (!food->IsDie()) return false; } return true; } bool CCollisionMgr::Check_Collision_Food(CObj* pPlayer, vector<CObj*> pFoodLst) { _float fLenght = 0.f; for (auto& iter : pFoodLst) { CFood* food = dynamic_cast<CFood*>(iter); if (food->IsDie()) continue; fLenght = length(*pPlayer->GetTransform()->Get_StateInfo(STATE_POSITION) - *iter->GetTransform()->Get_StateInfo(STATE_POSITION)); if (fLenght <= 2.f) { food->Die(); return IsFoodAllDie(pFoodLst); } } return false; }
ebef8556b8c6eaeb52b50087de5edb3ee036809c
14582f8c74c28d346399f877b9957d0332ba1c3c
/branches/pstade_1_03_5_head/pstade_subversive/pstade/junk/recursion.hpp
60191c4867e3a0080cbd2d42f57319ee4a3879df
[]
no_license
svn2github/p-stade
c7b421be9eeb8327ddd04d3cb36822ba1331a43e
909b46567aa203d960fe76055adafc3fdc48e8a5
refs/heads/master
2016-09-05T22:14:09.460711
2014-08-22T08:16:11
2014-08-22T08:16:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,136
hpp
recursion.hpp
#ifndef PSTADE_OVEN_RECURSION_HPP #define PSTADE_OVEN_RECURSION_HPP // PStade.Oven // // Copyright Shunsuke Sogame 2005-2007. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/assert.hpp> #include <boost/iterator/iterator_facade.hpp> #include <boost/optional.hpp> #include <boost/range/begin.hpp> #include <boost/range/end.hpp> #include <pstade/for_debug.hpp> #include <pstade/function.hpp> #include "./concepts.hpp" #include "./detail/next_prior.hpp" // next #include "./iter_range.hpp" #include "./range_difference.hpp" #include "./range_reference.hpp" #include "./range_traversal.hpp" #include "./range_value.hpp" namespace pstade { namespace oven { namespace recursion_detail { template< class Range > struct lazy_iterator; template< class Range > struct lazy_iterator_super { typedef boost::iterator_facade< lazy_iterator<Range>, typename range_value<Range>::type, typename range_pure_traversal<Range>::type, typename range_reference<Range>::type, typename range_difference<Range>::type > type; }; template< class Range > struct lazy_iterator : lazy_iterator_super<Range>::type { private: typedef typename lazy_iterator_super<Range>::type super_t; typedef typename super_t::reference ref_t; typedef typename super_t::difference_type diff_t; public: lazy_iterator() { } template< class > friend struct lazy_iterator; lazy_iterator(Range& rng, bool is_end) : m_prng(boost::addressof(rng)), m_is_from_end(is_end), m_saved_diff(0) { } typedef typename range_iterator<Range>::type base_type; base_type const& base() const { init_base(); return *m_obase; } Range& base_range() const { return *m_prng; } private: Range *m_prng; bool m_is_from_end; diff_t m_saved_diff; mutable boost::optional<base_type> m_obase; void init_base() const { if (m_obase) return; m_obase = !m_is_from_end ? boost::begin(*m_prng) : boost::end(*m_prng); m_obase = detail::next(*m_obase, m_saved_diff); } template< class Other > bool is_compatible(Other const& other) const { for_debug(); return m_prng == other.m_prng; } bool is_maybe_non_end() const { for_debug(); if (m_obase) // non-checkable return true; return m_is_from_end ? m_saved_diff < 0 : true; } friend class boost::iterator_core_access; ref_t dereference() const { BOOST_ASSERT(is_maybe_non_end()); init_base(); return *base(); } template< class Other > bool equal(Other const& other) const { BOOST_ASSERT(is_compatible(other)); // They never meet in infinite range. if (m_is_from_end != other.m_is_from_end) return false; if (m_obase || other.m_obase) return base() == other.base(); else return m_saved_diff == other.m_saved_diff; } void increment() { BOOST_ASSERT(is_maybe_non_end()); if (m_obase) ++*m_obase; else ++m_saved_diff; } void decrement() { if (m_obase) --*m_obase; else --m_saved_diff; } void advance(diff_t const& d) { if (m_obase) *m_obase += d; else m_saved_diff += d; } template< class Other > diff_t distance_to(Other const& other) const { BOOST_ASSERT(is_compatible(other)); BOOST_ASSERT("infinite difference" && m_is_from_end == other.m_is_from_end); if (m_obase || other.m_obase) return other.base() - base(); else return other.m_saved_diff - m_saved_diff; } }; template< class Range > struct baby { typedef lazy_iterator<Range> iter_t; typedef iter_range<iter_t> const result; result call(Range& rng) { PSTADE_CONCEPT_ASSERT((SinglePass<Range>)); return result(iter_t(rng, false), iter_t(rng, true)); } }; } // recursion_detail PSTADE_FUNCTION(recursion, (recursion_detail::baby<_>)) } } // namespace pstade::oven #endif
5d7b7bd1fff9b62282cca353c3098cc277b1b1e0
4b24a445652f2342120ef8894a496494f7c1e13d
/VoxelMap/Light.h
9e500b00e6a50dc558b65aee451e84fc4c8b18e0
[]
no_license
KraftJrIvo/IVOxel
f1acf136f807dd66f8148dfff48a4234df0dfab0
8e75b7f88d7fbad02b8332b5bc2f1bf65cd88d56
refs/heads/master
2021-09-21T13:02:21.733370
2021-09-13T19:34:44
2021-09-13T19:34:44
230,286,861
2
0
null
null
null
null
UTF-8
C++
false
false
322
h
Light.h
#pragma once #include <vector> enum LightType : unsigned char { NONE, AMBIENT, GLOBAL, LOCAL }; struct Light { Light(LightType type = NONE, const std::vector<uint8_t> rgba = { 0,0,0,0 }, const std::vector<float> position = { 0,0,0 }); LightType type; std::vector<float> position; std::vector<uint8_t> rgba; };
d65de3a58aab39515277d49deaa5fdf3e96f7f5a
ec53fa6d944ba104a17696d334cfbbf867145f0a
/zarun/backend/backend_context_delegate.h
4f29e84ced3d6321324604ce851abdafc27ae6dc
[]
no_license
zalemwoo/zarun
83f20ea7807973ce84646c05500daa1df24ab5f2
d1177881bf5e0028afa80c0eb1aded99fc862a04
refs/heads/master
2016-09-05T18:47:53.523668
2015-11-10T07:55:00
2015-11-10T07:55:00
26,324,736
0
0
null
null
null
null
UTF-8
C++
false
false
1,426
h
backend_context_delegate.h
/* * backend_context_delegate.h * */ #ifndef ZARUN_BACKEND_BACKEND_CONTEXT_DELEGATE_H_ #define ZARUN_BACKEND_BACKEND_CONTEXT_DELEGATE_H_ #include "base/callback.h" #include "base/memory/scoped_ptr.h" #include "gin/try_catch.h" #include "zarun/zarun_export.h" #include "zarun/script_context.h" namespace zarun { namespace backend { typedef base::Callback<void(std::string)> RunScriptCallback; class ZARUN_EXPORT BackendScriptContextDelegate : public ScriptContextDelegate { public: BackendScriptContextDelegate(); BackendScriptContextDelegate(RunScriptCallback runscript_callback); ~BackendScriptContextDelegate() override; void UnhandledException(zarun::ScriptContext* context, gin::TryCatch& try_catch) override; protected: // From ShellRunnerDelegate: v8::Handle<v8::ObjectTemplate> GetGlobalTemplate( v8::Isolate* isolate) override; void DidCreateContext(zarun::ScriptContext* context) override; void DidRunScript(zarun::ScriptContext* context) override; private: RunScriptCallback runscript_callback_; DISALLOW_COPY_AND_ASSIGN(BackendScriptContextDelegate); }; scoped_ptr<BackendScriptContextDelegate> CreateBackendScriptContextDelegate(); scoped_ptr<BackendScriptContextDelegate> CreateBackendScriptContextDelegate( const RunScriptCallback& runscript_callback); } } // namespace zarun::backend #endif // ZARUN_BACKEND_BACKEND_CONTEXT_DELEGATE_H_
168ed507970ddb2be0f43a0748feb53838ec1bcf
2a508ef51f861e91dae88712b8d86164014e20b0
/arraysum.cpp
468947cfe4af02a8295ebca896f5bacc9f656eb5
[]
no_license
swapnil20711/CPP
c17077a195bb87be3572e7c9a54a01c5b621f504
2ed3dbcb42a828282806a4962bf998008086a87c
refs/heads/master
2022-08-07T13:40:18.726845
2020-05-25T11:08:13
2020-05-25T11:08:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
337
cpp
arraysum.cpp
//Program to print sum of array elements #include<iostream> using namespace std; int main() { int i,n,arraySum=0; cout<<"Enter the size of array"<<endl; cin>>n; int arr[n]; cout<<"Enter the array elements"<<endl; for(i=0;i<n;i++) { cin>>arr[i]; } for(i=0;i<n;i++) { arraySum+=arr[i]; } cout<<"Array sum is "<<arraySum; return 0; }
4447b0e4da331570aed60e2015506c99771ed070
4e38ed925e356e7efe6b0918429dad19e23fe700
/mmshplugins/mmshsettingsuiplugin/src/mussettingsplugin.cpp
020c3767c8ca6abf56f2b37f0e0859c50f2a538c
[]
no_license
SymbianSource/oss.FCL.sf.app.mmsharinguis
75a90aebd091f5ebcedfe1e6cc3a3ff2043e31fa
9054f87d8ed408d79a305f09d720e6812e12244c
refs/heads/master
2021-01-10T22:41:23.550567
2010-10-03T21:13:53
2010-10-03T21:13:53
70,368,951
0
0
null
null
null
null
UTF-8
C++
false
false
30,094
cpp
mussettingsplugin.cpp
/* * Copyright (c) 2006-2007 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: MUSSettingsPlugin implementation. * */ #include "mussettingsplugin.h" #include "mussettingscontainer.h" #include "mussettingsmodel.h" #include "mussettingsplugin.hrh" #include "mussipprofilemodel.h" #include "muslogger.h" #include "musresourcefinderutil.h" #include "mussesseioninformationapi.h" #include <gscommon.hrh> #include <mussettingsplugin.mbg> // Icons #include <mussettingsuirsc.rsg> // GUI Resource #include <gsprivatepluginproviderids.h> #include <aknnotewrappers.h> #include <aknradiobuttonsettingpage.h> #include <aknpopupsettingpage.h> #include <akntextsettingpage.h> #include <aknViewAppUi.h> #include <AknGlobalNote.h> #include <featmgr.h> #include <StringLoader.h> #include <hlplch.h> // HlpLauncher #include <pathinfo.h> #include <e32property.h> #include <CAknMemorySelectionDialogMultiDrive.h> #include <AknCommonDialogsDynMem.h> #include <CAknMemorySelectionDialog.h> // #include <CAknMemorySelectionDialog.h> // ======== MEMBER FUNCTIONS ======== CMusSettingsPlugin::CMusSettingsPlugin() : iResources( *iCoeEnv ) { MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::CMusSettingsPlugin()" ) } CMusSettingsPlugin::~CMusSettingsPlugin() { MUS_LOG( "[MUSSET] -> CMusSettingsPlugin::~CMusSettingsPlugin()" ) FeatureManager::UnInitializeLib(); if( iContainer ) { AppUi()->RemoveFromViewStack( *this, iContainer ); delete iContainer; iContainer = NULL; } iResources.Close(); delete iModel; iModel = NULL; delete iHandler; iHandler = NULL; delete iDiskNotifyHandler; MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::~CMusSettingsPlugin()" ) } void CMusSettingsPlugin::ConstructL() { MUS_LOG( "[MUSSET] -> CMusSettingsPlugin::ConstructL()" ) FeatureManager::InitializeLibL(); HBufC* fileName = MusResourceFinderUtil::ResourcePathL( KVSSettingsResourceFileName ); TFileName fName(*fileName); delete fileName; MUS_LOG_TDESC( "[MUSSET] Resource FileName ",fName ) iResources.OpenL(fName); MUS_LOG( "[MUSSET] Constructing the Base " ) BaseConstructL( R_GS_VS_VIEW ); iHandler = CMusSIPProfileModel::NewL(); MUS_LOG( "[MUSSET] CMusSettingsPlugin::ConstructL() 2" ) iModel = CMusSettingsModel::NewL( *iHandler ); iDiskNotifyHandler = CDiskNotifyHandler::NewL( *this, iEikonEnv->FsSession() ); User::LeaveIfError( iDiskNotifyHandler->NotifyDisk() ); // Subscribe disk notifications MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::ConstructL()" ) } CMusSettingsPlugin* CMusSettingsPlugin::NewL( TAny* /*aInitParams*/ ) { MUS_LOG( "[MUSSET] -> CMusSettingsPlugin::NewL()" ) CMusSettingsPlugin* self = new( ELeave ) CMusSettingsPlugin(); CleanupStack::PushL(self); self->ConstructL(); CleanupStack::Pop(self); MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::NewL()" ) return self; } // ---------------------------------------------------------------------------- // From class CAknView. // Returns UID of *this* settings plugin. // ---------------------------------------------------------------------------- // TUid CMusSettingsPlugin::Id() const { MUS_LOG1( "[MUSSET] <- CMusSettingsPlugin::Id()( %d )", KGSVSSettingsPluginUID.iUid ) return KGSVSSettingsPluginUID; } // ---------------------------------------------------------------------------- // Hides non-virtual member from base class CGSBaseView. // Handles a change in client rectangle size. // ---------------------------------------------------------------------------- // void CMusSettingsPlugin::HandleClientRectChange() { MUS_LOG( "[MUSSET] -> CMusSettingsPlugin::HandleClientRectChange()" ) if ( iContainer && iContainer->iListBox ) { iContainer->SetRect( ClientRect() ); } MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::HandleClientRectChange()" ) } // ---------------------------------------------------------------------------- // From class CAknView. // Called by framework when *this* control is to be activated/focused. // ---------------------------------------------------------------------------- // void CMusSettingsPlugin::DoActivateL( const TVwsViewId& aPrevViewId, TUid aCustomMessageId, const TDesC8& aCustomMessage ) { MUS_LOG( "[MUSSET] -> CMusSettingsPlugin::DoActivateL()" ) CGSBaseView::DoActivateL( aPrevViewId, aCustomMessageId, aCustomMessage ); MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::DoActivateL()" ) } // ---------------------------------------------------------------------------- // From class CAknView. // Called by framework when *this* control is to be deactivated. // ---------------------------------------------------------------------------- // void CMusSettingsPlugin::DoDeactivate() { MUS_LOG( "[MUSSET] -> CMusSettingsPlugin::DoDeactivate()" ) CGSBaseView::DoDeactivate(); MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::DoDeactivate()" ) } // ---------------------------------------------------------------------------- // From class CAknView. // Handles a user selected menu command. // ---------------------------------------------------------------------------- // void CMusSettingsPlugin::HandleCommandL( TInt aCommand ) { MUS_LOG1( "[MUSSET] -> CMusSettingsPlugin::HandleCommandL()( %d )", aCommand ) CMusSettingsContainer& container = *static_cast<CMusSettingsContainer*>( iContainer ); const TInt currentItem = container.CurrentFeatureId(); switch ( aCommand ) { case EGSMSKCmdAppChange: case EGSCmdAppChange: { if ( currentItem == KGSSettIdVSActivation && aCommand == EGSCmdAppChange ) { if ( iModel->VSSettingsOperatorVariantL() == MusSettingsKeys::EOperatorSpecific ) { ShowOperatorSpecificActivationSettingDialogL(); } else { ShowVSSettingsActivationSettingDialogL(); } } else if ( currentItem == KGSSettIdRecordedVideoSaving && aCommand == EGSCmdAppChange ) { ShowVSSettingsRecordedVideoSavingSettingDialogL(); } else if ( KGSSettIdNote == currentItem && EGSCmdAppChange == aCommand ) { ShowVSSettingsNoteSettingDialogL(); } else { HandleListBoxSelectionL(); } break; } case EAknSoftkeyBack: { AppUi()->ActivateLocalViewL( iPrevViewId.iViewUid ); break; } case EAknCmdHelp: { if( FeatureManager::FeatureSupported( KFeatureIdHelp ) ) { HlpLauncher::LaunchHelpApplicationL( iEikonEnv->WsSession(), AppUi()->AppHelpContextL()); } break; } default: { AppUi()->HandleCommandL( aCommand ); break; } } MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::HandleCommandL()" ) } // ---------------------------------------------------------------------------- // From class CGSPluginInterface. // Gets caption text of *this* plugin. // ---------------------------------------------------------------------------- // void CMusSettingsPlugin::GetCaptionL( TDes& aCaption ) const { MUS_LOG( "[MUSSET] -> CMusSettingsPlugin::GetCaptionL()" ) HBufC* result = StringLoader::LoadL( R_GS_VS_PLUGIN_CAPTION ); aCaption.Copy( *result ); delete result; MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::GetCaptionL()" ) } // ---------------------------------------------------------------------------- // From class CGSPluginInterface. // Returns provider category of *this* plugin. // ---------------------------------------------------------------------------- // TInt CMusSettingsPlugin::PluginProviderCategory() const { MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::PluginProviderCategory()" ) return KGSPluginProviderInternal; } // ---------------------------------------------------------------------------- // From class MEikMenuObserver. // Called by framework before creating menus // ---------------------------------------------------------------------------- // void CMusSettingsPlugin::DynInitMenuPaneL( TInt aResourceId, CEikMenuPane* aMenuPane ) { // Delete Help item if feature is not supported if( aResourceId == R_VS_MENU_ITEM_EXIT ) { if( !FeatureManager::FeatureSupported( KFeatureIdHelp ) ) { aMenuPane->DeleteMenuItem( EAknCmdHelp ); } } } // ---------------------------------------------------------------------------- // From MDiskNotifyHandlerCallback // Called by framework When disk status changed // ---------------------------------------------------------------------------- // void CMusSettingsPlugin::HandleNotifyDisk( TInt /*aError*/, const TDiskEvent& /*aEvent*/ ) { MUS_LOG( "[MUSSET] -> CMusSettingsPlugin::HandleNotifyDisk()" ) // Since the plugin is created immediately after opening GS but container // will be created only after opening the VS view, this function may be // called before the creation of container. In such a case we simply ignore // the notification. if ( Container() ) { TRAP_IGNORE( Container()->UpdateListBoxL( KGSSettIdRecordedVideoSaving ) ) } MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::HandleNotifyDisk()" ) } // ---------------------------------------------------------------------------- // From class CGSBaseView. // Called by GS framework to create a GS container for *this* plugin. // ---------------------------------------------------------------------------- // void CMusSettingsPlugin::NewContainerL() { MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::NewContainerL()" ) iContainer = new( ELeave ) CMusSettingsContainer( *iModel ); } // ---------------------------------------------------------------------------- // From class CGSBaseView. // Handles users "middle click" aka MSK on selected feature. // ---------------------------------------------------------------------------- // void CMusSettingsPlugin::HandleListBoxSelectionL() { MUS_LOG( "[MUSSET] -> CMusSettingsPlugin::HandleListBoxSelectionL()" ) CMusSettingsContainer& container = *static_cast<CMusSettingsContainer*>( iContainer ); const TInt currentItem = container.CurrentFeatureId(); RDebug::Print( _L( "[CMusSettingsPlugin] Item selected: %d" ), currentItem ); MusSettingsKeys::TOperatorVariant operatorVarValue = iModel->VSSettingsOperatorVariantL(); switch ( currentItem ) { case KGSSettIdVSActivation: { if ( operatorVarValue == MusSettingsKeys::EOperatorSpecific ) { SwitchOnOffValueL( KGSSettIdVSActivation ); container.UpdateListBoxL( KGSSettIdVSActivation ); } else { ShowVSSettingsActivationSettingDialogL(); } break; } case KGSSettIdSIPProfile: { ShowVSSettingsProfileSettingDialogL(); break; } case KGSSettIdAutoRecord: { SwitchOnOffValueL( KGSSettIdAutoRecord ); container.UpdateListBoxL( KGSSettIdAutoRecord ); break; } case KGSSettIdRecordedVideoSaving: { ShowVSSettingsRecordedVideoSavingSettingDialogL(); // SwitchOnOffValueL( KGSSettIdRecordedVideoSaving ); // container.UpdateListBoxL( KGSSettIdRecordedVideoSaving ); break; } case KGSSettIdNote: { SwitchOnOffValueL( KGSSettIdNote ); container.UpdateListBoxL( KGSSettIdNote ); break; } default: { break; } } MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::HandleListBoxSelectionL()" ) } // ---------------------------------------------------------------------------- // From class CGSBaseView. // Returns container class of *this* plugin. iContainer is always garanteed to // be of type CMusSettingsContainer*. // ---------------------------------------------------------------------------- // CMusSettingsContainer* CMusSettingsPlugin::Container() { MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::Container()" ) return static_cast<CMusSettingsContainer*>( iContainer ); } // ---------------------------------------------------------------------------- // Shows a dialog for user to modify VS activation setting. Note that this // method has an alternative method for operator specific variant. // ---------------------------------------------------------------------------- // void CMusSettingsPlugin::ShowVSSettingsActivationSettingDialogL() { MUS_LOG( "[MUSSET] -> CMusSettingsPlugin::ShowVSSettingsActivationSettingDialogL()" ) MusSettingsKeys::TActivation currentValue = iModel->VSSettingsActivationL(); CDesCArrayFlat* items = iCoeEnv->ReadDesC16ArrayResourceL( R_ACTIVATION_SETTING_PAGE_LBX ); CleanupStack::PushL( items ); TInt intCurrentValue = static_cast<TInt>( currentValue ); CAknRadioButtonSettingPage* dlg = new ( ELeave ) CAknRadioButtonSettingPage( R_ACTIVATION_SETTING_PAGE, intCurrentValue, items); if ( dlg->ExecuteLD( CAknSettingPage::EUpdateWhenChanged ) ) { currentValue = static_cast<MusSettingsKeys::TActivation>( intCurrentValue ); iModel->SetVSSettingsActivationL( currentValue ); Container()->UpdateListBoxL( KGSSettIdVSActivation ); } CleanupStack::PopAndDestroy( items ); MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::ShowVSSettingsActivationSettingDialogL()" ) } // ---------------------------------------------------------------------------- // Shows a dialog for user to modify VS activation setting. Note that this // method is used only for operator specific variant. Alternative method for // "standard" variant exists. Note that because standard variant contains 3 // different values and operator variant contains only 2 values (0,2) the value // 2 (MusSettingsKeys::ENever) is converted to value 1 // (MusSettingsKeys::EActiveInHomeNetworks) in operator variant just before // showing the dialog. After showing the dialog the conversion mentioned above // is reversed. This temporarily conversion is done solely to use values 0 and // 1 for direct mapping to items array. // ---------------------------------------------------------------------------- // void CMusSettingsPlugin::ShowOperatorSpecificActivationSettingDialogL() { MUS_LOG( "[MUSSET] -> CMusSettingsPlugin::ShowOperatorSpecificActivationSettingDialogL()" ) MusSettingsKeys::TActivation currentValue = iModel->VSSettingsActivationL(); if ( currentValue == MusSettingsKeys::ENever ) { currentValue = MusSettingsKeys::EActiveInHomeNetworks; } CDesCArrayFlat* items = iCoeEnv->ReadDesC16ArrayResourceL( R_OPERATOR_ACTIVATION_SETTING_PAGE_LBX); CleanupStack::PushL( items ); TInt intCurrentValue = static_cast<TInt>(currentValue); CAknRadioButtonSettingPage* dlg = new ( ELeave ) CAknRadioButtonSettingPage( R_ACTIVATION_SETTING_PAGE, intCurrentValue, items ); if ( dlg->ExecuteLD( CAknSettingPage::EUpdateWhenChanged ) ) { currentValue = static_cast<MusSettingsKeys::TActivation>( intCurrentValue ); if ( currentValue == MusSettingsKeys::EActiveInHomeNetworks ) { currentValue = MusSettingsKeys::ENever; } iModel->SetVSSettingsActivationL( currentValue ); Container()->UpdateListBoxL( KGSSettIdVSActivation ); } CleanupStack::PopAndDestroy( items ); MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::ShowOperatorSpecificActivationSettingDialogL()" ) } // ---------------------------------------------------------------------------- // Shows SIP profile setting dialog (i.e. "use default profile" or "select // profile from list"). If select profile from list is selected, a list of // SIP profiles is provided for user to choose wanted SIP profile. // ---------------------------------------------------------------------------- // void CMusSettingsPlugin::ShowVSSettingsProfileSettingDialogL() { MUS_LOG( "[MUSSET] -> CMusSettingsPlugin::ShowVSSettingsProfileSettingDialogL()" ) TInt cenRepValue = iModel->VSSettingsProfileL(); TInt profileMode = CMusSettingsModel::KVsSipProfileDefault; if ( cenRepValue != CMusSettingsModel::KVsSipProfileDefault ) { profileMode = CMusSettingsModel::KVsSipProfileSelect; } TInt oldProfileMode( profileMode ); CDesCArrayFlat* items = iCoeEnv->ReadDesC16ArrayResourceL( R_SIP_PROFILE_SETTING_PAGE_LBX); CleanupStack::PushL( items ); items->Delete( CMusSettingsModel::KVsSipProfileSelectNone ); CAknRadioButtonSettingPage* dlg = new ( ELeave ) CAknRadioButtonSettingPage( R_VS_PROFILE_SETTING_PAGE, profileMode, items); if ( dlg->ExecuteLD( CAknSettingPage::EUpdateWhenChanged ) ) { if ( profileMode == CMusSettingsModel::KVsSipProfileDefault ) { if ( oldProfileMode != profileMode ) { iModel->SetVSSettingsProfileL( CMusSettingsModel::KVsSipProfileDefault ); Container()->ShowNewProfileActiveAfterCallL(); Container()->UpdateListBoxL( KGSSettIdSIPProfile ); } } else { ShowVSSettingsSelectSipProfileDialogL(); } } CleanupStack::PopAndDestroy( items ); MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::ShowVSSettingsProfileSettingDialogL()" ) } // ---------------------------------------------------------------------------- // Provides user a list of SIP profiles to select from. If no SIP profiles // exist an error note is displayed. // ---------------------------------------------------------------------------- // void CMusSettingsPlugin::ShowVSSettingsSelectSipProfileDialogL() { // Get the array of the profile names, ownership changes CDesCArray* array = iModel->ListOfProfileNamesL(); CleanupStack::PushL( array ); if ( array->Count() < 1 ) { ShowNoProfilesNotificationL(); } else { TInt selectedIndex = iModel->ProfileIndexByIdL( iModel->VSSettingsProfileL() ); TInt currentIndex ( selectedIndex ); if ( selectedIndex == KErrNotFound ) { // first profile in the list selectedIndex = CMusSettingsModel::KVsSipProfileDefault; } // Create and display the pop-up list CAknRadioButtonSettingPage* defaultPopUp = new ( ELeave ) CAknRadioButtonSettingPage( R_VS_SIP_PROFILE_LIST_VIEW_SELECT_SETTING_PAGE, selectedIndex, array ); if ( defaultPopUp->ExecuteLD( CAknSettingPage::EUpdateWhenChanged ) ) { if ( selectedIndex != currentIndex ) { // User has changed the selected profile, set new // setting to persistent storage TUint newValue = iModel->ProfileIdByIndex( selectedIndex ); iModel->SetVSSettingsProfileL( newValue ); Container()->ShowNewProfileActiveAfterCallL(); Container()->UpdateListBoxL( KGSSettIdSIPProfile ); } } } CleanupStack::PopAndDestroy( array ); // array } // ---------------------------------------------------------------------------- // Provides a dialog for user to choose saving location for recorderded video. // (locations are naturally phone memory or memory card). // ---------------------------------------------------------------------------- // void CMusSettingsPlugin::ShowVSSettingsRecordedVideoSavingSettingDialogL() { MUS_LOG( "[MUSSET] -> CMusSettingsPlugin::ShowVSSettingsRecordedVideoSavingSettingDialogL()" ) TDriveUnit phoneMemUnit( TParsePtrC( PathInfo::PhoneMemoryRootPath() ).Drive() ); TDriveUnit mmcUnit( TParsePtrC( PathInfo::MemoryCardRootPath() ).Drive() ); TInt currentValue = iModel->VSSettingsRecordedVideoSavingL(); CAknMemorySelectionDialogMultiDrive* dlg = iModel->MemorySelectionDialogLC(); // Use ECFDDialogTypeSave to have double list box in the query /* CAknMemorySelectionDialog* dlg = CAknMemorySelectionDialog::NewL( ECFDDialogTypeSave, R_VS_RECORDED_VIDEO_SAVING_SETTING_PAGE, EFalse ); CleanupStack::PushL( dlg ); */ TBool result( EFalse ); TDriveNumber driveNumber((TDriveNumber)currentValue); result = dlg->ExecuteL( driveNumber, NULL, NULL ); if ( result != CAknCommonDialogsBase::TReturnKey( CAknCommonDialogsBase::ERightSoftkey) ) { if ( ( TInt ) driveNumber != currentValue ) { iModel->SetVSSettingsRecordedVideoSavingL( ( TInt ) driveNumber ); } Container()->UpdateListBoxL( KGSSettIdRecordedVideoSaving ); } /* CAknMemorySelectionDialog::TMemory mem; if ( currentValue == ( TInt )mmcUnit ) { mem = CAknMemorySelectionDialog::EMemoryCard; } else { mem = CAknMemorySelectionDialog::EPhoneMemory; } TFileName ignore; TFileName path; if ( dlg->ExecuteL( mem, &path, &ignore ) ) { if ( mem == CAknMemorySelectionDialog::EPhoneMemory && currentValue != ( TInt ) phoneMemUnit ) { iModel->SetVSSettingsRecordedVideoSavingL( ( TInt )phoneMemUnit ); Container()->UpdateListBoxL( KGSSettIdRecordedVideoSaving ); } else if ( mem == CAknMemorySelectionDialog::EMemoryCard && currentValue != ( TInt )mmcUnit ) { iModel->SetVSSettingsRecordedVideoSavingL( ( TInt )mmcUnit ); Container()->UpdateListBoxL( KGSSettIdRecordedVideoSaving ); } } */ CleanupStack::PopAndDestroy(dlg); MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::ShowVSSettingsRecordedVideoSavingSettingDialogL()" ) } // ---------------------------------------------------------------------------- // In standard variant provides user a "Capability auditory note" setting // dialog, and in operator variant provides user an "Alerts" setting dialog. // Note that in both variants the different dialogs toggle the same setting. // ---------------------------------------------------------------------------- // void CMusSettingsPlugin::ShowVSSettingsNoteSettingDialogL() { MUS_LOG( "[MUSSET] -> CMusSettingsPlugin::ShowVSSettingsNoteSettingDialogL()" ) MusSettingsKeys::TAuditoryNotification currentValue = iModel->VSSettingsNoteL(); TInt intCurrentValue = static_cast<TInt>( currentValue ); CAknRadioButtonSettingPage* dlg; CDesCArrayFlat* items; if ( iModel->VSSettingsOperatorVariantL() == MusSettingsKeys::EStandard ) { items = iCoeEnv->ReadDesC16ArrayResourceL( R_VS_AUDIO_SETTING_PAGE_LBX ); CleanupStack::PushL( items ); dlg = new ( ELeave ) CAknRadioButtonSettingPage( R_VS_AUDIO_SETTING_PAGE, intCurrentValue, items ); } else { items = iCoeEnv->ReadDesC16ArrayResourceL( R_VS_NOTE_SETTING_PAGE_LBX ); CleanupStack::PushL( items ); dlg = new ( ELeave ) CAknRadioButtonSettingPage( R_VS_NOTE_SETTING_PAGE, intCurrentValue, items ); } if ( dlg->ExecuteLD( CAknSettingPage::EUpdateWhenChanged ) ) { currentValue = static_cast<MusSettingsKeys::TAuditoryNotification> ( intCurrentValue ); iModel->SetVSSettingsNoteL( currentValue ); Container()->UpdateListBoxL( KGSSettIdNote ); } CleanupStack::PopAndDestroy( items ); MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::ShowVSSettingsNoteSettingDialogL()" ) } // ---------------------------------------------------------------------------- // Shows a notifications that no SIP profiles exists. // ---------------------------------------------------------------------------- // void CMusSettingsPlugin::ShowNoProfilesNotificationL() { MUS_LOG( "[MUSSET] -> CMusSettingsPlugin::ShowNoProfilesNotificationL()" ) HBufC* infoTxt = StringLoader::LoadLC( R_QTN_MSH_SET_PROFILE_EMPTY ); CAknInformationNote* note = new ( ELeave ) CAknInformationNote( ETrue ); note->ExecuteLD( infoTxt->Des() ); CleanupStack::PopAndDestroy( infoTxt ); MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::ShowNoProfilesNotificationL()" ) } // --------------------------------------------------------------------------- // Switches between two possible values from one to another (i.e. toggles a // setting on/off). Toggled setting is passed in aValue parameter. // --------------------------------------------------------------------------- // void CMusSettingsPlugin::SwitchOnOffValueL( TInt aValue ) { switch( aValue ) { case KGSSettIdVSActivation: { if ( MusSettingsKeys::EAlwaysActive == iModel->VSSettingsActivationL() ) { iModel->SetVSSettingsActivationL( MusSettingsKeys::ENever ); } else { iModel->SetVSSettingsActivationL( MusSettingsKeys::EAlwaysActive ); } break; } case KGSSettIdAutoRecord: { if ( MusSettingsKeys::EAutoRecordOff == iModel->VSSettingsAutoRecordL() ) { iModel->SetVSSettingsAutoRecordL( MusSettingsKeys::EAutoRecordOn ); } else { iModel->SetVSSettingsAutoRecordL( MusSettingsKeys::EAutoRecordOff ); } break; } case KGSSettIdRecordedVideoSaving: { TDriveUnit phoneMemUnit( TParsePtrC( PathInfo::PhoneMemoryRootPath() ).Drive() ); TDriveUnit mmcUnit( TParsePtrC( PathInfo::MemoryCardRootPath() ).Drive() ); if ( ( TInt )phoneMemUnit == iModel->VSSettingsRecordedVideoSavingL() ) { iModel->SetVSSettingsRecordedVideoSavingL( ( TInt )mmcUnit ); } else { iModel->SetVSSettingsRecordedVideoSavingL( ( TInt )phoneMemUnit ); } break; } case KGSSettIdNote: { if ( MusSettingsKeys::EAuditoryNotificationOn == iModel->VSSettingsNoteL() ) { iModel->SetVSSettingsNoteL( MusSettingsKeys::EAuditoryNotificationOff ); } else { iModel->SetVSSettingsNoteL( MusSettingsKeys::EAuditoryNotificationOn ); } break; } default: { MUS_LOG( "[MUSSET] -> CMusSettingsPlugin::SwitchOnOffValueL() - error unknown setting" ) User::Leave( KErrArgument ); } } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- // void CMusSettingsPlugin::ShowGlobalInformationDialogL( TInt aResourceId ) { CAknGlobalNote* dlg = CAknGlobalNote::NewLC(); HBufC* dlgPrompt = StringLoader::LoadLC( aResourceId ); TRequestStatus status; dlg->ShowNoteL( status, EAknGlobalInformationNote, *dlgPrompt ); User::WaitForRequest( status ); CleanupStack::PopAndDestroy( dlgPrompt ); CleanupStack::PopAndDestroy( dlg ); } // ---------------------------------------------------------------------------- // From class CGSPluginInterface. // Creates a new icon of desired type. Overrided to provide custom icons. // Ownership of the created icon is transferred to the caller. // ---------------------------------------------------------------------------- // CGulIcon* CMusSettingsPlugin::CreateIconL( const TUid aIconType ) { MUS_LOG( "[MUSSET] -> CMusSettingsPlugin::CreateIconL()" ) CGulIcon* icon; if( aIconType == KGSIconTypeLbxItem ) { // Create a custom icon TParse* fp = new( ELeave ) TParse(); CleanupStack::PushL( fp ); HBufC* fileName = MusResourceFinderUtil::AppResourcePathL( KGSVSSettingsPluginIconDirAndName ); CleanupStack::PushL(fileName); fp->Set( *fileName , &KDC_BITMAP_DIR, NULL ); CleanupStack::PopAndDestroy( fileName ); icon = AknsUtils::CreateGulIconL( AknsUtils::SkinInstance(), KAknsIIDQgnPropSetVideoSharing, fp->FullName(), EMbmMussettingspluginQgn_prop_set_video_sharing, EMbmMussettingspluginQgn_prop_set_video_sharing_mask ); CleanupStack::PopAndDestroy( fp ); } else { // Use default icon from base class CGSPluginInterface. icon = CGSPluginInterface::CreateIconL( aIconType ); } MUS_LOG( "[MUSSET] <- CMusSettingsPlugin::CreateIconL()" ) return icon; }
5222b12f3764dd1db3446e0b766c8cd7bfbdc5cf
c10fc3ec27dc78385506344916505a8a351a6076
/3DDemo/world.cpp
c5c6a83891da6cfbcb68a55912da7c60395e0d4e
[]
no_license
wyrover/3DDemo
a284f197901eff0622667e35461c95ff8f8b790d
5e591535ef80ee7e3ab5daf034b214a94130160d
refs/heads/master
2021-01-15T13:12:03.014619
2015-01-29T08:42:50
2015-01-29T08:42:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,844
cpp
world.cpp
#include "PreCompile.h" #include "world.h" #include "BitmapReader.h" #include "LinearAlgebra.h" #include <PortableRuntime/CheckException.h> namespace Demo { static const Vector3f world_vertices[] = { { -2, -2, -10 }, // left lower front 0 { -2, 2, -10 }, // left upper front 1 { 2, -2, -10 }, // right lower front 2 { 2, 2, -10 }, // right upper front 3 { 2, -2, 0 }, // right lower back 4 { -2, -2, 0 }, // left lower back 5 { -2, 2, 0 }, // left upper back 6 { 2, 2, 0 }, // right upper back 7 // sky { -500, 50, -500 }, // left upper front 8 { -500, 50, 500 }, // left upper back 9 { 500, 50, 500 }, // right upper back 10 { 500, 50, -500 }, // right upper front 11 // outside wall { -10, -2, -20 }, // left lower front 12 { -10, 2, -20 }, // left upper front 13 { 10, -2, -20 }, // right lower front 14 { 10, 2, -20 }, // right upper front 15 // far floor { 10, -2, -20 }, // 16 { 10, -2, -10 }, // 17 { -10, -2, -10 }, // 18 // left far wall { -10, 2, -10 }, // 19 { 10, 2, -10 }, // 20 { 10, 4, -10 }, // 21 { -10, 4, -10 }, // 22 { 2, 4, -10 }, // 23 { -2, 4, -10 }, // 24 }; static const Vector2f world_texture_coords[] = { { 0.0, 0.0 }, { 0.0, 1.0 }, { 1.0, 0.0 }, { 1.0, 1.0 }, { 8.0, 0.0 }, { 8.0, 1.0 }, { 5.0, 0.0 }, { 5.0, 1.0 }, { 2.5, 0.0 }, { 2.5, 1.0 }, }; Polygon::Polygon() : texture(0), lightmap(0) { } std::istream& operator>>(std::istream& is, Demo::Polygon& polygon) { // Clear and realloc vectors. std::vector<unsigned int>().swap(polygon.vertex_indices); std::vector<unsigned int>().swap(polygon.texture_coordinates); unsigned int num_points; is >> num_points; if(num_points > 0) { polygon.vertex_indices.reserve(num_points); polygon.texture_coordinates.reserve(num_points); for(unsigned int ix = 0; ix < num_points; ++ix) { unsigned int vertex_indices; is >> vertex_indices; polygon.vertex_indices.push_back(vertex_indices); } for(unsigned int ix = 0; ix < num_points; ++ix) { unsigned int texture_coordinate; is >> texture_coordinate; polygon.texture_coordinates.push_back(texture_coordinate); } } is >> polygon.texture >> polygon.lightmap; return is; } // Returns true if the point is inside the bounds of all polygons in the world. bool is_point_in_world(const Vector3f& point) { // TODO: Use the world geometry to determine this. if(point.x() < -9.0 || point.x() > 9.0) { return false; } if(point.z() < 1.0 || point.z() > 19.0) { return false; } if(point.z() < 11.0) { if(point.x() < -1.25 || point.x() > 1.25) { return false; } } return true; } static Map load_world_data( std::istream& is, std::vector<ImageProcessing::Bitmap>* texture_list, std::vector<Vector3f>* vertices, std::vector<Vector2f>* texture_coords) { unsigned int cTextures; is >> cTextures; unsigned int ii; for(ii = 0; ii < cTextures; ++ii) { char file_name[MAX_PATH]; is >> file_name; texture_list->push_back(bitmap_from_file(file_name)); } unsigned int cPolys; is >> cPolys; Map map; for(ii = 0; ii < cPolys; ++ii) { Demo::Polygon poly; is >> poly; map.world_mesh.push_back(poly); for(auto jj = 0; jj < 4; ++jj) { // TODO: 2014: Bounds check constant arrays. auto ix = poly.vertex_indices[jj]; CHECK_EXCEPTION(ix < ARRAYSIZE(world_vertices)); vertices->push_back(world_vertices[ix]); ix = poly.texture_coordinates[jj]; CHECK_EXCEPTION(ix < ARRAYSIZE(world_texture_coords)); texture_coords->push_back(world_texture_coords[ix]); } } return map; } Map start_load( _In_z_ const char* file_name, std::vector<ImageProcessing::Bitmap>* texture_list, std::vector<Vector3f>* vertices, std::vector<Vector2f>* texture_coords) { std::ifstream fis; fis.open(file_name); PortableRuntime::check_exception(fis.is_open()); return load_world_data(fis, texture_list, vertices, texture_coords); } }
13c845a4fc885ca61835b155ac6902b9089ed349
9d89f00222f1c9108a006ea74607c4999491c8f5
/POO_SSS_projet/ProjetPOOWin32SDL/source/Vaisseau.cpp
5d2714a93dc87acc03b88adc5259158d58ee77a2
[]
no_license
AlexECX/POOprojectSSS
6343853a6010506cd9667d430c7a89cbecf39303
5190898bac012440b05b4e729c52f7f2fc7d26eb
refs/heads/master
2021-09-06T03:51:18.186113
2017-12-09T02:29:07
2017-12-09T02:29:07
112,216,328
0
0
null
null
null
null
UTF-8
C++
false
false
102
cpp
Vaisseau.cpp
#include "EntiteVolante.h" #include "Vaisseau.h" Vaisseau::Vaisseau() { } Vaisseau::~Vaisseau() { }
a22ad0150aff07daa5f10bc5ba9b41be49b3b650
b73401933b5c06aad64930147181b0a2108c7613
/tp3/src/timer.h
3e1b8fb3f4683f2e5637ac9a523ac2571db05416
[]
no_license
ABorgna/metnum
d62f06eb4385bd4efe7c6a70de9da7c8d0650e7a
c9469f1e83d079ccfebf8c127098514eb901b9a6
refs/heads/master
2020-04-15T02:57:23.870430
2019-01-06T17:32:06
2019-01-06T17:32:06
164,330,206
0
0
null
null
null
null
UTF-8
C++
false
false
687
h
timer.h
#pragma once #include <chrono> #include <iostream> #include <string> #include <vector> /* * Estructura para llevar la cuenta del tiempo de ejecución */ class TimeKeeper { private: std::chrono::steady_clock::time_point startPoint; std::string currentLabel; bool running = false; public: // List of recordings std::vector<std::pair<std::string, std::chrono::milliseconds>> registry; // Start recording a new entry // Stops the previous one if it is still running. void start(std::string label); // Stop the current recording std::chrono::milliseconds stop(); }; void showTimes(std::ostream& outStream, const TimeKeeper& timeKeeper);
cf877425f00f7f03d0827583b500848b98c8bd49
4009bb8e0dd4785f21f8a07c918ef2e37ed48609
/aula1/exemplo3/empresa3.cc
eeeca1d6553e5051d856bd84eebdd12d8bfd94eb
[]
no_license
gaaj-ufrpe/modelagem-e-simulacao
37c02a5ab803f1226effd2a67e885a8a888df82b
aa6cd701652d76b0b3af78c9059d00a2a390104e
refs/heads/main
2023-03-10T11:33:48.106516
2021-02-23T20:57:57
2021-02-23T20:57:57
316,964,462
1
0
null
null
null
null
UTF-8
C++
false
false
1,075
cc
empresa3.cc
#include <string.h> #include <omnetpp.h> using namespace omnetpp; class Maquina3 : public cSimpleModule { private: bool on = false; protected: virtual void initialize() override; virtual void handleMessage(cMessage *msg) override; virtual void updateDisplay(); public: void switchState() { on = !on; }; }; Define_Module(Maquina3); void Maquina3::initialize() { if (strcmp("m1", getName()) == 0) { cMessage *msg = new cMessage("switchMsg"); send(msg, "out"); } } void Maquina3::handleMessage(cMessage *msg) { switchState(); updateDisplay(); send(msg, "out"); } void Maquina3::updateDisplay() { const char* txt2 = "off"; const char* color = "red"; const char* status = "status/red"; if (on) { txt2 = "on"; color = "green"; status = "status/green"; } cDisplayString& ds = getDisplayString(); ds.setTagArg("i2",0,status); ds.setTagArg("i",1,color); refreshDisplay(); bubble(txt2); }
9bd1bbf0520c3445c07f0796ee49e01e767a7fbb
6d8faae66dd6332836bb11d7f02d6867c95d2a65
/glast/pulsePhase/src/PulsePhaseApp.cxx
c01362a6ddf7a283ae317953fb3a99c5cdae3f2c
[]
no_license
Areustle/fermi-glast
9085f32f732bec6bf33079ce8e2ea2a0374d0228
c51b821522a5521af253973fdd080e304fae88cc
refs/heads/master
2021-01-01T16:04:44.289772
2017-09-12T16:35:52
2017-09-12T16:35:52
97,769,090
0
1
null
null
null
null
UTF-8
C++
false
false
5,975
cxx
PulsePhaseApp.cxx
/** \file PulsePhaseApp.cxx \brief Implmentation of PulsePhaseApp class. \author Masaharu Hirayama, GSSC James Peachey, HEASARC/GSSC */ #include "PulsePhaseApp.h" #include <cctype> #include <cmath> #include <iostream> #include <memory> #include <set> #include <stdexcept> #include <string> #include "pulsarDb/EphChooser.h" #include "pulsarDb/EphComputer.h" #include "pulsarDb/EphStatus.h" #include "timeSystem/AbsoluteTime.h" #include "st_app/AppParGroup.h" #include "st_app/StApp.h" #include "st_app/StAppFactory.h" #include "st_stream/Stream.h" const std::string s_cvs_id("$Name: $"); PulsePhaseApp::PulsePhaseApp(): pulsarDb::PulsarToolApp(), m_os("PulsePhaseApp", "", 2) { setName("gtpphase"); setVersion(s_cvs_id); st_app::AppParGroup & par_group = getParGroup(); // getParGroup is in base class st_app::StApp par_group.setSwitch("ephstyle"); par_group.setCase("ephstyle", "FREQ", "ephepoch"); par_group.setCase("ephstyle", "FREQ", "timeformat"); par_group.setCase("ephstyle", "FREQ", "timesys"); par_group.setCase("ephstyle", "FREQ", "ra"); par_group.setCase("ephstyle", "FREQ", "dec"); par_group.setCase("ephstyle", "FREQ", "phi0"); par_group.setCase("ephstyle", "FREQ", "f0"); par_group.setCase("ephstyle", "FREQ", "f1"); par_group.setCase("ephstyle", "FREQ", "f2"); par_group.setCase("ephstyle", "PER", "ephepoch"); par_group.setCase("ephstyle", "PER", "timeformat"); par_group.setCase("ephstyle", "PER", "timesys"); par_group.setCase("ephstyle", "PER", "ra"); par_group.setCase("ephstyle", "PER", "dec"); par_group.setCase("ephstyle", "PER", "phi0"); par_group.setCase("ephstyle", "PER", "p0"); par_group.setCase("ephstyle", "PER", "p1"); par_group.setCase("ephstyle", "PER", "p2"); } PulsePhaseApp::~PulsePhaseApp() throw() {} void PulsePhaseApp::runApp() { m_os.setMethod("runApp()"); st_app::AppParGroup & par_group = getParGroup(); // getParGroup is in base class st_app::StApp // Prompt for selected parameters. par_group.Prompt("evfile"); par_group.Prompt("evtable"); par_group.Prompt("timefield"); par_group.Prompt("scfile"); par_group.Prompt("sctable"); par_group.Prompt("psrdbfile"); par_group.Prompt("psrname"); par_group.Prompt("ephstyle"); std::string eph_style = par_group["ephstyle"]; for (std::string::iterator itor = eph_style.begin(); itor != eph_style.end(); ++itor) *itor = toupper(*itor); if (eph_style == "FREQ") { par_group.Prompt("ephepoch"); par_group.Prompt("timeformat"); par_group.Prompt("timesys"); par_group.Prompt("ra"); par_group.Prompt("dec"); par_group.Prompt("phi0"); par_group.Prompt("f0"); par_group.Prompt("f1"); par_group.Prompt("f2"); } else if (eph_style == "PER") { par_group.Prompt("ephepoch"); par_group.Prompt("timeformat"); par_group.Prompt("timesys"); par_group.Prompt("ra"); par_group.Prompt("dec"); par_group.Prompt("phi0"); par_group.Prompt("p0"); par_group.Prompt("p1"); par_group.Prompt("p2"); } else if (eph_style == "DB") { // No action needed. } else { throw std::runtime_error("Ephemeris style \"" + eph_style + "\" is not supported"); } par_group.Prompt("tcorrect"); par_group.Prompt("solareph"); par_group.Prompt("matchsolareph"); par_group.Prompt("angtol"); par_group.Prompt("pphasefield"); par_group.Prompt("pphaseoffset"); par_group.Prompt("leapsecfile"); par_group.Prompt("reportephstatus"); par_group.Prompt("chatter"); par_group.Prompt("clobber"); par_group.Prompt("debug"); par_group.Prompt("gui"); par_group.Prompt("mode"); // Save the values of the parameters. par_group.Save(); // Open the event file(s). openEventFile(par_group, false); // Handle leap seconds. std::string leap_sec_file = par_group["leapsecfile"]; timeSystem::TimeSystem::setDefaultLeapSecFileName(leap_sec_file); // Setup time correction mode. defineTimeCorrectionMode("NONE", SUPPRESSED, SUPPRESSED, SUPPRESSED); defineTimeCorrectionMode("AUTO", ALLOWED, ALLOWED, SUPPRESSED); defineTimeCorrectionMode("BARY", REQUIRED, SUPPRESSED, SUPPRESSED); defineTimeCorrectionMode("BIN", REQUIRED, REQUIRED, SUPPRESSED); defineTimeCorrectionMode("ALL", REQUIRED, REQUIRED, SUPPRESSED); selectTimeCorrectionMode(par_group); // Set up EphComputer for arrival time corrections. pulsarDb::StrictEphChooser chooser; initEphComputer(par_group, chooser, m_os.info(4)); // Use user input (parameters) together with computer to determine corrections to apply. bool vary_ra_dec = true; bool guess_pdot = false; initTimeCorrection(par_group, vary_ra_dec, guess_pdot, m_os.info(3), "START"); // Report ephemeris status. std::set<pulsarDb::EphStatusCodeType> code_to_report; code_to_report.insert(pulsarDb::Unavailable); code_to_report.insert(pulsarDb::Remarked); reportEphStatus(m_os.warn(), code_to_report); // Reserve output column for creation if not existing in the event file(s). std::string phase_field = par_group["pphasefield"]; reserveOutputField(phase_field, "1D"); // Get EphComputer for orbital phase computation. pulsarDb::EphComputer & computer(getEphComputer()); // Read global phase offset. double phase_offset = par_group["pphaseoffset"]; // Iterate over events. for (setFirstEvent(); !isEndOfEventList(); setNextEvent()) { // Get event time as AbsoluteTime. timeSystem::AbsoluteTime abs_evt_time(getEventTime()); // Compute phase. double phase = computer.calcPulsePhase(abs_evt_time, phase_offset); // Write phase into output column. setFieldValue(phase_field, phase); } // Write parameter values to the event file(s). std::string creator_name = getName() + " " + getVersion(); std::string file_modification_time(createUtcTimeString()); std::string header_line("File modified by " + creator_name + " on " + file_modification_time); writeParameter(par_group, header_line); }
3dbf67bf1d5185898c768ee30ca14f870be2b338
3e4bc3ea32154d83146dfa6c6ba48eee0d7d615f
/Ojos.h
2f862c52492500b486c77f4547e4021f9f792afc
[]
no_license
edujguevara100/P3Lab-5_EduardoGuevara
c94fd41868b75dbae12f795772dac17cd9c42af3
23e989c8d61538d30c5fd868d8a8f51637d65c84
refs/heads/master
2021-01-25T13:48:34.964698
2018-03-02T22:25:12
2018-03-02T22:25:12
123,619,535
0
0
null
null
null
null
UTF-8
C++
false
false
184
h
Ojos.h
#ifndef OJOS_H #define OJOS_H #include <string> using namespace std; class Ojos{ private: string color; bool vision; public: Ojos(); Ojos(string, bool); ~Ojos(); }; #endif
ac01afb20805824bbc8d2e2af7f10792e1a308f7
dceebf5fc54832a0c6d463109a7f366ffb70841f
/zadanie6/MilitaryAircraft.h
cf47a6c7ea64d6caf157b6d1f7b768d393488942
[]
no_license
grips8/p2-lab
bc9930fbe719e56d11b61b10c4a2b8663440f4d9
fc9b6a4e4a13066b2bb8f688002933aa6b91a998
refs/heads/master
2023-05-06T03:39:33.085609
2021-05-23T17:31:56
2021-05-23T17:31:56
345,218,205
0
0
null
null
null
null
UTF-8
C++
false
false
644
h
MilitaryAircraft.h
#ifndef P2_LAB_MILITARYAIRCRAFT_H #define P2_LAB_MILITARYAIRCRAFT_H #include <iostream> #include "Aircraft.h" class MilitaryAircraft: public Aircraft { private: mutable int number_of_get_role_calls = 0; std::string class_of_aircraft; std::string role; public: MilitaryAircraft(std::string, std::string); MilitaryAircraft(std::string, std::string, int, std::string, std::string, std::string, int, int, std::string, std::string); std::string get_role() const; int get_number_of_get_role_calls() const; int calculate_range() const; void set_nationality(std::string); }; #endif //P2_LAB_MILITARYAIRCRAFT_H
8d0c863b045375df074131b425d1691c4072ada5
fae63976cb3bf8dd21735f80b9b7e7c71caaba8c
/main.cpp
6b6ca5e4f5d7b147d8b386e21ce9f85d6c67a650
[]
no_license
whisperapart/SupplyChainOptimization
6c004e055f0adaab630bc4ff589690d74ef138a1
4bcae5f8a1e514fd583063217b0e7bbe10d18c07
refs/heads/master
2022-11-22T09:09:09.251241
2020-07-20T06:34:04
2020-07-20T06:34:04
281,033,343
0
0
null
null
null
null
UTF-8
C++
false
false
20,028
cpp
main.cpp
/* * File: main.cpp * Author: Locyber <Locyber@cuttingplane.com> * * Created on 2015年9月21日, 上午9:21 */ #include <stdlib.h> #include <math.h> #include <time.h> #include <fstream> #include <iostream> #include <string> #include <sstream> #include <vector> #include <list> #include <algorithm> #include <numeric> // std::inner_product #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #ifdef _WIN32 #include <Windows.h> #else #include <sys/time.h> #include <ctime> #endif #define OK_DONE 0 #define ERR_INVALIDARG -1 #define ERR_NODIRECTOR -2 #define ERR_INVALIDDATA_MN -3 typedef long long int64; typedef unsigned long long uint64; typedef std::vector< std::vector<double> > vector2; using namespace std; // <editor-fold desc="模型相关常变量"> string networkFile = "GAResult_Network.txt"; string resultFile = "GAResult_Cost.txt"; string workingPath = "/wwwroot/demo.ccpcsoft.com/data"; int DC,RC; double za = 1.96; // 标准正态离差 double t = 0.95; // weight factor associated with the operating cost 运营成本系数 double r = 1.2; // 零售商需求方差和均值的比值 即 double beta = 0.0144; // weight factor associated with the transportation cost运输成本系数 double theta = 1.45; // weight factor associated with the inventory cost库存成本系数 double w = 0.556; vector<double> f; // DC的固定选址成本 vector<double> a; // DC的单位运输成本(从工厂到DC) vector<double> L; // DC的提前时间 vector<double> h; // DC的单位库存持有成本 vector<double> k; // DC的单位固定订货成本 vector<double> g; // DC的固定运输成本(工厂到DC) vector<double> mu; // R需求 vector2 am; // alpha*mu vector<double> c; // coefficient of gamma(S)+H(S) vector2 d; // 二维数组,距离 vector<double> CJA; //存储 C_{j,A(j)} 的值 // </editor-fold> // <editor-fold desc="GA相关变量"> vector<int> U; // U 未分配零售商 vector<int> O; // O 已开仓库 vector< vector< int > > A; // A[j] 表示仓库j所服务的零售商 O[j]=1时A[j]里才能有存储 vector<double> rho; //相当于每个零售商的平均费用 int IT=0; // iteration struct betalpha{ double value; int order; }; // </editor-fold> // <editor-fold desc="时间相关常变量"> uint64 startTime; // The time when GA execution starts uint64 endTime; // The end time of GA uint64 rgaTime; // The end time of RGA // </editor-fold> /** * 载入模型数据 */ void loadModuleData(int DC,int RC,string fPath) { string folderPath = fPath; folderPath = folderPath.append("/var_t.txt"); ifstream testSamplevt(folderPath.c_str()); testSamplevt>>t; testSamplevt.close(); folderPath = fPath; ifstream testSamplevr(folderPath.append("/var_r.txt").c_str()); testSamplevr>>r; testSamplevr.close(); folderPath = fPath; ifstream testSamplevbeta(folderPath.append("/var_beta.txt").c_str()); testSamplevbeta>>beta; testSamplevbeta.close(); folderPath = fPath; ifstream testSamplevtheta(folderPath.append("/var_theta.txt").c_str()); testSamplevtheta>>theta; testSamplevtheta.close(); folderPath = fPath; ifstream testSamplevw(folderPath.append("/var_w.txt").c_str()); testSamplevw>>w; testSamplevw.close(); folderPath = fPath; ifstream testSampleg(folderPath.append("/g.txt").c_str()); double gvalue; for ( int i = 0; i < DC && testSampleg >> gvalue; i++) { g.push_back(gvalue);} testSampleg.close(); folderPath = fPath; ifstream testSamplek(folderPath.append("/k.txt").c_str()); double kvalue; for ( int i = 0; i < DC && testSamplek >> kvalue; i++) {k.push_back(kvalue);} testSamplek.close(); folderPath = fPath; ifstream testSamplea(folderPath.append("/a.txt").c_str()); double avalue; for ( int i = 0; i < DC && testSamplea >> avalue; i++) {a.push_back(avalue);} testSamplea.close(); folderPath = fPath; ifstream testSampleL(folderPath.append("/L.txt").c_str()); double Lvalue; for ( int i = 0; i < DC && testSampleL >> Lvalue; i++) {L.push_back(Lvalue);} testSampleL.close(); folderPath = fPath; ifstream testSampleh(folderPath.append("/h.txt").c_str()); double hvalue; for ( int i = 0; i < DC && testSampleh >> hvalue; i++) {h.push_back(hvalue);} testSampleh.close(); folderPath = fPath; ifstream testSamplef(folderPath.append("/f.txt").c_str()); double fvalue; for ( int i = 0; i < DC && testSamplef >> fvalue; i++) {f.push_back(fvalue);} testSamplef.close(); /* folderPath = fPath; ifstream testSamplec(folderPath.append("/c.txt").c_str()); double cvalue; for ( int i = 0; i < DC && testSamplec >> cvalue; i++) {c.push_back(cvalue);} testSamplec.close(); */ for(int j=0;j<DC;j++) { c.push_back(sqrt(2*theta*h[j]*(k[j]+beta*g[j]))+theta*h[j]*za*sqrt(L[j]*r)); } folderPath = fPath; ifstream testSamplemu(folderPath.append("/mu.txt").c_str()); double muvalue; for ( int i = 0; i < RC && testSamplemu >> muvalue; i++) {mu.push_back(muvalue);} testSamplemu.close(); folderPath = fPath; ifstream testSampled(folderPath.append("/d.txt").c_str()); double dvalue; int row,col; vector<double> tmp; for ( int i = 0; i <RC*DC && testSampled >> dvalue; i++) { row = i/DC; col = i%DC; //cout<<i<<" :"<<row<<" "<<col<<" "<<dvalue<<endl; if(col == 0) // 第一个 { tmp.clear(); } tmp.push_back(dvalue); if(col==DC-1) { d.push_back(tmp); } } testSampled.close(); for ( int i = 0; i <DC; i++) { vector<double> amtmp; for(int j=0;j<RC;j++) { amtmp.push_back((a[j]+d[j][i])*mu[j]); } am.push_back(amtmp); } /** * 工具函数,计算数组中所有元素的和 * @param a 输入的整形数组 * @param num_elements 需要计算的长度 * @return 整形,数组中指定长度的值的和 */ int util_sumArray(vector< int > a, int num_elements) { int i, sum=0; if(num_elements>a.size()) return sum; for (i=0; i<num_elements; i++) { sum = sum + a[i]; } return(sum); } int util_checkDirExists(string path) { struct stat s; int err = stat(path.c_str(), &s); if(-1 == err) { return -1; } else { if(S_ISDIR(s.st_mode)) { return 1; } else { return 0; } } } /** * 工具函数,获得数组中最小的元素 * @param a 输入的数组 * @param count 需要计算的长度 * @return 双精,数组中指定长度的值中最小的 */ double util_getMinFromArr(vector< double> a,int count) { double ret = a[0]; if(count>a.size()) return 0; for(int i=1;i<count;i++) { ret = (ret<a[i])?ret:a[i]; } return ret; } /** * Returns the amount of milliseconds elapsed since the UNIX epoch. * Works on both windows and linux. */ uint64 GetTimeMs64() { #ifdef _WIN32 /* Windows */ FILETIME ft; LARGE_INTEGER li; /* Get the amount of 100 nano seconds intervals elapsed since January 1, 1601 (UTC) and copy it * to a LARGE_INTEGER structure. */ GetSystemTimeAsFileTime(&ft); li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; uint64 ret = li.QuadPart; ret -= 116444736000000000LL; /* Convert from file time to UNIX epoch time. */ ret /= 10000; /* From 100 nano seconds (10^-7) to 1 millisecond (10^-3) intervals */ return ret; #else /* Linux */ struct timeval tv; gettimeofday(&tv, NULL); uint64 ret = tv.tv_usec; /* Convert from micro seconds (10^-6) to milliseconds (10^-3) */ ret /= 1000; /* Adds the seconds (10^0) after converting them to milliseconds (10^-3) */ ret += (tv.tv_sec * 1000); return ret; #endif } /** * 结构体betalpha的比较函数 */ bool structCompare(betalpha a, betalpha b) { return a.value<b.value; } inline void getDCRC(int* DC, int* RC, string folderPath) { string tmp = folderPath; ifstream testSamplevt(tmp.append( "/var_m.txt").c_str()); testSamplevt>>*DC; testSamplevt.close(); tmp = folderPath; ifstream testSamplevr(tmp.append("/var_n.txt").c_str()); testSamplevr>>*RC; testSamplevr.close(); } void outputModel() { ofstream testSamplevt("/home/outputModel/var_t.txt"); testSamplevt.precision(16); testSamplevt<<t; testSamplevt.close(); ofstream testSamplevr("/home/outputModel/var_r.txt"); testSamplevr.precision(16); testSamplevr<<r; testSamplevr.close(); ofstream testSamplevbeta("/home/outputModel/var_beta.txt"); testSamplevbeta.precision(16); testSamplevbeta<<beta; testSamplevbeta.close(); ofstream testSamplevtheta("/home/outputModel/var_theta.txt"); testSamplevtheta.precision(16); testSamplevtheta<<theta; testSamplevtheta.close(); ofstream testSamplevw("/home/outputModel/var_w.txt"); testSamplevw.precision(16); testSamplevw<<w; testSamplevw.close(); ofstream testSamplef("/home/outputModel/f.txt"); testSamplef.precision(16); for(int i = 0; i < DC; i++) { testSamplef << f[i] << endl; } testSamplef.close(); ofstream testSamplec("/home/outputModel/c.txt"); testSamplec.precision(16); for(int i = 0; i < DC; i++) { testSamplec << c[i] << endl; } testSamplec.close(); ofstream testSamplemu("/home/outputModel/mu.txt"); testSamplemu.precision(16); for(int i = 0; i < RC; i++) { testSamplemu << mu[i] << endl; } testSamplemu.close(); ofstream testSampled("/home/outputModel/d.txt"); testSampled.precision(16); for(int i = 0; i < RC; i++) { for(int j=0;j<DC;j++) { testSampled << d[i][j] << " "; } testSampled << endl; } testSampled.close(); ofstream testSampleam("/home/outputModel/am.txt"); testSampleam.precision(16); for(int i = 0; i < DC; i++) { for(int j=0;j<RC;j++) { testSampleam << am[i][j] << " "; } testSampleam << endl; } testSampleam.close(); } int main(int argc,char* argv[]) { if(argc!=2) { return ERR_INVALIDARG; } string ID = argv[1]; // todo: check ID if (ID.length()!=32) return ERR_INVALIDARG; // todo: check ID path exits string folderPath = workingPath.append("/"); folderPath.append(ID); if(util_checkDirExists(folderPath)!=1) return ERR_NODIRECTOR; getDCRC(&DC,&RC,folderPath); if((DC<=0) || (RC<=0)) return ERR_INVALIDDATA_MN; loadModuleData(DC,RC,folderPath); // todo: checkModuleData int i,j,ii; // string resultPath = folderPath; // resultPath.append("/"); // resultPath.append(resultFile); // ofstream cout; // cout.open(resultPath.c_str(),fstream::out); // cout.precision(8); outputModel(); // Greedy Algorithm Starts // cout<<"===== greedy algorithm ====="<<endl; // startTime = GetTimeMs64(); // cout<<"start time:"<<startTime<<endl; vector< vector< betalpha > > DCxRC; for(i=0;i<DC;i++) { vector<betalpha> btvector; for(j=0;j<RC;j++) { betalpha bt = {mu[j]*(d[j][i]+a[i]),j}; btvector.push_back(bt); } sort(btvector.begin(),btvector.end(),structCompare); DCxRC.push_back(btvector); } for(i=0;i<RC;i++) { U.push_back(1); rho.push_back(0); } for(j=0;j<DC;j++) { O.push_back(0); CJA.push_back(0); vector< int > Arow; for(i=0;i<RC;i++) { Arow.push_back(0); } A.push_back(Arow); } outputModel(); while(true) { int nn = util_sumArray(U,RC); if(nn==0) break; IT++; cout<<"iteration: "<<IT<<endl; double min=0; // 本次最优值 vector< int > Sadd; // 本次最优值对应的S* int J = 0; // 本次最优值对应的j for(i=0;i<RC;i++) { Sadd.push_back(0); } for(j=0;j<DC;j++) { vector<int> ba; for(i=0;i<RC;i++) // for a selected DC, pick unchosen Retailers, and calc the transportation cost { if(U[DCxRC[j][i].order]==1) { ba.push_back(DCxRC[j][i].order); } } for(i=0;i<nn;i++) // nn = the total count of unchosen retailers { vector< int > S (RC,0); vector< int > AS (RC,0); for(ii=0;ii<=i;ii++) // 对于所有没有选中的retailer { S[ba[ii]] = 1; // 建一个S数组,把刚才排序好的靠前的ii个标记为1 } for(ii=0;ii<RC;ii++) { if(A[j][ii]+S[ii]>0) { AS[ii]=1; // 如果以前已经选择过,也标记1, } } if(j+i==0) //第一个计算得到的数值 { double x1 = (double)(std::inner_product(S.begin(),S.end(),am[j].begin(),0)); double x2 = (double)(std::inner_product(S.begin(),S.end(),mu.begin(),0)); min=(double)((f[j]+beta*x1+t*pow(x2,w)+c[j]*sqrt(x2))/x2); for(ii=0;ii<RC;ii++) { Sadd[ii]=S[ii]; } J=j; } else { double x01 = (double)(std::inner_product(AS.begin(),AS.end(),am[j].begin(),0)); double x02 = (double)(std::inner_product(AS.begin(),AS.end(),mu.begin(),0)); double x03 = (double)(std::inner_product(S.begin(),S.end(),mu.begin(),0)); double x04 = (double)((f[j]+beta*x01+t*pow(x02,w)+c[j]*sqrt(x02)-CJA[j])/x03); if(x04<min) { min=x04; for(ii=0;ii<RC;ii++) { Sadd[ii]=S[ii]; } J=j; } } } } O[J]=1; CJA[J]=min*std::inner_product(Sadd.begin(),Sadd.end(),mu.begin(),0)+CJA[J]; for(i=0;i<RC;i++) { if(Sadd[i]==1) { rho[i]=min; U[i]=0; A[J][i]=1; } } cout<<"min:\t"<<min<<endl; } // endTime = GetTimeMs64(); // cout<<"end time:"<<endTime<<endl; // cout<<"Open DCs number: "<<util_sumArray(O,DC)<<endl<<endl; // cout<<"时间(毫秒): "<<startTime -endTime<<endl<<endl; string resultPath = folderPath; resultPath.append("/"); resultPath.append(networkFile); ofstream cout; cout.open(resultPath.c_str(),fstream::out); cout.precision(8); for(j=0;j<DC;j++) { if(O[j]==1) { cout<<j<<" "; for(i=0;i<RC;i++) { if(A[j][i]==1) { cout<<i<<" "; } } cout<<endl; } } cout.close(); resultPath = folderPath; resultPath.append("/"); resultPath.append(resultFile); ofstream fout; fout.open(resultPath.c_str(),fstream::out); fout.precision(8); fout<<"Iterations:"<<IT<<endl; double tcost = std::inner_product(rho.begin(),rho.end(),mu.begin(),0.0); fout<<"total cost: "<<tcost<<endl; vector< double > mp ; vector< double > op(DC,0); // 存储每个warehouse对应的最优值 //int FS[DC][RC] = {[0 ... DC-1][0 ... RC-1]=1}; vector< vector < int > > FS; for(i=0;i<DC;i++) { vector < int > fsrow; for(j=0;j<RC;j++) { fsrow.push_back(1); } FS.push_back(fsrow); } for(i=0;i<RC;i++) { mp.push_back(mu[i]*rho[i]); } for(j=0;j<DC;j++) { double y1 = std::inner_product(FS[j].begin(),FS[j].end(),am[j].begin(),0); double y2 = std::inner_product(FS[j].begin(),FS[j].end(),mu.begin(),0); double y3 = std::inner_product(FS[j].begin(),FS[j].end(),mp.begin(),0); op[j] = (f[j]+beta*y1+t*pow(y2,w)+c[j]*sqrt(y2))/y3; //最优值由FS[j]决定 for(;;) { int yes = 0; //用于表明FS[j]是否发生改变,即theta是不是最优 std::vector<betalpha> batArr; for(i=0;i<RC;i++) { double z1 = beta*(d[i][j]+a[j])-op[j]*rho[i]; struct betalpha batV = {z1,i}; batArr.push_back(batV); } vector< double > batm; for(i=0;i<RC;i++) { batm.push_back(batArr[i].value * mu[i]); } std::sort(batArr.begin(),batArr.end(),structCompare); for(i=0;i<RC;i++) { if(batArr[i].value<0) //<0的个数即是可能最优解的个数 { vector< int > zz (RC,0); for(ii=0;ii<=i;ii++) { zz[batArr[ii].order]=1; } double rgax1 = std::inner_product(zz.begin(),zz.end(),batm.begin(),0); double rgax2 = std::inner_product(zz.begin(),zz.end(),mu.begin(),0); double rgax3 = std::inner_product(zz.begin(),zz.end(),mp.begin(),0); double rgax4 = std::inner_product(zz.begin(),zz.end(),am[j].begin(),0); double rgax5 = rgax1+t*pow(rgax2,w)+c[j]*sqrt(rgax2)+f[j]; double rgax6 = (f[j]+beta*rgax4+t*pow(rgax2,w)+c[j]*sqrt(rgax2))/rgax3; if(rgax5<0) { if(rgax6<op[j]) { op[j]=rgax6; yes=1; for(ii=0;ii<RC;ii++) { FS[j][ii]=zz[ii]; } } } } } if(yes==0) { break; } } } rgaTime = GetTimeMs64(); cout<<"rga time:"<<rgaTime<<endl; cout<<"rGA="<<1/util_getMinFromArr(op,DC)<<endl; cout<<"时间(毫秒): "<<rgaTime-startTime<<endl; cout.close(); return OK_DONE; } void leftmain() { }
3136bb16071d199bff767875283a5c8911ee109c
36e8e990339ee98bf263fc2ff7431d4d279d900d
/src/TrackGenerator.cpp
e2be36cb0db783691bd8ef38221aaa238dc805d1
[]
no_license
razianushrat/OpenMOC-LOO
c31d77cd77584bdc1bb79840aa35190e8e5f53b8
3ab84c1fee987cb691ec5364c15b82b453135dd4
refs/heads/master
2020-12-02T14:05:32.725790
2014-10-13T07:44:05
2014-10-13T07:44:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
35,218
cpp
TrackGenerator.cpp
#include "TrackGenerator.h" /** * TrackGenerator constructor * @param geom a pointer to a geometry object * @param plotter a pointer to a plotting object * @param num_azim number of azimuthal angles * @param spacing track spacing */ TrackGenerator::TrackGenerator(Geometry* geom, Plotter* plotter, Options* opts) { _plotter = plotter; _geom = geom; _opts = opts; _num_azim = opts->getNumAzim() / 2.0; _spacing = opts->getTrackSpacing(); _geometry_file = opts->getGeometryFile(); _tot_num_tracks = 0; _tot_num_segments = 0; _num_segments = NULL; _contains_tracks = false; _use_input_file = false; _tracks_filename = ""; } /** * TrackGenerator destructor frees memory for all tracks */ TrackGenerator::~TrackGenerator() { delete [] _num_tracks; delete [] _num_x; delete [] _num_y; delete [] _azim_weights; for (int i = 0; i < _num_azim; i++) delete [] _tracks[i]; delete [] _tracks; } /** * Return the azimuthal weights array * @return the array of azimuthal weights */ double* TrackGenerator::getAzimWeights() const { return _azim_weights; } /** * Return the number of azimuthal angles * @return the number of azimuthal angles */ int TrackGenerator::getNumAzim() const { return _num_azim; } /** * Return the number of tracks array indexed by azimuthal angle * @return the number of tracks */ int *TrackGenerator::getNumTracks() const { return _num_tracks; } /** * Return the track spacing array * @return the track spacing array */ double TrackGenerator::getSpacing() const { return _spacing; } /**-na 16 -ts 0.2 -ps * Return the 2D jagged array of track pointers * @return the 2D jagged array of tracks */ Track **TrackGenerator::getTracks() const { return _tracks; } /** * Computes the effective angles and track spacings. Computes the number of * tracks for each azimuthal angle, allocates memory for all tracks at each * angle and sets each track's starting and ending points, azimuthal weight, * and azimuthal angle */ void TrackGenerator::generateTracks() { /* Deletes tracks arrays if tracks have been generated */ if (_contains_tracks) { delete [] _num_tracks; delete [] _num_segments; delete [] _num_x; delete [] _num_y; delete [] _azim_weights; for (int i = 0; i < _num_azim; i++) delete [] _tracks[i]; delete [] _tracks; } /** Create tracks directory if one does not yet exist */ std::stringstream directory; directory << getOutputDirectory() << "/tracks"; struct stat st; if (!stat(directory.str().c_str(), &st) == 0) mkdir(directory.str().c_str(), S_IRWXU); struct stat buffer; std::stringstream test_filename; // Manipulates _gometry_file so that there is no "/" symbols. for (unsigned i = 0; i < _geometry_file.length(); i++) { switch(_geometry_file[i]) { case '/': _geometry_file[i] = '_'; } } test_filename << directory.str() << "/" << _geometry_file << "_" << _num_azim*2.0 << "_" << _spacing; if (_opts->getUseUpScatteringXS() == true) test_filename << "_up"; else test_filename << "_no"; if (_geom->getCmfd() || _geom->getLoo()){ test_filename << "_cmfd_" << _geom->getMesh()->getMeshLevel(); } test_filename << ".data"; _tracks_filename = test_filename.str(); if (!stat(_tracks_filename.c_str(), &buffer)) { if (readTracksFromFile()) { _use_input_file = true; _contains_tracks = true; } } /* If not tracks input file exists, generate tracks */ if (_use_input_file == false) { /* Allocate memory for the tracks */ try { _num_tracks = new int[_num_azim]; _num_x = new int[_num_azim]; _num_y = new int[_num_azim]; _azim_weights = new double[_num_azim]; _tracks = new Track*[_num_azim]; } catch (std::exception &e) { log_printf(ERROR, "Unable to allocate memory for TrackGenerator. " "Backtrace:\n%s", e.what()); } /* Check to make sure that height, width of the geometry are nonzero */ if ((_geom->getHeight() <= 0 - ON_SURFACE_THRESH) || (_geom->getWidth() <= 0 - ON_SURFACE_THRESH)) { log_printf(ERROR, "The total height and width of the geometry " "must be nonzero for track generation. Please specify " "the height and width in the geometry input file."); } try { log_printf(NORMAL, "Computing azimuthal angles and track " "spacings..."); /* Each element in arrays corresponds to a track angle in phi_eff */ /* Track spacing along x,y-axes, and perpendicular to each track */ double* dx_eff = new double[_num_azim]; double* dy_eff = new double[_num_azim]; double* d_eff = new double[_num_azim]; /* Effective azimuthal angles with respect to positive x-axis */ double* phi_eff = new double[_num_azim]; double x1, x2; double iazim = _num_azim*2.0; double width = _geom->getWidth(); double height = _geom->getHeight(); /* create BitMap for plotting */ BitMap<int>* bitMap = new BitMap<int>; bitMap->pixel_x = _plotter->getBitLengthX(); bitMap->pixel_y = _plotter->getBitLengthY(); initialize(bitMap); bitMap->geom_x = width; bitMap->geom_y = height; bitMap->color_type = BLACKWHITE; /* Determine azimuthal angles and track spacing */ for (int i = 0; i < _num_azim; i++) { /* desired angle */ double phi = 2.0 * M_PI / iazim * (0.5 + i); /* num intersections with x,y-axes */ _num_x[i] = (int) (fabs(width / _spacing * sin(phi))) + 1; _num_y[i] = (int) (fabs(height / _spacing * cos(phi))) + 1; log_printf(DEBUG, "For azimuthal angle %d, num_x = %d," " num_y = %d", i, _num_x[i], _num_y[i]); /* total num of tracks */ _num_tracks[i] = _num_x[i] + _num_y[i]; /* effective/actual angle (not the angle we desire, but close */ phi_eff[i] = atan((height * _num_x[i]) / (width * _num_y[i])); /* fix angles in range(pi/2, pi) */ if (phi > M_PI / 2.0) phi_eff[i] = M_PI - phi_eff[i]; /* Effective track spacing (not spacing we desire, but close */ dx_eff[i] = (width / _num_x[i]); dy_eff[i] = (height / _num_y[i]); d_eff[i] = (dx_eff[i] * sin(phi_eff[i])); } /* Compute azimuthal weights */ for (int i = 0; i < _num_azim; i++) { if (i < _num_azim - 1) x1 = 0.5 * (phi_eff[i+1] - phi_eff[i]); else x1 = 2 * M_PI / 2.0 - phi_eff[i]; if (i >= 1) x2 = 0.5 * (phi_eff[i] - phi_eff[i-1]); else x2 = phi_eff[i]; /* Multiply weight by 2 because angles are in [0, Pi] */ _azim_weights[i] = (x1 + x2) / (2 * M_PI) * d_eff[i] * 2; } log_printf(INFO, "Generating track start and end points..."); /* Compute track starting and end points */ for (int i = 0; i < _num_azim; i++) { /* Tracks for azimuthal angle i */ _tracks[i] = new Track[_num_tracks[i]]; /* Compute start points for tracks starting on x-axis */ for (int j = 0; j < _num_x[i]; j++) { _tracks[i][j].getStart()->setCoords(dx_eff[i] * (0.5 + j), 0); } /* Compute start points for tracks starting on y-axis */ for (int j = 0; j < _num_y[i]; j++) { /* If track points to the upper right */ if (sin(phi_eff[i]) > 0 && cos(phi_eff[i]) > 0) { _tracks[i][_num_x[i]+j].getStart() ->setCoords(0, dy_eff[i] * (0.5 + j)); } /* If track points to the upper left */ else if (sin(phi_eff[i]) > 0 && cos(phi_eff[i]) < 0) { _tracks[i][_num_x[i]+j].getStart() ->setCoords(width, dy_eff[i] * (0.5 + j)); } } /* Compute the exit points for each track */ for (int j = 0; j < _num_tracks[i]; j++) { /* Set the track's end point */ Point* start = _tracks[i][j].getStart(); Point* end = _tracks[i][j].getEnd(); computeEndPoint(start, end, phi_eff[i], width, height); /* Set the track's azimuthal weight and spacing*/ _tracks[i][j].setAzimuthalWeight(_azim_weights[i]); _tracks[i][j].setPhi(phi_eff[i]); _tracks[i][j].setSpacing(d_eff[i]); } log_printf(DEBUG, "azimuthal angle = %f", phi_eff[i]); } /* Recalibrate track start and end points to global origin */ int uid = 0; for (int i = 0; i < _num_azim; i++) { _tot_num_tracks += _num_tracks[i]; for (int j = 0; j < _num_tracks[i]; j++) { _tracks[i][j].setUid(uid); uid++; double x0 = _tracks[i][j].getStart()->getX(); double y0 = _tracks[i][j].getStart()->getY(); double x1 = _tracks[i][j].getEnd()->getX(); double y1 = _tracks[i][j].getEnd()->getY(); double new_x0 = x0 - _geom->getWidth()/2.0; double new_y0 = y0 - _geom->getHeight()/2.0; double new_x1 = x1 - _geom->getWidth()/2.0; double new_y1 = y1 - _geom->getHeight()/2.0; double phi = _tracks[i][j].getPhi(); _tracks[i][j].setValues(new_x0, new_y0, new_x1, new_y1,phi); _tracks[i][j].setAzimAngleIndex(i); /* Add line to segments bitmap */ if (_plotter->plotSpecs() == true) drawLine(bitMap, new_x0, new_y0, new_x1, new_y1, 1); } } if (_plotter->plotSpecs() == true) plot(bitMap, "tracks", _plotter->getExtension()); deleteBitMap(bitMap); delete [] dx_eff; delete [] dy_eff; delete [] d_eff; delete [] phi_eff; segmentize(); _contains_tracks = true; dumpTracksToFile(); _use_input_file = true; } catch (std::exception &e) { log_printf(ERROR, "Unable to allocate memory needed to generate " "tracks. Backtrace:\n%s", e.what()); } } return; } /** * This helper method for generateTracks finds the end point of a given track * with a defined start point and an angle from x-axis. This function does not * return a value but instead saves the x/y coordinates of the end point * directly within the track's end point * @param start pointer to the track start point * @param end pointer to where the end point should be stored * @param phi the azimuthal angle * @param width the width of the geometry * @param height the height of the geometry */ void TrackGenerator::computeEndPoint(Point* start, Point* end, const double phi, const double width, const double height) { double m = sin(phi) / cos(phi); /* slope */ double yin = start->getY(); /* y-coord */ double xin = start->getX(); /* x-coord */ try { Point *points = new Point[4]; /* Determine all possible points */ points[0].setCoords(0, yin - m * xin); points[1].setCoords(width, yin + m * (width - xin)); points[2].setCoords(xin - yin / m, 0); points[3].setCoords(xin - (yin - height) / m, height); /* For each of the possible intersection points */ for (int i = 0; i < 4; i++) { /* neglect the trivial point (xin, yin) */ if (points[i].getX() == xin && points[i].getY() == yin) { } /* The point to return will be within the bounds of the cell */ else if (points[i].getX() >= 0 && points[i].getX() <= width && points[i].getY() >= 0 && points[i].getY() <= height) { end->setCoords(points[i].getX(), points[i].getY()); } } delete[] points; return; } catch (std::exception &e) { log_printf(ERROR, "Unable to allocate memory for intersection points " "in computeEndPoint TrackGenerator. Backtrace:\n%s", e.what()); } } /** * Implements reflective boundary conditions by setting the incoming * and outgoing tracks for each track using a special indexing scheme * into the trackgenerator's 2d jagged array of tracks */ void TrackGenerator::makeReflective() { log_printf(INFO, "Creating boundary conditions..."); int nxi, nyi, nti; /* nx, ny, nt for a particular angle */ Track *curr; Track *refl; /* Loop over only half the angles since we will set the pointers for * connecting tracks at the same time */ for (int i = 0; i < floor(_num_azim / 2); i++) { nxi = _num_x[i]; nyi = _num_y[i]; nti = _num_tracks[i]; curr = _tracks[i]; refl = _tracks[_num_azim - i - 1]; /* Loop over all of the tracks for this angle */ for (int j = 0; j < nti; j++) { /* More tracks starting along x-axis than y-axis */ if (nxi <= nyi) { /* Bottom to right hand side */ if (j < nxi) { curr[j].setTrackIn(&refl[j]); refl[j].setTrackIn(&curr[j]); curr[j].setSurfBwd(3); refl[j].setSurfBwd(3); if (_geom->getSurface(3)->getBoundary() == REFLECTIVE){ curr[j].setReflIn(REFL_FALSE); refl[j].setReflIn(REFL_FALSE); } else{ curr[j].setReflIn(VAC_FALSE); refl[j].setReflIn(VAC_FALSE); } curr[j].setTrackOut(&refl[2 * nxi - 1 - j]); refl[2 * nxi - 1 - j].setTrackIn(&curr[j]); curr[j].setSurfFwd(2); refl[2 * nxi - 1 - j].setSurfBwd(2); if (_geom->getSurface(2)->getBoundary() == REFLECTIVE){ curr[j].setReflOut(REFL_FALSE); refl[2 * nxi - 1 - j].setReflIn(REFL_TRUE); } else{ curr[j].setReflOut(VAC_FALSE); refl[2 * nxi - 1 - j].setReflIn(VAC_TRUE); } } /* Left hand side to right hand side */ else if (j < nyi) { curr[j].setTrackIn(&refl[j - nxi]); refl[j - nxi].setTrackOut(&curr[j]); curr[j].setSurfBwd(1); refl[j - nxi].setSurfFwd(1); if (_geom->getSurface(1)->getBoundary() == REFLECTIVE){ curr[j].setReflIn(REFL_TRUE); refl[j - nxi].setReflOut(REFL_FALSE); } else{ curr[j].setReflIn(VAC_TRUE); refl[j - nxi].setReflOut(VAC_FALSE); } curr[j].setTrackOut(&refl[j + nxi]); refl[j + nxi].setTrackIn(&curr[j]); curr[j].setSurfFwd(2); refl[j + nxi].setSurfBwd(2); if (_geom->getSurface(2)->getBoundary() == REFLECTIVE){ curr[j].setReflOut(REFL_FALSE); refl[j + nxi].setReflIn(REFL_TRUE); } else{ curr[j].setReflOut(VAC_FALSE); refl[j + nxi].setReflIn(VAC_TRUE); } } /* Left hand side to top (j > ny) */ else { curr[j].setTrackIn(&refl[j - nxi]); refl[j - nxi].setTrackOut(&curr[j]); curr[j].setSurfBwd(1); refl[j - nxi].setSurfFwd(1); if (_geom->getSurface(1)->getBoundary() == REFLECTIVE){ curr[j].setReflIn(REFL_TRUE); refl[j - nxi].setReflOut(REFL_FALSE); } else{ curr[j].setReflIn(VAC_TRUE); refl[j - nxi].setReflOut(VAC_FALSE); } curr[j].setTrackOut(&refl[2 * nti - nxi - j - 1]); refl[2 * nti - nxi - j - 1].setTrackOut(&curr[j]); curr[j].setSurfFwd(4); refl[2 * nti - nxi - j - 1].setSurfFwd(4); if (_geom->getSurface(4)->getBoundary() == REFLECTIVE){ curr[j].setReflOut(REFL_TRUE); refl[2 * nti - nxi - j - 1].setReflOut(REFL_TRUE); } else{ curr[j].setReflOut(VAC_TRUE); refl[2 * nti - nxi - j - 1].setReflOut(VAC_TRUE); } } } /* More tracks starting on y-axis than on x-axis */ else { /* Bottom to top */ if (j < nxi - nyi) { curr[j].setTrackIn(&refl[j]); refl[j].setTrackIn(&curr[j]); curr[j].setSurfBwd(3); refl[j].setSurfBwd(3); if (_geom->getSurface(3)->getBoundary() == REFLECTIVE){ curr[j].setReflIn(REFL_FALSE); refl[j].setReflIn(REFL_FALSE); } else{ curr[j].setReflIn(VAC_FALSE); refl[j].setReflIn(VAC_FALSE); } curr[j].setTrackOut(&refl[nti - (nxi - nyi) + j]); refl[nti - (nxi - nyi) + j].setTrackOut(&curr[j]); curr[j].setSurfFwd(4); refl[nti - (nxi - nyi) + j].setSurfFwd(4); if (_geom->getSurface(4)->getBoundary() == REFLECTIVE){ curr[j].setReflOut(REFL_TRUE); refl[nti - (nxi - nyi) + j].setReflOut(REFL_TRUE); } else{ curr[j].setReflOut(VAC_TRUE); refl[nti - (nxi - nyi) + j].setReflOut(VAC_TRUE); } } /* Bottom to right hand side */ else if (j < nxi) { curr[j].setTrackIn(&refl[j]); refl[j].setTrackIn(&curr[j]); curr[j].setSurfBwd(3); refl[j].setSurfBwd(3); if (_geom->getSurface(3)->getBoundary() == REFLECTIVE){ curr[j].setReflIn(REFL_FALSE); refl[j].setReflIn(REFL_FALSE); } else{ curr[j].setReflIn(VAC_FALSE); refl[j].setReflIn(VAC_FALSE); } curr[j].setTrackOut(&refl[nxi + (nxi - j) - 1]); refl[nxi + (nxi - j) - 1].setTrackIn(&curr[j]); curr[j].setSurfFwd(2); refl[nxi + (nxi - j) - 1].setSurfBwd(2); if (_geom->getSurface(2)->getBoundary() == REFLECTIVE){ curr[j].setReflOut(REFL_FALSE); refl[nxi + (nxi - j) - 1].setReflIn(REFL_TRUE); } else{ curr[j].setReflOut(VAC_FALSE); refl[nxi + (nxi - j) - 1].setReflIn(VAC_TRUE); } } /* Left-hand side to top (j > nx) */ else { curr[j].setTrackIn(&refl[j - nxi]); refl[j - nxi].setTrackOut(&curr[j]); curr[j].setSurfBwd(1); refl[j - nxi].setSurfFwd(1); if (_geom->getSurface(1)->getBoundary() == REFLECTIVE){ curr[j].setReflIn(REFL_TRUE); refl[j - nxi].setReflOut(REFL_FALSE); } else{ curr[j].setReflIn(VAC_TRUE); refl[j - nxi].setReflOut(VAC_FALSE); } curr[j].setTrackOut(&refl[nyi + (nti - j) - 1]); refl[nyi + (nti - j) - 1].setTrackOut(&curr[j]); curr[j].setSurfFwd(4); refl[nyi + (nti - j) - 1].setSurfFwd(4); if (_geom->getSurface(4)->getBoundary() == REFLECTIVE){ curr[j].setReflOut(REFL_TRUE); refl[nyi + (nti - j) - 1].setReflOut(REFL_TRUE); } else{ curr[j].setReflOut(VAC_TRUE); refl[nyi + (nti - j) - 1].setReflOut(VAC_TRUE); } } } } } return; } /** * Generate segments for each track and plot segments * in bitmap array. */ void TrackGenerator::segmentize() { log_printf(NORMAL, "Segmenting tracks..."); double phi, sin_phi, cos_phi; double x0, y0, x1, y1; int num_segments; Track* track; /* create BitMaps for plotting */ BitMap<int>* bitMapFSR = new BitMap<int>; BitMap<int>* bitMap = new BitMap<int>; bitMapFSR->pixel_x = _plotter->getBitLengthX(); bitMapFSR->pixel_y = _plotter->getBitLengthY(); bitMap->pixel_x = _plotter->getBitLengthX(); bitMap->pixel_y = _plotter->getBitLengthY(); initialize(bitMap); initialize(bitMapFSR); bitMapFSR->geom_x = _geom->getWidth(); bitMapFSR->geom_y = _geom->getHeight(); bitMap->geom_x = _geom->getWidth(); bitMap->geom_y = _geom->getHeight(); bitMapFSR->color_type = SCALED; bitMap->color_type = RANDOM; if (_num_segments != NULL) delete [] _num_segments; if (!_use_input_file) { #if USE_OPENMP #pragma omp parallel for private(i, j, k, phi, \ sin_phi, cos_phi, track, \ x0, y0, x1, y1, num_segments) #endif /* Loop over all tracks */ for (int i = 0; i < _num_azim; i++) { phi = _tracks[i][0].getPhi(); sin_phi = sin(phi); cos_phi = cos(phi); for (int j = 0; j < _num_tracks[i]; j++){ track = &_tracks[i][j]; _geom->segmentize(track); /* plot segments */ if (_plotter->plotSpecs() == true) { x0 = track->getStart()->getX(); y0 = track->getStart()->getY(); num_segments = track->getNumSegments(); for (int k=0; k < num_segments; k++) { log_printf(DEBUG, "Segmented segment: %i...", k); x1 = x0 + cos_phi * track->getSegment(k)->_length; y1 = y0 + sin_phi * track->getSegment(k)->_length; drawLine(bitMap, x0, y0, x1, y1, track->getSegment(k)->_region_id); x0 = x1; y0 = y1; } } /* done with plotting */ } } /* Compute the total number of segments in the simulation */ _num_segments = new int[_tot_num_tracks]; _tot_num_segments = 0; for (int i=0; i < _num_azim; i++) { for (int j=0; j < _num_tracks[i]; j++) { track = &_tracks[i][j]; _num_segments[track->getUid()] = track->getNumSegments(); _tot_num_segments += _num_segments[track->getUid()]; } } log_printf(NORMAL, "Generated %d tracks, %d segments...", _tot_num_tracks, _tot_num_segments); if (_plotter->plotSpecs() == true){ /* plot segments, FSRs, cells, and materials */ plot(bitMap, "segments", _plotter->getExtension()); _plotter->copyFSRMap(bitMapFSR->pixels); plot(bitMapFSR, "FSRs", _plotter->getExtension()); _plotter->makeRegionMap(bitMapFSR->pixels, bitMap->pixels, _geom->getFSRtoCellMap()); plot(bitMap, "cells", _plotter->getExtension()); _plotter->makeRegionMap(bitMapFSR->pixels, bitMap->pixels, _geom->getFSRtoMaterialMap()); plot(bitMap, "materials", _plotter->getExtension()); } /* delete bitMaps */ deleteBitMap(bitMapFSR); deleteBitMap(bitMap); } return; } /** * Generate segments for each track and plot segments * in bitmap array. */ void TrackGenerator::plotSpec() { /* create BitMaps for plotting */ BitMap<int>* bitMapFSR = new BitMap<int>; BitMap<int>* bitMap = new BitMap<int>; bitMapFSR->pixel_x = _plotter->getBitLengthX(); bitMapFSR->pixel_y = _plotter->getBitLengthY(); bitMap->pixel_x = _plotter->getBitLengthX(); bitMap->pixel_y = _plotter->getBitLengthY(); initialize(bitMap); initialize(bitMapFSR); bitMapFSR->geom_x = _geom->getWidth(); bitMapFSR->geom_y = _geom->getHeight(); bitMap->geom_x = _geom->getWidth(); bitMap->geom_y = _geom->getHeight(); bitMapFSR->color_type = RANDOM; bitMap->color_type = RANDOM; if (_plotter->plotSpecs() == true){ _plotter->copyFSRMap(bitMapFSR->pixels); plot(bitMapFSR, "FSRs", _plotter->getExtension()); _plotter->makeRegionMap(bitMapFSR->pixels, bitMap->pixels, _geom->getFSRtoCellMap()); plot(bitMap, "cells", _plotter->getExtension()); _plotter->makeRegionMap(bitMapFSR->pixels, bitMap->pixels, _geom->getFSRtoMaterialMap()); plot(bitMap, "materials", _plotter->getExtension()); } /* delete bitMaps */ deleteBitMap(bitMapFSR); deleteBitMap(bitMap); return; } /** * @brief Writes all track and segment data to a *.tracks file. * @details Storing tracks in a file saves time by eliminating segmentation * for commonly simulated geometries. */ void TrackGenerator::dumpTracksToFile() { if (!_contains_tracks) log_printf(ERROR, "Unable to dump tracks to a file since no tracks " "have been generated for %d azimuthal angles and %f " "track spacing", _num_azim, _spacing); FILE* out; out = fopen(_tracks_filename.c_str(), "w"); std::string geometry_to_string = _geom->toString(); int string_length = geometry_to_string.length(); fwrite(&string_length, sizeof(int), 1, out); fwrite(geometry_to_string.c_str(), sizeof(char)*string_length, 1, out); fwrite(&_num_azim, sizeof(int), 1, out); fwrite(&_spacing, sizeof(double), 1, out); fwrite(_num_tracks, sizeof(int), _num_azim, out); fwrite(_num_x, sizeof(int), _num_azim, out); fwrite(_num_y, sizeof(int), _num_azim, out); double* azim_weights = new double[_num_azim]; for (int i=0; i < _num_azim; i++) azim_weights[i] = _azim_weights[i]; fwrite(azim_weights, sizeof(double), _num_azim, out); delete[] azim_weights; Track* curr_track; double x0, y0, x1, y1; double phi; int azim_angle_index; int num_segments; std::vector<segment*> _segments; segment* curr_segment; double length; int material_id; int region_id; int mesh_surface_fwd; int mesh_surface_bwd; for (int i=0; i < _num_azim; i++) { for (int j=0; j < _num_tracks[i]; j++) { curr_track = &_tracks[i][j]; x0 = curr_track->getStart()->getX(); y0 = curr_track->getStart()->getY(); x1 = curr_track->getEnd()->getX(); y1 = curr_track->getEnd()->getY(); phi = curr_track->getPhi(); azim_angle_index = curr_track->getAzimAngleIndex(); num_segments = curr_track->getNumSegments(); fwrite(&x0, sizeof(double), 1, out); fwrite(&y0, sizeof(double), 1, out); fwrite(&x1, sizeof(double), 1, out); fwrite(&y1, sizeof(double), 1, out); fwrite(&phi, sizeof(double), 1, out); fwrite(&azim_angle_index, sizeof(int), 1, out); fwrite(&num_segments, sizeof(int), 1, out); for (int s=0; s < num_segments; s++) { curr_segment = curr_track->getSegment(s); length = curr_segment->_length; material_id = curr_segment->_material->getId(); region_id = curr_segment->_region_id; fwrite(&length, sizeof(double), 1, out); fwrite(&material_id, sizeof(int), 1, out); fwrite(&region_id, sizeof(int), 1, out); if (_geom->getCmfd() || _geom->getLoo()){ mesh_surface_fwd = curr_segment->_mesh_surface_fwd; mesh_surface_bwd = curr_segment->_mesh_surface_bwd; fwrite(&mesh_surface_fwd, sizeof(int), 1, out); fwrite(&mesh_surface_bwd, sizeof(int), 1, out); } } } } fclose(out); } /** * @brief Reads tracks in from a file. * @details Storing tracks in a file saves time by eliminating segmentation * for commonly simulated geometries. */ bool TrackGenerator::readTracksFromFile() { /* Deletes tracks arrays if tracks have been generated */ if (_contains_tracks) { delete [] _num_tracks; delete [] _num_segments; delete [] _num_x; delete [] _num_y; delete [] _azim_weights; for (int i = 0; i < _num_azim; i++) delete [] _tracks[i]; delete [] _tracks; } FILE* in; in = fopen(_tracks_filename.c_str(), "r"); int string_length; int ret = 0; ret = fread(&string_length, sizeof(int), 1, in); char* geometry_to_string; geometry_to_string = new char[string_length+1]; fread(geometry_to_string, sizeof(char)*string_length, 1, in); geometry_to_string[string_length] = '\0'; if (_geom->toString().compare(0, string_length-1, geometry_to_string, 0, string_length-1) != 0) { log_printf(NORMAL, "Returning from readTracksFromFile, did not " "find a matching file containing generated tracks."); return false; } log_printf(NORMAL, "Reading segmentized tracks from file %s", _tracks_filename.c_str()); fread(&_num_azim, sizeof(int), 1, in); fread(&_spacing, sizeof(double), 1, in); _num_tracks = new int[_num_azim]; _num_x = new int[_num_azim]; _num_y = new int[_num_azim]; _azim_weights = new double[_num_azim]; double* azim_weights = new double[_num_azim]; _tracks = new Track*[_num_azim]; fread(_num_tracks, sizeof(int), _num_azim, in); fread(_num_x, sizeof(int), _num_azim, in); fread(_num_y, sizeof(int), _num_azim, in); fread(azim_weights, sizeof(double), _num_azim, in); for (int i = 0; i < _num_azim; i++) _azim_weights[i] = azim_weights[i]; delete[] azim_weights; Track* curr_track; double x0, y0, x1, y1; double phi; int azim_angle_index; int num_segments; double length; int material_id; int region_id; int mesh_surface_fwd; int mesh_surface_bwd; for (int i=0; i < _num_azim; i++) _tot_num_tracks += _num_tracks[i]; _num_segments = new int[_tot_num_tracks]; int uid = 0; _tot_num_segments = 0; for (int i=0; i < _num_azim; i++) { _tracks[i] = new Track[_num_tracks[i]]; for (int j=0; j < _num_tracks[i]; j++) { fread(&x0, sizeof(double), 1, in); fread(&y0, sizeof(double), 1, in); fread(&x1, sizeof(double), 1, in); fread(&y1, sizeof(double), 1, in); fread(&phi, sizeof(double), 1, in); fread(&azim_angle_index, sizeof(int), 1, in); fread(&num_segments, sizeof(int), 1, in); _tot_num_segments += num_segments; _num_segments[uid] += num_segments; curr_track = &_tracks[i][j]; curr_track->setValues(x0, y0, x1, y1, phi); curr_track->setUid(uid); curr_track->setAzimAngleIndex(azim_angle_index); // Added: curr_track->setAzimuthalWeight(_azim_weights[i]); for (int s=0; s < num_segments; s++) { fread(&length, sizeof(double), 1, in); fread(&material_id, sizeof(int), 1, in); fread(&region_id, sizeof(int), 1, in); segment* curr_segment = new segment; curr_segment->_length = length; curr_segment->_material = _geom->getMaterial(material_id); curr_segment->_region_id = region_id; if (_geom->getCmfd() || _geom->getLoo()){ fread(&mesh_surface_fwd, sizeof(int), 1, in); fread(&mesh_surface_bwd, sizeof(int), 1, in); curr_segment->_mesh_surface_fwd = mesh_surface_fwd; curr_segment->_mesh_surface_bwd = mesh_surface_bwd; } curr_track->addSegment(curr_segment); } uid++; } } if (ret) _contains_tracks = true; fclose(in); delete [] geometry_to_string; return true; }
4d3121deb84b43ea9692bee07384d1d4e92fb5ff
21fe6e3a229e480a27b33b6a98b41fbacc0e91a4
/src/message.hpp
356e7a0c8e802cf2daa7c035d2c4488ed2f82058
[]
no_license
Tusgavin/UDP-FileTransfer-ClientServer
7ab9669dace500d3c26ecd640d71beb0fe5893f4
f924e7a7a2f10e775c2aaa3bc7826b8f9eb8a8e6
refs/heads/master
2023-03-21T00:35:53.010828
2021-03-03T17:56:19
2021-03-03T17:56:19
344,212,496
0
0
null
null
null
null
UTF-8
C++
false
false
878
hpp
message.hpp
#ifndef MESSAGE_HPP #define MESSAGE_HPP #include <stdint.h> #define UDP_PORT_SIZE 4 #define FILE_NAME_SIZE 15 #define HELLO 1 #define CONNECTION 2 #define INFO_FILE 3 #define OK 4 #define FIM 5 #define FILE 6 #define ACK 7 #pragma pack(1) typedef struct { uint16_t id; } HELLO_OK_FIM_message_struct; #pragma pack() #pragma pack(1) typedef struct { uint16_t id; uint32_t port; } CONNECTION_message_struct; #pragma pack() #pragma pack(1) typedef struct { uint16_t id; char file_name[15]; uint64_t file_size; } INFOFILE_message_struct; #pragma pack() #pragma pack(1) typedef struct { uint16_t id; char sequence_number[4]; uint16_t payload_size; char payload_file[1000]; } FILE_message_struct; #pragma pack() #pragma pack(1) typedef struct { uint16_t id; char sequence_number[4]; } ACK_message_struct; #pragma pack() #endif //MESSAGE_HPP
066e84302736f2806262c94d35060f3e36a98482
dd7632e0e77aa4ff03e23bdce7d65234f4712540
/algorithms/Rotate Array/Rotate Array.cpp
eacd78881b1356a622a89df40f2ee4de5146e3b5
[]
no_license
luckcul/LeetCode
f979a7771455312471b9b516c1a48cfb53086c2e
9fa0ad174e6925fce4aae32a459e4a3c23951060
refs/heads/master
2021-01-20T18:48:50.657792
2020-10-21T22:30:55
2020-10-21T22:30:55
64,599,280
2
0
null
null
null
null
UTF-8
C++
false
false
727
cpp
Rotate Array.cpp
class Solution { public: void rotate(vector<int>& nums, int k) { int n = nums.size(); k %= n; if(k == 0) return ; int cycle = gcd(n, k); for(int i = 0; i < cycle; i++) { int now_index = i, now_val = nums[now_index]; int count = 0; int upper = n/cycle; while(count < upper) { now_index = (now_index + k) % n; int next_val = nums[now_index]; nums[now_index] = now_val; now_val = next_val; count ++; } } } int gcd(int a, int b) { if(!b) return a; if(a < b) return gcd(b, a); return gcd(b, a%b); } };
a118bcb21715d6642626e82f991794682a2fda5a
87c9e205ee1de595258f0f7a9432df448d637664
/nfs/client/Client.cpp
6703b8031a597f90d0a6229dc4ffbaf26fceb4e1
[]
no_license
faushine/NFS-CS754
210d6605ca34297baaa24125e63358e815972922
6d0f2af4f4b5459d38f9e9b0729975cc2cd09aba
refs/heads/master
2020-08-27T15:09:20.409466
2020-01-13T00:00:16
2020-01-13T00:00:16
217,417,782
2
0
null
null
null
null
UTF-8
C++
false
false
3,138
cpp
Client.cpp
// // Created by l367zhan on 2019-10-17. // #define FUSE_USE_VERSION 31 #include "fuse.h" #include <sys/stat.h> #include <fuse.h> #include "NFSClient.h" #include <stdio.h> struct fuse_operations nfsOps; std::string toStr(const char *path) { std::string a(path); return a; } bool useCommit = true; static ClientImp NFSClient(grpc::CreateChannel("localhost:3110", grpc::InsecureChannelCredentials())); int nfs_getattr(const char *path, struct stat *statbuf, struct fuse_file_info *fi) { std::string pathstr(path); std::cout << path << std::endl; return NFSClient.client_getattr(pathstr, statbuf); } int nfs_mkdir(const char *path, mode_t mode) { return NFSClient.client_mkdir(toStr(path), mode); } int nfs_rmdir(const char *path) { return NFSClient.client_rmdir(toStr(path)); } int nfs_rename(const char *path, const char *newpath, unsigned int flag) { return NFSClient.client_rename(toStr(path), toStr(newpath)); } int nfs_create(const char *path, mode_t mode, struct fuse_file_info *fileInfo) { return NFSClient.client_create(toStr(path), mode, fileInfo); } int nfs_open(const char *path, struct fuse_file_info *fileInfo) { return NFSClient.client_open(toStr(path), fileInfo); } int nfs_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo) { return NFSClient.client_read(path, buf, size, offset, fileInfo); } int nfs_unlink(const char *path) { return NFSClient.client_unlink(path); } int nfs_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo) { std::string pathstr(path); return NFSClient.client_write(pathstr, buf, size, offset, fileInfo); } int nfs_flush(const char *path, struct fuse_file_info *fileInfo) { std::string pathstr(path); return NFSClient.client_flush(pathstr, fileInfo, useCommit); } int nfs_release(const char *path, struct fuse_file_info *fileInfo) { return NFSClient.client_release(path, fileInfo, useCommit); } int nfs_fsync(const char *path, int isDataSync, struct fuse_file_info *fileInfo) { return NFSClient.client_fsync(path, isDataSync, fileInfo, useCommit); } int nfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fileInfo, fuse_readdir_flags rflags) { int responseCode; std::string pathValue(path); std::list <DirEntry> dirEntries = NFSClient.read_directory(pathValue, responseCode); for (auto const &dirEntry : dirEntries) { filler(buf, dirEntry.name.c_str(), &dirEntry.st, 0, FUSE_FILL_DIR_PLUS); } return responseCode; } int main(int argc, char **argv) { nfsOps.getattr = &nfs_getattr; nfsOps.readdir = &nfs_readdir; nfsOps.read = &nfs_read; nfsOps.mkdir = &nfs_mkdir; nfsOps.rmdir = &nfs_rmdir; nfsOps.rename = &nfs_rename; nfsOps.create = &nfs_create; nfsOps.open = &nfs_open; nfsOps.release = &nfs_release; nfsOps.unlink = &nfs_unlink; nfsOps.write = &nfs_write; nfsOps.flush = &nfs_flush; nfsOps.fsync = &nfs_fsync; return fuse_main(argc, argv, &nfsOps, NULL); }
db7512646131400cc93c7418113a590093ddf099
f25a9618845af6f7278947a47ca5354b7ad2f827
/include/LoggerWithHighlighting.h
36db8ed9e0e29afa1f8931d9945f5992f9e2fa6a
[ "MIT" ]
permissive
Szmyk/zspy-cli
ed054dc7c3d21f50347dd995b296f46690ce0f0b
5639f1b2d84652f3c8bf51ba391a2a4bbc1ba50b
refs/heads/master
2020-04-28T01:51:04.795993
2019-05-07T20:22:01
2019-05-07T20:22:01
174,875,094
8
0
null
null
null
null
UTF-8
C++
false
false
314
h
LoggerWithHighlighting.h
#pragma once #include "ILogger.h" #include <vector> class LoggerWithHighlighting : public ILogger { private: std::string textToHighlight; void performWriteLine(std::string message, rang::fg color); public: LoggerWithHighlighting(std::string textToHighlight, std::vector<std::string> messagesTypes); };
8400c46986a645c11b1668d27a202e041640651f
c2d63db2bb391c73849393804d5d33df889aa7a2
/Player.hpp
5630f0dfb6c7017b843f881a198d5d0e775c10e7
[]
no_license
KevinShaughnessy/RPG
78ee6353498063d6dde2cec7242d08c2041fdd5d
90bab83c981857640ee67d40c51dca16335dad02
refs/heads/master
2020-12-25T06:32:55.367448
2013-02-05T23:12:14
2013-02-05T23:12:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,601
hpp
Player.hpp
/* * File: Player.h * Author: Adrian * * Created on 15. Dezember 2012, 17:47 */ #include <string> #include <list> #include "Singleton.hpp" #include "Sprite.hpp" #include "Combat.hpp" #ifndef PLAYER_H #define PLAYER_H using namespace std; #define g_pPlayer Player::Get() enum DIRECTIONS { UP, DOWN, LEFT, RIGHT }; class Player : public TSingleton<Player> { public: Player(); Player(const Player& orig); virtual ~Player(); void Init(); void Quit(); void Reset(); void Render(); void Update(); string getName(); float getHP(); float getDMG(); float getSpeed(); float getHPreg(); int getStr(); int getVita(); int getDex(); int getSpirit(); int getLevel(); float getCurrentHP(); int getDirection(); void setName(string name); void setHP(float hp); void setDMG(float dmg); void setSpeed(float speed); void setHPreg(float hpReg); void setStr(int str); void setVita(int vita); void setDex(int dex); void setSpirit(int spirit); void setLevel(int level); void setCurrentHP(float newhp); void setEXP(long exp_gained); void levelUp(); void chooseStatPoint(); void displayStats(); struct hitbox { int width; int height; int left; int right; int top; int bottom; } player; struct attackbox { float atkXpos; float atkYpos; int width; int height; int left; int right; int top; int bottom; } player_atk_box; private: void ProcessMoving(); void Attacking(); void CheckPosition(); void AtkBoxPositioning(); void updateHitbox(); float calcHP(); float calcDMG(); float calcSpeed(); float calcHPreg(); bool attack_processed; float xPos; float yPos; float animPhase; float temp_animPhase; float animTimer; float currentHP; float hp; float dmg; float speed; float hpReg; int str; int vita; int dex; int spirit; int level; long exp; int currentDirection; bool diagonal_moving; string name; CSprite *SpritePlayer; static const int maxLevel; static const long exp_base; static const long exp_step; static const float vita_hp_factor; static const float str_dmg_factor; static const float dex_dmg_factor; static const float dex_speed_factor; static const float spirit_hpReg_factor; }; #endif /* PLAYER_H */
5cd3e24933673ff5bc7b6cb21cf885c8322a8acd
89239a46b20e9b17606ab541bc497b5fad08faa1
/US_Dist_LCD.ino
fa9265c1fa18bd8e0b580eb6f1cc4cec0c193cdc
[]
no_license
Manegiste/US_Dist_LCD
b8a36a750f3eaebca7a2be730ab8357f98381cd7
86a8aa7a4d8e2e9560283a271527956e7a62b0c5
refs/heads/master
2020-04-01T02:55:37.437952
2018-10-12T20:02:55
2018-10-12T20:02:55
152,801,890
0
0
null
null
null
null
UTF-8
C++
false
false
941
ino
US_Dist_LCD.ino
#define US_TRIG 2 #define US_ECHO 3 int US_Measure() { long duration; long distance; Serial.println ("Mesure ============="); // Clears the trigPin digitalWrite(US_TRIG, LOW); delayMicroseconds(2); // Sets the trigPin on HIGH state for 10 micro seconds digitalWrite(US_TRIG, HIGH); delayMicroseconds(10); digitalWrite(US_TRIG, LOW); // Reads the echoPin, returns the sound wave travel time in microseconds duration = pulseIn(US_ECHO, HIGH); Serial.println (duration); // Calculating the distance distance = duration * 0.034 / 2; return distance; } void setup() { // Ultrasound: send on 0, get feedback on 1 pinMode(US_TRIG, OUTPUT); pinMode(US_ECHO, INPUT); Serial.begin(9600); Serial.print ("************************************* Go ! Go ! Go !"); } void loop() { int dist = 0; dist = US_Measure(); Serial.print ("Distance: "); Serial.println (dist); delay (1000); }
678baca30807f27dede38ca25c387b65fb21cdae
f55a0e269d95418dcc600fd43c59f0ba76caaced
/MyWindow--createLinesTab.cpp
285ba94844d488188f7b2e28b36a523a736aa1c3
[]
no_license
dualsky/DynamicTemplates
550c159a6b235a37d5fae3cbc4a139bab52163f5
a8ce6a101f79174aa3824c159da7d0483398e844
refs/heads/master
2021-01-24T23:00:48.649628
2014-03-17T20:30:52
2014-03-17T20:30:52
29,475,833
2
0
null
2015-01-19T14:57:13
2015-01-19T14:57:13
null
UTF-8
C++
false
false
3,386
cpp
MyWindow--createLinesTab.cpp
// // $Id: MyWindow--createLinesTab.cpp,v 1.4 2009/01/29 02:47:51 igor Exp $ // // This file is part of DIY_Dynamic_Templates_V2 // // DIY_Dynamic_Templates_V2 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. // // DIY_Dynamic_Templates_V2 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. // // Refer to the GNU General Public License in file "license.txt" // Otherwise, see <http://www.gnu.org/licenses/>. #include "MyWindow.h" QWidget* MyWindow::createLinesTab ( QWidget* grandParent ) // : QWidget(parent) { QWidget* parent = new QWidget( grandParent ) ; customLine = new QDoubleSpinBox() ; customLine->setDecimals ( 4 ) ; customLine->setMinimum ( 0.0010 ) ; customLine->setMaximum ( 99.9999 ) ; customLine->setSingleStep ( 0.0100 ) ; customLine->setSuffix ( " x " ) ; linesComboBox = new QComboBox ( parent ) ; linesComboBox->addItem( tr("Wide Ruled") ) ; linesComboBox->addItem( tr("College Ruled") ) ; linesComboBox->addItem( tr("Narrow Ruled") ) ; linesComboBox->addItem( tr( "Custom" ) ) ; connect ( customLine, SIGNAL( valueChanged ( double ) ), this, SLOT( customLineChanged ( double ) ) ) ; connect ( linesComboBox, SIGNAL ( activated ( int ) ), this, SLOT ( linesComboBoxChanged ( int ) ) ) ; QSlider *penSlider = new QSlider ( Qt::Horizontal, parent ) ; penSlider->setMaximum ( 100 ) ; penSlider->setMinimum ( 1 ) ; QFormLayout* formLayout = new QFormLayout ( parent ) ; formLayout->addRow ( tr("Line Spacing:"), linesComboBox ) ; formLayout->addRow ( customLine ) ; linesThickLabel = new QLabel ( tr("Line Width - 0.10 - 10.0") ) ; formLayout->addRow ( linesThickLabel, penSlider ) ; linesComboBox->setCurrentIndex ( 1 ) ; linesComboBoxChanged ( 1 ) ; connect ( penSlider, SIGNAL ( valueChanged(int) ), this, SLOT ( penWidthSliderChanged(int) ) ) ; connect ( penSlider, SIGNAL ( valueChanged(int) ), this, SLOT ( setPenWidthLabel(int) ) ) ; penSlider->setValue ( 55 ) ; emit penWidthChanged ( 55 ) ; customLine->hide() ; return parent ; } ; void MyWindow::linesComboBoxChanged ( int which ) { switch ( which ) { case 0: lineSpaceValue = 8.70 ; // Wide customLine->hide() ; break ; case 1: lineSpaceValue = 7.10 ; // College or medium customLine->hide() ; break ; case 2: lineSpaceValue = 6.35 ; // Narrow or Legal customLine->hide() ; break ; case 3: // Custom qreal conv ; if ( isItInches ) { conv = MM_TO_INCHES ; } else { conv = MM_TO_CM ; } customLine->setValue( lineSpaceValue * conv ) ; customLine->show() ; break ; default: break ; } emit linesChanged ( lineSpaceValue ) ; } ; void MyWindow::penWidthSliderChanged ( int which ) { emit penWidthChanged ( which ) ; } ; void MyWindow::setPenWidthLabel ( int value ) { QString text = tr("Line Width - 0.10 - 10.0") + " (" + QString("%1").arg( (float) value / 10.0, 2, 'f', 1 ) + ")" ; linesThickLabel->setText ( tr( text.toLatin1().constData() ) ) ; }
140bffe52fb9d7d460800959a9c583b6ceeaf95d
9bf46e3671777ad141a1224eec2f9d36f19676d7
/main.cpp
0ef085dcebd12d41318f6001918754d4b4a10a6f
[]
no_license
Rahulsharma468/CG_PROJECT
c8c968bc2d8ecc89cc41bcd4fecd83724c1e1960
13b354deebd917a94ebddd01215d14e2efe0efa4
refs/heads/main
2023-04-15T19:04:59.296771
2021-05-02T14:53:49
2021-05-02T14:53:49
363,675,686
0
0
null
null
null
null
UTF-8
C++
false
false
6,463
cpp
main.cpp
#ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/glut.h> #include <GL/glu.h> #endif #include <stdio.h> #include <math.h> #include <stdlib.h> int win; GLint m_viewport[4]; bool mButtonPressed = false; enum view { INTRO , MENU , LINEAR , BINARY , EXIT}; view currentView = INTRO; int mouseX , mouseY; int val = 0; void *font = GLUT_BITMAP_9_BY_15; void init(){ glClearColor(1,1,1,1); glMatrixMode(GL_PROJECTION); glMatrixMode(GL_VIEWPORT); glLoadIdentity(); gluOrtho2D(0,700,0,700); } void output(int x , int y , char *str){ int len, i; glRasterPos2f(x, y); len = (int) strlen(str); for (i = 0; i < len; i++) { glutBitmapCharacter(font, str[i]); } } void backButton() { glBegin(GL_LINE_LOOP); glVertex2f(69,46); glVertex2f(69,75); glVertex2f(138,75); glVertex2f(138,46); glEnd(); if(mouseX <= 138 && mouseX >= 69 && mouseY >= 46 && mouseY <= 75){ glColor3f(0, 0, 1); if(mButtonPressed) { currentView = MENU; mButtonPressed = false; glutPostRedisplay(); } } else glColor3f(1, 0, 0); output(82 ,58 , "Back"); } void rasterDisp(int x , int y , int z , char *str){ glColor3b(1,1,1); glRasterPos3f(x, y, z); for(char* c = str; *c != '\0'; c++){ glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24 , *c); } } void introScreen(){ glClear(GL_COLOR_BUFFER_BIT); //OUTER LINE glColor3f(0,0,0); glLineWidth(2); glBegin(GL_LINE_LOOP); glVertex2f(7,7); glVertex2f(696,7); glVertex2f(696,696); glVertex2f(7,696); glEnd(); //END OUTER LINE //INNER LINE glColor3f(0,0,0); glLineWidth(1); glBegin(GL_LINE_LOOP); glVertex2f(14 , 14); glVertex2f(689,14); glVertex2f(689,689); glVertex2f(14,689); glEnd(); //END INNER LINE glColor3f(0,0,1); output(160, 660 ,"N.M.A.M INSTITUTE OF TECHNOLOGY"); glColor3f(0,0,0); output(120, 630,"Department of Computer Science and Engineering"); //LINE BELOW COLLEGE LOGO glBegin(GL_LINES); glVertex2f(20,620); glVertex2f(680,620); glEnd(); //END LINE BELOW LOGO output(90, 590, "Mini Project Title:"); output(230, 590, " Visualization of Searching Algorithms"); output(129, 565 , "Course Code : "); output(230, 565 , "18CS603"); output(129, 540, "Course Name : "); output(230, 540, "Computer Graphics"); output(148, 515, "Semester : "); output(230, 515, "6th "); output(155, 495, "Section : "); output(230, 495, "C "); output(124, 475, "Submitted By : "); output(230 , 475 , "4NM18CS164"); output(230 , 455 , "(Sharma Rahul Munna)"); output(370 , 475 , "4NM18CS128"); output(370 , 455 , "(Ramsharavan)"); output(124, 425, "Submitted To :"); output(230, 425, "Mr Puneeth R.P "); output(230 , 405 , "Assistant Professor Grade II"); output(190 , 380 , "Department Of Computer Science And Engineering"); output(150 , 300,"Press ENTER"); glFlush(); glutSwapBuffers(); } void tick(){ glutPostRedisplay(); } void passiveMotionFunc(int x,int y) { mouseX = float(x)/(m_viewport[2]/700.0); mouseY = 700.0-(float(y)/(m_viewport[3]/700.0)); glutPostRedisplay(); } void startScreen(){ //LINEAR BUTTON glLineWidth(4); glBegin(GL_LINE_LOOP); glVertex2f(240 , 550); glVertex2f(240 , 650); glVertex2f(440 , 650); glVertex2f(440 , 550); glEnd(); if(mouseX >= 240 && mouseX <= 440 && mouseY>=550 && mouseY<=650){ glColor3f(0 ,0 ,1); if(mButtonPressed){ currentView = LINEAR; mButtonPressed = false; } } else glColor3f(1 , 0, 0); rasterDisp(300 , 590 , 0.4 , "LINEAR"); //END LINEAR BUTTON //BINARY BUTTON glLineWidth(4); glBegin(GL_LINE_LOOP); glVertex2f(240 , 350); glVertex2f(240 , 450); glVertex2f(440 , 450); glVertex2f(440 , 350); glEnd(); if(mouseX>=240 && mouseX<=440 && mouseY>=350 && mouseY<=450){ glColor3f(0 ,0 ,1); if(mButtonPressed){ currentView = BINARY; mButtonPressed = false; } } else glColor3f(1 , 0, 0); rasterDisp(300 , 390 , 0.4 , "BINARY"); //END BINARY BUTTON //EXIT BUTTON glLineWidth(4); glBegin(GL_LINE_LOOP); glVertex2f(240 , 150); glVertex2f(240 , 250); glVertex2f(440 , 250); glVertex2f(440 , 150); glEnd(); if(mouseX>=240 && mouseX<=440 && mouseY>=150 && mouseY<=250){ glColor3f(0 ,0 ,1); if(mButtonPressed){ currentView = EXIT; mButtonPressed = false; } } else glColor3f(1 , 0, 0); rasterDisp(300 , 190 , 0.4 , "QUIT"); //END EXIT BUTTON glutPostRedisplay(); } void mouseClick(int buttonPressed ,int state ,int x, int y) { if(buttonPressed == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { mButtonPressed = true; printf("mousex = %d \nmouseY = %d\n", mouseX, mouseY); } else mButtonPressed = false; glutPostRedisplay(); } void keyPressed(unsigned char k, int x, int y){ printf("key pressed\n"); switch (k) { case 13: if(currentView == INTRO) { currentView = MENU; printf("view value changed to %d", currentView); } printf("enter key pressed\n"); break; } glutPostRedisplay(); } void linear(){ backButton(); glutPostRedisplay(); } void exitScreen(){ backButton(); glutDestroyWindow(win); exit(0); } void binary(){ backButton(); glutPostRedisplay(); } void display(){ glClear(GL_COLOR_BUFFER_BIT); switch (currentView) { case INTRO: introScreen(); break; case MENU: startScreen(); break; case LINEAR: linear(); break; case BINARY: binary(); break; case EXIT: exitScreen(); break; default: introScreen(); break; } glFlush(); glutSwapBuffers(); } int main(int argc , char **argv){ glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowPosition(500,90); glutInitWindowSize(700, 700); win = glutCreateWindow("Dynamic Searching Visualizer"); init(); glutDisplayFunc(display); glutKeyboardFunc(keyPressed); glutMouseFunc(mouseClick); glGetIntegerv(GL_VIEWPORT ,m_viewport); glutPassiveMotionFunc(passiveMotionFunc); glutMainLoop(); return 0; }
8dd9e8683f9911c8d80b82953b528c334b4d156b
00e9b8471bd2e81ceb667fc82e49240babbb113e
/main/src/coursewareTools/whiteboardtools.cpp
13005730d1bb0c4414c058a720b7f5d1510e157e
[]
no_license
Xershoo/BM-Client
4a6df1e4465d806bca6718391fc2f5c46ab1d2b4
2d1b8d26d63bb54b1ac296341353a6e07809b2d6
refs/heads/master
2020-03-29T05:01:00.564762
2019-03-06T01:46:35
2019-03-06T01:46:35
149,561,359
5
1
null
null
null
null
UTF-8
C++
false
false
11,929
cpp
whiteboardtools.cpp
#include "whiteboardtools.h" #include <QBitmap> #include <QDesktopWidget> #include "common/Env.h" #include "common/macros.h" #include "Courseware/coursewaredatamgr.h" #include "session/classsession.h" #include "Courseware/CoursewareTaskMgr.h" #include "Courseware/CoursewarePanel.h" whiteboardtools::whiteboardtools(QWidget *parent) : QWidget(parent) { ui.setupUi(this); connect(ui.pushButton_classRoomLeftClearAllBtn, SIGNAL(clicked()), this, SLOT(clickBtnClearAll())); connect(ui.pushButton_classRoomLeftColorBtn, SIGNAL(clicked()), this, SLOT(clickBtnColor())); connect(ui.pushButton_classRoomLeftEraserBtn, SIGNAL(clicked()), this, SLOT(clickBtnEraser())); connect(ui.pushButton_classRoomLeftMoveBtn, SIGNAL(clicked()), this, SLOT(clickBtnMove())); connect(ui.pushButton_classRoomLeftPenBtn, SIGNAL(clicked()), this, SLOT(clickBtnPen())); connect(ui.pushButton_classRoomLeftShowPreviewBtn, SIGNAL(clicked()), this, SLOT(clickBtnPreview())); connect(ui.pushButton_classRoomLeftTextBtn, SIGNAL(clicked()), this, SLOT(clickBtnText())); connect(ui.pushButton_classRoomLeftUndoBtn, SIGNAL(clicked()), this, SLOT(clickBtnUndo())); connect(ui.label_classRoomLeftHide, SIGNAL(clicked()), this, SLOT(leftSlideHideLabelClicked())); if (CoursewareDataMgr::GetInstance()->m_CoursewarePanel) { CoursewareDataMgr::GetInstance()->m_CoursewarePanel->setPreviewList(m_coursewarePreview.GetListWidget()); } connect(&m_selectColor, SIGNAL(set_now_color(int)), this, SLOT(ShowNowColor(int))); connect(ui.pushButton_showStuVideoListWnd, SIGNAL(clicked()), this, SLOT(showStuVideoListWndBtnClicked())); int nHeight = ui.widget_leftSildBar->height()/2 - 66/2; QRect rect = ui.label_classRoomLeftHide->rect(); //xiewb 2018.09.29 ui.pushButton_showStuVideoListWnd->hide(); } whiteboardtools::~whiteboardtools() { } void whiteboardtools::showStuVideoListWndBtnClicked() { emit show_stu_video_list(); } void whiteboardtools::leftSlideHideLabelClicked() { int nHeight = (ui.widget_leftSildBar->height() - 66)/2; QRect re = ui.verticalSpacer_2->geometry(); re.setHeight(nHeight); ui.verticalSpacer_2->setGeometry(re); if (ui.widget_leftSildeToolBtns_bk->isVisible()) { QString pixPath = Env::currentThemeResPath() + "widget_leftSildBar_mask2.png"; QPixmap pix(pixPath); QRegion rgn(0, nHeight, 50, 66); ui.widget_leftSildBar->setMask(rgn); ui.widget_leftSildeToolBtns_bk->hide(); } else { QString pixPath = Env::currentThemeResPath() + "widget_leftSildBar_mask.png"; QPixmap pix(pixPath); QRegion rgn1(0, 0, 41, QApplication::desktop()->height()); QRegion rgn2(0, nHeight, 50, 66); rgn1 = rgn1.united(rgn2); ui.widget_leftSildBar->setMask(rgn1/*pix.mask()*/); ui.widget_leftSildeToolBtns_bk->show(); } } void whiteboardtools::setRegion() { int nHeight = (ui.widget_leftSildBar->height() - 66)/2; QRect re = ui.verticalSpacer_2->geometry(); re.setHeight(nHeight); ui.verticalSpacer_2->setGeometry(re); QRegion rgn1(0, 0, 41, QApplication::desktop()->height()); QRegion rgn2(0, nHeight, 50, 70); rgn1 = rgn1.united(rgn2); ui.widget_leftSildBar->setMask(rgn1/*pix.mask()*/); } void whiteboardtools::clickBtnClearAll() { CoursewareDataMgr::GetInstance()->Clear(); } void whiteboardtools::clickBtnColor() { int nType = GetCoursewareFileType(wstring((wchar_t*)(CoursewareDataMgr::GetInstance()->m_NowFileName).unicode()).data()); if (COURSEWARE_AUDIO == nType || COURSEWARE_VIDEO == nType || COURSEWARE_IMG == nType || CoursewareDataMgr::GetInstance()->m_NowFileName.isEmpty()) { return; } QSize size = m_selectColor.size(); QPoint ptGlobal = ui.pushButton_classRoomLeftColorBtn->mapToGlobal(QPoint(0, 0)); ptGlobal.setY(ptGlobal.y()); ptGlobal.setX(ptGlobal.x() + ui.pushButton_classRoomLeftColorBtn->size().width()+5); m_selectColor.setGeometry(QRect(ptGlobal, size)); m_selectColor.SetColor(CoursewareDataMgr::GetInstance()->m_nColorType); m_selectColor.show(); m_selectColor.activateWindow(); } void whiteboardtools::clickBtnEraser() { CoursewareDataMgr::GetInstance()->SetMode(WB_MODE_ERASER); } void whiteboardtools::clickBtnMove() { CoursewareDataMgr::GetInstance()->SetMode(WB_MODE_NONE); } void whiteboardtools::clickBtnPen() { CoursewareDataMgr::GetInstance()->SetMode(WB_MODE_CURVE); } void whiteboardtools::clickBtnPreview() { PCOURSEWAREDATA pData = CoursewareTaskMgr::getInstance()->GetCoursewareByNameEx(wstring((wchar_t*)(CoursewareDataMgr::GetInstance()->m_NowFileName).unicode()).data()); if (pData && COURSEWARE_STATE_OK == pData->m_nState) { int nType = GetCoursewareFileType(wstring((wchar_t*)(CoursewareDataMgr::GetInstance()->m_NowFileName).unicode()).data()); if (COURSEWARE_PDF == nType || COURSEWARE_EXCLE == nType || COURSEWARE_DOC == nType || COURSEWARE_PPT == nType) { QSize size = m_coursewarePreview.size(); QPoint ptGlobal = this->mapToGlobal(QPoint(0, 0)); ptGlobal.setY(ptGlobal.y()); ptGlobal.setX(ptGlobal.x() + ui.widget_leftSildeToolBtns_bk->size().width()); m_coursewarePreview.setGeometry(QRect(ptGlobal, size)); m_coursewarePreview.show(); m_coursewarePreview.activateWindow(); } SAFE_DELETE(pData); } } void whiteboardtools::clickBtnText() { int nType = GetCoursewareFileType(wstring((wchar_t*)(CoursewareDataMgr::GetInstance()->m_NowFileName).unicode()).data()); if (COURSEWARE_AUDIO == nType || COURSEWARE_VIDEO == nType || COURSEWARE_IMG == nType || CoursewareDataMgr::GetInstance()->m_NowFileName.isEmpty()) { return; } QSize size = m_selectText.size(); QPoint ptGlobal = ui.pushButton_classRoomLeftTextBtn->mapToGlobal(QPoint(0, 0)); ptGlobal.setY(ptGlobal.y()); ptGlobal.setX(ptGlobal.x() + ui.pushButton_classRoomLeftTextBtn->size().width()+5); m_selectText.setGeometry(QRect(ptGlobal, size)); CoursewareDataMgr::GetInstance()->SetMode(WB_MODE_TEXT); m_selectText.SetFontSize(CoursewareDataMgr::GetInstance()->m_nFontSize); m_selectText.show(); m_selectText.activateWindow(); } void whiteboardtools::clickBtnUndo() { CoursewareDataMgr::GetInstance()->UnDo(); } void whiteboardtools::ShowPreview(QString filePath, int npage) { m_coursewarePreview.ShowPreview(filePath, npage); } void whiteboardtools::RemovePreview(QString filePath) { m_coursewarePreview.RemovePreview(filePath); } bool whiteboardtools::releaseViewData() { return true; } void whiteboardtools::showUI(bool bISShow) { if (ClassSeeion::GetInst()->IsTeacher()) { //xiewb 2018.09.30 ui.pushButton_showStuVideoListWnd->hide(); ui.line_left->hide(); if (bISShow) { ui.pushButton_classRoomLeftMoveBtn->setDisabled(false); ui.pushButton_classRoomLeftShowPreviewBtn->setDisabled(false); ui.pushButton_classRoomLeftPenBtn->setDisabled(false); ui.pushButton_classRoomLeftTextBtn->setDisabled(false); ui.pushButton_classRoomLeftColorBtn->setDisabled(false); ui.pushButton_classRoomLeftEraserBtn->setDisabled(false); ui.pushButton_classRoomLeftUndoBtn->setDisabled(false); ui.pushButton_classRoomLeftClearAllBtn->setDisabled(false); } else { ui.pushButton_classRoomLeftMoveBtn->setDisabled(true); ui.pushButton_classRoomLeftShowPreviewBtn->setDisabled(true); ui.pushButton_classRoomLeftPenBtn->setDisabled(true); ui.pushButton_classRoomLeftTextBtn->setDisabled(true); ui.pushButton_classRoomLeftColorBtn->setDisabled(true); ui.pushButton_classRoomLeftEraserBtn->setDisabled(true); ui.pushButton_classRoomLeftUndoBtn->setDisabled(true); ui.pushButton_classRoomLeftClearAllBtn->setDisabled(true); } } else if (ClassSeeion::GetInst()->IsStudent()) { #ifdef STUDENT_NO_SHOW_VIDEO_LIST ui.pushButton_showStuVideoListWnd->hide(); ui.line_left->hide(); #endif if (bISShow) { ui.pushButton_classRoomLeftMoveBtn->setDisabled(true); ui.pushButton_classRoomLeftPenBtn->setDisabled(false); ui.pushButton_classRoomLeftTextBtn->setDisabled(false); ui.pushButton_classRoomLeftColorBtn->setDisabled(false); ui.pushButton_classRoomLeftEraserBtn->setDisabled(false); ui.pushButton_classRoomLeftUndoBtn->setDisabled(false); ui.pushButton_classRoomLeftClearAllBtn->setDisabled(false); ui.pushButton_classRoomLeftShowPreviewBtn->hide(); } else { ui.pushButton_classRoomLeftMoveBtn->setDisabled(true); ui.pushButton_classRoomLeftPenBtn->setDisabled(true); ui.pushButton_classRoomLeftTextBtn->setDisabled(true); ui.pushButton_classRoomLeftColorBtn->setDisabled(true); ui.pushButton_classRoomLeftEraserBtn->setDisabled(true); ui.pushButton_classRoomLeftUndoBtn->setDisabled(true); ui.pushButton_classRoomLeftClearAllBtn->setDisabled(true); ui.pushButton_classRoomLeftShowPreviewBtn->hide(); } } } void whiteboardtools::ShowNowColor(int nColor) { QIcon colorSettingIcon; switch (nColor) { case WB_COLOR_RED: { colorSettingIcon.addFile(Env::currentThemeResPath() + "leftSildeColorBtn_normal.png", QSize(), QIcon::Normal, QIcon::On); colorSettingIcon.addFile(Env::currentThemeResPath() + "leftSildeColorBtn_hover.png", QSize(), QIcon::Active, QIcon::On); colorSettingIcon.addFile(Env::currentThemeResPath() + "leftSildeColorBtn_pressed.png", QSize(), QIcon::Selected, QIcon::On); } break; case WB_COLOR_YELLOW: { colorSettingIcon.addFile(Env::currentThemeResPath() + "yellow_normal.png", QSize(), QIcon::Normal, QIcon::On); colorSettingIcon.addFile(Env::currentThemeResPath() + "yellow_hover.png", QSize(), QIcon::Active, QIcon::On); colorSettingIcon.addFile(Env::currentThemeResPath() + "yellow_pressed.png", QSize(), QIcon::Selected, QIcon::On); } break; case WB_COLOR_BLUE: { colorSettingIcon.addFile(Env::currentThemeResPath() + "blue_normal.png", QSize(), QIcon::Normal, QIcon::On); colorSettingIcon.addFile(Env::currentThemeResPath() + "blue_hover.png", QSize(), QIcon::Active, QIcon::On); colorSettingIcon.addFile(Env::currentThemeResPath() + "blue_pressed.png", QSize(), QIcon::Selected, QIcon::On); } break; case WB_COLOR_GREEN: { colorSettingIcon.addFile(Env::currentThemeResPath() + "green_normal.png", QSize(), QIcon::Normal, QIcon::On); colorSettingIcon.addFile(Env::currentThemeResPath() + "green_hover.png", QSize(), QIcon::Active, QIcon::On); colorSettingIcon.addFile(Env::currentThemeResPath() + "green_pressed.png", QSize(), QIcon::Selected, QIcon::On); } break; case WB_COLOR_WHITE: { colorSettingIcon.addFile(Env::currentThemeResPath() + "white_normal.png", QSize(), QIcon::Normal, QIcon::On); colorSettingIcon.addFile(Env::currentThemeResPath() + "white_hover.png", QSize(), QIcon::Active, QIcon::On); colorSettingIcon.addFile(Env::currentThemeResPath() + "white_pressed.png", QSize(), QIcon::Selected, QIcon::On); } break; } ui.pushButton_classRoomLeftColorBtn->setIcon(colorSettingIcon); ui.pushButton_classRoomLeftColorBtn->setIconSize(QSize(28,28)); }
4f33bb59a349d5647153997ea9f0f7ad772b3fc6
a8c1d3db2148944e7091b698f88e51185a47e2e9
/src/ofxCasioProjectorControl.h
609c76b8dd373ada1bff45d952349bafe75dcd72
[]
no_license
DHaylock/ofxCasioProjectorControl
b152d7eac5fcb843deac2b7db349c3bd7e20a28b
75af38e5529cc5363247186bea509f3dbf0e9499
refs/heads/master
2021-01-10T17:58:15.585354
2016-01-18T16:54:05
2016-01-18T16:54:05
49,890,612
0
0
null
null
null
null
UTF-8
C++
false
false
3,061
h
ofxCasioProjectorControl.h
//-------------------------------------------------------------- //* Name: ofxCasioProjectorControl.h //* Author: David Haylock, Stewart Morgan //* Creation Date: 15-12-2015 //-------------------------------------------------------------- #include "ofMain.h" #include <stdlib.h> #define TIMEOUT_STEP_DURATION 250000 // In uSeconds #define TIMEOUT_DURATION 1 // In iterations of TIMEOUT_STEP_DURATION, 20 ~5s #define NUM_BYTES 1 #define BAUD 19200 #define POWER_ON "(PWR1)\n" #define POWER_OFF "(PWR0)\n" #define SET_INPUT_RGB_1 "(SRC0)\n" #define SET_INPUT_COMPONENT_1 "(SRC1)\n" #define SET_INPUT_VIDEO "(SRC2)\n" #define SET_INPUT_RGB_2 "(SRC3)\n" #define SET_INPUT_COMPONENT_2 "(SRC4)\n" #define SET_INPUT_AUTO_1 "(SRC6)\n" #define SET_INPUT_HDMI "(SRC7)\n" #define SET_INPUT_NETWORK "(SRC8)\n" #define SET_INPUT_S_VIDEO "(SRC9)\n" #define SET_INPUT_AUTO_2 "(SRC10)\n" #define SET_INPUT_FILE_VIEWER "(SRC11)\n" #define SET_INPUT_USB_DISPLAY "(SRC12)\n" #define SET_INPUT_CASIO_USB "(SRC13)\n" #define SET_BLANK_SCREEN_OFF "(BLK0)\n" #define SET_BLANK_SCREEN_ON "(BLK1)\n" #define SET_COLOR_MODE_1 "(PST1)\n" #define SET_COLOR_MODE_2 "(PST2)\n" #define SET_COLOR_MODE_3 "(PST3)\n" #define SET_COLOR_MODE_4 "(PST4)\n" #define SET_COLOR_MODE_5 "(PST5)\n" #define SET_ASPECT_NORMAL "(ARZ0)\n" #define SET_ASPECT_16_9 "(ARZ1)\n" #define SET_ASPECT_4_3 "(ARZ2)\n" #define SET_ASPECT_LETTERBOX "(ARZ3)\n" #define SET_ASPECT_FULL "(ARZ4)\n" #define SET_ASPECT_TRUE "(ARZ5)\n" #define SET_ASPECT_4_3_FORCED "(ARZ6)\n" #define GET_LAMP_HOURS "(LMP)\n" #define SET_FREEZE_ON "(FRZ1)\n" #define SET_FREEZE_OFF "(FRZ2)\n" #define MODE_FRONT "(POS0)\n" #define MODE_REAR "(POS1)\n" #define MODE_FRONT_CEILING "(POS2)\n" #define MODE_REAR_CEILING "(POS3)\n" #define SET_BLANK_SCREEN_OFF "(BLK0)\n" #define SET_BLANK_SCREEN_ON "(BLK1)\n" #define GET_ERROR_MESSAGE "(STS)\n" //-------------------------------------------------------------- class ofxCasioProjectorControl : public ofSerial { public: void openProjectorConnection(string serialName,int baud = BAUD); void closeConnection(); bool isConnected(); void reconnect(); bool doCommand(const char *command, unsigned int command_length, unsigned char *reply = NULL, unsigned int reply_size = 0); bool resyncProjector(); bool resetProjector(); bool turnProjectorOn(); bool turnProjectorOff(); bool setProjectionMode(int mode); bool setProjectionAspect(int mode); bool setProjectorInput(int mode); string getProjectorStatus(); int getLampHours(); protected: unsigned char returnValue; unsigned char bytesReturned[NUM_BYTES]; string messageBuffer; string message; private: string currentSerialName; int currentBaud; };
963ae7804e946ab1fea47c9f6a8e65c3df61b1c2
ef516abbf3cafc99dec7e12ddd9ee9423a0ccd93
/Synergy/src/Synergy/Font.h
109030b461713a05277e1995df80e6f98a8ce240
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
nmrsmn/synergy
15fb3baf851ab600b7a716c8ee26ee39b2f369a0
7f77c70c131debe66d2e91e00827fd30e736cf81
refs/heads/develop
2021-04-13T06:32:56.229898
2020-05-17T15:08:24
2020-05-17T15:08:24
249,143,774
0
0
MIT
2020-05-22T11:15:13
2020-03-22T08:40:09
C
UTF-8
C++
false
false
1,145
h
Font.h
// Created by Niels Marsman on 03-05-2020. // Copyright © 2020 Niels Marsman. All rights reserved. #ifndef SYNERGY_FONT_H #define SYNERGY_FONT_H #include <unordered_map> #include <glm/glm.hpp> #include <ft2build.h> #include FT_FREETYPE_H #include "Synergy/Core.h" #include "Synergy/Fonts.h" #include "Synergy/Renderer/Texture.h" namespace Synergy { class SYNERGY_API Font { public: struct SYNERGY_API Character { Synergy::Ref<Synergy::Texture> texture; glm::vec2 size; glm::vec2 bearing; uint32_t advance; }; private: static Synergy::Ref<Synergy::Font> Load(const std::string& path, uint32_t size); public: const Synergy::Font::Character GetCharacter(unsigned char character); private: Font(const std::string& path, uint32_t size); Synergy::Font::Character Cache(const char character); private: FT_Face face; std::unordered_map<unsigned char, Synergy::Font::Character> characters; friend class Fonts; }; } #endif
c87d3f95e0f3186b86cc79181da4271d2f186f78
18e4220339538573e4377096e25f624b1aadb68d
/GPS.ino
e27a8c74cb807ce9fc11265c5016f041bb5c004d
[]
no_license
pi3rrot/GPS-EM411
573cdf24268e378507dc7df6a52c5b5a26b817d5
b74ca2084c00861cffa44b088c1e0d76eb4cccd1
refs/heads/master
2021-01-22T17:53:14.784366
2013-01-19T01:16:30
2013-01-19T01:16:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
369
ino
GPS.ino
#include <SoftwareSerial.h> SoftwareSerial GPSinterne = SoftwareSerial(2,3); SoftwareSerial GPSexterne = SoftwareSerial(5,4); void setup() { GPSinterne.begin(4800); // GPSexterne.begin(4800); Serial.begin(9600); } void loop() { if(GPSinterne.available() > 0) { char chaine = GPSinterne.read(); // char someChar = GPSexterne.read(); Serial.print(chaine); } }
572e110c6d16f728ca266724fe0014ac2feec3a5
ef13e028bb85295266b79ca217b7fe9c2886637b
/delete the element by the position.cpp
2436d9599bff46efde554e7fcba653a400332262
[]
no_license
kavipriyaselvakumar/DataStructurs
202eaf7dad5c51fc0e1b352ec54a794b058ca0a7
66133833e0b12bb2a2330a253869c149ec9b1799
refs/heads/main
2023-04-21T23:19:07.727253
2021-05-20T19:17:03
2021-05-20T19:17:03
348,046,060
0
0
null
null
null
null
UTF-8
C++
false
false
977
cpp
delete the element by the position.cpp
#include<iostream> using namespace std; struct node { int data; struct node *next; }*head=NULL; int main() { int n; cout<<"Enter the number of node:"; cin>>n; int count=0; node *temp=new node(); for(int i=0;i<n;i++) { node *newnode =new node(); int ele; cout<<"Enter the element:"; cin>>ele; if(head==NULL) { newnode->data=ele; newnode->next=NULL; head=newnode; count=1; } else{ newnode->data=ele; newnode->next=NULL; count++; temp=head; while(temp->next!=NULL) { temp=temp->next; } temp->next=newnode; } } cout<<"Enter the position to be deleted:"; int position; cin>>position; temp=head; for(int i=0;i<n;i++) { if(position==0) { head=head->next; break; } if(i==position-2) { temp->next=temp->next->next; break; } temp=temp->next; } temp=head; while(temp!=NULL) { cout<<temp->data; temp=temp->next; } }
4b5b7ee4f12a37f27b7f2705f394bfec126784c5
42ab733e143d02091d13424fb4df16379d5bba0d
/third_party/spirv-tools/test/val/val_state_test.cpp
4097a1feb87294c0ad506de5b804c5de1f9d177f
[ "Apache-2.0", "CC0-1.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-generic-cla" ]
permissive
google/filament
11cd37ac68790fcf8b33416b7d8d8870e48181f0
0aa0efe1599798d887fa6e33c412c09e81bea1bf
refs/heads/main
2023-08-29T17:58:22.496956
2023-08-28T17:27:38
2023-08-28T17:27:38
143,455,116
16,631
1,961
Apache-2.0
2023-09-14T16:23:39
2018-08-03T17:26:00
C++
UTF-8
C++
false
false
7,998
cpp
val_state_test.cpp
// Copyright (c) 2015-2016 The Khronos Group Inc. // Copyright (c) 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Unit tests for ValidationState_t. #include <vector> #include "gtest/gtest.h" #include "source/latest_version_spirv_header.h" #include "source/enum_set.h" #include "source/extensions.h" #include "source/spirv_validator_options.h" #include "source/val/construct.h" #include "source/val/function.h" #include "source/val/validate.h" #include "source/val/validation_state.h" namespace spvtools { namespace val { namespace { // This is all we need for these tests. static uint32_t kFakeBinary[] = {0}; // A test with a ValidationState_t member transparently. class ValidationStateTest : public testing::Test { public: ValidationStateTest() : context_(spvContextCreate(SPV_ENV_UNIVERSAL_1_0)), options_(spvValidatorOptionsCreate()), state_(context_, options_, kFakeBinary, 0, 1) {} ~ValidationStateTest() override { spvContextDestroy(context_); spvValidatorOptionsDestroy(options_); } protected: spv_context context_; spv_validator_options options_; ValidationState_t state_; }; // A test of ValidationState_t::HasAnyOfCapabilities(). using ValidationState_HasAnyOfCapabilities = ValidationStateTest; TEST_F(ValidationState_HasAnyOfCapabilities, EmptyMask) { EXPECT_TRUE(state_.HasAnyOfCapabilities({})); state_.RegisterCapability(spv::Capability::Matrix); EXPECT_TRUE(state_.HasAnyOfCapabilities({})); state_.RegisterCapability(spv::Capability::ImageMipmap); EXPECT_TRUE(state_.HasAnyOfCapabilities({})); state_.RegisterCapability(spv::Capability::Pipes); EXPECT_TRUE(state_.HasAnyOfCapabilities({})); state_.RegisterCapability(spv::Capability::StorageImageArrayDynamicIndexing); EXPECT_TRUE(state_.HasAnyOfCapabilities({})); state_.RegisterCapability(spv::Capability::ClipDistance); EXPECT_TRUE(state_.HasAnyOfCapabilities({})); state_.RegisterCapability(spv::Capability::StorageImageWriteWithoutFormat); EXPECT_TRUE(state_.HasAnyOfCapabilities({})); } TEST_F(ValidationState_HasAnyOfCapabilities, SingleCapMask) { EXPECT_FALSE(state_.HasAnyOfCapabilities({spv::Capability::Matrix})); EXPECT_FALSE(state_.HasAnyOfCapabilities({spv::Capability::ImageMipmap})); state_.RegisterCapability(spv::Capability::Matrix); EXPECT_TRUE(state_.HasAnyOfCapabilities({spv::Capability::Matrix})); EXPECT_FALSE(state_.HasAnyOfCapabilities({spv::Capability::ImageMipmap})); state_.RegisterCapability(spv::Capability::ImageMipmap); EXPECT_TRUE(state_.HasAnyOfCapabilities({spv::Capability::Matrix})); EXPECT_TRUE(state_.HasAnyOfCapabilities({spv::Capability::ImageMipmap})); } TEST_F(ValidationState_HasAnyOfCapabilities, MultiCapMask) { const auto set1 = CapabilitySet{spv::Capability::SampledRect, spv::Capability::ImageBuffer}; const auto set2 = CapabilitySet{spv::Capability::StorageImageWriteWithoutFormat, spv::Capability::StorageImageReadWithoutFormat, spv::Capability::GeometryStreams}; EXPECT_FALSE(state_.HasAnyOfCapabilities(set1)); EXPECT_FALSE(state_.HasAnyOfCapabilities(set2)); state_.RegisterCapability(spv::Capability::ImageBuffer); EXPECT_TRUE(state_.HasAnyOfCapabilities(set1)); EXPECT_FALSE(state_.HasAnyOfCapabilities(set2)); } // A test of ValidationState_t::HasAnyOfExtensions(). using ValidationState_HasAnyOfExtensions = ValidationStateTest; TEST_F(ValidationState_HasAnyOfExtensions, EmptyMask) { EXPECT_TRUE(state_.HasAnyOfExtensions({})); state_.RegisterExtension(Extension::kSPV_KHR_shader_ballot); EXPECT_TRUE(state_.HasAnyOfExtensions({})); state_.RegisterExtension(Extension::kSPV_KHR_16bit_storage); EXPECT_TRUE(state_.HasAnyOfExtensions({})); state_.RegisterExtension(Extension::kSPV_NV_viewport_array2); EXPECT_TRUE(state_.HasAnyOfExtensions({})); } TEST_F(ValidationState_HasAnyOfExtensions, SingleCapMask) { EXPECT_FALSE(state_.HasAnyOfExtensions({Extension::kSPV_KHR_shader_ballot})); EXPECT_FALSE(state_.HasAnyOfExtensions({Extension::kSPV_KHR_16bit_storage})); state_.RegisterExtension(Extension::kSPV_KHR_shader_ballot); EXPECT_TRUE(state_.HasAnyOfExtensions({Extension::kSPV_KHR_shader_ballot})); EXPECT_FALSE(state_.HasAnyOfExtensions({Extension::kSPV_KHR_16bit_storage})); state_.RegisterExtension(Extension::kSPV_KHR_16bit_storage); EXPECT_TRUE(state_.HasAnyOfExtensions({Extension::kSPV_KHR_shader_ballot})); EXPECT_TRUE(state_.HasAnyOfExtensions({Extension::kSPV_KHR_16bit_storage})); } TEST_F(ValidationState_HasAnyOfExtensions, MultiCapMask) { const auto set1 = ExtensionSet{Extension::kSPV_KHR_multiview, Extension::kSPV_KHR_16bit_storage}; const auto set2 = ExtensionSet{Extension::kSPV_KHR_shader_draw_parameters, Extension::kSPV_NV_stereo_view_rendering, Extension::kSPV_KHR_shader_ballot}; EXPECT_FALSE(state_.HasAnyOfExtensions(set1)); EXPECT_FALSE(state_.HasAnyOfExtensions(set2)); state_.RegisterExtension(Extension::kSPV_KHR_multiview); EXPECT_TRUE(state_.HasAnyOfExtensions(set1)); EXPECT_FALSE(state_.HasAnyOfExtensions(set2)); } // A test of ValidationState_t::IsOpcodeInCurrentLayoutSection(). using ValidationState_InLayoutState = ValidationStateTest; TEST_F(ValidationState_InLayoutState, Variable) { state_.SetCurrentLayoutSectionForTesting(kLayoutTypes); EXPECT_TRUE(state_.IsOpcodeInCurrentLayoutSection(spv::Op::OpVariable)); state_.SetCurrentLayoutSectionForTesting(kLayoutFunctionDefinitions); EXPECT_TRUE(state_.IsOpcodeInCurrentLayoutSection(spv::Op::OpVariable)); } TEST_F(ValidationState_InLayoutState, ExtInst) { state_.SetCurrentLayoutSectionForTesting(kLayoutTypes); EXPECT_TRUE(state_.IsOpcodeInCurrentLayoutSection(spv::Op::OpExtInst)); state_.SetCurrentLayoutSectionForTesting(kLayoutFunctionDefinitions); EXPECT_TRUE(state_.IsOpcodeInCurrentLayoutSection(spv::Op::OpExtInst)); } TEST_F(ValidationState_InLayoutState, Undef) { state_.SetCurrentLayoutSectionForTesting(kLayoutTypes); EXPECT_TRUE(state_.IsOpcodeInCurrentLayoutSection(spv::Op::OpUndef)); state_.SetCurrentLayoutSectionForTesting(kLayoutFunctionDefinitions); EXPECT_TRUE(state_.IsOpcodeInCurrentLayoutSection(spv::Op::OpUndef)); } TEST_F(ValidationState_InLayoutState, Function) { state_.SetCurrentLayoutSectionForTesting(kLayoutFunctionDeclarations); EXPECT_TRUE(state_.IsOpcodeInCurrentLayoutSection(spv::Op::OpFunction)); state_.SetCurrentLayoutSectionForTesting(kLayoutFunctionDefinitions); EXPECT_TRUE(state_.IsOpcodeInCurrentLayoutSection(spv::Op::OpFunction)); } TEST_F(ValidationState_InLayoutState, FunctionParameter) { state_.SetCurrentLayoutSectionForTesting(kLayoutFunctionDeclarations); EXPECT_TRUE( state_.IsOpcodeInCurrentLayoutSection(spv::Op::OpFunctionParameter)); state_.SetCurrentLayoutSectionForTesting(kLayoutFunctionDefinitions); EXPECT_TRUE( state_.IsOpcodeInCurrentLayoutSection(spv::Op::OpFunctionParameter)); } TEST_F(ValidationState_InLayoutState, FunctionEnd) { state_.SetCurrentLayoutSectionForTesting(kLayoutFunctionDeclarations); EXPECT_TRUE(state_.IsOpcodeInCurrentLayoutSection(spv::Op::OpFunctionEnd)); state_.SetCurrentLayoutSectionForTesting(kLayoutFunctionDefinitions); EXPECT_TRUE(state_.IsOpcodeInCurrentLayoutSection(spv::Op::OpFunctionEnd)); } } // namespace } // namespace val } // namespace spvtools
42cf58c761d9ab03b0e35a912bfedd9d10bcc9a1
4d2067f60368d6e91210536f3dcf967650e8fa70
/is_bst.cpp
6e6481391d954a63050c6f42ac18bc1cc93db565
[]
no_license
Paxing939/Theory-of-algorithms
27be26d34c28261cfa7a4f90b047d53d5c28b44f
11e2b1032012028ff0c97b8ac282adaf04cb02d1
refs/heads/master
2022-12-13T14:16:57.219475
2022-12-06T13:57:19
2022-12-06T13:57:19
249,015,468
0
0
null
null
null
null
UTF-8
C++
false
false
1,098
cpp
is_bst.cpp
#include <iostream> #include <vector> struct Node { int64_t value; int64_t left; int64_t right; }; int main() { freopen("bst.in", "r", stdin); freopen("bst.out", "w", stdout); std::cin.tie(nullptr); std::ios_base::sync_with_stdio(false); int64_t n; std::cin >> n; std::vector<Node> tree(n); std::cin >> tree[0].value; tree[0].right = std::numeric_limits<int>::max(); tree[0].left = std::numeric_limits<int>::min(); tree[0].right += 10; tree[0].left -= 10; for (int64_t i = 1; i < n; ++i) { int64_t m, p; char c; std::cin >> m >> p >> c; p--; if (p == 6) { int df = 0; } if (c == 'L') { if (!(m >= tree[p].left && m < tree[p].value)) { std::cout << "NO"; return 0; } tree[i].left = tree[p].left; tree[i].right = tree[p].value; } else { if (!(m < tree[p].right && m >= tree[p].value)) { std::cout << "NO"; return 0; } tree[i].left = tree[p].value; tree[i].right = tree[p].right; } tree[i].value = m; } std::cout << "YES"; }
6a2efd71d95e9d1ea1b6cf7e796b77ea84e1a92d
718dc8e20a4b1fa265b2d7e96d39dd2038fb3b03
/OGLContext.h
d9d6ffb87527f8a20d0b3e14140eae3236af88b3
[]
no_license
EXL/SensorMonitor
efbccb597371d23b8d673e1a20f25357cca39ed9
66d1e64894721eed56361dbc8b63c18741e95ac4
refs/heads/master
2021-01-10T22:11:41.931963
2017-06-22T19:19:30
2017-06-22T19:19:30
16,229,910
1
0
null
null
null
null
UTF-8
C++
false
false
961
h
OGLContext.h
#ifndef OGLCONTEXT_H #define OGLCONTEXT_H #include <QGLWidget> #include <QVector2D> #include <QVector3D> #include <QTimer> class OGLContext : public QGLWidget { Q_OBJECT QVector<QVector3D> vertices; QVector<QVector2D> texCoords; GLuint textures[4]; GLfloat nScale; GLfloat ratio; GLfloat xRot; GLfloat yRot; GLfloat zRot; QPoint mousePosition; bool qRotate; QTimer *timer; void rotateBy(int xAngle, int yAngle, int zAngle); void makeObject(); private slots: void rotateOneStep(); protected: void initializeGL(); void resizeGL(int nWidth, int nHeight); void paintGL(); void mousePressEvent(QMouseEvent* event); void mouseMoveEvent(QMouseEvent *event); void wheelEvent(QWheelEvent *event); void keyPressEvent(QKeyEvent *event); public: OGLContext(QWidget* parent = 0); ~OGLContext(); }; #endif // OGLCONTEXT_H
b1b6dde306548bdbd328d4159a3edc4612939633
0f378fac224a14161f7e409e5468ec156eece83a
/BlinkMorse.ino
16edc35deca6dd823e06b025670bbe0bc06813cc
[ "MIT" ]
permissive
javleds/arduino-blink-morse
d7460cdbfd147c5c7a934b6ef34bb4b9651d9221
e6909ba82d249c2afc7c9b61050ae8dce72bb1d4
refs/heads/master
2022-11-12T00:47:46.248980
2020-07-05T01:51:54
2020-07-05T01:51:54
277,213,381
0
0
null
null
null
null
UTF-8
C++
false
false
3,028
ino
BlinkMorse.ino
const int DOT = 0; const int LINE = 1; const int OFF = 2; const int UNIT = 333; const int LETTER_SPACE_INTERVAL = 1000; const int END_PHRASE_BEEPS = 5; const int END_PHRASE_DELAY = 50; const int OUTPUT_PIN = 13; const int DICTIONARY[][4] = { {DOT, LINE, OFF, OFF}, // A {LINE, DOT, DOT, DOT}, // B {LINE, DOT, LINE, DOT}, // C {LINE, DOT, DOT, OFF}, // D {DOT, OFF, OFF, OFF}, // E {DOT, DOT, LINE, DOT}, // F {LINE, LINE, DOT, OFF}, // G {DOT, DOT, DOT, DOT}, // H {DOT, DOT, OFF, OFF}, // I {DOT, LINE, LINE, LINE}, // J {LINE, DOT, LINE, OFF}, // K {DOT, LINE, DOT, DOT}, // L {LINE, LINE, OFF, OFF}, // M {LINE, DOT, OFF, OFF}, // N {LINE, LINE, LINE, OFF}, // O {DOT, LINE, LINE, DOT}, // P {LINE, LINE, DOT, LINE}, // Q {DOT, LINE, DOT, OFF}, // R {DOT, DOT, DOT, OFF}, // S {LINE, OFF, OFF, OFF}, // T {DOT, DOT, LINE, OFF}, // U {DOT, DOT, DOT, LINE}, // V {DOT, LINE, LINE, OFF}, // W {LINE, DOT, DOT, LINE}, // X {LINE, DOT, LINE, LINE}, // Y {LINE, LINE, DOT, DOT}, // Z {OFF, OFF, OFF, OFF} // SPACE }; int getSequenceIndex(char letter) { switch(letter) { case 'A': return 0; case 'B': return 1; case 'C': return 2; case 'D': return 3; case 'E': return 4; case 'F': return 5; case 'G': return 6; case 'H': return 7; case 'I': return 8; case 'J': return 9; case 'K': return 10; case 'L': return 11; case 'M': return 12; case 'N': return 13; case 'O': return 14; case 'P': return 15; case 'Q': return 16; case 'R': return 17; case 'S': return 18; case 'T': return 19; case 'U': return 20; case 'V': return 21; case 'W': return 22; case 'X': return 23; case 'Y': return 24; case 'Z': return 25; default: return 26; } } void blinkSequence(int sequenceIndex) { for (int i = 0; i < 4; i++) { if (DICTIONARY[sequenceIndex][i] == DOT) { turnOn(UNIT); digitalWrite(OUTPUT_PIN, LOW); delay(UNIT); continue; } if (DICTIONARY[sequenceIndex][i]== LINE) { turnOn(UNIT * 3); digitalWrite(OUTPUT_PIN, LOW); delay(UNIT); continue; } } } void initPhrase() { int intermitenceTime = END_PHRASE_DELAY; for (int i = 0; i < END_PHRASE_BEEPS; i++) { turnOn(intermitenceTime); digitalWrite(OUTPUT_PIN, LOW); delay(intermitenceTime); } digitalWrite(OUTPUT_PIN, LOW); delay(LETTER_SPACE_INTERVAL); } void letterSeparator() { digitalWrite(OUTPUT_PIN, LOW); delay(LETTER_SPACE_INTERVAL); } void turnOn(int milliseconds) { digitalWrite(OUTPUT_PIN, HIGH); delay(milliseconds); } void setup() { pinMode(OUTPUT_PIN, OUTPUT); } void loop() { initPhrase(); String phrase = "Men, I really love to code!"; int length = phrase.length() + 1; char letters[length]; phrase.toUpperCase(); phrase.toCharArray(letters, length); for (int i = 0; i < phrase.length(); i++) { blinkSequence( getSequenceIndex(letters[i]) ); letterSeparator(); } }
72b956a30e0a360228e9add716e4ae7cb048925c
7ccdcc27e50526d568dfe2918aabfb172ef41b62
/Reorder_List.cpp
eb7e4539298c048e075b2f0b1d3aacd1c375a803
[]
no_license
albin3/leetcode
71c30df4a7a778b2ce10619a244b7bc2a5122f33
c458f80ec4a493f3b104883f6fa54321386f58a9
refs/heads/master
2021-01-22T15:22:32.827552
2015-08-12T10:08:59
2015-08-12T10:08:59
26,163,258
1
0
null
null
null
null
UTF-8
C++
false
false
1,005
cpp
Reorder_List.cpp
#include <iostream> #include <vector> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: void reorderList(ListNode *head) { if (head==NULL) return; vector<ListNode*> v; while(head) { v.push_back(head); head=head->next; } ListNode* p = new ListNode(0); head = p; int i=0,j=v.size()-1; while (i!=j) { p->next=v[i++]; p=p->next; if (i==j) break; p->next=v[j--]; p=p->next; } p->next = v[i]; p->next->next = NULL; p = head; head = p->next; delete p; } }; int main() { ListNode *head = new ListNode(1); head->next = new ListNode(2); head->next->next = new ListNode(3); head->next->next->next = new ListNode(4); (new Solution())->reorderList(head); int i=0; while(head!=NULL) { cout<<"hello: "<<head->val<<endl; head=head->next; i++; } }
f76fc2344f222a918b1be504dddec7baedc5604b
f324e18d380245e46fa897e54234327028983202
/Server/Utils.h
2069f9a4d647aea45c6c0877865c6d10c3a3e620
[]
no_license
StevenHD/Linkaging
ff1679d0061d891b885bddd967ab3328669d629c
725f85f06e86b7d5f1c2285823ab10e670548eee
refs/heads/master
2023-06-18T16:37:16.124398
2021-07-22T14:19:00
2021-07-22T14:19:00
366,744,254
1
0
null
null
null
null
UTF-8
C++
false
false
390
h
Utils.h
// // Created by hlhd on 2021/4/29. // #ifndef MODERNCPP_UTILS_H #define MODERNCPP_UTILS_H #define LSTNQUE 1024 // 监听队列长度,操作系统默认值为SOMAXCONN #include "../all.h" namespace Linkaging { namespace Utils { int createListenFd(int port); // 创建监听描述符 int setNonBlocking(int fd); // 设置非阻塞模式 }; } #endif //MODERNCPP_UTILS_H
c2d8870feeacd41808602cd9fe5b8586aa66ad0c
270937d32c2bc8e33622d96c045b43b8a23bc086
/ion/base/datacontainer.h
d8a6434de1e34f49ffdf5cb90fcacf729fd290f6
[ "Apache-2.0" ]
permissive
google/ion
32491fc26a0a2a5fd602e4008296ccba5017d689
514ce797458d02e7cd3a1b2d0b5c7ff8ccb5f5d1
refs/heads/master
2023-09-04T18:10:40.343013
2022-06-09T07:56:18
2022-06-09T07:56:18
50,387,855
1,651
132
Apache-2.0
2018-05-12T02:16:47
2016-01-25T23:13:46
C++
UTF-8
C++
false
false
10,014
h
datacontainer.h
/** Copyright 2017 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef ION_BASE_DATACONTAINER_H_ #define ION_BASE_DATACONTAINER_H_ #include <cstring> #include <functional> #if ION_DEBUG #include <set> #endif #include "base/integral_types.h" #include "base/macros.h" #include "ion/base/logging.h" #include "ion/base/notifier.h" #include "ion/port/nullptr.h" // For kNullFunction. namespace ion { namespace base { // Convenience typedefs for shared pointers to a DataContainer. class DataContainer; using DataContainerPtr = base::SharedPtr<DataContainer>; typedef base::WeakReferentPtr<DataContainer> DataContainerWeakPtr; // The DataContainer class encapsulates arbitrary user data passed to Ion. It // can only be created using one of the static Create() functions, templatized // on a type T. The data in the DataContainer is created and destroyed depending // on which Create() function is used. The three possibilities are: // // Create(T* data, Deleter data_deleter, bool is_wipeable, // const AllocatorPtr& container_allocator) // The internal data pointer is set to data and the DataContainer is allocated // using the passed Allocator. If data_deleter is NULL, then the caller is // responsible for deleting data, and is_wipeable is ignored. If data_deleter // is non-NULL, then the data will be deleted by calling data_deleter on the // pointer when WipeData() is called if is_wipeable is set; otherwise // data_deleter is called on the pointer only when the DataContainer is // destroyed. The deleter can be any std::function that properly cleans up // data; ArrayDeleter, PointerDeleter, and AllocatorDeleter static functions // are provided for convenience. // // CreateAndCopy(const T* data, size_t count, bool is_wipeable, // const AllocatorPtr& container_and_data_allocator) // The DataContainer and its internal data pointer are allocated from the // passed Allocator and count elements are copied from data if data is // non-NULL. The data will be deleted when WipeData() is called if // is_wipeable is set; otherwise it is deleted only when the DataContainer is // destroyed. The deleter function is always AllocatorDeleter (see below). // // CreateOverAllocated(size_t count, T* data, // const AllocatorPtr& container_allocator) // Over-allocates the DataContainer by count elements of type T (i.e., this is // essentially malloc(sizeof(DataContainer) + sizeof(T) * count)) and copies // data into the DataContainer's data if data is non-NULL. The memory is // allocated using the passed Allocator. The new data is destroyed only when // the DataContainer is destroyed. class ION_API DataContainer : public base::Notifier { public: // Generic delete function. typedef std::function<void(void* data_to_delete)> Deleter; // Generic deleters that perform the most common deletion operations. These // deleters may all be passed to Create() (see above). template <typename T> static void ArrayDeleter(void* data_to_delete) { T* data = reinterpret_cast<T*>(data_to_delete); delete [] data; } template <typename T> static void PointerDeleter(void* data_to_delete) { T* data = reinterpret_cast<T*>(data_to_delete); delete data; } // A deleter for data allocated by an Allocator. The AllocatorPtr is passed by // value so that a std::bind that invokes the deleter will hold a strong // reference to it. static void AllocatorDeleter(const AllocatorPtr& allocator, void* data_to_delete) { DCHECK(allocator.Get()); allocator->DeallocateMemory(data_to_delete); } // Returns the is_wipeable setting passed to the constructor. bool IsWipeable() const { return is_wipeable_; } // Returns a const data pointer. template <typename T> const T* GetData() const { return reinterpret_cast<const T*>(GetDataPtr()); } // Default GetData() returns a const void pointer. const void* GetData() const { return reinterpret_cast<const void*>(GetDataPtr()); } // Returns a non-const data pointer. template <typename T> T* GetMutableData() const { T* data = reinterpret_cast<T*>(GetDataPtr()); if (data) this->Notify(); else LOG(ERROR) << "GetMutableData() called on NULL (or wiped) DataContainer. " "The contents of the original buffer will not be returned " "and any data in GPU memory will likely be cleared. This " "is probably not what you want."; return data; } // See class comment for documentation. template <typename T> static DataContainerPtr Create( T* data, const Deleter& data_deleter, bool is_wipeable, const AllocatorPtr& container_allocator) { if (data_deleter && !AddOrRemoveDataFromCheck(data, true)) return DataContainerPtr(nullptr); DataContainer* container = Allocate(0, data_deleter, is_wipeable, container_allocator); container->data_ = data; return DataContainerPtr(container); } // See class comment for documentation. template <typename T> static DataContainerPtr CreateAndCopy( const T* data, size_t count, bool is_wipeable, const AllocatorPtr& container_and_data_allocator) { return CreateAndCopy(data, sizeof(T), count, is_wipeable, container_and_data_allocator); } // Overload of CreateAndCopy for use when the size of the // datatype of the pointer does not correspond to the size of each element. template <typename T> static DataContainerPtr CreateAndCopy( const T* data, size_t element_size, size_t count, bool is_wipeable, const AllocatorPtr& container_and_data_allocator) { DataContainer* container = Allocate(0, kNullFunction, is_wipeable, container_and_data_allocator); // If the data is wipeable then the allocation should be short term, // otherwise it should have the same lifetime as this. if (is_wipeable) { container->data_allocator_ = container->GetAllocator().Get() ? container->GetAllocator()->GetAllocatorForLifetime(kShortTerm) : AllocationManager::GetDefaultAllocatorForLifetime(kShortTerm); } else { container->data_allocator_ = container->GetAllocator(); } container->deleter_ = std::bind(DataContainer::AllocatorDeleter, container->data_allocator_, std::placeholders::_1); container->data_ = container->data_allocator_->AllocateMemory(element_size * count); // Copy the input data to the container. if (data) memcpy(container->data_, data, element_size * count); return DataContainerPtr(container); } // See class comment for documentation. template <typename T> static DataContainerPtr CreateOverAllocated( size_t count, const T* data, const AllocatorPtr& container_allocator) { // Allocate an additional 16 bytes to ensure that the data pointer can be // 16-byte aligned. DataContainer* container = Allocate(sizeof(T) * count + 16, kNullFunction, false, container_allocator); uint8* ptr = reinterpret_cast<uint8*>(container) + sizeof(DataContainer); // Offset the pointer by the right amount to make it 16-byte aligned. container->data_ = ptr + 16 - (reinterpret_cast<size_t>(ptr) % 16); // Copy the input data to the container. if (data) memcpy(container->data_, data, sizeof(T) * count); return DataContainerPtr(container); } // Informs the DataContainer that the data is no longer needed and can be // deleted. It does this only if is_wipeable=true was passed to the // constructor and there is a non-NULL deleter; otherwise, it has no effect. void WipeData(); protected: // The destructor is protected because all base::Referent classes must have // protected or private destructors. ~DataContainer() override; // The constructor is protected because all allocation of DataContainers // should be through the Create() functions. DataContainer(const Deleter& deleter, bool is_wipeable); private: // Allocates space for a DataContainer with extra_bytes, and initializes // the DataContainer with deleter and is_wipeable (see constructor). static DataContainer* Allocate(size_t extra_bytes, const Deleter& deleter, bool is_wipeable, const AllocatorPtr& allocator); // In debug mode, adds or removes data to or from a set of client-passed // pointers that are used by DataContainers. An error message is printed if // if the same pointer is passed to Create() before destroying the // DataContainer that already contains the pointer. static bool AddOrRemoveDataFromCheck(void* data, bool is_add); // Actually delete data. virtual void InternalWipeData(); // Returns the data pointer of this instance. virtual void* GetDataPtr() const { return data_; } // The actual data; void* data_; // Whether the data should be destroyed when WipeData() is called and there // is a deleter available. bool is_wipeable_; // Function to use to destroy data_. NULL if the DataContainer does not own // the pointer. Deleter deleter_; // The allocator used to allocate data when CreateAndCopy() is used. base::AllocatorPtr data_allocator_; DISALLOW_IMPLICIT_CONSTRUCTORS(DataContainer); }; } // namespace base } // namespace ion #endif // ION_BASE_DATACONTAINER_H_
cd99d9d3ea619d608705a3b8c3d1effd602dfb80
19a16e16c60401e468b3678975a7baad1201deee
/TrainingManager/mainwindow.h
b9ede1b9fa61fcb765eaba87a89baab5903b6806
[]
no_license
jmbalmaceda/orpocopo2
7a7a14c0a759301b37587a11be9cba4da770d115
084d079e8b0a1ed129b6e55e3888de35648aeb9e
refs/heads/master
2021-01-19T22:47:39.455260
2017-11-29T00:33:09
2017-11-29T00:33:09
88,871,506
0
0
null
null
null
null
UTF-8
C++
false
false
685
h
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <fnuevoentrenamiento.h> #include <fmodificarentrenamiento.h> #include "data.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { public: Data datos; explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void on_actionSalir_triggered(); void on_actionAbrir_video_triggered(); void on_nuevoEntrenamiento_clicked(); void on_modificarEntrenamiento_clicked(); private: Q_OBJECT Ui::MainWindow *ui; FnuevoEntrenamiento* fNuevoEntrenamiento; FModificarEntrenamiento* fModificarEntrenamiento; }; #endif // MAINWINDOW_H
dd51c483ca66f2ad9d5efe5e2d9d911a2e1dc356
260e13adb6fd9e7c19c0da64d2298af2d5cd1d5b
/ch29/Q29_2_1/Q29_2_1/Ex29_2_1_Answer.cpp
7179a3c35809fdc1c3f3024aebf948ace9594405
[]
no_license
neighborpil/CExampleProjects
f6104338255e962518126505df86ef686bde7671
fb7bc8969cf7a3059b3eb6425d58e26bf89079be
refs/heads/master
2021-01-13T09:51:40.225628
2017-05-16T15:27:36
2017-05-16T15:27:36
72,652,801
0
0
null
2017-05-16T15:27:37
2016-11-02T15:21:05
C
UHC
C++
false
false
733
cpp
Ex29_2_1_Answer.cpp
#include <stdio.h> #include <string.h> char* AddStringOne(char des[], char src[], int desLen); int main(void) { char str1[20] = "Your name is "; char str2[20]; char *ret; while (1) { printf("이름을 입력하세요 : "); gets_s(str2, sizeof(str2)); //20글자 이상이면 애러 ret = AddStringOne(str1, str2, sizeof(str1) / sizeof(char)); if (ret != NULL) break; else puts("너무 길다 다시"); } puts(str1); return 0; } char* AddStringOne(char dest[], char src[], int desLen) { int dStrLen = strlen(dest); int sStrLen = strlen(src); int maxAddLen = desLen - dStrLen; if (maxAddLen > sStrLen) //덧붙임 가능하다면 { strcat_s(dest, 20, src); return src; } else return NULL; }
a07fac390dda93880f76fe5e67111e71f6955269
085b0b660560d64465b0f25cc9678aed1d5799f9
/plugins/animate/particle.cpp
613812afb4bb5a81474e29b724a965ebed26cdc5
[ "MIT" ]
permissive
ddevault/wayfire
3eafa63d6955cbe31123eb99c9cba02fa45ae88c
007452f6ccc07ceca51879187bba142431832382
refs/heads/master
2020-03-15T13:55:01.974924
2018-03-27T06:07:37
2018-03-27T19:11:18
132,178,245
4
0
null
null
null
null
UTF-8
C++
false
false
9,537
cpp
particle.cpp
#include "particle.hpp" #include <opengl.hpp> #include <config.h> #include <debug.hpp> #include <GLES3/gl32.h> #include <GLES3/gl3ext.h> #include <EGL/egl.h> #include <thread> glm::vec4 operator * (glm::vec4 v, float x) { v[0] *= x; v[1] *= x; v[2] *= x; v[3] *= x; return v; } glm::vec4 operator / (glm::vec4 v, float x) { v[0] /= x; v[1] /= x; v[2] /= x; v[3] /= x; return v; } template<class T> T *get_shader_storage_buffer(GLuint bufID, size_t arrSize) { glBindBuffer(GL_SHADER_STORAGE_BUFFER, bufID); glBufferData(GL_SHADER_STORAGE_BUFFER, arrSize, NULL, GL_STATIC_DRAW); GLint mask = GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT; return (T*) glMapBufferRange(GL_SHADER_STORAGE_BUFFER, 0, arrSize, mask); } /* Implementation of ParticleSystem */ void wf_particle_system::load_rendering_program() { renderProg = glCreateProgram(); GLuint vss, fss; std::string shaderSrcPath = INSTALL_PREFIX"/share/wayfire/animate/shaders"; vss = OpenGL::load_shader(std::string(shaderSrcPath) .append("/vertex.glsl").c_str(), GL_VERTEX_SHADER); fss = OpenGL::load_shader(std::string(shaderSrcPath) .append("/frag.glsl").c_str(), GL_FRAGMENT_SHADER); GL_CALL(glAttachShader(renderProg, vss)); GL_CALL(glAttachShader (renderProg, fss)); GL_CALL(glLinkProgram (renderProg)); GL_CALL(glUseProgram(renderProg)); GL_CALL(glUniform1f(4, std::sqrt(2.0) * particleSize)); } void wf_particle_system::load_compute_program() { std::string shaderSrcPath = INSTALL_PREFIX"/share/wayfire/animate/shaders"; computeProg = GL_CALL(glCreateProgram()); GLuint css = OpenGL::load_shader(std::string(shaderSrcPath) .append("/compute.glsl").c_str(), GL_COMPUTE_SHADER); GL_CALL(glAttachShader(computeProg, css)); GL_CALL(glLinkProgram(computeProg)); GL_CALL(glUseProgram(computeProg)); GL_CALL(glUniform1i(1, particleLife)); } void wf_particle_system::load_gles_programs() { load_rendering_program(); load_compute_program(); } void wf_particle_system::create_buffers() { GL_CALL(glGenBuffers(1, &base_mesh)); GL_CALL(glGenBuffers(1, &particleSSbo)); GL_CALL(glGenBuffers(1, &lifeInfoSSbo)); } void wf_particle_system::default_particle_initer(particle_t &p) { p.life = particleLife + 1; p.x = p.y = -2; p.dx = float(std::rand() % 1001 - 500) / (500 * particleLife); p.dy = float(std::rand() % 1001 - 500) / (500 * particleLife); p.r = p.g = p.b = p.a = 0; } void wf_particle_system::thread_worker_init_particles(particle_t *p, size_t start, size_t end) { for(size_t i = start; i < end; ++i) default_particle_initer(p[i]); } void wf_particle_system::init_particle_buffer() { particleBufSz = maxParticles * sizeof(particle_t); particle_t *p = get_shader_storage_buffer<particle_t>(particleSSbo, particleBufSz); using namespace std::placeholders; auto threadFunction = std::bind(std::mem_fn(&wf_particle_system::thread_worker_init_particles), this, _1, _2, _3); size_t sz = std::thread::hardware_concurrency(); int interval = maxParticles / sz; if(maxParticles % sz != 0) ++interval; std::vector<std::thread> threads; threads.resize(sz); for(size_t i = 0; i < sz; ++i) { auto start = i * interval; auto end = std::min((i + 1) * interval, maxParticles); threads[i] = std::thread(threadFunction, p, start, end); } for(size_t i = 0; i < sz; ++i) threads[i].join(); GL_CALL(glUnmapBuffer(GL_SHADER_STORAGE_BUFFER)); } void wf_particle_system::init_life_info_buffer() { lifeBufSz = sizeof(int) * maxParticles; int *lives = get_shader_storage_buffer<int>(lifeInfoSSbo, lifeBufSz); for(size_t i = 0; i < maxParticles; ++i) lives[i] = 0; GL_CALL(glUnmapBuffer(GL_SHADER_STORAGE_BUFFER)); GL_CALL(memoryBarrierProc(GL_ALL_BARRIER_BITS)); } void wf_particle_system::gen_base_mesh() { /* scale base mesh */ for(size_t i = 0; i < sizeof(vertices) / sizeof(float); i++) vertices[i] *= particleSize; } void wf_particle_system::upload_base_mesh() { GL_CALL(glUseProgram(renderProg)); GL_CALL(glGenVertexArrays(1, &vao)); GL_CALL(glBindVertexArray(vao)); /* upload static base mesh */ GL_CALL(glEnableVertexAttribArray(0)); GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, base_mesh)); GL_CALL(glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW)); GL_CALL(glVertexAttribPointer (0, 2, GL_FLOAT, GL_FALSE, 0, 0)); GL_CALL(glDisableVertexAttribArray(0)); GL_CALL(glBindVertexArray(0)); GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, 0)); GL_CALL(glUseProgram(0)); } void wf_particle_system::init_gles_part() { memoryBarrierProc = (PFNGLMEMORYBARRIERPROC) eglGetProcAddress("glMemoryBarrier"); dispatchComputeProc = (PFNGLDISPATCHCOMPUTEPROC) eglGetProcAddress("glDispatchCompute"); if (!memoryBarrierProc || !dispatchComputeProc) { errio << "missing compute shader functionality, can't use fire effect!" << std::endl; return; } load_gles_programs(); create_buffers(); init_particle_buffer(); init_life_info_buffer(); gen_base_mesh(); upload_base_mesh(); } void wf_particle_system::set_particle_color(glm::vec4 scol, glm::vec4 ecol) { GL_CALL(glUseProgram(computeProg)); GL_CALL(glUniform4fv(2, 1, &scol[0])); GL_CALL(glUniform4fv(3, 1, &ecol[0])); auto tmp = (ecol - scol) / float(particleLife); GL_CALL(glUniform4fv(4, 1, &tmp[0])); } wf_particle_system::wf_particle_system() {} wf_particle_system::wf_particle_system(float size, size_t _maxp, size_t _pspawn, size_t _plife, size_t _respInterval) { particleSize = size; maxParticles = _maxp; partSpawn = _pspawn; particleLife = _plife; respawnInterval = _respInterval; init_gles_part(); set_particle_color(glm::vec4(0, 0, 1, 1), glm::vec4(1, 0, 0, 1)); } wf_particle_system::~wf_particle_system() { GL_CALL(glDeleteBuffers(1, &particleSSbo)); GL_CALL(glDeleteBuffers(1, &lifeInfoSSbo)); GL_CALL(glDeleteBuffers(1, &base_mesh)); GL_CALL(glDeleteVertexArrays(1, &vao)); GL_CALL(glDeleteProgram(renderProg)); GL_CALL(glDeleteProgram(computeProg)); } void wf_particle_system::pause () {spawnNew = false;} void wf_particle_system::resume() {spawnNew = true; } void wf_particle_system::simulate() { GL_CALL(glUseProgram(computeProg)); if(currentIteration++ % respawnInterval == 0 && spawnNew) { GL_CALL(glUseProgram(computeProg)); GL_CALL(glBindBuffer(GL_SHADER_STORAGE_BUFFER, lifeInfoSSbo)); auto lives = (int*) GL_CALL(glMapBufferRange(GL_SHADER_STORAGE_BUFFER, 0, sizeof(GLint) * maxParticles, GL_MAP_WRITE_BIT | GL_MAP_READ_BIT)); size_t sp_num = partSpawn, i = 0; while(i < maxParticles && sp_num > 0) { if(lives[i] == 0) { lives[i] = 1; --sp_num; } ++i; } GL_CALL(glUnmapBuffer(GL_SHADER_STORAGE_BUFFER)); GL_CALL(glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0)); } GL_CALL(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, particleSSbo)); GL_CALL(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, lifeInfoSSbo)); GL_CALL(dispatchComputeProc(WORKGROUP_COUNT, 1, 1)); GL_CALL(memoryBarrierProc(GL_ALL_BARRIER_BITS)); GL_CALL(glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0)); GL_CALL(glUseProgram(0)); } /* TODO: use glDrawElementsInstanced instead of glDrawArraysInstanced */ void wf_particle_system::render() { GL_CALL(glUseProgram(renderProg)); GL_CALL(glEnable(GL_BLEND)); GL_CALL(glBlendFunc(GL_SRC_ALPHA, GL_ONE)); GL_CALL(glBindVertexArray(vao)); /* prepare vertex attribs */ GL_CALL(glEnableVertexAttribArray(0)); GL_CALL(glBindBuffer (GL_ARRAY_BUFFER, base_mesh)); GL_CALL(glVertexAttribPointer (0, 2, GL_FLOAT, GL_FALSE, 0, 0)); GL_CALL(glEnableVertexAttribArray(1)); GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, particleSSbo)); GL_CALL(glVertexAttribPointer (1, 2, GL_FLOAT, GL_FALSE, sizeof(particle_t), 0)); GL_CALL(glEnableVertexAttribArray(2)); GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, particleSSbo)); GL_CALL(glVertexAttribPointer (2, 4, GL_FLOAT, GL_FALSE, sizeof(particle_t), (void*) (4 * sizeof(float)))); GL_CALL(glVertexAttribDivisor(0, 0)); GL_CALL(glVertexAttribDivisor(1, 1)); GL_CALL(glVertexAttribDivisor(2, 1)); /* draw particles */ GL_CALL(glDrawArraysInstanced(GL_TRIANGLES, 0, 3, maxParticles)); GL_CALL(glDisableVertexAttribArray(0)); GL_CALL(glDisableVertexAttribArray(1)); GL_CALL(glDisableVertexAttribArray(2)); GL_CALL(glBindVertexArray(0)); GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, 0)); GL_CALL(glUseProgram(0)); }
fe80e1f63b4f4104dcf9e2c96e852cfc00f6accf
a738fab3d35dbc7ae90b7ca24ff7411ac12a76d9
/Security and criptography/Tema2_SC/Tema2_SC/Debug/Generated Files/winrt/impl/Windows.ApplicationModel.Contacts.DataProvider.1.h
ae928d892325a9d40f5f48bf63221c0c26d7c6ab
[]
no_license
TheSeeven/personal-projects
66c309233dfdf1d9986846f5bec5ededd57cf119
0d103b9647d2b1c650b0f0d7a63cc64786ddac23
refs/heads/main
2023-06-10T19:12:06.490243
2021-07-01T08:34:01
2021-07-01T08:34:01
301,747,006
0
0
null
null
null
null
UTF-8
C++
false
false
10,670
h
Windows.ApplicationModel.Contacts.DataProvider.1.h
// WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.210403.2 #ifndef WINRT_Windows_ApplicationModel_Contacts_DataProvider_1_H #define WINRT_Windows_ApplicationModel_Contacts_DataProvider_1_H #include "winrt/impl/Windows.ApplicationModel.Contacts.DataProvider.0.h" WINRT_EXPORT namespace winrt::Windows::ApplicationModel::Contacts::DataProvider { struct __declspec(empty_bases) IContactDataProviderConnection : winrt::Windows::Foundation::IInspectable, impl::consume_t<IContactDataProviderConnection> { IContactDataProviderConnection(std::nullptr_t = nullptr) noexcept {} IContactDataProviderConnection(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IContactDataProviderConnection(IContactDataProviderConnection const&) noexcept = default; IContactDataProviderConnection(IContactDataProviderConnection&&) noexcept = default; IContactDataProviderConnection& operator=(IContactDataProviderConnection const&) & noexcept = default; IContactDataProviderConnection& operator=(IContactDataProviderConnection&&) & noexcept = default; }; struct __declspec(empty_bases) IContactDataProviderConnection2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IContactDataProviderConnection2> { IContactDataProviderConnection2(std::nullptr_t = nullptr) noexcept {} IContactDataProviderConnection2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IContactDataProviderConnection2(IContactDataProviderConnection2 const&) noexcept = default; IContactDataProviderConnection2(IContactDataProviderConnection2&&) noexcept = default; IContactDataProviderConnection2& operator=(IContactDataProviderConnection2 const&) & noexcept = default; IContactDataProviderConnection2& operator=(IContactDataProviderConnection2&&) & noexcept = default; }; struct __declspec(empty_bases) IContactDataProviderTriggerDetails : winrt::Windows::Foundation::IInspectable, impl::consume_t<IContactDataProviderTriggerDetails> { IContactDataProviderTriggerDetails(std::nullptr_t = nullptr) noexcept {} IContactDataProviderTriggerDetails(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IContactDataProviderTriggerDetails(IContactDataProviderTriggerDetails const&) noexcept = default; IContactDataProviderTriggerDetails(IContactDataProviderTriggerDetails&&) noexcept = default; IContactDataProviderTriggerDetails& operator=(IContactDataProviderTriggerDetails const&) & noexcept = default; IContactDataProviderTriggerDetails& operator=(IContactDataProviderTriggerDetails&&) & noexcept = default; }; struct __declspec(empty_bases) IContactListCreateOrUpdateContactRequest : winrt::Windows::Foundation::IInspectable, impl::consume_t<IContactListCreateOrUpdateContactRequest> { IContactListCreateOrUpdateContactRequest(std::nullptr_t = nullptr) noexcept {} IContactListCreateOrUpdateContactRequest(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IContactListCreateOrUpdateContactRequest(IContactListCreateOrUpdateContactRequest const&) noexcept = default; IContactListCreateOrUpdateContactRequest(IContactListCreateOrUpdateContactRequest&&) noexcept = default; IContactListCreateOrUpdateContactRequest& operator=(IContactListCreateOrUpdateContactRequest const&) & noexcept = default; IContactListCreateOrUpdateContactRequest& operator=(IContactListCreateOrUpdateContactRequest&&) & noexcept = default; }; struct __declspec(empty_bases) IContactListCreateOrUpdateContactRequestEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<IContactListCreateOrUpdateContactRequestEventArgs> { IContactListCreateOrUpdateContactRequestEventArgs(std::nullptr_t = nullptr) noexcept {} IContactListCreateOrUpdateContactRequestEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IContactListCreateOrUpdateContactRequestEventArgs(IContactListCreateOrUpdateContactRequestEventArgs const&) noexcept = default; IContactListCreateOrUpdateContactRequestEventArgs(IContactListCreateOrUpdateContactRequestEventArgs&&) noexcept = default; IContactListCreateOrUpdateContactRequestEventArgs& operator=(IContactListCreateOrUpdateContactRequestEventArgs const&) & noexcept = default; IContactListCreateOrUpdateContactRequestEventArgs& operator=(IContactListCreateOrUpdateContactRequestEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) IContactListDeleteContactRequest : winrt::Windows::Foundation::IInspectable, impl::consume_t<IContactListDeleteContactRequest> { IContactListDeleteContactRequest(std::nullptr_t = nullptr) noexcept {} IContactListDeleteContactRequest(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IContactListDeleteContactRequest(IContactListDeleteContactRequest const&) noexcept = default; IContactListDeleteContactRequest(IContactListDeleteContactRequest&&) noexcept = default; IContactListDeleteContactRequest& operator=(IContactListDeleteContactRequest const&) & noexcept = default; IContactListDeleteContactRequest& operator=(IContactListDeleteContactRequest&&) & noexcept = default; }; struct __declspec(empty_bases) IContactListDeleteContactRequestEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<IContactListDeleteContactRequestEventArgs> { IContactListDeleteContactRequestEventArgs(std::nullptr_t = nullptr) noexcept {} IContactListDeleteContactRequestEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IContactListDeleteContactRequestEventArgs(IContactListDeleteContactRequestEventArgs const&) noexcept = default; IContactListDeleteContactRequestEventArgs(IContactListDeleteContactRequestEventArgs&&) noexcept = default; IContactListDeleteContactRequestEventArgs& operator=(IContactListDeleteContactRequestEventArgs const&) & noexcept = default; IContactListDeleteContactRequestEventArgs& operator=(IContactListDeleteContactRequestEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) IContactListServerSearchReadBatchRequest : winrt::Windows::Foundation::IInspectable, impl::consume_t<IContactListServerSearchReadBatchRequest> { IContactListServerSearchReadBatchRequest(std::nullptr_t = nullptr) noexcept {} IContactListServerSearchReadBatchRequest(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IContactListServerSearchReadBatchRequest(IContactListServerSearchReadBatchRequest const&) noexcept = default; IContactListServerSearchReadBatchRequest(IContactListServerSearchReadBatchRequest&&) noexcept = default; IContactListServerSearchReadBatchRequest& operator=(IContactListServerSearchReadBatchRequest const&) & noexcept = default; IContactListServerSearchReadBatchRequest& operator=(IContactListServerSearchReadBatchRequest&&) & noexcept = default; }; struct __declspec(empty_bases) IContactListServerSearchReadBatchRequestEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<IContactListServerSearchReadBatchRequestEventArgs> { IContactListServerSearchReadBatchRequestEventArgs(std::nullptr_t = nullptr) noexcept {} IContactListServerSearchReadBatchRequestEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IContactListServerSearchReadBatchRequestEventArgs(IContactListServerSearchReadBatchRequestEventArgs const&) noexcept = default; IContactListServerSearchReadBatchRequestEventArgs(IContactListServerSearchReadBatchRequestEventArgs&&) noexcept = default; IContactListServerSearchReadBatchRequestEventArgs& operator=(IContactListServerSearchReadBatchRequestEventArgs const&) & noexcept = default; IContactListServerSearchReadBatchRequestEventArgs& operator=(IContactListServerSearchReadBatchRequestEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) IContactListSyncManagerSyncRequest : winrt::Windows::Foundation::IInspectable, impl::consume_t<IContactListSyncManagerSyncRequest> { IContactListSyncManagerSyncRequest(std::nullptr_t = nullptr) noexcept {} IContactListSyncManagerSyncRequest(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IContactListSyncManagerSyncRequest(IContactListSyncManagerSyncRequest const&) noexcept = default; IContactListSyncManagerSyncRequest(IContactListSyncManagerSyncRequest&&) noexcept = default; IContactListSyncManagerSyncRequest& operator=(IContactListSyncManagerSyncRequest const&) & noexcept = default; IContactListSyncManagerSyncRequest& operator=(IContactListSyncManagerSyncRequest&&) & noexcept = default; }; struct __declspec(empty_bases) IContactListSyncManagerSyncRequestEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<IContactListSyncManagerSyncRequestEventArgs> { IContactListSyncManagerSyncRequestEventArgs(std::nullptr_t = nullptr) noexcept {} IContactListSyncManagerSyncRequestEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IContactListSyncManagerSyncRequestEventArgs(IContactListSyncManagerSyncRequestEventArgs const&) noexcept = default; IContactListSyncManagerSyncRequestEventArgs(IContactListSyncManagerSyncRequestEventArgs&&) noexcept = default; IContactListSyncManagerSyncRequestEventArgs& operator=(IContactListSyncManagerSyncRequestEventArgs const&) & noexcept = default; IContactListSyncManagerSyncRequestEventArgs& operator=(IContactListSyncManagerSyncRequestEventArgs&&) & noexcept = default; }; } #endif
3f89c49bcaca844fd888cc377c55b1d281db6af6
0795b9eb913c8322238c2892206532218f5b13d2
/SLIC/SLIC.h
bd43cb91e11bb4e2572f130aa71293bf2432115a
[]
no_license
AlexsaseXie/SLIC_superpixel
d4ab6e9c78a634758e63e94584807230add2713c
989bfc28b69048e0280f6aedaf743e47908f6651
refs/heads/master
2020-04-08T02:41:29.629333
2018-11-24T14:42:35
2018-11-24T14:42:35
158,944,944
0
0
null
null
null
null
UTF-8
C++
false
false
361
h
SLIC.h
#pragma once #include <QtWidgets/QWidget> #include "ui_SLIC.h" #include "SLIC_function.h" class SLIC : public QWidget { Q_OBJECT public: SLIC(QWidget *parent = Q_NULLPTR); SLIC_Function f = SLIC_Function("lena512color.bmp", 1000, 30); private: Ui::SLICClass ui; public slots: void choose_input_image(); void choose_output_path(); void do_slic(); };
7f2a40562aeb4885429901d1f3c4a6729f765ff0
e7ea1d9916ded43eda9b96bd06210365f749d3f1
/LeetCode/Valid Mountain Array.cpp
3a62b77841d57a05fb6f9cd153906c53b8df99a5
[]
no_license
chhipanikhil9/CppCompetitiveRepository
8432808336c5e18c38ae5975cadcaf925578b9a2
ba06529fc7282bfe491d4a75480ba28c490cc37b
refs/heads/main
2023-07-21T14:26:22.912033
2023-07-13T03:26:54
2023-07-13T03:26:54
333,729,610
0
0
null
2021-04-17T13:41:19
2021-01-28T10:53:30
C++
UTF-8
C++
false
false
915
cpp
Valid Mountain Array.cpp
// One person climb from left side and go to peak of the mountain and then the right side class Solution { public: bool validMountainArray(vector<int>& a) { int n = a.size(); if(n<3 or a[0]>=a[1]) return false; int i = 1; while(i<n-1 and a[i]>a[i-1]){ i++; } while(i<n and a[i]<a[i-1]){ i++; } return (i==n); } }; // Two person: one climb from left and second climb from right and both reach at the peak of the mountain class Solution { public: bool validMountainArray(vector<int>& a) { int n = a.size(); if(n<3) return false; int i = 0; while(i<n-1 and a[i]<a[i+1]){ i++; } int j = n-1; while(j>=1 and a[j]<a[j-1]){ j--; } if(i>0 and j<n-1 and i==j){ return true; } return false; } };
9d036ac7c6fc10622d01e16e65aa9593f7c5748e
bb7645bab64acc5bc93429a6cdf43e1638237980
/Official Windows Platform Sample/Windows 8.1 Store app samples/99866-Windows 8.1 Store app samples/Direct3D tiled resources sample/C++/SamplingRenderer.h
5ea4a5f6196f716e5a13b9d162ebdc2c39565985
[ "MIT" ]
permissive
Violet26/msdn-code-gallery-microsoft
3b1d9cfb494dc06b0bd3d509b6b4762eae2e2312
df0f5129fa839a6de8f0f7f7397a8b290c60ffbb
refs/heads/master
2020-12-02T02:00:48.716941
2020-01-05T22:39:02
2020-01-05T22:39:02
230,851,047
1
0
MIT
2019-12-30T05:06:00
2019-12-30T05:05:59
null
UTF-8
C++
false
false
2,846
h
SamplingRenderer.h
//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A //// PARTICULAR PURPOSE. //// //// Copyright (c) Microsoft Corporation. All rights reserved #pragma once #include "DeviceResources.h" #include "StepTimer.h" #include "FreeCamera.h" namespace TiledResources { // A decoded sample from a sampling render pass. struct DecodedSample { float u; float v; short mip; short face; }; // Renders a low-resolution version of the world, encoding sampled data instead of colors. class SamplingRenderer { public: SamplingRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources); void CreateDeviceDependentResources(); concurrency::task<void> CreateDeviceDependentResourcesAsync(); void CreateWindowSizeDependentResources(); void ReleaseDeviceDependentResources(); void SetTargetsForSampling(); void RenderVisualization(); std::vector<DecodedSample> CollectSamples(); void SetDebugMode(bool value); void DebugSample(float x, float y); private: bool GetNextSamplePosition(int* row, int* column); DecodedSample DecodeSample(unsigned int encodedSample); // Cached pointer to device resources. std::shared_ptr<DX::DeviceResources> m_deviceResources; Microsoft::WRL::ComPtr<ID3D11Texture2D> m_colorTexture; Microsoft::WRL::ComPtr<ID3D11Texture2D> m_colorStagingTexture; Microsoft::WRL::ComPtr<ID3D11RenderTargetView> m_colorTextureRenderTargetView; Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_colorTextureView; Microsoft::WRL::ComPtr<ID3D11Texture2D> m_depthTexture; Microsoft::WRL::ComPtr<ID3D11DepthStencilView> m_depthTextureDepthStencilView; Microsoft::WRL::ComPtr<ID3D11PixelShader> m_samplingPixelShader; Microsoft::WRL::ComPtr<ID3D11Buffer> m_pixelShaderConstantBuffer; Microsoft::WRL::ComPtr<ID3D11Buffer> m_viewerVertexBuffer; Microsoft::WRL::ComPtr<ID3D11Buffer> m_viewerIndexBuffer; Microsoft::WRL::ComPtr<ID3D11InputLayout> m_viewerInputLayout; Microsoft::WRL::ComPtr<ID3D11VertexShader> m_viewerVertexShader; Microsoft::WRL::ComPtr<ID3D11PixelShader> m_viewerPixelShader; Microsoft::WRL::ComPtr<ID3D11SamplerState> m_viewerSampler; Microsoft::WRL::ComPtr<ID3D11Buffer> m_viewerVertexShaderConstantBuffer; CD3D11_VIEWPORT m_viewport; unsigned int m_sampleIndex; unsigned int m_sampleCount; bool m_debugMode; bool m_newDebugSamplePosition; float m_debugSamplePositionX; float m_debugSamplePositionY; }; }
5ac937f0a980d6f72023c85a8d627e8b44dbc965
bd58a8ca2483bb66cd8d8c7522865dd45e29f8a8
/All_QT_Projects/QPrinter_PDF_Word_EXECl_Other/printpdf.h
5389f7231dcae78511e4912c791ca8b3586755f4
[]
no_license
Feather-Wang/Qt_Wangqs
4bfd2c4da020fc3afdfb6321240a192fc06bd516
df9f9f74bde6c58518a9a7a42c513fea7e1830d7
refs/heads/master
2020-04-05T04:10:31.603173
2018-11-07T12:10:37
2018-11-07T12:10:37
156,540,672
0
0
null
null
null
null
UTF-8
C++
false
false
604
h
printpdf.h
#ifndef PRINTPDF_H #define PRINTPDF_H #include <QWidget> #include <QTextEdit> #include <QFileDialog> #include <QPrinter> #include <QPrintDialog> #include <QPrintPreviewDialog> #include <QAbstractPrintDialog> #include <QPageSetupDialog> class PrintPDF : public QWidget { Q_OBJECT public: PrintPDF(QWidget *parent = 0); ~PrintPDF(); bool printFile(const QString & filePath); private slots: void doPrint(); void doPrintPreview(); void printPreview(QPrinter *printer); void createPdf(); void setUpPage(); private: QTextEdit text_edit; }; #endif // PRINTPDF_H
2c688162da7cbec0b4da2611f0d34024a3a7659f
618ba8ff08760c367bbb92746714e6ca927deabf
/NanoUART.cpp
af622876a9c1bf0f971a2cbacc29f1b4c0a86ca6
[]
no_license
lsantiago/NANOS_cpp
eae67ed1eabbe2c03f69a74df0673380d8929516
9ce7f65f3799d22912a1115104d1c93f2681a771
refs/heads/master
2020-07-24T12:08:18.695137
2019-09-11T20:41:44
2019-09-11T20:41:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,411
cpp
NanoUART.cpp
/*! \file NanoUART.cpp \brief Library for managing RS-232 module Modified for Tracklink by Sisi IOT, 2019 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Version: 3.3 Design: David Gascon Implementation: Ahmad Saad */ /*********************************************************************** * Includes ***********************************************************************/ #include "NanoUART.h" /*********************************************************************** * Methods of the Class ***********************************************************************/ void NanoUART::ON(){ return ON(RS232); } void NanoUART::ON(uint8_t socket){ // set mux _mux = socket; // update register and select multiplexer switch(_mux){ case RS232: RegisterUART |= REG_RS232; PWR.setMuxRS232(); break; case MKBUS1: RegisterUART |= REG_MKBUS1; PWR.setMuxMKBUS1(); break; case MKBUS2: RegisterUART |= REG_MKBUS2; PWR.setMuxMKBUS2(); break; case FTDI: RegisterUART |= REG_FTDI; PWR.setMuxUSB(); break; default: break; } // Open UART beginUART(); // power on the socket // wait stabilization time delay(50); } //!************************************************************* //! Name: OFF() //! Description: Switches off the module and closes the UART //! Param : void //! Returns: void //!************************************************************* void NanoUART::OFF(void) { switch(_mux){ case RS232: RegisterUART &= ~(REG_RS232); break; case MKBUS1: RegisterUART &= ~(REG_MKBUS1); break; case MKBUS2: RegisterUART &= ~(REG_MKBUS2); break; case FTDI: RegisterUART &= ~(REG_FTDI); break; default: break; } // close uart // si UART no es utilizado, cerrar puerto if(RegisterUART==0){ closeUART(); // off mux } // switch back the mux to RS232 if needed else if(RegisterUART & REG_RS232){ PWR.setMuxRS232(); } // switch module OFF } //!************************************************************* //! Name: read() //! Description: Receives data through the UART //! Param : void //! Returns: char, data read //!************************************************************* char NanoUART::read(void) { secureMux(); return serialRead(_uart); } //!************************************************************* //! Name: receive() //! Description: Receives data through the UART //! Param : void //! Returns the number of received bytes //!************************************************************* uint16_t NanoUART::receive(void) { uint16_t nBytes = 0; secureMux(); nBytes = readBuffer(_bufferSize); return nBytes; } //!************************************************************* //! Name: receive() //! Description: wait for timeout and receives data through the UART //! Param : milliseconds to wait until time-out before a packet arrives //! Returns the number of received bytes //!************************************************************* uint16_t NanoUART::receiveTimeout(uint32_t timeout) { uint32_t previous; uint16_t nBytes = 0; secureMux(); // clear _buffer memset( _buffer, 0x00, _bufferSize ); _length = 0; // init previous previous = millis(); // Perform the different steps within a given timeout while( (millis()-previous) < timeout ) { // Read char if( serialAvailable(_uart) ) { _buffer[_length] = serialRead(_uart); _length++; nBytes++; } } return nBytes; } //!************************************************************* //! Name: send() //! Description: It sends an unsigned char(uint_8) n //! Param : uint8_t, data to send //! Returns: void //!************************************************************* void NanoUART::send(uint8_t n) { secureMux(); printByte(n, _uart); delay(_delay); } //!************************************************************* //! Name: send() //! Description: It sends an int n //! Param: int, data to send //! Returns: void //!************************************************************* void NanoUART::send(int n) { secureMux(); if (n < 0) { printByte('-', _uart); n = -n; } printIntegerInBase(n, 10, _uart); delay(_delay); } //!************************************************************* //! Name: send() //! Description: It sends an unsigned int //! Param : unsigned int, data to send //! Returns: void //!************************************************************* void NanoUART::send(unsigned int n) { secureMux(); printIntegerInBase(n, 10, _uart); delay(_delay); } //!************************************************************* //! Name: send() //! Description: It sends a long //! Param: long, data to send //! Returns: void //!************************************************************* void NanoUART::send(long n) { secureMux(); if (n < 0) { printByte('-', _uart); n = -n; } printIntegerInBase(n, 10, _uart); delay(_delay); } //!************************************************************* //! Name: send() //! Description: It sends a string //! Param : const char s, the string to send //! Returns:void //!************************************************************* void NanoUART::send(const char *s) { secureMux(); printString(s, _uart); delay(_delay); } //!************************************************************* //! Name: send() //! Description: It sends an unsigned long //! Param : unsigned long, data to send //! Returns: void //!************************************************************* void NanoUART::send (unsigned long n) { secureMux(); printIntegerInBase(n, 10, _uart); delay(_delay); } //!************************************************************* //! Name: send() //! Description: //! Param: param long n, unsigned long to send. //! param int base, the base for printing the number //! Returns: void //!************************************************************* void NanoUART::send(long n, int base) { secureMux(); if (base == 0) printByte((char) n, _uart); else printIntegerInBase(n, base, _uart); } /* * print( n ) - prints a double number * */ //!************************************************************* //! Name: send() //! Description: //! Param: param double n, to send. //! Returns: void //!************************************************************* void NanoUART::send(double n) { printFloat(n, 4); } void NanoUART::printFloat(double number, uint8_t digits) { secureMux(); // Handle negative numbers if (number < 0.0) { printByte('-', _uart); number = -number; } // Round correctly so that print(1.999, 2) prints as "2.00" double rounding = 0.5; for (uint8_t i=0; i<digits; ++i) rounding /= 10.0; number += rounding; // Extract the integer part of the number and print it unsigned long int_part = (unsigned long)number; double remainder = number - (double)int_part; printIntegerInBase(int_part, 10, _uart); // Print the decimal point, but only if there are digits beyond if (digits > 0) printByte('.', _uart); // Extract digits from the remainder one at a time while (digits-- > 0) { remainder *= 10.0; int toPrint = int(remainder); printIntegerInBase( (long) toPrint, 10, _uart); remainder -= toPrint; } delay(_delay); } //!************************************************************* //! Name: secureMux() //! Description: Select correct Mux //! Param : void //! Returns void //!************************************************************* void NanoUART::secureMux(void) { switch(_mux){ case RS232: PWR.setMuxRS232(); break; case MKBUS1: PWR.setMuxMKBUS1(); break; case MKBUS2: PWR.setMuxMKBUS2(); break; case FTDI: PWR.setMuxUSB(); break; default: break; } }
218645ed7146d735aeb27f676a937d2f93a25087
7bcba60b0bf019c8e62d1013bd0f1bdd2d38fbe8
/src/AEntity.h
efb4dc6606a26e398885bb2025ac12964b9b2f00
[]
no_license
rubenhir/Car-Game
705330b79e1f5aab7a6c0bcb2d554e03f255b92c
f30037b0eaab3467a6f0f3dcc2c18333ed574baa
refs/heads/master
2021-03-24T12:42:59.650788
2015-06-21T21:55:32
2015-06-21T21:55:32
37,735,749
0
0
null
null
null
null
UTF-8
C++
false
false
1,139
h
AEntity.h
/* * Car.h * * Created on: 23-mrt.-2015 * Author: ruben */ #include <string> #ifndef SRC_AENTITY_H_ #define SRC_AENTITY_H_ #include "ADisplayControl.h" namespace a { class AEntity{ public: AEntity(){ x = 0; y = 0; width=0; height=0; pointerWH=0; } virtual ~AEntity(){} virtual void MediaPath(std::string path)=0; virtual void position(int x, int y)=0; virtual int getX()=0; virtual int getY()=0; virtual void Visualize(a::ADisplayControl *_display) = 0; virtual void Update(a::ADisplayControl *_display) = 0; virtual void Free(a::ADisplayControl *_display)=0; // Visualisatie --> Die in een SDLCar effectief wordt voorgesteld protected: std::string path, type; int *pointerWH,x,y,width,height;; }; } /* namespace a */ #endif /* SRC_AENTITY_H_ */
c88c06285f9af4dbded4264c0464188cc7166d95
bfea494775d3268319cbb01d0f68bb2d70cac01d
/tools/release/ltsgraph/graph.cpp
4b75b3357e1310971d6d1978fa86953040e47b11
[ "BSL-1.0" ]
permissive
Noxsense/mCRL2
e16855c7489a6dea6856d3778218b55d5f692430
dd2fcdd6eb8b15af2729633041c2dbbd2216ad24
refs/heads/master
2021-07-04T21:36:46.816322
2021-01-12T09:20:11
2021-01-12T09:20:11
218,386,668
0
0
NOASSERTION
2019-10-29T21:26:04
2019-10-29T21:26:03
null
UTF-8
C++
false
false
21,092
cpp
graph.cpp
// Author(s): Rimco Boudewijns and Sjoerd Cranen // Copyright: see the accompanying file COPYING or copy at // https://github.com/mCRL2org/mCRL2/blob/master/COPYING // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #include <QDomDocument> #include <QFile> #include <QTextStream> #include <QtOpenGL> #include "exploration.h" #include "mcrl2/lts/lts_io.h" #include "mcrl2/gui/arcball.h" namespace Graph { static QString stateLabelToQString(const mcrl2::lts::state_label_empty& /*unused*/) { return QString(""); } static QString stateLabelToQString(const mcrl2::lts::state_label_lts& label) { return QString::fromStdString(mcrl2::lts::pp(label)); } static QString stateLabelToQString(const mcrl2::lts::state_label_fsm& label) { return QString::fromStdString(mcrl2::lts::pp(label)); } static QString transitionLabelToQString(const mcrl2::lts::action_label_lts& label) { return QString::fromStdString(mcrl2::lts::pp(label)); } static QString transitionLabelToQString(const mcrl2::lts::action_label_string& label) { return QString::fromStdString(label); } #ifndef DEBUG_GRAPH_LOCKS #define GRAPH_LOCK(type, where, x) x #else #define GRAPH_LOCK(type, where, x) \ do \ { \ debug_lock(type, where); \ x; \ debug_lock(type "ed", where); \ } while (false) void debug_lock(const char *type, const char *func) { static int count = 0; static std::unordered_map<Qt::HANDLE, int> ids; Qt::HANDLE id = QThread::currentThreadId(); if (!ids.count(id)) { ids[id] = ++count; } printf("[%d] %s at %s\n", ids[id], type, func); fflush(stdout); } #endif #define lockForRead(lock, where) GRAPH_LOCK("lock", where, (lock).lockForRead()) #define unlockForRead(lock, where) GRAPH_LOCK("unlock", where, (lock).unlock()) #define lockForWrite(lock, where) \ GRAPH_LOCK("W lock", where, (lock).lockForWrite()) #define unlockForWrite(lock, where) GRAPH_LOCK("W unlock", where, (lock).unlock()) Graph::Graph() : m_exploration(nullptr), m_type(mcrl2::lts::lts_lts), m_empty(""), m_stable(true) { } Graph::~Graph() { if (m_exploration != nullptr) { delete m_exploration; m_exploration = nullptr; } } std::size_t Graph::edgeCount() const { return m_edges.size(); } std::size_t Graph::nodeCount() const { return m_nodes.size(); } std::size_t Graph::transitionLabelCount() const { return m_transitionLabels.size(); } std::size_t Graph::stateLabelCount() const { return m_stateLabels.size(); } std::size_t Graph::initialState() const { return m_initialState; } void Graph::clear() { m_nodes.clear(); m_handles.clear(); m_edges.clear(); m_transitionLabels.clear(); m_transitionLabelnodes.clear(); m_stateLabels.clear(); m_stateLabelnodes.clear(); } void Graph::load(const QString& filename, const QVector3D& min, const QVector3D& max) { lockForWrite(m_lock, GRAPH_LOCK_TRACE); clear(); m_type = mcrl2::lts::detail::guess_format(filename.toUtf8().constData()); try { switch (m_type) { case mcrl2::lts::lts_aut: templatedLoad<mcrl2::lts::probabilistic_lts_aut_t>(filename, min, max); break; case mcrl2::lts::lts_dot: throw mcrl2::runtime_error("Cannot read a .dot file anymore."); break; case mcrl2::lts::lts_fsm: templatedLoad<mcrl2::lts::probabilistic_lts_fsm_t>(filename, min, max); break; case mcrl2::lts::lts_lts: default: m_type = mcrl2::lts::lts_lts; templatedLoad<mcrl2::lts::probabilistic_lts_lts_t>(filename, min, max); break; } } catch (mcrl2::runtime_error& e) { unlockForWrite(m_lock, GRAPH_LOCK_TRACE); throw e; } if (m_exploration != nullptr) { delete m_exploration; m_exploration = nullptr; } m_stable = true; unlockForWrite(m_lock, GRAPH_LOCK_TRACE); } template <class lts_t> void Graph::templatedLoad(const QString& filename, const QVector3D& min, const QVector3D& max) { lts_t lts; lts.load(filename.toUtf8().constData()); // Reserve all auxiliary data vectors m_nodes.reserve(lts.num_states()); m_edges.reserve(lts.num_transitions()); m_handles.reserve(lts.num_transitions()); m_transitionLabels.reserve(lts.num_action_labels()); m_transitionLabelnodes.reserve(lts.num_transitions()); m_stateLabels.reserve(lts.num_state_labels()); m_stateLabelnodes.reserve(lts.num_states()); for (std::size_t i = 0; i < lts.num_state_labels(); ++i) { m_stateLabels.push_back(stateLabelToQString(lts.state_label(i))); } // Position nodes randomly for (std::size_t i = 0; i < lts.num_states(); ++i) { const bool is_not_probabilistic = false; m_nodes.emplace_back( QVector3D(frand(min.x(), max.x()), frand(min.y(), max.y()), frand(min.z(), max.z())), is_not_probabilistic); m_stateLabelnodes.emplace_back(m_nodes[i].pos(), i); } // Store string representations of labels for (std::size_t i = 0; i < lts.num_action_labels(); ++i) { QString label = transitionLabelToQString(lts.action_label(i)); m_transitionLabels.push_back(LabelString(lts.is_tau(i), label)); } // Assign and position edge handles, position edge labels for (std::size_t i = 0; i < lts.num_transitions(); ++i) { mcrl2::lts::transition& t = lts.get_transitions()[i]; std::size_t new_probabilistic_state = add_probabilistic_state<lts_t>( lts.probabilistic_state(t.to()), min, max); m_edges.emplace_back(t.from(), new_probabilistic_state); m_handles.push_back(Node( (m_nodes[t.from()].pos() + m_nodes[new_probabilistic_state].pos()) / 2.0)); m_transitionLabelnodes.emplace_back( (m_nodes[t.from()].pos() + m_nodes[new_probabilistic_state].pos()) / 2.0, t.label()); } m_initialState = add_probabilistic_state<lts_t>( lts.initial_probabilistic_state(), min, max); } template <class lts_t> std::size_t Graph::add_probabilistic_state( const typename lts_t::probabilistic_state_t& probabilistic_state, const QVector3D& min, const QVector3D& max) { if (probabilistic_state.size() == 1) { return probabilistic_state.begin()->state(); } else { // There are multiple probabilistic states. Make a new state // with outgoing probabilistic transitions to all states. std::size_t index_of_the_new_probabilistic_state = m_nodes.size(); const bool is_probabilistic = true; m_nodes.emplace_back( QVector3D(frand(min.x(), max.x()), frand(min.y(), max.y()), frand(min.z(), max.z())), is_probabilistic); m_stateLabelnodes.emplace_back(m_nodes[index_of_the_new_probabilistic_state].pos(), index_of_the_new_probabilistic_state); // The following map recalls where probabilities are stored in // transitionLabels. typedef std::map<typename lts_t::probabilistic_state_t::probability_t, std::size_t> probability_map_t; probability_map_t probability_label_indices; for (const typename lts_t::probabilistic_state_t::state_probability_pair& p : probabilistic_state) { // Find an index for the probabilistic label of the outgoing transition of // the probabilistic state. std::size_t label_index; const typename probability_map_t::const_iterator i = probability_label_indices.find(p.probability()); if (i == probability_label_indices.end()) // not found { label_index = m_transitionLabels.size(); probability_label_indices[p.probability()] = label_index; m_transitionLabels.push_back( LabelString(false, QString::fromStdString(pp(p.probability())))); } else { label_index = i->second; } m_edges.push_back(Edge(index_of_the_new_probabilistic_state, p.state())); m_handles.push_back( Node((m_nodes[index_of_the_new_probabilistic_state].pos() + m_nodes[p.state()].pos()) / 2.0)); m_transitionLabelnodes.push_back( LabelNode((m_nodes[index_of_the_new_probabilistic_state].pos() + m_nodes[p.state()].pos()) / 2.0, label_index)); } return index_of_the_new_probabilistic_state; } } void Graph::loadXML(const QString& filename) { lockForWrite(m_lock, GRAPH_LOCK_TRACE); QDomDocument xml; QFile file(filename); if (!file.open(QFile::ReadOnly)) { mCRL2log(mcrl2::log::error) << "Could not open XML file: " << filename.toStdString() << std::endl; return; } QString errorMsg; if (!xml.setContent(&file, false, &errorMsg)) { file.close(); mCRL2log(mcrl2::log::error) << "Could not parse XML file: " << errorMsg.toStdString() << std::endl; return; } file.close(); QDomElement root = xml.documentElement(); if (root.tagName() != "Graph") { mCRL2log(mcrl2::log::error) << "XML contains no valid graph" << std::endl; return; } m_type = (mcrl2::lts::lts_type)root.attribute("type").toInt(); m_nodes.resize(root.attribute("states").toInt()); m_edges.resize(root.attribute("transitions").toInt()); m_handles.resize(root.attribute("transitions").toInt()); m_transitionLabels.resize(root.attribute("transitionlabels").toInt()); m_transitionLabelnodes.resize(root.attribute("transitions").toInt()); m_stateLabels.resize(root.attribute("statelabels").toInt()); m_stateLabelnodes.resize(root.attribute("states").toInt()); QDomNode node = root.firstChild(); while (!node.isNull()) { QDomElement e = node.toElement(); if (e.tagName() == "StateLabel") { m_stateLabels[e.attribute("value").toInt()] = e.attribute("label"); } if (e.tagName() == "State") { m_nodes[e.attribute("value").toInt()] = NodeNode( QVector3D(e.attribute("x").toFloat(), e.attribute("y").toFloat(), e.attribute("z").toFloat()), e.attribute("locked").toInt() != 0, // anchored is equal to locked. e.attribute("locked").toInt() != 0, 0.0f, // selected QVector3D(e.attribute("red").toFloat(), e.attribute("green").toFloat(), e.attribute("blue").toFloat()), e.attribute("is_probabilistic").toInt() != 0); if (e.attribute("isInitial").toInt() != 0) { m_initialState = e.attribute("value").toInt(); } } if (e.tagName() == "StateLabelNode") { m_stateLabelnodes[e.attribute("value").toInt()] = LabelNode( QVector3D(e.attribute("x").toFloat(), e.attribute("y").toFloat(), e.attribute("z").toFloat()), e.attribute("locked").toInt() != 0, // anchored is equal to locked. e.attribute("locked").toInt() != 0, 0.0f, // selected QVector3D(e.attribute("red").toFloat(), e.attribute("green").toFloat(), e.attribute("blue").toFloat()), e.attribute("labelindex").toInt()); } if (e.tagName() == "TransitionLabel") { m_transitionLabels[e.attribute("value").toInt()] = LabelString(e.attribute("isTau").toInt() != 0, e.attribute("label")); } if (e.tagName() == "Transition") { m_edges[e.attribute("value").toInt()] = Edge(e.attribute("from").toInt(), e.attribute("to").toInt()); m_handles[e.attribute("value").toInt()] = Node(QVector3D(e.attribute("x").toFloat(), e.attribute("y").toFloat(), e.attribute("z").toFloat()), e.attribute("locked").toInt() != 0, // anchored is equal to locked. e.attribute("locked").toInt() != 0, 0.0f); // selected } if (e.tagName() == "TransitionLabelNode") { m_transitionLabelnodes[e.attribute("value").toInt()] = LabelNode( QVector3D(e.attribute("x").toFloat(), e.attribute("y").toFloat(), e.attribute("z").toFloat()), e.attribute("locked").toInt() != 0, // anchored is equal to locked. e.attribute("locked").toInt() != 0, 0.0f, // selected QVector3D(e.attribute("red").toFloat(), e.attribute("green").toFloat(), e.attribute("blue").toFloat()), e.attribute("labelindex").toInt()); } node = node.nextSibling(); } if (m_exploration != nullptr) { delete m_exploration; m_exploration = nullptr; } m_stable = true; unlockForWrite(m_lock, GRAPH_LOCK_TRACE); } void Graph::saveXML(const QString& filename) { lockForRead(m_lock, GRAPH_LOCK_TRACE); QDomDocument xml; QDomElement root = xml.createElement("Graph"); root.setAttribute("type", (int)m_type); root.setAttribute("states", (int)nodeCount()); root.setAttribute("transitions", (int)edgeCount()); root.setAttribute("statelabels", (int)stateLabelCount()); root.setAttribute("transitionlabels", (int)transitionLabelCount()); xml.appendChild(root); for (std::size_t i = 0; i < stateLabelCount(); ++i) { QDomElement stateL = xml.createElement("StateLabel"); stateL.setAttribute("value", (int)i); stateL.setAttribute("label", stateLabelstring(i)); root.appendChild(stateL); } for (std::size_t i = 0; i < nodeCount(); ++i) { QDomElement state = xml.createElement("State"); state.setAttribute("value", (int)i); state.setAttribute("x", node(i).pos().x()); state.setAttribute("y", node(i).pos().y()); state.setAttribute("z", node(i).pos().z()); state.setAttribute("locked", static_cast<int>(node(i).locked())); state.setAttribute("isInitial", (int)(i == initialState())); state.setAttribute("red", node(i).color().x()); state.setAttribute("green", node(i).color().y()); state.setAttribute("blue", node(i).color().z()); state.setAttribute("is_probabilistic", static_cast<int>(node(i).is_probabilistic())); root.appendChild(state); QDomElement stateL = xml.createElement("StateLabelNode"); stateL.setAttribute("value", (int)i); stateL.setAttribute("labelindex", (int)stateLabel(i).labelindex()); stateL.setAttribute("x", stateLabel(i).pos().x()); stateL.setAttribute("y", stateLabel(i).pos().y()); stateL.setAttribute("z", stateLabel(i).pos().z()); stateL.setAttribute("locked", static_cast<int>(stateLabel(i).locked())); stateL.setAttribute("red", stateLabel(i).color().x()); stateL.setAttribute("green", stateLabel(i).color().y()); stateL.setAttribute("blue", stateLabel(i).color().z()); root.appendChild(stateL); } for (std::size_t i = 0; i < transitionLabelCount(); ++i) { QDomElement edgL = xml.createElement("TransitionLabel"); edgL.setAttribute("value", (int)i); edgL.setAttribute("label", transitionLabelstring(i)); root.appendChild(edgL); } for (std::size_t i = 0; i < edgeCount(); ++i) { QDomElement edg = xml.createElement("Transition"); edg.setAttribute("value", (int)i); edg.setAttribute("from", (int)edge(i).from()); edg.setAttribute("to", (int)edge(i).to()); edg.setAttribute("x", handle(i).pos().x()); edg.setAttribute("y", handle(i).pos().y()); edg.setAttribute("z", handle(i).pos().z()); edg.setAttribute("locked", static_cast<int>(handle(i).locked())); root.appendChild(edg); QDomElement edgL = xml.createElement("TransitionLabelNode"); edgL.setAttribute("value", (int)i); edgL.setAttribute("labelindex", (int)transitionLabel(i).labelindex()); edgL.setAttribute("x", transitionLabel(i).pos().x()); edgL.setAttribute("y", transitionLabel(i).pos().y()); edgL.setAttribute("z", transitionLabel(i).pos().z()); edgL.setAttribute("locked", static_cast<int>(transitionLabel(i).locked())); edgL.setAttribute("red", transitionLabel(i).color().x()); edgL.setAttribute("green", transitionLabel(i).color().y()); edgL.setAttribute("blue", transitionLabel(i).color().z()); root.appendChild(edgL); } QFile data(filename); if (data.open(QFile::WriteOnly | QFile::Truncate)) { QTextStream out(&data); xml.save(out, 2); } // Todo: Perhaps save exploration too unlockForRead(m_lock, GRAPH_LOCK_TRACE); } NodeNode& Graph::node(std::size_t index) { return m_nodes[index]; } Node& Graph::handle(std::size_t edge) { return m_handles[edge]; } LabelNode& Graph::transitionLabel(std::size_t edge) { return m_transitionLabelnodes[edge]; } LabelNode& Graph::stateLabel(std::size_t index) { return m_stateLabelnodes[index]; } const Edge& Graph::edge(std::size_t index) const { return m_edges[index]; } const NodeNode& Graph::node(std::size_t index) const { return m_nodes[index]; } const Node& Graph::handle(std::size_t edge) const { return m_handles[edge]; } const LabelNode& Graph::transitionLabel(std::size_t edge) const { return m_transitionLabelnodes[edge]; } const LabelNode& Graph::stateLabel(std::size_t index) const { return m_stateLabelnodes[index]; } const QString& Graph::transitionLabelstring(std::size_t labelindex) const { if (labelindex >= m_transitionLabels.size()) { return m_empty; } return m_transitionLabels[labelindex].label(); } const QString& Graph::stateLabelstring(std::size_t labelindex) const { if (labelindex >= m_stateLabels.size()) { return m_empty; } return m_stateLabels[labelindex]; } void Graph::clip(const QVector3D& min, const QVector3D& max) { lockForRead( m_lock, GRAPH_LOCK_TRACE); // read lock because indices are not invalidated m_clip_min = min; m_clip_max = max; for (NodeNode& node : m_nodes) { clipVector(node.pos_mutable(), min, max); } for (LabelNode& node : m_transitionLabelnodes) { clipVector(node.pos_mutable(), min, max); } for (Node& node : m_handles) { clipVector(node.pos_mutable(), min, max); } unlockForRead(m_lock, GRAPH_LOCK_TRACE); } const QVector3D& Graph::getClipMin() const { return m_clip_min; } const QVector3D& Graph::getClipMax() const { return m_clip_max; } void Graph::lock() const { lockForRead(m_lock, GRAPH_LOCK_TRACE); } void Graph::unlock() const { unlockForRead(m_lock, GRAPH_LOCK_TRACE); } #ifdef DEBUG_GRAPH_LOCKS void Graph::lock(const char *where) { lockForRead(m_lock, where); } void Graph::unlock(const char *where) { unlockForRead(m_lock, where); } #endif void Graph::makeExploration() { lockForWrite(m_lock, GRAPH_LOCK_TRACE); delete m_exploration; m_exploration = new Exploration(*this); unlockForWrite(m_lock, GRAPH_LOCK_TRACE); } void Graph::discardExploration() { lockForWrite(m_lock, GRAPH_LOCK_TRACE); if (m_exploration != nullptr) { delete m_exploration; m_exploration = nullptr; } // Deactive all nodes for (NodeNode& node : m_nodes) { node.m_active = false; } unlockForWrite(m_lock, GRAPH_LOCK_TRACE); } void Graph::toggleOpen(std::size_t index) { lockForWrite(m_lock, GRAPH_LOCK_TRACE); if (m_exploration != nullptr && index < m_nodes.size()) { NodeNode& node = m_nodes[index]; bool active = node.m_active; node.m_active = !node.m_active; if (active) { m_exploration->contract(index); } else { m_exploration->expand(index); } } unlockForWrite(m_lock, GRAPH_LOCK_TRACE); } bool Graph::isClosable(std::size_t index) { if (m_exploration == nullptr || index >= m_nodes.size()) { return false; } lockForRead(m_lock, GRAPH_LOCK_TRACE); // active node count: // Todo: improve this std::size_t count = 0; for (std::size_t nodeId : m_exploration->nodes) { if (m_nodes[nodeId].m_active) { ++count; } } NodeNode& node = m_nodes[index]; bool toggleable = !node.m_active || (m_exploration->isContractable(index) && count > 1); toggleable = toggleable && index != m_initialState; unlockForRead(m_lock, GRAPH_LOCK_TRACE); return toggleable; } void Graph::setStable(bool stable) { lockForRead(m_lock, GRAPH_LOCK_TRACE); m_stable = stable; unlockForRead(m_lock, GRAPH_LOCK_TRACE); } bool Graph::isBridge(std::size_t index) const { return m_exploration->isBridge(index); } bool Graph::hasExploration() const { return m_exploration != nullptr; } std::size_t Graph::explorationEdge(std::size_t index) const { return m_exploration->edges[index]; } std::size_t Graph::explorationNode(std::size_t index) const { return m_exploration->nodes[index]; } std::size_t Graph::explorationEdgeCount() const { if (m_exploration == nullptr) { return 0; } return m_exploration->edges.size(); } std::size_t Graph::explorationNodeCount() const { if (m_exploration == nullptr) { return 0; } return m_exploration->nodes.size(); } } // namespace Graph
aa035b39b7d0dd999389cba01919c4a00e3cf457
1791461e6740f81c2dd6704ae6a899a6707ee6b1
/NOI[OpenJudge]/1.11/1.11.4.cpp
1625a80ffcb47a81896f5d6932eee30930490663
[ "MIT" ]
permissive
HeRaNO/OI-ICPC-Codes
b12569caa94828c4bedda99d88303eb6344f5d6e
4f542bb921914abd4e2ee7e17d8d93c1c91495e4
refs/heads/master
2023-08-06T10:46:32.714133
2023-07-26T08:10:44
2023-07-26T08:10:44
163,658,110
22
6
null
null
null
null
UTF-8
C++
false
false
761
cpp
1.11.4.cpp
//Code By HeRaNO #include <cstdio> #include <algorithm> #define MAXN 10020 using namespace std; long long n, k, ans; long long left = 1, right, middle; double x; long long a[MAXN]; long long mymax(long long a, long long b) { return a > b ? a : b; } long long check(long long len) { long long cnt = 0; for (int i = 1; i <= n; i++) cnt += a[i] / len; return cnt; } int main() { scanf("%lld %lld", &n, &k); for (int i = 1; i <= n; i++) { scanf("%lf", &x); a[i] = (long long)(x * 100); right = mymax(right, a[i]); } sort(a + 1, a + n + 1); while (left <= right) { middle = (left + right) >> 1; if (check(middle) < k) right = middle - 1; else { ans = middle; left = middle + 1; } } printf("%.2lf\n", ans / 100.0); return 0; }
06b739809a004987338f94733765e4b651ad82db
8e961307a95fd14686b5562a765e6266478f2818
/global_count.cpp
53afa1dc1d7cb1aeca155b9aa795df27a277e515
[]
no_license
rmccrystal/Mirror-Cheat
16c63dcda679842bafb40ff71082e4f357e8134d
bb81c5138fe3780f0395d8fe711621a332013d60
refs/heads/master
2020-04-15T01:12:59.205302
2019-03-17T22:25:00
2019-03-17T22:25:00
164,267,484
1
0
null
null
null
null
UTF-8
C++
false
false
863
cpp
global_count.cpp
#include "global_count.h" void game_event::on_hurt(IGameEvent * Event) { for (auto i = 0; i < Interfaces::Engine->GetMaxClients(); ++i) { const auto player = const_cast <IClientEntity*>(Interfaces::EntList->GetClientEntity(i)); if (!Event) global_count::didhit[i] = false; if (!strcmp(Event->GetName(), "player_hurt")) { int deadfag = Event->GetInt("userid"); int attackingfag = Event->GetInt("attacker"); if (Interfaces::Engine->GetPlayerForUserID(attackingfag) == Interfaces::Engine->GetLocalPlayer()) { global_count::hits[player->GetIndex()]++; global_count::shots_fired[player->GetIndex()]++; } } if (!strcmp(Event->GetName(), "round_prestart")) { global_count::hits[player->GetIndex()] = 0; global_count::shots_fired[player->GetIndex()] = 0; global_count::missed_shots[player->GetIndex()] = 0; } } }
fcdf95700bef355bfa829b9f150ebcda10619c6b
70c00b8c597576f3ccbd299a64b7ccc0e575c557
/Src/Model3/DSB.h
09ab60b05c32ab132983a7a26cb5d9e5c35066d9
[]
no_license
mirror/model3emu
7404fb61808dc3ad0e496bada75bb8e9c96caf01
f77b119f7b3318ad5d3b7ccea2f7de2ffae1e571
refs/heads/master
2023-08-22T20:13:45.579652
2013-11-30T19:39:59
2013-11-30T19:39:59
7,616,012
7
0
null
null
null
null
UTF-8
C++
false
false
10,128
h
DSB.h
/** ** Supermodel ** A Sega Model 3 Arcade Emulator. ** Copyright 2011 Bart Trzynadlowski, Nik Henson ** ** This file is part of Supermodel. ** ** Supermodel 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. ** ** Supermodel 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 Supermodel. If not, see <http://www.gnu.org/licenses/>. **/ /* * DSB.h * * Header file for the Sega Digital Sound Board (Type 1 and 2) devices. CDSB1 * is an implementation of the Z80-based DSB Type 1, and CDSB2 is the 68K-based * Type 2 board. Only one may be active at a time because they rely on non- * reentrant MPEG playback code. */ #ifndef INCLUDED_DSB_H #define INCLUDED_DSB_H #include "Types.h" #include "CPU/Bus.h" /****************************************************************************** Configuration Because DSB code mixes both the sound board SCSP and MPEG audio together, both volume settings are stored here (for now). ******************************************************************************/ /* * CDSBConfig: * * Settings used by CDSB. */ class CDSBConfig { public: bool emulateDSB; // DSB emulation (enabled if true) // Sound (SCSP) volume (0-200, 100 being full amplitude) inline void SetSoundVolume(int vol) { if (vol > 200) { ErrorLog("Sound volume cannot exceed 200%%; setting to 100%%.\n"); vol = 100; } if (vol < 0) { ErrorLog("Sound volume cannot be negative; setting to 0%%.\n"); vol = 0; } soundVol = (unsigned) vol; } inline unsigned GetSoundVolume(void) { return soundVol; } // Music (DSB MPEG) volume (0-200) inline void SetMusicVolume(int vol) { if (vol > 200) { ErrorLog("Music volume cannot exceed 200%%; setting to 100%%.\n"); vol = 100; } if (vol < 0) { ErrorLog("Music volume cannot be negative; setting to 0%%.\n"); vol = 0; } musicVol = (unsigned) vol; } inline unsigned GetMusicVolume(void) { return musicVol; } // Defaults CDSBConfig(void) { emulateDSB = true; soundVol = 100; musicVol = 100; } private: unsigned soundVol; unsigned musicVol; }; /****************************************************************************** Resampling Used internally by the DSB's MPEG code. If this becomes sufficiently generic, it can be moved to Sound/. Not intended for general use for now. ******************************************************************************/ /* * CDSBResampler: * * Frame-by-frame resampler. Resamples one single frame of audio and maintains * continuity between frames by copying unprocessed input samples to the * beginning of the buffer and retaining the internal interpolation state. * * See DSB.cpp for a detailed description of how this works. * * NOTE: If the sampling frequencies change, it is probably best to call * Reset(). Whether the resampler will otherwise behave correctly and stay * within array bounds has not been verified. * * Designed for use at 60 Hz, for input frequencies of 11.025, 22.05, 16, and * 32 KHz and 44.1 KHz output frequencies. Theoretically, it should be able to * operate on most output frequencies and input frequencies that are simply * lower, but it has not been extensively verified. */ class CDSBResampler { public: int UpSampleAndMix(INT16 *outL, INT16 *outR, INT16 *inL, INT16 *inR, UINT8 volumeL, UINT8 volumeR, int sizeOut, int sizeIn, int outRate, int inRate); void Reset(void); private: int nFrac; int pFrac; }; /****************************************************************************** DSB Base Class ******************************************************************************/ /* * CDSB: * * Abstract base class defining the common interface for both DSB board types. */ class CDSB: public CBus { public: /* * SendCommand(data): * * Send a MIDI command to the DSB board. */ virtual void SendCommand(UINT8 data) = 0; /* * RunFrame(audioL, audioR): * * Runs one frame and updates the MPEG audio. Audio is mixed into the * supplied buffers (they are assumed to already contain audio data). * * Parameters: * audioL Left audio channel, one frame (44 KHz, 1/60th second). * audioR Right audio channel. */ virtual void RunFrame(INT16 *audioL, INT16 *audioR) = 0; /* * Reset(void): * * Resets the DSB. Must be called prior to RunFrame(). */ virtual void Reset(void) = 0; /* * SaveState(SaveState): * * Saves an image of the current device state. * * Parameters: * SaveState Block file to save state information to. */ virtual void SaveState(CBlockFile *SaveState) = 0; /* * LoadState(SaveState): * * Loads and a state image. * * Parameters: * SaveState Block file to load state information from. */ virtual void LoadState(CBlockFile *SaveState) = 0; /* * Init(progROMPtr, mpegROMPtr): * * Initializes the DSB board. This member must be called first. * * Parameters: * progROMPtr Program (68K or Z80) ROM. * mpegROMPtr MPEG data ROM. * * Returns: * OKAY if successful, otherwise FAIL. */ virtual bool Init(const UINT8 *progROMPtr, const UINT8 *mpegROMPtr) = 0; }; /****************************************************************************** DSB Classes DSB1 and DSB2 hardware. The base class, CDSB, should ideally be dynamically allocated using one of these. See CDSB for descriptions of member functions. ******************************************************************************/ /* * CDSB1: * * Sega Digital Sound Board Type 1: Z80 plus custom gate array for MPEG * decoding. */ class CDSB1: public CDSB { public: // Read and write handlers for the Z80 (required by CBus) UINT8 IORead8(UINT32 addr); void IOWrite8(UINT32 addr, UINT8 data); UINT8 Read8(UINT32 addr); void Write8(UINT32 addr, UINT8 data); // DSB interface (see CDSB definition) void SendCommand(UINT8 data); void RunFrame(INT16 *audioL, INT16 *audioR); void Reset(void); void SaveState(CBlockFile *StateFile); void LoadState(CBlockFile *StateFile); bool Init(const UINT8 *progROMPtr, const UINT8 *mpegROMPtr); // Returns a reference to the Z80 CPU CZ80 *GetZ80(void); // Constructor and destructor CDSB1(void); ~CDSB1(void); private: // Resampler CDSBResampler Resampler; int retainedSamples; // how many MPEG samples carried over from previous frame // MPEG decode buffers (48KHz, 1/60th second + 2 extra padding samples) INT16 *mpegL, *mpegR; // DSB memory const UINT8 *progROM; // Z80 program ROM (passed in from parent object) const UINT8 *mpegROM; // MPEG music ROM UINT8 *memoryPool; // all memory allocated here UINT8 *ram; // Z80 RAM // Command FIFO UINT8 fifo[128]; int fifoIdxR; // read position int fifoIdxW; // write position // MPEG playback variables int mpegStart; int mpegEnd; int mpegState; int loopStart; int loopEnd; // Settings of currently playing stream (may not match the playback register variables above) UINT32 usingLoopStart; // what was last set by MPEG_SetLoop() or MPEG_PlayMemory() UINT32 usingLoopEnd; UINT32 usingMPEGStart; // what was last set by MPEG_PlayMemory() UINT32 usingMPEGEnd; // Registers UINT32 startLatch; // MPEG start address latch UINT32 endLatch; // MPEG end address latch UINT8 status; UINT8 cmdLatch; UINT8 volume; // 0x00-0x7F UINT8 stereo; // Z80 CPU CZ80 Z80; }; /* * CDSB2: * * Sega Digital Sound Board Type 2: 68K CPU. */ class CDSB2: public CDSB { public: // Read and write handlers for the 68K (required by CBus) UINT8 Read8(UINT32 addr); UINT16 Read16(UINT32 addr); UINT32 Read32(UINT32 addr); void Write8(UINT32 addr, UINT8 data); void Write16(UINT32 addr, UINT16 data); void Write32(UINT32 addr, UINT32 data); // DSB interface (see definition of CDSB) void SendCommand(UINT8 data); void RunFrame(INT16 *audioL, INT16 *audioR); void Reset(void); void SaveState(CBlockFile *StateFile); void LoadState(CBlockFile *StateFile); bool Init(const UINT8 *progROMPtr, const UINT8 *mpegROMPtr); // Returns a reference to the 68K CPU context M68KCtx *GetM68K(void); // Constructor and destructor CDSB2(void); ~CDSB2(void); private: // Private helper functions void WriteMPEGFIFO(UINT8 byte); // Resampler CDSBResampler Resampler; int retainedSamples; // how many MPEG samples carried over from previous frame // MPEG decode buffers (48KHz, 1/60th second + 2 extra padding samples) INT16 *mpegL, *mpegR; // DSB memory const UINT8 *progROM; // 68K program ROM (passed in from parent object) const UINT8 *mpegROM; // MPEG music ROM UINT8 *memoryPool; // all memory allocated here UINT8 *ram; // 68K RAM // Command FIFO UINT8 fifo[128]; int fifoIdxR; // read position int fifoIdxW; // write position // Registers int cmdLatch; int mpegState; int mpegStart, mpegEnd, playing; UINT8 volume[2]; // left, right volume (0x00-0xFF) // Settings of currently playing stream (may not match the playback register variables above) UINT32 usingLoopStart; // what was last set by MPEG_SetLoop() or MPEG_PlayMemory() UINT32 usingLoopEnd; UINT32 usingMPEGStart; // what was last set by MPEG_PlayMemory() UINT32 usingMPEGEnd; // M68K CPU M68KCtx M68K; }; #endif // INCLUDED_DSB_H
c36e6bdc4ee3b266c046a76b575662436c5dccce
84ea17552c2fd77bc85af22f755ae04326486bb5
/Ablaze-Core/src/Entities/Components/UI/Clickable.cpp
f9bb34531e80c7a32ca74e4be1407f5bf915e4c9
[]
no_license
Totomosic/Ablaze
98159c0897b85b236cf18fc8362501c3873e49f4
e2313602d80d8622c810d3d0d55074cda037d287
refs/heads/master
2020-06-25T20:58:29.377957
2017-08-18T07:42:20
2017-08-18T07:42:20
96,988,561
1
1
null
null
null
null
UTF-8
C++
false
false
597
cpp
Clickable.cpp
#include "Clickable.h" namespace Ablaze { namespace Components { Clickable::Clickable() { } Clickable::Clickable(const std::function<void(const Clickable*)>& callback) : Clickable() { PushCallback(callback); } const std::vector<std::function<void(const Clickable*)>>& Clickable::GetCallbacks() const { return callbacks; } void Clickable::PushCallback(const std::function<void(const Clickable*)>& callback) { callbacks.push_back(callback); } void Clickable::Trigger() const { for (auto function : callbacks) { function(this); } } } }
b3e0e9b186c0735cd4dd2dd48928b7b9979c8d54
c6147c6bfa21da38ee60feb120b8b5a0c2406b5b
/mapamok/src/modelView.h
b26399f30a973ed34a7b75d6692304006a7c471b
[ "MIT" ]
permissive
lexvandersluijs/ProCamToolkit
8b63388e49efedcb9d7923192df7e1f2b41b8678
6760dcc68a2edeeede3f4d05c0ffd0feef1f3062
refs/heads/master
2020-12-25T06:07:04.380200
2013-10-05T12:58:48
2013-10-05T12:58:48
12,036,385
1
0
null
null
null
null
UTF-8
C++
false
false
504
h
modelView.h
#pragma once class projectorView; class modelView : public meshView { private: protected: public: ofEasyCam cam; void draw(ofxControlPanel& panel, float mouseX, float mouseY, projectorView* projView, ofLight& light, ofShader& shader, ofTexture* texture); //ofImage& customPicture, ofxThreadedVideo& mappingMovie); //void draw(ofxControlPanel& panel, float mouseX, float mouseY, projectorView* projView, ofLight& light, ofShader& shader, ofImage& customPicture, ofVideoPlayer& mappingMovie); };
0cfd13e0faf1ab08700ce9429810c271c62aaf52
20623fdd89c5893a4aada45873a17c585f2456db
/okno.h
cc7ac6de6a4b549c63675c3f934e608eafea3fa0
[]
no_license
faeton-off/nowy_tetris
0693b7e3c835bb0311e6fa3829b69b61c82a6b70
ea26d540050118cf9de1766c7cb9ce16b794b113
refs/heads/master
2023-05-30T16:49:09.179229
2021-06-14T17:15:01
2021-06-14T17:15:01
369,294,695
0
0
null
null
null
null
UTF-8
C++
false
false
892
h
okno.h
#ifndef OKNO_H #define OKNO_H #include <QWidget> QT_BEGIN_NAMESPACE class QLCDNumber; class QLabel; class QPushButton; QT_END_NAMESPACE class Plansza; class Okno : public QWidget { Q_OBJECT public: /*! * \brief * Tworzy interfejs programu. */ Okno(QWidget *parent = nullptr); private: QLabel *stworzOkno(const QString &text); // tworzy nowe okno Plansza *plansza; // wyświetla planszę QLabel *kolejnyKlocek; // kolejny klocek QLCDNumber *wyniklcd; // aktualny wynik QLCDNumber *poziomlcd; // aktualny poziom QLCDNumber *linijkilcd; // wypełnione linijki QPushButton *przyciskStart; // przycisk "Start" QPushButton *przyciskWyjdz; // przycisk "Wyjdź" QPushButton *przyciskPauza; // przycisk "Pauza/Wznów" }; #endif
2dc586f9fccc598d77d38654681b4a1da569ac76
388afeba0686c3900337ea733506f0f928301177
/test/cc/GPIOOutput.test.cc
ea99094be556b9e20def681c78b6a8d695c68425
[]
no_license
jsdevel/node-pi-native-tools
b6c17c7d06eb980f51a8a1950cc4d2ea7adac18b
d1cf0d87407d4e5dd0178bc186b8e27c2ff8f54a
refs/heads/master
2020-12-30T10:50:03.334183
2014-01-23T08:39:45
2014-01-23T08:39:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,828
cc
GPIOOutput.test.cc
#include <cstdio> #include <iostream> #include <unistd.h> #include "../../src/cc/bcm2835.h" #include "../../src/cc/GPIOOutput.h" #include "helpers/TestVars.h" using namespace std; extern TestVars TEST_VARS; #define USE_BEFORE 1 #define USE_AFTER 1 #include "helpers/assert.h" namespace test { GPIOOutput * gpio; void before(){ TEST_VARS.reset(); gpio = new GPIOOutput(5); } void after(){ delete gpio; } /*void valid_pins_for_constructor_throw_no_error(){ int pins [17] = {3, 5, 7, 8, 10, 11, 12, 13, 15, 16, 18, 19, 21, 22, 23, 24, 26}; for(int i = 0;i<17;i++){ new GPIOOutput(pins[i]); } }*/ /*void invalid_pins_for_constructor_throw_error(){ int pins [5] = {1, 2, 0, 40, 50}; for(int i = 0;i<5;i++){ try { new GPIOOutput(pins[i]); fail("didn't throw for"); } catch(...){ continue; } } }*/ void write_calls_bcm_write(){ gpio->write(); assert(TEST_VARS.output_write == 1); gpio->write(); assert(TEST_VARS.output_write == 2); } void write_uses_given_pin(){ gpio->write(); //note that the GPIO class should convert this assert(TEST_VARS.currentPin == 5); } void erase_calls_bcm_write(){ gpio->erase(); assert(TEST_VARS.currentValue == 0); gpio->write(); assert(TEST_VARS.currentValue == 1); gpio->erase(); assert(TEST_VARS.currentValue == 0); } void erase_uses_given_pin(){ gpio->erase(); //note that the GPIO class should convert this assert(TEST_VARS.currentPin == 5); } } int main(){ SUITE(); /*TEST(valid_pins_for_constructor_throw_no_error); TEST(invalid_pins_for_constructor_throw_error);*/ TEST(write_calls_bcm_write); TEST(write_uses_given_pin); TEST(erase_calls_bcm_write); TEST(erase_uses_given_pin); END(); }
160e06408aadee29b64a7c60431f52371c833270
31f7b80d2c0651a6a360f6f6b36b835cf1fc22e5
/Squareroot.cpp
e3df9f30cfb273e18a622347b87a8b481a6e070d
[]
no_license
sachin-nono/codingpractice
c59ed716c95a65e6ef30e802a377617a5546fd01
e83b9b716cb3e6b4b5d2a6e20aa7024db43ad67f
refs/heads/master
2020-03-21T10:00:07.561785
2018-07-28T10:01:44
2018-07-28T10:01:44
138,428,859
2
3
null
2018-07-05T16:18:12
2018-06-23T19:42:45
C++
UTF-8
C++
false
false
416
cpp
Squareroot.cpp
/* Print Integral Part of a Square Root */ #include<iostream> using namespace std; int main() { int squareroot(double),x; double y; cout<<"Enter number : "; cin>>y; x=squareroot(y); cout<<endl<<"Integral Part of Square Root of "<<y<<" is : "<<x<<endl; return 0; } int squareroot(double y) { int i=1; while(i*i<=y) i++; return i-1; }
1b1794fa3f7e8843f7a7852d0b932c78c4b07ade
62d74675721d939baae340864c0e79d3037df189
/inheritance/predict the output part 1/18.cpp
fce8fb9b592f11ad051ac33d2e3dd7325ae45213
[]
no_license
shubhamkanade/cpp-program
c5fe1c85d2adac7c67ebd934c34e9b69509466d4
0cf279bd9cd473541a8a72bfee1f4b948d7fdaba
refs/heads/master
2021-07-12T08:49:14.479420
2021-07-06T03:24:06
2021-07-06T03:24:06
172,293,386
0
0
null
null
null
null
UTF-8
C++
false
false
363
cpp
18.cpp
#include<iostream> using namespace std; class Base { public: void fun(int i) { cout<<"Base fun\n"; } void fun(int i,int j) { cout<<"Base fun\n"; } }; class Derived:public Base { public: void fun(int i) { cout<<"derivde fun\n"; } }; int main() { Base bobj; Derived dobj; bobj.fun(10); bobj.fun(10,20); dobj.fun(20); return 0; }
531ce2577505a977fda00e734cf5b64fd2ef53c3
1b8e1ddcb86f0a5cd018bc6b3400c8c6fb1c1984
/server/server/CheckIn/GameMsg_S2C_CheckResult.cpp
333f6cc3cd612b4e22b00ca0b8eeb74138f44a97
[]
no_license
yzfrs/ddianle_d1
5e9a3ab0ad646ca707368850c01f8117a09f5bfd
abffb574419cc2a8a361702e012cdd14f1102a6d
refs/heads/master
2021-01-01T03:32:51.973703
2016-05-12T09:27:00
2016-05-12T09:27:00
58,615,329
0
2
null
null
null
null
UTF-8
C++
false
false
1,132
cpp
GameMsg_S2C_CheckResult.cpp
#include "GameMsg_S2C_CheckResult.h" #include "../share/ServerMsgDef.h" GameMsg_S2C_CheckInSuccess::GameMsg_S2C_CheckInSuccess() :GameMsg_Base(MSG_S2C_CheckInSuccess) ,m_nDayIndex(0) ,m_nMoney(0) ,m_nBindCoin(0) { } GameMsg_S2C_CheckInSuccess::~GameMsg_S2C_CheckInSuccess() { } bool GameMsg_S2C_CheckInSuccess::doEncode(CParamPool &IOBuff) { IOBuff.AddUInt(m_nDayIndex); m_ItemReward.doEncode( IOBuff ); IOBuff.AddUInt( m_nMoney ); IOBuff.AddUInt( m_nBindCoin ); return true; } GameMsg_S2C_CheckInFail::GameMsg_S2C_CheckInFail() :GameMsg_Base(MSG_S2C_CheckResultFail) ,m_nFailFlag(0) { } GameMsg_S2C_CheckInFail::~GameMsg_S2C_CheckInFail() { } bool GameMsg_S2C_CheckInFail::doEncode(CParamPool &IOBuff) { IOBuff.AddUInt( m_nFailFlag ); return true; } GameMsg_S2C_CheckInMailRewardNotice::GameMsg_S2C_CheckInMailRewardNotice() :GameMsg_Base(MSG_S2C_CheckInRewardMailNotice) { } GameMsg_S2C_CheckInMailRewardNotice::~GameMsg_S2C_CheckInMailRewardNotice() { } bool GameMsg_S2C_CheckInMailRewardNotice::doEncode(CParamPool &IOBuff) { return true; }
54036dfb3e636204adb5a05fa87d8055393e62b6
18a3f93e4b94f4f24ff17280c2820497e019b3db
/BOSS/MucMappingAlg/MucChain.cxx
c96d3de10c93b9a9e573dfca8bcb7011b7147194
[]
no_license
jjzhang166/BOSS_ExternalLibs
0e381d8420cea17e549d5cae5b04a216fc8a01d7
9b3b30f7874ed00a582aa9526c23ca89678bf796
refs/heads/master
2023-03-15T22:24:21.249109
2020-11-22T15:11:45
2020-11-22T15:11:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,574
cxx
MucChain.cxx
//------------------------------------------------------------------------------| // [File ]: MucChain.cxx | // [Brief ]: Source file of class MucChain for electronics mapping | // [Author]: Xie Yuguang, <ygxie@mail.ihep.ac.cn> | // [Date ]: Jun 7, 2006 | // [Log ]: See ChangLog | //------------------------------------------------------------------------------| #include<iostream> #include<vector> using namespace std; #include "MucMappingAlg/MucChain.h" // Constructor MucChain :: MucChain( int id, std::string name, int module, int socket, int fecOrder ) { // cout << "MucChain:: Create chain : " << endl; // cout << "ID: " << id << "\tModule: " << module << "\tSocket: " << socket << "\tFecOrder: " << fecOrder << endl; m_ID = id; m_Name = name; m_Module = module; m_Socket = socket; m_FecOrder = fecOrder; Mapping(); } // Destructor MucChain :: ~MucChain() { // cout << "MucChain:: Destructor()." <<endl; delete []m_FirstStripID; delete []m_FecLayerID; delete []m_StripOrder; m_FecVect.clear(); } //----------------------- Set properties methods for public--------------- void MucChain :: ReMap( string name, int module, int socket ) { m_Name = name; m_Module = module; m_Socket = socket; MucChain::Mapping(); } void MucChain :: SetFecOrder( int fecOrder ) { m_FecOrder = fecOrder; MucChain::InitFecVect(); } // All FECs void MucChain :: SetStripOrder( int stripOrder ) { // cout << "MucChain:: SetStripOrder( int )." << endl; int order; if( stripOrder == 0 ) order = DEFAULT_STRIP_ORDER; else order = stripOrder; for(int i=0; i<m_FecTotal; i++) m_StripOrder[ i ] = order; } void MucChain :: SetStripOrder( int fecID, int stripOrder ) { // Decode FecVect member number by fecID int i = m_FecOrder * ( fecID - ((1-m_FecOrder)/2)*(m_FecTotal - 1) ); m_FecVect[i].SetStripOrder( stripOrder ); } void MucChain :: ArrayInvert( int* array, int number ) { int temp; for(int i=0; i<number/2; i++) { temp = array[i]; array[i] = array[number-1-i]; array[number-1-i] = temp; } } //------------------------ set properties methods for private--------------- void MucChain :: Mapping() { InitPart(); InitSegment(); InitFecTotal(); InitFecPerLayer(); InitFecLayerID(); InitFirstStripID(); InitStripOrder(); InitFecVect(); } void MucChain :: InitPart() { // cout << "MucChain:: InitPart()." <<endl; if( m_Name[0] == 'B' ) m_Part = BRID; else if( m_Name[1] == 'E' ) m_Part = EEID; else m_Part = WEID; } void MucChain :: InitSegment() { // cout << "MucChain:: InitSegment()." <<endl; if( m_Part == BRID ) { switch( m_Name[2] ) { case '1' : m_Segment = 2; break; case '2' : m_Segment = 1; break; case '3' : m_Segment = 0; break; case '4' : m_Segment = 7; break; case '5' : m_Segment = 6; break; case '6' : m_Segment = 5; break; case '7' : m_Segment = 4; break; case '8' : m_Segment = 3; break; default : ; } } else if( m_Part == EEID ) { switch( m_Name[2] ) { case '1' : m_Segment = 0; break; case '2' : m_Segment = 3; break; case '3' : m_Segment = 2; break; case '4' : m_Segment = 1; break; } } else { switch( m_Name[2] ) { case '1' : m_Segment = 1; break; case '2' : m_Segment = 2; break; case '3' : m_Segment = 3; break; case '4' : m_Segment = 0; break; } } } void MucChain :: InitFecTotal() { // cout << "MucChain:: InitFecTotal()." <<endl; if( m_Part == BRID ) // Barrel { if( m_Name[1] == 'O' ) // Odd layer chain { m_FecTotal = FEC_NUM - 1; // 15 FECs } else // Even layer chain { if( m_Segment == BRTOP && m_Name[1] == 'E' ) // Top segment { m_FecTotal = FEC_NUM ; // 16 FECs } else // Not top segment { m_FecTotal = FEC_NUM - 4; // 12 FECs } } } else // Endcap { m_FecTotal = FEC_NUM; // 16 FECs } } void MucChain :: InitFecPerLayer() { // cout << "MucChain:: InitFecPerLayer()." <<endl; if( m_FecTotal != 0 ) { if( m_FecTotal == FEC_NUM ) m_FecPerLayer = 4; else m_FecPerLayer = 3; } else m_FecPerLayer = 0; } void MucChain :: InitFecLayerID() { // cout << "MucChain:: InitLayer()." <<endl; // Init array for(int i=0; i<FEC_NUM; i++) m_FecLayerID[i] = 0; // Set FEC layer id according to default order if( m_Part == BRID ) // Barral chains { if( m_Name[1] == 'O' ) // Odd layer chain, layer id: 0, 2, 4, 6, 8 { for(int i=0; i<m_FecTotal; i++) { m_FecLayerID[i] = (i/m_FecPerLayer) * 2; } } else // Even layer chain, layer id: 1, 3, 5, 7 { for(int i=0; i<m_FecTotal; i++) { m_FecLayerID[i] = (i/m_FecPerLayer) * 2 + 1; } } } else // Endcap chains { if( m_Name[3] == 'F' ) // First chain, layer id: 0, 1, 2, 3 { for(int i=0; i<m_FecTotal; i++) { m_FecLayerID[i] = 3 - (i/m_FecPerLayer); } } else // Second chain, layer id: 4, 5, 6, 7 { for(int i=0; i<m_FecTotal; i++) { m_FecLayerID[i] = 7 - (i/m_FecPerLayer); } } } // If inverting order if( m_FecOrder == -1 ) MucChain::ArrayInvert( &m_FecLayerID[0], m_FecTotal ); } void MucChain :: InitFirstStripID() { // cout << "MucChain:: InitFirstStripID()." <<endl; // Init array for(int i=0; i<FEC_NUM; i++) m_FirstStripID[i] = 0; // Set first strip ID according to default fecOrder if( m_Part== BRID ) // Barrel chains { if( m_Name[1] == 'E' ) // East end, only even number layer chain, layer id: 1, 3, 5, 7 { // Section number is defined by m_FecTotal/m_FecPerLayer // Some sections of chain inverting default firstStripID sequence if(m_Segment==BRTOP) // BRTOP segment is exceptive, FirstStripID sequence is 64,96,80,48 { for(int i=0; i<m_FecTotal; i++) m_FirstStripID[i] = FIRST_STRID_SQC_BETOP[i%m_FecPerLayer ]; } else switch(m_Segment) { case 0: ; // Segment 0, 1, 5, section 0, 2: (+), 1, 3: (-) case 1: ; case 5: for(int i=0; i<m_FecTotal; i++) m_FirstStripID[i] = FIRST_STRID_SQC_BEA[i%m_FecPerLayer ]; break; default : // Other segments for(int i=0; i<m_FecTotal; i++) m_FirstStripID[i] = FIRST_STRID_SQC_BEB[i%m_FecPerLayer ]; } } else if( m_Name[1] == 'W' ) // West end, even number layer chain, layer id: 1, 3, 5, 7 { switch(m_Segment) { case 0: ; // Segment 0, 1, 2, 5 case 1: ; case 2: ; case 5: for(int i=0; i<m_FecTotal; i++) m_FirstStripID[i] = FIRST_STRID_SQC_BWA[i%m_FecPerLayer ]; break; default: // Other segments for(int i=0; i<m_FecTotal; i++) m_FirstStripID[i] = FIRST_STRID_SQC_BWB[i%m_FecPerLayer ]; } } else // West end, odd number layer chain, layer id: 0, 2, 4, 6 { switch(m_Segment) { case 0: ; // Segment 0, 1, 2, 5 case 1: ; case 2: ; case 5: for(int i=0; i<m_FecTotal; i++) m_FirstStripID[i] = FIRST_STRID_SQC_BWB[ i%m_FecPerLayer ]; break; default : // Other segments for(int i=0; i<m_FecTotal; i++) m_FirstStripID[i] = FIRST_STRID_SQC_BWA[ i%m_FecPerLayer ]; } } // for all chains in Barrel, section 0, 2, 4: (+), 1, 3: (-), inverting 1, 3; for(int j=1; j<m_FecTotal/m_FecPerLayer; j+=2) MucChain::ArrayInvert( &m_FirstStripID[j*m_FecPerLayer], m_FecPerLayer ); } // End barrel chains else // Endcap chains { // Set default firstStripID order(+), no inverting for(int i=0; i<m_FecTotal; i++) m_FirstStripID[i] = FIRST_STRID_SQC_EC[ i%m_FecPerLayer ]; } // If fecOrder inverting if( m_FecOrder == -1 ) { MucChain::ArrayInvert( m_FirstStripID, m_FecTotal ); } } unsigned int MucChain :: EncodeVmeRecord( int module, int socket, int fecID, unsigned short data) { // cout << "MucChain:: EncodeVmeRecord()." <<endl; unsigned int record = ((module << MODULE_BIT) | (socket << SOCKET_BIT) | fecID); return ( (record << LENGTH) | data ); } // All FECs void MucChain :: InitStripOrder() { // cout << "MucChain:: InitStripOrder()." << endl; for(int i=0; i<m_FecTotal; i++) { if( m_Part == BRID ) // Barrel { m_StripOrder[i] = -1; /* if( m_Name[1] == 'E' ) // East end, only even number layer chain, layer id: 1, 3, 5, 7 { // Section number is defined by m_FecTotal/m_FecPerLayer // Some sections of chain inverting default strip order if(m_Segment==BRTOP) //Strip order is +1, -1, +1, -1 { for(int i=0; i<m_FecTotal; i++) m_StripOrder[i] = STRORDER_BETOP[i%m_FecPerLayer ]; } else switch(m_Segment) { case 0: ; // Segment 0, 1, 5, section 0, 2: (--+), 1, 3: (+--) case 1: ; case 5: for(int i=0; i<m_FecTotal; i++) m_StripOrder[i] = STRORDER_BEA[i%m_FecPerLayer ]; break; default : // Other segments for(int i=0; i<m_FecTotal; i++) m_StripOrder[i] = STRORDER_BEB[i%m_FecPerLayer ]; } } else if( m_Name[1] == 'W' ) // West end, even number layer chain, layer id: 1, 3, 5, 7 { switch(m_Segment) { case 0: ; // Segment 0, 1, 2, 5, --+ case 1: ; case 2: ; case 5: for(int i=0; i<m_FecTotal; i++) m_StripOrder[i] = STRORDER_BEA[i%m_FecPerLayer ]; break; default : // Other segments, +-- for(int i=0; i<m_FecTotal; i++) m_StripOrder[i] = STRORDER_BEB[i%m_FecPerLayer ]; } } else // West end, odd number layer chain, layer id: 0, 2, 4, 6 { for(int i=0; i<m_FecTotal; i++) m_StripOrder[i] = STRORDER_BWO[ i%m_FecPerLayer ]; } // for all chains in Barrel, section 0, 2, 4: (+), 1, 3: (-), inverting 1, 3; for(int j=1; j<m_FecTotal/m_FecPerLayer; j+=2) MucChain::ArrayInvert( &m_StripOrder[j*m_FecPerLayer], m_FecPerLayer ); */ } // End Barrel else if( (m_Part==EEID && (m_Segment==0 || m_Segment==2)) || (m_Part==WEID && (m_Segment==1 || m_Segment==3)) ) m_StripOrder[ i ] = STRORDER_ECA[ m_FecLayerID[i] ]; else m_StripOrder[ i ] = STRORDER_ECB[ m_FecLayerID[i] ]; } // End FecTotal } void MucChain :: InitFecVect() { // cout << "MucChain:: InitFecVect()." << endl; unsigned short data = 0; int part = m_Part; int segment = m_Segment; int id; int layer; int firstStripID; int stripOrder; string chainName; unsigned int vmeRecord; for(int i=0; i<m_FecTotal; i++) { // Encode FEC id by FecVect member number id =( (1 - m_FecOrder)/2 ) * ( m_FecTotal - 1 ) + (m_FecOrder * i); layer = m_FecLayerID[ id ]; firstStripID = m_FirstStripID[ id ]; stripOrder = m_StripOrder[ id ]; chainName = MucChain::m_Name; vmeRecord = EncodeVmeRecord( m_Module, m_Socket, id , data); // cout << "FEC:\t" << id << "\t" << (vmeRecord>>LENGTH) << endl; MucFec aFec( id, stripOrder, part, segment, layer, firstStripID, vmeRecord, chainName ); m_FecVect.push_back( aFec ); } } // END
89157a01e3a3eb4cf3bc380d78696e88700363f9
3e0405e67a035d3b9ce31a6e83bd805b6dc94041
/src/core/arch/x86/Tss.cc
48a4029270793dcdba6f895b45b44330a86105db
[ "Apache-2.0" ]
permissive
IntroVirt/IntroVirt
33ec7fab4424656717d6ccb9ee87ba77e8f69b1f
e0953d1c9a12b6e501f6a876a07d188b7b80254a
refs/heads/main
2022-12-22T05:47:27.038862
2022-12-15T22:52:21
2022-12-16T00:50:10
339,445,106
46
10
Apache-2.0
2022-12-08T17:01:42
2021-02-16T15:37:13
C++
UTF-8
C++
false
false
1,438
cc
Tss.cc
/* * Copyright 2021 Assured Information Security, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <introvirt/core/arch/x86/Registers.hh> #include <introvirt/core/arch/x86/Tss.hh> #include <introvirt/core/domain/Vcpu.hh> #include <introvirt/core/memory/guest_ptr.hh> namespace introvirt { namespace x86 { guest_ptr<void> Tss::sp0() const { const Registers& registers = vcpu_.registers(); auto tr = registers.tr(); // On both 32-bit and 64-bit, the value is held at base + 4 uint64_t pSp0 = tr.base() + 4; uint64_t sp0; if (vcpu_.registers().efer().lme()) { // 64-bit mode sp0 = *guest_ptr<uint64_t>(vcpu_, pSp0); } else { // 32-bit mode sp0 = *guest_ptr<uint32_t>(vcpu_, pSp0); } return guest_ptr<void>(vcpu_, sp0); } Tss::Tss(const Vcpu& vcpu) : vcpu_(vcpu) {} Tss::~Tss() = default; } // namespace x86 } // namespace introvirt
c4ad8b247bf32bc6f5eab55200b201699d6a0536
e018d8a71360d3a05cba3742b0f21ada405de898
/Client/Packet/SubVampireSkillInfo.h
c7a79c3991308d530d24d414c9fa3a8a15c9602a
[]
no_license
opendarkeden/client
33f2c7e74628a793087a08307e50161ade6f4a51
321b680fad81d52baf65ea7eb3beeb91176c15f4
refs/heads/master
2022-11-28T08:41:15.782324
2022-11-26T13:21:22
2022-11-26T13:21:22
42,562,963
24
18
null
2022-11-26T13:21:23
2015-09-16T03:43:01
C++
UHC
C++
false
false
2,134
h
SubVampireSkillInfo.h
//---------------------------------------------------------------------- // // Filename : SubVampireSkillInfo.h // Written By : elca // Description : // //---------------------------------------------------------------------- #ifndef __SUB_VAMPIRE_SKILL_INFO_H__ #define __SUB_VAMPIRE_SKILL_INFO_H__ // include files #include "Types.h" #include "Exception.h" #include "SocketInputStream.h" #include "SocketOutputStream.h" //---------------------------------------------------------------------- // // Inventory 정보를 담고 있는 객체. // // GCUpdateInfo 패킷에 담겨서 클라이언트에게 전송된다. // 아이템이나 걸려있는 마법 같은 정보는 담겨있지 않다. // //---------------------------------------------------------------------- class SubVampireSkillInfo { public : // read data from socket input stream void read ( SocketInputStream & iStream ) throw ( ProtocolException , Error ); // write data to socket output stream void write ( SocketOutputStream & oStream ) const throw ( ProtocolException , Error ); // get size of object uint getSize () const throw () { return szSkillType + szTurn + szTurn; } // get max size of object static uint getMaxSize () throw () { return szSkillType + szTurn + szTurn; } #ifdef __DEBUG_OUTPUT__ // get debug std::string std::string toString () const throw (); #endif public : // get / set SkillType SkillType_t getSkillType() const throw() { return m_SkillType; } void setSkillType( SkillType_t SkillType ) throw() { m_SkillType = SkillType; } // get / set Turn Turn_t getSkillTurn() const throw() { return m_Interval ; } void setSkillTurn( Turn_t SkillTurn ) throw() { m_Interval = SkillTurn; } // get / set CastingTime Turn_t getCastingTime() const throw() { return m_CastingTime; } void setCastingTime( Turn_t CastingTime ) throw() { m_CastingTime = CastingTime; } private : // 스킬 타입 SkillType_t m_SkillType; // 한번쓰고 다음에 쓸 딜레이 Turn_t m_Interval; // 캐스팅 타임 Turn_t m_CastingTime; }; #endif
33a3c9e770fc176cf8487f3edb10cbebfafa59bb
e47af45932cb22b98ed24290125c4a07f733fb1f
/src/components/gates/ComponentOR.cpp
b83fc87888fff3bcc3723246edb6d11f2ada32b8
[]
no_license
lmallez/cpp_nanotekspice
67e1af235ad6ea50b8517b8a491b15a26f4b0943
a6bdfaf697132d1747f9d8ae211529a64870105b
refs/heads/master
2020-03-09T12:28:48.832123
2018-03-04T22:19:48
2018-03-04T22:19:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
591
cpp
ComponentOR.cpp
// // EPITECH PROJECT, 2018 // cpp_nanotekspice // File description: // ComponentOR.cpp // #include "ComponentOR.hpp" nts::ComponentOR::ComponentOR(std::string name) : AGate(name, 3) { _pin.push_back(new PinComponentIn(this)); _pin.push_back(new PinComponentIn(this)); _pin.push_back(new PinComponentOut(this));} nts::ComponentOR::~ComponentOR() { } nts::IComponent *nts::ComponentOR::clone(std::string name) const { return new ComponentOR(name); } void nts::ComponentOR::execute() { if (!tryExecution()) return; _pin[2]->setStatus(_pin[0]->compute() | _pin[1]->compute()); }
ced3f9b24a3e3e28e37e608c4f8e611807f83079
24cb2f3077d7be088ff4af406455c05a076391cc
/EmptyProject/first_game_page.cpp
4f4d6f9e47d682a96dae4ed81ed29b2022e84980
[]
no_license
yj310/DirectXGamePractice_210405
673dd68eb223191b7bdfbd9873058d845a1b7fc2
2c6ac62c4aa99e0fd7ea2c4614c03e57b345b21a
refs/heads/main
2023-04-03T16:14:47.717419
2021-04-11T13:46:14
2021-04-11T13:46:14
354,835,360
0
0
null
null
null
null
UHC
C++
false
false
7,616
cpp
first_game_page.cpp
#include "DXUT.h" #include "first_game_page.h" #include <stack> using namespace std; FirstGamePage::FirstGamePage() { player = new Player(); myLand = 0; backgroundTex = new LPDIRECT3DTEXTURE9(); D3DXCreateTextureFromFileExA( DXUTGetD3D9Device() , "resource/image/firstGame_background.png" , D3DX_DEFAULT_NONPOW2 , D3DX_DEFAULT_NONPOW2 , 0, 0 , D3DFMT_UNKNOWN , D3DPOOL_MANAGED , D3DX_DEFAULT , D3DX_DEFAULT , 0, nullptr, nullptr , backgroundTex); floorTex = new LPDIRECT3DTEXTURE9(); D3DXCreateTextureFromFileExA( DXUTGetD3D9Device() , "resource/image/floor.png" , D3DX_DEFAULT_NONPOW2 , D3DX_DEFAULT_NONPOW2 , 0, 0 , D3DFMT_UNKNOWN , D3DPOOL_MANAGED , D3DX_DEFAULT , D3DX_DEFAULT , 0, nullptr, nullptr , floorTex); maskTex = new LPDIRECT3DTEXTURE9(); D3DXCreateTextureFromFileExA( DXUTGetD3D9Device() , "resource/image/firstGame_mask.png" , D3DX_DEFAULT_NONPOW2 , D3DX_DEFAULT_NONPOW2 , 0, 0 , D3DFMT_UNKNOWN , D3DPOOL_MANAGED , D3DX_DEFAULT , D3DX_DEFAULT , 0, nullptr, nullptr , maskTex); D3DLOCKED_RECT lr; RECT rc = { 0, 0, FLOOR_WIDTH, FLOOR_HEIGHT }; if (SUCCEEDED((*floorTex)->LockRect(0, &lr, &rc, 0))) { DWORD* p = (DWORD*)lr.pBits; memcpy(floorP, p, FLOOR_PIXEL * sizeof(DWORD)); (*floorTex)->UnlockRect(0); } if (SUCCEEDED((*maskTex)->LockRect(0, &lr, &rc, 0))) { DWORD* p = (DWORD*)lr.pBits; memcpy(maskP, p, FLOOR_PIXEL * sizeof(DWORD)); (*maskTex)->UnlockRect(0); } for (int i = 0; i < FLOOR_PIXEL; ++i) { map[i] = MAP_EMPTY; } for (int y = 0; y < FLOOR_HEIGHT; ++y) { map[y * FLOOR_WIDTH + 0] = MAP_EDGE; map[y * FLOOR_WIDTH + FLOOR_WIDTH - 1] = MAP_EDGE; } for (int x = 0; x < FLOOR_WIDTH; ++x) { map[0 * FLOOR_WIDTH + x] = MAP_EDGE; map[(FLOOR_HEIGHT - 1) * FLOOR_WIDTH + x] = MAP_EDGE; } D3DXCreateSprite(DXUTGetD3D9Device(), &spr); D3DXCreateFont(DXUTGetD3D9Device(), 30, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial", &font); MapUpdate(); } FirstGamePage::~FirstGamePage() { (*backgroundTex)->Release(); (*floorTex)->Release(); (*maskTex)->Release(); font->Release(); spr->Release(); delete player; } void FirstGamePage::MapUpdate() { D3DLOCKED_RECT lr; RECT rc = { 0, 0, FLOOR_WIDTH, FLOOR_HEIGHT }; if (SUCCEEDED((*floorTex)->LockRect(0, &lr, &rc, 0))) { DWORD* p = (DWORD*)lr.pBits; for (int i = 0; i < FLOOR_PIXEL; ++i) { if (map[i] == MAP_EMPTY) { p[i] = maskP[i]; } else if (map[i] == MAP_EDGE) { p[i] = D3DCOLOR_ARGB(255, 255, 255, 255); } else if (map[i] == MAP_VISITED) { p[i] = floorP[i]; } else if (map[i] == MAP_VISITING) { p[i] = D3DCOLOR_ARGB(255, 255, 255, 0); } else if (map[i] == MAP_TEMP) { p[i] = D3DCOLOR_ARGB(255, 0, 0, 0, 0); } } (*floorTex)->UnlockRect(0); } } void FirstGamePage::FloodFill() { stack<Point> points; points.push(Point(300, 300)); while (!points.empty()) { Point p = points.top(); points.pop(); if (p.x < 0 || p.x >= FLOOR_WIDTH || p.y < 0 || p.y >= FLOOR_HEIGHT) continue; if (virtualMap[p.y * FLOOR_WIDTH + p.x] == MAP_TEMP) virtualMap[p.y * FLOOR_WIDTH + p.x] = MAP_EMPTY; else continue; points.push(Point(p.x - 1, p.y)); points.push(Point(p.x + 1, p.y)); points.push(Point(p.x, p.y - 1)); points.push(Point(p.x, p.y + 1)); } } void FirstGamePage::Bordering() { for (int y = 0; y < FLOOR_HEIGHT; ++y) { for (int x = 0; x < FLOOR_WIDTH; ++x) { int top_left = map[(y - 1) * FLOOR_WIDTH + x - 1]; int top = map[(y - 1) * FLOOR_WIDTH + x]; int top_right = map[(y - 1) * FLOOR_WIDTH + x + 1]; int left = map[y * FLOOR_WIDTH + x - 1]; int right = map[y * FLOOR_WIDTH + x + 1]; int bottom_left = map[(y + 1) * FLOOR_WIDTH + x - 1]; int bottom = map[(y + 1) * FLOOR_WIDTH + x]; int bottom_right = map[(y + 1) * FLOOR_WIDTH + x + 1]; if (y - 1 >= 0) { if (x - 1 >= 0) { if (top_left == MAP_EMPTY) continue; } if (top == MAP_EMPTY) continue; if (x + 1 < FLOOR_WIDTH) { if (top_right == MAP_EMPTY) continue; } } if (x - 1 >= 0) { if (left == MAP_EMPTY) continue; } if (x + 1 < FLOOR_WIDTH) { if (right == MAP_EMPTY) continue; } if (y + 1 < FLOOR_HEIGHT) { if (x - 1 >= 0) { if (bottom_left == MAP_EMPTY) continue; } if (bottom == MAP_EMPTY) continue; if (x + 1 < FLOOR_WIDTH) { if (bottom_right == MAP_EMPTY) continue; } } map[y * FLOOR_WIDTH + x] = MAP_VISITED; } } } void FirstGamePage::GetLand() { for (int i = 0; i < FLOOR_PIXEL; ++i) { if (map[i] == MAP_EMPTY) virtualMap[i] = MAP_TEMP; else virtualMap[i] = map[i]; } FloodFill(); for (int i = 0; i < FLOOR_PIXEL; ++i) { if (virtualMap[i] == MAP_TEMP) map[i] = MAP_VISITED; else if (virtualMap[i] == MAP_VISITING) map[i] = MAP_EDGE; else map[i] = virtualMap[i]; } Bordering(); myLand = 0; for (int i = 0; i < FLOOR_PIXEL; ++i) { if (map[i] == MAP_VISITED) myLand++; } } void FirstGamePage::PlayerMove(D3DXVECTOR2 dir) { for (int i = 0; i < player->getSpeed(); i++) { int x = player->getPosX(); int y = player->getPosY(); int nextX = x + dir.x; int nextY = y + dir.y; if (nextX >= 0 && nextX < FLOOR_WIDTH && nextY >= 0 && nextY < FLOOR_HEIGHT) { if (map[y * FLOOR_WIDTH + x] == MAP_EDGE && map[nextY * FLOOR_WIDTH + nextX] == MAP_EDGE) { player->move(dir); } else if (map[y * FLOOR_WIDTH + x] == MAP_EDGE && map[nextY * FLOOR_WIDTH + nextX] == MAP_EMPTY && isSpace) { isVisiting = true; visitingX = x; visitingY = y; map[nextY * FLOOR_WIDTH + nextX] = MAP_VISITING; player->move(dir); } else if (map[y * FLOOR_WIDTH + x] == MAP_VISITING && map[nextY * FLOOR_WIDTH + nextX] == MAP_EMPTY && isSpace) { map[nextY * FLOOR_WIDTH + nextX] = MAP_VISITING; player->move(dir); } else if (map[y * FLOOR_WIDTH + x] == MAP_VISITING && map[nextY * FLOOR_WIDTH + nextX] == MAP_EDGE && isSpace) { isVisiting = false; player->move(dir); GetLand(); } } } } void FirstGamePage::KeyInput() { // left if ((GetAsyncKeyState(VK_SPACE) & 0x8000) != 0) { isSpace = true; } else { isSpace = false; if (isVisiting) { isVisiting = false; player->setPos(visitingX, visitingY ); } } // left if ((GetAsyncKeyState(VK_LEFT) & 0x8000) != 0) { PlayerMove({ -1, 0 }); } // right else if ((GetAsyncKeyState(VK_RIGHT) & 0x8000) != 0) { PlayerMove({ 1, 0 }); } // up else if ((GetAsyncKeyState(VK_UP) & 0x8000) != 0) { PlayerMove({ 0, -1 }); } // down else if ((GetAsyncKeyState(VK_DOWN) & 0x8000) != 0) { PlayerMove({ 0, 1 }); } } void FirstGamePage::Update() { player->Update(); KeyInput(); MapUpdate(); } #include <atlconv.h> void FirstGamePage::Render() { D3DXVECTOR3 pos; D3DXVECTOR3 cen; spr->Begin(D3DXSPRITE_ALPHABLEND); spr->Draw(*backgroundTex, nullptr, nullptr, nullptr, D3DCOLOR_ARGB(255, 255, 255, 255)); pos = { (float)GAME_X, (float)GAME_Y, 0 }; spr->Draw(*floorTex, nullptr, nullptr, &pos, D3DCOLOR_ARGB(255, 255, 255, 255)); spr->End(); player->Render(); char text[] = "가나다라마"; int score = myLand; char cscore[256]; sprintf(cscore, "%d", score); USES_CONVERSION; WCHAR* w = A2W(cscore); RECT rc = { 10, 200, 500, 500 }; font->DrawText(NULL, w, -1, &rc, 0, D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f)); }
6e62e96bfd3132332b180ef89dfb47c691f55f27
d0ad8a66f04fce39af58393df458d20eecbf756e
/aplcore/include/apl/touch/utils/velocitytracker.h
c9c1d39364e15a6589d533505306b8bcea5ed784
[ "Apache-2.0" ]
permissive
alexa/apl-core-library
894b17b2aa38bfef3f4df1f2fe2ba1037a89485d
e3a15ae5ad1b85bf7ab3de4bc2e9688dc554e060
refs/heads/master
2023-08-13T20:54:09.374712
2023-07-06T21:24:03
2023-07-06T21:45:49
209,385,722
35
16
Apache-2.0
2021-04-16T17:45:30
2019-09-18T19:14:15
C++
UTF-8
C++
false
false
2,832
h
velocitytracker.h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #ifndef _APL_VELOCITY_TRACKER_H #define _APL_VELOCITY_TRACKER_H #include "apl/common.h" #include "apl/primitives/point.h" #include "apl/utils/ringbuffer.h" namespace apl { struct PointerEvent; /** * Simple extendable velocity estimation strategy interface that acts on base of pointer movement * history. */ class VelocityEstimationStrategy { public: VelocityEstimationStrategy(); virtual ~VelocityEstimationStrategy() = default; /** * Calculate and return estimated interaction velocity. Will take in account previously * calculated velocity if was not reset previously. * @return Pair of X and Y velocities for the interaction. */ virtual Point getEstimatedVelocity() = 0; /** * Add Pointer movement to the history. Limited to predefined value. * @param timestamp event timestamp. * @param position event position. */ void addMovement(apl_time_t timestamp, Point position); /** * Reset internal state and any Movement history. */ void reset(); protected: struct Movement { Movement() = default; Movement(apl_time_t timestamp, Point position) : timestamp(timestamp), position(position) {} apl_time_t timestamp; Point position; }; RingBuffer<Movement> mHistory; float mXVelocity; float mYVelocity; }; /** * Simple velocity tracking interface. */ class VelocityTracker { public: /** * @param rootConfig RootConfig for configuration. */ VelocityTracker(const RootConfig& rootConfig); /** * Process pointer event. * @param pointerEvent event. * @param timestamp event timestamp. */ void addPointerEvent(const PointerEvent& pointerEvent, apl_time_t timestamp); /** * Calculate and return estimated interaction velocity according to selected strategy. * @return Point of X and Y velocities for the interaction. */ Point getEstimatedVelocity(); /** * Reset tracker internal state. */ void reset(); private: std::shared_ptr<VelocityEstimationStrategy> mEstimationStrategy; apl_time_t mLastEventTimestamp; apl_duration_t mPointerInactivityTimeout; }; } // namespace apl #endif //_APL_VELOCITY_TRACKER_H
d877b764703a24775b9f6cb526d1facc5c2fba64
dec4e6d85543706046b6d96f8e7ad2a5641d7b44
/Protocol/objectdescription.cpp
e47a31bfb9721c69ab10ae63ba748c9413bf5eaa
[]
no_license
xorde/xoTools
31c2d734c8e389355f50837fbc0c132dba76f718
aea76df25f6776a8f388ac1130307a9d9d32a614
refs/heads/master
2022-11-10T13:50:58.868177
2020-06-30T14:13:20
2020-06-30T14:13:20
277,187,985
0
0
null
null
null
null
UTF-8
C++
false
false
2,816
cpp
objectdescription.cpp
#include "objectdescription.h" ObjectDescriptionHeaderV2::ObjectDescriptionHeaderV2() { memset(this, 0, sizeof(ObjectDescriptionHeaderV2)); version = 2; _verid = 0xF; } ObjectDescriptionHeaderV3::ObjectDescriptionHeaderV3() { memset(this, 0, sizeof(ObjectDescriptionHeaderV3)); version = 3; _verid = 0xF; } ObjectDescription::ObjectDescription() { } ObjectDescription::ObjectDescription(const QByteArray &ba) { parse(ba); } QString ObjectDescription::flagString() const { QString res = "afdhswrv"; for (int i=0; i<8; i++) { if (!(flags & (1<<i))) res[7-i] = '-'; } return res; } void ObjectDescription::read(QByteArray &ba) const { ba.append(reinterpret_cast<const char*>(this), sizeof(ObjectDescriptionHeaderV3)); ba.append(name.toUtf8()); } bool ObjectDescription::parse(const QByteArray &ba) { if (ba.size() < static_cast<int>(sizeof(ObjectDescriptionHeaderV1))) return false; const ObjectDescriptionHeaderV3 *hdr = reinterpret_cast<const ObjectDescriptionHeaderV3*>(ba.constData()); if (hdr->_verid == 0xF) // new-style descriptor { if (hdr->version == 3) { *static_cast<ObjectDescriptionHeaderV3*>(this) = *hdr; flags = swapRWflags(hdr->flags); const char *namedata = reinterpret_cast<const char*>(hdr + 1); name = QString::fromUtf8(namedata, ba.size() - static_cast<int>(sizeof(ObjectDescriptionHeaderV3))); return true; } else if (hdr->version == 2) { const ObjectDescriptionHeaderV2 *hdr2 = reinterpret_cast<const ObjectDescriptionHeaderV2*>(hdr); id = hdr2->id; group = hdr2->group; // swap read/write info flags = swapRWflags(hdr2->flags); extFlags = hdr2->extFlags; type = hdr2->wType? hdr2->wType: hdr2->rType; size = hdr2->writeSize? hdr2->writeSize: hdr2->readSize; const char *namedata = reinterpret_cast<const char*>(hdr2 + 1); name = QString::fromUtf8(namedata, ba.size() - static_cast<int>(sizeof(ObjectDescriptionHeaderV2))); return true; } } else // old-style descriptor (version 1) { const ObjectDescriptionHeaderV1 *hdr = reinterpret_cast<const ObjectDescriptionHeaderV1*>(ba.constData()); id = hdr->id; // swap read/write info flags = swapRWflags(hdr->flags); type = hdr->wType? hdr->wType: hdr->rType; size = hdr->writeSize? hdr->writeSize: hdr->readSize; const char *namedata = reinterpret_cast<const char*>(hdr + 1); name = QString::fromUtf8(namedata, ba.size() - static_cast<int>(sizeof(ObjectDescriptionHeaderV1))); return true; } return false; }
d2ee36bf251de38b2fb82d6f815f046174ecca3a
e07e3f41c9774c9684c4700a9772712bf6ac3533
/app/Temp/StagingArea/Data/il2cppOutput/System_System_Net_Mail_SmtpException1190166745.h
582554a5d3118c566fbf95da62c52bca33465b7f
[]
no_license
gdesmarais-gsn/inprocess-mobile-skill-client
0171a0d4aaed13dbbc9cca248aec646ec5020025
2499d8ab5149a306001995064852353c33208fc3
refs/heads/master
2020-12-03T09:22:52.530033
2017-06-27T22:08:38
2017-06-27T22:08:38
95,603,544
0
0
null
null
null
null
UTF-8
C++
false
false
1,061
h
System_System_Net_Mail_SmtpException1190166745.h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_Exception1927440687.h" #include "System_System_Net_Mail_SmtpStatusCode887155417.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Net.Mail.SmtpException struct SmtpException_t1190166745 : public Exception_t1927440687 { public: // System.Net.Mail.SmtpStatusCode System.Net.Mail.SmtpException::statusCode int32_t ___statusCode_11; public: inline static int32_t get_offset_of_statusCode_11() { return static_cast<int32_t>(offsetof(SmtpException_t1190166745, ___statusCode_11)); } inline int32_t get_statusCode_11() const { return ___statusCode_11; } inline int32_t* get_address_of_statusCode_11() { return &___statusCode_11; } inline void set_statusCode_11(int32_t value) { ___statusCode_11 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
263c6c9d168234ec759229b38dfeddfde0d2e0aa
90d253b075c47054ab1d6bf6206f37e810330068
/BOI/2018/paths.cpp
badc09b36e5589f184adcf0121053919f6211e46
[ "MIT" ]
permissive
eyangch/competitive-programming
45684aa804cbcde1999010332627228ac1ac4ef8
de9bb192c604a3dfbdd4c2757e478e7265516c9c
refs/heads/master
2023-07-10T08:59:25.674500
2023-06-25T09:30:43
2023-06-25T09:30:43
178,763,969
22
8
null
null
null
null
UTF-8
C++
false
false
826
cpp
paths.cpp
#include <bits/stdc++.h> #define int long long using namespace std; int N, M, K; int c[300000]; vector<int> graph[300000]; int dp[300000][32]; int ans = 0; int dfs(int id, int left){ if(dp[id][left] >= 0){ return dp[id][left]; } dp[id][left] = 0; for(int i : graph[id]){ if(!(left & (1 << c[i]))){ dp[id][left] += dfs(i, left | (1 << c[i])) + 1; } } return dp[id][left]; } signed main(){ cin >> N >> M >> K; for(int i = 0; i < N; i++){ cin >> c[i]; c[i]--; } for(int i = 0; i < M; i++){ int u, v; cin >> u >> v; graph[u-1].push_back(v-1); graph[v-1].push_back(u-1); } fill(dp[0], dp[N-1]+32, -1); for(int i = 0; i < N; i++){ ans += dfs(i, (1 << c[i])); } cout << ans << endl; }
57e47cb5f15727fc4061f5b45225b3952b44d77a
fd57ede0ba18642a730cc862c9e9059ec463320b
/ml/nn/driver/sample/SampleDriver.h
9796a8c3bd7a718af6c549d2b206ca08969e460a
[ "Apache-2.0" ]
permissive
kailaisi/android-29-framwork
a0c706fc104d62ea5951ca113f868021c6029cd2
b7090eebdd77595e43b61294725b41310496ff04
refs/heads/master
2023-04-27T14:18:52.579620
2021-03-08T13:05:27
2021-03-08T13:05:27
254,380,637
1
1
null
2023-04-15T12:22:31
2020-04-09T13:35:49
C++
UTF-8
C++
false
false
10,074
h
SampleDriver.h
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ANDROID_FRAMEWORKS_ML_NN_DRIVER_SAMPLE_SAMPLE_DRIVER_H #define ANDROID_FRAMEWORKS_ML_NN_DRIVER_SAMPLE_SAMPLE_DRIVER_H #include <hwbinder/IPCThreadState.h> #include <memory> #include <string> #include <utility> #include <vector> #include "BufferTracker.h" #include "CpuExecutor.h" #include "HalInterfaces.h" #include "NeuralNetworks.h" namespace android { namespace nn { namespace sample_driver { using hardware::MQDescriptorSync; // Manages the data buffer for an operand. class SampleBuffer : public hal::IBuffer { public: SampleBuffer(std::shared_ptr<ManagedBuffer> buffer, std::unique_ptr<BufferTracker::Token> token) : kBuffer(std::move(buffer)), kToken(std::move(token)) { CHECK(kBuffer != nullptr); CHECK(kToken != nullptr); } hal::Return<hal::ErrorStatus> copyTo(const hal::hidl_memory& dst) override; hal::Return<hal::ErrorStatus> copyFrom(const hal::hidl_memory& src, const hal::hidl_vec<uint32_t>& dimensions) override; private: const std::shared_ptr<ManagedBuffer> kBuffer; const std::unique_ptr<BufferTracker::Token> kToken; }; // Base class used to create sample drivers for the NN HAL. This class // provides some implementation of the more common functions. // // Since these drivers simulate hardware, they must run the computations // on the CPU. An actual driver would not do that. class SampleDriver : public hal::IDevice { public: SampleDriver(const char* name, const IOperationResolver* operationResolver = BuiltinOperationResolver::get()) : mName(name), mOperationResolver(operationResolver), mBufferTracker(BufferTracker::create()) { android::nn::initVLogMask(); } hal::Return<void> getCapabilities(getCapabilities_cb cb) override; hal::Return<void> getCapabilities_1_1(getCapabilities_1_1_cb cb) override; hal::Return<void> getCapabilities_1_2(getCapabilities_1_2_cb cb) override; hal::Return<void> getVersionString(getVersionString_cb cb) override; hal::Return<void> getType(getType_cb cb) override; hal::Return<void> getSupportedExtensions(getSupportedExtensions_cb) override; hal::Return<void> getSupportedOperations(const hal::V1_0::Model& model, getSupportedOperations_cb cb) override; hal::Return<void> getSupportedOperations_1_1(const hal::V1_1::Model& model, getSupportedOperations_1_1_cb cb) override; hal::Return<void> getSupportedOperations_1_2(const hal::V1_2::Model& model, getSupportedOperations_1_2_cb cb) override; hal::Return<void> getNumberOfCacheFilesNeeded(getNumberOfCacheFilesNeeded_cb cb) override; hal::Return<hal::V1_0::ErrorStatus> prepareModel( const hal::V1_0::Model& model, const sp<hal::V1_0::IPreparedModelCallback>& callback) override; hal::Return<hal::V1_0::ErrorStatus> prepareModel_1_1( const hal::V1_1::Model& model, hal::ExecutionPreference preference, const sp<hal::V1_0::IPreparedModelCallback>& callback) override; hal::Return<hal::V1_0::ErrorStatus> prepareModel_1_2( const hal::V1_2::Model& model, hal::ExecutionPreference preference, const hal::hidl_vec<hal::hidl_handle>& modelCache, const hal::hidl_vec<hal::hidl_handle>& dataCache, const hal::CacheToken& token, const sp<hal::V1_2::IPreparedModelCallback>& callback) override; hal::Return<hal::V1_3::ErrorStatus> prepareModel_1_3( const hal::V1_3::Model& model, hal::ExecutionPreference preference, hal::Priority priority, const hal::OptionalTimePoint& deadline, const hal::hidl_vec<hal::hidl_handle>& modelCache, const hal::hidl_vec<hal::hidl_handle>& dataCache, const hal::CacheToken& token, const sp<hal::V1_3::IPreparedModelCallback>& callback) override; hal::Return<hal::V1_0::ErrorStatus> prepareModelFromCache( const hal::hidl_vec<hal::hidl_handle>& modelCache, const hal::hidl_vec<hal::hidl_handle>& dataCache, const hal::CacheToken& token, const sp<hal::V1_2::IPreparedModelCallback>& callback) override; hal::Return<hal::V1_3::ErrorStatus> prepareModelFromCache_1_3( const hal::OptionalTimePoint& deadline, const hal::hidl_vec<hal::hidl_handle>& modelCache, const hal::hidl_vec<hal::hidl_handle>& dataCache, const hal::CacheToken& token, const sp<hal::V1_3::IPreparedModelCallback>& callback) override; hal::Return<hal::DeviceStatus> getStatus() override; hal::Return<void> allocate(const hal::V1_3::BufferDesc& desc, const hal::hidl_vec<sp<hal::V1_3::IPreparedModel>>& preparedModels, const hal::hidl_vec<hal::V1_3::BufferRole>& inputRoles, const hal::hidl_vec<hal::V1_3::BufferRole>& outputRoles, allocate_cb cb) override; // Starts and runs the driver service. Typically called from main(). // This will return only once the service shuts down. int run(); CpuExecutor getExecutor() const { return CpuExecutor(mOperationResolver); } const std::shared_ptr<BufferTracker>& getBufferTracker() const { return mBufferTracker; } protected: std::string mName; const IOperationResolver* mOperationResolver; const std::shared_ptr<BufferTracker> mBufferTracker; }; class SamplePreparedModel : public hal::IPreparedModel { public: SamplePreparedModel(const hal::Model& model, const SampleDriver* driver, hal::ExecutionPreference preference, uid_t userId, hal::Priority priority) : mModel(model), mDriver(driver), kPreference(preference), kUserId(userId), kPriority(priority) { (void)kUserId; (void)kPriority; } bool initialize(); hal::Return<hal::V1_0::ErrorStatus> execute( const hal::V1_0::Request& request, const sp<hal::V1_0::IExecutionCallback>& callback) override; hal::Return<hal::V1_0::ErrorStatus> execute_1_2( const hal::V1_0::Request& request, hal::MeasureTiming measure, const sp<hal::V1_2::IExecutionCallback>& callback) override; hal::Return<hal::V1_3::ErrorStatus> execute_1_3( const hal::V1_3::Request& request, hal::MeasureTiming measure, const hal::OptionalTimePoint& deadline, const hal::OptionalTimeoutDuration& loopTimeoutDuration, const sp<hal::V1_3::IExecutionCallback>& callback) override; hal::Return<void> executeSynchronously(const hal::V1_0::Request& request, hal::MeasureTiming measure, executeSynchronously_cb cb) override; hal::Return<void> executeSynchronously_1_3( const hal::V1_3::Request& request, hal::MeasureTiming measure, const hal::OptionalTimePoint& deadline, const hal::OptionalTimeoutDuration& loopTimeoutDuration, executeSynchronously_1_3_cb cb) override; hal::Return<void> configureExecutionBurst( const sp<hal::V1_2::IBurstCallback>& callback, const MQDescriptorSync<hal::V1_2::FmqRequestDatum>& requestChannel, const MQDescriptorSync<hal::V1_2::FmqResultDatum>& resultChannel, configureExecutionBurst_cb cb) override; hal::Return<void> executeFenced(const hal::Request& request, const hal::hidl_vec<hal::hidl_handle>& wait_for, hal::MeasureTiming measure, const hal::OptionalTimePoint& deadline, const hal::OptionalTimeoutDuration& loopTimeoutDuration, const hal::OptionalTimeoutDuration& duration, executeFenced_cb callback) override; const hal::Model* getModel() const { return &mModel; } private: hal::Model mModel; const SampleDriver* mDriver; std::vector<RunTimePoolInfo> mPoolInfos; const hal::ExecutionPreference kPreference; const uid_t kUserId; const hal::Priority kPriority; }; class SampleFencedExecutionCallback : public hal::IFencedExecutionCallback { public: SampleFencedExecutionCallback(hal::Timing timingSinceLaunch, hal::Timing timingAfterFence, hal::ErrorStatus error) : kTimingSinceLaunch(timingSinceLaunch), kTimingAfterFence(timingAfterFence), kErrorStatus(error) {} hal::Return<void> getExecutionInfo(getExecutionInfo_cb callback) override { callback(kErrorStatus, kTimingSinceLaunch, kTimingAfterFence); return hal::Void(); } private: const hal::Timing kTimingSinceLaunch; const hal::Timing kTimingAfterFence; const hal::ErrorStatus kErrorStatus; }; } // namespace sample_driver } // namespace nn } // namespace android #endif // ANDROID_FRAMEWORKS_ML_NN_DRIVER_SAMPLE_SAMPLE_DRIVER_H
d1d2e8aa9568b46381def7e0cda468bf5093e17c
164c043f88bfeb0157e0a852bd9b41635bba32fa
/MovingPixels/src/testApp.cpp
cb07d2b02d3272a67f004867d3658d4585115d06
[]
no_license
tokujin/MS2Final
507773bb402c1dac6de85d1824b10d052babd351
c7eb9032a89b1a89c883eaa5659f642fedad4c91
refs/heads/master
2016-09-06T10:37:29.793898
2013-05-08T17:18:24
2013-05-08T17:18:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,453
cpp
testApp.cpp
/************************************************************************ * Copyright (c) Nori & Mehdi * * * * * * Written: 2013.05.10 Nori & Mehdi at Parsons * * This is Nori and Mehdi's Project for Major Stuio class at Parsons. * Camera -> oF with OpenCV -> Arduino -> 104 Servos * ************************************************************************/ #include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ ofSetVerticalSync(true); // setup video grabber: video.initGrabber(624, 464); // get the width and height, and allocate color and grayscale images: width = video.width; height = video.height; // videoColorCvImage.allocate(width, height); videoGrayscaleCvImage.allocate(width, height); videoBgImage.allocate(width, height); videoDiffImage.allocate(width, height); modifiedImage.allocate(width, height); // set background color to be white: ofBackground(0, 0, 0); panel.setup("cv settings", 1380, 0, 300, 748); panel.addPanel("control", 1, false); panel.setWhichPanel("control"); panel.setWhichColumn(0); panel.addToggle("learn background ", "B_LEARN_BG", true); panel.addSlider("threshold ", "THRESHOLD", 150, 0, 255, true); panel.loadSettings("cvSettings.xml"); //Serial // arduino users check in arduino app.... mySerial.listDevices(); vector <ofSerialDeviceInfo> deviceList = mySerial.getDeviceList(); mySerial.setup(0, 9600); //open the first device mySerial.setup("tty.usbmodemfd121",9600); pct = 0; //initialize array for (int i = 0; i < 104; i++) { arr[i] = 0x00; } } //-------------------------------------------------------------- void testApp::update(){ //panel panel.update(); bool bLearnBg = panel.getValueB("B_LEARN_BG"); int threshold = panel.getValueI("THRESHOLD"); //video grabber, difference video.update(); if (video.isFrameNew()){ videoColorCvImage.setFromPixels(video.getPixels(), width, height); videoGrayscaleCvImage = videoColorCvImage; if (bLearnBg ){ videoBgImage = videoGrayscaleCvImage; panel.setValueB("B_LEARN_BG", false); } if (ofGetElapsedTimef() < 1.5){ videoBgImage = videoGrayscaleCvImage; } videoDiffImage.absDiff(videoGrayscaleCvImage, videoBgImage); videoDiffImage.threshold(threshold); } //OpenCV int r =0; int n=0; unsigned char * pixels = videoDiffImage.getPixels(); //Compress image(width 624, height 484 to width 13 height 8) for (int i = 0; i < 13; i++){ //devide width into 13 blocks for (int j = 0; j < 8; j++){ //devide height into 8 blocks valuetemp = 0; value=0; // for (int k = 0; k < 48; k+=4) { //pick up the pixels every 4 pixels for (int l = 0; l < 58; l+=4) { //pick up the pixels every 4 pixels valuetemp = valuetemp + pixels[(58*j+l) * width + (48*i+k)]; value = valuetemp / (12 * 15); //calculate the average } } pct = ofMap(value, 0,255, 0,20); // map the average 0 to 20 arr[8*i+j] = pct > 5 ? true : false; //if the average is larger than 5 then the grid is on } } bytesToSend[0] = 255; //set up header byte for serial communication for (int i=0; i<15; i++) { bytesToSend[i+1] = 0; //initialize the bytes to send } //extract boolean data and convert it to byte data for (int i=0; i < 104; i++) { if(arr[i] == true){ bytesToSend[1 + (i/7)] |= (0x00000001 << (i%7)); } } //write serial data mySerial.writeBytes(bytesToSend, 16); //print out! cout << "------------------------------" << endl; for(int i = 0; i < 16; i++){ cout << "bytesToSend[i] "<< " is " << (int)bytesToSend[i] << endl; } } //-------------------------------------------------------------- void testApp::draw(){ ofSetColor(255, 255, 255); videoDiffImage.draw(20,40); panel.draw(); // visualize servo rotation for (int i = 0; i < 104; i++){ if (arr[i]) ofSetColor(255,0,0); else ofSetColor(255); ofRect(624 + 80 + (i/8)*48, 40 + (i%8)*58, 30,30); } } //-------------------------------------------------------------- void testApp::keyPressed(int key){ } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ panel.mouseDragged(x,y,button); } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ panel.mousePressed(x,y,button); } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ panel.mouseReleased(); } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ }
53cd9efed70f48edee62a28014c34d2cfff6689b
9da52aa798484428d4620b115febfafb0cadc756
/dispositif/Cubicle/gestionfichier.cpp
3807be4b3717dce0ae7967571310e799380fc199
[]
no_license
ppff/Cubicle-GUI
83644b5aa10912831f263e766d58733074f93e05
d467d1da91a2fe11704db8a23a90622b69ea054a
refs/heads/master
2021-01-25T05:57:56.645808
2015-06-12T07:15:27
2015-06-12T07:15:27
35,814,339
0
0
null
null
null
null
UTF-8
C++
false
false
2,317
cpp
gestionfichier.cpp
#include "gestionfichier.h" using namespace std; GestionFichier::GestionFichier() { } void GestionFichier::ouvrir(QString empl,Cube c){ QFile file(empl); if(!file.open(QIODevice::ReadWrite | QIODevice::Text)){ qDebug()<<"le fichier n'est pas ouvert"; return; } QTextStream flux(&file); QString x,y,z; QString version=flux.readLine(); // on lit la ligne de la version file.resize(0); flux<<version<<endl; for(int cntP=0;cntP<9;cntP++){ y=QString::number(cntP); for(int cntL=0;cntL<9;cntL++){ z=QString::number(abs(8-cntL)); for(int cntA=0;cntA<9;cntA++){ Led l=c.getList1()->value(cntP).getLed(cntL,cntA); int e=l.getEtat() ; if (e) { x=QString::number(abs(8-cntA)); qDebug()<<"led ("+x+y+z+") allumé "; flux<<x+" "+y+" "+z<<endl; } } } } file.close(); } QString GestionFichier::getLinePlan(int nplan,int nligne,Cube c){ QString str=""; QString x,y,z; y=QString::number(nplan); z=QString::number(nligne); for(int i=0;i<9;i++){ Led l=c.getList1()->value(nplan).getLed(nligne,i); int e=l.getEtat() ; if (e==1) { x=QString::number(i); str+=x+y+z+'\n'; } } return str; } //parser le fichier du motif et renvoyer une liste de vecteurs 3D de leds allumées QList<QVector3D> GestionFichier:: parser(QString empl, QList<QVector3D> list){ QFile file(empl); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){ qDebug()<<"le fichier n'est pas ouvert"; } qDebug()<<"fichier ouvert"; QTextStream flux(&file); QString Line; list.clear(); //lire la première ligne: version Line= flux.readLine()+'\n'; while(!flux.atEnd()){ Line=flux.readLine()+'\n'; if(Line.size()>1){ QString sx=(QString)Line[0]; QString sy=(QString)Line[2]; QString sz=(QString)Line[4]; int x=sx.toInt(0,10); int y=sy.toInt(0,10); int z=sz.toInt(0,10); QVector3D v=QVector3D(x,y,z); list.append(v); } } file.close(); return list; }
793ee8cde7c9fdab19d511b76ba8824a7e611fe6
b07109df165c62585dd217c26ccb62430eb4be25
/DFSandBFS.cpp
a7396df72cc4c6a673457671dae778f2d5e07997
[]
no_license
LakshmiAnuroopaAnala/CPP
1f70209468bda9b920a5caa0e7d43dc1fe4fcf4e
33ec5ea7c2a961182c819602ba8ad1a20a2fc413
refs/heads/main
2023-06-09T19:21:33.679623
2021-07-03T11:09:28
2021-07-03T11:09:28
318,822,589
0
0
null
null
null
null
UTF-8
C++
false
false
708
cpp
DFSandBFS.cpp
#include<bits/stdc++.h> using namespace std; vector<int> adj[10000]; void dfs(int node,int prt) { cout<<node<<" "; for(auto i:adj[node]) { if(i!=prt) { dfs(i,node); } } } void Bfs(int node,int ptr) { queue<pair<int,int>> q; q.push({node,ptr}); while(!q.empty()) { auto it=q.front(); node=it.first; ptr=it.second; q.pop(); cout<<node<<" "; for(auto i:adj[node]) { if(i!=ptr) { q.push({i,node}); } } } } int main() { int i,n,u,v; cin>>n; for(i=0;i<n-1;i++) { cin>>u>>v; adj[u].push_back(v); adj[v].push_back(u); } //dfs(1,0); Bfs(1,0); return 0; } /* 8 1 2 1 3 2 4 2 7 3 8 3 9 9 10 */
d3c525bbe2d41911fcd566edc7992eee6c70e46f
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/UrbanExtreme/inc/states/startmenustate.h
4cc98c990d31e774f89cf3e0e52d43251b63d5d4
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
839
h
startmenustate.h
#ifndef GAMEMENU_H #define GAMEMENU_H #include "application/app.h" #include "application/gamestatehandler.h" #include "gui/nguieventhandler.h" #include "gui/nguicanvas.h" class nGuiBrush; class nGuiTextLabel; class nGuiButton; class GameMenuState : public Application::GameStateHandler, public nGuiEventHandler { public: GameMenuState(); virtual ~GameMenuState(); virtual void OnStateEnter(const nString& prevState); virtual void OnStateLeave(const nString& nextState); virtual void OnAttachToApplication(); virtual nString OnFrame(); void SetupGui(); virtual void HandleEvent(const nGuiEvent& e); nGuiCanvas* guiCanvas; nGuiCanvas* guiCredit; nGuiButton* guiBtGameStart; nGuiButton* guiBtExit; nGuiTextLabel* guiTextLabel; nGuiBrush* guiBrush; }; #endif
50f155ea5eedadff7e1a521e27d104994a6c7bed
1e9c314b4fc20a842f587b56b26eff3f9ce50e8c
/sbml_cvode/example/cpp/vct_sim_ss/QSP_vct_ss.cpp
6504c4470753853b2f8aa906be073acbd5118c40
[ "MIT" ]
permissive
popellab/SPQSP_IO
bd84070f044cfffc702379fdfedccd420b9f996b
eca3ea55ec2f75b0db5d58da09500ddffabc001d
refs/heads/main
2023-06-14T05:40:25.120050
2021-04-27T14:45:26
2021-07-09T14:55:26
384,192,318
0
0
null
null
null
null
UTF-8
C++
false
false
5,541
cpp
QSP_vct_ss.cpp
/* ################################################################################ # # # # # # ################################################################################ */ #include "MolecularModelCVode.h" #include "ODE_system.h" #include "Param.h" #include <iostream> #include <string> #include <algorithm> // min #include <boost/program_options.hpp> #include <boost/filesystem.hpp> // serialization #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/serialization/nvp.hpp> typedef boost::archive::text_iarchive iax; typedef boost::archive::text_oarchive oax; #define SEC_PER_DAY 86400 namespace po = boost::program_options; typedef MolecularModelCVode<CancerVCT::ODE_system> QSP; using CancerVCT::Param; int main(int argc, char* argv[]) { std::string _inputParam; std::string _outPath; std::string _outfile; std::string _savePath; std::string _loadFile; bool _save_stats = false; bool _save_steady_state = false; bool _load_steady_state = false; bool _use_resection = false; // command line options try { po::options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") ("input-file,i", po::value<std::string>(&_inputParam), "parameter file name") ("output-path,o", po::value<std::string>(&_outPath), "output file path") ("output-file-name,n", po::value<std::string>(&_outfile), "output file name") ("save-path,s", po::value<std::string>(&_savePath), "folder to save steady state serialization") ("load-file,l", po::value<std::string>(&_loadFile), "file to load steady state serialization from") ("use-resection,r", po::bool_switch(&_use_resection), "to perform resection") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << "\n"; return 0; } if (!vm.count("input-file")) { std::cout << desc << "\n"; std::cerr << "no input file specified!\n"; return 1; } if (vm.count("output-file-name")) { _save_stats = true; if (!vm.count("output-path")) { std::cout << desc << "\n"; std::cerr << "Output path not specified" << std::endl; return 1; } } if (vm.count("save-path")) { _save_steady_state = true; CancerVCT::ODE_system::use_steady_state = true; } if (vm.count("load-file")) { _load_steady_state = true; } if (_save_steady_state && _load_steady_state) { std::cout << desc << "\n"; std::cerr << "Cannot do both save and load steady-states" << " in the same simulation" << std::endl; return 1; } }catch (std::exception& e) { std::cerr << "error: " << e.what() << "\n"; return 1; } std::ofstream f; // output file if (_save_stats) { boost::filesystem::path pOut(_outPath); boost::filesystem::create_directories(pOut);// create output directory std::string output_file_name = _outPath + "/" + _outfile; f.open(output_file_name, std::ios::trunc); } // parameters Param params; params.initializeParams(_inputParam); CancerVCT::ODE_system::setup_class_parameters(params); if (_use_resection) { CancerVCT::ODE_system::use_resection = true; } // simulation object QSP model; // update variables from parameter file model.getSystem()->setup_instance_tolerance(params); model.getSystem()->setup_instance_varaibles(params); model.getSystem()->eval_init_assignment(); int nTeff = 2;//cent.Teff // load steady-state variable if (_load_steady_state) { // deserialize QSP model_ss; std::ifstream in_save_ss; in_save_ss.open(_loadFile); iax iaState(in_save_ss); iaState >> BOOST_SERIALIZATION_NVP(model_ss); in_save_ss.close(); // copy species values unsigned int n = model_ss.getSystem()->get_num_variables(); for (size_t i = 0; i < n; i++) { double v = model_ss.getSystem()->getSpeciesVar(i); model.getSystem()->setSpeciesVar(i, v); } model.getSystem()->eval_init_assignment(); model.getSystem()->updateVar(); } //std::cout << "resection: " << CancerVCT::ODE_system::use_resection << std::endl; // header if (_save_stats) { f << "t" << model.getSystem()->getHeader() << std::endl; } // solve ODE system double t_start = params.getVal(0) * SEC_PER_DAY; double t_step = params.getVal(1) * SEC_PER_DAY ; int nrStep = int(params.getVal(2)); auto t_end = t_start + t_step * nrStep; f << t_start << model << std::endl; while (t_start < t_end) { double t_remaining = t_end - t_start; double t_step_sim = std::min(t_remaining, t_step); model.solve(t_start, t_step_sim); t_start += t_step_sim; if (_save_stats) { f << t_start << model << std::endl; } //std::cout << t_start / SEC_PER_DAY << std::endl; } if (_save_stats) { f.close(); } // serialization if (_save_steady_state) { boost::filesystem::path pOut(_savePath); boost::filesystem::create_directories(pOut);// create output directory // save std::ofstream out_save; std::string save_file_name = _savePath + "/steady-state.dat"; out_save.open(save_file_name, std::ios::trunc); oax oaState(out_save); //CancerVCT::ODE_system::classSerialize(oaState, 0); oaState << BOOST_SERIALIZATION_NVP(model); out_save.close(); } //std::cout << "End of simulation" << std::endl; return 0; }
4958a7bd9dabbccbabd4705858374d5110e8fbee
8c881345865a01b5c63a5bb076f126403716420c
/easyx-游戏程序范例/打字母/Cla_LivingThings.cxx
0bdb0140cd40e9e132fb56920fdf08da41abd0b8
[]
no_license
Asher-1/C_Plus_Plus-projects
f758df626de074a5a5071c6bf1ae08cfb5c4d2e3
56941f1a76cf1645df5cc0fcb5529eddc64643f2
refs/heads/master
2022-01-28T13:03:24.493838
2019-05-30T13:06:35
2019-05-30T13:06:35
160,189,947
3
2
null
null
null
null
GB18030
C++
false
false
3,156
cxx
Cla_LivingThings.cxx
/*********************************************** //函数名称:Cla_LivingThings类 //函数说明:为活体运动类创建的父类 //函数作者:百度:haha1111111113 //函数版本:1.1.4 //完成时间:2013.4.25 //最后修改时间:2013.5.19 //版权:GPL标准 ***********************************************/ #include "stdafx.h" #include "Cla_LivingThings.h" int Cla_LivingThings::CreateLifeTotalNumber = 0; Cla_LivingThings::Cla_LivingThings() { ActionSpaceBegin_x_coo = 0; ActionSpaceBegin_y_coo = 0; ActionSpaceEnd_x_coo = 0; ActionSpaceEnd_y_coo = 0; now_x_coo = 0; now_y_coo = 0; x_coo_increment = 0; y_coo_increment = 0; last_x_coo = 0; last_y_coo = 0; later_x_coo = now_x_coo + x_coo_increment; later_y_coo = now_y_coo + y_coo_increment; life = true; NaturalDeath = 0; UnnaturalDeath = 0; transmigrate = 0; ++CreateLifeTotalNumber; } Cla_LivingThings::Cla_LivingThings(Cla_GLSMC &GLMsg) { ActionSpaceBegin_x_coo = GLMsg.ActionSpaceBegin_x_coo; ActionSpaceBegin_y_coo = GLMsg.ActionSpaceBegin_y_coo; ActionSpaceEnd_x_coo = GLMsg.ActionSpaceEnd_x_coo; ActionSpaceEnd_y_coo = GLMsg.ActionSpaceEnd_y_coo; now_x_coo = GLMsg.LivingThings_x_coo; now_y_coo = GLMsg.LivingThings_y_coo; x_coo_increment = GLMsg.LivingThings_x_coo_increment; y_coo_increment = GLMsg.LivingThings_y_coo_increment; last_x_coo = 0; last_y_coo = 0; later_x_coo = now_x_coo + x_coo_increment; later_y_coo = now_y_coo + y_coo_increment; life = true; NaturalDeath = 0; UnnaturalDeath = 0; transmigrate = 0; ++CreateLifeTotalNumber; } void Cla_LivingThings::LivingThingsAction() { last_x_coo = now_x_coo; last_y_coo = now_y_coo; now_x_coo += x_coo_increment; now_y_coo += y_coo_increment; later_x_coo = now_x_coo + x_coo_increment; later_y_coo = now_y_coo + y_coo_increment; if(now_x_coo < ActionSpaceBegin_x_coo || now_x_coo > ActionSpaceEnd_x_coo || now_y_coo < ActionSpaceBegin_y_coo || now_y_coo > ActionSpaceEnd_y_coo ) { life = false; } } void Cla_LivingThings::LivingThingsAccident() { life = false; LivingThingsRecord(1,0,0); } void Cla_LivingThings::LivingThingsRecord(int UD,int TS,int CL) { UnnaturalDeath += UD; transmigrate += TS; CreateLifeTotalNumber += CL; NaturalDeath = transmigrate - UnnaturalDeath; } Stru_LTSMC Cla_LivingThings::SendMessageCenter() { Stru_LTSMC LivingThingsInformation; Stru_LTSMC &LTI = LivingThingsInformation; LTI.life = life; LTI.now_x_coo = now_x_coo; LTI.now_y_coo = now_y_coo; LTI.NaturalDeath = NaturalDeath; LTI.UnnaturalDeath = NaturalDeath; LTI.transmigrate = transmigrate; LTI.CreateLifeTotalNumber = CreateLifeTotalNumber; return LTI; } void Cla_LivingThings::GaveLife(Cla_GLSMC &GLMsg) { life = true; ActionSpaceBegin_x_coo = GLMsg.ActionSpaceBegin_x_coo; ActionSpaceBegin_y_coo = GLMsg.ActionSpaceBegin_y_coo; ActionSpaceEnd_x_coo = GLMsg.ActionSpaceEnd_x_coo; ActionSpaceEnd_y_coo = GLMsg.ActionSpaceEnd_y_coo; now_x_coo = GLMsg.LivingThings_x_coo; now_y_coo = GLMsg.LivingThings_y_coo; x_coo_increment = GLMsg.LivingThings_x_coo_increment; y_coo_increment = GLMsg.LivingThings_y_coo_increment; LivingThingsRecord(0,1,1); }
d3cde18e8bc583d45f65438cb0047ea8ac119ed1
fa1ad2e2ac7e376fc7cb3b3a6e1bb88eed3e80be
/dts/inlong/inlong-tubemq/tubemq-client-twins/tubemq-client-cpp/include/tubemq/tubemq_config.h
c5090e0e71dcd3c8d003a6d1a5087ad772e0237a
[ "Apache-2.0", "MIT", "LicenseRef-scancode-compass", "BSD-3-Clause" ]
permissive
alldatacenter/alldata
7bc7713c9f1d56ad6b8e59ea03206d1073b7e047
8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6
refs/heads/master
2023-08-05T07:32:25.442740
2023-08-03T13:17:24
2023-08-03T13:17:24
213,321,771
774
250
Apache-2.0
2023-09-06T17:35:32
2019-10-07T07:36:18
null
UTF-8
C++
false
false
8,576
h
tubemq_config.h
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #ifndef TUBEMQ_CLIENT_CONFIGURE_H_ #define TUBEMQ_CLIENT_CONFIGURE_H_ #include <stdint.h> #include <stdio.h> #include <map> #include <set> #include <string> namespace tubemq { using std::map; using std::set; using std::string; // configure for log, thread pool etc. class TubeMQServiceConfig { public: TubeMQServiceConfig(); ~TubeMQServiceConfig(); void SetLogCofigInfo(int32_t log_max_num, int32_t log_max_size, int32_t log_level, const string& log_path); void SetLogPrintLevel(int32_t log_level); const int32_t GetMaxLogFileNum() const; const int32_t GetMaxLogFileSize() const; const int32_t GetLogPrintLevel() const; const string& GetLogStorePath() const; void SetDnsXfsPeriodInMs(int32_t dns_xfs_period_ms); const int32_t GetDnsXfsPeriodInMs() const; void SetServiceThreads(int32_t timer_threads, int32_t network_threads, int32_t signal_threads); const int32_t GetTimerThreads() const; const int32_t GetNetWorkThreads() const; const int32_t GetSignalThreads() const; const string ToString() const; private: // max log file count int32_t log_num_; // unit MB int32_t log_size_; // 0:trace, 1:debug, 2:info, 3:warn, 4:error int32_t log_level_; // need include log filename string log_path_; int32_t dns_xfs_period_ms_; int32_t timer_threads_; int32_t network_threads_; int32_t signal_threads_; }; class BaseConfig { public: BaseConfig(); ~BaseConfig(); BaseConfig& operator=(const BaseConfig& target); bool SetMasterAddrInfo(string& err_info, const string& master_addrinfo); bool SetTlsInfo(string& err_info, bool tls_enable, const string& trust_store_path, const string& trust_store_password); bool SetAuthenticInfo(string& err_info, bool authentic_enable, const string& usr_name, const string& usr_password); const string& GetMasterAddrInfo() const; bool IsTlsEnabled(); const string& GetTrustStorePath() const; const string& GetTrustStorePassword() const; bool IsAuthenticEnabled(); const string& GetUsrName() const; const string& GetUsrPassWord() const; // set the rpc timout, unit Millis-second, duration [8000, 300000], // default 15000 Millis-seconds; void SetRpcReadTimeoutMs(int32_t rpc_read_timeout_ms); int32_t GetRpcReadTimeoutMs(); // Set the duration of the client's heartbeat cycle, in Millis-seconds, // the default is 10000 Millis-seconds void SetHeartbeatPeriodMs(int32_t heartbeat_period_ms); int32_t GetHeartbeatPeriodMs(); void SetMaxHeartBeatRetryTimes(int32_t max_heartbeat_retry_times); int32_t GetMaxHeartBeatRetryTimes(); void SetHeartbeatPeriodAftFailMs(int32_t heartbeat_period_afterfail_ms); int32_t GetHeartbeatPeriodAftFailMs(); const string ToString() const; private: string master_addrinfo_; // user authenticate bool auth_enable_; string auth_usrname_; string auth_usrpassword_; // TLS configuration bool tls_enabled_; string tls_trust_store_path_; string tls_trust_store_password_; // other setting int32_t rpc_read_timeout_ms_; int32_t heartbeat_period_ms_; int32_t max_heartbeat_retry_times_; int32_t heartbeat_period_afterfail_ms_; }; enum ConsumePosition { kConsumeFromFirstOffset = -1, kConsumeFromLatestOffset = 0, kComsumeFromMaxOffsetAlways = 1 }; // enum ConsumePosition class ConsumerConfig : public BaseConfig { public: ConsumerConfig(); ~ConsumerConfig(); ConsumerConfig& operator=(const ConsumerConfig& target); bool SetGroupConsumeTarget(string& err_info, const string& group_name, const set<string>& subscribed_topicset); bool SetGroupConsumeTarget(string& err_info, const string& group_name, const map<string, set<string> >& subscribed_topic_and_filter_map); bool SetGroupConsumeTarget(string& err_info, const string& group_name, const map<string, set<string> >& subscribed_topic_and_filter_map, const string& session_key, uint32_t source_count, bool is_select_big, const map<string, int64_t>& part_offset_map); bool IsBoundConsume() const { return is_bound_consume_; } const string& GetSessionKey() const { return session_key_; } const uint32_t GetSourceCount() const { return source_count_; } bool IsSelectBig() const { return is_select_big_; } const map<string, int64_t>& GetPartOffsetInfo() const { return part_offset_map_; } const string& GetGroupName() const; const map<string, set<string> >& GetSubTopicAndFilterMap() const; void SetConsumePosition(ConsumePosition consume_from_where); const ConsumePosition GetConsumePosition() const; const int32_t GetMsgNotFoundWaitPeriodMs() const; // SetMaxPartCheckPeriodMs() use note: // The value range is [negative value, 0, positive value] and the value directly determines // the behavior of the TubeMQConsumer.GetMessage() function: // 1. if it is set to a negative value, it means that the GetMessage() calling thread will // be blocked forever and will not return until the consumption conditions are met; // 2. if If it is set to 0, it means that the GetMessage() calling thread will only block // the ConsumerConfig.GetPartCheckSliceMs() interval when the consumption conditions // are not met and then return; // 3. if it is set to a positive number, it will not meet the current user usage (including // unused partitions or allocated partitions, but these partitions do not meet the usage // conditions), the GetMessage() calling thread will be blocked until the total time of // ConsumerConfig.GetMaxPartCheckPeriodMs expires void SetMaxPartCheckPeriodMs(int32_t max_part_check_period_ms); const int32_t GetMaxPartCheckPeriodMs() const; void SetPartCheckSliceMs(uint32_t part_check_slice_ms); const uint32_t GetPartCheckSliceMs() const; void SetMsgNotFoundWaitPeriodMs(int32_t msg_notfound_wait_period_ms); const int32_t GetMaxSubinfoReportIntvl() const; void SetMaxSubinfoReportIntvl(int32_t max_subinfo_report_intvl); bool IsRollbackIfConfirmTimeout(); void setRollbackIfConfirmTimeout(bool is_rollback_if_confirm_timeout); const int32_t GetWaitPeriodIfConfirmWaitRebalanceMs() const; void SetWaitPeriodIfConfirmWaitRebalanceMs(int32_t reb_confirm_wait_period_ms); const int32_t GetMaxConfirmWaitPeriodMs() const; void SetMaxConfirmWaitPeriodMs(int32_t max_confirm_wait_period_ms); const int32_t GetShutdownRebWaitPeriodMs() const; void SetShutdownRebWaitPeriodMs(int32_t wait_period_when_shutdown_ms); const string ToString() const; private: bool setGroupConsumeTarget(string& err_info, bool is_bound_consume, const string& group_name, const map<string, set<string> >& subscribed_topic_and_filter_map, const string& session_key, uint32_t source_count, bool is_select_big, const map<string, int64_t>& part_offset_map); private: string group_name_; map<string, set<string> > sub_topic_and_filter_map_; bool is_bound_consume_; string session_key_; uint32_t source_count_; bool is_select_big_; map<string, int64_t> part_offset_map_; ConsumePosition consume_position_; int32_t max_subinfo_report_intvl_; int32_t max_part_check_period_ms_; uint32_t part_check_slice_ms_; int32_t msg_notfound_wait_period_ms_; bool is_rollback_if_confirm_timout_; int32_t reb_confirm_wait_period_ms_; int32_t max_confirm_wait_period_ms_; int32_t shutdown_reb_wait_period_ms_; }; class ProducerConfig : public BaseConfig { public: ProducerConfig(); ~ProducerConfig(); private: set<string> pub_topics_; }; } // namespace tubemq #endif // TUBEMQ_CLIENT_CONFIGURE_H_
769bb0506befe5019433ae581c8b19f8b04f7614
0ac7f4132bede7a860c5dd3e22622f1f1d26e0dd
/lib/sdl_main.hpp
20670206a817e58f67f22ad337d272318193b120
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
adityaIyerramesh98/glvis
d93b7d86eaa39430ecf18855fd6a7b1d2db0e2ff
9b5587eedf796dffd657a0bd8b327256cb5a6e7d
refs/heads/master
2023-07-16T00:38:53.076195
2021-07-23T05:58:11
2021-07-23T05:58:11
388,872,217
1
0
BSD-3-Clause
2021-07-23T17:08:29
2021-07-23T17:08:27
null
UTF-8
C++
false
false
4,482
hpp
sdl_main.hpp
// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-443271. // // This file is part of the GLVis visualization tool and library. For more // information and source code availability see https://glvis.org. // // GLVis is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #ifndef GLVIS_SDL_MAIN_HPP #define GLVIS_SDL_MAIN_HPP #include <atomic> #include <set> #include <condition_variable> #include "sdl.hpp" class SdlMainThread { private: using Handle = SdlWindow::Handle; public: SdlMainThread(); ~SdlMainThread(); // If called, all SDL window operations are run immediately; this is for // running in a single-threaded mode. void SetSingleThread() { sdl_multithread = false; } bool SdlInitialized() const { return sdl_init; } Uint32 GetCustomEvent() const { return glvis_event_type; } // Handles all SDL operations that are expected to be handled on the main // SDL thread (i.e. events and window creation) void MainLoop(bool server_mode); // Dequeues all incoming events from SDL, and queues them up to their // matching windows. Intended to be called only in single-threaded mode. void DispatchSDLEvents(); // Executed from a window worker thread. Returns a handle to a new window // and associated OpenGL context. Handle GetHandle(SdlWindow* wnd, const std::string& title, int x, int y, int w, int h, bool legacyGlOnly); // Executed from a window worker thread. Deletes a handle to a window and // the corresponding OpenGL context. void DeleteHandle(Handle to_delete); // Issues a command on the main thread to set the window title. void SetWindowTitle(const Handle& handle, std::string title); // Issues a command on the main thread to set the window size. void SetWindowSize(const Handle& handle, int w, int h); // Issues a command on the main thread to set the window position. void SetWindowPosition(const Handle& handle, int x, int y); // Wakes up the main thread, if sleeping. void SendEvent() { std::unique_lock<std::mutex> platform_lk{event_mtx}; event_cv.wait(platform_lk, [this]() { return try_create_platform; }); if (platform) { platform->SendEvent(); } } SdlNativePlatform* GetPlatform() const { return platform.get(); } private: struct CreateWindowCmd; struct SdlCtrlCommand; enum class SdlCmdType { None, Create, Delete, SetTitle, SetSize, SetPosition }; void queueWindowEvent(SdlCtrlCommand cmd); template<typename T> Uint32 getWindowID(const T& eventStruct) { return eventStruct.windowID; } void setWindowIcon(SDL_Window* hwnd); void handleWindowCmdImpl(SdlCtrlCommand& cmd); // Setup the correct OpenGL context flags in SDL for when we actually open the // window. void probeGLContextSupport(bool legacyGlOnly); void getDpi(const Handle& handle, int& wdpi, int& hdpi); void createWindowImpl(CreateWindowCmd& cmd); void handleBackgroundWindowEvent(SDL_WindowEvent e); Uint32 glvis_event_type {(Uint32)-1}; bool sdl_init {false}; bool sdl_multithread {true}; bool server_mode {false}; // A flag indicating whether the main loop will *begin* terminating bool terminating {false}; unique_ptr<SDL_Window, decltype(&SDL_DestroyWindow)> bg_wnd{nullptr, SDL_DestroyWindow}; // ------------------------------------------------------------------------- // Objects for handling passing of window control commands to the main event // loop. mutex window_cmd_mtx; vector<SdlCtrlCommand> window_cmds; int num_windows {-1}; // -1: waiting for window to be created // ------------------------------------------------------------------------- // Objects for handling dispatching events from the main event loop to // worker threads. unordered_map<int, SdlWindow*> hwnd_to_window; unordered_map<int, vector<SDL_Event>> wnd_events; std::set<SDL_FingerID> fingers; bool disable_mouse {false}; mutex gl_ctx_mtx; mutex event_mtx; condition_variable event_cv; bool try_create_platform{false}; unique_ptr<SdlNativePlatform> platform; }; #endif
5c37add1ac5bd32494f6b42d3b494bfdf02edf14
e18f26150849f066fffe2094e3a6f7ac5d431587
/example/access_specifier_base.cpp
6e61c6b03a6145abbdafb7e37302b4d354b270c4
[ "MIT" ]
permissive
HyeockJinKim/WeakKeywordCpp
44a22f46fbe5188eb4f8414e00eca6c4da72d3f3
a4826552d5c4aaca1bef8380961ca587b0d0b6f2
refs/heads/master
2021-06-25T22:28:33.096474
2019-06-02T18:52:14
2019-06-02T18:52:14
129,759,950
5
2
MIT
2019-04-25T15:02:54
2018-04-16T14:51:50
Java
UTF-8
C++
false
false
338
cpp
access_specifier_base.cpp
class A { public: int generate() { return 0; } }; class B : public A { int b; private: bool isA; void go() {} protected: int num(int a, int b) { return a+b; } public: void hello() {} virtual void f() {} }; int main() { A* a = new A; B* b = static_cast<B*>(a); // b->f(); }
e20c986b3c875e2b35cddda0aadc582b05ec3287
b3ff614159b3e0abedc7b6e9792b86145639994b
/math/game-theory/state-graph/keep_moving.cpp
28dd0c3254787110e32492dd5f7cb52cab3c02ca
[]
no_license
s-nandi/contest-problems
828b66e1ce4c9319033fdc78140dd2c240f40cd4
d4caa7f19bf51794e4458f5a61c50f23594d50a7
refs/heads/master
2023-05-01T06:17:01.181487
2023-04-26T00:42:52
2023-04-26T00:42:52
113,280,133
0
0
null
2018-02-09T18:44:26
2017-12-06T06:51:11
C++
UTF-8
C++
false
false
2,300
cpp
keep_moving.cpp
// game theory (dfs on game state graph) // https://toph.co/p/keep-moving #include <bits/stdc++.h> using namespace std; using ll = long long; using vi = vector<int>; #define rep(i, a, b) for(auto i = (a); i < (b); ++i) #define trav(a, x) for(auto& a: x) #define all(a) begin(a),end(a) #define sz(a) (int)a.size() struct edge{int to;}; using graph = vector<vector<edge>>; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; rep(test, 1, T + 1) { int n, m, x; cin >> n >> m >> x; --x; graph g(n), t(n); rep(i, 0, m) { int a, b; cin >> a >> b; --a; --b; g[a].push_back({b}); t[b].push_back({a}); } using state = tuple<int, int>; constexpr int win = 1, lose = -1; auto state_index = [&](int node, int my_turn){return 2 * node + my_turn;}; auto nn = 2 * n; queue<state> q; vi status(nn), outdegree(nn); rep(i, 0, n) { if (g[i].empty()) { status[state_index(i, 1)] = lose; status[state_index(i, 0)] = lose; q.push({i, 1}); q.push({i, 0}); } outdegree[state_index(i, 0)] = sz(g[i]); outdegree[state_index(i, 1)] = sz(g[i]); } while (!q.empty()) { auto [curr, turn] = q.front(); q.pop(); auto index = state_index(curr, turn); for (auto [to]: t[curr]) { auto new_state = state{to, 1 - turn}; auto new_index = state_index(to, 1 - turn); if (status[new_index] == win or status[new_index] == lose) continue; if (status[index] == lose) { status[new_index] = win; q.push(new_state); } else if (status[index] == win){ if (--outdegree[new_index] == 0) { status[new_index] = lose; q.push(new_state); } } } } auto will_win = status[state_index(x, 1)] == win; cout << "Case " << test << ": " << (will_win ? "Yes" : "No") << '\n'; } }
b2756af26114de6a9c76eac22a9c81982c45035f
9a6d93512d40eb7b67c071a68e2e9b1bf66f2df8
/NetworkProject_02/NetworkProject_02/chatDialog.cpp
f6ef5f301be70f77cacc36d7f9b00419ca9ca144
[]
no_license
hyyg123/Multicast-Chatting-Program
959c1efc2916fb6b92dca92688bda4ac3786de40
056a199753f66ac59ee77e684865bff07455561b
refs/heads/master
2016-09-13T23:00:39.089413
2016-05-14T09:56:02
2016-05-14T09:56:02
58,800,843
0
0
null
null
null
null
UHC
C++
false
false
18,180
cpp
chatDialog.cpp
//#pragma comment(lib, "ws2_32") #include "MulticastHandler.h" #include <windows.h> #include <windowsx.h> #include <tchar.h> #include <time.h> #include <chrono> #include <atlstr.h> using namespace std; // 컨트롤들의 아이디값 #define ACC_BTN 10 #define SEND_BTN 11 #define IP_EDIT 100 #define PORT_EDIT 101 #define NICK_EDIT 102 #define MSG_EDIT 103 #define SHOW_TEXT 104 // 컨트롤들의 배치를 위한 정의 #define MARGINE 20 #define EDIT_W 100 #define EDIT_H 20 #define BTN_H 30 #define STEP_HEIGHT 40 // 위도우 크기 #define WIDTH 540 #define HEIGHT 600 // 대화명 중복 플래그 값 #define _OVER "1" // 대화명 중복 경고 문구 #define WARNING "!!! 대화명이 중복됩니다. 변경해주세요! !!!" // // // // 변수 선언 // // // // HINSTANCE hInst; // 인스턴스 공유 MulticastHandler *mulHandler; // 멀티캐스트 핸들러 객체 HANDLE rThread, sThread; // 리시브, 샌드 쓰레드 char ip[20]; // 입력받은 IP 저장 char nickName[50]; // 입력받은 대화명 저장 int port; // 입력받은 포트 저장 char nickCheckInfo[15] = "[nci]"; // 대화명 중복 검사를 위한 패킷 헤더 char nickAckInfo[15] = "[nai]"; // 대화명 중복 여부를 위한 패킷 헤더 char idFlag[10] = "[id]"; // 클라이언트를 구별하기 위한 ID값 (시간으로 구별함) char recMsg[BUFSIZE + 1]; // 수신받은 메시지 버퍼 저장 char sendMsg[BUFSIZE + 1]; // 송신할 메시지 버퍼 char sendNmsg[BUFSIZE + 1]; // 대화명 중복 검사 패킷을 위한 송신 버퍼 int sendFlag = 0; // 전송 플래그, 1이면 전송 int sendFlagNmsg = 0; // 대화명 중복 검사 전송 플래그, 1이면 전송 int isAccess = 0; // 접속 여부 int exitFlag = 0; // 연결 종료 여부 int isExist = 0; // 대화명 중복 여부 unsigned long sendTime; // 클라이언트 구별을 위한 ID값 (시간으로 구별) // IP, PORT, NICKNAME, MSG, SHOW 등의 컨트롤들 HWND ipText, portText, nickText, msgText; HWND ipEdit, portEdit, nickEdit, msgEdit; HWND accServerBtn, sendMsgBtn; HWND showText; // 윈도우 클래스 제목 static TCHAR szWindowClass[] = _T("win32app"); static TCHAR szTitle[] = _T("NetworkProject02"); // 메시지박스 제목 static TCHAR msgTitle[] = _T("경고창"); // 메시지박스 속성 int msgBoxA = MB_OK | MB_ICONERROR; // 동기화 CRITICAL_SECTION cs; // // // // 함수 선언 // // // // LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // 윈도우 이벤트 함수 정의 void _WM_CREATE(HWND, UINT, WPARAM, LPARAM); void _WM_COMMAND(HWND, UINT, WPARAM, LPARAM); // 서버 접속시 쓰이는 함수들 int checkIp(char *); // 아이피 검사 int checkPort(char *); // 포트 검사 int checkAccess(HWND hWnd); // 아이피, 포트 검사 int accessServer(HWND hWnd); // 서버 접속 void setMsg(HWND hWnd); // 송신 메시지 설정 void showMessage(char *msg); // 메시지 출력 DWORD WINAPI ReceiveProcess(LPVOID arg); // 수신 스레드 프로세스 함수 DWORD WINAPI SendProcess(LPVOID arg); // 송신 스레드 프로세스 함수 void sendMyNickInfo(); // 자신의 대화명을 전송 (중복 검사를 위해) void getTime(char *time); // 현재 시간 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // 윈도우 클래스 등록 WNDCLASSEX wndclass; wndclass.cbSize = sizeof(WNDCLASSEX); wndclass.style = CS_HREDRAW | CS_VREDRAW; wndclass.lpfnWndProc = WndProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = hInstance; wndclass.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION)); wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW); wndclass.lpszMenuName = NULL; wndclass.lpszClassName = szWindowClass; wndclass.hIconSm = LoadIcon(wndclass.hInstance, MAKEINTRESOURCE(IDI_APPLICATION)); if (!RegisterClassEx(&wndclass)) { return 1; } hInst = hInstance; // 윈도우 생성 HWND hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, WIDTH, HEIGHT, NULL, NULL, hInstance, NULL); if (!hWnd) return 1; ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); // 메시지 루프 MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return (int) msg.wParam; } LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { PAINTSTRUCT ps; HDC hdc; switch (uMsg) { case WM_GETMINMAXINFO : // 윈도우 크기 고정? ((MINMAXINFO*)lParam)->ptMaxTrackSize.x = WIDTH; ((MINMAXINFO*)lParam)->ptMaxTrackSize.y = HEIGHT; return 0; case WM_CREATE : _WM_CREATE(hWnd, uMsg, wParam, lParam); return 0; case WM_COMMAND : _WM_COMMAND(hWnd, uMsg, wParam, lParam); return 0; case WM_KEYDOWN : return 0; case WM_SIZE : return 0; case WM_CLOSE : DestroyWindow(hWnd); return 0; case WM_DESTROY : PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } // 윈도우 컨트롤 구성 void _WM_CREATE(HWND hWnd, UINT, WPARAM, LPARAM) { // 첫 줄 int firstLineY = MARGINE; // IP주소 텍스트 int ipTextX = MARGINE, ipTextY = firstLineY, ipTextW = 70, ipTextH = EDIT_H; ipText = CreateWindow(L"static", L"IP 주소 :", WS_CHILD | WS_VISIBLE | SS_LEFT, ipTextX, ipTextY, ipTextW, ipTextH, hWnd, (HMENU)0, hInst, NULL); // IP주소 에디트 int ipEditX = ipTextX + ipTextW, ipEditY = firstLineY; int ipEditW = EDIT_W * 2, ipEditH = EDIT_H; ipEdit = CreateWindow(L"edit", NULL, WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_TABSTOP, ipEditX, ipEditY, ipEditW, ipEditH, hWnd, (HMENU)IP_EDIT, hInst, NULL); // 포트 텍스트 int portTextX = ipEditX + ipEditW + MARGINE, portTextY = firstLineY; int portTextW = 90, portTextH = EDIT_H; portText = CreateWindow(L"static", L"포트 번호 :", WS_CHILD | WS_VISIBLE | SS_LEFT, portTextX, portTextY, portTextW, portTextH, hWnd, (HMENU)0, hInst, NULL); // 포트 에디트 int portEditX = portTextX + portTextW, portEditY = firstLineY; int portEditW = EDIT_W, portEditH = EDIT_H; portEdit = CreateWindow(L"edit", NULL, WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_TABSTOP, portEditX, portEditY, portEditW, portEditH, hWnd, (HMENU)PORT_EDIT, hInst, NULL); // 두번째 줄 int secondLineY = firstLineY + STEP_HEIGHT; // 닉네임 텍스트 int nickTextX = MARGINE, nickTextY = secondLineY; int nickTextW = 70, nickTextH = EDIT_H; nickText = CreateWindow(L"static", L"대화명 :", WS_CHILD | WS_VISIBLE | SS_LEFT, nickTextX, nickTextY, nickTextW, nickTextH, hWnd, (HMENU)0, hInst, NULL); // 닉네임 에디트 int nickEditX = nickTextX + nickTextW, nickEditY = secondLineY; int nickEditW = EDIT_W * 2, nickEditH = EDIT_H; nickEdit = CreateWindow(L"edit", NULL, WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_TABSTOP, nickEditX, nickEditY, nickEditW, nickEditH, hWnd, (HMENU)NICK_EDIT, hInst, NULL); // 세번쨰 줄 int thirdLineY = secondLineY + STEP_HEIGHT / 1.5; // 서버 접속 버튼 int accServerBtnX = MARGINE, accServerBtnY = thirdLineY; int accServerBtnW = 480, accServerBtnH = BTN_H; accServerBtn = CreateWindow(L"button", L"서버(채팅방)에 접속하기", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, accServerBtnX, accServerBtnY, accServerBtnW, accServerBtnH, hWnd, (HMENU)ACC_BTN, hInst, NULL); // 네번째 줄 int fourthLineY = thirdLineY + STEP_HEIGHT + MARGINE; // 메시지 텍스트 int msgTextX = MARGINE, msgTextY = fourthLineY; int msgTextW = 70, msgTextH = EDIT_H; msgText = CreateWindow(L"static", L"메시지 :", WS_CHILD | WS_VISIBLE | SS_LEFT, msgTextX, msgTextY, msgTextW, msgTextH, hWnd, (HMENU)0, hInst, NULL); // 메시지 에디트 int msgEditX = msgTextX + msgTextW, msgEditY = fourthLineY; int msgEditW = 410, msgEditH = EDIT_H; msgEdit = CreateWindow(L"edit", NULL, WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_TABSTOP, msgEditX, msgEditY, msgEditW, msgEditH, hWnd, (HMENU)MSG_EDIT, hInst, NULL); // 5번째 줄 int fifthLineY = fourthLineY + STEP_HEIGHT / 1.5; // 메시지 전송 버튼 int sendMsgX = MARGINE, sendMsgY = fifthLineY; int sendMsgW = 480, sendMsgH = BTN_H; sendMsgBtn = CreateWindow(L"button", _T("메시지 전송하기"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, sendMsgX, sendMsgY, sendMsgW, sendMsgH, hWnd, (HMENU)SEND_BTN, hInst, NULL); // 6번째 줄 int sixthLineY = fifthLineY + STEP_HEIGHT; // 받거나 전송한 메시지를 출력할 텍스트 int showTextX = MARGINE, showTextY = sixthLineY; int showTextW = 480, showTextH = 330; showText = CreateWindow(L"edit", NULL, WS_CHILD | WS_VISIBLE | ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_BORDER | WS_VSCROLL, showTextX, showTextY, showTextW, showTextH, hWnd, (HMENU)SHOW_TEXT, hInst, NULL); SetFocus(ipEdit); } // 윈도우 명력에 대한 동작 void _WM_COMMAND(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (LOWORD(wParam)) { case ACC_BTN : // 접속 버튼 동작 if (isAccess) { // 서버 종료 루틴 strcpy(sendMsg, "["); strcat(sendMsg, nickName); strcat(sendMsg, "] 님이 서버와 연결이 종료되었습니다."); sendFlag = 1; Button_SetText(accServerBtn, L"서버(채팅방)에 접속하기"); isAccess = 0; exitFlag = 1; WSACleanup(); break; } if (accessServer(hWnd)) { Button_SetText(accServerBtn, L"서버 연결 종료하기"); isAccess = 1; // 접속 알림 char tempChar[BUFSIZE]; strcpy(tempChar, "["); strcat(tempChar, nickName); strcat(tempChar, "] 님이 접속하셨습니다."); strcpy(sendMsg, tempChar); sendFlag = 1; // 중복 검사를 위해 자신의 대화명 전송 sendMyNickInfo(); } break; case SEND_BTN : // 메시지 전송 버튼 동작 if(isAccess) setMsg(hWnd); else MessageBox(hWnd, L"서버 접속 후 이용해주세요.", msgTitle, msgBoxA); break; case MSG_EDIT : break; } } // 서버 접속 함수 int accessServer(HWND hWnd) { exitFlag = 0; if (!checkAccess(hWnd)) return 0; InitializeCriticalSection(&cs); mulHandler = new MulticastHandler(ip, port, nickName); if (mulHandler->initRecSocket()) { rThread = CreateThread(NULL, 0, ReceiveProcess, (LPVOID)mulHandler->recSocket, 0, NULL); }else { return 0; } if (mulHandler->initSendSocket()) { sThread = CreateThread(NULL, 0, SendProcess, (LPVOID)mulHandler->sendSocket, 0, NULL); }else { return 0; } return 1; } // 메시지 설정 함수 void setMsg(HWND hWnd) { char tempStr1[BUFSIZE + 1], tempStr2[BUFSIZE + 1]; char timeStr[100], nickStr[BUFSIZE + 1]; // 메시지 내용 얻기 GetWindowTextA(msgEdit, (LPSTR)tempStr1, BUFSIZE); // 대화명 얻기 GetWindowTextA(nickEdit, (LPSTR)tempStr2, BUFSIZE); // 대화명 비교 strcpy(nickStr, tempStr2); if (strcmp(nickName, nickStr) != 0) { isExist = 0; char temp[BUFSIZE]; char timeTemp[BUFSIZE]; getTime(timeTemp); // 현재 시간 strcpy(temp, nickName); strcat(temp, " -> "); strcat(temp, nickStr); strcat(temp, " (으)로 대화명을 변경하셨습니다. ["); strcat(temp, timeTemp); strcat(temp, "] \r\n"); strcpy(sendMsg, temp); nickName[0] = '\0'; strcpy(nickName, nickStr); // 중복 검사를 위해 sendMyNickInfo(); } // 현재 시간 구하기 getTime(timeStr); // 문자열 추가 strcat(sendMsg, tempStr2); strcat(sendMsg, " ("); strcat(sendMsg, timeStr); strcat(sendMsg, ") : "); strcat(sendMsg, tempStr1); // 메시지 에디트 비우기 Edit_SetText(msgEdit, L""); sendFlag = 1; // 대화명 중복 경고 if (isExist) { showMessage(WARNING); } } // 수신 스레드 프로세스 함수 DWORD WINAPI ReceiveProcess(LPVOID arg) { SOCKET socket = (SOCKET)arg; while (1) { if (exitFlag) break; int r = mulHandler->receive(recMsg); if (r == 1) { char *p = strstr(recMsg, nickCheckInfo); // 다른 대화명을 받을떄 메시지 char *q = strstr(recMsg, nickAckInfo); // 대화명에 대한 중복 여부 메시지 char *pp = strstr(recMsg, idFlag); // 클라이어트를 구별할 메시지 // 새로 접속하거나 변경한 클에서 보내온 // 대화명을 중복 검사 if (p != NULL) { p = p + strlen(nickCheckInfo); strtok(p, idFlag); pp = pp + strlen(idFlag); char reSendTime[50]; sprintf(reSendTime, "%ld", sendTime); int recPort = atoi(pp); if (strcmp(nickName, p) == 0 && strcmp(reSendTime, pp) != 0) { strcpy(sendNmsg, nickAckInfo); strcat(sendNmsg, "1"); strcat(sendNmsg, idFlag); strcat(sendNmsg, pp); sendFlagNmsg = 1; } } // 중복 검사를 다른 클에게 보낸 후 중복 여부를 받음 if (q != NULL) { q = q + strlen(q); strtok(q, idFlag); pp = pp + strlen(idFlag); char reSendTime[50]; sprintf(reSendTime, "%ld", sendTime); if (strcmp(q, _OVER) && strcmp(reSendTime, pp) == 0) { isExist = 1; showMessage(WARNING); }else { isExist = 0; } } // 일반 채팅 메시지 if(q == NULL && p == NULL){ showMessage(recMsg); } // 소켓 에러 }else if (r == -1) { showMessage("SOCKET ERROR"); } } mulHandler->closeRecSocket(); return 0; } // 송신 스레드 프로세스 함수 DWORD WINAPI SendProcess(LPVOID arg) { SOCKET socket = (SOCKET)arg; int i = 0; while (1) { // 소켓 종료 플래그 if (exitFlag) break; // 일반 메시지 블래그와 메시지 if (sendFlag) { mulHandler->send(sendMsg); sendMsg[0] = '\0'; sendFlag = 0; } // 대화명 중복 검사를 위한 플래그와 메시지 if (sendFlagNmsg) { mulHandler->send(sendNmsg); sendNmsg[0] = '\0'; sendFlagNmsg = 0; } } mulHandler->closeSendSocket(); return 0; } // 메시지를 GUI로 출력하는 함수 void showMessage(char *msg) { char temp[BUFSIZE + 1]; char *ptext, *rtext; int slen = strlen(msg); strcpy(temp, msg); int len = GetWindowTextLengthA(showText); ptext = (char*)malloc(sizeof(char) * (len + 1)); rtext = (char*)malloc(sizeof(char) * (len + BUFSIZE)); GetWindowTextA(showText, ptext, len + 1); strcpy(rtext, ptext); strcat(rtext, temp); strcat(rtext, "\r\n"); SetWindowTextA(showText, rtext); // 스크롤을 아래로 유지 SendMessage(showText, EM_SETSEL, 0, -1); SendMessage(showText, EM_SETSEL, -1, -1); SendMessage(showText, EM_SCROLLCARET, 0, 0); } // IP 포트를 검사하는 함수 int checkAccess(HWND hWnd) { char ipStr[50], portStr[50], nickStr[50]; GetWindowTextA(ipEdit, ipStr, 50); GetWindowTextA(portEdit, portStr, 50); GetWindowTextA(nickEdit, nickStr, 50); if (strlen(ipStr) == 0 || strlen(portStr) == 0 || strlen(nickStr) == 0) { MessageBox(hWnd, L"빈칸이 존재합니다.", msgTitle, msgBoxA); return 0; } int ibool = checkIp(ipStr); if (ibool == 0) { MessageBox(hWnd, L"잘못된 IP 주소입니다.", msgTitle, msgBoxA); return 0; } else if (ibool == -1) { MessageBox(hWnd, L"Class D IP 주소를 이용해주세요.", msgTitle, msgBoxA); return 0; } int pbool = checkPort(portStr); if (pbool == -1) { MessageBox(hWnd, L"포트 번호는 숫자만 입력해주세요.", msgTitle, msgBoxA); return 0; } else if (pbool == 0) { MessageBox(hWnd, L"포트 번호 범위를 넘었습니다.", msgTitle, msgBoxA); return 0; } char tempStr[20]; // 전역 변수로 공유하기 위해 strcpy(ip, ipStr); strcpy(tempStr, portStr); port = atoi(tempStr); strcpy(nickName, nickStr); return 1; } // 아이피 검사 int checkIp(char *ip) { char tempStr[50]; char *dclass; int len; strcpy(tempStr, ip); len = strlen(tempStr); // 마지막이 점일때 if (tempStr[len - 1] == '.') return 0; // 숫자와 점 검사 for (int i = 0; i < len; i++) { char ch = tempStr[i]; if (!(('0' <= ch && ch <= '9') || ch == '.')) { return 0; } } // IP 주소 체크 (0 ~ 255) 검사 dclass = strtok(tempStr, "."); for (int i = 224; i < 240; i++) { char tmpbuf[5]; sprintf(tmpbuf, "%d", i); if ((strcmp(dclass, tmpbuf) == 0)) { dclass = strtok(NULL, "."); int cnt = 0; while (dclass != NULL) { cnt++; int num = atoi(dclass); if (num < 0 || num > 255) { return 0; } dclass = strtok(NULL, "."); } // 길이 검사 if (cnt > 3) return 0; return 1; } } return -1; } // 포트 검사 함수 int checkPort(char *port) { int num; char tempStr[50]; strcpy(tempStr, port); // 문자 여부 검사 for (int i = 0; i < strlen(tempStr); i++) { char ch = tempStr[i]; if (!('0' <= ch && ch <= '9')) return -1; } num = atoi(tempStr); // 범위 검사 if (1024 > num || num > 65535) { return 0; } return 1; } // 중복 검사를 위하여 자신의 대화명을 알리는 함수 void sendMyNickInfo() { sendTime = GetTickCount64(); char tempPort[50]; //ultoa(sendTime, tempPort, 50); sprintf(tempPort, "%ld", sendTime); strcpy(sendNmsg, nickCheckInfo); strcat(sendNmsg, nickName); strcat(sendNmsg, idFlag); strcat(sendNmsg, tempPort); sendFlagNmsg = 1; } // 현재 시간을 구하는 함수 void getTime(char *timeStr) { time_t now; struct tm t; char buf[100]; time(&now); t = *localtime(&now); sprintf(buf, "%d/%02d/%02d %02d:%02d:%02d", t.tm_year + 1990, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec); strcpy(timeStr, buf); }
5333861ba26978d22c573efa4d56b85566842aae
643c81df57fee3f9ddb6596970db9767080c183f
/OOP_Project_04/CUpdater.h
2d1392bd61551d91935f6d85a2d6ff4075031321
[]
no_license
geumkang/Design_Pattern_MFC_Shooting_Game
c96d4f24a8533cb6a76c85e353dd959bf7866ad2
6397965850fcae48d47dad4452be89b75c250330
refs/heads/master
2020-04-09T02:20:50.988194
2018-12-07T09:10:04
2018-12-07T09:10:04
159,937,356
0
1
null
null
null
null
UTF-8
C++
false
false
98
h
CUpdater.h
#pragma once class CUpdater { public: virtual void Update() = 0; virtual void Pause() = 0; };
8d269331a66999a61290979d81ec344b448bb878
bdc27c22522a99b5bff2ec4cfa95fadcba65747d
/source/adios2/engine/ssc/SscReaderNaive.h
5e815a5823fd0661d8becdccdeab8c08a2df592a
[ "Apache-2.0" ]
permissive
ornladios/ADIOS2
a34e257b28adb26e6563b800502266ebb0c9088c
c8b7b66ed21b03bfb773bd972d5aeaaf10231e67
refs/heads/master
2023-08-31T18:11:22.186415
2023-08-29T20:45:03
2023-08-29T20:45:03
75,750,830
243
140
Apache-2.0
2023-09-14T11:15:00
2016-12-06T16:39:55
C++
UTF-8
C++
false
false
1,897
h
SscReaderNaive.h
/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * SscReaderNaive.h * * Created on: Mar 7, 2022 * Author: Jason Wang */ #ifndef ADIOS2_ENGINE_SSCREADERNAIVE_H_ #define ADIOS2_ENGINE_SSCREADERNAIVE_H_ #include "SscReaderBase.h" #include "adios2/core/IO.h" #include <mpi.h> namespace adios2 { namespace core { namespace engine { namespace ssc { class SscReaderNaive : public SscReaderBase { public: SscReaderNaive(IO &io, const std::string &name, const Mode mode, MPI_Comm comm); ~SscReaderNaive() = default; StepStatus BeginStep(const StepMode mode, const float timeoutSeconds, const bool readerLocked) final; size_t CurrentStep() final; void PerformGets() final; void EndStep(const bool readerLocked) final; void Close(const int transportIndex) final; #define declare_type(T) \ std::vector<typename Variable<T>::BPInfo> BlocksInfo(const Variable<T> &variable, \ const size_t step) const final; ADIOS2_FOREACH_STDTYPE_1ARG(declare_type) #undef declare_type std::vector<VariableStruct::BPInfo> BlocksInfo(const VariableStruct &variable, const size_t step) const final; void GetDeferred(VariableBase &, void *) final; private: template <typename T> std::vector<typename Variable<T>::BPInfo> BlocksInfoCommon(const Variable<T> &variable, const size_t step) const; template <class T> void GetDeferredCommon(Variable<T> &variable, T *data); std::unordered_map<std::string, ssc::BlockVec> m_BlockMap; }; } } } } #endif // ADIOS2_ENGINE_SSCREADERNAIVE_H_
5f73517ff8b59e3289c30d381ba67d3c5fb56081
f9c64e4c839c0c7549b5171ea7559a923a7bb0b4
/algo2tp3/usorecursos.cpp
6e18b267e84fdefa0a22d09ddc94989464a65684
[]
no_license
aaronson/AED2
d7ac535d3257be5a50e502c79f8bea13006b00a7
a6bed36787fcb9daee1a34128555f1fd238a61f8
refs/heads/master
2021-01-25T06:05:49.440651
2013-03-16T21:37:20
2013-03-16T21:37:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,306
cpp
usorecursos.cpp
#include "usorecursos.h" Usorecursos::Usorecursos(){ } Usorecursos::Usorecursos(recursos r){ unsigned int n = r.cantElemDistintos(); recursos::iterador it(r.crearIt()); rec* ar = new rec[n]; //cout << r.cardinal(0)<< endl; unsigned int temp = 0; while (it.hayMas()){ temp = it.actual(); ar[temp].total = r.cardinal(temp); //cout << ar[0].total << endl; ar[temp].disponible = ar[temp].total; //cout << ar[0].disponible << endl; it.borrarActual(); } record* ao = new record[n]; for (unsigned int j = 0; j < n; j++){ ao[j].recurso = j; ao[j].disponible = ar[j].disponible; ar[j].orden = j; } int i = (n/2) -1; while (i >= 0){ heapify(ao, i, ar, n); i--; } //cout << ar[0].total << endl; //cout << ar[0].disponible << endl; this->status = ar; this->ordenesConsumo = ao; this->cantRecursos = n; } Usorecursos::~Usorecursos(){ delete status; delete ordenesConsumo; } void Usorecursos::heapify(record ao[], int i, rec ar[], unsigned int n){ if (n > i*2+1){ //cambiado del TP, me aseguro que no entre a posiciones del arreglo invalidas if (n > i*2+2){ //cambiado del TP, me aseguro que no entre a posiciones del arreglo invalidas if (ao[2*i+1].disponible > ao[i].disponible || ao[2*i+2].disponible > ao[i].disponible){ if (ao[2*i+1].disponible > ao[2*i+2].disponible){ swap (ao[i], ao [i*2+1]); ar[ao[i].recurso].orden = i; ar[ao[i*2+1].recurso].orden = i*2+1; heapify (ao, i*2+2, ar, n); } } }else{ if (ao[i*2+1].disponible > ao[i].disponible){ swap (ao[i], ao[i*2+1]); ar[ao[i].recurso].orden = i; ar[ao[i*2+1].recurso].orden = i*2+1; } } } } unsigned int Usorecursos::tiposDeRecurso() const{ return this->cantRecursos; } unsigned int Usorecursos::verTotal(unsigned int r) const{ return this->status[r].total; } unsigned int Usorecursos::disponibilidad(unsigned int r) const{ return this->status[r].disponible; } void Usorecursos::nuevoConsumo (unsigned int r, unsigned int n){ this->status[r].disponible = n; this->ordenesConsumo[this->status[r].orden].disponible = n; this->status[r].orden = n; int i = n; while (i>0){ heapify (this->ordenesConsumo, i, this->status, this->cantRecursos); i = i/2 -1; } } unsigned int Usorecursos::menorConsumo () const{ unsigned int n = this->ordenesConsumo[0].recurso; return (this->status[n].total - this->status[n].disponible); } void Usorecursos::actualizarConsumo (recursos r){ unsigned int n = this->cantRecursos; //unsigned int i = 0; unsigned int rtemp; recursos::iterador it(r.crearIt()); while (it.hayMas()){ rtemp = it.actual(); this->status[rtemp].disponible -= r.cardinal(rtemp); this->ordenesConsumo[this->status[rtemp].orden].disponible += r.cardinal(rtemp); heapify (this->ordenesConsumo, rtemp, this->status, n); it.borrarActual(); } } void Usorecursos::actualizarUso(unsigned int* ar){ unsigned int n = this->cantRecursos; int i = 0; while (i< n){ this->status[i].disponible = ar[i]; this->ordenesConsumo[this->status[i].orden].disponible = ar[i]; i++; } i = n/2 -1; while (i >= 0){ heapify (this->ordenesConsumo, i, this->status, n); i--; } } bool Usorecursos::alcanzanLosRecursos (recursos r) const{ bool res = true; //unsigned int n = this->cantRecursos; //unsigned int i = 0; unsigned int rtemp; recursos::iterador it(r.crearIt()); while (it.hayMas() && res){ rtemp = it.actual(); res = (status[rtemp].disponible >= r.cardinal(rtemp)); it.borrarActual(); } return res; } recursos Usorecursos::multiconjuntizar() const{ recursos res; unsigned int n = this->cantRecursos; unsigned int cant; for (unsigned int i = 0; i < n; i++){ cant = this->status[i].total; while (cant > 0){ res.agregar(i); cant--; } } return res; } recursos Usorecursos::disponiblesEnMulticonj() const{ recursos res; unsigned int n = this->cantRecursos; unsigned int cant; for (unsigned int i = 0; i < n; i++){ cant = this->status[i].disponible; while (cant > 0){ res.agregar(i); cant--; } } return res; } Usorecursos& Usorecursos::operator=( Usorecursos& u){ //delete [] status; //delete [] ordenesConsumo; status = u.status; ordenesConsumo = u.ordenesConsumo; cantRecursos = u.cantRecursos; u.status = NULL; u.ordenesConsumo = NULL; return *this; }
d05c0c5ab23206d07d9a02856b0f7dc3be22c053
fab6f199e628aaa2e5e06fb3d0c9a50ea60edbfc
/codes/14.longest-common-prefix.cpp
0d7eb75d771e0c49bcaf273ed43ee52a97b32516
[]
no_license
sunmiaozju/leetcode
76a389a0ef6b037a980749ca333d455480e5fa63
a7e52930ed5467ca1e500b0af7847ade9b38f165
refs/heads/master
2020-07-21T18:49:43.843343
2020-06-25T15:47:58
2020-06-25T15:47:58
206,946,122
4
0
null
null
null
null
UTF-8
C++
false
false
2,379
cpp
14.longest-common-prefix.cpp
/* * @lc app=leetcode id=14 lang=cpp * * [14] Longest Common Prefix * * https://leetcode.com/problems/longest-common-prefix/description/ * * algorithms * Easy (34.02%) * Likes: 1565 * Dislikes: 1431 * Total Accepted: 525.7K * Total Submissions: 1.5M * Testcase Example: '["flower","flow","flight"]' * * Write a function to find the longest common prefix string amongst an array * of strings. * * If there is no common prefix, return an empty string "". * * Example 1: * * * Input: ["flower","flow","flight"] * Output: "fl" * * * Example 2: * * * Input: ["dog","racecar","car"] * Output: "" * Explanation: There is no common prefix among the input strings. * * * Note: * * All given inputs are in lowercase letters a-z. * */ #include <algorithm> #include <climits> #include <cmath> #include <iostream> #include <string> #include <vector> using namespace std; class Solution { public: // Solution() {} // ~Solution() {} string longestCommonPrefix(vector<string>& strs) { // if (strs.size() == 0) { // return ""; // } // string ans; // int j = 0; // int min = INT_MAX; // for (size_t i = 0; i < strs.size(); i++) { // if (min > strs[i].size()) { // min = strs[i].size(); // } // } // while (j < min) { // size_t i = 0; // char item = strs[i][j]; // for (; i < strs.size(); i++) { // if (strs[i][j] != item) { // return ans; // } // } // ans.push_back(item); // j++; // } // return ans; if (strs.size() == 0) { return ""; } int length = strs.size(); sort(strs.begin(), strs.end()); int min_num = min(strs[0].size(), strs[length - 1].size()); size_t i = 0; for (; i < min_num; i++) { if (strs[0][i] != strs[length - 1][i]) { break; } } return strs[0].substr(0, i); } }; // int main(int argc, const char** argv) // { // Solution ss; // vector<string> vec; // vec.push_back("flower"); // vec.push_back("flowe"); // vec.push_back("flow"); // ss.longestCommonPrefix(vec); // return 0; // }
cce80ea032736c165eef996ffed7b34e4017ab3f
de9adb25cc3e3cff81249d809ea198f9d55c28e4
/src/node.cc
4261a7a8bef542c383f3f4490e97c173dbf22240
[ "MIT" ]
permissive
ethz-asl/rgbd_segmentation
6f44c83e16d2e2094f3bceeb03445b0713c4f4bf
daafa0276d7c0d935acec087a7febc45847b53d9
refs/heads/master
2023-09-04T04:40:33.187150
2021-10-19T08:59:48
2021-10-19T08:59:48
157,723,310
10
1
null
null
null
null
UTF-8
C++
false
false
671
cc
node.cc
#include <glog/logging.h> #include "rgbd_segmentation/rgbd_segmentation.h" int main(int argc, char** argv) { std::cout << std::endl << "RGB-D segmentation ROS node - Copyright (c) 2020- " "Margarita Grinvald, Autonomous " "Systems Lab, ETH Zurich." << std::endl << std::endl; ros::init(argc, argv, "rgbd_segmentation_node"); google::InitGoogleLogging(argv[0]); FLAGS_stderrthreshold = 0; ros::NodeHandle nh; ros::NodeHandle nh_private("~"); RGBDSegmentation rgbd_segmentation(nh, nh_private); ros::AsyncSpinner spinner(0); spinner.start(); ros::waitForShutdown(); return 0; }
654a2adeb82d76c33862acbd45da76fab773bd46
93aedbc5300998a5087b17b0370b8dee87c7127b
/libdbapi/SqlConnection.hpp
5863e10befbf127b7b97d59cf10ae36574622e0e
[]
no_license
falquaddoomi/cs118-project1
848c3d5cdb203fe58c8e6cb769d1a209768dc53b
e02e9a307efbac477c9f89d68fc1a423cb1673fc
refs/heads/master
2021-01-16T18:06:01.315683
2013-02-18T07:36:18
2013-02-18T07:36:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,493
hpp
SqlConnection.hpp
#ifndef INCLUDE_up_db_SqlConnection_hpp #define INCLUDE_up_db_SqlConnection_hpp #include "SqlConnection.h" namespace up { namespace db { template <typename TKey, typename TConnection> SqlConnection<TKey, TConnection>::SqlConnection(TConnection const &connection): m_connection(connection), m_pool(m_connection) { } template <typename TKey, typename TConnection> typename SqlConnection<TKey, TConnection>::pool_type const &SqlConnection<TKey, TConnection>::pool() const { return this->m_pool; } template <typename TKey, typename TConnection> typename SqlConnection<TKey, TConnection>::pool_type &SqlConnection<TKey, TConnection>::pool() { return this->m_pool; } template <typename TKey, typename TConnection> typename SqlConnection<TKey, TConnection>::connection_type const *SqlConnection<TKey, TConnection>::operator ->() const { return &this->m_connection; } template <typename TKey, typename TConnection> typename SqlConnection<TKey, TConnection>::connection_type *SqlConnection<TKey, TConnection>::operator ->() { return &this->m_connection; } template <typename TKey, typename TConnection> SqlConnection<TKey, TConnection>::operator connection_type const &() const { return this->m_connection; } template <typename TKey, typename TConnection> SqlConnection<TKey, TConnection>::operator connection_type &() { return this->m_connection; } } // namespace db } // namespace up #endif // INCLUDE_up_db_SqlConnection_hpp
9cf36658913fbe48fb0a234af9afa42e2984a4a2
303e693dd45ded2d65eed959a5aa9e0f9cf49649
/src/cards/CardReader.h
d0e26a1e8537e9fc21a788464e172d902b88b1d1
[]
no_license
jleveau/Uno
1099306a3da957c8571fa5fbb39d8218c458b472
ab24e0f21e08aa2f8c883891f65b3d5691f73d6e
refs/heads/master
2021-01-17T18:30:51.718344
2016-12-20T18:13:19
2016-12-20T18:13:19
71,471,430
0
0
null
null
null
null
UTF-8
C++
false
false
374
h
CardReader.h
// // Created by julien on 09/10/16. // #ifndef GRAPH_CARDREADER_H #define GRAPH_CARDREADER_H #include <string> #include "Card.h" #include "vector" class CardReader { public: std::vector<Card *> *readCards(const std::string path, int &nb_color, int &nb_number); CardReader(); virtual ~CardReader(); protected: private: }; #endif //GRAPH_CARDREADER_H
507a6e870a622e2f6fd502d7eef26cd38a6c4c29
9c250214a3f17c4bff80bc6bd866c4de0b0b38bc
/src/developer/shell/interpreter/src/types.h
33b44dd180ff83ec3eec9251a2d341805eabfcdd
[ "BSD-3-Clause" ]
permissive
sysidos/fuchsia
e4d83bbdeec58e429aa24289a414ddf9dbd60ac3
0c00fd3c78a9c0111af4689f1e038b3926c4dc9b
refs/heads/master
2021-02-15T13:02:02.231060
2020-03-03T22:02:18
2020-03-03T22:02:18
244,899,807
0
0
null
null
null
null
UTF-8
C++
false
false
5,082
h
types.h
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SRC_DEVELOPER_SHELL_INTERPRETER_SRC_TYPES_H_ #define SRC_DEVELOPER_SHELL_INTERPRETER_SRC_TYPES_H_ #include "src/developer/shell/interpreter/src/nodes.h" #include "src/developer/shell/interpreter/src/value.h" namespace shell { namespace interpreter { class TypeUndefined : public Type { public: TypeUndefined() = default; size_t Size() const override { return 0; } bool IsUndefined() const override { return true; } std::unique_ptr<Type> Duplicate() const override; void Dump(std::ostream& os) const override; }; class TypeBuiltin : public Type { public: TypeBuiltin() = default; Variable* CreateVariable(ExecutionContext* context, Scope* scope, NodeId id, const std::string& name) const override; }; class TypeBool : public TypeBuiltin { public: TypeBool() = default; size_t Size() const override { return sizeof(bool); } std::unique_ptr<Type> Duplicate() const override; void Dump(std::ostream& os) const override; }; class TypeChar : public TypeBuiltin { public: TypeChar() = default; size_t Size() const override { return sizeof(uint32_t); } std::unique_ptr<Type> Duplicate() const override; void Dump(std::ostream& os) const override; }; class TypeString : public TypeBuiltin { public: TypeString() = default; size_t Size() const override { return sizeof(String*); } std::unique_ptr<Type> Duplicate() const override; void Dump(std::ostream& os) const override; void GenerateDefaultValue(ExecutionContext* context, code::Code* code) const override; void GenerateStringLiteral(ExecutionContext* context, code::Code* code, const StringLiteral* literal) const override; void LoadVariable(const ExecutionScope* scope, size_t index, Value* value) const override; }; class TypeInt8 : public TypeBuiltin { public: TypeInt8() = default; size_t Size() const override { return sizeof(int8_t); } std::unique_ptr<Type> Duplicate() const override; void Dump(std::ostream& os) const override; }; class TypeUint8 : public TypeBuiltin { public: TypeUint8() = default; size_t Size() const override { return sizeof(uint8_t); } std::unique_ptr<Type> Duplicate() const override; void Dump(std::ostream& os) const override; }; class TypeInt16 : public TypeBuiltin { public: TypeInt16() = default; size_t Size() const override { return sizeof(int16_t); } std::unique_ptr<Type> Duplicate() const override; void Dump(std::ostream& os) const override; }; class TypeUint16 : public TypeBuiltin { public: TypeUint16() = default; size_t Size() const override { return sizeof(uint16_t); } std::unique_ptr<Type> Duplicate() const override; void Dump(std::ostream& os) const override; }; class TypeInt32 : public TypeBuiltin { public: TypeInt32() = default; size_t Size() const override { return sizeof(int32_t); } std::unique_ptr<Type> Duplicate() const override; void Dump(std::ostream& os) const override; }; class TypeUint32 : public TypeBuiltin { public: TypeUint32() = default; size_t Size() const override { return sizeof(uint32_t); } std::unique_ptr<Type> Duplicate() const override; void Dump(std::ostream& os) const override; }; class TypeInt64 : public TypeBuiltin { public: TypeInt64() = default; size_t Size() const override { return sizeof(int64_t); } std::unique_ptr<Type> Duplicate() const override; void Dump(std::ostream& os) const override; }; class TypeUint64 : public TypeBuiltin { public: TypeUint64() = default; size_t Size() const override { return sizeof(uint64_t); } std::unique_ptr<Type> Duplicate() const override; void Dump(std::ostream& os) const override; void GenerateDefaultValue(ExecutionContext* context, code::Code* code) const override; void GenerateIntegerLiteral(ExecutionContext* context, code::Code* code, const IntegerLiteral* literal) const override; void LoadVariable(const ExecutionScope* scope, size_t index, Value* value) const override; }; class TypeInteger : public Type { public: TypeInteger() = default; // TODO(vbelliard): Use the right size when it will be implemented. size_t Size() const override { return 0; } std::unique_ptr<Type> Duplicate() const override; void Dump(std::ostream& os) const override; }; class TypeFloat32 : public TypeBuiltin { public: TypeFloat32() = default; size_t Size() const override { return sizeof(float); } std::unique_ptr<Type> Duplicate() const override; void Dump(std::ostream& os) const override; }; class TypeFloat64 : public TypeBuiltin { public: TypeFloat64() = default; size_t Size() const override { return sizeof(double); } std::unique_ptr<Type> Duplicate() const override; void Dump(std::ostream& os) const override; }; } // namespace interpreter } // namespace shell #endif // SRC_DEVELOPER_SHELL_INTERPRETER_SRC_TYPES_H_
1b49e149e32fa1fb8374d9f190b4e27906fb3e09
7ec5d6bdb52c2693af01686bc8678d951d06429e
/application_kit/Scripter/ScriptWorld/ScriptView.cpp
b36e7a21828769ab250ca21865e04c7621011b69
[ "BSD-2-Clause" ]
permissive
HaikuArchives/BeSampleCode
c3787cc3a5b8134cc73fb0b5428a6276ed3f7e46
ca5a319fecf425a69e944f3c928a85011563a932
refs/heads/haiku
2021-09-12T14:36:35.392130
2018-04-17T16:48:46
2018-04-17T16:48:46
82,111,290
8
6
NOASSERTION
2023-09-09T16:13:53
2017-02-15T22:01:51
C++
UTF-8
C++
false
false
5,014
cpp
ScriptView.cpp
/* ScriptView.cpp Copyright 1997 Be Incorporated, All Rights Reserved. */ /* Copyright 1999, Be Incorporated. All Rights Reserved. This file may be used under the terms of the Be Sample Code License. */ #ifndef SCRIPT_VIEW_H #include "ScriptView.h" #endif #ifndef _ROSTER_H #include <Roster.h> #endif #include <stdio.h> #include <string.h> #include <String.h> #include "PropDump.h" #include "SendPanel.h" const bigtime_t HUGE_TIMEOUT = 1000000; ScriptView::ScriptView(BRect rect, const char *name) : BOutlineListView(rect, name, B_SINGLE_SELECTION_LIST, B_FOLLOW_ALL) { BMessage *msg = new BMessage ('invk'); SetInvocationMessage(msg); } status_t ScriptView::FillList() { const char *name; int32 wincount, viewcount; BMessage reply; BList teams; status_t result; be_roster->GetAppList(&teams); int32 n = teams.CountItems(); for(int32 i=0; i<n; i++){ team_id id = (team_id)teams.ItemAt(i); BMessenger msgr(NULL, id); /* ask for App Name */ BMessage name_msg(B_GET_PROPERTY); name_msg.AddSpecifier("Name"); result = msgr.SendMessage(&name_msg, &reply, HUGE_TIMEOUT, HUGE_TIMEOUT); if(result == B_OK){ //reply.PrintToStream(); result = reply.FindString("result", 0, &name); if(result == B_OK){ BStringItem *app = new BStringItem(name, 0, false); AddItem(app); /* ask for Window Count */ BMessage count_msg(B_COUNT_PROPERTIES); count_msg.AddSpecifier("Window"); result = msgr.SendMessage(&count_msg, &reply, HUGE_TIMEOUT, HUGE_TIMEOUT); if(result == B_OK){ //reply.PrintToStream(); result = reply.FindInt32("result", 0, &wincount); if(result == B_OK){ for(int i=0; i<wincount; i++){ BMessage winname_msg(B_GET_PROPERTY); winname_msg.AddSpecifier("Title"); winname_msg.AddSpecifier("Window", i); result = msgr.SendMessage(&winname_msg, &reply, HUGE_TIMEOUT, HUGE_TIMEOUT); if(result == B_OK){ // reply.PrintToStream(); result = reply.FindString("result", 0, &name); if(result == B_OK){ BStringItem *winname = new BStringItem(name, 1, false); AddItem(winname); } /* count Views */ BMessage view_msg(B_COUNT_PROPERTIES); view_msg.AddSpecifier("View"); view_msg.AddSpecifier("Window", i); result = msgr.SendMessage(&view_msg, &reply, HUGE_TIMEOUT, HUGE_TIMEOUT); if(result == B_OK){ //reply.PrintToStream(); result = reply.FindInt32("result", 0, &viewcount); if(result != B_OK) { // most likely the window is busy continue; } /* ask for View Names */ for(int j=0; j<viewcount; j++){ BMessage viewname_msg(B_GET_PROPERTY); viewname_msg.AddSpecifier("InternalName"); viewname_msg.AddSpecifier("View", j); viewname_msg.AddSpecifier("Window", i); result = msgr.SendMessage(&viewname_msg, &reply, HUGE_TIMEOUT, HUGE_TIMEOUT); if(result != B_OK) break; // reply.PrintToStream(); result = reply.FindString("result", 0, &name); if(result != B_OK) break; BStringItem *viewname = new BStringItem(name, 2, false); AddItem(viewname); } } } } } } } } } return B_OK; } status_t ScriptView::Invoke(BMessage *msg) { const char *name; BMessenger *sendto = new BMessenger; BMessage script_msg(B_GET_PROPERTY); BStringItem *temp; BList teams; BMessage reply; status_t result; script_msg.AddSpecifier("Messenger"); int32 index = CurrentSelection(); BStringItem *item = (BStringItem *)ItemAt(index); if(item->OutlineLevel() == 2){ script_msg.AddSpecifier("View", item->Text()); temp = (BStringItem *)Superitem(item); item = temp; } if(item->OutlineLevel() == 1){ script_msg.AddSpecifier("Window", item->Text()); temp = (BStringItem *)Superitem(item); item = temp; } if(item->OutlineLevel() == 0){ be_roster->GetAppList(&teams); int n = teams.CountItems(); for(int i=0; i<n; i++){ team_id id = (team_id)teams.ItemAt(i); BMessenger msgr(NULL, id); /* ask for App Name */ BMessage name_msg(B_GET_PROPERTY); name_msg.AddSpecifier("Name"); result = msgr.SendMessage(&name_msg, &reply, HUGE_TIMEOUT, HUGE_TIMEOUT); if(result == B_OK){ reply.PrintToStream(); result = reply.FindString("result", 0, &name); if(result == B_OK){ if( strcmp(name, item->Text()) < 1 ){ /* get a messenger for this object */ printf("string compare\n"); script_msg.PrintToStream(); result = msgr.SendMessage(&script_msg, &reply, HUGE_TIMEOUT, HUGE_TIMEOUT); if (result == B_OK){ reply.PrintToStream(); result = reply.FindMessenger("result", sendto); if(result == B_OK){ SendPanel *panel = new SendPanel(sendto); panel->Show(); return B_OK; } } } } } } } return BOutlineListView::Invoke(msg); }
d0d4a7da273664929a766a315598dd4ae04d4158
edbef27bc07015f90dc0ef885a122a7585b38f64
/examples/cpp_models/cooperative_minefield/src/cooperative_minefield/cooperative_minefield.h
827ee5df6dce44e556b12f9860e9c0d7a21d2640
[]
no_license
lounick/despot
f295951039e46b80e3da5362df4aebe5d6c50c18
2434243c4c637c327e577234286dab51730266ad
refs/heads/master
2020-04-05T23:07:03.909936
2016-10-02T16:17:37
2016-10-02T16:17:37
62,072,297
0
0
null
2016-06-27T16:48:38
2016-06-27T16:48:38
null
UTF-8
C++
false
false
1,010
h
cooperative_minefield.h
// // Created by jim on 30/6/2016. // #ifndef DESPOT_COOPERATIVE_MINEFIELD_H #define DESPOT_COOPERATIVE_MINEFIELD_H #include <despot/core/pomdp.h> #include <despot/core/mdp.h> #include "base/base_cooperative_minefield.h" #include <despot/util/coord.h> #include <despot/util/grid.h> namespace despot{ /* ============================================================================= * CooperativeMinefield class * =============================================================================*/ class CooperativeMinefield: public BaseCooperativeMinefield { public: CooperativeMinefield(std::string map); CooperativeMinefield(int size, int mines); bool Step(State& state, double rand_num, int action, double& reward, OBS_TYPE& obs) const; int NumActions() const; double ObsProb(OBS_TYPE obs, const State& state, int action) const; void PrintObs(const State& state, OBS_TYPE observation, std::ostream& out = std::cout) const; }; } // namespace despot #endif //DESPOT_COOPERATIVE_MINEFIELD_H
65c38b0fe0ce323bf3e0c7a2aa08f7d1cae724e4
b351fc983e964ee732946fa300785280d27e6f4e
/Physics/Particle.cpp
97d155ddd6e6a00b419e2fbdd70a4b7404b3110c
[ "Apache-2.0" ]
permissive
sewaiper/Engine2DM
050980fa9dc8b784b692f70b118a65f317a00164
85925295878ccbc351cb4e58becf0a8953dd0dfe
refs/heads/master
2022-12-26T02:15:09.615903
2020-09-23T16:35:31
2020-09-23T16:35:31
298,030,326
0
0
null
null
null
null
UTF-8
C++
false
false
2,906
cpp
Particle.cpp
#include <iostream> #include <cmath> #include <SFML/Graphics.hpp> #include "Vector.hpp" class Particle : public sf::RectangleShape { public: float Mass; float Scale; Vector2 Acceleration; Vector2 Velocity; Vector2 Position; // Forces Vector2 AppForce; Vector2 Frictional; float Drag; float Gravity; Particle (float Mass=1.f, float g=9.81f) : Acceleration (0.f, 0.f), Velocity (0.f, 0.f), Position (0.f, 0.f), Frictional (0.f, 0.f), Drag (0.f), AppForce (0.f, 0.f), Mass (Mass), Scale (1.f) { Gravity = Mass * g; } ~Particle () { } void ApplyForce (Vector2 force) { AppForce += force; } Vector2 CalcNetForce () { Vector2 iDrag (Drag, Drag); Vector2 iFrictional (Frictional); Vector2 iGravity (0.f, Gravity - Drag); Vector2 iDirection = AppForce.direction (); iDrag &= ~iDirection; iFrictional &= ~iDirection; return (AppForce + iFrictional + iDrag + iGravity); } void Integration (float dt) { Vector2 NetForce; NetForce = CalcNetForce(); Acceleration = NetForce / Mass; Velocity = Velocity + (Acceleration * dt); Position = Position + (Velocity * dt) * Scale; setPosition (); } void setPosition () { sf::RectangleShape::setPosition (Position.x, Position.y); } }; class Firework : public Particle { }; int main () { Particle mat0 (1.f); Particle mat1 (3.f); mat0.Scale = 10.f; mat1.Scale = 10.f; mat0.Position.x = 100.f; mat0.Position.y = 10.f; mat0.setPosition (); mat1.Position.x = 120.f; mat1.Position.y = 10.f; mat1.setPosition (); mat0.Drag = 1.f; mat1.Drag = 4.f; mat0.setSize (sf::Vector2f (4.f, 4.f)); mat1.setSize (sf::Vector2f (4.f, 4.f)); mat0.setFillColor (sf::Color::Red); mat1.setFillColor (sf::Color::Green); mat0.ApplyForce (Vector2 (1.f, -2.f)); mat1.ApplyForce (Vector2 (5.f, 0.f)); sf::RenderWindow window (sf::VideoMode (600, 600), "Material"); sf::Event e; sf::Clock clock; float time = 0.f; while (window.isOpen ()) { time += clock.getElapsedTime ().asMicroseconds (); clock.restart (); if (time >= 1000) { time = 0; if ((mat0.Position.y + mat0.getSize ().y) <= 600.f) mat0.Integration (0.001f); if ((mat1.Position.y + mat1.getSize ().y) <= 600.f) mat1.Integration (0.001f); } while (window.pollEvent (e)) { if (e.type == sf::Event::Closed) { window.close (); } } window.clear (); window.draw (mat0); window.draw (mat1); window.display (); } return 0; }
3344280c33f2b00e13fa92af330c8867d4fd6277
83e9408e7a6c21d1357594715f631865142528e6
/oj/hzoj/174.cpp
56682d78bab70565863945931f451a7aeaf03895
[]
no_license
chill-cy/Data-Structure
0027ffbbc10c765f555951c678cf28b89494cb68
b325de5781f9f3f00aec7724dcbbb680b1e5dcc9
refs/heads/master
2022-03-28T15:29:37.437731
2020-01-12T09:01:20
2020-01-12T09:01:20
197,802,813
0
0
null
null
null
null
UTF-8
C++
false
false
583
cpp
174.cpp
/************************************************************************* > File Name: 174.cpp > Author:jiangxiaoyu > Mail:2291372880@qq.com > Created Time: 2019年07月03日 星期三 11时53分14秒 ************************************************************************/ #include<iostream> #include <cstring> #include <string> #include <algorithm> using namespace std; int main() { string str; getline(cin, str); while (str.find(' ') != -1) { int pos = str.find(' '); str = str.replace(pos, 1, "%20"); } cout << str; return 0; }
9dda96d82433eb5dc67c5ba78529331a69261ea2
73607fd03628f5f346cdbcad83b4b4c9619d7c99
/lwr_oro_bridge/src/lwr_oro_bridge-component.hpp
80ecf74c8cfb9cef360c0c5d197bd5124ec8de91
[]
no_license
basti35/lwr_tools
7a8caad42c19639428dcb0a02cee9f79bfe9c306
c8f4b8ec2a9b307ef4d22cfb729ba90d21cbf4d5
refs/heads/master
2016-09-05T19:48:22.952196
2015-07-03T14:50:46
2015-07-03T14:50:46
38,485,933
0
0
null
null
null
null
UTF-8
C++
false
false
3,197
hpp
lwr_oro_bridge-component.hpp
#ifndef OROCOS_LWR_ORO_BRIDGE_COMPONENT_HPP #define OROCOS_LWR_ORO_BRIDGE_COMPONENT_HPP #include <rtt/RTT.hpp> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <kdl/frames.hpp> #include <kdl/frames_io.hpp> #include <lwr_oro_bridge/friComm.h> #include <FRILibrary/FastResearchInterface.h> #include <FRILibrary/LinuxAbstraction.h> #define PI 3.1415926535897932384626433832795 #define NUMBER_OF_JOINTS 7 using namespace std; using namespace RTT; class Lwr_oro_bridge : public RTT::TaskContext{ public: Lwr_oro_bridge(std::string const& name); bool configureHook(); bool startHook(); void updateHook(); void stopHook(); void cleanupHook(); /* example function */ double add(double, double); /* reverse param function vector < double > reverse (vector < double > a); */ private: FastResearchInterface *FRI; // Internal function declarations vector < double > newHometransform( vector < double > tfmtx, vector < double > home ); vector < double > kukaHometransform( vector < double > cmtfmtx, vector < double > home ); vector < double > kdlreverseRPY (vector < double > tfmtx); vector < double > kdldirectRPY (vector < double > frmvec); vector < double > kdlEEbasewrenchtf (vector < double > eewr, vector < double > tfmtx); vector < double > reverse (vector < double > a); // Internal auxiliary variables float floatValuesMJT[FRI_USER_SIZE], floatValuesMEF[6], floatValuesMJP[FRI_USER_SIZE], floatValuesMCP[12]; int ResultValue; uint16_t fri_state_last; float JointValuesInRad[NUMBER_OF_JOINTS]; float Transformatrix[12], Stiff[6], Damp[6]; float JointStiff[7], JointDamp[7]; unsigned int controlScheme; int robotStarted; bool safetyEnabled; const char* statepointer; /*kdl*/ // Internal vectors vector < double > EEframe; vector < double > measCartPos; vector < double > initCartPos; vector < double > FTwrtEE; vector < double > estimExternalCartForces; vector < double > measJointPos; vector < double > desJointPos; vector < double > measJointTorques; vector < double > CommCartPos; vector < double > CommCartStiff; vector < double > CommCartDamp; vector < double > MatrixPos; vector < double > NewHome; vector < double > KukaHome_EEmeastfmtx; vector < double > NewHome_EEcmdtfmtx; // Input ports InputPort < vector < double > > in_desJointPos; InputPort < vector < double > > in_CommCartPos; InputPort < vector < double > > in_CommCartStiff; InputPort < vector < double > > in_CommCartDamp; InputPort < unsigned int > in_controlScheme; // Output ports OutputPort < vector < double > > out_measJointPos; OutputPort < vector < double > > out_measCartPos; OutputPort < vector < double > > out_EEframe; OutputPort < vector < double > > out_measJointTorques; OutputPort < vector < double > > out_estimExternalCartForces; OutputPort < bool > out_safetyEnabled; OutputPort < string > out_FRIstate; OutputPort < int > out_robotStarted; }; #endif