blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
12ef049e05095877590362e3fab8b1c05301c2c0
|
7276439b533f4874955c872f478627a243631728
|
/EU4toV2/Source/EU4World/EU4Leader.h
|
98fcd3a003f5165a9f8c4c5c1ada08891ff088dc
|
[
"MIT"
] |
permissive
|
ParadoxGameConverters/paradoxGameConverters
|
406ff200abad3d43e7f4ad57a88311b2074ccacc
|
a994edeb4618c2e60bc1b1e26327fe504f94aa06
|
refs/heads/master
| 2021-06-03T15:31:51.717844
| 2020-03-28T21:18:56
| 2020-03-28T21:18:56
| 36,950,594
| 71
| 38
|
MIT
| 2018-12-23T17:15:26
| 2015-06-05T19:10:11
|
C++
|
UTF-8
|
C++
| false
| false
| 1,930
|
h
|
EU4Leader.h
|
/*Copyright(c) 2018 The Paradox Game Converters Project
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef EU4_LEADER_H_
#define EU4_LEADER_H_
#include "Date.h"
#include "newParser.h"
namespace EU4
{
class leader: commonItems::parser
{
public:
leader(std::istream& theStream);
std::string getName() const { return name; }
int getFire() const { return fire; }
int getShock() const { return shock; }
int getManuever() const { return manuever; }
int getSiege() const { return siege; }
date getActivationDate() const { return activationDate; }
int getID() const { return id; }
bool isLand() const;
bool isAlive() const;
private:
std::string name;
std::string type;
bool female;
int fire;
int shock;
int manuever;
int siege;
std::string country;
std::string personality;
date activationDate;
date deathDate;
int id;
int monarchID;
};
}
#endif // EU4_LEADER_H_
|
63ff864aaa8773b1bb58b9d5dea4e44e64f3bafd
|
7af7797004c2ca5df59d90e8653ac31a1c69e73b
|
/TicTacToe.cpp
|
ace21be6e1ddd9d008382d80cd0ac96b81b0bfe9
|
[] |
no_license
|
ruthsilcoff/TicTacToe
|
cc79bee5d536372df7999171799d3f9afa95a9fa
|
a5f7509a47a9e260850e3f5602a8b36bf393853e
|
refs/heads/master
| 2022-05-26T01:12:15.235058
| 2020-05-02T20:55:27
| 2020-05-02T20:55:27
| 260,773,022
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,838
|
cpp
|
TicTacToe.cpp
|
#include<iostream>
#include<string>
using namespace std;
void greetAndInstruct(); //Q1
void displayBoard(char board[]); //Q2
bool checkIfLegal(int cellNbre, char board[]); //Q3
bool checkWinner(char board[]); //Q3
void computerMove(char board[]); //Q4
char board[27];
string num[27] ={"1","2","3","10","11","12","19","20","21","4","5","6","13","14","15","22","23","24","7","8","9","16","17","18","25","26","27"};
char XorY; //used to store winner
bool tie;
int main() //Q5
{
//initilize a new game
greetAndInstruct();
cout << "\n\nThe game has started";
int move;
tie = false;
bool winner = false;
//run until game ends (someone wins, tie happens, or illegal move played)
while(true)
{
//player's turn
cout << "\nHere is the copy of the current board:\n";
displayBoard(board);
cout << "\n\nPick a number to place an X:\n";
cin >> move;
bool canPlay = checkIfLegal(move, board); //1 is true, 0 is false
if(canPlay == 0)
{
cout << "\nIllegal moves are against the rules. Game over :(";
break;
}
//find place to put move
int loc=0;
for(int i = 0; i < 27; i ++)
{
if(num[i]==to_string(move)) //to string
{
loc=i;
break;
}
}
board[loc]='X';
num[loc]="0";
winner = checkWinner(board);
if(winner == 1)
{
if(XorY=='X')
{
cout <<"\nPlayer has won\n";
displayBoard(board);
}
else
{
cout <<"\nComputer has won\n";
displayBoard(board);
}
cout << "Once someone wins the game is over!\n";
break;
}
if(tie)
{
cout << "\nTie Game.";
break;
}
//computer's turn
computerMove(board);
cout << "\nThe computer has taken its turn";
winner = checkWinner(board);
if(winner == 1)
{
if(XorY=='X')
{
cout <<"\nPlayer has won\n";
displayBoard(board);
}
else
{
cout <<"\nComputer has won\n";
displayBoard(board);
}
cout << "Once someone wins the game is over!\n";
break;
}
if(tie)
{
cout << "\nTie Game.";
break;
}
}
exit(0);
}
void greetAndInstruct()
{
cout << "Hello and welcome to Tic-Tac-Toe challenge: Player against Compuetr." << endl;
cout << "The board is numbered from 1 to 27 as per the following:\n";
cout << "1|2|3\t10|11|12\t19|20|21\n";
cout << "-----\t---------\t---------\n";
cout << "4|5|6\t13|14|15\t22|23|24\n";
cout << "-----\t---------\t---------\n";
cout << "7|8|9\t16|17|18\t25|26|27\n";
cout << "\nPlayer starts first. Simply input the number of the cell you want to occupy. Player's move is marked with X. Computer's move is marked with O.\n";
cout << "Start?(y/n""): ";
string start ="";
cin >> start;
if(start=="n")
{
exit(0); //program exits
}
//otherwise program continues and game starts
}
void displayBoard(char board[])
{
cout <<endl; //clear line for display
int pos=0;
for(int i=0;i<3;i++)
{
for(int j=0;j<9;j++)
{
if(board[pos]==0)
{
//no moved is played there yet, so display number
cout<<num[pos];
}
else
{
//move is played so display character (X or O)
cout<<board[pos];
}
pos++;
if((j+1)%3==0)
{
cout<<"\t";
}
else
{
cout<<"|";
}
}
if(i!=2)
{
cout << "\n------\t---------\t---------\n";
}
}
}
bool checkIfLegal(int cellNbre, char board[])
{
if(cellNbre > 27 || cellNbre < 0)
{
cout << "\nIllegal move, not a real position";
return false;
}
if(board[cellNbre-1] !=0)
{
cout << "\nIllegal move, player already went there";
return false; //character already there
}
return true;
}
bool checkWinner(char board[])
{
int x = 0;
//checks if there is a 3 in a row for rows
for(int i=0; i<25;i+=3)
{
if(board[i]==board[i+1] && board[i+1]==board[i+2] && board[i] != 0)
{
XorY=board[i];
break;
}
}
while(x<19)
{
if(board[0+x]==board[4+x] && board[4+x]==board[8+x] && board[x] != 0)
{
XorY=board[x];
break;
}
x+=9;
}
//checks for columns
for(int i=0;i<9;i++)
{
if(board[i]==board[i+9] && board[i+9]==board[i+18] && board[i] != 0)
{
XorY=board[i];
break;
}
}
x=0;
while(x<3)
{
if(board[x]==board[x+12] && board[x+12]==board[x+24] && board[x] != 0)
{
XorY=board[x];
break;
}
x++;
}
//checks for diagonals
for(int i=0;i<7;i+=3)
{
if(board[i]==board[i+10] && board[i+10]==board[i+20] && board[i] != 0)
{
XorY=board[i];
break;
}
}
for(int i=2; i<9;i+=3)
{
if(board[i]==board[i+8] && board[i+8]==board[i+16] && board[i] != 0)
{
XorY=board[i];
break;
}
}
if(board[0]==board[13]&&board[13]==board[26] && board[0] != 0)
{
XorY=board[0];
}
if(board[8]==board[13]&&board[13]==board[18] && board[8] != 0)
{
XorY=board[8];
}
//check if in same cell across all tables
for(int i=0;i<21;i++)
{
if(board[i]==board[i+3] && board[i+3]==board[i+6] && board[i] != 0)
{
XorY=board[i];
break;
}
}
//if no winner, check if board is full, then declare tie if yes
bool full=true;
for(int i = 0; i <27; i ++)
{
if(board[i]==0)
{
full=false;
}
}
//result
if(XorY=='X' || XorY =='O')
{
return true;
}
else if(full)
{
tie=true;
return false;
}
else
{
return false;
}
}
void computerMove(char board[])
{
bool checkedWin;
for(int i=0;i<27;i++)
{
if(board[i]!='X' && board[i] != 'O')
{
//see if computer can win
board[i]='O';
checkedWin=checkWinner(board);
if(checkedWin)
{
XorY='\0';
tie=false;
return;
}
XorY='\0';
tie=false;
//see if player can win and block
board[i]='X';
checkedWin=checkWinner(board);
if(checkedWin)
{
board[i]='O'; //blocked player
XorY='\0';
tie=false;
return;
}
board[i]='\0'; //reset if don't use
}
}
//else play random
for(int i=0;i<27;i++)
{
if(board[i]==0)
{
board[i]='O';
return;
}
}
}
|
5197a2bc711e71a752353fa517da630aa51a6a2b
|
57f30cfa36bdf2a679b8ba10df3bdb1d95e9e6a9
|
/src/test.cpp
|
535950469dd0c81a2da6b3235398e4a3bf5d625b
|
[] |
no_license
|
squall1988/pythonStudy
|
4d8b5928c4a4efe2f0cf43cd792a83699cae4389
|
faebfcc9b0948ec813a117f48d41453a9be6f9cd
|
refs/heads/master
| 2016-09-05T23:53:59.377244
| 2015-06-26T09:00:27
| 2015-06-26T09:00:27
| 38,099,906
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 608
|
cpp
|
test.cpp
|
/*
* =====================================================================================
*
* Filename: test.cpp
*
* Description:
*
* Version: 1.0
* Created: 2015/06/26 16时45分05秒
* Revision: none
* Compiler: gcc
*
* Author: YOUR NAME (),
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
extern "C" {
extern float test_python(float *array, int len) {
for (int i = 0; i < len; i++) {
printf("%f\n", array[i]);
}
return 1.0;
}
}
|
cb718e9d117cf027981cef5ded18a03329f0c1c5
|
7afade08c4424a617f75f7bbc101d9caf9d3da31
|
/asteroids/src/model.cpp
|
f7d64a8f07ad4560cb7b6aa1c6b30010ee80d8ab
|
[] |
no_license
|
Small-Embedded-Systems/assignment-2-asteroids-W15016306
|
209709d0025705eef720d95aaaa201aa2ff02aec
|
cc1065f19a16e68f6b11445ddfd32ca2b6051488
|
refs/heads/master
| 2021-01-23T01:51:39.889798
| 2017-05-12T21:13:56
| 2017-05-12T21:13:56
| 85,941,142
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,131
|
cpp
|
model.cpp
|
//Joshua Higgins - W15016306
//Connor Moore - W15012760
/* Asteroids model */
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <math.h>
#include "model.h"
#include "utils.h"
#include "asteroids.h"
#include "view.h"
//variable Decleration
static const int heapsize = 25;
static node_t heap[heapsize];
static node_t *freenodes;
static int n = 0;
static float shot0[4] = {3000,3000,0,0},
shot1[4] = {3000,3000,0,0},
shot2[4] = {3000,3000,0,0},
shot3[4] = {3000,3000,0,0},
shot4[4] = {3000,3000,0,0};
static bool collision = false;
static int hits = 15;
static int newPosX, newPosY;
static int asteroidCount, totalAsteroids, destroyedAsteroids;
static int fired, firedCount;
static bool asteroidSplitMode = false;
double x1, y1, x2, y2, x3, y3;
static double acceleration = 0.0;
float bulletAcceleration = 4;
float newHeading, currentHeading;
//Heap Creation for linked list
void initialise_heap(void)
{
for( n=0 ; n<(heapsize-0) ; n++) {
heap[n].next = &heap[n+1];
}
heap[n].next = NULL;
freenodes = &heap[0];
}
node_t *allocnode(void)
{
node_t *node = NULL;
if( freenodes ) {
node = freenodes;
freenodes = freenodes->next;
}
return node;
}
void freenode(node_t *n)
{
n->next = freenodes;
freenodes = n;
}
//Games physics
void physics(void)
{
//shio movement
if(acceleration > 0.0)
{
player.p.x += acceleration*cos(radians(newHeading));
player.p.y += acceleration*sin(radians(newHeading));
if(acceleration > 0.5)
{
acceleration = acceleration-0.006;
}
else
{
acceleration = acceleration-0.002;
}
}
x1=-7*cos(radians(player.heading)) - 7*sin(radians(player.heading));
y1=-6*sin(radians(player.heading)) + 6*cos(radians(player.heading));
x2= -6* cos(radians(player.heading)) - -6*sin(radians(player.heading));
y2= -6* sin(radians(player.heading)) + -6*cos(radians(player.heading));
x3= 12*cos(radians(player.heading)) - sin(radians(player.heading));
y3= 12*sin(radians(player.heading)) + cos(radians(player.heading));
//Ship Wrapping
if(player.heading >= 360)
{
player.heading = 0;
}
if(player.heading <= -360)
{
player.heading = 0;
}
if(player.p.y < -10)
{
player.p.y = 272;
}
if(player.p.y > 282)
{
player.p.y = 0;
}
if(player.p.x > 490)
{
player.p.x = 40;
}
if(player.p.x < 40)
{
player.p.x = 480;
}
//destroy check
if(destroyedAsteroids == 11)
{
asteroidCount = 1;
totalAsteroids = 1;
destroyedAsteroids = 0;
}
}
///////////////////////////////////////////////////////////////
// Asteroid Control //
///////////////////////////////////////////////////////////////
//creates elements for list
void strike(struct particle *l)
{
if(asteroidCount < 5){
if(!asteroidSplitMode){
l->x = randrange(0,480);
l->y = randrange(0,270);
l->size = 2;
l->heading = randrange(-259,360);
l->ttl = 10;
l->active = true;
l->type = 0;
}
else
{
l->x = randrange(newPosX,newPosX+15);
l->y = randrange(newPosY,newPosY+15);
l->size = 1;
l->heading = randrange(-259,360);
l->ttl = 10;
l->active = true;
l->type = 0;
asteroidSplitMode = false;
}
asteroidCount++;
totalAsteroids++;
}
if((fired == 1)&&(firedCount <=5))
{
fired = 0;
l->x = player.p.x+x3;
l->y = player.p.y+y3;
l->active = true;
l->distanceCount = 0;
l->count = randrange(0,90000);
l->heading = player.heading;
l->type = 1;
if(shot0[3]==0)
{
shot0[2]=l->count;
shot0[3]=1;
}
else if(shot1[3]==0)
{
shot1[2]=l->count;
shot1[3]=1;
}
else if(shot2[3]==0)
{
shot2[2]=l->count;
shot2[3]=1;
}
else if(shot3[3]==0)
{
shot3[2]=l->count;
shot3[3]=1;
}
if(shot4[3]==0)
{
shot4[2]=l->count;
shot4[3]=1;
}
firedCount++;
}
else{
fired = 0;
}
}
///////////////////////////////////////////////////////////////
// List Managment //
///////////////////////////////////////////////////////////////
//updates elements in list
void update(struct particle *l)
{
for( ; l ; l = l->next ) {
if(firedCount < 0)
{
firedCount = 0;
}
if((!l->next->active)) {
if(l->type == 0)
{
destroyedAsteroids++;
struct particle *expired = l->next;
l->next = l->next->next;
freenode(expired);
}
if(l->type == 1)
{
firedCount--;
fired = 0;
struct particle *expired = l->next;
l->next = l->next->next;
freenode(expired);
}
}
if(l->type == 0){
//Bullets and Asteroids
int size;
if(l->size == 2)
{
size = 30;
}
else if(l->size == 1)
{
size = 15;
}
if ((((shot0[0] >= l->x-size)&&(shot0[0] <= l->x+size)) && ((shot0[1] >= l->y-size)&&(shot0[1] <= l->y+size))&&(shot0[3]==1)))
{
collision = true;
shot0[3]=0;
}
if ((((shot1[0] >= l->x-size)&&(shot1[0] <= l->x+size)) && ((shot1[1] >= l->y-size)&&(shot1[1] <= l->y+size))&&(shot1[3]==1)))
{
collision = true;
shot1[3]=0;
}
if ((((shot2[0] >= l->x-size)&&(shot2[0] <= l->x+size)) && ((shot2[1] >= l->y-size)&&(shot2[1] <= l->y+size))&&(shot2[3]==1)))
{
collision = true;
shot2[3]=0;
}
if ((((shot3[0] >= l->x-size)&&(shot3[0] <= l->x+size)) && ((shot3[1] >= l->y-size)&&(shot3[1] <= l->y+size))&&(shot3[3]==1)))
{
collision = true;
shot3[3]=0;
}
if ((((shot4[0] >= l->x-size)&&(shot4[0] <= l->x+size)) && ((shot4[1] >= l->y-size)&&(shot4[1] <= l->y+size))&&(shot4[3]==1)))
{
collision = true;
shot4[3]=0;
}
if(collision)
{
if(l->size == 2){
l->size=1;
asteroidSplitMode = true;
asteroidCount --;
newPosX = l->x;
newPosY = l->y;
if(firedCount >0){
firedCount-=1;
}
}
else if(l->size == 1)
{
l->active = false;
asteroidSplitMode = false;
if(firedCount > 0){
firedCount-=1;
}
}
collision = false;
}
//shield collision detection
if(!shield && ((player.p.x >= l->x-30)&&(player.p.x <= l->x+30)) && ((player.p.y >= l->y-30)&&(player.p.y <= l->y+30)))
{
lives--;
shield = true;
player.p.x = 240;
player.p.y = 136;
}
if(shield && ((player.p.x >= l->x-30)&&(player.p.x <= l->x+30)) && ((player.p.y >= l->y-30)&&(player.p.y <= l->y+30)))
{
shieldCollision = true;
damage--;
}
else
{
shieldCollision = false;
}
//astroid speed
if(l->size == 2)
{
l->x += 1*cos(radians(l->heading));
l->y += 1*sin(radians(l->heading));
}
if(l->size == 1){
l->x += 1.5*cos(radians(l->heading));
l->y += 1.5*sin(radians(l->heading));
}
//content wrapping
if(l->y > 300)
{
l->y = -30;
}
if(l->y < -30)
{
l->y = 300;
}
if(l -> x < 0)
{
l->x = 500;
}
if(l -> x > 500)
{
l->x = 0;
}
}
//Bullets
if(l->type ==1){
if(l->count == shot0[2])
{
if(shot0[3]==0)
{
l->active = false;
}
}
if(l->count == shot1[2])
{
if(shot1[3]==0)
{
l->active = false;
}
}
if(l->count == shot2[2])
{
if(shot2[3]==0)
{
l->active = false;
}
}
if(l->count == shot3[2])
{
if(shot3[3]==0)
{
l->active = false;
}
}
if(l->count == shot4[2])
{
if(shot4[3]==0)
{
l->active = false;
}
}
//Bullet Movement
l->x += 2*cos(radians(l->heading));
l->y += 2*sin(radians(l->heading));
l->distanceCount++;
if(l->distanceCount == 300)
{
l->active = false;
l->x = 3000;
l->y = 3000;
}
//Bullet Wrapping
if(l->x < 40)
{
l->x = 480;
}
else if(l->x > 480)
{
l->x = 40;
}
if(l->y < 0)
{
l->y = 270;
}
else if(l->y > 270)
{
l->y = 0;
}
//Bullet Position Tracking
if(l->count == shot0[2])
{
shot0[0]=l->x;
shot0[1]=l->y;
}
if(l->count == shot1[2])
{
shot1[0]=l->x;
shot1[1]=l->y;
}
if(l->count == shot2[2])
{
shot2[0]=l->x;
shot2[1]=l->y;
}
if(l->count == shot3[2])
{
shot3[0]=l->x;
shot3[1]=l->y;
}
if(l->count == shot4[2])
{
shot4[0]=l->x;
shot4[1]=l->y;
}
//Bullet/Ship Interaction
if(shield && l->active){
if(((player.p.x >= l->x-5)&&(player.p.x <= l->x+5)) && ((player.p.y >= l->y-5)&&(player.p.y <= l->y+5)))
{
damage-=10;
l->x = 3000;
l->y = 3000;
}
}
else if(((player.p.x >= l->x-5)&&(player.p.x <= l->x+5)) && ((player.p.y >= l->y-5)&&(player.p.y <= l->y+5))&&l->active)
{
lives--;
l->x = 3000;
l->y = 3000;
player.p.x = 240;
player.p.y = 136;
}
}
//shield reset
if(damage < 1)
{
lives --;
player.p.x = 240;
player.p.y = 136;
damage = 100;
shield = true;
}
}
}
struct particle *active = NULL;
void particle_system(void)
{
if((asteroidCount < 5)&&(totalAsteroids<10))
{
struct particle *spark = allocnode();
if(spark) {
spark->next = active;
active = spark;
strike(spark);
}
}
if((fired == 1) && (firedCount < 5))
{
struct particle *spark = allocnode();
if(spark) {
spark->next = active;
active = spark;
strike(spark);
}
}
update(active);
}
///////////////////////////////////////////////////////////////
// SHIP CONTROLS //
///////////////////////////////////////////////////////////////
void shipRight(void)
{
player.heading -=3;
}
void shipLeft(void)
{
player.heading +=3;
}
void shipUp(void)
{
newHeading = player.heading;
player.p.x += acceleration*cos(radians(player.heading));
player.p.y += acceleration*sin(radians(player.heading));
if(acceleration <= 1.5)
{
acceleration = acceleration+0.04;
}
}
void shipDown(void)
{
if(acceleration > 0.0)
{
acceleration = acceleration-0.004;
}
}
void setFire()
{
fired = 1;
}
|
cc85988368ba5142de3a63783d63d64a8c9341b8
|
49a497337f6892d9f2e3a32c07de88bd21734a54
|
/labs/lab5/Editor/ConstDocumentItem.cpp
|
3df40f2f598091d8fa4ab432c4825747fe9a352c
|
[] |
no_license
|
AnyaGl/ood
|
f8b39bce34868d171e0e539338f13098e5c06e5e
|
ec0e7dff3300362dc091369c0319540ad17d9f3a
|
refs/heads/master
| 2023-02-18T06:45:58.790351
| 2021-01-19T17:39:08
| 2021-01-19T17:39:08
| 293,276,494
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 543
|
cpp
|
ConstDocumentItem.cpp
|
#include "ConstDocumentItem.h"
CConstDocumentItem::CConstDocumentItem(Item const& item)
: m_item(item)
{
}
std::shared_ptr<const IImage> CConstDocumentItem::GetImage() const
{
if (std::holds_alternative<std::shared_ptr<IImage>>(m_item))
{
return std::get<std::shared_ptr<IImage>>(m_item);
}
return nullptr;
}
std::shared_ptr<const IParagraph> CConstDocumentItem::GetParagraph() const
{
if (std::holds_alternative<std::shared_ptr<IParagraph>>(m_item))
{
return std::get<std::shared_ptr<IParagraph>>(m_item);
}
return nullptr;
}
|
2e6794fd5faf4f17008364e4ac17ddc9f2fee531
|
7283326c73c2de62935a6a4e986ffc935117974d
|
/Source/VSMan/VSManGameMode.h
|
8c71cc7a856d04966c90b5a831f6823d3321e7be
|
[] |
no_license
|
AmadoJunior/BatteryCollectorUnrealEngine
|
635f94fb49b1834613a8fbc10d0bfc025f8f5902
|
785c3719ab8ab4e5768ca94dfd5a9bd5f7227e41
|
refs/heads/master
| 2023-03-28T10:49:25.133652
| 2021-03-24T06:15:53
| 2021-03-24T06:15:53
| 350,966,816
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 305
|
h
|
VSManGameMode.h
|
// Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "VSManGameMode.generated.h"
UCLASS(minimalapi)
class AVSManGameMode : public AGameModeBase
{
GENERATED_BODY()
public:
AVSManGameMode();
};
|
4832dd7f742a840c8a20d4d8facc8020d9843f46
|
7ea08b8f812f066518e7f2e8ca173ebb9062f3f0
|
/font.hpp
|
411d0b4fbf504c18c096a68627a888fd8a339989
|
[
"MIT"
] |
permissive
|
CobaltXII/boss
|
7524d7d1e60077bc0480b397f8214219c2c36ae5
|
e30a3364ab8b9318d59e69bb974cc5b840addfe3
|
refs/heads/master
| 2020-05-17T16:36:46.378671
| 2019-04-29T19:51:56
| 2019-04-29T19:51:56
| 183,823,496
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,334
|
hpp
|
font.hpp
|
// Decompress a VGA text mode font.
unsigned char* decompress(unsigned char* font,
int glyph_x_res,
int glyph_y_res)
{
// Allocate memory for the uncompressed font.
unsigned char* out = (unsigned char*)malloc(
glyph_x_res *
glyph_y_res *
256
);
if (!out) {
barf("Could not allocate font memory.");
}
// Calculate the length (in octets) of the font based on the dimensions of
// each glyph.
int font_length = (
glyph_x_res *
glyph_y_res *
32
);
// Decompress the font.
for (int i = 0; i < font_length; i++) {
for (int j = 0; j != 8; j++) {
// Little-endian machines will load fonts horizontally flipped as
// the font is compiled as big-endian.
if (is_big_endian) {
out[8 * i + j] = (font[i] >> j) & 1;
} else {
out[8 * i + (7 - j)] = (font[i] >> j) & 1;
}
}
}
return out;
}
// 8x8 VGA compressed text mode font (ASCII).
unsigned char cmp_vga_8x8[] = {
#include "8x8.inc"
};
// 8x8 VGA uncompressed text mode font (ASCII).
unsigned char* vga_8x8 = decompress(cmp_vga_8x8, 8, 8);
// 8x10 VGA compressed text mode font (ASCII).
unsigned char cmp_vga_8x10[] = {
#include "8x10.inc"
};
// 8x10 VGA uncompressed text mode font (ASCII).
unsigned char* vga_8x10 = decompress(cmp_vga_8x10, 8, 10);
// 8x12 VGA compressed text mode font (ASCII).
unsigned char cmp_vga_8x12[] = {
#include "8x12.inc"
};
// 8x12 VGA uncompressed text mode font (ASCII).
unsigned char* vga_8x12 = decompress(cmp_vga_8x12, 8, 12);
// 8x14 VGA compressed text mode font (ASCII).
unsigned char cmp_vga_8x14[] = {
#include "8x14.inc"
};
// 8x14 VGA uncompressed text mode font (ASCII).
unsigned char* vga_8x14 = decompress(cmp_vga_8x14, 8, 14);
// 8x15 VGA compressed text mode font (ASCII).
unsigned char cmp_vga_8x15[] = {
#include "8x15.inc"
};
// 8x15 VGA uncompressed text mode font (ASCII).
unsigned char* vga_8x15 = decompress(cmp_vga_8x15, 8, 15);
// 8x16 VGA compressed text mode font (ASCII).
unsigned char cmp_vga_8x16[] = {
#include "8x16.inc"
};
// 8x16 VGA uncompressed text mode font (ASCII).
unsigned char* vga_8x16 = decompress(cmp_vga_8x16, 8, 16);
// 8x32 VGA compressed text mode font (ASCII).
unsigned char cmp_vga_8x32[] = {
#include "8x32.inc"
};
// 8x32 VGA uncompressed text mode font (ASCII).
unsigned char* vga_8x32 = decompress(cmp_vga_8x32, 8, 32);
|
4ed622162337254797a7c65dc650688ad9754fa1
|
ca21d49c807f7cd70200fdde200a55964861405f
|
/word_wrap_problem/main.cpp
|
8d118ae49e43c21de2513277ad872113bf2a778b
|
[] |
no_license
|
mohamed-elalem/Algorithms
|
cb7c015c8672a29d8024853a0c4218172ca7c002
|
8fef0901a9b8c3f6521d5d9788a43e0b70c52fbb
|
refs/heads/master
| 2021-01-20T13:16:37.979543
| 2017-12-17T18:12:37
| 2017-12-17T18:12:37
| 82,684,100
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,556
|
cpp
|
main.cpp
|
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <stack>
#include <cstdio>
using namespace std;
int dp[100000], p[100000];
string words[100000];
int window = 80;
int wordCount = 0;
int pow2(int n) {
return n * n;
}
void solve() {
dp[0] = 0;
for(int i = 1; i <= wordCount; i++) {
int curLength = words[i - 1].size();
// cout << curLength << " ";
dp[i] = dp[i - 1] + pow2(window - curLength);
p[i] = i - 1;
for(int j = i - 1; j > 0; j--) {
curLength += words[j - 1].size() + 1;
if(curLength > window) {
break;
}
// cout << curLength << " ";
int state = dp[j - 1] + pow2(window - curLength);
if(state < dp[i]) {
dp[i] = state;
p[i] = j - 1;
}
}
// cout << " | " << dp[i] << endl;
}
}
int main()
{
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
while(!cin.eof()) {
cin >> words[wordCount++];
}
memset(p, -1, sizeof p);
for(int i = 0; i < 10000; i++) {
dp[i] = 0x9FFFFFF;
}
solve();
stack<int> lineBreaks;
for(int i = wordCount - 1; i != -1; i = p[i]) {
// cout << i << endl;
lineBreaks.push(i);
}
for(int i = 0; i < wordCount; i++) {
if(lineBreaks.top() == i) {
lineBreaks.pop();
cout << endl;
}
else if(i > 0){
cout << " ";
}
cout << words[i];
}
}
|
c1efa2a59855f2e828205168a02293363885137d
|
ffc1e21c5fd16cc8424a2845a9cd1a741b12ccdb
|
/Project1_Starter_Code/MatcherAutomaton.cpp
|
bddc0ab672cf4caf1b77068c00c2fd90273087d8
|
[] |
no_license
|
fogoplayer/Creative1
|
ea69da35433d350c40c93750a0690d1e6930622c
|
aa0d8c618a2947d83beb3c435675c056c3ab18fd
|
refs/heads/main
| 2023-09-05T01:26:38.722179
| 2021-11-04T14:50:14
| 2021-11-04T14:50:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,768
|
cpp
|
MatcherAutomaton.cpp
|
#include "MatcherAutomaton.h"
MatcherAutomaton::MatcherAutomaton(std::string toMatch, TokenType type) : Automaton(type) {
this->toMatch = toMatch;
this->type = type;
this->aType = "keyword";
}
//int MatcherAutomaton::Start(const std::string &input) {
//Don't need it because the base class has it implemented.
//}
void MatcherAutomaton::S0(const std::string &input) {
bool stillGood = true;
std::string matcher = this->toMatch;
if (this->toMatch.size() > input.size()) {
stillGood = false;
this->inputRead = 0;
}
else {
for(size_t i=0; i<this->toMatch.size(); i++){
//TODO: add an if stillGood is flase, to not do the rest to prevent out of bounds
if (input.at(i) == EOF || input.at(i) == '\n' || input.at(i) == '\t' || input.at(i) == ' ') {
stillGood = false;
this->inputRead = 0;
// if(i != 0){
// i = i - 1;
// }
}
if(stillGood) {
if((input.at(i) == matcher.at(i)) && stillGood){
this->inputRead += 1;
}
else {
stillGood = false;
this->inputRead = 0;
}
}
}
if (stillGood && this->toMatch.size() < input.size()) {
if(input.at(this->toMatch.size()) == EOF ||input.at(this->toMatch.size()) ==' ' || input.at(this->toMatch.size()) == '\t' || input.at(this->toMatch.size()) == '\n' || input.at(this->toMatch.size()) == ':') {
stillGood = true;
}
else {
this->inputRead = 0;
}
}
}
//TODO: make it check the next character
//if(input )
}
|
5302887e195cf66fec1ea2702fc2d1d362221af2
|
238d73e5f7ac2591b0c4d409d5522bf6eea1ec06
|
/code/roomimage.cpp
|
44edac78321c705b3d687442fa5949855073aa17
|
[] |
no_license
|
impulze/msc-robotik-projekt_ws_2014
|
d9fab7e598a291e680b92bc411b3509ce5e976e0
|
3685cbd2d67a37c42c1dd3f1349468af1a2dfc23
|
refs/heads/master
| 2016-09-05T15:10:01.730760
| 2015-01-26T07:01:44
| 2015-01-26T07:01:44
| 27,522,471
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,428
|
cpp
|
roomimage.cpp
|
#include "roomimage.h"
#include <cassert>
#include <map>
#include <set>
namespace
{
bool isBlack(unsigned char const *bytes)
{
return bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 0;
}
bool isGray(unsigned char const *bytes)
{
return bytes[0] == 200 && bytes[1] == 200 && bytes[2] == 200;
}
bool isWhite(unsigned char const *bytes)
{
return bytes[0] == 255 && bytes[1] == 255 && bytes[2] == 255;
}
std::vector<Coord2D> createNeighbours(Coord2D const &coord, unsigned int width, unsigned int height)
{
std::vector<Coord2D> neighbours;
bool addNorth = coord.y > 0;
bool addEast = coord.x < width - 1;
bool addSouth = coord.y < height - 1;
bool addWest = coord.x > 0;
if (addNorth) {
Coord2D north(coord.x, coord.y - 1);
neighbours.push_back(north);
if (addEast) {
Coord2D northEast(coord.x + 1, coord.y - 1);
neighbours.push_back(northEast);
}
if (addWest) {
Coord2D northWest(coord.x - 1, coord.y - 1);
neighbours.push_back(northWest);
}
}
if (addSouth) {
Coord2D south(coord.x, coord.y + 1);
neighbours.push_back(south);
if (addEast) {
Coord2D southEast(coord.x + 1, coord.y + 1);
neighbours.push_back(southEast);
}
if (addWest) {
Coord2D southWest(coord.x - 1, coord.y + 1);
neighbours.push_back(southWest);
}
}
if (addEast) {
Coord2D east(coord.x + 1, coord.y);
neighbours.push_back(east);
}
if (addWest) {
Coord2D west(coord.x - 1, coord.y);
neighbours.push_back(west);
}
return neighbours;
}
std::set<Coord2D> checkNeighbourCollision(Coord2D const &coord, unsigned int width, unsigned int height, unsigned char distance)
{
// check a quad of (distance * 2 + 1)^2
std::set<Coord2D> checks;
long checkX = coord.x;
long checkY = coord.y;
for (unsigned char i = 0; i < distance; i++) {
for (unsigned char j = 0; j < distance; j++) {
checkX = coord.x;
checkY = coord.y;
checkX -= (distance / 2) - j;
checkY -= (distance / 2) - i;
if (checkX < width && checkY < height) {
if (checkX >= 0 && checkY >= 0) {
checks.insert(Coord2D(checkX, checkY));
}
}
}
}
return checks;
}
}
RoomImage::RoomImage(std::string const &filename)
: Image(filename)
{
}
std::vector<Polygon2D> RoomImage::expandPolygon(std::set<Coord2D> &coords) const
{
std::vector<Polygon2D> borderPolygons;
enum DirectionType {
WEST,
SOUTH,
EAST,
NORTH
};
Polygon2D currentPolygon;
// walk east, sets store the coords low -> high
int currentDirection = EAST;
Coord2D coord = *coords.begin();
currentPolygon.push_back(coord);
while (!coords.empty()) {
bool hasWestNeighbours = coord.x > 0;
bool hasSouthNeighbours = coord.y < height() - 1;
bool hasEastNeighbours = coord.x < width() - 1;
bool hasNorthNeighbours = coord.y > 0;
std::set<Coord2D>::const_iterator insideNeighbours[4];
if (hasWestNeighbours) {
insideNeighbours[0] = coords.find(Coord2D(coord.x - 1, coord.y));
}
if (hasSouthNeighbours) {
insideNeighbours[1] = coords.find(Coord2D(coord.x, coord.y + 1));
}
if (hasEastNeighbours) {
insideNeighbours[2] = coords.find(Coord2D(coord.x + 1, coord.y));
}
if (hasNorthNeighbours) {
insideNeighbours[3] = coords.find(Coord2D(coord.x, coord.y - 1));
}
std::set<Coord2D>::const_iterator newCoord = coords.end();
bool switchedDirection = false;
// now do the work
switch (currentDirection) {
case WEST: {
if (insideNeighbours[WEST] != coords.end()) {
newCoord = insideNeighbours[WEST];
break;
}
int possibleDirections[2] = { NORTH, SOUTH };
for (int i = 0; i < 2; i++) {
int direction = possibleDirections[i];
if (insideNeighbours[direction] != coords.end()) {
newCoord = insideNeighbours[direction];
switchedDirection = true;
currentDirection = direction;
break;
}
}
break;
}
case SOUTH: {
if (insideNeighbours[SOUTH] != coords.end()) {
newCoord = insideNeighbours[SOUTH];
break;
}
int possibleDirections[2] = { WEST, EAST };
for (int i = 0; i < 2; i++) {
int direction = possibleDirections[i];
if (insideNeighbours[direction] != coords.end()) {
newCoord = insideNeighbours[direction];
switchedDirection = true;
currentDirection = direction;
break;
}
}
break;
}
case EAST: {
if (insideNeighbours[EAST] != coords.end()) {
newCoord = insideNeighbours[EAST];
break;
}
int possibleDirections[2] = { SOUTH, NORTH };
for (int i = 0; i < 2; i++) {
int direction = possibleDirections[i];
if (insideNeighbours[direction] != coords.end()) {
newCoord = insideNeighbours[direction];
switchedDirection = true;
currentDirection = direction;
break;
}
}
break;
}
case NORTH: {
if (insideNeighbours[NORTH] != coords.end()) {
newCoord = insideNeighbours[NORTH];
break;
}
int possibleDirections[2] = { WEST, EAST };
for (int i = 0; i < 2; i++) {
int direction = possibleDirections[i];
if (insideNeighbours[direction] != coords.end()) {
newCoord = insideNeighbours[direction];
switchedDirection = true;
currentDirection = direction;
break;
}
}
break;
}
}
coords.erase(coord);
if (switchedDirection) {
currentPolygon.push_back(coord);
}
if (newCoord == coords.end()) {
// support lines
if (currentPolygon.size() == 1) {
currentPolygon.push_back(coord);
}
borderPolygons.push_back(currentPolygon);
currentPolygon = Polygon2D();
if (coords.empty()) {
break;
}
coord = *coords.begin();
} else {
coord = *newCoord;
}
}
return borderPolygons;
}
void RoomImage::getBorderPolygons(unsigned char distance, std::vector<Polygon2D> &borderPolygons,
std::vector<Polygon2D> &doorPolygons) const
{
enum CoordType {
OUTSIDE,
WALL_OR_OBJECT_OUTLINE,
DOOR,
INSIDE,
COLLISION
};
typedef std::map<Coord2D, int> CoordTypesMap;
CoordTypesMap coordTypes;
unsigned char stride = type() == IMAGE_TYPE_RGB ? 3 : 4;
// stamp all coordinates with the appropriate type
for (unsigned int y = 0; y < height(); y++) {
for (unsigned int x = 0; x < width(); x++) {
Coord2D coord(x, y);
unsigned char const *bytes = data().data() + (y * width() + x) * stride;
if (isWhite(bytes)) {
coordTypes[coord] = OUTSIDE;
} else if (isBlack(bytes)) {
coordTypes[coord] = WALL_OR_OBJECT_OUTLINE;
} else if (isGray(bytes)) {
coordTypes[coord] = DOOR;
} else {
coordTypes[coord] = INSIDE;
}
}
}
// mark points as collision which can't be passed by the moving object
CoordTypesMap copyCoordTypes = coordTypes;
for (CoordTypesMap::const_iterator it = copyCoordTypes.begin(); it != copyCoordTypes.end(); it++) {
if (it->second != INSIDE && it->second != DOOR) {
coordTypes[it->first] = it->second;
continue;
}
Coord2D coord(it->first.x, it->first.y);
std::set<Coord2D> checks = checkNeighbourCollision(coord, width(), height(), distance);
for (std::set<Coord2D>::const_iterator cit = checks.begin(); cit != checks.end(); cit++) {
unsigned char const *bytes = data().data() + (cit->y * width() + cit->x) * stride;
if (isBlack(bytes)) {
coordTypes[coord] = COLLISION;
}
}
}
std::set<Coord2D> insideCoords;
std::set<Coord2D> doorCoords;
// first find all coordinates inside the room
for (CoordTypesMap::const_iterator it = coordTypes.begin(); it != coordTypes.end(); it++) {
bool insideCoord = it->second == INSIDE;
bool doorCoord = it->second == DOOR;
if (!insideCoord && !doorCoord) {
continue;
}
std::vector<Coord2D> neighbours = createNeighbours(it->first, width(), height());
// expand neighbours
for (std::vector<Coord2D>::const_iterator nit = neighbours.begin(); nit != neighbours.end(); nit++) {
// find the type of the neighbour coordinate
CoordTypesMap::const_iterator foundCoordType = coordTypes.find(*nit);
assert(foundCoordType != coordTypes.end());
if (doorCoord && foundCoordType->second != DOOR) {
doorCoords.insert(it->first);
}
if (foundCoordType->second != INSIDE && foundCoordType->second != DOOR) {
insideCoords.insert(it->first);
break;
}
}
}
borderPolygons = expandPolygon(insideCoords);
doorPolygons = expandPolygon(doorCoords);
}
|
d012727c674833757211f326980f1456968049c5
|
cea2b949a204f95c74b8769dfbb03054a13c28de
|
/src/bencode/bEncodeManager.cpp
|
b4b25294f131ea96cd9f82daf7c156d0e6f0ae0a
|
[
"MIT"
] |
permissive
|
sebestindragos/uTorrent-Backup
|
f51be9f6e451909fa63fef1a2f27876fa0a4d3f7
|
ffde87303d343f76d3981d7f538a086d1b851eb0
|
refs/heads/master
| 2020-08-03T00:08:05.354825
| 2016-11-12T16:21:27
| 2016-11-12T16:21:38
| 73,555,422
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,354
|
cpp
|
bEncodeManager.cpp
|
#include "stdafx.h"
#include "bEncodeManager.h"
#include "common/util/StringUtil.h"
#define BENCODE_END_MARKER L'e'
#define BENCODE_LENGTH_SEPARATOR L':'
#define BENCODE_DICTIONARY_MARKER L'd'
#define BENCODE_LIST_MARKER L'l'
#define BENCODE_INTEGER_MARKER L'i'
bEncodeManager::bEncodeManager()
: mRootItem(nullptr), mIteratorItem(nullptr)
{
}
bEncodeManager::~bEncodeManager()
{
PurgeItems();
}
void bEncodeManager::PurgeItems()
{
if (mRootItem)
delete mRootItem;
mRootItem = nullptr;
}
bool bEncodeManager::Decode(const wstring & aEncodedData)
{
bEncodeItem * crtItem = new bEncodeItem;
bEncodeItem * parentItem = crtItem;
int depth = 0;
size_t i = 0;
for (; i < aEncodedData.length() && parentItem; i++)
{
if ( crtItem && (crtItem->GetType() != bEncodeItem::Unset))
crtItem = new bEncodeItem;
// store the root item
if (i == 0)
mRootItem = crtItem;
switch(aEncodedData[i])
{
case L'd':
crtItem->SetType(bEncodeItem::Dictionary);
depth = 1;
break;
case L'l':
crtItem->SetType(bEncodeItem::List);
depth = 1;
break;
case L'e':
depth = -1;
break;
default:
{
depth = 0;
// decode segment
wstring label;
if (!DecodeSegment(wstring(&aEncodedData[i], aEncodedData.length() - i), label))
return false;
crtItem->SetLabel(label);
// update position in buffer
auto UpdatePosition = [&](const wstring & aSegment) -> bool
{
int offset = aEncodedData[i] == L'i' ? 1 : 0;
std::size_t pos;
pos = aEncodedData.find(aSegment, i + 1);
if (pos == wstring::npos)
return false;
i = pos + aSegment.length() + offset;
return true;
};
if (!UpdatePosition(label))
return false;
// get item type
auto GetNextItemType = [&aEncodedData, &i]() -> bEncodeItem::ItemType
{
return aEncodedData[i] == L'i' ? bEncodeItem::Integer : bEncodeItem::Binary;;
};
bEncodeItem::ItemType type = GetNextItemType();
// this is needed for the "0:" case because value has no length
if (type == bEncodeItem::Binary && label.length() == 0)
i++;
// check if the next item is a list or a dictionary, case in which
// we must leave the type unset and break.
if (aEncodedData[i] == L'd' || aEncodedData[i] == L'l')
{
i--;
break;
}
crtItem->SetType(type);
// check if the item is inside a list
if (parentItem->GetType() == bEncodeItem::List)
{
i--;
break;
}
//decode segment
wstring value;
if (!DecodeSegment(wstring(&aEncodedData[i], aEncodedData.length() - i), value))
return false;
crtItem->SetValue(value);
// update position in buffer
if (!UpdatePosition(value))
return false;
type = GetNextItemType();
crtItem->SetType(type);
// this is needed for the "0:" case because value has no length
if (type == bEncodeItem::Binary && value.length() == 0)
i++;
i--;
}
}
if ( (crtItem->GetType() != bEncodeItem::Unset) &&
crtItem != mRootItem)
parentItem->AddChild(crtItem);
if (depth == 1)
parentItem = crtItem;
else if (depth == -1)
parentItem = parentItem->GetParent();
}
if (i != aEncodedData.length() || parentItem != nullptr)
return false;
mIteratorItem = mRootItem;
return true;
}
bEncodeItem * bEncodeManager::GetRootItem()
{
return mRootItem;
}
bool bEncodeManager::DecodeSegment(const wstring & aRawSegment, wstring & aSegment)
{
if ( (aRawSegment[0] < 48 || aRawSegment[0] > 57) && aRawSegment[0] != L'i')
return false;
if (aRawSegment[0] == L'i')
{
size_t endMarkerPos = aRawSegment.find(BENCODE_END_MARKER);
if (endMarkerPos == wstring::npos)
return false;
aSegment = aRawSegment.substr(1, endMarkerPos - 1);
if (aSegment.length() != endMarkerPos - 1)
return false;
} else
{
int segmentLength = _ttoi(aRawSegment.c_str());
if (segmentLength < 0)
return false;
size_t separatorPos = aRawSegment.find(BENCODE_LENGTH_SEPARATOR);
aSegment.resize(segmentLength);
for (int i = 0; i < segmentLength; i++)
aSegment[i] = aRawSegment[separatorPos + 1 + i];
//aSegment = aRawSegment.substr(separatorPos + 1, segmentLength);
if ((int)aSegment.length() != segmentLength)
return false;
}
return true;
}
bool bEncodeManager::Decode2(const wstring & aEncodedData)
{
// cleanup old items
PurgeItems();
/**
* A bEncoded file must always have a root element which will be a dictionary.
*/
bEncodeItem * parentItem (new bEncodeItem);
parentItem->SetType(bEncodeItem::Dictionary);
mRootItem = parentItem;
// perform safety checks
if (aEncodedData[0] != BENCODE_DICTIONARY_MARKER)
return false;
if (aEncodedData.length() < 2)
return false;
// place root item type on stack
stack<bEncodeItem::ItemType> itemTypeStack;
bEncodeItem::ItemType itemType = bEncodeItem::Dictionary;
itemTypeStack.push(itemType);
// begin parsing the buffer
bEncodeItem * crtItem(new bEncodeItem);
size_t bufferIndex = 1;
const wchar_t * encodedBuffer = &aEncodedData[0];
bool expectRValue = false;
for (; bufferIndex < aEncodedData.length() && !itemTypeStack.empty(); bufferIndex++)
{
if (crtItem->GetType() != bEncodeItem::Unset && !expectRValue)
{
crtItem = new bEncodeItem;
}
auto GoToMarker = [&](wchar_t aMarker, bool aPostIncrement)
{
while (encodedBuffer[bufferIndex] != aMarker)
bufferIndex++;
if (aPostIncrement)
bufferIndex++;
};
int depth = 0;
switch (encodedBuffer[bufferIndex])
{
case BENCODE_DICTIONARY_MARKER:
itemType = bEncodeItem::Dictionary;
crtItem->SetType(itemType);
itemTypeStack.push(itemType);
expectRValue = false;
depth = 1;
break;
case BENCODE_LIST_MARKER:
itemType = bEncodeItem::List;
crtItem->SetType(itemType);
itemTypeStack.push(itemType);
expectRValue = false;
depth = 1;
break;
case BENCODE_INTEGER_MARKER:
{
crtItem->SetType(bEncodeItem::Integer);
int integerLength = 0;
while (encodedBuffer[bufferIndex + integerLength] != BENCODE_END_MARKER)
{
integerLength++;
}
wstring intSegment(encodedBuffer + bufferIndex + 1, integerLength - 1);
if (!expectRValue)
{
crtItem->SetLabel(std::move(intSegment));
}
else
{
crtItem->SetValue(std::move(intSegment));
expectRValue = false;
}
GoToMarker(BENCODE_END_MARKER, false);
}
break;
case BENCODE_END_MARKER:
itemType = itemTypeStack.top();
itemTypeStack.pop();
expectRValue = false;
depth = -1;
break;
default:
{
int segmentLength = _ttoi(encodedBuffer + bufferIndex);
GoToMarker(BENCODE_LENGTH_SEPARATOR, true);
wstring segment = wstring(encodedBuffer + bufferIndex, segmentLength);
bufferIndex += segmentLength - 1;
if (!expectRValue)
crtItem->SetLabel(std::move(segment));
else
crtItem->SetValue(std::move(segment));
crtItem->SetType(bEncodeItem::Binary);
if ( expectRValue == false &&
(itemTypeStack.top() != bEncodeItem::List) )
{
expectRValue = true;
}
else
expectRValue = false;
}
}
if (crtItem->GetType() != bEncodeItem::Unset && !expectRValue)
parentItem->AddChild(crtItem);
if (depth == 1)
parentItem = crtItem;
else if (depth == -1)
{
parentItem = parentItem->GetParent();
}
}
if (crtItem && crtItem->GetType() == bEncodeItem::Unset)
delete crtItem;
if ( bufferIndex != aEncodedData.length() ||
itemTypeStack.size() != 0 )
{
PurgeItems();
return false;
}
return true;
}
bool bEncodeManager::Encode(wstring & aEncodedResultData)
{
aEncodedResultData.clear();
aEncodedResultData = DoEncode(mRootItem);
return true;
}
wstring bEncodeManager::DoEncode(bEncodeItem * aItem)
{
wstring encodedItem;
if (!aItem)
return encodedItem;
auto AppendMarker = [&](wchar_t aMarker) -> void
{
wchar_t markerStr[2] = {aMarker, 0};
encodedItem.append(markerStr);
};
auto WithLength = [&aItem](wstring aString) -> wstring
{
if (aString.size() == 0)
if (aItem->GetType() == bEncodeItem::Binary)
return L"0:";
else
return wstring();
wstring strWithLength(StringUtil::IntToString(aString.size()));
wchar_t markerStr[2] = {BENCODE_LENGTH_SEPARATOR, 0};
strWithLength.append(markerStr);
strWithLength.append(aString);
return strWithLength;
};
bool needEndMarker = false;
switch (aItem->GetType())
{
case bEncodeItem::Dictionary:
encodedItem.append(WithLength(aItem->GetLabel()));
AppendMarker(BENCODE_DICTIONARY_MARKER);
needEndMarker = true;
break;
case bEncodeItem::List:
encodedItem.append(WithLength(aItem->GetLabel()));
AppendMarker(BENCODE_LIST_MARKER);
needEndMarker = true;
break;
case bEncodeItem::Integer:
if (aItem->GetValue() == L"")
{
AppendMarker(BENCODE_INTEGER_MARKER);
encodedItem.append(aItem->GetLabel());
}
else
{
encodedItem.append(WithLength(aItem->GetLabel()));
AppendMarker(BENCODE_INTEGER_MARKER);
encodedItem.append(aItem->GetValue());
}
needEndMarker = true;
break;
case bEncodeItem::Binary:
encodedItem.append(WithLength(aItem->GetLabel()));
encodedItem.append(WithLength(aItem->GetValue()));
break;
}
auto it = aItem->ChildrenBegin();
auto end = aItem->ChildrenEnd();
for (; it != end; ++it)
{
encodedItem.append(DoEncode(*it));
}
if (needEndMarker)
AppendMarker(BENCODE_END_MARKER);
return encodedItem;
}
wstring bEncodeManager::GetItemValue(const wstring & aItemName,
bEncodeItem::ItemType aType)
{
bEncodeItem * item = SearchItem(mRootItem, aItemName, wstring(), aType);
return item != nullptr ? item->GetValue() : wstring();
}
bEncodeItem * bEncodeManager::SearchItem(bEncodeItem * aItem,
const wstring & aLabel,
const wstring & aValue,
bEncodeItem::ItemType aType)
{
bool match = false;
match |= ( (aLabel.size() == 0 || aLabel == aItem->GetLabel()) &&
(aValue.size() == 0 || aValue == aItem->GetValue()) &&
(aType == aItem->GetType()) );
if (match)
return aItem;
auto it = aItem->ChildrenBegin();
auto end = aItem->ChildrenEnd();
for (; it != end; ++it)
{
bEncodeItem * item = SearchItem(*it, aLabel, aValue, aType);
if (item)
return item;
}
return nullptr;
}
bEncodeItem * bEncodeManager::AddChildItem(const wstring & aLabel,
const wstring & aValue,
bEncodeItem::ItemType aType,
bool aCloseItem)
{
if (mRootItem == nullptr)
{
mRootItem = new bEncodeItem;
mRootItem->SetType(bEncodeItem::Dictionary);
mIteratorItem = mRootItem;
}
if (!mIteratorItem)
mIteratorItem = mRootItem;
bEncodeItem * itemPtr = new bEncodeItem;
itemPtr->SetLabel(aLabel);
itemPtr->SetValue(aValue);
itemPtr->SetType(aType);
mIteratorItem->AddChild(itemPtr);
if (!aCloseItem)
mIteratorItem = itemPtr;
return itemPtr;
}
bEncodeItem * bEncodeManager::GetItem(const wstring & aItemName,
bEncodeItem::ItemType aType)
{
return SearchItem(mRootItem, aItemName, wstring(), aType);
}
void bEncodeManager::CloseItem()
{
if (mIteratorItem)
mIteratorItem = mIteratorItem->GetParent();
}
|
045b8882cc0e64f6c6d23e9fd3403d3f16f73f6b
|
bc6b4fddbfc101e5c31cfad9a788ce52e1fa7cb7
|
/Laboratory Work 3: Iterator/main.cpp
|
041888955e40c4d8bed5373d51ae34af8a7e6219
|
[] |
no_license
|
prometneus/Cpp-2020
|
adb5b9fa64c1b3888dfb01b0473042dcb0a85723
|
01036cec831a83462547385372fc99c3864bdf56
|
refs/heads/main
| 2023-06-24T15:19:19.341699
| 2021-07-24T21:19:47
| 2021-07-24T21:19:47
| 387,269,150
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,956
|
cpp
|
main.cpp
|
#include "Deque.h"
#include <ctime> // Чисто ради рандомчика добавил
int main() {
Deque<double> dq;
Deque<char> dva;
Iterator<Deque<char>> check = dva.begin();
cout << "Iterator empty() check with a spurious deque \"dva\" -- " << check.empty() << endl; // Через итераторы
dva.insertfirst('a'); // Добавим символ в фальшивую деку
check = dva.begin(); // Реинициализируем итератор
cout << "Iterator empty() check with a spurious deque \"dva\" with added element -- " << check.empty() << endl;
using iterator = Iterator<Deque<double>>;
cout << "Deque filling: " << endl;
dq.insertlast(3); // Вставка в конец
dq.insertfirst(2); // Вставка в начало
dq.insertfirst(1);
dq.insertlast(4);
dq.insertlast(5);
dq.insertfirst(0);
cout << "Deque: " << endl;
dq.show(); // Вывод на экран с помощью функции
iterator empty = dq.begin();
cout << "Emptiness check (iterator) -- " << empty.empty() << endl; // Через итераторы
cout << "Emptiness check (method) -- " << dq.isempty() << endl; // Через метод
cout << endl << endl << endl << endl;
cout << "Creating and filling another deque (dk) for swapping" << endl;
Deque<double> dk;
cin >> dk; // Заполнение второй деки с помощью перегруженного оператора ввода
cout << "Deque dq before swapping: " << endl << dq << endl; // Вывод на экран с помощью перегруженного оператора вывода
dq.swap(&dk);
cout << "Deque dq after swapping: " << endl;
dq.show();
cout << "Deque dk after swapping: " << endl << dk << endl << endl << endl;
cout << endl << endl << endl << endl;
iterator beginiter = dq.begin(); // После свапа я заново инициализирую итераторы на начало и конец
iterator enditer = dq.end();
cout << "beginiter begin: " << beginiter->data << endl; // Вывод первого элемента контейнера
cout << "Here is the print of deque's filling with postfix ++ operator" << endl;
for (beginiter; beginiter != NULL; beginiter++) { // Вывод всего контейнера итераторами
cout << beginiter->data << " ";
}
cout << endl << "Last element using enditer: " << enditer->data << endl; // Вывод последнего элемента итератором enditer
cout << endl << endl << endl << endl;
cout << "Let's add and delete an element in deque (dk)" << endl;
cout << "Deque before:" << endl;
dk.show();
enditer = dk.end(); // Снова реинициализирую итератор на конец, но уже из-за смены дека
cout << "Inserting random number before the pre-last position (on the pre-pre-last exactly) using prefix -- on enditer iterator " << endl;
srand(time(0)); // Для вставки случайного числа
dk.insert(--enditer, rand()); // Элемент вставится перед итератором, поэтому, если я хочу вставить на пред-предпоследнюю позицию,
cout << "Deque after:" << endl; // Нужно установить итератор на предпоследнюю позицию
dk.show();
cout << "Now erasing newly added element" << endl; // Теперь удаление этого добавленного элемента
cout << "What to erase: " << (--enditer)->data << endl; // Вывод, что именно за элемент будет удалён
dk.erase(enditer); // Само удаление
cout << "Deque after:" << endl;
dk.show(); // Вывод дека, чтобы показать, что всё прошло успешно
cout << endl << endl << endl << endl;
cout << "Now let's erase everything but first and last element in deque dq" << endl; // Оставим первый и последний элементы в деке
beginiter = dq.begin();
enditer = dq.end();
cout << "Deque before:" << endl << dq << endl;
dk.erase(++beginiter, enditer); // Будет почищено от первого элемента до последнего (не включая)
cout << "Deque after:" << endl;
dq.show();
cout << endl << endl;
cout << "Erasing all items except the last one in deque dk" << endl;
cout << "Deque before:" << endl << dk << endl;
dk.erase((dk.begin())++, dk.end()); // Будет удалено всё кроме последнего элемента
cout << "Deque after:" << endl;
dk.show();
return 0;
}
|
00e26163d6e81513538da8975ad6a26a13216cfe
|
ac0041def3b7d513b68fa2db795b416372a5046d
|
/alchemy/src/infer/ss.h
|
16f7cc4d24c720cbcbd310efd690650fef62acce
|
[] |
no_license
|
yaorongge/pl-semantics
|
ffe4457611ee1960dbbbd1072904771ed96066db
|
87112198b0eb5df25f7866ab0cbd1cd28ee2df39
|
refs/heads/master
| 2020-03-22T02:34:59.391763
| 2017-02-10T17:38:15
| 2017-02-10T17:38:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,110
|
h
|
ss.h
|
#ifndef SS_H_
#define SS_H_
#include "MAIN.h"
#include <stdlib.h>
#include <stdio.h>
#include "infer.h"
const int ssdebug = false;
extern char* aresultsFile;
struct SampleSearchParams
{
int maxSeconds;
int iBound;
int rbBound;
int numItr;
};
/**
* Calling SampleSearch
*/
class SampleSearchProxy: public Inference
{
public:
SampleSearchProxy(VariableState* state, long int seed, const bool& trackClauseTrueCnts,
SampleSearchParams* sampleSearchParams,
Array<Array<Predicate* >* >* queryFormulas = NULL, bool withSSQ = false)
: Inference(state, seed, trackClauseTrueCnts, queryFormulas)
{
this->withSSQ_ = withSSQ;
this->params = (*sampleSearchParams);
if(this->params.maxSeconds <=0 )
this->params.maxSeconds = 100;
}
~SampleSearchProxy()
{
}
void init()
{
}
void infer()
{
////////////////////////////////
/*
ofstream outFile;
outFile.open ("mln.uai");
//outFile <<"MARKOV"<<endl;
outFile << state_->getNumAtoms() << endl;
for (int i = 0; i < state_->getNumAtoms(); i++)
{
outFile <<"2 ";
}
outFile << endl;
outFile << state_->getNumClauses() << endl;
for (int i = 0; i < state_->getNumClauses(); i++)
{
GroundClause *gndClause = state_->getGndClause(i);
double weight = gndClause->getWt();
double expNegWeight = exp(-weight);
if(gndClause->isHardClause())
expNegWeight = 0;
outFile <<gndClause->getNumGroundPredicates()<<" " ;
for (int j = 0; j < gndClause->getNumGroundPredicates(); j++)
{
//outFile <<abs(gndClause->getGroundPredicateIndex(j))-1 << " ";
outFile <<gndClause->getGroundPredicateIndex(j)<< " ";
}
outFile <<expNegWeight<<endl;
//cout<<endl;
}
for (int i = 0; i < state_->getNumClauses(); i++)
{
GroundClause *gndClause = state_->getGndClause(i);
unsigned long long int numGndPred = gndClause->getNumGroundPredicates();
assert(numGndPred < 64);
unsigned long long int tableSize = (1LL<<numGndPred) ;
double weight = gndClause->getWt();
double expNegWeight = exp(-weight);
if(gndClause->isHardClause())
expNegWeight = 0;
outFile <<tableSize<<endl;
for (int j = 0; j < tableSize; j++)
{
bool satisfied = false;
unsigned long long int mask = 1;
for (int k = 0; k<numGndPred; k++)
{
bool isTrue = mask&j;
int predIndex = gndClause->getGroundPredicateIndex(numGndPred-1-k);
if( predIndex > 0 && isTrue || predIndex < 0 && !isTrue )
{
satisfied = true;
break;
}
mask = mask << 1;
}
if(satisfied)
outFile << "1 ";
else outFile << expNegWeight <<" ";
}
outFile << endl;
}
outFile.close();
*/
//std::system("cat mln.uai");
//std::ostringstream command;
//command << "./ijgp-samplesearch mln.uai empty.evd " << this->params.maxSeconds <<" PR";
//std::system(command.str().c_str());
std::ostringstream t;
t << this->params.maxSeconds;
std::ostringstream resFile;
resFile << aresultsFile;
if(this->withSSQ_)
resFile << ".num";
else
resFile << ".dnum";
char ** argv = new char*[5];
for(int i = 0;i<5;i++)
argv[i] = new char[200];
strcpy (argv[0],"./ijgp-samplesearch");
strcpy (argv[1],resFile.str().c_str());
strcpy (argv[2],"empty.evd");
strcpy (argv[3],t.str().c_str());
strcpy (argv[4],"PR");
//cout <<argv[0]<<endl;
//cout <<argv[1]<<endl;
//cout <<argv[2]<<endl;
//cout <<argv[3]<<endl;
//cout <<argv[4]<<endl;
cout << "calling SS"<<endl;
ss::MAIN (state_, 5, argv);
//cout << aresultsFile << endl;
//std::system("cat mln.uai.PR");
}
void printNetwork(std::ostream& out)
{}
void printProbabilities(std::ostream& out)
{}
void getChangedPreds(std::vector<std::basic_string<char> >& a , std::vector<float>& b, std::vector<float>& c, const float& d)
{}
void printTruePreds(std::ostream& out)
{}
void printTruePredsH(std::ostream& out)
{}
double getProbabilityH(GroundPredicate* const& p)
{return 0;}
double getProbability(GroundPredicate* const& gndPred)
{return 0;}
private:
SampleSearchParams params;
bool withSSQ_;
};
#endif /*SS_H_*/
|
7aa9c9c18ec7c580a373902d8237621c59eb473b
|
e55b544a1d0dd1709138adde894204d41a156b47
|
/codechef/oct/fenWriter.cpp
|
e22adc95c1b8eb98db27711e04ef85ef1bf0e4f5
|
[
"MIT"
] |
permissive
|
AadityaJ/CP
|
992255aef3237b62a21b7a8a4241a8b4450795fa
|
61664c1925ef5bb072a3fe78fb3dac4fb68d77a1
|
refs/heads/master
| 2021-10-18T02:04:35.459182
| 2019-02-13T16:00:32
| 2019-02-13T16:00:32
| 49,662,989
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,209
|
cpp
|
fenWriter.cpp
|
#include <iostream>
#include <string>
using namespace std;
long long int numones(string str){
long long int num=0;
for(long long int i=0;i<str.length();i++){
if(str[i]=='1') num++;
}
return num;
}
long long int trailones(string str){
long long int num=0;
for(long long int i=str.length()-1;i>=0;i--){
if(str[i]=='1'){num++;}
else return num;
}
return num;
}
long long int actualtrail(string l1,string l2,string l3,int n){
int x_l1=trailones(l1);
int x_l2=trailones(l2);
int x_l3=trailones(l3);
if(x_l3!=l3.length()) return x_l3;
if(x_l2!=l2.length()) return x_l3+x_l2;
return x_l3+(n*x_l2)+x_l1;
}
int main(int argc, char const *argv[]) {
int t;
cin>>t;
while(t--){
string l1,l2,l3;
int n;
cin>>l1>>l2>>l3>>n;
//string num;
//num.append(l1);
//for(int i=0;i<n;i++) num.append(l2);
//num.append(l3);
//long long int count=(numones(num)+1);
long long int count=(numones(l1));
count+=(numones(l3));
count+=(numones(l2)*n);
count++;
count-=actualtrail(l1,l2,l3,n);
cout<<count<<endl;
}
return 0;
}
|
de00fde68a0a0f702a6e805eba21ed342ffd6012
|
720b266677c19fb4de8676b92bd9a52adc67633c
|
/final_DRONE.c.ino
|
6b5a3e6616473a1dd8e1207c5db528d643826cbc
|
[] |
no_license
|
sherryroot/Arudino
|
dde728f25940f60aa45f0a6fc5595c1bbe1dbe34
|
a7165eba010f41ae778ffb7c4035a83cfcb0e180
|
refs/heads/master
| 2020-05-03T14:14:41.411090
| 2019-04-01T05:22:06
| 2019-04-01T05:22:06
| 178,672,045
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,391
|
ino
|
final_DRONE.c.ino
|
#include <MPU6050.h>
#include "Wire.h"
#include "I2Cdev.h"
#include "MPU6050.h"
#include <Servo.h>
MPU6050 accelgyro;
#include <SoftwareSerial.h>
//libraries finish
//
float utrl1_dist;//distance in utrl
float utrl2_dist;
const int utrl1_Echo=3;
const int utrl1_Trig=2;
const int utrl2_Echo=7;
const int utrl2_Trig=6;//utrl set pin
//
int16_t ax,ay,az,gx,gy,gz;//acccel
//
SoftwareSerial BT(10,11);
struct msg{
float utrl1;
float utrl2;
//float accel;
};//发送包结构
//__________________UTRL_____________________________________
//initialize
// utrl initial
void utrl_init(int Echo,int Trig){
pinMode(Trig, OUTPUT);
pinMode(Echo, INPUT);
}
//execution
//utrl test distance
float utrl_dist(int Trig,int Echo){
float temp;
float cm;
//给Trig发送一个低高低的短时间脉冲,触发测距
digitalWrite(Trig, LOW); //给Trig发送一个低电平
delayMicroseconds(2); //等待 2微妙
digitalWrite(Trig,HIGH); //给Trig发送一个高电平
delayMicroseconds(10); //等待 10微妙
digitalWrite(Trig, LOW); //给Trig发送一个低电平
temp = float(pulseIn(Echo, HIGH)); //存储回波等待时间,
//pulseIn函数会等待引脚变为HIGH,开始计算时间,再等待变为LOW并停止计时
//返回脉冲的长度
//声速是:340m/1s 换算成 34000cm / 1000000μs => 34 / 1000
//因为发送到接收,实际是相同距离走了2回,所以要除以2
//距离(厘米) = (回波时间 * (34 / 1000)) / 2
//简化后的计算公式为 (回波时间 * 17)/ 1000
cm = (temp * 17 )/1000; //把回波时间换算成cm
return cm;
}
//____________________Bluetooth______________________________________
//
void BT_init(){ // 如果是HC-05,請改成38400
// Serial.begin(38400);
BT.begin(9600);
Serial.println("baud is 9600 ok");
}
void BT_exe(){
// BT.write();
Serial.write("//receieve msg//");//发送test}
};
//____________________accelerate______________________________________
void mpu_init(){
Wire.begin();
// Serial.begin(9600);
Serial.println("Initializing I2C devices...");
accelgyro.initialize();
// verify connection
Serial.println("Testing device connections...");
Serial.println(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");
}
//____________
int count=0;
int f;
//____________
//********************************************************
void setup(){
Serial.begin(9600);//start serial,set up bode
utrl_init(utrl1_Echo,utrl1_Trig);
utrl_init(utrl2_Echo,utrl2_Trig);
mpu_init();
BT_init();
}
//
void loop(){
//超声波测距
utrl1_dist=utrl_dist(utrl1_Trig,utrl1_Echo);
utrl2_dist=utrl_dist(utrl2_Trig,utrl2_Echo);
accelgyro.getMotion6(&ax,&ay,&az,&gx,&gy,&gz);//get mpu6050 value
// Serial.println(ax);
//
//发送data
// BT_exe();
Serial.println(ax);
char t=ax;
f=count%6;
Serial.println(f);
if(f==0){
BT.write("ultra1:");}
if(f==1){
BT.write(t);}
if(f==2){
BT.write("ultra2:");}
if(f==3){
BT.write(t);}
if(f==4){
BT.write("MPU6050:");}
if(f==5){
BT.write(t);}
count=count+1;
delay(500);
delay(500);
}
|
2d8f88d410a611f9e6e33cd37cbd8136d36d5c31
|
bf573a7cd2b58187d76dd0851e4e96096cd70b55
|
/2016/2.h
|
b878543be1aae5c8285303acd57794963686e048
|
[] |
no_license
|
nafur/adventofcode
|
a025b722470fb1e663ba6cb6846aa09f48f4f25a
|
273292e15c25d6c45b04f5264e25aecc4053b9ab
|
refs/heads/master
| 2021-10-09T12:06:08.029141
| 2018-12-27T17:28:25
| 2018-12-27T17:28:25
| 112,719,547
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,718
|
h
|
2.h
|
#pragma once
#include "../utils/parser.h"
#include <algorithm>
#include <string>
template<>
struct solve<2> {
static auto solution() {
return std::make_pair("74921"s, "A6B35"s);
}
const std::string input = "2016/2.input";
struct Keypad1 {
int current = 5;
void move(char c) {
switch (c) {
case 'U': up(); break;
case 'R': right(); break;
case 'D': down(); break;
case 'L': left(); break;
}
}
void up() {
if (current < 4) return;
current -= 3;
}
void right() {
if (current % 3 == 0) return;
current += 1;
}
void down() {
if (current > 6) return;
current += 3;
}
void left() {
if (current % 3 == 1) return;
current -= 1;
}
char pos() const {
return '0' + current;
}
};
struct Keypad2 {
char current = '5';
void move(char c) {
switch (c) {
case 'U': up(); break;
case 'R': right(); break;
case 'D': down(); break;
case 'L': left(); break;
}
}
void up() {
switch (current) {
case '3': current = '1'; break;
case '6': current = '2'; break;
case '7': current = '3'; break;
case '8': current = '4'; break;
case 'A': current = '6'; break;
case 'B': current = '7'; break;
case 'C': current = '8'; break;
case 'D': current = 'B'; break;
}
}
void right() {
switch (current) {
case '2': current = '3'; break;
case '3': current = '4'; break;
case '5': current = '6'; break;
case '6': current = '7'; break;
case '7': current = '8'; break;
case '8': current = '9'; break;
case 'A': current = 'B'; break;
case 'B': current = 'C'; break;
}
}
void down() {
switch (current) {
case '1': current = '3'; break;
case '2': current = '6'; break;
case '3': current = '7'; break;
case '4': current = '8'; break;
case '6': current = 'A'; break;
case '7': current = 'B'; break;
case '8': current = 'C'; break;
case 'B': current = 'D'; break;
}
}
void left() {
switch (current) {
case '3': current = '2'; break;
case '4': current = '3'; break;
case '6': current = '5'; break;
case '7': current = '6'; break;
case '8': current = '7'; break;
case '9': current = '8'; break;
case 'B': current = 'A'; break;
case 'C': current = 'B'; break;
}
}
char pos() const {
return current;
}
};
template<typename Keypad, typename T>
auto simulate(const T& lines) const {
Keypad k;
std::string code;
for (const auto& l: lines) {
for (auto c: l) k.move(c);
code = code + k.pos();
}
return code;
}
auto operator()() const {
auto lines = read_file_linewise(input);
return std::make_pair(simulate<Keypad1>(lines), simulate<Keypad2>(lines));
}
};
|
95e8beb99b758048b34113633cfe2adc17f234a0
|
2c45bf84d1cd00dcb50e0bc79447ad366a207074
|
/Pincer Valley/source/event_receiver.h
|
d9fb4754e7fa854109dc29d6036254a7315e2c98
|
[] |
no_license
|
UserProgrammer/PincerValley
|
ebbb09c325be443ec7acea5c2b60d21b1e01e1d9
|
3bfcceceaa3c25eba75fb3596d63554ced1709d2
|
refs/heads/master
| 2021-01-12T17:23:16.009047
| 2016-10-21T11:03:01
| 2016-10-21T11:03:01
| 71,556,502
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,324
|
h
|
event_receiver.h
|
#ifndef INCLUDE_EVENT_CLASS
#define INCLUDE_EVENT_CLASS
#include <iostream>
#include <irrlicht.h>
#include "dummy.h"
using namespace std;
using namespace irr;
enum Mouse_Button{M_LEFT=KEY_LBUTTON, M_RIGHT=KEY_RBUTTON};
struct SAppContext
{
irr::IrrlichtDevice *device;
};
class EventReceiver:public irr::IEventReceiver
{
public:
EventReceiver(SAppContext &context);
~EventReceiver();
virtual bool OnEvent(const irr::SEvent &event);
/// Return the state of a specified keyboard key.
virtual bool IsKeyDown(EKEY_CODE keyCode);
/// Return the action of a specified keyboard key.
int IsKeyPressed(EKEY_CODE keyCode);
/// Reset variable that holds keyboard key actions (must be called at the end of the event loop in main.cpp)
void resetKeyPressed();
/// Return the state of the left mouse button.
bool IsMouseButtonDown(Mouse_Button button);
/// Return the state of the right mouse button.
int IsMouseButtonPressed(Mouse_Button button);
void resetMousePressed();
bool isCursorMoving();
void resetCursorMove();
private:
SAppContext &Context;
bool isKeyDown[KEY_KEY_CODES_COUNT];
int isKeyPressed[KEY_KEY_CODES_COUNT];
bool cursorMoving;
bool isLMouseDown, isRMouseDown;
int isLMousePressed, isRMousePressed;
};
#endif
|
ad222ea332ae476c50213abeae64baa9f16b76ec
|
d41a11526e14bcfef8a85d1d2c19e6134e733756
|
/cpp2/630-Knight-Shortest-Path-II.cpp
|
cecbbc753acbe198945f3a02b62e3267cb00221b
|
[] |
no_license
|
ezhou2008/algorithm-basic
|
7719abb9b984d8624f057de30d42b22ced45c3a3
|
6e47f9246013e1b1668f70f6e921a81c68b1f7d6
|
refs/heads/master
| 2021-01-22T18:34:23.359864
| 2017-03-15T16:53:40
| 2017-03-15T16:53:40
| 85,096,380
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,870
|
cpp
|
630-Knight-Shortest-Path-II.cpp
|
/*Knight Shortest Path II
Description
Given a knight in a chessboard n * m (a binary matrix with 0 as empty
and 1 as barrier). the knight initialze position is (0, 0) and he wants
to reach position (n - 1, m - 1), Knight can only be from left to right.
Find the shortest path to the destination position, return the length of
the route. Return -1 if knight can not reached.
Have you met this question in a real interview? Yes
Clarification
If the knight is at (x, y), he can get to the following positions in one
step:
(x + 1, y + 2)
(x - 1, y + 2)
(x + 2, y + 1)
(x - 2, y + 1)
Example
[[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
Return 3
[[0,0,0,0],
[0,0,0,0],
[0,1,0,0]]
Return -1
Tags
Dynamic Programming Amazon Breadth First Search
Related Problems
Medium Knight Shortest Path*/
class Solution_推荐 {
public:
struct Point {
int x, y;
Point() : x(0), y(0) {}
Point(int a, int b) : x(a), y(b) {}
};
/**
* @param grid a chessboard included 0 and 1
* @return the shortest path
*/
int shortestPath2(vector<vector<bool>>& grid) {
int n_row = grid.size();
int n_col = grid[0].size();
Point source(0,0);
Point destination(n_row-1,n_col-1);
return shortestPath(grid,source, destination);
}
int shortestPath(vector<vector<bool>>& grid, Point& source, Point& destination) {
// 标准的bfs
int n_row = grid.size();
int n_col = grid[0].size();
queue<Point> p_q;
p_q.push(source);
grid[source.x][source.y] = 1; //mark as visited
int r_len = -1;
while(!p_q.empty()) {
int q_size = p_q.size();
r_len++;
for (int i = 0; i<q_size; i++) {
Point cur_p = p_q.front();
p_q.pop();
if (cur_p.x == destination.x && cur_p.y == destination.y) {
return r_len;
}
vector<Point> neigbours = get_neigbours(cur_p, grid);
for (auto adj : neigbours) {
if (grid[adj.x][adj.y] == 0) {
p_q.push(adj);
grid[adj.x][adj.y] = 1; // makred as visited
}
}
}
}
return -1;
}
vector<Point> get_neigbours(Point& source, vector<vector<bool>>& grid) {
vector<Point> result;
int n_row = grid.size();
int n_col = grid[0].size();
vector<int> delta_x {1, -1, 2, -2};
vector<int> delta_y {2, 2, 1, 1};
for (int i = 0; i<delta_x.size(); i++) {
if ((source.x+delta_x[i] >=0 && source.x+delta_x[i] < n_row) &&
(source.y+delta_y[i] >= 0 && source.y+delta_y[i] < n_col) ) {
result.push_back(Point(source.x+delta_x[i], source.y+delta_y[i]));
}
}
return result;
}
};
class Solution {
public:
struct Point {
int x, y;
Point() : x(0), y(0) {}
Point(int a, int b) : x(a), y(b) {}
};
/**
* @param grid a chessboard included 0 and 1
* @return the shortest path
*
* dp搜索
*/
int shortestPath2(vector<vector<bool>>& grid) {
int n_row = grid.size();
int n_col = grid[0].size();
if (grid[0][0]==1 && grid[n_row-1][n_col-1]==1) {
return -1;
}
vector<vector<int>> dp_len(n_row,vector<int>(n_col,INT_MAX));
queue<Point> p_q;
p_q.push(Point(0,0));
dp_len[0][0] = 0;
while(!p_q.empty()) {
Point cur_p = p_q.front();
p_q.pop();
vector<Point> neigbours = get_neigbours(cur_p, grid);
for (auto adj : neigbours) {
// len长的路径必须排除,否则加入queue处理会超时
if (grid[adj.x][adj.y] == 0 &&
dp_len[cur_p.x][cur_p.y]+1 < dp_len[adj.x][adj.y]) {
p_q.push(adj);
dp_len[adj.x][adj.y] = dp_len[cur_p.x][cur_p.y]+1;
}
}
}
if (dp_len[n_row-1][n_col-1] == INT_MAX) {
return -1;
} else {
return dp_len[n_row-1][n_col-1];
}
}
vector<Point> get_neigbours(Point& source, vector<vector<bool>>& grid) {
vector<Point> result;
int n_row = grid.size();
int n_col = grid[0].size();
vector<int> delta_x {1, -1, 2, -2};
vector<int> delta_y {2, 2, 1, 1};
for (int i = 0; i<delta_x.size(); i++) {
if ((source.x+delta_x[i] >=0 && source.x+delta_x[i] < n_row) &&
(source.y+delta_y[i] >= 0 && source.y+delta_y[i] < n_col) ) {
result.push_back(Point(source.x+delta_x[i], source.y+delta_y[i]));
}
}
return result;
}
};
|
15be72398ef74c60c57a08e118a64b2620f4a2a3
|
4889e30d514ba1d9071140511df30f7989a94e71
|
/GuerraDeCartasV1/GuerraDeCartasV1/Nodo.h
|
26c97fb66db9cb2e40e443a6374536d7689f8f7f
|
[] |
no_license
|
DennisLy1995/GuerraCartas
|
ecec623ba43594af99b6c8de691a9301395cf3e7
|
32e37535ab7b931546e8414137455a62ee638b38
|
refs/heads/master
| 2020-05-07T00:53:36.290353
| 2019-04-29T23:54:01
| 2019-04-29T23:54:01
| 180,248,392
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 241
|
h
|
Nodo.h
|
#pragma once
#ifndef NODO_H
#define NODO_H
#include "Carta.h"
class Nodo
{
private:
Carta carta;
Nodo * sig;
public:
Nodo();
Nodo(Carta);
void setCarta(Carta);
Carta getCarta(void);
void setSig(Nodo*);
Nodo * getSig(void);
};
#endif
|
cfde80e957fc89a64d0431a4dbc8fd82b6cdd99c
|
78b0701b311cd2ee4cb6364ee9c077d8d7543ab8
|
/ogsNumerics/SolutionLib/Fem/FemIC.h
|
0a372e929b52d48b2c9469fcdef858fb7c424ec4
|
[
"BSD-2-Clause"
] |
permissive
|
Yonghui56/ComponentialMultiphase
|
9fc04527561ce101b1bd2118b9badf8e13014d3f
|
47c019ac50e1a182eb7d3912776795f71ac2963a
|
refs/heads/master
| 2021-01-17T07:04:51.515688
| 2016-05-20T15:16:55
| 2016-05-20T15:16:55
| 42,857,468
| 0
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,349
|
h
|
FemIC.h
|
/**
* Copyright (c) 2012, OpenGeoSys Community (http://www.opengeosys.com)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.com/LICENSE.txt
*
*
* \file FemIC.h
*
* Created on 2012-09-22 by Norihiro Watanabe
*/
#pragma once
#include <vector>
#include "BaseLib/CodingTools.h"
#include "GeoLib/GeoObject.h"
#include "MeshLib/Core/IMesh.h"
#include "NumLib/Function/ITXFunction.h"
#include "NumLib/Function/ITXDiscreteFunction.h"
namespace SolutionLib
{
/**
* \brief IC data for FEM
*
* - mesh
* - geometry
* - distribution
*/
class FemIC
{
public:
/**
*
* @param msh
*/
FemIC(const MeshLib::IMesh* msh)
: _msh(msh)
{
}
///
virtual ~FemIC()
{
BaseLib::releaseObjectsInStdVector( _vec_func );
}
/// add a distribution
void addDistribution(const GeoLib::GeoObject* geo, const NumLib::ITXFunction* ic_func);
/// return the number of registered distributions
size_t getNumberOfDistributions() const {return _vec_geo.size();};
/// setup
void setup(NumLib::ITXDiscreteFunction<double> &u0) const;
private:
const MeshLib::IMesh* _msh;
std::vector<const GeoLib::GeoObject*> _vec_geo;
std::vector<const NumLib::ITXFunction*> _vec_func;
};
}
|
16418256bbe15a797d62439a7c2ce4782d592f58
|
53ec60e7fbb72c011f00decd8227b080ecd80bd5
|
/src/el3d_module/3rd_party/carve/lib/csg_collector.cpp
|
af5efb2b101e92c1f6aca632b3f287a72fa200a2
|
[] |
no_license
|
mi6gan/elasticas-cad
|
fc45f91941d2725c3c4627c2bf5d7dbee6a8f22a
|
be0f17edd131d70c72f6ff3a7c3f848af8a45934
|
refs/heads/master
| 2020-03-24T21:48:01.911634
| 2019-08-09T16:38:18
| 2019-08-09T16:38:18
| 143,051,035
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,273
|
cpp
|
csg_collector.cpp
|
// Begin License:
// Copyright (C) 2006-2008 Tobias Sargeant (tobias.sargeant@gmail.com).
// All rights reserved.
//
// This file is part of the Carve CSG Library (http://carve-csg.com/)
//
// This file may be used under the terms of the GNU General Public
// License version 2.0 as published by the Free Software Foundation
// and appearing in the file LICENSE.GPL2 included in the packaging of
// this file.
//
// This file is provided "AS IS" with NO WARRANTY OF ANY KIND,
// INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE.
// End:
#if defined(HAVE_CONFIG_H)
# include <carve_config.h>
#endif
#include <carve/csg.hpp>
#include <iostream>
#include "intersect_debug.hpp"
typedef carve::poly::Polyhedron poly_t;
#if defined(CARVE_DEBUG_WRITE_PLY_DATA)
void writePLY(std::string &out_file, const carve::poly::Polyhedron *poly, bool ascii);
#endif
namespace carve {
namespace csg {
namespace {
class BaseCollector : public CSG::Collector {
BaseCollector();
BaseCollector(const BaseCollector &);
BaseCollector &operator=(const BaseCollector &);
protected:
struct face_data_t {
poly_t::face_t *face;
const poly_t::face_t *orig_face;
bool flipped;
face_data_t(poly_t::face_t *_face,
const poly_t::face_t *_orig_face,
bool _flipped) : face(_face), orig_face(_orig_face), flipped(_flipped) {
};
};
std::list<face_data_t> faces;
const poly_t *src_a;
const poly_t *src_b;
BaseCollector(const poly_t *_src_a,
const poly_t *_src_b) : CSG::Collector(), src_a(_src_a), src_b(_src_b) {
}
virtual ~BaseCollector() {
}
void FWD(const poly_t::face_t *orig_face,
const std::vector<const poly_t::vertex_t *> &vertices,
carve::geom3d::Vector normal,
bool poly_a,
FaceClass face_class,
CSG::Hooks &hooks) {
std::vector<poly_t::face_t *> new_faces;
new_faces.reserve(1);
new_faces.push_back(orig_face->create(vertices, false));
hooks.processOutputFace(new_faces, orig_face, false);
for (size_t i = 0; i < new_faces.size(); ++i) {
faces.push_back(face_data_t(new_faces[i], orig_face, false));
}
#if defined(CARVE_DEBUG) && defined(DEBUG_PRINT_RESULT_FACES)
std::cerr << "+" << ENUM(face_class) << " ";
for (unsigned i = 0; i < vertices.size(); ++i) std::cerr << " " << vertices[i] << ":" << *vertices[i];
std::cerr << std::endl;
#endif
}
void REV(const poly_t::face_t *orig_face,
const std::vector<const poly_t::vertex_t *> &vertices,
carve::geom3d::Vector normal,
bool poly_a,
FaceClass face_class,
CSG::Hooks &hooks) {
normal = -normal;
std::vector<poly_t::face_t *> new_faces;
new_faces.reserve(1);
new_faces.push_back(orig_face->create(vertices, true));
hooks.processOutputFace(new_faces, orig_face, true);
for (size_t i = 0; i < new_faces.size(); ++i) {
faces.push_back(face_data_t(new_faces[i], orig_face, true));
}
#if defined(CARVE_DEBUG) && defined(DEBUG_PRINT_RESULT_FACES)
std::cerr << "-" << ENUM(face_class) << " ";
for (unsigned i = 0; i < vertices.size(); ++i) std::cerr << " " << vertices[i] << ":" << *vertices[i];
std::cerr << std::endl;
#endif
}
virtual void collect(const poly_t::face_t *orig_face,
const std::vector<const poly_t::vertex_t *> &vertices,
carve::geom3d::Vector normal,
bool poly_a,
FaceClass face_class,
CSG::Hooks &hooks) =0;
virtual void collect(FaceLoopGroup *grp, CSG::Hooks &hooks) {
std::list<ClassificationInfo> &cinfo = (grp->classification);
if (cinfo.size() == 0) {
std::cerr << "WARNING! group " << grp << " has no classification info!" << std::endl;
return;
}
FaceClass fc = FACE_UNCLASSIFIED;
unsigned fc_bits = 0;
for (std::list<ClassificationInfo>::const_iterator i = grp->classification.begin(), e = grp->classification.end(); i != e; ++i) {
if ((*i).intersected_manifold < 0) {
// classifier only returns global info
fc_bits = class_to_class_bit((*i).classification);
break;
}
if ((*i).intersectedManifoldIsClosed()) {
if ((*i).classification == FACE_UNCLASSIFIED) continue;
fc_bits |= class_to_class_bit((*i).classification);
}
}
fc = class_bit_to_class(fc_bits);
// handle the complex cases where a group is classified differently with respect to two or more closed manifolds.
if (fc == FACE_UNCLASSIFIED) {
unsigned inout_bits = fc_bits & FACE_NOT_ON_BIT;
unsigned on_bits = fc_bits & FACE_ON_BIT;
// both in and out. indicates an invalid manifold embedding.
if (inout_bits == (FACE_IN_BIT | FACE_OUT_BIT)) goto out;
// on, both orientations. could be caused by two manifolds touching at a face.
if (on_bits == (FACE_ON_ORIENT_IN_BIT | FACE_ON_ORIENT_OUT_BIT)) goto out;
// in or out, but also on (with orientation). the on classification takes precedence.
fc = class_bit_to_class(on_bits);
}
out:
if (fc == FACE_UNCLASSIFIED) {
std::cerr << "group " << grp << " is unclassified!" << std::endl;
#if defined(CARVE_DEBUG_WRITE_PLY_DATA)
static int uc_count = 0;
std::vector<poly_t::face_t> faces;
for (FaceLoop *f = grp->face_loops.head; f; f = f->next) {
poly_t::face_t *temp = f->orig_face->create(f->vertices, false);
faces.push_back(*temp);
delete temp;
}
std::vector<poly_t::vertex_t> vertices;
carve::csg::VVMap vmap;
poly_t::collectFaceVertices(faces, vertices, vmap);
poly_t *p = new poly_t(faces, vertices);
std::ostringstream filename;
filename << "classifier_fail_" << ++uc_count << ".ply";
std::string out(filename.str().c_str());
::writePLY(out, p, false);
delete p;
#endif
return;
}
bool is_poly_a = cinfo.front().intersected_poly == src_b;
#if defined(CARVE_DEBUG)
bool is_poly_b = cinfo.front().intersected_poly == src_a;
std::cerr << "collect:: " << ENUM(fc) << " grp: " << grp << " (" << grp->face_loops.size() << " faces) is_poly_a?:" << is_poly_a << " is_poly_b?:" << is_poly_b << " against:" << cinfo.front().intersected_poly << std::endl;;
#endif
for (FaceLoop *f = grp->face_loops.head; f; f = f->next) {
collect(f->orig_face, f->vertices, f->orig_face->plane_eqn.N, is_poly_a, fc, hooks);
}
}
virtual poly_t *done(CSG::Hooks &hooks) {
std::vector<poly_t::face_t> f;
f.reserve(faces.size());
for (std::list<face_data_t>::iterator i = faces.begin(); i != faces.end(); ++i) {
f.push_back(poly_t::face_t());
std::swap(f.back(), *(*i).face);
delete (*i).face;
(*i).face = &f.back();
}
std::vector<poly_t::vertex_t> vertices;
carve::csg::VVMap vmap;
poly_t::collectFaceVertices(f, vertices, vmap);
poly_t *p = new poly_t(f, vertices);
if (hooks.hasHook(carve::csg::CSG::Hooks::RESULT_FACE_HOOK)) {
for (std::list<face_data_t>::iterator i = faces.begin(); i != faces.end(); ++i) {
hooks.resultFace((*i).face, (*i).orig_face, (*i).flipped);
}
}
return p;
}
};
class AllCollector : public BaseCollector {
public:
AllCollector(const poly_t *_src_a,
const poly_t *_src_b) : BaseCollector(_src_a, _src_b) {
}
virtual ~AllCollector() {
}
virtual void collect(FaceLoopGroup *grp, CSG::Hooks &hooks) {
for (FaceLoop *f = grp->face_loops.head; f; f = f->next) {
FWD(f->orig_face, f->vertices, f->orig_face->plane_eqn.N, f->orig_face->owner == src_a, FACE_OUT, hooks);
}
}
virtual void collect(const poly_t::face_t *orig_face,
const std::vector<const poly_t::vertex_t *> &vertices,
carve::geom3d::Vector normal,
bool poly_a,
FaceClass face_class,
CSG::Hooks &hooks) {
FWD(orig_face, vertices, normal, poly_a, face_class, hooks);
}
};
class UnionCollector : public BaseCollector {
public:
UnionCollector(const poly_t *_src_a,
const poly_t *_src_b) : BaseCollector(_src_a, _src_b) {
}
virtual ~UnionCollector() {
}
virtual void collect(const poly_t::face_t *orig_face,
const std::vector<const poly_t::vertex_t *> &vertices,
carve::geom3d::Vector normal,
bool poly_a,
FaceClass face_class,
CSG::Hooks &hooks) {
if (face_class == FACE_OUT || (poly_a && face_class == FACE_ON_ORIENT_OUT)) {
FWD(orig_face, vertices, normal, poly_a, face_class, hooks);
}
}
};
class IntersectionCollector : public BaseCollector {
public:
IntersectionCollector(const poly_t *_src_a,
const poly_t *_src_b) : BaseCollector(_src_a, _src_b) {
}
virtual ~IntersectionCollector() {
}
virtual void collect(const poly_t::face_t *orig_face,
const std::vector<const poly_t::vertex_t *> &vertices,
carve::geom3d::Vector normal,
bool poly_a,
FaceClass face_class,
CSG::Hooks &hooks) {
if (face_class == FACE_IN || (poly_a && face_class == FACE_ON_ORIENT_OUT)) {
FWD(orig_face, vertices, normal, poly_a, face_class, hooks);
}
}
};
class SymmetricDifferenceCollector : public BaseCollector {
public:
SymmetricDifferenceCollector(const poly_t *_src_a,
const poly_t *_src_b) : BaseCollector(_src_a, _src_b) {
}
virtual ~SymmetricDifferenceCollector() {
}
virtual void collect(const poly_t::face_t *orig_face,
const std::vector<const poly_t::vertex_t *> &vertices,
carve::geom3d::Vector normal,
bool poly_a,
FaceClass face_class,
CSG::Hooks &hooks) {
if (face_class == FACE_OUT) {
FWD(orig_face, vertices, normal, poly_a, face_class, hooks);
} else if (face_class == FACE_IN) {
REV(orig_face, vertices, normal, poly_a, face_class, hooks);
}
}
};
class AMinusBCollector : public BaseCollector {
public:
AMinusBCollector(const poly_t *_src_a,
const poly_t *_src_b) : BaseCollector(_src_a, _src_b) {
}
virtual ~AMinusBCollector() {
}
virtual void collect(const poly_t::face_t *orig_face,
const std::vector<const poly_t::vertex_t *> &vertices,
carve::geom3d::Vector normal,
bool poly_a,
FaceClass face_class,
CSG::Hooks &hooks) {
if ((face_class == FACE_OUT || face_class == FACE_ON_ORIENT_IN) && poly_a) {
FWD(orig_face, vertices, normal, poly_a, face_class, hooks);
} else if (face_class == FACE_IN && !poly_a) {
REV(orig_face, vertices, normal, poly_a, face_class, hooks);
}
}
};
class BMinusACollector : public BaseCollector {
public:
BMinusACollector(const poly_t *_src_a,
const poly_t *_src_b) : BaseCollector(_src_a, _src_b) {
}
virtual ~BMinusACollector() {
}
virtual void collect(const poly_t::face_t *orig_face,
const std::vector<const poly_t::vertex_t *> &vertices,
carve::geom3d::Vector normal,
bool poly_a,
FaceClass face_class,
CSG::Hooks &hooks) {
if ((face_class == FACE_OUT || face_class == FACE_ON_ORIENT_IN) && !poly_a) {
FWD(orig_face, vertices, normal, poly_a, face_class, hooks);
} else if (face_class == FACE_IN && poly_a) {
REV(orig_face, vertices, normal, poly_a, face_class, hooks);
}
}
};
}
CSG::Collector *makeCollector(CSG::OP op,
const poly_t *poly_a,
const poly_t *poly_b) {
switch (op) {
case CSG::UNION: return new UnionCollector(poly_a, poly_b);
case CSG::INTERSECTION: return new IntersectionCollector(poly_a, poly_b);
case CSG::A_MINUS_B: return new AMinusBCollector(poly_a, poly_b);
case CSG::B_MINUS_A: return new BMinusACollector(poly_a, poly_b);
case CSG::SYMMETRIC_DIFFERENCE: return new SymmetricDifferenceCollector(poly_a, poly_b);
case CSG::ALL: return new AllCollector(poly_a, poly_b);
}
return NULL;
}
}
}
|
ff3a3f643adcf049219c94f4fd57c17fe0e75572
|
502f2ff4dddc707b2ced51e3cd4058b5ad8f1502
|
/codeforces/101055A.cpp
|
fcb4bc4e0c5342c3e17441413bb61e17f3ff3e97
|
[] |
no_license
|
miguelAlessandro/CompetitiveProgramming
|
609a68a646f0976ed1c00fbcf861777844c7040d
|
64ac15eafb9c62dc713ce3d4b679ba6a032e1d5f
|
refs/heads/master
| 2021-06-01T11:02:22.439109
| 2020-10-08T06:26:27
| 2020-10-08T06:26:27
| 51,873,676
| 1
| 1
| null | 2020-10-08T06:26:28
| 2016-02-16T22:01:20
|
C++
|
UTF-8
|
C++
| false
| false
| 1,578
|
cpp
|
101055A.cpp
|
#include <bits/stdc++.h>
using namespace std;
const int N = 54;
long long X[N], Y[N], Z[N];
int n;
bool same(int l, int r){
return X[l] == X[r] and Y[l] == Y[r] and Z[l] == Z[r];
}
bool proof(int i, int j, int k, int l){
return ((Y[j]-Y[i])*(Z[k]-Z[i]) - (Y[k]-Y[i])*(Z[j]-Z[i]))*(X[l]-X[i]) +
((Z[j]-Z[i])*(X[k]-X[i]) - (X[j]-X[i])*(Z[k]-Z[i]))*(Y[l]-Y[i]) +
((X[j]-X[i])*(Y[k]-Y[i]) - (Y[j]-Y[i])*(X[k]-X[i]))*(Z[l]-Z[i]) == 0;
}
bool line(int i, int j, int k){
return (X[j]-X[i])*(Y[k]-Y[i]) == (Y[j]-Y[i])*(X[k]-X[i]) and
(X[j]-X[i])*(Z[k]-Z[i]) == (Z[j]-Z[i])*(X[k]-X[i]) and
(Y[j]-Y[i])*(Z[k]-Z[i]) == (Z[j]-Z[i])*(Y[k]-Y[i]);
}
int main(){
scanf("%d", &n);
for(int i = 0; i < n; ++i)
scanf("%I64d %I64d %I64d", X+i, Y+i, Z+i);
int r = 0;
for(int i = 0; i < n; ++i){
long long mask = 0;
int ans = 0;
for(int j = 0; j < n; ++j)
if(same(i, j)){
ans += 1;
mask |= (1LL<<j);
}
r = max(r, ans);
int ans2 = ans;
long long mask2 = mask;
for(int j = 0; j < n; ++j)
if(not(mask&(1LL<<j))){
ans++;
mask |= (1LL<<j);
for(int k = 0; k < n; ++k)
if(not(mask&(1LL<<k)) and line(i, j, k)){
ans += 1;
mask |= (1LL<<k);
}
int ans3 = ans;
for(int k = 0; k < n; ++k)
if(not(mask&(1LL<<k))){
ans += 1;
for(int l = 0; l < n; ++l)
if(l != k and not(mask&(1LL<<l)) and proof(i, j, k, l))
ans+=1;
r = max(r, ans);
ans = ans3;
}
r = max(r, ans);
mask = mask2;
ans = ans2;
}
}
printf("%d\n", r);
return 0;
}
|
2dae3c5832cb9beb88be1983af623c4837bb2752
|
c66b76f4f537c34e38b7645a9bd3eb6018aabfb8
|
/e7_tools_HRRT/libconvert/dift.cpp
|
0e94cf458c8c35cd3b505eead080f61fd09da3a9
|
[] |
no_license
|
andrewcrabb/hrrt_reconstruction
|
4a42ffb1e0dbc9e55c4c261b6e0bc9f3528f22da
|
1a3f0e2fe2607b3860acfe8804932be4882a3581
|
refs/heads/master
| 2020-07-19T08:42:16.473462
| 2019-09-04T21:50:56
| 2019-09-04T21:50:56
| 206,412,167
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 30,276
|
cpp
|
dift.cpp
|
/*! \class DIFT dift.h "dift.h"
\brief This class implements the DIFT (direct inverse fourier transform)
reconstruction of 2d sinograms.
\author Frank Kehren (frank.kehren@cpspet.com)
\date 2003/11/17 initial version
\date 2004/02/02 fixed the distortion-correction function, if the image
size is not a power of 2
\date 2005/01/25 added Doxygen style comments
The FFTs of the projections are calculated and shifted to the center of
rotation, and then the polar projections are distributed into the cartesian
grid of frequency space. The reconstructed image is iFFT'ed into image
space, corrected for distortions and shifted by one quadrant. The planes of
the image are calculated in parallel. Each thread calculates an even number
of planes. The number of threads is limited by the max_threads constant.
This code is originally based on Jim Hammils IDL DIFT reconstruction.
*/
#include <algorithm>
#include "e7_tools_const.h"
#include "dift.h"
#include "exception.h"
#include "fastmath.h"
#include "fft.h"
#include "global_tmpl.h"
#include "logging.h"
#include "progress.h"
#include "syngo_msg.h"
#include "thread_wrapper.h"
#include "types.h"
/*- constants ---------------------------------------------------------------*/
// expand projections by this factor (with padding)
const unsigned short int DIFT::EXPAND=4;
const unsigned short int DIFT::N_CORNERS=4; // corners to a square
const float DIFT::SMALL_VALUE=0.0001f; // weights smaller than this are zeroed
/*- local functions ---------------------------------------------------------*/
// The thread API is a C-API so C linkage and calling conventions have to be
// used, when creating a thread. To use a method as thread, a helper function
// in C is needed, that calls the method.
/*---------------------------------------------------------------------------*/
/*! \brief Start thread to execute DIFT reconstruction.
\param[in] param pointer to thread parameters
\return NULL or pointer to Exception object
\exception REC_UNKNOWN_EXCEPTION unknown exception generated
Start thread to execute DIFT reconstruction.
The thread API is a C-API so C linkage and calling conventions have to be
used, when creating a thread. To use a method as thread, a helper function
in C is needed, that calls the method.
*/
/*---------------------------------------------------------------------------*/
void *executeThread_DIFT(void *param)
{ try
{ DIFT::tthread_params *tp;
tp=(DIFT::tthread_params *)param;
tp->object->calc_dift(tp->sinogram, tp->image, tp->slices,
tp->fov_diameter, tp->max_threads,
tp->thread_number, true);
return(NULL);
}
catch (const Exception r)
{ return(new Exception(r.errCode(), r.errStr()));
}
catch (...)
{ return(new Exception(REC_UNKNOWN_EXCEPTION,
"Unknown exception generated."));
}
}
/*- methods -----------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/*! \brief Initialize object.
\param[in] _RhoSamples number of bins in projection
\param[in] _ThetaSamples number of angles in sinogram
\param[in] _DeltaXY with/height of voxel in image
\param[in] _loglevel top level for logging
Initialize object.
*/
/*---------------------------------------------------------------------------*/
DIFT::DIFT(const unsigned short int _RhoSamples,
const unsigned short int _ThetaSamples, const float _DeltaXY,
const unsigned short int _loglevel)
{ fft_rho_expand=NULL;
fft2d=NULL;
try
{ SyngoMsg("DIFT");
XYSamples=_RhoSamples;
DeltaXY=_DeltaXY;
origRhoSamples=_RhoSamples;
ThetaSamples=_ThetaSamples;
loglevel=_loglevel;
Logging::flog()->logMsg("XYSamples=#1", loglevel)->arg(XYSamples);
Logging::flog()->logMsg("DeltaXY=#1 mm", loglevel)->arg(DeltaXY);
Logging::flog()->logMsg("RhoSamples=#1", loglevel)->arg(origRhoSamples);
Logging::flog()->logMsg("ThetaSamples=#1", loglevel)->arg(ThetaSamples);
RhoSamples=2;
while (RhoSamples < origRhoSamples) RhoSamples*=2;
RhoSamplesExpand=RhoSamples*EXPAND;
XYSamples_padded=RhoSamples;
image_plane_size=(unsigned long int)XYSamples*
(unsigned long int)XYSamples;
image_plane_size_padded=(unsigned long int)XYSamples_padded*
(unsigned long int)XYSamples_padded;
sino_plane_size=(unsigned long int)RhoSamples*
(unsigned long int)ThetaSamples;
// transformation into frequency space by real-valued 1D-FFT
fft_rho_expand=new FFT(RhoSamplesExpand);
// transformation into image space by complex-valued 2D-FFT
fft2d=new FFT(XYSamples_padded, XYSamples_padded);
// array for weights used in coordinate transform from polar to cartesian
c.resize(N_CORNERS*(RhoSamplesExpand+1)*ThetaSamples);
indices.resize(c.size());// array for indices used in coordinate transform
dift_pol_cartes(&c, &indices); // create tables for coordinate transform
// create table for complex exp-function, used for
// shifting of projections in frequency space
cor_array=init_shift_table();
init_sinc_table(); // tables for distortion-correction and image mask
}
catch (...)
{ if (fft2d != NULL) { delete fft2d;
fft2d=NULL;
}
if (fft_rho_expand != NULL) { delete fft_rho_expand;
fft_rho_expand=NULL;
}
throw;
}
}
/*---------------------------------------------------------------------------*/
/*! \brief Destroy object.
Destroy object.
*/
/*---------------------------------------------------------------------------*/
DIFT::~DIFT()
{ if (fft2d != NULL) delete fft2d;
if (fft_rho_expand != NULL) delete fft_rho_expand;
}
/*---------------------------------------------------------------------------*/
/*! \brief DIFT reconstruction.
\param[in] sinogram sinogram data
\param[in,out] image reconstructed image
\param[in] slices number of sinogram slices
\param[out] fov_diameter diameter of FOV in mm
\param[in] max_threads maximum number of threads to use
\param[in] thread_num number of thread
\param[in] threaded method called as a thread ?
DIFT reconstruction of a stack of slices. This method is multi-threaded.
*/
/*---------------------------------------------------------------------------*/
void DIFT::calc_dift(float * const sinogram, float * const image,
const unsigned short int slices,
float * const fov_diameter,
const unsigned short int max_threads,
const unsigned short int thread_num, const bool threaded)
{ unsigned short int z;
float *sp, *ip;
std::string str;
std::vector <float> image_buffer;
if (threaded) str="thread "+toString(thread_num+1)+": ";
else str=std::string();
Logging::flog()->logMsg(str+"reconstruct #1 planes", loglevel+1)->
arg(slices);
image_buffer.resize(image_plane_size*2);
for (sp=sinogram,
ip=image,
z=0; z < slices; z+=2,
ip+=2*image_plane_size,
sp+=sino_plane_size)
{ bool fake_odd_slice;
float *c_ptr;
unsigned short int t;
unsigned long int *ind_ptr;
std::vector <float> image_buffer_padded;
// if number of slices is odd, the last slice
// (to make it an even number) is a zero slice
fake_odd_slice=(z == slices-1) && (slices & 0x1);
image_buffer_padded.assign(image_plane_size_padded*2, 0);
for (ind_ptr=&indices[0],
c_ptr=&c[0],
t=0; t < ThetaSamples; t++,
c_ptr+=N_CORNERS*(RhoSamplesExpand+1),
ind_ptr+=N_CORNERS*(RhoSamplesExpand+1),
sp+=RhoSamples)
// calculate FFT of projections and distribute polar
// projections into cartesian frequency domain image
distribute(dift_pad_ft(sp, fake_odd_slice), &image_buffer_padded[0],
ind_ptr, c_ptr);
// transform reconstruction back into image domain
fft2d->FFT_2D(&image_buffer_padded[0],
&image_buffer_padded[image_plane_size_padded], false,
max_threads);
// remove padding
{ unsigned short int offs, xs_2;
offs=XYSamples_padded-XYSamples;
xs_2=XYSamples/2;
for (unsigned short int plane=0; plane < 2; plane++)
for (unsigned short int y=0; y < XYSamples; y++)
{ float *ip, *is;
ip=&image_buffer[plane*image_plane_size+y*XYSamples];
is=&image_buffer_padded[plane*image_plane_size_padded+
y*XYSamples_padded];
if (y >= xs_2) is+=offs*XYSamples_padded;
memcpy(ip, is, xs_2*sizeof(float));
memcpy(ip+xs_2, is+offs+xs_2, xs_2*sizeof(float));
}
}
// correct two image slices for distortion, apply image mask
// and shift images by one quadrant
correct_image(&image_buffer[0], fov_diameter);
shift_image(&image_buffer[0], ip);
if (!fake_odd_slice)
{ correct_image(&image_buffer[image_plane_size], NULL);
shift_image(&image_buffer[image_plane_size], ip+image_plane_size);
}
}
Logging::flog()->logMsg(str+"scale #1 planes", loglevel+1)->arg(slices);
}
/*---------------------------------------------------------------------------*/
/*! \brief Correct for the distortions of the polar to cartesian coordinate
transformation.
\param[in,out] image data of image slice
\param[out] fov_diameter diameter of FOV in mm
Correct for the distortions of the polar to cartesian coordinate
transformation by dividing by \f$sinc^2(x)*sinc^2(y)\f$ and mask image.
*/
/*---------------------------------------------------------------------------*/
void DIFT::correct_image(float *image, float * const fov_diameter)
{ unsigned long int rsq_max;
// multiply image with 1/sinc function and mask image
rsq_max=image_plane_size/4;
if (fov_diameter != NULL)
*fov_diameter=sqrtf((float)rsq_max)*DeltaXY*2.0f;
for (unsigned short int y=0; y < XYSamples; y++)
{ unsigned long int y2;
y2=x2_table[y];
for (unsigned short int x=0; x < XYSamples; x++)
if (x2_table[x]+y2 <= rsq_max)
*image++*=(float)(sinc_table[x]*sinc_table[y]);
else *image++=0.0f;
}
}
/*---------------------------------------------------------------------------*/
/*! \brief Distribute array of polar-coordinates points into cartesian grid of
frequency domain.
\param[in] p (RhoSamplesExpand+1) data points,
representing complex FT of two
projections
\param[in,out] image_frq_slice1 two slices of frequency domain image
\param[in] indices indices used in converting from polar to
cartesian coordinates
\param[in] c weights used in converting from polar to
cartesian coordinates
Distribute array of polar-coordinates points into cartesian grid of
frequency domain.
*/
/*---------------------------------------------------------------------------*/
void DIFT::distribute(const std::vector<float> p,
float * const image_frq_slice1,
const unsigned long int *indices, const float *c) const
{ float *image_frq_slice2;
image_frq_slice2=image_frq_slice1+image_plane_size_padded;
for (unsigned short int r=0; r <= RhoSamplesExpand; r++)
{ float real, imag;
// distribute complex freq. domain value to 4 corners of cartesian grid
real=p[2*r];
imag=p[2*r+1];
for (unsigned short int i=0; i < N_CORNERS; i++)
{ image_frq_slice1[*indices]+=*c*real;
image_frq_slice2[*indices++]+=*c++*imag;
}
}
}
/*---------------------------------------------------------------------------*/
/*! \brief Padding of projections, FFT, shift to center-of-rotation and put
adjacent slices in the real and imaginary part of a complex slice.
\param[in] projection projection data (RhoSamples values)
\param[in] fake_odd_slice algorithm needs an even number of slices
\return FT of projections ((RhoSamplesExpand+1) complex values)
Padding of projections, FFT, shift to center-of-rotation and put adjacent
slices in the real and imaginary part of a complex slice.
*/
/*---------------------------------------------------------------------------*/
std::vector <float> DIFT::dift_pad_ft(const float * const projection,
const bool fake_odd_slice) const
{ float *pb1r, *pb1i;
std::vector <float> p, buf_even, buf_odd;
p.resize(2*RhoSamplesExpand+2);
buf_even.resize(RhoSamplesExpand+2);
// pad, FFT and shift of projection from even slice
dift_pft(projection, &buf_even[0], cor_array);
if (fake_odd_slice) // no odd slice available
{ float *pom;
unsigned short int x;
// output positive frequency
memcpy(&p[0], &buf_even[0], buf_even.size()*sizeof(float));
// output negative frequency
for (pb1r=&buf_even[2],
pb1i=&buf_even[3],
pom=&p[2*RhoSamplesExpand+1],
x=1; x <= RhoSamplesExpand/2; x++,
pb1r+=2,
pb1i+=2) { *pom--=-*pb1i;
*pom--=*pb1r;
}
}
else { float *pb2r, *pb2i, *pop, *pom;
unsigned short int x;
buf_odd.resize(RhoSamplesExpand+2);
// pad, FFT and shift of projection from odd slice
dift_pft(projection+sino_plane_size, &buf_odd[0], cor_array);
// combine FTs of projections
p[0]=buf_even[0]-buf_odd[1];
p[1]=buf_even[1]+buf_odd[0];
for (pb1r=&buf_even[2],
pb1i=&buf_even[3],
pb2r=&buf_odd[2],
pb2i=&buf_odd[3],
pop=&p[2],
pom=&p[2*RhoSamplesExpand+1],
x=1; x <= RhoSamplesExpand/2; x++,
pb1r+=2,
pb1i+=2,
pb2r+=2,
pb2i+=2)
{ *pop++=*pb1r-*pb2i;
*pop++=*pb2r+*pb1i;
*pom--=*pb2r-*pb1i;
*pom--=*pb1r+*pb2i;
}
}
return(p);
}
/*---------------------------------------------------------------------------*/
/*! \brief Padding and FFT of a projection and shifting of FFT.
\param[in] projection data of projection
\param[out] buffer resulting FT of projection
\param[in] cor_array lookup-table for complex exp() function
Padding and FFT of a projection and shifting of FFT.
*/
/*---------------------------------------------------------------------------*/
void DIFT::dift_pft(const float * const projection, float *buffer,
const std::vector <float> cor_array) const
{ memcpy(buffer, projection, RhoSamples*sizeof(float));
// padding of projection
memset(buffer+RhoSamples, 0, (RhoSamplesExpand-RhoSamples)*sizeof(float));
fft_rho_expand->rFFT_1D(buffer, true); // FFT of projection
buffer[RhoSamplesExpand]=buffer[1];
buffer[RhoSamplesExpand+1]=0.0f;
buffer[1]=0.0f;
// shift projection in frequency space
for (unsigned short int x=0; x <= RhoSamplesExpand/2; x++)
{ float ar, ai, br, bi;
ar=buffer[2*x];
ai=buffer[2*x+1];
br=cor_array[2*x];
bi=cor_array[2*x+1];
buffer[2*x]=ar*br-ai*bi;
buffer[2*x+1]=ar*bi+ai*br;
}
}
/*---------------------------------------------------------------------------*/
/*! \brief Find the four Cartesian coordinates points (u,v) surrounding a polar
point (k,m), and also the coefficients C(u,v;k,m) defined by
equation (21) in the report.
\param[out] c table of coefficients subscripted by
[view angle][radius][corner number]
\param[out] indices table of indices, for a given radius and angle in
frequency space, identify the lexigraphic indices
2*(x+N*y) of the four complex-number corners
Find the four Cartesian coordinates points (u,v) surrounding a polar
point (k,m), and also the coefficients C(u,v;k,m) defined by equation (21)
in the report.
*/
/*---------------------------------------------------------------------------*/
void DIFT::dift_pol_cartes(std::vector <float> * const c,
std::vector <unsigned long int> * const indices) const
{ unsigned short int mask_n;
unsigned long int *indptr;
float DeltaTheta, *cptr;
std::vector <float> rho, norm;
// set up the vector rho
rho.resize(RhoSamplesExpand+2);
{ unsigned short int r, r_retr;
rho[0]=0.0f;
for (r_retr=RhoSamplesExpand,
r=1; r <= RhoSamplesExpand/2; r++,
r_retr--)
{ rho[r]=(float)r/(float)EXPAND;
rho[r_retr]=-rho[r];
}
}
// create normalization matrix
norm.assign((unsigned long int)RhoSamples*(unsigned long int)RhoSamples*2,
0.0f);
mask_n=RhoSamples-1;
// compute the unnormalized coefficients and the indices
indptr=&(*indices)[0];
cptr=&(*c)[0];
DeltaTheta=M_PI/(float)ThetaSamples;
for (unsigned short int t=0; t < ThetaSamples; t++)
{ float *rptr;
unsigned short int r;
double cos_phi, sin_phi;
{ double theta;
theta=DeltaTheta*t;
cos_phi=cos(theta);
sin_phi=sin(theta);
}
if (t == ThetaSamples-1) DeltaTheta*=0.5f;
for (rptr=&rho[0],
r=0; r <= RhoSamplesExpand; r++,
rptr++)
{ signed short int ixw, ixe, iys, iyn;
float val, value, val2, wxw, wxe, wys, wyn;
double x, y, xe, yn;
signed long int ri;
// Locate the Cartesian grid points around each polar one and
// compute the weights of each point. The indices are converted
// to non-negative with a bit-by-bit logical AND.
x=*rptr*cos_phi;
y=*rptr*sin_phi;
xe=ceil(x);
yn=ceil(y);
wxw=xe-x;
wys=yn-y;
wxe=1.0f-wxw;
wyn=1.0f-wys;
ixe=(signed long int)xe;
ixw=(ixe-1) & mask_n;
ixe=ixe & mask_n;
iyn=(signed long int)yn;
iys=(iyn-1) & mask_n;
iyn=iyn & mask_n;
if (r == 0) val=0.25f/(float)EXPAND*DeltaTheta;
else val=fabsf(*rptr)*DeltaTheta;
// store the unnormalized coefficients for the four corners
val2=val*wys;
value=val2*wxw; // SW corner
ri=(signed long int)RhoSamples*iys;
*indptr=ri+ixw;
if (value >= SMALL_VALUE) { norm[*indptr]+=value;
*cptr++=value;
}
else *cptr++=0.0f;
indptr++;
value=val2*wxe; // SE corner
*indptr=ri+ixe;
if (value >= SMALL_VALUE) { norm[*indptr]+=value;
*cptr++=value;
}
else *cptr++=0.0f;
indptr++;
val2=val*wyn;
value=val2*wxw; // NW corner
ri=(signed long int)RhoSamples*iyn;
*indptr=ri+ixw;
if (value >= SMALL_VALUE) { norm[*indptr]+=value;
*cptr++=value;
}
else *cptr++=0.0f;
indptr++;
value=val2*wxe; // NE corner
*indptr=ri+ixe;
if (value >= SMALL_VALUE) { norm[*indptr]+=value;
*cptr++=value;
}
else *cptr++=0.0f;
indptr++;
}
}
// normalize the coefficients
for (unsigned long int i=0;
i < (unsigned long int)ThetaSamples*N_CORNERS*
(unsigned long int)(RhoSamplesExpand+1);
i++)
if ((*c)[i] > 0.0f) (*c)[i]/=norm[(*indices)[i]];
}
/*---------------------------------------------------------------------------*/
/*! \brief Create tables for distortion correction and masking.
Create \f$\frac{1}{sinc^2(x)}\f$-table used to correct for the distortions
of the polar to cartesian coordinate transformation and \f$x^2\f$-table
used to mask the image.
*/
/*---------------------------------------------------------------------------*/
void DIFT::init_sinc_table()
{ double coefficient;
unsigned short int idx, idx_retr;
unsigned long int x;
sinc_table.resize(XYSamples);
x2_table.resize(XYSamples);
// initialize tables for 1/sinc^2(x) and x^2
coefficient=M_PI/(double)XYSamples_padded;
sinc_table[0]=1.0f; // 1/sinc^2 at 0
x2_table[0]=0;
for (idx=1,
idx_retr=XYSamples-1,
x=1; x <= (unsigned long int)XYSamples/2; x++,
idx_retr--,
idx++)
{ double arg;
arg=coefficient*(double)x;
arg/=sin(arg);
sinc_table[idx]=arg*arg;
sinc_table[idx_retr]=sinc_table[idx];
x2_table[idx]=x*x;
x2_table[idx_retr]=x2_table[idx];
}
}
/*---------------------------------------------------------------------------*/
/*! \brief Create table for complex exp-function, used for shifting of
projections in frequency domain.
\return cor_array complex exponentials
Create table for complex exp-function, used for shifting of projections in
frequency domain.
*/
/*---------------------------------------------------------------------------*/
std::vector <float> DIFT::init_shift_table() const
{ double coeff;
std::vector <float> cor_array;
cor_array.clear();
coeff=-M_PI/(double)EXPAND;
for (unsigned short int i=0; i <= RhoSamplesExpand/2; i++)
{ double arg;
arg=coeff*(double)i;
cor_array.push_back(cosf((float)arg));
cor_array.push_back(sinf((float)arg));
}
return(cor_array);
}
/*---------------------------------------------------------------------------*/
/*! \brief Perform a multi-threaded DIFT reconstruction.
\param[in] sinogram sinogram data
\param[in] slices number of sinogram slices
\param[in] num matrix number
\param[out] fov_diameter diameter of FOV after reconstruction
\param[in] max_threads maximum number of threads to use
\return reconstructed image
Perform a multi-threaded DIFT reconstruction.
*/
/*---------------------------------------------------------------------------*/
float *DIFT::reconstruct(float *sinogram, unsigned short int slices,
const unsigned short int num,
float * const fov_diameter,
const unsigned short int max_threads)
{ try
{ float *image=NULL, *sino_pad=NULL;
std::vector <tthread_id> tid;
std::vector <bool> thread_running;
void *thread_result;
unsigned short int threads=0, t;
try
{ Progress::pro()->sendMsg(COM_EVENT::PROCESSING, 2,
"DIFT reconstruction (frame #1)")->arg(num);
// number of bins in projections must be power of 2
if (RhoSamples != origRhoSamples)
{ float *sp, *osp;
Logging::flog()->logMsg("padding of sinogram from #1x#2x#3 to "
"#4x#5x#6", loglevel)->arg(origRhoSamples)->
arg(ThetaSamples)->arg(slices)->arg(RhoSamples)->arg(ThetaSamples)->
arg(slices);
sino_pad=new float[sino_plane_size*(unsigned long int)slices];
memset(sino_pad, 0,
sino_plane_size*(unsigned long int)slices*sizeof(float));
sp=sino_pad+(RhoSamples-origRhoSamples)/2;
osp=sinogram;
for (unsigned long int pt=0;
pt < (unsigned long int)ThetaSamples*(unsigned long int)slices;
pt++,
sp+=RhoSamples,
osp+=origRhoSamples)
memcpy(sp, osp, origRhoSamples*sizeof(float));
sinogram=sino_pad;
}
threads=std::min(max_threads, slices);
// create buffer for reconstructed image
image=new float[image_plane_size*(unsigned long int)slices];
// single threaded ?
if (threads == 1)
{ calc_dift(sinogram, image, slices, fov_diameter, max_threads, 1,
false);
return(image);
}
float *sp, *ip;
unsigned short int i;
std::vector <tthread_params> tp;
tid.resize(threads);
tp.resize(threads);
thread_running.assign(threads, false);
for (sp=sinogram,
ip=image,
t=threads,
i=0; i < threads; i++,// distribute sinogram onto different threads
t--)
{ tp[i].object=this;
tp[i].sinogram=sp;
tp[i].image=ip;
tp[i].slices=slices/t;
if (i == 0) tp[i].fov_diameter=fov_diameter;
else tp[i].fov_diameter=NULL;
tp[i].thread_number=i;
tp[i].max_threads=max_threads;
// number of slices per thread must be even except last thread
if ((tp[i].slices & 0x1) != 0 && (t > 1)) tp[i].slices++;
thread_running[i]=true;
// start thread
Logging::flog()->logMsg("start thread #1 to reconstruct #2 planes",
loglevel)->arg(i+1)->arg(tp[i].slices);
ThreadCreate(&tid[i], &executeThread_DIFT, &tp[i]);
slices-=tp[i].slices;
sp+=(unsigned long int)tp[i].slices*sino_plane_size;
ip+=(unsigned long int)tp[i].slices*image_plane_size;
}
for (i=0; i < threads; i++) // wait until all threads are finished
{ ThreadJoin(tid[i], &thread_result);
thread_running[i]=false;
Logging::flog()->logMsg("thread #1 finished", loglevel)->arg(i+1);
if (thread_result != NULL) throw (Exception *)thread_result;
}
if (sino_pad != NULL) { delete[] sino_pad;
sino_pad=NULL;
}
return(image);
}
catch (...)
{ thread_result=NULL;
for (t=0; t < thread_running.size(); t++)
// thread_running is only true, if the
// exception was not thrown by the thread
if (thread_running[t])
{ void *tr;
ThreadJoin(tid[t], &tr);
// if we catch exceptions from the terminating threads,
// we store only the first one and ignore the others
if (thread_result == NULL)
if (tr != NULL) thread_result=tr;
}
if (image != NULL) delete[] image;
if (sino_pad != NULL) { delete[] sino_pad;
sino_pad=NULL;
}
// if the threads have thrown exceptions we throw the first
// one of them, not the one we are currently dealing with.
if (thread_result != NULL) throw (Exception *)thread_result;
throw;
}
}
catch (const Exception *r) // handle exceptions from threads
{ std::string err_str;
unsigned long int err_code;
// move exception object from heap to stack
err_code=r->errCode();
err_str=r->errStr();
delete r;
throw Exception(err_code, err_str); // and throw again
}
}
/*---------------------------------------------------------------------------*/
/*! \brief Shift image to new center.
\param[in] image_buffer image_data
\param[out] image shifted image data
Shift image to new center ((0,0) -> (n/2, n/2)).
*/
/*---------------------------------------------------------------------------*/
void DIFT::shift_image(const float * const image_buffer,
float * const image) const
{ unsigned short int size, y;
unsigned long int offs1, offs2, offs3, offs4;
size=XYSamples/2*sizeof(float);
for (offs1=0,
offs2=XYSamples/2,
offs3=image_plane_size/2,
offs4=image_plane_size/2+XYSamples/2,
y=0; y < XYSamples/2; y++,
offs4+=XYSamples,
offs3+=XYSamples,
offs2+=XYSamples,
offs1+=XYSamples)
{ memcpy(image+offs1, image_buffer+offs4, size);
memcpy(image+offs2, image_buffer+offs3, size);
memcpy(image+offs3, image_buffer+offs2, size);
memcpy(image+offs4, image_buffer+offs1, size);
}
}
|
130fa8fe2b29b94628504d80fd404ca4c78c7188
|
7c5ef5faf9b88e4c43d4e7403a176b939e68571e
|
/SatBoolValuesToInt/index.cpp
|
98afb5a57958917f9082223004f3b1066872ffbf
|
[] |
no_license
|
Nauchnik/utils
|
60421a9bfae92a0ed023c96dbd70b88783d65294
|
5f2818e4af543670e4cff29bf776e1e4c69623fd
|
refs/heads/master
| 2022-07-21T09:15:27.217845
| 2022-07-07T18:09:38
| 2022-07-07T18:09:38
| 13,406,116
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 827
|
cpp
|
index.cpp
|
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <boost/dynamic_bitset.hpp>
#include "../../pdsat/src_common/addit_func.h"
int main() {
std::ifstream ifile("in.txt");
std::vector<int> vars;
int val;
while ( ifile >> val )
vars.push_back( val );
ifile.close();
ifile.open( "bivium_reg_0" );
std::vector<bool> var_values;
unsigned k=0;
while ( ifile >> val ) {
if ( val == 0 )
continue;
var_values.push_back( val > 0 ? true : false );
}
ifile.close();
boost::dynamic_bitset<> d_b;
for ( unsigned i=0; i < vars.size(); i++ ) {
d_b.push_back( var_values[vars[i]-1] );
std::cout << d_b[d_b.size()-1];
}
std::cout << std::endl;
unsigned long long ull;
ull = Addit_func::BitsetToUllong( d_b );
std::cout << ull;
return 0;
}
|
3803ab1aee318c4a18d7eaebead8dc9d68c4ac70
|
4024dcc1dd142ef83a6f485a6187b064dbadac8a
|
/Assignment/Divide And Conquer/pivotElement.cpp
|
a7e0ad3e3639e5d513b981b942724744f8853b6f
|
[] |
no_license
|
Devforlife07/Algorithms
|
37b75c710614f81b2d7e8c6908561e98c4286daf
|
b191ae712ccc7e4bcb56f6d38eea62f7b8a1217e
|
refs/heads/master
| 2023-04-14T23:32:03.830844
| 2021-04-09T18:13:27
| 2021-04-09T18:13:27
| 268,325,882
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 659
|
cpp
|
pivotElement.cpp
|
#include <iostream>
using namespace std;
int getResult(int *a, int n, int s, int e)
{
if (s > e)
return -1;
if (s == e)
return s;
int mid = (s + e) / 2;
if (mid < e and a[mid] > a[mid + 1])
return mid;
if (mid > s and a[mid - 1] > a[mid])
return mid - 1;
if (a[s] >= a[mid])
return getResult(a, n, s, mid - 1);
else
return getResult(a, n, mid + 1, e);
}
int main()
{
int n;
cin >> n;
int *a = new int[n];
int i = 0;
while (i < n)
{
cin >> a[i];
i++;
}
int output = getResult(a, n, 0, n - 1);
cout << output << endl;
return 0;
}
|
ad0e491a1e8778443ce75b2394ca4c8a3a3f14d9
|
cfc52a796e8ad10c8d78274a1efe2d1ec47f38aa
|
/Quadroped.h
|
1817bb754501f2880f49cc7b37d6367eab00c0f6
|
[] |
no_license
|
Auk0105/Satoko
|
25e1d775d07397a4112aeb300a47636834bb76d2
|
f7895202467f9e886086de4332bd8768889c06b6
|
refs/heads/master
| 2016-09-01T09:16:53.177040
| 2016-03-24T04:07:28
| 2016-03-24T04:07:28
| 54,613,913
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,319
|
h
|
Quadroped.h
|
#ifndef _QUADROPED_H_
#define _QUADROPED_H_
#include "mbed.h"
#include "leg.h"
// http://marupeke296.com/TIPS_No13_ClassArrayInitialize.html
// 引数付きコンストラクタを持つメンバクラス配列の初期化
#include <new>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#define servo_tx p13
#define servo_rx p14
#define LF 0
#define LB 1
#define RF 2
#define RB 3
#define Irq_Cycle 0.01
#define Irq_Interval 0.00125 // cycle/8
#define Interval 0.25
#define RotaGain 1
#define SlowGain 3
#define MAX_xy 512
void Walk(int x_, int y_, bool sw1_, bool sw2_);
class Quadroped{
public:
Quadroped();
void attach();
void detach();
void SetStand();
void SetDrive();
void SetBack();
void SetLeft();
void SetRight();
void SetTurn_R();
void SetTurn_L();
void SetRota();
void SetSlow();
void SetStd();
void (Quadroped::*Irq)();
private:
Leg leg[4];
Ticker timer;
void CallIrq();
void Stand();
void Drive();
void Back();
void Left();
void Right();
void Turn_R();
void Turn_L();
float interval;
int interval_gain;
int call_count;
int flg[7];
};
#endif
|
a54a4a9860cb498500acc3afb2145edba44b3ed1
|
184cca2b088d0577ecae7ec9873f8ce50eb5c971
|
/src/ZoneServer/GroupManager.h
|
082586fae50d9b7a5042a524566ac232a827dadd
|
[] |
no_license
|
ferrin/mmoserver
|
b4cee672f725b768ef095f2f2af3f7eaf08acdcc
|
0d31607c60d879737752541a6c007fa9d316aa4e
|
refs/heads/master
| 2021-01-17T09:35:29.647731
| 2010-04-20T03:43:33
| 2010-04-20T03:43:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,621
|
h
|
GroupManager.h
|
/*
---------------------------------------------------------------------------------------
This source file is part of swgANH (Star Wars Galaxies - A New Hope - Server Emulator)
For more information, see http://www.swganh.org
Copyright (c) 2006 - 2010 The swgANH Team
---------------------------------------------------------------------------------------
*/
#ifndef ANH_ZONESERVER_GroupManager_H
#define ANH_ZONESERVER_GroupManager_H
#include <list>
#include "Common/MessageDispatchCallback.h"
#include "DatabaseManager/DatabaseCallback.h"
#include "Utils/typedefs.h"
//======================================================================================================================
#define gGroupManager GroupManager::getSingletonPtr()
//======================================================================================================================
class Database;
class DispatchClient;
class GroupObject;
class Message;
class MessageDispatch;
class MissionObject;
typedef std::vector<std::pair<MissionObject*,uint32> > MissionGroupRangeList;
typedef std::vector<GroupObject*> GroupList;
//======================================================================================================================
class GroupManager : public MessageDispatchCallback, public DatabaseCallback
{
public:
static GroupManager* getSingletonPtr() { return mSingleton; }
static GroupManager* Init(Database* database,MessageDispatch* dispatch);
GroupManager(Database* database,MessageDispatch* dispatch);
~GroupManager();
static inline void deleteManager(void)
{
if (mSingleton)
{
delete mSingleton;
mSingleton = 0;
}
}
void Shutdown();
virtual void handleDispatchMessage(uint32 opcode,Message* message,DispatchClient* client);
void sendGroupMissionUpdate(GroupObject* group);
MissionObject* getZoneGroupMission(std::list<uint64>* members);
GroupObject* getGroupObject(uint64 id);
void addGroupObject(GroupObject* group){mGroupList.push_back(group);}
void deleteGroupObject(uint64 id);
GroupList* getGroupList(){return &mGroupList;}
private:
void _processIsmInviteRequest(Message* message);
void _processIsmGroupCREO6deltaGroupId(Message* message);
void _processIsmGroupLootModeResponse(Message* message);
void _processIsmGroupLootMasterResponse(Message* message);
void _processIsmGroupInviteInRangeRequest(Message* message);
static GroupManager* mSingleton;
static bool mInsFlag;
Database* mDatabase;
MessageDispatch* mMessageDispatch;
GroupList mGroupList;
};
#endif
|
3ff29a5129446689891cb6e8270672b2d0190d25
|
ade4c266442afa5656695f8c148f8a52697523c6
|
/srccode/6276/20401413_AC_46ms_3744kB.cpp
|
8da9ccfbcead04bdc2796dcac2c0f25df351ed3a
|
[
"MIT"
] |
permissive
|
VaalaCat/hdu-auto-ac
|
ccfd88a0fba9f1d0cba1052e1f66940169bf342d
|
bb40ea61fc294dba20472b8e37a1fdd1d197c3e6
|
refs/heads/main
| 2023-02-04T03:26:03.659199
| 2020-12-30T06:11:24
| 2020-12-30T06:11:24
| 325,469,509
| 5
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 885
|
cpp
|
20401413_AC_46ms_3744kB.cpp
|
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <string>
#include <vector>
#include <set>
#define ls id<<1
#define rs id<<1|1
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const ll mod=1e9+7;
template <class _E> inline void read(_E &e){
e=0;bool ck=0;char ch=getchar();
while(ch>'9'||ch<'0'){if(ch=='-')ck=1;ch=getchar();}
while(ch>='0'&&ch<='9'){e=e*10+ch-'0';ch=getchar();}
if(ck)e=-e;
}
int n,ans;
ll sum;
int a[200050];
ll s[200050];
int main(){
while(scanf("%d",&n)==1){
ans=0;sum=0;
int pos=0;
for(int i=0;i<=n;++i)read(a[i]),s[i]=s[i-1]+a[i];
for(int i=1;i<=n;++i){
if(a[i]>=i){
sum=0;ans=i;continue;
}
else{
sum+=a[i];
while(sum>ans){
ans++;sum-=a[ans];
}
}
}
cout<<ans<<endl;
}
return 0;
}
|
db5fae0e0ace25fd6a1f0ba77eb490c751f7f74f
|
0fcb83f50a6bdec74882f3648a4c17d5d82c1707
|
/Trie.cpp
|
a9f24300815ef23d0db9f35d2c3f47649d0af8e5
|
[] |
no_license
|
vaibhav1865/HacktoberCodes
|
3cd29bf2ae5c12f26dd1bdff8a4a8555e6d2922c
|
d9afbcaf67119534ff15fa56a9b209d6bb9be782
|
refs/heads/main
| 2023-08-15T16:38:46.721158
| 2021-10-03T11:06:42
| 2021-10-03T11:06:42
| 413,052,557
| 0
| 0
| null | 2021-10-03T11:03:22
| 2021-10-03T11:03:21
| null |
UTF-8
|
C++
| false
| false
| 1,347
|
cpp
|
Trie.cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef struct node
{
struct node* children[26];
bool isEndOfWord=false;
node()
{
for(int i=0; i<26; i++)
children[i] = NULL;
}
}node;
void insert(node* root, string newStr)
{
node* curr = root;
for(int i=0; i<newStr.length(); i++)
{
int index = newStr[i] - 'a';
if(curr->children[index] == NULL)
curr->children[index] = new node;
curr = curr->children[index];
}
curr->isEndOfWord = true;
}
bool search(node* root, string key)
{
node* curr = root;
for(int i=0; i<key.length(); i++)
{
int index = key[i] - 'a';
if(curr->children[index] == NULL)
return false;
curr = curr->children[index];
}
if(curr!=NULL && curr->isEndOfWord)
return true;
return false;
}
int main()
{
vector<string> list_of_words { "bear", "bell", "bid", "bull", "buy", "sell", "stock", "stop" };
node* root = new node;
for(int i=0; i<list_of_words.size(); i++)
insert(root, list_of_words[i]);
cout<<"Is bell presnt in trie : " << search(root, "bell") << endl;
cout<<"Is belly present in trie : "<< search(root, "belly") << endl;
return 0;
}
|
98095908b398bc372df9c29947dea0eb025610fa
|
e9c0ffba62f5bd0c7bc1b3ca6173b40f3ab488f6
|
/LeetCode/Insert-Interval.cpp
|
08fe641c46d965425b815537bd838bc5d8329802
|
[] |
no_license
|
iiison/technical-interview-prep
|
501f15877feef3b6b6e1bf3c1ba8b06b894a923b
|
55b91267cdeeb45756fe47e1817cb5f80ed6d368
|
refs/heads/master
| 2022-11-24T11:21:22.526093
| 2020-08-04T13:49:32
| 2020-08-04T13:49:32
| 285,201,793
| 1
| 0
| null | 2020-08-05T06:33:34
| 2020-08-05T06:33:33
| null |
UTF-8
|
C++
| false
| false
| 1,177
|
cpp
|
Insert-Interval.cpp
|
// Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
// You may assume that the intervals were initially sorted according to their start times.
/* Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
Example 2:
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. */
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
intervals.push_back(newInterval);
sort(intervals.begin(), intervals.end(), [](Interval a, Interval b) {
return a.start < b.start;
});
vector<Interval> res = {intervals[0]};
for(int i = 1; i < intervals.size(); i++) {
if (res.back().end < intervals[i].start) {
res.push_back(intervals[i]);
} else {
res.back().end = max(res.back().end, intervals[i].end);
}
}
return res;
}
|
23f3dafc45aa648b3f45c299e4ba69eb49eee6d0
|
caa9c82b8127856aa035ca77a205bb0f7adfd14f
|
/EBYTE.h
|
52b5c1bb2524dae192ff9571c03159a5a692d220
|
[
"MIT"
] |
permissive
|
MxFxM/EBYTE
|
2d5029d8875087f3883bfcee6317b358eaff5957
|
5628efee248669aacbbeb3aba545e2dc6ace6810
|
refs/heads/master
| 2023-04-18T16:10:07.178394
| 2021-05-15T09:59:18
| 2021-05-15T09:59:18
| 286,521,357
| 0
| 0
| null | 2020-08-10T16:09:13
| 2020-08-10T16:09:12
| null |
UTF-8
|
C++
| false
| false
| 8,001
|
h
|
EBYTE.h
|
/*
Original code by: Kris Kasprzak kris.kasprzak@yahoo.com
Modified by: Max-Felix Mueller mxfxmmueller@gmail.com
This library is intended to be used with EBYTE transcievers, small wireless units for MCU's such as
Teensy and Arduino. This library let's users program the operating parameters and both send and recieve data.
This company makes several modules with different capabilities, but most #defines here should be compatible with them
All constants were extracted from several data sheets and listed in binary as that's how the data sheet represented each setting
Hopefully, any changes or additions to constants can be a matter of copying the data sheet constants directly into these #defines
Usage of this library consumes around 970 bytes
Module connection
Module MCU Description
MO any digital pin Pin to control working/program modes
M1 any digital pin Pin to control working/program modes
Rx Tx of Serial Interface Serial communication via UART
Tx Rx of Serial Interface Serial communication via UART
AUX any digital pin Pin to indicate when an operation is complete (low is busy, high is done)
Vcc +3v3 Use 3v3 to be save. Current draw can be high during transmission
Gnd Ground Ground must be common to module and MCU
Code usage
1. Create a serial object
2. Create EBYTE object that uses the serial object
3. Begin the serial object
4. Init the EBYTE object
5. Set parameters (optional but required if sender and reciever are different)
6. Send or listen to sent data
*/
#include <Arduino.h>
// delays in milliseconds to allow module to save and change states
#define PIN_RECOVER 20
#define AUX_PIN_RECOVER 20
// operating modes of module
#define MODE_NORMAL 0 // can send and recieve
#define MODE_WAKEUP 1 // sends a preamble to waken receiver
#define MODE_POWERDOWN 2 // can't transmit but receive works only in wake up mode
#define MODE_PROGRAM 3 // for reading and changeing programming
// save parameters during power loss or not
#define PERMANENT 0xC0
#define TEMPORARY 0xC2
// parity bit options
// (must be the same for transmitter and reveiver)
#define PB_8N1 0b00 // default
#define PB_8O1 0b01
#define PB_8E1 0b11
// UART data rates
// (can be different for transmitter and reveiver)
#define UDR_1200 0b000 // 1200 baud
#define UDR_2400 0b001 // 2400 baud
#define UDR_4800 0b010 // 4800 baud
#define UDR_9600 0b011 // 9600 baud default
#define UDR_19200 0b100 // 19200 baud
#define UDR_38400 0b101 // 34800 baud
#define UDR_57600 0b110 // 57600 baud
#define UDR_115200 0b111 // 115200 baud
// air data rates (certian types of modules)
// (must be the same for transmitter and reveiver)
#define ADR_300 0b000 // 300 baud
#define ADR_1200 0b001 // 1200 baud
#define ADR_2400 0b010 // 2400 baud
#define ADR_4800 0b011 // 4800 baud
#define ADR_9600 0b100 // 9600 baud
#define ADR_19200 0b101 // 19200 baud
// air data rates (other types of modules)
#define ADR_1K 0b000 // 1k baud
#define ADR_2K 0b001 // 2K baud
#define ADR_5K 0b010 // 4K baud
#define ADR_8K 0b011 // 8K baud
#define ADR_10K 0b100 // 10K baud
#define ADR_15K 0b101 // 15K baud
#define ADR_20K 0b110 // 20K baud
#define ADR_25K 0b111 // 25K baud
// various options
// (can be different for transmitter and reveiver)
#define OPT_FMDISABLE 0b0 //default
#define OPT_FMENABLE 0b1
#define OPT_IOOPENDRAIN 0b0
#define OPT_IOPUSHPULL 0b1
#define OPT_WAKEUP250 0b000
#define OPT_WAKEUP500 0b001
#define OPT_WAKEUP750 0b010
#define OPT_WAKEUP1000 0b011
#define OPT_WAKEUP1250 0b100
#define OPT_WAKEUP1500 0b101
#define OPT_WAKEUP1750 0b110
#define OPT_WAKEUP2000 0b111
#define OPT_FECDISABLE 0b0
#define OPT_FECENABLE 0b1
// transmitter output power
// check local regulations on legal transmit power
// refer to the data sheet as not all modules support these power levels
// constants for 1W units
// (can be different for transmitter and reveiver)
//#define OPT_TP30 0b00 // 30 db
//#define OPT_TP27 0b01 // 27 db
//#define OPT_TP24 0b10 // 24 db
//#define OPT_TP21 0b11 // 21 db
// constants or 500 mW units
//#define OPT_TP27 0b00 // 27 db
//#define OPT_TP24 0b01 // 24 db
//#define OPT_TP21 0b10 // 21 db
//#define OPT_TP18 0b11 // 17 db
//#define OPT_TP17 0b11 // 17 db
// constants or 100 mW units
#define OPT_TP20 0b00 // 20 db
#define OPT_TP17 0b01 // 17 db
#define OPT_TP14 0b10 // 14 db
#define OPT_TP11 0b11 // 10 db
#define OPT_TP10 0b11 // 10 db
class Stream;
class EBYTE {
public:
// constructor
EBYTE(Stream *s, uint8_t PIN_M0 = 4, uint8_t PIN_M1 = 5, uint8_t PIN_AUX = 6);
// initialization
bool init();
// methods to set modules working parameters
// NOTHING WILL BE APPLIED UNLESS SaveParameters() is called
void SetMode(uint8_t mode = MODE_NORMAL);
void SetAddress(uint16_t val = 0);
void SetAddressH(uint8_t val = 0);
void SetAddressL(uint8_t val = 0);
void SetAirDataRate(uint8_t val);
void SetUARTBaudRate(uint8_t val);
void SetSpeed(uint8_t val);
void SetOptions(uint8_t val);
void SetChannel(uint8_t val);
void SetParityBit(uint8_t val);
void SetTransmissionMode(uint8_t val);
void SetPullupMode(uint8_t val);
void SetWORTIming(uint8_t val);
void SetFECMode(uint8_t val);
void SetTransmitPower(uint8_t val);
// serial interface pass through
bool available();
void flush();
// methods to get modules working parameters
uint16_t GetAddress();
uint8_t GetModel();
uint8_t GetVersion();
uint8_t GetFeatures();
uint8_t GetAddressH();
uint8_t GetAddressL();
uint8_t GetAirDataRate();
uint8_t GetUARTBaudRate();
uint8_t GetChannel();
uint8_t GetParityBit();
uint8_t GetTransmissionMode();
uint8_t GetPullupMode();
uint8_t GetWORTIming();
uint8_t GetFECMode();
uint8_t GetTransmitPower();
uint8_t GetOptions();
uint8_t GetSpeed();
// methods to get data from sending unit
uint8_t GetByte();
bool GetStruct(const void *TheStructure, uint16_t size_);
// method to send to data to receiving unit
void SendByte(uint8_t TheByte);
bool SendStruct(const void *TheStructure, uint16_t size_);
// debug method to print parameters
void PrintParameters();
// apply changes after setting parameters
void SaveParameters(uint8_t retention = TEMPORARY);
protected:
// not working...
void Reset();
// function to read modules parameters
bool ReadParameters();
// wait for module to finish last operation
void CompleteTask(unsigned long timeout = 0);
// utility funciton to build the collection of a few different parameters
void BuildSpeedByte();
// utility funciton to build the collection of a few different parameters
void BuildOptionByte();
private:
// read model information
bool ReadModelData();
// discard serial interface input buffer
void ClearBuffer();
// variable for the serial stream
Stream* _s;
// pins
int8_t _M0;
int8_t _M1;
int8_t _AUX;
// variable for the 6 bytes that are sent to the module to program it
// or bytes received to indicate modules programmed settings
uint8_t _Params[6];
// indicidual variables for each of the 6 bytes
// _Params could be used as the main variable storage, but since some bytes
// are a collection of several options, let's just make storage consistent
// also Param[1] is different data depending on the _Save variable
uint8_t _Save;
uint8_t _AddressHigh;
uint8_t _AddressLow;
uint8_t _Speed;
uint8_t _Channel;
uint8_t _Options;
// individual variables for all the options
uint8_t _ParityBit;
uint8_t _UARTDataRate;
uint8_t _AirDataRate;
uint8_t _OptionTrans;
uint8_t _OptionPullup;
uint8_t _OptionWakeup;
uint8_t _OptionFEC;
uint8_t _OptionPower;
uint16_t _Address;
uint8_t _Model;
uint8_t _Version;
uint8_t _Features;
uint8_t _buf;
};
|
9bdc7d43fea19d791f187632f271d6f6fe0be569
|
25a31b58ca87b807db450021fd1150166b7d5d29
|
/直接插入排序.h
|
788d7ffa74b24b68944b90d4522a828618119ba5
|
[] |
no_license
|
yefuyi/hello_world
|
f47e3fbd9eacc6f48447dc7ae8b778a34ee37e35
|
cd67bd6c4b959088d3f4dab4eebd11f08b7c02ba
|
refs/heads/master
| 2021-01-17T18:18:49.222466
| 2020-06-29T12:28:34
| 2020-06-29T12:28:34
| 61,782,725
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 581
|
h
|
直接插入排序.h
|
#ifndef HEADER
#define HEADR 1
//用直接插入排序对数组a中的元素进行升序排序
template<class T>
void insertionSort(T a[], int n)
{
int i,j;
T temp;
//将下标从1 ~ n - 1的元素逐个插入到已排序的序列中的适当位置
for(int i = 1; i < n; i++)//从a[i-1]开始向a[0]方向扫描各个元素,寻找合适的位置插入a[i]
{
int j = i;
T temp = a[i];
while( j > 0 && temp < a[j - 1])//逐个比较直到temp > a[j - 1],那么a[j]便是插入位置
{
a[j] = a[j - 1];
j--;
}
a[j] = temp;
}
}
#endif
|
4652d1e9116e260894fdad85a7f2701c66ee8fbc
|
6d6f30e25560e05c62d39e6a1e81a12b67cc954a
|
/ssilki.cpp
|
f0cccec671f512aad0cdd804b449bc7478d524cb
|
[] |
no_license
|
FrolovaOlga/Olga-labs
|
7253b05b2e07e02503c9efc2b42896a741f1695e
|
7c926754c8468856ad582a030e3f074c5f5806f1
|
refs/heads/master
| 2016-08-12T23:06:23.464644
| 2016-03-30T13:19:30
| 2016-03-30T13:19:30
| 55,064,722
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 449
|
cpp
|
ssilki.cpp
|
#include <iostream>
using namespace std;
class MyClass{
public:
int a;
int b;
int c;
void show() {
cout<<"a= "<<a<<endl;
cout<<"b= "<<b<<endl;
cout<<"c= "<<c<<endl;
}
};
int main() {
sas a,b,c;
sas *p,*q,*x;
p=&a;
q=&b;
x=&c;
p->a=10;
q->b=25;
x->c=6;
cout<<(p->a+q->b+x->c)*p->a<<endl;
system ("pause");
return 0;
}
|
2c80aa78360affeaaed853a131f804cfe7269f6d
|
13da34a8bb7a182626a8bc0c769a734f5f925a9f
|
/cpp_solutions/hamming_distance.cpp
|
cbd60bf5ac87ab6c025b09b4a4527b49a1cd25d2
|
[] |
no_license
|
dhruv-jain/leetcode
|
e7bdc0b78fb2260c0f47162c3b82c17597d6c39b
|
a10b926b0db383a976b283f00a3ce2b21bba1d2c
|
refs/heads/master
| 2022-02-13T13:18:12.923259
| 2022-02-03T20:42:40
| 2022-02-03T20:42:40
| 79,752,469
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 556
|
cpp
|
hamming_distance.cpp
|
//The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
//Given two integers x and y, calculate the Hamming distance.
//Example:
//Input: x = 1, y = 4
//Output: 2
//Author - Dhruv Jain
class Solution {
public:
int hammingDistance(int x, int y) {
int count = 0;
int s = x ^ y;
while(s!=0)
{
if(s%2==1)
{
count++;
}
s = s/2;
}
return count;
}
};
|
e71798218cb93699ca8477139496625e6acb7928
|
8c8e31263c3f1ca6984754a4580ec7a6091ac843
|
/example-code/arduino-bt/do_command/WString.cpp
|
15f7afac566000377b2fbdfe1af3e72fff65d38a
|
[] |
no_license
|
reenberg/wobot
|
4a696ad9af37e0aac74ff67f3782ff2910d8f681
|
ce7f112096ba1abd43b8d29da7e8944c2a004125
|
refs/heads/master
| 2020-05-17T14:48:26.506669
| 2010-10-26T15:06:28
| 2010-10-26T15:06:28
| 130,731
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,927
|
cpp
|
WString.cpp
|
/*
WString.cpp - String library for Wiring & Arduino
version 0.4
Based on Tom Igoe's TextString original C++ implementation
Copyright (c) 2006-08 Hernando Barragan. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdlib.h>
#include "WProgram.h"
#include "WString.h"
String::String(const int length)
{
_array = (char*)malloc(length+1);
_capacity = length;
_length = 0;
clear();
}
String::String(const char* bytes)
{
if(bytes == NULL)
bytes= "";
_length = strlen(bytes);
//if (_capacity < _length) {
_capacity = _length;
// free(_array);
_array = (char*)malloc(_length+1);
//}
clear();
setArray(bytes);
}
String::String(const String &str)
{
_length = _capacity = str._length;
_array = (char*)malloc(_length + 1);
clear();
setArray(str._array);
}
// Public Methods
// Functions available in Wiring sketches, and other libraries
const String & String::operator=( const String &rightStr )
{
if ( this == &rightStr )
return *this;
if ( rightStr._length > _capacity )
{
free(_array);
_capacity = rightStr._length;
_array = (char*)malloc(_capacity+1);
}
_length = rightStr._length;
clear();
setArray( rightStr._array );
return *this;
}
const String & String::operator=(const char* bytes) {
//return *this = String(bytes);
if(bytes == NULL)
bytes = "";
_length = strlen(bytes);
if (_length > _capacity) {
_capacity = _length;
free(_array);
_array = (char*)malloc(_length+1);
}
clear();
setArray(bytes);
return *this;
}
const String & String::operator+=( const char* bytes) {
if(bytes == NULL)
bytes = "";
_length += strlen(bytes);
if ( _length > _capacity )
{
char *tmp = _array;
_capacity = _length;
_array = (char *) malloc (_length + 1);
setArray(tmp);
//strcpy( _array, tmp );
free(tmp);
}
strcat( _array, bytes );
_array[_length] = '\0';
return *this;
}
const String & String::operator+=( const char ch )
{
if ( _length == _capacity ) {
char *tmp = _array;
_capacity = ++_capacity*2;
_array = (char*)malloc(_capacity + 1);
setArray(tmp);
free(tmp);
}
_array[ _length++ ] = ch;
_array[ _length ] = '\0';
return *this;
}
const String & String::operator+=(int n)
{
append((long)n, 10);
//char *t = valueOf((long)n, 10);
//*this+=t;
//free(t);
return *this;
}
const String & String::operator+=(long n)
{
append(n, 10);
//char *t = valueOf(n, 10);
//*this+=t;
//free(t);
return *this;
}
const String & String::operator+=( const String &str )
{
_length += str._length;
if ( _length > _capacity )
{
char *tmp = _array;
_capacity = _length;
_array = (char *) malloc (_length + 1);
setArray(tmp);
//strcpy( _array, tmp );
free(tmp);
}
strcat( _array, str._array );
_array[_length] = '\0';
return *this;
}
const String & String::append(char c)
{
return (*this)+=c;
}
const String & String::append(char *str)
{
return (*this)+=str;
}
const String & String::append(const String &s1)
{
return (*this)+=s1;
}
const String & String::append(int n, int base)
{
append((long)n, base);
//char *t = valueOf((long)n, base);
//*this+=t;
//free(t);
return *this;
}
const String & String::append(long n, int base)
{
char *t = valueOf(n, base);
*this+=t;
free(t);
return *this;
}
const String & String::append(int n)
{
append((long)n, 10);
return *this;
//return (*this)+=n;
}
const String & String::append(long n)
{
append(n, 10);
return *this;
//return (*this)+=n;
}
// the library uses the append versions instead
// of the ones below, sometimes odd things happen :)
/*
String operator+(const String &s1, int n)
{
String result(s1);
result+=n;
return result;
}
String operator+(const String &s1, char c2)
{
String result(s1);
result+=c2;
return result;
}
String operator+(const String &s1, long n)
{
String result(s1);
result+=n;
return result;
}
String operator+(int n, const String &s1)
{
String result;
result+=n;
result+=s1;
return result;
}
String operator+(long n, const String &s1)
{
String result;
result+=n;
result+=s1;
return result;
}
String operator+(const String &s1, const String &s2)
{
String result(s1);
result+=s2;
return result;
}
String operator+(const String &s1, const char *s2)
{
String result(s1);
result += s2;
return result;
}
String operator+(const char *s1, const String &s2)
{
String result(s1);
result += s2;
return result;
}
String operator+(char c1, const String &s2)
{
String result;
result += c1;
result += s2;
return result;
}
*/
char String::charAt(int index)
{
char thisChar; // the character to return
//int length = strlen(_array); // the length of the string (not the whole array)
// as long as charNum isn't negative or bigger than the string length:
if (index >= 0 && _length > index) {
// get the character
thisChar = _array[index];
} else {
// if charNum is higher than the string length, return 0:
thisChar = 0;
}
return thisChar;
}
void String::setCharAt(int charNum, char thisChar)
{
if (_length > charNum) {
_array[charNum] = thisChar;
}
}
// Not needed, use append(String) instead
/*
const String & String::concat(const String &str)
{
return (*this) += str;
}
*/
boolean String::equals(char* str)
{
char match = 0; // whether or not the strings match
// strcmp() returns the comparison value of two strings. 0 means they're the same:
int comparison = strcmp(_array, str);
// if the comparison returns 0, you have a match:
match = (comparison == 0);
return match;
}
boolean String::equals(const String &str)
{
return equals(str.cstr());
}
boolean String::contains(char* subString)
{
char * subStringPointer;
subStringPointer = strstr(_array,subString);
return (subStringPointer != 0);
}
byte* String::getBytes(void)
{
return (byte*) _array;
}
void String::setArray(const char* bytes) {
//clear();
strncpy(_array,bytes,_length+1);
_array[_length] = '\0';
}
int String::indexOf(int ch)
{
return indexOf(ch, 0);
}
int String::indexOf(const String &str)
{
return indexOf(str, 0);
}
int String::indexOf(char ch, int fromIndex)
{
if(fromIndex >= _length)
return -1;
char* tmp = strchr( &_array[fromIndex], ch);
if(tmp == NULL)
return -1;
return tmp - _array;
}
int String::indexOf(const String &str, int fromIndex)
{
if(fromIndex >= _length)
return -1;
char *result = strstr(&_array[fromIndex], str.cstr());
if(result == NULL)
return -1;
return result - _array;
}
boolean String::startsWith(const String &prefix)
{
if(_length < prefix._length)
return false;
return startsWith( prefix, 0);
}
boolean String::startsWith( const String &prefix, int offset )
{
if ( offset > _length - prefix._length )
return 0;
return strncmp( &_array[offset], prefix.cstr(), prefix._length ) == 0;
}
String String::substring(int beginIndex)
{
return substring(beginIndex, _length);
}
String String::substring(int beginIndex, int endIndex)
{
if ( beginIndex > endIndex )
{
int tmp = endIndex;
endIndex = beginIndex;
beginIndex = tmp;
}
if ( endIndex > _length )
{
exit(1);
}
char ch = _array[ endIndex ];
_array[ endIndex ] = '\0';
String str = String( _array + beginIndex );
_array[ endIndex ] = ch;
return str;
}
char* String::valueOf(int n, int base)
{
return valueOf((long) n, base);
}
char* String::valueOf(long n, int base)
{
char *buf;
buf = (char*)malloc(8*sizeof(long)+1);
ltoa(n, buf, base);
return buf;
}
// The ones below are String version, not used in the actual library
/*String String::valueOf(int n, int base)
{
return valueOf((long) n, base);
}
String String::valueOf(long n, int base)
{
String str(8*sizeof(long)+1);
uint8_t buf[8*sizeof(long)+1];
int i = 0;
if(n < 0) {
str+='-';
n = -n;
}
if(n == 0) {
str+='0';
return str;
}
while(n > 0) {
buf[i++] = n%base;
n /= base;
}
for (i--; i >= 0; i--){
str+=(char)(buf[i] < 10 ? '0' + buf[i] : 'A' + buf[i] - 10);
}
return str;
}
*/
char* String::getChars(void)
{
// it should return a new array but it might end up
// being a memory leak in user's programs so it just returns a pointer
// to the internal array
/*
char *str = (char *)malloc(_length + 1);
strcpy(str, _array);
return str;
*/
return _array;
}
void String::trim(void)
{
// get the position of the last non-zero byte:
int stringIndex = 0;
// trim from the end of the string:
while (_array[stringIndex] == '\t' || // tab
_array[stringIndex] == '\r' || // carriage return
_array[stringIndex] == '\n' || // newline
_array[stringIndex] == ' ' || // space
_array[stringIndex] == 0x11) // vertical tab
{
stringIndex++;
}
memmove(_array, _array+stringIndex, strlen(_array));
// get the position of the last non-zero byte:
stringIndex = strlen(_array) - 1;
// trim from the end of the string:
while(_array[stringIndex] == '\t' || // tab
_array[stringIndex] == '\r' || // carriage return
_array[stringIndex] == '\n' || // newline
_array[stringIndex] == ' ' || // space
_array[stringIndex] == 0x11) // vertical tab
{
_array[stringIndex] = '\0';
stringIndex--;
}
}
boolean String::endsWith(const String &suffix)
{
if ( _length < suffix._length )
return 0;
return strcmp(&_array[_length-suffix._length], suffix.cstr()) == 0;
}
void String::replace(char oldChar, char newChar)
{
char* tmp = _array;
while( tmp = strchr( tmp, oldChar ) )
*tmp = newChar;
}
void String::toLowerCase(void)
{
for(int i = 0; i < _length; i++) {
_array[i] = tolower( _array[i]);
}
}
void String::toUpperCase(void)
{
for(int i = 0; i < _length; i++) {
_array[i] = toupper( _array[i]);
}
}
void String::clear(void) {
//int length = strlen(_array);
for (int c = 0; c < _capacity; c++) {
_array[c] = '\0';
}
}
/*
version() returns the version of the library:
*/
String String::version(void) {
return "0.4";
}
|
280603ee460137baa1c9638bfdcf40694667d7d6
|
b120b6a7dc4b4fecda47b72b745a976c71adf6c3
|
/OPT/bool_vector.h
|
1668de86a91c4da95ff22f617540cd51a8d762ac
|
[] |
no_license
|
ankifor/dualization-OPT
|
89f442c125a0ac74f8ee8a6face4f535464197b3
|
e7c44fd6422e1dbb6783d004e78596274776fed7
|
refs/heads/master
| 2020-12-30T10:12:47.981704
| 2015-02-26T22:05:33
| 2015-02-26T22:05:33
| 30,719,000
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,487
|
h
|
bool_vector.h
|
#pragma once
#include "my_int.h"
class Bool_Vector {
public:
ui32 find_next(ui32 bit) const throw();
ui32 popcount() const throw();
bool any() const throw();
bool all() const throw();
ui32 at(ui32 bit) const throw();
void set(ui32 bit) throw();
void reset(ui32 bit) throw();
void setall() throw();
void resetall() throw();
void resetupto(ui32 bit) throw();
//void reset_irrelevant_bits() throw();
inline ui32& operator[] (ui32 ind) throw() { return data_[ind]; }
inline const ui32& operator[] (ui32 ind) const throw() { return data_[ind]; }
inline const void* get_data() const throw() { return data_; }
inline ui32 size() const throw() { return size_; }
inline ui32 bitsize() const throw() { return bitsize_; }
inline ui32 mask() const throw() { return last_mask_; }
void copy(const Bool_Vector& src);
void assign(ui32* data, ui32 bitsz);//nocopy
void reserve(ui32 bitsz) { init_stats_(bitsz); reserve_(size_); }
Bool_Vector() : data_(nullptr), capacity_(0) { init_stats_(0); reserve_(0); }
Bool_Vector(ui32* data, ui32 bitsz) : data_(nullptr), capacity_(0) { assign(data, bitsz); }
~Bool_Vector() { init_stats_(0); reserve_(0); }
protected:
void init_stats_(ui32 bitsz) throw();//modifies bitsize_, size_, last_, mask_
void reserve_(ui32 capacity);
//static ui32 size_from_bitsize(ui32 bitsz) throw() { return (bitsz + UI32_BITS - 1) >> UI32_LOG2BIT; }
protected:
ui32* data_;
ui32 bitsize_;
ui32 size_;
ui32 last_mask_;
ui32 capacity_;
};
|
7aa96b1a296de6ed54945ca470d38a219028dd89
|
35becd680f26ba95b04104329406a13a3bd4bc0b
|
/Lab9_1/src/Lab9_1.cpp
|
18d03cca5e48b44dc389fb431e037e7581a27982
|
[] |
no_license
|
Stjowa/CS1
|
9765fbf0dbd1488c4dbdfc2658d595de1c2616c3
|
aaff3b4be8584f61d6293cc3806186f0fdccea89
|
refs/heads/master
| 2021-01-22T02:39:22.315857
| 2012-03-03T03:00:26
| 2012-03-03T03:00:26
| 2,432,735
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 563
|
cpp
|
Lab9_1.cpp
|
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
typedef char* charPtr;
charPtr p;
p = new char[64];
int pSize;
string tempString;
bool test=true;
char temp;
cout << "Please enter your sentence: ";
getline(cin, tempString);
for (int count=0;count < tempString.size();count++)
{
temp = tempString.at(count);
for(int i = 0; i < pSize; i++)
if(temp==p[i])
test = false;
if(test)
{
p[pSize]=temp;
pSize++;
}
test=true;
}
for(int i=0;i<pSize;i++)
cout << p[i];
delete p;
return 0;
}
|
ce0810606d8754699ca6b84e12eeedd89830b802
|
46ea1f05a06d7c8ee7323d47d3d249e9853236db
|
/src/cgi/txproj_list.cpp
|
86a292ec8f71657255879efd34dfdeacefbe6013
|
[] |
no_license
|
strangeroad/internship-2014
|
5a770e5977f2ac68093a2e4ecf921b0406585c4c
|
06f69490f7fb405f1fbe25af839d9b085253273d
|
refs/heads/master
| 2020-09-21T14:50:28.478152
| 2014-09-29T12:39:38
| 2014-09-29T12:39:38
| 224,822,353
| 1
| 0
| null | 2019-11-29T09:34:44
| 2019-11-29T09:34:44
| null |
UTF-8
|
C++
| false
| false
| 2,350
|
cpp
|
txproj_list.cpp
|
/*
* =====================================================================================
*
*
* Filename: txproj_list.cpp
*
* Description: 返回json
*
* Version: 1.0
* Created: 2014年08月17日 10时53分30秒
* Revision: none
* Compiler: gcc
*
* Author: pythonwood (wws), 582223837@qq.com
* Organization:
*
* =====================================================================================
*/
#include "../common/common.h"
using namespace std;
using namespace cgicc;
int main(int argc, char *argv[])
{
try {
Cgicc cgi;
char buf_send[MAXLINE]="\0", buf_recv[MAXLINE]="\0";
string
name = getCookie(cgi, "name"), //"rich", //
type = getCookie(cgi, "type"), //"2", //
token = getCookie(cgi, "token"), //"1080151822rich", //
id = getCookie(cgi, "id"); //"1000003"; //
if (type!="" && name!="" && token!="" && id!=""){
// if (type=="" || name=="" || token=="" || id==""){
string cmd = "list|" + type + '|' + id + '|' + token;
send_reci(cmd.c_str(), cmd.size()+10, buf_recv, MAXLINE);
// 有没有长度都行的
// 有但不对会误导浏览器,使执行时间长达15秒!!!!
// cout << "Content-Length:" << strlen(buf_recv)+2 << "\r\n";
cout << "Content-Type:application/json" << "\r\n\r\n";
// 格式必须json正确,不如$.get[JSON]回调函数不执行,大坑!!!
cout << buf_recv << "\r\n";
// cout << "{\"error\":0}" << "\r\n";
// cout << "{\"error\":0,\"type\":2, \"len\":0, \"data\":[]}" << "\r\n";
// cout << "{\"error\":0,\"type\":2, \"len\":0, \"data\":[{\"test\":1}]}" << "\r\n";
} else {
// 其他情况,失败
cout << HTTPHTMLHeader();
cout << "login " << buf_recv << "\r\n";
cout << "<script type=\"text/javascript\"> \
alert(\"非法!将定向到登录页。\");\
location.href='/txproj_index.html';\
</script>" << "\r\n";
}
}
catch(exception& e) {
// handle any errors - omitted for brevity
}
return 0;
}
|
436dea78c7369c8ac97c0659c1df0511cc550b5f
|
20d024bd04ace59987ba05f864d6d9dece72fbab
|
/CQU Summer/7-17 A/C - 小孩报数问题.cpp
|
37f274490659e05571ca5cd7a642a3dafacf4f48
|
[] |
no_license
|
Yeluorag/ACM-ICPC-Code-Library
|
8837688c23bf487d4374a76cf0656cb7adc751b0
|
77751c79549ea8ab6f790d55fac3738d5b615488
|
refs/heads/master
| 2021-01-20T20:18:43.366920
| 2016-08-12T08:08:38
| 2016-08-12T08:08:38
| 64,487,659
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 778
|
cpp
|
C - 小孩报数问题.cpp
|
#include <iostream>
#include <cstdio>
#include <map>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
int n, w, s, vis[105];
char str[105][105];
int main(){
// freopen("/Users/apple/input.txt","r",stdin);
// freopen("/Users/apple/out.txt","w",stdout);
cin >> n;
for(int i = 0; i < n; i++)
scanf("%s", str[i]);
memset(vis, 0, sizeof(vis));
scanf("%d,%d", &w, &s);
int i = w - 1, k = n;
while(k) {
int cnt = s;
for(; ; i++) {
i %= n;
if(vis[i]) continue;
cnt --;
if(!cnt) {
vis[i] = 1;
cout << str[i] << endl;
i ++;
break;
}
}
k --;
}
return 0;
}
|
ce6aa3f0706f4588d158d7a28961b779a4ff2c10
|
c68f791005359cfec81af712aae0276c70b512b0
|
/Regionals 2015 Asia - Jakarta/c.cpp
|
c98d68fe75f53a2a230675955d42e4a20eb44593
|
[] |
no_license
|
luqmanarifin/cp
|
83b3435ba2fdd7e4a9db33ab47c409adb088eb90
|
08c2d6b6dd8c4eb80278ec34dc64fd4db5878f9f
|
refs/heads/master
| 2022-10-16T14:30:09.683632
| 2022-10-08T20:35:42
| 2022-10-08T20:35:42
| 51,346,488
| 106
| 46
| null | 2017-04-16T11:06:18
| 2016-02-09T04:26:58
|
C++
|
UTF-8
|
C++
| false
| false
| 1,718
|
cpp
|
c.cpp
|
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
vector<int> all, pos[N];
map<pair<int, int>, int> cache;
int a[N], b[N];
int id(int val) {
return lower_bound(all.begin(), all.end(), val) - all.begin();
}
bool ada(int v) {
return binary_search(all.begin(), all.end(), v);
}
int main() {
int t;
scanf("%d", &t);
for (int tt = 1; tt <= t; tt++) {
cache.clear();
all.clear();
for (int i = 0; i < N; i++) pos[i].clear();
int n, q;
scanf("%d %d", &n, &q);
for (int i = 1; i <= n; i++) {
scanf("%d", a + i);
all.push_back(a[i]);
}
sort(all.begin(), all.end());
all.resize(distance(all.begin(), unique(all.begin(), all.end())));
for (int i = 1; i <= n; i++) {
int d = id(a[i]);
pos[d].push_back(i);
}
for (int i = 1; i <= n; i++) {
scanf("%d", b + i);
}
printf("Case #%d: \n", tt);
while (q--) {
int u, y;
scanf("%d %d", &u, &y);
if (!ada(u)) {
puts("1");
continue;
}
if (cache.count({u, y})) {
printf("%d\n", cache[{u, y}]);
continue;
}
int num = u;
u = id(u);
int now = -1;
int ans = 0;
int asli = 0;
while (now < (int) pos[u].size()) {
int at = lower_bound(pos[u].begin(), pos[u].end(), asli + b[y]) - pos[u].begin();
if (now + y < (int) pos[u].size()) {
at = max(at, now + y);
} else {
at = N;
}
if (at < (int) pos[u].size()) {
ans++;
asli = pos[u][at];
}
now = at;
}
if (asli != n) ans++;
printf("%d\n", ans);
cache[{num, y}] = ans;
}
}
return 0;
}
|
bac9a809e1adb4411d5e2793a6735568016ee189
|
27227bb903ff04c93f532325f148e539990278a2
|
/assignment-5/SkipList.cpp
|
1d2aa8dbed9564555dc66aed371a15638004ca61
|
[] |
no_license
|
MrFlyingPizza/cmpt-225-projects
|
1cfe2c37981f63bdbc2a5a7f4504a96f1dcfae41
|
498699ecefa4945dd9c91322e97bb0dbbf1c35ec
|
refs/heads/master
| 2023-01-21T05:19:03.560911
| 2020-12-03T07:35:28
| 2020-12-03T07:35:28
| 309,770,856
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,651
|
cpp
|
SkipList.cpp
|
#include <string>
#include <iostream>
#include "Entry.h"
#include "QuadNode.h"
#include "SkipList.h"
SkipList::SkipList()
: size_(0), max_level_(0)
{
lnode_ = new QuadNode(new Entry(Entry::MINUS));
lnode_->next_= new QuadNode(new Entry(Entry::PLUS));
rnode_ = lnode_->next_;
base_node_ = lnode_;
}
SkipList::~SkipList()
{
QuadNode *vnode = lnode_,
*hnode, *temp;
while (vnode != nullptr)
{
hnode = vnode;
while (hnode != nullptr)
{
temp = hnode;
hnode = hnode->next_;
}
vnode = vnode->below_;
}
}
Entry const& SkipList::find(const int k) const
{
if (empty()) return Entry::END_ENTRY;
QuadNode *current = lnode_->below_;
while (current != nullptr)
{
if (current->entry_->isKeyEqual(k)) return *current->entry_;
current = (!current->next_->entry_->isKeyGreaterThan(k))
? current->next_ : current->below_;
}
return Entry::END_ENTRY;
}
Entry const& SkipList::lesserEntry(const int k) const
{
if (empty()) return Entry::M_INF;
QuadNode* current = lnode_;
QuadNode* ahead = current->next_;
while (ahead->entry_->isKeyLessThan(k) || current->below_ != nullptr)
{
current = (!ahead->entry_->isKeyLessThan(k) || *ahead->entry_ == *rnode_->entry_)
? current->below_ : current->next_;
ahead = current->next_;
}
return *current->entry_;
}
Entry const& SkipList::greaterEntry(const int k) const
{
if (empty()) return Entry::P_INF;
QuadNode* current = rnode_;
QuadNode* ahead = current->prev_;
while (ahead->entry_->isKeyGreaterThan(k) || current->below_ != nullptr)
{
current = (!ahead->entry_->isKeyGreaterThan(k) || *ahead->entry_ == *lnode_->entry_)
? current->below_ : current->prev_;
ahead = current->prev_;
}
return *current->entry_;
}
void SkipList::put(const int k, const std::string v)
{
Entry *new_entry = new Entry(k,v);
int count = 0;
while (rand()%2 == 0) ++count;
for (int i = max_level_; i <= count; i++)
{
lnode_->above_ = new QuadNode(lnode_->entry_);
rnode_->above_ = new QuadNode(rnode_->entry_);
lnode_->above_->below_ = lnode_;
rnode_->above_->below_ = rnode_;
lnode_ = lnode_->above_;
rnode_ = rnode_->above_;
lnode_->next_ = rnode_;
rnode_->prev_ = lnode_;
++max_level_;
}
QuadNode *search_node = lnode_;
QuadNode *insert_node, *old_node = nullptr;
Entry *old_entry = nullptr;
int to_drop = max_level_ - count;
while (search_node != nullptr)
{
if (*search_node->next_->entry_ <= *new_entry)
{
search_node = search_node->next_;
}
else
{
insert_node = nullptr;
if (*search_node->entry_ == *new_entry)
{
if (search_node->below_ == nullptr)
old_entry = search_node->entry_;
insert_node = search_node;
insert_node->entry_ = new_entry;
}
else if (to_drop == 0)
{
insert_node = new QuadNode(new_entry);
insert_node->prev_ = search_node;
insert_node->next_ = search_node->next_;
insert_node->next_->prev_ = insert_node;
search_node->next_ = insert_node;
}
if (insert_node != nullptr)
{
insert_node->above_ = old_node;
if (old_node != nullptr)
old_node->below_ = insert_node;
old_node = insert_node;
}
search_node = search_node->below_;
if (to_drop != 0)
--to_drop;
}
}
if (old_entry == nullptr)
++size_;
else
delete old_entry;
}
void SkipList::erase(const int k)
{
if (empty()) throw NotFoundException();
QuadNode *current = lnode_->below_;
QuadNode *next = current;
while (!current->entry_->isKeyEqual(k) && current != nullptr)
{
next = current->next_;
current = (!next->entry_->isKeyGreaterThan(k) && *current->next_->entry_ != *rnode_->entry_)
? current->next_ : current->below_;
}
if (current == nullptr)
throw NotFoundException();
QuadNode *descend_lnode = lnode_->below_, *descend_rnode = rnode_->below_;
QuadNode *delete_node;
bool is_relink_top;
while (current != nullptr)
{
if (*current->prev_->entry_ == *lnode_->entry_ && *current->next_->entry_ == *rnode_->entry_)
{
descend_lnode = descend_lnode->below_;
descend_rnode = descend_rnode->below_;
delete current->prev_;
delete current->next_;
is_relink_top = true;
--max_level_;
}
current->prev_->next_ = current->next_;
current->next_->prev_ = current->prev_;
delete_node = current;
current = current->below_;
delete delete_node;
}
if (is_relink_top)
{
descend_lnode->above_ = lnode_;
descend_rnode->above_ = rnode_;
lnode_->below_ = descend_lnode;
rnode_->below_ = descend_rnode;
is_relink_top = false;
}
--size_;
}
int SkipList::size() const
{
return size_;
}
bool SkipList::empty() const
{
return size_ <= 0;
}
void SkipList::print() const
{
QuadNode *vnode = lnode_;
while (vnode != nullptr)
{
QuadNode *hnode = vnode;
QuadNode *search_node = base_node_;
while (hnode != nullptr)
{
int dash_count = 0;
while (*search_node->entry_ != *hnode->entry_)
{
dash_count += 2;
if (*search_node->next_->entry_ != *hnode->entry_)
dash_count += std::to_string(search_node->next_->entry_->getKey()).length();
search_node = search_node->next_;
}
for (int i = 0; i < dash_count; ++i)
std::cout << '-';
if (*hnode->entry_ == *lnode_->entry_)
{
std::cout << "-INF";
}
else if (*hnode->entry_ == *rnode_->entry_)
{
std::cout << "INF+";
}
else
{
std::cout << hnode->entry_->getKey();
}
hnode = hnode->next_;
}
std::cout << std::endl;
vnode = vnode->below_;
}
}
|
e5639281ff830a8f09e50c5ae6548481c007432c
|
32bfc176a5db0d59129f3c39381c46b0a520eb86
|
/demos/QMPlay/src/plugins/mp3/build/ui/ui_formMp3.h
|
7e1d5e5fbe6605d40c7ee02f61c9361dccd7baf1
|
[] |
no_license
|
varzhou/Hifi-Pod
|
2fb4c6bd3172720f8813fbbdf48375a10598a834
|
eec4e27e37bc5d99b9fddb65be06ef5978da2eee
|
refs/heads/master
| 2021-05-28T18:26:14.507496
| 2012-09-16T05:45:28
| 2012-09-16T05:45:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,773
|
h
|
ui_formMp3.h
|
/********************************************************************************
** Form generated from reading UI file 'formMp3.ui'
**
** Created: Tue Aug 21 20:18:27 2012
** by: Qt User Interface Compiler version 4.6.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_FORMMP3_H
#define UI_FORMMP3_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QPushButton>
#include <QtGui/QWidget>
QT_BEGIN_NAMESPACE
class Ui_FormMP3
{
public:
QLabel *aBitRateL;
QPushButton *closeButton;
QLabel *label;
QLabel *label_4;
QLabel *chnL;
QLineEdit *pthE;
QLabel *srateL;
QPushButton *id3B;
QLabel *id3L;
QLabel *imgL;
void setupUi(QWidget *FormMP3)
{
if (FormMP3->objectName().isEmpty())
FormMP3->setObjectName(QString::fromUtf8("FormMP3"));
FormMP3->resize(400, 220);
FormMP3->setMinimumSize(QSize(400, 220));
FormMP3->setMaximumSize(QSize(400, 220));
QIcon icon;
icon.addFile(QString::fromUtf8(""), QSize(), QIcon::Normal, QIcon::Off);
FormMP3->setWindowIcon(icon);
aBitRateL = new QLabel(FormMP3);
aBitRateL->setObjectName(QString::fromUtf8("aBitRateL"));
aBitRateL->setGeometry(QRect(70, 140, 52, 18));
closeButton = new QPushButton(FormMP3);
closeButton->setObjectName(QString::fromUtf8("closeButton"));
closeButton->setGeometry(QRect(310, 160, 81, 27));
closeButton->setCursor(QCursor(Qt::PointingHandCursor));
closeButton->setCheckable(true);
label = new QLabel(FormMP3);
label->setObjectName(QString::fromUtf8("label"));
label->setGeometry(QRect(10, 140, 61, 18));
label_4 = new QLabel(FormMP3);
label_4->setObjectName(QString::fromUtf8("label_4"));
label_4->setGeometry(QRect(10, 170, 51, 18));
chnL = new QLabel(FormMP3);
chnL->setObjectName(QString::fromUtf8("chnL"));
chnL->setGeometry(QRect(140, 130, 61, 18));
pthE = new QLineEdit(FormMP3);
pthE->setObjectName(QString::fromUtf8("pthE"));
pthE->setGeometry(QRect(10, 190, 381, 25));
pthE->setReadOnly(true);
srateL = new QLabel(FormMP3);
srateL->setObjectName(QString::fromUtf8("srateL"));
srateL->setGeometry(QRect(140, 150, 61, 20));
id3B = new QPushButton(FormMP3);
id3B->setObjectName(QString::fromUtf8("id3B"));
id3B->setGeometry(QRect(310, 130, 81, 28));
id3B->setCursor(QCursor(Qt::PointingHandCursor));
id3B->setCheckable(true);
id3L = new QLabel(FormMP3);
id3L->setObjectName(QString::fromUtf8("id3L"));
id3L->setGeometry(QRect(10, 10, 381, 111));
id3L->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop);
imgL = new QLabel(FormMP3);
imgL->setObjectName(QString::fromUtf8("imgL"));
imgL->setGeometry(QRect(230, 130, 50, 50));
imgL->setMinimumSize(QSize(50, 50));
imgL->setMaximumSize(QSize(50, 50));
imgL->setFrameShape(QFrame::StyledPanel);
imgL->setFrameShadow(QFrame::Raised);
QWidget::setTabOrder(closeButton, id3B);
QWidget::setTabOrder(id3B, pthE);
retranslateUi(FormMP3);
QMetaObject::connectSlotsByName(FormMP3);
} // setupUi
void retranslateUi(QWidget *FormMP3)
{
FormMP3->setWindowTitle(QApplication::translate("FormMP3", "MP3 music information", 0, QApplication::UnicodeUTF8));
aBitRateL->setText(QApplication::translate("FormMP3", "BR", 0, QApplication::UnicodeUTF8));
closeButton->setText(QApplication::translate("FormMP3", "Close", 0, QApplication::UnicodeUTF8));
closeButton->setShortcut(QApplication::translate("FormMP3", "Esc", 0, QApplication::UnicodeUTF8));
label->setText(QApplication::translate("FormMP3", "Bitrate:", 0, QApplication::UnicodeUTF8));
label_4->setText(QApplication::translate("FormMP3", "Path:", 0, QApplication::UnicodeUTF8));
chnL->setText(QApplication::translate("FormMP3", "channels", 0, QApplication::UnicodeUTF8));
srateL->setText(QApplication::translate("FormMP3", "rate", 0, QApplication::UnicodeUTF8));
id3B->setText(QApplication::translate("FormMP3", "Edit ID3", 0, QApplication::UnicodeUTF8));
id3L->setText(QString());
imgL->setText(QString());
} // retranslateUi
};
namespace Ui {
class FormMP3: public Ui_FormMP3 {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_FORMMP3_H
|
f70a7795f7c8da9932d72185bd33b1c3c563d57d
|
2045ab194dccdf69ca312589cf968278248e9a27
|
/ts-messages/messages/Part43ATCRBS.h
|
03460916e5f25f31e021f8de60eaa95269829806
|
[] |
no_license
|
manish-drake/ts-wrap
|
427d1e7cf2e1cfa3d63b4bde576eead9a06d0c04
|
c165024102985aea9942f6ca2f217acdaf737ce5
|
refs/heads/master
| 2020-08-28T04:10:03.493253
| 2020-01-29T15:48:04
| 2020-01-29T15:48:04
| 217,583,116
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,217
|
h
|
Part43ATCRBS.h
|
#ifndef __Part43ATCRBS_h
#define __Part43ATCRBS_h
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "TServerMessage.h"
class CPart43ATCRBS:public TServerMessage
{
const int mFormatVersion = 0;
char* json_string;
public:
static const unsigned int mCmdID=0xc;
CPart43ATCRBS(void)
{
setCmdID(mCmdID);
}
CPart43ATCRBS(Json::Value obj):TServerMessage(obj)
{
set(obj);
setCmdID(mCmdID);
}
void setTestNum(unsigned int value)
{
write("TestNum",value);
}
unsigned int getTestNum(void)
{
return getUInt("TestNum");
}
bool isTestNumValid(void)
{
return isValid("TestNum");
}
void setModeACode(unsigned int value)
{
write("ModeACode",value);
}
unsigned int getModeACode(void)
{
return getUInt("ModeACode");
}
bool isModeACodeValid(void)
{
return isValid("ModeACode");
}
void setModeACodeReplyPass(bool value)
{
write("ModeACodeReplyPass",value);
}
bool getModeACodeReplyPass(void)
{
return getBool("ModeACodeReplyPass");
}
bool isModeACodeReplyPassValid(void)
{
return isValid("ModeACodeReplyPass");
}
void setModeACodeReplyPct(float value)
{
write("ModeACodeReplyPct",value);
}
float getModeACodeReplyPct(void)
{
return getFloat("ModeACodeReplyPct");
}
bool isModeACodeReplyPctValid(void)
{
return isValid("ModeACodeReplyPct");
}
void setModeAIdent(bool value)
{
write("ModeAIdent",value);
}
bool getModeAIdent(void)
{
return getBool("ModeAIdent");
}
bool isModeAIdentValid(void)
{
return isValid("ModeAIdent");
}
void setModeCAltitude(unsigned int value)
{
write("ModeCAltitude",value);
}
unsigned int getModeCAltitude(void)
{
return getUInt("ModeCAltitude");
}
bool isModeCAltitudeValid(void)
{
return isValid("ModeCAltitude");
}
void setModeCReplyPass(bool value)
{
write("ModeCReplyPass",value);
}
bool getModeCReplyPass(void)
{
return getBool("ModeCReplyPass");
}
bool isModeCReplyPassValid(void)
{
return isValid("ModeCReplyPass");
}
void setModeCReplyPct(float value)
{
write("ModeCReplyPct",value);
}
float getModeCReplyPct(void)
{
return getFloat("ModeCReplyPct");
}
bool isModeCReplyPctValid(void)
{
return isValid("ModeCReplyPct");
}
void setPass(bool value)
{
write("Pass",value);
}
bool getPass(void)
{
return getBool("Pass");
}
bool isPassValid(void)
{
return isValid("Pass");
}
void setMessage(std::string jsonstring)
{
TServerMessage::setMessage(jsonstring);
}
void set(Json::Value obj)
{
TServerMessage::set(obj);
}
std::string getMessage(void)
{
return TServerMessage::getMessage();
}
Json::Value get(void)
{
return TServerMessage::get();
}
};
#endif
|
6397bf723fd06360c9f0a607ab159937d01ed98a
|
e1b592074c550149f43c1dce0a4d4ece26bce92c
|
/Strings/orderly queue - GOOD.cpp
|
d3c4ebb254e1322b943a5dffec81b1888ccf49a0
|
[] |
no_license
|
taruvar-mittal/DSA-Solutions
|
2155ccc170c372f92c60fa5acd3676ec4891baf9
|
2a23a688fc553d28d9beb7965c5b2b1db2f8f266
|
refs/heads/master
| 2023-08-17T07:14:46.680402
| 2021-09-25T15:57:04
| 2021-09-25T15:57:04
| 358,480,177
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,264
|
cpp
|
orderly queue - GOOD.cpp
|
/*
Leetcode 899. Orderly Queue
ques:-
You are given a string s and an integer k. You can choose one of the first k letters of s and append it at the end of the string..
Return the lexicographically smallest string you could have after applying the mentioned step any number of moves.
Example 1:
Input: s = "cba", k = 1
Output: "acb"
Explanation:
In the first move, we move the 1st character 'c' to the end, obtaining the string "bac".
In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb".
Example 2:
Input: s = "baaca", k = 3
Output: "aaabc"
Explanation:
In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab".
In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc".
*/
class Solution
{
public:
string orderlyQueue(string s, int k)
{
if (k == 1)
{
string ans = s;
for (int i = 0; i < s.length(); i++)
{
char c = s[0];
string temp = s.substr(1);
temp += c;
ans = min(ans, temp);
s = temp;
}
return ans;
}
sort(s.begin(), s.end());
return s;
}
};
|
36552f5d9bda9d2a159991d29e9800fcb56c49f7
|
a89efb0fd45e057b8c1ef6de49b2b7a8254164b1
|
/FastCG/include/FastCG/Rendering/MaterialDefinition.h
|
4fa479f1efd29f49e0c9c69327af10bf11e2508d
|
[] |
no_license
|
pboechat/FastCG
|
cd5760b94cee7be760c5b267f64b20ba7b87a42e
|
663272da3a45656ce5590e5d9c317b92200c9e47
|
refs/heads/master
| 2023-08-31T20:57:32.259089
| 2023-08-10T10:13:08
| 2023-08-10T10:13:08
| 9,269,509
| 6
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,064
|
h
|
MaterialDefinition.h
|
#ifndef FASTCG_MATERIAL_DEFINITION_H
#define FASTCG_MATERIAL_DEFINITION_H
#include <FastCG/Graphics/GraphicsSystem.h>
#include <FastCG/Graphics/GraphicsContextState.h>
#include <FastCG/Graphics/ConstantBuffer.h>
#include <vector>
#include <unordered_map>
#include <cassert>
namespace FastCG
{
struct MaterialDefinitionArgs
{
std::string name;
const Shader *pShader;
std::vector<ConstantBuffer::Member> constantBufferMembers;
std::unordered_map<std::string, const Texture *> textures;
GraphicsContextState graphicsContextState;
};
class MaterialDefinition final
{
public:
MaterialDefinition(const MaterialDefinitionArgs &rArgs) : mName(rArgs.name),
mpShader(rArgs.pShader),
mConstantBuffer(rArgs.constantBufferMembers),
mTextures(rArgs.textures),
mGraphicsContextState(rArgs.graphicsContextState)
{
assert(mpShader != nullptr);
}
~MaterialDefinition() = default;
inline const std::string &GetName() const
{
return mName;
}
inline const Shader *GetShader() const
{
return mpShader;
}
inline const ConstantBuffer &GetConstantBuffer() const
{
return mConstantBuffer;
}
inline const auto &GetTextures() const
{
return mTextures;
}
inline const GraphicsContextState &GetGraphicsContextState() const
{
return mGraphicsContextState;
}
protected:
const std::string mName;
const Shader *mpShader;
const ConstantBuffer mConstantBuffer;
const std::unordered_map<std::string, const Texture *> mTextures;
const GraphicsContextState mGraphicsContextState;
};
}
#endif
|
4a094f984d69567af9f2837a467b5a4b7d59d884
|
dc466cedcd1d328e75d59ad4c044b8bcd1061b06
|
/src/Client.cpp
|
23679cd18ad8a7547233c0597056c84cc0efe075
|
[] |
no_license
|
whztt07/RampageRacing-Ogre
|
3299118e3b3bf299e5f45c00d054c51304ff0838
|
3f77e8bd7d4d78e49f00ae5668690f0818ed7b76
|
refs/heads/master
| 2021-01-18T18:14:24.022966
| 2015-04-11T21:25:36
| 2015-04-11T21:25:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,082
|
cpp
|
Client.cpp
|
#include "Client.h"
Client::Client()
{
Ogre::String basename, path;
Ogre::StringUtil::splitFilename("network.settings", basename, path);
Ogre::DataStreamPtr pStream = Ogre::ResourceGroupManager::getSingleton().openResource(basename, "General");
while (!pStream->eof())
{
Ogre::String data = pStream->getLine();
auto p = data.find(" ");
std::string phrase = data.substr(0, p);
if (phrase == "serverIP")
{
char buffer[32];
sscanf_s(data.c_str(), "%*[^ ] %s", &buffer, 32);
this->ip = Ogre::String(buffer);
}
}
}
Client::~Client()
{
RakNet::RakPeerInterface::DestroyInstance(mClient);
}
void Client::Connect(const char* address, const unsigned int& serverPort, const unsigned int clientPort, const char* password)
{
mSockDesc = new RakNet::SocketDescriptor(clientPort, NULL);
mSockDesc->socketFamily = AF_INET;
mClient = RakNet::RakPeerInterface::GetInstance();
RakNet::StartupResult res = mClient->Startup(1, mSockDesc, 1);
assert(res == RakNet::RAKNET_STARTED && "client Count Not Connect.\n");
RakNet::ConnectionAttemptResult conRes = mClient->Connect(address, serverPort, password, strlen(password));
assert(conRes == RakNet::CONNECTION_ATTEMPT_STARTED && "Client could not connect.\n");
}
void Client::SendString(const std::string &data)
{
mClient->Send(data.c_str(), data.length(), HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true);
}
void Client::Recieve()
{
while ((mPacket = mClient->Receive()) != NULL)
{
std::string str = std::string((char*)mPacket->data).substr(0, mPacket->length);
auto p = str.find(" ");
std::string phrase = str.substr(0, p);
if (phrase == "pos")
{
int id = 0;
float pos[3];
sscanf_s(str.c_str(), "%*[^0-9]%d %f %f %f", &id, &pos[0], &pos[1], &pos[2]);
//guard against uninitialized values
if (pos[0] > -99999 && pos[0] < 99999 && totalPlayers > 0)
{
Ogre::Vector3 p = Ogre::Vector3(pos[0], pos[1], pos[2]);
mConnectedPlayers[id].futurePos = (p - mConnectedPlayers[id].currentPos) + p;
mConnectedPlayers[id].currentPos = p;
}
}
else if (phrase == "rot")
{
int id = 0;
float rot[4];
sscanf_s(str.c_str(), "%*[^0-9]%d %f %f %f %f", &id, &rot[0], &rot[1], &rot[2], &rot[3]);
if (rot[0] > -99999 && rot[0] < 99999 && totalPlayers > 0)
{
mConnectedPlayers[id].time = 0.0f;
Ogre::Quaternion r = Ogre::Quaternion(rot[3], rot[0], rot[1], rot[2]);
mConnectedPlayers[id].futureRot = (r - mConnectedPlayers[id].currentRot) + r;
mConnectedPlayers[id].currentRot = r;
}
}
else if (phrase == "startIndex" && startingIndex == 999)
{
sscanf_s(str.c_str(), "%*[^0-9]%d", &startingIndex);
}
else if (phrase == "totalPlayers")
{
sscanf_s(str.c_str(), "%*[^0-9]%d", &totalPlayers);
mConnectedPlayers = new Object[totalPlayers];
}
else if (phrase == "start")
{
if (startingIndex != 999)
{
allReady = true;
}
}
else if (phrase == "everyoneDoneLoading")
{
allDoneLoading = true;
}
else if (phrase == "item")
{
unsigned int i, item;
sscanf_s(str.c_str(), "%*[^0-9]%d %d", &i, &item);
mConnectedPlayers[i].item = ITEM_BOX_TYPE(item);
}
else if (phrase == "res")
{
TimeObject temp;
sscanf_s(str.c_str(), "res %d %d %d %d %d", &temp.rank, &temp.id, &temp.minutes, &temp.seconds, &temp.ms);
raceResults.push_back(temp);
}
else if (phrase == "raceComplete")
{
raceComplete = true;
}
else if (phrase == "seed")
{
int seed;
sscanf_s(str.c_str(), "%*[^0-9]%d", &seed);
srand(seed);
}
mClient->DeallocatePacket(mPacket);
}
}
void Client::Update(const float deltaTime, const unsigned int id)
{
mConnectedPlayers[id].time += deltaTime;
mConnectedPlayers[id].pos = Ogre::Math::lerp(mConnectedPlayers[id].currentPos, mConnectedPlayers[id].futurePos, mConnectedPlayers[id].time/EXPECTED_TIME_BETWEEN_NETWORK_UPDATES);
mConnectedPlayers[id].rot = Ogre::Math::lerp(mConnectedPlayers[id].currentRot, mConnectedPlayers[id].currentRot, mConnectedPlayers[id].time/EXPECTED_TIME_BETWEEN_NETWORK_UPDATES);
}
|
c35d368a2ba212d1d808fbcea920bc25717b4d99
|
87257c3ce00d00b9cf4105f9ab507b13ae2237ff
|
/src/Options.cpp
|
fda8e6e37be40d0c19d64ddf0275d0f7c40f4624
|
[] |
no_license
|
redavids/wASTRAL
|
5588a038b0fb5da0356c3511bcd746fc93a657d7
|
294775d3c0adb7fe819281d6bb520bb62e6dde9b
|
refs/heads/master
| 2022-08-22T09:24:05.942611
| 2016-02-08T19:17:45
| 2016-02-08T19:17:45
| 51,416,931
| 0
| 1
| null | 2022-08-09T21:22:37
| 2016-02-10T02:41:48
|
C++
|
UTF-8
|
C++
| false
| false
| 2,828
|
cpp
|
Options.cpp
|
#include "Options.hpp"
#include "Logger.hpp"
#include <cassert>
#include <iostream>
#include <iterator>
#include <sstream>
bool Options::inited = false;
vector<string> Options::argv;
map<string, string> Options::opts_map;
string Options::input;
enum option_type {SHORT, LONG, ARG, END, EMPTY};
option_type get_option_type(string& arg) {
if (arg.size() == 0) return EMPTY;
if (arg[0] != '-') return ARG;
if (arg.size() == 1) {
cerr << "INVALID ARGUMENT " << arg << endl;
exit(1);
}
if (arg[1] == '-') {
if (arg.size() == 2) return END;
arg = string(arg, 2); //remove starting --
return LONG;
}
if (arg.size() > 2) {
cerr << "INVALID ARGUMENT " << arg << endl;
exit(1);
}
arg = string(arg, 1);
return SHORT;
}
string Options::str() {
return input;
}
void Options::init(int argc_, char** argv_) {
for (int i = 1; i < argc_; i++) {
cerr << i << " " << argv_[i] << endl;
argv.push_back(string(argv_[i]));
input += string(argv_[i]) + " ";
}
argv.push_back("--");
string last_option = "";
for (string arg : argv) {
option_type opttype = get_option_type(arg);
DEBUG << arg << " " << opttype << endl;
switch(opttype) {
case SHORT:
case LONG:
if (last_option != "") {
opts_map[last_option] = "";
}
last_option = arg;
break;
case ARG:
if (last_option == ""){
cerr << "ARGUMENT WITHOUT OPTION: " << arg << endl;
exit(1);
}
opts_map[last_option] = arg;
last_option = "";
break;
case END:
if (last_option != "") {
opts_map[last_option] = "";
}
}
}
DEBUG << "OPTIONS MAP:\n";
for (auto& kv : opts_map) {
DEBUG << kv.first << " = " << kv.second << endl;
}
inited = true;
}
int Options::get(string opts, string* arg) {
assert(inited);
stringstream ss(opts);
istream_iterator<std::string> begin(ss);
istream_iterator<std::string> end;
vector<string> vopts(begin, end);
for (auto& opt : vopts) {
if (opts_map.count(opt)) {
if (arg)
*arg = opts_map[opt];
return 1;
}
}
return 0;
// opterr = 0;
// struct option opts[] = {{ longopt.c_str(), optional_argument, 0, 0},
// { 0, 0, 0, 0}
// };
// int c;
// int option_index;
// string optstring = "-:";
// if (shortopt) {
// if (arg)
// optstring = ":" + string(&shortopt, 1) + ":";
// else
// optstring = ":" + string(&shortopt, 1) ;
// }
// while ((c = getopt_long(argc, argv, optstring.c_str(), &(opts[0]), &option_index)) != -1) {
// if (c == shortopt || c == 0 ) {
// if (arg && (size_t)optarg)
// *arg = string(optarg);
// optind = 1;
// return 1;
// cout << shortopt << " " << longopt << " " << arg << endl;
// }
// }
// optind = 1;
// return 0;
}
|
02ad0b429554eb40f822a4edc139800e69f0f102
|
f45847f670577df3b47dd3f3f18f31d2dafcab97
|
/Classes/Sprite/Enemy/Enemy02.cpp
|
2f5b1e72617568abb4faa63bf1b7a775ffb0d18b
|
[] |
no_license
|
noguchi999/shooting2
|
0aec3924158ef4375f4cc47c4bd1f3a82173f6be
|
35275a5b5496928b5bf564a0e60d24cf55a3d081
|
refs/heads/master
| 2016-09-06T03:22:28.928167
| 2014-02-23T06:13:41
| 2014-02-23T06:13:41
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,512
|
cpp
|
Enemy02.cpp
|
#include "Enemy02.h"
USING_NS_CC;
Enemy02::Enemy02()
{
score = 50;
}
Enemy02::~Enemy02()
{
}
const char* Enemy02::getImageFileName()
{
return "enemy02.png";
}
void Enemy02::update(float delta)
{
Enemy::update(delta);
if (getStatus() == Status::Captured)
{
auto target = getTarget();
if (getBoundingBox().containsPoint(target->getPosition()))
{
destroy();
}
else
{
captured();
}
}
}
void Enemy02::move()
{
}
void Enemy02::attack()
{
}
void Enemy02::attack(Point from, Point to)
{
}
void Enemy02::specialAttack()
{
}
void Enemy02::specialAttack(Point from, Point to)
{
}
void Enemy02::captured()
{
auto target = getTarget();
MoveTo* move = MoveTo::create(0.5f, target->getPosition());
ActionInterval* actionRotate = RotateBy::create(0.5f, 360);
auto spawn = Spawn::createWithTwoActions(actionRotate, move);
runAction(spawn);
}
void Enemy02::hurt(int power, BattleManager::SpecialEffect sp)
{
if (getStatus() == Status::Unbreakable)
{
return;
}
switch (sp)
{
case BattleManager::Capture:
setStatus(Status::Captured);
break;
default:
break;
}
}
void Enemy02::destroy()
{
removeFromParent();
auto reward_manager = RewardManager::getInstance();
reward_manager->setScore(reward_manager->getScore() + score);
}
|
f6c410c72c51dd4edb21648f87e9b09a091e2188
|
93f81597e6d8bfb69084d4a2f56a0420305103ea
|
/topcoder/SRM/0723/b.cc
|
594859c283230dcb6b3c2a3b83baf16cefa26fb4
|
[] |
no_license
|
himkt/problems.2019
|
94405abc8301ab60d6240219219cf741ce10827e
|
e2c9cda0199df37cc9cbac55ca10fe4092fa82d2
|
refs/heads/master
| 2022-11-26T03:49:46.262568
| 2020-08-03T14:29:57
| 2020-08-03T14:29:57
| 30,968,278
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 585
|
cc
|
b.cc
|
//#define _GRIBCXX_DEBUG
#include <bits/stdc++.h>
# define rep(i, n) for (int i = 0; i < (int)(n); i++)
using namespace std;
class TopXorerEasy {
public:
int maximalRating(int, int, int);
};
int TopXorerEasy::maximalRating(int A, int B, int C) {
int k = max(A, max(B, C));
int d = 0;
while(true) {
if (pow(2, d) > k) {
break;
}
d++;
}
int ans = 0;
while (d >= 0) {
ans += pow(2, d-1);
d--;
}
return ans;
};
int main() {
int a, b, c;
cin >> a >> b >> c;
cout << TopXorerEasy().maximalRating(a, b, c) << endl;
return 0;
}
|
0354a35d6f7f8cf79abbc19a48b134e3154f139f
|
30ef8f12fdd857ee56030ca22b240554e7c02406
|
/authwidget.h
|
89517ea83f9b315bb00aa6dc6814b6c8f4dd03c3
|
[] |
no_license
|
ypaaxx/Debtor
|
854be2748dd5206e2198a0189f8892f33d22acd9
|
f5b5b389f1fca521d5af8b0927a60781661ed1a0
|
refs/heads/master
| 2020-03-12T04:58:50.392060
| 2018-06-12T08:26:45
| 2018-06-12T08:26:45
| 130,455,136
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 223
|
h
|
authwidget.h
|
#ifndef AUTHWIDGET_H
#define AUTHWIDGET_H
#include <QWidget>
class AuthWidget : public QWidget
{
Q_OBJECT
public:
explicit AuthWidget(QWidget *parent = nullptr);
signals:
public slots:
};
#endif // AUTHWIDGET_H
|
d4963fa92e0712df03eb0de94b0356e5b7c98dc0
|
050c5121ae9240d3912f1529dd569f8c15e702f4
|
/include/file_systems/inode_system.h
|
65b66ce0425f18fd4e2a6c85e6c207a1ef694542
|
[] |
no_license
|
renantarouco/file_system
|
685deb09870b2f1d17f42df50ef53da928e3e5c9
|
8b573a4723ed789e9f66d81a35604e2459613e2d
|
refs/heads/master
| 2020-04-09T08:14:04.717489
| 2018-12-13T05:10:40
| 2018-12-13T05:10:40
| 160,186,759
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 593
|
h
|
inode_system.h
|
#include <file_systems/file_system.h>
#include <chrono>
class INodeSystem : public FileSystem {
private:
std::vector<int> _get_block_stream(int);
std::vector<int> _get_block_stream(std::vector<std::string> path, char file_type);
public:
INodeSystem();
INodeSystem(int, int);
bool mkdir(std::vector<std::string>);
bool cd(std::vector<std::string>);
std::vector<FileDescriptor> ls(std::vector<std::string>);
bool touch(std::vector<std::string>, int, std::string);
std::string cat(std::vector<std::string> path);
bool rm(std::vector<std::string> path);
};
|
0316c00b13620a7db57f26b570be6dc3bf0ca035
|
fedfa36451c39e7dbbbd34029634ab1c78ff4c25
|
/sequence2/Client/RegDialog.h
|
8d17cf8e24fadd1de0c6e6c9fff3756fec5a024d
|
[] |
no_license
|
DiceMaster/dudge
|
9532304a0a6ff0e77fd71101ef39c82b6d4f9969
|
a65f5cde671b63e22b07fe53026b8cfd047c5a8d
|
refs/heads/master
| 2021-05-16T03:19:51.511110
| 2016-11-20T18:25:10
| 2016-11-20T18:25:10
| 32,222,886
| 5
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 414
|
h
|
RegDialog.h
|
#pragma once
#include <windows.h>
#include <string>
class RegDialog
{
public:
RegDialog(HWND hParent);
~RegDialog();
bool ShowModal();
std::string GetLogin();
std::string GetPassword();
private:
static int WINAPI RegProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
private:
bool mbLoop;
HWND mDialog;
std::string mLogin;
std::string mPassword;
bool mResult;
};
|
bac541b1f5fc26e8a31552432e6e46ad03a01749
|
06bed8ad5fd60e5bba6297e9870a264bfa91a71d
|
/libPr3/Signal/virtualsignalmast.h
|
4a7171d5567634c7a649f6c11e848eeec1d077a9
|
[] |
no_license
|
allenck/DecoderPro_app
|
43aeb9561fe3fe9753684f7d6d76146097d78e88
|
226c7f245aeb6951528d970f773776d50ae2c1dc
|
refs/heads/master
| 2023-05-12T07:36:18.153909
| 2023-05-10T21:17:40
| 2023-05-10T21:17:40
| 61,044,197
| 4
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 760
|
h
|
virtualsignalmast.h
|
#ifndef VIRTUALSIGNALMAST_H
#define VIRTUALSIGNALMAST_H
#include "abstractsignalmast.h"
class LIBPR3SHARED_EXPORT VirtualSignalMast : public AbstractSignalMast
{
Q_OBJECT
public:
//explicit VirtualSignalMast(QObject *parent = 0);
/*public*/ VirtualSignalMast(QString systemName, QString userName = "", QObject *parent = 0) ;
// /*public*/ VirtualSignalMast(QString systemName) ;
void configureFromName(QString systemName) ;
/*public*/ void setAspect(QString aspect) override;
/*public*/ static int getLastRef();
/*public*/ QString className();
signals:
public slots:
private:
static int lastRef;// = 0;
Logger* log;
protected:
/*protected*/ static void setLastRef(int newVal);
};
#endif // VIRTUALSIGNALMAST_H
|
50ac168d4d95e40866d3fc63de2f1ab58a49481e
|
0dbfd5628e193b4a6ae1b61de9b8578c35678a2a
|
/MonsterChase/FloatHelperTest.cpp
|
800f46714f4144b6c37c579a457f8224f7058f7d
|
[] |
no_license
|
JerryZhangJingyi/MonsterChase
|
82eac09b47d5f16095d4a556739e50680cfe76e8
|
d67bffaa99c5b0aedeafa10a19b89118cefcef8a
|
refs/heads/main
| 2023-07-07T03:51:03.728452
| 2021-08-02T19:14:47
| 2021-08-02T19:14:47
| 392,064,139
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,024
|
cpp
|
FloatHelperTest.cpp
|
#include "FloatHelperTest.h"
#include <xlocinfo>
#include <windows.h>
void _FloatHelperTest::test()
{
const size_t lenBuffer = 65;
char Buffer[lenBuffer];
sprintf_s(Buffer, lenBuffer, "float test 1 %s\n", _FloatHelper::IsNaN(3.0f) ? "true" : "false"); //false
OutputDebugStringA(Buffer);
sprintf_s(Buffer, lenBuffer, "float test 2 %s\n", _FloatHelper::IsNaN(nanf("foo")) ? "true" : "false"); //true
OutputDebugStringA(Buffer);
sprintf_s(Buffer, lenBuffer, "float test 3 %s\n", _FloatHelper::AboutEqual(1.f, 2.f) ? "true" : "false"); //false
OutputDebugStringA(Buffer);
sprintf_s(Buffer, lenBuffer, "float test 4 %s\n", _FloatHelper::AboutEqual(1.f, 1.00001f) ? "true" : "false"); //true
OutputDebugStringA(Buffer);
sprintf_s(Buffer, lenBuffer, "float test 5 %s\n", _FloatHelper::IsZero(0.0001f) ? "true" : "false"); //false
OutputDebugStringA(Buffer);
sprintf_s(Buffer, lenBuffer, "float test 6 %s\n", _FloatHelper::IsZero(0.000000000000001f) ? "true" : "false"); //true
OutputDebugStringA(Buffer);
}
|
c29dd1f2bb12ce6d98262788c1f137951fe4c39d
|
e0c3ab98fd1c1afb4f1ffe1ea649c9a0df084c63
|
/ZephyrSharp.Input/JoyStick.h
|
9218a8ad465efd173f9f36f5ee406db132c25f58
|
[] |
no_license
|
s059ff/ZephyrEngine
|
6b9e28fb3cb0f8d90e0cba73b758c33ce77a0137
|
b484258119ecff0f51a785fa02e9c4d4594ddf2a
|
refs/heads/master
| 2020-03-22T14:20:23.452845
| 2018-07-08T23:44:42
| 2018-07-08T23:44:42
| 110,549,395
| 0
| 0
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 3,659
|
h
|
JoyStick.h
|
#pragma once
#include "common.h"
#include "ButtonState.h"
namespace ZephyrSharp
{
namespace Input
{
/// <summary>
/// ジョイスティックコントローラを表します。
/// </summary>
public ref class JoyStick
: public INativeWrapper<zephyr::input::JoyStick>
{
public:
/// <summary>
/// デバイスの状態を更新します。このメソッドは毎フレーム呼び出す必要があります。
/// </summary>
void Update()
{
Native->Update();
}
/// <summary>
/// ボタンの状態を取得します。
/// </summary>
/// <param name="id">ボタンの ID 。</param>
ButtonState GetButtonState(int id)
{
return (ButtonState)Native->GetButtonState(id);
}
/// <summary>
/// ボタンの状態を取得します。
/// </summary>
property ButtonState default[int]
{
ButtonState get(int id) { return this->GetButtonState(id); }
}
public:
/// <summary>
/// アナログスティック第 1 軸の X 軸の値を取得します。
/// </summary>
property double AxisX { double get() { return Native->AxisX; } }
/// <summary>
/// アナログスティック第 1 軸の Y 軸の値を取得します。
/// </summary>
property double AxisY { double get() { return Native->AxisY; } }
/// <summary>
/// アナログスティック第 2 軸の X 軸の値を取得します。
/// </summary>
property double SubAxisX { double get() { return Native->SubAxisX; } }
/// <summary>
/// アナログスティック第 2 軸の Y 軸の値を取得します。
/// </summary>
property double SubAxisY { double get() { return Native->SubAxisY; } }
/// <summary>
/// POV スイッチの左方向のボタンの状態を取得します。
/// </summary>
property ButtonState Left { ButtonState get() { return (ButtonState)Native->Left; } }
/// <summary>
/// POV スイッチの右方向のボタンの状態を取得します。
/// </summary>
property ButtonState Right { ButtonState get() { return (ButtonState)Native->Right; } }
/// <summary>
/// POV スイッチの上方向のボタンの状態を取得します。
/// </summary>
property ButtonState Up { ButtonState get() { return (ButtonState)Native->Up; } }
/// <summary>
/// POV スイッチの下方向のボタンの状態を取得します。
/// </summary>
property ButtonState Down { ButtonState get() { return (ButtonState)Native->Down; } }
/// <summary>
/// コントローラが接続されているか調べます。
/// </summary>
property bool IsConnected { bool get() { return Native->IsConnected; } }
/// <summary>
/// アナログスティックのデッドゾーンの大きさを 0 から 1 の範囲で指定します。
/// </summary>
property double DeadZone
{
double get() { return Native->DeadZone; }
void set(double value) { Native->DeadZone = value; }
}
};
}
}
|
0cc30dfd92b3c6f55f41732d1bad82f3ad89f38f
|
12d705b7bfa7f49e058049dc2ffae93b8f7c6b4a
|
/Engine/OpenSceneGraph-3.4.1/src/osgPlugins/rbm/DataInputStream.h
|
bc2b98fe5bb7e09cb4060f451707d04f070bdef7
|
[] |
no_license
|
lzjee147/osg
|
1a23a48aae8fec8e2f92351ecc83b005a4c446ab
|
53004ed58f4a7d8e12d286e920cdab4b48bab042
|
refs/heads/master
| 2020-09-21T23:26:05.475842
| 2019-11-25T13:42:49
| 2019-11-25T13:42:49
| 224,970,980
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,564
|
h
|
DataInputStream.h
|
#ifndef IVE_DATAINPUTSTREAM
#define IVE_DATAINPUTSTREAM 1
#include <iostream> // for ifstream
#include <string>
#include <map>
#include <vector>
#include <osgGe/Vec2>
#include <osgGe/Vec3>
#include <osgGe/Vec4>
#include <osgGe/Vec2d>
#include <osgGe/Vec3d>
#include <osgGe/Vec4d>
#include <osg/Quat>
#include <osg/Array>
#include <osg/Matrix>
#include <osg/Image>
#include <osg/Geometry>
#include <osg/StateSet>
#include <osg/Uniform>
#include <osg/ref_ptr>
#include <osgTerrain/TerrainTile>
#include <osgVolume/VolumeTile>
#include <osgDB/ReaderWriter>
#include "Exception.h"
#include "DataTypeSize.h"
#include "IveVersion.h"
namespace ive{
class DataInputStream{
public:
DataInputStream(std::istream* istream, const osgDB::ReaderWriter::Options* options);
~DataInputStream();
const osgDB::ReaderWriter::Options* getOptions() const { return _options.get(); }
inline unsigned int getVersion() const { return _version; }
bool readBool();
char readChar();
unsigned char readUChar();
unsigned short readUShort();
unsigned int readUInt();
int readInt();
int peekInt();
float readFloat();
long readLong();
unsigned long readULong();
double readDouble();
std::string readString();
void readCharArray(char* data, int size);
osg::Vec2 readVec2();
osg::Vec3 readVec3();
osg::Vec4 readVec4();
osg::Vec2d readVec2d();
osg::Vec3d readVec3d();
osg::Vec4d readVec4d();
osg::Plane readPlane();
osg::Vec4ub readVec4ub();
osg::Quat readQuat();
osg::Matrixf readMatrixf();
osg::Matrixd readMatrixd();
deprecated_osg::Geometry::AttributeBinding readBinding();
osg::Array* readArray();
osg::IntArray* readIntArray();
osg::UByteArray* readUByteArray();
osg::UShortArray* readUShortArray();
osg::UIntArray* readUIntArray();
osg::Vec4ubArray* readVec4ubArray();
bool readPackedFloatArray(osg::FloatArray* floatArray);
osg::FloatArray* readFloatArray();
osg::Vec2Array* readVec2Array();
osg::Vec3Array* readVec3Array();
osg::Vec4Array* readVec4Array();
osg::Vec2bArray* readVec2bArray();
osg::Vec3bArray* readVec3bArray();
osg::Vec4bArray* readVec4bArray();
osg::Vec2sArray* readVec2sArray();
osg::Vec3sArray* readVec3sArray();
osg::Vec4sArray* readVec4sArray();
osg::Vec2dArray* readVec2dArray();
osg::Vec3dArray* readVec3dArray();
osg::Vec4dArray* readVec4dArray();
osg::Image* readImage(std::string s);
osg::Image* readImage(IncludeImageMode mode);
osg::Image* readImage();
osg::Object* readObject(){ return NULL;};
osg::StateSet* readStateSet();
osg::StateAttribute* readStateAttribute();
osg::Uniform* readUniform();
osg::Shader* readShader();
osg::Drawable* readDrawable();
osg::Shape* readShape();
osg::Node* readNode();
osgTerrain::Layer* readLayer();
osgTerrain::Locator* readLocator();
osgVolume::Layer* readVolumeLayer();
osgVolume::Locator* readVolumeLocator();
osgVolume::Property* readVolumeProperty();
// Set and get if must be generated external reference ive files
void setLoadExternalReferenceFiles(bool b) {_loadExternalReferenceFiles=b;};
bool getLoadExternalReferenceFiles() {return _loadExternalReferenceFiles;};
typedef std::map<std::string, osg::ref_ptr<osg::Image> > ImageMap;
typedef std::map<int,osg::ref_ptr<osg::StateSet> > StateSetMap;
typedef std::map<int,osg::ref_ptr<osg::StateAttribute> > StateAttributeMap;
typedef std::map<int,osg::ref_ptr<osg::Uniform> > UniformMap;
typedef std::map<int,osg::ref_ptr<osg::Shader> > ShaderMap;
typedef std::map<int,osg::ref_ptr<osg::Drawable> > DrawableMap;
typedef std::map<int,osg::ref_ptr<osg::Shape> > ShapeMap;
typedef std::map<int,osg::ref_ptr<osg::Node> > NodeMap;
typedef std::map<int,osg::ref_ptr<osgTerrain::Layer> > LayerMap;
typedef std::map<int,osg::ref_ptr<osgTerrain::Locator> > LocatorMap;
typedef std::map<int,osg::ref_ptr<osgVolume::Layer> > VolumeLayerMap;
typedef std::map<int,osg::ref_ptr<osgVolume::Locator> > VolumeLocatorMap;
typedef std::map<int,osg::ref_ptr<osgVolume::Property> > VolumePropertyMap;
bool _verboseOutput;
std::istream* _istream;
int _byteswap;
bool _owns_istream;
bool uncompress(std::istream& fin, std::string& destination) const;
void throwException(const std::string& message) { _exception = new Exception(message); }
void throwException(Exception* exception) { _exception = exception; }
const Exception* getException() const { return _exception.get(); }
private:
int _version;
bool _peeking;
int _peekValue;
ImageMap _imageMap;
StateSetMap _statesetMap;
StateAttributeMap _stateAttributeMap;
UniformMap _uniformMap;
ShaderMap _shaderMap;
DrawableMap _drawableMap;
ShapeMap _shapeMap;
NodeMap _nodeMap;
LayerMap _layerMap;
LocatorMap _locatorMap;
VolumeLayerMap _volumeLayerMap;
VolumeLocatorMap _volumeLocatorMap;
VolumePropertyMap _volumePropertyMap;
bool _loadExternalReferenceFiles;
osg::ref_ptr<const osgDB::ReaderWriter::Options> _options;
osg::ref_ptr<Exception> _exception;
};
}
#endif // IVE_DATAINPUTSTREAM
|
937410e42c56d517eeb8e5611815c8cfc088b3dd
|
3f157e39c9d90fc0dfbfcb4e0e36641fd99a9a75
|
/ccc/44_files.cpp
|
a496515098fc2d67738e160522f2a35f37405963
|
[
"BSD-3-Clause"
] |
permissive
|
admantium-sg/learning-cpp
|
87ce5528ce059fca45a8037b5de8f4f5deb4b4f4
|
cc827a8d7eabceac32069bb7f5a64b3c0fe488f4
|
refs/heads/main
| 2023-04-22T00:27:23.851983
| 2021-03-21T08:39:40
| 2021-03-21T08:39:40
| 349,941,441
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,004
|
cpp
|
44_files.cpp
|
/*
* ---------------------------------------
* Copyright (c) Sebastian Günther 2021 |
* |
* devcon@admantium.com |
* |
* SPDX-License-Identifier: BSD-3-Clause |
* ---------------------------------------
*/
#include <stdio.h>
#include <stdexcept>
#include <iostream>
#include <cstddef>
#include <filesystem>
#include <iomanip>
using namespace std;
using namespace std::filesystem;
int main(int argc, char* argv[]) {
cout << "Number of args: " << argc << endl;
for (int i=0; i < argc; i++) {
cout << "Arg " << i << ": " << argv[i] << endl;
}
path local{"./"};
cout << "Listing files in DIR '" << local.string() << "'" << endl;
for (auto item : directory_iterator{local}) {
if (item.is_directory()) {
cout << " .*" << endl;
} else {
cout << item.path().filename().string() << " :: " << item.file_size() << " byte" << endl;
}
}
cout << "Goodbye!";
}
|
e6533b9fef5398fc2df60e88479a58feb8766242
|
18919b4e9708ae890c2efc6f7c987f2a88218406
|
/dune/stuff/test/grid_walker.cc
|
dde3285f730f99e4d64dc71dde9b01053baadb54
|
[
"BSD-2-Clause"
] |
permissive
|
BarbaraV/dune-stuff
|
7aab5165475708b42ef159d3dde838b790705656
|
f6297fed873f5e640354508eb927c875b60724a9
|
refs/heads/master
| 2021-01-15T09:24:15.852069
| 2018-02-21T15:06:59
| 2018-02-21T15:06:59
| 35,220,334
| 0
| 0
| null | 2015-05-07T13:02:58
| 2015-05-07T13:02:58
| null |
UTF-8
|
C++
| false
| false
| 3,303
|
cc
|
grid_walker.cc
|
// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#include "main.hxx"
#if HAVE_DUNE_GRID
# include <dune/stuff/grid/walker.hh>
# include <dune/stuff/grid/provider/cube.hh>
# include <dune/stuff/common/parallel/partitioner.hh>
# include <dune/stuff/common/logstreams.hh>
# if DUNE_VERSION_NEWER(DUNE_COMMON,3,9) && HAVE_TBB // EXADUNE
# include <dune/grid/utility/partitioning/seedlist.hh>
# endif
using namespace Dune::Stuff;
using namespace Dune::Stuff::Common;
using namespace Dune::Stuff::Grid;
using namespace std;
typedef testing::Types< Int<1>, Int<2>, Int<3> > GridDims;
template < class T >
struct GridWalkerTest : public ::testing::Test
{
static const size_t griddim = T::value;
static const size_t level = 4;
typedef Dune::YaspGrid<griddim> GridType;
typedef typename GridType::LeafGridView GridViewType;
typedef typename DSG::Entity< GridViewType >::Type EntityType;
typedef typename DSG::Intersection< GridViewType >::Type IntersectionType;
const DSG::Providers::Cube<GridType> grid_prv;
GridWalkerTest()
:grid_prv(0.f,1.f,level)
{}
void check_count() {
const auto gv = grid_prv.grid().leafGridView();
Walker<GridViewType> walker(gv);
const auto correct_size = gv.size(0);
atomic<size_t> count(0);
auto counter = [&](const EntityType&){count++;};
auto test1 = [&]{ walker.add(counter); walker.walk(false); };
auto test2 = [&]{ walker.add(counter); walker.walk(true); };
list<function<void()>> tests({ test1, test2 });
# if DUNE_VERSION_NEWER(DUNE_COMMON,3,9) // EXADUNE
auto test3 = [&]{
IndexSetPartitioner<GridViewType> partitioner(gv.grid().leafIndexSet());
Dune::SeedListPartitioning<GridType, 0> partitioning(gv, partitioner);
walker.add(counter);
walker.walk(partitioning);
};
tests.push_back(test3);
# endif // DUNE_VERSION_NEWER(DUNE_COMMON,3,9) // EXADUNE
for (const auto& test : tests) {
count = 0;
test();
EXPECT_EQ(count, correct_size);
}
}
void check_apply_on() {
const auto gv = grid_prv.grid().leafGridView();
Walker<GridViewType> walker(gv);
size_t filter_count = 0, all_count = 0;
auto boundaries = [=](const GridViewType&, const IntersectionType& inter){return inter.boundary();};
auto filter_counter = [&](const IntersectionType&, const EntityType&, const EntityType&){filter_count++;};
auto all_counter = [&](const IntersectionType&, const EntityType&, const EntityType&){all_count++;};
auto on_filter_boundaries = new DSG::ApplyOn::FilteredIntersections<GridViewType>(boundaries);
auto on_all_boundaries = new DSG::ApplyOn::BoundaryIntersections<GridViewType>();
walker.add(filter_counter, on_filter_boundaries);
walker.add(all_counter, on_all_boundaries);
walker.walk();
EXPECT_EQ(filter_count, all_count);
}
};
TYPED_TEST_CASE(GridWalkerTest, GridDims);
TYPED_TEST(GridWalkerTest, Misc) {
this->check_count();
this->check_apply_on();
}
# else // HAVE_DUNE_GRID
TEST(DISABLED_GridWalkerTest, Misc) {};
# endif // HAVE_DUNE_GRID
|
9775faa0f41a79a3348c9f1d19eeec89daec4017
|
788cfa8d89ab6f8aacd84fb5587ae41aeef33e44
|
/src/benchmark.cpp
|
334bef289f58155c0a64cb35f7a7a68226835287
|
[
"LicenseRef-scancode-boost-original",
"MIT",
"BSL-1.0"
] |
permissive
|
vgteam/vg
|
5064ca0996db9c54c9642cc4d63d2fef2cefcdb0
|
e173d0a81c6aa0e5b93a863f19b73ee4200177dc
|
refs/heads/master
| 2023-08-31T04:08:13.862938
| 2023-08-25T00:35:47
| 2023-08-25T00:35:47
| 24,727,800
| 886
| 202
|
NOASSERTION
| 2023-09-08T11:33:30
| 2014-10-02T16:54:27
|
C++
|
UTF-8
|
C++
| false
| false
| 6,478
|
cpp
|
benchmark.cpp
|
#include "benchmark.hpp"
#include <vector>
#include <iostream>
#include <cassert>
#include <numeric>
#include <cmath>
#include <iomanip>
/**
* \file benchmark.hpp: implementations of benchmarking functions
*/
namespace vg {
using namespace std;
double BenchmarkResult::score() const {
// We comnpute a score in points by comparing the experimental and control runtimes.
// Higher is better.
// How many tests can we run per control run?
double tests_per_control = (double)control_mean.count() / (double)test_mean.count();
return tests_per_control * 1000;
}
double BenchmarkResult::score_error() const {
// Do error propagation for the score calculation
// Set up some abstract variables according to the notation at
// <https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas>
double A = control_mean.count();
double stddev_A = control_stddev.count();
double B = test_mean.count();
double stddev_B = test_stddev.count();
double f = score() / 1000;
// Do the error propagation
// Assume the variables are uncorrelated (covariance = 0)
// Not because that's really true but because we don't track the covariance
double err = abs(f) * sqrt(pow(stddev_A / A, 2) + pow(stddev_B / B, 2));
// Scale up because of scaling factor on the score.
return err * 1000;
}
ostream& operator<<(ostream& out, const BenchmarkResult& result) {
// Dump it as a partial TSV line
// We want to report times in fractional us
using frac_secs = chrono::duration<double, std::micro>;
// Save stream settings
auto initial_precision = out.precision();
auto initial_flags = out.flags();
// Set up formatting
cout << setprecision(2) << scientific;
out << result.runs;
out << "\t";
out << chrono::duration_cast<frac_secs>(result.test_mean).count();
out << "\t";
out << chrono::duration_cast<frac_secs>(result.test_stddev).count();
out << "\t";
out << chrono::duration_cast<frac_secs>(result.control_mean).count();
out << "\t";
out << chrono::duration_cast<frac_secs>(result.control_stddev).count();
out << "\t";
// Scores get different formatting
cout << fixed;
out << result.score();
out << "\t";
out << result.score_error();
out << "\t";
out << result.name;
out.precision(initial_precision);
out.flags(initial_flags);
return out;
}
void benchmark_control() {
// We need to do something that takes time.
vector<size_t> things;
for (size_t i = 0; i < 100; i++) {
things.push_back(i ^ (i/5));
}
size_t max_thing = 0;
for (auto& thing : things) {
for (auto& other_thing : things) {
max_thing = max(max_thing, max(thing, other_thing));
other_thing = other_thing ^ (thing << 5);
}
}
size_t total = 0;
for (auto& thing : things) {
total += thing;
}
// These are the results of that arbitrary math
assert(max_thing == 18444166782598024656U);
assert(total == 17868247911721767448U);
}
BenchmarkResult run_benchmark(const string& name, size_t iterations, const function<void(void)>& under_test) {
return run_benchmark(name, iterations, []() {}, under_test);
}
BenchmarkResult run_benchmark(const string& name, size_t iterations, const function<void(void)>& setup,
const function<void(void)>& under_test) {
// We'll fill this in with the results of the benchmark run
BenchmarkResult to_return;
to_return.runs = iterations;
to_return.name = name;
// Where do we put our test runtime samples?
// They need to be normal integral types so we can feasibly square them.
vector<benchtime::rep> test_samples;
// And the samples for the control?
vector<benchtime::rep> control_samples;
// We know how big they will be
test_samples.reserve(iterations);
control_samples.reserve(iterations);
for (size_t i = 0; i < iterations; i++) {
// For each iteration
// Run the setup function
setup();
// Run the function under test
auto test_start = chrono::high_resolution_clock::now();
under_test();
auto test_stop = chrono::high_resolution_clock::now();
// And run the control
auto control_start = chrono::high_resolution_clock::now();
benchmark_control();
auto control_stop = chrono::high_resolution_clock::now();
// Make sure time went forward and nobody changed the clock (as far as we know)
assert(test_stop > test_start);
assert(control_stop > control_start);
// Compute the runtimes and save them
test_samples.push_back(chrono::duration_cast<benchtime>(test_stop - test_start).count());
control_samples.push_back(chrono::duration_cast<benchtime>(control_stop - control_start).count());
}
// Calculate the moments with magic numeric algorithms
// See <https://stackoverflow.com/a/7616783>
// Total up the ticks for the test
benchtime::rep test_total = accumulate(test_samples.begin(), test_samples.end(),
benchtime::zero().count());
// And make a duration for the mean
to_return.test_mean = benchtime(test_total / iterations);
// Then total up the squares of the tick counts
benchtime::rep test_square_total = inner_product(test_samples.begin(), test_samples.end(),
test_samples.begin(), benchtime::zero().count());
// Calculate the standard deviation in ticks, and represent it as a duration
to_return.test_stddev = benchtime((benchtime::rep) sqrt(test_square_total / iterations -
to_return.test_mean.count() * to_return.test_mean.count()));
// Similarly for the control
benchtime::rep control_total = accumulate(control_samples.begin(), control_samples.end(),
benchtime::zero().count());
to_return.control_mean = benchtime(control_total / iterations);
benchtime::rep control_square_total = inner_product(control_samples.begin(), control_samples.end(),
control_samples.begin(), benchtime::zero().count());
to_return.control_stddev = benchtime((benchtime::rep) sqrt(control_square_total / iterations -
to_return.control_mean.count() * to_return.control_mean.count()));
return to_return;
}
}
|
92a90ec6f0f57b3886c678f70697f4ee0ba934fd
|
46fda2ea47f311ee7fefc6f6210811c7f4bd74ad
|
/databases/mysql-connector-odbc/files/patch-driver_dll.cc
|
b69ce6b9e812f934b9d5e6ab273b9b749afa8794
|
[
"BSD-2-Clause"
] |
permissive
|
truenas/ports
|
ad560a8adde884dc0cfc4b292bbbcad91903b287
|
da4ed13ad08a6af5c54361f45964fa1177367c68
|
refs/heads/truenas/13.0-stable
| 2023-09-02T03:00:28.652837
| 2023-08-16T16:05:00
| 2023-08-16T16:05:00
| 8,656,293
| 18
| 9
|
NOASSERTION
| 2023-09-12T15:15:34
| 2013-03-08T17:35:37
| null |
UTF-8
|
C++
| false
| false
| 327
|
cc
|
patch-driver_dll.cc
|
--- driver/dll.cc.orig 2019-04-15 16:56:34 UTC
+++ driver/dll.cc
@@ -125,7 +125,7 @@ void myodbc_end()
This eliminates the delay when mysys_end() is called and other threads
have been initialized but not ended.
*/
- my_thread_end_wait_time= 0;
+ static uint my_thread_end_wait_time= 0;
#endif
/*
|
0193f2fa7e6f7964e1837f6bd1763ff275d82234
|
c1e10ac7a355a39067954918d62dc5f28df3f8f8
|
/tutorial/ruud_van_der_pass_openmp/04_omp_methods/10_omp_get_wtime.cpp
|
518643a807af63b728a727ec7ea662674a5636f5
|
[] |
no_license
|
grayasm/git-main
|
be46c568c3b9edcfe9d583bac8aba1302932b0d1
|
88ef1393b241383a75ade3e8677238536fe95afa
|
refs/heads/master
| 2023-08-05T03:49:36.674748
| 2023-08-03T14:57:55
| 2023-08-03T14:57:55
| 32,255,990
| 12
| 5
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,028
|
cpp
|
10_omp_get_wtime.cpp
|
/* double omp_get_wtime(void);
Elapsed wall clock time in seconds. The time is measured per thread,
no guarantee can be made that two distinct threads measure the same time.
Time is measured from some "time in the past", which is an arbitrary time
guaranteed not to change during the execution of the program.
*/
#include <stdio.h>
#include <omp.h>
#ifdef WIN32
#include <windows.h>
#define sleep(a) Sleep(a*1000)
#else //linux
#include <unistd.h>
#endif //WIN32
int main(int argc, char** argv)
{
double start = omp_get_wtime ();
sleep (1);
double end = omp_get_wtime ();
double wtick = omp_get_wtick ();
printf ("start = %.16g\n"
"end = %.16g\n"
"diff = %.16g\n",
start, end, end - start);
printf ("wtick = %.16g\n"
"1/wtick = %.16g\n",
wtick, 1.0/wtick);
return 0;
}
/*
$> ./10_omp_get_wtime
start = 31352.738506449
end = 31353.738726453
diff = 1.000220003999857
wtick = 1e-09
1/wtick = 999999999.9999999
*/
|
055b952467c7592d39c5de91d21528ffe5bb2a19
|
8715867ccf09f502a6725b80355042ea99008bae
|
/[C++] Freelance/FREELANCE6/OB4/OB4/Source.cpp
|
3634f455f1e4b1592ed45820d138c8f773491af5
|
[] |
no_license
|
MaxRev-Dev/My-Labs
|
0ef1f07313e0eb5bd23ce01c2bd012ed389858d8
|
0ac8c7570985701606fe65277ad58c7590895912
|
refs/heads/master
| 2022-12-11T12:04:45.121156
| 2021-11-05T02:18:20
| 2021-11-05T02:18:20
| 148,040,090
| 0
| 0
| null | 2022-12-08T01:16:43
| 2018-09-09T15:42:32
|
C++
|
UTF-8
|
C++
| false
| false
| 609
|
cpp
|
Source.cpp
|
#include <iostream>
#include <Windows.h>
#include <algorithm>
#include <string>
#include <conio.h>
using namespace std;
int main() {
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
string str;
cout << "Введіть текст (АБ): ";
getline(cin, str);
size_t n1 = count(str.begin(), str.end(), 'А'); // просто функція пошуку з algorithm
cout << "Входжень А в тексті - "<<n1;
size_t n2 = count(str.begin(), str.end(), 'Б');
cout << "\nВходжень Б в тексті - "<<n2<<endl;
cout << (n1 > n2 ? "TRUE" : "FALSE") << endl;
_getch();
return 0;
}
|
09bebc0865fab7ae7bf782a50561dbe242ae1ad6
|
ea4edc2884fc719b201663c853bf4ba921ad640a
|
/source/wrapper/WrapperCo.h
|
b03c5c35518a51be6687146efb54bfb9dd876765
|
[
"MIT"
] |
permissive
|
Jde-cpp/MarketLibrary
|
69b55be9b5b4860d505dadc2d750140f1a9c9879
|
bd4b68a0106a92b7b2e0864b8e0b9aedf1772791
|
refs/heads/master
| 2022-08-13T14:58:13.891313
| 2022-08-01T09:11:27
| 2022-08-01T09:11:27
| 218,258,652
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,772
|
h
|
WrapperCo.h
|
#include <jde/markets/Exports.h>
#include "../../../Framework/source/coroutine/Coroutine.h"
#include "./WrapperLog.h"
#include "../../../Framework/source/collections/UnorderedMapValue.h"
//#include <jde/markets/types/proto/results.pb.h>
namespace Jde::Markets
{
struct Contract;struct TwsClientCo; struct HistoryAwait; struct HistoricalNewsAwait; struct ContractAwait; struct NewsProviderAwait; struct NewsArticleAwait; struct SecDefOptParamAwait; struct AccountsAwait; struct PlaceOrderAwait; struct HeadTimestampAwait;
using namespace Jde::Coroutine;
#define $ noexcept->void override
struct ΓM WrapperCo : WrapperLog
{
α error2( int id, int errorCode, str errorMsg )noexcept->bool override;
α error( int id, int errorCode, str errorMsg, str advancedOrderRejectJson )$;
α headTimestamp( int reqId, str headTimestamp )$;
α historicalNews( int requestId, str time, str providerCode, str articleId, str headline )$;
α historicalNewsEnd( int requestId, bool hasMore )$;
α historicalData( TickerId reqId, const ::Bar& bar )$;
α historicalDataEnd( int reqId, str startDateStr, str endDateStr )$;
α contractDetails( int reqId, const ::ContractDetails& contractDetails )$;
α contractDetailsEnd( int reqId )$;
α managedAccounts( str accountsList )$;
α newsProviders( const vector<NewsProvider>& providers )$;
α newsArticle( int reqId, int articleType, str articleText )$;
α securityDefinitionOptionalParameter( int reqId, str exchange, int underlyingConId, str tradingClass, str multiplier, const std::set<std::string>& expirations, const std::set<double>& strikes )$;
α securityDefinitionOptionalParameterEnd( int reqId )$;
α OpenOrder( ::OrderId orderId, const ::Contract& contract, const ::Order& order, const ::OrderState& state )noexcept->sp<Proto::Results::OpenOrder>;
protected:
flat_map<ReqId,up<vector<sp<::ContractDetails>>>> _requestContracts; UnorderedMapValue<ReqId,HCoroutine> _contractHandles;
private:
flat_map<int,up<Proto::Results::NewsCollection>> _news;UnorderedMapValue<int,HCoroutine> _newsHandles;
UnorderedSet<HCoroutine> _newsProviderHandles;
UnorderedMapValue<int,HCoroutine> _newsArticleHandles;
flat_map<ReqId,sp<Proto::Results::OptionExchanges>> _optionParams; UnorderedMapValue<ReqId,HCoroutine> _secDefOptParamHandles;
UnorderedMapValue<int,HistoryAwait*> _historical;
HCoroutine _accountHandle;
UnorderedMapValue<::OrderId,HCoroutine> _orderHandles;
UnorderedMapValue<ReqId,HCoroutine> _headTimestampHandles;
friend TwsClientCo; friend HistoricalNewsAwait; friend ContractAwait; friend NewsProviderAwait; friend NewsArticleAwait; friend HistoryAwait; friend SecDefOptParamAwait; friend AccountsAwait; friend PlaceOrderAwait; friend HeadTimestampAwait;
};
}
#undef $
|
ff15c45d15cbf2056c688dada8351a8ce3c04df3
|
56a4cb943d085a672f8b0d08a8c047f772e6a45e
|
/code/Johnson_Engine/Runtime/world_particle_blocker_data.h
|
b4389aa9310de67ed931a838be57863e92139bbc
|
[] |
no_license
|
robertveloso/suddenattack_legacy
|
2016fa21640d9a97227337ac8b2513af7b0ce00b
|
05ff49cced2ba651c25c18379fed156c58a577d7
|
refs/heads/master
| 2022-06-20T05:00:10.375695
| 2020-05-08T01:46:02
| 2020-05-08T01:46:02
| 262,199,345
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 790
|
h
|
world_particle_blocker_data.h
|
//////////////////////////////////////////////////////////////////////////////
// Polygons that block particle movement.
#ifndef __WORLD_PARTICLE_BLOCKER_DATA_H__
#define __WORLD_PARTICLE_BLOCKER_DATA_H__
#include "ltmodule.h"
#include "loadstatus.h"
#include <vector>
class IWorldParticleBlockerData : public IBase
{
public:
interface_version(IWorldParticleBlockerData, 0);
virtual ~IWorldParticleBlockerData() {};
virtual void Term() = 0;
virtual ELoadWorldStatus Load(ILTStream *pStream) = 0;
virtual bool GetBlockersInAABB( const LTVector& pos, const LTVector& dims, std::vector<uint32>& indices ) = 0;
virtual bool GetBlockerEdgesXZ( uint32 index, LTPlane& blockerPlane, uint32& numEdges, LTPlane*& edgePlanes ) = 0;
};
#endif //__WORLD_PARTICLE_BLOCKER_DATA_H__
|
0b4d8959310983ce1f3eddb65e260fbf31b89b33
|
1fe464d4a0e50caa0314307a41eda5a618e08027
|
/brianna-and-yu-ambient-telepresence.ino
|
1a16549bf9ae2ffb69d19fbac83aa9ae8ed68c14
|
[] |
no_license
|
Jyu0927/Triangular-Walking-Sensor
|
12fc3e1da8f7b0341cfbc3d1bccd9116a0df396b
|
6a1607067e49169982e176132998dca4519a2277
|
refs/heads/main
| 2023-01-09T00:12:59.800098
| 2020-10-31T16:36:06
| 2020-10-31T16:36:06
| 308,925,443
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,901
|
ino
|
brianna-and-yu-ambient-telepresence.ino
|
#include <Servo.h>
//================================================================
// Hardware definitions. You will need to customize this for your specific hardware.
const int SONAR_TRIGGER_PIN = 8; // Specify a pin for a sonar trigger output.
const int SONAR_ECHO_PIN = 7; // Specify a pin for a sonar echo input.
const int SERVO_PIN = 9;
const int base = 100;
int last_value = -1;
Servo svo;
int servoMapValue = 0;
//================================================================
// Set the serial port transmission rate. The baud rate is the number of bits
// per second.
const long BAUD_RATE = 115200;
//================================================================
// This function is called once after reset to initialize the program.
void setup()
{
// Initialize the Serial port for host communication.
Serial.begin(BAUD_RATE);
// Initialize the digital input/output pins. You will need to customize this
// for your specific hardware.
pinMode(SONAR_TRIGGER_PIN, OUTPUT);
pinMode(SONAR_ECHO_PIN, INPUT);
svo.attach(SERVO_PIN);
}
//================================================================
// This function is called repeatedly to handle all I/O and periodic processing.
// This loop should never be allowed to stall or block so that all tasks can be
// constantly serviced.
void loop()
{
serial_input_poll();
hardware_input_poll();
}
//================================================================
// Polling function to process messages received over the serial port from the
// remote Arduino. Each message is a line of text containing a single integer
// as text.
void serial_input_poll(void)
{
while (Serial.available()) {
// When serial data is available, process and interpret the available text.
// This may be customized for your particular hardware.
// The default implementation assumes the line contains a single integer
// which controls the built-in LED state.
int value = Serial.parseInt();
if (last_value == -1) {
last_value = value;
} else if (abs(value-last_value) > 25) {
value = last_value;
} else {
last_value = value;
}
int MapValue = value + base;
int increment = 2;
int servoMoveValue = 0;
int original_pos = svo.read();
// Drive the servo to the value read in.
if (MapValue > original_pos){
while (((svo.read() + increment) <= MapValue) & (servoMoveValue < MapValue - original_pos)){
servoMoveValue += increment;
//delay(10);
svo.write(servoMoveValue + original_pos);
}
}
else{
while ((svo.read() - increment) >= MapValue & (servoMoveValue < original_pos - MapValue)){
servoMoveValue -= increment;
//delay(10);
svo.write(servoMoveValue + original_pos);
}
}
// Once all expected values are processed, flush any remaining characters
// until the line end. Note that when using the Arduino IDE Serial Monitor,
// you may need to set the line ending selector to Newline.
Serial.find('\n');
}
}
//================================================================
// Polling function to read the inputs and transmit data whenever needed.
void hardware_input_poll(void)
{
// Calculate the interval in milliseconds since the last polling cycle.
static unsigned long last_time = 0;
unsigned long now = millis();
unsigned long interval = now - last_time;
last_time = now;
// Poll each hardware device. Each function returns true if the input has
// been updated. Each function directly updates the global output state
// variables as per your specific hardware. The input_changed flag will be
// true if any of the polling functions return true (a logical OR using ||).
bool input_changed = (poll_sonar(interval));
// Update the message timer used to guarantee a minimum message rate.
static long message_timer = 0;
message_timer -= interval;
// If either the input changed or the message timer expires, retransmit to the network.
if (input_changed || (message_timer < 0)) {
message_timer = 1000; // one second timeout to guarantee a minimum message rate
transmit_packet();
}
}
//================================================================
// Poll the sonar at regular intervals.
bool poll_sonar(unsigned long interval)
{
static long sonar_timer = 0;
sonar_timer -= interval;
if (sonar_timer < 0) {
sonar_timer = 250; // 4 Hz sampling rate
// Generate a short trigger pulse.
digitalWrite(SONAR_TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(SONAR_TRIGGER_PIN, LOW);
// Measure the echo pulse length. The ~6 ms timeout is chosen for a maximum
// range of 100 cm assuming sound travels at 340 meters/sec. With a round
// trip of 2 meters distance, the maximum ping time is 2/340 = 0.0059
// seconds. You may wish to customize this for your particular hardware.
const unsigned long TIMEOUT = 5900;
unsigned long ping_time = pulseIn(SONAR_ECHO_PIN, HIGH, TIMEOUT);
// The default implementation only updates the data if a ping was observed,
// the no-ping condition is ignored.
if (ping_time > 0) {
// Update the data output and indicate a change.
servoMapValue = map(ping_time, 0, TIMEOUT, 2, 178);
if (servoMapValue > 100) {
servoMapValue = 100;
}
int MapValue = servoMapValue + base;
int increment = 2;
int servoMoveValue = 0;
int original_pos = svo.read();
/*while (svo.read() < servoMapValue + base) {
svo.write(svo.read() + increment + base);
delay(200);
}*/
if (MapValue > original_pos){
while (((svo.read() + increment) <= MapValue) & (servoMoveValue < MapValue - original_pos)){
servoMoveValue += increment;
//Serial.print("move up ");
delay(100);
svo.write(servoMoveValue + original_pos);
//Serial.println(servoMoveValue);
//Serial.println(svo.read());
}
}
else{
while ((svo.read() - increment) >= MapValue & (servoMoveValue < original_pos - MapValue)){
servoMoveValue -= increment;
//Serial.print("move down ");
delay(100);
svo.write(servoMoveValue + original_pos);
//Serial.println(servoMoveValue);
//Serial.println(svo.read());
}
}
return true;
}
}
return false; // No change in state.
}
//================================================================
// Send the current data to the MQTT server over the serial port. The values
// are clamped to the legal range using constrain().
void transmit_packet(void)
{
if (servoMapValue > 100) {
Serial.println(100);
} else {
Serial.println(servoMapValue);
}
}
//================================================================
|
a74be62d110eab000adb3656d4fe8eb22913b8f0
|
9a4b0866d77722718576a37bb97fa50c725b9b79
|
/ConnectedComponents.cpp
|
d20021d906f538674d52af218aceae4f969f0220
|
[] |
no_license
|
kartikeya72001/GraphsCpp
|
149da0f409bec86d2ed6ad72f03652beb77b8fc0
|
0edc93b2e77286180df6cabe7966cf85e2ebf518
|
refs/heads/master
| 2022-12-28T09:39:24.844309
| 2020-10-15T11:34:51
| 2020-10-15T11:34:51
| 262,566,092
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,229
|
cpp
|
ConnectedComponents.cpp
|
#include <iostream>
#include<queue>
#include<map>
#include<list>
using namespace std;
template<typename T>
class Graph{
map<T,list<T>> l;
public:
void addEdge(T x, T y)
{
l[x].push_back(y);
l[y].push_back(x);
}
void dfshelper(T src, map<T,bool> &visited){
cout<<src<<" ";
visited[src] = true;
for(T nbr:l[src])
{
if(!visited[nbr])
{
dfshelper(nbr,visited);
}
}
}
void dfs()
{
map<T,bool> visited;
for(auto x:l){
T node = x.first;
visited[node] = false;
}
//Iterating all over
int cnt = 0;
for(auto p:l)
{
T node = p.first;
if(!visited[node])
{
cout<<"Component: "<<cnt<<" --> ";
dfshelper(node,visited);
cnt++;
cout<<endl;
}
}
}
};
int main(int argc, char const *argv[]) {
Graph<int> g;
g.addEdge(0,1);
g.addEdge(1,2);
g.addEdge(0,4);
g.addEdge(0,3);
g.addEdge(2,3);
g.addEdge(5,6);
g.addEdge(6,7);
g.addEdge(8,8);
g.dfs();
return 0;
}
|
13f2d4f99233d941f9fc993859e99e7643d937b0
|
8b04e0aad840452c0a674e62f21060289bed0b9c
|
/src/core/config.hpp
|
7916c3a028809deda606cc78a8b485003c3fc2a8
|
[
"MIT",
"BSL-1.0"
] |
permissive
|
bradosia/BookFiler-Module-HTTP
|
220a2ab085037654e8fa90f6f47cbff13992dfc2
|
7a4b81badb32391a9f640babd676cdf81d6e1f39
|
refs/heads/main
| 2023-01-22T06:43:58.959804
| 2020-11-29T16:08:52
| 2020-11-29T16:08:52
| 302,550,989
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 960
|
hpp
|
config.hpp
|
/*
* @name BookFiler Module - HTTP w/ Curl
* @author Branden Lee
* @version 1.00
* @license MIT
* @brief HTTP module for BookFiler™ applications.
*/
#ifndef BOOKFILER_MODULE_HTTP_CONFIG_H
#define BOOKFILER_MODULE_HTTP_CONFIG_H
#define HTTPS_GET_JSON_DEBUG 1
#define HTTPS_GET_JSON_ENABLE 1
#define BOOKFILER_HTTP_CLIENT_END_DEBUG_RESPONSE 1
#define BOOKFILER_HTTP_CLIENT_CLIENT_DEBUG_URL 1
#define RSA_KEY_LENGTH 2048
#define BOOKFILER_MODULE_HTTP_BOOST_BEAST_EXPOSE 1
// boost
#define BOOST_ALLOW_DEPRECATED_HEADERS
#include <string>
namespace bookfiler {
namespace HTTP {
static std::string moduleName = "BookFiler Module HTTP";
static std::string moduleCode = "bookfiler::HTTP";
} // namespace HTTP
namespace certificate {
static std::string moduleName = "BookFiler Module Certificate";
static std::string moduleCode = "bookfiler::certificate";
} // namespace certificate
} // namespace bookfiler
#endif // BOOKFILER_MODULE_HTTP_CONFIG_H
|
db4bea7762c1b551f920f8346faf5d0d8cb2933a
|
ffea6219dc14e6515c199acb4fbb84db0cd65225
|
/autonomous.cpp
|
d11b38f232e919d1abc7e1b131ce55b92717fb13
|
[] |
no_license
|
Andrew929H/Competition12-7
|
cdcaf382390f98663bc5d95e450fe423b624dc96
|
c8d362a00c3dd2b9f93d609a06ec6ef9bf10e09c
|
refs/heads/master
| 2020-04-10T08:19:49.180941
| 2018-12-08T04:19:07
| 2018-12-08T04:19:07
| 160,903,244
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,867
|
cpp
|
autonomous.cpp
|
#include "main.h"
#include "globals.h"
#include <cmath>
#include "okapi/api.hpp"
using namespace okapi;
inline int auton = 0;
pros::Motor intake(3, true);
pros::Motor indexRoller(5, true);
pros::Motor flywheel(9, true);
pros::Motor descore(11);
pros::Motor rightFront(19, true);
pros::Motor rightRear(20, true);
pros::Motor leftFront(1);
pros::Motor leftRear(2);
Rate rate;
auto chassis = ChassisControllerFactory::create({1,2}, {-19, -20}, AbstractMotor::gearset::green, {4_in, 12.5_in});
void forwardsTime(double speed, QTime time){
leftRear.move_velocity(speed);
leftFront.move_velocity(speed);
rightFront.move_velocity(speed);
rightRear.move_velocity(speed);
rate.delayUntil(time);
leftRear.move_velocity(0);
leftFront.move_velocity(0);
rightFront.move_velocity(0);
rightRear.move_velocity(0);
}
void autonomous() {
switch(auton){
//RED FLAGS AUTON
case 0:
//set chassis speed
chassis.setMaxVelocity(100);
//run intake
intake.move_velocity(200);
//move chassis forwards
chassis.moveDistance(43_in);
//wait then reverse slightly
intake.move_velocity(0);
flywheel.move_velocity(200);
chassis.moveDistance(-38_in);
chassis.turnAngle(-90.0_deg);
pros::delay(750);
indexRoller.move_velocity(200);
pros::delay(500);
indexRoller.move_velocity(0);
chassis.moveDistance(31_in);
pros::delay(500);
intake.move_velocity(200);
indexRoller.move_velocity(200);
pros::delay(1000);
chassis.turnAngle(-8_deg);
chassis.setMaxVelocity(200);
chassis.moveDistance(18);
flywheel.move_velocity(0);
break;
//BLUE FLAGS AUTON
case 1:
//set chassis speed
chassis.setMaxVelocity(100);
//run intake
intake.move_velocity(200);
//move chassis forwards
chassis.moveDistance(43_in);
//wait then reverse slightly
intake.move_velocity(0);
flywheel.move_velocity(200);
chassis.moveDistance(-38_in);
chassis.turnAngle(90.0_deg);
pros::delay(750);
indexRoller.move_velocity(200);
pros::delay(500);
indexRoller.move_velocity(0);
chassis.moveDistance(31_in);
pros::delay(500);
intake.move_velocity(200);
indexRoller.move_velocity(200);
pros::delay(1000);
chassis.turnAngle(8_deg);
chassis.setMaxVelocity(200);
chassis.moveDistance(18);
flywheel.move_velocity(0);
break;
//RED PARKING AUTON
case 2:
//set chassis speed
chassis.setMaxVelocity(100);
//run intake
intake.move_velocity(200);
//move chassis forwards
chassis.moveDistance(43_in);
//wait then reverse slightly
rate.delayUntil(750_ms);
intake.move_velocity(0);
chassis.moveDistance(-5_in);
rate.delayUntil(750_ms);
chassis.turnAngle(90.0_deg);
rate.delayUntil(750_ms);
chassis.moveDistance(-30_in);
break;
//BLUE PARK AUTON
case 3:
//set chassis speed
chassis.setMaxVelocity(100);
//run intake
intake.move_velocity(200);
//move chassis forwards
chassis.moveDistance(43_in);
//wait then reverse slightly
rate.delayUntil(750_ms);
intake.move_velocity(0);
chassis.moveDistance(-5_in);
rate.delayUntil(750_ms);
chassis.turnAngle(-90.0_deg);
rate.delayUntil(750_ms);
chassis.moveDistance(-30_in);
break;
//SKILLS AUTON
case 4:
//Move forwards to get ball and come back
chassis.setMaxVelocity(110);
intake.move_velocity(200);
flywheel.move_velocity(200);
chassis.moveDistance(48.5_in);
intake.move_velocity(0);
chassis.moveDistance(-38_in);
//Line up with wall and turn
forwardsTime(-50,2000_ms);
chassis.moveDistance(8);
rate.delayUntil(750_ms);
chassis.turnAngle(-90.0_deg);
rate.delayUntil(750_ms);
break;
}
}
|
4248b3ec2db952f4cd9d9815999dc845e3fac1e1
|
599d32cdc9dbd15806b0e7d2bb77e8fd904b5caf
|
/c++/0076.cpp
|
b608c1ff31590a41492d491f473a365d45040e4d
|
[] |
no_license
|
maximusyoung007/LeetCode
|
03776bc6191864469a9a30a391cf49a909b9b9a8
|
fe4a6186d4e039c271efda0ddb05965bdde1f172
|
refs/heads/master
| 2023-07-15T23:21:05.796959
| 2023-07-02T15:18:12
| 2023-07-02T15:18:12
| 176,424,589
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,634
|
cpp
|
0076.cpp
|
#include<string>
#include<vector>
#include<map>
using namespace std;
class Solution0076 {
public:
string minWindow(string s, string t) {
if(s == "" || t == "") return "";
if(s.size() < t.size()) return "";
if(s == t) return s;
int left = 0, right = 0, minLeft = 0, minRight = 0;
int min = s.size() + 1;
map<char,int> m1;
int count = t.size();
for(int i = 0; i < t.size(); i++) {
if(m1.count(t[i]) == 0) {
m1[t[i]] = 1;
}
else if(m1.count(t[i]) > 0) {
m1[t[i]] += 1;
}
}
while(right < s.size()) {
if (m1.count(s[right]) > 0) {
if (m1[s[right]] > 0) {
m1[s[right]]--;
count--;
} else if (m1[s[right]] <= 0) {
m1[s[right]]--;
}
}
right++;
//如果当前符合,开始动左下标
while (count == 0) {
if(right - left < min) {
minLeft = left;
minRight = right;
min = right - left;
}
if(m1.count(s[left]) > 0) {
if(m1[s[left]] < 0) {
m1[s[left]]++;
} else if(m1[s[left]] >= 0) {
m1[s[left]]++;
count++;
}
}
left++;
}
}
string result = s.substr(minLeft, minRight - minLeft);
return result;
}
};
|
67f8796edfaaba39036fa7e607a41d301954f102
|
d9aa48b214225ea3f2e39234a0d7859678ddb83a
|
/serial/serial.h
|
0aaed23ffaffe571a5630283ae061c2ddb2f886c
|
[] |
no_license
|
Spuu/QRfpClient
|
142e90c83fa6c163273d4cf21f6caf70e46f01b6
|
79ac59bdd5f44e6053cf454ab4bc93aad23d59df
|
refs/heads/master
| 2021-01-12T12:06:43.520491
| 2016-11-08T17:46:47
| 2016-11-08T17:46:47
| 72,303,495
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 789
|
h
|
serial.h
|
#ifndef SERIAL_H
#define SERIAL_H
#include <QByteArray>
namespace Serial {
enum RESULT {
SUCCESS,
FAIL
};
enum PACKET {
ENQ = 0x05,
ACK = 0x06,
NAK = 0x15,
STX = 0x02,
ETX = 0x03,
ETB = 0x17,
EOT = 0x04,
WACK = 0x09,
RVI = 0x40
};
class IPacketHandler {
public:
virtual char handleData(const QByteArray&) = 0;
};
class IPacket
{
public:
virtual QByteArray getData() const = 0;
virtual void setResult(RESULT result);
private:
RESULT result_ = FAIL;
};
QByteArray CalcCrc(const QByteArray& ba);
QByteArray CalcCrc(const char *str,int len);
QByteArray createSerialPacket(PACKET p);
}
#endif // SERIAL_H
|
799b080d659fc82e898f660479fc8cdc0d31ccd8
|
4d625beedb31d9a19c57cf892dd501ef126f6c9c
|
/ros_controllers/joint_trajectory_controller/test/joint_trajectory_controller_adapter_test.cpp
|
8ae6a4fd8003f30ac1f805d1229f2188aa1fe6ca
|
[] |
no_license
|
CureThomas/Palbator_simulation
|
f65d31ef6aed28436a7aaf79eee6157a3d261c89
|
42748e47a03ea3a40593b0b43908bb7b239c7ed7
|
refs/heads/master
| 2023-04-03T23:46:33.977864
| 2020-07-16T08:55:35
| 2020-07-16T08:55:35
| 261,386,414
| 0
| 3
| null | 2021-04-06T13:14:42
| 2020-05-05T07:14:25
|
C++
|
UTF-8
|
C++
| false
| false
| 2,262
|
cpp
|
joint_trajectory_controller_adapter_test.cpp
|
/*
* Copyright 2020 PAL Robotics SL. All Rights Reserved
*
* Unauthorized copying of this file, via any medium is strictly prohibited,
* unless it was supplied under the terms of a license agreement or
* nondisclosure agreement with PAL Robotics SL. In this case it may not be
* copied or disclosed except in accordance with the terms of that agreement.
*/
/** \author Sai Kishor Kothakota **/
#include <gtest/gtest.h>
#include <ros/node_handle.h>
#include <joint_trajectory_controller/joint_trajectory_controller.h>
#include <trajectory_interface/quintic_spline_segment.h>
TEST(JointTrajectoryControllerTest, CustomAdapterTest)
{
joint_trajectory_controller::JointTrajectoryController<
trajectory_interface::QuinticSplineSegment<double>,
hardware_interface::EffortJointInterface, hardware_interface::EffortJointInterface>
effort_trajectory_adapter;
joint_trajectory_controller::JointTrajectoryController<
trajectory_interface::QuinticSplineSegment<double>, hardware_interface::EffortJointInterface>
effort_trajectory_no_adapter;
// Not recommended in real scenario, but used here for testing purpose
joint_trajectory_controller::JointTrajectoryController<
trajectory_interface::QuinticSplineSegment<double>,
hardware_interface::EffortJointInterface, hardware_interface::PositionJointInterface>
effort_trajectory_position_adapter;
joint_trajectory_controller::JointTrajectoryController<
trajectory_interface::QuinticSplineSegment<double>,
hardware_interface::PositionJointInterface, hardware_interface::EffortJointInterface>
position_trajectory_effort_adapter;
ros::NodeHandle nh, pnh;
hardware_interface::EffortJointInterface effort_int;
hardware_interface::PositionJointInterface pos_int;
ASSERT_NO_THROW(effort_trajectory_adapter.init(&effort_int, nh, pnh));
ASSERT_NO_THROW(effort_trajectory_no_adapter.init(&effort_int, nh, pnh));
ASSERT_NO_THROW(effort_trajectory_position_adapter.init(&effort_int, nh, pnh));
ASSERT_NO_THROW(position_trajectory_effort_adapter.init(&pos_int, nh, pnh));
}
int main(int argc, char *argv[])
{
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "joint_trajectory_controller_test");
return RUN_ALL_TESTS();
}
|
1c63ca32f56a5cec39a37c134b2e7393cbba5d1a
|
279324a6c345135f77f718ca0af4fc4f1ea7e6e8
|
/src/exceptions/Exception.h
|
c071c8a8d17a653f47158b16698fdb5d5951f0d5
|
[] |
no_license
|
latufla/BRenderer
|
8ec47be04cf73978c76d5a005f5dbde1dce4712e
|
7b890f1ab7ef87c22f6eee1db4b3f49eeca903c7
|
refs/heads/master
| 2021-01-01T06:04:47.030970
| 2015-02-27T09:46:38
| 2015-02-27T12:56:11
| 26,016,340
| 6
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,750
|
h
|
Exception.h
|
#pragma once
#include "../utils/SharedHeaders.h"
#define EXCEPTION_INFO __FUNCTION__,__LINE__
namespace br {
class Exception : public std::exception {
public:
Exception(std::string func, uint32_t line, std::string reason) : func(func), line(line), reason(reason) {}
~Exception() = default;
virtual std::string msg() const {
return func + "(" + std::to_string(line) + "): " + what() + " " + reason;
};
protected:
std::string func;
uint32_t line;
std::string reason;
};
class WeakPtrException : public Exception {
public:
WeakPtrException(std::string func, uint32_t line) : Exception(func, line, "") {}
~WeakPtrException() = default;
const char* what() const override {
return "WeakPtrException";
}
};
class NativeWindowException : public Exception {
public:
NativeWindowException(std::string func, uint32_t line, std::string reason)
: Exception(func, line, reason) {
}
~NativeWindowException() = default;
const char* what() const override {
return "NativeWindowException";
}
};
class EglException : public Exception {
public:
EglException(std::string func, uint32_t line, std::string reason)
: Exception(func, line, reason) {
}
~EglException() = default;
const char* what() const override {
return "EglException";
}
};
class ShaderException : public Exception {
public:
ShaderException(std::string func, uint32_t line, std::string reason)
: Exception(func, line, reason) {
}
~ShaderException() = default;
const char* what() const override {
return "ShaderException";
}
};
class InvalidObjectIdException : public Exception {
public:
InvalidObjectIdException(std::string func, uint32_t line, uint32_t objId)
: Exception(func, line, "id: " + std::to_string(objId)) {
}
~InvalidObjectIdException() = default;
const char* what() const override {
return "InvalidObjectIdException";
}
};
class AssetException : public Exception {
public:
AssetException(std::string func, uint32_t line, std::string path, std::string reason)
: Exception(func, line, "path: " + path + " " + reason) {
}
~AssetException() = default;
const char* what() const override {
return "AssetException";
}
};
class GpuException : public Exception {
public:
GpuException(std::string func, uint32_t line, std::string reason)
: Exception(func, line, reason) {
}
~GpuException() = default;
const char* what() const override {
return "GpuException";
}
};
class LogicException : public Exception {
public:
LogicException(std::string func, uint32_t line, std::string reason)
: Exception(func, line, reason) {
}
~LogicException() = default;
const char* what() const override {
return "LogicException";
}
};
}
|
118ca6e13878f2ac8762fe992b428327fe4f0dac
|
1dca551611e643f5692f726f6f3e90c6c00eb7f7
|
/DatabaseBrowser/Views/memoryviewcontrol.h
|
fd33bd012a0b882df30822d595dd3f863a153df4
|
[
"MIT"
] |
permissive
|
HowCanidothis/DevLib
|
d47b977dfa01999e4fd8f26cad7ef2c9c77471fa
|
58fb0fa099cc6cb5f58ad2e8481bc4ca3758cdfb
|
refs/heads/master
| 2023-08-22T21:21:47.705274
| 2023-08-16T09:41:32
| 2023-08-21T15:40:18
| 282,774,252
| 0
| 1
|
MIT
| 2022-12-22T05:17:14
| 2020-07-27T02:23:37
|
C++
|
UTF-8
|
C++
| false
| false
| 553
|
h
|
memoryviewcontrol.h
|
#ifndef MEMORYVIEWCONTROL_H
#define MEMORYVIEWCONTROL_H
#include <QWidget>
#include <PropertiesModule/internal.hpp>
namespace Ui {
class MemoryViewControl;
}
class MemoryViewControl : public QWidget
{
Q_OBJECT
public:
explicit MemoryViewControl(QWidget *parent = nullptr);
~MemoryViewControl();
public Q_SLOTS:
void AboutToBeReset();
void Reset();
private:
Ui::MemoryViewControl *ui;
PointerPropertyPtr<class DbDatabase> m_currentDatabase;
class ModelMemoryTree* model() const;
};
#endif // MEMORYVIEWCONTROL_H
|
558b68117b056abf7d7dea24b8fdb447bbd28b3f
|
fa82a6fe381ebf75f3b107d8d53bb25e3821f5b8
|
/system/include/s_system_files.h
|
3cf56d2cb6d102046aa20d4e27a13ed88a8f7454
|
[] |
no_license
|
motriuc/sasha-noob-engine
|
30a005b2c45cdfe41124cd6bfc93447c31e2760d
|
91266dda425f533667568bca4eba7315daa357ed
|
refs/heads/master
| 2016-09-06T14:36:58.961996
| 2013-11-02T20:54:03
| 2013-11-02T20:54:03
| 33,181,907
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 865
|
h
|
s_system_files.h
|
/////////////////////////////////////////////////////////////////////
// File Name : s_system_files.h
// Created : 28 6 2007 17:25
// File path : SLibF\system\Include
// Author : Alexandru Motriuc
// Platform Independent : 0%
// Library :
//
/////////////////////////////////////////////////////////////////////
// Purpose:
//
//
/////////////////////////////////////////////////////////////////////
//
// Modification History:
//
/////////////////////////////////////////////////////////////////////
#ifndef _SYSTEM_FILES_INC_
#define _SYSTEM_FILES_INC_
/**
* File namespace
*/
namespace Files
{
using namespace Types;
#include "s_system_files_lfile.h"
#include "s_system_files_error.h"
#include "s_system_files_name.h"
}
#endif // _SYSTEM_FILES_INC_
|
53044749e077926829117b1a212cee8a1d5ca7dd
|
cae0243512e1614fc9ef945713c9499d1a56d389
|
/src/packing/posl_uncoder.h
|
0ff5224aff705ade66a214986eaf4cab561eb0ed
|
[] |
no_license
|
alejandro-reyesamaro/POSL
|
15b5b58a9649234fa9bedbca4393550d38a69e7d
|
0b3b7cf01a0392fc76394bbc04c52070637b3009
|
refs/heads/master
| 2021-04-15T11:10:24.998562
| 2016-09-06T15:10:54
| 2016-09-06T15:10:54
| 33,991,084
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 760
|
h
|
posl_uncoder.h
|
#pragma once
#include "../solver/posl_solver.h"
#include "../tools/hash_map.h"
#include "../connections/connections_declaration.h"
class PoslUncoder
{
public:
PoslUncoder();
HashMap<std::string, std::shared_ptr<POSL_Solver> > uncode_declarations(std::vector<std::string> code,
std::shared_ptr<Benchmark> bench);//,
//shared_ptr<SearchProcessParamsStruct> psp_params);
std::vector<ConnectionsDeclaration> uncode_connections(std::string code);
//std::vector<std::shared_ptr<POSL_Solver>> uncode_declarations(std::string code, std::shared_ptr<Benchmark> bench);
};
|
9b096e562791b18f0ade0d9959f0d2be01014d24
|
f98e3c238ecf5ee0281c2b26cc122455cf8ab810
|
/src/common/utilFunction.h
|
26c2a6c9588f5123e74e9211e4d3d42818d04d08
|
[
"Apache-2.0"
] |
permissive
|
Wlain/rasterizer
|
2130f9579bd36bf5535bd62490e1ff94cc91267c
|
5fc3f377b3afadd52467da46976824a7f5e809b9
|
refs/heads/master
| 2023-04-18T18:46:51.059520
| 2021-05-07T14:27:04
| 2021-05-07T14:27:04
| 363,450,632
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 587
|
h
|
utilFunction.h
|
//
// Created by william on 2021/5/4.
//
#ifndef RASTERIZER_UTILFUNCTION_H
#define RASTERIZER_UTILFUNCTION_H
#include "commonDefine.h"
#include "vector3.h"
#include "vector4.h"
#define MATRIX_SIZE (sizeof(float) * 16)
/**
* 判断当前点是否在三角形内部
* @param point 当前点坐标
* @param vertexes 三角形顶点坐标
* @param barycentricCoord 重心坐标
* @return
*/
bool insideTriangle(const rasterizer::Vector3& point, const std::vector<rasterizer::Vector4>& vertexes, std::vector<float>& barycentricCoord);
#endif //RASTERIZER_UTILFUNCTION_H
|
aa4fc80d2e019ce8ae3d5c7dcae4d3a14e1ac8c0
|
bed3ac926beac0f4e0293303d7b2a6031ee476c9
|
/Modules/Filtering/DistanceMap/test/itkApproximateSignedDistanceMapImageFilterTest.cxx
|
48afee17b8659bd40c8a3150dae0972fc02f0e76
|
[
"IJG",
"Zlib",
"LicenseRef-scancode-proprietary-license",
"SMLNJ",
"BSD-3-Clause",
"BSD-4.3TAHOE",
"LicenseRef-scancode-free-unknown",
"Spencer-86",
"LicenseRef-scancode-llnl",
"FSFUL",
"Libpng",
"libtiff",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-hdf5",
"MIT",
"NTP",
"LicenseRef-scancode-mit-old-style",
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"MPL-2.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] |
permissive
|
InsightSoftwareConsortium/ITK
|
ed9dbbc5b8b3f7511f007c0fc0eebb3ad37b88eb
|
3eb8fd7cdfbc5ac2d0c2e5e776848a4cbab3d7e1
|
refs/heads/master
| 2023-08-31T17:21:47.754304
| 2023-08-31T00:58:51
| 2023-08-31T14:12:21
| 800,928
| 1,229
| 656
|
Apache-2.0
| 2023-09-14T17:54:00
| 2010-07-27T15:48:04
|
C++
|
UTF-8
|
C++
| false
| false
| 5,798
|
cxx
|
itkApproximateSignedDistanceMapImageFilterTest.cxx
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkApproximateSignedDistanceMapImageFilter.h"
#include "itkShiftScaleImageFilter.h"
#include "itkImageFileWriter.h"
#include "itkNumericTraits.h"
#include "itkTestingMacros.h"
// Anonymous namespace
namespace
{
// Simple signed distance function
template <typename TPoint>
double
SimpleSignedDistance(const TPoint & p)
{
TPoint center;
center.Fill(32);
double radius = 16;
double accum = 0.0;
for (unsigned int j = 0; j < TPoint::PointDimension; ++j)
{
accum += itk::Math::sqr(p[j] - center[j]);
}
accum = std::sqrt(accum);
return (accum - radius);
}
} // namespace
int
itkApproximateSignedDistanceMapImageFilterTest(int argc, char * argv[])
{
if (argc < 3)
{
std::cerr << "Missing parameters" << std::endl;
std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " insideValue outputImage" << std::endl;
return EXIT_FAILURE;
}
constexpr unsigned int ImageDimension = 2;
using InputPixelType = unsigned int;
using OutputPixelType = float;
using WriterPixelType = short;
using PointPixelType = double;
using InputImageType = itk::Image<InputPixelType, ImageDimension>;
using OutputImageType = itk::Image<OutputPixelType, ImageDimension>;
using WriterImageType = itk::Image<WriterPixelType, ImageDimension>;
using PointType = itk::Point<PointPixelType, ImageDimension>;
// Make a binary input image based on the signed distance function
// using the inside and outside values
const InputPixelType insideValue = std::stoi(argv[1]);
constexpr InputPixelType outsideValue = 0;
auto image = InputImageType::New();
InputImageType::SizeType size;
size.Fill(64);
InputImageType::RegionType region(size);
image->SetRegions(region);
image->Allocate();
using InputIteratorType = itk::ImageRegionIteratorWithIndex<InputImageType>;
InputIteratorType iter(image, region);
iter.GoToBegin();
while (!iter.IsAtEnd())
{
PointType point;
image->TransformIndexToPhysicalPoint(iter.GetIndex(), point);
iter.Set(SimpleSignedDistance(point) > 0 ? outsideValue : insideValue);
++iter;
}
// Set up the filter
using DistanceMapFilterType = itk::ApproximateSignedDistanceMapImageFilter<InputImageType, OutputImageType>;
auto signedDistanceMapFilter = DistanceMapFilterType::New();
ITK_EXERCISE_BASIC_OBJECT_METHODS(
signedDistanceMapFilter, ApproximateSignedDistanceMapImageFilter, ImageToImageFilter);
signedDistanceMapFilter->SetInput(image);
signedDistanceMapFilter->SetInsideValue(insideValue);
ITK_TEST_SET_GET_VALUE(insideValue, signedDistanceMapFilter->GetInsideValue());
signedDistanceMapFilter->SetOutsideValue(outsideValue);
ITK_TEST_SET_GET_VALUE(outsideValue, signedDistanceMapFilter->GetOutsideValue());
ITK_TRY_EXPECT_NO_EXCEPTION(signedDistanceMapFilter->Update());
// Write the output image
using RescaleFilterType = itk::ShiftScaleImageFilter<OutputImageType, WriterImageType>;
auto rescaler = RescaleFilterType::New();
rescaler->SetInput(signedDistanceMapFilter->GetOutput());
rescaler->SetScale(1000);
ITK_TRY_EXPECT_NO_EXCEPTION(rescaler->Update());
if (rescaler->GetUnderflowCount() + rescaler->GetOverflowCount() > 0)
{
std::cerr << "Test failed!" << std::endl;
std::cerr << "Under-/overflow when scaling distances before writing distance map to disc: " << std::endl
<< "Underflow: " << rescaler->GetUnderflowCount() << std::endl
<< "Overflow: " << rescaler->GetOverflowCount() << std::endl;
return EXIT_FAILURE;
}
using WriterType = itk::ImageFileWriter<WriterImageType>;
auto writer = WriterType::New();
writer->SetInput(rescaler->GetOutput());
writer->SetFileName(argv[2]);
ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update());
OutputPixelType maxDistance = 0;
using OutputIteratorType = itk::ImageRegionConstIteratorWithIndex<OutputImageType>;
OutputIteratorType oIt(signedDistanceMapFilter->GetOutput(),
signedDistanceMapFilter->GetOutput()->GetLargestPossibleRegion());
oIt.GoToBegin();
while (!oIt.IsAtEnd())
{
PointType point;
image->TransformIndexToPhysicalPoint(oIt.GetIndex(), point);
OutputPixelType distance = itk::Math::abs(oIt.Get() - SimpleSignedDistance(point));
if (distance > maxDistance)
{
maxDistance = distance;
}
++oIt;
}
// Regression test
OutputPixelType maxAllowedDistance = 2;
if (maxDistance > maxAllowedDistance)
{
std::cout << "Test failed!" << std::endl;
std::cout << "The output image had pixels too far away from the correct distance." << std::endl;
std::cout << "The maximum error was: " << static_cast<itk::NumericTraits<OutputPixelType>::PrintType>(maxDistance)
<< std::endl;
std::cout << "The maximum allowed error is: "
<< static_cast<itk::NumericTraits<OutputPixelType>::PrintType>(maxAllowedDistance) << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed" << std::endl;
return EXIT_SUCCESS;
}
|
2e029ec7999322897f556ad78425568ec2331465
|
8b2fcb4cc471e9c6c45052cb381b2d66d85f8415
|
/State_Design/State.cpp
|
2f4ecbd0e29f944dca58ae80790c32eb89d49fb6
|
[] |
no_license
|
mrwangcheng/DesignPatterns
|
7de2fdc327727ca3f48faa57303c5ef41332c582
|
f6c778b8b2237de3c37d988b9ff701a1e80053d7
|
refs/heads/master
| 2020-04-05T17:17:15.177463
| 2019-06-16T16:21:06
| 2019-06-16T16:21:06
| 157,053,188
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,081
|
cpp
|
State.cpp
|
#include "stdafx.h"
#include "State.h"
#include "ContextEx.h"
#include <iostream>
using namespace std;
State::State()
{
}
State::~State()
{
}
void State::OperationInterface(ContextEx* con)
{
cout << "State::.." << endl;
}
bool State::ChangeState(ContextEx* con, State* st)
{
con->ChangeState(st);
return true;
}
void State::OperationChangeState(ContextEx* con)
{
}
ConcreteStateA::ConcreteStateA()
{
}
ConcreteStateA::~ConcreteStateA()
{
}
void ConcreteStateA::OperationInterface(ContextEx* con)
{
cout << "ConcreteStateA::OperationInterface......" << endl;
}
void ConcreteStateA::OperationChangeState(ContextEx* con)
{
OperationInterface(con);
this->ChangeState(con, new ConcreteStateB());
}
ConcreteStateB::ConcreteStateB()
{
}
ConcreteStateB::~ConcreteStateB()
{
}
void ConcreteStateB::OperationInterface(ContextEx* con)
{
cout << "ConcreteStateB::OperationInterface......" << endl;
}
void ConcreteStateB::OperationChangeState(ContextEx* con)
{
OperationInterface(con);
this->ChangeState(con, new ConcreteStateA());
}
|
6ba34ba43fdf146fd77840b7b2c7bcd708e347e6
|
fb6251837c15a0ee0b28b15d214599165e11de83
|
/Algorithms and Data Structures/pollard_rho.cpp
|
a6b7699a5edb40b156397fe9691a63f5d7bfbaf2
|
[] |
no_license
|
CDPS/Competitive-Programming
|
de72288b8dc02ca2a45ed40491ce1839e983b765
|
24c046cbde7fea04a6c0f22518a688faf7521e2e
|
refs/heads/master
| 2023-08-09T09:57:15.368959
| 2023-08-05T00:44:41
| 2023-08-05T00:44:41
| 104,966,014
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,053
|
cpp
|
pollard_rho.cpp
|
#include <bits/stdc++.h>
using namespace std;
const int rounds=10;
typedef unsigned long long ull;
typedef long long ll;
ll gcd(ll a, ll b) {
if(b==0) return a;
else return gcd(b,a%b);
}
ll mul(ull a, ull b, ull mod) {
ull ret = 0;
for (a %= mod, b %= mod; b != 0; b >>= 1, a <<= 1, a = a >= mod ? a - mod : a) {
if (b&1) {
ret += a;
if (ret >= mod) ret -= mod;
}
}
return ret;
}
ll powm(ll a,ll b,ll c){
ll ans = 1;
while (b > 0) {
if (b & 1)
ans = mul(ans, a, c);
a = mul(a, a, c);
b >>= 1;
}
return ans;
}
bool witness(ll a,ll n){
ll u=n-1;
ll t=0;
if(n==a) return true;
while(u%2==0){ t++; u>>=1; }
ll next = powm(a,u,n);
if(next==1 )return false;
ll last;
for(int i=0;i<t;i++){
last = next;
next = mul(last, last,n);
if(next==1){
return last != n-1;
}
}
return next !=1;
}
bool miller_rabin(ull n, int it= rounds){
if (n <= 1) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
for (int i = 0; i < it; ++i) {
ll a = rand() % (n - 1) + 1;
if (witness(a, n)) {
return false;
}
}
return true;
}
ll pollard_rho(ll n){
ll x, y, i = 1, k = 2, d;
x = y = rand() % n;
while (1) {
++i;
x = mul(x, x, n);
x += 2;
if (x >= n) x -= n;
if (x == y) return 1;
d = gcd(abs(x - y), n);
if (d != 1) return d;
if (i == k) {
y = x;
k *= 2;
}
}
return 1;
}
vector<ll> factorize(ll n) {
vector<ll> ans;
if (n == 1)
return ans;
if (miller_rabin(n)) {
ans.push_back(n);
} else {
ull d = 1ull;
while (d == 1)
d = pollard_rho(n);
vector<ll> dd = factorize(d);
ans = factorize(n / d);
for (int i = 0; i < dd.size(); ++i)
ans.push_back(dd[i]);
}
return ans;
}
|
b02cca67769db454adf7f2dec191dd6a43287c68
|
9808c0970f80c3260d1b91a226580aba3e52e2d5
|
/valdes-engineering/src/thermal/model/tbc2009/dimensionless/b.cpp
|
b6d0f4d3d7ed53f71f2f8e944f2960b9afeed0f4
|
[] |
no_license
|
raymondvaldes/tat
|
5d519732efb5ed379be1ac2579a6dbf7ac67e52f
|
0fa3a1902cf81682d741fe0063435c6b61bac148
|
refs/heads/master
| 2021-01-18T15:42:09.009818
| 2015-10-30T16:55:23
| 2015-10-30T16:55:23
| 13,633,268
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 530
|
cpp
|
b.cpp
|
//
// b.cpp
// tat
//
// Created by Raymond Valdes on 3/26/15.
// Copyright (c) 2015 Raymond Valdes. All rights reserved.
//
#include "b.h"
namespace thermal {
namespace model {
namespace tbc2009 {
namespace dimensionless{
auto b
(
units::quantity< units::si::length > const beam_radius,
units::quantity< units::si::length > const L
) noexcept -> units::quantity< units::si::dimensionless >
{
return beam_radius / L;
}
} // namespace dimensionless
} // namespace tbc2009
} // namespace model
} // namespace thermal
|
4a4e2ae1f98f50af53d0ab2c20be013463f9901c
|
1292fa3e2d2f680b6b7941d1af02d598a44bf7cd
|
/1028ListSorting.cpp
|
a498062c1f922188be21e823bddc8c895651867c
|
[] |
no_license
|
hedejing/PAT
|
f05a7746cc3c6f04b2c44a947eee852731a824a2
|
afea5e8682ca554213b54b593d654499f0c220bf
|
refs/heads/master
| 2021-01-10T10:39:30.209502
| 2016-03-02T05:33:04
| 2016-03-02T05:33:04
| 52,936,435
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 918
|
cpp
|
1028ListSorting.cpp
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
struct Data {
string id;
string name;
int grade;
};
int main()
{
int N, C;
cin >> N >> C;
vector<Data> datas(N);
for (int i = 0; i < N; i++)
cin >> datas[i].id >> datas[i].name >> datas[i].grade;
switch (C) {
case 1:
{
sort(datas.begin(), datas.end(), [](const Data &a, const Data&b) {
return a.id < b.id;
});
break;
}
case 2: {
sort(datas.begin(), datas.end(), [](const Data &a, const Data&b) {
if (a.name == b.name)
return a.id < b.id;
else
return a.name < b.name;
});
break;
}
case 3: {
sort(datas.begin(), datas.end(), [](const Data &a, const Data&b) {
if (a.grade == b.grade)
return a.id < b.id;
else
return a.grade < b.grade;
});
break;
}
}
for (auto i : datas)
printf("%s %s %d\n", i.id.data(), i.name.data(), i.grade);
system("pause");
}
|
e0d92f9046b7b04f30eb9ebf0f97ac7b15361358
|
ae7ba9c83692cfcb39e95483d84610715930fe9e
|
/yubinbai/pcuva-problems/UVa 11172 - Relational Operator/sol.cpp
|
ec8a24f35ba09b47f2bed14b9b08a6eac61c32b0
|
[] |
no_license
|
xenron/sandbox-github-clone
|
364721769ea0784fb82827b07196eaa32190126b
|
5eccdd8631f8bad78eb88bb89144972dbabc109c
|
refs/heads/master
| 2022-05-01T21:18:43.101664
| 2016-09-12T12:38:32
| 2016-09-12T12:38:32
| 65,951,766
| 5
| 7
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 320
|
cpp
|
sol.cpp
|
#include<stdio.h>
int main()
{
long int c, a, b, i;
while (scanf("%ld", &c) == 1)
{
for (i = 1; i <= c; i++)
{
scanf("%ld%ld", &a, &b);
if (a > b) printf(">\n");
else if (a < b) printf("<\n");
else printf("=\n");
}
}
return 0;
}
|
5cf9820bda1701c453c547a6bd4087ef547feddd
|
e8543c451443b4aecab96412dbb3419bfdefc54c
|
/src/test.cpp
|
4508a0710391f07c1cdc693b7fb895f44ae107f1
|
[] |
no_license
|
fisherleeyhl77/Dijkstra_heap
|
52b21debbb56e6ec77a2472c3de16f5415e06e2f
|
c88823c647b8b3f1288b04a05097c20cc2c40fd9
|
refs/heads/master
| 2021-05-13T21:07:12.031389
| 2018-01-05T21:22:34
| 2018-01-05T21:22:34
| 116,454,499
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 989
|
cpp
|
test.cpp
|
/*
* test.cpp
* Author: Huili Yu
*/
#include <iostream>
#include <climits>
#include <cstdlib>
#include <string>
#include "../include/graph.h"
#include "../include/dijkstra.h"
int main(int argc, char **argv)
{
if (argc != 2) {
std::cerr << "Please input the file for specifying "
"the graph connectivity" << std::endl;
exit(EXIT_FAILURE);
}
std::string connectivity_file = argv[1];
dijkstra::Dijkstra dj(connectivity_file);
int startNodeIdx = 0;
int endNodeIdx = 6;
std::vector<int> path;
int length_of_path =
dj.FindShortestPath(startNodeIdx, endNodeIdx, path);
dj.PrintPath(path);
std::cout << "The length of path is " << length_of_path << std::endl;
startNodeIdx = 4;
endNodeIdx = 1;
path.clear();
length_of_path = dj.FindShortestPath(startNodeIdx, endNodeIdx, path);
dj.PrintPath(path);
std::cout << "The length of path is " << length_of_path << std::endl;
std::cout << "End of main" << std::endl;
return 0;
}
|
e02b56d71ba1fc68175fc21a7ecd822fa68cc9f2
|
16e130599e881b7c1782ae822f3c52d88eac5892
|
/leetcode/movingStonesUntilConsecutive/q1.cpp
|
00b2ab5a4bdedfcf99868c59240d0bf458ad043d
|
[] |
no_license
|
knightzf/review
|
9b40221a908d8197a3288ba3774651aa31aef338
|
8c716b13b5bfba7eafc218f29e4f240700ae3707
|
refs/heads/master
| 2023-04-27T04:43:36.840289
| 2023-04-22T22:15:26
| 2023-04-22T22:15:26
| 10,069,788
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 470
|
cpp
|
q1.cpp
|
#include "header.h"
class Solution {
public:
vector<int> numMovesStones(int a, int b, int c) {
vector<int> v{a, b, c};
sort(v.begin(), v.end());
int x = v[1] - v[0] - 1;
int y = v[2] - v[1] - 1;
int minMove = 2;
if(x == 0 && y == 0) minMove = 0;
else if(x == 0 || y == 0 || x == 1 || y == 1) minMove = 1;
return {minMove, x + y};
}
};
int main()
{
Solution s;
}
|
bb97b5680bbbb3cfcda958b2f031cc8fef0f23d3
|
94d912f1cd5844f6c118e805e416e9f1da4f38a3
|
/SPTetris2.0/source/TetisPiece.cpp
|
f6beb92c924fbec2b31b2bcd624fd09056ae7a2e
|
[] |
no_license
|
Svampen/SPTetris2.0
|
7b500d98701a2f8425b9794b617e5a70f79b1218
|
c4f60e7711ca52355a195cf3161c8229337559b3
|
refs/heads/master
| 2020-05-20T15:38:48.795549
| 2013-07-28T14:47:57
| 2013-07-28T14:47:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 773
|
cpp
|
TetisPiece.cpp
|
/* TetrisPiece class
** Super class to all tetris pieces
**
** Created by Stefan Hagdahl
*/
#include "TetrisPiece.h"
TetrisPiece::TetrisPiece()
{
}
TetrisPiece::~TetrisPiece()
{
}
void TetrisPiece::move(Block::DIR Dir)
{
mBlock0->move(Dir);
mBlock1->move(Dir);
mBlock2->move(Dir);
mBlock3->move(Dir);
}
void TetrisPiece::fall(float dt)
{
float speed = mFallSpeed * dt;
mBlock0->moveY(speed);
mBlock1->moveY(speed);
mBlock2->moveY(speed);
mBlock3->moveY(speed);
}
void TetrisPiece::revertMove()
{
mBlock0->setOldPos();
mBlock1->setOldPos();
mBlock2->setOldPos();
mBlock3->setOldPos();
}
void TetrisPiece::setOldRotationStage()
{
mRotationStage = mOldRotationStage;
}
void TetrisPiece::setSpeed(float speed)
{
mFallSpeed = mBlock0->getSize().y * speed;
}
|
4d19b04530c7a3ddd7c3f09cfbae83a566c6a2ab
|
6b2a8dd202fdce77c971c412717e305e1caaac51
|
/solutions_5630113748090880_1/C++/haoranxu510/B.cpp
|
50ec7e31e7baeb1f0a30634c6b795af30225a203
|
[] |
no_license
|
alexandraback/datacollection
|
0bc67a9ace00abbc843f4912562f3a064992e0e9
|
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
|
refs/heads/master
| 2021-01-24T18:27:24.417992
| 2017-05-23T09:23:38
| 2017-05-23T09:23:38
| 84,313,442
| 2
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,052
|
cpp
|
B.cpp
|
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <cstring>
#include <cassert>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
#define SIZE(x) (int((x).size()))
#define rep(i,l,r) for (int i=(l); i<=(r); i++)
#define repd(i,r,l) for (int i=(r); i>=(l); i--)
#define rept(i,c) for (typeof((c).begin()) i=(c).begin(); i!=(c).end(); i++)
#ifndef ONLINE_JUDGE
#define debug(x) { cerr<<#x<<" = "<<(x)<<endl; }
#else
#define debug(x) {}
#endif
int c[2510];
void lemon()
{
int n; scanf("%d",&n);
memset(c,0,sizeof c);
rep(i,1,2*n-1)
rep(j,1,n)
{
int x; scanf("%d",&x);
c[x]^=1;
}
int z=0;
rep(i,1,2500)
if (c[i]==1)
{
printf("%d ",i); z++;
}
assert(z==n);
printf("\n");
}
int main()
{
ios::sync_with_stdio(true);
#ifndef ONLINE_JUDGE
freopen("B.in","r",stdin);
#endif
int tcase; scanf("%d",&tcase);
rep(nowcase,1,tcase)
{
printf("Case #%d: ",nowcase);
lemon();
}
return 0;
}
|
d0a478b1853ccf0e49ad795e9422d3bf4761fd04
|
2f557f60fc609c03fbb42badf2c4f41ef2e60227
|
/RecoJets/JetAlgorithms/interface/CompoundPseudoJet.h
|
3e898a97e975bfa9bfed91e8307e9862b90f7642
|
[
"Apache-2.0"
] |
permissive
|
CMS-TMTT/cmssw
|
91d70fc40a7110832a2ceb2dc08c15b5a299bd3b
|
80cb3a25c0d63594fe6455b837f7c3cbe3cf42d7
|
refs/heads/TMTT_1060
| 2020-03-24T07:49:39.440996
| 2020-03-04T17:21:36
| 2020-03-04T17:21:36
| 142,576,342
| 3
| 5
|
Apache-2.0
| 2019-12-05T21:16:34
| 2018-07-27T12:48:13
|
C++
|
UTF-8
|
C++
| false
| false
| 3,187
|
h
|
CompoundPseudoJet.h
|
#ifndef RecoJets_JetAlgorithms_CompoundPseudoJet_h
#define RecoJets_JetAlgorithms_CompoundPseudoJet_h
// -*- C++ -*-
//// -*- C++ -*-
//
// Package: CompoundPseudoJet
// Class: CompoundPseudoJet
//
/**
*/
//-------------------------------------------------------------------------------------
//!\class CompoundPseudoJet CompoundPseudoJet.cc RecoJets/JetAlgorithms/interface/CompoundPseudoJet.h
//!\brief CompoundPseudoJet holds an association of fastjet::PseudoJets that represent
//! a "hard" top jet with subjets.
//!
//-------------------------------------------------------------------------------------
//
// Original Author: Salvatore Rappoccio
// Created: Wed Nov 28 15:31:57 CST 2007
//
//-------------------------------------------------------------------------------------
#include <fastjet/JetDefinition.hh>
#include <fastjet/PseudoJet.hh>
#include <vector>
#include <algorithm>
class CompoundPseudoSubJet {
public:
CompoundPseudoSubJet() {}
CompoundPseudoSubJet(fastjet::PseudoJet const & subjet,
std::vector<int> const & constituents ) :
subjet_(subjet),
subjetArea_(0.0),
constituents_(constituents.size() )
{
copy( constituents.begin(), constituents.end(), constituents_.begin() );
}
CompoundPseudoSubJet(fastjet::PseudoJet const & subjet,
double subjetArea,
std::vector<int> const & constituents ) :
subjet_(subjet),
subjetArea_(subjetArea),
constituents_(constituents.size() )
{
copy( constituents.begin(), constituents.end(), constituents_.begin() );
}
~CompoundPseudoSubJet() {}
fastjet::PseudoJet const & subjet() const { return subjet_; }
double subjetArea() const { return subjetArea_; }
std::vector<int> const & constituents() const { return constituents_; }
protected:
fastjet::PseudoJet subjet_;
double subjetArea_;
std::vector<int> constituents_;
};
class CompoundPseudoJet {
public:
CompoundPseudoJet() {}
CompoundPseudoJet(fastjet::PseudoJet const & hardJet,
std::vector<CompoundPseudoSubJet> const & subjets ) :
hardJet_(hardJet),
hardJetArea_(0.0),
subjets_(subjets.size())
{
copy( subjets.begin(), subjets.end(), subjets_.begin() );
}
CompoundPseudoJet(fastjet::PseudoJet const & hardJet,
double hardJetArea,
std::vector<CompoundPseudoSubJet> const & subjets ) :
hardJet_(hardJet),
hardJetArea_(hardJetArea),
subjets_(subjets.size())
{
copy( subjets.begin(), subjets.end(), subjets_.begin() );
}
~CompoundPseudoJet() {}
fastjet::PseudoJet const & hardJet() const {return hardJet_;}
double hardJetArea() const {return hardJetArea_;}
std::vector<CompoundPseudoSubJet>const& subjets() const {return subjets_; }
protected:
fastjet::PseudoJet hardJet_;
double hardJetArea_;
std::vector<CompoundPseudoSubJet> subjets_;
};
inline bool greaterByEtPseudoJet( fastjet::PseudoJet const & j1, fastjet::PseudoJet const & j2 ) {
return j1.perp() > j2.perp();
}
#endif
|
68f4588b6fa6e137d0d5c1337cc515097c3776c3
|
7999462d6d68dcab0b140a1fef33149b4ae6f0a6
|
/include/VISAGE/_mensurium.hpp
|
bfcd38a4757e4e8f2d2e43d9b46ce03d41f74d08
|
[] |
no_license
|
gabrieljt/VisAGE
|
43ad10e15ca2c52053864adbe1ddd940b4ead637
|
4d63f8b889612c2322ef447a1d1771240e9eda3d
|
refs/heads/master
| 2019-01-02T04:55:15.886674
| 2014-12-10T19:56:48
| 2014-12-10T19:56:48
| 20,076,682
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,700
|
hpp
|
_mensurium.hpp
|
#ifndef VISAGE_MENSURIUMAGE_HPP
#define VISAGE_MENSURIUMAGE_HPP
#include <opencv/cv.h>
#include <opencv2/opencv.hpp>
#include <queue>
#include <mutex>
class Marcador{
public:
void Inic(int x, int y,float dx,float dy);
Marcador();
CvPoint* CentroTab(std::vector<cv::Point2f> pontos);
void calcCantosDigonal(std::vector<cv::Point2f> C);
CvPoint* getCantosDigonal();
cv::Mat getPosicao();
void setPosicao(cv::Mat pos);
cv::Mat getOrientacao();
void setOrientacao(cv::Mat orient);
cv::Mat getMatP3D();
bool VerificaCor(cv::Mat& img, cv::Scalar cor,cv::Scalar deltaCor );
void AcharCantoProx(cv::Mat src, int deltaVan, cv::Mat imgDes);
cv::Point getCentroImg();
void setValido();
bool isValido();
private:
CvPoint centroImg;
CvPoint cantosDigonal[4];
cv::Mat orientacao;
cv::Mat posicao;
CvPoint cantoProximo;
CvMat* posCantoProximo;
double tamanhoReal[2];
double tamanhoDig;
CvSize tamTab;
cv::Mat matPontos3D;
std::vector<cv::Point2f> corners;
int cornerCount;
double deltaTab[2];
cv::Mat PontosTab3D();
double Dist(CvPoint p1, CvPoint p2);
cv::Point canto;
bool valido;
};
class Placa{
public:
Placa();
Marcador* marco;
void Inic(int n);
void CalcentroPlaca();
void setarPontosCam();
void setnMarcoAch(int nMarcoAch);
int getnMarcoAch();
cv::Point getPosCentroImg();
cv::Mat getmatPontosPlaca3D();
Marcador getMarcador(int i);
private:
CvMat posicaoCentro;
CvMat rotacao;
cv::Point posCentroImg;
CvMat* posCantos[];
CvMat* pontosPlaca3D;
cv::Mat matPontosPlaca3D;
CvMat* pontosPlacaCam;
int nMarcoAch;
};
class Mensurium
{
public:
Mensurium(unsigned int l, unsigned int a, float t, unsigned int c);
int AcharTabs(cv::Mat img, int n, CvMat** trans, int npl, cv::Mat imgDes = cv::Mat(0,0,CV_8UC1));
Marcador AcharCentro1Tab(cv::Mat img, Marcador& marco, unsigned int largura, unsigned int altura, float tamanho);
bool Rodar(char *nomeJan, cv::Mat img);
cv::Mat Stereo(cv::Mat imgE,cv::Mat imgD);
cv::Mat steroRegMarcos();
Placa getPlaca(int i);
Placa* placa;
void IniciarCaptura();
std::queue<Marcador> filaMarcadores;
std::mutex mutexMarcador;
std::queue<cv::Mat> filaImagens;
std::mutex mutexImagem;
private:
cv::Mat distCoeffs;
cv::Mat cameraMatrix;
unsigned int largura;
unsigned int altura;
float tamanho;
unsigned int camera;
void* CapturarImagem(void);
static void* chamarCapturarImagem(void *arg){return ((Mensurium*)arg)->CapturarImagem();}
};
#endif // VISAGE_MENSURIUMAGE_HPP
|
8d8db0aacf44fca5c50ea4fd98e77dd594df97d0
|
657d32e17cc206b5635fa84e19917b62f2f30977
|
/src/Shader.h
|
0d2bc58de1b06b95a1c0231456a1bdc776a6f033
|
[
"MIT"
] |
permissive
|
lpalozzi/rxp
|
59af9e45321b7c73983d1fd55baa4997f09a31e2
|
edf3ef3c0627fb6107427bd23d71f902b1acebbb
|
refs/heads/master
| 2020-07-07T21:21:42.774855
| 2019-08-21T02:54:03
| 2019-08-21T02:54:03
| 203,481,027
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 418
|
h
|
Shader.h
|
/*
* Shader.h
*
* Author: leo
*/
#ifndef SHADER_H_
#define SHADER_H_
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengles2.h>
class Shader
{
public:
~Shader();
GLuint id;
static Shader *load (const char *name);
private:
Shader (GLuint id);
static GLuint compile (const char *name, GLenum shader_type);
static GLuint link (GLuint vertex_obj, GLuint fragment_obj);
};
#endif /* SHADER_H_ */
|
c4cd6ee7a39ab794f51554f56176f09fc8a74c0a
|
6b62b0d9727ad3da3d266649086cc3444ae0d9d5
|
/src/ECS/Systems/entityDestroying.hpp
|
d35f665ac8e5eec52d4ba1ee1e30490dff85a356
|
[
"MIT"
] |
permissive
|
dualword/PopHead
|
55079a30bf7099b74d6c83e9f1a85ddea0774574
|
2bce21b1a6b3d16a2ccecf0d15faeebf6a486c81
|
refs/heads/master
| 2023-03-15T21:28:48.545172
| 2020-11-12T16:54:59
| 2020-11-12T16:54:59
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 181
|
hpp
|
entityDestroying.hpp
|
#pragma once
#include "ECS/system.hpp"
namespace ph::system {
class EntityDestroying : public System
{
public:
using System::System;
void update(float dt) override;
};
}
|
7a8d02e910e363b80eca2a922a5c7d5c51427c9f
|
29af718d33105bceddd488326e53dab24e1014ef
|
/ComputerAlgebra/Hypergraphs/Lisp/Generators/plans/milestones.hpp
|
962d98546c3cb08d1430ed53d528489a00c43f3f
|
[] |
no_license
|
OKullmann/oklibrary
|
d0f422847f134705c0cd1eebf295434fe5ffe7ed
|
c578d0460c507f23b97329549a874aa0c0b0541b
|
refs/heads/master
| 2023-09-04T02:38:14.642785
| 2023-09-01T11:38:31
| 2023-09-01T11:38:31
| 38,629
| 21
| 64
| null | 2020-10-30T17:13:04
| 2008-07-30T18:20:06
|
C++
|
UTF-8
|
C++
| false
| false
| 2,120
|
hpp
|
milestones.hpp
|
// Oliver Kullmann, 23.1.2010 (Swansea)
/* Copyright 2010, 2012 Oliver Kullmann
This file is part of the OKlibrary. OKlibrary is free software; you can redistribute
it and/or modify it under the terms of the GNU General Public License as published by
the Free Software Foundation and included in this library; either version 3 of the
License, or any later version. */
/*!
\file ComputerAlgebra/Hypergraphs/Lisp/Generators/plans/milestones.hpp
\module_version Hypergraphs/Lisp/Generators 0.1.0.1 (23.10.2010)
\par Version 0.1.1
\par
In ComputerAlgebra/Hypergraphs/Lisp/Generators/plans/general.hpp
the following topics are handled:
- Organisation
- ramseyrv_ohg handles r=0 incorrectly
- %Ramsey hypergraphs
\par
In ComputerAlgebra/Hypergraphs/Lisp/Generators/plans/general.hpp
the following topics are handled:
- Hypergraphs of arithmetic progressions : DONE
\par Version 0.1.2
\par
In ComputerAlgebra/Hypergraphs/Lisp/Generators/plans/GreenTao.hpp
the following topics are handled:
- Further information on arithmetic progressions in prime numbers
\par
In ComputerAlgebra/Hypergraphs/Lisp/Generators/plans/Gasarch.hpp
the following topics are handled:
- Completition
\par Version 0.1.3
\par
In ComputerAlgebra/Hypergraphs/Lisp/Generators/plans/general.hpp
the following topics are handled:
- Statistics
- Sudoku
\par Version 0.1.4
\par
In ComputerAlgebra/Hypergraphs/Lisp/Generators/plans/Hindman.hpp
the following topics are handled:
- Implement iterator-forms
- Implement general functionality (arbitrary k)
\par Version 0.1.5
\par
In ComputerAlgebra/Hypergraphs/Lisp/Generators/plans/Rado.hpp
the following topics are handled:
- Basic functionality
- Checking regularity
\par
Further milestones are created.
-------------------------------------------------------------------------------------------------------------------------------------
\par Version history
- 0.1 : 23.1.2010; various generators related to Ramsey theory, plus complete hypergraphs.
*/
|
e80b9b48b14f91e2793a818e8522e0e2e671d80b
|
0f0526a16f5749ff5d45a0b0c565e9f9447c93a9
|
/Nodes/NodesHeaders/Expressions/MethodInvocation.h
|
d1fb8bcb3f6c93aa74947dcfc097ea57bc6145ec
|
[] |
no_license
|
Pikassik/minijava-compiler
|
c1f4a0b88ddca6e01f7264e417356969afd64256
|
7f413fc984fab32c015903590ad43b2d70a2dfc5
|
refs/heads/master
| 2022-12-18T12:27:00.012886
| 2020-04-17T01:51:43
| 2020-04-17T01:51:43
| 252,119,447
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 598
|
h
|
MethodInvocation.h
|
#pragma once
#include <Nodes/NodesHeaders/Expressions/Expression.h>
#include <Nodes/NodesHeaders/Statements/Statement.h>
#include <vector>
namespace node {
struct MethodInvocation : Expression, Statement {
std::shared_ptr<Expression> class_expression;
std::string method_identifier;
std::vector<std::shared_ptr<Expression>> arguments;
MethodInvocation(std::shared_ptr<Expression> class_expression,
std::string method_identifier,
std::vector<std::shared_ptr<Expression>> arguments);
void Accept(Visitor& visitor) override;
};
} // namespace node
|
d8bc740e58d518fef2a5ff17d1b5cdd655c831aa
|
543a165f7a18b7a874273f918f13a4cdad758ccf
|
/IECacheCatcher-VS2010/IECacheThread.cpp
|
c174e56ee23fc380b61fd702fa0509d4968985f4
|
[] |
no_license
|
DTTKillASmallScale/cocoshun
|
1ba2c18bfdb68c93f59e4dd9201da923500599d4
|
e7a2700353db896d94e3528c95af287f667ea75b
|
refs/heads/master
| 2021-01-22T19:31:08.859894
| 2012-11-09T01:29:00
| 2012-11-09T01:29:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,066
|
cpp
|
IECacheThread.cpp
|
// IECacheThread.cpp: implementation of the CIECacheThread class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "IECacheCatcher.h"
#include "IECacheThread.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
HWND CIECacheThread::m_hWnd;
CString CIECacheThread::m_tagPath;
CString CIECacheThread::m_Filter;
CString CIECacheThread::m_FilterSpliter;
CString CIECacheThread::m_WebSite;
CIECacheThread::CIECacheThread()
{
m_dwID = 0;
m_hThread = NULL;
m_hThreadClear = NULL;
}
CIECacheThread::~CIECacheThread()
{
CloseHandle(m_hThread);
}
void CIECacheThread::Interrupt()
{
m_IECache.Interrupt();
if(m_hThread)
{
WaitForSingleObject(m_hThread,WAIT_ABANDONED);
CloseHandle(m_hThread);
m_hThread = NULL;
}
}
void CIECacheThread::Export(CString tagPath, CString Filter,CString FilterSpliter, CString WebSite )
{
m_tagPath= tagPath;
m_Filter = Filter;
m_FilterSpliter = FilterSpliter;
m_WebSite = WebSite;
m_hThread = CreateThread(NULL,
0,
(LPTHREAD_START_ROUTINE)ThreadProc,
(void*) this,
0,
&m_dwID);
}
UINT CIECacheThread::ThreadProc(void* lpParam)
{
CIECacheThread* pThis = (CIECacheThread*)(lpParam);
::SendMessage(pThis->m_hWnd, MSG_NOTIFY_STATUS, IDS_SEARCH_CACHEENTRY, NULL);
pThis->m_IECache.SearchCacheEntry(pThis->m_Filter, pThis->m_FilterSpliter, pThis->m_WebSite);
if(pThis->m_IECache.IsInterrupted())
goto finish;
::SendMessage(pThis->m_hWnd, MSG_NOTIFY_STATUS, IDS_SEARCH_CACHEENTRY, NULL);
pThis->m_IECache.Export(pThis->m_tagPath, ExportCallback);
finish:
::SendMessage(pThis->m_hWnd, MSG_NOTIFY_STATUS, NULL, NULL);
return 0;
}
int WINAPI CIECacheThread::ExportCallback( LPCTSTR Param1,LPCTSTR Param2,LPCTSTR Param3,LPCTSTR Param4 )
{
if(!Param1)
return 0;
LIST_DATA *pListData = new LIST_DATA;
pListData->bSuccess = (BOOL) Param1;
pListData->FileName = new TCHAR[_tcslen(Param2)+1];
pListData->Website = new TCHAR[_tcslen(Param3)+1];
pListData->LocalPath = new TCHAR[_tcslen(Param4)+1];
_tcscpy(pListData->FileName, Param2);
_tcscpy(pListData->Website, Param3);
_tcscpy(pListData->LocalPath, Param4);
::SendMessage(CIECacheThread::m_hWnd, MSG_NOTIFY_EXPORT_RECORD, NULL, (LPARAM ) pListData);
return 0;
}
void CIECacheThread::ClearCache()
{
//m_hThread =
CreateThread(NULL,
0,
(LPTHREAD_START_ROUTINE)ThreadProcClearCache,
(void*) this,
0,
&m_dwID);
}
UINT __stdcall CIECacheThread::ThreadProcClearCache( void* lpParam )
{
CIECacheThread* pThis = (CIECacheThread*)(lpParam);
pThis->m_IECache.ClearInternetTemp();
::SendMessage(CIECacheThread::m_hWnd, MSG_NOTIFY_CLEARCACHE_DONE, NULL, NULL);
return 0;
}
void CIECacheThread::SetHWnd( HWND hWnd )
{
m_hWnd = hWnd;
}
|
5b076575a8f8e736a81fe7b0dc915712cda9085d
|
64178ab5958c36c4582e69b6689359f169dc6f0d
|
/vscode/wg/sdk/UMaterialInstance.hpp
|
c3c1abf3c126179b9faa292f9dad5506724c3bf1
|
[] |
no_license
|
c-ber/cber
|
47bc1362f180c9e8f0638e40bf716d8ec582e074
|
3cb5c85abd8a6be09e0283d136c87761925072de
|
refs/heads/master
| 2023-06-07T20:07:44.813723
| 2023-02-28T07:43:29
| 2023-02-28T07:43:29
| 40,457,301
| 5
| 5
| null | 2023-05-30T19:14:51
| 2015-08-10T01:37:22
|
C++
|
UTF-8
|
C++
| false
| false
| 5,999
|
hpp
|
UMaterialInstance.hpp
|
#pragma once
#include "UMaterialInterface.hpp"
#include "FMaterialInstanceBasePropertyOverrides.hpp"
#ifdef _MSC_VER
#pragma pack(push, 1)
#endif
namespace PUBGSDK {
struct alignas(1) UMaterialInstance // Size: 0x1B8
: public UMaterialInterface // Size: 0x78
{
private:
typedef UMaterialInstance t_struct;
typedef ExternalPtr<t_struct> t_structHelper;
public:
static ExternalPtr<struct UClass> StaticClass()
{
static ExternalPtr<struct UClass> ptr;
if(!ptr) ptr = UObject::FindClassFast(1020); // id32("Class Engine.MaterialInstance")
return ptr;
}
ExternalPtr<struct UPhysicalMaterial> PhysMaterial; /* Ofs: 0x78 Size: 0x8 - ObjectProperty Engine.MaterialInstance.PhysMaterial */
ExternalPtr<struct UMaterialInterface> Parent; /* Ofs: 0x80 Size: 0x8 - ObjectProperty Engine.MaterialInstance.Parent */
uint8_t boolField88;
uint8_t UnknownData89[0x7];
TArray<struct FFontParameterValue> FontParameterValues; /* Ofs: 0x90 Size: 0x10 - ArrayProperty Engine.MaterialInstance.FontParameterValues */
TArray<struct FScalarParameterValue> ScalarParameterValues; /* Ofs: 0xA0 Size: 0x10 - ArrayProperty Engine.MaterialInstance.ScalarParameterValues */
TArray<struct FTextureParameterValue> TextureParameterValues; /* Ofs: 0xB0 Size: 0x10 - ArrayProperty Engine.MaterialInstance.TextureParameterValues */
TArray<struct FVectorParameterValue> VectorParameterValues; /* Ofs: 0xC0 Size: 0x10 - ArrayProperty Engine.MaterialInstance.VectorParameterValues */
uint8_t boolFieldD0;
uint8_t UnknownDataD1[0x3];
FMaterialInstanceBasePropertyOverrides BasePropertyOverrides; /* Ofs: 0xD4 Size: 0x14 - StructProperty Engine.MaterialInstance.BasePropertyOverrides */
uint8_t UnknownDataE8[0xD0];
inline bool SetPhysMaterial(t_structHelper inst, ExternalPtr<struct UPhysicalMaterial> value) { inst.WriteOffset(0x78, value); }
inline bool SetParent(t_structHelper inst, ExternalPtr<struct UMaterialInterface> value) { inst.WriteOffset(0x80, value); }
inline bool bHasStaticPermutationResource()
{
return boolField88& 0x1;
}
inline bool SetbHasStaticPermutationResource(t_structHelper inst, bool value)
{
auto curVal = *reinterpret_cast<uint8_t*>(&value);
inst.WriteOffset(0x88, (uint8_t)(value ? curVal | (uint8_t)1 : curVal & ~(uint8_t)1));
}
inline bool bOverrideSubsurfaceProfile()
{
return boolField88& 0x4;
}
inline bool SetbOverrideSubsurfaceProfile(t_structHelper inst, bool value)
{
auto curVal = *reinterpret_cast<uint8_t*>(&value);
inst.WriteOffset(0x88, (uint8_t)(value ? curVal | (uint8_t)4 : curVal & ~(uint8_t)4));
}
inline bool SetFontParameterValues(t_structHelper inst, TArray<struct FFontParameterValue> value) { inst.WriteOffset(0x90, value); }
inline bool SetScalarParameterValues(t_structHelper inst, TArray<struct FScalarParameterValue> value) { inst.WriteOffset(0xA0, value); }
inline bool SetTextureParameterValues(t_structHelper inst, TArray<struct FTextureParameterValue> value) { inst.WriteOffset(0xB0, value); }
inline bool SetVectorParameterValues(t_structHelper inst, TArray<struct FVectorParameterValue> value) { inst.WriteOffset(0xC0, value); }
inline bool bOverrideBaseProperties()
{
return boolFieldD0& 0x1;
}
inline bool SetbOverrideBaseProperties(t_structHelper inst, bool value)
{
auto curVal = *reinterpret_cast<uint8_t*>(&value);
inst.WriteOffset(0xD0, (uint8_t)(value ? curVal | (uint8_t)1 : curVal & ~(uint8_t)1));
}
inline bool SetBasePropertyOverrides(t_structHelper inst, FMaterialInstanceBasePropertyOverrides value) { inst.WriteOffset(0xD4, value); }
};
#ifdef VALIDATE_SDK
namespace Validation{
auto constexpr sizeofUMaterialInstance = sizeof(UMaterialInstance); // 440
static_assert(sizeof(UMaterialInstance) == 0x1B8, "Size of UMaterialInstance is not correct.");
auto constexpr UMaterialInstance_PhysMaterial_Offset = offsetof(UMaterialInstance, PhysMaterial);
static_assert(UMaterialInstance_PhysMaterial_Offset == 0x78, "UMaterialInstance::PhysMaterial offset is not 78");
auto constexpr UMaterialInstance_Parent_Offset = offsetof(UMaterialInstance, Parent);
static_assert(UMaterialInstance_Parent_Offset == 0x80, "UMaterialInstance::Parent offset is not 80");
auto constexpr UMaterialInstance_boolField88_Offset = offsetof(UMaterialInstance, boolField88);
static_assert(UMaterialInstance_boolField88_Offset == 0x88, "UMaterialInstance::boolField88 offset is not 88");
auto constexpr UMaterialInstance_FontParameterValues_Offset = offsetof(UMaterialInstance, FontParameterValues);
static_assert(UMaterialInstance_FontParameterValues_Offset == 0x90, "UMaterialInstance::FontParameterValues offset is not 90");
auto constexpr UMaterialInstance_ScalarParameterValues_Offset = offsetof(UMaterialInstance, ScalarParameterValues);
static_assert(UMaterialInstance_ScalarParameterValues_Offset == 0xa0, "UMaterialInstance::ScalarParameterValues offset is not a0");
auto constexpr UMaterialInstance_TextureParameterValues_Offset = offsetof(UMaterialInstance, TextureParameterValues);
static_assert(UMaterialInstance_TextureParameterValues_Offset == 0xb0, "UMaterialInstance::TextureParameterValues offset is not b0");
auto constexpr UMaterialInstance_VectorParameterValues_Offset = offsetof(UMaterialInstance, VectorParameterValues);
static_assert(UMaterialInstance_VectorParameterValues_Offset == 0xc0, "UMaterialInstance::VectorParameterValues offset is not c0");
auto constexpr UMaterialInstance_boolFieldD0_Offset = offsetof(UMaterialInstance, boolFieldD0);
static_assert(UMaterialInstance_boolFieldD0_Offset == 0xd0, "UMaterialInstance::boolFieldD0 offset is not d0");
auto constexpr UMaterialInstance_BasePropertyOverrides_Offset = offsetof(UMaterialInstance, BasePropertyOverrides);
static_assert(UMaterialInstance_BasePropertyOverrides_Offset == 0xd4, "UMaterialInstance::BasePropertyOverrides offset is not d4");
}
#endif
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
f22a092b619aa566e4b589487fff15410f79b2fa
|
347334f675bc31ecab5d74ca6388827b13097ed9
|
/src/lib/src/commands/sql-worker.cpp
|
560fb5509ee10c7e8f81bc88161d4b8e8e14a47d
|
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
Bionus/imgbrd-grabber
|
442108d9663a06a848ef49837943d5950bca9d8c
|
4ab008d5d0f62ab2bc34aff7de02e05d598e058a
|
refs/heads/master
| 2023-08-20T21:50:37.649081
| 2023-08-17T22:54:55
| 2023-08-17T22:54:55
| 32,276,615
| 2,226
| 301
|
Apache-2.0
| 2023-08-12T16:31:57
| 2015-03-15T18:26:31
|
HTML
|
UTF-8
|
C++
| false
| false
| 1,885
|
cpp
|
sql-worker.cpp
|
#include "commands/sql-worker.h"
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlDriver>
#include <QtSql/QSqlError>
#include <QtSql/QSqlField>
#include <QtSql/QSqlQuery>
#include <utility>
#include "logger.h"
SqlWorker::SqlWorker(QString driver, QString host, QString user, QString password, QString database, bool dryRun, QObject *parent)
: QThread(parent), m_driver(std::move(driver)), m_host(std::move(host)), m_user(std::move(user)), m_password(std::move(password)), m_database(std::move(database)), m_dryRun(dryRun)
{
m_enabled = (m_driver == QLatin1String("QSQLITE") && !m_database.isEmpty())
|| (!m_host.isEmpty() && !m_user.isEmpty() && !m_database.isEmpty());
m_started = false;
}
bool SqlWorker::connect()
{
if (!m_enabled || m_started) {
return true;
}
m_db = QSqlDatabase::addDatabase(m_driver, "SQL worker - " + m_database);
m_db.setDatabaseName(m_database);
m_db.setUserName(m_user);
m_db.setPassword(m_password);
const int portSeparator = m_host.lastIndexOf(':');
if (portSeparator > 0) {
m_db.setHostName(m_host.left(portSeparator));
m_db.setPort(m_host.mid(portSeparator + 1).toInt());
} else {
m_db.setHostName(m_host);
}
if (!m_db.open()) {
log(QStringLiteral("Error initializing commands: %1").arg(m_db.lastError().text()), Logger::Error);
return false;
}
m_started = true;
return true;
}
QString SqlWorker::escape(const QVariant &val)
{
QSqlDriver *driver = QSqlDatabase::database().driver();
if (driver == nullptr) {
return nullptr;
}
QSqlField f;
f.setType(val.type());
f.setValue(val);
return driver->formatValue(f);
}
bool SqlWorker::execute(const QString &sql)
{
if (!m_enabled || !connect()) {
return false;
}
log(QStringLiteral("SQL execution of \"%1\"").arg(sql));
Logger::getInstance().logCommandSql(sql);
if (m_dryRun) {
return true;
}
QSqlQuery query(m_db);
return query.exec(sql);
}
|
13587ef22fa6ce657bfaebc3072b7ba5fc4f77f6
|
158065b59fea05fa61a31ce400becd29106d70ca
|
/FastBlur/FastBlur.cpp
|
5b6ded56c025f374e80fe88b0955a57ba8bb0140
|
[
"Apache-2.0"
] |
permissive
|
nullptr-0/FastBlur
|
7c4e54761b0cd0db3c4908fefcaeb47f01d2031a
|
f90c17a630defd337fff38d974dbb4043a2bce69
|
refs/heads/main
| 2023-07-09T05:36:08.809588
| 2021-08-25T03:12:55
| 2021-08-25T03:12:55
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,577
|
cpp
|
FastBlur.cpp
|
// FastBlur.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include "framework.h"
#include "FastBlur.h"
#include "EasyBMP.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
using namespace std;
#define COLOR_RED 1
#define COLOR_GREEN 2
#define COLOR_BLUE 3
#define COLOR_PURPLE 4
#define COLOR_YELLOW 5
#define COLOR_CYAN 6
#define COLOR_TRANSPARENT 0
// 唯一的应用程序对象
CWinApp theApp;
using namespace std;
void Blur(BMP& bitmap, short radius, bool cmp)
{
if (radius < 1)
{
return;
}
int w = bitmap.TellWidth();
int h = bitmap.TellHeight();
int* pix = new int[w * h];
int* oripix = new int[w * h];
for (size_t i = 0; i < w * h - 1; i++)
{
RGBApixel p = bitmap.GetPixel(i % w, i / w);
pix[i] = (((p.Red << 8) | p.Green) << 8) | p.Blue;
oripix[i] = pix[i];
}
int wm = w - 1;
int hm = h - 1;
int wh = w * h;
int div = radius + radius + 1;
int* r = new int[wh];
int* g = new int[wh];
int* b = new int[wh];
int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
int* vmin = new int[max(w, h)];
int divsum = (div + 1) >> 1;
divsum *= divsum;
int temp = 256 * divsum;
int* dv = new int[temp];
for (i = 0; i < temp; i++)
{
dv[i] = (i / divsum);
}
yw = yi = 0;
int** stack = new int* [div];
for (size_t i = 0; i < div; i++)
{
stack[i] = new int[3];
}
int stackpointer;
int stackstart;
int* sir;
int rbs;
int r1 = radius + 1;
int routsum, goutsum, boutsum;
int rinsum, ginsum, binsum;
for (y = 0; y < h; y++)
{
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
for (i = -radius; i <= radius; i++)
{
p = pix[yi + min(wm, max(i, 0))];
sir = stack[i + radius];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = (p & 0x0000ff);
rbs = r1 - abs(i);
rsum += sir[0] * rbs;
gsum += sir[1] * rbs;
bsum += sir[2] * rbs;
if (i > 0)
{
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
}
else
{
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
}
stackpointer = radius;
for (x = 0; x < w; x++)
{
r[yi] = dv[rsum];
g[yi] = dv[gsum];
b[yi] = dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (y == 0)
{
vmin[x] = min(x + radius + 1, wm);
}
p = pix[yw + vmin[x]];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = (p & 0x0000ff);
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[(stackpointer) % div];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi++;
}
yw += w;
}
for (x = 0; x < w; x++)
{
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
yp = -radius * w;
for (i = -radius; i <= radius; i++)
{
yi = max(0, yp) + x;
sir = stack[i + radius];
sir[0] = r[yi];
sir[1] = g[yi];
sir[2] = b[yi];
rbs = r1 - abs(i);
rsum += r[yi] * rbs;
gsum += g[yi] * rbs;
bsum += b[yi] * rbs;
if (i > 0)
{
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
}
else
{
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
if (i < hm)
{
yp += w;
}
}
yi = x;
stackpointer = radius;
for (y = 0; y < h; y++)
{
pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (x == 0)
{
vmin[y] = min(y + r1, hm) * w;
}
p = x + vmin[y];
sir[0] = r[p];
sir[1] = g[p];
sir[2] = b[p];
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[stackpointer];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi += w;
}
}
int cmpmode = -1;
if (cmp == true)
{
srand(time(0));
cmpmode = rand() % 8;
}
for (size_t i = 0; i < w * h - 1; i++)
{
RGBApixel p;
if (cmp == true)
{
switch (cmpmode)
{
case 0:
if ((i % w) <= (w / 2))
{
pix[i] = oripix[i];
}
break;
case 1:
if ((i % w) > (w / 2))
{
pix[i] = oripix[i];
}
break;
case 2:
if ((i / w) <= (h / 2))
{
pix[i] = oripix[i];
}
break;
case 3:
if ((i / w) > (h / 2))
{
pix[i] = oripix[i];
}
break;
case 4:
if (((i % w) <= (w / 2) && (i / w) <= (h / 2)) || ((i % w) > (w / 2) && (i / w) > (h / 2)))
{
pix[i] = oripix[i];
}
break;
case 5:
if (!(((i % w) <= (w / 2) && (i / w) <= (h / 2)) || ((i % w) > (w / 2) && (i / w) > (h / 2))))
{
pix[i] = oripix[i];
}
break;
case 6:
if (((i % w) <= (w / 3) && ((i / w) <= (h / 3) || (i / w) > (h * 2 / 3))) ||
((i % w) > (w * 2 / 3) && ((i / w) <= (h / 3) || (i / w) > (h * 2 / 3))) ||
((w / 3) < (i % w) && (i % w) <= (w * 2 / 3) && (h / 3) < (i / w) && (i / w) <= (h * 2 / 3)))
{
pix[i] = oripix[i];
}
break;
case 7:
if (!(((i % w) <= (w / 3) && ((i / w) <= (h / 3) || (i / w) > (h * 2 / 3))) ||
((i % w) > (w * 2 / 3) && ((i / w) <= (h / 3) || (i / w) > (h * 2 / 3))) ||
((w / 3) < (i % w) && (i % w) <= (w * 2 / 3) && (h / 3) < (i / w) && (i / w) <= (h * 2 / 3))))
{
pix[i] = oripix[i];
}
break;
default:
break;
}
}
p.Red = pix[i] >> 16;
p.Green = (pix[i] - (p.Red << 16)) >> 8;
p.Blue = pix[i] - (p.Red << 16) - (p.Green << 8);
p.Alpha = 0x0;
bitmap.SetPixel(i % w, i / w, p);
}
return;
}
void FilterColor(BMP& bitmap, short colorFilter)
{
if (0 >= colorFilter || colorFilter > 6)
{
return;
}
int w = bitmap.TellWidth();
int h = bitmap.TellHeight();
for (size_t i = 0; i < w * h - 1; i++)
{
RGBApixel p = bitmap.GetPixel(i % w, i / w);
if (colorFilter == COLOR_RED || colorFilter == COLOR_PURPLE || colorFilter == COLOR_YELLOW)
{
p.Red = 0;
}
if (colorFilter == COLOR_GREEN || colorFilter == COLOR_YELLOW || colorFilter == COLOR_CYAN)
{
p.Green = 0;
}
if (colorFilter == COLOR_BLUE || colorFilter == COLOR_PURPLE || colorFilter == COLOR_CYAN)
{
p.Blue = 0;
}
p.Alpha = 0x0;
bitmap.SetPixel(i % w, i / w, p);
}
return;
}
void Brighten(BMP& bitmap, short brighten)
{
if (-255 > brighten || brighten > 255)
{
return;
}
int w = bitmap.TellWidth();
int h = bitmap.TellHeight();
for (size_t i = 0; i < w * h - 1; i++)
{
RGBApixel p = bitmap.GetPixel(i % w, i / w);
int tRGB = 0;
tRGB = p.Red + brighten;
if (tRGB > 255)
{
p.Red = 255;
}
else
{
if (tRGB < 0)
{
p.Red = 0;
}
else
{
p.Red = tRGB;
}
}
tRGB = p.Green + brighten;
if (tRGB > 255)
{
p.Green = 255;
}
else
{
if (tRGB < 0)
{
p.Green = 0;
}
else
{
p.Green = tRGB;
}
}
tRGB = p.Blue + brighten;
if (tRGB > 255)
{
p.Blue = 255;
}
else
{
if (tRGB < 0)
{
p.Blue = 0;
}
else
{
p.Blue = tRGB;
}
}
p.Alpha = 0x0;
bitmap.SetPixel(i % w, i / w, p);
}
return;
}
void Binarization(BMP& bitmap, int threshold, short probability)
{
probability = 10001 - probability;
if (0 > threshold || threshold > 0xffffff || probability <= 0 || probability > 10000)
{
return;
}
int w = bitmap.TellWidth();
int h = bitmap.TellHeight();
srand(time(0));
for (size_t i = 0; i < w * h - 1; i++)
{
RGBApixel p = bitmap.GetPixel(i % w, i / w);
int pix = (((p.Red << 8) | p.Green) << 8) | p.Blue;
if (pix >= threshold)
{
if (rand() % probability == 0)
{
p.Red = 0;
p.Green = 0;
p.Blue = 0;
}
else
{
p.Red = 255;
p.Green = 255;
p.Blue = 255;
}
}
else
{
if (rand() % probability == 0)
{
p.Red = 255;
p.Green = 255;
p.Blue = 255;
}
else
{
p.Red = 0;
p.Green = 0;
p.Blue = 0;
}
}
bitmap.SetPixel(i % w, i / w, p);
}
return;
}
void Grayed(BMP& bitmap, double gamma)
{
int w = bitmap.TellWidth();
int h = bitmap.TellHeight();
for (size_t i = 0; i < w * h - 1; i++)
{
RGBApixel p = bitmap.GetPixel(i % w, i / w);
short gray = pow((pow(p.Red, gamma) * 0.2973 + pow(p.Green, gamma) * 0.6274 + pow(p.Blue, gamma) * 0.0753), (1 / gamma));
p.Red = gray;
p.Green = gray;
p.Blue = gray;
bitmap.SetPixel(i % w, i / w, p);
}
return;
}
void process(char* input, char* output)
{
BMP bitmap;
if (!bitmap.ReadFromFile(input))
return;
short blurRadius = 0;
short colorFilter = 0;
short brighten = 0;
int binaryThreshold = 0;
short probability = 0;
double gamma = 0;
//cout << "输入虚化半径:" << endl;
//cin >> blurRadius;
//cout << "输入颜色筛选器(0~6):" << endl;
//cin >> colorFilter;
//cout << "输入颜色增量(-255~255):" << endl;
//cin >> brighten;
//cout << "输入二值化阈值(0~0xFFFFFF):" << endl;
//cin >> binaryThreshold;
//cout << "输入反色概率(1~10000):" << endl;
//cin >> probability;
cout << "输入Gamma(建议值 2.2):" << endl;
cin >> gamma;
//Blur(bitmap, blurRadius, true);
//FilterColor(bitmap, colorFilter);
//Brighten(bitmap, brighten);
//Binarization(bitmap, binaryThreshold, probability);
Grayed(bitmap, gamma);
bitmap.WriteToFile(output);
return;
}
int main(int argc, char** argv)
{
char* input = new char[MAX_PATH];
if (argc == 1)
{
cout << "输入文件路径或拖拽文件至此。" << endl;
cin >> input;
}
else
strcpy(input, argv[1]);
int nRetCode = 0;
HMODULE hModule = ::GetModuleHandle(nullptr);
if (hModule != nullptr)
{
// 初始化 MFC 并在失败时显示错误
if (!AfxWinInit(hModule, nullptr, ::GetCommandLine(), 0))
{
// TODO: 在此处为应用程序的行为编写代码。
wprintf(L"错误: MFC 初始化失败\n");
nRetCode = 1;
}
else
{
// TODO: 在此处为应用程序的行为编写代码。
}
}
else
{
// TODO: 更改错误代码以符合需要
wprintf(L"错误: GetModuleHandle 失败\n");
nRetCode = 1;
}
char* output = new char[MAX_PATH];
strcpy(output, input);
strcat(output, ".Blurred.bmp");
process(input, output);
ShellExecuteA(0, "open", output, "", "", SW_SHOW);
return nRetCode;
}
|
b760256512ed9b4f50aa83a4045879f5df782d10
|
cd9d5422bfab6f6e7c573af09a16626d0a738916
|
/accepted/291.WordPatternII.cpp
|
36855568a0486215aaa4b731caafce37a73c19e0
|
[] |
no_license
|
Lingfei-Li/leetcode
|
dd4bd8365a25ca279b51fc8cc546f44c02c5d7ef
|
36bd3b2a9e679c61962e946901f995142b85efaa
|
refs/heads/master
| 2021-01-19T06:58:57.783787
| 2016-06-21T04:37:58
| 2016-06-21T04:37:58
| 59,934,535
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,586
|
cpp
|
291.WordPatternII.cpp
|
#include"mytest.h"
class Solution {
public:
unordered_map<char, string> dict;
unordered_set<string> st;
bool match(string& s1, string& s2, int p2) {
if(s2.length()-p2 < s1.length()) return false;
for(unsigned int i = 0; i < s1.length(); i ++) {
if(s1[i] != s2[p2+i]) return false;
}
return true;
}
bool solve(string& pattern, int p1, string& str, int p2) {
if(p1 == pattern.length() && p2 == str.length()) return true;
if(dict.count(pattern[p1])){
if(match(dict[pattern[p1]], str, p2)) {
return solve(pattern, p1+1, str, p2+dict[pattern[p1]].length());
}
else {
return false;
}
}
else {
for(unsigned int i = p2; i < str.length(); i ++) { //prune?
string subs = str.substr(p2, i-p2+1);
if(!st.count(subs)){
st.insert(subs);
dict[pattern[p1]] = subs;
if(solve(pattern, p1+1, str, i+1)) return true;
st.erase(subs);
dict.erase(pattern[p1]);
}
}
}
return false;
}
bool wordPatternMatch(string pattern, string str) {
return solve(pattern, 0, str, 0);
}
};
int main() {
srand(time(NULL));
string s1, s2;
while(cin>>s1>>s2){
Solution sol;
cout<<sol.wordPatternMatch(s1, s2)<<endl;
}
return 0;
}
|
cc4b62f45cd1a11aad32de3caed37dd9963d6109
|
aee37b130e559780722394117a7acffe89a2d2b5
|
/src/RectanguLand.Graphics/Objects/Texture.h
|
bab2ed6345a7e4cf36a49f160b6998b2c017c3db
|
[] |
no_license
|
Craftrect/rectangu.land
|
8b240d4038caba4e5a130837701aff4ea426621c
|
a2db3b79fe9324b207a91dfe9bc7da9b3aba3c29
|
refs/heads/master
| 2021-01-18T14:34:12.434823
| 2013-09-28T20:16:12
| 2013-09-28T20:16:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 562
|
h
|
Texture.h
|
#pragma once
#include "ApiObject.h"
namespace Graphics
{
SHARED_FORWARD(Texture);
class Texture : public ApiObject
{
protected:
static TexturePtr gDefaultTexture;
Texture(ApiType type) : ApiObject(type) {
}
virtual void updateData(const void* memory, uint32 size) = 0;
public:
static TexturePtr getDefaultTexture() { return gDefaultTexture; }
virtual void generateMipmaps() = 0;
template<typename T>
void updateData(const std::vector<T>& data) {
updateData(data.data(), data.size() * sizeof(T));
}
};
WEAK_TYPE(Texture);
}
|
9e1c830fcd19719f20ee9a2658877b44a309b028
|
69d1fafb6d949401d57009cbf196c797f607fabf
|
/movingobject.cpp
|
943cd54ba1dac82c4a95c7ca14b9d73eb1e5c358
|
[] |
no_license
|
chvatma2/test-game
|
fc7ac06006f5d27ccd9bdf5b3c73536a3a1bd173
|
eba156803b5f85a1676238e99048d0f3d1a7129e
|
refs/heads/master
| 2020-03-26T18:32:42.568098
| 2015-05-16T16:17:11
| 2015-05-16T16:17:11
| 35,066,104
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 478
|
cpp
|
movingobject.cpp
|
#include "movingobject.h"
MovingObject::MovingObject(const QVector2D &position, GLuint texture, float speed)
: GameObject(position, texture), m_Speed(speed)
{
}
MovingObject::~MovingObject()
{
}
void MovingObject::update(const std::vector<std::string> &levelData, std::vector<GameObject *> objects)
{
}
void MovingObject::collideWithLevel(const std::vector<std::string> &levelData)
{
}
void MovingObject::collideWithObjects(std::vector<GameObject *> objects)
{
}
|
2cacc16e357662fc77ab2653ac55813899212116
|
23d7b35f9c613af0fa059f04694368bf9c48728f
|
/ObjectsTraining/OOP.cpp
|
da1a8fb8a17f769605d00dc483429f7544b23788
|
[] |
no_license
|
PetroniusIsAlive/Projects_uni
|
7eb216e7ad5e3312d8a2af7c4d15b8979ababe3e
|
03a7a8febb9a6aefcffd80daeb123229404f8988
|
refs/heads/master
| 2023-04-09T13:01:15.946257
| 2021-04-03T07:47:51
| 2021-04-03T07:47:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,749
|
cpp
|
OOP.cpp
|
#include <iostream>
#include <cstring>
class BankAccount {
private:
char memberName[20];
char bankNum[10] = "BG";
char subArray[8];
size_t balance = 0;
size_t arrLength(char* arr) {
return strlen(arr);
}
public:
char getMemberName() {
return *memberName;
}
void setMemberName(char data , size_t location) {
memberName[location] = data;
}
char getBankNum() {
return *bankNum;
}
void setBankNum(char data, size_t location) {
bankNum[location] = data;
}
char getSubArray() {
return *subArray;
}
void setSubArray(char data, size_t location) {
subArray[location] = data;
}
size_t getBalance() {
return balance;
}
void setBalance(size_t balance) {
this->balance = balance;
}
BankAccount* makeAccount() {
std::cout << "Fill member name." << std::endl;
std::cin.getline(memberName, 20);
std::cout << "Fill bank num." << std::endl;
std::cin.getline(subArray, 10);
for (int i = 2;i < arrLength(subArray) + 2;++i) {
bankNum[i] = subArray[i - 2];
}
do {
std::cout << "Deposit minimum 500 for account copleation! " << std::endl;
std::cin >> balance;
}
while (balance < 500);
return this;
}
void printData() {
std::cout << std::endl;
std::cout << "Member name: ";
for (int a = 0; a < arrLength(memberName); ++a) {
std::cout<< memberName[a];
}
std::cout << std::endl;
std::cout << "Bank number: ";
for (int i = 0; i < arrLength(bankNum); ++i) {
std::cout<< bankNum[i];
}
std::cout << std::endl;
std::cout << "Balance: " << balance << std::endl;
}
BankAccount* pushOrPull() {
char desition = ' ';
size_t moneyCount;
while (desition != 'n') {
std::cout << "Now you can depozit(enter d) money from the account " << std::endl;
std::cout << "or pull(enter p) money form the account curent balance: " <<balance << std::endl;
std::cout << "or do nothing(n)" << std::endl;
do {
std::cin >> desition;
} while (desition != 'd' && desition != 'p' && desition != 'n');
switch (desition) {
case 'd':
std::cout << "So you want to depozit, ok then pick a number!" << std::endl;
std::cin >> moneyCount;
this->balance += moneyCount;
break;
case 'p':
do {
std::cout << "So you want to pull money, ok then pick a number, but no bigger than the balance! " << "Yout balance: " << balance << std::endl;
std::cin >> moneyCount;
} while (moneyCount > balance);
this->balance -= moneyCount;
break;
case 'n':
std::cout << "You changed your mind? Ok." << std::endl;
break;
}
}
return this;
}
};
int main() {
BankAccount member1;
member1.makeAccount()->pushOrPull()->printData();
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.