blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34
values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | text stringlengths 13 4.23M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
c8ebd8ce7112c93eedae017460503ed47d5bdd6b | C++ | abhidurg/CSE_331_Algorithms_Data_Structures | /cse331project01/QuickSort.h | UTF-8 | 2,261 | 3.6875 | 4 | [] | no_license | /*
* File: QuickSort.h
* Author: Abhiram Durgaraju
*
* Created on September 24, 2017, 8:56 PM
*/
#ifndef _QUICKSORT_H_
#define _QUICKSORT_H_
#include <vector>
#include "InsertionSort.h"
#include <cstdlib>
using namespace std;
/*This function takes 3 inputs: the vecfor reference, the starting index, and
the ending index of the vector. It then returns count, the number of
comparisons that were made in the sorting process*/
long quickSort(vector<int>& vector_to_sort, int start_index, int end_index){
long count = 0; //this tracks the # of comparisons
if (start_index < end_index){ //quicksort ONLY if the indexes are in range
int pivot_index = (rand()% (end_index-start_index)) + start_index;
//cout<<"pivot_index"<<pivot_index<<endl;
int pivot = vector_to_sort[pivot_index]; //choose 1st # as pivot
int partition_index = start_index; //The index before this is partitioned
swap (vector_to_sort[pivot_index], vector_to_sort[end_index]);
//swap the pivot with the last element
for (int i = start_index; i <= end_index - 1; i++){
//for all indices except the last (the pivot after swapped)
if (vector_to_sort[i] <= pivot){
swap(vector_to_sort[i], vector_to_sort[partition_index]);
partition_index += 1; //increment the current partition
}
}
swap (vector_to_sort[end_index], vector_to_sort[partition_index]);
//swap the pivot, which is at the end, with the current partition
count += (end_index - start_index) -1;
//add m-1 to the count where m is the size of the subarray
count += quickSort(vector_to_sort, start_index, partition_index -1 );
count += quickSort(vector_to_sort, partition_index+1, end_index);
//recursive call to quicksort and add those counts as well
}
return count;
}
/*This function takes a vector reference and passes it through another quicksort
function that 3 variables as input */
long quickSort(vector<int>& vector_to_sort){
int start_index = 0;
int end_index = vector_to_sort.vector::size() -1;
long count = quickSort(vector_to_sort, start_index, end_index);
return count;
}
#endif /* QUICKSORT_H */
| true |
9ccf3fd0847375a03d4bb972facb54601cefe925 | C++ | extinctCoder/arduinoBoard | /serialCommunication.ino | UTF-8 | 505 | 2.734375 | 3 | [] | no_license | int data = -1;
void setup() {
pinMode(13, OUTPUT);
Serial.begin(9600);
digitalWrite(13, HIGH);
}
void loop() {
if(Serial.available())
{
data=Serial.read();
if(data=='1'){
Serial.println("turning led on");
digitalWrite(13, HIGH);
Serial.println("led on");
}
else if(data=='0'){
Serial.println("turning led off");
digitalWrite(13, LOW);
Serial.println("led off");
}
else{
Serial.println("wrong command");
}
}
}
| true |
82f4d840464111c79b5e385082da1e16b8f526b8 | C++ | lambertwang/tensor_stuff | /src/nodeOperations/dotproduct.h | UTF-8 | 555 | 2.703125 | 3 | [] | no_license | /**
* DotProduct Class Header
*
*/
#ifndef __DOTPRODUCT_H__
#define __DOTPRODUCT_H__
#include "node/tensorNode.h"
class DotProduct: public TensorNode {
protected:
std::string getDefaultTag();
public:
/**
* Constructor for a DotProduct
*/
DotProduct(std::initializer_list<const TensorNode *> values);
Tensor evaluate() const;
Tensor evaluate(Session *session) const;
/**
* Returns the product of all other inputs
*/
Tensor derivative(const TensorNode *dx, Session *session) const;
};
#endif
| true |
ca26a6a4936183365b9d50f8b92ca70e03c7d7db | C++ | simplegsb/gazengine | /GazEngine-OpenGL/gazengine/scene/OpenGLCamera.cpp | UTF-8 | 2,312 | 2.84375 | 3 | [] | no_license | #include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include "OpenGLCamera.h"
using namespace std;
OpenGLCamera::OpenGLCamera() :
farClippingDistance(1000.0f),
frameHeight(0.0f),
frameWidth(0.0f),
nearClippingDistance(0.1f),
node(NULL)
{
}
float OpenGLCamera::getFarClippingDistance() const
{
return farClippingDistance;
}
float OpenGLCamera::getFrameHeight() const
{
return frameHeight;
}
float OpenGLCamera::getFrameWidth() const
{
return frameWidth;
}
float OpenGLCamera::getNearClippingDistance() const
{
return nearClippingDistance;
}
SimpleTree* OpenGLCamera::getNode()
{
return node;
}
Vector3 OpenGLCamera::getTranslation() const
{
return Vector3();
}
void OpenGLCamera::lookAt(const Vector3& target, const Vector3& up)
{
gluLookAt(0.0f, 0.0f, 0.0f, target.X(), target.Y(), target.Z(), up.X(), up.Y(), up.Z());
}
void OpenGLCamera::setFarClippingDistance(float farClippingDistance)
{
this->farClippingDistance = farClippingDistance;
}
void OpenGLCamera::setFrameHeight(float frameHeight)
{
this->frameHeight = frameHeight;
}
void OpenGLCamera::setFrameWidth(float frameWidth)
{
this->frameWidth = frameWidth;
}
void OpenGLCamera::setNearClippingDistance(float nearClippingDistance)
{
this->nearClippingDistance = nearClippingDistance;
}
void OpenGLCamera::setNode(SimpleTree* node)
{
this->node = node;
}
void OpenGLCamera::setOrthogonal(float width, float height)
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-width / 2, width / 2, -height / 2, height / 2, nearClippingDistance, farClippingDistance);
frameHeight = height;
frameWidth = width;
glMatrixMode(GL_MODELVIEW);
}
void OpenGLCamera::setPerspective(float yAxisFieldOfView, float aspectRatio)
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
float halfYAxisFieldOfView = yAxisFieldOfView / 2.0f;
float unitCircleCos = 1 - pow(cos(halfYAxisFieldOfView), 2.0f);
float unitCircleSin = 1 - pow(sin(halfYAxisFieldOfView), 2.0f);
float sin = (nearClippingDistance / unitCircleCos) * unitCircleSin;
frameHeight = sin * 2.0f;
frameWidth = frameHeight * aspectRatio;
glFrustum(-frameWidth / 2, frameWidth / 2, -frameHeight / 2, frameHeight / 2, nearClippingDistance,
farClippingDistance);
glMatrixMode(GL_MODELVIEW);
}
void OpenGLCamera::setTranslation(const Vector3&)
{
}
| true |
bb789c4c1dbbbba70b33fba268be4fa41c0419c5 | C++ | azevedog/reativos | /azevedog/Exercicio3.ino | UTF-8 | 2,161 | 2.875 | 3 | [] | no_license | /**API CLIENTE/SERVIRDOR*/
void init_();
void button_listen(int pin);
void timer_set(int ms);
void button_changed(int pin, int v);
void timer_expired(void);
/**GERADOR DE EVENTOS*/
struct listElem {
int pin;
int lastVal;
struct listElem* next;
};
typedef struct listElem LIST;
LIST* btnList = NULL;
void button_listen(int pin) {
LIST* novo = (LIST*) malloc(sizeof(LIST));
novo->pin = pin;
novo->lastVal = LOW;
novo->next = btnList;
btnList = novo;
}
int now;
int old;
int wait;
int exit1 = 0;
void timer_set(int ms) {
wait = ms;
//old = millis();
}
int getWait() {
return wait;
}
void loop() {
LIST* current = btnList;
while (current != NULL) {
int pin = current->pin;
int val = digitalRead(current->pin);
if (val != current->lastVal) {
current->lastVal = val;
button_changed(pin, val);
}
current = current->next;
}
now = millis();
if (now - old >= wait) {
old = now;
timer_expired();
}
}
/**OUVINTE*/
int tarefa3LastBtn1 = 0;
int tarefa3ClickStep = 30;
int tarefa3State = LOW;
const int tarefa3Btn1 = 2;
const int tarefa3Btn2 = 3;
const int tarefa3Led = 4;
const int helloLed = 11;
const int helloBtn = 12;
void init_() {
button_listen(tarefa3Btn1);
button_listen(tarefa3Btn2);
button_listen(helloBtn);
timer_set(500);
}
void setup() {
Serial.begin(9600);
pinMode(tarefa3Btn1, INPUT);
pinMode(tarefa3Btn2, INPUT);
pinMode(tarefa3Led, OUTPUT);
pinMode(helloBtn, INPUT);
pinMode(helloLed, OUTPUT);
init_();
}
void button_changed(int pin, int v) {
int ms;
switch (pin) {
case tarefa3Btn1:
tarefa3LastBtn1 = millis();
ms = getWait();
timer_set(ms + tarefa3ClickStep);
break;
case tarefa3Btn2:
Serial.println("HEY");
if (millis() - tarefa3LastBtn1 <= 125) {
exit1 = 1;
digitalWrite(tarefa3Led, HIGH);
}
ms = getWait();
timer_set(ms - tarefa3ClickStep);
break;
case helloBtn:
digitalWrite(helloLed, v);
break;
}
}
void timer_expired(void) {
if (!exit1) {
tarefa3State = ! tarefa3State;
digitalWrite(tarefa3Led, tarefa3State);
}
}
| true |
200864358c2f7774dcba683cdb87af4ce4298716 | C++ | jimsrobot/btcontrol | /BTControl/BTControl.ino | UTF-8 | 13,096 | 2.671875 | 3 | [] | no_license |
/**************************************
*
* REFLOW OVEN BLUETOOTH CONTROLLER
*
****************************************
The reflow profile has a number of stages, these are
built on the android device and the profile is sent to
the board where it gets saved into the EEPROM
To run the profile you can press the button on the board
or you can send a start signal from the android device
The board sends the temperature out and various progress
messages.
********************************************************
* EEPROM Map
********************************************************
!! MAKE SURE YOU SEND STRINGS TO BOARD ALREADY PADDED OUT
!! WITH LEADING ZEROS. YOUR ANDROID/BT SHOULD SUPPLY CORRECTLY
!! FORMATTED STRINGS.
The profile is sent via BT serial and arrives as a string.
The string has the profile name, then the nuber of stages,
then each stage (each stage is 10 bytes)
** First we get profile name and number of stages
** Following is where we store them in the EEPROM
0 to 19 bytes = name of profile (max 20 characters)
49-50 xx = number of stages (max 12)
** Each stage uses 10 Bytes
** Stage 1 is 51 to 60
51 x stage type
52-54 xxx temperature - 000 to 399
55-57 xxx percent rate - 000 to 100
58-60 xxx seconds - 000 to 999
61-70 stage 2
71-80 stage 3
81-90 stage 4
91-100 stage 5
101-110 stage 6
111-120 stage 7
121-130 stage 8
131-140 stage 9
141-150 stage 10
151-160 stage 11
161-170 stage 12
*********************************************************
* Output prefixes:
Output is prefixed byt a 2 character code so you know
what's coming out.
C: Temperature
P: Profile Name
S: Stage number that's starting
D: Profile complete
B: Beep
E: Profile saved to EEPROM
*********************************************************/
#include <SoftwareSerial.h>
#include <itoa.h>
#include <EEPROM.h>
#define DEF_BTBAUD 9600
#define MAX_TIME 2147483647
const byte buttonPin = 0; // the number of the pushbutton pin
const byte rxPin = 4;
const byte txPin = 3;
const byte relayPin = 1; // Digital 1
const byte thermoPin = 1; // Analog 1
//const byte serialDelay = 4; // milliseconds delay to use - reduces serial buffer issues
// Variables will change:
byte relayState = LOW; // the current state of the output pin
byte buttonState = LOW; // the current reading from the input pin
byte lastButtonState = LOW; // the previous reading from the input pin
byte inByte = 0;
int counter = 0;
byte inputStringMax = 145;
// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = millis(); // the last time the output pin was toggled
long debounceDelay = 20; // the debounce time; increase if the output flickers
unsigned long lastStatusSent = 0; // when we last sent the status
int statusInterval = 1500; // millisecs between sending status
// We need to track where we are in the profile stages
int stage_pos = 0; // which stage are we in
byte stage_type = 0; // what type of stage? 1=pause,2=heat,3=beep
int target_temp = 0; // temperature we want to reach
unsigned long stage_end_time = MAX_TIME; // end time for this stage
byte temp_reached = 0; // have we completed the stage?
// Prepare the softwareserial
SoftwareSerial BTSerial(rxPin, txPin); // RX, TX
// the setup routine runs once when you press reset:
void setup() {
BTSerial.begin(9600);
BTSerial.listen();
pinMode(relayPin, OUTPUT); // initialize the digital pins as an output or input.
pinMode(buttonPin, INPUT);
digitalWrite(relayPin, relayState);
lastStatusSent = millis(); // reset the update interval
}
// the loop routine runs over and over again forever:
void loop() {
//Check if we need to send an update via BT
if ((millis() - statusInterval) > lastStatusSent) {
if (lastStatusSent > 3000) {
SendTemperature();
}
//BTSerial.print(F("sp:"));BTSerial.println(lastStatusSent);
lastStatusSent = millis();
}
CheckButtonPress(); // start / stop reflow profile
CheckSerialIn(); // check for uploads of a new profile
// If stage_pos > 0 then we're in the middle of a reflow process.
// A stage can complete on time or on temperature. E.g. we can finish
// after 30 seconds or when we reach 150 degrees C.
if (stage_pos > 0){
// BTSerial.println(F("xxx"));
switch (stage_type){
case 1: // Pause for nnn seconds
if ( stage_end_time < millis() ){
GetNextStage(); // move to next stage
}
break;
case 2: // Heat to nnn degrees, and hold for nnn seconds
// First we need to reach the required temperature and then
// we can finish at the set time
if (target_temp > GetTemperature() ){
digitalWrite(relayPin, 1); // Relay On
}
else
{
digitalWrite(relayPin, 0); // Relay off
temp_reached = 1; // Temperature must be reached to stop
}
if ( (stage_end_time < millis()) && (temp_reached = 1) ){
GetNextStage(); // move to next stage
}
break;
case 3: // return "BEEP"
BTSerial.println(F("B:"));//delay(serialDelay);
GetNextStage(); // move to next stage
break;
}
}
}
// GetNextStage will increment through all the stages
// Stage 0 (zero) will do nothing, so setting
// GetNextStage = 0 will pause any reflow
int GetNextStage(){
// If we're at zero we're just starting, send the stage name
if ( stage_pos == 0 ) {
char profName[20];
for(byte i=0; i<20; i++)
{
// Get a character
profName[i] = EEPROM.read(i);
if(profName[i] == '\0'){
i = 21; //break
}
}
BTSerial.print(F("P:"));
BTSerial.println(profName);
}
stage_pos++;
if ( stage_pos > MaxStages() ) {
// we've finished so reset everything and stop
BTSerial.println(F("reset"));
stage_pos = 0;
stage_type = 0; // what type of stage? 1=pause,2=heat,3=beep
target_temp = 0; // temperature we want to reach
stage_end_time = MAX_TIME; // end time for this stage
BTSerial.println(F("D:")); // Profile done message
}
else
{
// We need to load all the settings for this stage and
// get it started
/** Each stage uses 10 Bytes
** Stage 1 is 51 to 60
51 x stage type
52-54 xxx temperature - 000 to 399
55-57 xxx percent rate - 000 to 100
58-60 xxx seconds - 000 to 999 */
// BTSerial.println(F("get set"));
stage_type = GetEEPROMSetting(0, 1); // what type of stage? 1=pause,2=heat,3=beep
target_temp = GetEEPROMSetting(1, 3); // temperature we want to reach
stage_end_time = millis() + (1000*GetEEPROMSetting(7, 3)); // end time for this stage
// Send the stage number to output
//char stage_out[5];
//itoa(stage_pos,stage_out, 10);
//stage_out[4] = '\0';
BTSerial.print(F("S:"));
//BTSerial.println(stage_out);
BTSerial.println(stage_pos);
}
}
// Get all the EEPROM settings
int GetEEPROMSetting(byte offset, byte len){
int ret_val;
byte eep_pos;
char eep_val[4];
// Stages start at 51 and are 10 bytes long
eep_pos = (stage_pos * 10) + 41 + offset;
eep_val[0] = EEPROM.read(eep_pos + 0);
eep_val[1] = '\0';
eep_val[2] = '\0';
if ( len == 3 ){
eep_val[1] = EEPROM.read(eep_pos + 1);
eep_val[2] = EEPROM.read(eep_pos + 2 );
eep_val[3] = '\0';
}
ret_val = atoi(&eep_val[0]);
return ret_val;
}
int CheckSerialIn(){
if (BTSerial.available() > 0) {
//We have serial data to grab
counter = 0;
char strMsg[inputStringMax];
while ((counter < inputStringMax) && (BTSerial.available() > 0)) {
strMsg[counter] = BTSerial.read();
counter++;
}
strMsg[counter+1] = '\0'; // Null string terminator
// Now that we have the serial data we need to process it
// The string GO means to start the profile.
if ((strMsg[0] == 'G') && (strMsg[1] == 'O')) {
BTSerial.println(F("GO!"));
stage_pos = 0; // start at the beginning
GetNextStage(); // triggers the next stage and starts profile
//ReadFromEEPROM();
//return 2;
}
else //It wasn't "GO" so it must (hopefully) be a profile to save
{
SaveProfileToEEPROM(strMsg, sizeof(strMsg));
}
}
}
void ReadFromEEPROM()
{
char profName[20];
for(byte i=0; i<20; i++)
{
// Get a character
profName[i] = EEPROM.read(i);
if(profName[i] == '\0')
break;
}
// BTSerial.println(profName);
}
void SaveProfileToEEPROM(char *ProfileInfo, int bufsize){
int i = -2; // Count through the profile bits, start at -2 for ease of positioning eeprom
int j = 0; // loop variable
int eeprom_pos = 0;
char *str;
while ((str = strtok_r(ProfileInfo, "[", &ProfileInfo)) != NULL)
{
if (i == -2){
while (j<20 && str[j] != '\0'){
EEPROM.write(j, str[j]);
j++;
}
EEPROM.write(j, '\0');
i++; // Move on to the next delimited string
// Send a message that the EEPROM loaded
BTSerial.print("E:"); //SerialDelay();
BTSerial.println(str); //SerialDelay();
}
else if (i == -1){
// this is the number of stages to save - needs to arrive
// already padded to 2 digits with a leading zero if needed
// BTSerial.println("h11");delay(serialDelay);
EEPROM.write(49, str[0]);
EEPROM.write(50, str[1]);
i++; // Move on to the next part
}
else
{
// this is a stage - 10 bytes of info
eeprom_pos = (i * 10) + 51; // Starting eeprom position
for (int k = 0; k < 10; k++){
EEPROM.write(eeprom_pos + k, str[k]);
}
i++;
}
}
}
void CheckButtonPress(){
// read the state of the switch into a local variable:
byte reading = digitalRead(buttonPin);
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state:
// if the button state has changed:
if (reading != buttonState) {
buttonState = reading;
// stage_pos is zero when we're not in a stage and
// we are idle
if ( stage_pos == 0 ) {
stage_pos = 0; // start at the beginning
GetNextStage(); // triggers the next stage and starts profile
}
else
{
stage_pos = 0; // stops any stages.
digitalWrite(relayPin, 0);
}
}
// set the relay:
digitalWrite(relayPin, relayState);
}
// save the reading. Next time through the loop,
// it'll be the lastButtonState:
lastButtonState = reading;
}
void SendTemperature(){
//Messaging variables
// char strOutCE[7]="C: ";
char strOutTemperature[5];
itoa(GetTemperature(),strOutTemperature, 10);
// for(byte i=0; i<4; i++)
// {
// Get a character
// strOutCE[i+2] = strOutTemperature[i];
// }
// strOutCE[7] = '\0';
BTSerial.print(F("C:"));
BTSerial.println(strOutTemperature);
// BTSerial.println();
}
int GetTemperature(){
// Get the temperature reading
// Each increment = 3.3 / 1024 = 0.00322265625v
int temperature = (analogRead(thermoPin) * 3.3 / 5);
// A bit of safety - cut off relay at 300 C
if ( temperature > 300 ){
digitalWrite(relayPin, 0);
}
return temperature;
}
// The number of stages are written to EEPROM 49 and 50
int MaxStages(){
int num_stages = 0;
char stage_count[3] = "00";
stage_count[0] = EEPROM.read(49);
stage_count[1] = EEPROM.read(50);
num_stages = atoi(&stage_count[0]);
// BTSerial.print("ns:");
// BTSerial.println(num_stages);
return num_stages;
}
/*
void SerialDelay(){
long delay_time = millis() + 200; // millisecs
byte nothing = 0;
while (millis() < delay_time){nothing = 0;}
//BTSerial.println("waiting");
}
*/
// ATMEL ATTINYX5 / ARDUINO
//
// +-\/-+
// Ain0 (D 5) PB5 1| |8 VCC
// Ain3 (D 3) PB3 2| |7 PB2 (D 2) INT0 Ain1
// Ain2 (D 4) PB4 3| |6 PB1 (D 1) pwm1
// GND 4| |5 PB0 (D 0) pwm0
// +----+
| true |
00a2ade0c2f2cf208a8bf1152e976ee26102044e | C++ | CAMILA125/C | /exercicios_lista_5/vogal_ou_consoante.cpp | WINDOWS-1252 | 674 | 3.046875 | 3 | [] | no_license | /*
Escreva um programa em C que leia uma letra e indique se ela uma vogal ou consoante.
Utilize uma estrutura de caso para resolver este problema.
*/
#include<stdio.h>
#include<locale.h>
#include<conio.h>
int main() {
setlocale(LC_ALL,"");
char letra;
printf ("\nEscreva uma letra do alfabeto: ");
scanf ("%s", &letra);
switch (letra) {
case 'a':
printf ("vogal");
break;
case 'e':
printf ("vogal");
break;
case 'i':
printf ("vogal");
break;
case 'o':
printf ("vogal");
break;
case 'u':
printf ("vogal");
break;
default:
printf("consoante");
break;
}
return main ();
}
| true |
0499293711ff4e2e888f75120e1e366adb69fddc | C++ | SolansPuig/Knapsack-Public-Cryptosystem | /recursive_subset_sum.cpp | UTF-8 | 1,588 | 2.9375 | 3 | [] | no_license | #include <iostream>
// #define ITEMS 30
// #define WEIGHT 75
//
// #if ITEMS == 2
// int value[ITEMS] = {9, 3};
// #endif
// #if ITEMS == 4
// int value[ITEMS] = {9, 3, 5, 7};
// #endif
// #if ITEMS == 10
// int value[ITEMS] = {9, 3, 5, 7, 5, 9, 8, 9, 7, 3};
// #endif
// #if ITEMS == 20
// int value[ITEMS] = {9, 3, 5, 7, 5, 9, 8, 9, 7, 3, 8, 4, 8, 2, 1, 0, 9, 8, 4, 2};
// #endif
// #if ITEMS == 30
// int value[ITEMS] = {9, 3, 5, 7, 5, 9, 8, 9, 7, 3, 8, 4, 8, 2, 1, 0, 9, 8, 4, 2, 5, 6, 7, 1, 1, 0, 1, 5, 1, 4};
// #endif
// #if ITEMS == 100
// int value[ITEMS] = {9, 3, 5, 7, 5, 9, 8, 9, 7, 3, 8, 4, 8, 2, 1, 0, 9, 8, 4, 2, 5, 6, 7, 1, 1, 0, 1, 5, 1, 4, 4, 3, 1, 3, 1, 0, 7, 3, 5, 2, 5, 8, 1, 7, 1, 8, 8, 6, 5, 1, 2, 4, 4, 1, 4, 9, 6, 7, 4, 7, 5, 1, 7, 1, 0, 7, 5, 9, 1, 2, 7, 9, 2, 4, 2, 9, 7, 2, 4, 2, 8, 9, 3, 9, 1, 0, 1, 0, 2, 4, 5, 5, 1, 0, 4, 9, 2, 5, 6, 3};
// #endif
int value[10] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int weight1 = 76;
int weight2 = 81;
int weight3 = 0;
bool subset_sum(int i, int acc, int w) {
if (i <= 0) return false;
if (acc == w) return true;
int new_acc = acc + value[i-1];
if (new_acc > w) return subset_sum(i-1, acc, w);
bool s1 = subset_sum(i-1, new_acc, w);
bool s2 = subset_sum(i-1, acc, w);
if (s1 || s2) return true;
else return false;
}
int main() {
std::cout << subset_sum(10, 0, weight1) << std::endl; // should return true
std::cout << subset_sum(10, 0, weight2) << std::endl; // should return false
std::cout << subset_sum(10, 0, weight3) << std::endl; // 0 always true
return 0;
}
| true |
0515c68eb35c176fc6671ca370efa5c7ce99ded9 | C++ | wilseypa/warped2-models | /models/wildfire/wildfire.hpp | UTF-8 | 5,233 | 3.03125 | 3 | [
"MIT",
"GPL-3.0-only"
] | permissive | //Implementation of a WildFire Simulation
#ifndef WILDFIRE_HPP_DEFINED
#define WILDFIRE_HPP_DEFINED
#include <string>
#include <vector>
#include "warped.hpp"
/* Status of the fire */
enum cell_status_t {
UNBURNT,
BURNING,
BURNT_OUT
};
WARPED_DEFINE_LP_STATE_STRUCT(CellState) {
cell_status_t burn_status_;
unsigned int heat_content_;
};
/* Wildfire events */
enum cell_event_t {
RADIATION_TIMER,
RADIATION,
IGNITION,
PEAK
};
/* The direction of the spread of fire from the currently burning LP */
enum direction_t {
NORTH,
NORTH_EAST,
EAST,
SOUTH_EAST,
SOUTH,
SOUTH_WEST,
WEST,
NORTH_WEST,
DIRECTION_MAX
};
/*! Class Definition of a Wildfire event */
class CellEvent : public warped::Event {
public:
CellEvent() = default;
CellEvent( const std::string& receiver_name,
const cell_event_t type,
const unsigned int heat_content,
const unsigned int timestamp )
: receiver_name_(receiver_name),
type_(type),
heat_content_(heat_content),
ts_(timestamp) {}
const std::string& receiverName() const { return receiver_name_; }
unsigned int timestamp() const { return ts_; }
unsigned int size() const {
return receiver_name_.length() +
sizeof(type_) +
sizeof(heat_content_) +
sizeof(ts_);
}
std::string receiver_name_; /*! Name of the LP that is recieving the event */
cell_event_t type_; /*! The type of event being sent */
unsigned int heat_content_; /*! Heat being sent in the event */
unsigned int ts_; /*! Timestamp used by the kernel that identifies when the event takes place */
WARPED_REGISTER_SERIALIZABLE_MEMBERS(cereal::base_class<warped::Event>(this),
receiver_name_, type_, heat_content_, ts_)
};
/*! Class that will hold all of the attributes of the LP's */
class Cell : public warped::LogicalProcess{
public:
Cell( const unsigned int num_rows,
const unsigned int num_cols,
unsigned char **combustible_map,
const unsigned int ignition_threshold,
const unsigned int growth_rate,
const unsigned int peak_threshold,
const unsigned int radiation_rate,
const unsigned int burnout_threshold,
const unsigned int heat_content,
const unsigned int index )
: LogicalProcess(lp_name(index)),
state_(),
num_rows_(num_rows),
num_cols_(num_cols),
ignition_threshold_(ignition_threshold),
growth_rate_(growth_rate),
peak_threshold_(peak_threshold),
radiation_rate_(radiation_rate),
burnout_threshold_(burnout_threshold),
index_(index) {
/* Initialize the state variables */
state_.burn_status_ = UNBURNT;
state_.heat_content_ = heat_content;
/* Populate the connection_matrix */
for (unsigned int direction = NORTH; direction < DIRECTION_MAX; direction++) {
connection_[direction] = neighbor_conn( (direction_t)direction, combustible_map );
}
}
/*! Function to start the fire by comparing the heat content of the LP with
that LP's ignition threshold */
virtual std::vector<std::shared_ptr<warped::Event> > initializeLP() override;
/*! Function that will handle all events being sent to and from LP's */
virtual std::vector<std::shared_ptr<warped::Event> > receiveEvent(const warped::Event&) override;
/*! Returns the state of Burn that the LP in */
virtual warped::LPState& getState() override { return this->state_; }
CellState state_;
/*! Simple function that returns the name of an LP using th index */
static inline std::string lp_name( const unsigned int );
const unsigned int num_rows_; /*! Number of rows in the vegetation grid */
const unsigned int num_cols_; /*! Number of columns in the vegetation grid */
const unsigned int ignition_threshold_; /*! Minimum heat content needed to ignite an LP */
const unsigned int growth_rate_; /*! Speed at which the fire grows in an LP */
const unsigned int peak_threshold_; /*! Maximum heat content threshold of an LP */
const unsigned int radiation_rate_; /*! Heat radiated out by a burning LP in unit time */
const unsigned int burnout_threshold_; /*! Heat content threshold for a burnt out LP */
bool connection_[DIRECTION_MAX]; /*! Boolean that returns true when an LP exists in adjacent node */
const unsigned int index_; /*! Unique LP number that is used by the kernel to find an certain LP */
std::string find_cell( direction_t direction ); /* Function to find an adjacent cell in a certain direction */
/*! Function to find whether connection exits to a neighbor in a certain given direction */
bool neighbor_conn( direction_t direction, unsigned char **combustible_map );
};
#endif
| true |
a9d126199033065dbfc41992b07d6e1ce49d529f | C++ | wolfen601/SoftwareQuality | /part3/login.cpp | UTF-8 | 1,665 | 3.796875 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
string* findUser(string username);
string removePadding(string token);
//function asks user to enter their existing username, then calls the findUser function
//if the function does not return null the currentUser vector is returned to the main
//file so the current users information can be used in other functions
//sets the username as '--error--' if the username is not found
string* login() {
string username;
string* currentUser = new string[3];
cout << "Enter username: ";
cin >> username;
currentUser = findUser(username);
if (currentUser[0] != "--error--")
{
cout << currentUser[0] << " " << currentUser[1] << " " << currentUser[2] << endl;
return currentUser;
} else {
return currentUser;
}
}
//Reads the currentUsers.txt file line by line and tokenizes each line
//at the space, if the first token of the line(the username) mathes the
//entered username then the username, account type and account balance
//are stored in the currentUsers vector and returned to the login function
//otherwise NULL is returned
string* findUser(string username) {
string* currentUser = new string[3];
ifstream inputfile("currentUsers.txt");
string fileLine;
string token;
while(!inputfile.eof()) {
getline(inputfile, fileLine);
istringstream iss(fileLine);
for (int i = 0; i < 3; ++i) {
getline(iss,token,' ');
token = removePadding(token);
currentUser[i] = token;
}
if (username == currentUser[0]) {
inputfile.close();
return currentUser;
}
}
inputfile.close();
currentUser[0] = "--error--";
return currentUser;
} | true |
9e7eb05adce078cfef5be7e549ae0bf575cd1d9a | C++ | walkupup/hybrid-astar-planner | /test.cpp | UTF-8 | 509 | 2.6875 | 3 | [] | no_license | #include "include/Planner.hpp"
State getStartState();
State getTargetState();
int main(){
Map *map = new Map();
State *start = new State(700, 100, 36);// getStartState();
State *target = new State(100, 600, 18);// getTargetState();
Planner astar;
astar.plan(*start, *target, *map);
delete map;
delete start;
delete target;
}
State getStartState()
{
//to do: read from yml file
return State(700, 100, 36);
}
State getTargetState()
{
//to do: read from yml file
return State(100, 600, 18);
} | true |
fb209498d59e1ea3f8fe6e6b53c7aa2467901d36 | C++ | rjxircgz/programming | /IT 211 - Data Structures/ProgrammingExercise7/main.cpp | UTF-8 | 581 | 2.59375 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#include "queue.h"
void main()
{
Q *a=NULL;
Q2 *b=NULL;
int c;
for(int n=1;n<=4;n++)
{
printf("enter P%d:",n);
scanf("%d",&c);
enqueue(&a,c);
enqueue(&b,n);
}
printf("enter time quantum: ");
scanf("%d",&c);
while(!isEmpty2(a))
{
int sub=dequeue(&a)-c;
int num=dequeue(&b);
if(sub>0) {
enqueue(&a,sub);
enqueue(&b,num);
printf("p%d=%d\n",num,sub);
}
}
getch();
}
| true |
f0753c565a1b4999de9ec9842b40f3731932a366 | C++ | Alerrom/programming_2_sem_ITMO | /laba6.cpp | UTF-8 | 9,752 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <map>
#include <fstream>
#include <sstream>
/*
Some tips:
colors
WWW
WWW
WWW
OOO GGG RRR BBB
OOO GGG RRR BBB
OOO GGG RRR BBB
YYY
YYY
YYY
sides:
U
L F R B
D
0
1 2 3 4
5
side:
0 1 2
7 x 3
6 5 4
Now every side is uint32_t:
4 bits per square - 0000 0000 0000 0000 0000 0000 0000 0000
indices of sides -- 0 1 2 3 4 5 6 7
*/
enum Rotation {
U = 2, Up = -2, U2 = 4,
D = 3, Dp = -3, D2 = 9,
F = 5, Fp = -5, F2 = 25,
B = 7, Bp = -7, B2 = 49,
L = 11, Lp = -11, L2 = 121,
R = 13, Rp = -13, R2 = 169
};
char print_color(uint32_t i) {
if (i == 0)
return 'W';
else if (i == 1)
return 'O';
else if (i == 2)
return 'G';
else if (i == 3)
return 'R';
else if (i == 4)
return 'B';
else if (i == 5)
return 'Y';
else
return ' ';
}
class Cube {
public:
Cube() {
sides[0] = 0x00000000;
sides[1] = 0x11111111;
sides[2] = 0x22222222;
sides[3] = 0x33333333;
sides[4] = 0x44444444;
sides[5] = 0x55555555;
}
Cube(const Cube& cube) {
for (size_t i = 0; i < 6; ++i)
this->sides[i] = cube.sides[i];
}
Cube(uint32_t sides[6]) {
for (size_t i = 0; i < 6; ++i)
this->sides[i] = sides[i];
}
Cube& operator=(const Cube& other) {
for (size_t i = 0; i < 6; ++i)
sides[i] = other.sides[i];
return *this;
}
friend std::ostream& operator<<(std::ostream&, const Cube&);
uint32_t get_val(size_t side, size_t index) {
return (sides[side] & (0x0000000F << (index * 4))) >> (index * 4);
}
void set_val(size_t side, size_t index, uint32_t new_val) {
sides[side] &= ~(0x0000000F << (index * 4));
sides[side] |= new_val << (index * 4);
}
uint32_t get_side(size_t index) {
return sides[index];
}
void up(bool reverse = false) {
for (size_t count = 0; count < (reverse ? 3 : 1); ++count) {
rotate(0);
uint32_t mask = 0x00000FFF;
uint32_t temp = sides[1] & mask;
for (size_t j = 1; j < 4; ++j) {
sides[j] &= ~mask;
sides[j] |= sides[j + 1] & mask;
}
sides[4] &= ~mask;
sides[4] |= temp;
}
}
void down(bool reverse = false) {
for (size_t count = 0; count < (reverse ? 3 : 1); ++count) {
rotate(5);
uint32_t mask = 0x0FFF0000;
uint32_t temp = sides[4] & mask;
for (size_t j = 4; j > 1; --j) {
sides[j] &= ~mask;
sides[j] |= sides[j - 1] & mask;
}
sides[1] &= ~mask;
sides[1] |= temp;
}
}
void left(bool reverse = false) {
for (size_t count = 0; count < (reverse ? 3 : 1); ++count) {
rotate(1);
uint32_t t[3];
for (size_t i = 0; i < 3; ++i)
t[i] = get_val(4, i + 2);
for (size_t i = 6; i <= 8; ++i) {
set_val(4, i - 4, get_val(5, i % 8));
set_val(5, i % 8, get_val(2, i % 8));
set_val(2, i % 8, get_val(0, i % 8));
set_val(0, i % 8, t[i - 6]);
}
}
}
void right(bool reverse = false) {
for (size_t count = 0; count < (reverse ? 3 : 1); ++count) {
rotate(3);
uint32_t t[3];
for (size_t i = 0; i < 3; ++i)
t[i] = get_val(4, (i + 6) % 8);
for (size_t i = 2; i <= 4; ++i) {
set_val(4, (i + 4) % 8, get_val(0, i));
set_val(0, i, get_val(2, i));
set_val(2, i, get_val(5, i));
set_val(5, i, t[i - 2]);
}
}
}
void front(bool reverse = false) {
for (size_t count = 0; count < (reverse ? 3 : 1); ++count) {
rotate(2);
uint32_t t[3];
for (size_t i = 0; i < 3; ++i)
t[i] = get_val(0, i + 4);
for (size_t i = 0; i < 3; ++i) {
set_val(0, i + 4, get_val(1, i + 2));
set_val(1, i + 2, get_val(5, i));
set_val(5, i, get_val(3, (i + 6) % 8));
set_val(3, (i + 6) % 8, t[i]);
}
}
}
void back(bool reverse = false) {
for (size_t count = 0; count < (reverse ? 3 : 1); ++count) {
rotate(4);
uint32_t t[3];
for (size_t i = 0; i < 3; ++i)
t[i] = get_val(0, i);
for (size_t i = 0; i < 3; ++i) {
set_val(0, i, get_val(3, i + 2));
set_val(3, i + 2, get_val(5, i + 4));
set_val(5, i + 4, get_val(1, (i + 6) % 8));
set_val(1, (i + 6) % 8, t[i]);
}
}
}
bool solved() {
return sides[0] == 0x00000000 &&
sides[1] == 0x11111111 &&
sides[2] == 0x22222222 &&
sides[3] == 0x33333333 &&
sides[4] == 0x44444444 &&
sides[5] == 0x55555555;
}
void combo_move(std::vector<Rotation>& data) {
for (auto com : data) {
switch (com)
{
case Rotation::U:
up();
break;
case Rotation::Up:
up(true);
break;
case Rotation::U2:
for (size_t i = 0; i < 2; ++i)
up();
break;
case Rotation::D:
down();
break;
case Rotation::Dp:
down(true);
break;
case Rotation::D2:
for (size_t i = 0; i < 2; ++i)
down();
break;
case Rotation::F:
front();
break;
case Rotation::Fp:
front(true);
break;
case Rotation::F2:
for (size_t i = 0; i < 2; ++i)
front();
break;
case Rotation::B:
back();
break;
case Rotation::Bp:
back(true);
break;
case Rotation::B2:
for (size_t i = 0; i < 2; ++i)
back();
break;
case Rotation::L:
left();
break;
case Rotation::Lp:
left(true);
break;
case Rotation::L2:
for (size_t i = 0; i < 2; ++i)
left();
break;
case Rotation::R:
right();
break;
case Rotation::Rp:
right(true);
break;
case Rotation::R2:
for (size_t i = 0; i < 2; ++i)
right();
break;
}
}
}
private:
uint32_t sides[6] = { 0, 0, 0, 0, 0, 0 };
uint32_t get_color(size_t side, size_t row, size_t col) const {
if (row == 0)
return (sides[side] & (0x0000000F << (col * 4))) >> (col * 4);
if (row == 1) {
if (col == 0)
return (sides[side] & 0xF0000000) >> 28;
if (col == 1)
return side;
if (col == 2)
return (sides[side] & 0x0000F000) >> 12;
return 0xFFFFFFFF;
}
if (row == 2)
return (sides[side] & (0x0F000000 >> (col * 4))) >> (24 - col * 4);
return 0xFFFFFFFF;
}
void rotate(size_t side) {
uint32_t temp = (sides[side] & 0xFF000000) >> 24;
sides[side] <<= 8;
sides[side] |= temp;
}
};
std::ostream& operator<<(std::ostream& out, const Cube& cube) {
for (size_t i = 0; i < 3; ++i) {
out << " ";
for (size_t j = 0; j < 3; ++j) {
out << print_color(cube.get_color(0, i, j));
}
out << '\n';
}
for (size_t i = 0; i < 3; ++i) {
for (size_t side = 1; side <= 4; ++side) {
for (size_t j = 0; j < 3; ++j)
out << print_color(cube.get_color(side, i, j));
out << ' ';
}
out << '\n';
}
for (size_t i = 0; i < 3; ++i) {
out << " ";
for (size_t j = 0; j < 3; ++j) {
out << print_color(cube.get_color(5, i, j));
}
out << '\n';
}
return out;
}
void commands() {
std::cout << "Here some commands you can use during session:\n";
std::cout << "load + f. name - load your cube\n";
std::cout << "save + f. name - save your cube\n";
std::cout << "print - show your cube\n";
std::cout << "new - create new cube\n";
std::cout << "rotate + ... - use basics commands to your cube\n";
std::cout << "solve - find solution of your cube\n";
std::cout << "exit - stop programm\n";
}
class Manager {
public:
Manager() {
turns_to_strings = {
{U, "U"}, {Up, "Up\'"}, {U2, "U2"},
{L, "B"}, {Lp, "Lp\'"}, {L2, "L2"},
{F, "F"}, {Fp, "Fp\'"}, {F2, "F2"},
{R, "R"}, {Rp, "Rp\'"}, {R2, "R2"},
{B, "B"}, {Bp, "Bp\'"}, {B2, "B2"},
{D, "D"}, {Dp, "Dp\'"}, {D2, "D2"}
};
strings_to_turns = {
{"U", U}, {"U\'", Up}, {"U2", U2},
{"L", B}, {"L\'", Lp}, {"L2", L2},
{"F", F}, {"F\'", Fp}, {"F2", F2},
{"R", R}, {"R\'", Rp}, {"R2", R2},
{"B", B}, {"B\'", Bp}, {"B2", B2},
{"D", D}, {"D\'", Dp}, {"D2", D2}
};
}
void start() {
std::cout << "Hello man!\n";
commands();
std::string comm1, comm2;
while (true) {
std::cout << ">>> ";
std::cin >> comm1;
if (comm1 == "load") {
std::cin >> comm2;
load_cube(comm2);
}
else if (comm1 == "save") {
std::cin >> comm2;
save_cube(comm2);
}
else if (comm1 == "print") {
std::cout << cube << '\n';
}
else if (comm1 == "new") {
cube = Cube();
std::cout << cube << '\n';
}
else if (comm1 == "rotate") {
std::getline(std::cin, comm2);
auto rot = parse_turns(comm2);
cube.combo_move(rot);
std::cout << cube << '\n';
}
else if (comm1 == "solve") {
//give_solution
std::cout << "Sorry, doesn't work yet:(\n";
}
else if (comm1 == "exit") {
std::cout << "See you later!\n";
break;
}
else {
std::cout << "Wrong command\n";
}
}
}
private:
Cube cube;
std::map<Rotation, std::string> turns_to_strings;
std::map<std::string, Rotation> strings_to_turns;
void load_cube(const std::string& fname) {
std::ifstream fin(fname);
if (!fin.good()) {
fin.close();
std::cout << "file \"" << fname << "\" not found\n";
return;
}
uint32_t sides[6];
for (size_t i = 0; i < 6; ++i)
fin >> sides[i];
cube = Cube(sides);
fin.close();
}
void save_cube(const std::string& fname) {
std::ofstream fout(fname);
for (size_t i = 0; i < 6; ++i)
fout << cube.get_side(i) << '\n';
fout.close();
}
std::vector<Rotation> parse_turns(const std::string& line) {
std::stringstream ss;
std::vector<Rotation> rot;
ss << line;
std::string turn;
while (ss >> turn)
rot.push_back(strings_to_turns[turn]);
return rot;
}
};
int main() {
Manager m;
m.start();
return 0;
} | true |
bc7901bf55335d848a6db9961d5ce833ab0ead6d | C++ | tihmstar/rb3converter | /rb3converter/main.cpp | UTF-8 | 3,204 | 2.640625 | 3 | [] | no_license | //
// main.cpp
// rb3converter
//
// Created by tihmstar on 14.12.20.
//
#include <iostream>
#include "ConvertMogg.hpp"
#include "ConvertPNG.hpp"
#include "ConvertMid.hpp"
#include "STFS.hpp"
#include "dtaParser.hpp"
#include <libgeneral/macros.h>
#include <getopt.h>
#include "songsManager.hpp"
static struct option longopts[] = {
{ "help", no_argument, NULL, 'h' },
{ "klic", required_argument, NULL, 'k' },
{ "rap", required_argument, NULL, 'p' },
{ "region", required_argument, NULL, 'r' },
{ "threads", required_argument, NULL, 'j' },
{ NULL, 0, NULL, 0 }
};
void cmd_help(){
printf("Usage: rb3converter <CON dir> <PS3 dir>\n");
printf("Converts RB3 XBOX songs to PS3 songs\n\n");
printf(" -h, --help\t\t\tprints usage information\n");
printf(" -k, --klic <path>\tPath to klic.txt\n");
printf(" -p, --rap <path>\tPath to .rap\n");
printf(" -r, --region <reg>\tSet region to 'pal' or 'ntsc'\n");
printf(" -j, --threads <num>\tSet the number of threads to use\n");
}
int main_r(int argc, const char * argv[]) {
info("%s", VERSION_STRING);
int optindex = 0;
int opt = 0;
const char *condir = NULL;
const char *ps3dir = NULL;
const char *klicPath = NULL;
const char *rapPath = NULL;
int threads = 1;
ConvertMid::Region region = ConvertMid::Region_undefined;
while ((opt = getopt_long(argc, (char* const *)argv, "hk:p:r:j:", longopts, &optindex)) > 0) {
switch (opt) {
case 'h':
cmd_help();
return 0;
case 'k': //long-opt klic
klicPath = optarg;
break;
case 'p': //long-opt rap
rapPath = optarg;
break;
case 'j': //long-opt threads
threads = atoi(optarg);
break;
case 'r': //long-opt region
if (strcasecmp(optarg, "pal") == 0) {
region = ConvertMid::Region_PAL;
} else if (strcasecmp(optarg, "ntsc") == 0) {
region = ConvertMid::Region_NTSC;
} else {
reterror("unknown region '%s'",optarg);
}
break;
default:
cmd_help();
return -1;
}
}
retassure(region != ConvertMid::Region_undefined, "Error: region not set");
if (argc-optind == 2) {
argc -= optind;
argv += optind;
condir = argv[0];
ps3dir = argv[1];
}else{
cmd_help();
return -2;
}
songsManager mgr(condir,ps3dir);
if (threads > 1) {
info("Setting threads to %d",threads);
mgr.setThreads(threads);
}
mgr.convertCONtoPS3(klicPath, rapPath, region);
return 0;
}
int main(int argc, const char * argv[]) {
#ifdef DEBUG
return main_r(argc, argv);
#else
try {
return main_r(argc, argv);
} catch (tihmstar::exception &e) {
printf("%s: failed with exception:\n",PACKAGE_NAME);
e.dump();
return e.code();
}
#endif
}
| true |
4fd2fe672e52872b53076b00cd0b9648eecd5e08 | C++ | Kahila/oop_cpp | /basicOOP/basic.h | UTF-8 | 1,234 | 3.421875 | 3 | [] | no_license | #ifndef BASIC_H_INCLUDED
#define BASIC_H_INCLUDED
#include <cstdlib>
#include <sstream>
#include <iostream>
using namespace std;
struct RGBColor
{
int intRed;
int intBlue;
int intGreen;
};
enum StatusCode {SUCCESS,FAIL};
///the class that will be used for abstraction
class Image
{
public:
Image();///default constructor
Image(int intRows, int intCols);///perameterised constructor
string toPPM();///method that will return a string with the RGB colors
///accessor methods
int getRows() const;
int getCols() const;
RGBColor getPixel(int intRows, int intCols, RGBColor color) const;
///mutator method
void setPixels(int intRows, int intClo, RGBColor Colors);
///setting constant value for total rows, columns and the max size
static const int D_Rows = 600;
static const int D_Cols = 800;
static const int Max_size = 100000;
///destructor
~Image();
private:
///method that will be used to check if the given value is within the rang of rows and columns
void enforceRange(int intValue, int intMin, int intMax) const;
RGBColor **_pixels;
int _rows;
int _cols;
};
#endif // BASIC_H_INCLUDED
| true |
e91b014673165bfeb38eb8733b26cc6e868d6703 | C++ | tectronics/cashplusplus | /accountmodel.cpp | UTF-8 | 2,394 | 2.546875 | 3 | [] | no_license | #include "accountmodel.h"
#include "cashplusplus.h"
AccountModel::AccountModel(QObject* parent)
: QSqlRelationalTableModel(parent, QSqlDatabase::database(CashPlusPlus::DB_NAME))
{
setTable("accounts");
setEditStrategy(OnRowChange);
setSort(1, Qt::AscendingOrder);
setRelation(2, QSqlRelation("account_types", "id", "name"));
setHeaderData(0, Qt::Horizontal, tr("ID"));
setHeaderData(1, Qt::Horizontal, tr("Name"));
setHeaderData(2, Qt::Horizontal, tr("Type"));
setHeaderData(3, Qt::Horizontal, tr("Balance"));
select();
}
void AccountModel::addAccount()
{
submitAll();
QSqlQuery q(database());
q.prepare("INSERT INTO accounts VALUES (NULL, ?, ?, ?)");
q.addBindValue("<New Account>");
q.addBindValue(CashPlusPlus::CASH);
q.addBindValue(0.0);
q.exec();
q.finish();
select();
}
void AccountModel::deleteAccounts(const QModelIndexList& currentSelection)
{
submitAll();
setEditStrategy(OnManualSubmit);
for (int i = 0; i < currentSelection.count(); ++i)
{
if (currentSelection.at(i).column() != 0)
{
continue;
}
int id = currentSelection.at(i).model()->index(currentSelection.at(i).row(), 0).data().toInt();
QSqlQuery q(database());
q.prepare("DELETE FROM transactions WHERE account_id = ?");
q.addBindValue(id);
q.exec();
q.exec("VACUUM");
removeRow(currentSelection.at(i).row());
}
submitAll();
setEditStrategy(OnRowChange);
}
QPair<int,int> AccountModel::ndAccounts()
{
int domerAccount = -1;
int flexAccount = -1;
QSqlQuery q(database());
q.exec("SELECT id, type FROM accounts");
while(q.next())
{
int type = q.value(1).toInt();
if (CashPlusPlus::DOMER == type)
{
domerAccount = q.value(0).toInt();
}
else if (CashPlusPlus::FLEX == type)
{
flexAccount = q.value(0).toInt();
}
}
return QPair<int,int>(domerAccount,flexAccount);
}
void AccountModel::updateNDBalances(double domer, double flex)
{
QPair<int,int> accounts = ndAccounts();
int domer_id = accounts.first;
int flex_id = accounts.second;
QSqlQuery q(database());
q.prepare("UPDATE accounts SET amount = ? WHERE id = ?");
if (domer_id > -1)
{
q.addBindValue(domer);
q.addBindValue(domer_id);
q.exec();
}
if (flex_id > -1)
{
q.addBindValue(flex);
q.addBindValue(flex_id);
q.exec();
}
select();
}
| true |
0d021fbcdcd6215cd50b64f7e162ac6676d3e1eb | C++ | Angelay2/2020-6-3 | /OJ.cpp | GB18030 | 875 | 3.6875 | 4 | [] | no_license | //#include <stdio.h>
//#include <stdlib.h>
//#include <iostream>
//#include <vector>
//
//using std::cout;
//using std::endl;
//using std::vector;
//using std::string;
//// ֻ(byte short int long float double boolean char)ͣͰ
///*
//1. ֻһε
//һǿ飬ijԪֻһ⣬ÿԪؾΡҳǸֻһεԪء( Χfor)
//*/
//// õvector͵ĵ
//class Solution{
//public:
// //
// int singleNumber(vector<int>& nums) {
//
// }
// // Χfor
// for (const)
//};
///*
//2.
//һǸ numRowsǵǰ numRows
//*/
//class Solution {
//public:
// vector<vector<int>> generate(int numRows) {
//
// }
//}; | true |
d5d842783a1a5321e70602fdb87d5ba9bcf9dc17 | C++ | Mityai/contests | /camps/lksh-2014/day7/build-tree.cpp | UTF-8 | 1,173 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cstdlib>
typedef long long ll;
using namespace std;
struct TNode {
int L, R;
int key;
};
TNode tree[1000000];
int a[30000];
void buildTree(int root, int L, int R) {
tree[root].L = L;
tree[root].R = R;
if (R - L == 1) {
tree[root].key = a[L];
return;
}
int M = (L + R) / 2;
buildTree(2 * root, L, M);
buildTree(2 * root + 1, M, R);
tree[root].key = min(tree[2 * root].key, tree[2 * root + 1].key);
}
int main() {
freopen("build-tree.in", "r", stdin);
freopen("build-tree.out", "w", stdout);
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
buildTree(1, 0, n);
printf("%d\n", 2 * n - 1);
int cnt = 0, i = 0;
while (cnt < 2 * n - 1) {
++i;
if (tree[i].L == 0 && tree[i].R == 0) {
continue;
}
printf("%d %d %d %d ", i, tree[i].L, tree[i].R, tree[i].key);
if (tree[i].R - tree[i].L == 1) {
printf("%d %d\n", -1, -1);
} else {
printf("%d %d\n", 2 * i, 2 * i + 1);
}
++cnt;
}
} | true |
cf67259a46e282309df753b5b4f610560a902acb | C++ | mapenghui/guessGame | /guessGameTest/guessGame.h | UTF-8 | 1,982 | 3.828125 | 4 | [] | no_license | /**
*Date:2016-06-27
*Author:Joe
*Function:Guess the number the program generates randomly
**/
#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
/**
*generate a random integer number between 0 and 19.
*input:null
*output:randomNumber
**/
int randomNumber;
int generateRanomNumber() {
srand((unsigned)time(NULL));
int randomNumber = rand()%20;
return randomNumber;
}
/**
*Read the number user inputs.
*input:null
*output:inputNumber
**/
int readUserNumber() {
int inputNumber;
cin >> inputNumber;
cout << endl;
while(cin.fail()) {
cout << "The number you input is invalid, please input again:";
cin.clear();
cin.ignore();
cin >> inputNumber;
cout << endl;
}
return inputNumber;
}
/**
*hint user to input an integer number between 0 and 19.
*input:null
*output:hint string
**/
void interactWithUser() {
cout << "Please an integer number between 0 and 19:";
}
/**
*Compare random number the program generates with user inputs.
*input:randomNumber,inputNumber
*output:0/1/2
**/
int isEqual(int randomNumber,int inputNumber) {
if(randomNumber == inputNumber)
return 0;
else if(randomNumber > inputNumber)
return 1;
else
return 2;
}
/**
*hint user to input an integer number between 0 and 19.
*input:compare result(0/1/2).
*output:hint string
**/
void interactWithUserAfterCompare(int flag) {
if(flag == 0)
cout << "Congratulate!you guess it" << endl;
else if( flag == 1) {
cout << "The number you input is smaller, please input again:";
int inputNumber = readUserNumber();
int flag0 = isEqual(randomNumber,inputNumber);
interactWithUserAfterCompare(flag0);
}
else {
cout << "The number you input is bigger, please input again:";
int inputNumber = readUserNumber();
int flag0 = isEqual(randomNumber,inputNumber);
interactWithUserAfterCompare(flag0);
}
}
| true |
91fd8b9380e882a46be381e1588d0de07b5f579e | C++ | mequint/Cpp-Samples | /Quintessence/Sandbox/src/TestState.cpp | UTF-8 | 4,074 | 2.546875 | 3 | [
"MIT"
] | permissive | #include "TestState.h"
#include <iostream>
#include "qe/Animation/SpriteLoader.h"
#include "qe/Context.h"
#include "qe/ECS/SystemManager.h"
#include "qe/State/StateManager.h"
#include "qe/Resource/FontManager.h"
#include "qe/Resource/TextureManager.h"
#include "qe/Utilities/Utilities.h"
#include "qe/Window/Window.h"
#include "ECS/ECSTypes.h"
#include "ECS/Components//Components.h"
#include "StateTypes.h"
TestState::TestState(qe::StateManager * stateManager) :
BaseState(stateManager), m_animation(nullptr) {
}
void TestState::onCreate() {
std::cout << "Creating TestState" << std::endl;
// Setup texture
auto textures = m_stateManager->getContext()->m_textureManager;
auto texture = textures->getResource("PacMan");
auto animatedTexture = textures->getResource("AnimatedPacMan");
//m_sprite.setTexture(*texture);
//m_sprite.setOrigin(texture->getSize().x / 2.0f, texture->getSize().y / 2.0f);
// Setup text
auto fonts = m_stateManager->getContext()->m_fontManager;
m_text.setFont(*fonts->getResource("Game"));
m_text.setCharacterSize(18);
m_text.setString("Pac Man");
m_text.setOrigin(m_text.getGlobalBounds().width / 2.0f, m_text.getGlobalBounds().height / 2.0f);
m_text.setPosition(400.0f, 300.0f + texture->getSize().y);
// Setup entity
auto entityManager = m_stateManager->getContext()->m_entityManager;
qe::Bitmask bits;
bits.set(static_cast<qe::ComponentType>(Component::Position));
bits.set(static_cast<qe::ComponentType>(Component::Sprite));
int id = entityManager->addEntity(bits);
auto position = entityManager->getComponent<C_Position>(id, static_cast<qe::ComponentType>(Component::Position));
position->setPosition(400.0f, 300.0f);
auto sprite = entityManager->getComponent<C_Sprite>(id, static_cast<qe::ComponentType>(Component::Sprite));
sprite->create(textures, "PacMan");
// Setup animated sprite
qe::SpriteLoader spriteLoader(textures);
m_animation = spriteLoader.loadFromJsonFile(qe::Utils::getWorkingDirectory() + "../media/Animations/AnimatedPacMan.json");
// Add callbacks to event manager
auto events = m_stateManager->getContext()->m_eventManager;
events->addCallback(StateType::Game, "Enter_KeyDown", &TestState::onNextScreen, this);
events->addCallback(StateType::Game, "Escape_KeyDown", &TestState::onClose, this);
events->addCallback(StateType::Game, "Left_MouseButtonDown", &TestState::onClick, this);
}
void TestState::onDestroy() {
std::cout << "Destroying TestState" << std::endl;
// Remove callbacks from event manager
auto events = m_stateManager->getContext()->m_eventManager;
events->removeCallback(StateType::Game, "Enter_KeyDown");
events->removeCallback(StateType::Game, "Escape_KeyDown");
events->removeCallback(StateType::Game, "Left_MouseButtonDown");
}
void TestState::onEnter() {
std::cout << "Enter TestState" << std::endl;
auto window = m_stateManager->getContext()->m_window;
window->setCursor("../media/Cursors/SwordCursor.png", sf::Vector2u(0, 16));
//window.setCursor(qe::CursorType::Text);
m_animation->changeAnimation("MoveDown", true);
}
void TestState::onExit() {
std::cout << "Exiting TestState" << std::endl;
auto window = m_stateManager->getContext()->m_window;
window->setCursor(qe::CursorType::Arrow);
m_animation->changeAnimation("StopLeft", true);
}
void TestState::update(const sf::Time& time) {
m_stateManager->getContext()->m_systemManager->update(time.asSeconds());
m_animation->update(time.asSeconds());
}
void TestState::draw() {
auto window = m_stateManager->getContext()->m_window;
//m_stateManager->getContext()->m_systemManager->draw(window);
// GUI Rendering
auto renderer = window->getRenderWindow();
renderer->draw(m_text);
m_animation->draw(renderer);
}
void TestState::onNextScreen(qe::EventDetails* details) {
m_stateManager->changeState(StateType::NextState);
}
void TestState::onClose(qe::EventDetails * details) {
m_stateManager->getContext()->m_window->close(details);
}
void TestState::onClick(qe::EventDetails * details) {
std::cout << details->m_mouse.x << " " << details->m_mouse.y << std::endl;
} | true |
7143ed9a6b5ed38a61b0f3fd375cc25eaec54f62 | C++ | Jeff-CCH/simpleBlockchain | /blockchain.cpp | UTF-8 | 1,104 | 3.140625 | 3 | [] | no_license | #include "blockchain.h"
BlockChain::BlockChain(uint32_t difficulty) : difficulty(difficulty) {
genFirstBlock();
cout << "init BlockChain complete\n";
}
void BlockChain::genFirstBlock() {
Block firstBlock(0, "This is Genisis Block\n");
firstBlock.sHashPrev = "0";
firstBlock.mine(this->difficulty);
blockchain.push_back(firstBlock);
}
bool BlockChain::addBlock(Block &newBlock) {
newBlock.sHashPrev = getLastBlock().getHash();
newBlock.mine(difficulty); //mine block
//send to others to verify the integrity
//after confirmed, add to blockchain
blockchain.push_back(newBlock);
return true;
}
Block BlockChain::getLastBlock() const {
return blockchain.back();
}
void BlockChain::displayChain() const {
for (auto &b : blockchain) {
printf("Block#%d Data: %s Hash:%s Prev Hash: %s\n", b.index,
b.sData.c_str(),
b.sHash.c_str(),
b.sHashPrev.c_str());
}
}
| true |
e57e544d459633e620fb0f286add087583b50610 | C++ | Krishtof-Korda/CarND-Path-Planning-Project-Submission | /src/OtherVehicle.h | UTF-8 | 994 | 2.59375 | 3 | [] | no_license | // Self-driving Car Engineer Nanodegree - Udacity
// OtherVehicle.hpp
// path_planning
//
// Created by Krishtof Korda on 04/Nov/17.
//
#ifndef OtherVehicle_h
#define OtherVehicle_h
#include <stdio.h>
#include <vector>
#include "tools.h"
#include "structs.h"
#include <utility>
//#include "cost_functions.h"
using namespace std;
using namespace tools;
//KK Houses the data of a vehicle other than Ego.
class OtherVehicle{
public:
//Constructor
OtherVehicle();
//Destructor
virtual ~OtherVehicle();
double id;
double x;
double y;
double vx;
double vy;
double s;
float d;
double yaw;
double speed;
int lane;
double dist_from_ego = DBL_MAX;
//KK Place holder to predict points where vehicle will be in the future
Trajectory predicted_trajectory;
//KK return -1 for empty vehicle
bool isEmpty();
//KK Generate a spline trajectory for given variables
Trajectory generate_predicted_trajectory(RoadMap roadMap);
};
#endif /* OtherVehicle_h */
| true |
5af9255c718decbf40c78c290b69acc4147fa211 | C++ | EdipTac/PandemicGame | /Pandemic/TextualCard.h | UTF-8 | 636 | 3.5625 | 4 | [] | no_license | #pragma once
#include "Card.h"
// Represents a card with a custom name and description
class TextualCard
: virtual public Card
{
public:
// Constructs a card with a given name and description
TextualCard(std::string name, std::string description);
// Virutal destructor to make class abstract
virtual ~TextualCard() override = 0;
// The card's name
virtual std::string name() const override;
void setName(const std::string& name);
// The card's description
virtual std::string description() const override;
void setDescription(const std::string& description);
private:
std::string _description;
std::string _name;
};
| true |
0a28bd19f4a3d6cd84275fa7b47ef49bdb27dd8e | C++ | shunjilin/SlidingTilesPuzzle | /src/open/open_array.hpp | UTF-8 | 2,080 | 3.515625 | 4 | [
"MIT"
] | permissive | #ifndef OPEN_ARRAY_HPP
#define OPEN_ARRAY_HPP
#include <array>
#include <vector>
#include <optional>
/* Array-based Open list that allows 3 level tie-breaking [min f, max g, LIFO]
*/
template <typename Node, int MAX_MOVES>
struct OpenArray {
int min_f = MAX_MOVES;
int max_g = -1;
size_t size = 0;
// index by f_value, then g_value
std::array< std::array< std::vector<Node>, MAX_MOVES>, MAX_MOVES> queue;
// updates min_f to be minimum f value, updates g as well (see updateG())
void updateFG() noexcept {
while (min_f < MAX_MOVES) {
updateG();
if (max_g >= 0) return; // nodes found in g bucket
// no nodes found on current f
++min_f;
max_g = MAX_MOVES - 1;
}
}
// updates max_g to be maximum g value in current min_f layer
void updateG() noexcept {
if (max_g == MAX_MOVES) --max_g; // avoid out of bounds
while (max_g >= 0 && queue[min_f][max_g].empty()) {
// the following line is for when memory is a scarce resource
//std::vector<Node>().swap(queue[min_f][max_g]); // deallocate
--max_g;
}
}
// inserts node into open list
void push(Node node) {
auto f = getF(node);
auto g = getG(node);
// inconsistent heuristic, lower f value
if (f < min_f) {
min_f = f;
max_g = g;
}
// same f, higher g value
else if (f == min_f && g > max_g) {
max_g = g;
}
++size;
queue[f][g].emplace_back(std::move(node));
}
// pops and returns node from open list
std::optional<Node> pop() {
if (size == 0) return {};
if (queue[min_f][max_g].empty()) updateFG();
auto node = queue[min_f][max_g].back();
queue[min_f][max_g].pop_back();
--size;
return node;
}
// returns true if queue is empty, also updates f and g
bool empty() noexcept {
if (size == 0) return true;
return false;
}
};
#endif
| true |
06e4003672b12fe5bdfd011b622f9ab1db7be4db | C++ | pbarragan/mechIdentPartLocalStick | /setupUtils.cpp | UTF-8 | 70,321 | 2.5625 | 3 | [] | no_license | //Setup Utilities
#include "setupUtils.h"
#include "logUtils.h"
#include "translator.h"
#include "actionSelection.h"
#include "fileUtils.h"
#include "globalVars.h" // Global variables
#include <iostream> // DELETE
#define _USE_MATH_DEFINES
#include <math.h> // cos, sin
#include <algorithm> // std::find_if
#include <stdexcept> // throw exception
bool closeEnough(std::vector<double> &a1,std::vector<double> &a2,double thresh){
return pow(a1[0]-a2[0],2)<pow(thresh,2) && pow(a1[1]-a2[1],2)<pow(thresh,2);
}
// fake actions and fake observations
void setupUtils::fakeAOfromFile(std::vector<std::vector<double> > &actionList,
std::vector<int> &FAinds,
std::vector<std::vector<double> > &fakeObs,
std::string fileName,
int numSteps){
std::vector<std::vector<double> > fakeActions;
fileUtils::txtFileToActionsObs(fileName,fakeActions,fakeObs,numSteps);
std::cout << "action size: " << fakeActions.size() << std::endl;
std::cout << "obs size:" << fakeObs.size() << std::endl;
std::vector<int> FAIs;
double thresh = 0.00001;
for(size_t i=0;i<fakeActions.size();i++){
std::cout << "step: " << i << std::endl;
std::cout << fakeActions[i][0] << "," << fakeActions[i][1] << std::endl;
for(size_t j=0;j<actionList.size();j++){
std::cout << actionList[j][0] << "," << actionList[j][1] << std::endl;
if(closeEnough(fakeActions[i],actionList[j],thresh)){
std::cout << "found an action" << std::endl;
FAIs.push_back(j);
break;
}
else std::cout << "didn't match that action" << std::endl;
}
}
FAinds = FAIs;
}
// fake actions
std::vector<int> setupUtils::fakeActions(std::vector<
std::vector<double> >& actionList){
std::vector<std::vector<double> > fakeActions;
std::vector<double> actions0;
actions0.push_back(-2.20436e-17);
actions0.push_back(-0.12);
fakeActions.push_back(actions0);
std::vector<double> actions1;
actions1.push_back(0.12);
actions1.push_back(0.0);
fakeActions.push_back(actions1);
std::vector<double> actions2;
actions2.push_back(0.0848528);
actions2.push_back(0.0848528);
fakeActions.push_back(actions2);
std::vector<double> actions3;
actions3.push_back(-0.12);
actions3.push_back(1.46958e-17);
fakeActions.push_back(actions3);
std::vector<double> actions4;
actions4.push_back(-2.20436e-17);
actions4.push_back(-0.12);
fakeActions.push_back(actions4);
std::vector<double> actions5;
actions5.push_back(0.0848528);
actions5.push_back(0.0848528);
fakeActions.push_back(actions5);
std::vector<double> actions6;
actions6.push_back(0.0848528);
actions6.push_back(-0.0848528);
fakeActions.push_back(actions6);
std::vector<double> actions7;
actions7.push_back(0.12);
actions7.push_back(0.0);
fakeActions.push_back(actions7);
std::vector<double> actions8;
actions8.push_back(-0.0848528);
actions8.push_back(-0.0848528);
fakeActions.push_back(actions8);
std::vector<double> actions9;
actions9.push_back(7.34788e-18);
actions9.push_back(0.12);
fakeActions.push_back(actions9);
std::vector<int> FAinds;
double thresh = 0.00001;
for(size_t i=0;i<fakeActions.size();i++){
for(size_t j=0;j<actionList.size();j++){
if(closeEnough(fakeActions[i],actionList[j],thresh)){
FAinds.push_back(j);
break;
}
}
}
return FAinds;
}
// fake observations
std::vector<std::vector<double> > setupUtils::fakeObs(){
std::vector<std::vector<double> > fakeObs;
std::vector<double> obs0;
obs0.push_back(0.00061114);
obs0.push_back(0.002612);
fakeObs.push_back(obs0);
std::vector<double> obs1;
obs1.push_back(0.00133904);
obs1.push_back(0.00395064);
fakeObs.push_back(obs1);
std::vector<double> obs2;
obs2.push_back(0.00185868);
obs2.push_back(0.00609914);
fakeObs.push_back(obs2);
std::vector<double> obs3;
obs3.push_back(0.000326171);
obs3.push_back(0.00410389);
fakeObs.push_back(obs3);
std::vector<double> obs4;
obs4.push_back(0.000480639);
obs4.push_back(0.00303153);
fakeObs.push_back(obs4);
std::vector<double> obs5;
obs5.push_back(0.00150034);
obs5.push_back(0.00635989);
fakeObs.push_back(obs5);
std::vector<double> obs6;
obs6.push_back(0.0010297);
obs6.push_back(0.00337847);
fakeObs.push_back(obs6);
std::vector<double> obs7;
obs7.push_back(0.00143139);
obs7.push_back(0.00413988);
fakeObs.push_back(obs7);
std::vector<double> obs8;
obs8.push_back(9.53211e-05);
obs8.push_back(0.00229638);
fakeObs.push_back(obs8);
std::vector<double> obs9;
obs9.push_back(0.00151811);
obs9.push_back(0.0034373);
fakeObs.push_back(obs9);
return fakeObs;
}
////////////////////////////////////////////////////////////////////////////////
// Particle Section //
////////////////////////////////////////////////////////////////////////////////
// SAMPLING SECTION
//using Eigen::MatrixXd;
//using Eigen::VectorXd;
void setupUtils::resampleParticles(std::vector<stateStruct>& stateList,std::vector<double>& logProbList,bool& printResample){
double logProbPerPart = logUtils::logSumExp(logProbList)
-logUtils::safe_log(logProbList.size());
if(printResample){
std::cout << "Number of particles: " << logProbList.size() << std::endl;
std::cout << "Log Prob Per Particle: " << logProbPerPart << std::endl;
}
// Samples from the particles state according to the probability distribution
// Step 0: Normalize the log probability list
std::vector<double> normLogProbList =
logUtils::normalizeVectorInLogSpace(logProbList);
//Step 1: Assume only log probs exist. Exponentiate to get probs.
std::vector<double> probList = logUtils::expLogProbs(normLogProbList);
//Step 1: Create the CDF of the current belief from the PDF probList_.
std::vector<double> probCDF = actionSelection::createCDF(probList);
std::cout << probCDF[0] << std::endl;
std::cout << probCDF[probCDF.size()-1] << std::endl;
//Step 2: Sample states from the belief
std::vector<stateStruct> tempStateList; // empty state list
for (size_t i=0;i<stateList.size();i++){
tempStateList.push_back(actionSelection::getSampleState(probCDF,stateList));
}
stateList = tempStateList;
std::vector<double> tempLogProbList (logProbList.size(),logProbPerPart);
logProbList = tempLogProbList;
}
std::vector<double> setupUtils::standardGaussianVariates(){
// Box-Muller Transform
// Generate random numbers between 0 and 1
double x1 = ((double)rand()/(double)RAND_MAX);
double x2 = ((double)rand()/(double)RAND_MAX);
// Calculate standard normal variates (mean 0, var 1)
std::vector<double> variates;
variates.push_back(sqrt(-2*logUtils::safe_log(x1))*cos(2*M_PI*x2));
variates.push_back(sqrt(-2*logUtils::safe_log(x1))*sin(2*M_PI*x2));
return variates;
}
double setupUtils::randomDouble(){
double X = ((double)rand()/(double)RAND_MAX);
return X;
}
/*
Eigen::VectorXd setupUtils::sampleParticle(unsigned int size,Eigen::VectorXd& mu,Eigen::MatrixXd& A){
// Sample size standard normal variates
Eigen::VectorXd z = VectorXd::Zero(size);
for (size_t i=0; i<size; i+=2){
std::vector<double> variates = standardGaussianVariates();
z[i] = variates[0];
if (i != size-1) z[i+1] = variates[1];
}
// Return sample from multivariate guassian (type Eigen::VectorXd x)
return mu+A*z;
}
*/
/*
void setupUtils::setupParticles(std::vector<stateStruct>& stateList,std::vector<double>& logProbList,int modelNum,double initParamVar,double initVarVar,int numParticles,int numMechTypes,std::vector< std::vector<double> >& workspace){
stateList.clear(); // Make sure the stateList is empty
if (modelNum == 1){
// For model 1 (the fixed model), only ever sample the single valid state
for (size_t i=0;i<numParticles;i++){
stateStruct x_state;
x_state.model = modelNum;
x_state.params.push_back(0.0);
x_state.params.push_back(0.0);
stateList.push_back(x_state);
}
}
else{
// For any other model:
// Determine shape of state space for this modelNum
int numParams = MODEL_DESCRIPTIONS[modelNum][0]; // in globalVars.h
int numVars = MODEL_DESCRIPTIONS[modelNum][1]; // in globalVars.h
unsigned int size = numParams+numVars; // dimension of space
Eigen::MatrixXd Cov = MatrixXd::Zero(size,size);
Eigen::VectorXd mu = VectorXd::Zero(size);
// Setup initial diagonal covariance matrix with
// a) initial parameter variance for each parameter dimension
// b) initial variable variance for each variable dimension
for (size_t i=0; i<numParams; i++){
Cov(i,i) = initParamVar;
}
for (size_t i=numParams; i<size; i++){
Cov(i,i) = initVarVar;
}
// Generate matrix A from Choleksy decomposition of Cov Matrix
// Cast back to dense matrix for use in sampling function
Eigen::MatrixXd A( Cov.llt().matrixL() );
// Sample numParticles particles,
// shape them into states, and place in vector
size_t count = 0; // How many valid particles we have sampled
while (count<numParticles){
Eigen::VectorXd x = sampleParticle(size,mu,A);
stateStruct x_state;
x_state.model = modelNum;
for (size_t i=0; i<numParams; i++){
x_state.params.push_back(x(i));
}
for (size_t i=numParams; i<size; i++){
x_state.vars.push_back(x(i));
}
if (translator::isStateValid(x_state,workspace)){
stateList.push_back(x_state);
count++;
}
}
}
// Set the probability of the samples equal across all models
// prob per particle
double probPerParticle = logUtils::safe_log(1.0/(numParticles*numMechTypes));
logProbList.clear(); // Make sure the logProbList is empty
std::vector<double> probs (numParticles,probPerParticle);
logProbList = probs;
}
*/
void setupUtils::setupParticlesIndependent(std::vector<stateStruct>& stateList,std::vector<double>& logProbList,int modelNum,double initParamVar,double initVarVar,int numParticles,int numMechTypes,std::vector< std::vector<double> >& workspace){
stateList.clear(); // Make sure the stateList is empty
if (modelNum == 1){
// For model 1 (the fixed model), only ever sample the single valid state
for (size_t i=0;i<numParticles;i++){
stateStruct x_state;
x_state.model = modelNum;
x_state.params.push_back(0.0);
x_state.params.push_back(0.0);
stateList.push_back(x_state);
}
}
else{
// For any other model:
// Determine shape of state space for this modelNum
int numParams = MODEL_DESCRIPTIONS[modelNum][0]; // in globalVars.h
int numVars = MODEL_DESCRIPTIONS[modelNum][1]; // in globalVars.h
unsigned int size = numParams+numVars; // dimension of space
std::vector<double> z (size,0.0); // holds standard normal variates
// Get standard deviations
double paramSD = sqrt(initParamVar);
double varSD = sqrt(initVarVar);
std::cout << paramSD << std::endl;
std::cout << varSD << std::endl;
// Sample numParticles particles,
// shape them into states, and place in vector
size_t count = 0; // How many valid particles we have sampled
size_t numRejected = 0; // How many particles we rejected
bool reject;
while (count<numParticles){
// Sample size standard normal variates
for (size_t i=0; i<size; i+=2){
std::vector<double> variates = standardGaussianVariates();
z[i] = variates[0];
if (i != size-1) z[i+1] = variates[1];
}
// temporarily sample around the true mean
// Create the state
std::vector<double> mu;
mu.push_back(-0.396);
mu.push_back(-0.396);
mu.push_back(0.56);
mu.push_back(0.7854);
stateStruct x_state;
x_state.model = modelNum;
/*
if (count<numParticles*.000001){
for (size_t i=0; i<numParams; i++){
x_state.params.push_back(z[i]*.01+mu[i]); // replace .05 with paramSD
}
for (size_t i=numParams; i<size; i++){
x_state.vars.push_back(z[i]*.01+mu[i]); // replace .05 with varSD
}
}
else{
for (size_t i=0; i<numParams; i++){
x_state.params.push_back(z[i]*paramSD+mu[i]); // replace .05 with paramSD
}
for (size_t i=numParams; i<size; i++){
x_state.vars.push_back(z[i]*paramSD+mu[i]); // replace .05 with varSD
}
}
*/
for (size_t i=0; i<numParams; i++){
x_state.params.push_back(z[i]*paramSD*.1+mu[i]); // replace .05 with paramSD
}
for (size_t i=numParams; i<size; i++){
x_state.vars.push_back(z[i]*paramSD*.1+mu[i]); // replace .05 with varSD
}
reject = false;
/*
if (translator::isStateValid(x_state,workspace)){
stateList.push_back(x_state);
count++;
//if (count % 10000 == 9999) std::cout << count << std::endl;
}
*/
if (x_state.params[2]<=0){ /*std::cout << "r < 0" << std::endl;*/ reject=true;}
else{
// Check if state places rbt outside of rbt workspace
double x = x_state.params[0]+x_state.params[2]*cos(x_state.vars[0]);
double y = x_state.params[1]+x_state.params[2]*sin(x_state.vars[0]);
//std::cout << x << "," << y << std::endl;
if (x<workspace[0][0] || x>workspace[0][1] ||
y<workspace[1][0] || y>workspace[1][1]){ /*std::cout << "out of workspace" << std::endl;*/ reject=true;}
}
if (!reject){
stateList.push_back(x_state);
count++;
//if (count % 10000 == 9999) std::cout << count << std::endl;
}
else numRejected++;
//stateList.push_back(x_state);
//count++;
}
std::cout << "Number Rejected: " << numRejected << std::endl;
}
/*
// If you put this back, you have to
// add the right answer temporarily
stateStruct rightState;
rightState.model = 2;
rightState.params.push_back(-0.396);
rightState.params.push_back(-0.396);
rightState.params.push_back(0.56);
rightState.vars.push_back(0.7854);
stateList.push_back(rightState);
*/
// Set the probability of the samples equal across all models
// prob per particle
double probPerParticle = logUtils::safe_log(1.0/(numParticles*numMechTypes));
logProbList.clear(); // Make sure the logProbList is empty
std::vector<double> probs (numParticles,probPerParticle);
logProbList = probs;
}
void setupUtils::setupParticlesRevSpecial(std::vector<stateStruct>& stateList,std::vector<double>& logProbList,int modelNum,double initParamVar,double initVarVar,int numParticles,int numMechTypes,std::vector< std::vector<double> >& workspace){
stateList.clear(); // Make sure the stateList is empty
if (modelNum == 1){
// For model 1 (the fixed model), only ever sample the single valid state
for (size_t i=0;i<numParticles;i++){
stateStruct x_state;
x_state.model = modelNum;
x_state.params.push_back(0.0);
x_state.params.push_back(0.0);
stateList.push_back(x_state);
}
}
else{
// For any other model:
// Determine shape of state space for this modelNum
int numParams = MODEL_DESCRIPTIONS[modelNum][0]; // in globalVars.h
int numVars = MODEL_DESCRIPTIONS[modelNum][1]; // in globalVars.h
unsigned int size = numParams+numVars; // dimension of space
std::vector<double> z (size,0.0); // holds standard normal variates
// Get standard deviations
double paramSD = sqrt(initParamVar);
double varSD = sqrt(initVarVar);
std::cout << paramSD << std::endl;
std::cout << varSD << std::endl;
// Sample numParticles particles,
// shape them into states, and place in vector
size_t count = 0; // How many valid particles we have sampled
size_t numRejected = 0; // How many particles we rejected
bool reject;
double pivotSD = 2.0;
double handleSD = 0.01;
while (count<numParticles){
// Sample a pivot and handle by sampling standard normal variates
std::vector<double> pivot = standardGaussianVariates();
std::vector<double> handle = standardGaussianVariates();
//handle[0] = 0.0;
//handle[1] = 0.0;
stateStruct x_state;
x_state.model = modelNum;
double xp = pivot[0]*pivotSD;
double yp = pivot[1]*pivotSD;
double xh = handle[0]*handleSD;
double yh = handle[1]*handleSD;
x_state.params.push_back(xp);
x_state.params.push_back(yp);
x_state.params.push_back(sqrt((xp-xh)*(xp-xh)+(yp-yh)*(yp-yh)));
x_state.vars.push_back(atan2((yh-yp),(xh-xp)));
reject = false;
if (x_state.params[2]<=0){ /*std::cout << "r < 0" << std::endl;*/ reject=true;}
else{
// Check if state places rbt outside of rbt workspace
if (xh<workspace[0][0] || xh>workspace[0][1] ||
yh<workspace[1][0] || yh>workspace[1][1]){ /*std::cout << "out of workspace" << std::endl;*/ reject=true;}
}
if (!reject){
stateList.push_back(x_state);
count++;
//if (count % 10000 == 9999) std::cout << count << std::endl;
}
else numRejected++;
//stateList.push_back(x_state);
//count++;
}
std::cout << "Number Rejected: " << numRejected << std::endl;
}
/*
// If you put this back, you have to
// add the right answer temporarily
stateStruct rightState;
rightState.model = 2;
rightState.params.push_back(-0.396);
rightState.params.push_back(-0.396);
rightState.params.push_back(0.56);
rightState.vars.push_back(0.7854);
stateList.push_back(rightState);
*/
// Set the probability of the samples equal across all models
// prob per particle
double probPerParticle = logUtils::safe_log(1.0/(numParticles*numMechTypes));
logProbList.clear(); // Make sure the logProbList is empty
std::vector<double> probs (numParticles,probPerParticle);
logProbList = probs;
}
// This is the special sampling that we actually use
void setupUtils::setupParticlesSpecial(std::vector<stateStruct>& stateList,std::vector<double>& logProbList,int modelNum,double initParamVar,double initVarVar,int numParticles,int numMechTypes,std::vector< std::vector<double> >& workspace){
stateList.clear(); // Make sure the stateList is empty
if (modelNum == 0){
// For model 0 (the free model), only ever sample the single valid state
// which is vars x,y = (0,0)
for (size_t i=0;i<numParticles;i++){
stateStruct x_state;
x_state.model = modelNum;
x_state.vars.push_back(0.0);
x_state.vars.push_back(0.0);
stateList.push_back(x_state);
}
}
else if (modelNum == 1){
// For model 1 (the fixed model), only ever sample the single valid state
// which is parameters x,y = (0,0)
for (size_t i=0;i<numParticles;i++){
stateStruct x_state;
x_state.model = modelNum;
x_state.params.push_back(0.0);
x_state.params.push_back(0.0);
stateList.push_back(x_state);
}
}
else if (modelNum == 2){
if(false){
// For model 2 (the revolute model), only sample the pivot position and
// calculate the other parameters and variables
// Sample a pivot by sampling standard normal variates
double pivotSD = 2.0;
for (size_t i=0;i<numParticles;i++){
std::vector<double> pivot = standardGaussianVariates();
stateStruct x_state;
x_state.model = modelNum;
double xp = pivot[0]*pivotSD;
double yp = pivot[1]*pivotSD;
x_state.params.push_back(xp);
x_state.params.push_back(yp);
x_state.params.push_back(sqrt(xp*xp+yp*yp));
x_state.vars.push_back(atan2(-yp,-xp));
stateList.push_back(x_state);
}
}
else{
// For model 2 (the revolute model), sample a radius and an angle and
// calculate the other parameters
// Sample a radius uniformly between min and max
double rMin = 0.15;
double rMax = 1.15;
// Sample a angle uniformly between min and max
double thMin = -M_PI+0.000000001; // maybe this is a good thing to do
double thMax = M_PI;
for (size_t i=0;i<numParticles;i++){
double r = rMin+(rMax-rMin)*randomDouble();
double th = thMin+(thMax-thMin)*randomDouble();
stateStruct x_state;
x_state.model = modelNum;
x_state.params.push_back(r*cos(th)); // xp
x_state.params.push_back(r*sin(th)); // yp
x_state.params.push_back(r);
if(th<=0) x_state.vars.push_back(th+M_PI);
else x_state.vars.push_back(th-M_PI);
stateList.push_back(x_state);
}
}
}
else if (modelNum == 3){
// For model 3 (the prismatic model), only sample the angle and calculate
// the other parameters and variables.
// **** This model needs to be changed in the future because the pivot
// is a redundant piece of information ****
double offset = 0.40; // Pivot offset. This should be unnecessary.
for (size_t i=0;i<numParticles;i++){
// sample uniformly between -pi and pi
double angle = 2*M_PI*((double)rand()/(double)RAND_MAX)-M_PI;
stateStruct x_state;
x_state.model = modelNum;
x_state.params.push_back(-offset*cos(angle));
x_state.params.push_back(-offset*sin(angle));
x_state.params.push_back(angle);
x_state.vars.push_back(offset);
stateList.push_back(x_state);
}
}
else{
throw std::invalid_argument("Sampler not setup for more than models 0-3.");
}
// Set the probability of the samples equal across all models
// prob per particle
double probPerParticle = logUtils::safe_log(1.0/(numParticles*numMechTypes));
logProbList.clear(); // Make sure the logProbList is empty
std::vector<double> probs (numParticles,probPerParticle);
logProbList = probs;
}
// This is the special sampling that we actually use with repeating samples
void setupUtils::setupParticlesSpecialRepeat(std::vector<stateStruct>& stateList,std::vector<double>& logProbList,int modelNum,double initParamVar,double initVarVar,int numParticles,int numRepeats,int numMechTypes,std::vector< std::vector<double> >& workspace){
stateList.clear(); // Make sure the stateList is empty
if (modelNum == 0){
// For model 0 (the free model), only ever sample the single valid state
// which is vars x,y = (0,0)
for (size_t i=0;i<numParticles;i+=numRepeats){
stateStruct x_state;
x_state.model = modelNum;
x_state.vars.push_back(0.0);
x_state.vars.push_back(0.0);
for (size_t j=0;j<numRepeats;j++) stateList.push_back(x_state);
}
}
else if (modelNum == 1){
// For model 1 (the fixed model), only ever sample the single valid state
// which is parameters x,y = (0,0)
for (size_t i=0;i<numParticles;i+=numRepeats){
stateStruct x_state;
x_state.model = modelNum;
x_state.params.push_back(0.0);
x_state.params.push_back(0.0);
for (size_t j=0;j<numRepeats;j++) stateList.push_back(x_state);
}
}
else if (modelNum == 2){
if(false){
// For model 2 (the revolute model), only sample the pivot position and
// calculate the other parameters and variables
// Sample a pivot by sampling standard normal variates
double pivotSD = 2.0;
for (size_t i=0;i<numParticles;i+=numRepeats){
std::vector<double> pivot = standardGaussianVariates();
stateStruct x_state;
x_state.model = modelNum;
double xp = pivot[0]*pivotSD;
double yp = pivot[1]*pivotSD;
x_state.params.push_back(xp);
x_state.params.push_back(yp);
x_state.params.push_back(sqrt(xp*xp+yp*yp));
x_state.vars.push_back(atan2(-yp,-xp));
for (size_t j=0;j<numRepeats;j++) stateList.push_back(x_state);
}
}
else if(false){
// For model 2 (the revolute model), sample a radius and an angle and
// calculate the other parameters
// Sample a radius uniformly between min and max
//double rMin = 0.54;//0.15;
//double rMax = 0.58;//1.15;
double r = 0.56;
// Sample an angle uniformly between min and max
double thMin = -M_PI+0.000000001; // -2.5 // maybe this is a good thing to do
double thMax = M_PI; // -2.1
for (size_t i=0;i<numParticles;i+=numRepeats){
//double r = rMin+(rMax-rMin)*randomDouble();
double th = thMin+(thMax-thMin)*randomDouble();
stateStruct x_state;
x_state.model = modelNum;
x_state.params.push_back(r*cos(th+M_PI)); // xp - flip angle
x_state.params.push_back(r*sin(th+M_PI)); // yp - flip angle
x_state.params.push_back(r);
x_state.vars.push_back(th);
//if(th<=0) x_state.vars.push_back(th+M_PI);
//else x_state.vars.push_back(th-M_PI);
for (size_t j=0;j<numRepeats;j++) stateList.push_back(x_state);
}
}
else if(false){
// SAMPLE ONLY ONE SET!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// For model 2 (the revolute model), sample a radius and an angle and
// calculate the other parameters
// Sample a radius uniformly between min and max
//double rMin = 0.54;//0.15;
//double rMax = 0.58;//1.15;
double r = 0.56;
// Sample an angle uniformly between min and max
//double thMin = -M_PI+0.000000001; // -2.5 // maybe this is a good thing to do
//double thMax = M_PI; // -2.1
double th = -2.480;//-2.29;
for (size_t i=0;i<numParticles;i+=numRepeats){
//double r = rMin+(rMax-rMin)*randomDouble();
//double th = thMin+(thMax-thMin)*randomDouble();
stateStruct x_state;
x_state.model = modelNum;
x_state.params.push_back(r*cos(th+M_PI)); // xp - flip angle
x_state.params.push_back(r*sin(th+M_PI)); // yp - flip angle
x_state.params.push_back(r);
x_state.vars.push_back(th);
//if(th<=0) x_state.vars.push_back(th+M_PI);
//else x_state.vars.push_back(th-M_PI);
for (size_t j=0;j<numRepeats;j++) stateList.push_back(x_state);
}
}
else{
// For model 2 (the revolute model), sample a radius and an angle and
// calculate the other parameters
// Sample a radius uniformly between min and max
double rMin = 0.15;
double rMax = 1.15;
// Sample an angle uniformly between min and max
double thMin = -M_PI+0.000000001; // -2.5 // maybe this is a good thing to do
double thMax = M_PI; // -2.1
for (size_t i=0;i<numParticles;i+=numRepeats){
double r = rMin+(rMax-rMin)*randomDouble();
double th = thMin+(thMax-thMin)*randomDouble();
stateStruct x_state;
x_state.model = modelNum;
x_state.params.push_back(r*cos(th+M_PI)); // xp - flip angle
x_state.params.push_back(r*sin(th+M_PI)); // yp - flip angle
x_state.params.push_back(r);
x_state.vars.push_back(th);
//if(th<=0) x_state.vars.push_back(th+M_PI);
//else x_state.vars.push_back(th-M_PI);
for (size_t j=0;j<numRepeats;j++) stateList.push_back(x_state);
}
}
}
else if (modelNum == 3){
// For model 3 (the prismatic model), only sample the angle and calculate
// the other parameters and variables.
// **** This model needs to be changed in the future because the pivot
// is a redundant piece of information ****
double offset = 0.40; // Pivot offset. This should be unnecessary.
if(false){
// SAMPLE ONLY ONE SET!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
for (size_t i=0;i<numParticles;i+=numRepeats){
// sample uniformly between -pi and pi
//double angle = 2*M_PI*((double)rand()/(double)RAND_MAX)-M_PI;
// sample uniformly between 0 and pi
//double angle = M_PI*((double)rand()/(double)RAND_MAX);
double angle = 2.232;//2.417;
stateStruct x_state;
x_state.model = modelNum;
x_state.params.push_back(-offset*cos(angle));
x_state.params.push_back(-offset*sin(angle));
x_state.params.push_back(angle);
x_state.vars.push_back(offset);
for (size_t j=0;j<numRepeats;j++) stateList.push_back(x_state);
}
}
else{
// NORMAL
for (size_t i=0;i<numParticles;i+=numRepeats){
// sample uniformly between -pi and pi
//double angle = 2*M_PI*((double)rand()/(double)RAND_MAX)-M_PI;
// sample uniformly between 0 and pi
double angle = M_PI*((double)rand()/(double)RAND_MAX);
stateStruct x_state;
x_state.model = modelNum;
x_state.params.push_back(-offset*cos(angle));
x_state.params.push_back(-offset*sin(angle));
x_state.params.push_back(angle);
x_state.vars.push_back(offset);
for (size_t j=0;j<numRepeats;j++) stateList.push_back(x_state);
}
}
}
else if (modelNum == 4){
// For model 4 (the latch 1 model), only sample the angle and calculate
// the other parameters and variables.
// **** This model needs to be changed in the future because the pivot
// is a redundant piece of information ****
if(false){
// NORMAL
for (size_t i=0;i<numParticles;i+=numRepeats){
// sample uniformly between -pi and pi
//double angle = 2*M_PI*((double)rand()/(double)RAND_MAX)-M_PI;
// sample uniformly between 0 and pi
double angle = M_PI*((double)rand()/(double)RAND_MAX);
double offset = 0.30; // Pivot offset. This should be unnecessary.
stateStruct x_state;
x_state.model = modelNum;
x_state.params.push_back(-offset*cos(angle));
x_state.params.push_back(-offset*sin(angle));
x_state.params.push_back(0.19);
x_state.params.push_back(angle);
x_state.params.push_back(0.11);
x_state.vars.push_back(angle);
x_state.vars.push_back(0.11);
for (size_t j=0;j<numRepeats;j++) stateList.push_back(x_state);
}
}
else{
// NORAML over two dimensions, th and d
// set radius as constant
double r = 0.19;
// Sample a distance uniformly between min and max
double dMin = 0.05;
double dMax = 0.15;
// Sample an angle uniformly between min and max
double thMin = -M_PI+0.000000001; // maybe this is a good thing to do
double thMax = M_PI;
for (size_t i=0;i<numParticles;i+=numRepeats){
// sample uniformly between -pi and pi
double d = dMin+(dMax-dMin)*randomDouble();
double th = thMin+(thMax-thMin)*randomDouble();
double offset = r+d;
stateStruct x_state;
x_state.model = modelNum;
x_state.params.push_back(-offset*cos(th));
x_state.params.push_back(-offset*sin(th));
x_state.params.push_back(r);
x_state.params.push_back(th);
x_state.params.push_back(d);
x_state.vars.push_back(th);
x_state.vars.push_back(d);
for (size_t j=0;j<numRepeats;j++) stateList.push_back(x_state);
}
}
}
else{
throw std::invalid_argument("Sampler not setup for more than models 0-3.");
}
// Set the probability of the samples equal across all models
// prob per particle
double probPerParticle = logUtils::safe_log(1.0/(numParticles*numMechTypes));
logProbList.clear(); // Make sure the logProbList is empty
std::vector<double> probs (numParticles,probPerParticle);
logProbList = probs;
}
// END SAMPLING SECTION
////////////////////////////////////////////////////////////////////////////////
// End Particle Section //
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Model Section //
////////////////////////////////////////////////////////////////////////////////
//dimRanges (dimension ranges) gives you the min and max in each dimension.
//dimNums gives you the number of discrete points along a dimension.
std::vector<stateStruct> setupUtils::setupModel0(std::vector<stateStruct>& modelParamPairs){
// Model 0 is the free model
// State looks like:
// Model: 0
// Params:
// Vars: x,y in rbt space
int modelNum = 0;
int paramNum = 0; //how many parameters
int varNum = 2; //how many variables
//Dimension Ranges for Params
std::vector< std::vector<double> > dRP (paramNum, std::vector<double> (2,0.0)); // empty size 0 vector
//Dimension Numbers for Params
std::vector<int> dNP (paramNum, 0); // empty size 0 vector
//Dimension Ranges for Vars
std::vector< std::vector<double> > dRV (varNum, std::vector<double> (2,0.0));
dRV[0][0] = -0.15;
dRV[0][1] = 0.15;
dRV[1][0] = -0.15;
dRV[1][1] = 0.15;
//Dimension Numbers for Vars
std::vector<int> dNV (varNum, 0);
dNV[0] = 11; // bs: 10
dNV[1] = 11; // bs: 10
return setupModelFromDec(dRP,dNP,dRV,dNV,modelNum,modelParamPairs);
}
std::vector<stateStruct> setupUtils::setupModel1(std::vector<stateStruct>& modelParamPairs){
// Model 1 is the fixed model
// State looks like:
// Model: 1
// Params: x,y in rbt space
// Vars:
int modelNum = 1;
int paramNum = 2; //how many parameters
int varNum = 0; //how many variables
//Dimension Ranges for Params
std::vector< std::vector<double> > dRP (paramNum, std::vector<double> (2,0.0));
dRP[0][0] = 0.0;
dRP[0][1] = 0.0;
dRP[1][0] = 0.0;
dRP[1][1] = 0.0;
//Dimension Numbers for Params
std::vector<int> dNP (paramNum, 0);
dNP[0] = 1;
dNP[1] = 1;
//Dimension Ranges for Vars
std::vector< std::vector<double> > dRV (varNum, std::vector<double> (2,0.0)); // empty size 0 vector
//Dimension Numbers for Vars
std::vector<int> dNV (varNum, 0); // empty size 0 vector
return setupModelFromDec(dRP,dNP,dRV,dNV,modelNum,modelParamPairs);
}
std::vector<stateStruct> setupUtils::setupModel2(std::vector<stateStruct>& modelParamPairs){
// Model 2 is the revolute model
// State looks like:
// Model: 2
// Params: x_pivot,y_pivot in rbt space, r
// Vars: theta in rbt space
int modelNum = 2;
int paramNum = 3; //how many parameters
int varNum = 1; //how many variables
//Dimension Ranges for Params
std::vector< std::vector<double> > dRP (paramNum, std::vector<double> (2,0.0));
dRP[0][0] = 0.396; // ICRA 2014 - 0.3 - 0.3111
dRP[0][1] = 0.396; // ICRA 2014 - 0.3 - 0.3111
dRP[1][0] = 0.396; // ICRA 2014 - 0.3 - 0.3111
dRP[1][1] = 0.396; // ICRA 2014 - 0.3 - 0.3111
dRP[2][0] = 0.56; // ICRA 2014 - 0.3 - 0.44
dRP[2][1] = 0.56; // ICRA 2014 - 0.3 - 0.44
//Dimension Numbers for Params
std::vector<int> dNP (paramNum, 0);
dNP[0] = 1;
dNP[1] = 1;
dNP[2] = 1;
//Dimension Ranges for Vars
std::vector< std::vector<double> > dRV (varNum, std::vector<double> (2,0.0));
dRV[0][0] = -3.14159; // bs: 3.14
dRV[0][1] = 3.14159-0.065449846949787; // bs: 3.14
//Dimension Numbers for Vars
std::vector<int> dNV (varNum, 0);
dNV[0] = 96; // bs: 100
return setupModelFromDec(dRP,dNP,dRV,dNV,modelNum,modelParamPairs);
}
std::vector<stateStruct> setupUtils::setupModel3(std::vector<stateStruct>& modelParamPairs){
// Model 3 is the prismatic model
// State looks like:
// Model: 3
// Params: x_axis,y_axis,theta_axis in rbt space
// Vars: d
int modelNum = 3;
int paramNum = 3; //how many parameters
int varNum = 1; //how many variables
//Dimension Ranges for Params
std::vector< std::vector<double> > dRP (paramNum, std::vector<double> (2,0.0));
dRP[0][0] = 0.0; // ICRA 2014 - -0.16
dRP[0][1] = 0.0; // ICRA 2014 - -0.16
dRP[1][0] = 0.226274; // ICRA 2014 - -0.16
dRP[1][1] = 0.226274; // ICRA 2014 - -0.16
dRP[2][0] = -1.570796; // ICRA 2014 - 0.7865
dRP[2][1] = -1.570796; // ICRA 2014 - 0.7865
//Dimension Numbers for Params
std::vector<int> dNP (paramNum, 0);
dNP[0] = 1;
dNP[1] = 1;
dNP[2] = 1;
//Dimension Ranges for Vars
std::vector< std::vector<double> > dRV (varNum, std::vector<double> (2,0.0));
dRV[0][0] = -0.45255;
dRV[0][1] = 0.45255;
//Dimension Numbers for Vars
std::vector<int> dNV (varNum, 0);
dNV[0] = 49; // bs: 50
return setupModelFromDec(dRP,dNP,dRV,dNV,modelNum,modelParamPairs);
}
std::vector<stateStruct> setupUtils::setupModel4(std::vector<stateStruct>& modelParamPairs){
// Model 4 is the revolute prismatic latch model
// State looks like:
// Model: 4
// Params: x_pivot,y_pivot in rbt space, r, theta_L in rbt space, d_L
// Vars: theta in rbt space, d
int modelNum = 4;
int paramNum = 5; //how many parameters
int varNum = 2; //how many variables
//Dimension Ranges for Params
std::vector< std::vector<double> > dRP (paramNum, std::vector<double> (2,0.0));
dRP[0][0] = 0.27; // ICRA 2014 and Vid1 - -0.2
dRP[0][1] = 0.27; // ICRA 2014 and Vid1 - -0.2
dRP[1][0] = 0.0;
dRP[1][1] = 0.0;
dRP[2][0] = 0.17; // ICRA 2014 and Vid1 - 0.1
dRP[2][1] = 0.17; // ICRA 2014 and Vid1 - 0.1
dRP[3][0] = -3.14159; // ICRA 2014 and Vid1 - 0.0
dRP[3][1] = -3.14159; // ICRA 2014 and Vid1 - 0.0
dRP[4][0] = 0.1;
dRP[4][1] = 0.1;
//Dimension Numbers for Params
std::vector<int> dNP (paramNum, 0);
dNP[0] = 1;
dNP[1] = 1;
dNP[2] = 1;
dNP[3] = 1;
dNP[4] = 1;
//Dimension Ranges for Vars
std::vector< std::vector<double> > dRV (varNum, std::vector<double> (2,0.0));
dRV[0][0] = -3.14159; // ICRA 2014 and Vid1 - -1.57
dRV[0][1] = 3.14159-0.26179938779*.5; // bs: 3.14159-0.26179938779 // ICRA 2014 and Vid1 - 1.57
dRV[1][0] = 0.0;
dRV[1][1] = 0.30; // bs: 0.27 // ICRA 2014 and Vid1 - 0.2
//Dimension Numbers for Vars
std::vector<int> dNV (varNum, 0);
dNV[0] = 24*2; // bs: 24 // ICRA 2014 and Vid1 - 12
dNV[1] = 16; // bs: 10
return setupModelFromDec(dRP,dNP,dRV,dNV,modelNum,modelParamPairs);
}
std::vector<stateStruct> setupUtils::setupModel5(std::vector<stateStruct>& modelParamPairs){
// Model 5 is the prismatic prismatic latch model
// State looks like:
// Model: 5
// Params: x_axis2,y_axis2,theta_axis2 in rbt space, d_L2, d_L1
// Vars: d_2, d_1
int modelNum = 5;
int paramNum = 5; //how many parameters
int varNum = 2; //how many variables
//Dimension Ranges for Params
std::vector< std::vector<double> > dRP (paramNum, std::vector<double> (2,0.0));
dRP[0][0] = -0.1;
dRP[0][1] = -0.1;
dRP[1][0] = -0.1;
dRP[1][1] = -0.1;
dRP[2][0] = 0.0;
dRP[2][1] = 0.0;
dRP[3][0] = 0.1;
dRP[3][1] = 0.1;
dRP[4][0] = 0.1;
dRP[4][1] = 0.1;
//Dimension Numbers for Params
std::vector<int> dNP (paramNum, 0);
dNP[0] = 1;
dNP[1] = 1;
dNP[2] = 1;
dNP[3] = 1;
dNP[4] = 1;
//Dimension Ranges for Vars
std::vector< std::vector<double> > dRV (varNum, std::vector<double> (2,0.0));
dRV[0][0] = 0.00; // used to be 0.01
dRV[0][1] = 0.20;
dRV[1][0] = 0.00; // used to be 0.01
dRV[1][1] = 0.20;
//Dimension Numbers for Vars
std::vector<int> dNV (varNum, 0);
dNV[0] = 9; // used to be 10
dNV[1] = 9;
return setupModelFromDec(dRP,dNP,dRV,dNV,modelNum,modelParamPairs);
}
////////////////////////////////////////////////////////////////////////////////
// End Model Section //
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Extra Model Section //
////////////////////////////////////////////////////////////////////////////////
std::vector<stateStruct> setupUtils::setupModel6(std::vector<stateStruct>& modelParamPairs){
// Model 2 is the revolute model
// State looks like:
// Model: 2
// Params: x_pivot,y_pivot in rbt space, r
// Vars: theta in rbt space
int modelNum = 2;
int paramNum = 3; //how many parameters
int varNum = 1; //how many variables
//Dimension Ranges for Params
std::vector< std::vector<double> > dRP (paramNum, std::vector<double> (2,0.0));
dRP[0][0] = 0.396; // ICRA 2014 - 0.3 - 0.3111
dRP[0][1] = 0.396; // ICRA 2014 - 0.3 - 0.3111
dRP[1][0] = -0.396; // ICRA 2014 - 0.3 - -0.3111
dRP[1][1] = -0.396; // ICRA 2014 - 0.3 - -0.3111
dRP[2][0] = 0.56; // ICRA 2014 - 0.3 - 0.44
dRP[2][1] = 0.56; // ICRA 2014 - 0.3 - 0.44
//Dimension Numbers for Params
std::vector<int> dNP (paramNum, 0);
dNP[0] = 1;
dNP[1] = 1;
dNP[2] = 1;
//Dimension Ranges for Vars
std::vector< std::vector<double> > dRV (varNum, std::vector<double> (2,0.0));
dRV[0][0] = -3.14159; // bs: 3.14
dRV[0][1] = 3.14159-0.065449846949787; // bs: 3.14
//Dimension Numbers for Vars
std::vector<int> dNV (varNum, 0);
dNV[0] = 96; // bs: 100
return setupModelFromDec(dRP,dNP,dRV,dNV,modelNum,modelParamPairs);
}
std::vector<stateStruct> setupUtils::setupModel7(std::vector<stateStruct>& modelParamPairs){
// Model 3 is the prismatic model
// State looks like:
// Model: 3
// Params: x_axis,y_axis,theta_axis in rbt space
// Vars: d
int modelNum = 3;
int paramNum = 3; //how many parameters
int varNum = 1; //how many variables
//Dimension Ranges for Params
std::vector< std::vector<double> > dRP (paramNum, std::vector<double> (2,0.0));
dRP[0][0] = 0.226274; // bs: 0.16 // ICRA 2014 - -0.16
dRP[0][1] = 0.226274; // bs: 0.16 // ICRA 2014 - -0.16
dRP[1][0] = 0.0; // ICRA 2014 - -0.16
dRP[1][1] = 0.0; // ICRA 2014 - -0.16
dRP[2][0] = -3.14159; // ICRA 2014 - 0.7865
dRP[2][1] = -3.14159; // ICRA 2014 - 0.7865
//Dimension Numbers for Params
std::vector<int> dNP (paramNum, 0);
dNP[0] = 1;
dNP[1] = 1;
dNP[2] = 1;
//Dimension Ranges for Vars
std::vector< std::vector<double> > dRV (varNum, std::vector<double> (2,0.0));
dRV[0][0] = -0.45255;
dRV[0][1] = 0.45255;
//Dimension Numbers for Vars
std::vector<int> dNV (varNum, 0);
dNV[0] = 49; // bs: 50
return setupModelFromDec(dRP,dNP,dRV,dNV,modelNum,modelParamPairs);
}
std::vector<stateStruct> setupUtils::setupModel8(std::vector<stateStruct>& modelParamPairs){
// Model 4 is the revolute prismatic latch model
// State looks like:
// Model: 4
// Params: x_pivot,y_pivot in rbt space, r, theta_L in rbt space, d_L
// Vars: theta in rbt space, d
int modelNum = 4;
int paramNum = 5; //how many parameters
int varNum = 2; //how many variables
//Dimension Ranges for Params
std::vector< std::vector<double> > dRP (paramNum, std::vector<double> (2,0.0));
dRP[0][0] = -0.27; // ICRA 2014 and Vid1 - -0.2
dRP[0][1] = -0.27; // ICRA 2014 and Vid1 - -0.2
dRP[1][0] = 0.0;
dRP[1][1] = 0.0;
dRP[2][0] = 0.17; // ICRA 2014 and Vid1 - 0.1
dRP[2][1] = 0.17; // ICRA 2014 and Vid1 - 0.1
dRP[3][0] = 0.0; // ICRA 2014 and Vid1 - 0.0
dRP[3][1] = 0.0; // ICRA 2014 and Vid1 - 0.0
dRP[4][0] = 0.1;
dRP[4][1] = 0.1;
//Dimension Numbers for Params
std::vector<int> dNP (paramNum, 0);
dNP[0] = 1;
dNP[1] = 1;
dNP[2] = 1;
dNP[3] = 1;
dNP[4] = 1;
//Dimension Ranges for Vars
std::vector< std::vector<double> > dRV (varNum, std::vector<double> (2,0.0));
dRV[0][0] = -3.14159; // ICRA 2014 and Vid1 - -1.57
dRV[0][1] = 3.14159-0.26179938779*.5; // bs: 3.14159-0.26179938779 // ICRA 2014 and Vid1 - 1.57
dRV[1][0] = 0.0;
dRV[1][1] = 0.30; // bs: 0.27 // ICRA 2014 and Vid1 - 0.2
//Dimension Numbers for Vars
std::vector<int> dNV (varNum, 0);
dNV[0] = 24*2; // bs: 24 // ICRA 2014 and Vid1 - 12
dNV[1] = 16; // bs: 10
return setupModelFromDec(dRP,dNP,dRV,dNV,modelNum,modelParamPairs);
}
std::vector<stateStruct> setupUtils::setupModel9(std::vector<stateStruct>& modelParamPairs){
// Model 5 is the prismatic prismatic latch model
// State looks like:
// Model: 5
// Params: x_axis2,y_axis2,theta_axis2 in rbt space, d_L2, d_L1
// Vars: d_2, d_1
int modelNum = 5;
int paramNum = 5; //how many parameters
int varNum = 2; //how many variables
//Dimension Ranges for Params
std::vector< std::vector<double> > dRP (paramNum, std::vector<double> (2,0.0));
dRP[0][0] = 0.1;
dRP[0][1] = 0.1;
dRP[1][0] = 0.1;
dRP[1][1] = 0.1;
dRP[2][0] = -3.14159;
dRP[2][1] = -3.14159;
dRP[3][0] = 0.1;
dRP[3][1] = 0.1;
dRP[4][0] = 0.1;
dRP[4][1] = 0.1;
//Dimension Numbers for Params
std::vector<int> dNP (paramNum, 0);
dNP[0] = 1;
dNP[1] = 1;
dNP[2] = 1;
dNP[3] = 1;
dNP[4] = 1;
//Dimension Ranges for Vars
std::vector< std::vector<double> > dRV (varNum, std::vector<double> (2,0.0));
dRV[0][0] = 0.00; // used to be 0.01
dRV[0][1] = 0.20;
dRV[1][0] = 0.00; // used to be 0.01
dRV[1][1] = 0.20;
//Dimension Numbers for Vars
std::vector<int> dNV (varNum, 0);
dNV[0] = 9; // used to be 10
dNV[1] = 9;
return setupModelFromDec(dRP,dNP,dRV,dNV,modelNum,modelParamPairs);
}
////////////////////////////////////////////////////////////////////////////////
// End Extra Model Section //
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Setup Section //
////////////////////////////////////////////////////////////////////////////////
//Create the list of states
void setupUtils::setupStates(std::vector<stateStruct>& stateList,std::vector<stateStruct>& modelParamPairs){
//setup model parameter pair lists for each model
std::vector<stateStruct> modelParamPairs0;
std::vector<stateStruct> modelParamPairs1;
std::vector<stateStruct> modelParamPairs2;
std::vector<stateStruct> modelParamPairs3;
std::vector<stateStruct> modelParamPairs4;
std::vector<stateStruct> modelParamPairs5;
std::vector<stateStruct> modelParamPairs6;
std::vector<stateStruct> modelParamPairs7;
std::vector<stateStruct> modelParamPairs8;
std::vector<stateStruct> modelParamPairs9;
//Set up a state list for each model.
//Then stick together all of the lists into one master list.
std::vector<stateStruct> stateList0 = setupModel0(modelParamPairs0);
std::vector<stateStruct> stateList1 = setupModel1(modelParamPairs1);
std::vector<stateStruct> stateList2 = setupModel2(modelParamPairs2);
std::vector<stateStruct> stateList3 = setupModel3(modelParamPairs3);
std::vector<stateStruct> stateList4 = setupModel4(modelParamPairs4);
std::vector<stateStruct> stateList5 = setupModel5(modelParamPairs5);
std::vector<stateStruct> stateList6 = setupModel6(modelParamPairs6);
std::vector<stateStruct> stateList7 = setupModel7(modelParamPairs7);
std::vector<stateStruct> stateList8 = setupModel8(modelParamPairs8);
std::vector<stateStruct> stateList9 = setupModel9(modelParamPairs9);
//populate the modelParamPairs vector
modelParamPairs = modelParamPairs0;
modelParamPairs.insert(modelParamPairs.end(), modelParamPairs1.begin(), modelParamPairs1.end());
modelParamPairs.insert(modelParamPairs.end(), modelParamPairs2.begin(), modelParamPairs2.end());
modelParamPairs.insert(modelParamPairs.end(), modelParamPairs3.begin(), modelParamPairs3.end());
modelParamPairs.insert(modelParamPairs.end(), modelParamPairs4.begin(), modelParamPairs4.end());
modelParamPairs.insert(modelParamPairs.end(), modelParamPairs5.begin(), modelParamPairs5.end());
modelParamPairs.insert(modelParamPairs.end(), modelParamPairs6.begin(), modelParamPairs6.end());
modelParamPairs.insert(modelParamPairs.end(), modelParamPairs7.begin(), modelParamPairs7.end());
modelParamPairs.insert(modelParamPairs.end(), modelParamPairs8.begin(), modelParamPairs8.end());
modelParamPairs.insert(modelParamPairs.end(), modelParamPairs9.begin(), modelParamPairs9.end());
//populate the stateList vector
stateList = stateList0;
stateList.insert(stateList.end(), stateList1.begin(), stateList1.end());
stateList.insert(stateList.end(), stateList2.begin(), stateList2.end());
stateList.insert(stateList.end(), stateList3.begin(), stateList3.end());
stateList.insert(stateList.end(), stateList4.begin(), stateList4.end());
stateList.insert(stateList.end(), stateList5.begin(), stateList5.end());
stateList.insert(stateList.end(), stateList6.begin(), stateList6.end());
stateList.insert(stateList.end(), stateList7.begin(), stateList7.end());
stateList.insert(stateList.end(), stateList8.begin(), stateList8.end());
stateList.insert(stateList.end(), stateList9.begin(), stateList9.end());
}
void setupUtils::setupModelParamPairs(std::vector<stateStruct>& stateList,std::vector<stateStruct>& modelParamPairs,std::vector<int>& numVarTypesPerStateType){
//1. Count up how many times certain instances occur
//A state type is a model-parameter pair
std::vector<stateStruct> tempModelParamPairs; //how many different model-parameter pairs
numVarTypesPerStateType.clear(); //how many different variable sets per model-parameter pair
bool addStateType;
for (size_t i=0; i<stateList.size(); i++){
addStateType = true;
for (size_t j=0; j<tempModelParamPairs.size(); j++){
if (stateList[i].model == tempModelParamPairs[j].model && stateList[i].params == tempModelParamPairs[j].params){
addStateType = false;
numVarTypesPerStateType[j]++;
break; //the break assumes we didn't somehow add the same pair twice to the found list
}
}
if (addStateType){
stateStruct tempState = stateList[i];
tempState.vars.clear(); // Remove variables from any model-param pair
tempModelParamPairs.push_back(tempState);
numVarTypesPerStateType.push_back(1);
}
}
modelParamPairs.clear(); // Empty the vector before reassigning
modelParamPairs = tempModelParamPairs;
}
//Overloaded
//setup a uniform prior over model and parameter pairs
void setupUtils::setupUniformPrior(std::vector<stateStruct>& stateList,std::vector<double>& probList){
//1. Count up how many times certain instances occur
//A state type is a model-parameter pair
std::vector<stateStruct> foundStateTypes; //how many different model-parameter pairs
std::vector<int> numVarTypesPerStateType; //how many different variable sets per model-parameter pair
bool addStateType;
for (size_t i=0; i<stateList.size(); i++){
addStateType = true;
for (size_t j=0; j<foundStateTypes.size(); j++){
if (stateList[i].model == foundStateTypes[j].model && stateList[i].params == foundStateTypes[j].params){
addStateType = false;
numVarTypesPerStateType[j]++;
break; //the break assumes we didn't somehow add the same pair twice to the found list
}
}
if (addStateType){
foundStateTypes.push_back(stateList[i]);
numVarTypesPerStateType.push_back(1);
}
}
//2. Figure out how much probability to assign to each instance
double probPerStateType = (1.0/foundStateTypes.size());
std::vector<double> probAmounts; //how much probability to assign per var type per state type. Same order as above.
for (size_t i=0; i<foundStateTypes.size(); i++){
probAmounts.push_back(probPerStateType/numVarTypesPerStateType[i]);
}
//3. Assing the probability to the right instances
std::vector<double> expProbList; //exponatiated probabilities
for (size_t i=0; i<stateList.size(); i++){
for (size_t j=0; j<foundStateTypes.size(); j++){
if (stateList[i].model == foundStateTypes[j].model && stateList[i].params == foundStateTypes[j].params){
expProbList.push_back(probAmounts[j]);
}
}
}
//4. Convert probabilities to log form
probList.clear(); //make sure this bad boy is empty
for (size_t i = 0; i<expProbList.size(); i++){
probList.push_back(logUtils::safe_log(expProbList[i]));
}
}
// Overloaded - this one has the model-parameter pairs passed to it
// setup a uniform prior over model and parameter pairs
void setupUtils::setupUniformPrior(std::vector<stateStruct>& stateList,std::vector<double>& probList,std::vector<stateStruct>& modelParamPairs){
// 1. Count up how many times certain instances occur
// A state type is a model-parameter pair
std::vector<int> numVarTypesPerStateType (modelParamPairs.size(),0); //how many different variable sets per model-parameter pair
for (size_t i=0; i<stateList.size(); i++){
for (size_t j=0; j<modelParamPairs.size(); j++){
if (stateList[i].model == modelParamPairs[j].model && stateList[i].params == modelParamPairs[j].params){
numVarTypesPerStateType[j]++;
break; //the break assumes we didn't somehow add the same pair twice to the found list
}
}
}
// 2. Figure out how much probability to assign to each instance
double probPerStateType = (1.0/modelParamPairs.size());
std::vector<double> probAmounts; //how much probability to assign per var type per state type. Same order as above.
for (size_t i=0; i<modelParamPairs.size(); i++){
probAmounts.push_back(probPerStateType/numVarTypesPerStateType[i]);
}
// 3. Assing the probability to the right instances
std::vector<double> expProbList; //exponatiated probabilities
for (size_t i=0; i<stateList.size(); i++){
for (size_t j=0; j<modelParamPairs.size(); j++){
if (stateList[i].model == modelParamPairs[j].model && stateList[i].params == modelParamPairs[j].params){
expProbList.push_back(probAmounts[j]);
}
}
}
// 4. Convert probabilities to log form
probList.clear(); // make sure this bad boy is empty
for (size_t i = 0; i<expProbList.size(); i++){
probList.push_back(logUtils::safe_log(expProbList[i]));
}
}
// This was here when you only had one model. You updated it on 2/5/14
/*
// setup a gaussian prior over cartesian positions of states
void setupUtils::setupGaussianPrior(std::vector<stateStruct>& stateList,std::vector<double>& probList){
probList.clear(); // make sure this bad boy is empty
// holders
std::vector<double> tempCartPosInRbt;
std::vector<double> assumedCartStartPosInRbt (2,0.0); // this is just your basic assumption. that the robot starts it's gripper at 0,0.
// Define covariance matrices
// Might want to change this later so that it's the same as something that makes sense already
// set additional variables
// create inverse matrix (hard coded)
//double invObsArray[] = {100.0,0.0,0.0,100.0}; // change
double invObsArray[] = {10000.0,0.0,0.0,10000.0};
std::vector<double> invObsCovMat;
invObsCovMat.assign(invObsArray, invObsArray + sizeof(invObsArray)/sizeof(double));
// create determinant (hard coded)
//double detCovMat = 0.0001; // change
double detCovMat = 0.00000001;
for (size_t i=0;i<stateList.size();i++){
tempCartPosInRbt = translator::translateStToRbt(stateList[i]);
probList.push_back(logUtils::evaluteLogMVG(tempCartPosInRbt,assumedCartStartPosInRbt,invObsCovMat,detCovMat));
}
// probList is not normalized because of the discretization
// normalize
probList = logUtils::normalizeVectorInLogSpace(probList);
}
*/
// Overloaded
// setup a gaussian prior over cartesian positions of states
void setupUtils::setupGaussianPrior(std::vector<stateStruct>& stateList,std::vector<double>& probList){
// 0. Setup the Gaussian used to calculate the probabilities of each state.
probList.clear(); // make sure this bad boy is empty
// holders
std::vector<double> tempCartPosInRbt;
std::vector<double> assumedCartStartPosInRbt (2,0.0); // this is just your basic assumption. that the robot starts it's gripper at 0,0.
// Define covariance matrices
// Might want to change this later so that it's the same as something that makes sense already
// set additional variables
// create inverse matrix (hard coded)
//double invObsArray[] = {100.0,0.0,0.0,100.0}; // change
double invObsArray[] = {10000.0,0.0,0.0,10000.0};
std::vector<double> invObsCovMat;
invObsCovMat.assign(invObsArray, invObsArray + sizeof(invObsArray)/sizeof(double));
// create determinant (hard coded)
//double detCovMat = 0.0001; // change
double detCovMat = 0.00000001;
// 1. Count up how many times certain instances occur
// A state type is a model-parameter pair
std::vector<stateStruct> foundStateTypes; // how many different model-parameter pairs
std::vector<int> numVarTypesPerStateType; // how many different variable sets per model-parameter pair
std::vector<std::vector<double> > stateTypeProbLists; // a list of lists of probabilites of the foundStateTypes
bool addStateType;
for (size_t i=0; i<stateList.size(); i++){
addStateType = true;
for (size_t j=0; j<foundStateTypes.size(); j++){
if (stateList[i].model == foundStateTypes[j].model && stateList[i].params == foundStateTypes[j].params){
addStateType = false;
numVarTypesPerStateType[j]++;
// Calculate value from Gaussian distribution
tempCartPosInRbt = translator::translateStToObs(stateList[i]);
stateTypeProbLists[j].push_back(logUtils::evaluteLogMVG(tempCartPosInRbt,assumedCartStartPosInRbt,invObsCovMat,detCovMat));
break; //the break assumes we didn't somehow add the same pair twice to the found list
}
}
if (addStateType){
foundStateTypes.push_back(stateList[i]);
numVarTypesPerStateType.push_back(1);
// Calculate value from Gaussian distribution
tempCartPosInRbt = translator::translateStToObs(stateList[i]);
std::vector<double> tempProbVect;
tempProbVect.push_back(logUtils::evaluteLogMVG(tempCartPosInRbt,assumedCartStartPosInRbt,invObsCovMat,detCovMat));
stateTypeProbLists.push_back(tempProbVect);
}
}
// 2. Normalize the vectors in stateTypeProbLists.
for (size_t i=0; i<stateTypeProbLists.size(); i++){
stateTypeProbLists[i] = logUtils::normalizeVectorInLogSpace(stateTypeProbLists[i]);
}
// 3. Figure out how much probability to assign to each model-param pair
double probPerStateType = logUtils::safe_log((1.0/foundStateTypes.size()));
/*
std::cout << "hi" << std::endl;
for (size_t i=0; i<stateTypeProbLists.size(); i++){
std::cout << i << std::endl;
for (size_t j=0; j<stateTypeProbLists[i].size(); j++){
std::cout << stateTypeProbLists[i][j] << ",";
}
std::cout << std::endl;
}
*/
// 4. Assign the probabilities to probList in the correct order.
// Also scale the probabilities (by adding) so the final distribution is a distribution
// (this assumes traversing stateList happens the same way every time. Which is probably true)
// This is FIFO
for (size_t i=0; i<stateList.size(); i++){
//std::cout << i << std::endl;
for (size_t j=0; j<foundStateTypes.size(); j++){
if (stateList[i].model == foundStateTypes[j].model && stateList[i].params == foundStateTypes[j].params){
/*
std::cout << "first" << std::endl;
std::cout << stateTypeProbLists[j][0] << std::endl;
std::cout << j << std::endl;
std::cout << probPerStateType << std::endl;
*/
probList.push_back(stateTypeProbLists[j][0]+probPerStateType); // access the first probability for that model parameter type + scale probabilities
//std::cout << "second" << std::endl;
stateTypeProbLists[j].erase(stateTypeProbLists[j].begin()); // erase the first element
break; // once you find the right type for a state, no need to keep iterating
}
}
}
}
// Overloaded - this one has the model-parameter pairs passed to it
// setup a gaussian prior over cartesian positions of states
void setupUtils::setupGaussianPrior(std::vector<stateStruct>& stateList,std::vector<double>& probList,std::vector<stateStruct>& modelParamPairs){
// 0. Setup the Gaussian used to calculate the probabilities of each state.
probList.clear(); // make sure this bad boy is empty
// holders
std::vector<double> tempCartPosInRbt;
std::vector<double> assumedCartStartPosInRbt (2,0.0); // this is just your basic assumption. that the robot starts it's gripper at 0,0.
// Define covariance matrices
// Might want to change this later so that it's the same as something that makes sense already
// set additional variables
// create inverse matrix (hard coded)
//double invObsArray[] = {100.0,0.0,0.0,100.0}; // change
double invObsArray[] = {10000.0,0.0,0.0,10000.0};
std::vector<double> invObsCovMat;
invObsCovMat.assign(invObsArray, invObsArray + sizeof(invObsArray)/sizeof(double));
// create determinant (hard coded)
//double detCovMat = 0.0001; // change
double detCovMat = 0.00000001;
// 1. Count up how many times certain instances occur
// A state type is a model-parameter pair
std::vector<int> numVarTypesPerStateType (modelParamPairs.size(),0); // how many different variable sets per model-parameter pair
std::vector<std::vector<double> > stateTypeProbLists (modelParamPairs.size(),std::vector<double>() ); // a list of lists of probabilites of the modelParamPairs
for (size_t i=0; i<stateList.size(); i++){
for (size_t j=0; j<modelParamPairs.size(); j++){
if (stateList[i].model == modelParamPairs[j].model && stateList[i].params == modelParamPairs[j].params){
numVarTypesPerStateType[j]++;
// Calculate value from Gaussian distribution
tempCartPosInRbt = translator::translateStToObs(stateList[i]);
stateTypeProbLists[j].push_back(logUtils::evaluteLogMVG(tempCartPosInRbt,assumedCartStartPosInRbt,invObsCovMat,detCovMat));
break; //the break assumes we didn't somehow add the same pair twice to the found list
}
}
}
// 2. Normalize the vectors in stateTypeProbLists.
for (size_t i=0; i<stateTypeProbLists.size(); i++){
stateTypeProbLists[i] = logUtils::normalizeVectorInLogSpace(stateTypeProbLists[i]);
}
// 3. Figure out how much probability to assign to each model-param pair
double probPerStateType = logUtils::safe_log((1.0/modelParamPairs.size()));
/*
std::cout << "hi" << std::endl;
for (size_t i=0; i<stateTypeProbLists.size(); i++){
std::cout << i << std::endl;
for (size_t j=0; j<stateTypeProbLists[i].size(); j++){
std::cout << stateTypeProbLists[i][j] << ",";
}
std::cout << std::endl;
}
*/
// 4. Assign the probabilities to probList in the correct order.
// Also scale the probabilities (by adding) so the final distribution is a distribution
// (this assumes traversing stateList happens the same way every time. Which is probably true)
// This is FIFO
for (size_t i=0; i<stateList.size(); i++){
//std::cout << i << std::endl;
for (size_t j=0; j<modelParamPairs.size(); j++){
if (stateList[i].model == modelParamPairs[j].model && stateList[i].params == modelParamPairs[j].params){
/*
std::cout << "first" << std::endl;
std::cout << stateTypeProbLists[j][0] << std::endl;
std::cout << j << std::endl;
std::cout << probPerStateType << std::endl;
*/
probList.push_back(stateTypeProbLists[j][0]+probPerStateType); // access the first probability for that model parameter type + scale probabilities
//std::cout << "second" << std::endl;
stateTypeProbLists[j].erase(stateTypeProbLists[j].begin()); // erase the first element
break; // once you find the right type for a state, no need to keep iterating
}
}
}
}
//Create the list of actions
void setupUtils::setupActions(std::vector< std::vector<double> >& actionList){
/*
std::vector<double> action1;
std::vector<double> action2;
std::vector<double> action3;
std::vector<double> action4;
action1.push_back(0.06);
action1.push_back(0.06);
action2.push_back(0.06);
action2.push_back(-0.06);
action3.push_back(-0.06);
action3.push_back(-0.06);
action4.push_back(-0.06);
action4.push_back(0.06);
actionList.clear();
actionList.push_back(action1);
actionList.push_back(action2);
actionList.push_back(action3);
actionList.push_back(action4);
*/
if(RELATIVE){
/*
std::vector<double> action1;
std::vector<double> action2;
std::vector<double> action3;
std::vector<double> action4;
action1.push_back(0.06);
action1.push_back(0.06);
action2.push_back(0.06);
action2.push_back(-0.06);
action3.push_back(-0.06);
action3.push_back(-0.06);
action4.push_back(-0.06);
action4.push_back(0.06);
actionList.clear();
actionList.push_back(action1);
actionList.push_back(action2);
actionList.push_back(action3);
actionList.push_back(action4);
*/
//This is totally 2D
// In a circle around the gripper
int numPts = 8; // how many points around the circle
double radius = 0.12; // radius of the points //used to be .06, big is .12
double angleDelta = 2*M_PI/numPts;
actionList.clear(); // clear anything in there
std::vector<double> tempAction; // slightly faster if outside
for (size_t i=0;i<numPts;i++){
tempAction.clear();
tempAction.push_back(radius*cos(i*angleDelta)); // add x component
tempAction.push_back(radius*sin(i*angleDelta)); // add y component
actionList.push_back(tempAction);
}
for(size_t i=0;i<actionList.size();i++){
std::cout << actionList[i][0] << "," << actionList[i][1] << std::endl;
}
}
else{
/*
std::vector<double> action1;
std::vector<double> action2;
std::vector<double> action3;
std::vector<double> action4;
action1.push_back(0.06);
action1.push_back(0.06);
action2.push_back(0.12);
action2.push_back(0.0);
action3.push_back(0.06);
action3.push_back(-0.06);
action4.push_back(0.0);
action4.push_back(0.0);
actionList.clear();
actionList.push_back(action1);
actionList.push_back(action2);
actionList.push_back(action3);
actionList.push_back(action4);
*/
// how many dimensions for an action
int actDimNum = 2;
//Dimension Ranges for Actions
std::vector< std::vector<double> > dRA (actDimNum, std::vector<double> (2,0.0));
dRA[0][0] = -0.12;
dRA[0][1] = 0.12;
dRA[1][0] = -0.12;
dRA[1][1] = 0.12;
//Dimension Numbers for Actions
std::vector<int> dNA (actDimNum, 0);
dNA[0] = 3;
dNA[1] = 3;
//setup for Actions
actionList = dimsToList(dRA,dNA);
}
}
////////////////////////////////////////////////////////////////////////////////
// End Setup Section //
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Validate Section //
////////////////////////////////////////////////////////////////////////////////
void setupUtils::validateStates(std::vector<stateStruct>& stateList,std::vector< std::vector<double> >& workspace){
// All workspace stuff right now assumes a 2D workspace - FIX
// States must be within the workspace and satisfy model-specific conditions
std::vector<stateStruct> tempStates;
for (size_t i=0;i<stateList.size();i++){
if (translator::isStateValid(stateList[i],workspace)){
tempStates.push_back(stateList[i]);
}
}
stateList.clear();
stateList = tempStates;
}
void setupUtils::validateActions(std::vector< std::vector<double> >& actionList,std::vector< std::vector<double> >& workspace){
// All workspace stuff right now assumes a 2D workspace - FIX
// Actions must be within the workspace
std::vector< std::vector<double> > tempActions;
for (size_t i=0;i<actionList.size();i++){
if (!(actionList[i][0]<workspace[0][0] || actionList[i][0]>workspace[0][1] || actionList[i][1]<workspace[1][0] || actionList[i][1]>workspace[1][1])){
tempActions.push_back(actionList[i]);
}
}
actionList.clear();
actionList = tempActions;
}
////////////////////////////////////////////////////////////////////////////////
// End Validate Section //
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Aux Section //
////////////////////////////////////////////////////////////////////////////////
std::vector<stateStruct> setupUtils::setupModelFromDec(std::vector< std::vector<double> >& dRP,std::vector<int>& dNP,std::vector< std::vector<double> >& dRV,std::vector<int>& dNV,int& modelNum,std::vector<stateStruct>& modelParamPairs){
//setup for model from decleration in setupModel*
std::vector< std::vector<double> > paramsList = dimsToList(dRP,dNP);
std::vector< std::vector<double> > varsList = dimsToList(dRV,dNV);
//fill in model-parameter pairs. vars is blank for a stateType
modelParamPairs.clear();
stateStruct tempState;
tempState.model=modelNum;
for (size_t i=0;i<paramsList.size();i++){
tempState.params=paramsList[i];
modelParamPairs.push_back(tempState);
}
return createStateListForModel(modelNum,paramsList,varsList);
}
std::vector<stateStruct> setupUtils::createStateListForModel(int modelNum,std::vector< std::vector<double> > paramsList,std::vector< std::vector<double> > varsList){
std::vector<stateStruct> stateList;
stateStruct tempState;
tempState.model=modelNum;
for (size_t i=0; i<paramsList.size(); i++){
tempState.params=paramsList[i];
for (size_t j=0; j<varsList.size(); j++){
tempState.vars=varsList[j];
stateList.push_back(tempState);
}
}
return stateList;
}
//convert from set of dimension ranges and number of points to a list of points
std::vector< std::vector<double> > setupUtils::dimsToList(std::vector< std::vector<double> > dimRanges, std::vector<int> dimNums){
std::vector< std::vector<double> > valueList = createValueList(dimRanges,dimNums);
return recurseList(std::vector< std::vector<double> > (), std::vector<double> (), 0, valueList);
}
//create the value list to set up states
std::vector< std::vector<double> > setupUtils::createValueList(std::vector< std::vector<double> > dimRanges, std::vector<int> dimNums){
//there might be a shorter way
std::vector< std::vector<double> > valueList;
int dims = dimNums.size(); //how many dimension numbers is the number of dimensions
for (size_t i=0; i<dims; i++) {
double delta = 0.0;
if (dimNums[i]>1){
delta = (dimRanges[i][1]-dimRanges[i][0])/(dimNums[i]-1); //-1 because of the spacing
}
std::vector<double> tempVect;
for (size_t j=0; j<dimNums[i]; j++) {
// This is ridiculous - huge SAS problem - crazy fix
// HACK THIS IS NOT A FIX DELETE CHECK
tempVect.push_back(dimRanges[i][0]+delta*j);
}
valueList.push_back(tempVect);
}
return valueList;
}
//the recursive function
std::vector< std::vector<double> > setupUtils::recurseList(std::vector< std::vector<double> > totalList, std::vector<double> oldSeq, int level, std::vector< std::vector<double> > valueList){
//if (level>valueList.size()-1) {
if (level>=valueList.size()) {
totalList.push_back(oldSeq);
}
else {
for (size_t i=0; i<valueList[level].size(); i++) {
oldSeq.push_back(valueList[level][i]);
totalList = recurseList(totalList,oldSeq,level+1,valueList);
oldSeq.pop_back();
}
}
return totalList;
}
////////////////////////////////////////////////////////////////////////////////
// End Aux Section //
////////////////////////////////////////////////////////////////////////////////
| true |
5a0db6fc2625224fe377567c9eaa9618f878f9b4 | C++ | olwal/microdollar | /src/Templates.h | UTF-8 | 1,947 | 3.15625 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | /*
MicroDollar: $1 Gesture Recognizer C++ port with optimizations for embedded hardware | Alex Olwal (www.olwal.com)
Gesture template classes, specified as a C++ Template to allow use of different data types for data (e.g., int or float).
This allows portability between 8-bit microcontrollers and more advanced platforms (for increased precision).
*/
#ifndef _TEMPLATES_H_
#define _TEMPLATES_H_
// Template with points and index for a gesture to recognize
template <class T>
class Template
{
public:
T * points;
int nPoints;
int index;
bool allocated;
Template() : nPoints(0), index(0), allocated(false)
{
}
void init(int nValues)
{
allocate(nValues);
}
~Template()
{
deallocate();
}
void allocate(int nValues)
{
if (allocated)
deallocate();
points = new T[nValues];
nPoints = nValues;
memset(points, 0, nValues);
//points[N_VALUES - 1] = -1; //for debugging
allocated = true;
}
void deallocate()
{
if (allocated)
{
delete[] points;
}
allocated = false;
}
};
// Holds a set of Templates for each gesture that we want to recognize
template <class T>
class Templates
{
public:
bool allocated;
Template <T> * templates;
int nLoaded;
Templates() : nLoaded(0), allocated(false)
{
}
~Templates()
{
deallocate();
}
void init(int nValues, int nTemplates)
{
allocate(nValues, nTemplates);
}
void allocate(int nValues, int nTemplates)
{
if (allocated)
deallocate();
templates = new Template<T>[nTemplates];
for (int i = 0; i < nTemplates; i++)
templates[i].init(nValues);
allocated = true;
}
void deallocate()
{
if (allocated)
{
delete[] templates;
}
allocated = false;
}
T * getPoints(int index)
{
return templates[index].points;
}
int getNPoints(int index)
{
return templates[index].nPoints;
}
};
#endif
| true |
a343db7f600c1d19f9c73ff87c79faad9fa23a48 | C++ | Phoenix-RK/Leetcode | /38. Count and Say.cpp | UTF-8 | 1,724 | 3.59375 | 4 | [] | no_license | //Phoenix_RK
/*
The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
countAndSay(1) = "1"
countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is then converted into a different digit string.
To determine how you "say" a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character. Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying.
Given a positive integer n, return the nth term of the count-and-say sequence.
Example 1:
Input: n = 1
Output: "1"
Explanation: This is the base case.
Example 2:
Input: n = 4
Output: "1211"
Explanation:
countAndSay(1) = "1"
countAndSay(2) = say "1" = one 1 = "11"
countAndSay(3) = say "11" = two 1's = "21"
countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211"
*/
class Solution {
public:
string countChar(int n,string s)
{
if(n==1)
{
return "1";
}
else
{
string res="";
s= countChar(n-1,s);
int i=0;
while(i<s.length())
{
int count=1;
char ch=s[i++];
while(i<s.length() && s[i]==ch)
{
count++;
i++;
}
res=res+to_string(count)+ch;
}
return res;
}
}
string countAndSay(int n) {
string s="";
return countChar(n,s);
}
};
| true |
620af9f4ed73bbf353e4ebaf375cd36109dd0342 | C++ | atulk471/Hacktoberfest2021 | /Convert_time_in_words.cpp | UTF-8 | 1,224 | 3.15625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
string timeInWords(int h, int m) {
vector<string> v = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "twenty one", "twenty two", "twenty three", "twenty four", "twenty five", "twenty six", "twenty seven", "twenty eight", "twenty nine" };
string time;
if(m<=30){
if(m==0)
time=v[h]+" o' clock";
else if(m==15)
time="quarter past "+v[h];
else if(m==30)
time="half past "+v[h];
else if(m==1)
time=v[m]+" minute past "+v[h];
else
time=v[m]+" minutes past "+v[h];
}
else{
if(m==45)
time="quarter to "+v[h+1];
else if(m==59)
time=v[60-m]+" minute to "+v[h+1];
else
time=v[60-m]+" minutes to "+v[h+1];
}
return time;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int h;
cin >> h;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
int m;
cin >> m;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string result = timeInWords(h, m);
fout << result << "\n";
fout.close();
return 0;
}
| true |
65b70e17d070667b98fd2b8e1fab9e58bcc85959 | C++ | leighpauls/cs343 | /assignment_4/q2Santa.cc | UTF-8 | 906 | 2.703125 | 3 | [] | no_license | #include "q2Santa.h"
#include "q2Yielder.h"
Santa::Santa(Workshop& wrk, Printer& prt) : mWorkshop(wrk), mPrinter(prt) {}
void Santa::main() {
randomYield(10);
mPrinter.print(SANTA_ID, Printer::Starting);
for (;;) {
randomYield(3);
mPrinter.print(SANTA_ID, Printer::Napping);
Workshop::Status status = mWorkshop.sleep();
mPrinter.print(SANTA_ID, Printer::Awake);
if (status == Workshop::Done) {
break;
} else if (status == Workshop::Delivery) {
mPrinter.print(SANTA_ID, Printer::DeliveringToys);
randomYield(5);
mWorkshop.doneDelivering(SANTA_ID);
mPrinter.print(SANTA_ID, Printer::DoneDelivering);
} else {
mPrinter.print(SANTA_ID, Printer::Consulting);
randomYield(3);
mWorkshop.doneConsulting(SANTA_ID);
mPrinter.print(SANTA_ID, Printer::DoneConsulting);
}
}
mPrinter.print(SANTA_ID, Printer::Finished);
}
| true |
580c4626bb643eb9966cb02a89799365e2cb8058 | C++ | ellynhan/programmers | /functionDev.cpp | UTF-8 | 542 | 2.859375 | 3 | [] | no_license | #include <vector>
using namespace std;
vector<int> solution(vector<int> progresses, vector<int> speeds) {
vector<int> answer;
while(!progresses.empty()){
for(int i=0; i<progresses.size(); i++){
progresses[i]+=speeds[i];
}
int result=0;
while(*progresses.begin()>=100&&!progresses.empty()){
result++;
progresses.erase(progresses.begin());
speeds.erase(speeds.begin());
}
if(result!=0)answer.push_back(result);
}
return answer;
}
| true |
65aaa794249cc4481a69c8a4b57f7c010f56243c | C++ | BornaBiro/Inkplate6P | /examples/Inkplate_Simple_Backlight/Inkplate_Simple_Backlight.ino | UTF-8 | 1,385 | 3.265625 | 3 | [] | no_license | #include "Inkplate6Plus.h" //Include Inkplate library
Inkplate display(INKPLATE_1BIT); //Create an object on Inkplate class
int b = 31; //Variable that holds intensity of the backlight
void setup() {
Serial.begin(115200); //Set up a serial communication of 115200 baud
display.begin(); //Init Inkplate library
display.backlight(true); //Enable backlight circuit
display.setBacklight(b); //Set backlight intensity
}
void loop() {
if (Serial.available()) //Change backlight value by sending "+" sign into serial monitor to increase backlight or "-" sign to decrese backlight
{
bool change = false; //Variable that indicates that backlight value has changed and intessity has to be updated
char c = Serial.read(); //Read incomming serial data
if (c == '+' && b < 63) //If is received +, increase backlight
{
b++;
change = true;
}
if (c == '-' && b > 0) //If is received -, decrease backlight
{
b--;
change = true;
}
if (change) //If backlight valuse has changed, update the intensity and show current value of backlight
{
display.setBacklight(b);
Serial.print("Backlight:");
Serial.print(b, DEC);
Serial.println("/63");
}
}
}
| true |
f32bc7cf00e3abc0fd699ce733cbdf8976cee733 | C++ | satsukisahi/AtCoder | /01solved/AGC-C/agc002-c.cpp | UTF-8 | 494 | 2.546875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)
int main()
{
ll n , l ;
cin >> n >> l ;
vector<ll> a(n+1);
vector<ll> ans;
rep(i, n){
cin >> a[i+1];
}
rep(i,n){
if(a[i]+a[i+1]>=l){
for(ll j=i;j>0;j--)ans.push_back(j);
for(ll j=i+1;j<n;j++)ans.push_back(j);
cout << "Possible" << endl;
rep(i,n-1){
cout << ans[n-i-2] << endl;
}
return 0;
}
}
cout << "Impossible" << endl;
return 0;
}
| true |
e840aa63a02d77278965a9571a82ba3b511b70d9 | C++ | PsichiX/XenonCore2 | /XenonFramework2/XenonFramework2/XeFramework/Singleton.inl | UTF-8 | 697 | 2.625 | 3 | [] | no_license | #include "MemoryManager.h"
template< class T >
T* Singleton< T >::instance = 0;
template< class T >
T& Singleton< T >::use()
{
if( !Singleton< T >::instance )
#if defined( XMM_MEMORY_TRACING_MODE )
Singleton< T >::instance = MemoryManager::__newDebug< T >( __FILE__, __LINE__ );
#else
Singleton< T >::instance = MemoryManager::__new< T >();
#endif
return( *Singleton< T >::instance );
}
template< class T >
void Singleton< T >::destroy()
{
if( Singleton< T >::instance )
{
#if defined( XMM_MEMORY_TRACING_MODE )
MemoryManager::__deleteDebug< T >( Singleton< T >::instance );
#else
MemoryManager::__delete< T >( Singleton< T >::instance );
#endif
Singleton< T >::instance = 0;
}
} | true |
4bb1caddf8406b661b2dd087a65721e57ddcaecd | C++ | zhanghua0926/GifImageSource | /GifImage/Shared/Vector4F.h | UTF-8 | 676 | 2.734375 | 3 | [
"MIT"
] | permissive | #pragma once
namespace GifImage
{
public ref class Vector4F sealed
{
float m_x;
float m_y;
float m_z;
float m_w;
public:
Vector4F(float x, float y,float z, float w) :m_x(x), m_y(y),m_z(z),m_w(w)
{
}
property float X {
float get() {
return m_x;
}
void set(float value) {
m_x = value;
}
}
property float Y {
float get() {
return m_y;
}
void set(float value) {
m_y = value;
}
}
property float Z {
float get() {
return m_z;
}
void set(float value) {
m_z = value;
}
}
property float W {
float get() {
return m_w;
}
void set(float value) {
m_w = value;
}
}
};
}
| true |
816379cf26c23cacf31a78aa1ccf0400d628e274 | C++ | liuxinyu123/effective_cpp | /item3/textblock.h | UTF-8 | 292 | 2.515625 | 3 | [] | no_license | #ifndef _TEXTBLOCK_H_
#define _TEXTBLOCK_H_
#include <string>
class TextBlock
{
public:
TextBlock (const std::string &s = "");
TextBlock (const TextBlock &tb);
char& operator[] (std::size_t i);
const char& operator[] (std::size_t i) const;
private:
std::string text;
};
#endif
| true |
d181c92e34da71eee59d61cb6d87325dc32eb37b | C++ | wfystx/LeetCodeDailyPractice | /HashMap/290WordPattern.cpp | UTF-8 | 437 | 2.734375 | 3 | [] | no_license | class Solution {
public:
bool wordPattern(string pattern, string str) {
unordered_map<char,int> m1;
unordered_map<string,int> m2;
istringstream in(str);
int i = 0, n = pattern.size();
for (string word; in >> word; ++i) {
if (i == n || m1[pattern[i]] != m2[word])
return false;
m1[pattern[i]] = m2[word] = i + 1;
}
return i == n;
}
}; | true |
2195cc3902850fab54f09c572bfac5d3643403d4 | C++ | Amoners/cc0 | /src/toolchain/core/CodeDom/BlockExpression.cpp | UTF-8 | 1,040 | 2.671875 | 3 | [
"BSD-2-Clause"
] | permissive |
#include "BlockExpression.h"
#include <stdlib.h>
#include "ExpressionVisitor.h"
#include <core/Type/VoidType.h>
BlockExpression::BlockExpression()
: Expression(Expression::Block), _scope(NULL)
{
_expressions = new std::vector<Expression *>();
//FIXME: memory leak!
}
BlockExpression::~BlockExpression()
{
}
void BlockExpression::Accept(ExpressionVisitor* visitor)
{
visitor->Visit(this);
}
Expression* BlockExpression::GetLValue()
{
return NULL;
}
std::vector<Expression *> * BlockExpression::GetExpressionList()
{
return _expressions;
}
Type* BlockExpression::GetType()
{
if (_expressions->empty())
{
return new VoidType();
}
else
{
return (*_expressions)[_expressions->size() - 1]->GetType();
}
}
void BlockExpression::SetExpressionList(std::vector< Expression* >* exprList)
{
_expressions = exprList;
}
SymbolScope* BlockExpression::GetBlockScope()
{
return _scope;
}
void* BlockExpression::SetBlockScope(SymbolScope* scope)
{
_scope = scope;
}
| true |
ec5f8d6e4985b93da6f637b14feb42eb4f1c50bb | C++ | Shashank-Ojha-bot/DSA-Topicwise-Questions | /Arrays/MaxDifference.cpp | UTF-8 | 729 | 3.28125 | 3 | [] | no_license | //Naive Solution:TC- theta(N^2)
#include<bits/stdc++.h>
using namespace std;
//int MaxDifference(int arr[],int n)
//{
// int res=arr[1]-arr[0];
// for(int i=0;i<n;i++)
// {
// for(int j=i+1;j<n;j++)
// {
// res=max(res,arr[j]-arr[i]);
// }
// }
// return res;
//}
//int main()
//{
// int arr[]={2,3,10,6,4,8,1};
// int size=sizeof(arr)/sizeof(arr[0]);
// cout<<MaxDifference(arr,size);
//}
//Efficient Solution- theta(N)
int MaxDifference(int arr[],int n)
{
int res=arr[1]-arr[0];
int minVal=arr[0];
for(int j=0;j<n;j++)
{
res=max(res,arr[j]-minVal);
minVal=min(minVal,arr[j]);
}
return res;
}
int main()
{
int arr[]={2,3,10,6,4,8,1};
int size=sizeof(arr)/sizeof(arr[0]);
cout<<MaxDifference(arr,size);
}
| true |
4f05292d6bb46852623b54787cc22ed9704b6e5a | C++ | gnachman/fish-shell | /builtin_set.cpp | UTF-8 | 20,330 | 2.640625 | 3 | [] | no_license | /** \file builtin_set.c Functions defining the set builtin
Functions used for implementing the set builtin.
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <wchar.h>
#include <wctype.h>
#include <sys/types.h>
#include <termios.h>
#include <signal.h>
#include <vector>
#include <algorithm>
#include "fallback.h"
#include "util.h"
#include "wutil.h"
#include "builtin.h"
#include "env.h"
#include "expand.h"
#include "common.h"
#include "wgetopt.h"
#include "proc.h"
#include "parser.h"
/* We know about these buffers */
extern wcstring stdout_buffer, stderr_buffer;
/**
Error message for invalid path operations
*/
#define BUILTIN_SET_PATH_ERROR L"%ls: Warning: path component %ls may not be valid in %ls.\n"
/**
Hint for invalid path operation with a colon
*/
#define BUILTIN_SET_PATH_HINT L"%ls: Did you mean 'set %ls $%ls %ls'?\n"
/**
Error for mismatch between index count and elements
*/
#define BUILTIN_SET_ARG_COUNT L"%ls: The number of variable indexes does not match the number of values\n"
/**
Test if the specified variable should be subject to path validation
*/
static int is_path_variable(const wchar_t *env)
{
return contains(env, L"PATH", L"CDPATH");
}
/**
Call env_set. If this is a path variable, e.g. PATH, validate the
elements. On error, print a description of the problem to stderr.
*/
static int my_env_set(const wchar_t *key, const wcstring_list_t &val, int scope)
{
size_t i;
int retcode = 0;
const wchar_t *val_str=NULL;
if (is_path_variable(key))
{
/* Fix for https://github.com/fish-shell/fish-shell/issues/199 . Return success if any path setting succeeds. */
bool any_success = false;
/* Don't bother validating (or complaining about) values that are already present */
wcstring_list_t existing_values;
const env_var_t existing_variable = env_get_string(key, scope);
if (! existing_variable.missing_or_empty())
tokenize_variable_array(existing_variable, existing_values);
for (i=0; i< val.size() ; i++)
{
const wcstring &dir = val.at(i);
if (list_contains_string(existing_values, dir))
{
any_success = true;
continue;
}
bool show_perror = false;
int show_hint = 0;
bool error = false;
struct stat buff;
if (wstat(dir, &buff))
{
error = true;
show_perror = true;
}
if (!(S_ISDIR(buff.st_mode)))
{
error = true;
}
if (!error)
{
any_success = true;
}
else
{
append_format(stderr_buffer, _(BUILTIN_SET_PATH_ERROR), L"set", dir.c_str(), key);
const wchar_t *colon = wcschr(dir.c_str(), L':');
if (colon && *(colon+1))
{
show_hint = 1;
}
}
if (show_perror)
{
builtin_wperror(L"set");
}
if (show_hint)
{
append_format(stderr_buffer, _(BUILTIN_SET_PATH_HINT), L"set", key, key, wcschr(dir.c_str(), L':')+1);
}
}
/* Fail at setting the path if we tried to set it to something non-empty, but it wound up empty. */
if (! val.empty() && ! any_success)
{
return 1;
}
}
wcstring sb;
if (! val.empty())
{
for (i=0; i< val.size() ; i++)
{
sb.append(val[i]);
if (i<val.size() - 1)
{
sb.append(ARRAY_SEP_STR);
}
}
val_str = sb.c_str();
}
switch (env_set(key, val_str, scope | ENV_USER))
{
case ENV_PERM:
{
append_format(stderr_buffer, _(L"%ls: Tried to change the read-only variable '%ls'\n"), L"set", key);
retcode=1;
break;
}
case ENV_SCOPE:
{
append_format(stderr_buffer, _(L"%ls: Tried to set the special variable '%ls' with the wrong scope\n"), L"set", key);
retcode=1;
break;
}
case ENV_INVALID:
{
append_format(stderr_buffer, _(L"%ls: Unknown error"), L"set");
retcode=1;
break;
}
}
return retcode;
}
/**
Extract indexes from a destination argument of the form name[index1 index2...]
\param indexes the list to insert the new indexes into
\param src the source string to parse
\param name the name of the element. Return null if the name in \c src does not match this name
\param var_count the number of elements in the array to parse.
\return the total number of indexes parsed, or -1 on error
*/
static int parse_index(std::vector<long> &indexes,
const wchar_t *src,
const wchar_t *name,
size_t var_count)
{
size_t len;
int count = 0;
const wchar_t *src_orig = src;
if (src == 0)
{
return 0;
}
while (*src != L'\0' && (iswalnum(*src) || *src == L'_'))
{
src++;
}
if (*src != L'[')
{
append_format(stderr_buffer, _(BUILTIN_SET_ARG_COUNT), L"set");
return 0;
}
len = src-src_orig;
if ((wcsncmp(src_orig, name, len)!=0) || (wcslen(name) != (len)))
{
append_format(stderr_buffer,
_(L"%ls: Multiple variable names specified in single call (%ls and %.*ls)\n"),
L"set",
name,
len,
src_orig);
return 0;
}
src++;
while (iswspace(*src))
{
src++;
}
while (*src != L']')
{
wchar_t *end;
long l_ind;
errno = 0;
l_ind = wcstol(src, &end, 10);
if (end==src || errno)
{
append_format(stderr_buffer, _(L"%ls: Invalid index starting at '%ls'\n"), L"set", src);
return 0;
}
if (l_ind < 0)
{
l_ind = var_count+l_ind+1;
}
src = end;
if (*src==L'.' && *(src+1)==L'.')
{
src+=2;
long l_ind2 = wcstol(src, &end, 10);
if (end==src || errno)
{
return 1;
}
src = end;
if (l_ind2 < 0)
{
l_ind2 = var_count+l_ind2+1;
}
int direction = l_ind2<l_ind ? -1 : 1 ;
for (long jjj = l_ind; jjj*direction <= l_ind2*direction; jjj+=direction)
{
// debug(0, L"Expand range [set]: %i\n", jjj);
indexes.push_back(jjj);
count++;
}
}
else
{
indexes.push_back(l_ind);
count++;
}
while (iswspace(*src)) src++;
}
return count;
}
static int update_values(wcstring_list_t &list,
std::vector<long> &indexes,
wcstring_list_t &values)
{
size_t i;
/* Replace values where needed */
for (i = 0; i < indexes.size(); i++)
{
/*
The '- 1' below is because the indices in fish are
one-based, but the vector uses zero-based indices
*/
long ind = indexes[i] - 1;
const wcstring newv = values[ i ];
if (ind < 0)
{
return 1;
}
if ((size_t)ind >= list.size())
{
list.resize(ind+1);
}
// free((void *) al_get(list, ind));
list[ ind ] = newv;
}
return 0;
}
/**
Erase from a list of wcstring values at specified indexes
*/
static void erase_values(wcstring_list_t &list, const std::vector<long> &indexes)
{
// Make a set of indexes.
// This both sorts them into ascending order and removes duplicates.
const std::set<long> indexes_set(indexes.begin(), indexes.end());
// Now walk the set backwards, so we encounter larger indexes first, and remove elements at the given (1-based) indexes.
std::set<long>::const_reverse_iterator iter;
for (iter = indexes_set.rbegin(); iter != indexes_set.rend(); ++iter)
{
long val = *iter;
if (val > 0 && (size_t)val <= list.size())
{
// One-based indexing!
list.erase(list.begin() + val - 1);
}
}
}
/**
Print the names of all environment variables in the scope, with or without shortening,
with or without values, with or without escaping
*/
static void print_variables(int include_values, int esc, bool shorten_ok, int scope)
{
wcstring_list_t names = env_get_names(scope);
sort(names.begin(), names.end());
for (size_t i = 0; i < names.size(); i++)
{
const wcstring key = names.at(i);
const wcstring e_key = escape_string(key, 0);
stdout_buffer.append(e_key);
if (include_values)
{
env_var_t value = env_get_string(key, scope);
if (!value.missing())
{
int shorten = 0;
if (shorten_ok && value.length() > 64)
{
shorten = 1;
value.resize(60);
}
wcstring e_value = esc ? expand_escape_variable(value) : value;
stdout_buffer.append(L" ");
stdout_buffer.append(e_value);
if (shorten)
{
stdout_buffer.push_back(ellipsis_char);
}
}
}
stdout_buffer.append(L"\n");
}
}
/**
The set builtin. Creates, updates and erases environment variables
and environemnt variable arrays.
*/
static int builtin_set(parser_t &parser, wchar_t **argv)
{
/** Variables used for parsing the argument list */
const struct woption long_options[] =
{
{ L"export", no_argument, 0, 'x' },
{ L"global", no_argument, 0, 'g' },
{ L"local", no_argument, 0, 'l' },
{ L"erase", no_argument, 0, 'e' },
{ L"names", no_argument, 0, 'n' },
{ L"unexport", no_argument, 0, 'u' },
{ L"universal", no_argument, 0, 'U' },
{ L"long", no_argument, 0, 'L' },
{ L"query", no_argument, 0, 'q' },
{ L"help", no_argument, 0, 'h' },
{ 0, 0, 0, 0 }
} ;
const wchar_t *short_options = L"+xglenuULqh";
int argc = builtin_count_args(argv);
/*
Flags to set the work mode
*/
int local = 0, global = 0, exportv = 0;
int erase = 0, list = 0, unexport=0;
int universal = 0, query=0;
bool shorten_ok = true;
bool preserve_incoming_failure_exit_status = true;
const int incoming_exit_status = proc_get_last_status();
/*
Variables used for performing the actual work
*/
wchar_t *dest = 0;
int retcode=0;
int scope;
int slice=0;
int i;
const wchar_t *bad_char = NULL;
/* Parse options to obtain the requested operation and the modifiers */
woptind = 0;
while (1)
{
int c = wgetopt_long(argc, argv, short_options, long_options, 0);
if (c == -1)
{
break;
}
switch (c)
{
case 0:
break;
case 'e':
erase = 1;
preserve_incoming_failure_exit_status = false;
break;
case 'n':
list = 1;
preserve_incoming_failure_exit_status = false;
break;
case 'x':
exportv = 1;
break;
case 'l':
local = 1;
break;
case 'g':
global = 1;
break;
case 'u':
unexport = 1;
break;
case 'U':
universal = 1;
break;
case 'L':
shorten_ok = false;
break;
case 'q':
query = 1;
preserve_incoming_failure_exit_status = false;
break;
case 'h':
builtin_print_help(parser, argv[0], stdout_buffer);
return 0;
case '?':
builtin_unknown_option(parser, argv[0], argv[woptind-1]);
return 1;
default:
break;
}
}
/*
Ok, all arguments have been parsed, let's validate them
*/
/*
If we are checking the existance of a variable (-q) we can not
also specify scope
*/
if (query && (erase || list))
{
append_format(stderr_buffer,
BUILTIN_ERR_COMBO,
argv[0]);
builtin_print_help(parser, argv[0], stderr_buffer);
return 1;
}
/* We can't both list and erase variables */
if (erase && list)
{
append_format(stderr_buffer,
BUILTIN_ERR_COMBO,
argv[0]);
builtin_print_help(parser, argv[0], stderr_buffer);
return 1;
}
/*
Variables can only have one scope
*/
if (local + global + universal > 1)
{
append_format(stderr_buffer,
BUILTIN_ERR_GLOCAL,
argv[0]);
builtin_print_help(parser, argv[0], stderr_buffer);
return 1;
}
/*
Variables can only have one export status
*/
if (exportv && unexport)
{
append_format(stderr_buffer,
BUILTIN_ERR_EXPUNEXP,
argv[0]);
builtin_print_help(parser, argv[0], stderr_buffer);
return 1;
}
/*
Calculate the scope value for variable assignement
*/
scope = (local ? ENV_LOCAL : 0) | (global ? ENV_GLOBAL : 0) | (exportv ? ENV_EXPORT : 0) | (unexport ? ENV_UNEXPORT : 0) | (universal ? ENV_UNIVERSAL:0) | ENV_USER;
if (query)
{
/*
Query mode. Return the number of variables that do not exist
out of the specified variables.
*/
int i;
for (i=woptind; i<argc; i++)
{
wchar_t *arg = argv[i];
int slice=0;
if (!(dest = wcsdup(arg)))
{
DIE_MEM();
}
if (wcschr(dest, L'['))
{
slice = 1;
*wcschr(dest, L'[')=0;
}
if (slice)
{
std::vector<long> indexes;
wcstring_list_t result;
size_t j;
env_var_t dest_str = env_get_string(dest, scope);
if (! dest_str.missing())
tokenize_variable_array(dest_str, result);
if (!parse_index(indexes, arg, dest, result.size()))
{
builtin_print_help(parser, argv[0], stderr_buffer);
retcode = 1;
break;
}
for (j=0; j < indexes.size() ; j++)
{
long idx = indexes[j];
if (idx < 1 || (size_t)idx > result.size())
{
retcode++;
}
}
}
else
{
if (!env_exist(arg, scope))
{
retcode++;
}
}
free(dest);
}
return retcode;
}
if (list)
{
/* Maybe we should issue an error if there are any other arguments? */
print_variables(0, 0, shorten_ok, scope);
return 0;
}
if (woptind == argc)
{
/*
Print values of variables
*/
if (erase)
{
append_format(stderr_buffer,
_(L"%ls: Erase needs a variable name\n"),
argv[0]);
builtin_print_help(parser, argv[0], stderr_buffer);
retcode = 1;
}
else
{
print_variables(1, 1, shorten_ok, scope);
}
return retcode;
}
if (!(dest = wcsdup(argv[woptind])))
{
DIE_MEM();
}
if (wcschr(dest, L'['))
{
slice = 1;
*wcschr(dest, L'[')=0;
}
if (!wcslen(dest))
{
free(dest);
append_format(stderr_buffer, BUILTIN_ERR_VARNAME_ZERO, argv[0]);
builtin_print_help(parser, argv[0], stderr_buffer);
return 1;
}
if ((bad_char = wcsvarname(dest)))
{
append_format(stderr_buffer, BUILTIN_ERR_VARCHAR, argv[0], *bad_char);
builtin_print_help(parser, argv[0], stderr_buffer);
free(dest);
return 1;
}
/*
set assignment can work in two modes, either using slices or
using the whole array. We detect which mode is used here.
*/
if (slice)
{
/*
Slice mode
*/
std::vector<long> indexes;
wcstring_list_t result;
const env_var_t dest_str = env_get_string(dest, scope);
if (! dest_str.missing())
{
tokenize_variable_array(dest_str, result);
}
else if (erase)
{
retcode = 1;
}
if (!retcode)
{
for (; woptind<argc; woptind++)
{
if (!parse_index(indexes, argv[woptind], dest, result.size()))
{
builtin_print_help(parser, argv[0], stderr_buffer);
retcode = 1;
break;
}
size_t idx_count = indexes.size();
size_t val_count = argc-woptind-1;
if (!erase)
{
if (val_count < idx_count)
{
append_format(stderr_buffer, _(BUILTIN_SET_ARG_COUNT), argv[0]);
builtin_print_help(parser, argv[0], stderr_buffer);
retcode=1;
break;
}
if (val_count == idx_count)
{
woptind++;
break;
}
}
}
}
if (!retcode)
{
/*
Slice indexes have been calculated, do the actual work
*/
if (erase)
{
erase_values(result, indexes);
my_env_set(dest, result, scope);
}
else
{
wcstring_list_t value;
while (woptind < argc)
{
value.push_back(argv[woptind++]);
}
if (update_values(result,
indexes,
value))
{
append_format(stderr_buffer, L"%ls: ", argv[0]);
append_format(stderr_buffer, ARRAY_BOUNDS_ERR);
stderr_buffer.push_back(L'\n');
}
my_env_set(dest, result, scope);
}
}
}
else
{
woptind++;
/*
No slicing
*/
if (erase)
{
if (woptind != argc)
{
append_format(stderr_buffer,
_(L"%ls: Values cannot be specfied with erase\n"),
argv[0]);
builtin_print_help(parser, argv[0], stderr_buffer);
retcode=1;
}
else
{
retcode = env_remove(dest, scope);
}
}
else
{
wcstring_list_t val;
for (i=woptind; i<argc; i++)
val.push_back(argv[i]);
retcode = my_env_set(dest, val, scope);
}
}
free(dest);
if (retcode == STATUS_BUILTIN_OK && preserve_incoming_failure_exit_status)
retcode = incoming_exit_status;
return retcode;
}
| true |
ce6d33d3b7ceeca740604dafca0fc6f5dbc51453 | C++ | JenSperry/181DatabaseP4 | /qe/qe.cc | UTF-8 | 13,071 | 2.796875 | 3 | [] | no_license |
#include "qe.h"
Filter::Filter(Iterator* input, const Condition &condition)
{
iter = input;
cond = condition;
}
// ... the rest of your implementations go here
RC Filter::getNextTuple(void *data)
{
void* tempData = malloc(4096);
void* value = malloc (4096);
bool condTrue;
vector<Attribute> attr;
getAttributes(attr);
for(int i = 0; i < attr.size(); i++)
{
if (attr[i].name == cond.lhsAttr) {lhsAttrNum = i;}
if (cond.bRhsIsAttr)
{
if(attr[i].name == cond.rhsAttr) {rhsAttrNum = i;}
}
}
lhsAttrVal = malloc(attr[lhsAttrNum].length + 1);
if(cond.bRhsIsAttr)
{
rhsAttrVal = malloc(attr[rhsAttrNum].length + 1);
}
else
{
if(cond.rhsValue.type == TypeInt || cond.rhsValue.type == TypeReal)
{
rhsAttrVal = malloc(4);
memcpy(rhsAttrVal, cond.rhsValue.data, 4);
}
else
{
rhsAttrVal = malloc(*(int*)cond.rhsValue.data + 1);
memcpy(rhsAttrVal, (void*)((char*)cond.rhsValue.data+4), (*(int*)cond.rhsValue.data));
*((char*)rhsAttrVal + *(int*)cond.rhsValue.data) = '\0';
}
}
do
{
if(iter->getNextTuple(tempData) == QE_EOF)
{
return QE_EOF;
}
//read lhs value out of tuple
//read rhs attr value if applicable
int nullbytes = ceil((float)attr.size()/8.0);
void* nulls = malloc(nullbytes);
memcpy(nulls, tempData, nullbytes);
int offset = nullbytes;
for(int i = 0; i < attr.size(); i++)
{
int size = 0;
int indicatorIndex = i / CHAR_BIT;
int indicatorMask = 1 << (CHAR_BIT - 1 - (i % CHAR_BIT));
if ((((char*)nulls)[indicatorIndex] & indicatorMask) != 0)
{
if(attr[i].type == TypeInt || attr[i].type == TypeReal)
{
size = 4;
memcpy(value, (void*)((char*)tempData+offset), size);
offset = offset + size;
}
else
{
memcpy(value, (void*)((char*)tempData+offset+4), *((int*)tempData+offset));
offset = offset + size;
*((char*)value + *((int*)tempData+offset)) = '\0';
size++;
}
if(i == lhsAttrNum)
{
memcpy(lhsAttrVal, value, size);
}
if(i == rhsAttrNum)
{
memcpy(rhsAttrVal, value, size);
}
}
}
//else read rhsValue into rhsAttrValue
if(attr[lhsAttrNum].type == TypeInt)
{
condTrue = checkCond(*(int*)lhsAttrVal);
}
else if(attr[lhsAttrNum].type == TypeReal)
{
condTrue = checkCond(*(float*)lhsAttrVal);
}
else if(attr[lhsAttrNum].type == TypeVarChar)
{
condTrue = checkCond((char*)lhsAttrVal);
}
}while(!condTrue && iter != NULL);
free(tempData);
free(value);
if(condTrue)
{
data = tempData;
return 0;
}
return QE_EOF;
}
bool Filter::checkCond(const int intCond)
{
switch(cond.op)
{
case EQ_OP :
if(intCond == *(int*)rhsAttrVal) {return true;}
else {return false;}
break;
case LT_OP :
if(intCond < *(int*)rhsAttrVal) {return true;}
else {return false;}
break;
case LE_OP :
if(intCond <= *(int*)rhsAttrVal) {return true;}
else {return false;}
break;
case GT_OP :
if(intCond > *(int*)rhsAttrVal) {return true;}
else {return false;}
break;
case GE_OP :
if(intCond >= *(int*)rhsAttrVal) {return true;}
else {return false;}
break;
case NE_OP :
if(intCond != *(int*)rhsAttrVal) {return true;}
else {return false;}
break;
case NO_OP :
return true;
}
return false;
}
bool Filter::checkCond(const float realCond)
{
switch(cond.op)
{
case EQ_OP :
if(realCond == *(float*)rhsAttrVal) {return true;}
else {return false;}
break;
case LT_OP :
if(realCond < *(float*)rhsAttrVal) {return true;}
else {return false;}
break;
case LE_OP :
if(realCond <= *(float*)rhsAttrVal) {return true;}
else {return false;}
break;
case GT_OP :
if(realCond > *(float*)rhsAttrVal) {return true;}
else {return false;}
break;
case GE_OP :
if(realCond >= *(float*)rhsAttrVal) {return true;}
else {return false;}
break;
case NE_OP :
if(realCond != *(float*)rhsAttrVal) {return true;}
else {return false;}
break;
case NO_OP :
return true;
}
return false;
}
//will definitely segfault if the rhsAttr is not null terminated, which includes if it's improperly assumed to be a string when
//it is actually an int or a real
bool Filter::checkCond(const char* charCond)
{
int strcmpRes;
strcmpRes = strcmp(charCond, (char*)rhsAttrVal);
switch(cond.op)
{
case EQ_OP :
if(strcmpRes == 0) {return true;}
else {return false;}
break;
case LT_OP :
if(strcmpRes < 0) {return true;}
else {return false;}
break;
case LE_OP :
if(strcmpRes <= 0) {return true;}
else {return false;}
break;
case GT_OP :
if(strcmpRes > 0) {return true;}
else {return false;}
break;
case GE_OP :
if(strcmpRes >= 0) {return true;}
else {return false;}
break;
case NE_OP :
if(strcmpRes != 0) {return true;}
else {return false;}
break;
case NO_OP :
return true;
}
return false;
}
// For attribute in vector<Attribute>, name it as rel.attr
void Filter::getAttributes(vector<Attribute> &attrs) const
{
iter->getAttributes(attrs);
}
void INLJoin::parseTuple(void *innerData, vector<Attribute> innerAttributes, string compAttr, char *stringResult, int32_t &numResult){
RecordBasedFileManager *rbfm = RecordBasedFileManager::instance();
char *cursor = (char *)innerData;
char *nullIndicator = (char *)innerData;
int nullSize = rbfm->getNullIndicatorSize(innerAttributes.size());
cursor += nullSize;
int i = 0;
Attribute desired;
for(auto a: innerAttributes){
if(a.name.compare(compAttr) == 0){
desired = a;
break;
}
if(rbfm->fieldIsNull(nullIndicator, i)){
i++;
continue;
}
if(a.type == TypeVarChar){
int32_t length;
memcpy(&length, cursor, 4);
cursor += 4 + length;
}else{
cursor += 4;
}
i++;
}
if(desired.type == TypeVarChar){
memcpy(&numResult, cursor, 4);
cursor += 4;
// +1 for null termination
stringResult = (char *)malloc(numResult+1);
memcpy(stringResult, cursor, numResult);
*(char *)(stringResult + numResult) = '\0';
}else{
memcpy(&numResult, cursor, 4);
}
}
/*foreach tuple r in R do
* foreach tuple s in S where r(i) == s(i) do
* add <r,s> to result
*/
INLJoin::INLJoin(Iterator *leftIn, // Iterator of input R
IndexScan *rightIn, // IndexScan Iterator of input S
const Condition &condition) // Join condition
{
vector<Attribute> outerAttributes;
vector<Attribute> innerAttributes;
leftIn->getAttributes(outerAttributes);
rightIn->getAttributes(innerAttributes);
vector<Attribute> combinedAttributes;
combinedAttributes = outerAttributes;
failFlag = false;
sameAttributeName = false;
if(!condition.bRhsIsAttr){
// You cannot join on a non attribute
failFlag = true;
return;
}
if(condition.lhsAttr.compare(condition.rhsAttr) == 0){
sameAttributeName = true;
}
Attribute outerAttribute;
Attribute innerAttribute;
for(auto a: innerAttributes){
if(sameAttributeName && a.name.compare(condition.lhsAttr) != 0){
combinedAttributes.push_back(a);
}else if(a.name.compare(condition.rhsAttr) == 0){
innerAttribute = a;
combinedAttributes.push_back(a);
}
else{
combinedAttributes.push_back(a);
}
}
this->combinedAttribute = combinedAttributes;
for(auto a: outerAttributes){
if(a.name.compare(condition.lhsAttr) == 0){
outerAttribute = a;
break;
}
}
RelationManager *rm = RelationManager::instance();
RC rc = rm->createTable("joinTable", combinedAttributes);
if(rc)
failFlag = true;
void *data = malloc(PAGE_SIZE);
while(leftIn->getNextTuple(data) != -1){
char *strData = NULL;
int32_t numData = 0;
parseTuple(data, outerAttributes, condition.lhsAttr, strData, numData);
void *innerData = malloc(PAGE_SIZE);
while(rightIn->getNextTuple(innerData) != -1){
char *innerStrData = NULL;
int32_t innerNumData = 0;
parseTuple(innerData, innerAttributes, condition.rhsAttr, innerStrData, innerNumData);
bool addFlag = false;
if(innerAttribute.type == TypeVarChar){
if(strcmp(strData, innerStrData) == 0){
addFlag = true;
}
} else{
if(numData == innerNumData)
addFlag = true;
}
free(innerStrData);
}
if(addFlag){
RID rid;
void * tuple = mergeTuples(data, innerData, outerAttributes, innerAttributes, outerAttribute.name, sameAttributeName);
rm->insertTuple("joinTable", data, rid);
rids.push_back(rid);
}
//now we need to insert this tuple into the table
free(strData);
free(innerData);
}
free(data);
//now call scanTable!!!!!
}
INLJoin::~INLJoin()
{
}
void * INLJoin::mergeTuples(void * tupleOne, void * tupleTwo, vector<Attribute> oneAttrs, vector<Attribute> twoAttrs, string name, bool same)
{
RecordBasedFileManager *rbfm = RecordBasedFileManager::instance();
void * data = malloc(PAGE_SIZE);
int dataOffset = rbfm->getNullIndicatorSize(oneAttrs.size()+twoAttrs.size()-1);
if(!same){
//we aren't merging the attributes, so the size will be the sum
dataOffset = rbfm->getNullIndicatorSize(oneAttrs.size()+twoAttrs.size());
}
int nullSize = dataOffset;
int oneOffset = rbfm->getNullIndicatorSize(oneAttrs.size());
int twoOffset = rbfm->getNullIndicatorSize(twoAttrs.size());
void * oneNullBytes = malloc(oneOffset);
memset(oneNullBytes, 0, oneOffset);
memcpy(oneNullBytes, tupleOne, oneOffset);
void * twoNullBytes = malloc(twoOffset);
memset(twoNullBytes, 0, twoOffset);
memcpy(twoNullBytes, tupleTwo, twoOffset);
void * dataNullBytes = malloc(dataOffset);
memset(dataNullBytes, 0, dataOffset);
for(int i = 0; i<oneAttrs.size(); i++){
if(rbfm->fieldIsNull((char*)oneNullBytes, i )){
int indicatorIndex = (i+1) / CHAR_BIT;
int indicatorMask = 1 << (CHAR_BIT - 1 - (i % CHAR_BIT));
((char*)dataNullBytes)[indicatorIndex] |= indicatorMask;
}else{
if(oneAttrs[i].type == TypeVarChar){
void * len = malloc(4);
memcpy(len, (char*)oneNullBytes+oneOffset, 4);
memcpy((char*)data+dataOffset, (char*)oneNullBytes+oneOffset, (*(int*)len)+4);
dataOffset+=(*(int*)len)+4;
oneOffset+=(*(int*)len)+4;
}else{
memcpy((char*)data+dataOffset, (char*)oneNullBytes+oneOffset, 4);
dataOffset += 4;
oneOffset += 4;
}
}
}
int j = oneAttrs.size();
for(int i = 0; i<twoAttrs.size(); i++){
bool add = true;
if(same && twoAttrs[i].name.compare(name) == 0){
//this attribute already in result :)
add = false;
continue;
}
if(rbfm->fieldIsNull((char*)twoNullBytes, i )){
int indicatorIndex = (j+1) / CHAR_BIT;
int indicatorMask = 1 << (CHAR_BIT - 1 - (j % CHAR_BIT));
((char*)dataNullBytes)[indicatorIndex] |= indicatorMask;
}else{
j++;
if(twoAttrs[i].type == TypeVarChar){
void * len = malloc(4);
memcpy(len, (char*)twoNullBytes+twoOffset, 4);
if(!add){
memcpy((char*)data+dataOffset, (char*)twoNullBytes+twoOffset, (*(int*)len)+4);
}
dataOffset+=(*(int*)len)+4;
twoOffset+=(*(int*)len)+4;
}else{
if(!add){
memcpy((char*)data+dataOffset, (char*)twoNullBytes+twoOffset, 4);
}
dataOffset += 4;
twoOffset += 4;
}
}
}
memcpy(data, dataNullBytes, nullSize);
return data;
}
vector<Attribute> INLJoin::mergeAttributes(vector<Attribute> one, vector<Attribute> two, string name, int &index)
{
vector<Attribute> three;
// one of the attrs is in both & we don't want to duplicate it
three.reserve(one.size()+two.size()-1);
for(int i = 0 ; i < one.size(); i++){
three[i] = one[i];
}
int j = one.size();
for(int i = 0 ; i < two.size(); i++){
if(two[i].name.compare(name) == 0){
three[j] = two[i];
j++;
index = i;
}
}
return three;
}
RC INLJoin::getNextTuple(void *data)
{
if(rids.size() == 0){
deleteTable("joinTable");
return QE_EOF;
}
RID rid = rids.back();
RC rc = readTuple("joinTable", rid, data);
if(rc)
return rc;
rids.pop_back();
return 0;
}
// For attribute in vector<Attribute>, name it as rel.attr
void INLJoin::getAttributes(vector<Attribute> &attrs) const
{
attrs = this->combinedAttribute;
}
| true |
1678f68cd5bb4214408d89642f7638590ae32d7d | C++ | RodrigoHolztrattner/Wonderland | /Wonderland/Wonderland/Editor/Modules/TextureCollecion/TextureCollectionString.cpp | UTF-8 | 1,748 | 2.78125 | 3 | [
"MIT"
] | permissive | ////////////////////////////////////////////////////////////////////////////////
// Filename: FluxMyWrapper.cpp
////////////////////////////////////////////////////////////////////////////////
#include "TextureCollectionString.h"
TextureCollection::TextureCollectionString::TextureCollectionString()
{
// Set the initial data
// ...
}
TextureCollection::TextureCollectionString::TextureCollectionString(const char* _string)
{
if (strlen(_string) <= MaxStringSize)
strcpy(m_String, _string);
}
TextureCollection::TextureCollectionString::~TextureCollectionString()
{
}
void TextureCollection::TextureCollectionString::operator =(const char* _string)
{
if (strlen(_string) <= MaxStringSize)
strcpy(m_String, _string);
}
void TextureCollection::TextureCollectionString::SetString(const char* _string)
{
if (strlen(_string) <= MaxStringSize)
strcpy(m_String, _string);
}
void TextureCollection::TextureCollectionString::SetString(const char* _string, uint32_t _stringSize)
{
if ((_stringSize + 1) <= MaxStringSize) // Include the null terminator
{
// Copy the string
memcpy(m_String, _string, sizeof(char) * (_stringSize));
// Include the null terminator
m_String[_stringSize] = 0;
}
}
char* TextureCollection::TextureCollectionString::GetString()
{
return m_String;
}
bool TextureCollection::TextureCollectionString::IsEqual(TextureCollectionString& _string, uint32_t _stringSize)
{
return IsEqual(_string.GetString(), _stringSize);
}
bool TextureCollection::TextureCollectionString::IsEqual(const char* _string, uint32_t _stringSize)
{
uint32_t currentSize = 0;
while (currentSize < _stringSize)
{
if (m_String[currentSize] != _string[currentSize])
{
return false;
}
currentSize++;
}
return true;
} | true |
6bf370c825bd8bf514195a1f8217fc1ba452ba0b | C++ | yaoguilv/Alex | /Cal/Al/src/C2/U3/Quick.cpp | UTF-8 | 1,358 | 3.53125 | 4 | [] | no_license | #include "C2/U3/Quick.h"
void Quick::sort(Comparable ** a, int arrLen)
{
// Eliminate dependence on input.
sort(a, 0, arrLen - 1);
}
void Quick::sort(Comparable ** a, int lo, int hi)
{
if(hi <= lo) return;
int j = partition(a, lo, hi);
// Sort left part a[lo .. j-1].
sort(a, lo, j - 1);
// Sort right part a[j+1 .. hi].
sort(a, j + 1, hi);
}
int Quick::partition(Comparable ** a, int lo, int hi)
{
// Partition into a[lo .. i-1], a[i], a[i+1 .. hi]
// left and right scan indices
int i = lo, j = hi + 1;
// partitioning item
Comparable * v = a[lo];
while(true)
{
// Scan right, scan left, check for scan complete, and exchange.
while(less(a[++i], v))
if(i == hi) break;
while(less(v, a[--j]))
if(j == lo) break;
if(i >= j) break;
exch(a, i, j);
}
// Put v = a[j] into position
exch(a, lo, j);
// with a[lo .. j-1] <= a[j] <= a[j+1 .. hi].
return j;
}
bool Quick::less(Comparable * v, Comparable * w)
{
return v->compareTo(w) < 0;
}
void Quick::exch(Comparable ** a, int i, int j)
{
Comparable * t = a[i];
a[i] = a[j];
a[j] = t;
}
bool Quick::isSorted(Comparable ** a, int arrLength)
{
for(int i = 1; i< arrLength; i++)
if(less(a[i], a[i - 1])) return false;
return true;
}
| true |
4e5ba43b45921d380528b7668e58b6851075c2ce | C++ | Personal-Learnings/CPP_Learning_CodeLite | /Workspace/InheritanceSectionChallenge/Account.h | UTF-8 | 585 | 3.328125 | 3 | [] | no_license | #ifndef ACCOUNT_H
#define ACCOUNT_H
#include <iostream>
#include <string>
using namespace std;
class Account
{
friend ostream &operator<<(ostream &os, const Account &account);
private:
static constexpr const char *DEFAULT_NAME = "Unnamed Account";
static constexpr const double DEFAULT_BALANCE = 0.0;
protected:
string name;
double balance;
public:
Account(string name = DEFAULT_NAME, double balance = DEFAULT_BALANCE);
bool withdraw(double amount);
bool deposit(double amount);
double getBalance() const;
};
#endif // ACCOUNT_H
| true |
9699f716370ce5676dc4e7e7c4e78842c0699f34 | C++ | Kishorehere/Spider_Task_v2.0 | /MERGE_SO.CPP | UTF-8 | 973 | 3.28125 | 3 | [] | no_license |
//NAME: ELANTHAMIZHAN A R - 103118023
//Merging two array
//First array given in ascending order
//Second array given in descending order
#include<iostream.h>
#include<conio.h>
void merge(int [],int,int [],int,int []);
void main()
{
int a[10],b[10],c[10];
int s1,s2;
clrscr();
cout<<"\nEnter the size of asc. array: ";
cin>>s1;
cout<<"\nEnter your asc. array: ";
for(int i=0;i<s1;i++)
{
cin>>a[i]; }
cout<<"\nEnter the size of desc. array: ";
cin>>s2;
cout<<"\nEnter your desc. array: ";
for(int j=0;j<s2;j++)
{
cin>>b[j]; }
int s3=s1+s2;
merge(a,s1,b,s2,c);
cout<<"\n\n\tYour merged array!!\n\t";
for(i=0;i<s3;i++)
cout<<c[i]<<" ";
cout<<"\n";
getch();
}
void merge(int a[],int m,int b[],int n,int c[])
{
int i,j,k;
for(i=0,j=n-1,k=0;i<m && j>=0; )
{
if(a[i]<=b[j])
c[k++]=a[i++];
else
c[k++]=b[j--];
}
if(i<m)
{
while(i<m)
c[k++]=a[i++];
}
else
{
while(j>=0)
c[k++]=b[j--];
}
} | true |
6aa63da565b831255a65474995d68be4c7d56888 | C++ | cfs6/DSandAlgorithm | /jianzhiOffer/PermutationCombinationBYDP.cpp | GB18030 | 1,576 | 3.34375 | 3 | [] | no_license | //һַ,ֵӡַַС
//ַabc,ӡַa,b,cгַabc,acb,bac,bca,cabcba
//̬滮
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
void addchar(char c, vector<string> &res) {
vector<string> res2 = res;
int ressize = res2.size();
int strlength = res2[0].length();
res.clear();
for (int i = 0; i<ressize; ++i) {
for (int j = 0; j<=strlength; ++j) {
string pres = res2[i];
pres.insert(j, 1, c);
res.push_back(pres);
}
// for (auto r : res) {
// cout << r<<" ";
// }
cout << endl;
}
}
int main() {
string str;
getline(cin, str);
vector<string> resv;
int strlength = str.length();
string newstr1(str, 0, 1);
resv.push_back(newstr1);
// for (auto re : resv)
// cout << re<<endl;
for (int i = 1; i<strlength; ++i) {
addchar(str[i], resv);
}
/*
set<string> resset;
for (int i = 0; i<resv.size() - 1; ++i) {
resset.insert(resv[i]);
}
*/
// cout << resset[resset.size() - 1];
vector<string>::iterator it1;
vector<string>::iterator it2;
for (it1 = ++resv.begin(); it1 != resv.end();) {
it2 = find(resv.begin(), it1, *it1);
if (it1 != it2)
it1 = resv.erase(it1);
else
it1++;
}
sort(resv.begin(), resv.end());
for (int i = 0; i<resv.size() - 1; ++i) {
cout << resv[i] << ", ";
}
cout << resv[resv.size() - 1]<<endl;
cout << resv.size() << endl;
system("pause");
}
| true |
bf10f9a301a9dc93a7b4edd8775476adf3964895 | C++ | MakeevVlad/Crystall-growth-simulation | /Functions.cpp | UTF-8 | 21,027 | 2.640625 | 3 | [] | no_license | #include <vector>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <random>
#include <fstream>
#include <string>
#include <omp.h>
#include "Functions.h"
//Функция, сохраняющая данные в файл для дальнейшей отрисовки
void collect_data(Field& field)
{
std::ofstream file("crystal.txt", std::ios::out);
for (double x = 0; x < field.size[0]; ++x)
for (double y = 0; y < field.size[1]; ++y)
for (double z = 1; z < field.size[2]; ++z)
if (field[x][y][z][0] == 1)
file << x << " " << y << " " << z << " " << field[x][y][z][1] << std::endl;
file.close();
}
//В файл записывается только координата верхней молекулы
void smart_data_collect(Field& field)
{
std::ofstream file("crystal.txt", std::ios::out);
for (double x = -1; x <= field.size[0]; ++x)
for (double y = -1; y <= field.size[1]; ++y)
for (double z = 0; z < field.size[2]; ++z)
{
if (x == -1 || y == -1 || x == field.size[0] || y == field.size[1])
{
file << x << " " << y << " " << 0 << " " << 0 << std::endl;
continue;
}
if (field[x][y][z][0] == 1 && (z == field.get_size_z() ? 0 : field[x][y][z + 1][0] == 0))
file << x << " " << y << " " << z << " " << field[x][y][z][1] << std::endl;
}
}
//Задаются параметры сборки
void set_configuration(Field& field, Molecule& mol)
{
std::cout << "\n-------------------------------------------------------------\n";
std::cout << "Enter cooficients for L-J formula\n";
std::cin >> field.sigma >> field.e;
std::cout << "Enter ALONG_EN, ASCENT_EN, FALLING_EN\n";
std::cin >> mol.ALONG_EN >> mol.ASCENT_EN >> mol.FALLING_EN;
std::cout << "Enter MAX_ENERGY and CRIT_ENERGY\n ";
std::cin >> mol.MAX_ENERGY >> mol.CRIT_EN;
std::cout << "\n-------------------------------------------------------------\n";
}
//Выбор режима запуска программы
size_t set_mode()
{
size_t val;
std::cout << "\n---------------------------\n";
std::cout << "Choose mode you want to use: \n1 - standart simulation \n2 - 'min-pot' mode \n";
std::cin >> val;
return val;
}
//*****Фунции движения********************************************************************
//Эта функция задает точку присоединения, если энергия частицы достаточно мала
void direction(Molecule& mol, Field& field)
{
std::vector<std::vector<double>> pot;
//Инициализация вектора pot
pot.resize(10);
for (auto& c : pot)
c.resize(4);
//Случай, когда частица перемещается строго по Oy (тут происходит заполнение массива потенциалов потенциалом :))
if (mol.dir[0] == 0)
{
size_t x_max = field.get_size_x(), y_max = field.get_size_y();
//Направления движения частицы(выбор следующей клетки)
size_t y = mol.y != 0 ? (mol.y + mol.dir[1]) % y_max : (y_max + mol.dir[1]) % y_max;
//Pot[0] - описание точки, на которой находится частица
pot[0][0] = field[mol.x][mol.y][mol.z][1];
pot[0][1] = mol.x;
pot[0][2] = mol.y;
pot[0][3] = mol.z;
size_t i = 1;
for (size_t x = (mol.x != 0 ? mol.x - 1 : x_max - 1); x <= (mol.x + 1) % x_max; x = (++x) % x_max)
{
if (i == 10) break;
for (size_t z = mol.z - 1; z <= mol.z + 1; ++z, ++i)
{
if (i == 10) break; //Кастыль
if (field[x][y][z][0] == 1 || field[x][y][z == 0 ? 0 : z - 1][0] == 0)
//В простейшем случае свободная частица не может выбить уже закреплённую
// Также она не может повиснуть в воздухе
{
pot[i][0] = 1000;
pot[i][1] = x;
pot[i][2] = y;
pot[i][3] = z;
continue;
}
pot[i][0] = field[x][y][z][1];
pot[i][1] = x;
pot[i][2] = y;
pot[i][3] = z;
}
}
}
//Случай, когда частица перемещается строго по Ox (тут происходит заполнение массива потенциалов потенциалом :) )
else if (mol.dir[0] != 0 && abs(mol.dir[1]) != 1)
{
size_t x_max = field.get_size_x(), y_max = field.get_size_y();
//Направления движения частицы
size_t x = mol.x != 0 ? (mol.x + mol.dir[0]) % x_max : (x_max + mol.dir[0]) % x_max;
//Pot[0] - описание точки, на которой находится частица
pot[0][0] = field[mol.x][mol.y][mol.z][1];
pot[0][1] = mol.x;
pot[0][2] = mol.y;
pot[0][3] = mol.z;
size_t i = 1;
for (size_t y = (mol.y != 0 ? mol.y - 1 : y_max - 1); y <= (mol.y + 1) % y_max; y = (++y) % y_max)
{
if (i == 10) break;
for (size_t z = mol.z - 1; z <= mol.z + 1; ++z, ++i)
{
if (i == 10) break; //Кастыль
if (field[x][y][z][0] == 1 || field[x][y][z == 0 ? 0 : z - 1][0] == 0)
//В простейшем случае свободная частица не может выбить уже закреплённую
// Также она не может повиснуть в воздухе
{
pot[i][0] = 1000;
pot[i][1] = x;
pot[i][2] = y;
pot[i][3] = z;
continue;
}
pot[i][0] = field[x][y][z][1];
pot[i][1] = x;
pot[i][2] = y;
pot[i][3] = z;
}
}
}
//Случай, когда частица двигается по диагонали (движение по диагонали напрямую не реализована в этой версии)
else
{
return;
}
//Для простоты модели просто выбирается минимальный потенциал
size_t num = 10;
double pote = 10000;
for (size_t i = 0; i < pot.size(); ++i)
{
if (pote > pot[i][0])
{
pote = pot[i][0];
num = i;
}
}
field[mol.x][mol.y][mol.z][0] = 0;
mol.x = size_t(pot[num][1]);
mol.y = size_t(pot[num][2]);
mol.z = size_t(pot[num][3]);
if(field[mol.x][mol.y][mol.z][0] == 1) std::cout << "OOO no " << std::endl;
field[mol.x][mol.y][mol.z][0] = 1;
//field.lj_potencial();
return;
}
//Функция отвечающая за отражение частицы
void movement_reflection(Molecule& mol, Field& field)
{
mol.along();
mol.dir[0] *= -1;
mol.dir[1] *= -1;
}
//Функция отвечающая за восхождение :)
void movement_ascent(Molecule& mol, Field& field)
{
//Реализация пока что в основном коде
}
//Функция отвечающая за кооксиальное движение
void movement_along(Molecule& mol, Field& field)
{
//Реализация пока что в основном коде
}
//Эта функция отвечает за перемещение частицы
bool movement(Molecule& mol, Field& field)
{
std::cout << std::endl << mol.x << " " << mol.y << " " << mol.z << " ";
//"Падение" молекулы
if (mol.z == field.get_size_z())
while (field[mol.x][mol.y][mol.z - 1][0] == 0)
{
--mol.z;
std::cout << " ->" << mol.z;
}
//Для случая, если частица совершает первое перемещение
field[mol.x][mol.y][mol.z][0] = 1;
size_t x_max = field.get_size_x(), y_max = field.get_size_y();
//Координаты точки по направлению(вынесено, чтобы каждый раз не писать)
size_t _X = mol.x != 0 ? (mol.x + mol.dir[0]) % x_max : (x_max + mol.dir[0]) % x_max;
size_t _Y = mol.y != 0 ? (mol.y + mol.dir[1]) % y_max : (y_max + mol.dir[1]) % y_max;
size_t _Z = mol.z + 1;
//Случай, когда частица двигается вдоль осей:
//!!! % cord_max означает, что частица при переходе за поле автоматически перемещается нв другую его сторону
if ((abs(mol.dir[0]) == 1 && mol.dir[1] == 0) || (abs(mol.dir[1]) == 1 && mol.dir[0] == 0))
{
if (field[_X][_Y][mol.z][0] == 0) //Если последующая ячейка свободна
{
//Случай, когда частица переходит строго вперёд
if (field[_X][_Y][mol.z - 1][0] == 1)
{
field.lj_potencial(mol.x, mol.y, mol.z);
//Проверка на возможность движения
if (mol.along_check(field, _X, _Y, mol.z) <= mol.CRIT_EN)
{
direction(mol, field);
return 1;
}
double scnd_pot;
//Возможность перехода наискось (В этом ужасном фрагменте кода происходит проверка соседних ячеек поля, на возможность присоединения в них)
if (abs(mol.dir[0]) == 1 && (field[_X][(_Y + 1) % y_max][mol.z][0] == 0 || field[_X][_Y == 0 ? y_max - 1 : _Y - 1][mol.z][0] == 0))
{
if (field[_X][(_Y + 1) % y_max][mol.z][1] > field[_X][_Y == 0 ? y_max - 1 : _Y - 1][mol.z][1])
{
scnd_pot = field[_X][_Y == 0 ? y_max - 1 : _Y - 1][mol.z][1];
if(field[_X][_Y][mol.z][1] > scnd_pot && field[_X][_Y == 0 ? y_max - 1 : _Y - 1][mol.z - 1][0] == 1)
_Y = _Y == 0 ? y_max - 1 : _Y - 1;
}
else
{
scnd_pot = field[_X][(_Y + 1) % y_max][mol.z][1];
if (field[_X][_Y][mol.z][1] > scnd_pot && field[_X][(_Y + 1) % y_max][mol.z-1][0] == 1)
_Y = _Y == 0 ? y_max - 1 : _Y - 1;
}
}
else
{
if (field[(_X + 1) % x_max][_Y ][mol.z][0] == 1 || field[_X == 0 ? x_max - 1 : _X - 1][_Y][mol.z][0] == 1)
{
if (field[(_X + 1) % x_max][_Y][mol.z][1] > field[_X == 0 ? x_max - 1 : _X - 1][_Y][mol.z][1])
{
scnd_pot = field[_X == 0 ? x_max - 1 : _X - 1][_Y][mol.z][1];
if ((field[_X][_Y][mol.z][1] > scnd_pot) && field[_X == 0 ? x_max - 1 : _X - 1][_Y][mol.z - 1][0] == 1)
_X = _X == 0 ? x_max - 1 : _X - 1;
}
else
{
scnd_pot = field[(_X + 1) % x_max][_Y][mol.z][1];
if (field[_X][_Y][mol.z][1] > scnd_pot && field[_X == 0 ? x_max - 1 : _X - 1][_Y][mol.z - 1][0] == 1)
_X = (_X + 1) % x_max;
}
}
}
//Убираем молекулу из начальной координаты
field[mol.x][mol.y][mol.z][0] = 0;
//Изменяем энергию молекулы
mol.along(field, _X, _Y, mol.z);
//Следующие координаты
mol.x = _X;
mol.y = _Y;
field[mol.x][mol.y][mol.z][0] = 1;
return 0;
}
//Случай, когда частица переходит на уровень вниз
else
{
//mol.falling();
field[mol.x][mol.y][mol.z][0] = 0; //Убираем молекулу из начальной координаты
int n = 0;
size_t z0 = mol.z;
//"Падение" частицы(z0 для того, чтобы цикл не был бесконечным
while (field[mol.x][mol.y][z0 - 1][0] == 0) { --z0; --n; }
field.lj_potencial(mol.x, mol.y, mol.z, n);
mol.falling(field, _X, _Y, mol.z + n, -1 * n);
//Следующие координаты
mol.x = _X;
mol.y = _Y;
mol.z += n;
field[mol.x][mol.y][mol.z][0] = 1;
return 0;
}
}
//Если последующая ячейка занята(происходит выбор между отражением и переходом наверх)
else
{
//Подсчет количества я чеек подъёма
size_t n = 1;
while (field[_X][_Y][_Z][0] == 1) { ++n; ++_Z; }
field.lj_potencial(mol.x, mol.y, mol.z, n);
//Вероятности p_reflect - отражения and p_ascent - поднятия на уровень
double p_reflect = 1 / (1 + mol.ALONG_EN / (n * mol.ASCENT_EN));
double p_ascent = 1 - p_reflect;
//Генерируем вероятность
std::srand(std::time(0));
double p = (rand() % 1000) / 1000;
if( p <= p_ascent) //Подъём
{
//Проверка на возможность движения
if (mol.ascent_check(field, _X, _Y, mol.z + n, n) <= mol.CRIT_EN)
{
direction(mol, field);
return 1;
}
field[mol.x][mol.y][mol.z][0] = 0; //Убираем молекулу из начальной координаты
mol.ascent(field, _X, _Y, mol.z + n, n);
//Следующие координаты
mol.x = _X;
mol.y = _Y;
field[mol.x][mol.y][mol.z + n][0] = 1;
return 0;
}
else //Отражение
{
//Проверка на возможность движения
if (mol.energy - mol.ALONG_EN <= mol.CRIT_EN)
{
direction(mol, field);
return 1;
}
movement_reflection(mol, field);
movement(mol, field) == 1? 1 : 0;
}
}
}
}
//*****Функции класса Field***************************************************************
Field::Field() { set_size(100, 100, 100); }
Field::Field(size_t len, size_t wid, size_t hei)
{
size[0] = len; //x_size
size[1] = wid; //y_size
size[2] = hei; //z_size
//Инициализация поля НУЖНО ВЫНЕСТИ КАК ОТДЕЛЬНУЮ ФУНКЦИЮ!!!!!!!!
zone.resize(len);
size_t i = 0;
for (auto& y : zone) {
y.resize(wid);
for (auto& z : y) {
z.resize(hei);
i = 0;
for (auto& val : z) {
val.resize(2);
if (i == 0) val[0] = 1;
++i;
}
}
}
//Задание начальной карты потенциала
//this->lj_potencial();
}
void Field::set_size(size_t len, size_t wid, size_t hei)
{
size[0] = len; //x_size
size[1] = wid; //y_size
size[2] = hei; //z_size
//Инициализация поля НУЖНО ВЫНЕСТИ КАК ОТДЕЛЬНУЮ ФУНКЦИЮ!!!!!!!!
zone.resize(len);
for(auto& y : zone) {
y.resize(wid);
for (auto& z : y) {
z.resize(hei);
for (auto& val : z) {
val.resize(2);
}
}
}
}
size_t& Field::get_size_x()
{ return size[0]; }
size_t& Field::get_size_y()
{ return size[1]; }
size_t& Field::get_size_z()
{ return size[2]; }
std::vector<std::vector<std::vector<double>>>& Field::operator[](size_t i)
{
return zone[i];
}
//Задание рандомных потенциалов
void Field::potencial_uniform()
{
//Генератор случайных чисел(uniform distribution)
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> uniform(0, 1000);
std::srand(std::time(nullptr));
for (auto& y : zone)
for (auto& z : y)
for (auto& val : z)
val[1] += uniform(gen);
}
//Задание потенциала по формуле Леннарда-Джонса
void Field::lj_potencial()
{
#pragma omp parallel for ordered schedule(dynamic)
for (int x = 0; x < size[0]; ++x)
for (double y = 0; y < size[1]; ++y)
for (double z = 0; z < size[2]; ++z)
{
#pragma omp parallel for ordered schedule(dynamic)
for (int x1 = 0; x1 < size[0]; ++x1)
for (double y1 = 0; y1 < size[1]; ++y1)
for (double z1 = 0; z1 < size[2]; ++z1)
{
if (zone[size_t(x1)][size_t(y1)][size_t(z1)][0] == 1 && (x != x1 || y != y1 || z != z1))
{
double r = sqrt((double(x) - double(x1))*(double(x) - double(x1)) + (y - y1)*(y - y1) + (z - z1)*(z - z1));
zone[size_t(x)][size_t(y)][size_t(z)][1] += 4 * e * (pow(sigma / r, 12) - pow(sigma / r, 6));
}
}
}
}
//Упрощенный вариант (потенциал пересчитывается только в ячейках, подходящих для перемщения)
void Field::lj_potencial(size_t _x, size_t _y, size_t _z, int n)
{
size_t x_start = _x != 0 ? _x - 1 : size[0] - 1,
y_start = _y != 0 ? _y - 1 : size[1] - 1;
size_t x_end = ((_x + 1) % size[0]) + 1,
y_end = ((_y + 1) % size[1]) + 1;
size_t z_start, z_end;
if (n < 0) { z_end = _z + 1; z_start = _z + n; }
else { z_end = _z + n; z_start = _z - 1; }
#pragma omp parallel for ordered schedule(dynamic)
for (int x = x_start; x < x_end; ++x)
for (double y = y_start; y < y_end; ++y)
for (double z = z_start; z < z_end; ++z)
{
#pragma omp parallel for ordered schedule(dynamic)
for (int x1 = 0; x1 < size[0]; ++x1)
for (double y1 = 0; y1 < size[1]; ++y1)
for (double z1 = 0; z1 < size[2]; ++z1)
{
if (zone[size_t(x1)][size_t(y1)][size_t(z1)][0] == 1 && (x != x1 || y != y1 || z != z1))
{
double r = sqrt((double(x) - double(x1))*(double(x) - double(x1)) + (y - y1)*(y - y1) + (z - z1)*(z - z1));
zone[size_t(x)][size_t(y)][size_t(z)][1] += 4 * e * (pow(sigma / r, 12) - pow(sigma / r, 6));
}
}
}
}
//*****Функции класса Molecule***********************************************************
Molecule::Molecule(Field field)
{
std::srand(std::time(nullptr));
//Генератор случайных чисел(uniform distribution)
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> uniform_x(0, field.size[0]);
std::uniform_real_distribution<> uniform_y(0, field.size[1]);
x = uniform_x(gen);
y = uniform_y(gen);
z = field.get_size_z();
int variants[3] = { 0, 1,-1 };
//Выбор направления движения******Условный оператор нужен, чтобы нельзя было выбрать dir = {0, 0}
dir[0] = variants[rand() % 3];
dir[0] == 0 ? dir[1] = variants[rand() % 2 + 1] : dir[1] = 0;
std::uniform_real_distribution<> uniform(0, MAX_ENERGY);
energy = uniform(gen);
}
Molecule::Molecule(Field field, size_t _x, size_t _y, size_t _z, int dir0, int dir1)
{
x = _x;
y = _y;
z = _z;
dir[0] = dir0;
dir[1] = dir1;
energy = 350;
}
Molecule::~Molecule()
{
delete &x, &y, &z, dir, &energy;
}
void Molecule::mol_generator(Field& field)
{
std::srand(std::time(nullptr));
//Генератор случайных чисел(uniform distribution)
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> uniform_x(0, field.size[0]);
std::uniform_real_distribution<> uniform_y(0, field.size[1]);
x = uniform_x(gen);
y = uniform_y(gen);
z = field.get_size_z();
int variants[3] = { 0, 1,-1 };
//Выбор направления движения******Условный оператор нужен, чтобы нельзя было выбрать dir = {0, 0}
dir[0] = variants[rand() % 3];
dir[0] == 0 ? dir[1] = variants[rand() % 2 + 1] : dir[1] = 0;
std::uniform_real_distribution<> uniform(0, MAX_ENERGY);
energy = uniform(gen);
std::cout << std::endl << "****new molecule!**** energy =" << energy << std::endl;
}
//выйгрыш энергии частицой при переходе на уровень вниз
void Molecule::falling(size_t n)
{
energy += n*FALLING_EN;
}
void Molecule::falling(Field& field, size_t _x, size_t _y, size_t _z, size_t n)
{
double del_phi = field[x][y][z][1] - field[_x][_y][_z][1];
energy -= (del_phi*charge - n * FALLING_EN);
}
double Molecule::falling_check(Field& field, size_t _x, size_t _y, size_t _z, size_t n)
{
double del_phi = field[x][y][z][1] - field[_x][_y][_z][1];
return energy - (del_phi*charge - n * FALLING_EN);
}
//Потеря энергии частицой при переходе на уровень вверх
void Molecule::ascent(size_t n)
{
energy -= n*ASCENT_EN;
}
void Molecule::ascent(Field& field, size_t _x, size_t _y, size_t _z, size_t n)
{
double del_phi = field[x][y][z][1] - field[_x][_y][_z][1];
energy -= (n * ASCENT_EN - del_phi*charge);
}
double Molecule::ascent_check(Field& field, size_t _x, size_t _y, size_t _z, size_t n)
{
double del_phi = field[x][y][z][1] - field[_x][_y][_z][1];
return energy - (n * ASCENT_EN - del_phi * charge);
}
//Потеря энергии при движении по оси
void Molecule::along()
{
energy -= ALONG_EN;
}
void Molecule::along(Field& field, size_t _x, size_t _y, size_t _z)
{
double del_phi = field[x][y][z][1] - field[_x][_y][_z][1];
energy -= (ALONG_EN - del_phi * charge);
}
double Molecule::along_check(Field& field, size_t _x, size_t _y, size_t _z)
{
double del_phi = field[x][y][z][1] - field[_x][_y][_z][1];
return energy - (ALONG_EN - del_phi * charge);
}
| true |
a15040547fa3d64d750461694dcb9fbffe343c73 | C++ | Tomerfi1210/Dave | /Project/PlayerMove.cpp | UTF-8 | 2,709 | 2.796875 | 3 | [] | no_license | #include "PlayerMove.h"
#include "GameObject.h"
#include "ResourceManager.h"
#include "Dave.h"
#include <iostream>
//TODO move from here
static int count = 0;
PlayerMove::PlayerMove(Dave& dave) : m_moveHands(false), m_dave(dave)
{
m_speed = 0.7f;
m_moves.emplace(sf::Keyboard::Right, [&]() {m_step.x = { m_speed }; m_dave.getSprite().setScale({ 1,1 }); m_dir = Right; });
m_moves.emplace(sf::Keyboard::Left, [&]() {m_step.x = { -m_speed }; m_dave.getSprite().setScale({ -1,1 }); m_dir = Left; });
m_moves.emplace(sf::Keyboard::Up, [&]() {if (!m_can_jump && !m_can_fly || m_step.y != 0) return; m_can_jump = false; if (m_can_fly) m_can_jump = true; m_step.y = { -m_speed }; count++;
if (m_dir == Right)m_dave.getSprite().setScale({ 1,1 }); else m_dave.getSprite().setScale({ -1,1 }); });
m_moves.emplace(sf::Keyboard::Down, [&]() {if (!m_can_fly) return; m_step.y = { m_speed }; m_dave.getSprite().setScale({ 1,1 }); });
}
//------------------------------------------------------------------------------------
std::unique_ptr<MoveStrategy> PlayerMove::move(GameObject& player, sf::Vector2f&)
{
if (m_can_fly) {
sf::IntRect tmp(0, 0, DYNAMIC_SIZE, DYNAMIC_SIZE);
m_dave.getSprite().setTextureRect(tmp);
}
else {
if (m_timer.getElapsedTime().asSeconds() >= m_moveTimer.asSeconds() && m_moveHands)
{
m_timer.restart();
m_walk++;
}
if (m_walk >= 3) {
m_walk = 0;
}
if (m_step.y == 0) {
sf::IntRect tmp(DYNAMIC_SIZE * m_walk, 0, DYNAMIC_SIZE, DYNAMIC_SIZE);
m_dave.getSprite().setTextureRect(tmp);
}
}
m_dave.getSprite().move(m_step);
m_step.x = { 0 };
return nullptr;
}
//----------------------------------------------------------------------------------------
void PlayerMove::setDirection()
{
bool isPressed = false;
for (const auto &cell : m_moves)
{
if (sf::Keyboard::isKeyPressed(cell.first))
{
cell.second();
m_moveHands = true;
isPressed = true;
}
}
if(!isPressed)
m_moveHands = false;
static int jetCountUp = 0;
static int jetCountDown = 0;
if (m_can_fly)
{
if (m_step.y < 0) {
jetCountUp++;
if (jetCountUp >= 70)
{
jetCountUp = 0;
m_step.y = 0;
}
}
else if (m_step.y > 0) {
jetCountDown++;
if (jetCountDown >= 70)
{
jetCountDown = 0;
m_step.y = 0;
}
}
return;
}
//adding the movement upwards to the counter
if (m_step.y < 0)
count++;
//TODO, make this 200 an attribute(data member)
if (count >= 270)
{
count = 0;
//keep it true for going downwards
m_step = { 0, m_speed };//make him go back down
m_can_jump = false;
}
/*if (count <= 0)
m_jumping = false;*/
}
| true |
e39b5a9360a9e0d8984c595f0f10f83aa7221e0a | C++ | the-sword/autoscan-windows | /seven_dof_arm_test/src/add_collision_objct.cpp | UTF-8 | 7,955 | 2.5625 | 3 | [] | no_license | // 包含API的头文件
#include <moveit/move_group_interface/move_group.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <moveit_msgs/AttachedCollisionObject.h>
#include <moveit_msgs/CollisionObject.h>
int main(int argc, char **argv)
{
ros::init(argc, argv, "add_collision_objct");
ros::NodeHandle nh_add_coll;
ros::AsyncSpinner spin(1);
spin.start();
// 创建运动规划的情景,等待创建完成
moveit::planning_interface::PlanningSceneInterface current_scene;
sleep(1.0);
// 声明一个障碍物的实例,并且为其设置一个id,方便对其进行操作,该实例会发布到当前的情景实例中
moveit_msgs::CollisionObject cylinder;
cylinder.id = "seven_dof_arm_cylinder";
// 设置障碍物的外形、尺寸等属性
shape_msgs::SolidPrimitive primitive;
primitive.type = primitive.CYLINDER;
primitive.dimensions.resize(3);
primitive.dimensions[0] = 0.56;
primitive.dimensions[1] = 0.185;
// 设置障碍物的位置
geometry_msgs::Pose pose;
pose.orientation.w = 1;
pose.position.x = 0.64000;
pose.position.y = 0.000000;
pose.position.z = -0.280000;
// 将障碍物的属性、位置加入到障碍物的实例中
cylinder.primitives.push_back(primitive);
cylinder.primitive_poses.push_back(pose);
cylinder.operation = cylinder.ADD;
// 声明一个障碍物的实例,并且为其设置一个id,方便对其进行操作,该实例会发布到当前的情景实例中
moveit_msgs::CollisionObject boxUp;
boxUp.id = "seven_dof_arm_boxUp";
// 设置障碍物的外形、尺寸等属性
shape_msgs::SolidPrimitive primitiveUp;
primitiveUp.type = primitiveUp.BOX;
primitiveUp.dimensions.resize(3);
primitiveUp.dimensions[0] = 0.20;
primitiveUp.dimensions[1] = 0.24;
primitiveUp.dimensions[2] = 0.56;
// 设置障碍物的位置
geometry_msgs::Pose poseUp;
poseUp.orientation.w = 1;
poseUp.position.x = 0.64000;
poseUp.position.y = 0.000000;
poseUp.position.z = -0.280000;
// 将障碍物的属性、位置加入到障碍物的实例中
boxUp.primitives.push_back(primitiveUp);
boxUp.primitive_poses.push_back(poseUp);
boxUp.operation = boxUp.ADD;
// 声明一个障碍物的实例,并且为其设置一个id,方便对其进行操作,该实例会发布到当前的情景实例中
moveit_msgs::CollisionObject object;
object.id = "seven_dof_arm_object";
// 设置障碍物的外形、尺寸等属性
shape_msgs::SolidPrimitive primitive2;
primitive2.type = primitive2.BOX;
primitive2.dimensions.resize(3);
primitive2.dimensions[0] = 0.11;
primitive2.dimensions[1] = 0.16;
primitive2.dimensions[2] = 0.19;
//7,5.5,13
// 设置障碍物的位置
geometry_msgs::Pose pose2;
pose2.orientation.w = 1;
pose2.position.x = 0.640000;
pose2.position.y = 0.000000;
pose2.position.z = 0.0750000;
// 将障碍物的属性、位置加入到障碍物的实例中
object.primitives.push_back(primitive2);
object.primitive_poses.push_back(pose2);
object.operation = object.ADD;
// 声明一个障碍物的实例,并且为其设置一个id,方便对其进行操作,该实例会发布到当前的情景实例中
moveit_msgs::CollisionObject box_right;
box_right.id = "box_right";
// 设置障碍物的外形、尺寸等属性
shape_msgs::SolidPrimitive primitiveRight;
primitiveRight.type = primitiveRight.BOX;
primitiveRight.dimensions.resize(3);
primitiveRight.dimensions[0] = 2.00;
primitiveRight.dimensions[1] = 0.16;
primitiveRight.dimensions[2] = 4.00;
// 设置障碍物的位置
geometry_msgs::Pose poseRight;
poseRight.orientation.w = 1;
poseRight.position.x = 0.000000;
poseRight.position.y = -1.040000;
poseRight.position.z = -1.00000;
// 将障碍物的属性、位置加入到障碍物的实例中
box_right.primitives.push_back(primitiveRight);
box_right.primitive_poses.push_back(poseRight);
box_right.operation = box_right.ADD;
// 声明一个障碍物的实例,并且为其设置一个id,方便对其进行操作,该实例会发布到当前的情景实例中
moveit_msgs::CollisionObject box_left;
box_left.id = "box_left";
// 设置障碍物的外形、尺寸等属性
shape_msgs::SolidPrimitive primitiveLeft;
primitiveLeft.type = primitiveLeft.BOX;
primitiveLeft.dimensions.resize(3);
primitiveLeft.dimensions[0] = 0.8;
primitiveLeft.dimensions[1] = 0.1;
primitiveLeft.dimensions[2] = 0.74;
// 设置障碍物的位置
geometry_msgs::Pose poseLeft;
poseLeft.orientation.w = 1;
poseLeft.position.x = -0.130000;
poseLeft.position.y = 0.9850000;
poseLeft.position.z = -0.22000;
// 将障碍物的属性、位置加入到障碍物的实例中
box_left.primitives.push_back(primitiveLeft);
box_left.primitive_poses.push_back(poseLeft);
box_left.operation = box_left.ADD;
// 声明一个障碍物的实例,并且为其设置一个id,方便对其进行操作,该实例会发布到当前的情景实例中
moveit_msgs::CollisionObject box_bottom;
box_bottom.id = "box_bottom";
// 设置障碍物的外形、尺寸等属性
shape_msgs::SolidPrimitive primitiveBottom;
primitiveBottom.type = primitiveBottom.BOX;
primitiveBottom.dimensions.resize(3);
primitiveBottom.dimensions[0] = 2.0;
primitiveBottom.dimensions[1] = 2.0;
primitiveBottom.dimensions[2] = 0.1;
// 设置障碍物的位置
geometry_msgs::Pose poseBottom;
poseBottom.orientation.w = 1;
poseBottom.position.x = 0.00000;
poseBottom.position.y = 0.00000;
poseBottom.position.z = -0.36000;
// 将障碍物的属性、位置加入到障碍物的实例中
box_bottom.primitives.push_back(primitiveBottom);
box_bottom.primitive_poses.push_back(poseBottom);
box_bottom.operation = box_bottom.ADD;
// 声明一个障碍物的实例,并且为其设置一个id,方便对其进行操作,该实例会发布到当前的情景实例中
moveit_msgs::CollisionObject box_bottom_cy;
box_bottom_cy.id = "box_bottom_cy";
// 设置障碍物的外形、尺寸等属性
shape_msgs::SolidPrimitive primitiveBottomCy;
primitiveBottomCy.type = primitiveBottomCy.BOX;
primitiveBottomCy.dimensions.resize(3);
primitiveBottomCy.dimensions[0] = 0.16;
primitiveBottomCy.dimensions[1] = 0.26;
primitiveBottomCy.dimensions[2] = 0.56;
// 设置障碍物的位置
geometry_msgs::Pose poseBottomCy;
poseBottomCy.orientation.w = 1;
poseBottomCy.position.x = 0.00000;
poseBottomCy.position.y = 0.00000;
poseBottomCy.position.z = -0.28000;
// 将障碍物的属性、位置加入到障碍物的实例中
box_bottom_cy.primitives.push_back(primitiveBottomCy);
box_bottom_cy.primitive_poses.push_back(poseBottomCy);
box_bottom_cy.operation = box_bottom_cy.ADD;
// 创建一个障碍物的列表,把之前创建的障碍物实例加入其中
std::vector<moveit_msgs::CollisionObject> collision_objects;
//collision_objects.push_back(cylinder);
collision_objects.push_back(object);
collision_objects.push_back(box_right);
collision_objects.push_back(box_left);
collision_objects.push_back(boxUp);
//collision_objects.push_back(boxBoard);
collision_objects.push_back(box_bottom);
collision_objects.push_back(box_bottom_cy);
// 所有障碍物加入列表后(这里只有一个障碍物),再把障碍物加入到当前的情景中,如果要删除障碍物,使用removeCollisionObjects(collision_objects)
current_scene.addCollisionObjects(collision_objects);
ros::shutdown();
return 0;
}
| true |
5c37719d83270cfa807e71664ed080f109d87a3f | C++ | adityanjr/code-DS-ALGO | /CodeForces/Complete/900-999/910A-TheWayToHome.cpp | UTF-8 | 592 | 2.734375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
int main(){
long n, d; std::cin >> n >> d;
std::string s; std::cin >> s;
std::vector<long> v;
for(long p = 0; p < s.size(); p++){if(s[p] == '1'){v.push_back(p);}}
std::vector<long> w(v.size(), n + 1); w[0] = 0;
for(long from = 0; from < v.size(); from++){
for(long to = from + 1; to < v.size(); to++){
if(v[to] - v[from] <= d){w[to] = (w[to] <= w[from] + 1) ? w[to] : (w[from] + 1);}
else{break;}
}
}
std::cout << ((w.back() <= n) ? w.back() : -1) << std::endl;
return 0;
}
| true |
30bad955c8016a30bfdcbcdac96c81f646a6e5c3 | C++ | amclauth/Euler | /C++/Euler (C++)/src/problems/P031xP040/P037.cpp | UTF-8 | 4,642 | 3.65625 | 4 | [] | no_license | #include "../../base/problem.h"
#include "../../util/prime.h"
#include <vector>
/**
* P037<br>
* The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right,
* and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
* Find the sum of the only eleven primes that are both truncatable from left to right and right to left.
* NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
* Ans: 748317
*/
class P037: public Problem
{
public:
P037()
{
problem_number = 37;
variations = 2;
}
~P037()
{
}
std::string execute(int variation)
{
switch (variation)
{
case 0:
return to_string(bruteForce());
case 1:
case -1:
return to_string(faster());
default:
return std::string("unavailable");
}
return NULL;
}
private:
/**
* Check all numbers less than 1 million!
*/
long bruteForce()
{
int total = 0 -2 -3 -5 -7; // these are not "truncatable"
std::vector<int>* primes = prime::EratosthenesPrimesUpTo(1000000);
for (std::vector<int>::iterator it = primes->begin(); it != primes->end(); ++it)
{
int p = *it;
int right = p;
int left = 0;
int power = 1;
bool isTruncatable = true;
while (isTruncatable)
{
left = power * (right % 10) + left;
power *= 10;
right = right / 10;
if (right == 0)
break;
if (!prime::isPrime(left) || !prime::isPrime(right))
{
isTruncatable = false;
}
}
if (isTruncatable || p == 3137 || p == 739397)
{
total += p;
}
}
delete primes;
return total;
}
/**
* Build the numbers to test. The rightmost must be prime in and of itself (2,3,5,7),
* but can't be 5 or would be divisible by 5 and can't be 2 or would be divisible by 2,
* so it must be 3 or 7.
* Numbers in the middle can't be even or 5 or right truncation would end up with them
* being non prime (1,3,7,9).
* The leftmost number must simple be a prime number (2,3,5,7)
*/
long faster()
{
int total = 0;
int lefts[] = {2,3,5,7};
int middles[] = {1,3,7,9};
int rights[] = {3,7};
for (int ii = 0; ii < 4; ii++)
{
int left = lefts[ii];
// check the simple case
{
for (int jj = 0; jj < 2; jj++)
{
int right = rights[jj];
int digit = left * 10 + right;
if (prime::isPrime(digit) && isTruncatable(digit))
{
total += digit;
}
}
}
// up to a six digit number, so we need the left digit, up to 4 in the middle, and the
// right digit. So we need to simply count.
for (int midIdx = 0; midIdx < 256; midIdx++)
{
int predigit = left;
int idx = midIdx;
while (true)
{
predigit = predigit * 10 + middles[idx%4];
idx = idx / 4;
if (idx == 0)
break;
}
for (int jj = 0; jj < 2; jj++)
{
int right = rights[jj];
int digit = predigit * 10 + right;
if (prime::isPrime(digit) && isTruncatable(digit))
{
total += digit;
}
}
}
}
return total;
}
bool isTruncatable(int digit)
{
int rightTrunc = digit;
int leftTrunc = 0;
int power = 1;
bool isTruncatable = true;
while (isTruncatable)
{
leftTrunc = power * (rightTrunc % 10) + leftTrunc;
power *= 10;
rightTrunc = rightTrunc / 10;
if (rightTrunc == 0)
break;
if (!prime::isPrime(leftTrunc) || !prime::isPrime(rightTrunc))
{
isTruncatable = false;
}
}
return isTruncatable;
}
};
| true |
fffd114b24a4af7b2123b97fbb0aedd91dece0a2 | C++ | InsightSoftwareConsortium/ITK | /Modules/Numerics/Statistics/test/itkSampleTest3.cxx | UTF-8 | 5,454 | 2.515625 | 3 | [
"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",
... | permissive | /*=========================================================================
*
* 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 <iostream>
#include "itkSample.h"
#include "itkObjectFactory.h"
#include "itkMath.h"
namespace itk
{
namespace Statistics
{
namespace SampleTest
{
template <typename TMeasurementVector>
class MySample : public Sample<TMeasurementVector>
{
public:
/** Standard class type alias. */
using Self = MySample;
using Superclass = Sample<TMeasurementVector>;
using Pointer = SmartPointer<Self>;
using ConstPointer = SmartPointer<const Self>;
/** Standard macros */
itkTypeMacro(MySample, Sample);
/** Method for creation through the object factory. */
itkNewMacro(Self);
using typename Superclass::MeasurementVectorType;
using typename Superclass::TotalAbsoluteFrequencyType;
using typename Superclass::AbsoluteFrequencyType;
using typename Superclass::InstanceIdentifier;
/** Get the size of the sample (number of measurements) */
InstanceIdentifier
Size() const override
{
return static_cast<InstanceIdentifier>(m_Values.size());
}
/** Remove all measurement vectors */
virtual void
Clear()
{
m_Values.clear();
}
/** Get the measurement associated with a particular
* InstanceIdentifier. */
const MeasurementVectorType &
GetMeasurementVector(InstanceIdentifier id) const override
{
return m_Values[id];
}
/** Get the frequency of a measurement specified by instance
* identifier. */
AbsoluteFrequencyType
GetFrequency(InstanceIdentifier id) const override
{
return m_Frequencies[id];
}
/** Get the total frequency of the sample. */
TotalAbsoluteFrequencyType
GetTotalFrequency() const override
{
TotalAbsoluteFrequencyType sum{};
auto itr = m_Frequencies.begin();
while (itr != m_Frequencies.end())
{
sum += *itr;
++itr;
}
return sum;
}
void
PrintSelf(std::ostream & os, Indent indent) const override
{
Superclass::PrintSelf(os, indent);
os << indent << m_Values.size() << std::endl;
os << indent << m_Frequencies.size() << std::endl;
}
void
AddMeasurementVector(const MeasurementVectorType & measure, AbsoluteFrequencyType frequency)
{
m_Values.push_back(measure);
m_Frequencies.push_back(frequency);
}
private:
std::vector<TMeasurementVector> m_Values;
std::vector<AbsoluteFrequencyType> m_Frequencies;
};
} // namespace SampleTest
} // namespace Statistics
} // namespace itk
int
itkSampleTest3(int, char *[])
{
constexpr unsigned int MeasurementVectorSize = 17;
using MeasurementVectorType = itk::VariableLengthVector<float>;
using SampleType = itk::Statistics::SampleTest::MySample<MeasurementVectorType>;
auto sample = SampleType::New();
std::cout << sample->GetNameOfClass() << std::endl;
std::cout << sample->SampleType::Superclass::GetNameOfClass() << std::endl;
sample->Print(std::cout);
sample->SetMeasurementVectorSize(MeasurementVectorSize); // for code coverage
if (sample->GetMeasurementVectorSize() != MeasurementVectorSize)
{
std::cerr << "GetMeasurementVectorSize() Failed !" << std::endl;
return EXIT_FAILURE;
}
std::cout << sample->Size() << std::endl;
MeasurementVectorType measure(MeasurementVectorSize);
for (unsigned int i = 0; i < MeasurementVectorSize; ++i)
{
measure[i] = 29 * i * i;
}
using AbsoluteFrequencyType = SampleType::AbsoluteFrequencyType;
AbsoluteFrequencyType frequency = 17;
sample->AddMeasurementVector(measure, frequency);
MeasurementVectorType measureBack = sample->GetMeasurementVector(0);
AbsoluteFrequencyType frequencyBack = sample->GetFrequency(0);
if (frequencyBack != frequency)
{
std::cerr << "Error in GetFrequency()" << std::endl;
return EXIT_FAILURE;
}
for (unsigned int j = 0; j < MeasurementVectorSize; ++j)
{
if (itk::Math::NotExactlyEquals(measureBack[j], measure[j]))
{
std::cerr << "Error in Set/Get MeasurementVector()" << std::endl;
return EXIT_FAILURE;
}
}
std::cout << sample->GetTotalFrequency() << std::endl;
try
{
sample->SetMeasurementVectorSize(MeasurementVectorSize + 5);
std::cerr << "Sample failed to throw an exception when calling SetMeasurementVectorSize()" << std::endl;
return EXIT_FAILURE;
}
catch (const itk::ExceptionObject & excp)
{
std::cout << "Expected exception caught: " << excp << std::endl;
}
// If we call Clear(), now we should be able to change the
// MeasurementVectorSize of the Sample:
sample->Clear();
try
{
sample->SetMeasurementVectorSize(MeasurementVectorSize + 5);
}
catch (const itk::ExceptionObject & excp)
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| true |
a2f15079694a23c486781a52a94daca9460cba59 | C++ | algorithmstudy4/sw_test | /s_coding/1992_쿼드트리.cpp | UTF-8 | 1,749 | 3.453125 | 3 | [] | no_license | //1992 쿼드 트리
//https://www.acmicpc.net/problem/1992
#include <iostream>
#include <string>
using namespace std;
int arr[64][64];
//1.현재 구간에 있는 구간들이 0 으로만 또는 1로만 이루어져 있으면 해당숫자 출력
//2.1번 조건이 성립하지 않으면 ( 출력하고 2->1->4->3 사분면 순서로 구간을 잘라 재귀호출 후 )출력
//3.기저사례는 구간의 크기가 1일 경우 , 구간의 크기가 1이면 해당 숫자 출력
void compress(int n,int y,int x){ //(y,x):start point
bool zero = true, one = true;
//기저사례: 해당 숫자 출력
if (n == 1) {
cout << arr[y][x];
return;
}
for (int i = y; i < y + n; i++) { //구간내에서
for (int j = x; j < x + n; j++) {
if (arr[i][j] == 1) { //구간내에서 1이 하나라도 있으면
zero = false; //0은 false
}else { //구간 내에서 0이 하나라도 있으면
one = false; //1은 false
}
}
}
if (zero) { //zero true면 구간내에서 zero밖에 없는 것
cout << "0";
}
else if (one) { //one이 true면 구간 내에서 one밖에 없는것
cout << "1";
}
else { //0으로만 ,1로만 , 이루어져 있지 않다면 재귀 통해서 구간 반으로
cout << "(";
compress(n / 2, y, x); //2사분면
compress(n / 2, y, x+n/2); //1사분면
compress(n / 2, y+n/2, x); //3사분면
compress(n / 2, y + n / 2, x + n / 2); //4사분면
cout << ")";
}
return;
}
int main() {
int size;
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> size;
bool zero = true, one = true;
for (int i = 0; i < size; i++) {
string str;
cin >> str;
for (int j = 0; j < size; j++) {
arr[i][j] = str[j] - '0';
}
}
compress(size, 0, 0);
cout << endl;
return 0;
}
| true |
8ba20b0d360a2fcdb73dd50b8a13d1530eb2aaea | C++ | indjev99/Competitive-Programming-Problems | /transmission/system/manager.cpp | UTF-8 | 4,030 | 2.65625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <vector>
#include <signal.h>
static int n,d,k,seed,m,m2,n2;
static std::vector<bool> data;
static std::vector<bool> message;
static std::vector<bool> deletions;
static std::vector<bool> corruptedMessage;
static std::vector<bool> reconstructedData;
static double authorScore;
static double score;
static int invalid;
static const long long HASH_BASE=198437;
static const long long HASH_MOD=1940242723;
static long long hash_message_with(long long num)
{
long long hsh=num%HASH_MOD;
for (int i=0;i<message.size();++i)
{
hsh=(hsh*HASH_BASE+message[i])%HASH_MOD;
}
return hsh;
}
static long long random_number()
{
return rand()*(RAND_MAX+1ll)+rand();
}
static void input()
{
std::cin>>n>>d>>k>>seed>>authorScore;
data.resize(n);
srand(seed);
for (int i=0;i<n;++i)
{
data[i]=rand()%2;
}
}
static void output_result()
{
if (invalid==0)
{
std::cout<<std::setprecision(6)<<std::min(score/authorScore,1.0)<<"\n";
std::cerr<<"Result: "<<std::setprecision(6)<<std::min(score/authorScore,1.0)<<"\n";
return;
}
if (invalid==-1)
{
std::cout<<"0\n";
std::cerr<<"Your transmitter returned too many bits.\n";
return;
}
if (invalid==-2)
{
std::cout<<"0\n";
std::cerr<<"Your receiver returned too few/many bits.\n";
return;
}
if (invalid=-3)
{
std::cout<<"0\n";
std::cerr<<"Your receiver didn't get more then half the bits correct.\n";
return;
}
std::cout<<"0\n";
std::cerr<<"Unknown error.\n";
}
static void generate_deletions()
{
srand(hash_message_with(seed));
deletions.resize(m);
int deleted=0;
int toDelete=std::min(d,m);
while (deleted<toDelete)
{
int pos=random_number()%m;
for (int j=0;j<k && pos+j<m && deleted<toDelete;++j)
{
if (deletions[pos+j]==0)
{
deletions[pos+j]=1;
++deleted;
}
}
}
}
static void corrupt_message()
{
m2=std::max(0,m-d);
corruptedMessage.resize(m2);
int j=0;
for (int i=0;i<m2;++i)
{
while (deletions[j]) ++j;
corruptedMessage[i]=message[j];
++j;
}
}
static void get_score()
{
int correct=0;
for (int i=0;i<n;++i)
{
if (reconstructedData[i]==data[i]) ++correct;
}
if (2*correct<=n)
{
invalid=-3;
return;
}
score=2*correct-n;
score/=std::max(m2,n);
}
int main(int argc, char **argv)
{
signal(SIGPIPE, SIG_IGN);
FILE *fifo_in_1, *fifo_out_1, *fifo_in_2, *fifo_out_2;
fifo_out_1 = fopen(argv[1],"w");
fifo_in_1 = fopen(argv[2],"r");
fifo_out_2 = fopen(argv[3],"w");
fifo_in_2 = fopen(argv[4],"r");
input();
int x;
//message=transmit(data,d);
fprintf(fifo_out_1,"%d %d\n",n,d);
for(int i=0;i<n;++i)
{
if (i) fprintf(fifo_out_1," ");
fprintf(fifo_out_1,"%d",(int)data[i]);
}
fprintf(fifo_out_1,"\n");
fflush(fifo_out_1);
fscanf(fifo_in_1,"%d",&m);
message.resize(m);
for (int i=0;i<m;++i)
{
fscanf(fifo_in_1,"%d",&x);
message[i]=x;
}
generate_deletions();
corrupt_message();
//reconstructedData=receive(corruptedMessage,n,d);
fprintf(fifo_out_2,"%d %d %d\n",n,d,m2);
for (int i=0;i<m2;++i)
{
if (i) fprintf(fifo_out_2," ");
fprintf(fifo_out_2,"%d",(int)corruptedMessage[i]);
}
fprintf(fifo_out_2,"\n");
fflush(fifo_out_2);
fscanf(fifo_in_2,"%d",&n2);
reconstructedData.resize(n2);
for (int i=0;i<n2;++i)
{
fscanf(fifo_in_2,"%d",&x);
reconstructedData[i]=x;
}
if (m>100000) invalid=-1;
else if (n2!=n) invalid=-2;
if (!invalid) get_score();
output_result();
fclose(fifo_in_1);
fclose(fifo_out_1);
fclose(fifo_in_2);
fclose(fifo_out_2);
return 0;
}
| true |
03a0a0d7a93fc29b5c1b457d2f9dbe8752a31601 | C++ | Mazbah/UVA-OJ | /uva-11945.cpp | UTF-8 | 507 | 2.625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
void printcomma(int n){
if(n<1000){
cout<<n;
return;
}
printcomma(n/1000);
printf(",%03d",n%1000);
}
int main()
{
int n,i,j;
double sum,a,r;
cin>>n;
setlocale(LC_ALL,"en_US.UTF-8");
for(i=1;i<=n;i++){
sum = 0;
for(j=1;j<=12;j++){
cin>>a;
sum+=a;
}
// r = sum/12;
printf("%d $%'.2lf\n",i,sum/12.0);
}
return 0;
}
| true |
544e47adff0fdb5d6a779ac2ec05178b7dcf4e89 | C++ | JMang0321/designPattern | /adaptor/stack_class/stack.h | UTF-8 | 292 | 3.328125 | 3 | [] | no_license | #pragma once
#include <vector>
using namespace std;
class Stack {
public:
Stack() {}
virtual void pop() {
if (m_num.size() <= 0)
return;
else
m_num.erase(m_num.end());
}
virtual void push(int num) {
m_num.push_back(num);
}
private:
vector<int> m_num;
}; | true |
47182f7e5ab747e12b1efaf471851dfa6f986f37 | C++ | wenxinz/C-PrimerPlus | /chapter15/ex4.cpp | UTF-8 | 1,888 | 3.09375 | 3 | [] | no_license | #include <iostream>
#include "sales.h"
int main(){
using std::cout;
using std::cin;
using std::endl;
double vals1[12]={1220,1100,1122,2212,1232,2334,
2884,2393,3302,2922,3002,3544};
double vals2[12]={12,11,22,21,32,34,
28,29,33,29,32,35};
Sales sales1(2004, vals1, 12);
LabeledSales sales2("Blogstar", 2005, vals2, 12);
cout << "First try block:\n";
try{
int i;
cout << "Year = " << sales1.Year() << endl;
for(i=0;i<12;++i){
cout << sales1[i] << ' ';
if(i%6 == 5)
cout << endl;
}
cout << "Year = " << sales2.Year() << endl;
cout << "Label = " << sales2.Label() << endl;
for(i=0;i<=12;++i){
cout << sales2[i] << ' ';
if(i%6 == 5)
cout << endl;
}
cout << "End of try block 1.\n";
}
catch(Sales::bad_index & bad){
Sales::bad_index * bp = &bad;
LabeledSales::nbad_index * ni;
if(ni = dynamic_cast<LabeledSales::nbad_index *>(bp)){
cout << ni->what();
cout << "Company: " << ni->label_val() << endl;
cout << "bad index: " << ni->bi_val() << endl;
}
else{
cout << bp->what();
cout << "bad index: " << bp->bi_val() << endl;
}
}
cout << "\nNext try block:\n";
try{
sales2[2] = 37.5;
sales1[20] = 23345;
cout << "End of try block 2.\n";
}
catch(Sales::bad_index & bad){
Sales::bad_index * bp = &bad;
LabeledSales::nbad_index * ni;
if(ni = dynamic_cast<LabeledSales::nbad_index *>(bp)){
cout << ni->what();
cout << "Company: " << ni->label_val() << endl;
cout << "bad index: " << ni->bi_val() << endl;
}
else{
cout << bp->what();
cout << "bad index: " << bp->bi_val() << endl;
}
}
cout << "done\n";
return 0;
}
| true |
c361aea72230d7b2a9bdb0aafa792599607c252c | C++ | da-phil/SDC-Controls-PID | /src/PID.h | UTF-8 | 1,378 | 2.703125 | 3 | [
"MIT"
] | permissive | #ifndef PID_H
#define PID_H
class PID {
public:
/*
* Errors
*/
double p_error;
double i_error;
double d_error;
/*
* Coefficients
*/
double Kp;
double Ki;
double Kd;
int skip_initial_samples;
int sample_count;
bool twiddle_enable;
double rmse_sum;
double rmse_best;
double twiddle_tolerance;
double twiddle_params[3];
int samples_per_twiddle;
int twiddle_direction, twiddle_index;
int twiddle_step;
/*
* Constructor
*/
PID();
PID(double Kp, double Ki, double Kd) {
Init(Kp, Ki, Kd);
};
/*
* Destructor.
*/
virtual ~PID();
/*
* Initialize PID.
*/
void Init(double Kp, double Ki, double Kd, int skip_initial_samples = 50);
/*
* Update the PID error variables given cross track error.
*/
void UpdateError(double cte);
/*
* Calculate the total PID error.
*/
double TotalError();
/*
* Calculate the RMSE of all total PID errors so far.
*/
double GetRMSE();
/*
* Reset internal RMSE value
*/
void ResetRMSE();
/*
* Parameterize twiddle, which optimizes the P, I and D gains by reducing the RMSE.
*/
void ActivateTwiddle(double Kp_d, double Ki_d, double Kd_d, double twiddle_tolerance, int samples_per_twiddle);
/*
* Twiddle function which keeps changing the P, I and D gains in order to recude the RMSE.
*/
void Twiddle();
};
#endif /* PID_H */
| true |
bc9fd3f7b592080191fcc42c921913670d8f1def | C++ | BackupTheBerlios/robotm6 | /robot2005/src/devices/real/motorIsa_05.cpp | ISO-8859-1 | 5,831 | 2.546875 | 3 | [] | no_license | #include "implementation/motorIsa.h"
#ifdef TEST_MAIN
#include <signal.h>
#include <stdlib.h>
#endif
#include "HCTLControl.h"
#include "log.h"
// ============================================================================
// ============================== class MotorIsa ==========================
// ============================================================================
/** Reset les hctl (gauche et droite) */
bool MotorIsa::reset()
{
#ifndef TEST_MAIN
LOG_FUNCTION();
// on previent robot_pos qu'il y a un saut possible dans la valeur des
// codeurs avant et apres le reset
MotorCL::reset();
hctlSetMotorSpeed(0, 0);
if (resetCallBack_) resetCallBack_();
hctlIdle();
if (resetCallBack_) resetCallBack_();
hctlInit();
if (resetCallBack_) resetCallBack_();
#else
MotorCL::reset();
hctlSetMotorSpeed(0, 0);
hctlIdle();
hctlInit();
#endif
return true;
}
/** Defini la constante d'acceleration des moteurs */
void MotorIsa::setAcceleration(MotorAcceleration acceleration)
{
hctlSetAcceleration(acceleration);
}
/** Specifie un consigne en vitesse pour les moteurs */
void MotorIsa::setSpeed(MotorSpeed left,
MotorSpeed right)
{
// on a change les moteurs et les codeurs, maintenant ca va 2 fois
// moins vite. Pour pas changer les gains qu'on a teste, on change
// juste la consigne envoyee aux moteurs. A corrige en 2005 ;)
hctlSetMotorSpeed( 2*right, 2*left);
}
/** Retourne la position des codeurs */
void MotorIsa::getPosition(MotorPosition &left,
MotorPosition &right)
{
right=hctlGetRightPos();
left =hctlGetLeftPos();
}
/** Retourne la consigne reellement envoyee au moteurs */
void MotorIsa::getPWM(MotorPWM &left,
MotorPWM &right)
{
left =hctlGetLeftPWM();
right=hctlGetRightPWM();
}
/** Desasservit les moteurs */
void MotorIsa::idle()
{
hctlIdle();
}
/** Constructeur */
MotorIsa::MotorIsa(bool automaticReset,
MotorAlertFunction fn) :
MotorCL(automaticReset, fn), isStarted_(false)
{
}
void MotorIsa::start()
{
#ifndef TEST_MAIN
LOG_FUNCTION();
#endif
hctlInit();
// reset();
#ifndef TEST_MAIN
LOG_OK("Initialisation termine\n");
#endif
isStarted_ = true;
}
MotorIsa::~MotorIsa()
{
hctlCleanUp();
}
#ifdef TEST_MAIN
#include <unistd.h>
#include <termios.h>
#include <stdio.h>
#include <errno.h>
struct termios confterm;
typedef struct MotorOrder {
int speedRight;
int speedLeft;
MotorOrder(): speedRight(0), speedLeft(0){}
} MotorOrder;
MotorOrder order;
static const int MAX_NORMAL_SPEED=120;
void configureKeyboard()
{
tcgetattr(0,&confterm);
confterm.c_lflag = confterm.c_lflag & ~ICANON;
confterm.c_cc[VMIN]=1;
tcsetattr(0,TCSANOW,&confterm);
}
/**
* Check that motor order is in normal range
*/
void checkMotorOrder()
{
if (order.speedLeft>MAX_NORMAL_SPEED)
order.speedLeft=MAX_NORMAL_SPEED;
else if (order.speedLeft<-MAX_NORMAL_SPEED)
order.speedLeft=-MAX_NORMAL_SPEED;
if (order.speedRight>MAX_NORMAL_SPEED)
order.speedRight=MAX_NORMAL_SPEED;
else if (order.speedRight<-MAX_NORMAL_SPEED)
order.speedRight=-MAX_NORMAL_SPEED;
}
/**
* Display programm usage
*/
void showUsage()
{
printf("\nUsage:\n");
printf(" Space : emergency stop\n");
printf(" Use arrows to move the robot\n");
printf(" r: reset motor\n");
printf(" q : exit the application\n");
printf(" h : display this message\n");
printf("\n");
}
void setEmergencyStopOrder()
{
order.speedRight=0;
order.speedLeft =0;
printf("setSpeed(%d, %d)\n", order.speedLeft, order.speedRight);
}
void handle8()
{
order.speedLeft +=5;
order.speedRight+=5;
printf("setSpeed(%d, %d)\n", order.speedLeft, order.speedRight);
}
void handle2()
{
order.speedLeft -=5;
order.speedRight-=5;
printf("setSpeed(%d, %d)\n", order.speedLeft, order.speedRight);
}
void handle4()
{
order.speedLeft -=5;
order.speedRight+=5;
printf("setSpeed(%d, %d)\n", order.speedLeft, order.speedRight);
}
void handle6()
{
order.speedLeft +=5;
order.speedRight-=5;
printf("setSpeed(%d, %d)\n", order.speedLeft, order.speedRight);
}
bool getKeyboardOrder(MotorIsa& motor)
{
char rep;
read(0,&rep,1);
switch (rep) {
// motor
case 27 :
read(0,&rep,1);
read(0,&rep,1);
switch (rep) {
case 'A' : handle8(); break;
case 'B' : handle2(); break;
case 'D' : handle4(); break;
case 'C' : handle6(); break;
}
break;
case '8' : handle8(); break;
case '2' : handle2(); break;
case '4' : handle4(); break;
case '6' : handle6(); break;
// emergency stop
case '5' :
case ' ' :
setEmergencyStopOrder();
break;
case 'r' :
case 'R' :
motor.reset();
order.speedLeft=0;
order.speedRight=0;
break;
case 'c' :
case 'C' :
MotorPosition posLeft, posRight;
motor.getPosition(posLeft, posRight);
printf("Coder position: left=%d,\tright=%d\n", posLeft, posRight);
break;
case 'w' :
case 'W' :
MotorPWM pwmLeft, pwmRight;
motor.getPWM(pwmLeft, pwmRight);
printf("PWM: left=%d,\tright=%d\n",pwmLeft, pwmRight);
break;
case 'h' :
case 'H' :
showUsage();
break;
// exit
case 'q':
case 'Q':
case '-':
return false;
break;
default:
break;
}
checkMotorOrder();
motor.setSpeed(order.speedLeft, order.speedRight);
return true;
}
MotorIsa * pMotor=NULL;
void motorRealTelecommandSIGINT(int sig) {
if (pMotor) pMotor->reset();
usleep(10000);
exit(-1);
}
int main() {
showUsage();
configureKeyboard();
(void) signal(SIGINT, motorRealTelecommandSIGINT);
MotorIsa motor;
motor.start();
pMotor=&motor;
motor.reset();
while(getKeyboardOrder(motor));
motor.reset();
pMotor = NULL;
printf("Bye\n");
}
#endif // TEST_MAIN
| true |
b60d4aaac93828c5a9f2586e749f03561700d4aa | C++ | LightGrand/nmos-cpp | /Development/nmos/log_manip.h | UTF-8 | 805 | 2.5625 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #ifndef NMOS_LOG_MANIP_H
#define NMOS_LOG_MANIP_H
#include "nmos/slog.h"
#include "nmos/model.h"
namespace nmos
{
// Log a model in abbreviated form (relying on logging of utility::string_t, from nmos/slog.h)
inline slog::log_statement::manip_function put_model(const model& model)
{
return slog::log_manip([&](slog::log_statement& s)
{
for (auto& resource : model.resources)
{
s << resource.type << ' ' << resource.id.substr(0, 6) << ' ' << make_version(resource.created) << ' ' << make_version(resource.updated) << '\n';
for (auto& sub_resource : resource.sub_resources)
{
s << " " << sub_resource.substr(0, 6) << '\n';
}
}
});
}
}
#endif
| true |
46da765426d05d31e031e8858691cb11d2e2dd43 | C++ | MarcoDuesentrieb/pad-ex01 | /ex01/async.cpp | UTF-8 | 9,009 | 3.109375 | 3 | [] | no_license | #include <benchmark/benchmark.h> // google benchmark
#include <algorithm>
#include <future>
#include <iostream>
#include <random>
#include <thread>
#include <type_traits>
#include <utility>
#include <vector>
using ElementType = int;
using Ex1VectorType = std::vector<ElementType>;
//-------------------------------------------
// From ex1.1: For comparison with base line.
//-------------------------------------------
Ex1VectorType matVec(const Ex1VectorType& A, const Ex1VectorType& x) {
if (A.size() % x.size() != 0)
throw std::invalid_argument("wrong matrix size");
std::size_t ni = x.size();
std::size_t nj = A.size() / ni;
Ex1VectorType result(nj, 0); // initializes result to 0
for (std::size_t j = 0; j < nj; ++j)
for (std::size_t i = 0; i < ni; ++i)
result[j] += A[ni * j + i] * x[i];
// result is an rvalue as per C++14, §12.8, thus the move is implicit;
// however, most compilers use NRVO here (i.e. the result object is
// constructed in-place, i.e. neither copy nor move is necessary). C++17 even
// mandates that the copy be elided.
return result;
}
Ex1VectorType generateVectorOfRandomNumbers(std::size_t size, unsigned seed) {
std::mt19937 gen(seed);
std::uniform_int_distribution<std::int32_t> dis;
Ex1VectorType result(size);
for (auto& entry : result)
entry = dis(gen);
return result;
}
struct TestDataSet {
Ex1VectorType A;
Ex1VectorType x;
TestDataSet(std::size_t nX, std::size_t nY, unsigned seed)
: A(generateVectorOfRandomNumbers(nX * nY, seed)),
x(generateVectorOfRandomNumbers(nX, seed)) {}
};
//--------------------------------------
// Ex1.3: Actual implementation of Ex1.3
//--------------------------------------
template <typename ResultIterT,
typename MatIterT,
typename VecIterT,
typename BinaryOpT,
typename AccumulatorT>
void matVec_generic_iterator(
ResultIterT itResult,
MatIterT firstA,
MatIterT lastA,
VecIterT firstX,
VecIterT lastX,
BinaryOpT binaryOp, // T binaryOp(T lhs, T rhs)
AccumulatorT accumulator, // T accumulator(T sum, T part)
ElementType nA,
ElementType nX,
ElementType nY,
typename std::iterator_traits<ResultIterT>::value_type seed = {}) {
static_assert(
std::is_same<
typename std::iterator_traits<ResultIterT>::value_type,
typename std::iterator_traits<MatIterT>::value_type>::value &&
std::is_same<
typename std::iterator_traits<ResultIterT>::value_type,
typename std::iterator_traits<VecIterT>::value_type>::value,
"all iterators should have the same value_type");
// We can't easily check for dimension errors here because we don't know
// whether itResult points to a large enough data structure, and because
// MatIterT and VecIterT might be iterators without random access.
// START WRITING YOUR CODE AFTER THIS LINE
if (nA % nX != 0)
throw std::invalid_argument("wrong matrix size");
std::cout << "Result of accumulator: " << accumulator(*itResult, binaryOp(*firstA, *firstX)) << " real result: " << (*firstA) * (*firstX) << std::endl;
for (std::size_t j = 0; j < nY; ++j) {
for (std::size_t i = 0; i < nX; ++i) {
auto currentItResult = itResult + j;
*currentItResult = accumulator(*currentItResult, binaryOp(*(firstA + nX * j + i), *(firstX + i)));
}
}
// FINISH WRITING YOUR CODE BEFORE THIS LINE
}
template <typename ResultIterT,
typename MatIterT,
typename VecIterT,
typename BinaryOpT,
typename AccumulatorT>
void matVec_parallel(
ResultIterT itResult,
MatIterT firstA,
MatIterT lastA,
VecIterT firstX,
VecIterT lastX,
BinaryOpT binaryOp, // T binaryOp(T lhs, T rhs)
AccumulatorT accumulator, // T accumulator(T sum, T part)
unsigned parallelism = 1,
typename std::iterator_traits<ResultIterT>::value_type seed = {}) {
static_assert(
std::is_same<
typename std::iterator_traits<ResultIterT>::value_type,
typename std::iterator_traits<MatIterT>::value_type>::value &&
std::is_same<
typename std::iterator_traits<ResultIterT>::value_type,
typename std::iterator_traits<VecIterT>::value_type>::value,
"all iterators should have the same value_type");
// here we have to assume that MatIterT and VecIterT are random access
// iterators anyway, so we can do at least some error checking
std::size_t nA = lastA - firstA;
std::size_t nX = lastX - firstX;
if (nA % nX != 0)
throw std::invalid_argument("wrong matrix size");
std::size_t nY = nA / nX;
// find out how many tasks we need
unsigned numThreads = std::min(parallelism, static_cast<unsigned>(nY));
std::size_t delta = (nY + numThreads - 1) / numThreads;
// set up tasks
// START WRITING YOUR CODE AFTER THIS LINE
int rowsPerTask = nY / numThreads;
int leftOver = nY % numThreads;
std::vector<std::future<void>> tasks;
//std::cout << "nA: " << nA << "; nX: " << nX << "; numThreads: " << numThreads << "; leftOver: " << leftOver << "; parallelism: " << parallelism << std::endl;
for(int i = 0; i < numThreads; i++) {
std::future<void> task;
if(i == numThreads - 1 && leftOver != 0) {
auto firstA_p = firstA + i * rowsPerTask * nX;
auto lastA_p = firstA + i * rowsPerTask * nX + leftOver * nX;
auto firstItResult = itResult + i * rowsPerTask;
task = std::async(std::launch::async, [&] { matVec_generic_iterator(firstItResult, firstA_p, firstA_p, firstX, lastX, binaryOp, accumulator, leftOver * nX, nX, leftOver, seed); });
} else {
auto firstA_p = firstA + i * rowsPerTask * nX;
auto lastA_p = firstA + (i + 1) * rowsPerTask * nX;
auto firstItResult = itResult + i * rowsPerTask;
task = std::async(std::launch::async, [&] { matVec_generic_iterator(firstItResult, firstA_p, lastA_p, firstX, lastX, binaryOp, accumulator, rowsPerTask * nX, nX, rowsPerTask, seed); });
}
tasks.push_back(move(task));
}
for(auto& task: tasks) {
task.get();
}
// FINISH WRITING YOUR CODE BEFORE THIS LINE
}
//--------------------------
// Google Benchmark Template
//--------------------------
static void Ex1Arguments(benchmark::internal::Benchmark* b) {
unsigned int nthreads = std::thread::hardware_concurrency();
const auto lowerLimit = 1;
const auto upperLimit = 100000;
// Generate x,y
for (auto x = lowerLimit; x <= upperLimit; x *= 10) {
for (auto y = lowerLimit; y <= upperLimit; y *= 10) {
for (auto t = 1; t <= nthreads; t = t << 1) {
b->Args({x, y, t});
}
}
}
}
void setCustomCounter(benchmark::State& state) {
state.counters["x"] = state.range(0);
state.counters["y"] = state.range(1);
state.counters["threads"] = state.range(2);
auto BytesProcessed = int64_t(state.iterations()) * int64_t(state.range(0)) *
int64_t(state.range(1)) * sizeof(ElementType);
state.counters["bytes"] = BytesProcessed;
state.SetBytesProcessed(BytesProcessed);
auto FLOP = int64_t(state.iterations()) * int64_t(state.range(0)) *
int64_t(state.range(1)) * 2;
state.counters["FLOP"] = FLOP;
state.counters["FLOPperIter"] = FLOP / state.iterations();
state.counters["sizeof(A+x+y)"] =
sizeof(ElementType) * (int64_t(state.range(0)) * int64_t(state.range(1)) +
int64_t(state.range(0)) + int64_t(state.range(1)));
}
// Multithreaded
static void benchAsync(benchmark::State& state) {
auto seed = 42;
TestDataSet data{static_cast<std::size_t>(state.range(0)), static_cast<std::size_t>(state.range(1)), static_cast<unsigned>(seed)};
auto y = matVec(data.A, data.x);
// storage for result of parallel computation
Ex1VectorType yp(data.A.size() / data.x.size());
Ex1VectorType result(state.range(1));
for (auto _ : state) {
std::fill(yp.begin(), yp.end(), 0);
matVec_parallel(yp.begin(), data.A.begin(), data.A.end(), data.x.begin(),
data.x.end(), std::multiplies<ElementType>(),
std::plus<ElementType>(), state.range(2));
benchmark::DoNotOptimize(yp.data());
benchmark::ClobberMemory();
}
setCustomCounter(state);
// not sure what the problem is, for some reason on the second try, yp[0] has a different result than y[0], even though everything is the same
std::cout << "sizeof: " << sizeof(data.A) << " " << sizeof(data.x) << " " << sizeof(y) << " " << sizeof(y[0]) << " " << sizeof(yp) << " " << sizeof(yp[0]) << std::endl;
std::cout << "variables: " << data.A[0] << " " << data.x[0] << " " << y[0] << " " << yp[0] << " " << data.A[0] * data.x[0] << std::endl;
if (y != yp)
throw std::runtime_error("wrong result.");
else
std::cout << "Correct result." << std::endl;
}
BENCHMARK(benchAsync)->Apply(Ex1Arguments)->UseRealTime();
BENCHMARK_MAIN();
| true |
422c708fa0872c1d9188c25b56b2df06af8aa414 | C++ | sriharsha00/Sriharsha-s-Projects | /Coding Assingment/cart.h | UTF-8 | 1,038 | 3.671875 | 4 | [] | no_license | #ifndef CART_H
#define CART_H
/* This is a header file of cart class. This header file includes cart class definitions */
#include "item.h"
#include <vector>
class GroceryCart {
public:
void insertItem(Item); // inserts a item into this function by using push_back function.
void deleteItem(Item); // deletes a item into this function by using erase function.
int getItemCount(); // get cart count by using size function.
bool isCartEmpty(); // returns size = 0 if cart is empty.
double calcTotalCost(); // calculates the total cost of the cart object.
friend bool operator==(GroceryCart& cart3, GroceryCart& cart4); // comapres if cart 3 and 4 are equal by using bool statement.
double getSize(); // gets the size of the item for specific cart.
Item getItemAt(double); // getting the item from item class for the comparision of cart 3 and 4.
private:
double count;
double cost;
std::vector<Item> cart;
};
#endif | true |
d2b86f236fdd55b3c331e7cf01ebe19bcd1c5b9d | C++ | WadeZeak/C_and_Cpp | /cpp基础/new&delete/newdelete/对象数组.cpp | GB18030 | 464 | 3.078125 | 3 | [] | no_license |
#include<stdlib.h>
#include<iostream>
using namespace std;
class MyClass1
{
private:
int *p;
int len;
public:
MyClass1()//ʱʼ
{
cout << "MyClass " << endl;
}
~MyClass1()//ɾʱͷڴ
{
cout << "MyClass " << endl;
}
};
void mainghf()
{
MyClass1 *p = new MyClass1[10];
//ͿֱdeleteӵҪ[ ]
delete []p;
system("pause");
} | true |
ff48d4d36601c8ea87127760d1183ad06ece011c | C++ | DennisRoos/Advent2019 | /template.cpp | UTF-8 | 485 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main(int argc, char * argv[])
{
ifstream infile;
infile.open("data.txt");
if (infile.is_open())
{
int num;
int answer;
while (infile >> num)
{
//dostuff with numbers
}
//calculate final answer
cout << Final answer is << " answer << "\n";
}
else {
cout << "can't find file?\n";
}
} | true |
ceb514c0e0d3f2d3bf64d626c47ee8fe46d952db | C++ | wangscript007/XLib-1 | /Source/XLib.Containers.CyclicQueue.h | UTF-8 | 3,167 | 3.265625 | 3 | [] | no_license | #pragma once
#include "XLib.Types.h"
#include "XLib.Debug.h"
#include "XLib.Util.h"
namespace XLib
{
struct CyclicQueueStoragePolicy abstract final
{
struct InternalHeap abstract final {};
struct External abstract final {};
template <uint32 storageSize>
struct InternalStatic abstract final {};
};
template <typename Type, typename StoragePolicy = CyclicQueueStoragePolicy::InternalHeap>
class CyclicQueue
{
static_assert(true, "XLib.Containers.CyclicQueue: invalid storage policy");
};
// TODO: add rvalues and destructors
template <typename Type>
class CyclicQueue<Type, CyclicQueueStoragePolicy::External>
{
private:
Type *buffer = nullptr;
uint32 bufferSize = 0;
uint32 frontIdx = 0, backIdx = 0;
public:
inline void initialize(Type* storage, uint32 capacity)
{
buffer = storage;
bufferSize = capacity;
frontIdx = 0;
backIdx = 0;
}
inline uint32 getCapacity() { return bufferSize; }
inline uint32 getSize() { return (bufferSize + backIdx - frontIdx) % bufferSize; }
inline bool isFull() { return (backIdx + 1) % bufferSize == frontIdx; }
inline bool isEmpty() { return frontIdx == backIdx; }
inline void pushBack(const Type& value)
{
XASSERT(!isFull(), "queue is full");
buffer[backIdx] = value;
backIdx = (backIdx + 1) % bufferSize;
}
inline Type popFront()
{
XASSERT(!isEmpty(), "queue is empty");
Type value = buffer[frontIdx];
frontIdx = (frontIdx + 1) % bufferSize;
return value;
}
inline void dropFront()
{
XASSERT(!isEmpty(), "queue is empty");
buffer[frontIdx].~Type();
frontIdx = (frontIdx + 1) % bufferSize;
}
inline Type& front() { return buffer[frontIdx]; }
inline Type& back() { return buffer[(backIdx + bufferSize - 1) % bufferSize]; }
inline Type& operator [] (uint32 index) { return buffer[(frontIdx + index) % bufferSize]; }
};
template <typename Type, uint32 bufferSize>
class CyclicQueue<Type, CyclicQueueStoragePolicy::InternalStatic<bufferSize>>
{
private:
Type buffer[bufferSize];
uint32 frontIdx, backIdx;
public:
inline CyclicQueue() : frontIdx(0), backIdx(0) {}
inline uint32 size() { return (bufferSize + backIdx - frontIdx) % bufferSize; }
inline bool isFull() { return (backIdx + 1) % bufferSize == frontIdx; }
inline bool isEmpty() { return frontIdx == backIdx; }
inline void pushBack(const Type& value)
{
XASSERT(!isFull(), "queue is full");
buffer[backIdx] = value;
backIdx = (backIdx + 1) % bufferSize;
}
inline Type popFront()
{
XASSERT(!isEmpty(), "queue is empty");
Type value = buffer[frontIdx];
frontIdx = (frontIdx + 1) % bufferSize;
return value;
}
inline void dropFront()
{
XASSERT(!isEmpty(), "queue is empty");
buffer[frontIdx]->~Type();
frontIdx = (frontIdx + 1) % bufferSize;
}
inline void enqueue(const Type& value) { pushBack(value); }
inline Type dequeue() { return popFront(); }
inline Type& operator [] (uint32 index) { return buffer[(frontIdx + index) % bufferSize]; }
inline Type& front() { return buffer[frontIdx % bufferSize]; }
inline Type& back() { return buffer[(backIdx - 1) % bufferSize]; }
};
} | true |
37c1bf73ca755c56a444162d7e2c7b3e6a1e49a5 | C++ | Patrickjusz/CPP | /keylogger-fud/Autorun.cpp | UTF-8 | 3,213 | 2.515625 | 3 | [] | no_license | /* TODO:
* + Dodać obsługe innego autostartu gdy nie dodano klucza do rejestru
*/
#include "Autorun.h"
Autorun::Autorun(string keyloggerFileNameIn) {
this->config = new Config();
this->keyloggerFileName = keyloggerFileNameIn;
this->newWinApix = new newWinApi();
}
bool Autorun::addAutostart() {
HKEY keyHandle;
LPCTSTR keyDir = this->config->StringToLPCTSTR(this->config->GetRegKeyDir());
LONG result = newWinApix->OtworzKluczRejestru()(HKEY_CURRENT_USER, keyDir, 0, KEY_ALL_ACCESS, &keyHandle);
if (result == ERROR_SUCCESS) {
LPCTSTR keyName = this->config->StringToLPCTSTR(this->config->GetRegKeyName()); //TU BYL ENCRYPT LPCTSTRTOSTR
LPCTSTR filePath = this->config->StringToLPCTSTR(this->config->GetRegFilePath());
LONG setRes = newWinApix->UstawWartoscKluczaRejestru()(keyHandle, keyName, 0, REG_SZ, (LPBYTE) filePath, strlen(filePath) + 1);
if (setRes == ERROR_SUCCESS) {
newWinApix->ZamknijKluczRejestru()(keyHandle);
//succes add key
return true;
} else {
//failed add key
newWinApix->ZamknijKluczRejestru()(keyHandle);
return false;
}
} else {
//error open key
}
}
bool Autorun::deleteAutostart() {
LPCTSTR keyDir = this->config->StringToLPCTSTR(this->config->GetRegKeyDir());
HKEY keyHandle;
LONG result = newWinApix->OtworzKluczRejestru()(HKEY_CURRENT_USER, keyDir, 0L, KEY_ALL_ACCESS, &keyHandle);
if (result == ERROR_SUCCESS) {
LPCTSTR keyName = this->config->StringToLPCTSTR(this->config->GetRegKeyName()); //TU BYL ENCRYPT LPCTST TO STR
long delResult = newWinApix->UsunKluczRejestru()(keyHandle, keyName);
if (delResult == ERROR_SUCCESS) {
newWinApix->ZamknijKluczRejestru()(keyHandle);
return true;
}
newWinApix->ZamknijKluczRejestru()(keyHandle);
}
return false;
}
bool Autorun::isActive() {
LPCTSTR keyDir = this->config->StringToLPCTSTR(this->config->GetRegKeyDir());
HKEY keyHandle;
LONG result = newWinApix->OtworzKluczRejestru()(HKEY_CURRENT_USER, keyDir, 0, KEY_READ, & keyHandle);
if (result == ERROR_SUCCESS) {
LPCTSTR keyName = this->config->StringToLPCTSTR(this->config->GetRegKeyName()); // encryptStringToLPCTSTR
LONG key = RegQueryValueExA(keyHandle, keyName, NULL, NULL, NULL, NULL);
if (key == ERROR_FILE_NOT_FOUND) {
newWinApix->ZamknijKluczRejestru()(keyHandle);
return false;
} else {
newWinApix->ZamknijKluczRejestru()(keyHandle);
return true;
}
}
return false;
}
bool Autorun::CopyFileAutostart() {
LPCTSTR filePath = this->config->StringToLPCTSTR(this->config->GetRegFilePath());
return newWinApix->KopiujPlik()(this->getKeyloggerFileName().c_str(), filePath, 0);
}
string Autorun::getKeyloggerFileName() {
return this->keyloggerFileName;
}
bool Autorun::isCopyFile() {
Log *log = new Log();
if (!log->fileExist(this->config->GetRegFilePath())) {
this->CopyFileAutostart();
return this->CopyFileAutostart();
} else {
return false;
}
} | true |
fbce1ec972b820551586d1a817b76f1683bcf06c | C++ | rasto2211/nanopore-read-align | /src/hmm.h | UTF-8 | 6,544 | 3.09375 | 3 | [] | no_license | #pragma once
#include <vector>
#include <cmath>
#include <memory>
#include <random>
#include <typeinfo>
#include <json/value.h>
#include "log2_num.h"
#include "gtest/gtest_prod.h"
// Transition from one state to another.
struct Transition {
int to_state_;
Log2Num prob_;
friend inline std::ostream& operator<<(std::ostream& os,
const Transition& rhs);
inline bool operator==(const Transition& rhs) const {
return (prob_ == rhs.prob_) && (to_state_ == rhs.to_state_);
}
};
inline std::ostream& operator<<(std::ostream& os, const Transition& rhs) {
os << "(" << rhs.to_state_ << ", " << rhs.prob_ << ")";
return os;
}
template <typename EmissionType>
class State {
public:
// Is this state silent?
virtual bool isSilent() const = 0;
// Emission probability for the state
virtual Log2Num prob(const EmissionType& emission) const = 0;
// These two method are used for serialization.
std::string toJsonStr() const { return toJsonValue().toStyledString(); }
virtual Json::Value toJsonValue() const = 0;
virtual bool operator==(const State<EmissionType>& state) const = 0;
};
// State with no emission. Prob method always returns 1. It's convenient.
template <typename EmissionType>
class SilentState : public State<EmissionType> {
public:
SilentState(const Json::Value& /* params */) {}
SilentState() {};
bool isSilent() const { return true; }
Log2Num prob(const EmissionType& /* emission */) const { return Log2Num(1); }
Json::Value toJsonValue() const;
bool operator==(const State<EmissionType>& state) const {
return typeid(*this) == typeid(state);
}
};
// State with Gaussian emission.
class GaussianState : public State<double> {
public:
GaussianState(const Json::Value& params) {
mu_ = params["mu"].asDouble();
sigma_ = params["sigma"].asDouble();
}
GaussianState(double mu, double sigma) : mu_(mu), sigma_(sigma) {}
bool isSilent() const { return false; }
Log2Num prob(const double& emission) const;
Json::Value toJsonValue() const;
bool operator==(const State<double>& state) const {
if (typeid(*this) != typeid(state)) return false;
const GaussianState& gaussian = dynamic_cast<const GaussianState&>(state);
return (mu_ == gaussian.mu_) && (sigma_ == gaussian.sigma_);
}
protected:
FRIEND_TEST(GaussianStateTest, GaussianStateDeserializeParamsTest);
double mu_;
double sigma_;
};
// Hidden Markov Model with silent states. It has one initial state.
// States for the HMM has to be calculated for every emissions sequence because
// that's the way it is in ONT data.
template <typename EmissionType>
class HMM {
public:
HMM() {}
// States are evaluated in ascending order by id during DP.
// Therefore we have to put restriction on transitions going
// to silent state. Let's say that we have transition x->y
// and y is silent states. Then x<y has to hold true.
// No transition can go to initial state and initial state is silent.
HMM(int initial_state,
const std::vector<std::vector<Transition>>& transitions);
// Constructs HMM from JSON.
HMM(const Json::Value& hmm_json);
// Runs Viterbi algorithm and returns sequence of states.
// @emission_seq - sequence of emissions - MinION read.
// @states - states of HMM.
std::vector<int> runViterbiReturnStateIds(
const std::vector<EmissionType>& emission_seq,
const std::vector<std::unique_ptr<State<EmissionType>>>& states) const;
// Samples from P(state_sequence|emission_sequence) and returns n sequences of
// states.
// @samples - number of samples in the result.
// @seed - seed used for random number generator.
// @states - states of HMM.
std::vector<std::vector<int>> posteriorProbSample(
int samples, int seed, const std::vector<EmissionType>& emissions,
const std::vector<std::unique_ptr<State<EmissionType>>>& states) const;
// Serializes transitions to JSON.
std::string toJsonStr() const;
private:
FRIEND_TEST(HMMTest, ComputeViterbiMatrixTest);
FRIEND_TEST(HMMTest, ForwardTrackingTest);
FRIEND_TEST(HMMTest, ComputeInvTransitions);
FRIEND_TEST(HMMTest, HMMDeserializationTest);
typedef typename std::pair<Log2Num, int> ProbStateId;
typedef typename std::vector<std::vector<ProbStateId>> ViterbiMatrix;
typedef typename std::vector<std::vector<std::vector<double>>> ForwardMatrix;
typedef typename std::vector<std::vector<std::discrete_distribution<int>>>
SamplingMatrix;
// Finds best path to @state after @steps using @prob[steps][state].
// Helper method for Viterbi algorithm.
ProbStateId bestPathTo(int state_id, const State<EmissionType>& state,
int emissions_prefix_len,
const EmissionType& last_emission,
const ViterbiMatrix& prob) const;
// Computes matrix which is used in Viterbi alorithm.
ViterbiMatrix computeViterbiMatrix(
const std::vector<EmissionType>& emissions,
const std::vector<std::unique_ptr<State<EmissionType>>>& states) const;
// Computes matrix res[i][j][k] which means:
// Sum of probabilities of all paths of form
// initial_state -> ... -> inv_transitions_[j][k] -> j
// and emitting emissions[0... i-1].
ForwardMatrix forwardTracking(
const std::vector<EmissionType>& emissions,
const std::vector<std::unique_ptr<State<EmissionType>>>& states) const;
std::vector<int> backtrackMatrix(
int last_state, int last_row,
const std::vector<std::unique_ptr<State<EmissionType>>>& states,
const std::function<int(int, int)>& nextState) const;
// Computes inverse transition.
void computeInvTransitions();
// These checks are done:
// 1) Initial state has to be silent.
// 2) No transitions can go to initial state.
// 3) Transition to silent state. Outgoing state has to have lower number.
void isValid(const std::vector<std::unique_ptr<State<EmissionType>>>& states)
const;
// This constant is used in Viterbi algorithm to denote that we cannot get
// into this state. No previous state.
const int kNoState = -1;
int initial_state_;
// Number of states including the initial state.
int num_states_;
// List of transitions from one state to another with probabilities.
// Ids of states are from 0 to transitions_.size()-1
std::vector<std::vector<Transition>> transitions_;
// Inverse transitions.
std::vector<std::vector<Transition>> inv_transitions_;
};
// Implementation of template classes.
#include "hmm.tcc"
| true |
1cfc0f811efbd9901620db4ef95964a2fe4855a6 | C++ | montanker/GamePhysics | /FinalProject/FinalProject/ParticleContact.h | UTF-8 | 693 | 2.609375 | 3 | [] | no_license | #ifndef PARTICLECONTACT_H
#define PARTICLECONTACT_H
#include "Particle.h"
const Color CONTACT_COLOR = Color(1.0f, 0.0f, 0.0f);
const float CONTACT_WIDTH = 5.0f;
class ParticleContact
{
public:
ParticleContact(){};
double calculateSeparatingVelocity();
void resolve(float duration);
void init();
void draw();
Particle* mParticle[2];
Vector3 mParticleMovement[2];
double mRestitution;
double mPenetration;
bool drawLine;
bool use;
Color color;
Vector3 mContactNormal;
protected:
//void init();
//void resolve(float duration);
//double calculateSeparatingVelocity();
private:
void resolveVelocity(float duration);
void resolveInterpenetration(float duration);
};
#endif | true |
e63b8c279ba61d05391ef38b7f06e0533cabe296 | C++ | lineCode/cpp-lazy | /include/Lz/Enumerate.hpp | UTF-8 | 4,502 | 3.6875 | 4 | [
"MIT"
] | permissive | #pragma once
#include <vector>
#include <array>
#include "detail/BasicIteratorView.hpp"
#include "detail/EnumerateIterator.hpp"
namespace lz {
template<class Iterator, class IntType>
class Enumerate final : public detail::BasicIteratorView<detail::EnumerateIterator<Iterator, IntType>> {
public:
using iterator = detail::EnumerateIterator<Iterator, IntType>;
using const_iterator = iterator;
using value_type = typename iterator::value_type;
private:
iterator _begin{};
iterator _end{};
public:
/**
* @param begin Beginning of the iterator.
* @param end Ending of the iterator.
* @param start The start of the counting index. 0 is assumed by default.
*/
Enumerate(const Iterator begin, const Iterator end, const IntType start = 0) :
_begin(start, begin),
_end(static_cast<IntType>(std::distance(begin, end)), end) {
}
Enumerate() = default;
/**
* @brief Returns the beginning of the enumerate iterator object.
* @return A random access EnumerateIterator.
*/
iterator begin() const override {
return _begin;
}
/**
* @brief Returns the ending of the enumerate object.
* @return A random access EnumerateIterator.
*/
iterator end() const override {
return _end;
}
};
/**
* @addtogroup ItFns
* @{
*/
/**
* @brief Creates an Enumerate (random access) object from two iterators. This can be useful when an index and a
* value type of a container is needed.
* @details Creates an Enumerate object. The enumerator consists of a `std::pair<IntType, value_type&>`. The
* elements of the enumerate iterator are by reference. The `std:::pair<IntType, value_type&>::first` is the
* counter index. The `std:::pair<IntType, value_type&>::second` is the element of the iterator by reference.
* Furthermore, the `operator*` of this iterator returns an std::pair by value.
* @tparam IntType The type of the iterator integer. By default, `int` is assumed. Can be any arithmetic type.
* @tparam Iterator The type of the iterator. Is automatically deduced by default.
* @param begin Beginning of the iterator.
* @param end Ending of the iterator.
* @param start The start of the counting index. 0 is assumed by default.
* @return Enumerate iterator object from [begin, end).
*/
template<class IntType = int, class Iterator>
Enumerate<Iterator, IntType> enumeraterange(const Iterator begin, const Iterator end, const IntType start = 0) {
static_assert(std::is_arithmetic<IntType>::value, "the template parameter IntType is meant for integrals only");
return Enumerate<Iterator, IntType>(begin, end, start);
}
/**
* @brief Creates an Enumerate (random access) object from an iterable. This can be useful when an index and a value
* type of a iterable is needed. If MSVC and the type is an STL iterator, pass a pointer iterator, not an actual
* iterator object.
* @details Creates an Enumerate object. The enumerator consists of a `std::pair<IntType, value_type&>`. The
* elements of the enumerate iterator are by reference. The `std:::pair<IntType, value_type&>::first` is the
* counter index. The `std:::pair<IntType, value_type&>::second` is the element of the iterator by reference.
* Furthermore, the `operator*` of this iterator returns an std::pair by value.
* @tparam IntType The type of the iterator integer. By default, `int` is assumed. Can be any arithmetic type.
* @tparam Iterable The type of the Iterable. Is automatically deduced by default.
* @param iterable An iterable, e.g. a container / object with `begin()` and `end()` methods.
* @param start The start of the counting index. 0 is assumed by default.
* @return Enumerate iterator object. One can iterate over this using `for (auto pair : lz::enumerate(..))`
*/
template<class IntType = int, class Iterable>
auto enumerate(Iterable&& iterable, const IntType start = 0) -> Enumerate<decltype(std::begin(iterable)), IntType> {
return enumeraterange(std::begin(iterable), std::end(iterable), start);
}
// End of group
/**
* @}
*/
} | true |
8c341105beacf5fa64eed1566991c11e3d6db8f7 | C++ | JakubMakaruk/UMCS | /ALGORYTMY/ALGORYTMY 2018-1/algorytm9.cpp | UTF-8 | 1,470 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int liczbaZestawowDanych;
cin >> liczbaZestawowDanych;
for(int i=0; i<liczbaZestawowDanych; i++)
{
long int koszt=0;
int element1, element2;
long int liczbaProgramow;
int pierwszaMinuta, kolejneMinuty;
cin >> liczbaProgramow >> pierwszaMinuta >> kolejneMinuty;
vector<int> czasPoczatkowy;
vector<int> czasKoncowy;
for(long int j=0; j<liczbaProgramow; j++)
{
cin >> element1 >> element2;
czasPoczatkowy.push_back(element1);
czasKoncowy.push_back(element2);
koszt = koszt + pierwszaMinuta + kolejneMinuty*(element2-element1);
}
sort(czasPoczatkowy.begin(), czasPoczatkowy.end());
sort(czasKoncowy.begin(), czasKoncowy.end());
for(int i=czasKoncowy.size()-1; i>=0; i--)
{
vector<int>::iterator roznica = upper_bound(czasPoczatkowy.begin(), czasPoczatkowy.end(), czasKoncowy[i]);
if(roznica == czasPoczatkowy.end())
continue;
int pomK = czasKoncowy[i];
if( ((*roznica-pomK)*kolejneMinuty) < pierwszaMinuta)
{
koszt = koszt - (pierwszaMinuta - ((*roznica-pomK)*kolejneMinuty));
czasPoczatkowy.erase(roznica);
}
}
cout << koszt << endl;
}
return 0;
} | true |
43136721171cacae685dbe6fe4572b4f5bf074dd | C++ | sency90/allCode | /jongmanbook/510-1.cc | UTF-8 | 2,250 | 2.953125 | 3 | [] | no_license | #include <stdio.h>
#include <algorithm>
int r[201], p[201];
using namespace std;
int gcd(int b, int l) {return (l==0)?b:gcd(l,b%l);}
//X = max(put[i]/recipe[i])라 하자. 즉 X는 비율중의 최대를 의미한다.
//우리는 모든 p[i]/r[i]가 X라는 비율보다 크거나 같도록 v[i]만큼 마법약을 추가해야 한다.
//즉, X<=Y 이면서, 모든 i에 대해 Y=(p[i]+v[i])/r[i] 를 만족하는 최소 Y를 알고 싶은 것이다. (문제의 조건에 따라 Y의 최소값은 1임을 주의하자.)
//여기서 Y를 a/b라고 하면 a/b = (p[i]+v[i])/r[i] 이고, r[i]*a/b = p[i]+v[i]가 된다.
//여기서 p[i], v[i]는 정수이므로 r[i]*a/b는 정수가 되어야 한다. 즉, b는 gcd(r[i])인 셈이다.
//그럼 이제 b를 g라고 표기하자.
//그럼 지금 우리가 v[i](추가해야하는 최소 마법약)를 구하는 것이 최종 목표인데, 아직 모르는 값 a가 하나 남아있다.
//다시 위의 식을 살펴보면, X<=Y=(a/g) 이고 a,g는 정수 이므로, g*X<=a를 만족하는 최소 정수 a를 찾으면 된다.
//이때 조심해야 할 부부은 X가 max(put[i]/recipe[i])라고 해서 X를 max(ceil(put[i]/recipe[i]))라고 생각하면 안된다.
//구간 [p[i]/r[i], ceil(p[i]/r[i]))에서 recipe[i]/g가 put[i]와 약분되는 경우가 있기 때문이다.
//따라서 g*X<=a를 만족 하는 최소 정수 a는 max(ceil(g*p[i]/r[i]))이다.
//아래의 코드에서 a는 mx라고 표기되었다.
//따라서 r[i]*a/g = p[i]+v[i]이므로 v[i]=r[i]*a/g - p[i] => v[i] = r[i]*max(ceil(g*p[i]/r[i])/g - p[i] 이다.
//여기서 올림함수(ceil)안에 있는 g와 그 함수 바깥에 있는 g를 약분해버리는 병신같은 짓거리를 해서는 안된다.
//이제 v[i]를 순서대로 출력해주기만 하면 된다.
int main() {
int t;
scanf("%d", &t);
while(t--) {
int n, mx=1;
scanf("%d", &n);
for(int i=0; i<n; i++) scanf("%d", &r[i]);
for(int i=0; i<n; i++) scanf("%d", &p[i]);
int g = r[0];
for(int i=1; i<n; i++) g = gcd(g, r[i]);
for(int i=0; i<n; i++) mx = max(mx, (g*p[i]+r[i]-1)/r[i]);
for(int i=0; i<n; i++) printf("%d ", mx*r[i]/g-p[i]);
puts("");
}
return 0;
}
| true |
6039d564f1973cdc246f148a1a9a41e910cc05fb | C++ | lil7abt/study_notes | /Cpp_Primer_Plus/CH16_STL_Code/Eg_initializer_list/ilist.cpp | UTF-8 | 348 | 3.40625 | 3 | [] | no_license | #include <iostream>
#include <initializer_list>
double sum(std::initializer_list<double> il);
double average(const std::initializer_list<double> &ril);
int main()
{
using std::cout;
cout<<"List 1: sum = "<<sum({2,3,4})
<<", ave = "<<average({2,3,4})<<'\n';
std::initializer_list<double> dl={1.1, 2.2, 3.3, 4.4, 5.5};
} | true |
04d5032b385e4757a9f8c9699263b02e849f9d19 | C++ | aconstlink/natus | /device/components/button.hpp | UTF-8 | 2,999 | 2.796875 | 3 | [
"MIT"
] | permissive |
#pragma once
#include "../component.hpp"
namespace natus
{
namespace device
{
namespace components
{
enum class button_state
{
none,
pressed,
pressing,
released,
num_keys
};
static natus::ntd::string_cref_t to_string( natus::device::components::button_state const s ) noexcept
{
using bs_t = natus::device::components::button_state ;
static natus::ntd::string_t __button_states[] = { "none", "pressed", "pressing", "released", "invalid" } ;
size_t const i = size_t( s ) >= size_t( bs_t::num_keys ) ? size_t( bs_t::num_keys ) : size_t( s ) ;
return __button_states[ i ] ;
}
class button : public input_component
{
natus_this_typedefs( button ) ;
private:
natus::device::components::button_state _bs = button_state::none ;
float_t _value = 0.0f ;
public:
button( void_t )
{
}
button( this_cref_t rhv ) noexcept : input_component( rhv )
{
_bs = rhv._bs ;
_value = rhv._value ;
}
button( this_rref_t rhv ) noexcept : input_component( ::std::move(rhv) )
{
_bs = rhv._bs ; rhv._bs = natus::device::components::button_state::none ;
_value = rhv._value ;
}
virtual ~button( void_t ) noexcept {}
public:
this_ref_t operator = ( float_t const v ) noexcept
{
_value = v ;
return *this ;
}
this_ref_t operator = ( button_state const bs ) noexcept
{
_bs = bs ;
return *this ;
}
this_ref_t operator = ( this_cref_t rhv )
{
_bs = rhv._bs ;
_value = rhv._value ;
return *this ;
}
float_t value ( void_t ) const noexcept { return _value ; }
button_state state( void_t ) const noexcept { return _bs ; }
virtual void_t update( void_t ) noexcept final
{
if( _bs == natus::device::components::button_state::pressed )
{
_bs = natus::device::components::button_state::pressing ;
}
else if( _bs == natus::device::components::button_state::released )
{
_bs = natus::device::components::button_state::none ;
}
}
};
natus_typedef( button ) ;
}
}
}
| true |
ce794d76863bb332319cbbd43107ba0aa4ebdd9d | C++ | SoilRos/dune-copasi | /dune/copasi/grid/mark_stripes.hh | UTF-8 | 2,806 | 2.75 | 3 | [] | no_license | #ifndef DUNE_COPASI_GRID_MARK_STRIPES_HH
#define DUNE_COPASI_GRID_MARK_STRIPES_HH
#include <dune/grid/uggrid.hh>
#include <list>
namespace Dune::Copasi {
/**
* @brief Mark stripes for refinement
* @details If a cube element is surrounded by non-cubes in oposite sides
* such cube is understood to be part of a stripe of cubes. In such
* case, this method should mark the grid such that a stripe is a
* stripe after refinment (e.g. refine in the direction of
* perpendicular to the non cubes)
*
* @param grid The grid
* @param[in] mark_others If true, mark non-stripe entities for refinment.
*
* @tparam dim Dimension of the grid
*/
template<int dim>
void mark_stripes(UGGrid<dim>& grid, bool mark_others = true)
{
using RuleType = typename UG_NS<dim>::RefinementRule;
auto grid_view = grid.leafGridView();
std::list<int> non_cube_side;
// Loop over the grid
for (auto&& entity : Dune::elements(grid_view))
{
if (entity.type().isCube())
{
// register side index with simplices (see DUNE cheatsheet for entity ids)
non_cube_side.clear();
for (auto&& ig : Dune::intersections(grid_view,entity))
if(ig.neighbor())
if (not ig.outside().type().isCube())
non_cube_side.push_back(ig.indexInInside());
bool is_stripe = false;
// oposite facets have consecutive indexing (e.g. [2,3] are oposite)
if (non_cube_side.size() == 2)
is_stripe = !(non_cube_side.front()/2 - non_cube_side.back()/2);
if (is_stripe)
{
// side orienation of the simplices
[[maybe_unused]] int orientation = *(non_cube_side.begin())/2;
if constexpr (dim == 2)
{
// mark entity with a blue type refinment
grid.mark(entity,RuleType::BLUE,!(bool)orientation);
}
else if constexpr (dim == 3)
{
DUNE_THROW(NotImplemented,"Stripes on 3D is not available yet!");
// Need a mesh to correctly check which orientation needs which rule!
// if (orientation == 0)
// grid.mark(entity,RuleType::HEX_BISECT_0_1);
// if (orientation == 1)
// grid.mark(entity,RuleType::HEX_BISECT_0_2);
// if (orientation == 2)
// grid.mark(entity,RuleType::HEX_BISECT_0_3);
}
else
{
DUNE_THROW(NotImplemented,
"Stripe refinement not known for grids of dimension '"
<< dim << "'");
}
}
else if (mark_others)
{
grid.mark(1,entity);
}
}
else if (mark_others)
{
grid.mark(1,entity);
}
}
}
} // namespace Dune::Copasi
#endif // DUNE_COPASI_GRID_MARK_STRIPES_HH
| true |
e0c30f64f59550a026ac1145eb670ca2acb803bd | C++ | ahbab15/Multiplug | /main.cpp | UTF-8 | 9,493 | 2.53125 | 3 | [] | no_license | #include<windows.h>
#include <GL/glut.h>
#include <stdlib.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <math.h>
static GLfloat spin = 0.0;
static float tx = 0.0;
static float ty = 0.0;
int on,off;
void DrawCircle(float cx, float cy, float rx,float ry, int num_segments)
{
glBegin(GL_TRIANGLE_FAN);
for(int i = 0; i < num_segments; i++)
{
float theta = 2.0f * 3.1416f * float(i) / float(num_segments);
float x = rx * cosf(theta);
float y = ry * sinf(theta);
glVertex2f(x + cx, y + cy);
}
glEnd();
}
void init()
{
glClearColor(0.0f,0.50f,0.5f,0.0f);
glOrtho(-100,100,-100,100,-100,100);
}
void myDisplay()
{
glClear(GL_COLOR_BUFFER_BIT);
//main frame
glColor3f(0.0f,0.0f,0.0f);
glRectf(-70,50,70,-50);
glColor3f(1.0f,1.0f,1.0f);
glRectf(-68,48,65,-45);
//button
glColor3f(0.0f, 0.5f, 0.9f);
DrawCircle(-45,25,4,9,350);
glColor3f(0.0f, 0.5f, 0.9f);
DrawCircle(-15,25,4,9,350);
glColor3f(0.0f, 0.5f, 0.9f);
DrawCircle(15,25,4,9,350);
glColor3f(0.0f, 0.5f, 0.9f);
DrawCircle(45,25,4,9,350);
//2nd frame
glColor3f(0.2f,0.25f,0.15f);
glRectf(-62,15,62,-43);
glColor3f(1.0f,1.0f,1.0f);
glRectf(-60,13,60,-41);
//switch
glColor3f(0.0f,0.0f,0.0f);
glRectf(-47,5,-44,-3);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-16,5,-13,-3);
glColor3f(0.0f,0.0f,0.0f);
glRectf(14,5,17,-3);
glColor3f(0.0f,0.0f,0.0f);
glRectf(45,5,48,-3);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-53,-14,-50,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-41,-14,-38,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-22,-14,-19,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-10,-14,-7,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(8,-14,11,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(20,-14,23,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(39,-14,42,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(51,-14,54,-22);
//separation
glColor3f(0.2f,0.25f,0.15f);
glRectf(-30,15,-28,-43);
glColor3f(0.2f,0.25f,0.15f);
glRectf(00,15,2,-43);
glColor3f(0.2f,0.25f,0.15f);
glRectf(30,15,32,-43);
glFlush();
}
void myDisplay1()
{
glClear(GL_COLOR_BUFFER_BIT);
//main frame
glColor3f(0.0f,0.0f,0.0f);
glRectf(-70,50,70,-50);
glColor3f(1.0f,1.0f,1.0f);
glRectf(-68,48,65,-45);
//button
glColor4f(1.0f, 0.0f, 0.0f, 0.0f);
DrawCircle(-45,25,4,9,350);
glColor3f(0.0f, 0.5f, 0.9f);
glColor3f(0.0f, 0.5f, 0.9f);
DrawCircle(-15,25,4,9,350);
glColor3f(0.0f, 0.5f, 0.9f);
DrawCircle(15,25,4,9,350);
glColor3f(0.0f, 0.5f, 0.9f);
DrawCircle(45,25,4,9,350);
//2nd frame
glColor3f(0.2f,0.25f,0.15f);
glRectf(-62,15,62,-43);
glColor3f(1.0f,1.0f,1.0f);
glRectf(-60,13,60,-41);
//switch
glColor3f(0.0f,0.0f,0.0f);
glRectf(-47,5,-44,-3);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-16,5,-13,-3);
glColor3f(0.0f,0.0f,0.0f);
glRectf(14,5,17,-3);
glColor3f(0.0f,0.0f,0.0f);
glRectf(45,5,48,-3);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-53,-14,-50,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-41,-14,-38,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-22,-14,-19,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-10,-14,-7,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(8,-14,11,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(20,-14,23,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(39,-14,42,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(51,-14,54,-22);
//separation
glColor3f(0.2f,0.25f,0.15f);
glRectf(-30,15,-28,-43);
glColor3f(0.2f,0.25f,0.15f);
glRectf(00,15,2,-43);
glColor3f(0.2f,0.25f,0.15f);
glRectf(30,15,32,-43);
glFlush();
}
void myDisplay2()
{
glClear(GL_COLOR_BUFFER_BIT);
//main frame
glColor3f(0.0f,0.0f,0.0f);
glRectf(-70,50,70,-50);
glColor3f(1.0f,1.0f,1.0f);
glRectf(-68,48,65,-45);
//button
glColor3f(0.0f, 0.5f, 0.9f);
DrawCircle(-45,25,4,9,350);
glColor4f(1.0f, 0.0f, 0.0f, 0.0f);
DrawCircle(-15,25,4,9,350);
glColor3f(0.0f, 0.5f, 0.9f);
DrawCircle(15,25,4,9,350);
glColor3f(0.0f, 0.5f, 0.9f);
DrawCircle(45,25,4,9,350);
//2nd frame
glColor3f(0.2f,0.25f,0.15f);
glRectf(-62,15,62,-43);
glColor3f(1.0f,1.0f,1.0f);
glRectf(-60,13,60,-41);
//switch
glColor3f(0.0f,0.0f,0.0f);
glRectf(-47,5,-44,-3);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-16,5,-13,-3);
glColor3f(0.0f,0.0f,0.0f);
glRectf(14,5,17,-3);
glColor3f(0.0f,0.0f,0.0f);
glRectf(45,5,48,-3);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-53,-14,-50,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-41,-14,-38,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-22,-14,-19,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-10,-14,-7,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(8,-14,11,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(20,-14,23,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(39,-14,42,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(51,-14,54,-22);
//separation
glColor3f(0.2f,0.25f,0.15f);
glRectf(-30,15,-28,-43);
glColor3f(0.2f,0.25f,0.15f);
glRectf(00,15,2,-43);
glColor3f(0.2f,0.25f,0.15f);
glRectf(30,15,32,-43);
glFlush();
}
void myDisplay3()
{
glClear(GL_COLOR_BUFFER_BIT);
//main frame
glColor3f(0.0f,0.0f,0.0f);
glRectf(-70,50,70,-50);
glColor3f(1.0f,1.0f,1.0f);
glRectf(-68,48,65,-45);
//button
glColor3f(0.0f, 0.5f, 0.9f);
DrawCircle(-45,25,4,9,350);
glColor3f(0.0f, 0.5f, 0.9f);
DrawCircle(-15,25,4,9,350);
glColor4f(1.0f, 0.0f, 0.0f, 0.0f);
DrawCircle(15,25,4,9,350);
glColor3f(0.0f, 0.5f, 0.9f);
DrawCircle(45,25,4,9,350);
//2nd frame
glColor3f(0.2f,0.25f,0.15f);
glRectf(-62,15,62,-43);
glColor3f(1.0f,1.0f,1.0f);
glRectf(-60,13,60,-41);
//switch
glColor3f(0.0f,0.0f,0.0f);
glRectf(-47,5,-44,-3);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-16,5,-13,-3);
glColor3f(0.0f,0.0f,0.0f);
glRectf(14,5,17,-3);
glColor3f(0.0f,0.0f,0.0f);
glRectf(45,5,48,-3);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-53,-14,-50,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-41,-14,-38,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-22,-14,-19,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-10,-14,-7,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(8,-14,11,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(20,-14,23,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(39,-14,42,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(51,-14,54,-22);
//separation
glColor3f(0.2f,0.25f,0.15f);
glRectf(-30,15,-28,-43);
glColor3f(0.2f,0.25f,0.15f);
glRectf(00,15,2,-43);
glColor3f(0.2f,0.25f,0.15f);
glRectf(30,15,32,-43);
glFlush();
}
void myDisplay4()
{
glClear(GL_COLOR_BUFFER_BIT);
//main frame
glColor3f(0.0f,0.0f,0.0f);
glRectf(-70,50,70,-50);
glColor3f(1.0f,1.0f,1.0f);
glRectf(-68,48,65,-45);
//button
glColor3f(0.0f, 0.5f, 0.9f);
DrawCircle(-45,25,4,9,350);
glColor3f(0.0f, 0.5f, 0.9f);
DrawCircle(-15,25,4,9,350);
glColor3f(0.0f, 0.5f, 0.9f);
DrawCircle(15,25,4,9,350);
glColor4f(1.0f, 0.0f, 0.0f, 0.0f);
DrawCircle(45,25,4,9,350);
//2nd frame
glColor3f(0.2f,0.25f,0.15f);
glRectf(-62,15,62,-43);
glColor3f(1.0f,1.0f,1.0f);
glRectf(-60,13,60,-41);
//switch
glColor3f(0.0f,0.0f,0.0f);
glRectf(-47,5,-44,-3);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-16,5,-13,-3);
glColor3f(0.0f,0.0f,0.0f);
glRectf(14,5,17,-3);
glColor3f(0.0f,0.0f,0.0f);
glRectf(45,5,48,-3);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-53,-14,-50,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-41,-14,-38,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-22,-14,-19,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(-10,-14,-7,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(8,-14,11,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(20,-14,23,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(39,-14,42,-22);
glColor3f(0.0f,0.0f,0.0f);
glRectf(51,-14,54,-22);
//separation
glColor3f(0.2f,0.25f,0.15f);
glRectf(-30,15,-28,-43);
glColor3f(0.2f,0.25f,0.15f);
glRectf(00,15,2,-43);
glColor3f(0.2f,0.25f,0.15f);
glRectf(30,15,32,-43);
glFlush();
}
void my_keyboard(unsigned char key, int x, int y)
{
switch (key) {
case '1':
myDisplay1();
break;
case '2':
myDisplay2();
break;
case '3':
myDisplay3();
break;
case '4':
myDisplay4();
break;
default:
break;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(1200,700);
glutInitWindowPosition(0,0);
glutCreateWindow("MultiPlug");
init();
glutDisplayFunc(myDisplay);
glutKeyboardFunc(my_keyboard);
glutMainLoop();
return 0;
}
| true |
af22dbe3028777fe7bf26e3658ca7f79c210091d | C++ | Ian-Fund/2430-GW1 | /Personnel.h | UTF-8 | 525 | 2.578125 | 3 | [] | no_license | //
// Created by mathbot on 2/1/18.
//
#ifndef GW1_PERSONNEL_H
#define GW1_PERSONNEL_H
#include <stdio.h>
#include <string>
using namespace std;
class Personnel
{
public:
Personnel(int ssn, char name, char city, int year, long salary);
Personnel();
void readFromFilePersonnel();
void size();
void readkey();
void writeToFile();
int current;
string line[10000000];
protected:
int ssn[9];
char *name;
char *city;
int year;
long salary;
};
#endif //GW1_PERSONNEL_H
| true |
e2b00fdeb1f22aab547fef4f2a92a4f59ac31f62 | C++ | arrows-1011/CPro | /AOJ/Volume05/0577.cpp | UTF-8 | 506 | 2.546875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int n,mat[200][3],point[200]={0};
cin >> n;
for(int i = 0 ; i < n ; i++)
for(int j = 0 ; j < 3 ; j++)
cin >> mat[i][j];
for(int i = 0 ; i < n ; i++){
for(int j = 0 ; j < 3 ; j++){
int cnt = 0;
for(int l = 0 ; l < n ; l++){
if(mat[i][j] != mat[l][j] && i != l) cnt++;
}
if(cnt == n-1) point[i] += mat[i][j];
}
}
for(int i = 0 ; i < n ; i++){
cout << point[i] << endl;
}
return 0;
}
| true |
32118a542a664aa801bd3efd2879ca52429d1e29 | C++ | hannesSchuerer/Pong | /Ball.cpp | UTF-8 | 3,836 | 2.703125 | 3 | [] | no_license | #include "Ball.hpp"
Ball::Ball()
{
if (!m_texture.loadFromFile("Sprites/PongBall.png"))
{
std::cerr << "Cant load player" << std::endl;
}
else
{
m_sprite.setTexture(m_texture);
}
m_sprite.setOrigin(m_sprite.getGlobalBounds().height / 2, m_sprite.getGlobalBounds().width / 2);
m_direction = sf::Vector2f(1.f, 0);
m_direction *= m_speed;
m_vectorUp = (m_random.getRandomNumber(60, 10) / 100.f)*-1;
m_vectorDown = m_random.getRandomNumber(60, 10) / 100.f;
}
Ball::~Ball()
{
}
void Ball::draw(sf::RenderWindow & target)
{
target.draw(m_sprite);
}
void Ball::setPosition(sf::Vector2f pos)
{
m_sprite.setPosition(pos);
}
void Ball::update(const float & dt, Player* playerOne, Player* playerTwo)
{
m_sprite.move(m_direction*dt);
if ((m_sprite.getPosition().y + m_sprite.getGlobalBounds().height / 2 <= 0))
{
m_sprite.setPosition(sf::Vector2f(m_sprite.getPosition().x, 2));
m_direction.y *= -1;
}
if ((m_sprite.getPosition().y + m_sprite.getGlobalBounds().height / 2 >= 800))
{
m_sprite.setPosition(sf::Vector2f(m_sprite.getPosition().x, 790));
m_direction.y *= -1;
}
if (m_sprite.getPosition().x < -100)
{
this->scorePlayerTwo++;
m_ballOut = true;
m_direction = sf::Vector2f(1400.f/2.f, 800.f/2.f)-m_sprite.getPosition();
normalizeVector(m_direction);
m_direction *= 800.f;
}
if (m_sprite.getPosition().x > 1500)
{
this->scorePlayerOne++;
m_ballOut = true;
m_direction = sf::Vector2f(1400.f / 2.f, 800.f / 2.f) - m_sprite.getPosition();
normalizeVector(m_direction);
m_direction *= 800.f;
}
if (m_sprite.getGlobalBounds().intersects(m_middle) && m_ballOut)
{
m_sprite.setPosition(sf::Vector2f(1400.f / 2.f, 800.f / 2.f));
m_time += dt;
if (m_time >= 1)
{
m_time = 0;
m_direction.x = 1.f;
m_direction.y = 0.f;
m_direction *= m_speed;
m_ballOut = false;
}
}
if (m_sprite.getGlobalBounds().intersects(playerOne->getBounds(), m_hitResult) && !m_ballOut)
{
m_relativeHit = m_hitResult.top - playerOne->getBounds().top + m_sprite.getGlobalBounds().width / 2;
if (m_relativeHit < (113.f / 5.f) * 3.f)
{
normalizeVector(m_direction);
m_direction.x = 1.f;
m_direction.y += m_vectorUp;
if (m_direction.y > m_maxVectorUp)
m_direction.y = m_maxVectorUp;
normalizeVector(m_direction);
m_direction *= m_speed;
}
else
{
normalizeVector(m_direction);
m_direction.x = 1.f;
m_direction.y += m_vectorDown;
if (m_direction.y < m_maxVectorDown)
m_direction.y = m_maxVectorDown;
normalizeVector(m_direction);
m_direction *= m_speed;
}
m_vectorUp = (m_random.getRandomNumber(60, 10) / 100.f)*-1;
m_vectorDown = m_random.getRandomNumber(60, 10) / 100.f;
}
if (m_sprite.getGlobalBounds().intersects(playerTwo->getBounds(), m_hitResult) && !m_ballOut)
{
m_relativeHit = m_hitResult.top - playerTwo->getBounds().top + m_sprite.getGlobalBounds().width / 2;
if (m_relativeHit < (113.f / 5.f) * 3.f)
{
normalizeVector(m_direction);
m_direction.x = -1.f;
m_direction.y += m_vectorUp;
if (m_direction.y > m_maxVectorUp)
m_direction.y = m_maxVectorUp;
normalizeVector(m_direction);
m_direction *= m_speed;
}
else
{
normalizeVector(m_direction);
m_direction.x = -1.f;
m_direction.y += m_vectorDown;
if (m_direction.y < m_maxVectorDown)
m_direction.y = m_maxVectorDown;
normalizeVector(m_direction);
m_direction *= m_speed;
}
m_vectorUp = (m_random.getRandomNumber(60, 10) / 100.f)*-1;
m_vectorDown = m_random.getRandomNumber(60, 10) / 100.f;
}
}
sf::FloatRect Ball::getBounds()
{
return m_sprite.getGlobalBounds();
}
void Ball::normalizeVector(sf::Vector2f & vector)
{
float length = sqrt((vector.x * vector.x) + (vector.y * vector.y));
if (length != 0)
vector = sf::Vector2f(vector.x / length, vector.y / length);
}
| true |
a5515451c2d48463fc72b4c61920a2caa4775bb4 | C++ | kevinnhuynh/CPSC441-ACNS | /ChatHistory.cpp | UTF-8 | 1,124 | 3.015625 | 3 | [] | no_license | //NOTCOMPLETED
//saving objects in files adapted from https://www.geeksforgeeks.org/readwrite-class-objects-fromto-file-c/
#include "ChatHistory.h"
#include <string>
int ChatHistory::channelIDCounter=0;
ChatHistory::ChatHistory(string access, string type):FileInfo(access,access){
this->channelType = type;
this->channelID = ++channelIDCounter;
}
ChatHistory::ChatHistory(string filename, string channelId, string channelType,list<string>accessList):FileInfo(filename,accessList){
this->channelType = channelType;
this->channelID = atoi(channelId.c_str());
}
string ChatHistory::addMessageToChat(string message){
fileptr.open (filename,fstream::in | fstream::out |fstream::app);
fileptr<<message;
fileptr.close();
return this->getFile();
}
ChatHistory::ChatHistory(const ChatHistory& rhs):FileInfo(rhs){
this->channelID = rhs.channelID;
this->channelType = rhs.channelType;
}
ChatHistory ChatHistory::operator = (const ChatHistory&src){
FileInfo::operator=(src);
this->channelID = src.channelID;
this->channelType = src.channelType;
return *this;
} | true |
7f8a1d583a91007e225aa85967b80c3ad071733e | C++ | Manav-Aggarwal/competitive-programming | /HackerRank/IsFibo.cpp | UTF-8 | 775 | 3.390625 | 3 | [] | no_license | #include <iostream>
using namespace std;
bool isFibo(unsigned long long int a);
void Caller(unsigned long long int test);
int main()
{
unsigned int noOfTestCases;
cin >> noOfTestCases;
while (noOfTestCases--)
{
unsigned long long int num = 0;
cin >> num;
Caller(num);
}
return 0;
}
bool isFibo(unsigned long long int a)
{
unsigned long long int first = 0, second = 1, next;
for (int i = 0;;i++)
{
next = first + second;
first = second;
second = next;
if (next == a)
{
return true;
}
else if(next>a)
{
return false;
}
}
}
void Caller(unsigned long long int test)
{
if (isFibo(test))
{
cout << "IsFibo" << endl;
}
else
{
cout << "IsNotFibo" << endl;
}
}
| true |
758ae0955a5ff88412a79735d55e02fae919155c | C++ | rathoresrikant/interviewbit | /Linked Lists/list_cycle.cpp | UTF-8 | 1,014 | 3.65625 | 4 | [] | no_license | /*
List Cycle
Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Try solving it using constant additional space. Example :
Input :
______
| |
\/ |
1 -> 2 -> 3 -> 4
Return the node corresponding to node 3.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* Solution::detectCycle(ListNode* A) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
ListNode *temp = A;
unordered_map <ListNode *, int> mp;
while(temp != NULL)
{
if(mp[temp] != 0)
return temp;
mp[temp] = 1;
temp = temp->next;
}
return NULL;
}
| true |
014322b33960a6d4bef0f537000b3aab3bbe3b92 | C++ | pulcherriman/Programming_Contest | /AtCoder/ABC/000-099/ABC082/abc082_a.cpp | UTF-8 | 239 | 2.671875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
constexpr int lcm(int a,int b){return b?lcm(b,a%b):a;}
constexpr int gcd(int a,int b){return a*b/lcm(a,b);}
int main(void){
float a,b;
cin>>a>>b;
cout<<(int)ceil((a+b)/2)<<endl;
} | true |
a568eeaf8b7ea0be8174bb2304b1e4df7d631e6c | C++ | josephjaspers/ARCHIVED-BlackCat_NeuralNetworks-Version-2 | /Include/BlackCatTensors_dependencies/Scalar.h | UTF-8 | 4,615 | 2.890625 | 3 | [] | no_license | /*
* Scalar.h
*
* Created on: Aug 15, 2017
* Author: joseph
*/
#ifndef SCALAR_H_
#define SCALAR_H_
#include "LinearAlgebraRoutines.h"
#include "BC_MathematicsDeviceController.h"
#include <iostream>
template <typename number_type, typename TensorOperations = CPU>
class Scalar {
template <typename t, typename t2>
friend class Tensor;
protected:
//protected constructors
bool ownership = true;
number_type* scalar;
//Index Tensor
public:
Scalar<number_type, TensorOperations>(const Scalar& s);
Scalar<number_type, TensorOperations>(Scalar&& s);
Scalar<number_type, TensorOperations>(number_type);
Scalar<number_type, TensorOperations>() {scalar = new number_type; }
virtual Scalar<number_type, TensorOperations>& operator = (const Scalar<number_type, TensorOperations>& s);
virtual Scalar<number_type, TensorOperations>& operator = (number_type s);
virtual Scalar<number_type, TensorOperations>& operator = (Scalar<number_type, TensorOperations>&& s);
virtual ~Scalar<number_type, TensorOperations>() {
//if (ownership) Tensor_Operations<number_type>::destruction(scalar); }
}
//Access data
virtual const number_type& operator () () const {return this->scalar[0];};
virtual number_type& operator () () { return this->scalar[0];};
//Mathematics operators (By scalar)
Scalar<number_type, TensorOperations> operator^(const Scalar<number_type, TensorOperations>& t) const;
Scalar<number_type, TensorOperations> operator/(const Scalar<number_type, TensorOperations>& t) const;
Scalar<number_type, TensorOperations> operator+(const Scalar<number_type, TensorOperations>& t) const;
Scalar<number_type, TensorOperations> operator-(const Scalar<number_type, TensorOperations>& t) const;
Scalar<number_type, TensorOperations> operator&(const Scalar<number_type, TensorOperations>& t) const;
virtual Scalar<number_type, TensorOperations>& operator^=(const Scalar<number_type, TensorOperations>& t);
virtual Scalar<number_type, TensorOperations>& operator/=(const Scalar<number_type, TensorOperations>& t);
virtual Scalar<number_type, TensorOperations>& operator+=(const Scalar<number_type, TensorOperations>& t);
virtual Scalar<number_type, TensorOperations>& operator-=(const Scalar<number_type, TensorOperations>& t);
virtual Scalar<number_type, TensorOperations>& operator&=(const Scalar<number_type, TensorOperations>& t);
void print() const { std::cout << "[" << *scalar << "]"<< std::endl;};
void printDimensions() const { std::cout << "[1]" << std::endl; };
number_type* data() { return scalar; }
const number_type* data() const { return scalar; }
};
//
//template<typename number_type, typename ParentTensor>
//class ID_Scalar : public Scalar<number_type, TensorOperations> {
//
//
//
// const ParentTensor* parent;
//public:
//
// ID_Scalar<number_type, ParentTensor>(const ParentTensor& mother, number_type* val) {
// this->ownership = false;
// this->scalar = val;
// parent = &mother;
// }
// ~ID_Scalar<number_type,ParentTensor>() {
// parent = nullptr;
// this->scalar = nullptr;
// this->ownership = false;
// }
//
// number_type& operator () () { parent->alertUpdate(); return this->scalar[0];};
// Scalar<number_type, TensorOperations>& operator = (const Scalar<number_type, TensorOperations>& s) {
// parent->alertUpdate();
// return this->Scalar<number_type, TensorOperations>::operator=(s);
// }
//
//
// Scalar<number_type, TensorOperations>& operator = (number_type s) {
// parent->alertUpdate();
// return this->Scalar<number_type, TensorOperations>::operator=(s);
// }
// Scalar<number_type, TensorOperations>& operator = (Scalar<number_type, TensorOperations>&& s) {
// parent->alertUpdate();
// return this->Scalar<number_type, TensorOperations>::operator=(s);
// }
// Scalar<number_type, TensorOperations>& operator^=(const Scalar<number_type, TensorOperations>& t) {
// parent->alertUpdate();
// return this->operator^=(t);
// }
// Scalar<number_type, TensorOperations>& operator/=(const Scalar<number_type, TensorOperations>& t) {
// parent->alertUpdate();
// return this->operator/=(t);
// }
// Scalar<number_type, TensorOperations>& operator+=(const Scalar<number_type, TensorOperations>& t) {
// parent->alertUpdate();
// return this->operator+=(t);
// }
// Scalar<number_type, TensorOperations>& operator-=(const Scalar<number_type, TensorOperations>& t) {
// parent->alertUpdate();
// return this->operator-=(t);
// }
// Scalar<number_type, TensorOperations>& operator&=(const Scalar<number_type, TensorOperations>& t) {
// parent->alertUpdate();
// return this->operator&=(t);
// }
//};
#endif /* SCALAR_H_ */
| true |
0f7ba1dc868162ce34399d60ae4d01ec5517a494 | C++ | bradley27783/TheCivilWarOfMalibu | /Game/read.cpp | UTF-8 | 4,061 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
#include "libsqlite.hpp"
void read::military_Units(){
string sqliteFile = "civilwarofMalibu.db";
try{
sqlite::sqlite db( sqliteFile );
auto cur = db.get_statement();
cur->set_sql( "SELECT * FROM military_Units "); //If you want to see other table replace military_Units with production_Units
cur->prepare();
cout << "ID " << " Name " << " Atk " << "Def " << "Cost" << endl;
while(cur->step()){
int ID = cur->get_int(0);
string Name = cur->get_text(1);
int Attack = cur->get_int(2);
int Defence = cur->get_int(3);
int Cost = cur->get_int(4);
cout << ID << " " << Name << " " << Attack << " " << Defence << " " << Cost << endl;
}
}
catch( sqlite::exception e){
std::cerr << e.what() << endl;
}
}
void read::production_Units(){
string sqliteFile = "civilwarofMalibu.db";
try{
sqlite::sqlite db( sqliteFile );
auto cur = db.get_statement();
cur->set_sql( "SELECT * FROM production_Units "); //If you want to see other table replace military_Units with production_Units
cur->prepare();
cout << "ID " << " Name " << " Income " << "Cost" << endl;
while(cur->step()){
int ID = cur->get_int(0);
string Name = cur->get_text(1);
int Income = cur->get_int(2);
int Cost = cur->get_int(3);
cout << ID << " " << Name << " " << Income << " " << Cost << endl;
}
}
catch( sqlite::exception e){
std::cerr << e.what() << endl;
}
}
void read::map(){
string sqliteFile = "civilwarofMalibu.db";
try{
sqlite::sqlite db( sqliteFile );
auto cur = db.get_statement();
cur->set_sql( "SELECT * FROM Map "); //If you want to see other table replace military_Units with production_Units
cur->prepare();
cout << "ID " << " Name " << " Owned? " << endl;
while(cur->step()){
int ID = cur->get_int(0);
string Name = cur->get_text(1);
string Owned = cur->get_text(2);
cout << ID << " " << Name << " " << Owned << endl;
}
}
catch( sqlite::exception e){
std::cerr << e.what() << endl;
}
}
void read::saves(){
string sqliteFile = "civilwarofMalibu.db";
try{
sqlite::sqlite db( sqliteFile );
auto cur = db.get_statement();
cur->set_sql( "SELECT * FROM Saves ");
cur->prepare();
while(cur->step()){
string Name = cur->get_text(0);
int Atk1 = cur->get_int(1);
int Def1 = cur->get_int(2);
int Atk2 = cur->get_int(3);
int Def2 = cur->get_int(4);
string Territories = cur->get_text(5);
cout << Name << " " << Atk1 << " " << Def1 << " " << Atk2 << " " << Def2 << " " << Territories << endl;
}
}
catch( sqlite::exception e){
std::cerr << e.what() << endl;
}
}
int read::read(){
int user_Input;
while(user_Input == 1||2||3||4||5){
cout << "What file would you like to read? " << endl;
cout << "1: Military Units " << "2: Production Units " << "3: Map " << "4: Saves " << "5: Cancel" << endl;
cout << "Enter here: ";
cin >> user_Input;
if(user_Input == 1){
military_Units();
}
else if(user_Input==2){
production_Units();
}
else if(user_Input==3){
map();
}
else if(user_Input==4){
saves();
}
else if(user_Input==5){
break;
}
else{
cout << "Please enter a valid number!" << endl;
cout << "" << endl;
break;
}
}
}
int main(){
read();
return 0;
} | true |
113e378878287cad99636ef64c1faa3490385d8b | C++ | takaakit/design-pattern-examples-in-cpp | /structural_patterns/proxy/ProxyPrinter.h | UTF-8 | 944 | 2.625 | 3 | [
"CC0-1.0"
] | permissive | // ˅
// ˄
#ifndef STRUCTURAL_PATTERNS_PROXY_PROXYPRINTER_H_
#define STRUCTURAL_PATTERNS_PROXY_PROXYPRINTER_H_
// ˅
#include <string>
#include "structural_patterns/proxy/Printer.h"
class RealPrinter;
using namespace std;
// ˄
// ProxyPrinter forwards requests to RealPrinter when appropriate.
class ProxyPrinter : public Printer
{
// ˅
// ˄
private:
string current_name;
// A printer that actually prints
RealPrinter* real;
public:
ProxyPrinter(const string& name);
~ProxyPrinter();
const string getName() const;
void changeName(const string& name);
void output(const string& content);
// ˅
public:
protected:
private:
ProxyPrinter(const ProxyPrinter&) = delete;
ProxyPrinter& operator=(const ProxyPrinter&) = delete;
ProxyPrinter(ProxyPrinter&&) = delete;
ProxyPrinter& operator=(ProxyPrinter&&) = delete;
// ˄
};
// ˅
// ˄
#endif // STRUCTURAL_PATTERNS_PROXY_PROXYPRINTER_H_
// ˅
// ˄
| true |
eebbef7e584c479d35919921c09593a26e8d4214 | C++ | NutBandera/MagicTGB | /MagicTGB/Tile.h | UTF-8 | 263 | 2.671875 | 3 | [] | no_license | #pragma once
#include "Actor.h"
class Tile : public Actor
{
public:
Tile(string filename, float x, float y, Game* game);
Tile(string filename, float x, float y, int lifeSeconds, Game* game);
int lifeSeconds = 0;
int getLifeSeconds();
void reduceLife();
};
| true |
95073d910d9190be3d5e3c74bc6fc7b3f0088ecb | C++ | asarium/imageloader | /test/src/util.cpp | UTF-8 | 2,273 | 3 | 3 | [
"MIT"
] | permissive |
#include "util.h"
#include <cstdio>
namespace
{
void* IMGLOAD_CALLBACK mem_realloc(void* ud, void* mem, size_t size)
{
return realloc(mem, size);
}
void IMGLOAD_CALLBACK mem_free(void* ud, void* mem)
{
free(mem);
}
size_t IMGLOAD_CALLBACK std_read(void* ud, uint8_t* buf, size_t size)
{
return std::fread(buf, 1, size, static_cast<FILE*>(ud));
}
int64_t IMGLOAD_CALLBACK std_seek(void* ud, int64_t offset, int whence)
{
std::fseek(static_cast<FILE*>(ud), static_cast<long>(offset), whence);
return static_cast<int64_t>(std::ftell(static_cast<FILE*>(ud)));
}
ImgloadErrorCode IMGLOAD_CALLBACK logger(void* ud, ImgloadLogLevel level, const char* text)
{
switch(level)
{
case IMGLOAD_LOG_DEBUG:
std::cout << "DEBG: ";
break;
case IMGLOAD_LOG_INFO:
std::cout << "INFO: ";
break;
case IMGLOAD_LOG_WARNING:
std::cout << "WARN: ";
break;
case IMGLOAD_LOG_ERROR:
std::cout << " ERR: ";
break;
}
std::cout << text;
return IMGLOAD_ERR_NO_ERROR;
}
}
namespace util
{
ContextFixture::ContextFixture() : ctx(nullptr)
{
}
void ContextFixture::SetUp()
{
makeContext(0);
}
void ContextFixture::TearDown()
{
if (ctx != nullptr)
{
imgload_context_free(ctx);
ctx = nullptr;
}
}
ImgloadIO get_std_io()
{
ImgloadIO io;
io.read = std_read;
io.seek = std_seek;
return io;
}
void ContextFixture::makeContext(ImgloadContextFlags flags)
{
if (ctx != nullptr)
{
imgload_context_free(ctx);
ctx = nullptr;
}
ImgloadMemoryAllocator allocator;
allocator.realloc = mem_realloc;
allocator.free = mem_free;
auto err = imgload_context_init(&ctx, flags, &allocator, nullptr);
if (err != IMGLOAD_ERR_NO_ERROR)
{
ctx = nullptr;
FAIL() << "Failed to allocate imgload context!";
}
imgload_context_set_log_callback(ctx, logger, nullptr);
}
}
| true |
a870abfb164423fa0bf3a4f00405bd8f8d147aff | C++ | eVillain/StruggleBox | /StruggleBox/Engine/Rendering/TextAtlasCache.cpp | UTF-8 | 987 | 2.828125 | 3 | [] | no_license | #include "TextAtlasCache.h"
#include "TextAtlas.h"
#include "Log.h"
const TextAtlasID TextAtlasCache::NO_ATLAS_ID = 0;
TextAtlasCache::TextAtlasCache()
: m_nextTextAtlasID(1)
{
}
TextAtlasID TextAtlasCache::addTextAtlas(TextAtlas* texture, const std::string& name)
{
const TextAtlasID prevID = getTextAtlasID(name);
if (prevID != NO_ATLAS_ID)
{
Log::Warn("Text atlas with name %s already cached!", name.c_str());
return NO_ATLAS_ID;
}
const TextAtlasID atlasID = m_nextTextAtlasID;
m_nextTextAtlasID++;
m_atlases[atlasID] = texture;
m_atlasNames[name] = atlasID;
return atlasID;
}
TextAtlasID TextAtlasCache::getTextAtlasID(const std::string& name)
{
const auto it = m_atlasNames.find(name);
if (it != m_atlasNames.end())
{
return it->second;
}
return NO_ATLAS_ID;
}
TextAtlas* TextAtlasCache::getTextAtlasByID(const TextAtlasID textureID)
{
const auto it = m_atlases.find(textureID);
if (it != m_atlases.end())
{
return it->second;
}
return nullptr;
}
| true |
793b7fe8fe408ce035cf47d6c3cd87384b38d8ad | C++ | sawfly/straustrup | /src/4.3.cpp | UTF-8 | 1,374 | 3.53125 | 4 | [] | no_license | #include <iostream>
int main() {
enum E1 {first};
enum E2 {second, third, fourth, fifth, sixth, sevens, eights, ninth, tenth};
std::cout << "Size of bool: " << "\t\t\t" << sizeof(bool) << '.' << '\n';
std::cout << "Size of char: " << "\t\t\t" << sizeof(char) << '.' << '\n';
std::cout << "Size of wchar_t: " << "\t\t" << sizeof(wchar_t) << '.' << '\n';
std::cout << "Size of short int: " << "\t\t" << sizeof(short int) << '.' << '\n';
std::cout << "Size of int: " << "\t\t\t" << sizeof(int) << '.' << '\n';
std::cout << "Size of long int: " << "\t\t" << sizeof(long int) << '.' << '\n';
std::cout << "Size of float: " << "\t\t\t" << sizeof(float) << '.' << '\n';
std::cout << "Size of double: " << "\t\t" << sizeof(double) << '.' << '\n';
std::cout << "Size of long double: " << "\t" << sizeof(long double) << '.' << '\n';
std::cout << "Size of enum E1: " << "\t\t" << sizeof(E1) << '.' << '\n';
std::cout << "Size of enum E2: " << "\t\t" << sizeof(E2) << '.' << '\n';
std::cout << "Size of string: " << "\t\t" << sizeof(std::string) << '.' << '\n';
std::cout << "Size of char*: " << "\t\t\t" << sizeof(char*) << '.' << '\n';
std::cout << "Size of bool*: " << "\t\t\t" << sizeof(bool*) << '.' << '\n';
std::cout << "Size of long double*: " << "\t" << sizeof(long double*) << '.' << '\n';
return 0;
} | true |
184e74597ea343e866aa2252d170a0a8ff41e142 | C++ | snoplus/snogoggles | /src/Frames/Frames2d/Projections/ProjectionBase.hh | UTF-8 | 2,325 | 2.59375 | 3 | [] | no_license | ////////////////////////////////////////////////////////////////////////
/// \class Viewer::Frames::ProjectionBase
///
/// \brief Base frame for projections
///
/// \author Phil Jones <p.g.jones@qmul.ac.uk>
///
/// REVISION HISTORY:\n
/// 21/02/12 : P.Jones - First Revision, new file. \n
///
/// \detail All projection frame classes should just override the
/// project function, which converts a 3d point into a 2d point.
/// The project function is pure virtual and hence this is an
/// abstract class
///
////////////////////////////////////////////////////////////////////////
#ifndef __Viewer_Frames_ProjectionBase__
#define __Viewer_Frames_ProjectionBase__
#include <SFML/System/Vector2.hpp>
#include <SFML/System/Vector3.hpp>
#include <Viewer/Frame2d.hh>
namespace Viewer
{
class ProjectionImage;
namespace Frames
{
class ProjectionBase : public Frame2d
{
public:
ProjectionBase( RectPtr rect ) : Frame2d( rect ) { }
virtual ~ProjectionBase();
void Initialise( const sf::Rect<double>& size );
/// Initialise without using the DataStore
virtual void PreInitialise( const ConfigurationTable* configTable );
/// Initilaise with DataStore access
virtual void PostInitialise( const ConfigurationTable* configTable );
/// Save the configuration
void SaveConfiguration( ConfigurationTable* configTable ) { };
virtual void EventLoop();
virtual std::string GetName() = 0;
virtual void ProcessEvent( const RenderState& renderState );
virtual void ProcessRun();
virtual void Render2d( RWWrapper& renderApp,
const RenderState& renderState );
void Render3d( RWWrapper& renderApp,
const RenderState& renderState ) { }
//EFrameType GetFrameType() { return eUtil; }
virtual void DrawOutline() { };
protected:
void ProjectGeodesicLine( sf::Vector3<double> v1,
sf::Vector3<double> v2 );
void DrawHits( const RenderState& renderState );
void DrawGeodesic();
void DrawAllPMTs();
virtual sf::Vector2<double> Project( sf::Vector3<double> pmtPos ) = 0;
std::vector< sf::Vector2<double> > fProjectedPMTs; /// < Vector of projected pmt positions
std::vector< sf::Vector2<double> > fProjectedGeodesic; /// < Vecotr of projected geodesic positions
ProjectionImage* fImage;
};
} // ::Frames
} // ::Viewer
#endif
| true |
5dfb1d8c02964b7d5d5685719995f4908e642bb0 | C++ | Sriram4361/MRND_Summer_Team2 | /SummerCourseDay1/SummerCourseDay1/stringCompress.cpp | UTF-8 | 620 | 2.890625 | 3 | [] | no_license | #include"stringCompress.h"
void stringCompression()
{
char* str = (char *)calloc(sizeof(char),100);
printf("enter the string:\n");
scanf_s("%s", str,100);
int ind1 = 0, ind2 = 0, count = 1;
while (str[ind2+1] != '\0')
{
if (str[ind2] == str[ind2+1])
{
count++;
}
else if (count > 1)
{
str[ind1] = str[ind2];
ind1++;
str[ind1] = count+48;
ind1++;
count = 1;
}
else
{
str[ind1] = str[ind2];
ind1++;
}
ind2++;
}
if (count != 1)
{
str[ind1] = str[ind2 - 1];
ind1++;
str[ind1] = count+48;
}
else
str[ind1] = str[ind2];
str[++ind1] = '\0';
printf("%s", str);
} | true |
a690ed0174dc790fef13823d3bacf37026e54463 | C++ | Zend0r-ai/BattleCity | /app/inc/booster.h | UTF-8 | 742 | 2.515625 | 3 | [] | no_license | #pragma once
#include "Framework.h"
#include "player.h"
#include "displayableObject.h"
class Booster : public DisplayableObject {
public:
Booster(int posX, int posY) : DisplayableObject(ModelType::EXTRA_LIFE, posX, posY) {
sprite_ = createSprite("../../app/resources/ExtraLife.TGA");
isVisible_ = false;
setCollisionModel();
}
void ifBorderCollisionDetected() override;
void move(FRKey direction, int frame) override;
void ifCollisionDetected(DisplayableObject *obj) override;
void hitObject() override;
void setPosition(int posX, int posY) {
this->collisionModel.x = posX;
this->collisionModel.y = posY;
}
~Booster() {
destroySprite(sprite_);
}
};
| true |
c1beeba993c64d90678ff65edaa7782f087c1502 | C++ | daniel-perry/rt | /src/gl/TInstance.cc | UTF-8 | 2,195 | 3.0625 | 3 | [
"MIT"
] | permissive | /* Daniel Perry
* for cs6620 - spring 2005
* started 4 April 2005
*/
/* TInstance - transformed instance class
*
*/
#include "TInstance.h"
#include "hpoint.h"
#include "Material.h"
#include "matrix.h"
TInstance::TInstance( Primitive * o , Material * mat , const matrix & m )
:original(o),
transform_matrix(m),
material(mat)
{
inverse_transform_matrix = transform_matrix.inverse();
}
bool TInstance::intersect( HitRecord & hit , const RenderContext & context, const ray & r ) const {
Point newOrigin = transform_point_inverse(r.origin());
Vector newDirection = transform_vector_inverse( r.direction() );
newDirection.MakeUnitVector();
ray trans_r( newOrigin , newDirection );
if( original->intersect( hit , context , trans_r ) ){
Vector hit_p = trans_r.eval(hit.t);
hit.setPoint(transform_point( hit_p ));
Vector norm = original->normal( hit_p );
norm = transform_normal( norm );
norm.MakeUnitVector();
hit.prim = this;
hit.material = material;
hit.normal = norm;
return true;
}
return false;
}
vector3d TInstance::normal( const vector3d & p ) const{
return Normal;
}
Vector TInstance::transform_point( const Vector & p ) const {
hpoint pt( p , 1 );
pt = transform_matrix * pt;
return Vector( pt.x() , pt.y() , pt.z() );
}
Vector TInstance::transform_vector( const Vector & v ) const {
hpoint pt( v , 0 );
pt = transform_matrix * pt;
return Vector( pt.x() , pt.y() , pt.z() );
}
Vector TInstance::transform_normal( const Vector & n ) const {
hpoint pt( n , 0 );
pt = inverse_transform_matrix.transpose() * pt;
return Vector( pt.x() , pt.y() , pt.z() );
}
Vector TInstance::transform_point_inverse( const Vector & p ) const {
hpoint pt( p , 1 );
pt = inverse_transform_matrix * pt;
return Vector( pt.x() , pt.y() , pt.z() );
}
Vector TInstance::transform_vector_inverse( const Vector & v ) const {
hpoint pt( v , 0 );
pt = inverse_transform_matrix * pt;
return Vector( pt.x() , pt.y() , pt.z() );
}
Vector TInstance::transform_normal_inverse( const Vector & n ) const {
hpoint pt( n , 0 );
pt = transform_matrix.transpose() * pt;
return Vector( pt.x() , pt.y() , pt.z() );
}
| true |
b49ba4ff33eb3729809928eb84133519a6108c29 | C++ | Keepen/DP | /dp2.cpp | UTF-8 | 2,098 | 4.125 | 4 | [] | no_license | //问题描述:
// 在一个数组中,给定一个目标数字S,求在该数组中能否找到几个数的和刚好等于目标数字
// 能:true;不能:false
//思路:
// 还是要与不要的原则
// 如果要当前数字 :就看前i - 1个数字能否拼成 S - v[i]
// 如果不要当前数字:就看前 i - 1个数字能否拼成 S
#include <iostream>
#include <vector>
using namespace std;
//递归版本
bool isOK(vector<int>& v, int i, int s){
if(s == 0){
return true;
}
else if(i == 0){
return v[0] == s;
}
else if (v[i] > s){
return isOK(v, i - 1, s);
}
else{
//要当前数字
bool a = isOK(v, i - 1, s - v[i]);
//不要当前数字
bool b = isOK(v, i - 1, s);
return a || b;
}
}
//非递归版本
//利用二维数组:v.size() * s --- v.size()行,s列的数组
// ret[i][j]表示,前i个数字能否拼成和为数字j
bool unrec_isOK(vector<int>& v, int s){
vector<vector<bool>> ret(v.size(), vector<bool>(s + 1, false));
ret[0][v[0]] = true; //初始化了第一行的值
for(int i = 1;i < v.size();++i){
for(int j = 0;j <= s;++j){
if(j == 0){
ret[i][j] = true;
}
//如果出现比目标数字大的就不要选
if(v[i] > j){
ret[i][j] = ret[i - 1][j];
}
//等于目标数字就是true
else if(v[i] == j){
ret[i][j] = true;
}
else{
// 选 不选
ret[i][j] = ret[i - 1][j - v[i]] || ret[i - 1][j];
}
}
}
return ret[v.size() - 1][s];
}
void solu(){
vector<int> v = {3,34,4,12,5,2};
int s = 9;
while(cin >> s){
//bool key = isOK(v, v.size() - 1, s);
bool key = unrec_isOK(v, s);
if(key){
cout << "true" << endl;
}
else{
cout << "false" << endl;
}
}
}
int main(){
solu();
return 0;
} | true |
9631b6ad80f9ab7afecf2ee7a55d45f2517fc998 | C++ | teri-leblanc/LoadedDiceGame | /RollTheDice/Die.h | UTF-8 | 692 | 3.015625 | 3 | [] | no_license | /*
* File: Die.h
* Author: Terianne Bolding
*
* Created on November 20, 2015, 11:28 AM
*/
#ifndef DIE_H
#define DIE_H
#include <cstdlib>
#include <string>
#include <vector>
class Die {
public:
Die();
Die(std::string _identifier, int _numberSides);
Die(const Die& orig);
int GetNumberSides() const; // Getter for numberSides - this initial value should never change
virtual ~Die();
int Roll() const;
virtual void CalculateDieProbabilites();
std::string identifier; // Name of the die
std::vector<double> DieSides; // Array to hold weight of each side of the die
private:
int numberSides;
};
#endif /* DIE_H */
| true |
9acfa9bfcba3dd9f38a95b251a0606eb83e621e5 | C++ | H3r3zy/nanotekspice | /Src/Component/Component/OrGate.cpp | UTF-8 | 988 | 2.578125 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2018
** cpp_nanotekspice
** File description:
** Created by sahel.lucas-saoudi@epitech.eu,
*/
#include "OrGate.hpp"
nts::OrGate::OrGate(nts::OrGate const &data)
{
_pin_number = data._pin_number;
_pinsArgument = data._pinsArgument;
_pins = data._pins;
_res = data._res;
}
nts::OrGate& nts::OrGate::operator=(nts::OrGate const &data)
{
_pin_number = data._pin_number;
_pinsArgument = data._pinsArgument;
_pins = data._pins;
_res = data._res;
return *this;
}
nts::Tristate nts::OrGate::compute(size_t pin)
{
if (pin == 3) {
nts::Tristate value1 = getPins(1);
nts::Tristate value2 = getPins(2);
if (ISFALSE(value1) && ISFALSE(value2)) {
_res = nts::FALSE;
} else if (ISTRUE(value1) || ISTRUE(value2)) {
_res = nts::TRUE;
} else {
_res = nts::UNDEFINED;
}
} else {
return getPins(pin);
}
return _res;
}
void nts::OrGate::dump() const
{
std::cout << "Or Gate" << std::endl;
}
nts::OrGate *nts::OrGate::copy() const
{
return new nts::OrGate(*this);
} | true |
a81d997578339831ce0d233d10b379059c3aad7d | C++ | hovatterz/Ludum-Dare-28 | /src/movement_system.cpp | UTF-8 | 3,221 | 2.671875 | 3 | [] | no_license | #include <map>
#include "events.h"
#include "faction_member.h"
#include "health.h"
#include "rng.h"
#include "spatial.h"
#include "turn_taker.h"
#include "movement_system.h"
struct Direction {
int x, y;
Direction() : x(0), y(0) {}
Direction(int x, int y) : x(x), y(y) {}
};
static std::map<Action, Direction> move_directions;
MovementSystem::MovementSystem() {
move_directions[kActionMoveNorth] = Direction(0, -1);
move_directions[kActionMoveSouth] = Direction(0, 1);
move_directions[kActionMoveWest] = Direction(-1, 0);
move_directions[kActionMoveEast] = Direction(1, 0);
move_directions[kActionMoveNorthwest] = Direction(-1, -1);
move_directions[kActionMoveNortheast] = Direction(1, -1);
move_directions[kActionMoveSouthwest] = Direction(-1, 1);
move_directions[kActionMoveSoutheast] = Direction(1, 1);
}
void MovementSystem::update(entityx::ptr<entityx::EntityManager> entities,
entityx::ptr<entityx::EventManager> events,
double delta) {
for (auto entity : entities->entities_with_components<TurnTaker, Spatial>()) {
if (entity.valid() == false) { continue; }
auto turn_taker = entity.component<TurnTaker>();
Action action = turn_taker->action();
if (action != kActionMoveNorth &&
action != kActionMoveWest &&
action != kActionMoveSouth &&
action != kActionMoveEast &&
action != kActionMoveNorthwest &&
action != kActionMoveNortheast &&
action != kActionMoveSouthwest &&
action != kActionMoveSoutheast) {
// This entity is not schedulde to move. Skip it.
continue;
}
auto direction_iter = move_directions.find(turn_taker->action());
if (direction_iter == move_directions.end()) {
// Invalid direction. Skip it.
turn_taker->set_action(kActionNone);
continue;
}
auto spatial = entity.component<Spatial>();
int new_x = spatial->x() + direction_iter->second.x;
int new_y = spatial->y() + direction_iter->second.y;
bool attacked_something = false;
for (auto other : entities->entities_with_components<Health, Spatial>()) {
if (other.valid() == false) { continue; }
// This is out of scope of movement. Should be refactored probably
auto other_spatial = other.component<Spatial>();
if (other_spatial->x() == new_x && other_spatial->y() == new_y) {
auto faction_member = entity.component<FactionMember>();
auto other_faction_member = other.component<FactionMember>();
if (faction_member != nullptr && other_faction_member != nullptr &&
faction_member->faction() != other_faction_member->faction()) {
auto other_health = other.component<Health>();
int damage = Dice(1, 8).roll();
other_health->offset(-damage);
events->emit<AttackEvent>(&entity, &other, damage);
if (other_health->dead() == true) {
events->emit<DeathEvent>(&other);
other.destroy();
}
attacked_something = true;
}
}
}
turn_taker->set_action(kActionNone);
if (attacked_something == true) { continue; }
spatial->set_position(new_x, new_y);
}
}
| true |
59d05eef8c683572c194eba16d2958819cf15cf4 | C++ | paulohbmatias/ICG | /Trabalho Individual/mygl.h | UTF-8 | 8,269 | 3.515625 | 4 | [] | no_license | #ifndef _MYGL_H_
#define _MYGL_H_
#include "definitions.h"
#include <math.h>
//*****************************************************************************
// Defina aqui as suas funções gráficas
//*****************************************************************************
class cor //Classe com as componentes RGBA da cor
{
public:
double r, g, b, a;
cor(double r, double g, double b, double a){
this->r=r;
this->g=g;
this->b=b;
this->a=a;
}
};
class coordenada //Classe que contém as coordenadas X e Y de um ponto
{
public:
double x, y;
coordenada(double x, double y){
this->x = x;
this->y = y;
}
};
//Imprimir um pixel na tela na posição x, y e em uma cor c
void PutPixel(int x, int y, cor c){
FBptr[4*x + 4*y*IMAGE_WIDTH+0]=c.r;
FBptr[4*x + 4*y*IMAGE_WIDTH+1]=c.g;
FBptr[4*x + 4*y*IMAGE_WIDTH+2]=c.b;
FBptr[4*x + 4*y*IMAGE_WIDTH+3]=c.a;
}
double getX(int octante, double x, double y){ //Retorna o valor de x de acordo com o octante em que a linha se encontra
if(octante == 2 || octante == 7){
return y;
}
else if(octante == 3 || octante == 6){
return -y;
}
else if(octante == 4 || octante == 5){
return -x;
}
else{
return x;
}
}
double getY(int octante, double x, double y){ //Retorna o valor de y de acordo com o octante em que a linha se encontra
if(octante == 2 || octante == 3){
return x;
}
else if(octante == 5 || octante == 8){
return -y;
}
else if(octante == 6 || octante == 7){
return -x;
}
else{
return y;
}
}
void DrawLine(coordenada c1, coordenada c2, cor cor1, cor cor2){
double dx = c2.x-c1.x; //delta x
double dy = c2.y-c1.y; //delta y
double modulodx, modulody; //modulo de delta x e delta y
double aux; //variável auxiliar para trocar valores
int octante; //octante em que está a linha
double x = c1.x; //coordenada x que varia para imprimir a linha na tela
double y = c1.y; //coordenada y que varia para imprimir a linha na tela
double x2 = c2.x; //coordenada x final
modulodx = abs(dx);
modulody = abs(dy);
//condição para saber se está no octante 1
if(dx>=0 && dy>=0 && modulodx>=modulody){
octante = 1;
}
/*
condição para saber se está no octante 2, caso esteja, troca os valores de dx por dy, dy por dx,
x por y, y por x e x2 por y final
*/
else if(dx>=0 && dy>=0 && modulody>=modulodx){
octante = 2;
aux = dx;
dx = dy;
dy = aux;
aux = x;
x = y;
y = aux;
x2 = c2.y;
}
/*
condição para saber se está no octante 3, caso esteja, troca dy por -dx, dx por dy e x2 por y final
*/
else if(dx<0 && dy>=0 && modulody>=modulodx){
octante = 3;
aux = -dx;
dx = dy;
dy = aux;
aux = -x;
x = y;
y = aux;
x2 = c2.y;
}
/*
condição para saber se está no octante 4, caso esteja, troca dx por -dx, x por -x, x2 por -x2
*/
else if(dx<0 && dy>=0 && modulodx>=modulody){
octante = 4;
dx = -dx;
x = -x;
x2 = -x2;
}
/*
condição para saber se está no octante 5, caso esteja, troca dx por -dx, dy por -dy, x por -x, y por -y e x2 por -x2
*/
else if(dx<0 && dy<0 && modulodx>=modulody){
octante = 5;
dx = -dx;
dy = -dy;
x = -x;
y = -y;
x2 = -x2;
}
/*
condição para saber se está no octante 6, caso esteja, troca dx por -dy, dy por -dx, x por -x, x2 por -x2
*/
else if(dx<0 && dy<0 && modulody>=modulodx){
octante = 6;
aux = -dx;
dx = -dy;
dy = aux;
aux = -x;
x = -y;
y = aux;
x2 = -c2.y;
}
/*
condição para saber se está no octante 7, caso esteja, troca dx por -dy, dy por dx, x por -y, y por x e x2 por -y
*/
else if(dx>=0 && dy<0 && modulody>=modulodx){
octante = 7;
aux = dx;
dx = -dy;
dy = aux;
aux = x;
x = -y;
y = aux;
x2 = -c2.y;
}
/*
condição para saber se está no octante 8, caso esteja, troca dy por -dy e y por -y
*/
else if(dx>=0 && dy<0 && modulodx>=modulody){
octante = 8;
dy = -dy;
y = -y;
}
//variação das cores RGBA, quanto aumento cada vez que roda o while até chega ao x final
double varR = (cor2.r - cor1.r) / dx;
double varG = (cor2.g - cor1.g) / dx;
double varB = (cor2.b - cor1.b) / dx;
double varA = (cor2.a - cor2.a) / dx;
//Algoritmo de Bresenham
double d = 2*dy-dx;
double incr_e = 2*dy;
double incr_ne = 2*(dy-dx);
PutPixel(getX(octante, x, y), getY(octante, x, y), cor1);
while(x<x2){
if(d<=0){
d += incr_e;
x++;
}else{
d += incr_ne;
x++;
y++;
}
//incremento das cores de modo a interpolar do inicio ao fim da linha
cor1.r += varR;
cor1.g += varG;
cor1.b += varB;
cor1.a += varA;
PutPixel(getX(octante, x, y), getY(octante, x, y), cor1);
}
}
void DrawTrianglePreenchido(coordenada c1, coordenada c2, coordenada c3, cor cor1, cor cor2){
double i=c1.x, j=c1.y, varX=1, varY=1; //i inicia no x inicial, j inicia no y inicial, variação de x e y começam com 1
coordenada p(c2.x-c1.x, c2.y-c1.y); //ponto médio das coordenadas c1 e c2
bool incrementaI = false; //variavel pra saber se o i vai ser incrementado ou decrementado
bool incrementaJ = false; //variavel pra saber se o j vai ser incrementado ou decrementado
if(c1.x<=c2.x){ // se o ponto x inicial for menor que o ponto x final, então i incrementa, se não, decrementa
incrementaI = true;
}
if(c1.y<=c2.y){// se o ponto y inicial for menor que o ponto y final, então j incrementa, se não, decrementa
incrementaJ = true;
}
double modulopx = abs(p.x); //modulo de x do ponto médio
double modulopy = abs(p.y); //modulo de y do ponto médio
/*
se o modulo de x for maior que o modulo de y e modulo de y for diferente de 0,
então a variação de x vai ser modulo de x do ponto médio dividido pelo modulo de y
do ponto médio
*/
if(modulopx>modulopy && modulopy!=0){
varX = modulopx/modulopy;
}
/*
se o modulo de y for maior que o modulo de x e modulo de x for diferente de 0,
então a variação de y vai ser modulo de y do ponto médio dividido pelo modulo de x
do ponto médio
*/
if(modulopy>modulopx && modulopx!=0){
varY = modulopy/modulopx;
}
double variacao = 0.1; //variação de incremento/decremento
while(true){
/*
vai ser impresso linhas variando de c1 a c2 com a destino a c3, de modo a preencher o triangulo
*/
DrawLine(coordenada(i, j), c3, cor1, cor2);
if(incrementaI){
if(i<c2.x){ //i incrementa até a coordenada x final
i+= varX*variacao;
}
}else{
if(i>c2.x){ //i decrementa até a coordenada x inicial
i-= varX*variacao;
}
}
if(incrementaJ){
if(j<c2.y){//j incrementa até a coordenada y final
j+= varY*variacao;
}
}else{
if(j>c2.y){//j decrementa até a coordenada y inicial
j-= varY*variacao;
}
}
if(incrementaI && incrementaJ){
/*
Caso i incremente e J incremente, a condição de parada é quando i for menor ao x final
e j for menor que o y final
*/
if(i>=c2.x && j>=c2.y){
break;
}
}
if(!incrementaI && incrementaJ){
/*
Caso i decremente e J incremente, a condição de parada é quando i for maior ao x final
e j for menor que o y final
*/
if(i<=c2.x && j>=c2.y){
break;
}
}
if(incrementaI && !incrementaJ){
/*
Caso i incremente e J decremente, a condição de parada é quando i for menor ao x final
e j for maior que o y final
*/
if(i>=c2.x && j<=c2.y){
break;
}
}
if(!incrementaI && !incrementaJ){
/*
Caso i decremente e J decremente, a condição de parada é quando i for maior ao x final
e j for maior que y final
*/
if(i<=c2.x && j<=c2.y){
break;
}
}
}
}
double Distancia(coordenada c1,coordenada c2){ //retorna a distancia de dois pontos
coordenada p(c2.x - c1.x, c2.y - c1.y);
return sqrt(pow(p.x, 2)+pow(p.y, 2));
}
void DrawTriangle(coordenada c1, coordenada c2, coordenada c3, cor cor1, cor cor2){
/*
imprime o triangulo preenchido, partido da variação das coordenadas do menor lado e indo em direção
ao terceiro ponto
*/
if(Distancia(c1, c2) <= Distancia(c1,c3) && Distancia(c1, c2)<=Distancia(c2, c3)){
DrawTrianglePreenchido(c1, c2, c3, cor1, cor2);
}else if(Distancia(c1, c3)<=Distancia(c1, c2) && Distancia(c1, c3)<=Distancia(c2, c3)){
DrawTrianglePreenchido(c1, c3, c2, cor1, cor2);
}else{
DrawTrianglePreenchido(c2, c3, c1, cor1, cor2);
}
}
#endif // _MYGL_H_
| true |
66732faf5269ae859f7c2946ff8a2fe0aeed393d | C++ | sanyamdtu/interview_questions | /graphs/mother_vertex.cpp | UTF-8 | 662 | 3.046875 | 3 | [] | no_license |
void dfs(vector<int> g[], int vis[], int src, stack<int> &s)
{
for (auto i : g[src])
{
if (vis[i] == 0)
{
vis[i] = 1;
dfs(g, vis, i, s);
}
}
s.push(src);
}
int findMother(int n, vector<int> g[])
{
int vis[n];
memset(vis, 0, sizeof(vis));
stack<int> s;
for (int i = 0; i < n; i++)
{
if (vis[i] == 0)
{
vis[i] = 1;
dfs(g, vis, i, s);
}
}
memset(vis, 0, sizeof(vis));
int a = s.top();
vis[a] = 1;
dfs(g, vis, a, s);
for (int i = 0; i < n; i++)
if (vis[i] == 0)
return -1;
return a;
}
| true |
5636faf622bec622a027b6504968857d6e5fd3d3 | C++ | ZidongLiu/leet_code_Solution | /main.cpp | UTF-8 | 483 | 2.59375 | 3 | [] | no_license | #include <vector>
#include <set>
#include <algorithm>
#include <iostream>
#include <string>
#include <iomanip>
#include <map>
#include <cmath>
#include <unordered_set>
#include <limits>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int main(){
Solution b;
TreeNode *a= new TreeNode(-2147483648);
///a->right = new TreeNode();
cout<<b.isValidBST(a);
}
| true |
d135b8287534756077fa046404c4877d3451161b | C++ | TomLott/cpp | /day00/ex01/phonebook.class.cpp | UTF-8 | 1,648 | 2.703125 | 3 | [] | no_license | #include "phonebook.hpp"
PhoneBook::PhoneBook()
{
exist = 0;
}
PhoneBook::~PhoneBook(){}
void PhoneBook::setFirstName(std::string &s) {
PhoneBook::_firstName = s;
}
void PhoneBook::setLastName(std::string &s){ this->_lastName = s;}
void PhoneBook::setNickname(std::string &s){ this->_nickname = s;}
void PhoneBook::setLogin(std::string &s){ this->_login = s;}
void PhoneBook::setPostalAddress(std::string &s) { this->_postalAddress = s;}
void PhoneBook::setEmailAddress(std::string &s) { this->_emailAddress = s;}
void PhoneBook::setPhoneNumber(std::string &s) { this->_phoneNumber = s;}
void PhoneBook::setBirthdayDate(std::string &s) { this->_birthdayDate = s;}
void PhoneBook::setFavoriteMeal(std::string &s) { this->_favoriteMeal = s;}
void PhoneBook::setUnderwearColor(std::string &s) { this->_underwearColor = s;}
void PhoneBook::setDarkestSecret(std::string &s) {this->_darkestSecret = s;}
std::string &PhoneBook::getFirstName() { return (this->_firstName);}
std::string &PhoneBook::getLastName() { return (_lastName);}
std::string &PhoneBook::getNickname() { return (_nickname);}
std::string &PhoneBook::getLogin() { return (_login);}
std::string &PhoneBook::getPostalAddress() {return (_postalAddress);}
std::string &PhoneBook::getEmailAddress() { return (_emailAddress) ;}
std::string &PhoneBook::getPhoneNumber() { return (_phoneNumber);}
std::string &PhoneBook::getBirthdayDate() { return (_birthdayDate);}
std::string &PhoneBook::getFavoriteMeal() { return (_favoriteMeal);}
std::string &PhoneBook::getUnderwearColor() { return (_underwearColor);}
std::string &PhoneBook::getDarkestSecret() { return (_darkestSecret);}
| true |