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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ca9b72f1507770191959ad823c7fc8e536347d39 | 2ce369d1726b3b0229ef7038771e5415a82bed9a | /xnvusettings.cpp | 7e1f0f610cde4033871bc1a7c5761176c297523b | [] | no_license | Vantskruv/XNVU-Calculator | a06beb08bf2e99a2732518dda7a6d77d92cc7699 | 13d39dd4140ea6f51bd48a72b2fad4164a4ce058 | refs/heads/master | 2022-02-13T14:15:01.608640 | 2018-12-06T12:38:01 | 2018-12-06T12:38:01 | 67,116,192 | 2 | 1 | null | 2022-04-16T05:08:20 | 2016-09-01T09:10:19 | C++ | UTF-8 | C++ | false | false | 992 | cpp | xnvusettings.cpp | #include "xnvusettings.h"
#include <QFile>
XNVUSettings::XNVUSettings()
{
}
bool XNVUSettings::loadSettings()
{
QFile infile(XNVU_SETTINGS_FILE);
if(!infile.open(QIODevice::ReadOnly | QIODevice::Text)) return false;
while(!infile.atEnd())
{
QString line = infile.readLine();
line.simplified();
if(line.contains("airports.txt", Qt::CaseInsensitive))
{
fileAirports = line;
}
else if(line.contains("navaids.txt", Qt::CaseInsensitive))
{
fileNavaids = line;
}//if
else if(line.contains("waypoints.txt", Qt::CaseInsensitive))
{
fileWaypoints = line;
}//if
else if(line.contains("rsbn.txt", Qt::CaseInsensitive))
{
fileRSBN = line;
}//if
else if(line.contains("earth_nav.dat", Qt::CaseInsensitive))
{
fileNavdata = line;
}//if
}//while
infile.close();
return true;
}
|
10dc124d8b9c5b1318a6c2c929cf4143d3c27e80 | b4a372307728ea5eb35b7653c7fb767fad9aa2d8 | /Keyboard/Keyboard.ino | 17feab61c44904ec9d855a72d1d8b8b0bfccf632 | [] | no_license | sutekh137/Energia | 4a9fa4936f070f58c42a18d050a46fb2e2475377 | 4763b7c01be830afff4132d34dbe24d3ed54288e | refs/heads/master | 2020-05-28T05:08:32.542525 | 2013-06-28T00:51:43 | 2013-06-28T00:51:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,395 | ino | Keyboard.ino | #include "pitches.h"
#define AUDIO_OUT 19
#define TONES_IN_RANGE 13
#define NOTE_START_PIN 2
#define NOTE_END_PIN 14
#define MIN_RANGE 1
#define MAX_RANGE 7
#define PIN_RANGE_UP 15
#define PIN_RANGE_DOWN 18
#define START_RANGE 4 // C4 is "middle C"
#define SPECIAL_BASE_1 3
#define SPECIAL_BASE_2 5
#define SPECIAL_TRIGGER_1 NOTE_END_PIN
#define SPECIAL_TRIGGER_2 NOTE_END_PIN - 1
#define USE_LOW_POWER true
// Variables used in interrupts should be "volatile" so they
// don't get optimized out by the compiler.
boolean volatile glISRFree = true;
boolean volatile glReplay = false;
boolean volatile glSpecial1 = false;
boolean volatile glSpecial2 = false;
byte volatile gnRange = 0;
unsigned int gaNotes[TONES_IN_RANGE];
unsigned long volatile gnLoopsElapsed = 0;
// It takes ~38 seconds for 1,000,000 loops to run, a frequency of
// 26.315 kHz. That means one second of time passes for the loop() here to
// run 26,315 times. E.g. let's say we want an idle time of ~30 seconds to trigger
// low power mode. That would mean 30 x 26315 = 789,450 loops. (We could use 800,000.)
// (NOTE: even when loops to idle is zero, things work pretty darn well.
//#define LOOPS_TO_IDLE 800000 // About 30 seconds.
#define LOOPS_TO_IDLE 130000 // About 5 Seconds.
void setup() {
// All note buttons and interrupt triggers should be pulled up so that taking them
// LOW (or using FALLING, for IRQs) is cleaner. So, LOW state is what plays notes,
// and IRQs are triggered via FALLING (and checking for LOW in ISR as a quick debounce).
for (byte i = NOTE_START_PIN; i <= NOTE_END_PIN; i++) {
pinMode(i, INPUT_PULLUP);
}
// Range buttons are also pulled up.
pinMode(PIN_RANGE_UP, INPUT_PULLUP);
pinMode(PIN_RANGE_DOWN, INPUT_PULLUP);
// Attach any persistent interrupts. Normal notes will have interrupts attached and
// detached depending on power mode.
attachInterrupt(SPECIAL_TRIGGER_1, ISR_Special1, FALLING);
attachInterrupt(SPECIAL_TRIGGER_2, ISR_Special2, FALLING);
attachInterrupt(PIN_RANGE_UP, ISR_ChangeRangeUp, FALLING);
attachInterrupt(PIN_RANGE_DOWN, ISR_ChangeRangeDown, FALLING);
// Quick start-up tones. Sound slike the "line disconnected" phone trio.
tone(AUDIO_OUT, 950);
delay(500);
tone(AUDIO_OUT, 1400);
delay(500);
tone(AUDIO_OUT, 1875);
delay(1000);
noTone(AUDIO_OUT);
SetRange(START_RANGE);
}
void loop() {
// ncrement global loop counter (used for LPM entry after set idle time at end of loop).
gnLoopsElapsed++;
// Before we check the keyboard, see if there are any special actions we should take.
// Special actions should be mutually-exclusive, so no need to "else" anything.
if (glSpecial1) {
PlayTestTones();
glSpecial1 = false;
return;
}
if (glSpecial2) {
PlayQuadrophenia();
glSpecial2 = false;
return;
}
// Because of the way we have set up the note pins, we can simply go incrementally from
// first to last and play whatever first note we find as LOW (pressed). The PlayNote()
// subroutine loops until key is released.
byte lnButton = 0;
for (byte i = NOTE_START_PIN; i <= NOTE_END_PIN; i++) {
if (digitalRead(i) == LOW) {
// Save what button is pressed. Testing shows it doesn't really matter if we force an
// exit or not...we can scan all keys if we want and it doesn't affect performance.
lnButton = i;
}
}
// See if we have a note to play, and play it if we do.
if (lnButton > 0) {PlayNote(lnButton);}
// We have made it here because no buttons are pressed or the last-pressed button was
// just released. We can now check to see if we want to drop into low power mode.
if (USE_LOW_POWER && (gnLoopsElapsed > LOOPS_TO_IDLE)) {
// Switch to LPM4 with interrupts enabled. ISRs will wake things up, then another idle period
// will put things back to sleep. Attach/Detach interrupts to prevent any stuttering in played
// notes. When in active mode, it will be as if LPM was never initiated. But in LPM, interrupts
// will be in place to wake things up.
// 1. Get ready for sleep. Make sure all interrupts are attached so that playing a note
// immediately wakes up the MCU. We also have to attach the "special key", as those keys
// are also just notes. If we don't re-attach them after cycling in and out of LPM, the
// special key combinations will not work. (Apparently attachInterrupt() is smart enough
// to replace the interrups as first established by the "for" loop).
for (byte i = NOTE_START_PIN; i <= NOTE_END_PIN; i++) {
attachInterrupt(i, ISR_ButtonPressed, FALLING);
}
attachInterrupt(SPECIAL_TRIGGER_1, ISR_Special1, FALLING);
attachInterrupt(SPECIAL_TRIGGER_2, ISR_Special2, FALLING);
// 2. Sleep, baby. Hush now.
_BIS_SR(LPM4_bits | GIE);
// 3. We're back and awake. We don't need interrupts on normal, playable pins (notes) any more,
// except for the "special" keys, as that will just add stuttering/warbling to notes played in sequence.
for (byte i = NOTE_START_PIN; i <= NOTE_END_PIN; i++) {
if (i != SPECIAL_TRIGGER_1 && i != SPECIAL_TRIGGER_2) {
detachInterrupt(i);
}
}
gnLoopsElapsed = 0;
}
}
// 04/05/2013 - Tried using noInterrupts() and interrupts() instead of a Lock/Unlock scheme,
// but it didn't seem to work. Any button attached to an interrupt would cause the MCU to
// reset. I have no idea why and don't care -- this works, and only adds a few dozen bytes
// to the flashed code size (and is still well within the 8K limit of the 2452 chip).
void LockInt() {
glISRFree = false;
delayMicroseconds(100);
}
void UnlockInt() {
glISRFree = true;
delayMicroseconds(100);
}
void ISR_ButtonPressed() {
// Just here to wake up from low power mode (if even attached).
// It does not appear that any live code needs to occur.
}
void ISR_Special1() {
if (glISRFree) {
LockInt();
if (SpecialState()) {
glSpecial1 = true;
}
UnlockInt();
}
return;
}
void ISR_Special2() {
if (glISRFree) {
LockInt();
if (SpecialState()) {
glSpecial2 = true;
}
UnlockInt();
}
return;
}
void ISR_ChangeRangeUp() {
if (glISRFree) {
LockInt();
delayMicroseconds(1000);
if (digitalRead(PIN_RANGE_UP) != LOW) {
UnlockInt();
return;
}
SetRange(gnRange + 1);
glReplay = true;
UnlockInt();
}
return;
}
void ISR_ChangeRangeDown() {
if (glISRFree) {
LockInt();
delayMicroseconds(1000);
if (digitalRead(PIN_RANGE_DOWN) != LOW) {
UnlockInt();
return;
}
SetRange(gnRange - 1);
glReplay = true;
UnlockInt();
}
return;
}
void PlayNote(byte pnButton) {
if (digitalRead(pnButton) == LOW) {
byte lnNoteIndex = pnButton - 2; // Buttons start at 2, note array is zero-indexed.
tone(AUDIO_OUT, gaNotes[lnNoteIndex]);
while (true) {
if (digitalRead(pnButton) == HIGH) {
noTone(AUDIO_OUT);
return;
} else {
if (glReplay) {
tone(AUDIO_OUT, gaNotes[lnNoteIndex]);
glReplay = false;
}
}
}
}
}
boolean SpecialState() {
return (digitalRead(SPECIAL_BASE_1) == LOW & digitalRead(SPECIAL_BASE_2) == LOW);
}
void SetRange(byte pnRange) {
gnRange = pnRange;
// Make sure we are not going out of bounds in terms of range.
if (gnRange < MIN_RANGE) {gnRange = MIN_RANGE;}
if (gnRange > MAX_RANGE) {gnRange = MAX_RANGE;}
switch (gnRange) {
case 1:
gaNotes[0] = NOTE_C1;
gaNotes[1] = NOTE_CS1;
gaNotes[2] = NOTE_D1;
gaNotes[3] = NOTE_DS1;
gaNotes[4] = NOTE_E1;
gaNotes[5] = NOTE_F1;
gaNotes[6] = NOTE_FS1;
gaNotes[7] = NOTE_G1;
gaNotes[8] = NOTE_GS1;
gaNotes[9] = NOTE_A1;
gaNotes[10] = NOTE_AS1;
gaNotes[11] = NOTE_B1;
gaNotes[12] = NOTE_C2;
break;
case 2:
gaNotes[0] = NOTE_C2;
gaNotes[1] = NOTE_CS2;
gaNotes[2] = NOTE_D2;
gaNotes[3] = NOTE_DS2;
gaNotes[4] = NOTE_E2;
gaNotes[5] = NOTE_F2;
gaNotes[6] = NOTE_FS2;
gaNotes[7] = NOTE_G2;
gaNotes[8] = NOTE_GS2;
gaNotes[9] = NOTE_A2;
gaNotes[10] = NOTE_AS2;
gaNotes[11] = NOTE_B2;
gaNotes[12] = NOTE_C3;
break;
case 3:
gaNotes[0] = NOTE_C3;
gaNotes[1] = NOTE_CS3;
gaNotes[2] = NOTE_D3;
gaNotes[3] = NOTE_DS3;
gaNotes[4] = NOTE_E3;
gaNotes[5] = NOTE_F3;
gaNotes[6] = NOTE_FS3;
gaNotes[7] = NOTE_G3;
gaNotes[8] = NOTE_GS3;
gaNotes[9] = NOTE_A3;
gaNotes[10] = NOTE_AS3;
gaNotes[11] = NOTE_B3;
gaNotes[12] = NOTE_C4;
break;
case 4:
gaNotes[0] = NOTE_C4;
gaNotes[1] = NOTE_CS4;
gaNotes[2] = NOTE_D4;
gaNotes[3] = NOTE_DS4;
gaNotes[4] = NOTE_E4;
gaNotes[5] = NOTE_F4;
gaNotes[6] = NOTE_FS4;
gaNotes[7] = NOTE_G4;
gaNotes[8] = NOTE_GS4;
gaNotes[9] = NOTE_A4;
gaNotes[10] = NOTE_AS4;
gaNotes[11] = NOTE_B4;
gaNotes[12] = NOTE_C5;
break;
case 5:
gaNotes[0] = NOTE_C5;
gaNotes[1] = NOTE_CS5;
gaNotes[2] = NOTE_D5;
gaNotes[3] = NOTE_DS5;
gaNotes[4] = NOTE_E5;
gaNotes[5] = NOTE_F5;
gaNotes[6] = NOTE_FS5;
gaNotes[7] = NOTE_G5;
gaNotes[8] = NOTE_GS5;
gaNotes[9] = NOTE_A5;
gaNotes[10] = NOTE_AS5;
gaNotes[11] = NOTE_B5;
gaNotes[12] = NOTE_C6;
break;
case 6:
gaNotes[0] = NOTE_C6;
gaNotes[1] = NOTE_CS6;
gaNotes[2] = NOTE_D6;
gaNotes[3] = NOTE_DS6;
gaNotes[4] = NOTE_E6;
gaNotes[5] = NOTE_F6;
gaNotes[6] = NOTE_FS6;
gaNotes[7] = NOTE_G6;
gaNotes[8] = NOTE_GS6;
gaNotes[9] = NOTE_A6;
gaNotes[10] = NOTE_AS6;
gaNotes[11] = NOTE_B6;
gaNotes[12] = NOTE_C7;
break;
case 7:
gaNotes[0] = NOTE_C7;
gaNotes[1] = NOTE_CS7;
gaNotes[2] = NOTE_D7;
gaNotes[3] = NOTE_DS7;
gaNotes[4] = NOTE_E7;
gaNotes[5] = NOTE_F7;
gaNotes[6] = NOTE_FS7;
gaNotes[7] = NOTE_G7;
gaNotes[8] = NOTE_GS7;
gaNotes[9] = NOTE_A7;
gaNotes[10] = NOTE_AS7;
gaNotes[11] = NOTE_B7;
gaNotes[12] = NOTE_C8;
break;
}
}
void PlayTestTones() {
// Test the full ranges.
byte lnCurrRange = gnRange;
for (byte i = MIN_RANGE; i <= MAX_RANGE; i++) {
SetRange(i);
for (byte j = 0; j <= TONES_IN_RANGE - 1; j++) {
tone(AUDIO_OUT, gaNotes[j], 1000);
delay(100);
}
}
// One last tone for next highest note (a C)! (Range will still be set to highest).
tone(AUDIO_OUT, gaNotes[TONES_IN_RANGE - 1], 2000);
delay(1000);
SetRange(lnCurrRange);
}
void PlayQuadrophenia() {
int laQuadNotes[] = {NOTE_E4,
NOTE_D4,
NOTE_E4,
NOTE_F4,
NOTE_G4,
NOTE_F4,
NOTE_G4,
NOTE_C4,
NOTE_GS4,
NOTE_G4,
NOTE_GS4,
NOTE_G4,
NOTE_F4,
NOTE_E4,
NOTE_F4,
NOTE_D4};
for (byte i = 0; i <= 15; i++) {
tone(AUDIO_OUT, laQuadNotes[i]);
delay(200);
}
noTone(AUDIO_OUT);
}
|
659abcb9090066342d45177c0129660b33f5e3fb | 54d6f4e07ce667130c59726d281cfe511f535d0f | /OverlappingIntervals(GeeksForGeeks).cpp | c014bdb1b1a619d9b40b8aa686cb99c307e568ef | [] | no_license | G33k1973/CodingGames | 36285caf48fb33c7947d3596f3446929b3a0a1ab | 7fa55622c9ee525ac3974cd2036cd61ec448802b | refs/heads/master | 2021-07-08T14:35:14.183733 | 2020-09-05T08:39:08 | 2020-09-05T08:39:08 | 184,714,072 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 884 | cpp | OverlappingIntervals(GeeksForGeeks).cpp | #define M 1005
using ip = pair<int, int>;
void dfs(const vector<ip>& a, int n, int i, int& ts, int& te, vector<bool>& visited) {
if (i == n)return;
if (visited[i] || a[i].first > te)dfs(a, n, i + 1, ts, te, visited);
else {
ts = min(ts, a[i].first);
te = max(te, a[i].second);
visited[i] = 1;
dfs(a, n, i + 1, ts, te, visited);
}
}
vector<pair<int, int>> overlappedInterval(vector<pair<int, int>> vec, int n) {
//code here
if (n < 2)return vec;
sort(begin(vec), end(vec), [&](const pair<int, int>& a, const pair<int, int>& b)->bool {
if (a.first == b.first)
return a.second < b.second;
return a.first < b.first;
});
vector<bool> visited(n, false);
vector<ip> r;
for (int i = 0; i < n; ++i) {
if (visited[i])continue;
int st_ = vec[i].first, ed_ = vec[i].second;
dfs(vec, n, i + 1, st_, ed_, visited);
r.push_back(make_pair(st_, ed_));
}
return r;
} |
52feb61b7eff0e32e35dc6f2f270a6715e35af1a | 7e79e0be56f612288e9783582c7b65a1a6a53397 | /problem-solutions/ICPC/NWERC/2015/D.cpp | b692e2d5ddb9aa5933a176a23125eaa71bc39d1c | [] | no_license | gcamargo96/Competitive-Programming | a643f492b429989c2d13d7d750c6124e99373771 | 0325097de60e693009094990d408ee8f3e8bb18a | refs/heads/master | 2020-07-14T10:27:26.572439 | 2019-08-24T15:11:20 | 2019-08-24T15:11:20 | 66,391,304 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 820 | cpp | D.cpp | #include <bits/stdc++.h>
using namespace std;
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define mp make_pair
#define pb push_back
#define eb emplace_back
#define fi first
#define se second
#define PI acos(-1)
#define fastcin ios_base::sync_with_stdio(false);
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<bool> vb;
typedef pair<int,int> ii;
typedef complex<double> base;
const ll INF = 1000000000000000000LL;
ll n, r, p;
ll LOG(ll x){
ll cnt = 0, cur = 1;
while(cur*2LL <= x){
cnt++;
cur *= 2;
}
return cnt;
}
int main(void){
scanf("%lld%lld%lld", &n, &r, &p);
if(n == 1){
printf("0\n");
return 0;
}
ll ans = LOG(n)*(r+p);
for(int i = 1; i < n; i++){
ans = min(ans, r + ll(i)*p + LOG(n-i)*(r+p));
}
printf("%lld\n", ans);
return 0;
} |
3ae3b5eacbc1a4e8713f59561ca668ac74606655 | f49b246d59ddffda9e6e5cfb96d9a3d16a992ebf | /Inc/Common/Templates/CommonProcess2D.h | 20be51d8910f6a6aa5753ed5564d209c5929767e | [] | no_license | JackBro/PEGGY | 3bbf06564043c5bc2b8ef5eb74f67e3775d84e47 | 9bd4d9b9abc4080a7015b6422d5e45b06de0abb7 | refs/heads/master | 2021-05-28T09:23:33.356849 | 2012-08-23T16:49:26 | 2012-08-23T16:49:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 389 | h | CommonProcess2D.h | #pragma once
#include "CommonProcess.h"
template <typename T, typename U>
class CommonProcess2D :
public CommonProcess<T, U>
{
public:
// cons
CommonProcess2D()
:
CommonProcess()
{
};
protected:
virtual void
SetStore()
{
SetStoreP(new U [GetHeight() * GetWidth()]);
};
virtual T *
GenDest()
const
{
return new T(GetHeight(), GetWidth(), GetStore());
};
};
|
e61495b26702b02159a3cc0d6690c5b65b091b5d | d9a16f827617b189c23277e5c0a6dfb35f6b5f90 | /802.11abgn_phy_11a/eiTemplate/SysConfigWizardStep5.h | d04431bb2cd1846cb6c90d243be3c52688a25aef | [] | no_license | ganlubbq/802.11abgn | ddef686af998efe6e5b1a56d94f96a1316bc1e2c | a21de4921f64cec28fd7b337638cfb57035943cf | refs/heads/master | 2021-06-30T03:50:42.026587 | 2017-09-21T03:05:04 | 2017-09-21T03:05:04 | 111,549,178 | 1 | 0 | null | 2017-11-21T12:58:02 | 2017-11-21T12:58:02 | null | GB18030 | C++ | false | false | 748 | h | SysConfigWizardStep5.h | #pragma once
// CSysConfigWizardStep5 对话框
class CSysConfigWizardStep5 : public CPropertyPage
{
DECLARE_DYNAMIC(CSysConfigWizardStep5)
public:
CSysConfigWizardStep5();
virtual ~CSysConfigWizardStep5();
// 对话框数据
enum { IDD = IDD_SYSCONFIGWIZARD_STEP_5 };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
private:
CBrush m_whiterush;
CFont m_font_title;
CFont m_font_content;
CStatic m_text_title;
CStatic m_text_content;
CStatic m_connection_info;
BOOL b_send_conn;
public:
virtual BOOL OnInitDialog();
afx_msg void OnPaint();
afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
virtual BOOL OnSetActive();
virtual LRESULT OnWizardBack();
};
|
40a24af82241ac5680bab8a9de77c33685965688 | 03fc5fdac295973206f72f9b401f31699d44c1ef | /src/balInterp1D.h | e15e2cd0633ffc8d9e6f7d2a574f571d3d989b31 | [
"MIT"
] | permissive | danielelinaro/BAL | 92c7412d45a14c94df22c943f894a8f7eea16f54 | d735048d9962a0c424c29db93f774494c67b12a9 | refs/heads/master | 2020-05-17T20:13:24.603297 | 2011-04-18T10:38:08 | 2011-04-18T10:38:08 | 22,284,523 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,854 | h | balInterp1D.h | /*=========================================================================
*
* Program: Bifurcation Analysis Library
* Module: balInterp1D.h
*
* Copyright (C) 2009,2010 Daniele Linaro
*
* 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, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*=========================================================================*/
/**
* \file balInterp1D.h
* \brief Definition of classes BaseInterp1D, LinearInterp1D, PolyInterp1D and SplineInterp1D.
*/
#ifndef _BALINTERP1D_
#define _BALINTERP1D_
#include <cmath>
#include <iostream>
#include "balInterpolator.h"
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define NATURAL_SPLINE 1.0e99
#define FINITE_DIFFERENCES_STEP 1.0e-6
namespace bal {
/**
* \class BaseInterp1D
* \brief Base class for one dimensional interpolation of vector functions f: R -> R^{nf}.
*
* \sa Interpolator
*/
class BaseInterp1D : public Interpolator {
public:
/** Returns the name of the class. */
virtual const char * GetClassName() const;
/** Copies a BaseInterp1D. */
static BaseInterp1D * Copy(const BaseInterp1D & interp);
/** Destroys a BaseInterp1D. */
virtual void Destroy();
/** Sets the interpolation points.
* xi is a vector containing the abscissas of the points
* yi is a matrix containing the different ordinates corresponding to each ascissa. yi must have dimensions nf x length.
* length is the number of interpolation points.
* nf is the number of ordinates for each abscissa (dimension of the function codomain) */
virtual void SetInterpolationPoints(double * xi, double **yi, int length, int nf);
/**
* Given a value x, return a value j such that x is (insofar as possible) centered in the subrange
* xx[j..j+mm-1], where xx is the stored pointer. The values in xx must be monotonic, either
* increasing or decreasing. The returned value is not less than 0, nor greater than n-1.
*
* Taken from "Numerical Recipes: The art of scientific computing". Third
* Edition, page 115.
*/
int Locate(const double x);
/**
* Given a value x, return a value j such that x is (insofar as possible) centered in the subrange
* xx[j..j+mm-1], where xx is the stored pointer. The values in xx must be monotonic, either
* increasing or decreasing. The returned value is not less than 0, nor greater than n-1.
*
* Taken from "Numerical Recipes: The art of scientific computing". Third
* Edition, page 116.
*/
int Hunt(const double x);
/** Returns true if it is better you use Hunt() instead of Locate() */
bool nextHunt();
protected:
/** Constructor of BaseInterp1D. */
BaseInterp1D();
/** Copy constructor of BaseInterp1D. */
BaseInterp1D(const BaseInterp1D & interp);
/** Destructor of BaseInterp1D. */
~BaseInterp1D();
int n, mm, jsav, cor, dj;
double *xx, **yy;
};
/**
* \class LinearInterp1D
* \brief Class for one dimensional linear interpolation of vector functions f: R -> R^{nf}.
*
* \sa BaseInterp1D
*/
class LinearInterp1D : public BaseInterp1D {
public:
/** Returns the name of the class. */
virtual const char * GetClassName() const;
/** Destroys a LinearInterp1D. */
virtual void Destroy();
/** Creates a LinearInterp1D */
static LinearInterp1D * Create();
/** Copies a LinearInterp1D */
static LinearInterp1D * Copy(LinearInterp1D *interp);
virtual LinearInterp1D * Clone() const;
/** Evaluates the function in point x. The result is stored in array y.
* If an error has occurred the return value is -1, otherwise it is 0. */
virtual int Evaluate(double *x, double *y);
/** Evaluates the Jacobian matrix of the function in point x. The result is stored in matrix y (of dimensions nf x 1).
* If an error has occurred the return value is -1, otherwise it is 0. */
virtual int EvaluateJacobian(double *x, double **y);
/** Evaluates (if nd = nf) the divergence of the vector field in point x. The result is stored in y (scalar).
* If an error has occurred the return value is -1, otherwise it is 0. */
virtual int EvaluateDivergence(double *x, double *y);
protected:
/** Constructor of LinearInterp1D. */
LinearInterp1D();
/** Copy constructor of LinearInterp1D. */
LinearInterp1D(const LinearInterp1D & interp);
/** Destructor of LinearInterp1D. */
~LinearInterp1D();
};
/**
* \class PolyInterp1D
* \brief Class for one dimensional polynomial interpolation of vector functions f: R -> R^{nf}.
.
* \sa BaseInterp1D
*/
class PolyInterp1D : public BaseInterp1D {
public:
/** Returns the name of the class. */
virtual const char * GetClassName() const;
/** Destroys a PolyInterp1D. */
virtual void Destroy();
/** Creates a PolyInterp1D */
static PolyInterp1D * Create();
/** Copies a PolyInterp1D */
static PolyInterp1D * Copy(PolyInterp1D *interp);
virtual PolyInterp1D * Clone() const;
/** Sets the interpolation order, i.e. the order of the polinomial used to interpolate. Default: 2 (linear interpolation) */
void SetInterpolationOrder(int m);
/** Evaluates the function in point x. The result is stored in array y.
* If an error has occurred the return value is -1, otherwise it is 0. */
virtual int Evaluate(double *x, double *y);
/** Evaluates the Jacobian matrix of the function in point x. The result is stored in matrix y (of dimensions nf x 1).
* If an error has occurred the return value is -1, otherwise it is 0.
* Implemented with finite differences. */
virtual int EvaluateJacobian(double *x, double **y);
/** Evaluates (if nd = nf) the divergence of the vector field in point x. The result is stored in y (scalar).
* If an error has occurred the return value is -1, otherwise it is 0. */
virtual int EvaluateDivergence(double *x, double *y);
protected:
/** Constructor of PolyInterp1D. */
PolyInterp1D();
/** Copy constructor of PolyInterp1D. */
PolyInterp1D(const PolyInterp1D & interp);
/** Destructor of PolyInterp1D. */
~PolyInterp1D();
private:
double dy;
};
/**
* \class SplineInterp1D
* \brief Class for one dimensional interpolation of vector functions f: R -> R^{nf} by using splines.
*
* \sa BaseInterp1D
*/
class SplineInterp1D : public BaseInterp1D {
public:
/** Returns the name of the class. */
virtual const char * GetClassName() const;
/** Destroys a SplineInterp1D. */
virtual void Destroy();
/** Creates a SplineInterp1D */
static SplineInterp1D * Create();
/** Copies a SplineInterp1D */
static SplineInterp1D * Copy(SplineInterp1D *interp);
virtual SplineInterp1D * Clone() const;
/** Sets the value of the first derivative at the boundaries of the domain. There is a single value for each component of the codomain.
* Default value: natural splines (second derivative equal to 0 in the boundaries) */
void SetBoundaryConditions(double yp1, double ypn);
/** Initializes the Spline1D. You have to perform this operation before evaluating the function.
* If an error has occurred the return value is -1, otherwise it is 0. */
int Init();
/** Evaluates the function in point x. The result is stored in array y.
* If an error has occurred the return value is -1, otherwise it is 0. */
virtual int Evaluate(double *x, double *y);
/** Evaluates the Jacobian matrix of the function in point x. The result is stored in matrix y (of dimensions nf x 1).
* If an error has occurred the return value is -1, otherwise it is 0. */
virtual int EvaluateJacobian(double *x, double **y);
/** Evaluates (if nd = nf) the divergence of the vector field in point x. The result is stored in y (scalar).
* If an error has occurred the return value is -1, otherwise it is 0. */
virtual int EvaluateDivergence(double *x, double *y);
protected:
/** Constructor of SplineInterp1D. */
SplineInterp1D();
/** Copy constructor of SplineInterp1D. */
SplineInterp1D(const SplineInterp1D & interp);
/** Destructor of SplineInterp1D. */
~SplineInterp1D();
/** Method used by Init(). */
void Sety2();
private:
double **y2,yyp1,yypn;
};
/**
* \class SmoothingSplineInterp1D
* \brief Class for one dimensional approximation of vector functions f: R -> R^{nf} by using smoothing Reinsch splines.
* Notice that an interpolation is not performed.
* \sa BaseInterp1D
*/
class SmoothingSplineInterp1D : public BaseInterp1D {
public:
/** Returns the name of the class. */
virtual const char * GetClassName() const;
/** Destroys a SmoothingSplineInterp1D. */
virtual void Destroy();
/** Creates a SmoothingSplineInterp1D. */
static SmoothingSplineInterp1D * Create();
virtual SmoothingSplineInterp1D * Clone() const;
/** Copies a SmoothingSplineInterp1D. */
static SmoothingSplineInterp1D * Copy(SmoothingSplineInterp1D *interp);
/** Sets the smoothing factors. The smoothing spline is computed by finding a third order polinomial which minimizes the
* integral of the square of the second derivative under these constraints:
* __
* \
* /_ ( (f(x_i) - y_i) / dy_i )^2 <= S
*
* If S = 0, or all dy values = 0, an interpolation is performed.
* By increasing S or dy values the function becomes smoother and smoother.
*/
void SetSmoothingParameters(double *dy, double S);
/** Sets the smoothing factors. The smoothing spline is computed by finding a third order polinomial which minimizes the
* integral of the square of the second derivative under these constraints:
* __
* \
* /_ (f(x_i) - y_i)^2 <= smooth^2
*
* If smooth = 0 an interpolation is performed.
* By increasing smooth the function becomes smoother and smoother.
*/
void SetSmoothingParameters(double smooth);
/** Initializes the SmoothingSplineInterp1D. You have to perform this operation before evaluating the function.
* If an error has occurred the return value is -1, otherwise it is 0. */
int Init();
/** Evaluates the function in point x. The result is stored in array y.
* If an error has occurred the return value is -1, otherwise it is 0. */
virtual int Evaluate(double *x, double *y);
/** Evaluates the Jacobian matrix of the function in point x. The result is stored in matrix y (of dimensions nf x 1).
* If an error has occurred the return value is -1, otherwise it is 0. */
virtual int EvaluateJacobian(double *x, double **y);
/** Evaluates (if nd = nf) the divergence of the vector field in point x. The result is stored in y (scalar).
* If an error has occurred the return value is -1, otherwise it is 0. */
virtual int EvaluateDivergence(double *x, double *y);
protected:
/** Constructor of SmoothingSplineInterp1D. */
SmoothingSplineInterp1D();
/** Copy constructor of SmoothingSplineInterp1D. */
SmoothingSplineInterp1D(const SmoothingSplineInterp1D & interp);
/** Destructor of SmoothingSplineInterp1D. */
~SmoothingSplineInterp1D();
/** Method used by Init(). */
int ComputeCoefficients(int i);
private:
double *ddy,SS,**a,**b,**c,**d;
int _DEALLOC_DDY;
};
} // namespace bal
#endif
|
fb5b4536c65c339210b9f3430cc4b0f8a7c7e415 | ab9147e5209b5b5b3be74eaa50a615ec341e4aa5 | /Uebung4/Vektorenb.cpp | 3b0d90de8490b12c1a068cbc1de3b9713045ccc8 | [] | no_license | M0M097/ipk-Uebungen | 075583cc1a251235cbd3c35ee69fd850d9b3884d | 5a21480005731db5d64c257491a5ffd9fead39af | refs/heads/main | 2023-02-22T00:24:14.742065 | 2021-01-23T10:54:21 | 2021-01-23T10:54:21 | 315,058,445 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 533 | cpp | Vektorenb.cpp | #include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
std::pair<double,double> kleingross(std::vector<double> v)
{
int ende = v.size() - 1;
std::sort(v.begin(),v.end());
return std::make_pair (v[0], v[ende]);
}
int main(int argc, char** argv)
{
std::pair<double,double> kg;
std::vector<double> v3 = {{ 3, 8, 7, 5, 9, 2 }};
kg = kleingross(v3);
std::cout << "kleinste Zahl des Vektors: " << kg.first << std::endl;
std::cout << "groesste Zahl des Vektors: " << kg.second << std::endl;
return 0;
}
|
7a8affe1658499c4c540e8ea277c48a1d3c64554 | d364d70966586d4429b4244947d11a4e4b791f1d | /pathlibrary.cpp | 1528bdf943e5241ccdb965ed0b4d4763389236c9 | [] | no_license | SaltedFishTung/AGV_System | 4dabda09b8835dd1185409a1383bf210613b0ae7 | fd391ffa0cc459cc4fe00c684f96c68efc4e0249 | refs/heads/master | 2020-05-13T18:01:04.528238 | 2019-06-01T17:28:16 | 2019-06-01T17:28:16 | 181,646,862 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 58 | cpp | pathlibrary.cpp | #include "pathlibrary.h"
PathLibrary::PathLibrary()
{
}
|
7e35dbabf9459686c03b689426c960bc9bcab43e | 671b33372cd8eaf6b63284b03b94fbaf5eb8134e | /protocols/quorum/quorum_libbyz.cc | bdd569d17316a10985387f3fadfb12cdd93ab298 | [
"MIT"
] | permissive | LPD-EPFL/consensusinside | 41f0888dc7c0f9bd25f1ff75781e7141ffa21894 | 4ba9c5274a9ef5bd5f0406b70d3a321e7100c8ac | refs/heads/master | 2020-12-24T15:13:51.072881 | 2014-11-30T11:27:41 | 2014-11-30T11:27:41 | 23,539,134 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,563 | cc | quorum_libbyz.cc | #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pthread.h>
#include "quorum_libbyz.h"
#include "Q_Client.h"
#include "Q_Replica.h"
#include "Q_Request.h"
#include "Q_Reply.h"
//#include "crypt.h"
//#define TRACES
Q_Client *q_client;
void*Q_replica_handler(void *o);
void*Q_client_handler(void *o);
Byz_rep *srep;
static void wait_chld(int sig)
{
// Get rid of zombies created by sfs code.
while (waitpid(-1, 0, WNOHANG) > 0)
;
}
int quorum_alloc_request(Byz_req *req)
{
//fprintf(stderr,"Allocating new request\n");
Q_Request *request = new Q_Request((Request_id) 0);
// fprintf(stderr,"Allocated new request\n");
if (request == 0)
{
return -1;
}
int len;
req->contents = request->store_command(len);
req->size = len;
req->opaque = (void*) request;
return 0;
}
void quorum_free_request(Byz_req *req)
{
Q_Request *request = (Q_Request *) req->opaque;
delete request;
}
void quorum_free_reply(Byz_rep *rep)
{
Q_Reply *reply = (Q_Reply *) rep->opaque;
delete reply;
}
int quorum_init_replica(char *conf, char *conf_priv, char *host_name,
int(*exec)(Byz_req*, Byz_rep*, Byz_buffer*, int, bool),
int (*perform_checkpoint)(), short port)
{
// signal handler to get rid of zombies
struct sigaction act;
act.sa_handler = wait_chld;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGCHLD, &act, NULL);
// Initialize random number generator
srand48(getpid());
/*pthread_attr_t tattr;
int rc;
if(rc = pthread_attr_init(&tattr)){
fprintf(stderr,"ERROR: rc from pthread_attr_init() is %d\n",rc);
exit(-1);
}
if(rc = pthread_attr_setstacksize(&tattr,2*PTHREAD_STACK_MIN)){
fprintf(stderr,"ERROR: rc from pthread_attr_setstacksize() is %d\n",rc);
exit(-1);
}
*/
///////////////////////////
// QUORUM
///////////////////////////
fprintf(stderr, "*******************************************\n");
fprintf(stderr, "* QUORUM replica protocol *\n");
fprintf(stderr, "*******************************************\n");
FILE *config_file = fopen(conf, "r");
if (config_file == 0)
{
fprintf(stderr, "libmodular_BFT: Invalid configuration file %s \n",
conf);
return -1;
}
FILE *config_priv_file = fopen(conf_priv, "r");
if (config_priv_file == 0)
{
fprintf(stderr, "libmodular_BFT: Invalid private configuration file %s \n", conf_priv);
return -1;
}
Q_node = new Q_Replica(config_file, config_priv_file, host_name, port);
// Register service-specific functions.
((Q_Replica *) Q_node)->register_exec(exec);
((Q_Replica *) Q_node)->register_perform_checkpoint(perform_checkpoint);
fclose(config_file);
fclose(config_priv_file);
return 0;
}
int quorum_init_client(char *conf, char *host_name, short port)
{
// signal handler to get rid of zombies
struct sigaction act;
act.sa_handler = wait_chld;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGCHLD, &act, NULL);
// Initialize random number generator
srand48(getpid());
// Intialize random number generator
//random_init();
fprintf(stderr, "******************************************\n");
fprintf(stderr, "* QUORUM client protocol *\n");
fprintf(stderr, "******************************************\n");
FILE *config_file_quorum = fopen(conf, "r");
if (config_file_quorum == 0)
{
fprintf(stderr, "libmodular_BFT: Invalid configuration file %s \n",
conf);
return -1;
}
q_client = new Q_Client(config_file_quorum, host_name, port);
/* pthread_t Q_client_handler_thread;
if (pthread_create(&Q_client_handler_thread, 0, &Q_client_handler,
(void *)q_client) != 0)
{
fprintf(stderr, "Failed to create the Q_client thread\n");
exit(1);
}
*/
return 0;
}
int quorum_send_request(Byz_req *req, int size, bool ro)
{
bool retval;
Q_Request *request = (Q_Request *) req->opaque;
retval = q_client->send_request(request, size, ro);
return (retval) ? 0 : -1;
}
int quorum_invoke(Byz_req *req, Byz_rep *rep, int size, bool ro)
{
if (quorum_send_request(req, size, ro) == -1)
{
return -1;
}
//Abort_data *ad = NULL;
int retval = quorum_recv_reply(rep);
if ( retval == 0)
{
;
return 0;
}
return retval;
}
int quorum_recv_reply(Byz_rep *rep)
{
Q_Reply *reply = q_client->recv_reply();
if (reply == NULL)
{
return -1;
}
else if (reply->should_switch())
{
next_protocol_instance = reply->next_instance_id();
rep->opaque = NULL;
return -127;
}
else
{
rep->contents = reply->reply(rep->size);
rep->opaque = reply;
return 0;
}
return 0;
}
|
99aefcccc8144a01eca8602c5b7e82babf277661 | 0bdfbfde1f44cd94f39eb45aff269d4a0864cdb0 | /src/core/color/packedcolor.cpp | 772b9a036e4540ff5bc3f3bb5b59e846cfd83053 | [] | no_license | Catlinz/catcore-cpp | edb0abdad4262c5d3042599803420960df85619c | 524fd8b0e4257039b96906ec454e581531a2d03e | refs/heads/master | 2021-03-27T13:30:14.393254 | 2015-03-11T14:39:12 | 2015-03-11T14:39:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 541 | cpp | packedcolor.cpp | #include "core/color/packedcolor.h"
#include "core/math/mathcore.h"
namespace Cat {
PackedColorVal PackedColor::fromRGB(Real r, Real g, Real b) {
return fromRGB((UByte)Math::rounded(r/255.0),
(UByte)Math::rounded(g/255.0),
(UByte)Math::rounded(b/255.0));
}
PackedColorVal PackedColor::fromRGBA(Real r, Real g, Real b, Real a) {
return fromRGBA((UByte)Math::rounded(r/255.0),
(UByte)Math::rounded(g/255.0),
(UByte)Math::rounded(b/255.0),
(UByte)Math::rounded(a/255.0));
}
} // namespace Cat
|
4d71b3c0fc0baf14d052b9d1a04d53100278f445 | 47f30284675b6f5b799c29615ebdc9458906932b | /Project_4_RubeGoldberg/main.cpp | 44959a68f79d081c646874db984d6529203e32ae | [] | no_license | NikolaiAlexanderHimlan/GamePhysics | 1ac42bd2f1e1bbffc903cdf5f36af24d9efa044a | 2e2124eaeeefdf24a22c3b8d2327767c4b2fa80e | refs/heads/master | 2020-06-04T00:22:44.205818 | 2015-05-02T15:56:12 | 2015-05-02T15:56:12 | 30,273,439 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,683 | cpp | main.cpp | #include <string>
#include <GLTools.h>
#include <GLShaderManager.h>
#include <GL/glut.h>
#include <GLFrustum.h>
#include <GL/glui.h>
#include <GraphicsGlobals.h>
#include <PhysicsGlobals.h>
#include <CameraView.h>
#include <Object3D.h>
#include <Color.h>
#include <DebugTools.h>
#include <Timer.h>
#include <CountedArray.h>
#include <DataSystem.h>
#include <StringTools.h>
#include <ParticleObject.h>
#include <GroundArea.h>
#include <Boundings.h>//HACK: including Boundings for fixing scale on bounds
#include <RigidObject.h>
#include <RigidBodySystem.h>
#include <TransformObject.h>
#define RENDER_DATA mainView, shaderManager, mvpMatrix /*the necessary parameters for calling draw*/
using namespace nah;
//Engine Data
Timer engineTimer;
GLUI* gluiWindow;
int glutWindowID;
doubleFactor gcSimulationScale;
//datafile parsing values
const std::string DATA_DIR = "Data/";
const std::string DATAFILE_NAME = "LevelData.ini";
const std::string SEC_SIM = "simulation";
const std::string VAL_SCALEFACT = "scale factor";
const std::string VAL_GRAVITY = "gravity force";
const std::string SEC_GAME = "game";
const std::string VAL_NUM_OBJECTS = "num objects";
const std::string SEC_OBJ_PREFIX = "object";
const std::string VAL_OBJ_TYPE = "type";
const std::string VAL_OBJ_POS = "pos";//append axis
//GL rendering
GLShaderManager shaderManager;
GLfloat offset;
GLfloat counter;
GLboolean bDoSomething;
M3DMatrix44f mvpMatrix;
GLint width = 800, height = 600;
inline int getWindowWidth()
{ return width; };
//{ return glutGet((GLenum)GLUT_WINDOW_WIDTH); };
inline int getWindowHeight()
{ return height; };
//{ return glutGet((GLenum)GLUT_WINDOW_HEIGHT); };
//Debugging
bool gDebugGraphics = true;
bool gDebugPhysics = true;
Object3D* debugObj;
RigidBody* debugPhys;
int debugTargetIndex = 2;
bool gPauseSimulation = false;
//UI
GLUI_Control* camPosLocl;
GLUI_Control* camPosWrld;
GLUI_Control* targtIndx;
GLUI_Control* targtName;
GLUI_Control* targtPosGraph;
GLUI_Control* targtPosPhys;
GLUI_Control* targtVel;
GLUI_Control* targtRot;
GLUI_Control* collisionVal;
CameraView* mainView;
float viewDefaultDistance = 55.0f;//starting distance from any planet
//Implementation Data
//physics objects
std::vector<RigidBody*> gameObjects;
RigidObject* model1;
RigidObject* model2;
//forces
float gravityForce = 5.0f;
//contacts
uint maxContacts = 50;//TODO: update based on number of particles
GroundArea* ground;
void ChangeSize(int w, int h)
{
width = w;
height = h;
glViewport(0, 0, width, height);
float aspectRatio = (float)(getWindowWidth() / getWindowHeight());
float fovCalc = 35.0f; // 46.6f / aspectRatio;
mainView->viewFrustum->SetPerspective(fovCalc, aspectRatio, 1.0f, 1000.0f);
}
//Implementation Functions
//assign model batches to models here
void setupModels()
{
model1->setBatchCube(0.5f, 0.5f, 0.5f);
model2->setBatchCube(0.5f, 0.5f, 0.5f);
//model2->setBounds(new Bounding());/*Point Bounding*//*Scaled Cube Bounding
//HACK: fix bounds size since bounds do not currently account for scale
RigidBody::RigidBounds model2Bounding = model2->getBounds();
model2Bounding.width *= 2;
model2Bounding.length *= 2;
model2Bounding.height *= 2;
model2->setBounds(model2Bounding);
//*/
}
void setupWorld()
{
{//view setup
mainView->clearParent();
mainView->clearTarget();
Vector3f viewPosition;
Rotation3D rotateView = Rotation3D(false);
viewPosition[0] = 0;//left/right
viewPosition[1] = -3;//up/down
viewPosition[2] = -15;//towards/away
rotateView.x = 0;
rotateView.y = 0;
rotateView.z = 0;
mainView->setWorldPosition(viewPosition);
mainView->setWorldRotation(rotateView);
}
{//Model1 setup
//model1 position
Vector3f model1Position;
model1Position[0] = -3.0f;//X, left/right
model1Position[1] = -3.0f;//Y, up/down
model1Position[2] = 5.0f;//Z, in/out
model1->refLocalTransform().position = (model1Position);
//model1 rotation
Rotation3D rotateModel1;
rotateModel1.x = 0;
rotateModel1.y = 0;
rotateModel1.z = 0;
model1->refLocalTransform().rotation = (rotateModel1);
}
{//Model2 setup
//model2 position
Vector3f model2Position;
model2Position[0] = 0;//X, left/right
model2Position[1] = 0.0f;//Y, up/down
model2Position[2] = 5.0f;//Z, in/out
model2->refLocalTransform().position = (model2Position);
//model2 rotation
Rotation3D rotateModel2;
rotateModel2.x = 0;
rotateModel2.y = 0;
rotateModel2.z = 0;
model2->refLocalTransform().rotation = (rotateModel2);
//model2 scale
model2->refLocalTransform().scale = 2.0f;
}
//Ground plane setup
ground->physicsPosition.y = -5.0f;
}
void LoadData()
{
gpDataReader->readIniFile(DATA_DIR + DATAFILE_NAME);
gcSimulationScale.setFactor(nah::StringTools::parseSciNotation(gpDataReader->getIniKeyValue(SEC_SIM, VAL_SCALEFACT)));
int numObjects = atoi(gpDataReader->getIniKeyValue(SEC_GAME, VAL_NUM_OBJECTS).c_str());
//Particle* holdParticle;
for (int i = 0; i < numObjects; i++)
{
//holdParticle->setPhysicsPosition(Vector3f());
//gameObjects.push_back(holdParticle);
}
}
void ResetPhysics()
{
//TODO: RigidBody force system
//getGlobalParticleSystem()->clearParticleForceRegistrations();//clear existing force registrations so there don't end up being duplicates
//getGlobalParticleSystem()->clearParticleContactValues();//clear existing contacts as they are probably no longer valid
//set initial velocities
model1->clearPhysics();
model2->clearPhysics();
//set constant acceleration
model1->setAccelerationConst(0.0, -gravityForce, 0.0);
model2->setAccelerationConst(0.0, -gravityForce, 0.0);
}
void SetupPhysics()
{
//add particles to manager
model1->Manage();
model2->Manage();
//TODO: RigidBody contact system
//initialize particle contact generation and register particle contacts
//getGlobalRigidBodySystem()->InitContactGenerator(maxContacts);
//getGlobalRigidBodySystem()->ManageParticleContactGenerator(ground);
ResetPhysics();
}
void setupUI()
{
//setup and initialize GLUI
{
gluiWindow = GLUI_Master.create_glui("GLUI", 0,
glutGet((GLenum)GLUT_WINDOW_X) + glutGet((GLenum)GLUT_WINDOW_WIDTH),
glutGet((GLenum)GLUT_WINDOW_Y) + -20);
std::string bufferText = "__________________;";
//Debug controls
GLUI_Panel* holdPanel = new GLUI_Panel(gluiWindow, "Debug Ctrl");
new GLUI_Checkbox(holdPanel, "Show Physics Debug", (int*)&gDebugPhysics);
new GLUI_Checkbox(holdPanel, "Show Graphics Debug", (int*)&gDebugGraphics);
//Debug output
holdPanel = new GLUI_Panel(gluiWindow, "Debug Out");
targtPosGraph = new GLUI_StaticText(holdPanel, "Target_");
camPosLocl = new GLUI_StaticText(holdPanel, ("Camera_L: " + bufferText).c_str());
camPosWrld = new GLUI_StaticText(holdPanel, ("Camera_W: " + bufferText).c_str());
new GLUI_Separator(holdPanel);
targtIndx = new GLUI_EditText(holdPanel, "Index: ", &debugTargetIndex, GLUI_EDITTEXT_INT);
targtName = new GLUI_StaticText(holdPanel, "Target_");
targtPosPhys = new GLUI_StaticText(holdPanel, "Target_");
targtVel = new GLUI_StaticText(holdPanel, "Target_");
//Collision testing
holdPanel = new GLUI_Panel(gluiWindow, "Collision Testing");
collisionVal = new GLUI_StaticText(holdPanel, ("Ground Collision: " + bufferText).c_str());
gluiWindow->set_main_gfx_window(glutWindowID);
}
}
void myInit()
{
engineTimer.Reset();
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
shaderManager.InitializeStockShaders();
glEnable(GL_DEPTH_TEST);
//Projection
mainView->viewFrustum->SetPerspective(35.0f, (float)(width / height), 1.0f, 1000.0f);
//LoadData();
setupModels();
setupWorld();
SetupPhysics();
setupUI();
//mainView->clearParent();
//mainView->clearTarget();
}
void ResetView()
{
setupWorld();
}
void ResetSimulation()
{
ResetView();
ResetPhysics();
};
void UpdateUI()
{
//Set debug targets
debugObj = model2;
if (debugTargetIndex < 0)
debugTargetIndex = getGlobalRigidBodySystem()->numRigidBodies() - 1;//wrap back to the last index
else if (debugTargetIndex >= (int)getGlobalRigidBodySystem()->numRigidBodies())
debugTargetIndex = 0;//wrap forward to the first index
debugPhys = getGlobalRigidBodySystem()->getRigidBody(debugTargetIndex);
//Handle Debug
if (gDebugPhysics || gDebugGraphics)
{
//TODO: limit character lengths so the numbers don't jump left/right as they change
if (gDebugGraphics)
{
//Debug output
camPosLocl->set_text(("Camera_L: \n" + mainView->getLocalTransform().toStringMultiLine(true, true, false)).c_str());
camPosWrld->set_text(("Camera_W: \n" + mainView->getWorldTransform().toStringMultiLine(true, true, false)).c_str());
if (debugObj != nullptr)
targtPosGraph->set_text(("GrphObjPos: \n" + debugObj->getWorldTransform().toStringMultiLine()).c_str());
}
if (gDebugPhysics)
{
if (debugPhys != nullptr)
{
targtIndx->set_int_val(debugTargetIndex);
targtName->set_text(("Phys Name:\n " + debugPhys->getName()).c_str());
//targtPosGraph->set_text(("GrphPhysPos:\n " + debugPhys->getWorldTransform().position.toString()).c_str());
targtPosPhys->set_text(("SimPos:\n " + debugPhys->getPhysicsPosition().toString()).c_str());
targtVel->set_text(("Velocity:\n " + debugPhys->getVelocityLinear().toString()).c_str());
}
std::string val = "beep";
collisionVal->set_text(("Ground Collision: " + val).c_str());//TODO: output collision information
}
static bool isRefreshed = false;
if (!isRefreshed)
{
gluiWindow->refresh();
isRefreshed = true;
}
}
}
void RenderScene(void)
{
//Swap Colors
GLfloat vColor[] = { 1.0f, 1.0f, 1.0f, 1.0f };
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
//TODO: Depth Buffer
//Draw all models
model1->Draw(RENDER_DATA);
model2->Draw(RENDER_DATA);
ground->Draw(RENDER_DATA);
UpdateUI();
glutSwapBuffers();
}
void Keys(unsigned char key, int x, int y)
{
if (key == 27)//Esc
exit(0);
//Move view
float viewSpeed = 1;
if ((key == 'W') || (key == 'w'))//view move forward
{
mainView->refLocalTransform().moveForward(viewSpeed);
}
if ((key == 'A') || (key == 'a'))//view move left
{
mainView->refLocalTransform().moveRight(-viewSpeed);
}
if ((key == 'S') || (key == 's'))//view move backward
{
mainView->refLocalTransform().moveForward(-viewSpeed);
}
if ((key == 'D') || (key == 'd'))//view move right
{
mainView->refLocalTransform().moveRight(viewSpeed);
}
if ((key == 'R') || (key == 'r'))//view rise
{
//mainView->localTransform.moveUp(viewSpeed);//local rise
//want to move up/down in world
mainView->refLocalTransform().position.y += viewSpeed;
}
if ((key == 'F') || (key == 'f'))//view fall
{
//mainView->localTransform.moveUp(-viewSpeed);//local fall
//want to move up/down in world
mainView->refLocalTransform().position.y -= viewSpeed;
}
//Rotate view
float viewSpinSpeed = 10.0f;
if ((key == 'Q') || (key == 'q'))
{
//roll left
mainView->refLocalTransform().rotation.rotateRollRightDeg(-viewSpinSpeed);
}
if ((key == 'E') || (key == 'e'))
{
//roll right
mainView->refLocalTransform().rotation.rotateRollRightDeg(viewSpinSpeed);
}
//Move target planet
float model2Speed = 1;
if ((key == 'L') || (key == 'l'))
{
model2->refLocalTransform().position.x += model2Speed;//model position X up
}
if ((key == 'J') || (key == 'j'))
{
model2->refLocalTransform().position.x -= model2Speed;//model position X down
}
if ((key == 'U') || (key == 'u'))
{
model2->refLocalTransform().position.y += model2Speed;//model position Y up
}
if ((key == 'O') || (key == 'o'))
{
model2->refLocalTransform().position.y -= model2Speed;//model position Y down
}
if ((key == 'I') || (key == 'i'))
{
model2->refLocalTransform().position.z += model2Speed;//model position Z up
}
if ((key == 'K') || (key == 'k'))
{
model2->refLocalTransform().position.z -= model2Speed;//model position Z down
}
//View controls
if ((key == 'G') || (key == 'g'))
{
//unlock the camera from the target
mainView->clearTarget();
mainView->clearParent();
}
}
void SpecialKeys(int key, int x, int y)
{
if (key == GLUT_KEY_HOME)//reset camera
ResetSimulation();
if (key == GLUT_KEY_END)//pause
gPauseSimulation = !gPauseSimulation;
//iterate through all the particles for debugging
if (key == GLUT_KEY_PAGE_UP)//previous particle
debugTargetIndex--;
if (key == GLUT_KEY_PAGE_DOWN)//next particle
debugTargetIndex++;
//Rotate view
float viewTurnSpeed = 5.0f;
if (key == GLUT_KEY_LEFT)
{
mainView->refLocalTransform().rotation.rotateYawTurnRightDeg(-viewTurnSpeed);
}
if (key == GLUT_KEY_RIGHT)
{
mainView->refLocalTransform().rotation.rotateYawTurnRightDeg(viewTurnSpeed);
}
if (key == GLUT_KEY_UP)
{
mainView->refLocalTransform().rotation.rotatePitchTiltUpDeg(viewTurnSpeed);
}
if (key == GLUT_KEY_DOWN)
{
mainView->refLocalTransform().rotation.rotatePitchTiltUpDeg(-viewTurnSpeed);
}
}
void create()
{
DataSystem::instantiateGlobal();
RigidBodySystem::InstantiateGlobal();
mainView = new CameraView();
gcSimulationScale.setFactor(1.0f);
//Create Objects
model1 = new RigidObject(5.0f, "Bonus Model");
model2 = new RigidObject(10.0f, "Falling Model");
ground = new GroundArea(10.0f, 10.0f, -5.0f);
}
void Update()
{
Time elapsedSeconds = engineTimer.ElapsedSeconds();
//physics
if (!gPauseSimulation)
{
gpRigidBodySystem->PhysicsUpdate(elapsedSeconds);
}
//graphics
glutSetWindow(glutWindowID);
glutPostRedisplay();
engineTimer.Reset();
}
void cleanup()
{
delete mainView;
mainView = nullptr;
//Clean up Objects
model1->Unmanage();
delete model1;
model1 = nullptr;
model2->Unmanage();
delete model2;
model2 = nullptr;
/*prevent end of program crash due to glut extra update
delete modelLink1;
modelLink1 = nullptr;
delete modelLink2;
modelLink2 = nullptr;
delete ground;
ground = nullptr;
*/
RigidBodySystem::ClearGlobal();
DataSystem::clearGlobal();
}
// Entry
int main(int argc, char* argv[])
{
atexit(cleanup);
gltSetWorkingDirectory(argv[0]);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL | GLUT_ALPHA);
glutInitWindowSize(getWindowWidth(), getWindowHeight());
glutWindowID = glutCreateWindow("Boxor");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
glutSpecialFunc(SpecialKeys);
glutKeyboardFunc(Keys);
//glutIdleFunc(Update);
GLUI_Master.set_glutIdleFunc(Update);
GLenum err = glewInit();
if (GLEW_OK != err)
{
fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err));
return 1;
}
create();
myInit();
glutMainLoop();
cleanup();
//Cleanup GLUI
{
gluiWindow->close();
delete gluiWindow;
}
return 0;
}
|
3eb5fc111345817fda2ca1be824c90e41aab6543 | 2b1b459706bbac83dad951426927b5798e1786fc | /src/devices/bin/driver_runtime/channel_test.cc | d3d435245335f8dfc99a60fa2766a8d4cced6d4b | [
"BSD-2-Clause"
] | permissive | gnoliyil/fuchsia | bc205e4b77417acd4513fd35d7f83abd3f43eb8d | bc81409a0527580432923c30fbbb44aba677b57d | refs/heads/main | 2022-12-12T11:53:01.714113 | 2022-01-08T17:01:14 | 2022-12-08T01:29:53 | 445,866,010 | 4 | 3 | BSD-2-Clause | 2022-10-11T05:44:30 | 2022-01-08T16:09:33 | C++ | UTF-8 | C++ | false | false | 65,095 | cc | channel_test.cc | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/devices/bin/driver_runtime/channel.h"
#include <lib/async-loop/cpp/loop.h>
#include <lib/async/task.h>
#include <lib/fdf/cpp/channel_read.h>
#include <lib/fdf/cpp/dispatcher.h>
#include <lib/fit/defer.h>
#include <lib/sync/completion.h>
#include <lib/sync/cpp/completion.h>
#include <lib/zx/event.h>
#include <set>
#include <zxtest/zxtest.h>
#include "src/devices/bin/driver_runtime/arena.h"
#include "src/devices/bin/driver_runtime/dispatcher.h"
#include "src/devices/bin/driver_runtime/driver_context.h"
#include "src/devices/bin/driver_runtime/handle.h"
#include "src/devices/bin/driver_runtime/runtime_test_case.h"
#include "src/devices/bin/driver_runtime/test_utils.h"
class ChannelTest : public RuntimeTestCase {
protected:
ChannelTest() : arena_(nullptr), loop_(&kAsyncLoopConfigNoAttachToCurrentThread) {}
void SetUp() override;
void TearDown() override;
// Registers a wait_async request on |ch| and blocks until it is ready for reading.
void WaitUntilReadReady(fdf_handle_t ch) {
return RuntimeTestCase::WaitUntilReadReady(ch, fdf_dispatcher_);
}
// Allocates and populates an array of size |size|, containing test data. The array is owned by
// |arena|.
void AllocateTestData(fdf_arena_t* arena, size_t size, void** out_data);
void AllocateTestDataWithStartValue(fdf_arena_t* arena, size_t size, size_t start_value,
void** out_data);
fdf::Channel local_;
fdf::Channel remote_;
fdf::Arena arena_;
async::Loop loop_;
fdf_dispatcher_t* fdf_dispatcher_;
DispatcherShutdownObserver dispatcher_observer_;
};
void ChannelTest::SetUp() {
auto channels = fdf::ChannelPair::Create(0);
ASSERT_OK(channels.status_value());
local_ = std::move(channels->end0);
remote_ = std::move(channels->end1);
constexpr uint32_t tag = 'TEST';
arena_ = fdf::Arena(tag);
driver_runtime::Dispatcher* dispatcher;
ASSERT_EQ(ZX_OK,
driver_runtime::Dispatcher::CreateWithLoop(
FDF_DISPATCHER_OPTION_UNSYNCHRONIZED, "scheduler_role", "", CreateFakeDriver(),
&loop_, dispatcher_observer_.fdf_observer(), &dispatcher));
fdf_dispatcher_ = static_cast<fdf_dispatcher_t*>(dispatcher);
// Pretend all calls are non-reentrant so we don't have to worry about threading.
driver_context::PushDriver(CreateFakeDriver());
loop_.StartThread();
}
void ChannelTest::TearDown() {
local_.reset();
remote_.reset();
arena_.reset();
loop_.StartThread(); // Make sure an async loop thread is running for dispatcher destruction.
fdf_dispatcher_shutdown_async(fdf_dispatcher_);
ASSERT_OK(dispatcher_observer_.WaitUntilShutdown());
fdf_dispatcher_destroy(fdf_dispatcher_);
loop_.Quit();
loop_.JoinThreads();
ASSERT_EQ(0, driver_runtime::gHandleTableArena.num_allocated());
driver_context::PopDriver();
}
void ChannelTest::AllocateTestData(fdf_arena_t* arena, size_t size, void** out_data) {
AllocateTestDataWithStartValue(arena, size, 0, out_data);
}
void ChannelTest::AllocateTestDataWithStartValue(fdf_arena_t* arena, size_t size,
size_t start_value, void** out_data) {
uint32_t nums[size / sizeof(uint32_t)];
for (uint32_t i = 0; i < size / sizeof(uint32_t); i++) {
nums[i] = i;
}
void* data = arena->Allocate(size);
ASSERT_NOT_NULL(data);
memcpy(data, nums, size);
*out_data = data;
}
TEST_F(ChannelTest, CreateAndDestroy) {}
TEST_F(ChannelTest, WriteReadEmptyMessage) {
ASSERT_EQ(ZX_OK, fdf_channel_write(local_.get(), 0, nullptr, nullptr, 0, nullptr, 0));
ASSERT_NO_FATAL_FAILURE(WaitUntilReadReady(remote_.get()));
ASSERT_NO_FATAL_FAILURE(AssertRead(remote_.get(), nullptr, 0, nullptr, 0));
}
// Tests writing and reading an array of numbers.
TEST_F(ChannelTest, WriteData) {
constexpr uint32_t kNumBytes = 24 * 1024;
void* data;
AllocateTestData(arena_.get(), kNumBytes, &data);
ASSERT_EQ(ZX_OK, fdf_channel_write(local_.get(), 0, arena_.get(), data, kNumBytes, NULL, 0));
ASSERT_NO_FATAL_FAILURE(WaitUntilReadReady(remote_.get()));
ASSERT_NO_FATAL_FAILURE(AssertRead(remote_.get(), data, kNumBytes, nullptr, 0));
}
// Tests that transferring zircon handles are allowed.
TEST_F(ChannelTest, WriteZirconHandle) {
zx::event event;
ASSERT_EQ(ZX_OK, zx::event::create(0, &event));
void* handles_buf = arena_.Allocate(sizeof(fdf_handle_t));
ASSERT_NOT_NULL(handles_buf);
fdf_handle_t* handles = reinterpret_cast<fdf_handle_t*>(handles_buf);
handles[0] = event.release();
EXPECT_OK(fdf_channel_write(local_.get(), 0, arena_.get(), nullptr, 0, handles, 1));
ASSERT_NO_FATAL_FAILURE(WaitUntilReadReady(remote_.get()));
ASSERT_NO_FATAL_FAILURE(AssertRead(remote_.get(), nullptr, 0, handles, 1));
}
// Tests reading channel handles from a channel message, and writing to
// one of those handles.
TEST_F(ChannelTest, WriteToTransferredChannels) {
// Create some channels to transfer.
fdf_handle_t a0, a1;
fdf_handle_t b0, b1;
ASSERT_EQ(ZX_OK, fdf_channel_create(0, &a0, &a1));
ASSERT_EQ(ZX_OK, fdf_channel_create(0, &b0, &b1));
constexpr uint32_t kNumChannels = 2;
size_t alloc_size = kNumChannels * sizeof(fdf_handle_t);
auto channels_to_transfer = reinterpret_cast<fdf_handle_t*>(arena_.Allocate(alloc_size));
ASSERT_NOT_NULL(channels_to_transfer);
channels_to_transfer[0] = a1;
channels_to_transfer[1] = b1;
ASSERT_EQ(ZX_OK, fdf_channel_write(local_.get(), 0, arena_.get(), nullptr, 0,
channels_to_transfer, kNumChannels));
// Retrieve the transferred channels.
ASSERT_NO_FATAL_FAILURE(WaitUntilReadReady(remote_.get()));
fdf_arena_t* read_arena;
zx_handle_t* handles;
uint32_t num_handles;
ASSERT_EQ(ZX_OK, fdf_channel_read(remote_.get(), 0, &read_arena, nullptr, nullptr, &handles,
&num_handles));
ASSERT_NOT_NULL(handles);
ASSERT_EQ(num_handles, kNumChannels);
// Write to the transferred channel.
constexpr uint32_t kNumBytes = 4096;
void* data;
AllocateTestData(read_arena, kNumBytes, &data);
ASSERT_EQ(ZX_OK, fdf_channel_write(handles[1], 0, read_arena, data, kNumBytes, NULL, 0));
ASSERT_NO_FATAL_FAILURE(WaitUntilReadReady(b0));
ASSERT_NO_FATAL_FAILURE(AssertRead(b0, data, kNumBytes, nullptr, 0));
fdf_handle_close(a0);
fdf_handle_close(a1);
fdf_handle_close(b0);
fdf_handle_close(b1);
read_arena->Destroy();
}
// Tests waiting on a channel before a write happens.
TEST_F(ChannelTest, WaitAsyncBeforeWrite) {
sync_completion_t read_completion;
auto channel_read = std::make_unique<fdf::ChannelRead>(
remote_.get(), 0,
[&read_completion](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read,
zx_status_t status) { sync_completion_signal(&read_completion); });
ASSERT_OK(channel_read->Begin(fdf_dispatcher_));
constexpr uint32_t kNumBytes = 4096;
void* data;
AllocateTestData(arena_.get(), kNumBytes, &data);
ASSERT_EQ(ZX_OK, fdf_channel_write(local_.get(), 0, arena_.get(), data, kNumBytes, NULL, 0));
sync_completion_wait(&read_completion, ZX_TIME_INFINITE);
ASSERT_NO_FATAL_FAILURE(AssertRead(remote_.get(), data, kNumBytes, nullptr, 0));
}
// Tests reading multiple channel messages from within one read callback.
TEST_F(ChannelTest, ReadMultiple) {
constexpr uint32_t kFirstMsgNumBytes = 128;
constexpr uint32_t kSecondMsgNumBytes = 256;
void* data;
AllocateTestData(arena_.get(), kFirstMsgNumBytes, &data);
ASSERT_EQ(ZX_OK,
fdf_channel_write(local_.get(), 0, arena_.get(), data, kFirstMsgNumBytes, NULL, 0));
void* data2;
AllocateTestData(arena_.get(), kSecondMsgNumBytes, &data2);
ASSERT_EQ(ZX_OK,
fdf_channel_write(local_.get(), 0, arena_.get(), data2, kSecondMsgNumBytes, NULL, 0));
sync_completion_t completion;
auto channel_read = std::make_unique<fdf::ChannelRead>(
remote_.get(), 0,
[&](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, zx_status_t status) {
ASSERT_NO_FATAL_FAILURE(AssertRead(remote_.get(), data, kFirstMsgNumBytes, nullptr, 0));
ASSERT_NO_FATAL_FAILURE(AssertRead(remote_.get(), data2, kSecondMsgNumBytes, nullptr, 0));
// There should be no more messages.
ASSERT_EQ(ZX_ERR_SHOULD_WAIT,
fdf_channel_read(remote_.get(), 0, nullptr, nullptr, nullptr, nullptr, nullptr));
sync_completion_signal(&completion);
});
ASSERT_OK(channel_read->Begin(fdf_dispatcher_));
sync_completion_wait(&completion, ZX_TIME_INFINITE);
}
// Tests reading and re-registering the wait async read handler multiple times.
TEST_F(ChannelTest, ReRegisterReadHandler) {
constexpr size_t kNumReads = 10;
constexpr uint32_t kDataSize = 128;
// Populated below.
std::array<std::array<uint8_t, kDataSize>, kNumReads> test_data;
size_t completed_reads = 0;
sync_completion_t completion;
auto channel_read = std::make_unique<fdf::ChannelRead>(
remote_.get(), 0,
[&](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, zx_status_t status) {
ASSERT_NO_FATAL_FAILURE(
AssertRead(remote_.get(), test_data[completed_reads].data(), kDataSize, nullptr, 0));
completed_reads++;
if (completed_reads == kNumReads) {
sync_completion_signal(&completion);
} else {
ASSERT_OK(channel_read->Begin(fdf_dispatcher_));
}
});
ASSERT_OK(channel_read->Begin(fdf_dispatcher_));
for (size_t i = 0; i < kNumReads; i++) {
void* data;
AllocateTestDataWithStartValue(arena_.get(), kDataSize, i, &data);
memcpy(test_data[i].data(), data, kDataSize);
ASSERT_EQ(ZX_OK, fdf_channel_write(local_.get(), 0, arena_.get(), data, kDataSize, NULL, 0));
}
sync_completion_wait(&completion, ZX_TIME_INFINITE);
ASSERT_EQ(completed_reads, kNumReads);
}
// Tests that we get a read call back if we had registered a read wait,
// and the peer closes.
TEST_F(ChannelTest, CloseSignalsPeerClosed) {
sync_completion_t read_completion;
auto channel_read = std::make_unique<fdf::ChannelRead>(
remote_.get(), 0,
[&read_completion](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read,
zx_status_t status) {
ASSERT_NOT_OK(status);
sync_completion_signal(&read_completion);
});
ASSERT_OK(channel_read->Begin(fdf_dispatcher_));
local_.reset();
sync_completion_wait(&read_completion, ZX_TIME_INFINITE);
}
// Tests closing the channel from the channel read callback is allowed.
TEST_F(ChannelTest, CloseChannelInCallback) {
libsync::Completion completion;
auto channel_read = std::make_unique<fdf::ChannelRead>(
remote_.get(), 0,
[&](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, zx_status_t status) {
ASSERT_OK(status);
remote_.reset();
completion.Signal();
});
ASSERT_OK(channel_read->Begin(fdf_dispatcher_));
ASSERT_EQ(ZX_OK, local_.Write(0, arena_, nullptr, 0, cpp20::span<zx_handle_t>()).status_value());
ASSERT_OK(completion.Wait(zx::time::infinite()));
}
// Tests cancelling a channel read that has not yet been queued with the synchronized dispatcher.
TEST_F(ChannelTest, SyncDispatcherCancelUnqueuedRead) {
const void* driver = CreateFakeDriver();
DispatcherShutdownObserver dispatcher_observer;
driver_runtime::Dispatcher* sync_dispatcher;
ASSERT_EQ(ZX_OK,
driver_runtime::Dispatcher::CreateWithLoop(
0, "", "", driver, &loop_, dispatcher_observer.fdf_observer(), &sync_dispatcher));
auto channel_read = std::make_unique<fdf::ChannelRead>(
remote_.get(), 0,
[&](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, zx_status_t status) {
ASSERT_FALSE(true); // This callback should never be called.
});
ASSERT_OK(channel_read->Begin(static_cast<fdf_dispatcher_t*>(sync_dispatcher)));
ASSERT_OK(channel_read->Cancel()); // Cancellation should always succeed for sync dispatchers.
sync_dispatcher->ShutdownAsync();
ASSERT_OK(dispatcher_observer.WaitUntilShutdown());
sync_dispatcher->Destroy();
}
// Tests cancelling a channel read that has been queued with the synchronized dispatcher.
TEST_F(ChannelTest, SyncDispatcherCancelQueuedRead) {
const void* driver = CreateFakeDriver();
DispatcherShutdownObserver dispatcher_observer;
driver_runtime::Dispatcher* sync_dispatcher;
ASSERT_EQ(ZX_OK,
driver_runtime::Dispatcher::CreateWithLoop(
0, "", "", driver, &loop_, dispatcher_observer.fdf_observer(), &sync_dispatcher));
// Make calls reentrant so any callback will be queued on the async loop.
driver_context::PushDriver(driver);
auto pop_driver = fit::defer([]() { driver_context::PopDriver(); });
auto channel_read = std::make_unique<fdf::ChannelRead>(
remote_.get(), 0,
[&](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, zx_status_t status) {
ASSERT_FALSE(true); // This callback should never be called.
});
ASSERT_OK(channel_read->Begin(static_cast<fdf_dispatcher_t*>(sync_dispatcher)));
sync_completion_t task_completion;
ASSERT_OK(async::PostTask(sync_dispatcher->GetAsyncDispatcher(), [&] {
// This should queue the callback on the async loop. It won't be running yet
// as this task is currently blocking the loop.
ASSERT_EQ(ZX_OK, fdf_channel_write(local_.get(), 0, arena_.get(), nullptr, 0, nullptr, 0));
ASSERT_EQ(sync_dispatcher->callback_queue_size_slow(), 1);
// This should synchronously cancel the callback.
ASSERT_OK(channel_read->Cancel()); // Cancellation should always succeed for sync dispatchers.
ASSERT_EQ(sync_dispatcher->callback_queue_size_slow(), 0);
sync_completion_signal(&task_completion);
}));
ASSERT_OK(sync_completion_wait(&task_completion, ZX_TIME_INFINITE));
// The read should already be cancelled, try registering a new one.
sync_completion_t read_completion;
channel_read = std::make_unique<fdf::ChannelRead>(
remote_.get(), 0,
[&read_completion](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read,
zx_status_t status) { sync_completion_signal(&read_completion); });
ASSERT_OK(channel_read->Begin(static_cast<fdf_dispatcher_t*>(sync_dispatcher)));
ASSERT_OK(sync_completion_wait(&read_completion, ZX_TIME_INFINITE));
sync_dispatcher->ShutdownAsync();
ASSERT_OK(dispatcher_observer.WaitUntilShutdown());
sync_dispatcher->Destroy();
}
// Tests cancelling a channel read that has been queued with the synchronized dispatcher.
TEST_F(ChannelTest, SyncDispatcherCancelQueuedReadFromTask) {
loop_.Quit();
loop_.JoinThreads();
loop_.ResetQuit();
const void* driver = CreateFakeDriver();
DispatcherShutdownObserver dispatcher_observer;
driver_runtime::Dispatcher* sync_dispatcher;
ASSERT_EQ(ZX_OK,
driver_runtime::Dispatcher::CreateWithLoop(
0, "", "", driver, &loop_, dispatcher_observer.fdf_observer(), &sync_dispatcher));
// Make calls reentrant so any callback will be queued on the async loop.
driver_context::PushDriver(driver);
auto pop_driver = fit::defer([]() { driver_context::PopDriver(); });
auto channel_read = std::make_unique<fdf::ChannelRead>(
remote_.get(), 0,
[&](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, zx_status_t status) {
ASSERT_FALSE(true); // This callback should never be called.
});
sync_completion_t task_completion;
ASSERT_OK(async::PostTask(sync_dispatcher->GetAsyncDispatcher(), [&] {
ASSERT_EQ(sync_dispatcher->callback_queue_size_slow(), 1);
// This should synchronously cancel the callback.
channel_read->Cancel();
ASSERT_EQ(sync_dispatcher->callback_queue_size_slow(), 0);
sync_completion_signal(&task_completion);
}));
ASSERT_OK(channel_read->Begin(static_cast<fdf_dispatcher_t*>(sync_dispatcher)));
// This should queue the callback on the async loop.
ASSERT_EQ(ZX_OK, fdf_channel_write(local_.get(), 0, arena_.get(), nullptr, 0, nullptr, 0));
// This should run the task, and cancel the callback.
loop_.StartThread();
ASSERT_OK(sync_completion_wait(&task_completion, ZX_TIME_INFINITE));
// The read should already be cancelled, try registering a new one.
sync_completion_t read_completion;
channel_read = std::make_unique<fdf::ChannelRead>(
remote_.get(), 0,
[&read_completion](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read,
zx_status_t status) { sync_completion_signal(&read_completion); });
ASSERT_OK(channel_read->Begin(static_cast<fdf_dispatcher_t*>(sync_dispatcher)));
ASSERT_OK(sync_completion_wait(&read_completion, ZX_TIME_INFINITE));
sync_dispatcher->ShutdownAsync();
ASSERT_OK(dispatcher_observer.WaitUntilShutdown());
sync_dispatcher->Destroy();
}
TEST_F(ChannelTest, SyncDispatcherCancelTaskFromChannelRead) {
loop_.Quit();
loop_.JoinThreads();
loop_.ResetQuit();
const void* driver = CreateFakeDriver();
DispatcherShutdownObserver dispatcher_observer;
driver_runtime::Dispatcher* sync_dispatcher;
ASSERT_EQ(ZX_OK,
driver_runtime::Dispatcher::CreateWithLoop(
0, "", "", driver, &loop_, dispatcher_observer.fdf_observer(), &sync_dispatcher));
// Make calls reentrant so any callback will be queued on the async loop.
driver_context::PushDriver(driver);
auto pop_driver = fit::defer([]() { driver_context::PopDriver(); });
async::TaskClosure task;
task.set_handler([] { ASSERT_FALSE(true); });
sync_completion_t completion;
auto channel_read = std::make_unique<fdf::ChannelRead>(
remote_.get(), 0,
[&](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, zx_status_t status) {
ASSERT_EQ(sync_dispatcher->callback_queue_size_slow(), 1);
// This should synchronously cancel the callback.
task.Cancel();
ASSERT_EQ(sync_dispatcher->callback_queue_size_slow(), 0);
sync_completion_signal(&completion);
});
ASSERT_OK(channel_read->Begin(static_cast<fdf_dispatcher_t*>(sync_dispatcher)));
// This should queue the callback on the async loop.
ASSERT_EQ(ZX_OK, fdf_channel_write(local_.get(), 0, arena_.get(), nullptr, 0, nullptr, 0));
ASSERT_OK(task.Post(sync_dispatcher->GetAsyncDispatcher()));
// This should run the callback, and cancel the task.
loop_.StartThread();
ASSERT_OK(sync_completion_wait(&completion, ZX_TIME_INFINITE));
sync_dispatcher->ShutdownAsync();
ASSERT_OK(dispatcher_observer.WaitUntilShutdown());
sync_dispatcher->Destroy();
}
// Tests cancelling a channel read that has not yet been queued with the unsynchronized dispatcher.
TEST_F(ChannelTest, UnsyncDispatcherCancelUnqueuedRead) {
const void* driver = CreateFakeDriver();
DispatcherShutdownObserver dispatcher_observer;
driver_runtime::Dispatcher* unsync_dispatcher;
ASSERT_EQ(ZX_OK, driver_runtime::Dispatcher::CreateWithLoop(
FDF_DISPATCHER_OPTION_UNSYNCHRONIZED, "", "", driver, &loop_,
dispatcher_observer.fdf_observer(), &unsync_dispatcher));
// Make calls reentrant so that any callback will be queued on the async loop.
driver_context::PushDriver(driver);
auto pop_driver = fit::defer([]() { driver_context::PopDriver(); });
sync_completion_t completion;
auto channel_read = std::make_unique<fdf::ChannelRead>(
remote_.get(), 0,
[&](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, zx_status_t status) {
ASSERT_EQ(status, ZX_ERR_CANCELED);
sync_completion_signal(&completion);
});
ASSERT_OK(channel_read->Begin(static_cast<fdf_dispatcher_t*>(unsync_dispatcher)));
ASSERT_OK(channel_read->Cancel());
ASSERT_OK(sync_completion_wait(&completion, ZX_TIME_INFINITE));
unsync_dispatcher->ShutdownAsync();
ASSERT_OK(dispatcher_observer.WaitUntilShutdown());
unsync_dispatcher->Destroy();
}
// Tests cancelling a channel read that has been queued with the unsynchronized dispatcher.
TEST_F(ChannelTest, UnsyncDispatcherCancelQueuedRead) {
const void* driver = CreateFakeDriver();
DispatcherShutdownObserver dispatcher_observer;
driver_runtime::Dispatcher* unsync_dispatcher;
ASSERT_EQ(ZX_OK, driver_runtime::Dispatcher::CreateWithLoop(
FDF_DISPATCHER_OPTION_UNSYNCHRONIZED, "", "", driver, &loop_,
dispatcher_observer.fdf_observer(), &unsync_dispatcher));
// Make calls reentrant so that the callback will be queued on the async loop.
driver_context::PushDriver(driver);
auto pop_driver = fit::defer([]() { driver_context::PopDriver(); });
sync_completion_t read_completion;
auto channel_read = std::make_unique<fdf::ChannelRead>(
remote_.get(), 0,
[&](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, zx_status_t status) {
ASSERT_EQ(status, ZX_ERR_CANCELED);
sync_completion_signal(&read_completion);
});
ASSERT_OK(channel_read->Begin(static_cast<fdf_dispatcher_t*>(unsync_dispatcher)));
ASSERT_OK(async::PostTask(unsync_dispatcher->GetAsyncDispatcher(), [&] {
// This should queue the callback on the async loop.
ASSERT_EQ(ZX_OK, fdf_channel_write(local_.get(), 0, arena_.get(), nullptr, 0, nullptr, 0));
ASSERT_EQ(unsync_dispatcher->callback_queue_size_slow(), 1);
ASSERT_OK(channel_read->Cancel()); // We should be able to find and cancel the channel read.
// The channel read is still expecting a callback.
ASSERT_NOT_OK(channel_read->Begin(static_cast<fdf_dispatcher_t*>(unsync_dispatcher)));
}));
ASSERT_OK(sync_completion_wait(&read_completion, ZX_TIME_INFINITE));
ASSERT_EQ(unsync_dispatcher->callback_queue_size_slow(), 0);
// Try scheduling another read.
sync_completion_reset(&read_completion);
channel_read = std::make_unique<fdf::ChannelRead>(
remote_.get(), 0,
[&read_completion](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read,
zx_status_t status) { sync_completion_signal(&read_completion); });
ASSERT_OK(channel_read->Begin(static_cast<fdf_dispatcher_t*>(unsync_dispatcher)));
ASSERT_OK(sync_completion_wait(&read_completion, ZX_TIME_INFINITE));
unsync_dispatcher->ShutdownAsync();
ASSERT_OK(dispatcher_observer.WaitUntilShutdown());
unsync_dispatcher->Destroy();
}
// Tests cancelling a channel read that has been queued with the unsynchronized dispatcher,
// and is about to be dispatched.
TEST_F(ChannelTest, UnsyncDispatcherCancelQueuedReadFails) {
loop_.Quit();
loop_.JoinThreads();
loop_.ResetQuit();
const void* driver = CreateFakeDriver();
DispatcherShutdownObserver dispatcher_observer;
driver_runtime::Dispatcher* unsync_dispatcher;
ASSERT_EQ(ZX_OK, driver_runtime::Dispatcher::CreateWithLoop(
FDF_DISPATCHER_OPTION_UNSYNCHRONIZED, "", "", driver, &loop_,
dispatcher_observer.fdf_observer(), &unsync_dispatcher));
// Make calls reentrant so that any callback will be queued on the async loop.
driver_context::PushDriver(driver);
auto pop_driver = fit::defer([]() { driver_context::PopDriver(); });
// We will queue 2 channel reads, the first will block so we can test what happens
// when we try to cancel in-flight callbacks.
libsync::Completion read_entered;
libsync::Completion read_block;
auto channel_read = std::make_unique<fdf::ChannelRead>(
remote_.get(), 0,
[&](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, zx_status_t status) {
read_entered.Signal();
ASSERT_OK(read_block.Wait(zx::time::infinite()));
ASSERT_EQ(status, ZX_OK);
});
ASSERT_OK(channel_read->Begin(static_cast<fdf_dispatcher_t*>(unsync_dispatcher)));
auto channels = fdf::ChannelPair::Create(0);
ASSERT_OK(channels.status_value());
auto local2 = std::move(channels->end0);
auto remote2 = std::move(channels->end1);
libsync::Completion read_complete;
auto channel_read2 = std::make_unique<fdf::ChannelRead>(
remote2.get(), 0,
[&](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, zx_status_t status) {
ASSERT_OK(status); // We could not cancel this in time.
read_complete.Signal();
});
ASSERT_OK(channel_read2->Begin(static_cast<fdf_dispatcher_t*>(unsync_dispatcher)));
ASSERT_EQ(ZX_OK, fdf_channel_write(local_.get(), 0, arena_.get(), nullptr, 0, nullptr, 0));
ASSERT_EQ(ZX_OK, fdf_channel_write(local2.get(), 0, arena_.get(), nullptr, 0, nullptr, 0));
// Start dispatching the read callbacks. The first callback should block.
loop_.StartThread();
ASSERT_OK(read_entered.Wait(zx::time::infinite()));
ASSERT_EQ(channel_read->Cancel(), ZX_ERR_NOT_FOUND);
ASSERT_EQ(channel_read2->Cancel(), ZX_ERR_NOT_FOUND);
read_block.Signal();
ASSERT_OK(read_complete.Wait(zx::time::infinite()));
unsync_dispatcher->ShutdownAsync();
ASSERT_OK(dispatcher_observer.WaitUntilShutdown());
unsync_dispatcher->Destroy();
}
// Tests that you can wait on and read pending messages from a channel even if the peer is closed.
TEST_F(ChannelTest, ReadRemainingMessagesWhenPeerIsClosed) {
void* data = arena_.Allocate(64);
ASSERT_EQ(ZX_OK, fdf_channel_write(local_.get(), 0, arena_.get(), data, 64, NULL, 0));
local_.reset();
ASSERT_NO_FATAL_FAILURE(WaitUntilReadReady(remote_.get()));
ASSERT_NO_FATAL_FAILURE(AssertRead(remote_.get(), data, 64, nullptr, 0));
}
// Tests that read provides ownership of an arena.
TEST_F(ChannelTest, ReadArenaOwnership) {
void* data = arena_.Allocate(64);
ASSERT_EQ(ZX_OK, fdf_channel_write(local_.get(), 0, arena_.get(), data, 64, NULL, 0));
arena_.reset();
fdf_arena_t* read_arena;
ASSERT_NO_FATAL_FAILURE(WaitUntilReadReady(remote_.get()));
ASSERT_NO_FATAL_FAILURE(AssertRead(remote_.get(), data, 64, nullptr, 0, &read_arena));
// Re-use the arena provided by the read call.
data = read_arena->Allocate(64);
ASSERT_EQ(ZX_OK, fdf_channel_write(remote_.get(), 0, read_arena, data, 64, NULL, 0));
fdf_arena_destroy(read_arena);
ASSERT_NO_FATAL_FAILURE(WaitUntilReadReady(local_.get()));
ASSERT_NO_FATAL_FAILURE(AssertRead(local_.get(), data, 64, nullptr, 0));
}
// This test was adapted from the Zircon Channel test of the same name.
TEST_F(ChannelTest, ConcurrentReadsConsumeUniqueElements) {
// Used to force both threads to stall until both are ready to run.
zx::event event;
constexpr uint32_t kNumMessages = 2000;
enum class ReadMessageStatus {
kUnset,
kReadFailed,
kOk,
};
struct Message {
uint64_t data = 0;
uint32_t data_size = 0;
ReadMessageStatus status = ReadMessageStatus::kUnset;
fdf_arena_t* arena = nullptr;
};
std::vector<Message> read_messages;
read_messages.resize(kNumMessages);
auto reader_worker = [&](uint32_t offset) {
zx_status_t wait_status = event.wait_one(ZX_USER_SIGNAL_0, zx::time::infinite(), nullptr);
if (wait_status != ZX_OK) {
return;
}
for (uint32_t i = 0; i < kNumMessages / 2; ++i) {
fdf_arena_t* arena;
void* data;
uint32_t read_bytes = 0;
zx_status_t read_status =
fdf_channel_read(remote_.get(), 0, &arena, &data, &read_bytes, nullptr, nullptr);
uint32_t index = offset + i;
auto& message = read_messages[index];
if (read_status != ZX_OK) {
message.status = ReadMessageStatus::kReadFailed;
continue;
}
message.status = ReadMessageStatus::kOk;
message.data = *(reinterpret_cast<uint64_t*>(data));
message.data_size = read_bytes;
message.arena = arena;
}
return;
};
ASSERT_OK(zx::event::create(0, &event));
constexpr uint32_t kReader1Offset = 0;
constexpr uint32_t kReader2Offset = kNumMessages / 2;
{
test_utils::AutoJoinThread worker_1(reader_worker, kReader1Offset);
test_utils::AutoJoinThread worker_2(reader_worker, kReader2Offset);
auto cleanup = fit::defer([&]() {
// Notify cancelled.
event.reset();
});
fdf_arena_t* arena;
ASSERT_OK(fdf_arena_create(0, 'TEST', &arena));
for (uint64_t i = 1; i <= kNumMessages; ++i) {
void* data = fdf_arena_allocate(arena, sizeof(i));
memcpy(data, &i, sizeof(i));
ASSERT_OK(fdf_channel_write(local_.get(), 0, arena, data, sizeof(i), nullptr, 0));
}
fdf_arena_destroy(arena);
ASSERT_OK(event.signal(0, ZX_USER_SIGNAL_0));
// Join before cleanup.
worker_1.Join();
worker_2.Join();
}
std::set<uint64_t> read_data;
// Check that data os within (0, kNumMessages] range and that is monotonically increasing per
// each reader.
auto ValidateMessages = [&read_data, &read_messages, kNumMessages](uint32_t offset) {
uint64_t prev = 0;
for (uint32_t i = offset; i < kNumMessages / 2 + offset; ++i) {
const auto& message = read_messages[i];
read_data.insert(message.data);
EXPECT_GT(message.data, 0);
EXPECT_LE(message.data, kNumMessages);
EXPECT_GT(message.data, prev);
prev = message.data;
EXPECT_EQ(message.data_size, sizeof(uint64_t));
EXPECT_EQ(message.status, ReadMessageStatus::kOk);
}
};
ValidateMessages(kReader1Offset);
ValidateMessages(kReader2Offset);
// No repeated messages.
ASSERT_EQ(read_data.size(), kNumMessages,
"Read messages do not match the number of written messages.");
for (uint32_t i = 0; i < kNumMessages; i++) {
fdf_arena_destroy(read_messages[i].arena);
}
}
// Tests that handles in unread messages are closed when the channel is closed.
TEST_F(ChannelTest, OnFlightHandlesSignalledWhenPeerIsClosed) {
zx::channel zx_on_flight_local;
zx::channel zx_on_flight_remote;
ASSERT_OK(zx::channel::create(0, &zx_on_flight_local, &zx_on_flight_remote));
fdf_handle_t on_flight_local;
fdf_handle_t on_flight_remote;
ASSERT_EQ(ZX_OK, fdf_channel_create(0, &on_flight_local, &on_flight_remote));
// Write the fdf channel |zx_on_flight_remote| from |local_| to |remote_|.
zx_handle_t* channels_to_transfer =
reinterpret_cast<zx_handle_t*>(arena_.Allocate(sizeof(zx_handle_t)));
ASSERT_NOT_NULL(channels_to_transfer);
*channels_to_transfer = zx_on_flight_remote.release();
ASSERT_OK(fdf_channel_write(local_.get(), 0, arena_.get(), nullptr, 0, channels_to_transfer, 1));
// Write the zircon channel |on_flight_remote| from |remote_| to |local_|.
channels_to_transfer = channels_to_transfer =
reinterpret_cast<zx_handle_t*>(arena_.Allocate(sizeof(zx_handle_t)));
ASSERT_NOT_NULL(channels_to_transfer);
*channels_to_transfer = on_flight_remote;
ASSERT_OK(fdf_channel_write(remote_.get(), 0, arena_.get(), nullptr, 0, channels_to_transfer, 1));
// Close |local_| and verify that |on_flight_local| gets a peer closed notification.
sync_completion_t read_completion;
auto channel_read_ = std::make_unique<fdf::ChannelRead>(
on_flight_local, 0 /* options */,
[&](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, zx_status_t status) {
sync_completion_signal(&read_completion);
});
EXPECT_EQ(ZX_OK, channel_read_->Begin(fdf_dispatcher_));
local_.reset();
sync_completion_wait(&read_completion, ZX_TIME_INFINITE);
// Because |remote| is still not closed, |zx_on_flight_local| should still be writeable.
zx_signals_t signals;
ASSERT_EQ(zx_on_flight_local.wait_one(0, zx::time::infinite_past(), &signals), ZX_ERR_TIMED_OUT);
ASSERT_NE(signals & ZX_CHANNEL_WRITABLE, 0);
// Close |remote_| and verify that |zx_on_flight_local| gets a peer closed notification.
remote_.reset();
ASSERT_OK(zx_on_flight_local.wait_one(ZX_CHANNEL_PEER_CLOSED, zx::time::infinite(), nullptr));
fdf_handle_close(on_flight_local);
}
// Nest 200 channels, each one in the payload of the previous one.
TEST_F(ChannelTest, NestingIsOk) {
constexpr uint32_t kNestedCount = 200;
std::vector<fdf_handle_t> local(kNestedCount);
std::vector<fdf_handle_t> remote(kNestedCount);
for (uint32_t i = 0; i < kNestedCount; i++) {
ASSERT_OK(fdf_channel_create(0, &local[i], &remote[i]));
}
for (uint32_t i = kNestedCount - 1; i > 0; i--) {
fdf_handle_t* handles =
reinterpret_cast<fdf_handle_t*>(arena_.Allocate(2 * sizeof(fdf_handle_t)));
ASSERT_NOT_NULL(handles);
handles[0] = local[i];
handles[1] = remote[i];
ASSERT_OK(fdf_channel_write(local[i - 1], 0, arena_.get(), nullptr, 0, handles, 2));
}
// Close the handles and for destructions.
fdf_handle_close(local[0]);
fdf_handle_close(remote[0]);
}
//
// Channel::Call() test helpers.
//
// Describes a message to transfer for a channel call transaction.
// This is passed from the test to the server thread for verifying received messages.
class Message {
public:
static constexpr uint32_t kMaxDataSize = 64;
// |data_size| specifies the size of the data to transfer, not including the txid.
// |num_handles| specifies the number of handles to create and transfer.
Message(uint32_t data_size, uint32_t num_handles)
: data_size_(data_size), num_handles_(num_handles) {}
// |handles| specifies the handles that should be transferred, rather than creating new ones.
Message(uint32_t data_size, cpp20::span<zx_handle_t> handles)
: handles_(handles),
data_size_(data_size),
num_handles_(static_cast<uint32_t>(handles.size())) {}
// Writes a message to |channel|, with the data and handle buffers allocated using |arena|.
zx_status_t Write(const fdf::Channel& channel, const fdf::Arena& arena, fdf_txid_t txid) const;
// Synchronously calls to |channel|, with the data and handle buffers allocated using |arena|.
zx::result<fdf::Channel::ReadReturn> Call(const fdf::Channel& channel, const fdf::Arena& arena,
zx::time deadline = zx::time::infinite()) const;
// Returns whether |read| contains the expected data and number of handles.
bool IsEquivalent(fdf::Channel::ReadReturn& read) const;
private:
// Allocates the fake data and handle buffers using |arena|.
// This can be used to create the expected arguments for Channel::Call() / Channel::Write().
// The returned data buffer will contain |txid| and |data|,
// and the returned handles buffer will either contain newly constructed event objects,
// or the |handles_| set by the Message constructor.
zx_status_t AllocateBuffers(const fdf::Arena& arena, fdf_txid_t txid, void** out_data,
uint32_t* out_num_bytes, cpp20::span<zx_handle_t>* out_handles) const;
uint32_t data_[kMaxDataSize] = {0};
cpp20::span<zx_handle_t> handles_;
uint32_t data_size_;
uint32_t num_handles_;
};
zx_status_t Message::Write(const fdf::Channel& channel, const fdf::Arena& arena,
fdf_txid_t txid) const {
void* data = nullptr;
uint32_t num_bytes = 0;
cpp20::span<zx_handle_t> handles;
zx_status_t status = AllocateBuffers(arena, txid, &data, &num_bytes, &handles);
if (status != ZX_OK) {
return status;
}
auto write_status = channel.Write(0, arena, data, num_bytes, std::move(handles));
return write_status.status_value();
}
// Synchronously calls to |channel|, with the data and handle buffers allocated using |arena|.
zx::result<fdf::Channel::ReadReturn> Message::Call(const fdf::Channel& channel,
const fdf::Arena& arena,
zx::time deadline) const {
void* data = nullptr;
uint32_t num_bytes = 0;
cpp20::span<zx_handle_t> handles;
zx_status_t status = AllocateBuffers(arena, 0, &data, &num_bytes, &handles);
if (status != ZX_OK) {
return zx::error(status);
}
return channel.Call(0, deadline, arena, data, num_bytes, std::move(handles));
}
// Allocates the fake data and handle buffers using |arena|.
// This can be used to create the expected arguments for Channel::Call() / Channel::Write().
// The returned data buffer will contain |txid| and |data|,
// and the returned handles buffer will either contain newly constructed event objects,
// or the |handles_| set by the Message constructor.
zx_status_t Message::AllocateBuffers(const fdf::Arena& arena, fdf_txid_t txid, void** out_data,
uint32_t* out_num_bytes,
cpp20::span<zx_handle_t>* out_handles) const {
uint32_t total_size = sizeof(fdf_txid_t) + data_size_;
void* bytes = arena.Allocate(total_size);
if (!bytes) {
return ZX_ERR_NO_MEMORY;
}
memcpy(bytes, &txid, sizeof(txid));
memcpy(static_cast<uint8_t*>(bytes) + sizeof(txid), data_, data_size_);
void* handles_bytes = arena.Allocate(num_handles_ * sizeof(fdf_handle_t));
if (!handles_bytes) {
return ZX_ERR_NO_MEMORY;
}
fdf_handle_t* handles = static_cast<fdf_handle_t*>(handles_bytes);
uint32_t i = 0;
auto cleanup = fit::defer([&i, handles]() {
for (uint32_t j = 0; j < i; j++) {
zx_handle_close(handles[j]);
}
});
for (i = 0; i < num_handles_; i++) {
if (handles_.size() > i) {
handles[i] = handles_[i];
} else {
zx::event event;
zx_status_t status = zx::event::create(0, &event);
if (status != ZX_OK) {
return status;
}
handles[i] = event.release();
}
}
cleanup.cancel();
cpp20::span<zx_handle_t> handles_span{handles, num_handles_};
*out_data = bytes;
*out_num_bytes = total_size;
*out_handles = std::move(handles_span);
return ZX_OK;
}
// Returns whether |read| contains the expected data and number of handles.
bool Message::IsEquivalent(fdf::Channel::ReadReturn& read) const {
if ((data_size_ + sizeof(fdf_txid_t)) != read.num_bytes) {
return false;
}
uint8_t* read_data_start = static_cast<uint8_t*>(read.data) + sizeof(fdf_txid_t);
if (memcmp(data_, read_data_start, data_size_) != 0) {
return false;
}
if (num_handles_ != read.handles.size()) {
return false;
}
return true;
}
void CloseHandles(const fdf::Channel::ReadReturn& read) {
for (const auto& h : read.handles) {
fdf_handle_close(h);
}
}
// Server implementation for channel call tests.
// Waits for |message_count| messages, and replies to the messages if |accumulated_messages|
// mnumber of messages has been received.
// If |wait_for_event| is provided, waits for the event to be signaled before returning.
template <uint32_t reply_data_size, uint32_t reply_handle_count, uint32_t accumulated_messages>
void ReplyAndWait(const Message& request, uint32_t message_count, fdf::Channel svc,
async::Loop* process_loop, std::atomic<const char*>* error,
zx::event* wait_for_event) {
// Make a separate dispatcher for the server.
int fake_driver; // For creating a fake pointer to the driver.
auto observer = std::make_unique<ChannelTest::DispatcherShutdownObserver>();
driver_runtime::Dispatcher* dispatcher;
ASSERT_EQ(ZX_OK, driver_runtime::Dispatcher::CreateWithLoop(
0, "scheduler_role", "", reinterpret_cast<void*>(&fake_driver), process_loop,
observer->fdf_observer(), &dispatcher));
auto fdf_dispatcher = static_cast<fdf_dispatcher_t*>(dispatcher);
auto shutdown = fit::defer([&, observer = std::move(observer)]() {
dispatcher->ShutdownAsync();
ASSERT_OK(observer->WaitUntilShutdown());
dispatcher->Destroy();
});
std::set<fdf_txid_t> live_ids;
std::vector<fdf::Channel::ReadReturn> live_requests;
for (uint32_t i = 0; i < message_count; ++i) {
ASSERT_NO_FATAL_FAILURE(RuntimeTestCase::WaitUntilReadReady(svc.get(), fdf_dispatcher));
auto read_return = svc.Read(0);
if (read_return.is_error()) {
*error = "Failed to read request.";
return;
}
if (!request.IsEquivalent(*read_return)) {
*error = "Failed to validate request.";
return;
}
CloseHandles(*read_return);
fdf_txid_t txid = *static_cast<fdf_txid_t*>(read_return->data);
if (live_ids.find(txid) != live_ids.end()) {
*error = "Repeated id used for live transaction.";
return;
}
live_ids.insert(txid);
live_requests.push_back(std::move(*read_return));
if (live_requests.size() < accumulated_messages) {
continue;
}
// We've collected |accumulated_messages|, so we reply to all pending messages.
for (const auto& req : live_requests) {
fdf_txid_t txid = *static_cast<fdf_txid_t*>(req.data);
Message reply = Message(reply_data_size, reply_handle_count);
zx_status_t status = reply.Write(svc, req.arena, txid);
if (status != ZX_OK) {
*error = "Failed to write reply.";
return;
}
}
live_requests.clear();
}
if (wait_for_event != nullptr) {
if (wait_for_event->wait_one(ZX_USER_SIGNAL_0, zx::time::infinite(), nullptr) != ZX_OK) {
*error = "Failed to wait for signal event.";
return;
}
}
}
template <uint32_t reply_data_size, uint32_t reply_handle_count, uint32_t accumulated_messages = 0>
void Reply(const Message& request, uint32_t message_count, fdf::Channel svc,
async::Loop* process_loop, std::atomic<const char*>* error) {
ReplyAndWait<reply_data_size, reply_handle_count, accumulated_messages>(
request, message_count, std::move(svc), process_loop, error, nullptr);
}
template <uint32_t reply_data_size, uint32_t reply_handle_count>
void SuccessfulChannelCall(fdf::Channel local, fdf::Channel remote, async::Loop* process_loop,
const fdf::Arena& arena, const Message& request) {
std::atomic<const char*> error = nullptr;
{
test_utils::AutoJoinThread service_thread(Reply<reply_data_size, reply_handle_count>, request,
1, std::move(remote), process_loop, &error);
auto read = request.Call(local, arena);
ASSERT_OK(read.status_value());
ASSERT_EQ(read->num_bytes, sizeof(fdf_txid_t) + reply_data_size);
ASSERT_EQ(read->handles.size(), reply_handle_count);
CloseHandles(*read);
}
if (error != nullptr) {
FAIL("Service Thread reported error: %s\n", error.load());
}
}
//
// Tests for fdf_channel_call
//
TEST_F(ChannelTest, CallBytesFitIsOk) {
constexpr uint32_t kReplyDataSize = 5;
constexpr uint32_t kReplyHandleCount = 0;
Message request(4, 0);
ASSERT_NO_FATAL_FAILURE((SuccessfulChannelCall<kReplyDataSize, kReplyHandleCount>(
std::move(local_), std::move(remote_), &loop_, arena_, request)));
}
TEST_F(ChannelTest, CallHandlesFitIsOk) {
constexpr uint32_t kReplyDataSize = 0;
constexpr uint32_t kReplyHandleCount = 2;
zx::event event;
ASSERT_OK(zx::event::create(0, &event));
zx_handle_t handles[1] = {event.release()};
Message request = Message(0, handles);
ASSERT_NO_FATAL_FAILURE((SuccessfulChannelCall<kReplyDataSize, kReplyHandleCount>(
std::move(local_), std::move(remote_), &loop_, arena_, request)));
}
TEST_F(ChannelTest, CallHandleAndBytesFitsIsOk) {
constexpr uint32_t kReplyDataSize = 2;
constexpr uint32_t kReplyHandleCount = 2;
zx::event event;
ASSERT_OK(zx::event::create(0, &event));
zx_handle_t handles[1] = {event.release()};
Message request = Message(2, handles);
ASSERT_NO_FATAL_FAILURE((SuccessfulChannelCall<kReplyDataSize, kReplyHandleCount>(
std::move(local_), std::move(remote_), &loop_, arena_, request)));
}
TEST_F(ChannelTest, CallManagedThreadAllowsSyncCalls) {
static constexpr uint32_t kNumBytes = 4;
void* data = arena_.Allocate(kNumBytes);
ASSERT_EQ(ZX_OK, fdf_channel_write(local_.get(), 0, arena_.get(), data, kNumBytes, NULL, 0));
// Create a dispatcher that allows sync calls.
auto driver = CreateFakeDriver();
DispatcherShutdownObserver dispatcher_observer;
driver_runtime::Dispatcher* allow_sync_calls_dispatcher;
ASSERT_EQ(ZX_OK, driver_runtime::Dispatcher::CreateWithLoop(
FDF_DISPATCHER_OPTION_ALLOW_SYNC_CALLS, "", "", driver, &loop_,
dispatcher_observer.fdf_observer(), &allow_sync_calls_dispatcher));
auto shutdown = fit::defer([&]() {
allow_sync_calls_dispatcher->ShutdownAsync();
ASSERT_OK(dispatcher_observer.WaitUntilShutdown());
allow_sync_calls_dispatcher->Destroy();
});
// Signaled once the Channel::Call completes.
sync_completion_t call_complete;
auto sync_channel_read = std::make_unique<fdf::ChannelRead>(
remote_.get(), 0,
[&](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, zx_status_t status) {
// This is now running on a managed thread that allows sync calls.
fdf::UnownedChannel unowned(channel_read->channel());
auto read = unowned->Read(0);
ASSERT_OK(read.status_value());
auto call = unowned->Call(0, zx::time::infinite(), arena_, data, kNumBytes,
cpp20::span<zx_handle_t>());
ASSERT_OK(call.status_value());
sync_completion_signal(&call_complete);
});
{
// Make the call non-reentrant.
// This will still run the callback on an async thread, as the dispatcher allows sync calls.
driver_context::PushDriver(driver);
auto pop_driver = fit::defer([]() { driver_context::PopDriver(); });
ASSERT_OK(sync_channel_read->Begin(static_cast<fdf_dispatcher*>(allow_sync_calls_dispatcher)));
}
// Wait for the call request and reply.
auto channel_read = std::make_unique<fdf::ChannelRead>(
local_.get(), 0,
[&](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, zx_status_t status) {
fdf::UnownedChannel unowned(channel_read->channel());
auto read = unowned->Read(0);
ASSERT_OK(read.status_value());
ASSERT_EQ(read->num_bytes, kNumBytes);
fdf_txid_t* txid = static_cast<fdf_txid_t*>(read->data);
// Write a reply with the same txid.
void* reply = read->arena.Allocate(sizeof(fdf_txid_t));
memcpy(reply, txid, sizeof(fdf_txid_t));
auto write =
unowned->Write(0, read->arena, reply, sizeof(fdf_txid_t), cpp20::span<zx_handle_t>());
ASSERT_OK(write.status_value());
});
ASSERT_OK(channel_read->Begin(fdf_dispatcher_));
sync_completion_wait(&call_complete, ZX_TIME_INFINITE);
}
TEST_F(ChannelTest, CallPendingTransactionsUseDifferentIds) {
constexpr uint32_t kReplyDataSize = 0;
constexpr uint32_t kReplyHandleCount = 0;
// The service thread will wait until |kAcummulatedMessages| have been read from the channel
// before replying in the same order they came through.
constexpr uint32_t kAccumulatedMessages = 20;
std::atomic<const char*> error = nullptr;
std::vector<zx_status_t> call_result(kAccumulatedMessages, ZX_OK);
Message request(2, 0);
fdf::Channel local = std::move(local_);
{
test_utils::AutoJoinThread service_thread(
Reply<kReplyDataSize, kReplyHandleCount, kAccumulatedMessages>, request,
kAccumulatedMessages, std::move(remote_), &loop_, &error);
std::vector<test_utils::AutoJoinThread> calling_threads;
calling_threads.reserve(kAccumulatedMessages);
for (uint32_t i = 0; i < kAccumulatedMessages; ++i) {
calling_threads.push_back(
test_utils::AutoJoinThread([i, &call_result, &local, &request, this]() {
auto read_return = request.Call(local, arena_);
call_result[i] = read_return.status_value();
}));
}
}
for (auto call_status : call_result) {
EXPECT_OK(call_status, "channel::call failed in client thread.");
}
if (error != nullptr) {
FAIL("Service Thread reported error: %s\n", error.load());
}
}
TEST_F(ChannelTest, CallDeadlineExceededReturnsTimedOut) {
constexpr uint32_t kReplyDataSize = 0;
constexpr uint32_t kReplyHandleCount = 0;
constexpr uint32_t kAccumulatedMessages = 2;
std::atomic<const char*> error = nullptr;
zx::event event;
ASSERT_OK(zx::event::create(0, &event));
Message request = Message(2, 0);
{
// We pass in accumulated_messages > message_count, so the server will read
// the message without replying.
test_utils::AutoJoinThread service_thread(
ReplyAndWait<kReplyDataSize, kReplyHandleCount, kAccumulatedMessages>, request,
kAccumulatedMessages - 1 /* message_count */, std::move(remote_), &loop_, &error, &event);
auto read_return = request.Call(local_, arena_, zx::time::infinite_past());
ASSERT_EQ(ZX_ERR_TIMED_OUT, read_return.status_value());
// Signal the server to quit.
event.signal(0, ZX_USER_SIGNAL_0);
}
if (error != nullptr) {
FAIL("Service Thread reported error: %s\n", error.load());
}
}
//
// Tests for fdf_channel_write error conditions
//
TEST_F(ChannelTest, WriteToClosedHandle) {
local_.reset();
ASSERT_DEATH([&] {
EXPECT_EQ(ZX_ERR_BAD_HANDLE,
fdf_channel_write(local_.get(), 0, nullptr, nullptr, 0, nullptr, 0));
});
}
// Tests providing a close handle as part of a channel message.
TEST_F(ChannelTest, WriteClosedHandle) {
fdf_handle_t closed_ch;
fdf_handle_t additional_ch;
ASSERT_EQ(ZX_OK, fdf_channel_create(0, &closed_ch, &additional_ch));
fdf_handle_close(closed_ch);
void* handles_buf = arena_.Allocate(sizeof(fdf_handle_t));
ASSERT_NOT_NULL(handles_buf);
fdf_handle_t* handles = reinterpret_cast<fdf_handle_t*>(handles_buf);
handles[0] = closed_ch;
EXPECT_EQ(ZX_ERR_INVALID_ARGS,
fdf_channel_write(local_.get(), 0, arena_.get(), nullptr, 0, handles, 1));
fdf_handle_close(additional_ch);
}
// Tests providing non arena-managed data in a channel message.
TEST_F(ChannelTest, WriteNonManagedData) {
uint8_t data[100];
ASSERT_EQ(ZX_ERR_INVALID_ARGS,
fdf_channel_write(local_.get(), 0, arena_.get(), data, 100, NULL, 0));
}
// Tests providing a non arena-managed handles array in a channel message.
TEST_F(ChannelTest, WriteNonManagedHandles) {
fdf_handle_t transfer_ch;
fdf_handle_t additional_ch;
ASSERT_EQ(ZX_OK, fdf_channel_create(0, &transfer_ch, &additional_ch));
EXPECT_EQ(ZX_ERR_INVALID_ARGS,
fdf_channel_write(local_.get(), 0, arena_.get(), nullptr, 0, &transfer_ch, 1));
fdf_handle_close(transfer_ch);
fdf_handle_close(additional_ch);
}
// Tests writing to the channel after the peer has closed their end.
TEST_F(ChannelTest, WriteClosedPeer) {
local_.reset();
void* data = arena_.Allocate(64);
ASSERT_EQ(ZX_ERR_PEER_CLOSED,
fdf_channel_write(remote_.get(), 0, arena_.get(), data, 64, NULL, 0));
}
TEST_F(ChannelTest, WriteSelfHandleReturnsNotSupported) {
void* handles_buf = arena_.Allocate(sizeof(fdf_handle_t));
ASSERT_NOT_NULL(handles_buf);
fdf_handle_t* handles = reinterpret_cast<fdf_handle_t*>(handles_buf);
handles[0] = local_.get();
EXPECT_EQ(ZX_ERR_NOT_SUPPORTED,
fdf_channel_write(local_.get(), 0, arena_.get(), nullptr, 0, handles, 1));
}
TEST_F(ChannelTest, WriteWaitedHandle) {
fdf_handle_t local;
fdf_handle_t remote;
ASSERT_EQ(ZX_OK, fdf_channel_create(0, &local, &remote));
auto channel_read_ = std::make_unique<fdf::ChannelRead>(
remote, 0 /* options */,
[](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, zx_status_t status) {});
ASSERT_OK(channel_read_->Begin(fdf_dispatcher_));
void* handles_buf = arena_.Allocate(sizeof(fdf_handle_t));
ASSERT_NOT_NULL(handles_buf);
fdf_handle_t* handles = reinterpret_cast<fdf_handle_t*>(handles_buf);
handles[0] = remote;
ASSERT_NOT_OK(fdf_channel_write(local_.get(), 0, arena_.get(), nullptr, 0, handles, 1));
fdf_handle_close(local);
fdf_handle_close(remote);
}
//
// Tests for fdf_channel_read error conditions
//
// Tests reading from a closed channel handle.
TEST_F(ChannelTest, ReadToClosedHandle) {
local_.reset();
ASSERT_DEATH([&] {
EXPECT_EQ(ZX_ERR_BAD_HANDLE,
fdf_channel_read(local_.get(), 0, nullptr, nullptr, 0, nullptr, 0));
});
}
TEST_F(ChannelTest, ReadNullArenaWithData) {
void* data = arena_.Allocate(64);
ASSERT_EQ(ZX_OK, fdf_channel_write(local_.get(), 0, arena_.get(), data, 64, NULL, 0));
ASSERT_NO_FATAL_FAILURE(WaitUntilReadReady(remote_.get()));
void* out_data;
uint32_t num_bytes;
ASSERT_EQ(ZX_ERR_INVALID_ARGS,
fdf_channel_read(remote_.get(), 0, nullptr, &out_data, &num_bytes, nullptr, 0));
}
TEST_F(ChannelTest, ReadNullArenaWithHandles) {
fdf_handle_t transfer_ch_local;
fdf_handle_t transfer_ch_remote;
ASSERT_EQ(ZX_OK, fdf_channel_create(0, &transfer_ch_local, &transfer_ch_remote));
void* handles_buf = arena_.Allocate(sizeof(fdf_handle_t));
ASSERT_NOT_NULL(handles_buf);
fdf_handle_t* handles = reinterpret_cast<fdf_handle_t*>(handles_buf);
handles[0] = transfer_ch_remote;
ASSERT_EQ(ZX_OK, fdf_channel_write(local_.get(), 0, arena_.get(), nullptr, 0, handles, 1));
ASSERT_NO_FATAL_FAILURE(WaitUntilReadReady(remote_.get()));
fdf_handle_t* read_handles;
uint32_t num_handles;
EXPECT_EQ(ZX_ERR_INVALID_ARGS, fdf_channel_read(remote_.get(), 0, nullptr, nullptr, nullptr,
&read_handles, &num_handles));
fdf_handle_close(transfer_ch_local);
// We do not need to to close the transferred handle, as it is consumed by |fdf_channel_write|.
}
// Tests reading from the channel before any message has been sent.
TEST_F(ChannelTest, ReadWhenEmptyReturnsShouldWait) {
fdf_arena_t* arena;
void* data;
uint32_t num_bytes;
ASSERT_EQ(ZX_ERR_SHOULD_WAIT,
fdf_channel_read(local_.get(), 0, &arena, &data, &num_bytes, nullptr, 0));
}
TEST_F(ChannelTest, ReadWhenEmptyAndClosedReturnsPeerClosed) {
remote_.reset();
fdf_arena_t* arena;
void* data;
uint32_t num_bytes;
ASSERT_EQ(ZX_ERR_PEER_CLOSED,
fdf_channel_read(local_.get(), 0, &arena, &data, &num_bytes, nullptr, 0));
}
// Tests reading from the channel after the peer has closed their end.
TEST_F(ChannelTest, ReadClosedPeer) {
local_.reset();
ASSERT_EQ(ZX_ERR_PEER_CLOSED,
fdf_channel_read(remote_.get(), 0, nullptr, nullptr, 0, nullptr, 0));
}
//
// Tests for fdf_channel_wait_async error conditions
//
TEST_F(ChannelTest, WaitAsyncClosedPeerNoPendingMsgs) {
local_.reset();
auto channel_read_ = std::make_unique<fdf::ChannelRead>(
remote_.get(), 0 /* options */,
[](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, zx_status_t status) {});
EXPECT_EQ(ZX_ERR_PEER_CLOSED, channel_read_->Begin(fdf_dispatcher_));
}
TEST_F(ChannelTest, WaitAsyncAlreadyWaiting) {
auto channel_read_ = std::make_unique<fdf::ChannelRead>(
local_.get(), 0 /* options */,
[](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, zx_status_t status) {});
EXPECT_OK(channel_read_->Begin(fdf_dispatcher_));
auto channel_read2_ = std::make_unique<fdf::ChannelRead>(
local_.get(), 0 /* options */,
[](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, zx_status_t status) {});
EXPECT_EQ(ZX_ERR_BAD_STATE, channel_read2_->Begin(fdf_dispatcher_));
EXPECT_OK(fdf_channel_write(remote_.get(), 0, nullptr, nullptr, 0, nullptr, 0));
ASSERT_NO_FATAL_FAILURE(WaitUntilReadReady(local_.get()));
}
//
// Tests for fdf_channel_call error conditions
//
TEST_F(ChannelTest, CallWrittenBytesSmallerThanFdfTxIdReturnsInvalidArgs) {
constexpr uint32_t kDataSize = sizeof(fdf_txid_t) - 1;
void* data = arena_.Allocate(kDataSize);
auto read =
local_.Call(0, zx::time::infinite(), arena_, data, kDataSize, cpp20::span<zx_handle_t>());
EXPECT_EQ(ZX_ERR_INVALID_ARGS, read.status_value());
}
TEST_F(ChannelTest, CallToClosedHandle) {
constexpr uint32_t kDataSize = sizeof(fdf_txid_t);
void* data = arena_.Allocate(kDataSize);
local_.reset();
ASSERT_DEATH([&] {
auto read =
local_.Call(0, zx::time::infinite(), arena_, data, kDataSize, cpp20::span<zx_handle_t>());
ASSERT_EQ(ZX_ERR_BAD_HANDLE, read.status_value());
});
}
// Tests providing a closed handle as part of a channel message.
TEST_F(ChannelTest, CallTransferClosedHandle) {
constexpr uint32_t kDataSize = sizeof(fdf_txid_t);
void* data = arena_.Allocate(kDataSize);
auto channels = fdf::ChannelPair::Create(0);
ASSERT_OK(channels.status_value());
void* handles_buf = arena_.Allocate(sizeof(fdf_handle_t));
ASSERT_NOT_NULL(handles_buf);
fdf_handle_t* handles = reinterpret_cast<fdf_handle_t*>(handles_buf);
handles[0] = channels->end0.get();
channels->end0.reset();
auto read = local_.Call(0, zx::time::infinite(), arena_, data, kDataSize,
cpp20::span<zx_handle_t>(handles, 1));
EXPECT_EQ(ZX_ERR_INVALID_ARGS, read.status_value());
}
// Tests providing non arena-managed data in a channel message.
TEST_F(ChannelTest, CallTransferNonManagedData) {
constexpr uint32_t kDataSize = sizeof(fdf_txid_t);
uint8_t data[kDataSize];
auto read =
local_.Call(0, zx::time::infinite(), arena_, data, kDataSize, cpp20::span<zx_handle_t>());
ASSERT_EQ(ZX_ERR_INVALID_ARGS, read.status_value());
}
// Tests providing a non arena-managed handles array in a channel message.
TEST_F(ChannelTest, CallTransferNonManagedHandles) {
constexpr uint32_t kDataSize = sizeof(fdf_txid_t);
void* data = arena_.Allocate(kDataSize);
auto channels = fdf::ChannelPair::Create(0);
ASSERT_OK(channels.status_value());
fdf_handle_t handle = channels->end0.get();
auto read = local_.Call(0, zx::time::infinite(), arena_, data, kDataSize,
cpp20::span<zx_handle_t>(&handle, 1));
EXPECT_EQ(ZX_ERR_INVALID_ARGS, read.status_value());
}
// Tests writing to the channel after the peer has closed their end.
TEST_F(ChannelTest, CallClosedPeer) {
constexpr uint32_t kDataSize = sizeof(fdf_txid_t);
void* data = arena_.Allocate(kDataSize);
fdf_handle_close(remote_.release());
auto read =
local_.Call(0, zx::time::infinite(), arena_, data, kDataSize, cpp20::span<zx_handle_t>());
ASSERT_EQ(ZX_ERR_PEER_CLOSED, read.status_value());
}
TEST_F(ChannelTest, CallTransferSelfHandleReturnsNotSupported) {
constexpr uint32_t kDataSize = sizeof(fdf_txid_t);
void* data = arena_.Allocate(kDataSize);
void* handles_buf = arena_.Allocate(sizeof(fdf_handle_t));
ASSERT_NOT_NULL(handles_buf);
fdf_handle_t* handles = reinterpret_cast<fdf_handle_t*>(handles_buf);
handles[0] = local_.get();
auto read = local_.Call(0, zx::time::infinite(), arena_, data, kDataSize,
cpp20::span<zx_handle_t>(handles, 1));
EXPECT_EQ(ZX_ERR_NOT_SUPPORTED, read.status_value());
}
TEST_F(ChannelTest, CallTransferWaitedHandle) {
constexpr uint32_t kDataSize = sizeof(fdf_txid_t);
void* data = arena_.Allocate(kDataSize);
auto channels = fdf::ChannelPair::Create(0);
ASSERT_OK(channels.status_value());
auto channel_read_ = std::make_unique<fdf::ChannelRead>(
channels->end0.get(), 0 /* options */,
[](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, zx_status_t status) {
ASSERT_EQ(status, ZX_ERR_PEER_CLOSED);
delete channel_read;
});
ASSERT_OK(channel_read_->Begin(fdf_dispatcher_));
channel_read_.release(); // Deleted on callback.
void* handles_buf = arena_.Allocate(sizeof(fdf_handle_t));
ASSERT_NOT_NULL(handles_buf);
fdf_handle_t* handles = reinterpret_cast<fdf_handle_t*>(handles_buf);
handles[0] = channels->end0.get();
auto read = local_.Call(0, zx::time::infinite(), arena_, data, kDataSize,
cpp20::span<zx_handle_t>(handles, 1));
EXPECT_EQ(ZX_ERR_INVALID_ARGS, read.status_value());
}
TEST_F(ChannelTest, CallConsumesHandlesOnError) {
constexpr uint32_t kDataSize = sizeof(fdf_txid_t);
void* data = arena_.Allocate(kDataSize);
constexpr uint32_t kNumHandles = 2;
// Create some handles to transfer.
zx::event event;
ASSERT_OK(zx::event::create(0, &event));
zx::event event2;
ASSERT_OK(zx::event::create(0, &event2));
void* handles_buf = arena_.Allocate(kNumHandles * sizeof(fdf_handle_t));
ASSERT_NOT_NULL(handles_buf);
fdf_handle_t* handles = reinterpret_cast<fdf_handle_t*>(handles_buf);
handles[0] = event.release();
handles[1] = event2.release();
// Close the remote end of the channel so the call will fail.
remote_.reset();
auto read = local_.Call(0, zx::time::infinite(), arena_, data, kDataSize,
cpp20::span<zx_handle_t>(handles, kNumHandles));
EXPECT_EQ(ZX_ERR_PEER_CLOSED, read.status_value());
for (uint32_t i = 0; i < kNumHandles; i++) {
ASSERT_EQ(ZX_ERR_BAD_HANDLE, zx_handle_close(handles[i]));
}
}
TEST_F(ChannelTest, CallNotifiedOnPeerClosed) {
constexpr uint32_t kDataSize = sizeof(fdf_txid_t);
void* data = arena_.Allocate(kDataSize);
{
test_utils::AutoJoinThread service_thread(
[&](fdf::Channel svc) {
// Make the call non-reentrant.
driver_context::PushDriver(CreateFakeDriver());
// Wait until call message is received.
ASSERT_NO_FATAL_FAILURE(WaitUntilReadReady(svc.get()));
// Close the peer.
svc.reset();
},
std::move(remote_));
auto read =
local_.Call(0, zx::time::infinite(), arena_, data, kDataSize, cpp20::span<zx_handle_t>());
EXPECT_EQ(ZX_ERR_PEER_CLOSED, read.status_value());
}
}
TEST_F(ChannelTest, CallManagedThreadDisallowsSyncCalls) {
static constexpr uint32_t kNumBytes = 4;
void* data = arena_.Allocate(kNumBytes);
ASSERT_EQ(ZX_OK, fdf_channel_write(local_.get(), 0, arena_.get(), data, kNumBytes, NULL, 0));
auto channel_read = std::make_unique<fdf::ChannelRead>(
remote_.get(), 0,
[&](fdf_dispatcher_t* dispatcher, fdf::ChannelRead* channel_read, zx_status_t status) {
fdf::UnownedChannel unowned(channel_read->channel());
auto read = unowned->Read(0);
ASSERT_OK(read.status_value());
auto call = unowned->Call(0, zx::time::infinite(), arena_, data, kNumBytes,
cpp20::span<zx_handle_t>());
ASSERT_EQ(ZX_ERR_BAD_STATE, call.status_value());
});
ASSERT_OK(channel_read->Begin(fdf_dispatcher_));
}
//
// Tests for C++ API
//
TEST_F(ChannelTest, MoveConstructor) {
auto channels = fdf::ChannelPair::Create(0);
ASSERT_EQ(ZX_OK, channels.status_value());
local_ = std::move(channels->end0);
remote_ = std::move(channels->end1);
local_.reset();
remote_.reset();
ASSERT_EQ(0, driver_runtime::gHandleTableArena.num_allocated());
}
TEST_F(ChannelTest, CloseZirconChannel) {
zx_handle_t local_handle, remote_handle;
{
zx::channel local;
zx::channel remote;
ASSERT_OK(zx::channel::create(0, &local, &remote));
local_handle = local.get();
remote_handle = remote.get();
fdf::Channel fdf_local(local.release());
fdf::Channel fdf_remote(remote.release());
}
ASSERT_EQ(ZX_ERR_BAD_HANDLE,
zx_object_get_info(local_handle, ZX_INFO_HANDLE_VALID, nullptr, 0, nullptr, nullptr));
ASSERT_EQ(ZX_ERR_BAD_HANDLE,
zx_object_get_info(remote_handle, ZX_INFO_HANDLE_VALID, nullptr, 0, nullptr, nullptr));
}
TEST(ChannelTest, IsValid) {
fdf::Channel invalid_channel;
ASSERT_FALSE(invalid_channel.is_valid());
auto channels = fdf::ChannelPair::Create(0);
ASSERT_TRUE(channels->end0.is_valid());
channels->end0.close();
ASSERT_FALSE(channels->end0.is_valid());
}
TEST(ChannelTest2, CreateAllThePairs) {
static constexpr uint32_t kNumIterations = 100000;
for (uint32_t i = 0; i < kNumIterations; i++) {
auto channels = fdf::ChannelPair::Create(0);
ASSERT_TRUE(channels->end0.is_valid());
ASSERT_TRUE(channels->end1.is_valid());
}
}
TEST(UnownedChannelTest, Equality) {
fdf::UnownedChannel c1;
fdf::UnownedChannel c2;
EXPECT_TRUE(c1 == c2);
EXPECT_FALSE(c1 != c2);
EXPECT_FALSE(c1 > c2);
EXPECT_FALSE(c1 < c2);
EXPECT_TRUE(c1 >= c2);
EXPECT_TRUE(c1 <= c2);
}
TEST(UnownedChannelTest, Comparison) {
zx::result channels = fdf::ChannelPair::Create(0);
ASSERT_EQ(ZX_OK, channels.status_value());
fdf::Channel c = std::move(channels->end0);
fdf::UnownedChannel unowned_valid{c};
fdf::UnownedChannel unowned_default;
EXPECT_FALSE(unowned_valid == unowned_default);
EXPECT_TRUE(unowned_valid != unowned_default);
EXPECT_TRUE(unowned_valid > unowned_default);
EXPECT_FALSE(unowned_valid < unowned_default);
EXPECT_TRUE(unowned_valid >= unowned_default);
EXPECT_FALSE(unowned_valid <= unowned_default);
}
TEST_F(ChannelTest, Borrow) {
auto channels = fdf::ChannelPair::Create(0);
ASSERT_EQ(ZX_OK, channels.status_value());
fdf::Channel ch = std::move(channels->end0);
fdf::UnownedChannel unowned = ch.borrow();
ASSERT_EQ(unowned->get(), ch.get());
unowned = {};
// Handle is not closed. Writing succeeds.
void* data = arena_.Allocate(64);
ASSERT_EQ(ZX_OK, fdf_channel_write(channels->end1.get(), 0, arena_.get(), data, 64, NULL, 0));
}
|
142faf1962aa786dd6a1183e43adee63eea737f3 | 7c0e94dcd26b97bc79e007ccd6506df855a6869c | /ValueLabsAssignment/TChartfiles/gaugehands.cpp | cab244a82519187a7ddb63319795a091f0b57dc1 | [] | no_license | syedmobashir/SalesReportSample | 065f959e65c87bb1f67a9f9510911b738c30ee92 | 24c4561024cb6ffd984f69c4a0b9a47d5984f28d | refs/heads/master | 2020-06-06T14:15:00.574299 | 2019-06-19T17:25:37 | 2019-06-19T17:25:37 | 192,759,993 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 989 | cpp | gaugehands.cpp | // Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++
// NOTE: Do not modify the contents of this file. If this class is regenerated by
// Microsoft Visual C++, your modifications will be overwritten.
#include "stdafx.h"
#include "gaugehands.h"
// Dispatch interfaces referenced by this interface
#include "gaugehanditem.h"
/////////////////////////////////////////////////////////////////////////////
// CGaugeHands properties
/////////////////////////////////////////////////////////////////////////////
// CGaugeHands operations
CGaugeHandItem CGaugeHands::GetItems(long AIndex)
{
LPDISPATCH pDispatch;
static BYTE parms[] =
VTS_I4;
InvokeHelper(0xc9, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, parms,
AIndex);
return CGaugeHandItem(pDispatch);
}
long CGaugeHands::Add(double AValue)
{
long result;
static BYTE parms[] =
VTS_R8;
InvokeHelper(0xca, DISPATCH_METHOD, VT_I4, (void*)&result, parms,
AValue);
return result;
}
|
29a3b7c9f5ae147f5b00a32ff258b50fab1ab0a7 | 1b9a32ea5f2492fd3512965f92e0f057b0528d33 | /Bulb_Switcher_III.cpp | f4fb9aa5830973d8b848f00ac84059a5b8ba1910 | [] | no_license | shivangigoel1302/leetcode_solutions | a459a4279ffcfa889cf1fe0e8eb681e4e79186b6 | 3373f9710bd797bcda5cbd86958e8914ba9e2a15 | refs/heads/master | 2023-08-23T04:18:26.678630 | 2021-11-01T14:57:21 | 2021-11-01T14:57:21 | 274,206,300 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 365 | cpp | Bulb_Switcher_III.cpp | class Solution {
public:
int numTimesAllBlue(vector<int>& light) {
int ans = 0;
int bulbs = 0;
int maximum = 0;
for(int i = 0 ; i < light.size(); i++){
maximum = max(maximum, light[i]);
bulbs++;
if(maximum == bulbs){
ans++;
}
}
return ans;
}
};
|
2c77f1cae0fcbc653a91a3c28a043819d4743899 | 4081245b8ed21b053664ebd66340db8d38ab8c4f | /HuffmanCodingHACKERRANK.cpp | c6bbd9f23c2c6af3ee0bf598be936b348a5f7020 | [] | no_license | anandaditya444/LEETCODE | 5240f0adf1df6a87747e00842f87566b0df59f92 | 82e597c21efa965cfe9e75254011ce4f49c2de36 | refs/heads/master | 2020-05-07T15:48:19.081727 | 2019-08-25T16:03:57 | 2019-08-25T16:03:57 | 180,653,012 | 2 | 1 | null | 2019-10-05T13:45:29 | 2019-04-10T19:48:40 | C++ | UTF-8 | C++ | false | false | 358 | cpp | HuffmanCodingHACKERRANK.cpp | string ans = "";
void decode_huff(node * root, string s) {
node* cur = root;
for(int i=0;i<s.length();i++)
{
if(s[i] == '0')
cur = cur->left;
else
cur = cur->right;
if(!cur->left && !cur->right)
{
ans += cur->data;
cur = root;
}
}
cout<<ans<<endl;
} |
518a39d0921ea97b051791040b4eccfa62de784d | d5610507bc33bdaecb370f913b61d6bb7e028da4 | /Ray.cpp | 3047a1b393a49cef52a8d6400ebe9825e2d105d0 | [] | no_license | gpcucb/RayTracing-Vinze_Gonzales | 95fe983154ac75361ad2eb2476d08b6424462c5b | 974261ad237a198d4582216a5ad836ebadffad47 | refs/heads/master | 2021-01-18T16:42:43.533416 | 2017-03-30T23:07:51 | 2017-03-30T23:07:51 | 86,756,866 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 279 | cpp | Ray.cpp | //
// Ray.cpp
// RayTracing
//
// Created by Vinze Gonzales on 3/29/17.
// Copyright © 2017 Vinze. All rights reserved.
//
#include "Ray.hpp"
Ray::Ray(Vector position, Vector direction)
{
this->position=position;
this->direction=direction;
}
Ray::~Ray()
{
}
|
d19557f12eda1101f8fd6031f08c7102bec20779 | 7e7a3cd90fdeb556dd3459eb5e6a8f68a0718d1d | /GBemu/gb/input/GbInput.cpp | e769b58a5da00e28b0aab8a18b3704a6c0ef4493 | [
"Apache-2.0"
] | permissive | robojan/EmuAll | 7d3c792fce79db4b10613b93f0a0a7c23f42a530 | 0a589136df9fefbfa142e605e1d3a0c94f726bad | refs/heads/master | 2021-01-21T04:50:46.603365 | 2016-07-22T10:44:18 | 2016-07-22T10:44:18 | 44,864,341 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,845 | cpp | GbInput.cpp | #include "../../util/memDbg.h"
#include "GbInput.h"
GbInput::GbInput(Gameboy *master)
{
_gb = master;
_u = false;
_d = false;
_l = false;
_r = false;
_a = false;
_b = false;
_st = false;
_se = false;
}
GbInput::~GbInput()
{
}
void GbInput::update()
{
if (_gb == NULL || _gb->_mem == NULL)
{
return;
}
gbByte joyp = _gb->_mem->read(JOYP);
joyp &= 0xF0;
joyp |= 0xCF;
if((joyp & BUTTON_KEYS) == 0)
{
if(_st) joyp &= ~J_START;
if(_se) joyp &= ~J_SELECT;
if(_a) joyp &= ~J_A;
if(_b) joyp &= ~J_B;
}
if((joyp & DIR_KEYS) == 0)
{
if(_d) joyp &= ~J_DOWN;
if(_u) joyp &= ~J_UP;
if(_l) joyp &= ~J_LEFT;
if(_r) joyp &= ~J_RIGHT;
}
_gb->_mem->write(JOYP, joyp, false);
}
void GbInput::registerEvents()
{
if (_gb != NULL && _gb->_mem != NULL)
{
_gb->_mem->registerEvent(JOYP, this);
}
}
void GbInput::MemEvent(address_t address, gbByte val)
{
if(address == JOYP)
{
update();
}
}
void GbInput::Input(int key, bool pressed)
{
bool interrupt = false;
switch(key)
{
case INPUT_U:
_u = pressed;
interrupt = true;
break;
case INPUT_D:
_d = pressed;
interrupt = true;
break;
case INPUT_L:
_l = pressed;
interrupt = true;
break;
case INPUT_R:
_r = pressed;
interrupt = true;
break;
case INPUT_B:
_b = pressed;
interrupt = true;
break;
case INPUT_A:
_a = pressed;
interrupt = true;
break;
case INPUT_START:
_st = pressed;
interrupt = true;
break;
case INPUT_SELECT:
_se = pressed;
interrupt = true;
break;
}
if(interrupt)
{
_gb->_mem->write(IF, _gb->_mem->read(IF) | INT_JOYPAD);
}
update();
}
static const uint32_t StateINPTid = 0x494e5054;
// 0 - id
// 4 - size
// 8 - input
// 9 -
bool GbInput::LoadState(const SaveData_t *data)
{
Endian conv(false);
uint8_t *ptr = (uint8_t *)data->miscData;
size_t miscLen = data->miscDataLen;
// Find cpu segment
while (miscLen >= 8) {
uint32_t id = conv.convu32(*(uint32_t *)(ptr + 0));
uint32_t len = conv.convu32(*(uint32_t *)(ptr + 4));
if (id == StateINPTid && len >= 9) {
_u = (ptr[8] & 0x01) != 0;
_d = (ptr[8] & 0x02) != 0;
_l = (ptr[8] & 0x04) != 0;
_r = (ptr[8] & 0x08) != 0;
_a = (ptr[8] & 0x10) != 0;
_b = (ptr[8] & 0x20) != 0;
_se = (ptr[8] & 0x40) != 0;
_st = (ptr[8] & 0x80) != 0;
return true;
}
ptr += len;
miscLen -= len;
}
return false;
}
bool GbInput::SaveState(std::vector<uint8_t> &data)
{
Endian conv(false);
int dataLen = 9;
data.resize(data.size() + dataLen);
uint8_t *ptr = data.data() + data.size() - dataLen;
*(uint32_t *)(ptr + 0) = conv.convu32(StateINPTid);
*(uint32_t *)(ptr + 4) = conv.convu32(dataLen);
ptr[8] =
(_u ? 0x01 : 0x00) |
(_d ? 0x02 : 0x00) |
(_l ? 0x04 : 0x00) |
(_r ? 0x08 : 0x00) |
(_a ? 0x10 : 0x00) |
(_b ? 0x20 : 0x00) |
(_se ? 0x40 : 0x00) |
(_st ? 0x80 : 0x00);
return true;
} |
9fac6c4f371a9c2a1a75af5a9a05e80cb0c80147 | 742645689a39625f5d694586177542a920bd8e99 | /lib/raylibCpp/src/Audio/IAudio.hpp | 7470b0c92dcb63e0b2677bb9823dac54134ff30d | [] | no_license | aurelienjoncour/Bombercraft | a2653cc1d2df5440276a414f1636d940a732431e | 1821bf9f6fd4a743a753fc672e0f291091c5a830 | refs/heads/master | 2023-06-05T20:07:58.919298 | 2021-06-22T09:16:54 | 2021-06-22T09:16:54 | 378,857,284 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 675 | hpp | IAudio.hpp | /*
** EPITECH PROJECT, 2021
** IndieStudio
** File description:
** IAudio
*/
#ifndef IAUDIO_HPP
#define IAUDIO_HPP
#include "../../include/object.hpp"
namespace raylib
{
class IAudio {
public:
virtual ~IAudio() = default;
virtual void play() = 0;
virtual void stop() = 0;
virtual void resume() = 0;
virtual void pause() = 0;
virtual void update() = 0;
virtual bool isPlaying() const = 0;
virtual void setPath(const string &path) = 0;
virtual void setVolume(const float volume) = 0;
virtual void setPitch(const float pitch) = 0;
};
}; // namespace raylib
#endif // IAUDIO_HPP |
1024b2ed438913cab1196812f995e28730cd2863 | c130d34827720a6f22319c02028a56531b2b6fa1 | /Source/MapNode.cpp | ac5ae216c666d8cd9bea475c9670b92486188f44 | [] | no_license | 88Fuzz/Paths | 2075b45827facbbe7c0b2da8edd6f52e6b21b5ef | 334cbc0f62b07098c519beaceffffd23c912259b | refs/heads/master | 2021-05-01T01:06:33.674632 | 2016-04-19T02:35:11 | 2016-04-19T02:35:11 | 33,108,780 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,967 | cpp | MapNode.cpp | #include "MapNode.hpp"
#include <iostream>
MapNode::MapNode() :
MapNode(0, 0, 0, 0, MapNode::Type::NONE)
{
}
MapNode::MapNode(int x, int y, int width, int height, MapNode::Type type) :
SceneNode(),
gValue(0),
hValue(0),
parentPathNode(NULL),
childPathNode(NULL),
tileWidth(width),
tileHeight(height)
{
pos = sf::Vector2f(x * width, y * height);
rect.setPosition(pos.x, pos.y);
rect.setSize(sf::Vector2f(width - 1, height - 1));
rect.setOutlineColor(sf::Color::Black);
setType(type);
}
MapNode::~MapNode()
{
}
sf::Vector2f MapNode::getPosition()
{
return pos;
}
sf::Vector2f MapNode::getTilePosition()
{
sf::Vector2f tmpPos = sf::Vector2f(pos.x / tileWidth, pos.y / tileHeight);
return tmpPos;
}
sf::Vector2f MapNode::getCenteredPosition()
{
sf::Vector2f tmpPos = sf::Vector2f(pos.x + tileWidth/2, pos.y + tileHeight/2);
return tmpPos;
}
//TODO decide if this should be returning an int or a float
int MapNode::getTileWidth()
{
return tileWidth;
}
//TODO decide if this should be returning an int or a float
int MapNode::getTileHeight()
{
return tileHeight;
}
void MapNode::drawCurrent(sf::RenderTarget& target, sf::RenderStates states) const
{
target.draw(rect);
}
MapNode::Type MapNode::getType()
{
return nodeType;
}
void MapNode::setType(MapNode::Type type)
{
nodeType = type;
rect.setFillColor(getTypeColor(type));
}
sf::Color MapNode::getTypeColor(MapNode::Type type)
{
switch(type)
{
case MapNode::Type::REGULAR:
//GREEN
return sf::Color(0x00, 0x99, 0x00);
case MapNode::Type::START:
//RED
return sf::Color(0xFF, 0x00, 0x00);
case MapNode::Type::END:
//YELLOw
return sf::Color(0xFF, 0xFF, 0x00);
case MapNode::Type::PATH:
//ORANGE
return sf::Color(0xFF, 0x80, 0x00);
case MapNode::Type::OPEN:
//CYAN
return sf::Color(0x00, 0xFF, 0xFF);
case MapNode::Type::CLOSED:
//PURPLE
return sf::Color(0x7F, 0x00, 0xFF);
case MapNode::Type::BLOCK:
//BLACK
return sf::Color(0x00, 0x00, 0x00);
case MapNode::Type::NONE:
default:
//CLEAR
return sf::Color(0x00, 0x00, 0x00, 0x00);
}
}
float MapNode::getFValue()
{
return gValue + hValue;
}
float MapNode::getDistanceFromStart()
{
return gValue;
}
float MapNode::getDistanceToEnd()
{
return hValue;
}
void MapNode::setDistanceFromStart(float value)
{
gValue = value;
}
void MapNode::setDistanceToEnd(float value)
{
hValue = value;
}
void MapNode::setParentPathNode(MapNode *node)
{
parentPathNode = node;
}
MapNode * MapNode::getParentPathNode()
{
return parentPathNode;
}
MapNode *MapNode::getChildPathNode()
{
return childPathNode;
}
void MapNode::setChildPathNode(MapNode *node)
{
childPathNode = node;
}
|
a64a56b786b4761ab4e0dd542693dbdcbdaef5ac | 6bc77fafc7d3a2c423e2f69f57db319cae1740a8 | /Commands/PoleCommand.h | 3a8bc828334c304c874329eb1899f3d224a9df3c | [
"MIT"
] | permissive | nielslanting/spin | d83e89b84ec6b35234b927fb910404ee8b09013f | 7ef585fa55896932f9c1ffec0cae243b7c6bbed9 | refs/heads/master | 2021-01-21T03:16:17.103896 | 2015-06-24T18:14:35 | 2015-06-24T18:14:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 370 | h | PoleCommand.h | //
// Created by root on 15-6-15.
//
#ifndef SPIN_POLECOMMAND_H
#define SPIN_POLECOMMAND_H
#include "ICommand.h"
class PoleCommand : public ICommand{
public:
PoleCommand(ServoDriver *servoDriver, SensorData *sensorData) : ICommand(servoDriver, sensorData) { }
virtual void init() override;
virtual void run() override;
};
#endif //SPIN_POLECOMMAND_H
|
db444d851a78df2fab49f104ca723b62b977c9bc | 76cad88856c8a0f799e6b8f69e8b7f6d03971ca7 | /MoAlgorithm/MoAlgorithm.cpp | 35a56cb1d6cba894aeaf5cee4f70da9ce84a024d | [] | no_license | huyquangvevo/Mo_and_Baby | ea0e002f7f887019744eaddeb9cfc723d516f443 | 6f1728c5ad9f96190cef7092c8b6985a37f5bc5c | refs/heads/master | 2020-04-04T02:00:28.082930 | 2018-12-01T08:50:27 | 2018-12-01T08:50:27 | 155,685,386 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,487 | cpp | MoAlgorithm.cpp | #include<stdio.h>
#include<math.h>
#include<vector>
#include<iostream>
#include"hash_structure.h"
using namespace std;
int N,Q,S;
const int n_max = 100000;
int A[n_max],AP[n_max];
int Freq[n_max];
int maxMode=0;
HashMo* sHash;
struct Query {
int left;
int right;
};
vector<int> Fre[100];
Query queries[n_max];
void init(){
scanf("%d %d",&N,&Q);
for(int i=0;i<N;i++){
scanf("%d",&A[i]);
AP[i] = 0;
}
for(int i=0;i<Q;i++){
scanf("%d %d",&queries[i].left,&queries[i].right);
}
S = floor(sqrt(N));
}
bool cmpQuery(Query A,Query B){
if(A.left/S != B.left/S){
return A.left/S < B.left/S;
}
return A.right < B.right;
}
void swap(int a,int b){
Query t = queries[a];
queries[a] = queries[b];
queries[b] = t;
}
int Partition(int L,int R){
int i,j;
Query p = queries[L];
i=L;
j=R+1;
while(i<j){
i++;
while((i<R)&&(cmpQuery(queries[i],p)))
i++;
j--;
while((j>L)&&(!cmpQuery(queries[j],p)))
j--;
swap(i,j);
}
swap(i,j);
swap(j,L);
return j;
}
void quick_sort(int left,int right){
int pivot;
if(left<right){
pivot = Partition(left,right);
if(cmpQuery(queries[left],queries[pivot]))
quick_sort(left,pivot-1);
if(right>pivot)
quick_sort(pivot+1,right);
}
}
void printTest(){
for(int i=0;i<Q;i++)
printf("\n%d %d\n",queries[i].left,queries[i].right);
int count[N];
for(int i = 0;i<N;i++){
count[N] = 0;
}
for(int i=0;i<Q;i++){
for(int j=queries[i].left;i<queries[i].right;i++)
count[j]++;
}
printf("%d",S);
}
void printQuery(Query q){
for(int i=0;i<N;i++)
if(i>=q.left && i<=q.right)
printf(" %d",A[i]);
else
printf(" ",A[i]);
}
void printAll(){
printf("\nDay so:\n");
for(int i=0;i<N;i++){
printf("%3d",A[i]);
}
printf("\n");
for(int i=0;i<N;i++)
printf("%3d",i);
}
void printDQuery(Query a,Query b){
printf("\nQuery 1 (%2d - %2d): ",a.left,a.right);
printQuery(a);
printf("\nQuery 2 (%2d - %2d): ",b.left,b.right);
printQuery(b);
}
int modeArr;
void insElement(int value){
// printf("\nInfo: %d - %d",value,Freq[value]);
sHash[Freq[value]].remove(value);
Freq[value] += 1;
// printf("\nInsert: %d - %d",value,Freq[value]);
sHash[Freq[value]].add(value);
if(Freq[value]>maxMode){
maxMode = Freq[value];
modeArr = value;
}
}
void delElement(int value){
sHash[Freq[value]].remove(value);
if(Freq[value]>0)
Freq[value] -= 1;
sHash[Freq[value]].add(value);
while (sHash[maxMode].isEmpty()&&maxMode>0){
maxMode--;
modeArr = sHash[maxMode].arr[0];
}
}
void printsHash(){
sHash[1].printHash();
sHash[2].printHash();
sHash[3].printHash();
}
int getMode(Query preQ,Query curQ){
modeArr = A[curQ.left];
printDQuery(preQ,curQ);
if(preQ.left<=curQ.left)
for(int i=preQ.left;i<curQ.left;i++)
delElement(A[i]);
else
for(int i=curQ.left;i<preQ.left;i++)
insElement(A[i]);
// printsHash();
// printf("\nBefore: Mode: %d --- Max: %d\n",modeArr,maxMode);
// printf("\nAfter: \n");
if(preQ.right<=curQ.right)
for(int i=preQ.right+1;i<=curQ.right;i++)
insElement(A[i]);
else
for(int i=curQ.right+1;i<=preQ.right;i++)
delElement(A[i]);
// printsHash();
printf("\n\tMode: %d --- Max: %d\n",modeArr,maxMode);
}
int main(){
init();
quick_sort(0,Q-1);
sHash = new HashMo[n_max];
printAll();
for(int i=0;i<n_max;i++)
Freq[i] = 0;
for(int i=queries[0].left;i<=queries[0].right;i++){
insElement(A[i]);
}
for(int i=0;i<Q-1;i++)
getMode(queries[i],queries[i+1]);
}
|
ce502259f8be601c1970027f77d68c3629d6dc1e | fa476614d54468bcdd9204c646bb832b4e64df93 | /otherRepos/Codes/Laptop_Ubuntu/luis/674_UVA.cpp | 91df3987c4470a1d788b5fac22948fab25203fd8 | [] | no_license | LuisAlbertoVasquezVargas/CP | 300b0ed91425cd7fea54237a61a4008c5f1ed2b7 | 2901a603a00822b008fae3ac65b7020dcddcb491 | refs/heads/master | 2021-01-22T06:23:14.143646 | 2017-02-16T17:52:59 | 2017-02-16T17:52:59 | 81,754,145 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,549 | cpp | 674_UVA.cpp | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pii pair< int , int >
#define pll pair< ll , ll >
#define all(v) v.begin() , v.end()
#define rall(v) v.rbegin() , v.rend()
#define FOR(it,A) for(typeof A.begin() it = A.begin(); it!=A.end(); it++)
#define REP(i,n) for(int i=0;i<(n);i++)
#define pb push_back
#define vi vector<int>
#define vll vector<ll>
#define vull vector<ull>
#define vvi vector< vi >
#define vpii vector< pii >
#define mp make_pair
#define fi first
#define se second
#define sc(x) scanf("%d",&x)
#define clr(t,val) memset( t , val , sizeof(t) )
#define ones(x) __builtin_popcount(x)
#define test puts("************test************");
#define sync ios_base::sync_with_stdio(false);
#define N 10005
#define nV 6
/*int memo[ N ][ nV ];
int n = 5;
int V[] = { 1 , 5 , 10 , 25 , 50 };
int dp( int total , int k ){
if( total == 0 ) return 1;
if( k == n )return 0;
int &dev = memo[ total ][ k ];
if( dev == -1 ){
dev = dp( total , k + 1 );
if( total - V[ k ] >= 0 )
dev += dp( total - V[ k ] , k );
}
return dev;
}*/
int DP[ N ][ nV ];
int n = 5;
int V[] = { 1 , 5 , 10 , 25 , 50 };
int main()
{
//clr( memo , -1 );
REP( total , N ) DP[ total ][ n ] = 0;
REP( k , n + 1 ) DP[ 0 ][ k ] = 1;
for( int k = n - 1 ; k >= 0 ; --k )REP( total , N )
{
int &dev = DP[ total ][ k ] = DP[ total ][ k + 1 ];
if( total - V[ k ] >= 0 )
dev += DP[ total - V[ k ] ][ k ];
}
int money;
while( scanf( "%d" , &money ) == 1 )
printf( "%d\n" , DP[ money ][ 0 ] );
}
|
d9008384e42f60c361cbc6c1c3ea857af4505142 | 1b06d5bf179f0d75a30a4b020dd88fc5b57a39bc | /Repository/Logix/system/Doors/basic_room.cp | 89d3b0876651ade2b056075e31fddcc24c8fa8f8 | [] | no_license | ofirr/bill_full_cvs | b508f0e8956b5a81d6d6bca6160054d7eefbb2f1 | 128421e23c7eff22afe6292f88a01dbddd8b1974 | refs/heads/master | 2022-11-07T23:32:35.911516 | 2007-07-06T08:51:59 | 2007-07-06T08:51:59 | 276,023,188 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,700 | cp | basic_room.cp | /* $Header: /baz/users/cvs-root/Doors/basic_room.cp,v 1.2 1994/07/26 13:58:16 marilyn Exp $ */
-language(dfcp).
-mode(interrupt).
-export([create, basic_room, show_doors, show_filtered_doors,
rcv_control, send, update_id_card, self_rcv,
update_cards, discard_entry, unify_if_ok, which_update_id]).
-override([create1, room, room_close]).
create(IdCard,Door,Ok) :-
create1(IdCard,Door,super,Ok).
create1(IdCard,InitialDoor,InitialDoorId,Ok) :-
ground(IdCard) |
id_card#query(IdCard,[(name:Name),(type:Type)]),
update_id_card(IdCard,IdCard'),
doors#corridor(InitialDoor,Door1),
self_rcv(SndSelf?,SndSelf1),
doors#merger(SndSelf1?,RcvSelf),
entries#create(Doors),
Rcv' = [initialize(IdCard'?,SndSelf,Ok),
([self] : paste(Door1?,InitialDoorId?,Ok1)),
initialize_application(Ok2)
| RcvSelf? ],
ok([Ok1?, Ok2?], create1_ok),
room.
update_id_card(IdCard1, IdCard2) :-
processor#interface(gmtime(Date)),
id_card#update(IdCard1, [(created: Date?)], IdCard2).
self_rcv(Rcv,Snd) :-
Rcv ? message([],From,Request,Ok?), Request =\= merge(_) |
Snd ! ([self|From] : Request),
Ok = true,
self;
Rcv ? message([],[],merge(Snd1),Ok?) |
Ok = true,
Snd ! merge(Snd1?),
self;
Rcv ? message(To,From,Message,Ok), To =\= [] |
Snd ! message(To,[self|From],Message,Ok),
self;
Rcv = [] | Snd = [].
/************************************************************************
*
* To open a "Pure" basic room - Call "create"
* To inherit basic room functionality - Inherit "basic_room"
*
*************************************************************************/
room(Rcv, Doors, Name, Type) :-
+initialized_room;
+room_ignore_events.
initialized_room(Rcv, Doors, Name, Type) :-
+room_initialize_application;
+basic_room.
room_initialize_application(Rcv) :-
Rcv ? initialize_application(Ok?) |
Ok = true,
self.
basic_room(Rcv, Doors, Name, Type) :-
+room_initialize;
+room_close;
+room_route;
+room_send;
+room_show;
+room_paste;
+room_discard;
+room_discarded;
+room_invalid;
+room_update_id_card;
+room_protect;
+room_listen_to.
room_initialize(Rcv,Doors, Name, Type) :-
Rcv ? initialize(IdCard,Snd,Ok) |
entries#allocate_entry(self,Doors,Doors',Entry?,_EntryId,Ok),
entries#fill_entry(Entry,IdCard,Snd,_DiscardNotify),
self.
room_close(Rcv, Doors) :-
Rcv ? (_From: close(Ok?)) |
Rcv'=_,
entries#close(Doors),
finalize,
Ok=true.
room_show(Rcv,Doors) :-
Rcv ? (_From: show(doors,DoorsInfo,Ok?)) |
show_doors(Doors,Doors',DoorsInfo),
Ok=true,
self;
Rcv ? (_From: show(doors(Pairs), DoorsInfo, Ok?)), ground(Pairs) |
% computation#display(["want to show doors of ", Pairs]),
show_filtered_doors(Pairs, Doors,Doors',DoorsInfo),
Ok = true,
self;
Rcv ? (From: show(path,From^,true^)) |
self;
Rcv ? (_From: show(id_card(Id),IdCard,Ok)) |
entries#id_to_id_card(Id,IdCard,Doors,Doors',Ok),
self.
show_doors(Doors,Doors1,DoorsInfo) :-
entries#retrieve_IdCards(Doors,Doors1,DoorsInfo).
show_filtered_doors(Pairs, Doors,Doors1, FilteredInfo) :-
entries#retrieve_IdCards(Doors,Doors1,Info),
% computation#display(["unfiltered doors are ", Info??]),
filter_doors_info(Pairs, Info?, FilteredInfo).
filter_doors_info(Pairs, Info, FilteredInfo) :-
Info ? DoorInfo, DoorInfo = (Id - IdCard), ground(IdCard), ground(Pairs) |
id_card#match(IdCard, Pairs, Ok),
include_if_ok(Ok?, Id, IdCard, FilteredInfo, FilteredInfo'?),
self;
Info = [] |
Pairs = _,
% computation#display("finished filtering"),
FilteredInfo = [].
include_if_ok(Ok, Id, IdCard,FilteredInfo1, FilteredInfo2):-
Ok = true, constant(Id), ground(IdCard) |
% computation#display(["matched Id of ", Id, " IdCard of ", IdCard]),
FilteredInfo1 = [(Id - IdCard) | FilteredInfo2];
Ok =\= true |
Id = _, IdCard = _,
FilteredInfo1 = FilteredInfo2.
update_cards(From,IdCard1,EntryId,IdCard2,DoorCard,Doors1,Doors2) :-
From = _,
processor#interface(gmtime(Date)),
id_card#update([],[(joined_date: Date?)],DoorCard),
Doors2 = Doors1,
id_card#update(IdCard1,[(entry_id:EntryId)], IdCard2).
rcv_control(Rcv,EntryId,Snd, DiscardNotify) :-
DiscardNotify = true | doors#door_terminator(Rcv), Snd=[], EntryId=_;
Rcv=[] | Snd=[([EntryId]:discarded(_))], DiscardNotify = _;
Rcv ? message(To,From,Message,Ok),
To =\= [], unknown(DiscardNotify), ground(EntryId) |
Snd ! message(To,[EntryId|From],Message,Ok),
self;
Rcv ? message([],From,Message,Ok?),
unknown(DiscardNotify), ground(EntryId) |
Snd ! ([EntryId|From] : Message),
Ok = true,
self;
Rcv ? Message, Message =\= message(_,_,_,_),
unknown(DiscardNotify), ground(EntryId) |
Snd ! ([EntryId] : Message),
self;
invalid(Rcv), ground(EntryId) |
invalid_reason(Rcv,Reason),
Snd ! (EntryId: invalid(Reason?)),
Snd' = [],
DiscardNotify = _,
EntryId = _.
room_route(Rcv,Doors) :-
Rcv ? message(To,From,Message,Ok), To =\= [] |
send(To,From,Message,Doors,Doors',Ok),
self.
room_send(Rcv,Doors) :-
Rcv ? send(To,Message), To =\= [] |
send(To,[],Message,Doors,Doors',Ok),
ok(Ok?,room_send),
self.
send(To,From,Message,Doors1,Doors2,Ok) :-
entries#send(To,From,Message,Doors1,Doors2,Ok).
room_discard(Rcv,Doors) :-
Rcv ? (From: discard(Id,Ok1?)), ground(Id) |
discard_entry(Id,Doors,Doors',IdCard, Rcv'?, Rcv'', Ok),
listen2(Ok?, Ok1, Ok2),
TheEvent = event(doors, (From : discard(Id,IdCard?))),
unify_if_ok(Ok2?, TheEvent?, Rcv''',Rcv''?),
self.
room_discarded(Rcv,Doors) :-
Rcv ? ([From]: discarded(OkRet?)), ground(From) |
OkRet = true,
discard_entry(From,Doors,Doors',IdCard, Rcv'?, Rcv'', Ok),
listen2(Ok?, Ok1, Ok2),
TheEvent = event(doors, ([From] : discard(From,IdCard?))),
unify_if_ok(Ok1?, TheEvent?, Rcv''',Rcv''?),
ok(Ok2?, room_discarded),
self.
room_invalid(Rcv,Doors) :-
Rcv ? (From: invalid(Reason)), ground(From) |
discard_entry(From,Doors,Doors',IdCard, Rcv'?, Rcv'', Ok),
TheEvent = event(doors, (From : invalid(Reason,IdCard?))),
unify_if_ok(Ok?, TheEvent?, Rcv''',Rcv''?),
self.
room_ignore_events(Rcv) :-
Rcv ? event(_Type, _Event) | self.
discard_entry(Id, Doors, Doors1, IdCard, Rcv1, Rcv2, Ok) :-
entries#discard_entry(Id,Doors,Doors1,IdCard,Ok, FloatingRoom),
is_inaccessible_room(FloatingRoom?, Rcv1, Rcv2).
/*
Check whether the room is inaccessible from the outside
i.e. the only door is self. if so -> terminate room.
*/
is_inaccessible_room(FloatingRoom, Rcv1, Rcv2) :-
FloatingRoom = false |
Rcv2 = Rcv1;
FloatingRoom = true |
Rcv2 = [(self: close(Ok)) | Rcv1],
ok(Ok?, close_room).
room_update_id_card(Rcv,Doors) :-
Rcv ? ([From|_]: update(id_card(UpdateId,IdCard),Ok1?)),
ground(From) |
which_update_id(From,UpdateId,Id),
listen2(Id?, Id1, Id2),
listen2(IdCard?, IdCard1, IdCard2),
entries#update_id(Id1?,IdCard1?,Doors,Doors',Ok),
listen2(Ok?, Ok1, Ok2),
TheEvent = event(id_cards, ([From] : update(id_card(Id2?, IdCard2?)))),
unify_if_ok(Ok2?, TheEvent?, Rcv'', Rcv'?),
self;
Rcv ? ([From|_]: tail_and_update(id_card(UpdateId,IdCard),Ok1?)),
ground(From) |
which_update_id(From,UpdateId,Id),
listen2(Id?, Id1, Id2),
listen2(IdCard?, IdCard1, IdCard2),
entries#tail_and_update(Id1?,IdCard1?,Doors,Doors',Ok),
listen2(Ok?, Ok1, Ok2),
TheEvent = event(id_cards, ([From] : update(id_card(Id2?, IdCard2?)))),
unify_if_ok(Ok2?, TheEvent?, Rcv'', Rcv'?),
self;
Rcv ? ([From|_]: replace(id_card(UpdateId,IdCard),Ok1?)),
ground(From) |
which_update_id(From,UpdateId,Id),
listen2(Id?, Id1, Id2),
listen2(IdCard?, IdCard1, IdCard2),
entries#replace_id(Id1?,IdCard1?,Doors,Doors',Ok),
listen2(Ok?, Ok1, Ok2),
TheEvent = event(id_cards, ([From] : replace(id_card(Id2?, IdCard2?)))),
unify_if_ok(Ok2?, TheEvent?, Rcv'', Rcv'?),
self.
which_update_id(From, To, Id) :-
To = self |
Id = From;
To =\= self |
From = _,
Id = To.
unify_if_ok(Ok, Message, Rcv1, Rcv2) :-
Ok =\= true | Rcv1 = Rcv2, Message = _;
Ok = true | Rcv1 = [Message | Rcv2].
room_protect(Rcv) :-
Rcv ? protect(Ok,Message), Ok = true |
Rcv''= [Message|Rcv'],
self;
Rcv ? protect(Ok,Message), Ok =\= true |
doors#generic_reply(Message,Ok),
self.
room_listen_to(Rcv, Doors) :-
Rcv ? (From : death_signal(DiscardNotify?)) |
entries#retrieve_DiscardNotify(From, Doors, Doors', DiscardNotify),
self;
Rcv ? listen_to(RoomToListenTo, EventTypes, EventControl, Ok) |
Rcv'' = [ send([self],merge(M?)),
message(RoomToListenTo, [],
listen(EventTypes, M, EventControl, Ok1), Ok2)
| Rcv'?],
and([Ok1?, Ok2?], Ok),
self.
room_paste(Rcv, Doors) :-
Rcv ? (From: paste(Door,EntryId,Ok1?)), Door = door(_,_) |
entries#allocate_entry(EntryId,Doors,Doors',Entry?,EntryId',Ok),
listen2(Ok?, Ok1, Ok2),
Rcv'' = [protect(Ok2?,paste(From,Door,Entry,EntryId'?,_Ok))|Rcv'],
self;
Rcv ? (_From: paste(Door, _EntryId,Ok?)), invalid(Door) |
Ok = false(invalid),
self;
Rcv ? paste(From,Door,Entry,EntryId,_Ok), ground(EntryId), ground(From),
Door = door(DoorSnd?,DoorRcv) |
update_cards(From,IdCard?,EntryId,IdCard',DoorCard,Doors,Doors'),
DoorSnd ! update(id_card(self,IdCard'?),_Ok1),
entries#fill_entry(Entry,DoorCard?,DoorSnd',DiscardNotify),
rcv_control(DoorRcv,EntryId,DoorRcv',DiscardNotify?),
Rcv'' = [ send([self],merge(DoorRcv'?)),
([]: show(id_card(self),IdCard,Ok2)),
event(doors, (From : paste(EntryId)))
| Rcv'],
ok(Ok2?, update_cards),
self.
|
f9bd667825d17f6c2a97c7a862f2e2594f1670f2 | 95d91f6c306197fb7fa0b6d0b1a6e15da3d17b00 | /demos/dox/find/finder_aho_corasick.cpp | 6e70e3bee1fe3411d6c16f6f6e05b319fe9013a7 | [
"BSD-3-Clause"
] | permissive | seqan/seqan | e11ebd62fdd38e64664717f137f042b5c6580445 | 5efe02f4ac37156152ec8ec5512ce74a163d6675 | refs/heads/main | 2023-08-07T03:25:45.143396 | 2023-07-06T13:30:29 | 2023-07-06T13:37:19 | 6,383,869 | 438 | 201 | NOASSERTION | 2023-09-11T10:21:06 | 2012-10-25T08:02:15 | C++ | UTF-8 | C++ | false | false | 1,168 | cpp | finder_aho_corasick.cpp | #include <seqan/find.h>
using namespace seqan2;
int main()
{
typedef String<AminoAcid> AminoAcidString;
// A simple amino acid database.
StringSet<AminoAcidString> dbs;
appendValue(dbs, "MARDPLY");
appendValue(dbs, "AVGGGGAAA");
// We put some words of the database into the queries.
String<AminoAcidString> queries;
appendValue(queries, "MARD");
appendValue(queries, "AAA");
appendValue(queries, "DPLY");
appendValue(queries, "VGGGG");
// Define the Aho-Corasick pattern over the queries with the preprocessing
// data structure.
Pattern<String<AminoAcidString>, AhoCorasick> pattern(queries);
// Search for the queries in the databases. We have to search database
// sequence by database sequence.
std::cout << "DB\tPOS\tENDPOS\tTEXT\n";
for (unsigned i = 0; i < length(dbs); ++i)
{
Finder<AminoAcidString> finder(dbs[i]); // new finder for each seq
while (find(finder, pattern))
std::cout << i << "\t" << position(finder) << "\t"
<< endPosition(finder) << "\t"
<< infix(finder) << "\n";
}
return 0;
}
|
6b6c23e397d7f8469dbbbdb8adb53fd12cd6d935 | 89485890afeeacdae996de966b8b13ba0c1bbc9a | /mplib/src/zchatmessagewidget.cpp | abefc57905797511d840fecb2be445aa446966da | [] | no_license | weinkym/src_miao | b7c8a35a80e5928470bea07d5eb7e36d54966da9 | 0759c1f819c15c8bb2172fe2558fcb728a186ff8 | refs/heads/master | 2021-08-07T17:55:52.239541 | 2021-06-17T03:38:44 | 2021-06-17T03:38:44 | 64,458,033 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,766 | cpp | zchatmessagewidget.cpp | #include <QTextDocument>
#include <QUrl>
#include <QDateTime>
#include "zchatmessagewidget.h"
ZChatMessageWidget::ZChatMessageWidget(QWidget *parent)
:QTextEdit(parent)
,m_timeAddable(true)
{
m_timeTextBackgroundColor = QColor("#EEE5DE");
m_timeTextColor = QColor(Qt::blue);
m_timeTextFont.setPointSize(12);
m_timeTextFont.setBold(false);
m_textBackgroundColor = QColor(Qt::white);
m_textColor = QColor("#0A0A0A");
m_textFont.setPointSize(16);
m_textFont.setBold(true);
}
ZChatMessageWidget::~ZChatMessageWidget()
{
//
}
bool ZChatMessageWidget::insertImage(const QString &fileName)
{
QImage image(fileName);
if (image.isNull())
{
return false;
}
int width = this->viewport()->width();
int height = this->viewport()->height();
if (image.width() > width || image.height() > height) {
// image = image.scaled(width, height, Qt::KeepAspectRatio, Qt::SmoothTransformation);
}
QTextCursor cursor = this->textCursor();
// QTextDocument *document = this->document();
cursor.movePosition(QTextCursor::End);
// document->addResource(QTextDocument::ImageResource, QUrl(fileName), QVariant(image));
// QUrl url();
// document->addResource(QTextDocument::ImageResource, QUrl(fileName), QVariant(image));
//插入图像,使用QTextCursor API文档:
QTextImageFormat image_format;
image_format.setName(fileName);
cursor.insertImage(image_format);
return true;
}
void ZChatMessageWidget::setTimeAddable(bool addable)
{
m_timeAddable = addable;
}
void ZChatMessageWidget::addText(const QString &text, bool isSend)
{
if(m_timeAddable)
{
addTimeText();
setAlignment(Qt::AlignLeft);
if(isSend)
{
setAlignment(Qt::AlignRight);
}
}
append(text);
if(!m_timeAddable)
{
setAlignment(Qt::AlignLeft);
if(isSend)
{
setAlignment(Qt::AlignRight);
}
}
}
void ZChatMessageWidget::addTimeText()
{
QTextCharFormat fmt;//文本字符格式
fmt.setForeground(m_timeTextColor);// 前景色(即字体色)设为col色
fmt.setFont(m_timeTextFont);
fmt.setBackground(m_timeTextBackgroundColor);
QTextCursor cursor = this->textCursor();//获取文本光标
cursor.mergeCharFormat(fmt);//光标后的文字就用该格式显示
this->mergeCurrentCharFormat(fmt);//textEdit使用当前的字符格式
append(QDateTime::currentDateTime().toString("yyyy-M-d h:m:s"));
fmt.setForeground(m_textColor);// 前景色(即字体色)设为col色
fmt.setFont(m_textFont);
fmt.setBackground(m_textBackgroundColor);
this->mergeCurrentCharFormat(fmt);//textEdit使用当前的字符格式
}
|
48b2a366bd38b75a81cec59bc1f4e3c72699c56d | 6b910d41838d7f516545c625b4bf5e7d1ff55e68 | /onion/onions/src/onions/primitive.cpp | 8ec642a5899b3034529dbf0d65d973520e5307fc | [] | no_license | zipdrive/onion | 7c55a77c5c32da0bb6e2079fb481b2f5b2f54356 | 8e3deb5feec6a143d763035b31f4373bbc666737 | refs/heads/version-0-1 | 2022-02-17T12:44:39.914554 | 2020-11-24T22:13:03 | 2020-11-24T22:13:03 | 242,404,288 | 0 | 0 | null | 2020-11-24T22:13:04 | 2020-02-22T20:06:28 | C++ | UTF-8 | C++ | false | false | 635 | cpp | primitive.cpp | #include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "../../include/onions/primitive.h"
namespace onion
{
template <>
struct _primitive<bool>
{
using type = GLboolean;
};
template <>
struct _primitive<int>
{
using type = GLint;
};
template <>
struct _primitive<unsigned int>
{
using type = GLuint;
};
template <>
struct _primitive<float>
{
using type = GLfloat;
};
template <>
struct _primitive<double>
{
using type = GLdouble;
};
template <>
struct _primitive<char>
{
using type = GLchar;
};
template <>
struct _primitive<std::string>
{
using type = std::basic_string<GLchar>;
};
} |
7b23e8115a9f8379f88ee3011b2d1ccd245562a4 | 4521077433dbba6b17ac2ab4a360abfa9e335ece | /zjazd5/EnumDni.cpp | 11b04dfa4928ec7c7c410e7341f0872c2013e8b6 | [] | no_license | s20309-pj/pgr1 | 23dab685ea41fd8f1ef3881b8d658e744b35dc3f | 9d2a6eaf577f9ab7167d60ffe786829c368ba3ae | refs/heads/master | 2020-08-07T13:49:16.902321 | 2020-01-10T22:58:44 | 2020-01-10T22:58:44 | 213,476,137 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22 | cpp | EnumDni.cpp |
#include "EnumDni.h"
|
43d9962d48bf5992d838228bb8c99423ca806db9 | 830934ba65b11c21aa9051546eac0aa03893b210 | /src/FBXSource/ofxFBXSrcPose.h | c6d2000f7ecfb41e44332bfa6c34a65243a81224 | [
"MIT"
] | permissive | NickHardeman/ofxFBX | e9cca47c232a10ef4b89c12672fc2df68d9ecbc4 | f032fd43a78a740e7ab4b4f497a61a1654ef9a59 | refs/heads/master | 2023-09-03T19:21:22.013743 | 2023-08-30T14:51:34 | 2023-08-30T14:51:34 | 32,026,580 | 117 | 43 | MIT | 2022-11-22T15:13:13 | 2015-03-11T15:53:23 | C++ | UTF-8 | C++ | false | false | 458 | h | ofxFBXSrcPose.h | //
// ofxFBXPose.h
// DogImportTest
//
// Created by Nick Hardeman on 9/22/14.
//
#pragma once
#include "ofxFBXUtils.h"
namespace ofxFBXSource {
class Pose {
public:
Pose();
void setup( FbxPose* aPose, int aFbxIndex );
string getName();
int getFbxIndex();
FbxPose* getFbxPose();
bool isBindPose();
bool isRestPose();
private:
string name;
int fbxIndex = 0;
FbxPose* fbxPose = NULL;
};
}
|
61a4099ce3a42530af506b3d0f3499865362622f | 335249c5446a00961efffe7cd68bd75c6b43abc4 | /Lab02B/Lab02_partB.cpp | cf58ea073d0fb700ac2be2c6778474fc5b876855 | [] | no_license | tsmit317/CSC-134-Labs | a96071627a918ce3fb3a7553181a4c9137f82bd9 | 810e7af16921486baf90e1cf35f028ab61815527 | refs/heads/master | 2021-06-24T05:09:14.423045 | 2017-09-10T23:40:22 | 2017-09-10T23:40:22 | 103,068,364 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,517 | cpp | Lab02_partB.cpp | ///////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Filename: Lab02_partB.cpp
// Date: 01/30/14
// Programmer: Taylor Smith
//
// Decription:
// Program calculates monthly bill for internet provider's customer's by asking user for the
// plan, data usage, and access time. Additionally, the program then uses these inputs to determine
// if any other plans offered would save them money; displaying the plan, charge, and savings.
//
////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include "InternetCharge.h" // include class InternetCharge
using namespace std;
// function main begins program execution
int main()
{
// create object myCharge
InternetCharge myCharge1;
// declare local variables
int pln = 0;
int mnt = 0;
double dta = 0.0;
// begin myCharge
myCharge1.setPlan(pln); // setPlan: asks user for plan #
myCharge1.setMinutes(mnt); // setMinute: asks user for access time (minutes)
myCharge1.setData(dta); // setData: asks user for data usage (GB)
myCharge1.calcPlanCharge(pln); // calculates monthly charge
myCharge1.displayMonCharge(); // displays user input information as well as monthly charge
myCharge1.displayBetterPlans(); // calculates, compares, and displays plans that would save money
cin.get();
return 0;
}// end main
|
22c2d5e42d60d3bfcbf0d7ecb37133ad24071dac | 737728a38690e2e31c4b4c1a998fae923502cf54 | /C++/4889_안정적인문자열.cpp | 14a69c707170aaf01966a59c861d8420ef12e97c | [] | 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 | 1,442 | cpp | 4889_안정적인문자열.cpp | #include <iostream>
#include <string>
#include <stack>
using namespace std;
int main() {
int T = 0; // 루프의 순서 알려줄 변수
while(true){
string S;
cin >> S;
int s_len = S.length();
if(s_len > 0 && S[0] == '-'){ // 만약 '-'가 한 개 이상 존재하면 종료
break;
}
T++;
int cnt = 0; // 연산의 수를 세기 위한 변수
stack<bool> s; // '{'를 넣기 위한 stack('{'를 true로 넣을 것)
for(int i = 0; i < s_len; i++){ // 문자열의 문자 하나씩 확인
if(S[i] == '{'){ // '{'일 경우
s.push(true); // stack에 추가
}
else{ // '}'일 경우
if(s.empty()){ // stack이 비어있는지 확인해서 비어있으면 짝이 맞지 않는 것
cnt++; // 이때 '}'를 '{'로 바꿔주기 -> 연산 수 1증가
s.push(true); // '{'로 바꾸었기 때문에 stack에 추가
}
else{ // stack이 비어있지 않으면
s.pop(); // stack의 '{'와 짝을 이루기 때문에 하나 pop!
}
}
}
int s_size = s.size();
if(s_size != 0){ // 안정적인 문자열이라면 짝이 모두 맞기 때문에 stack이 비어있어야 함 -> 비어있지 않은 경우는 '{'가 더 많은 경우
cnt += s_size/2; // 남은 '{'끼리 서로 짝을 만들어 주어야 하므로 남은 '{'의 절반을 '}'로 바꿔야 함 -> 연산수: 남은 '{'의 수/2 만큼 추가
}
cout << T << ". " << cnt << '\n';
}
return 0;
}
|
9c1fd55809dfe5e3fbb6a92e6a441165452a0001 | 5c1bb4d852ce097badbda1646c4467b370a1c841 | /day04/ex01/Enemy.h | 701673fe5151cc190fc93e73ed2f525fd2378268 | [
"MIT"
] | permissive | BimManager/cpp_piscine | dd83d836be826e6002107e232db43f17b6a5bd98 | 170cdb37a057bff5a5d1299d51a6dcfef469bfad | refs/heads/master | 2022-12-23T01:54:46.079038 | 2020-09-25T07:01:56 | 2020-09-25T07:01:56 | 274,365,036 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 579 | h | Enemy.h | // Copyright 2020 kkozlov
#ifndef DAY04_EX01_ENEMY_H_
#define DAY04_EX01_ENEMY_H_
#include <string>
#include <iostream>
class Enemy {
public:
Enemy(int hp, std::string const &type);
Enemy(Enemy const &other);
virtual ~Enemy(void);
Enemy& operator=(Enemy const &rhs);
std::string const& Type(void) const;
int HP(void) const;
void SetType(std::string const &type);
void SetHP(int hp);
virtual void TakeDamage(int);
private:
std::string type_;
int hp_;
};
std::ostream &operator<<(std::ostream &os, Enemy const &in);
#endif // DAY04_EX01_ENEMY_H_
|
e88abfabd1d92dfa54eeee663bd77546fe73e11b | fbb451429d7c4bace20f1d1c6ae4123526784491 | /D2D/Native/H/Setup/SetupInf.h | 9faab247392ae08ac6d4b2fb133433dfbf137312 | [] | no_license | cliicy/autoupdate | 93ffb71feb958ff08915327b2ea8eec356918286 | 8da1c549847b64a9ea00452bbc97c16621005b4f | refs/heads/master | 2021-01-24T08:11:26.676542 | 2018-02-26T13:33:29 | 2018-02-26T13:33:29 | 122,970,736 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,012 | h | SetupInf.h | /////////////////////////////////////////////////////////////////////////////
// SetupInf.h CSetupInf Interface
// Copyright (C) 2016 Arcserve, including its affiliates and subsidiaries.
//All rights reserved. Any third party trademarks or copyrights are the
//property of their respective owners.
#ifndef _SETUPINF
#define _SETUPINF
#ifdef _SETUPCLS_DLL
class __declspec(dllexport) CSetupInf
#else
class __declspec(dllimport) CSetupInf
#endif
{
private:
static const CString m_sARCSETUP_INF;
static const CString m_sComponents;
static const CString m_sDataMigration;
static const CString m_sTNGFrameWork;
static const CString m_sTNGFrameWorkSetupFileName;
static const CString m_sProductInfo;
static const CString m_sProductName;
static const CString m_sSetupFileName;
static const CString m_sCALicenseInfo;
static const CString m_sProdSubType;
static const CString m_sProductType;
static const CString m_sLicInstallFileName;
static const CString m_sChangerLicenseLevel;
static const CString m_sLicenseTextFile;
static const CString m_sProdBuildNoRange;
static const CString m_sIE5InstallFileName;
static const CString m_sConfigFileName;
static const CString m_sMsiInstallFileName;
static const CString m_sMsmInstallFileName;
static const CString m_sLicComponentCode;
// { #30032006 // added by yuani01 for SQL 2005 Express installation
static const CString m_sSQL2005EFileName;
// } #30032006
// { #070802001 yuani01 for Beta upgrade
static const CString m_sBetaUpgradeVerName;
// } #070802001 yuani01
CString m_sInfFile;
BOOL m_bHSMAvailable;
BOOL m_bTNGFWAvailable;
CString m_sTNGFWSetupFile;
CString m_sSetupProductName;
CString m_sSetupFile;
BOOL m_bExists;
BOOL FindFile();
CString m_sLicInstallFile;
DWORD m_dwChangerLicLevel;
CString m_sLicenseTextFileName;
CString m_sIE5InstallFile;
CString m_sConfigFile;
CString m_sMsiFile;
CString m_sMsmFile;
CString m_sLicCompCode;
// { #30032006
CString m_sSQL2005EInstFileName;
// } #30032006
public:
CSetupInf();
~CSetupInf();
BOOL IsHSMAvailable();
BOOL IsTNGFWAvailable();
LPCTSTR GetTNGFWSetupFileName();
LPCTSTR GetSetupProductName();
LPCTSTR GetSetupFileName();
int GetProductSubType();
int GetProductType();
LPCTSTR GetLicInstallFileName();
DWORD GetChangerLicLevel();
LPCTSTR GetLicenseTextFileName();
BOOL GetUpdateBuildNoRange( LPCTSTR pKeyName, int* nMinBuild, int* nMaxBuild);
BOOL SetARCsetupINFName(LPCTSTR lpszFileName);
LPCTSTR GetIE5InstallFileName();
LPCTSTR GetConfigFileName();
LPCTSTR GetMsiFileName();
LPCTSTR GetMsmFileName();
LPCTSTR GetLicCompCode();
// CSetupInf(LPCTSTR lpszFileName = NULL);
// { #30032006 yuani01
LPCTSTR GetSQL2005EInstFileName();
// } #30032006 yuani01
// { #070802001 yuani01
BOOL GetBetaUpgVer( WORD& wBetaVer );
// } #070802001 yuani01
private:
static const CString m_sSetup;
static const CString m_sSupport;
};
#endif
|
b53eb770ee703117c494c3f77bf991046b6a3a92 | ab81ae0e5c03d5518d535f4aa2e3437081e351af | /OCCT.Foundation.Net/Visualization/TKV3d/AIS/XAIS_Selection.cpp | e26bddf82834634843ed256bffbbe47d3c2665f7 | [] | no_license | sclshu3714/MODELWORX.CORE | 4f9d408e88e68ab9afd8644027392dc52469b804 | 966940b110f36509e58921d39e8c16b069e167fa | refs/heads/master | 2023-03-05T23:15:43.308268 | 2021-02-11T12:05:41 | 2021-02-11T12:05:41 | 299,492,644 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,066 | cpp | XAIS_Selection.cpp | // Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#include <AIS_Selection.hxx>
#include <AIS_InteractiveObject.hxx>
IMPLEMENT_STANDARD_RTTIEXT(AIS_Selection, Standard_Transient)
namespace
{
static const Standard_Integer THE_MaxSizeOfResult = 100000;
}
//=======================================================================
//function : AIS_Selection
//purpose :
//=======================================================================
AIS_Selection::AIS_Selection()
{
// for maximum performance on medium selections (< 100000 objects)
myResultMap.ReSize (THE_MaxSizeOfResult);
}
//=======================================================================
//function : Clear
//purpose :
//=======================================================================
void AIS_Selection::Clear()
{
for (AIS_NListOfEntityOwner::Iterator aSelIter (Objects()); aSelIter.More(); aSelIter.Next())
{
const Handle(SelectMgr_EntityOwner) anObject = aSelIter.Value();
anObject->SetSelected (Standard_False);
}
myresult.Clear();
myResultMap.Clear();
myIterator = AIS_NListOfEntityOwner::Iterator();
}
//=======================================================================
//function : Select
//purpose :
//=======================================================================
AIS_SelectStatus AIS_Selection::Select (const Handle(SelectMgr_EntityOwner)& theObject)
{
if (theObject.IsNull()
|| !theObject->HasSelectable())
{
return AIS_SS_NotDone;
}
if (!myResultMap.IsBound (theObject))
{
AIS_NListOfEntityOwner::Iterator aListIter;
myresult.Append (theObject, aListIter);
myResultMap.Bind (theObject, aListIter);
theObject->SetSelected (Standard_True);
return AIS_SS_Added;
}
AIS_NListOfEntityOwner::Iterator aListIter = myResultMap.Find (theObject);
if (myIterator == aListIter)
{
if (myIterator.More())
{
myIterator.Next();
}
else
{
myIterator = AIS_NListOfEntityOwner::Iterator();
}
}
// In the mode of advanced mesh selection only one owner is created for all selection modes.
// It is necessary to check the current detected entity
// and remove the owner from map only if the detected entity is the same as previous selected (IsForcedHilight call)
if (theObject->IsForcedHilight())
{
return AIS_SS_Added;
}
myresult.Remove (aListIter);
myResultMap.UnBind (theObject);
theObject->SetSelected (Standard_False);
// update list iterator for next object in <myresult> list if any
if (aListIter.More())
{
const Handle(SelectMgr_EntityOwner)& aNextObject = aListIter.Value();
if (myResultMap.IsBound (aNextObject))
{
myResultMap (aNextObject) = aListIter;
}
else
{
myResultMap.Bind (aNextObject, aListIter);
}
}
return AIS_SS_Removed;
}
//=======================================================================
//function : AddSelect
//purpose :
//=======================================================================
AIS_SelectStatus AIS_Selection::AddSelect (const Handle(SelectMgr_EntityOwner)& theObject)
{
if (theObject.IsNull()
|| !theObject->HasSelectable()
|| myResultMap.IsBound (theObject))
{
return AIS_SS_NotDone;
}
AIS_NListOfEntityOwner::Iterator aListIter;
myresult.Append (theObject, aListIter);
myResultMap.Bind (theObject, aListIter);
theObject->SetSelected (Standard_True);
return AIS_SS_Added;
}
|
e66f6a26a89140c00c572508e3749750b99bb8fd | 95ff168e880636c72970a8f4b0908d3d2100155f | /servo.ino | 6f7c7979cce181840be23737263b3ea52b7589c0 | [] | no_license | DavScu/Project-Code | f830209f0d69f0c600c8895059347e83d92ba3c3 | 4e3338e5daf1a9939dfd7efe3f9b7ed5e2c2aece | refs/heads/main | 2023-01-12T12:29:19.588598 | 2020-11-19T01:39:21 | 2020-11-19T01:39:21 | 314,105,564 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 546 | ino | servo.ino | #include <Servo.h>
Servo myservo;
int angle = 0;
void setup()
{
// put your setup code here, to run once:
myservo.attach(9);
//down();
//up();
}
void down()
{
myservo.write(100);
for (angle = 100; angle <= 190; angle += 1) {
myservo.write(angle);
delay(600);
}
delay(900);
}
void up()
{
myservo.write(100);
for (angle = 100; angle <= 190; angle -= 1) {
myservo.write(angle);
delay(600);
}
delay(900);
}
void loop() {
// put your main code here, to run repeatedly:
}
|
31b8573fea4f05a43ba3febe2e9c21291c2f79d7 | 5f5a6cbbadf6c3f86da4b7f66a60a1735bafea92 | /counter_shiftreg/shift_reg/shift_reg/shift_reg.cpp | 7ceae90a33d60c3d3aaa9f937ad348965f4be82d | [] | no_license | AntonNikitenko/SystemC | 1db3dfe8a83915a7321c805099e5ddc19710770e | 6130233fababbaf66651b98fc52e0c6a3ac02497 | refs/heads/master | 2021-01-22T20:08:22.444353 | 2017-03-28T12:19:53 | 2017-03-28T12:19:53 | 85,282,589 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 578 | cpp | shift_reg.cpp | #include "shift_reg.h"
void shift_reg::shift() {
// We check if reset is active
data = 0;
data_out = 0;
out = 0;
wait();
while (true) {
if(dir==false){
data.write((data.read().range(6, 0), in.read()));
data_out.write(data.read());
out = (bool)data.read().bit(7);
}
else {
data.write((in.read(),data.read().range(7, 1)));
data_out.write(data.read());
out = (bool)data.read().bit(0);
}
cout << "@" << sc_time_stamp() << " :: Have stored " << data_out.read() << endl;
wait();
}
}
|
f9f5c4346d707eb273e44794e969380d3d4191bb | ed138fd31f62cb7c2b10dc69e14e2908bd2e5646 | /FirstOpenGL/CStringHelper.cpp | 3696adee03f50820965f6e7f00ba426cb54a435f | [] | no_license | WesBach/GameJam | 54b8506ec995b58231f977329e124dd2f629b9ef | 1fdf04c77cffab4b38355b078f77c6b64745a4e8 | refs/heads/master | 2020-03-14T13:22:37.123729 | 2018-05-01T19:56:40 | 2018-05-01T19:56:40 | 124,302,422 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,406 | cpp | CStringHelper.cpp | #include "CStringHelper.h"
#include <sstream>
CStringHelper::~CStringHelper()
{
if (this->m_pTheInstance)
{
delete this->m_pTheInstance;
}
return;
}
/*static*/
CStringHelper* CStringHelper::m_pTheInstance = NULL;
/*static*/
CStringHelper* CStringHelper::getInstance(void)
{
if (CStringHelper::m_pTheInstance == NULL)
{
CStringHelper::m_pTheInstance = new CStringHelper();
}
return CStringHelper::m_pTheInstance;
}
/*static*/
std::wstring CStringHelper::ASCIIToUnicodeQnD(std::string ASCIIString)
{
return CStringHelper::m_pTheInstance->m_ASCIIToUnicodeQnD(ASCIIString);
}
std::wstring CStringHelper::m_ASCIIToUnicodeQnD(std::string ASCIIString)
{
std::wstringstream ss;
for (std::string::iterator itChar = ASCIIString.begin(); itChar != ASCIIString.end(); itChar++)
{
char tempChar = *itChar;
wchar_t tempCharUni = static_cast<wchar_t>(tempChar);
ss << tempCharUni;
}
return ss.str();
}
/*static*/
std::string CStringHelper::UnicodeToASCII_QnD(std::wstring UnicodeString)
{
return CStringHelper::getInstance()->m_UnicodeToASCII_QnD(UnicodeString);
}
std::string CStringHelper::m_UnicodeToASCII_QnD(std::wstring UnicodeString)
{
std::stringstream ssReturnASCII;
for (std::wstring::iterator itChar = UnicodeString.begin(); itChar != UnicodeString.end(); itChar++)
{
char theChar = static_cast<char>(*itChar);
ssReturnASCII << theChar;
}
return ssReturnASCII.str();
} |
3c051ff35c6d84018c6f50fadc1b4538e1897a92 | 4d6f1c83d9dbb972e73bcc6b0afd4ac04ff5e776 | /inputmethods_plat/ptiengine_key_definations_api/tsrc/src/ptiEngTestDomApiBlocks.cpp | e0f7adf6893c07a89ef3ea68b7ef51e72915b3e7 | [] | no_license | SymbianSource/oss.FCL.sf.mw.inputmethods | 344aff3e5dc049d050c0626210de231737bbf441 | 51e877bef2e0a93793490fba6e97b04aaa1ee368 | refs/heads/master | 2021-01-13T08:38:51.371385 | 2010-10-03T21:39:41 | 2010-10-03T21:39:41 | 71,818,739 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 44,376 | cpp | ptiEngTestDomApiBlocks.cpp | /*
* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0""
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: ?Description
*
*/
// [INCLUDE FILES] - do not remove
#include <e32svr.h>
#include <StifParser.h>
#include <StifTestInterface.h>
#include "ptiEngTestDomApi.h"
#include <PtiCore.h>
#include <PtiEngine.h>
#include <ecom/ecom.h>
#include <PtiUserDictionary.h>
#include <PtiLanguage.h>
#include <PtiKeyMappings.h>
#include <PtiLanguageDatabase.h>
#include <PtiUserDicEntry.h>
#include <PtiUids.hrh>
#include <PtiKeyMapData.h>
#include <AknInputLanguageInfo.h>
#include <e32lang.h>
#include <PtiKeyboardDatabase.h>
// EXTERNAL DATA STRUCTURES
//extern ?external_data;
// EXTERNAL FUNCTION PROTOTYPES
//extern ?external_function( ?arg_type,?arg_type );
// CONSTANTS
//const ?type ?constant_var = ?constant;
// MACROS
//#define ?macro ?macro_def
// LOCAL CONSTANTS AND MACROS
//const ?type ?constant_var = ?constant;
//#define ?macro_name ?macro_def
// MODULE DATA STRUCTURES
//enum ?declaration
//typedef ?declaration
// LOCAL FUNCTION PROTOTYPES
//?type ?function_name( ?arg_type, ?arg_type );
// FORWARD DECLARATIONS
//class ?FORWARD_CLASSNAME;
// ============================= LOCAL FUNCTIONS ===============================
// -----------------------------------------------------------------------------
// ?function_name ?description.
// ?description
// Returns: ?value_1: ?description
// ?value_n: ?description_line1
// ?description_line2
// -----------------------------------------------------------------------------
//
/*
?type ?function_name(
?arg_type arg, // ?description
?arg_type arg) // ?description
{
?code // ?comment
// ?comment
?code
}
*/
// ============================ MEMBER FUNCTIONS ===============================
// -----------------------------------------------------------------------------
// CptiEngTestDomApi::Delete
// Delete here all resources allocated and opened from test methods.
// Called from destructor.
// -----------------------------------------------------------------------------
//
void CptiEngTestDomApi::Delete()
{
}
// -----------------------------------------------------------------------------
// CptiEngTestDomApi::RunMethodL
// Run specified method. Contains also table of test mothods and their names.
// -----------------------------------------------------------------------------
//
TInt CptiEngTestDomApi::RunMethodL(
CStifItemParser& aItem )
{
static TStifFunctionInfo const KFunctions[] =
{
ENTRY( "PtiTestKeyBindings", CptiEngTestDomApi::PtiTestKeyMapDataKeyBindingsL),
ENTRY( "PtiTestLanguages", CptiEngTestDomApi::PtiTestKeyMapDataLanguagesL),
ENTRY( "PtiTestKeys", CptiEngTestDomApi::PtiTestKeyMapDataTestkeysL),
ENTRY( "PtiTestDeadKeys", CptiEngTestDomApi::PtiTestKeyMapDataTestDeadkeysL),
ENTRY( "PtiTestNumericKeys", CptiEngTestDomApi::PtiTestKeyMapDataTestNumerickeysL),
ENTRY( "PtiTestVowels", CptiEngTestDomApi::PtiTestKeyMapDataTestVowelsL),
ENTRY( "PtiTestOthers", CptiEngTestDomApi::PtiTestKeyMapDataTestOthersL),
ENTRY( "PtiTestDataFactory", CptiEngTestDomApi::PtiTestKeyMapDataFactoryL),
ENTRY( "PtiTestKeyboardDatabase", CptiEngTestDomApi::PtiTestKeyboardDatabaseFactoryL),
// [test cases entries] - Do not remove
};
const TInt count = sizeof( KFunctions ) /
sizeof( TStifFunctionInfo );
return RunInternalL( KFunctions, count, aItem );
}
// -----------------------------------------------------------------------------
// CptiEngTestDomApi::PtiTestKeyMapDataKeyBindingsL
// Example test method function.
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
TInt CptiEngTestDomApi::PtiTestKeyMapDataKeyBindingsL()
{
__UHEAP_MARK;
TInt errStatus = KErrNone;
CPtiKeyMapData * keyMapData = static_cast<CPtiKeyMapData*>(GetKeyMapDataL());
TPtiKey key = EPtiKey1;
TPtiTextCase ptiCase =EPtiCaseLower;
TInt index = keyMapData->CaseBasedIndexInBindingTable(EPtiKeyboard12Key,key,ptiCase);
if(index != 0)
{
errStatus = KErrGeneral;
iLog->Log(_L("CptiEngTestDomApi : CaseBasedIndexInBindingTable for EPtiKeyboard12Key,EPtiKey1,EPtiCaseLower returned something other than 0"));
}
else
iLog->Log(_L("CptiEngTestDomApi : CaseBasedIndexInBindingTable for EPtiKeyboard12Key,EPtiKey1,EPtiCaseLower returned 0"));
TPtiTextCase ptiCase1;
TPtiKey key1 =keyMapData->KeyForBindingTableIndex(EPtiKeyboard12Key,index,ptiCase1);
if( (ptiCase != ptiCase1) || (key != key1))
{
errStatus = KErrGeneral;
iLog->Log(_L("CptiEngTestDomApi : KeyForBindingTableIndex for EPtiKeyboard12Key,index 0 returned something other than EPtiKey1"));
}
else
iLog->Log(_L("CptiEngTestDomApi : KeyForBindingTableIndex for EPtiKeyboard12Key,index 0 returned EPtiKey1"));
delete keyMapData;
REComSession::FinalClose();
iLog->Log(_L(" "));
__UHEAP_MARKEND;
return errStatus;
}
// -----------------------------------------------------------------------------
// CptiEngTestDomApi::PtiTestKeyMapDataLanguagesL
// Example test method function.
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
TInt CptiEngTestDomApi::PtiTestKeyMapDataLanguagesL()
{
__UHEAP_MARK;
TInt errStatus = KErrNone;
CPtiKeyMapData * keyMapData = static_cast<CPtiKeyMapData*>(GetKeyMapDataL());
RArray<TInt> langList;
//CPtiKeyMapData::ListLanguagesL(langList); No implementation but exported in .h file :(
TInt langCode =keyMapData->LanguageCode();
if( langCode != 01) //01 is for english
{
errStatus = KErrGeneral;
iLog->Log(_L("CptiEngTestDomApi : LanguageCode for english returned something other than 01"));
}
else
iLog->Log(_L("CptiEngTestDomApi : LanguageCode for english 01"));
langList.Close();
delete keyMapData;
REComSession::FinalClose();
iLog->Log(_L(" "));
__UHEAP_MARKEND;
return errStatus;
}
// -----------------------------------------------------------------------------
// CptiEngTestDomApi::PtiTestKeyMapDataTestkeysL
// Example test method function.
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
TInt CptiEngTestDomApi::PtiTestKeyMapDataTestkeysL()
{
__UHEAP_MARK;
TInt errStatus = KErrNone;
CPtiKeyMapData * keyMapData = static_cast<CPtiKeyMapData*>(GetKeyMapDataL());
if((TInt)EFalse == keyMapData->HasKeyData(EPtiKeyboard12Key))
{
errStatus = KErrGeneral;
iLog->Log(_L("CptiEngTestDomApi : HasKeyData for EPtiKeyboard12Key returned EFlase"));
}
else
iLog->Log(_L("CptiEngTestDomApi : HasKeyData for EPtiKeyboard12Key returned ETrue"));
if((TInt)EFalse == keyMapData->HasKeyData(EPtiKeyboardQwerty4x12))
{
errStatus = KErrGeneral;
iLog->Log(_L("CptiEngTestDomApi : HasKeyData for EPtiKeyboardQwerty4x12 returned EFlase"));
}
else
iLog->Log(_L("CptiEngTestDomApi : HasKeyData for EPtiKeyboardQwerty4x12 returned ETrue"));
if((TInt)EFalse == keyMapData->HasKeyData(EPtiKeyboardQwerty4x10))
{
errStatus = KErrGeneral;
iLog->Log(_L("CptiEngTestDomApi : HasKeyData for EPtiKeyboardQwerty4x10 returned EFlase"));
}
else
iLog->Log(_L("CptiEngTestDomApi : HasKeyData for EPtiKeyboardQwerty4x10 returned ETrue"));
if((TInt)EFalse == keyMapData->HasKeyData(EPtiKeyboardQwerty3x11))
{
errStatus = KErrGeneral;
iLog->Log(_L("CptiEngTestDomApi : HasKeyData for EPtiKeyboardQwerty3x11 returned EFlase"));
}
else
iLog->Log(_L("CptiEngTestDomApi : HasKeyData for EPtiKeyboardQwerty3x11 returned ETrue"));
if((TInt)EFalse == keyMapData->HasKeyData(EPtiKeyboardHalfQwerty))
{
errStatus = KErrGeneral;
iLog->Log(_L("CptiEngTestDomApi : HasKeyData for EPtiKeyboardHalfQwerty returned EFlase"));
}
else
iLog->Log(_L("CptiEngTestDomApi : HasKeyData for EPtiKeyboardHalfQwerty returned ETrue"));
TBuf<200> dataforkey1_0(keyMapData->DataForKey(EPtiKeyboard12Key,EPtiKey1,EPtiCaseLower));
if(0 == dataforkey1_0.Length())
{
errStatus = KErrGeneral;
iLog->Log(_L("CptiEngTestDomApi : DataForKey for EPtiKeyboard12Key returned NULL"));
}
else
iLog->Log(_L("CptiEngTestDomApi : DataForKey for EPtiKeyboard12Key returned valid data"));
TBuf<200> dataforkey1_1(keyMapData->DataForKey(EPtiKeyboard12Key,0));
if(0 == dataforkey1_1.Length())
{
errStatus = KErrGeneral;
iLog->Log(_L("CptiEngTestDomApi : DataForKey for EPtiKeyboard12Key returned NULL"));
}
else
iLog->Log(_L("CptiEngTestDomApi : DataForKey for EPtiKeyboard12Key returned valid data"));
TInt numberOfKeys =keyMapData->NumberOfKeys(EPtiKeyboard12Key);
if( 12 != numberOfKeys)
{
errStatus = KErrGeneral;
iLog->Log(_L("CptiEngTestDomApi : NumberOfKeys for EPtiKeyboard12Key returned something other than 12 "));
}
else
iLog->Log(_L("CptiEngTestDomApi : NumberOfKeys for EPtiKeyboard12Key returned 12 "));
TInt dataSize =0;
const TUint16* keyData= keyMapData->KeyData(EPtiKeyboard12Key,dataSize);
if((dataSize <=0) || (keyData == NULL))
{
errStatus = KErrGeneral;
iLog->Log(_L("CptiEngTestDomApi : KeyData for EPtiKeyboard12Key returned NULL"));
}
else
iLog->Log(_L("CptiEngTestDomApi : KeyData for EPtiKeyboard12Key returned valid pointer"));
TInt numOfItems =0;
const TPtiKeyBinding* keyBindings = keyMapData->KeyBindingTable(EPtiKeyboard12Key,numOfItems);
if((numOfItems <=0) || (keyBindings == NULL))
{
errStatus = KErrGeneral;
iLog->Log(_L("CptiEngTestDomApi : KeyBindingTable for EPtiKeyboard12Key returned NULL"));
}
else
iLog->Log(_L("CptiEngTestDomApi : KeyBindingTable for EPtiKeyboard12Key returned valid pointer"));
delete keyMapData;
//This part of the code is to just to make sure that below API's are called
//KeyBindingTable,KeyData,LanguageCode
CPtiKeyMapData * keyMapDataDummy = NULL;
keyMapDataDummy = new CPtiKeyMapData();
if(keyMapDataDummy)
{
TInt dummyItems =0;
keyMapDataDummy->KeyBindingTable(EPtiKeyboard12Key,dummyItems);
keyMapDataDummy->KeyData(EPtiKeyboard12Key,dummyItems);
keyMapDataDummy->LanguageCode();
}
delete keyMapDataDummy;
keyMapDataDummy = NULL;
REComSession::FinalClose();
iLog->Log(_L(" "));
__UHEAP_MARKEND;
return errStatus;
}
// -----------------------------------------------------------------------------
// CptiEngTestDomApi::PtiTestKeyMapDataTestDeadkeysL
// Example test method function.
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
TInt CptiEngTestDomApi::PtiTestKeyMapDataTestDeadkeysL()
{
__UHEAP_MARK;
TInt errStatus = KErrNone;
CPtiKeyMapData * keyMapData = static_cast<CPtiKeyMapData*>(GetKeyMapDataL());
if( TInt(ETrue) == keyMapData->IsDeadKey(EPtiKeyboard12Key,EPtiKey1 ,EPtiCaseLower))
{
iLog->Log(_L("CptiEngTestDomApi : IsDeadKey for EPtiKeyboard12Key,EPtiKey1,EPtiCaseLower returned ETrue"));
}
else
iLog->Log(_L("CptiEngTestDomApi : IsDeadKey for EPtiKeyboard12Key,EPtiKey1,EPtiCaseLower returned EFalse"));
TBuf<100> deadKeyData(keyMapData->DeadKeyDataForKey(EPtiKeyboard12Key,EPtiKey1 ,EPtiCaseLower));
if(deadKeyData.Length() == 0)
{
iLog->Log(_L("CptiEngTestDomApi : DeadKeyDataForKey for EPtiKeyboard12Key,EPtiKey1,EPtiCaseLower returned emptystring"));
}
else
iLog->Log(_L("CptiEngTestDomApi : DeadKeyDataForKey for EPtiKeyboard12Key,EPtiKey1,EPtiCaseLower returned valid data"));
delete keyMapData;
//Loop thru all the keymapings for vowel table
RArray<TInt> dataImpl;
CPtiKeyMapDataFactory::ListImplementationsL(dataImpl);
TInt tempVal1=0;
TInt tempVal2=0;
for(TInt a =0;a<dataImpl.Count();a++)
{
CPtiKeyMapDataFactory * keymapDatafactory = CPtiKeyMapDataFactory::CreateImplementationL(TUid::Uid(dataImpl[a]));
CleanupStack::PushL(keymapDatafactory);
RArray<TInt> langList;
keymapDatafactory->ListLanguagesL(langList);
for(TInt b=0;b<langList.Count();b++)
{
CPtiKeyMapData * keyMapData =NULL;
keyMapData = static_cast<CPtiKeyMapData*>(keymapDatafactory->KeyMapDataForLanguageL(langList[b]));
if( TInt(ETrue) == keyMapData->HasDeadKeys(EPtiKeyboard12Key))
{
TBuf<200> data(_L("CptiEngTestDomApi : HasDeadKeys for key board EPtiKeyboard12Key returned ETrue for lang"));
data.AppendNum(langList[b]);
iLog->Log(data);
tempVal1 =1;
}
TInt numOfRows =0;
const TUint16* deadKeyDataArray1= keyMapData->DeadKeyDataArray(EPtiKeyboard12Key,numOfRows);
if(deadKeyDataArray1 != NULL)
{
TBuf<200> data(_L("CptiEngTestDomApi : DeadKeyDataArray for key board EPtiKeyboard12Key is there for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
tempVal2 =1;
}
UpdateLogForDeadKeys(tempVal1,tempVal2,langList[b],errStatus);
tempVal1=tempVal2=0;
if( TInt(ETrue) == keyMapData->HasDeadKeys(EPtiKeyboardQwerty4x12))
{
TBuf<200> data(_L("CptiEngTestDomApi : HasDeadKeys for key board EPtiKeyboardQwerty4x12 returned ETrue for lang"));
data.AppendNum(langList[b]);
iLog->Log(data);
tempVal1 =1;
}
const TUint16* deadKeyDataArray2 = keyMapData->DeadKeyDataArray(EPtiKeyboardQwerty4x12,numOfRows);
if(deadKeyDataArray2 != NULL)
{
TBuf<200> data(_L("CptiEngTestDomApi : DeadKeyDataArray for key board EPtiKeyboardQwerty4x12 is there for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
tempVal2 =1;
}
UpdateLogForDeadKeys(tempVal1,tempVal2,langList[b],errStatus);
tempVal1=tempVal2=0;
if( TInt(ETrue) == keyMapData->HasDeadKeys(EPtiKeyboardQwerty4x10))
{
TBuf<200> data(_L("CptiEngTestDomApi : HasDeadKeys for key board EPtiKeyboardQwerty4x10 returned ETrue for lang"));
data.AppendNum(langList[b]);
iLog->Log(data);
tempVal1 =1;
}
const TUint16* deadKeyDataArray3 = keyMapData->DeadKeyDataArray(EPtiKeyboardQwerty4x10,numOfRows);
if(deadKeyDataArray3 != NULL)
{
TBuf<200> data(_L("CptiEngTestDomApi : DeadKeyDataArray for key board EPtiKeyboardQwerty4x10 is there for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
tempVal2 =1;
}
UpdateLogForDeadKeys(tempVal1,tempVal2,langList[b],errStatus);
tempVal1=tempVal2=0;
if( TInt(ETrue) == keyMapData->HasDeadKeys(EPtiKeyboardQwerty3x11))
{
TBuf<200> data(_L("CptiEngTestDomApi : HasDeadKeys for key board EPtiKeyboardQwerty3x11 returned ETrue for lang"));
data.AppendNum(langList[b]);
iLog->Log(data);
tempVal1 =1;
}
const TUint16* deadKeyDataArray4 = keyMapData->DeadKeyDataArray(EPtiKeyboardQwerty3x11,numOfRows);
if(deadKeyDataArray4 != NULL)
{
TBuf<200> data(_L("CptiEngTestDomApi : DeadKeyDataArray for key board EPtiKeyboardQwerty3x11 is there for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
tempVal2 =1;
}
UpdateLogForDeadKeys(tempVal1,tempVal2,langList[b],errStatus);
tempVal1=tempVal2=0;
if( TInt(ETrue) == keyMapData->HasDeadKeys(EPtiKeyboardHalfQwerty))
{
TBuf<200> data(_L("CptiEngTestDomApi : HasDeadKeys for key board EPtiKeyboardHalfQwerty returned ETrue for lang"));
data.AppendNum(langList[b]);
iLog->Log(data);
tempVal1 =1;
}
const TUint16* deadKeyDataArray5 = keyMapData->DeadKeyDataArray(EPtiKeyboardHalfQwerty,numOfRows);
if(deadKeyDataArray5 != NULL)
{
TBuf<200> data(_L("CptiEngTestDomApi : DeadKeyDataArray for key board EPtiKeyboardHalfQwerty is there for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
tempVal2 =1;
}
UpdateLogForDeadKeys(tempVal1,tempVal2,langList[b],errStatus);
tempVal1=tempVal2=0;
delete keyMapData;
}
langList.Close();
CleanupStack::PopAndDestroy(keymapDatafactory); //keymapDatafactory
}
dataImpl.Close();
REComSession::FinalClose();
iLog->Log(_L(" "));
__UHEAP_MARKEND;
return errStatus;
}
void CptiEngTestDomApi::UpdateLogForDeadKeys(TInt aVal,TInt bVal, TInt aLang,TInt &aErrStatus)
{
if(aVal != bVal)
{
aErrStatus = KErrGeneral;
TBuf<200> data(_L("CptiEngTestDomApi : HasDeadKeys & DeadKeyDataArray conflict for lang "));
data.AppendNum(aLang);
iLog->Log(data);
}
}
// -----------------------------------------------------------------------------
// CptiEngTestDomApi::PtiTestKeyMapDataTestNumerickeysL
// Example test method function.
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
TInt CptiEngTestDomApi::PtiTestKeyMapDataTestNumerickeysL()
{
__UHEAP_MARK;
TInt errStatus = KErrNone;
//Loop thru all the keymapings for Numeric Key table
RArray<TInt> dataImpl;
CPtiKeyMapDataFactory::ListImplementationsL(dataImpl);
for(TInt a =0;a<dataImpl.Count();a++)
{
CPtiKeyMapDataFactory * keymapDatafactory = CPtiKeyMapDataFactory::CreateImplementationL(TUid::Uid(dataImpl[a]));
CleanupStack::PushL(keymapDatafactory);
RArray<TInt> langList;
keymapDatafactory->ListLanguagesL(langList);
for(TInt b=0;b<langList.Count();b++)
{
CPtiKeyMapData * keyMapData =NULL;
keyMapData = static_cast<CPtiKeyMapData*>(keymapDatafactory->KeyMapDataForLanguageL(langList[b]));
RArray<TPtiNumericKeyBinding> numericModeKeys;
keyMapData->GetNumericModeKeysL(EPtiKeyboard12Key,numericModeKeys);
if(numericModeKeys.Count() >0)
{
TBuf<200> data(_L("CptiEngTestDomApi : GetNumericModeKeysL for key board EPtiKeyboard12Key returned a valide Numeric Kay Bindings for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
for(TInt a=0;a<numericModeKeys.Count();a++)
{
if(TInt(ETrue) == keyMapData->IsNumberModeKey(EPtiKeyboard12Key,numericModeKeys[a]))
{
TBuf<200> data(_L("CptiEngTestDomApi : IsNumberModeKey for key board EPtiKeyboard12Key with key "));
data.AppendNum(numericModeKeys[a].iKey);
data.Append(_L(" returned ETrue for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
}
}
numericModeKeys.Reset();
}
TInt numOfEntries;
const TPtiNumericKeyBinding* numericKeyBindings = NULL;
numericKeyBindings = keyMapData->NumericModeKeysTable(EPtiKeyboard12Key,numOfEntries);
if(numericKeyBindings != NULL)
{
TBuf<200> data(_L("CptiEngTestDomApi : NumericModeKeysTable for key board EPtiKeyboard12Key is there for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
}
keyMapData->GetNumericModeKeysL(EPtiKeyboardQwerty4x12,numericModeKeys);
if(numericModeKeys.Count() >0)
{
TBuf<200> data(_L("CptiEngTestDomApi : GetNumericModeKeysL for key board EPtiKeyboardQwerty4x12 returned a valide Numeric Kay Bindings for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
for(TInt a=0;a<numericModeKeys.Count();a++)
{
if(TInt(ETrue) == keyMapData->IsNumberModeKey(EPtiKeyboardQwerty4x12,numericModeKeys[a]))
{
TBuf<200> data(_L("CptiEngTestDomApi : IsNumberModeKey for key board EPtiKeyboardQwerty4x12 with key "));
data.AppendNum(numericModeKeys[a].iKey);
data.Append(_L(" returned ETrue for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
}
}
numericModeKeys.Reset();
}
numericKeyBindings = keyMapData->NumericModeKeysTable(EPtiKeyboardQwerty4x12,numOfEntries);
if(numericKeyBindings != NULL)
{
TBuf<200> data(_L("CptiEngTestDomApi : NumericModeKeysTable for key board EPtiKeyboardQwerty4x12 is there for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
}
keyMapData->GetNumericModeKeysL(EPtiKeyboardQwerty4x10,numericModeKeys);
if(numericModeKeys.Count() >0)
{
TBuf<200> data(_L("CptiEngTestDomApi : GetNumericModeKeysL for key board EPtiKeyboardQwerty4x10 returned a valide Numeric Kay Bindings for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
for(TInt a=0;a<numericModeKeys.Count();a++)
{
if(TInt(ETrue) == keyMapData->IsNumberModeKey(EPtiKeyboardQwerty4x10,numericModeKeys[a]))
{
TBuf<200> data(_L("CptiEngTestDomApi : IsNumberModeKey for key board EPtiKeyboardQwerty4x10 with key "));
data.AppendNum(numericModeKeys[a].iKey);
data.Append(_L(" returned ETrue for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
}
}
numericModeKeys.Reset();
}
numericKeyBindings = keyMapData->NumericModeKeysTable(EPtiKeyboardQwerty4x10,numOfEntries);
if(numericKeyBindings != NULL)
{
TBuf<200> data(_L("CptiEngTestDomApi : NumericModeKeysTable for key board EPtiKeyboardQwerty4x10 is there for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
}
keyMapData->GetNumericModeKeysL(EPtiKeyboardQwerty3x11,numericModeKeys);
if(numericModeKeys.Count() >0)
{
TBuf<200> data(_L("CptiEngTestDomApi : GetNumericModeKeysL for key board EPtiKeyboardQwerty3x11 returned a valide Numeric Kay Bindings for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
for(TInt a=0;a<numericModeKeys.Count();a++)
{
if(TInt(ETrue) == keyMapData->IsNumberModeKey(EPtiKeyboardQwerty3x11,numericModeKeys[a]))
{
TBuf<200> data(_L("CptiEngTestDomApi : IsNumberModeKey for key board EPtiKeyboardQwerty3x11 with key "));
data.AppendNum(numericModeKeys[a].iKey);
data.Append(_L(" returned ETrue for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
}
}
numericModeKeys.Reset();
}
numericKeyBindings = keyMapData->NumericModeKeysTable(EPtiKeyboardQwerty3x11,numOfEntries);
if(numericKeyBindings != NULL)
{
TBuf<200> data(_L("CptiEngTestDomApi : NumericModeKeysTable for key board EPtiKeyboardQwerty3x11 is there for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
}
keyMapData->GetNumericModeKeysL(EPtiKeyboardHalfQwerty,numericModeKeys);
if(numericModeKeys.Count() >0)
{
TBuf<200> data(_L("CptiEngTestDomApi : GetNumericModeKeysL for key board EPtiKeyboardHalfQwerty returned a valide Numeric Kay Bindings for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
for(TInt a=0;a<numericModeKeys.Count();a++)
{
if(TInt(ETrue) == keyMapData->IsNumberModeKey(EPtiKeyboardHalfQwerty,numericModeKeys[a]))
{
TBuf<200> data(_L("CptiEngTestDomApi : IsNumberModeKey for key board EPtiKeyboardHalfQwerty with key "));
data.AppendNum(numericModeKeys[a].iKey);
data.Append(_L(" returned ETrue for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
}
}
numericModeKeys.Reset();
}
numericKeyBindings = keyMapData->NumericModeKeysTable(EPtiKeyboardHalfQwerty,numOfEntries);
if(numericKeyBindings != NULL)
{
TBuf<200> data(_L("CptiEngTestDomApi : NumericModeKeysTable for key board EPtiKeyboardHalfQwerty is there for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
}
delete keyMapData;
numericModeKeys.Close();
}
langList.Close();
CleanupStack::PopAndDestroy(keymapDatafactory); //keymapDatafactory
}
dataImpl.Close();
REComSession::FinalClose();
iLog->Log(_L(" "));
__UHEAP_MARKEND;
return errStatus;
}
// -----------------------------------------------------------------------------
// CptiEngTestDomApi::PtiTestKeyMapDataTestVowelsL
// Example test method function.
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
TInt CptiEngTestDomApi::PtiTestKeyMapDataTestVowelsL()
{
__UHEAP_MARK;
TInt errStatus = KErrNone;
//Loop thru all the keymapings for vowel table
RArray<TInt> dataImpl;
CPtiKeyMapDataFactory::ListImplementationsL(dataImpl);
TInt tempVal1=0;
TInt tempVal2=0;
for(TInt a =0;a<dataImpl.Count();a++)
{
CPtiKeyMapDataFactory * keymapDatafactory = CPtiKeyMapDataFactory::CreateImplementationL(TUid::Uid(dataImpl[a]));
CleanupStack::PushL(keymapDatafactory);
RArray<TInt> langList;
keymapDatafactory->ListLanguagesL(langList);
for(TInt b=0;b<langList.Count();b++)
{
CPtiKeyMapData * keyMapData =NULL;
keyMapData = static_cast<CPtiKeyMapData*>(keymapDatafactory->KeyMapDataForLanguageL(langList[b]));
if(TInt(ETrue) == keyMapData->HasVowelSequences(EPtiKeyboard12Key))
{
TBuf<200> data(_L("CptiEngTestDomApi : HasVowelSequences for key board EPtiKeyboard12Key returned ETrue for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
tempVal1 =1;
}
TInt numOfEntries;
const TVowelSequence* vowelsSequance = NULL;
vowelsSequance = keyMapData->VowelSequenceTable(EPtiKeyboard12Key,numOfEntries);
if(vowelsSequance != NULL)
{
TBuf<200> data(_L("CptiEngTestDomApi : VowelSequenceTable for key board EPtiKeyboard12Key is there for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
tempVal2 =1;
}
UpdateLogForVowels(tempVal1,tempVal2,langList[b],errStatus);
tempVal1=tempVal2=0;
if(TInt(ETrue) == keyMapData->HasVowelSequences(EPtiKeyboardQwerty4x12))
{
TBuf<200> data(_L("CptiEngTestDomApi : HasVowelSequences for key board EPtiKeyboardQwerty4x12 returned ETrue for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
tempVal1 =1;
}
vowelsSequance = keyMapData->VowelSequenceTable(EPtiKeyboardQwerty4x12,numOfEntries);
if(vowelsSequance != NULL)
{
TBuf<200> data(_L("CptiEngTestDomApi : VowelSequenceTable for key board EPtiKeyboardQwerty4x12 is there for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
tempVal2 =1;
}
UpdateLogForVowels(tempVal1,tempVal2,langList[b],errStatus);
tempVal1=tempVal2=0;
if(TInt(ETrue) == keyMapData->HasVowelSequences(EPtiKeyboardQwerty4x10))
{
TBuf<200> data(_L("CptiEngTestDomApi : HasVowelSequences for key board EPtiKeyboardQwerty4x10 returned ETrue for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
tempVal1 =1;
}
vowelsSequance = keyMapData->VowelSequenceTable(EPtiKeyboardQwerty4x10,numOfEntries);
if(vowelsSequance != NULL)
{
TBuf<200> data(_L("CptiEngTestDomApi : VowelSequenceTable for key board EPtiKeyboardQwerty4x10 is there for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
tempVal2 =1;
}
UpdateLogForVowels(tempVal1,tempVal2,langList[b],errStatus);
tempVal1=tempVal2=0;
if(TInt(ETrue) == keyMapData->HasVowelSequences(EPtiKeyboardQwerty3x11))
{
TBuf<200> data(_L("CptiEngTestDomApi : HasVowelSequences for key board EPtiKeyboardQwerty3x11 returned ETrue for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
tempVal1 =1;
}
vowelsSequance = keyMapData->VowelSequenceTable(EPtiKeyboardQwerty3x11,numOfEntries);
if(vowelsSequance != NULL)
{
TBuf<200> data(_L("CptiEngTestDomApi : VowelSequenceTable for key board EPtiKeyboardQwerty3x11 is there for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
tempVal2 =1;
}
UpdateLogForVowels(tempVal1,tempVal2,langList[b],errStatus);
tempVal1=tempVal2=0;
if(TInt(ETrue) == keyMapData->HasVowelSequences(EPtiKeyboardHalfQwerty))
{
TBuf<200> data(_L("CptiEngTestDomApi : HasVowelSequences for key board EPtiKeyboardHalfQwerty returned ETrue for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
tempVal1 =1;
}
vowelsSequance = keyMapData->VowelSequenceTable(EPtiKeyboardHalfQwerty,numOfEntries);
if(vowelsSequance != NULL)
{
TBuf<200> data(_L("CptiEngTestDomApi : VowelSequenceTable for key board EPtiKeyboardHalfQwerty is there for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
tempVal2 =1;
}
UpdateLogForVowels(tempVal1,tempVal2,langList[b],errStatus);
tempVal1=tempVal2=0;
delete keyMapData;
}
langList.Close();
CleanupStack::PopAndDestroy(keymapDatafactory); //keymapDatafactory
}
dataImpl.Close();
REComSession::FinalClose();
iLog->Log(_L(" "));
__UHEAP_MARKEND;
return errStatus;
}
void CptiEngTestDomApi::UpdateLogForVowels(TInt aVal,TInt bVal, TInt aLang,TInt &aErrStatus)
{
if(aVal != bVal)
{
aErrStatus = KErrGeneral;
TBuf<200> data(_L("CptiEngTestDomApi : HasVowelSequences & VowelSequenceTable conflict for lang "));
data.AppendNum(aLang);
iLog->Log(data);
}
}
// -----------------------------------------------------------------------------
// CptiEngTestDomApi::PtiTestKeyMapDataTestOthersL
// Example test method function.
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
TInt CptiEngTestDomApi::PtiTestKeyMapDataTestOthersL()
{
__UHEAP_MARK;
TInt errStatus = KErrNone;
CPtiKeyMapData * keyMapData = static_cast<CPtiKeyMapData*>(GetKeyMapDataL());
//for future use
keyMapData->Reserved_1();
keyMapData->Reserved_2();
keyMapData->Reserved_3();
keyMapData->Reserved_4();
delete keyMapData;
//Loop thru all the keymapings for latin modes
RArray<TInt> dataImpl;
CPtiKeyMapDataFactory::ListImplementationsL(dataImpl);
for(TInt a =0;a<dataImpl.Count();a++)
{
CPtiKeyMapDataFactory * keymapDatafactory = CPtiKeyMapDataFactory::CreateImplementationL(TUid::Uid(dataImpl[a]));
CleanupStack::PushL(keymapDatafactory);
RArray<TInt> langList;
keymapDatafactory->ListLanguagesL(langList);
for(TInt b=0;b<langList.Count();b++)
{
CPtiKeyMapData * keyMapData =NULL;
keyMapData = static_cast<CPtiKeyMapData*>(keymapDatafactory->KeyMapDataForLanguageL(langList[b]));
TBool boolValue1 = keyMapData->SuitableForLatinOnlyMode();
if((TInt)boolValue1 == EFalse )
{
TBuf<200> data(_L("CptiEngTestDomApi : SuitableForLatinOnlyMode returned EFalse for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
}
else
{
TBuf<200> data(_L("CptiEngTestDomApi : SuitableForLatinOnlyMode returned ETrue for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
}
if(TInt(ETrue) == keyMapData->HasFnKeyBindings(EPtiKeyboard12Key))
{
TBuf<200> data(_L("CptiEngTestDomApi : HasFnKeyBindings for key board EPtiKeyboard12Key returned ETrue for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
}
if(TInt(ETrue) == keyMapData->HasFnKeyBindings(EPtiKeyboardQwerty4x12))
{
TBuf<200> data(_L("CptiEngTestDomApi : HasFnKeyBindings for key board EPtiKeyboardQwerty4x12 returned ETrue for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
}
if(TInt(ETrue) == keyMapData->HasFnKeyBindings(EPtiKeyboardQwerty4x10))
{
TBuf<200> data(_L("CptiEngTestDomApi : HasFnKeyBindings for key board EPtiKeyboardQwerty4x10 returned ETrue for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
}
if(TInt(ETrue) == keyMapData->HasFnKeyBindings(EPtiKeyboardQwerty3x11))
{
TBuf<200> data(_L("CptiEngTestDomApi : HasFnKeyBindings for key board EPtiKeyboardQwerty3x11 returned ETrue for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
}
if(TInt(ETrue) == keyMapData->HasFnKeyBindings(EPtiKeyboardHalfQwerty))
{
TBuf<200> data(_L("CptiEngTestDomApi : HasFnKeyBindings for key board EPtiKeyboardHalfQwerty returned ETrue for lang "));
data.AppendNum(langList[b]);
iLog->Log(data);
}
delete keyMapData;
}
langList.Close();
CleanupStack::PopAndDestroy(keymapDatafactory); //keymapDatafactory
}
dataImpl.Close();
REComSession::FinalClose();
iLog->Log(_L(" "));
__UHEAP_MARKEND;
return errStatus;
}
// -----------------------------------------------------------------------------
// CptiEngTestDomApi::PtiTestKeyMapDataTestDataFactoryL
// Example test method function.
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
TInt CptiEngTestDomApi::PtiTestKeyMapDataFactoryL()
{
__UHEAP_MARK;
TInt errStatus = KErrNone;
RArray<TInt> implList;
TRAP(errStatus,CPtiKeyMapDataFactory::ListImplementationsL(implList));
if(errStatus != KErrNone)
{
iLog->Log(_L("CptiEngTestDomApi : ListImplementationsL leaved"));
}
if(implList.Count() > 0)
{
CPtiKeyMapDataFactory* dataFactory = NULL;
TRAP(errStatus, dataFactory = CPtiKeyMapDataFactory::CreateImplementationL(TUid::Uid(implList[0])));
if(errStatus != KErrNone)
{
iLog->Log(_L("CptiEngTestDomApi : CPtiKeyMapDataFactory leaved"));
}
else
delete dataFactory;
}
else
{
errStatus = KErrGeneral;
iLog->Log(_L("CptiEngTestDomApi : ListImplementationsL returned <0"));
}
implList.Close();
class tempclass :public CPtiKeyMapDataFactory
{
public:
MPtiKeyMapData* KeyMapDataForLanguageL(TInt aLanguageCode)
{
return NULL; // Just return NULL
}
void ListLanguagesL(RArray<TInt>& aResult)
{
//Empty
}
};
CPtiKeyMapDataFactory * dataFactory = new tempclass();
dataFactory->Reserved_1();
dataFactory->Reserved_2();
delete dataFactory;
REComSession::FinalClose();
iLog->Log(_L(" "));
__UHEAP_MARKEND;
return errStatus;
}
// -----------------------------------------------------------------------------
// CptiEngTestDomApi::PtiTestKeyboardDatabaseFactoryL
// Example test method function.
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
TInt CptiEngTestDomApi::PtiTestKeyboardDatabaseFactoryL()
{
__UHEAP_MARK;
TInt errStatus = KErrNone;
iLog->Log(_L("CptiEngTestDomApi : CPtiKeyboardDatabase is very specific to XT9 engine"));
CPtiKeyboardDatabaseFactory * dataFactory = NULL;
RArray<TPtiKeyboardDatabaseMappingOpaque> result;
CleanupClosePushL(result);
RArray<TInt> implResult;
CleanupClosePushL(implResult);
CPtiKeyboardDatabaseFactory::ListImplementationsL(0x2000BEFF,implResult); //0x2000BEFF is interface uid for T9 keyboard plugins
if(implResult.Count() > 0)
{
iLog->Log(_L("CptiEngTestDomApi : PtiTestKeyboardDatabaseFactoryL returned a valid list of imples"));
CPtiKeyboardDatabaseFactory::CreateMappingTableWithOpaqueL(0x2000BEFF,result);
if(result.Count() >0 )
{
iLog->Log(_L("CptiEngTestDomApi : CreateMappingTableWithOpaqueL returned a valid list of TPtiKeyboardDatabaseMappingOpaque"));
}
}
CleanupStack::PopAndDestroy(); //implResult
for(TInt i=0;i<result.Count();i++)
{
dataFactory = CPtiKeyboardDatabaseFactory::CreateImplementationL(TUid::Uid(result[i].iUid));
if (!dataFactory)
{
errStatus = KErrGeneral;
break;
}
CleanupStack::PushL(dataFactory);
//for future use
dataFactory->Reserved_1();
dataFactory->Reserved_2();
TBuf<200> data(_L("CptiEngTestDomApi : CreateImplementationL returned a valide pointer to CPtiKeyboardDatabaseFactory for uid "));
data.AppendNum(result[i].iUid);
iLog->Log(data);
RArray<TInt> langList;
CleanupClosePushL(langList);
dataFactory->ListLanguagesL(langList);
TBool langFound = EFalse;
for(TInt j=0;j<langList.Count();j++)
{
CPtiKeyboardDatabase* keyboardDatabase = NULL;
keyboardDatabase = static_cast<CPtiKeyboardDatabase*>(dataFactory->KeyMapDataForLanguageL(langList[j]));
if (!keyboardDatabase)
{
delete dataFactory;
errStatus = KErrGeneral;
break;
}
keyboardDatabase->Reserved_1();
keyboardDatabase->Reserved_2();
if (keyboardDatabase->LanguageCode() == langList[j])
{
langFound = ETrue;
}
if(keyboardDatabase->NativeId() <= 0)
{
errStatus = KErrGeneral;
}
// Not trying to interpreat KbdData as it would not be understable
keyboardDatabase->KdbData(0, NULL);
delete keyboardDatabase;
keyboardDatabase = NULL;
}
CleanupStack::PopAndDestroy(); //langList
if (!langFound)
{
errStatus = KErrGeneral;
}
CleanupStack::PopAndDestroy(); //dataFactory
}
CleanupStack::PopAndDestroy(); //result
REComSession::FinalClose();
iLog->Log(_L(" "));
__UHEAP_MARKEND;
return errStatus;
}
// This function return CKeyMapData for english language
MPtiKeyMapData * CptiEngTestDomApi::GetKeyMapDataL()
{
RArray<TInt> dataImpl;
CPtiKeyMapDataFactory::ListImplementationsL(dataImpl);
TUid uid = TUid::Uid(dataImpl[0]);
CPtiKeyMapDataFactory * keymapDatafactory = CPtiKeyMapDataFactory::CreateImplementationL(uid);
CleanupStack::PushL(keymapDatafactory);
dataImpl.Close();
MPtiKeyMapData * keyMapData =NULL;
keyMapData = keymapDatafactory->KeyMapDataForLanguageL(01); //English
if(NULL == keyMapData)
User::Leave(KErrGeneral); //This leave fails all the testcases that are calling this function
CleanupStack::PopAndDestroy(keymapDatafactory); //keymapDatafactory
return keyMapData;
}
// ========================== OTHER EXPORTED FUNCTIONS =========================
// None
// [End of File] - Do not remove
|
c914a53f1b4563f4d1d5db3588bbd820814a7301 | 92083f6a9e75aa943a491cd72d01c42762c351a6 | /src/main.cpp | bce7fb89f468d40f6130a06c1ea7d430e03297bc | [] | no_license | vondraussen/rfm2usb | 4ae34cd99d818bf3e6b35934facbaadb3876bbe2 | 235a814f2bad383021ef8a95d57d7b95fbebb706 | refs/heads/master | 2023-08-17T20:35:24.756155 | 2021-09-11T11:52:30 | 2021-09-11T11:52:30 | 340,103,905 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,030 | cpp | main.cpp | #include <Arduino.h>
#include <ArduinoJson.h>
#include <RFM69.h>
#include <SPI.h>
#include <pb_common.h>
#include <pb_decode.h>
#include <pb_encode.h>
#include <stdio.h>
#include "messages.pb.h"
bool decodeStateMsgSensorData(pb_istream_t* stream,
const pb_field_t* field,
void** arg);
bool encodeStateMsgSensorData(pb_ostream_t* stream,
const pb_field_t* field,
void* const* arg);
#define NODEID 1
#define NETWORKID 100
#define GATEWAYID 1
#define SENSORS_COUNT 1
#define FREQUENCY RF69_868MHZ
#define ENCRYPTKEY \
"sampleEncryptKey" // has to be same 16 characters/bytes on all nodes, not
// more not less!
#define RFM69_IRQ PC_7
#define RFM69_NSS PB_6
#define RFM69_IS_RFMHW false
// SPIClass spi();
RFM69 radio(RFM69_NSS, RFM69_IRQ, RFM69_IS_RFMHW);
void setup() {
radio.initialize(FREQUENCY, NODEID, NETWORKID);
SerialUSB.begin();
}
#if (NODEID == GATEWAYID)
void loop() {
State state_msg = State_init_zero;
state_msg.has_node = true;
state_msg.node = Node_init_zero;
Sensor sensorData[1] = {0};
state_msg.sensor.funcs.decode = &decodeStateMsgSensorData;
state_msg.sensor.arg = &sensorData;
// receive messages
if (radio.receiveDone()) {
if (radio.ACKRequested())
radio.sendACK();
// deserialize protobuf
pb_istream_t stream = pb_istream_from_buffer(radio.DATA, radio.DATALEN);
pb_decode_ex(&stream, &State_msg, &state_msg, PB_ENCODE_DELIMITED);
// Json Stuff
StaticJsonDocument<200> doc;
doc["id"] = state_msg.node.id;
doc["battery"] = state_msg.node.battery_mv;
doc["humidity"] = sensorData[0].humidity;
doc["temperature"] = sensorData[0].temperature;
doc["rssi"] = radio.readRSSI();
doc["radio_temp"] = radio.readTemperature();
serializeJson(doc, SerialUSB);
SerialUSB.write("\n", 1);
}
}
#else
void loop() {
uint8_t buffer[64];
size_t message_length;
bool status;
State state_msg = State_init_zero;
state_msg.has_node = true;
state_msg.node = Node_init_zero;
Sensor sensorData[SENSORS_COUNT] = {0};
state_msg.sensor.funcs.encode = &encodeStateMsgSensorData;
state_msg.sensor.arg = &sensorData;
// Create a stream that will write to our buffer.
pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
state_msg.node.battery_mv = 0; // adc_read_vcc();
sensorData[0].humidity = 0;
sensorData[0].temperature = 0;
// sensorData[0].humidity = si7020_measure_humi();
// sensorData[0].temperature = si7020_get_prev_temp();
state_msg.node.id = NODEID;
// Now we are ready to encode the message!
status = pb_encode_ex(&stream, &State_msg, &state_msg, PB_ENCODE_DELIMITED);
message_length = stream.bytes_written;
// Then just check for any errors..
if (!status) {
// printf("Encoding failed: %s\n", PB_GET_ERROR(&stream));
}
radio.send(GATEWAYID, (const void*)(buffer), message_length, false);
radio.sleep();
// hemnode_sleep_s(POWER_DOWN_S);
}
#endif
bool decodeStateMsgSensorData(pb_istream_t* stream,
const pb_field_t* field,
void** arg) {
Sensor* sensors = (Sensor*)*arg;
for (uint8_t i = 0; i < 1; i++) {
pb_decode(stream, Sensor_fields, sensors);
return false;
}
return true;
}
bool encodeStateMsgSensorData(pb_ostream_t* stream,
const pb_field_t* field,
void* const* arg) {
Sensor* sensors = (Sensor*)*arg;
for (uint8_t i = 0; i < SENSORS_COUNT; i++) {
if (!pb_encode_tag_for_field(stream, field))
return false;
Sensor sensorData = Sensor_init_zero;
sensorData.id = (sensors + i)->id;
sensorData.temperature = (sensors + i)->temperature;
sensorData.humidity = (sensors + i)->humidity;
sensorData.light = (sensors + i)->light;
if (!pb_encode_submessage(stream, &Sensor_msg, &sensorData))
return false;
}
return true;
} |
3c73ba001fd31dcd308f3357c82d57bf81af01a3 | 6728f511ffb966da8d9c7e27c752aa318e66da54 | /test/functional/steps/TorusSteps.cpp | e90fb33a14fb3a158cd51603d05a07bd6b3a46b2 | [] | no_license | tkadauke/raytracer | 32bf28f6a3368dc6c75a950cc929a81157b6c06d | 013cf2817c925bbce763d277b8db7ebd428ae8df | refs/heads/master | 2023-02-07T05:00:40.258183 | 2023-01-28T09:54:58 | 2023-01-28T09:54:58 | 6,061,333 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,226 | cpp | TorusSteps.cpp | #include "test/functional/support/RaytracerFeatureTest.h"
#include "test/functional/support/GivenWhenThen.h"
#include "test/helpers/ShapeRecognition.h"
#include "raytracer/primitives/Torus.h"
#include "raytracer/primitives/Instance.h"
#include "core/math/Matrix.h"
using namespace testing;
using namespace raytracer;
GIVEN(RaytracerFeatureTest, "a centered torus") {
auto torus = std::make_shared<Torus>(1, 0.5);
torus->setMaterial(test->redDiffuse());
test->add(torus);
}
GIVEN(RaytracerFeatureTest, "a 90 degree rotated torus") {
auto torus = std::make_shared<Torus>(1, 0.5);
auto instance = std::make_shared<Instance>(torus);
instance->setMatrix(Matrix3d::rotateX(90_degrees));
instance->setMaterial(test->redDiffuse());
test->add(instance);
}
THEN(RaytracerFeatureTest, "i should see the torus") {
ShapeRecognition rec;
ASSERT_TRUE(rec.recognizeCircle(test->buffer()));
}
THEN(RaytracerFeatureTest, "i should see the torus with a hole in the middle") {
ASSERT_TRUE(test->objectVisible());
ASSERT_EQ(Colord::white().rgb(), test->colorAt(100, 75));
}
THEN(RaytracerFeatureTest, "i should not see the torus") {
ShapeRecognition rec;
ASSERT_FALSE(rec.recognizeCircle(test->buffer()));
}
|
063991a6b38c295a39d3467d26bb63dc6c2170f9 | 4972197e6b613a1c0a031a29727ca89a4188d16b | /test/rwlock_unittest.cpp | 804f026a077864bd1e5a8b442560a3d86346422a | [] | no_license | enterpriseih/cyprestore | 1947eaa639173d2c1f69b104c5d53bfc823d0e09 | d93790494b8794441a979569c8a1fcdf30db5ea9 | refs/heads/master | 2023-08-19T00:47:35.191413 | 2021-06-16T07:38:42 | 2021-06-16T07:38:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,184 | cpp | rwlock_unittest.cpp | #include "common/rwlock.h"
#include <pthread.h>
#include "gtest/gtest.h"
namespace cyprestore {
namespace common {
namespace {
struct SharedObject {
SharedObject() : count(0) {}
uint64_t Get() {
ReadLock rlock(lock);
return count;
}
void Add() {
WriteLock wlock(lock);
++count;
}
uint64_t count;
RWLock lock;
};
void *read_func(void *arg) {
SharedObject *obj = static_cast<SharedObject *>(arg);
uint32_t loop_counts = 100000;
while (loop_counts > 0) {
obj->Get();
--loop_counts;
}
return nullptr;
}
void *write_func(void *arg) {
SharedObject *obj = static_cast<SharedObject *>(arg);
uint32_t loop_counts = 100000;
while (loop_counts > 0) {
obj->Add();
--loop_counts;
}
return nullptr;
}
TEST(RWLockTest, TestReadLock) {
const int kNumThreads = 5;
std::vector<pthread_t> tids(kNumThreads);
SharedObject obj;
for (size_t i = 0; i < tids.size(); ++i) {
int ret = pthread_create(&tids[i], nullptr, read_func, &obj);
ASSERT_EQ(ret, 0);
}
for (size_t i = 0; i < tids.size(); ++i) {
pthread_join(tids[i], nullptr);
}
}
TEST(RWLockTest, TestWriteLock) {
const int kNumThreads = 5;
std::vector<pthread_t> tids(kNumThreads);
SharedObject obj;
for (size_t i = 0; i < tids.size(); ++i) {
int ret = pthread_create(&tids[i], nullptr, write_func, &obj);
ASSERT_EQ(ret, 0);
}
for (size_t i = 0; i < tids.size(); ++i) {
pthread_join(tids[i], nullptr);
}
}
TEST(RWLockTest, TestReadWriteLock) {
const int kNumThreads = 5;
std::vector<pthread_t> tids(kNumThreads);
SharedObject obj;
for (size_t i = 0; i < tids.size(); ++i) {
int ret = 0;
if (i % 2 == 0) {
ret = pthread_create(&tids[i], nullptr, write_func, &obj);
} else {
ret = pthread_create(&tids[i], nullptr, read_func, &obj);
}
ASSERT_EQ(ret, 0);
}
for (size_t i = 0; i < tids.size(); ++i) {
pthread_join(tids[i], nullptr);
}
}
} // namespace
} // namespace common
} // namespace cyprestore
|
9d8530697589ef70087ea31610f84f57974c1a22 | 60ccc97366c43b0f83275c2c7aabd569939f8a43 | /lcpfw/app/main/profiles/main_profile.cc | fb7ea4407454a2a77d8bf10101f5d3860c82322e | [] | no_license | VestasWey/mysite | d89c886c333e5aae31a04584e592bd108ead8dd3 | 41ea707007b688a3ef27eec55332500e369a191f | refs/heads/master | 2022-12-09T10:02:19.268154 | 2022-10-03T03:14:16 | 2022-10-03T03:14:16 | 118,091,757 | 1 | 1 | null | 2022-11-26T14:29:04 | 2018-01-19T07:22:23 | C++ | UTF-8 | C++ | false | false | 1,123 | cc | main_profile.cc | #include "main_profile.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/files/file_path.h"
#include "base/strings/string_util.h"
#include "components/prefs/json_pref_store.h"
#include "components/prefs/pref_service_factory.h"
#include "components/prefs/pref_value_store.h"
#include "common/app_constants.h"
#include "main/profiles/prefs_register.h"
std::unique_ptr<Profile> MainProfile::CreateGlobalProfile(const base::FilePath& path,
Delegate* delegate,
scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner)
{
return Profile::CreateProfile(
path.Append(lcpfw::kPreferencesFilename),
delegate,
lcpfw::RegisterGlobalProfilePrefs,
sequenced_task_runner);
}
std::unique_ptr<Profile> MainProfile::CreateProfile(const base::FilePath& path,
Delegate* delegate,
scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner)
{
return Profile::CreateProfile(
path.Append(lcpfw::kPreferencesFilename),
delegate,
lcpfw::RegisterUserProfilePrefs,
sequenced_task_runner);
}
|
7335d7547ba2eb163bb603d411095c114d8b2fd5 | 21591106b3bc40b602b7f1e519d6d73127f1ce5a | /warrior.h | c38305382709131db5092286442314b3bec5c7b0 | [] | no_license | cadovnikxyan/learnPatterns | 1815622228f5897e1637ad69449644f5245f5ac3 | 46ae26b02022ca4cce6db95625e47f32a6e38be1 | refs/heads/master | 2021-01-20T14:53:34.648697 | 2017-04-24T07:46:19 | 2017-04-24T07:46:19 | 82,782,686 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 594 | h | warrior.h | #ifndef WARRIOR_H
#define WARRIOR_H
#include <map>
#include "logui.h"
#include "composite.h"
enum Warrior_ID {
Infantryman_ID,
Archer_ID,
Horseman_ID,
Swordman_ID
};
class Warrior;
typedef std::map<Warrior_ID, Warrior*> Registry;
Registry& getRegistry();
class Dimmy{};
class Warrior
{
public:
virtual Warrior* clone()= 0;
virtual void info() =0;
virtual ~Warrior();
static Warrior* createWarrior(Warrior_ID id);
protected:
static void addPrototype (Warrior_ID id, Warrior* proto);
static void removePrototype(Warrior_ID id);
};
#endif // WARRIOR_H
|
64ea06173971a439eaaba07d1ced8b9499cdc17e | 7c3745d03f9d8f115a4ff4634f8a618818eac67d | /Hackerrank/Algorithms/Easy/staircase.cpp | 13edd2b56c50dff513d8e7169e3cbfb7bb1e8c91 | [] | no_license | rahulmalhotra/Programming-Vidya | 822f5c1b8c9e123ab298ff39c1f094bd52ae96f6 | 4148fd0a9f810bd3d7dfd64430f4028f71d2cabe | refs/heads/master | 2023-03-10T20:52:15.320174 | 2021-03-01T11:23:13 | 2021-03-01T11:23:13 | 268,011,795 | 2 | 2 | null | 2020-10-08T09:37:57 | 2020-05-30T04:54:43 | C++ | UTF-8 | C++ | false | false | 871 | cpp | staircase.cpp | /*
* Author:- Rahul Malhotra
* Source:- Programming Vidya
* Description:- Solution for HackerRank Staircase problem
* Problem Link:- https://www.hackerrank.com/challenges/staircase/problem
* Website:- www.programmingvidya.com
*/
#include <bits/stdc++.h>
using namespace std;
// Complete the staircase function below.
void staircase(int n) {
// * Printing n rows
for(int i=0; i<n; i++) {
// * Printing n-i-1 spaces for the current row
for(int j=n-1; j>i; j--) {
cout<<" ";
}
// * Printing i+1 # for the current row
for(int j=i; j>=0; j--) {
cout<<"#";
}
// * Adding a new line at the end of the current row
cout<<endl;
}
}
int main()
{
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
staircase(n);
return 0;
}
|
2605453f4453c7073bd4f985f03bcc6cbbd81bb6 | 49cac1a03b729ea70c9e35df29dec8d16c4219a0 | /longest_palindromic_subsequence/main.cpp | 592705647ef1bbce22fc6b6c0b969b6988b04061 | [] | no_license | tonickkozlov/algorithms | 22c8a6968f6c6275ac52601cbdfcbf28f46a8355 | cd2d1cfc2d7f65ec514d83aa85e22689cb20eb3a | refs/heads/master | 2021-09-07T13:17:57.736356 | 2018-02-23T11:37:57 | 2018-02-23T11:37:57 | 108,146,312 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,231 | cpp | main.cpp | // Find the length of the longest palindromic subsequence in a string
#include <vector>
#include <string>
#include <iostream>
\
#define CATCH_CONFIG_MAIN
#include "../catch.hpp"
using namespace std;
void print(const vector<vector<int>> &q) {
for (const auto &row: q) {
for (const auto &el: row) {
cout << el << " ";
}
cout << endl;
}
}
string longestPalindromicSubsequence(string s) {
vector<vector<int>> q(s.size(), vector<int>(s.size(), 0));
int maxLength = 1;
for (int i = 0; i < s.size(); i++) {
q[i][i] = 1;
}
int start = 0;
for (int i = 0; i < s.size()-1; i++) {
if (s[i] == s[i+1]) {
start = i;
maxLength = 2;
q[i][i+1] = 1;
}
}
for (int k = 3; k <= s.size(); k++) {
for (int i = 0; i < s.size()-k+1; i++) {
int j = i + k - 1;
if (q[i+1][j-1] == 1 && s[i] == s[j]) {
q[i][j] = 1;
if (k > maxLength) {
maxLength = k;
start = i;
}
}
}
}
print(q);
return s.substr(start, maxLength);
}
TEST_CASE( "Edit distance" ) {
REQUIRE(longestPalindromicSubsequence("forgeeksskeegfor") == "geeksskeeg");
REQUIRE(longestPalindromicSubsequence("forgeeksbskeegfor") == "geeksbskeeg");
}
|
389fbfd5d5789d2703fa383311e390ff87d0244c | 23da16219262910cb6473ab4581b0f1df2be4e67 | /source/domini/model/Restaurant.h | 7dc4c2dae411adc7fcd969489bffa9bbe3dd0081 | [] | no_license | MrManwe/IES-CadenaDeRestaurants | be2dea5f46f70c46649f0976d7e470fbfaa96ae7 | 83436bddb82156c65821247d37515bf1a169d7f0 | refs/heads/master | 2022-07-22T22:20:22.830412 | 2020-05-10T16:05:13 | 2020-05-10T16:05:13 | 262,822,966 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 844 | h | Restaurant.h | #pragma once
#include <string>
#include <set>
#include "domini/Defs.h"
namespace domini
{
namespace model
{
class Producte;
class Ingredient;
class PlatNormal;
class Postre;
class Beguda;
class Restaurant
{
public:
Restaurant(std::string i_adreca);
std::string ObteAdreca() const;
void SetAdreca(std::string i_adreca);
std::set<Producte*> ObteProductes();
void AfegeixProducte(Producte* i_producte);
std::set<Ingredient*> ObteIngredients();
void AfegeixIngredient(Ingredient* i_ingredient);
std::set<DadesMenu> LlistaMenusVegetarians();
void CrearMenu(std::string i_nomMenu, PlatNormal* i_platNormal, Postre* i_postre, Beguda* i_beguda, bool i_infantil, float i_preu);
private:
std::string m_adreca;
std::set<Producte*> m_productes;
std::set<Ingredient*> m_ingredients;
};
}
} |
ce653fa6bc49c896bac2669c0b043c062fb8dfde | f83ef53177180ebfeb5a3e230aa29794f52ce1fc | /ACE/ACE_wrappers/TAO/TAO_IDL/be/be_visitor_module/module_ch.cpp | 85636db20ea01f8f359f918f1110e9187da44414 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-sun-iiop"
] | permissive | msrLi/portingSources | fe7528b3fd08eed4a1b41383c88ee5c09c2294ef | 57d561730ab27804a3172b33807f2bffbc9e52ae | refs/heads/master | 2021-07-08T01:22:29.604203 | 2019-07-10T13:07:06 | 2019-07-10T13:07:06 | 196,183,165 | 2 | 1 | Apache-2.0 | 2020-10-13T14:30:53 | 2019-07-10T10:16:46 | null | UTF-8 | C++ | false | false | 2,120 | cpp | module_ch.cpp |
//=============================================================================
/**
* @file module_ch.cpp
*
* Visitor generating code for Module in the client header
*
* @author Aniruddha Gokhale
*/
//=============================================================================
#include "module.h"
be_visitor_module_ch::be_visitor_module_ch (be_visitor_context *ctx)
: be_visitor_module (ctx)
{
}
be_visitor_module_ch::~be_visitor_module_ch (void)
{
}
int
be_visitor_module_ch::visit_module (be_module *node)
{
if (node->cli_hdr_gen () || node->imported ())
{
return 0;
}
TAO_OutStream *os = this->ctx_->stream ();
TAO_OutStream *aos = 0;
*os << be_nl_2 << "// TAO_IDL - Generated from" << be_nl
<< "// " << __FILE__ << ":" << __LINE__ << be_nl_2;
*os << "namespace " << node->local_name () << be_nl
<< "{" << be_idt;
if (be_global->gen_anyop_files ())
{
aos = tao_cg->anyop_header ();
*aos << be_nl_2 << "// TAO_IDL - Generated from" << be_nl
<< "// " << __FILE__ << ":" << __LINE__ << be_nl_2;
*aos << "namespace " << node->local_name () << be_nl
<< "{" << be_idt;
}
// Generate code for the module definition by traversing thru the
// elements of its scope. We depend on the front-end to have made sure
// that only legal syntactic elements appear in our scope.
if (this->visit_scope (node) == -1)
{
ACE_ERROR_RETURN ((LM_ERROR,
"(%N:%l) be_visitor_module_ch::"
"visit_module - "
"codegen for scope failed\n"),
-1);
}
*os << be_uidt_nl << be_nl << "// TAO_IDL - Generated from" << be_nl
<< "// " << __FILE__ << ":" << __LINE__ << be_nl;
*os << be_nl
<< "} // module " << node->name ();
if (be_global->gen_anyop_files ())
{
*aos << be_uidt_nl << be_nl << "// TAO_IDL - Generated from" << be_nl
<< "// " << __FILE__ << ":" << __LINE__ << be_nl;
*aos << be_nl
<< "} // module " << node->name () << be_nl;
}
return 0;
}
|
1ed3bd4c87f69d16a14ed7e398e5017afef82619 | be312f35ef33d8e235e93f6e0612a3c59cc52ea3 | /KickstartB/peaks.cpp | aca8df15152a73769cc9487ba35e6455a89afa14 | [] | no_license | yozaam/CompetitiveProgramming | d98467d513a8db7ad2ddc8a4b7065aae585220a2 | e115e3517ea045481f5cd8cae6b7cfe217143ab6 | refs/heads/master | 2023-01-03T04:16:34.411478 | 2020-10-24T13:16:33 | 2020-10-24T13:16:33 | 291,016,437 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,069 | cpp | peaks.cpp | #include <iostream>
#include <vector>
using namespace std;
int main() {
// ios_base::sync_with_stdio(false);
// cin.tie(NULL);
int T;
cin>>T;
int N;
vector<int> h;
int ans;
for( int i = 1 ; i <= T ; i++){
// cout<<"\ni is"<<i;
cin>>N;
// cout<<"\n N is "<<N;
h.resize(0);
while(N>0){
// cout<<"y";
int temp;
cin>>temp;
// cout<<"ok ok ";
h.push_back(temp);
N--;
}
//now3
// in h
//when it goes down
//if it goes up next it is a peak
ans =0;
// cout<<"h.size()-1"<<h.size()-1;
for(int j = 1 ; j < h.size()-1 ; j++){
// cout<<"in loop : "<<h[j]<<" \n";
if(h[j]>h[j-1]){
// cout<<" go up \n";
if(h[j] > h[j+1]){
// cout<<"going down; \n";
ans++;
}
}
}
cout<<"Case #"<<i<<": "<<ans<<"\n";
}
return 0;
} |
a2d580554afbb0c14bd65789a48ab951e8ddef75 | 5d4511ef1daa16e566a5e04ee6b13b366ed8bde0 | /xxutils/utils.h | 0692028f1794c4b72feba893d131994dc823326c | [
"MIT"
] | permissive | cabralfilho/card-proxy | 2dd8057c5b197019be0f5a655767150cfa12ddb0 | 1bd8464c91ba5bf18571c691194501f0f5874dfc | refs/heads/master | 2021-06-18T13:09:54.461402 | 2017-06-29T15:00:51 | 2017-06-29T15:00:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,376 | h | utils.h | // -*- Mode: C++; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
#ifndef CARD_PROXY__UTILS_H
#define CARD_PROXY__UTILS_H
#include <string>
#include <stdexcept>
class RunTimeError: public std::runtime_error
{
public:
RunTimeError(const std::string &msg);
};
enum StringHexCaseMode { HEX_UPPERCASE=0, HEX_LOWERCASE=1, HEX_NOSPACES=2 };
char int_to_hexchar(int digit, int mode=0);
int hexchar_to_int(char symbol);
std::string string_to_hexstring(const std::string &input, int mode=0);
std::string string_from_hexstring(const std::string &hex_input, int mode=0);
std::string encode_base64(const std::string &message);
std::string decode_base64(const std::string &b64message);
void generate_random_bytes(void *buf, size_t len);
std::string generate_random_bytes(size_t length);
std::string generate_random_number(size_t length);
std::string generate_random_string(size_t length);
std::string generate_random_hex_string(size_t length);
const std::string read_file(const std::string &file_name);
const std::string get_process_name();
const std::string fmt_string_escape(const std::string &s);
const std::string replace_str(const std::string &str,
const std::string &search,
const std::string &replace);
const std::string get_utc_iso_ts();
#endif // CARD_PROXY__UTILS_H
// vim:ts=4:sts=4:sw=4:et:
|
7a8c850ccae338eb4b9f5571a139a04b37f1002f | d8a29bf1d4be5c67271b0bb18126c5d51a78798e | /SNMPServer/BERDecoder.h | 557dc90b1247d703fbc4000183de65a1c3e70e15 | [] | no_license | marcingrzelak/MPASK-Lab | 5cba6cc2cb2fa4dd15b5e87618cb641ab6073144 | ae5ea88194bd0fe7ca41a4cc7883751a6068f127 | refs/heads/master | 2020-04-02T07:42:13.728213 | 2019-02-21T12:51:15 | 2019-02-21T12:51:15 | 154,210,485 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 813 | h | BERDecoder.h | #pragma once
#include "Identifier.h"
#include "Length.h"
#include "Value.h"
#include "TreeStructure.h"
#include "DataStructures.h"
#include "CheckValue.h"
class BERDecoder
{
public:
BERDecoder();
~BERDecoder();
Identifier identifier;
Length length;
Value value;
string classValue, classConstructedValue, complexityValue, dataValue;
unsigned int tagValue, tagConstructedValue;
unsigned long long lengthValue;
bool undefinedFlag = false;
TreeNodeBER *currentParent = nullptr;
vector<uint8_t> octets;
vector<uint8_t> values;
void getVectorOfBytes(string pValue);
void getIdentifier(int &pIndex);
void getLength(int &pIndex);
void getValue(int &pIndex);
void getValueINT();
void decode(string & pValue, int pIndex, TreeBER & pTree, TreeNodeBER *pParentNode);
}; |
45c6ed391966b34422a55bda0b278fb770536b7a | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/httpd/gumtree/httpd_old_log_5628.cpp | 4d5ade08cfb544d7fabc3eaf5c91cb751f1da6d5 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 150 | cpp | httpd_old_log_5628.cpp | ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP,
apr_get_os_error(), NULL,
"OpenService failed"); |
b635ec6f108cae216a39f4595aea3aebef8cea01 | 7d258494ac0747b64f8dd120c5eaf4034256d69a | /acmicpc code/10870.cpp | 1615ac235b689e3e25234ca11f70c831edffe6fc | [] | no_license | JeongJinLee/algorithm | 1eadff53d01b4254740e73e6d0534ddf3781959e | a5b2e377687745d6325a78f1474dda694f4bffb6 | refs/heads/master | 2020-01-23T21:43:30.213920 | 2017-05-16T10:52:00 | 2017-05-16T10:52:00 | 74,685,216 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 712 | cpp | 10870.cpp | #include <stdio.h>
unsigned long long FIBONACCI2(unsigned long long n);
unsigned long long FIB(unsigned long long n, unsigned long long acc1, unsigned long long acc2);
int main(void)
{
unsigned long long n;
unsigned long long i;
unsigned long long value;
scanf("%llu", &n);
for (i = 0; i <= n; i++)
{
value = FIBONACCI2(i);
if(i==n)
printf("%llu\n", value);
}
return 0;
}
unsigned long long FIBONACCI2(unsigned long long n)
{
unsigned long long F0 = 0, F1 = 1;
return FIB(n, F0, F1);
}
unsigned long long FIB(unsigned long long n, unsigned long long acc1, unsigned long long acc2)
{
if (n == 0)
return acc1;
return FIB(n - 1, acc2, acc1 + acc2);
} |
21d95df6e50709f6ce4dc198953ab5c09e0ef70d | 8ab2066ab9bbd7ce0b22555dbb22f5c0937dc0f2 | /wzr20_2i/graphics.cpp | 149d3bd31c1eb78aa248f9a9e4e56371d9101052 | [] | no_license | amadeusz-chmielowski/WZR | a4e1020835ceb07d5f2d4b2feab6203e36051a4b | b5c29ba301bdc56f5867cad0e530c37618d7dc05 | refs/heads/master | 2022-09-22T23:40:52.310946 | 2020-06-02T21:24:46 | 2020-06-02T21:24:46 | 257,298,213 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 22,414 | cpp | graphics.cpp | /************************************************************
Grafika OpenGL
*************************************************************/
#define __GRAPHICS_CPP_
#include <windows.h>
#include <time.h>
#include <gl\gl.h>
#include <gl\glu.h>
#include <iterator>
#include <map>
using namespace std;
#include "graphics.h"
#include "objects.h"
ViewParams view_parameters;
extern MovableObject *my_vehicle; // obiekt przypisany do tej aplikacji
extern map<int, MovableObject*> network_vehicles;
extern CRITICAL_SECTION m_cs;
extern Terrain planet_terrain;
extern long time_day;
int g_GLPixelIndex = 0;
HGLRC g_hGLContext = NULL;
unsigned int font_base;
extern long time_start; // czas od uruchomienia potrzebny np. do obliczenia położenia słońca
extern HWND window_handle;
extern void CreateDisplayLists(); // definiujemy listy tworzące labirynt
extern void DrawGlobalCoordAxes();
int GraphicsInitialisation(HDC g_context)
{
if (SetWindowPixelFormat(g_context) == FALSE)
return FALSE;
if (CreateViewGLContext(g_context) == FALSE)
return 0;
BuildFont(g_context);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
CreateDisplayLists(); // definiujemy listy tworzące różne elementy sceny
planet_terrain.DrawInitialisation();
// początkowe ustawienia widoku:
// Parametry widoku:
view_parameters.cam_direct_1 = Vector3(10, -3, -14); // kierunek patrzenia
view_parameters.cam_pos_1 = Vector3(-35, 6, 10); // położenie kamery
view_parameters.cam_vertical_1 = Vector3(0, 1, 0); // kierunek pionu kamery
view_parameters.cam_direct_2 = Vector3(0, -1, 0.02); // to samo dla widoku z góry
view_parameters.cam_pos_2 = Vector3(0, 100, 0);
view_parameters.cam_vertical_2 = Vector3(0, 0, -1);
view_parameters.cam_direct = view_parameters.cam_direct_1;
view_parameters.cam_pos = view_parameters.cam_pos_1;
view_parameters.cam_vertical = view_parameters.cam_vertical_1;
view_parameters.tracking = 0; // tryb śledzenia obiektu przez kamerę
view_parameters.top_view = 0; // tryb widoku z góry
view_parameters.cam_distance = 21.0; // cam_distance widoku z kamery
view_parameters.cam_angle = 0; // obrót kamery góra-dół
view_parameters.cam_distance_1 = view_parameters.cam_distance;
view_parameters.cam_angle_1 = view_parameters.cam_angle;
view_parameters.cam_distance_2 = view_parameters.cam_distance;
view_parameters.cam_angle_2 = view_parameters.cam_angle;
view_parameters.cam_distance_3 = view_parameters.cam_distance;
view_parameters.cam_angle_3 = view_parameters.cam_angle;
view_parameters.zoom = 1.0;
}
void DrawScene()
{
GLfloat OwnVehicleColor[] = { 0.4f, 0.0f, 0.8f, 0.5f };
GLfloat NetworkVehiclesColor[] = { 0.6f, 0.6f, 0.25f, 0.7f };
//GLfloat RedSurface[] = { 0.8f, 0.2f, 0.1f, 0.5f };
GLfloat YellowSurface[] = { 0.75f, 0.75f, 0.0f, 1.0f };
GLfloat LightAmbient[] = { 0.1f, 0.1f, 0.1f, 0.1f };
GLfloat LightDiffuse[] = { 0.4f, 0.7f, 0.7f, 0.7f };
GLfloat LightPosition[] = { 5.0f, 5.0f, 5.0f, 0.0f };
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glLightfv(GL_LIGHT0, GL_AMBIENT, LightAmbient); //1 składowa: światło otaczające (bezkierunkowe)
glLightfv(GL_LIGHT0, GL_DIFFUSE, LightDiffuse); //2 składowa: światło rozproszone (kierunkowe)
glLightfv(GL_LIGHT0, GL_POSITION, LightPosition);
glEnable(GL_LIGHT0);
glPushMatrix();
//glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, BlueSurface);
Vector3 direction_k, vertical_k, position_k;
if (view_parameters.tracking)
{
direction_k = my_vehicle->state.qOrient.rotate_vector(Vector3(1, 0, 0));
vertical_k = my_vehicle->state.qOrient.rotate_vector(Vector3(0, 1, 0));
Vector3 v_cam_right = my_vehicle->state.qOrient.rotate_vector(Vector3(0, 0, 1));
vertical_k = vertical_k.rotation(view_parameters.cam_angle, v_cam_right.x, v_cam_right.y, v_cam_right.z);
direction_k = direction_k.rotation(view_parameters.cam_angle, v_cam_right.x, v_cam_right.y, v_cam_right.z);
position_k = my_vehicle->state.vPos - direction_k*my_vehicle->length * 0 +
vertical_k.znorm()*my_vehicle->height * 5;
view_parameters.cam_vertical = vertical_k;
view_parameters.cam_direct = direction_k;
view_parameters.cam_pos = position_k;
}
else
{
vertical_k = view_parameters.cam_vertical;
direction_k = view_parameters.cam_direct;
position_k = view_parameters.cam_pos;
Vector3 v_cam_right = (direction_k*vertical_k).znorm();
vertical_k = vertical_k.rotation(view_parameters.cam_angle / 20, v_cam_right.x, v_cam_right.y, v_cam_right.z);
direction_k = direction_k.rotation(view_parameters.cam_angle / 20, v_cam_right.x, v_cam_right.y, v_cam_right.z);
}
// Ustawianie widoku sceny
gluLookAt(position_k.x - view_parameters.cam_distance*direction_k.x,
position_k.y - view_parameters.cam_distance*direction_k.y, position_k.z - view_parameters.cam_distance*direction_k.z,
position_k.x + direction_k.x, position_k.y + direction_k.y, position_k.z + direction_k.z,
vertical_k.x, vertical_k.y, vertical_k.z);
//glRasterPos2f(0.30,-0.27);
//glPrint("my_vehicle->iID = %d",my_vehicle->iID );
DrawGlobalCoordAxes();
// słońce + tło:
int R = 52000; // promień obiegu
long x = (clock() - time_start) % (time_day*CLOCKS_PER_SEC);
float angle = (float)x / (time_day*CLOCKS_PER_SEC) * 2 * 3.1415926535898;
//char lan[128];
//sprintf(lan,"angle = %f\n", angle);
//SetWindowText(window_handle, lan);
float cos_abs = fabs(cos(angle));
float cos_sq = cos_abs*cos_abs, sin_sq = sin(angle)*sin(angle);
float sin_angminpi = fabs(sin(angle/2 - 3.1416/2)); // 0 gdy słońce na antypodach, 1 w południe
float sin_angminpi_sqr = sin_angminpi*sin_angminpi;
float cos_ang_zachod = fabs(cos((angle - 1.5)*3)); // 1 w momencie wschodu lub zachodu
glClearColor(0.65*cos_abs*sin_angminpi_sqr + 0.25*sin_sq*cos_ang_zachod, 0.75*cos_abs*sin_angminpi_sqr, 4.0*cos_abs*sin_angminpi_sqr, 1.0); // ustawienie tła
GLfloat SunColor[] = { 8.0*cos_sq, 8.0 * cos_sq*cos_sq*sin_angminpi, 4.0 * cos_sq*cos_sq*sin_angminpi, 1.0f };
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, SunColor);
glPushMatrix();
glTranslatef(R*cos(angle), R*(cos(angle)*0.5 - 0.2), R*sin(angle)); // ustawienie słońca
//glTranslatef(R*cos(angle), 5000, R*sin(angle));
GLUquadricObj *Qsph = gluNewQuadric();
gluSphere(Qsph, 600.0 + 5000 * sin_sq*sin_sq, 27, 27);
gluDeleteQuadric(Qsph);
glPopMatrix();
GLfloat GroundSurface[] = { 0.7*(0.8 + 0.4*sin_angminpi), 0.5*(0.2 + 0.8*sin_angminpi), 0.1*(0.1 + 0.9*sin_angminpi), 1.0f };
//glPushMatrix();
for (int w = -1; w < 2; w++)
for (int k = -1; k < 2; k++)
{
glPushMatrix();
glTranslatef(planet_terrain.number_of_columns*planet_terrain.field_size*k, 0, planet_terrain.number_of_rows*planet_terrain.field_size*w);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, OwnVehicleColor);
glEnable(GL_BLEND);
my_vehicle->DrawObject();
// Lock the Critical section
EnterCriticalSection(&m_cs);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, NetworkVehiclesColor);
for (map<int, MovableObject*>::iterator it = network_vehicles.begin(); it != network_vehicles.end(); ++it)
it->second->DrawObject();
//for each (auto&& it in network_vehicles) it.second->DrawObject(); // od VC 2013 (C++ 11)
//Release the Critical section
LeaveCriticalSection(&m_cs);
glDisable(GL_BLEND);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, GroundSurface);
planet_terrain.Draw();
glPopMatrix();
}
glPopMatrix();
glFlush();
}
void WindowResize(int cx, int cy)
{
GLsizei width, height;
GLdouble aspect;
width = cx;
height = cy;
if (cy == 0)
aspect = (GLdouble)width;
else
aspect = (GLdouble)width / (GLdouble)height;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(35 * view_parameters.zoom, aspect, 1, 100000.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glDrawBuffer(GL_BACK);
glEnable(GL_LIGHTING);
glEnable(GL_DEPTH_TEST);
}
void EndOfGraphics()
{
if (wglGetCurrentContext() != NULL)
{
// dezaktualizacja contextu renderującego
wglMakeCurrent(NULL, NULL);
}
if (g_hGLContext != NULL)
{
wglDeleteContext(g_hGLContext);
g_hGLContext = NULL;
}
glDeleteLists(font_base, 96);
}
BOOL SetWindowPixelFormat(HDC hDC)
{
PIXELFORMATDESCRIPTOR pixelDesc;
pixelDesc.nSize = sizeof(PIXELFORMATDESCRIPTOR);
pixelDesc.nVersion = 1;
pixelDesc.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_STEREO_DONTCARE;
pixelDesc.iPixelType = PFD_TYPE_RGBA;
pixelDesc.cColorBits = 32;
pixelDesc.cRedBits = 8;
pixelDesc.cRedShift = 16;
pixelDesc.cGreenBits = 8;
pixelDesc.cGreenShift = 8;
pixelDesc.cBlueBits = 8;
pixelDesc.cBlueShift = 0;
pixelDesc.cAlphaBits = 0;
pixelDesc.cAlphaShift = 0;
pixelDesc.cAccumBits = 64;
pixelDesc.cAccumRedBits = 16;
pixelDesc.cAccumGreenBits = 16;
pixelDesc.cAccumBlueBits = 16;
pixelDesc.cAccumAlphaBits = 0;
pixelDesc.cDepthBits = 32;
pixelDesc.cStencilBits = 8;
pixelDesc.cAuxBuffers = 0;
pixelDesc.iLayerType = PFD_MAIN_PLANE;
pixelDesc.bReserved = 0;
pixelDesc.dwLayerMask = 0;
pixelDesc.dwVisibleMask = 0;
pixelDesc.dwDamageMask = 0;
g_GLPixelIndex = ChoosePixelFormat(hDC, &pixelDesc);
if (g_GLPixelIndex == 0)
{
g_GLPixelIndex = 1;
if (DescribePixelFormat(hDC, g_GLPixelIndex, sizeof(PIXELFORMATDESCRIPTOR), &pixelDesc) == 0)
{
return FALSE;
}
}
if (SetPixelFormat(hDC, g_GLPixelIndex, &pixelDesc) == FALSE)
{
return FALSE;
}
return TRUE;
}
BOOL CreateViewGLContext(HDC hDC)
{
g_hGLContext = wglCreateContext(hDC);
if (g_hGLContext == NULL)
{
return FALSE;
}
if (wglMakeCurrent(hDC, g_hGLContext) == FALSE)
{
return FALSE;
}
return TRUE;
}
GLvoid BuildFont(HDC hDC) // Build Our Bitmap Font
{
HFONT font; // Windows Font ID
HFONT oldfont; // Used For Good House Keeping
font_base = glGenLists(96); // Storage For 96 Characters
font = CreateFont(-15, // Height Of Font
0, // Width Of Font
0, // Angle Of Escapement
0, // Orientation Angle
FW_NORMAL, // Font Weight
TRUE, // Italic
FALSE, // Underline
FALSE, // Strikeout
ANSI_CHARSET, // Character Set Identifier
OUT_TT_PRECIS, // Output Precision
CLIP_DEFAULT_PRECIS, // Clipping Precision
ANTIALIASED_QUALITY, // Output Quality
FF_DONTCARE | DEFAULT_PITCH, // Family And Pitch
"Courier New"); // Font Name
oldfont = (HFONT)SelectObject(hDC, font); // Selects The Font We Want
wglUseFontBitmaps(hDC, 32, 96, font_base); // Builds 96 Characters Starting At Character 32
SelectObject(hDC, oldfont); // Selects The Font We Want
DeleteObject(font); // Delete The Font
}
// Napisy w OpenGL
GLvoid glPrint(const char *fmt, ...) // Custom GL "Print" Routine
{
char text[256]; // Holds Our String
va_list ap; // Pointer To List Of Arguments
if (fmt == NULL) // If There's No Text
return; // Do Nothing
va_start(ap, fmt); // Parses The String For Variables
vsprintf(text, fmt, ap); // And Converts Symbols To Actual Numbers
va_end(ap); // Results Are Stored In Text
glPushAttrib(GL_LIST_BIT); // Pushes The Display List Bits
glListBase(font_base - 32); // Sets The Base Character to 32
glCallLists(strlen(text), GL_UNSIGNED_BYTE, text); // Draws The Display List Text
glPopAttrib(); // Pops The Display List Bits
}
void CreateDisplayLists()
{
glNewList(Wall1, GL_COMPILE); // GL_COMPILE - lista jest kompilowana, ale nie wykonywana
glBegin(GL_QUADS); // inne opcje: GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP
// GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, GL_QUAD_STRIP, GL_POLYGON
glNormal3f(-1.0, 0.0, 0.0);
glVertex3f(-1.0, -1.0, 1.0);
glVertex3f(-1.0, 1.0, 1.0);
glVertex3f(-1.0, 1.0, -1.0);
glVertex3f(-1.0, -1.0, -1.0);
glEnd();
glEndList();
glNewList(Wall2, GL_COMPILE);
glBegin(GL_QUADS);
glNormal3f(1.0, 0.0, 0.0);
glVertex3f(1.0, -1.0, 1.0);
glVertex3f(1.0, 1.0, 1.0);
glVertex3f(1.0, 1.0, -1.0);
glVertex3f(1.0, -1.0, -1.0);
glEnd();
glEndList();
glNewList(Auto, GL_COMPILE);
glBegin(GL_QUADS);
// przod
glNormal3f(0.0, 0.0, 1.0);
glVertex3f(0, 0, 1);
glVertex3f(0, 1, 1);
glVertex3f(0.6, 1, 1);
glVertex3f(0.6, 0, 1);
glVertex3f(0.6, 0, 1);
glVertex3f(0.6, 0.5, 1);
glVertex3f(1.0, 0.5, 1);
glVertex3f(1.0, 0, 1);
// tyl
glNormal3f(0.0, 0.0, -1.0);
glVertex3f(0, 0, 0);
glVertex3f(0.6, 0, 0);
glVertex3f(0.6, 1, 0);
glVertex3f(0, 1, 0);
glVertex3f(0.6, 0, 0);
glVertex3f(1.0, 0, 0);
glVertex3f(1.0, 0.5, 0);
glVertex3f(0.6, 0.5, 0);
// gora
glNormal3f(0.0, 1.0, 0.0);
glVertex3f(0, 1, 0);
glVertex3f(0, 1, 1);
glVertex3f(0.6, 1, 1);
glVertex3f(0.6, 1, 0);
glVertex3f(0.6, 0.5, 0);
glVertex3f(0.6, 0.5, 1);
glVertex3f(1.0, 0.5, 1);
glVertex3f(1.0, 0.5, 0);
// dol
glNormal3f(0.0, -1.0, 0.0);
glVertex3f(0, 0, 0);
glVertex3f(1, 0, 0);
glVertex3f(1, 0, 1);
glVertex3f(0, 0, 1);
// prawo
glNormal3f(1.0, 0.0, 0.0);
glVertex3f(0.6, 0.5, 0);
glVertex3f(0.6, 0.5, 1);
glVertex3f(0.6, 1, 1);
glVertex3f(0.6, 1, 0);
glVertex3f(1.0, 0.0, 0);
glVertex3f(1.0, 0.0, 1);
glVertex3f(1.0, 0.5, 1);
glVertex3f(1.0, 0.5, 0);
// lewo
glNormal3f(-1.0, 0.0, 0.0);
glVertex3f(0, 0, 0);
glVertex3f(0, 1, 0);
glVertex3f(0, 1, 1);
glVertex3f(0, 0, 1);
glEnd();
glEndList();
}
void DrawGlobalCoordAxes(void)
{
glColor3f(1, 0, 0);
glBegin(GL_LINES);
glVertex3f(0, 0, 0);
glVertex3f(2, 0, 0);
glVertex3f(2, -0.25, 0.25);
glVertex3f(2, 0.25, -0.25);
glVertex3f(2, -0.25, -0.25);
glVertex3f(2, 0.25, 0.25);
glEnd();
glColor3f(0, 1, 0);
glBegin(GL_LINES);
glVertex3f(0, 0, 0);
glVertex3f(0, 2, 0);
glVertex3f(0, 2, 0);
glVertex3f(0.25, 2, 0);
glVertex3f(0, 2, 0);
glVertex3f(-0.25, 2, 0.25);
glVertex3f(0, 2, 0);
glVertex3f(-0.25, 2, -0.25);
glEnd();
glColor3f(0, 0, 1);
glBegin(GL_LINES);
glVertex3f(0, 0, 0);
glVertex3f(0, 0, 2);
glVertex3f(-0.25, -0.25, 2);
glVertex3f(0.25, 0.25, 2);
glVertex3f(-0.25, -0.25, 2);
glVertex3f(0.25, -0.25, 2);
glVertex3f(-0.25, 0.25, 2);
glVertex3f(0.25, 0.25, 2);
glEnd();
glColor3f(1, 1, 1);
}
unsigned int base;
int loadBMP(char *filename, textureImage *texture)
{
FILE *file;
unsigned short int bfType;
long int bfOffBits;
short int biPlanes;
short int biBitCount;
long int biSizeImage;
int i;
unsigned char temp;
/* make sure the file is there and open it read-only (binary) */
if ((file = fopen(filename, "rb")) == NULL)
{
printf("File not found : %s\n", filename);
return 0;
}
if (!fread(&bfType, sizeof(short int), 1, file))
{
printf("Error reading file!\n");
return 0;
}
/* check if file is a bitmap */
if (bfType != 19778)
{
printf("Not a Bitmap-File!\n");
return 0;
}
/* get the file size */
/* skip file size and reserved fields of bitmap file header */
fseek(file, 8, SEEK_CUR);
/* get the position of the actual bitmap data */
if (!fread(&bfOffBits, sizeof(long int), 1, file))
{
printf("Error reading file!\n");
return 0;
}
//printf("Data at Offset: %ld\n", bfOffBits);
/* skip size of bitmap info header */
fseek(file, 4, SEEK_CUR);
/* get the width of the bitmap */
fread(&texture->width, sizeof(int), 1, file);
//printf("Width of Bitmap: %d\n", texture->width);
/* get the height of the bitmap */
fread(&texture->height, sizeof(int), 1, file);
//printf("Height of Bitmap: %d\n", texture->height);
/* get the number of planes (must be set to 1) */
fread(&biPlanes, sizeof(short int), 1, file);
if (biPlanes != 1)
{
printf("Error: number of Planes not 1!\n");
return 0;
}
/* get the number of bits per pixel */
if (!fread(&biBitCount, sizeof(short int), 1, file))
{
printf("Error reading file!\n");
return 0;
}
texture->biCount = biBitCount;
printf("Load texture %s %ix%ix%i ", filename, texture->width, texture->height, texture->biCount);
biSizeImage = texture->width * texture->height * 3;
texture->data = (unsigned char *)(malloc(biSizeImage));
switch (texture->biCount)
{
case 24:
fseek(file, bfOffBits, SEEK_SET);
if (!fread(texture->data, biSizeImage, 1, file))
{
printf("Error loading file!\n");
return 0;
}
/* zamiana skladowych red z blue (bgr -> rgb) */
for (i = 0; i < biSizeImage; i += 3)
{
temp = texture->data[i];
texture->data[i] = texture->data[i + 2];
texture->data[i + 2] = temp;
}
printf("ok\n");
break;
case 4:
{
unsigned char *ucpPointer;
unsigned char *ucpTabRGB;
ucpPointer = (unsigned char *)(malloc(biSizeImage / 3));
ucpTabRGB = (unsigned char *)(malloc(256 * 4));
fseek(file, bfOffBits - 256 * 4, SEEK_SET);
if (!fread(ucpTabRGB, 256 * 4, 1, file))
{
printf("Error loading file!\n");
return 0;
}
printf("rgbTab ");
fseek(file, bfOffBits, SEEK_SET);
if (!fread(ucpPointer, biSizeImage / 3, 1, file))
{
printf("Error loading file!\n");
return 0;
}
printf("data ");
for (i = 0; i < biSizeImage / 3; i++)
{
texture->data[i * 3 + 2] = ucpTabRGB[ucpPointer[i] * 4];
texture->data[i * 3 + 1] = ucpTabRGB[ucpPointer[i] * 4 + 1];
texture->data[i * 3] = ucpTabRGB[ucpPointer[i] * 4 + 2];
}
free(ucpPointer);
free(ucpTabRGB);
printf("ok\n");
}
break;
case 8:
{
unsigned char *ucpPointer;
unsigned char *ucpTabRGB;
ucpPointer = (unsigned char *)(malloc(biSizeImage / 3));
ucpTabRGB = (unsigned char *)(malloc(256 * 4));
fseek(file, bfOffBits - 256 * 4, SEEK_SET);
if (!fread(ucpTabRGB, 256 * 4, 1, file))
{
printf("Error loading file!\n");
return 0;
}
printf("rgbTab ");
fseek(file, bfOffBits, SEEK_SET);
if (!fread(ucpPointer, biSizeImage / 3, 1, file))
{
printf("Error loading file!\n");
return 0;
}
printf("data ");
for (i = 0; i < biSizeImage / 3; i++)
{
texture->data[i * 3] = ucpTabRGB[ucpPointer[i] * 4 + 2];
texture->data[i * 3 + 1] = ucpTabRGB[ucpPointer[i] * 4 + 1];
texture->data[i * 3 + 2] = ucpTabRGB[ucpPointer[i] * 4];
}
free(ucpPointer);
free(ucpTabRGB);
printf("ok\n");
}
break;
default:
break;
}// end switch
return 1;
}
int loadBBMP(char *filename, textureImage *texture)
{
char full_name[50];
char full_name2[50];
textureImage *texRGB;
textureImage *texGrey;
int iTexSize;
int i, ii;
printf("loadBBMP\n");
texRGB = (textureImage *)(malloc(sizeof(textureImage)));
if (loadBMP(filename, texRGB)) // zaladowanie bitmapy
printf("Load RGB ");
else
{
printf("Error Load RGB ");
return 0;
};
sprintf(full_name, "%s", filename);
full_name[strlen(full_name) - 4] = 0;
sprintf(full_name2, "%s_b.bmp", full_name);
texGrey = (textureImage *)(malloc(sizeof(textureImage)));
printf("loadGREy %s\n", full_name2);
if (loadBMP(full_name2, texGrey)) // zaladowanie kolorow
printf("Load Grey ");
else
{
printf("Error Load Grey ");
return 0;
};
texture->width = texRGB->width;
texture->height = texRGB->height;
texture->biCount = 32;
iTexSize = texture->width*texture->height*(texture->biCount / 8);
texture->data = (unsigned char *)(malloc(iTexSize));
ii = 0;
for (i = 0; i < iTexSize; i += 4)
{
texture->data[i] = texRGB->data[ii];
texture->data[i + 1] = texRGB->data[ii + 1];
texture->data[i + 2] = texRGB->data[ii + 2];
texture->data[i + 3] = texGrey->data[ii];
ii += 3;
}
free(texRGB);
free(texGrey);
return 1;
}
unsigned int loadTextures(char *filename)
{
unsigned char status;
textureImage *texti;
unsigned int Textur;
status = 0; // false
texti = (textureImage *)(malloc(sizeof(textureImage)));
if (loadBMP(filename, texti)) // zaladowanie bitmapy do zmiennej texti
{
status = 1; // liczba tekstur
glGenTextures(1, &Textur); // generuje nazwy (numerki) tekstur
glBindTexture(GL_TEXTURE_2D, Textur); // ustawienie biezacej tekstury
gluBuild2DMipmaps(GL_TEXTURE_2D, 3, texti->width,// tworzenie mipmap dla biezacej tekstury
texti->height, GL_RGB, GL_UNSIGNED_BYTE, texti->data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
/*
glTexImage2D(GL_TEXTURE_2D, 0, 3, texti->width, texti->height, 0,
GL_RGB, GL_UNSIGNED_BYTE, texti->data);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
*/
if (texti)
{
if (texti->data)
free(texti->data);
free(texti);
/* zwonienie pamieci uzywanej podczas tworzenia tekstury */
}
return Textur;
}
return 0;
}
unsigned int loadBlendTextures(char *filename)
{
unsigned char status;
textureImage *texti;
unsigned int Textur;
status = 0; // false
texti = (textureImage *)(malloc(sizeof(textureImage)));
if (loadBBMP(filename, texti))
{
status = 1; // true
glGenTextures(1, &Textur); /* stworzenie tekstury - struktura */
glBindTexture(GL_TEXTURE_2D, Textur);
/* generowanie tekstury - wypelnienie danymi */
gluBuild2DMipmaps(GL_TEXTURE_2D, 4, texti->width,
texti->height, GL_RGBA, GL_UNSIGNED_BYTE, texti->data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
/*
glTexImage2D(GL_TEXTURE_2D, 0, 4, texti->width, texti->height, 0,
GL_RGBA, GL_UNSIGNED_BYTE, texti->data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
*/
if (texti)
{
if (texti->data)
free(texti->data);
free(texti);
/* zwonienie pamieci uzywanej podczas tworzenia tekstury */
}
return Textur;
}
return 0;
}
|
0ffbcdbd31bd3b1e9659767468a5b3cf1372b61a | 38974da4a42a73726ccf42a2f07aa922ef591186 | /image_handler/src/main.cpp | 123f8474a5e4b4fc871e92f9257f075f7ae68275 | [
"MIT"
] | permissive | LEGaTO-SmartMirror/SmartMirror-Image-Handler | 7a143e7db619036640acd8018b29fa92b25c2035 | 5b2eb1a7faa28920e07b2ea6028e0ec3b0db8b3d | refs/heads/master | 2023-01-27T11:33:11.315199 | 2020-12-10T10:18:58 | 2020-12-10T10:18:58 | 258,480,314 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 18,890 | cpp | main.cpp | #include "main.h"
// -------------------------------------------------------------------------------
// MAIN! preparing and looping through everything
int main(int argc, char * argv[]) try
{
// default preparations like signal handler
std::cout << setiosflags(ios::fixed) << setprecision(2);
signal(SIGINT, sig_handler);
// check cmd line arguments for e.g. result image variables
if(argc > 3){
IMAGE_WIDTH_RESULT = atoi(argv[1]);
IMAGE_HEIGHT_RESULT = atoi(argv[2]);
IMAGE_ROTATION_RESULT = atoi(argv[3]);
if(argc > 4){
PATH_ICON_GESTURES = argv[4];
}
to_node("STATUS", "parsing args done");
}
//std::cout << "{\"STATUS\": \"starting with config: " << IMAGE_WIDTH_RESULT << " " << IMAGE_HEIGHT_RESULT << " " << IMAGE_ROTATION_RESULT << " \"}" << std::endl;
cv::Mat black_image = cv::Mat::zeros(cv::Size(IMAGE_WIDTH_RESULT, IMAGE_HEIGHT_RESULT), CV_8UC3);
// create camera graber and initialize it
myCamera_grabber cam_grab;
cam_grab.mg_init();
// Pointer for threaded image pre prossesing like rotation and flipping...
std::thread* prepare_rgb_image_thr;
std::thread* prepare_depth_image_thr;
std::thread* prepare_center_image_thr;
// we will write with a thread to mjpeg writer, so create pointer to one
std::thread* center_writer_thr;
std::thread* stdin_thr = new std::thread(check_stdin);
// get first image for setup of the mjpeg writer. It needs a image to be started.
auto processed = cam_grab.get_cam_images();
rs2::frame color = processed.get_color_frame(); // Find the color data
cv::Mat rgb (COLOR_INPUT_HEIGHT, COLOR_INPUT_WIDTH, CV_8UC3, (uchar *) color.get_data());
pre_draw_image = rgb;
pre_draw_image.copyTo(post_draw_image);
prepare_center_image_thr = new std::thread(prepare_center_image, std::ref(pre_draw_image));
// Create mjpeg writer with a choosen port.
// TODO maybe parameterize the port ???
mjpeg_writer_ptr = new MJPEGWriter(7777);
center_writer_thr = new std::thread(write_to_mjpeg_writer,std::ref(post_draw_image));
mjpeg_writer_ptr->start(); //Starts the HTTP Server on the selected port
// Create image output devices for each image that is shared
writer_hd_image = new myImage_writer(gst_socket_path_hd_image, FRAMERATE, IMAGE_WIDTH_RESULT, IMAGE_HEIGHT_RESULT, true, 200000000);
writer_small_image = new myImage_writer(gst_socket_path_small_image, FRAMERATE, COLOR_SMALL_WIDTH, COLOR_SMALL_HEIGHT, true,100000000);
writer_image_1m = new myImage_writer(gst_socket_path_image_1m, FRAMERATE, IMAGE_WIDTH_RESULT, IMAGE_HEIGHT_RESULT, true,100000000);
//writer_depth_image = new myImage_writer(gst_socket_path_depth, FRAMERATE, IMAGE_WIDTH_RESULT, IMAGE_HEIGHT_RESULT, false);
// Some GPUMats that will be used later..
cv::cuda::GpuMat rgb_image (COLOR_INPUT_HEIGHT, COLOR_INPUT_WIDTH, CV_16U);
cv::cuda::GpuMat rgb_scaled (COLOR_SMALL_HEIGHT,COLOR_SMALL_WIDTH,CV_16U);
cv::cuda::GpuMat depth_image (COLOR_INPUT_HEIGHT, COLOR_INPUT_WIDTH, CV_8U);
// Some Mats that will be used later..
cv::Mat rgb_image_out;
cv::Mat depth_image_out;
cv::Mat rgb_back_image_out;
cv::Mat small_rgb_image_out;
// A gaussian filter used to blur the depth image a bit. this should remove artifacts and reduse noice.
Ptr<cv::cuda::Filter> gaussian = cv::cuda::createGaussianFilter(depth_image.type(),depth_image.type(), Size(31,31),0);
// And always look to the clock..
auto now = std::chrono::system_clock::now();
auto before = now;
char cwd[100];
getcwd(cwd,sizeof(cwd));
to_node("STATUS", cwd );
load_images_gestures();
to_node("STATUS","Gesture images loaded.");
string gst_string_style = "shmsrc socket-path=/dev/shm/style_transfer ! video/x-raw, format=BGR, height=" + to_string(IMAGE_HEIGHT_RESULT) + ", width=" + to_string(IMAGE_WIDTH_RESULT) + ", framerate=30/1 ! videoconvert ! video/x-raw, format=BGR ! appsink drop=true sync=false";
//std::cout << "{\"INIT\": \"DONE\"}" << std::endl;
to_node("INIT", "DONE");
//to_node("STATUS","starting with config: " + IMAGE_WIDTH_RESULT );
// -------------------------------------------------------------------------------
// THE MAIN LOOP STARTS HERE
while (true){
// get a new camera image pair. It will be aligned already
auto processed = cam_grab.get_cam_images();
try{
prepare_rgb_image_thr = new std::thread(prepare_rgb_image, processed, std::ref(rgb_image), std::ref(rgb_image_out));
prepare_depth_image_thr = new std::thread(prepare_depth_image, processed, std::ref(depth_image), std::ref(depth_image_out));
} catch (...) {
to_node("STATUS","IMAGE PREPARE THREAD FAILED");
continue;
}
try{
prepare_rgb_image_thr->join();
//rgb_image.download(rgb_image_out);
prepare_depth_image_thr->join();
//depth_image.download(depth_image_out);
} catch (...) {
to_node("STATUS","JOIN IMAGE PREPARE THREAD AND DOWNLOAD IMAGES FAILED");
continue;
}
try{
// remove background from image
cv::cuda::GpuMat rgb_back_image = cut_background_of_rgb_image(rgb_image, depth_image, gaussian, DISTANS_TO_CROP, cam_grab.get_depth_scale());
rgb_back_image.download(rgb_back_image_out);
} catch (...) {
to_node("STATUS","CUT BACKGROUND FROM IMAGES FAILED");
continue;
}
try{
// resize the image for the object and gesture detection and download it from the gpu.
cv::cuda::resize(rgb_image, rgb_scaled, Size(COLOR_SMALL_WIDTH, COLOR_SMALL_HEIGHT),0,0, INTER_AREA);
rgb_scaled.download(small_rgb_image_out);
} catch (...) {
to_node("STATUS","SCALE IMAGE SMALL");
continue;
}
try{
writer_hd_image->write_image(rgb_image_out);
writer_small_image->write_image(small_rgb_image_out);
writer_image_1m->write_image(rgb_back_image_out);
//writer_depth_image->write_image(depth_image_out);
} catch (...) {
to_node("STATUS","IMAGE WRITER FAILED");
continue;
}
try{
prepare_center_image_thr->join();
center_writer_thr->join();
} catch (...) {
to_node("STATUS","JOIN THREADS FROM LAST ITERATION");
continue;
}
//cap_video_style >> post_draw_image;
if(show_style_transfer){
try{
if (!cap_video_style.isOpened()) {
to_node("STATUS", "style transfere image sink was not ready jet (?)..");
cap_video_style.open(gst_string_style, CAP_GSTREAMER);
std::this_thread::sleep_for(std::chrono::seconds(1));
} else {
Mat frame;
if (cap_video_style.read(frame)){
frame.copyTo(post_draw_image);
}
}
} catch (...) {
to_node("STATUS","STYLE TRANSFERE FAILED");
continue;
}
} else {
pre_draw_image.copyTo(post_draw_image);
}
if(show_camera){
if(show_camera_1m){
rgb_back_image_out.copyTo(pre_draw_image);
} else {
rgb_image_out.copyTo(pre_draw_image);
}
} else {
black_image.copyTo(pre_draw_image);
}
try{
center_writer_thr = new std::thread(write_to_mjpeg_writer, std::ref(post_draw_image));
prepare_center_image_thr = new std::thread(prepare_center_image, std::ref(pre_draw_image));
} catch (...) {
to_node("STATUS","DRAW CENTER IMAGE AND WRITE THREADS FAILED");
continue;
}
// -------------------------------------------------------------------------------
// sleep if to fast.. and print fps after 30 frames
std::this_thread::sleep_until<std::chrono::system_clock>(before + std::chrono::milliseconds (1000/(FRAMERATE+1)));
auto now = std::chrono::system_clock::now();
auto after = now;
double curr = 1000. / std::chrono::duration_cast<std::chrono::milliseconds>(after - before).count();
framecounteracc += curr;
before = after;
framecounter += 1;
if (framecounter > 30){
std::cout << "{\"IMAGE_HANDLER_FPS\": " << (framecounteracc/framecounter) <<"}" << std::endl;
framecounteracc = 0.0;
framecounter = 0.0;
}
}
// return if loop breaks
return EXIT_SUCCESS;
// MAIN ENDS HERE
}
catch( const rs2::error & e )
{
std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what() << std::endl;
return EXIT_FAILURE;
}
catch( const std::exception & e )
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
// -------------------------------------------------------------------------------
// Function description below
void load_images_gestures() {
for (int i = 0; i < NUMBER_OF_GESTURES ; i++) {
//std::cout << PATH_ICON_GESTURES << str_gestures[i] << ".jpg" << std::endl;
resize(imread(PATH_ICON_GESTURES + str_gestures[i] + ".jpg"), gesture_images[i],Size(100,100));
//gesture_images[i] = imread(PATH_ICON_GESTURES + str_gestures[i] + ".jpg");
}
}
// rotate and flip input image according to IMAGE_ROTATION_RESULT
// A flip is always needed due to being a mirror
void rotate_image(cv::cuda::GpuMat& input){
//cv::cuda::GpuMat input_fliped;
cv::cuda::GpuMat tmp;
if(IMAGE_ROTATION_RESULT == 90){
cv::cuda::flip(input, tmp,1);
cv::cuda::rotate(tmp, input, Size(IMAGE_WIDTH_RESULT, IMAGE_HEIGHT_RESULT), 90.0, 0, COLOR_INPUT_WIDTH);
}else if(IMAGE_ROTATION_RESULT == -90) {
cv::cuda::flip(input, tmp,0);
cv::cuda::rotate(tmp, input, Size(IMAGE_WIDTH_RESULT,IMAGE_HEIGHT_RESULT), 90.0, 0, COLOR_INPUT_WIDTH);
}else {
cv::cuda::flip(input, tmp,1);
input = tmp;
}
//return output;
}
void rotate_image_cv(cv::Mat& input){
//cv::cuda::GpuMat input_fliped;
cv::Mat tmp;
if(IMAGE_ROTATION_RESULT == 90){
cv::transpose(input, input);
//cv::flip(tmp ,input,1);
//cv::rotate(tmp, input, 1);
}else if(IMAGE_ROTATION_RESULT == -90) {
cv::flip(input, tmp,0);
cv::rotate(tmp, input, 90);
}else {
cv::flip(input, tmp,1);
input = tmp;
}
//return output;
}
// Create color image
void prepare_rgb_image (rs2::frameset processed_frameSet,cv::cuda::GpuMat& rgb_image, cv::Mat& rgb ){
rs2::frame color = processed_frameSet.get_color_frame();
cv::Mat tmp_rgb (COLOR_INPUT_HEIGHT, COLOR_INPUT_WIDTH, CV_8UC3, (uchar *) color.get_data());
rotate_image_cv(tmp_rgb);
rgb_image.upload(tmp_rgb);
rgb = tmp_rgb;
//rotate_image(rgb_image);
}
// Create depth image
void prepare_depth_image (rs2::frameset processed_frameSet, cv::cuda::GpuMat& depth_image, cv::Mat& depth8u){
rs2::frame depth = processed_frameSet.get_depth_frame();
cv::Mat depth16 (COLOR_INPUT_HEIGHT, COLOR_INPUT_WIDTH, CV_16U,(uchar *) depth.get_data());
cv::convertScaleAbs(depth16,depth8u, 0.03);
rotate_image_cv(depth8u);
depth_image.upload(depth8u);
//rotate_image(depth_image);
}
// cut everything away that is to far away.
cv::cuda::GpuMat cut_background_of_rgb_image(cv::cuda::GpuMat& rgb, cv::cuda::GpuMat& depth,Ptr<cuda::Filter>& gaussianFilter, int distance_to_crop, float camera_depth_scale ){
cv::cuda::GpuMat output;
cv::cuda::GpuMat depth_tmp;
auto thresh = double(distance_to_crop * camera_depth_scale );
cv::cuda::threshold(depth,depth,thresh,255,THRESH_TOZERO_INV);
gaussianFilter->apply(depth, depth_tmp);
cv::cuda::threshold(depth_tmp,depth,double(5),1,THRESH_BINARY);
cv::cuda::GpuMat rgb_back_image;
rgb.copyTo(output,depth);
return output;
}
// Function to write in correct format
void to_node(std::string topic, std::string payload) {
json j;
j[topic] = payload;
cout << j.dump() << endl;
}
// signal handler
// if sigint arrives, delete everything accordingly
void sig_handler(int sig) {
switch (sig) {
case SIGINT:
delete writer_hd_image;
delete writer_small_image;
delete writer_image_1m;
//delete writer_depth_image;
delete mjpeg_writer_ptr;
exit(0);
default:
fprintf(stderr, "wasn't expecting that!\n");
abort();
}
}
void set_command(string setting) {
if (setting == "TOGGLE") {
show_camera = !show_camera;
show_style_transfer = false;
} else if (setting == "DISTANCE") {
show_camera_1m = !show_camera_1m;
} else if (setting == "FACE") {
show_captions_face = !show_captions_face;
} else if (setting == "OBJECT") {
show_captions_objects = !show_captions_objects;
} else if (setting == "GESTURE") {
show_captions_gestures = !show_captions_gestures;
} else if (setting == "PERSON") {
show_captions_persons = !show_captions_persons;
} else if (setting == "STYLE_TRANSFERE" && is_ai_art) {
show_camera = false;
show_camera_1m = false;
show_captions_face = false;
show_captions_objects = false;
show_captions_gestures = false;
show_captions_persons = false;
show_style_transfer = !show_style_transfer;
to_node("STATUS","STYLE_TRANSFERE was toggelt");
} else if (setting == "HIDEALL") {
show_camera = false;
show_camera_1m = false;
show_captions_face = false;
show_captions_objects = false;
show_captions_gestures = false;
show_captions_persons = false;
show_style_transfer = false;
} else if (setting == "SHOWALL") {
show_camera = true;
show_captions_face = true;
show_captions_objects = true;
show_captions_gestures = true;
show_captions_persons = true;
show_style_transfer = false;
}
}
string get_stdin() {
std::string line;
std::getline(std::cin, line);
return line;
}
void check_stdin(){
vector<string> lines;
while (true) {
try{
auto line = get_stdin();
auto args = json::parse(line);
//to_node("STATUS", "Got stdin line: " + args.dump());
if (args.count("SET") == 1) {
string setting = args["SET"];
set_command(setting);
} else if (args.count("DETECTED_FACES")==1) {
json_faces.push(args["DETECTED_FACES"]);
// to_node("STATUS", json_faces.front().dump());
} else if (args.count("DETECTED_GESTURES")==1) {
json_gestures.push(args["DETECTED_GESTURES"]);
// to_node("status", json_gestures.dump());
} else if (args.count("DETECTED_OBJECTS")==1) {
json_objects.push(args["DETECTED_OBJECTS"]);
// to_node("status", json_objects.dump());
} else if (args.count("RECOGNIZED_PERSONS")==1) {
json_persons.push(args["RECOGNIZED_PERSONS"]);
// to_node("status", json_persons.dump());
}
} catch (json::exception& e)
{
to_node("STATUS","CPP Error: " + string(e.what()) + "; Line was ");
}
}
}
// Prepare the center image
void prepare_center_image(cv::Mat& pre_draw_image){
try{
draw_objects(std::ref(pre_draw_image));
draw_gestures(std::ref(pre_draw_image));
draw_faces(std::ref(pre_draw_image));
draw_persons(std::ref(pre_draw_image));
} catch (...) {
to_node("STATUS","DRAW IMAGE FAILED");
}
}
// converting x,y and w,h to a cv rect
cv::Rect convert_back(float x, float y, float w, float h){
auto abs_w = w * IMAGE_WIDTH_RESULT;
auto abs_h = h * IMAGE_HEIGHT_RESULT;
auto abs_x = (x * IMAGE_WIDTH_RESULT) - (abs_w/2);
auto abs_y = (y * IMAGE_HEIGHT_RESULT) - (abs_h/2);
return Rect (abs_x, abs_y, abs_w, abs_h );
}
// Draw detected objects in to referenced image.
void draw_objects(cv::Mat& pre_draw_image){
int i = json_objects.size();
while (i > 0){
json_objects.pop(json_object);
i--;
}
if (!json_object.is_null() && show_captions_objects){
for (auto& element : json_object) {
Rect rect = convert_back(element["center"][0].get<float>(), element["center"][1].get<float>(), element["w_h"][0].get<float>(), element["w_h"][1].get<float>());
rectangle(pre_draw_image, rect, Scalar(55,255,55));
putText(pre_draw_image, element["name"].get<std::string>() + "/ID:" + to_string(element["TrackID"].get<int>()),Point(rect.x, rect.y),FONT_HERSHEY_COMPLEX,1,Scalar(55,255,55),3);
}
}
}
// Draw detected gestures in to referenced image.
void draw_gestures(cv::Mat& pre_draw_image){
int i = json_gestures.size();
while (i > 0){
json_gestures.pop(json_gesture);
i--;
}
if (!json_gesture.is_null() && show_captions_gestures ){
for (auto& element : json_gesture) {
Rect rect = convert_back(element["center"][0].get<float>(), element["center"][1].get<float>(), element["w_h"][0].get<float>(), element["w_h"][1].get<float>());
rectangle(pre_draw_image, rect, Scalar(55,255,55));
putText(pre_draw_image, element["name"].get<std::string>() + "/ID:" + to_string(element["TrackID"].get<int>()),Point(rect.x, rect.y),FONT_HERSHEY_COMPLEX,1,Scalar(55,255,55),3);
}
}
if(!show_captions_gestures && !show_captions_objects && !show_captions_face && !show_camera){
for (auto& element : json_gesture) {
for (int i = 0 ; i < NUMBER_OF_GESTURES; i++){
if (element["name"].get<std::string>().compare(str_gestures[i]) == 0){
//Rect rect = convert_back(element["center"][0].get<float>(), element["center"][1].get<float>(), element["w_h"][1].get<float>());
gesture_images[i].copyTo(pre_draw_image(cv::Rect(element["center"][0].get<float>() * IMAGE_WIDTH_RESULT,element["center"][1].get<float>() * IMAGE_HEIGHT_RESULT,gesture_images[i].cols, gesture_images[i].rows)));
}
}
/*for (auto gesture : str_gestures) {
if (element["name"].get<std::string>().compare(gesture) == 0){
to_node("STATUS", gesture + "needs to be drawn");
//small_image.copyTo(big_image(cv::Rect(x,y,small_image.cols, small_image.rows)));
//gesture_images
}
} */
}
}
}
// Draw detected faces in to referenced image.
void draw_faces(cv::Mat& pre_draw_image){
int i = json_faces.size();
while (i> 0){
json_faces.pop(json_face);
i--;
}
if (!json_face.is_null() && show_captions_face){
for (auto& element : json_face) {
Rect rect = convert_back(element["center"][0].get<float>(), element["center"][1].get<float>(), element["w_h"][0].get<float>(), element["w_h"][1].get<float>());
rectangle(pre_draw_image, rect, Scalar(255,55,55));
putText(pre_draw_image, element["name"].get<std::string>() + "/ID:" + to_string(element["TrackID"].get<int>()),Point(rect.x, rect.y),FONT_HERSHEY_COMPLEX,1,Scalar(255,55,55),3);
}
}
}
// Draw persons in to referenced image.
void draw_persons(cv::Mat& pre_draw_image){
int i = json_persons.size();
while (i> 0){
json_persons.pop(json_person);
i--;
}
if (!json_person.is_null() && show_captions_persons){
for (auto& element : json_person) {
Rect rect = convert_back(element["center"][0].get<float>(), element["center"][1].get<float>(), element["w_h"][0].get<float>(), element["w_h"][1].get<float>());
rectangle(pre_draw_image, rect, Scalar(255,255,255));
putText(pre_draw_image, element["name"].get<std::string>() + "/ID:" + to_string(element["TrackID"].get<int>()),Point(rect.x, rect.y),FONT_HERSHEY_COMPLEX,1,Scalar(255,255,255),3);
}
}
}
|
43fc8aa730b7d70d4459c10bfb1038f3b8e9ec24 | 02383c4c79846536cfcfe1ff7dcbec61fbed628a | /altona_wz4/altona/main/base/graphics_dx9_private.hpp | 0e802a64434b3e9a1ab29eec7b91228ffbe505a4 | [
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] | permissive | Ace17/fr_public | f8df170d76d7f6daf929e85cc3872fe834e37e4b | 9014f5b8e9ea9f9cca4d1b689a2c82e8202cbed4 | refs/heads/master | 2021-01-17T11:23:10.188451 | 2015-01-27T20:21:56 | 2015-01-27T20:21:56 | 29,902,485 | 0 | 0 | null | 2015-01-27T07:24:25 | 2015-01-27T07:24:25 | null | UTF-8 | C++ | false | false | 4,201 | hpp | graphics_dx9_private.hpp | /*+**************************************************************************/
/*** ***/
/*** This file is distributed under a BSD license. ***/
/*** See LICENSE.txt for details. ***/
/*** ***/
/**************************************************************************+*/
#pragma once
#include "base/types.hpp"
/****************************************************************************/
enum
{
sMTRL_MAXTEX = 16, // max number of textures
sMTRL_MAXPSTEX = 16, // max number of pixel shader samplers
sMTRL_MAXVSTEX = 4, // max number of vertex shader samplers
};
/****************************************************************************/
class sGeometryPrivate
{
};
struct sVertexFormatHandlePrivate
{
protected:
struct IDirect3DVertexDeclaration9* Decl;
public:
struct IDirect3DVertexDeclaration9* GetDecl()
{
return Decl;
} // this is only for internal use.
};
class sTextureBasePrivate
{
protected:
/*
friend void sSetRendertargetPrivate(class sTextureBase *tex,sInt xs,sInt ys,const sRect *vrp,sInt flags,struct IDirect3DSurface9 *cubesurface);
friend void sSetScreen(const sRect &rect,sU32 *data);
friend void sResolveTargetPrivate();
*/
friend void sRender3DEnd(sBool flip);
friend void sSetTarget(const struct sTargetPara& para);
friend void sResolveTargetPrivate(class sTextureBase* tex);
friend void sCopyTexture(const struct sCopyTexturePara& para);
friend void sBeginReadTexture(const sU8 * &data, sS32 & pitch, enum sTextureFlags& flags, class sTexture2D * tex);
friend class sGpuToCpu;
enum TexturePrivateResolveFlags
{
RF_MultiValid = 0x0001,
RF_SingleValid = 0x0002,
RF_Resolve = 0x0004,
};
union
{
struct IDirect3DBaseTexture9* TexBase;
struct IDirect3DTexture9* Tex2D;
struct IDirect3DCubeTexture9* TexCube;
struct IDirect3DVolumeTexture9* Tex3D;
};
struct IDirect3DSurface9* Surf2D; // used only by DXBackBuffer
struct IDirect3DSurface9* MultiSurf2D; // used by DXBackBuffer and multisampled rendertargets
virtual void OnLostDevice(sBool reinit = sFALSE);
sU32 ResolveFlags; // RF_???
sU32 DXFormat;
sTextureBasePrivate();
};
class sShaderPrivate
{
friend sShader* sCreateShader(sInt type, const sU8* code, sInt bytes);
friend sShader* sCreateShaderRaw(sInt type, const sU8* code, sInt bytes);
friend void sSetShaders(sShader* vs, sShader* ps, sShader* gs, sLinkedShader** link, sCBufferBase** cbuffers, sInt cbcount);
friend void sCreateShader2(sShader* shader, sShaderBlob* blob);
friend void sDeleteShader2(sShader* shader);
friend void sSetShader2(sShader* shader);
friend class sMaterial;
protected:
union
{
struct IDirect3DVertexShader9* vs; // sRENDER_DX9
struct IDirect3DPixelShader9* ps; // sRENDER_DX9
};
};
class sMaterialPrivate
{
public:
// need access from specialized sToolPlatforms...
sU32** States;
sInt* StateCount;
};
/****************************************************************************/
struct sOccQueryNode
{
sDNode Node;
sInt Pixels;
struct IDirect3DQuery9* Query;
};
class sOccQueryPrivate
{
protected:
sOccQueryNode* Current;
sDList2<sOccQueryNode> Queries;
};
/****************************************************************************/
class sCBufferBasePrivate
{
public:
void* DataPersist;
void** DataPtr;
sU64 Mask; // used register mask
};
/****************************************************************************/
class sGfxThreadContextPrivate
{
};
/****************************************************************************/
class sGpuToCpuPrivate
{
protected:
sInt SizeX, SizeY;
sInt Flags;
sInt DXFormat;
sBool Locked;
sTexture2D* SrcTex;
sInt SrcMipLevel;
struct IDirect3DSurface9* Dest;
};
/****************************************************************************/
|
c605c6b490d77ad451b9e8fc6357dc9a7ea189f8 | bb1c9d8f47789137ce7269fdd056992f7848fed0 | /src/api/dcps/isocpp/include/dds/sub/cond/detail/QueryCondition.hpp | 127968f592d514e453721a11856df42791ffe197 | [
"Apache-2.0"
] | permissive | osrf/opensplice | e37ed7e1a24ece7c0f480b4807cd95d3ee18daad | 7c3466f76d083cae38a6d7fcbba1c29106a43ea5 | refs/heads/osrf-6.9.0 | 2021-01-15T14:20:20.065297 | 2020-05-11T18:05:53 | 2020-05-11T18:05:53 | 16,789,031 | 10 | 13 | Apache-2.0 | 2020-05-11T18:05:54 | 2014-02-13T02:13:20 | C | UTF-8 | C++ | false | false | 6,174 | hpp | QueryCondition.hpp | /*
* Vortex OpenSplice
*
* This software and documentation are Copyright 2006 to TO_YEAR ADLINK
* Technology Limited, its affiliated companies and licensors. 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 OSPL_DDS_SUB_COND_DETAIL_QUERYCONDITION_HPP_
#define OSPL_DDS_SUB_COND_DETAIL_QUERYCONDITION_HPP_
/**
* @file
*/
// Implementation
#include <dds/sub/cond/detail/ReadCondition.hpp>
#include <dds/sub/Query.hpp>
#include <org/opensplice/core/exception_helper.hpp>
#include <iostream>
#ifdef OMG_DDS_CONTENT_SUBSCRIPTION_SUPPORT
namespace dds
{
namespace sub
{
namespace cond
{
namespace detail
{
class QueryCondition;
}
}
}
}
/**
* @internal QueryCondition inherits from ReadCondition and additionally provides the ability
* to store a query made up of a query expression and parameters. As with ReadCondition,
* a handler functor can be passed in at construction time which is then executed
* by WaitSetImpl which calls it's dispatch member function when the condition is triggered.
*/
class dds::sub::cond::detail::QueryCondition: public dds::sub::cond::detail::ReadCondition
{
public:
typedef std::vector<std::string>::iterator iterator;
typedef std::vector<std::string>::const_iterator const_iterator;
public:
QueryCondition() : ReadCondition(), query_(dds::core::null) { }
QueryCondition(
const dds::sub::Query& query,
const dds::sub::status::DataState& data_state)
: ReadCondition(query.data_reader(), data_state, true),
query_(query)
{
DDS::StringSeq params;
params.length(static_cast<DDS::ULong>(query.parameters_length() + 1));
uint32_t i = 0;
for(dds::sub::Query::const_iterator it = query.begin(); it != query.end(); it++)
{
params[i] = it->c_str();
i++;
}
params[query.parameters_length()] = DDS::string_dup("");
query_condition_ = adr_->get_dds_datareader()->create_querycondition(status_.sample_state().to_ulong(),
status_.view_state().to_ulong(), status_.instance_state().to_ulong(), query.expression().c_str(), params);
if(query_condition_.in() == 0) throw dds::core::NullReferenceError(org::opensplice::core::exception_helper(
OSPL_CONTEXT_LITERAL("dds::core::NullReferenceError : Unable to create QueryCondition. "
"Nil return from ::create_querycondition")));
condition_ = query_condition_.in();
}
template <typename FUN>
QueryCondition(const dds::sub::Query& query,
const dds::sub::status::DataState& data_state, const FUN& functor)
: ReadCondition(query.data_reader(), data_state, functor, true),
query_(query)
{
DDS::StringSeq params;
params.length(static_cast<DDS::ULong>(query.parameters_length() + 1));
uint32_t i = 0;
for(dds::sub::Query::const_iterator it = query.begin(); it != query.end(); it++)
{
params[i] = it->c_str();
i++;
}
params[query.parameters_length()] = DDS::string_dup("");
query_condition_ = adr_->get_dds_datareader()->create_querycondition(status_.sample_state().to_ulong(),
status_.view_state().to_ulong(), status_.instance_state().to_ulong(), query.expression().c_str(), params);
if(query_condition_.in() == 0) throw dds::core::NullReferenceError(org::opensplice::core::exception_helper(
OSPL_CONTEXT_LITERAL("dds::core::NullReferenceError : Unable to create QueryCondition. "
"Nil return from ::create_querycondition")));
condition_ = query_condition_.in();
}
virtual ~QueryCondition()
{
if(query_condition_)
{
DDS::ReturnCode_t result = adr_->get_dds_datareader()->delete_readcondition(query_condition_.in());
org::opensplice::core::check_and_throw(result, OSPL_CONTEXT_LITERAL("Calling ::delete_readcondition"));
}
}
void expression(const std::string& expr)
{
query_.expression(expr);
}
const std::string& expression()
{
return query_.expression();
}
/**
* @internal Provides the begin iterator to the parameter list.
*/
iterator begin()
{
return query_.begin();
}
/**
* @internal The end iterator to the parameter list.
*/
iterator end()
{
return query_.end();
}
const_iterator begin() const
{
return query_.begin();
}
/**
* @internal The end iterator to the parameter list.
*/
const_iterator end() const
{
return query_.end();
}
template<typename FWIterator>
void parameters(const FWIterator& begin, const FWIterator end)
{
query_.parameters(begin, end);
}
void add_parameter(const std::string& param)
{
query_.add_parameter(param);
}
uint32_t parameters_length() const
{
return query_.parameters_length();
}
const AnyDataReader& data_reader()
{
return query_.data_reader();
}
const DDS::QueryCondition_var& query_condition()
{
return query_condition_;
}
const dds::sub::Query& query()
{
return query_;
}
private:
DDS::QueryCondition_var query_condition_;
dds::sub::Query query_;
};
#endif // OMG_DDS_CONTENT_SUBSCRIPTION_SUPPORT
// End of implementation
#endif /* OSPL_DDS_SUB_COND_DETAIL_QUERYCONDITION_HPP_ */
|
662e0fc9e1d57d07dd4aa76d19915c59045f22f2 | b7f74833ddc73edbb8ebfce606b4ceb765f77bdb | /Bayes_Bin_Two.cpp | 4febb6b4d56a8e44863a40ecda427913cc52a91f | [] | no_license | kaiding/bayes_utils | a3eb430c61adb966ecc071ac3ac686efd5cefb8c | a16c506d89fbbeaa30f21303b92191108787655f | refs/heads/master | 2022-12-13T09:04:24.587857 | 2020-08-27T18:46:09 | 2020-08-27T18:46:09 | 285,686,843 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,507 | cpp | Bayes_Bin_Two.cpp | #define RCPPDIST_DONT_USE_ARMA
#include <Rcpp.h>
#include <RcppDist.h>
// [[Rcpp::depends(RcppDist)]]
// [[Rcpp::depends(RcppEigen)]]
// [[Rcpp::depends(RcppNumerical)]]
#include <RcppNumerical.h>
using namespace Rcpp;
//Binary Endpoints
//Bayesian predictive power (simulation-based),
//Conditional power, and predictive power.
// predictive probability afer interim given beta prior
// which is a beta-binom
// [[Rcpp::export]]
double beta_binom(int s, int t, double a, double b, int N, int n){
double num = R::beta(s + t + a, N - s - t + b);
double den = (N - n - t)*R::beta(t + 1,N - n- t)*R::beta(s + a, n - s + b);
return(num/den);
}
// posterior probability of detecting a treatment difference
// Simulation-based
// [[Rcpp::export]]
double post_Bin_MC_cpp(double a1, double b1, double a2, double b2, double delta,
double N1, double N2, double x1, double x2, double nsim){
double a1s = a1 + x1;
double b1s = N1 - x1 + b1;
double a2s = a2 + x2;
double b2s = N2 - x2 +b2;
NumericVector p1 = rbeta(nsim, a1s, b1s);
NumericVector p2 = rbeta(nsim, a2s, b2s);
NumericVector diff = p1 - p2;
return(mean(diff > delta));
}
// Bayesian predictive probability
// Simulation-based
// [[Rcpp::export]]
double Pbayes_Bin_MC_cpp(double a1, double b1, double a2, double b2,
double n1, double s1, double n2, double s2,
double N, double delta, double neta, double nsim){
double res=0;
for (int t1 = 0; t1 < N - n1; ++t1){
double p1;
double x1 = s1 + t1;
p1 = beta_binom(s1, t1, a1, b1, N, n1);
//Rcout << "t1: "<<t1<<" p1: "<<p1<<"\n";
for(int t2 = 0; t2 < N - n2; ++t2){
double p2;
double post;
double x2 = s2 + t2;
post = post_Bin_MC_cpp(a1, b1, a2, b2, delta, N, N, x1, x2, nsim);
//Rcout << "t2: "<<t2<<" p2: "<<p2<<" post: "<<post<<"\n";
if (post > neta) {
p2 = beta_binom(s2, t2, a2, b2, N, n2);
res += p1*p2;
}
}
}
return(res);
}
//Binary Endpoints
//Bayesian predictive power (analytical-based),
// Integrand used in Bayes Pred Prob
class bayes_int: public Numer::Func
{
private:
double a1;
double b1;
double a2;
double b2;
double delta;
public:
bayes_int(double a1_, double b1_, double a2_, double b2_, double delta_) :
a1(a1_), b1(b1_), a2(a2_), b2(b2_), delta(delta_) {}
double operator()(const double& x) const
{
return std::pow(x, a1-1)*std::pow(1-x, b1-1)*R::pbeta(x-delta, a2, b2, 1, 0);
}
};
double integrate_bayes(double a1, double b1, double a2, double b2, double delta){
const double upper = 1;
bayes_int f(a1, b1, a2, b2, delta);
double err_est;
int err_code;
const double res = integrate(f, delta, upper, err_est, err_code);
return res;
}
// posterior probability of detecting a treatment difference
// Analytical-based
// [[Rcpp::export]]
double post_Bin_Analytical_cpp(double a1, double b1, double a2, double b2, double delta,
double N1, double N2, double x1, double x2){
double a1s = a1 + x1;
double b1s = N1 - x1 + b1;
double a2s = a2 + x2;
double b2s = N2 - x2 +b2;
double res = integrate_bayes(a1s, b1s, a2s, b2s, delta);
double pgds = (1/(R::beta(a1s, b1s)));
return(pgds*res);
}
// Bayesian predictive probability
// Analytical-based
// [[Rcpp::export]]
double Pbayes_Bin_Analytical_cpp(double n1, double n2, double neta, double delta,
double N, double s1, double s2,
double a1, double a2, double b1, double b2){
double ans = 0;
for (int t1 = 0; t1 < N - n1; ++t1){
double ptgs1 = beta_binom(s1, t1, a1, b1, N, n1);
double pgds = (1/(R::beta(s1+t1+a1, N - s1 - t1 + b1)));
double a1s = s1 + t1 + a1;
double b1s = N - s1 - t1 + b1;
//Rcout << "t1: "<<t1<<" p1: "<<ptgs1<<"\n";
for (int t2 = 0; t2 < N - n2; ++t2) {
double a2s = s2 + t2 + a2;
double b2s = N - s2 - t2 + b2;
double integral = integrate_bayes(a1s, b1s, a2s, b2s, delta);
double pgd = pgds*integral;
//Rcout << "t2: "<<t2<<" p2: "<<ptgs2<<" post: "<<pgd<<"\n";
if (pgd > neta) {
double ptgs2 = beta_binom(s2, t2, a2, b2, N, n2);
ans += ptgs1*ptgs2;
}
}
}
return ans;
}
//Wrapper for predictive prob using either analytical or simulation methods
// [[Rcpp::export]]
// Predictive power
double Pbayes_Bin_cpp(double a1, double b1, double a2, double b2,
double n1, double s1, double n2, double s2,
double N, double delta, double neta, int method, double nsim){
double tmp;
//method = 1 for analytical
if (method == 1) tmp = Pbayes_Bin_Analytical_cpp(n1, n2, neta, delta, N, s1, s2, a1, a2, b1, b2);
//else (by default) for simulation
else tmp = Pbayes_Bin_MC_cpp(a1, b1, a2, b2, n1, s1, n2, s2, N, delta, neta, nsim);
return(tmp);
}
//Conditional Power
// [[Rcpp::export]]
double Pcond_Bin_cpp(double n1, double n2, double s1, double s2,
double N, double alpha, double es, double P1, double P2){
double p1 = s1/n1;
double p2 = s2/n2;
double n = (n1 + n2)/2;
double pbar = (s1 + s2)/(n1 + n2);
double theta = 0;
double PBAR = (P1+P2)/2;
double sigma = std::sqrt(PBAR*(1-PBAR));
if (es == 1) {
theta = P1 - P2;
}
if (es == 2) {
theta = p1 - p2;
}
if (es == 3) {
theta = 0;
}
double Zn = (p1 - p2)/std::sqrt(pbar*(1 - pbar)*(1/n1 + 1/n2));
return(R::pnorm((sqrt(n)*Zn+(N-n)*theta/(sigma*sqrt(2))-sqrt(N)*R::qnorm(1-alpha, 0, 1, 1, 0))/sqrt(N-n), 0, 1, 1, 0));
}
//Predictive Power
// [[Rcpp::export]]
double Ppred_Bin_cpp(double n1, double n2, double s1, double s2, double N,
double alpha, double a1, double b1, double a2, double b2){
double res=0;
double Za = R::qnorm(1-alpha, 0, 1, 1, 0);
for (int t1 = 0; t1 < N - n1; ++t1){
double x1 = s1 + t1;
double p1 = beta_binom(s1, t1, a1, b1, N, n1);
double p1hat = x1/N;
//Rcout << "t1: "<<t1<<" p1: "<<p1<<"\n";
for(int t2 = 0; t2 < N - n2; ++t2){
double x2 = s2 + t2;
double p2 = beta_binom(s2, t2, a2, b2, N, n2);
double p2hat = x2/N;
double pbar = (p1hat + p2hat)/2;
double ZN = (p1hat - p2hat)/sqrt(2*pbar*(1-pbar)/N);
if (ZN > Za) res += p1*p2;
//Rcout << "t2: "<<t2<<" p2: "<<p2<<" post: "<<post<<"\n";
}
}
return(res);
}
// [[Rcpp::export]]
// Interim monitoring
List IA_Bin_cpp(double n1, double n2, double s1, double s2, double N, int methodpb, double nsim_p,
double delta, double neta, double alpha,
NumericVector a1, NumericVector b1, NumericVector a2, NumericVector b2,
double P1, double P2){
int nr = a1.length();
NumericVector prob_BP(nr);
NumericVector prob_PP(nr);
NumericVector prob_CP(3);
for (int es =1; es <4; es++){
prob_CP[es-1] = Pcond_Bin_cpp(n1, n2, s1, s2, N, alpha, es, P1, P2);
}
for (int i=0; i < nr; i++) {
prob_BP[i] = Pbayes_Bin_cpp(a1[i], b1[i], a2[i], b2[i], n1, s1, n2, s2,
N, delta, neta, methodpb, nsim_p);
prob_PP[i] = Ppred_Bin_cpp(n1, n2, s1, s2, N,
alpha, a1[i], b1[i], a2[i], b2[i]);
}
List output = List::create(Named("PredProb") = prob_BP, _["PredPower"] = prob_PP,
_["CondPower"] = prob_CP);
return(output);
}
//Modified cumsum for selected subsets
NumericVector cumsum_bin_cpp(NumericVector sim_data, NumericVector n){
double ns = sim_data.length();
double tp = 0;
double j = 0;
NumericVector res(n.length());
for (int i=0; i < ns; i++){
tp += sim_data[i];
if (i == n[j]-1) {
res[j] = tp;
j += 1;
}
}
return(res);
}
// Interim decision based on power/probability, eg., result=1 for futiliy stopping
double interim(double p, double tau){
double res;
if (p < tau) res = 1;
else res = 0;
return(res);
}
// [[Rcpp::export]]
// Operating Characteristics
List OC_Bin_cpp(double nsim, double a1s, double b1s, double a2s, double b2s,
NumericVector n, int methodpb, double nsim_p,
double delta, double neta, double alpha, double tau,
NumericVector a1, NumericVector b1, NumericVector a2, NumericVector b2,
double P1, double P2){
int nr = a1.length();
int nc = n.length();
double N = n[nc-1];
NumericMatrix res_BP(nr, nc+2);
NumericMatrix res_PP(nr, nc+2);
NumericMatrix res_CP1(nr, nc+2);
NumericMatrix res_CP2(nr, nc+2);
NumericMatrix res_CP3(nr, nc+2);
//Rcout << "Interim+final: " << nc << "\n";
double z_final;
z_final = R::qnorm(1-alpha, 0, 1, 1, 0);
for (int k = 0; k < nsim; ++k){
double prop1 = rbeta(1, a1s, b1s)[0];
double prop2 = rbeta(1, a2s, b2s)[0];
NumericVector x1 = rbinom(N, 1, prop1);
NumericVector x2 = rbinom(N, 1, prop2);
NumericVector r1 = cumsum_bin_cpp(x1, n);
NumericVector r2 = cumsum_bin_cpp(x2, n);
//Rcout << "Current n: " << n << "\n";
//Rcout << "Current x1: " << x1 << "\n";
//Rcout << "Current x2: " << x2 << "\n";
//Rcout << "Current s1: " << r1 << "\n";
//Rcout << "Current s2: " << r2 << "\n";
double p1 = r1[nc-1]/N;
double p2 = r2[nc-1]/N;
double pbar = (p1 + p2)/2;
double ZN = (p1 - p2)/std::sqrt(2*pbar*(1 - pbar)/N);
//Rcout << "sim: "<< k+1 << "\n";
for (int j = 0; j < nr; ++j){
NumericVector ind_BP(nr);
NumericVector ind_PP(nr);
NumericVector ind_CP1(nr);
NumericVector ind_CP2(nr);
NumericVector ind_CP3(nr);
// Rcout << "..."<< "scenario: "<< j+1 << "\n";
for (int i = 0; i < nc; ++i){
double prob_BP;
double prob_PP;
double prob_CP1;
double prob_CP2;
double prob_CP3;
// Rcout << "......"<<"look: "<< i+1 << "\n";
// Rcout << "......"<< "Current Ind_BP: " << ind_BP[j] << "\n";
// Rcout << "......"<< "Current Ind_PP: " << ind_PP[j] << "\n";
// Rcout << "......"<< "Current Ind_CP: " << ind_CP[j] << "\n";
double n1 = n[i];
double n2 = n[i];
double s1 = r1[i];
double s2 = r2[i];
// Rcout << "......"<< "Current n1: " << n1 << "\n";
// Rcout << "......"<< "Current s1: " << s1 << "\n";
// Rcout << "......"<< "Current n2: " << n2 << "\n";
// Rcout << "......"<< "Current s2: " << s2 << "\n";
if (i == 0) {
prob_BP = Pbayes_Bin_cpp(a1[j], b1[j], a2[j], b2[j], n1, s1, n2, s2,
N, delta, neta, methodpb, nsim_p);
prob_PP = Ppred_Bin_cpp(n1, n2, s1, s2, N,
alpha, a1[j], b1[j], a2[j], b2[j]);
prob_CP1 = Pcond_Bin_cpp(n1, n2, s1, s2, N, alpha, 1, P1, P2);
prob_CP2 = Pcond_Bin_cpp(n1, n2, s1, s2, N, alpha, 2, P1, P2);
prob_CP3 = Pcond_Bin_cpp(n1, n2, s1, s2, N, alpha, 3, P1, P2);
ind_BP[j] = interim(prob_BP, tau);
ind_PP[j] = interim(prob_PP, tau);
ind_CP1[j] = interim(prob_CP1, tau);
ind_CP2[j] = interim(prob_CP2, tau);
ind_CP3[j] = interim(prob_CP3, tau);
res_BP(j, i) += ind_BP[j];
res_PP(j, i) += ind_PP[j];
res_CP1(j, i) += ind_CP1[j];
res_CP2(j, i) += ind_CP2[j];
res_CP3(j, i) += ind_CP3[j];
res_BP(j, nc+1) += ind_BP[j]*n[i];
res_PP(j, nc+1) += ind_PP[j]*n[i];
res_CP1(j, nc+1) += ind_CP1[j]*n[i];
res_CP2(j, nc+1) += ind_CP2[j]*n[i];
res_CP3(j, nc+1) += ind_CP3[j]*n[i];
}
else if (i < nc - 1) {
if(ind_BP[j] == 0) {
prob_BP = Pbayes_Bin_cpp(a1[j], b1[j], a2[j], b2[j], n1, s1, n2, s2,
N, delta, neta, methodpb, nsim_p);
ind_BP[j] = interim(prob_BP, tau);
res_BP(j, i) += ind_BP[j];
res_BP(j, nc+1) += ind_BP[j]*n[i];
}
if(ind_PP[j] == 0) {
prob_PP = Ppred_Bin_cpp(n1, n2, s1, s2, N,
alpha, a1[j], b1[j], a2[j], b2[j]);
ind_PP[j] = interim(prob_PP, tau);
res_PP(j, i) += ind_PP[j];
res_PP(j, nc+1) += ind_PP[j]*n[i];
}
if(ind_CP1[j] == 0){
prob_CP1 = Pcond_Bin_cpp(n1, n2, s1, s2, N, alpha, 1, P1, P2);
ind_CP1[j] = interim(prob_CP1, tau);
res_CP1(j, i) += ind_CP1[j];
res_CP1(j, nc+1) += ind_CP1[j]*n[i];
}
if(ind_CP2[j] == 0){
prob_CP2 = Pcond_Bin_cpp(n1, n2, s1, s2, N, alpha, 2, P1, P2);
ind_CP2[j] = interim(prob_CP2, tau);
res_CP2(j, i) += ind_CP2[j];
res_CP2(j, nc+1) += ind_CP2[j]*n[i];
}
if(ind_CP3[j] == 0){
prob_CP3 = Pcond_Bin_cpp(n1, n2, s1, s2, N, alpha, 3, P1, P2);
ind_CP3[j] = interim(prob_CP3, tau);
res_CP3(j, i) += ind_CP3[j];
res_CP3(j, nc+1) += ind_CP3[j]*n[i];
}
}
else {
if(ind_BP[j] == 1) res_BP(j, i) += 1;
else {
res_BP(j, nc+1) += n[i];
prob_BP = post_Bin_Analytical_cpp(a1[j], b1[j], a2[j], b2[j], delta,
N, N, s1, s2);
if (prob_BP < neta) res_BP(j, i) += 1;
}
if(ind_PP[j] == 1) res_PP(j, i) += 1;
else {
res_PP(j, nc+1) += n[i];
if (ZN < z_final) res_PP(j, i) += 1;
}
if(ind_CP1[j] == 1) res_CP1(j, i) += 1;
else {
res_CP1(j, nc+1) += n[i];
if (ZN < z_final) res_CP1(j, i) += 1;
}
if(ind_CP2[j] == 1) res_CP2(j, i) += 1;
else {
res_CP2(j, nc+1) += n[i];
if (ZN < z_final) res_CP2(j, i) += 1;
}
if(ind_CP3[j] == 1) res_CP3(j, i) += 1;
else {
res_CP3(j, nc+1) += n[i];
if (ZN < z_final) res_CP3(j, i) += 1;
}
}
// Rcout << "......"<< "PredProb/PredPow/CondPow"<< prob_BP << " " << prob_PP << " " << prob_CP << "\n";
// Rcout << "......"<< "Ind_BP after this look: " << ind_BP[j] << "\n";
// Rcout << "......"<< "Ind_PP after this look: " << ind_PP[j] << "\n";
// Rcout << "......"<< "Ind_CP after this look: " << ind_CP[j] << "\n";
// Rcout << "......"<< "res_BP: " << res_BP <<"\n";
// Rcout << "......"<< "res_PP: " << res_PP <<"\n";
// Rcout << "......"<< "res_CP: " << res_CP <<"\n";
}
}
}
res_BP = res_BP/nsim;
res_PP = res_PP/nsim;
res_CP1 = res_CP1/nsim;
res_CP2 = res_CP2/nsim;
res_CP3 = res_CP3/nsim;
res_BP(_, nc) = 1 - res_BP(_, nc-1);
res_PP(_, nc) = 1 - res_PP(_, nc-1);
res_CP1(_, nc) = 1 - res_CP1(_, nc-1);
res_CP2(_, nc) = 1 - res_CP2(_, nc-1);
res_CP3(_, nc) = 1 - res_CP3(_, nc-1);
List output = List::create(Named("PredProb") = res_BP, _["PredPower"] = res_PP,
_["CondPower1"] = res_CP1(1,_), _["CondPower2"] = res_CP2(1,_),
_["CondPower3"] = res_CP3(1,_));
return(output);
}
|
bc4a2cd224dcdd1ff2bec38386e1f01d599a2c39 | 17f3b846c0e739ebfcaf0dc27d19edf634eede92 | /Code/Game/Message.hpp | ae26f8864cafbfb9495c7bc75fa5933f73b70783 | [] | no_license | afulsom/GuildhallRoguelike | d22049ee0c97977cb87cf64881ebe81e77fbc627 | 3ec28ce4e740a25fa8336c54f6e6db4be78ce9be | refs/heads/master | 2021-05-09T11:04:55.396208 | 2018-01-26T00:12:06 | 2018-01-26T00:12:06 | 118,982,810 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 245 | hpp | Message.hpp | #pragma once
#include <string>
#include "Engine\Core\Rgba.hpp"
struct Message
{
Message(std::string text, const Rgba& color, float size)
: m_text(text), m_color(color), m_size(size) {}
std::string m_text;
Rgba m_color;
float m_size;
};
|
b3f51e238ae35840966901bd47bfcc5dd26b5b2d | 0363e5f25ce4d6e2ef0f122c0f430f64521252b7 | /Problems/PTA/A1058.cpp | 701d4b92791ba10f23ef8300f9688de442c58f13 | [
"Apache-2.0"
] | permissive | five-5/code | b734f7c4e63b93f6d06f210fb3e2b0c68f4ae6a1 | 9c20757b1d4a087760c51da7d3dcdcc2b17aee07 | refs/heads/master | 2021-06-30T02:53:46.463096 | 2020-10-13T02:37:14 | 2020-10-13T02:37:14 | 177,311,694 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 576 | cpp | A1058.cpp | #include <iostream>
#define Galleon (17*29)
#define Sickle 29
struct currency {
long long galleon;
int sickle;
int knut;
} A, B;
int main()
{
char c;
std::cin >> A.galleon >> c >> A.sickle >> c >> A.knut;
std::cin >> B.galleon >> c >> B.sickle >> c >> B.knut;
long long tmpA = A.galleon * Galleon + A.sickle * Sickle + A.knut;
long long tmpB = B.galleon * Galleon + B.sickle * Sickle + B.knut;
long long result = tmpA + tmpB;
std::cout << result / Galleon << c << (result % Galleon) / Sickle << c << result % Sickle;
return 0;
}
|
11bdf1b2dc13461bd87553e840b63b01c9691629 | b2447967414d64de23f66affa6288d35dd034fd1 | /Minimum_steps_by_knight_gfg.cpp | 9453a9a4f9c9e54acbe887fc47acb257a5e0f76b | [] | no_license | aryastarkananyaa/DSA-Questions | 1f93158316173cdc7e538ee49482d00defa48e87 | 9e05dbbac65c0e970f9815a3ba910c386114ce73 | refs/heads/main | 2023-05-12T11:33:02.533071 | 2021-06-07T11:51:22 | 2021-06-07T11:51:22 | 370,683,847 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 816 | cpp | Minimum_steps_by_knight_gfg.cpp | class Solution
{
public:
//Function to find out minimum steps Knight needs to reach target position.
int dx[8] = { -2, -1, 1, 2, -2, -1, 1, 2 };
int dy[8] = { -1, -2, -2, -1, 1, 2, 2, 1 };
int minStepToReachTarget(vector<int>&KnightPos,vector<int>&TargetPos,int N){
queue<pair<int,int>>q;
int count=0;
vector<vector<bool>> visited(N+1,vector<bool>(N+1,false));
q.push({KnightPos[0],KnightPos[1]});
visited[KnightPos[0]][KnightPos[1]]=true;
while(!q.empty())
{
int n=q.size();
for(int i=0;i<n;i++) { auto tmp=q.front();
q.pop();
if(tmp.first==TargetPos[0] and tmp.second==TargetPos[1])
return count;
for(int i=0;i<8;i++){ int nx=tmp.first+dx[i];
int ny=tmp.second+dy[i];
if(nx>=1 and nx<=N and ny>=1 and ny<=N and !visited[nx][ny])
{
visited[nx][ny]=true;
q.push({nx,ny});
}
}
}
count++;
}
return -1;
}
};
|
63f9135562ea71cb95537b771847ddd1a7c70dc3 | 333056fe82afcd6ea894549ff5527c0e4cccf80c | /arduino/Current_Voltage_Power.ino | 4948966ab161a05b0365fae77be62ec969335f2d | [] | no_license | gbraitch/windturbine | a60d6a5ef04c0dec05015f9e67f96d39daecc894 | 57246258b8c3686185ff1a07f2a924735876fcc9 | refs/heads/master | 2022-12-15T01:06:57.288597 | 2020-08-23T01:41:23 | 2020-08-23T01:41:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,722 | ino | Current_Voltage_Power.ino | /*
* Take analog read from A2 for voltage every interrupt and add to sum, display the average every 100 reads and reset
* A3 current
* A4 voltage from potentiometer
*/
void AnalogSensor()
{
VS_count++;
VS_sum += analogRead(VS_inputPin);
WS_sum += analogRead(WS_inputPin);
CS_sum += analogRead(CS_inputPin);
if(VS_count == 100){
// Voltage Calculations
VS_sum /= (float)VS_count; // Divide by VS_count to get average voltage
VS_sum *= (5.0/1023.0); // Multiply by 5/1023 to get the actual voltage value
VS_sum = VS_sum/(R2/(R1+R2)); // Reverse voltage divider to get real voltage
// Current Calculations
CS_sum /= (float)VS_count; // Divide by VS_count to get average
CS_sum *= (5.0/1023.0);
CS_sum /= 1.75; // Use formula derived from sample points to convert voltage
// to current
// Voltage calculations from potentiometer
WS_sum /= (float)VS_count;
WS_sum *= (5.0/1023);
WS_val = WS_sum;
// Pass values to power calculation
PC_voltage = VS_sum;
PC_current = CS_sum;
PC_power = PC_voltage * PC_current;
// Display values on serial print
Serial.print("Voltage Sensor = ");
Serial.print(VS_sum, 4);
Serial.println("V");
Serial.print("WSensor Voltage = ");
Serial.print(WS_val, 4);
Serial.println("V");
Serial.print("Current = ");
Serial.print(CS_sum, 3);
Serial.println("A");
Serial.print("Power =");
Serial.print(PC_power, 4);
Serial.println("W");
dutycycle = (int)((float)(duty3_2)/1023 * 100);
Serial.println(dutycycle);
Serial.println(boostup);
Serial.println();
/*
Serial.print(",");
Serial.print(VS_sum, 4);
Serial.print(" V");
Serial.print(",");
Serial.print(CS_sum, 3);
Serial.print(" A");
Serial.print(",");
Serial.print(WS_val, 4);
Serial.print(" V");
Serial.print(",");
Serial.print(PC_power, 4);
Serial.print(" W");
Serial.print(",");
Serial.print(dutycycle,1);
Serial.print(" ?");
Serial.println(",");
*/
ble.print(",");
ble.print(VS_sum, 4);
ble.print(",");
ble.print(CS_sum, 3);
ble.print(",");
ble.print(WS_val, 4);
ble.print(",");
ble.print(PC_power, 4);
ble.print(",");
ble.print(dutycycle,1);
ble.println(",");
// Reset counter and sum vals
VS_count = VS_sum = CS_sum = WS_sum = 0;
}
}
|
7cd9385cfaffa849658416a028d949299ed8f741 | 75909166a593f0c8c39486919939c46e3063bdd0 | /ClientSocket.cpp | 544b76bab3e5e25feffe7d4cf6c5208094a7a5e2 | [] | no_license | goingcoder/ftp4fun | 409d18dfcdf53192c2f20b5c5cfbdd13c7915570 | b1542d0d9155aac06fb4be5470373ae8d5416a81 | refs/heads/master | 2020-03-19T09:50:20.505487 | 2016-04-19T16:43:49 | 2016-04-19T16:43:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 729 | cpp | ClientSocket.cpp | #include "ClientSocket.h"
#include "Socket.h"
#include "SocketException.h"
ClientSocket::ClientSocket(std::string host, int port) {
if (!Socket::create()) {
throw SocketException ("Could not create client socket.");
}
if (!Socket::connect(host, port)) {
throw SocketException ("Could not connect to server.");
}
}
const ClientSocket& ClientSocket::operator << (const std::string s) const {
if (!Socket::send(s)) {
throw SocketException ("Could not write to socket.");
}
return *this;
}
const ClientSocket& ClientSocket::operator >> (std::string &s) const {
if (!Socket::recv(s)) {
throw SocketException ("Could not read from socket.");
}
return *this;
} |
d22f90a4b0988abd8c91440fa924936de047cc2d | 0e1dc2824b976c7ecae3be8489319dde2845d22b | /new_instance.cpp | a15b7669c9f07abae8d4df50748f3fe888a50b92 | [] | no_license | tarotez/cppintro | d1f053a8a61521634857cc320699a94f6877c60e | e2a8f038be22f7a1e903d18611a20253c0c7ebc3 | refs/heads/master | 2020-06-20T21:59:52.172487 | 2019-12-03T05:47:45 | 2019-12-03T05:47:45 | 74,819,722 | 6 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 730 | cpp | new_instance.cpp | /* new_instance.cpp */
#include <iostream>
using namespace std;
class person{
public:
string name;
};
class ticket{
public:
int id;
person* user;
ticket(){user = new person;}
};
int main()
{
int ticketNum;
cout << "チケットを何枚購入しますか? ";
cin >> ticketNum;
cout << "\n";
ticket* tickets = new ticket [ticketNum];
for(int i = 0; i < ticketNum; i++){
tickets[i].id = i+1;
cout << i+1 << "人目の利用者の名前を入力してください: ";
cin >> tickets[i].user->name;
}
cout << "\nチケット利用者一覧:\n";
for(int i = 0; i < ticketNum; i++){
cout << " " << tickets[i].id << " : " << tickets[i].user->name << "\n";
}
cout << "\n";
}
|
10477acb13d1db1fcbfcf501bcc845b06b406b35 | 8cdb51622a7f330968293dcd82db5e18cd376b9c | /include/CPVFramework/Module/Module.hpp | 013b3d1c2640305c636d29f8c6c2f99135d0e3e4 | [
"MIT"
] | permissive | Lwelch45/cpv-framework | 90930d4ffc75bfe3e6f9f6271a2556fb750adcca | 11f3e882cd3bdec1c4a590f09148c21705b21f60 | refs/heads/master | 2020-03-18T23:11:31.042662 | 2018-05-16T00:58:43 | 2018-05-16T01:43:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,107 | hpp | Module.hpp | #pragma once
#include <core/shared_ptr.hh>
#include <core/future.hh>
#include "../Container/Container.hpp"
#include "../Utility/JsonUtilsSlim.hpp"
#include "../Http/Server.hpp"
namespace cpv {
/**
* The base class of modules.
* A module will setup with following calls in order:
* - registerServices
* - initializeServices
* - registerRoutes
*/
class Module {
public:
/** Register services to dependency injection container, do nothing by default */
virtual seastar::future<> registerServices(Container& container);
/** Initialize registered services, do nothing by default */
virtual seastar::future<> initializeServices(const Container& container);
/** Register http handlers for http server, do nothing by default */
virtual seastar::future<> registerRoutes(
const seastar::shared_ptr<const Container>& container,
httpd::http_server& server);
/** Constructor */
explicit Module(const seastar::shared_ptr<const Json>& configuration);
/** Virtual destructor */
virtual ~Module() = default;
protected:
seastar::shared_ptr<const Json> configuration_;
};
}
|
2803c2709d41d45e4d20b13dc839a6700d0aaf80 | 8c28894a71e70f5c86edbbd073c658f7bcd9acba | /src/ln.cpp | 0e30afed5727eb19cd96688cf4ccf25cac20c0fb | [
"MIT"
] | permissive | jodavaho/earth_coords | 1d142962964f3afe7e812e2b543b02a1b6f4c1ca | f964f5e85749eb3a0ab5170bd6b15a871ecf6b27 | refs/heads/master | 2016-09-03T06:58:05.007990 | 2015-02-16T18:33:32 | 2015-02-16T18:33:32 | 30,881,991 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,602 | cpp | ln.cpp | /*
* earconverter.cpp
*
* Created on: Mar 26, 2011
* Author: joshua
*/
#include "EarthCoords/EarthCoords.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char** argv){
if (argc<8){
printf("use as:\n\tlineup <home-lat> <home-lon> <pt1 lat> <pt1 lon> <pt2 lat> <pt2 lon> [more pairs] N\n" );
return -1;
}
RSN::EarthCoords e;
e.setHome(atof(argv[1]),atof(argv[2]));
int npts = (argc - 4)/2;
int nlegs = npts - 1;
int N = atoi(argc[argv-1]);
double * d = new double[nlegs];
double * dx = new double[nlegs];
double * dy = new double[nlegs];
double * ptx = new double[npts];
double * pty = new double[npts];
double sum=0;
for (int i=1;i<=npts;i++){
ptx[i-1] = atof(argv[1+2*i]);
pty[i-1] = atof(argv[2+2*i]);
}
for (int i=0;i<nlegs;i++){
double cdx = ptx[i+1] - ptx[i];
double cdy = pty[i+1] - pty[i];
d[i] = pow(ptx[i+1]-ptx[i],2) + pow(pty[i+1]-pty[i],2);
d[i] = sqrt(d[i]);
dx[i] = cdx;
dy[i] = cdy;
sum+=d[i];
//printf("%f, %f -> %f, %f dl= %f,%f d=%f \n",ptx[i],pty[i],ptx[i+1],pty[i+1],dx[i],dy[i],d[i]);
}
double inc = sum/N;
//printf("%d\n",nlegs);
for (int seg=0;seg<nlegs;seg++){
int n = floor(d[seg]/inc);
double offset = d[seg] - n*inc;
double xo,yo;
if (dy[seg]==0){yo = 0;xo = offset/2;}
else if (dx[seg]==0){xo = 0;yo = offset/2;}
else {
xo = offset/2 * dy[seg]/dx[seg];
yo = offset/2 * dx[seg]/dy[seg];
}
for (int i=0;i<n;i++){
double z,a;
e.getLocalCords(xo+ptx[seg]+i*dx[seg]/n,yo+pty[seg]+i*dy[seg]/n,z,a);
printf("%f %f\n",z,a);
}
}
printf("\n");
return 0;
}
|
81e52a06a417214d96205362061d3133ffb20b49 | 2c15a21c15a184e99d1735f2ddc16d7dad2bd314 | /src/BombField.h | 8562a85d501e1131379dfc5bccf69bebec11b9d3 | [] | no_license | vitaliyshlyahovchuk/4-Elements-Test | 793142efeea907c08ea4e1c5c897ca71d035a0f5 | 9c86e640c17d3357ec80eea164c463cd62ddb696 | refs/heads/master | 2020-04-09T07:32:30.382959 | 2014-08-17T12:33:19 | 2014-08-17T12:33:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,456 | h | BombField.h | #ifndef ONCE_BOMB_FIELD_CLASS
#define ONCE_BOMB_FIELD_CLASS
class BombField
{
private:
IPoint _position; // координаты левого нижнего угла бомбы в ячейках поля
Render::Texture *_texture;
Render::Texture *_textureUp;
EffectsContainer _effCont;
ParticleEffect *_eff;
IPoint _textureDelta;
typedef enum {
HIDE = 0,
WAIT,
WAIT_FOR_BOOM,
ACTIVATE
} State;
State _state;
float _deathTimer; // жуууудкий таймер =)
float _boomTimer; // взрывоопаcный таймер
bool _visible;
float _pauseBang;
public:
int bangRadius;
bool selected; //выбрана
public:
BombField();
void Draw();
void Update(float dt);
void Reset();
void Save(Xml::TiXmlElement *root);
void Load(rapidxml::xml_node<> *root);
void SetPosition(const IPoint& point);
IPoint GetPosition() const;
// Эти функции иcпользуютcя только в редакторе
bool Editor_CaptureBomb(const IPoint& mouse_pos, int x, int y);
void StartBang(bool explode);
void IncBangRadius(int delta = 1);
void UpdateVisible();
bool CheckActivateZone();
bool CheckActivateZone(const IPoint &pos);
typedef boost::shared_ptr<BombField> HardPtr;
};
class BombFields
{
private:
typedef std::vector<BombField::HardPtr> BombFieldVector;
BombFieldVector _allBombs; // Спиcок вcех бомб, которые еcть на уровне
BombFieldVector _clipboard;
// Эти для редактора
BombField *_dragBomb;
BombField *_selectedBomb;
IPoint _startDragPos;
public :
BombFields();
~BombFields();
void Reset();
void Clear();
void Draw();
void Update(float dt);
void UpdateVisibility();
void AddBomb(BombField::HardPtr bomb);
void IncBangRadius(int delta);
void Editor_MoveBomb(const IPoint& mouse_pos, int x, int y);
bool Editor_CaptureBomb(const IPoint& mouse_pos, int x, int y);
bool Editor_CheckRemove(const IPoint& mouse_pos, int x, int y);
void Editor_ReleaseBomb();
bool Editor_RemoveUnderMouse(const IPoint& mouse_pos, int x, int y);
void Editor_CutToClipboard(IRect part);
bool Editor_PasteFromClipboard(IPoint pos);
void SaveLevel(Xml::TiXmlElement *root);
void LoadLevel(rapidxml::xml_node<> *root);
void GetBombInPoint(const IPoint &pos, std::vector<BombField::HardPtr> &bombs);
void StartBang(const IPoint &pos, bool explode = true);
};
namespace Gadgets
{
extern BombFields bombFields;
}
#endif |
fc4918a7f091aec1292bd65bd0d7bdabc70e7562 | e1882a0adb6903245f7fd34b1d9d6ff4cc325a8e | /uegui/CarInfoHook.cpp | 25c1d168ee2439f6d95272be07c1412d66fbf171 | [] | no_license | treejames/navi | 684d8d16303b98d5d4912f54ecb4324b1618cfe1 | 32c4a00dfd5f8d30294378127f2da18278124d55 | refs/heads/master | 2017-12-04T21:07:51.776645 | 2013-08-22T13:22:37 | 2013-08-22T13:22:37 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 8,630 | cpp | CarInfoHook.cpp | #include "CarInfoHook.h"
//using namespace UeGui;
#include "InputHook.h"
#include "uebase\pathconfig.h"
namespace UeGui
{
CCarInfoHook::CCarInfoHook():m_pathBasic(CPathBasic::Get())
{
/*TCHAR path[301]={0, };
m_pathBasic.GetModulePath(path,300);
tstring dataPath = path;
m_filename = dataPath + _T("\\attrs\\carinfo.db");*/
m_filename = CPathConfig::GetCommonPath(CPathConfig::CPK_AttrsPath);
//m_pathBasic.GetPathSeperator(m_filename);
m_filename += _T("carinfo.db");
getCarInfoFromFile();
}
CCarInfoHook::~CCarInfoHook()
{
m_elements.clear();
m_ctrlNames.clear();
m_imageNames.clear();
}
bool CCarInfoHook::getCarInfoFromFile(void)
{
HANDLE handleRead;
// 文件存在则打开,不存在则创建
handleRead=::CreateFile(m_filename.c_str(),GENERIC_READ,0,
NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
if (INVALID_HANDLE_VALUE==handleRead)
{
return false;
}
//读取数据
if (GetFileSize(handleRead,NULL)==sizeof(CarInfoData))
{
int irealRWSize=0;
SetFilePointer(handleRead,0,0,FILE_BEGIN);
if ( !(ReadFile(handleRead,&m_carInfoData,sizeof(m_carInfoData),(LPDWORD)&irealRWSize,NULL)) )
{
return false;
}
}
//关闭文件
CloseHandle(handleRead);
return true;
}
bool CCarInfoHook::saveCarInfoToFile(void)
{
HANDLE handleWrite;
// 总是新建
handleWrite=::CreateFile(m_filename.c_str(),GENERIC_WRITE,0,
NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
if (INVALID_HANDLE_VALUE==handleWrite)
{
return false;
}
//更新文件
int irealRWSize=0;
SetFilePointer(handleWrite,0,0,FILE_BEGIN);
if ( !(WriteFile(handleWrite,&m_carInfoData,sizeof(m_carInfoData),(LPDWORD)&irealRWSize,NULL)) )
{
return false;
}
//关闭文件
CloseHandle(handleWrite);
return true;
}
void CCarInfoHook::MakeGUI()
{
FetchWithBinary();
MakeNames();
MakeControls();
}
void CCarInfoHook::ShowCarInfo()
{
//从文件读取信息
getCarInfoFromFile();
//显示
::sprintf((char *)m_editMid1Ctrl.GetCenterElement()->m_label,
(char *)m_carInfoData.carLicence);
::sprintf(m_editMid2Ctrl.GetCenterElement()->m_label,"%.2f 米",m_carInfoData.width);
::sprintf(m_editMid3Ctrl.GetCenterElement()->m_label,"%.2f 米",m_carInfoData.height);
::sprintf(m_editMid4Ctrl.GetCenterElement()->m_label,"%.2f 吨",m_carInfoData.weight);
}
//item是 你在输入面板输入的字符串
void CCarInfoHook::GetInputs(const char* item)
{
switch(m_Rowtag)
{
case CarInfoHook_EditBgk1:
{
::sprintf( (char *)m_carInfoData.carLicence, item );
}
break;
case CarInfoHook_EditBgk2:
{
m_carInfoData.width = atof(item);
}
break;
case CarInfoHook_EditBgk3:
{
m_carInfoData.height = atof(item);
}
break;
case CarInfoHook_EditBgk4:
{
m_carInfoData.weight = atof(item);
}
break;
}
//把item写入到文件中保存起来
saveCarInfoToFile();
ShowCarInfo();
}
void CCarInfoHook::callInputPanel(void* sender, const UeQuery::SQLRecord * data)
{
if (NULL == sender)
{
return;
}
CViewHook::m_curHookType = CViewHook::DHT_VehicleInformationHook;
CCarInfoHook* carinfohook = static_cast<CCarInfoHook*>(sender);
carinfohook->GetInputs(data->m_asciiName);
IView *view = IView::GetView();
view->RefreshUI();
}
short CCarInfoHook::MouseUp(CGeoPoint<short> &scrPoint)
{
short ctrlType = CAggHook::MouseUp(scrPoint);
switch(m_downElementType)
{
case CarInfoHook_EditBgk1: //车牌号
case CarInfoHook_EditBgk2: //宽
case CarInfoHook_EditBgk3: //高
case CarInfoHook_EditBgk4: //重
{
m_editBtnCtrl[m_downElementType-CarInfoHook_EditBgk1].MouseUp();
const static char* title[4]={"编辑车牌号","编辑车宽","编辑车高","编辑载重量"};
m_Rowtag = m_downElementType;
CInputHook::gotoCurInputMethod(
CInputHook::IM_Edit,
CViewHook::DHT_VehicleInformationHook,
this,
callInputPanel,
title[m_downElementType-CarInfoHook_EditBgk1] //标题
//m_editMid4Ctrl.GetCaption() //进入输入面板时的默认值
);
}
break;
case CarInfoHook_GotoMapBtn:
{
m_gotoMapBtnCtrl.MouseUp();
if(ctrlType == m_downElementType)
{
/*CViewHook::m_prevHookType=CViewHook::m_curHookType;
CViewHook::m_curHookType=CViewHook::DHT_MapHook;*/
CViewHook::GoToMapHook();
((CAggHook *)m_view->GetHook(CViewHook::DHT_MapHook))->ComeBack();
}
}
break;
case CarInfoHook_LogicBackBtn:
{
m_logicBackBtnCtrl.MouseUp();
if(ctrlType == m_downElementType)
{
/*CViewHook::m_prevHookType = CViewHook::DHT_VehicleInformationHook;
CViewHook::m_curHookType = CViewHook::DHT_TruckMainMenuHook;*/
CViewHook::ReturnPrevHook();
}
}
break;
default:
{
m_isNeedRefesh = false;
assert(false);
}
break;
}
if (m_isNeedRefesh)
{
this->Refresh();
}
m_isNeedRefesh = true;
return ctrlType;
}
short CCarInfoHook::MouseDown(CGeoPoint<short> &scrPoint)
{
short ctrlType = CAggHook::MouseDown(scrPoint);
switch(ctrlType)
{
case CarInfoHook_EditBgk1: //车牌号
case CarInfoHook_EditBgk2: //宽
case CarInfoHook_EditBgk3: //高
case CarInfoHook_EditBgk4: //重
{
m_editBtnCtrl[ctrlType-CarInfoHook_EditBgk1].MouseDown();
}
break;
case CarInfoHook_GotoMapBtn:
{
m_gotoMapBtnCtrl.MouseDown();
}
break;
case CarInfoHook_LogicBackBtn:
{
m_logicBackBtnCtrl.MouseDown();
}
break;
default:
{
m_isNeedRefesh = false;
assert(false);
}
break;
}
if (m_isNeedRefesh)
{
this->Refresh();
}
m_isNeedRefesh = true;
return ctrlType;
}
bool CCarInfoHook::operator ()()
{
return false;
}
void CCarInfoHook::MakeNames()
{
m_ctrlNames.erase(m_ctrlNames.begin(), m_ctrlNames.end());
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_BackGround, "BackGround"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_BGMenuText, "BGMenuText"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_GotoMapBtn, "GotoMapBtn"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_LogicBackBtn, "LogicBackBtn"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_labelTip1, "labelTip1"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_labelTip2, "labelTip2"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_LabelCarLicense, "LabelCarLicense"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_LabelCarWidth, "LabelCarWidth"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_LabelCarHeight, "LabelCarHeight"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_LabelCarWeight, "LabelCarWeight"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_EditLeft1, "EditLeft1"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_EditMid1, "EditMid1"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_EditLeft2, "EditLeft2"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_EditMid2, "EditMid2"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_EditLeft3, "EditLeft3"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_EditMid3, "EditMid3"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_EditLeft4, "EditLeft4"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_EditMid4, "EditMid4"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_EditBgk1, "EditBgk1"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_EditBgk2, "EditBgk2"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_EditBgk3, "EditBgk3"));
m_ctrlNames.insert(GuiName::value_type(CarInfoHook_EditBgk4, "EditBgk4"));
}
void CCarInfoHook::MakeControls()
{
m_bGMenuTextCtrl.SetCenterElement(GetGuiElement(CarInfoHook_BGMenuText));
m_backGroundCtrl.SetCenterElement(GetGuiElement(CarInfoHook_BackGround));
m_editLeft1Ctrl.SetCenterElement(GetGuiElement(CarInfoHook_EditLeft1));
m_editLeft2Ctrl.SetCenterElement(GetGuiElement(CarInfoHook_EditLeft2));
m_editLeft3Ctrl.SetCenterElement(GetGuiElement(CarInfoHook_EditLeft3));
m_editLeft4Ctrl.SetCenterElement(GetGuiElement(CarInfoHook_EditLeft4));
m_editMid1Ctrl.SetCenterElement(GetGuiElement(CarInfoHook_EditMid1));
m_editMid2Ctrl.SetCenterElement(GetGuiElement(CarInfoHook_EditMid2));
m_editMid3Ctrl.SetCenterElement(GetGuiElement(CarInfoHook_EditMid3));
m_editMid4Ctrl.SetCenterElement(GetGuiElement(CarInfoHook_EditMid4));
m_gotoMapBtnCtrl.SetCenterElement(GetGuiElement(CarInfoHook_GotoMapBtn));
m_logicBackBtnCtrl.SetCenterElement(GetGuiElement(CarInfoHook_LogicBackBtn));
// m_labelTip1Ctrl.SetCenterElement(GetGuiElement(CarInfoHook_labelTip1));
// m_labelTip2Ctrl.SetCenterElement(GetGuiElement(CarInfoHook_labelTip2));
for (int i=0;i<4;i++)
{
m_editBtnCtrl[i].SetCenterElement(GetGuiElement(CarInfoHook_EditBgk1+i));
}
m_bGMenuTextCtrl.SetCaption("车辆信息");
ShowCarInfo();
}
}
|
1ac59b507a1268ead94aa155df0055de16911f2b | 111c3ebecfa9eac954bde34b38450b0519c45b86 | /SDK_Perso/include/UserInterface/Include/SliderButton.h | 881dfaccefd97e7facdb50b66629a47598093231 | [] | no_license | 1059444127/NH90 | 25db189bb4f3b7129a3c6d97acb415265339dab7 | a97da9d49b4d520ad169845603fd47c5ed870797 | refs/heads/master | 2021-05-29T14:14:33.309737 | 2015-10-05T17:06:10 | 2015-10-05T17:06:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,029 | h | SliderButton.h | #ifndef __USERINTERFACE_SLIDERBUTTON_H__
#define __USERINTERFACE_SLIDERBUTTON_H__
#include "Static.h"
struct USERINTERFACE_EXPORT_IMPORT_SPECIFICATOR SliderButtonParameters : public StaticParameters
{
public:
SliderButtonParameters(int preset = 0);
//Хранитель ресурсов
RESOURCEKEEPER_DEFAULTRESOURCEFILE_H(SliderButtonParameters)
virtual void serialize(Serializer &);
typedef StaticParameters Base;
void read(const char*, int);
bool useFromTo;
float fromCoordinate;
float toCoordinate;
bool usePositions;
double minPosition;
double maxPosition;
bool usePosition;
int position;
int minSize;
bool verticalDir;
};
class USERINTERFACE_EXPORT_IMPORT_SPECIFICATOR SliderButton : public Static
{
public:
typedef Static Base;
typedef SliderButtonParameters Parameters;
private:
DECLARE_MESSAGE_TABLE()
private:
//Служебные переменные
double pointsPerPos; //На сколько точек должен сместиться курсор, чтобы сместить слайдер на одну позицию
float posOnSlider; //На каком расстоянии от края слайдера нажали
//Оформление
void thisArrange(const SliderButtonParameters& prms);
protected:
//Параметры
//Настраиваемые
float fromCoordinate;
float toCoordinate;
double minPosition;
double maxPosition;
//Параметры
//Ненастраиваемые
float minSize; //минимальный размер
float fixedSize; //Если больше нуля, то имеет фиксированный размер, если нет, то изменяет размер
float pixelsPerString; //на сколько пикселей уменьшается размер при увеличинии количества невидимых строк на 1
//Состояние
double position;
//Инициализация
void init();
//Реакция на события
void onLButtonDown(int keys, int x, int y);
void onLButtonUp(int keys, int x, int y);
void onMouseMove(int keys, int x, int y);
void onPaint();
void onMove(int dx, int dy);
void onSetFocus(Control* losingFocus);
void onKillFocus(Control* reseivingFocus);
void onCreate(SliderButtonParameters* prms);
void onClose();
void onStyleChanging(bool deselect, int newStyle);
public:
SliderButton(const Parameters&);
//Конструкторы
SliderButton(int tag,
float x = 0.f, float y = 0.f,
float X = 0.f, float Y = 0.f);
virtual ~SliderButton();
//Настройка параметров
void setPositionRange(double minPos = 0,
double maxPos = 0,
bool onFitSliderSize = true);
double getMinPosition() const {return minPosition;}
double getMaxPosition() const {return maxPosition;}
void setScrollRange(float fromCoord,
float toCoord,
bool onFitSliderSize = true);
float getFromCoordinate(){return fromCoordinate;}
float getToCoordinate(){return toCoordinate;}
void getXYofPos(double pos, float *x, float *y);
virtual void setCoordinates(float rx, float ry, float rX, float rY);
virtual void shift(float dx, float dy);
void shiftFromToCoordinates(float dx, float dy);
//Управление состоянием
void setPosition(double inPos, bool inParentNotify = true);
double getPosition() const {return position;}
void fitSliderSize();
int getFixedSize() const {return (int)fixedSize;}
void setFixedSize(int size = 0);
//Оформление
void arrange(const Parameters& prms);
void arrange(const ed::string& name) NAMEARRANGE(Parameters)
};
#endif // __USERINTERFACE_SLIDERBUTTON_H__ |
ef27bfddb694b0f8db1217f0c0986f0fb0771fdc | a1aa572aafbec8cc651be49342732126e54df085 | /bab3_doublelinkedlist/main.cpp | 79f424cd57ffa5c9cbb8d837b46ccaab6649c75d | [] | no_license | poncoe/datastructure_cpp_basic | c5a86bd5575645d8f59945767f54cdcb02b37dd5 | a64fd3fb20f75d9f2bc1747242435a67662870d4 | refs/heads/master | 2020-04-18T09:05:31.080488 | 2019-03-23T18:40:41 | 2019-03-23T18:40:41 | 167,422,048 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,481 | cpp | main.cpp | #include <iostream>
#include <stdlib.h>
#include "doublelist.h"
#include "bonus.h"
using namespace std;
int main() {
List L;
address P, Prec;
infotype X, Y;
cout<<endl;
cout<<"1a. Test the given project: Allocation and Deallocation"<<endl;
X = 'A';
P = allocate(X);
cout<<" print X = "<<X<<endl;
cout<<" P = allocate(X)"<<endl;
cout<<" print info(P) = "<<info(P)<<endl;
cout<<" print address of the element P = "<<P<<endl;
cout<<""<<endl;
cout<<" [press enter to continue]"<<endl;
cin.get();
cout<<" deallocate(P)"<<endl;
deallocate(P);
/** cout<<" print info(P) = "<<info(P)<<endl; // this will cause error */
cout<<" print address of the element P = "<<P<<endl;
cout<<" [press enter to continue]"<<endl;
cin.get();system("cls");
cout<<endl;
cout<<"1b. Test the given project: Create List and Print Info"<<endl;
createList(L);
cout<<" Test Print Info of the List L"<<endl;
printInfo(L);
cout<<" you can modify the printInfo(List L) procedure to show some message"<<endl
<<" when the list is empty"<<endl;
cout<<" [press enter to continue]"<<endl;
cin.get();system("cls");
cout<<endl;
cout<<"2. Test the procedure insertFirst(List &L, address P)"<<endl;
createList(L);
cout<<" Initial List is [empty]: "; printInfo(L);
cout<<endl;
cout<<" Insert First info = L"<<endl;
insertFirst(L, allocate('L'));
cout<<" The list should be : L, "<<endl;
cout<<" Your list : "; printInfo(L);
cout<<endl;
cout<<" Insert First info = M"<<endl;
insertFirst(L, allocate('M'));
cout<<" The list should be : M, L, "<<endl;
cout<<" Your list : "; printInfo(L);
cout<<endl;
cout<<" Insert First info = I"<<endl;
insertFirst(L, allocate('I'));
cout<<" The list should be : I, M, L, "<<endl;
cout<<" Your list : "; printInfo(L);
cout<<endl;
cout<<" Insert First info = S"<<endl;
insertFirst(L, allocate('S'));
cout<<" The list should be : S, I, M, L, "<<endl;
cout<<" Your list : "; printInfo(L);
cout<<" [press enter to continue]"<<endl;
cin.get();system("cls");
cout<<endl;
cout<<"3. Test the function findElement(List L, infotype x)"<<endl;
cout<<" Initial List: "; printInfo(L);
cout<<endl;
cout<<" Find Element = S"<<endl;
P = findElement(L, 'S');
cout<<" The info(P) should be : S "<<endl;
cout<<" Your info(P) : "<<info(P)<<endl;
cout<<" The address P should be : "<<first(L)<<endl;
cout<<" Your address P : "<<P<<endl;
cout<<endl;
cout<<" Find Element = M"<<endl;
P = findElement(L, 'M');
cout<<" The info(P) should be : M "<<endl;
cout<<" Your info(P) : "<<info(P)<<endl;
cout<<" The address P should be : "<<prev(last(L))<<endl;
cout<<" Your address P : "<<P<<endl;
cout<<endl;
cout<<" Find Element = X"<<endl;
P = findElement(L, 'X');
cout<<" The address P should be : 0"<<endl;
cout<<" Your address P : "<<P<<endl;
cout<<endl;
cout<<" [press enter to continue]"<<endl;
cin.get();system("cls");
cout<<endl;
cout<<"4. Test the procedure insertAfter(List &L, address Prec, address P)"<<endl;
cout<<" ** You might get an error at this point **"<<endl;
cout<<" ** think hard why it happened, then ask your TAs **"<<endl<<endl;
cout<<" Initial List: "; printInfo(L);
cout<<endl;
cout<<" Find Element = L"<<endl;
Prec = findElement(L, 'L');
cout<<" Info(Prec) should be : L"<<endl;
cout<<" Your Info(Prec) : "<<info(Prec)<<endl;
cout<<" Insert After Prec with info = E"<<endl;
insertAfter(L, Prec, allocate('E'));
cout<<" The list should be : S, I, M, L, E, "<<endl;
cout<<" Your list : "; printInfo(L);
cout<<endl;
cout<<" Find Element = M"<<endl;
Prec = findElement(L, 'M');
cout<<" Info(Prec) should be : M"<<endl;
cout<<" Your Info(Prec) : "<<info(Prec)<<endl;
cout<<" Insert After Prec with info = P"<<endl;
insertAfter(L, Prec, allocate('P'));
cout<<" The list should be : S, I, M, P, L, E, "<<endl;
cout<<" Your list : "; printInfo(L);
cout<<endl;
cout<<" [press enter to continue]"<<endl;
cin.get();system("cls");
cout<<endl;
cout<<"4. Test the procedure insertAfter(List &L, address Prec, address P) [Cont'd]"<<endl;
cout<<" Initial List: "; printInfo(L);
cout<<endl;
cout<<" Find Element = O"<<endl;
Prec = findElement(L, 'O');
cout<<" Prec should be : 0"<<endl;
cout<<" Your Prec : "<<Prec<<endl;
cout<<" Insert After Prec with info = H"<<endl;
insertAfter(L, Prec, allocate('H'));
cout<<" The list should be : S, I, M, P, L, E, "<<endl;
cout<<" Your list : "; printInfo(L);
cout<<endl;
cout<<" [press enter to continue]"<<endl;
cin.get();system("cls");
cout<<endl;
cout<<"5. Test the procedure deleteLast(List &L, address &P)"<<endl;
cout<<" ** You might get an error at this point **"<<endl;
cout<<" ** think hard why it happened, then ask your TAs **"<<endl<<endl;
cout<<" Initial List: "; printInfo(L);
cout<<endl;
cout<<" Delete Last"<<endl; deleteLast(L, P);
cout<<" Info(P) should be : E"<<endl;
cout<<" Your Info(P) : "<<info(P)<<endl;
cout<<" The list should be : S, I, M, P, L, "<<endl;
cout<<" Your list : "; printInfo(L);
deallocate(P);
cout<<endl;
cout<<" [press enter to continue]"<<endl;
cin.get();system("cls");
cout<<endl;
cout<<"6. Test the procedure deleteAfter(List &L, address Prec, address &P)"<<endl;
cout<<" ** You might get an error at this point **"<<endl;
cout<<" ** think hard why it happened, then ask your TAs **"<<endl<<endl;
cout<<" Initial List: "; printInfo(L);
cout<<endl;
cout<<" Find Element = I"<<endl;Prec = findElement(L, 'I');
cout<<" Info(Prec) should be : I"<<endl;
cout<<" Your Info(Prec) : "<<info(Prec)<<endl;
cout<<" Delete After"<<endl;deleteAfter(L, Prec, P);
cout<<" Info(P) should be : M"<<endl;
cout<<" Your Info(P) : "<<info(P)<<endl;
cout<<" The list should be : S, I, P, L, "<<endl;
cout<<" Your list : "; printInfo(L);
deallocate(P);
cout<<endl;
cout<<" Find Element = P"<<endl;Prec = findElement(L, 'P');
cout<<" Info(Prec) should be : P"<<endl;
cout<<" Your Info(Prec) : "<<info(Prec)<<endl;
cout<<" Delete After"<<endl;deleteAfter(L, Prec, P);
cout<<" Info(P) should be : L"<<endl;
cout<<" Your Info(P) : "<<info(P)<<endl;
cout<<" The list should be : S, I, P, "<<endl;
cout<<" Your list : "; printInfo(L);
deallocate(P);
cout<<endl;
cout<<" [press enter to continue]"<<endl;
cin.get();system("cls");
cout<<endl;
cout<<"6. Test the procedure deleteAfter(List &L, address Prec, address &P) [Cont'd]"<<endl;
cout<<" Initial List: "; printInfo(L);
cout<<endl;
cout<<" Find Element = P"<<endl;Prec = findElement(L, 'P');
cout<<" Info(Prec) should be : P"<<endl;
cout<<" Your Info(Prec) : "<<info(Prec)<<endl;
cout<<" Delete After"<<endl;deleteAfter(L, Prec, P);
cout<<" The list should be : S, I, P, "<<endl;
cout<<" Your list : "; printInfo(L);
cout<<endl;
cout<<" Find Element = A"<<endl;Prec = findElement(L, 'A');
cout<<" Prec should be : 0"<<endl;
cout<<" Your Prec : "<<Prec<<endl;
cout<<" Delete After"<<endl;deleteAfter(L, Prec, P);
cout<<" The list should be : S, I, P, "<<endl;
cout<<" Your list : "; printInfo(L);
deallocate(P);
cout<<endl;
cout<<" Find Element = S"<<endl;Prec = findElement(L, 'S');
cout<<" Prec should be : S"<<endl;
cout<<" Your Prec : "<<info(Prec)<<endl;
cout<<" Delete After"<<endl;deleteAfter(L, Prec, P);
cout<<" Info(P) should be : I"<<endl;
cout<<" Your Info(P) : "<<info(P)<<endl;
cout<<" The list should be : S, P, "<<endl;
cout<<" Your list : "; printInfo(L);
deallocate(P);
cout<<endl;
cout<<" [press enter to continue]"<<endl;
cin.get();system("cls");
cout<<endl;
cout<<"5. Test the procedure deleteLast(List &L, address &P) [Cont'd]"<<endl;
cout<<" Initial List: "; printInfo(L);
cout<<endl;
cout<<" Delete Last"<<endl; deleteLast(L, P);
cout<<" Info(P) should be : P"<<endl;
cout<<" Your Info(P) : "<<info(P)<<endl;
cout<<" The list should be : S, "<<endl;
cout<<" Your list : "; printInfo(L);
deallocate(P);
cout<<endl;
cout<<" Delete Last"<<endl; deleteLast(L, P);
cout<<" Info(P) should be : S"<<endl;
cout<<" Your Info(P) : "<<info(P)<<endl;
cout<<" The list should be : [empty] "<<endl;
cout<<" Your list : "; printInfo(L);
deallocate(P);
cout<<endl;
cout<<" Delete Last"<<endl; deleteLast(L, P);
cout<<" The list should be : [empty] "<<endl;
cout<<" Your list : "; printInfo(L);
cout<<endl;
cout<<" [press enter to continue]"<<endl;
cin.get();system("cls");
cout<<endl;
cout<<endl;
cout<<"BONUS: Find Biggest"<<endl;
cout<<"examine the provided findBiggest procedure, and observe the result below"<<endl;
createList(L);
insertFirst(L,allocate('T'));
insertFirst(L,allocate('A'));
insertFirst(L,allocate('D'));
insertFirst(L,allocate('K'));
insertFirst(L,allocate('U'));
insertFirst(L,allocate('R'));
insertFirst(L,allocate('T'));
insertFirst(L,allocate('S'));
List L1;
createList(L1);
insertFirst(L1,allocate('K'));
insertFirst(L1,allocate('I'));
insertFirst(L1,allocate('Y'));
insertFirst(L1,allocate('S'));
insertFirst(L1,allocate('A'));
cout<<" Initial List L1 : "; printInfo(L);
cout<<" Initial List L2 : "; printInfo(L1);
cout<<" Perform Find Biggest"<<endl;
cout<<" Found : ";findBiggest(L, L1);
cout<<" [press enter to continue]"<<endl;
cin.get();system("cls");
cout<<endl;
cout<<"BONUS: Insertion Sort"<<endl;
cout<<"examine the provided insertionSort procedure, and observe the result below"<<endl;
cout<<" Initial List: "; printInfo(L);
cout<<" Perform Insertion Sort"<<endl;
insertionSort(L);
cout<<" Sorted List : "; printInfo(L);
cout<<" [press enter to continue]"<<endl;
cin.get();system("cls");
cout<<endl;
cout<<"Reverse Half"<<endl;
cout<<"examine the provided reverseHalf procedure, and observe the result below"<<endl;
cout<<" Initial List : "; printInfo(L);
cout<<" Perform Reverse Half"<<endl;
reverseHalf(L);
cout<<" Reversed List : "; printInfo(L);
cout<<" [press enter to continue]"<<endl;
cin.get();system("cls");
cout<<endl;
return 0;
}
|
6bba512851c20bcafd9fd3ee3b8129312833a7f9 | 8209f14e1949031e0023a04ab366bb49817237a6 | /src/hud/key_display.h | fe8cf5418eae2428de85694ef8b58d71d126e8eb | [
"MIT"
] | permissive | WilliamLewww/Thane | 3fdb6220c603c4dd3b65ceaad77ef2e922427049 | c9fc1ea7780e51e78e3362670a08b1764843ed7e | refs/heads/master | 2021-01-20T07:15:37.438212 | 2019-02-08T04:35:06 | 2019-02-08T04:35:06 | 101,527,318 | 0 | 0 | MIT | 2018-08-30T18:16:27 | 2017-08-27T03:27:00 | C++ | UTF-8 | C++ | false | false | 425 | h | key_display.h | #pragma once
#include <vector>
#include "..\core\vector2.h"
#include "..\core\drawing.h"
#include "..\core\input.h"
struct DispayBox {
Vector2 position;
int width, height;
};
class KeyDisplay {
private:
std::vector<DispayBox> boxList;
float scale;
int alpha = 150;
int releaseColor[3] = { 130, 130, 130 };
int pressColor[3] = { 102, 153, 153 };
public:
KeyDisplay(Vector2 position, float scale);
void draw();
}; |
535da06f04eb87983fecdbd4dcaa89f2cc9a339e | 4d77397318bff9a25f8efd938e8199eda22e6cfa | /insersion_sort_list.cpp | 49b872c53d99f2c4ff4d129aeac452001f7bb98b | [] | no_license | lixinming913/c_plus_learning | f18e1d00861fa2117f4cc35985a5807ee4757725 | 8ffcd96c9ac4a1c8618cf7843b5e5899f529d2c6 | refs/heads/master | 2021-01-21T02:35:31.197861 | 2015-09-13T08:45:51 | 2015-09-13T08:45:51 | 38,868,602 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 943 | cpp | insersion_sort_list.cpp | /*
* Insertion Sort List
* Sort a linked list using insertion sort.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void swap(ListNode *p1, ListNode *p2) {
int temp = p1->val;
p1->val = p2->val;
p2->val = temp;
}
ListNode* insertionSortList(ListNode* head) {
if(!head || head->next == NULL)
return head;
ListNode* current = head;
ListNode* temp = head;
while(current != NULL) {
temp = head;
while(temp != current) {
if(current->val < temp->val)
swap(temp, current);
temp = temp->next;
}
current = current->next;
}
return head;
}
}; |
679479fb5a6535ffe3d22ca7713e0cc67f4d369e | 606191f87be112a987347cbc61c6d1870692160c | /modules/mysql/Handle/Statement.hpp | e49c4d0af8b17324e0f0388e0e0350cf9329a93a | [
"MIT"
] | permissive | dracc/VCMP-SqMod | 9ba692f57972120a04acc0c80b09113dad20fb2a | d3e6adea147f5b2cae5119ddd6028833aa625c09 | refs/heads/master | 2020-06-12T09:37:01.389364 | 2019-06-16T00:35:17 | 2019-06-16T00:35:17 | 194,260,084 | 0 | 0 | MIT | 2019-06-28T11:09:11 | 2019-06-28T11:09:11 | null | UTF-8 | C++ | false | false | 8,208 | hpp | Statement.hpp | #ifndef _SQMYSQL_HANDLE_STATEMENT_HPP_
#define _SQMYSQL_HANDLE_STATEMENT_HPP_
// ------------------------------------------------------------------------------------------------
#include "Handle/Connection.hpp"
#include "Base/Buffer.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* The structure that holds the data associated with a certain bind point.
*/
struct StmtBind
{
public:
// --------------------------------------------------------------------------------------------
typedef MYSQL_STMT Type; // The managed type.
// --------------------------------------------------------------------------------------------
typedef Type* Pointer; // Pointer to the managed type.
typedef const Type* ConstPtr; // Constant pointer to the managed type.
// --------------------------------------------------------------------------------------------
typedef Type& Reference; // Reference to the managed type.
typedef const Type& ConstRef; // Constant reference to the managed type.
// --------------------------------------------------------------------------------------------
typedef MYSQL_BIND BindType; // Database bind type.
typedef MYSQL_TIME TimeType; // Database time type.
typedef my_bool BoolType; // Database boolean type.
public:
// --------------------------------------------------------------------------------------------
BoolType mIsNull; // Allows the database to specify if the parameter is null.
BoolType mError; // Allows the database if errors occured on this parameter.
Buffer mData; // Buffer to store non fundamental data for the parameter.
BindType * mBind; // The associated database bind point handle.
TimeType mTime; // Structure used to store time data from database.
// --------------------------------------------------------------------------------------------
union
{
Uint64 mUint64; // Store unsigned integer values for the parameter.
Int64 mInt64; // Store signed integer values for the parameter.
Int32 mInt32[2]; // Store 32 bit signed integer values for the parameter.
Float64 mFloat64; // Store 32 bit floating point values for the parameter.
Float32 mFloat32[2]; // Store 64 bit floating point values for the parameter.
};
public:
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
StmtBind()
: mIsNull(0), mError(0), mData(), mBind(nullptr), mTime(), mUint64(0)
{
/* ... */
}
/* --------------------------------------------------------------------------------------------
* Copy constructor. (disabled)
*/
StmtBind(const StmtBind & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move constructor. (disabled)
*/
StmtBind(StmtBind && o) = delete;
/* --------------------------------------------------------------------------------------------
* Copy assignment operator. (disabled)
*/
StmtBind & operator = (const StmtBind & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move assignment operator. (disabled)
*/
StmtBind & operator = (StmtBind && o) = delete;
/* --------------------------------------------------------------------------------------------
* Retrieve the used buffer.
*/
CStr GetBuffer()
{
return mData ? mData.Data() : reinterpret_cast< CStr >(&mUint64);
}
/* --------------------------------------------------------------------------------------------
* Retrieve the buffer length.
*/
Ulong GetLength() const
{
return (mBind == nullptr) ? 0 : mBind->buffer_length;
}
/* --------------------------------------------------------------------------------------------
* Configure the input of a certain statement parameter.
*/
void SetInput(enum_field_types type, BindType * bind, CCStr buffer = nullptr, Ulong length = 0);
};
/* ------------------------------------------------------------------------------------------------
* The structure that holds the data associated with a certain statement handle.
*/
struct StmtHnd
{
public:
// --------------------------------------------------------------------------------------------
typedef MYSQL_STMT Type; // The managed type.
// --------------------------------------------------------------------------------------------
typedef Type* Pointer; // Pointer to the managed type.
typedef const Type* ConstPtr; // Constant pointer to the managed type.
// --------------------------------------------------------------------------------------------
typedef Type& Reference; // Reference to the managed type.
typedef const Type& ConstRef; // Constant reference to the managed type.
// --------------------------------------------------------------------------------------------
typedef MYSQL_BIND BindType; // Database bind type.
typedef MYSQL_TIME TimeType; // Database time type.
typedef my_bool BoolType; // Database boolean type.
public:
// --------------------------------------------------------------------------------------------
Pointer mPtr; // The managed statement handle.
// --------------------------------------------------------------------------------------------
Uint32 mErrNo; // Last received error string.
String mErrStr; // Last received error message.
// --------------------------------------------------------------------------------------------
Ulong mParams; // Number of parameters in the statement.
StmtBind * mBinds; // List of parameter binds.
BindType * mMyBinds; // List of parameter binds.
// --------------------------------------------------------------------------------------------
ConnRef mConnection; // Reference to the associated connection.
String mQuery; // The query string.
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
StmtHnd();
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~StmtHnd();
/* --------------------------------------------------------------------------------------------
* Grab the current error in the associated statement handle.
*/
void GrabCurrent();
/* --------------------------------------------------------------------------------------------
* Grab the current error in the associated statement handle and throw it.
*/
#if defined(_DEBUG) || defined(SQMOD_EXCEPTLOC)
void ThrowCurrent(CCStr act, CCStr file, Int32 line);
#else
void ThrowCurrent(CCStr act);
#endif // _DEBUG
/* --------------------------------------------------------------------------------------------
* Validate the associated statement handle and parameter index and throw an error if invalid.
*/
#if defined(_DEBUG) || defined(SQMOD_EXCEPTLOC)
void ValidateParam(Uint32 idx, CCStr file, Int32 line) const;
#else
void ValidateParam(Uint32 idx) const;
#endif // _DEBUG
/* --------------------------------------------------------------------------------------------
* Check whether a specific param index is within range.
*/
bool CheckParamIndex(Uint32 idx) const
{
return (idx < mParams);
}
/* --------------------------------------------------------------------------------------------
* Create the actual statement.
*/
void Create(const ConnRef & conn, CSStr query);
};
} // Namespace:: SqMod
#endif // _SQMYSQL_HANDLE_STATEMENT_HPP_
|
fcdac6d369b391b6f1b0e023fec79f8a1c563c38 | 96fccf32ca1f8995874a5ee862450323c69b23d2 | /token.cpp | 3a79fda552f19e8f5e5f0d15a2fa0faac17fba32 | [] | no_license | niceLemonGuy/Yellow_finals | 2def91cbd3acf603c93d8e833818e532ae562358 | 5f4f0549ee7d9c884a46f7dc2d7ff52f0e24a4de | refs/heads/master | 2022-11-07T02:14:49.981601 | 2020-07-01T19:44:02 | 2020-07-01T19:44:02 | 276,456,431 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 6,855 | cpp | token.cpp | #include "token.h"
#include <stdexcept>
using namespace std;
// Функция занимается делением строки из потока на кусоки "токены", с которыми удобно работать дальше
vector<Token> Tokenize(istream& cl) {
vector<Token> tokens; // Создаём вектор токенов для хранения распаршеного потока "строка - тип"
char c; // Создаём символьную переменную для посимвольного считывания
while (cl >> c) { // Считываем символы в цикле, пока поток не вернёт конец
if (isdigit(c)) { // Проверка на цифру. Если да, то работаем с датой
string date(1, c); // Создание строки из одного считанного символа, для набора символов для токена
for (int i = 0; i < 3; ++i) { // Дата разделена на три части
while (isdigit(cl.peek())) { // Пока следующий символ цифра - продолжаем
date += cl.get(); // Считываем из потока символ и добавляем в строку
}
if (i < 2) { // Если не третья часть даты, то заходем
date += cl.get(); // Добавляем стмвол '-'
}
}
tokens.push_back({date, TokenType::DATE}); // Добавляем в вектор токенов строку и тип токена
} else if (c == '"') { // Если считанный символ равен '"', значит это пример события для поиска
string event; // Создаём строку под считывание из потока
getline(cl, event, '"'); // Считываем из потока всё до слудующего символа '"'
tokens.push_back({event, TokenType::EVENT}); // Добавляем в вектор токенов строку и тип токена
} else if (c == 'd') { // Если считанный символ равен "d", значит это слово "date"
if (cl.get() == 'a' && cl.get() == 't' && cl.get() == 'e') { // Считывание и проверка остальных букв в слове "date"
tokens.push_back({"date", TokenType::COLUMN}); // Добавляем в вектор токенов строку и тип токена
} else { // Иначе в поток затесалоть некорректное выражение
throw logic_error("Unknown token"); // Кинуть исключение
}
} else if (c == 'e') { // Если считанный символ равен "e", значит это слово "event"
if (cl.get() == 'v' && cl.get() == 'e' && cl.get() == 'n' &&
cl.get() == 't') { // Считывание и проверка остальных букв в слове "event"
tokens.push_back({"event", TokenType::COLUMN}); // Добавляем в вектор токенов строку и тип токена
} else { // Иначе в поток затесалоть некорректное выражение
throw logic_error("Unknown token"); // Кинуть исключение
}
} else if (c == 'A') { // Если считанный символ равен "A", значит это слово "AND"
if (cl.get() == 'N' && cl.get() == 'D') { // Считывание и проверка остальных букв в слове "AND"
tokens.push_back({"AND", TokenType::LOGICAL_OP}); // Добавляем в вектор токенов строку и тип токена
} else { // Иначе в поток затесалоть некорректное выражение
throw logic_error("Unknown token"); // Кинуть исключение
}
} else if (c == 'O') { // Если считанный символ равен "O", значит это слово "OR"
if (cl.get() == 'R') { // Считывание и проверка остальных букв в слове "OR"
tokens.push_back({"OR", TokenType::LOGICAL_OP}); // Добавляем в вектор токенов строку и тип токена
} else { // Иначе в поток затесалоть некорректное выражение
throw logic_error("Unknown token"); // Кинуть исключение
}
} else if (c == '(') { // Если считанный символ равен "(", значит начало выражения
tokens.push_back({"(", TokenType::PAREN_LEFT}); // Добавляем в вектор токенов строку и тип токена
} else if (c == ')') { // Если считанный символ равен "(", значит конец выражения
tokens.push_back({")", TokenType::PAREN_RIGHT}); // Добавляем в вектор токенов строку и тип токена
} else if (c == '<') { // Если считанный символ равен "<"
if (cl.peek() == '=') { // Проверяем следующий символ, вдруг это оператор "<="
cl.get(); // Считываем символ
tokens.push_back({"<=", TokenType::COMPARE_OP}); // Добавляем "<="
} else {
tokens.push_back({"<", TokenType::COMPARE_OP}); // Добавляем "<"
}
} else if (c == '>') { // Если считанный символ равен ">"
if (cl.peek() == '=') { // Проверяем следующий символ, вдруг это оператор ">="
cl.get(); // Считываем символ
tokens.push_back({">=", TokenType::COMPARE_OP}); // Добавляем ">="
} else {
tokens.push_back({">", TokenType::COMPARE_OP}); // Добавляем ">"
}
} else if (c == '=') { // Если считанный символ равен "="
if (cl.get() == '=') { // Проверяем следующий символ, вдруг это оператор "=="
tokens.push_back({"==", TokenType::COMPARE_OP}); // Добавляем "=="
} else {
throw logic_error("Unknown token");
}
} else if (c == '!') {
if (cl.get() == '=') {
tokens.push_back({"!=", TokenType::COMPARE_OP});
} else { // Иначе в поток затесалоть некорректное выражение
throw logic_error("Unknown token"); // Кинуть исключениеs
}
}
}
return tokens;
}
|
10566a4388fe6e34ac3a7e95ade50fbe90344a62 | 5f85a0d7cc024ff0e6752378b95f0f7c5d6565cb | /C++学习/C++数据结构/实验五/源.cpp | 52cf04ebc43030e3ddf893a8c1cc79b9b537aae1 | [] | no_license | lskyo/school | 9060ce45411bdbd457a0b1def2582b7230742752 | 5eb9cc59c1021ea04a34b8bf10a42f0344598cbe | refs/heads/master | 2021-01-12T15:23:05.547248 | 2017-06-15T02:20:39 | 2017-06-15T02:20:39 | 71,765,365 | 3 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,153 | cpp | 源.cpp | #include <iostream>
#include <conio.h>
#include <cstdio>
#include <queue>
#include <stack>
#define MaxSize 100
#define DataType char
using namespace std;
class Node {
friend class BTree;
private:
Node *lChild; //左子树指针
Node *rChild; //右子树指针
public:
DataType data; //数据域,存储数据元素
//构造结点函数
Node(){
lChild = NULL;
rChild = NULL;
}
//构造结点函数
Node(DataType item, Node *left = NULL,Node *right = NULL){
data = item;
lChild = left;
rChild = right;
}
//析构函数
~Node(){}
};
//自定义函数,输出结点的数据域
void Visit(Node* p) {
cout<<p->data<<" ";
}
class BTree {
public:
BTree(); //构造函数
BTree(int No[],char data[],int n);//构造函数
void Create(int No[],char data[],int n); //创建二叉树
void PreOrder(Node* r,void Visit(Node*)); //先序遍历的递归算法
void InOrder(Node* r,void Visit(Node*)); //中序遍历的递归算法
void PostOrder(Node* r,void Visit(Node*)); //后序遍历的递归算法
void PreOrder1(Node* r,void Visit(Node*));//先序遍历的非递归算法
void LevelOrder(void Visit(Node*)); //层次遍历
int High(Node* bt); //求二叉树高度的递归算法
int NodeNum(Node* bt); // 求二叉树结点数目
int LeafNum(Node* bt); // 求二叉树叶结点数目
void Destroy(Node *r); // 撤消结点,释放空间
Node* getRoot(); //获取二叉树的根结点
void Print(Node* r,int level); //实现二叉树的凹入表形式打印
private:
Node* root;
};
//创建二叉树二叉链表
BTree::BTree() {
root = NULL;
}
Node* BTree::getRoot() {
return root;
}
// 已知二叉树的结点的层序编号序列,数据数列和结点数,建立此二叉树
void BTree::Create(int No[],char data[],int n) {
Node *to[100];
for(int i = 0; i < n; i++)
{
if(i == 0)
{
root = new Node(data[i]);
to[No[i]] = root;
}
else
{
int k = (No[i] - 1) / 2;
if(No[i]%2 == 0)
{
to[k]->rChild = new Node(data[i]);
to[No[i]] = to[k]->rChild;
}
else
{
to[k]->lChild = new Node(data[i]);
to[No[i]] = to[k]->lChild;
}
}
}
}
//二叉树先序遍历递归算法
void BTree::PreOrder(Node* r,void Visit(Node*)) {
if(r == NULL)
return;
cout << r->data << " ";
PreOrder(r->lChild,Visit);
PreOrder(r->rChild,Visit);
}
//二叉树中序遍历递归算法
void BTree::InOrder(Node* r,void Visit(Node*)) {
if(r == NULL)
return;
InOrder(r->lChild,Visit);
cout << r->data << " ";
InOrder(r->rChild,Visit);
}
//二叉树后序遍历 递归算法
void BTree::PostOrder(Node* r,void Visit(Node* )) {
if(r == NULL)
return;
PostOrder(r->lChild,Visit);
PostOrder(r->rChild,Visit);
cout << r->data << " ";
}
//二叉树先序遍历的非递归算法
void BTree::PreOrder1(Node* r,void Visit(Node*)) {
stack<Node*>sta;
sta.push(r);
while(!sta.empty())
{
Node* k = sta.top();
sta.pop();
cout << k->data << " ";
if(k->rChild != NULL)
sta.push(k->rChild);
if(k->lChild != NULL)
sta.push(k->lChild);
}
}
//利用队列完成对二叉树的层序遍历
void BTree::LevelOrder(void Visit(Node*)) {
queue<Node*>q;
q.push(root);
while(!q.empty())
{
Node* k = q.front();
q.pop();
cout << k->data << " ";
if(k->lChild != NULL)
q.push(k->lChild);
if(k->rChild != NULL)
q.push(k->rChild);
}
}
//求二叉树的高度,可使用递归算法
int BTree::High(Node* r) {
if(r == NULL)
return 0;
int ll = High(r->lChild) + 1;
int rr = High(r->rChild) + 1;
if(ll < rr)
return rr;
return ll;
}
//求二叉树结点数目,可使用递归算法
int BTree::NodeNum(Node* r) {
if(r == NULL)
return 0;
int ll = NodeNum(r->lChild);
int rr = NodeNum(r->rChild);
return ll + rr + 1;
}
//求二叉树叶结点数目,可使用递归算法
int BTree::LeafNum(Node* r) {
if(r == NULL)
return 0;
if(r->lChild == NULL && r->rChild == NULL)
return 1;
int ll = LeafNum(r->lChild);
int rr = LeafNum(r->rChild);
return ll + rr;
}
//r为打印的二叉树的根节点,level为该结点在整棵树中所在的层次
//完成二叉树的凹入表法打印
void BTree::Print(Node* r, int level) {
if(r == NULL)
return;
if(level == 1)
{
Print(r->rChild, level + 1);
cout << r->data << endl;
Print(r->lChild, level + 1);
return;
}
Print(r->rChild, level + 1);
for(int i = 1 ; i < level - 1; i++)
cout << " ";
cout << " ----"<<r->data << endl;
Print(r->lChild, level + 1);
}
void BTree::Destroy(Node *r) {
if(r ==NULL) return;
else {
if(r->lChild != NULL) Destroy(r->lChild);
if(r->rChild != NULL) Destroy(r->rChild);
cout << r->data << " "; //此语句只是为了方便测试
delete r;
}
}
int main()
{
int n,i;
int * No;//层序编号动态数组;
DataType *data;//结点数据动态数组;
cout<<"请输入结点数"<<endl;
cin>>n;
No=new int[n];
data=new char[n];
cout<<"请输入该结点的层序编号序列:";
for( i=0;i<n;i++)
cin>>No[i] ;
cout<<"请输入结点的数据序列:";
for( i=0;i<n;i++)
cin>>data[i];
BTree bt;
bt.Create(No,data,n); //创建二叉对
bt.Print(bt.getRoot(),1); //凹入表法打印打印二叉树
cout<<"先序遍历结果(递归):";
bt.PreOrder(bt.getRoot(),Visit); //正确调用成员函数
cout<<endl;
cout<<"先序遍历结果(非递归):";
bt.PreOrder1(bt.getRoot(),Visit); //正确调用成员函数
cout<<endl;
cout<<"中序遍历结果:";
bt.InOrder(bt.getRoot(),Visit); //正确调用成员函数
cout<<endl;
cout<<"后序遍历结果:";
bt.PostOrder(bt.getRoot(),Visit); //正确调用成员函数
cout<<endl;
cout<<"层序遍历结果:";
bt.LevelOrder(Visit); //正确调用成员函数
cout<<endl;
cout<<"二叉树的高度 = "<<bt.High(bt.getRoot())<<endl; //正确调用成员函数
cout<<"二叉树的结点数目 = "<<bt.NodeNum(bt.getRoot())<<endl; //正确调用成员函数
cout<<"二叉树的叶结点数目 = "<<bt.LeafNum(bt.getRoot())<<endl; //正确调用成员函数
cout<<"撤销二叉树,撤销次序:";
bt.Destroy(bt.getRoot()); //正确调用成员函数
getch();
}
|
3484f60bb4c9cddc2f2a33ccb42d4786596e0e9b | cd03e6f5b96fa70670df087b1daa551d07989a4a | /RStein.AsyncCpp/DataFlow/ActionBlock.h | 1da3569603021f882d15285732c982114e0cb902 | [
"MIT"
] | permissive | lineCode/Rstein.AsyncCpp | a2534733dd1ea6983351329b55ccdbfe9aea02c5 | 4ff60de5299d94b6ef031e31489a269bfb81a956 | refs/heads/master | 2022-06-24T18:31:04.010903 | 2020-05-07T20:25:59 | 2020-05-07T20:25:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,762 | h | ActionBlock.h | #pragma once
#include "../Detail/DataFlow/DataFlowBlockCommon.h"
#include <memory>
namespace RStein::AsyncCpp::DataFlow
{
template<typename TInputItem, typename TState = Detail::NoState>
class ActionBlock : public IInputBlock<TInputItem>,
public std::enable_shared_from_this<ActionBlock<TInputItem, TState>>
{
private:
using InnerDataFlowBlock = Detail::DataFlowBlockCommon<TInputItem, Detail::NoOutput, TState>;
using InnerDataFlowBlockPtr = typename InnerDataFlowBlock::DataFlowBlockCommonPtr;
public:
ActionBlock(typename InnerDataFlowBlock::AsyncActionFuncType actionFunc,
typename InnerDataFlowBlock::CanAcceptFuncType canAcceptFunc = [](const auto& _){ return true;}) :
IInputBlock<TInputItem>{},
std::enable_shared_from_this<ActionBlock<TInputItem, TState>>{},
_innerBlock{std::make_shared<InnerDataFlowBlock>([actionFunc](const TInputItem& inputItem, TState*& state) ->Tasks::Task<Detail::NoOutput>
{
co_await actionFunc(inputItem, state);
co_return Detail::NoOutput::Default();
},
canAcceptFunc)}
{
}
ActionBlock(//TODO: Avoid unused variable, ambiguous ctor
typename InnerDataFlowBlock::ActionFuncType actionFunc,
typename InnerDataFlowBlock::CanAcceptFuncType canAcceptFunc = [](const auto& _){ return true;}) :
IInputBlock<TInputItem>{},
std::enable_shared_from_this<ActionBlock<TInputItem, TState>>{},
_innerBlock{std::make_shared<InnerDataFlowBlock>([actionFunc](const TInputItem& inputItem, TState*& state)
{
actionFunc(inputItem, state);
return Detail::NoOutput::Default();
},
canAcceptFunc)}
{
}
ActionBlock(const ActionBlock& other) = delete;
ActionBlock(ActionBlock&& other) = delete;
ActionBlock& operator=(const ActionBlock& other) = delete;
ActionBlock& operator=(ActionBlock&& other) = delete;
virtual ~ActionBlock() = default;
[[nodiscard]] std::string Name() const override;
void Name(std::string name);
[[nodiscard]] typename IDataFlowBlock::TaskVoidType Completion() const override;
void Start() override;
void Complete() override;
void SetFaulted(std::exception_ptr exception) override;
bool CanAcceptInput(const TInputItem& item) override;
typename IDataFlowBlock::TaskVoidType AcceptInputAsync(const TInputItem& item) override;
typename IDataFlowBlock::TaskVoidType AcceptInputAsync(TInputItem&& item) override;
private:
InnerDataFlowBlockPtr _innerBlock;
};
template <typename TInputItem, typename TState>
std::string ActionBlock<TInputItem, TState>::Name() const
{
return _innerBlock->Name();
}
template <typename TInputItem, typename TState>
void ActionBlock<TInputItem, TState>::Name(std::string name)
{
_innerBlock->Name(name);
}
template <typename TInputItem, typename TState>
IDataFlowBlock::TaskVoidType ActionBlock<TInputItem, TState>::Completion() const
{
return _innerBlock->Completion();
}
template <typename TInputItem, typename TState>
void ActionBlock<TInputItem, TState>::Start()
{
_innerBlock ->Start();
}
template <typename TInputItem, typename TState>
void ActionBlock<TInputItem, TState>::Complete()
{
return _innerBlock->Complete();
}
template <typename TInputItem, typename TState>
void ActionBlock<TInputItem, TState>::SetFaulted(std::exception_ptr exception)
{
_innerBlock->SetFaulted(exception);
}
template <typename TInputItem, typename TState>
bool ActionBlock<TInputItem, TState>::CanAcceptInput(const TInputItem& item)
{
return _innerBlock->CanAcceptInput(item);
}
template <typename TInputItem, typename TState>
IDataFlowBlock::TaskVoidType ActionBlock<TInputItem, TState>::AcceptInputAsync(const TInputItem& item)
{
return _innerBlock->AcceptInputAsync(item);
}
template <typename TInputItem, typename TState>
IDataFlowBlock::TaskVoidType ActionBlock<TInputItem, TState>::AcceptInputAsync(TInputItem&& item)
{
return _innerBlock->AcceptInputAsync(item);
}
}
|
e2f4b77f55e58568dd64d4faa5113d9a636c66e5 | bcbc1645f58b5ff02e28f81d28b75d96c69917bf | /ccf/ccf201812-2.cpp | 30695bebede55a7521e66ed2e9af1d3e6c9cb764 | [] | no_license | bleuxr/C-Cplusplus_glance | 86f73dcd62573c4c85fac9a91349c051c2f8ead8 | 172b386af60cc607e2c7909dd6cd72860661fd4e | refs/heads/master | 2020-04-28T09:15:11.262353 | 2019-08-23T07:41:05 | 2019-08-23T07:41:05 | 175,160,858 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 598 | cpp | ccf201812-2.cpp | #include <iostream>
using namespace std;
typedef long long ll;
ll r,y,g;
ll add (ll k,ll t,ll time){
if(k==0) return t;
if(k==1)
t=r-t;
else if(k==2)
t=r+g+y-t;
else if(k==3)
t=r+g-t;
t=(t+time)%(r+g+y);
if(0<=t&&t<r)
return r-t;
else if(r<=t&&t<r+g+y)
return 0;
else if(r+g<=t&&t<r+g+y)
return (r+g+y-t+r);
}
int main(){
ll n,ans=0,k,t;
scanf("%lld%lld%lld%lld",&r,&y,&g,&n);
while(n--){
scanf("%lld%lld",&k,&t);
ans+=add(k,t,ans);
}
printf("%lld\n",ans);
return 0;
} |
5da8b6cb221908dac01e68c609230fec8240c19c | af1ca1da86f6601e7d9774dc164fd99095f64639 | /src/MobDist.cpp | aa58c310c10100d48b16c97f93862395022ccd61 | [] | no_license | pylgrym/basin | ba07751b98607900339113583f52ce0e07539501 | de067738c369c6f0dbdea752676ecf38952e583a | refs/heads/master | 2023-03-04T06:48:02.377659 | 2023-03-02T08:25:35 | 2023-03-02T08:25:35 | 30,758,171 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,265 | cpp | MobDist.cpp | #include "stdafx.h"
#include "MobDist.h"
#include <set>
#include "numutil/myrnd.h"
#include <assert.h>
#include <iomanip>
MobDist::MobDist()
{
}
MobDist::~MobDist()
{
}
bool MobRating::operator < (const MobRating& rhs) const {
if (rating != rhs.rating) { return rating < rhs.rating; }
return mobIx < rhs.mobIx;
}
class LevelRating {
public:
LevelRating() { ratingSum = 0.0; }
std::set< MobRating > mobs;
double ratingSum;
void addRating(const MobRating& r) { mobs.insert(r); }
void makeLevelSum() {
ratingSum = 0.0;
std::set< MobRating >::iterator i;
for (i = mobs.begin(); i != mobs.end(); ++i) {
ratingSum += (*i).rating;
}
}
CreatureEnum rndMob() {
assert(ratingSum != 0.0); // Means level has not been initialized.
double rndChoice = rnd::Rnd( (int) ratingSum);
double accum = 0.0;
std::set< MobRating >::iterator i;
for (i = mobs.begin(); i != mobs.end(); ++i) {
accum += (*i).rating;
if (rndChoice < accum) {
return (*i).mobIx;
}
}
return (CreatureEnum) (CR_MaxLimit - 1);
}
double mobRating(CreatureEnum mobIx) {
std::set< MobRating >::iterator i;
for (i = mobs.begin(); i != mobs.end(); ++i) {
const MobRating& mr = *i;
if (mr.mobIx == mobIx) {
double rate = mr.rating / ratingSum;
return rate;
}
}
return 0.0;
}
} ratings[MaxLevel + 1];
CreatureEnum MobDist::suggRndMob(int levelNum) {
assert(levelNum >= 0);
assert(levelNum <= MaxLevel);
LevelRating& level = ratings[levelNum];
CreatureEnum ctype = level.rndMob();
return ctype;
}
void MobDist::dump() {
std::ofstream os("mobstats.txt");
for (int i = CR_Kobold; i < CR_MaxLimit; ++i) { // We'll make rows for each mobb.
MobRating mr; mr.mobIx = (CreatureEnum)i;
const MobDef& def = Creature::mobDef(mr.mobIx);
os << def.desc << ";";
for (int L = 1; L < MaxLevel; ++L) { // Go through all levels.
LevelRating& level = ratings[L];
double rate = level.mobRating(mr.mobIx);
int intRate = int(rate * 1000.0 + 0.5);
double rounded = (intRate / 10.0);
if (rounded == 0.0) {
os << "-;";
} else {
os << std::fixed << std::setprecision(1) << rounded << ";";
}
}
os << std::endl;
}
}
void MobDist::enumTownLevel() {
LevelRating& level = ratings[0];
MobRating mr;
// Add fixed town level mobs:
mr.mobIx = CR_Kobold; mr.rating = 10; level.addRating(mr);
mr.mobIx = CR_Rat; mr.rating = 10; level.addRating(mr);
mr.mobIx = CR_Squirrel; mr.rating = 10; level.addRating(mr);
mr.mobIx = CR_Goblin; mr.rating = 10; level.addRating(mr);
level.makeLevelSum();
}
void MobDist::enumerate() {
const RatingNum MaxRating = 1000.0;
enumTownLevel();
for (int L = 1; L < MaxLevel; ++L) { // Go through all levels.
LevelRating& level = ratings[L];
for (int i = CR_Kobold; i < CR_MaxLimit; ++i) {
MobRating mr; mr.mobIx = (CreatureEnum)i;
const MobDef& def = Creature::mobDef(mr.mobIx);
int deltaL = (L - def.mlevel); // '+2' means 'mob is 2 levels lower' (and in the process of (slowly) fading out.)
// //, '-2' means 'mob is 2 above cur level' (and in the process of (abruptly) fading in.
mr.rating = 0;
if (deltaL >= 0) { // Above current level, we slowly fade out.
const int softFadeIn = 2; // Change this from zero to e.g. 2, to not fade in/out so abruptly (zero means 1000, 500,333,250.)
mr.rating = MaxRating / (deltaL + 1 + softFadeIn);
} else { // ( <0 ) // Below current level, we abruptly fade in (ie squared.)
int absDelta = -deltaL;
int squareDelta = (absDelta + 1); squareDelta = (squareDelta * squareDelta);
mr.rating = MaxRating / squareDelta;
const int hardFloor = -3; // We never allow high-level monsters more than 3 levels under intended level.
if (deltaL < hardFloor) { // (IE "no multihued ancient dragons on L1.")
mr.rating = 0; // Force it to zero.
}
}
// Now add this mob rating to cur Level.
if (mr.rating > 0) {
level.addRating(mr);
}
} // for mobs.
level.makeLevelSum();
} // for levels.
dump();
}
|
af48e14cc17e6ca06c8c849c291877484f72008d | 373f94a2d37db5374f05c215fe73528edde72c64 | /B - Lazy Student CodeForces.cpp | 92a9407db16025d5b201c89653811a4d94183e4f | [] | no_license | Nobel-ruettt/Poj | 101f55f00b5fb63bea25004b852abe131ac59965 | ede4fe53f54c807dc15973fcbe87aa4abb0e4c10 | refs/heads/master | 2022-01-16T06:45:25.572481 | 2019-07-16T11:09:12 | 2019-07-16T11:09:12 | 111,105,604 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,479 | cpp | B - Lazy Student CodeForces.cpp | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define sc(n) scanf("%lld",&n)
vector<ll>graph[1000];
ll visited[1000];
string ans;
vector<ll>ab;
vector<ll>c;
vector<ll>a;
vector<ll>b;
ll u,v,count_a,count_b,count_c;
int main()
{
ll n,m;
sc(n);sc(m);
for(ll i=1;i<=m;i++)
{
sc(u);
sc(v);
graph[u].push_back(v);
graph[v].push_back(u);
}
for(ll i=0;i<1000;i++)
{
ans.push_back('z');
}
for(ll i=1;i<=n;i++)
{
if(graph[i].size()==(n-1))
{
visited[i]=2;
ans[i]='b';
count_b++;
}
}
for(ll i=1;i<=n;i++)
{
if(visited[i]==0)
{
visited[i]=1;
ans[i]='a';
count_a++;
for(ll j=0;j<graph[i].size();j++)
{
ll adj=graph[i][j];
if(visited[adj]!=2)
{
visited[adj]=1;
ans[adj]='a';
count_a++;
}
}
break;
}
}
for(ll i=1;i<=n;i++)
{
if(visited[i]==0)
{
visited[i]=3;
ans[i]='c';
count_c++;
}
}
//cout<<count_a<<" "<<count_b<<" "<<count_c<<endl;
bool flag=0;
for(ll i=1;i<=n;i++)
{
if(visited[i]==1)
{
ll count1_a=0;
ll count1_b=0;
count1_a++;
for(ll j=0;j<graph[i].size();j++)
{
ll adj=graph[i][j];
if(visited[adj]==2)
{
count1_b++;
}
else if(visited[adj]==1)
{
count1_a++;
}
else if(visited[adj]==3)
{
flag=1;
}
}
if(flag==1)
{
break;
}
if(count1_a==count_a && count1_b==count_b)
{
continue;
}
flag=1;
break;
}
else if(visited[i]==2)
{
ll count1_a=0;
ll count1_b=0;
ll count1_c=0;
count1_b++;
for(ll j=0;j<graph[i].size();j++)
{
ll adj=graph[i][j];
if(visited[adj]==2)
{
count1_b++;
}
else if(visited[adj]==1)
{
count1_a++;
}
else if(visited[adj]==3)
{
count1_c++;
}
}
if(count1_a==count_a && count1_b==count_b && count1_c==count_c)
{
// cout<<"dhukse"<<endl;
continue;
}
flag=1;
break;
}
else if(visited[i]==3)
{
// cout<<i<<" : ";
// for(ll j=0;j<graph[i].size();j++)
// {
// cout<<graph[i][j]<<" ";
// }
// cout<<endl;
ll count1_b=0;
ll count1_c=0;
count1_c++;
for(ll j=0;j<graph[i].size();j++)
{
ll adj=graph[i][j];
if(visited[adj]==2)
{
count1_b++;
}
else if(visited[adj]==3)
{
count1_c++;
}
else if(visited[adj]==1)
{
flag=1;
}
}
if(flag==1)
{
break;
}
if(count1_b==count_b && count1_c==count_c)
{
continue;
}
flag=1;
break;
}
}
for(ll i=1;i<=n;i++)
{
if(ans[i]=='z')
{
flag=1;
break;
}
}
if(flag==1)
{
cout<<"No"<<endl;
}
else
{
cout<<"Yes"<<endl;
for(ll i=1;i<=n;i++)
{
cout<<ans[i];
}
cout<<endl;
}
return 0;
}
/*
5 8
1 2
1 4
1 5
2 4
4 5
2 5
2 3
5 3
*/
|
35258ca50d8975ead5a6fff61912e3dd3b47c768 | 79e897a9e762282bc5a9795dc8378355dc827f1a | /Module-cpp-04/ex01/RadScorpion.cpp | c4cff8a9749a6447a8b1c99f40fcfb8f882c3fc4 | [] | no_license | sphaxou/CPP-42 | 37a807c8c3799b93da681bec732ba0b6eab6777d | dee5653046d890737ffec93651696fb326a970aa | refs/heads/master | 2023-01-13T19:40:32.988592 | 2020-11-19T16:28:17 | 2020-11-19T16:28:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,565 | cpp | RadScorpion.cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* RadScorpion.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rchallie <rchallie@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/15 20:31:43 by rchallie #+# #+# */
/* Updated: 2020/10/14 00:20:01 by rchallie ### ########.fr */
/* */
/* ************************************************************************** */
#include "RadScorpion.hpp"
/*
** @brief Init contrcutor:
** The "Pony".
*/
RadScorpion::RadScorpion()
:
Enemy(
80,
"RadScorpion"
)
{
std::cout << "* click click click *" << std::endl;
}
/*
** @brief Copy:
** Copy the "Pony".
**
** @param copy the "Pony" to copy.
*/
RadScorpion::RadScorpion(const RadScorpion & copy)
:
Enemy(copy)
{}
/*
** @brief Destructor:
** Called when the object "Pony" is delete
*/
RadScorpion::~RadScorpion()
{
std::cout << "* SPROTCH *" << std::endl;
}
RadScorpion & RadScorpion::operator=(const RadScorpion& op)
{
if (this == &op)
return (*this);
Enemy::operator=(op);
return (*this);
} |
8e1ad9ca73c741a9f405a947b991f34ceb6fd0e1 | c177e885e4cfd03a928e2d15f5428bc4a41fdeb5 | /src/BattleState.hpp | faa45413923e1027fd073ed71a34739b0faf7965 | [] | no_license | BarresOusaid/Final-Fantasy | d97dcc7e3c3c7917cb0238a0190c6adaa91c05db | c3582b683329647c5a9ee90acbf59a9077565671 | refs/heads/master | 2016-09-03T07:11:26.164840 | 2016-01-15T08:00:13 | 2016-01-15T08:00:13 | 42,917,664 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 79 | hpp | BattleState.hpp | #ifndef BATTLESTATE__H
#define BATTLESTATE__H
#include "BattleState.h"
#endif |
14b05c3866f67f418044f80e300c27d78252f05e | e8db4eeab529af596d2761e20583ebf0603bb6e9 | /Charack/charack/move.cpp | 2f1df816ec423ee5711dc26a12978f4c88e3d807 | [] | no_license | gamedevforks/charack | 099c83fe64c076c126b1ea9212327cd3bd05b42c | c5153d3107cb2a64983d52ee37c015bcd7e93426 | refs/heads/master | 2020-04-11T04:18:57.615099 | 2008-10-29T13:26:33 | 2008-10-29T13:26:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,685 | cpp | move.cpp | #include "move.h"
void processNormalKeys(unsigned char key, int x, int y) {
switch(key) {
case 27:
exit(0);
break;
case 'w':
// Move forward
gCamera.moveForward();
/*
gCameraPosition.z = gCameraPosition.z + CK_CAMERA_MOV_SPEED*cos(DEG2RAD(360 - gRotY));
gCameraPosition.x = gCameraPosition.x + CK_CAMERA_MOV_SPEED*sin(DEG2RAD(360 - gRotY));
*/
break;
case 's':
// Move backward
gCamera.moveBackward();
/*
gCameraPosition.z = gCameraPosition.z - CK_CAMERA_MOV_SPEED*cos(DEG2RAD(360 - gRotY));
gCameraPosition.x = gCameraPosition.x - CK_CAMERA_MOV_SPEED*sin(DEG2RAD(360 - gRotY));
*/
break;
case 'a':
// Move left
gCamera.moveLeft();
/*
gCameraPosition.z = gCameraPosition.z + CK_CAMERA_MOV_SPEED*cos(DEG2RAD(90 - gRotY));
gCameraPosition.x = gCameraPosition.x + CK_CAMERA_MOV_SPEED*sin(DEG2RAD(90 - gRotY));
*/
break;
case 'd':
// Move right
gCamera.moveRight();
/*
gCameraPosition.z = gCameraPosition.z + CK_CAMERA_MOV_SPEED*cos(DEG2RAD(270 - gRotY));
gCameraPosition.x = gCameraPosition.x + CK_CAMERA_MOV_SPEED*sin(DEG2RAD(270 - gRotY));
*/
break;
case 'r':
// Olha para cima
gCamera.rotateLookUpDown(5);
//gRotX += CK_CAMERA_ROT_SPEED;
break;
case 'f':
// Olha para baixo
gCamera.rotateLookUpDown(-5);
//gRotX -= CK_CAMERA_ROT_SPEED;
break;
case 'q':
// Olha para esquerda
gCamera.rotateLookLeftRight(-5);
//gRotY -= CK_CAMERA_ROT_SPEED;
break;
case 'e':
// Olha para direita
gCamera.rotateLookLeftRight(5);
//gRotY += CK_CAMERA_ROT_SPEED;
break;
}
}
|
8fd03d053d36b4b1466423f04a8c77362d309dc6 | b357d3accff98e8a58dcfe57c4b328ed086e4544 | /TrainSimulation/TrainStation.h | e1ac8409905876158cb26ddb3331e2716b2092d5 | [
"MIT"
] | permissive | hlimbo/Train-Simulation | 8cb02b3a7e4d8e13cd7aabb4e1e3a0eb4ba98130 | 6373bfd2c099e68878250be76e1aa775348168f2 | refs/heads/master | 2021-05-07T09:32:14.729723 | 2017-11-05T22:51:51 | 2017-11-05T22:51:51 | 109,623,331 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,181 | h | TrainStation.h | #ifndef TRAIN_STATION
#define TRAIN_STATION
#include <vector>
#include <queue>
enum class StationStates { IDLE, BUSY };
class Train;
class Crew;
//The environment that trains and crew members arrive and depart from
class TrainStation
{
public:
Train* dockedTrain;
//Used to free up trains that haven't arrived in the queue due to the simulation ending.
std::queue<Train*> trainsToArriveQueue;
//Used to free up replacement crews that haven't arrived to their designated trains due to the simulation ending.
std::queue<Crew*> replacementCrews;
std::queue<Train*> trainLineQueue;
StationStates state;
float startIdleTime;
float startBusyTime;
float startHoggedOutTime;
float startHoggedOutTimeInQueue;
TrainStation();
~TrainStation();
Train* PopFromQueue();
void PushToQueue(Train* train);
Train* Front();
bool IsEmpty();
Train* getDockedTrain();
//called at the end of the simulation if any trains are still waiting in the queue.
void RemoveTrains();
//called at the end of the simulation if any replacment crews are scheduled to arrive past max simulation time.
void RemoveReplacementCrews();
};
#endif |
e9be127904d1201b6c9c233d4cd63b65a7db3f62 | 30a99c508a0076aaa59a1a616783b9eef8361080 | /BaekJoon/3273.cpp | 684bfaf393d82376e4dc84c747b64bfcf1da4b12 | [] | no_license | chanhk-im/Algorithm | 1c05254241e6dafedff75a8673a139afb62854db | d816a8bb00ce07e7f7b3f0769d6ec33737a68fe4 | refs/heads/master | 2023-05-11T14:50:19.694798 | 2023-05-04T11:14:41 | 2023-05-04T11:14:41 | 233,513,871 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 548 | cpp | 3273.cpp | #include <bits/stdc++.h>
using namespace std;
int n, x;
vector<int> arr(100005);
vector<int> num_cnt(2000005, 0);
int main()
{
cin.tie(NULL);
ios::sync_with_stdio(false);
int cnt = 0;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cin >> x;
for (int i = 0; i < n; i++) {
if (arr[i] <= x) {
if (num_cnt[x - arr[i]] > 0) {
cnt += num_cnt[x - arr[i]];
}
}
num_cnt[arr[i]]++;
}
cout << cnt << '\n';
return 0;
} |
499faa14dfb0b5fc504a7fc21c3ae16b61fba3fd | 8af5f737599e8c68ca7feb40b06d6eff47dfcff1 | /dbltab.cc | 80b4f654db71d00443eb63f40321c57b8a93b665 | [] | no_license | mondaugen/libcm | 49799d7650193e8a7dd60719b185243900efaf42 | 32875694ef008efe693d66e9c9bfac71c5c68126 | refs/heads/master | 2021-01-10T06:09:57.933999 | 2013-06-16T17:03:34 | 2013-06-16T17:03:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 665 | cc | dbltab.cc | /* Copyright 2013 Nicholas Esterer. All Rights Reserved. */
/* A table for holding doubles. Performs no interpolation. */
#include <cm/dbltab.h>
#include <cmath>
#include <cm/utils.h>
DblTab::DblTab() { }
DblTab::DblTab(double *tab, long int len)
{
this->tab = tab;
this->len = len;
}
DblTab::~DblTab(void)
{
}
double DblTab::get_index(double i)
{
i = cm_fclip(i, 0, len - 1);
return tab[(long int)floor(i)];
}
double DblTab::get_index(int i)
{
i = cm_clip(i, 0, len - 1);
return tab[i];
}
double DblTab::length()
{
return (double)len;
}
double DblTab::first_x()
{
return 0;
}
double DblTab::last_x()
{
return len-1;
}
|
d9ea1badfdaf224c517c842af5932b25d17759e3 | 0ed8ccb2e6fe8070087f687b492f77462bd4ffb9 | /code/07.2 3dEngine3_arrowKey/dataStruct.h | 286d11bfd4f640ab85e0a7ac524978244f571c5f | [] | no_license | joyce725/RenderLearningPlan | b7921e8e925ad8fc7695f0b87eb9c82cd581a937 | a44411da6761f634813173b36974bdf8a7e08fe0 | refs/heads/master | 2023-03-23T23:26:20.805506 | 2021-03-11T07:15:01 | 2021-03-11T07:15:01 | null | 0 | 0 | null | null | null | null | BIG5 | C++ | false | false | 6,504 | h | dataStruct.h | #pragma once
#include <fstream>
#include <strstream>
#include <vector>
typedef unsigned int u32;
typedef struct _Vec2 { float x, y; } vec2;
typedef struct _Vec3 { float x = 0, y = 0, z = 0, w = 1; } vec3;
typedef struct _Triangle {
vec3 p[3];
u32 col;
} triangle;
typedef struct MATRIX4X4_TYP {
union {
float M[4][4];
struct {
float M00, M01, M02, M03;
float M10, M11, M12, M13;
float M20, M21, M22, M23;
float M30, M31, M32, M33;
};
};
}mat4x4, * mat4x4_ptr;
vec3 Vector_Add(vec3& v1, vec3& v2)
{
return { v1.x + v2.x, v1.y + v2.y, v1.z + v2.z };
}
vec3 Vector_Sub(vec3& v1, vec3& v2)
{
return { v1.x - v2.x, v1.y - v2.y, v1.z - v2.z };
}
vec3 Vector_Mul(vec3& v1, float k)
{
return { v1.x * k, v1.y * k, v1.z * k };
}
vec3 Vector_Div(vec3& v1, float k)
{
return { v1.x / k, v1.y / k, v1.z / k };
}
float Vector_DotProduct(vec3& v1, vec3& v2)
{
return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
}
float Vector_Length(vec3& v)
{
return sqrtf(Vector_DotProduct(v, v));
}
vec3 Vector_Normalise(vec3& v)
{
float l = Vector_Length(v);
return { v.x / l, v.y / l, v.z / l };
}
vec3 Vector_CrossProduct(vec3& v1, vec3& v2)
{
vec3 v;
v.x = v1.y * v2.z - v1.z * v2.y;
v.y = v1.z * v2.x - v1.x * v2.z;
v.z = v1.x * v2.y - v1.y * v2.x;
return v;
}
void MultiplyMatrixVector(mat4x4& m44, vec3& i, vec3& o)
{
/*
r\c
[a b c d] |x|
[e f g h] |y|
[i j k l] |z|
[m n o p] |w|
m44[0][1]=>b
m44[0][2]=>c
*/
o.x = i.x * m44.M[0][0] + i.y * m44.M[0][1] + i.z * m44.M[0][2] + m44.M[0][3];
o.y = i.x * m44.M[1][0] + i.y * m44.M[1][1] + i.z * m44.M[1][2] + m44.M[1][3];
o.z = i.x * m44.M[2][0] + i.y * m44.M[2][1] + i.z * m44.M[2][2] + m44.M[2][3];
float w = i.x * m44.M[3][0] + i.y * m44.M[3][1] + i.z * m44.M[3][2] + m44.M[3][3];
if (w != 0.0f)
{
o.x /= (float)w; o.y /= (float)w; o.z /= (float)w;
}
}
vec3 Matrix_MultiplyVector(mat4x4& m44, vec3& i) {
vec3 v;
v.x = i.x * m44.M[0][0] + i.y * m44.M[0][1] + i.z * m44.M[0][2] + m44.M[0][3];
v.y = i.x * m44.M[1][0] + i.y * m44.M[1][1] + i.z * m44.M[1][2] + m44.M[1][3];
v.z = i.x * m44.M[2][0] + i.y * m44.M[2][1] + i.z * m44.M[2][2] + m44.M[2][3];
v.w = i.x * m44.M[3][0] + i.y * m44.M[3][1] + i.z * m44.M[3][2] + m44.M[3][3];
return v;
}
mat4x4 Matrix_MakeIdentity()
{
mat4x4 matrix = {
1,0,0,0,
0,1,0,0,
0,0,1,0,
0,0,0,1
};
return matrix;
}
mat4x4 Matrix_MakeRotationX(float fAngleRad)
{
mat4x4 matrix = {
1,0,0,0,
0,cosf(fAngleRad),-sinf(fAngleRad),0,
0,sinf(fAngleRad),cosf(fAngleRad),0,
0,0,0,1
};
return matrix;
}
mat4x4 Matrix_MakeRotationY(float fAngleRad)
{
mat4x4 matrix = {
cosf(fAngleRad),0,sinf(fAngleRad),0,
0,1,0,0,
-sinf(fAngleRad),0,cosf(fAngleRad),0,
0,0,0,1
};
return matrix;
}
mat4x4 Matrix_MakeRotationZ(float fAngleRad)
{
mat4x4 matrix = {
cosf(fAngleRad),-sinf(fAngleRad),0,0,
sinf(fAngleRad),cosf(fAngleRad),0,0,
0,0,1,0,
0,0,0,1
};
return matrix;
}
mat4x4 Matrix_MakeTranslation(float tx, float ty, float tz)
{
mat4x4 matrix = {
1,0,0,tx,
0,1,0,ty,
0,0,1,tz,
0,0,0,1
};
return matrix;
}
// 視角、長寬比、近截面、遠截面
mat4x4 Matrix_MakeProjection(float fFovDegrees, float fAspectRatio, float fNear, float fFar)
{
float fFovRad = 1.0f / tanf(fFovDegrees * 0.5f / 180.0f * 3.14159f);
mat4x4 matrix = {
fAspectRatio * fFovRad,0,0,0,
0,fFovRad,0,0,
0,0,fFar / (fFar - fNear),(-fFar * fNear) / (fFar - fNear),
0,0,1,0
};
return matrix;
}
mat4x4 Matrix_PointAt(vec3& pos, vec3& target, vec3& up)
{
// Calculate new forward direction
vec3 newForward = Vector_Sub(target, pos);
newForward = Vector_Normalise(newForward);
// Calculate new Up direction
vec3 a = Vector_Mul(newForward, Vector_DotProduct(up, newForward));
vec3 newUp = Vector_Sub(up, a);
newUp = Vector_Normalise(newUp);
// New Right direction is easy, its just cross product
vec3 newRight = Vector_CrossProduct(newUp, newForward);
// Construct Dimensioning and Translation Matrix
mat4x4 matrix = {
newRight.x,newUp.x,newForward.x,pos.x,
newRight.y,newUp.y,newForward.y,pos.y,
newRight.z,newUp.z,newForward.z,pos.z,
0,0,0,1
};
//matrix.m[0][0] = newRight.x; matrix.m[0][1] = newRight.y; matrix.m[0][2] = newRight.z; matrix.m[0][3] = 0.0f;
//matrix.m[1][0] = newUp.x; matrix.m[1][1] = newUp.y; matrix.m[1][2] = newUp.z; matrix.m[1][3] = 0.0f;
//matrix.m[2][0] = newForward.x; matrix.m[2][1] = newForward.y; matrix.m[2][2] = newForward.z; matrix.m[2][3] = 0.0f;
//matrix.m[3][0] = pos.x; matrix.m[3][1] = pos.y; matrix.m[3][2] = pos.z; matrix.m[3][3] = 1.0f;
return matrix;
}
mat4x4 Matrix_QuickInverse(mat4x4& m) // Only for Rotation/Translation Matrices
{
mat4x4 matrix = {
m.M[0][0], m.M[1][0], m.M[2][0], 0,
m.M[0][1], m.M[1][1], m.M[2][1], 0,
m.M[0][2], m.M[1][2], m.M[2][2], 0,
0, 0, 0, 1
};
matrix.M[0][3] = -(matrix.M[0][0] * m.M[0][3] + matrix.M[0][1] * m.M[1][3] + matrix.M[0][2] * m.M[2][3]);
matrix.M[1][3] = -(matrix.M[1][0] * m.M[0][3] + matrix.M[1][1] * m.M[1][3] + matrix.M[1][2] * m.M[2][3]);
matrix.M[2][3] = -(matrix.M[2][0] * m.M[0][3] + matrix.M[2][1] * m.M[1][3] + matrix.M[2][2] * m.M[2][3]);
//matrix.M[0][0] = m.M[0][0]; matrix.M[0][1] = m.M[1][0]; matrix.M[0][2] = m.M[2][0]; matrix.M[0][3] = 0.0f;
//matrix.M[1][0] = m.M[0][1]; matrix.M[1][1] = m.M[1][1]; matrix.M[1][2] = m.M[2][1]; matrix.M[1][3] = 0.0f;
//matrix.M[2][0] = m.M[0][2]; matrix.M[2][1] = m.M[1][2]; matrix.M[2][2] = m.M[2][2]; matrix.M[2][3] = 0.0f;
//matrix.M[3][0] = -(m.M[3][0] * matrix.M[0][0] + m.M[3][1] * matrix.M[1][0] + m.M[3][2] * matrix.M[2][0]);
//matrix.M[3][1] = -(m.M[3][0] * matrix.M[0][1] + m.M[3][1] * matrix.M[1][1] + m.M[3][2] * matrix.M[2][1]);
//matrix.M[3][2] = -(m.M[3][0] * matrix.M[0][2] + m.M[3][1] * matrix.M[1][2] + m.M[3][2] * matrix.M[2][2]);
//matrix.M[3][3] = 1.0f;
return matrix;
}
mat4x4 Matrix_MultiplyMatrix(mat4x4& m1, mat4x4& m2)
{
/*mat4x4 m1 = {
1,2,3,4,
5,6,7,8,
9,10,11,12,
13,14,15,16
};
mat4x4 m2 = {
1,1,1,1,
2,2,2,2,
3,3,3,3,
4,4,4,4
};
mat4x4 m3 = Matrix_MultiplyMatrix(m1, m2);*/
mat4x4 matrix;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
matrix.M[i][j] =
m1.M[i][0] * m2.M[0][j] +
m1.M[i][1] * m2.M[1][j] +
m1.M[i][2] * m2.M[2][j] +
m1.M[i][3] * m2.M[3][j];
return matrix;
}
void showMatrix(mat4x4 m) {
printf("------\n");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
printf("%.3f\t", m.M[i][j]);
}
printf("\n");
}
printf("------\n");
} |
2fb1321af4a69915fa35ca00c53a8f4ce934228b | a6981c098e357564fdd9a702fa02c6a59829e437 | /src/yarp_connector.cpp | 5c03f47fe921ac6b25049eec612cc6e9fd63d04e | [
"ISC"
] | permissive | severin-lemaignan/liboro | 109ebcdbc92e7220e325a7a692d7586f03fd9b1b | 058168bbabd7d79fbf38e242695ba15a6bea5deb | refs/heads/master | 2021-07-19T10:58:15.615630 | 2021-02-25T22:57:45 | 2021-02-25T22:57:45 | 8,359,960 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,346 | cpp | yarp_connector.cpp |
/*
* Copyright (c) 2008-2010 LAAS-CNRS Séverin Lemaignan slemaign@laas.fr
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <iostream>
#include <iterator>
#include <algorithm>
#include <time.h>
#include "oro_exceptions.h"
#include "yarp_connector.h"
using namespace yarp::os;
using namespace std;
namespace oro {
//Defines two constants needed to decode YARP status.
const char* OK = "ok";
const char* ERROR = "error";
class ParametersSerializationHolder; //forward declaration
YarpConnector::YarpConnector(const string port_name, const string oro_in_port_name){
Network::init();
// Work locally - don't rely on name server (just for this example).
// If you have a YARP name server running, you can remove this line.
//Network::setLocalMode(true);
//Checks that a YARP nameserver is reachable.
if (! Network::checkNetwork()) {
cerr << "Looks like there is no YARP server started! Exiting.";
throw ConnectorException("No YARP server can be found. Abandon.");
exit(0);
}
// we will want to read every message, with no skipping of "old" messages
// when new ones come in
in.setStrict();
// Name the ports
oro_server = oro_in_port_name;
in_port = "/" + port_name + "/in";
out_port = "/" + port_name + "/out";
in.open( in_port.c_str() );
out.open( out_port.c_str() );
// Connect the local output port to the ontology server incoming port.
// No connection to the server results port since this connection is handled by the ontology server itself.
Network::connect(out_port.c_str() ,("/" + oro_server + "/in").c_str() );
//cout << "Connection to Yarp network ok" << endl;
}
YarpConnector::~YarpConnector(){
cout << "Closing YARP connection...";
if (Network::isConnected(out_port.c_str() ,("/" + oro_server + "/in").c_str() )) {
executeDry("close");
Network::disconnect(out_port.c_str() ,("/" + oro_server + "/in").c_str() );
}
in.close();
out.close();
Network::fini();
cout << "done." << endl;
}
ServerResponse YarpConnector::execute(const string query, const Bottle& args){
ServerResponse res;
// Send one "Bottle" object. The port is responsible for creating
// and reusing/destroying that object, since it needs to be sure
// it exists until communication to all recipients (just one in
// this case) is complete.
Bottle& outBot = out.prepare(); // Get the object
outBot.clear();
outBot.fromString((in_port + " " + query).c_str()); //Prepend the query with the port name where the server should send back the result.
Bottle& argsBot = outBot.addList();
argsBot.append(args);
//printf("Writing bottle (%s)\n", outBot.toString().c_str());
out.write(); // Now send it on its way
read(res);
return res;
}
ServerResponse YarpConnector::execute(const string query, const vector<server_param_types>& vect_args){
ParametersSerializationHolder paramsHolder;
//serialization of arguments
std::for_each(
vect_args.begin(),
vect_args.end(),
boost::apply_visitor(paramsHolder)
);
return execute(query, paramsHolder.getBottle());
}
ServerResponse YarpConnector::execute(const string query, const server_param_types& arg){
ParametersSerializationHolder paramsHolder;
//serialization of argument
boost::apply_visitor(paramsHolder, arg);
return execute(query, paramsHolder.getBottle());
}
ServerResponse YarpConnector::execute(const string query){
ServerResponse res;
// Send one "Bottle" object. The port is responsible for creating
// and reusing/destroying that object, since it needs to be sure
// it exists until communication to all recipients (just one in
// this case) is complete.
Bottle& outBot = out.prepare(); // Get the object
outBot.clear();
outBot.fromString((in_port + " " + query).c_str()); //Prepend the query with the port name where the server should send back the result.
//printf("Writing bottle (%s)\n", outBot.toString().c_str());
out.write(); // Now send it on its way
//cout << "Waiting for an answer from oro-server" << endl;
read(res);
//cout << "Got the answer!" << endl;
return res;
}
void YarpConnector::executeDry(const string query){
Bottle& outBot = out.prepare(); // Get the object
outBot.clear();
outBot.fromString((in_port + " " + query).c_str()); //Prepend the query with the port name where the server should send back the result.
out.write(); // Now send it on its way
}
void YarpConnector::read(ServerResponse& res){
//cout << "Waiting for answer...";
Bottle *rawResult = NULL;
int delay = 0;
rawResult = in.read(false);
while (rawResult == NULL && delay < ORO_MAX_DELAY){
msleep(50);
delay += 50;
rawResult = in.read(false);
}
//The server doesn't answer quickly enough.
if (rawResult == NULL){
res.status = ServerResponse::failed;
res.error_msg = "oro-server read timeout.";
return;
}
//cout << "got it! " << endl;
//cout << "Taille: " << rawResult->size() << endl;
if (rawResult->size() < 2 || rawResult->size() > 3) throw OntologyServerException("Internal error! Wrong number of result element returned by the server.");
if (!rawResult->get(0).isString()) throw OntologyServerException("Internal error! The server answer should start with a status string!");
if (rawResult->get(0).asString() == ERROR){
//throw OntologyServerException(rawResult->get(1).asString());
res.status = ServerResponse::failed;
res.exception_msg = rawResult->get(1).asString();
res.error_msg = rawResult->get(2).asString();
//cout << "ERROR Query to ontology server failed." << endl;
return;
}
if (rawResult->get(0).asString() == OK){
res.status = ServerResponse::ok;
if(rawResult->get(1).isList()){
Value tmp(rawResult->get(1));
//cout << "Received bottle: " << tmp.asList()->toString() << endl;
pourBottle(*(tmp.asList()), res.result);
}
else
{
throw OntologyServerException("INTERNAL ERROR! The second element of the server answer should be a list (bottle) of results!");
}
//copy(res.result.begin(), res.result.end(), ostream_iterator<string>(cout, "\n"));
//cout << "Query to ontology server succeeded." << endl;
return;
}
throw OntologyServerException("Internal error! The server answer should start with \"ok\" or \"error\"");
}
void YarpConnector::vectorToBottle(const vector<string>& data, Bottle& bottle)
{
vector<string>::const_iterator itData = data.begin();
for( ; itData != data.end() ; ++itData)
bottle.addString((*itData).c_str());
}
void YarpConnector::setToBottle(const set<string>& data, Bottle& bottle)
{
set<string>::const_iterator itData = data.begin();
for( ; itData != data.end() ; ++itData)
bottle.addString((*itData).c_str());
}
void YarpConnector::mapToBottle(const map<string, string>& data, Bottle& bottle)
{
map<string, string>::const_iterator itData = data.begin();
for( ; itData != data.end() ; ++itData) {
Bottle& tmp = bottle.addList();
tmp.addString((*itData).first.c_str());
tmp.addString((*itData).second.c_str());
}
}
void YarpConnector::pourBottle(const Bottle& bottle, server_return_types& result)
{
//result.clear();
//cout << bottle.toString() << endl;
int size = bottle.size();
//Only empty bottles or bottles with one value are handled
if (size == 0) {
//do nothing
}
else if (size == 1) {
if (bottle.get(0).isString()) {
if (bottle.get(0).asString() == "true")
result = true;
else if (bottle.get(0).asString() == "false")
result = false;
else
result = bottle.get(0).asString().c_str();
}
else if (bottle.get(0).isInt())
result = bottle.get(0).asInt();
else if (bottle.get(0).isDouble())
result = bottle.get(0).asDouble();
else if (bottle.get(0).isList())
result = makeCollec(*(bottle.get(0).asList()));
}
else {
assert(false); //the server shouldn't answer more than one value...
}
}
server_return_types YarpConnector::makeCollec(const Bottle& bottle) {
bool isValidMap = true;
bool isValidSet = true;
//First, inspect the bottle to determine the type.
for (int i = 0; i < bottle.size(); i++)
{
//cout << "Bottle[i]:" << bottle.get(i).toString().c_str() << endl;
if (!isValidMap || !bottle.get(i).isList() || bottle.get(i).asList()->size() != 2 || !bottle.get(i).asList()->get(0).isString() || !bottle.get(i).asList()->get(1).isString())
isValidMap = false;
if (!isValidSet || !bottle.get(i).isString())
isValidSet = false;
}
assert(!(isValidMap && isValidSet));
if (!isValidMap && !isValidSet) throw OntologyServerException("INTERNAL ERROR! The server answered an invalid collection!");
//TODO: avoid the unnecessary copy
if (isValidMap) {
map<string, string> result;
for (int i = 0; i < bottle.size(); i++)
{
result[bottle.get(i).asList()->get(0).asString().c_str()] = bottle.get(i).asList()->get(1).asString().c_str();
}
return result;
} else {
assert(isValidSet);
set<string> result;
for (int i = 0; i < bottle.size(); i++)
{
result.insert(bottle.get(i).asString().c_str());
}
return result;
}
}
void YarpConnector::pourBottle(const Bottle& bottle, vector<Concept>& result)
{
result.clear();
int size = bottle.size();
for (int i = 0;i < size; i++)
{
Concept tmp = Concept(bottle.get(i).asString().c_str());
result.push_back(tmp);
}
}
int YarpConnector::msleep(unsigned long milisec)
{
struct timespec req={0};
time_t sec=(int)(milisec/1000);
milisec=milisec-(sec*1000);
req.tv_sec=sec;
req.tv_nsec=milisec*1000000L;
while(nanosleep(&req,&req)==-1)
continue;
return 1;
}
}
|
81ed1888cae4990c35ecc6dd4f8b99331213700b | 8b9c62af6999ce124660adf522e0602ef426f702 | /main.cpp | 19ed4b4f4f0ffe381e9a05460f1f38a1ba4146e2 | [] | no_license | cplusplusgoddess/PYRAMID | 5ca26998121bdc185c0799df25138fc6b8df40b1 | 0dbae545c7425f42db66066f80f99a0407be3c40 | refs/heads/master | 2022-08-28T17:31:44.001273 | 2022-07-26T17:34:58 | 2022-07-26T17:34:58 | 167,294,255 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,456 | cpp | main.cpp | // ############################################
// Author: Amber Rogowicz
// File : main.cpp main driver for running pyramid
// Date: Jan 2019
// ############################################
//
// INPUT: An input file passed to the program as a parameter
// specifies:
// the target and input of the pyramid is retrieved from
// a file with the following syntax e.g.
// Target: 720
// 2
// 4 3 where there are SPACES and NO COMMAS separating the
// 3 2 6 numbers ...numbers can be on any number of lines
// 2 9 5 2
// 10 5 2 15 5
//
// OUTPUT:
// output is to the command line or standard output
// in the form of "L R L" where L = left R = right
// traversal down the pyramid
#include <iostream>
#include <string>
#include <stdlib.h>
#include "pyramid.cpp"
using namespace std;
static void show_usage(std::string name)
{
std::cerr << "Usage: " << name << " | -h | inputFILENAME \n"
<< "\t-h,--help\t\tShow this help message\n"
<< std::endl;
}
int main(int argc, char *argv[])
{
int target;
// Check the command line arguments
// user is asking for help to run the program
if ( ( argc < 2 ) || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help") )
{
show_usage(argv[0]);
return(1);
};
// open up the input file and read in the data to the
// Pyramid Object
ifstream infile(argv[1]);
if (infile.is_open())
{
infile.ignore( std::numeric_limits<std::streamsize>::max(), ':' ); // ignore "Target:
infile >> target;
}else{
cout << "Could not open file: " << argv[1] ;
return(1);
}
// read in the target integer
Pyramid pyramid;
try{
if( SUCCESS == pyramid.build( infile ))
{ //loop thru bottom elements for a path with a target
//pyramid.print();
infile.close();
string pathStr;
bool result = FAIL;
result = pyramid.getPath( target, 0, 0 , pathStr);
//cout << "\n Target: " << target << endl;
//cout << "\n Status: " << ((result==FAIL)?" FAIL":"SUCCESS") << endl;
cout << "\n Path: " << pathStr << endl;
}// end if building successful pyramid
}catch(const ios::failure& error){
cerr << "I/O exception " << error.what() << endl;
infile.close();
return EXIT_FAILURE;
}catch(...){
cout << "Unknown Problem reading the file " << argv[1] ;
infile.close();
return EXIT_FAILURE;
} // end build pyramid fail
exit(0);
} // end main()
|
a5d573942436c17a439f34f9fc8f33de7b3b9ded | 60ad5a5b9fba819b747f0061b0ded5df40c5da03 | /src/QCefBrowser/RenderDelegates/QCefSurfaceRenderDelegate.h | 88f7182243063a1f04ebaa6b497927052936c9c7 | [
"MIT"
] | permissive | alaiyeshi/QCefWebEngine | 5034c1a6863b145ab8c1cc7d45b865ee10c0853a | dd844352a5a5b8fc31192d9fe4ddcfb4c07d3ec8 | refs/heads/main | 2023-08-28T23:33:07.938846 | 2021-01-25T00:03:09 | 2021-01-25T00:03:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,627 | h | QCefSurfaceRenderDelegate.h | #pragma once
#pragma region std_headers
#include <unordered_map>
#pragma endregion
#pragma region cef_headers
#include <include/wrapper/cef_message_router.h>
#pragma endregion cef_headers
#pragma region project_headers
#include "../QCefViewRenderApp.h"
#include "QCefClient.h"
#pragma endregion project_headers
namespace QCefViewSurfaceRenderDelegate {
/// <summary>
///
/// </summary>
void
CreateBrowserDelegate(QCefViewRenderApp::RenderDelegateSet& delegates);
/// <summary>
///
/// </summary>
class RenderDelegate : public QCefViewRenderApp::RenderDelegate {
public:
/// <summary>
///
/// </summary>
RenderDelegate() = default;
/// <summary>
///
/// </summary>
/// <param name="app"></param>
/// <param name="browser"></param>
/// <param name="source_process"></param>
/// <param name="message"></param>
/// <returns></returns>
virtual bool OnProcessMessageReceived(CefRefPtr<QCefViewRenderApp> app,
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefProcessId source_process,
CefRefPtr<CefProcessMessage> message);
protected:
void onGetLinkAtPosition(CefRefPtr<CefBrowser> browser, const CefRefPtr<CefListValue>& args);
void onSetHorizontalScroll(CefRefPtr<CefBrowser> browser, const CefRefPtr<CefListValue>& args);
void onSetVerticalScroll(CefRefPtr<CefBrowser> browser, const CefRefPtr<CefListValue>& args);
private:
IMPLEMENT_REFCOUNTING(RenderDelegate);
};
}
|
943364561168688b250fd1be14bb2a6fc963f4ad | 2829a4aea5097f04b4c0e6aebb8e14970d9c36ff | /stm32_exti/src/STM32F303_startup.cpp | 9eda9d44680d49491e869adf7628f8b1e63dd2ca | [
"BSD-3-Clause"
] | permissive | Aghosh993/cmxx-demos | db377087b6a9e01c68c3d003caee1d5887df60dd | c5c4e9e293e2e3764eeed06996f7ebed2ae9b935 | refs/heads/master | 2020-03-27T07:27:32.816218 | 2018-08-28T12:42:46 | 2018-08-28T12:42:46 | 146,192,304 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,670 | cpp | STM32F303_startup.cpp | #include <STM32F303_startup.h>
static IRQ defaultRegistration;
IRQ* IRQ::irqRegistrationTable[PERIPHERAL_IRQS] = {
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration,
&defaultRegistration
};
// Cortex-M4 Exceptions: //
void IRQ::Reset_Handler(void)
{
/*
Copy initialization data from flash into SRAM:
*/
uint32_t *src, *dst;
src = &__etext;
for(dst = &__data_start__; dst < &__data_end__; )
{
*dst++ = *src++;
}
/*
Zero out BSS (RAM):
*/
for(dst = &__bss_start__; dst < &__bss_end__;)
{
*dst++ = 0U;
}
main();
while(1);
}
void IRQ::NMI_Handler(void)
{
while(1);
}
void IRQ::HardFault_Handler(void)
{
while(1);
}
void IRQ::MemManage_Handler(void)
{
while(1);
}
void IRQ::BusFault_Handler(void)
{
while(1);
}
void IRQ::UsageFault_Handler(void)
{
while(1);
}
void IRQ::SVC_Handler(void)
{
while(1);
}
void IRQ::DebugMon_Handler(void)
{
while(1);
}
void IRQ::PendSV_Handler(void)
{
while(1);
}
void IRQ::SysTick_Handler(void)
{
while(1);
}
// STM32F303 Exceptions: //
void IRQ::WWDG_handler(void)
{
irqRegistrationTable[0]->ISR();
}
void IRQ::PVD_handler(void)
{
irqRegistrationTable[1]->ISR();
}
void IRQ::TAMP_STAMP_handler(void)
{
irqRegistrationTable[2]->ISR();
}
void IRQ::RTC_WKUP_handler(void)
{
irqRegistrationTable[3]->ISR();
}
void IRQ::FLASH_handler(void)
{
irqRegistrationTable[4]->ISR();
}
void IRQ::RCC_handler(void)
{
irqRegistrationTable[5]->ISR();
}
void IRQ::EXTI0_handler(void)
{
irqRegistrationTable[6]->ISR();
}
void IRQ::EXTI1_handler(void)
{
irqRegistrationTable[7]->ISR();
}
void IRQ::EXTI2_TSC_handler(void)
{
irqRegistrationTable[8]->ISR();
}
void IRQ::EXTI3_handler(void)
{
irqRegistrationTable[9]->ISR();
}
void IRQ::EXTI4_handler(void)
{
irqRegistrationTable[10]->ISR();
}
void IRQ::DMA1_CH1_handler(void)
{
irqRegistrationTable[11]->ISR();
}
void IRQ::DMA1_CH2_handler(void)
{
irqRegistrationTable[12]->ISR();
}
void IRQ::DMA1_CH3_handler(void)
{
irqRegistrationTable[13]->ISR();
}
void IRQ::DMA1_CH4_handler(void)
{
irqRegistrationTable[14]->ISR();
}
void IRQ::DMA1_CH5_handler(void)
{
irqRegistrationTable[15]->ISR();
}
void IRQ::DMA1_CH6_handler(void)
{
irqRegistrationTable[16]->ISR();
}
void IRQ::DMA1_CH7_handler(void)
{
irqRegistrationTable[17]->ISR();
}
void IRQ::ADC1_2_handler(void)
{
irqRegistrationTable[18]->ISR();
}
void IRQ::USB_HP_CAN_TX_handler(void)
{
irqRegistrationTable[19]->ISR();
}
void IRQ::USB_LP_CAN_RX0_handler(void)
{
irqRegistrationTable[20]->ISR();
}
void IRQ::CAN_RX1_handler(void)
{
irqRegistrationTable[21]->ISR();
}
void IRQ::CAN_SCE_handler(void)
{
irqRegistrationTable[22]->ISR();
}
void IRQ::EXTI9_5_handler(void)
{
irqRegistrationTable[23]->ISR();
}
void IRQ::TIM1_BRK_TIM15_handler(void)
{
irqRegistrationTable[24]->ISR();
}
void IRQ::TIM1_UP_TIM16_handler(void)
{
irqRegistrationTable[25]->ISR();
}
void IRQ::TIM1_TRG_COM_TIM17_handler(void)
{
irqRegistrationTable[26]->ISR();
}
void IRQ::TIM1_CC_handler(void)
{
irqRegistrationTable[27]->ISR();
}
void IRQ::TIM2_handler(void)
{
irqRegistrationTable[28]->ISR();
}
void IRQ::TIM3_handler(void)
{
irqRegistrationTable[29]->ISR();
}
void IRQ::TIM4_handler(void)
{
irqRegistrationTable[30]->ISR();
}
void IRQ::I2C1_EV_EXTI23_handler(void)
{
irqRegistrationTable[31]->ISR();
}
void IRQ::I2C1_ER_handler(void)
{
irqRegistrationTable[32]->ISR();
}
void IRQ::I2C2_EV_EXTI24_handler(void)
{
irqRegistrationTable[33]->ISR();
}
void IRQ::I2C2_ER_handler(void)
{
irqRegistrationTable[34]->ISR();
}
void IRQ::SPI1_handler(void)
{
irqRegistrationTable[35]->ISR();
}
void IRQ::SPI2_handler(void)
{
irqRegistrationTable[36]->ISR();
}
void IRQ::USART1_EXTI25_handler(void)
{
irqRegistrationTable[37]->ISR();
}
void IRQ::USART2_EXTI26_handler(void)
{
irqRegistrationTable[38]->ISR();
}
void IRQ::USART3_EXTI28_handler(void)
{
irqRegistrationTable[39]->ISR();
}
void IRQ::EXTI15_10_handler(void)
{
irqRegistrationTable[40]->ISR();
}
void IRQ::RTCAlarm_handler(void)
{
irqRegistrationTable[41]->ISR();
}
void IRQ::USB_WKUP_handler(void)
{
irqRegistrationTable[42]->ISR();
}
void IRQ::TIM8_BRK_handler(void)
{
irqRegistrationTable[43]->ISR();
}
void IRQ::TIM8_UP_handler(void)
{
irqRegistrationTable[44]->ISR();
}
void IRQ::TIM8_TRG_COM_handler(void)
{
irqRegistrationTable[45]->ISR();
}
void IRQ::TIM8_CC_handler(void)
{
irqRegistrationTable[46]->ISR();
}
void IRQ::ADC3_handler(void)
{
irqRegistrationTable[47]->ISR();
}
void IRQ::FMC_handler(void)
{
irqRegistrationTable[48]->ISR();
}
void IRQ::SPI3_handler(void)
{
irqRegistrationTable[51]->ISR();
}
void IRQ::UART4_EXTI34_handler(void)
{
irqRegistrationTable[52]->ISR();
}
void IRQ::UART5_EXTI35_handler(void)
{
irqRegistrationTable[53]->ISR();
}
void IRQ::TIM6_DACUNDER_handler(void)
{
irqRegistrationTable[54]->ISR();
}
void IRQ::TIM7_handler(void)
{
irqRegistrationTable[55]->ISR();
}
void IRQ::DMA2_CH1_handler(void)
{
irqRegistrationTable[56]->ISR();
}
void IRQ::DMA2_CH2_handler(void)
{
irqRegistrationTable[57]->ISR();
}
void IRQ::DMA2_CH3_handler(void)
{
irqRegistrationTable[58]->ISR();
}
void IRQ::DMA2_CH4_handler(void)
{
irqRegistrationTable[59]->ISR();
}
void IRQ::DMA2_CH5_handler(void)
{
irqRegistrationTable[60]->ISR();
}
void IRQ::ADC4_handler(void)
{
irqRegistrationTable[61]->ISR();
}
void IRQ::COMP123_handler(void)
{
irqRegistrationTable[64]->ISR();
}
void IRQ::COMP456_handler(void)
{
irqRegistrationTable[65]->ISR();
}
void IRQ::COMP7_handler(void)
{
irqRegistrationTable[66]->ISR();
}
void IRQ::I2C3_EV_handler(void)
{
irqRegistrationTable[72]->ISR();
}
void IRQ::I2C3_ER_handler(void)
{
irqRegistrationTable[73]->ISR();
}
void IRQ::USB_HP_handler(void)
{
irqRegistrationTable[74]->ISR();
}
void IRQ::USB_LP_handler(void)
{
irqRegistrationTable[75]->ISR();
}
void IRQ::USB_WKUP_EXTI_handler(void)
{
irqRegistrationTable[76]->ISR();
}
void IRQ::TIM20_BRK_handler(void)
{
irqRegistrationTable[77]->ISR();
}
void IRQ::TIM20_UP_handler(void)
{
irqRegistrationTable[78]->ISR();
}
void IRQ::TIM20_TRG_COM_handler(void)
{
irqRegistrationTable[79]->ISR();
}
void IRQ::TIM20_CC_handler(void)
{
irqRegistrationTable[80]->ISR();
}
void IRQ::FPU_handler(void)
{
irqRegistrationTable[81]->ISR();
}
void IRQ::SPI4_handler(void)
{
irqRegistrationTable[84]->ISR();
}
// Class-wide methods: //
void IRQ::registerInterrupt(int nInterrupt, IRQ *thisPtr)
{
irqRegistrationTable[nInterrupt] = thisPtr;
}
// User-defined interrupt implementation (default infinite loop to preserve system state): //
void IRQ::ISR(void)
{
while(1);
}
void* isr_vectors[] __attribute__ ((section(".isr_vector"))) = {
&__StackTop,
IRQ::Reset_Handler,
IRQ::NMI_Handler,
IRQ::HardFault_Handler,
IRQ::MemManage_Handler,
IRQ::BusFault_Handler,
IRQ::UsageFault_Handler,
0,
0,
0,
0,
IRQ::SVC_Handler,
IRQ::DebugMon_Handler,
0,
IRQ::PendSV_Handler,
IRQ::SysTick_Handler,
// Jump addresses for STM32F303 interrupts: //
IRQ::WWDG_handler,
IRQ::PVD_handler,
IRQ::TAMP_STAMP_handler,
IRQ::RTC_WKUP_handler,
IRQ::FLASH_handler,
IRQ::RCC_handler,
IRQ::EXTI0_handler,
IRQ::EXTI1_handler,
IRQ::EXTI2_TSC_handler,
IRQ::EXTI3_handler,
IRQ::EXTI4_handler,
IRQ::DMA1_CH1_handler,
IRQ::DMA1_CH2_handler,
IRQ::DMA1_CH3_handler,
IRQ::DMA1_CH4_handler,
IRQ::DMA1_CH5_handler,
IRQ::DMA1_CH6_handler,
IRQ::DMA1_CH7_handler,
IRQ::ADC1_2_handler,
IRQ::USB_HP_CAN_TX_handler,
IRQ::USB_LP_CAN_RX0_handler,
IRQ::CAN_RX1_handler,
IRQ::CAN_SCE_handler,
IRQ::EXTI9_5_handler,
IRQ::TIM1_BRK_TIM15_handler,
IRQ::TIM1_UP_TIM16_handler,
IRQ::TIM1_TRG_COM_TIM17_handler,
IRQ::TIM1_CC_handler,
IRQ::TIM2_handler,
IRQ::TIM3_handler,
IRQ::TIM4_handler,
IRQ::I2C1_EV_EXTI23_handler,
IRQ::I2C1_ER_handler,
IRQ::I2C2_EV_EXTI24_handler,
IRQ::I2C2_ER_handler,
IRQ::SPI1_handler,
IRQ::SPI2_handler,
IRQ::USART1_EXTI25_handler,
IRQ::USART2_EXTI26_handler,
IRQ::USART3_EXTI28_handler,
IRQ::EXTI15_10_handler,
IRQ::RTCAlarm_handler,
IRQ::USB_WKUP_handler,
IRQ::TIM8_BRK_handler,
IRQ::TIM8_UP_handler,
IRQ::TIM8_TRG_COM_handler,
IRQ::TIM8_CC_handler,
IRQ::ADC3_handler,
IRQ::FMC_handler,
0,
0,
IRQ::SPI3_handler,
IRQ::UART4_EXTI34_handler,
IRQ::UART5_EXTI35_handler,
IRQ::TIM6_DACUNDER_handler,
IRQ::TIM7_handler,
IRQ::DMA2_CH1_handler,
IRQ::DMA2_CH2_handler,
IRQ::DMA2_CH3_handler,
IRQ::DMA2_CH4_handler,
IRQ::DMA2_CH5_handler,
IRQ::ADC4_handler,
0,
0,
IRQ::COMP123_handler,
IRQ::COMP456_handler,
IRQ::COMP7_handler,
0,
0,
0,
0,
0,
IRQ::I2C3_EV_handler,
IRQ::I2C3_ER_handler,
IRQ::USB_HP_handler,
IRQ::USB_LP_handler,
IRQ::USB_WKUP_EXTI_handler,
IRQ::TIM20_BRK_handler,
IRQ::TIM20_UP_handler,
IRQ::TIM20_TRG_COM_handler,
IRQ::TIM20_CC_handler,
IRQ::FPU_handler,
0,
0,
IRQ::SPI4_handler
};
|
3d185e1aab5941405229297fe41c229125018272 | 05975df9f354e16e4dacdf07a231c72b6066e825 | /Castlevania/CrossItem.cpp | e653038ebfb4b385f30d6d2d4211142dfe84876c | [] | no_license | PhanVinhLong/GameDevIntro | d55ea4ecb17913f4f270c8a43386e015b86e53b8 | 16138b495467730e33937dcfbc741657c563f0c0 | refs/heads/master | 2020-03-29T03:55:49.210954 | 2019-01-05T12:08:20 | 2019-01-05T12:08:20 | 149,507,531 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 510 | cpp | CrossItem.cpp | #include "CrossItem.h"
CCrossItem::CCrossItem(D3DXVECTOR2 position)
{
x = position.x;
y = position.y;
id = ID_ITEM_CROSS;
AddAnimation(ID_ANI_CROSS_ITEM);
}
CCrossItem::~CCrossItem()
{
}
void CCrossItem::GetBoundingBox(float & l, float & t, float & r, float & b)
{
l = x;
t = y - CROSS_ITEM_BBOX_HEIGHT;
r = x + CROSS_ITEM_BBOX_WIDTH;
b = y;
}
void CCrossItem::Update(DWORD dt, vector<LPGAMEOBJECT>* coObjects)
{
CItem::Update(dt, coObjects);
if (!isOnGround)
vy += CROSS_ITEM_GRAVITY * dt;
}
|
bb87d7e7388644fb4d8e883e662b9b5c73e11403 | ced2b83ef7cc267792e8014aed7dc90f21ce9899 | /leetcode/17_LetterCombinations.cpp | 25332a31c99f1e2c4c3ebb95d8faf3da7e89e8f7 | [] | no_license | cypress777/oj | 4f380dd84ed3b7f398dfc6ad0c254cab1adfd1a3 | 80062f6969162dbf11634ccfceb502dbc6874531 | refs/heads/master | 2022-03-10T17:32:13.664052 | 2022-02-23T11:04:26 | 2022-02-23T11:04:26 | 144,862,105 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,061 | cpp | 17_LetterCombinations.cpp | class Solution {
public:
void gen(const string &digits, int id, string &s,
unordered_map<int, string> &phone, set<string> &res) {
if (id >= digits.size()) {
res.insert(s);
} else {
int num = digits[id] - '0';
string letters = phone[num];
for (int i = 0; i < letters.size(); i++) {
string next = s;
next.push_back(letters[i]);
gen(digits, id + 1, next, phone, res);
}
}
}
vector<string> letterCombinations(string digits) {
unordered_map<int, string> phone = {{2, "abc"}, {3, "def"}, {4, "ghi"},
{5, "jkl"}, {6, "mno"}, {7, "pqrs"},
{8, "tuv"}, {9, "wxyz"}};
set<string> res;
string empty;
gen(digits, 0, empty, phone, res);
vector<string> uniq_res;
for (auto r : res) {
if (!r.empty()) uniq_res.push_back(r);
}
return uniq_res;
}
};
|
d03a6ebc50b95b14b0d3e6566546166cb221a997 | 3450a3575b85c63e0aa8fe72de4a10b2f847bc2f | /Controllers/Stock/providercontroller.h | a656c37bc665c840a37d22c121d776e1c370f7bd | [] | no_license | rdal/erprock | 96a188fe154a8b4c3729de59e52cca8b08cda24b | 1d2f880d366551283046a75c0b0ea331846dfb3d | refs/heads/master | 2020-03-22T04:28:22.521351 | 2018-07-02T22:32:22 | 2018-07-02T22:32:22 | 139,501,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,491 | h | providercontroller.h | #ifndef PROVIDERCONTROLLER_H
#define PROVIDERCONTROLLER_H
#include <QObject>
#include "utilities.h"
#include "databasecontroller.h"
//! Controller for providers
/*!
\author Rafael Donato <rafaeldonato@gmail.com>
This class is responsible for providers management.
*/
class ProviderController : public QObject
{
Q_OBJECT
public:
//! Default constructor.
/*!
* Create a new instance of ProviderController.
*/
explicit ProviderController(QObject *parent = 0);
//! Destructor.
/*!
* Release all resources here.
*/
~ProviderController();
/*!
Beforing adding a provider, this method checks if there is already a provider with that CNPJ,
if its name has less than 100 characters, and if the given CNPJ is valid.
\param provider The Provider object to be added.
\return Returns the Status Control of the operation.
\sa updateProvider(), removeProvider(), getProviderByCNPJ() and getProviders()
*/
Utilities::StatusControl addProvider(Provider *provider);
/*!
Beforing updating a provider, this method checks if there is a provider with that CNPJ,
and if its name has less than 100 characters.
\param provider The Provider object to be updated.
\return Returns the Status Control of the operation.
\sa addProvider(), removeProvider(), getProviderByCNPJ() and getProviders()
*/
Utilities::StatusControl updateProvider(Provider *provider);
/*!
Beforing removing an provider, this method checks if there is a provider with that CNPJ.
\param cnpj The cnpj whose provider will be removed.
\return Returns the Status Control of the operation.
\sa addProvider(), updateProvider(), getProviderByCNPJ() and getProviders()
*/
Utilities::StatusControl removeProvider(QString cnpj);
/*!
Get an provider by its CNPJ.
\param cnpj The Provider's CNPJ.
\return Returns the provider object associated with the given CNPJ.
\sa addProvider(), updateProvider(), removeProvider() and getProviders()
*/
Provider *getProviderByCNPJ(QString cnpj);
/*!
This method returns all the providers that were previously stored at database.
\return Returns all stored providers.
\sa addProvider(), updateProvider(), removeProvider() and getProviderByCNPJ()
*/
QList<Provider*> *getProviders();
private:
DatabaseController *dbController;
signals:
public slots:
};
#endif // PROVIDERCONTROLLER_H
|
520aca8047c790e84a8a9bb5a0d4fb7060c61431 | 835a80ac73114c328ac229ed953c989d3351861d | /SparseSDF/old/TrigIter2D.h | b670412d50960d73c15712aece919774f5313e18 | [] | no_license | desaic/webgl | db18661f446bd35cc3236c98b30f914941f9379f | 2e0e78cb14967b7885bfa00824e4d5f409d7cc07 | refs/heads/master | 2023-08-14T15:31:57.451868 | 2023-08-10T17:49:48 | 2023-08-10T17:49:48 | 10,447,154 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,971 | h | TrigIter2D.h | #ifndef TRIG_ITER_2D
#define TRIG_ITER_2D
#include "Vec2.h"
#include "LineIter2D.h"
int obb_round(float f);
class TrigIter2D
{
protected:
Vec2i m_vertex[3]; ///< The 3D Transformed vertices
int m_lower_left_idx;
int m_upper_left_idx;
int m_the_other_idx;
LineIter2D m_left_ridge_iterator;
LineIter2D m_right_ridge_iterator;
// Types and variables for scan-convertion
typedef enum {
find_nonempty_scanline_state
, in_scanline_state
, scanline_found_state
, finished_state
} state_type;
state_type m_state;
int m_start_x; // Screen coordinates
int m_end_x;
int m_current_y;
protected:
/**
* returns the index of the vertex with the smallest y-coordinate
* If there is a horizontal edge, the vertex with the smallest
* x-coordinate is chosen.
*/
int find_lower_left_vertex_index()
{
int ll = 0;
for (int i = ll + 1; i < 3; ++i)
{
if (
(this->m_vertex[i][1] < this->m_vertex[ll][1])
||
(
(this->m_vertex[i][1] == this->m_vertex[ll][1])
&&
(this->m_vertex[i][0] < this->m_vertex[ll][0])
)
)
{
ll = i;
}
}
return ll;
}
/**
* returns the index of the vertex with the greatest y-coordinate
* If there is a horizontal edge, the vertex with the smallest
* x-coordinate is chosen.
*/
int find_upper_left_vertex_index()
{
int ul = 0;
for (int i = ul + 1; i < 3; ++i)
{
if (
(this->m_vertex[i][1] > this->m_vertex[ul][1])
||
(
(this->m_vertex[i][1] == this->m_vertex[ul][1])
&&
(this->m_vertex[i][0] < this->m_vertex[ul][0])
)
)
{
ul = i;
}
}
return ul;
}
LineIter2D get_left_ridge_iterator() const
{
typedef float real_type;
// Let u be the vector from 'lowerleft' to 'upperleft', and let v be the vector
// from 'lowerleft' to 'theother'. If the cross product u x v is positive then
// the point 'theother' is to the left of u.
Vec2i u = this->m_vertex[this->m_upper_left_idx] - this->m_vertex[this->m_lower_left_idx];
Vec2i v = this->m_vertex[this->m_the_other_idx] - this->m_vertex[this->m_lower_left_idx];
real_type cross_product = u[0] * v[1] - u[1] * v[0];
if (cross_product >= 0)
{
// Here there is no need to check for a horizontal edge, because it
// would be a top edge, and therefore it would not be drawn anyway.
// The point 'theother' is to the left of the vector u
return LineIter2D(this->m_vertex[this->m_lower_left_idx]
, this->m_vertex[this->m_the_other_idx]
, this->m_vertex[this->m_upper_left_idx]);
}
else
{
// The point 'theother' is to the right of the vector u
return LineIter2D(this->m_vertex[this->m_lower_left_idx], this->m_vertex[this->m_upper_left_idx]);
}
}
LineIter2D get_right_ridge_iterator() const
{
typedef float real_type;
// Let u be the vector from 'lowerleft' to 'upperleft', and let v be the vector
// from 'lowerleft' to 'theother'. If the cross product u x v is negative then
// the point 'theother' is to the right of u.
Vec2i u = this->m_vertex[this->m_upper_left_idx] - this->m_vertex[this->m_lower_left_idx];
Vec2i v = this->m_vertex[this->m_the_other_idx] - this->m_vertex[this->m_lower_left_idx];
real_type cross_product = u[0] * v[1] - u[1] * v[0];
if (cross_product < 0)
{
// The point 'theother' is to the right of the vector u
// Check if there is a horizontal edge
if (this->m_vertex[this->m_lower_left_idx][1] != this->m_vertex[this->m_the_other_idx][1] )
{
return LineIter2D(
this->m_vertex[this->m_lower_left_idx]
, this->m_vertex[this->m_the_other_idx]
, this->m_vertex[this->m_upper_left_idx]
);
}
else
{
// Horizontal edge - ('lowerleft', 'theother') - throw it away
return LineIter2D(
this->m_vertex[this->m_the_other_idx]
, this->m_vertex[this->m_upper_left_idx]
);
}
}
else
{
// The point 'theother' is to the left of the u vector
return LineIter2D(
this->m_vertex[this->m_lower_left_idx]
, this->m_vertex[this->m_upper_left_idx]
);
}
}
bool find_nonempty_scanline()
{
while (m_left_ridge_iterator())
{
this->m_start_x = this->m_left_ridge_iterator.x();
this->m_end_x = this->m_right_ridge_iterator.x();
this->m_current_y = this->m_left_ridge_iterator.y();
if (this->m_start_x < this->m_end_x)
{
this->m_state = in_scanline_state;
return this->valid();
}
else
{
++(this->m_left_ridge_iterator);
++(this->m_right_ridge_iterator);
this->m_state = find_nonempty_scanline_state;
}
}
// We ran our of left_ridge_iterator...
return this->valid();
}
public:
bool valid() const { return this->m_left_ridge_iterator.valid(); }
int x0() const { return this->m_start_x; }
int x1() const { return this->m_end_x; }
int y() const { return this->m_current_y; }
public:
virtual ~TrigIter2D(){}
/**
*
* vertex coordinates are assumed to be transformed into screen
* space of the camera. Normals can be given in whatever coordinate
* frame one wants. Just remember that normals are lineary
* interpolated in screen space.
*
*/
TrigIter2D(
Vec2f const & v1
, Vec2f const & v2
, Vec2f const & v3
)
{
this->initialize(v1,v2,v3);
}
TrigIter2D(TrigIter2D const & iter) { (*this) = iter; }
TrigIter2D const & operator=(TrigIter2D const & iter)
{
this->m_vertex[0] = iter.m_vertex[0];
this->m_vertex[1] = iter.m_vertex[1];
this->m_vertex[2] = iter.m_vertex[2];
this->m_lower_left_idx = iter.m_lower_left_idx;
this->m_upper_left_idx = iter.m_upper_left_idx;
this->m_the_other_idx = iter.m_the_other_idx;
this->m_left_ridge_iterator = iter.m_left_ridge_iterator;
this->m_right_ridge_iterator = iter.m_right_ridge_iterator;
this->m_state = iter.m_state;
this->m_start_x = iter.m_start_x;
this->m_end_x = iter.m_end_x;
this->m_current_y = iter.m_current_y;
return *this;
}
/**
*
*
* @return If there are any more fragments left then the
* return value is true otherwise it is false.
*/
bool operator()() const { return this->m_left_ridge_iterator.valid(); }
/**
* Advances the iterator to the next fragment. Initially the
* fragement iterator points to the first fragment (if any).
*
*/
bool operator++()
{
if (this->m_state == find_nonempty_scanline_state)
{
if (this->find_nonempty_scanline())
{
this->m_state = scanline_found_state;
}
}
if (this->m_state == in_scanline_state)
{
++(this->m_left_ridge_iterator);
++(this->m_right_ridge_iterator);
if (this->find_nonempty_scanline())
{
this->m_state = in_scanline_state;
}
}
if (this->m_state == scanline_found_state)
{
this->m_state = in_scanline_state;
}
return this->valid();
}
public:
/**
*
* vertex coordinates are assumed to be transformed into screen
* space of the camera. Normals can be given in whatever coordinate
* frame one wants. Just remember that normals are lineary
* interpolated in screen space.
*
*/
void initialize(
Vec2f const & v1
, Vec2f const & v2
, Vec2f const & v3
)
{
this->m_vertex[0] = Vec2i(obb_round(v1[0]), obb_round(v1[1]));
this->m_vertex[1] = Vec2i(obb_round(v2[0]), obb_round(v2[1]));
this->m_vertex[2] = Vec2i(obb_round(v3[0]), obb_round(v3[1]));
this->m_lower_left_idx = this->find_lower_left_vertex_index();
this->m_upper_left_idx = this->find_upper_left_vertex_index();
if(this->m_lower_left_idx == this->m_upper_left_idx)
{
// We must have encountered a degenerate case! Either a point or horizontal line
int a = (this->m_lower_left_idx + 1) % 3;
int b = (a + 1) % 3;
this->m_upper_left_idx = (this->m_vertex[a][0] < this->m_vertex[b][0]) ? a : b;
}
this->m_the_other_idx = 3 - (this->m_lower_left_idx + this->m_upper_left_idx);
this->m_left_ridge_iterator = this->get_left_ridge_iterator();
this->m_right_ridge_iterator = this->get_right_ridge_iterator();
this->m_state = find_nonempty_scanline_state;
this->find_nonempty_scanline();
}
};
#endif |
ccc1865f4f3e4f636c8a003b6281eb39b10c000b | 871bf020e1546e043a2f1ffc083f24b3f6b59d97 | /LearnSuperBible/Unit2/Unit2Triangle.cpp | 60ffd0fa751ae2f2edfc4eabc7581ed7ff59c985 | [] | no_license | jjzhang166/HelloQtOpenGL | b53bb76b462a7c1d00b28ec311b084ac7c1dfb7d | 14ef50ad491f09d05fcd8315aef69d7a97cc236e | refs/heads/master | 2023-03-20T20:57:04.763180 | 2020-08-05T13:48:21 | 2020-08-05T13:48:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,658 | cpp | Unit2Triangle.cpp | #include "Unit2Triangle.h"
#include <QSurfaceFormat>
#include <QOpenGLContext>
#include <QDebug>
Unit2Triangle::Unit2Triangle(QWidget *parent)
: QOpenGLWidget(parent)
{
connect(timer,&QTimer::timeout,[this]{
//累加或减,到达极限就反转flag
if(offsetFlag){
offsetCount+=5;
if(offsetCount>255){
offsetCount=255;
offsetFlag=!offsetFlag;
}
}else{
offsetCount-=5;
if(offsetCount<55){
offsetCount=55;
offsetFlag=!offsetFlag;
}
}
update();
});
timer->start(50);
}
Unit2Triangle::~Unit2Triangle()
{
//此为Qt接口:通过使相应的上下文成为当前上下文并在该上下文中绑定帧缓冲区对象,
//准备为此小部件呈现OpenGL内容。在调用paintGL()之前会自动调用。
makeCurrent();
//.. ...
//此为Qt接口:释放上下文。在大多数情况下不需要调用此函数,
//因为小部件将确保在调用paintGL()时正确绑定和释放上下文。
doneCurrent();
}
void Unit2Triangle::initializeGL()
{
//此为Qt接口:为当前上下文初始化OpenGL函数解析
initializeOpenGLFunctions();
//打印OpenGL信息,使用gl函数,应该是获取的系统的
//使用了QSurfaceFormat设置gl后就不能调用这个了
//const GLubyte * vendor = glGetString(GL_VENDOR);
//const GLubyte * renderer = glGetString(GL_RENDERER);
//const GLubyte * version = glGetString(GL_VERSION);
//qDebug()<<"OpenGL实现厂商"<<(char*)vendor;
//qDebug()<<"渲染器标识符"<<(char*)renderer;
//qDebug()<<"OpenGL版本号"<<(char*)version;
//QSurfaceFormat默认版本为2.0=QSurfaceFormat::defaultFormat().version()
qDebug()<<"QSurfaceFormat::defaultFormat()"<<QSurfaceFormat::defaultFormat();
//窗口清除的颜色
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
}
void Unit2Triangle::paintGL()
{
//【主要部分】
//清除颜色缓冲区
glClear(GL_COLOR_BUFFER_BIT);
//绘制三角(坐标范围默认为[-1,1])
glBegin(GL_TRIANGLES);
//三角形的三个顶点 --每个顶点一个颜色,中部分为线性插值
glColor3f((float)(offsetCount/255.0),0.0f,0.0f);
glVertex3f(-0.5f,-0.4f,0.0f);
glColor3f(0.0f,(float)(offsetCount/255.0),0.0f);
glVertex3f(0.5f,-0.4f,0.0f);
glColor3f(0.0f,0.0f,(float)(offsetCount/255.0));
glVertex3f( 0.0f,0.4f,0.0f );
glEnd();
}
void Unit2Triangle::resizeGL(int width, int height)
{
//视口,靠左下角缩放
glViewport(0,0,width,height);
}
|
65d1f2bd3a98e29e967bd753d82ae97325ff6957 | c094d381422c2788d67a3402cff047b464bf207b | /c++_primer_plus/c++_primer_plus/研究 - 007类继承之台球俱乐部会员管理类.h | 54d000b9f25ce061db9f871c393f63e65b9b887d | [] | no_license | liuxuanhai/C-code | cba822c099fd4541f31001f73ccda0f75c6d9734 | 8bfeab60ee2f8133593e6aabfeefaf048357a897 | refs/heads/master | 2020-04-18T04:26:33.246444 | 2016-09-05T08:32:33 | 2016-09-05T08:32:33 | 67,192,848 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,765 | h | 研究 - 007类继承之台球俱乐部会员管理类.h | // 关于继承的学习 然后下节是多态继承
// 派生类不集成基类的构造函数, 所以将构造函数设置成虚函数没什么意义
// 公有继承: is-a关系
#ifndef 会员管理_H_
#define 会员管理_H_
#include <string>
using std::string;
class TableTennisPlayer
{
private:
string strFirstName;
string strLastName;
bool isHasTable;
public:
TableTennisPlayer(const string & fn = "FirstName", const string & ln = "LastName", bool ht = false);
void ShowName() const;
bool GetisHasTable() const { return isHasTable; }
void ResetTable(bool v) { isHasTable = v; }
};
class RatedPlayer : public TableTennisPlayer // 公有派生: 公有->公有 私有->成为派生类的一部分, 但是只能通过基类的公有和保护方法访问
// 派生类不继承基类的构造函数
{
private:
unsigned int rating;
public:
RatedPlayer(unsigned int r = 0, const string & fn = "fname", const string & ln = "lname", bool ht = false);
RatedPlayer(unsigned int r, const TableTennisPlayer & tp); // 派生类的构造函数必须给派生的新成员和基类的成员提供数据;
// 由于多态, tp也能是派生类 // 派生类的构造函数必须使用基类的构造函数(如果没有显式调用将会隐式调用默认构造函数);
// 创建派生类对象的时候, 程序首先创建基类对象, 这意味着基类对象应该在进入派生类构造函数之前被创建, C++使用成员初始化列表语法完成这种工作;
// 释放对象的顺序与创建的顺序相反, 先调用派生类对象的析构函数, 然后调用基类的析构函数;
unsigned int GetRating() const { return rating; }
void ResetRating(unsigned int r) { rating = r; }
};
#endif |
bf1dd79301f31da6f06f0008438c8a1ac43b42b8 | e0ea35e1f43be31fba61b7c727f0daf1d88ef77d | /day_05.cpp | f8960dd0a4b49b584170c42987a64d9686169da1 | [] | no_license | watmough/Advent-of-Code-2018 | 14d79eed1387bde5203dadb0d8cb7208aa638b31 | 8578e322a1c90ae3d64b2748db2a05e6d5164990 | refs/heads/master | 2020-04-09T01:09:43.226699 | 2018-12-17T10:11:22 | 2018-12-17T10:11:22 | 159,893,944 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,048 | cpp | day_05.cpp | // Advent of Code 2018
// Day 05 - Alchemical Reduction
#include "aoc.hpp"
using namespace std;
// React a polymer by reducing adjacent units
// E.g. assert(react(string("dabAcCaCBAcCcaDA"))==string("dabCBAcaDA"));
string react(const string& s)
{
auto sp = string(begin(s),begin(s)+1);
for (auto c=begin(s)+1;c!=end(s);++c )
if ((*c^sp.back())==('a'^'A')) sp.pop_back(); else sp.push_back(*c);
return sp;
}
int main(int argc, char* argv[])
{
// Part 1
auto text{react(read_input("day_05.txt").front())};
cout << "Part 1: Polymer length: " << text.length() << "\n";
// Part 2 - Find shortest with 1 unit removed
auto shortest{text.length()};
for (auto u{'a'};u<='z';++u) {
auto textpp{text};
textpp.erase(std::remove(textpp.begin(), textpp.end(), u), textpp.end());
textpp.erase(std::remove(textpp.begin(), textpp.end(), toupper(u)), textpp.end());
shortest = min(shortest,react(textpp).length());
}
cout << "Part 2: Shortest polymer: " << shortest << "\n";
}
|
37bf4369339896c0482b1f222bd870adae2e0599 | d987cf37f26d25a760cd16c96c8af8a77de8bb3c | /firmware/src/keyboardcontroller.cpp | 290227f29ddb519cc7adebc7ee6318bd5d6c32ab | [] | no_license | Inkering/CozyPad | 51bcff3c1f66b1f2234deb645d9a884bad5257fb | b3f3a7c70eb73d2843234a0543c1bc760a89d66a | refs/heads/master | 2021-01-05T08:15:54.471712 | 2020-04-03T16:06:03 | 2020-04-03T16:06:03 | 240,947,750 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 419 | cpp | keyboardcontroller.cpp | /**
* Cozypad Keyboard Project
* Keyboard.cpp
* Dieter Brehm, Sam Daitzman
* Simple representation of a keyboard matrix,
* with scanning, repeat(hold), tapping, N-key rollover, and other
* processing.
*/
#include "Arduino.h"
#include "keyboardcontroller.hpp"
KeyboardController::KeyboardController() {}
void KeyboardController::boardLoop() {
// run the matrix loop, sending pressed
masterMatrix.operate();
}
|
b92e11c1252439437ea6dd18b1ca2a85369a9ad0 | 6c55459a18b4de6c0f8d209eb119baa481456d2b | /qt/study/xml/readXml/src/mainApplication.cpp | 4c022569decd89661722197fe557df1bc787e350 | [] | no_license | pennazhang/study | 0dfb88309a43c27ddab288cb349fb9bb678bce3c | 120cd47f1168c79847a51c2a8259fe6e3c3823fe | refs/heads/master | 2021-10-26T14:44:11.302585 | 2021-10-08T06:29:20 | 2021-10-08T06:29:20 | 238,823,362 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 811 | cpp | mainApplication.cpp | #include "mainApplication.h"
#include <QTime>
#include <QNetworkConfigurationManager>
#include <qnetworkaccessmanager.h>
#include <QUrl>
#include <QNetworkRequest>
#include <QDirIterator>
#include <QDebug>
#include <QThread>
#include <QString>
#include <QtCore/qmath.h>
#define QUIT_TIME_IN_SECOND 30
MainApplication::MainApplication(int argc, char *argv[])
: QCoreApplication(argc, argv)
{
m_pTimer_CmdLoop = new QTimer(this);
m_pTimer_CmdLoop->start(500);
connect(m_pTimer_CmdLoop, SIGNAL(timeout()), this, SLOT(onTimer_CmdLoop()));
}
MainApplication::~MainApplication()
{
}
void MainApplication::onTimer_CmdLoop()
{
static int index = 0;
index++;
g_stdOut << index << "... ";
g_stdOut.flush();
if (index == 10)
{
g_stdOut << endl;
exit(0);
}
}
|
9d36082d65c8444765a835f342f65ec9ce594cf0 | d543fc54f17e17eb6f6ad2a8c146efb0c90af3fb | /mainwindow.h | d59e59f119d5f1ce5418e8b6dd19b0bbfb7af258 | [] | no_license | khladnokrovnaya/lab2_2 | 5d14659708e63fd5ac03bd72d42a66f0d12efb86 | 3caed3805d81cbd5a9a16572fa3c02e24da72cb9 | refs/heads/main | 2023-01-29T15:31:02.899983 | 2020-12-12T14:01:12 | 2020-12-12T14:01:12 | 320,843,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 768 | h | mainwindow.h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "vector"
#include "author.h"
#include "QMessageBox"
#include <QFileDialog>
#include "QHBoxLayout"
#include "qdynamicauthor.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void AddAuthor(Author * author);
private slots:
void on_pushButton_clicked();
void on_loadFileBtn_clicked();
void on_pushButton_3_clicked();
void on_createCollectionBtn_clicked();
void onDestroyedAuthor(int id);
private:
Ui::MainWindow *ui;
QHBoxLayout* scrollLayout;
std::vector<Author*> authors;
};
#endif // MAINWINDOW_H
|
3043424d5853c522f84a2420c3cc2c05a22472c0 | 67f959dbd41b248d8a9fd7f1b5d0438651a5883d | /Arrays-Implementation/reverseString/main.cpp | 900460ef87188d0438264fda47de52cb7ad0d484 | [] | no_license | Omar-Hosni/Data-Structures-and-Algorithms | 517f4286b5400a13bc649051903cbaaf2dd8f0f2 | 844eaed6d1039d426212b9135e8fbe7633b0a509 | refs/heads/master | 2023-06-07T20:27:24.668385 | 2023-05-31T14:36:22 | 2023-05-31T14:36:22 | 286,316,218 | 1 | 0 | null | 2020-08-09T21:01:25 | 2020-08-09T21:01:24 | null | UTF-8 | C++ | false | false | 455 | cpp | main.cpp | #include<bits/stdc++.h>
using namespace std;
int main() {
// let us take input from the user for this one.
string str;
cout<<"Enter String of your choice..."<<endl;
getline(cin, str);
cout<<"Entered String is: "<<str<<endl;
// reverse(str.begin(), str.end()); method - 1 using built-in library
cout<<"Reversed String is: "<<endl;
for(int i = str.length() - 1; i >= 0; i--) {
cout<<str[i];
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.