blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
bfe913b96a94c72044b1b1f8f8b88cd708ae1cf4
1fcb517b835343b671b0d70ffc37583b33408f51
/Source/Artemisa/ArtemisaPlayerController.h
762ce8583ca51efe7577456ca335692ec046e2c2
[]
no_license
AdrianFL/Artemisa
5ec13d76d6e3d5404a9ea2177264566e983d9230
ecfb2529a78de765a0f4b8cdfee94376da0e63d6
refs/heads/master
2020-03-26T01:48:32.418640
2018-09-13T20:16:26
2018-09-13T20:16:26
144,383,419
0
0
null
null
null
null
UTF-8
C++
false
false
376
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/PlayerController.h" #include "ArtemisaPlayerController.generated.h" /** * */ UCLASS() class ARTEMISA_API AArtemisaPlayerController : public APlayerController { GENERATED_BODY() public: virtual void BeginPlay() override; };
[ "lga42@gcloud.ua.es" ]
lga42@gcloud.ua.es
f70320f3deb37c1248d3842bb294a10575f3cada
17f791c50ca063770e7ab0fbe6adb6e277518eba
/29. Large and small among 3 numbers.cpp
f55f863809544213c1bdd28fbf2a15d308ffc0eb
[]
no_license
mosroormofizarman/Practice-CPP-Programming-of-Anisul-Islam-Tutorials
376123a94beb3e99343c44f240366fa20899693c
2babd3eb60485693181ce08b5c7763e35ae61be1
refs/heads/main
2023-08-20T00:50:43.082445
2021-10-14T13:21:18
2021-10-14T13:21:18
412,907,927
0
0
null
null
null
null
UTF-8
C++
false
false
1,241
cpp
#include <iostream> #include <conio.h> using namespace std; int main() { int num1, num2, num3; cout << "Enter three integer numbers: "; cin >> num1 >> num2 >> num3; if(num1>num2 && num1>num3 && num2>num3){ cout << num1 << " is the largest , " << num2 << " is the middelest and " << num3 << " is the smallest number."; } else if(num1>num2 && num1>num3 && num3>num2){ cout << num1 << " is the largest , " << num3 << " is the middelest and " << num2 << " is the smallest number."; } else if(num2>num1 && num2>num3 && num3>num1){ cout << num2 << " is the largest , " << num3 << " is the middelest and " << num1 << " is the smallest number."; } else if(num2>num1 && num2>num3 && num1>num3){ cout << num2 << " is the largest , " << num1 << " is the middelest and " << num3 << " is the smallest number."; } else if(num3>num1 && num3>num2 && num1>num2){ cout << num3 << " is the largest , " << num1 << " is the middelest and " << num2 << " is the smallest number."; } else{ cout << num3 << " is the largest , " << num2 << " is the middelest and " << num1 << " is the smallest number."; } getch(); }
[ "noreply@github.com" ]
noreply@github.com
61889c0dd346b70022bac2eeacfbe9710bef3ac4
21a3cf4795b53fa48ece2fac7f50f3bd4bfd1de5
/FP/Sesión 7/Aula/20 - Insercción.cpp
01acf3db988e67c8034832bc6a1846b5614c1064
[]
no_license
xBece/DGIIM
6363ca3cdc4f546cce9ca0c2ce3a62c9ba77ab95
a87a2b09ff06cadec573fba399ef629809984e52
refs/heads/master
2020-04-06T12:37:05.019462
2019-04-14T18:57:55
2019-04-14T18:57:55
157,462,703
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,316
cpp
/* Construir un programa que inserte una cadena de caracteres dentro de otra cadena, en una determinada posición. Por ejemplo, insertar la cadena "caracola" en la posición 2 de la cadena hola, resultaría la segunda cadena con el valor hocaracolala. */ #include <iostream> #include <cstring> using namespace std; int main () { const int MAX_COMP = 100; char cadena_principal [MAX_COMP], cadena_secundaria [MAX_COMP]; int posicion, intervalo, tamanio, i, j = 0; cout << "Este programa insertará una cadena de caracteres introducida en la posición indicada de otra."; cout << "\n\n\t-> Introduzca la cadena principal : "; cin.getline(cadena_principal, MAX_COMP); cout << "\n\t-> Introduzca la cadena que quiera insertar en la anterior : "; cin.getline(cadena_secundaria, MAX_COMP); tamanio = strlen(cadena_secundaria); cout << "\n¿En qué posición de la cadena principal desa introducir la segunda? : "; cin >> posicion; intervalo = posicion + tamanio; for ( i = posicion, j = 0; i < intervalo; i++, j++ ) { cadena_principal [i + tamanio ] = cadena_principal [i]; cadena_principal [i] = cadena_secundaria [j]; } cout << "\nLa cadena final es : " << cadena_principal; cout << "\n\n"; system ("PAUSE"); return 0; }
[ "noreply@github.com" ]
noreply@github.com
9268bbb41a74d668da05d63b9cdfc90a5f0b553e
f582969f9ba001dcb76cdfa07e4e5ac813c69e1c
/Codigo/VideoJuegoInfo/fondosgame.h
38233e785e1d380f41475dc788251d9cf505e4d3
[]
no_license
santiagopr123/Proyecto-Final
1552ccc22905ad43c26459b7b2c4c3a7e6be044e
ecaa281a73bbd8bf0b8157bfadac5f58987fc8d3
refs/heads/master
2023-09-03T22:31:17.521669
2021-10-29T04:22:45
2021-10-29T04:22:45
350,543,206
0
0
null
null
null
null
UTF-8
C++
false
false
281
h
#ifndef FONDOSGAME_H #define FONDOSGAME_H #include <QGraphicsPixmapItem> class FondosGame: public QGraphicsPixmapItem { public: explicit FondosGame(const QPixmap &pixmap, QGraphicsItem *parent = 0); public: virtual QPainterPath shape() const; }; #endif // FONDOSGAME_H
[ "santiagopr@udea.edu.co" ]
santiagopr@udea.edu.co
7f009ce68bf6698c5faba109a2d51ad4b8b910e5
5a2f3d6d61fb2e539b857238be65b139b894cc8d
/Plugins/Runtime/CriWare/CriWare/Source/CriWareRuntime/Classes/AtomSpectrumAnalyzer.h
89ba3b75a067be9597bc28261965816eaae05fe6
[]
no_license
BlueAmulet/NaReRu
e731268423b91659b72c625e5baf3210ab8b4b7e
c593a924b3cb50536f903bbdc62ca096f8d23f2a
refs/heads/master
2023-05-25T16:39:46.859122
2021-01-11T02:44:13
2021-01-11T02:44:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,288
h
/**************************************************************************** * * CRI Middleware SDK * * Copyright (c) 2014-2017 CRI Middleware Co., Ltd. * * Library : CRIWARE plugin for Unreal Engine 4 * Module : Atom Spectrum Analyzer * File : AtomSpectrumAnalyzer.h * ****************************************************************************/ /* 多重定義防止 */ #pragma once /*************************************************************************** * インクルードファイル * Include files ***************************************************************************/ /* Unreal Engine 4関連ヘッダ */ #include "Kismet/BlueprintFunctionLibrary.h" /* CRIWAREプラグインヘッダ */ #include "CriWareApi.h" #include "AtomAsrRack.h" #include "SoundAtomCue.h" #include "AtomComponent.h" #include "SoundAtomConfig.h" /* モジュールヘッダ */ #include "AtomSpectrumAnalyzer.generated.h" /*************************************************************************** * 定数マクロ * Macro Constants ***************************************************************************/ /*************************************************************************** * 処理マクロ * Macro Functions ***************************************************************************/ /*************************************************************************** * データ型宣言 * Data Type Declarations ***************************************************************************/ /*************************************************************************** * 変数宣言 * Prototype Variables ***************************************************************************/ /*************************************************************************** * クラス宣言 * Prototype Classes ***************************************************************************/ UCLASS(meta=(ToolTip = "AtomComponent class.")) class CRIWARERUNTIME_API UAtomSpectrumAnalyzer : public UBlueprintFunctionLibrary { GENERATED_BODY() public: UAtomSpectrumAnalyzer(); /* DSPSpectra作成 */ UFUNCTION(BlueprintCallable, Category="Atom", meta=(UnsafeDuringActorConstruction = "true", ToolTip = "Create Dsp Spectra.")) static void CreateDspSpectra(UAtomAsrRack* asr_rack, FString bus_name, int32 num_bands); /* スペクトル解析結果の出力 */ UFUNCTION(BlueprintCallable, Category="Atom", meta=(UnsafeDuringActorConstruction = "true", ToolTip = "Get spectrum information.")) static void GetLevels(TArray<float>& spectra); /* スペクトル解析結果の出力(デシベル値変換) */ /* display_range:表示範囲(例:display_range=96の場合は-96dB以上の値を格納) */ UFUNCTION(BlueprintCallable, Category="Atom", meta=(UnsafeDuringActorConstruction = "true", ToolTip = "Get spectrum information with converting to decibel value.")) static void GetLevelsDB(float display_range, TArray<float>& spectra); private: static int32 NumBands; }; /*************************************************************************** * 関数宣言 * Prototype Functions ***************************************************************************/
[ "tetosants@tetoravr.com" ]
tetosants@tetoravr.com
a415dc6bc35ffce87836a854c75d879a575bde33
28a705194d2c996fcc47f49c2d56ecd0e8be437e
/线上赛/2017国庆线上赛/ACM10月4日 Anniversary Cake/Anniversary Cake.cpp
a62bb34407699a73284160f8c6605b2b8a3a1389
[]
no_license
guanhuhao/my_project
0741dd2c668a5e5a59d2c22eee238a3c93b7f73d
53b8b2e17c3ef16cb8f1b694cd2996581baaff28
refs/heads/master
2021-07-24T17:06:49.429872
2019-02-04T07:18:30
2019-02-04T07:18:30
141,687,361
0
0
null
null
null
null
UTF-8
C++
false
false
486
cpp
#include<stdio.h> int main() { long i,j,flag=0; double k,b,x1,x2,y1,y2,x,y; scanf("%lf%lf%lf%lf%lf%lf",&x,&y,&x1,&y1,&x2,&y2); for(i=0;i<x;i++) { for(j=0;j<x;j++) { if(j-i==0) { if((i-x1)*(i-x2)<0) { flag=1; break; } else continue; } k=y/(j-i); b=-i*(k); if((y1-k*x1-b)*(y2-k*x2-b)<0) { flag=1; break; } } if(flag==1) break; } printf("%ld 0 %ld %0.f\n",i,j,y); return 0; }
[ "1057368050@qq.com" ]
1057368050@qq.com
bad94a7a4b640fbe77c0ecd9c60e8dd560ef45b7
b209ace562b2fdcfc1e15fb4f95a872fedfd289a
/src/scp/QuorumSetUtils.h
791cd8a495f2b49eac5658e3458112565a705c3e
[ "BSD-3-Clause", "MIT", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
SuperBlockChain/core
b0e8f58649f71747cd249da5835379b8a9728c1e
2216d02c548ab6700c950d6bf1da162f38ff26e2
refs/heads/master
2020-03-07T16:30:14.927588
2018-04-01T01:26:58
2018-04-01T01:26:58
127,584,504
0
0
null
null
null
null
UTF-8
C++
false
false
394
h
// Copyright 2016 SuperBlockChain Development Foundation and contributors. Licensed // under the Apache License, Version 2.0. See the COPYING file at the root // of this distribution or at http://www.apache.org/licenses/LICENSE-2.0 #pragma once namespace snb { struct SCPQuorumSet; bool isQuorumSetSane(SCPQuorumSet const& qSet, bool extraChecks); void normalizeQSet(SCPQuorumSet& qSet); }
[ "pierre@gmail.com" ]
pierre@gmail.com
03f4c7ff3429b94f925cc0a0b28ec5675e9a1da9
3fa2cde31779d810a1cadc3f878cc56b185f9fd1
/IDioms/2일차/18_PolicyClone2_template_template.cpp
a2a22ad76174c0cf5962dd09fe7011abde9b6dbb
[]
no_license
utilForever/Temp
f48668e2a1a4a9d6772fef37411fe293c81808b6
1ef578c1a5ae81ea8151854be855cb91260e3eda
refs/heads/master
2023-07-17T13:00:30.636042
2019-08-28T12:47:27
2021-09-03T01:17:25
74,953,356
3
0
null
null
null
null
UHC
C++
false
false
545
cpp
// template template template<typename T> class list {}; template<typename T, template<typename> class C> class stack { }; int main() { list s1; list<int> s2; stack<int, ? > st; } // template template 을 사용한 allocator의 변경 template<typename T> class allocator { public: T* allocate(int sz) { return new T[sz]; } void deallocate(T* p) { delete[] p; } }; template<typename T, typename Ax = allocator<T> > class list { } int main() { list<int, allocator<int> > v; v.resize(10); }
[ "noreply@github.com" ]
noreply@github.com
40c0c9bbcd13abc0baaf3829da662d243eb23003
a974b38441b875e00b3fe32cce5fc505bca69873
/Lesson_01/01_hello_SDL.cpp
62082c42b47a060ee1cba244f655959ce94d7682
[]
no_license
lfarci/sdl-tutorials
d64de21950ec5a8261adc6fe27da442a0451b8db
4cb4c4eab31844085b2dd62da9f2d17880b5a412
refs/heads/main
2023-05-13T12:28:59.604826
2021-06-04T17:26:00
2021-06-04T17:26:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,309
cpp
/*This source code copyrighted by Lazy Foo' Productions (2004-2020) and may not be redistributed without written permission.*/ //Using SDL and standard IO #include <SDL2/SDL.h> #include <stdio.h> //Screen dimension constants const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; int main( int argc, char* args[] ) { //The window we'll be rendering to SDL_Window* window = NULL; //The surface contained by the window SDL_Surface* screenSurface = NULL; //Initialize SDL if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() ); } else { //Create window window = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ); if( window == NULL ) { printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() ); } else { //Get window surface screenSurface = SDL_GetWindowSurface( window ); //Fill the surface white SDL_FillRect( screenSurface, NULL, SDL_MapRGB( screenSurface->format, 0xFF, 0xFF, 0xFF ) ); //Update the surface SDL_UpdateWindowSurface( window ); //Wait two seconds SDL_Delay( 2000 ); } } //Destroy window SDL_DestroyWindow( window ); //Quit SDL subsystems SDL_Quit(); return 0; }
[ "farci.logan@gmail.com" ]
farci.logan@gmail.com
35d1b4d76f659166d4241f85c774d3e8f68c397a
1caa061b196a5b89b52acc1a16d5607af9fec46b
/cube.cpp
63642302e5a11e5b6b15fd64320efca7104349b1
[]
no_license
Tadrion/opengl
f40ed953bb8f1634217caf820332cf7f1a2de54e
35ef0a36ac09608084668e9673b02bc3f3c01b42
refs/heads/master
2020-03-24T23:31:57.706772
2010-07-28T19:27:47
2010-07-28T19:27:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,763
cpp
#include <cstdio> #include <cstdlib> #include <GL/glfw.h> const int windowWidth = 800; const int windowHeight = 600; float rotate_y = 0; float rotate_z = 0; const float rotations_per_tick = 0.2; double timer = 0.0; double old_timer = 0.0; typedef struct vert{ int x,y,z; }VERTEX; VERTEX v[9]; void Shut_Down(int return_code) { glfwTerminate(); exit(return_code); } void Init() { if( glfwInit() != GL_TRUE ) { Shut_Down(1); } if (glfwOpenWindow(windowWidth,windowHeight,5,6,5,0,0,0,GLFW_WINDOW) != GL_TRUE) Shut_Down(1); glfwSetWindowTitle("My Window"); glMatrixMode(GL_PROJECTION); glLoadIdentity(); float aspect_ratio = ((float)windowHeight) / windowWidth; glFrustum(.5, -.5, -.5 * aspect_ratio, .5 * aspect_ratio, 1,1000); glMatrixMode(GL_MODELVIEW); glEnable(GL_DEPTH_TEST); //glfwSwapInterval(1); } void Draw_Square(float red, float green, float blue){ glBegin(GL_QUADS); { glColor3f(red, green, blue); glVertex2i(1, 11); glColor3f(red * .8, green * .8, blue * .8); glVertex2i(-1,11); glColor3f(red * .5, green * .5, blue * .5); glVertex2i(-1, 9); glColor3f(red * .8, green * .8, blue * .8); glVertex2i(1, 9); } glEnd(); } void Draw() { glLoadIdentity(); glTranslatef(0,0,-50); glRotatef(rotate_y, 0, 1, 0); glRotatef(rotate_z, 0, 0, 1); int i = 0, squares = 15; float red = 0, blue = 1; for(; i < squares; ++i) { glRotatef(360.0/squares, 0, 0, 1); red += 1.0 /12; blue -= 1.0/12; Draw_Square(red, .6, blue); } } void Main_Loop() { double old_time = glfwGetTime(); int it = 0; while(1) { double current_time = glfwGetTime(); double delta_rotate = (current_time - old_time) * rotations_per_tick * 360; old_time = current_time; if(glfwGetKey(GLFW_KEY_ESC) == GLFW_PRESS) break; rotate_z += delta_rotate; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); Draw(); glfwSwapBuffers(); it++; timer = glfwGetTime(); if(timer - old_timer >= 1.0) { printf("%lf\n",it / (timer - old_timer) ); it = 0; old_timer = timer; } } } void DrawSq(VERTEX a1,VERTEX a2, VERTEX a3, VERTEX a4, float r = 1, float g = 1, float b = 1) { glBegin(GL_QUADS); { glColor3f(r,g,b); glVertex3i(a1.x,a1.y, a1.z); glColor3f(r,g,b); glVertex3i(a2.x,a2.y, a2.z); glColor3f(r,g,b); glVertex3i(a3.x,a3.y, a3.z); glColor3f(r,g,b); glVertex3i(a4.x,a4.y, a4.z); } glEnd(); } void MDraw() { glLoadIdentity(); glTranslatef(0,0,-30); glRotatef(45.0, 1, 1, 0); float r = 1; float g = 1; float b = 1; glBegin(GL_QUADS); { glColor3f(r,g,b); glVertex3i(-5,-5, 0); glColor3f(r,g,b); glVertex3i(-5,5, 0); glColor3f(r,g,b); glVertex3i(5,5, 0); glColor3f(r,g,b); glVertex3i(5,-5, 0); } glEnd(); glBegin(GL_QUADS); { glColor3f(0.8*r,0.1*g,0.1*b); glVertex3i(5,5, 0); glColor3f(0.8*r,0.1*g,0.1*b); glVertex3i(5,5, -5); glColor3f(0.8*r,0.1*g,0.1*b); glVertex3i(5,-5, -5); glColor3f(0.8*r,0.1*g,0.1*b); glVertex3i(5,-5, 0); } glEnd(); glfwSwapBuffers(); } void Loop2() { float x = 0.0; while(1) { if(glfwGetKey(GLFW_KEY_ESC) == GLFW_PRESS) break; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearDepth(1); glLoadIdentity(); glTranslatef(0,0,-30); glRotatef(x, 1, 1, 0); //glRotatef(x, 0, 1, 0); //glRotatef(x, 0, 1, 2); DrawSq(v[1],v[2],v[3],v[4],1,1,1); DrawSq(v[1],v[4],v[8],v[5],1,0,0); DrawSq(v[1],v[2],v[6],v[5],0,1,0); DrawSq(v[4],v[3],v[7],v[8],0,0,1); DrawSq(v[2],v[3],v[7],v[6],1,1,0); DrawSq(v[5],v[6],v[7],v[8],0,1,1); x += 1.0; glfwSwapBuffers(); } } int main() { int w = 4; // v[1].x = 0; // v[1].y = 0; // v[1].z = 0; // v[2].x = w; // v[2].y = 0; // v[2].z = 0; // v[3].x = w; // v[3].y = w; // v[3].z = 0; // v[4].x = 0; // v[4].y = w; // v[4].z = 0; // v[5].x = 0; // v[5].y = 0; // v[5].z = -w; // v[6].x = w; // v[6].y = 0; // v[6].z = -w; // v[7].x = w; // v[7].y = w; // v[7].z = -w; // v[8].x = 0; // v[8].y = w; // v[8].z = -w; v[1].x = -w; v[1].y = -w; v[1].z = w; v[2].x = w; v[2].y = -w; v[2].z = w; v[3].x = w; v[3].y = w; v[3].z = w; v[4].x = -w; v[4].y = w; v[4].z = w; v[5].x = -w; v[5].y = -w; v[5].z = -w; v[6].x = w; v[6].y = -w; v[6].z = -w; v[7].x = w; v[7].y = w; v[7].z = -w; v[8].x = -w; v[8].y = w; v[8].z = -w; Init(); Loop2(); Shut_Down(0); }
[ "tadekdul@gmail.com" ]
tadekdul@gmail.com
eeb20ef2e4672247e03fedf07b5f1abd8956c111
52595e8ee0eaa348600226573cf6d42a98bbb3b5
/查找与排序实验/1 奥运排行榜 (25分).cpp
277581b44a685acdbc234e41cd5b1d54bc8dd52d
[]
no_license
HANXU2018/HBUDataStruct
f47049b21728a3e07324ed1f6c359fff230ad7f6
4223983450df0e21c5d0baaea3cf9cbd1126a750
refs/heads/master
2020-09-25T16:14:14.604340
2020-03-25T04:04:18
2020-03-25T04:04:18
226,041,175
1
0
null
null
null
null
GB18030
C++
false
false
2,121
cpp
#include<iostream> #include<algorithm> using namespace std; int n, m; struct Country{ int id; //记录国家的编号 int gold; int medal; int pnum; double avgold; double avgmedal; void cal() { avgold = (double)gold / pnum; avgmedal = (double)medal / pnum; } }; const int maxn = 226; Country a[maxn]; bool cmp1(Country b, Country c){ return b.gold > c.gold; } bool cmp2(Country b, Country c){ return b.medal > c.medal; } bool cmp3(Country b, Country c){ return b.avgold > c.avgold; } bool cmp4(Country b, Country c){ return b.avgmedal > c.avgmedal; } int main() { cin >> n >> m; for(int i = 0;i < n;i++) { cin >> a[i].gold >> a[i].medal >> a[i].pnum; a[i].id = i; //国家编号 a[i].cal(); } //rank记录最优排名,way记录最优排名的排名方法 int id, rank, way; for(int i = 0;i < m;i++) { rank = 0x3f3f3f3f; way = 0; cin >> id; //要查找的国家编号 sort(a, a + n, cmp1); for(int j = 0;j < n;j++) { //如果是这个国家,有更好的rank if(a[j].id == id){ //如果我的名次不是第一,那么我要跟前面的比一比,看看是否跟前一名并列 while(j != 0 && a[j].gold == a[j - 1].gold){j--;} if(j < rank){rank = j;way = 1;} break; } } //再按第二种方式排序 sort(a, a + n, cmp2); for(int j = 0;j < n;j++) { if(a[j].id == id){ while(j != 0 && a[j].medal == a[j - 1].medal){j--;} if(j < rank){rank = j;way = 2;} break; } } //第三种方式排序 sort(a, a + n, cmp3); for(int j = 0;j < n;j++) { if(a[j].id == id){ while(j != 0 && a[j].avgold == a[j - 1].avgold){j--;} if(j < rank){rank = j;way = 3;} break; } } //第四种方式排序 sort(a, a + n, cmp4); for(int j = 0;j < n;j++) { if(a[j].id == id){ while(j != 0 && a[j].avgmedal == a[j - 1].avgmedal){j--;} if(j < rank){rank = j;way = 4;} break; } } //输出的时候rank + 1,因为我是从0开始算的 if(i != m - 1) cout << rank + 1 << ":" << way << " "; else cout << rank + 1 << ":" << way << endl; } return 0; }
[ "1076998404@qq.com" ]
1076998404@qq.com
5cbd5430071b37f2f53be89488e4fb593b8cba61
dd4566651e2ac8d03ae9104d134ec28cb205330e
/NativePatcher/BridgeBuilder/Patcher_ExtCode/myext/ExportFuncs.h
cecc816b94491a0e00c9e1f0733077d22ba34103
[]
no_license
jaswgq/CefBridge
ba2f7d213425a78e16f9a8790f4e08ec50412f18
be1b8903ebf1cbb7d5d50b6c0eebfd0b06e45234
refs/heads/master
2021-01-20T03:29:26.465308
2017-01-30T11:49:12
2017-01-30T11:49:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,440
h
#include "dll_init.h" #include "../../shared/common/client_app.h" #include "../browser/client_handler.h" #include "../browser/client_handler_std.h" #include "../browser/root_window.h" #include "../browser/root_window_win.h" #include "../browser/browser_window_osr_win.h" #include "mycef.h" #define MY_DLL_EXPORT __declspec(dllexport) extern "C" { class MyBrowser { public: client::RootWindowWin* rootWin; client::BrowserWindow* bwWindow; }; //part 1 //1. MY_DLL_EXPORT int MyCefGetVersion(); //2. MY_DLL_EXPORT int RegisterManagedCallBack(managed_callback callback, int callBackKind); //3. MY_DLL_EXPORT client::ClientApp* MyCefCreateClientApp(HINSTANCE hInstance); //3.1 MY_DLL_EXPORT void MyCefEnableKeyIntercept(MyBrowser* myBw, int enable); //4. MY_DLL_EXPORT MyBrowser* MyCefCreateMyWebBrowser(managed_callback callback); //4. OSR MY_DLL_EXPORT MyBrowser* MyCefCreateMyWebBrowserOSR(managed_callback callback, HWND freeFormHwnd); //5. MY_DLL_EXPORT int MyCefSetupBrowserHwnd(MyBrowser* myBw, HWND surfaceHwnd, int x, int y, int w, int h, const wchar_t* url,CefRequestContext* cefRefContext); //5. OSR MY_DLL_EXPORT int MyCefSetupBrowserHwndOSR(MyBrowser* myBw, HWND surfaceHwnd, int x, int y, int w, int h, const wchar_t* url, CefRequestContext* cefRefContext); //6 MY_DLL_EXPORT void MyCefCloseMyWebBrowser(MyBrowser* myBw); //7. MY_DLL_EXPORT void MyCefDoMessageLoopWork(); //8. MY_DLL_EXPORT void MyCefSetBrowserSize(MyBrowser* myBw, int w, int h); MY_DLL_EXPORT void MyCefShutDown(); MY_DLL_EXPORT void MyCefDomGetTextWalk(MyBrowser* myBw, managed_callback strCallBack); MY_DLL_EXPORT void MyCefDomGetSourceWalk(MyBrowser* myBw, managed_callback strCallBack); //-------------------- MY_DLL_EXPORT void MyCefSetInitSettings(CefSettings* cefSetting, int keyName, const wchar_t* value); //-------------------- //part 2 //1. MY_DLL_EXPORT jsvalue MyCefNativeMetGetArgs(MethodArgs* args, int argIndex); //3. MY_DLL_EXPORT void MyCefMetArgs_SetResultAsJsValue(MethodArgs* args, int retIndex, jsvalue* value); //4. MY_DLL_EXPORT void MyCefMetArgs_SetResultAsString(MethodArgs* args, int argIndex, const wchar_t* buffer, int len); MY_DLL_EXPORT void MyCefMetArgs_SetResultAsInt32(MethodArgs* args, int argIndex, int value); MY_DLL_EXPORT void MyCefMetArgs_SetResultAsByteBuffer(MethodArgs* args, int argIndex, const char* byteBuffer, int len); MY_DLL_EXPORT void MyCefMetArgs_SetInputAsString(MethodArgs* args, int argIndex, const wchar_t* buffer, int len); MY_DLL_EXPORT void MyCefMetArgs_SetInputAsInt32(MethodArgs* args, int argIndex, int32_t value); //part3: //-------------------- //1. MY_DLL_EXPORT void MyCefBwNavigateTo(MyBrowser* myBw, const wchar_t* url); //2. MY_DLL_EXPORT void MyCefBwExecJavascript(MyBrowser* myBw, const wchar_t* jscode, const wchar_t* script_url); MY_DLL_EXPORT void MyCefBwExecJavascript2(CefBrowser* nativeWb, const wchar_t* jscode, const wchar_t* script_url); //3. MY_DLL_EXPORT void MyCefBwPostData(MyBrowser* myBw, const wchar_t* url, const wchar_t* rawDataToPost, size_t rawDataLength); //4. MY_DLL_EXPORT void MyCefShowDevTools(MyBrowser* myBw, MyBrowser* myBwDev, HWND parentHwnd); //---------------------------- MY_DLL_EXPORT void MyCefBwGoBack(MyBrowser* myBw); MY_DLL_EXPORT void MyCefBwGoForward(MyBrowser* myBw); MY_DLL_EXPORT void MyCefBwStop(MyBrowser* myBw); MY_DLL_EXPORT void MyCefBwReload(MyBrowser* myBw); MY_DLL_EXPORT void MyCefBwReloadIgnoreCache(MyBrowser* myBw); //---------------------------- //part4: javascript context MY_DLL_EXPORT CefV8Context* MyCefJsGetCurrentContext(); MY_DLL_EXPORT CefV8Context* MyCefJs_GetEnteredContext(); MY_DLL_EXPORT void MyCefJsNotifyRenderer(managed_callback callback, MethodArgs* args); MY_DLL_EXPORT CefV8Context* MyCefJsFrameContext(CefFrame* wbFrame); MY_DLL_EXPORT CefV8Value* MyCefJsGetGlobal(CefV8Context* cefV8Context); /*MY_DLL_EXPORT MethodArgs* CreateMethodArgs();*/ MY_DLL_EXPORT void DisposeMethodArgs(MethodArgs* args); MY_DLL_EXPORT CefV8Context* MyCefJs_EnterContext(CefV8Context* cefV8Context); MY_DLL_EXPORT void MyCefJs_ExitContext(CefV8Context* cefV8Context); MY_DLL_EXPORT CefV8Handler* MyCefJs_New_V8Handler(managed_callback callback); MY_DLL_EXPORT void MyCefJs_CefV8Value_SetValue_ByString(CefV8Value* target, const wchar_t* key, CefV8Value* value, int setAttribute); MY_DLL_EXPORT void MyCefJs_CefV8Value_SetValue_ByIndex(CefV8Value* target, int index, CefV8Value* value); MY_DLL_EXPORT bool MyCefJs_CefV8Value_IsFunc(CefV8Value* target); MY_DLL_EXPORT bool MyCefJs_CefRegisterExtension(const wchar_t* extensionName, const wchar_t* extensionCode); MY_DLL_EXPORT CefV8Value* MyCefJs_CreateFunction(const wchar_t* name, CefV8Handler* handler); MY_DLL_EXPORT CefV8Value* MyCefJs_ExecJsFunctionWithContext(CefV8Value* cefJsFunc, CefV8Context* context, const wchar_t* argAsJsonString); MY_DLL_EXPORT void MyCefFrame_GetUrl(CefFrame* frame, wchar_t* outputBuffer, int outputBufferLen, int* actualLength); MY_DLL_EXPORT void MyCefString_Read(CefString* cefStr, wchar_t* outputBuffer, int outputBufferLen, int* actualLength); MY_DLL_EXPORT void MyCefJs_CefV8Value_ReadAsString(CefV8Value* target, wchar_t* outputBuffer, int outputBufferLen, int* actualLength); MY_DLL_EXPORT void MyCefStringHolder_Read(MyCefStringHolder* mycefstr, wchar_t* outputBuffer, int outputBufferLen, int* actualLength); MY_DLL_EXPORT void MyCefJs_MetReadArgAsString(const CefV8ValueList* jsArgs, int index, wchar_t* outputBuffer, int outputBufferLen, int* actualLength); MY_DLL_EXPORT int MyCefJs_MetReadArgAsInt32(const CefV8ValueList* jsArgs, int index); MY_DLL_EXPORT CefV8Value* MyCefJs_MetReadArgAsCefV8Value(const CefV8ValueList* jsArgs, int index); MY_DLL_EXPORT CefV8Handler* MyCefJs_MetReadArgAsV8FuncHandle(const CefV8ValueList* jsArgs, int index); MY_DLL_EXPORT MyCefStringHolder* MyCefCreateCefString(const wchar_t* str); //------------------------------ //part 5 : UI Proc Ext //---------------------------- //part 6 MY_DLL_EXPORT bool MyCefAddCrossOriginWhitelistEntry( const wchar_t* sourceOrigin, const wchar_t* targetProtocol, const wchar_t* targetDomain, bool allow_target_subdomains ); MY_DLL_EXPORT bool MyCefRemoveCrossOriginWhitelistEntry( const wchar_t* sourceOrigin, const wchar_t* targetProtocol, const wchar_t* targetDomain, bool allow_target_subdomains ); }
[ "wintercoredev@gmail.com" ]
wintercoredev@gmail.com
c2e2767ff76c5205132073e9109831d83a56c72c
08057c01f6612023f72d7cc3872ff1b68679ec5d
/Assignments/Assignment_6/Gaddis_8thEdition_Chap8_ProgChal1_ChargeVal/main.cpp
2128165493d2e4718c64d9f6ced009cf7bd33371
[]
no_license
xMijumaru/RamosKevin_CSC5_SPRING2018__
d42519a426391303af3e77480b4451a3e07e7f62
7d904ed93c8490786dc62d546a93a01a999b0b69
refs/heads/master
2021-07-24T04:21:46.427089
2018-08-11T20:49:03
2018-08-11T20:49:03
125,411,373
0
0
null
null
null
null
UTF-8
C++
false
false
1,492
cpp
/* * File: main.cpp * Author: Kevin Ramos * Created on May 24, 2016, 9:07 AM * Purpose: Account Validation */ //System Libraries Here #include <iostream> #include <cstdlib> using namespace std; //User Libraries Here //Global Constants Only, No Global Variables //Like PI, e, Gravity, or conversions //Function Prototypes Here bool linear(int[], int, int); //Program Execution Begins Here int main(int argc, char** argv) { //Declare all Variables Here const int acc=18; int array[acc]={5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 8080152, 4562555, 5552012, 5050552, 7825877, 1250255, 1005231, 6545231, 3852085, 7576651, 7881200, 4581002}; int num=18; //Number of accounts on the system int enter;//Account number that will be inputed by the user bool result; //Boolian which will display the results //Input or initialize values Here cout << "Enter your Seven digit account number for validation: "; cin >> enter; result=linear(array,num, enter); if (result==true) cout << "Account " << enter << " has been verified" << endl; else cout << "Account " << enter << " is invalid " << endl; //Process/Calculations Here //Output Located Here //Exit return 0; } bool linear (int array[], int num, int enter) { for (int x=0;x<num;x++){ if (enter==array[x]){ return true; } } return false; }
[ "kramos24@student.rccd.edu" ]
kramos24@student.rccd.edu
db61bc9496bf47a8302ea233053240aa46f4bac6
7ad8ff903f7d7b5dd2d605cb0f7bb685f2bc99a1
/MemoryMap/test/test1_writing.cpp
1dda66586bbf53db1b18d034f59356708c6b069b
[ "MIT" ]
permissive
hiraditya/fool
cebf3de261d0e34fefb3f4e1b7a5555bcfac5cb2
0ec8cb02edeab65bacf579017d234f7de70ed2dd
refs/heads/master
2023-04-27T16:39:55.593559
2023-04-21T13:37:32
2023-04-21T13:37:32
47,622,971
0
1
null
null
null
null
UTF-8
C++
false
false
1,732
cpp
#include <iostream> #include <string> #include <fstream> #include <ctime> #include "file_map.hpp" using namespace std; using namespace filemap; int main() { int max = 1000; timespec ts, te; // Open a file using fstream for writing clock_gettime(CLOCK_MONOTONIC, &ts); ofstream myfile; myfile.open ("fstream1.txt"); for(int i = 0; i < max; i++) { myfile << i+1; } myfile.close(); clock_gettime(CLOCK_MONOTONIC, &te); timespec temp; if ((te.tv_nsec - ts.tv_nsec)<0) { temp.tv_sec = te.tv_sec - ts.tv_sec-1; temp.tv_nsec = 1000000000+te.tv_nsec-ts.tv_nsec; } else { temp.tv_sec = te.tv_sec-ts.tv_sec; temp.tv_nsec = te.tv_nsec-ts.tv_nsec; } // now time difference is in temp std::cout << "\n Time taken by fstream to carry out " << max << " writes to file in nanoseconds \t" << (temp.tv_nsec) << "\n" << std::endl; // cout << "Done" << endl; // Open a file using filemap for writing clock_gettime(CLOCK_MONOTONIC, &ts); file_map<int> myfile2("map1.txt", O_RDWR, 1000000); for(int i = 0; i < 100000; i++) { myfile2[i] = i + 1; } myfile2.update_file(); clock_gettime(CLOCK_MONOTONIC, &te); // timespec temp; if ((te.tv_nsec - ts.tv_nsec)<0) { temp.tv_sec = te.tv_sec - ts.tv_sec-1; temp.tv_nsec = 1000000000+te.tv_nsec-ts.tv_nsec; } else { temp.tv_sec = te.tv_sec-ts.tv_sec; temp.tv_nsec = te.tv_nsec-ts.tv_nsec; } // now time difference is in temp std::cout << "\n Time taken by file_map to carry out " << max << " writes to file in nanoseconds \t" << (temp.tv_nsec) << "\n" << std::endl; }
[ "hiraditya@d69eb80e-660b-f9d4-7be1-ad7134eeed8e" ]
hiraditya@d69eb80e-660b-f9d4-7be1-ad7134eeed8e
69eab3ae89b29692a45a5451e51ef1070b659785
db6ed48dd2be8edbd038ea0b7aa9d2720d9121e6
/jni/DemoAndroidApplication/MainMenu/Input/MMInputController.hpp
e7ae0e7746c81ed0b19354045c9710a3170c1d21
[ "Apache-2.0" ]
permissive
links234/MPACK
c66aa9d6a21c4ebed5bd52ba115b1ed90f57623e
3eec9616630825d45453e9bf14dae0a3ee4d81e9
refs/heads/master
2021-05-16T03:22:02.479750
2016-11-21T16:07:10
2016-11-21T16:07:10
10,639,047
1
3
null
2015-11-27T20:45:28
2013-06-12T08:31:51
C
UTF-8
C++
false
false
632
hpp
#ifndef MMINPUTCONTROLLER_HPP #define MMINPUTCONTROLLER_HPP #include "MPACK.hpp" #include <vector> class MMInputController { public: MMInputController(); virtual ~MMInputController(); void Update(GLfloat delta); void Link_FUP(const MPACK::Core::Param2PtrCallbackStruct &link); void Link_FDOWN(const MPACK::Core::Param2PtrCallbackStruct &link); protected: static void DOWNEvent(void *pointer1, void *pointer2); static void UPEvent(void *pointer1, void *pointer2); std::vector<MPACK::Core::Param2PtrCallbackStruct> m_callbackFunc_FUP; std::vector<MPACK::Core::Param2PtrCallbackStruct> m_callbackFunc_FDOWN; }; #endif
[ "murtaza_alexandru73@yahoo.com" ]
murtaza_alexandru73@yahoo.com
e4e5d33a95d9efc28d368d3817abdeb2e2dede49
1dbf007249acad6038d2aaa1751cbde7e7842c53
/eip/src/v3/model/ShowPublicipRequest.cpp
f8f2a53ca0ffead460d058ee87f8f7a9ac67d3df
[]
permissive
huaweicloud/huaweicloud-sdk-cpp-v3
24fc8d93c922598376bdb7d009e12378dff5dd20
71674f4afbb0cd5950f880ec516cfabcde71afe4
refs/heads/master
2023-08-04T19:37:47.187698
2023-08-03T08:25:43
2023-08-03T08:25:43
324,328,641
11
10
Apache-2.0
2021-06-24T07:25:26
2020-12-25T09:11:43
C++
UTF-8
C++
false
false
2,329
cpp
#include "huaweicloud/eip/v3/model/ShowPublicipRequest.h" namespace HuaweiCloud { namespace Sdk { namespace Eip { namespace V3 { namespace Model { ShowPublicipRequest::ShowPublicipRequest() { publicipId_ = ""; publicipIdIsSet_ = false; fieldsIsSet_ = false; } ShowPublicipRequest::~ShowPublicipRequest() = default; void ShowPublicipRequest::validate() { } web::json::value ShowPublicipRequest::toJson() const { web::json::value val = web::json::value::object(); if(publicipIdIsSet_) { val[utility::conversions::to_string_t("publicip_id")] = ModelBase::toJson(publicipId_); } if(fieldsIsSet_) { val[utility::conversions::to_string_t("fields")] = ModelBase::toJson(fields_); } return val; } bool ShowPublicipRequest::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("publicip_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("publicip_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setPublicipId(refVal); } } if(val.has_field(utility::conversions::to_string_t("fields"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("fields")); if(!fieldValue.is_null()) { std::vector<std::string> refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setFields(refVal); } } return ok; } std::string ShowPublicipRequest::getPublicipId() const { return publicipId_; } void ShowPublicipRequest::setPublicipId(const std::string& value) { publicipId_ = value; publicipIdIsSet_ = true; } bool ShowPublicipRequest::publicipIdIsSet() const { return publicipIdIsSet_; } void ShowPublicipRequest::unsetpublicipId() { publicipIdIsSet_ = false; } std::vector<std::string>& ShowPublicipRequest::getFields() { return fields_; } void ShowPublicipRequest::setFields(const std::vector<std::string>& value) { fields_ = value; fieldsIsSet_ = true; } bool ShowPublicipRequest::fieldsIsSet() const { return fieldsIsSet_; } void ShowPublicipRequest::unsetfields() { fieldsIsSet_ = false; } } } } } }
[ "hwcloudsdk@huawei.com" ]
hwcloudsdk@huawei.com
72827f9e9b15a21fd492719e436a7c2b1dc9f912
d304a44e46d314f46e214fa3efcc85db4c42d18c
/miniScope.ino
77e09757d80db468726151c7aad64647140ce6cd
[]
no_license
zeta0707/ardMiniScope
0fd303307263d5d325fbaf61ae6ea30a7d0e8176
726363f44afe954bffe5bb6f30815c1545a49927
refs/heads/master
2021-01-20T00:20:57.639639
2017-04-25T14:28:33
2017-04-25T14:28:33
89,115,837
3
0
null
null
null
null
UTF-8
C++
false
false
9,520
ino
/* Arduino Mega 2560 + HX8357 * Mini scope with reading ADC * Typically a clear screen for a 320 x 480 TFT will complete in only 12ms. * Original code: 240 x 320 QVGA resolutions. */ #include <TFT_HX8357.h> // Hardware-specific library /********************************************/ TFT_HX8357 tft = TFT_HX8357(); // Invoke custom library #define LTBLUE 0xB6DF #define LTTEAL 0xBF5F #define LTGREEN 0xBFF7 #define LTCYAN 0xC7FF #define LTRED 0xFD34 #define LTMAGENTA 0xFD5F #define LTYELLOW 0xFFF8 #define LTORANGE 0xFE73 #define LTPINK 0xFDDF #define LTPURPLE 0xCCFF #define LTGREY 0xE71C #define BLUE 0x001F #define TEAL 0x0438 #define GREEN 0x07E0 #define CYAN 0x07FF #define RED 0xF800 #define MAGENTA 0xF81F #define YELLOW 0xFFE0 #define ORANGE 0xFC00 #define PINK 0xF81F #define PURPLE 0x8010 #define GREY 0xC618 #define WHITE 0xFFFF #define BLACK 0x0000 #define DKBLUE 0x000D #define DKTEAL 0x020C #define DKGREEN 0x03E0 #define DKCYAN 0x03EF #define DKRED 0x6000 #define DKMAGENTA 0x8008 #define DKYELLOW 0x8400 #define DKORANGE 0x8200 #define DKPINK 0x9009 #define DKPURPLE 0x4010 #define DKGREY 0x4A49 #define COLOR_BACK BLACK //backgrond color #define COLOR_GRAPH LTORANGE //graph color #define maxWIDTH 479 #define maxHEIGHT 319 #define grEND 420 #define btSTART (grEND+5) #define resGRID 70 #define ROW1 0 #define ROW2 (ROW1+resGRID) #define ROW3 (ROW2+resGRID) #define ROW4 (ROW3+resGRID) #define ROW5 (ROW4+resGRID) #define resBTCOL resGRID #define resBTROW (maxWIDTH-btSTART-1) #define resBTSELCOL (resBTCOL-2) #define resBTSELROW (resBTROW-2) #define valSTART (btSTART+5) char buf[12]; char recv_str[100]; int x,y; int Input = 0; byte Sample[grEND*2]; byte OldSample[grEND*2]; int Sum=0; float SquareSum=0; int StartSample = 0; int EndSample = 0; int Max = 100; int Min = 100; int mode = 0; int dTime = 0; int tmode = 0; int Trigger = 0; int SampleSize = 0; int SampleTime = 0; int dgvh; int hpos = 45; //set 0v on horizontal grid int vsens = 35; // vertical sensitivity,1/10 // Define various ADC prescaler const unsigned char PS_16 = (1 << ADPS2); const unsigned char PS_32 = (1 << ADPS2) | (1 << ADPS0); const unsigned char PS_64 = (1 << ADPS2) | (1 << ADPS1); const unsigned char PS_128 = (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0); //------------Start Subrutines------------------------------------ //--------draw buttons sub void buttons(){ tft.fillRoundRect (btSTART, ROW1, resBTROW, resBTCOL, 1, BLUE); tft.fillRoundRect (btSTART, ROW2, resBTROW, resBTCOL, 1, BLUE); tft.fillRoundRect (btSTART, ROW3, resBTROW, resBTCOL, 1, BLUE); tft.fillRoundRect (btSTART, ROW4, resBTROW, resBTCOL, 1, BLUE); } //receive message from Bluetooth with time out int recvMsg(unsigned int timeout) { //wait for feedback unsigned int time = 0; unsigned char num; unsigned char i; //waiting for the first character with time out i = 0; while(1) { delay(50); if(Serial.available()) { recv_str[i] = char(Serial.read()); i++; break; } time++; if(time > (timeout / 50)) return -1; } //read other characters from uart buffer to string while(Serial.available() && (i < 100)) { recv_str[i] = char(Serial.read()); i++; } recv_str[i] = '\0'; return 0; } //-------touchscreen position sub void touch(){ if(Serial.available()) { int delayIn=0, trigIn=0, hposIn=0; if(recvMsg(100) == 0) { if(strcmp((char *)recv_str, (char *)"DELAY") == 0) delayIn=1; else if (strcmp((char *)recv_str, (char *)"TRIG") == 0) trigIn=1; else if(strcmp((char *)recv_str, (char *)"HPOS") == 0) hposIn=1; } if(delayIn==1) { mode = mode+1; tft.drawRoundRect(btSTART+2, ROW1+2, resBTSELROW, resBTSELCOL, 2, MAGENTA); // Select delay times if (mode == 0) dTime = 0; if (mode == 1) dTime = 1; if (mode == 2) dTime = 2; if (mode == 3) dTime = 5; if (mode == 4) dTime = 10; if (mode == 5) dTime = 20; if (mode == 6) dTime = 30; if (mode == 7) dTime = 50; if (mode == 8) dTime = 100; if (mode == 9) dTime = 200; if (mode == 10) dTime = 500; if (mode > 10) mode = 0; } if(trigIn==1) { tmode= tmode+1; // Select Software trigger value tft.drawRoundRect (btSTART+2, ROW2+2, resBTSELROW, resBTSELCOL, 2, MAGENTA); if (tmode == 1) Trigger = 0; if (tmode == 2) Trigger = 10; if (tmode == 3) Trigger = 20; if (tmode == 4) Trigger = 30; if (tmode == 5) Trigger = 50; if (tmode > 5) tmode = 0; } if(hposIn==1) { hpos= hpos+5; tft.drawRoundRect (btSTART+2, ROW3+2, resBTSELROW, resBTSELCOL, 2, MAGENTA); if (hpos > 80) hpos = 20; } delay(500); buttons(); tft.fillScreen(TFT_BLACK); Serial.print(dTime); Serial.print(Trigger);Serial.println(hpos); } } //----------draw grid sub void DrawGrid(){ for( dgvh = 0; dgvh < 5; dgvh ++ ){ tft.drawLine( dgvh * resGRID, 0, dgvh * resGRID, ROW5, LTGREEN); //vertical tft.drawLine( 0, dgvh * resGRID, grEND ,dgvh * resGRID, LTGREEN); //horizental } //tft.drawLine( 0, maxHEIGHT, grEND ,maxHEIGHT, LTGREEN); //bottom line tft.drawLine( 5* resGRID, 0, 5* resGRID, ROW5, LTGREEN); //6'th vertica tft.drawLine( 6 * resGRID, 0, 6 * resGRID, ROW5, LTGREEN); //7'th vertical tft.drawRoundRect(btSTART, ROW1, resGRID, resGRID, 1, WHITE); tft.drawRoundRect(btSTART, ROW2, resGRID, resGRID, 1, WHITE); tft.drawRoundRect(btSTART, ROW3, resGRID, resGRID, 1, WHITE); tft.drawRoundRect(btSTART, ROW4, resGRID, resGRID, 1, WHITE); } // ------ Wait for input to be greater than trigger sub void trigger(){ while (Input < Trigger) Input = analogRead(A0)*5/102; } //---------------End Subrutines ---------------------- void setup() { tft.begin(); tft.fillScreen(TFT_BLACK); tft.setRotation(1); buttons(); pinMode(0, INPUT); // set up the ADC ADCSRA &= ~PS_128; // remove bits set by Arduino library // you can choose a prescaler from below. // PS_16, PS_32, PS_64 or PS_128 ADCSRA |= PS_64; // set our own prescaler Serial.begin(115200); Serial.println("miniOSC starts"); } void loop() { touch(); DrawGrid(); //shoul run, graph destroy grid trigger(); // Collect the analog data into an array StartSample = micros(); for( int xpos = 0; xpos < grEND; xpos ++) { Sample[ xpos] = analogRead(A0)*5/102; delayMicroseconds(dTime); } EndSample = micros(); // Display the collected analog data from array for( int xpos = 0; xpos < grEND; xpos ++) { // Erase previous display tft.drawLine (xpos + 1, 255-OldSample[xpos+1]*vsens/10 - hpos, xpos + 2, 255-OldSample[ xpos + 2]* vsens/10 - hpos, COLOR_BACK); if (xpos == 0) tft.drawLine(xpos + 1, 1, xpos + 1, maxHEIGHT, COLOR_BACK); //Draw the new data tft.drawLine (xpos, 255-Sample[xpos]*vsens/10 - hpos, xpos + 1, 255-Sample[ xpos + 1]* vsens /10 - hpos, COLOR_GRAPH); } // Determine sample voltage peak to peak Max = Sample[ 100]; Min = Sample[ 100]; Sum = 0; SquareSum=0; for( int xpos = 0; xpos < grEND; xpos ++) { OldSample[ xpos] = Sample[ xpos]; if (Sample[ xpos] > Max) Max = Sample[ xpos]; if (Sample[ xpos] < Min) Min = Sample[ xpos]; Sum = Sum + Sample[xpos]; SquareSum = SquareSum + Sample[xpos]*Sample[xpos]; } // display the sample time, delay time and trigger level tft.setTextSize(1); tft.setTextColor(WHITE,BLUE); tft.drawString("Delay", valSTART, ROW1+5, 2); // 5+70*i tft.drawString(itoa ( dTime, buf, 10), valSTART, ROW1+20, 2); // 20+70*i tft.drawString("Trig.", valSTART, ROW2+5, 2); tft.drawString(itoa( Trigger, buf, 10), valSTART, ROW2+20, 2); tft.drawString("H Pos.", valSTART, ROW3+5, 2); tft.drawString( itoa( hpos, buf, 10), valSTART, ROW3+20, 2); SampleTime =(EndSample-StartSample)/1000; tft.drawString("mSec.", valSTART, ROW4+5, 2); tft.drawFloat(SampleTime, 2, valSTART, ROW4+20, 2); // color setting of Vpp, Vrms, Vmean tft.setTextColor(CYAN, BLACK); //show Vpp SampleSize =(Max-Min)*100; tft.drawString("Vpp(mVolt)", 5, 290, 2); //y:290 tft.drawString(" ", 5, 315, 2); //y:315, clear previous value tft.drawString(itoa(SampleSize, buf, 10),5, 315, 2); //x:5 //show Vmrs or V //tft.drawString("V(mVolt)", 5+100, 290, 2); //tft.drawString(" ", 5+100, 315, 2); //tft.drawString(itoa(analogRead(A0)*50.0/10.23, buf, 10),5+100 ,315, 2); tft.drawString("Vrms(mVolt)", 5+100, 290, 2); //y:290 tft.drawString(" ", 5+100, 315, 2); //y:315, clear previous value tft.drawString(itoa(sqrt(SquareSum/grEND)*100, buf, 10),5+100 ,315, 2); //x:105 //show Vmean tft.drawString("Vmean(mVolt)", 5+200, 290, 2); //y:290 tft.drawString(" ", 5+200, 315, 2); //y:315, clear previous value tft.drawString( itoa((Sum/grEND*100), buf, 10),5+200 ,315, 2); //x:205 }
[ "zeta0707@gmail.com" ]
zeta0707@gmail.com
a0909ae259e9dc31f68556f1fcf7dc711b9427a2
78324cf5e08c9eeb624f13dbf9cfa3ecdaac87cc
/Disjoint/Source.cpp
f344e0e6edfb9c4e93ed1dbb5c8d87d23470a9e9
[ "Apache-2.0" ]
permissive
runngezhang/Algorithms-Implementation
86179da901006c365be9de52af83981982a202cb
182a9bd625d2b3d109a87af9060709953224a243
refs/heads/master
2023-07-26T19:04:35.217685
2019-03-19T21:31:12
2019-03-19T21:31:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,129
cpp
#include <iostream> #include <algorithm> #include <queue> #include <vector> #include <cstring> using namespace std; #define SIZE 100010 int parent[SIZE], sz[SIZE]; inline int findParent(int vertex) { if (vertex == parent[vertex]) return parent[vertex]; else return parent[vertex] = findParent(parent[vertex]); } inline bool merge(pair<int, int> pairVertex) { if (findParent(pairVertex.first) == findParent(pairVertex.second)) return true; else { pairVertex.first = findParent(pairVertex.first); pairVertex.second = findParent(pairVertex.second); if (sz[pairVertex.first] < sz[pairVertex.second]) swap(pairVertex.first, pairVertex.second); parent[pairVertex.second] = parent[pairVertex.first]; sz[pairVertex.first] += sz[pairVertex.second]; return false; } } int main() { int n, m, x, y; cin >> n >> m; for (int i = 1; i <= n; i++) { parent[i] = i; sz[i] = 1; } for (int i = 0; i < m; i++) { cin >> x >> y; cout << merge(make_pair(x, y)) << endl; } for (int i = 1; i <= n; i++) cout << findParent(i) << endl; }
[ "saman.khamesian@gmail.com" ]
saman.khamesian@gmail.com
0bd0218aefda6537c3267a0d8e598c1b79af171b
28c8ce71b80c195ff30809a68008091b7922e788
/src/checkpoints.cpp
a7a15ed595441680f5c676cd53e2845155d28905
[ "MIT" ]
permissive
DecentralShopCoin/DecentralShopCoin-wallet-v1.0-core
f288987297cc2bba92be2bf153ccd0a488487668
3fdfeabceb7d452688cb48e25fc64d9a43ab9b4f
refs/heads/master
2020-04-12T19:53:20.659073
2018-12-29T15:24:02
2018-12-29T15:24:02
162,720,545
0
0
null
null
null
null
UTF-8
C++
false
false
3,480
cpp
// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017 The DecentralShop developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "checkpoints.h" #include "chainparams.h" #include "main.h" #include "uint256.h" #include <stdint.h> #include <boost/foreach.hpp> namespace Checkpoints { /** * How many times we expect transactions after the last checkpoint to * be slower. This number is a compromise, as it can't be accurate for * every system. When reindexing from a fast disk with a slow CPU, it * can be up to 20, while when downloading from a slow network with a * fast multicore CPU, it won't be much higher than 1. */ static const double SIGCHECK_VERIFICATION_FACTOR = 5.0; bool fEnabled = true; bool CheckBlock(int nHeight, const uint256& hash) { if (!fEnabled) return true; const MapCheckpoints& checkpoints = *Params().Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } //! Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex* pindex, bool fSigchecks) { if (pindex == NULL) return 0.0; int64_t nNow = time(NULL); double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0; double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkpoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData& data = Params().Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint) / 86400.0 * data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter * fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->GetBlockTime()) / 86400.0 * data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore * fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter * fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (!fEnabled) return 0; const MapCheckpoints& checkpoints = *Params().Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint() { if (!fEnabled) return NULL; const MapCheckpoints& checkpoints = *Params().Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH (const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; BlockMap::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } // namespace Checkpoints
[ "root@localhost" ]
root@localhost
8f4b3a864ab9d1c40684784ee7ae93e5578ac3e0
b5571d53d011154291cd5bfd34f7f374661ffbec
/core/plot2d.cpp
d34f88a7e9e13b2f9d17280f0334ec5f7e99a77a
[]
no_license
standlucian/RoGecko
387dff7dd0f97aa16f704e7ba2e5ff59d24c0bdc
2129352c4c42acf5a60786cb6e6bfc3d3ac006aa
refs/heads/master
2021-03-16T05:26:24.759891
2017-05-17T08:14:28
2017-05-17T08:14:28
91,550,573
0
0
null
null
null
null
UTF-8
C++
false
false
41,249
cpp
/* Copyright 2011 Bastian Loeher, Roland Wirth This file is part of GECKO. GECKO is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. GECKO 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/>. */ #include "plot2d.h" #include "samqvector.h" #include <limits> #include <QTimer> #include <QPixmap> using namespace std; Annotation::Annotation(QPoint _p, annoType _type, QString _text) : p(_p) , text (_text) , type(_type) { } Annotation::~Annotation() { } Channel::Channel(QVector<double> _data) : xmin (0) , xmax (0) , ymin (0) , ymax (0) , ylog (false) , xlog (false) , color (Qt::black) , name ("unset") , type (line) , id (0) , enabled (true) , stepSize (1) , data (_data) { } Channel::~Channel() { clearAnnotations(); } void Channel::clearAnnotations(){ QList<Annotation *> annos (annotations); annotations.clear (); foreach (Annotation *a, annos) delete a; } void Channel::setColor(QColor color){ this->color = color;} void Channel::setData(QVector<double> _data) { this->data = _data; emit changed (); } void Channel::setEnabled(bool enabled){ this->enabled = enabled;} void Channel::setId(unsigned int id){ this->id = id;} void Channel::setName(QString name){ this->name = name;} void Channel::setType(plotType type){ this->type = type;} void Channel::setStepSize(double stepSize){ this->stepSize = stepSize;} void Channel::addAnnotation(QPoint p, Annotation::annoType type, QString text) { Annotation* a = new Annotation(p,type,text); this->annotations.push_back(a); } // Plot2D plot2d::plot2d(QWidget *parent, QSize size, unsigned int id) : QWidget(parent) , state(0) , curTickCh(0) , calibration (0) , scalemode (ScaleOff) , viewport (0, -0.15, 1, 1) , backbuffer (NULL) , backbuffervalid (false) { this->id = id; setBackgroundRole(QPalette::Base); setAutoFillBackground(false); this->setGeometry(QRect(QPoint(0,0),size)); this->channels = new QList<Channel*>; // xmin = 0; ymin = 0; // xmax = this->width(); ymax = this->height(); useExternalBoundaries = false; zoomExtendsTrue = false; // ext_xmin = xmin; // ext_xmax = xmax; // ext_ymin = ymin; // ext_ymax = ymax; createActions(); setMouseTracking(true); } plot2d::~plot2d() { channels->clear(); delete channels; delete backbuffer; } void plot2d::resizeEvent(QResizeEvent *event) { delete backbuffer; backbuffer = NULL; update(); QWidget::resizeEvent(event); } void plot2d::addChannel(unsigned int id, QString name, QVector<double> data, QColor color, Channel::plotType type = Channel::line, double stepSize = 1) { Channel *newChannel = new Channel(data); newChannel->setColor(color); newChannel->setName(name); newChannel->setId(id); newChannel->setStepSize(stepSize); newChannel->setType(type); this->channels->append(newChannel); connect (newChannel, SIGNAL(changed()), SLOT(channelUpdate())); viewport.setCoords (0, -0.15, 1, 1); QAction* a = new QAction(tr("Ch %1").arg(id,1,10),this); a->setData(QVariant::fromValue(id)); // setCurTickChActions.push_back(a); } void plot2d::removeChannel(unsigned int id) { for(unsigned int i = 0; i < this->getNofChannels(); i++) { if(this->channels->at(i)->getId() == id) { Channel * ch = channels->at(i); ch->disconnect(SIGNAL(changed()), this, SLOT(channelUpdate())); channels->removeAt(i); delete ch; } } } void plot2d::mousePressEvent (QMouseEvent *ev) { if (ev->y () <= height ()*0.15 || ev->y () >= 0.85*height ()) { scalemode = ScaleX; scalestart = viewport.x () + ev->x () / (1.0 * width ()) * viewport.width (); scaleend = scalestart; } else if (ev->x () <= width()*0.05 || ev->x () >= width ()*0.95) { scalemode = ScaleY; scalestart = viewport.y () + ev->y () / (1.0 * height ()) * viewport.height (); scaleend = scalestart; } } void plot2d::mouseReleaseEvent(QMouseEvent *) { switch (scalemode) { case ScaleX: if (fabs (scalestart - scaleend) / viewport.width () * width () >= 5) { if(scalestart<0) scalestart=0; if(scaleend<0) scaleend=0; if(scalestart>1) scalestart=1; if(scaleend>1) scaleend=1; viewport.setLeft (std::min (scalestart, scaleend)); viewport.setRight (std::max (scalestart, scaleend)); autoscaleZoom(); } break; case ScaleY: if (fabs (scalestart - scaleend) / viewport.height () * height ()>= 5) { if(scalestart>1) scalestart=1; if(scaleend>1) scaleend=1; if(scalestart<-0.15) scalestart=-0.15; if(scaleend<-0.15) scaleend=-0.15; viewport.setTop (std::min (scalestart, scaleend)); viewport.setBottom (std::max (scalestart, scaleend)); } break; default: break; } if (scalemode != ScaleOff) { scalemode = ScaleOff; unsetCursor (); backbuffervalid = false; update (); } } void plot2d::mouseMoveEvent(QMouseEvent *ev) { curxmin = channels->at(curTickCh)->xmin; curxmax = channels->at(curTickCh)->xmax; curymin = channels->at(curTickCh)->ymin; curymax = channels->at(curTickCh)->ymax; Channel *curChan = channels->at(0); QVector<double> data = curChan->getData(); QPoint p = (ev->pos()); double toolTipx2=0; int toolTipx,toolTipx3; toolTipx3=(viewport.x()+viewport.width()*p.x()/width())*(curxmax-curxmin); if (calibration) { toolTipx2=(viewport.x()+viewport.width()*p.x()/width())*(curxmax-curxmin)*calibCoef1; toolTipx=toolTipx2; QToolTip::showText(ev->globalPos(), tr("E:%1\nCounts:%2") .arg((int)(toolTipx),3,10) .arg((int)(data[toolTipx3]),3,10),this); } else QToolTip::showText(ev->globalPos(), tr("%1,%2") .arg((int)((viewport.x()+viewport.width()*p.x()/width())*(curxmax-curxmin)),3,10) .arg((int)(data[toolTipx3]),3,10),this); if (ev->y () <= height ()*0.15 || ev->y () >= height ()*0.85) { setCursor (Qt::SizeHorCursor); } else if (ev->x () <= width()*0.05 || ev->x () >= width()*0.95) { setCursor (Qt::SizeVerCursor); } else if (scalemode == ScaleOff) { // XXX: does this have to happen everytime the mouse moves? --rw unsetCursor (); } if (scalemode == ScaleX || scalemode == ScaleY) { switch (scalemode) { case ScaleX: scaleend = viewport.x () + ev->x () / (1.0 * width ()) * viewport.width (); break; case ScaleY: scaleend = viewport.y () + ev->y () / (1.0 * height ()) * viewport.height (); break; default: break; } update (); } } void plot2d::mouseDoubleClickEvent(QMouseEvent *) { viewport.setCoords (0, -0.15, 1, 1); backbuffervalid = false; update (); } void plot2d::autoscaleZoom() { curxmin = channels->at(curTickCh)->xmin; curxmax = channels->at(curTickCh)->xmax; curymax = channels->at(curTickCh)->ymax; QVector<double> data = channels->at(0)->getData(); int datamin=(int)(viewport.x()*(curxmax-curxmin)); int datamax=(int)((viewport.x()+viewport.width())*(curxmax-curxmin)); double localmax=0; for(int i=datamin;i<datamax;i++) {if (data[i]>localmax) localmax=data[i];} if(state==1) { if(curymax>1) viewport.setTop (1-1.15*log10(localmax)/log10(curymax)); else viewport.setTop (-0.15); } else if(state==2) { viewport.setTop (1-1.15*sqrt(localmax)/sqrt(curymax)); } else { viewport.setTop (1-1.15*localmax/curymax); } } void plot2d::setZoom(double x, double width) { viewport.setX(x); viewport.setWidth(width); autoscaleZoom(); } void plot2d::channelUpdate () { backbuffervalid = false; } void plot2d::paintEvent(QPaintEvent *) { //printf("paintEvent\n"); fflush(stdout); if (!backbuffer || !backbuffervalid) { if (!backbuffer) { backbuffer = new QPixmap (size ()); } backbuffer->fill (isEnabled () ? QColor(252,252,252) : Qt::lightGray); QPainter pixmappainter (backbuffer); { QReadLocker rd (&lock); setBoundaries(); drawChannels(pixmappainter); } if(state==1) drawLogTicks(pixmappainter); else if(state==2) drawSqrtTicks(pixmappainter); else drawTicks(pixmappainter); backbuffervalid = true; } QPainter painter (this); painter.drawPixmap(0, 0, *backbuffer); if (scalemode == ScaleX) { double start = (scalestart - viewport.x ()) / viewport.width(); double end = (scaleend - viewport.x()) / viewport.width(); QRectF rectangle1 (QPoint(start * width (), 0.005 * height ()), QSize((end-start) * width (), 0.995*height ())); painter.save (); painter.fillRect (rectangle1,QBrush(QColor(185,211,238,64),Qt::SolidPattern)); painter.restore (); } if (scalemode == ScaleY) { double start = (scalestart - viewport.y ()) / viewport.height(); double end = (scaleend - viewport.y()) / viewport.height(); QRectF rectangle2 (QPoint(0.005 * width (), start * height ()), QSize(0.995 * width (),(end-start) *height ())); painter.save (); painter.fillRect (rectangle2,QBrush(QColor(185,211,238,64),Qt::SolidPattern)); painter.restore (); } } void plot2d::redraw() { this->update(); } void plot2d::setBoundaries() { // Get extents in data foreach(Channel* ch, (*channels)) { if(useExternalBoundaries) { if(ch->ymax > ext_ymax) ch->ymax = ext_ymax; if(ch->ymin < ext_ymin) ch->ymin = ext_ymin; if(ch->xmax > ext_xmax) ch->xmax = ext_xmax; if(ch->xmin < ext_xmin) ch->xmin = ext_xmin; } else if(ch->isEnabled()) { int newymin = std::numeric_limits<int>::max(); int newymax = std::numeric_limits<int>::min(); QVector<double> data = ch->getData(); if(data.size() > 0) { ch->xmax = data.size(); if(ch->getType() == Channel::steps) { ch->ymin = 0; } else { newymin = dsp->min(data)[AMP]; if(newymin < ch->ymin) ch->ymin = newymin; } newymax = dsp->max(data)[AMP]; if(newymax > ch->ymax) ch->ymax = newymax; if(zoomExtendsTrue) { ch->ymax = newymax; ch->ymin = newymin; } } //cout << "Bounds: (" << ch->xmin << "," << ch->xmax << ") (" << ch->ymin << "," << ch->ymax << ") " << endl; //cout << std::flush; data.clear(); } } } void plot2d::drawChannels(QPainter &painter) { if(state==1) { for(unsigned int i = 0; i < this->getNofChannels(); i++) if(channels->at(i)->isEnabled()) drawLogChannel(painter, i); } else if(state==2) { for(unsigned int i = 0; i < this->getNofChannels(); i++) if(channels->at(i)->isEnabled()) drawSqrtChannel(painter, i); } else for(unsigned int i = 0; i < this->getNofChannels(); i++) if(channels->at(i)->isEnabled()) drawChannel(painter, i); } void plot2d::drawChannel(QPainter &painter, unsigned int id) { Channel *curChan = channels->at(id); QVector<double> data = curChan->getData(); Channel::plotType curType = curChan->getType(); double nofPoints = data.size(); //cout << "Drawing ch " << id << " with size " << data.size() << endl; if(nofPoints > 0) { painter.save (); painter.setWindow(QRectF (viewport.x () * width (), viewport.y () * height (), viewport.width () * width (), viewport.height () * height ()).toRect ()); double max = curChan->ymax; double min = curChan->ymin; // Move 0,0 to lower left corner painter.translate(0,this->height()); if(curType == Channel::steps) { min = 0; } //cout << "Bounds: (" << curChan->xmin << "," << curChan->xmax << ") (" << curChan->ymin << "," << curChan->ymax << ") " << endl; QPolygon poly; double stepX = (curChan->xmax*1. - curChan->xmin)/(double)(width()/viewport.width()); if (stepX > 1) { // there are multiple points per pixel long lastX = 0; int coord = curChan->xmin; double dataMin, dataMax, dataFirst, dataLast; dataMin = dataMax = dataFirst = dataLast = data [curChan->xmin]; // draw at most 4 points per picture column: first, min, max, last. That way // the lines between pixels are correct and not too much detail gets lost for (unsigned int i = curChan->xmin + 1; (i < nofPoints && i < curChan->xmax); ++i) { long x = lrint ((i - curChan->xmin) / stepX); if (lastX != x) { // begin drawing a new pixel poly.push_back(QPoint (coord, -dataFirst)); if (dataLast == dataMin) { // save a point by drawing the min last if (dataMax != dataFirst) poly.push_back (QPoint (coord, -dataMax)); if (dataMin != dataMax) poly.push_back (QPoint (coord, -dataMin)); } else { if (dataMin != dataFirst) poly.push_back (QPoint (coord, -dataMin)); if (dataMax != dataMin) poly.push_back (QPoint (coord, -dataMax)); if (dataLast != dataMin) poly.push_back (QPoint (coord, -dataLast)); } lastX = x; coord = i; dataMin = dataMax = dataFirst = dataLast = data [i]; } else { // continue pixel dataLast = data [i]; if (dataMin > dataLast) dataMin = dataLast; if (dataMax < dataLast) dataMax = dataLast; } } //finish last pixel poly.push_back(QPoint (coord, -dataFirst)); if (dataMin != dataFirst) poly.push_back (QPoint (coord, -dataMin)); if (dataMax != dataMin) poly.push_back (QPoint (coord, -dataMax)); if (dataLast != dataMin) poly.push_back (QPoint (coord, -dataLast)); } else { int lastX = 0; int delta = 0; int deltaX = 0; int lastData = 0; for(unsigned int i = curChan->xmin; (i < nofPoints && i < curChan->xmax); i++) { // Only append point, if it would actually be displayed if(abs(data[i]-data[lastX]) > abs(delta)) { delta = data[i]-data[lastX]; deltaX = i; //std::cout << "Delta: " << delta << " , i: " << i << std::endl; } if((int)(i) >= lastX+1 || i == (curChan->xmax-1)) { // y-values increase downwards //poly.push_back(QPoint(i,-data[i])); //poly.push_back(QPoint(i+1,-data[i])); lastData += delta; poly.push_back(QPoint(i,-data[deltaX])); poly.push_back(QPoint(i+1,-data[deltaX])); lastX = i; delta=0; } } } painter.setPen(QPen(isEnabled () ? curChan->getColor() : Qt::darkGray)); // painter.drawText(QPoint(0,id*20),tr("%1").arg(id,1,10)); // Scale and move to display complete signals if(max-min < 0.00000001) max++; if(curChan->xmax-curChan->xmin < 0.00000001) curChan->xmax++; //cout << "Scaling: " << width()/nofPoints << " " << height()/(max-min) << endl; painter.scale(width()/(curChan->xmax-curChan->xmin),height()/(max-min)); painter.translate(0,min); painter.drawPolyline(poly); //std::cout << "Drew " << std::dec << poly.size() << " points" << std::endl; painter.restore (); } } void plot2d::drawLogChannel(QPainter &painter, unsigned int id) { Channel *curChan = channels->at(id); QVector<double> data = curChan->getData(); Channel::plotType curType = curChan->getType(); double nofPoints = data.size(); for(int i=0;i<nofPoints;i++) if(data[i]!=0) data[i]=1000*log10(data[i]); //cout << "Drawing ch " << id << " with size " << data.size() << endl; if(nofPoints > 0) { painter.save (); painter.setWindow(QRectF (viewport.x () * width (), viewport.y () * height (), viewport.width () * width (), viewport.height () * height ()).toRect ()); double max; if(curChan->ymax!=0) max=1000*log10(curChan->ymax); else max=0; double min; if(curChan->ymin!=0) min=1000*log10(curChan->ymin); else min=0; // Move 0,0 to lower left corner painter.translate(0,this->height()); if(curType == Channel::steps) { min = 0; } //cout << "Bounds: (" << curChan->xmin << "," << curChan->xmax << ") (" << curChan->ymin << "," << curChan->ymax << ") " << endl; QPolygon poly; double stepX = (curChan->xmax*1. - curChan->xmin)/(double)(width()/viewport.width()); if (stepX > 1) { // there are multiple points per pixel long lastX = 0; int coord = curChan->xmin; double dataMin, dataMax, dataFirst, dataLast; dataMin = dataMax = dataFirst = dataLast = data [curChan->xmin]; // draw at most 4 points per picture column: first, min, max, last. That way // the lines between pixels are correct and not too much detail gets lost for (unsigned int i = curChan->xmin + 1; (i < nofPoints && i < curChan->xmax); ++i) { long x = lrint ((i - curChan->xmin) / stepX); if (lastX != x) { // begin drawing a new pixel poly.push_back(QPoint (coord, -dataFirst)); if (dataLast == dataMin) { // save a point by drawing the min last if (dataMax != dataFirst) poly.push_back (QPoint (coord, -dataMax)); if (dataMin != dataMax) poly.push_back (QPoint (coord, -dataMin)); } else { if (dataMin != dataFirst) poly.push_back (QPoint (coord, -dataMin)); if (dataMax != dataMin) poly.push_back (QPoint (coord, -dataMax)); if (dataLast != dataMin) poly.push_back (QPoint (coord, -dataLast)); } lastX = x; coord = i; dataMin = dataMax = dataFirst = dataLast = data [i]; } else { // continue pixel dataLast = data [i]; if (dataMin > dataLast) dataMin = dataLast; if (dataMax < dataLast) dataMax = dataLast; } } //finish last pixel poly.push_back(QPoint (coord, -dataFirst)); if (dataMin != dataFirst) poly.push_back (QPoint (coord, -dataMin)); if (dataMax != dataMin) poly.push_back (QPoint (coord, -dataMax)); if (dataLast != dataMin) poly.push_back (QPoint (coord, -dataLast)); } else { int lastX = 0; int delta = 0; int deltaX = 0; int lastData = 0; for(unsigned int i = curChan->xmin; (i < nofPoints && i < curChan->xmax); i++) { // Only append point, if it would actually be displayed if(abs(data[i]-data[lastX]) > abs(delta)) { delta = data[i]-data[lastX]; deltaX = i; //std::cout << "Delta: " << delta << " , i: " << i << std::endl; } if((int)(i) >= lastX+1 || i == (curChan->xmax-1)) { // y-values increase downwards //poly.push_back(QPoint(i,-data[i])); //poly.push_back(QPoint(i+1,-data[i])); lastData += delta; poly.push_back(QPoint(i,-data[deltaX])); poly.push_back(QPoint(i+1,-data[deltaX])); lastX = i; delta=0; } } } painter.setPen(QPen(isEnabled () ? curChan->getColor() : Qt::darkGray)); // painter.drawText(QPoint(0,id*20),tr("%1").arg(id,1,10)); // Scale and move to display complete signals if(max-min < 0.00000001) max++; if(curChan->xmax-curChan->xmin < 0.00000001) curChan->xmax++; //cout << "Scaling: " << width()/nofPoints << " " << height()/(max-min) << endl; painter.scale(width()/(curChan->xmax-curChan->xmin),height()/(max-min)); painter.translate(0,min); painter.drawPolyline(poly); //std::cout << "Drew " << std::dec << poly.size() << " points" << std::endl; painter.restore (); } } void plot2d::drawSqrtChannel(QPainter &painter, unsigned int id) { Channel *curChan = channels->at(id); QVector<double> data = curChan->getData(); Channel::plotType curType = curChan->getType(); double nofPoints = data.size(); for(int i=0;i<nofPoints;i++) if(data[i]!=0) data[i]=1000*sqrt(data[i]); //cout << "Drawing ch " << id << " with size " << data.size() << endl; if(nofPoints > 0) { painter.save (); painter.setWindow(QRectF (viewport.x () * width (), viewport.y () * height (), viewport.width () * width (), viewport.height () * height ()).toRect ()); double max; if(curChan->ymax!=0) max=1000*sqrt(curChan->ymax); else max=0; double min; if(curChan->ymin!=0) min=1000*sqrt(curChan->ymin); else min=0; // Move 0,0 to lower left corner painter.translate(0,this->height()); if(curType == Channel::steps) { min = 0; } //cout << "Bounds: (" << curChan->xmin << "," << curChan->xmax << ") (" << curChan->ymin << "," << curChan->ymax << ") " << endl; QPolygon poly; double stepX = (curChan->xmax*1. - curChan->xmin)/(double)(width()/viewport.width()); if (stepX > 1) { // there are multiple points per pixel long lastX = 0; int coord = curChan->xmin; double dataMin, dataMax, dataFirst, dataLast; dataMin = dataMax = dataFirst = dataLast = data [curChan->xmin]; // draw at most 4 points per picture column: first, min, max, last. That way // the lines between pixels are correct and not too much detail gets lost for (unsigned int i = curChan->xmin + 1; (i < nofPoints && i < curChan->xmax); ++i) { long x = lrint ((i - curChan->xmin) / stepX); if (lastX != x) { // begin drawing a new pixel poly.push_back(QPoint (coord, -dataFirst)); if (dataLast == dataMin) { // save a point by drawing the min last if (dataMax != dataFirst) poly.push_back (QPoint (coord, -dataMax)); if (dataMin != dataMax) poly.push_back (QPoint (coord, -dataMin)); } else { if (dataMin != dataFirst) poly.push_back (QPoint (coord, -dataMin)); if (dataMax != dataMin) poly.push_back (QPoint (coord, -dataMax)); if (dataLast != dataMin) poly.push_back (QPoint (coord, -dataLast)); } lastX = x; coord = i; dataMin = dataMax = dataFirst = dataLast = data [i]; } else { // continue pixel dataLast = data [i]; if (dataMin > dataLast) dataMin = dataLast; if (dataMax < dataLast) dataMax = dataLast; } } //finish last pixel poly.push_back(QPoint (coord, -dataFirst)); if (dataMin != dataFirst) poly.push_back (QPoint (coord, -dataMin)); if (dataMax != dataMin) poly.push_back (QPoint (coord, -dataMax)); if (dataLast != dataMin) poly.push_back (QPoint (coord, -dataLast)); } else { int lastX = 0; int delta = 0; int deltaX = 0; int lastData = 0; for(unsigned int i = curChan->xmin; (i < nofPoints && i < curChan->xmax); i++) { // Only append point, if it would actually be displayed if(abs(data[i]-data[lastX]) > abs(delta)) { delta = data[i]-data[lastX]; deltaX = i; //std::cout << "Delta: " << delta << " , i: " << i << std::endl; } if((int)(i) >= lastX+1 || i == (curChan->xmax-1)) { // y-values increase downwards //poly.push_back(QPoint(i,-data[i])); //poly.push_back(QPoint(i+1,-data[i])); lastData += delta; poly.push_back(QPoint(i,-data[deltaX])); poly.push_back(QPoint(i+1,-data[deltaX])); lastX = i; delta=0; } } } painter.setPen(QPen(isEnabled () ? curChan->getColor() : Qt::darkGray)); // painter.drawText(QPoint(0,id*20),tr("%1").arg(id,1,10)); // Scale and move to display complete signals if(max-min < 0.00000001) max++; if(curChan->xmax-curChan->xmin < 0.00000001) curChan->xmax++; //cout << "Scaling: " << width()/nofPoints << " " << height()/(max-min) << endl; painter.scale(width()/(curChan->xmax-curChan->xmin),height()/(max-min)); painter.translate(0,min); painter.drawPolyline(poly); //std::cout << "Drew " << std::dec << poly.size() << " points" << std::endl; painter.restore (); } } void plot2d::setCalibration(double value2) { calibration=1; calibCoef1=value2; } void plot2d::setPlotState(int receivedState) { state=receivedState; } void plot2d::drawTicks(QPainter &painter) { int ch = curTickCh; long i=0, value=0; long incx=0, incy=0; double chxmin = channels->at(ch)->xmin; double chxmax = channels->at(ch)->xmax; double chymin = channels->at(ch)->ymin; double chymax = channels->at(ch)->ymax; double xmin = (chxmax - chxmin) * viewport.left (); double xmax = (chxmax - chxmin) * viewport.right (); double ymin = (chymax - chymin) * (1 - viewport.bottom ()); double ymax = (chymax - chymin) * (1 - viewport.top ()); // Draw tickmarks around the border // Range chooser while(incx<50 && incx<(xmax-xmin)/10) { incx+=10; } while(incx<10000 && incx<(xmax-xmin)/10) { incx+=50; } // for large ranges the increment is the smallest multiple of 10000 larger than // or equal to one tenth of the x-range if (incx < (xmax-xmin)/10) incx = 10000 * (floor ((xmax-xmin)/(10*10000)) + 1); while(incy<10 && incy<(ymax-ymin)/5) { incy+=1; } while(incy<50 && incy<(ymax-ymin)/5) { incy+=10; } while(incy<10000 && incy<(ymax-ymin)/5) { incy+=50; } // for large ranges the increment is the smallest multiple of 10000 larger than // or equal to one fifth of the y-range if (incy < (ymax-ymin)/5) incy = 10000 * (floor ((ymax-ymin)/(5*10000)) + 1); if(incx == 0) incx = 1; if(incy == 0) incy = 1; painter.save (); painter.setPen(QPen(isEnabled () ? channels->at(ch)->getColor() : Qt::darkGray)); // x Ticks value=xmin; int xtickInc = 0; if(xmax-xmin <= 1) { xtickInc = width(); } else { xtickInc = (incx*width()/(xmax-xmin)); } for(i=0; i<width(); i+=xtickInc) { QLine line1(i,0,i,height()*0.01); painter.drawLine(line1); } // y Ticks value=ymin; int ytickInc = 0; if(ymax-ymin <= 1) { ytickInc = height(); } else { ytickInc = (incy*height()/(ymax-ymin)); } if(ymax-ymin < 0.000001) ymax += 1; for(i=height(); i>0; i-=ytickInc) { //std::cout << "Drawing y tick " << i << std::endl; QLine line1(0,i,width()*0.01,i); QLine line2(width(),i,width()*0.99,i); painter.drawLine(line1); painter.drawLine(line2); painter.drawText(width()-40,i-6,tr("%1").arg(value,5,10)); painter.drawText(0,i-6,tr("%1").arg(value,5,10)); value+=incy; } painter.setPen(QColor(159,182,205,255)); for(uint i=0;i<maximaList.size();i++) { int position = width()*((maximaList[i]/(curxmax-curxmin))-viewport.x())/viewport.width(); QLine line1(position,height()*(1-(dataVector[maximaList[i]]/(ymax-ymin)-0.005)),position,height()*(1-(dataVector[maximaList[i]]/(ymax-ymin)+0.02))); painter.drawLine(line1); painter.drawText(position-15,height()*(1-(dataVector[maximaList[i]]/(ymax-ymin)+0.05)),tr("%1").arg(maximaList[i],5,10)); } painter.restore (); } void plot2d::drawLogTicks(QPainter &painter) { int ch = curTickCh; long i=0; long incx=0; double value=0, incy=0; double chxmin = channels->at(ch)->xmin; double chxmax = channels->at(ch)->xmax; double chymin = channels->at(ch)->ymin; double chymax = channels->at(ch)->ymax; double xmin = (chxmax - chxmin) * viewport.left (); double xmax = (chxmax - chxmin) * viewport.right (); double ymin = pow(10,(1 - viewport.bottom ())*log10(chymax - chymin)); if(ymin>=1&&ymin<2) ymin=0; double ymax = pow(10,(1 - viewport.top ())*log10(chymax - chymin)); // Draw tickmarks around the border // Range chooser while(incx<50 && incx<(xmax-xmin)/10) { incx+=10; } while(incx<10000 && incx<(xmax-xmin)/10) { incx+=50; } // for large ranges the increment is the smallest multiple of 10000 larger than // or equal to one tenth of the x-range if (incx < (xmax-xmin)/10) incx = 10000 * (floor ((xmax-xmin)/(10*10000)) + 1); while(incy<10 && incy<pow(ymax-ymin,0.2)) { incy+=1; } while(incy<50 && incy<pow(ymax-ymin,0.2)) { incy+=10; } while(incy<10000 && incy<pow(ymax-ymin,0.2)) { incy+=50; } if(incx == 0) incx = 1; if(incy == 0) incy = 1; painter.save (); painter.setPen(QPen(isEnabled () ? channels->at(ch)->getColor() : Qt::darkGray)); // x Ticks value=xmin; int xtickInc = 0; if(xmax-xmin <= 1) { xtickInc = width(); } else { xtickInc = (incx*width()/(xmax-xmin)); } for(i=0; i<width(); i+=xtickInc) { QLine line1(i,0,i,height()*0.01); painter.drawLine(line1); } // y Ticks value=0; int ytickInc = 0; if(ymax-ymin <= 1) { ytickInc = height(); } else { ytickInc = (log10(incy)*height()/log10(ymax-ymin)); } if(ymax-ymin < 0.000001) ymax += 1; for(i=height(); i>0; i-=ytickInc) { //std::cout << "Drawing y tick " << i << std::endl; QLine line1(0,i,width()*0.01,i); QLine line2(width(),i,width()*0.99,i); painter.drawLine(line1); painter.drawLine(line2); if((i==height())&&viewport.bottom()>0.99) { painter.drawText(width()-40,i-6,tr("%1").arg(0,5,10)); painter.drawText(0,i-6,tr("%1").arg(0,5,10)); } else { painter.drawText(width()-40,i-6,tr("%1").arg((int)(ymin+pow(incy,value)),5,10)); painter.drawText(0,i-6,tr("%1").arg((int)(ymin+pow(incy,value)),5,10)); } value+=1; } painter.restore (); } void plot2d::drawSqrtTicks(QPainter &painter) { int ch = curTickCh; long i=0; long incx=0; double value=0, incy=0; double chxmin = channels->at(ch)->xmin; double chxmax = channels->at(ch)->xmax; double chymin = channels->at(ch)->ymin; double chymax = channels->at(ch)->ymax; double xmin = (chxmax - chxmin) * viewport.left (); double xmax = (chxmax - chxmin) * viewport.right (); double ymin = pow((1 - viewport.bottom ())*sqrt((chymax - chymin)),2); double ymax = pow((1 - viewport.top ())*sqrt((chymax - chymin)),2); // Draw tickmarks around the border // Range chooser while(incx<50 && incx<(xmax-xmin)/10) { incx+=10; } while(incx<10000 && incx<(xmax-xmin)/10) { incx+=50; } // for large ranges the increment is the smallest multiple of 10000 larger than // or equal to one tenth of the x-range if (incx < (xmax-xmin)/10) incx = 10000 * (floor ((xmax-xmin)/(10*10000)) + 1); while(incy<10 && incy<(ymax-ymin)/25) { incy+=1; } while(incy<50 && incy<(ymax-ymin)/25) { incy+=10; } while(incy<10000 && incy<(ymax-ymin)/25) { incy+=50; } // for large ranges the increment is the smallest multiple of 10000 larger than // or equal to one fifth of the y-range //if (incy < pow(1/5,ymax-ymin)) // incy = 10000 * (floor ((ymax-ymin)/(5*10000)) + 1); if(incx == 0) incx = 1; if(incy == 0) incy = 1; painter.save (); painter.setPen(QPen(isEnabled () ? channels->at(ch)->getColor() : Qt::darkGray)); // x Ticks value=xmin; int xtickInc = 0; if(xmax-xmin <= 1) { xtickInc = width(); } else { xtickInc = (incx*width()/(xmax-xmin)); } for(i=0; i<width(); i+=xtickInc) { QLine line1(i,0,i,height()*0.01); painter.drawLine(line1); } // y Ticks value=0; int ytickInc = 0; if(ymax-ymin <= 1) { ytickInc = height(); } else { ytickInc = (sqrt(incy)*height()/sqrt(ymax-ymin)); } if(ymax-ymin < 0.000001) ymax += 1; for(i=height(); i>0; i-=ytickInc) { //std::cout << "Drawing y tick " << i << std::endl; QLine line1(0,i,width()*0.01,i); QLine line2(width(),i,width()*0.99,i); painter.drawLine(line1); painter.drawLine(line2); if((i==height())&&viewport.bottom()>0.99) { painter.drawText(width()-40,i-6,tr("%1").arg(0,5,10)); painter.drawText(0,i-6,tr("%1").arg(0,5,10)); } else { painter.drawText(width()-40,i-6,tr("%1").arg((int)(ymin+pow(value*sqrt(incy),2)),5,10)); painter.drawText(0,i-6,tr("%1").arg((int)(ymin+pow(value*sqrt(incy),2)),5,10)); } value+=1; } painter.restore (); } void plot2d::createActions() { clearHistogramAction = new QAction(tr("Clear Histogram"), this); connect(clearHistogramAction, SIGNAL(triggered()), this, SLOT(clearHistogram())); saveChannelAction = new QAction(tr("Save histogram"), this); connect(saveChannelAction, SIGNAL(triggered()), this, SLOT(saveChannel())); sameZoomAll = new QAction(tr("Same zoom for all"),this); connect(sameZoomAll, SIGNAL(triggered()), this, SLOT(emitZoomExtends())); unzoomAll = new QAction(tr("Unzoom all"),this); connect(unzoomAll, SIGNAL(triggered()), this, SLOT(emitUnzoomAll())); } void plot2d::contextMenuEvent(QContextMenuEvent *event) { QMenu menu(this); menu.addAction(this->clearHistogramAction); menu.addAction(this->saveChannelAction); menu.addAction(this->sameZoomAll); menu.addAction(this->unzoomAll); menu.exec(event->globalPos()); /*QMenu* sub = menu.addMenu("Axes for"); sub->addActions(setCurTickChActions); QAction* curAct = foreach(QAction* act, setCurTickChActions) { if(curAct == act) { selectCurTickCh(act->data().value<int>()); } }*/ } void plot2d::emitZoomExtends() { emit this->changeZoomForAll(this->id,viewport.x(),viewport.width()); } void plot2d::emitUnzoomAll() { emit this->changeZoomForAll(this->id,0,1); } void plot2d::clearHistogram() { for(unsigned int i = 0; i < this->getNofChannels(); i++) { emit this->histogramCleared(channels->at(i)->getId(),this->id); } } void plot2d::setMaximumExtends(int _xmin, int _xmax, int _ymin, int _ymax) { ext_xmin = _xmin; ext_xmax = _xmax; ext_ymin = _ymin; ext_ymax = _ymax; } void plot2d::toggleExternalBoundaries(bool newValue) { useExternalBoundaries = newValue; } void plot2d::maximumFinder() { smoothed.resize(8192); derivative.resize(8192); dataVector = channels->at(0)->getData(); smoothData(); findMaxima(); channelUpdate(); } void plot2d::smoothData() { smoothed[0]=dataVector[0]; smoothed[1]=(dataVector[0]+2*dataVector[1]+dataVector[2])/4; for(int i=2;i<8190;i++) { smoothed[i]=dataVector[i-2]+2*dataVector[i-1]+3*dataVector[i]+2*dataVector[i+1]+dataVector[i+2]; smoothed[i]=smoothed[i]/9; } smoothed[8190]=(dataVector[8189]+2*dataVector[8190]+dataVector[8191])/4; smoothed[8191]=dataVector[8191]; } void plot2d::calculateDerivative() { for(int i=1;i<8192;i++) { derivative[i]=smoothed[i+1]-smoothed[i-1]; derivative[i]=derivative[i]/2; } } void plot2d::findMaxima() { double ratio; std::vector <int> extremaList; calculateDerivative(); for(int i=2;i<8192;i++) if(derivative[i-2]*derivative[i-1]*derivative[i]*derivative[i+1]<0) if(dataVector[i]>100) extremaList.push_back(i); for(unsigned int i=0;i<extremaList.size()-1;i++) if(extremaList[i+1]-extremaList[i]<10) { if(extremaList[i]>extremaList[i+1]) extremaList.erase(extremaList.begin()+i+1); else { extremaList.erase(extremaList.begin()+i); i--; } } for(unsigned int i=1;i<extremaList.size()-1;i++) { int minmax; if(dataVector[extremaList[i-1]]>dataVector[extremaList[i+1]]) minmax=dataVector[extremaList[i-1]]; else minmax=dataVector[extremaList[i+1]]; ratio=(double)(dataVector[extremaList[i]]/minmax); if(ratio>1.7) maximaList.push_back(extremaList[i]); } for(unsigned int i=0;i<maximaList.size();i++) std::cout<<maximaList[i]<<" "<<smoothed[maximaList[i]]<<std::endl; } void plot2d::zoomExtends(bool newValue) { zoomExtendsTrue = newValue; } void plot2d::selectCurTickCh(int _curTickCh) { curTickCh = _curTickCh; } void plot2d::resetBoundaries(int ch) { channels->at(ch)->xmin = 0; channels->at(ch)->xmax = 1; channels->at(ch)->ymin = 0; channels->at(ch)->ymax = 1; } void plot2d::saveChannel() { QString fileName = QFileDialog::getSaveFileName(this,"Save Histogram as...","","Data files (*.dat)"); if (fileName.isEmpty()) return; QVector<double> data = channels->first()->getData(); dsp->vectorToFile(data,fileName.toStdString()); }
[ "standlucian@gmail.com" ]
standlucian@gmail.com
f013e2034811a937f4859ca9e5b461912c11dd98
25a79b640ae5de887f56b0a522e10f68613da76e
/DX11 Terrain Tutorials/tertut10/skydomeshaderclass.cpp
f44bdbfb0bb656496b8b2bd7c589999b9fee349e
[]
no_license
annjeff/DirectX11_study
982307d6a8b54428c3eafdd97b873765abd59e78
2f2f873d70e1967eaf77dff29ace971bfa011f88
refs/heads/master
2020-04-12T03:25:42.980612
2018-04-02T15:06:11
2018-04-02T15:06:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,172
cpp
//////////////////////////////////////////////////////////////////////////////// // Filename: skydomeshaderclass.cpp //////////////////////////////////////////////////////////////////////////////// #include "skydomeshaderclass.h" SkyDomeShaderClass::SkyDomeShaderClass() { m_vertexShader = 0; m_pixelShader = 0; m_layout = 0; m_matrixBuffer = 0; m_gradientBuffer = 0; } SkyDomeShaderClass::SkyDomeShaderClass(const SkyDomeShaderClass& other) { } SkyDomeShaderClass::~SkyDomeShaderClass() { } bool SkyDomeShaderClass::Initialize(ID3D11Device* device, HWND hwnd) { bool result; // Initialize the vertex and pixel shaders. result = InitializeShader(device, hwnd, L"../../tertut10/skydome.vs", L"../../tertut10/skydome.ps"); if(!result) { return false; } return true; } void SkyDomeShaderClass::Shutdown() { // Shutdown the vertex and pixel shaders as well as the related objects. ShutdownShader(); return; } bool SkyDomeShaderClass::Render( ID3D11DeviceContext* deviceContext, int indexCount, const XMMATRIX& worldMatrix, const XMMATRIX& viewMatrix, const XMMATRIX& projectionMatrix, const XMFLOAT4& apexColor, const XMFLOAT4& centerColor ) { bool result; // Set the shader parameters that it will use for rendering. result = SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, apexColor, centerColor); if(!result) { return false; } // Now render the prepared buffers with the shader. RenderShader(deviceContext, indexCount); return true; } bool SkyDomeShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename) { HRESULT result; ID3D10Blob* errorMessage; ID3D10Blob* vertexShaderBuffer; ID3D10Blob* pixelShaderBuffer; D3D11_INPUT_ELEMENT_DESC polygonLayout[1]; unsigned int numElements; D3D11_BUFFER_DESC matrixBufferDesc; D3D11_BUFFER_DESC gradientBufferDesc; // Initialize the pointers this function will use to null. errorMessage = 0; vertexShaderBuffer = 0; pixelShaderBuffer = 0; // Compile the vertex shader code. result = D3DCompileFromFile(vsFilename, NULL, NULL, "SkyDomeVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, &vertexShaderBuffer, &errorMessage); if(FAILED(result)) { // If the shader failed to compile it should have writen something to the error message. if(errorMessage) { OutputShaderErrorMessage(errorMessage, hwnd, vsFilename); } // If there was nothing in the error message then it simply could not find the shader file itself. else { MessageBox(hwnd, vsFilename, L"Missing Shader File", MB_OK); } return false; } // Compile the pixel shader code. result = D3DCompileFromFile(psFilename, NULL, NULL, "SkyDomePixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, &pixelShaderBuffer, &errorMessage); if(FAILED(result)) { // If the shader failed to compile it should have writen something to the error message. if(errorMessage) { OutputShaderErrorMessage(errorMessage, hwnd, psFilename); } // If there was nothing in the error message then it simply could not find the file itself. else { MessageBox(hwnd, psFilename, L"Missing Shader File", MB_OK); } return false; } // Create the vertex shader from the buffer. result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader); if(FAILED(result)) { return false; } // Create the pixel shader from the buffer. result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader); if(FAILED(result)) { return false; } // Create the vertex input layout description. polygonLayout[0].SemanticName = "POSITION"; polygonLayout[0].SemanticIndex = 0; polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[0].InputSlot = 0; polygonLayout[0].AlignedByteOffset = 0; polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[0].InstanceDataStepRate = 0; // Get a count of the elements in the layout. numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); // Create the vertex input layout. result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout); if(FAILED(result)) { return false; } // Release the vertex shader buffer and pixel shader buffer since they are no longer needed. vertexShaderBuffer->Release(); vertexShaderBuffer = 0; pixelShaderBuffer->Release(); pixelShaderBuffer = 0; // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. result = device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer); if(FAILED(result)) { return false; } // Setup the description of the gradient constant buffer that is in the pixel shader. gradientBufferDesc.Usage = D3D11_USAGE_DYNAMIC; gradientBufferDesc.ByteWidth = sizeof(GradientBufferType); gradientBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; gradientBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; gradientBufferDesc.MiscFlags = 0; gradientBufferDesc.StructureByteStride = 0; // Create the constant buffer pointer so we can access the pixel shader constant buffer from within this class. result = device->CreateBuffer(&gradientBufferDesc, NULL, &m_gradientBuffer); if(FAILED(result)) { return false; } return true; } void SkyDomeShaderClass::ShutdownShader() { // Release the gradient constant buffer. if(m_gradientBuffer) { m_gradientBuffer->Release(); m_gradientBuffer = 0; } // Release the matrix constant buffer. if(m_matrixBuffer) { m_matrixBuffer->Release(); m_matrixBuffer = 0; } // Release the layout. if(m_layout) { m_layout->Release(); m_layout = 0; } // Release the pixel shader. if(m_pixelShader) { m_pixelShader->Release(); m_pixelShader = 0; } // Release the vertex shader. if(m_vertexShader) { m_vertexShader->Release(); m_vertexShader = 0; } return; } void SkyDomeShaderClass::OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, WCHAR* shaderFilename) { char* compileErrors; SIZE_T bufferSize, i; ofstream fout; // Get a pointer to the error message text buffer. compileErrors = (char*)(errorMessage->GetBufferPointer()); // Get the length of the message. bufferSize = errorMessage->GetBufferSize(); // Open a file to write the error message to. fout.open("shader-error.txt"); // Write out the error message. for(i=0; i<bufferSize; i++) { fout << compileErrors[i]; } // Close the file. fout.close(); // Release the error message. errorMessage->Release(); errorMessage = 0; // Pop a message up on the screen to notify the user to check the text file for compile errors. MessageBox(hwnd, L"Error compiling shader. Check shader-error.txt for message.", shaderFilename, MB_OK); return; } bool SkyDomeShaderClass::SetShaderParameters( ID3D11DeviceContext* deviceContext, const XMMATRIX& worldMatrix, const XMMATRIX& viewMatrix, const XMMATRIX& projectionMatrix, const XMFLOAT4& apexColor, const XMFLOAT4& centerColor ) { HRESULT result; D3D11_MAPPED_SUBRESOURCE mappedResource; MatrixBufferType* dataPtr; GradientBufferType* dataPtr2; unsigned int bufferNumber; XMMATRIX worldMatrixCopy = worldMatrix; XMMATRIX viewMatrixCopy = viewMatrix; XMMATRIX projectionMatrixCopy = projectionMatrix; // Transpose the matrices to prepare them for the shader. worldMatrixCopy = XMMatrixTranspose( worldMatrix ); viewMatrixCopy = XMMatrixTranspose( viewMatrix ); projectionMatrixCopy = XMMatrixTranspose( projectionMatrix ); // Lock the constant buffer so it can be written to. result = deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); if(FAILED(result)) { return false; } // Get a pointer to the data in the constant buffer. dataPtr = (MatrixBufferType*)mappedResource.pData; // Copy the matrices into the constant buffer. dataPtr->world = worldMatrixCopy; dataPtr->view = viewMatrixCopy; dataPtr->projection = projectionMatrixCopy; // Unlock the constant buffer. deviceContext->Unmap(m_matrixBuffer, 0); // Set the position of the constant buffer in the vertex shader. bufferNumber = 0; // Finally set the constant buffer in the vertex shader with the updated values. deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer); // Lock the gradient constant buffer so it can be written to. result = deviceContext->Map(m_gradientBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); if(FAILED(result)) { return false; } // Get a pointer to the data in the constant buffer. dataPtr2 = (GradientBufferType*)mappedResource.pData; // Copy the gradient color variables into the constant buffer. dataPtr2->apexColor = apexColor; dataPtr2->centerColor = centerColor; // Unlock the constant buffer. deviceContext->Unmap(m_gradientBuffer, 0); // Set the position of the gradient constant buffer in the pixel shader. bufferNumber = 0; // Finally set the gradient constant buffer in the pixel shader with the updated values. deviceContext->PSSetConstantBuffers(bufferNumber, 1, &m_gradientBuffer); return true; } void SkyDomeShaderClass::RenderShader(ID3D11DeviceContext* deviceContext, int indexCount) { // Set the vertex input layout. deviceContext->IASetInputLayout(m_layout); // Set the vertex and pixel shaders that will be used to render the triangles. deviceContext->VSSetShader(m_vertexShader, NULL, 0); deviceContext->PSSetShader(m_pixelShader, NULL, 0); // Render the triangle. deviceContext->DrawIndexed(indexCount, 0, 0); return; }
[ "578223343@qq.com" ]
578223343@qq.com
1e2739e598cb0000b78108002b0b02fd5fb5332b
61b5b6ea710a623e8bab1e4af8e53ddd9b0f2a2a
/LinkedList/LinkedListClass.cpp
d9dd9516f0cbe7467916ae0dd0e0c8c2ffdee246
[]
no_license
HADES-Temp/jubilant-guide
62702bd9a3fec7aa4a3a4238b8299f18412948cf
b44e15752e07c06ef54a25c7b8bac1bd62c1ecbc
refs/heads/master
2023-08-11T14:21:13.495218
2021-10-12T16:52:55
2021-10-12T16:52:55
415,354,964
1
2
null
null
null
null
UTF-8
C++
false
false
1,708
cpp
#include<bits/stdc++.h> using namespace std; class Node{ public: int data; Node *next; }; class LinkedList{ Node *first; public: LinkedList(){first = NULL;} LinkedList(int A[], int n); ~LinkedList(); void Display(); void Append(int index); void Insert(int index, int pos); int Delete(int index); int Length(); }; void LinkedList::Append(int x){ cout<<"called"; Node *temp = new Node, *p = first; temp->next = NULL; temp->data = x; if(first == NULL){ cout<<"ran"; first = temp; } else{ while(p->next){ p = p->next; } p->next = temp; } } void LinkedList::Display(){ Node *p = first; while(p->next){ cout<<p->data<<"->"; p = p->next; } } void LinkedList::Insert(int pos, int x){ if(pos < 0 || pos > Length()) return; Node *p = first, *q = NULL, *temp = new Node; temp->data = x; temp->next = NULL; if(pos == 0){ temp->next = first; first = temp; } else{ for(int i = 0; i < pos && p; i++){ q = p; p = p-> next; } q->next = temp; temp->next = p; } } LinkedList::LinkedList(int A[], int n){ first = NULL; for(int i = 0; i < n; i++){ Append(A[i]); } } LinkedList::~LinkedList(){ Node *p = first; while(first){ first = first->next; delete p; p = first; } } int LinkedList::Length(){ int ctr; Node *p = first; while(p){ p = p->next; ctr++; } return ctr; } int LinkedList::Delete(int pos){ if(pos < 1 || pos > this->Length()) return -1; Node *p = first, *q = NULL; int x = -1; for(int i = 0; i < pos - 1 && p; i++){ q = p; p = p->next; } x = p->data; q->next = p->next; delete p; return x; } int main(){ int A[] = {1,3,6,2,4,9,5,13,6,1}; LinkedList L1(A, 10); L1.Display(); return 0; }
[ "adityavats122017@gmail.com" ]
adityavats122017@gmail.com
30d595ee328209ce3ffd3fbb309962b61bd5d1c6
fb13e3278f5e30f716527fc798045fe9eb2492be
/riscv-sim/include/RISCVConsole.h
999c3ef13ad26124812d124a7f6a260a7abfff67
[]
no_license
helloparthshah/riscv-console
76b3cefb77319fa7f698bdfe60f65f84ea80f3db
5b20edc4f54c8edf2f2f4e6769e2f02676eaf994
refs/heads/main
2023-08-02T12:05:33.750545
2021-10-10T01:49:37
2021-10-10T01:49:37
415,193,004
1
0
null
null
null
null
UTF-8
C++
false
false
7,147
h
#ifndef RISCVCCONSOLE_H #define RISCVCCONSOLE_H #include "RISCVCPU.h" #include "RISCVConsoleChipset.h" #include "ElfLoad.h" #include "MemoryDevice.h" #include "FlashMemoryDevice.h" #include "VideoController.h" #include "DataSource.h" #include <thread> #include <mutex> #include <condition_variable> #include <chrono> #include <set> using CRISCVConsoleBreakpointCalldata = void *; using CRISCVConsoleBreakpointCallback = void (*)(CRISCVConsoleBreakpointCalldata); class CRISCVConsole{ public: enum class EDirection : uint32_t {Left = 0x1, Up = 0x2, Down = 0x4, Right = 0x8}; enum class EButtonNumber : uint32_t {Button1 = 0x10, Button2 = 0x20, Button3 = 0x40, Button4 = 0x80}; protected: enum class EThreadState : uint32_t {Stop = 0, Run = 1, Breakpoint = 2}; bool DDebugMode; uint32_t DTimerDelayUS; uint32_t DVideoDelayMS; uint32_t DDebugCPUFreq; uint32_t DVideoTicks; uint32_t DTimerTicks; std::atomic< bool > DRefreshScreenBuffer; size_t DPendingReleaseBuffer; std::shared_ptr< CRISCVCPU > DCPU; std::shared_ptr< CRISCVCPU::CInstructionCache > DCPUCache; std::shared_ptr< CMemoryDevice > DMemoryController; std::shared_ptr< CMemoryDevice > DMainMemory; std::shared_ptr< CRegisterBlockMemoryDevice > DRegisterBlock; std::shared_ptr< CFlashMemoryDevice > DFirmwareFlash; std::shared_ptr< CFlashMemoryDevice > DCartridgeFlash; std::shared_ptr< CVideoController > DVideoController; std::shared_ptr< CRISCVConsoleChipset > DChipset; std::atomic<uint32_t> DSystemCommand; std::atomic<uint32_t> DCPUAcknowledge; std::atomic<uint32_t> DTimerAcknowledge; std::atomic<uint32_t> DSystemAcknowledge; std::shared_ptr< std::thread > DCPUThread; std::shared_ptr< std::thread > DTimerThread; std::shared_ptr< std::thread > DSystemThread; std::chrono::steady_clock::time_point DSystemStartTime; uint64_t DCPUStartInstructionCount; std::vector< std::string > DFirmwareInstructionStrings; std::unordered_map< uint32_t, size_t > DFirmwareAddressesToIndices; std::vector< std::string > DFirmwareInstructionLabels; std::vector< size_t > DFirmwareInstructionLabelIndices; std::vector< std::string > DCartridgeInstructionStrings; std::unordered_map< uint32_t, size_t > DCartridgeAddressesToIndices; std::vector< std::string > DCartridgeInstructionLabels; std::vector< size_t > DCartridgeInstructionLabelIndices; std::vector< std::string > DInstructionStrings; std::unordered_map< uint32_t, size_t > DInstructionAddressesToIndices; std::vector< std::string > DInstructionLabels; std::vector< size_t > DInstructionLabelIndices; std::set< uint32_t > DBreakpoints; CRISCVConsoleBreakpointCalldata DBreakpointCalldata; CRISCVConsoleBreakpointCallback DBreakpointCallback; static const uint32_t DMainMemorySize; static const uint32_t DMainMemoryBase; static const uint32_t DFirmwareMemorySize; static const uint32_t DFirmwareMemoryBase; static const uint32_t DCartridgeMemorySize; static const uint32_t DCartridgeMemoryBase; static const uint32_t DVideoMemoryBase; static const uint32_t DRegisterMemoryBase; void CPUThreadExecute(); void TimerThreadExecute(); void SystemThreadExecute(); void SystemRun(); void SystemStop(); bool SystemStep(); void ResetComponents(); void ConstructInstructionStrings(CElfLoad &elffile, std::vector< std::string > &strings, std::unordered_map< uint32_t, size_t > &translations, std::vector< std::string > &labels, std::vector< size_t > &labelindices); void ConstructFirmwareStrings(CElfLoad &elffile); void ConstructCartridgeStrings(CElfLoad &elffile); void MarkBreakpointStrings(); public: CRISCVConsole(uint32_t timerus, uint32_t videoms, uint32_t cpufreq); ~CRISCVConsole(); uint32_t ScreenWidth(){ return DVideoController->ScreenWidth(); }; uint32_t ScreenHeight(){ return DVideoController->ScreenHeight(); }; std::shared_ptr< CRISCVCPU > CPU(){ return DCPU; }; std::shared_ptr< CMemoryDevice > Memory(){ return DMemoryController; }; void SetDebugMode(bool debug); void Reset(); void PowerOn(); void PowerOff(); void Run(); void Stop(); void Step(); uint64_t PressDirection(EDirection dir); uint64_t ReleaseDirection(EDirection dir); uint64_t PressButton(EButtonNumber button); uint64_t ReleaseButton(EButtonNumber button); uint64_t PressCommand(); bool VideoTimerTick(std::shared_ptr<CGraphicSurface> screensurface); bool ProgramFirmware(std::shared_ptr< CDataSource > elfsrc); uint64_t InsertCartridge(std::shared_ptr< CDataSource > elfsrc); uint64_t RemoveCartridge(); void AddBreakpoint(uint32_t addr); void RemoveBreakpoint(uint32_t addr); void SetBreakcpointCallback(CRISCVConsoleBreakpointCalldata calldata, CRISCVConsoleBreakpointCallback callback); const std::set< uint32_t > &Breakpoints() const{ return DBreakpoints; }; void ClearBreakpoints(); const std::vector< std::string > &InstructionStrings() const{ return DInstructionStrings; } size_t InstructionAddressesToIndices(uint32_t addr) const{ auto Search = DInstructionAddressesToIndices.find(addr); if(Search != DInstructionAddressesToIndices.end()){ return Search->second; } return -1; } const std::vector< std::string > &InstructionLabels() const{ return DInstructionLabels; } const std::vector< size_t > &InstructionLabelIndices() const{ return DInstructionLabelIndices; } uint32_t MainMemorySize(){ return DMainMemorySize; }; uint32_t MainMemoryBase(){ return DMainMemoryBase; }; uint32_t FirmwareMemorySize(){ return DFirmwareMemorySize; }; uint32_t FirmwareMemoryBase(){ return DFirmwareMemoryBase; }; uint32_t CartridgeMemorySize(){ return DCartridgeMemorySize; }; uint32_t CartridgeMemoryBase(){ return DCartridgeMemoryBase; }; uint32_t VideoMemorySize(){ return DVideoController->VideoRAM()->MemorySize(); }; uint32_t VideoMemoryBase(){ return DVideoMemoryBase; }; uint32_t RegisterMemorySize(){ return DRegisterBlock->MemorySize(); }; uint32_t RegisterMemoryBase(){ return DRegisterMemoryBase; }; }; #endif
[ "cjnitta@gmail.com" ]
cjnitta@gmail.com
3550f6233c7e86fb5dac2bd4febb65751a0aad1a
889070c36584bf72670ead396b2c0932b9cb2f2d
/AdvancedGraphs/FILLMTR.cpp
bd3b04bcbd12ae702ed5e1dcd43ca4cde3925c17
[]
no_license
viralipurbey/CompetitiveProgramminCodingNinjas
2586cb1f688265c29e66a50da906424986f98fa8
7fa063930a92f02efbdcf9afe55252df9e0299a6
refs/heads/master
2022-11-27T06:44:22.829945
2020-08-02T07:20:19
2020-08-02T07:20:19
257,389,120
0
0
null
null
null
null
UTF-8
C++
false
false
2,270
cpp
#include<bits/stdc++.h> using namespace std; int getParent(int* parent, int v){ while(parent[v] != v){ v = parent[v]; } return v; } bool bipartite(vector<int> *edges, int n, int root, bool* visited){ if(n == 0){ return true; } unordered_set<int> sets[2]; vector<int> pending; sets[0].insert(root); pending.push_back(root); visited[root] = true; while(pending.size() > 0){ int curr = pending.back(); pending.pop_back(); int currSet = sets[0].count(curr) > 0 ? 0 : 1; for(int i = 0; i < edges[curr].size(); i++){ int neighbor = edges[curr][i]; visited[neighbor] = true; if(sets[0].count(neighbor) == 0 && sets[1].count(neighbor) == 0){ sets[1-currSet].insert(neighbor); pending.push_back(neighbor); }else if(sets[currSet].count(neighbor) > 0){ return false; } } } return true; } bool FILLMTR(int** B, int n){ int* parent = new int[n]; for(int i = 0; i < n; i++){ parent[i] = i; } // Making Components for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ int sourcePar = getParent(parent, i); int destPar = getParent(parent, j); if(B[i][j] == 0 && sourcePar != destPar){ parent[sourcePar] = destPar; } } } // Making edges on basis of 1 vector<int>* edges = new vector<int>[n]; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(B[i][j] == 1){ int sourcePar = getParent(parent, i); int destPar = getParent(parent, j); if(sourcePar == destPar){ return false; } edges[sourcePar].push_back(destPar); edges[destPar].push_back(sourcePar); } } } // Checking for bipartite bool* visited = new bool[n]; for(int i = 0; i < n; i++){ visited[i] = false; } for(int i = 0; i < n; i++){ if(!visited[i]){ bool ans = bipartite(edges, n, i, visited); if(!ans){ return false; } } } return true; } int main(){ int t; cin >> t; while(t--){ int n, q; cin >> n, q; int **B = new int*[n]; for(int i = 0; i < n; i++){ B[i] = new int[n]; for(int j = 0; j < n; j++){ B[i][j] = -1; } } for(int i = 0; i < q; i++){ int j, k, val; cin >> j >> k >> val; B[j-1][k-1] = val; } bool ans = FILLMTR(B, n); if(ans){ cout << "yes" << endl; }else{ cout << "no" << endl; } } }
[ "viralipurbey4567@gmail.com" ]
viralipurbey4567@gmail.com
cd1cc760da22b2e3e186195057a0029ef8bdb086
a3a7d5a213527237f649b1cd0e4052789fca6db3
/BOJ/BOJ_2609_최대공약수와최소공배수.cpp
8d9d6fa55a5bb7e951d209c3db5a2c0fadeda9b4
[]
no_license
yuchanleeme/Problem_Solving
5d84cda878a674783d9b270f7cf17f73f552156a
b68960103702bbbbdcd156a1d13596acdb021dc2
refs/heads/master
2021-11-15T04:53:20.053863
2021-10-23T16:46:05
2021-10-23T16:46:05
185,592,120
0
0
null
null
null
null
UTF-8
C++
false
false
612
cpp
#include <iostream> #include <vector> using namespace std; //https://www.acmicpc.net/problem/2609 /* <최대공약수와 최소공배수> 주요: 유클리드 알고리즘 1. 유클리드 알고리즘을 구현한다. 2. 차례대로 최대공약수와 최소공배수를 출력한다. */ // 최대공약수 int gcd(int a, int b){ if(b == 0){ return a; } else{ return gcd(b, a%b); } } // 최소공배수 long long lcm (int a, int b){ int val = gcd(a, b); return val * (a/val) *(b/val); } int main() { int N, M; cin >> N >> M; cout << gcd(N,M) << '\n' << lcm(N,M); return 0; }
[ "yuchanlee.me@gmail.com" ]
yuchanlee.me@gmail.com
f3a96aca3f57f16970ffef7f19796718193a2042
47a95b0fb223fbb85f85413bc80d4d2225478583
/Source/AlumCockSGJ/Actors/Interactive/InteractiveActor.cpp
718dd64312ce9f84ad75e783af43fc91e8ec3642
[]
no_license
slavarsound/AlumCockSGJ
7e4972b99d3c517ab98181ad4ffe0b60eaede686
5d70de5c707801d61f2bc65f46ef299d2927798e
refs/heads/main
2023-08-30T08:37:34.976336
2021-10-30T07:10:18
2021-10-30T07:10:18
422,815,024
0
0
null
2021-10-30T07:33:29
2021-10-30T07:33:29
null
UTF-8
C++
false
false
1,534
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "InteractiveActor.h" #include "Characters/BaseCharacter.h" // Called when the game starts or when spawned void AInteractiveActor::BeginPlay() { Super::BeginPlay(); if (IsValid(InteractionVolume)) { InteractionVolume->OnComponentBeginOverlap.AddDynamic(this, &AInteractiveActor::OnInteractionVolumeOverlapBegin); InteractionVolume->OnComponentEndOverlap.AddDynamic(this, &AInteractiveActor::OnInteractionVolumeOverlapEnd); } } void AInteractiveActor::OnInteractionVolumeOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { ABaseCharacter* Character = Cast<ABaseCharacter>(OtherActor); if (!IsOverlappingCharacterCapsule(Character, OtherComp)) return; Character->RegisterInteractiveActor(this); } void AInteractiveActor::OnInteractionVolumeOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex) { ABaseCharacter* Character = Cast<ABaseCharacter>(OtherActor); if (!IsOverlappingCharacterCapsule(Character, OtherComp)) return; Character->UnregisterInteractiveActor(this); } bool AInteractiveActor::IsOverlappingCharacterCapsule(const ACharacter* Character, const UPrimitiveComponent* OtherComp) const { return IsValid(Character) && OtherComp == reinterpret_cast<UPrimitiveComponent*>(Character->GetCapsuleComponent()); }
[ "reddification@gmail.com" ]
reddification@gmail.com
e520be28a2e05ec9db8576354897c373f661ea6d
eedd7f3468f62c60774b4bcc44df9195d0520a9c
/7.25 LeetCode/7.25 LeetCode/test.cpp
3c1b562fd5f2fa1f7834a2df34bf2eb21cb1c204
[]
no_license
shanzhou-buaa/class
702d6f32a1b73c4bb8cab0aed80ac4cb1b5b816a
d40691316ce0b8bab333cf4789e2d1d4934f3992
refs/heads/master
2023-07-11T06:24:57.789855
2021-08-10T08:10:30
2021-08-10T08:10:30
329,871,744
0
0
null
null
null
null
UTF-8
C++
false
false
347
cpp
#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <stdbool.h> #include <time.h> #include <windows.h> #include <iostream> #include <string> #include <vector> #include <list> #include <stack> #include <queue> using namespace std; int main() { return 0; }
[ "2115362170@qq.com" ]
2115362170@qq.com
6f1df1e795eb04dc37d4763b1eca7279a3e77870
ef3a7391b0a5c5d8e276355e97cbe4de621d500c
/venv/Lib/site-packages/torch/include/caffe2/operators/enforce_finite_op.h
97435fea3f4c71af212cdb90d80103bf782a32ea
[ "Apache-2.0" ]
permissive
countBMB/BenjiRepo
143f6da5d198ea6f06404b4559e1f4528b71b3eb
79d882263baaf2a11654ca67d2e5593074d36dfa
refs/heads/master
2022-12-11T07:37:04.807143
2019-12-25T11:26:29
2019-12-25T11:26:29
230,090,428
1
1
Apache-2.0
2022-12-08T03:21:09
2019-12-25T11:05:59
Python
UTF-8
C++
false
false
1,134
h
#ifndef CAFFE_OPERATORS_ENFORCE_FINITE_OP_H_ #define CAFFE_OPERATORS_ENFORCE_FINITE_OP_H_ #include "caffe2/core/context.h" #include "caffe2/core/logging.h" #include "caffe2/core/operator.h" #include "caffe2/utils/math.h" namespace caffe2 { template <class Context> class EnforceFiniteOp final : public Operator<Context> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; template <class... Args> explicit EnforceFiniteOp(Args&&... args) : Operator<Context>(std::forward<Args>(args)...) {} bool RunOnDevice() override { return DispatchHelper<TensorTypes<float, double>>::call(this, Input(0)); } template <typename T> bool DoRunWithType(); private: Tensor buffer_{CPU}; template <typename T> void EnforceOnCPU(const Tensor& input) { const T* input_data = input.template data<T>(); auto size = input.numel(); for (auto i = 0; i < size; i++) { CAFFE_ENFORCE( std::isfinite(input_data[i]), "Index ", i, " is not finite (e.g., NaN, Inf): ", input_data[i]); } } }; } // namespace caffe2 #endif // CAFFE_OPERATORS_ENFORCE_FINITE_OP_H_
[ "bengmen92@gmail.com" ]
bengmen92@gmail.com
90075a69a6cf41d390679d46f297c0b2a4e345ac
426e6d4c9147d105087f0d5c13fbb58d57758e39
/trunk/pacman/jni/json_helper.cpp
94477391e3d6c1f4f8ce56a170c7c80c584e67a2
[]
no_license
Im-dex/pacman
52e08d183cd4785472f9d7de4a84863a3479e764
26c545aa21adba35ec00e8fc8c515e6a54a76bb4
refs/heads/master
2021-05-04T06:42:01.518772
2012-10-15T00:59:21
2012-10-15T00:59:21
70,499,036
1
0
null
null
null
null
UTF-8
C++
false
false
3,870
cpp
#include "json_helper.h" #include "error.h" namespace Pacman { namespace JsonHelper { Value::Value(const std::string& data) { Json::Reader reader; const bool parseResult = reader.parse(data, mRoot, false); PACMAN_CHECK_ERROR(parseResult && mRoot.isObject()); } Value::Value(const Json::Value value) : mRoot(value) { } template <> std::string Value::GetAs<std::string>() const { PACMAN_CHECK_ERROR(mRoot.isString()); return mRoot.asString(); } template <> int8_t Value::GetAs<int8_t>() const { PACMAN_CHECK_ERROR(mRoot.isNumeric()); return static_cast<int8_t>(mRoot.asInt()); } template <> int16_t Value::GetAs<int16_t>() const { PACMAN_CHECK_ERROR(mRoot.isNumeric()); return static_cast<int16_t>(mRoot.asInt()); } template <> int32_t Value::GetAs<int32_t>() const { PACMAN_CHECK_ERROR(mRoot.isNumeric()); return static_cast<int32_t>(mRoot.asInt()); } template <> int64_t Value::GetAs<int64_t>() const { PACMAN_CHECK_ERROR(mRoot.isNumeric()); return static_cast<int64_t>(mRoot.asInt()); } template <> uint8_t Value::GetAs<uint8_t>() const { PACMAN_CHECK_ERROR(mRoot.isNumeric()); return static_cast<uint8_t>(mRoot.asUInt()); } template <> uint16_t Value::GetAs<uint16_t>() const { PACMAN_CHECK_ERROR(mRoot.isNumeric()); return static_cast<uint16_t>(mRoot.asUInt()); } template <> uint32_t Value::GetAs<uint32_t>() const { PACMAN_CHECK_ERROR(mRoot.isNumeric()); return static_cast<uint32_t>(mRoot.asUInt()); } template <> uint64_t Value::GetAs<uint64_t>() const { PACMAN_CHECK_ERROR(mRoot.isNumeric()); return static_cast<uint64_t>(mRoot.asUInt()); } template <> float Value::GetAs<float>() const { PACMAN_CHECK_ERROR(mRoot.isNumeric()); return static_cast<float>(mRoot.asDouble()); } template <> double Value::GetAs<double>() const { PACMAN_CHECK_ERROR(mRoot.isNumeric()); mRoot.asDouble(); } template <> bool Value::GetAs<bool>() const { PACMAN_CHECK_ERROR(mRoot.isBool()); return mRoot.asBool(); } template <> Value Value::GetAs<Value>() const { return *this; } template <> Array Value::GetAs<Array>() const { PACMAN_CHECK_ERROR(mRoot.isArray()); return Array(mRoot); } template <> Value Value::GetValue<Value>(const std::string& name) const { const Json::Value val = mRoot[name]; PACMAN_CHECK_ERROR(val.isObject()); return Value(val); } //========================================================================= ArrayIterator::ArrayIterator(const Json::Value value) : mValue(value), mPosition(0) { } ArrayIterator::ArrayIterator(Json::Value value, const size_t position) : mValue(value), mPosition(position) { } bool ArrayIterator::operator== (const ArrayIterator& other) const { return mPosition == other.mPosition; } bool ArrayIterator::operator!= (const ArrayIterator& other) const { return mPosition != other.mPosition; } Value ArrayIterator::operator* () const { return Value(mValue[mPosition]); } ArrayIterator& ArrayIterator::operator++ () { ++mPosition; return *this; } ArrayIterator ArrayIterator::operator++ (int) { return ArrayIterator(mValue, mPosition++); } Array::Array(const Json::Value value) : mValue(value) { } Value Array::operator[] (const size_t index) const { PACMAN_CHECK_ERROR(index < GetSize()); return Value(mValue[index]); } size_t Array::GetSize() const { return mValue.size(); } ArrayIterator Array::begin() const { return ArrayIterator(mValue); } ArrayIterator Array::end() const { return ArrayIterator(mValue, GetSize()); } } // JsonHelper namespace } // Pacman namespace
[ "Im-dex@users.noreply.github.com" ]
Im-dex@users.noreply.github.com
395d42a6de63c0727a8e491dab2fa2e187000141
c3918b6f6dd5d0aa78483d9e494d8137c0dd4564
/Server/ServerCoreModules/CoreModules/Database/Tables/Playlist/Fields/playlistName1.cpp
2f215fe833cba680857d0902394cb00e9fa82d77
[]
no_license
cm226/HTML-Media-Center
3756ef456ca23453f55fbd6e5780cb9621894481
1f47b77c6f3b1f2ef7617debee3386b97efa1330
refs/heads/master
2022-08-05T20:44:28.126007
2022-05-03T19:31:25
2022-05-03T19:31:25
3,529,546
1
1
null
2021-08-20T12:42:37
2012-02-23T20:28:55
C++
UTF-8
C++
false
false
634
cpp
#include "playlistName.h" namespace DatabaseTables{ namespace Playlist{ namespace Fields{ playlistName::playlistName():DatabaseTables::DatabaseTableField<std::string>("Playlist") { } playlistName::~playlistName() { } std::string playlistName::getName() { return "Playlist.playlistName"; } std::string playlistName::fieldName() { return "playlistName"; } std::string playlistName::getStrValue() { std::stringstream ss; ss << this->getValue(); return ss.str(); } void playlistName::takeValue(ResultWrapper* resRwapper) { std::string value = resRwapper->getString("playlistName");this->setValue(&value); } } } }
[ "c.matear@gmail.com" ]
c.matear@gmail.com
aa19be0e82e39e86e48b3189b029e81041412a58
5e6910a3e9a20b15717a88fd38d200d962faedb6
/Google/Codejam2021/Round1-B/A.cpp
e5879dce198ed3d193cdae7778c7cd20640c84da
[]
no_license
khaledsliti/CompetitiveProgramming
f1ae55556d744784365bcedf7a9aaef7024c5e75
635ef40fb76db5337d62dc140f38105595ccd714
refs/heads/master
2023-08-29T15:12:04.935894
2023-08-15T13:27:12
2023-08-15T13:27:12
171,742,989
3
0
null
null
null
null
UTF-8
C++
false
false
3,411
cpp
// RedStone #include <bits/stdc++.h> using namespace std; #define pb push_back #define mp make_pair #define endl '\n' #define sz(x) ((int)(x).size()) #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() typedef long long ll; // Region Debug string to_string(const string &s) { return '"' + s + '"'; } string to_string(const char* s) { return to_string((string) s); } string to_string(bool b) { return (b ? "true" : "false"); } template<typename A, typename B> string to_string(const pair<A, B>& p); template <typename A, typename B, typename C> string to_string(tuple<A, B, C> p); template<typename T> string to_string(const vector<T>& v) { string res = "{"; for (int i = 0; i < static_cast<int>(v.size()); i++) { if (i > 0) res += ", "; res += to_string(v[i]); } res += "}"; return res; } template <size_t N> string to_string(bitset<N> v) { string res = ""; for (size_t i = 0; i < N; i++) { res += static_cast<char>('0' + v[i]); } return res; } template <typename A> string to_string(A v) { bool first = true; string res = "{"; for (const auto &x : v) { if (!first) res += ", "; first = false; res += to_string(x); } res += "}"; return res; } template<typename A, typename B> string to_string(const pair<A, B>& p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; } template <typename A, typename B, typename C> string to_string(tuple<A, B, C> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")"; } void debug_out() { cerr << endl; } template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) { cerr << " " << to_string(H); debug_out(T...); } #define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__) // End Region const ll T = 10000000000LL; const ll N = 1000000000LL; const ll nano_per_day = 12LL * 60 * 60 * N; const ll nano_per_hour = 60LL * 60 * N; const ll nano_per_min = 60 * N; bool check(ll A, ll B, ll C, ll h, ll m, ll s, ll n) { if (h < 0 || h >= 12 || m < 0 || m >= 60 || s < 0 || s >= 60 || n >= N) return false; // debug(A, B, C); // debug(h, m, s, n); ll nano = n + s * N + m * 60 * N + h * 60 * 60 * N; ll a = nano; nano -= h * 60 * 60 * N; ll b = nano * 12; nano -= m * 60 * N; ll c = nano * 720; // debug(a, b, c); return A == a && B == b && C == c; } bool solve(ll A, ll B, ll C) { // debug(A, B, C); ll h = A / (360LL * 12LL * T / 12LL); ll m = B / (360LL * 12LL * T / 60LL); ll s = C / (360LL * 12LL * T / 60LL); ll n = (C - s) / 720; // debug(h, m, s, n); if(check(A, B, C, h, m, s, n)) { cout << h << " " << m << " " << s << " " << n << endl; return true; } if((C - s) % 720 != 0) { ll d = 720 - ((C - s) % 720); // debug(d); A = (A + d) % nano_per_day; B = (B + d) % nano_per_hour; C = (C + d) % nano_per_min; return solve(A, B, C); } // debug(A, B, C); return false; } void solve() { vector<long long> v(3); for(int i = 0; i < sz(v); i++) { cin >> v[i]; } sort(all(v)); do { if(solve(v[0], v[1], v[2])) return; } while(next_permutation(all(v))); } int main() { // cout << solve(0, 11, 719) << endl; // return 0; int T; cin >> T; for(int tc = 1; tc <= T; tc++) { cout << "Case #" << tc << ": "; solve(); } return 0; }
[ "khaled.sliti1@gmail.com" ]
khaled.sliti1@gmail.com
a85b042d0d0231f99038c3c25a0509c8c64e2fc5
efd80acbef5552e2c01417457bba0c0a5aacb607
/AtCoder_PastProblems/ABC_035/A.cpp
0e73d0a82c9baafacde8e2bb7697cb289a5a9ef4
[]
no_license
skyto0927/Programming-Contest
4e590a1f17ba61f58af91932f52bedeeff8039e8
5966bd843d9dec032e5b6ff20206d54c9cbf8b14
refs/heads/master
2021-06-04T05:02:58.491853
2020-10-06T21:55:14
2020-10-06T21:55:14
135,557,393
0
0
null
null
null
null
UTF-8
C++
false
false
390
cpp
#include <bits/stdc++.h> using namespace std; #define REP(i, n) for(int i = 0; i < n; i++) #define REPR(i, n) for(int i = n; i >= 0; i--) #define FOR(i, m, n) for(int i = m; i < n; i++) #define ALL(obj) (obj).begin(), (obj).end() #define INF 1e9 #define LINF 1e18 typedef long long ll; int main() { int w,h; cin >> w >> h; cout << (w*3==h*4?"4:3":"16:9") << endl; return 0; }
[ "skyto0927@gmail.com" ]
skyto0927@gmail.com
7829607cb8eab109b5ab9d323a64e5e95a6eceaa
04b1803adb6653ecb7cb827c4f4aa616afacf629
/chromeos/components/multidevice/fake_secure_message_delegate.h
8bb1aaa7ec1d1feffbdc8d4beb5e244ea8f401fa
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
2,064
h
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROMEOS_COMPONENTS_MULTIDEVICE_FAKE_SECURE_MESSAGE_DELEGATE_H_ #define CHROMEOS_COMPONENTS_MULTIDEVICE_FAKE_SECURE_MESSAGE_DELEGATE_H_ #include "base/macros.h" #include "chromeos/components/multidevice/secure_message_delegate.h" namespace chromeos { namespace multidevice { // Fake implementation of SecureMessageDelegate used in tests. // For clarity in tests, all functions in this delegate will invoke their // callback with the result before returning. class FakeSecureMessageDelegate : public SecureMessageDelegate { public: FakeSecureMessageDelegate(); ~FakeSecureMessageDelegate() override; // SecureMessageDelegate: void GenerateKeyPair(const GenerateKeyPairCallback& callback) override; void DeriveKey(const std::string& private_key, const std::string& public_key, const DeriveKeyCallback& callback) override; void CreateSecureMessage( const std::string& payload, const std::string& key, const CreateOptions& create_options, const CreateSecureMessageCallback& callback) override; void UnwrapSecureMessage( const std::string& serialized_message, const std::string& key, const UnwrapOptions& unwrap_options, const UnwrapSecureMessageCallback& callback) override; // Returns the corresponding private key for the given |public_key|. std::string GetPrivateKeyForPublicKey(const std::string& public_key); // Sets the next public key to be returned by GenerateKeyPair(). The // corresponding private key will be derived from this public key. void set_next_public_key(const std::string& public_key) { next_public_key_ = public_key; } private: std::string next_public_key_; DISALLOW_COPY_AND_ASSIGN(FakeSecureMessageDelegate); }; } // namespace multidevice } // namespace chromeos #endif // CHROMEOS_COMPONENTS_MULTIDEVICE_FAKE_SECURE_MESSAGE_DELEGATE_H_
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
f9c558e7c0fcd2020873d4a91b60925700d9fe91
b48930fd7547a852a3770256bfdf54dd02c3f7e4
/examples/restclient/JsonPlaceholderApi/mainwindow.cpp
8e9b920339ea10432e0ae4b53065b1c568ccb6bc
[ "BSD-3-Clause" ]
permissive
Skycoder42/QtRestClient
9a0e8c244001df1c561c0a75566ea007eb7542c7
62c3bce0cabe24a9b54b87af43e85da4c5061273
refs/heads/master
2022-06-07T11:02:48.988085
2022-05-27T19:53:03
2022-05-27T19:53:03
77,643,340
89
31
BSD-3-Clause
2022-05-27T19:53:04
2016-12-29T22:21:36
C++
UTF-8
C++
false
false
3,004
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QMessageBox> using namespace QtRestClient; MainWindow::MainWindow(QWidget *parent) : QWidget(parent), ui(new Ui::MainWindow), api(new ExampleApi(this)) { ui->setupUi(this); api->restClient()->setModernAttributes(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_reloadButton_clicked() { ui->postsTreeWidget->clear(); ui->reloadButton->setEnabled(false); api->posts()->listPosts()->onSucceeded([this](int code, QList<Post> posts){ ui->loadStatusLabel->setText(QStringLiteral("Status: %1").arg(code)); ui->reloadButton->setEnabled(true); for(const auto& post : qAsConst(posts)) { new QTreeWidgetItem(ui->postsTreeWidget, { QString::number(post.id()), QString::number(post.userId()), post.title(), post.body() }); } })->onAllErrors([this](QString error, int code, RestReply::ErrorType type){ onError(true, error, code, type); }); } void MainWindow::onError(bool isLoad, const QString& error, int code, RestReply::ErrorType type) { if(isLoad) ui->loadStatusLabel->setText(QStringLiteral("Status: %1").arg(type == RestReply::FailureError ? code : -1)); else ui->editStatusLabel->setText(QString::number(type == RestReply::FailureError ? code : -1)); QMessageBox::critical(this, QStringLiteral("Error of type %1").arg(type), QStringLiteral("Code: %1\nError Text: %2").arg(code).arg(error)); } void MainWindow::on_addButton_clicked() { api->posts()->savePost(getPost())->onSucceeded([this](int code, Post post){ ui->editStatusLabel->setText(QString::number(code)); setPost(post); })->onAllErrors([this](QString error, int code, RestReply::ErrorType type){ onError(false, error, code, type); }); } void MainWindow::on_updateButton_clicked() { api->posts()->updatePost(getPost(), ui->idSpinBox->value())->onSucceeded([this](int code, Post post){ ui->editStatusLabel->setText(QString::number(code)); setPost(post); })->onAllErrors([this](QString error, int code, RestReply::ErrorType type){ onError(false, error, code, type); }); } void MainWindow::on_deleteButton_clicked() { api->posts()->deletePost(ui->idSpinBox->value())->onSucceeded([this](int code){ ui->editStatusLabel->setText(QString::number(code)); clearPost(); })->onAllErrors([this](QString error, int code, RestReply::ErrorType type){ onError(false, error, code, type); }); } Post MainWindow::getPost() const { Post p; p.setId(ui->idSpinBox->value()); p.setUserId(ui->userIDSpinBox->value()); p.setTitle(ui->titleLineEdit->text()); p.setBody(ui->bodyLineEdit->text()); return p; } void MainWindow::setPost(const Post &post) { ui->replyIdBox->setValue(post.id()); ui->replyUserBox->setValue(post.userId()); ui->replyTitleBox->setText(post.title()); ui->replyBodyBox->setText(post.body()); } void MainWindow::clearPost() { ui->replyIdBox->clear(); ui->replyUserBox->clear(); ui->replyTitleBox->clear(); ui->replyBodyBox->clear(); }
[ "Skycoder42@users.noreply.github.com" ]
Skycoder42@users.noreply.github.com
22a6f37ee13fa99b520b8400534124814024a371
b526330604e6cc42b4604dee855ba3291f2df454
/CodeLib/Geometry/POJ 3565 Ants.cpp
760aeb64ea6c6aac1939f35a91b715cbd096f320
[]
no_license
KamikazeChan/Contest
039166160140b1eb424cbcc2e2765e6f04d3cafc
dcacfee07e7c7c201205b73dc1d92281e6824c63
refs/heads/master
2021-01-24T23:11:44.978319
2014-12-15T10:38:15
2014-12-15T10:38:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,109
cpp
/* ** POJ 3565 Ants ** Created by Rayn @@ 2014/07/23 */ #include <cstdio> #include <cstring> #include <vector> #include <queue> #include <cmath> #include <algorithm> using namespace std; const int MAXN = 110; const double EPS = 1e-8; struct Point { double x, y; Point(double x = 0, double y = 0): x(x), y(y) {} void Read() { scanf("%lf%lf", &x, &y); } } ants[MAXN], apple[MAXN]; typedef Point Vector; Vector operator + (const Point& A, const Point& B) { return Vector(A.x+B.x, A.y+B.y); } Vector operator - (const Point& A, const Point& B) { return Vector(A.x-B.x, A.y-B.y); } int dcmp(double x) { if(fabs(x) < EPS) return 0; else return (x < 0)? -1 : 1; } double Cross(const Vector& A, const Vector& B) { return A.x*B.y - A.y*B.x; } bool SegmentProperIntersect(Point a1, Point a2, Point b1, Point b2) { double d1 = Cross(a2-a1, b1-a1), d2 = Cross(a2-a1, b2-a1), d3 = Cross(b2-b1, a1-b1), d4 = Cross(b2-b1, a2-b1); return dcmp(d1*d2) < 0 && dcmp(d3*d4) < 0; } int main() { #ifdef _Rayn //freopen("in.txt", "r", stdin); #endif // _Rayn int n; int link[MAXN]; while(scanf("%d", &n) != EOF && n) { for(int i = 1; i <= n; ++i) { ants[i].Read(); } for(int i = 1; i <= n; ++i) { apple[i].Read(); } for(int i = 1; i <= n; ++i) { link[i] = i; } while(1) { bool ok = true; for(int i = 1; i <= n; ++i) { for(int j = 1; j <= n; ++j) { if(i == j) continue; if(SegmentProperIntersect(ants[i], apple[link[i]], ants[j], apple[link[j]])) { swap(link[i], link[j]); ok = false; } } } if(ok) break; } for(int i = 1; i <= n; ++i) { printf("%d\n", link[i]); } } return 0; }
[ "rayn1027@outlook.com" ]
rayn1027@outlook.com
b4c6fb44bc1d3a5ded34c240353efb7df0ad1b19
bdf82a1df2993812355521e098d9c804004f4ff7
/engine/input/macos/GamepadDeviceIOKit.hpp
2c346a731b884fde2d6527cc05b869af65c40d7c
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
elnormous/ouzel
0561dce5c04d1c9990c9d3f0ff5d747b93a3b77a
b44958765b412bad80a8f621c3c99ac00ed7f429
refs/heads/master
2023-08-06T23:51:10.982327
2023-07-25T05:02:14
2023-07-25T05:02:14
48,319,858
1,053
144
Unlicense
2023-07-23T10:41:29
2015-12-20T12:40:52
C++
UTF-8
C++
false
false
1,742
hpp
// Ouzel by Elviss Strazdins #ifndef OUZEL_INPUT_GAMEPADDEVICEIOKIT_HPP #define OUZEL_INPUT_GAMEPADDEVICEIOKIT_HPP #include <unordered_map> #include <IOKit/hid/IOHIDManager.h> #include "GamepadDeviceMacOS.hpp" #include "../Gamepad.hpp" namespace ouzel::input::macos { class GamepadDeviceIOKit final: public GamepadDevice { public: GamepadDeviceIOKit(InputSystem& initInputSystem, DeviceId initId, IOHIDDeviceRef initDevice); auto getDevice() const noexcept { return device; } void handleInput(IOHIDValueRef value); private: void handleAxisChange(CFIndex oldValue, CFIndex newValue, CFIndex min, CFIndex range, Gamepad::Button negativeButton, Gamepad::Button positiveButton); IOHIDDeviceRef device = nullptr; IOHIDElementRef hatElement = nullptr; CFIndex hatValue = 8; struct Button final { Gamepad::Button button = Gamepad::Button::none; CFIndex value = 0; }; std::unordered_map<IOHIDElementRef, Button> buttons; struct Axis final { Gamepad::Axis axis = Gamepad::Axis::none; CFIndex min = 0; CFIndex max = 0; CFIndex range = 0; CFIndex value = 0; Gamepad::Button negativeButton = Gamepad::Button::none; Gamepad::Button positiveButton = Gamepad::Button::none; }; std::unordered_map<IOHIDElementRef, Axis> axes; bool hasLeftTrigger = false; bool hasRightTrigger = false; }; } #endif // OUZEL_INPUT_GAMEPADDEVICEIOKIT_HPP
[ "elviss@elviss.lv" ]
elviss@elviss.lv
7315ea6184399d394e33d819a4c6eff68054c409
197fb1ee13ca7b27dc2e31405cd41366e6152945
/include/common.hpp
89002c0c1f9c9a7936759932aa4b564a5b651c83
[]
no_license
bpedret/Sassena-GPU
c0db207e70e25934f191215c28074e5a61a243b0
816f789bcd6dad9bb06969874766b9a993f55465
refs/heads/master
2021-01-20T20:41:39.797195
2016-07-21T13:05:29
2016-07-21T13:05:29
63,868,252
0
0
null
null
null
null
UTF-8
C++
false
false
775
hpp
/** \file The content of this file is included by any other file within the project. Use it to apply application wide modifications. \author Benjamin Lindner <ben@benlabs.net> \version 1.3.0 \copyright GNU General Public License */ #ifndef COMMON_HPP_ #define COMMON_HPP_ //#ifdef CMAKE_CXX_COMPILER_ENV_VAR //// needed for xdrfile module //#define C_PLUSPLUS //#endif // standard header #include <cuComplex.h> #include <cstring> #include <sstream> #include <fstream> #include <vector> // special library headers // other headers // define here #define PRECISION_TYPE_SINGLE // triggers here #ifdef PRECISION_TYPE_DOUBLE typedef double coor_t; typedef double coor2_t; #endif #ifdef PRECISION_TYPE_SINGLE typedef float coor_t; typedef double coor2_t; #endif #endif
[ "b.pedret@students.aula-ee.com" ]
b.pedret@students.aula-ee.com
f2682fa7a92421cf1ce59773cee2075b90b62be8
55ece00803eb84a77278fb847ce93dc63ac50807
/http_server/httpserver/http_server.h
9ec2c0228fb414782932a6c38984588adb9fdc0f
[]
no_license
chenshuchao/practice
2dc7924c2181d5951988e972b2927289f5d585c2
af057271dad8b2a8bfbb13ee730775c96b845755
refs/heads/master
2021-01-10T13:36:37.470941
2016-01-07T08:33:22
2016-01-07T08:33:22
43,728,500
0
0
null
null
null
null
UTF-8
C++
false
false
1,176
h
#ifndef HTTPSERVER_H #define HTTPSERVER_H #include <boost/noncopyable.hpp> #include "tcp_server.h" #include "base_handler.h" #include "http_handler.h" namespace bytree { class HTTPServer : boost::noncopyable { public: HTTPServer(muduo::net::EventLoop &loop, const muduo::net::InetAddress& addr, const muduo::string& name, HTTPHandlerFactory* factory); void Start(); void Stop(); void Bind(); private: void OnCreateOrDestroyConnection(const muduo::net::TcpConnectionPtr& conn); void OnConnection(const muduo::net::TcpConnectionPtr& conn); void OnDisconnection(const muduo::net::TcpConnectionPtr& conn); void OnData(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buf, muduo::Timestamp); void CreateHandler(const muduo::net::TcpConnectionPtr& conn); void RemoveHandler(const HTTPHandlerPtr& handler); HTTPHandlerPtr FindHandler(const muduo::net::TcpConnectionPtr& conn); std::string name_; HTTPHandlerFactoryPtr handler_factory_; muduo::net::TcpServer tcp_server_; std::map<std::string, HTTPHandlerPtr> handler_map_; }; typedef boost::shared_ptr<HTTPServer> HTTPServerPtr; } #endif
[ "shuchao.me@gmail.com" ]
shuchao.me@gmail.com
39ae5f5c61474a21e2eedbb935cdd7cc567b6ada
bd01f7cd8404406e01717dd00e71569978fdbd9c
/Signal Logger/SignalLoggerGui.h
cfde1bd9fb920fd9eed96245d8b8d1375e7f6ca3
[]
no_license
JeffMcClintock/SynthEdit_SDK
d22174bc891e6f6b4ee45f6f9401f3eed0f91c4c
3a6432983b062642ec97c43fa6860001b7adac11
refs/heads/master
2023-04-14T00:02:36.263255
2023-04-10T01:02:19
2023-04-10T01:07:43
165,553,934
8
1
null
null
null
null
UTF-8
C++
false
false
1,028
h
#ifndef SIGNALLOGGERGUI_H_INCLUDED #define SIGNALLOGGERGUI_H_INCLUDED #include <vector> #include "MP_SDK_GUI.h" struct captureChunk { captureChunk(int nothing) : signal(0), signal_peak(0){}; float* signal; float* signal_peak; }; class SignalLoggerGui : public SeGuiWindowsGfxBase { public: SignalLoggerGui( IMpUnknown* host ); ~SignalLoggerGui(); // overrides virtual int32_t MP_STDCALL paint( HDC hDC ); virtual int32_t MP_STDCALL receiveMessageFromAudio( int32_t id, int32_t size, void* messageData ); virtual int32_t MP_STDCALL onLButtonDown( UINT flags, POINT point ); virtual int32_t MP_STDCALL onLButtonUp( UINT flags, POINT point ); virtual int32_t MP_STDCALL onMouseMove( UINT flags, POINT point ); void onSetZoom(); private: void Reset(); FloatGuiPin pinZoomX; FloatGuiPin pinZoomY; FloatGuiPin pinPanX; FloatGuiPin pinPanY; std::vector< std::vector<captureChunk> > signaldata; int captureCount_; int capturedFrames_; static const int peakRate = 16; POINT previousPoint_; }; #endif
[ "jef@synthedit.com" ]
jef@synthedit.com
df93a857e3aad3c252c0cb43e1297860a99afc94
9976471535fb5fd4af37528a8cc06f9cc7f8a280
/lib/FastLED/src/platforms/arm/sam/clockless_arm_sam.h
0bf0672d17b185e12289928e16b324b9cfd7b85f
[ "MIT" ]
permissive
TheMourningDawn/AmbientBeatsHeadboard
46a3aa7c2abc2ca10669d739d68752d14a4a4c0f
7d3858c420efe8b2b3cb53b6058adf63f367d508
refs/heads/master
2020-04-05T02:09:01.051516
2019-03-19T01:27:06
2019-03-19T01:27:06
156,465,779
0
0
null
null
null
null
UTF-8
C++
false
false
4,549
h
#ifndef __INC_CLOCKLESS_ARM_SAM_H #define __INC_CLOCKLESS_ARM_SAM_H FASTLED_NAMESPACE_BEGIN // Definition for a single channel clockless controller for the sam family of arm chips, like that used in the due and rfduino // See clockless.h for detailed info on how the template parameters are used. #if defined(__SAM3X8E__) #define TADJUST 0 #define TOTAL ( (T1+TADJUST) + (T2+TADJUST) + (T3+TADJUST) ) #define T1_MARK (TOTAL - (T1+TADJUST)) #define T2_MARK (T1_MARK - (T2+TADJUST)) #define SCALE(S,V) scale8_video(S,V) // #define SCALE(S,V) scale8(S,V) #define FASTLED_HAS_CLOCKLESS 1 template <uint8_t DATA_PIN, int T1, int T2, int T3, EOrder RGB_ORDER = RGB, int XTRA0 = 0, bool FLIP = false, int WAIT_TIME = 50> class ClocklessController : public CLEDController { typedef typename FastPinBB<DATA_PIN>::port_ptr_t data_ptr_t; typedef typename FastPinBB<DATA_PIN>::port_t data_t; data_t mPinMask; data_ptr_t mPort; CMinWait<WAIT_TIME> mWait; public: virtual void init() { FastPinBB<DATA_PIN>::setOutput(); mPinMask = FastPinBB<DATA_PIN>::mask(); mPort = FastPinBB<DATA_PIN>::port(); } virtual void clearLeds(int nLeds) { showColor(CRGB(0, 0, 0), nLeds, 0); } protected: // set all the leds on the controller to a given color virtual void showColor(const struct CRGB & rgbdata, int nLeds, CRGB scale) { PixelController<RGB_ORDER> pixels(rgbdata, nLeds, scale, getDither()); mWait.wait(); showRGBInternal(pixels); mWait.mark(); } virtual void show(const struct CRGB *rgbdata, int nLeds, CRGB scale) { PixelController<RGB_ORDER> pixels(rgbdata, nLeds, scale, getDither()); mWait.wait(); showRGBInternal(pixels); mWait.mark(); } #ifdef SUPPORT_ARGB virtual void show(const struct CARGB *rgbdata, int nLeds, CRGB scale) { PixelController<RGB_ORDER> pixels(rgbdata, nLeds, scale, getDither()); mWait.wait(); showRGBInternal(pixels); sei(); mWait.mark(); } #endif template<int BITS> __attribute__ ((always_inline)) inline static void writeBits(register uint32_t & next_mark, register data_ptr_t port, register uint8_t & b) { // Make sure we don't slot into a wrapping spot, this will delay up to 12.5µs for WS2812 // bool bShift=0; // while(VAL < (TOTAL*10)) { bShift=true; } // if(bShift) { next_mark = (VAL-TOTAL); }; for(register uint32_t i = BITS; i > 0; i--) { // wait to start the bit, then set the pin high while(DUE_TIMER_VAL < next_mark); next_mark = (DUE_TIMER_VAL+TOTAL); *port = 1; // how long we want to wait next depends on whether or not our bit is set to 1 or 0 if(b&0x80) { // we're a 1, wait until there's less than T3 clocks left while((next_mark - DUE_TIMER_VAL) > (T3)); } else { // we're a 0, wait until there's less than (T2+T3+slop) clocks left in this bit while((next_mark - DUE_TIMER_VAL) > (T2+T3+6+TADJUST+TADJUST)); } *port=0; b <<= 1; } } #define FORCE_REFERENCE(var) asm volatile( "" : : "r" (var) ) // This method is made static to force making register Y available to use for data on AVR - if the method is non-static, then // gcc will use register Y for the this pointer. static uint32_t showRGBInternal(PixelController<RGB_ORDER> & pixels) { // Setup and start the clock TC_Configure(DUE_TIMER,DUE_TIMER_CHANNEL,TC_CMR_TCCLKS_TIMER_CLOCK1); pmc_enable_periph_clk(DUE_TIMER_ID); TC_Start(DUE_TIMER,DUE_TIMER_CHANNEL); register data_ptr_t port asm("r7") = FastPinBB<DATA_PIN>::port(); FORCE_REFERENCE(port); *port = 0; // Setup the pixel controller and load/scale the first byte pixels.preStepFirstByteDithering(); register uint8_t b = pixels.loadAndScale0(); uint32_t next_mark = (DUE_TIMER_VAL + (TOTAL)); while(pixels.has(1)) { pixels.stepDithering(); #if (FASTLED_ALLOW_INTERRUPTS == 1) cli(); if(DUE_TIMER_VAL > next_mark) { if((DUE_TIMER_VAL - next_mark) > ((WAIT_TIME-INTERRUPT_THRESHOLD)*CLKS_PER_US)) { sei(); TC_Stop(DUE_TIMER,DUE_TIMER_CHANNEL); return DUE_TIMER_VAL; } } #endif writeBits<8+XTRA0>(next_mark, port, b); b = pixels.loadAndScale1(); writeBits<8+XTRA0>(next_mark, port,b); b = pixels.loadAndScale2(); writeBits<8+XTRA0>(next_mark, port,b); b = pixels.advanceAndLoadAndScale0(); #if (FASTLED_ALLOW_INTERRUPTS == 1) sei(); #endif }; TC_Stop(DUE_TIMER,DUE_TIMER_CHANNEL); return DUE_TIMER_VAL; } }; #endif FASTLED_NAMESPACE_END #endif
[ "TheMourningDawn@gmail.com" ]
TheMourningDawn@gmail.com
e40503f89dc8202ac7e803d17b0c4621c8b382a3
d4da977bb5f060d6b4edebfdf32b98ee91561b16
/Note/集训队作业/2015/作业2/11j_bash_杜瑜皓/Cellular Automaton/CellularAutomaton.cpp
7016eedd582d1ec4d9f364f7c9c4b951e78af9b1
[]
no_license
lychees/ACM-Training
37f9087f636d9e4eead6c82c7570e743d82cf68e
29fb126ad987c21fa204c56f41632e65151c6c23
refs/heads/master
2023-08-05T11:21:22.362564
2023-07-21T17:49:53
2023-07-21T17:49:53
42,499,880
100
22
null
null
null
null
UTF-8
C++
false
false
1,425
cpp
#include <bits/stdc++.h> using namespace std; #define rep(i,a,n) for (int i=a;i<n;i++) #define per(i,a,n) for (int i=n-1;i>=a;i--) #define pb push_back #define mp make_pair #define all(x) (x).begin(),(x).end() #define SZ(x) ((int)(x).size()) #define fi first #define se second typedef vector<int> VI; typedef long long ll; typedef pair<int,int> PII; const ll mod=1000000007; ll powmod(ll a,ll b) {ll res=1;a%=mod;for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;} // head const int N=2010; int u[N],v[N],w[N],dis[N],tot,sp[N]; int ww,x; char s[N]; void add(int x,int y,int l,int r) { u[tot]=x; v[tot]=y; w[tot]=r; tot++; u[tot]=y; v[tot]=x; w[tot]=-l; tot++; } bool check(int p,int s) { sp[p]=s; tot=0; rep(i,0,x) if (i<=p) add(2*i,2*i+1,-sp[i],-sp[i]); else add(2*i,2*i+1,-1,0); rep(i,0,x) add(2*i+1,2*(2*i%x),0,0),add(2*i+1,2*(2*i%x+1),1,1); rep(i,0,2*x) dis[i]=1<<30; dis[0]=0; bool fg=0; rep(i,0,2*x+1) { fg=0; rep(j,0,tot) if (dis[u[j]]>dis[v[j]]+w[j]) { dis[u[j]]=dis[v[j]]+w[j]; fg=1; } } return !fg; } void dfs(int p,int f) { if (p==x) { rep(i,0,p) putchar(sp[i]+'0'); puts(""); throw 0; } else { rep(i,f==0?(s[p]-'0'):0,2) if (check(p,i)) dfs(p+1,f|(i!=s[p]-'0')); } } int main() { freopen("idtire.in","r",stdin); freopen("idtire.out","w",stdout); scanf("%d",&ww); scanf("%s",s); x=1<<(2*ww+1); try { dfs(0,0); } catch(int e) { return 0; } puts("no"); }
[ "lychees67@gmail.com" ]
lychees67@gmail.com
001465e8449b6bb40bc5a2525d4cabb6e1a03402
93343c49771b6e6f2952d03df7e62e6a4ea063bb
/HDOJ/1794.cpp
20cf905832f750a752adddd6712b61966650c05d
[]
no_license
Kiritow/OJ-Problems-Source
5aab2c57ab5df01a520073462f5de48ad7cb5b22
1be36799dda7d0e60bd00448f3906b69e7c79b26
refs/heads/master
2022-10-21T08:55:45.581935
2022-09-24T06:13:47
2022-09-24T06:13:47
55,874,477
36
9
null
2018-07-07T00:03:15
2016-04-10T01:06:42
C++
UTF-8
C++
false
false
1,820
cpp
#include <cstdio> #include <cstdlib> #include <cstring> #include <vector> #include <algorithm> #include <functional> using namespace std; int mp[31][31]; int main() { int t; scanf("%d",&t); while(t--) { int n; scanf("%d",&n); vector<int> zerocntvec; int zerocnt=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { scanf("%d",&mp[i][j]); if(mp[i][j]==0) { ++zerocnt; int cnt=1; for(int sz=2;sz<=n;sz++) { for(int line=0;line<sz;line++) { for(int col=0;col<sz;col++) { /// 求这个方框的左上角和右下角 int luline=i-line; int lucol=j-col; int rdline=i+sz-line-1; int rdcol=j+sz-col-1; if(luline>=0&&lucol>=0&&rdline<n&&rdcol<n) ++cnt; } } } zerocntvec.push_back(cnt); } } } int m; scanf("%d",&m); vector<int> fillvec; for(int i=0;i<m;i++) { int x; scanf("%d",&x); fillvec.push_back(x); } sort(zerocntvec.begin(),zerocntvec.end(),greater<int>()); sort(fillvec.begin(),fillvec.end(),greater<int>()); long long ans=0; for(int i=0;i<zerocnt;i++) { ans+=zerocntvec[i]*fillvec[i]; } printf("%lld\n",ans); } return 0; }
[ "noreply@github.com" ]
noreply@github.com
b3bc7f96326e22e5844426fe6e1b94af74982cfa
49f8428d59da443db1ba0a86d1f00822e35c8eeb
/Lesson01/ClassLesson01/ClassLesson01/CChara.h
2a5833f6ef529ffb9e0aa69c7c118a66a899baed
[]
no_license
raweromon/GC2016_Cp1
619d87a182e639253dd3a11e3dd5f30ca34b946c
4f736c08475a4efb86cc892e3334ce9b53c433ab
refs/heads/master
2020-06-13T22:40:33.421578
2016-12-04T15:51:55
2016-12-04T15:51:55
75,544,824
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
316
h
/* CCharaクラス: 2016/11/21 */ #pragma once #include <d3d.h> class CChara { protected: D3DVECTOR pos; int str; public: //関数のプロトタイプ宣言 CChara(); void setPos(D3DVECTOR); D3DVECTOR getPos(void); void setStr(int damage) { str = damage; }; int getStr(void) { return str; }; };
[ "junsai@emanon.jp" ]
junsai@emanon.jp
7e73d67b957ed7667c6e6f0f1ef5e008eeff9667
7e62f0928681aaaecae7daf360bdd9166299b000
/external/DirectXShaderCompiler/lib/DXIL/DxilOperations.cpp
bd501c96882083f642d9abbcc02f1b0dd75062ac
[ "NCSA", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yuri410/rpg
949b001bd0aec47e2a046421da0ff2a1db62ce34
266282ed8cfc7cd82e8c853f6f01706903c24628
refs/heads/master
2020-08-03T09:39:42.253100
2020-06-16T15:38:03
2020-06-16T15:38:03
211,698,323
0
0
null
null
null
null
UTF-8
C++
false
false
124,832
cpp
/////////////////////////////////////////////////////////////////////////////// // // // DxilOperations.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Implementation of DXIL operation tables. // // // /////////////////////////////////////////////////////////////////////////////// #include "dxc/DXIL/DxilOperations.h" #include "dxc/Support/Global.h" #include "dxc/DXIL/DxilModule.h" #include "dxc/DXIL/DxilInstructions.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/Type.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" using namespace llvm; using std::vector; using std::string; namespace hlsl { using OC = OP::OpCode; using OCC = OP::OpCodeClass; //------------------------------------------------------------------------------ // // OP class const-static data and related static methods. // /* <py> import hctdb_instrhelp </py> */ /* <py::lines('OPCODE-OLOADS')>hctdb_instrhelp.get_oloads_props()</py>*/ // OPCODE-OLOADS:BEGIN const OP::OpCodeProperty OP::m_OpCodeProps[(unsigned)OP::OpCode::NumOpCodes] = { // OpCode OpCode name, OpCodeClass OpCodeClass name, void, h, f, d, i1, i8, i16, i32, i64, udt, obj, function attribute // Temporary, indexable, input, output registers void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::TempRegLoad, "TempRegLoad", OCC::TempRegLoad, "tempRegLoad", { false, true, true, false, false, false, true, true, false, false, false}, Attribute::ReadOnly, }, { OC::TempRegStore, "TempRegStore", OCC::TempRegStore, "tempRegStore", { false, true, true, false, false, false, true, true, false, false, false}, Attribute::None, }, { OC::MinPrecXRegLoad, "MinPrecXRegLoad", OCC::MinPrecXRegLoad, "minPrecXRegLoad", { false, true, false, false, false, false, true, false, false, false, false}, Attribute::ReadOnly, }, { OC::MinPrecXRegStore, "MinPrecXRegStore", OCC::MinPrecXRegStore, "minPrecXRegStore", { false, true, false, false, false, false, true, false, false, false, false}, Attribute::None, }, { OC::LoadInput, "LoadInput", OCC::LoadInput, "loadInput", { false, true, true, false, false, false, true, true, false, false, false}, Attribute::ReadNone, }, { OC::StoreOutput, "StoreOutput", OCC::StoreOutput, "storeOutput", { false, true, true, false, false, false, true, true, false, false, false}, Attribute::None, }, // Unary float void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::FAbs, "FAbs", OCC::Unary, "unary", { false, true, true, true, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Saturate, "Saturate", OCC::Unary, "unary", { false, true, true, true, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::IsNaN, "IsNaN", OCC::IsSpecialFloat, "isSpecialFloat", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::IsInf, "IsInf", OCC::IsSpecialFloat, "isSpecialFloat", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::IsFinite, "IsFinite", OCC::IsSpecialFloat, "isSpecialFloat", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::IsNormal, "IsNormal", OCC::IsSpecialFloat, "isSpecialFloat", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Cos, "Cos", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Sin, "Sin", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Tan, "Tan", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Acos, "Acos", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Asin, "Asin", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Atan, "Atan", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Hcos, "Hcos", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Hsin, "Hsin", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Htan, "Htan", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Exp, "Exp", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Frc, "Frc", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Log, "Log", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Sqrt, "Sqrt", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Rsqrt, "Rsqrt", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, // Unary float - rounding void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::Round_ne, "Round_ne", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Round_ni, "Round_ni", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Round_pi, "Round_pi", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Round_z, "Round_z", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, // Unary int void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::Bfrev, "Bfrev", OCC::Unary, "unary", { false, false, false, false, false, false, true, true, true, false, false}, Attribute::ReadNone, }, { OC::Countbits, "Countbits", OCC::UnaryBits, "unaryBits", { false, false, false, false, false, false, true, true, true, false, false}, Attribute::ReadNone, }, { OC::FirstbitLo, "FirstbitLo", OCC::UnaryBits, "unaryBits", { false, false, false, false, false, false, true, true, true, false, false}, Attribute::ReadNone, }, // Unary uint void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::FirstbitHi, "FirstbitHi", OCC::UnaryBits, "unaryBits", { false, false, false, false, false, false, true, true, true, false, false}, Attribute::ReadNone, }, // Unary int void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::FirstbitSHi, "FirstbitSHi", OCC::UnaryBits, "unaryBits", { false, false, false, false, false, false, true, true, true, false, false}, Attribute::ReadNone, }, // Binary float void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::FMax, "FMax", OCC::Binary, "binary", { false, true, true, true, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::FMin, "FMin", OCC::Binary, "binary", { false, true, true, true, false, false, false, false, false, false, false}, Attribute::ReadNone, }, // Binary int void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::IMax, "IMax", OCC::Binary, "binary", { false, false, false, false, false, false, true, true, true, false, false}, Attribute::ReadNone, }, { OC::IMin, "IMin", OCC::Binary, "binary", { false, false, false, false, false, false, true, true, true, false, false}, Attribute::ReadNone, }, // Binary uint void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::UMax, "UMax", OCC::Binary, "binary", { false, false, false, false, false, false, true, true, true, false, false}, Attribute::ReadNone, }, { OC::UMin, "UMin", OCC::Binary, "binary", { false, false, false, false, false, false, true, true, true, false, false}, Attribute::ReadNone, }, // Binary int with two outputs void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::IMul, "IMul", OCC::BinaryWithTwoOuts, "binaryWithTwoOuts", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, // Binary uint with two outputs void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::UMul, "UMul", OCC::BinaryWithTwoOuts, "binaryWithTwoOuts", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, { OC::UDiv, "UDiv", OCC::BinaryWithTwoOuts, "binaryWithTwoOuts", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, // Binary uint with carry or borrow void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::UAddc, "UAddc", OCC::BinaryWithCarryOrBorrow, "binaryWithCarryOrBorrow", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, { OC::USubb, "USubb", OCC::BinaryWithCarryOrBorrow, "binaryWithCarryOrBorrow", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, // Tertiary float void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::FMad, "FMad", OCC::Tertiary, "tertiary", { false, true, true, true, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Fma, "Fma", OCC::Tertiary, "tertiary", { false, false, false, true, false, false, false, false, false, false, false}, Attribute::ReadNone, }, // Tertiary int void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::IMad, "IMad", OCC::Tertiary, "tertiary", { false, false, false, false, false, false, true, true, true, false, false}, Attribute::ReadNone, }, // Tertiary uint void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::UMad, "UMad", OCC::Tertiary, "tertiary", { false, false, false, false, false, false, true, true, true, false, false}, Attribute::ReadNone, }, // Tertiary int void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::Msad, "Msad", OCC::Tertiary, "tertiary", { false, false, false, false, false, false, false, true, true, false, false}, Attribute::ReadNone, }, { OC::Ibfe, "Ibfe", OCC::Tertiary, "tertiary", { false, false, false, false, false, false, false, true, true, false, false}, Attribute::ReadNone, }, // Tertiary uint void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::Ubfe, "Ubfe", OCC::Tertiary, "tertiary", { false, false, false, false, false, false, false, true, true, false, false}, Attribute::ReadNone, }, // Quaternary void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::Bfi, "Bfi", OCC::Quaternary, "quaternary", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, // Dot void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::Dot2, "Dot2", OCC::Dot2, "dot2", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Dot3, "Dot3", OCC::Dot3, "dot3", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Dot4, "Dot4", OCC::Dot4, "dot4", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, // Resources void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::CreateHandle, "CreateHandle", OCC::CreateHandle, "createHandle", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::CBufferLoad, "CBufferLoad", OCC::CBufferLoad, "cbufferLoad", { false, true, true, true, false, true, true, true, true, false, false}, Attribute::ReadOnly, }, { OC::CBufferLoadLegacy, "CBufferLoadLegacy", OCC::CBufferLoadLegacy, "cbufferLoadLegacy", { false, true, true, true, false, false, true, true, true, false, false}, Attribute::ReadOnly, }, // Resources - sample void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::Sample, "Sample", OCC::Sample, "sample", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::SampleBias, "SampleBias", OCC::SampleBias, "sampleBias", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::SampleLevel, "SampleLevel", OCC::SampleLevel, "sampleLevel", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::SampleGrad, "SampleGrad", OCC::SampleGrad, "sampleGrad", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::SampleCmp, "SampleCmp", OCC::SampleCmp, "sampleCmp", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::SampleCmpLevelZero, "SampleCmpLevelZero", OCC::SampleCmpLevelZero, "sampleCmpLevelZero", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, // Resources void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::TextureLoad, "TextureLoad", OCC::TextureLoad, "textureLoad", { false, true, true, false, false, false, true, true, false, false, false}, Attribute::ReadOnly, }, { OC::TextureStore, "TextureStore", OCC::TextureStore, "textureStore", { false, true, true, false, false, false, true, true, false, false, false}, Attribute::None, }, { OC::BufferLoad, "BufferLoad", OCC::BufferLoad, "bufferLoad", { false, true, true, false, false, false, true, true, false, false, false}, Attribute::ReadOnly, }, { OC::BufferStore, "BufferStore", OCC::BufferStore, "bufferStore", { false, true, true, false, false, false, true, true, false, false, false}, Attribute::None, }, { OC::BufferUpdateCounter, "BufferUpdateCounter", OCC::BufferUpdateCounter, "bufferUpdateCounter", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, { OC::CheckAccessFullyMapped, "CheckAccessFullyMapped", OCC::CheckAccessFullyMapped, "checkAccessFullyMapped", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadOnly, }, { OC::GetDimensions, "GetDimensions", OCC::GetDimensions, "getDimensions", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, // Resources - gather void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::TextureGather, "TextureGather", OCC::TextureGather, "textureGather", { false, true, true, false, false, false, true, true, false, false, false}, Attribute::ReadOnly, }, { OC::TextureGatherCmp, "TextureGatherCmp", OCC::TextureGatherCmp, "textureGatherCmp", { false, true, true, false, false, false, true, true, false, false, false}, Attribute::ReadOnly, }, // Resources - sample void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::Texture2DMSGetSamplePosition, "Texture2DMSGetSamplePosition", OCC::Texture2DMSGetSamplePosition, "texture2DMSGetSamplePosition", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::RenderTargetGetSamplePosition, "RenderTargetGetSamplePosition", OCC::RenderTargetGetSamplePosition, "renderTargetGetSamplePosition", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::RenderTargetGetSampleCount, "RenderTargetGetSampleCount", OCC::RenderTargetGetSampleCount, "renderTargetGetSampleCount", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, // Synchronization void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::AtomicBinOp, "AtomicBinOp", OCC::AtomicBinOp, "atomicBinOp", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::None, }, { OC::AtomicCompareExchange, "AtomicCompareExchange", OCC::AtomicCompareExchange, "atomicCompareExchange", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::None, }, { OC::Barrier, "Barrier", OCC::Barrier, "barrier", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::NoDuplicate, }, // Pixel shader void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::CalculateLOD, "CalculateLOD", OCC::CalculateLOD, "calculateLOD", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::Discard, "Discard", OCC::Discard, "discard", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, { OC::DerivCoarseX, "DerivCoarseX", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::DerivCoarseY, "DerivCoarseY", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::DerivFineX, "DerivFineX", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::DerivFineY, "DerivFineY", OCC::Unary, "unary", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::EvalSnapped, "EvalSnapped", OCC::EvalSnapped, "evalSnapped", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::EvalSampleIndex, "EvalSampleIndex", OCC::EvalSampleIndex, "evalSampleIndex", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::EvalCentroid, "EvalCentroid", OCC::EvalCentroid, "evalCentroid", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::SampleIndex, "SampleIndex", OCC::SampleIndex, "sampleIndex", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, { OC::Coverage, "Coverage", OCC::Coverage, "coverage", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, { OC::InnerCoverage, "InnerCoverage", OCC::InnerCoverage, "innerCoverage", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, // Compute/Mesh/Amplification shader void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::ThreadId, "ThreadId", OCC::ThreadId, "threadId", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, { OC::GroupId, "GroupId", OCC::GroupId, "groupId", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, { OC::ThreadIdInGroup, "ThreadIdInGroup", OCC::ThreadIdInGroup, "threadIdInGroup", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, { OC::FlattenedThreadIdInGroup, "FlattenedThreadIdInGroup", OCC::FlattenedThreadIdInGroup, "flattenedThreadIdInGroup", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, // Geometry shader void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::EmitStream, "EmitStream", OCC::EmitStream, "emitStream", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, { OC::CutStream, "CutStream", OCC::CutStream, "cutStream", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, { OC::EmitThenCutStream, "EmitThenCutStream", OCC::EmitThenCutStream, "emitThenCutStream", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, { OC::GSInstanceID, "GSInstanceID", OCC::GSInstanceID, "gsInstanceID", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, // Double precision void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::MakeDouble, "MakeDouble", OCC::MakeDouble, "makeDouble", { false, false, false, true, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::SplitDouble, "SplitDouble", OCC::SplitDouble, "splitDouble", { false, false, false, true, false, false, false, false, false, false, false}, Attribute::ReadNone, }, // Domain and hull shader void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::LoadOutputControlPoint, "LoadOutputControlPoint", OCC::LoadOutputControlPoint, "loadOutputControlPoint", { false, true, true, false, false, false, true, true, false, false, false}, Attribute::ReadNone, }, { OC::LoadPatchConstant, "LoadPatchConstant", OCC::LoadPatchConstant, "loadPatchConstant", { false, true, true, false, false, false, true, true, false, false, false}, Attribute::ReadNone, }, // Domain shader void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::DomainLocation, "DomainLocation", OCC::DomainLocation, "domainLocation", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, // Hull shader void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::StorePatchConstant, "StorePatchConstant", OCC::StorePatchConstant, "storePatchConstant", { false, true, true, false, false, false, true, true, false, false, false}, Attribute::None, }, { OC::OutputControlPointID, "OutputControlPointID", OCC::OutputControlPointID, "outputControlPointID", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, // Hull, Domain and Geometry shaders void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::PrimitiveID, "PrimitiveID", OCC::PrimitiveID, "primitiveID", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, // Other void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::CycleCounterLegacy, "CycleCounterLegacy", OCC::CycleCounterLegacy, "cycleCounterLegacy", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, // Wave void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::WaveIsFirstLane, "WaveIsFirstLane", OCC::WaveIsFirstLane, "waveIsFirstLane", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, { OC::WaveGetLaneIndex, "WaveGetLaneIndex", OCC::WaveGetLaneIndex, "waveGetLaneIndex", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::WaveGetLaneCount, "WaveGetLaneCount", OCC::WaveGetLaneCount, "waveGetLaneCount", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::WaveAnyTrue, "WaveAnyTrue", OCC::WaveAnyTrue, "waveAnyTrue", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, { OC::WaveAllTrue, "WaveAllTrue", OCC::WaveAllTrue, "waveAllTrue", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, { OC::WaveActiveAllEqual, "WaveActiveAllEqual", OCC::WaveActiveAllEqual, "waveActiveAllEqual", { false, true, true, true, true, true, true, true, true, false, false}, Attribute::None, }, { OC::WaveActiveBallot, "WaveActiveBallot", OCC::WaveActiveBallot, "waveActiveBallot", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, { OC::WaveReadLaneAt, "WaveReadLaneAt", OCC::WaveReadLaneAt, "waveReadLaneAt", { false, true, true, true, true, true, true, true, true, false, false}, Attribute::None, }, { OC::WaveReadLaneFirst, "WaveReadLaneFirst", OCC::WaveReadLaneFirst, "waveReadLaneFirst", { false, true, true, false, true, true, true, true, true, false, false}, Attribute::None, }, { OC::WaveActiveOp, "WaveActiveOp", OCC::WaveActiveOp, "waveActiveOp", { false, true, true, true, true, true, true, true, true, false, false}, Attribute::None, }, { OC::WaveActiveBit, "WaveActiveBit", OCC::WaveActiveBit, "waveActiveBit", { false, false, false, false, false, true, true, true, true, false, false}, Attribute::None, }, { OC::WavePrefixOp, "WavePrefixOp", OCC::WavePrefixOp, "wavePrefixOp", { false, true, true, true, false, true, true, true, true, false, false}, Attribute::None, }, // Quad Wave Ops void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::QuadReadLaneAt, "QuadReadLaneAt", OCC::QuadReadLaneAt, "quadReadLaneAt", { false, true, true, true, true, true, true, true, true, false, false}, Attribute::None, }, { OC::QuadOp, "QuadOp", OCC::QuadOp, "quadOp", { false, true, true, true, false, true, true, true, true, false, false}, Attribute::None, }, // Bitcasts with different sizes void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::BitcastI16toF16, "BitcastI16toF16", OCC::BitcastI16toF16, "bitcastI16toF16", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::BitcastF16toI16, "BitcastF16toI16", OCC::BitcastF16toI16, "bitcastF16toI16", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::BitcastI32toF32, "BitcastI32toF32", OCC::BitcastI32toF32, "bitcastI32toF32", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::BitcastF32toI32, "BitcastF32toI32", OCC::BitcastF32toI32, "bitcastF32toI32", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::BitcastI64toF64, "BitcastI64toF64", OCC::BitcastI64toF64, "bitcastI64toF64", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::BitcastF64toI64, "BitcastF64toI64", OCC::BitcastF64toI64, "bitcastF64toI64", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, // Legacy floating-point void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::LegacyF32ToF16, "LegacyF32ToF16", OCC::LegacyF32ToF16, "legacyF32ToF16", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::LegacyF16ToF32, "LegacyF16ToF32", OCC::LegacyF16ToF32, "legacyF16ToF32", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, // Double precision void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::LegacyDoubleToFloat, "LegacyDoubleToFloat", OCC::LegacyDoubleToFloat, "legacyDoubleToFloat", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::LegacyDoubleToSInt32, "LegacyDoubleToSInt32", OCC::LegacyDoubleToSInt32, "legacyDoubleToSInt32", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::LegacyDoubleToUInt32, "LegacyDoubleToUInt32", OCC::LegacyDoubleToUInt32, "legacyDoubleToUInt32", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, // Wave void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::WaveAllBitCount, "WaveAllBitCount", OCC::WaveAllOp, "waveAllOp", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, { OC::WavePrefixBitCount, "WavePrefixBitCount", OCC::WavePrefixOp, "wavePrefixOp", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, // Pixel shader void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::AttributeAtVertex, "AttributeAtVertex", OCC::AttributeAtVertex, "attributeAtVertex", { false, true, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, // Graphics shader void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::ViewID, "ViewID", OCC::ViewID, "viewID", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, // Resources void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::RawBufferLoad, "RawBufferLoad", OCC::RawBufferLoad, "rawBufferLoad", { false, true, true, true, false, false, true, true, true, false, false}, Attribute::ReadOnly, }, { OC::RawBufferStore, "RawBufferStore", OCC::RawBufferStore, "rawBufferStore", { false, true, true, true, false, false, true, true, true, false, false}, Attribute::None, }, // Raytracing object space uint System Values void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::InstanceID, "InstanceID", OCC::InstanceID, "instanceID", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, { OC::InstanceIndex, "InstanceIndex", OCC::InstanceIndex, "instanceIndex", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, // Raytracing hit uint System Values void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::HitKind, "HitKind", OCC::HitKind, "hitKind", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, // Raytracing uint System Values void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::RayFlags, "RayFlags", OCC::RayFlags, "rayFlags", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, // Ray Dispatch Arguments void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::DispatchRaysIndex, "DispatchRaysIndex", OCC::DispatchRaysIndex, "dispatchRaysIndex", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, { OC::DispatchRaysDimensions, "DispatchRaysDimensions", OCC::DispatchRaysDimensions, "dispatchRaysDimensions", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, // Ray Vectors void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::WorldRayOrigin, "WorldRayOrigin", OCC::WorldRayOrigin, "worldRayOrigin", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::WorldRayDirection, "WorldRayDirection", OCC::WorldRayDirection, "worldRayDirection", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, // Ray object space Vectors void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::ObjectRayOrigin, "ObjectRayOrigin", OCC::ObjectRayOrigin, "objectRayOrigin", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::ObjectRayDirection, "ObjectRayDirection", OCC::ObjectRayDirection, "objectRayDirection", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, // Ray Transforms void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::ObjectToWorld, "ObjectToWorld", OCC::ObjectToWorld, "objectToWorld", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::WorldToObject, "WorldToObject", OCC::WorldToObject, "worldToObject", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, // RayT void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::RayTMin, "RayTMin", OCC::RayTMin, "rayTMin", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::RayTCurrent, "RayTCurrent", OCC::RayTCurrent, "rayTCurrent", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, // AnyHit Terminals void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::IgnoreHit, "IgnoreHit", OCC::IgnoreHit, "ignoreHit", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::NoReturn, }, { OC::AcceptHitAndEndSearch, "AcceptHitAndEndSearch", OCC::AcceptHitAndEndSearch, "acceptHitAndEndSearch", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::NoReturn, }, // Indirect Shader Invocation void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::TraceRay, "TraceRay", OCC::TraceRay, "traceRay", { false, false, false, false, false, false, false, false, false, true, false}, Attribute::None, }, { OC::ReportHit, "ReportHit", OCC::ReportHit, "reportHit", { false, false, false, false, false, false, false, false, false, true, false}, Attribute::None, }, { OC::CallShader, "CallShader", OCC::CallShader, "callShader", { false, false, false, false, false, false, false, false, false, true, false}, Attribute::None, }, // Library create handle from resource struct (like HL intrinsic) void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::CreateHandleForLib, "CreateHandleForLib", OCC::CreateHandleForLib, "createHandleForLib", { false, false, false, false, false, false, false, false, false, false, true}, Attribute::ReadOnly, }, // Raytracing object space uint System Values void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::PrimitiveIndex, "PrimitiveIndex", OCC::PrimitiveIndex, "primitiveIndex", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, // Dot product with accumulate void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::Dot2AddHalf, "Dot2AddHalf", OCC::Dot2AddHalf, "dot2AddHalf", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, { OC::Dot4AddI8Packed, "Dot4AddI8Packed", OCC::Dot4AddPacked, "dot4AddPacked", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, { OC::Dot4AddU8Packed, "Dot4AddU8Packed", OCC::Dot4AddPacked, "dot4AddPacked", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, // Wave void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::WaveMatch, "WaveMatch", OCC::WaveMatch, "waveMatch", { false, true, true, true, false, true, true, true, true, false, false}, Attribute::None, }, { OC::WaveMultiPrefixOp, "WaveMultiPrefixOp", OCC::WaveMultiPrefixOp, "waveMultiPrefixOp", { false, true, true, true, false, true, true, true, true, false, false}, Attribute::None, }, { OC::WaveMultiPrefixBitCount, "WaveMultiPrefixBitCount", OCC::WaveMultiPrefixBitCount, "waveMultiPrefixBitCount", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, // Mesh shader instructions void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::SetMeshOutputCounts, "SetMeshOutputCounts", OCC::SetMeshOutputCounts, "setMeshOutputCounts", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, { OC::EmitIndices, "EmitIndices", OCC::EmitIndices, "emitIndices", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, { OC::GetMeshPayload, "GetMeshPayload", OCC::GetMeshPayload, "getMeshPayload", { false, false, false, false, false, false, false, false, false, true, false}, Attribute::ReadOnly, }, { OC::StoreVertexOutput, "StoreVertexOutput", OCC::StoreVertexOutput, "storeVertexOutput", { false, true, true, false, false, false, true, true, false, false, false}, Attribute::None, }, { OC::StorePrimitiveOutput, "StorePrimitiveOutput", OCC::StorePrimitiveOutput, "storePrimitiveOutput", { false, true, true, false, false, false, true, true, false, false, false}, Attribute::None, }, // Amplification shader instructions void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::DispatchMesh, "DispatchMesh", OCC::DispatchMesh, "dispatchMesh", { false, false, false, false, false, false, false, false, false, true, false}, Attribute::None, }, // Sampler Feedback void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::WriteSamplerFeedback, "WriteSamplerFeedback", OCC::WriteSamplerFeedback, "writeSamplerFeedback", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, { OC::WriteSamplerFeedbackBias, "WriteSamplerFeedbackBias", OCC::WriteSamplerFeedbackBias, "writeSamplerFeedbackBias", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, { OC::WriteSamplerFeedbackLevel, "WriteSamplerFeedbackLevel", OCC::WriteSamplerFeedbackLevel, "writeSamplerFeedbackLevel", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, { OC::WriteSamplerFeedbackGrad, "WriteSamplerFeedbackGrad", OCC::WriteSamplerFeedbackGrad, "writeSamplerFeedbackGrad", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, // Inline Ray Query void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::AllocateRayQuery, "AllocateRayQuery", OCC::AllocateRayQuery, "allocateRayQuery", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, { OC::RayQuery_TraceRayInline, "RayQuery_TraceRayInline", OCC::RayQuery_TraceRayInline, "rayQuery_TraceRayInline", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, { OC::RayQuery_Proceed, "RayQuery_Proceed", OCC::RayQuery_Proceed, "rayQuery_Proceed", { false, false, false, false, true, false, false, false, false, false, false}, Attribute::None, }, { OC::RayQuery_Abort, "RayQuery_Abort", OCC::RayQuery_Abort, "rayQuery_Abort", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, { OC::RayQuery_CommitNonOpaqueTriangleHit, "RayQuery_CommitNonOpaqueTriangleHit", OCC::RayQuery_CommitNonOpaqueTriangleHit, "rayQuery_CommitNonOpaqueTriangleHit", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, { OC::RayQuery_CommitProceduralPrimitiveHit, "RayQuery_CommitProceduralPrimitiveHit", OCC::RayQuery_CommitProceduralPrimitiveHit, "rayQuery_CommitProceduralPrimitiveHit", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::None, }, { OC::RayQuery_CommittedStatus, "RayQuery_CommittedStatus", OCC::RayQuery_StateScalar, "rayQuery_StateScalar", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CandidateType, "RayQuery_CandidateType", OCC::RayQuery_StateScalar, "rayQuery_StateScalar", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CandidateObjectToWorld3x4, "RayQuery_CandidateObjectToWorld3x4", OCC::RayQuery_StateMatrix, "rayQuery_StateMatrix", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CandidateWorldToObject3x4, "RayQuery_CandidateWorldToObject3x4", OCC::RayQuery_StateMatrix, "rayQuery_StateMatrix", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CommittedObjectToWorld3x4, "RayQuery_CommittedObjectToWorld3x4", OCC::RayQuery_StateMatrix, "rayQuery_StateMatrix", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CommittedWorldToObject3x4, "RayQuery_CommittedWorldToObject3x4", OCC::RayQuery_StateMatrix, "rayQuery_StateMatrix", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CandidateProceduralPrimitiveNonOpaque, "RayQuery_CandidateProceduralPrimitiveNonOpaque", OCC::RayQuery_StateScalar, "rayQuery_StateScalar", { false, false, false, false, true, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CandidateTriangleFrontFace, "RayQuery_CandidateTriangleFrontFace", OCC::RayQuery_StateScalar, "rayQuery_StateScalar", { false, false, false, false, true, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CommittedTriangleFrontFace, "RayQuery_CommittedTriangleFrontFace", OCC::RayQuery_StateScalar, "rayQuery_StateScalar", { false, false, false, false, true, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CandidateTriangleBarycentrics, "RayQuery_CandidateTriangleBarycentrics", OCC::RayQuery_StateVector, "rayQuery_StateVector", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CommittedTriangleBarycentrics, "RayQuery_CommittedTriangleBarycentrics", OCC::RayQuery_StateVector, "rayQuery_StateVector", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_RayFlags, "RayQuery_RayFlags", OCC::RayQuery_StateScalar, "rayQuery_StateScalar", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_WorldRayOrigin, "RayQuery_WorldRayOrigin", OCC::RayQuery_StateVector, "rayQuery_StateVector", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_WorldRayDirection, "RayQuery_WorldRayDirection", OCC::RayQuery_StateVector, "rayQuery_StateVector", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_RayTMin, "RayQuery_RayTMin", OCC::RayQuery_StateScalar, "rayQuery_StateScalar", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CandidateTriangleRayT, "RayQuery_CandidateTriangleRayT", OCC::RayQuery_StateScalar, "rayQuery_StateScalar", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CommittedRayT, "RayQuery_CommittedRayT", OCC::RayQuery_StateScalar, "rayQuery_StateScalar", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CandidateInstanceIndex, "RayQuery_CandidateInstanceIndex", OCC::RayQuery_StateScalar, "rayQuery_StateScalar", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CandidateInstanceID, "RayQuery_CandidateInstanceID", OCC::RayQuery_StateScalar, "rayQuery_StateScalar", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CandidateGeometryIndex, "RayQuery_CandidateGeometryIndex", OCC::RayQuery_StateScalar, "rayQuery_StateScalar", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CandidatePrimitiveIndex, "RayQuery_CandidatePrimitiveIndex", OCC::RayQuery_StateScalar, "rayQuery_StateScalar", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CandidateObjectRayOrigin, "RayQuery_CandidateObjectRayOrigin", OCC::RayQuery_StateVector, "rayQuery_StateVector", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CandidateObjectRayDirection, "RayQuery_CandidateObjectRayDirection", OCC::RayQuery_StateVector, "rayQuery_StateVector", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CommittedInstanceIndex, "RayQuery_CommittedInstanceIndex", OCC::RayQuery_StateScalar, "rayQuery_StateScalar", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CommittedInstanceID, "RayQuery_CommittedInstanceID", OCC::RayQuery_StateScalar, "rayQuery_StateScalar", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CommittedGeometryIndex, "RayQuery_CommittedGeometryIndex", OCC::RayQuery_StateScalar, "rayQuery_StateScalar", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CommittedPrimitiveIndex, "RayQuery_CommittedPrimitiveIndex", OCC::RayQuery_StateScalar, "rayQuery_StateScalar", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CommittedObjectRayOrigin, "RayQuery_CommittedObjectRayOrigin", OCC::RayQuery_StateVector, "rayQuery_StateVector", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CommittedObjectRayDirection, "RayQuery_CommittedObjectRayDirection", OCC::RayQuery_StateVector, "rayQuery_StateVector", { false, false, true, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, // Raytracing object space uint System Values, raytracing tier 1.1 void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::GeometryIndex, "GeometryIndex", OCC::GeometryIndex, "geometryIndex", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadNone, }, // Inline Ray Query void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::RayQuery_CandidateInstanceContributionToHitGroupIndex, "RayQuery_CandidateInstanceContributionToHitGroupIndex", OCC::RayQuery_StateScalar, "rayQuery_StateScalar", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadOnly, }, { OC::RayQuery_CommittedInstanceContributionToHitGroupIndex, "RayQuery_CommittedInstanceContributionToHitGroupIndex", OCC::RayQuery_StateScalar, "rayQuery_StateScalar", { false, false, false, false, false, false, false, true, false, false, false}, Attribute::ReadOnly, }, // Get handle from heap void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute { OC::CreateHandleFromHeap, "CreateHandleFromHeap", OCC::CreateHandleFromHeap, "createHandleFromHeap", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::ReadOnly, }, { OC::AnnotateHandle, "AnnotateHandle", OCC::AnnotateHandle, "annotateHandle", { true, false, false, false, false, false, false, false, false, false, false}, Attribute::ReadNone, }, }; // OPCODE-OLOADS:END const char *OP::m_OverloadTypeName[kNumTypeOverloads] = { "void", "f16", "f32", "f64", "i1", "i8", "i16", "i32", "i64", "udt", }; const char *OP::m_NamePrefix = "dx.op."; const char *OP::m_TypePrefix = "dx.types."; const char *OP::m_MatrixTypePrefix = "class.matrix."; // Allowed in library // Keep sync with DXIL::AtomicBinOpCode static const char *AtomicBinOpCodeName[] = { "AtomicAdd", "AtomicAnd", "AtomicOr", "AtomicXor", "AtomicIMin", "AtomicIMax", "AtomicUMin", "AtomicUMax", "AtomicExchange", "AtomicInvalid" // Must be last. }; unsigned OP::GetTypeSlot(Type *pType) { Type::TypeID T = pType->getTypeID(); switch (T) { case Type::VoidTyID: return 0; case Type::HalfTyID: return 1; case Type::FloatTyID: return 2; case Type::DoubleTyID: return 3; case Type::IntegerTyID: { IntegerType *pIT = dyn_cast<IntegerType>(pType); unsigned Bits = pIT->getBitWidth(); switch (Bits) { case 1: return 4; case 8: return 5; case 16: return 6; case 32: return 7; case 64: return 8; } } case Type::PointerTyID: return 9; case Type::StructTyID: return 10; default: break; } return UINT_MAX; } const char *OP::GetOverloadTypeName(unsigned TypeSlot) { DXASSERT(TypeSlot < kUserDefineTypeSlot, "otherwise caller passed OOB index"); return m_OverloadTypeName[TypeSlot]; } llvm::StringRef OP::GetTypeName(Type *Ty, std::string &str) { unsigned TypeSlot = OP::GetTypeSlot(Ty); if (TypeSlot < kUserDefineTypeSlot) { return GetOverloadTypeName(TypeSlot); } else if (TypeSlot == kUserDefineTypeSlot) { if (Ty->isPointerTy()) Ty = Ty->getPointerElementType(); StructType *ST = cast<StructType>(Ty); return ST->getStructName(); } else if (TypeSlot == kObjectTypeSlot) { StructType *ST = cast<StructType>(Ty); return ST->getStructName(); } else { raw_string_ostream os(str); Ty->print(os); os.flush(); return str; } } const char *OP::GetOpCodeName(OpCode opCode) { DXASSERT(0 <= (unsigned)opCode && opCode < OpCode::NumOpCodes, "otherwise caller passed OOB index"); return m_OpCodeProps[(unsigned)opCode].pOpCodeName; } const char *OP::GetAtomicOpName(DXIL::AtomicBinOpCode OpCode) { unsigned opcode = static_cast<unsigned>(OpCode); DXASSERT_LOCALVAR(opcode, opcode < static_cast<unsigned>(DXIL::AtomicBinOpCode::Invalid), "otherwise caller passed OOB index"); return AtomicBinOpCodeName[static_cast<unsigned>(OpCode)]; } OP::OpCodeClass OP::GetOpCodeClass(OpCode opCode) { DXASSERT(0 <= (unsigned)opCode && opCode < OpCode::NumOpCodes, "otherwise caller passed OOB index"); return m_OpCodeProps[(unsigned)opCode].opCodeClass; } const char *OP::GetOpCodeClassName(OpCode opCode) { DXASSERT(0 <= (unsigned)opCode && opCode < OpCode::NumOpCodes, "otherwise caller passed OOB index"); return m_OpCodeProps[(unsigned)opCode].pOpCodeClassName; } llvm::Attribute::AttrKind OP::GetMemAccessAttr(OpCode opCode) { DXASSERT(0 <= (unsigned)opCode && opCode < OpCode::NumOpCodes, "otherwise caller passed OOB index"); return m_OpCodeProps[(unsigned)opCode].FuncAttr; } bool OP::IsOverloadLegal(OpCode opCode, Type *pType) { DXASSERT(0 <= (unsigned)opCode && opCode < OpCode::NumOpCodes, "otherwise caller passed OOB index"); unsigned TypeSlot = GetTypeSlot(pType); return TypeSlot != UINT_MAX && m_OpCodeProps[(unsigned)opCode].bAllowOverload[TypeSlot]; } bool OP::CheckOpCodeTable() { for (unsigned i = 0; i < (unsigned)OpCode::NumOpCodes; i++) { if ((unsigned)m_OpCodeProps[i].opCode != i) return false; } return true; } bool OP::IsDxilOpFuncName(StringRef name) { return name.startswith(OP::m_NamePrefix); } bool OP::IsDxilOpFunc(const llvm::Function *F) { // Test for null to allow IsDxilOpFunc(Call.getCalledFunc()) to be resilient to indirect calls if (F == nullptr || !F->hasName()) return false; return IsDxilOpFuncName(F->getName()); } bool OP::IsDxilOpTypeName(StringRef name) { return name.startswith(m_TypePrefix) || name.startswith(m_MatrixTypePrefix); } bool OP::IsDxilOpType(llvm::StructType *ST) { if (!ST->hasName()) return false; StringRef Name = ST->getName(); return IsDxilOpTypeName(Name); } bool OP::IsDupDxilOpType(llvm::StructType *ST) { if (!ST->hasName()) return false; StringRef Name = ST->getName(); if (!IsDxilOpTypeName(Name)) return false; size_t DotPos = Name.rfind('.'); if (DotPos == 0 || DotPos == StringRef::npos || Name.back() == '.' || !isdigit(static_cast<unsigned char>(Name[DotPos + 1]))) return false; return true; } StructType *OP::GetOriginalDxilOpType(llvm::StructType *ST, llvm::Module &M) { DXASSERT(IsDupDxilOpType(ST), "else should not call GetOriginalDxilOpType"); StringRef Name = ST->getName(); size_t DotPos = Name.rfind('.'); StructType *OriginalST = M.getTypeByName(Name.substr(0, DotPos)); DXASSERT(OriginalST, "else name collison without original type"); DXASSERT(ST->isLayoutIdentical(OriginalST), "else invalid layout for dxil types"); return OriginalST; } bool OP::IsDxilOpFuncCallInst(const llvm::Instruction *I) { const CallInst *CI = dyn_cast<CallInst>(I); if (CI == nullptr) return false; return IsDxilOpFunc(CI->getCalledFunction()); } bool OP::IsDxilOpFuncCallInst(const llvm::Instruction *I, OpCode opcode) { if (!IsDxilOpFuncCallInst(I)) return false; return llvm::cast<llvm::ConstantInt>(I->getOperand(0))->getZExtValue() == (unsigned)opcode; } OP::OpCode OP::GetDxilOpFuncCallInst(const llvm::Instruction *I) { DXASSERT(IsDxilOpFuncCallInst(I), "else caller didn't call IsDxilOpFuncCallInst to check"); return (OP::OpCode)llvm::cast<llvm::ConstantInt>(I->getOperand(0))->getZExtValue(); } bool OP::IsDxilOpWave(OpCode C) { unsigned op = (unsigned)C; /* <py::lines('OPCODE-WAVE')>hctdb_instrhelp.get_instrs_pred("op", "is_wave")</py>*/ // OPCODE-WAVE:BEGIN // Instructions: WaveIsFirstLane=110, WaveGetLaneIndex=111, // WaveGetLaneCount=112, WaveAnyTrue=113, WaveAllTrue=114, // WaveActiveAllEqual=115, WaveActiveBallot=116, WaveReadLaneAt=117, // WaveReadLaneFirst=118, WaveActiveOp=119, WaveActiveBit=120, // WavePrefixOp=121, QuadReadLaneAt=122, QuadOp=123, WaveAllBitCount=135, // WavePrefixBitCount=136, WaveMatch=165, WaveMultiPrefixOp=166, // WaveMultiPrefixBitCount=167 return (110 <= op && op <= 123) || (135 <= op && op <= 136) || (165 <= op && op <= 167); // OPCODE-WAVE:END } bool OP::IsDxilOpGradient(OpCode C) { unsigned op = (unsigned)C; /* <py::lines('OPCODE-GRADIENT')>hctdb_instrhelp.get_instrs_pred("op", "is_gradient")</py>*/ // OPCODE-GRADIENT:BEGIN // Instructions: Sample=60, SampleBias=61, SampleCmp=64, TextureGather=73, // TextureGatherCmp=74, CalculateLOD=81, DerivCoarseX=83, DerivCoarseY=84, // DerivFineX=85, DerivFineY=86 return (60 <= op && op <= 61) || op == 64 || (73 <= op && op <= 74) || op == 81 || (83 <= op && op <= 86); // OPCODE-GRADIENT:END } bool OP::IsDxilOpFeedback(OpCode C) { unsigned op = (unsigned)C; /* <py::lines('OPCODE-FEEDBACK')>hctdb_instrhelp.get_instrs_pred("op", "is_feedback")</py>*/ // OPCODE-FEEDBACK:BEGIN // Instructions: WriteSamplerFeedback=174, WriteSamplerFeedbackBias=175, // WriteSamplerFeedbackLevel=176, WriteSamplerFeedbackGrad=177 return (174 <= op && op <= 177); // OPCODE-FEEDBACK:END } #define SFLAG(stage) ((unsigned)1 << (unsigned)DXIL::ShaderKind::stage) void OP::GetMinShaderModelAndMask(OpCode C, bool bWithTranslation, unsigned &major, unsigned &minor, unsigned &mask) { unsigned op = (unsigned)C; // Default is 6.0, all stages major = 6; minor = 0; mask = ((unsigned)1 << (unsigned)DXIL::ShaderKind::Invalid) - 1; /* <py::lines('OPCODE-SMMASK')>hctdb_instrhelp.get_min_sm_and_mask_text()</py>*/ // OPCODE-SMMASK:BEGIN // Instructions: ThreadId=93, GroupId=94, ThreadIdInGroup=95, // FlattenedThreadIdInGroup=96 if ((93 <= op && op <= 96)) { mask = SFLAG(Compute) | SFLAG(Mesh) | SFLAG(Amplification); return; } // Instructions: DomainLocation=105 if (op == 105) { mask = SFLAG(Domain); return; } // Instructions: LoadOutputControlPoint=103, LoadPatchConstant=104 if ((103 <= op && op <= 104)) { mask = SFLAG(Domain) | SFLAG(Hull); return; } // Instructions: EmitStream=97, CutStream=98, EmitThenCutStream=99, // GSInstanceID=100 if ((97 <= op && op <= 100)) { mask = SFLAG(Geometry); return; } // Instructions: PrimitiveID=108 if (op == 108) { mask = SFLAG(Geometry) | SFLAG(Domain) | SFLAG(Hull); return; } // Instructions: StorePatchConstant=106, OutputControlPointID=107 if ((106 <= op && op <= 107)) { mask = SFLAG(Hull); return; } // Instructions: QuadReadLaneAt=122, QuadOp=123 if ((122 <= op && op <= 123)) { mask = SFLAG(Library) | SFLAG(Compute) | SFLAG(Amplification) | SFLAG(Mesh) | SFLAG(Pixel); return; } // Instructions: WaveIsFirstLane=110, WaveGetLaneIndex=111, // WaveGetLaneCount=112, WaveAnyTrue=113, WaveAllTrue=114, // WaveActiveAllEqual=115, WaveActiveBallot=116, WaveReadLaneAt=117, // WaveReadLaneFirst=118, WaveActiveOp=119, WaveActiveBit=120, // WavePrefixOp=121, WaveAllBitCount=135, WavePrefixBitCount=136 if ((110 <= op && op <= 121) || (135 <= op && op <= 136)) { mask = SFLAG(Library) | SFLAG(Compute) | SFLAG(Amplification) | SFLAG(Mesh) | SFLAG(Pixel) | SFLAG(Vertex) | SFLAG(Hull) | SFLAG(Domain) | SFLAG(Geometry) | SFLAG(RayGeneration) | SFLAG(Intersection) | SFLAG(AnyHit) | SFLAG(ClosestHit) | SFLAG(Miss) | SFLAG(Callable); return; } // Instructions: Sample=60, SampleBias=61, SampleCmp=64, CalculateLOD=81, // DerivCoarseX=83, DerivCoarseY=84, DerivFineX=85, DerivFineY=86 if ((60 <= op && op <= 61) || op == 64 || op == 81 || (83 <= op && op <= 86)) { mask = SFLAG(Library) | SFLAG(Pixel); return; } // Instructions: RenderTargetGetSamplePosition=76, // RenderTargetGetSampleCount=77, Discard=82, EvalSnapped=87, // EvalSampleIndex=88, EvalCentroid=89, SampleIndex=90, Coverage=91, // InnerCoverage=92 if ((76 <= op && op <= 77) || op == 82 || (87 <= op && op <= 92)) { mask = SFLAG(Pixel); return; } // Instructions: AttributeAtVertex=137 if (op == 137) { major = 6; minor = 1; mask = SFLAG(Pixel); return; } // Instructions: ViewID=138 if (op == 138) { major = 6; minor = 1; mask = SFLAG(Vertex) | SFLAG(Hull) | SFLAG(Domain) | SFLAG(Geometry) | SFLAG(Pixel) | SFLAG(Mesh); return; } // Instructions: RawBufferLoad=139, RawBufferStore=140 if ((139 <= op && op <= 140)) { if (bWithTranslation) { major = 6; minor = 0; } else { major = 6; minor = 2; } return; } // Instructions: IgnoreHit=155, AcceptHitAndEndSearch=156 if ((155 <= op && op <= 156)) { major = 6; minor = 3; mask = SFLAG(AnyHit); return; } // Instructions: CallShader=159 if (op == 159) { major = 6; minor = 3; mask = SFLAG(Library) | SFLAG(ClosestHit) | SFLAG(RayGeneration) | SFLAG(Miss) | SFLAG(Callable); return; } // Instructions: ReportHit=158 if (op == 158) { major = 6; minor = 3; mask = SFLAG(Library) | SFLAG(Intersection); return; } // Instructions: InstanceID=141, InstanceIndex=142, HitKind=143, // ObjectRayOrigin=149, ObjectRayDirection=150, ObjectToWorld=151, // WorldToObject=152, PrimitiveIndex=161 if ((141 <= op && op <= 143) || (149 <= op && op <= 152) || op == 161) { major = 6; minor = 3; mask = SFLAG(Library) | SFLAG(Intersection) | SFLAG(AnyHit) | SFLAG(ClosestHit); return; } // Instructions: RayFlags=144, WorldRayOrigin=147, WorldRayDirection=148, // RayTMin=153, RayTCurrent=154 if (op == 144 || (147 <= op && op <= 148) || (153 <= op && op <= 154)) { major = 6; minor = 3; mask = SFLAG(Library) | SFLAG(Intersection) | SFLAG(AnyHit) | SFLAG(ClosestHit) | SFLAG(Miss); return; } // Instructions: TraceRay=157 if (op == 157) { major = 6; minor = 3; mask = SFLAG(Library) | SFLAG(RayGeneration) | SFLAG(ClosestHit) | SFLAG(Miss); return; } // Instructions: DispatchRaysIndex=145, DispatchRaysDimensions=146 if ((145 <= op && op <= 146)) { major = 6; minor = 3; mask = SFLAG(Library) | SFLAG(RayGeneration) | SFLAG(Intersection) | SFLAG(AnyHit) | SFLAG(ClosestHit) | SFLAG(Miss) | SFLAG(Callable); return; } // Instructions: CreateHandleForLib=160 if (op == 160) { if (bWithTranslation) { major = 6; minor = 0; } else { major = 6; minor = 3; } return; } // Instructions: Dot2AddHalf=162, Dot4AddI8Packed=163, Dot4AddU8Packed=164 if ((162 <= op && op <= 164)) { major = 6; minor = 4; return; } // Instructions: WriteSamplerFeedbackLevel=176, WriteSamplerFeedbackGrad=177, // AllocateRayQuery=178, RayQuery_TraceRayInline=179, RayQuery_Proceed=180, // RayQuery_Abort=181, RayQuery_CommitNonOpaqueTriangleHit=182, // RayQuery_CommitProceduralPrimitiveHit=183, RayQuery_CommittedStatus=184, // RayQuery_CandidateType=185, RayQuery_CandidateObjectToWorld3x4=186, // RayQuery_CandidateWorldToObject3x4=187, // RayQuery_CommittedObjectToWorld3x4=188, // RayQuery_CommittedWorldToObject3x4=189, // RayQuery_CandidateProceduralPrimitiveNonOpaque=190, // RayQuery_CandidateTriangleFrontFace=191, // RayQuery_CommittedTriangleFrontFace=192, // RayQuery_CandidateTriangleBarycentrics=193, // RayQuery_CommittedTriangleBarycentrics=194, RayQuery_RayFlags=195, // RayQuery_WorldRayOrigin=196, RayQuery_WorldRayDirection=197, // RayQuery_RayTMin=198, RayQuery_CandidateTriangleRayT=199, // RayQuery_CommittedRayT=200, RayQuery_CandidateInstanceIndex=201, // RayQuery_CandidateInstanceID=202, RayQuery_CandidateGeometryIndex=203, // RayQuery_CandidatePrimitiveIndex=204, RayQuery_CandidateObjectRayOrigin=205, // RayQuery_CandidateObjectRayDirection=206, // RayQuery_CommittedInstanceIndex=207, RayQuery_CommittedInstanceID=208, // RayQuery_CommittedGeometryIndex=209, RayQuery_CommittedPrimitiveIndex=210, // RayQuery_CommittedObjectRayOrigin=211, // RayQuery_CommittedObjectRayDirection=212, // RayQuery_CandidateInstanceContributionToHitGroupIndex=214, // RayQuery_CommittedInstanceContributionToHitGroupIndex=215 if ((176 <= op && op <= 212) || (214 <= op && op <= 215)) { major = 6; minor = 5; return; } // Instructions: DispatchMesh=173 if (op == 173) { major = 6; minor = 5; mask = SFLAG(Amplification); return; } // Instructions: WaveMatch=165, WaveMultiPrefixOp=166, // WaveMultiPrefixBitCount=167 if ((165 <= op && op <= 167)) { major = 6; minor = 5; mask = SFLAG(Library) | SFLAG(Compute) | SFLAG(Amplification) | SFLAG(Mesh) | SFLAG(Pixel) | SFLAG(Vertex) | SFLAG(Hull) | SFLAG(Domain) | SFLAG(Geometry) | SFLAG(RayGeneration) | SFLAG(Intersection) | SFLAG(AnyHit) | SFLAG(ClosestHit) | SFLAG(Miss) | SFLAG(Callable); return; } // Instructions: GeometryIndex=213 if (op == 213) { major = 6; minor = 5; mask = SFLAG(Library) | SFLAG(Intersection) | SFLAG(AnyHit) | SFLAG(ClosestHit); return; } // Instructions: WriteSamplerFeedback=174, WriteSamplerFeedbackBias=175 if ((174 <= op && op <= 175)) { major = 6; minor = 5; mask = SFLAG(Library) | SFLAG(Pixel); return; } // Instructions: SetMeshOutputCounts=168, EmitIndices=169, GetMeshPayload=170, // StoreVertexOutput=171, StorePrimitiveOutput=172 if ((168 <= op && op <= 172)) { major = 6; minor = 5; mask = SFLAG(Mesh); return; } // Instructions: CreateHandleFromHeap=216, AnnotateHandle=217 if ((216 <= op && op <= 217)) { major = 6; minor = 6; return; } // OPCODE-SMMASK:END } void OP::GetMinShaderModelAndMask(const llvm::CallInst *CI, bool bWithTranslation, unsigned valMajor, unsigned valMinor, unsigned &major, unsigned &minor, unsigned &mask) { OpCode opcode = OP::GetDxilOpFuncCallInst(CI); GetMinShaderModelAndMask(opcode, bWithTranslation, major, minor, mask); if (DXIL::CompareVersions(valMajor, valMinor, 1, 5) < 0) { // validator 1.4 didn't exclude wave ops in mask if (IsDxilOpWave(opcode)) mask = ((unsigned)1 << (unsigned)DXIL::ShaderKind::Invalid) - 1; // validator 1.4 didn't have any additional rules applied: return; } // Additional rules are applied manually here. // Barrier with mode != UAVFenceGlobal requires compute, amplification, or mesh // Instructions: Barrier=80 if (opcode == DXIL::OpCode::Barrier) { DxilInst_Barrier barrier(const_cast<CallInst*>(CI)); unsigned mode = barrier.get_barrierMode_val(); if (mode != (unsigned)DXIL::BarrierMode::UAVFenceGlobal) { mask = SFLAG(Library) | SFLAG(Compute) | SFLAG(Amplification) | SFLAG(Mesh); } return; } } #undef SFLAG static Type *GetOrCreateStructType(LLVMContext &Ctx, ArrayRef<Type*> types, StringRef Name, Module *pModule) { if (StructType *ST = pModule->getTypeByName(Name)) { // TODO: validate the exist type match types if needed. return ST; } else return StructType::create(Ctx, types, Name); } //------------------------------------------------------------------------------ // // OP methods. // OP::OP(LLVMContext &Ctx, Module *pModule) : m_Ctx(Ctx) , m_pModule(pModule) , m_LowPrecisionMode(DXIL::LowPrecisionMode::Undefined) { memset(m_pResRetType, 0, sizeof(m_pResRetType)); memset(m_pCBufferRetType, 0, sizeof(m_pCBufferRetType)); memset(m_OpCodeClassCache, 0, sizeof(m_OpCodeClassCache)); static_assert(_countof(OP::m_OpCodeProps) == (size_t)OP::OpCode::NumOpCodes, "forgot to update OP::m_OpCodeProps"); m_pHandleType = GetOrCreateStructType(m_Ctx, Type::getInt8PtrTy(m_Ctx), "dx.types.Handle", pModule); m_pResourcePropertiesType = GetOrCreateStructType( m_Ctx, {Type::getInt32Ty(m_Ctx), Type::getInt32Ty(m_Ctx)}, "dx.types.ResourceProperties", pModule); Type *DimsType[4] = { Type::getInt32Ty(m_Ctx), Type::getInt32Ty(m_Ctx), Type::getInt32Ty(m_Ctx), Type::getInt32Ty(m_Ctx) }; m_pDimensionsType = GetOrCreateStructType(m_Ctx, DimsType, "dx.types.Dimensions", pModule); Type *SamplePosType[2] = { Type::getFloatTy(m_Ctx), Type::getFloatTy(m_Ctx) }; m_pSamplePosType = GetOrCreateStructType(m_Ctx, SamplePosType, "dx.types.SamplePos", pModule); Type *I32cTypes[2] = { Type::getInt32Ty(m_Ctx), Type::getInt1Ty(m_Ctx) }; m_pBinaryWithCarryType = GetOrCreateStructType(m_Ctx, I32cTypes, "dx.types.i32c", pModule); Type *TwoI32Types[2] = { Type::getInt32Ty(m_Ctx), Type::getInt32Ty(m_Ctx) }; m_pBinaryWithTwoOutputsType = GetOrCreateStructType(m_Ctx, TwoI32Types, "dx.types.twoi32", pModule); Type *SplitDoubleTypes[2] = { Type::getInt32Ty(m_Ctx), Type::getInt32Ty(m_Ctx) }; // Lo, Hi. m_pSplitDoubleType = GetOrCreateStructType(m_Ctx, SplitDoubleTypes, "dx.types.splitdouble", pModule); Type *Int4Types[4] = { Type::getInt32Ty(m_Ctx), Type::getInt32Ty(m_Ctx), Type::getInt32Ty(m_Ctx), Type::getInt32Ty(m_Ctx) }; // HiHi, HiLo, LoHi, LoLo m_pInt4Type = GetOrCreateStructType(m_Ctx, Int4Types, "dx.types.fouri32", pModule); // Try to find existing intrinsic function. RefreshCache(); } void OP::RefreshCache() { for (Function &F : m_pModule->functions()) { if (OP::IsDxilOpFunc(&F) && !F.user_empty()) { CallInst *CI = cast<CallInst>(*F.user_begin()); OpCode OpCode = OP::GetDxilOpFuncCallInst(CI); Type *pOverloadType = OP::GetOverloadType(OpCode, &F); Function *OpFunc = GetOpFunc(OpCode, pOverloadType); (void)(OpFunc); DXASSERT_NOMSG(OpFunc == &F); } } } void OP::UpdateCache(OpCodeClass opClass, Type * Ty, llvm::Function *F) { m_OpCodeClassCache[(unsigned)opClass].pOverloads[Ty] = F; m_FunctionToOpClass[F] = opClass; } Function *OP::GetOpFunc(OpCode opCode, Type *pOverloadType) { DXASSERT(0 <= (unsigned)opCode && opCode < OpCode::NumOpCodes, "otherwise caller passed OOB OpCode"); _Analysis_assume_(0 <= (unsigned)opCode && opCode < OpCode::NumOpCodes); DXASSERT(IsOverloadLegal(opCode, pOverloadType), "otherwise the caller requested illegal operation overload (eg HLSL function with unsupported types for mapped intrinsic function)"); OpCodeClass opClass = m_OpCodeProps[(unsigned)opCode].opCodeClass; Function *&F = m_OpCodeClassCache[(unsigned)opClass].pOverloads[pOverloadType]; if (F != nullptr) { UpdateCache(opClass, pOverloadType, F); return F; } vector<Type*> ArgTypes; // RetType is ArgTypes[0] Type *pETy = pOverloadType; Type *pRes = GetHandleType(); Type *pDim = GetDimensionsType(); Type *pPos = GetSamplePosType(); Type *pV = Type::getVoidTy(m_Ctx); Type *pI1 = Type::getInt1Ty(m_Ctx); Type *pI8 = Type::getInt8Ty(m_Ctx); Type *pI16 = Type::getInt16Ty(m_Ctx); Type *pI32 = Type::getInt32Ty(m_Ctx); Type *pPI32 = Type::getInt32PtrTy(m_Ctx); (void)(pPI32); // Currently unused. Type *pI64 = Type::getInt64Ty(m_Ctx); (void)(pI64); // Currently unused. Type *pF16 = Type::getHalfTy(m_Ctx); Type *pF32 = Type::getFloatTy(m_Ctx); Type *pPF32 = Type::getFloatPtrTy(m_Ctx); Type *pI32C = GetBinaryWithCarryType(); Type *p2I32 = GetBinaryWithTwoOutputsType(); Type *pF64 = Type::getDoubleTy(m_Ctx); Type *pSDT = GetSplitDoubleType(); // Split double type. Type *pI4S = GetInt4Type(); // 4 i32s in a struct. Type *udt = pOverloadType; Type *obj = pOverloadType; Type *resProperty = GetResourcePropertiesType(); std::string funcName = (Twine(OP::m_NamePrefix) + Twine(GetOpCodeClassName(opCode))).str(); // Add ret type to the name. if (pOverloadType != pV) { std::string typeName; funcName = Twine(funcName).concat(".").concat(GetTypeName(pOverloadType, typeName)).str(); } // Try to find exist function with the same name in the module. if (Function *existF = m_pModule->getFunction(funcName)) { F = existF; UpdateCache(opClass, pOverloadType, F); return F; } #define A(_x) ArgTypes.emplace_back(_x) #define RRT(_y) A(GetResRetType(_y)) #define CBRT(_y) A(GetCBufferRetType(_y)) /* <py::lines('OPCODE-OLOAD-FUNCS')>hctdb_instrhelp.get_oloads_funcs()</py>*/ switch (opCode) { // return opCode // OPCODE-OLOAD-FUNCS:BEGIN // Temporary, indexable, input, output registers case OpCode::TempRegLoad: A(pETy); A(pI32); A(pI32); break; case OpCode::TempRegStore: A(pV); A(pI32); A(pI32); A(pETy); break; case OpCode::MinPrecXRegLoad: A(pETy); A(pI32); A(pPF32);A(pI32); A(pI8); break; case OpCode::MinPrecXRegStore: A(pV); A(pI32); A(pPF32);A(pI32); A(pI8); A(pETy); break; case OpCode::LoadInput: A(pETy); A(pI32); A(pI32); A(pI32); A(pI8); A(pI32); break; case OpCode::StoreOutput: A(pV); A(pI32); A(pI32); A(pI32); A(pI8); A(pETy); break; // Unary float case OpCode::FAbs: A(pETy); A(pI32); A(pETy); break; case OpCode::Saturate: A(pETy); A(pI32); A(pETy); break; case OpCode::IsNaN: A(pI1); A(pI32); A(pETy); break; case OpCode::IsInf: A(pI1); A(pI32); A(pETy); break; case OpCode::IsFinite: A(pI1); A(pI32); A(pETy); break; case OpCode::IsNormal: A(pI1); A(pI32); A(pETy); break; case OpCode::Cos: A(pETy); A(pI32); A(pETy); break; case OpCode::Sin: A(pETy); A(pI32); A(pETy); break; case OpCode::Tan: A(pETy); A(pI32); A(pETy); break; case OpCode::Acos: A(pETy); A(pI32); A(pETy); break; case OpCode::Asin: A(pETy); A(pI32); A(pETy); break; case OpCode::Atan: A(pETy); A(pI32); A(pETy); break; case OpCode::Hcos: A(pETy); A(pI32); A(pETy); break; case OpCode::Hsin: A(pETy); A(pI32); A(pETy); break; case OpCode::Htan: A(pETy); A(pI32); A(pETy); break; case OpCode::Exp: A(pETy); A(pI32); A(pETy); break; case OpCode::Frc: A(pETy); A(pI32); A(pETy); break; case OpCode::Log: A(pETy); A(pI32); A(pETy); break; case OpCode::Sqrt: A(pETy); A(pI32); A(pETy); break; case OpCode::Rsqrt: A(pETy); A(pI32); A(pETy); break; // Unary float - rounding case OpCode::Round_ne: A(pETy); A(pI32); A(pETy); break; case OpCode::Round_ni: A(pETy); A(pI32); A(pETy); break; case OpCode::Round_pi: A(pETy); A(pI32); A(pETy); break; case OpCode::Round_z: A(pETy); A(pI32); A(pETy); break; // Unary int case OpCode::Bfrev: A(pETy); A(pI32); A(pETy); break; case OpCode::Countbits: A(pI32); A(pI32); A(pETy); break; case OpCode::FirstbitLo: A(pI32); A(pI32); A(pETy); break; // Unary uint case OpCode::FirstbitHi: A(pI32); A(pI32); A(pETy); break; // Unary int case OpCode::FirstbitSHi: A(pI32); A(pI32); A(pETy); break; // Binary float case OpCode::FMax: A(pETy); A(pI32); A(pETy); A(pETy); break; case OpCode::FMin: A(pETy); A(pI32); A(pETy); A(pETy); break; // Binary int case OpCode::IMax: A(pETy); A(pI32); A(pETy); A(pETy); break; case OpCode::IMin: A(pETy); A(pI32); A(pETy); A(pETy); break; // Binary uint case OpCode::UMax: A(pETy); A(pI32); A(pETy); A(pETy); break; case OpCode::UMin: A(pETy); A(pI32); A(pETy); A(pETy); break; // Binary int with two outputs case OpCode::IMul: A(p2I32); A(pI32); A(pETy); A(pETy); break; // Binary uint with two outputs case OpCode::UMul: A(p2I32); A(pI32); A(pETy); A(pETy); break; case OpCode::UDiv: A(p2I32); A(pI32); A(pETy); A(pETy); break; // Binary uint with carry or borrow case OpCode::UAddc: A(pI32C); A(pI32); A(pETy); A(pETy); break; case OpCode::USubb: A(pI32C); A(pI32); A(pETy); A(pETy); break; // Tertiary float case OpCode::FMad: A(pETy); A(pI32); A(pETy); A(pETy); A(pETy); break; case OpCode::Fma: A(pETy); A(pI32); A(pETy); A(pETy); A(pETy); break; // Tertiary int case OpCode::IMad: A(pETy); A(pI32); A(pETy); A(pETy); A(pETy); break; // Tertiary uint case OpCode::UMad: A(pETy); A(pI32); A(pETy); A(pETy); A(pETy); break; // Tertiary int case OpCode::Msad: A(pETy); A(pI32); A(pETy); A(pETy); A(pETy); break; case OpCode::Ibfe: A(pETy); A(pI32); A(pETy); A(pETy); A(pETy); break; // Tertiary uint case OpCode::Ubfe: A(pETy); A(pI32); A(pETy); A(pETy); A(pETy); break; // Quaternary case OpCode::Bfi: A(pETy); A(pI32); A(pETy); A(pETy); A(pETy); A(pETy); break; // Dot case OpCode::Dot2: A(pETy); A(pI32); A(pETy); A(pETy); A(pETy); A(pETy); break; case OpCode::Dot3: A(pETy); A(pI32); A(pETy); A(pETy); A(pETy); A(pETy); A(pETy); A(pETy); break; case OpCode::Dot4: A(pETy); A(pI32); A(pETy); A(pETy); A(pETy); A(pETy); A(pETy); A(pETy); A(pETy); A(pETy); break; // Resources case OpCode::CreateHandle: A(pRes); A(pI32); A(pI8); A(pI32); A(pI32); A(pI1); break; case OpCode::CBufferLoad: A(pETy); A(pI32); A(pRes); A(pI32); A(pI32); break; case OpCode::CBufferLoadLegacy: CBRT(pETy); A(pI32); A(pRes); A(pI32); break; // Resources - sample case OpCode::Sample: RRT(pETy); A(pI32); A(pRes); A(pRes); A(pF32); A(pF32); A(pF32); A(pF32); A(pI32); A(pI32); A(pI32); A(pF32); break; case OpCode::SampleBias: RRT(pETy); A(pI32); A(pRes); A(pRes); A(pF32); A(pF32); A(pF32); A(pF32); A(pI32); A(pI32); A(pI32); A(pF32); A(pF32); break; case OpCode::SampleLevel: RRT(pETy); A(pI32); A(pRes); A(pRes); A(pF32); A(pF32); A(pF32); A(pF32); A(pI32); A(pI32); A(pI32); A(pF32); break; case OpCode::SampleGrad: RRT(pETy); A(pI32); A(pRes); A(pRes); A(pF32); A(pF32); A(pF32); A(pF32); A(pI32); A(pI32); A(pI32); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); break; case OpCode::SampleCmp: RRT(pETy); A(pI32); A(pRes); A(pRes); A(pF32); A(pF32); A(pF32); A(pF32); A(pI32); A(pI32); A(pI32); A(pF32); A(pF32); break; case OpCode::SampleCmpLevelZero: RRT(pETy); A(pI32); A(pRes); A(pRes); A(pF32); A(pF32); A(pF32); A(pF32); A(pI32); A(pI32); A(pI32); A(pF32); break; // Resources case OpCode::TextureLoad: RRT(pETy); A(pI32); A(pRes); A(pI32); A(pI32); A(pI32); A(pI32); A(pI32); A(pI32); A(pI32); break; case OpCode::TextureStore: A(pV); A(pI32); A(pRes); A(pI32); A(pI32); A(pI32); A(pETy); A(pETy); A(pETy); A(pETy); A(pI8); break; case OpCode::BufferLoad: RRT(pETy); A(pI32); A(pRes); A(pI32); A(pI32); break; case OpCode::BufferStore: A(pV); A(pI32); A(pRes); A(pI32); A(pI32); A(pETy); A(pETy); A(pETy); A(pETy); A(pI8); break; case OpCode::BufferUpdateCounter: A(pI32); A(pI32); A(pRes); A(pI8); break; case OpCode::CheckAccessFullyMapped: A(pI1); A(pI32); A(pI32); break; case OpCode::GetDimensions: A(pDim); A(pI32); A(pRes); A(pI32); break; // Resources - gather case OpCode::TextureGather: RRT(pETy); A(pI32); A(pRes); A(pRes); A(pF32); A(pF32); A(pF32); A(pF32); A(pI32); A(pI32); A(pI32); break; case OpCode::TextureGatherCmp: RRT(pETy); A(pI32); A(pRes); A(pRes); A(pF32); A(pF32); A(pF32); A(pF32); A(pI32); A(pI32); A(pI32); A(pF32); break; // Resources - sample case OpCode::Texture2DMSGetSamplePosition:A(pPos); A(pI32); A(pRes); A(pI32); break; case OpCode::RenderTargetGetSamplePosition:A(pPos); A(pI32); A(pI32); break; case OpCode::RenderTargetGetSampleCount:A(pI32); A(pI32); break; // Synchronization case OpCode::AtomicBinOp: A(pI32); A(pI32); A(pRes); A(pI32); A(pI32); A(pI32); A(pI32); A(pI32); break; case OpCode::AtomicCompareExchange: A(pI32); A(pI32); A(pRes); A(pI32); A(pI32); A(pI32); A(pI32); A(pI32); break; case OpCode::Barrier: A(pV); A(pI32); A(pI32); break; // Pixel shader case OpCode::CalculateLOD: A(pF32); A(pI32); A(pRes); A(pRes); A(pF32); A(pF32); A(pF32); A(pI1); break; case OpCode::Discard: A(pV); A(pI32); A(pI1); break; case OpCode::DerivCoarseX: A(pETy); A(pI32); A(pETy); break; case OpCode::DerivCoarseY: A(pETy); A(pI32); A(pETy); break; case OpCode::DerivFineX: A(pETy); A(pI32); A(pETy); break; case OpCode::DerivFineY: A(pETy); A(pI32); A(pETy); break; case OpCode::EvalSnapped: A(pETy); A(pI32); A(pI32); A(pI32); A(pI8); A(pI32); A(pI32); break; case OpCode::EvalSampleIndex: A(pETy); A(pI32); A(pI32); A(pI32); A(pI8); A(pI32); break; case OpCode::EvalCentroid: A(pETy); A(pI32); A(pI32); A(pI32); A(pI8); break; case OpCode::SampleIndex: A(pI32); A(pI32); break; case OpCode::Coverage: A(pI32); A(pI32); break; case OpCode::InnerCoverage: A(pI32); A(pI32); break; // Compute/Mesh/Amplification shader case OpCode::ThreadId: A(pI32); A(pI32); A(pI32); break; case OpCode::GroupId: A(pI32); A(pI32); A(pI32); break; case OpCode::ThreadIdInGroup: A(pI32); A(pI32); A(pI32); break; case OpCode::FlattenedThreadIdInGroup:A(pI32); A(pI32); break; // Geometry shader case OpCode::EmitStream: A(pV); A(pI32); A(pI8); break; case OpCode::CutStream: A(pV); A(pI32); A(pI8); break; case OpCode::EmitThenCutStream: A(pV); A(pI32); A(pI8); break; case OpCode::GSInstanceID: A(pI32); A(pI32); break; // Double precision case OpCode::MakeDouble: A(pF64); A(pI32); A(pI32); A(pI32); break; case OpCode::SplitDouble: A(pSDT); A(pI32); A(pF64); break; // Domain and hull shader case OpCode::LoadOutputControlPoint: A(pETy); A(pI32); A(pI32); A(pI32); A(pI8); A(pI32); break; case OpCode::LoadPatchConstant: A(pETy); A(pI32); A(pI32); A(pI32); A(pI8); break; // Domain shader case OpCode::DomainLocation: A(pF32); A(pI32); A(pI8); break; // Hull shader case OpCode::StorePatchConstant: A(pV); A(pI32); A(pI32); A(pI32); A(pI8); A(pETy); break; case OpCode::OutputControlPointID: A(pI32); A(pI32); break; // Hull, Domain and Geometry shaders case OpCode::PrimitiveID: A(pI32); A(pI32); break; // Other case OpCode::CycleCounterLegacy: A(p2I32); A(pI32); break; // Wave case OpCode::WaveIsFirstLane: A(pI1); A(pI32); break; case OpCode::WaveGetLaneIndex: A(pI32); A(pI32); break; case OpCode::WaveGetLaneCount: A(pI32); A(pI32); break; case OpCode::WaveAnyTrue: A(pI1); A(pI32); A(pI1); break; case OpCode::WaveAllTrue: A(pI1); A(pI32); A(pI1); break; case OpCode::WaveActiveAllEqual: A(pI1); A(pI32); A(pETy); break; case OpCode::WaveActiveBallot: A(pI4S); A(pI32); A(pI1); break; case OpCode::WaveReadLaneAt: A(pETy); A(pI32); A(pETy); A(pI32); break; case OpCode::WaveReadLaneFirst: A(pETy); A(pI32); A(pETy); break; case OpCode::WaveActiveOp: A(pETy); A(pI32); A(pETy); A(pI8); A(pI8); break; case OpCode::WaveActiveBit: A(pETy); A(pI32); A(pETy); A(pI8); break; case OpCode::WavePrefixOp: A(pETy); A(pI32); A(pETy); A(pI8); A(pI8); break; // Quad Wave Ops case OpCode::QuadReadLaneAt: A(pETy); A(pI32); A(pETy); A(pI32); break; case OpCode::QuadOp: A(pETy); A(pI32); A(pETy); A(pI8); break; // Bitcasts with different sizes case OpCode::BitcastI16toF16: A(pF16); A(pI32); A(pI16); break; case OpCode::BitcastF16toI16: A(pI16); A(pI32); A(pF16); break; case OpCode::BitcastI32toF32: A(pF32); A(pI32); A(pI32); break; case OpCode::BitcastF32toI32: A(pI32); A(pI32); A(pF32); break; case OpCode::BitcastI64toF64: A(pF64); A(pI32); A(pI64); break; case OpCode::BitcastF64toI64: A(pI64); A(pI32); A(pF64); break; // Legacy floating-point case OpCode::LegacyF32ToF16: A(pI32); A(pI32); A(pF32); break; case OpCode::LegacyF16ToF32: A(pF32); A(pI32); A(pI32); break; // Double precision case OpCode::LegacyDoubleToFloat: A(pF32); A(pI32); A(pF64); break; case OpCode::LegacyDoubleToSInt32: A(pI32); A(pI32); A(pF64); break; case OpCode::LegacyDoubleToUInt32: A(pI32); A(pI32); A(pF64); break; // Wave case OpCode::WaveAllBitCount: A(pI32); A(pI32); A(pI1); break; case OpCode::WavePrefixBitCount: A(pI32); A(pI32); A(pI1); break; // Pixel shader case OpCode::AttributeAtVertex: A(pETy); A(pI32); A(pI32); A(pI32); A(pI8); A(pI8); break; // Graphics shader case OpCode::ViewID: A(pI32); A(pI32); break; // Resources case OpCode::RawBufferLoad: RRT(pETy); A(pI32); A(pRes); A(pI32); A(pI32); A(pI8); A(pI32); break; case OpCode::RawBufferStore: A(pV); A(pI32); A(pRes); A(pI32); A(pI32); A(pETy); A(pETy); A(pETy); A(pETy); A(pI8); A(pI32); break; // Raytracing object space uint System Values case OpCode::InstanceID: A(pI32); A(pI32); break; case OpCode::InstanceIndex: A(pI32); A(pI32); break; // Raytracing hit uint System Values case OpCode::HitKind: A(pI32); A(pI32); break; // Raytracing uint System Values case OpCode::RayFlags: A(pI32); A(pI32); break; // Ray Dispatch Arguments case OpCode::DispatchRaysIndex: A(pI32); A(pI32); A(pI8); break; case OpCode::DispatchRaysDimensions: A(pI32); A(pI32); A(pI8); break; // Ray Vectors case OpCode::WorldRayOrigin: A(pF32); A(pI32); A(pI8); break; case OpCode::WorldRayDirection: A(pF32); A(pI32); A(pI8); break; // Ray object space Vectors case OpCode::ObjectRayOrigin: A(pF32); A(pI32); A(pI8); break; case OpCode::ObjectRayDirection: A(pF32); A(pI32); A(pI8); break; // Ray Transforms case OpCode::ObjectToWorld: A(pF32); A(pI32); A(pI32); A(pI8); break; case OpCode::WorldToObject: A(pF32); A(pI32); A(pI32); A(pI8); break; // RayT case OpCode::RayTMin: A(pF32); A(pI32); break; case OpCode::RayTCurrent: A(pF32); A(pI32); break; // AnyHit Terminals case OpCode::IgnoreHit: A(pV); A(pI32); break; case OpCode::AcceptHitAndEndSearch: A(pV); A(pI32); break; // Indirect Shader Invocation case OpCode::TraceRay: A(pV); A(pI32); A(pRes); A(pI32); A(pI32); A(pI32); A(pI32); A(pI32); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); A(udt); break; case OpCode::ReportHit: A(pI1); A(pI32); A(pF32); A(pI32); A(udt); break; case OpCode::CallShader: A(pV); A(pI32); A(pI32); A(udt); break; // Library create handle from resource struct (like HL intrinsic) case OpCode::CreateHandleForLib: A(pRes); A(pI32); A(obj); break; // Raytracing object space uint System Values case OpCode::PrimitiveIndex: A(pI32); A(pI32); break; // Dot product with accumulate case OpCode::Dot2AddHalf: A(pETy); A(pI32); A(pETy); A(pF16); A(pF16); A(pF16); A(pF16); break; case OpCode::Dot4AddI8Packed: A(pI32); A(pI32); A(pI32); A(pI32); A(pI32); break; case OpCode::Dot4AddU8Packed: A(pI32); A(pI32); A(pI32); A(pI32); A(pI32); break; // Wave case OpCode::WaveMatch: A(pI4S); A(pI32); A(pETy); break; case OpCode::WaveMultiPrefixOp: A(pETy); A(pI32); A(pETy); A(pI32); A(pI32); A(pI32); A(pI32); A(pI8); A(pI8); break; case OpCode::WaveMultiPrefixBitCount:A(pI32); A(pI32); A(pI1); A(pI32); A(pI32); A(pI32); A(pI32); break; // Mesh shader instructions case OpCode::SetMeshOutputCounts: A(pV); A(pI32); A(pI32); A(pI32); break; case OpCode::EmitIndices: A(pV); A(pI32); A(pI32); A(pI32); A(pI32); A(pI32); break; case OpCode::GetMeshPayload: A(pETy); A(pI32); break; case OpCode::StoreVertexOutput: A(pV); A(pI32); A(pI32); A(pI32); A(pI8); A(pETy); A(pI32); break; case OpCode::StorePrimitiveOutput: A(pV); A(pI32); A(pI32); A(pI32); A(pI8); A(pETy); A(pI32); break; // Amplification shader instructions case OpCode::DispatchMesh: A(pV); A(pI32); A(pI32); A(pI32); A(pI32); A(pETy); break; // Sampler Feedback case OpCode::WriteSamplerFeedback: A(pV); A(pI32); A(pRes); A(pRes); A(pRes); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); break; case OpCode::WriteSamplerFeedbackBias:A(pV); A(pI32); A(pRes); A(pRes); A(pRes); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); break; case OpCode::WriteSamplerFeedbackLevel:A(pV); A(pI32); A(pRes); A(pRes); A(pRes); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); break; case OpCode::WriteSamplerFeedbackGrad:A(pV); A(pI32); A(pRes); A(pRes); A(pRes); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); break; // Inline Ray Query case OpCode::AllocateRayQuery: A(pI32); A(pI32); A(pI32); break; case OpCode::RayQuery_TraceRayInline:A(pV); A(pI32); A(pI32); A(pRes); A(pI32); A(pI32); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); A(pF32); break; case OpCode::RayQuery_Proceed: A(pI1); A(pI32); A(pI32); break; case OpCode::RayQuery_Abort: A(pV); A(pI32); A(pI32); break; case OpCode::RayQuery_CommitNonOpaqueTriangleHit:A(pV); A(pI32); A(pI32); break; case OpCode::RayQuery_CommitProceduralPrimitiveHit:A(pV); A(pI32); A(pI32); A(pF32); break; case OpCode::RayQuery_CommittedStatus:A(pI32); A(pI32); A(pI32); break; case OpCode::RayQuery_CandidateType: A(pI32); A(pI32); A(pI32); break; case OpCode::RayQuery_CandidateObjectToWorld3x4:A(pF32); A(pI32); A(pI32); A(pI32); A(pI8); break; case OpCode::RayQuery_CandidateWorldToObject3x4:A(pF32); A(pI32); A(pI32); A(pI32); A(pI8); break; case OpCode::RayQuery_CommittedObjectToWorld3x4:A(pF32); A(pI32); A(pI32); A(pI32); A(pI8); break; case OpCode::RayQuery_CommittedWorldToObject3x4:A(pF32); A(pI32); A(pI32); A(pI32); A(pI8); break; case OpCode::RayQuery_CandidateProceduralPrimitiveNonOpaque:A(pI1); A(pI32); A(pI32); break; case OpCode::RayQuery_CandidateTriangleFrontFace:A(pI1); A(pI32); A(pI32); break; case OpCode::RayQuery_CommittedTriangleFrontFace:A(pI1); A(pI32); A(pI32); break; case OpCode::RayQuery_CandidateTriangleBarycentrics:A(pF32); A(pI32); A(pI32); A(pI8); break; case OpCode::RayQuery_CommittedTriangleBarycentrics:A(pF32); A(pI32); A(pI32); A(pI8); break; case OpCode::RayQuery_RayFlags: A(pI32); A(pI32); A(pI32); break; case OpCode::RayQuery_WorldRayOrigin:A(pF32); A(pI32); A(pI32); A(pI8); break; case OpCode::RayQuery_WorldRayDirection:A(pF32); A(pI32); A(pI32); A(pI8); break; case OpCode::RayQuery_RayTMin: A(pF32); A(pI32); A(pI32); break; case OpCode::RayQuery_CandidateTriangleRayT:A(pF32); A(pI32); A(pI32); break; case OpCode::RayQuery_CommittedRayT: A(pF32); A(pI32); A(pI32); break; case OpCode::RayQuery_CandidateInstanceIndex:A(pI32); A(pI32); A(pI32); break; case OpCode::RayQuery_CandidateInstanceID:A(pI32); A(pI32); A(pI32); break; case OpCode::RayQuery_CandidateGeometryIndex:A(pI32); A(pI32); A(pI32); break; case OpCode::RayQuery_CandidatePrimitiveIndex:A(pI32); A(pI32); A(pI32); break; case OpCode::RayQuery_CandidateObjectRayOrigin:A(pF32); A(pI32); A(pI32); A(pI8); break; case OpCode::RayQuery_CandidateObjectRayDirection:A(pF32); A(pI32); A(pI32); A(pI8); break; case OpCode::RayQuery_CommittedInstanceIndex:A(pI32); A(pI32); A(pI32); break; case OpCode::RayQuery_CommittedInstanceID:A(pI32); A(pI32); A(pI32); break; case OpCode::RayQuery_CommittedGeometryIndex:A(pI32); A(pI32); A(pI32); break; case OpCode::RayQuery_CommittedPrimitiveIndex:A(pI32); A(pI32); A(pI32); break; case OpCode::RayQuery_CommittedObjectRayOrigin:A(pF32); A(pI32); A(pI32); A(pI8); break; case OpCode::RayQuery_CommittedObjectRayDirection:A(pF32); A(pI32); A(pI32); A(pI8); break; // Raytracing object space uint System Values, raytracing tier 1.1 case OpCode::GeometryIndex: A(pI32); A(pI32); break; // Inline Ray Query case OpCode::RayQuery_CandidateInstanceContributionToHitGroupIndex:A(pI32); A(pI32); A(pI32); break; case OpCode::RayQuery_CommittedInstanceContributionToHitGroupIndex:A(pI32); A(pI32); A(pI32); break; // Get handle from heap case OpCode::CreateHandleFromHeap: A(pRes); A(pI32); A(pI32); A(pI1); break; case OpCode::AnnotateHandle: A(pRes); A(pI32); A(pRes); A(pI8); A(pI8); A(resProperty);break; // OPCODE-OLOAD-FUNCS:END default: DXASSERT(false, "otherwise unhandled case"); break; } #undef RRT #undef A FunctionType *pFT; DXASSERT(ArgTypes.size() > 1, "otherwise forgot to initialize arguments"); pFT = FunctionType::get(ArgTypes[0], ArrayRef<Type*>(&ArgTypes[1], ArgTypes.size()-1), false); F = cast<Function>(m_pModule->getOrInsertFunction(funcName, pFT)); UpdateCache(opClass, pOverloadType, F); F->setCallingConv(CallingConv::C); F->addFnAttr(Attribute::NoUnwind); if (m_OpCodeProps[(unsigned)opCode].FuncAttr != Attribute::None) F->addFnAttr(m_OpCodeProps[(unsigned)opCode].FuncAttr); return F; } const SmallDenseMap<llvm::Type *, llvm::Function *, 8> & OP::GetOpFuncList(OpCode opCode) const { DXASSERT(0 <= (unsigned)opCode && opCode < OpCode::NumOpCodes, "otherwise caller passed OOB OpCode"); _Analysis_assume_(0 <= (unsigned)opCode && opCode < OpCode::NumOpCodes); return m_OpCodeClassCache[(unsigned)m_OpCodeProps[(unsigned)opCode] .opCodeClass] .pOverloads; } void OP::RemoveFunction(Function *F) { if (OP::IsDxilOpFunc(F)) { OpCodeClass opClass = m_FunctionToOpClass[F]; for (auto it : m_OpCodeClassCache[(unsigned)opClass].pOverloads) { if (it.second == F) { m_OpCodeClassCache[(unsigned)opClass].pOverloads.erase(it.first); m_FunctionToOpClass.erase(F); break; } } } } bool OP::GetOpCodeClass(const Function *F, OP::OpCodeClass &opClass) { auto iter = m_FunctionToOpClass.find(F); if (iter == m_FunctionToOpClass.end()) { // When no user, cannot get opcode. DXASSERT(F->user_empty() || !IsDxilOpFunc(F), "dxil function without an opcode class mapping?"); return false; } opClass = iter->second; return true; } bool OP::UseMinPrecision() { return m_LowPrecisionMode == DXIL::LowPrecisionMode::UseMinPrecision; } void OP::SetMinPrecision(bool bMinPrecision) { DXIL::LowPrecisionMode mode = bMinPrecision ? DXIL::LowPrecisionMode::UseMinPrecision : DXIL::LowPrecisionMode::UseNativeLowPrecision; DXASSERT((mode == m_LowPrecisionMode || m_LowPrecisionMode == DXIL::LowPrecisionMode::Undefined), "LowPrecisionMode should only be set once."); m_LowPrecisionMode = mode; } uint64_t OP::GetAllocSizeForType(llvm::Type *Ty) { return m_pModule->getDataLayout().getTypeAllocSize(Ty); } llvm::Type *OP::GetOverloadType(OpCode opCode, llvm::Function *F) { DXASSERT(F, "not work on nullptr"); Type *Ty = F->getReturnType(); FunctionType *FT = F->getFunctionType(); /* <py::lines('OPCODE-OLOAD-TYPES')>hctdb_instrhelp.get_funcs_oload_type()</py>*/ switch (opCode) { // return OpCode // OPCODE-OLOAD-TYPES:BEGIN case OpCode::TempRegStore: case OpCode::CallShader: DXASSERT_NOMSG(FT->getNumParams() > 2); return FT->getParamType(2); case OpCode::MinPrecXRegStore: case OpCode::StoreOutput: case OpCode::BufferStore: case OpCode::StorePatchConstant: case OpCode::RawBufferStore: case OpCode::StoreVertexOutput: case OpCode::StorePrimitiveOutput: case OpCode::DispatchMesh: DXASSERT_NOMSG(FT->getNumParams() > 4); return FT->getParamType(4); case OpCode::IsNaN: case OpCode::IsInf: case OpCode::IsFinite: case OpCode::IsNormal: case OpCode::Countbits: case OpCode::FirstbitLo: case OpCode::FirstbitHi: case OpCode::FirstbitSHi: case OpCode::IMul: case OpCode::UMul: case OpCode::UDiv: case OpCode::UAddc: case OpCode::USubb: case OpCode::WaveActiveAllEqual: case OpCode::CreateHandleForLib: case OpCode::WaveMatch: DXASSERT_NOMSG(FT->getNumParams() > 1); return FT->getParamType(1); case OpCode::TextureStore: DXASSERT_NOMSG(FT->getNumParams() > 5); return FT->getParamType(5); case OpCode::TraceRay: DXASSERT_NOMSG(FT->getNumParams() > 15); return FT->getParamType(15); case OpCode::ReportHit: DXASSERT_NOMSG(FT->getNumParams() > 3); return FT->getParamType(3); case OpCode::CreateHandle: case OpCode::BufferUpdateCounter: case OpCode::GetDimensions: case OpCode::Texture2DMSGetSamplePosition: case OpCode::RenderTargetGetSamplePosition: case OpCode::RenderTargetGetSampleCount: case OpCode::Barrier: case OpCode::Discard: case OpCode::EmitStream: case OpCode::CutStream: case OpCode::EmitThenCutStream: case OpCode::CycleCounterLegacy: case OpCode::WaveIsFirstLane: case OpCode::WaveGetLaneIndex: case OpCode::WaveGetLaneCount: case OpCode::WaveAnyTrue: case OpCode::WaveAllTrue: case OpCode::WaveActiveBallot: case OpCode::BitcastI16toF16: case OpCode::BitcastF16toI16: case OpCode::BitcastI32toF32: case OpCode::BitcastF32toI32: case OpCode::BitcastI64toF64: case OpCode::BitcastF64toI64: case OpCode::LegacyF32ToF16: case OpCode::LegacyF16ToF32: case OpCode::LegacyDoubleToFloat: case OpCode::LegacyDoubleToSInt32: case OpCode::LegacyDoubleToUInt32: case OpCode::WaveAllBitCount: case OpCode::WavePrefixBitCount: case OpCode::IgnoreHit: case OpCode::AcceptHitAndEndSearch: case OpCode::WaveMultiPrefixBitCount: case OpCode::SetMeshOutputCounts: case OpCode::EmitIndices: case OpCode::WriteSamplerFeedback: case OpCode::WriteSamplerFeedbackBias: case OpCode::WriteSamplerFeedbackLevel: case OpCode::WriteSamplerFeedbackGrad: case OpCode::AllocateRayQuery: case OpCode::RayQuery_TraceRayInline: case OpCode::RayQuery_Abort: case OpCode::RayQuery_CommitNonOpaqueTriangleHit: case OpCode::RayQuery_CommitProceduralPrimitiveHit: case OpCode::CreateHandleFromHeap: case OpCode::AnnotateHandle: return Type::getVoidTy(m_Ctx); case OpCode::CheckAccessFullyMapped: case OpCode::AtomicBinOp: case OpCode::AtomicCompareExchange: case OpCode::SampleIndex: case OpCode::Coverage: case OpCode::InnerCoverage: case OpCode::ThreadId: case OpCode::GroupId: case OpCode::ThreadIdInGroup: case OpCode::FlattenedThreadIdInGroup: case OpCode::GSInstanceID: case OpCode::OutputControlPointID: case OpCode::PrimitiveID: case OpCode::ViewID: case OpCode::InstanceID: case OpCode::InstanceIndex: case OpCode::HitKind: case OpCode::RayFlags: case OpCode::DispatchRaysIndex: case OpCode::DispatchRaysDimensions: case OpCode::PrimitiveIndex: case OpCode::Dot4AddI8Packed: case OpCode::Dot4AddU8Packed: case OpCode::RayQuery_CommittedStatus: case OpCode::RayQuery_CandidateType: case OpCode::RayQuery_RayFlags: case OpCode::RayQuery_CandidateInstanceIndex: case OpCode::RayQuery_CandidateInstanceID: case OpCode::RayQuery_CandidateGeometryIndex: case OpCode::RayQuery_CandidatePrimitiveIndex: case OpCode::RayQuery_CommittedInstanceIndex: case OpCode::RayQuery_CommittedInstanceID: case OpCode::RayQuery_CommittedGeometryIndex: case OpCode::RayQuery_CommittedPrimitiveIndex: case OpCode::GeometryIndex: case OpCode::RayQuery_CandidateInstanceContributionToHitGroupIndex: case OpCode::RayQuery_CommittedInstanceContributionToHitGroupIndex: return IntegerType::get(m_Ctx, 32); case OpCode::CalculateLOD: case OpCode::DomainLocation: case OpCode::WorldRayOrigin: case OpCode::WorldRayDirection: case OpCode::ObjectRayOrigin: case OpCode::ObjectRayDirection: case OpCode::ObjectToWorld: case OpCode::WorldToObject: case OpCode::RayTMin: case OpCode::RayTCurrent: case OpCode::RayQuery_CandidateObjectToWorld3x4: case OpCode::RayQuery_CandidateWorldToObject3x4: case OpCode::RayQuery_CommittedObjectToWorld3x4: case OpCode::RayQuery_CommittedWorldToObject3x4: case OpCode::RayQuery_CandidateTriangleBarycentrics: case OpCode::RayQuery_CommittedTriangleBarycentrics: case OpCode::RayQuery_WorldRayOrigin: case OpCode::RayQuery_WorldRayDirection: case OpCode::RayQuery_RayTMin: case OpCode::RayQuery_CandidateTriangleRayT: case OpCode::RayQuery_CommittedRayT: case OpCode::RayQuery_CandidateObjectRayOrigin: case OpCode::RayQuery_CandidateObjectRayDirection: case OpCode::RayQuery_CommittedObjectRayOrigin: case OpCode::RayQuery_CommittedObjectRayDirection: return Type::getFloatTy(m_Ctx); case OpCode::MakeDouble: case OpCode::SplitDouble: return Type::getDoubleTy(m_Ctx); case OpCode::RayQuery_Proceed: case OpCode::RayQuery_CandidateProceduralPrimitiveNonOpaque: case OpCode::RayQuery_CandidateTriangleFrontFace: case OpCode::RayQuery_CommittedTriangleFrontFace: return IntegerType::get(m_Ctx, 1); case OpCode::CBufferLoadLegacy: case OpCode::Sample: case OpCode::SampleBias: case OpCode::SampleLevel: case OpCode::SampleGrad: case OpCode::SampleCmp: case OpCode::SampleCmpLevelZero: case OpCode::TextureLoad: case OpCode::BufferLoad: case OpCode::TextureGather: case OpCode::TextureGatherCmp: case OpCode::RawBufferLoad: { StructType *ST = cast<StructType>(Ty); return ST->getElementType(0); } // OPCODE-OLOAD-TYPES:END default: return Ty; } } Type *OP::GetHandleType() const { return m_pHandleType; } Type *OP::GetResourcePropertiesType() const { return m_pResourcePropertiesType; } Type *OP::GetDimensionsType() const { return m_pDimensionsType; } Type *OP::GetSamplePosType() const { return m_pSamplePosType; } Type *OP::GetBinaryWithCarryType() const { return m_pBinaryWithCarryType; } Type *OP::GetBinaryWithTwoOutputsType() const { return m_pBinaryWithTwoOutputsType; } Type *OP::GetSplitDoubleType() const { return m_pSplitDoubleType; } Type *OP::GetInt4Type() const { return m_pInt4Type; } bool OP::IsResRetType(llvm::Type *Ty) { for (Type *ResTy : m_pResRetType) { if (Ty == ResTy) return true; } return false; } Type *OP::GetResRetType(Type *pOverloadType) { unsigned TypeSlot = GetTypeSlot(pOverloadType); if (m_pResRetType[TypeSlot] == nullptr) { string TypeName("dx.types.ResRet."); TypeName += GetOverloadTypeName(TypeSlot); Type *FieldTypes[5] = { pOverloadType, pOverloadType, pOverloadType, pOverloadType, Type::getInt32Ty(m_Ctx) }; m_pResRetType[TypeSlot] = GetOrCreateStructType(m_Ctx, FieldTypes, TypeName, m_pModule); } return m_pResRetType[TypeSlot]; } Type *OP::GetCBufferRetType(Type *pOverloadType) { unsigned TypeSlot = GetTypeSlot(pOverloadType); if (m_pCBufferRetType[TypeSlot] == nullptr) { string TypeName("dx.types.CBufRet."); TypeName += GetOverloadTypeName(TypeSlot); Type *i64Ty = Type::getInt64Ty(pOverloadType->getContext()); Type *i16Ty = Type::getInt16Ty(pOverloadType->getContext()); if (pOverloadType->isDoubleTy() || pOverloadType == i64Ty) { Type *FieldTypes[2] = { pOverloadType, pOverloadType }; m_pCBufferRetType[TypeSlot] = GetOrCreateStructType(m_Ctx, FieldTypes, TypeName, m_pModule); } else if (!UseMinPrecision() && (pOverloadType->isHalfTy() || pOverloadType == i16Ty)) { TypeName += ".8"; // dx.types.CBufRet.fp16.8 for buffer of 8 halves Type *FieldTypes[8] = { pOverloadType, pOverloadType, pOverloadType, pOverloadType, pOverloadType, pOverloadType, pOverloadType, pOverloadType, }; m_pCBufferRetType[TypeSlot] = GetOrCreateStructType(m_Ctx, FieldTypes, TypeName, m_pModule); } else { Type *FieldTypes[4] = { pOverloadType, pOverloadType, pOverloadType, pOverloadType }; m_pCBufferRetType[TypeSlot] = GetOrCreateStructType(m_Ctx, FieldTypes, TypeName, m_pModule); } } return m_pCBufferRetType[TypeSlot]; } //------------------------------------------------------------------------------ // // LLVM utility methods. // Constant *OP::GetI1Const(bool v) { return Constant::getIntegerValue(IntegerType::get(m_Ctx, 1), APInt(1, v)); } Constant *OP::GetI8Const(char v) { return Constant::getIntegerValue(IntegerType::get(m_Ctx, 8), APInt(8, v)); } Constant *OP::GetU8Const(unsigned char v) { return GetI8Const((char)v); } Constant *OP::GetI16Const(int v) { return Constant::getIntegerValue(IntegerType::get(m_Ctx, 16), APInt(16, v)); } Constant *OP::GetU16Const(unsigned v) { return GetI16Const((int)v); } Constant *OP::GetI32Const(int v) { return Constant::getIntegerValue(IntegerType::get(m_Ctx, 32), APInt(32, v)); } Constant *OP::GetU32Const(unsigned v) { return GetI32Const((int)v); } Constant *OP::GetU64Const(unsigned long long v) { return Constant::getIntegerValue(IntegerType::get(m_Ctx, 64), APInt(64, v)); } Constant *OP::GetFloatConst(float v) { return ConstantFP::get(m_Ctx, APFloat(v)); } Constant *OP::GetDoubleConst(double v) { return ConstantFP::get(m_Ctx, APFloat(v)); } } // namespace hlsl
[ "yuri410@users.noreply.github.com" ]
yuri410@users.noreply.github.com
f44b5ebc7c3e4dd75f382d259f79fe54c3e6f0c2
135a6abace0f47b54a7fac3a39f17491735df0b4
/src/qt/bitcoinstrings.cpp
45400f96b08ba77b6827fb461fb1a0ab125ddb65
[ "MIT" ]
permissive
openrightlabs/StealthCash
e6c82599144820b09522fe23fafa58c3ea4f938f
68c71fcb341763ca3db1360d3930ed0b5d9581d1
refs/heads/master
2016-09-10T22:32:32.278843
2015-06-22T18:34:59
2015-06-22T18:34:59
37,872,906
0
0
null
null
null
null
UTF-8
C++
false
false
13,173
cpp
#include <QtGlobal> // Automatically generated by extract_strings.py #ifdef __GNUC__ #define UNUSED __attribute__((unused)) #else #define UNUSED #endif static const char UNUSED *bitcoin_strings[] = {QT_TRANSLATE_NOOP("bitcoin-core", "To use the %s option"), QT_TRANSLATE_NOOP("bitcoin-core", "" "%s, you must set a rpcpassword in the configuration file:\n" " %s\n" "It is recommended you use the following random password:\n" "rpcuser=stealthcashrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file " "permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"StealthCash Alert\" admin@foo." "com\n"), QT_TRANSLATE_NOOP("bitcoin-core", "Error"), QT_TRANSLATE_NOOP("bitcoin-core", "" "An error occurred while setting up the RPC port %u for listening on IPv6, " "falling back to IPv4: %s"), QT_TRANSLATE_NOOP("bitcoin-core", "" "An error occurred while setting up the RPC port %u for listening on IPv4: %s"), QT_TRANSLATE_NOOP("bitcoin-core", "" "You must set rpcpassword=<password> in the configuration file:\n" "%s\n" "If the file does not exist, create it with owner-readable-only file " "permissions."), QT_TRANSLATE_NOOP("bitcoin-core", "StealthCash version"), QT_TRANSLATE_NOOP("bitcoin-core", "Usage:"), QT_TRANSLATE_NOOP("bitcoin-core", "Send command to -server or stealthcashd"), QT_TRANSLATE_NOOP("bitcoin-core", "List commands"), QT_TRANSLATE_NOOP("bitcoin-core", "Get help for a command"), QT_TRANSLATE_NOOP("bitcoin-core", "StealthCash"), QT_TRANSLATE_NOOP("bitcoin-core", "Options:"), QT_TRANSLATE_NOOP("bitcoin-core", "This help message"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify configuration file (default: stealthcash.conf)"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify pid file (default: stealthcashd.pid)"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify data directory"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify wallet file (within data directory)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set database cache size in megabytes (default: 25)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set database disk log size in megabytes (default: 100)"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify connection timeout in milliseconds (default: 5000)"), QT_TRANSLATE_NOOP("bitcoin-core", "Connect through socks proxy"), QT_TRANSLATE_NOOP("bitcoin-core", "Select the version of socks proxy to use (4-5, default: 5)"), QT_TRANSLATE_NOOP("bitcoin-core", "Use proxy to reach tor hidden services (default: same as -proxy)"), QT_TRANSLATE_NOOP("bitcoin-core", "Allow DNS lookups for -addnode, -seednode and -connect"), QT_TRANSLATE_NOOP("bitcoin-core", "Listen for connections on <port> (default: 51737 or testnet: 51997)"), QT_TRANSLATE_NOOP("bitcoin-core", "Maintain at most <n> connections to peers (default: 125)"), QT_TRANSLATE_NOOP("bitcoin-core", "Add a node to connect to and attempt to keep the connection open"), QT_TRANSLATE_NOOP("bitcoin-core", "Connect only to the specified node(s)"), QT_TRANSLATE_NOOP("bitcoin-core", "Connect to a node to retrieve peer addresses, and disconnect"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify your own public address"), QT_TRANSLATE_NOOP("bitcoin-core", "Only connect to nodes in network <net> (IPv4, IPv6 or Tor)"), QT_TRANSLATE_NOOP("bitcoin-core", "Discover own IP address (default: 1 when listening and no -externalip)"), QT_TRANSLATE_NOOP("bitcoin-core", "Find peers using internet relay chat (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"), QT_TRANSLATE_NOOP("bitcoin-core", "Bind to given address. Use [host]:port notation for IPv6"), QT_TRANSLATE_NOOP("bitcoin-core", "Find peers using DNS lookup (default: 1)"), QT_TRANSLATE_NOOP("bitcoin-core", "Stake your coins to support network and gain reward (default: 1)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Sync time with other nodes. Disable if time on your system is precise e.g. " "syncing with NTP (default: 1)"), QT_TRANSLATE_NOOP("bitcoin-core", "Sync checkpoints policy (default: strict)"), QT_TRANSLATE_NOOP("bitcoin-core", "Threshold for disconnecting misbehaving peers (default: 100)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Number of seconds to keep misbehaving peers from reconnecting (default: " "86400)"), QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)"), QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)"), QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 1 when listening)"), QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Detach block and address databases. Increases shutdown time (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "Fee per KB to add to transactions you send"), QT_TRANSLATE_NOOP("bitcoin-core", "" "When creating transactions, ignore inputs with value less than this " "(default: 0.01)"), QT_TRANSLATE_NOOP("bitcoin-core", "Accept command line and JSON-RPC commands"), QT_TRANSLATE_NOOP("bitcoin-core", "Run in the background as a daemon and accept commands"), QT_TRANSLATE_NOOP("bitcoin-core", "Use the test network"), QT_TRANSLATE_NOOP("bitcoin-core", "Output extra debugging information. Implies all other -debug* options"), QT_TRANSLATE_NOOP("bitcoin-core", "Output extra network debugging information"), QT_TRANSLATE_NOOP("bitcoin-core", "Prepend debug output with timestamp"), QT_TRANSLATE_NOOP("bitcoin-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"), QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to console instead of debug.log file"), QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to debugger"), QT_TRANSLATE_NOOP("bitcoin-core", "Username for JSON-RPC connections"), QT_TRANSLATE_NOOP("bitcoin-core", "Password for JSON-RPC connections"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Listen for JSON-RPC connections on <port> (default: 51736 or testnet: 51996)"), QT_TRANSLATE_NOOP("bitcoin-core", "Allow JSON-RPC connections from specified IP address"), QT_TRANSLATE_NOOP("bitcoin-core", "Send commands to node running on <ip> (default: 127.0.0.1)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Execute command when the best block changes (%s in cmd is replaced by block " "hash)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Execute command when a wallet transaction changes (%s in cmd is replaced by " "TxID)"), QT_TRANSLATE_NOOP("bitcoin-core", "Require a confirmations for change (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Enforce transaction scripts to use canonical PUSH operators (default: 1)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Execute command when a relevant alert is received (%s in cmd is replaced by " "message)"), QT_TRANSLATE_NOOP("bitcoin-core", "Upgrade wallet to latest format"), QT_TRANSLATE_NOOP("bitcoin-core", "Set key pool size to <n> (default: 100)"), QT_TRANSLATE_NOOP("bitcoin-core", "Rescan the block chain for missing wallet transactions"), QT_TRANSLATE_NOOP("bitcoin-core", "Attempt to recover private keys from a corrupt wallet.dat"), QT_TRANSLATE_NOOP("bitcoin-core", "How many blocks to check at startup (default: 2500, 0 = all)"), QT_TRANSLATE_NOOP("bitcoin-core", "How thorough the block verification is (0-6, default: 1)"), QT_TRANSLATE_NOOP("bitcoin-core", "Imports blocks from external blk000?.dat file"), QT_TRANSLATE_NOOP("bitcoin-core", "Block creation options:"), QT_TRANSLATE_NOOP("bitcoin-core", "Set minimum block size in bytes (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set maximum block size in bytes (default: 250000)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Set maximum size of high-priority/low-fee transactions in bytes (default: " "27000)"), QT_TRANSLATE_NOOP("bitcoin-core", "SSL options: (see the Bitcoin Wiki for SSL setup instructions)"), QT_TRANSLATE_NOOP("bitcoin-core", "Use OpenSSL (https) for JSON-RPC connections"), QT_TRANSLATE_NOOP("bitcoin-core", "Server certificate file (default: server.cert)"), QT_TRANSLATE_NOOP("bitcoin-core", "Server private key (default: server.pem)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:" "@STRENGTH)"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -paytxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: -paytxfee is set very high! This is the transaction fee you will " "pay if you send a transaction."), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -mininput=<amount>: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Wallet %s resides outside data directory %s."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Cannot obtain a lock on data directory %s. StealthCash is probably already " "running."), QT_TRANSLATE_NOOP("bitcoin-core", "Verifying database integrity..."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Error initializing database environment %s! To recover, BACKUP THAT " "DIRECTORY, then remove everything from it except for wallet.dat."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as " "wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect " "you should restore from a backup."), QT_TRANSLATE_NOOP("bitcoin-core", "wallet.dat corrupt, salvage failed"), QT_TRANSLATE_NOOP("bitcoin-core", "Unknown -socks proxy version requested: %i"), QT_TRANSLATE_NOOP("bitcoin-core", "Unknown network specified in -onlynet: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -proxy address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -tor address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -bind address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to listen on any port. Use -listen=0 if you want this."), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -externalip address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -reservebalance=<amount>"), QT_TRANSLATE_NOOP("bitcoin-core", "Unable to sign checkpoint, wrong checkpointkey?\n"), QT_TRANSLATE_NOOP("bitcoin-core", "Loading block index..."), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading blkindex.dat"), QT_TRANSLATE_NOOP("bitcoin-core", "Loading wallet..."), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet corrupted"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: error reading wallet.dat! All keys read correctly, but transaction " "data or address book entries might be missing or incorrect."), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet requires newer version of StealthCash"), QT_TRANSLATE_NOOP("bitcoin-core", "Wallet needed to be rewritten: restart StealthCash to complete"), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot downgrade wallet"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot initialize keypool"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot write default address"), QT_TRANSLATE_NOOP("bitcoin-core", "Rescanning..."), QT_TRANSLATE_NOOP("bitcoin-core", "Importing blockchain data file."), QT_TRANSLATE_NOOP("bitcoin-core", "Importing bootstrap blockchain data file."), QT_TRANSLATE_NOOP("bitcoin-core", "Loading addresses..."), QT_TRANSLATE_NOOP("bitcoin-core", "Error: could not start node"), QT_TRANSLATE_NOOP("bitcoin-core", "Done loading"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Unable to bind to %s on this computer. StealthCash is probably already running."), QT_TRANSLATE_NOOP("bitcoin-core", "Unable to bind to %s on this computer (bind returned error %d, %s)"), QT_TRANSLATE_NOOP("bitcoin-core", "Error: Wallet locked, unable to create transaction "), QT_TRANSLATE_NOOP("bitcoin-core", "Error: Wallet unlocked for staking only, unable to create transaction."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Error: This transaction requires a transaction fee of at least %s because of " "its amount, complexity, or use of recently received funds "), QT_TRANSLATE_NOOP("bitcoin-core", "Error: Transaction creation failed "), QT_TRANSLATE_NOOP("bitcoin-core", "Sending..."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Error: The transaction was rejected. This might happen if some of the coins " "in your wallet were already spent, such as if you used a copy of wallet.dat " "and coins were spent in the copy but not marked as spent here."), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount"), QT_TRANSLATE_NOOP("bitcoin-core", "Insufficient funds"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: Please check that your computer's date and time are correct! If " "your clock is wrong StealthCash will not work properly."), QT_TRANSLATE_NOOP("bitcoin-core", "Warning: This version is obsolete, upgrade required!"), QT_TRANSLATE_NOOP("bitcoin-core", "WARNING: syncronized checkpoint violation detected, but skipped!"), QT_TRANSLATE_NOOP("bitcoin-core", "Warning: Disk space is low!"), QT_TRANSLATE_NOOP("bitcoin-core", "" "WARNING: Invalid checkpoint found! Displayed transactions may not be " "correct! You may need to upgrade, or notify developers."), };
[ "niitassin@gmail.com" ]
niitassin@gmail.com
0fbdd0ceef497c724ef9d0d479c243bcfc6ccb1e
6b5357388049b43be7b5fb3933ef883a147ec012
/PathPlannerApp/CCS/planner/Preplanner.h
d425c4c75a96dfae7112e25a3e42c48ad24f7feb
[]
no_license
akosnagy2/Diploma
eb1dc3c2c642aea22eb52ab00cda468c1789ce4c
00753e658347b4b8fddc7f3b1223b320ed53b4eb
refs/heads/master
2021-01-23T21:33:58.306157
2015-06-25T20:57:50
2015-06-25T20:57:50
24,590,168
1
2
null
null
null
null
UTF-8
C++
false
false
439
h
/* * File: Preplanner.h * Author: Gábor * * Created on 2014. március 25., 10:48 */ #ifndef PREPLANNER_H #define PREPLANNER_H #include "Shape.h" #include "Triangulator.h" class Preplanner { public: Preplanner(Robot& robot, pointList& points, adjacencyMatrix& connections); configurationList& getPath(); bool isPathExist(); private: configurationList configPath; bool isPath; }; #endif /* PREPLANNER_H */
[ "csorvagep@gmail.com" ]
csorvagep@gmail.com
88f97535a5325461f9f14c0c8da21190d98a3832
4eb4242f67eb54c601885461bac58b648d91d561
/third_part/indri5.6/TFIDFTermScoreFunction.cpp
224553165c78565095ebecf948fe0d1cdb76a195
[]
no_license
biebipan/coding
630c873ecedc43a9a8698c0f51e26efb536dabd1
7709df7e979f2deb5401d835d0e3b119a7cd88d8
refs/heads/master
2022-01-06T18:52:00.969411
2018-07-18T04:30:02
2018-07-18T04:30:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
590
cpp
/*========================================================================== * Copyright (c) 2004 University of Massachusetts. All Rights Reserved. * * Use of the Lemur Toolkit for Language Modeling and Information Retrieval * is subject to the terms of the software license set forth in the LICENSE * file included with this software, and also available at * http://www.lemurproject.org/license.html * *========================================================================== */ // // TFIDFScoreFunction // // 23 January 2004 -- tds // #include "TFIDFTermScoreFunction.hpp"
[ "guoliqiang2006@126.com" ]
guoliqiang2006@126.com
19e1d32a720cd050339b9145e0b37c1bc578422b
3fb0d8bc4c426af216894957e9ede0790183a801
/include/DroneAI/Math.h
346399fbf5ae549201fc6a688437ff46d31f6a31
[]
no_license
wmramazan/atlas_drone
f654796dff6b13da62704aab687b0069bf40935a
d2dab31e8afafd118229d7a506fef5390c52fe24
refs/heads/master
2020-03-19T15:02:51.945921
2019-01-21T01:09:02
2019-01-21T01:09:02
136,653,446
1
0
null
null
null
null
UTF-8
C++
false
false
2,215
h
#ifndef MATH_H #define MATH_H #include <geometry_msgs/QuaternionStamped.h> #include <geometry_msgs/Quaternion.h> #include <geometry_msgs/PoseStamped.h> #include <geometry_msgs/Pose.h> #include <geometry_msgs/PointStamped.h> #include <geometry_msgs/Point.h> #include <tf/tf.h> using namespace geometry_msgs; #define PI 3.14159265359 #define DEG2RAD ((PI * 2) / 360) #define RAD2DEG (360 / (PI * 2)) class Math { public: static double GetRPY(geometry_msgs::Quaternion orientation, double& roll, double& pitch, double& yaw) { tf::Quaternion quaternion(orientation.x, orientation.y, orientation.z, orientation.w); tf::Matrix3x3 m(quaternion); m.getRPY(roll, pitch, yaw); } static void SetRPY(geometry_msgs::Quaternion& orientation, double roll, double pitch, double yaw) { tf::Quaternion quaternion(orientation.x, orientation.y, orientation.z, orientation.w); tf::Matrix3x3 m(quaternion); m.setRPY(roll, pitch, yaw); m.getRotation(quaternion); orientation.x = quaternion.getX(); orientation.y = quaternion.getY(); orientation.z = quaternion.getZ(); orientation.w = quaternion.getW(); //tf::quaternionTFToMsg(quaternion, orientation); } static double GetRoll(Quaternion orientation) { double roll, pitch, yaw; GetRPY(orientation, roll, pitch, yaw); return roll; } static double GetPitch(Quaternion orientation) { double roll, pitch, yaw; GetRPY(orientation, roll, pitch, yaw); return pitch; } static double GetYaw(Quaternion orientation) { double roll, pitch, yaw; GetRPY(orientation, roll, pitch, yaw); return yaw; } static void SetYaw(Quaternion& orientation, double yaw_angle) { double roll, pitch, yaw; GetRPY(orientation, roll, pitch, yaw); SetRPY(orientation, roll, pitch, yaw_angle); } static double ClampAngle(double angle) { if (angle > PI) { angle -= 2 * PI; } else if (angle < -PI) { angle += 2 * PI; } return angle; } }; #endif // MATH_H
[ "wmrmzn@gmail.com" ]
wmrmzn@gmail.com
3f49002673caa84b15eefc9d9a42f9f775539cc3
22f927d932a752f5d7d179ca33501bd714b2ffaa
/ConditionServer/GlobalConfig.h
b75c7dd8ec862a41f467244296a6202b843ef176
[]
no_license
alfredyanglei/HELLO-WORLD
e4d4771c6e8fa5532839b7e9a17d6488bbe54899
02749d5ae85a1fcdce578012d3b1169e9401dc40
refs/heads/master
2020-03-26T05:39:46.620471
2018-08-14T01:07:01
2018-08-14T01:07:01
144,567,908
0
0
null
null
null
null
UTF-8
C++
false
false
1,582
h
/* * GlobalConfig.h * * Created on: 2017年1月20日 * Author: 8888 */ #ifndef GLOBALCONFIG_H_ #define GLOBALCONFIG_H_ #include "servant/Application.h" #include "Common.h" #include "Condition.h" #include "util/tc_mysql.h" #include "util/tc_common.h" class GlobalConfig : public TC_Singleton<GlobalConfig> { public: GlobalConfig(); virtual ~GlobalConfig(); public: void initialize(); inline string getBasicHqObj(){return _sBasicHqObj;} inline taf::TC_DBConf getDBConf(){return _dbConf;} inline int getFreshTime(){ return _FreshTime; } inline int getInfoTime(){ return _InfoTime; } inline int getHqTime(){ return _HqTime; } inline string getRowList(){ return _sRowList; } string getFactorValue(HQExtend::E_CONDITION_FACTOR eFct); string getTableName(HQExtend::E_CONDITION_TABLE eTable); string getMacdValue(int iType); string getKdjValue(int iType); string getRsiValue(int iType); string getBollValue(int iType); string getKxtValue(int iType); private: string _sBasicHqObj; taf::TC_DBConf _dbConf; int _FreshTime; //quant_fct_value_row_q_fresh更新数据时间 int _InfoTime; //stk_basic_info更新数据时间 int _HqTime; //更新最新行情数据时间 //因子对应值 map<string, string> _mFctValue; //因子对应的查询表 map<string, string> _mTable; //技术指标因子枚举对应列 map<string, string> _mMacdValue; map<string, string> _mKdjValue; map<string, string> _mBollValue; map<string, string> _mRsiValue; map<string, string> _mKxtValue; string _sRowList; }; #endif /* GLOBALCONFIG_H_ */
[ "alfredyang@upchina.com" ]
alfredyang@upchina.com
04f2e88b9b25ea13c7ed96a9a3cc1a18939c83b0
44216c5af9074234a495a343820338b12090f252
/extras/drone_segment.cpp
2d74e9da19c5f4e12053574229ecce7eb987e5e9
[]
no_license
ncoop57/drone_reu_2017
e3a75d2c27eb9b860569625ed9b382d2d186bf77
5ec0722a87687592d4e8e5df423a6ddba24f11b2
refs/heads/master
2021-01-25T08:20:06.692904
2017-07-13T15:51:54
2017-07-13T15:51:54
93,757,820
1
0
null
null
null
null
UTF-8
C++
false
false
13,159
cpp
#include <iostream> #include <algorithm> #include <stdio.h> #include <opencv2/opencv_modules.hpp> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/cudafeatures2d.hpp> #include <opencv2/cudaimgproc.hpp> #include <opencv2/xfeatures2d/cuda.hpp> #include <opencv2/videoio/videoio.hpp> #include <opencv2/features2d.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/ximgproc.hpp> #include "opencv2/imgcodecs.hpp" #include "ardrone/ardrone.h" #include <pthread.h> //#include <omp.h> using namespace std; using namespace cv; using namespace cv::cuda; #define NUM_THREADS 1 ARDrone ardrone; int FLAG = 0; /* Used for segmentation */ Scalar hsv_to_rgb(Scalar c) { Mat in(1, 1, CV_32FC3); Mat out(1, 1, CV_32FC3); float * p = in.ptr<float>(0); p[0] = (float)c[0] * 360.0f; p[1] = (float)c[1]; p[2] = (float)c[2]; cv::cvtColor(in, out, cv::COLOR_HSV2RGB); Scalar t; Vec3f p2 = out.at<Vec3f>(0, 0); t[0] = (int)(p2[0] * 255); t[1] = (int)(p2[1] * 255); t[2] = (int)(p2[2] * 255); return t; } /* Used for segmentation */ Scalar color_mapping(int segment_id) { double base = (double)(segment_id) * 0.618033988749895 + 0.24443434; return hsv_to_rgb(Scalar(fmod(base, 1.2), 0.95, 0.80)); } // Struct used in clustering section typedef struct{ bool is_grouped; cv::Point Pt; int ID; }node; // Struct used to pass arguments to Pthread typedef struct{ double vxt; double vyt; double vzt; double vrt; }thread_data; thread_data thread_data_array[NUM_THREADS]; // Pthread function to issue avoidance command void *move(void *threadarg) { thread_data *my_data; my_data = (thread_data *) threadarg; double vx = my_data->vxt; double vy = my_data->vyt; double vz = my_data->vzt; double vr = my_data->vrt; for(int i = 0; i < 5; i++) ardrone.move3D(0.0, vy, vz, vr); pthread_exit(NULL); } int main(int argc, char* argv[]) { try { // ARDrone ardrone; if (!ardrone.open()) return -1; cv::Mat frame, currFrame, origFrame, prevFrame, h_currDescriptors, h_prevDescriptors, image_gray; std::vector<cv::KeyPoint> h_currKeypoints, h_prevKeypoints; GpuMat d_frame, d_fgFrame, d_greyFrame, d_descriptors, d_keypoints; GpuMat d_threshold; /* Segmentation variable */ Ptr<cv::ximgproc::segmentation::GraphSegmentation> seg = cv::ximgproc::segmentation::createGraphSegmentation(0.8, 300, 30); SURF_CUDA detector(800); cv::BFMatcher matcher; //Ptr<cv::cuda::DescriptorMatcher> matcher = cv::cuda::DescriptorMatcher::createBFMatcher(detector.defaultNorm()); vector<cv::DMatch> matches, good_matches; origFrame = ardrone.getImage(); cv::resize(origFrame, prevFrame, cv::Size(200,200)); d_frame.upload(prevFrame); cv::cuda::cvtColor(d_frame, d_greyFrame, CV_RGB2GRAY); detector(d_greyFrame, GpuMat(), d_keypoints, d_descriptors); detector.downloadKeypoints(d_keypoints, h_prevKeypoints); d_descriptors.download(h_prevDescriptors); for (;;) { std::cout << "Battery = " << ardrone.getBatteryPercentage() << "[%]\r" << std::flush; origFrame = ardrone.getImage(); cv::resize(origFrame, currFrame, cv::Size(200,200)); d_frame.upload(currFrame); cv::cuda::cvtColor(d_frame, d_greyFrame, CV_RGB2GRAY); detector(d_greyFrame, GpuMat(), d_keypoints, d_descriptors); detector.downloadKeypoints(d_keypoints, h_currKeypoints); d_descriptors.download(h_currDescriptors); h_prevDescriptors.convertTo(h_prevDescriptors, CV_32F); h_currDescriptors.convertTo(h_currDescriptors, CV_32F); try { matcher.match(h_prevDescriptors, h_currDescriptors, matches); } catch (const cv::Exception& ex) { } currFrame.copyTo(frame); double max_dist = 0; double min_dist = 100; for (int i = 0; i < h_prevDescriptors.rows; i++) { double dist = matches[i].distance; if (dist < min_dist) min_dist = dist; if (dist > max_dist) max_dist = dist; } std::vector<cv::DMatch> good_matches; for (int i = 0; i < h_prevDescriptors.rows; i++) { int prev = matches[i].queryIdx; int curr = matches[i].trainIdx; double ratio = h_currKeypoints[curr].size / h_prevKeypoints[prev].size; if (matches[i].distance < 4*min_dist && ratio > 1.0) { good_matches.push_back(matches[i]); } } try { if (good_matches.size() > 2) { std::vector<cv::Point> prevPoints; std::vector<cv::Point> currPoints; std::vector<node> prev_quick; std::vector<node> curr_quick; std::vector<cv::Point> prev_midpoints; std::vector<cv::Point> curr_midpoints; for (unsigned int i = 0; i < good_matches.size(); i++) { prevPoints.push_back(h_prevKeypoints[good_matches[i].queryIdx].pt); currPoints.push_back(h_currKeypoints[good_matches[i].trainIdx].pt); node prev_node = {false, h_prevKeypoints[good_matches[i].queryIdx].pt, -1}; node curr_node = {false, h_currKeypoints[good_matches[i].trainIdx].pt, -1}; prev_quick.push_back(prev_node); curr_quick.push_back(curr_node); } // cout << "Initialized Nodes" << endl; //-------------- Clustering Section --------------- std::vector<std::vector<cv::Point > > prev_group_pts; std::vector<std::vector<cv::Point> > curr_group_pts; std::vector<node> queue; int threshold = 55; for(unsigned int i = 0; i < good_matches.size(); i++) { if(curr_quick[i].is_grouped) continue; std::vector<cv::Point> prev_cluster; std::vector<cv::Point > curr_cluster; prev_cluster.push_back(prev_quick[i].Pt); curr_cluster.push_back(curr_quick[i].Pt); curr_quick[i].is_grouped = true; curr_quick[i].ID = curr_group_pts.size(); queue.push_back(curr_quick[i]); while(!queue.empty()) { // cout << " Q Size: " << queue.size() << endl; node work_node = queue.back(); queue.pop_back(); for (unsigned int j = 0; j < good_matches.size(); j++) { if(work_node.Pt == curr_quick[j].Pt || curr_quick[j].is_grouped == true ) continue; double dist = norm(work_node.Pt - curr_quick[j].Pt); if(dist < threshold) { curr_quick[j].is_grouped = true; curr_quick[j].ID = curr_group_pts.size(); prev_cluster.push_back(prev_quick[j].Pt); curr_cluster.push_back(curr_quick[j].Pt); queue.push_back(curr_quick[j]); } } // cout << "Added Node to cluster" << endl; } // Compute midpoints double cx = 0, cy = 0, px = 0, py = 0; for(unsigned int p = 0; p < curr_cluster.size(); p++) { cx += curr_cluster[p].x; cy += curr_cluster[p].y; px += prev_cluster[p].x; py += prev_cluster[p].y; } cx /= curr_cluster.size(); cy /= curr_cluster.size(); px /= curr_cluster.size(); py /= curr_cluster.size(); Point c_mid(cx, cy); Point p_mid(px, py); if (curr_cluster.size() > 2) { curr_midpoints.push_back(c_mid); prev_midpoints.push_back(p_mid); prev_group_pts.push_back(prev_cluster); curr_group_pts.push_back(curr_cluster); // cout << "Group Created: " << curr_group_pts.size() << endl; } } // cout << "Group Created: " << curr_group_pts.size() << endl; // --------------End of Clustering----------------- // -------------Begining of Segmentation ---------- Mat prev_input, prev_output, curr_input, curr_output, prev_output_image, curr_output_image; seg->processImage(prevFrame, prev_output); double mins, maxs; minMaxLoc(prev_output, &mins, &maxs); int nb_segs = (int)maxs + 1; std::cout << nb_segs << " segments" << std::endl; prev_output_image = Mat::zeros(prev_output.rows, prev_output.cols, CV_8UC3); uint* p; uchar* p2; for (int i = 0; i < prev_output.rows; i++) { p = prev_output.ptr<uint>(i); p2 = prev_output_image.ptr<uchar>(i); for (int j = 0; j < prev_output.cols; j++) { Scalar color = color_mapping(p[j]); p2[j*3] = (uchar)color[0]; p2[j*3 + 1] = (uchar)color[1]; p2[j*3 + 2] = (uchar)color[2]; } } seg->processImage(currFrame, curr_output); minMaxLoc(curr_output, &mins, &maxs); nb_segs = (int)maxs + 1; std::cout << nb_segs << " segments" << std::endl; curr_output_image = Mat::zeros(curr_output.rows, curr_output.cols, CV_8UC3); uint* q; uchar* q2; for (int i = 0; i < curr_output.rows; i++) { q = curr_output.ptr<uint>(i); q2 = curr_output_image.ptr<uchar>(i); for (int j = 0; j < curr_output.cols; j++) { Scalar color = color_mapping(q[j]); q2[j*3] = (uchar)color[0]; q2[j*3 + 1] = (uchar)color[1]; q2[j*3 + 2] = (uchar)color[2]; } } imshow("curr", curr_output_image); // ------------End of segmentation --------------- double vx = 1.0, vy = 0.0, vz = 0.0, vr = 0.0; std::vector<std::vector<cv::Point> > prev_hull(prev_group_pts.size()); std::vector<std::vector<cv::Point> > curr_hull(curr_group_pts.size()); for (unsigned int i = 0; i < curr_group_pts.size(); i++) { int prev_fill = 0, curr_fill = 0; Rect boundRect; prev_fill = floodFill(prev_output_image, prev_midpoints[i], cv::Scalar(250, 250, 250)); curr_fill = floodFill(curr_output_image, curr_midpoints[i], cv::Scalar(250, 250, 250), &boundRect); cv::circle(frame, curr_midpoints[i], 10, cv::Scalar(250, 50, 0), 3); double ratio = (double)curr_fill / prev_fill; std::cout << "Prev Area: " << prev_fill << " Curr Area: " << curr_fill << " Ratio: " << ratio << std::endl; if (ratio > 1.2 && ratio < 2) { // Used to approximate countours to polygons + get bounding rects cv::rectangle(frame, boundRect.tl(), boundRect.br(), cv::Scalar(200,200,0), 2, 8, 0); // Check which quadrant(s) rectangle is in cv::Point top_left(boundRect.tl().x, boundRect.tl().y); cv::Point top_right(boundRect.tl().x + boundRect.width, boundRect.tl().y); cv::Point bot_left(boundRect.tl().x, boundRect.tl().y + boundRect.height); cv::Point bot_right(boundRect.tl().x + boundRect.width, boundRect.tl().y + boundRect.height); vy += min(0.25, 0.01 * (top_left.x - frame.cols / 2.0)); vy += max(-0.25, 0.01 * (top_right.x - frame.cols / 2.0)); // vz -= min(1.0, 0.01 * (top_left.y - frame.rows / 2.0)); // vz -= max(-1.0, 0.01 * (bot_left.y - frame.rows / 2.0)); cout << "Left/Right: " << vy << " Up/Down: " << vz << endl; } } /* ------------------PTHREAD SECTION ----------------------*/ pthread_t threads[NUM_THREADS]; int rc; long t; for(t = 0; t < NUM_THREADS; t++) { thread_data_array[t].vxt = vx; thread_data_array[t].vyt = vy; thread_data_array[t].vzt = vz; thread_data_array[t].vrt = vr; rc = pthread_create(&threads[t], NULL, move, (void *) &thread_data_array[t]); if(rc){ cout << "Error creating thread" << endl; exit(-1); } } /* for (int i = 0; i < 10; i++) { char key = cv::waitKey(1); if (key == ' ') { if (ardrone.onGround()) ardrone.takeoff(); else ardrone.landing(); } ardrone.move3D(vx, vy, vz, vr); } */ /*------------------END OF PTHREAD-------------------------*/ curr_group_pts.clear(); prev_group_pts.clear(); } } catch (const cv::Exception& ex) { continue; } cv::imshow("Result", frame); char key = cvWaitKey(1); if (key == 27) // Esc key break; currFrame.copyTo(prevFrame); h_prevKeypoints.clear(); h_prevKeypoints = h_currKeypoints; h_currKeypoints.clear(); h_currDescriptors.copyTo(h_prevDescriptors); // Take off / Landing if (key == ' ') { if (ardrone.onGround()) { ardrone.takeoff(); cout << "Start" << endl; // Wait(secs) to stabilize, before commands sleep(10); cout << "End" << endl; } else ardrone.landing(); } // Move /* double vx = 0.0, vy = 0.0, vz = 0.0, vr = 0.0; if (key == 'w' || key == CV_VK_UP) vx = 0.5; if (key == 's' || key == CV_VK_DOWN) vx = -0.5; if (key == 'q' || key == CV_VK_LEFT) vr = 0.5; if (key == 'e' || key == CV_VK_RIGHT) vr = -0.5; if (key == 'a') vy = 1.0; if (key == 'd') vy = -1.0; if (key == 'u') vz = 1.0; if (key == 'j') vz = -1.0; ardrone.move3D(vx, vy, vz, vr); */ // Change camera static int mode = 0; if (key == 'c') ardrone.setCamera(++mode % 4); } ardrone.close(); } catch (const cv::Exception& ex) { std::cout << "Error: " << ex.what() << std::endl; } // pthread_exit(NULL); return 0; }
[ "chapmro@auburn.edu" ]
chapmro@auburn.edu
c5d282257e3579a631396c208c36f8f899dcea42
f4ad4581cffee0416b1dee2624467673337f6135
/src/competitionCtrl.h
54b724481091d94566249db64d194c73440b49b9
[]
no_license
agoffer/secretary
76fba58e33e39f4ba784590c7779d69f2be29ded
0c24719741f7796ae8231d1452c81466b7620ad2
refs/heads/master
2020-05-19T11:53:56.836823
2018-02-15T18:22:50
2018-02-15T18:22:50
6,301,848
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
4,644
h
//--------------------------------------------------------------------------- #ifndef competitionCtrlH #define competitionCtrlH #include "competitionRankCtrl.h" #include <vcl.h> //****************************************// // Класс представлющий объекты // "Соревнования" // Определены методы управления объектом // @author Andrey V. Goffer // @create 24.11.05 //****************************************// class TCompetition{ private: //Идентификатор int id; //Дата начала соревнований TDate beginDate; //Дата окончания соревнований TDate endDate; //Комментарии AnsiString asComments; //Идентификатор статуса соревнований int competitionRankId; //Поля расширения bool extended; TCompetitionRank competitionRank; // Интерфейс объекта // public: //-- Конструктор //@param inBeginDate - дата начала проведения соревнований //@param inEndDate - дата окончания проведения соревнований //@param inCompetitionRankId - идент. статуса соревнований //@param asInComments - комментарии TCompetition(TDate inBeginDate, TDate inEndDate, int inCompetitionRankId, AnsiString asInComments); //-- Конструктор по умолчанию TCompetition(void){ beginDate = Now(); endDate = Now(); competitionRankId = 0; asComments = ""; id = 0; extended = false; } //-- Деструктор ~TCompetition(void); //--Проверка объекта //@return true - если объект допустим, false - если объект не валидный bool valid(AnsiString &errmess); //-- Сохранение объекта в базе данных void store(void); //-- Чтение всех объектов из базы данных //@return Массив объектов, прочитанных из базы данных, // или null, если объектов в базе не найдено static TList* getAll(void); //-- Загрузить объект из хранилища //@param id идентификатор записи, которую загрузить void getById(int id); //-- Получить текущее соревнование из расширенной таблицы static TCompetition getExtendedCurrent(void); //-- Получить максимальную и минимальную дату начала соревнований //@param minBeginDate - минимальная дата начала соревнования //@param maxBeginDate - максимальная дата начала соревнования static void getMinMaxBeginDate(TDateTime &minBeginDate, TDateTime &maxBeginDate); //-- Получить максимальную и минимальную дату окончания соревнований //@param minEndDate - минимальная дата окончания соревнования //@param maxEndDate - максимальная дата окончания соревнования static void getMinMaxEndDate(TDateTime &minBeginDate, TDateTime &maxBeginDate); //-- методы получения и сохранения свойств объекта int getId(void); void setId(int inId); TDate getBeginDate(void); void setBeginDate(TDate inBeginDate); TDate getEndDate(void); void setEndDate(TDate inEndDate); int getCompetitionRankId(void); void setCompetitionRankId(int inCompetitionRankId); AnsiString getComments(void); void setComments(AnsiString asInComments); //-- Определяем, был ли объект расширен bool isExtended(void){return extended;} //-- Методы возвращающие расширенные поля TCompetitionRank getCompetitionRank(void){return competitionRank;} //-- Расширить объект подобъектами void extend(TCompetitionRank inCompetitionRank){competitionRank = inCompetitionRank; extended = true;}; }; //--------------------------------------------------------------------------- #endif
[ "a.goffer@gmail.com" ]
a.goffer@gmail.com
7d4fdde60a6e483424bb9011cadcfd5b05a56492
fac780cf62dacb346e4f7139bb1e9ac07b816486
/SRC/javascript.cpp
71dad15e9692290f32fcad16703cf693c3448497
[ "MIT" ]
permissive
ChatScript/ChatScript
88670862f27199121effe5039ff12840bd7e2899
7b0d126cd3cc0132c5497d05e3c02430d7c01f05
refs/heads/master
2023-08-18T09:56:59.110537
2023-08-13T13:12:59
2023-08-13T13:12:59
121,162,370
320
144
MIT
2023-01-31T11:24:55
2018-02-11T20:08:21
C++
UTF-8
C++
false
false
6,779
cpp
#include "common.h" // Copyright(C) 2011 - 2020 by Bruce Wilcox #ifndef DISCARDJAVASCRIPT #include "duktape/duktape.h" duk_context *ctxPermanent = NULL; duk_context *ctxTransient = NULL; duk_context *ctx; #endif #include "common1.h" #ifndef WIN32 #define stricmp strcasecmp #define strnicmp strncasecmp #endif void ChangeSpecial(char* buffer); // Duktape has no I/O by default // define function that can be called from JS that will log a string static duk_ret_t native_log(duk_context *ctx) { Log(USERLOG, "%s", duk_to_string(ctx, 0)); return 0; /* no return value (= undefined) */ } // there are 2 contexts: a permanently resident one for the system and a transient one per volley. // ONE instance per server... so all routines are shared until gone. Need to distinguish "inits" from calls. // OR runtime per user, always init and call. FunctionResult RunJavaScript(char* definition, char* buffer, unsigned int args) { // Javascript permanent {call void name type type} eval ...code... char* defstart = definition; bool inited = (*definition++ == '.'); *buffer = 0; #ifndef DISCARDJAVASCRIPT char context[MAX_WORD_SIZE]; definition = ReadCompiledWord(definition,context); if (!stricmp(context,"permanent")) { if (!ctxPermanent) { ctxPermanent = duk_create_heap_default(); if (!ctxPermanent) return FAILRULE_BIT; // unable to init it } ctx = ctxPermanent; } else { if (!ctxTransient) { ctxTransient = duk_create_heap_default(); if (!ctxTransient) return FAILRULE_BIT; // unable to init it } ctx = ctxTransient; } char word[MAX_WORD_SIZE]; definition = ReadCompiledWord(definition,word); // is it a call? call test string int char name[MAX_WORD_SIZE]; *name = 0; char returnType[MAX_WORD_SIZE]; char* callbase = NULL; char* code = definition; if (!stricmp(word,"call")) // skip over the description for now { definition = ReadCompiledWord(definition,returnType); definition = ReadCompiledWord(definition,name); ReadCompiledWord(definition,word); // arg type there? callbase = definition; // start of arguments list code = definition; while (!stricmp(word,"string") || !stricmp(word,"int") || !stricmp(word,"float")) { code = definition; // start of arguments list definition = ReadCompiledWord(definition,word); } } // compile requirements - execute the code definition if not inited bool compile = false; if (!stricmp(word,"compile")) { char* ptr = ReadCompiledWord(code,word); compile = true; // compile vs eval if (!*ptr) return FAILRULE_BIT; // require some code } else if (!stricmp(word,"eval")) { char* ptr = ReadCompiledWord(code, word); if (!*ptr) return FAILRULE_BIT; // require some code } else if (!*name) return FAILRULE_BIT; // need to define someting, be it a compile or a call char* terminator = strchr(code,'`'); *terminator = 0; // hide this from javascript if (*code && !inited) // code was supplied, handle it if not yet executed { *defstart = '.'; char file[SMALL_WORD_SIZE]; ReadCompiledWord(code,file); if (!stricmp(file,"file")) // read files { while ((code = ReadCompiledWord(code,file)) != NULL && !stricmp(file,"file")) { code = ReadCompiledWord(code,file); // name char* filename = file; if (file[0] == '"') { size_t len = strlen(file); file[len-1] = 0; ++filename; } if (!compile) duk_eval_file(ctx, filename); else duk_compile_file(ctx, 0, filename); duk_pop(ctx); } } else { if (!compile) duk_eval_string(ctx, (const char *)code); // execute the definition else duk_compile_string(ctx, 0, (const char *)code); // compile the definition duk_pop(ctx); /* pop result/error */ } } // now do a call, if one should be done if (*name) { // Map a JS print() function to the function that can use the CS logger duk_push_c_function(ctx, native_log, 1); duk_put_global_string(ctx, "log"); duk_push_global_object(ctx); int found = (int) duk_get_prop_string(ctx, -1 /*index*/, name); // find the function if (!found) { duk_pop(ctx); // discard context *terminator = '`'; return FAILRULE_BIT; } unsigned int index = 0; FunctionResult result = NOPROBLEM_BIT; while (index < args) { char type[MAX_WORD_SIZE]; *buffer = 0; if ((result = JavascriptArgEval(index,buffer)) != NOPROBLEM_BIT) { for (unsigned int i = 0; i < index; ++i) duk_pop(ctx); // discard saved args duk_pop(ctx); // discard context *terminator = '`'; return FAILRULE_BIT; } callbase = ReadCompiledWord(callbase,type); if (!stricmp(type,"string")) { duk_push_string(ctx, buffer); } else if (!stricmp(type,"int" )) { if (!(*buffer >= '0' && *buffer <= '9') && *buffer != '-' && *buffer != '+') { result = FAILRULE_BIT; break; } duk_push_int(ctx, atoi(buffer)); } else if (!stricmp(type,"float" )) { if (!(*buffer >= '0' && *buffer <= '9') && *buffer != '-' && *buffer != '+' && *buffer != '.') { result = FAILRULE_BIT; break; } duk_push_number(ctx, (double)atof(buffer)); } else break; ++index; } *buffer = 0; if (result != NOPROBLEM_BIT) // abandon the call { for (unsigned int i = 0; i < index; ++i) duk_pop(ctx); // discard saved args duk_pop(ctx); // discard context *terminator = '`'; return FAILRULE_BIT; } if (duk_pcall(ctx, args) != 0) // call failed { printf("Javascript Error: %s\r\n", duk_safe_to_string(ctx, -1)); duk_pop_n(ctx, 2); // have remove global object and thr function return/error val *terminator = '`'; return FAILRULE_BIT; } else { if (!stricmp(returnType,"string")) { strcpy(buffer,duk_safe_to_string(ctx, -1)); // assumes there is a return string! if (strchr(buffer,'\n') || strchr(buffer,'\r') || strchr(buffer,'\t')) ChangeSpecial(buffer); // do not allow special characters in string } else if (!stricmp(returnType,"int")) strcpy(buffer,duk_safe_to_string(ctx, -1)); // assumes there is a return string! else if (!stricmp(returnType,"float")) strcpy(buffer,duk_safe_to_string(ctx, -1)); // assumes there is a return string! duk_pop_n(ctx, 2); // have remove global object and thr function return/error val *terminator = '`'; return NOPROBLEM_BIT; } } *terminator = '`'; return NOPROBLEM_BIT; #else return FAILRULE_BIT; // if javascript not compiled into engine #endif } void DeletePermanentJavaScript() { #ifndef DISCARDJAVASCRIPT if (ctxPermanent) { duk_destroy_heap(ctxPermanent); ctxPermanent = NULL; } #endif } void DeleteTransientJavaScript() { #ifndef DISCARDJAVASCRIPT if (ctxTransient) { duk_destroy_heap(ctxTransient); ctxTransient = NULL; } #endif }
[ "gowilcox@gmail.com" ]
gowilcox@gmail.com
4de3bc22a07266b07efaeef29f0cbf21761e51bf
13b4773b8815e8b88873d9480b98f72eabec7f7d
/Vetor/idade e altura de N pessoas.cpp
e03e0f0c69e7b3c396f77529f74aa87e56d80be3
[]
no_license
George100Neres/Logica-de-Programacao
ed9139c2d3d6515b14cc51e90792ee8b655e40cb
69941edeb489cad5cad272d05735d22fdf6cf602
refs/heads/main
2023-01-05T14:31:56.772829
2020-10-31T02:34:42
2020-10-31T02:34:42
308,498,768
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,428
cpp
/*Fazer um programa para ler nome, idade e altura de N pessoas,conforme o exemplo.Depois,mostrar na tela a altura média das pessoas, e mostrar também a porcentagem de pessoas com menos de 16 anos,bem como o nome dessas pessoas se caso houver.*/ #include<stdio.h> #include<string.h> int main() { int N,menores; char nomes[N] [50]; // Vetor de N posiçoes,onde cada posição será um vetor de 50 char. double alturas[N]; double soma,media,percentualMenores; int idades[N]; printf("Quantas pessoas serao digitadas:?"); scanf("%d",&N); for(int i=0; i<N; i++){ printf("Nome: "); fseek (stdin, 0,SEEK_END); gets(nomes[i]); printf("Idades:"); scanf("%d", &idades[i]); printf("Altura: "); scanf("%f", &alturas[i]); } soma =0; for(int i=0; i<N; i++){ soma = soma + alturas[i]; } media = media / N; printf("Altura media %.2f",media); menores =0; for(int i=0; i<N; i++){ if(idades [i] < 16){ menores++; } } // Aplica-se uma regra de três N - 100% // Cont - x% percentualMenores = menores * 100.0 / N; printf("Pessoas com menos de 16 anos: %.1f %%\n",percentualMenores); // No C,para poder printar o sinal de porcetagem,temos que colocar 2%, um so apenas para placeholer.*/ for(int i=0; i<N; i++){ if(idades [i] < 16){ printf("Nomes: %s\n",nomes[i]); } } }
[ "george.neres100@gmail.com" ]
george.neres100@gmail.com
a29c955197467c0f30a1c8c7f87a926b012af896
3e69d118ffc0a4745290b2440c4404df53768692
/src/qt/sendcoinsdialog.cpp
2f3eee16949d6e4190dc8573858fec86d9cb085b
[ "MIT" ]
permissive
mafacoin/debugging-ico-file
736755b2f800bce60d6ef15ff1347e909717499e
3939f589183aca5a463050210ab102004ef67f96
refs/heads/master
2021-05-02T15:40:31.911786
2018-02-08T02:45:24
2018-02-08T02:45:24
120,700,311
0
0
null
null
null
null
UTF-8
C++
false
false
18,545
cpp
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "init.h" #include "walletmodel.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "guiutil.h" #include "askpassphrasedialog.h" #include "coincontrol.h" #include "coincontroldialog.h" #include <QMessageBox> #include <QTextDocument> #include <QScrollBar> #include <QClipboard> SendCoinsDialog::SendCoinsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SendCoinsDialog), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->lineEditCoinControlChange->setPlaceholderText(tr("Enter a MafaCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)")); #endif addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control ui->lineEditCoinControlChange->setFont(GUIUtil::bitcoinAddressFont()); connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int))); connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString &)), this, SLOT(coinControlChangeEdited(const QString &))); // Coin Control: clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); fNewRecipientAllowed = true; } void SendCoinsDialog::setModel(WalletModel *model) { this->model = model; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setModel(model); } } if(model && model->getOptionsModel()) { setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // Coin Control connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool))); connect(model->getOptionsModel(), SIGNAL(transactionFeeChanged(qint64)), this, SLOT(coinControlUpdateLabels())); ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures()); coinControlUpdateLabels(); } } SendCoinsDialog::~SendCoinsDialog() { delete ui; } void SendCoinsDialog::on_sendButton_clicked() { QList<SendCoinsRecipient> recipients; bool valid = true; if(!model) return; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { if(entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if(!valid || recipients.isEmpty()) { return; } // Format confirmation message QStringList formatted; foreach(const SendCoinsRecipient &rcp, recipients) { #if QT_VERSION < 0x050000 formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address)); #else formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), rcp.label.toHtmlEscaped(), rcp.address)); #endif } fNewRecipientAllowed = false; QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { fNewRecipientAllowed = true; return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; return; } WalletModel::SendCoinsReturn sendstatus; if (!model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) sendstatus = model->sendCoins(recipients); else sendstatus = model->sendCoins(recipients, CoinControlDialog::coinControl); switch(sendstatus.status) { case WalletModel::InvalidAddress: QMessageBox::warning(this, tr("Send Coins"), tr("The recipient address is not valid, please recheck."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::InvalidAmount: QMessageBox::warning(this, tr("Send Coins"), tr("The amount to pay must be larger than 0."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The amount exceeds your balance."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountWithFeeExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The total exceeds your balance when the %1 transaction fee is included."). arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::DuplicateAddress: QMessageBox::warning(this, tr("Send Coins"), tr("Duplicate address found, can only send to each address once per send operation."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCreationFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: Transaction creation failed!"), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCommitFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::Aborted: // User aborted, nothing to do break; case WalletModel::OK: accept(); CoinControlDialog::coinControl->UnSelectAll(); coinControlUpdateLabels(); break; } fNewRecipientAllowed = true; } void SendCoinsDialog::clear() { // Remove entries until only one left while(ui->entries->count()) { ui->entries->takeAt(0)->widget()->deleteLater(); } addEntry(); updateRemoveEnabled(); ui->sendButton->setDefault(true); } void SendCoinsDialog::reject() { clear(); } void SendCoinsDialog::accept() { clear(); } SendCoinsEntry *SendCoinsDialog::addEntry() { SendCoinsEntry *entry = new SendCoinsEntry(this); entry->setModel(model); ui->entries->addWidget(entry); connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*))); connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels())); updateRemoveEnabled(); // Focus the field, so that entry can start immediately entry->clear(); entry->setFocus(); ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); qApp->processEvents(); QScrollBar* bar = ui->scrollArea->verticalScrollBar(); if(bar) bar->setSliderPosition(bar->maximum()); return entry; } void SendCoinsDialog::updateRemoveEnabled() { // Remove buttons are enabled as soon as there is more than one send-entry bool enabled = (ui->entries->count() > 1); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setRemoveEnabled(enabled); } } setupTabChain(0); coinControlUpdateLabels(); } void SendCoinsDialog::removeEntry(SendCoinsEntry* entry) { entry->deleteLater(); updateRemoveEnabled(); } QWidget *SendCoinsDialog::setupTabChain(QWidget *prev) { for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { prev = entry->setupTabChain(prev); } } QWidget::setTabOrder(prev, ui->addButton); QWidget::setTabOrder(ui->addButton, ui->sendButton); return ui->sendButton; } void SendCoinsDialog::setAddress(const QString &address) { SendCoinsEntry *entry = 0; // Replace the first entry if it is still unused if(ui->entries->count() == 1) { SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if(first->isClear()) { entry = first; } } if(!entry) { entry = addEntry(); } entry->setAddress(address); } void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv) { if(!fNewRecipientAllowed) return; SendCoinsEntry *entry = 0; // Replace the first entry if it is still unused if(ui->entries->count() == 1) { SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if(first->isClear()) { entry = first; } } if(!entry) { entry = addEntry(); } entry->setValue(rv); } bool SendCoinsDialog::handleURI(const QString &uri) { SendCoinsRecipient rv; // URI has to be valid if (GUIUtil::parseBitcoinURI(uri, &rv)) { CBitcoinAddress address(rv.address.toStdString()); if (!address.IsValid()) return false; pasteEntry(rv); return true; } return false; } void SendCoinsDialog::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance) { Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); if(!model || !model->getOptionsModel()) return; int unit = model->getOptionsModel()->getDisplayUnit(); ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); } void SendCoinsDialog::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update labelBalance with the current balance and the current unit ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance())); } } // Coin Control: copy label "Quantity" to clipboard void SendCoinsDialog::coinControlClipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void SendCoinsDialog::coinControlClipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: copy label "Fee" to clipboard void SendCoinsDialog::coinControlClipboardFee() { GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" "))); } // Coin Control: copy label "After fee" to clipboard void SendCoinsDialog::coinControlClipboardAfterFee() { GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" "))); } // Coin Control: copy label "Bytes" to clipboard void SendCoinsDialog::coinControlClipboardBytes() { GUIUtil::setClipboard(ui->labelCoinControlBytes->text()); } // Coin Control: copy label "Priority" to clipboard void SendCoinsDialog::coinControlClipboardPriority() { GUIUtil::setClipboard(ui->labelCoinControlPriority->text()); } // Coin Control: copy label "Low output" to clipboard void SendCoinsDialog::coinControlClipboardLowOutput() { GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text()); } // Coin Control: copy label "Change" to clipboard void SendCoinsDialog::coinControlClipboardChange() { GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" "))); } // Coin Control: settings menu - coin control enabled/disabled by user void SendCoinsDialog::coinControlFeatureChanged(bool checked) { ui->frameCoinControl->setVisible(checked); if (!checked && model) // coin control features disabled CoinControlDialog::coinControl->SetNull(); } // Coin Control: button inputs -> show actual coin control dialog void SendCoinsDialog::coinControlButtonClicked() { CoinControlDialog dlg; dlg.setModel(model); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: checkbox custom change address void SendCoinsDialog::coinControlChangeChecked(int state) { if (model) { if (state == Qt::Checked) CoinControlDialog::coinControl->destChange = CBitcoinAddress(ui->lineEditCoinControlChange->text().toStdString()).Get(); else CoinControlDialog::coinControl->destChange = CNoDestination(); } ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked)); ui->labelCoinControlChangeLabel->setVisible((state == Qt::Checked)); } // Coin Control: custom change address changed void SendCoinsDialog::coinControlChangeEdited(const QString & text) { if (model) { CoinControlDialog::coinControl->destChange = CBitcoinAddress(text.toStdString()).Get(); // label for the change address ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}"); if (text.isEmpty()) ui->labelCoinControlChangeLabel->setText(""); else if (!CBitcoinAddress(text.toStdString()).IsValid()) { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("Warning: Invalid Bitcoin address")); } else { QString associatedLabel = model->getAddressTableModel()->labelForAddress(text); if (!associatedLabel.isEmpty()) ui->labelCoinControlChangeLabel->setText(associatedLabel); else { CPubKey pubkey; CKeyID keyid; CBitcoinAddress(text.toStdString()).GetKeyID(keyid); if (model->getPubKey(keyid, pubkey)) ui->labelCoinControlChangeLabel->setText(tr("(no label)")); else { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("Warning: Unknown change address")); } } } } } // Coin Control: update labels void SendCoinsDialog::coinControlUpdateLabels() { if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) CoinControlDialog::payAmounts.append(entry->getValue().amount); } if (CoinControlDialog::coinControl->HasSelected()) { // actual coin control calculation CoinControlDialog::updateLabels(model, this); // show coin control stats ui->labelCoinControlAutomaticallySelected->hide(); ui->widgetCoinControl->show(); } else { // hide coin control stats ui->labelCoinControlAutomaticallySelected->show(); ui->widgetCoinControl->hide(); ui->labelCoinControlInsuffFunds->hide(); } }
[ "tsweeney1471@gmail.com" ]
tsweeney1471@gmail.com
f8498f3545188a9bc65ac24126ebe27a40229f23
cb77dcbbce6c480f68c3dcb8610743f027bee95c
/android/art/runtime/gc/space/image_space.h
3383d6b383dc855f8655ae82dea7b8f1de6f5330
[ "MIT", "Apache-2.0", "NCSA" ]
permissive
fengjixuchui/deoptfuscator
c888b93361d837ef619b9eb95ffd4b01a4bef51a
dec8fbf2b59f8dddf2dbd10868726b255364e1c5
refs/heads/master
2023-03-17T11:49:00.988260
2023-03-09T02:01:47
2023-03-09T02:01:47
333,074,914
0
0
MIT
2023-03-09T02:01:48
2021-01-26T12:16:31
null
UTF-8
C++
false
false
8,886
h
/* * Copyright (C) 2011 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 ART_RUNTIME_GC_SPACE_IMAGE_SPACE_H_ #define ART_RUNTIME_GC_SPACE_IMAGE_SPACE_H_ #include "arch/instruction_set.h" #include "gc/accounting/space_bitmap.h" #include "image.h" #include "space.h" namespace art { class OatFile; namespace gc { namespace space { // An image space is a space backed with a memory mapped image. class ImageSpace : public MemMapSpace { public: SpaceType GetType() const { return kSpaceTypeImageSpace; } // Load boot image spaces from a primary image file for a specified instruction set. // // On successful return, the loaded spaces are added to boot_image_spaces (which must be // empty on entry) and oat_file_end is updated with the (page-aligned) end of the last // oat file. static bool LoadBootImage(const std::string& image_file_name, const InstructionSet image_instruction_set, std::vector<space::ImageSpace*>* boot_image_spaces, uint8_t** oat_file_end) REQUIRES_SHARED(Locks::mutator_lock_); // Try to open an existing app image space. static std::unique_ptr<ImageSpace> CreateFromAppImage(const char* image, const OatFile* oat_file, std::string* error_msg) REQUIRES_SHARED(Locks::mutator_lock_); // Reads the image header from the specified image location for the // instruction set image_isa. Returns null on failure, with // reason in error_msg. static ImageHeader* ReadImageHeader(const char* image_location, InstructionSet image_isa, std::string* error_msg); // Give access to the OatFile. const OatFile* GetOatFile() const; // Releases the OatFile from the ImageSpace so it can be transfer to // the caller, presumably the OatFileManager. std::unique_ptr<const OatFile> ReleaseOatFile(); void VerifyImageAllocations() REQUIRES_SHARED(Locks::mutator_lock_); const ImageHeader& GetImageHeader() const { return *reinterpret_cast<ImageHeader*>(Begin()); } // Actual filename where image was loaded from. // For example: /data/dalvik-cache/arm/system@framework@boot.art const std::string GetImageFilename() const { return GetName(); } // Symbolic location for image. // For example: /system/framework/boot.art const std::string GetImageLocation() const { return image_location_; } accounting::ContinuousSpaceBitmap* GetLiveBitmap() const OVERRIDE { return live_bitmap_.get(); } accounting::ContinuousSpaceBitmap* GetMarkBitmap() const OVERRIDE { // ImageSpaces have the same bitmap for both live and marked. This helps reduce the number of // special cases to test against. return live_bitmap_.get(); } void Dump(std::ostream& os) const; // Sweeping image spaces is a NOP. void Sweep(bool /* swap_bitmaps */, size_t* /* freed_objects */, size_t* /* freed_bytes */) { } bool CanMoveObjects() const OVERRIDE { return false; } // Returns the filename of the image corresponding to // requested image_location, or the filename where a new image // should be written if one doesn't exist. Looks for a generated // image in the specified location and then in the dalvik-cache. // // Returns true if an image was found, false otherwise. static bool FindImageFilename(const char* image_location, InstructionSet image_isa, std::string* system_location, bool* has_system, std::string* data_location, bool* dalvik_cache_exists, bool* has_data, bool *is_global_cache); // Use the input image filename to adapt the names in the given boot classpath to establish // complete locations for secondary images. static void ExtractMultiImageLocations(const std::string& input_image_file_name, const std::string& boot_classpath, std::vector<std::string>* image_filenames); static std::string GetMultiImageBootClassPath(const std::vector<const char*>& dex_locations, const std::vector<const char*>& oat_filenames, const std::vector<const char*>& image_filenames); // Returns true if the dex checksums in the given oat file match the // checksums of the original dex files on disk. This is intended to be used // to validate the boot image oat file, which may contain dex entries from // multiple different (possibly multidex) dex files on disk. Prefer the // OatFileAssistant for validating regular app oat files because the // OatFileAssistant caches dex checksums that are reused to check both the // oat and odex file. // // This function is exposed for testing purposes. static bool ValidateOatFile(const OatFile& oat_file, std::string* error_msg); // Return the end of the image which includes non-heap objects such as ArtMethods and ArtFields. uint8_t* GetImageEnd() const { return Begin() + GetImageHeader().GetImageSize(); } // Return the start of the associated oat file. uint8_t* GetOatFileBegin() const { return GetImageHeader().GetOatFileBegin(); } // Return the end of the associated oat file. uint8_t* GetOatFileEnd() const { return GetImageHeader().GetOatFileEnd(); } void DumpSections(std::ostream& os) const; // De-initialize the image-space by undoing the effects in Init(). virtual ~ImageSpace(); protected: // Tries to initialize an ImageSpace from the given image path, returning null on error. // // If validate_oat_file is false (for /system), do not verify that image's OatFile is up-to-date // relative to its DexFile inputs. Otherwise (for /data), validate the inputs and generate the // OatFile in /data/dalvik-cache if necessary. If the oat_file is null, it uses the oat file from // the image. static std::unique_ptr<ImageSpace> Init(const char* image_filename, const char* image_location, bool validate_oat_file, const OatFile* oat_file, std::string* error_msg) REQUIRES_SHARED(Locks::mutator_lock_); static Atomic<uint32_t> bitmap_index_; std::unique_ptr<accounting::ContinuousSpaceBitmap> live_bitmap_; ImageSpace(const std::string& name, const char* image_location, MemMap* mem_map, accounting::ContinuousSpaceBitmap* live_bitmap, uint8_t* end); // The OatFile associated with the image during early startup to // reserve space contiguous to the image. It is later released to // the ClassLinker during it's initialization. std::unique_ptr<OatFile> oat_file_; // There are times when we need to find the boot image oat file. As // we release ownership during startup, keep a non-owned reference. const OatFile* oat_file_non_owned_; const std::string image_location_; friend class ImageSpaceLoader; friend class Space; private: // Create a boot image space from an image file for a specified instruction // set. Cannot be used for future allocation or collected. // // Create also opens the OatFile associated with the image file so // that it be contiguously allocated with the image before the // creation of the alloc space. The ReleaseOatFile will later be // used to transfer ownership of the OatFile to the ClassLinker when // it is initialized. static std::unique_ptr<ImageSpace> CreateBootImage(const char* image, InstructionSet image_isa, bool secondary_image, std::string* error_msg) REQUIRES_SHARED(Locks::mutator_lock_); DISALLOW_COPY_AND_ASSIGN(ImageSpace); }; } // namespace space } // namespace gc } // namespace art #endif // ART_RUNTIME_GC_SPACE_IMAGE_SPACE_H_
[ "gyoonus@gmail.com" ]
gyoonus@gmail.com
148138d406ab4c21fe2c3c68fc8fa01248056c11
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/tcss/src/v20201101/model/DescribeSecLogDeliveryKafkaSettingRequest.cpp
3c0b930e1ada6a0c0627d84011d9e61869b0b783
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp
9f5df8220eaaf72f7eaee07b2ede94f89313651f
42a76b812b81d1b52ec6a217fafc8faa135e06ca
refs/heads/master
2023-08-30T03:22:45.269556
2023-08-30T00:45:39
2023-08-30T00:45:39
188,991,963
55
37
Apache-2.0
2023-08-17T03:13:20
2019-05-28T08:56:08
C++
UTF-8
C++
false
false
1,426
cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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. */ #include <tencentcloud/tcss/v20201101/model/DescribeSecLogDeliveryKafkaSettingRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Tcss::V20201101::Model; using namespace std; DescribeSecLogDeliveryKafkaSettingRequest::DescribeSecLogDeliveryKafkaSettingRequest() { } string DescribeSecLogDeliveryKafkaSettingRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); }
[ "tencentcloudapi@tencent.com" ]
tencentcloudapi@tencent.com
d2f1e866efe54f74b8de2ac220ecf183d49a1cde
fd4103e6f5116c776249b00171d8639313f05bc1
/Src/PartModeler/PmException.cpp
02b5743ed0a2e0e491bbc806b0fa16b2791185ee
[]
no_license
Wanghuaichen/TransCAD
481f3b4e54cc066dde8679617a5b32ac2041911b
35ca89af456065925984492eb23a0543e3125bb8
refs/heads/master
2020-03-25T03:54:51.488397
2018-06-25T17:38:39
2018-06-25T17:38:39
143,367,529
2
1
null
2018-08-03T02:30:03
2018-08-03T02:30:03
null
UTF-8
C++
false
false
196
cpp
#include "StdAfx.h" #include ".\pmexception.h" PmException::PmException(void) { } PmException::PmException(const CString & message) : m_message(message) { } PmException::~PmException(void) { }
[ "kyk5415@gmail.com" ]
kyk5415@gmail.com
83b6823e3ed2965f67d2675d687a050b873375b0
c97fc4f7305cc6ac3cc34d0564840feaf24c5d51
/Ingresar_dos_numeros.cpp
587be026e9f4d6d5f5a101eaa192d2354941f8b9
[]
no_license
marialejamaap/Class-examples
f36371040e0152dbdd8592e0f13199c1b9f4ef44
924d562727412466b32bd92ad1f94823d60f7803
refs/heads/master
2020-03-26T18:47:37.200324
2018-10-23T07:12:48
2018-10-23T07:12:48
145,231,207
0
0
null
null
null
null
UTF-8
C++
false
false
950
cpp
// El programa consiste en ingresar dos numeros e imprimirlos en consola /* Objetivos: Nombrar variables, asignar variables, utilizar elementos de entrada y salida*/ #include <stdlib.h> #include <iostream> using namespace std;// evita escribir los elementos del espacio de nombres std::<elemento> int main() { int num1, num2; // defino variables tipo entero(int) y las nombro(num1, num2); cout<<" \t\t Enter two numbers " <<endl; cout <<" number 1: "; cin>>num1; cout << " number 2: "; cin>>num2; system("cls"); // limpia lo que hay en consola (este elementos va en librería stdlib.h) cout<<" The numbers are: " <<num1 <<" and " <<num2;//imprima los números ingresados en consola cout<<endl<<endl; // imprima dos saltos de línea return 0; // retorno de función principal a 0 } /*para flotantes o numeros más grandes que ocupen más cantidad de memoria sólo es cambiar el tipo de dato de las variables num*/
[ "noreply@github.com" ]
noreply@github.com
1142af3d24b7044fcbba255131427ddf4776ba09
b9ee68d627e37a028331a4aa321c732e6981eb69
/AbstractVM/src/Vm/Instruction/InstructionMul.cpp
ea1d1eeef643baa08ed4d187ad110fb9a1c0fc06
[]
no_license
cpaille/Assembleur
8b09a6b5192cc731ded19da2dc2242cfa1190f89
730832608962f9b1f8f693030cf76e4d4ecee2d7
refs/heads/master
2020-04-15T16:33:36.741562
2013-02-15T15:45:57
2013-02-15T15:45:57
7,080,482
1
0
null
null
null
null
UTF-8
C++
false
false
349
cpp
#include "InstructionMul.hh" InstructionMul::InstructionMul() { } InstructionMul::~InstructionMul() { } void InstructionMul::execute() { PileInterface * pile = AbstractVM::getInstance()->getPile(); OperandInterface * first = pile->get(); pile->pop(); OperandInterface * second = pile->get(); pile->pop(); pile->push(*first * *second); }
[ "c.paille@orange.fr" ]
c.paille@orange.fr
cf64ce425a637a6a0ffcc785f685191b49950114
513019c48e5a35a5558a382b3739fef6da183968
/DreamsDontWorkUnlessYouDo/hungry/prob1.1/prob1.1/bitvector.cpp
f7fb343df612f1a04ecdff5ca0efcf884b04a6d9
[]
no_license
gvp-yamini/DataStructuresAlgorithms
a06aa0ecea3d05b5bdee8afcbda578af00a17c07
5078fef48256546711e13b7d3934cd5bdbae7bb9
refs/heads/master
2021-01-18T17:27:17.601528
2019-06-27T14:19:16
2019-06-27T14:19:16
68,348,101
0
0
null
null
null
null
UTF-8
C++
false
false
854
cpp
// prob1.1.cpp : Defines the entry point for the console application. //Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures? #include "stdafx.h" #include "stdio.h" #include "conio.h" #include "malloc.h" int isUniqueString(char *,int ); int _tmain(int argc, _TCHAR* argv[]) { int len,j,i=0; char *arr; printf("enter number of characters of a string\n"); scanf_s("%d",&len); arr = (char *)malloc((len+1)*sizeof(char )); printf("enter string\n"); for(i=0;i<len;i++) { arr[i]=getc(stdin); } arr[len]='\0'; printf("inserted string is"); for(i=0;i<len;i++){ printf("%c",arr[i]); } printf("\n"); if(isUniqueString(arr,len)) { printf("unique string"); }else{ printf("contains duplicates"); } getch(); return 0; } int isUniqueString(char *arr,int len){ }
[ "KH1924@KH1924.kitspl.com" ]
KH1924@KH1924.kitspl.com
d96adfd9edd17aa1aa27c0e2cd3b467f7024b159
bc8fa0fedbd1ba13380e90cf17c356175b02f9fe
/src/linear_allocator.cpp
98441c8715e599c10673e3fe8626c9e2caf9d058
[]
no_license
jdryg/jx
f191b14082eff3afccc0cf6329247dfff5c1d2b1
611d3ad717caaf16d268873da869066eb71bba27
refs/heads/master
2023-07-08T07:20:59.716447
2023-06-22T05:52:50
2023-06-22T05:52:50
220,175,137
1
1
null
null
null
null
UTF-8
C++
false
false
2,919
cpp
#include <jx/linear_allocator.h> #include <jx/sys.h> namespace jx { static const uint32_t kLinearAllocatorChunkAlignment = 16; inline uint32_t alignSize(uint32_t sz, uint32_t alignment) { JX_CHECK(bx::isPowerOf2<uint32_t>(alignment), "Invalid alignment value"); const uint32_t mask = alignment - 1; return (sz & (~mask)) + ((sz & mask) != 0 ? alignment : 0); } LinearAllocator::LinearAllocator(bx::AllocatorI* parentAllocator, uint32_t minChunkSize) : m_ParentAllocator(parentAllocator) , m_ChunkListHead(nullptr) , m_ChunkListTail(nullptr) , m_CurChunk(nullptr) , m_MinChunkSize(minChunkSize) { JX_CHECK(bx::isPowerOf2(m_MinChunkSize), "Linear allocator chunk size should be a power of 2"); } LinearAllocator::~LinearAllocator() { Chunk* c = m_ChunkListHead; while (c) { Chunk* next = c->m_Next; BX_ALIGNED_FREE(m_ParentAllocator, c, kLinearAllocatorChunkAlignment); c = next; } m_ChunkListHead = nullptr; m_ChunkListTail = nullptr; m_CurChunk = nullptr; } void* LinearAllocator::realloc(void* _ptr, size_t _size, size_t _align, const char* _file, uint32_t _line) { BX_UNUSED(_file, _line); JX_CHECK(!_ptr || (_ptr && !_size), "LinearAllocator doesn't support reallocations"); _align = bx::max<size_t>(_align, (size_t)8); if (_ptr) { // // Reallocation (unsupported) or Free (ignore) return nullptr; } while (m_CurChunk) { void* ptr = allocFromChunk(m_CurChunk, _size, _align); if (ptr != nullptr) { return ptr; } m_CurChunk = m_CurChunk->m_Next; } // Allocate new chunk. const uint32_t chunkCapacity = alignSize((uint32_t)_size, m_MinChunkSize); const uint32_t totalMemory = 0 + alignSize(sizeof(Chunk), kLinearAllocatorChunkAlignment) + chunkCapacity ; uint8_t* mem = (uint8_t*)BX_ALIGNED_ALLOC(m_ParentAllocator, totalMemory, kLinearAllocatorChunkAlignment); if (mem == nullptr) { // Failed to allocate new chunk. return nullptr; } Chunk* c = (Chunk*)mem; mem += alignSize(sizeof(Chunk), kLinearAllocatorChunkAlignment); c->m_Buffer = mem; mem += chunkCapacity; c->m_Capacity = chunkCapacity; c->m_Offset = 0; c->m_Next = nullptr; if (m_ChunkListHead == nullptr) { JX_CHECK(m_ChunkListTail == nullptr, "Invalid LinearAllocator state"); m_ChunkListHead = c; m_ChunkListTail = c; } else if (m_ChunkListTail != nullptr) { m_ChunkListTail->m_Next = c; } m_CurChunk = c; return allocFromChunk(m_CurChunk, _size, _align); } void LinearAllocator::freeAll() { Chunk* c = m_ChunkListHead; while (c != nullptr) { c->m_Offset = 0; c = c->m_Next; } m_CurChunk = m_ChunkListHead; } void* LinearAllocator::allocFromChunk(Chunk* c, size_t size, size_t align) { uintptr_t offset = (uintptr_t)bx::alignPtr(c->m_Buffer + c->m_Offset, 0, align) - (uintptr_t)c->m_Buffer; if (offset + size > c->m_Capacity) { return nullptr; } void* ptr = &c->m_Buffer[offset]; c->m_Offset = (uint32_t)(offset + size); return ptr; } }
[ "makingartstudios@gmail.com" ]
makingartstudios@gmail.com
c9a604cdf0ed03b13daf3d73c01510ccbcd09e0d
4d408971c07fcc1bec5e3120109713bf4da11581
/Token/TokenTester.cpp
21624eae8838815e003d10012a1224f2eaf64f4a
[]
no_license
chulchultrain/FactoryHead
c108f3dcda4ed44a7b74b32ffcf4ba1fdbab1353
01362c1cc41a73156e9e896df848eb70ad295675
refs/heads/master
2020-05-21T23:51:44.620899
2018-01-04T05:47:14
2018-01-04T05:47:14
63,737,643
2
0
null
2017-05-25T18:27:32
2016-07-20T00:44:32
C++
UTF-8
C++
false
false
1,036
cpp
#include <Token/Token.h> #include <iostream> #include <stdlib.h> #include <map> #include <cassert> #include <vector> using namespace std; /* Token Test Function. Will test the constructor and whether the proper values can be retrieved from the class instance. Types(as specified by the enum in the header file): NONE,TYPE, NAME, MOVE, ROUND Can have values of empty and non-empty strings. Non-empty have a space */ void TokenUnitTest() { Token a("TYPE","FIRE"); assert(a.getTokenType() == Token::TYPE && a.getVal() == "FIRE" && "1"); Token b("NONE","WATER"); assert(b.getTokenType() == Token::NONE && b.getVal() == "WATER" && "2"); Token c("NAME","MOVE"); assert(c.getTokenType() == Token::NAME && c.getVal() == "MOVE" && "3"); Token d("MOVE","Flamethrower"); assert(d.getTokenType() == Token::MOVE && d.getVal() == "Flamethrower" && "4"); Token e("ROUND","Solar Beam"); assert(e.getTokenType() == Token::ROUND && e.getVal() == "Solar Beam" && "5"); } int main() { TokenUnitTest(); return 0; }
[ "yangchulmin0@gmail.com" ]
yangchulmin0@gmail.com
57e9d58798d335c156386427ae01cacb807d13fe
5d2a8af9709af1b6e3db40eace44cdfea59df208
/frameworks/runtime-src/Classes/BlockEngine/BlockTessellators.cpp
00aab04bf4b5697130b6289426b0e0ba21209a0b
[]
no_license
tatfook/ParaCraftMobile
a714a2566fa5c83f675472fc5d6df440b27aafa1
072b53957d2a83808ee10fc99e746257e83a4d9a
refs/heads/master
2021-01-20T08:57:16.049744
2017-07-03T03:49:12
2017-07-03T03:49:12
90,208,741
6
3
null
null
null
null
UTF-8
C++
false
false
23,142
cpp
//----------------------------------------------------------------------------- // Class: All kinds of block tessellation // Authors: LiXizhi // Emails: LiXizhi@yeah.net // Company: ParaEngine // Date: 2014.12.22 //----------------------------------------------------------------------------- #include "ParaEngine.h" #include "BlockModel.h" #include "BlockCommon.h" #include "VertexFVF.h" #include "BlockChunk.h" #include "BlockRegion.h" #include "BlockWorld.h" #include "VertexFVF.h" #include "BlockTessellators.h" using namespace ParaEngine; ParaEngine::BlockTessellatorBase::BlockTessellatorBase(CBlockWorld* pWorld) : m_pWorld(pWorld), m_pCurBlockTemplate(0), m_pCurBlockModel(0), m_blockId_ws(0, 0, 0), m_nBlockData(0), m_pChunk(0), m_blockId_cs(0,0,0) { memset(neighborBlocks, 0, sizeof(neighborBlocks)); } void ParaEngine::BlockTessellatorBase::SetWorld(CBlockWorld* pWorld) { if (m_pWorld != pWorld) { m_pWorld = pWorld; } } int32 ParaEngine::BlockTessellatorBase::TessellateBlock(BlockChunk* pChunk, uint16 packedBlockId, BlockRenderMethod dwShaderID, BlockVertexCompressed** pOutputData) { return 0; } int32_t ParaEngine::BlockTessellatorBase::GetMaxVertexLight(int32_t v1, int32_t v2, int32_t v3, int32_t v4) { int32_t max1 = Math::Max(v1, v2); int32_t max2 = Math::Max(v3, v4); return Math::Max(max1, max2); } uint8 ParaEngine::BlockTessellatorBase::GetMeshBrightness(BlockTemplate * pBlockTemplate, uint8* blockBrightness) { uint8 centerLightness = blockBrightness[rbp_center]; if (centerLightness > 0 && pBlockTemplate->GetLightOpacity() > 1) return Math::Min(centerLightness + pBlockTemplate->GetLightOpacity(), 15); else return Math::Max(Math::Max(Math::Max(Math::Max(Math::Max(Math::Max(centerLightness, blockBrightness[rbp_nX]), blockBrightness[rbp_pX]), blockBrightness[rbp_nZ]), blockBrightness[rbp_pZ]), blockBrightness[rbp_pY]), blockBrightness[rbp_nY]); } int32_t ParaEngine::BlockTessellatorBase::GetAvgVertexLight(int32_t v1, int32_t v2, int32_t v3, int32_t v4) { if ((v2 > 0 || v3 > 0)) { int32_t max1 = Math::Max(v1, v2); int32_t max2 = Math::Max(v3, v4); return Math::Max(max1, max2); } else { return v1; } } bool ParaEngine::BlockTessellatorBase::UpdateCurrentBlock(BlockChunk* pChunk, uint16 packedBlockId) { Block* pCurBlock = pChunk->GetBlock(packedBlockId); if (pCurBlock) { m_pCurBlockTemplate = pCurBlock->GetTemplate(); if (m_pCurBlockTemplate) { m_pChunk = pChunk; UnpackBlockIndex(packedBlockId, m_blockId_cs.x, m_blockId_cs.y, m_blockId_cs.z); m_blockId_ws.x = pChunk->m_minBlockId_ws.x + m_blockId_cs.x; m_blockId_ws.y = pChunk->m_minBlockId_ws.y + m_blockId_cs.y; m_blockId_ws.z = pChunk->m_minBlockId_ws.z + m_blockId_cs.z; neighborBlocks[rbp_center] = pCurBlock; m_nBlockData = pCurBlock->GetUserData(); m_pCurBlockModel = &(m_pCurBlockTemplate->GetBlockModel(m_pWorld, m_blockId_ws.x, m_blockId_ws.y, m_blockId_ws.z, (uint16)m_nBlockData, neighborBlocks)); tessellatedModel.ClearVertices(); return true; } } return false; } void ParaEngine::BlockTessellatorBase::FetchNearbyBlockInfo(BlockChunk* pChunk, const Uint16x3& blockId_cs, int nNearbyBlockCount, int nNearbyLightCount) { //neighbor block info: excluding the first (center) block, since it has already been fetched. if (nNearbyBlockCount > 1) { memset(neighborBlocks + 1, 0, sizeof(Block*) * (nNearbyBlockCount - 1)); pChunk->QueryNeighborBlockData(blockId_cs, neighborBlocks+1, 1, nNearbyBlockCount - 1); } //neighbor light info if (!m_pCurBlockModel->IsUsingSelfLighting()) { nNearbyLightCount = nNearbyLightCount < 0 ? nNearbyBlockCount : nNearbyLightCount; memset(blockBrightness, 0, sizeof(uint8_t) * nNearbyLightCount * 3); m_pWorld->GetBlockBrightness(m_blockId_ws, blockBrightness, nNearbyLightCount, 3); } } uint32_t ParaEngine::BlockTessellatorBase::CalculateCubeAO() { uint32_t aoFlags = 0; Block* pCurBlock = neighborBlocks[rbp_pXpYpZ]; if (pCurBlock) { if (pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) aoFlags |= BlockModel::evf_xyz; } pCurBlock = neighborBlocks[rbp_nXpYpZ]; if (pCurBlock) { if (pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) aoFlags |= BlockModel::evf_Nxyz; } pCurBlock = neighborBlocks[rbp_pXpYnZ]; if (pCurBlock) { if (pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) aoFlags |= BlockModel::evf_xyNz; } pCurBlock = neighborBlocks[rbp_nXpYnZ]; if (pCurBlock) { if (pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) { aoFlags |= BlockModel::evf_NxyNz; } } pCurBlock = neighborBlocks[rbp_pYnZ]; if (pCurBlock) { if (pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) aoFlags |= BlockModel::evf_topFront; } pCurBlock = neighborBlocks[rbp_nXpY]; if (pCurBlock) { if (pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) aoFlags |= BlockModel::evf_topLeft; } pCurBlock = neighborBlocks[rbp_pXpY]; if (pCurBlock) { if (pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) aoFlags |= BlockModel::evf_topRight; } pCurBlock = neighborBlocks[rbp_pYpZ]; if (pCurBlock) { if (pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) aoFlags |= BlockModel::evf_topBack; } pCurBlock = neighborBlocks[rbp_nXnZ]; if (pCurBlock) { if (pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) aoFlags |= BlockModel::evf_LeftFront; } pCurBlock = neighborBlocks[rbp_nXpZ]; if (pCurBlock) { if (pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) aoFlags |= BlockModel::evf_leftBack; } pCurBlock = neighborBlocks[rbp_pXnZ]; if (pCurBlock) { if (pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) aoFlags |= BlockModel::evf_rightFont; } pCurBlock = neighborBlocks[rbp_pXpZ]; if (pCurBlock) { if (pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) aoFlags |= BlockModel::evf_rightBack; } pCurBlock = neighborBlocks[rbp_pXnYPz]; if (pCurBlock) { if (pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) aoFlags |= BlockModel::evf_xNyz; } pCurBlock = neighborBlocks[rbp_pXnYnZ]; if (pCurBlock) { if (pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) aoFlags |= BlockModel::evf_xNyNz; } pCurBlock = neighborBlocks[rbp_nXnYPz]; if (pCurBlock) { if (pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) aoFlags |= BlockModel::evf_NxNyz; } pCurBlock = neighborBlocks[rbp_nXnYnZ]; if (pCurBlock) { if (pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) aoFlags |= BlockModel::evf_NxNyNz; } pCurBlock = neighborBlocks[rbp_nYnZ]; if (pCurBlock) { if (pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) aoFlags |= BlockModel::evf_bottomFront; } pCurBlock = neighborBlocks[rbp_nXnY]; if (pCurBlock) { if (pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) aoFlags |= BlockModel::evf_bottomLeft; } pCurBlock = neighborBlocks[rbp_pXnY]; if (pCurBlock) { if (pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) aoFlags |= BlockModel::evf_bottomRight; } pCurBlock = neighborBlocks[rbp_nYpZ]; if (pCurBlock) { if (pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) aoFlags |= BlockModel::evf_bottomBack; } return aoFlags; } ////////////////////////////////////////////////////////// // // BlockGeneralTessellator // ////////////////////////////////////////////////////////// ParaEngine::BlockGeneralTessellator::BlockGeneralTessellator(CBlockWorld* pWorld) : BlockTessellatorBase(pWorld) { } int32 ParaEngine::BlockGeneralTessellator::TessellateBlock(BlockChunk* pChunk, uint16 packedBlockId, BlockRenderMethod dwShaderID, BlockVertexCompressed** pOutputData) { if (!UpdateCurrentBlock(pChunk, packedBlockId)) return 0; if (m_pCurBlockTemplate->IsMatchAttribute(BlockTemplate::batt_liquid)) { // water, ice or other transparent cube blocks // adjacent faces of the same liquid type will be removed. TessellateLiquidOrIce(dwShaderID); } else { if (m_pCurBlockModel->IsUsingSelfLighting()) { // like wires, etc. TessellateSelfLightingCustomModel(dwShaderID); } else if (m_pCurBlockModel->IsUniformLighting()) { // custom models like stairs, slabs, button, torch light, grass, etc. TessellateUniformLightingCustomModel(dwShaderID); } else { // standard cube including tree leaves. TessellateStdCube(dwShaderID); } } int nFaceCount = tessellatedModel.GetFaceCount(); if (nFaceCount > 0 ) { tessellatedModel.TranslateVertices(m_blockId_cs.x, m_blockId_cs.y, m_blockId_cs.z); *pOutputData = tessellatedModel.GetVertices(); } return nFaceCount; } void ParaEngine::BlockGeneralTessellator::TessellateUniformLightingCustomModel(BlockRenderMethod dwShaderID) { int nFetchNearybyCount = 7; // m_pCurBlockTemplate->IsTransparent() ? 7 : 1; FetchNearbyBlockInfo(m_pChunk, m_blockId_cs, nFetchNearybyCount); tessellatedModel.CloneVertices(m_pCurBlockTemplate->GetBlockModel(m_pWorld, m_blockId_ws.x, m_blockId_ws.y, m_blockId_ws.z, (uint16)m_nBlockData, neighborBlocks)); const uint16_t nFaceCount = m_pCurBlockModel->GetFaceCount(); // custom model does not use AO and does not remove any invisible faces. int32_t max_light = 0; int32_t max_sun_light = 0; int32_t max_block_light = 0; if (dwShaderID == BLOCK_RENDER_FIXED_FUNCTION) { max_light = GetMeshBrightness(m_pCurBlockTemplate, &(blockBrightness[rbp_center])); // not render completely dark max_light = Math::Max(max_light, 2); float fLightValue = m_pWorld->GetLightBrightnessLinearFloat(max_light); for (int face = 0; face < nFaceCount; ++face) { int nFirstVertex = face * 4; for (int v = 0; v < 4; ++v) { tessellatedModel.SetLightIntensity(nFirstVertex + v, fLightValue); } } } else { max_sun_light = GetMeshBrightness(m_pCurBlockTemplate, &(blockBrightness[rbp_center + nFetchNearybyCount * 2])); max_block_light = GetMeshBrightness(m_pCurBlockTemplate, &(blockBrightness[rbp_center + nFetchNearybyCount])); uint8 block_lightvalue = m_pWorld->GetLightBrightnessInt(max_block_light); uint8 sun_lightvalue = max_sun_light << 4; for (int face = 0; face < nFaceCount; ++face) { int nFirstVertex = face * 4; for (int v = 0; v < 4; ++v) { tessellatedModel.SetVertexLight(nFirstVertex + v, block_lightvalue, sun_lightvalue); } } } } void ParaEngine::BlockGeneralTessellator::TessellateSelfLightingCustomModel(BlockRenderMethod dwShaderID) { FetchNearbyBlockInfo(m_pChunk, m_blockId_cs, 19, 0); tessellatedModel.CloneVertices(m_pCurBlockTemplate->GetBlockModel(m_pWorld, m_blockId_ws.x, m_blockId_ws.y, m_blockId_ws.z, (uint16)m_nBlockData, neighborBlocks)); if (m_pCurBlockModel->IsUseAmbientOcclusion()) { uint32 aoFlags = CalculateCubeAO(); const uint16_t nFaceCount = tessellatedModel.GetFaceCount(); for (int face = 0; face < nFaceCount; ++face) { int nIndex = face * 4; tessellatedModel.SetVertexShadowFromAOFlags(nIndex, nIndex, aoFlags); } } } int32 VertexVerticalScaleMaskMap[] = { 3, // evf_NxyNz, //g_topLB 1, // evf_Nxyz, //g_topLT 0, // evf_xyz, //g_topRT 2, // evf_xyNz, //g_topRB -1, //g_frtLB 3, // evf_NxyNz, //g_frtLT 2, // evf_xyNz, //g_frtRT -1, //g_frtRB -1, //g_btmLB -1, //g_btmLT -1, //g_btmRT -1, //g_btmRB -1, // g_leftLB 1, // evf_Nxyz, // g_leftLT 3, // evf_NxyNz, // g_leftRT -1, // g_leftRB -1, // g_rightLB 2, // evf_xyNz, // g_rightLT 0, // evf_xyz, // g_rightRT -1, // g_rightRB -1, // g_bkLB 0, // evf_xyz, // g_bkLT 1, // evf_Nxyz, // g_bkRT -1, // g_bkRB }; void ParaEngine::BlockGeneralTessellator::TessellateLiquidOrIce(BlockRenderMethod dwShaderID) { FetchNearbyBlockInfo(m_pChunk, m_blockId_cs, 27); uint32 aoFlags = 0; if (m_pCurBlockModel->IsUseAmbientOcclusion()) { aoFlags = CalculateCubeAO(); } const uint16_t nFaceCount = m_pCurBlockModel->GetFaceCount(); PE_ASSERT(nFaceCount <= 6); bool bHasTopScale = false; float TopFaceVerticalScales[] = {1.f, 1.f, 1.f, 1.f}; DWORD dwBlockColor = m_pCurBlockTemplate->GetDiffuseColor(m_nBlockData); const bool bHasColorData = dwBlockColor != Color::White; //----------calc vertex lighting---------------- for (int face = 0; face < nFaceCount; ++face) { int nFirstVertex = face * 4; Block* pCurBlock = neighborBlocks[BlockCommon::RBP_SixNeighbors[face]]; if (!(pCurBlock && ( (pCurBlock->GetTemplate()->IsAssociatedBlockID(m_pCurBlockTemplate->GetID()) // TODO: we should show the face when two transparent color blocks with different color are side by side. // However, since we are not doing face sorting anyway, this feature is turned off at the moment. // && pCurBlock->GetTemplate()->GetDiffuseColor(pCurBlock->GetUserData()) == dwBlockColor ) || (face != 0 && pCurBlock->GetTemplate()->IsFullyOpaque())))) { int32_t baseIdx = nFirstVertex * 4; int32_t v1 = blockBrightness[BlockCommon::NeighborLightOrder[baseIdx]]; int32_t max_light = Math::Max(v1, 2); bool bHideFace = false; if (face == 0 && !m_pCurBlockTemplate->IsMatchAttribute(BlockTemplate::batt_solid)) { // check top face, just in case we need to scale edge water block according to gravity. for (int v = 0; v < 4; ++v) { int i = nFirstVertex + v; int32_t baseIdx = i * 4; // if both of the two adjacent blocks to the edge vertex are empty, we will scale that edge vertex to 0 height. Block* b2; Block* b3; if (v == 0){ b2 = neighborBlocks[rbp_nX]; b3 = neighborBlocks[rbp_nZ]; if (!((b2 && b2->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid | BlockTemplate::batt_obstruction | BlockTemplate::batt_liquid)) || (b3 && b3->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid | BlockTemplate::batt_obstruction | BlockTemplate::batt_liquid)))) { // BlockModel::evf_NxyNz TopFaceVerticalScales[3] = 0.4f; bHasTopScale = true; } else { if (!((neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 1]] && neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 1]]->GetTemplate() == m_pCurBlockTemplate) || (neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 2]] && neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 2]]->GetTemplate() == m_pCurBlockTemplate) || (neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 3]] && neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 3]]->GetTemplate() == m_pCurBlockTemplate))) { // BlockModel::evf_NxyNz TopFaceVerticalScales[3] = 0.8f; // surface block is always a little lower bHasTopScale = true; } } } else if (v == 1){ b2 = neighborBlocks[rbp_nX]; b3 = neighborBlocks[rbp_pZ]; if (!((b2 && b2->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid | BlockTemplate::batt_obstruction | BlockTemplate::batt_liquid)) || (b3 && b3->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid | BlockTemplate::batt_obstruction | BlockTemplate::batt_liquid)))) { // BlockModel::evf_Nxyz TopFaceVerticalScales[1] = 0.4f; bHasTopScale = true; } else { if (!((neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 1]] && neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 1]]->GetTemplate() == m_pCurBlockTemplate) || (neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 2]] && neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 2]]->GetTemplate() == m_pCurBlockTemplate) || (neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 3]] && neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 3]]->GetTemplate() == m_pCurBlockTemplate))) { // BlockModel::evf_Nxyz TopFaceVerticalScales[1] = 0.8f; bHasTopScale = true; } } } else if (v == 2){ b2 = neighborBlocks[rbp_pX]; b3 = neighborBlocks[rbp_pZ]; if (!((b2 && b2->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid | BlockTemplate::batt_obstruction | BlockTemplate::batt_liquid)) || (b3 && b3->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid | BlockTemplate::batt_obstruction | BlockTemplate::batt_liquid)))) { // BlockModel::evf_xyz TopFaceVerticalScales[0] = 0.4f; bHasTopScale = true; } else { if (!((neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 1]] && neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 1]]->GetTemplate() == m_pCurBlockTemplate) || (neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 2]] && neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 2]]->GetTemplate() == m_pCurBlockTemplate) || (neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 3]] && neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 3]]->GetTemplate() == m_pCurBlockTemplate))) { // BlockModel::evf_xyz TopFaceVerticalScales[0] = 0.8f; bHasTopScale = true; } } } else if (v == 3){ b2 = neighborBlocks[rbp_pX]; b3 = neighborBlocks[rbp_nZ]; if (!((b2 && b2->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid | BlockTemplate::batt_obstruction | BlockTemplate::batt_liquid)) || (b3 && b3->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid | BlockTemplate::batt_obstruction | BlockTemplate::batt_liquid)))) { // BlockModel::evf_xyNz TopFaceVerticalScales[2] = 0.4f; bHasTopScale = true; } else { if (!((neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 1]] && neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 1]]->GetTemplate() == m_pCurBlockTemplate) || (neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 2]] && neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 2]]->GetTemplate() == m_pCurBlockTemplate) || (neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 3]] && neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx + 3]]->GetTemplate() == m_pCurBlockTemplate))) { // BlockModel::evf_xyNz TopFaceVerticalScales[2] = 0.8f; bHasTopScale = true; } } } } if (!bHasTopScale && (pCurBlock && pCurBlock->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid))) { bHideFace = true; } } if (!bHideFace) { for (int v = 0; v < 4; ++v) { int i = nFirstVertex + v; int nIndex = tessellatedModel.AddVertex(*m_pCurBlockModel, i); if (bHasTopScale && VertexVerticalScaleMaskMap[i] >= 0) { float fScale = TopFaceVerticalScales[VertexVerticalScaleMaskMap[i]]; if (fScale != 1.f) { tessellatedModel.SetVertexHeightScale(nIndex, fScale); } } if (dwShaderID == BLOCK_RENDER_FIXED_FUNCTION) { tessellatedModel.SetLightIntensity(nIndex, m_pWorld->GetLightBrightnessLinearFloat(max_light)); } else { if (m_pCurBlockTemplate->IsMatchAttribute(BlockTemplate::batt_solid)) tessellatedModel.SetVertexLight(nIndex, m_pWorld->GetLightBrightnessInt(blockBrightness[BlockCommon::NeighborLightOrder[baseIdx] + 27]), blockBrightness[BlockCommon::NeighborLightOrder[baseIdx] + 27 * 2] << 4); else tessellatedModel.SetVertexLight(nIndex, m_pWorld->GetLightBrightnessInt(blockBrightness[27]), blockBrightness[27 * 2] << 4); } tessellatedModel.SetVertexShadowFromAOFlags(nIndex, i, aoFlags); if (bHasColorData) { tessellatedModel.SetVertexColor(nIndex, dwBlockColor); } } tessellatedModel.IncrementFaceCount(1); } } } } void ParaEngine::BlockGeneralTessellator::TessellateStdCube(BlockRenderMethod dwShaderID) { FetchNearbyBlockInfo(m_pChunk, m_blockId_cs, 27); uint32 aoFlags = 0; if (m_pCurBlockModel->IsUseAmbientOcclusion()) { aoFlags = CalculateCubeAO(); } const uint16_t nFaceCount = m_pCurBlockModel->GetFaceCount(); PE_ASSERT(nFaceCount <= 6); DWORD dwBlockColor = m_pCurBlockTemplate->GetDiffuseColor(m_nBlockData); const bool bHasColorData = dwBlockColor!=Color::White; for (int face = 0; face < nFaceCount; ++face) { int nFirstVertex = face * 4; Block* pCurBlock = neighborBlocks[BlockCommon::RBP_SixNeighbors[face]]; if (!pCurBlock || (pCurBlock->GetTemplate()->GetLightOpacity() < 15)) { for (int v = 0; v < 4; ++v) { int i = nFirstVertex + v; int32_t baseIdx = i * 4; int32_t max_light = 0; int32_t max_sun_light = 0; int32_t max_block_light = 0; if (dwShaderID == BLOCK_RENDER_FIXED_FUNCTION) { int32_t v1 = blockBrightness[BlockCommon::NeighborLightOrder[baseIdx]]; int32_t v2 = blockBrightness[BlockCommon::NeighborLightOrder[baseIdx + 1]]; int32_t v3 = blockBrightness[BlockCommon::NeighborLightOrder[baseIdx + 2]]; int32_t v4 = blockBrightness[BlockCommon::NeighborLightOrder[baseIdx + 3]]; max_light = GetAvgVertexLight(v1, v2, v3, v4); } else { int32_t v1 = blockBrightness[BlockCommon::NeighborLightOrder[baseIdx] + 27]; int32_t v2 = blockBrightness[BlockCommon::NeighborLightOrder[baseIdx + 1] + 27]; int32_t v3 = blockBrightness[BlockCommon::NeighborLightOrder[baseIdx + 2] + 27]; int32_t v4 = blockBrightness[BlockCommon::NeighborLightOrder[baseIdx + 3] + 27]; max_block_light = GetAvgVertexLight(v1, v2, v3, v4); v1 = blockBrightness[BlockCommon::NeighborLightOrder[baseIdx] + 27 * 2]; v2 = blockBrightness[BlockCommon::NeighborLightOrder[baseIdx + 1] + 27 * 2]; v3 = blockBrightness[BlockCommon::NeighborLightOrder[baseIdx + 2] + 27 * 2]; v4 = blockBrightness[BlockCommon::NeighborLightOrder[baseIdx + 3] + 27 * 2]; max_sun_light = GetAvgVertexLight(v1, v2, v3, v4); } Block* pCurBlock1 = neighborBlocks[BlockCommon::NeighborLightOrder[baseIdx]]; if (pCurBlock1 && pCurBlock1->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_solid)) { // simulate ao but not render completely dark. max_light -= 3; max_sun_light -= 3; max_block_light -= 3; } int nIndex = tessellatedModel.AddVertex(*m_pCurBlockModel, i); if (dwShaderID == BLOCK_RENDER_FIXED_FUNCTION) { max_light = Math::Max(max_light, 2); tessellatedModel.SetLightIntensity(nIndex, m_pWorld->GetLightBrightnessLinearFloat(max_light)); } else { max_sun_light = Math::Max(max_sun_light, 0); max_block_light = Math::Max(max_block_light, 0); tessellatedModel.SetVertexLight(nIndex, m_pWorld->GetLightBrightnessInt(max_block_light), max_sun_light << 4); } tessellatedModel.SetVertexShadowFromAOFlags(nIndex, i, aoFlags); if (bHasColorData) { tessellatedModel.SetVertexColor(nIndex, dwBlockColor); } } tessellatedModel.IncrementFaceCount(1); } } }
[ "zyguochn@gmail.com" ]
zyguochn@gmail.com
af281718989fd1767440cbfc6a14987cc55f7491
10a921d63bcbee56e00cfacb809d430d8bafec8a
/third_party/ceres-solver/include/ceres/crs_matrix.h
d2d62894194df8058c54f793ae844c89ca5fab71
[ "BSD-3-Clause" ]
permissive
zyxrrr/GraphSfM
b527383c09fcbf6a89fb848266d61e5e130dcb27
1af22ec17950ffc8a5c737a6a46f4465c40aa470
refs/heads/master
2020-04-23T02:48:42.557291
2019-03-26T02:41:10
2019-03-26T02:41:10
170,858,089
0
0
BSD-3-Clause
2019-02-15T11:57:46
2019-02-15T11:57:46
null
UTF-8
C++
false
false
3,124
h
// Ceres Solver - A fast non-linear least squares minimizer // Copyright 2012 Google Inc. All rights reserved. // http://code.google.com/p/ceres-solver/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Google Inc. nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Author: sameeragarwal@google.com (Sameer Agarwal) #ifndef CERES_PUBLIC_CRS_MATRIX_H_ #define CERES_PUBLIC_CRS_MATRIX_H_ #include <vector> #include "ceres/internal/port.h" #include "ceres/internal/disable_warnings.h" namespace ceres { // A compressed row sparse matrix used primarily for communicating the // Jacobian matrix to the user. struct CERES_EXPORT CRSMatrix { CRSMatrix() : num_rows(0), num_cols(0) {} int num_rows; int num_cols; // A compressed row matrix stores its contents in three arrays, // rows, cols and values. // // rows is a num_rows + 1 sized array that points into the cols and // values array. For each row i: // // cols[rows[i]] ... cols[rows[i + 1] - 1] are the indices of the // non-zero columns of row i. // // values[rows[i]] .. values[rows[i + 1] - 1] are the values of the // corresponding entries. // // cols and values contain as many entries as there are non-zeros in // the matrix. // // e.g, consider the 3x4 sparse matrix // // [ 0 10 0 4 ] // [ 0 2 -3 2 ] // [ 1 2 0 0 ] // // The three arrays will be: // // // -row0- ---row1--- -row2- // rows = [ 0, 2, 5, 7] // cols = [ 1, 3, 1, 2, 3, 0, 1] // values = [10, 4, 2, -3, 2, 1, 2] vector<int> cols; vector<int> rows; vector<double> values; }; } // namespace ceres #include "ceres/internal/reenable_warnings.h" #endif // CERES_PUBLIC_CRS_MATRIX_H_
[ "1701213988@pku.edu.cn" ]
1701213988@pku.edu.cn
afa5ed485008fc36193d53f397cf54e2d7c5cef3
a06d62ba6d1386f18b6af4977cac1ab8e32fa6f9
/Macacário/Graphs/hungarian.cpp
6031941108dce492ecc074bb6b6f5ad3d4d6505d
[]
no_license
wuerges/Competitive-Programming
0ddc52b3b9a2ba0d8c404e17797e954cfabf4306
d5ad53b87c85ee59d535ca7545a09792256f82d4
refs/heads/master
2020-03-30T08:33:11.751967
2018-10-01T02:00:25
2018-10-01T02:00:25
151,024,027
1
0
null
2018-10-01T01:39:43
2018-10-01T01:39:43
null
UTF-8
C++
false
false
1,428
cpp
#include <cstdio> #include <cstring> #include <vector> using namespace std; #define MAXN 1009 vector<int> adjU[MAXN]; int pairU[MAXN], pairV[MAXN]; bool vis[MAXN]; int m, n; ///Vértices enumerados de 1 a m em U e de 1 a n em V!!!! bool dfs(int u) { vis[u] = true; if (u == 0) return true; int v; for (int i=0; i!=(int)adjU[u].size(); ++i) { v = adjU[u][i]; if (!vis[pairV[v]] && dfs(pairV[v])) { pairV[v] = u; pairU[u] = v; return true; } } return false; } //O(E*V) int hungarian() { memset(&pairU, 0, sizeof pairU); memset(&pairV, 0, sizeof pairV); int result = 0; for (int u = 1; u <= m; u++) { memset(&vis, false, sizeof vis); if (pairU[u]==0 && dfs(u)) result++; } return result; } int main() { int T, lu[MAXN], lv[MAXN]; scanf("%d", &T); for(int caseNo=1; caseNo <= T; caseNo++) { scanf("%d", &m); for(int i=1; i<=m; i++) { scanf("%d", lu+i); adjU[i].clear(); } scanf("%d", &n); for(int i=1; i<=n; i++) { scanf("%d", lv+i); for(int j=1; j<=m; j++) { if (lu[j] != 0 && lv[i]%lu[j] == 0) adjU[j].push_back(i); if (lu[j] == 0 && lv[i] == 0) adjU[j].push_back(i); } } printf("Case %d: %d\n", caseNo, hungarian()); } return 0; }
[ "lucas.fra.oli18@gmail.com" ]
lucas.fra.oli18@gmail.com
414eab8fba2be570f53376b0e20dae45873c47b6
4af341026c371c8e25d37780c3d2a85063ec60ea
/CF-649-D-Div2-Ehab and last corollary-Cutting cycles in a graph-bi-coloring a graph(combo of tree and cycles and graphs)-APPLICATION OF DEQUEUE.cpp
2b4e45145fcbbc731c140284bdcde1231dd4f7bf
[]
no_license
i-am-arvinder-singh/CP
46a32f9235a656e7d777a16ccbce980cb1eb1c63
e4e79e4ffc636f078f16a25ce81a3095553fc060
refs/heads/master
2023-07-12T19:20:41.093734
2021-08-29T06:58:55
2021-08-29T06:58:55
266,883,239
1
1
null
2020-10-04T14:00:29
2020-05-25T21:25:39
C++
UTF-8
C++
false
false
3,249
cpp
#include<bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> // Common file #include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update using namespace std; using namespace __gnu_pbds;//which means policy based DS #define endl "\n" #define int long long #define ff first #define ss second #define fl(i,a,b) for(int i=a; i<b; i++) #define bfl(i,a,b) for(int i=a-1; i>=b; i--) #define pb push_back #define mp make_pair #define pii pair<int,int> #define vi vector<int> #define vt(type) vector<type> #define omniphantom ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #define mii map<int,int> #define pqb priority_queue<int> //Below is implementation of min heap #define pqs priority_queue<int,vi,greater<int> > #define setbits(x) __builtin_popcountll(x) #define zrobits(x) __builtin_ctzll(x) #define mod 998244353 #define inf 1e18 #define ps(x,y) fixed<<setprecision(y)<<x #define mk(arr,n,type) type *arr=new type[n]; #define w(x) int x; cin>>x; while(x--) #define pw(b,p) pow(b,p) + 0.1 #define ini const int #define sz(v) ((int)(v).size()) #define LEFT(n) (2*n) #define RIGHT(n) (2*n+1) const double pi = acos(-1.0); typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; ini mx = 2e5+5; vi edges[mx],col[2],s; deque<int> cyc; vt(pii) e; int pos[mx]; bool ex[mx]; void dfs(int node) { pos[node]=s.size(); col[pos[node]%2].pb(node); s.pb(node); for(auto v:edges[node]){ if(pos[v]==-1) dfs(v); else if(pos[node]-pos[v]>1 && pos[v]!=-1 && cyc.empty()){ for(int i=pos[v];i<=pos[node];i++){ cyc.pb(s[i]); ex[s[i]]=1;//mark } return; } } s.pop_back(); } void solve() { int n,m,k; cin>>n>>m>>k; while(m--){ int a,b; cin>>a>>b; edges[a].pb(b); edges[b].pb(a); e.pb({a,b}); } memset(pos,-1,sizeof(pos)); dfs(1); if(cyc.empty()){ if(col[0].size()<col[1].size()) swap(col[0],col[1]); cout<<1<<endl; fl(i,0,(k+1)/2) cout<<col[0][i]<<" "; } else{ for(auto p:e){ if(ex[p.ff] && ex[p.ss] && abs(pos[p.ff]-pos[p.ss])>1){ while(cyc.front()!=p.ff && cyc.front()!=p.ss){ ex[cyc.front()]=0; cyc.pop_front(); } while(cyc.back()!=p.ff && cyc.back()!=p.ss){ ex[cyc.back()]=0; cyc.pop_back(); } } } if(cyc.size()<=k){ cout<<2<<endl<<cyc.size()<<endl; for(auto x:cyc) cout<<x<<" "; } else{ cout<<1<<endl; fl(i,0,(k+1)/2){ cout<<cyc[i*2]<<" "; } } } } int32_t main() { omniphantom solve(); return 0; }
[ "arvinderavy@ymail.com" ]
arvinderavy@ymail.com
8a1960a1da388c98748df2227ddb5eeb4b8bb1b2
8088c26d067eb1bd16ba3536f03d89e659ac120b
/lib/libutils/utils/crypto/encrypted_message.h
988ce9ed253d9306f05cc97bf4cb9a1b981c74df
[]
no_license
bloXroute-Labs/bxextensions
b4d94e3b892a91da04f229f69415b979d7b5169e
b50a121d612297a6670f579db8c26ef684cb6d49
refs/heads/master
2022-04-28T14:51:55.765111
2022-03-31T16:19:12
2022-03-31T16:19:12
167,323,216
2
0
null
null
null
null
UTF-8
C++
false
false
895
h
#include <iostream> #include "utils/common/byte_array.h" #ifndef UTILS_CRYPTO_ENCRYPTED_MESSAGE_H_ #define UTILS_CRYPTO_ENCRYPTED_MESSAGE_H_ namespace utils { namespace crypto { class EncryptedMessage { public: EncryptedMessage(size_t cipher_len); const common::ByteArray& cipher_text(); const common::ByteArray& cipher(); const common::ByteArray& nonce(); common::ByteArray& nonce_array(); common::ByteArray& cipher_array(); common::ByteArray& cipher_text_array(); void set_cipher_text(int cipher_start_idx); void resize(size_t cipher_length); void reserve(size_t cipher_capacity); void from_cipher_text(const std::vector<uint8_t>& cipher_text, int padding_len); void clear(void); private: common::ByteArray _nonce; common::ByteArray _cipher; common::ByteArray _cipher_text; }; } // crypto } // utils #endif /* UTILS_CRYPTO_ENCRYPTED_MESSAGE_H_ */
[ "avraham.mahfuda@bloxroute.com" ]
avraham.mahfuda@bloxroute.com
04760befd5fc43b958f5d0771b1bea9c5a03414c
4c4e9f0cd801a1e98ae4c1bac3adea0a63bec22a
/src/autonomous_test.cpp
1f0cece724b15b5d736eb169551022151c22444f
[]
no_license
shangl/kukadu_tutorials
8b7c16b7fd129cc3b403fda293c0616ce2c724cf
78aac82955d0ef6d1817901d14df955c95a0b6bc
refs/heads/master
2022-03-26T06:44:03.599757
2020-01-06T22:18:34
2020-01-06T22:18:34
140,934,115
0
0
null
null
null
null
UTF-8
C++
false
false
2,237
cpp
#include <limits> #include <armadillo> #include <kukadu/kukadu.hpp> using namespace std; using namespace arma; using namespace kukadu; int main(int argc, char** args) { bool loadSkills = false; string inputFolder; for(int i = 1; i < argc; ++i) { KukaduTokenizer tok(args[i], "="); auto currTok = tok.next(); if(currTok == "--help") { cout << "usage: rosrun kukadu_tutorials " << args[0] << " [-i=$input_path$]" << endl; return EXIT_FAILURE; } else if(currTok == "-i") { loadSkills = true; inputFolder = tok.next(); } } loadSkills = true; ros::init(argc, args, "kukadu_skillexporter_demo"); ros::NodeHandle node; sleep(1); ros::AsyncSpinner spinner(10); spinner.start(); StorageSingleton& storage = StorageSingleton::get(); ModuleUsageSingleton::get().stopStatisticsModule(); SkillExporter exporter(storage); if(loadSkills) { cout << "loading data" << endl; std::vector<long long int> startTimes; std::vector<long long int> endTimes; long long int timeStep; /* auto importedSkill = exporter.loadExecutions(inputFolder, startTimes, endTimes, timeStep); AutonomousTester tester(storage, "simple_grasp", {}, importedSkill, startTimes, endTimes, timeStep); tester.testSkill("simple_grasp"); */ AutonomousTester tester(storage, true, {1}); tester.addSimulatedSkill("simple_grasp", {0, 1}, {10.0, 20.0}, {3.0, 4.0}, 200, 2000); tester.addSimulatedSkill("simple_grasp2", {1, 3, 4}, {10.0, 20.0, 5.0}, {3.0, 4.0, 5.0}, 200, 2000); tester.addSimulatedSkill("simple_grasp3", {0, 2, 5}, {10.0, 20.0, 30.0}, {3.0, 4.0, 4.0}, 200, 2000); tester.addSimulatedSkill("simple_grasp4", {0, 2, 3, 5}, {10.0, 20.0, 30.0, 10.0}, {3.0, 4.0, 4.0, 2.0}, 200, 2000); tester.testRobot(); /* while(true) { int executionIdx = 0; cout << "insert the skill execution index with which you want to test: "; cin >> executionIdx; tester.computeFailureProb("simple_grasp", importedSkill.second.at(executionIdx)); } */ } return 0; }
[ "simon.hangl@uibk.ac.at" ]
simon.hangl@uibk.ac.at
2595f0e1d1bd4d022f96d7b3f495771a98586316
c95e836a91df3789b23869ecec04534a109377d9
/commandeditor.h
33aa71e6337f6cb3bbc59d14809bfccc32607524
[]
no_license
leo-ratner/pa9_cplusplus
4dfc2f1b7151957e876e5af7c61e365c4f3e7128
d3fd0aa44f7aa7a74c0830c070690d3cc7d170a0
refs/heads/master
2020-03-11T01:03:45.419646
2018-04-16T08:35:51
2018-04-16T08:35:51
129,680,300
0
0
null
null
null
null
UTF-8
C++
false
false
2,301
h
#ifndef COMMANDEDITOR_H #define COMMANDEDITOR_H #include <QFrame> #include <QFileDialog> #include <QMessageBox> #include <QTextStream> #include <QTextCursor> #include <QTextBlock> #include "garden.h" #include "highlighter.h" /* * Note: This part of the code is mostly just based off of the example text editor tutorial * provided in the QT tutorial. As such, it has a higher degree of redundant code than the rest of * the program. This may be changed some time in the future, in which case hopefully I'll * remember to remove this comment. */ namespace Ui { class CommandEditor; } class CommandEditor : public QFrame { Q_OBJECT public: explicit CommandEditor(QWidget *parent = 0); ~CommandEditor(); public slots: //little hack to keep actions private but invoke them from parent. //TODO: figure out if inline will speed this up. void make_new() {on_actionNew_triggered();} void open() {on_actionOpen_triggered();} void save() {on_actionSave_triggered();} void saveAs() {on_actionSaveAs_triggered();} //note: had to be made public to connect them in the parent widget. public slots: void on_actionNew_triggered(); void on_actionOpen_triggered(); void on_actionSave_triggered(); void on_actionSaveAs_triggered(); void on_actionCopy_triggered(); void on_actionRedo_triggered(); void on_actionPaste_triggered(); void on_actionCut_triggered(); void on_actionUndo_triggered(); private: Ui::CommandEditor *ui; Highlighter* highlighter; //syntax highlighting. QString currentFile; //stores the current file name. bool valid; void nextNonEmpty(QTextCursor&); int startPoint; //where does the setup stop? public slots: //stuff related to line number manipulation. void goToFirstLine(); QString nextCommand(); //note, this *IGNORES* lines which are entirely whitespace. bool atEnd(); void goToLine(int); bool isValid(); Garden* attemptGardenSetup(double&); int getStartPoint(); int getCurrentLine(); int getLineCount(); //public slots: // void reset(); // void stepOnce(); // void loopThrough(bool); }; #endif // COMMANDEDITOR_H
[ "noreply@github.com" ]
noreply@github.com
f03023fedbe208fc4a699a26c10d8d0e61a92388
d6d28bdc0a26df048f5bdd702389fd66a5cb86b6
/CS32/Project1/Robot.cpp
ee7b08a1c485d6096f572b1343de0049559fd6fc
[]
no_license
prianna/courses
593244cb3d8b69fd1daa4875d34b62d66f06b172
d32802c8cfaac110e3d1a55254e6a535363287ac
refs/heads/master
2020-06-02T03:40:34.191619
2015-01-28T21:29:35
2015-01-28T21:29:35
29,174,441
0
1
null
null
null
null
UTF-8
C++
false
false
4,127
cpp
/** @file Robot.cpp */ ////////////////////////////////////////////////////////////////////////// // Robot implementation /////////////////////////////////////////////////////////////////////////// #include <iostream> #include <string> #include <cstdlib> #include <ctime> #include "globals.h" #include "Robot.h" #include "Valley.h" using namespace std; // Constructor: Create a Robot in the Valley pointed to by vp, with // name nm, location (r,c), and direction d. Robot::Robot(string nm, Valley* vp, int r, int c, int d) : m_name(nm), m_energy(FULL_ENERGY), m_row(r), m_col(c), m_dir(d), m_valley(vp), m_battery(FULL_BATTERY) { // Since the first character of the Robot's name shows up in the // display, there had better be a first character. if (nm.size() == 0) { cout << "***** A robot must have a non-empty name!" << endl; exit(1); } if (vp == NULL) { cout << "***** A robot must be in some Valley!" << endl; exit(1); } if (r < 0 || r >= vp->rows() || c < 0 || c >= vp->cols()) { cout << "***** Robot created with invalid coordinates (" << r << "," << c << ") in valley of size " << vp->rows() << "x" << vp->cols() << "!" << endl; exit(1); } switch (d) { case NORTH: case EAST: case SOUTH: case WEST: break; default: cout << "**** Robot created with invalid direction code " << d << "!" << endl; exit(1); } } string Robot::name() const { return m_name; } int Robot::energy() const { return m_energy; } int Robot::row() const { return m_row; } int Robot::col() const { return m_col; } int Robot::dir() const { return m_dir; } int Robot::batteryLevel() const { return m_battery.level(); } void Robot::decreaseBattery() { m_battery.decrease(); } bool Robot::step() { // If the robot has no energy left, return false if (m_energy == 0) { if (batteryLevel() == 0) return false; else m_energy++; decreaseBattery(); } // Randomly change direction with probability 1/3 if (rand() % 3 == 0) // 1/3 probability to pick a direction m_dir = rand() % 4; // pick a random direction (0 through 3) // Attempt to move one step in the direction we're currently facing. // If we can't move in that direction, don't move. switch (m_dir) { case NORTH: if (m_row > 0) m_row--; else m_dir = 1, m_row++; // switch direction to South and move one step South. break; case SOUTH: if (m_row < m_valley->rows()-1) m_row++; else m_dir = 0, m_row--; // switch direction to North and move one step North. break; case WEST: if (m_col > 0) m_col--; else m_dir = 2, m_col++; // switch direction to East and move one step East. break; case EAST: if (m_col < m_valley->cols()-1) m_col++; else m_dir = 3, m_col--; // switch direction to West and move one step West. break; } // The attempt to move consumes one unit of energy. m_energy--; // If as a result of the attempt to move, the robot is at an energy // source, it's recharged to the FULL_ENERGY level. if (m_valley->energySourceAt(m_row, m_col)) m_energy = FULL_ENERGY; // If at this spot there's another robot whose energy level is 0, // and we have at least SHARE_THRESHOLD units of energy, // transfer SHARE_AMOUNT units to that other robot. if (m_energy >= SHARE_THRESHOLD) { Robot* rp = m_valley->otherRobotAt(this); if (rp != NULL && rp->energy() == 0) { m_energy -= SHARE_AMOUNT; rp->m_energy += SHARE_AMOUNT; } } return true; }
[ "prianna@g.ucla.edu" ]
prianna@g.ucla.edu
d84c13793bbd1ad71389875194803145362b82bc
aa354c9318d71db93c625bbdfc6c014df2d59aec
/utils.hpp
551be1565399ed30b6234c737efc66f9c28302f4
[]
no_license
Nfreewind/TLD-MOD
dcd19e92b7ed32a8bf5eaa1fa167fda8e681da41
a7790de2819a79ff16bb1551433d41b216c943da
refs/heads/master
2020-05-25T01:46:43.724294
2018-07-11T23:23:02
2018-07-11T23:23:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,102
hpp
#ifndef UTILS_HPP_INCLUDED #define UTILS_HPP_INCLUDED #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "opencv2/legacy/legacy.hpp" #include <iostream> #define MAX_DIST_CLUSTER 0.5 //Distância máxima da amostra até o centro de seu cluster #ifndef MIN #define MIN(a,b) ((a) > (b) ? (b) : (a)) #endif #ifndef MAX #define MAX(a,b) ((a) < (b) ? (b) : (a)) #endif #ifndef SQR #define SQR(a) ((a)*(a)) #endif #ifndef EPSILON #define EPSILON 0.0000077 #endif #define _DEBUG_IL 0 #define _DEBUG_TRACKER 0 #define _DEBUG_DETECTOR 1 #define OVERLAP_THRESHOLD 0.5 #define MIN_BB 20 //Tamanho mínimo de bb #define SMOOTH(image, blur) GaussianBlur(image, blur, Size(-1, -1), 3, 3); #define UCHAR 0 #define SIGNED8 1 #define UNSIGNED16 2 #define SIGNED16 3 #define SIGNED32 4 #define FLOAT32 5 #define DOUBLE64 6 #define ONEBIT 7 #ifndef RAD2DEG #define RAD2DEG(a) (((a) * 180) / M_PI) #endif #ifndef LESSER #define LESSER(a, b) (a < b ? a : b) #endif using namespace cv; enum VIDEO_TYPE{ WEBCAM, VIDEO, IMAGE_LIST }; typedef std::array<float,4> BoundingBox; //xMin, yMin, xMax, yMax. &BoundingBox no cabeçalho para alterar conteúdo dentro da função. A chamada é feita com BoundingBox. typedef double Vector2D[2]; typedef struct _sortElement{ //Elemento para ordenação int index; double val; }SortElement; double L2norm(double hist[], int hist_size); int maxVal(const void * a, const void * b); float widthBB(BoundingBox bb); float heightBB(BoundingBox bb); float areaBB(BoundingBox bb); float intersectionArea(BoundingBox bb1, BoundingBox bb2); float overlap(BoundingBox bb1, BoundingBox bb2); // interseção / união \in [0,1] void writeBBInfos(string filename, BoundingBox bb, int frame, bool type); Mat integralImage(Mat image, int p); float* getVariance(Mat image, vector<BoundingBox> bb_list); int matType(Mat frame, int &channels); int clusterConf(Mat frame, vector<BoundingBox> d_answers, vector<double> d_conf, vector<BoundingBox> &c_answers, vector<double> &c_conf, bool show); #endif // UTILS_HPP_INCLUDED
[ "noreply@github.com" ]
noreply@github.com
6de50fdea9d891849bed018e0a5f45791d0e7c83
d03309b8465f50e0580ec1754e41c5fbe6c334ab
/src/Utils/src/ArgParseUtils.cpp
98ea855a9b22513931572beb8601a718c3df679e
[ "BSD-3-Clause" ]
permissive
saifullah3396/team-nust-robocup-v2
7d042f3232e5e19504efee24bdf72cf4e08a0a6e
4f1953817def77c1c6157bd82208bc39a797d557
refs/heads/master
2020-04-27T18:12:38.482594
2019-09-01T10:42:51
2019-09-01T10:42:51
174,559,212
0
0
null
null
null
null
UTF-8
C++
false
false
1,137
cpp
/** * @file Utils/src/ArgParseUtils.cpp * * This file implements the helper functions associated with argument parsing * * @author <A href="mailto:saifullah3396@gmail.com">Saifullah</A> * @date 17 Jul 2018 */ #include <algorithm> #include "Utils/include/ArgParseUtils.h" #include "Utils/include/Exceptions/ArgParseException.h" #include "Utils/include/PrintUtils.h" namespace ArgParseUtils { /** * Gets the value of the option for given string */ char* getCmdOption( char ** begin, char ** end, const string & option) { try { char ** itr = std::find(begin, end, option); if (itr != end && ++itr != end) { return *itr; } else { throw ArgParseException( "No argument specified for option: " + option, false, EXC_NO_ARG_SPECIFIED ); } } catch (ArgParseException& e) { LOG_EXCEPTION(e.what()); } return 0; } /** * Checks if the given option exists */ bool cmdOptionExists( char** begin, char** end, const string& option) { return find(begin, end, option) != end; } }
[ "Saifullah3396@gmail.com" ]
Saifullah3396@gmail.com
671433336643fb721c443395c2f5874257061a9a
8ff2cf7b5dee304c238912d724a1339bea0ca20d
/td_module.cpp
0e9ce0942a0cfedec31ee58444501693caf8488f
[]
no_license
dprefontaine/deepees_tower_defense_module
b4a8058c10b0726c69619cd12ecb638c9339d6d6
5b86dd2ba89a9a2d4312ab36c8a556b481c1a4bd
refs/heads/main
2023-05-21T21:10:36.216723
2021-05-24T17:44:49
2021-05-24T17:44:49
370,432,668
0
0
null
null
null
null
UTF-8
C++
false
false
40,227
cpp
#include "td_module.h" int determine_buildover(TARGET_BUILDOVER buildover, int grid_data){ switch (buildover){ case TOWER_PHASEABLE: if (grid_data == 1) return 0; else return 3; break; case TOWER_UNPHASEABLE: return 3; break; case TOWER_DIGGING: return 0; break; } return 0; } td_module::td_module(int cam_x_accel, int cam_y_accel, int max_x_vel, int max_y_vel){ td_grid = grid_manager(); enemies_to_spawn = std::stack<std::pair<int, enemy>>(); td_enemies = std::map<int, enemy>(); td_bullets = bullet_space(); td_bullets.set_bullet_space(&td_bullets); td_bullets.set_enemy_space(&td_enemies); td_towers = std::vector<tower>(); td_waves = std::queue<std::string>(); td_resources = std::map<std::string, resource>(); lives = resource(15, 15); load_waves(); build_button_mappings = std::map<td_module_build_button_selection, std::string>(); load_button_mapping(); x_click = y_click = 0; control_state = MODULE_DEFAULT; level_playing = false; moving_up = moving_down = moving_left = moving_right = false; x_acc = cam_x_accel; y_acc = cam_y_accel; x_vel = y_vel = 0; x_vel_max = max_x_vel; y_vel_max = max_y_vel; //RESOURCES td_resources.insert(std::pair<std::string, resource>("Metal",resource(250,9999))); td_resources.insert(std::pair<std::string, resource>("Wood",resource(150,9999))); td_resources.insert(std::pair<std::string, resource>("Crystal",resource(15,9999))); td_bullets.set_resources(&td_resources); //NOTIFICATION notification_on = false; notification_message = ""; } td_module::~td_module(){ selected_tower_index = 0; std::map<int, enemy>().swap(td_enemies); std::vector<tower>().swap(td_towers); std::map<std::string, resource>().swap(td_resources); std::map<td_module_build_button_selection, std::string>().swap(build_button_mappings); } void td_module::update_td_module(unsigned int ticks){ extern main_controller* game; //THE CAMERA AND NOTIFICATION ARE INDEPENDENT OF THE TICK SPEED if (ticks < 100){ int vert_sign = 0; int horz_sign = 0; if (moving_down){ //std::cout << "Moving down" << std::endl; vert_sign++; } if (moving_up){ //std::cout << "Moving up" << std::endl; vert_sign--; } if (moving_right){ //std::cout << "Moving right" << std::endl; horz_sign++; } if (moving_left){ //std::cout << "Moving left" << std::endl; horz_sign--; } vert_accel = ticks/1000.f; vert_accel*=y_acc; if (vert_sign != 0){ y_vel+=vert_accel; if (y_vel > y_vel_max) y_vel = y_vel_max; } else if (y_vel != 0){ y_vel-=vert_accel; if (y_vel < 0) y_vel = 0; } horz_accel = ticks/1000.f; horz_accel*=x_acc; if (horz_sign != 0){ x_vel+=horz_accel; if (x_vel > x_vel_max) x_vel = x_vel_max; } else if (x_vel != 0){ x_vel-=horz_accel; if (x_vel < 0) x_vel = 0; } game->set_camera_position(0,1,x_vel*horz_sign, y_vel*vert_sign); if (notification_on){ static int notification_threshold = 0; notification_threshold+=ticks; if (!game->get_active("Notification")){ game->reload_as_text("Notification", "notification font", notification_message, false, 0); game->set_blend_mode("Notification", SDL_BLENDMODE_BLEND); game->set_active("Notification", true); } if (notification_threshold > 2000){ notification_threshold = 0; notification_on = false; game->set_active("Notification", false); } } ///SPEED MULTIPLIER IS HERE ticks*=speed_multiplier; //UPDATING BULLETS td_bullets.update(ticks); draw_bullets(); //UPDATING ANY MOVEMENTS BASED ON STATE OF THE MAP if (level_playing){ //std::cout << "Level is playing!" << std::endl; if (remaining_enemies_to_spawn()){ if (spawn_rate.alarm_set(ticks) > 0){ spawn_rate.reset_warning(); spawn_enemy(); } } if (!(remaining_enemies_to_spawn()) && td_enemies.empty()){ level_playing = false; increase_level(); } } //UPDATING ENEMIES if (!td_enemies.empty()){ std::map<int, enemy>::iterator enemy_iterator = td_enemies.begin(); for (unsigned int i = 0; i < total_wave_enemies; i++){ enemy_iterator = td_enemies.find(i); if (enemy_iterator != td_enemies.end()) //RETURNS TRUE IF ABOUT TO TERMINATE if (enemy_iterator->second.update(ticks)){ if (enemy_iterator->second.get_end_state() == ENEMY_KILLED){ enemy_bountied(enemy_iterator->first); } else if (enemy_iterator->second.get_end_state() == ENEMY_FINISHED){ enemy_at_end(enemy_iterator->first); } } } } else { total_enemies = 0; } draw_enemies(); //UPDATING TOWERS if (!td_towers.empty()){ //UPDATING TOWERS for (unsigned int i = 0; i < td_towers.size(); i++){ td_towers.at(i).update(ticks); } } draw_board(); } } int td_module::toggling_speed(){ if (speed_multiplier == 1){ speed_multiplier = 2; return 1; } else if (speed_multiplier == 2) { speed_multiplier = 4; return 2; } else { speed_multiplier = 1; return 0; } } void td_module::increase_level(){ if (!level.add_to_resource(1)){ notification_message = "You won the game!"; notification_on = true; } } void td_module::remove_life(){ if (!lives.use_resource(1) || lives.get_resource() == 0){ notification_message = "You lost the game!"; notification_on = true; } } void td_module::click_on_grid(unsigned int x_click, unsigned int y_click){ td_module::x_click = x_click/SQUARE_SIZE; td_module::y_click = y_click/SQUARE_SIZE; //std::cout << "X: " << td_module::x_click << " Y: " << td_module::y_click << std::endl; td_grid.set_grid_point(td_module::x_click, td_module::y_click); switch(control_state){ case MODULE_DEFAULT: observe_grid_click(); break; case MODULE_BUILD: build_tower_click(); break; } set_state(MODULE_DEFAULT); } void td_module::over_grid(unsigned int x_over, unsigned int y_over){ x_click = x_over/SQUARE_SIZE; y_click = y_over/SQUARE_SIZE; //std::cout << td_module::x_click << " " << td_module::y_click << std::endl; td_grid.set_grid_point(x_click, y_click); switch(control_state){ case MODULE_DEFAULT: observe_grid_over(); break; case MODULE_BUILD: build_tower_over(); break; } } void td_module::set_build_click(td_module_build_button_selection new_state){ if (build_data_select == new_state){ set_state(MODULE_DEFAULT); build_data_select = BUILD_BUTTON_NONE; deactivate_selection(); } else if (new_state == BUILD_BUTTON_NONE) { set_state(MODULE_DEFAULT); build_data_select = BUILD_BUTTON_NONE; } else { extern main_controller* game; extern td_level_loader* table; set_state(MODULE_BUILD); build_data_select = new_state; ///GET THE NAME OF THE DATA THIS BUTTON IS ASSOCIATED WITH tower_data_name = build_button_mappings.at(build_data_select); ///SETTING THE TOWER IMAGE game->reload_as_image("Tower Select", table->get_tower_data(tower_data_name).tower_image_link, {0,0,90,90}); game->set_alpha("Tower Select", 0xAA); game->set_blend_mode("Tower Select", SDL_BLENDMODE_BLEND); activate_selection(true, false); } } td_module_build_button_selection td_module::get_build_click(){ return build_data_select; } void td_module::set_button_data_set(){ extern main_controller* game; extern td_level_loader* table; game->reload_as_image("Build Icon One", table->get_tower_data(build_button_mappings.at(BUILD_BUTTON_ONE)).tower_icon_name, {0,0,95,95}); game->reload_as_image("Build Icon Two", table->get_tower_data(build_button_mappings.at(BUILD_BUTTON_TWO)).tower_icon_name, {0,0,95,95}); game->reload_as_image("Build Icon Three", table->get_tower_data(build_button_mappings.at(BUILD_BUTTON_THREE)).tower_icon_name, {0,0,95,95}); game->reload_as_image("Build Icon Four", table->get_tower_data(build_button_mappings.at(BUILD_BUTTON_FOUR)).tower_icon_name, {0,0,95,95}); game->reload_as_image("Build Icon Five", table->get_tower_data(build_button_mappings.at(BUILD_BUTTON_FIVE)).tower_icon_name, {0,0,95,95}); game->reload_as_image("Build Icon Six", table->get_tower_data(build_button_mappings.at(BUILD_BUTTON_SIX)).tower_icon_name, {0,0,95,95}); game->reload_as_image("Build Icon Seven", table->get_tower_data(build_button_mappings.at(BUILD_BUTTON_SEVEN)).tower_icon_name, {0,0,95,95}); game->reload_as_image("Build Icon Eight", table->get_tower_data(build_button_mappings.at(BUILD_BUTTON_EIGHT)).tower_icon_name, {0,0,95,95}); game->reload_as_image("Build Icon Nine", table->get_tower_data(build_button_mappings.at(BUILD_BUTTON_NINE)).tower_icon_name, {0,0,95,95}); } void td_module::draw_grid(){ extern main_controller* game; //THIS SHOULD STAY THE SAME, SO IT'S NO BIG DEAL int grid_data = 0; //START FROM THE TOP td_grid.set_grid_point(0,0); game->clear_points("Grey Tile"); game->clear_points("Pink Tile"); game->clear_points("Orange Tile"); game->clear_points("Blue Tile"); do { //GET DATA OF THAT POINT ///FOR REFERENCE: //GREY IS CROSSABLE AND NOT BUILDABLE //PINK IS CROSSABLE AND BUILDABLE //ORANGE IS NOT CROSSABLE AND BUILDABLE grid_data = td_grid.get_grid_data_at_current_point(); switch (grid_data){ case 0: //Draw grey game->add_point("Grey Tile", td_grid.get_grid_x_current_point()*SQUARE_SIZE+SQUARE_SIZE/2, td_grid.get_grid_y_current_point()*SQUARE_SIZE+SQUARE_SIZE/2); break; case 1: //Draw pink game->add_point("Pink Tile", td_grid.get_grid_x_current_point()*SQUARE_SIZE+SQUARE_SIZE/2, td_grid.get_grid_y_current_point()*SQUARE_SIZE+SQUARE_SIZE/2); break; case 2: //Draw orange game->add_point("Orange Tile", td_grid.get_grid_x_current_point()*SQUARE_SIZE+SQUARE_SIZE/2, td_grid.get_grid_y_current_point()*SQUARE_SIZE+SQUARE_SIZE/2); break; case 3: // game->add_point("Blue Tile", td_grid.get_grid_x_current_point()*SQUARE_SIZE+SQUARE_SIZE/2, td_grid.get_grid_y_current_point()*SQUARE_SIZE+SQUARE_SIZE/2); } } while (td_grid.inc_grid_point()); } void td_module::draw_board(){ extern main_controller* game; static std::stringstream ss = std::stringstream(); //GET THE MONEY AND DISPLAY IT ss << td_resources.at("Metal").get_resource(); game->reload_as_text("Metal", "base font", ss.str(), false, 0); game->set_point("Metal", 0, 70+game->get_spot("Metal").w/2, 30); ss.str(""); ss << td_resources.at("Wood").get_resource(); game->reload_as_text("Wood", "base font", ss.str(), false, 0); game->set_point("Wood", 0, 230+game->get_spot("Wood").w/2, 30); ss.str(""); ss << td_resources.at("Crystal").get_resource(); game->reload_as_text("Crystal", "base font", ss.str(), false, 0); game->set_point("Crystal", 0, 390+game->get_spot("Crystal").w/2, 30); ss.str(""); //GET THE LEVEL AND DISPLAY IT ss << level.get_resource(); game->reload_as_text("Level", "base font", ss.str(), false, 0); game->set_point("Level", 0, 555+game->get_spot("Level").w/2, 30); ss.str(""); //GET THE LIVES AND DISPLAY THEM ss << lives.get_resource(); game->reload_as_text("Lives", "base font", ss.str(), false, 0); game->set_point("Lives", 0, 940+game->get_spot("Lives").w/2, 30); ss.str(""); } void td_module::draw_points(){ extern main_controller* game; game->add_point("Start Portal", START_POINT_X*SQUARE_SIZE+SQUARE_SIZE/2, START_POINT_Y*SQUARE_SIZE+SQUARE_SIZE/2); game->add_point("Move Point One", ONE_POINT_X*SQUARE_SIZE+SQUARE_SIZE/2, ONE_POINT_Y*SQUARE_SIZE+SQUARE_SIZE/2); game->add_point("Move Point Two", TWO_POINT_X*SQUARE_SIZE+SQUARE_SIZE/2, TWO_POINT_Y*SQUARE_SIZE+SQUARE_SIZE/2); game->add_point("House", END_POINT_X*SQUARE_SIZE+SQUARE_SIZE/2, END_POINT_Y*SQUARE_SIZE+SQUARE_SIZE/2); } void td_module::add_tower_image(std::string tower_image_spot, std::string tower_image_source){ extern main_controller* game; game->create_image(tower_image_spot, tower_image_source, {0,0,90,90}); game->set_active(tower_image_spot, true); } void td_module::remove_tower_image(std::string tower_image_spot){ extern main_controller* game; game->set_active(tower_image_spot, false); game->clear_points(tower_image_spot); game->remove_image_copy(tower_image_spot); draw_towers(); } void td_module::draw_towers(){ extern main_controller* game; //draw all the currently build towers for (unsigned int i = 0; i < td_towers.size(); i++){ game->clear_points(td_towers.at(i).get_name()); game->add_point(td_towers.at(i).get_name(), td_towers.at(i).get_range()->get_x(), td_towers.at(i).get_range()->get_y()); } } void td_module::set_points(){ td_grid.set_grid_point(START_POINT_X, START_POINT_Y); td_grid.set_start_on_point(); td_grid.add_destination(0, ONE_POINT_X, ONE_POINT_Y); td_grid.add_destination(1, TWO_POINT_X, TWO_POINT_Y); td_grid.add_destination(2, END_POINT_X, END_POINT_Y); } void td_module::load_map(){ extern td_level_loader* table; td_grid.set_grid_point(0,0); std::queue<int> map_stream = std::queue<int>(); table->set_map(&map_stream, selected_map); if (!map_stream.empty()) do { td_grid.set_grid_data(map_stream.front()); map_stream.pop(); } while (td_grid.inc_grid_point() && !map_stream.empty()); } void td_module::set_state(td_module_state new_state){ extern main_controller* game; control_state = new_state; if (control_state == MODULE_DEFAULT) game->clear_points("Tower Select"); } td_module_state td_module::get_state(){ return control_state; } void td_module::tower_found(){ extern main_controller* game; //ASSUMING OVER A POINT FOR WHATEVER REASON //CHECK IF ANY TOWER FALLS UNDER THE COORDINATES OF BEING CLICKED bool click_flag = false; int i = 0; while (i < (int)td_towers.size() && !click_flag){ if ((int)td_towers.at(i).get_range()->get_x()/(int)SQUARE_SIZE == x_click && (int)td_towers.at(i).get_range()->get_y()/(int)SQUARE_SIZE == y_click){ game->add_point("Circle Selected", x_click*SQUARE_SIZE+SQUARE_SIZE/2, y_click*SQUARE_SIZE+SQUARE_SIZE/2); selected_tower_index = i; click_flag = true; } i++; } if (!click_flag){ selected_tower_index = i = -1; } } void td_module::observe_grid_click(){ extern main_controller* game; //COME HERE FROM DEFAULT STATE game->clear_points("Circle Selected"); tower_found(); if (selected_tower_index != -1){ //std::cout << "Displaying the selected tower" << std::endl; //std::cout << "Single Target Type" << std::endl; //std::cout << "Attack: " << td_towers.at(selected_tower_index).get_damage() << std::endl; //std::cout << "Range: " << td_towers.at(selected_tower_index).get_range()->get_radius() << std::endl; tower_data_name = td_towers.at(selected_tower_index).get_display_name(); activate_selection(false, true); } else { deactivate_selection(); } } void td_module::activate_selection(bool is_building, bool is_selling){ extern main_controller* game; extern td_level_loader* table; game->set_active("Tower Name", true); game->set_active("Attack", true); game->set_active("Range", true); game->set_active("Rate", true); game->set_active("Tower Description", true); game->set_active("Select", false); //ACTIVATING BUTTONS FIRST if (is_building){ game->set_active("Cost Display", true); game->set_active("Upgrade Button", false); game->set_button_active("Upgrade Button", false); game->set_active("Blank Upgrade Button", false); //BUILD STRINGS FOR DISPLAYING THE BUILDING COST } else { game->set_active("Cost Display", false); //CHECK IF THE SELECTED TOWER HAS AN AVAILABLE UPGRADE if (table->get_tower_data(td_towers.at(selected_tower_index).get_display_name()).has_upgrade){ game->set_active("Blank Upgrade Button", false); game->set_active("Upgrade Button", true); game->set_button_active("Upgrade Button", true); //BUILD STRINGS FOR DISPLAYING THE UPGRADE COST //std::string upgrade_tower_name = table->get_tower_data(td_towers.at(selected_tower_index).get_display_name()).upgrade_name; //tower_data upgrade_tower_data = table->get_tower_data(upgrade_tower_name); } else { game->set_active("Blank Upgrade Button", true); game->set_active("Upgrade Button", false); game->set_button_active("Upgrade Button", false); } } game->set_active("Button Metal", true); game->set_active("Button Wood", true); game->set_active("Button Crystal", true); if (is_selling){ game->set_active("Sell Button", true); game->set_active("Sell Button Metal", true); game->set_active("Sell Button Wood", true); game->set_active("Sell Button Crystal", true); game->set_button_active("Sell Button", true); game->set_active("Blank Sell Button", false); } else { game->set_active("Blank Sell Button", true); game->set_button_active("Sell Button", false); game->set_active("Sell Button Metal", false); game->set_active("Sell Button Wood", false); game->set_active("Sell Button Crystal", false); game->set_button_active("Sell Button", false); } //UPDATING DISPLAYS draw_selection(is_building, is_selling); } void td_module::deactivate_selection(){ extern main_controller* game; game->set_active("Blank Upgrade Button", false); game->set_active("Blank Sell Button", false); game->set_active("Cost Display", false); game->set_active("Upgrade Button", false); game->set_active("Button Metal", false); game->set_active("Button Wood", false); game->set_active("Button Crystal", false); game->set_active("Sell Button", false); game->set_active("Sell Button Metal", false); game->set_active("Sell Button Wood", false); game->set_active("Sell Button Crystal", false); game->set_active("Blank Button", false); game->set_button_active("Upgrade Button", false); game->set_button_active("Sell Button", false); game->set_active("Tower Name", false); game->set_active("Attack", false); game->set_active("Range", false); game->set_active("Rate", false); game->set_active("Tower Description", false); game->set_active("Select", true); } void td_module::draw_selection(bool is_building, bool is_selling){ extern main_controller* game; extern td_level_loader* table; //GETTING DATA tower_data selection_data = table->get_tower_data(tower_data_name); tower_bullet_data bullet_selection_data = table->get_bullet_data(selection_data.bullet_data_name); std::stringstream stat_stream = std::stringstream(); //SETTING NAME game->reload_as_text("Tower Name", "display font header", selection_data.tower_name, false, 0); game->set_blend_mode("Tower Name", SDL_BLENDMODE_BLEND); stat_stream.str(""); //GET THE ATTACK AND DISPLAY IT stat_stream << "Attack: " << bullet_selection_data.get_attack(); game->reload_as_text("Attack", "display font stats", stat_stream.str(), false, 0); game->set_point("Attack", 0, 20+game->get_spot("Attack").w/2, 90); stat_stream.str(""); //GET THE LEVEL AND DISPLAY IT stat_stream << "Range: " << selection_data.attack_range; game->reload_as_text("Range", "display font stats", stat_stream.str(), false, 0); game->set_point("Range", 0, 20+game->get_spot("Range").w/2, 130); stat_stream.str(""); //GET THE LIVES AND DISPLAY THEM stat_stream << "Rate: " << selection_data.attack_rate; game->reload_as_text("Rate", "display font stats", stat_stream.str(), false, 0); game->set_point("Rate", 0, 20+game->get_spot("Rate").w/2, 170); stat_stream.str(""); //GET THE DESCRIPTION std::string tower_description = selection_data.description; game->reload_as_text("Tower Description", "display font description", tower_description, true, 220); game->set_spot("Tower Description", {0,0,game->get_image_x_size("Tower Description"), game->get_image_y_size("Tower Description")}); game->set_point("Tower Description", 0, 20+game->get_spot("Tower Description").w/2, 200+game->get_spot("Tower Description").h/2); //GET THE UPGRADE/BUILD COST/SELLING COST if (is_building){ stat_stream << selection_data.metal_use; game->reload_as_text("Metal Cost", "display font costs", stat_stream.str(), false, 0); game->set_point("Metal Cost", 0, 32+game->get_spot("Metal Cost").w/2, 552); game->set_active("Metal Cost", true); stat_stream.str(""); stat_stream << selection_data.wood_use; game->reload_as_text("Wood Cost", "display font costs", stat_stream.str(), false, 0); game->set_point("Wood Cost", 0, 109+game->get_spot("Wood Cost").w/2, 552); game->set_active("Wood Cost", true); stat_stream.str(""); stat_stream << selection_data.crystal_use; game->reload_as_text("Crystal Cost", "display font costs", stat_stream.str(), false, 0); game->set_point("Crystal Cost", 0, 186+game->get_spot("Crystal Cost").w/2, 552); game->set_active("Crystal Cost", true); stat_stream.str(""); game->set_active("Metal Upgrade Cost", false); game->set_active("Wood Upgrade Cost", false); game->set_active("Crystal Upgrade Cost", false); } else { game->set_active("Metal Cost", false); game->set_active("Wood Cost", false); game->set_active("Crystal Cost", false); //CHECK IF UPGRADABLE if (selection_data.has_upgrade){ //GET THE COST OF THE UPGRADE tower_data upgrade_selection = table->get_tower_data(selection_data.upgrade_name); stat_stream << upgrade_selection.metal_use; game->reload_as_text("Metal Cost", "display font costs", stat_stream.str(), false, 0); game->set_point("Metal Cost", 0, 32+game->get_spot("Metal Cost").w/2, 552); game->set_active("Metal Cost", true); stat_stream.str(""); stat_stream << upgrade_selection.wood_use; game->reload_as_text("Wood Cost", "display font costs", stat_stream.str(), false, 0); game->set_point("Wood Cost", 0, 109+game->get_spot("Wood Cost").w/2, 552); game->set_active("Wood Cost", true); stat_stream.str(""); stat_stream << upgrade_selection.crystal_use; game->reload_as_text("Crystal Cost", "display font costs", stat_stream.str(), false, 0); game->set_point("Crystal Cost", 0, 186+game->get_spot("Crystal Cost").w/2, 552); game->set_active("Crystal Cost", true); stat_stream.str(""); } } if (is_selling){ stat_stream << selection_data.metal_sell; game->reload_as_text("Sell Metal Cost", "display font costs", stat_stream.str(), false, 0); game->set_point("Sell Metal Cost", 0, 32+game->get_spot("Sell Metal Cost").w/2, 622); game->set_active("Sell Metal Cost", true); stat_stream.str(""); stat_stream << selection_data.wood_sell; game->reload_as_text("Sell Wood Cost", "display font costs", stat_stream.str(), false, 0); game->set_point("Sell Wood Cost", 0, 109+game->get_spot("Sell Wood Cost").w/2, 622); game->set_active("Sell Wood Cost", true); stat_stream.str(""); stat_stream << selection_data.crystal_sell; game->reload_as_text("Sell Crystal Cost", "display font costs", stat_stream.str(), false, 0); game->set_point("Sell Crystal Cost", 0, 186+game->get_spot("Sell Crystal Cost").w/2, 622); game->set_active("Sell Crystal Cost", true); stat_stream.str(""); } else { game->set_active("Sell Metal Cost", false); game->set_active("Sell Wood Cost", false); game->set_active("Sell Crystal Cost", false); } } void td_module::build_tower_click(){ //COME HERE FROM BUILD STATE //CHECK IF THE POINT IS BUILDABLE FIRST tower_found(); if (can_build_on_point() && !level_playing && selected_tower_index == -1){ //CHECK IF RESOURCES ARE AVAILABLE //RESOURCE CHECKING IN A SEPARATE FUNCTION BECAUSE OF UGLY NESTING REQUIRED if (have_resources()){ //BUILD THE TOWER AT THAT POINT //std::cout << "Building tower..." << std::endl; //adding the tower create_tower(); draw_grid(); //selecting the new tower observe_grid_click(); draw_towers(); //UPDATE THE BOARD draw_board(); } //NOTIFY THERE IS NOT ENOUGH OF THE GIVEN RESOURCES } else { //NOTIFY THE POINT CANNOT BE BUILT ON //std::cout << "Can't build there!" << std::endl; notification_message = "Can't build there!"; notification_on = true; } if (level_playing){ notification_message = "Can't build while level is playing!"; } extern main_controller* game; game->clear_points("Tower Select"); set_build_click(BUILD_BUTTON_NONE); } bool td_module::have_resources(){ extern td_level_loader* table; int metal_to_use = table->get_tower_data(tower_data_name).metal_use; int wood_to_use = table->get_tower_data(tower_data_name).wood_use; int crystal_to_use = table->get_tower_data(tower_data_name).crystal_use; if (td_resources.at("Metal").use_resource(metal_to_use)){ if (td_resources.at("Wood").use_resource(wood_to_use)){ if (td_resources.at("Crystal").use_resource(crystal_to_use)){ return true; } else { //REFUND td_resources.at("Metal").add_to_resource(metal_to_use); td_resources.at("Wood").add_to_resource(metal_to_use); //NOTIFY notification_message = "Not enough crystal!"; notification_on = true; } } else { //REFUND td_resources.at("Metal").add_to_resource(metal_to_use); //NOTIFY notification_message = "Not enough lumber!"; notification_on = true; } } else { //NOTIFY notification_message = "Not enough metal!"; notification_on = true; } return false; } void td_module::create_tower(){ ///GET THE TOWER DATA FROM THE TABLE FIRST extern td_level_loader* table; tower_data tower_to_create = table->get_tower_data(tower_data_name); tower_bullet_data bullet_to_create = table->get_bullet_data(tower_to_create.bullet_data_name); std::stringstream ss; ss << tower_to_create.tower_name << total_towers; td_towers.push_back(tower(x_click*SQUARE_SIZE+SQUARE_SIZE/2, y_click*SQUARE_SIZE+SQUARE_SIZE/2, tower_to_create.attack_range, 1, tower_to_create.attack_rate, tower_to_create.new_tile, td_grid.get_grid_data_at_current_point(), tower_data_name, ss.str(), tower_to_create.tower_image, bullet_to_create)); //ADDING AURAS IF NEEDED if (!tower_to_create.auras.empty()){ for (unsigned int i = 0; i < tower_to_create.auras.size(); i++) td_towers.back().add_tower_aura(tower_to_create.auras.at(i)); } td_towers.back().set_towers(&td_towers); td_towers.back().set_bullets(&td_bullets); td_towers.back().set_enemies(&td_enemies); //std::cout << td_towers.back().get_name() << std::endl; add_tower_image(ss.str(), tower_to_create.tower_image); //setting tower base //determining what to set for that grid point first int buildover_tile = determine_buildover(td_towers.back().get_buildover_type(), td_grid.get_grid_data_at_current_point()); td_grid.set_grid_data(buildover_tile); total_towers++; } void td_module::observe_grid_over(){ extern main_controller* game; //FROM DEFAULT STATE game->clear_points("Circle Select"); //CHECK IF ANY TOWER FALLS UNDER THE COORDINATES OF BEING CLICKED for (unsigned int i = 0; i < td_towers.size(); i++) if (td_towers.at(i).get_range()->get_x()/90 == x_click && td_towers.at(i).get_range()->get_y()/90 == y_click) game->add_point("Circle Select", x_click*SQUARE_SIZE+SQUARE_SIZE/2, y_click*SQUARE_SIZE+SQUARE_SIZE/2); } void td_module::build_tower_over(){ extern main_controller* game; //FROM BUILD STATE game->clear_points("Tower Select"); game->add_point("Tower Select",x_click*SQUARE_SIZE+45,y_click*SQUARE_SIZE+45); tower_found(); //NOTIFY IF A BUILDABLE SPOT BY CHANGING TOWER SELECT COLOR if (can_build_on_point() && selected_tower_index == -1){ game->set_color("Tower Select", {0x33,0xFF,0x33,0x00}); } else { game->set_color("Tower Select", {0xFF,0x33,0x33,0x00}); } game->clear_points("Circle Selected"); } bool td_module::over_tower_on_point(){ return true; } bool td_module::can_build_on_point(){ int point_data = td_grid.get_grid_data_at_current_point(); return (point_data != 0 && point_data != 3); } void td_module::upgrade_tower(){ if (selected_tower_index > -1 && !level_playing){ //extern main_controller* game; extern td_level_loader* table; //GETTING TOWER DATA tower_data tower_to_upgrade_into_data = table->get_tower_data(td_towers.at(selected_tower_index).get_display_name()); //CHECK IF THERE IS ACTUALLY AN UPGRADE if (tower_to_upgrade_into_data.has_upgrade){ tower_data_name = tower_to_upgrade_into_data.upgrade_name; if (have_resources()){ //STORING THE CURRENT POINT BEFOREHAND x_click = td_towers.at(selected_tower_index).get_range()->get_x()/90; y_click = td_towers.at(selected_tower_index).get_range()->get_y()/90; //CLEARING PREVIOUS TOWER erase_tower(); td_grid.set_grid_point(x_click, y_click); //GETTING THE TOWER UPGRADE create_tower(); draw_towers(); draw_board(); draw_grid(); selected_tower_index = td_towers.size()-1; observe_grid_click(); } } } if (level_playing){ notification_message = "Can't upgrade while level is playing!"; notification_on = true; } } void td_module::sell_tower(){ if (selected_tower_index > -1 && !level_playing){ extern main_controller* game; extern td_level_loader* table; //GETTING TOWER DATA tower_data tower_to_sell_data = table->get_tower_data(td_towers.at(selected_tower_index).get_display_name()); td_resources.at("Metal").add_to_resource(tower_to_sell_data.metal_sell); td_resources.at("Wood").add_to_resource(tower_to_sell_data.wood_sell); td_resources.at("Crystal").add_to_resource(tower_to_sell_data.crystal_sell); erase_tower(); draw_towers(); draw_board(); draw_grid(); game->clear_points("Circle Selected"); observe_grid_click(); } if (level_playing){ notification_message = "Can't sell while level is playing!"; notification_on = true; } } void td_module::erase_tower(){ remove_tower_image(td_towers.at(selected_tower_index).get_name()); td_grid.set_grid_point(td_towers.at(selected_tower_index).get_range()->get_x()/SQUARE_SIZE, td_towers.at(selected_tower_index).get_range()->get_y()/SQUARE_SIZE); td_grid.set_grid_data(td_towers.at(selected_tower_index).get_old_tile()); td_towers.erase(td_towers.begin()+selected_tower_index); selected_tower_index = -1; draw_grid(); } void td_module::move_up(bool move_state){ moving_up = move_state; } void td_module::move_down(bool move_state){ moving_down = move_state; } void td_module::move_left(bool move_state){ moving_left = move_state; } void td_module::move_right(bool move_state){ moving_right = move_state; } void td_module::start_level(){ if (!level_playing && !td_waves.empty()){ extern td_level_loader* table; std::vector<grid_node<int>> final_path = td_grid.create_path(); level_path.clear(); ///GET THE WAVE FROM THE QUEUE std::queue<std::string> wave_to_load = table->get_wave(td_waves.front()); total_wave_enemies = wave_to_load.size(); td_waves.pop(); unsigned int final_path_index = 0; while (final_path_index < final_path.size()){ std::cout << "(" << final_path.at(final_path_index).x_coord << ", " << final_path.at(final_path_index).y_coord << ") "; level_path.push_back(point(final_path.at(final_path_index).x_coord*90+45, final_path.at(final_path_index).y_coord*90+45)); final_path_index++; } //CHECK IF REACHES THE END if (!level_path.empty()){ level_playing = true; //ADD THE ENEMIES while (!wave_to_load.empty()){ enemy_data_name = wave_to_load.front(); create_enemy(); wave_to_load.pop(); } //SET THE WAVE SIZE FOR TOWERS TO CONSIDER for (unsigned int i = 0; i < td_towers.size(); i++){ td_towers.at(i).set_wave_size(total_wave_enemies); } } else { //NOTIFY THE PATH IS BLOCKED notification_message = "The path is blocked!"; notification_on = true; } } } void td_module::create_enemy(){ extern td_level_loader* table; ///GET THE ENEMY DATA FIRST enemy_data enemy_to_create = table->get_enemy_data(enemy_data_name); //std::cout << "ADDING ENEMY TO THE SPAWN" << std::endl; std::stringstream ss; ss << enemy_to_create.enemy_name << total_enemies; std::cout << ss.str() << std::endl; enemies_to_spawn.push(std::pair<int, enemy>(total_enemies, enemy(enemy_to_create.enemy_hp_base + enemy_to_create.enemy_hp_scale*level.get_resource(), enemy_to_create.enemy_regen_base + enemy_to_create.enemy_regen_scale*level.get_resource(), enemy_to_create.enemy_armor_base + enemy_to_create.enemy_armor_scale*level.get_resource(), enemy_to_create.enemy_armor_type, enemy_to_create.enemy_speed_base + enemy_to_create.enemy_speed_scale*level.get_resource(), level_path.front().get_x(), level_path.front().get_y(), SQUARE_SIZE/2, ss.str(), enemy_to_create.enemy_image_source, enemy_to_create.enemy_metal_bounty_base + enemy_to_create.enemy_metal_bounty_scale*level.get_resource(), enemy_to_create.enemy_wood_bounty_base + enemy_to_create.enemy_wood_bounty_scale*level.get_resource(), enemy_to_create.enemy_crystal_bounty_base + enemy_to_create.enemy_crystal_bounty_scale*level.get_resource(), enemies_to_spawn.size()))); //ADDING TRAVEL PATHS enemies_to_spawn.top().second.set_path(level_path); total_enemies++; } bool td_module::remaining_enemies_to_spawn(){ return !enemies_to_spawn.empty(); } void td_module::spawn_enemy(){ int spawn_index; td_enemies.insert(std::pair<int, enemy>(spawn_index = enemies_to_spawn.top().first, enemies_to_spawn.top().second)); td_enemies.at(spawn_index).activate_enemy_image(); td_enemies.at(spawn_index).create_hp_bar(); enemies_to_spawn.pop(); } void td_module::draw_bullets(){ extern main_controller* game; if (!td_bullets.bullets.empty()){ unsigned int i = 0; while (i < td_bullets.bullets.size()){ game->clear_points(td_bullets.bullets.at(i).get_name()); game->add_point(td_bullets.bullets.at(i).get_name(), td_bullets.bullets.at(i).get_hitbox()->get_x(), td_bullets.bullets.at(i).get_hitbox()->get_y()); i++; } } } void td_module::draw_enemies(){ for (std::map<int, enemy>::iterator enemy_iterator = td_enemies.begin(); enemy_iterator != td_enemies.end(); ++enemy_iterator){ enemy_iterator->second.draw_enemy(); } } void td_module::enemy_bountied(int enemy_index){ td_resources.at("Metal").add_to_resource(td_enemies.at(enemy_index).get_metal_bounty()); td_resources.at("Wood").add_to_resource(td_enemies.at(enemy_index).get_wood_bounty()); td_resources.at("Crystal").add_to_resource(td_enemies.at(enemy_index).get_crystal_bounty()); kill_enemy(enemy_index); draw_board(); } void td_module::enemy_at_end(int enemy_index){ remove_life(); kill_enemy(enemy_index); draw_board(); } void td_module::kill_enemy(int enemy_index){ if (td_enemies.find(enemy_index) != td_enemies.end()){ //ERASE THAT ENEMY td_enemies.at(enemy_index).remove_enemy_image(); td_enemies.erase(enemy_index); } } void td_module::set_selected_map(std::string new_map){ selected_map = new_map; } std::string td_module::get_selected_map(){ return selected_map; } void td_module::set_build_race_one(std::string new_race_one){ build_race_1 = new_race_one; } void td_module::set_build_race_two(std::string new_race_two){ build_race_2 = new_race_two; } void td_module::set_to_race_one(){ load_button_mapping(BUILD_RACE_ONE); set_button_data_set(); } void td_module::set_to_race_two(){ load_button_mapping(BUILD_RACE_TWO); set_button_data_set(); } void td_module::set_tower_data_to_look_up(std::string new_tower_data_name){ tower_data_name = new_tower_data_name; } void td_module::set_enemy_data_to_look_up(std::string new_enemy_data_name){ enemy_data_name = new_enemy_data_name; }
[ "43427173+dprefontaine@users.noreply.github.com" ]
43427173+dprefontaine@users.noreply.github.com
54541ee87ba4a1c68b9a0e1c38dd13f06062101f
b1b1bb6b89d16940708208043068cbe2df47e6df
/Malowanie autostrady/mal.cpp
0ee8cba074cda4978e173812f8788fdfb03a6bac
[]
no_license
Gonthar/ASD
7e847e547b68c32b542eacf41289e066faf32241
9b144b7f158aaf93dd3759c2fdb8a3b03651d1a7
refs/heads/master
2021-01-12T04:36:21.130040
2017-01-17T21:22:12
2017-01-17T21:22:12
77,688,676
0
0
null
null
null
null
UTF-8
C++
false
false
2,688
cpp
#include <iostream> #include <algorithm> #include <vector> #define MAX_N 1000000 long n; //road length long size; //structure size long w[4 * MAX_N]; bool act[4 * MAX_N]; long findX(long n) { int tmp = n; while (tmp < size) tmp *= 2; return tmp - size; } long findY(long n) { int tmp = n; while (tmp < size) tmp = (tmp * 2 + 1); return tmp - size; } //zacząć od [a, b], 1 void push(long a, long b, long v) { long x, y; x = findX(v); y = findY(v); if (x >= a && y <= b) return; if (y < a || x > b) return; if (act[v] == true) { w[v * 2] = w[v] / 2; w[v * 2 + 1] = w[v] / 2; act[v * 2] = true; act[v * 2 + 1] = true; act[v] = false; } push(a, b, v * 2); push(a, b, v * 2 + 1); } long value(long v) { long x, y; x = findX(v); y = findY(v); return y - x + 1; } void insert(long a, long b, int v) { push(a, b, 1); long va = size + a, vb = size + b; w[va] = (v == 0) ? 0 : value(va); act[va] = true; if (a != b){ w[vb] = w[va]; act[vb] = true; } while (va != 1) { if (va / 2 != vb / 2) { if (va % 2 == 0) { w[va + 1] = (v == 0) ? 0 : value(va); act[va + 1] = true; } if (vb % 2 == 1) { w[vb - 1] = (v == 0) ? 0 : value(vb); act[vb - 1] = true; } } va /= 2; vb /= 2; w[va] = w[va * 2] + w[va * 2 + 1]; w[vb] = w[vb * 2] + w[vb * 2 + 1]; } w[1] = w[2] + w[3]; } void update(long x, int val) { long v = size + x; w[v] = val; while(v != 1) { v /= 2; w[v] = w[2 * v] + w[2 * v + 1]; } } long long query(long low, long high, long half, std::vector<unsigned long long>& db) { long vl = half + low; long vh = half + high; unsigned long long res = db[vl]; if(vl != vh) { res += db[vh] % 1000000000; } while(vl / 2 != vh / 2) { if(vl % 2 == 0) { res += db[vl + 1] % 1000000000; } if(vh % 2 == 1) { res += db[vh - 1] % 1000000000; } vl = vl / 2; vh = vh / 2; } return res % 1000000000; } void findTreeLength() { size = 1; while(size < n) { size *= 2; } } int main() { std::ios_base::sync_with_stdio(0); long m = 0; //number of nights long a = 0, b = 0, c = 0; char ch; std::cin >> n >> m; findTreeLength(); for (long i = m; i > 0; --i) { std::cin >> a >> b >> ch; c = (ch == 'C') ? 0 : 1; insert(a, b, c); std::cout << w[1] << std::endl; } }
[ "maciej.gontar@gmail.com" ]
maciej.gontar@gmail.com
2ad44acd0e2d79268dad288e4c34c6d19879f907
86dea79cc10988fb375e388ce6910e6bdcc4be46
/ViniLibCpp/ExceptionExample.cpp
5842d5afbdc186f8d946b704da735a197a23a2bc
[]
no_license
vianalista/ViniLibCpp
c178dec4f3ac0da64418d8f631092f5554244d7e
521ba67d86b523f21e4b12911e1a5fd268eebf5f
refs/heads/master
2021-01-10T02:13:41.372833
2015-10-01T18:47:50
2015-10-01T18:47:50
43,002,596
0
0
null
null
null
null
UTF-8
C++
false
false
1,044
cpp
//Exception #include <iostream> #include "ExceptionExample.h" using namespace std; void ExampleException(void){ KeyWordThrow(); cout << "---------------- \n"; UsingLibraryException(); } void KeyWordThrow(void){ try{ throw 20; } catch (int valueThrow){ cout << " = Code received by expecption valueThrow = " << valueThrow << endl; } } //================================ overwrite the derived classes [what]=========== #include <exception> class CDaughterExceptionClass : public exception{ virtual const char *what() const throw(){ return " = CDaughterExceptionClass::what() My mensage aboult the exception."; } }MyWhat; /** * The C++ Standard library provides a class [expection] that contain a class [what] * We can overwrite the derived classes [what]. */ void UsingLibraryException(){ try{ throw MyWhat; } // Notice "&"(ampersand), to create a object by reference. catch (exception &objException){ cout << objException.what() << endl; } }
[ "vianalista@gmail.com" ]
vianalista@gmail.com
dfc3e03a390f4a6900b086acc119c85bc66e857d
b147e873c00741785dbe9cb00bcbcaa07524c402
/Examples/include/asposecpplib/system/convert.h
7f78aa1a2a2550a7b1b68e04a4c467f4b6d2f7e3
[ "MIT" ]
permissive
aliahmedaspose/Aspose.PDF-for-C
252dbac94ec8643de74c313e87f76ff2a861d886
fe860e5ad490993dc5b3ee39762763a8662bad60
refs/heads/master
2020-04-26T17:58:54.914004
2019-06-04T21:15:11
2019-06-04T21:15:11
173,730,780
0
0
null
2019-03-04T11:18:02
2019-03-04T11:18:02
null
UTF-8
C++
false
false
91,355
h
/// @file system/convert.h /// Contains declarations of System::Convert class. #ifndef _aspose_system_convert_h_ #define _aspose_system_convert_h_ #include "system/object.h" #include "system/shared_ptr.h" #include "fwd.h" #include "system/primitive_types.h" #include "system/math.h" #include "system/exceptions.h" #include "system/array.h" #include "system/decimal.h" #include "system/date_time.h" #include "system/globalization/number_style.h" #include "system/globalization/culture_info.h" #include "system/iformatprovider.h" #include "system/guid.h" #include "system/type_code.h" #include <bitset> #include <iostream> #include <iomanip> #include <cwctype> #include <type_traits> #include "globalization/convert_impl.h" /// Declares a static method that accepts a value of type @p from as an argument and returns a value of type @p type. #define ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO_2(name, type, from) \ static ASPOSECPP_SHARED_API type To##name(from value); /// Declares several methods such that each of them accepts a value of a primitive type and returns a value of type @p type_. #define ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO(name, type_) \ ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO_2(name, type_, char); \ ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO_2(name, type_, unsigned char); \ ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO_2(name, type_, short); \ ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO_2(name, type_, unsigned short); \ ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO_2(name, type_, int); \ ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO_2(name, type_, unsigned int); \ ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO_2(name, type_, long); \ ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO_2(name, type_, unsigned long); \ ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO_2(name, type_, long long); \ ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO_2(name, type_, unsigned long long); \ ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO_2(name, type_, float); \ ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO_2(name, type_, double); \ template <typename Enum, typename = typename std::enable_if<std::is_enum<Enum>::value, int>::type> static type_ To##name(Enum value) \ { \ return To##name(static_cast<typename std::underlying_type<Enum>::type>(value)); \ } namespace System { /// Enumeration containing values that represent different formats of base-64 encoded data. enum class Base64FormattingOptions { /// No formatting None = 0, /// Insert line breaks after every 76th character InsertLineBreaks = 1, }; /// The structure that contains methods performing conversion of values of one type to the values of another type. /// This type should be allocated on stack and passed to functions by value or by reference. /// Never use System::SmartPtr class to manage objects of this type. struct Convert { /// NOT IMPLEMENTED /// @throws NotImplementedException Always static ASPOSECPP_SHARED_API SharedPtr<Object> ChangeType(const SharedPtr<Object>& value, const TypeInfo& conversionType); /// NOT IMPLEMENTED /// @throws NotImplementedException Always template<typename T> static std::enable_if_t<!IsSmartPtr<T>::value, bool> IsDBNull(const T&) { throw System::NotImplementedException(ASPOSE_CURRENT_FUNCTION); } /// NOT IMPLEMENTED /// Fake implementation, checks if value is nullptr template<typename T> static bool IsDBNull(const SharedPtr<T>& value) { return value == nullptr; } // ---------- Base64 Conversions ---------- /// Base-64 encodes a range of elements in the specified byte array and stores the encoded data as an array of Unicode characters. /// @param inArray The array of bytes containing the range of elements to encode /// @param offsetIn An index of an element in the input array at which the range to encode begins /// @param length The length of the range of elements to encode /// @param outArray A constant reference to the output array to which the resulting data is to be put /// @param offsetOut An index in the output array at which to start putting the resulting data /// @param insertLineBreaks Specifies whether the line break characters are to be inserted in the output array after every 76 base-64 characters /// @returns The number of characters written to the output array static ASPOSECPP_SHARED_API int ToBase64CharArray(const ArrayPtr<uint8_t>& inArray, int offsetIn, int length, const ArrayPtr<char16_t>& outArray, int offsetOut, bool insertLineBreaks = false); /// Base-64 encodes elements in the specified byte array and returns the encoded data as a string. /// @param inArray The array of bytes to encode /// @param insertLineBreaks Specifies whether line break characters are to be inserted in the output string after every 76 base-64 characters /// @returns The string containing the base-64 encoded representation of the input array static ASPOSECPP_SHARED_API String ToBase64String(const ArrayPtr<uint8_t>& inArray, bool insertLineBreaks = false); /// Base-64 encodes a range of elements in the specified byte array and returns the encoded data as a string. /// @param inArray The array of bytes containing the range of elements to encode /// @param offsetIn An index of an element in the input array at which the range to encode begins /// @param length The length of the range of elements to encode /// @param insertLineBreaks Specifies whether line break characters are to be inserted in the output string after every 76 base-64 characters /// @returns The string containing the base-64 encoded representation of the range of elements of the input array static ASPOSECPP_SHARED_API String ToBase64String(const ArrayPtr<uint8_t>& inArray, int offsetIn, int length, bool insertLineBreaks = false); /// Base-64 encodes a range of elements in the specified byte array and stores the encoded data as an array of Unicode characters. /// @param inArray The array of bytes containing the range of elements to encode /// @param offsetIn An index of an element in the input array at which the range to encode begins /// @param length The length of the range of elements to encode /// @param outArray A constant reference to the output array to which the resulting data is to be put /// @param offsetOut An index in the output array at which to start putting the resulting data /// @param options Specifies formatting options of base-64 encoded data /// @returns The number of characters written to the output array static ASPOSECPP_SHARED_API int ToBase64CharArray(const ArrayPtr<uint8_t>& inArray, int offsetIn, int length, const ArrayPtr<char_t>& outArray, int offsetOut, Base64FormattingOptions options); /// Base-64 encodes elements in the specified byte array and returns the encoded data as a string. /// @param inArray The array of bytes to encode /// @param options Specifies formatting options of base-64 encoded data /// @returns The string containing the base-64 encoded representation of the input array static ASPOSECPP_SHARED_API String ToBase64String(const ArrayPtr<uint8_t>& inArray, Base64FormattingOptions options); /// Base-64 encodes a range of elements in the specified byte array and returns the encoded data as a string. /// @param inArray The array of bytes containing the range of elements to encode /// @param offsetIn An index of an element in the input array at which the range to encode begins /// @param length The length of the range of elements to encode /// @param options Specifies formatting options of base-64 encoded data /// @returns The string containing the base-64 encoded representation of the range of elements of the input array static ASPOSECPP_SHARED_API String ToBase64String(const ArrayPtr<uint8_t>& inArray, int offsetIn, int length, Base64FormattingOptions options); /// Decodes base-64 encoded data represented as a range in the array of Unicode characters. /// @param inArray The array containing the data to decode /// @param offset The position in the input array at which the range to decode begins /// @param length The length of the range to decode /// @returns A byte-array containing the decoded data static ASPOSECPP_SHARED_API ArrayPtr<uint8_t> FromBase64CharArray(const ArrayPtr<char_t>& inArray, int offset, int length); /// Decodes base-64 encoded data represented as a string. /// @param s The string containing the base-64 encoded data to decode /// @returns A byte-array containing the decoded data static ASPOSECPP_SHARED_API ArrayPtr<uint8_t> FromBase64String(const String& s); // ---------- Boolean Conversions ---------- /// Template method that converts the value of the specified type to the value of bool type. /// @param value The value to convert /// @returns True if the specified value is not equal to 0, otherwise - false /// @tparam T The type of the value to convert template <typename T> static bool ToBoolean(T value) { return value != 0; } /// Returns the specified bool value. /// @param value The value to return /// @returns The specified value static ASPOSECPP_SHARED_API bool ToBoolean(bool value); /// Converts the specified c-string to the value of bool type. /// @param value The c-string to convert /// @returns True if the specified c-string is equal to "True" and false if the specified c-string is equal to "False". /// @throws FormatException If the specified c-string is not equal to "True" or "False". static bool ToBoolean(const char_t* value) { return ToBoolean(String(value)); } /// Converts the specified string to the value of bool type. /// @param value The string to convert /// @returns True if the specified c-string is equal to "True" and false if the specified string is equal to "False". /// @throws FormatException If the specified string is not equal to "True" or "False". static ASPOSECPP_SHARED_API bool ToBoolean(const String& value); /// Converts the specified value to the value of bool type. /// @param value The value to convert /// @returns True if the specified value is not equal to 0, otherwise - false /// @tparam T The type of the value to convert static ASPOSECPP_SHARED_API bool ToBoolean(const Decimal& value); /// The template method that converts the specified instance of SharedPtr<> to the value of bool type. /// @param value The value to convert /// @returns True if the specified shared pointer value is not a null-pointer, otherwise - false /// @tparam U The type of the value pointed to by the specified shared pointer template <typename U> static bool ToBoolean(const SharedPtr<U>& value) { return value != 0; } // ---------- Byte Conversions ---------- /// Converts the specified string containing the string representation of a number /// to the equivalent unsigned 8-bit integer value by invoking the proper overload /// of Convert::ToByte() method /// @param value The string to convert /// @param args The arguments passed to the corresponding overload of ToByte() method /// @returns The unsigned 8-bit integer value equal to the number represented by the specified string /// @tparam Args The types of all arguments passed to the method except the first argument template <class... Args> static uint8_t ToByteNative(const String& value, Args... args) { if (value.IsNull()) return 0; return ToByte(value, args...); } /// Declaration of methods that convert values of primitive types to an unsigned 8-bit integer value. ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO(Byte, uint8_t); /// Converts the specified bool value to the unsigned 8-bit integer value. /// @param value The value to convert /// @returns 1 if the specified value is true, otherwise - 0 static ASPOSECPP_SHARED_API uint8_t ToByte(bool value); /// Converts the specified Decimal value to the unsigned 8-bit integer value. /// @param value The value to convert /// @returns The unsigned 8-bit integer value equivalent to the specified Decimal value static ASPOSECPP_SHARED_API uint8_t ToByte(const Decimal& value); /// Converts the specified c-string containing the string representation of a number to the equivalent unsigned 8-bit integer value. /// @param value The c-string to convert /// @returns The unsigned 8-bit integer value equal to the number represented by the specified c-string /// @throws FormatException If the specified c-string does not represent a number /// @throws OverflowException If the number represented by the specified c-string is greater than UINT8_MAX or is a negative number static uint8_t ToByte(const char_t* value) { return ToByte(String(value)); } /// Converts the specified string containing the string representation of a number to the equivalent unsigned 8-bit integer value. /// @param value The string to convert /// @returns The unsigned 8-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than UINT8_MAX or is a negative number static ASPOSECPP_SHARED_API uint8_t ToByte(const String& value); /// Converts the specified string containing the string representation of a number in the specified base to the equivalent unsigned 8-bit integer value. /// @param value The string to convert /// @param fromBase The base of the number represented by the string /// @returns The unsigned 8-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than UINT8_MAX or is a negative number static ASPOSECPP_SHARED_API uint8_t ToByte(const String& value, int fromBase); /// Converts the specified string containing the string representation of a number to the equivalent unsigned 8-bit integer value using the provided formatting information. /// @param value The string to convert /// @param fp A pointer to an object that contains the string format information /// @returns The unsigned 8-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than UINT8_MAX or is a negative number static ASPOSECPP_SHARED_API uint8_t ToByte(const String& value, const SharedPtr<IFormatProvider>& fp); /// Converts the specified string containing the string representation of a number to the equivalent unsigned 8-bit integer value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @returns The unsigned 8-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than UINT8_MAX or is a negative number static ASPOSECPP_SHARED_API uint8_t ToByte(const String& value, Globalization::NumberStyles style, const SharedPtr<IFormatProvider>& fp = nullptr); /// Converts the specified string containing the string representation of a number /// to the equivalent 8-bit integer value by invoking the proper overload /// of Convert::SToByte() method /// @param value The string to convert /// @param args The arguments passed to the corresponding overload of ToSByte() method /// @returns The 8-bit integer value equal to the number represented by the specified string /// @tparam Args The types of all arguments passed to the method except the first argument template <class... Args> static int8_t ToSByteNative(const String& value, Args... args) { if (value.IsNull()) return 0; return ToSByte(value, args...); } /// Declaration of methods that convert values of primitive types to a 8-bit integer value. ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO(SByte, int8_t); /// Converts the specified bool value to the 8-bit integer value. /// @param value The value to convert /// @returns 1 if the specified value is true, otherwise - 0 static ASPOSECPP_SHARED_API int8_t ToSByte(bool value); /// Converts the specified Decimal value to the 8-bit integer value. /// @param value The value to convert /// @returns The 8-bit integer value equivalent to the specified Decimal value static ASPOSECPP_SHARED_API int8_t ToSByte(const Decimal& value); /// Converts the specified c-string containing the string representation of a number to the equivalent 8-bit integer value. /// @param value The c-string to convert /// @returns The 8-bit integer value equal to the number represented by the specified c-string /// @throws FormatException If the specified c-string does not represent a number /// @throws OverflowException If the number represented by the specified c-string is greater than INT8_MAX or less that INT8_MIN static int8_t ToSByte(const char_t* value) { return ToSByte(String(value)); } /// Converts the specified string containing the string representation of a number to the equivalent 8-bit integer value. /// @param value The string to convert /// @returns The 8-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than INT8_MAX or less than INT8_MIN static ASPOSECPP_SHARED_API int8_t ToSByte(const String& value); /// Converts the specified string containing the string representation of a number in the specified base to the equivalent 8-bit integer value. /// @param value The string to convert /// @param fromBase The base of the number represented by the string /// @returns The 8-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than INT8_MAX or less than INT8_MIN static ASPOSECPP_SHARED_API int8_t ToSByte(const String& value, int fromBase); /// Converts the specified string containing the string representation of a number to the equivalent unsigned 8-bit integer value using the provided formatting information. /// @param value The string to convert /// @param fp A pointer to an object that contains the string format information /// @returns The 8-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than INT8_MAX or less than INT8_MIN static ASPOSECPP_SHARED_API int8_t ToSByte(const String& value, const SharedPtr<IFormatProvider>& fp); /// Converts the specified string containing the string representation of a number to the equivalent 8-bit integer value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @returns The unsigned 8-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than INT8_MAX or is less than INT8_MIN static ASPOSECPP_SHARED_API int8_t ToSByte(const String& value, Globalization::NumberStyles style, const SharedPtr<IFormatProvider>& fp = nullptr); // ---------- Char Conversions ---------- /// Declaration of methods that convert values of primitive types to a char. ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO(Char, char_t); /// Template method that converts the value of the specified type to the value of char_t type. /// @param value The value to convert /// @returns Char representation of value passed. /// @tparam T The type of the value to convert template <typename T> static inline char_t ToChar(T value, const System::SharedPtr<IFormatProvider>&) { return ToChar(value); } /// Converts the first and the only character of the specified c-string to a char_t value. /// @param value The c-string to convert; it is expected that the c-string be exactly 1 character long. /// @returns The first and the only character of the specified c-string if it is exactly 1 characetr long, otherwise - 0 static char_t ToChar(const char_t* value) { return ToChar(String(value)); } /// Converts the first and the only character of the specified string to a char_t value. /// @param value The string to convert; it is expected that the string be exactly 1 character long /// @returns The first and the only character of the specified string if it is exactly 1 characetr long, otherwise - 0 static ASPOSECPP_SHARED_API char_t ToChar(const String& value); // ---------- Int16 Conversions ---------- /// Converts the specified string containing the string representation of a number /// to the equivalent 16-bit integer value by invoking the proper overload /// of Convert::ToInt16() method /// @param value The string to convert /// @param args The arguments passed to the corresponding overload of ToInt16() method /// @returns The 16-bit integer value equal to the number represented by the specified string /// @tparam Args The types of all arguments passed to the method except the first argument template <class... Args> static int16_t ToInt16Native(const String& value, Args... args) { if (value.IsNull()) return 0; return ToInt16(value, args...); } /// Declaration of methods that convert values of primitive types to a 16-bit integer value. ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO(Int16, int16_t); /// Converts the specified bool value to the 16-bit integer value. /// @param value The value to convert /// @returns 1 if the specified value is true, otherwise - 0 static ASPOSECPP_SHARED_API int16_t ToInt16(bool value); /// Converts the specified c-string containing the string representation of a number to the equivalent 16-bit integer value. /// @param value The c-string to convert /// @returns The 16-bit integer value equal to the number represented by the specified c-string /// @throws FormatException If the specified c-string does not represent a number /// @throws OverflowException If the number represented by the specified c-string is greater than INT16_MAX or less that INT16_MIN static int16_t ToInt16(const char_t* value) { return ToInt16(String(value)); } /// Converts the specified Decimal value to the 16-bit integer value. /// @param value The value to convert /// @returns The 16-bit integer value equivalent to the specified Decimal value static ASPOSECPP_SHARED_API int16_t ToInt16(const Decimal &value); /// Converts the specified string containing the string representation of a number to the equivalent 16-bit integer value. /// @param value The string to convert /// @returns The 16-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than INT16_MAX or less than INT16_MIN static ASPOSECPP_SHARED_API int16_t ToInt16(const String& value); /// Converts the specified string containing the string representation of a number in the specified base to the equivalent 16-bit integer value. /// @param value The string to convert /// @param fromBase The base of the number represented by the string /// @returns The 16-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than INT16_MAX or less than INT16_MIN static ASPOSECPP_SHARED_API int16_t ToInt16(const String& value, int fromBase); /// Converts the specified string containing the string representation of a number to the equivalent 16-bit integer value using the provided formatting information. /// @param value The string to convert /// @param fp A pointer to an object that contains the string format information /// @returns The 16-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than INT16_MAX or less than INT16_MIN static ASPOSECPP_SHARED_API int16_t ToInt16(const String& value, const SharedPtr<IFormatProvider>& fp); /// Converts the specified string containing the string representation of a number to the equivalent 16-bit integer value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @returns The 16-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than INT16_MAX or is less than INT16_MIN static ASPOSECPP_SHARED_API int16_t ToInt16(const String& value, System::Globalization::NumberStyles style, const SharedPtr<IFormatProvider>& fp = nullptr); /// Converts the specified string containing the string representation of a number /// to the equivalent unsigned 86-bit integer value by invoking the proper overload /// of Convert::UInt16() method /// @param value The string to convert /// @param args The arguments passed to the corresponding overload of ToUInt16() method /// @returns The unsigned 16-bit integer value equal to the number represented by the specified string /// @tparam Args The types of all arguments passed to the method except the first argument template <class... Args> static uint16_t ToUInt16Native(const String& value, Args... args) { if (value.IsNull()) return 0; return ToUInt16(value, args...); } /// Declaration of methods that convert values of primitive types to an unsigned 16-bit integer value. ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO(UInt16, uint16_t); /// Converts the specified bool value to the unsigned 16-bit integer value. /// @param value The value to convert /// @returns 1 if the specified value is true, otherwise - 0 static ASPOSECPP_SHARED_API uint16_t ToUInt16(bool value); /// Converts the specified c-string containing the string representation of a number to the equivalent unsigned 16-bit integer value. /// @param value The c-string to convert /// @returns The unsigned 16-bit integer value equal to the number represented by the specified c-string /// @throws FormatException If the specified c-string does not represent a number /// @throws OverflowException If the number represented by the specified c-string is greater than UINT16_MAX or is a negative number static uint16_t ToUInt16(const char_t* value) { return ToUInt16(String(value)); } /// Converts the specified Decimal value to the unsigned 16-bit integer value. /// @param value The value to convert /// @returns The unsigned 16-bit integer value equivalent to the specified Decimal value static ASPOSECPP_SHARED_API uint16_t ToUInt16(const Decimal &value); /// Converts the specified string containing the string representation of a number to the equivalent unsigned 16-bit integer value. /// @param value The string to convert /// @returns The unsigned 16-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than UINT16_MAX or is a negative number static ASPOSECPP_SHARED_API uint16_t ToUInt16(const String& value); /// Converts the specified string containing the string representation of a number in the specified base to the equivalent unsigned 16-bit integer value. /// @param value The string to convert /// @param fromBase The base of the number represented by the string /// @returns The unsigned 16-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than UINT16_MAX or is a negative number static ASPOSECPP_SHARED_API uint16_t ToUInt16(const String& value, int fromBase); /// Converts the specified string containing the string representation of a number to the equivalent unsigned 16-bit integer value using the provided formatting information. /// @param value The string to convert /// @param fp A pointer to an object that contains the string format information /// @returns The unsigned 16-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than UINT16_MAX or is a negative number static ASPOSECPP_SHARED_API uint16_t ToUInt16(const String& value, const SharedPtr<IFormatProvider>& fp); /// Converts the specified string containing the string representation of a number to the equivalent unsigned 16-bit integer value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @returns The unsigned 16-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than UINT16_MAX or is a negative number static ASPOSECPP_SHARED_API uint16_t ToUInt16(const String& value, System::Globalization::NumberStyles style, const SharedPtr<IFormatProvider>& fp = nullptr); // ---------- Int32 Conversions ---------- /// Converts the specified string containing the string representation of a number /// to the equivalent 32-bit integer value by invoking the proper overload /// of Convert::ToInt32() method /// @param value The string to convert /// @param args The arguments passed to the corresponding overload of ToInt32() method /// @returns The 32-bit integer value equal to the number represented by the specified string /// @tparam Args The types of all arguments passed to the method except the first argument template <class... Args> static int ToInt32Native(const String& value, Args... args) { if (value.IsNull()) return 0; return ToInt32(value, args...); } /// Declaration of methods that convert values of primitive types to a 32-bit integer value. ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO(Int32, int); /// Converts the specified value to the 32-bit integer value. /// @param value The value to convert /// @returns A 32-bit integer value equivalent to the specified value /// @tparam T The type of the value to convert template <typename T> static int ToInt32(T value, const SharedPtr<IFormatProvider>&) { return ToInt32(value); } /// Converts the specified bool value to the 32-bit integer value. /// @param value The value to convert /// @returns 1 if the specified value is true, otherwise - 0 static ASPOSECPP_SHARED_API int ToInt32(bool value); /// Converts the specified c-string containing the string representation of a number to the equivalent 32-bit integer value. /// @param value The c-string to convert /// @returns The 32-bit integer value equal to the number represented by the specified c-string /// @throws FormatException If the specified c-string does not represent a number /// @throws OverflowException If the number represented by the specified c-string is greater than INT16_MAX or less that INT32_MIN static int ToInt32(const char_t* value) { return ToInt32(String(value)); } /// Converts the specified string containing the string representation of a number to the equivalent 32-bit integer value. /// @param value The string to convert /// @returns The 32-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than INT32_MAX or less than INT32_MIN static ASPOSECPP_SHARED_API int ToInt32(const String& value); /// Converts the specified Decimal value to the 32-bit integer value. /// @param value The value to convert /// @returns The 32-bit integer value equivalent to the specified Decimal value static ASPOSECPP_SHARED_API int ToInt32(const Decimal &value); /// Converts the specified string containing the string representation of a number in the specified base to the equivalent 32-bit integer value. /// @param value The string to convert /// @param fromBase The base of the number represented by the string /// @returns The 32-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than INT32_MAX or less than INT32_MIN static ASPOSECPP_SHARED_API int ToInt32(const String& value, int fromBase); /// Converts the specified string containing the string representation of a number to the equivalent 32-bit integer value using the provided formatting information. /// @param value The string to convert /// @param fp A pointer to an object that contains the string format information /// @returns The 32-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than INT32_MAX or less than INT32_MIN static ASPOSECPP_SHARED_API int ToInt32(const String& value, const SharedPtr<IFormatProvider>& fp); /// Converts the specified string containing the string representation of a number to the equivalent 32-bit integer value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @returns The 32-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than INT32_MAX or is less than INT32_MIN static ASPOSECPP_SHARED_API int ToInt32(const String& value, Globalization::NumberStyles style, const SharedPtr<IFormatProvider>& fp = nullptr); // ---------- UInt32 Conversions ---------- /// Converts the specified string containing the string representation of a number /// to the equivalent unsigned 32-bit integer value by invoking the proper overload /// of Convert::ToUInt32() method /// @param value The string to convert /// @param args The arguments passed to the corresponding overload of ToUInt32() method /// @returns The unsigned 32-bit integer value equal to the number represented by the specified string /// @tparam Args The types of all arguments passed to the method except the first argument template <class... Args> static uint32_t ToUInt32Native(const String& value, Args... args) { if (value.IsNull()) return 0; return ToUInt32(value, args...); } /// Declaration of methods that convert values of primitive types to an unsigned 32-bit integer value. ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO(UInt32, uint32_t); /// Converts the specified bool value to the unsigned 32-bit integer value. /// @param value The value to convert /// @returns 1 if the specified value is true, otherwise - 0 static ASPOSECPP_SHARED_API uint32_t ToUInt32(bool value); /// Converts the specified c-string containing the string representation of a number to the equivalent unsigned 32-bit integer value. /// @param value The c-string to convert /// @returns The unsigned 32-bit integer value equal to the number represented by the specified c-string /// @throws FormatException If the specified c-string does not represent a number /// @throws OverflowException If the number represented by the specified c-string is greater than UINT32_MAX or is a negative number static uint32_t ToUInt32(const char_t* value) { return ToUInt32(String(value)); } /// Converts the specified string containing the string representation of a number to the equivalent unsigned 32-bit integer value. /// @param value The string to convert /// @returns The unsigned 32-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than UINT32_MAX or is a negative number static ASPOSECPP_SHARED_API uint32_t ToUInt32(const String& value); /// Converts the specified string containing the string representation of a number in the specified base to the equivalent unsigned 32-bit integer value. /// @param value The string to convert /// @param fromBase The base of the number represented by the string /// @returns The unsigned 32-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than UINT32_MAX or is a negative number static ASPOSECPP_SHARED_API uint32_t ToUInt32(const String& value, int fromBase); /// Converts the specified string containing the string representation of a number to the equivalent unsigned 32-bit integer value using the provided formatting information. /// @param value The string to convert /// @param fp A pointer to an object that contains the string format information /// @returns The unsigned 32-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than UINT32_MAX or is a negative number static ASPOSECPP_SHARED_API uint32_t ToUInt32(const String& value, const SharedPtr<IFormatProvider>& fp); /// Converts the specified string containing the string representation of a number to the equivalent unsigned 32-bit integer value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @returns The unsigned 32-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than UINT32_MAX or is a negative number static ASPOSECPP_SHARED_API uint32_t ToUInt32(const String& value, System::Globalization::NumberStyles style, const SharedPtr<IFormatProvider>& fp = nullptr); // ---------- TryParse Conversions ---------- /// Converts the specified string containing the string representation of a number to the equivalent 8-bit integer value. /// @param value The string to convert /// @param result The reference to a 8-bit integer variable where the result of the conversion is put /// @returns True if the conversion succeeded, otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, int8_t &result); /// Converts the specified string containing the string representation of a number to the equivalent 8-bit integer value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @param result The reference to a 8-bit integer variable where the result of the conversion is put /// @returns True if the conversion succeeded, otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, System::Globalization::NumberStyles style, const SharedPtr<IFormatProvider>& fp, int8_t &result); /// Converts the specified string containing the string representation of a number to the equivalent unsigned 8-bit integer value. /// @param value The string to convert /// @param result The reference to an unsigned 8-bit integer variable where the result of the conversion is put /// @returns True if the conversion succeeded, otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, uint8_t &result); /// Converts the specified string containing the string representation of a number to the equivalent unsigned 8-bit integer value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @param result The reference to an unsigned 8-bit integer variable where the result of the conversion is put /// @returns True if the conversion succeeded, otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, System::Globalization::NumberStyles style, const SharedPtr<IFormatProvider>& fp, uint8_t &result); /// Converts the specified string containing the string representation of a number to the equivalent 32-bit integer value. /// @param value The string to convert /// @param result The reference to a 32-bit integer variable where the result of the conversion is put /// @returns True if the conversion succeeded, otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, int32_t &result); /// Converts the specified string containing the string representation of a number to the equivalent 32-bit integer value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @param result The reference to a 32-bit integer variable where the result of the conversion is put /// @returns True if the conversion succeeded, otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, System::Globalization::NumberStyles style, const SharedPtr<IFormatProvider>& fp, int32_t &result); /// Converts the specified string containing the string representation of a number to the equivalent unsigned 32-bit integer value. /// @param value The string to convert /// @param result The reference to an unsigned 32-bit integer variable where the result of the conversion is put /// @returns True if the conversion succeeded, otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, uint32_t &result); /// Converts the specified string containing the string representation of a number to the equivalent unsigned 32-bit integer value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @param result The reference to an unsigned 32-bit integer variable where the result of the conversion is put /// @returns True if the conversion succeeded, otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, System::Globalization::NumberStyles style, const SharedPtr<IFormatProvider>& fp, uint32_t &result); /// Converts the specified string containing the string representation of a number to the equivalent 16-bit integer value. /// @param value The string to convert /// @param result The reference to a 16-bit integer variable where the result of the conversion is put /// @returns True if the conversion succeeded, otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, int16_t &result); /// Converts the specified string containing the string representation of a number to the equivalent 16-bit integer value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @param result The reference to a 16-bit integer variable where the result of the conversion is put /// @returns True if the conversion succeeded, otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, System::Globalization::NumberStyles style, const SharedPtr<IFormatProvider>& fp, int16_t &result); /// Converts the specified string containing the string representation of a number to the equivalent unsigned 16-bit integer value. /// @param value The string to convert /// @param result The reference to an unsigned 16-bit integer variable where the result of the conversion is put /// @returns True if the conversion succeeded, otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, uint16_t &result); /// Converts the specified string containing the string representation of a number to the equivalent unsigned 16-bit integer value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @param result The reference to an unsigned 16-bit integer variable where the result of the conversion is put /// @returns True if the conversion succeeded, otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, System::Globalization::NumberStyles style, const SharedPtr<IFormatProvider>& fp, uint16_t &result); /// Converts the specified string containing the string representation of a number to the equivalent 64-bit integer value. /// @param value The string to convert /// @param result The reference to a 64-bit integer variable where the result of the conversion is put /// @returns True if the conversion succeeded, otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, int64_t &result); /// Converts the specified string containing the string representation of a number to the equivalent 64-bit integer value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @param result The reference to a 64-bit integer variable where the result of the conversion is put /// @returns True if the conversion succeeded, otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, System::Globalization::NumberStyles style, const SharedPtr<IFormatProvider>& fp, int64_t &result); /// Converts the specified string to a value of bool type. /// @param value The string to convert /// @param result The reference to a bool variable where the result of the conversion is put; the result is true if the specified string is equal to "True" and false if the specified string is equal to "False" /// @returns True if the specified string is equal either to "True" or "False", otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, bool& result); /// Converts the specified string containing the string representation of a number to the equivalent Decimal value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @param result An output argument; contains the result of conversion /// @returns True if the conversion succeeded, otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, System::Globalization::NumberStyles style, const SharedPtr<IFormatProvider>& fp, Decimal &result); // ---------- Int64 Conversions ---------- /// Declaration of methods that convert values of primitive types to a 64-bit integer value. ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO(Int64, int64_t); /// Converts the specified string containing the string representation of a number /// to the equivalent 64-bit integer value by invoking the proper overload /// of Convert::ToInt64() method /// @param value The string to convert /// @param args The arguments passed to the corresponding overload of ToInt64() method /// @returns The 64-bit integer value equal to the number represented by the specified string /// @tparam Args The types of all arguments passed to the method except the first argument template <class... Args> static int64_t ToInt64Native(const String& value, Args... args) { if (value.IsNull()) return 0; return ToInt64(value, args...); } /// Converts the specified bool value to the 64-bit integer value. /// @param value The value to convert /// @returns 1 if the specified value is true, otherwise - 0 static ASPOSECPP_SHARED_API int64_t ToInt64(bool value); /// Converts the specified c-string containing the string representation of a number to the equivalent 64-bit integer value. /// @param value The c-string to convert /// @returns The 64-bit integer value equal to the number represented by the specified c-string /// @throws FormatException If the specified c-string does not represent a number /// @throws OverflowException If the number represented by the specified c-string is greater than INT16_MAX or less that INT64_MIN static int64_t ToInt64(const char_t* value) { return ToInt64(String(value)); } /// Converts the specified Decimal value to the 64-bit integer value. /// @param value The value to convert /// @returns The 64-bit integer value equivalent to the specified Decimal value static ASPOSECPP_SHARED_API int64_t ToInt64(const Decimal &value); /// Converts the specified string containing the string representation of a number to the equivalent 64-bit integer value. /// @param value The string to convert /// @returns The 64-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than INT64_MAX or less than INT64_MIN static ASPOSECPP_SHARED_API int64_t ToInt64(const String& value); /// Converts the specified string containing the string representation of a number in the specified base to the equivalent 64-bit integer value. /// @param value The string to convert /// @param fromBase The base of the number represented by the string /// @returns The 64-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than INT64_MAX or less than INT64_MIN static ASPOSECPP_SHARED_API int64_t ToInt64(const String& value, int fromBase); /// Converts the specified string containing the string representation of a number to the equivalent 64-bit integer value using the provided formatting information. /// @param value The string to convert /// @param fp A pointer to an object that contains the string format information /// @returns The 64-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than INT64_MAX or less than INT64_MIN static ASPOSECPP_SHARED_API int64_t ToInt64(const String& value, const SharedPtr<IFormatProvider>& fp); /// Converts the specified string containing the string representation of a number to the equivalent 64-bit integer value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @returns The 64-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than INT64_MAX or is less than INT64_MIN static ASPOSECPP_SHARED_API int64_t ToInt64(const String& value, Globalization::NumberStyles style, const SharedPtr<IFormatProvider>& fp = nullptr); /// Converts the specified string containing the string representation of a number /// to the equivalent unsigned 64-bit integer value by invoking the proper overload /// of Convert::ToUInt64() method /// @param value The string to convert /// @param args The arguments passed to the corresponding overload of ToUInt64() method /// @returns The unsigned 64-bit integer value equal to the number represented by the specified string /// @tparam Args The types of all arguments passed to the method except the first argument template <class... Args> static uint64_t ToUInt64Native(const String& value, Args... args) { if (value.IsNull()) return 0; return ToUInt64(value, args...); } /// Declaration of methods that convert values of primitive types to an unsigned 64-bit integer value. ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO(UInt64, uint64_t); /// Converts the specified bool value to the unsigned 64-bit integer value. /// @param value The value to convert /// @returns 1 if the specified value is true, otherwise - 0 static ASPOSECPP_SHARED_API uint64_t ToUInt64(bool value); /// Converts the specified c-string containing the string representation of a number to the equivalent unsigned 64-bit integer value. /// @param value The c-string to convert /// @returns The unsigned 64-bit integer value equal to the number represented by the specified c-string /// @throws FormatException If the specified c-string does not represent a number /// @throws OverflowException If the number represented by the specified c-string is greater than UINT64_MAX or is a negative number static uint64_t ToUInt64(const char_t* value) { return ToUInt64(String(value)); } /// Converts the specified string containing the string representation of a number in the specified base to the equivalent unsigned 64-bit integer value. /// @param value The string to convert /// @param fromBase The base of the number represented by the string /// @returns The unsigned 64-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than UINT64_MAX or is a negative number static ASPOSECPP_SHARED_API uint64_t ToUInt64(const String& value, int fromBase = 10); /// Converts the specified string containing the string representation of a number to the equivalent unsigned 64-bit integer value using the provided formatting information. /// @param value The string to convert /// @param fp A pointer to an object that contains the string format information /// @returns The unsigned 64-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than UINT64_MAX or is a negative number static ASPOSECPP_SHARED_API uint64_t ToUInt64(const String& value, const SharedPtr<IFormatProvider>& fp); /// Converts the specified string containing the string representation of a number to the equivalent unsigned 64-bit integer value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @returns The unsigned 64-bit integer value equal to the number represented by the specified string /// @throws FormatException If the specified string does not represent a number /// @throws OverflowException If the number represented by the specified string is greater than UINT64_MAX or is a negative number static ASPOSECPP_SHARED_API uint64_t ToUInt64(const String& value, Globalization::NumberStyles style, SharedPtr<IFormatProvider> fp = nullptr); // ---------- Decimal Conversions ---------- /// Converts the specified string containing the string representation of a number /// to the Decimal object representing equivalent value by invoking the proper overload /// of Convert::ToDecimal() method /// @param value The string to convert /// @param args The arguments passed to the corresponding overload of ToDecimal() method /// @returns An instance of Decimal class representing value equivalent to the number represented by the specified string /// @tparam Args The types of all arguments passed to the method except the first argument template <class... Args> static Decimal ToDecimalNative(const String& value, Args... args) { if (value.IsNull()) return 0; return ToDecimal(value, args...); } /// Template method that converts the value of the specified type to the value of Decimal type. /// @param value The value to convert /// @returns Decimal value equivalent to the specified value /// @tparam T The type of the value to convert template <typename T> static Decimal ToDecimal(T value) { return Decimal(value); } /// Converts the specified bool value to the Decimal value. /// @param value The value to convert /// @returns 1 if the specified value is true, otherwise - 0 static ASPOSECPP_SHARED_API Decimal ToDecimal(bool value); /// Converts the specified c-string containing the string representation of a number to the equivalent Decimal value. /// @param value The c-string to convert /// @returns The Decimal value equal to the number represented by the specified c-string static Decimal ToDecimal(const char_t* value) { return ToDecimal(String(value)); } /// Converts the specified string containing the string representation of a number to the equivalent Decimal value. /// @param value The string to convert /// @returns The Decimal value equal to the number represented by the specified string static ASPOSECPP_SHARED_API Decimal ToDecimal(const String& value); /// Converts the specified string containing the string representation of a number to the equivalent Decimal value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @returns The Decimal value equal to the number represented by the specified string static ASPOSECPP_SHARED_API Decimal ToDecimal(const String& value, Globalization::NumberStyles style, const SharedPtr<IFormatProvider>& fp = nullptr); /// Converts the specified string containing the string representation of a number to the equivalent Decimal value using the provided formatting information. /// @param value The string to convert /// @param fp A pointer to an object that contains the string format information /// @returns The Decimal value equal to the number represented by the specified string static ASPOSECPP_SHARED_API Decimal ToDecimal(const String& value, SharedPtr<System::IFormatProvider> fp); /// Converts the specified string containing the string representation of a number to the equivalent Decimal value. /// @param value The string to convert /// @param result The reference to a Decimal variable where the result of the conversion is put /// @returns True if the conversion succeeded, otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, Decimal& result); // ---------- Single Conversions ---------- /// Converts the specified string containing the string representation of a number /// to the equivalent single-precision floating point value by invoking the proper overload /// of Convert::ToSingle() method /// @param value The string to convert /// @param args The arguments passed to the corresponding overload of ToSingle() method /// @returns The single-precision floating point value equal to the number represented by the specified string /// @tparam Args The types of all arguments passed to the method except the first argument template <class... Args> static float ToSingleNative(const String& value, Args... args) { if (value.IsNull()) return 0; return ToSingle(value, args...); } /// Declaration of methods that convert values of primitive types to a single-precision floating point value. ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO(Single, float); /// Converts the specified Decimal value to the single-precision floating-point value. /// @param value The value to convert /// @returns The single-precision floating-point value equivalent to the specified Decimal value static ASPOSECPP_SHARED_API float ToSingle(const Decimal& value); /// Converts the specified c-string containing the string representation of a number to the equivalent single-precision floating-point value. /// @param value The c-string to convert /// @returns The single-precision floating-point value equal to the number represented by the specified c-string static float ToSingle(const char_t* value) { return ToSingle(String(value)); } /// Converts the specified string containing the string representation of a number to the equivalent single-precision floating-point value. /// @param value The string to convert /// @returns The single-precision floating-point value equal to the number represented by the specified string static ASPOSECPP_SHARED_API float ToSingle(const String& value); /// Converts the specified string containing the string representation of a number to the equivalent single-precision floating-point value using the provided formatting information. /// @param value The string to convert /// @param fp A pointer to an object that contains the string format information /// @returns The single-precision floating-point value equal to the number represented by the specified string static ASPOSECPP_SHARED_API float ToSingle(const String& value, const SharedPtr<IFormatProvider>& fp); /// Converts the specified string containing the string representation of a number to the equivalent single-precision floating-point value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @returns The single-precision floating-point value equal to the number represented by the specified string static ASPOSECPP_SHARED_API float ToSingle(const String& value, System::Globalization::NumberStyles style, const SharedPtr<IFormatProvider>& fp = nullptr); /// Converts the specified string containing the string representation of a number to the equivalent single-precision floating-point value. /// @param value The string to convert /// @param result The reference to a single-precision floating-point variable where the result of the conversion is put /// @returns True if the conversion succeeded, otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, float &result); /// Converts the specified string containing the string representation of a number to the equivalent single-precision floating-point value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @param result The reference to a single-precision floating-point variable where the result of the conversion is put /// @returns True if the conversion succeeded, otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, System::Globalization::NumberStyles style, SharedPtr<IFormatProvider> fp, float &result); // ---------- Double Conversions ---------- /// Converts the specified string containing the string representation of a number /// to the equivalent double-precision floating point value by invoking the proper overload /// of Convert::ToDouble() method /// @param value The string to convert /// @param args The arguments passed to the corresponding overload of ToDouble() method /// @returns The double-precision floating point value equal to the number represented by the specified string /// @tparam Args The types of all arguments passed to the method except the first argument template <class... Args> static double ToDoubleNative(const String& value, Args... args) { if (value.IsNull()) return 0; return ToDouble(value, args...); } /// Declaration of methods that convert values of primitive types to a double-precision floating point value. ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO(Double, double); /// Converts the specified Decimal value to the double-precision floating-point value. /// @param value The value to convert /// @returns The double-precision floating-point value equivalent to the specified Decimal value static ASPOSECPP_SHARED_API double ToDouble(const Decimal& value); /// Converts the specified c-string containing the string representation of a number to the equivalent double-precision floating-point value. /// @param value The c-string to convert /// @returns The double-precision floating-point value equal to the number represented by the specified c-string static double ToDouble(const char_t* value) { return ToDouble(String(value)); } /// Converts the specified string containing the string representation of a number to the equivalent double-precision floating-point value. /// @param value The string to convert /// @returns The double-precision floating-point value equal to the number represented by the specified string static ASPOSECPP_SHARED_API double ToDouble(const String& value); //parameter fp can be SharedPtr<CultureInfo>, SharedPtr<NumberFormatInfo> /// Converts the specified string containing the string representation of a number to the equivalent double-precision floating-point value using the provided formatting information. /// @param value The string to convert /// @param fp A pointer to an object that contains the string format information /// @returns The double-precision floating-point value equal to the number represented by the specified string static ASPOSECPP_SHARED_API double ToDouble(const String& value, const SharedPtr<IFormatProvider>& fp); /// Converts the specified string containing the string representation of a number to the equivalent double-precision floating-point value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @returns The double-precision floating-point value equal to the number represented by the specified string static ASPOSECPP_SHARED_API double ToDouble(const String& value, System::Globalization::NumberStyles style, const SharedPtr<IFormatProvider>& fp = nullptr); /// Converts the specified string containing the string representation of a number to the equivalent double-precision floating-point value. /// @param value The string to convert /// @param result The reference to a double-precision floating-point variable where the result of the conversion is put /// @returns True if the conversion succeeded, otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, double &result); /// Converts the specified string containing the string representation of a number to the equivalent double-precision floating-point value using the provided formatting information and number style. /// @param value The string to convert /// @param style A bitwise combination of values of NumberStyles enum that specifies the permitted style of the string representation of a number /// @param fp A pointer to an object that contains the string format information /// @param result The reference to a double-precision floating-point variable where the result of the conversion is put /// @returns True if the conversion succeeded, otherwise - false static ASPOSECPP_SHARED_API bool TryParse(const String& value, System::Globalization::NumberStyles style, SharedPtr<IFormatProvider> fp, double &result); // ---------- String Conversions ---------- /// Converts the specified value to its string representation using the specified string format /// and culture-specific format information provided by the specified IFormatProvider object. /// @param value The value to convert /// @param format The string format /// @param fp The IFormatProvider object providing the culture-specific format information /// @returns The string representation of the specified value /// @tparam T The type of the value to convert template <typename T> static String ToString(T value, const String& format = String::Empty, const SharedPtr<IFormatProvider>& fp = nullptr); /// Converts the specified array of unicode characters to string using the specified culture-specific format information provided by the specified IFormatProvider object. /// @param value The array to convert /// @param fp The IFormatProvider object providing the culture-specific format information /// @returns The string representation of the specified array /// @tparam N The size of the array template <size_t N> static String ToString(const char_t (&value)[N], const SharedPtr<IFormatProvider>& fp = nullptr) { return String(value, N - 1); } /// Converts the specified value to string using the specified string format. /// @param value The value to convert /// @param fp An object containing the information about the string format /// @returns The string representation of the specified value /// @tparam T The type of the value to convert template <typename T> static String ToString(T value, const SharedPtr<IFormatProvider>& fp); /// Converts the specified value to string. /// @param value The value to convert /// @returns The string representation of the specified value static ASPOSECPP_SHARED_API String ToString(const DateTime& value); /// Converts the specified value to string using the specified string format. /// @param value The value to convert /// @param fp An object containing the information about the string format /// @returns The string representation of the specified value static ASPOSECPP_SHARED_API String ToString(const Decimal& value, const SharedPtr<IFormatProvider>& fp = nullptr); /// Converts the specified value to string. /// @param value The value to convert /// @returns The string representation of the specified value static ASPOSECPP_SHARED_API String ToString(const Guid& value); /// Returns the specified value; no conversion is performed. static ASPOSECPP_SHARED_API String ToString(const String& value, const SharedPtr<IFormatProvider>& fp = nullptr); /// Converts the specified integer value to its string representation in the specified base. /// @param value The value to convert /// @param toBase The base in which the specified value is to be represented /// @returns The string representation of the specified value in the specified base /// @tparam T The typ of the value to convert template <typename T> static String ToString(T value, int toBase) { switch (toBase) { case 2: return stream_converter_bin<T>(value); case 8: return stream_converter_octhex<T>(value, true); case 10: return ToString<T>(value); case 16: return stream_converter_octhex<T>(value, false); default: throw ArgumentException(u"Invalid Base"); } } // ---------- DateTime Conversions ---------- /// Converts the specified string to an instance of DateTime class. /// @param value The string to convert /// @returns An instance of DateTime class representing the date and time information represented by the specified string static ASPOSECPP_SHARED_API DateTime ToDateTime(const String& value); // ---------- Boxed Conversions ---------- /// Converts the specified boxed value to double-precision floating-point value. If the type of boxed value is String, the specified string format is used during conversion. /// @param obj The shared pointer to the object boxing the value to convert /// @param fp The string format to be used if the type of the boxed value is String /// @returns A double-precision floating-point value equivalent to the specified boxed value static ASPOSECPP_SHARED_API double ToDouble(const SharedPtr<Object>& obj, const SharedPtr<IFormatProvider>& fp = nullptr); /// Converts the specified boxed value to equivalent Decimal value. /// @param obj The shared pointer to the object boxing the value to convert /// @returns A Decimal value equivalent to the specified boxed value static ASPOSECPP_SHARED_API Decimal ToDecimal(const SharedPtr<Object>& obj); /// Converts the specified boxed value to single-precision floating-point value. /// @param obj The shared pointer to the object boxing the value to convert /// @returns A single-precision floating-point value equivalent to the specified boxed value static ASPOSECPP_SHARED_API float ToSingle(const SharedPtr<Object>& obj); /// Converts the specified boxed value to equivalent 32-bit integer value. /// @param obj The shared pointer to the object boxing the value to convert /// @returns A 32-bit integer value equivalent to the specified boxed value static ASPOSECPP_SHARED_API int ToInt32(const SharedPtr<Object>& obj); /// Converts the specified boxed value to equivalent unsigned 32-bit integer value. /// @param obj The shared pointer to the object boxing the value to convert /// @returns An unsigned 32-bit integer value equivalent to the specified boxed value static ASPOSECPP_SHARED_API uint32_t ToUInt32(const SharedPtr<Object>& obj); /// Converts the specified boxed value to equivalent 16-bit integer value. /// @param obj The shared pointer to the object boxing the value to convert /// @returns A 16-bit integer value equivalent to the specified boxed value static ASPOSECPP_SHARED_API int16_t ToInt16(const SharedPtr<Object>& obj); /// Converts the specified boxed value to equivalent unsigned 16-bit integer value. /// @param obj The shared pointer to the object boxing the value to convert /// @returns An unsigned 16-bit integer value equivalent to the specified boxed value static ASPOSECPP_SHARED_API uint16_t ToUInt16(const SharedPtr<Object>& obj); /// Converts the specified boxed value to equivalent 64-bit integer value. /// @param obj The shared pointer to the object boxing the value to convert /// @returns A 64-bit integer value equivalent to the specified boxed value static ASPOSECPP_SHARED_API int64_t ToInt64(const SharedPtr<Object>& obj); /// Converts the specified boxed value to equivalent unsigned 64-bit integer value. /// @param obj The shared pointer to the object boxing the value to convert /// @returns An unsigned 64-bit integer value equivalent to the specified boxed value static ASPOSECPP_SHARED_API uint64_t ToUInt64(const SharedPtr<Object>& obj); /// Converts the specified boxed value to equivalent unsigned 8-bit integer value. /// @param obj The shared pointer to the object boxing the value to convert /// @returns An unsigned 8-bit integer value equivalent to the specified boxed value static ASPOSECPP_SHARED_API uint8_t ToByte(const SharedPtr<Object>& obj); /// Converts the specified boxed value to equivalent 8-bit integer value. /// @param obj The shared pointer to the object boxing the value to convert /// @returns An 8-bit integer value equivalent to the specified boxed value static ASPOSECPP_SHARED_API int8_t ToSByte(const SharedPtr<Object>& obj); /// Converts the specified boxed value to equivalent DateTime value. /// @param obj The shared pointer to the object boxing the value to convert /// @returns A DateTime value equivalent to the specified boxed value static ASPOSECPP_SHARED_API DateTime ToDateTime(const SharedPtr<Object>& obj); /// Converts the specified boxed value to its string representation. If the type of boxed value is String, the specified string format is used during conversion. /// @param obj The shared pointer to the object boxing the value to convert /// @param fp The string format to be used if the type of the boxed value is String /// @returns A string representing the specified boxed value static ASPOSECPP_SHARED_API String ToString(const SharedPtr<Object>& obj, const SharedPtr<IFormatProvider>& fp = nullptr); // --------------------------------------- /// Returns a TypeCode value representing the type of the specified boxed value. /// @param obj The shared pointer to the object boxing the value the type of which is to be returned /// @returns The value representing the type of the boxed value static ASPOSECPP_SHARED_API TypeCode GetTypeCode(const SharedPtr<Object>& obj); /// Converts the specified int value to its string representation. Specialized implementation to increase performance. /// @param value The value to convert /// @returns The string representing the specified int value static ASPOSECPP_SHARED_API String ToString(int value); protected: /// The string representation of bool value 'true'. static const String ASPOSECPP_SHARED_API s_trueString; /// The string representation of bool value 'false'. static const String ASPOSECPP_SHARED_API s_falseString; // base64 /// Base-64 encodes a sequence of bytes and returns the encoded data as a string. /// @param data The pointer to the beginning of the buffer containing the bytes to encode /// @param size The number of bytes in the buffer to encode /// @param linebreaks Specifies whether the line break characters are to be inserted in the output string after every 76 base-64 characters /// @returns The string containing the base-64 encoded bytes from the specified buffer static ASPOSECPP_SHARED_API std::string to_base64(const uint8_t* data, size_t size, bool linebreaks); /// Decodes base-64 encoded data represented as vector of char16_t bytes. /// @param first The beginning of range with base-64 encoded data /// @param last The ending of range with base-64 encoded data /// @param out The output parameter; the decoded bytes are stored in the specified vector /// @returns The number of bytes decoded static ASPOSECPP_SHARED_API int32_t from_base64(const char_t * first, const char_t* last, std::vector<uint8_t>& out); // numeric /// A helper method that performs type conversion. /// @param value The value to convert /// @returns The value of type @p Target equivalent to the specified value /// @tparam Target The target type /// @tparam Source The source type template <typename Target, typename Source> static Target numeric_cast_wrap(Source value); /// A helper method that converts a single-precision floating point value to a value of type @p Target. /// @param value The value to convert /// @returns The value of type @p Target equivalent to the specified value /// @tparam Target The target type template <typename Target> static Target numeric_cast_wrap(float value); /// A helper method that converts a double-precision floating point value to a value of type @p Target. /// @param value The value to convert /// @returns The value of type @p Target equivalent to the specified value /// @tparam Target The target type template <typename Target> static Target numeric_cast_wrap(double value); // numeric cast helper /// Helper structs that provides methods that convert a value of type @p Source to equivalent value of type @p Target. template<typename Target, typename Source, bool is_enum = std::is_enum<Source>::value> struct NumericCastHelper; /// Helper structs that provides methods that convert an enumeration value of type @p Source to equivalent value of type @p Target. template<typename Target, typename Source> struct NumericCastHelper<Target, Source, true>; // from string /// Converts the string representation of a number in the specified base to 64-bit integer value. /// @param value The string to convert /// @param fromBase The base in which the number is represented /// @returns A 64-bit integer equivalent to the number represented by the specified string static ASPOSECPP_SHARED_API int64_t string_to_int64(const String& value, int fromBase); /// Converts the string representation of a number in the specified base to unsigned 64-bit integer value. /// @param value The string to convert /// @param fromBase The base in which the number is represented /// @returns An unsigned 64-bit integer equivalent to the number represented by the specified string static ASPOSECPP_SHARED_API uint64_t string_to_uint64(const String& value, int fromBase); // to string /// Converts the specified value to a string representation of this value in binary notation. /// @param value The value to convert /// @param tooct_or_tohex Specifies if the value has to be represented in octal (true) or hexadecimal notation (false). /// @param len The length of resulting string; all non-significant positions in the resulting string representation of a number /// are filled with zeroes. /// @returns A string reprsentation of the specified value in the specified notation. /// @tparam Source The type of the value to convert template <typename Source> static String stream_converter_octhex(Source value, bool tooct_or_tohex, int len = 0) { std::wstringstream ss; ss << (tooct_or_tohex ? std::oct : std::hex); if (len > 0) { ss << std::setfill(L'0'); ss << std::setw(len); } ss << value; return String(ss.str()); } /// Converts the specified value to a string representation of this value in binary notation. /// @param value The value to convert /// @returns A string reprsentation of the specified value in binary notation. /// @tparam Source The type of the value to convert template <typename Source> static String stream_converter_bin(Source value) { std::u16string rv; for (int i = static_cast<int>(sizeof(Source)) - 1; i >= 0; --i) { uint8_t b = *(reinterpret_cast<uint8_t*>(&value) + i); for (int j = 0; j < 8; j++) { if ((b & 0x80) == 0x80) rv += u'1'; else if (rv.size() > 0) rv += u'0'; b <<= 1; } } return String(rv); } }; // class Convert #undef ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO_2 #undef ASPOSE_SYSTEM_CONVERT_DECLARE_STATIC_TO /// Implementation. template <typename T> inline String Convert::ToString(T value, const String& format, const SharedPtr<IFormatProvider>& fp) { return System::Globalization::Details::ToString(value, format, fp); } /// Implementation. template <typename T> inline String Convert::ToString(T value, const SharedPtr<IFormatProvider>& fp) { return System::Globalization::Details::ToString(value, String::Empty, fp); } /// Implementation of the specialization for char_t as the type of the value to convert. template <> inline String Convert::ToString<char_t>(char_t value, const String& format, const SharedPtr<IFormatProvider>& provider) { return String(value, 1); } /// Implementation of the specialization for char_t as the type of the value to convert. template <> inline String Convert::ToString<char_t>(char_t value, const SharedPtr<IFormatProvider>& provider) { return String(value, 1); } /// Implementation of the specialization for bool as the type of the value to convert. template <> inline String Convert::ToString<bool>(bool value, const String& format, const SharedPtr<IFormatProvider>& provider) { return value ? s_trueString : s_falseString; } /// Implementation of the specialization for bool as the type of the value to convert. template <> inline String Convert::ToString<bool>(bool value, const SharedPtr<IFormatProvider>& provider) { return value ? s_trueString : s_falseString; } /// Implementation of the specialization for DateTime as the type of the value to convert. template <> inline String Convert::ToString<DateTime>(DateTime value, const System::SharedPtr<System::IFormatProvider>& provider) { return value.ToString(provider); } /// Implementation of the specialization for DateTime as the type of the value to convert. template <> inline String Convert::ToString<DateTime>(DateTime value, const System::String& format, const System::SharedPtr<System::IFormatProvider>& provider) { return value.ToString(format, provider); } } // namespace System #endif // _aspose_system_convert_h_
[ "ali.ahmed@aspose.com" ]
ali.ahmed@aspose.com
253cb9e42ff29c7875df5fbddc5e2898f26a2518
abef0ff484515fcf17a5e5176f51e852caa06410
/Example1_Colour/Buffer.h
528175999cdc0a77637ba26b6061e45d88f5fb38
[]
no_license
nikodems/final-year-project
46c877c985711adc9218b605aec035640e04b8c2
f86117316edd93bb02bd966ba39863702becafdd
refs/heads/master
2022-11-14T23:05:51.580919
2020-07-08T17:01:27
2020-07-08T17:01:27
278,146,534
0
0
null
null
null
null
UTF-8
C++
false
false
658
h
#ifndef _BUFFER_H #define _BUFFER_H #include "DXF.h" #include <vector> //Struct to hold a tile's path and vector data struct Buffer { XMINT3 path; std::vector<float> vec; bool operator==(const Buffer& lhs) { return lhs.path.x == path.x && lhs.path.y == path.y && lhs.path.z == path.z; } Buffer(XMINT3 p, std::vector<float> v) { path = p, vec = v; } Buffer() {}; }; //Struct to describe a tile's position relative to the centre tile struct TileDesc { enum { NoneVert = 0, North = 1, South = -1, SouthSouth = -2, NorthNorth = 2, NorthNorthNorth = 3} vertical; enum { NoneHor = 0, East = 10, West = -10 } horizontal; }; #endif _BUFFER_H
[ "32880727+nikodems@users.noreply.github.com" ]
32880727+nikodems@users.noreply.github.com
373a4d9590fe71f9d47fafd734e9be16305a465d
cf73faea2454d63a09b5661f6bdfedfe60a05f26
/leetcode/binary-tree-postorder-traversal.cpp
10d323abdbfc287bf7e5ee2c5f926358b8e97b5d
[]
no_license
lqhl/programming
f556987eecafe4c6b6dcb25cd80f1db781ac40e3
927212e848d3627c4d7b0305e6eb05d100215e42
refs/heads/master
2020-12-24T14:18:51.140730
2016-03-29T07:10:04
2016-03-29T07:10:04
15,156,593
1
1
null
2015-08-24T07:44:47
2013-12-13T06:35:34
C++
UTF-8
C++
false
false
1,363
cpp
#include "util.hpp" struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> results; TreeNode* prev = nullptr; stack<TreeNode*> s; if (root) s.push(root); else return results; while (!s.empty()) { TreeNode* cur = s.top(); if (prev == nullptr || prev->left == cur || prev->right == cur) { if (cur->left) s.push(cur->left); else if (cur->right) s.push(cur->right); } else if (prev == cur->left) { if (cur->right) s.push(cur->right); } else { results.push_back(cur->val); s.pop(); } prev = cur; } return results; } }; class Solution2 { private: void dfs(TreeNode* cur, vector<int>& result) { if (cur == nullptr) return; dfs(cur->left, result); dfs(cur->right, result); result.push_back(cur->val); } public: vector<int> postorderTraversal(TreeNode* root) { vector<int> result; dfs(root, result); return result; } };
[ "lqgy2001@gmail.com" ]
lqgy2001@gmail.com
1c3494c580d95597e29c9061e2674884a68f35f0
217ddc76e3ca8309b85c94d3733c0e227a019ba5
/Assignment1/Spring.cpp
6c47fd89de80d6e50d187d170212791a717396a3
[]
no_license
StubbornArtist/cpsc587-03
0c0d3981fbd8225353cbd17125ab978ffcd80ab3
4ef990a5fee789513f0be21fddd4c6c3bc2a2325
refs/heads/master
2020-05-21T07:10:34.153323
2017-03-23T02:24:01
2017-03-23T02:24:01
84,592,561
0
0
null
null
null
null
UTF-8
C++
false
false
1,503
cpp
#include "Spring.h" Spring::Spring() { k = 0.0f; m1 = 0; m2 = 0; damp = 0.0f; restLen = 0; } Spring::Spring(Mass * mOne, Mass * mTwo, float stiffness, float d) { m1 = mOne; m2 = mTwo; k = stiffness; damp = d; restLen = length(m1->getPosition() - m2->getPosition()); } float Spring::getStiffness() { return k; } void Spring::setStiffness(float s) { k = s; } float Spring :: getDamping() { return damp; } void Spring :: setDamping(float d) { damp = d; } Mass * Spring::getFirstMass() { return m1; } void Spring::setFirstMass(Mass * m) { m1 = m; } Mass * Spring::getSecondMass() { return m2; } void Spring::setSecondMass(Mass * m) { m2 = m; } float Spring::getRestLength() { return restLen; } void Spring::setRestLength(float r) { restLen = r; } //update the forces on each mass in this spring void Spring::updateInternalForce() { vec3 curLen = m1->getPosition() - m2->getPosition(); //use Hooke's law to calculate the force on the first mass //(force exterted on the second mass will be the negation) vec3 f = -k * (length(curLen) - restLen) * normalize(curLen); //add force exterted by the spring to each mass attached to it m1->addToForce(f); m2->addToForce(-f); //add damping to each mass //ignore this when the force is zero to avoid division by zero if (!(f.x == 0.0f && f.y == 0.0f && f.z == 0.0f)) { vec3 fn = normalize(f); vec3 fd = -damp * (dot(m1->getVelocity() - m2->getVelocity(), fn) / dot(fn, fn)) * fn; m1->addToForce(fd); m2->addToForce(-fd); } }
[ "ashleycurr@live.ca" ]
ashleycurr@live.ca
dc96d58fba7faec5a30f0d9f19fd5adfb73ff7d0
a2164bb399a9f9a9bb732c419ce59ba4854b2b26
/code/Engine/Log.cpp
c004ecb649ccb6ba4e181bfcf9c56ce284e236fe
[]
no_license
WarzesProject/3DRPG
9daded41a8395091c5ae770c6091f973d6300480
fa56f5d07e5b70d506550b11de799d13b2e5d727
refs/heads/master
2021-04-12T14:16:08.106043
2020-04-16T07:10:34
2020-04-16T07:10:34
249,083,917
0
0
null
null
null
null
UTF-8
C++
false
false
2,633
cpp
#include "stdafx.h" #include "Log.h" //----------------------------------------------------------------------------- Logger DefaultLog; //----------------------------------------------------------------------------- Log::~Log() { if ( !m_str.empty() ) m_logger.Print(m_str, m_level); } //----------------------------------------------------------------------------- void Logger::logString(stl::string_view str, Log::Level level) { #if SE_PLATFORM_ANDROID int priority = 0; switch ( level ) { case Log::Level::Error: priority = ANDROID_LOG_ERROR; break; case Log::Level::Warning: priority = ANDROID_LOG_WARN; break; case Log::Level::Info: priority = ANDROID_LOG_INFO; break; case Log::Level::All: priority = ANDROID_LOG_DEBUG; break; default: return; } __android_log_print(priority, "Sapphire", "%s", str.data()); #elif SE_PLATFORM_LINUX int fd = 0; switch ( level ) { case Log::Level::Error: case Log::Level::Warning: fd = STDERR_FILENO; break; case Log::Level::Info: case Log::Level::All: fd = STDOUT_FILENO; break; default: return; } std::vector<char> output(str.begin(), str.end()); output.push_back('\n'); size_t offset = 0; while ( offset < output.size() ) { const ssize_t written = write(fd, output.data() + offset, output.size() - offset); if ( written == -1 ) return; offset += static_cast<size_t>(written); } #elif SE_PLATFORM_WINDOWS const int bufferSize = MultiByteToWideChar(CP_UTF8, 0, str.data(), -1, nullptr, 0); if ( bufferSize == 0 ) return; std::vector<WCHAR> buffer(bufferSize + 1); // +1 for the newline if ( MultiByteToWideChar(CP_UTF8, 0, str.data(), -1, buffer.data(), static_cast<int>(buffer.size())) == 0 ) return; if ( FAILED(StringCchCatW(buffer.data(), buffer.size(), L"\n")) ) return; OutputDebugStringW(buffer.data()); # if SE_DEBUG HANDLE handle; switch ( level ) { case Log::Level::Error: case Log::Level::Warning: handle = GetStdHandle(STD_ERROR_HANDLE); break; case Log::Level::Info: case Log::Level::All: handle = GetStdHandle(STD_OUTPUT_HANDLE); break; default: return; } DWORD bytesWritten; WriteConsoleW(handle, buffer.data(), static_cast<DWORD>(wcslen(buffer.data())), &bytesWritten, nullptr); # endif #elif SE_PLATFORM_EMSCRIPTEN int flags = EM_LOG_CONSOLE; switch ( level ) { case Log::Level::Error: flags |= EM_LOG_ERROR; break; case Log::Level::Warning: flags |= EM_LOG_WARN; break; case Log::Level::Info: case Log::Level::All: break; default: return; } emscripten_log(flags, "%s", str.data()); #endif } //-----------------------------------------------------------------------------
[ "warzes@mail.ru" ]
warzes@mail.ru
4697e513d72b348260caa851be7bcc798b9e3e38
a3d39c53b1abf4d35c9a9a1d8c8f226572f29bcd
/src/qt/walletframe.cpp
4a8b22ea744d8b28dcbf55c1506e8182883af75a
[ "MIT" ]
permissive
BakedInside/Beans-Core
afc3a55efa3e14e62a19f4bc4d5ae5a357f5f1de
daa9b2ddbfd3305881749bda7f32146738154260
refs/heads/master
2022-07-30T05:42:26.680123
2021-05-22T15:35:40
2021-05-22T15:35:40
369,584,373
1
0
null
null
null
null
UTF-8
C++
false
false
8,564
cpp
// Copyright (c) 2011-2020 The Beans Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/walletframe.h> #include <qt/beansgui.h> #include <qt/createwalletdialog.h> #include <qt/overviewpage.h> #include <qt/walletcontroller.h> #include <qt/walletmodel.h> #include <qt/walletview.h> #include <cassert> #include <QGroupBox> #include <QHBoxLayout> #include <QLabel> #include <QPushButton> #include <QVBoxLayout> WalletFrame::WalletFrame(const PlatformStyle* _platformStyle, BeansGUI* _gui) : QFrame(_gui), gui(_gui), platformStyle(_platformStyle), m_size_hint(OverviewPage{platformStyle, nullptr}.sizeHint()) { // Leave HBox hook for adding a list view later QHBoxLayout *walletFrameLayout = new QHBoxLayout(this); setContentsMargins(0,0,0,0); walletStack = new QStackedWidget(this); walletFrameLayout->setContentsMargins(0,0,0,0); walletFrameLayout->addWidget(walletStack); // hbox for no wallet QGroupBox* no_wallet_group = new QGroupBox(walletStack); QVBoxLayout* no_wallet_layout = new QVBoxLayout(no_wallet_group); QLabel *noWallet = new QLabel(tr("No wallet has been loaded.\nGo to File > Open Wallet to load a wallet.\n- OR -")); noWallet->setAlignment(Qt::AlignCenter); no_wallet_layout->addWidget(noWallet, 0, Qt::AlignHCenter | Qt::AlignBottom); // A button for create wallet dialog QPushButton* create_wallet_button = new QPushButton(tr("Create a new wallet"), walletStack); connect(create_wallet_button, &QPushButton::clicked, [this] { auto activity = new CreateWalletActivity(gui->getWalletController(), this); connect(activity, &CreateWalletActivity::finished, activity, &QObject::deleteLater); activity->create(); }); no_wallet_layout->addWidget(create_wallet_button, 0, Qt::AlignHCenter | Qt::AlignTop); no_wallet_group->setLayout(no_wallet_layout); walletStack->addWidget(no_wallet_group); } WalletFrame::~WalletFrame() { } void WalletFrame::setClientModel(ClientModel *_clientModel) { this->clientModel = _clientModel; for (auto i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) { i.value()->setClientModel(_clientModel); } } bool WalletFrame::addWallet(WalletModel *walletModel) { if (!gui || !clientModel || !walletModel) return false; if (mapWalletViews.count(walletModel) > 0) return false; WalletView *walletView = new WalletView(platformStyle, this); walletView->setClientModel(clientModel); walletView->setWalletModel(walletModel); walletView->showOutOfSyncWarning(bOutOfSync); walletView->setPrivacy(gui->isPrivacyModeActivated()); WalletView* current_wallet_view = currentWalletView(); if (current_wallet_view) { walletView->setCurrentIndex(current_wallet_view->currentIndex()); } else { walletView->gotoOverviewPage(); } walletStack->addWidget(walletView); mapWalletViews[walletModel] = walletView; connect(walletView, &WalletView::outOfSyncWarningClicked, this, &WalletFrame::outOfSyncWarningClicked); connect(walletView, &WalletView::transactionClicked, gui, &BeansGUI::gotoHistoryPage); connect(walletView, &WalletView::coinsSent, gui, &BeansGUI::gotoHistoryPage); connect(walletView, &WalletView::message, [this](const QString& title, const QString& message, unsigned int style) { gui->message(title, message, style); }); connect(walletView, &WalletView::encryptionStatusChanged, gui, &BeansGUI::updateWalletStatus); connect(walletView, &WalletView::incomingTransaction, gui, &BeansGUI::incomingTransaction); connect(walletView, &WalletView::hdEnabledStatusChanged, gui, &BeansGUI::updateWalletStatus); connect(gui, &BeansGUI::setPrivacy, walletView, &WalletView::setPrivacy); return true; } void WalletFrame::setCurrentWallet(WalletModel* wallet_model) { if (mapWalletViews.count(wallet_model) == 0) return; // Stop the effect of hidden widgets on the size hint of the shown one in QStackedWidget. WalletView* view_about_to_hide = currentWalletView(); if (view_about_to_hide) { QSizePolicy sp = view_about_to_hide->sizePolicy(); sp.setHorizontalPolicy(QSizePolicy::Ignored); view_about_to_hide->setSizePolicy(sp); } WalletView *walletView = mapWalletViews.value(wallet_model); assert(walletView); // Set or restore the default QSizePolicy which could be set to QSizePolicy::Ignored previously. QSizePolicy sp = walletView->sizePolicy(); sp.setHorizontalPolicy(QSizePolicy::Preferred); walletView->setSizePolicy(sp); walletView->updateGeometry(); walletStack->setCurrentWidget(walletView); walletView->updateEncryptionStatus(); } void WalletFrame::removeWallet(WalletModel* wallet_model) { if (mapWalletViews.count(wallet_model) == 0) return; WalletView *walletView = mapWalletViews.take(wallet_model); walletStack->removeWidget(walletView); delete walletView; } void WalletFrame::removeAllWallets() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) walletStack->removeWidget(i.value()); mapWalletViews.clear(); } bool WalletFrame::handlePaymentRequest(const SendCoinsRecipient &recipient) { WalletView *walletView = currentWalletView(); if (!walletView) return false; return walletView->handlePaymentRequest(recipient); } void WalletFrame::showOutOfSyncWarning(bool fShow) { bOutOfSync = fShow; QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->showOutOfSyncWarning(fShow); } void WalletFrame::gotoOverviewPage() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoOverviewPage(); } void WalletFrame::gotoHistoryPage() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoHistoryPage(); } void WalletFrame::gotoReceiveCoinsPage() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoReceiveCoinsPage(); } void WalletFrame::gotoSendCoinsPage(QString addr) { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoSendCoinsPage(addr); } void WalletFrame::gotoSignMessageTab(QString addr) { WalletView *walletView = currentWalletView(); if (walletView) walletView->gotoSignMessageTab(addr); } void WalletFrame::gotoVerifyMessageTab(QString addr) { WalletView *walletView = currentWalletView(); if (walletView) walletView->gotoVerifyMessageTab(addr); } void WalletFrame::gotoLoadPSBT(bool from_clipboard) { WalletView *walletView = currentWalletView(); if (walletView) { walletView->gotoLoadPSBT(from_clipboard); } } void WalletFrame::encryptWallet() { WalletView *walletView = currentWalletView(); if (walletView) walletView->encryptWallet(); } void WalletFrame::backupWallet() { WalletView *walletView = currentWalletView(); if (walletView) walletView->backupWallet(); } void WalletFrame::changePassphrase() { WalletView *walletView = currentWalletView(); if (walletView) walletView->changePassphrase(); } void WalletFrame::unlockWallet() { WalletView *walletView = currentWalletView(); if (walletView) walletView->unlockWallet(); } void WalletFrame::usedSendingAddresses() { WalletView *walletView = currentWalletView(); if (walletView) walletView->usedSendingAddresses(); } void WalletFrame::usedReceivingAddresses() { WalletView *walletView = currentWalletView(); if (walletView) walletView->usedReceivingAddresses(); } WalletView* WalletFrame::currentWalletView() const { return qobject_cast<WalletView*>(walletStack->currentWidget()); } WalletModel* WalletFrame::currentWalletModel() const { WalletView* wallet_view = currentWalletView(); return wallet_view ? wallet_view->getWalletModel() : nullptr; } void WalletFrame::outOfSyncWarningClicked() { Q_EMIT requestedSyncWarningInfo(); }
[ "lanorlasystem@gmail.com" ]
lanorlasystem@gmail.com
463e118b7a57efef6441a4895afebe2719bc4b0a
fad35ba1e6601c4e650848c83798385b0a678dac
/include/cmd_handler.h
9fc9a6db441a1ca8bbd2c8506d02b240a4e2ad0b
[]
no_license
deltaboltz/OSP5
8f958823b5c715aafe19fe4efa24700e8a261f8a
ad63d64ddf08868577611f9a72dc7e55d3fe3a15
refs/heads/main
2023-01-19T14:27:31.829135
2020-11-22T01:22:08
2020-11-22T01:22:08
312,167,747
0
0
null
null
null
null
UTF-8
C++
false
false
371
h
#ifndef CMD_HANDLER_H #define CMD_HANDLER_H #include <vector> #include <string> int getcliarg(int argc, char** argv, const char* options, \ const char* flags, std::vector<std::string> &optout,\ bool* flagout); void parserunpath(char** argv, std::string& runpath, std::string& pref); bool pathdepcheck(std::string runpath, std::string depname); #endif
[ "deltaboltz@me.com" ]
deltaboltz@me.com
c60bcaab57b2b1f07da1084813fa4e4fc4606125
e6b668c5afc2a333a836bd8dc1dce6e04a5ef328
/contest/mbstu practice contest (CF B&C)/14.cpp
a2b38d6ab1ec5dad551a1659e13fe655c0136f6e
[]
no_license
mahim007/Online-Judge
13b48cfe8fe1e8a723ea8e9e2ad40efec266e7ee
f703fe624035a86d7c6433c9111a3e3ee3e43a77
refs/heads/master
2020-03-11T21:02:04.724870
2018-04-20T11:28:42
2018-04-20T11:28:42
130,253,727
2
0
null
null
null
null
UTF-8
C++
false
false
713
cpp
#include<bits/stdc++.h> using namespace std; #define ll long long int #define mxn 1009 ll cost[mxn],vis[mxn]; vector<ll>G[mxn]; ll ans,n; void dfs(ll u){ vis[u]=1; ll sz=G[u].size(); for(ll i=0;i<sz;i++){ ll v=G[u][i]; ans+=min(cost[u],cost[v]); if(vis[v]==0){ dfs(v); } } } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll m,i,j,k,u,v; cin>>n>>m; for(i=1;i<=n;i++) cin>>cost[i]; for(i=1;i<=m;i++){ cin>>u>>v; G[u].push_back(v); //G[v].push_back(u); } for(i=1;i<=n;i++){ if(vis[i]==0){ dfs(i); } } cout<<ans<<"\n"; return 0; }
[ "ashrafulmahim@gmail.com" ]
ashrafulmahim@gmail.com
2922b87fed3603285729870adff41269fd65b4f1
c2b6c8a1332287f8ca3230659c02edd51c6d85b9
/TDES.cpp
19975d240c494e9c5ee7c9a4c5999d56114905a6
[ "MIT" ]
permissive
yuanyangwangTJ/RSA
59b42daaac76eb05305f1d1d6f5e3382d9b49392
384423bf33d555047755bb253a3531e35870ffd6
refs/heads/master
2023-05-07T02:20:05.925205
2021-06-12T02:33:43
2021-06-12T02:33:43
372,157,063
0
0
null
null
null
null
UTF-8
C++
false
false
5,494
cpp
/*********************************** * Class Name: TDES * Function: 实现 Triple DES * ********************************/ #include "TDES.h" #include <cstring> #include <iostream> #include <fstream> #define ERROR -1 using namespace std; // 构造函数 TDES::TDES() { keyRead(); generateKeys(); } // 读取密钥 void TDES::keyRead() { ifstream fin("key.dat"); if (!fin) { cout << "ERROR in opening 'key.dat'"; exit(ERROR); } string stmp; for (int i = 0; i < 3; i++) { fin >> stmp; bitset<64> btmp(stmp); k[i] = btmp; } fin.close(); } // 对 56 位密钥的前后部分进行左移 bitset<28> TDES::leftShift(bitset<28> k, int shift) { bitset<28> tmp = k; for (int i = 27; i >= 0; i--) { if (i - shift < 0) { k[i] = tmp[i - shift + 28]; } else { k[i] = tmp[i - shift]; } } return k; } // 64 位密钥转换为 48 位 void TDES::key64To48(bitset<64> key, bitset<48> subkey[16]) { bitset<56> realKey; bitset<48> compressKey; bitset<28> left, right; // 去掉奇偶校验位,将 64 位密钥变为 56 位 for (int i = 0; i < 56; i++) { realKey[55 - i] = key[64 - PC1[i]]; } // 生成子密钥,保存在 subkey[16] 中 for (int r = 0; r < 16; r++) { // 前后 28 位处理 for (int i = 28; i < 56; i++) { left[i - 28] = realKey[i]; } for (int i = 0; i < 28; i++) { right[i] = realKey[i]; } // 左移 left = leftShift(left, SHIFTS[r]); right = leftShift(right, SHIFTS[r]); // 压缩置换,由 56 位得到 48 位子密钥 for (int i = 28; i < 56; i++) { realKey[i] = left[i - 28]; } for (int i = 0; i < 28; i++) { realKey[i] = right[i]; } for (int i = 0; i < 48; i++) { compressKey[47 - i] = realKey[56 - PC2[i]]; } subkey[r] = compressKey; } } // 为每一个密钥生成 16 个子密钥,存储在 sk 中 void TDES::generateKeys() { for (int i = 0; i < 3; i++) { key64To48(k[i], sk[i]); } } // DES 的 f 函数 bitset<32> TDES::function(bitset<32> A, bitset<48> k) { bitset<48> EXA; bitset<32> RES; // 扩展置换,32 -> 48 for (int i = 0; i < 48; i++) { EXA[47 - i] = A[32 - E[i]]; } // 异或 EXA = EXA ^ k; // 使用 S 盒置换 int x = 0; for (int i = 0; i < 48; i += 6) { int row = EXA[47 - i] * 2 + EXA[47 - i - 5]; int col = EXA[46 - i] * 8 + EXA[45 - i] * 4 + EXA[44 - i] * 2 + EXA[43 - i]; int num = SBox[i / 6][row][col]; bitset<4> Sbox(num); for (int j = 0; j < 4; j++) { RES[31 - x - j] = Sbox[3 - j]; } x += 4; } // P 置换 bitset<32> tmp = RES; for (int i = 0; i < 32; i++) { RES[31 - i] = tmp[32 - P[i]]; } return RES; } // DES 加密(单次加密),n 表示第 n 个密钥(可以为 0,1,2) bitset<64> TDES::desEncrypt(bitset<64> plaintext, int n) { bitset<64> currentBits, ciphertext; bitset<32> left, right, newLeft; // 初始置换 IP for (int i = 0; i < 64; i++) { currentBits[63 - i] = plaintext[64 - IP[i]]; } // 获取 Li 和 Ri for (int i = 32; i < 64; i++) { left[i - 32] = currentBits[i]; } for (int i = 0; i < 32; i++) { right[i] = currentBits[i]; } // 16 轮迭代(子密钥逆序使用) for (int r = 0; r < 16; r++) { newLeft = right; right = left ^ function(right, sk[n][r]); left = newLeft; } // 合并 L16 和 R16,合并为 R16L16 for (int i = 0; i < 32; i++) { ciphertext[i] = left[i]; } for (int i = 32; i < 64; i++) { ciphertext[i] = right[i - 32]; } // 结尾置换 FP currentBits = ciphertext; for (int i = 0; i < 64; i++) { ciphertext[63 - i] = currentBits[64 - FP[i]]; } return ciphertext; } // DES 解密(单次解密),n 表示第 n 个密钥(可以为 0,1,2) bitset<64> TDES::desDecrypt(bitset<64> ciphertext, int n) { bitset<64> plaintext, currentBits; bitset<32> left, right, newLeft; // 初始置换 IP for (int i = 0; i < 64; i++) { currentBits[63 - i] = ciphertext[64 - IP[i]]; } // 获取 Li 和 Ri for (int i = 32; i < 64; i++) { left[i - 32] = currentBits[i]; } for (int i = 0; i < 32; i++) { right[i] = currentBits[i]; } // 16 轮迭代(子密钥逆序使用) for (int r = 0; r < 16; r++) { newLeft = right; right = left ^ function(right, sk[n][15 - r]); left = newLeft; } // 合并 L16 和 R16,合并为 R16L16 for (int i = 0; i < 32; i++) { plaintext[i] = left[i]; } for (int i = 32; i < 64; i++) { plaintext[i] = right[i - 32]; } currentBits = plaintext; for (int i = 0; i < 64; i++) { plaintext[63 - i] = currentBits[64 - FP[i]]; } return plaintext; } // TDES 加密(三重加密) bitset<64> TDES::TDESEncrypt() { cipher = desEncrypt(plain, 0); cipher = desDecrypt(cipher, 1); cipher = desEncrypt(cipher, 2); return cipher; } // TDES 解密(三重解密) bitset<64> TDES::TDESDecrypt() { plain = desDecrypt(cipher, 2); plain = desEncrypt(plain, 1); plain = desDecrypt(plain, 0); return plain; }
[ "hadoop@LAPTOP-QT7BLFJ0.localdomain" ]
hadoop@LAPTOP-QT7BLFJ0.localdomain
1e2b258eb22c1d838e910af7da8de86f0827e65e
727d2c083de7eb6d4e8321e924686f5b6ce1efe7
/test/tcp_packet_stream_test.cpp
74e4d45ebb686291129b5b4795ea475afb9e71df
[]
no_license
leohahn/libpitaya-cpp
2d907ea846cfceb6c19a11223f2589b01dcb8050
fee65ec01410d8b0659fe5c96bf546465d46cd2e
refs/heads/master
2020-04-12T08:00:21.012329
2019-05-19T04:48:44
2019-05-19T04:48:44
162,378,500
0
0
null
null
null
null
UTF-8
C++
false
false
43
cpp
#include "connection/tcp_packet_stream.h"
[ "leonnardo.hahn@gmail.com" ]
leonnardo.hahn@gmail.com
a5a4e7da2c031ddb29cac531282c9eb82bd324c2
b904dc145daa2d968a4570e1b16e69b05403c6d4
/plantstimuli/software/StimuliZion/StimuliZion.ino
d022b1975edb2ddc4040d240a3b7cb76a294232d
[ "MIT" ]
permissive
vioklab/FabAcademy2014
5b7b5b6b518ac0a123563c064bf2db1e67cf821f
bb74a2a2215800ed9ec0f70177137b8cc8c0bb7e
refs/heads/master
2021-01-01T19:15:32.851103
2014-06-14T21:21:46
2014-06-14T21:21:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,480
ino
#include "SPI.h" // LCD library #include "Adafruit_WS2801.h" // LED strip library // Choose which 2 pins you will use for output. uint8_t dataPin = 2; // Yellow wire on Adafruit Pixels uint8_t clockPin = 3; // Green wire on Adafruit Pixels // Don't forget to connect the ground wire to Arduino ground, // and the +5V wire to a +5V supply // Set the first variable to the NUMBER of pixels. 25 = 25 pixels in a row Adafruit_WS2801 strip = Adafruit_WS2801(16, dataPin, clockPin); void setup() { /* SERIAL & I2C Communication - MASTER READER */ Serial.begin(9600); serialSetup(); // important! /* LCD CRYSTAL DISPLAY */ //lcd.begin(16, 2); //lcd.clear(); //lcd.setCursor(0,0); //lcd.print("Hello"); /* LED STRIP */ // Update LED contents, to start they are all 'off' strip.begin(); strip.show(); //led_PotController(); } void loop() { //Serial.println(time); // wait a second so as not to send massive amounts of data //delay(1000); //led_PotController(); checkStimuli(); // led_RaibowWater(10,1); /* SERIAL CONTROLLER */ if (Serial.available() > 0) { // lee el byte entrante: char serialRun = Serial.read(); switch(serialRun){ case '1': led_PotController(); Serial.println("Led Status 1"); break; case '2': led_RaibowWater(10,1); Serial.println("Led Status 2"); break; } } else { //led_RaibowWater(10,1); //led_PotController(); } }
[ "leo@vioklab.com" ]
leo@vioklab.com
123a815a6e1e3604c5dd7079432511e7276e3766
aa6be7c4515ccf99f30ffcece8519fd27b5466f2
/C++/euler1.cpp
1f8a80434a5c607d1f710cee7c20ba3d009b1cf3
[]
no_license
mbreedlove/project-euler
e59f747aeeb579286c512ce2f21ce9c8598af241
cd851cf2a5e36c08c5ceb6f3b93e7823dbbd3004
refs/heads/master
2021-01-01T05:42:03.092693
2013-08-16T02:35:05
2013-08-16T02:35:05
1,087,453
0
0
null
null
null
null
UTF-8
C++
false
false
180
cpp
#include <iostream> using namespace std; int main() { int sum = 0; for(int i = 0; i < 1000; ++i) { if(i % 3 == 0 || i % 5 == 0) { sum += i; } } cout << sum << endl; }
[ "michael.breedlove1@gmail.com" ]
michael.breedlove1@gmail.com
bf298c7dc24cf82d42a1cacc553c190077374f40
4d67062e403644154118ce49cd255429e2a68059
/resources/code/polimorfismo/perro.h
8b2f92e81cf7dcc4325a11b2ac5e3941c11d9567
[]
no_license
fiuba-apuntes/7542-9508-tallerdeprogramacion1
59229d016dd1279a04a839c84e7eb873229243b3
ea345a3d6d86bb3e015e7d5a2bb7f10215b4b673
refs/heads/master
2016-09-06T08:53:40.639741
2015-03-08T23:29:41
2015-03-08T23:29:41
28,704,162
2
0
null
null
null
null
UTF-8
C++
false
false
465
h
class Perro{ public: /** * Método base, todos los perros ladran por defecto de la misma forma */ std::string ladrar() const{ return "guau"; } /** * Otros métodos base */ int getEdad() const{ return this->edad; } void setEdad(int edad){ this->edad = edad; } private: int edad; }; class Doge : public Perro{ public: /** * Se sobreescribe la forma de ladrar */ std::string ladrar() const{ return "wow, such code, many meme"; } };
[ "matias@shishi" ]
matias@shishi
b621c51351e49619e2d95d662b03802f93b4fe12
8ddef74060accfe362e7940f1b2d823eca116161
/Gui/MagnetLayout/MagnetLayout/MagnetLayoutSystem/magnetwidget.h
f8b5ae04cae41f50716799b6bf235e3d6f8a9d2e
[ "BSD-2-Clause-Views", "BSD-2-Clause" ]
permissive
Bitfall/AppWhirr-SamplesAndPrototypes
a56e72c687c963e39e08964ee5e608083aea05e1
d990391a345f15c7cd516f3dba26867b6d75f3be
refs/heads/master
2021-01-22T23:20:46.777259
2013-01-31T09:58:03
2013-01-31T09:58:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
229
h
#ifndef MAGNETWIDGET_H #define MAGNETWIDGET_H #include <QObject> class MagnetWidget : public QObject { Q_OBJECT public: explicit MagnetWidget(QObject *parent = 0); signals: public slots: }; #endif // MAGNETWIDGET_H
[ "viktor.benei@gmail.com" ]
viktor.benei@gmail.com
c4493fb9215275e49726df509fdf20a1c75107c5
a8285164f3a64dd9585b3b98ad355e07a1051bfb
/friday/USACO3/main.cpp
5e948a1127e0e585987491f7efcbb4dc96f1b7b0
[]
no_license
tqfan28/usaco
800eb6723488ca7ac22096741a7c05a621e2e4ed
8bee046beeb28ffc56e3ddee54087a7aba8c9bed
refs/heads/master
2020-03-22T23:35:15.743228
2018-10-13T13:40:51
2018-10-13T13:40:51
140,818,659
0
0
null
null
null
null
UTF-8
C++
false
false
1,728
cpp
// // main.cpp // USACO3 // // Created by TFAN on 2017/8/12. // Copyright © 2017年 TFAN. All rights reserved. // /* ID: tfan0328 PROG: friday LANG: C++ */ #include <iostream> #include <string> #include <fstream> #include <vector> #include <algorithm> using namespace std; // compute a given date is Monday or Tuesday or ... in a given month // 0--Monday int Day(int start, int date) { return (((date -1) % 7) + start)%7; } void compute(int (&result)[7], int& next, int leap) { for (int j = 1; j < 13; ++j) { //cout << next << endl; if (j == 4 || j == 6 || j == 9 || j == 11) { result[Day(next,13)] += 1; next = (Day(next, 30) + 1) % 7; } else if (j == 2) { result[Day(next,13)] += 1; next = (Day(next, leap) + 1) % 7; } else { result[Day(next,13)] += 1; next = (Day(next, 31) + 1) % 7; } } } int main(int argc, const char * argv[]) { ofstream fout ("friday.out"); ifstream fin ("friday.in"); //cout << "Hello"<< endl; int n; int result [7] = {0, 0, 0, 0, 0, 0, 0}; fin >> n; int next = 0; for (int i = 0; i < n; ++i) { // leap year if ( ((1900 + i) % 100 != 0 && (1900 + i) % 4 == 0) || ((1900 + i) % 100 == 0 && (1900 + i) % 400 == 0)) { //cout << 1900+i << endl; compute(result, next, 29); } else { compute(result, next, 28); } } for (int i = 0; i < 7; ++i) { if (i != 6) { fout << result[((i+5)%7)] << ' '; } else { fout << result[((i+5)%7)] << '\n'; } } return 0; }
[ "tfan0328@gmail.com" ]
tfan0328@gmail.com
61780c3518a60b9cea377a1ac70a5d3fa7666b48
ab120702769a19353cf634ce270642f4d228200b
/modele/rectangle.cpp
9247927363941b9cf7ad8be4cbdea3454fe586ef
[]
no_license
HugoMoy/TP-Heritage
c8efc5e1e89f7edbded41ae1e015be7052bbb23f
6b84d432cfffbd0125676f7c2a1d1b9cafd8dfc8
refs/heads/master
2016-08-12T21:32:10.371058
2016-02-05T00:28:53
2016-02-05T00:28:53
50,918,592
0
0
null
2016-02-05T00:28:53
2016-02-02T12:18:54
C++
UTF-8
C++
false
false
978
cpp
#include "rectangle.h" Rectangle::Rectangle(string name, int x1, int y1, int x2, int y2) : Polygone(name, 4) { ajouterPoint(x1, y1); ajouterPoint(x2, y1); ajouterPoint(x2, y2); ajouterPoint(x1, y2); } Rectangle::~Rectangle() { } bool Rectangle::contient(pair<int, int> point) { return (point.first>=listePoints[0].first && point.first<=listePoints[2].first && point.second>=listePoints[0].second && point.second<=listePoints[2].second); } ptr_Forme Rectangle::clone() { Rectangle * rectangleClone = new Rectangle(nom, listePoints[0].first, listePoints[0].second, listePoints[2].first, listePoints[2].second); return rectangleClone; } void Rectangle::display() { cout << "RECTANGLE : " << nom << "contenant les points : "; for (int i = 0; i < nbPoints-1; i++) cout << "(" << listePoints[i].first << ", " << listePoints[i].second << ") ; "; cout << "(" << listePoints[nbPoints-1].first << ", " << listePoints[nbPoints-1].second << ")" << endl; }
[ "ValentinQB@live.fr" ]
ValentinQB@live.fr
2286aa1f8dd2a5d4fac0fdfc6d22e2e0f94945e0
d8270b72e0c7c9cc5414530a1a74c297d33a821f
/1837_isenbaev.cpp
b3e5b83281dccf6095d25b4dcf6740573dbbc3f8
[]
no_license
evgenykol/otus_cpp_08
3b03c40308b7d3f42b26681f2f175f6548e564f6
5469e040df8dda536599f9ddff75acd76bd542cc
refs/heads/master
2021-05-02T00:17:04.577567
2018-02-11T19:55:12
2018-02-11T19:55:12
120,941,384
0
0
null
null
null
null
UTF-8
C++
false
false
1,819
cpp
//http://acm.timus.ru/problem.aspx?space=1&num=1837 #include <iostream> #include <map> #include <set> #include <string> #include <queue> using namespace std; int main() { #ifndef ONLINE_JUDGE freopen("1837_input.txt", "rt", stdin); //freopen("h_output.txt", "wt", stdout); #endif map<string, set<string>> persons; int commands = 0; cin >> commands; for(int i = 0; i < commands; ++i) { string names[3]; cin >> names[0] >> names[1] >> names[2]; persons[names[0]].insert({names[1], names[2]}); persons[names[1]].insert({names[0], names[2]}); persons[names[2]].insert({names[0], names[1]}); } // for(auto p : persons) // { // cout << p.first << ": "; // for(auto tm : p.second) // { // cout << tm << " "; // } // cout << endl; // } // cout << endl; string top; map<string, int> rating; if(persons.count("Isenbaev")) { top = "Isenbaev"; queue<string> q; q.push(top); map<string, bool> used; used[top] = true; while(!q.empty()) { auto v = q.front(); q.pop(); for(auto vv : persons[v]) { if(!used[vv]) { used[vv] = true; q.push(vv); rating[vv] = rating[v]+1; } } } } for(auto p : persons) { cout << p.first << " "; if (p.first == "Isenbaev") { cout << "0"; } else if(rating[p.first]) { cout << rating[p.first]; } else { cout << "undefined"; } cout << endl; } return 0; }
[ "edkolotilov@gmail.com" ]
edkolotilov@gmail.com
58c6e2863ef82cb8ac879216d34e86cf3d35766b
a2966d90e450d5e20df96e97886e6cc37a7cf021
/dropapples/main.cpp
4155e2ef6b0a2cf3481544687c978fd2b42e3ea3
[]
no_license
random25umezawa/my_problem
978013acc80ae8c79305a099f86d41e09740be4a
728c3f0d380d4bb9f4c0e9e172c0e2f8661af728
refs/heads/master
2020-04-30T13:24:34.639812
2019-03-28T17:45:43
2019-03-28T17:45:43
176,856,912
0
0
null
null
null
null
UTF-8
C++
false
false
516
cpp
#include <iostream> #include <vector> using namespace std; int main() { while(true) { int n; cin >> n; if(n==0) break; int dp[127][126] = {}; for(int i = 0; i < n; i++) { int x,y,v; cin >> x >> y >> v; dp[x][y/v]++; } for(int y = 1; y <= 125; y++) { for(int x = 1; x <= 125; x++) { dp[x][y] = max(dp[x][y-1],max(dp[x-1][y-1],dp[x+1][y-1]))+dp[x][y]; } } int ans = 0; for(int x = 1; x <= 125; x++) { ans = max(ans,dp[x][125]); } cout << ans << endl; } return 0; }
[ "bday7125@gmail.com" ]
bday7125@gmail.com
814f4b80d910f114608e6d7aee7fd36ab3dbfe97
c51febc209233a9160f41913d895415704d2391f
/library/ATF/FONT2DVERTEXInfo.hpp
30f71e7a61d1368101112ab559af92ae1569f326
[ "MIT" ]
permissive
roussukke/Yorozuya
81f81e5e759ecae02c793e65d6c3acc504091bc3
d9a44592b0714da1aebf492b64fdcb3fa072afe5
refs/heads/master
2023-07-08T03:23:00.584855
2023-06-29T08:20:25
2023-06-29T08:20:25
463,330,454
0
0
MIT
2022-02-24T23:15:01
2022-02-24T23:15:00
null
UTF-8
C++
false
false
504
hpp
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <FONT2DVERTEX.hpp> START_ATF_NAMESPACE namespace Info { using FONT2DVERTEXctor_FONT2DVERTEX1_ptr = int64_t (WINAPIV*)(struct FONT2DVERTEX*); using FONT2DVERTEXctor_FONT2DVERTEX1_clbk = int64_t (WINAPIV*)(struct FONT2DVERTEX*, FONT2DVERTEXctor_FONT2DVERTEX1_ptr); }; // end namespace Info END_ATF_NAMESPACE
[ "b1ll.cipher@yandex.ru" ]
b1ll.cipher@yandex.ru
7ef8a74ceff8b45e37723b4fcfa5c7d94f8d292b
adf253ebc9c3bb326a727d87ba2e071ded76d608
/wallet/work.cpp
03d17f7e022fc7f1aacc04430b73839f5dd688d0
[ "MIT" ]
permissive
NeblioTeam/neblio
5e0da815df7f1d69d04090fe5e7fed2445962dce
cebf9fcb1fb4e9935fcfdf459d5185488a2c04e5
refs/heads/master
2023-05-01T20:35:36.266611
2023-03-02T07:31:07
2023-03-02T07:31:07
98,357,215
143
71
MIT
2023-04-19T10:07:40
2017-07-25T23:06:34
C++
UTF-8
C++
false
false
1,575
cpp
#include "work.h" #include "globals.h" #include "txdb-lmdb.h" #include "util.h" // miner's coin base reward int64_t GetProofOfWorkReward(const ITxDB& txdb, int64_t nFees) { // Miner reward: 2000 coin for 500 Blocks = 1,000,000 coin int64_t nSubsidy = 2000 * COIN; const int bestHeight = txdb.GetBestChainHeight().value_or(0); if (bestHeight == 0) { // Total premine coin, after the first 501 blocks are mined there will be a total of 125,000,000 nSubsidy = 124000000 * COIN; } // 0 reward for PoW blocks after 500 if (bestHeight > 500) { nSubsidy = 0; } if (fDebug) NLog.write(b_sev::debug, "GetProofOfWorkReward() : create={} nSubsidy={}", FormatMoney(nSubsidy), nSubsidy); return nSubsidy + nFees; } // miner's coin stake reward based on coin age spent (coin-days) int64_t GetProofOfStakeReward(const ITxDB& txdb, int64_t nCoinAge, int64_t nFees) { // CBlockLocator locator; int64_t nRewardCoinYear = COIN_YEAR_REWARD; // 10% reward up to end NLog.write(b_sev::info, "Block Number {}", txdb.GetBestChainHeight().value_or(0)); int64_t nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8); NLog.write(b_sev::info, "coin-Subsidy {}", nSubsidy); NLog.write(b_sev::info, "coin-Age {}", nCoinAge); NLog.write(b_sev::info, "Coin Reward {}", nRewardCoinYear); if (fDebug) NLog.write(b_sev::debug, "GetProofOfStakeReward(): create={} nCoinAge={}", FormatMoney(nSubsidy), nCoinAge); return nSubsidy + nFees; }
[ "info@afach.de" ]
info@afach.de
bfae8fadbd693c302eb990256f9aaad1a0506839
10667399019171140970f0a100ff52cecb9dbc42
/24.10.2018.Hometask/TaskDigits.cpp
97185349ff6508d1bbe6d495745439d854ec8ec3
[]
no_license
PolinaTur/Hometask
6ebd448a6bae26f335fdd6007a914ba07482f5de
bbeaba247f4e29eb278e8fcc5a42e7ae23269058
refs/heads/master
2020-04-01T15:43:04.200463
2018-12-19T14:59:38
2018-12-19T14:59:38
153,348,600
0
0
null
null
null
null
UTF-8
C++
false
false
2,699
cpp
#include <iostream> #include <cmath> int AmountOfDigits(long long number); long long InPutNumber(); int MinDigit(long long number); int MaxDigit(long long number); bool IsPrimeNumber(long long number); using namespace std; int main() { char escape = 'y'; while (escape == 'y' || escape == 'Y') { long long number = InPutNumber(); cout << "The amount of digits is - " << AmountOfDigits(number) << endl; cout << "The minimum digit is - " << MinDigit(number) << endl; cout << "The maximum digit is - " << MaxDigit(number) << endl; if (IsPrimeNumber(number) == 1) { cout << "This number is prime"; } else { cout << "This number isn't prime"; } cout << "If you want to continue enter y or Y"; cin >> escape; system("cls"); } system("pause"); return 0; } int AmountOfDigits(long long number) { int i = 1; number = abs(number); while (number >= 1) { i++; number = number / (10 * i); } return i; } int MinDigit(long long number) { int digit_min = 9, digit = 0; number = abs(number); while (number >= 1) { digit = number % 10; if (digit_min > digit) { digit_min = digit; } number /= 10; } return digit_min; } int MaxDigit(long long number) { int digit = 0, digit_max = 0; number = abs(number); while (number > 0) { digit = number % 10; if (digit_max < digit) { digit_max = digit; } number /= 10; } return digit_max; } long long InPutNumber() { long long number; cout << "Please enter number "; cin >> number; return number; } bool IsPrimeNumber(long long number) { for (int i = 2; i < sqrt(number); i++) { if (!(number % i)) { return false; } } return true; } //int Digits(long long number) //{ // int i = 1, digit = 0; // number = abs(number); // while (number >= 1) // { // int counter0= 0, counter1 = 0; // digit = number % 10; // switch (digit) // { // // // case 0: // { // ++counter0; // break; // } // case 1: // { // ++counter1; // break; // } // case 2: // { // ++counter2; // break; // } // case 3: // { // ++counter3; // break; // } // case 4: // { // ++counter4; // } // case 5: // { // ++counter5; // // } // case 6: // { // ++counter6; // break; // } // case 7: // { // ++counter7; // break; // } // case 8: // { // ++counter8; // break; // } // case 9: // { // ++counter9; // break; // } // default : // { // cout << "error"; // } // // // // // } // // return 0; //}
[ "noreply@github.com" ]
noreply@github.com
0d177bbe9060e5b7dff0367fe1b8697f6969848c
38d2133487a508805a18e634cb21788df37b3bb1
/updateex/NotifyThread.cpp
7884f0d30ed068777f30ad3d3397c6302ad9d5e7
[ "BSD-3-Clause" ]
permissive
barbalion/farplug-alvls
dcaf7758e34df02c56f5d0fd0318df2bf7cf8ca2
d26fb36abdac642b18def09d63b8d70b5d39cbc9
refs/heads/master
2021-05-09T10:05:41.410464
2018-01-25T18:40:17
2018-01-25T18:40:17
118,952,115
3
0
null
null
null
null
UTF-8
C++
false
false
2,902
cpp
#define WM_TRAY_TRAYMSG WM_APP + 0x00001000 #define NOTIFY_DURATION 10000 LRESULT CALLBACK tray_wnd_proc(HWND wnd, UINT msg, WPARAM w_param, LPARAM l_param) { if (msg == WM_TRAY_TRAYMSG && l_param == WM_LBUTTONDBLCLK) PostQuitMessage(0); return DefWindowProc(wnd, msg, w_param, l_param); } DWORD WINAPI NotifyProc(LPVOID) { HICON tray_icon=nullptr; HWND tray_wnd=nullptr; WNDCLASSEX tray_wc; NOTIFYICONDATA tray_icondata; ZeroMemory(&tray_wc, sizeof(tray_wc)); ZeroMemory(&tray_icondata, sizeof(tray_icondata)); tray_icon=ExtractIcon(GetModuleHandle(nullptr), Info.ModuleName, 0); tray_wc.cbSize=sizeof(WNDCLASSEX); tray_wc.style=CS_HREDRAW|CS_VREDRAW; tray_wc.lpfnWndProc=&tray_wnd_proc; tray_wc.cbClsExtra=0; tray_wc.cbWndExtra=0; tray_wc.hInstance=GetModuleHandle(nullptr); tray_wc.hIcon=tray_icon; tray_wc.hCursor=LoadCursor(nullptr, IDC_ARROW); tray_wc.hbrBackground=(HBRUSH)(COLOR_WINDOW + 1); tray_wc.lpszMenuName=nullptr; tray_wc.lpszClassName=L"UpdateNotifyClass"; tray_wc.hIconSm=tray_icon; if (RegisterClassEx(&tray_wc)) { tray_wnd=CreateWindow(tray_wc.lpszClassName, L"", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, GetModuleHandle(nullptr), nullptr); if (tray_wnd) { tray_icondata.cbSize=NOTIFYICONDATA_V3_SIZE;//sizeof(NOTIFYICONDATA); tray_icondata.uID=1; tray_icondata.hWnd=tray_wnd; tray_icondata.uFlags=NIF_ICON|NIF_MESSAGE|NIF_INFO|NIF_TIP; tray_icondata.hIcon=tray_icon; tray_icondata.uTimeout=NOTIFY_DURATION; tray_icondata.dwInfoFlags=NIIF_INFO|NIIF_LARGE_ICON; FSF.sprintf(tray_icondata.szInfo,MSG(MTrayNotify),CountDownload,CountUpdate); lstrcpy(tray_icondata.szInfoTitle, MSG(MName)); lstrcpy(tray_icondata.szTip,tray_icondata.szInfo); tray_icondata.uCallbackMessage=WM_TRAY_TRAYMSG; if (Shell_NotifyIcon(NIM_ADD, &tray_icondata)) { size_t n=CountDownload; for (;;) { if (n!=CountDownload) { n++; FSF.sprintf(tray_icondata.szInfo,MSG(MTrayNotify),CountDownload,CountUpdate); lstrcpy(tray_icondata.szInfoTitle, MSG(MName)); lstrcpy(tray_icondata.szTip,tray_icondata.szInfo); Shell_NotifyIcon(NIM_MODIFY, &tray_icondata); } MSG msg; if (PeekMessage(&msg,nullptr,0,0,PM_NOREMOVE)) { GetMessage(&msg,nullptr,0,0); if (msg.message == WM_CLOSE) break; } if (GetStatus()!=S_DOWNLOAD) { PostQuitMessage(0); break; } TranslateMessage(&msg); DispatchMessage(&msg); } } Shell_NotifyIcon(NIM_DELETE, &tray_icondata); DestroyWindow(tray_wnd); tray_wnd=nullptr; } } if (tray_icon) DestroyIcon(tray_icon); UnregisterClass(tray_wc.lpszClassName, GetModuleHandle(nullptr)); CloseHandle(hNotifyThread); hNotifyThread=nullptr; return 0; }
[ "barbalion@gmail.com" ]
barbalion@gmail.com
9f1b80fccd89ebcf6ce438a176edb3aebd3d7c55
61304bfb26ac0615629ebd44ecfcff2dce803fcb
/snakeAndBlocks.cpp
762a112fb5dc6c1e292f578028dc4f0b13990511
[]
no_license
gokul1998/Codechef
c6109d5ade6c1fcfbb581647ed0ff8c97b441ccc
253a779a0c669cb2b41d3f1ede1bdf0f7259b40e
refs/heads/master
2020-06-23T09:48:58.653802
2019-07-24T08:11:33
2019-07-24T08:14:06
198,589,391
3
0
null
null
null
null
UTF-8
C++
false
false
1,224
cpp
#include<bits/stdc++.h> using namespace std; int minimum(int a,int b,int c){ if(a<=b && a<=c)return a; else if(b<=c && b<=a)return b; else return c; } int main(){ int n,m,mini=INT_MAX; cin>>n>>m; int a[n][m],i,j; int dp[n][m]; for(i=0;i<n;i++){ for(j=0;j<m;j++) { cin>>a[i][j]; dp[i][j]=0; } } /*cout<<"nexxxx"<<endl; 1 2 3 4 5 6 7 8 9 for(i=0;i<n;i++){ for(j=0;j<m;j++){ cout<<dp[i][j]<<" "; } cout<<endl; }*/ for(j=0;j<m;j++){ dp[n-1][j]=a[n-1][j]; //cout<<"hello"<<dp[n-1][j]<<endl; } /*for(i=0;i<n;i++){ for(j=0;j<m;j++){ cout<<dp[i][j]<<" "; } cout<<endl; }*/ //cout<<"next"<<endl; for(i=n-2;i>=0;i--){ for(j=0;j<m;j++){ if(j-1>=0 && j+1<m)mini=minimum(a[i][j-1],a[i][j],a[i][j+1]); else if(j-1>=0)mini=min(a[i][j-1],a[i][j]); else mini=min(a[i][j],a[i][j+1]); //cout<<"mini = "<<mini<<" dp[i-1][j] = "<<dp[i+1][j]<<endl; dp[i][j]=dp[i+1][j]+mini; } } for(i=0;i<n;i++){ for(j=0;j<m;j++){ cout<<dp[i][j]<<" "; } cout<<endl; } mini=INT_MAX; for(i=0;i<m;i++){ if(mini>dp[0][i])mini=dp[0][i]; } cout<<"minimum blocks = "<<mini; } /*wrong program*/
[ "gokulakrishnan.parir@fireeye.com" ]
gokulakrishnan.parir@fireeye.com
5864869e53bcdb2bc651bb2bdb9e768e2ac76448
b0cd57ef1e61ed038caf00ffec36b677fedefbe9
/main.cpp
11c5ba80b52b4eefd538c7c7ba4bf6a9b474ec52
[]
no_license
SanjanaVenkat/practiceproblem2
5a51283f2091e425f5dec29c5255b6ac27ea3365
254c1c3a912bda3f02ab8f4964a06433a15b2bd7
refs/heads/master
2020-04-16T15:07:06.183784
2019-01-14T17:09:59
2019-01-14T17:09:59
165,691,720
0
0
null
null
null
null
UTF-8
C++
false
false
1,332
cpp
#include <iostream> #include <cstring> #include <iomanip> #include "node.h" using namespace std; Node* addInfo(Node* start) { char i[1000]; Node* current = start; Node* first = start; Info* in = new Info(); cout << "Enter info" << endl; cin.get(i, 1000); in->setInfo(i); if (current == NULL) { current = new Node(in); first = current; } else { while (current->getNext() != NULL) { current = current->getNext(); } Node* n = new Node(in); current->setNext(n); } return first; } void printLargest(Node* start) { Node* current = start; Node* largest = start; while (current != NULL) { Info* i = current->getInfo(); Info* in = largest->getInfo(); //cout << i->getInfo() << " " << strlen(i->getInfo())<< endl; if (strlen(i->getInfo()) >= strlen(in->getInfo())) { largest = current; } current = current->getNext(); } Info* info = largest->getInfo(); cout << "String with the most info (the longest string): "; cout << info->getInfo() << " " << strlen(info->getInfo()) << endl; } int main() { Node* start = NULL; char response[1000]; char y[] = "y"; char n[] = "n"; while (strcmp(n, response) != 0) { start = addInfo(start); cout << "y/n" << endl; cin.get(response, 1000); } printLargest(start); return 0; }
[ "noreply@github.com" ]
noreply@github.com
7e4229f0b90771518829456517ed44878a64be0f
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/admin/darwin/src/msitools/orca/exportd.h
80cc40e1606442a69e7adc4e5811436286073ebc
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
1,638
h
//+------------------------------------------------------------------------- // // Microsoft Windows // // Copyright (C) Microsoft Corporation, 1998 // //-------------------------------------------------------------------------- #if !defined(AFX_EXPORTD_H__25468EE2_FC84_11D1_AD45_00A0C9AF11A6__INCLUDED_) #define AFX_EXPORTD_H__25468EE2_FC84_11D1_AD45_00A0C9AF11A6__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // ExportD.h : header file // ///////////////////////////////////////////////////////////////////////////// // CExportD dialog class CExportD : public CDialog { // Construction public: CExportD(CWnd* pParent = NULL); // standard constructor CStringList* m_plistTables; CString m_strSelect; CCheckListBox m_ctrlList; // Dialog Data //{{AFX_DATA(CExportD) enum { IDD = IDD_EXPORT_TABLE }; CString m_strDir; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CExportD) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CExportD) virtual BOOL OnInitDialog(); virtual void OnOK(); afx_msg void OnBrowse(); afx_msg void OnSelectAll(); afx_msg void OnClearAll(); afx_msg void OnInvert(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #endif // !defined(AFX_EXPORTD_H__25468EE2_FC84_11D1_AD45_00A0C9AF11A6__INCLUDED_)
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com