blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9d1c7e8bfffd4b40d95973e589a8b696becd8806 | 6d34ff39c44b23831639ff60f7c0a9ba24e80372 | /Class_Assignments/Assignment1/C2Q1_Array_Struct.cpp | 5c852306236abbda5d9aaaa7e3108e16ee77ee09 | [] | no_license | eneskemalergin/Programming-Languages | 8bef08707d63a741a1f0b735de8945aca79460d5 | 1ada6de001e503a87cb2f8333dc7952a686daaa3 | refs/heads/master | 2021-01-01T05:53:44.654020 | 2015-12-13T01:58:22 | 2015-12-13T01:58:22 | 41,777,117 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 691 | cpp | C2Q1_Array_Struct.cpp | /* To understand the value of records in a programming language,
* write a small program in a C-based language that uses
* an array of structs that store student information, including name,
* age, GPA as a float, and grade level as a string
* (e.g., “freshmen,” etc.).
*/
/* Author: Enes Kemal Ergin
* Assignment: Assignment 1P
* Class : Programming Languages
* Date : 09/06/15
*/
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
float gpa;
string gradeLevel;
};
int main (int argc, char* argv[])
{
Student students[2] = {{"Enes", 21, 3.89, "Senior"},
{"Kemal", 24, 3.49, "Freshman"}};
}
|
2a7ceb8c8509bbbb1203599d7f3751ed7aad8ffc | 09f4740e2aec22c02b6ec13dbce2ba2ad30fc1e0 | /src/NOKIA5110_TEXT.h | 5073778b49787935b400cd10cb95cf44a6cf230a | [] | no_license | WGR7/NOKIA5110_TEXT | 24a0183c41d0458da7d95e365305b89594dc3e62 | fc8feb2340e660915937a9e7d3de51edaaaf0eb0 | refs/heads/master | 2022-04-02T12:21:24.864676 | 2020-02-08T16:41:22 | 2020-02-08T16:41:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,495 | h | NOKIA5110_TEXT.h | /*
* Project Name: NOKIA5110_TEXT
* File: NOKIA5110_TEXT.h
* Description: Nokia library header file
* Author: Gavin Lyons.
* URL: https://github.com/gavinlyonsrepo/NOKIA5110_TEXT
*/
#ifndef NOKIA5110_TEXT_H
#define NOKIA5110_TEXT_H
#if (ARDUINO >=100)
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
// **** FONT DEFINE SECTION ******
// Comment in the fonts you want, X_1 is default.
#define NOKIA5110_FONT_1
//#define NOKIA5110_FONT_2
//#define NOKIA5110_FONT_3
//#define NOKIA5110_FONT_4
//#define NOKIA5110_FONT_5
//#define NOKIA5110_FONT_6
// **** END OF FONT DEFINE SECTION ******
#ifdef NOKIA5110_FONT_1
#include "NOKIA5110_TEXT_FONT.h"
#endif
#ifdef NOKIA5110_FONT_2
#include "NOKIA5110_TEXT_FONT_TWO.h"
#endif
#ifdef NOKIA5110_FONT_3
#include "NOKIA5110_TEXT_FONT_THREE.h"
#endif
#ifdef NOKIA5110_FONT_4
#include "NOKIA5110_TEXT_FONT_FOUR.h"
#endif
#ifdef NOKIA5110_FONT_5
#include "NOKIA5110_TEXT_FONT_FIVE.h"
#endif
#ifdef NOKIA5110_FONT_6
#include "NOKIA5110_TEXT_FONT_SIX.h"
#endif
//LCD Commands PCD8544_
#define LCD_COMMAND_MODE 0x21 //FUNCTIONSET + extended instruction
#define LCD_CONTRAST 0xBF //Set LCD VOP Contrast Try 0xB1 or 0xBF if is too dark range = ((0x00-0x7F) |0x80)
#define LCD_TEMP_COEF 0x04 //Set Temp coefficient
#define LCD_BIAS 0x14 // //LCD bias mode 1:48: Try 0x13 or 0x14
#define LCD_FUNCTIONSET 0x20 //We must send 0x20 before modifying the display control mode
#define LCD_DISPLAYCONTROL 0x0C //Set display control, normal mode. 0x0D for inverse
#define LCD_DISPLAYCONTROL_INVERSE 0x0D //Set display control, inverse mode. 0x0D for inverse
#define LCD_POWERDOWN 0x24 //LCD power off
// Misc LCD Data
#define LCD_FONTNUMBER 0x01 // default Font number 1, 1 to 6 fonts
#define LCD_ASCII_OFFSET 0x20 //0x20, ASCII character for Space, The font table starts with this character
//The DC pin tells the LCD if sending a command or data
#define LCD_COMMAND 0
#define LCD_DATA 1
// 84 by 48 pixels screen
#define LCD_X 84
#define LCD_Y 48
// GPIO on/off
#define _LCD_CLK_SetHigh digitalWrite(_LCD_CLK, true)
#define _LCD_CLK_SetLow digitalWrite(_LCD_CLK, false)
#define _LCD_DIN_SetHigh digitalWrite(_LCD_DIN, true)
#define _LCD_DIN_SetLow digitalWrite(_LCD_DIN, false)
#define _LCD_DC_SetHigh digitalWrite(_LCD_DC, true)
#define _LCD_DC_SetLow digitalWrite(_LCD_DC, false)
#define _LCD_CE_SetHigh digitalWrite(_LCD_CE, true)
#define _LCD_CE_SetLow digitalWrite(_LCD_CE, false)
#define _LCD_RST_SetHigh digitalWrite(_LCD_RST, true)
#define _LCD_RST_SetLow digitalWrite(_LCD_RST, false)
class NOKIA5110_TEXT {
public:
// Constructor
NOKIA5110_TEXT(uint8_t LCD_RST, uint8_t LCD_CE, uint8_t LCD_DC, uint8_t LCD_DIN, uint8_t LCD_CLK);
// Methods
void LCDInit(bool , uint8_t , uint8_t);
void LCDgotoXY(uint8_t , uint8_t);
void LCDClear(void);
void LCDClearBlock(uint8_t);
void LCDString(const char *characters);
void LCDsetContrast(uint8_t );
void LCDenableSleep(void);
void LCDdisableSleep(void);
void LCDCharacter(char);
void LCDWrite(unsigned char , unsigned char);
void LCDFont(uint8_t);
void LCDSetPixel(uint8_t, uint8_t);
private:
uint8_t _LCD_RST;
uint8_t _LCD_CE;
uint8_t _LCD_DC;
uint8_t _LCD_DIN;
uint8_t _LCD_CLK;
uint8_t _contrast = LCD_CONTRAST ;
uint8_t _FontNumber = LCD_FONTNUMBER;
boolean _sleep;
boolean _inverse;
};
#endif
|
f5a23b0db3d145c20b5dcfe1e52f37aa8c67a724 | f87302e58193507abafaef92efe2b3363135af83 | /libs/model/include/model/analysis/dominator.hpp | 31ec19dc4ea11c76f0274330240e5fa0fa5dca10 | [] | no_license | dannybpoulsen/minimc | 7ccbb7a3ea9d73825db8730f2b04e92f967a7993 | e496b903866a93436f561834e375197b68e16511 | refs/heads/master | 2023-09-05T19:22:44.325477 | 2023-08-10T18:49:44 | 2023-08-10T18:49:44 | 252,640,133 | 8 | 1 | null | 2023-04-20T09:44:47 | 2020-04-03T05:26:04 | C++ | UTF-8 | C++ | false | false | 1,315 | hpp | dominator.hpp | #ifndef _DOMINATOR_ANALYSIS_MANAGER__
#define _DOMINATOR_ANALYSIS_MANAGER__
#include <algorithm>
#include <memory>
#include <set>
#include <unordered_map>
#include <vector>
#include "model/cfg.hpp"
namespace MiniMC {
namespace Model {
namespace Analysis {
template <class T>
class DominatorInfo {
public:
using T_ptr = std::shared_ptr<T>;
using const_iterator = typename std::set<T_ptr>::const_iterator;
const_iterator dombegin(const T_ptr& n) const { return dominator_map[n.get()].begin(); }
const_iterator domend(const T_ptr& n) const { return dominator_map[n.get()].end(); }
bool dominates(const T_ptr& node, const T_ptr& dominatedBy) const {
return dominator_map[node.get()].count(dominatedBy);
}
bool setDominators(const T_ptr& n, const std::set<T_ptr>& h) {
if (dominator_map[n.get()] == h)
return false;
else {
dominator_map[n.get()] = h;
return true;
}
}
private:
mutable std::unordered_map<const T*, std::set<T_ptr>> dominator_map;
};
DominatorInfo<MiniMC::Model::Location> calculateDominators(const MiniMC::Model::CFA& cfg);
} // namespace Analysis
} // namespace Model
} // namespace MiniMC
#endif
|
2e7d0f8e632cfca6acf73f8f918f15aa8a4a3d81 | f0c170e7daa0fdc2abec2eb6ff1b672d0f812f7b | /code/03 Demo/MyAdoDemo1/Config.h | f650287741066c5ff953fac6432ef079287200a1 | [] | no_license | mqd520/CPlusPlusLib | 88dc22aa92e4a41ac83c0f123ff1a9c94938308e | 2ec726db5397d78d7c261ce3b4b51227a7571e66 | refs/heads/master | 2020-09-10T01:08:31.051065 | 2019-11-30T21:33:51 | 2019-11-30T21:33:51 | 221,612,262 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 684 | h | Config.h | #pragma once
#include <vector>
using namespace std;
#include "Def.h"
// Config
class Config
{
public:
Config();
protected:
vector<XmlSqlInfo> vecSqlInfos; // Sql info list
public:
bool bMultiThread; // Whether multi thread
int nSqlTaskThreadTime; // Sql task thread time
AdoThreadInfo adoThreadInfo; // Ado Thread Info
string strDbConnection; // Db connection
public:
//************************************
// Method: Init
//************************************
void Init();
//************************************
// Method: List
//************************************
vector<XmlSqlInfo>& List();
};
extern Config _cfg; // the only Config object |
55876dfdfaad731d0075861382e3ad184f861f41 | 93dbd845aadb47433778372b0514b785ec4aede5 | /flight_controller/flight_controller.ino | 20c8af5c52c8824b24d464fb93af91439b567548 | [] | no_license | Egor18/diy_fpv_plane | f25b73cc97520d46c97c56f20c4106c82a7770d0 | e705768888b9d93f540cedbaae8b0b8135f91506 | refs/heads/master | 2020-03-28T08:16:18.346719 | 2018-10-08T17:17:25 | 2018-10-08T17:17:25 | 147,955,090 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,390 | ino | flight_controller.ino | #include <Servo.h>
#include "I2C.h"
#define BAUD_RATE 57600
enum Channel
{
ELEVATOR = 0,
RUDDER = 1,
AILERON = 2,
THROTTLE = 3,
CAMERA = 4,
OSD = 5
};
#define OSD_WIRE_ADDR 0x08
enum OSDCommand
{
OSD_OFF = 51,
OSD_ON = 52,
DIM_OFF = 53,
DIM_ON = 54,
ERR_INC = 55,
ERR_DEC = 56,
SET_HOME = 57,
LOST_CONN = 58
};
#define GetNum(byte) (((byte) & 0b11000000) >> 6)
#define GetData(byte) (((byte) & 0b00111111))
#define MIN_THROTTLE 0
#define MAX_THROTTLE 50
#define MIN_POS 0
#define MAX_POS 62
#define ELEVATOR_START 850
#define ELEVATOR_END 1550
#define RUDDER_START 550
#define RUDDER_END 1250
#define AILERON_LEFT_START 1275
#define AILERON_LEFT_END 1975
#define AILERON_RIGHT_START 1200
#define AILERON_RIGHT_END 1900
#define CAMERA_START 450
#define CAMERA_END 2050
#define ENGINE_START 900
#define ENGINE_END 2000
int byteCounter = 0;
unsigned char currentBytes[4];
Servo elevatorServo;
Servo rudderServo;
Servo aileronLeftServo;
Servo aileronRightServo;
Servo cameraServo;
Servo engineESC;
boolean i2cError = false;
void setup()
{
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
elevatorServo.attach(9);
rudderServo.attach(8);
aileronLeftServo.attach(7);
aileronRightServo.attach(6);
cameraServo.attach(5);
engineESC.attach(2);
// Set servos to the middle position
elevatorServo.writeMicroseconds((ELEVATOR_START + ELEVATOR_END) / 2);
rudderServo.writeMicroseconds((RUDDER_START + RUDDER_END) / 2);
aileronLeftServo.writeMicroseconds((AILERON_LEFT_START + AILERON_LEFT_END) / 2);
aileronRightServo.writeMicroseconds((AILERON_RIGHT_START + AILERON_RIGHT_END) / 2);
cameraServo.writeMicroseconds((CAMERA_START + CAMERA_END) / 2);
// Arm engine ESC
engineESC.writeMicroseconds(ENGINE_START);
Serial.begin(BAUD_RATE);
I2c.begin();
I2c.timeOut(100);
delay(500);
}
void SendByteToOSD(unsigned char data)
{
if (i2cError)
{
return;
}
uint8_t rc = I2c.write((uint8_t)OSD_WIRE_ADDR, data);
if (rc != 0 && rc < 8)
{
// I2C timeout occured
// Stop all communication with OSD, to prevent further delays
i2cError = true;
}
}
void ProcessPackageData(unsigned char bytes[4])
{
unsigned char channel = GetData(bytes[0]);
unsigned char channelConfirmation = GetData(bytes[1]);
unsigned char data = GetData(bytes[2]);
unsigned char dataConfirmation = GetData(bytes[3]);
if ((channel != channelConfirmation || data != dataConfirmation) ||
(channel > OSD) ||
(channel == THROTTLE && data > MAX_THROTTLE) ||
(channel == OSD && data > LOST_CONN) ||
(channel != OSD && data > MAX_POS))
{
byteCounter = 0;
SendByteToOSD(ERR_INC);
return;
}
switch (channel)
{
case ELEVATOR:
elevatorServo.writeMicroseconds(map(data, MIN_POS, MAX_POS, ELEVATOR_START, ELEVATOR_END));
break;
case RUDDER:
rudderServo.writeMicroseconds(map(data, MIN_POS, MAX_POS, RUDDER_START, RUDDER_END));
break;
case AILERON:
aileronLeftServo.writeMicroseconds(map(data, MIN_POS, MAX_POS, AILERON_LEFT_START, AILERON_LEFT_END));
aileronRightServo.writeMicroseconds(map(data, MIN_POS, MAX_POS, AILERON_RIGHT_START, AILERON_RIGHT_END));
break;
case CAMERA:
cameraServo.writeMicroseconds(map(data, MIN_POS, MAX_POS, CAMERA_START, CAMERA_END));
break;
case THROTTLE:
engineESC.writeMicroseconds(map(data, MIN_THROTTLE, MAX_THROTTLE, ENGINE_START, ENGINE_END));
SendByteToOSD(data);
break;
case OSD:
SendByteToOSD(data);
break;
}
}
unsigned long lastDataReceivedTime = 0;
void loop()
{
if (Serial.available() > 0)
{
lastDataReceivedTime = millis();
int data = Serial.read();
if (data == -1 || GetNum(data) != byteCounter)
{
byteCounter = 0;
SendByteToOSD(ERR_INC);
}
else
{
currentBytes[byteCounter++] = (unsigned char) data;
if (byteCounter == 4)
{
ProcessPackageData(currentBytes);
byteCounter = 0;
}
}
}
if (millis() - lastDataReceivedTime > 4000 && lastDataReceivedTime != 0)
{
// Connection is lost
// Engine off, elevator down
SendByteToOSD(LOST_CONN);
engineESC.writeMicroseconds(ENGINE_START);
elevatorServo.writeMicroseconds(ELEVATOR_END);
SendByteToOSD(0);
delay(150);
}
}
|
0af48c1217a880ed826143bed70a758740c3d2b4 | af0ecafb5428bd556d49575da2a72f6f80d3d14b | /CodeJamCrawler/dataset/12_14872_25.cpp | 96d2c3c906b60309559cf2cca45d7895f5265962 | [] | no_license | gbrlas/AVSP | 0a2a08be5661c1b4a2238e875b6cdc88b4ee0997 | e259090bf282694676b2568023745f9ffb6d73fd | refs/heads/master | 2021-06-16T22:25:41.585830 | 2017-06-09T06:32:01 | 2017-06-09T06:32:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,309 | cpp | 12_14872_25.cpp | #define __DEBUG
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
const int keyIndex[] = {97, 100, 103, 106, 109, 112, 116, 119};
ifstream inputFile;
ofstream outputFile;
void OpenInputFile(char* filename);
void OpenOutputFile(char* filename);
char KeyPadNumOf(int asciiCode);
void FindSolution(int numCase, string inputStr);
int main()
{
OpenInputFile("C-large-practice.in");
OpenOutputFile("output.out");
if (inputFile.is_open())
{
string readInt; int numCase;
getline(inputFile, readInt);
numCase = atoi (readInt.c_str());
string temp;
for (int i = 0; i < numCase; ++i)
{
getline(inputFile, temp);
FindSolution(i, temp);
}
}
else
{
cout << "Failed to open input file.\n";
}
inputFile.close();
outputFile.close();
cin.get();
cin.get();
return 0;
}
void OpenInputFile(char* filename)
{
inputFile.open(filename);
}
void OpenOutputFile(char* filename)
{
outputFile.open(filename);
}
char KeyPadNumOf(int asciiCode)
{
char returnValue = '.';
switch (asciiCode)
{
case 32:
returnValue = '0';
break;
case 97 ... 99:
returnValue = '2';
break;
case 100 ... 102:
returnValue = '3';
break;
case 103 ... 105:
returnValue = '4';
break;
case 106 ... 108:
returnValue = '5';
break;
case 109 ... 111:
returnValue = '6';
break;
case 112 ... 115:
returnValue = '7';
break;
case 116 ... 118:
returnValue = '8';
break;
case 119 ... 122:
returnValue = '9';
break;
}
return returnValue;
}
void FindSolution(int numCase, string inputStr)
{
#ifdef __DEBUG
cout << numCase << "," << inputStr << "\n";
#endif
string parsedString = "";
char last = '-';
for (int i = 0; i < inputStr.size(); ++i)
{
int asciiCode = int(inputStr[i]);
char keypad = KeyPadNumOf(asciiCode);
if (keypad == last)
{
parsedString.append(" ");
}
stringstream ss;
string keypadInStr;
ss << keypad;
ss >> keypadInStr;
if (asciiCode >= 97)
{
int repeatedPress = asciiCode - keyIndex[keypad - int('2')];
#ifdef __DEBUG
cout << asciiCode << "," << keypad << "," << keypadInStr << "," << repeatedPress << "\n";
#endif
for (int j = 0; j <= repeatedPress; ++j)
{
parsedString.append(keypadInStr);
}
}
else if (asciiCode == 32)
{
parsedString.append(keypadInStr);
}
last = keypad;
}
cout << "parsed word: " << parsedString << "\n";
outputFile << "Case #" << numCase + 1 << ": " << parsedString << "\n";
}
|
cf839a82f0b2b70a4acf8f2cefdbbd879eb812b2 | d618f171a639311de598850d80a0422610dace80 | /LogitechSteeringWheelSDK_8.75.30/Samples/SteeringWheelSDKSimple/SteeringWheelSDKSimple/SteeringWheelSDKSimpleDlg.cpp | c9123b452ab05d0c51a191f9e610f68e492629f9 | [] | no_license | tongji-cdi/driving-simulator | 0cb09206dfb4da30081de2094165f3dc80b36dd1 | a5d9beb114abff1484674d0e5a5b17802b4b6cf2 | refs/heads/main | 2023-08-28T01:57:33.194866 | 2021-10-19T07:29:08 | 2021-10-19T07:29:08 | 412,952,748 | 1 | 2 | null | 2021-10-19T07:29:09 | 2021-10-03T01:55:44 | C# | UTF-8 | C++ | false | false | 35,625 | cpp | SteeringWheelSDKSimpleDlg.cpp |
// DemoWheelSimpleDlg.cpp : implementation file
//
#include "stdafx.h"
#include "SteeringWheelSDKSimple.h"
#include "SteeringWheelSDKSimpleDlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
CSteeringWheelSimpleDlg::CSteeringWheelSimpleDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CSteeringWheelSimpleDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CSteeringWheelSimpleDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_SCROLLOFFSET, m_scrollBarOffset);
DDX_Control(pDX, IDC_SCROLLSATURATION, m_scrollBarSaturation);
DDX_Control(pDX, IDC_SCROLLCOEFFICIENT, m_scrollBarCoefficient);
DDX_Control(pDX, IDC_SCROLLMAGNITUDE, m_scrollBarMagnitude);
DDX_Control(pDX, IDC_SCROLLUSABLERANGE, m_scrollBarUsableRange);
DDX_Control(pDX, IDC_CHECKALLDEVICES, m_checkAllDevices);
DDX_Control(pDX, IDC_CHECKFULLRANGE, m_checkFullRangePercentages);
DDX_Control(pDX, IDC_CHECKSPRING, m_checkSpring);
DDX_Control(pDX, IDC_CHECKCONSTANT, m_checkConstant);
DDX_Control(pDX, IDC_CHECKDAMPER, m_checkDamper);
DDX_Control(pDX, IDC_CHECKDIRTROAD, m_checkDirtRoad);
DDX_Control(pDX, IDC_CHECKBUMPYROAD, m_checkBumpyRoad);
DDX_Control(pDX, IDC_CHECKSLIPPERYROAD, m_checkSlipperyRoad);
DDX_Control(pDX, IDC_CHECKCARAIRBORNE, m_checkCarAirborne);
DDX_Control(pDX, IDC_CHECKSOFTSTOP, m_checkSoftstop);
}
BEGIN_MESSAGE_MAP(CSteeringWheelSimpleDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_HSCROLL()
ON_WM_TIMER()
ON_BN_CLICKED(IDC_EXIT, &CSteeringWheelSimpleDlg::OnBnClickedExit)
ON_BN_CLICKED(IDC_LogiSteeringInitialize, &CSteeringWheelSimpleDlg::OnBnClickedLogiSteeringInitialize)
ON_BN_CLICKED(IDC_LogiSteeringInitializeWithWindow, &CSteeringWheelSimpleDlg::OnBnClickedLogiSteeringInitializeWithWindow)
ON_BN_CLICKED(IDC_LogiSteeringGetSdkVersion, &CSteeringWheelSimpleDlg::OnBnClickedLogiSteeringGetSdkVersion)
ON_BN_CLICKED(IDC_LogiUpdate, &CSteeringWheelSimpleDlg::OnBnClickedLogiUpdate)
ON_BN_CLICKED(IDC_LogiGetStateENGINES, &CSteeringWheelSimpleDlg::OnBnClickedLogiGetStateENGINES)
ON_BN_CLICKED(IDC_LogiGetState, &CSteeringWheelSimpleDlg::OnBnClickedLogiGetState)
ON_BN_CLICKED(IDC_LogiGetFriendlyProductName, &CSteeringWheelSimpleDlg::OnBnClickedLogiGetFriendlyProductName)
ON_BN_CLICKED(IDC_LogiIsConnected, &CSteeringWheelSimpleDlg::OnBnClickedLogiIsConnected)
ON_BN_CLICKED(IDC_LogiIsDeviceConnected, &CSteeringWheelSimpleDlg::OnBnClickedLogiIsDeviceConnected)
ON_BN_CLICKED(IDC_LogiIsManufacturerConnected, &CSteeringWheelSimpleDlg::OnBnClickedLogiIsManufacturerConnected)
ON_BN_CLICKED(IDC_LogiIsModelConnected, &CSteeringWheelSimpleDlg::OnBnClickedLogiIsModelConnected)
ON_BN_CLICKED(IDC_LogiButtonTriggered, &CSteeringWheelSimpleDlg::OnBnClickedLogiButtonTriggered)
ON_BN_CLICKED(IDC_LogiButtonReleased, &CSteeringWheelSimpleDlg::OnBnClickedLogiButtonReleased)
ON_BN_CLICKED(IDC_LogiButtonIsPressed, &CSteeringWheelSimpleDlg::OnBnClickedLogiButtonIsPressed)
ON_BN_CLICKED(IDC_LogiGenerateNonLinearValues, &CSteeringWheelSimpleDlg::OnBnClickedLogiGenerateNonLinearValues)
ON_BN_CLICKED(IDC_LogiGetNonLinearValue, &CSteeringWheelSimpleDlg::OnBnClickedLogiGetNonLinearValue)
ON_BN_CLICKED(IDC_LogiHasForceFeedback, &CSteeringWheelSimpleDlg::OnBnClickedLogiHasForceFeedback)
ON_BN_CLICKED(IDC_LogiIsPlaying, &CSteeringWheelSimpleDlg::OnBnClickedLogiIsPlaying)
ON_BN_CLICKED(IDC_LogiPlaySpringForce, &CSteeringWheelSimpleDlg::OnBnClickedLogiPlaySpringForce)
ON_BN_CLICKED(IDC_LogiStopSpringForce, &CSteeringWheelSimpleDlg::OnBnClickedLogiStopSpringForce)
ON_BN_CLICKED(IDC_LogiPlayConstantForce, &CSteeringWheelSimpleDlg::OnBnClickedLogiPlayConstantForce)
ON_BN_CLICKED(IDC_LogiStopConstantForce, &CSteeringWheelSimpleDlg::OnBnClickedLogiStopConstantForce)
ON_BN_CLICKED(IDC_LogiPlayDamperForce, &CSteeringWheelSimpleDlg::OnBnClickedLogiPlayDamperForce)
ON_BN_CLICKED(IDC_LogiStopDamperForce, &CSteeringWheelSimpleDlg::OnBnClickedLogiStopDamperForce)
ON_BN_CLICKED(IDC_LogiPlaySideCollisionForce, &CSteeringWheelSimpleDlg::OnBnClickedLogiPlaySideCollisionForce)
ON_BN_CLICKED(IDC_LogiPlayFrontalCollisionForce, &CSteeringWheelSimpleDlg::OnBnClickedLogiPlayFrontalCollisionForce)
ON_BN_CLICKED(IDC_LogiPlayDirtRoadEffect, &CSteeringWheelSimpleDlg::OnBnClickedLogiPlayDirtRoadEffect)
ON_BN_CLICKED(IDC_LogiStopDirtRoadEffect, &CSteeringWheelSimpleDlg::OnBnClickedLogiStopDirtRoadEffect)
ON_BN_CLICKED(IDC_LogiPlayBumpyRoadEffect, &CSteeringWheelSimpleDlg::OnBnClickedLogiPlayBumpyRoadEffect)
ON_BN_CLICKED(IDC_LogiStopBumpyRoadEffect, &CSteeringWheelSimpleDlg::OnBnClickedLogiStopBumpyRoadEffect)
ON_BN_CLICKED(IDC_LogiPlaySlipperyRoadEffect, &CSteeringWheelSimpleDlg::OnBnClickedLogiPlaySlipperyRoadEffect)
ON_BN_CLICKED(IDC_LogiStopSlipperyRoadEffect, &CSteeringWheelSimpleDlg::OnBnClickedLogiStopSlipperyRoadEffect)
ON_BN_CLICKED(IDC_LogiPlaySurfaceEffect, &CSteeringWheelSimpleDlg::OnBnClickedLogiPlaySurfaceEffect)
ON_BN_CLICKED(IDC_LogiStopSurfaceEffect, &CSteeringWheelSimpleDlg::OnBnClickedLogiStopSurfaceEffect)
ON_BN_CLICKED(IDC_LogiPlayCarAirborne, &CSteeringWheelSimpleDlg::OnBnClickedLogiPlayCarAirborne)
ON_BN_CLICKED(IDC_LogiStopCarAirborne, &CSteeringWheelSimpleDlg::OnBnClickedLogiStopCarAirborne)
ON_BN_CLICKED(IDC_LogiPlaySoftstopForce, &CSteeringWheelSimpleDlg::OnBnClickedLogiPlaySoftstopForce)
ON_BN_CLICKED(IDC_LogiStopSoftstopForce, &CSteeringWheelSimpleDlg::OnBnClickedLogiStopSoftstopForce)
ON_BN_CLICKED(IDC_LogiSetPreferredControllerProperties, &CSteeringWheelSimpleDlg::OnBnClickedLogiSetPreferredControllerProperties)
ON_BN_CLICKED(IDC_LogiGetCurrentControllerProperties, &CSteeringWheelSimpleDlg::OnBnClickedLogiGetCurrentControllerProperties)
ON_BN_CLICKED(IDC_LogiGetShifterMode, &CSteeringWheelSimpleDlg::OnBnClickedLogiGetShifterMode)
ON_BN_CLICKED(IDC_LogiPlayLeds, &CSteeringWheelSimpleDlg::OnBnClickedLogiPlayLeds)
ON_BN_CLICKED(IDC_LogiSteeringShutdown, &CSteeringWheelSimpleDlg::OnBnClickedLogiSteeringShutdown)
ON_EN_CHANGE(IDC_DEVICE, &CSteeringWheelSimpleDlg::OnEnChangeDevice)
ON_BN_CLICKED(IDC_CHECKALLDEVICES, &CSteeringWheelSimpleDlg::OnBnClickedCheckAllDevices)
ON_BN_CLICKED(IDC_CHECKSPRING, &CSteeringWheelSimpleDlg::OnBnClickedCheckSpring)
ON_BN_CLICKED(IDC_CHECKCONSTANT, &CSteeringWheelSimpleDlg::OnBnClickedCheckConstant)
ON_BN_CLICKED(IDC_CHECKDAMPER, &CSteeringWheelSimpleDlg::OnBnClickedCheckDamper)
ON_BN_CLICKED(IDC_CHECKDIRTROAD, &CSteeringWheelSimpleDlg::OnBnClickedCheckDirtRoad)
ON_BN_CLICKED(IDC_CHECKBUMPYROAD, &CSteeringWheelSimpleDlg::OnBnClickedCheckBumpyRoad)
ON_BN_CLICKED(IDC_CHECKSLIPPERYROAD, &CSteeringWheelSimpleDlg::OnBnClickedCheckSlipperyRoad)
ON_BN_CLICKED(IDC_CHECKCARAIRBORNE, &CSteeringWheelSimpleDlg::OnBnClickedCheckCarAirborne)
ON_BN_CLICKED(IDC_CHECKSOFTSTOP, &CSteeringWheelSimpleDlg::OnBnClickedCheckSoftstop)
ON_BN_CLICKED(IDC_CHECKFULLRANGE, &CSteeringWheelSimpleDlg::OnBnClickedCheckFullRange)
ON_BN_CLICKED(IDC_LogiGetGUID, &CSteeringWheelSimpleDlg::OnBnClickedLogiGetDevicePath)
END_MESSAGE_MAP()
// CSteeringWheelSimpleDlg message handlers
BOOL CSteeringWheelSimpleDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
m_deviceIndex = 0;
m_offsetPercentage = 0;
m_saturationPercentage = 0;
m_coefficientPercentage = 0;
m_magnitudePercentage = 0;
m_usableRangePercentage = 0;
m_allDevices = false;
m_spring = false;
m_constant = false;
m_damper = false;
m_dirtRoad = false;
m_bumpyRoad = false;
m_slipperyRoad = false;
m_carAirborne = false;
m_softstop = false;
SetDlgItemInt(IDC_DEVICE, m_deviceIndex, 0);
m_scrollBarOffset.SetScrollRange(0, 100);
m_scrollBarSaturation.SetScrollRange(0, 100);
m_scrollBarCoefficient.SetScrollRange(0, 100);
m_scrollBarMagnitude.SetScrollRange(0, 100);
m_scrollBarUsableRange.SetScrollRange(0, 100);
SetTimer(1, 1000 / 30, NULL);
return TRUE; // return TRUE unless you set the focus to a control
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CSteeringWheelSimpleDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
void CSteeringWheelSimpleDlg::OnTimer(UINT_PTR nIDEvent)
{
UNREFERENCED_PARAMETER(nIDEvent);
// Update the input device every timer message.
//if the return value is false, means that the application has not been initialized yet and there is no hwnd available
if (!LogiUpdate()) return;
if (m_spring)
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiPlaySpringForce(t_index, m_offsetPercentage, m_saturationPercentage, m_coefficientPercentage);
}
}
else
{
LogiPlaySpringForce(m_deviceIndex, m_offsetPercentage, m_saturationPercentage, m_coefficientPercentage);
}
}
if (m_constant)
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiPlayConstantForce(t_index, m_magnitudePercentage);
}
}
else
{
LogiPlayConstantForce(m_deviceIndex, m_magnitudePercentage);
}
}
if (m_damper)
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiPlayDamperForce(t_index, m_coefficientPercentage);
}
}
else
{
LogiPlayDamperForce(m_deviceIndex, m_coefficientPercentage);
}
}
if (m_dirtRoad)
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiPlayDirtRoadEffect(t_index, m_magnitudePercentage);
}
}
else
{
LogiPlayDirtRoadEffect(m_deviceIndex, m_magnitudePercentage);
}
}
if (m_bumpyRoad)
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiPlayBumpyRoadEffect(t_index, m_magnitudePercentage);
}
}
else
{
LogiPlayBumpyRoadEffect(m_deviceIndex, m_magnitudePercentage);
}
}
if (m_slipperyRoad)
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiPlaySlipperyRoadEffect(t_index, m_magnitudePercentage);
}
}
else
{
LogiPlaySlipperyRoadEffect(m_deviceIndex, m_magnitudePercentage);
}
}
if (m_carAirborne)
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiPlayCarAirborne(t_index);
}
}
else
{
LogiPlayCarAirborne(m_deviceIndex);
}
}
if (m_softstop)
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiPlaySoftstopForce(t_index, m_usableRangePercentage);
}
}
else
{
LogiPlaySoftstopForce(m_deviceIndex, m_usableRangePercentage);
}
}
}
void CSteeringWheelSimpleDlg::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
int CurPos = pScrollBar->GetScrollPos();
// Determine the new position of scroll box.
switch (nSBCode)
{
case SB_LEFT: // Scroll to far left.
CurPos = SCROLL_MIN;
break;
case SB_RIGHT: // Scroll to far right.
CurPos = SCROLL_MAX;
break;
case SB_ENDSCROLL: // End scroll.
break;
case SB_LINELEFT: // Scroll left.
if (CurPos > SCROLL_MIN)
CurPos--;
break;
case SB_LINERIGHT: // Scroll right.
if (CurPos < SCROLL_MAX)
CurPos++;
break;
case SB_PAGELEFT: // Scroll one page left.
{
// Get the page size.
SCROLLINFO info;
pScrollBar->GetScrollInfo(&info, SIF_ALL);
if (CurPos > SCROLL_MIN)
CurPos = max(0, CurPos - (int)info.nPage);
}
break;
case SB_PAGERIGHT: // Scroll one page right
{
// Get the page size.
SCROLLINFO info;
pScrollBar->GetScrollInfo(&info, SIF_ALL);
if (CurPos < SCROLL_MAX)
CurPos = min(122, CurPos + (int)info.nPage);
}
break;
case SB_THUMBPOSITION: // Scroll to absolute position. nPos is the position
CurPos = nPos; // of the scroll box at the end of the drag operation.
break;
case SB_THUMBTRACK: // Drag scroll box to specified position. nPos is the
CurPos = nPos; // position that the scroll box has been dragged to.
break;
}
pScrollBar->SetScrollPos(CurPos);
m_offsetPercentage = m_scrollBarOffset.GetScrollPos();
m_saturationPercentage = m_scrollBarSaturation.GetScrollPos();
m_coefficientPercentage = m_scrollBarCoefficient.GetScrollPos();
m_magnitudePercentage = m_scrollBarMagnitude.GetScrollPos();
m_usableRangePercentage = m_scrollBarUsableRange.GetScrollPos();
if (m_fullRange)
{
m_offsetPercentage = (m_offsetPercentage * 2) - 100;
m_coefficientPercentage = (m_coefficientPercentage * 2) - 100;
m_magnitudePercentage = (m_magnitudePercentage * 2) - 100;
}
CDialogEx::OnHScroll(nSBCode, nPos, pScrollBar);
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CSteeringWheelSimpleDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CSteeringWheelSimpleDlg::OnBnClickedExit()
{
CDialog::OnOK();
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiSteeringInitialize()
{
if (LogiSteeringInitialize(true))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiSteeringInitialize returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiSteeringInitialize returned FALSE");
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiSteeringInitializeWithWindow()
{
if (LogiSteeringInitializeWithWindow(true, m_hWnd))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiSteeringInitializeWithWindow returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiSteeringInitializeWithWindow returned FALSE");
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiSteeringGetSdkVersion()
{
// TODO: Add your control notification handler code here
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiSteeringGetSdkVersion is not yet implemented");
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiUpdate()
{
if (LogiUpdate())
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiUpdate returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiUpdate returned FALSE");
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiGetStateENGINES()
{
// TODO: Add your control notification handler code here
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiGetStateENGINES is not yet implemented");
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiGetState()
{
// TODO: Add your control notification handler code here
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiGetState is not yet implemented");
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiGetFriendlyProductName()
{
TCHAR sBuffer_[512] = { '\0' };
TCHAR buf[128] = { '\0' };
if (LogiIsConnected(m_deviceIndex) && LogiGetFriendlyProductName(m_deviceIndex, buf, 128))
{
wsprintf(sBuffer_, TEXT("%s %s"), L"LogiGetFriendlyProductName returned", buf);
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), sBuffer_);
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiGetFriendlyProductName returned FALSE");
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiGetDevicePath()
{
TCHAR sBuffer_[512] = { '\0' };
wchar_t buf[MAX_PATH] = { '\0' };
if (LogiIsConnected(m_deviceIndex) && LogiGetDevicePath(m_deviceIndex, buf, MAX_PATH))
{
wsprintf(sBuffer_, TEXT("%s %s"), L"LogiGetDevicePath returned", buf);
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), sBuffer_);
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiGetDevicePath returned FALSE");
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiIsConnected()
{
if (LogiIsConnected(m_deviceIndex))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiIsConnected is TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiIsConnected is FALSE");
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiIsDeviceConnected()
{
if (LogiIsDeviceConnected(m_deviceIndex, LOGI_DEVICE_TYPE_WHEEL))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiIsDeviceConnected is TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiIsDeviceConnected is FALSE");
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiIsManufacturerConnected()
{
if (LogiIsManufacturerConnected(m_deviceIndex, LOGI_MANUFACTURER_LOGITECH))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiIsManufacturerConnected is TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiIsManufacturerConnected is FALSE");
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiIsModelConnected()
{
if (LogiIsModelConnected(m_deviceIndex, LOGI_MODEL_G29))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiIsModelConnected is TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiIsModelConnected is FALSE");
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiButtonTriggered()
{
if (LogiButtonTriggered(m_deviceIndex, 0))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiButtonTriggered returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiButtonTriggered returned FALSE");
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiButtonReleased()
{
if (LogiButtonReleased(m_deviceIndex, 0))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiButtonReleased returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiButtonReleased returned FALSE");
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiButtonIsPressed()
{
if (LogiButtonIsPressed(m_deviceIndex, 0))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiButtonIsPressed returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiButtonIsPressed returned FALSE");
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiGenerateNonLinearValues()
{
// TODO: Add your control notification handler code here
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiGenerateNonLinearValues is not yet implemented");
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiGetNonLinearValue()
{
// TODO: Add your control notification handler code here
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiGetNonLinearValue is not yet implemented");
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiHasForceFeedback()
{
if (LogiHasForceFeedback(m_deviceIndex))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiHasForceFeedback returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiHasForceFeedback returned FALSE");
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiIsPlaying()
{
if (LogiIsPlaying(m_deviceIndex, 0))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiIsPlaying returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiIsPlaying returned FALSE");
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiPlaySpringForce()
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiPlaySpringForce(t_index, m_offsetPercentage, m_saturationPercentage, m_coefficientPercentage);
}
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlaySpringForce is now active on all devices");
}
else
{
if (LogiPlaySpringForce(m_deviceIndex, m_offsetPercentage, m_saturationPercentage, m_coefficientPercentage))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlaySpringForce returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlaySpringForce returned FALSE");
}
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiStopSpringForce()
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiStopSpringForce(t_index);
}
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopSpringForce is now active on all devices");
}
else
{
if (LogiStopSpringForce(m_deviceIndex))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopSpringForce returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopSpringForce returned FALSE");
}
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiPlayConstantForce()
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiPlayConstantForce(t_index, m_magnitudePercentage);
}
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlayConstantForce is now active on all devices");
}
else
{
if (LogiPlayConstantForce(m_deviceIndex, m_magnitudePercentage))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlayConstantForce returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlayConstantForce returned FALSE");
}
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiStopConstantForce()
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiStopConstantForce(t_index);
}
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopConstantForce is now active on all devices");
}
else
{
if (LogiPlayConstantForce(m_deviceIndex, m_magnitudePercentage))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopConstantForce returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopConstantForce returned FALSE");
}
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiPlayDamperForce()
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiPlayDamperForce(t_index, m_coefficientPercentage);
}
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlayDamperForce is now active on all devices");
}
else
{
if (LogiPlayDamperForce(m_deviceIndex, m_coefficientPercentage))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlayDamperForce returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlayDamperForce returned FALSE");
}
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiStopDamperForce()
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiStopDamperForce(t_index);
}
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopDamperForce is now active on all devices");
}
else
{
if (LogiStopDamperForce(m_deviceIndex))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopDamperForce returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopDamperForce returned FALSE");
}
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiPlaySideCollisionForce()
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiPlaySideCollisionForce(t_index, m_magnitudePercentage);
}
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlaySideCollisionForce is now active on all devices");
}
else
{
if (LogiPlaySideCollisionForce(m_deviceIndex, m_magnitudePercentage))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlaySideCollisionForce returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlaySideCollisionForce returned FALSE");
}
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiPlayFrontalCollisionForce()
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiPlayFrontalCollisionForce(t_index, m_magnitudePercentage);
}
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlayFrontalCollisionForce is now active on all devices");
}
else
{
if (LogiPlayFrontalCollisionForce(m_deviceIndex, m_magnitudePercentage))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlayFrontalCollisionForce returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlayFrontalCollisionForce returned FALSE");
}
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiPlayDirtRoadEffect()
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiPlayDirtRoadEffect(t_index, m_magnitudePercentage);
}
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlayDirtRoadEffect is now active on all devices");
}
else
{
if (LogiPlayDirtRoadEffect(m_deviceIndex, m_magnitudePercentage))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlayDirtRoadEffect returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlayDirtRoadEffect returned FALSE");
}
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiStopDirtRoadEffect()
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiStopDirtRoadEffect(t_index);
}
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopDirtRoadEffect is now active on all devices");
}
else
{
if (LogiStopDirtRoadEffect(m_deviceIndex))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopDirtRoadEffect returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopDirtRoadEffect returned FALSE");
}
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiPlayBumpyRoadEffect()
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiPlayBumpyRoadEffect(t_index, m_magnitudePercentage);
}
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlayBumpyRoadEffect is now active on all devices");
}
else
{
if (LogiPlayBumpyRoadEffect(m_deviceIndex, m_magnitudePercentage))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlayBumpyRoadEffect returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlayBumpyRoadEffect returned FALSE");
}
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiStopBumpyRoadEffect()
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiStopBumpyRoadEffect(t_index);
}
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopBumpyRoadEffect is now active on all devices");
}
else
{
if (LogiStopBumpyRoadEffect(m_deviceIndex))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopBumpyRoadEffect returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopBumpyRoadEffect returned FALSE");
}
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiPlaySlipperyRoadEffect()
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiPlaySlipperyRoadEffect(t_index, m_magnitudePercentage);
}
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlaySlipperyRoadEffect is now active on all devices");
}
else
{
if (LogiPlaySlipperyRoadEffect(m_deviceIndex, m_magnitudePercentage))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlaySlipperyRoadEffect returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlaySlipperyRoadEffect returned FALSE");
}
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiStopSlipperyRoadEffect()
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiStopSlipperyRoadEffect(t_index);
}
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopSlipperyRoadEffect is now active on all devices");
}
else
{
if (LogiStopSlipperyRoadEffect(m_deviceIndex))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopSlipperyRoadEffect returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopSlipperyRoadEffect returned FALSE");
}
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiPlaySurfaceEffect()
{
if (LogiPlaySurfaceEffect(m_deviceIndex, 0, m_magnitudePercentage, 100))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlaySurfaceEffect returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlaySurfaceEffect returned FALSE");
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiStopSurfaceEffect()
{
if (LogiStopSurfaceEffect(m_deviceIndex))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopSurfaceEffect returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopSurfaceEffect returned FALSE");
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiPlayCarAirborne()
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiPlayCarAirborne(t_index);
}
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlayCarAirborne is now active on all devices");
}
else
{
if (LogiPlayCarAirborne(m_deviceIndex))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlayCarAirborne returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlayCarAirborne returned FALSE");
}
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiStopCarAirborne()
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiStopCarAirborne(t_index);
}
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopCarAirborne is now active on all devices");
}
else
{
if (LogiStopCarAirborne(m_deviceIndex))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopCarAirborne returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopCarAirborne returned FALSE");
}
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiPlaySoftstopForce()
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiPlaySoftstopForce(t_index, m_usableRangePercentage);
}
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlaySoftstopForce is now active on all devices");
}
else
{
if (LogiPlaySoftstopForce(m_deviceIndex, m_usableRangePercentage))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlaySoftstopForce returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlaySoftstopForce returned FALSE");
}
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiStopSoftstopForce()
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiStopSoftstopForce(t_index);
}
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopSoftstopForce is now active on all devices");
}
else
{
if (LogiStopSoftstopForce(m_deviceIndex))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopSoftstopForce returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopSoftstopForce returned FALSE");
}
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiSetPreferredControllerProperties()
{
// TODO: Add your control notification handler code here
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiControllerPropertiesData data;
ZeroMemory(&data, sizeof(data));
LogiGetCurrentControllerProperties(t_index, data);
data.wheelRange = 900;
LogiSetPreferredControllerProperties(data);
}
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopSoftstopForce is now active on all devices");
}
else
{
LogiControllerPropertiesData data;
ZeroMemory(&data, sizeof(data));
LogiGetCurrentControllerProperties(m_deviceIndex, data);
data.wheelRange = 900;
LogiSetPreferredControllerProperties(data);
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiGetCurrentControllerProperties()
{
if (m_allDevices)
{
for (int t_index = 0; LogiIsConnected(t_index); t_index++)
{
LogiControllerPropertiesData data;
ZeroMemory(&data, sizeof(data));
LogiGetCurrentControllerProperties(t_index, data);
data.wheelRange = 200;
LogiSetPreferredControllerProperties(data);
}
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiStopSoftstopForce is now active on all devices");
}
else
{
LogiControllerPropertiesData data;
ZeroMemory(&data, sizeof(data));
LogiGetCurrentControllerProperties(m_deviceIndex, data);
data.wheelRange = 200;
LogiSetPreferredControllerProperties(data);
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiGetShifterMode()
{
TCHAR sBuffer_[512] = { '\0' };
wsprintf(sBuffer_, TEXT("%s %d"), L"LogiGetShifterMode returned", LogiGetShifterMode(m_deviceIndex));
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), sBuffer_);
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiPlayLeds()
{
if (LogiPlayLeds(m_deviceIndex, 1, 1, 1))
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlayLeds returned TRUE");
}
else
{
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiPlayLeds returned FALSE");
}
}
void CSteeringWheelSimpleDlg::OnBnClickedLogiSteeringShutdown()
{
LogiSteeringShutdown();
::SetWindowText(::GetDlgItem(m_hWnd, IDC_RESULT), L"LogiSteeringShutdown has no return");
}
void CSteeringWheelSimpleDlg::OnEnChangeDevice()
{
m_deviceIndex = GetDlgItemInt(IDC_DEVICE, 0, 0);
}
void CSteeringWheelSimpleDlg::OnBnClickedCheckAllDevices()
{
CWnd *wndDevice = this->GetDlgItem(IDC_DEVICE);
if (m_allDevices)
{
m_allDevices = false;
wndDevice->EnableWindow(true);
}
else
{
m_allDevices = true;
wndDevice->EnableWindow(false);
}
}
void CSteeringWheelSimpleDlg::OnBnClickedCheckFullRange()
{
if (m_fullRange)
{
m_fullRange = false;
}
else
{
m_fullRange = true;
}
}
void CSteeringWheelSimpleDlg::OnBnClickedCheckSpring()
{
LogiSteeringInitialize(true);
if (m_spring)
{
m_spring = false;
}
else
{
m_spring = true;
}
}
void CSteeringWheelSimpleDlg::OnBnClickedCheckConstant()
{
LogiSteeringInitialize(true);
if (m_constant)
{
m_constant = false;
}
else
{
m_constant = true;
}
}
void CSteeringWheelSimpleDlg::OnBnClickedCheckDamper()
{
LogiSteeringInitialize(true);
if (m_damper)
{
m_damper = false;
}
else
{
m_damper = true;
}
}
void CSteeringWheelSimpleDlg::OnBnClickedCheckDirtRoad()
{
LogiSteeringInitialize(true);
if (m_dirtRoad)
{
m_dirtRoad = false;
}
else
{
m_dirtRoad = true;
}
}
void CSteeringWheelSimpleDlg::OnBnClickedCheckBumpyRoad()
{
LogiSteeringInitialize(true);
if (m_bumpyRoad)
{
m_bumpyRoad = false;
}
else
{
m_bumpyRoad = true;
}
}
void CSteeringWheelSimpleDlg::OnBnClickedCheckSlipperyRoad()
{
LogiSteeringInitialize(true);
if (m_slipperyRoad)
{
m_slipperyRoad = false;
}
else
{
m_slipperyRoad = true;
}
}
void CSteeringWheelSimpleDlg::OnBnClickedCheckCarAirborne()
{
LogiSteeringInitialize(true);
if (m_carAirborne)
{
m_carAirborne = false;
}
else
{
m_carAirborne = true;
}
}
void CSteeringWheelSimpleDlg::OnBnClickedCheckSoftstop()
{
LogiSteeringInitialize(true);
if (m_softstop)
{
m_softstop = false;
}
else
{
m_softstop = true;
}
}
|
cb0e0dda3b58e61a3ccd748633991e3c21664a6f | 4fcccffe897b192779d638ff5b3e36051d605209 | /TheGestion/theacceuil.cpp | e74d8d08eb6e6540456e2b570e624f49a813f37a | [] | no_license | Celerier/ProjetAppliCpoo | ff8c46dd53fe5437678c890e6eac4ab7d0e822b6 | 288eb2ef90b388aa4dbfb34e4c41df763d05b827 | refs/heads/master | 2020-03-19T13:38:53.586164 | 2018-06-08T08:19:55 | 2018-06-08T08:19:55 | 136,588,813 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,937 | cpp | theacceuil.cpp | #include "theacceuil.h"
#include "thegeneral.h"
#include "thechoose.h"
#include <QtSql>
#include <QSqlDatabase>
#include <iostream>
#include <QString>
#include <QMainWindow>
#include <QtCore>
#include <QPrinter>
#include <QPdfWriter>
#include <QPainter>
TheAcceuil::TheAcceuil() : QMainWindow()
{
zoneCentrale = new QWidget();
msg = new QLabel("");
login_admin = new QLineEdit();
mdp_admin = new QLineEdit();
mdp_admin->setEchoMode(QLineEdit::Password);
valid_admin = new QPushButton("Valider");
// connect pour admin
QWidget::connect(valid_admin,SIGNAL(clicked()),this,SLOT(co_admin()));
//Creation du formulaire admin
form_admin = new QFormLayout();
form_admin->addRow("Login : ",login_admin);
form_admin->addRow("Password : ",mdp_admin);
form_admin->addRow("Connexion : ",valid_admin);
login_etu = new QLineEdit();
mdp_etu = new QLineEdit();
mdp_etu->setEchoMode(QLineEdit::Password);
valid_etu = new QPushButton("Valider");
// connect pour etu
QWidget::connect(valid_etu,SIGNAL(clicked()),this,SLOT(co_etu()));
//Creation du formulaire admin
form_etu = new QFormLayout();
form_etu->addRow("Login : ",login_etu);
form_etu->addRow("Password : ",mdp_etu);
form_etu->addRow("Connexion : ",valid_etu);
// Le titre
QLabel *titre = new QLabel("The Gestion");
titre->setFont(QFont("Comic Sans MS",20));
// Edition de la page
globalForm = new QGridLayout();
globalForm->addWidget(titre,0,0);
globalForm->addWidget(new QLabel("Admin Log :"),1,0);
globalForm->addWidget(new QLabel("Etudiant Log :"),1,2);
globalForm->addLayout(form_admin,2,1);
globalForm->addLayout(form_etu,2,3);
zoneCentrale->setLayout(globalForm);
setCentralWidget(zoneCentrale);
}
// SLOT
// Test de connexion d'un admin
void TheAcceuil::co_admin() {
QSqlQuery query;
query.exec("SELECT * FROM User WHERE login=\""+login_admin->text()+
"\" AND password=\""+mdp_admin->text()+"\" AND statut=\"admin\" ");
if (query.next()){
msg->setText("Admin Co !");
// Renvoie vers Ecran des choix AVEC un QDialog
TheChoose *test = new TheChoose(query.value(1).toString(),query.value(2).toString());
test->exec();
}
else {
msg->setText("Admin NOT Co ..");
}
globalForm->addWidget(msg,3,1);
}
// Test de connexion d'un étudiant
void TheAcceuil::co_etu() {
QSqlQuery query;
query.exec("SELECT * FROM User WHERE login=\""+login_etu->text()+
"\" AND password=\""+mdp_etu->text()+"\" AND statut=\"etu\" ");
if (query.next()){
msg->setText("Etu Co !");
// Renvoie vers Ecran des choix AVEC un QDialog
TheChoose *test = new TheChoose(query.value(1).toString(),query.value(2).toString());
test->exec();
}
else {
msg->setText("Etu NOT Co ..");
}
globalForm->addWidget(msg,3,2);
}
// Function
// Connexion à la BDD
bool TheAcceuil::BBD_Connexion(){
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setUserName("userBD");
db.setPassword("junior");
db.setDatabaseName("JuniorEntreprise");
if (db.open()) {
msg->setText("BDD Co !");
globalForm->addWidget(msg,0,1);
return true;
}
else {
msg->setText("BDD NOT Co !");
globalForm->addWidget(msg,0,1);
return false;
}
}
/*bool TheAcceuil::BBD_Connexion(){
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setUserName("papuche");
db.setPassword("3600");
db.setDatabaseName("JuniorEntreprise");
if (db.open()) {
msg->setText("BDD Co !");
globalForm->addWidget(msg,0,1);
return true;
}
else {
msg->setText("BDD NOT Co !");
globalForm->addWidget(msg,0,1);
return false;
}
}*/
|
f3bc0f46695a5464a9d8c7f4beac58253e26fec2 | 2d1acb7958a4b551929fe39217ee2fe87859a045 | /net_test/httpserver.cpp | 0af102affe632e79c8db1f925cc72fc01e34515c | [] | no_license | zz198808/tbnet | 7b3ac920a4e205e7970d7610d5998bdb0a2f313f | 73234830f1139bbeb7bb4616d8d7766d4a05d59e | refs/heads/master | 2021-01-20T10:32:40.974795 | 2016-11-28T10:07:41 | 2016-11-28T10:07:41 | 75,140,300 | 1 | 0 | null | 2016-11-30T01:53:38 | 2016-11-30T01:53:38 | null | UTF-8 | C++ | false | false | 2,405 | cpp | httpserver.cpp | /*
* (C) 2007-2010 Taobao Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*
* Version: $Id$
*
* Authors:
* duolong <duolong@taobao.com>
*
*/
#include "tbnet.h"
using namespace tbnet;
/**
* packetµÄserverAdapter
*/
class HttpServerAdapter : public IServerAdapter
{
public:
HttpServerAdapter(IPacketFactory *factory) {
_factory = factory;
}
IPacketHandler::HPRetCode handlePacket(Connection *connection, Packet *packet)
{
HttpRequestPacket *request = (HttpRequestPacket*) packet;
HttpResponsePacket *reply = (HttpResponsePacket*)_factory->createPacket(0);
reply->setStatus(true);
reply->setKeepAlive(request->isKeepAlive());
if (!request->isKeepAlive()) {
connection->setWriteFinishClose(true);
}
char *query = request->getQuery();
if (query) {
reply->setBody(query, strlen(query));
}
request->free();
connection->postPacket(reply);
return IPacketHandler::FREE_CHANNEL;
}
private:
IPacketFactory *_factory;
};
/*
* server ·þÎñÆ÷
*/
class HttpServer {
public:
HttpServer(char *spec);
~HttpServer();
void start();
void stop();
private:
Transport _transport;
char *_spec;
};
HttpServer::HttpServer(char *spec)
{
_spec = strdup(spec);
}
HttpServer::~HttpServer()
{
if (_spec) {
free(_spec);
}
}
void HttpServer::start()
{
DefaultHttpPacketFactory factory;
HttpPacketStreamer streamer(&factory);
HttpServerAdapter serverAdapter(&factory);
IOComponent *ioc = _transport.listen(_spec, &streamer, &serverAdapter);
if (ioc == NULL) {
TBSYS_LOG(ERROR, "listen error.");
return;
}
_transport.start();
_transport.wait();
}
void HttpServer::stop()
{
_transport.stop();
}
HttpServer *_httpServer;
void singalHandler(int seg)
{
_httpServer->stop();
}
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("%s [tcp|udp]:ip:port\n", argv[0]);
return EXIT_FAILURE;
}
HttpServer httpServer(argv[1]);
_httpServer = &httpServer;
signal(SIGTERM, singalHandler);
httpServer.start();
TBSYS_LOG(INFO, "exit.");
return EXIT_SUCCESS;
}
|
68698e3899a9c1f65eefe0aeb4c81791590e5d23 | bb5ae0c5f2fcc917d5c95f5f0886d262d8f55021 | /Source/TheTree/Public/10.Level/TTCommonBattleLevel.h | eff57fd2efadb49d489d3420fce33033c7ad0b64 | [] | no_license | doyoulikerock/TheTree | efa2f634a17826cd78c04647f2d2d4030030e7e7 | fc0d08bb1944a4f3355d6af5db949dd46442d053 | refs/heads/master | 2023-03-19T07:43:35.695149 | 2020-08-25T11:19:37 | 2020-08-25T11:19:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 241 | h | TTCommonBattleLevel.h | #pragma once
#include "TTBaseLevel.h"
#include "TTCommonBattleLevel.generated.h"
UCLASS()
class THETREE_API ATTCommonBattleLevel : public ATTBaseLevel
{
GENERATED_BODY()
private:
void ClearEvents();
public:
ATTCommonBattleLevel();
};
|
be7649ff3e4fabd058e59260d35a13cf7838387f | cffbc9b2dcb4f50719148e8c8798279500d8ac2a | /main.cpp | 8a033858280ecfb86eacecd07e15d0495bb12526 | [] | no_license | sllujaan/stack_cpp | 9c5e341637e2172e9199ebf5216cba458a8914de | 035641945b39b533a40689bc5f5f663fa033638d | refs/heads/master | 2022-06-18T09:58:04.802077 | 2020-05-12T12:48:59 | 2020-05-12T12:48:59 | 263,326,540 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 654 | cpp | main.cpp | using namespace std;
#include<iostream>
#include"STACK.h"
int main(int argc, char *argv[]) {
int arr[] = {5, 6, 7};
int len = sizeof(arr) / sizeof(*arr);
//STACK<int> _stack;
try{
//STACK<int, 5> _stack = arr;
//print(_stack);
STACK<int, 5> _stack = 1;
_stack.push(2);
_stack.push(3);
int poped = _stack.pop();
poped = _stack.pop();
poped = _stack.pop();
poped = _stack.pop();
poped = _stack.pop();
cout<<"poped = "<<poped<<endl;
_stack.push(2);
_stack.push(3);
print(_stack);
}
catch(Exception e) {
cout<<e.msg<<endl;
}
//int arr[] = {};
//int len = siz(arreof)/sizeof(arr[0]);
//cout<<len<<endl;
}
|
9d6709d8ce249c2c43d081de2d3cda508c5be3bf | 81361fbb260f3a43f2dfd05474c1bb06c5160d9c | /CodeChef/2014 July Challange/RETPO Reach The Point.cpp | fab8e8ef78dcf97cd4e10a4d00b6f86fdfabb0ee | [] | no_license | enamcse/ACM-Programming-Codes | 9307a22aafb0be6d8f64920e46144f2f813c493a | 70b57c35ec551eae6322959857b3ac37bcf615fa | refs/heads/master | 2022-10-09T19:35:54.894241 | 2022-09-30T01:26:24 | 2022-09-30T01:26:24 | 33,211,745 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,609 | cpp | RETPO Reach The Point.cpp | //#include <bits/stdc++.h>
//#define _ ios_base::sync_with_stdio(0);cin.tie(0);
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <queue>
#include <vector>
#include <algorithm>
#include <cctype>
#include <fstream>
#include <map>
#include <list>
#include <set>
#include <string>
#include <stack>
#include <bitset>
#define sz 50005
#define pb(a) push_back(a)
#define pp pop_back()
#define ll long long
#define fread freopen("input.txt","r",stdin)
#define fwrite freopen("output.txt","w",stdout)
#define inf (1e9)
#define chng(a,b) a^=b^=a^=b;
#define clr(abc,z) memset(abc,z,sizeof(abc))
#define PI acos(-1)
#define fr(i,a,b) for(i=a;i<=b;i++)
#define print1(a) cout<<a<<endl
#define print2(a,b) cout<<a<<" "<<b<<endl
#define print3(a,b,c) cout<<a<<" "<<b<<" "<<c<<endl
#define mod 1000000007
using namespace std;
int main()
{
#ifdef ENAM
// fread;
// fwrite;
#endif // ENAM
int t, n, m, cas=1;
ll x, y, mn, mov, now;
scanf("%d", &t);
while(t--)
{
mov = 0LL;
scanf("%lld %lld", &x, &y);
x = abs(x);
y = abs(y);
mn = min(x,y);
mov = mn*2LL;
x-=mn;
y-=mn;
if(x)
{
now = (x>>1);
now<<=1;
mov+=(now<<1);
if(x!=now) mov+=3;
}
else if(y)
{
now = (y>>1);
now<<=1;
mov+=(now<<1);
if(y!=now) mov+=1;
}
printf("%lld\n", mov);
}
return 0;
}
|
0b268d3e2f3fc4b360d0c6a8cfae0ceb40cd1831 | 293c244b17524210780b4fcb644c03d5cd6f1729 | /src/bugengine/introspect/src/dbcontext.cc | 4cf5103d040508a64c0758951848fb9c4c29a1b6 | [
"BSD-3-Clause"
] | permissive | bugengine/BugEngine | 380c0aee8ba48a07e5b820877352f922cbba0a21 | 1b3831d494ee06b0bd74a8227c939dd774b91226 | refs/heads/master | 2021-08-08T00:20:11.200535 | 2021-07-31T13:53:24 | 2021-07-31T13:53:24 | 20,094,089 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,118 | cc | dbcontext.cc | /* BugEngine <bugengine.devel@gmail.com>
see LICENSE for detail */
#include <bugengine/introspect/stdafx.h>
#include <bugengine/introspect/dbcontext.hh>
namespace BugEngine { namespace Meta { namespace AST {
DbContext::DbContext(minitl::Allocator& arena, ref< Folder > rootFolder)
: rootNamespace(ref< Namespace >::create(arena, byref(arena)))
, rootFolder(rootFolder)
, messages(arena)
, errorCount()
{
}
DbContext::DbContext(minitl::Allocator& arena, ref< Namespace > ns, ref< Folder > rootFolder)
: rootNamespace(ns)
, rootFolder(rootFolder)
, messages(arena)
, errorCount()
{
}
void DbContext::error(weak< const Node > owner, const Message::MessageType& error)
{
messages.push_back(Message(owner, error, logError));
errorCount++;
}
void DbContext::warning(weak< const Node > owner, const Message::MessageType& warning)
{
messages.push_back(Message(owner, warning, logWarning));
}
void DbContext::info(weak< const Node > owner, const Message::MessageType& info)
{
messages.push_back(Message(owner, info, logInfo));
}
}}} // namespace BugEngine::Meta::AST
|
eff364f65a4cb4d9b3a01b7f3ec83d3cc075c676 | e6c35a12e6bae5b1ac3a7583365e657c516f74a5 | /Comm/source/IpMaps.cpp | 2d1dba26593775fa6a1cecf85179588362b9f9d7 | [] | no_license | radtek/zephyr-server | 1675f7693c8b19ad59eb98b942bab1372efdc10e | 44b7faf06bb3ce6cc3736cce9011234d0e705443 | refs/heads/master | 2020-06-08T11:45:43.412677 | 2019-04-19T14:40:10 | 2019-04-19T14:40:10 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 8,947 | cpp | IpMaps.cpp | #include "IpMaps.h"
#ifdef _WIN32
#include "winsock2.h"
#endif
#include "stdio.h"
#include "SettingFile.h"
#include "SysMacros.h"
namespace Zephyr
{
CIpMap::CIpMap()
{
m_nrOfNodes = 0;
m_nrOfVirtualIp = 0;
m_localNodeId = 0;
m_localVirtualIp = 0;
m_pVirtualIps = NULL;
m_pRoutes = NULL;
m_nNrOfMapItem = 0;
}
int CIpMap::ReadIpMapItem4Node(void *pFile,int nVip,CIpMapItem *pItem)
{
char pMain[16];
sprintf(pMain,"NODE%d",nVip);
CSettingFile &file = *((CSettingFile*)pFile);
const char* pIp = file.GetString(pMain,"myIp");
unsigned int myIp = 0;
if (pIp)
{
myIp = inet_addr(pIp);
}
else
{
return -1;
}
unsigned int remoteIp = 0;
pIp = file.GetString(pMain,"remoteIp");
if (pIp)
{
remoteIp = inet_addr(pIp);
}
else
{
return -1;
}
unsigned short myPort = 0;
unsigned short remotePort = 0;
myPort = file.GetInteger(pMain,"myPort");
remotePort = file.GetInteger(pMain,"remotePort");
if ((remotePort == myPort)&&(remoteIp==myIp))
{
return -1;
}
pItem->m_tKey.Init(remoteIp,myIp,remotePort,myPort);
return SUCCESS;
}
TInt32 CIpMap::Init(const TChar *pConfigName,IfConnection *pSelf)
{
CSettingFile settingFile;
if (!settingFile.LoadFromFile(pConfigName))
{
return NULL_POINTER;
}
m_nrOfNodes = settingFile.GetInteger("MAIN","nrOfNodes");
m_nrOfVirtualIp = settingFile.GetInteger("MAIN","nrOfVirtualIp");
m_localNodeId = settingFile.GetInteger("MAIN","localNodeId");
m_localVirtualIp = settingFile.GetInteger("MAIN","localVirtualIp");
m_nNrOfMapItem = m_nrOfVirtualIp;
if (m_nrOfNodes > 1)
{
for (int i=0;i<m_nrOfNodes;++i)
{
if (i == m_localNodeId)
{
continue;
}
char buff[64];
sprintf(buff,"NODE%d",i);
if (m_localVirtualIp == settingFile.GetInteger(buff,"localVIP"))
{
++m_nNrOfMapItem;
}
}
}
//if (m_nrOfNodes > 0)
{
NEW(m_pVirtualIps,CIpMapItem,(m_nNrOfMapItem));
if (!m_pVirtualIps)
{
return OUT_OF_MEM;
}
}
TUInt32 uRemoteIp;
TUInt32 uMyIp;
TUInt16 uMyPort;
TUInt16 uRemotePort;
char szMain[16];
sprintf(szMain,"VIP%d",m_localVirtualIp);
const char* pIp = settingFile.GetString(szMain,"ip");
if (pIp)
{
uMyIp = inet_addr(pIp);
}
else
{
return -1;
}
unsigned short uLocalPort = settingFile.GetInteger(szMain,"port");
for (int i=0;i<m_nrOfVirtualIp;++i)
{
char szMain[16];
sprintf(szMain,"VIP%d",m_localVirtualIp);
m_pVirtualIps[i].m_nNodeId = m_localNodeId;
m_pVirtualIps[i].m_nVirtualIp = i;
CConPair &iPair = m_pVirtualIps[i].m_tKey;
pIp = settingFile.GetString(szMain,"ip");
if (pIp)
{
uRemoteIp = inet_addr(pIp);
}
else
{
return -1;
}
if (IsPostive(i)) //是我主動連對端
{
//所以端口號是對端的監聽端口
char szRemoteMain[16];
sprintf(szRemoteMain,"VIP%d",i);
uRemotePort = settingFile.GetInteger(szRemoteMain,"port");
uMyPort = uRemotePort + m_localVirtualIp - i;
}
else //是我被動
{
uMyPort = uLocalPort;
uRemotePort = uLocalPort + i - m_localVirtualIp;
}
iPair.Init(uRemoteIp,uMyIp,uRemotePort,uMyPort);
if (i == m_localVirtualIp)
{
AddListeningExisted(&m_pVirtualIps[i],i);
}
//if (i)
//只监听一个
}
int usedNode = 0;
//获取我的node信息
if (m_nrOfNodes > 1)
{
m_pRoutes = new TUInt32[m_nrOfNodes];
memset(m_pRoutes,0,(sizeof(TUInt32)*m_nrOfNodes));
m_pRoutes[m_localNodeId] = m_localVirtualIp;
for (int i=0;i<m_nrOfNodes;++i)
{
if (i == m_localNodeId)
{
m_pRoutes[i] = 0;
continue;
}
char buff[32];
sprintf(buff,"NODE%d",i);
if (m_localVirtualIp == settingFile.GetInteger(buff,"localVIP"))
{
m_pRoutes[i] = m_nrOfVirtualIp + usedNode;
if (ReadIpMapItem4Node(&settingFile,i,&m_pVirtualIps[m_pRoutes[i]]) < 0)
{
return -1;
}
m_pVirtualIps[m_pRoutes[i]].m_nNodeId = i;
m_pVirtualIps[m_pRoutes[i]].m_nVirtualIp = 0;
++usedNode;
}
else
{
m_pRoutes[i] = settingFile.GetInteger(buff,"localVIP");
}
AddListeningExisted(&m_pVirtualIps[m_pRoutes[i]],m_pRoutes[i]);
}
}
//不try了
m_pVirtualIps[m_localVirtualIp].m_pIfConnection = pSelf;
return SUCCESS;
}
TInt32 CIpMap::InitWithConfig(const TChar *pConfig,IfConnection *pSelf)
{
CSettingFile settingFile;
if (!settingFile.Load(pConfig))
{
return NULL_POINTER;
}
m_nrOfNodes = settingFile.GetInteger("MAIN","nrOfNodes");
m_nrOfVirtualIp = settingFile.GetInteger("MAIN","nrOfVirtualIp");
m_localNodeId = settingFile.GetInteger("MAIN","localNodeId");
m_localVirtualIp = settingFile.GetInteger("MAIN","localVirtualIp");
m_nNrOfMapItem = m_nrOfVirtualIp;
if (m_nrOfNodes > 1)
{
for (int i=0;i<m_nrOfNodes;++i)
{
if (i == m_localNodeId)
{
continue;
}
char buff[64];
sprintf(buff,"NODE%d",i);
if (m_localVirtualIp == settingFile.GetInteger(buff,"localVIP"))
{
++m_nNrOfMapItem;
}
}
}
//if (m_nrOfNodes > 0)
{
NEW(m_pVirtualIps,CIpMapItem,(m_nNrOfMapItem));
if (!m_pVirtualIps)
{
return OUT_OF_MEM;
}
}
TUInt32 uRemoteIp;
TUInt32 uMyIp;
TUInt16 uMyPort;
TUInt16 uRemotePort;
char szMain[16];
sprintf(szMain,"VIP%d",m_localVirtualIp);
const char* pIp = settingFile.GetString(szMain,"ip");
if (pIp)
{
uMyIp = inet_addr(pIp);
}
else
{
return -1;
}
unsigned short uLocalPort = settingFile.GetInteger(szMain,"port");
for (int i=0;i<m_nrOfVirtualIp;++i)
{
char szMain[16];
sprintf(szMain,"VIP%d",m_localVirtualIp);
m_pVirtualIps[i].m_nNodeId = m_localNodeId;
m_pVirtualIps[i].m_nVirtualIp = i;
CConPair &iPair = m_pVirtualIps[i].m_tKey;
pIp = settingFile.GetString(szMain,"ip");
if (pIp)
{
uRemoteIp = inet_addr(pIp);
}
else
{
return -1;
}
if (IsPostive(i)) //是我主動連對端
{
//所以端口號是對端的監聽端口
char szRemoteMain[16];
sprintf(szRemoteMain,"VIP%d",i);
uRemotePort = settingFile.GetInteger(szRemoteMain,"port");
uMyPort = uRemotePort + m_localVirtualIp - i;
}
else //是我被動
{
uMyPort = uLocalPort;
uRemotePort = uLocalPort + i - m_localVirtualIp;
}
iPair.Init(uRemoteIp,uMyIp,uRemotePort,uMyPort);
if (i == m_localVirtualIp)
{
AddListeningExisted(&m_pVirtualIps[i],i);
}
//if (i)
//只监听一个
}
int usedNode = 0;
//获取我的node信息
if (m_nrOfNodes > 1)
{
m_pRoutes = new TUInt32[m_nrOfNodes];
memset(m_pRoutes,0,(sizeof(TUInt32)*m_nrOfNodes));
m_pRoutes[m_localNodeId] = m_localVirtualIp;
for (int i=0;i<m_nrOfNodes;++i)
{
if (i == m_localNodeId)
{
m_pRoutes[i] = 0;
continue;
}
char buff[32];
sprintf(buff,"NODE%d",i);
if (m_localVirtualIp == settingFile.GetInteger(buff,"localVIP"))
{
m_pRoutes[i] = m_nrOfVirtualIp + usedNode;
if (ReadIpMapItem4Node(&settingFile,i,&m_pVirtualIps[m_pRoutes[i]]) < 0)
{
return -1;
}
m_pVirtualIps[m_pRoutes[i]].m_nNodeId = i;
m_pVirtualIps[m_pRoutes[i]].m_nVirtualIp = 0;
++usedNode;
}
else
{
m_pRoutes[i] = settingFile.GetInteger(buff,"localVIP");
}
AddListeningExisted(&m_pVirtualIps[m_pRoutes[i]],m_pRoutes[i]);
}
}
//不try了
m_pVirtualIps[m_localVirtualIp].m_pIfConnection = pSelf;
return SUCCESS;
}
}
|
a7d6debbf55761c35fa55b9cd5785cb9f1600ae9 | 7cc03603e365c30a3b751498775a0b8a10d58456 | /tests/Utilities/ConnEx/ConnEx.cpp | 4d83e571c0a6b194215d13c25e201401f85ba05c | [
"MIT"
] | permissive | wes-b/Azure-Kinect-Sensor-SDK-1 | f079358c4cecc598741251016a008d368d96a552 | cd55fd4b5aac4a26ca8918fc79550f3d5752d084 | refs/heads/develop | 2020-05-23T19:22:09.653115 | 2019-05-15T22:06:11 | 2019-05-15T22:06:11 | 186,911,034 | 4 | 1 | MIT | 2020-02-05T17:09:58 | 2019-05-15T22:26:28 | C++ | UTF-8 | C++ | false | false | 7,525 | cpp | ConnEx.cpp | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "ConnEx.h"
#define VC_EXTRALEAN
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <stdio.h>
#include <k4ainternal/logging.h>
#define CONNEX_CMD_PORT "port"
#define CONNEX_CMD_VOLTS "volts"
#define CONNEX_CMD_AMPS "amps"
#define CONNEX_CMD_VERSION "version"
// This is the version expected to come back from the connection exerciser.
// This consists of the hardcoded HMD Validation Kit version and the type of shield.
#define CONN_EX_VERSION "0108"
typedef struct connection_exerciser_internal_t
{
HANDLE serialHandle;
} connection_exerciser_internal_t;
static HANDLE OpenComPort(LPCSTR comPort)
{
// Open serial port
HANDLE serialHandle;
serialHandle = CreateFile(comPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (serialHandle == INVALID_HANDLE_VALUE || serialHandle == NULL)
{
DWORD lastError = GetLastError();
if (lastError != ERROR_FILE_NOT_FOUND)
{
LOG_ERROR("Failed to open %s. Last Error=%d", comPort, lastError);
}
return INVALID_HANDLE_VALUE;
}
// Do some basic settings
DCB serialParams = { 0 };
serialParams.DCBlength = sizeof(serialParams);
if (!GetCommState(serialHandle, &serialParams))
{
LOG_ERROR("GetCommState Failed. Last Error=%d", comPort, GetLastError());
CloseHandle(serialHandle);
return INVALID_HANDLE_VALUE;
}
serialParams.BaudRate = CBR_9600;
serialParams.ByteSize = 8;
serialParams.StopBits = ONESTOPBIT;
serialParams.Parity = NOPARITY;
serialParams.fDtrControl = DTR_CONTROL_DISABLE;
serialParams.fRtsControl = RTS_CONTROL_DISABLE;
if (!SetCommState(serialHandle, &serialParams))
{
LOG_ERROR("SetCommState Failed. Last Error=%d", comPort, GetLastError());
CloseHandle(serialHandle);
return INVALID_HANDLE_VALUE;
}
// Set timeouts
COMMTIMEOUTS timeout = { 0 };
if (!GetCommTimeouts(serialHandle, &timeout))
{
LOG_ERROR("GetCommTimeouts Failed. Last Error=%d", comPort, GetLastError());
CloseHandle(serialHandle);
return INVALID_HANDLE_VALUE;
}
timeout.ReadTotalTimeoutConstant = 500;
if (!SetCommTimeouts(serialHandle, &timeout))
{
LOG_ERROR("SetCommTimeouts Failed. Last Error=%d", comPort, GetLastError());
CloseHandle(serialHandle);
return INVALID_HANDLE_VALUE;
}
return serialHandle;
}
connection_exerciser::connection_exerciser()
{
state = new (std::nothrow) connection_exerciser_internal_t();
}
connection_exerciser::~connection_exerciser()
{
if (state->serialHandle != INVALID_HANDLE_VALUE)
{
CloseHandle(state->serialHandle);
}
delete state;
}
k4a_result_t connection_exerciser::set_usb_port(int port)
{
char usbPort[16] = { 0 };
if (sprintf_s(usbPort, "%d", port) == -1)
{
LOG_ERROR("Failed to generate the USB port command.");
return K4A_RESULT_FAILED;
}
return TRACE_CALL(send_command(CONNEX_CMD_PORT, usbPort));
}
int connection_exerciser::get_usb_port()
{
char buffer[16] = { 0 };
if (K4A_FAILED(TRACE_CALL(send_command(CONNEX_CMD_PORT, nullptr, buffer))))
{
return -1;
}
int rawValue;
sscanf_s(buffer, "%d", &rawValue);
return rawValue;
}
float connection_exerciser::get_voltage_reading()
{
char buffer[16] = { 0 };
if (K4A_FAILED(TRACE_CALL(send_command(CONNEX_CMD_VOLTS, nullptr, buffer))))
{
return -1;
}
int rawValue;
if (sscanf_s(buffer, "%d", &rawValue) == -1)
{
LOG_ERROR("Failed to parse response.");
return -1;
}
return (float)(rawValue / 100.0);
}
float connection_exerciser::get_current_reading()
{
char buffer[16] = { 0 };
if (K4A_FAILED(TRACE_CALL(send_command(CONNEX_CMD_AMPS, nullptr, buffer))))
{
return -1;
}
int rawValue;
if (sscanf_s(buffer, "%d", &rawValue) == -1)
{
LOG_ERROR("Failed to parse response.");
return -1;
}
// The "1000" digit appears to be a sign digit. A negative number would be 1000 + the value. With this scheme
// "negative zero" is possible and needs to be converted to 0.
if (rawValue >= 1000)
{
rawValue = 1000 - rawValue;
}
return (float)(rawValue / 100.0);
}
template<size_t size>
inline k4a_result_t connection_exerciser::send_command(const char *command,
const char *parameter,
char (&response)[size])
{
return send_command(command, parameter, response, size);
}
inline k4a_result_t connection_exerciser::send_command(const char *command, const char *parameter)
{
return send_command(command, parameter, nullptr, 0);
}
k4a_result_t connection_exerciser::send_command(const char *command, const char *parameter, char *response, size_t size)
{
RETURN_VALUE_IF_ARG(K4A_RESULT_FAILED, command == NULL);
DWORD command_length = 0;
DWORD bytes_transfered = 0;
char buffer[1024] = { 0 };
if (parameter != nullptr)
{
if ((command_length = sprintf_s(buffer, "%s %s\r\n", command, parameter)) == -1)
{
LOG_ERROR("Failed to generate the command.");
return K4A_RESULT_FAILED;
}
}
else
{
if ((command_length = sprintf_s(buffer, "%s\r\n", command)) == -1)
{
LOG_ERROR("Failed to generate the command.");
return K4A_RESULT_FAILED;
}
}
if (WriteFile(state->serialHandle, buffer, command_length, nullptr, nullptr) == 0)
{
LOG_ERROR("WriteFile failed with %d", GetLastError());
return K4A_RESULT_FAILED;
}
buffer[0] = '\0';
if (ReadFile(state->serialHandle, buffer, sizeof(buffer), &bytes_transfered, nullptr) == 0)
{
LOG_ERROR("ReadFile failed with %d", GetLastError());
return K4A_RESULT_FAILED;
}
buffer[bytes_transfered] = '\0';
if (response != nullptr)
{
strcpy_s(response, size, buffer);
for (size_t i = strlen(response) - 1; i >= 0; --i)
{
if (response[i] == '\n' || response[i] == '\r')
{
response[i] = '\0';
}
else
{
break;
}
}
}
return K4A_RESULT_SUCCEEDED;
}
k4a_result_t connection_exerciser::find_connection_exerciser()
{
LOG_INFO("Searching for a connection exerciser...", 0);
char comPort[16] = { 0 };
char buffer[1024] = { 0 };
if (state->serialHandle != INVALID_HANDLE_VALUE)
{
CloseHandle(state->serialHandle);
state->serialHandle = INVALID_HANDLE_VALUE;
}
for (int i = 1; i < 10; ++i)
{
sprintf_s(comPort, "COM%d", i);
LOG_INFO("Opening %s", comPort);
state->serialHandle = OpenComPort(comPort);
if (state->serialHandle != INVALID_HANDLE_VALUE)
{
if (K4A_SUCCEEDED(TRACE_CALL(send_command(CONNEX_CMD_VERSION, nullptr, buffer))) &&
strcmp(buffer, CONN_EX_VERSION) == 0)
{
return K4A_RESULT_SUCCEEDED;
}
else
{
CloseHandle(state->serialHandle);
state->serialHandle = INVALID_HANDLE_VALUE;
}
}
}
return K4A_RESULT_FAILED;
}
|
7cc92f1a2839ddfa7add178be89cff8a6bab0e61 | 23ec6adce704bff40d04cd6fc0ba446375405b68 | /September_Leetcode_Challenge/repeated_substring_pattern-3.cpp | 83edaf19ae55770e64367299a92c675830e206ee | [] | no_license | amoghrajesh/Coding | 1845be9ea8df2d13d2a21ebef9ee6de750c8831d | a7dc41a4963f97dfb62ee4b1cab5ed80043cfdef | refs/heads/master | 2023-08-31T10:10:48.948129 | 2023-08-30T15:04:02 | 2023-08-30T15:04:02 | 267,779,618 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 498 | cpp | repeated_substring_pattern-3.cpp | class Solution {
public:
bool repeatedSubstringPattern(string s) {
int n = s.size();
for(int i = n / 2; i > 0; i--){
if(n % i == 0){
int reps = n / i;
string r = s.substr(0, i);
string x = r;
for(int j = 0; j < reps - 1; j++){
x += r;
}
if(x == s){
return true;
}
}
}
return false;
}
}; |
ab09102cb6a91c497809b9ef69fba6d118d9d9a9 | 472126e884b0061d7d700a8422e27f1a9b4fae48 | /zlink/zlink_inner.h | f2f93bc7c63b9303ad7921eca196a57d8ae9e7f8 | [] | no_license | shizhongNice/udt-link | 9f1f7c216c4e4f1a5c21eb584037f19ac55c51ea | bfd4f29643baa2e26c80b6b2766c97b7515ff62b | refs/heads/main | 2022-12-19T11:02:18.367648 | 2020-09-29T07:16:11 | 2020-09-29T07:16:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,404 | h | zlink_inner.h | #ifndef ZLINK_INNER_H
#define ZLINK_INNER_H
#include "ZLink.h"
#include "udt.h"
#include "utils.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <map>
using namespace std;
#define CLIENT_SESSION_ID (0)
#define ZLINK_SESSION_EXTERN_CHANS (4)
class LinkSession
{
public:
LinkSession()
{
sessionID = 0;
strClientIP = "";
strClientSN = "";
sockExternChans.resize(ZLINK_SESSION_EXTERN_CHANS);
}
SYSSOCKET sessionID; //会话ID
std::string strClientIP; //会话设备IP
std::string strClientSN; //会话设备序列号
UDTSOCKET sockAudio; //会话音频通道
UDTSOCKET sockVideo; //会话视频通道
vector<UDTSOCKET> sockExternChans; //扩展通道
};
class LinkManager
{
public:
LinkManager()
{
m_nRole = ZLINK_UNKNOWN;
m_strNetCardName = "";
m_strLocalIP = "";
m_nLocalPort = 0;
m_isInit = false;
m_eventCallBackFunc = NULL;
m_strUid = "";
m_strPwd = "";
m_strServerIP = "";
m_nServerPort = 0;
m_trdSearch = 0;
m_nTcpServer = 0;
m_nUdtServer = 0;
m_nSessionMaxCount = 10;
m_mapSessions.clear();
}
//![1] 服务端客户端通用属性 在ZLink_Init初始化除了UID和passwd
ZLINK_ROLE m_nRole; //Zlink要初始化的角色
std::string m_strNetCardName; //本地网卡名称
std::string m_strLocalIP; //本地IP
int m_nLocalPort; //本地绑定端口
bool m_isInit; //是否已经完成主机或客户端初始化
ZL_PF_ST_EVT m_eventCallBackFunc; //会话事件回调函数
std::string m_strUid; //会话验证用户名
std::string m_strPwd; //会话验证密码
//![2] 客户端属性 ZLink_Client_Init初始化
std::string m_strServerIP; //客户端填充服务端的IP
int m_nServerPort; //客户端填充服务端的Port
// LinkSession m_clientInfo;
//![3] 服务端属性 ZLink_Host_Init初始化
pthread_t m_trdSearch; //服务器局域网广播线程
SYSSOCKET m_nTcpServer; //服务器TCP监听socket
UDTSOCKET m_nUdtServer; //服务器UDT监听socket
int m_nSessionMaxCount; //最大会话数量
map<int, LinkSession> m_mapSessions; //服务端会话信息表
};
extern LinkManager *_g_link;
//! 检测zlink是否已经初始化
#define CHECK_ZLINK_LIB_INIT \
do{ \
if(_g_link == NULL) \
return ZLINK_ERR_NOINIT; \
}while(0)
//! 检测zlink是否初始化为HOST
#define CHECK_ZLINK_ROLE_HOST \
do{ \
if(_g_link->m_nRole != ZLINK_HOST) \
return ZLINK_ERR_NOHOST; \
}while(0)
//! 检测zlink是否初始化为CLIENT
#define CHECK_ZLINK_ROLE_CLIENT \
do{ \
if(_g_link->m_nRole != ZLINK_CLIENT) \
return ZLINK_ERR_NOCLIENT; \
}while(0)
//! 检测zlink是否已经客户端或者主机初始化
#define CHECK_ZLINK_ROLE_INIT \
do{ \
if(_g_link->m_isInit != true) \
return ZLINK_ERR_ROLE_NOINIT; \
}while(0)
//! 检测session是否存在
#define CHECK_ZLINK_SESSION(nSid) \
do{ \
if(0 == _g_link->m_mapSessions.count(nSid)) \
{ return ZLINK_ERR_NOSESSION; } \
}while(0)
int createServerSocket(LinkManager *link);
int closeServerSocket(LinkManager *link);
int setServerListen(LinkManager *link);
int AvFrameDataRecv(int nAVCid, char *pFrameData, int nFrameDataMaxSize, char *pFrameInfo, int nFrameInfoMaxSize, int nTimeoutMs, ZLINK_CHANNEL_TYPE chn);
int AvFrameDataSend(int nAVCid, char *pFrameData, int nFrameDataMaxSize, char *pFrameInfo, int nFrameInfoMaxSize, int nTimeoutMs, ZLINK_CHANNEL_TYPE chn);
int avHeaderSend(int nSid, ZLINK_CHANNEL_TYPE chn,int nTimeoutMs,int nFrameInfoSize, int nFrameDataSize);
int avHeaderRecv(int nSid, ZLINK_CHANNEL_TYPE chn,int nTimeoutMs,int *nFrameInfoSize, int *nFrameDataSize);
#endif // ZLINK_INNER_H
|
e1bae0ea61d5a9c15bff415caf856f9b16507aec | 63a75aa5ff831440062cf7710c8e2d29b5a104a3 | /A4D/Engine/CameraMove.cpp | dfeb9ae8ff2806b05ae2c6ed00eca16483b2fda3 | [
"MIT"
] | permissive | 365082218/A4D | f544db96cb808287e70dc54824877f264c4f4b2e | 4c34c53c5cc0eeaaffface9f60ed114b8388c2c0 | refs/heads/master | 2020-11-27T11:50:19.753133 | 2020-01-06T03:55:28 | 2020-01-06T03:55:28 | 229,427,023 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 1,926 | cpp | CameraMove.cpp | #include "stdafx.h"
#include "CameraMove.h"
#include <QtGui/qevent.h>
#include <d3d9.h>
#include <d3dx9tex.h>
#include "Pool.h"
#include "Time.h"
#include "GameObject.h"
#include "Transform.h"
//摄像机控制脚本
REGISTER_CLASS(CameraMove)
CameraMove::CameraMove()
{
intensity = 5;
}
CameraMove::~CameraMove()
{
}
void CameraMove::Update()
{
}
void CameraMove::OnKeyDown(KeyEvent * context)
{
//6个方向的平移
if (context->keyCode == Qt::Key_W)
{
D3DXVECTOR3 vec = gameObject->transform->forward * Time::deltaTime * intensity;
gameObject->transform->Translate(vec);
}
if (context->keyCode == Qt::Key_S)
{
D3DXVECTOR3 vec = gameObject->transform->forward * -Time::deltaTime * intensity;
gameObject->transform->Translate(vec);
}
if (context->keyCode == Qt::Key_A)
gameObject->transform->Translate(-intensity * Time::deltaTime, 0, 0);
if (context->keyCode == Qt::Key_D)
gameObject->transform->Translate(intensity * Time::deltaTime, 0, 0);
if (context->keyCode == Qt::Key_E)
gameObject->transform->Translate(0, intensity * Time::deltaTime, 0);
if (context->keyCode == Qt::Key_Q)
gameObject->transform->Translate(0, -intensity * Time::deltaTime, 0);
//3个轴向的旋转
if (context->keyCode == Qt::Key_R)
gameObject->transform->Rotate(D3DXVECTOR3(0, 1, 0), Time::deltaTime * intensity);//绕Y轴
if (context->keyCode == Qt::Key_T)
gameObject->transform->Rotate(D3DXVECTOR3(1, 0, 0), Time::deltaTime * intensity);//绕X轴
if (context->keyCode == Qt::Key_Y)
gameObject->transform->Rotate(D3DXVECTOR3(0, 0, 1), Time::deltaTime * intensity);//绕Z轴
}
void CameraMove::OnKeyUp(KeyEvent * context)
{
}
void CameraMove::OnMouseDown(MouseEvent * context)
{
}
void CameraMove::OnMouseUp(MouseEvent * context)
{
}
void CameraMove::OnEnable(AEvent * context)
{
__super::OnEnable(context);
}
void CameraMove::OnDisable(AEvent * context)
{
__super::OnDisable(context);
} |
88000efdbaa6e9d28586e2ef1ceb20e54785099d | 4b691575edf0eff7d0c85f79da9b4c89b94cbf2b | /Final/Demo/Include/Resource.h | da08d149021d2ac93002a1c57e67094144d0a631 | [] | no_license | Ikutzu/ZzZ--engine | bf7c421d4960766c8d43acfc943f7aa3ff2a6bf3 | 5be359fb87a8ede679fa1e8fae8e501d4c08f2fb | refs/heads/master | 2020-05-29T15:20:35.341969 | 2014-12-12T10:43:48 | 2014-12-12T10:43:48 | 23,692,668 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 248 | h | Resource.h | #pragma once
#include <string>
namespace ZZZ
{
class Resource
{
public:
Resource();
Resource(std::string fn);
~Resource();
std::string getFileName();
virtual std::string getFullPath() = 0;
protected:
std::string fileName;
};
}
|
c5efc54597f45a352d349cc5fb7ed57bc3dd1f24 | 5052cec0f5a138914a2b1d807e706f9406e63b25 | /xcode/src/GuiObjects/NavigationBarObject.h | 83d1d005916025f4014c9e53c618f5333b5ce0a9 | [] | no_license | prudolph/cinder_gui_interface | 486626db8c695d22ce9dde3fdd4fc4290be6db88 | fc73e7cc01453d9f423848afb64f71ed63c812d8 | refs/heads/master | 2021-01-01T18:02:09.501418 | 2013-07-23T19:38:33 | 2013-07-23T19:38:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 750 | h | NavigationBarObject.h | //
// NavigationBarObject.h
// guiObjects
//
// Created by Paul Rudolph on 7/10/13.
//
//
#pragma once
#include "NavigationObject.h"
#include <map>
using namespace std;
class NavigationBarObject:public GuiObject{
public:
NavigationBarObject();
void setup(Rectf containerRect, boost::function<void(GuiObject*)> fn);
void objectDraw();
void addChild(GuiObject* o);
void navButtonSelected(GuiObject *selectedObject);
void organizeChildren();
float nbBufferSz;
ColorA nbContainerColor;
virtual void touchesBeganHandler();
virtual void touchesMovedHandler();
virtual void touchesEndedHandler();
protected:
vector<GuiObject*> nbChildren;
map<GuiObject*,int> touchCountMap;
}; |
90fe6f8f5ceece6c953a58df764e27cfb63f9817 | c20c4812ac0164c8ec2434e1126c1fdb1a2cc09e | /Source/Source/Client/SO3Client/Test/TestProject/TestSO3Client/KItemNull_Test.cpp | d8bed8bc0371915b2eb4d001a3b1c4f1221960e7 | [
"MIT"
] | permissive | uvbs/FullSource | f8673b02e10c8c749b9b88bf18018a69158e8cb9 | 07601c5f18d243fb478735b7bdcb8955598b9a90 | refs/heads/master | 2020-03-24T03:11:13.148940 | 2018-07-25T18:30:25 | 2018-07-25T18:30:25 | 142,408,505 | 2 | 2 | null | 2018-07-26T07:58:12 | 2018-07-26T07:58:12 | null | GB18030 | C++ | false | false | 13,469 | cpp | KItemNull_Test.cpp | #include "stdafx.h"
#ifdef _UNIT_TEST
#include "KItemNull_Test.h"
#include "../ui/elem/wndstation.h"
CPPUNIT_TEST_SUITE_REGISTRATION(KItemNull_Test);
void KItemNull_Test::setUp()
{
int nRetCode = false;
m_item = NULL;
m_item = UI::KItemNull::Create(m_itemdata);
CPPUNIT_ASSERT(m_item);
nRetCode = UI::KWndStation::Init();
CPPUNIT_ASSERT(nRetCode);
}
void KItemNull_Test::tearDown()
{
if (m_item)
{
KG_COM_RELEASE(m_item);
}
UI::KItemEventMgr::Exit();
}
//////////////////////////////////////////////////////////////////////////
//@用例编号 :1
//@用例目的 :验证int KItemNull::Init(KItemNullData & ItemNullData) 的正确性
//@前置场景 :
//@C1 :
//@操作源 :
//@操作对象 :
//@操作过程 :
//@OP1 :传入空对象
//@OP2 :未初始化内存的KItemNullData
//@OP3 :KItemNullData第一个字符为0
//@OP4 :内存皆初始化为1
//@OP5 :赋值正常的KItemNullData对象
//@OP6 :Init两次
//@后置场景 :
//@CP1 :Init失败
//@CP2 :Init失败
//@CP3 :Init失败
//@CP4 :Init失败
//@CP5 :Init成功
//@CP6 :Init成功
//////////////////////////////////////////////////////////////////////////
void KItemNull_Test::InitItemTest_1()
{
int nRetCode = false;
UI::KItemNullData *pTempItemData = NULL;
nRetCode = m_item->Init(*pTempItemData);
CPPUNIT_ASSERT(!nRetCode);
}
void KItemNull_Test::InitItemTest_2()
{
int nRetCode = false;
UI::KItemNullData *pTempItemData = NULL;
pTempItemData = (UI::KItemNullData *)malloc(sizeof(UI::KItemNullData));
nRetCode = m_item->Init(*pTempItemData);
if (pTempItemData)
{
free(pTempItemData);
pTempItemData = NULL;
}
CPPUNIT_ASSERT(!nRetCode);
}
void KItemNull_Test::InitItemTest_3()
{
int nRetCode = false;
UI::KItemNullData *pTempItemData = NULL;
char *pstr = NULL;
pTempItemData = (UI::KItemNullData *)malloc(sizeof(UI::KItemNullData));
pstr = (char *)pTempItemData;
pstr[0] = '\0';
nRetCode = m_item->Init(*pTempItemData);
if (pTempItemData)
{
free(pTempItemData);
pTempItemData = NULL;
}
CPPUNIT_ASSERT(!nRetCode);
}
void KItemNull_Test::InitItemTest_4()
{
int nRetCode = false;
UI::KItemNullData *pTempItemData = NULL;
char *pstr = NULL;
pTempItemData = (UI::KItemNullData *)malloc(sizeof(UI::KItemNullData));
memset(pTempItemData, 1, sizeof(UI::KItemNullData));
nRetCode = m_item->Init(*pTempItemData);
if (pTempItemData)
{
free(pTempItemData);
pTempItemData = NULL;
}
CPPUNIT_ASSERT(!nRetCode);
}
void KItemNull_Test::InitItemTest_5()
{
int nRetCode = false;
UI::KItemNullData *pTempItemData = NULL;
char *pstr = NULL;
strcpy(m_itemdata.szName, "testitem1");
m_itemdata.nAutoSize = 0;
m_itemdata.nPosType = 1;
m_itemdata.fHeight = 0.1f;
m_itemdata.fWidth = 0.2f;
pTempItemData = &m_itemdata;
nRetCode = m_item->Init(*pTempItemData);
CPPUNIT_ASSERT(nRetCode);
}
void KItemNull_Test::InitItemTest_6()
{
int nRetCode = false;
UI::KItemNullData *pTempItemData = NULL;
char *pstr = NULL;
strcpy(m_itemdata.szName, "testitem2");
m_itemdata.nAutoSize = 2;
m_itemdata.nPosType = 2;
m_itemdata.fHeight = 0.5f;
m_itemdata.fWidth = 0.2f;
pTempItemData = &m_itemdata;
nRetCode = m_item->Init(*pTempItemData);
CPPUNIT_ASSERT(nRetCode);
nRetCode = m_item->Init(*pTempItemData);
CPPUNIT_ASSERT(nRetCode);
}
//////////////////////////////////////////////////////////////////////////
//@用例编号 :2
//@用例目的 :验证virtual void Release(); 的正确性
//@前置场景 :
//@C1 :
//@操作源 :
//@操作对象 :
//@操作过程 :
//@OP1 :连续两次Release
//@后置场景 :
//@CP1 :Release成功
//////////////////////////////////////////////////////////////////////////
void KItemNull_Test::DeleteItemTest()
{
int nRetCode = false;
m_item->Release();
m_item->Release();
}
//////////////////////////////////////////////////////////////////////////
//@用例编号 :3
//@用例目的 :验证virtual int IsItemCanChangeTo(DWORD dwType); 的正确性
//@前置场景 :
//@C1 :
//@操作源 :
//@操作对象 :
//@操作过程 :
//@OP1 :参数为ITEM_BEGINE
//@OP2 :参数为ITEM_NULL
//@OP3 :参数为ITEM_ANIAMTE
//@OP4 :参数为ITEM_COUNT
//@OP5 :参数为100
//@OP6 :参数为-1
//@后置场景 :
//@CP1 :返回成功
//@CP2 :返回成功
//@CP3 :返回失败
//@CP4 :返回失败
//@CP5 :返回失败
//@CP6 :返回失败
//////////////////////////////////////////////////////////////////////////
void KItemNull_Test::ChgItemTypeTest_1()
{
int nRetCode = false;
DWORD dwItemType = UI::ITEM_BEGINE;
nRetCode = m_item->IsItemCanChangeTo(dwItemType);
CPPUNIT_ASSERT(nRetCode);
}
void KItemNull_Test::ChgItemTypeTest_2()
{
int nRetCode = false;
DWORD DWItemType = UI::ITEM_NULL;
nRetCode = m_item->IsItemCanChangeTo(DWItemType);
CPPUNIT_ASSERT(nRetCode);
}
void KItemNull_Test::ChgItemTypeTest_3()
{
int nRetCode = false;
DWORD DWItemType = UI::ITEM_ANIAMTE;
nRetCode = m_item->IsItemCanChangeTo(DWItemType);
CPPUNIT_ASSERT(nRetCode);
}
void KItemNull_Test::ChgItemTypeTest_4()
{
int nRetCode = false;
DWORD DWItemType = UI::ITEM_COUNT;
nRetCode = m_item->IsItemCanChangeTo(DWItemType);
CPPUNIT_ASSERT(nRetCode);
}
void KItemNull_Test::ChgItemTypeTest_5()
{
int nRetCode = false;
DWORD DWItemType = 100;
nRetCode = m_item->IsItemCanChangeTo(DWItemType);
CPPUNIT_ASSERT(nRetCode);
}
void KItemNull_Test::ChgItemTypeTest_6()
{
int nRetCode = false;
DWORD DWItemType = -1;
nRetCode = m_item->IsItemCanChangeTo(DWItemType);
CPPUNIT_ASSERT(nRetCode);
}
//////////////////////////////////////////////////////////////////////////
//@用例编号 :4
//@用例目的 :验证int KItemNull::PtInItem(float fAbsX, float fAbsY)的正确性
//@前置场景 :
//@C1 :
//@操作源 :
//@操作对象 :
//@操作过程 :
//@OP1 :X<m_fAbsX,Y<m_fAbsY
//@OP2 :X<m_fAbsX,Y=m_fAbsY
//@OP3 :X=m_fAbsX,Y<m_fAbsY
//@OP4 :X=m_fAbsX,Y=m_fAbsY
//@OP5 :X=m_fAbsX + m_fWidth,y=m_fAbsY +m_fHeight
//@OP6 :X>m_fAbsX + m_fWidth,y=m_fAbsY +m_fHeight
//@OP7 :X=m_fAbsX + m_fWidth,y>m_fAbsY +m_fHeight
//@OP8 :X>m_fAbsX + m_fWidth,y>m_fAbsY +m_fHeight
//@OP9 :Item属性为显示
//@OP10 :Item属性为隐藏
//@后置场景 :
//@CP1 :不在Item中
//@CP2 :不在Item中
//@CP3 :不在Item中
//@CP4 :在Item中
//@CP5 :在Item中
//@CP6 :不在Item中
//@CP7 :不在Item中
//@CP8 :不在Item中
//@CP9 :坐标x=m_fAbsX+1,y=m_fAbsY+1,坐标在Item中
//@CP10 :坐标x=m_fAbsX+1,y=m_fAbsY+1,坐标不在Item中
//////////////////////////////////////////////////////////////////////////
void KItemNull_Test::PtINItemTest_1()
{
int nResult = false;
int nRetCode = false;
float fx = 0;
float fy = 0;
nRetCode = m_item->SetAbsPos(1, 1);
KG_PROCESS_ERROR(nRetCode);
nRetCode = m_item->SetSize(10, 10);
KG_PROCESS_ERROR(nRetCode);
fx = 0;
fy = 0;
nRetCode = m_item->PtInItem(fx,fy);
KG_PROCESS_ERROR(!nRetCode);
nResult = true;
Exit0:
CPPUNIT_ASSERT(nResult);
}
void KItemNull_Test::PtINItemTest_2()
{
int nResult = false;
int nRetCode = false;
float fx = 0;
float fy = 0;
nRetCode = m_item->SetAbsPos(1, 1);
KG_PROCESS_ERROR(nRetCode);
nRetCode = m_item->SetSize(10, 10);
KG_PROCESS_ERROR(nRetCode);
fx = 0;
fy = 1;
nRetCode = m_item->PtInItem(fx,fy);
KG_PROCESS_ERROR(!nRetCode);
nResult = true;
Exit0:
CPPUNIT_ASSERT(nResult);
}
void KItemNull_Test::PtINItemTest_3()
{
int nResult = false;
int nRetCode = false;
float fx = 0;
float fy = 0;
nRetCode = m_item->SetAbsPos(1, 1);
KG_PROCESS_ERROR(nRetCode);
nRetCode = m_item->SetSize(10, 10);
KG_PROCESS_ERROR(nRetCode);
fx = 1;
fy = 0;
nRetCode = m_item->PtInItem(fx,fy);
KG_PROCESS_ERROR(!nRetCode);
nResult = true;
Exit0:
CPPUNIT_ASSERT(nResult);
}
void KItemNull_Test::PtINItemTest_4()
{
int nResult = false;
int nRetCode = false;
float fx = 0;
float fy = 0;
nRetCode = m_item->SetAbsPos(1, 1);
KG_PROCESS_ERROR(nRetCode);
nRetCode = m_item->SetSize(10, 10);
KG_PROCESS_ERROR(nRetCode);
fx = 1;
fy = 1;
nRetCode = m_item->PtInItem(fx,fy);
KG_PROCESS_ERROR(nRetCode);
nResult = true;
Exit0:
CPPUNIT_ASSERT(nResult);
}
void KItemNull_Test::PtINItemTest_5()
{
int nResult = false;
int nRetCode = false;
float fx = 0;
float fy = 0;
nRetCode = m_item->SetAbsPos(1, 1);
KG_PROCESS_ERROR(nRetCode);
nRetCode = m_item->SetSize(10, 10);
KG_PROCESS_ERROR(nRetCode);
fx = 11;
fy = 11;
nRetCode = m_item->PtInItem(fx,fy);
KG_PROCESS_ERROR(nRetCode);
nResult = true;
Exit0:
CPPUNIT_ASSERT(nResult);
}
void KItemNull_Test::PtINItemTest_6()
{
int nResult = false;
int nRetCode = false;
float fx = 0;
float fy = 0;
nRetCode = m_item->SetAbsPos(1, 1);
KG_PROCESS_ERROR(nRetCode);
nRetCode = m_item->SetSize(10, 10);
KG_PROCESS_ERROR(nRetCode);
fx = 15;
fy = 11;
nRetCode = m_item->PtInItem(fx,fy);
KG_PROCESS_ERROR(!nRetCode);
nResult = true;
Exit0:
CPPUNIT_ASSERT(nResult);
}
void KItemNull_Test::PtINItemTest_7()
{
int nResult = false;
int nRetCode = false;
float fx = 0;
float fy = 0;
nRetCode = m_item->SetAbsPos(1, 1);
KG_PROCESS_ERROR(nRetCode);
nRetCode = m_item->SetSize(10, 10);
KG_PROCESS_ERROR(nRetCode);
fx = 11;
fy = 12;
nRetCode = m_item->PtInItem(fx,fy);
KG_PROCESS_ERROR(!nRetCode);
nResult = true;
Exit0:
CPPUNIT_ASSERT(nResult);
}
void KItemNull_Test::PtINItemTest_8()
{
int nResult = false;
int nRetCode = false;
float fx = 0;
float fy = 0;
nRetCode = m_item->SetAbsPos(1, 1);
KG_PROCESS_ERROR(nRetCode);
nRetCode = m_item->SetSize(10, 10);
KG_PROCESS_ERROR(nRetCode);
fx = 15;
fy = 12;
nRetCode = m_item->PtInItem(fx,fy);
KG_PROCESS_ERROR(!nRetCode);
nResult = true;
Exit0:
CPPUNIT_ASSERT(nResult);
}
void KItemNull_Test::PtINItemTest_9()
{
int nResult = false;
int nRetCode = false;
float fx = 0;
float fy = 0;
nRetCode = m_item->SetAbsPos(1, 1);
KG_PROCESS_ERROR(nRetCode);
nRetCode = m_item->SetSize(10, 10);
KG_PROCESS_ERROR(nRetCode);
fx = 7;
fy = 7;
nRetCode = m_item->Show();
KG_PROCESS_ERROR(nRetCode);
nRetCode = m_item->PtInItem(fx,fy);
KG_PROCESS_ERROR(nRetCode);
nResult = true;
Exit0:
CPPUNIT_ASSERT(nResult);
}
void KItemNull_Test::PtINItemTest_10()
{
int nResult = false;
int nRetCode = false;
float fx = 0;
float fy = 0;
nRetCode = m_item->SetAbsPos(1, 1);
KG_PROCESS_ERROR(nRetCode);
nRetCode = m_item->SetSize(10, 10);
KG_PROCESS_ERROR(nRetCode);
fx = 7;
fy = 7;
nRetCode = m_item->Hide();
KG_PROCESS_ERROR(nRetCode);
nRetCode = m_item->PtInItem(fx,fy);
KG_PROCESS_ERROR(!nRetCode);
nResult = true;
Exit0:
CPPUNIT_ASSERT(nResult);
}
//////////////////////////////////////////////////////////////////////////
//@用例编号 :5
//@用例目的 :验证int KItemNull::SetPosType(DWORD dwPosType) 的正确性
//@前置场景 :
//@C1 :
//@操作源 :
//@操作对象 :
//@操作过程 :
//@OP1 :设置为POSITION_BEGINE
//@OP2 :设置为POSITION_END
//@OP3 :设置为POSITION_TOP_CENTER
//@OP4 :设置为-1
//@OP5 :设置为100
//@后置场景 :
//@CP1 :设置成功
//@CP2 :设置失败
//@CP3 :设置成功
//@CP4 :设置失败
//@CP5 :设置失败
//////////////////////////////////////////////////////////////////////////
void KItemNull_Test::SetPosTypeTest_1()
{
int nRetCode = false;
nRetCode = m_item->SetPosType(UI::POSITION_BEGINE);
CPPUNIT_ASSERT(nRetCode);
}
void KItemNull_Test::SetPosTypeTest_2()
{
int nRetCode = false;
nRetCode = m_item->SetPosType(UI::POSITION_END);
CPPUNIT_ASSERT(!nRetCode);
}
void KItemNull_Test::SetPosTypeTest_3()
{
int nRetCode = false;
nRetCode = m_item->SetPosType(UI::POSITION_TOP_CENTER);
CPPUNIT_ASSERT(nRetCode);
}
void KItemNull_Test::SetPosTypeTest_4()
{
int nRetCode = false;
nRetCode = m_item->SetPosType(-1);
CPPUNIT_ASSERT(!nRetCode);
}
void KItemNull_Test::SetPosTypeTest_5()
{
int nRetCode = false;
nRetCode = m_item->SetPosType(100);
CPPUNIT_ASSERT(!nRetCode);
}
//////////////////////////////////////////////////////////////////////////
//@用例编号 :6
//@用例目的 :验证int KItemNull::SetName(LPCTSTR pcszItemName) 的正确性
//@前置场景 :
//@C1 :
//@操作源 :
//@操作对象 :
//@操作过程 :
//@OP1 :参数为空指针
//@OP2 :参数为空字符串
//@OP3 :参数为传入字符串长度超出范围ITEM_NAME_MAX_SIZE
//@OP4 :参数为正常字符串
//@后置场景 :
//@CP1 :设置失败
//@CP2 :设置失败
//@CP3 :设置失败
//@CP4 :设置成功
//////////////////////////////////////////////////////////////////////////
void KItemNull_Test::SetNameTest_1()
{
int nRetCode = false;
LPCTSTR pcszItemName = NULL;
nRetCode = m_item->SetName(pcszItemName);
CPPUNIT_ASSERT(!nRetCode);
}
void KItemNull_Test::SetNameTest_2()
{
int nRetCode = false;
LPCTSTR pcszItemName = "";
//pcszItemName[0] = '\0';
nRetCode = m_item->SetName(pcszItemName);
CPPUNIT_ASSERT(!nRetCode);
}
void KItemNull_Test::SetNameTest_3()
{
int nRetCode = false;
LPCTSTR pcszItemName = "a123456789b123456789c123456789d12";
nRetCode = m_item->SetName(pcszItemName);
CPPUNIT_ASSERT(!nRetCode);
}
void KItemNull_Test::SetNameTest_4()
{
int nRetCode = false;
LPCTSTR pcszItemName = "test001";
nRetCode = m_item->SetName(pcszItemName);
CPPUNIT_ASSERT(nRetCode);
}
#endif //#ifdef UNIT_TEST |
94cbdb77997dde590f8a1a8c347f33d3202d9712 | 49fa47948e67e2600dcfc72d28e86e24dadd4296 | /Sources/epoch_config/Configs/CfgEpochClient.hpp | 3a26ead9ce4d8f31e2c36d69e4ed2491d6057964 | [] | no_license | MGTDB/Epoch | 5ae1f476ae9d99f94d39cf471d9fc5112666d6ee | ae9d5fd6cd9cf884cc436a2ac5900a20b232e3f2 | refs/heads/release | 2021-05-02T01:24:28.727331 | 2017-01-06T13:24:22 | 2017-01-06T13:24:22 | 78,964,958 | 0 | 0 | null | 2017-01-14T20:31:48 | 2017-01-14T20:31:47 | null | UTF-8 | C++ | false | false | 9,152 | hpp | CfgEpochClient.hpp | /*
Author: Aaron Clark - EpochMod.com
Contributors: Andrew Gregory
Description:
Main Client side configs for the Epoch gamemode
Licence:
Arma Public License Share Alike (APL-SA) - https://www.bistudio.com/community/licenses/arma-public-license-share-alike
Github:
https://github.com/EpochModTeam/Epoch/tree/release/Sources/epoch_config/Configs/CfgEpochClient.hpp
*/
/*[[[cog from arma_config_tools import *; json_to_arma()]]]*/
class CfgEpochClient
{
epochVersion = "0.4.0.0";
sapperRngChance = 100;
droneRngChance = 100;
buildingNearbyMilitary = 0;
buildingNearbyMilitaryRange = 300;
buildingNearbyMilitaryClasses[] = {"Cargo_Tower_base_F","Cargo_HQ_base_F","Cargo_Patrol_base_F","Cargo_House_base_F"};
restrictedLocations[] = {"NameCityCapital"};
restrictedLocationsRange = 300;
buildingRequireJammer = 1; //1 = require jammer to build
buildingJammerRange = 75;
jammerPerGroup = 1;
minJammerDistance = 650;
maxBuildingHeight = 33;
buildingCountLimit = 200; //overall building limit in range of jammer (overridden if "useGroupCountLimits=1")
storageCountLimit = 100; //overall storage limit in range of jammer (triggers only if "splitCountLimits=1" & "useGroupCountLimits=0")
splitCountLimits = 0; //1 = distinguish buildingCountLimit from storageCountLimit (ex.: buildingCountLimit=100, storageCountLimit=100 >> you can build 100 baseparts AND additional 100 storage objects like safes, lockboxes...)
useGroupCountLimits = 1; //1 = enable leader and member counts (doesn´t affect "splitCountLimits")
buildingCountLeader = 125; //ignore if "useGroupCountLimits=0"
buildingCountPerMember = 5; //ignore if "useGroupCountLimits=0"
storageCountLeader = 10; //ignore if "splitCountLimits=0" & "useGroupCountLimits=0"
storageCountPerMember = 5; //ignore if "splitCountLimits=0" & "useGroupCountLimits=0"
maxdoors = 8;
maxgates = 5;
disableRemoteSensors = "true";
EPOCH_news[] = {"Word is that Sappers have a new boss.","Dogs will often lure them monsters away.","My dog was blown up. I miss him.."};
deathMorphClass[] = {"Epoch_Sapper_F","Epoch_SapperB_F","I_UAV_01_F","Epoch_Cloak_F"};
niteLight[] = {1,1.88,22};
ryanZombiesEnabled = "true";
antagonistSpawnIndex[] = {{"Epoch_Cloak_F",1},{"GreatWhite_F",2},{"Epoch_Sapper_F",2},{"Epoch_SapperB_F",1},{"I_UAV_01_F",2},{"PHANTOM",1},{"B_Heli_Transport_01_F",1},{"EPOCH_RyanZombie_1",12}};
customVarsDefaults[] = {{"Temp",98.6,{106.7,95,102,105,96,95}},{"Hunger",1500,{5000,0,5001,5001,1250,0}},{"Thirst",750,{2500,0,2501,2501,625,0}},{"AliveTime",0,{-2,0}},{"Energy",0,{2500,0}},{"Wet",0,{100,0,35,55,-1,-1}},{"Soiled",0,{100,0,35,55,-1,-1}},{"Immunity",0,{100,0}},{"Toxicity",0,{100,0,35,55,-1,-1}},{"Stamina",100,{"EPOCH_playerStaminaMax",0}},{"Crypto",0,{250000,0}},{"HitPoints",{0,0,0,0},{1,0,0.5,1,-1,-1}},{"BloodP",100,{190,0,120,140,70,50}},{"SpawnArray",{},{}},{"Karma",0,{50000,-50000}},{"Alcohol",0,{100,0,35,55,-1,-1}},{"Radiation",0,{100,0,35,55,-1,-1}},{"Nuisance",0,{100,0}},{"MissionArray",{},{}}};
hudConfigs[] = {{{"BloodP","","",{"getPlayerDamage",">=",0.7}},"topRight","x\addons\a3_epoch_code\Data\UI\bleeding_ca.paa",{"forceUpdate"}},{{"Oxygen","getPlayerOxygenRemaining","",{},{1,0,2,2,1,0.55}},"topRight","x\addons\a3_epoch_code\Data\UI\oxygen_ca.paa"},{"Hunger","topRight","x\addons\a3_epoch_code\Data\UI\hunger_ca.paa",{"forceBloodRise"}},{"Thirst","topRight","x\addons\a3_epoch_code\Data\UI\thirst_ca.paa",{"forceBloodRise"}},{"Temp","topRight",{"x\addons\a3_epoch_code\Data\UI\hot_ca.paa","x\addons\a3_epoch_code\Data\UI\cold_ca.paa"},{"forceFatigue"}},{"Toxicity","topRight","x\addons\a3_epoch_code\Data\UI\hazzard_ca.paa"},{"Alcohol","topRight","x\addons\a3_epoch_code\Data\UI\drunk_ca.paa"},{"Soiled","topRight","x\addons\a3_epoch_code\Data\UI\soiled_ca.paa"},{"Radiation","topRight","x\addons\a3_epoch_code\Data\UI\rads_ca.paa"},{{"HitPoints","getPlayerHitPointDamage","HitLegs"},"topRight","x\addons\a3_epoch_code\Data\UI\broken_ca.paa"}};
group_upgrade_lvl[] = {4,"1000",6,"1500",8,"2000",10,"2500",12,"3000",14,"3500",16,"4000",32,"8000",64,"16000"};
displayAddEventHandler[] = {"keyDown","keyUp"};
keyDown = "(_this call EPOCH_KeyDown)";
keyUp = "(_this call EPOCH_KeyUp)";
addEventHandler[] = {"Respawn","Put","Take","InventoryClosed","InventoryOpened","Fired","Killed","HandleRating","GetInMan","GetOutMan"};
Respawn = "(_this select 0) call EPOCH_clientRespawn";
Put = "(_this select 1) call EPOCH_interact;_this call EPOCH_PutHandler";
Take = "(_this select 1) call EPOCH_interact;_this call EPOCH_UnisexCheck";
Fired = "_this call EPOCH_fnc_playerFired;";
InventoryClosed = "if !(EPOCH_arr_interactedObjs isEqualTo[]) then {[EPOCH_arr_interactedObjs] remoteExec['EPOCH_server_save_vehicles', 2]; EPOCH_arr_interactedObjs = [];};";
InventoryOpened = "setMousePosition[0.5, 0.5];call EPOCH_showStats;_this spawn EPOCH_initUI;params ['_unit','_container','_sec'];_containerlocked = (locked _container in [2, 3] || _container getVariable['EPOCH_Locked', false]);_seclocked = false;if !(isNull _sec) then {_seclocked = (locked _sec in [2, 3] || _sec getVariable['EPOCH_Locked', false]);};if (_containerlocked || _seclocked) then {[] spawn {disableSerialization;waitUntil {!isNull findDisplay 602};_d = findDisplay 602;_cargo = _d displayCtrl 6401;_ground = _d displayCtrl 6321;_cargo ctrlEnable false;ctrlSetFocus _ground;ctrlActivate _ground;};};";
Killed = "_this call EPOCH_fnc_playerDeath;";
HandleRating = "EPOCH_playerKarma = EPOCH_playerKarma + (_this select 1);0";
HandleDamage = "";
HandleHeal = "";
Dammaged = "";
Hit = "";
HitPart = "";
GetInMan = "_this call EPOCH_getInMan";
GetOutMan = "_this call EPOCH_getOutMan;";
nonJammerAI[] = {"B_Heli_Transport_01_F","PHANTOM","EPOCH_Sapper_F","Epoch_SapperB_F","I_UAV_01_F","EPOCH_RyanZombie_1"};
nonTraderAI[] = {"B_Heli_Transport_01_F","PHANTOM","EPOCH_Sapper_F","Epoch_SapperB_F","I_UAV_01_F","Epoch_Cloak_F","GreatWhite_F","EPOCH_RyanZombie_1"};
nonTraderAIRange = 50;
fishLoots[] = {"ItemTuna","ItemSeaBass","ItemSeaBass","ItemSeaBass","ItemTrout","ItemTrout","ItemTrout","ItemTrout","ItemTrout","ItemTrout"};
animalAiTables[] = {"Sheep_random_EPOCH","Sheep_random_EPOCH","Goat_random_EPOCH","Goat_random_EPOCH","Goat_random_EPOCH",{"Cock_random_EPOCH","Hen_random_EPOCH"},{"Cock_random_EPOCH","Hen_random_EPOCH"},"Rabbit_EPOCH","Rabbit_EPOCH","Rabbit_EPOCH","Snake_random_EPOCH","Snake2_random_EPOCH",{"Fin_random_EPOCH","Alsatian_Random_EPOCH"}};
playerDeathScreen = "TapOut";
playerKilledScreen = "TapOut2";
playerDisableRevenge = 0;
playerRevengeMinAliveTime = 900;
bankTransferTime[] = {0.0006,1.2,0.06};
#include "CfgEpochClient\Altis.hpp"
#include "CfgEpochClient\australia.hpp"
#include "CfgEpochClient\Bornholm.hpp"
#include "CfgEpochClient\Chernarus_Summer.hpp"
#include "CfgEpochClient\Chernarus.hpp"
#include "CfgEpochClient\Esseker.hpp"
#include "CfgEpochClient\ProvingGrounds_PMC.hpp"
#include "CfgEpochClient\Sara_dbe1.hpp"
#include "CfgEpochClient\Sara.hpp"
#include "CfgEpochClient\SaraLite.hpp"
#include "CfgEpochClient\Stratis.hpp"
#include "CfgEpochClient\takistan.hpp"
#include "CfgEpochClient\utes.hpp"
#include "CfgEpochClient\vr.hpp"
#include "CfgEpochClient\Zargabad.hpp"
#include "CfgEpochClient\Tanoa.hpp"
#include "CfgEpochClient\WorldInteractions.hpp"
};
class CfgEpochSapper
{
detonateDistMax = 8;
groanTrig = 16;
sRange = 300;
smellDist = 24;
reflexSpeed = 0.25;
nestChance = 2;
hideLevel = 72;
chargeLevel = 62;
};
class CfgEpochUAV
{
UAVMinDist = 48;
UAVMaxDist = 180;
UAVHeight = 100;
};
class CfgEpochUAVSupport
{
unitTypes[] = {"I_Soldier_EPOCH","I_Soldier2_EPOCH","I_Soldier3_EPOCH"};
maxUnitNum = 2;
minAISkill = 0.2;
maxAimingAccuracy = 0.7;
maxAimingShake = 0.9;
maxAimingSpeed = 0.6;
maxEndurance = 0.4;
maxSpotDistance = 0.4;
maxSpotTime = 0.3;
maxCourage = 0.3;
maxReloadSpeed = 0.5;
maxCommanding = 0.4;
maxGeneral = 0.4;
};
class CfgEpochAirDrop
{
AirDropFreq = 1200;
AirDropChance = 6;
};
class CfgEpochCloak
{
cRange = 300;
cAggression = 75;
attackFrequency = 120;
attackDistance = 38;
targetChangeFrequency = 42;
teleportChance = 66;
hoverFrequency = 1280;
};
class CfgEpochRyanZombie
{
zeds[] = {"EPOCH_RyanZombie_1","EPOCH_RyanZombie_2","EPOCH_RyanZombie_3","EPOCH_RyanZombie_4","EPOCH_RyanZombie_5"};
attackDist = 1.6;
range = 45;
disposeRange = 800;
smell[] = {38,0.42};
sight[] = {28,0.72};
hearing[] = {108,0.68};
memory[] = {480,0.8};
reflexSpeed = 0.25;
moans[] = {"ryanzombiesmoan1","ryanzombiesmoan2","ryanzombiesmoan3","ryanzombiesmoan4"};
screams[] = {"ryanzombiesscream1","ryanzombiesscream2","ryanzombiesscream3","ryanzombiesscream4","ryanzombiesscream5","ryanzombiesscream6","ryanzombiesscream7","ryanzombiesscream8","ryanzombiesscream9"};
};
/*[[[end]]]*/
|
51f37c5266b8b7d4303e57b4e789289050e36785 | d1cf34b4d5280e33ebcf1cd788b470372fdd5a26 | /topcoder/algorithm/4/533.srm409/MagicalSpheres.cc | 0d1d9c082106830eb46dadf18fae43fbf3b8abf6 | [] | no_license | watashi/AlgoSolution | 985916ac511892b7e87f38c9b364069f6b51a0ea | bbbebda189c7e74edb104615f9c493d279e4d186 | refs/heads/master | 2023-08-17T17:25:10.748003 | 2023-08-06T04:34:19 | 2023-08-06T04:34:19 | 2,525,282 | 97 | 32 | null | 2020-10-09T18:52:29 | 2011-10-06T10:40:07 | C++ | UTF-8 | C++ | false | false | 3,116 | cc | MagicalSpheres.cc | #include <algorithm>
#include <iostream>
#include <sstream>
#include <numeric>
#include <string>
#include <utility>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <list>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <cstdarg>
#include <cstring>
using namespace std;
#define ALL(c) (c).begin(), (c).end()
#define FOR(i, n) for (int i = 0; i < (int)(n); ++i)
#define FOREACH(i, n) for (typeof(n.begin()) i = n.begin(); i != n.end(); ++i)
#define MEMSET(p, c) memset(p, c, sizeof(p))
typedef long long llint;
typedef pair<int, int> PII;
/// BEGIN CUT HERE
#define WATASHI_PC
inline void errf(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
}
template<typename T>
inline void errf(const char *fmt, const vector<T>& v) {
errf("{");
FOR(i, v.size()) {
errf(fmt, v[i]);
}
errf("}\n");
}
// TODO
/// END CUT HERE
#ifndef WATASHI_PC
#define errf(fmt, ...) do { } while (false)
#endif
struct MagicalSpheres {
int divideWork(int spheresCount, int fakeSpheresCount, int gnomesAvailable);
};
llint facexp(llint n, llint p) {
llint m = 0;
for (int i = 1; n > 0; --i) {
m += n / p;
n /= p;
}
return m;
}
map<int, int> factor(int n) {
map<int, int> ret;
for (int i = 2; i * i <= n; ++i) {
while (n % i == 0) {
++ret[i];
n /= i;
}
}
if (n > 1) {
++ret[n];
}
return ret;
}
int MagicalSpheres::divideWork(int spheresCount, int fakeSpheresCount, int gnomesAvailable) {
llint m = spheresCount;
llint n = fakeSpheresCount;
while (true) {
bool flag = true;
map<int, int> f = factor(gnomesAvailable);
FOREACH (fi, f) {
llint c = facexp(m + n, fi->first) - facexp(m, fi->first) - facexp(n, fi->first);
if (c < fi->second) {
flag = false;
break;
}
}
if (flag) {
return gnomesAvailable;
} else {
--gnomesAvailable;
}
}
return -1;
}
/// BEGIN CUT HERE
// TODO
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))
template<typename T>
ostream& operator<<(ostream& os, vector<T>& v) {
os << "{";
FOR(i, v.size()) {
os << "\"" << v[i] << "\",";
}
os << "}";
return os;
}
template<typename S, typename T>
void eq(int id, S v1, T v2) {
ostringstream s1, s2;
s1 << v1;
s2 << v2;
errf("Case #%d: ", id);
if (s1.str() == s2.str()) {
errf("\033[1;32mPassed\033[0m\n");
} else {
errf("\033[1;31mFailed\033[0m\n");
errf("\tReceived \"%s\"\n", s1.str().c_str());
errf("\tExpected \"%s\"\n", s2.str().c_str());
}
}
int main(int argc, char *argv[]) {
{
MagicalSpheres theObject;
eq(0, theObject.divideWork(3, 1, 3),2);
}
{
MagicalSpheres theObject;
eq(1, theObject.divideWork(3, 3, 50),20);
}
{
MagicalSpheres theObject;
eq(2, theObject.divideWork(4, 3, 4),1);
}
{
MagicalSpheres theObject;
eq(3, theObject.divideWork(15634, 456, 5000),4990);
}
puts("\033[1;33mPress any key to continue...\033[0m");
getchar();
return 0;
}
/*
* first second iterator
* push_back priority_queue
*/
/*
* vim: ft=cpp.doxygen
*/
/// END CUT HERE
|
5a1f40a3d6c5fbac1e8b7b77d4f4c1728edbd3af | aee4fcdad6a9b09e07f38cb49a46db321e3c560a | /src/Logger.cpp | 3550f2517360db870f65f99b40d0254d4771c4c8 | [
"BSD-2-Clause"
] | permissive | timre13/chip8asm | df5796552308059cb5b1565c7bff1fcbddd29d9d | 1b289607178b0608b9eea4df5359c1bdf5400492 | refs/heads/master | 2023-07-21T06:45:46.628768 | 2021-08-18T16:33:06 | 2021-08-18T16:33:06 | 387,043,936 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 992 | cpp | Logger.cpp | #include "Logger.h"
namespace Logger
{
Logger dbg{Logger::Type::Debug};
Logger log{Logger::Type::Log};
Logger warn{Logger::Type::Warning};
Logger err{Logger::Type::Error};
Logger fatal{Logger::Type::Fatal};
void setLoggerVerbosity(LoggerVerbosity verbosity)
{
switch (verbosity)
{
case LoggerVerbosity::Quiet:
dbg.m_isEnabled = false;
log.m_isEnabled = false;
warn.m_isEnabled = true;
err.m_isEnabled = true;
fatal.m_isEnabled = true;
break;
case LoggerVerbosity::Verbose:
dbg.m_isEnabled = false;
log.m_isEnabled = true;
warn.m_isEnabled = true;
err.m_isEnabled = true;
fatal.m_isEnabled = true;
break;
case LoggerVerbosity::Debug:
dbg.m_isEnabled = true;
log.m_isEnabled = true;
warn.m_isEnabled = true;
err.m_isEnabled = true;
fatal.m_isEnabled = true;
break;
}
}
} // End of namespace Logger
|
3f4437acfe1ee0e8f67c6c70d154103a6b614a0f | 3ef62205d9583cca10848309343bfc3edfa91524 | /WinToolsLib/Data/Sqlite/StatementDecorators/ExtendableBase.h | 71b23cdef32735615bdb345f87bebdb72a6f1161 | [] | no_license | alexander-borodulya/WinToolsLib | cc84abcc5659231bc174fae70d7c69ac628792dd | 9eb22734a26db6d092249098d7b04ca159d83b3e | refs/heads/master | 2020-12-07T06:24:44.632273 | 2017-09-25T14:59:44 | 2017-09-25T14:59:44 | 65,025,406 | 1 | 2 | null | 2016-08-05T14:34:57 | 2016-08-05T14:34:57 | null | UTF-8 | C++ | false | false | 5,803 | h | ExtendableBase.h | #pragma once
#include "..\..\..\Types.h"
#include "..\..\..\Buffer.h"
#include "..\Statement.h"
#include "..\SqliteException.h"
namespace WinToolsLib { namespace Data { namespace Sqlite { namespace StatementDecorators
{
using namespace Serialization;
class ExtendableBase : public IStatement
{
ExtendableBase(const ExtendableBase& other); // Non-copyable
ExtendableBase& operator=(const ExtendableBase& other); // Non-copyable
public:
ExtendableBase(Database* db, StatementPtr&& statement, const TChar* sql);
virtual ~ExtendableBase();
ExtendableBase(ExtendableBase&& other);
ExtendableBase& operator=(ExtendableBase&& other);
Void Finalize() override;
Int64 Execute() override;
Void BeginStoreProperties() override;
Void StoreProperty(const TChar* name, Bool value, BoolFormat format = BoolFormat::TrueFalse) override;
Void StoreProperty(const TChar* name, Int8 value, IntFormat format = IntFormat::Dec) override;
Void StoreProperty(const TChar* name, UInt8 value, IntFormat format = IntFormat::Dec) override;
Void StoreProperty(const TChar* name, Int16 value, IntFormat format = IntFormat::Dec) override;
Void StoreProperty(const TChar* name, UInt16 value, IntFormat format = IntFormat::Dec) override;
Void StoreProperty(const TChar* name, Int32 value, IntFormat format = IntFormat::Dec) override;
Void StoreProperty(const TChar* name, UInt32 value, IntFormat format = IntFormat::Dec) override;
Void StoreProperty(const TChar* name, Int64 value, IntFormat format = IntFormat::Dec) override;
Void StoreProperty(const TChar* name, UInt64 value, IntFormat format = IntFormat::Dec) override;
Void StoreProperty(const TChar* name, Float value, FloatFormat format = FloatFormat::Default) override;
Void StoreProperty(const TChar* name, Double value, FloatFormat format = FloatFormat::Default) override;
Void StoreProperty(const TChar* name, const String& value) override;
Void StoreProperty(const TChar* name, const Buffer& value) override;
Void EndStoreProperties() override;
IStorePropertyPtr StoreChild(const TChar* name) override;
Void StoreNull(const TChar* name) override;
Int64 GetLastId() const override;
Int32 GetRowsModified() const override;
protected:
Void MoveFrom(ExtendableBase& other);
String SearchByRegExp(const TChar* regExp) const;
Void ReplaceInSql(const String& replaceableStr, const TChar* format, const TChar* additionalStr);
virtual Void ModifySql(const TChar* name, const TChar* type) = 0;
protected:
String m_sql;
Database* m_db;
private:
Void StorePropertyList();
template <class Value, class Format>
Void TryStore(const TChar* name, const TChar* type, Value value, Format format);
Void RecreateStatement(const TChar* name, const TChar* type);
private:
typedef std::tuple<String, Buffer, StringA, Int32> StoredProperty;
std::vector<StoredProperty> m_propertyList;
StatementPtr m_statement;
};
inline Void ExtendableBase::Finalize()
{
m_statement->Finalize();
}
inline Int64 ExtendableBase::Execute()
{
m_propertyList.clear();
return m_statement->Execute();
}
inline Void ExtendableBase::BeginStoreProperties()
{
m_statement->BeginStoreProperties();
}
inline Void ExtendableBase::StoreProperty(const TChar* name, Bool value, BoolFormat format)
{
TryStore(name, Text("BOOL"), value, format);
}
inline Void ExtendableBase::StoreProperty(const TChar* name, Int8 value, IntFormat format)
{
TryStore(name, Text("INTEGER"), value, format);
}
inline Void ExtendableBase::StoreProperty(const TChar* name, UInt8 value, IntFormat format)
{
TryStore(name, Text("INTEGER"), value, format);
}
inline Void ExtendableBase::StoreProperty(const TChar* name, Int16 value, IntFormat format)
{
TryStore(name, Text("INTEGER"), value, format);
}
inline Void ExtendableBase::StoreProperty(const TChar* name, UInt16 value, IntFormat format)
{
TryStore(name, Text("INTEGER"), value, format);
}
inline Void ExtendableBase::StoreProperty(const TChar* name, Int32 value, IntFormat format)
{
TryStore(name, Text("INTEGER"), value, format);
}
inline Void ExtendableBase::StoreProperty(const TChar* name, UInt32 value, IntFormat format)
{
TryStore(name, Text("INTEGER"), value, format);
}
inline Void ExtendableBase::StoreProperty(const TChar* name, Int64 value, IntFormat format)
{
TryStore(name, Text("INTEGER"), value, format);
}
inline Void ExtendableBase::StoreProperty(const TChar* name, UInt64 value, IntFormat format)
{
TryStore(name, Text("INTEGER"), value, format);
}
inline Void ExtendableBase::StoreProperty(const TChar* name, Float value, FloatFormat format)
{
TryStore(name, Text("REAL"), value, format);
}
inline Void ExtendableBase::StoreProperty(const TChar* name, Double value, FloatFormat format)
{
TryStore(name, Text("REAL"), value, format);
}
inline Void ExtendableBase::EndStoreProperties()
{
m_statement->EndStoreProperties();
}
inline IStorePropertyPtr ExtendableBase::StoreChild(const TChar* name)
{
return m_statement->StoreChild(name);
}
template <class Value, class Format>
Void ExtendableBase::TryStore(const TChar* name, const TChar* type, Value value, Format format)
{
try
{
m_statement->StoreProperty(name, value, format);
}
catch (ColumnNotFoundException&)
{
RecreateStatement(name, type);
m_statement->StoreProperty(name, value, format);
}
Buffer data((PCByte)&value, sizeof(value));
auto prop = std::make_tuple(name, std::move(data), typeid(value).name(), (Int32)format);
m_propertyList.push_back(std::move(prop));
}
inline Int64 ExtendableBase::GetLastId() const
{
return m_statement->GetLastId();
}
inline Int32 ExtendableBase::GetRowsModified() const
{
return m_statement->GetRowsModified();
}
} } } }
|
dfbdb364934bfe1b2d6b217c36cbf01300164e49 | 4a54b6d393c247075d425670b70beafb70ce27a2 | /mainwindow.cpp | e085aa41e10ebce174d5be71c1b4b189579a9bab | [] | no_license | mortalis13/Android-Manager-Qt | eefbbc611c3ee83f960b161b60aad124e1ee76c7 | 0fefcd45ba0d631499685f875037f20b94a6c06c | refs/heads/master | 2023-01-25T00:40:24.225323 | 2023-01-19T09:20:01 | 2023-01-19T09:20:01 | 56,925,525 | 7 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 16,683 | cpp | mainwindow.cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtDebug>
#include <QtAlgorithms>
#include <QStringListModel>
#include <QShortcut>
#include <QFileInfo>
#include "fun.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
init();
addActions();
addShortcuts();
}
MainWindow::~MainWindow() {
delete ui;
}
void MainWindow::init() {
tableView()->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->lProgress->setText("");
ui->lStatus->setText("");
setCopyProgressValue(0, 0);
curDirPath = "";
copyActive = true;
dirsList = new QList<FileItem>();
filesList = new QList<FileItem>();
tableModel = new QStandardItemModel();
}
void MainWindow::addActions() {
// connect( ui->bTest, SIGNAL(clicked()), this, SLOT(bTestClick()) );
connect( ui->bGoRoot, SIGNAL(clicked()), this, SLOT(goRoot()) );
connect( ui->bGoUp, SIGNAL(clicked()), this, SLOT(goUp()) );
connect( ui->bCopy, SIGNAL(clicked()), this, SLOT(bCopyClick()) );
connect( ui->bGo, SIGNAL(clicked()), this, SLOT(bGoClick()) );
connect( ui->lePath, SIGNAL(returnPressed()), this, SLOT(pathEnter()) );
connect( ui->tvList, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(listDoubelClick(const QModelIndex &)) );
}
void MainWindow::addShortcuts() {
QShortcut *bGoRoot_Key = new QShortcut(QKeySequence("F1"), this);
connect( bGoRoot_Key, SIGNAL(activated()), ui->bGoRoot, SLOT(click()) );
QShortcut *bGo_Key = new QShortcut(QKeySequence("F4"), this);
connect( bGo_Key, SIGNAL(activated()), ui->bGo, SLOT(click()) );
QShortcut *quit_Key = new QShortcut(QKeySequence("Esc"), this);
connect( quit_Key, SIGNAL(activated()), this, SLOT(close()) );
QShortcut *bCopy_Key = new QShortcut(QKeySequence("F5"), this);
connect( bCopy_Key, SIGNAL(activated()), ui->bCopy, SLOT(click()) );
// QShortcut *bCopy_Key = new QShortcut(QKeySequence("F5"), tableView(), 0, 0, Qt::WidgetShortcut);
// connect( bCopy_Key, SIGNAL(activated()), ui->bCopy, SLOT(click()) );
// -- file table
QShortcut *bGoUp_Key = new QShortcut(QKeySequence("Backspace"), tableView(), 0, 0, Qt::WidgetShortcut);
connect( bGoUp_Key, SIGNAL(activated()), ui->bGoUp, SLOT(click()) );
QShortcut *prevDir_Key = new QShortcut(QKeySequence("Left"), tableView(), 0, 0, Qt::WidgetShortcut);
connect( prevDir_Key, SIGNAL(activated()), this, SLOT(prevDir()) );
QAction *action = new QAction(this);
QList<QKeySequence> shortcuts;
shortcuts << QKeySequence("Right") << QKeySequence("Return") << QKeySequence("Enter");
action->setShortcuts(shortcuts);
action->setShortcutContext(Qt::WidgetShortcut);
connect( action, SIGNAL(triggered()), this, SLOT(enterDir()) );
tableView()->addAction(action);
QShortcut *homeList_Key = new QShortcut(QKeySequence("Home"), tableView(), 0, 0, Qt::WidgetShortcut);
connect( homeList_Key, SIGNAL(activated()), this, SLOT(homeList()) );
QShortcut *endList_Key = new QShortcut(QKeySequence("End"), tableView(), 0, 0, Qt::WidgetShortcut);
connect( endList_Key, SIGNAL(activated()), this, SLOT(endList()) );
}
bool compareInsensitive(const QString &s1, const QString &s2) {
return s1.toLower() < s2.toLower();
}
bool compareInsensitiveItems(const FileItem &item1, const FileItem &item2) {
return item1.fileName.toLower() < item2.fileName.toLower();
}
// ------------------------------------------------ actions ------------------------------------------------
void MainWindow::bGoClick() {
pathEnter();
}
void MainWindow::bTestClick() {
}
void MainWindow::bCopyClick() {
if (!tableView() || !tableView()->model() || !tableView()->selectionModel()) {
return;
}
setCopyProgressValue(0, 0);
copyActive = true;
totalCopyNum = 0;
curCopyNum = 0;
totalCopySize = 0;
fileSize = 0;
prevFileSize = 0;
speedText = "";
CopyQueue *cq = new CopyQueue(this);
connect( cq, SIGNAL(progressValue(int, int)), this, SLOT(setCopyProgressValue(int, int)) );
connect( cq, SIGNAL(timerTimeout()), this, SLOT(timerUpdate()) );
connect( cq, SIGNAL(finishedNextCopy()), this, SLOT(finishedNextCopyAction()) );
connect( cq, SIGNAL(copyQueueFinished()), this, SLOT(copyQueueFinished()) );
QModelIndexList list = tableView()->selectionModel()->selectedIndexes();
totalCopyNum = list.length();
if (totalCopyNum == 0) {
qDebug("No files selected to copy");
return;
}
QString toPath = ui->leToPath->text();
toPath = formatPath(toPath);
Fun::createDirs(toPath);
foreach(const QModelIndex &index, list) {
int row = index.row();
int column = index.column();
QModelIndex nameIndex = index.sibling(row, 0);
QModelIndex attrsIndex = index.sibling(row, 2);
if (!nameIndex.isValid()) {
qFatal("Invalid Sibling Index (bCopyClick)");
return;
}
QString name = nameIndex.data().toString();
QString attrs = attrsIndex.data().toString();
if (attrs.at(0) == 'd') continue;
QString origName = name;
QString convertedName = fixPullEncoding(origName);
QString fromPath = curDirPath + convertedName;
QString filePath = toPath + "/" + convertedName;
QString command = "adb pull \"" + fromPath + "\" \"" + toPath + "/.\"";
qDebug() << QString("Copy command: %1").arg(command);
int itemIndex = index.row() - dirsList->length();
int fileSize = filesList->at(itemIndex).fileSize;
totalCopySize += fileSize;
cq->add(command, fileSize, filePath, origName);
}
if (cq->count() > 0) {
cq->startCopy();
}
tableView()->setFocus();
}
void MainWindow::listDoubelClick(const QModelIndex &index) {
enterDir();
}
void MainWindow::pathEnter() {
QString path = ui->lePath->text();
// qDebug() << path;
curDirPath = "";
path.replace(QRegExp("/$"), "");
goToDir(path);
tableView()->setFocus();
}
// ------------------------------------------------ navigation ------------------------------------------------
void MainWindow::goRoot() {
curDirPath = "";
goToDir();
tableView()->setFocus();
}
void MainWindow::goUp() {
QString prevDir = getPrevDir(curDirPath);
QString currentDirName = getCurrentDir(curDirPath);
// qDebug() << "prevDir:" << prevDir;
// qDebug() << "currentDirName:" << currentDirName;
curDirPath = "";
goToDir(prevDir);
int row = 0;
FileItem temp;
temp.fileName = currentDirName;
int res = dirsList->indexOf(temp);
if (res != -1)
row = res;
// qDebug() << "row:" << row;
QModelIndex newIndex = tableView()->model()->index(row, 0);
tableView()->setCurrentIndex(newIndex);
tableView()->scrollTo(newIndex);
tableView()->setFocus();
}
void MainWindow::goToDir(QString dir) {
if (dir.length() == 0)
curDirPath = "";
ui->teOutput->clear();
proc = new QProcess(this);
curDirPath = curDirPath + dir + "/";
QString command = "adb shell \"ls -l \'" + curDirPath + "\'\"";
ui->lePath->setText(curDirPath);
proc->start(command);
if (!proc->waitForFinished())
return;
QByteArray resBA = proc->readAllStandardOutput();
QString res = QString::fromUtf8(resBA);
proc->close();
res = res.replace("\r\r", "\r");
res = res.trimmed();
ui->teOutput->append(res);
QStringList list, dirlist, filelist;
list = res.split("\r\n", QString::SkipEmptyParts);
// qDebug() << "listLen:" << list.length();
if (list.length() > 0) {
// qDebug() << "list";
dirsList->clear();
filesList->clear();
foreach(QString item, list) {
if (item.at(0) == 'd') {
QStringList attrs = item.split(QRegExp("\\s+"));
QString name = "";
for (int i = 5; i<attrs.length(); i++) {
name += attrs[i] + " ";
}
name.remove(name.length()-1, 1);
QString attributes = attrs[0];
FileItem dirItem;
dirItem.fileName = name;
dirItem.attributes = attributes;
dirsList->append(dirItem);
dirlist.append(name);
}
else if (item.at(0) == '-') {
QStringList attrs = item.split(QRegExp("\\s+"));
QString name = "";
for (int i = 6; i<attrs.length(); i++) {
name += attrs[i] + " ";
}
name.remove(name.length()-1, 1);
int size = attrs[3].toInt();
QString attributes = attrs[0];
FileItem fileItem;
fileItem.fileName = name;
fileItem.fileSize = size;
fileItem.attributes = attributes;
filesList->append(fileItem);
filelist.append(name);
}
}
ui->teOutput->moveCursor(QTextCursor::Start);
qSort(dirsList->begin(), dirsList->end(), compareInsensitiveItems);
qSort(filesList->begin(), filesList->end(), compareInsensitiveItems);
// QStandardItemModel *tableModel = new QStandardItemModel();
tableModel->clear();
tableModel->setColumnCount(3);
QStringList labels;
labels.append("Name");
labels.append("Size");
labels.append("Attributes");
tableModel->setHorizontalHeaderLabels(labels);
for (int i = 0; i<dirsList->length(); i++) {
FileItem item = dirsList->at(i);
QList<QStandardItem*> list;
QStandardItem *nameCol = new QStandardItem(item.fileName);
nameCol->setData(QIcon("icons/dir.png"), Qt::DecorationRole);
QStandardItem *sizeCol = new QStandardItem("");
QStandardItem *attrsCol = new QStandardItem(item.attributes);
list.append(nameCol);
list.append(sizeCol);
list.append(attrsCol);
tableModel->appendRow(list);
}
for (int i = 0; i<filesList->length(); i++) {
FileItem item = filesList->at(i);
QList<QStandardItem*> list;
QStandardItem *nameCol = new QStandardItem(item.fileName);
nameCol->setData(QIcon("icons/file.png"), Qt::DecorationRole);
QString fileSize = formatSize(item.fileSize);
QStandardItem *sizeCol = new QStandardItem(fileSize);
QStandardItem *attrsCol = new QStandardItem(item.attributes);
list.append(nameCol);
list.append(sizeCol);
list.append(attrsCol);
tableModel->appendRow(list);
}
tableView()->setModel(tableModel);
QHeaderView *hHeader = tableView()->horizontalHeader();
hHeader->setResizeMode(0, QHeaderView::Stretch);
hHeader->resizeSection(1, 100);
hHeader->setStyleSheet(hHeaderStyle);
QHeaderView *vHeader = tableView()->verticalHeader();
vHeader->setStyleSheet(vHeaderStyle);
updateStatus(dirlist.length(), filelist.length());
QModelIndex index = tableView()->model()->index(0, 0);
tableView()->setCurrentIndex(index);
}
else {
tableView()->setModel(NULL);
updateStatus(0, 0);
}
}
// ------------------------------------------------ custom slots ------------------------------------------------
void MainWindow::homeList() {
QModelIndex index = tableView()->model()->index(0, 0);
tableView()->setCurrentIndex(index);
}
void MainWindow::endList() {
int rows = tableView()->model()->rowCount();
QModelIndex index = tableView()->model()->index(rows-1, 0);
tableView()->setCurrentIndex(index);
}
void MainWindow::prevDir() {
bool focus = tableView()->hasFocus();
// qDebug() << "table-focus-prev:" << focus;
if (!focus) return;
ui->bGoUp->click();
}
void MainWindow::enterDir() {
bool focus = tableView()->hasFocus();
// qDebug() << "table-focus-enter:" << focus;
if (!focus) return;
QModelIndexList list = tableView()->selectionModel()->selectedIndexes();
if (list.length() == 0) {
// qDebug() << "no-selection";
return;
}
QModelIndex index = list.at(0);
if (!index.isValid()) {
// qDebug() << "Invalid Index (enterDir)";
// ui->teOutput->append("Invalid Index (enterDir)");
return;
}
int row = index.row();
int column = index.column();
QModelIndex nameIndex = index.sibling(row, 0);
QModelIndex attrsIndex = index.sibling(row, 2);
if (!nameIndex.isValid()) {
// ui->teOutput->append("Invalid Sibling Index (enterDir)");
return;
}
QString name = nameIndex.data().toString();
QString attrs = attrsIndex.data().toString();
QString type = "file";
if (attrs.length() != 0) {
QChar typeChar = attrs.at(0);
if (typeChar == 'd') {
type = "dir";
}
}
if (type == "dir") {
goToDir(name);
}
else {
// qDebug() << "file (enterDir)";
}
}
void MainWindow::copyProcFinished(int status) {
// qDebug() << "copyProcFinished";
}
void MainWindow::finishedNextCopyAction() {
fileSize = 0;
prevFileSize = 0;
curCopyNum++;
}
void MainWindow::timerUpdate() {
int speedi = fileSize - prevFileSize;
speedText = formatSize(speedi);
prevFileSize = fileSize;
}
void MainWindow::setCopyProgressValue(int val, int max) {
if (val == 0) {
ui->pbCopy->setValue(0);
ui->lProgress->setText("");
return;
}
if (!copyActive) return;
fileSize = val;
int percent = 0;
if (val != 0 && max != 0) {
percent = (double) val / max * 100;
}
ui->pbCopy->setValue(percent);
int curNum = curCopyNum + 1;
curNum = qMin(curNum, totalCopyNum);
QString copiedCur = formatSize(val);
QString copiedTotal = formatSize(max);
QString copySpeed = speedText.length() != 0 ? ", " + speedText + "/s": "";
QString progressText = QString("Copy [%1/%2]: %3 of %4%5").arg(curNum).arg(totalCopyNum).arg(copiedCur).arg(copiedTotal).arg(copySpeed);
ui->lProgress->setText(progressText);
}
void MainWindow::copyQueueFinished() {
copyActive = false;
ui->lProgress->setText("Copy Queue Finished");
ui->pbCopy->setValue(0);
}
// ------------------------------------------------ ui service ------------------------------------------------
void MainWindow::updateStatus(int dirlen, int filelen) {
ui->lStatus->setText("Dirs: " + QString::number(dirlen) + "; Files: " + QString::number(filelen));
}
QTableView* MainWindow::tableView() {
return ui->tvList;
}
// ------------------------------------------------ service ------------------------------------------------
QString MainWindow::fixPullEncoding(QString item) {
QByteArray b = item.toUtf8();
QString res;
QByteArray codes;
codes.append(0x81);
codes.append(0x8d);
codes.append(0x8f);
codes.append(0x90);
codes.append(0x9d);
QTextCodec *codec = QTextCodec::codecForName("Windows-1252");
for (int i = 0; i<b.length(); i++) {
QString s1;
char ch = b.at(i);
if (codes.contains(ch)) {
unsigned char code = (unsigned char) ch;
// qDebug() << "fix-code:" << code;
res += ch;
continue;
}
QByteArray btemp;
btemp.append(ch);
s1 = codec->toUnicode(btemp);
res += s1;
}
return res;
}
QString MainWindow::formatPath(QString path) {
if (path.length() == 0) {
path = "Downloads";
}
QString res = "";
// QFileInfo info(path);
// res = info.absoluteFilePath();
QDir d(path);
res = d.absolutePath();
res.replace(QRegExp("/$"), "");
qDebug() << res;
return res;
}
QString MainWindow::formatSize(int size) {
double res = (double) size, tmp;
QString sizeRes = "";
QStringList unitsList;
unitsList << "B" << "KB" << "MB" << "GB";
QString units = unitsList.at(0);
int uidx = 0;
tmp = res / 1000;
while(tmp > 1) {
res = tmp;
uidx++;
units = unitsList.at(uidx);
tmp = tmp / 1000;
}
sizeRes = QString::number(res, 'f', 2) + " " + units;
return sizeRes;
}
QString MainWindow::getPrevDir(QString dir) {
QString res = dir;
res.replace(QRegExp("/$"), "");
QRegExp rx("^(.+)/");
int pos = rx.indexIn(res);
if (pos == -1) return "";
res = rx.cap(1);
return res;
}
QString MainWindow::getCurrentDir(QString dir) {
QString res = dir;
res.replace(QRegExp("/$"), "");
QRegExp rx("[^/]+$");
int pos = rx.indexIn(res);
if (pos == -1) return "";
res = rx.cap(0);
return res;
}
// ----------------------------------------- add -----------------------------------------
QString MainWindow::getCodesFromString(QString str) {
QString res = "";
QString sep = " ";
for (int i = 0; i<str.length(); i++) {
if (i == str.length()-1)
sep = "";
res += QString::number(str.at(i).unicode()) + sep;
}
return res;
}
QString MainWindow::getCodesFromBytes(QByteArray bytes) {
QString res = "";
QString sep = " ";
for (int i = 0; i<bytes.length(); i++) {
if (i == bytes.length()-1) sep = "";
res += QString::number((int) bytes.at(i)) + sep;
}
return res;
}
QString MainWindow::getCodesFromBytesHex(QByteArray bytes) {
QString res = "";
QString sep = " ";
bytes = bytes.toHex();
for (int i = 0; i<bytes.length(); i++) {
if (i == bytes.length()-1)
sep = "";
res += bytes[i];
if (i%2 != 0)
res += sep;
}
return res;
}
|
33ebe9cb71721df29ee92a1ae3b43fd2ef106fe8 | 15b7e5452329a7fe438e2cb06782a0c6d3846e6c | /inflearn/sorting_CountingSort.cpp | f6b0c6369cd806b7fcdf991ab36fbff68192f7c6 | [] | no_license | currybob/algorithm-ps | bf57f61552ce60a4b829767c2c95132fbd121ca9 | 73bae34322bc64700200c6287c48605253caa3f2 | refs/heads/master | 2020-05-03T13:30:26.770865 | 2019-07-06T05:28:45 | 2019-07-06T05:28:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,787 | cpp | sorting_CountingSort.cpp | // Sorting_SortingInLinearTime
/*
Non-Comparsion Sort
어떤 Comparison Sort도 Linear Time을 가질 수 없음
Counting Sort
n개의 정수를 정렬하라. 단, 모든 정수는 0에서 k사이의 정수이다.
예) n명의 학생들의 시험점수를 정렬하라. 단 모든 점수는 100이하의 양의 정수이다.
예) k = 5인 경우의 예
A = {2, 5, 3, 0, 2, 3, 0, 3}
counting 배열을 만듦 C = {2, 0, 2, 3, 0, 1} 각각의 숫자 갯수를 나타냄
counting 배열의 값에 따라 그 index를 반복해서 출력하면 됨
>> 0 0 2 2 3 3 3 5
(seudo code)
int A[n];
int C[k] = {0,};
for (int i = 1; i <= n; i++)
C[A[i]]++;
for (int s = 1, i = 0; i <= k; i++){
for(int j = 0; j < C[i]; j++)
A[s++] = j;
}
위의 경우 숫자만 정렬이 됨
만약 학생 이름도 같이 있다면 그 이름들은 정렬이 되지 않음
>> Counting 배열에 누적값을 계산해서 넣자
i보다 작거나 같은 것들의 개수가 배열에 들어가있는 것
B라는 추가배열의 누적값번째 index에 값을 넣어주면 정렬이 됨
예) A = {2, 5, 3, 0, 2, 3, 0, 3} C = {2, 2, 4, 7, 7, 8}
B[7] = 3 -> B[6] = 3 ....
(seudo code)
CountingSort(A, B, k)
for i <- 0 to k
do C[i] <- 0
for j <- 1 to length[A]
do C[A[j]] <- C[A[j]] + 1
for i <- 1 to k
do C[i] <- C[i] + C[i - 1]
for j <- length[A] downto 1
do B[C[A[j]]] <- A[j]
C[A[j]] <- C[A[j]] - 1
시간복잡도
O(n+k) 또는 O(n) if k=O(n) : linear time
k가 클 경우 비실용적
Stable 정렬 알고리즘
입력에 동일한 값이 있을 때 입력에 먼저 나오는 값이 출력에서도 먼저 나온다
Counting Sort는 stable하다.
*/
|
1401b9a55f53c68aacd4cadaaeff6a59f697a6b4 | 3a197ae498e5636d4aee5cc0d6426c6622f1dcc1 | /Square/Square/_Ending.cpp | cbd36293de70da38fa1bcd1db9656c76f63f513a | [
"MIT"
] | permissive | stackprobe/Square | e8341d54e712e3dea845f2f1e8df6bab875e13a4 | 5864a2348d722eda610bf55be3597d5d4095a49a | refs/heads/master | 2022-11-17T23:26:39.732891 | 2022-11-05T17:38:41 | 2022-11-05T17:38:41 | 99,126,317 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,383 | cpp | _Ending.cpp | #include "all.h"
static Random *Rnd;
static void DrawWall_old(void)
{
DPE_SetBright(0, 0, 0);
DrawRect(P_WHITEBOX, 0, 0, SCREEN_W, SCREEN_H);
DPE_Reset();
double rate;
ifsceneBegin(600, ActFrame)
{
rate = 0.0;
}
ifscene(6000)
{
rate = sc_rate;
}
ifsceneEnd
{
rate = 1.0;
}
sceneLeave();
if(Rnd->DRnd() < 0.03 + 0.07 * rate)
{
if(Rnd->DRnd() < rate)
CEE_SetBright(Rnd->DRnd(), Rnd->DRnd(), Rnd->DRnd());
/*
星の画像は 120x120 だけど絵は 50x50 程度, 最大 x3 -> 最大 150x150 -> 対角線 212 程度
300x300 は超えないと思う -> 150 で画面外に出るはず。
*/
CEE.ScreenArea.T = -150;
AddCommonEffect(
Gnd.EL,
0,
D_STAR_W_00 + 6 | DTP,
Rnd->DRnd() * SCREEN_W,
SCREEN_H + 100.0,
0.0,
Rnd->DRnd() * 2.0 + 1.0,
0.3,
Rnd->ERnd() * 0.01,
Rnd->DRnd() * -1.0 - 0.5,
Rnd->ERnd() * 0.01
);
CEE_Reset();
}
DrawCenter(P_ALLFLOORCLEARED, 400, 100);
DrawCenter(P_CONGRATULATION, 400, 200);
DrawCenter(P_THANKYOUFORPLAYING, 400, 500);
}
static void DrawWall(void)
{
DrawRect(P_ENDING_1, 0, 0, SCREEN_W, SCREEN_H);
// DrawRect(P_ENDING_2, 0, 0, SCREEN_W, SCREEN_H);
double rate;
ifsceneBegin(600, ActFrame)
{
rate = 0.0;
}
ifscene(60 * 20)
{
rate = sc_rate;
}
ifsceneEnd
{
rate = 1.0;
}
sceneLeave();
if(Rnd->DRnd() < 0.005 + 0.015 * rate)
{
if(Rnd->DRnd() < rate)
CEE_SetBright(Rnd->DRnd(), Rnd->DRnd(), Rnd->DRnd());
CEE.ScreenArea.T = -200;
AddCommonEffect(
Gnd.EL,
0,
D_STAR_W_00 + 6 | DTP,
Rnd->DRnd() * SCREEN_W,
SCREEN_H + 100.0,
0.0,
Rnd->DRnd() * 1.0 + 0.5,
0.3,
Rnd->ERnd() * 0.01,
Rnd->DRnd() * -1.0 - 0.5,
Rnd->ERnd() * 0.01
);
CEE_Reset();
}
}
void Ending(void)
{
Rnd = new Random((int)time(NULL));
// <-- init
SetCurtain(0, -1.0);
ActFrame = 0;
forscene(60)
{
DrawWall();
EachFrame();
}
sceneLeave();
// SetCurtain(200); // old
SetCurtain(400);
MusicPlay(MUS_ENDING);
for(; ; )
{
if(120 < ActFrame && (GetInput(INP_A) || GetInput(INP_B)))
{
break;
}
#if LOG_ENABLED
// clsDx();
// printfDx("%d\n", Gnd.EL->GetCount());
#endif
DrawWall();
EachFrame();
}
MusicFade(200);
SetCurtain(200, -1.0);
forscene(230)
{
DrawWall();
EachFrame();
}
sceneLeave();
Gnd.EL->Clear(); // 星を消さないと残っちゃうよ。
// fnlz -->
delete Rnd;
}
|
79b62a4ee59d687c82683696a570bec52f0fdc00 | b11e816f307bb7ad4206b1daebcba6cf05666860 | /算法学习/并查集专题/好朋友.cpp | 491bfed55720609a466f9fc82854a5be9c63fb39 | [] | no_license | silver-birch-wawa/PAT | 7ab43f3851a6b79a1fdb6b3c8f046ab1e0fbebed | 918873721c35b22e67007ca256a0c592281716b2 | refs/heads/master | 2021-04-18T22:20:12.281360 | 2019-07-26T14:47:51 | 2019-07-26T14:47:51 | 126,701,448 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 913 | cpp | 好朋友.cpp | /*
test:
4 2
1 4
2 3
7 5
1 2
2 3
1 3
1 4
5 6
*/
#include<vector>
#include <iostream>
using namespace std;
#define N 100001
int father[N],sum,relations;
int findFather(int x){
int b=x;
while (x!=father[x]) {
x=father[x];
}
while(b!=father[b]){
int t=father[b];
father[b]=x;
b=t;
}
return x;
}
void Union(int a,int b){
int faA=findFather(a);
int faB=findFather(b);
father[faA]=faB;
}
bool init[N]={false};
int main(){
int i,j,a,b;
vector<int>v;
scanf("%d %d",&sum,&relations);
for(i=1;i<sum+1;i++){
father[i]=i;
}
for(i=0;i<relations;i++){
scanf("%d %d",&a,&b);
// father[max(a,b)]=min(a,b); //如果max一样的话会相互覆盖输出错误。
Union(a,b);
}
for(i=1;i<sum+1;i++){
int res=findFather(i);
init[res]=true;
}
int cal=0;
for(i=1;i<sum+1;i++){
if(init[i]==true){
cal++;
}
}
printf("%d",cal);
}
|
fe905c6e34e54b46ff5e5be40c66bdcf74c2d8d0 | d071547ff0500a85e82b788ea154e3b9bb30fff1 | /Address.h | 8cc3fbbdd6afe841cfc4f58ed2dc80827f11f36e | [] | no_license | DimaLaguta/IP-calculator | 3c6c96b379f33b2d3396b338b0e7b9959190cb0f | 7056d9b4e238d3ffe768fd7069d30a381b64f881 | refs/heads/master | 2022-02-22T02:19:20.685155 | 2019-10-04T11:49:02 | 2019-10-04T11:49:02 | 211,547,499 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 864 | h | Address.h | #ifndef ADDRESS_H
#define ADDRESS_H
class Address
{
public:
unsigned int addres = 0;
int numBitsMask = 0;
private:
int numOktets = 0;
public:
Address();
Address(char* address);
Address(int mask);//создает маску по кличеству бит
Address(unsigned int mask);//создает масску по int
static void Binary(unsigned int x);
char* charAddres();
~Address();
private:
unsigned int genericMask(int mask);
unsigned int* Parse(char* addres);
char** splitToString(char* addres);
unsigned int* convertToInt(char** oktets);
void makeIntAddress(unsigned int* oktets);
unsigned int convertCharToInt(char* oktet);
unsigned int* convertToMasInt();
char** makeCharOktets(unsigned int* oktets);
char* uniteOktets(char** oktet);
char* convertIntToChar(unsigned int num);
void reversChar(char* num);
};
#endif ADDRESS_H |
d829e6515302b0ced051b24e408aecf7d6300f62 | 3548088470f21052787e75d91bd8cdda8664cc12 | /joosc.h | b1201605c4f39f91a6caa40c256e36c0c7cc88bc | [] | no_license | Maximus-Wu/joosc | 0ec81a079bf9691be7be96795df1e2f7220fad3a | bbb4e916284f84a6eb51ee10a93d56032e5e6136 | refs/heads/master | 2021-04-19T04:01:59.677911 | 2017-01-03T01:50:38 | 2017-01-03T01:50:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,185 | h | joosc.h | #ifndef JOOSC_H
#define JOOSC_H
#include "ast/ast_fwd.h"
#include "base/errorlist.h"
#include "base/fileset.h"
#include "ir/ir_generator.h"
#include "types/types.h"
namespace types {
class TypeInfoMap;
} // namespace types
// A stage of the compiler. Note that each constant implicitly includes all
// prior constants. That is to say, LEX implicitly means to OPEN_FILES then
// LEX.
enum class CompilerStage {
OPEN_FILES,
LEX,
UNSUPPORTED_TOKS,
PARSE,
WEED,
TYPE_CHECK,
GEN_IR,
GEN_ASM,
ALL,
};
// Run the compiler up to and including the indicated stage. The second
// argument is a list of files to compile.
bool CompilerMain(CompilerStage stage, const vector<string>& files,
std::ostream* out, std::ostream* err);
sptr<const ast::Program> CompilerFrontend(CompilerStage stage, const base::FileSet* fs, types::TypeSet* typeset_out, types::TypeInfoMap* tinfo_out, types::ConstStringMap* string_map_out, base::ErrorList* err_out);
bool CompilerBackend(CompilerStage stage, sptr<const ast::Program> prog, const string& dir, const types::TypeInfoMap& tinfo_map, const types::ConstStringMap& string_map, const base::FileSet& fs, std::ostream* err);
#endif
|
d0b84d6f902d38067ad3e6b24c43aa929388d74c | 63933a82ddac094d84b618ffeeab1840d188ac66 | /Metabolic Navigator/selectlabelwidget.cpp | 9bec10fe1cbf54b8e3c5d0cfa8417143892d663c | [] | no_license | catkira/Metabolic-Navigator | 4fedd20f1fe5bf0133b4b19ba5205bf44fe3d78e | c2cb57e64e38ab8884ce6dfe05501f8f4ea57bd9 | refs/heads/master | 2023-02-09T06:08:52.175724 | 2021-01-06T21:22:16 | 2021-01-06T21:22:16 | 327,431,802 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 179 | cpp | selectlabelwidget.cpp | #include "selectlabelwidget.h"
SelectLabelWidget::SelectLabelWidget(QWidget *parent)
: QDialogparent)
{
ui.setupUi(this);
}
SelectLabelWidget::~SelectLabelWidget()
{
}
|
949ab351acb8f78038871a834bec4a6d84873de3 | d835d30f334cda50d4e0aae973b3ab7d08fa438e | /Heatmap/main.cpp | 8e27d118b3eb1c8d21aec5f97f14009312ebf70a | [] | no_license | kulbitsky99/ParProg2020 | 06c306dd716eed69592414378381e9eae0bd3664 | a331235d5d1c2b2b38ca71ba714bd785c52b4818 | refs/heads/master | 2023-01-18T16:38:19.381941 | 2020-10-22T18:57:09 | 2020-10-22T18:57:09 | 304,318,708 | 0 | 0 | null | 2020-10-22T19:17:16 | 2020-10-15T12:26:50 | C++ | UTF-8 | C++ | false | false | 899 | cpp | main.cpp | #include <iostream>
#include <iomanip>
#include <fstream>
#include <omp.h>
#include <sys/time.h>
#include <climits>
#include <string>
int create_threads(int n_of_threads);
long int ReadArg(char * str);
int main(int argc, char** argv)
{
return 0;
}
int create_threads(int n_of_threads)
{
int res = 0;
#pragma omp parallel num_threads(n_of_threads)
{
res++;
}
return res;
}
long int ReadArg(char * str)
{
char* endptr;
errno = 0;
long int number = strtol(str, &endptr, 10);
if ((errno == ERANGE && (number == LONG_MAX || number == LONG_MIN)) || (errno != 0 && number == 0))
{
perror("strtol");
exit(EXIT_FAILURE);
}
if (endptr == str)
{
fprintf(stderr, "Error!\n");
exit(EXIT_FAILURE);
}
if (*endptr != '\0')
{
fprintf(stderr, "Error!\n");
exit(EXIT_FAILURE);
}
return number;
}
|
2269c68fc353e99566db1a9102e316f569c713e0 | d2c7a119e436c44436361329af13ae2760e9af56 | /source/Entity Manager/Entities/Subsystems/LifeSupport.cpp | 6a07a3225feb93faca7e058c7d83c3ef6072f181 | [] | no_license | rodrigobmg/Damage-Control-FinalProject | 48a902b7d747c0409b7a7d0a553a18d861be4ad2 | 8ad5a3509bc0db96025873da37290f1a51538a8b | refs/heads/master | 2020-05-01T08:08:49.425070 | 2016-02-06T23:47:47 | 2016-02-06T23:47:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,314 | cpp | LifeSupport.cpp | /***********************************************
* Filename: LifeSupport.cpp
* Date: 05/22/2015
* Mod. Date:
* Mod. Initials:
* Author: Michael Mozdzierz
* Purpose:
************************************************/
#include "LifeSupport.h"
#include <string>
#include "../../../Asset Manager/DDSTextureLoader.h"
#include "../../../Renderer/Renderer.h"
#include "../Player.h"
#include "../../../Audio Manager/AudioSystemWwise.h"
#include "../../../TinyXML2/tinyxml2.h"
using namespace MathHelper;
using namespace std;
/*****************************************************************
* CLifeSupport()
*
* Ins:
*
* Outs:
*
* Returns:
*
* Mod. Date: 05/28/2015
* Mod. Initials:
*****************************************************************/
CLifeSupport::CLifeSupport(void)
{
LoadStats();
m_szTag = "LifeSupport";
tCollider = new TAABB;
tCollider->type = TCollider::eAABB;
m_fHealthRegen = 5.0f;
AudioSystemWwise::Get( )->RegisterEntity(this, "LifeSupport");
}
/*****************************************************************
* ~CLifeSupport() - Sets the position of the engines
*
* Ins:
*
* Outs:
*
* Returns:
*
* Mod. Date: 05/28/2015
* Mod. Initials:
*****************************************************************/
/*virtual*/ CLifeSupport::~CLifeSupport(void)
{
AudioSystemWwise::Get( )->UnRegisterEntity(this);
delete tCollider;
tCollider = nullptr;
}
/*****************************************************************
* SetPosition() - Sets the position of the engines
*
* Ins: position - the position to set the engines
*
* Outs:
*
* Returns:
*
* Mod. Date: 05/28/2015
* Mod. Initials:
*****************************************************************/
/*virtual*/ void CLifeSupport::SetPosition(DirectX::XMFLOAT3& position) /*override*/
{
CEntity::SetPosition(position);
(tCollider)->vMin = position - DirectX::XMFLOAT3(60, 0, 60);
(tCollider)->vMax = position + DirectX::XMFLOAT3(60, 120, 60);
}
/*****************************************************************
* Updates() - Updates the subsystem
*
* Ins: dt - the ammount of time that has elapsed
*
* Outs:
*
* Returns:
*
* Mod. Date: 05/28/2015
* Mod. Initials:
*****************************************************************/
/*virtual*/ void CLifeSupport::Update(float dt) /*override*/
{
//Heal the player and refill 02 over time
if (GetAlive( ))
{
m_pPlayer->Heal(m_fHealthRegen * dt * PercentHealth( ));
//Fill oxygen back up to 100
if (m_pPlayer->GetOxygen( ) < 100)
{
m_pPlayer->SetOxygen(m_pPlayer->GetOxygen( ) + (dt * PercentHealth( ) * m_fOxygenRegen));
if (m_pPlayer->GetOxygen( ) > 100)
{
m_pPlayer->SetOxygen(100);
}
}
}
m_fCurrentDSoundTime += dt;
#if PRINT_SUBSYSTEM_STATUS
if (m_fPrintCounter >= 5.f)
{
//DebugPrint((std::string("Oxygen:") + to_string(m_pPlayer->GetOxygen()) + std::string("\n")).c_str(), ConsoleColor::Cyan);
m_fPrintCounter = 0.f;
}
#endif
CSubSystem::Update(dt);
}
void CLifeSupport::TakeDamage(float fDamage)
{
CLivingEntities::TakeDamage(fDamage);
if (m_fCurrentDSoundTime > m_fDamageSoundTimer && GetIsDestroyed() == false)
{
AudioSystemWwise::Get()->PostEvent(AK::EVENTS::PLAY_2D_LSUPPORT_ATTACKED);
if (nullptr != m_pAIDirector)
{
std::string message;
message = "Life support system, under attack!";
m_pAIDirector->SetSubtitle(message);
}
m_fCurrentDSoundTime = 0.0f;
}
}
bool CLifeSupport::LoadStats(void)
{
tinyxml2::XMLDocument xmlDoc;
//TODO: Load stats based on difficulty
xmlDoc.LoadFile("Assets//XML//Balance//LifeSupportStats.xml");
//Did not open file properly
if (xmlDoc.Error())
{
xmlDoc.Clear();
return false;
}
tinyxml2::XMLElement* xmlHead = xmlDoc.RootElement();
tinyxml2::XMLElement* xmlShoulder = xmlHead->FirstChildElement("Default");
tinyxml2::XMLElement* xmlKnee = nullptr;
//Load in the actual stats
xmlKnee = xmlShoulder->FirstChildElement("Defense");
m_fMaxHealth = m_fCurrentHealth = (float)atof(xmlKnee->Attribute("Health"));
//m_fArmor = (float)atof(xmlElement->Attribute("Armor"));
xmlKnee = xmlShoulder->FirstChildElement("Utility");
m_fHealthRegen = (float)atof(xmlKnee->Attribute("HealthRegen"));
m_fOxygenRegen = (float)atof(xmlKnee->Attribute("O2Regen"));
//We're done here
xmlDoc.Clear();
return true;
} |
fcfb78c3db1f78dea17ffdd1319e8244bf2c30d8 | 03f9ce37e1a503ee8e02a113a6a6e75ea9280ac9 | /Section_5/41_Pointers_Arrays.cpp | 580e9f16ec2ac02a0f58dcc672e6e09aafb23b10 | [] | no_license | gasar8/cpp-tutorial | 45ac1152c2c58709683b9dbb6cd7534c2cbd14cd | 89e4b62734347d8728aadec6ddfc29dc257d1cc7 | refs/heads/master | 2022-11-29T15:22:43.059956 | 2020-07-28T07:31:28 | 2020-07-28T07:31:28 | 280,093,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,713 | cpp | 41_Pointers_Arrays.cpp | #include <iostream>
using namespace std;
int main()
{
string texts[] = {"one", "two", "three"};
string *pTexts = texts;
cout << "Sizeof array: " << sizeof(texts) / sizeof(string) << endl;
cout << "s====================================================\n" << endl;
cout << "1. example: Normal for loop" << endl;
for (int i = 0; i < sizeof(texts) / sizeof(string); i++)
{
cout << pTexts[i] << " " << flush;
}
cout << "\n====================================================\n" << endl;
// We can iterate through the array also with the help of pointers
cout << "2. example: Increment pointer" << endl;
for (int i = 0; i < sizeof(texts) / sizeof(string); i++)
{
cout << *pTexts << " " << flush;
pTexts++;
}
cout << "\n====================================================\n" << endl;
// More condensed example
cout << "3. example: Increment pointer (condensed)" << endl;
string *pTexts1 = texts; // Initialize once more, otherwise pTexts remains where it was left at the end of previous for loop.
for (int i = 0; i < sizeof(texts) / sizeof(string); i++, pTexts1++)
{
cout << *pTexts1 << " " << flush;
}
cout << "\n====================================================\n" << endl;
// One more way to iterate through array
cout << "4. example: While loop" << endl;
string *pElement = &texts[0];
string *pEnd = &texts[2];
while (true)
{
cout << *pElement << " " << flush;
if (pElement == pEnd)
{
break;
}
pElement++;
}
cout << "\n====================================================\n" << endl;
return 0;
} |
f0be616f48ec0b03fc1d04e665d278ccec8d4288 | 181e5901afb7079762cae1b0a491c8a390ae6870 | /src/refreshgovernor.h | 18b696057e1762e10860180df6a34d14a62f9d21 | [
"MIT"
] | permissive | hrxcodes/cbftp | baf3cc2da40d0edc04731cc1948122c4bd1eba48 | bf2784007dcc4cc42775a2d40157c51b80383f81 | refs/heads/master | 2022-04-21T04:11:30.532918 | 2020-04-01T06:05:07 | 2020-04-01T06:05:07 | 258,615,100 | 0 | 0 | MIT | 2020-04-24T20:17:59 | 2020-04-24T20:17:58 | null | UTF-8 | C++ | false | false | 512 | h | refreshgovernor.h | #pragma once
#include <memory>
class Site;
class RefreshGovernor {
public:
RefreshGovernor(const std::shared_ptr<Site>& site);
~RefreshGovernor();
bool refreshAllowed() const; // is it time to perform a refresh?
void timePassed(int timepassed); // called continously by the sitelogic ticker
void useRefresh(); // call when a refresh has been "taken" by a connection
void update(); // call when site settings have changed
private:
std::shared_ptr<Site> site;
int interval;
int timepassed;
};
|
0e149785728b3be82433ae0f0f2037f692e0fc90 | 3bae1e0391ab877c0ddfbdfbf392a2c5965d1669 | /cbmc_trunk/cbmc_trunk_windows - Copy/src/langapi/language_util.cpp | 48af18467db04adc4ff97c4ba5b5d9d6d1e3a8c6 | [
"BSD-2-Clause"
] | permissive | cocreature/rvt | 36f6e2a153b3f398bd997ebeccdec38ca6259241 | b9dc17b21a87b5b93326376117401c3011bb4fa3 | refs/heads/master | 2021-01-11T16:14:54.732076 | 2017-08-28T19:18:54 | 2017-08-28T19:18:54 | 80,048,732 | 0 | 1 | null | 2017-01-25T19:20:46 | 2017-01-25T19:20:46 | null | UTF-8 | C++ | false | false | 2,930 | cpp | language_util.cpp | /*******************************************************************\
Module:
Author: Daniel Kroening, kroening@cs.cmu.edu
\*******************************************************************/
#include <memory>
#include "language_util.h"
#include "mode.h"
#include <symbol_table.h>
#include <namespace.h>
#include <language.h>
/*******************************************************************\
Function: from_expr
Inputs:
Outputs:
Purpose:
\*******************************************************************/
std::string from_expr(
const namespacet &ns,
const irep_idt &identifier,
const exprt &expr)
{
std::auto_ptr<languaget> p;
if(identifier=="")
p=std::auto_ptr<languaget>(get_default_language());
else
{
const symbolt *symbol;
if(ns.lookup(identifier, symbol))
p=std::auto_ptr<languaget>(get_default_language());
else if(symbol->mode=="")
p=std::auto_ptr<languaget>(get_default_language());
else
{
languaget *ptr=get_language_from_mode(symbol->mode);
if(ptr==NULL)
throw "symbol `"+id2string(symbol->name)+
"' has unknown mode '"+id2string(symbol->mode)+"'";
p=std::auto_ptr<languaget>(ptr);
}
}
std::string result;
p->from_expr(expr, result, ns);
return result;
}
/*******************************************************************\
Function: from_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
std::string from_type(
const namespacet &ns,
const irep_idt &identifier,
const typet &type)
{
std::auto_ptr<languaget> p;
if(identifier=="")
p=std::auto_ptr<languaget>(get_default_language());
else
{
const symbolt *symbol;
if(ns.lookup(identifier, symbol))
p=std::auto_ptr<languaget>(get_default_language());
else if(symbol->mode=="")
p=std::auto_ptr<languaget>(get_default_language());
else
{
languaget *ptr=get_language_from_mode(symbol->mode);
if(ptr==NULL)
throw "symbol `"+id2string(symbol->name)+
"' has unknown mode '"+id2string(symbol->mode)+"'";
p=std::auto_ptr<languaget>(ptr);
}
}
std::string result;
p->from_type(type, result, ns);
return result;
}
/*******************************************************************\
Function: from_expr
Inputs:
Outputs:
Purpose:
\*******************************************************************/
std::string from_expr(const exprt &expr)
{
symbol_tablet symbol_table;
return from_expr(namespacet(symbol_table), "", expr);
}
/*******************************************************************\
Function: from_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
std::string from_type(const typet &type)
{
symbol_tablet symbol_table;
return from_type(namespacet(symbol_table), "", type);
}
|
00f7dd046c7d435fe5b3007b0eab7576ca9e24ba | 737728a38690e2e31c4b4c1a998fae923502cf54 | /C++/17135_캐슬디펜스.cpp | 6ab27dab889d7cfd9790399ff5f65dc4c00d50e4 | [] | no_license | chaeonee/baekjoon | 528c300f15f7f88a4c608a46e7b82aa6cf325a76 | 90da231f7134ab10a3649d4038da3ad6d631de45 | refs/heads/master | 2023-06-27T03:17:54.908553 | 2021-07-26T07:06:53 | 2021-07-26T07:06:53 | 220,909,690 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,880 | cpp | 17135_캐슬디펜스.cpp | #include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
struct Pos{
int r, c;
};
bool cmp(Pos a, Pos b){
return a.c < b.c;
}
void choice(int N, int M, int D, int**map, int start, vector<Pos> &num, vector<Pos> &e, int &max);
int defense(int N, int M, int D, int**map, vector<Pos> &num, vector<Pos> e);
int main() {
int N, M, D;
cin >> N >> M >> D; //M이 성의 수
int **map = new int*[N];
for(int i = 0; i < N; i++){
map[i] = new int[M];
}
vector<Pos> e;
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
cin >> map[i][j];
if(map[i][j] == 1){
e.push_back({i,j});
}
}
}
vector<Pos> num;
int max = 0;
choice(N, M, D, map, 0, num , e, max);
cout << max;
return 0;
}
void choice(int N, int M, int D, int**map, int start, vector<Pos> &num, vector<Pos> &e, int &max){
if(num.size() == 3){
int **copy = new int*[N];
for(int i = 0; i < N; i++){
copy[i] = new int[M];
}
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
copy[i][j] = map[i][j];
}
}
int tmp = defense(N, M, D, copy, num, e);
if(tmp > max){
max = tmp;
}
return;
}
for(int i = start; i < M; i++){
num.push_back({N,i});
choice(N,M,D,map,i+1,num,e,max);
num.pop_back();
}
}
int defense(int N, int M, int D, int**map, vector<Pos> &num, vector<Pos> e){
int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
int r = 0;
while(!e.empty()){
queue<Pos> remove;
for(int i = 0; i < 3; i++){
queue<Pos> q;
q.push(num[i]);
int d = D;
while(d > 0 && !q.empty()){
vector<Pos> tmp_remove;
bool flag = false;
int S = q.size();
d--;
for(int s = 0; s < S; s++){
Pos p = q.front();
q.pop();
for(int d = 0; d < 4; d++){
int new_r = p.r + dir[d][0];
int new_c = p.c + dir[d][1];
if(new_r >= 0 && new_r < N && new_c >= 0 && new_c < M){
if(map[new_r][new_c] == 1){
flag = true;
tmp_remove.push_back({new_r,new_c});
}
else{
q.push({new_r,new_c});
}
}
}
}
if(flag == true){
sort(tmp_remove.begin(),tmp_remove.end(),cmp);
remove.push(tmp_remove[0]);
break;
}
}
}
while(!remove.empty()){
Pos p = remove.front();
remove.pop();
int s = e.size();
for(int i = 0; i < s; i++){
if(p.r == e[i].r && p.c == e[i].c){
r++;
map[p.r][p.c] = 0;
e.erase(e.begin()+i);
break;
}
}
}
int s = e.size();
int er = 0;
for(int i = s-1; i >= 0; i--){//cout << e[i-er].r << " " << e[i-er].c << "/";
map[e[i].r][e[i].c] = 0;
e[i].r++;
if(e[i].r >= N){
e.erase(e.begin()+i);
er++;
}
else{//cout << e[i].r << " " << e[i].c << endl;
map[e[i].r][e[i].c] = 1;
}
}
}
return r;
}
|
3142e6bb95775ac58eb55ea3c560d946df107904 | 64589428b06258be0b9b82a7e7c92c0b3f0778f1 | /Codeforces/Gym/100651 2004-2005 ACM-ICPC East Central North America Regional Contest (ECNA 2004)/F.cpp | 2a9c0692c443396e5ef63cefef2b938f83741e79 | [] | no_license | splucs/Competitive-Programming | b6def1ec6be720c6fbf93f2618e926e1062fdc48 | 4f41a7fbc71aa6ab8cb943d80e82d9149de7c7d6 | refs/heads/master | 2023-08-31T05:10:09.573198 | 2023-08-31T00:40:32 | 2023-08-31T00:40:32 | 85,239,827 | 141 | 27 | null | 2023-01-08T20:31:49 | 2017-03-16T20:42:37 | C++ | UTF-8 | C++ | false | false | 919 | cpp | F.cpp | #include <bits/stdc++.h>
using namespace std;
#define MAXN 109
int N;
char rank[MAXN][10], cur[10], minrank[10];
int diff[MAXN], mp[10], arr[10];
int bubblesort() {
int ans = 0;
for(int i=0; i<5; i++) {
for(int j=1; j<5; j++) {
if (arr[j] < arr[j-1]){
swap(arr[j], arr[j-1]);
ans++;
}
}
}
return ans;
}
int main() {
int mindiff, curdiff;
while(scanf("%d", &N), N) {
for(int i=0; i<N; i++) {
scanf(" %s", rank[i]);
}
mindiff = 1000009;
for(int k=0; k<5; k++) cur[k] = 'A' + k;
do {
for(int k=0; k<5; k++) mp[cur[k] - 'A'] = k;
curdiff = 0;
for(int j=0; j<N; j++) {
for(int k=0; k<5; k++) arr[k] = mp[rank[j][k] - 'A'];
curdiff += bubblesort();
}
if (curdiff < mindiff) {
mindiff = curdiff;
strcpy(minrank, cur);
}
} while(next_permutation(cur, cur+5));
printf("%s is the median ranking with value %d.\n", minrank, mindiff);
}
return 0;
} |
d59cf0e821e6669e0372885d818d04760bb28dbe | 713a93eeec7c9f9f759eb6bc4b552f0c31307cb1 | /21.03.2021/c.cpp | 60d451dd42f326d6a9c35974b111a0a2bc5714e8 | [] | no_license | markov-alex/practice | 98a55d1a0dd46a4fa729108ac440ad74839b4245 | 83f679698f29a6ed34ac8ac64a2b07bcb2a2247c | refs/heads/main | 2023-06-07T08:21:12.940256 | 2021-07-05T13:53:53 | 2021-07-05T13:53:53 | 383,140,566 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,032 | cpp | c.cpp | #include <bits/stdc++.h>
std::vector<std::list<int>> adjacency_list;
std::vector<bool> visited;
std::vector<bool> leaf;
int res = 0;
void dfs_visit(int u) {
visited[u] = true;
int cnt = 0;
int son = 0;
for (int v : adjacency_list[u]) {
if (!visited[v]) {
cnt++;
son = v;
dfs_visit(v);
}
}
if (cnt == 0) {
leaf[u] = true;
} else if (cnt == 1) {
if (leaf[son]) {
res++;
}
}
}
void dfs() {
visited[0] = true;
for (int u : adjacency_list[0]) {
if (!visited[u]) {
dfs_visit(u);
}
}
}
int main() {
int n;
std::cin >> n;
adjacency_list.resize(n);
visited.assign(n, false);
leaf.assign(n, false);
int from, to;
for (int i = 0; i < n - 1; i++) {
std::cin >> from >> to;
adjacency_list[from - 1].push_back(to - 1);
adjacency_list[to - 1].push_back(from - 1);
}
dfs();
std::cout << res << "\n";
return 0;
} |
bb63db8480d01334347122375547123432eff554 | 4f55e9f539469002db1df650cc14d9347233a57c | /examples/de_casteljau_point2d/main.cpp | 0c908bb0de2271ede8750ba12bec25aaf5efa83e | [
"BSL-1.0"
] | permissive | hazelnusse/spline | 9a5583b2e0b2ff62a72fb7216b2c39b2aa50f359 | 43ef1dbf02947f97b51323774b57e433f9524754 | refs/heads/main | 2023-06-23T18:58:20.759736 | 2021-06-13T21:26:45 | 2021-06-13T21:26:45 | 374,172,603 | 4 | 1 | BSL-1.0 | 2021-06-15T00:27:33 | 2021-06-05T17:19:58 | C++ | UTF-8 | C++ | false | false | 1,980 | cpp | main.cpp | #include <algorithm>
#include <charconv>
#include <cstring>
#include <functional>
#include <limits>
#include <numeric>
#include <random>
#include <spline/de_casteljau_subdivide.hpp>
#include <vector>
namespace
{
template <class Real>
constexpr auto nan = std::numeric_limits<Real>::quiet_NaN();
template <typename Real>
struct Point2d
{
Real data[2];
constexpr Point2d<Real> operator+(Point2d<Real> const& other)
{
return {other.data[0] + data[0], other.data[1] + data[1]};
}
constexpr Point2d<Real> operator*(Real const a)
{
return {data[0] * a, data[1] * a};
}
constexpr Real operator[](std::size_t i) const { return data[i]; }
};
void example1(std::size_t N)
{
using Point = Point2d<double>;
std::vector<Point> input;
input.reserve(N);
std::vector<Point> output;
output.reserve(2 * N - 1);
constexpr Point nan_point{nan<double>, nan<double>};
std::fill(output.begin(), output.end(), nan_point);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(-1.0, 1.0);
double const dt = 2.0 / double(N - 1);
for (std::size_t i = 0; i < N; ++i)
{
// Point const random_point{dis(gen), dis(gen)};
Point const random_point{-1.0 + dt * double(i), dis(gen)};
input.push_back(random_point);
}
spline::de_casteljau_subdivide(
input.cbegin(), input.cend(), output.begin(), 0.5,
[](auto a, auto t) -> Point {
return Point{a[0] * t, a[1] * t};
},
[](auto a, auto b) -> Point {
return Point{a[0] + b[0], a[1] + b[1]};
});
}
} // namespace
int main(int argc, char** argv)
{
if (argc != 2)
{
return 1;
}
std::size_t N = 0;
if (auto [p, ec] =
std::from_chars(argv[1], argv[1] + std::strlen(argv[1]), N);
ec == std::errc())
{
example1(N);
}
else
{
return 1;
}
return 0;
}
|
64bdf9596ee9d7805d6d549982f33bf1795d84ac | 0fcb8388e4ac7610117657c87f87a7788f7d81ff | /robot/main.cpp | 7ca66bb05098444e64fe69ae56c266aa72c02608 | [] | no_license | macrat/projectR-teamC | eee21348d308e0e996e5b87bffa20972cbc58508 | c96d133ca7da26fe81cf4ccef19b5b3bc342b359 | refs/heads/master | 2021-01-19T06:37:01.710832 | 2016-08-05T14:13:44 | 2016-08-05T14:13:44 | 63,482,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,425 | cpp | main.cpp | #include <limits.h>
#include <stdint.h>
#include "mbed.h"
#include "template_serial.h"
#include "hardware.h"
#pragma pack(1)
struct {
struct {
int8_t left, right;
} body;
struct {
int8_t horizontal, vertical, grab;
} arm;
} typedef control_packet_t;
#pragma pack()
struct {
struct {
float left, right;
} body;
struct {
float horizontal, vertical;
uint8_t grab;
} arm;
} typedef control_t;
float fixed2float(int8_t bin) {
return bin / 127.0;
}
control_t parsePacket(control_packet_t packet) {
return {
{ fixed2float(packet.body.left), fixed2float(packet.body.right) },
{ fixed2float(packet.arm.horizontal), fixed2float(packet.arm.vertical), packet.arm.grab },
};
}
class Arm {
private:
static const float hand_opened = 0.75;
static const float hand_closed = 0.45;
DualMotor arm;
Servo hand;
float hand_target;
public:
Arm() : arm(PTC9, PTC8, PTA5, PTA2, PTA12, PTD4, PTA4),
hand(PTA1) {
hand = hand_target = hand_opened;
}
void on_tick() {
hand = hand + (hand_target - hand)/4.0;
}
void update(const control_t& packet) {
arm.setA(packet.arm.horizontal);
arm.setB(packet.arm.vertical);
hand_target = packet.arm.grab ? hand_closed : hand_opened;
}
};
class Body {
private:
TemplateSerial& serial;
DualMotor motor;
public:
Body(TemplateSerial& serial) : serial(serial),
motor(PTE21, PTB1, PTB0, PTE29, PTB3, PTC2, PTB2) {}
void on_tick() {
}
void update(const control_t& packet) {
motor.setA(packet.body.right);
motor.setB(packet.body.left);
}
};
class TeamC {
private:
Arm arm;
Body body;
Ticker ticker;
public:
TeamC(TemplateSerial& serial) : body(serial) {}
void on_tick() {
arm.on_tick();
body.on_tick();
}
void start() {
ticker.attach(this, &TeamC::on_tick, 0.1);
}
void stop() {
ticker.detach();
}
void update(const control_t packet) {
arm.update(packet);
body.update(packet);
}
};
int main() {
TemplateSerial blu(PTE22, PTE23);
TeamC robot(blu);
blu.baud(115200);
robot.start();
while(true){
robot.update(parsePacket(blu.read<control_packet_t>()));
}
}
|
4af87f8dc034c741163bf3614b264f8f3ca1b8e7 | 579d1b8d7166bf800369b5c96c80642c6d4c187a | /dp/0063_uniquePathsWithObstacles.cpp | 76ffbd4b36565ed28e79453111298fdccf03ebae | [] | no_license | zephyr-bj/algorithm | bd1914d9d518ae2b8cccb0d6c3d1c9ba98dbe7bc | e2a52c533ba9bbd6d9530b672cb685ed3d9c4467 | refs/heads/master | 2022-10-14T01:41:45.221235 | 2022-09-26T08:47:51 | 2022-09-26T08:47:51 | 81,426,931 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,324 | cpp | 0063_uniquePathsWithObstacles.cpp | int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
if(m<1)return 0;
int n = obstacleGrid[0].size();
vector<int>tmpR(n,0);
vector<vector<int>>map(m,tmpR);
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(obstacleGrid[i][j]==1)continue;
if(i==0 && j==0){
map[i][j]=1;
}else{
if(i-1>=0&&obstacleGrid[i-1][j]!=1)map[i][j]+=map[i-1][j];
if(j-1>=0&&obstacleGrid[i][j-1]!=1)map[i][j]+=map[i][j-1];
}
}
}
return map[m-1][n-1];
}
// use one dimension dp
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int n = obstacleGrid.size();
if(n<1)return 0;
int m = obstacleGrid[0].size();
if(m<1)return 0;
vector<long>paths(m,0);
for(int j=0; j<m; j++){
if(obstacleGrid[0][j])break;
else paths[j]=1;
}
for(int i=1; i<n; i++){
if(obstacleGrid[i][0])paths[0]=0;
for(int j=1; j<m; j++){
if(obstacleGrid[i][j])paths[j]=0;
else paths[j]=paths[j]+paths[j-1];
}
}
return paths[m-1];
}
|
2909b18f6e2151f75871ce22a12ebb28d77a954f | d96077f7131a2179a879d6651b20b71cad0c3117 | /KY2DViewer_DLL/KY2DViewer_IF.h | 7d70d4fd7c8b3f8bc15afbe7bdfd55ee0788c0c5 | [] | no_license | wowlsh93/2DViwer | 647c135f77baeb041576b387ffb5e644917b80a8 | 4dd102f56d93896f05ddcbfd812a3735fe37163d | refs/heads/master | 2022-04-14T23:50:23.042248 | 2020-04-11T02:47:06 | 2020-04-11T02:47:06 | 254,779,766 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 4,296 | h | KY2DViewer_IF.h | // KY2DViewer_IF.h : KY2DViewer_DLL 의 인터페이스 파일입니다.
//
#pragma once
#include <string>
#ifdef _EXPORTS
#define KY2DAPI __declspec(dllexport)
#else
#define KY2DAPI __declspec(dllimport)
#endif
namespace KY2DVIEWER
{
enum e2DShapeType
{
e2DShapeType_RECT = 0
, e2DShapeType_ELLIPSE
, e2DShapeType_POLYGON
, e2DShapeType_GRID
, e2DShapeType_LINE
, e2DShapeType_TEXT
, e2DShapeType_MAX = 0xFFFFFFFF
};
struct KY2DSAHPE
{
INT m_nID2DShape;
INT m_e2DShapeType;
float m_ptCenterX;
float m_ptCenterY;
float m_szSizeW;
float m_szSizeH;
float m_fAngle;
ULONG m_crColor;
INT m_nCW;
UINT m_nFlags;
std::wstring m_sText;
INT m_nPointCount;
void * m_points;
inline KY2DSAHPE() : m_nID2DShape(-1), m_e2DShapeType(e2DShapeType_RECT), m_fAngle(0.0f)
, m_crColor(RGB(255, 255, 255)), m_ptCenterX(0), m_ptCenterY(0), m_szSizeW(0), m_szSizeH(0)
, m_nCW(0), m_nPointCount(0), m_points(0), m_nFlags(0) {}
};
class KY2DEDITEvents
{
public:
virtual bool On2DShapeSelect(KY2DVIEWER::KY2DSAHPE& shape) = 0;
virtual bool On2DShapeDragStart(KY2DVIEWER::KY2DSAHPE& shape) = 0;
virtual bool On2DShapeDragMove(KY2DVIEWER::KY2DSAHPE& shape) = 0;
virtual bool On2DShapeDragEnd(KY2DVIEWER::KY2DSAHPE& shape) = 0;
virtual bool On2DShapeCreate(KY2DVIEWER::KY2DSAHPE& shape) = 0;
};
extern "C" KY2DAPI BOOL PASCAL viewer_create(HWND hWND);
extern "C" KY2DAPI BOOL PASCAL viewer_delete(HWND hWND);
extern "C" KY2DAPI LONG PASCAL viewer_config(HWND hWND, LPCWSTR szCMD, WPARAM wParam, LPARAM lParam);
};
/****************************************************************************************************
config commands
=====================================================================================================
배경색을 지정함
@param szCMD "set_bk_color"
@param wParam COLORREF 색상
@param lParam 0
-----------------------------------------------------------------------------------------------------
2DShape Event Listener를 등록
@param szCMD "addEventListener"
@param wParam 0
@param lParam KY2DEDITEvents* 등록 할 Event Listener 포인터
-----------------------------------------------------------------------------------------------------
2DShape Event Listener를 제거
@param szCMD "removeEventListener"
@param wParam 0
@param lParam KY2DEDITEvents* 제거 할 Event Listener 포인터
-----------------------------------------------------------------------------------------------------
2D Shape을 모두 제거
@param szCMD "clearShapes"
@param wParam 0
@param lParam 0
-----------------------------------------------------------------------------------------------------
2D Shape 생성
@param szCMD "createShape"
@param wParam 생성할 2DShape의 종류
@param lParam 0
-----------------------------------------------------------------------------------------------------
2D Shape을 등록
@param szCMD "addShapes"
@param wParam KY2DSAHPE 배열의 갯수
@param lParam KY2DSHAPE 배열의 포인터
-----------------------------------------------------------------------------------------------------
2D Shape을 제거
@param szCMD "removeShape"
@param wParam 제거할 2DShape의 아이디
@param lParam 0
-----------------------------------------------------------------------------------------------------
2D Shape 을 선택
@param szCMD "selectShape"
@param wParam 선택할 2DShape의 아이디
@param lParam 0
-----------------------------------------------------------------------------------------------------
2D Shape 종류를 변경
@param szCMD "changeShapeType"
@param wParam 선택할 2DShape의 아이디 또는 -1(현재 선택된 2DShape)
@param lParam 변경 할 2DShape 종류
-----------------------------------------------------------------------------------------------------
2D Shape 의 색상을 변경
@param szCMD "changeShapeColor"
@param wParam 선택할 2DShape의 아이디 또는 -1(현재 선택된 2DShape)
@param lParam COLORREF 변경 할 색상
-----------------------------------------------------------------------------------------------------
2D Shape 생성
@param szCMD "selectCreateColor"
@param wParam 0
@param lParam COLORREF 변경 할 색상
****************************************************************************************************/ |
3955735cf81005b98eee7150e537bf0e10ca8a70 | 6bab09541bd6fe7106d11921db4b46f77c884c95 | /user_msg.cpp | 4d46e8a0619771fee9ccd8c7a43e299e8a92e0cc | [] | no_license | Zsx3/- | 3057b4ceb2df1f9fd509f986067808f7a36ef4a1 | dabfe7c76e6609805a0c2296c9c3385a91a08d1e | refs/heads/master | 2020-09-28T15:03:40.268814 | 2019-12-09T11:56:04 | 2019-12-09T11:56:04 | 226,801,250 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,527 | cpp | user_msg.cpp | #include "stdafx.h"
#include "user_msg.h"
#include<iomanip>
user_msg::user_msg()
{
}
user_msg::~user_msg()
{
}
void user_msg::ReadDocline1()//将人员账号和密码载入一个list<user_information>方便索引查询用户对应的密码
{
ifstream ifs(_F_USER); //输入方式打开文件
char buf[1024] = { 0 };
user_list.clear();
//取出表头(用户|密码)
ifs.getline(buf, sizeof(buf));
while (!ifs.eof()) //没到文件结尾
{
user_information tmp;//用于一次记录人员的账号和密码;通过push_back将所有人员账号密码放入
ifs.getline(buf, sizeof(buf)); //读取一行
//AfxMessageBox(CString(buf));
char *sst = strtok(buf, "|"); //以"|"分隔
if (sst != NULL)
{
tmp.name = CString(sst); //用户名
}
else
{
break;
}
sst = strtok(NULL, "|");
tmp.pwd = CString(sst); //密码
user_list.push_back(tmp); //放在链表的后面
}
ifs.close(); //关闭文件
}
void user_msg::WriteDocline1(CString in_string, int index)
{
ofstream ofs(_F_LOGIN_TIME, ios::app);//
switch (index)
{
case 0://写入换行符
ofs << endl;
break;
case 1://写入用户名
ofs << setiosflags(ios::left) << setw(12) << in_string;
//ofs << in_string<<"|";
break;
case 2://写入登录时间
ofs << setiosflags(ios::left) << setw(40) << in_string;
//ofs << in_string << "|";
break;
case 3://写入退出时间
ofs << setiosflags(ios::left) << setw(40) << in_string;
//ofs << in_string << "|";
break;
default:
break;
}
ofs.close();
}
|
d5926b081cd890c6bfc6be733040c440352e884e | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-frauddetector/include/aws/frauddetector/model/EvaluatedExternalModel.h | e48925bffed811894af7aeceb94a95beb8918154 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 10,057 | h | EvaluatedExternalModel.h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/frauddetector/FraudDetector_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace FraudDetector
{
namespace Model
{
/**
* <p> The details of the external (Amazon Sagemaker) model evaluated for
* generating predictions. </p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/frauddetector-2019-11-15/EvaluatedExternalModel">AWS
* API Reference</a></p>
*/
class EvaluatedExternalModel
{
public:
AWS_FRAUDDETECTOR_API EvaluatedExternalModel();
AWS_FRAUDDETECTOR_API EvaluatedExternalModel(Aws::Utils::Json::JsonView jsonValue);
AWS_FRAUDDETECTOR_API EvaluatedExternalModel& operator=(Aws::Utils::Json::JsonView jsonValue);
AWS_FRAUDDETECTOR_API Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p> The endpoint of the external (Amazon Sagemaker) model. </p>
*/
inline const Aws::String& GetModelEndpoint() const{ return m_modelEndpoint; }
/**
* <p> The endpoint of the external (Amazon Sagemaker) model. </p>
*/
inline bool ModelEndpointHasBeenSet() const { return m_modelEndpointHasBeenSet; }
/**
* <p> The endpoint of the external (Amazon Sagemaker) model. </p>
*/
inline void SetModelEndpoint(const Aws::String& value) { m_modelEndpointHasBeenSet = true; m_modelEndpoint = value; }
/**
* <p> The endpoint of the external (Amazon Sagemaker) model. </p>
*/
inline void SetModelEndpoint(Aws::String&& value) { m_modelEndpointHasBeenSet = true; m_modelEndpoint = std::move(value); }
/**
* <p> The endpoint of the external (Amazon Sagemaker) model. </p>
*/
inline void SetModelEndpoint(const char* value) { m_modelEndpointHasBeenSet = true; m_modelEndpoint.assign(value); }
/**
* <p> The endpoint of the external (Amazon Sagemaker) model. </p>
*/
inline EvaluatedExternalModel& WithModelEndpoint(const Aws::String& value) { SetModelEndpoint(value); return *this;}
/**
* <p> The endpoint of the external (Amazon Sagemaker) model. </p>
*/
inline EvaluatedExternalModel& WithModelEndpoint(Aws::String&& value) { SetModelEndpoint(std::move(value)); return *this;}
/**
* <p> The endpoint of the external (Amazon Sagemaker) model. </p>
*/
inline EvaluatedExternalModel& WithModelEndpoint(const char* value) { SetModelEndpoint(value); return *this;}
/**
* <p> Indicates whether event variables were used to generate predictions. </p>
*/
inline bool GetUseEventVariables() const{ return m_useEventVariables; }
/**
* <p> Indicates whether event variables were used to generate predictions. </p>
*/
inline bool UseEventVariablesHasBeenSet() const { return m_useEventVariablesHasBeenSet; }
/**
* <p> Indicates whether event variables were used to generate predictions. </p>
*/
inline void SetUseEventVariables(bool value) { m_useEventVariablesHasBeenSet = true; m_useEventVariables = value; }
/**
* <p> Indicates whether event variables were used to generate predictions. </p>
*/
inline EvaluatedExternalModel& WithUseEventVariables(bool value) { SetUseEventVariables(value); return *this;}
/**
* <p> Input variables use for generating predictions. </p>
*/
inline const Aws::Map<Aws::String, Aws::String>& GetInputVariables() const{ return m_inputVariables; }
/**
* <p> Input variables use for generating predictions. </p>
*/
inline bool InputVariablesHasBeenSet() const { return m_inputVariablesHasBeenSet; }
/**
* <p> Input variables use for generating predictions. </p>
*/
inline void SetInputVariables(const Aws::Map<Aws::String, Aws::String>& value) { m_inputVariablesHasBeenSet = true; m_inputVariables = value; }
/**
* <p> Input variables use for generating predictions. </p>
*/
inline void SetInputVariables(Aws::Map<Aws::String, Aws::String>&& value) { m_inputVariablesHasBeenSet = true; m_inputVariables = std::move(value); }
/**
* <p> Input variables use for generating predictions. </p>
*/
inline EvaluatedExternalModel& WithInputVariables(const Aws::Map<Aws::String, Aws::String>& value) { SetInputVariables(value); return *this;}
/**
* <p> Input variables use for generating predictions. </p>
*/
inline EvaluatedExternalModel& WithInputVariables(Aws::Map<Aws::String, Aws::String>&& value) { SetInputVariables(std::move(value)); return *this;}
/**
* <p> Input variables use for generating predictions. </p>
*/
inline EvaluatedExternalModel& AddInputVariables(const Aws::String& key, const Aws::String& value) { m_inputVariablesHasBeenSet = true; m_inputVariables.emplace(key, value); return *this; }
/**
* <p> Input variables use for generating predictions. </p>
*/
inline EvaluatedExternalModel& AddInputVariables(Aws::String&& key, const Aws::String& value) { m_inputVariablesHasBeenSet = true; m_inputVariables.emplace(std::move(key), value); return *this; }
/**
* <p> Input variables use for generating predictions. </p>
*/
inline EvaluatedExternalModel& AddInputVariables(const Aws::String& key, Aws::String&& value) { m_inputVariablesHasBeenSet = true; m_inputVariables.emplace(key, std::move(value)); return *this; }
/**
* <p> Input variables use for generating predictions. </p>
*/
inline EvaluatedExternalModel& AddInputVariables(Aws::String&& key, Aws::String&& value) { m_inputVariablesHasBeenSet = true; m_inputVariables.emplace(std::move(key), std::move(value)); return *this; }
/**
* <p> Input variables use for generating predictions. </p>
*/
inline EvaluatedExternalModel& AddInputVariables(const char* key, Aws::String&& value) { m_inputVariablesHasBeenSet = true; m_inputVariables.emplace(key, std::move(value)); return *this; }
/**
* <p> Input variables use for generating predictions. </p>
*/
inline EvaluatedExternalModel& AddInputVariables(Aws::String&& key, const char* value) { m_inputVariablesHasBeenSet = true; m_inputVariables.emplace(std::move(key), value); return *this; }
/**
* <p> Input variables use for generating predictions. </p>
*/
inline EvaluatedExternalModel& AddInputVariables(const char* key, const char* value) { m_inputVariablesHasBeenSet = true; m_inputVariables.emplace(key, value); return *this; }
/**
* <p> Output variables. </p>
*/
inline const Aws::Map<Aws::String, Aws::String>& GetOutputVariables() const{ return m_outputVariables; }
/**
* <p> Output variables. </p>
*/
inline bool OutputVariablesHasBeenSet() const { return m_outputVariablesHasBeenSet; }
/**
* <p> Output variables. </p>
*/
inline void SetOutputVariables(const Aws::Map<Aws::String, Aws::String>& value) { m_outputVariablesHasBeenSet = true; m_outputVariables = value; }
/**
* <p> Output variables. </p>
*/
inline void SetOutputVariables(Aws::Map<Aws::String, Aws::String>&& value) { m_outputVariablesHasBeenSet = true; m_outputVariables = std::move(value); }
/**
* <p> Output variables. </p>
*/
inline EvaluatedExternalModel& WithOutputVariables(const Aws::Map<Aws::String, Aws::String>& value) { SetOutputVariables(value); return *this;}
/**
* <p> Output variables. </p>
*/
inline EvaluatedExternalModel& WithOutputVariables(Aws::Map<Aws::String, Aws::String>&& value) { SetOutputVariables(std::move(value)); return *this;}
/**
* <p> Output variables. </p>
*/
inline EvaluatedExternalModel& AddOutputVariables(const Aws::String& key, const Aws::String& value) { m_outputVariablesHasBeenSet = true; m_outputVariables.emplace(key, value); return *this; }
/**
* <p> Output variables. </p>
*/
inline EvaluatedExternalModel& AddOutputVariables(Aws::String&& key, const Aws::String& value) { m_outputVariablesHasBeenSet = true; m_outputVariables.emplace(std::move(key), value); return *this; }
/**
* <p> Output variables. </p>
*/
inline EvaluatedExternalModel& AddOutputVariables(const Aws::String& key, Aws::String&& value) { m_outputVariablesHasBeenSet = true; m_outputVariables.emplace(key, std::move(value)); return *this; }
/**
* <p> Output variables. </p>
*/
inline EvaluatedExternalModel& AddOutputVariables(Aws::String&& key, Aws::String&& value) { m_outputVariablesHasBeenSet = true; m_outputVariables.emplace(std::move(key), std::move(value)); return *this; }
/**
* <p> Output variables. </p>
*/
inline EvaluatedExternalModel& AddOutputVariables(const char* key, Aws::String&& value) { m_outputVariablesHasBeenSet = true; m_outputVariables.emplace(key, std::move(value)); return *this; }
/**
* <p> Output variables. </p>
*/
inline EvaluatedExternalModel& AddOutputVariables(Aws::String&& key, const char* value) { m_outputVariablesHasBeenSet = true; m_outputVariables.emplace(std::move(key), value); return *this; }
/**
* <p> Output variables. </p>
*/
inline EvaluatedExternalModel& AddOutputVariables(const char* key, const char* value) { m_outputVariablesHasBeenSet = true; m_outputVariables.emplace(key, value); return *this; }
private:
Aws::String m_modelEndpoint;
bool m_modelEndpointHasBeenSet = false;
bool m_useEventVariables;
bool m_useEventVariablesHasBeenSet = false;
Aws::Map<Aws::String, Aws::String> m_inputVariables;
bool m_inputVariablesHasBeenSet = false;
Aws::Map<Aws::String, Aws::String> m_outputVariables;
bool m_outputVariablesHasBeenSet = false;
};
} // namespace Model
} // namespace FraudDetector
} // namespace Aws
|
8e5df32b3fd90c24a355c6bc8b3e1e5cebd80f32 | fb5a7667fa36a16f312c7828837558c69fdf27e8 | /SimpleExample2019.4.23/iOS-Export/SimpleExample/Libraries/RegisterMonoModules.cpp | cb064b90196c214b210a9d1f5f270ddc977daa45 | [] | no_license | skillz/integration-examples | 048cce107e1b0f67408736c4cd0d07f3f73daf2c | f283c0624d757131d48d7af135550281709877ba | refs/heads/master | 2021-12-15T06:02:38.174945 | 2021-12-13T22:25:38 | 2021-12-13T22:25:38 | 250,074,665 | 9 | 28 | null | 2021-12-13T22:25:38 | 2020-03-25T19:40:33 | C | UTF-8 | C++ | false | false | 128 | cpp | RegisterMonoModules.cpp | version https://git-lfs.github.com/spec/v1
oid sha256:7d261bc6d7f287092fb13bc986cbc7a841992abce3ddf97013521cf2c04e277b
size 368
|
ccce4a4989f8c08e21e510c0da448d3a4e896e93 | ce37ba275f0c32e2653df1833dd09391c7064dff | /include/cbag/polygon/polygon_90_data.h | 2888de92af884631913ba1ecbd17226070cf882e | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | ucb-art/cbag_polygon | e1a35b609af90c4147b07a9460abfec4d10d9d42 | 2c00d8c768fca40ced7905f77b4e3dad49c0b85b | refs/heads/master | 2022-12-16T23:25:48.097823 | 2020-06-24T18:13:57 | 2020-06-24T18:13:57 | 292,124,854 | 0 | 0 | null | 2020-09-01T22:54:00 | 2020-09-01T22:53:59 | null | UTF-8 | C++ | false | false | 6,318 | h | polygon_90_data.h | // Copyright 2019 Blue Cheetah Analog Design Inc.
// SPDX-License-Identifier: Apache-2.0
#ifndef CBAG_POLYGON_POLYGON_90_DATA_H
#define CBAG_POLYGON_POLYGON_90_DATA_H
#include <type_traits>
#include <vector>
#include <cbag/polygon/point_concept.h>
#include <cbag/polygon/point_data.h>
#include <cbag/polygon/polygon_90_concept.h>
#include <cbag/polygon/polygon_concept.h>
namespace cbag {
namespace polygon {
template <typename T> class polygon_90_data {
public:
using coordinate_type = T;
using compact_iterator_type = typename std::vector<coordinate_type>::const_iterator;
using area_type = typename coordinate_traits<coordinate_type>::area_type;
using iterator_type = poly90_point_iterator<compact_iterator_type, coordinate_type>;
using point_type = typename iterator_type::value_type;
private:
std::vector<coordinate_type> coords_;
public:
polygon_90_data() = default;
explicit polygon_90_data(std::vector<coordinate_type> compact_data)
: coords_(std::move(compact_data)) {
_fix_coord();
}
template <typename iT, IsPoint<typename iT::value_type> = 0>
polygon_90_data(iT start, iT stop, std::size_t n = 4) {
set_points(start, stop, n);
}
template <typename iT,
std::enable_if_t<std::is_same_v<coordinate_type, typename iT::value_type>, int> = 0>
polygon_90_data(iT start_compact, iT stop_compact, std::size_t n = 4) {
set_compact(start_compact, stop_compact, n);
}
bool operator==(const polygon_90_data &rhs) const { return coords_ == rhs.coords_; }
auto begin() const -> iterator_type { return {coords_.begin(), coords_.end()}; }
auto end() const -> iterator_type { return iterator_type{coords_.end()}; }
auto begin_compact() const noexcept -> compact_iterator_type { return coords_.begin(); }
auto end_compact() const noexcept -> compact_iterator_type { return coords_.end(); }
std::size_t size() const noexcept { return coords_.size(); }
polygon_90_data &operator=(std::vector<coordinate_type> data) {
coords_ = std::move(data);
_fix_coord();
return *this;
}
template <typename iT, IsPoint<typename iT::value_type> = 0>
polygon_90_data &set_points(iT start, iT stop, std::size_t n = 4) {
coords_.clear();
if (start != stop) {
coords_.reserve(n);
auto orient = 0;
auto y0 = get(*start, orientation_2d::Y);
for (; start != stop; ++start, orient ^= 1) {
coords_.emplace_back(get(*start, static_cast<orientation_2d>(orient)));
}
n = coords_.size();
if (n < 4)
coords_.clear();
else if (n & 1)
coords_.emplace_back(y0);
}
return *this;
}
template <typename iT,
std::enable_if_t<std::is_same_v<coordinate_type, typename iT::value_type>, int> = 0>
polygon_90_data &set_compact(iT start_compact, iT stop_compact, std::size_t n = 4) {
coords_.clear();
coords_.reserve(n);
for (; start_compact != stop_compact; ++start_compact) {
coords_.emplace_back(*start_compact);
}
_fix_coord();
return *this;
}
private:
void _fix_coord() {
auto n = coords_.size();
if (n < 4)
coords_.clear();
else if (n & 1)
coords_.pop_back();
}
}; // namespace polygon
template <typename T>
bool operator!=(const polygon_90_data<T> &lhs, const polygon_90_data<T> &rhs) {
return !(lhs == rhs);
}
template <typename T> std::string to_string(const polygon_90_data<T> &obj) {
std::string ans;
auto n = obj.size();
if (n < 4) {
ans = "[]";
} else {
ans += "[";
auto iter = obj.begin_compact();
auto stop = obj.end_compact();
ans += std::to_string(*iter);
++iter;
for (; iter != stop; ++iter) {
ans += ", ";
ans += std::to_string(*iter);
}
ans += "]";
}
return ans;
}
template <typename T>
std::ostream &operator<<(std::ostream &stream, const polygon_90_data<T> &obj) {
stream << to_string(obj);
return stream;
}
template <typename T> struct tag<polygon_90_data<T>> { using type = polygon_90_tag; };
template <typename T> struct polygon_90_traits<polygon_90_data<T>> {
using polygon_type = polygon_90_data<T>;
using coordinate_type = typename polygon_type::coordinate_type;
using area_type = typename polygon_type::area_type;
using compact_iterator_type = typename polygon_type::compact_iterator_type;
using iterator_type = typename polygon_type::iterator_type;
using point_type = typename iterator_type::value_type;
static compact_iterator_type begin_compact(const polygon_type &t) { return t.begin_compact(); }
static compact_iterator_type end_compact(const polygon_type &t) { return t.end_compact(); }
static iterator_type begin_points(const polygon_type &t) { return t.begin(); }
static iterator_type end_points(const polygon_type &t) { return t.end(); }
static std::size_t size(const polygon_type &t) { return t.size(); }
template <typename iT, IsPoint<typename iT::value_type> = 0>
static void set_points(polygon_type &t, iT start, iT stop, std::size_t n = 4) {
t.set_points(start, stop, n);
}
template <typename iT,
std::enable_if_t<std::is_same_v<coordinate_type, typename iT::value_type>, int> = 0>
static void set_compact(polygon_type &t, iT start, iT stop, std::size_t n = 4) {
t.set_compact(start, stop, n);
}
static void set_compact(polygon_type &t, std::vector<coordinate_type> &&data) {
t = std::move(data);
}
template <typename iT,
std::enable_if_t<std::is_same_v<coordinate_type, typename iT::value_type>, int> = 0>
static polygon_type construct_compact(iT start, iT stop, std::size_t n = 4) {
return {start, stop, n};
}
template <typename iT, IsPoint<typename iT::value_type> = 0>
static polygon_type construct(iT start, iT stop, std::size_t n = 4) {
auto ans = polygon_type();
ans.set_points(start, stop, n);
return ans;
}
};
} // namespace polygon
} // namespace cbag
#endif
|
d8e6efc4a8f7af3b76cdcdf874bb62048dafd132 | 2d7e3b4a580d4476a6415866754354de287602a3 | /pemc/pemc.cc | ebc768b7c34ddb39dc831a1120129ad4e884e3d1 | [
"MIT"
] | permissive | joleuger/pemc | ff3439808ebeea654dbcea34dd4d0d6980f88e6b | ba1608a8b575bbd324d59e376a60f54f1f55526b | refs/heads/master | 2023-07-07T15:35:07.134183 | 2023-06-27T19:19:43 | 2023-06-27T19:19:43 | 147,083,609 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,042 | cc | pemc.cc | // The MIT License (MIT)
//
// Copyright (c) 2014-2018, Institute for Software & Systems Engineering
// Copyright (c) 2018, Johannes Leupolz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "pemc/pemc.h"
#include <atomic>
#include "pemc/executable_model/model_executor.h"
#include "pemc/formula/bounded_unary_formula.h"
#include "pemc/generic_traverser/generic_traverser.h"
#include "pemc/lmc/lmc_model_checker.h"
#include "pemc/lmc_traverser/add_transitions_to_lmc_modifier.h"
#include "pemc/lmc_traverser/lmc_choice_resolver.h"
#include "pemc/reachability_traverser/reachability_choice_resolver.h"
#include "pemc/reachability_traverser/reachability_modifier.h"
namespace pemc {
Pemc::Pemc() {
conf = Configuration();
};
Pemc::Pemc(const Configuration& _conf) {
conf = _conf;
};
std::unique_ptr<Lmc> Pemc::buildLmcFromExecutableModel(
const std::function<std::unique_ptr<AbstractModel>()>& modelCreator,
std::vector<std::shared_ptr<Formula>> formulas) {
// initialize an empty Lmc, which will contain the resulting model.
auto lmc = std::make_unique<Lmc>();
lmc->initialize(*conf.modelCapacity);
// Set the labels of the Lmc.
auto labelIdentifier = std::vector<std::string>();
labelIdentifier.reserve(formulas.size());
std::transform(formulas.begin(), formulas.end(),
std::back_inserter(labelIdentifier),
[](std::shared_ptr<Formula>& formula) {
return formula->getIdentifier();
});
lmc->setLabelIdentifier(labelIdentifier);
auto traverser = GenericTraverser(conf);
// Declare a creator for a ModelExecutor that has an instance of the model
// that should be executed.
auto transitionsCalculatorCreator =
[&modelCreator, &conf = this->conf,
&formulas]() -> std::unique_ptr<ModelExecutor> {
auto modelExecutor = std::make_unique<ModelExecutor>(conf);
auto model = modelCreator();
model->setFormulasForLabel(formulas);
modelExecutor->setModel(std::move(model));
modelExecutor->setChoiceResolver(std::make_unique<LmcChoiceResolver>());
return modelExecutor;
};
traverser.transitionsCalculatorCreator = transitionsCalculatorCreator;
// Declare a creator for a modifier that adds states to the Lmc.
auto addTransitionsToLmcModifierCreator =
[p_lmc = lmc.get()]() -> std::unique_ptr<IPostStateStorageModifier> {
auto modifier = std::make_unique<AddTransitionsToLmcModifier>(p_lmc);
return modifier;
};
traverser.postStateStorageModifierCreators.push_back(
addTransitionsToLmcModifierCreator);
// Traverse the model.
traverser.traverse(cancellation_token::none());
// Finish the creation of the Lmc and return it.
auto getNoOfStates = traverser.getNoOfStates();
lmc->finishCreation(getNoOfStates);
return lmc;
}
bool Pemc::checkReachabilityInExecutableModel(
const std::function<std::unique_ptr<AbstractModel>()>& modelCreator,
std::shared_ptr<Formula> formula) {
// initialize an empty Lmc, which will contain the resulting model.
auto lmc = std::make_unique<Lmc>();
lmc->initialize(*conf.modelCapacity);
// Because there is only one formula there is only one label
std::vector<std::shared_ptr<Formula>> formulas;
formulas.push_back(formula);
auto traverser = GenericTraverser(conf);
// Declare a creator for a ModelExecutor that has an instance of the model
// that should be executed.
auto transitionsCalculatorCreator =
[&modelCreator, &conf = this->conf,
&formulas]() -> std::unique_ptr<ModelExecutor> {
auto modelExecutor = std::make_unique<ModelExecutor>(conf);
auto model = modelCreator();
model->setFormulasForLabel(formulas);
modelExecutor->setModel(std::move(model));
modelExecutor->setChoiceResolver(
std::make_unique<ReachabilityChoiceResolver>());
return modelExecutor;
};
traverser.transitionsCalculatorCreator = transitionsCalculatorCreator;
std::atomic<bool> reached(false);
// the tokenSource is used to cancel the token when a state satisfying the
// condition is reached
cancellation_token_source tokenSource;
// Declare a creator for a modifier that adds states to the Lmc.
auto reachabilityModifierCreator =
[&reached, &tokenSource]() -> std::unique_ptr<IPostStateStorageModifier> {
auto modifier =
std::make_unique<ReachabilityModifier>(&reached, tokenSource);
return modifier;
};
traverser.postStateStorageModifierCreators.push_back(
reachabilityModifierCreator);
// Traverse the model.
traverser.traverse(tokenSource.get_token());
return reached.load();
}
Probability Pemc::calculateProbabilityToReachStateWithinBound(
Lmc& lmc,
std::shared_ptr<Formula> formula,
int32_t bound) {
auto finally_formula = std::make_shared<BoundedUnaryFormula>(
formula, UnaryOperator::Finally, bound);
auto mc = LmcModelChecker(lmc, conf);
auto probability = mc.calculateProbability(*finally_formula);
return probability;
}
} // namespace pemc
|
bc3b96aa3980611f7908a9df86b8027abfc8d141 | 2329437594f97ae6fd43edfed26456854e745995 | /VarInfo.cpp | e5ad691774a3a0ead8363e6d17281c48ffc5edd6 | [] | no_license | TomSendrovich/FlightGear | 450abd18503716fda388daaa132e1f126ca6d50c | 17b8e3ecef255aa179ca86eb4c1e5de41bc1e6a4 | refs/heads/master | 2020-12-06T03:14:39.288384 | 2020-01-04T14:51:41 | 2020-01-04T14:51:41 | 232,323,644 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 931 | cpp | VarInfo.cpp | //
// Created by guy on 16/12/2019.
//
#include "VarInfo.h"
VarInfo::VarInfo(string name, int direction, string path) {
_name = name;
_direction = direction;
_path = path;
_value = 0.0;
}
double VarInfo::getValue() {
lock_guard<mutex> lock(m_lock);
return _value;
}
void VarInfo::setValue(double value) {
lock_guard<mutex> lock(m_lock);
_value = value;
}
string VarInfo::getName() {
lock_guard<mutex> lock(m_lock);
return _name;
}
string VarInfo::getPath() {
lock_guard<mutex> lock(m_lock);
return _path;
}
int VarInfo::getDirection() {
lock_guard<mutex> lock(m_lock);
return _direction;
}
void VarInfo::setDirection(int direction) {
lock_guard<mutex> lock(m_lock);
_direction = direction;
}
void VarInfo::setSecondName(string secondName) {
lock_guard<mutex> lock(m_lock);
_secondName = secondName;
}
string VarInfo::getSecondName() {
lock_guard<mutex> lock(m_lock);
return _secondName;
}
|
1c0883e901556f042bdbf67e0b33f0579b672c1d | 93deffee902a42052d9f5fb01e516becafe45b34 | /cf/1000/C.cpp | 0b5e937eb61c55345f26dee3a3392a81b6b9b5ae | [] | no_license | kobortor/Competitive-Programming | 1aca670bc37ea6254eeabbe33e1ee016174551cc | 69197e664a71a492cb5b0311a9f7b00cf0b1ccba | refs/heads/master | 2023-06-25T05:04:42.492243 | 2023-06-16T18:28:42 | 2023-06-16T18:28:42 | 95,998,328 | 10 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 607 | cpp | C.cpp | #include<bits/stdc++.h>
using namespace std;
#define allof(x) (x).begin(), (x).end()
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main(){
cin.tie(0);
cin.sync_with_stdio(0);
int N;
cin >> N;
map<ll, ll> mp, ans;
for(int a = 1; a <= N; a++){
ll l, r;
cin >> l >> r;
mp[l]++;
mp[r + 1]--;
}
ll cnt = 0;
ll prv = 0;
for(pll p : mp){
ans[cnt] += p.first - prv;
cnt += p.second;
prv = p.first;
}
for(int a = 1; a <= N; a++){
cout << ans[a] << " ";
}
}
|
7193bb3b97436f858d3eef2bbb34db44c4c6a8a8 | 0cd73b1729b90fed0a99852bcf7a2862f9397250 | /hs_unoidl/src/writer.cxx | cb639533daedc17e5786abf0c74f22a68b470f74 | [] | no_license | jorgecunhamendes/haskell-uno-binding | 26e224019f3ec8851446b033d9efbf96e97850ab | 7f99674cf986f5f9a4079353f079d7982e2ffc61 | refs/heads/master | 2021-01-23T20:45:15.587242 | 2015-08-28T11:23:00 | 2015-08-28T11:23:00 | 37,615,841 | 7 | 2 | null | 2015-08-25T09:31:02 | 2015-06-17T19:20:35 | C++ | UTF-8 | C++ | false | false | 4,909 | cxx | writer.cxx | /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "writer.hxx"
#include <string>
#include <vector>
#include <fstream>
#include <ostream>
#include <iostream>
#include "osl/file.hxx"
#include "osl/process.h"
#include "rtl/ref.hxx"
#include "file.hxx"
#include "types.hxx"
#include "utils.hxx"
#include "writer/cxx.hxx"
#include "writer/hxx.hxx"
#include "writer/hs.hxx"
#include "writer/utils.hxx"
using rtl::OUString;
void writePlainStruct (EntityList const & entities, EntityRef const & entity) {
const OUString filePath ("gen/" + Module(entity->type).asPathCapitalized());
// cxx
OUString cxxFilePath = filePath + cxxFileExtension;
CxxWriter cxx (File::getFileUrlFromPath(cxxFilePath), entity, entities);
cxx.writeOpening();
cxx.writePlainStructTypeEntity();
// hxx
OUString hxxFilePath = filePath + hxxFileExtension;
HxxWriter hxx (File::getFileUrlFromPath(hxxFilePath), entity, entities);
hxx.writeOpening();
hxx.writePlainStructTypeEntity();
hxx.writeClosing();
// hs
OUString hsFilePath = filePath + hsFileExtension;
HsWriter hs (File::getFileUrlFromPath(hsFilePath), entity, entities);
hs.writeOpening(hs.plainStructTypeEntityDependencies());
hs.writePlainStructTypeEntity();
}
void writeInterface (EntityList const & entities, EntityRef const & entity) {
const OUString filePath ("gen/" + Module(entity->type).asPathCapitalized());
// cxx
OUString cxxFilePath = filePath + cxxFileExtension;
CxxWriter cxx (File::getFileUrlFromPath(cxxFilePath), entity, entities);
cxx.writeOpening();
cxx.writeInterfaceTypeEntity();
// hxx
OUString hxxFilePath = filePath + hxxFileExtension;
HxxWriter hxx (File::getFileUrlFromPath(hxxFilePath), entity, entities);
hxx.writeOpening();
hxx.writeInterfaceTypeEntity();
hxx.writeClosing();
// hs
OUString hsFilePath = filePath + hsFileExtension;
HsWriter hs (File::getFileUrlFromPath(hsFilePath), entity, entities);
hs.writeOpening(hs.interfaceTypeEntityDependencies());
hs.writeInterfaceTypeEntity();
}
void writeException (EntityRef const & entity)
{
const OUString filePath ("gen/" + Module(entity->type).asPathCapitalized());
// cxx
OUString cxxFilePath = filePath + cxxFileExtension;
CxxWriter cxx (File::getFileUrlFromPath(cxxFilePath), entity);
cxx.writeOpening();
// hxx
OUString hxxFilePath = filePath + hxxFileExtension;
HxxWriter hxx (File::getFileUrlFromPath(hxxFilePath), entity);
hxx.writeOpening();
hxx.writeClosing();
// hs
OUString hsFilePath = filePath + hsFileExtension;
HsWriter hs (File::getFileUrlFromPath(hsFilePath), entity);
hs.writeOpening();
}
void writeSingleInterfaceBasedService (EntityList const & entities,
EntityRef const & entity)
{
const OUString filePath ("gen/" + Module(entity->type).asPathCapitalized());
// cxx
OUString cxxFilePath = filePath + cxxFileExtension;
CxxWriter cxx (File::getFileUrlFromPath(cxxFilePath), entity, entities);
cxx.writeOpening();
cxx.writeSingleInterfaceBasedServiceEntity();
// hxx
OUString hxxFilePath = filePath + hxxFileExtension;
HxxWriter hxx (File::getFileUrlFromPath(hxxFilePath), entity, entities);
hxx.writeOpening();
hxx.writeSingleInterfaceBasedServiceEntity();
hxx.writeClosing();
// hs
OUString hsFilePath = filePath + hsFileExtension;
HsWriter hs (File::getFileUrlFromPath(hsFilePath), entity, entities);
hs.writeOpening(hs.singleInterfaceBasedServiceEntityDependencies());
hs.writeSingleInterfaceBasedServiceEntity();
}
void writeInterfaceBasedSingleton (EntityList const & entities,
EntityRef const & entity)
{
const OUString filePath ("gen/" + Module(entity->type).asPathCapitalized());
// hs
OUString hsFilePath = filePath + hsFileExtension;
HsWriter hs (File::getFileUrlFromPath(hsFilePath), entity, entities);
hs.writeOpening(hs.interfaceBasedSingletonEntityDependencies());
hs.writeInterfaceBasedSingletonEntity();
}
void writeModule (ModuleList const & modules, const EntityRef & entity) {
const OUString filePath ("gen/" + Module(entity->type).asPathCapitalized());
ModuleList::const_iterator entitiesIt = modules.find(entity->type);
assert(entitiesIt != modules.end());
EntityList entities = entitiesIt->second;
OUString hsFilePath = filePath + hsFileExtension;
HsWriter hs (File::getFileUrlFromPath(hsFilePath), entity, entities);
hs.writeOpening();
hs.writeModule();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
e188b8362982d91570af9207f0e3e6418e8ccb8e | 2f100caef4b7c2a3e0bef722325c59a5ab91086c | /Scene.h | da2581cbc5ea47cddbc27d60ec0ee7c4055277c2 | [] | no_license | ilotXXI/RayBacktrace | 3f0222c499236b78af2973d5ba0866168e278ba8 | 3acd1aad22537a3e595cffc8a16d515f248086fe | refs/heads/master | 2021-01-11T20:37:50.557873 | 2019-02-01T10:50:10 | 2019-02-01T10:50:10 | 79,155,592 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,729 | h | Scene.h | #ifndef SCENE_H
#define SCENE_H
#include <vector>
#include "Polygon.h"
#include "SpotLight.h"
class Scene
{
public:
Scene();
Scene(const std::vector<Polygon> &polygons,
const std::vector<SpotLight> &lights);
const std::vector<Polygon> & polygons() const;
std::vector<Polygon> polygons();
void setPolygons(const std::vector<Polygon> &polygons);
void addPolygon(const Polygon &polygon);
void addPolygon(Polygon &&polygon);
size_t polygonsCount() const;
const std::vector<SpotLight> & lights() const;
std::vector<SpotLight> lights();
void setLights(const std::vector<SpotLight> &lights);
void addLight(const SpotLight &light);
void addLight(SpotLight &&light);
size_t lightsCount() const;
void clear();
private:
std::vector<Polygon> _polygons;
std::vector<SpotLight> _lights;
};
inline const std::vector<Polygon> & Scene::polygons() const
{
return _polygons;
}
inline std::vector<Polygon> Scene::polygons()
{
return _polygons;
}
inline void Scene::addPolygon(const Polygon &polygon)
{
_polygons.push_back(polygon);
}
inline void Scene::addPolygon(Polygon &&polygon)
{
_polygons.emplace_back(std::move(polygon));
}
inline size_t Scene::polygonsCount() const
{
return _polygons.size();
}
inline const std::vector<SpotLight> & Scene::lights() const
{
return _lights;
}
inline std::vector<SpotLight> Scene::lights()
{
return _lights;
}
inline void Scene::addLight(const SpotLight &light)
{
_lights.push_back(light);
}
inline void Scene::addLight(SpotLight &&light)
{
_lights.emplace_back(std::move(light));
}
inline size_t Scene::lightsCount() const
{
return _lights.size();
}
#endif // SCENE_H
|
a007468323d5709200aa0e48d6c299262d22c701 | 4f462f866f1b2470fa2b4b35731ff65b5231a0c9 | /src/datastore.cpp | 52a739696196b535254b71946b80ed407457bcd6 | [] | no_license | Gigahawk/mech366_DAQ | e52c172dd0fb99af849e8d144ad128cada5c36c2 | 5e0216526d31b0a54b3dc2a7c3af7b06947a99ba | refs/heads/master | 2020-09-11T12:01:20.098243 | 2019-12-01T12:04:22 | 2019-12-01T12:04:22 | 222,057,566 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,409 | cpp | datastore.cpp | #include "datastore.h"
#define DS_BUFFER_LENGTH (uint16_t)(1.05*COLLECTION_PERIOD*ACCEL_RATE)
int16_t x_accel[DS_BUFFER_LENGTH];
int16_t y_accel[DS_BUFFER_LENGTH];
int16_t z_accel[DS_BUFFER_LENGTH];
int16_t accel_time[DS_BUFFER_LENGTH];
volatile uint16_t accel_idx;
MPU6050 accel = MPU6050(ACCEL_ADDRESS);
bool collecting_data;
bool accel_need_save;
bool imu_connected = false;
unsigned long data_collect_start;
volatile unsigned long data_cur_time;
void accel_isr();
void reset_data() {
Serial.println("Clearing accelerometer buffers");
for(int i=0; i < DS_BUFFER_LENGTH; i++) {
x_accel[i] = 0;
y_accel[i] = 0;
z_accel[i] = 0;
}
Serial.println("Accelerometer buffers cleared");
}
void start_data() {
Serial.println("Starting data collection");
accel_idx = 0;
data_collect_start = millis();
attachInterrupt(
digitalPinToInterrupt(ACCEL_INT),
accel_isr,
FALLING);
accel_isr();
}
String generateFilename() {
String filename = String(loaded_file) + "_" + String(millis()) + ".xyz";
// Try again if filename already exists
while(SPIFFS.exists(filename))
filename = String(loaded_file) + "_" + String(millis()) + ".xyz";
return filename;
}
void save_data() {
String filename = generateFilename();
Serial.print("Saving data to ");
Serial.println(filename);
int16_t txyz[4];
File xyz_file = SPIFFS.open(filename, "w");
if(!xyz_file) {
Serial.println("file open failed");
return;
}
for(int i=0; i < DS_BUFFER_LENGTH; i++) {
txyz[0] = accel_time[i];
txyz[1] = x_accel[i];
txyz[2] = y_accel[i];
txyz[3] = z_accel[i];
xyz_file.write((uint8_t*)txyz, 8);
}
xyz_file.close();
Serial.print("Saved successfully");
}
void stop_data() {
detachInterrupt(digitalPinToInterrupt(ACCEL_INT));
accel_need_save = true;
}
void accel_loop() {
if(accel_need_save) {
save_data();
accel_need_save = false;
}
}
void ICACHE_RAM_ATTR accel_isr() {
data_cur_time = millis() - data_collect_start;
if(data_cur_time >= COLLECTION_PERIOD*1000 || accel_idx >= DS_BUFFER_LENGTH) {
stop_data();
return;
}
accel.getAcceleration(x_accel + accel_idx, y_accel + accel_idx, z_accel + accel_idx);
accel_time[accel_idx] = data_cur_time;
accel_idx++;
}
|
8f4dfc66f990bbe848569992e5364b988168e6f8 | d6b4bdf418ae6ab89b721a79f198de812311c783 | /tiw/include/tencentcloud/tiw/v20190919/model/DescribeTIWRoomDailyUsageRequest.h | 557ed6d6fa4dd2fc39d0c2cffcb16c9e4a5d8abc | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp-intl-en | d0781d461e84eb81775c2145bacae13084561c15 | d403a6b1cf3456322bbdfb462b63e77b1e71f3dc | refs/heads/master | 2023-08-21T12:29:54.125071 | 2023-08-21T01:12:39 | 2023-08-21T01:12:39 | 277,769,407 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,542 | h | DescribeTIWRoomDailyUsageRequest.h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_TIW_V20190919_MODEL_DESCRIBETIWROOMDAILYUSAGEREQUEST_H_
#define TENCENTCLOUD_TIW_V20190919_MODEL_DESCRIBETIWROOMDAILYUSAGEREQUEST_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Tiw
{
namespace V20190919
{
namespace Model
{
/**
* DescribeTIWRoomDailyUsage request structure.
*/
class DescribeTIWRoomDailyUsageRequest : public AbstractModel
{
public:
DescribeTIWRoomDailyUsageRequest();
~DescribeTIWRoomDailyUsageRequest() = default;
std::string ToJsonString() const;
/**
* 获取SdkAppId of the whiteboard application.
* @return SdkAppId SdkAppId of the whiteboard application.
*
*/
int64_t GetSdkAppId() const;
/**
* 设置SdkAppId of the whiteboard application.
* @param _sdkAppId SdkAppId of the whiteboard application.
*
*/
void SetSdkAppId(const int64_t& _sdkAppId);
/**
* 判断参数 SdkAppId 是否已赋值
* @return SdkAppId 是否已赋值
*
*/
bool SdkAppIdHasBeenSet() const;
/**
* 获取Subproduct usage to be queried. The following parameters are supported:
- sp_tiw_board: The duration of use of whiteboards, in minutes.
- sp_tiw_ric: The duration of real-time recording, in minutes.
* @return SubProduct Subproduct usage to be queried. The following parameters are supported:
- sp_tiw_board: The duration of use of whiteboards, in minutes.
- sp_tiw_ric: The duration of real-time recording, in minutes.
*
*/
std::string GetSubProduct() const;
/**
* 设置Subproduct usage to be queried. The following parameters are supported:
- sp_tiw_board: The duration of use of whiteboards, in minutes.
- sp_tiw_ric: The duration of real-time recording, in minutes.
* @param _subProduct Subproduct usage to be queried. The following parameters are supported:
- sp_tiw_board: The duration of use of whiteboards, in minutes.
- sp_tiw_ric: The duration of real-time recording, in minutes.
*
*/
void SetSubProduct(const std::string& _subProduct);
/**
* 判断参数 SubProduct 是否已赋值
* @return SubProduct 是否已赋值
*
*/
bool SubProductHasBeenSet() const;
/**
* 获取Start date in the format of YYYY-MM-DD. The start date is included in the query period.
* @return StartTime Start date in the format of YYYY-MM-DD. The start date is included in the query period.
*
*/
std::string GetStartTime() const;
/**
* 设置Start date in the format of YYYY-MM-DD. The start date is included in the query period.
* @param _startTime Start date in the format of YYYY-MM-DD. The start date is included in the query period.
*
*/
void SetStartTime(const std::string& _startTime);
/**
* 判断参数 StartTime 是否已赋值
* @return StartTime 是否已赋值
*
*/
bool StartTimeHasBeenSet() const;
/**
* 获取End date in the format of YYYY-MM-DD. The end date is included in the query period. The period queried per request cannot be longer than 31 days.
* @return EndTime End date in the format of YYYY-MM-DD. The end date is included in the query period. The period queried per request cannot be longer than 31 days.
*
*/
std::string GetEndTime() const;
/**
* 设置End date in the format of YYYY-MM-DD. The end date is included in the query period. The period queried per request cannot be longer than 31 days.
* @param _endTime End date in the format of YYYY-MM-DD. The end date is included in the query period. The period queried per request cannot be longer than 31 days.
*
*/
void SetEndTime(const std::string& _endTime);
/**
* 判断参数 EndTime 是否已赋值
* @return EndTime 是否已赋值
*
*/
bool EndTimeHasBeenSet() const;
/**
* 获取Room IDs to be queried. If you leave this parameter empty, all room IDs are queried.
* @return RoomIDs Room IDs to be queried. If you leave this parameter empty, all room IDs are queried.
*
*/
std::vector<uint64_t> GetRoomIDs() const;
/**
* 设置Room IDs to be queried. If you leave this parameter empty, all room IDs are queried.
* @param _roomIDs Room IDs to be queried. If you leave this parameter empty, all room IDs are queried.
*
*/
void SetRoomIDs(const std::vector<uint64_t>& _roomIDs);
/**
* 判断参数 RoomIDs 是否已赋值
* @return RoomIDs 是否已赋值
*
*/
bool RoomIDsHasBeenSet() const;
/**
* 获取Offset for query. Default value: `0`.
* @return Offset Offset for query. Default value: `0`.
*
*/
uint64_t GetOffset() const;
/**
* 设置Offset for query. Default value: `0`.
* @param _offset Offset for query. Default value: `0`.
*
*/
void SetOffset(const uint64_t& _offset);
/**
* 判断参数 Offset 是否已赋值
* @return Offset 是否已赋值
*
*/
bool OffsetHasBeenSet() const;
/**
* 获取Maximum number of entries returned per query. Default value: `20`.
* @return Limit Maximum number of entries returned per query. Default value: `20`.
*
*/
uint64_t GetLimit() const;
/**
* 设置Maximum number of entries returned per query. Default value: `20`.
* @param _limit Maximum number of entries returned per query. Default value: `20`.
*
*/
void SetLimit(const uint64_t& _limit);
/**
* 判断参数 Limit 是否已赋值
* @return Limit 是否已赋值
*
*/
bool LimitHasBeenSet() const;
private:
/**
* SdkAppId of the whiteboard application.
*/
int64_t m_sdkAppId;
bool m_sdkAppIdHasBeenSet;
/**
* Subproduct usage to be queried. The following parameters are supported:
- sp_tiw_board: The duration of use of whiteboards, in minutes.
- sp_tiw_ric: The duration of real-time recording, in minutes.
*/
std::string m_subProduct;
bool m_subProductHasBeenSet;
/**
* Start date in the format of YYYY-MM-DD. The start date is included in the query period.
*/
std::string m_startTime;
bool m_startTimeHasBeenSet;
/**
* End date in the format of YYYY-MM-DD. The end date is included in the query period. The period queried per request cannot be longer than 31 days.
*/
std::string m_endTime;
bool m_endTimeHasBeenSet;
/**
* Room IDs to be queried. If you leave this parameter empty, all room IDs are queried.
*/
std::vector<uint64_t> m_roomIDs;
bool m_roomIDsHasBeenSet;
/**
* Offset for query. Default value: `0`.
*/
uint64_t m_offset;
bool m_offsetHasBeenSet;
/**
* Maximum number of entries returned per query. Default value: `20`.
*/
uint64_t m_limit;
bool m_limitHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_TIW_V20190919_MODEL_DESCRIBETIWROOMDAILYUSAGEREQUEST_H_
|
c8a1b8642da8d070caf08a2231d7a48b01412639 | ed313bf0460c93ad03ad34e86175250b3c0e6ab4 | /newshuoj/contest_84/I.cpp | d797a4de16f355999888a084a884e56690a7e163 | [] | no_license | ThereWillBeOneDaypyf/Summer_SolveSet | fd41059c5ddcbd33e2420277119613e991fb6da9 | 9895a9c035538c95a31f66ad4f85b6268b655331 | refs/heads/master | 2022-10-20T02:31:07.625252 | 2020-04-24T11:51:32 | 2020-04-24T11:51:32 | 94,217,614 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 670 | cpp | I.cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int T;
cin >> T;
while(T--)
{
int k,n;
cin >> k >> n;
set<pair<int,int> > incache;
int ans = 0;
for(int i = 0;i < n;i++)
{
int x;
cin >> x;
int isin = 0;
set<pair<int,int> > :: iterator it;
for(auto temp = incache.begin(); temp != incache.end();
temp ++)
if((*temp).second == x)
{
isin = 1;
it = temp;
break;
}
if(isin)
{
ans ++;
incache.erase(it);
incache.insert(make_pair(i,x));
continue;
}
if(k == incache.size())
incache.erase(incache.begin());
incache.insert(make_pair(i,x));
}
cout << ans << endl;
}
}
|
6141999973e38697623b8ccba049dbe33558be02 | 70255bed739886125d65264a1a5887f810694df4 | /include/radar/estimator_fsk.h | beea63fa5e36a8abfdf8674ede2174852a4fb8cb | [] | no_license | mbr0wn/gr-radar | 808bb0f50fb6c683a4f1a66516184d7defa05786 | 6b03ca63df16f063d199de2c0f696c5246b879ce | refs/heads/master | 2021-05-10T07:45:58.675552 | 2018-02-28T10:48:52 | 2018-02-28T10:48:52 | 118,856,125 | 4 | 0 | null | 2018-01-25T03:19:29 | 2018-01-25T03:19:29 | null | UTF-8 | C++ | false | false | 2,347 | h | estimator_fsk.h | /* -*- c++ -*- */
/*
* Copyright 2014 Communications Engineering Lab, KIT.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef INCLUDED_RADAR_ESTIMATOR_FSK_H
#define INCLUDED_RADAR_ESTIMATOR_FSK_H
#include <radar/api.h>
#include <gnuradio/block.h>
namespace gr {
namespace radar {
/*!
* \brief This block estimates the range with peaks given from a FSK spectrum. Needed identifiers (symbols) are 'frequency' and 'phase'. The velocity is calculated with the 'frequency' information and the doppler formula. The phase of the doppler peaks are used to estimate the range. Output identifier are 'range' and 'velocity'. If push_power is true the information about the power of the peaks is pushed through. This can be used for estimating the RCS of an object.
*
* \param center_freq Center frequency
* \param delta_freq Frequency difference of high and low frequency
* \param push_power Toggle pushing through information about power of peaks
*
* \ingroup radar
*
*/
class RADAR_API estimator_fsk : virtual public gr::block
{
public:
typedef boost::shared_ptr<estimator_fsk> sptr;
/*!
* \brief Return a shared_ptr to a new instance of radar::estimator_fsk.
*
* To avoid accidental use of raw pointers, radar::estimator_fsk's
* constructor is in a private implementation
* class. radar::estimator_fsk::make is the public interface for
* creating new instances.
*/
static sptr make(float center_freq, float delta_freq, bool push_power=false);
};
} // namespace radar
} // namespace gr
#endif /* INCLUDED_RADAR_ESTIMATOR_FSK_H */
|
24da6832ef9fd996b2adb68415448b1e975faf93 | 91e77ae31b4079d25d669e425a54c335a721d86a | /Array/1_largest_and_smallest_array.cpp | fb328dcc03bb195f9a10e3913affe33c6fe707cd | [] | no_license | KashifAhmad1789/KashifAhmad-dsa | cae60727463f8266e84a726be53a757c74f03e80 | 4c536959b204c4ecd377de3c43c2f597dd28ab6b | refs/heads/main | 2023-08-12T05:03:04.789563 | 2021-09-17T18:49:45 | 2021-09-17T18:49:45 | 402,451,950 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 722 | cpp | 1_largest_and_smallest_array.cpp | #include <iostream>
#include <climits>
using namespace std;
int main() {
int n,i;
int a[1000];
cin>>n;
int largest = INT_MIN;
int smallest = INT_MAX;
for(i=0;i<n;i++){
cin>>a[i];
}
// Smallest and lasrgest function of arrays;
// for(i=0;i<n;i++){
// if(a[i]>largest){
// largest=a[i];
// }
// if(a[i]<smallest){
// smallest=a[i];
// }
// }
// Inbuilt function of largest and smallest of array
for(i=0;i<n;i++){
largest=max(largest,a[i]);
smallest=min(smallest,a[i]);
}
cout<<"largest "<<largest<<endl;
cout<<"smallest "<<smallest<<endl;
return 0;
} |
c078cdfb3666d97fdb7e559706b024e638b2ac23 | b49b177bf5e0e318e643c0844ee72736bd0be961 | /libwiisys/source/logging/FileLogger.cpp | 8aadcb7b32b79ad35e6abee4a958ce7854ff1e78 | [] | no_license | CLEMENTINATOR/TeamWiigen | a8edf883318cbf087dfa2efbf9e887758abc51c1 | 011bc8023f4bcb2a1a9e682f14e2197fddfacc02 | refs/heads/master | 2020-06-19T10:32:58.356873 | 2013-06-18T17:28:00 | 2013-06-18T17:28:00 | 74,909,223 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,400 | cpp | FileLogger.cpp | #include <Libwiisys/logging/FileLogger.h>
#include <sstream>
using namespace std;
using namespace Libwiisys::IO;
using namespace Libwiisys::Logging;
FileLogger::FileLogger(const std::string& filePath) :
_filePath(filePath)
{
if (File::Exists(filePath))
File::Delete(filePath);
paused = true;
}
FileLogger::~FileLogger()
{
if (!paused)
{
_logFile->Close();
delete _logFile;
}
}
void FileLogger::Init(std::string appName, std::string appVersion)
{}
void FileLogger::Start()
{
if (!paused)
return;
if (!File::Exists(_filePath))
_logFile = &(File::Create(_filePath));
else
_logFile = &(File::Open(_filePath, FileMode_Write));
paused = false;
}
void FileLogger::Pause()
{
if (paused)
return;
_logFile->Close();
delete _logFile;
paused = true;
}
void FileLogger::Write(const std::string& line)
{
if (paused)
Start();
string endLine = "\n";
Buffer message(line.c_str(), line.length());
message.Append(endLine.c_str(), endLine.length());
_logFile->Write(message);
}
void FileLogger::WriteError(const std::string& message, int line,
const char* file, const string& appName, const string& appVersion)
{
stringstream formatedMessage;
formatedMessage << "Error " << " (" << file << " line : " << line << "): "
<< message;
Write(formatedMessage.str());
}
void FileLogger::WriteWarning(const std::string& message, int line,
const char* file, const string& appName, const string& appVersion)
{
stringstream formatedMessage;
formatedMessage << "Warning " << " (" << file << " line : " << line
<< "): " << message;
Write(formatedMessage.str());
}
void FileLogger::WriteInfo(const std::string& message, int line,
const char* file, const string& appName, const string& appVersion)
{
stringstream formatedMessage;
formatedMessage << "Info " << " (" << file << " line : " << line << "): "
<< message;
Write(formatedMessage.str());
}
void FileLogger::WriteDebug(const std::string& message, int line, const char* file, const string& appName, const string& appVersion)
{
stringstream formatedMessage;
formatedMessage << "Debug " << " (" << file << " line : " << line << "): "
<< message;
Write(formatedMessage.str());
}
std::string FileLogger::GetType()
{
return "Libwiisys::Logging::FileLogger,"+Object::GetType();
}
|
a56b0dc516db578965eb6c5c35028860d0b89bab | db666b5c6b5381c55c716f95818a7ecc241d59c7 | /C++/681-nextClosestTime.cpp | 2daab77cbd727ea84c46e4aa5c3f7f9b60b40f65 | [] | no_license | SaberDa/LeetCode | ed5ea145ff5baaf28ed104bb08046ff9d5275129 | 7dc681a2124fb9e2190d0ab37bf0965736bb52db | refs/heads/master | 2023-06-25T09:16:14.521110 | 2021-07-26T21:58:33 | 2021-07-26T21:58:33 | 234,479,225 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,143 | cpp | 681-nextClosestTime.cpp | #include <string>
#include <unordered_set>
using namespace std;
int distance(string cur, string next) {
int a = stoi(cur.substr(0, 2)) * 60 + stoi(cur.substr(2));
int b = stoi(next.substr(0, 2)) * 60 + stoi(next.substr(2));
return a < b ? b - a : b - a + 24 * 60;
}
void DFS(unordered_set<char> &set, string &cur, int pos, int &minDis, string &res, string &next) {
if (pos == 2 && stoi(next.substr(0, 2)) >= 24) return;
if (pos == 4) {
if (stoi(next.substr(2)) >= 60) return;
int dis = distance(cur, next);
if (dis < minDis) {
minDis = dis;
res = next;
}
return;
}
for (auto c : set) {
next.push_back(c);
DFS(set, cur, pos + 1, minDis, res, next);
next.pop_back();
}
}
string nextClosestTime(string time) {
string cur = time.substr(0, 2) + time.substr(3);
unordered_set<char> set;
for (auto c : cur) set.insert(c);
if (set.size() == 1) return time;
int minDis = 24 * 60;
string res = "", next = "";
DFS(set, cur, 0, minDis, res, next);
res.insert(res.begin() + 2, ':');
return res;
} |
7324c24c52e9a59d208f4c72925cc4bc013c3b66 | 21b5b3116ba4bc1ade58cb80d63e3beb25127590 | /gearoenix/glc3/shader/glc3-shd-forward-pbr.cpp | 036156aeb24443e9e88d6d41ca778cf0c231a16e | [] | no_license | bmjoy/gearoenix | 54ac24d088627af16208e7e98f6d3c317b9b5ca0 | 0b6c0c3c19899d99272a2b5168197c7880fa0fc3 | refs/heads/master | 2022-04-17T15:31:42.942367 | 2020-04-21T02:19:08 | 2020-04-21T02:19:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,263 | cpp | glc3-shd-forward-pbr.cpp | #include "glc3-shd-forward-pbr.hpp"
#ifdef GX_USE_OPENGL_CLASS_3
#include "../../core/cr-function-loader.hpp"
#include "../../gl/gl-loader.hpp"
#include "../../system/sys-app.hpp"
#include "../engine/glc3-eng-engine.hpp"
#include <sstream>
#define GX_GLC3_SHADER_SRC_EFFECT_UNIFORMS \
"uniform vec4 effect_point_lights_color_min_radius[" GX_MAX_POINT_LIGHTS_STR "];\n" \
"uniform vec4 effect_point_lights_position_max_radius[" GX_MAX_POINT_LIGHTS_STR "];\n" \
"uniform mat4 effect_shadow_caster_directional_lights_cascades_view_projection_bias[" GX_MAX_DIRECTIONAL_LIGHTS_CASCADES_STR "];\n" \
"uniform vec4 effect_shadow_caster_directional_lights_color_cascades_count[" GX_MAX_DIRECTIONAL_LIGHTS_SHADOW_CASTER_STR "];\n" \
"uniform vec4 effect_shadow_caster_directional_lights_direction[" GX_MAX_DIRECTIONAL_LIGHTS_SHADOW_CASTER_STR "];\n" \
"uniform float effect_point_lights_count;\n" \
"uniform float effect_shadow_caster_directional_lights_count;\n"
gearoenix::glc3::shader::ForwardPbr::ForwardPbr(engine::Engine* const e, const core::sync::EndCaller<core::sync::EndCallerIgnore>& c) noexcept
: Shader(e, c)
{
GX_GLC3_SHADER_SRC_DEFAULT_VERTEX_STARTING <<
// camera uniform(s)
"uniform mat4 camera_vp;\n" GX_GLC3_SHADER_SRC_EFFECT_UNIFORMS
// model uniform(s)
"uniform mat4 model_m;\n"
// output(s)
"out vec3 out_pos;\n"
"out vec3 out_nrm;\n"
"out vec3 out_tng;\n"
"out vec3 out_btg;\n"
"out vec2 out_uv;\n"
// One thing that I'm not sure about is its interpolating, it may not acceptably result
"out vec3 out_directional_lights_cascades_pojected[" GX_MAX_DIRECTIONAL_LIGHTS_CASCADES_STR "];\n"
// Main function
"void main()\n"
"{\n"
" vec4 pos = model_m * vec4(position, 1.0);\n"
" out_pos = pos.xyz;\n"
" out_nrm = normalize((model_m * vec4(normal, 0.0)).xyz);\n"
" out_tng = normalize((model_m * vec4(tangent.xyz, 0.0)).xyz);\n"
" out_btg = normalize(cross(out_nrm, out_tng) * tangent.w);\n"
" out_uv = uv;\n"
// Computing cascaded shadows
" int effect_shadow_caster_directional_lights_count_int = int(effect_shadow_caster_directional_lights_count);\n"
" for(int diri = 0, i = 0; diri < effect_shadow_caster_directional_lights_count_int; ++diri)\n"
" {\n"
" int effect_shadow_caster_directional_lights_cascades_count_int = int(effect_shadow_caster_directional_lights_color_cascades_count[diri].w);\n"
" int diff_ccc_cc = " GX_MAX_SHADOW_CASCADES_STR " - effect_shadow_caster_directional_lights_cascades_count_int;\n"
" for(int j = 0; j < effect_shadow_caster_directional_lights_cascades_count_int; ++j, ++i)\n"
" {\n"
" vec4 light_pos = effect_shadow_caster_directional_lights_cascades_view_projection_bias[i] * pos;\n"
" light_pos.xyz /= light_pos.w;\n"
" light_pos.z *= 0.5;\n"
" light_pos.z += 0.5;\n"
" out_directional_lights_cascades_pojected[i] = light_pos.xyz;\n"
" }\n"
" i += diff_ccc_cc;\n"
" }\n"
" gl_Position = camera_vp * pos;\n"
"}";
GX_GLC3_SHADER_SRC_DEFAULT_FRAGMENT_STARTING <<
// Material uniforms
"uniform float material_alpha;\n"
"uniform float material_alpha_cutoff;\n"
"uniform float material_metallic_factor;\n"
"uniform float material_normal_scale;\n"
"uniform float material_occlusion_strength;\n"
"uniform float material_roughness_factor;\n"
"uniform float material_radiance_lod_coefficient;\n"
"uniform sampler2D material_base_color;\n"
"uniform sampler2D material_metallic_roughness;\n"
"uniform sampler2D material_normal;\n"
"uniform sampler2D material_emissive;\n"
// scenes uniform(s)
"uniform vec3 scene_ambient_light;\n"
"uniform vec4 scene_directional_lights_color[" GX_MAX_DIRECTIONAL_LIGHTS_STR "];\n"
"uniform vec4 scene_directional_lights_direction[" GX_MAX_DIRECTIONAL_LIGHTS_STR "];\n"
"uniform float scene_directional_lights_count;\n"
// samples-count, radius, z-tolerance
"uniform float scene_ssao_samples_count;\n"
"uniform float scene_ssao_radius;\n"
"uniform float scene_ssao_z_tolerance;\n"
// effect uniforms
"uniform samplerCube effect_diffuse_environment;\n"
"uniform samplerCube effect_specular_environment;\n"
"uniform sampler2D effect_ambient_occlusion;\n"
"uniform sampler2D effect_shadow_caster_directional_lights_cascades_shadow_map[" GX_MAX_DIRECTIONAL_LIGHTS_CASCADES_STR "];\n"
"uniform sampler2D effect_brdflut;\n" GX_GLC3_SHADER_SRC_EFFECT_UNIFORMS
// camera uniform(s)
"uniform vec3 camera_position;\n"
"uniform float camera_hdr_tune_mapping;\n"
"uniform float camera_gamma_correction;\n"
// output(s) of vertex shader
"in vec3 out_pos;\n"
"in vec3 out_nrm;\n"
"in vec3 out_tng;\n"
"in vec3 out_btg;\n"
"in vec2 out_uv;\n"
"in vec3 out_directional_lights_cascades_pojected[" GX_MAX_DIRECTIONAL_LIGHTS_CASCADES_STR "];\n"
"out vec4 frag_color;\n"
// Normal Distribution Function Trowbridge-Reitz GGX
"float distribution_ggx(const vec3 normal, const vec3 halfway, const float roughness) {\n"
" float roughness2 = roughness * roughness;\n"
" float nh = max(dot(normal, halfway), 0.0);\n"
" float nh2 = nh * nh;\n"
" float nom = roughness2;\n"
" float tmpdenom = nh2 * (roughness2 - 1.0) + 1.0;\n"
" float denom = GX_PI * tmpdenom * tmpdenom;\n"
" return nom / denom;\n"
"}\n"
"float geometry_schlick_ggx(const float nd, const float roughness, const float k, const float k_inv) {\n"
" float nom = nd;\n"
" float denom = nd * k_inv + k;\n"
" return nom / denom;\n"
"}\n"
"float geometry_smith(const float normal_dot_light, const float normal_dot_view, const float roughness) {\n"
" float k = roughness + 1.0;\n"
" k = (k * k) * (1.0 / 8.0);\n"
" float k_inv = 1.0 - k;\n"
" float ggx2 = geometry_schlick_ggx(normal_dot_view, roughness, k, k_inv);\n"
" float ggx1 = geometry_schlick_ggx(normal_dot_light, roughness, k, k_inv);\n"
" return ggx1 * ggx2;\n"
"}\n"
"vec3 fresnel_schlick(const float nv, const vec3 f0) {\n"
" float inv = 1.0 - nv;\n"
" float inv2 = inv * inv;\n"
" float inv4 = inv2 * inv2;\n"
" float inv5 = inv4 * inv;\n"
" return f0 + ((1.0 - f0) * inv5);\n"
"}\n"
// cos_theta is (n dot v)
"vec3 fresnel_schlick_roughness(const float nv, const vec3 f0, const float roughness)\n"
"{\n"
" float inv = 1.0 - nv;\n"
" float inv2 = inv * inv;\n"
" float inv4 = inv2 * inv2;\n"
" float inv5 = inv4 * inv;\n"
" return f0 + ((max(vec3(1.0 - roughness), f0) - f0) * inv5);\n"
"}\n"
"void main()\n"
"{\n"
// material properties
" vec4 tmpv4 = texture(material_base_color, out_uv);\n"
" tmpv4.w *= material_alpha;\n"
" vec4 albedo = tmpv4;\n"
" if(albedo.w < material_alpha_cutoff) discard;\n"
" tmpv4.xy = texture(material_metallic_roughness, out_uv).xy;\n"
" tmpv4.xy *= vec2(material_metallic_factor, material_roughness_factor);\n"
" float metallic = tmpv4.x;\n"
" float roughness = tmpv4.y;\n"
// TODO: in future maybe I will add ao in here
// input lighting data
" vec3 normal = normalize(mat3(out_tng, out_btg, out_nrm) * ((texture(material_normal, out_uv).xyz - 0.5) * 2.0 * material_normal_scale));\n"
" vec3 view = normalize(camera_position - out_pos);\n"
" vec3 reflection = normalize(reflect(-view, normal));\n"
" float normal_dot_view = max(dot(normal, view), 0.0);\n"
// calculate reflectance at normal incidence; if dia-electric (like plastic) use F0
// of 0.04 and if it's a metal, use the albedo color as F0 (metallic workflow)
// TODO: in future I must bring builder fresnel factor 0 (the hard coded 0.4) from matrial uniform data
" vec3 f0 = mix(vec3(0.04), albedo.xyz, metallic);\n"
// reflectance equation
" vec3 lo = vec3(0.0);\n"
// computing point lights
" int effect_point_lights_count_int = int(effect_point_lights_count);\n"
" for (int i = 0; i < effect_point_lights_count_int; ++i)\n"
" {\n"
// calculate per-light radiance
" vec3 light_vec = effect_point_lights_position_max_radius[i].xyz - out_pos;\n"
// TODO: in future consider max and min radius
" float distance = length(light_vec);\n"
" float distance_inv = 1.0 / distance;\n"
" vec3 light_direction = light_vec * distance_inv;\n"
" float normal_dot_light = max(dot(normal, light_direction), 0.0);\n"
" vec3 half_vec = normalize(view + light_direction);\n"
" float attenuation = distance_inv * distance_inv;\n"
" vec3 radiance = effect_point_lights_color_min_radius[i].xyz * attenuation;\n"
// Cook-Torrance BRDF
" float ndf = distribution_ggx(normal, half_vec, roughness);\n"
" float geo = geometry_smith(normal_dot_light, normal_dot_view, roughness);\n"
" vec3 frsn = fresnel_schlick(max(dot(half_vec, view), 0.0), f0);\n"
" vec3 nominator = ndf * geo * frsn;\n"
// 0.001 to prevent divide by zero.
" float denominator = 4.0 * normal_dot_view * normal_dot_light + 0.001;\n"
" vec3 specular = nominator / denominator;\n"
// kS is equal to Fresnel
" vec3 ks = frsn;\n"
// for energy conservation, the diffuse and specular light can't
// be above 1.0 (unless the surface emits light); to preserve this
// relationship the diffuse component (kD) should equal 1.0 - kS.
// multiply kD by the inverse metalness such that only non-metals
// have diffuse lighting, or a linear blend if partly metal (pure metals
// have no diffuse light).
" vec3 kd = (vec3(1.0) - ks) * (1.0 - metallic);\n"
// scale light by NdotL
// add to outgoing radiance Lo
// note that we already multiplied the BRDF by the Fresnel (kS) so we won't multiply by kS again
" lo += (kd * albedo.xyz / GX_PI + specular) * radiance * normal_dot_light;\n"
" }\n"
// computing directional lights
" for (float i = 0.001; i < scene_directional_lights_count; ++i)\n"
" {\n"
" int ii = int(i);\n"
" vec3 light_direction = -scene_directional_lights_direction[ii].xyz;\n"
" float normal_dot_light = max(dot(normal, light_direction), 0.0);\n"
" vec3 half_vec = normalize(view + light_direction);\n"
" vec3 radiance = scene_directional_lights_color[ii].xyz;\n"
// Cook-Torrance BRDF
" float ndf = distribution_ggx(normal, half_vec, roughness);\n"
" float geo = geometry_smith(normal_dot_light, normal_dot_view, roughness);\n"
" vec3 frsn = fresnel_schlick(max(dot(half_vec, view), 0.0), f0);\n"
" vec3 nominator = ndf * geo * frsn;\n"
// 0.001 to prevent divide by zero.
" float denominator = 4.0 * normal_dot_view * normal_dot_light + 0.001;\n"
" vec3 specular = nominator / denominator;\n"
// kS is equal to Fresnel
" vec3 ks = frsn;\n"
// for energy conservation, the irradiance and radiance light can't
// be above 1.0 (unless the surface emits light); to preserve this
// relationship the irradiance component (kD) should equal 1.0 - kS.
// multiply kD by the inverse metalness such that only non-metals
// have irradiance lighting, or a linear blend if partly metal (pure metals
// have no irradiance light).
" vec3 kd = (vec3(1.0) - ks) * (1.0 - metallic);\n"
// scale light by NdotL
// add to outgoing radiance Lo
// note that we already multiplied the BRDF by the Fresnel (kS) so we won't multiply by kS again
" lo += (kd * albedo.xyz / GX_PI + specular) * radiance * normal_dot_light;\n"
" }\n"
" int effect_shadow_caster_directional_lights_count_int = int(effect_shadow_caster_directional_lights_count);\n"
" for(int diri = 0, lcasi = 0; diri < effect_shadow_caster_directional_lights_count_int; ++diri, lcasi = diri * " GX_MAX_SHADOW_CASCADES_STR ")\n"
" {\n"
" bool is_in_directional_light = true;\n"
" float normal_dot_light = max(dot(out_nrm, -effect_shadow_caster_directional_lights_direction[diri].xyz), 0.0);\n"
" float shadow_bias = 0.001;\n"
" if(normal_dot_light > 0.0)\n"
" {\n"
" shadow_bias = clamp(sqrt((0.000025 / (normal_dot_light * normal_dot_light)) - 0.000025), 0.001, 0.02);\n"
" }\n"
" else\n"
" {\n"
" is_in_directional_light = false;"
" }\n"
" if(is_in_directional_light)\n"
" {\n"
" int effect_shadow_caster_directional_lights_cascades_count_int = int(effect_shadow_caster_directional_lights_color_cascades_count[diri].w);\n"
" for(int i = 0; i < effect_shadow_caster_directional_lights_cascades_count_int; ++i)\n"
" {\n"
" vec3 lightuv = out_directional_lights_cascades_pojected[lcasi];\n"
" if (lightuv.x > 0.0 && lightuv.x < 1.0 && lightuv.y > 0.0 && lightuv.y < 1.0)\n"
" {\n"
#if GX_MAX_DIRECTIONAL_LIGHTS_CASCADES == 1
#define SHADOW_MAP_INDEX "0"
#else
#define SHADOW_MAP_INDEX "lcasi"
#endif
" float depth = texture(effect_shadow_caster_directional_lights_cascades_shadow_map[" SHADOW_MAP_INDEX "], lightuv.xy, 0.0).x;\n"
" if(depth + shadow_bias <= lightuv.z)\n"
" {\n"
" is_in_directional_light = false;\n"
" }\n"
" break;\n"
" }\n"
" }\n"
" }\n"
" if(is_in_directional_light)\n"
" {\n"
" vec3 half_vec = normalize(view - effect_shadow_caster_directional_lights_direction[diri].xyz);\n"
" vec3 radiance = effect_shadow_caster_directional_lights_color_cascades_count[diri].xyz;\n"
// Cook-Torrance BRDF
" float ndf = distribution_ggx(normal, half_vec, roughness);\n"
" float geo = geometry_smith(normal_dot_light, normal_dot_view, roughness);\n"
" vec3 frsn = fresnel_schlick(max(dot(half_vec, view), 0.0), f0);\n"
" vec3 nominator = ndf * geo * frsn;\n"
// 0.001 to prevent divide by zero.
" float denominator = 4.0 * normal_dot_view * normal_dot_light + 0.001;\n"
" vec3 specular = nominator / denominator;\n"
// kS is equal to Fresnel
" vec3 ks = frsn;\n"
// for energy conservation, the irradiance and radiance light can't
// be above 1.0 (unless the surface emits light); to preserve this
// relationship the irradiance component (kD) should equal 1.0 - kS.
// multiply kD by the inverse metalness such that only non-metals
// have irradiance lighting, or a linear blend if partly metal (pure metals
// have no irradiance light).
" vec3 kd = (vec3(1.0) - ks) * (1.0 - metallic);\n"
// scale light by NdotL
// add to outgoing radiance Lo
// note that we already multiplied the BRDF by the Fresnel (kS) so we won't multiply by kS again
" lo += (kd * albedo.xyz / GX_PI + specular) * radiance * normal_dot_light;\n"
" }\n"
" }\n"
// ambient lighting (we now use IBL as the ambient term)
" vec3 frsn = fresnel_schlick_roughness(normal_dot_view, f0, roughness);\n"
" vec3 ks = frsn;\n"
" vec3 kd = (1.0 - ks) * (1.0 - metallic);\n"
" vec3 irradiance = texture(effect_diffuse_environment, normal).rgb;\n"
" vec3 diffuse = irradiance * albedo.xyz;\n"
// sample both the pre-filter map and the BRDF lut and combine them together as per
// the Split-Sum approximation to get the IBL radiance part.
" vec3 prefiltered_color = textureLod(effect_specular_environment, reflection, roughness * material_radiance_lod_coefficient).rgb;\n"
" vec2 brdf = texture(effect_brdflut, vec2(normal_dot_view, roughness)).rg;\n"
" vec3 specular = prefiltered_color * ((frsn * brdf.x) + brdf.y);\n"
// TODO: add ambient occlusion (* ao);
" vec3 ambient = kd * diffuse + specular + scene_ambient_light * albedo.xyz;\n"
" tmpv4.xyz = ambient + lo;\n"
" if(camera_gamma_correction > 0.001) {\n"
// HDR tone mapping
" tmpv4.xyz = tmpv4.xyz / (tmpv4.xyz + vec3(camera_hdr_tune_mapping));\n"
// gamma correct
" tmpv4.xyz = pow(tmpv4.xyz, vec3(1.0 / camera_gamma_correction));\n"
"}\n"
//" frag_color = vec4((tmpv4.xyz * 0.001) + textureLod(effect_diffuse_environment, normalize(out_pos), 0.0).xyz, albedo.w);\n"
" frag_color = vec4(tmpv4.xyz, albedo.w);\n"
"}";
e->get_function_loader()->load([this, vertex_shader_code { vertex_shader_code.str() }, fragment_shader_code { fragment_shader_code.str() }] {
set_vertex_shader(vertex_shader_code);
set_fragment_shader(fragment_shader_code);
link();
GX_GLC3_SHADER_SET_TEXTURE_INDEX_STARTING
GX_GLC3_THIS_GET_UNIFORM(material_alpha)
GX_GLC3_THIS_GET_UNIFORM(material_alpha_cutoff)
GX_GLC3_THIS_GET_UNIFORM_TEXTURE(material_base_color)
// GX_GLC3_THIS_GET_UNIFORM_TEXTURE(material_emissive)
GX_GLC3_THIS_GET_UNIFORM(material_metallic_factor)
GX_GLC3_THIS_GET_UNIFORM_TEXTURE(material_metallic_roughness)
GX_GLC3_THIS_GET_UNIFORM_TEXTURE(material_normal)
GX_GLC3_THIS_GET_UNIFORM(material_normal_scale)
GX_GLC3_THIS_GET_UNIFORM(material_radiance_lod_coefficient)
// GX_GLC3_THIS_GET_UNIFORM(material_occlusion_strength)
GX_GLC3_THIS_GET_UNIFORM(material_roughness_factor)
GX_GLC3_THIS_GET_UNIFORM(camera_position)
GX_GLC3_THIS_GET_UNIFORM(camera_vp)
GX_GLC3_THIS_GET_UNIFORM(camera_hdr_tune_mapping)
GX_GLC3_THIS_GET_UNIFORM(camera_gamma_correction)
// TODO
//GX_GLC3_THIS_GET_UNIFORM(effect_ambient_occlusion)
GX_GLC3_THIS_GET_UNIFORM_TEXTURE(effect_brdflut)
GX_GLC3_THIS_GET_UNIFORM_TEXTURE(effect_diffuse_environment)
GX_GLC3_THIS_GET_UNIFORM(effect_point_lights_color_min_radius)
GX_GLC3_THIS_GET_UNIFORM(effect_point_lights_position_max_radius)
GX_GLC3_THIS_GET_UNIFORM_TEXTURE_ARRAY(effect_shadow_caster_directional_lights_cascades_shadow_map)
GX_GLC3_THIS_GET_UNIFORM(effect_shadow_caster_directional_lights_cascades_view_projection_bias)
GX_GLC3_THIS_GET_UNIFORM(effect_shadow_caster_directional_lights_color_cascades_count)
GX_GLC3_THIS_GET_UNIFORM(effect_shadow_caster_directional_lights_direction)
GX_GLC3_THIS_GET_UNIFORM(effect_shadow_caster_directional_lights_count)
GX_GLC3_THIS_GET_UNIFORM_TEXTURE(effect_specular_environment)
GX_GLC3_THIS_GET_UNIFORM(model_m)
GX_GLC3_THIS_GET_UNIFORM(scene_ambient_light)
GX_GLC3_THIS_GET_UNIFORM(scene_directional_lights_color)
GX_GLC3_THIS_GET_UNIFORM(scene_directional_lights_direction)
GX_GLC3_THIS_GET_UNIFORM(scene_directional_lights_count)
// GX_GLC3_THIS_GET_UNIFORM(scene_ssao_radius)
// GX_GLC3_THIS_GET_UNIFORM(scene_ssao_samples_count)
// GX_GLC3_THIS_GET_UNIFORM(scene_ssao_z_tolerance)
});
}
gearoenix::glc3::shader::ForwardPbr::~ForwardPbr() noexcept = default;
void gearoenix::glc3::shader::ForwardPbr::bind() const noexcept
{
Shader::bind();
GX_GLC3_SHADER_SET_TEXTURE_INDEX_UNIFORM(material_base_color)
GX_GLC3_SHADER_SET_TEXTURE_INDEX_UNIFORM(material_emissive)
GX_GLC3_SHADER_SET_TEXTURE_INDEX_UNIFORM(material_metallic_roughness)
GX_GLC3_SHADER_SET_TEXTURE_INDEX_UNIFORM(material_normal)
GX_GLC3_SHADER_SET_TEXTURE_INDEX_UNIFORM(effect_ambient_occlusion)
GX_GLC3_SHADER_SET_TEXTURE_INDEX_UNIFORM(effect_brdflut)
GX_GLC3_SHADER_SET_TEXTURE_INDEX_UNIFORM(effect_diffuse_environment)
GX_GLC3_SHADER_SET_TEXTURE_INDEX_ARRAY_UNIFORM(effect_shadow_caster_directional_lights_cascades_shadow_map)
GX_GLC3_SHADER_SET_TEXTURE_INDEX_UNIFORM(effect_specular_environment)
}
#endif
|
e812d54a39c165b3f2e89564199021a324ea4e07 | 9faf70be5b39535134280fdf432868048847fc7a | /URI 1256 - Tabelas Hash.cpp | ef4efa0383a454c914be7d3ef02b65661f42a70b | [] | no_license | luigim1998/Questoes_URI_Luigi_Muller | 6967b53f290993be2fb13267b26d78acee90df21 | e0f89ece36ccca444ad4b1dd8f123a7e63f11352 | refs/heads/master | 2021-08-22T13:11:31.664959 | 2020-04-03T18:56:13 | 2020-04-03T18:56:13 | 155,127,273 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,201 | cpp | URI 1256 - Tabelas Hash.cpp | #include <iostream>
#include <queue>
using namespace std;
int main(){
int casos; // número de casos de teste
int endereco; // número de endereços-base que ele terá em cada caso
int quantidade; // quantidade de valores a ser inseridos no caso
int aux;
cin >> casos;
while(casos > 0){
cin >> endereco;
cin >> quantidade;
// crio um vetor de filas para os inteiros que entrarão na tabela
queue<int> tabela[endereco];
// insere os valores na tabela no índice x mod endereco
for(int cont = 0; cont < quantidade; cont++){
cin >> aux;
tabela[aux%endereco].push(aux);
}
// imprime cada linha da tabela
for(int cont = 0; cont < endereco; cont++){
cout << cont << " -> ";
while(!tabela[cont].empty()){
cout << tabela[cont].front() << " -> ";
tabela[cont].pop();
}
cout << "\\" << endl;
}
casos--;
//se não for zero então separa com uma nova linha o caso
if(casos != 0){
cout << endl;
}
}
return 0;
} |
a720d8a1a5909636690c8018dabc1cb40dde8108 | 1948ad2f78654b52c2addbab0a83ca3051a8da43 | /buttons.ino | cd521611a4c5854b37e5221a07d6316f70dd8d39 | [
"MIT"
] | permissive | dJPoida/dJPsController | 0628bc362dc1ac220294110181e1142f91f1be10 | 175e26a507e6b5f604aad3a77385886e09e53a23 | refs/heads/master | 2020-08-31T17:00:24.379269 | 2019-10-31T10:27:42 | 2019-10-31T10:27:42 | 218,738,666 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,168 | ino | buttons.ino | /**
* Update the Button A
*/
bool updateButtonA() {
// Read the new values
bool newBtnA = !digitalRead(PIN_BTN_A);
// Any changes?
if (newBtnA != btnA){
btnA = newBtnA;
return true;
}
return false;
}
/**
* Update the Button B
*/
bool updateButtonB() {
// Read the new values
bool newBtnB = !digitalRead(PIN_BTN_B);
// Any changes?
if (newBtnB != btnB){
btnB = newBtnB;
return true;
}
return false;
}
/**
* Update the Button C
*/
bool updateButtonC() {
// Read the new values
bool newBtnC = !digitalRead(PIN_BTN_C);
// Any changes?
if (newBtnC != btnC){
btnC = newBtnC;
return true;
}
return false;
}
/**
* Update the Select Button
*/
bool updateButtonSelect() {
// Read the new values
bool newBtnSelect = !digitalRead(PIN_BTN_SELECT);
// Any changes?
if (newBtnSelect != btnSelect){
btnSelect = newBtnSelect;
return true;
}
return false;
}
/**
* Update the toggle button value
*/
bool updateButtonToggle() {
bool newBtnToggle = !digitalRead(PIN_TOGGLE);
if (newBtnToggle != btnToggle) {
btnToggle = newBtnToggle;
return true;
}
return false;
}
|
de978254252c782845c5c881b8e35de85d29f1d4 | d48b00b905ed9fb27949285737601f0b3d04c857 | /2018/09/01/南京网络赛/L.cpp | 4ccaa99345e3ede56ba9ee9035b0005f9fc30e64 | [] | no_license | Smlight/Programming-Contest | 1162bbd5476cc687c1afe3d2fd92e4832cf4b979 | ee90ad89804ae10c9cd4b31171adb467f2493b33 | refs/heads/master | 2021-06-01T10:42:08.730261 | 2020-12-09T07:36:35 | 2020-12-09T07:36:35 | 56,766,943 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,641 | cpp | L.cpp | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N=100010;
const int inf=0x3f3f3f3f;
struct Edge {
int to,next,val;
} eg[N<<1];
int last[N],tot=0;
int T,n,m,k;
struct Node {
ll len;
int x,y;
bool operator <(const Node &r) const {
return len<r.len;
}
bool operator >(const Node &r) const {
return r<*this;
}
};
ll dp[N][12];
bool vis[N][12];
void addedge(int x,int y,int z)
{
eg[tot]={y,last[x],z};
last[x]=tot++;
}
void dij(int S)
{
priority_queue< Node,vector<Node>,greater<Node> > q;
memset(dp,inf,sizeof(dp));
memset(vis,0,sizeof(vis));
dp[S][0]=0;
// vis[S][0]=true;
q.push({dp[S][0],S,0});
while (!q.empty()){
Node cur=q.top();
q.pop();
int u=cur.x,y=cur.y;
if (y>k) continue;
vis[u][y]=true;
for (int i=last[u];i!=-1;i=eg[i].next) {
int v=eg[i].to;
if (!vis[v][y]) {
if (cur.len+eg[i].val<dp[v][y]) {
dp[v][y]=cur.len+eg[i].val;
q.push({dp[v][y],v,y});
}
}
if (!vis[v][y+1]) {
if (cur.len<dp[v][y+1]) {
dp[v][y+1]=cur.len;
q.push({dp[v][y+1],v,y+1});
}
}
}
}
}
int main()
{
scanf("%d",&T);
while (T--) {
scanf("%d%d%d",&n,&m,&k);
tot=0;
memset(last,-1,sizeof(last));
for (int i=1;i<=m;i++) {
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
addedge(a,b,c);
}
dij(1);
printf("%lld\n",*min_element(dp[n],dp[n]+k+1));
}
return 0;
}
|
fa39281700e3864ee5cad4ae06f183c36880e3dc | 01dee3bf83b1ab356a0109cc70b3536c57b065a1 | /codeforces/553/E.cpp | cd31dec4a6eb7a3aa72e8897f708db54fa979000 | [] | no_license | YMDragon/OJ-code | 3e5c9c9871e86fffdd5a24e9da247b9980f364f4 | 6569bfa6519021cc3303aa42a4e60a40149a7816 | refs/heads/master | 2021-01-23T06:01:36.991005 | 2017-05-02T01:21:09 | 2017-05-02T01:21:09 | 86,330,585 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,758 | cpp | E.cpp | #include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <complex>
#include <cstdio>
#include <cmath>
using namespace std;
const double pi=acos(-1);
struct comp{double a,b;}A[1<<15],B[1<<15],C[1<<15];
struct edge{int s,t,d,n;double p[20002],S[20002];}e[105];
int n,m,x,t,dis[55];
double f[55][20002],g[105][20002];
comp operator + (comp x,comp y){return (comp){x.a+y.a,x.b+y.b};}
comp operator - (comp x,comp y){return (comp){x.a-y.a,x.b-y.b};}
comp operator * (comp x,comp y){return (comp){x.a*y.a-x.b*y.b,x.a*y.b+x.b*y.a};}
comp operator / (comp x,double y){return (comp){x.a/y,x.b/y};}
int gi()
{
int w=0; char ch=getchar();
while ((ch<'0')||('9'<ch)) ch=getchar();
while (('0'<=ch)&&(ch<='9')) w=w*10+ch-'0',ch=getchar();
return w;
}
void FFT(comp *a,int n,int op)
{
for (int i=0,j,t,p; i<n; i++)
{
t=i,p=0;
for (j=1; j<n; j<<=1) p<<=1,p|=(t&1),t>>=1;
if (p<i) swap(a[i],a[p]);
}
for (int len=2; len<=n; len<<=1)
{
comp w=(comp){cos(2*pi*op/len),sin(2*pi*op/len)};
for (int i=0; i<n; i+=len)
{
comp W=(comp){1,0};
for (int j=0; j<(len>>1); j++)
{
comp u=a[i+j],v=a[i+j+(len>>1)];
a[i+j]=u+W*v,a[i+j+(len>>1)]=u-W*v,W=W*w;
}
}
}
if (op==-1) for (int i=0; i<n; i++) a[i]=a[i]/n;
}
void trans(int id,int l,int r)
{
int mid=(l+r)>>1,N=1;
while (N<=r-mid-1+r-l) N<<=1;
for (int i=mid+1; i<=r; i++) A[i-mid-1]=(comp){f[e[id].t][i],0};
for (int i=1; i<=r-l; i++) B[r-l-i]=(comp){e[id].p[i],0};
FFT(A,N,1),FFT(B,N,1);
for (int i=0; i<N; i++) C[i]=A[i]*B[i];
FFT(C,N,-1);
for (int i=l; i<=mid; i++) g[id][i]+=C[r-mid-l-1+i].a;
for (int i=0; i<N; i++) A[i]=B[i]=(comp){0,0};
}
void solve(int l,int r)
{
if (l==r)
{
for (int i=1; i<=m; i++)
f[e[i].s][l]=min(f[e[i].s][l],g[i][l]+e[i].d);
return;
}
int mid=(l+r)>>1;
solve(mid+1,r);
for (int i=1; i<=m; i++) trans(i,l,r);
solve(l,mid);
}
void work()
{
n=gi(),m=gi(),t=gi(),x=gi();
for (int i=1; i<=m; i++)
{
e[i].s=gi(),e[i].t=gi(),e[i].d=gi();
for (int j=1; j<=t; j++) e[i].p[j]=gi()/1e5;
for (int j=t; j; j--) e[i].S[j]=e[i].S[j+1]+e[i].p[j];
}
for (int i=1; i<n; i++)
for (int j=0; j<=t; j++)
f[i][j]=1e20;
for (int i=1; i<n; i++) dis[i]=1<<30;
for (int i=1; i<=n; i++)
for (int j=1; j<=m; j++)
dis[e[j].s]=min(dis[e[j].s],dis[e[j].t]+e[j].d);
for (int i=1; i<=n; i++) f[i][t+1]=dis[i]+x;
for (int i=1; i<=m; i++)
for (int j=0; j<=t; j++)
g[i][j]=e[i].S[t-j+1]*f[e[i].t][t+1];
solve(0,t);
printf("%lf",f[1][0]);
}
int main()
{
freopen("E.in","r",stdin);
freopen("E.out","w",stdout);
work();
return 0;
}
|
f9ae7d3aa620e5f2a805ddd476494cfbfe8533c0 | 17953c4ff376936161fc89eb41d605b66699a38c | /src/ServerEngine/test/RouterServerTest/TestGS/TestGameImp.cpp | 26cdb50b61a9039f9ca057affa96077f9b891a41 | [] | no_license | equalizer-bourne/otherserver | 8353fc495e71bb549b23759c58d1595e590be902 | e6865f90ef8c008601a7e2c6657d102ae4820c40 | refs/heads/master | 2020-05-15T16:20:38.684392 | 2018-09-18T18:49:56 | 2018-09-18T18:49:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,441 | cpp | TestGameImp.cpp | #include "TestGameImp.h"
#include "Push.h"
#include "RouterServer.pb.h"
TestGameImp::TestGameImp()
{
}
TestGameImp::~TestGameImp()
{
}
void TestGameImp::initialize()
{
}
void TestGameImp::destroy()
{
}
taf::Int32 TestGameImp::doRequest(taf::Int64 iConnId,const std::string & strAccount,const std::string & sMsgPack,const std::string & sRsObjAddr,const map<std::string, std::string> & mClientParam,taf::JceCurrentPtr current)
{
current->setResponse(false);
ServerEngine::CSMessage tmpCsMsg;
if(!tmpCsMsg.ParseFromString(sMsgPack) )
{
return -1;
}
cout<<"dorequest|"<<strAccount<<"|"<<sRsObjAddr<<"|"<<tmpCsMsg.strmsgbody()<<endl;
ServerEngine::PushPrx pushPrx = Application::getCommunicator()->stringToProxy<ServerEngine::PushPrx>(sRsObjAddr);
ServerEngine::CSMessage tmpMsg;
tmpMsg.set_icmd(100000);
tmpMsg.set_strmsgbody(tmpCsMsg.strmsgbody() );
char szData[1024] = {0};
tmpMsg.SerializeToArray(&szData[2], tmpMsg.ByteSize() );
*(unsigned short*)szData = htons(tmpMsg.ByteSize() + 2);
pushPrx->async_doPush(NULL, iConnId, string(szData, tmpMsg.ByteSize() + 2) );
return -1;
}
taf::Int32 TestGameImp::doNotifyLoginOff(const std::string & strAccount,taf::Short nLoginOffCode,const std::string & sRsObjAddr,taf::Int64 iConnId,taf::JceCurrentPtr current)
{
return 1;
}
void TestGameImp::getGameStatus(ServerEngine::GameQueryStatus &gameStatus,taf::JceCurrentPtr current)
{
gameStatus.iMemberCount = 1510;
}
|
2a78963af2a2cba32df9a50bc654892a46571ec9 | 924de80dab7907fdb03ab1cafeea6e399d9759c6 | /CODE/GRAPHIC/SYSTEM/GRAPHIC_SYSTEM.h | ae02a3b91b7675ba5c4fe7b7cd8a64e316193ff5 | [] | no_license | x-tox-man/xengine | 866fd44d79207c71c6ad2709a66496d392ec0f6d | 81b9445795422969848acfffde59136e1eb66fbe | refs/heads/master | 2021-04-29T10:39:43.257184 | 2020-10-25T10:48:54 | 2020-10-25T10:48:54 | 77,837,329 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,646 | h | GRAPHIC_SYSTEM.h | //
// GRAPHIC_SYSTEM.h
// GAME-ENGINE
//
// Created by Christophe Bernard on 21/06/15.
// Copyright (c) 2015 Christophe Bernard. All rights reserved.
//
#ifndef __GAME_ENGINE_REBORN__GRAPHIC_SYSTEM__
#define __GAME_ENGINE_REBORN__GRAPHIC_SYSTEM__
#include "CORE_HELPERS_CLASS.h"
#include "GRAPHIC_SYSTEM_RUNTIME_ENVIRONMENT.h"
#include "GRAPHIC_SYSTEM_COMPARE_OPERATION.h"
#include "GRAPHIC_SYSTEM_BLEND_OPERATION.h"
#include "GRAPHIC_SYSTEM_POLYGON_FILL_MODE.h"
#include "GRAPHIC_POLYGON_FACE.h"
#include "CORE_MATH_VECTOR.h"
#include "CORE_MATH_MATRIX.h"
#include "CORE_DATA_BUFFER.h"
#include "GRAPHIC_TEXTURE_INFO.h"
#include "CORE_PARALLEL_LOCK_MUTEX.h"
#include "CORE_HELPERS_COLOR.h"
#include "GRAPHIC_TEXTURE_FILTERING.h"
#include "GRAPHIC_TEXTURE_WRAP.h"
#include "GRAPHIC_RENDER_TARGET_FRAMEBUFFER_MODE.h"
#include "GRAPHIC_SYSTEM_STENCIL_FAIL_ACTION.h"
#include "GRAPHIC_SYSTEM_BLEND_EQUATION.h"
#include "GRAPHIC_SHADER_BIND.h"
#include "GRAPHIC_RENDERER_STATE_DESCRIPTOR.h"
class GRAPHIC_TEXTURE;
class GRAPHIC_RENDER_TARGET;
class GRAPHIC_SHADER_LIGHT;
class GRAPHIC_SHADER_PROGRAM;
class GRAPHIC_SHADER_ATTRIBUTE;
class GRAPHIC_MESH;
class GRAPHIC_RENDERER;
class GRAPHIC_MATERIAL;
XS_CLASS_BEGIN( GRAPHIC_SYSTEM )
~GRAPHIC_SYSTEM();
static void Initialize( const char * app_name, int app_version );
static void Finalize();
static void EnableScissor( bool enable, void * __GRAPHIC_SYSTEM_CONTEXT = NULL );
static void SetScissorRectangle(float x, float y, float width, float height, void * __GRAPHIC_SYSTEM_CONTEXT = NULL );
static void EnableBlend( const GRAPHIC_SYSTEM_BLEND_OPERATION source, const GRAPHIC_SYSTEM_BLEND_OPERATION destination, void * __GRAPHIC_SYSTEM_CONTEXT = NULL );
static void DisableBlend( void * __GRAPHIC_SYSTEM_CONTEXT = NULL);
static void SetBlendFunction( const GRAPHIC_SYSTEM_BLEND_EQUATION equation, void * __GRAPHIC_SYSTEM_CONTEXT = NULL );
static void EnableStencilTest( const GRAPHIC_SYSTEM_COMPARE_OPERATION operation, int ref, unsigned int mask, void * __GRAPHIC_SYSTEM_CONTEXT = NULL );
static void DisableStencil( void * __GRAPHIC_SYSTEM_CONTEXT = NULL );
static void SetStencilOperation( const GRAPHIC_POLYGON_FACE face, const GRAPHIC_SYSTEM_STENCIL_FAIL_ACTION stencil_fail, const GRAPHIC_SYSTEM_STENCIL_FAIL_ACTION stencil_pass, const GRAPHIC_SYSTEM_STENCIL_FAIL_ACTION stencil_and_depth_fail, void * __GRAPHIC_SYSTEM_CONTEXT = NULL );
static void EnableDepthTest( const GRAPHIC_SYSTEM_COMPARE_OPERATION operation, bool mask, float range_begin = 0.0f, float range_end = 1.0f, void * __GRAPHIC_SYSTEM_CONTEXT = NULL );
static void DisableDepthTest( void * __GRAPHIC_SYSTEM_CONTEXT = NULL );
static void EnableAlpha( void * __GRAPHIC_SYSTEM_CONTEXT = NULL );
static void DisableAlpha( void * __GRAPHIC_SYSTEM_CONTEXT = NULL );
static void EnableBackfaceCulling( const GRAPHIC_POLYGON_FACE face );
static void DisableFaceCulling();
static void UpdateVertexBuffer( GRAPHIC_MESH * mesh, CORE_DATA_BUFFER & data );
static void ReleaseTexture( GRAPHIC_TEXTURE * texture );
static void CreateTexture( GRAPHIC_TEXTURE * texture );
static void CreateDepthTexture( GRAPHIC_TEXTURE * texture, GRAPHIC_TEXTURE_IMAGE_TYPE type );
static void CreateTexture( GRAPHIC_TEXTURE * texture, CORE_DATA_BUFFER & texture_data, bool generate_mipmap );
static void CreateSubTexture( GRAPHIC_TEXTURE * sub_texture, const GRAPHIC_TEXTURE & texture, const CORE_MATH_VECTOR & offset, const CORE_MATH_VECTOR & size, const void * data );
static void ApplyTexture( GRAPHIC_TEXTURE * texture, int texture_index, int shader_texture_attribute_index );
static void ApplyDepthTexture( GRAPHIC_TEXTURE * texture, int texture_index, int shader_texture_attribute_index );
static void DiscardTexture( GRAPHIC_TEXTURE * texture );
static void SetTextureOptions( GRAPHIC_TEXTURE * texture, GRAPHIC_TEXTURE_FILTERING filtering, GRAPHIC_TEXTURE_WRAP wrap, const CORE_HELPERS_COLOR & color );
static void CreateFrameBuffer( GRAPHIC_RENDER_TARGET * target, GRAPHIC_RENDER_TARGET_FRAMEBUFFER_MODE mode );
static void CreateDepthBuffer( GRAPHIC_RENDER_TARGET * target, int width, int height );
static void SetPolygonMode( const GRAPHIC_SYSTEM_POLYGON_FILL_MODE fill_mode );
static void ApplyLightDirectional( const GRAPHIC_SHADER_LIGHT & light, GRAPHIC_SHADER_PROGRAM & program );
static void ApplyLightAmbient( const GRAPHIC_SHADER_LIGHT & light, GRAPHIC_SHADER_PROGRAM & program );
static void ApplyLightPoint( const GRAPHIC_SHADER_LIGHT & light, GRAPHIC_SHADER_PROGRAM & program, int index );
static void ApplyLightSpot( const GRAPHIC_SHADER_LIGHT & light, GRAPHIC_SHADER_PROGRAM & program, int index );
static void ApplyShaderAttributeVector( GRAPHIC_RENDERER & renderer, const float * vector, GRAPHIC_SHADER_ATTRIBUTE & attribute );
static void ApplyShaderAttributeVectorTable( GRAPHIC_RENDERER & renderer, const float * vector, int size, GRAPHIC_SHADER_ATTRIBUTE & attribute );
static void ApplyShaderAttributeFloat( GRAPHIC_RENDERER & renderer, const float value, GRAPHIC_SHADER_ATTRIBUTE & attribute );
static void ApplyShaderAttributeMatrix( GRAPHIC_RENDERER & renderer, const float * matrixs, GRAPHIC_SHADER_ATTRIBUTE & attribute );
static void CreateVertexBuffer( GRAPHIC_MESH & mesh );
static void CreateIndexBuffer( GRAPHIC_MESH & mesh );
static void ReleaseBuffers(GRAPHIC_MESH &mesh);
static void ApplyBuffers( GRAPHIC_RENDERER & renderer, GRAPHIC_MESH &mesh);
static const char * GetShaderDirectoryPath() { return ShaderDirectoryPath; }
static void SetClearColor( CORE_HELPERS_COLOR & color ) { ClearColor = color; }
static void Clear();
static void ClearFrambufferDepth( float default_depth );
static void ClearFrambufferColor();
static void ClearFrambufferStencil();
static void BeginRendering();
static void EndRendering();
static void EnableDefaultFrameBuffer();
static void DisableDefaultFrameBuffer();
static void ApplyMaterial( const GRAPHIC_MATERIAL & material );
// TODO: Remove this hack
static bool RendersOnScreen() { return ItRenderOnScreen; }
static void SetRendersOnScreen( bool on_screen ) { ItRenderOnScreen = on_screen; }
#if X_METAL
static void BeginMtlFrame();
static void EndMtlFrame();
static void * CreateMtlVertexDescriptor( GRAPHIC_SHADER_BIND bind);
static void * CreateMetalFunction( const char * function_name );
static void InitializeMetal( void * view );
static void * GetMtlView();
static void * CreateMetalPipelineState( void * descriptor, GRAPHIC_SHADER_PROGRAM & program );
static void EnableMtlPipelineState( void * pipeline_state );
static void * CreateMetalDynamicUniformBuffer( unsigned long size );
static void EnableMtlUniforms( void * buffer, uint32_t offset, uint32_t size );
static void * GetMtlBufferPointer( void * buffer );
static void * CreateMtlTextureFromDescriptor( void * descriptor );
static void * CreateMtlRenderEncoder( void * descriptor );
static void MtlReleasePipelineState( void * state );
static void * GetCachedStateFromRenderer( GRAPHIC_RENDERER &, GRAPHIC_SHADER_PROGRAM * );
static void * MtlGetCachedStencilStateFromRenderer( GRAPHIC_RENDERER & );
#endif
static CORE_PARALLEL_LOCK_MUTEX
GraphicSystemLock;
static const char *
ShaderDirectoryPath;
static CORE_HELPERS_COLOR
ClearColor;
static bool
ItRenderOnScreen;
XS_CLASS_END
#endif /* defined(__GAME_ENGINE_REBORN__GRAPHIC_SYSTEM__) */
|
5c4dc55546f7193713c79c7ba888725181554082 | bfc88535fa1495c64672f048a5559e8bb6de1ae1 | /CodeChef/APRIL19B/g.cpp | 956b3d265bb8e2f7ffddb98c9bb033b1dce3d96b | [] | no_license | famus2310/CP | 59839ffe23cf74019e2f655f49af224390846776 | d8a77572830fb3927de92f1e913ee729d04865e1 | refs/heads/master | 2021-07-05T00:23:31.113026 | 2020-08-07T22:28:24 | 2020-08-07T22:28:24 | 144,426,214 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,671 | cpp | g.cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
typedef pair<int, pair<int, int> > piii;
#define pb push_back
#define debug(x) cout << x << endl
#define fastio ios_base::sync_with_stdio(0), cin.tie(0)
#define PI acos(-1)
#define all(c) c.begin(), c.end()
#define SET(x, y) memset((x), y, sizeof(x))
const int MOD = 1e9 + 7;
const int INF = 1e9 + 5;
const LL INF64 = 1e18;
const int N = 1e5 + 5;
bool isPalin[1005][1005];
LL dp[1005][1005];
LL dp1[1005][1005];
LL dp2[1005][1005];
LL cnt[1005][1005];
string s;
bool isPal(string s) {
string tmp = s;
reverse(all(s));
return tmp == s;
}
int main() {
cin >> s;
int sz = s.size();
if (sz == 1) {
cout << 0 << endl;
return 0;
}
assert(sz > 0);
SET(dp, 0);
for (int i = 0; i < sz; i++) {
isPalin[i][i] = 1;
}
for (int i = 2; i <= sz; i++) {
for (int j = 0; j + i - 1 < sz; j++) {
int lf = j;
int rg = j + i - 1;
if (rg - lf == 1) {
isPalin[lf][rg] = (s[lf] == s[rg]);
} else
isPalin[lf][rg] = isPalin[lf + 1][rg - 1] && (s[lf] == s[rg]);
// cout << lf << " " << rg << " : " << isPalin[lf][rg] << endl;
}
}
LL ans = 0LL;
for (int i = 0; i < sz; i++) {
dp2[i][i] = dp1[i][i] = 1;
}
for (int i = 2; i <= sz; i++) {
for (int j = 0; j + i - 1 < sz; j++) {
int lf = j;
int rg = i + j - 1;
if (s[lf] == s[rg]) {
if (rg - lf > 1)
dp[lf][rg] += dp1[lf + 1][rg - 1] + dp2[lf + 1][rg - 1];
dp[lf][rg] += dp[lf + 1][rg - 1] + 1;
}
dp1[lf][rg] = dp1[lf][rg - 1] + isPalin [lf][rg];
dp2[lf][rg] = dp2[lf + 1][rg] + isPalin [lf][rg];
ans = ans + dp[lf][rg];
// cout << dp1[lf + 1][rg - 1] << endl;
// cout << dp2[lf + 1][rg - 1] << endl;
// cout << lf << " " << rg << " : "<< endl;
// cout << "dp : " << dp[lf][rg] << endl;
// cout << "dp1 : " << dp1[lf][rg] << endl;
// cout << "dp2 : " << dp2[lf][rg] << endl;
}
}
// SET(cnt, 0);
// int tmp = 0;
// for (int i = 0; i < sz; i++) {
// for (int j = i + 1; j < sz; j++) {
// for (int szi = 1; i + szi - 1 < j; szi++) {
// for (int szj = 1; j + szj - 1 < sz; szj++) {
// string a = s.substr(i, szi);
// string b = s.substr(j, szj);
// if (isPal(a + b)) {
// if (i == 0 && j + szj - 1 == 4)
// cout << a << " " << b << endl;
// cnt[i][j + szj - 1]++;
// tmp++;
// }
// }
// }
// }
// }
// cout << endl;
// for (int i = 2; i <= sz; i++) {
// for (int j = 0; j + i - 1 < sz; j++) {
// int lf = j;
// int rg = j + i - 1;
// cout << lf << " " << rg << " : " << cnt[lf][rg] << endl;
// }
// }
// cout << tmp << endl;
cout << ans << endl;
return 0;
}
|
b15c6169416edda19a898f00b8642861d06809d2 | a980ba973c6365b2b2f11a1af443191596ded453 | /lib/Secrets/lockcoderequest.cpp | 0ee2c31fdb0f3932b28016958e7216afc4f4ab23 | [
"LicenseRef-scancode-free-unknown",
"BSD-3-Clause"
] | permissive | sailfishos/sailfish-secrets | 44f724f1470e7b4bbfbd4c0ab4cb481cbc54f2e0 | 303687d1e4e71cf741b6aec3b35dd78c033b1ede | refs/heads/master | 2023-04-07T06:44:07.878773 | 2023-03-21T10:41:41 | 2023-03-21T10:41:41 | 109,001,458 | 27 | 16 | BSD-3-Clause | 2023-08-31T14:14:11 | 2017-10-31T13:43:11 | C++ | UTF-8 | C++ | false | false | 17,604 | cpp | lockcoderequest.cpp | /*
* Copyright (C) 2018 Jolla Ltd.
* Contact: Chris Adams <chris.adams@jollamobile.com>
* All rights reserved.
* BSD 3-Clause License, see LICENSE.
*/
#include "Secrets/lockcoderequest.h"
#include "Secrets/lockcoderequest_p.h"
#include "Secrets/secretmanager.h"
#include "Secrets/secretmanager_p.h"
#include "Secrets/serialization_p.h"
#include <QtDBus/QDBusPendingReply>
#include <QtDBus/QDBusPendingCallWatcher>
using namespace Sailfish::Secrets;
LockCodeRequestPrivate::LockCodeRequestPrivate()
: m_lockStatus(LockCodeRequest::Unknown)
, m_lockCodeRequestType(LockCodeRequest::ModifyLockCode)
, m_lockCodeTargetType(LockCodeRequest::MetadataDatabase)
, m_userInteractionMode(SecretManager::SystemInteraction)
, m_status(Request::Inactive)
{
}
/*!
\qmltype LockCodeRequest
\brief Allows a client to request that the system service either
unlock, lock, or modify the lock code associated with the
device, an extension plugin, a standalone secret or a
collection.
\inqmlmodule Sailfish.Secrets
\inherits Request
*/
/*!
\class LockCodeRequest
\brief Allows a client to request that the system service either
unlock, lock, or modify the lock code associated with the
device, an extension plugin, a standalone secret or a
collection.
\inmodule SailfishSecrets
\inheaderfile Secrets/lockcoderequest.h
\b{Note: most clients will never need to use this class, as the
other request types automatically trigger locking and relocking
flows as required.}
The operation will be applied to the secrets bookkeeping database
of the device, an extension plugin, a custom-locked collection or
a standalone secret specified by the \l{lockCodeTargetType()} and
\l{lockCodeTarget()} parameters. This operation is only valid for
custom-locked collections or secrets when performed by a non-privileged
application.
If the \l{lockCodeRequestType()} specified is \l{ModifyLockCode}
then the user will be prompted (via a system-mediated user interaction
flow) for the current lock code, and if that matches the existing
lock code, they will then be prompted for the new lock code. The
datum will then be re-encrypted with a key derived from the new lock code.
If the \l{lockCodeRequestType()} specified is \l{QueryLockStatus}
then the service will return whether the specified target plugin
or metadata database is locked and requires a lock code to be entered.
If the \l{lockCodeRequestType()} specified is \l{ProvideLockCode}
then the user will be prompted (via a system-mediated user interaction
flow) for the current lock code, which will be used to unlock the datum.
If the \l{lockCodeRequestType()} specified is \l{ForgetLockCode}
then if the datum is currently unlocked, the user will be prompted (via a
system-mediated user interaction flow) for the current lock code, and if
it matches the actual lock code, the datum will be locked.
An example of modifying the lock code used for a custom-locked collection
follows:
\code
// Require an alpha-numeric lock code to be provided
Sailfish::Secrets::InteractionParameters uiParams;
uiParams.setInputType(Sailfish::Secrets::InteractionParameters::AlphaNumericInput);
uiParams.setEchoMode(Sailfish::Secrets::InteractionParameters::PasswordEcho);
// Request that the collection be re-keyed.
Sailfish::Secrets::SecretManager sm;
Sailfish::Secrets::LockCodeRequest lcr;
lcr.setManager(&sm);
lcr.setLockCodeRequestType(Sailfish::Secrets::LockCodeRequest::ModifyLockCode);
lcr.setLockCodeTargetType(Sailfish::Secrets::LockCodeRequest::ExtensionPlugin);
lcr.setLockCodeTarget(QLatin1String("Some custom-locked collection"));
lcr.setInteractionParameters(uiParams);
lcr.startRequest(); // status() will change to Finished when complete
\endcode
*/
/*!
\brief Constructs a new LockCodeRequest object with the given \a parent.
*/
LockCodeRequest::LockCodeRequest(QObject *parent)
: Request(parent)
, d_ptr(new LockCodeRequestPrivate)
{
}
/*!
\brief Destroys the LockCodeRequest
*/
LockCodeRequest::~LockCodeRequest()
{
}
/*!
\qmlproperty enumeration lockCodeRequestType
\brief The type of lock code operation being requested
\value QueryLockStatus
\value ModifyLockCode
\value ProvideLockCode
\valie ForgetLockCode
*/
/*!
\brief Returns the type of lock code operation being requested
*/
LockCodeRequest::LockCodeRequestType LockCodeRequest::lockCodeRequestType() const
{
Q_D(const LockCodeRequest);
return d->m_lockCodeRequestType;
}
/*!
\brief Sets the type of lock code operation being requested to \a type
*/
void LockCodeRequest::setLockCodeRequestType(LockCodeRequest::LockCodeRequestType type)
{
Q_D(LockCodeRequest);
if (d->m_status != Request::Active && d->m_lockCodeRequestType != type) {
d->m_lockCodeRequestType = type;
if (d->m_status == Request::Finished) {
d->m_status = Request::Inactive;
emit statusChanged();
}
if (d->m_lockStatus != LockCodeRequest::Unknown) {
d->m_lockStatus = LockCodeRequest::Unknown;
emit lockStatusChanged();
}
emit lockCodeRequestTypeChanged();
}
}
/*!
\qmlproperty enumeration LockCodeRequest::lockCodeTargetType
\brief The type of the target of the lock code operation
\value MetadataDatabase
\value ExtensionPlugin
*/
/*!
\brief Returns the type of the target of the lock code operation
*/
LockCodeRequest::LockCodeTargetType LockCodeRequest::lockCodeTargetType() const
{
Q_D(const LockCodeRequest);
return d->m_lockCodeTargetType;
}
/*!
\brief Sets the type of the target of the lock code operation to \a type
Only privileged applications (usually, the system settings application)
can perform lock code operations on the bookkeeping database.
Only the owner of a collection or standalone-secret can perform lock code
operations on that collection or secret.
Some plugins must be unlocked prior to use, and such plugins should
document their semantics for their intended clients.
*/
void LockCodeRequest::setLockCodeTargetType(LockCodeRequest::LockCodeTargetType type)
{
Q_D(LockCodeRequest);
if (d->m_status != Request::Active && d->m_lockCodeTargetType != type) {
d->m_lockCodeTargetType = type;
if (d->m_status == Request::Finished) {
d->m_status = Request::Inactive;
emit statusChanged();
}
emit lockCodeTargetTypeChanged();
}
}
/*!
\qmlproperty enumeration LockCodeRequest::userInteractionMode
\brief The user interaction mode required when retrieving lock codes from the user
\value PreventInteraction no user interaction allowed, operation will fail if interaction is required
\value SystemInteraction system-mediated user interaction via system UI if required
\value ApplicationInteraction in-process application UI will handle interaction, ApplicationSpecificAuthentication only.
*/
/*!
\brief Returns the user interaction mode required when retrieving lock codes from the user
*/
SecretManager::UserInteractionMode LockCodeRequest::userInteractionMode() const
{
Q_D(const LockCodeRequest);
return d->m_userInteractionMode;
}
/*!
\brief Sets the user interaction mode required when retrieving lock codes from the user to \a mode
This should only (and must be) be set to
\l{SecretManager::ApplicationInteraction} if the collection or standalone
secret is owned by the caller application and its original user interaction
mode was already set to \c{ApplicationInteraction}, otherwise an error will
be returned.
Note that if \l{interactionParameters()} are provided then the \a mode
will be ignored, which may result in an error being returned to the client
(that is, if the collection or standalone secret is owned by the caller
application and its original user interaction mode was set to
\c{ApplicationInteraction}).
*/
void LockCodeRequest::setUserInteractionMode(SecretManager::UserInteractionMode mode)
{
Q_D(LockCodeRequest);
if (d->m_status != Request::Active && d->m_userInteractionMode != mode) {
d->m_userInteractionMode = mode;
if (d->m_status == Request::Finished) {
d->m_status = Request::Inactive;
emit statusChanged();
}
emit userInteractionModeChanged();
}
}
/*!
\qmlproperty InteractionParameters LockCodeRequest::interactionParameters
\brief The user input parameters which should be used when requesting the secret data from the user
*/
/*!
\brief Returns the user input parameters which should be used when requesting the secret data from the user
*/
InteractionParameters LockCodeRequest::interactionParameters() const
{
Q_D(const LockCodeRequest);
return d->m_interactionParameters;
}
/*!
\brief Sets the user input parameters which should be used when requesting the lock code from the user to \a params
Note: specifying user input parameters implies that system-mediated user interaction
flows are allowed by the calling application, and are required by the collection
or standalone secret for which the lock code is being requested.
*/
void LockCodeRequest::setInteractionParameters(const InteractionParameters ¶ms)
{
Q_D(LockCodeRequest);
if (d->m_status != Request::Active && d->m_interactionParameters != params) {
d->m_interactionParameters = params;
if (d->m_status == Request::Finished) {
d->m_status = Request::Inactive;
emit statusChanged();
}
emit interactionParametersChanged();
}
}
// TODO: in the future support oldLockCodeInteractionParameters also?
// e.g. to allow changing the type of lock code (from PIN to ALPHANUM, etc)?
/*!
\qmlproperty string LockCodeRequest::lockCodeTarget
\brief The name of the target to which the lock code operation should be applied
*/
/*!
\brief Returns the name of the target to which the lock code operation should be applied
*/
QString LockCodeRequest::lockCodeTarget() const
{
Q_D(const LockCodeRequest);
return d->m_lockCodeTarget;
}
/*!
\brief Sets the name of the target to which the lock code operation should be applied to \a name
The \a name may identify either a custom-locked collection,
a custom-locked standalone secret, an extension plugin or
the bookkeeping database, depending on the value of the
\l{lockCodeTargetType()}.
*/
void LockCodeRequest::setLockCodeTarget(const QString &targetName)
{
Q_D(LockCodeRequest);
if (d->m_status != Request::Active && d->m_lockCodeTarget != targetName) {
d->m_lockCodeTarget = targetName;
if (d->m_status == Request::Finished) {
d->m_status = Request::Inactive;
emit statusChanged();
}
emit lockCodeTargetChanged();
}
}
/*!
\qmlproperty enumeration LockCodeRequest::lockStatus
\brief The current lock status of the target plugin or metadata database
\value Unknown
\value Unsupported
\value Unlocked
\value Locked
*/
/*!
\brief Returns the current lock status of the target plugin or metadata database
The value will only be valid if the request's operation is \c{QueryLockStatus}.
Per-plugin lock status information is also reported from PluginInfoRequest.
*/
LockCodeRequest::LockStatus LockCodeRequest::lockStatus() const
{
Q_D(const LockCodeRequest);
return d->m_lockStatus;
}
Request::Status LockCodeRequest::status() const
{
Q_D(const LockCodeRequest);
return d->m_status;
}
Result LockCodeRequest::result() const
{
Q_D(const LockCodeRequest);
return d->m_result;
}
SecretManager *LockCodeRequest::manager() const
{
Q_D(const LockCodeRequest);
return d->m_manager.data();
}
void LockCodeRequest::setManager(SecretManager *manager)
{
Q_D(LockCodeRequest);
if (d->m_manager.data() != manager) {
d->m_manager = manager;
emit managerChanged();
}
}
void LockCodeRequest::startRequest()
{
Q_D(LockCodeRequest);
if (d->m_status != Request::Active && !d->m_manager.isNull()) {
d->m_status = Request::Active;
emit statusChanged();
if (d->m_result.code() != Result::Pending) {
d->m_result = Result(Result::Pending);
emit resultChanged();
}
if (d->m_lockCodeRequestType == LockCodeRequest::QueryLockStatus) {
QDBusPendingReply<Result, LockCodeRequest::LockStatus> reply;
reply = d->m_manager->d_ptr->queryLockStatus(d->m_lockCodeTargetType,
d->m_lockCodeTarget);
if (!reply.isValid() && !reply.error().message().isEmpty()) {
d->m_status = Request::Finished;
d->m_result = Result(Result::SecretManagerNotInitializedError,
reply.error().message());
d->m_lockStatus = LockCodeRequest::Unknown;
emit lockStatusChanged();
emit statusChanged();
emit resultChanged();
} else if (reply.isFinished()
// work around a bug in QDBusAbstractInterface / QDBusConnection...
&& reply.argumentAt<0>().code() != Sailfish::Secrets::Result::Succeeded) {
d->m_status = Request::Finished;
d->m_result = reply.argumentAt<0>();
d->m_lockStatus = LockCodeRequest::Unknown;
emit lockStatusChanged();
emit statusChanged();
emit resultChanged();
} else {
d->m_watcher.reset(new QDBusPendingCallWatcher(reply));
connect(d->m_watcher.data(), &QDBusPendingCallWatcher::finished,
[this] {
QDBusPendingCallWatcher *watcher = this->d_ptr->m_watcher.take();
QDBusPendingReply<Result, LockCodeRequest::LockStatus> reply = *watcher;
this->d_ptr->m_status = Request::Finished;
this->d_ptr->m_result = reply.argumentAt<0>();
this->d_ptr->m_lockStatus = reply.argumentAt<1>();
watcher->deleteLater();
emit this->lockStatusChanged();
emit this->statusChanged();
emit this->resultChanged();
});
}
} else {
QDBusPendingReply<Result> reply;
if (d->m_lockCodeRequestType == LockCodeRequest::ModifyLockCode) {
reply = d->m_manager->d_ptr->modifyLockCode(d->m_lockCodeTargetType,
d->m_lockCodeTarget,
d->m_interactionParameters,
d->m_userInteractionMode);
} else if (d->m_lockCodeRequestType == LockCodeRequest::ProvideLockCode) {
reply = d->m_manager->d_ptr->provideLockCode(d->m_lockCodeTargetType,
d->m_lockCodeTarget,
d->m_interactionParameters,
d->m_userInteractionMode);
} else { // ForgetLockCode
reply = d->m_manager->d_ptr->forgetLockCode(d->m_lockCodeTargetType,
d->m_lockCodeTarget,
d->m_interactionParameters,
d->m_userInteractionMode);
}
if (!reply.isValid() && !reply.error().message().isEmpty()) {
d->m_status = Request::Finished;
d->m_result = Result(Result::SecretManagerNotInitializedError,
reply.error().message());
emit statusChanged();
emit resultChanged();
} else if (reply.isFinished()
// work around a bug in QDBusAbstractInterface / QDBusConnection...
&& reply.argumentAt<0>().code() != Sailfish::Secrets::Result::Succeeded) {
d->m_status = Request::Finished;
d->m_result = reply.argumentAt<0>();
emit statusChanged();
emit resultChanged();
} else {
d->m_watcher.reset(new QDBusPendingCallWatcher(reply));
connect(d->m_watcher.data(), &QDBusPendingCallWatcher::finished,
[this] {
QDBusPendingCallWatcher *watcher = this->d_ptr->m_watcher.take();
QDBusPendingReply<Result> reply = *watcher;
this->d_ptr->m_status = Request::Finished;
if (reply.isError()) {
this->d_ptr->m_result = Result(Result::DaemonError,
reply.error().message());
} else {
this->d_ptr->m_result = reply.argumentAt<0>();
}
watcher->deleteLater();
emit this->statusChanged();
emit this->resultChanged();
});
}
}
}
}
void LockCodeRequest::waitForFinished()
{
Q_D(LockCodeRequest);
if (d->m_status == Request::Active && !d->m_watcher.isNull()) {
d->m_watcher->waitForFinished();
}
}
|
9f83026a4b573bbfd9bdf50b05fdcc64b3312b21 | 2ea34a7ff11da761313e32914b23ca748e7d3d66 | /coba-coba Addition of two numbers 230919.cpp | 8354c147f46819520d9ad0098d8320142cc91ef1 | [] | no_license | andimaliaAMFB/Dasar-Pemrograman-C- | a6c0666f458df1a31c287c3fd7dd80866541ab34 | 1584a080b955851f304a1dbb9e3108ea56d7714c | refs/heads/main | 2023-02-25T20:31:50.498096 | 2021-01-30T05:57:04 | 2021-01-30T05:57:04 | 334,338,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 230 | cpp | coba-coba Addition of two numbers 230919.cpp | #include <iostream>
using namespace std;
int main()
{
int num1,num2,hasil;
cout<<"Masukan angka Pertama: ";
cin>>num1;
cout<<"Masukan angka ke-2: ";
cin>>num2;
hasil=num1+num2;
cout<<"Hasil= "<<hasil;
}
|
fac2dbcf30bfa4e8b1b885e7f84317671716ee1c | 1f41b828fb652795482cdeaac1a877e2f19c252a | /standalone c++/glfwProj/glfwProj/Key.h | cab59deb554358aa412344950560f6a63ff61e93 | [] | no_license | jonntd/mayadev-1 | e315efe582ea433dcf18d7f1e900920f5590b293 | f76aeecb592df766d05a4e10fa2c2496f0310ca4 | refs/heads/master | 2021-05-02T07:16:17.941007 | 2018-02-05T03:55:12 | 2018-02-05T03:55:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 169 | h | Key.h | #pragma once
#include <GLFW/glfw3.h>
class Key
{
public:
Key();
~Key();
static void key_callback(GLFWwindow* wnd, int key, int scancode, int action, int mods);
}; |
f30a5acfe9425b1ce02cf2943f201fbf29ed3a55 | 5eb519bf5c71ff4c28d2c7463825c0816ea92584 | /src/lib/ARObjects.h | b943a41044fe7a594eca62916df10996cf5d7384 | [] | no_license | sortofsleepy/ofxARKit | ab219a5e1454042c0a956253a222245707f87e73 | 1ede6a0ea1b5e909ed50cf9e0caef49c36f36ad7 | refs/heads/master | 2023-02-22T02:06:36.357252 | 2021-08-15T17:28:50 | 2021-08-15T17:28:50 | 99,613,090 | 255 | 35 | null | 2023-02-08T22:02:07 | 2017-08-07T19:35:58 | Objective-C++ | UTF-8 | C++ | false | false | 3,689 | h | ARObjects.h | // ARObjects.hpp
//
// Created by Joseph Chow on 8/25/17.
// With additional help by contributors.
//
#ifndef ARObjects_hpp
#define ARObjects_hpp
#include <stdio.h>
#include "ofMain.h"
#include "ARFaceTrackingBool.h"
namespace ofxARKit {
//! This defines the basic data structure of a Plane
typedef struct {
ofVec3f position;
float width;
float height;
ofMatrix4x4 transform;
NSUUID * uuid;
ARPlaneAnchor * rawAnchor;
ARPlaneAnchorAlignment alignment;
ARPlaneAnchorAlignment getAlignment(){
return alignment;
}
// here for convinience, but you may want to build your own.
ofMesh planeMesh;
// reference to vertices
vector<glm::vec3> vertices;
// reference to uvs
vector<glm::vec2> uvs;
// reference to indices
vector<uint16_t> indices;
// colors, just for fun
ofFloatColor debugColor;
vector<ofFloatColor> colors;
void buildMesh(){
// clear previous contents
planeMesh.clear();
planeMesh.addVertices(vertices);
planeMesh.addTexCoords(uvs);
planeMesh.addIndices(indices);
planeMesh.addColors(colors);
}
}PlaneAnchorObject;
typedef struct {
ofVec3f position;
std::string imageName;
float width;
float height;
ofMatrix4x4 transform;
NSUUID * uuid;
ARImageAnchor * rawAnchor;
}ImageAnchorObject;
//! The base class you can use to build your AR object. Provides a model matrix and a mesh for easy tracking by ARKit.
typedef struct {
// a flag indicating whether or not this object was found by ARKit itself, or whether or not it was user added.
bool systemAdded=false;
// mesh for drawing a 3d object
ofMesh mesh;
// model matrix to store anchor tranform info
ofMatrix4x4 modelMatrix;
// a reference to the anchor itself.
ARAnchor * rawAnchor;
NSUUID * getUUID(){
return rawAnchor.identifier;
}
}ARObject;
#if AR_FACE_TRACKING
//! The base class to build a Face geometry
typedef struct {
// raw anchor
ARFaceAnchor * raw;
// reference to vertices
vector<glm::vec3> vertices;
int vertexCount;
int triangleCount;
// reference to uvs
vector<glm::vec2> uvs;
// reference to indices
vector<uint16_t> indices;
NSUUID * uuid;
// here for convinience, but you may want to build your own.
ofMesh faceMesh;
void rebuildFace(){
// clear previous contents
faceMesh.clear();
faceMesh.addVertices(vertices);
faceMesh.addTexCoords(uvs);
faceMesh.addIndices(indices);
}
float getBlendShape(ARBlendShapeLocation blendShapeLocation) {
return raw.blendShapes[blendShapeLocation].floatValue;
}
}FaceAnchorObject;
#endif
//! quickly constructs an standard ARObject
static inline ARObject buildARObject(ARAnchor * rawAnchor,ofMatrix4x4 modelMatrix,bool systemAdded=false){
ARObject obj;
obj.rawAnchor = rawAnchor;
obj.modelMatrix = modelMatrix;
obj.systemAdded = systemAdded;
return obj;
}
};
#endif /* ARObjects_hpp */
|
518782b494be85456b208b8e626fd41e62239362 | 997f0af92ac9fa805e916c9135fac763a7eadd51 | /Digital Circuits/alwaysoffgate.cpp | f964d871c5a4a187edc3d3b11bf51851aba424fd | [] | no_license | nimajnaimi/Cpp | 2e9037947050949b36cae272395173f73605c6c8 | f1bb1237c52a973c81576306f03dadd195145e42 | refs/heads/master | 2020-09-13T01:11:07.589957 | 2019-11-19T05:44:53 | 2019-11-19T05:44:53 | 222,614,663 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 269 | cpp | alwaysoffgate.cpp | #include "alwaysoffgate.h"
AlwaysOFFgate::AlwaysOFFgate(string name) : Gate(name)
{
output = false;
}
AlwaysOFFgate::~AlwaysOFFgate()
{
//dtor
}
void AlwaysOFFgate::cycle() {
}
bool AlwaysOFFgate::isReadyToCycle() const {
return true;
}
|
05da82fddf6b2aa0a6ba8beadb06650671c5e8bb | e67259f518e61f2b15dda1eb767f012a5f3a6958 | /src/planner/binder/statement/bind_delete.cpp | cbe02c005e7a608b1096bca60b777ca26afe1c97 | [
"MIT"
] | permissive | AdrianRiedl/duckdb | e0151d883d9ef2fa1b84296c57e9d5d11210e9e3 | 60c06c55973947c37fcf8feb357da802e39da3f1 | refs/heads/master | 2020-11-26T13:14:07.776404 | 2020-01-31T11:44:23 | 2020-01-31T11:44:23 | 229,081,391 | 2 | 0 | MIT | 2019-12-19T15:17:41 | 2019-12-19T15:17:40 | null | UTF-8 | C++ | false | false | 777 | cpp | bind_delete.cpp | #include "duckdb/parser/statement/delete_statement.hpp"
#include "duckdb/planner/binder.hpp"
#include "duckdb/planner/expression_binder/where_binder.hpp"
#include "duckdb/planner/statement/bound_delete_statement.hpp"
using namespace duckdb;
using namespace std;
unique_ptr<BoundSQLStatement> Binder::Bind(DeleteStatement &stmt) {
auto result = make_unique<BoundDeleteStatement>();
// visit the table reference
result->table = Bind(*stmt.table);
if (result->table->type != TableReferenceType::BASE_TABLE) {
throw BinderException("Can only delete from base table!");
}
// project any additional columns required for the condition
if (stmt.condition) {
WhereBinder binder(*this, context);
result->condition = binder.Bind(stmt.condition);
}
return move(result);
}
|
72c80429c089982723e0c1ce6900cc0f48c75c38 | 57625110a30efc8360f396294c247e107e220efa | /src/modules/data/data.cc | c6054ecb603b886a1ae16be1c5bb282e1e1efe7b | [] | no_license | Jsty00/star | f27314864f84a7072a37ff875a260678132d51c2 | 64a8dff9719dd5926f12e77898c8994780c3b97a | refs/heads/master | 2023-03-23T10:01:51.233265 | 2021-02-24T16:11:42 | 2021-02-24T16:11:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,756 | cc | data.cc | #include "../util/files.h"
#include "data_c.h"
using namespace star;
m21list *star_data_get_lines_from_file(const char *filename) {
char *path;
FILE *file = fopen(filename, "r");
if (!file) math21_file_error(filename);
m21list *lines = math21_data_structure_list_create();
while ((path = math21_file_get_line_c(file))) {
math21_data_structure_list_insert(lines, path);
}
fclose(file);
return lines;
}
char **star_data_get_labels(const char *filename) {
m21list *plist = star_data_get_lines_from_file(filename);
char **labels = (char **) math21_data_structure_list_to_array(plist);
math21_data_structure_list_free(plist);
return labels;
}
m21list *star_data_read_config(const char *filename) {
FILE *file = fopen(filename, "r");
if (file == 0) math21_file_error(filename);
char *line;
int nu = 0;
m21list *options = math21_data_structure_list_create();
while ((line = math21_file_get_line_c(file)) != 0) {
++nu;
math21_string_strip(line);
switch (line[0]) {
case '\0':
case '#':
case ';':
free(line);
break;
default:
if (!math21_function_option_read(line, options)) {
fprintf(stderr, "Config file error line %d, could parse: %s\n", nu, line);
free(line);
}
break;
}
}
fclose(file);
return options;
}
mllabels star_data_get_labels_from_data_config(const char *data_config) {
mllabels m = {0};
m21list *options = star_data_read_config(data_config);
const char *name_list = math21_function_option_find_str(options, "names", 0);
if (!name_list) name_list = math21_function_option_find_str(options, "labels", 0);
if (!name_list) {
fprintf(stderr, "No names or labels found\n");
} else {
m.names = star_data_get_labels(name_list);
}
m.n = math21_function_option_find_int(options, "classes", 2);
math21_data_structure_list_free(options);
return m;
}
const char *star_data_get_backup_dir(m21list *l, const char *def) {
const char *backup_directory = math21_function_option_find_str(l, "backup", def);
fprintf(stderr, "You should make sure %s exists!\n", backup_directory);
return backup_directory;
}
size_t star_pr_rand_size_t() {
return math21_pr_rand_size_t();
}
star_float_pair
star_ml_function_rnn_data_get_one_hot_n(const int *tokens, size_t *mb_offsets, int x_size, size_t n_data_x, int mbs,
int n_time_step) {
float *x = (float *) math21_vector_calloc_cpu(n_time_step * mbs * x_size, sizeof(float));
float *y = (float *) math21_vector_calloc_cpu(n_time_step * mbs * x_size, sizeof(float));
int i, j;
for (j = 0; j < n_time_step; ++j) {
for (i = 0; i < mbs; ++i) {
int curr = tokens[(mb_offsets[i]) % n_data_x];
int next = tokens[(mb_offsets[i] + 1) % n_data_x];
x[(j * mbs + i) * x_size + curr] = 1;
y[(j * mbs + i) * x_size + next] = 1;
mb_offsets[i] = (mb_offsets[i] + 1) % n_data_x;
if (curr >= x_size || curr < 0 || next >= x_size || next < 0) {
math21_error("Bad char");
}
}
}
star_float_pair p;
p.x = x;
p.y = y;
return p;
}
// x shape: n_time_step * mbs * x_size, x_size = 256, and x in x_size is one-hot.
star_float_pair star_ml_function_rnn_data_get_one_hot_255(const unsigned char *data, size_t *mb_offsets, int x_size,
size_t n_data_x, int mbs, int n_time_step) {
float *x = (float *) math21_vector_calloc_cpu(n_time_step * mbs * x_size, sizeof(float));
float *y = (float *) math21_vector_calloc_cpu(n_time_step * mbs * x_size, sizeof(float));
int i, j;
for (j = 0; j < n_time_step; ++j) {
for (i = 0; i < mbs; ++i) {
unsigned char curr = data[(mb_offsets[i]) % n_data_x];
unsigned char next = data[(mb_offsets[i] + 1) % n_data_x];
x[(j * mbs + i) * x_size + curr] = 1;
y[(j * mbs + i) * x_size + next] = 1;
mb_offsets[i] = (mb_offsets[i] + 1) % n_data_x;
if (curr <= 0 || next <= 0) {
math21_error("Bad char");
}
}
}
star_float_pair p;
p.x = x;
p.y = y;
return p;
}
star_float_pair star_ml_function_rnn_data_get_n_dim(
const float *data, size_t *mb_offsets, int x_size,
size_t n_data_x, int mbs, int n_time_step) {
auto *x = (float *) math21_vector_calloc_cpu(n_time_step * mbs * x_size, sizeof(float));
auto *y = (float *) math21_vector_calloc_cpu(n_time_step * mbs * x_size, sizeof(float));
int its, imb, ix;
for (its = 0; its < n_time_step; ++its) {
for (imb = 0; imb < mbs; ++imb) {
size_t curr = (mb_offsets[imb]) % n_data_x;
size_t next = (mb_offsets[imb] + 1) % n_data_x;
for (ix = 0; ix < x_size; ++ix) {
x[(its * mbs + imb) * x_size + ix] = data[curr * x_size + ix];
y[(its * mbs + imb) * x_size + ix] = data[next * x_size + ix];
}
mb_offsets[imb] = (mb_offsets[imb] + 1) % n_data_x;
}
}
star_float_pair p;
p.x = x;
p.y = y;
return p;
}
star_float_pair star_ml_function_rnn_data_stock_get_n_dim(
const float *data, size_t *mb_offsets, int x_size,
size_t n_data_x, int mbs, int n_time_step) {
auto *x = (float *) math21_vector_calloc_cpu(n_time_step * mbs * x_size, sizeof(float));
auto *y = (float *) math21_vector_calloc_cpu(n_time_step * mbs * x_size, sizeof(float));
int its, imb, ix;
for (its = 0; its < n_time_step; ++its) {
for (imb = 0; imb < mbs; ++imb) {
size_t curr = (mb_offsets[imb]) % n_data_x;
size_t next = (mb_offsets[imb] + 1) % n_data_x;
for (ix = 0; ix < x_size; ++ix) {
x[(its * mbs + imb) * x_size + ix] = data[curr * x_size + ix];
y[(its * mbs + imb) * x_size + ix] = data[next * x_size + ix];
}
mb_offsets[imb] = (mb_offsets[imb] + 1) % n_data_x;
}
}
star_float_pair p;
p.x = x;
p.y = y;
return p;
}
// Normalise window with a base value of zero
void star_ml_function_rnn_data_stock_normalise_windows(
float *x, float *y, int mbs, int n_time_step, int x_size) {
int its, imb, ix;
for (imb = 0; imb < mbs; ++imb) {
for (its = n_time_step - 1; its >= 0; --its) {
for (ix = 0; ix < x_size; ++ix) {
int index0 = 0 * mbs * x_size + imb * x_size + ix;
int index = its * mbs * x_size + imb * x_size + ix;
x[index] = x[index] / x[index0] - 1;
y[index] = y[index] / y[index0] - 1;
}
}
}
}
star_float_pair star_ml_function_rnn_data_get_stock(
float *data, size_t *mb_offsets, int x_size,
size_t n_data_x, int mbs, int n_time_step) {
star_float_pair p = star_ml_function_rnn_data_stock_get_n_dim(
data, mb_offsets, x_size,
n_data_x, mbs, n_time_step);
star_ml_function_rnn_data_stock_normalise_windows(p.x, p.y, mbs, n_time_step, x_size);
return p;
}
// x_size = y_size
star_float_pair star_ml_function_rnn_data_get_sin_01(
float *data, size_t *mb_offsets, int x_size,
size_t n_data_x, int mbs, int n_time_step) {
star_float_pair p = star_ml_function_rnn_data_stock_get_n_dim(
data, mb_offsets, x_size,
n_data_x, mbs, n_time_step);
return p;
}
// y has no time dimension.
// x_size != y_size
star_float_pair star_ml_function_rnn_data_get_sin(
float *data, size_t *mb_offsets, int x_size, int y_size,
size_t n_data_x, int mbs, int n_time_step) {
auto *x = (float *) math21_vector_calloc_cpu(n_time_step * mbs * x_size, sizeof(float));
// auto *y = (float *) math21_vector_calloc_cpu(n_time_step * mbs * y_size, sizeof(float));
auto *y = (float *) math21_vector_calloc_cpu(mbs * y_size, sizeof(float));
int its, imb, ix;
size_t n_data_raw = n_data_x * x_size;
for (imb = 0; imb < mbs; ++imb) {
for (its = 0; its < n_time_step; ++its) {
size_t curr = (mb_offsets[imb]) % n_data_x;
for (ix = 0; ix < x_size; ++ix) {
x[(its * mbs + imb) * x_size + ix] = data[curr * x_size + ix];
}
mb_offsets[imb] = (mb_offsets[imb] + 1) % n_data_x;
}
// for y
size_t curr = (mb_offsets[imb]) % n_data_x;
for (ix = 0; ix < y_size; ++ix) {
y[imb * y_size + ix] = data[(curr * x_size + ix) % n_data_raw];
}
}
star_float_pair p;
p.x = x;
p.y = y;
return p;
}
char **star_data_read_tokens(const char *filename, size_t *read) {
MATH21_ASSERT(0)
return 0;
/*size_t size = 512;
size_t count = 0;
FILE *fp = fopen(filename, "r");
char **d = (char **) math21_vector_calloc_cpu(size, sizeof(char *));
char *line;
while ((line = math21_file_get_line_c(fp)) != 0) {
++count;
if (count > size) {
size = size * 2;
d = (char **) math21_vector_realloc_cpu(d, size * sizeof(char *));
}
if (0 == strcmp(line, "<NEWLINE>")) line = "\n";
d[count - 1] = line;
}
fclose(fp);
d = (char **) math21_vector_realloc_cpu(d, count * sizeof(char *));
*read = count;
return d;*/
}
void star_ml_function_net_load_function_paras_from_config_upto_dk(mlfunction_net *fnet, const char *filename,
int index_node_start,
int index_node_cutoff) {
#ifndef MATH21_FLAG_USE_CPU
if (fnet->gpuDevice >= 0) {
math21_gpu_set_device_wrapper(fnet->gpuDevice);
}
#endif
fprintf(stdout, "Loading weights from %s...\n", filename);
fflush(stdout);
FILE *fp = fopen(filename, "rb");
if (!fp) math21_file_error(filename);
int major;
int minor;
int revision;
fread(&major, sizeof(int), 1, fp);
fread(&minor, sizeof(int), 1, fp);
fread(&revision, sizeof(int), 1, fp);
if ((major * 10 + minor) >= 2 && major < 1000 && minor < 1000) {
size_t n_seen;
fread(&n_seen, sizeof(size_t), 1, fp);
fnet->n_seen = n_seen;
} else {
int n_seen = 0;
fread(&n_seen, sizeof(int), 1, fp);
fnet->n_seen = n_seen;
}
#if 1
m21log("major", major);
m21log("minor", minor);
m21log("revision", revision);
m21log("fnet->n_seen", fnet->n_seen);
#endif
int transpose = (major > 1000) || (minor > 1000);
int i;
for (i = index_node_start; i < fnet->n_node && i < index_node_cutoff; ++i) {
mlfunction_node *fnode = fnet->nodes[i];
// layer l = net->layers[i];
if (fnode->dontload) continue;
if (fnode->type == mlfnode_type_conv) {
mlfunction_conv *f = (mlfunction_conv *) fnode->function;
math21_ml_function_conv_load_theta(f, fp);
} else if (fnode->type == mlfnode_type_fully_connected) {
mlfunction_fully_connected *f = (mlfunction_fully_connected *) fnode->function;
math21_ml_function_fully_connected_load_theta_order_bwsmv_flipped(f, fp, transpose);
} else if (fnode->type == mlfnode_type_rnn) {
mlfunction_rnn *f = (mlfunction_rnn *) fnode->function;
math21_ml_function_fully_connected_load_theta_order_bwsmv_flipped(f->input_layer, fp, transpose);
math21_ml_function_fully_connected_load_theta_order_bwsmv_flipped(f->self_layer, fp, transpose);
math21_ml_function_fully_connected_load_theta_order_bwsmv_flipped(f->output_layer, fp, transpose);
} else if (fnode->type == mlfnode_type_lstm) {
mlfunction_lstm *f = (mlfunction_lstm *) fnode->function;
math21_tool_assert(f->implementationMode==1);
math21_ml_function_fully_connected_load_theta_order_bwsmv_flipped(f->fcUi, fp, transpose);
math21_ml_function_fully_connected_load_theta_order_bwsmv_flipped(f->fcUf, fp, transpose);
math21_ml_function_fully_connected_load_theta_order_bwsmv_flipped(f->fcUo, fp, transpose);
math21_ml_function_fully_connected_load_theta_order_bwsmv_flipped(f->fcUg, fp, transpose);
math21_ml_function_fully_connected_load_theta_order_bwsmv_flipped(f->fcWi, fp, transpose);
math21_ml_function_fully_connected_load_theta_order_bwsmv_flipped(f->fcWf, fp, transpose);
math21_ml_function_fully_connected_load_theta_order_bwsmv_flipped(f->fcWo, fp, transpose);
math21_ml_function_fully_connected_load_theta_order_bwsmv_flipped(f->fcWg, fp, transpose);
} else if (fnode->type == mlfnode_type_batchnorm) {
math21_tool_assert(0);
mlfunction_batchnorm *f = (mlfunction_batchnorm *) fnode->function;
math21_ml_function_batchnorm_load_theta(f, fp, 1);
}
}
fprintf(stderr, "Done!\n");
fclose(fp);
}
void star_ml_function_net_load_function_paras_from_config(mlfunction_net *fnet, const char *filename) {
if (math21_ml_is_function_paras_file(filename)) {
math21_ml_function_net_load_function_paras_from_config(fnet, filename);
} else {
star_ml_function_net_load_function_paras_from_config_upto_dk(fnet, filename, 0, fnet->n_node);
}
}
mlfunction_net *star_ml_function_net_create_from_file(const char *function_file, const char *paras_file, int isClear) {
mlfunction_net *fnet = math21_ml_function_net_load_function_form_from_config(function_file);
if (paras_file && paras_file[0] != 0) {
star_ml_function_net_load_function_paras_from_config(fnet, paras_file);
}
if (isClear) fnet->n_seen = 0;
return fnet;
}
void
star_ml_function_net_save_function_paras_upto_dk(mlfunction_net *fnet, const char *filename, int index_node_cutoff) {
#ifndef MATH21_FLAG_USE_CPU
if (fnet->gpuDevice >= 0) {
math21_gpu_set_device_wrapper(fnet->gpuDevice);
}
#endif
fprintf(stdout, "Saving weights to %s\n", filename);
FILE *fp = fopen(filename, "wb");
if (!fp) math21_file_error(filename);
int major = 0;
int minor = 2;
int revision = 0;
fwrite(&major, sizeof(int), 1, fp);
fwrite(&minor, sizeof(int), 1, fp);
fwrite(&revision, sizeof(int), 1, fp);
size_t n_seen = fnet->n_seen;
fwrite(&n_seen, sizeof(size_t), 1, fp);
int i;
for (i = 0; i < fnet->n_node && i < index_node_cutoff; ++i) {
mlfunction_node *fnode = fnet->nodes[i];
if (fnode->dontsave) continue;
if (fnode->type == mlfnode_type_conv) {
mlfunction_conv *f = (mlfunction_conv *) fnode->function;
math21_ml_function_conv_save_theta(f, fp);
} else if (fnode->type == mlfnode_type_fully_connected) {
mlfunction_fully_connected *f = (mlfunction_fully_connected *) fnode->function;
math21_ml_function_fully_connected_save_theta_order_bwsmv(f, fp);
} else if (fnode->type == mlfnode_type_rnn) {
mlfunction_rnn *f = (mlfunction_rnn *) fnode->function;
math21_ml_function_fully_connected_save_theta_order_bwsmv(f->input_layer, fp);
math21_ml_function_fully_connected_save_theta_order_bwsmv(f->self_layer, fp);
math21_ml_function_fully_connected_save_theta_order_bwsmv(f->output_layer, fp);
} else if (fnode->type == mlfnode_type_lstm) {
mlfunction_lstm *f = (mlfunction_lstm *) fnode->function;
math21_tool_assert(f->implementationMode==1);
math21_ml_function_fully_connected_save_theta_order_bwsmv(f->fcUi, fp);
math21_ml_function_fully_connected_save_theta_order_bwsmv(f->fcUf, fp);
math21_ml_function_fully_connected_save_theta_order_bwsmv(f->fcUo, fp);
math21_ml_function_fully_connected_save_theta_order_bwsmv(f->fcUg, fp);
math21_ml_function_fully_connected_save_theta_order_bwsmv(f->fcWi, fp);
math21_ml_function_fully_connected_save_theta_order_bwsmv(f->fcWf, fp);
math21_ml_function_fully_connected_save_theta_order_bwsmv(f->fcWo, fp);
math21_ml_function_fully_connected_save_theta_order_bwsmv(f->fcWg, fp);
} else if (fnode->type == mlfnode_type_batchnorm) {
math21_tool_assert(0 && "not used!");
mlfunction_batchnorm *f = (mlfunction_batchnorm *) fnode->function;
math21_ml_function_batchnorm_save_theta(f, fp, 1);
}
}
fclose(fp);
}
// save theta of the function f(x, theta)
void star_ml_function_net_save_function_paras(mlfunction_net *fnet, const char *filename, const char *type) {
if (!type) {
math21_ml_function_net_save_function_paras(fnet, filename);
} else if (math21_string_is_equal(type, "dk")) {
star_ml_function_net_save_function_paras_upto_dk(fnet, filename, fnet->n_node);
}
}
void star_ml_function_paras_convert(const char *function_form, const char *function_paras, const char *dst_paras,
const char *type) {
std::string baseName = star_string_get_file_base_name(function_form);
fprintf(stdout, "converting %s paras\n", baseName.c_str());
mlfunction_net *fnet = star_ml_function_net_create_from_file(function_form, function_paras, 0);
star_ml_function_net_save_function_paras(fnet, dst_paras, type);
}
int sky_ml_function_paras_convert(int argc, const char **argv) {
if (argc == 2) {
if (math21_string_is_equal(argv[1], "--help") || math21_string_is_equal(argv[1], "--h")) {
m21log("\tsky_ml_function_paras_convert \n"
"\tflags:\n"
"\t -function_form\n"
"\t -function_paras\n"
"\t -dst_paras\n"
"\t -type\n"
);
m21log("\te.x., \n"
"\tsky_ml_net_run_rnn train -data rnn.data -function_form lstm.train.cfg\n");
return 1;
}
}
if (argc < 2) {
return 0;
}
const char *function_form = star_string_args_find_c_string(argc, argv, "function_form", 0);
const char *function_paras = star_string_args_find_c_string(argc, argv, "function_paras", 0);
const char *dst_paras = star_string_args_find_c_string(argc, argv, "dst_paras", 0);
const char *type = star_string_args_find_c_string(argc, argv, "type", 0);
star_ml_function_paras_convert(function_form, function_paras, dst_paras, type);
return 1;
} |
b13dcc63eda7b197259a54fa9b7c006c9d459ea5 | 57dde4ae85512d71a412b1a9b7bac8f4a22c7ea8 | /8. Segment Tree/Query bits.cpp | b0cbf90665d2ca6326a0a0f27924e4665fa64776 | [] | no_license | HemantKr79/CB-Competitive-Programming-Solutions | 0efec4f60df03fe54b747c0d561a4eeab568c75e | 5170aeba51730eca8f1e5f31782a6bb5e556b16b | refs/heads/main | 2023-03-22T20:00:18.305515 | 2021-03-01T02:20:46 | 2021-03-01T02:20:46 | 343,264,988 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,709 | cpp | Query bits.cpp | #include<iostream>
#include<vector>
using namespace std;
#define int long long
#define mod 1000000007
vector<int> power(2000006, 0);
void set_bits(vector<int> &tree, vector<int> &lazy, int ss, int se, int l, int r, int index) {
if (lazy[index] != -1) {
if (ss != se) {
lazy[2 * index] = lazy[2 * index + 1] = lazy[index];
}
if (lazy[index] == 1) {
tree[index] = power[se - ss + 1] - 1;
}
else {
tree[index] = 0;
}
lazy[index] = -1;
}
if (r < ss || l > se) {
return;
}
if (l <= ss && r >= se) {
tree[index] = power[se - ss + 1] - 1;
if (ss != se) {
lazy[2 * index] = lazy[2 * index + 1] = 1;
}
return;
}
int m = (ss + se) / 2;
set_bits(tree, lazy, ss, m, l, r, 2 * index);
set_bits(tree, lazy, m + 1, se, l, r, 2 * index + 1);
tree[index] = (power[se - m] * tree[2 * index] + tree[2 * index + 1]) % mod;
}
void clear_bits(vector<int> &tree, vector<int> &lazy, int ss, int se, int l, int r, int index) {
if (lazy[index] != -1) {
if (ss != se) {
lazy[2 * index] = lazy[2 * index + 1] = lazy[index];
}
if (lazy[index] == 1) {
tree[index] = power[se - ss + 1] - 1;
}
else {
tree[index] = 0;
}
lazy[index] = -1;
}
if (r < ss || l > se) {
return;
}
if (l <= ss && r >= se) {
tree[index] = 0;
if (ss != se) {
lazy[2 * index] = lazy[2 * index + 1] = 0;
}
return;
}
int m = (ss + se) / 2;
clear_bits(tree, lazy, ss, m, l, r, 2 * index);
clear_bits(tree, lazy, m + 1, se, l, r, 2 * index + 1);
tree[index] = (power[se - m] * tree[2 * index] + tree[2 * index + 1]) % mod;
}
int query(vector<int> &tree, vector<int> &lazy, int ss, int se, int l, int r, int index) {
if (lazy[index] != -1) {
if (ss != se) {
lazy[2 * index] = lazy[2 * index + 1] = lazy[index];
}
if (lazy[index] == 1) {
tree[index] = power[se - ss + 1] - 1;
}
else {
tree[index] = 0;
}
lazy[index] = -1;
}
if (r < ss || l > se) {
return 0;
}
if (l <= ss && r >= se) {
return tree[index];
}
int m = (ss + se) / 2;
int leftAns = query(tree, lazy, ss, m, l, r, 2 * index);
int shift = max(0ll, m - l + 1);
int rightAns = query(tree, lazy, m + 1, se, l, r, 2 * index + 1);
return (power[shift] * leftAns + rightAns) % mod;
}
int32_t main() {
int n, q;
cin >> n >> q;
vector<int> tree(4 * n + 2, 0);
vector<int> lazy(4 * n + 2, -1);
power[0] = 1;
for (int i = 1; i <= n; i++) {
power[i] = 2 * power[i - 1];
power[i] %= mod;
}
while (q--) {
int qType, l, r;
cin >> qType >> l >> r;
if (qType == 0) {
clear_bits(tree, lazy, 0, n - 1, l, r, 1);
}
else if (qType == 1) {
set_bits(tree, lazy, 0, n - 1, l, r, 1);
}
else {
cout << query(tree, lazy, 0, n - 1, l, r, 1) << "\n";
}
}
return 0;
} |
1af8adda88635ef91b6365cc67dae0c4345e94af | eea72893d7360d41901705ee4237d7d2af33c492 | /src/track/spacepoint/CsCalSpacePoint.h | 788408614947735393c25d6320503b92a0faba1d | [] | no_license | lsilvamiguel/Coral.Efficiencies.r14327 | 5488fca306a55a7688d11b1979be528ac39fc433 | 37be8cc4e3e5869680af35b45f3d9a749f01e50a | refs/heads/master | 2021-01-19T07:22:59.525828 | 2017-04-07T11:56:42 | 2017-04-07T11:56:42 | 87,541,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 860 | h | CsCalSpacePoint.h | // $Id: CsCalSpacePoint.h,v 1.2 2003/04/24 07:23:24 benigno Exp $
/*!
\file CsCalSpacePoint.h
\brief Calibrarion spacepoint, derived from CsSpacePoint Class.
\author Hugo Pereira
\version $Revision: 1.2 $
\date $Date: 2003/04/24 07:23:24 $
*/
#ifndef CsCalSpacePoint_h
#define CsCalSpacePoint_h
#include <list>
#include "CsSpacePoint.h"
class CsCluster;
class CsDetector;
class CsCalSpacePoint: public CsSpacePoint {
public:
CsCalSpacePoint( const CsDetFamily &df, std::list<CsCluster*> c, double z, int mode); //!< default constructor.
CsCalSpacePoint( const CsCalSpacePoint& sp):CsSpacePoint( sp ) { *this = sp; } //!< copy constructor.
CsCalSpacePoint& operator = ( const CsCalSpacePoint& ); //!< assignment operator.
CsDetector* detOff_;
bool found_;
CsCluster* clFound_;
};
#endif
|
7bb0b775a33dcf4206a98ee06f27196096aefc46 | 65851f6c2ee158020264781c5dc0ee70eba3597a | /Chapter02_Forces/Ex25GravitationalAttractors/src/Ex25GravitationalAttractorsApp.cpp | dc4eef047274592b1f7e17a7a006ed83480669f5 | [] | no_license | hinike/The-Nature-of-Cinder | 2a56d47e80885abe63f61945cf7d9c563e1f5daa | e86ccfe713c9a7ecf860975915c0818ddeadd0b5 | refs/heads/master | 2020-03-19T16:02:40.712658 | 2015-01-27T06:15:32 | 2015-01-27T06:15:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,020 | cpp | Ex25GravitationalAttractorsApp.cpp | #include <vector>
#include "cinder/app/AppNative.h"
#include "cinder/gl/gl.h"
#include "cinder/Rand.h"
#include "Mover.h"
#include "Attractor.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class Ex25GravitationalAttractorsApp : public AppNative {
public:
void prepareSettings( Settings* settings );
void setup();
void mouseDown( MouseEvent event );
void mouseUp( MouseEvent event );
void mouseMove( MouseEvent event );
void mouseDrag( MouseEvent event );
void update();
void draw();
private:
vector< Mover > movers;
unique_ptr< Attractor > attractor;
Vec2f mouseLocation;
};
void Ex25GravitationalAttractorsApp::prepareSettings( Settings* settings )
{
settings->setWindowSize( 800, 200 );
}
void Ex25GravitationalAttractorsApp::setup()
{
for ( auto i = 0; i < 100; ++i ) {
movers.push_back( Mover( randFloat( 0.5f, 1.5f ), randFloat( getWindowWidth() ), randFloat( getWindowHeight() ) ) );
}
attractor = unique_ptr < Attractor > ( new Attractor{ getWindowCenter().x, getWindowCenter().y } );
}
void Ex25GravitationalAttractorsApp::mouseDown( MouseEvent event )
{
attractor->clicked( event.getPos() );
}
void Ex25GravitationalAttractorsApp::mouseUp( MouseEvent event )
{
attractor->stopDragging();
}
void Ex25GravitationalAttractorsApp::mouseMove( MouseEvent event )
{
mouseLocation = event.getPos();
}
void Ex25GravitationalAttractorsApp::mouseDrag( MouseEvent event )
{
mouseLocation = event.getPos();
}
void Ex25GravitationalAttractorsApp::update()
{
attractor->hover( mouseLocation );
attractor->drag( mouseLocation );
for ( auto& mover : movers ) {
mover.applyForce( attractor->attract( mover ) );
mover.update();
}
}
void Ex25GravitationalAttractorsApp::draw()
{
gl::clear( Color{ 0.f, 0.f, 0.f } );
attractor->draw();
for ( auto& mover : movers ) {
mover.draw();
}
}
CINDER_APP_NATIVE( Ex25GravitationalAttractorsApp, RendererGl )
|
b6d179e555815404d7b6efdd6df099b3e5440b5c | 2919deaad34e98b368a919b73f68e2f9e2ae10d9 | /Graphic2/Graphic2/SkinnedAnimations.cpp | e61c99dbaf308f96da2321446f1d87e9a2890949 | [] | no_license | Tonykidv2/The2Planeteersandthe1Musketeer | f720a6158fa90eae892c9c52a4ae46df5831ce20 | 50a2b98e31bf5927d7516519d8a3141efbdfbdb8 | refs/heads/master | 2021-01-11T05:20:21.604026 | 2016-11-18T14:32:40 | 2016-11-18T14:32:40 | 71,957,424 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,981 | cpp | SkinnedAnimations.cpp | #include "SkinnedAnimations.h"
float BoneAnimation::GetStartTime()const
{
// Keyframes are sorted by time, so first keyframe gives start time.
return (float)Keyframes.front()->m_FrameNum;
}
float BoneAnimation::GetEndTime()const
{
// Keyframes are sorted by time, so last keyframe gives end time.
float f = (float)Keyframes.back()->m_FrameNum;
return f;
}
void BoneAnimation::Interpolate(float t, DirectX::XMFLOAT4X4& M)const
{
if (t <= Keyframes.front()->m_FrameNum)
{
DirectX::XMVECTOR S = DirectX::XMLoadFloat3(&Keyframes.front()->Scale);
DirectX::XMVECTOR P = DirectX::XMLoadFloat3(&Keyframes.front()->Translation);
DirectX::XMVECTOR Q = DirectX::XMLoadFloat4(&Keyframes.front()->RotationQuat);
DirectX::XMVECTOR zero = DirectX::XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f);
DirectX::XMStoreFloat4x4(&M, DirectX::XMMatrixAffineTransformation(S, zero, Q, P));
}
else if (t >= Keyframes.back()->m_FrameNum)
{
float lerpPercent = (t / (Keyframes.back()->m_FrameNum + Keyframes[Keyframes.size() -1]->m_FrameNum));
DirectX::XMVECTOR S = DirectX::XMLoadFloat3(&Keyframes.back()->Scale);
DirectX::XMVECTOR P = DirectX::XMLoadFloat3(&Keyframes.back()->Translation);
DirectX::XMVECTOR Q = DirectX::XMLoadFloat4(&Keyframes.back()->RotationQuat);
DirectX::XMVECTOR zero = DirectX::XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f);
DirectX::XMStoreFloat4x4(&M, DirectX::XMMatrixAffineTransformation(S, zero, Q, P));
}
else
{
for (UINT i = 0; i < Keyframes.size() - 1; ++i)
{
if (t >= Keyframes[i]->m_FrameNum && t <= Keyframes[i + 1]->m_FrameNum)
{
float lerpPercent = (t - Keyframes[i]->m_FrameNum) / (Keyframes[i + 1]->m_FrameNum - Keyframes[i]->m_FrameNum);
DirectX::XMVECTOR s0 = DirectX::XMLoadFloat3(&Keyframes[i]->Scale);
DirectX::XMVECTOR s1 = DirectX::XMLoadFloat3(&Keyframes[i + 1]->Scale);
DirectX::XMVECTOR p0 = DirectX::XMLoadFloat3(&Keyframes[i]->Translation);
DirectX::XMVECTOR p1 = DirectX::XMLoadFloat3(&Keyframes[i + 1]->Translation);
DirectX::XMVECTOR q0 = DirectX::XMLoadFloat4(&Keyframes[i]->RotationQuat);
DirectX::XMVECTOR q1 = DirectX::XMLoadFloat4(&Keyframes[i + 1]->RotationQuat);
DirectX::XMVECTOR S = DirectX::XMVectorLerp(s0, s1, lerpPercent);
DirectX::XMVECTOR P = DirectX::XMVectorLerp(p0, p1, lerpPercent);
DirectX::XMVECTOR Q = DirectX::XMQuaternionSlerp(q0, q1, lerpPercent);
DirectX::XMVECTOR zero = DirectX::XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f);
DirectX::XMStoreFloat4x4(&M, DirectX::XMMatrixAffineTransformation(S, zero, Q, P));
break;
}
}
}
}
float AnimationClip::GetClipStartTime()const
{
// Find smallest start time over all bones in this clip.
float t = FLT_MAX;
for (unsigned int i = 0; i < BoneAnimations.size(); ++i)
{
if (BoneAnimations[i].Keyframes.size() == 0)
continue;
t = min(t, BoneAnimations[i].GetStartTime());
}
return t;
}
float AnimationClip::GetClipEndTime()const
{
// Find largest end time over all bones in this clip.
float t = 0.0f;
for (unsigned int i = 0; i < BoneAnimations.size(); ++i)
{
if (BoneAnimations[i].Keyframes.size() == 0)
continue;
t = max(t, BoneAnimations[i].GetEndTime());
}
return t;
}
void AnimationClip::Interpolate(float t, DirectX::XMFLOAT4X4(*boneTransforms)[50])const
{
for (unsigned int i = 0; i < BoneAnimations.size(); ++i)
{
if (BoneAnimations[i].Keyframes.size() == 0)
continue;
BoneAnimations[i].Interpolate(t, (*boneTransforms)[i]);
}
}
void AnimationController::Update(float _dt, DirectX::XMFLOAT4X4(*boneTransforms)[50])
{
if (GetAsyncKeyState(VK_NUMPAD0) & 0x1)
{
WhichAnimation++;
if (WhichAnimation > Anim.size() - 1)
WhichAnimation = 0;
}
CurrTime += _dt;
Anim[WhichAnimation].Interpolate(CurrTime, boneTransforms);
if (CurrTime >= Anim[WhichAnimation].GetClipEndTime())
CurrTime = 0.95f;
}
void AnimationBlending::Update(float _dt, AnimationClip fromthis, AnimationClip ToThis, DirectX::XMFLOAT4X4(*OutTransform)[50])
{
} |
22b154a6ac1ec7eadbce6523f9a1e449b1eafff0 | 5d4753b7e463827c9540e982108de22f62435c3f | /testing/cc/keyset_impl_test.cc | 248adfedc48176f7d4bb161dcd8bb0c4a7bdfbd7 | [
"Apache-2.0"
] | permissive | thaidn/tink | 8c9b65e3f3914eb54d70847c9f56853afd051dd3 | 2a75c1c3e4ef6aa1b6e29700bf5946b725276c95 | refs/heads/master | 2021-07-25T02:02:59.839232 | 2021-02-10T17:21:31 | 2021-02-10T17:22:01 | 337,815,957 | 2 | 0 | Apache-2.0 | 2021-02-10T18:28:20 | 2021-02-10T18:28:20 | null | UTF-8 | C++ | false | false | 6,830 | cc | keyset_impl_test.cc | // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////
#include "keyset_impl.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "tink/aead/aead_key_templates.h"
#include "tink/binary_keyset_reader.h"
#include "tink/binary_keyset_writer.h"
#include "tink/cleartext_keyset_handle.h"
#include "tink/config/tink_config.h"
#include "tink/hybrid/hybrid_key_templates.h"
#include "proto/testing/testing_api.grpc.pb.h"
namespace crypto {
namespace tink {
namespace {
using ::crypto::tink::AeadKeyTemplates;
using ::crypto::tink::BinaryKeysetReader;
using ::crypto::tink::BinaryKeysetWriter;
using ::crypto::tink::CleartextKeysetHandle;
using ::crypto::tink::HybridKeyTemplates;
using google::crypto::tink::KeyTemplate;
using ::testing::Eq;
using ::testing::IsEmpty;
using tink_testing_api::KeysetFromJsonRequest;
using tink_testing_api::KeysetFromJsonResponse;
using tink_testing_api::KeysetGenerateRequest;
using tink_testing_api::KeysetGenerateResponse;
using tink_testing_api::KeysetPublicRequest;
using tink_testing_api::KeysetPublicResponse;
using tink_testing_api::KeysetToJsonRequest;
using tink_testing_api::KeysetToJsonResponse;
class KeysetImplTest : public ::testing::Test {
protected:
static void SetUpTestSuite() { ASSERT_TRUE(TinkConfig::Register().ok()); }
};
TEST_F(KeysetImplTest, GenerateSuccess) {
tink_testing_api::KeysetImpl keyset;
const KeyTemplate& key_template = AeadKeyTemplates::Aes128Eax();
KeysetGenerateRequest request;
std::string templ;
EXPECT_TRUE(key_template.SerializeToString(&templ));
request.set_template_(templ);
KeysetGenerateResponse response;
EXPECT_TRUE(keyset.Generate(nullptr, &request, &response).ok());
EXPECT_THAT(response.err(), IsEmpty());
auto reader_result = BinaryKeysetReader::New(response.keyset());
ASSERT_TRUE(reader_result.ok());
auto handle_result =
CleartextKeysetHandle::Read(std::move(reader_result.ValueOrDie()));
EXPECT_TRUE(handle_result.ok());
}
TEST_F(KeysetImplTest, GenerateFail) {
tink_testing_api::KeysetImpl keyset;
KeysetGenerateRequest request;
request.set_template_("bad template");
KeysetGenerateResponse response;
EXPECT_TRUE(keyset.Generate(nullptr, &request, &response).ok());
EXPECT_THAT(response.err(), Not(IsEmpty()));
}
std::string ValidPrivateKeyset() {
auto handle_result = KeysetHandle::GenerateNew(
HybridKeyTemplates::EciesP256HkdfHmacSha256Aes128Gcm());
EXPECT_TRUE(handle_result.ok());
std::stringbuf keyset;
auto writer_result =
BinaryKeysetWriter::New(absl::make_unique<std::ostream>(&keyset));
EXPECT_TRUE(writer_result.ok());
auto status = CleartextKeysetHandle::Write(writer_result.ValueOrDie().get(),
*handle_result.ValueOrDie());
EXPECT_TRUE(status.ok());
return keyset.str();
}
TEST_F(KeysetImplTest, PublicSuccess) {
tink_testing_api::KeysetImpl keyset;
KeysetPublicRequest request;
request.set_private_keyset(ValidPrivateKeyset());
KeysetPublicResponse response;
EXPECT_TRUE(keyset.Public(nullptr, &request, &response).ok());
EXPECT_THAT(response.err(), IsEmpty());
auto reader_result = BinaryKeysetReader::New(response.public_keyset());
ASSERT_TRUE(reader_result.ok());
auto public_handle_result =
CleartextKeysetHandle::Read(std::move(reader_result.ValueOrDie()));
EXPECT_TRUE(public_handle_result.ok());
}
TEST_F(KeysetImplTest, PublicFail) {
tink_testing_api::KeysetImpl keyset;
KeysetPublicRequest request;
request.set_private_keyset("bad keyset");
KeysetPublicResponse response;
EXPECT_TRUE(keyset.Public(nullptr, &request, &response).ok());
EXPECT_THAT(response.err(), Not(IsEmpty()));
}
TEST_F(KeysetImplTest, FromJsonSuccess) {
tink_testing_api::KeysetImpl keyset;
std::string json_keyset = R""""(
{
"primaryKeyId": 42,
"key": [
{
"keyData": {
"typeUrl": "type.googleapis.com/google.crypto.tink.AesGcmKey",
"keyMaterialType": "SYMMETRIC",
"value": "AFakeTestKeyValue1234567"
},
"outputPrefixType": "TINK",
"keyId": 42,
"status": "ENABLED"
}
]
})"""";
KeysetFromJsonRequest from_request;
from_request.set_json_keyset(json_keyset);
KeysetFromJsonResponse from_response;
EXPECT_TRUE(keyset.FromJson(nullptr, &from_request, &from_response).ok());
EXPECT_THAT(from_response.err(), IsEmpty());
std::string output = from_response.keyset();
auto reader_result = BinaryKeysetReader::New(from_response.keyset());
EXPECT_TRUE(reader_result.ok());
auto keyset_proto_result = reader_result.ValueOrDie()->Read();
EXPECT_TRUE(keyset_proto_result.ok());
EXPECT_THAT(keyset_proto_result.ValueOrDie()->primary_key_id(), Eq(42));
}
TEST_F(KeysetImplTest, ToFromJsonSuccess) {
tink_testing_api::KeysetImpl keyset;
std::string keyset_data = ValidPrivateKeyset();
KeysetToJsonRequest to_request;
to_request.set_keyset(keyset_data);
KeysetToJsonResponse to_response;
EXPECT_TRUE(keyset.ToJson(nullptr, &to_request, &to_response).ok());
EXPECT_THAT(to_response.err(), IsEmpty());
std::string json_keyset = to_response.json_keyset();
KeysetFromJsonRequest from_request;
from_request.set_json_keyset(json_keyset);
KeysetFromJsonResponse from_response;
EXPECT_TRUE(keyset.FromJson(nullptr, &from_request, &from_response).ok());
EXPECT_THAT(from_response.err(), IsEmpty());
std::string output = from_response.keyset();
EXPECT_THAT(from_response.keyset(), Eq(keyset_data));
}
TEST_F(KeysetImplTest, ToJsonFail) {
tink_testing_api::KeysetImpl keyset;
KeysetToJsonRequest request;
request.set_keyset("bad keyset");
KeysetToJsonResponse response;
EXPECT_TRUE(keyset.ToJson(nullptr, &request, &response).ok());
EXPECT_THAT(response.err(), Not(IsEmpty()));
}
TEST_F(KeysetImplTest, FromJsonFail) {
tink_testing_api::KeysetImpl keyset;
KeysetFromJsonRequest request;
request.set_json_keyset("bad json keyset");
KeysetFromJsonResponse response;
EXPECT_TRUE(keyset.FromJson(nullptr, &request, &response).ok());
EXPECT_THAT(response.err(), Not(IsEmpty()));
}
} // namespace
} // namespace tink
} // namespace crypto
|
af8bf4fe74d228b794d6708cec4ce83d9eb45ab3 | 7b53e837f7a5cc4473d1a4e29af82dbde2d94be4 | /98_writing_classes_in_separate_files_using_define/Person.h | c83c3139e8d6bf0825418d4c1d841dc88fa4ec95 | [] | no_license | Rakshit0404/OOPS-programs-and-explainations-by-me | 62035653d878b1b8cc0454a4e9db4bfd185978ae | 002383a4eff3f2dba61a76a2ae21d462313d541b | refs/heads/master | 2023-07-16T18:21:18.257764 | 2021-09-04T06:32:56 | 2021-09-04T06:32:56 | 395,921,333 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 447 | h | Person.h | #ifndef PERSON_H//this line is to check if the variable is not defined,
#define PERSON_H//if it is not defined, we define it and then class definition is done.
//this has been dont to avoid multiple declaration of the same classes.
class Person{
public:
Person();
void display();//if we make headers to include in cpp files and we define a class, its compulsary to declare the member functions.
protected:
private:
};
#endif
|
f40de3ce334705389ea86dc3ad14fc8b66635ebc | 98c0eb22dd0c31e7a2b98367070ef770bc67a4fa | /DoublyLinkedList.h | b0b994ddd37ac7672873f44072f64f68aa4c905e | [] | no_license | naryshev/cpsc350-fall2020-assignment4 | b9f7c7d9da7816cc28be9cac49977f0210ae891d | 5f186aff2914d56aaa5a121b3163358ffd5a3b7b | refs/heads/main | 2023-01-21T22:33:21.688132 | 2020-11-19T07:42:39 | 2020-11-19T07:42:39 | 313,548,986 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,030 | h | DoublyLinkedList.h | /*
Daniel Naryshev
2327209
dnaryshev@chapman.edu
Eshaan Vora
2318955
evora@chapman.edu
Assignment 4 - Registrar Office
*/
#include <iostream>
#include "ListNode.h"
using namespace std;
template <class T>
class DoublyLinkedList {
private:
ListNode<T> *front;
ListNode<T> *back;
unsigned int size;
public:
DoublyLinkedList<T>();
~DoublyLinkedList<T>();
void insertFront(T d);
void insertBack(T d);
T removeFront();
T removeBack();
T getFront();
void printList();
bool isEmpty();
int getSize();
};
template <class T>
DoublyLinkedList<T>::DoublyLinkedList() {
front = NULL;
back = NULL;
size = 0;
}
template <class T>
DoublyLinkedList<T>::~DoublyLinkedList() {
ListNode<T> *current = front;
while(current != 0) {
ListNode<T>* next = current->next;
delete current;
current = next;
}
front = 0;
}
template <class T>
void DoublyLinkedList<T>::printList() {
ListNode<T> *current = front;
while(current != NULL) {
cout << current->data << endl;
current = current->next;
}
}
template <class T>
void DoublyLinkedList<T>::insertFront(T d) {
ListNode<T> *node = new ListNode<T>(d);
if(size == 0) {
back = node;
} else {
node->next = front;
}
front = node;
++size;
}
template <class T>
T DoublyLinkedList<T>::removeFront() {
ListNode<T> *current = front;
delete front;
front = current->next;
return front->data;
}
template <class T>
void DoublyLinkedList<T>::insertBack(T d) {
ListNode<T> *node = new ListNode<T>(d);
if(front == NULL) {
front = back;
} else {
back->next = node;
}
back = node;
++size;
}
template <class T>
T DoublyLinkedList<T>::removeBack() {
ListNode<T> *current = back;
delete back;
back = current->prev;
return back->data;
}
template <class T>
int DoublyLinkedList<T>::getSize() {
return size;
}
template <class T>
T DoublyLinkedList<T>::getFront() {
return front->data;
}
|
a57e48af6ef799794b6060172f2abd27c1f12797 | 94ebc8ca6afaedfba770785f96f3e16d83ba986a | /GBEmu/MMU.cpp | d3beb69468d80059a3c0c51bf9f5eb587cc2d863 | [] | no_license | Dgrayson/GBEmu | 366a563618bc07a27c7161d8f37cdabc0e04bfaa | 975e87ec207ad208251b932e194f1034c983972b | refs/heads/master | 2021-06-19T06:38:57.866809 | 2021-03-23T22:10:06 | 2021-03-23T22:10:06 | 187,305,493 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 587 | cpp | MMU.cpp | #include "pch.h"
#include "MMU.h"
#include <cstdio>
#include <ostream>
#include <iostream>
MMU::MMU()
{
}
MMU::~MMU()
{
}
short MMU::readByte(short PC)
{
return memory[PC];
}
void MMU::writeByte(short PC, short byte)
{
memory[PC] = byte;
}
void MMU::loadRom(char* fileName)
{
FILE* rom;
fopen_s(&rom, fileName, "rb");
if (rom == nullptr)
std::cout << "INvalid file" << std::endl;
fseek(rom, 0, SEEK_END);
long size = ftell(rom);
rewind(rom);
char* buffer = (char*)malloc(sizeof(char) * size);
for(int i = 0; i < size; i++)
{
memory[i] = buffer[i];
}
}
|
6ca9a3ca1df108be4466328e24b6b794864c5a66 | a373b1c21040d6ed7b12448f53140b41c6983c48 | /Classes/gamebase/U2CocosViewComponent.h | 710e3503d3c8878373810e2aec9d9e4b80b81a34 | [] | no_license | Crasader/mygamelogic | 258bfbd16786065b9007b1a3250591bb617c4879 | 609552035469ebdc8075b55ce9bfed7a03059313 | refs/heads/master | 2020-12-10T04:01:14.607094 | 2016-02-16T08:53:08 | 2016-02-16T08:53:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,806 | h | U2CocosViewComponent.h | //
// CRemoteMsgManager.h
// myGame
//
// Created by jiang on 13-7-23.
//
//
#ifndef __U2CocosViewComponent__
#define __U2CocosViewComponent__
#include "U2Core.h"
#include "U2Mvc.h"
#include "cocos2d.h"
#include "ui/CocosGUI.h"
#include "cocostudio/CocoStudio.h"
U2EG_NAMESPACE_USING
class CocosViewComponent : public ViewComponent
{
public:
/**
* Constructor.
*/
CocosViewComponent(const u2::String& type, const u2::String& name);
/**
* Virtual destructor.
*/
virtual ~CocosViewComponent(void);
//virtual const String& getUiName() const = 0;
virtual void loadUi() override;
virtual void onUiLoaded() override;
virtual void unloadUi() override;
virtual void onWillUiUnload() override;
virtual void enter() override;
virtual void onEntered() override;
virtual void exit() override;
virtual void onWillExit() override;
virtual void attach(void* parent) override;
virtual void detach(void* parent) override;
virtual void* getParent() const override;
cocos2d::Node* seekNodeByName(const u2::String& name);
cocos2d::Node* seekNodeByName(cocos2d::Node* root, const u2::String& name);
bool isTransEnd() const;
protected:
cocos2d::Action* createEnterAction();
cocos2d::Action* createExitAction();
void _runAction(cocos2d::FiniteTimeAction* action, const u2::String& actionName);
cocostudio::timeline::ActionTimeline* _runTimeline(const u2::String csb, const u2::String& timelineName);
cocostudio::timeline::ActionTimeline* _runTimeline(cocos2d::Node* pNode, const u2::String csb, const u2::String& timelineName);
protected:
cocos2d::Node* m_pRootNode;
cocos2d::Node* m_pParent;
bool m_bTransEnd;
};
#endif /* defined(__U2CocosViewComponent__) */
|
74553cf5971e8920d6e82d38f51e0919e733fe2f | edab58696afb07657232f17490b24c8e1e11b6c2 | /uva/11388n.cpp | 47142cbb76e70d8b04f12cd95672de5227fa161e | [] | no_license | mhcayan/competitive-programming | cd8e08da67138cfbdcd2d47cd70572a7fc6435fd | f80ab6929a5d2eb780d35679688ea39138cf9e8a | refs/heads/master | 2022-05-27T15:03:46.147224 | 2022-05-22T00:21:29 | 2022-05-22T00:21:29 | 161,851,714 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 185 | cpp | 11388n.cpp | #include<stdio.h>
int main()
{
long c,g,l;
scanf("%ld",&c);
while(c--)
{
scanf("%ld %ld",&g,&l);
if(l%g==0)
printf("%ld %ld\n",g,l);
else
printf("-1\n");
}
return 0;
} |
538cc46a092b51fa007b736afb90ba19ab676871 | 989fbdb229e8d8f93de4dd2e784c520ca837dd15 | /src/base/units/Times.cpp | e17c67cba07d68a6f1bc388324014a3e819242be | [] | no_license | gehldp/OpenEaagles | 3ed7f37d91499067a64dae8fa5826a1e8e47d1f0 | 3f7964d007278792d5f7ac3645b3cd32c11008e3 | refs/heads/master | 2021-01-15T15:58:14.038678 | 2017-08-10T02:35:03 | 2017-08-10T02:35:03 | 2,516,276 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,533 | cpp | Times.cpp | //------------------------------------------------------------------------------
// Time, Seconds, MilliSeconds, Minutes, Hours, Days
//------------------------------------------------------------------------------
#include "openeaagles/base/units/Times.hpp"
#include <iostream>
namespace oe {
namespace base {
//==============================================================================
// Time --
//==============================================================================
IMPLEMENT_ABSTRACT_SUBCLASS(Time, "AbstractTime")
EMPTY_SLOTTABLE(Time)
EMPTY_DELETEDATA(Time)
Time::Time() : Number()
{
STANDARD_CONSTRUCTOR()
}
Time::Time(const double value) : Number(value)
{
STANDARD_CONSTRUCTOR()
}
void Time::copyData(const Time& org, const bool)
{
BaseClass::copyData(org);
val = fromTime(org.toTime());;
}
std::ostream& Time::serialize(std::ostream& sout, const int i, const bool slotsOnly) const
{
int j = 0;
if (!slotsOnly) {
indent(sout, i);
sout << "( " << getFactoryName() << std::endl;
j = 4;
}
indent(sout, i+j);
sout << val << std::endl;
BaseClass::serialize(sout, i+j, true);
if (!slotsOnly) {
indent(sout, i);
sout << ")" << std::endl;
}
return sout;
}
//==============================================================================
// Seconds --
//==============================================================================
IMPLEMENT_EMPTY_SLOTTABLE_SUBCLASS(Seconds, "Seconds")
EMPTY_SERIALIZER(Seconds)
EMPTY_COPYDATA(Seconds)
EMPTY_DELETEDATA(Seconds)
Seconds::Seconds() : Time()
{
STANDARD_CONSTRUCTOR()
}
Seconds::Seconds(const double value) : Time(value)
{
STANDARD_CONSTRUCTOR()
}
Seconds::Seconds(const Time& org) : Time()
{
STANDARD_CONSTRUCTOR()
BaseClass::copyData(org,true);
}
//==============================================================================
// MilliSeconds --
//==============================================================================
IMPLEMENT_EMPTY_SLOTTABLE_SUBCLASS(MilliSeconds, "MilliSeconds")
EMPTY_SERIALIZER(MilliSeconds)
EMPTY_COPYDATA(MilliSeconds)
EMPTY_DELETEDATA(MilliSeconds)
MilliSeconds::MilliSeconds() : Time()
{
STANDARD_CONSTRUCTOR()
}
MilliSeconds::MilliSeconds(const double value) : Time(value)
{
STANDARD_CONSTRUCTOR()
}
MilliSeconds::MilliSeconds(const Time& org) : Time()
{
STANDARD_CONSTRUCTOR()
BaseClass::copyData(org,true);
}
//==============================================================================
// MicroSeconds --
//==============================================================================
IMPLEMENT_EMPTY_SLOTTABLE_SUBCLASS(MicroSeconds, "MicroSeconds")
EMPTY_SERIALIZER(MicroSeconds)
EMPTY_COPYDATA(MicroSeconds)
EMPTY_DELETEDATA(MicroSeconds)
MicroSeconds::MicroSeconds() : Time()
{
STANDARD_CONSTRUCTOR()
}
MicroSeconds::MicroSeconds(const double value) : Time(value)
{
STANDARD_CONSTRUCTOR()
}
MicroSeconds::MicroSeconds(const Time& org) : Time()
{
STANDARD_CONSTRUCTOR()
BaseClass::copyData(org,true);
}
//==============================================================================
// NanoSeconds --
//==============================================================================
IMPLEMENT_EMPTY_SLOTTABLE_SUBCLASS(NanoSeconds, "NanoSeconds")
EMPTY_SERIALIZER(NanoSeconds)
EMPTY_COPYDATA(NanoSeconds)
EMPTY_DELETEDATA(NanoSeconds)
NanoSeconds::NanoSeconds() : Time()
{
STANDARD_CONSTRUCTOR()
}
NanoSeconds::NanoSeconds(const double value) : Time(value)
{
STANDARD_CONSTRUCTOR()
}
NanoSeconds::NanoSeconds(const Time& org) : Time()
{
STANDARD_CONSTRUCTOR()
BaseClass::copyData(org,true);
}
//==============================================================================
// Minutes --
//==============================================================================
IMPLEMENT_EMPTY_SLOTTABLE_SUBCLASS(Minutes, "Minutes")
EMPTY_SERIALIZER(Minutes)
EMPTY_COPYDATA(Minutes)
EMPTY_DELETEDATA(Minutes)
Minutes::Minutes() : Time()
{
STANDARD_CONSTRUCTOR()
}
Minutes::Minutes(const double value) : Time(value)
{
STANDARD_CONSTRUCTOR()
}
Minutes::Minutes(const Time& org) : Time()
{
STANDARD_CONSTRUCTOR()
BaseClass::copyData(org,true);
}
//==============================================================================
// Hours --
//==============================================================================
IMPLEMENT_EMPTY_SLOTTABLE_SUBCLASS(Hours, "Hours")
EMPTY_SERIALIZER(Hours)
EMPTY_COPYDATA(Hours)
EMPTY_DELETEDATA(Hours)
Hours::Hours() : Time()
{
STANDARD_CONSTRUCTOR()
}
Hours::Hours(const double value) : Time(value)
{
STANDARD_CONSTRUCTOR()
}
Hours::Hours(const Time& org) : Time()
{
STANDARD_CONSTRUCTOR()
BaseClass::copyData(org,true);
}
//==============================================================================
// Days --
//==============================================================================
IMPLEMENT_EMPTY_SLOTTABLE_SUBCLASS(Days, "Days")
EMPTY_SERIALIZER(Days)
EMPTY_COPYDATA(Days)
EMPTY_DELETEDATA(Days)
Days::Days() : Time()
{
STANDARD_CONSTRUCTOR()
}
Days::Days(const double value) : Time(value)
{
STANDARD_CONSTRUCTOR()
}
Days::Days(const Time& org) : Time()
{
STANDARD_CONSTRUCTOR()
BaseClass::copyData(org,true);
}
}
}
|
8477130e3d96c59c6ef15f4db14ee22eac76af56 | d4446dd5e3590110225ecff0d273c5effe2e5e76 | /solutions/amazonPowerGrid.cpp | 619267eae48d888cbe50cbfa46c2571591540c87 | [] | no_license | realmelan/leetcode | 7f41dd4cadfe8e55cfbbee8d00c3a2683b74411b | e8d147908dac7e357a22af31921459ee9ed3c5dc | refs/heads/master | 2021-08-19T09:18:20.781322 | 2021-05-05T20:25:56 | 2021-05-05T20:25:56 | 120,499,148 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,666 | cpp | amazonPowerGrid.cpp | //
// amazonPowerGrid.cpp
// leetcode
//
// Created by Song Ding on 11/12/20.
// Copyright © 2020 Song Ding. All rights reserved.
//
#include "common.h"
using namespace std;
namespace amazonPowerGrid {
/*
// TODO: copy problem statement here
Position: New Grad
Platform: SHL
Location: USA
Date: Aug 2020
Your team at amazon is overseeing the design of a new high-efficiency data center at HQ2. A power grid need to be generated for supplying power to N servers. All servers in the grid have to be connected such that they have access to power. The cost of connections between different servers varies.
Assume that there are no ties, names of servers are unique, connections are directionless, there is at most one connection between a pair of servers, all costs are greater than zero, and a server does not connect to itself.
Write an algorithm to minimize the cost of connecting all servers in the power grid.
Input
num, an Integer representing number of connections.
connectons, representing a list of connections where each element of the list consists of two servers and the cost of connection between the servers.
Note
The cost of connection between the servers is always greater than 0.
Example
Input
num = 5
connection =
[[A,B,1],
[B,C,4],
[B,D,6],
[D,E,5],
[C,E,1]]
Output
[[A,B,1],
[B,C,4],
[C,E,1],
[D,E,5]]
*/
class Solution {
public:
// TODO: copy function signature here
vector<vector<int>> amazonPowerGrid(vector<vector<int>>& connections) {
// use priority queue to perform prim's minimum spanning tree
int n = connections.size();
int maxi = 0;
unordered_map<int, unordered_map<int,int>> conns;
vector<int> minCost(3, INT_MAX);
for (auto& edge : connections) {
conns[edge[0]][edge[1]] = edge[2];
conns[edge[1]][edge[0]] = edge[2];
maxi = max(maxi, max(edge[1], edge[0]));
if (minCost[2] > edge[2]) {
minCost = edge;
}
}
auto cmp = [](const auto& a, const auto& b){
return a[2] > b[2];
};
vector<vector<int>> res;
unordered_set<int> added;
priority_queue<vector<int>, vector<vector<int>>, decltype(cmp)> q(cmp);
q.push(minCost);
while (res.size() < maxi) {
auto edge = q.top();q.pop();
if (added.count(edge[0]) && added.count(edge[1])) {
continue;
}
res.push_back(edge);
added.insert(edge[0]);
added.insert(edge[1]);
for (auto p : conns[edge[0]]) {
if (!added.count(p.first)) {
q.push({edge[0], p.first, p.second});
}
}
for (auto p : conns[edge[1]]) {
if (!added.count(p.first)) {
q.push({edge[1], p.first, p.second});
}
}
}
return res;
}
private:
};
}
/*
int main() {
// TODO: define parameter type here
struct param {
vector<vector<int>> connections;
};
// TODO: prepare parameters here
vector<struct param> params {
{{{0,1,1},{1,2,4},{1,3,6},{3,4,5},{2,4,1}}},
};
// TODO: provide expected results here
vector<vector<int>> answers {
{{0,1,1},{1,2,4},{2,4,1},{3,4,5}},
};
for (auto& dp : params) {
cout << endl;
clock_t tstart = clock();
auto res = amazonPowerGrid::Solution().amazonPowerGrid(dp.connections);
cout << res << endl;
cout << clock() - tstart << endl;
}
return 0;
}
//*/
|
5597e88903272842b1f8ea775dd388f76158951e | 8b1a8925f22ba204d179540462724b9d986d0ee3 | /container.cpp | dc1bcdadd1678b9915d520b100d90a56877d48ba | [] | no_license | chengzhengqian/CommonJITInterface | 129019ae56675845bcca84c52bb028dcbd5d6421 | 1b4ad8a8695bd6460458e9eb5e21b9fd817beac0 | refs/heads/master | 2020-04-10T01:30:18.362409 | 2018-12-06T18:52:33 | 2018-12-06T18:52:33 | 160,717,805 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 751 | cpp | container.cpp | #include <iostream>
#include <map>
using namespace std;
typedef void *MapRef;
extern "C" {
MapRef createMapLL() { return (MapRef) new map<long, long>(); }
void disposeMapLL(MapRef m) { delete ((map<long, long> *)m); }
void setMapLL(MapRef m, long k, long v) {
auto m_ = (map<long, long> *)m;
(*m_)[k] = v;
}
long getMapLL(MapRef m, long k) {
auto m_ = (map<long, long> *)m;
return (*m_)[k];
}
void printMapLL(MapRef m) {
auto m_ = (map<long, long> *)m;
for (auto x : (*m_)) {
cout << x.first << ", " << x.second << endl;
}
}
long getMapLLSectionStart(MapRef m, long addr) {
auto m_ = (map<long, long> *)m;
for (auto x : (*m_)) {
if (addr >= x.first && addr < (x.first + x.second))
return x.first;
}
return 0;
}
}
|
4f7e54bff89b50f1fcaf86ac825a667f405dcd8b | 580ca0cde8d78bb908c380bb914e82160e8ff35e | /SDLGame01/Mandel.cpp | 8f10c7699dd2a1c5d4fd1e65d4335feb1c37f2fd | [] | no_license | m-hegyi/sdl-test | 4e43d61b991ddb4022d0d714b260a2842afdea52 | 58cf4a9431eecb797f3b219f8659c7a7e2fb59d3 | refs/heads/master | 2020-03-28T09:04:44.057573 | 2018-09-12T18:58:48 | 2018-09-12T18:58:48 | 148,012,338 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,343 | cpp | Mandel.cpp | #include "Mandel.hpp"
#include <iostream>
bool Mandel::init()
{
m_centerPoint.setX((int)m_width / 2);
m_centerPoint.setY((int)m_height / 2);
m_pixels = new Uint32[m_width * m_height];
memset(m_pixels, 255, m_width * m_height * sizeof(Uint32));
m_resolution = 4;
m_texture = SDL_CreateTexture(m_engine->getRenderer(),
SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STATIC, m_width, m_height);
calculate();
if (m_texture == NULL) {
return false;
}
return true;
}
void Mandel::render() {
/*for (int x = 0; x < m_width; x++) {
Uint8 color = (int)((x + 1) * 255) / m_width;
for (int y = 0; y < m_height; y++) {
m_pixels[x + y * m_width] = color << 16;
}
}*/
SDL_UpdateTexture(m_texture, NULL, m_pixels, m_width * sizeof(Uint32));
SDL_RenderCopy(m_engine->getRenderer(), m_texture, NULL, NULL);
}
void Mandel::calculate() {
// 0 position at 320, 240
// base 100 pixel = 1
// -x -> m_x < 320
// -y -> m_y < 240
// x Min: -3,2 Max: 3,2
// y Min: -2,4 Max: 2,4
// test x => y = 0 z*z+c
//float pos = ((0 - m_centerPoint.getX()) - 0) / (m_unit * m_zoom);
for (int x = 0; x < m_width; x++) {
// if x = 0 pos is -3.2
float pos = ((0 - m_centerPoint.getX()) + x) / (m_unit * m_zoom);
if (!iterate(pos, 0.f)) {
}
}
}
bool Mandel::iterate(float xPos, float yPos) {
// 3 times
return false;
}
|
0fc38d7464b42a367e446c5ac57f46d2d1e6e2f5 | ecd7d2120a0e99c17defdb11ffabc8b237df576c | /cf1265D.cpp | 07353b1ca2a20c1f211139cc73cd67ffacf06dee | [] | no_license | emanlaicepsa/codes | 246735d9b04945ba3511f2bb2f20581abb405ddc | da2fdee786433708251cc8c4fc472e21354a6bc4 | refs/heads/master | 2021-05-20T08:51:38.902467 | 2020-04-01T14:58:51 | 2020-04-01T14:58:51 | 252,206,207 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,411 | cpp | cf1265D.cpp | #include <bits/stdc++.h>
#define IOS ios::sync_with_stdio(false);cin.tie(0);
#define rep(k,n) for(int k=0;k<(n);k++)
#define rep1(k,n) for(int k=1;k<=(n);k++)
#define fi first
#define se second
#define reset(n,k) memset((n),k,sizeof(n))
#define all(n) n.begin(),n.end()
#define pb push_back
#define vi vector<int>
using namespace std;
using ll=long long;
using pii=pair<int,int>;
int arr[100005];
int main(){
int a,b,c,d;
cin>>a>>b>>c>>d;
if(a<=1&&b==0&&c==0&&d==0){
cout<<"YES\n";
cout<<0<<'\n';
return 0;
}
if(a==0&&b==0&&c==0&&d==1){
cout<<"YES\n";
cout<<3<<'\n';
return 0;
}
if(a==b+1&&c==0&&d==0){
cout<<"YES\n";
cout<<0<<" ";
for(int i=0;i<b;i++){
cout<<1<<" "<<0<<" \n"[i==b-1];
}
return 0;
}
if(d==c+1&&a==0&&b==0){
cout<<"YES\n";
cout<<3<<" ";
for(int i=0;i<c;i++){
cout<<2<<" "<<3<<" \n"[i==c-1];
}
return 0;
}
int n=a+b+c+d;
if(a>b||d>c)cout<<"NO\n";
else{
b-=a;
c-=d;
int x=b-c;
if(x>1||x<-1)cout<<"NO\n";
else{
cout<<"YES\n";
int idx=1;
int ridx=n;
if(x==1){
arr[1]=1;
idx++;
b--;
}
if(x==-1){
arr[ridx]=2;
ridx--;
c--;
}
for(int i=0;i<a;i++){
arr[idx++]=0;
arr[idx++]=1;
}
for(int i=0;i<d;i++){
arr[ridx--]=3;
arr[ridx--]=2;
}
for(int i=0;i<b;i++){
arr[idx++]=2;
arr[idx++]=1;
}
rep1(i,n){
cout<<arr[i]<<" \n"[i==n];
}
}
}
}
|
5e9fba1a8044bde594be3bada5ac6bfb16218a7d | af6b7370dcdf9bfccf81d963084b1bbb50a9e714 | /leds.h | 97be6b59e6d305c0d1dc4a5fec2945e8ba61de5c | [] | no_license | maykonsouza/fechadura | 50629426c8c905d854396e273956fa525d9e7a42 | 6afeda421b832fc459ee4459b9099b9f2c010cc9 | refs/heads/master | 2023-06-27T23:31:29.016291 | 2021-07-29T19:45:01 | 2021-07-29T19:45:01 | 386,354,380 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 205 | h | leds.h | #ifndef LEDS_H_INCLUDED
#define LEDS_H_INCLUDED
class Led{
public:
Led(int pin);
void init();
void ligar();
void desligar();
private:
int pin;
};
#endif // LEDS_H_INCLUDED
|
b1f042be1e127158d6b241e1f52021bdc03c6c35 | 72ef49782ccd004b8352a8c6db7bca9123a50247 | /src/client/gui/pawscontrolwindow.cpp | 4c819cb28f099ae44f81bcac5abf041c6cc6edec | [] | no_license | joaocc/planeshift-git | 857d55788fcb5eb857f49a54780e39576fb167df | 7d62dd986a35cb591646c9928c4cd4be15e8ba8e | refs/heads/master | 2021-01-19T14:52:50.468518 | 2014-07-25T02:52:06 | 2014-07-25T02:52:06 | 22,362,463 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,135 | cpp | pawscontrolwindow.cpp | /*
* pawscontrolwindow.cpp - Author: Andrew Craig
*
* Copyright (C) 2003 Atomic Blue (info@planeshift.it, http://www.atomicblue.org)
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation (version 2 of the License)
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
//////////////////////////////////////////////////////////////////////
#include <psconfig.h>
// CS INCLUDES
#include <csgeom/vector3.h>
#include <csutil/xmltiny.h>
#include <iutil/vfs.h>
#include <iutil/objreg.h>
// COMMON INCLUDES
// CLIENT INCLUDES
#include "globals.h"
#include "util/psxmlparser.h"
#include <iutil/cfgmgr.h>
#include <iutil/csinput.h>
// PAWS INCLUDES
#include "pawscontrolwindow.h"
#include "pawsconfigwindow.h"
#include "psmainwidget.h"
#include "paws/pawstextbox.h"
#include "paws/pawsbutton.h"
#include "paws/pawsmanager.h"
#include "paws/pawsyesnobox.h"
#include "util/localization.h"
#include "net/cmdhandler.h"
#include "net/clientmsghandler.h"
//////////////////////////////////////////////////////////////////////
// GUI BUTTONS NOTE: ONLY THOSE WHO NEEDS SPECIAL TREATMENT SHOULD BE
// PLACED HERE!
//////////////////////////////////////////////////////////////////////
#define CONTROL_MINIUP 10
#define CONTROL_MINIDOWN 20
#define CONTROL_QUIT 100
#define IMAGE_SIZE 52
#define ICONS 14
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
pawsControlWindow::pawsControlWindow()
{
hidden = false;
style = 0;
alwaysResize = true;
}
pawsControlWindow::~pawsControlWindow()
{
visible = true; // Force visibility on next load
if (hidden) Toggle(); // Unhide so we get the right sizes saved
csRef<iConfigManager> file = psengine->GetConfig();
file->SetInt("PlaneShift.GUI.ControlWindow.CurrentStyle", style);
file->Save();
}
bool pawsControlWindow::PostSetup()
{
SetAlwaysOnTop(true);
AddWindow( "InventoryWindow" , "InventoryButton" );
AddWindow( "ConfigWindow" , "OptionsButton" );
AddWindow( "SpellBookWindow" , "SpellBookButton" );
AddWindow( "AttackBookWindow" , "AttackButton" );
AddWindow( "InfoWindow" , "InfoButton" );
AddWindow( "HelpWindow" , "HelpButton" );
AddWindow( "ShortcutMenu" , "ShortcutButton" );
AddWindow( "BuddyWindow" , "BuddyButton" );
AddWindow( "GroupWindow" , "GroupButton" );
AddWindow( "PetitionWindow" , "PetitionButton" );
AddWindow( "ChatWindow" , "ChatButton" );
AddWindow( "SkillWindow" , "SkillsButton" );
AddWindow( "QuestNotebook" , "QuestButton" );
AddWindow( "GuildWindow" , "GuildButton" );
AddWindow( "ActiveMagicWindow" , "ActiveMagicButton" );
keyboard = csQueryRegistry<iKeyboardDriver> (PawsManager::GetSingleton().GetObjectRegistry());
//The quit button is a bit special
//We need to manualy register it
QuitIcon = new Icon;
QuitIcon->window = NULL;
QuitIcon->theirButton = (pawsButton*)FindWidget("QuitButton");
QuitIcon->orgRes = QuitIcon->theirButton->GetBackground();
QuitIcon->IsActive = false;
QuitIcon->IsOver = false;
buttons.Push(QuitIcon);
csRef<iConfigManager> file = psengine->GetConfig();
int loadStyle = file->GetInt("PlaneShift.GUI.ControlWindow.CurrentStyle", 1);
for (int i=0; i < loadStyle; i++)
NextStyle(); // Switch to saved style
buttonUp = FindWidget("ShowButtonUp");
buttonDown = FindWidget("ShowButtonDown");
return true;
}
//show/hide buttons
void pawsControlWindow::Toggle()
{
static int oldW = 0, oldH = 0;
static int oldMinW = 0, oldMinH = 0;
for (size_t z = 0; z < children.GetSize(); z++ )
{
if (hidden) children[z]->Show();
else children[z]->Hide();
}
if (hidden)
{
buttonUp->Show();
buttonDown->Hide();
this->SetForceSize(oldW,oldH);
this->SetMinSize(oldMinW,oldMinH);
}
else
{
oldW = this->GetScreenFrame().Width();
oldH = this->GetScreenFrame().Height();
this->GetMinSize(oldMinW,oldMinH);
int w = buttonUp->GetScreenFrame().Width();
int h = buttonUp->GetScreenFrame().Height();
this->SetForceSize(w,h);
this->SetMinSize(w,h);
buttonUp->Hide();
buttonDown->Show();
buttonDown->SetRelativeFramePos(0,0);
}
hidden = !hidden;
}
bool pawsControlWindow::OnMouseEnter()
{
if(keyboard->GetKeyState(CSKEY_SHIFT) && !alwaysResize)
{
SetResizeShow(true);
pawsWidget::OnMouseEnter();
return true;
}
else
return pawsWidget::OnMouseEnter();
}
bool pawsControlWindow::OnMouseExit()
{
if(!alwaysResize)
SetResizeShow(false);
pawsWidget::OnMouseExit();
return true;
}
bool pawsControlWindow::OnButtonReleased(int mouseButton, int /*keyModifier*/, pawsWidget* reporter)
{
if(reporter->GetID() == CONTROL_MINIDOWN || reporter->GetID() == CONTROL_MINIUP)
{
if (mouseButton == csmbRight)
{ //If the user clicked on the right mouse button, switch to another style
if ( !hidden ) //don't allow to change styles while the toolbar is closed
NextStyle();
return true;
}
else if (mouseButton == csmbMiddle)
{
Debug3(LOG_PAWS, 0, "Resetting toolbar to orginal size (%d,%d)", orgw, orgh);
SetRelativeFrameSize(orgw,orgh);
return true;
}
}
switch ( reporter->GetID() )
{
case CONTROL_MINIUP:
{
if ( !hidden )
Toggle();
return true;
}
case CONTROL_MINIDOWN:
{
if ( hidden )
Toggle();
return true;
}
case CONTROL_QUIT:
{
HandleQuit();
QuitIcon->IsActive = true;
csString bg(QuitIcon->orgRes);
bg += "_active";
QuitIcon->theirButton->SetBackground(bg.GetData());
return true;
}
////////////////////////////////////////////////////////////////////
//Special cases that need more than the standard to open correctly
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// These two are from the confirm window buttons for quiting.
////////////////////////////////////////////////////////////////////
case CONFIRM_YES:
{
psengine->QuitClient();
return true;
}
case CONFIRM_NO:
{
PawsManager::GetSingleton().SetModalWidget( 0 );
reporter->GetParent()->Hide();
QuitIcon->IsActive = false;
QuitIcon->theirButton->SetBackground(QuitIcon->orgRes.GetData());
return true;
}
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
//Default handle for windows
////////////////////////////////////////////////////////////////////
default:
{
pawsWidget* wdg = FindWidget(reporter->GetID());
if (!wdg)
return false;
pawsControlledWindow* wnd = FindWindowFromButton(wdg->GetName());
if (!wnd)
return false;
HandleWindow(wnd->GetName());
return true;
}
}
return false;
}
//Returns true if it made it visible, returns false if it made it invisible or error
bool pawsControlWindow::HandleWindow(csString widgetStr)
{
pawsWidget* widget = PawsManager::GetSingleton().FindWidget(widgetStr.GetData());
if (!widget)
{
Error2("%s isn't loaded", widgetStr.GetData());
return false;
}
if ( widget->IsVisible() )
{
widget->Hide();
if ( this->Includes(PawsManager::GetSingleton().GetCurrentFocusedWidget()) )
PawsManager::GetSingleton().SetCurrentFocusedWidget(NULL); // Don't leave focus on us after hiding
return false;
}
else
{
widget->Show();
return true;
}
}
bool pawsControlWindow::HandleWindowName(csString widgetStr)
{
csString widget;
widgetStr.Downcase();
if(widgetStr == "options" )
widget = "ConfigWindow";
else if(widgetStr == "stats" || widgetStr =="skills")
widget = "SkillWindow";
else if(widgetStr == "spell book" || widgetStr == "spells")
widget = "SpellBookWindow";
else if(widgetStr == "inventory" || widgetStr == "inv")
widget = "InventoryWindow";
else if(widgetStr == "attackwindow")
widget = "AttackBookWindow";
else if(widgetStr == "help")
widget = "HelpWindow";
else if(widgetStr == "buddy")
widget = "BuddyWindow";
else if(widgetStr == "info")
widget = "InfoWindow";
else if(widgetStr == "petition" || widgetStr == "petitions")
widget = "PetitionWindow";
else if(widgetStr == "quest")
widget = "QuestNotebook";
else if(widgetStr == "gm")
widget = "GmGUI";
else if(widgetStr == "shortcut")
widget = "ShortcutMenu";
else if(widgetStr == "group")
widget = "GroupWindow";
else if(widgetStr == "guild")
widget = "GuildWindow";
else if(widgetStr == "glyph")
widget = "GlyphWindow";
else if(widgetStr == "sketch")
widget = "SketchWindow";
else if(widgetStr == "merchant")
widget = "MerchantWindow";
else if(widgetStr == "loot")
widget = "LootWindow";
else if(widgetStr == "detail")
widget = "DetailWindow";
else if(widgetStr == "exchange")
widget = "ExchangeWindow";
else if(widgetStr == "write")
widget = "WritingWindow";
else if(widgetStr == "read")
widget = "BookReadingWindow";
else if(widgetStr == "questreward")
widget = "QuestRewardWindow";
else if(widgetStr == "craft")
widget = "CraftWindow";
else if(widgetStr == "ignore")
widget = "IgnoreWindow";
else if(widgetStr == "bag" || widgetStr == "smallinventory")
widget = "SmallInventoryWindow";
else if(widgetStr == "talk" || widgetStr == "chat" || widgetStr == "communications")
widget = "ChatWindow";
else if(widgetStr == "activemagic")
widget = "ActiveMagicWindow";
else if(widgetStr == "managepetitions")
widget = "PetitionGMWindow";
else if(widgetStr == "music")
widget = "MusicWindow";
else if(widgetStr == "quit")
{
HandleQuit();
return true;
}
else if(widgetStr == "buy")
{
psengine->GetCmdHandler()->Execute("/buy");
return true;
}
if(widget)
{
HandleWindow(widget);
return true;
}
else return false;
}
void pawsControlWindow::HandleQuit()
{
PawsManager::GetSingleton().CreateYesNoBox( "\nDo you really wish to leave Yliakum?", this );
}
bool pawsControlWindow::OnChildMouseEnter(pawsWidget *child)
{
pawsButton* btn = (pawsButton*)child;
Icon* icon = GetIcon(child->GetName());
if (!icon)
return false;
csString bg(icon->orgRes); //Get the icon and then get the orignal resource bg
bg += "_over";
btn->SetBackground(bg.GetData());
return true;
}
bool pawsControlWindow::OnChildMouseExit(pawsWidget *child)
{
pawsButton* btn = (pawsButton*)child;
Icon* icon = GetIcon(child->GetName());
if (!icon)
return false;
csString bg(icon->orgRes);
btn->SetBackground(bg.GetData());
if (GetIcon(child->GetName())->IsActive)
{
bg = GetIcon(child->GetName())->orgRes;
bg += "_active";
btn->SetBackground(bg.GetData());
}
return true;
}
// When a new window registers make a new entry for them in our list.
void pawsControlWindow::Register( pawsControlledWindow* window )
{
Icon * icon = new Icon;
icon->window = window;
icon->theirButton = FindButtonFromWindow( window->GetName() );
if( icon->theirButton==NULL )
{
Error2("pawsControlWindow::Register couldn't find window %s!", window->GetName() );
delete icon;
return;
}
icon->orgRes = icon->theirButton->GetBackground();
icon->IsActive = false;
icon->IsOver = false;
buttons.Push( icon );
}
void pawsControlWindow::AddWindow(csString wndName, csString btnName)
{
WBName newName;
pawsButton* btn = (pawsButton*)FindWidget(btnName.GetData());
if (!btn)
{
Error2("Couldn't find button %s!", btnName.GetData());
return;
}
newName.buttonName = btnName;
newName.windowName = wndName;
newName.id = btn->GetID();
wbs.Push(newName);
}
pawsControlledWindow* pawsControlWindow::FindWindowFromButton(csString btnName)
{
for (size_t x = 0; x < wbs.GetSize(); x++ )
{
if ( wbs[x].buttonName == btnName )
{
pawsWidget* wdg = PawsManager::GetSingleton().FindWidget(wbs[x].windowName.GetData());
if (!wdg)
{
Error2("Found %s but FindWidget returned null!", btnName.GetData());
return NULL;
}
return (pawsControlledWindow*)wdg;
}
}
return NULL;
}
pawsButton* pawsControlWindow::FindButtonFromWindow(csString wndName)
{
for (size_t x = 0; x < wbs.GetSize(); x++ )
{
if ( wbs[x].windowName == wndName )
{
pawsWidget* wdg = FindWidget(wbs[x].buttonName.GetData());
if (!wdg)
{
Error2("Couldn't find window %s!", wndName.GetData());
return NULL;
}
return (pawsButton*)wdg;
}
}
return NULL;
}
Icon* pawsControlWindow::GetIcon(csString btnName)
{
for (size_t x = 0; x < buttons.GetSize(); x++ )
{
if ( !strcmp(buttons[x]->theirButton->GetName(), btnName.GetData()) )
{
return buttons[x];
}
}
return NULL;
}
//This is called everytime a window that has a button opens
void pawsControlWindow::WindowOpen(pawsWidget* wnd)
{
pawsButton* btn = FindButtonFromWindow(wnd->GetName());
Icon* icon = GetIcon(btn->GetName());
icon->IsActive = true;
csString bg(icon->orgRes);
bg += "_active";
btn->SetBackground(bg.GetData());
}
//This is called everytime a window that has a button closes
void pawsControlWindow::WindowClose(pawsWidget* wnd)
{
pawsButton* btn = FindButtonFromWindow(wnd->GetName());
Icon* icon = GetIcon(btn->GetName());
icon->IsActive = false;
btn->SetBackground(icon->orgRes.GetData());
}
void pawsControlWindow::NextStyle()
{
// We load it each time to make the user able to change the style without the need to
// restart the client
//Increase style
style++;
csString filename;
filename = PawsManager::GetSingleton().GetLocalization()->FindLocalizedFile("control_styles.xml");
if (!psengine->GetVFS()->Exists(filename.GetData()))
{
Error2( "Could not find XML: %s", filename.GetData());
return;
}
csRef<iDocument> doc = ParseFile(psengine->GetObjectRegistry(),filename.GetData());
if (!doc)
{
Error2("Error parsing file %s", filename.GetData());
return;
}
csString topNodestr("style");
topNodestr += style;
csRef<iDocumentNode> root = doc->GetRoot();
if (!root)
{
Error2("No XML root in %s", filename.GetData());
return;
}
csRef<iDocumentNode> topNode = root->GetNode(topNodestr.GetData());
//If "style"+style doesn't exist, jump to start
if (!topNode)
{
if (style == 1) //No styles at all :(
return;
style=0;
NextStyle();
return;
}
csRef<iDocumentNodeIterator> iter = topNode->GetNodes();
//Loop through the XML
int bwidth=52, bheight=52, mwidth=16, mheight=16;
float xscale=1.0f, yscale=1.0f;
// get the current width and height of the buttons (should be the same for all)
pawsButton* btn = (pawsButton*)FindWidget("QuitButton");
int boldwidth = btn->ClipRect().Width();
int boldheight = btn->ClipRect().Height();
while ( iter->HasNext() )
{
csRef<iDocumentNode> node = iter->Next();
if (!strcmp(node->GetValue(),"button"))
{
int x = GetActualWidth(node->GetAttributeValueAsInt("x"));
int y = GetActualHeight(node->GetAttributeValueAsInt("y"));
csString name = node->GetAttributeValue("name");
pawsWidget* wdg = FindWidget(name.GetData());
if (!wdg)
{
Error2("No such widget as %s!", name.GetData());
continue;
}
wdg->SetSize(bwidth, bheight);
wdg->SetRelativeFramePos(x, y);
}
else if (!strcmp(node->GetValue(),"buttons"))
{
bwidth = GetActualWidth(node->GetAttributeValueAsInt("width"));
bheight = GetActualHeight(node->GetAttributeValueAsInt("height"));
mwidth = GetActualWidth(node->GetAttributeValueAsInt("hide_width"));
mheight = GetActualHeight(node->GetAttributeValueAsInt("hide_height"));
// get the multiplier for the button and the widget size
if (boldwidth != 0 && boldheight != 0)
{
xscale = float(boldwidth) / float(bwidth);
yscale = float(boldheight) / float(bheight);
}
}
else if (!strcmp(node->GetValue(), "bar"))
{
orgw = GetActualWidth(node->GetAttributeValueAsInt("width"));
orgh = GetActualWidth(node->GetAttributeValueAsInt("height"));
SetRelativeFrameSize(orgw, orgh);
min_width = GetActualWidth(node->GetAttributeValueAsInt("min_w"));
min_height = GetActualWidth(node->GetAttributeValueAsInt("min_h"));
alwaysResize = node->GetAttributeValueAsBool("always_resize", true);
SetResizeShow(alwaysResize);
}
}
/* Resize the widget according to the proportions of the previous style.
*
* When the new styles dimensions exceeds its max it will be downsized to fit.
* See: pawsWidget::Resize(int deltaX, int deltaY, int flags)
*/
Resize( int(xscale*orgw-orgw), int(yscale*orgh-orgh), RESIZE_RIGHT | RESIZE_BOTTOM );
// Set the minimize buttons size
pawsButton* minUp = (pawsButton*)FindWidget("ShowButtonUp");
minUp->SetSize(mwidth,mheight);
pawsButton* minDown = (pawsButton*)FindWidget("ShowButtonDown");
minDown->SetSize(mwidth,mheight);
}
void pawsControlWindow::Hide()
{
if (!hidden)
Toggle();
}
void pawsControlWindow::Show()
{
if (hidden)
Toggle();
pawsWidget::Show();
}
bool pawsControlWindow::Contains( int x, int y )
{
if(!pawsWidget::Contains(x, y))
return false;
// Special case of a resize border
if(keyboard->GetKeyState(CSKEY_SHIFT) || (ResizeFlags(x,y) && showResize) || alwaysResize)
return true;
// Typical case, this window is transparent
for (size_t z = 0; z < children.GetSize(); z++ )
{
if (children[z]->IsVisible() )
{
if ( children[z]->Contains(x,y) )
return true;
}
}
return false;
}
|
2d51f28ffd1005e1bd9ea2aade46cbbbe057f58a | 86229a4a89c0694fbf10952f02831a7c0c968da3 | /dev/sql.h | 080565d8702dde0836ccaf86389b5199e2de48b7 | [] | no_license | ggipson2/seniorcap | ba0852a750e4523f81d33b6f98629ea4102a6c80 | 19666cb5bc003933c73c334773866f79671c6131 | refs/heads/master | 2021-01-21T08:25:09.335496 | 2015-05-13T00:20:52 | 2015-05-13T00:20:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,268 | h | sql.h | /*******************************************************************************
File Name: sql.h
Author: Grant Gipson
Date Last Edited: May 14, 2011
Description: Function prototypes for database access
*******************************************************************************/
#ifndef _SQL_H_
#define _SQL_H_
#include <mysql_driver.h>
#include <mysql_connection.h>
#include <cppconn/exception.h>
#include <cppconn/prepared_statement.h>
#include <list>
#include <string>
using namespace std;
using namespace sql;
struct ContentRec {
unsigned id;
string title;
};
extern Connection* sqlconn;
void dosql_archive_insert(const int user_id, list<string>& body);
bool dosql_archive_select(unsigned& archive_id, int& user_id,
list<ContentRec>& content);
void dosql_archive_finish(const unsigned archive_id);
void dosql_content_delete(list<string>& body);
void dosql_content_rename(list<string>& body);
bool dosql_content_insert(list<string>& body, int user_id, string& filename, unsigned& content_id);
void dosql_job_insert(const int user_id, list<string>& body);
bool dosql_job_select(unsigned& job_id, int& user_id, string& type, string& url);
void dosql_job_failed(const int job_id);
void dosql_job_finish(const int job_id);
#endif /* _SQL_H_ */
|
321100ef5fe98b0970b01f21d7804a5a82d78927 | 3e3fd47e5955d98f9657dc52ced1ec6aa1571a03 | /worker/include/RTC/RTCP/XrDelaySinceLastRr.hpp | b2a7ec2c8814c16f32694829fdc460dcccbfb825 | [
"ISC"
] | permissive | versatica/mediasoup | f9de556f16d81694e6d776ec2ed9c7d6633c6fee | d6d5fcc9f98a42a5e2f38bd4faaafcbd77960df7 | refs/heads/v3 | 2023-09-01T17:39:26.877961 | 2023-08-30T17:24:33 | 2023-08-30T17:24:33 | 27,918,697 | 5,654 | 1,141 | ISC | 2023-09-14T15:32:28 | 2014-12-12T12:00:36 | C++ | UTF-8 | C++ | false | false | 3,857 | hpp | XrDelaySinceLastRr.hpp | #ifndef MS_RTC_RTCP_XR_DELAY_SINCE_LAST_RR_HPP
#define MS_RTC_RTCP_XR_DELAY_SINCE_LAST_RR_HPP
#include "common.hpp"
#include "RTC/RTCP/XR.hpp"
/* https://tools.ietf.org/html/rfc3611
* Delay Since Last Receiver Report (DLRR) Report Block
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| BT=5 | reserved | block length |
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
| SSRC_1 (SSRC of first receiver) | sub-
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ block
| last RR (LRR) | 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| delay since last RR (DLRR) |
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
| SSRC_2 (SSRC of second receiver) | sub-
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ block
: ... : 2
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
*/
namespace RTC
{
namespace RTCP
{
class DelaySinceLastRr : public ExtendedReportBlock
{
public:
static DelaySinceLastRr* Parse(const uint8_t* data, size_t len);
public:
class SsrcInfo
{
public:
static const size_t BodySize{ 12 };
static SsrcInfo* Parse(const uint8_t* data, size_t len);
public:
struct Body
{
uint32_t ssrc;
uint32_t lrr;
uint32_t dlrr;
};
public:
// Locally generated Report. Holds the data internally.
SsrcInfo()
{
this->body = reinterpret_cast<Body*>(this->raw);
}
// Parsed Report. Points to an external data.
explicit SsrcInfo(Body* body) : body(body)
{
}
void Dump() const;
size_t Serialize(uint8_t* buffer);
size_t GetSize() const
{
return BodySize;
}
uint32_t GetSsrc() const
{
return uint32_t{ ntohl(this->body->ssrc) };
}
void SetSsrc(uint32_t ssrc)
{
this->body->ssrc = uint32_t{ htonl(ssrc) };
}
uint32_t GetLastReceiverReport() const
{
return uint32_t{ ntohl(this->body->lrr) };
}
void SetLastReceiverReport(uint32_t lrr)
{
this->body->lrr = uint32_t{ htonl(lrr) };
}
uint32_t GetDelaySinceLastReceiverReport() const
{
return uint32_t{ ntohl(this->body->dlrr) };
}
void SetDelaySinceLastReceiverReport(uint32_t dlrr)
{
this->body->dlrr = uint32_t{ htonl(dlrr) };
}
private:
Body* body{ nullptr };
uint8_t raw[BodySize] = { 0 };
};
public:
using Iterator = std::vector<SsrcInfo*>::iterator;
public:
DelaySinceLastRr() : ExtendedReportBlock(ExtendedReportBlock::Type::DLRR)
{
}
explicit DelaySinceLastRr(CommonHeader* header)
: ExtendedReportBlock(ExtendedReportBlock::Type::DLRR)
{
this->header = header;
}
~DelaySinceLastRr()
{
for (auto* ssrcInfo : this->ssrcInfos)
{
delete ssrcInfo;
}
}
public:
void AddSsrcInfo(SsrcInfo* ssrcInfo)
{
this->ssrcInfos.push_back(ssrcInfo);
}
Iterator Begin()
{
return this->ssrcInfos.begin();
}
Iterator End()
{
return this->ssrcInfos.end();
}
/* Pure virtual methods inherited from ExtendedReportBlock. */
public:
virtual void Dump() const override;
virtual size_t Serialize(uint8_t* buffer) override;
virtual size_t GetSize() const override
{
size_t size{ 4u }; // Common header.
for (auto* ssrcInfo : this->ssrcInfos)
{
size += ssrcInfo->GetSize();
}
return size;
}
private:
std::vector<SsrcInfo*> ssrcInfos;
};
} // namespace RTCP
} // namespace RTC
#endif
|
7b6fc3ba8c728a8b225187a045b657a51b4d07f4 | 26309a202bfc2b61151555b926295e119a0f5d87 | /aibohp.cpp | 66e504fc835a36fd77118869c6dae51abcc6ead5 | [] | no_license | ClearSeve/Old-Codes | 7696ecb9816ac8c972ede66a88dc7a2a3ff3b3be | c2bc55bd94da84d404e6ed3be92b81ffcfbaa74f | refs/heads/master | 2023-03-18T17:13:36.472947 | 2014-10-19T15:19:06 | 2014-10-19T15:19:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 584 | cpp | aibohp.cpp | #include<iostream>
#include<cstdio>
#include<cstring>
char s[5005];
int dp[2000][2000];
#define min(a,b) (a>b?b:a)
int main()
{
int t;
for(scanf("%d",&t);t--;)
{
memset(dp, 0, sizeof dp);
scanf("%s",s);
int l = strlen(s);
for(int i = 1; i < l; i++)
for(int j = 0; j < l-i; j++)
{
if(s[ j ] == s[ i + j ])
dp[ i][ j ] = dp[ i ][ j + 1 ];
else
dp[i][ j ] = 1 + min(dp[i - 1][ j ], dp[ i - 1 ][ j + 1 ]);
}
printf("%d\n",dp[(l-1)][0]);
}
return 0;
}
/*dhayan rakhia
i&1 = 0 when i is even
i&1 = 1 when i is odd
*/
|
be2427906c95ae63c06bcf4cf9cce1b4f1a1c3a7 | 845937fa74a320967ff0f6447f7eedf17c1413cc | /include/ph/Opt/IdentifierFinder.h | 22813fdacdd8fce3695317fe1bbc40852cbedc72 | [
"WTFPL"
] | permissive | lijiansong/Phaeton | 2fa0f813fbeebd8bb188629df3f8f5b4f092206e | 3afcbdd8803eec7f009c7e9febd04c4f1aafee3b | refs/heads/master | 2021-07-10T20:25:52.730911 | 2020-09-04T04:47:08 | 2020-09-04T04:47:08 | 192,645,813 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,245 | h | IdentifierFinder.h | //==--- IdentifierFinder.h - Representation of Identifier expr finder ------==//
//
// The Phaeton Compiler Infrastructure
//
//===----------------------------------------------------------------------===//
//
// This file defines the class IdentifierFinder.
//
//===----------------------------------------------------------------------===//
#ifndef PHAETON_OPT_ID_FINDER_H
#define PHAETON_OPT_ID_FINDER_H
#include "ph/CodeGen/CodeGen.h"
#include "ph/Opt/TensorExprTree.h"
#include <string>
namespace phaeton {
/// IdentifierFinder - This pass works on the Identifier Expr. If the same
/// identifier appears on the LHS and the RHS of an assignment, but with
/// incompatible index structures, a temporary copy of the identifier is created
/// and used on the RHS.
class IdentifierFinder : public ExprTreeVisitor {
public:
IdentifierFinder(const ExpressionNode *root) : Root(root) {}
void visitChildren(const ExpressionNode *en) {
for (int i = 0; i < en->getNumChildren(); i++)
en->getChild(i)->visit(this);
}
virtual void visitIdentifierExpr(const IdentifierExpr *en) override {
if (en->getName() == NameToFind) {
Found = true;
// Note that if the identifiers expression seen so far are still
// compatible, set to 'Incompatible', i.e. we have to make sure that
// 'IdIncompatible' is never unset once it has been set to 'true'.
if (IdIncompatible == false)
IdIncompatible = Incompatible;
}
}
bool getIdIncompatible() const { return IdIncompatible; }
#define GEN_VISIT_COMPATIBLE_EXPR_NODE_IMPL(ExprName) \
virtual void visit##ExprName##Expr(const ExprName##Expr *en) override { \
visitChildren(en); \
}
GEN_VISIT_COMPATIBLE_EXPR_NODE_IMPL(Add)
GEN_VISIT_COMPATIBLE_EXPR_NODE_IMPL(Sub)
GEN_VISIT_COMPATIBLE_EXPR_NODE_IMPL(Mul)
GEN_VISIT_COMPATIBLE_EXPR_NODE_IMPL(ScalarMul)
GEN_VISIT_COMPATIBLE_EXPR_NODE_IMPL(Div)
GEN_VISIT_COMPATIBLE_EXPR_NODE_IMPL(ScalarDiv)
#undef GEN_VISIT_COMPATIBLE_EXPR_NODE_IMPL
#define GEN_VISIT_INCOMPATIBLE_EXPR_NODE_IMPL(ExprName) \
virtual void visit##ExprName##Expr(const ExprName##Expr *en) override { \
bool savedIncompatible = Incompatible; \
Incompatible = true; \
visitChildren(en); \
Incompatible = savedIncompatible; \
}
GEN_VISIT_INCOMPATIBLE_EXPR_NODE_IMPL(Product)
GEN_VISIT_INCOMPATIBLE_EXPR_NODE_IMPL(Stack)
GEN_VISIT_INCOMPATIBLE_EXPR_NODE_IMPL(Transposition)
GEN_VISIT_INCOMPATIBLE_EXPR_NODE_IMPL(Contraction)
#undef GEN_VISIT_INCOMPATIBLE_EXPR_NODE_IMPL
virtual bool find(const std::string nameToFind) {
NameToFind = nameToFind;
Found = false;
IdIncompatible = false;
Incompatible = false;
Root->visit(this);
return Found;
}
private:
const ExpressionNode *Root;
bool Incompatible;
std::string NameToFind;
bool Found;
bool IdIncompatible;
};
} // end namespace phaeton
#endif // PHAETON_OPT_ID_FINDER_H
|
20ad626714718bc11fa98730bfc1c38d24baedb0 | 1e97a97f123749f5cad346c542f259d0425be3d3 | /util/volleyball-mcsat.cpp | a41f11a4efb2555c070ae37f480b3eaa3499890f | [
"MIT"
] | permissive | waldow90/repel-2 | 3c6b8f63c507d3f790e93ad31bcd7c02ee6fcbcd | e45c40dee951eb7365d5cc9dd827fb270508222c | refs/heads/master | 2021-05-28T01:46:00.809333 | 2012-08-12T00:27:05 | 2012-08-12T00:27:05 | 280,900,091 | 0 | 1 | MIT | 2020-07-19T15:58:43 | 2020-07-19T15:58:42 | null | UTF-8 | C++ | false | false | 27,265 | cpp | volleyball-mcsat.cpp | /*
* volleyball-mcsat.cpp
*
* Created on: Jun 1, 2012
* Author: selman.joe@gmail.com
*/
#include <boost/random.hpp>
#include <boost/program_options.hpp>
#include <boost/iostreams/filtering_stream.hpp>
//#include <boost/iostreams/filter/zlib.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <stdexcept>
#include <iostream>
#include <fstream>
#include "../src/logic/ELSyntax.h"
#include "../src/inference/MCSat.h"
#include "../src/AllSerializationExports.h"
#include "../test/TestUtilities.h" // <-- TODO: shouldn't be needed here
namespace po = boost::program_options;
namespace io = boost::iostreams;
int analyzeOutput(const std::string& filename) {
MCSat solver;
{
io::file_descriptor_source inFile(filename.c_str(), std::ios_base::in | std::ios_base::binary);
if (!inFile.is_open()) {
std::cerr << "unable to open file " + filename + " for model reading" << std::endl;
return EXIT_FAILURE;
} else {
io::filtering_istream dataIn;
dataIn.push(io::gzip_decompressor());
dataIn.push(inFile);
boost::archive::text_iarchive tin(dataIn);
registerAllPELTypes(tin);
tin >> solver;
}
}
std::cout << "number of samples: " << solver.numSamples() << std::endl;
boost::shared_ptr<Sentence> ballContactS = getAsSentence("BallContact(them)");
Proposition ballContactProp(static_cast<const Atom&>(*ballContactS), true);
std::cout << "counts:" << std::endl;
Interval maxInterval = solver.domain()->maxInterval();
unsigned int counts[maxInterval.finish() - maxInterval.start() + 1];
for (unsigned int j = maxInterval.start(); j <= maxInterval.finish(); j++) {
counts[j] = solver.countProps(ballContactProp, Interval(j,j));
std::cout << counts[j];
if (j != maxInterval.finish()) std::cout << ", ";
}
std::cout << std::endl;
return EXIT_SUCCESS;
}
int main(int argc, char* argv[]) {
// build the variable map from our configuration
po::options_description options("Allowed options");
options.add_options()
("help", "this message")
("disable-up", "disable unit propagation")
("analyze", po::value<std::string>(), "analyse previously-generated output")
("seed", po::value<unsigned int>(), "rng seed")
("name", po::value<std::string>(), "job name (used for file naming)");
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(options).run(), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << "Usage: volleyball-mcsat [OPTION]..." << std::endl;
std::cout << options << std::endl;
return EXIT_FAILURE;
}
if (vm.count("analyze")) {
return analyzeOutput(vm["analyze"].as<std::string>());
}
boost::mt19937 rng;
if (vm.count("rng")) {
rng.seed(vm["rng"].as<unsigned int>());
} else {
rng.seed((time(NULL) * 32)^getpid());
}
// disable debug logging
FileLog::globalLogLevel() = LOG_ERROR;
std::string facts("# Video002.mat\n"
"# BackLeft\n"
"D-Squat(backleft) @ [1:133]\n"
"\n"
"# BackMiddle\n"
"D-Squat(backmiddle) @ [1:133]\n"
"D-Squat(backmiddle) @ [156:164]\n"
"D-Squat(backmiddle) @ [329:352]\n"
"\n"
"# BackRight\n"
"D-Squat(backright) @ [1:31]\n"
"D-Squat(backright) @ [71:122]\n"
"D-Squat(backright) @ [303:327]\n"
"\n"
"# FrontLeft\n"
"D-Spike(frontleft) @ [377:393]\n"
"D-Block(frontleft) @ [214:224]\n"
"D-Squat(frontleft) @ [1:136]\n"
"\n"
"# FrontMiddle\n"
"D-Spike(frontmiddle) @ [223:238]\n"
"D-Spike(frontmiddle) @ [409:423]\n"
"D-Block(frontmiddle) @ [304:319]\n"
"D-Squat(frontmiddle) @ [23:116]\n"
"\n"
"# FrontRight\n"
"D-Set(frontright) @ [199:209]\n"
"D-Set(frontright) @ [365:389]\n"
"D-Squat(frontright) @ [43:117]\n"
"\n"
"# RefNet\n"
"D-Flag(refnet) @ [462:541]\n"
"\n"
"# RefBack\n"
"D-Flag(refback) @ [451:541]\n"
"\n"
"# Group\n"
"D-Huddle() @ [484:541]\n"
"\n"
"# Ball\n"
"D-BallTrajectory() @ [113:153]\n"
"D-BallTrajectory() @ [159:164]\n"
"D-BallTrajectory() @ [173:228]\n"
"D-BallTrajectory() @ [307:312]\n"
"D-BallTrajectory() @ [322:337]\n"
"D-BallTrajectory() @ [341:381]\n"
"D-BallTrajectory() @ [387:392]\n"
"D-BallTrajectory() @ [421:436]\n"
"\n"
"D-BallGoingOut() @ [270:270]\n"
"D-BallGoingOut() @ [393:393]\n"
"\n"
"D-BallGoingin() @ [303:303]\n"
"D-BallGoingin() @ [412:412]\n"
"\n"
"D-BallContact(frontleft) @ [233:233]\n"
"D-BallContact(frontleft) @ [419:419]\n"
"\n"
"D-BallContact(frontright) @ [201:201]\n"
"D-BallContact(frontright) @ [382:382]\n"
"\n"
"D-BallContact(backleft) @ [163:163]\n"
"D-BallContact(backleft) @ [344:344]\n"
"\n"
"D-BallContact(them) @ [108:108]\n"
"D-BallContact(them) @ [127:127]\n"
"D-BallContact(them) @ [244:244]\n"
"D-BallContact(them) @ [260:260]\n"
"D-BallContact(them) @ [310:310]\n"
"D-BallContact(them) @ [425:425]\n"
"D-BallContact(them) @ [441:441]\n"
"\n"
);
std::string formulas("1: [ D-BallContact(backleft) -> BallContact(backleft) ]\n"
"1: [ D-BallContact(backright) -> BallContact(backright) ]\n"
"1: [ D-BallContact(backmiddle) -> BallContact(backmiddle) ]\n"
"1: [ D-BallContact(frontleft) -> BallContact(frontleft) ]\n"
"1: [ D-BallContact(frontright) -> BallContact(frontright) ]\n"
"1: [ D-BallContact(frontmiddle) -> BallContact(frontmiddle) ]\n"
"1: [ BallContact(backleft) -> D-BallContact(backleft) ]\n"
"1: [ BallContact(backright) -> D-BallContact(backright) ]\n"
"1: [ BallContact(backmiddle) -> D-BallContact(backmiddle) ]\n"
"1: [ BallContact(frontleft) -> D-BallContact(frontleft) ]\n"
"1: [ BallContact(frontright) -> D-BallContact(frontright) ]\n"
"1: [ BallContact(frontmiddle) -> D-BallContact(frontmiddle) ]\n"
"1: [ D-Spike(backleft) -> Spike(backleft) ]\n"
"1: [ D-Spike(backright) -> Spike(backright) ]\n"
"1: [ D-Spike(backmiddle) -> Spike(backmiddle) ]\n"
"1: [ D-Spike(frontleft) -> Spike(frontleft) ]\n"
"1: [ D-Spike(frontright) -> Spike(frontright) ]\n"
"1: [ D-Spike(frontmiddle) -> Spike(frontmiddle) ]\n"
"1: [ Spike(backleft) -> D-Spike(backleft) ]\n"
"1: [ Spike(backright) -> D-Spike(backright) ]\n"
"1: [ Spike(backmiddle) -> D-Spike(backmiddle) ]\n"
"1: [ Spike(frontleft) -> D-Spike(frontleft) ]\n"
"1: [ Spike(frontright) -> D-Spike(frontright) ]\n"
"1: [ Spike(frontmiddle) -> D-Spike(frontmiddle) ]\n"
"1: [ D-Set(backleft) -> Set(backleft) ]\n"
"1: [ D-Set(backright) -> Set(backright) ]\n"
"1: [ D-Set(backmiddle) -> Set(backmiddle) ]\n"
"1: [ D-Set(frontleft) -> Set(frontleft) ]\n"
"1: [ D-Set(frontright) -> Set(frontright) ]\n"
"1: [ D-Set(frontmiddle) -> Set(frontmiddle) ]\n"
"1: [ Set(backleft) -> D-Set(backleft) ]\n"
"1: [ Set(backright) -> D-Set(backright) ]\n"
"1: [ Set(backmiddle) -> D-Set(backmiddle) ]\n"
"1: [ Set(frontleft) -> D-Set(frontleft) ]\n"
"1: [ Set(frontright) -> D-Set(frontright) ]\n"
"1: [ Set(frontmiddle) -> D-Set(frontmiddle) ]\n"
"1: [ D-Serve(backleft) -> Serve(backleft) ]\n"
"1: [ D-Serve(backright) -> Serve(backright) ]\n"
"1: [ D-Serve(backmiddle) -> Serve(backmiddle) ]\n"
"1: [ D-Serve(frontleft) -> Serve(frontleft) ]\n"
"1: [ D-Serve(frontright) -> Serve(frontright) ]\n"
"1: [ D-Serve(frontmiddle) -> Serve(frontmiddle) ]\n"
"1: [ Serve(backleft) -> D-Serve(backleft) ]\n"
"1: [ Serve(backright) -> D-Serve(backright) ]\n"
"1: [ Serve(backmiddle) -> D-Serve(backmiddle) ]\n"
"1: [ Serve(frontleft) -> D-Serve(frontleft) ]\n"
"1: [ Serve(frontright) -> D-Serve(frontright) ]\n"
"1: [ Serve(frontmiddle) -> D-Serve(frontmiddle) ]\n"
"1: [ D-Dig(backleft) -> Dig(backleft) ]\n"
"1: [ D-Dig(backright) -> Dig(backright) ]\n"
"1: [ D-Dig(backmiddle) -> Dig(backmiddle) ]\n"
"1: [ D-Dig(frontleft) -> Dig(frontleft) ]\n"
"1: [ D-Dig(frontright) -> Dig(frontright) ]\n"
"1: [ D-Dig(frontmiddle) -> Dig(frontmiddle) ]\n"
"1: [ Dig(backleft) -> D-Dig(backleft) ]\n"
"1: [ Dig(backright) -> D-Dig(backright) ]\n"
"1: [ Dig(backmiddle) -> D-Dig(backmiddle) ]\n"
"1: [ Dig(frontleft) -> D-Dig(frontleft) ]\n"
"1: [ Dig(frontright) -> D-Dig(frontright) ]\n"
"1: [ Dig(frontmiddle) -> D-Dig(frontmiddle) ]\n"
"1: [ D-Block(backleft) -> Block(backleft) ]\n"
"1: [ D-Block(backright) -> Block(backright) ]\n"
"1: [ D-Block(backmiddle) -> Block(backmiddle) ]\n"
"1: [ D-Block(frontleft) -> Block(frontleft) ]\n"
"1: [ D-Block(frontright) -> Block(frontright) ]\n"
"1: [ D-Block(frontmiddle) -> Block(frontmiddle) ]\n"
"1: [ Block(backleft) -> D-Block(backleft) ]\n"
"1: [ Block(backright) -> D-Block(backright) ]\n"
"1: [ Block(backmiddle) -> D-Block(backmiddle) ]\n"
"1: [ Block(frontleft) -> D-Block(frontleft) ]\n"
"1: [ Block(frontright) -> D-Block(frontright) ]\n"
"1: [ Block(frontmiddle) -> D-Block(frontmiddle) ]\n"
"1: [ D-Squat(backleft) -> Squat(backleft) ]\n"
"1: [ D-Squat(backright) -> Squat(backright) ]\n"
"1: [ D-Squat(backmiddle) -> Squat(backmiddle) ]\n"
"1: [ D-Squat(frontleft) -> Squat(frontleft) ]\n"
"1: [ D-Squat(frontright) -> Squat(frontright) ]\n"
"1: [ D-Squat(frontmiddle) -> Squat(frontmiddle) ]\n"
"1: [ Squat(backleft) -> D-Squat(backleft) ]\n"
"1: [ Squat(backright) -> D-Squat(backright) ]\n"
"1: [ Squat(backmiddle) -> D-Squat(backmiddle) ]\n"
"1: [ Squat(frontleft) -> D-Squat(frontleft) ]\n"
"1: [ Squat(frontright) -> D-Squat(frontright) ]\n"
"1: [ Squat(frontmiddle) -> D-Squat(frontmiddle) ]\n"
"1: [ D-Flag(refback) -> Flag(refback) ]\n"
"1: [ Flag(refback) -> D-Flag(refback) ]\n"
"1: [ D-Flag(refnet) -> Flag(refnet) ]\n"
"1: [ Flag(refnet) -> D-Flag(refnet) ]\n"
"1: [ D-BallContact(them) -> BallContact(them) ]\n"
"1: [ BallContact(them) -> D-BallContact(them) ]\n"
"1: [ D-Huddle() -> Huddle() ]\n"
"1: [ Huddle() -> D-Huddle() ]\n"
"1: [ D-BallTrajectory() -> BallTrajectory() ]\n"
"1: [ BallTrajectory() -> D-BallTrajectory() ]\n"
"1: [ D-BallGoingOut() -> BallGoingOut() ]\n"
"1: [ BallGoingOut() -> D-BallGoingOut() ]\n"
"1: [ D-BallGoingIn() -> BallGoingIn() ]\n"
"1: [ BallGoingIn() -> D-BallGoingIn() ]\n"
"1: [ D-BallGoingin() -> BallGoingin() ]\n"
"1: [ BallGoingin() -> D-BallGoingin() ]\n"
"\n"
"# a player can have at most one pose at a time\n"
"10: [ (Spike(backleft) ^ !Set(backleft) ^ !Serve(backleft) ^ !Dig(backleft) ^ !Block(backleft) ^ !Squat(backleft)) v (!Spike(backleft) ^ Set(backleft) ^ !Serve(backleft) ^ !Dig(backleft) ^ !Block(backleft) ^ !Squat(backleft)) v (!Spike(backleft) ^ !Set(backleft) ^ Serve(backleft) ^ !Dig(backleft) ^ !Block(backleft) ^ !Squat(backleft)) v (!Spike(backleft) ^ !Set(backleft) ^ !Serve(backleft) ^ Dig(backleft) ^ !Block(backleft) ^ !Squat(backleft)) v (!Spike(backleft) ^ !Set(backleft) ^ !Serve(backleft) ^ !Dig(backleft) ^ Block(backleft) ^ !Squat(backleft)) v (!Spike(backleft) ^ !Set(backleft) ^ !Serve(backleft) ^ !Dig(backleft) ^ !Block(backleft) ^ Squat(backleft)) v (!Spike(backleft) ^ !Set(backleft) ^ !Serve(backleft) ^ !Dig(backleft) ^ !Block(backleft) ^ !Squat(backleft)) ]\n"
"10: [ (Spike(backright) ^ !Set(backright) ^ !Serve(backright) ^ !Dig(backright) ^ !Block(backright) ^ !Squat(backright)) v (!Spike(backright) ^ Set(backright) ^ !Serve(backright) ^ !Dig(backright) ^ !Block(backright) ^ !Squat(backright)) v (!Spike(backright) ^ !Set(backright) ^ Serve(backright) ^ !Dig(backright) ^ !Block(backright) ^ !Squat(backright)) v (!Spike(backright) ^ !Set(backright) ^ !Serve(backright) ^ Dig(backright) ^ !Block(backright) ^ !Squat(backright)) v (!Spike(backright) ^ !Set(backright) ^ !Serve(backright) ^ !Dig(backright) ^ Block(backright) ^ !Squat(backright)) v (!Spike(backright) ^ !Set(backright) ^ !Serve(backright) ^ !Dig(backright) ^ !Block(backright) ^ Squat(backright)) v (!Spike(backright) ^ !Set(backright) ^ !Serve(backright) ^ !Dig(backright) ^ !Block(backright) ^ !Squat(backright)) ]\n"
"10: [ (Spike(backmiddle) ^ !Set(backmiddle) ^ !Serve(backmiddle) ^ !Dig(backmiddle) ^ !Block(backmiddle) ^ !Squat(backmiddle)) v (!Spike(backmiddle) ^ Set(backmiddle) ^ !Serve(backmiddle) ^ !Dig(backmiddle) ^ !Block(backmiddle) ^ !Squat(backmiddle)) v (!Spike(backmiddle) ^ !Set(backmiddle) ^ Serve(backmiddle) ^ !Dig(backmiddle) ^ !Block(backmiddle) ^ !Squat(backmiddle)) v (!Spike(backmiddle) ^ !Set(backmiddle) ^ !Serve(backmiddle) ^ Dig(backmiddle) ^ !Block(backmiddle) ^ !Squat(backmiddle)) v (!Spike(backmiddle) ^ !Set(backmiddle) ^ !Serve(backmiddle) ^ !Dig(backmiddle) ^ Block(backmiddle) ^ !Squat(backmiddle)) v (!Spike(backmiddle) ^ !Set(backmiddle) ^ !Serve(backmiddle) ^ !Dig(backmiddle) ^ !Block(backmiddle) ^ Squat(backmiddle)) v (!Spike(backmiddle) ^ !Set(backmiddle) ^ !Serve(backmiddle) ^ !Dig(backmiddle) ^ !Block(backmiddle) ^ !Squat(backmiddle)) ]\n"
"10: [ (Spike(frontleft) ^ !Set(frontleft) ^ !Serve(frontleft) ^ !Dig(frontleft) ^ !Block(frontleft) ^ !Squat(frontleft)) v (!Spike(frontleft) ^ Set(frontleft) ^ !Serve(frontleft) ^ !Dig(frontleft) ^ !Block(frontleft) ^ !Squat(frontleft)) v (!Spike(frontleft) ^ !Set(frontleft) ^ Serve(frontleft) ^ !Dig(frontleft) ^ !Block(frontleft) ^ !Squat(frontleft)) v (!Spike(frontleft) ^ !Set(frontleft) ^ !Serve(frontleft) ^ Dig(frontleft) ^ !Block(frontleft) ^ !Squat(frontleft)) v (!Spike(frontleft) ^ !Set(frontleft) ^ !Serve(frontleft) ^ !Dig(frontleft) ^ Block(frontleft) ^ !Squat(frontleft)) v (!Spike(frontleft) ^ !Set(frontleft) ^ !Serve(frontleft) ^ !Dig(frontleft) ^ !Block(frontleft) ^ Squat(frontleft)) v (!Spike(frontleft) ^ !Set(frontleft) ^ !Serve(frontleft) ^ !Dig(frontleft) ^ !Block(frontleft) ^ !Squat(frontleft)) ]\n"
"10: [ (Spike(frontright) ^ !Set(frontright) ^ !Serve(frontright) ^ !Dig(frontright) ^ !Block(frontright) ^ !Squat(frontright)) v (!Spike(frontright) ^ Set(frontright) ^ !Serve(frontright) ^ !Dig(frontright) ^ !Block(frontright) ^ !Squat(frontright)) v (!Spike(frontright) ^ !Set(frontright) ^ Serve(frontright) ^ !Dig(frontright) ^ !Block(frontright) ^ !Squat(frontright)) v (!Spike(frontright) ^ !Set(frontright) ^ !Serve(frontright) ^ Dig(frontright) ^ !Block(frontright) ^ !Squat(frontright)) v (!Spike(frontright) ^ !Set(frontright) ^ !Serve(frontright) ^ !Dig(frontright) ^ Block(frontright) ^ !Squat(frontright)) v (!Spike(frontright) ^ !Set(frontright) ^ !Serve(frontright) ^ !Dig(frontright) ^ !Block(frontright) ^ Squat(frontright)) v (!Spike(frontright) ^ !Set(frontright) ^ !Serve(frontright) ^ !Dig(frontright) ^ !Block(frontright) ^ !Squat(frontright)) ]\n"
"10: [ (Spike(frontmiddle) ^ !Set(frontmiddle) ^ !Serve(frontmiddle) ^ !Dig(frontmiddle) ^ !Block(frontmiddle) ^ !Squat(frontmiddle)) v (!Spike(frontmiddle) ^ Set(frontmiddle) ^ !Serve(frontmiddle) ^ !Dig(frontmiddle) ^ !Block(frontmiddle) ^ !Squat(frontmiddle)) v (!Spike(frontmiddle) ^ !Set(frontmiddle) ^ Serve(frontmiddle) ^ !Dig(frontmiddle) ^ !Block(frontmiddle) ^ !Squat(frontmiddle)) v (!Spike(frontmiddle) ^ !Set(frontmiddle) ^ !Serve(frontmiddle) ^ Dig(frontmiddle) ^ !Block(frontmiddle) ^ !Squat(frontmiddle)) v (!Spike(frontmiddle) ^ !Set(frontmiddle) ^ !Serve(frontmiddle) ^ !Dig(frontmiddle) ^ Block(frontmiddle) ^ !Squat(frontmiddle)) v (!Spike(frontmiddle) ^ !Set(frontmiddle) ^ !Serve(frontmiddle) ^ !Dig(frontmiddle) ^ !Block(frontmiddle) ^ Squat(frontmiddle)) v (!Spike(frontmiddle) ^ !Set(frontmiddle) ^ !Serve(frontmiddle) ^ !Dig(frontmiddle) ^ !Block(frontmiddle) ^ !Squat(frontmiddle)) ]\n"
"\n"
"# only one player can contact the ball at a time\n"
"10: [ BallContact(backleft) -> !BallContact(backright) ]\n"
"10: [ BallContact(backleft) -> !BallContact(backmiddle) ]\n"
"10: [ BallContact(backleft) -> !BallContact(frontleft) ]\n"
"10: [ BallContact(backleft) -> !BallContact(frontright) ]\n"
"10: [ BallContact(backleft) -> !BallContact(frontmiddle) ]\n"
"10: [ BallContact(backleft) -> !BallContact(them) ]\n"
"10: [ BallContact(backright) -> !BallContact(backleft) ]\n"
"10: [ BallContact(backright) -> !BallContact(backmiddle) ]\n"
"10: [ BallContact(backright) -> !BallContact(frontleft) ]\n"
"10: [ BallContact(backright) -> !BallContact(frontright) ]\n"
"10: [ BallContact(backright) -> !BallContact(frontmiddle) ]\n"
"10: [ BallContact(backright) -> !BallContact(them) ]\n"
"10: [ BallContact(backmiddle) -> !BallContact(backleft) ]\n"
"10: [ BallContact(backmiddle) -> !BallContact(backright) ]\n"
"10: [ BallContact(backmiddle) -> !BallContact(frontleft) ]\n"
"10: [ BallContact(backmiddle) -> !BallContact(frontright) ]\n"
"10: [ BallContact(backmiddle) -> !BallContact(frontmiddle) ]\n"
"10: [ BallContact(backmiddle) -> !BallContact(them) ]\n"
"10: [ BallContact(frontleft) -> !BallContact(backleft) ]\n"
"10: [ BallContact(frontleft) -> !BallContact(backright) ]\n"
"10: [ BallContact(frontleft) -> !BallContact(backmiddle) ]\n"
"10: [ BallContact(frontleft) -> !BallContact(frontright) ]\n"
"10: [ BallContact(frontleft) -> !BallContact(frontmiddle) ]\n"
"10: [ BallContact(frontleft) -> !BallContact(them) ]\n"
"10: [ BallContact(frontright) -> !BallContact(backleft) ]\n"
"10: [ BallContact(frontright) -> !BallContact(backright) ]\n"
"10: [ BallContact(frontright) -> !BallContact(backmiddle) ]\n"
"10: [ BallContact(frontright) -> !BallContact(frontleft) ]\n"
"10: [ BallContact(frontright) -> !BallContact(frontmiddle) ]\n"
"10: [ BallContact(frontright) -> !BallContact(them) ]\n"
"10: [ BallContact(frontmiddle) -> !BallContact(backleft) ]\n"
"10: [ BallContact(frontmiddle) -> !BallContact(backright) ]\n"
"10: [ BallContact(frontmiddle) -> !BallContact(backmiddle) ]\n"
"10: [ BallContact(frontmiddle) -> !BallContact(frontleft) ]\n"
"10: [ BallContact(frontmiddle) -> !BallContact(frontright) ]\n"
"10: [ BallContact(frontmiddle) -> !BallContact(them) ]\n"
"10: [ BallContact(them) -> !BallContact(backleft) ]\n"
"10: [ BallContact(them) -> !BallContact(backright) ]\n"
"10: [ BallContact(them) -> !BallContact(backmiddle) ]\n"
"10: [ BallContact(them) -> !BallContact(frontleft) ]\n"
"10: [ BallContact(them) -> !BallContact(frontright) ]\n"
"10: [ BallContact(them) -> !BallContact(frontmiddle) ]\n"
"\n"
// "# if the backleft player served, nobody posed before that action\n"
// "10: Serve(backleft) -> !(<>{<} [Spike(backleft) v Set(backleft) v Serve(backleft) v Dig(backleft) v Block(backleft) v Squat(backleft)])\n"
// "10: Serve(backleft) -> !(<>{<} [Spike(backright) v Set(backright) v Serve(backright) v Dig(backright) v Block(backright) v Squat(backright)])\n"
// "10: Serve(backleft) -> !(<>{<} [Spike(backmiddle) v Set(backmiddle) v Serve(backmiddle) v Dig(backmiddle) v Block(backmiddle) v Squat(backmiddle)])\n"
// "10: Serve(backleft) -> !(<>{<} [Spike(frontleft) v Set(frontleft) v Serve(frontleft) v Dig(frontleft) v Block(frontleft) v Squat(frontleft)])\n"
// "10: Serve(backleft) -> !(<>{<} [Spike(frontright) v Set(frontright) v Serve(frontright) v Dig(frontright) v Block(frontright) v Squat(frontright)])\n"
// "10: Serve(backleft) -> !(<>{<} [Spike(frontmiddle) v Set(frontmiddle) v Serve(frontmiddle) v Dig(frontmiddle) v Block(frontmiddle) v Squat(frontmiddle)])\n"
// "\n"
// "# if a huddle occurs, it\'s the final pose\n"
// "10: Huddle() -> !(<>{>} [Spike(backleft) v Set(backleft) v Serve(backleft) v Dig(backleft) v Block(backleft) v Squat(backleft)])\n"
// "10: Huddle() -> !(<>{>} [Spike(backright) v Set(backright) v Serve(backright) v Dig(backright) v Block(backright) v Squat(backright)])\n"
// "10: Huddle() -> !(<>{>} [Spike(backmiddle) v Set(backmiddle) v Serve(backmiddle) v Dig(backmiddle) v Block(backmiddle) v Squat(backmiddle)])\n"
// "10: Huddle() -> !(<>{>} [Spike(frontleft) v Set(frontleft) v Serve(frontleft) v Dig(frontleft) v Block(frontleft) v Squat(frontleft)])\n"
// "10: Huddle() -> !(<>{>} [Spike(frontright) v Set(frontright) v Serve(frontright) v Dig(frontright) v Block(frontright) v Squat(frontright)])\n"
// "10: Huddle() -> !(<>{>} [Spike(frontmiddle) v Set(frontmiddle) v Serve(frontmiddle) v Dig(frontmiddle) v Block(frontmiddle) v Squat(frontmiddle)])\n"
// "\n"
"# if a player contacts the ball, they are in some sort of pose\n"
"10: [ BallContact(backleft) -> Spike(backleft) v Set(backleft) v Serve(backleft) v Dig(backleft) v Block(backleft) v Squat(backleft) ]\n"
"10: [ BallContact(backright) -> Spike(backright) v Set(backright) v Serve(backright) v Dig(backright) v Block(backright) v Squat(backright) ]\n"
"10: [ BallContact(backmiddle) -> Spike(backmiddle) v Set(backmiddle) v Serve(backmiddle) v Dig(backmiddle) v Block(backmiddle) v Squat(backmiddle) ]\n"
"10: [ BallContact(frontleft) -> Spike(frontleft) v Set(frontleft) v Serve(frontleft) v Dig(frontleft) v Block(frontleft) v Squat(frontleft) ]\n"
"10: [ BallContact(frontright) -> Spike(frontright) v Set(frontright) v Serve(frontright) v Dig(frontright) v Block(frontright) v Squat(frontright) ]\n"
"10: [ BallContact(frontmiddle) -> Spike(frontmiddle) v Set(frontmiddle) v Serve(frontmiddle) v Dig(frontmiddle) v Block(frontmiddle) v Squat(frontmiddle) ]\n"
"\n"
// "# if a player served, nobody on our team will touch the ball before the opponents\n"
// "10: Serve(backleft) ^{<} BallContact(them) -> (<>{d} BallContact(them)) v (!<>{d} [BallContact(backright) v BallContact(backmiddle) v BallContact(frontleft) v BallContact(frontright) v BallContact(frontmiddle)])\n"
// "\n"
"# only the back left player may serve\n"
"10: [ !Serve(backright) ^ !Serve(backmiddle) ^ !Serve(frontleft) ^ !Serve(frontright) ^ !Serve(frontmiddle) ]\n"
"\n"
"# only players in the front row may spike\n"
"10: [ !Spike(backleft) ^ !Spike(backright) ^ !Spike(backmiddle) ]\n"
"\n"
);
Domain d = loadDomainWithStreams(facts, formulas);
std::set<unsigned int> timePoints;
for (Domain::fact_const_iterator it = d.facts_begin(); it != d.facts_end(); it++) {
SISet set = it->second;
for (SISet::const_iterator siIt = set.begin(); siIt != set.end(); siIt++) {
SpanInterval si = *siIt;
timePoints.insert(si.start().start());
timePoints.insert(si.start().finish());
timePoints.insert(si.finish().start());
timePoints.insert(si.finish().finish());
}
}
std::cout << "found " << timePoints.size() << " timepoints." << std::endl;
MCSat mcSatSolver(&d);
mcSatSolver.setBurnInIterations(1);
mcSatSolver.setNumSamples(1);
if (vm.count("disable-up")) {
mcSatSolver.setUseUnitPropagation(false);
} else {
mcSatSolver.setUseUnitPropagation(true);
}
std::cout << "running mcSatSolver with " << mcSatSolver.burnInIterations() << " burn in iterations and a sample size of " << mcSatSolver.numSamples() << std::endl;
std::string prefix = (vm.count("name") ? vm["name"].as<std::string>() : "mcsat-volleyball");
std::cout << "saving random seed..." << std::endl;
{
std::string rngFilename = prefix + "-seed.txt.gz";
io::file_descriptor_sink rngOutFile(rngFilename.c_str(), std::ios_base::out | std::ios_base::trunc | std::ios_base::binary);
if (!rngOutFile.is_open()){
std::cerr << "unable to open file " + rngFilename + "for RNG writing." << std::endl;
} else {
// gzip it using boost iostreams
io::filtering_ostream rngOut;
rngOut.push(io::gzip_compressor());
rngOut.push(rngOutFile);
rngOut << rng;
}
}
//std::cout << "rng = " << rng << std::endl;
std::cout << "starting run..." << std::endl;
mcSatSolver.setSampleStrategy(new MCSatSampleLiquidlyStrategy());
std::clock_t start = std::clock();
mcSatSolver.run(rng);
std::clock_t end = std::clock();
std::cout << "ran in " << (end - start)/CLOCKS_PER_SEC << " seconds." << std::endl;
std::cout << "saving model file..." << std::endl;
{
std::string outFilename = prefix + "-model.dat.gz";
io::file_descriptor_sink outFile(outFilename.c_str(), std::ios_base::out | std::ios_base::trunc | std::ios_base::binary);
if (!outFile.is_open()) {
std::cerr << "unable to open file " + outFilename + " for model writing." << std::endl;
} else {
io::filtering_ostream dataOut;
dataOut.push(io::gzip_compressor());
dataOut.push(outFile);
boost::archive::text_oarchive tout(dataOut);
registerAllPELTypes(tout);
tout << mcSatSolver;
}
}
}
|
48b5630e4c494f55dca0df0ebb45b567906fdc1b | 60e45951f7e82ae52c0d61c7804b5dd271e63e8d | /tests/json_dictionary.cpp | ca28df1401922dc12d2560a293045adb577acc02 | [
"MIT"
] | permissive | Koheiru/gts | 52be27aa959a2f3bdef695b98ea9982908fa60f1 | f708585a8f93597887cbc7f52eaafd18d3ef2147 | refs/heads/master | 2020-05-27T04:36:50.615955 | 2019-06-12T17:07:00 | 2019-06-12T17:07:00 | 188,485,600 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,446 | cpp | json_dictionary.cpp | #include <boost/property_tree/json_parser.hpp>
#include <gtest/gtest.h>
#include <gts/json.h>
// ----------------------------------------------------------------------------
template <class T>
class JsonDictionarySuite : public ::testing::Test
{
public:
JsonDictionarySuite() = default;
virtual ~JsonDictionarySuite() = default;
};
// ----------------------------------------------------------------------------
TYPED_TEST_SUITE_P(JsonDictionarySuite);
// ----------------------------------------------------------------------------
template <class C>
struct DictionaryHook;
template <template<class...> class C, class T, class ...Rest>
struct DictionaryHook<C<std::string, T, Rest...>>
{
template <class U>
using Container = C<std::string, U, Rest...>;
};
template <template<class...> class C, class T, class ...Rest>
struct DictionaryHook<C<std::pair<std::string, T>, Rest...>>
{
template <class U>
using Container = C<std::pair<std::string, U>, Rest...>;
};
// ----------------------------------------------------------------------------
static std::string FormatPtree(const boost::property_tree::ptree& tree)
{
std::stringstream stream;
boost::property_tree::write_json(stream, tree, false);
return stream.str();
}
// ----------------------------------------------------------------------------
template <class Container>
static boost::property_tree::ptree SerializeByBoost(const Container& items)
{
boost::property_tree::ptree tree;
for (const auto& item : items)
{
boost::property_tree::ptree child{};
child.put_value(item.second);
tree.push_back(std::make_pair(item.first, child));
}
return tree;
}
// ----------------------------------------------------------------------------
template <class T>
static bool CheckT()
{
return true;
}
// ----------------------------------------------------------------------------
template <class Container>
static boost::property_tree::ptree SerializeByGts(const Container& items)
{
using meta_type = typename gts::meta_type<Container>::value;
const auto isChecked = CheckT<meta_type>();
using serializer = typename gts::json<meta_type>;
const auto tree = serializer::serialize(items, boost::property_tree::ptree{});
return tree;
}
// ----------------------------------------------------------------------------
TYPED_TEST_P(JsonDictionarySuite, SerializeStrings)
{
using Container = DictionaryHook<TypeParam>::Container<std::string>;
const Container items({
{ std::string("first"), std::string("one") },
{ std::string("second"), std::string("two and three") },
{ std::string("third"), std::string(" four ") } });
const auto text = FormatPtree(SerializeByGts(items));
std::cout << "JSON: " << text << std::endl;
EXPECT_EQ(text, "{\"first\":\"one\",\"second\":\"two and three\",\"third\":\" four \"}\n");
}
// ----------------------------------------------------------------------------
TYPED_TEST_P(JsonDictionarySuite, SerializeDictionaries)
{
using Dictionary = std::map<std::string, std::string>;
using Container = DictionaryHook<TypeParam>::Container<Dictionary>;
const Container items({
{ std::string("first"),
Dictionary({ { std::string("one"), std::string("1") } }) },
{ std::string("second"),
Dictionary({ { std::string("two and three"), std::string("2 & 3") } }) },
{ std::string("third"),
Dictionary({ { std::string("four"), std::string("4") } }) },
});
const auto text = FormatPtree(SerializeByGts(items));
std::cout << "JSON: " << text << std::endl;
EXPECT_EQ(text, "{\"first\":{\"one\":\"1\"},\"second\":{\"two and three\":\"2 & 3\"},\"third\":{\"four\":\"4\"}}\n");
}
// ----------------------------------------------------------------------------
REGISTER_TYPED_TEST_SUITE_P(JsonDictionarySuite,
SerializeStrings,
SerializeDictionaries);
// ----------------------------------------------------------------------------
struct tag {};
using Containers = ::testing::Types<
std::map<std::string, tag>, std::multimap<std::string, tag>, std::unordered_map<std::string, tag>,
std::vector<std::pair<std::string, tag>>, std::deque<std::pair<std::string, tag>>, std::list<std::pair<std::string, tag>>, std::forward_list<std::pair<std::string, tag>>>;
INSTANTIATE_TYPED_TEST_SUITE_P(My, JsonDictionarySuite, Containers);
|
6a6d9bbf10614342188d4bfd4c7c02c2eaa72ad1 | f76ea88828f9598ad53a8bd2d2b39e0c62bae17b | /src/moon9/render/atlas/atlas.hpp | ec38949d7e2eac713aa4febf31684afa6fd8275b | [
"LicenseRef-scancode-warranty-disclaimer",
"Zlib",
"MIT"
] | permissive | xingjilin/moon9 | 61c7c3cbb8b85d5587b020d311355404283c599d | d4e1255b1517744e0e74dc05d5967aba7fdcbe4f | refs/heads/master | 2020-05-01T03:08:37.991393 | 2015-05-10T15:32:12 | 2015-05-10T15:32:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 103 | hpp | atlas.hpp | #pragma once
#include "texture/texture.hpp"
namespace moon9
{
typedef moon9::texturemap atlas;
}
|
56cbe0e318f2220173293b2716ff5becbb75a377 | 386025f7751e3b7c9a4442aea936410e89f0bb78 | /confirmcalculator.h | ec314060d3781df39c4d919609c0b29054c33184 | [] | no_license | ArtemHodeev/Gidrolog | cdb741b501a9655541fe959d5234eba7058c10aa | ec5cb800d34058e578e95bccfa71c3dc499c9e6b | refs/heads/master | 2020-04-27T20:35:06.142336 | 2014-06-24T12:13:42 | 2014-06-24T12:13:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 684 | h | confirmcalculator.h | #ifndef CONFIRMCALCULATOR_H
#define CONFIRMCALCULATOR_H
#include <QDialog>
#include <confirmcalculatormodel.h>
#include <QItemSelectionModel>
namespace Ui {
class ConfirmCalculator;
}
class ConfirmCalculator : public QDialog
{
Q_OBJECT
public:
explicit ConfirmCalculator(QWidget *parent = 0);
~ConfirmCalculator();
bool isCanceled();
void setModel(ConfirmCalculatorModel *model);
private slots:
void on_pushButton_cancel_clicked();
void on_pushButton_ok_pressed();
private:
bool cancel;
ConfirmCalculatorModel *model;
QItemSelectionModel *sel_model;
// QVector<ItemInfo>
Ui::ConfirmCalculator *ui;
};
#endif // CONFIRMCALCULATOR_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.