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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
34079ebea6528d32f9652139726219b2bea58077 | 398b94d55b0729cd6b45b0b7263cb24ab134a698 | /CPSC591-Project/SSAOUI.cpp | 11c7684861f3e0026b366703c0d0e27d71b5a163 | [] | no_license | DannyPhantom/SSAO-Viewer | 49491d78091569b4b0073e4c5a1a7d9d1861c008 | ca0838818ca7785d1f76fb6683e281481978c85f | refs/heads/master | 2021-06-14T15:27:52.191876 | 2016-12-25T04:16:39 | 2016-12-25T04:16:39 | 74,872,592 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,495 | cpp | SSAOUI.cpp | #include "SSAOUI.h"
SSAOUI::SSAOUI(GLuint program) : program(program)
{
setup();
isHidden = false;
}
SSAOUI::~SSAOUI()
{
}
void SSAOUI::draw() {
if (!isHidden) {
background->draw(program);
firstPassParamsText->draw(program);
firstPassParamsSamplesNumberText->draw(program);
firstPassNumberOfSamplesTrackbar->render();
firstPassParamsSamplesNumberMinText->draw(program);
firstPassParamsSamplesNumberMaxText->draw(program);
firstPassParamsRadiusText->draw(program);
firstPassRadiusTrackbar->render();
firstPassParamsRadiusMinText->draw(program);
firstPassParamsRadiusMaxText->draw(program);
secondPassParamsText->draw(program);
secondPassParamsSamplesNumberText->draw(program);
secondPassNumberOfSamplesTrackbar->render();
secondPassParamsSamplesNumberMinText->draw(program);
secondPassParamsSamplesNumberMaxText->draw(program);
secondPassParamsRadiusText->draw(program);
secondPassRadiusTrackbar->render();
secondPassParamsRadiusMinText->draw(program);
secondPassParamsRadiusMaxText->draw(program);
hideButton->render(program);
}
else {
backgroundHidden->draw(program);
showButton->render(program);
}
}
void SSAOUI::setup() {
Texture *backgroundTexture = new Texture(GL_TEXTURE_2D, "Textures/backgroundTexture.png");
backgroundTexture->Load();
background = new TexturedObject2D(backgroundTexture, glm::vec2(0.75, 0.6), 0.25, 0.4);
Texture *firstPassParamsTextTexture = new Texture(GL_TEXTURE_2D, "Textures/firstPassParametersText.png");
firstPassParamsTextTexture->Load();
firstPassParamsText = new TexturedObject2D(firstPassParamsTextTexture, glm::vec2(0.75, 0.95), 0.2, 0.05);
Texture *firstPassParamsSamplesNumberTextTexture = new Texture(GL_TEXTURE_2D, "Textures/ssaoParametersSampleNumberText.png");
firstPassParamsSamplesNumberTextTexture->Load();
firstPassParamsSamplesNumberText = new TexturedObject2D(firstPassParamsSamplesNumberTextTexture, glm::vec2(0.75, 0.85), 0.1, 0.03);
firstPassNumberOfSamplesTrackbar = new TrackBar(8, 256, 0.17, 0.015, program);
firstPassNumberOfSamplesTrackbar->setCenter(glm::vec2(0.75, 0.8));
firstPassNumberOfSamplesTrackbar->setColor(glm::vec3(0.3, 0.3, 0.3));
firstPassNumberOfSamplesTrackbar->setCurrentValue(32);
Texture *firstPassParamsSamplesNumberMinTextTexture = new Texture(GL_TEXTURE_2D, "Textures/8.png");
firstPassParamsSamplesNumberMinTextTexture->Load();
firstPassParamsSamplesNumberMinText = new TexturedObject2D(firstPassParamsSamplesNumberMinTextTexture, glm::vec2(0.565, 0.8), 0.015, 0.015);
Texture *firstPassParamsSamplesNumberMaxTextTexture = new Texture(GL_TEXTURE_2D, "Textures/256.png");
firstPassParamsSamplesNumberMaxTextTexture->Load();
firstPassParamsSamplesNumberMaxText = new TexturedObject2D(firstPassParamsSamplesNumberMaxTextTexture, glm::vec2(0.95, 0.8), 0.03, 0.015);
Texture *firstPassParamsRadiusTextTexture = new Texture(GL_TEXTURE_2D, "Textures/radiusText.png");
firstPassParamsRadiusTextTexture->Load();
firstPassParamsRadiusText = new TexturedObject2D(firstPassParamsRadiusTextTexture, glm::vec2(0.75, 0.75), 0.04, 0.03);
firstPassRadiusTrackbar = new TrackBar(1, 10, 0.17, 0.015, program);
firstPassRadiusTrackbar->setCenter(glm::vec2(0.75, 0.7));
firstPassRadiusTrackbar->setColor(glm::vec3(0.3, 0.3, 0.3));
firstPassRadiusTrackbar->setCurrentValue(1);
Texture *firstPassParamsRadiusMinTextTexture = new Texture(GL_TEXTURE_2D, "Textures/1.png");
firstPassParamsRadiusMinTextTexture->Load();
firstPassParamsRadiusMinText = new TexturedObject2D(firstPassParamsRadiusMinTextTexture, glm::vec2(0.565, 0.70), 0.015, 0.015);
Texture *firstPassParamsRadiusMaxTextTexture = new Texture(GL_TEXTURE_2D, "Textures/10.png");
firstPassParamsRadiusMaxTextTexture->Load();
firstPassParamsRadiusMaxText = new TexturedObject2D(firstPassParamsRadiusMaxTextTexture, glm::vec2(0.9425, 0.70), 0.022, 0.015);
Texture *secondPassParamsTextTexture = new Texture(GL_TEXTURE_2D, "Textures/secondPassParametersText.png");
secondPassParamsTextTexture->Load();
secondPassParamsText = new TexturedObject2D(secondPassParamsTextTexture, glm::vec2(0.75, 0.60), 0.2, 0.05);
Texture *secondPassParamsSamplesNumberTextTexture = new Texture(GL_TEXTURE_2D, "Textures/ssaoParametersSampleNumberText.png");
secondPassParamsSamplesNumberTextTexture->Load();
secondPassParamsSamplesNumberText = new TexturedObject2D(secondPassParamsSamplesNumberTextTexture, glm::vec2(0.75, 0.50), 0.1, 0.03);
secondPassNumberOfSamplesTrackbar = new TrackBar(8, 256, 0.17, 0.015, program);
secondPassNumberOfSamplesTrackbar->setCenter(glm::vec2(0.75, 0.45));
secondPassNumberOfSamplesTrackbar->setColor(glm::vec3(0.3, 0.3, 0.3));
secondPassNumberOfSamplesTrackbar->setCurrentValue(32);
Texture *secondPassParamsSamplesNumberMinTextTexture = new Texture(GL_TEXTURE_2D, "Textures/8.png");
secondPassParamsSamplesNumberMinTextTexture->Load();
secondPassParamsSamplesNumberMinText = new TexturedObject2D(secondPassParamsSamplesNumberMinTextTexture, glm::vec2(0.565, 0.45), 0.015, 0.015);
Texture *secondPassParamsSamplesNumberMaxTextTexture = new Texture(GL_TEXTURE_2D, "Textures/256.png");
secondPassParamsSamplesNumberMaxTextTexture->Load();
secondPassParamsSamplesNumberMaxText = new TexturedObject2D(secondPassParamsSamplesNumberMaxTextTexture, glm::vec2(0.95, 0.45), 0.03, 0.015);
Texture *secondPassParamsRadiusTextTexture = new Texture(GL_TEXTURE_2D, "Textures/radiusText.png");
secondPassParamsRadiusTextTexture->Load();
secondPassParamsRadiusText = new TexturedObject2D(secondPassParamsRadiusTextTexture, glm::vec2(0.75, 0.40), 0.04, 0.03);
secondPassRadiusTrackbar = new TrackBar(1, 10, 0.17, 0.015, program);
secondPassRadiusTrackbar->setCenter(glm::vec2(0.75, 0.35));
secondPassRadiusTrackbar->setColor(glm::vec3(0.3, 0.3, 0.3));
secondPassRadiusTrackbar->setCurrentValue(5);
Texture *secondPassParamsRadiusMinTextTexture = new Texture(GL_TEXTURE_2D, "Textures/1.png");
secondPassParamsRadiusMinTextTexture->Load();
secondPassParamsRadiusMinText = new TexturedObject2D(secondPassParamsRadiusMinTextTexture, glm::vec2(0.565, 0.35), 0.015, 0.015);
Texture *secondPassParamsRadiusMaxTextTexture = new Texture(GL_TEXTURE_2D, "Textures/10.png");
secondPassParamsRadiusMaxTextTexture->Load();
secondPassParamsRadiusMaxText = new TexturedObject2D(secondPassParamsRadiusMaxTextTexture, glm::vec2(0.9425, 0.35), 0.022, 0.015);
Texture *hideButtonTextureActive = new Texture(GL_TEXTURE_2D, "Textures/hideButtonActive.png");
hideButtonTextureActive->Load();
Texture *hideButtonTextureInactive = new Texture(GL_TEXTURE_2D, "Textures/hideButtonInactive.png");
hideButtonTextureInactive->Load();
TexturedObject2D *hideButtonTexturedObjectActive = new TexturedObject2D(hideButtonTextureActive, glm::vec2(0.75, 0.27), 0.05, 0.04);
TexturedObject2D *hideButtonTexturedObjectInactive = new TexturedObject2D(hideButtonTextureInactive, glm::vec2(0.75, 0.27), 0.05, 0.04);
hideButton = new Button(hideButtonTexturedObjectInactive, hideButtonTexturedObjectActive, this);
Texture *backgroundHiddenTexture = new Texture(GL_TEXTURE_2D, "Textures/backgroundTexture.png");
backgroundHiddenTexture->Load();
backgroundHidden = new TexturedObject2D(backgroundHiddenTexture, glm::vec2(0.9, 0.9), 0.1, 0.1);
Texture *showButtonTextureActive = new Texture(GL_TEXTURE_2D, "Textures/showButtonActive.png");
showButtonTextureActive->Load();
Texture *showButtonTextureInactive = new Texture(GL_TEXTURE_2D, "Textures/showButtonInactive.png");
showButtonTextureInactive->Load();
TexturedObject2D *showButtonTexturedObjectActive = new TexturedObject2D(showButtonTextureActive, glm::vec2(0.9, 0.90), 0.05, 0.04);
TexturedObject2D *showButtonTexturedObjectInactive = new TexturedObject2D(showButtonTextureInactive, glm::vec2(0.9, 0.90), 0.05, 0.04);
showButton = new Button(showButtonTexturedObjectInactive, showButtonTexturedObjectActive, this);
}
bool SSAOUI::mousePressed(float x, float y) {
if (!isHidden) {
return firstPassNumberOfSamplesTrackbar->mousePressed(x, y)
|| firstPassRadiusTrackbar->mousePressed(x, y)
|| secondPassNumberOfSamplesTrackbar->mousePressed(x, y)
|| secondPassRadiusTrackbar->mousePressed(x, y)
|| hideButton->mousePressed(x, y);
}
else {
return showButton->mousePressed(x, y);
}
}
void SSAOUI::mouseReleased() {
firstPassNumberOfSamplesTrackbar->mouseReleased();
firstPassRadiusTrackbar->mouseReleased();
secondPassNumberOfSamplesTrackbar->mouseReleased();
secondPassRadiusTrackbar->mouseReleased();
hideButton->mouseReleased();
showButton->mouseReleased();
}
void SSAOUI::mouseMoved(float newX, float newY) {
firstPassNumberOfSamplesTrackbar->setNewMousePosition(newX, newY);
firstPassRadiusTrackbar->setNewMousePosition(newX, newY);
secondPassNumberOfSamplesTrackbar->setNewMousePosition(newX, newY);
secondPassRadiusTrackbar->setNewMousePosition(newX, newY);
}
int SSAOUI::getFirstPassNumberOfSamples() {
return (int)floor(firstPassNumberOfSamplesTrackbar->getCurrentValue());
}
float SSAOUI::getFirstPassRadius() {
return firstPassRadiusTrackbar->getCurrentValue();
}
int SSAOUI::getSecondPassNumberOfSamples() {
return (int)floor(secondPassNumberOfSamplesTrackbar->getCurrentValue());
}
float SSAOUI::getSecondPassRadius() {
return secondPassRadiusTrackbar->getCurrentValue();
}
void SSAOUI::setIsHidden(bool isHidden) {
this->isHidden = isHidden;
}
void SSAOUI::onButtonClick(Button *button) {
}
void SSAOUI::onButtonRelease(Button *button) {
isHidden = !isHidden;
} |
431e1433c8986a5245bfc29635fb48c35b686593 | aeb60a81cf5ef9c9340405a5661d5191f199d629 | /Verkefni 1 b2/include/Superhero.h | 513ef09fbee3822b733560e73bb32e69395468e9 | [] | no_license | sjofno17/Turtles-Pizzaria | 66926b0aab9ffecc9315aa38d5e253f679620e6c | 4a375f21871c0bfd9b1143edef3d07461fe5f8ca | refs/heads/master | 2021-08-30T02:28:59.772064 | 2017-12-15T18:10:29 | 2017-12-15T18:10:29 | 112,354,614 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 481 | h | Superhero.h | #ifndef SUPERHERO_H
#define SUPERHERO_H
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Superhero
{
public:
Superhero();
Superhero(char name[60], int age, char superpower, int num_heroes);
friend ostream& operator << (ostream& out, const Superhero& super);
friend istream& operator >> (istream& in, Superhero& super);
private:
char name[60];
int age;
char superpower;
int num_heroes;
};
#endif // SUPERHERO_H
|
7c7a132e8b0c50cf41ad6d72d7573b72c3c57462 | 32b5beff459a4e130c3b231e32d717bed4178a1c | /include/z5/compression/compressor_base.hxx | 9a40e517d0d8f15eff9993880426ad7c221c83d3 | [
"MIT"
] | permissive | constantinpape/z5 | 9deb76fe52a1335dac7ef49e85c40cf7efbb8887 | bd5cb52782a9cabf534ea77ba0823f207c8eccb8 | refs/heads/master | 2023-07-06T15:58:13.279554 | 2023-07-04T07:26:21 | 2023-07-04T07:26:21 | 101,700,504 | 94 | 28 | MIT | 2023-07-04T07:26:23 | 2017-08-29T00:31:10 | C++ | UTF-8 | C++ | false | false | 655 | hxx | compressor_base.hxx | #pragma once
#include <vector>
#include "z5/types/types.hxx"
namespace z5 {
namespace compression {
// abstract basis class for compression
template<typename T>
class CompressorBase {
public:
//
// API -> must be implemented by child classes
//
virtual ~CompressorBase() {}
virtual void compress(const T *, std::vector<char> &, std::size_t) const = 0;
virtual void decompress(const std::vector<char> &, T *, std::size_t) const = 0;
virtual types::Compressor type() const = 0;
virtual void getOptions(types::CompressionOptions &) const = 0;
};
}
} // namespace::z5
|
c0d8f5aedd8cb0bc541f0fed94d0172e3d049bf1 | c5e26167d000f9d52db0a1491c7995d0714f8714 | /洛谷/P2042 [NOI2005]维护数列.cpp | 3da69404783e2390b402c0a8176bc768e3ef4623 | [] | no_license | memset0/OI-Code | 48d0970685a62912409d75e1183080ec0c243e21 | 237e66d21520651a87764c385345e250f73b245c | refs/heads/master | 2020-03-24T21:23:04.692539 | 2019-01-05T12:38:28 | 2019-01-05T12:38:28 | 143,029,281 | 18 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,006 | cpp | P2042 [NOI2005]维护数列.cpp | // luogu-judger-enable-o2
// ==============================
// author: memset0
// website: https://memset0.cn
// ==============================
#include <bits/stdc++.h>
#define ll long long
#define rep(i,l,r) for (int i = l; i <= r; i++)
#define getc(x) getchar(x)
#define putc(x) putchar(x)
template <typename T> inline void read(T &x) {
x = 0; register char ch; register bool fl = 0;
while (ch = getc(), ch < 48 || 57 < ch) fl ^= ch == '-'; x = (ch & 15);
while (ch = getc(), 47 < ch && ch < 58) x = (x << 1) + (x << 3) + (ch & 15);
if (fl) x = -x;
}
template <typename T> inline void readc(T &x) {
while (x = getc(), !islower(x) && !isupper(x));
}
template <typename T> inline void print(T x, char c = ' ') {
static int buf[40];
if (x == 0) { putc('0'); putc(c); return; }
if (x < 0) putc('-'), x = -x;
for (buf[0] = 0; x; x /= 10) buf[++buf[0]] = x % 10 + 48;
while (buf[0]) putc((char) buf[buf[0]--]);
putc(c);
}
const int maxn = 4000010;
#define inf (1000000000)
#define max2(a,b) std::max(a,b)
#define max3(a,b,c) std::max(a,std::max(b,c))
int n, m, x, y, z, k, l, v, rt, cnt, opt;
int a[maxn], siz[maxn], val[maxn], rnd[maxn], ch[maxn][2];
int sum[maxn], lmax[maxn], rmax[maxn], smax[maxn];
int tag[maxn], rev[maxn];
void read_opt(int &x) {
register char ch;
while (ch = getc(), !isupper(ch));
if (ch == 'I') x = 1;
else if (ch == 'D') x = 2;
else if (ch == 'R') x = 4;
else if (ch == 'G') x = 5;
else {
getc(), ch = getc();
if (ch == 'K') x = 3;
else x = 6;
}
while (ch = getc(), ch != '\n' && ch != ' ');
}
inline int newnode(int v) {
int u = ++cnt;
siz[u] = 1, val[u] = v, rnd[v] = rand();
lmax[u] = rmax[u] = smax[u] = v;
ch[u][0] = ch[u][1] = 0;
rev[u] = 0, tag[u] = inf;
return u;
}
inline void pushup_tag(int u, int v) {
if (!u) return;
tag[u] = val[u] = v, rev[u] = 0;
sum[u] = v * siz[u];
lmax[u] = rmax[u] = smax[u] = std::max(val[u], sum[u]);
}
inline void pushup_rev(int u) {
if (!u) return;
rev[u] ^= 1;
std::swap(ch[u][0], ch[u][1]);
std::swap(lmax[u], rmax[u]);
}
inline void pushdown(int u) {
if (tag[u] ^ inf) {
// printf("pushdown tag %d(%d)\n", u, val[u]);
pushup_tag(ch[u][0], tag[u]);
pushup_tag(ch[u][1], tag[u]);
tag[u] = inf;
}
if (rev[u]) {
// printf("pushdown rev %d(%d)\n", u, val[u]);
pushup_rev(ch[u][0]);
pushup_rev(ch[u][1]);
rev[u] = 0;
}
}
inline void update(int u) {
pushdown(u);
siz[u] = siz[ch[u][0]] + siz[ch[u][1]] + 1;
sum[u] = sum[ch[u][0]] + sum[ch[u][1]] + val[u];
lmax[u] = max2(lmax[ch[u][0]], sum[ch[u][0]] + val[u] + std::max(lmax[ch[u][1]], 0));
rmax[u] = max2(rmax[ch[u][1]], sum[ch[u][1]] + val[u] + std::max(rmax[ch[u][0]], 0));
smax[u] = max3(smax[ch[u][0]], smax[ch[u][1]], max2(rmax[ch[u][0]], 0) + val[u] + max2(lmax[ch[u][1]], 0));
}
int build(int l, int r) {
if (l > r) return 0;
int mid = (l + r) >> 1;
int u = newnode(a[mid]);
ch[u][0] = build(l, mid - 1);
ch[u][1] = build(mid + 1, r);
return update(u), u;
}
int merge(int x, int y) {
if (!x || !y) return x | y;
if (rnd[x] < rnd[y]) {
pushdown(x);
ch[x][1] = merge(ch[x][1], y);
return update(x), x;
} else {
pushdown(y);
ch[y][0] = merge(x, ch[y][0]);
return update(y), y;
}
}
void split(int u, int v, int &x, int &y) {
if (!u) return (void)(x = y = 0);
pushdown(u);
if (v > siz[ch[u][0]]) {
x = u, split(ch[x][1], v - siz[ch[u][0]] - 1, ch[x][1], y);
} else {
y = u, split(ch[y][0], v, x, ch[y][0]);
}
update(u);
}
void dfs(int u) {
pushdown(u);
// update(u);
if (ch[u][0]) dfs(ch[u][0]);
// printf("%d : %d %d %d\n", u, val[u], sum[u], siz[u]);
print(val[u]);
if (ch[u][1]) dfs(ch[u][1]);
}
int main() {
// freopen("INPUT", "r", stdin);
// freopen("OUTPUT", "w", stdout);
srand(20040725);
read(n), read(m);
for (int i = 1; i <= n; i++)
read(a[i]);
rt = build(1, n);
lmax[0] = rmax[0] = smax[0] = -inf;
for (int i = 1; i <= m; i++) {
read_opt(opt);
switch (opt) {
case 1:
read(k), read(n);
for (int i = 1; i <= n; i++)
read(a[i]);
split(rt, k, x, z);
y = build(1, n);
rt = merge(x, merge(y, z));
break;
case 2:
read(k), read(v);
split(rt, k - 1, x, y);
split(y, v, y, z);
rt = merge(x, z);
break;
case 3:
read(k), read(l), read(v);
split(rt, k - 1, x, y);
split(y, l, y, z);
pushup_tag(y, v);
rt = merge(x, merge(y, z));
break;
case 4:
read(k), read(l);
split(rt, k - 1, x, y);
split(y, l, y, z);
pushup_rev(y);
rt = merge(x, merge(y, z));
break;
case 5:
read(k), read(l);
split(rt, k - 1, x, y);
split(y, l, y, z);
print(sum[y], '\n');
rt = merge(x, merge(y, z));
break;
case 6:
print(smax[rt], '\n');
break;
}
// dfs(rt), putc('\n');
// printf("%d %d %d\n", lmax[0], rmax[0], smax[0]);
}
return 0;
} |
c319d63e45bc5c303276d80fa168ad84f8226f62 | 50891e4fa0c216d2772e2803f8d770b2eb520b36 | /include/template.h | abf6baa051b3a142b97eaa2614af32ef6b355057 | [] | no_license | LingDar77/cppl | c2453b8252ac2fc07e4b0c357a9f5e2f4495c11a | ebef4f11292149c0215982fc1f299b285415a127 | refs/heads/master | 2023-03-08T04:31:56.911256 | 2021-02-28T07:32:42 | 2021-02-28T07:32:42 | 340,648,581 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,079 | h | template.h | //todo we can define a universal template to avoid define kindds of functions for every kind
template <typename T> //? typename T,... is a template parameter list which should not be empty
int compare(const T &t1, const T &t2)
{
if (t1 < t2)
return -1;
if (t2 < t1)
return 1;
return 0;
}
//! besides we can use nontype parameter to express a value,but this parameter must be a const value
template <unsigned N, unsigned M>
int compare(const char (&p1)[N], const char (&p2)[M])
{
return strcmp(p1, p2);
}
//! template can also be inline or constexpr but inline or constexpr should be put behind the temlate
//! besides, to program nontype code, we have to follow two laws:
//? parameters should be reference to const
//* use const reference makes sure our function can be used in types which can not be copy, and makes it faster
//? operators in function body can only use <
//* only use operator< can lower the request to this type, but actually we can use less<T> to define our function
template <class T> //? in template, class equals typename
int cmp(const T &t1, const T &t2) //! in this version, pointer can be alright
{
if (less<T>(t1, t2))
return -1;
if (less<T>(t2, t1))
return 1;
//? less<T> will call <, so this version is not very well
//? the two pointers point two different arrays, its behavers are undefined
return 0;
}
//! btw, head files usually contain declarations and definations of template functions or template classes
//* in some cases, when many files instantiate a same template costs much
//* in this case, we can use explicit instantiation to avoid extra cost
// extern template declaration //explicit instantiate declaration
// template declaration //explicit instantiate definition
// in this form, declaration means a type or a function declaration
#include "Blob.h"
#include <string>
extern template class Blob<std::string>; //declarations
template int compare(const int&,const int&); //definition
template<typename A>
bool comp(const A& a1,const A& a2); |
58c8aeae4247b98662e7e9a735a92f96e701ee96 | 3423d0d2bcff69ba758ccd082e68e578c8800b20 | /ArpDetect/config.h | d4c172d5e2700748562f69e0a82361e784b14a53 | [] | no_license | crspecter/IP-conflict-detection-telnet-shell | 45f10dbf350c2005929e269eb0defc323f41d2ef | b76ea032e742c27773dfb6b4ca9ec4c5ecc6a43f | refs/heads/master | 2021-01-10T13:19:09.095708 | 2015-11-04T01:39:45 | 2015-11-04T01:39:45 | 45,507,225 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,180 | h | config.h | #ifndef __CONFIG_H__
#define __CONFIG_H__
#include <map>
#include <string>
#include <cstring>
#include <cstdint>
class Config_parser
{
typedef std::map<std::string, std::string> MAP_LOCATION;
typedef std::map<std::string, MAP_LOCATION > MAP_TOTAL;
typedef std::map<std::string, std::string>::iterator value_it;
typedef std::map<std::string, MAP_LOCATION >::iterator seg_it;
public:
Config_parser();
void parse_file();
std::string get_string(const std::string &seg, const std::string &key, std::string def = "");
uint32_t get_int(const std::string &seg, const std::string &key, uint32_t def = 0);
private:
void trim_space(std::string &dest_str);
bool start_with(const std::string& dst_str, const std::string& targ);
bool end_with(const std::string& dst_str, const std::string& targ);
void get_process_name();
bool is_comment(std::string line);
bool is_segment(std::string line);
bool is_space_line(std::string line);
std::string get_segment(std::string &line);
bool get_key_and_value(std::string& line, std::string &key, std::string &value);
private:
std::string config_file_name;
MAP_TOTAL parse_ret;
};
#endif |
70afd4ab2f976244e132eda19e32d39e43c46f6f | 1cbd1e299feefb329528571c44270b5014b58ec8 | /opencketch_code/simulation/os_counterrevanalyze.cc | 8f5b5622bd259c308446c1b80be46cfcd73999a8 | [] | no_license | SDNTHU/SDN | 637e68896f190784f4e041e65be78e1ff2f87522 | 5fc0bd169086b14f498efc9d86055802f4dbf91d | refs/heads/master | 2021-01-23T03:04:02.918522 | 2014-05-02T13:01:48 | 2014-05-02T13:01:48 | 18,706,001 | 1 | 0 | null | 2014-04-13T16:16:02 | 2014-04-12T14:34:19 | null | UTF-8 | C++ | false | false | 8,837 | cc | os_counterrevanalyze.cc | #include "os_counterrevanalyze.h"
typedef vector<list<NodeType*> > GraphType;
OS_CounterRevAnalyze::OS_CounterRevAnalyze() {
uint32 table, j, k;
for (table = 0; table < REVERSIBLE_NUMROWS; table++) {
for (j = 0; j < REVERSIBLE_NUMDIVS; j++) {
revLookupTable[table][j].resize(8);
for (k = 0; k < 8; k++) {
//revLookupTable[table][j][k].resize(256);
}
}
}
}
OS_CounterRevAnalyze::~OS_CounterRevAnalyze(){}
void OS_CounterRevAnalyze::populateLookupTable(uint32 table,\
uint64 seed) {
int64views h;
int64views vx;
uint32 i, j, k;
uint8 i8, a8, k8, tmp;
// seeds[table] = seed[table];
// h(ip) = h1(ip1).h2(ip2).h3(ip3).h4(ip4) = val
// i: 0 thru 255 is what's in ip1, ip2 etc.
// j: 0 thru 3 is "which tuple" of ip
// k: 0 thru 7 is h(tuple)
// lookupTable[table][i][j] --> k
// revLookupTable[table][j][k] --> {i, i', i''}
// for (table = 0; table < rev::NUMTABLES; table++) {
h.as_int64 = seed;
for (i = 0; i < REVERSIBLE_NUMKEYS; i++) {
vx.as_int32s[0] = i;
i8 = vx.as_int8s[0];
for (j = 0; j < REVERSIBLE_NUMDIVS; j++) {
a8 = h.as_int8s[j];
k8 = os_dietz8to3(i, a8);
k = k8 & 7;
lookupTable[table][i][j] = k8;
revLookupTable[table][j][k].push_back(i8);
}
}
//}
}
void OS_CounterRevAnalyze::getPossibleKeys(uint32 table,\
list<uint8> &keys,\
uint32 div, uint32 bin){
uint32 i;
vector<uint8>* lKeys;
uint8 bin8 = ((bin >> (div*3)) & 7);
lKeys = &(revLookupTable[table][div][bin8]);
/*cout << lKeys->size() << " possible keys for div's bin # " \
<< (bin8 & 7) << ".\n";*/
for (i = 0; i < lKeys->size(); i++)
keys.push_back((*lKeys)[i]);
}
void OS_CounterRevAnalyze::changeDetection(uint32 table,\
list<uint32> &changes,\
double threshold){
uint32 i;
for(i = 0; i < REVERSIBLE_COUNTERSPERROW; i++)
if (get_count(table, i) > threshold)
changes.push_back(i);
}
double OS_CounterRevAnalyze::findThreshold(uint32 table,\
int numAnoms,\
double minThreshold){
uint32 count, numChgs, i;
vector<double> heavy_counts;
heavy_counts.clear();
// cout << "table " << table << "\n";
for(i = 0; i < REVERSIBLE_COUNTERSPERROW; i++){
count = get_count(table, i);
// cout << "count " << i << ": " << count << ", ";
if (count > minThreshold)
heavy_counts.push_back(count);
}
// cout << "\n";
numChgs = heavy_counts.size();
cout << "number of changes > " << minThreshold << ": " << numChgs << "\n";
if (numChgs == 0) return -1;
else if (numChgs <= numAnoms) return minThreshold;
sort(heavy_counts.begin(), heavy_counts.end());
return(heavy_counts[numChgs-numAnoms]);
// want not more than numAnoms returned
// (1, 3, 2, 2, 4) say numAnoms is 2,
// then threshold is [numChgs-numAnoms] --> 2
// will return only "4", not "4, 2, 2"
}
bool OS_CounterRevAnalyze::getKeys(uint32 iterSize,\
uint32 *maxThresh,\
list<uint32> &tempLst){
bool done = false;
uint32 table;
uint32 heavybins = 0;
vector<list<uint32> > bktLists(REVERSIBLE_NUMROWS);
unsigned int nextThresh;
for(table = 0; table < REVERSIBLE_NUMROWS; table++ ){
nextThresh = findThreshold(table, iterSize, *maxThresh);
if( nextThresh == -1.0 ) {done = true; break;}
else *maxThresh = nextThresh;
}
if (done) return done;
/*cout << "threshold for no more than " \
<< iterSize << " heavy bins in a table is "\
<< *maxThresh << "\n";*/
for(table = 0; table < REVERSIBLE_NUMROWS; table++ ){
bktLists[table].clear();
changeDetection(table, bktLists[table], *maxThresh);
heavybins += bktLists[table].size();
}
if (!heavybins) return (done=true);
/*cout << "found " << bktLists[0].size() << " heavy bins" \
" in table " << 0 << " and " << heavybins << " in all.\n";*/
GraphType graph;
uint32 div;
graph.clear();
/*cout << "cleared graph successfully.\n";*/
createNodes(graph, bktLists);
/*cout << "created nodes successfully.\n";*/
for(div = 0; div < REVERSIBLE_NUMDIVS; div++)
createLinks(graph, div);
/*cout << "created links successfully.\n";*/
tempLst.clear();
generateFullKeys(graph,tempLst);
/*cout << "generated full keys successfully.\n";*/
return done;
}
uint32 OS_CounterRevAnalyze::get_count(uint32 table, uint32 bin) { \
if (pCounts) return (*pCounts)[(table*REVERSIBLE_COUNTERSPERROW)+bin];
else return 100000;
}
void OS_CounterRevAnalyze::createNodes(GraphType &graph, \
const vector<list<uint32> > &bktLists){
uint32 div, table;
map<uint8, NodeType*> nodeMap;
list<uint32>::const_iterator bktListIt;
list<uint8> keys;
list<uint8>::iterator keyIt;
graph.resize(4);
for(div = 0; div < REVERSIBLE_NUMDIVS; div++){
nodeMap.clear();
for(table = 0; table < REVERSIBLE_NUMROWS; table++){
for(bktListIt = bktLists[table].begin();\
bktListIt != bktLists[table].end();\
bktListIt++){
/* cout << "div: " << div \
<< ", table: " << table\
<< ", *bktListIt: " << *bktListIt\
<< ".\n";*/
keys.clear();
getPossibleKeys(table, keys, div, *bktListIt);
//cout << "got possible keys for " << *bktListIt << ".\n";
for(keyIt = keys.begin(); keyIt != keys.end();\
keyIt++) {
NodeType *node = nodeMap[*keyIt];
if( node == NULL ) {
node = new NodeType(*keyIt, *bktListIt,\
table, REVERSIBLE_NUMROWS);
nodeMap[*keyIt] = node;
}
else {
if( node->bktLists[table].empty() ) node->numFound++;
node->bktLists[table].push_back(*bktListIt);
}
}
}
}
map<uint8, NodeType*>::iterator nodeMapIt;
for(nodeMapIt = nodeMap.begin();\
nodeMapIt != nodeMap.end();\
nodeMapIt++) {
NodeType *node = nodeMapIt->second;
if( (REVERSIBLE_NUMROWS - node->numFound) <= REVERSIBLE_R )
graph[div].push_back(node);
else delete node;
}
}
}
void OS_CounterRevAnalyze::createLinks(GraphType &graph, int startDiv){
if( startDiv >= 3 )
return; // cannot start at the last level
list<NodeType*> *l1List = &(graph[startDiv]);
list<NodeType*> *l2List = &(graph[startDiv+1]);
list<NodeType*> linkList;
for( list<NodeType*>::iterator l1It = l1List->
begin();
l1It != l1List->end();
l1It++ )
{
for( list<NodeType*>::iterator l2It = l2List->
begin();
l2It != l2List->end();
l2It++ )
{
NodeType *newNode = rIntersect(*l1It, *l2It);
if( newNode != NULL )
linkList.push_back(newNode);
} // End for...l2It
delete *l1It; // no longer need this node in level 1
}
// Delete all of the nodes in L2
for( list<NodeType*>
::iterator l2It = l2List->begin();
l2It != l2List->end();
l2It++ )
delete *l2It;
l1List->clear();
l2List->clear();
l2List->insert(l2List->end(), linkList.begin(), linkList.end());
}
NodeType* OS_CounterRevAnalyze::rIntersect(NodeType *node1, NodeType *node2){
NodeType *newNode = new NodeType;
newNode->bktLists.resize(REVERSIBLE_NUMROWS);
for( int tbl = 0; tbl < REVERSIBLE_NUMROWS; tbl++ )
{
list<uint32> *node1Lst = &(node1->bktLists[tbl]);
list<uint32> *node2Lst = &(node2->bktLists[tbl]);
list<uint32> *newLst = &(newNode->bktLists[tbl]);
listIntersect(*newLst, *node1Lst, *node2Lst);
if( newLst->empty() )
{
if( newNode->numFound >= REVERSIBLE_R )
{
delete newNode;
return NULL;
}
else
newNode->numFound++;
}
}
list<uint8> *keyLst = &(newNode->keyList);
keyLst->insert(keyLst->end(), node1->keyList.begin(), node1->keyList.end());
keyLst->insert(keyLst->end(), node2->keyList.begin(), node2->keyList.end());
return newNode;
}
void OS_CounterRevAnalyze::generateFullKeys(GraphType &graph,\
list<uint32> &resultList){
uint32 fullKey, div;
uint8 *keyDivided = (uint8 *)&fullKey;
list<NodeType*>::iterator lstIt;
list<uint8> *keyList;
list<uint8>::iterator keyIt;
for(lstIt = graph[3].begin(); lstIt != graph[3].end();
lstIt++ )
{
keyList = &((*lstIt)->keyList);
if( keyList->size() == 4 ){
div = 0;
for(keyIt = keyList->begin(); keyIt != keyList->end(); \
keyIt++, div++ )
keyDivided[div] = *keyIt;
resultList.push_back(fullKey);
}
//delete *lstIt;
}
}
void OS_CounterRevAnalyze::listIntersect(list<uint32> &outList, \
const list<uint32> &l1, \
const list<uint32> &l2){
outList.clear();
list<uint32>::const_iterator l1It = l1.begin();
list<uint32>::const_iterator l2It = l2.begin();
while( true )
{
if( (l1It == l1.end()) || (l2It == l2.end()) )
return;
if( *l1It > *l2It )
l2It++;
else if( *l1It < *l2It )
l1It++;
else
{
outList.push_back(*l1It);
l1It++;
l2It++;
}
}
};
|
282daf16f2c8a5c32850d56ca04daa976f2c72d2 | f7ace99e3f15df3a58aae465361033497dd85ea4 | /lab3/main/DoubleLinkedList.ino | fa6cceec0232e2be5df4e5973560e073c347aff2 | [] | no_license | matt5200/ee_474 | 05615b475a0d5431bf8e4b1f8a6526ff1e3c1977 | d7e826600c799c53e243f8ef990118554cdc3082 | refs/heads/master | 2020-03-30T04:41:27.597832 | 2018-12-09T02:29:32 | 2018-12-09T02:29:32 | 150,756,807 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,864 | ino | DoubleLinkedList.ino | #include <Arduino.h>
// Doubley Linked List
// Define TCB struct, holds task
// and task data
typedef struct TCB {
void (*myTask)(void*);
void* taskDataPtr;
} TCB;
// Define NodeTCB, holds TCB,
// next and prev node pointers
typedef struct NodeTCB {
TCB* func;
struct NodeTCB* prev;
struct NodeTCB* next;
} NodeTCB;
// Doubley Linked List methods
int currentLength;
void deleteNode(NodeTCB** front,NodeTCB** back, int index);
void insert(NodeTCB** front,NodeTCB** back, TCB* newNode2);
TCB removeNode(NodeTCB** front,NodeTCB** back);
TCB* getN(NodeTCB** front,NodeTCB** back, int index);
NodeTCB* getNode(NodeTCB** front,NodeTCB** back,int index);
// Insert node to doubley linked list
void insert(NodeTCB** front,NodeTCB** back, TCB* newNode2) {
NodeTCB* newNode = (NodeTCB*)malloc(sizeof( NodeTCB));
newNode->func = (TCB*)malloc(sizeof(TCB));
*newNode->func = *newNode2;
if (currentLength == 0) {
(*front) = newNode;
(*back) = newNode;
delay(100);
} else if (currentLength == 1) {
(*front)->next = newNode;
newNode->prev = *front;
*back = newNode;
} else {
(*back)->next = newNode;
newNode->prev = *back;
*back = newNode;
}
currentLength++;
}
// Remove node from back of doubley linked list
TCB removeNode(NodeTCB** front,NodeTCB** back){
NodeTCB* last = *back;
if (currentLength > 1) {
*back = last->prev;
free((*back)->next);
}
else {
free(*back);
free(*front);
}
currentLength--;
return *last->func;
}
// Delete node from index of list
void deleteNode(NodeTCB** front,NodeTCB** back, int index) {
if (index == currentLength - 1) {
removeNode(front, back);
return;
}
NodeTCB* rem = getNode(front, back, index);
if (index == 0) {
*front = (*front)->next;
free(rem);
(*front)->prev = NULL;
} else {
NodeTCB* behind = getNode(front, back, index - 1);
NodeTCB* inFront = getNode(front, back, index + 1);
behind->next = inFront;
inFront->prev = behind;
free(rem);
free(rem);
}
currentLength--;
return;
}
TCB* getN(NodeTCB** front,NodeTCB** back, int index) {
return (getNode(front, back, index))->func;
}
// Get node from location in doubley linked list
NodeTCB* getNode(NodeTCB** front,NodeTCB** back,int index) {
NodeTCB* result = *front;
for (int i = 0; i < index; i++) {
result = (result->next);
}
delay(1000);
return result;
}
|
748b756ff79fc0e84e02eb5ef1ed0c6b0e55a87f | dadcb9246781f271a75acd38c97683dc9c10e308 | /boostasiodemo/asio_example/http/server/sml.cc | 539137ca529eaf63b9eeef4911b38736f5e54e3f | [] | no_license | wCmJ/KB | b9b2e60e67f745b642c4cdfcc040b200682f7548 | 4a4595809c1d3afc1893ffd7c3db3f619b69a994 | refs/heads/main | 2023-04-16T12:54:58.685910 | 2021-04-25T03:51:49 | 2021-04-25T03:51:49 | 306,245,916 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,087 | cc | sml.cc |
#include <boost/sml.hpp>
struct StateMachine {
explicit StateMachine(Test* Test) : Test_(Test) {}
auto operator()() noexcept {
auto account_info_ready = [this] {
return Test_->session_.AccountInfoReady();
};
auto can_start = [this](const Start& e) { return CanStart(e); };
auto can_restart = [this](const Restart& e) { return CanStart(e); };
// clang-format off
return boost::sml::make_transition_table(
*"Power Off"_s + event<Start> [ can_start ] = "Connecting"_s,
"Power Off"_s + event<Restart> [ can_restart ] = "Connecting"_s,
"Power Off"_s + "Send"_e / [this] { FailAllCachedTransaction(); },
"Connecting"_s + "ManualConnect"_e / [this] { MayRaceImmediately(); },
"Connecting"_s + event<Connected> / [this](const auto& e) { OnConnected(e); } = "Connected"_s,
"Connecting"_s + "Shutdown"_e / [this] { StopRace(); } = "Power Off"_s,
"Connected"_s + event<Disconnected> / [this](const auto& e) { OnBackward(e.code); } = "Connecting"_s,
"Connected"_s [ account_info_ready ] / [this] { Register(); } = "Registering"_s,
"Connected"_s + "Shutdown"_e / [this] { StopRace(); Disconnect(); } = "Power Off"_s,
"Registering"_s + "Registered"_e = "Online"_s,
"Registering"_s + event<RegisterFailed> / [this](const auto& e) { Disconnect(); OnBackward(e.code); } = "Connecting"_s,
"Registering"_s + "Unregister"_e / defer,
"Registering"_s + "Shutdown"_e / [this] { StopRace(); Disconnect(); } = "Power Off"_s,
"Online"_s + event<Disconnected> / [this](const auto& e) { OnOffline(e.code); } = "Connecting"_s,
"Online"_s + "Unregister"_e / [this](const auto& e) { OnOffline(TestError::kLogout); } = "Unregistering"_s,
"Online"_s + "Shutdown"_e / defer,
"Online"_s + event<Restart> / defer,
"Online"_s + "Send"_e / [this] { SendCachedTransactions(); },
"Online"_s + event<HeartbeatEvent> / [this](const auto& e) { Heartbeat(e.reason); },
"Unregistering"_s + "Unregister Done"_e = "Connected"_s,
"Unregistering"_s + "Shutdown"_e / defer,
"Unregistering"_s + event<Restart> / defer,
"Registering"_s + event<Disconnected> / [] { assert(false); } = "Connecting"_s,
"Unregistering"_s + event<Disconnected> / [] { assert(false); } = "Connecting"_s,
"Power Off"_s + on_entry<_> / [this] { FailAllCachedTransaction(); OnShutdown(); },
"Connecting"_s + on_entry<_> / [this] { StartOrContinueRace(); },
"Unregistering"_s + on_entry<_> / [this] { Unregister(); },
"Online"_s + on_entry<_> / [this] { StopRace(); Heartbeat("heartbeat"); OnOnline(); },
"Online"_s + on_exit<_> / [this] { CancelHeartbeat(); }
);
// clang-format on
}
bool CanStart(const StartupBase& e) {
Test_->session_.SetUserID(e.uid);
Test_->session_.SetServiceToken(e.service_token);
Test_->session_.SetServiceSecurity(e.service_security);
if (Test_->session_.AccountInfoReady()) {
return true;
} else {
for (auto listener : Test_->online_listeners_)
if (auto locked_listener = listener.lock())
locked_listener->OnLoginFailed(TestError::kInvalidAccountInfo);
return false;
}
}
void StartOrContinueRace() {
Test_->connection_generator_->StartOrContinueRace();
}
void StopRace() { Test_->connection_generator_->StopRace(); }
void MayRaceImmediately() {
Test_->connection_generator_->MayRaceImmediately();
}
void OnConnected(const Connected& e) {
Test_->connection_ = e.connection;
Test_->connection_->SetDelegate(Test_->weak_from_this());
}
void Disconnect() {
if (Test_->connection_) {
Test_->connection_->SetDelegate({});
Test_->connection_->Finalise();
Test_->connection_.reset();
}
}
void Register() {
Test_->connection_->Register([=](std::error_code code) {
if (code) {
KwaiLogger::Error("Register failed with code {}[{}]", CODE);
for (auto listener : Test_->online_listeners_)
if (auto locked_listener = listener.lock())
locked_listener->OnLoginFailed(code);
if (INNER_SM) INNER_SM->process_event(RegisterFailed{code});
} else {
KwaiLogger::Info("Register succeeded.");
if (INNER_SM) INNER_SM->process_event("Registered"_e());
}
});
}
void Unregister() {
Test_->connection_->Unregister([=](std::error_code code) {
KwaiLogger::Info("Unregister done with code {}[{}]", CODE);
Test_->session_.ClearAccountInfo();
if (INNER_SM) INNER_SM->process_event("Unregister Done"_e());
});
}
void Heartbeat(const std::string& reason) {
CancelHeartbeat();
if (Test_->connection_)
Test_->connection_->Heartbeat(reason, [=](auto code) {
PrintDebugInfo();
ScheduleHeartbeat();
});
// TODO(Lynn) Shall we try connect if not connected?
}
void ScheduleHeartbeat() {
CancelHeartbeat();
heartbeat_timer_ =
Test_->Queue()->PostAfter(Test_->Config()->HeartbeatInterval(),
&StateMachine::Heartbeat, this, "heartbeat");
}
void CancelHeartbeat() {
if (heartbeat_timer_.IsValid()) Test_->Queue()->Cancel(&heartbeat_timer_);
}
void OnOnline() {
PrintDebugInfo();
Test_->latest_code_.clear();
for (auto listener : Test_->online_listeners_)
if (auto locked_listener = listener.lock()) locked_listener->OnOnline();
SendCachedTransactions();
}
void OnOffline(std::error_code code) {
Test_->latest_code_ = code;
for (auto listener : Test_->online_listeners_)
if (auto locked_listener = listener.lock())
locked_listener->OnOffline(code);
}
void OnShutdown() {
for (auto listener : Test_->online_listeners_)
if (auto locked_listener = listener.lock()) locked_listener->OnShutdown();
}
void OnBackward(std::error_code code) { Test_->latest_code_ = code; }
void SendCachedTransactions() {
if (Test_->connection_) {
KwaiLogger::Info("Test send transactions.");
for (auto transaction : Test_->transactions_)
Test_->connection_->SendMessage(transaction.second);
Test_->transactions_.clear();
} else if (!Test_->transactions_.empty()) {
KwaiLogger::Warn("Test not online, schedule to check timeout.");
Test_->ScheduleToCheckTimeout();
}
}
void FailAllCachedTransaction() {
decltype(Test_->transactions_) transactions =
std::move(Test_->transactions_);
for (auto transaction : transactions) {
transaction.second->SetErrorCode(TestError::kShutdown);
transaction.second->Complete();
}
}
template <class State, class Event>
void OnNoTransition(const State&, const Event&) {
KwaiLogger::Warn("No transition from {} with {}",
boost::sml::aux::get_type_name<State>(),
boost::sml::aux::get_type_name<Event>());
// TODO(Lynn) Record this to debug
}
void PrintDebugInfo() {
auto current_access_point = Test_->CurrentAccessPoint();
auto server_time =
std::chrono::system_clock::to_time_t(Test_->GetServerClock()->Now());
// FIXME(Lynn)
std::ostringstream oss;
oss << std::put_time(localtime(&server_time), "%Y-%m-%d %H:%M:%S");
KwaiLogger::Info(
"Test version is {}, AppId is {}, UserId is {}, InstanceId is {}, "
"Current Access Point is {}:{}, server time is {}",
Version(), Test_->GetAppId(), Test_->GetUserId(),
Test_->GetInstanceId(), current_access_point.first,
current_access_point.second, oss.str());
}
Test* Test_;
util::Queue::TaskHandle heartbeat_timer_;
};
enum ITest::State Test::State() const {
if (!SM) return ITest::kInit;
// clang-format off
if (SM->is("Power Off"_s)) return ITest::kInit;
else if (SM->is("Connecting"_s)) return ITest::kConnecting;
else if (SM->is("Connected"_s)) return ITest::kConnected;
else if (SM->is("Registering"_s)) return ITest::kRegistering;
else if (SM->is("Unregistering"_s)) return ITest::kUnregistering;
else if (SM->is("Online"_s)) return ITest::kOnline;
else return ITest::kInit;
// clang-format on
}
|
e9c0c5ce769e637c07d5175435c6f637c9420043 | f51a638ce5626b7b35a305cf27eb7edb0d058e8b | /filaDinamicaPessoa.hpp | a197c06da9197b487f28fb8620bc4e753b1f91bd | [] | no_license | brunobutka/trabalho-etapa1-estrutura1 | 2515c85be6ce0b5feb5236a718524cc830b8bb1d | 33b892d4eefbf3c0256dfda78b5efe0050981f29 | refs/heads/master | 2023-07-02T13:54:25.273859 | 2021-08-14T01:07:03 | 2021-08-14T01:07:03 | 395,846,314 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,874 | hpp | filaDinamicaPessoa.hpp | #ifndef _HPP_FILAPESSOA_DINAMICA
#define _HPP_FILAPESSOA_DINAMICA
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
#include "estruturas.hpp"
typedef estruturaPessoa DadoNoFilaPessoa;
struct NoFilaPessoa{
DadoNoFilaPessoa dado;
NoFilaPessoa *prox;
};
struct FilaPessoa{
NoFilaPessoa *inicio;
NoFilaPessoa *fim;
FilaPessoa() {
inicio = nullptr;
fim = nullptr;
}
};
void inicializaFPessoa(FilaPessoa *f){
f->inicio = nullptr;
f->fim = nullptr;
}
bool vaziaFPessoa(FilaPessoa *f){
if (!f->inicio)
return true;
else
return false;
}
bool enfileiraFPessoa(FilaPessoa *f, DadoNoFilaPessoa dado){
NoFilaPessoa *novo = new NoFilaPessoa();
if (!novo)
return false;
novo->dado = dado;
novo->prox = nullptr;
if (!f->inicio)
f->inicio = novo;
else
f->fim->prox = novo;
f->fim = novo;
return true;
}
bool desenfileiraFPessoa(FilaPessoa *f, DadoNoFilaPessoa *dado){
if (f->inicio){
*dado = f->inicio->dado;
NoFilaPessoa *apagar = f->inicio;
f->inicio = f->inicio->prox;
delete apagar;
if (!f->inicio)
f->fim = nullptr;
return true;
} else
return false;
}
bool espiaFPessoa(FilaPessoa* f, DadoNoFilaPessoa *dado){
if (f->inicio){
*dado = f->inicio->dado;
return true;
}
else
return false;
}
void mostraFPessoa(FilaPessoa *f){
if(f->inicio){
cout << "{";
NoFilaPessoa *no = f->inicio;
while (no){
cout << "[" << no->dado.nomePessoa;
cout << ", " << no->dado.sexo;
cout << ", " << no->dado.cpf;
cout << ", " << no->dado.idade;
cout << ", " << no->dado.pcd;
cout << ", " << no->dado.gestante << "]";
no = no->prox;
if(no)
cout << ", ";
}
cout << "}" << endl << endl;
} else
cout << "Fila vazia.\n\n";
}
/*bool buscaFPessoa(FilaPessoa *f, DadoNoFilaPessoa valor){
NoFilaPessoa *no = f->inicio;
while (no){
if(no->dado == valor)
return true;
no = no->prox;
}
return false;
}*/
void destroiFPessoa(FilaPessoa *f){
NoFilaPessoa *no = f->inicio;
while (no){
NoFilaPessoa *apagar = no;
no = no->prox;
delete apagar;
}
f->inicio = nullptr;
f->fim = nullptr;
}
void controlePessoas(FilaPessoa *f, DadoNoFilaPessoa *dado, int *tP, int *pSF, int *pSM, int *pD, int *mG){
NoFilaPessoa *no = f->inicio;
(*tP)--;
if(no->dado.sexo == 'F')
(*pSF)--;
else if(no->dado.sexo == 'M')
(*pSM)--;
if(no->dado.pcd == true)
(*pD)--;
if(no->dado.gestante == true)
(*mG)--;
}
#endif /// _HPP_FILAPESSOA_DINAMICA
|
9c487bd5be0994de37be75c35bc1d526f5fecedb | 3b91dfd4409513207575f2728918a1e2e484e13b | /trunk/test/xirang/ref_ptr.cpp | 47dc89c756f48e8f48ad295f18b8e22e25c71899 | [] | no_license | wingfiring/xirang | 16a8b10de9965b7609153acb8d4cfe878a089aa5 | eda84647cca476a29e8d785b8fd8ceda78bb952f | refs/heads/master | 2019-06-15T08:06:44.692019 | 2017-06-04T10:25:57 | 2017-06-04T10:25:57 | 6,007,811 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 622 | cpp | ref_ptr.cpp | /*
$COMMON_HEAD_COMMENTS_CONTEXT$
*/
#include "precompile.h"
#include <xirang/ref_ptr.h>
#include <xirang/assert.h>
//BOOST
#include <boost/mpl/list.hpp>
//STL
#include <string>
BOOST_AUTO_TEST_SUITE(ref_ptr_suite)
using namespace xirang;
typedef boost::mpl::list<int, const int, std::string, const std::string> test_types;
BOOST_AUTO_TEST_CASE_TEMPLATE(ref_ptr_case, T, test_types)
{
typedef ref_ptr<T> ref_type;
T t = T();
ref_type h1(t);
BOOST_CHECK(&h1.get() == &t);
BOOST_CHECK((T&)h1 == t);
T v = T();
ref_type h2(v);
swap(h1, h2);
BOOST_CHECK(&h1.get() == &v);
}
BOOST_AUTO_TEST_SUITE_END()
|
0d793de836b7a49c2a20177ea7d970351fbcb221 | 3195762cf17324063677d0d053a8640386eb294e | /UAlbertaBot/Source/Squad.h | 0c4a34e48c9dbf59656ac89ae496e01cfef71a58 | [
"MIT"
] | permissive | davechurchill/ualbertabot | 02545fc822dbdaa21dc3eb7cb23dcfd4a7e73971 | 558899d8793456f4a6ec4196efbb5235552e24db | refs/heads/master | 2023-05-25T16:37:20.975939 | 2022-03-01T19:22:32 | 2022-03-01T19:22:32 | 23,928,013 | 549 | 242 | MIT | 2023-05-19T09:19:30 | 2014-09-11T17:18:49 | C++ | UTF-8 | C++ | false | false | 1,801 | h | Squad.h | #pragma once
#include "Common.h"
#include "MeleeManager.h"
#include "RangedManager.h"
#include "DetectorManager.h"
#include "TransportManager.h"
#include "SquadOrder.h"
#include "TankManager.h"
#include "MedicManager.h"
namespace UAlbertaBot
{
class Squad
{
BWAPI::Unitset m_units;
std::string m_name = "Default";
std::string m_regroupStatus = "Default";
int m_lastRetreatSwitch = 0;
bool m_lastRetreatSwitchVal = false;
size_t m_priority = 0;
SquadOrder m_order;
MeleeManager m_meleeManager;
RangedManager m_rangedManager;
DetectorManager m_detectorManager;
TransportManager m_transportManager;
TankManager m_tankManager;
MedicManager m_medicManager;
std::map<BWAPI::Unit, bool> m_nearEnemy;
BWAPI::Unit unitClosestToEnemy();
void updateUnits();
void addUnitsToMicroManagers();
void setNearEnemyUnits();
void setAllUnits();
bool unitNearEnemy(BWAPI::Unit unit);
bool needsToRegroup();
int squadUnitsNear(BWAPI::Position p);
public:
Squad(const std::string & name, SquadOrder order, size_t priority);
Squad();
~Squad();
void update();
void setSquadOrder(const SquadOrder & so);
void addUnit(BWAPI::Unit u);
void removeUnit(BWAPI::Unit u);
bool containsUnit(BWAPI::Unit u) const;
bool isEmpty() const;
void clear();
size_t getPriority() const;
void setPriority(const size_t & priority);
const std::string & getName() const;
BWAPI::Position calcCenter();
BWAPI::Position calcRegroupPosition();
const BWAPI::Unitset & getUnits() const;
const SquadOrder & getSquadOrder() const;
};
} |
56662600d583fb149b045ca19b730b42ffca9c88 | 906a385007d81611f6642960d8873233d4d28c25 | /week3/MagicBeads/main.cpp | 8b2f639363c0847a3226dc39130bee306f86b47f | [] | no_license | zengmmm00/DSAA | 7cb25138248a6a5507a006faa5136a2ade4ffd30 | db183ac8dac6c160edc1400a44684eebd01e117b | refs/heads/main | 2023-07-24T22:28:40.033234 | 2021-09-04T03:15:26 | 2021-09-04T03:15:26 | 402,950,608 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,326 | cpp | main.cpp | #include <iostream>
using namespace std;
struct str{
long long red;
long long blue;
long long group;
};
void GroupMerge(str A[], long long start, long long end){
long long n = end - start + 1;//size of B
str B[n];
long long i = start;
long long j = start + n / 2;
for (long long k = 0; k < n; ++k) {
if((A[i].group < A[j].group && i <= start + n / 2 -1) || j > end){
B[k] = A[i];
i++;
} else{
B[k] = A[j];
j++;
}
}
for (long long k = 0; k < n; ++k) {
A[start + k] = B[k];
}
}
void redMerge(str A[], long long start, long long end){//blue < red
long long n = end - start + 1;//size of B
str B[n];
long long i = start;
long long j = start + n / 2;
for (long long k = 0; k < n; ++k) {
if((A[i].blue< A[j].blue && i <= start + n / 2 -1) || j > end){
B[k] = A[i];
i++;
} else{
B[k] = A[j];
j++;
}
}
for (long long k = 0; k < n; ++k) {
A[start + k] = B[k];
}
}
void BlueMerge(str A[], long long start, long long end){//blue > red
long long n = end - start + 1;//size of B
str B[n];
long long i = start;
long long j = start + n / 2;
for (long long k = 0; k < n; ++k) {
if((A[i].red > A[j].red && i <= start + n / 2 -1) || j > end){
B[k] = A[i];
i++;
} else{
B[k] = A[j];
j++;
}
}
for (long long k = 0; k < n; ++k) {
A[start + k] = B[k];
}
}
void GroupmergeSort(str A[], long long start, long long end, int a){
if(end - start >= 1){
long long n = (end - start + 1) / 2;
GroupmergeSort(A, start, start + n-1,a);
GroupmergeSort(A, start + n, end,a);
// GroupMerge(A, start, end);
if(a == 0){ GroupMerge(A, start, end);}
else if(a == 1){redMerge(A, start, end);}
else{BlueMerge(A, start, end);}
}
}
int main() {
long long T;
scanf("%lld",&T);
for (long long i = 0; i < T; ++i) {
long long n;
long long count = 0;
scanf("%lld",&n);
str beads[n];
long long zero = 0;
long long two = 0;
for (long long j = 0; j < n; ++j) {
scanf("%lld", &beads[j].blue);
scanf("%lld", &beads[j].red);
if(beads[j].blue < beads[j].red){
beads[j].group = 0;
zero++;
} else if(beads[j].blue == beads[j].red){
beads[j].group = 1;
} else{
beads[j].group = 2;
two++;
}
}
if(n == 1){
printf("0\n");
continue;
}
GroupmergeSort(beads, 0, n - 1, 0);
if(zero != 0){
GroupmergeSort(beads, 0, zero - 1, 1);
}
if(two != 0){
GroupmergeSort(beads, n - two , n - 1,2);
}
//sort finish
for (int j = 0; j < n - 1; ++j) {
if(beads[j].red > beads[j+1].blue){
count +=beads[j+1].blue;
beads[j+1].red += beads[j].red - beads[j+1].blue;
} else{
count += beads[j].red;
}
}
printf("%lld\n",count);
}
return 0;
} |
d4e0134fe0e801269505590c52717766407b47d8 | c2283e833bdb0eeb985d95fc5a1db8facb027f05 | /Project/Source/GCAA/SpellManager/Spells/CWindblast.h | 9167e876fa0c710732d78babefa9267a7c9a20c0 | [] | no_license | Bibool/Lost-Souls | ce44653b7672cb3703ba79795e0cee94051e38ff | 67e58de79c8bf26a6f45273595cb765b729cb69b | refs/heads/main | 2022-07-29T17:20:53.648402 | 2021-05-26T17:16:32 | 2021-05-26T17:16:32 | 368,998,934 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,203 | h | CWindblast.h | ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// (C) Gamer Camp / Abdallah Boutrif (A.B) //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "CoreMinimal.h"
#include "Components/TimelineComponent.h"
#include "GameFramework/Actor.h"
#include "GCAA/Interfaces/PoolStatusIdentifier.h"
#include "GCAA/Structures/FActorDistanceData.h"
#include "GCAA/Structures/FWindBlastStatsStruct.h"
#include "CWindblast.generated.h"
class ACPlayer;
class ASpellManager;
UCLASS()
class GCAA_API ACWindblast : public AActor, public IPoolStatusIdentifier
{
GENERATED_BODY()
public:
ACWindblast();
// Fires off the spell logic. Called by the Spell manager when the player casts it.
void FireWindblast();
// Setters
void SetSpellManager ( ASpellManager* pSpellManager ); // The spell manager. _deprecated_
void SetPlayer ( ACPlayer* pPlayer ); // The player. _deprecated_
void SetStats ( FWindBlastStatsStruct sStats ); // The stats of this spell.
// Tick (Update) Override - Used exclusively for the timeline.
virtual void Tick ( float DeltaTime ) override;
// BeginPlay Override - Currently unused.
virtual void BeginPlay() override;
private:
// Finds valid targets.
void TraceForTargets();
virtual void VFireEvent() override;
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////// NOW UNUSED ////////////////////////////////////////
// Displaces the targets. //
void DisplaceTargets(); //
// Called in the timeline, lerps the location (Displaces) the target actors. //
UFUNCTION() //
void ApplyDisplacement(float Value); //
// CB Function when the timeline has completed. Or when the lerp has reached desired offset. //
UFUNCTION() //
void TimelineComplete(); //
////////////////////////////////////////////////////////////////////////////////////////////////
UFUNCTION()
void RestoreNPCState();
// If the spell found no valid targets, refunds the cooldown.
void ReportSpellFailure();
////////////////////////////////// VARIABLES //////////////////////////////////////
bool m_bCastFail; // Used to know if cast failed.
bool m_bTargetsFound; // Was any targets valid?
bool m_bDisplacing; // Are the targets being moved?
UPROPERTY()
TArray<FActorDistanceData> m_apsTargets; // TArray of our target data.
UPROPERTY()
FWindBlastStatsStruct m_sSpellStats; // Member copy of our stats.
UPROPERTY()
FTimerHandle m_sRestoreControl; // Timer for restoring NPC state.
UPROPERTY()
ASpellManager* m_pcSpellManager; // Pointer to the manager. _deprecated_
UPROPERTY()
ACPlayer* m_pcPlayer; // Pointer to the player. _deprecated_
UPROPERTY()
FTimeline m_sMoveBackWardTimeline; // Timeline used to displace. _deprecated_
};
|
262ccb1973b2b63ef0122a2b0a08ec2574bede39 | df860eaae4a8c9d4439fd5b43a7051716cc9b2f1 | /apps/editor_qt/editor/widgets/objects_list/objects_tree.cpp | 13503270d6c988ae45c71f2fa6b6acba1fc4bfbc | [] | no_license | Jakub-Ciecierski/CloudFitting | d769b468348e50f59687dfaf09571fc1fad4c1a4 | f5e18465a3bc62b1435ac5b25a8c728e585d1f73 | refs/heads/master | 2021-01-10T16:30:51.948388 | 2016-04-19T14:02:27 | 2016-04-19T14:02:27 | 54,993,885 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 717 | cpp | objects_tree.cpp | #include "objects_tree.h"
#include <QMenu>
#include <editor_window.h>
ObjectsTree::ObjectsTree(QWidget* parent) :
QTreeWidget(parent)
{
setupContextMenu();
}
void ObjectsTree::setupContextMenu(){
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, SIGNAL(customContextMenuRequested(const QPoint&)),
this, SLOT(ShowContextMenu(const QPoint&)));
}
void ObjectsTree::ShowContextMenu(const QPoint& pos){
QPoint globalPos = this->mapToGlobal(pos);
ContextMenu& menu = EditorWindow::getInstance().
getObjectsListContextMenu();
QAction* selectedItem = menu.show(globalPos);
menu.handle(selectedItem, this->selectedItems());
}
#include "moc_objects_tree.cpp"
|
a9b976095cc0bafbe4703668d1311d13577f0985 | 33d283a4adabc1cf641a04a9b803f67a50432f48 | /ProxyTester/ProxyTester.cpp | e45730a19437ab4a967a070e436b7b3deeede8f8 | [
"Unlicense"
] | permissive | legendarynacar/ProxyTester | df22525ea00a0890336a1259e07928630215ebf1 | b903d54b1b975607ee9a96291a0598ac29b8f24e | refs/heads/master | 2021-01-18T15:19:51.573703 | 2013-05-26T19:11:20 | 2013-05-26T19:11:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,200 | cpp | ProxyTester.cpp | #include "stdio.h"
#include <iostream>
#include <stdint.h>
#include <fstream>
#include <string>
#include "Stream/stream_utility.h"
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/lexical_cast.hpp>
// http://en.wikipedia.org/wiki/SOCKS
bool TestProxy(const std::string & host, uint16_t port, const std::string & username = "", const std::string & password = "")
{
//International Silkroad Online
uint32_t remote_address = inet_addr("121.128.133.26");
uint16_t remote_port = htons(15779);
boost::system::error_code ec;
boost::asio::io_service io_service;
boost::asio::ip::tcp::socket socket(io_service);
StreamUtility w, r;
std::vector<uint8_t> buffer;
buffer.resize(64);
//Resolve the hostname
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::resolver::query query(boost::asio::ip::tcp::v4(), host, boost::lexical_cast<std::string>(port));
boost::asio::ip::tcp::resolver::iterator iterator = resolver.resolve(query, ec);
if(ec)
{
std::cout << "Could not resolve " << host << ":" << port << std::endl;
return false;
}
//Connect to the socks server
socket.connect(*iterator, ec);
if(ec)
{
std::cout << "Could not connect to " << host << ":" << port << std::endl;
return false;
}
w.Write<uint8_t>(4); //SOCKS version (v4)
w.Write<uint8_t>(1); //TCP stream connection
w.Write<uint16_t>(remote_port); //TCP port
w.Write<uint32_t>(remote_address); //IP
w.Write_Ascii("ProjectHax\0", 11); //Username
boost::asio::write(socket, boost::asio::buffer(w.GetStreamPtr(), w.GetStreamSize()), boost::asio::transfer_all(), ec);
//Error sending data
if(ec)
{
std::cout << "Unable to send data to " << host << ":" << port << std::endl;
return false;
}
//Read the servers response
socket.read_some(boost::asio::buffer(&buffer[0], 63), ec);
//Error receiving data
if(ec)
{
std::cout << "Unable to receive data from " << host << ":" << port << std::endl;
return false;
}
r = StreamUtility(&buffer[0], 63);
r.Read<uint8_t>(); //Null byte
uint8_t status = r.Read<uint8_t>(); //Status
switch(status)
{
case 0x5a: //Request granted
{
socket.read_some(boost::asio::buffer(&buffer[0], 63), ec);
r = StreamUtility(&buffer[0], 63);
r.Read<uint16_t>(); //Size
uint16_t opcode = r.Read<uint16_t>(); //Opcode
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
socket.close(ec);
if(opcode == 0x5000)
return true;
}break;
case 0x5b: //Request rejected or failed
{
}break;
case 0x5c: //Request failed because client is not running identd
{
return false;
}break;
case 0x5d: //Request failed because client's identd could not confirm the user ID string in the request
{
return false;
}break;
};
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
socket.close(ec);
//Connect to the socks server
socket.connect(*iterator, ec);
if(ec)
{
std::cout << "Could not connect to " << host << ":" << port << std::endl;
return false;
}
w.Clear();
w.Write<uint8_t>(5); //SOCKS version (v5)
if(!username.empty())
{
w.Write<uint8_t>(2); //Number of authentication methods supported (2)
w.Write<uint8_t>(0); //No authentication
w.Write<uint8_t>(2); //Username/password authentication
}
else
{
w.Write<uint8_t>(1); //Number of authentication methods supported (1)
w.Write<uint8_t>(0); //No authentication
}
boost::asio::write(socket, boost::asio::buffer(w.GetStreamPtr(), w.GetStreamSize()), boost::asio::transfer_all(), ec);
//Error sending data
if(ec)
{
std::cout << "Unable to send data to " << host << ":" << port << std::endl;
return false;
}
//Read the servers response
socket.read_some(boost::asio::buffer(&buffer[0], 63), ec);
//Error receiving data
if(ec)
{
std::cout << "Unable to receive data from " << host << ":" << port << std::endl;
return false;
}
r = StreamUtility(&buffer[0], 63);
uint8_t version = r.Read<uint8_t>(); //SOCKS version (must be v5)
uint8_t authentication = r.Read<uint8_t>(); //Authentication method
//No authentication
if(version == 5)
{
w.Clear();
//No authentication
if(authentication == 0)
{
w.Write<uint8_t>(5); //SOCKS version (v5)
w.Write<uint8_t>(1); //TCP stream connection
w.Write<uint8_t>(0); //Reserved
w.Write<uint8_t>(1); //Address type, (1 = IPv4 address, 3 = domain, 4 = IPv6 address)
w.Write<uint32_t>(remote_address); //IP
w.Write<uint16_t>(remote_port); //TCP port
}
//Username/password authentication
else if(authentication == 2)
{
w.Write<uint8_t>(1); //Authentication version
w.Write<uint8_t>(username.length()); //Username length
w.Write_Ascii(username); //Username
w.Write<uint8_t>(password.length()); //Password length
w.Write_Ascii(password); //Password
}
boost::asio::write(socket, boost::asio::buffer(w.GetStreamPtr(), w.GetStreamSize()), boost::asio::transfer_all(), ec);
//Error sending data
if(ec)
{
std::cout << "Unable to send data to " << host << ":" << port << std::endl;
return false;
}
//Read the servers response
socket.read_some(boost::asio::buffer(&buffer[0], 63), ec);
//Error receiving data
if(ec)
{
std::cout << "Unable to receive data from " << host << ":" << port << std::endl;
return false;
}
if(authentication == 2)
{
r = StreamUtility(&buffer[0], 63);
if(r.Read<uint8_t>() != 1 || r.Read<uint8_t>() != 0)
return false;
w.Clear();
w.Write<uint8_t>(5); //SOCKS version (v5)
w.Write<uint8_t>(1); //TCP stream connection
w.Write<uint8_t>(0); //Reserved
w.Write<uint8_t>(1); //Address type, (1 = IPv4 address, 3 = domain, 4 = IPv6 address)
w.Write<uint32_t>(remote_address); //IP
w.Write<uint16_t>(remote_port); //TCP port
boost::asio::write(socket, boost::asio::buffer(w.GetStreamPtr(), w.GetStreamSize()), boost::asio::transfer_all(), ec);
//Error sending data
if(ec)
{
std::cout << "Unable to send data to " << host << ":" << port << std::endl;
return false;
}
//Read the servers response
socket.read_some(boost::asio::buffer(&buffer[0], 63), ec);
//Error receiving data
if(ec)
{
std::cout << "Unable to receive data from " << host << ":" << port << std::endl;
return false;
}
}
r = StreamUtility(&buffer[0], 10);
version = r.Read<uint8_t>(); //SOCKS version (must be v5)
status = r.Read<uint8_t>(); //Status
switch(status)
{
case 0: //Request granted
{
socket.read_some(boost::asio::buffer(&buffer[0], 63), ec);
r = StreamUtility(&buffer[0], 63);
r.Read<uint16_t>(); //Size
uint16_t opcode = r.Read<uint16_t>(); //Opcode
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
socket.close(ec);
if(opcode == 0x5000)
return true;
}break;
case 1: //General failure
{
}break;
case 2: //Connection not allowed by ruleset
{
}break;
case 3: //Network unreachable
{
}break;
case 4: //Host unreachable
{
}break;
case 5: //Connection refused by destination host
{
}break;
case 6: //TTL expired
{
}break;
case 7: //Command not supported / protocol error
{
}break;
case 8: //Address type not supported
{
}break;
};
}
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
socket.close(ec);
return false;
}
int main(int argc, char* argv[])
{
std::ifstream ifs("proxy.txt");
std::fstream fs("working.txt", std::ios::out);
uint32_t working = 0;
if(ifs.is_open() && fs.is_open())
{
std::string line;
std::string host;
uint16_t port;
while(!ifs.eof())
{
ifs >> line;
size_t index = line.find(":");
if(index != std::string::npos)
{
host = line.substr(0, index);
port = boost::lexical_cast<uint16_t>(line.substr(index + 1, line.length() - index));
if(TestProxy(host, port))
{
fs << line << "\n";
working++;
}
}
}
fs.close();
ifs.close();
}
std::cout << "Done. " << working << " servers work." << std::endl;
std::cin.get();
return 0;
} |
4255ae346732913e561654f600f813b6b515c141 | 95cf609f397eccb095cc453cecdefc7516362cde | /DMenu.cpp | 9916973b07be5f52129e4f750c82f699f5a8201c | [] | no_license | powersjt4/GroceryStore | 2b16ca510b3f1de82c589a876f15f5f132f3b8cc | a275b8559befde6a68944527b825ef1a2bf24ee1 | refs/heads/master | 2021-03-30T21:04:46.910976 | 2018-05-07T21:05:46 | 2018-05-07T21:05:46 | 124,706,674 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 947 | cpp | DMenu.cpp | /*******************************************
**************************
** Author:Jake Powers
** Date: 7/14/17
** Description: This class creates a vector of strings
** for display as a menu.
********************************************
*************************/
#include <iostream>
#include <string>
#include "DMenu.hpp"
/************************************************************
DMenu::addItem(string of menu item)
Adds menu item to vector
***********************************************************/
void DMenu::addItem(std::string str) {
menu.push_back(str);
return;
}
/************************************************************
DMenu::printDMenu(none)
This will print the menu vector with corresponding line number.
***********************************************************/
void DMenu::printDMenu() {
for (unsigned int i = 0; i < menu.size(); i++) {
std::cout << i + 1 << ": " << menu[i] << std::endl;
}
return;
}
|
1bd1f47bcb6116d2160ac3d0bf638cd9b994a4df | a1d31d7fe3274a0dcf10adf767801f03a6c683d4 | /codeforces/main.cpp | 0f63a571d3b9914f28573d7b61ae503f1c414cb3 | [] | no_license | swarnali1498/Programs | d73bbc37f037c61979a464cc303281b0919d5f4b | c67bf5ee1f41b9d386555eac5b52c32de670317b | refs/heads/master | 2022-12-30T04:42:00.141682 | 2020-10-14T18:23:36 | 2020-10-14T18:23:36 | 304,057,965 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 638 | cpp | main.cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int s[9][9],i,j; long s1;
for(i=0;i<9;i++)
{
cin>>s1;
for(j=8;j>=1;j--)
{
s[i][j]=s1%10;
s1=s1/10;
}
s[i][j]=s1;
}
for(i=0;i<9;i++)
{
s[i][i]=((s[i][i]+1)%9);
if(s[i][i]==0)
s[i][i]=9;
}
for(i=0;i<9;i++)
{
for(j=0;j<9;j++)
{
cout<<s[i][j];
}
cout<<endl;
}
}
}
|
b7d4b83c685a1e076b571d63023e6f8095c330fa | b6d7b33a91e0ec4b260c57ee1d501d2e3bbe740d | /Classes/UI/Dialog.cpp | 90d7d71eb4ac78196dcf00325bd7ac06144a82df | [] | no_license | SongCF/game-CoolRun | 747576cddb7964998bd4a2da004162418b1ba1cd | 4ed65732e7742b7550808eed547eb1aef51e9408 | refs/heads/master | 2020-04-12T15:58:14.573484 | 2015-08-29T03:40:36 | 2015-08-29T03:40:36 | 41,579,631 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,444 | cpp | Dialog.cpp | #include "Dialog.h"
#include "extensions/cocos-ext.h"
#include "Font.h"
#include "RunningHelper.h"
using namespace cocos2d::extension;
#define BG_NAME "BackGround"
#define Touche_Layer "Touche_Layer"
void MessageDialog::showDialog(string msg, pfuncMessageDialogCallback callback)
{
MessageDialog* layer = new MessageDialog;
if (layer && layer->init(msg, callback))
{
Director::getInstance()->getRunningScene()->addChild(layer, DIALOG_ZORDER, DIALOG_NAME);
layer->release();
}
else
{
CC_SAFE_DELETE(layer);
}
}
bool MessageDialog::init(string& msg, pfuncMessageDialogCallback callback)
{
if (! LayerColor::initWithColor(Color4B(0,0,0,60)))
return false;
m_callback = callback;
Size winSize = Director::getInstance()->getWinSize();
//touch
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);
listener->onTouchBegan = [&](Touch* pTouch, Event* pEvent)
{
return true;
};
listener->onTouchEnded = [&](Touch* pTouch, Event* pEvent)
{
if (m_callback)
{
m_callback();
}
this->removeFromParent();
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
//bg
Scale9Sprite *pDlgBg = Scale9Sprite::create("UI_tanchukuang_shuoming.png");
pDlgBg->setContentSize(Size(460, 226));
this->addChild(pDlgBg, 1, BG_NAME);
pDlgBg->setPosition(Director::getInstance()->getWinSize()/2);
//描述
Label *pMiaoshu = Label::createWithSystemFont(msg.c_str(), Font_TTF_KaTong, 30, Size(winSize.width*0.6f, 0), TextHAlignment::CENTER);
pDlgBg->setContentSize(pMiaoshu->getContentSize() + Size(100,90));
pDlgBg->addChild(pMiaoshu, 10);
pMiaoshu->setColor(Font_Color_BaseColor);
pMiaoshu->setAnchorPoint(Vec2(0.5f,0.5f));
pMiaoshu->setPosition(pDlgBg->getContentSize()/2);
return true;
}
GuideDialog* GuideDialog::showDialog(string text, string imply, string menuString, std::function<void()> callback)
{
GuideDialog* layer = new GuideDialog;
if (layer && layer->init(text, imply, menuString, callback))
{
Director::getInstance()->getRunningScene()->addChild(layer, DIALOG_ZORDER, DIALOG_NAME);
layer->release();
}
else
{
CC_SAFE_DELETE(layer);
}
return layer;
}
bool GuideDialog::init(string text, string imply, string menuString, std::function<void()> callback)
{
if (! LayerColor::initWithColor(Color4B(0,0,0,60)))
return false;
m_bTouchedClose = false;
m_callback = callback;
Sprite *pDlgBg = Sprite::create("UI_tanchukuang_jiaoxue.png");
this->addChild(pDlgBg, 1, BG_NAME);
pDlgBg->setPosition(Director::getInstance()->getWinSize()/2);
Sprite* pIcongBg = Sprite::create("UI_jiaose_qiehuanrenwu_bg.png");
pDlgBg->addChild(pIcongBg);
pIcongBg->setScale(1.2f);
pIcongBg->setPosition(Vec2(20, pDlgBg->getContentSize().height - 20));
Sprite* pIcon = Sprite::create("UI_touxiang_long.png");
// pIcon->setScale(0.8f);
pIcongBg->addChild(pIcon);
pIcon->setPosition(Vec2(pIcongBg->getContentSize().width/2 + 10, pIcongBg->getContentSize().height/2+5));
//描述
Label *pMiaoShu = Label::createWithSystemFont(text.c_str(), Font_TTF_KaTong, 30, Size(470, 0), TextHAlignment::LEFT);
pDlgBg->addChild(pMiaoShu, 10);
pMiaoShu->setColor(Font_Color_BaseColor);
// pMiaoShu->setAnchorPoint(Vec2(0.5f,1));
pMiaoShu->setPosition(pDlgBg->getContentSize().width/2, pDlgBg->getContentSize().height/2 + 20);
//提示
Label *pTishi = Label::createWithSystemFont(imply.c_str(), Font_TTF_KaTong, 36, Size(470, 0), TextHAlignment::CENTER);
pDlgBg->addChild(pTishi, 10);
// pTishi->setColor(Color3B::RED);
// pTishi->setAnchorPoint(Vec2(0,0));
pTishi->setPosition(pDlgBg->getContentSize().width/2, pTishi->getContentSize().height/2 + 40);
//按钮
if (! menuString.empty() && callback != nullptr)
{
Menu* menu = Menu::create();
pDlgBg->addChild(menu, 10);
menu->setPosition(Vec2::ZERO);
{//swllow item
Layer *layer = Layer::create();
pDlgBg->addChild(layer, 1);
auto touchListener = EventListenerTouchOneByOne::create();
touchListener->setSwallowTouches(true);
touchListener->onTouchBegan = [&](Touch* pTouch, Event* pEvent){return true;};
_eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, layer);
}
Sprite *qxS1 = Sprite::create("UI_youxizhong_fuhuo_anniu_bg.png");
Label *resLa1 = Label::createWithSystemFont(menuString.c_str(), Font_TTF_KaTong, 24);
qxS1->addChild(resLa1);
resLa1->setPosition(qxS1->getContentSize()/2);
//
Sprite *qxS2 = Sprite::create("UI_youxizhong_fuhuo_anniu_bg.png");
Label *resLa2 = Label::createWithSystemFont(menuString.c_str(), Font_TTF_KaTong, 30);
qxS2->addChild(resLa2);
resLa2->setPosition(qxS2->getContentSize()/2);
float sX=1, sY=1;
sX = (resLa1->getContentSize().width+20)/qxS1->getContentSize().width;
sY = (resLa1->getContentSize().height+20)/qxS1->getContentSize().height;
qxS1->setScale(sX,sY);
qxS2->setScale(sX,sY);
resLa1->setScaleX(1/sX);resLa1->setScaleY(1/sY);
resLa2->setScaleX(1/sX);resLa2->setScaleY(1/sY);
//
MenuItemSprite *item = MenuItemSprite::create(qxS1, qxS2, [&](Ref *pSender){
m_callback();
});
item->setScale(1.5f);
menu->addChild(item, 1);
item->setPosition(pDlgBg->getContentSize().width/2 + 20, qxS1->getContentSize().height/2+30);
}
return true;
}
void GuideDialog::setBossGudie(bool e)
{
m_bTouchedClose = e;
if (e)
{
this->removeChildByName(Touche_Layer);
{//swllow item
Layer *layer = Layer::create();
this->getChildByName(BG_NAME)->addChild(layer, 1, Touche_Layer);
auto touchListener = EventListenerTouchOneByOne::create();
touchListener->setSwallowTouches(true);
touchListener->onTouchBegan = [&](Touch* pTouch, Event* pEvent){
if (m_bTouchedClose)
{
if (RunningHelper::getHelper()->getCurrentScenePlayMode() == mode_Fight)
//&& !this->getChildByName(BG_NAME)->getBoundingBox().containsPoint(pTouch->getLocation()))
{
this->removeFromParent();
RunningHelper::getHelper()->gameResume();
}
}
return true;
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, layer);
}
}
else
{
this->removeChildByName(Touche_Layer);
}
}
//对话框
SelectDialog::SelectDialog()
{
}
SelectDialog::~SelectDialog()
{
}
SelectDialog* SelectDialog::create(string title, string context, string iconName)
{
SelectDialog* pMessageDialog = new SelectDialog();
if (pMessageDialog && pMessageDialog->initWithInfo(title, context, iconName))
{
pMessageDialog->autorelease();
return pMessageDialog;
}
CC_SAFE_DELETE(pMessageDialog);
return pMessageDialog;
}
bool SelectDialog::initWithInfo(const string& title, const string& context, const string& iconName)
{
if (!Layer::init())
{
return false;
}
LayerColor* pLayerColor = LayerColor::create(Color4B(0, 0, 0, 125));
this->addChild(pLayerColor, -1);
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);
listener->onTouchBegan = [&](Touch* pTouch, Event* pEvent)
{
return true;
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
m_DialogType = DiglogType_TwoBtn;
m_pBg = Sprite::create("UI_tanchukuang.png");
this->addChild(m_pBg, 1, iTag_Bg);
m_pBg->setPosition(Vec2(this->getContentSize().width/2, this->getContentSize().height/2 + 50));
m_pCloseBtn = MenuItemImage::create(
"UI_jiaose_anniu_guanbi.png",
"UI_jiaose_anniu_guanbi.png",
std::bind(&SelectDialog::close, this, std::placeholders::_1));
Menu* pMenu = Menu::create(m_pCloseBtn, nullptr);
pMenu->setPosition(Vec2(0, 0));
m_pBg->addChild(pMenu, 2);
m_pCloseBtn->setPosition(Vec2(m_pBg->getContentSize().width - 20, m_pBg->getContentSize().height - 20));
int Yoffset = 30;
m_pTitle = Label::createWithSystemFont(title, Font_TTF_KaTong, 40);
m_pTitle->setColor(Font_Color_BaseColor);
m_pBg->addChild(m_pTitle, 1, iTag_Title_Str);
m_pTitle->setPosition(Vec2(m_pBg->getContentSize().width/2, m_pBg->getContentSize().height - m_pTitle->getContentSize().height/2 - Yoffset));
m_pBg_Info_Str = Label::createWithSystemFont(context, Font_TTF_KaTong, 26, Size(420, 90), TextHAlignment::LEFT);
m_pBg->addChild(m_pBg_Info_Str, 1, iTag_Bg_Str);
m_pBg_Info_Str->setPosition(Vec2(m_pBg->getContentSize().width/2, m_pBg->getContentSize().height/2-Yoffset));
m_pBg_Icon = nullptr;
if (iconName.size() > 0)
{
m_pBg_Icon = Sprite::create(iconName.c_str());
Sprite* pBg = Sprite::create("UI_jiaose_qiehuanrenwu_bg.png");
m_pBg_Icon->addChild(pBg, -1);
pBg->setPosition(m_pBg_Icon->getContentSize()/2);
}
else
{
m_pBg_Icon = Sprite::create();
}
if (m_pBg_Icon)
{
m_pBg->addChild(m_pBg_Icon, 1, iTag_Bg_Icon);
m_pBg_Icon->setPosition(Vec2(m_pBg_Icon->getContentSize().width/2 + 20, m_pBg->getContentSize().height/2 - Yoffset));
if (iconName.size() > 0)
{
m_pBg_Info_Str->setPosition(Vec2(m_pBg_Icon->getPositionX()+m_pBg_Icon->getContentSize().width/2 + m_pBg_Info_Str->getContentSize().width/2, m_pBg_Icon->getPositionY()));
}
else
{
m_pBg_Info_Str->setPosition(Vec2(m_pBg->getContentSize().width/2, m_pBg_Icon->getPositionY()));
}
}
int xOffset = 80;
m_pLeftBtn = createBtn("OK", "", std::bind(&SelectDialog::close, this, std::placeholders::_1));
pMenu->addChild(m_pLeftBtn, 1);
m_pLeftBtn->setPosition(Vec2(m_pBg->getContentSize().width/2 - m_pLeftBtn->getContentSize().width/2 - xOffset,
m_pBg->getPositionY() - m_pBg->getContentSize().height - m_pLeftBtn->getContentSize().height - 100));
m_pRightBtn = createBtn("Cancel", "", std::bind(&SelectDialog::close, this, std::placeholders::_1));
pMenu->addChild(m_pRightBtn, 1);
m_pRightBtn->setPosition(Vec2(m_pBg->getContentSize().width/2 + m_pRightBtn->getContentSize().width/2 + xOffset,
m_pLeftBtn->getPositionY()));
m_pMiddleBtn = createBtn("OK", "", std::bind(&SelectDialog::close, this, std::placeholders::_1));
pMenu->addChild(m_pMiddleBtn, 1);
m_pMiddleBtn->setPosition(Vec2(m_pBg->getContentSize().width/2,
m_pLeftBtn->getPositionY()));
setDialogType(m_DialogType);
return true;
}
MenuItemImage* SelectDialog::createBtn(string str, string iconName, const ccMenuCallback& callback)
{
MenuItemImage* pBtn = MenuItemImage::create("UI_youxizhong_fuhuo_anniu_bg.png", "UI_youxizhong_fuhuo_anniu_bg.png", callback);
Label* pInfo_Str = Label::createWithSystemFont(str, Font_TTF_KaTong, 30);
pBtn->addChild(pInfo_Str, 1, iTag_Btn_Str);
pInfo_Str->setPosition(pBtn->getContentSize()/2);
Sprite* pIcon = nullptr;
if (iconName.size() > 0)
{
pIcon = Sprite::create(iconName.c_str());
}
else
{
pIcon = Sprite::create();
}
if (pIcon)
{
pBtn->addChild(pIcon, 1, iTag_Btn_Icon);
pInfo_Str->setPosition(Vec2(pBtn->getContentSize().width/2 - pIcon->getContentSize().width/2, pBtn->getContentSize().height/2));
pIcon->setPosition(Vec2(pInfo_Str->getPositionX()+pIcon->getContentSize().width/2+pInfo_Str->getContentSize().width/2, pInfo_Str->getPositionY()));
}
return pBtn;
}
void SelectDialog::close(Ref* pObj)
{
this->removeFromParent();
}
void SelectDialog::setCloseCallBack(const ccMenuCallback& callback)
{
if (callback)
{
m_pCloseBtn->setCallback(callback);
}
}
void SelectDialog::setLeftBtnCallBack(const ccMenuCallback& callback)
{
if (callback)
{
m_pLeftBtn->setCallback(callback);
}
}
void SelectDialog::setMiddleBtnCallBack(const ccMenuCallback& callback)
{
if (callback)
{
m_pMiddleBtn->setCallback(callback);
}
}
void SelectDialog::setRightBtnCallBack(const ccMenuCallback& callback)
{
if (callback)
{
m_pRightBtn->setCallback(callback);
}
}
void SelectDialog::setBtnInfo(string str, string iconName, const ccMenuCallback& callback, BtnType btntype)
{
MenuItemImage* pBtn = nullptr;
if (btntype == Type_Left)
{
pBtn = m_pLeftBtn;
setLeftBtnCallBack(callback);
}
else if (btntype == Type_Middle)
{
pBtn = m_pMiddleBtn;
setMiddleBtnCallBack(callback);
}
else if (btntype == Type_Right)
{
pBtn = m_pRightBtn;
setRightBtnCallBack(callback);
}
if (!pBtn)
{
return;
}
Label* pStr = (Label*)pBtn->getChildByTag(iTag_Btn_Str);
Sprite* pIcon = (Sprite*)pBtn->getChildByTag(iTag_Btn_Icon);
pStr->setString(str.c_str());
if (iconName.size() > 0)
{
pIcon->setTexture(iconName.c_str());
pStr->setPosition(Vec2(pBtn->getContentSize().width/2 - pIcon->getContentSize().width/2, pBtn->getContentSize().height/2));
pIcon->setPosition(Vec2(pStr->getPositionX()+pIcon->getContentSize().width/2+pStr->getContentSize().width/2, pStr->getPositionY()));
}
}
void SelectDialog::setDialogType(DigLogType type)
{
m_DialogType = type;
if (m_DialogType == DiglogType_OneBtn)
{
m_pLeftBtn->setVisible(false);
m_pRightBtn->setVisible(false);
m_pMiddleBtn->setVisible(true);
}
else if (m_DialogType == DiglogType_TwoBtn)
{
m_pLeftBtn->setVisible(true);
m_pRightBtn->setVisible(true);
m_pMiddleBtn->setVisible(false);
}
}
void SelectDialog::setBgInfo(string context, string iconName)
{
m_pBg_Info_Str->setString(context.c_str());
if (iconName.size() > 0)
{
m_pBg_Icon->setTexture(iconName.c_str());
m_pBg_Icon->setPosition(Vec2(m_pBg_Icon->getContentSize().width/2 + 20, m_pBg->getContentSize().height/2 - 25));
m_pBg_Info_Str->setPosition(Vec2(m_pBg_Icon->getPositionX()+m_pBg_Icon->getContentSize().width/2 + m_pBg_Info_Str->getContentSize().width/2, m_pBg_Icon->getPositionY()));
}
}
void SelectDialog::setBgInfo(string title, string context, string iconName)
{
m_pTitle->setString(title);
setBgInfo(context, iconName);
} |
9dc67fec8591ce0bdde9a247906478401370a5d5 | 9b79d3308955ef1c9be41de6977acea97d6fec22 | /common/layers.cpp | 8758b018413c836ae98d53a214beb63d848b0e8b | [] | no_license | computer-network-shenjian/linux-data-transfer | c98707d2ae8de7fd2c5e37625c5914f79a599804 | 936f06867436c1cce6a22387207fbb24672a9184 | refs/heads/master | 2020-04-10T04:09:20.877577 | 2018-12-31T17:48:44 | 2018-12-31T17:48:44 | 160,789,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,285 | cpp | layers.cpp | #include "layers.hpp"
using namespace std;
bool sig_get_STL = false;
bool sig_good_STL = false;
bool sig_get_SNL = false;
bool sig_good_SNL = false;
bool sig_get_SDL = false;
bool sig_good_SDL = false;
bool sig_get_SPL = false;
bool sig_good_SPL = false;
bool sig_get_RAL = false;
bool sig_good_RAL = false;
bool sig_get_RTL = false;
bool sig_good_RTL = false;
bool sig_get_RNL = false;
bool sig_good_RNL = false;
bool sig_get_RDL = false;
bool sig_good_RDL = false;
/* Application Layer */
int sender_application_layer(const int pid, const int segment_id) {
cout << "Sender Application Layer:" << endl;
// initialize process
char *shared_memory = process_init(segment_id);
if (shared_memory == (char*) -1) { // shared memory allocation error
kill(pid, SIGBAD);
GRACEFUL_RETURN("Shared memory attachment\n", SharedMemoryAttachment);
}
int data_len = 20;
int tcp_len = 9 * 4;
char *buf = new char[data_len];
generate_init_vector(buf, data_len);
memcpy(shared_memory+kMacLength+kIpLength+tcp_len, buf, data_len);
write_dat(buf, data_len, kRawSendDat);
cout << "SAL write dat file OK" << endl;
print_tcp_data(buf, data_len);
kill(pid, SIGGOOD);
delete[] buf;
while(1) sleep(1);
return 0;
}
int receiver_application_layer(const int segment_id, const CopyMode copy_mode) {
// initialize process
sig_get_RAL = false;
sig_good_RAL = false;
char *shared_memory = process_init(segment_id);
if (shared_memory == (char*) -1) { // shared memory allocation error
GRACEFUL_RETURN("Shared memory attachment\n", SharedMemoryAttachment);
}
// bind signal
signal(SIGGOOD, signal_handler_RAL);
signal(SIGBAD, signal_handler_RAL);
// Wait for signals.
while(!sig_get_RAL) {
usleep(100);
}
if(!sig_good_RAL) {
cerr << "RTL bad result, RAL end." << endl;
return FatherBad;
}
cout << endl << "Receiver Application Layer:" << endl;
// do parse work
char *ptr_header, *ptr_buf;
int tcp_header_len = 0;
uint16_t dat_length = get_dat_length(kReadDat);
HeaderTCP header;
switch (copy_mode) {
case CopyMode::Copy:
ptr_header = new char[dat_length-kMacLength-kIpLength];
memcpy(ptr_header, shared_memory+kMacLength+kIpLength, dat_length-kMacLength-kIpLength);
memcpy(&header, ptr_header, kTcpMaxLength);
tcp_header_len = get_tcp_data_length(header);
ptr_buf = new char[dat_length-kMacLength-kIpLength-tcp_header_len];
memcpy(ptr_buf, shared_memory+kMacLength+kIpLength+tcp_header_len, dat_length-kMacLength-kIpLength-tcp_header_len);
break;
case CopyMode::Shared:
ptr_header = shared_memory+kMacLength+kIpLength;
memcpy(&header, ptr_header, kTcpMaxLength);
tcp_header_len = get_tcp_data_length(header);
ptr_buf = shared_memory+kMacLength+kIpLength+tcp_header_len;
break;
default:
cerr << "wrong copy mode" << endl;
return WrongCopyMode;
}
print_tcp_data(ptr_buf, dat_length-kMacLength-kIpLength-tcp_header_len);
write_dat(ptr_buf, dat_length-kMacLength-kIpLength-tcp_header_len, kRawRecvDat);
cout << "RAL write dat file OK" << endl;
if (copy_mode == CopyMode::Copy) {
delete[] ptr_header;
delete[] ptr_buf;
}
cout << "All done! Press ctrl+C to exit all processes..." << endl;
return OK;
}
void signal_handler_RAL(int sig) {
switch (sig) {
case SIGGOOD:
//cout << "DEBUG: SIGGOOD detected.\n";
sig_get_RAL = true;
sig_good_RAL = true;
break;
case SIGBAD:
cout << "DEBUG: SIGBAD detected.\n";
sig_get_RAL = true;
sig_good_RAL = false;
break;
default:
//cout << "DEBUG: unknown signal detected.\n";
sig_get_RAL = false;
sig_good_RAL = false;
break;
}
}
/* Transport Layer */
int sender_transport_layer(const int pid, const int segment_id, const CopyMode copy_mode) {
// initialize process
sig_get_STL = false;
sig_good_STL = false;
char *shared_memory = process_init(segment_id);
if (shared_memory == (char*) -1) { // shared memory allocation error
kill(pid, SIGBAD);
GRACEFUL_RETURN("Shared memory attachment\n", SharedMemoryAttachment);
}
// bind signal
signal(SIGGOOD, signal_handler_STL);
signal(SIGBAD, signal_handler_STL);
// Wait for signals.
while(!sig_get_STL) {
usleep(100);
}
if(!sig_good_STL) {
cerr << "SAL bad result, STL end." << endl;
kill(pid, SIGBAD);
return FatherBad;
}
cout << endl << "Sender Transport Layer:" << endl;
// do parse work
int data_len = 20;
int tcp_len = 9 * 4;
HeaderTCP header;
char *ptr_header;
switch (copy_mode) {
case CopyMode::Copy:
ptr_header = new char[data_len+tcp_len];
memcpy(ptr_header+tcp_len, shared_memory+kMacLength+kIpLength+tcp_len, data_len);
break;
case CopyMode::Shared:
ptr_header = shared_memory+kMacLength+kIpLength;
break;
default:
cerr << "wrong copy mode" << endl;
kill(pid, SIGBAD);
return WrongCopyMode;
}
PseudoHeaderTCP pseudo;
pseudo.tcp_length = htons(data_len + tcp_len);
memcpy(ptr_header, &header, tcp_len);
uint16_t cksum = checksum_TCP_sender(ptr_header, data_len + tcp_len, pseudo);
header.tcp_check_sum = htons(cksum);
print_header_TCP(header, cksum);
memcpy(ptr_header, &header, tcp_len);
if (copy_mode == CopyMode::Copy) {
memcpy(shared_memory+kMacLength+kIpLength, ptr_header, tcp_len);
delete[] ptr_header;
}
kill(pid, SIGGOOD);
while(1) sleep(1);
return OK;
}
int receiver_transport_layer(const int pid, const int segment_id, const CopyMode copy_mode) {
// initialize process
sig_get_RTL = false;
sig_good_RTL = false;
char *shared_memory = process_init(segment_id);
if (shared_memory == (char*) -1) { // shared memory allocation error
kill(pid, SIGBAD);
GRACEFUL_RETURN("Shared memory attachment\n", SharedMemoryAttachment);
}
// bind signal
signal(SIGGOOD, signal_handler_RTL);
signal(SIGBAD, signal_handler_RTL);
// Wait for signals.
while(!sig_get_RTL) {
usleep(100);
}
if(!sig_good_RTL) {
cerr << "RNL bad result, RTL end." << endl;
kill(pid, SIGBAD);
return FatherBad;
}
cout << endl << "Receiver Transport Layer:" << endl;
// do parse work
char *ptr_header, *ptr_buf;
switch (copy_mode) {
case CopyMode::Copy:
ptr_header = new char[kMaxPacketLen-kMacLength-kIpLength];
memcpy(ptr_header, shared_memory+kMacLength+kIpLength, kMaxPacketLen-kMacLength-kIpLength);
ptr_buf = new char[kMaxPacketLen-kMacLength];
memcpy(ptr_buf, shared_memory+kMacLength, kMaxPacketLen-kMacLength);
break;
case CopyMode::Shared:
ptr_header = shared_memory+kMacLength+kIpLength;
ptr_buf = shared_memory+kMacLength;
break;
default:
cerr << "wrong copy mode" << endl;
kill(pid, SIGBAD);
return WrongCopyMode;
}
HeaderTCP header;
memcpy(&header, ptr_header, kTcpMaxLength);
uint16_t checksum = checksum_TCP(ptr_buf);
print_header_TCP(header, checksum);
if (copy_mode == CopyMode::Copy) {
delete[] ptr_header;
delete[] ptr_buf;
}
kill(pid, SIGGOOD);
while(1) sleep(1);
return OK;
}
void signal_handler_STL(int sig) {
switch (sig) {
case SIGGOOD:
//cout << "DEBUG: SIGGOOD detected.\n";
sig_get_STL = true;
sig_good_STL = true;
break;
case SIGBAD:
cout << "DEBUG: SIGBAD detected.\n";
sig_get_STL = true;
sig_good_STL = false;
break;
default:
//cout << "DEBUG: unknown signal detected.\n";
sig_get_STL = false;
sig_good_STL = false;
break;
}
}
void signal_handler_RTL(int sig) {
switch (sig) {
case SIGGOOD:
//cout << "DEBUG: SIGGOOD detected.\n";
sig_get_RTL = true;
sig_good_RTL = true;
break;
case SIGBAD:
cout << "DEBUG: SIGBAD detected.\n";
sig_get_RTL = true;
sig_good_RTL = false;
break;
default:
//cout << "DEBUG: unknown signal detected.\n";
sig_get_RTL = false;
sig_good_RTL = false;
break;
}
}
/* Network Layer */
int sender_network_layer(const int pid, const int segment_id, const CopyMode copy_mode) {
// initialize process
sig_get_SNL = false;
sig_good_SNL = false;
char *shared_memory = process_init(segment_id);
if (shared_memory == (char*) -1) { // shared memory allocation error
kill(pid, SIGBAD);
GRACEFUL_RETURN("Shared memory attachment\n", SharedMemoryAttachment);
}
// bind signal
signal(SIGGOOD, signal_handler_SNL);
signal(SIGBAD, signal_handler_SNL);
// Wait for signals.
while(!sig_get_SNL) {
usleep(100);
}
if(!sig_good_SNL) {
cerr << "STL bad result, SNL end." << endl;
kill(pid, SIGBAD);
return FatherBad;
}
cout << endl << "Sender Network Layer:" << endl;
// do parse work
int data_len = 20;
int tcp_len = 9 * 4;
char *ptr_header;
switch (copy_mode) {
case CopyMode::Copy:
ptr_header = new char[data_len+tcp_len+kIpLength];
memcpy(ptr_header+kIpLength, shared_memory+kMacLength+kIpLength, data_len+tcp_len);
break;
case CopyMode::Shared:
ptr_header = shared_memory+kMacLength;
break;
default:
cerr << "wrong copy mode" << endl;
kill(pid, SIGBAD);
return WrongCopyMode;
}
HeaderIP header;
header.packet_length = htons(data_len+tcp_len+kIpLength);
uint16_t cksum = checksum_IP(header);
header.ip_check_sum = htons(cksum);
print_header_IP(header);
memcpy(ptr_header, &header, kIpLength);
if (copy_mode == CopyMode::Copy) {
memcpy(shared_memory+kMacLength, ptr_header, kIpLength);
delete[] ptr_header;
}
kill(pid, SIGGOOD);
while(1) sleep(1);
return OK;
}
int receiver_network_layer(const int pid, const int segment_id, const CopyMode copy_mode) {
// initialize process
sig_get_RNL = false;
sig_good_RNL = false;
char *shared_memory = process_init(segment_id);
if (shared_memory == (char*) -1) { // shared memory allocation error
kill(pid, SIGBAD);
GRACEFUL_RETURN("Shared memory attachment\n", SharedMemoryAttachment);
}
// bind signal
signal(SIGGOOD, signal_handler_RNL);
signal(SIGBAD, signal_handler_RNL);
// Wait for signals.
while(!sig_get_RNL) {
usleep(100);
}
if(!sig_good_RNL) {
cerr << "RDL bad result, RNL end." << endl;
kill(pid, SIGBAD);
return FatherBad;
}
cout << endl << "Receiver Network Layer:" << endl;
// do parse work
char *ptr_header;
switch (copy_mode) {
case CopyMode::Copy:
ptr_header = new char[kMaxPacketLen-kMacLength];
memcpy(ptr_header, shared_memory+kMacLength, kMaxPacketLen-kMacLength);
break;
case CopyMode::Shared:
ptr_header = shared_memory+kMacLength;
break;
default:
cerr << "wrong copy mode" << endl;
kill(pid, SIGBAD);
return WrongCopyMode;
}
HeaderIP header;
memcpy(&header, ptr_header, kIpLength);
print_header_IP(header);
if (copy_mode == CopyMode::Copy) {
delete[] ptr_header;
}
kill(pid, SIGGOOD);
while(1) sleep(1);
return OK;
}
void signal_handler_SNL(int sig) {
switch (sig) {
case SIGGOOD:
//cout << "DEBUG: SIGGOOD detected.\n";
sig_get_SNL = true;
sig_good_SNL = true;
break;
case SIGBAD:
cout << "DEBUG: SIGBAD detected.\n";
sig_get_SNL = true;
sig_good_SNL = false;
break;
default:
//cout << "DEBUG: unknown signal detected.\n";
sig_get_SNL = false;
sig_good_SNL = false;
break;
}
}
void signal_handler_RNL(int sig) {
switch (sig) {
case SIGGOOD:
//cout << "DEBUG: SIGGOOD detected.\n";
sig_get_RNL = true;
sig_good_RNL = true;
break;
case SIGBAD:
cout << "DEBUG: SIGBAD detected.\n";
sig_get_RNL = true;
sig_good_RNL = false;
break;
default:
//cout << "DEBUG: unknown signal detected.\n";
sig_get_RNL = false;
sig_good_RNL = false;
break;
}
}
/* Datalink Layer */
int sender_datalink_layer(const int pid, const int segment_id, const CopyMode copy_mode) {
// initialize process
sig_get_SDL = false;
sig_good_SDL = false;
char *shared_memory = process_init(segment_id);
if (shared_memory == (char*) -1) { // shared memory allocation error
kill(pid, SIGBAD);
GRACEFUL_RETURN("Shared memory attachment\n", SharedMemoryAttachment);
}
// bind signal
signal(SIGGOOD, signal_handler_SDL);
signal(SIGBAD, signal_handler_SDL);
// Wait for signals.
while(!sig_get_SDL) {
usleep(100);
}
if(!sig_good_SDL) {
cerr << "SNL bad result, SDL end." << endl;
kill(pid, SIGBAD);
return FatherBad;
}
cout << endl << "Sender Datalink Layer:" << endl;
// do parse work
int data_len = 20;
int tcp_len = 9 * 4;
char *ptr_header;
switch (copy_mode) {
case CopyMode::Copy:
ptr_header = new char[data_len+tcp_len+kIpLength+kMacLength];
memcpy(ptr_header+kMacLength, shared_memory+kMacLength, data_len+tcp_len+kIpLength);
break;
case CopyMode::Shared:
ptr_header = shared_memory;
break;
default:
cerr << "wrong copy mode" << endl;
kill(pid, SIGBAD);
return WrongCopyMode;
}
HeaderMAC header;
print_header_MAC(header);
memcpy(ptr_header, &header, kMacLength);
if (copy_mode == CopyMode::Copy) {
memcpy(shared_memory, ptr_header, kMacLength);
delete[] ptr_header;
}
kill(pid, SIGGOOD);
while(1) sleep(1);
return OK;
}
int receiver_datalink_layer(const int pid, const int segment_id, const CopyMode copy_mode) {
// initialize process
sig_get_RDL = false;
sig_good_RDL = false;
char *shared_memory = process_init(segment_id);
if (shared_memory == (char*) -1) { // shared memory allocation error
kill(pid, SIGBAD);
GRACEFUL_RETURN("Shared memory attachment\n", SharedMemoryAttachment);
}
// bind signal
signal(SIGGOOD, signal_handler_RDL);
signal(SIGBAD, signal_handler_RDL);
// Wait for signals.
while(!sig_get_RDL) {
usleep(100);
}
if(!sig_good_RDL) {
cerr << "RPL bad result, RDL end." << endl;
kill(pid, SIGBAD);
return FatherBad;
}
cout << endl << "Receiver Datalink Layer:" << endl;
// do parse work
char *ptr_header;
switch (copy_mode) {
case CopyMode::Copy:
ptr_header = new char[kMaxPacketLen];
memcpy(ptr_header, shared_memory, kMaxPacketLen);
break;
case CopyMode::Shared:
ptr_header = shared_memory;
break;
default:
cerr << "wrong copy mode" << endl;
kill(pid, SIGBAD);
return WrongCopyMode;
}
HeaderMAC header;
memcpy(&header, ptr_header, kMacLength);
print_header_MAC(header);
if (copy_mode == CopyMode::Copy) {
delete[] ptr_header;
}
kill(pid, SIGGOOD);
while(1) sleep(1);
return OK;
}
void signal_handler_SDL(int sig) {
switch (sig) {
case SIGGOOD:
//cout << "DEBUG: SIGGOOD detected.\n";
sig_get_SDL = true;
sig_good_SDL = true;
break;
case SIGBAD:
cout << "DEBUG: SIGBAD detected.\n";
sig_get_SDL = true;
sig_good_SDL = false;
break;
default:
//cout << "DEBUG: unknown signal detected.\n";
sig_get_SDL = false;
sig_good_SDL = false;
break;
}
}
void signal_handler_RDL(int sig) {
switch (sig) {
case SIGGOOD:
//cout << "DEBUG: SIGGOOD detected.\n";
sig_get_RDL = true;
sig_good_RDL = true;
break;
case SIGBAD:
cout << "DEBUG: SIGBAD detected.\n";
sig_get_RDL = true;
sig_good_RDL = false;
break;
default:
//cout << "DEBUG: unknown signal detected.\n";
sig_get_RDL = false;
sig_good_RDL = false;
break;
}
}
/* Physical Layer */
int sender_physical_layer(const int segment_id, const CopyMode copy_mode) {
// initialize process
sig_get_SPL = false;
sig_good_SPL = false;
char *shared_memory = process_init(segment_id);
if (shared_memory == (char*) -1) { // shared memory allocation error
GRACEFUL_RETURN("Shared memory attachment\n", SharedMemoryAttachment);
}
// bind signal
signal(SIGGOOD, signal_handler_SPL);
signal(SIGBAD, signal_handler_SPL);
// Wait for signals.
while(!sig_get_SPL) {
usleep(100);
}
if(!sig_good_SPL) {
cerr << "SDL bad result, SPL end." << endl;
return FatherBad;
}
cout << endl << "Sender Physical Layer:" << endl;
// do parse work
int data_len = 20;
int tcp_len = 9 * 4;
char *ptr_header;
switch (copy_mode) {
case CopyMode::Copy:
ptr_header = new char[data_len+tcp_len+kIpLength+kMacLength];
memcpy(ptr_header, shared_memory, data_len+tcp_len+kIpLength+kMacLength);
break;
case CopyMode::Shared:
ptr_header = shared_memory;
break;
default:
cerr << "wrong copy mode" << endl;
return WrongCopyMode;
}
write_dat(ptr_header, data_len+tcp_len+kIpLength+kMacLength, kDat);
if (copy_mode == CopyMode::Copy) {
delete[] ptr_header;
}
cout << "All done! Press ctrl+C to exit all processes..." << endl;
return OK;
}
int receiver_physical_layer(const int pid, const int segment_id) {
cout << "Receiver Physical Layer:" << endl;
// initialize process
char *shared_memory = process_init(segment_id);
if (shared_memory == (char*) -1) { // shared memory allocation error
kill(pid, SIGBAD);
GRACEFUL_RETURN("Shared memory attachment\n", SharedMemoryAttachment);
}
int len_recv = read_dat(shared_memory, kReadDat);
if (len_recv == OpenFile) {
kill(pid, SIGBAD);
return OpenFile;
}
cout << "Bytes read from packet:\t" << len_recv << endl;
kill(pid, SIGGOOD);
while(1) sleep(1);
return OK;
}
void signal_handler_SPL(int sig) {
switch (sig) {
case SIGGOOD:
//cout << "DEBUG: SIGGOOD detected.\n";
sig_get_SPL = true;
sig_good_SPL = true;
break;
case SIGBAD:
cout << "DEBUG: SIGBAD detected.\n";
sig_get_SPL = true;
sig_good_SPL = false;
break;
default:
//cout << "DEBUG: unknown signal detected.\n";
sig_get_SPL = false;
sig_good_SPL = false;
break;
}
}
|
b22ea2947384dd134e9f16729a393f44d4c259cd | 6ccdba429f396d6453d44ea9345e8131f637659c | /gdb.h | dbe1222cf3ec6cf2bad69cf37666eeb89ffcb946 | [
"MIT"
] | permissive | kura197/riscv-simulator | 107de7ce7fae8092843b192cbd4221cced043cbc | 5cdc14f40d45613f0389709931b0165081086557 | refs/heads/master | 2021-10-02T21:54:04.281590 | 2018-12-01T10:41:54 | 2018-12-01T10:41:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,953 | h | gdb.h | #ifndef GDB_H_
#define GDB_H_
#include <iostream>
#include <string>
#include <vector>
#include<sys/time.h>
#include "emulator.h"
/*! Size of the matchpoint hash table. Largest prime < 2^10 */
#define MP_HASH_SIZE 1021
#define GDB_BUF_MAX ((NUM_REGS) * 8 + 1)
#define RSP_TRACE 1
/*! Enumeration of different types of matchpoint. These have explicit values
matching the second digit of 'z' and 'Z' packets. */
enum mp_type {
BP_MEMORY = 0,
BP_HARDWARE = 1,
WP_WRITE = 2,
WP_READ = 3,
WP_ACCESS = 4
};
static const char hexchars[]="0123456789abcdef";
template<typename T>
void remove(std::vector<T>& vector, unsigned int index)
{
vector.erase(vector.begin() + index);
}
class rsp{
int client_waiting; /*!< Is client waiting a response? */
int proto_num; /*!< Number of the protocol used */
int client_fd; /*!< FD for talking to GDB */
Emulator *gdb_emu;
struct timeval tv;
fd_set readfd;
public:
int sigval; /*!< GDB signal for any exception */
bool stop = false;
bool step = false;
bool attach = false;
vector<unsigned int> bp;
int FLAGS_port;
bool FLAGS_p;
rsp(Emulator* emu, int port, bool watch);
~rsp(){ rsp_client_close(); };
void handle_rsp();
//return 0 if success
int rsp_get_client();
int get_rsp_char();
void put_rsp_char(char c);
void rsp_client_request ();
void rsp_client_close ();
string get_packet();
int convert_hex(int c);
void rsp_query(string buf);
void put_str_packet (const string str);
void put_packet (string buf);
void rsp_report_exception();
void rsp_vpkt (string buf);
void rsp_read_all_regs();
void reg2hex (unsigned long int val, string* buf);
void rsp_read_reg(string buf);
void rsp_read_mem (string buf);
void rsp_insert_matchpoint (string buf);
void rsp_remove_matchpoint (string buf);
void rsp_continue(string buf);
void rsp_step (string buf);
int handle_interrupt_rsp();
};
#endif
|
fe1152f80ef0a4afa1c354cc19c49d1832734f46 | 899f43b57ef340f49a8e330b199a4594b9162051 | /Linked_List/src/Node.cpp | 9f0ea891706c985ba98bf0bb68b4b92033bffae0 | [] | no_license | sairajdherange/Algorithms-and-Data-Structures | e546280a76430ca8381a2efd950ac062cb6d65a8 | 859687863e27f24c9c909c156de5aa506c4cdc8a | refs/heads/master | 2022-04-09T22:29:34.662838 | 2020-03-25T08:40:41 | 2020-03-25T08:40:41 | 246,792,478 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 716 | cpp | Node.cpp | //============================================================================
// Name : Node.cpp
// Author : Sairaj Dherange
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include "Node.h"
#include <iostream>
namespace std {
Node::Node() {
this->data = 0 ;
this->next = NULL;
}
void Node::set_data(int data){
this->data = data ;
}
void Node::set_next(Node *next){
this->next = next ;
}
int Node::get_data(){
return this->data;
}
Node* Node::get_next(){
return this->next;
}
Node::~Node() {
// TODO Auto-generated destructor stub
}
} /* namespace std */
|
52a8d469cafdd198127c3b094cc7a43fc81c08d2 | 098de7d77b877755f3acf0153356d8af0467836e | /Aiub indivi con 18-1/Run For Your Prize.cpp | 21766e860e19c26ba4e43e2dc2c8df175554e6cc | [] | no_license | tariqul2814/ACMProblemSolves | 58594deb51bd1d810e1efcf11257d56dc61da285 | d23054508061812cc877237358c32eea5e9616c0 | refs/heads/master | 2020-05-19T11:30:11.848996 | 2019-05-05T06:59:30 | 2019-05-05T06:59:30 | 184,992,045 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 622 | cpp | Run For Your Prize.cpp | #include <bits/stdc++.h>
using namespace std;
long long int n;
long long int arr[1000000];
int main()
{
cin>>n;
for(long long int i=0;i<n;i++)
{
cin>>arr[i];
}
long long int counter=0;
long long int me = 1;
long long int friend1 = 1000000;
for(long long int i=0;i<n;i++)
{
if(abs(arr[i]-me)<abs(friend1-arr[i]))
{
counter+=abs(arr[i]-me);
me = arr[i];
}
else if(abs(arr[i]-me)>abs(friend1-arr[i]))
{
counter+=abs(friend1-arr[i]);
me = arr[i];
}
}
cout << counter <<endl;
}
|
b08c5a4a41ca895f99ede04067b3d5c1f5d3bf9a | d37acb2eec4f53ac7b10abd8562a2f42e6786f6d | /DXDebug.h | 4eaee4b67fe93c0656679fd00904b2a4c7f7eb87 | [] | no_license | EmilFransson/solaris | fbc82633b4f6bdd4cd563f9c886a71ccbe9a1836 | 0d1f097a600dee20fc097f722502e4c1a999ae69 | refs/heads/master | 2023-04-12T03:44:18.275948 | 2021-05-11T12:06:13 | 2021-05-11T12:06:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,894 | h | DXDebug.h | #pragma once
#if defined(DEBUG) | defined (_DEBUG)
#ifndef HR
#define HR(x, var) \
{ \
HRESULT hr = (x); \
if (FAILED(hr)) \
{ \
std::string errorString = "\0"; \
errorString.append("Error: "); \
errorString.append(var); \
errorString.append(" failed."); \
errorString.append("\nFile: "); \
errorString.append(__FILE__); \
errorString.append(".\nLine: "); \
errorString.append(std::to_string(__LINE__)); \
errorString.append(".\nSee console output for detailed debug information.");\
MessageBoxA(nullptr, errorString.c_str(), "ERROR", MB_OK | MB_ICONERROR); \
return false; \
} \
}
#endif
#else
#ifndef HR
#define HR(x, var) (x)
#endif
#endif
#if defined(DEBUG) | defined (_DEBUG)
#ifndef HR_E
#define HR_E(x, y, var) \
{ \
HRESULT hr = (x); \
if (FAILED(hr)) \
{ \
std::string errorString = "\0"; \
errorString.append("Error: "); \
errorString.append(var); \
errorString.append(" failed."); \
errorString.append("\nFile: "); \
errorString.append(__FILE__); \
errorString.append(".\nLine: "); \
errorString.append(std::to_string(__LINE__)); \
errorString.append(".\nSee console output for detailed debug information.");\
Microsoft::WRL::ComPtr<ID3DBlob> pErrorBlob = (y); \
if (pErrorBlob != nullptr) \
{ \
OutputDebugStringA((char*)pErrorBlob->GetBufferPointer()); \
} \
MessageBoxA(nullptr, errorString.c_str(), "ERROR", MB_OK | MB_ICONERROR); \
return false; \
} \
}
#endif
#else
#ifndef HR_E
#define HR_E(x, y, var) (x)
#endif
#endif
#if defined(DEBUG) | defined (_DEBUG)
#ifndef HR_A
#define HR_A(x, var) \
{ \
HRESULT hr = (x); \
if (FAILED(hr)) \
{ \
std::string errorString = "\0"; \
errorString.append("Error: "); \
errorString.append(var); \
errorString.append(" failed."); \
errorString.append("\nFile: "); \
errorString.append(__FILE__); \
errorString.append(".\nLine: "); \
errorString.append(std::to_string(__LINE__)); \
errorString.append(".\nSee console output for detailed debug information.");\
MessageBoxA(nullptr, errorString.c_str(), "ERROR", MB_OK | MB_ICONERROR); \
assert(SUCCEEDED(hr)); \
} \
}
#endif
#else
#ifndef HR_A
#define HR_A(x, var) (x)
#endif
#endif
#if defined(DEBUG) | defined (_DEBUG)
#ifndef HR_X
#define HR_X(x, var) \
{ \
HRESULT hr = (x); \
if (FAILED(hr)) \
{ \
std::string errorString = "\0"; \
errorString.append("Error: "); \
errorString.append(var); \
errorString.append(" failed."); \
errorString.append("\nFile: "); \
errorString.append(__FILE__); \
errorString.append(".\nLine: "); \
errorString.append(std::to_string(__LINE__)); \
errorString.append(".\nSee console output for detailed debug information.");\
MessageBoxA(nullptr, errorString.c_str(), "ERROR", MB_OK | MB_ICONERROR); \
assert(SUCCEEDED(hr)); \
} \
}
#endif
#else
#ifndef HR_X
#define HR_X(x, var) (x)
#endif
#endif |
f4b013d23a3eca8fe86cf3a086e4245b2459a8f6 | 1a558156784f8fba83d80ea1e79c4c92efa52748 | /book_chap5.2/UVA10182.cpp | 3952a2f1c5d6df73595b8e123f52ec1ce4f95207 | [] | no_license | guipingxie1/book_problems | b45ca6e6f29757da31fe63b9cd58eca26b07361b | 30083291d0554fc68debee68998821c5c1232b0a | refs/heads/master | 2021-01-09T20:17:15.879380 | 2017-03-05T21:57:37 | 2017-03-05T21:57:37 | 65,775,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,063 | cpp | UVA10182.cpp | #include <bits/stdc++.h>
using namespace std;
int n, k, p, o, m;
vector<int> v;
int main() {
int idx = 0;
while (k < 100000) {
k = 3 * idx * idx + 3 * idx + 1;
v.push_back(k);
++idx;
}
while (scanf("%d", &n) == 1) {
k = lower_bound(v.begin(), v.end(), n) - v.begin();
if (n == v[k]) {
printf("%d 0\n", k);
} else {
p = (n - v[k - 1]) / k;
m = v[k - 1] + 1 + p * k;
o = n - m;
if (p == 0) {
printf("%d %d\n", k - 1 - o, 1 + o);
} else if (p == 1) {
printf("%d %d\n", -1 - o, k);
} else if (p == 2) {
printf("%d %d\n", -k, k - 1 - o);
} else if (p == 3) {
printf("%d %d\n", o - (k - 1), -1 - o);
} else if (p == 4) {
printf("%d %d\n", 1 + o, -k);
} else if (p == 5) {
printf("%d %d\n", k, o - (k - 1));
}
}
}
return 0;
}
|
e36dc88fb8e53a039d17cb6241e6b0a6414590bd | 0cffef7438a0379199aefa29469e719918a582a3 | /examples/volcano/command.inl | d622219308cbe8be6eb5cf4082fcc1104a658b05 | [
"LicenseRef-scancode-public-domain",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | djohansson/slang | b0251f97b5ad6ad202a1b5b5233d4b02aa05c639 | 6d616c065dc8c9b344987d350c05d536a01141dc | refs/heads/master | 2023-05-27T17:31:47.515021 | 2023-05-12T21:43:00 | 2023-05-12T21:43:00 | 159,946,191 | 2 | 0 | MIT | 2018-12-01T13:14:51 | 2018-12-01T13:14:51 | null | UTF-8 | C++ | false | false | 2,051 | inl | command.inl | template <GraphicsBackend B>
CommandBufferAccessScope<B>
CommandPoolContext<B>::commands(const CommandBufferAccessScopeDesc<B>& beginInfo)
{
if (myRecordingCommands[beginInfo.level] &&
myRecordingCommands[beginInfo.level].value().getDesc() == beginInfo)
return internalCommands(beginInfo);
else
return internalBeginScope(beginInfo);
}
template <GraphicsBackend B>
void CommandPoolContext<B>::internalEndCommands(CommandBufferLevel<B> level)
{
if (myRecordingCommands[level])
myRecordingCommands[level] = std::nullopt;
}
template <GraphicsBackend B>
CommandBufferAccessScope<B>::CommandBufferAccessScope(
CommandBufferArray<B>* array, const CommandBufferAccessScopeDesc<B>& beginInfo)
: myDesc(beginInfo)
, myRefCount(std::make_shared<uint32_t>(1))
, myArray(array)
, myIndex(myDesc.scopedBeginEnd ? myArray->begin(beginInfo) : 0)
{}
template <GraphicsBackend B>
CommandBufferAccessScope<B>::CommandBufferAccessScope(const CommandBufferAccessScope& other)
: myDesc(other.myDesc)
, myRefCount(other.myRefCount)
, myArray(other.myArray)
, myIndex(other.myIndex)
{
(*myRefCount)++;
}
template <GraphicsBackend B>
CommandBufferAccessScope<B>::CommandBufferAccessScope(CommandBufferAccessScope&& other) noexcept
: myDesc(std::exchange(other.myDesc, {}))
, myRefCount(std::exchange(other.myRefCount, {}))
, myArray(std::exchange(other.myArray, {}))
, myIndex(std::exchange(other.myIndex, {}))
{}
template <GraphicsBackend B>
CommandBufferAccessScope<B>::~CommandBufferAccessScope()
{
if (myDesc.scopedBeginEnd && myRefCount && (--(*myRefCount) == 0) &&
myArray->recording(myIndex))
myArray->end(myIndex);
}
template <GraphicsBackend B>
CommandBufferAccessScope<B>& CommandBufferAccessScope<B>::operator=(CommandBufferAccessScope other)
{
swap(other);
return *this;
}
template <GraphicsBackend B>
void CommandBufferAccessScope<B>::swap(CommandBufferAccessScope& rhs) noexcept
{
std::swap(myDesc, rhs.myDesc);
std::swap(myRefCount, rhs.myRefCount);
std::swap(myArray, rhs.myArray);
std::swap(myIndex, rhs.myIndex);
}
|
ce7f6fb0ef1c5ab61305252a8454907d1190c955 | a0eb9016e9a705502561323a711b14190f513d77 | /BlasterMasterEngine/src/Core/Input/Input.cpp | 5683678e91629437e73bdde64fa690d6dbb9bee3 | [] | no_license | Hengle/BlasterMasterEngine | c65d4cf49238951aac229406f568c5ca09c87d60 | 0e58882799bd0166ace3893f0c4a30a5f9f1322f | refs/heads/main | 2023-04-03T21:00:23.931203 | 2021-03-23T05:47:24 | 2021-03-23T05:47:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,632 | cpp | Input.cpp | #include "d3dpch.h"
#include "Input.h"
DIMOUSESTATE2 Input::currentMouseState = {};
DIMOUSESTATE2 Input::previousMouseState = {};
std::array<BYTE, 256> Input::previousKeyState = {};
std::array<BYTE, 256> Input::currentKeyState = {};
Input::Input()
{
dinput = NULL;
dimouse = NULL;
dikeyboard = NULL;
}
Input::~Input()
{
ReleaseMouse();
ReleaseKeyboard();
}
HRESULT Input::CreateInputResources(HWND hWnd)
{
HRESULT hr = S_OK;
hr = DirectInput8Create(
GetModuleHandle(NULL),
DIRECTINPUT_VERSION,
IID_IDirectInput8,
(void**)&dinput,
NULL);
if (FAILED(hr))
{
__ASSERT(false, "Unable to create Direct Input resources!");
}
return hr;
}
HRESULT Input::CreateKeyboardDevice(HWND hWnd)
{
HRESULT hr = S_OK;
hr = dinput->CreateDevice(GUID_SysKeyboard,
&dikeyboard, NULL);
if (FAILED(hr))
{
__ASSERT(false, "Unable to create keyboard device!");
return hr;
}
hr = dikeyboard->SetDataFormat(&c_dfDIKeyboard);
if (FAILED(hr))
{
__ASSERT(false, "Unable to set data format!");
return hr;
}
hr = dikeyboard->SetCooperativeLevel(hWnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND);
if (FAILED(hr))
{
__ASSERT(false, "Unable to set cooperative level!");
return hr;
}
hr = dikeyboard->Acquire();
if (FAILED(hr))
{
if (hr == E_ACCESSDENIED)
{
hr = S_OK;
}
else
{
__ASSERT(false, "Unable to acquire keyboard!");
}
return hr;
}
return hr;
}
HRESULT Input::CreateMouseDevice(HWND hWnd)
{
HRESULT hr = S_OK;
ZeroMemory(¤tMouseState, sizeof(currentMouseState));
ZeroMemory(&previousMouseState, sizeof(previousMouseState));
hr = dinput->CreateDevice(GUID_SysMouse,
&dimouse, NULL);
if (FAILED(hr))
{
__ASSERT(false, "Unable to create mouse device!");
return hr;
}
hr = dimouse->SetDataFormat(&c_dfDIMouse2);
if (FAILED(hr))
{
__ASSERT(false, "Unable to set data format!");
return hr;
}
hr = dimouse->SetCooperativeLevel(hWnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND);
if (FAILED(hr))
{
__ASSERT(false, "Unable to set cooperative level!");
return hr;
}
hr = dimouse->Acquire();
if (FAILED(hr))
{
if (hr == E_ACCESSDENIED)
{
hr = S_OK;
}
else
{
__ASSERT(false, "Unable to acquire keyboard!");
}
return hr;
}
return hr;
}
void Input::ReleaseMouse()
{
if (dimouse != NULL)
{
dimouse->Unacquire();
dimouse->Release();
dimouse = NULL;
}
}
void Input::ReleaseKeyboard()
{
if (dikeyboard != NULL)
{
dikeyboard->Unacquire();
dikeyboard->Release();
dikeyboard = NULL;
}
}
void Input::GetMouse()
{
previousMouseState = currentMouseState;
HRESULT hr = dimouse->GetDeviceState(sizeof(DIMOUSESTATE2), (LPVOID)¤tMouseState);
if (FAILED(hr))
{
ZeroMemory(¤tMouseState, sizeof(currentMouseState));
dimouse->Acquire();
}
}
void Input::GetKeyboard()
{
previousKeyState = currentKeyState;
HRESULT hr = dikeyboard->GetDeviceState(sizeof(currentKeyState), (LPVOID)¤tKeyState);
if (FAILED(hr))
{
dikeyboard->Acquire();
}
}
float Input::GetMouseX()
{
return (float)currentMouseState.lX;
}
float Input::GetMouseY()
{
return (float)currentMouseState.lY;
}
float Input::GetMouseZ()
{
return (float)currentMouseState.lZ;
}
bool Input::GetMouseButtonDown(int button)
{
return ((currentMouseState.rgbButtons[button] & 0x80) && !(previousMouseState.rgbButtons[button] & 0x80));
}
bool Input::GetKeyDown(int keyCode)
{
return ((currentKeyState[keyCode] & 0x80) && !(previousKeyState[keyCode] & 0x80));
}
bool Input::GetMouseButton(int button)
{
return (currentMouseState.rgbButtons[button] & 0x80);
}
bool Input::GetKey(int keyCode)
{
return (currentKeyState[keyCode] & 0x80);
} |
60df268b909483f2811bf025bd103f8e628934b9 | e9eeb732649583342807b32a495e4e11720774a4 | /src/graphics/unitGI.cc | df7d634c833ec116e186b9c282e8a006a787a5e8 | [] | no_license | V1nc3ntL/ProjetS7CPP | c504d241fcd7701d29bfc28b9835908929aac1b5 | 10dc2463b58c0f1e5bc9a57aee9247b2599d6596 | refs/heads/main | 2023-02-20T17:26:31.456895 | 2021-01-25T22:26:11 | 2021-01-25T22:26:11 | 321,944,080 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 790 | cc | unitGI.cc | /*! \file unitGI.cc
* \brief A graphical interface to dysplay units
* \author Vincent Lefebvre
* \version 0.1
* \date 21/01/25
*/
#include "unitGI.hh"
#include MAP_GI_H
#include <iostream>
UnitGI::UnitGI(Unit & unit,MapGI & map ):
theUnit(unit)
{
TileGI gi;
if (unitTexture[unit.getType()].loadFromFile(IMGS_DIR+spriteTab[unit.getType()]))
sprit.setTexture(unitTexture[unit.getType()]);
sprit.setPosition(map.getTileAt(unit.getPos()).leftAngle().first
+map.getSquareSize()-
sprit.getGlobalBounds().width/2-MARGIN,
map.getTileAt(unit.getPos()).leftAngle().second -
sprit.getGlobalBounds().height);
}
|
414fde872bb261f8a7aaf383881f5d0d274e00a9 | 199db94b48351203af964bada27a40cb72c58e16 | /lang/jap/gen/Bible66.h | 748a4de55d1adb94257fc3b592a0b792cf2680d6 | [] | no_license | mkoldaev/bible50cpp | 04bf114c1444662bb90c7e51bd19b32e260b4763 | 5fb1fb8bd2e2988cf27cfdc4905d2702b7c356c6 | refs/heads/master | 2023-04-05T01:46:32.728257 | 2021-04-01T22:36:06 | 2021-04-01T22:36:06 | 353,830,130 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 87,248 | h | Bible66.h | #include <map>
#include <string>
class Bible66
{
struct jap1 { int val; const char *msg; };
struct jap2 { int val; const char *msg; };
struct jap3 { int val; const char *msg; };
struct jap4 { int val; const char *msg; };
struct jap5 { int val; const char *msg; };
struct jap6 { int val; const char *msg; };
struct jap7 { int val; const char *msg; };
struct jap8 { int val; const char *msg; };
struct jap9 { int val; const char *msg; };
struct jap10 { int val; const char *msg; };
struct jap11 { int val; const char *msg; };
struct jap12 { int val; const char *msg; };
struct jap13 { int val; const char *msg; };
struct jap14 { int val; const char *msg; };
struct jap15 { int val; const char *msg; };
struct jap16 { int val; const char *msg; };
struct jap17 { int val; const char *msg; };
struct jap18 { int val; const char *msg; };
struct jap19 { int val; const char *msg; };
struct jap20 { int val; const char *msg; };
struct jap21 { int val; const char *msg; };
struct jap22 { int val; const char *msg; };
public:
static void view1() {
struct jap1 poems[] = {
{1, "1 イエス・キリストの黙示。この黙示は、神が、すぐにも起るべきことをその僕たちに示すためキリストに与え、そして、キリストが、御使をつかわして、僕ヨハネに伝えられたものである。"},
{2, "2 ヨハネは、神の言とイエス・キリストのあかしと、すなわち、自分が見たすべてのことをあかしした。"},
{3, "3 この預言の言葉を朗読する者と、これを聞いて、その中に書かれていることを守る者たちとは、さいわいである。時が近づいているからである。"},
{4, "4 ヨハネからアジヤにある七つの教会へ。今いまし、昔いまし、やがてきたるべきかたから、また、その御座の前にある七つの霊から、"},
{5, "5 また、忠実な証人、死人の中から最初に生れた者、地上の諸王の支配者であるイエス・キリストから、恵みと平安とが、あなたがたにあるように。わたしたちを愛し、その血によってわたしたちを罪から解放し、"},
{6, "6 わたしたちを、その父なる神のために、御国の民とし、祭司として下さったかたに、世々限りなく栄光と権力とがあるように、アァメン。"},
{7, "7 見よ、彼は、雲に乗ってこられる。すべての人の目、ことに、彼を刺しとおした者たちは、彼を仰ぎ見るであろう。また地上の諸族はみな、彼のゆえに胸を打って嘆くであろう。しかり、アァメン。"},
{8, "8 今いまし、昔いまし、やがてきたるべき者、全能者にして主なる神が仰せになる、「わたしはアルパであり、オメガである」。"},
{9, "9 あなたがたの兄弟であり、共にイエスの苦難と御国と忍耐とにあずかっている、わたしヨハネは、神の言とイエスのあかしとのゆえに、パトモスという島にいた。"},
{10, "10 ところが、わたしは、主の日に御霊に感じた。そして、わたしのうしろの方で、ラッパのような大きな声がするのを聞いた。"},
{11, "11 その声はこう言った、「あなたが見ていることを書きものにして、それをエペソ、スミルナ、ペルガモ、テアテラ、サルデス、ヒラデルヒヤ、ラオデキヤにある七つの教会に送りなさい」。"},
{12, "12 そこでわたしは、わたしに呼びかけたその声を見ようとしてふりむいた。ふりむくと、七つの金の燭台が目についた。"},
{13, "13 それらの燭台の間に、足までたれた上着を着、胸に金の帯をしめている人の子のような者がいた。"},
{14, "14 そのかしらと髪の毛とは、雪のように白い羊毛に似て真白であり、目は燃える炎のようであった。"},
{15, "15 その足は、炉で精錬されて光り輝くしんちゅうのようであり、声は大水のとどろきのようであった。"},
{16, "16 その右手に七つの星を持ち、口からは、鋭いもろ刃のつるぎがつき出ており、顔は、強く照り輝く太陽のようであった。"},
{17, "17 わたしは彼を見たとき、その足もとに倒れて死人のようになった。すると、彼は右手をわたしの上において言った、「恐れるな。わたしは初めであり、終りであり、"},
{18, "18 また、生きている者である。わたしは死んだことはあるが、見よ、世々限りなく生きている者である。そして、死と黄泉とのかぎを持っている。"},
{19, "19 そこで、あなたの見たこと、現在のこと、今後起ろうとすることを、書きとめなさい。"},
{20, "20 あなたがわたしの右手に見た七つの星と、七つの金の燭台との奥義は、こうである。すなわち、七つの星は七つの教会の御使であり、七つの燭台は七つの教会である。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view2() {
struct jap2 poems[] = {
{1, "1 エペソにある教会の御使に、こう書きおくりなさい。『右の手に七つの星を持つ者、七つの金の燭台の間を歩く者が、次のように言われる。"},
{2, "2 わたしは、あなたのわざと労苦と忍耐とを知っている。また、あなたが、悪い者たちをゆるしておくことができず、使徒と自称してはいるが、その実、使徒でない者たちをためしてみて、にせ者であると見抜いたことも、知っている。"},
{3, "3 あなたは忍耐をし続け、わたしの名のために忍びとおして、弱り果てることがなかった。"},
{4, "4 しかし、あなたに対して責むべきことがある。あなたは初めの愛から離れてしまった。"},
{5, "5 そこで、あなたはどこから落ちたかを思い起し、悔い改めて初めのわざを行いなさい。もし、そうしないで悔い改めなければ、わたしはあなたのところにきて、あなたの燭台をその場所から取りのけよう。"},
{6, "6 しかし、こういうことはある、あなたはニコライ宗の人々のわざを憎んでおり、わたしもそれを憎んでいる。"},
{7, "7 耳のある者は、御霊が諸教会に言うことを聞くがよい。勝利を得る者には、神のパラダイスにあるいのちの木の実を食べることをゆるそう』。"},
{8, "8 スミルナにある教会の御使に、こう書きおくりなさい。『初めであり、終りである者、死んだことはあるが生き返った者が、次のように言われる。"},
{9, "9 わたしは、あなたの苦難や、貧しさを知っている(しかし実際は、あなたは富んでいるのだ)。また、ユダヤ人と自称してはいるが、その実ユダヤ人でなくてサタンの会堂に属する者たちにそしられていることも、わたしは知っている。"},
{10, "10 あなたの受けようとする苦しみを恐れてはならない。見よ、悪魔が、あなたがたのうちのある者をためすために、獄に入れようとしている。あなたがたは十日の間、苦難にあうであろう。死に至るまで忠実であれ。そうすれば、いのちの冠を与えよう。"},
{11, "11 耳のある者は、御霊が諸教会に言うことを聞くがよい。勝利を得る者は、第二の死によって滅ぼされることはない』。"},
{12, "12 ペルガモにある教会の御使に、こう書きおくりなさい。『鋭いもろ刃のつるぎを持っているかたが、次のように言われる。"},
{13, "13 わたしはあなたの住んでいる所を知っている。そこにはサタンの座がある。あなたは、わたしの名を堅く持ちつづけ、わたしの忠実な証人アンテパスがサタンの住んでいるあなたがたの所で殺された時でさえ、わたしに対する信仰を捨てなかった。"},
{14, "14 しかし、あなたに対して責むべきことが、少しばかりある。あなたがたの中には、現にバラムの教を奉じている者がある。バラムは、バラクに教え込み、イスラエルの子らの前に、つまずきになるものを置かせて、偶像にささげたものを食べさせ、また不品行をさせたのである。"},
{15, "15 同じように、あなたがたの中には、ニコライ宗の教を奉じている者もいる。"},
{16, "16 だから、悔い改めなさい。そうしないと、わたしはすぐにあなたのところに行き、わたしの口のつるぎをもって彼らと戦おう。"},
{17, "17 耳のある者は、御霊が諸教会に言うことを聞くがよい。勝利を得る者には、隠されているマナを与えよう。また、白い石を与えよう。この石の上には、これを受ける者のほかだれも知らない新しい名が書いてある』。"},
{18, "18 テアテラにある教会の御使に、こう書きおくりなさい。『燃える炎のような目と光り輝くしんちゅうのような足とを持った神の子が、次のように言われる。"},
{19, "19 わたしは、あなたのわざと、あなたの愛と信仰と奉仕と忍耐とを知っている。また、あなたの後のわざが、初めのよりもまさっていることを知っている。"},
{20, "20 しかし、あなたに対して責むべきことがある。あなたは、あのイゼベルという女を、そのなすがままにさせている。この女は女預言者と自称し、わたしの僕たちを教え、惑わして、不品行をさせ、偶像にささげたものを食べさせている。"},
{21, "21 わたしは、この女に悔い改めるおりを与えたが、悔い改めてその不品行をやめようとはしない。"},
{22, "22 見よ、わたしはこの女を病の床に投げ入れる。この女と姦淫する者をも、悔い改めて彼女のわざから離れなければ、大きな患難の中に投げ入れる。"},
{23, "23 また、この女の子供たちをも打ち殺そう。こうしてすべての教会は、わたしが人の心の奥底までも探り知る者であることを悟るであろう。そしてわたしは、あなたがたひとりびとりのわざに応じて報いよう。"},
{24, "24 また、テアテラにいるほかの人たちで、まだあの女の教を受けておらず、サタンの、いわゆる「深み」を知らないあなたがたに言う。わたしは別にほかの重荷を、あなたがたに負わせることはしない。"},
{25, "25 ただ、わたしが来る時まで、自分の持っているものを堅く保っていなさい。"},
{26, "26 勝利を得る者、わたしのわざを最後まで持ち続ける者には、諸国民を支配する権威を授ける。"},
{27, "27 彼は鉄のつえをもって、ちょうど土の器を砕くように、彼らを治めるであろう。それは、わたし自身が父から権威を受けて治めるのと同様である。"},
{28, "28 わたしはまた、彼に明けの明星を与える。"},
{29, "29 耳のある者は、御霊が諸教会に言うことを聞くがよい』。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view3() {
struct jap3 poems[] = {
{1, "1 サルデスにある教会の御使に、こう書きおくりなさい。『神の七つの霊と七つの星とを持つかたが、次のように言われる。わたしはあなたのわざを知っている。すなわち、あなたは、生きているというのは名だけで、実は死んでいる。"},
{2, "2 目をさましていて、死にかけている残りの者たちを力づけなさい。わたしは、あなたのわざが、わたしの神のみまえに完全であるとは見ていない。"},
{3, "3 だから、あなたが、どのようにして受けたか、また聞いたかを思い起して、それを守りとおし、かつ悔い改めなさい。もし目をさましていないなら、わたしは盗人のように来るであろう。どんな時にあなたのところに来るか、あなたには決してわからない。"},
{4, "4 しかし、サルデスにはその衣を汚さない人が、数人いる。彼らは白い衣を着て、わたしと共に歩みを続けるであろう。彼らは、それにふさわしい者である。"},
{5, "5 勝利を得る者は、このように白い衣を着せられるのである。わたしは、その名をいのちの書から消すようなことを、決してしない。また、わたしの父と御使たちの前で、その名を言いあらわそう。"},
{6, "6 耳のある者は、御霊が諸教会に言うことを聞くがよい』。"},
{7, "7 ヒラデルヒヤにある教会の御使に、こう書きおくりなさい。『聖なる者、まことなる者、ダビデのかぎを持つ者、開けばだれにも閉じられることがなく、閉じればだれにも開かれることのない者が、次のように言われる。"},
{8, "8 わたしは、あなたのわざを知っている。見よ、わたしは、あなたの前に、だれも閉じることのできない門を開いておいた。なぜなら、あなたには少ししか力がなかったにもかかわらず、わたしの言葉を守り、わたしの名を否まなかったからである。"},
{9, "9 見よ、サタンの会堂に属する者、すなわち、ユダヤ人と自称してはいるが、その実ユダヤ人でなくて、偽る者たちに、こうしよう。見よ、彼らがあなたの足もとにきて平伏するようにし、そして、わたしがあなたを愛していることを、彼らに知らせよう。"},
{10, "10 忍耐についてのわたしの言葉をあなたが守ったから、わたしも、地上に住む者たちをためすために、全世界に臨もうとしている試錬の時に、あなたを防ぎ守ろう。"},
{11, "11 わたしは、すぐに来る。あなたの冠がだれにも奪われないように、自分の持っているものを堅く守っていなさい。"},
{12, "12 勝利を得る者を、わたしの神の聖所における柱にしよう。彼は決して二度と外へ出ることはない。そして彼の上に、わたしの神の御名と、わたしの神の都、すなわち、天とわたしの神のみもとから下ってくる新しいエルサレムの名と、わたしの新しい名とを、書きつけよう。"},
{13, "13 耳のある者は、御霊が諸教会に言うことを聞くがよい』。"},
{14, "14 ラオデキヤにある教会の御使に、こう書きおくりなさい。『アァメンたる者、忠実な、まことの証人、神に造られたものの根源であるかたが、次のように言われる。"},
{15, "15 わたしはあなたのわざを知っている。あなたは冷たくもなく、熱くもない。むしろ、冷たいか熱いかであってほしい。"},
{16, "16 このように、熱くもなく、冷たくもなく、なまぬるいので、あなたを口から吐き出そう。"},
{17, "17 あなたは、自分は富んでいる、豊かになった、なんの不自由もないと言っているが、実は、あなた自身がみじめな者、あわれむべき者、貧しい者、目の見えない者、裸な者であることに気がついていない。"},
{18, "18 そこで、あなたに勧める。富む者となるために、わたしから火で精錬された金を買い、また、あなたの裸の恥をさらさないため身に着けるように、白い衣を買いなさい。また、見えるようになるため、目にぬる目薬を買いなさい。"},
{19, "19 すべてわたしの愛している者を、わたしはしかったり、懲らしめたりする。だから、熱心になって悔い改めなさい。"},
{20, "20 見よ、わたしは戸の外に立って、たたいている。だれでもわたしの声を聞いて戸をあけるなら、わたしはその中にはいって彼と食を共にし、彼もまたわたしと食を共にするであろう。"},
{21, "21 勝利を得る者には、わたしと共にわたしの座につかせよう。それはちょうど、わたしが勝利を得てわたしの父と共にその御座についたのと同様である。"},
{22, "22 耳のある者は、御霊が諸教会に言うことを聞くがよい』」。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view4() {
struct jap4 poems[] = {
{1, "1 その後、わたしが見ていると、見よ、開いた門が天にあった。そして、さきにラッパのような声でわたしに呼びかけるのを聞いた初めの声が、「ここに上ってきなさい。そうしたら、これから後に起るべきことを、見せてあげよう」と言った。"},
{2, "2 すると、たちまち、わたしは御霊に感じた。見よ、御座が天に設けられており、その御座にいますかたがあった。"},
{3, "3 その座にいますかたは、碧玉や赤めのうのように見え、また、御座のまわりには、緑玉のように見えるにじが現れていた。"},
{4, "4 また、御座のまわりには二十四の座があって、二十四人の長老が白い衣を身にまとい、頭に金の冠をかぶって、それらの座についていた。"},
{5, "5 御座からは、いなずまと、もろもろの声と、雷鳴とが、発していた。また、七つのともし火が、御座の前で燃えていた。これらは、神の七つの霊である。"},
{6, "6 御座の前は、水晶に似たガラスの海のようであった。御座のそば近くそのまわりには、四つの生き物がいたが、その前にも後にも、一面に目がついていた。"},
{7, "7 第一の生き物はししのようであり、第二の生き物は雄牛のようであり、第三の生き物は人のような顔をしており、第四の生き物は飛ぶわしのようであった。"},
{8, "8 この四つの生き物には、それぞれ六つの翼があり、その翼のまわりも内側も目で満ちていた。そして、昼も夜も、絶え間なくこう叫びつづけていた、「聖なるかな、聖なるかな、聖なるかな、全能者にして主なる神。昔いまし、今いまし、やがてきたるべき者」。"},
{9, "9 これらの生き物が、御座にいまし、かつ、世々限りなく生きておられるかたに、栄光とほまれとを帰し、また、感謝をささげている時、"},
{10, "10 二十四人の長老は、御座にいますかたのみまえにひれ伏し、世々限りなく生きておられるかたを拝み、彼らの冠を御座のまえに、投げ出して言った、"},
{11, "11 「われらの主なる神よ、あなたこそは、栄光とほまれと力とを受けるにふさわしいかた。あなたは万物を造られました。御旨によって、万物は存在し、また造られたのであります」。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view5() {
struct jap5 poems[] = {
{1, "1 わたしはまた、御座にいますかたの右の手に、巻物があるのを見た。その内側にも外側にも字が書いてあって、七つの封印で封じてあった。"},
{2, "2 また、ひとりの強い御使が、大声で、「その巻物を開き、封印をとくのにふさわしい者は、だれか」と呼ばわっているのを見た。"},
{3, "3 しかし、天にも地にも地の下にも、この巻物を開いて、それを見ることのできる者は、ひとりもいなかった。"},
{4, "4 巻物を開いてそれを見るのにふさわしい者が見当らないので、わたしは激しく泣いていた。"},
{5, "5 すると、長老のひとりがわたしに言った、「泣くな。見よ、ユダ族のしし、ダビデの若枝であるかたが、勝利を得たので、その巻物を開き七つの封印を解くことができる」。"},
{6, "6 わたしはまた、御座と四つの生き物との間、長老たちの間に、ほふられたとみえる小羊が立っているのを見た。それに七つの角と七つの目とがあった。これらの目は、全世界につかわされた、神の七つの霊である。"},
{7, "7 小羊は進み出て、御座にいますかたの右の手から、巻物を受けとった。"},
{8, "8 巻物を受けとった時、四つの生き物と二十四人の長老とは、おのおの、立琴と、香の満ちている金の鉢とを手に持って、小羊の前にひれ伏した。この香は聖徒の祈である。"},
{9, "9 彼らは新しい歌を歌って言った、「あなたこそは、その巻物を受けとり、封印を解くにふさわしいかたであります。あなたはほふられ、その血によって、神のために、あらゆる部族、国語、民族、国民の中から人々をあがない、"},
{10, "10 わたしたちの神のために、彼らを御国の民とし、祭司となさいました。彼らは地上を支配するに至るでしょう」。"},
{11, "11 さらに見ていると、御座と生き物と長老たちとのまわりに、多くの御使たちの声が上がるのを聞いた。その数は万の幾万倍、千の幾千倍もあって、"},
{12, "12 大声で叫んでいた、「ほふられた小羊こそは、力と、富と、知恵と、勢いと、ほまれと、栄光と、さんびとを受けるにふさわしい」。"},
{13, "13 またわたしは、天と地、地の下と海の中にあるすべての造られたもの、そして、それらの中にあるすべてのものの言う声を聞いた、「御座にいますかたと小羊とに、さんびと、ほまれと、栄光と、権力とが、世々限りなくあるように」。"},
{14, "14 四つの生き物はアァメンと唱え、長老たちはひれ伏して礼拝した。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view6() {
struct jap6 poems[] = {
{1, "1 小羊がその七つの封印の一つを解いた時、わたしが見ていると、四つの生き物の一つが、雷のような声で「きたれ」と呼ぶのを聞いた。"},
{2, "2 そして見ていると、見よ、白い馬が出てきた。そして、それに乗っている者は、弓を手に持っており、また冠を与えられて、勝利の上にもなお勝利を得ようとして出かけた。"},
{3, "3 小羊が第二の封印を解いた時、第二の生き物が「きたれ」と言うのを、わたしは聞いた。"},
{4, "4 すると今度は、赤い馬が出てきた。そして、それに乗っている者は、人々が互に殺し合うようになるために、地上から平和を奪い取ることを許され、また、大きなつるぎを与えられた。"},
{5, "5 また、第三の封印を解いた時、第三の生き物が「きたれ」と言うのを、わたしは聞いた。そこで見ていると、見よ、黒い馬が出てきた。そして、それに乗っている者は、はかりを手に持っていた。"},
{6, "6 すると、わたしは四つの生き物の間から出て来ると思われる声が、こう言うのを聞いた、「小麦一ますは一デナリ。大麦三ますも一デナリ。オリブ油とぶどう酒とを、そこなうな」。"},
{7, "7 小羊が第四の封印を解いた時、第四の生き物が「きたれ」と言う声を、わたしは聞いた。"},
{8, "8 そこで見ていると、見よ、青白い馬が出てきた。そして、それに乗っている者の名は「死」と言い、それに黄泉が従っていた。彼らには、地の四分の一を支配する権威、および、つるぎと、ききんと、死と、地の獣らとによって人を殺す権威とが、与えられた。"},
{9, "9 小羊が第五の封印を解いた時、神の言のゆえに、また、そのあかしを立てたために、殺された人々の霊魂が、祭壇の下にいるのを、わたしは見た。"},
{10, "10 彼らは大声で叫んで言った、「聖なる、まことなる主よ。いつまであなたは、さばくことをなさらず、また地に住む者に対して、わたしたちの血の報復をなさらないのですか」。"},
{11, "11 すると、彼らのひとりびとりに白い衣が与えられ、それから、「彼らと同じく殺されようとする僕仲間や兄弟たちの数が満ちるまで、もうしばらくの間、休んでいるように」と言い渡された。"},
{12, "12 小羊が第六の封印を解いた時、わたしが見ていると、大地震が起って、太陽は毛織の荒布のように黒くなり、月は全面、血のようになり、"},
{13, "13 天の星は、いちじくのまだ青い実が大風に揺られて振り落されるように、地に落ちた。"},
{14, "14 天は巻物が巻かれるように消えていき、すべての山と島とはその場所から移されてしまった。"},
{15, "15 地の王たち、高官、千卒長、富める者、勇者、奴隷、自由人らはみな、ほら穴や山の岩かげに、身をかくした。"},
{16, "16 そして、山と岩とにむかって言った、「さあ、われわれをおおって、御座にいますかたの御顔と小羊の怒りとから、かくまってくれ。"},
{17, "17 御怒りの大いなる日が、すでにきたのだ。だれが、その前に立つことができようか」。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view7() {
struct jap7 poems[] = {
{1, "1 この後、わたしは四人の御使が地の四すみに立っているのを見た。彼らは地の四方の風をひき止めて、地にも海にもすべての木にも、吹きつけないようにしていた。"},
{2, "2 また、もうひとりの御使が、生ける神の印を持って、日の出る方から上って来るのを見た。彼は地と海とをそこなう権威を授かっている四人の御使にむかって、大声で叫んで言った、"},
{3, "3 「わたしたちの神の僕らの額に、わたしたちが印をおしてしまうまでは、地と海と木とをそこなってはならない」。"},
{4, "4 わたしは印をおされた者の数を聞いたが、イスラエルの子らのすべての部族のうち、印をおされた者は十四万四千人であった。"},
{5, "5 ユダの部族のうち、一万二千人が印をおされ、ルベンの部族のうち、一万二千人、ガドの部族のうち、一万二千人、"},
{6, "6 アセルの部族のうち、一万二千人、ナフタリの部族のうち、一万二千人、マナセの部族のうち、一万二千人、"},
{7, "7 シメオンの部族のうち、一万二千人、レビの部族のうち、一万二千人、イサカルの部族のうち、一万二千人、"},
{8, "8 ゼブルンの部族のうち、一万二千人、ヨセフの部族のうち、一万二千人、ベニヤミンの部族のうち、一万二千人が印をおされた。"},
{9, "9 その後、わたしが見ていると、見よ、あらゆる国民、部族、民族、国語のうちから、数えきれないほどの大ぜいの群衆が、白い衣を身にまとい、しゅろの枝を手に持って、御座と小羊との前に立ち、"},
{10, "10 大声で叫んで言った、「救は、御座にいますわれらの神と小羊からきたる」。"},
{11, "11 御使たちはみな、御座と長老たちと四つの生き物とのまわりに立っていたが、御座の前にひれ伏し、神を拝して言った、"},
{12, "12 「アァメン、さんび、栄光、知恵、感謝、ほまれ、力、勢いが、世々限りなく、われらの神にあるように、アァメン」。"},
{13, "13 長老たちのひとりが、わたしにむかって言った、「この白い衣を身にまとっている人々は、だれか。また、どこからきたのか」。"},
{14, "14 わたしは彼に答えた、「わたしの主よ、それはあなたがご存じです」。すると、彼はわたしに言った、「彼らは大きな患難をとおってきた人たちであって、その衣を小羊の血で洗い、それを白くしたのである。"},
{15, "15 それだから彼らは、神の御座の前におり、昼も夜もその聖所で神に仕えているのである。御座にいますかたは、彼らの上に幕屋を張って共に住まわれるであろう。"},
{16, "16 彼らは、もはや飢えることがなく、かわくこともない。太陽も炎暑も、彼らを侵すことはない。"},
{17, "17 御座の正面にいます小羊は彼らの牧者となって、いのちの水の泉に導いて下さるであろう。また神は、彼らの目から涙をことごとくぬぐいとって下さるであろう」。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view8() {
struct jap8 poems[] = {
{1, "1 小羊が第七の封印を解いた時、半時間ばかり天に静けさがあった。"},
{2, "2 それからわたしは、神のみまえに立っている七人の御使を見た。そして、七つのラッパが彼らに与えられた。"},
{3, "3 また、別の御使が出てきて、金の香炉を手に持って祭壇の前に立った。たくさんの香が彼に与えられていたが、これは、すべての聖徒の祈に加えて、御座の前の金の祭壇の上にささげるためのものであった。"},
{4, "4 香の煙は、御使の手から、聖徒たちの祈と共に神のみまえに立ちのぼった。"},
{5, "5 御使はその香炉をとり、これに祭壇の火を満たして、地に投げつけた。すると、多くの雷鳴と、もろもろの声と、いなずまと、地震とが起った。"},
{6, "6 そこで、七つのラッパを持っている七人の御使が、それを吹く用意をした。"},
{7, "7 第一の御使が、ラッパを吹き鳴らした。すると、血のまじった雹と火とがあらわれて、地上に降ってきた。そして、地の三分の一が焼け、木の三分の一が焼け、また、すべての青草も焼けてしまった。"},
{8, "8 第二の御使が、ラッパを吹き鳴らした。すると、火の燃えさかっている大きな山のようなものが、海に投げ込まれた。そして、海の三分の一は血となり、"},
{9, "9 海の中の造られた生き物の三分の一は死に、舟の三分の一がこわされてしまった。"},
{10, "10 第三の御使が、ラッパを吹き鳴らした。すると、たいまつのように燃えている大きな星が、空から落ちてきた。そしてそれは、川の三分の一とその水源との上に落ちた。"},
{11, "11 この星の名は「苦よもぎ」と言い、水の三分の一が「苦よもぎ」のように苦くなった。水が苦くなったので、そのために多くの人が死んだ。"},
{12, "12 第四の御使が、ラッパを吹き鳴らした。すると、太陽の三分の一と、月の三分の一と、星の三分の一とが打たれて、これらのものの三分の一は暗くなり、昼の三分の一は明るくなくなり、夜も同じようになった。"},
{13, "13 また、わたしが見ていると、一羽のわしが中空を飛び、大きな声でこう言うのを聞いた、「ああ、わざわいだ、わざわいだ、地に住む人々は、わざわいだ。なお三人の御使がラッパを吹き鳴らそうとしている」。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view9() {
struct jap9 poems[] = {
{1, "1 第五の御使が、ラッパを吹き鳴らした。するとわたしは、一つの星が天から地に落ちて来るのを見た。この星に、底知れぬ所の穴を開くかぎが与えられた。"},
{2, "2 そして、この底知れぬ所の穴が開かれた。すると、その穴から煙が大きな炉の煙のように立ちのぼり、その穴の煙で、太陽も空気も暗くなった。"},
{3, "3 その煙の中から、いなごが地上に出てきたが、地のさそりが持っているような力が、彼らに与えられた。"},
{4, "4 彼らは、地の草やすべての青草、またすべての木をそこなってはならないが、額に神の印がない人たちには害を加えてもよいと、言い渡された。"},
{5, "5 彼らは、人間を殺すことはしないで、五か月のあいだ苦しめることだけが許された。彼らの与える苦痛は、人がさそりにさされる時のような苦痛であった。"},
{6, "6 その時には、人々は死を求めても与えられず、死にたいと願っても、死は逃げて行くのである。"},
{7, "7 これらのいなごは、出陣の用意のととのえられた馬によく似ており、その頭には金の冠のようなものをつけ、その顔は人間の顔のようであり、"},
{8, "8 また、そのかみの毛は女のかみのようであり、その歯はししの歯のようであった。"},
{9, "9 また、鉄の胸当のような胸当をつけており、その羽の音は、馬に引かれて戦場に急ぐ多くの戦車の響きのようであった。"},
{10, "10 その上、さそりのような尾と針とを持っている。その尾には、五か月のあいだ人間をそこなう力がある。"},
{11, "11 彼らは、底知れぬ所の使を王にいただいており、その名をヘブル語でアバドンと言い、ギリシヤ語ではアポルオンと言う。"},
{12, "12 第一のわざわいは、過ぎ去った。見よ、この後、なお二つのわざわいが来る。"},
{13, "13 第六の御使が、ラッパを吹き鳴らした。すると、一つの声が、神のみまえにある金の祭壇の四つの角から出て、"},
{14, "14 ラッパを持っている第六の御使にこう呼びかけるのを、わたしは聞いた。「大ユウフラテ川のほとりにつながれている四人の御使を、解いてやれ」。"},
{15, "15 すると、その時、その日、その月、その年に備えておかれた四人の御使が、人間の三分の一を殺すために、解き放たれた。"},
{16, "16 騎兵隊の数は二億であった。わたしはその数を聞いた。"},
{17, "17 そして、まぼろしの中で、それらの馬とそれに乗っている者たちとを見ると、乗っている者たちは、火の色と青玉色と硫黄の色の胸当をつけていた。そして、それらの馬の頭はししの頭のようであって、その口から火と煙と硫黄とが、出ていた。"},
{18, "18 この三つの災害、すなわち、彼らの口から出て来る火と煙と硫黄とによって、人間の三分の一は殺されてしまった。"},
{19, "19 馬の力はその口と尾とにある。その尾はへびに似ていて、それに頭があり、その頭で人に害を加えるのである。"},
{20, "20 これらの災害で殺されずに残った人々は、自分の手で造ったものについて、悔い改めようとせず、また悪霊のたぐいや、金、銀、銅、石、木で造られ、見ることも聞くことも歩くこともできない偶像を礼拝して、やめようともしなかった。"},
{21, "21 また、彼らは、その犯した殺人や、まじないや、不品行や、盗みを悔い改めようとしなかった。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view10() {
struct jap10 poems[] = {
{1, "1 わたしは、もうひとりの強い御使が、雲に包まれて、天から降りて来るのを見た。その頭に、にじをいただき、その顔は太陽のようで、その足は火の柱のようであった。"},
{2, "2 彼は、開かれた小さな巻物を手に持っていた。そして、右足を海の上に、左足を地の上に踏みおろして、"},
{3, "3 ししがほえるように大声で叫んだ。彼が叫ぶと、七つの雷がおのおのその声を発した。"},
{4, "4 七つの雷が声を発した時、わたしはそれを書きとめようとした。すると、天から声があって、「七つの雷の語ったことを封印せよ。それを書きとめるな」と言うのを聞いた。"},
{5, "5 それから、海と地の上に立っているのをわたしが見たあの御使は、天にむけて右手を上げ、"},
{6, "6 天とその中にあるもの、地とその中にあるもの、海とその中にあるものを造り、世々限りなく生きておられるかたをさして誓った、「もう時がない。"},
{7, "7 第七の御使が吹き鳴らすラッパの音がする時には、神がその僕、預言者たちにお告げになったとおり、神の奥義は成就される」。"},
{8, "8 すると、前に天から聞えてきた声が、またわたしに語って言った、「さあ行って、海と地との上に立っている御使の手に開かれている巻物を、受け取りなさい」。"},
{9, "9 そこで、わたしはその御使のもとに行って、「その小さな巻物を下さい」と言った。すると、彼は言った、「取って、それを食べてしまいなさい。あなたの腹には苦いが、口には蜜のように甘い」。"},
{10, "10 わたしは御使の手からその小さな巻物を受け取って食べてしまった。すると、わたしの口には蜜のように甘かったが、それを食べたら、腹が苦くなった。"},
{11, "11 その時、「あなたは、もう一度、多くの民族、国民、国語、王たちについて、預言せねばならない」と言う声がした。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view11() {
struct jap11 poems[] = {
{1, "1 それから、わたしはつえのような測りざおを与えられて、こう命じられた、「さあ立って、神の聖所と祭壇と、そこで礼拝している人々とを、測りなさい。"},
{2, "2 聖所の外の庭はそのままにしておきなさい。それを測ってはならない。そこは異邦人に与えられた所だから。彼らは、四十二か月の間この聖なる都を踏みにじるであろう。"},
{3, "3 そしてわたしは、わたしのふたりの証人に、荒布を着て、千二百六十日のあいだ預言することを許そう」。"},
{4, "4 彼らは、全地の主のみまえに立っている二本のオリブの木、また、二つの燭台である。"},
{5, "5 もし彼らに害を加えようとする者があれば、彼らの口から火が出て、その敵を滅ぼすであろう。もし彼らに害を加えようとする者があれば、その者はこのように殺されねばならない。"},
{6, "6 預言をしている期間、彼らは、天を閉じて雨を降らせないようにする力を持っている。さらにまた、水を血に変え、何度でも思うままに、あらゆる災害で地を打つ力を持っている。"},
{7, "7 そして、彼らがそのあかしを終えると、底知れぬ所からのぼって来る獣が、彼らと戦って打ち勝ち、彼らを殺す。"},
{8, "8 彼らの死体はソドムや、エジプトにたとえられている大いなる都の大通りにさらされる。彼らの主も、この都で十字架につけられたのである。"},
{9, "9 いろいろな民族、部族、国語、国民に属する人々が、三日半の間、彼らの死体をながめるが、その死体を墓に納めることは許さない。"},
{10, "10 地に住む人々は、彼らのことで喜び楽しみ、互に贈り物をしあう。このふたりの預言者は、地に住む者たちを悩ましたからである。"},
{11, "11 三日半の後、いのちの息が、神から出て彼らの中にはいり、そして、彼らが立ち上がったので、それを見た人々は非常な恐怖に襲われた。"},
{12, "12 その時、天から大きな声がして、「ここに上ってきなさい」と言うのを、彼らは聞いた。そして、彼らは雲に乗って天に上った。彼らの敵はそれを見た。"},
{13, "13 この時、大地震が起って、都の十分の一は倒れ、その地震で七千人が死に、生き残った人々は驚き恐れて、天の神に栄光を帰した。"},
{14, "14 第二のわざわいは、過ぎ去った。見よ、第三のわざわいがすぐに来る。"},
{15, "15 第七の御使が、ラッパを吹き鳴らした。すると、大きな声々が天に起って言った、「この世の国は、われらの主とそのキリストとの国となった。主は世々限りなく支配なさるであろう」。"},
{16, "16 そして、神のみまえで座についている二十四人の長老は、ひれ伏し、神を拝して言った、"},
{17, "17 「今いまし、昔いませる、全能者にして主なる神よ。大いなる御力をふるって支配なさったことを、感謝します。"},
{18, "18 諸国民は怒り狂いましたが、あなたも怒りをあらわされました。そして、死人をさばき、あなたの僕なる預言者、聖徒、小さき者も、大いなる者も、すべて御名をおそれる者たちに報いを与え、また、地を滅ぼす者どもを滅ぼして下さる時がきました」。"},
{19, "19 そして、天にある神の聖所が開けて、聖所の中に契約の箱が見えた。また、いなずまと、もろもろの声と、雷鳴と、地震とが起り、大粒の雹が降った。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view12() {
struct jap12 poems[] = {
{1, "1 また、大いなるしるしが天に現れた。ひとりの女が太陽を着て、足の下に月を踏み、その頭に十二の星の冠をかぶっていた。"},
{2, "2 この女は子を宿しており、産みの苦しみと悩みとのために、泣き叫んでいた。"},
{3, "3 また、もう一つのしるしが天に現れた。見よ、大きな、赤い龍がいた。それに七つの頭と十の角とがあり、その頭に七つの冠をかぶっていた。"},
{4, "4 その尾は天の星の三分の一を掃き寄せ、それらを地に投げ落した。龍は子を産もうとしている女の前に立ち、生れたなら、その子を食い尽そうとかまえていた。"},
{5, "5 女は男の子を産んだが、彼は鉄のつえをもってすべての国民を治めるべき者である。この子は、神のみもとに、その御座のところに、引き上げられた。"},
{6, "6 女は荒野へ逃げて行った。そこには、彼女が千二百六十日のあいだ養われるように、神の用意された場所があった。"},
{7, "7 さて、天では戦いが起った。ミカエルとその御使たちとが、龍と戦ったのである。龍もその使たちも応戦したが、"},
{8, "8 勝てなかった。そして、もはや天には彼らのおる所がなくなった。"},
{9, "9 この巨大な龍、すなわち、悪魔とか、サタンとか呼ばれ、全世界を惑わす年を経たへびは、地に投げ落され、その使たちも、もろともに投げ落された。"},
{10, "10 その時わたしは、大きな声が天でこう言うのを聞いた、「今や、われらの神の救と力と国と、神のキリストの権威とは、現れた。われらの兄弟らを訴える者、夜昼われらの神のみまえで彼らを訴える者は、投げ落された。"},
{11, "11 兄弟たちは、小羊の血と彼らのあかしの言葉とによって、彼にうち勝ち、死に至るまでもそのいのちを惜しまなかった。"},
{12, "12 それゆえに、天とその中に住む者たちよ、大いに喜べ。しかし、地と海よ、おまえたちはわざわいである。悪魔が、自分の時が短いのを知り、激しい怒りをもって、おまえたちのところに下ってきたからである」。"},
{13, "13 龍は、自分が地上に投げ落されたと知ると、男子を産んだ女を追いかけた。"},
{14, "14 しかし、女は自分の場所である荒野に飛んで行くために、大きなわしの二つの翼を与えられた。そしてそこでへびからのがれて、一年、二年、また、半年の間、養われることになっていた。"},
{15, "15 へびは女の後に水を川のように、口から吐き出して、女をおし流そうとした。"},
{16, "16 しかし、地は女を助けた。すなわち、地はその口を開いて、龍が口から吐き出した川を飲みほした。"},
{17, "17 龍は、女に対して怒りを発し、女の残りの子ら、すなわち、神の戒めを守り、イエスのあかしを持っている者たちに対して、戦いをいどむために、出て行った。 [12:18] そして、海の砂の上に立った。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view13() {
struct jap13 poems[] = {
{1, "1 わたしはまた、一匹の獣が海から上って来るのを見た。それには角が十本、頭が七つあり、それらの角には十の冠があって、頭には神を汚す名がついていた。"},
{2, "2 わたしの見たこの獣はひょうに似ており、その足はくまの足のようで、その口はししの口のようであった。龍は自分の力と位と大いなる権威とを、この獣に与えた。"},
{3, "3 その頭の一つが、死ぬほどの傷を受けたが、その致命的な傷もなおってしまった。そこで、全地の人々は驚きおそれて、その獣に従い、"},
{4, "4 また、龍がその権威を獣に与えたので、人々は龍を拝み、さらに、その獣を拝んで言った、「だれが、この獣に匹敵し得ようか。だれが、これと戦うことができようか」。"},
{5, "5 この獣には、また、大言を吐き汚しごとを語る口が与えられ、四十二か月のあいだ活動する権威が与えられた。"},
{6, "6 そこで、彼は口を開いて神を汚し、神の御名と、その幕屋、すなわち、天に住む者たちとを汚した。"},
{7, "7 そして彼は、聖徒に戦いをいどんでこれに勝つことを許され、さらに、すべての部族、民族、国語、国民を支配する権威を与えられた。"},
{8, "8 地に住む者で、ほふられた小羊のいのちの書に、その名を世の初めからしるされていない者はみな、この獣を拝むであろう。"},
{9, "9 耳のある者は、聞くがよい。"},
{10, "10 とりこになるべき者は、とりこになっていく。つるぎで殺す者は、自らもつるぎで殺されねばならない。ここに、聖徒たちの忍耐と信仰とがある。"},
{11, "11 わたしはまた、ほかの獣が地から上って来るのを見た。それには小羊のような角が二つあって、龍のように物を言った。"},
{12, "12 そして、先の獣の持つすべての権力をその前で働かせた。また、地と地に住む人々に、致命的な傷がいやされた先の獣を拝ませた。"},
{13, "13 また、大いなるしるしを行って、人々の前で火を天から地に降らせることさえした。"},
{14, "14 さらに、先の獣の前で行うのを許されたしるしで、地に住む人々を惑わし、かつ、つるぎの傷を受けてもなお生きている先の獣の像を造ることを、地に住む人々に命じた。"},
{15, "15 それから、その獣の像に息を吹き込んで、その獣の像が物を言うことさえできるようにし、また、その獣の像を拝まない者をみな殺させた。"},
{16, "16 また、小さき者にも、大いなる者にも、富める者にも、貧しき者にも、自由人にも、奴隷にも、すべての人々に、その右の手あるいは額に刻印を押させ、"},
{17, "17 この刻印のない者はみな、物を買うことも売ることもできないようにした。この刻印は、その獣の名、または、その名の数字のことである。"},
{18, "18 ここに、知恵が必要である。思慮のある者は、獣の数字を解くがよい。その数字とは、人間をさすものである。そして、その数字は六百六十六である。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view14() {
struct jap14 poems[] = {
{1, "1 なお、わたしが見ていると、見よ、小羊がシオンの山に立っていた。また、十四万四千の人々が小羊と共におり、その額に小羊の名とその父の名とが書かれていた。"},
{2, "2 またわたしは、大水のとどろきのような、激しい雷鳴のような声が、天から出るのを聞いた。わたしの聞いたその声は、琴をひく人が立琴をひく音のようでもあった。"},
{3, "3 彼らは、御座の前、四つの生き物と長老たちとの前で、新しい歌を歌った。この歌は、地からあがなわれた十四万四千人のほかは、だれも学ぶことができなかった。"},
{4, "4 彼らは、女にふれたことのない者である。彼らは、純潔な者である。そして、小羊の行く所へは、どこへでもついて行く。彼らは、神と小羊とにささげられる初穂として、人間の中からあがなわれた者である。"},
{5, "5 彼らの口には偽りがなく、彼らは傷のない者であった。"},
{6, "6 わたしは、もうひとりの御使が中空を飛ぶのを見た。彼は地に住む者、すなわち、あらゆる国民、部族、国語、民族に宣べ伝えるために、永遠の福音をたずさえてきて、"},
{7, "7 大声で言った、「神をおそれ、神に栄光を帰せよ。神のさばきの時がきたからである。天と地と海と水の源とを造られたかたを、伏し拝め」。"},
{8, "8 また、ほかの第二の御使が、続いてきて言った、「倒れた、大いなるバビロンは倒れた。その不品行に対する激しい怒りのぶどう酒を、あらゆる国民に飲ませた者」。"},
{9, "9 ほかの第三の御使が彼らに続いてきて、大声で言った、「おおよそ、獣とその像とを拝み、額や手に刻印を受ける者は、"},
{10, "10 神の怒りの杯に混ぜものなしに盛られた、神の激しい怒りのぶどう酒を飲み、聖なる御使たちと小羊との前で、火と硫黄とで苦しめられる。"},
{11, "11 その苦しみの煙は世々限りなく立ちのぼり、そして、獣とその像とを拝む者、また、だれでもその名の刻印を受けている者は、昼も夜も休みが得られない。"},
{12, "12 ここに、神の戒めを守り、イエスを信じる信仰を持ちつづける聖徒の忍耐がある」。"},
{13, "13 またわたしは、天からの声がこう言うのを聞いた、「書きしるせ、『今から後、主にあって死ぬ死人はさいわいである』」。御霊も言う、「しかり、彼らはその労苦を解かれて休み、そのわざは彼らについていく」。"},
{14, "14 また見ていると、見よ、白い雲があって、その雲の上に人の子のような者が座しており、頭には金の冠をいただき、手には鋭いかまを持っていた。"},
{15, "15 すると、もうひとりの御使が聖所から出てきて、雲の上に座している者にむかって大声で叫んだ、「かまを入れて刈り取りなさい。地の穀物は全く実り、刈り取るべき時がきた」。"},
{16, "16 雲の上に座している者は、そのかまを地に投げ入れた。すると、地のものが刈り取られた。"},
{17, "17 また、もうひとりの御使が、天の聖所から出てきたが、彼もまた鋭いかまを持っていた。"},
{18, "18 さらに、もうひとりの御使で、火を支配する権威を持っている者が、祭壇から出てきて、鋭いかまを持つ御使にむかい、大声で言った、「その鋭いかまを地に入れて、地のぶどうのふさを刈り集めなさい。ぶどうの実がすでに熟しているから」。"},
{19, "19 そこで、御使はそのかまを地に投げ入れて、地のぶどうを刈り集め、神の激しい怒りの大きな酒ぶねに投げ込んだ。"},
{20, "20 そして、その酒ぶねが都の外で踏まれた。すると、血が酒ぶねから流れ出て、馬のくつわにとどくほどになり、一千六百丁にわたってひろがった。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view15() {
struct jap15 poems[] = {
{1, "1 またわたしは、天に大いなる驚くべきほかのしるしを見た。七人の御使が、最後の七つの災害を携えていた。これらの災害で神の激しい怒りがその頂点に達するのである。"},
{2, "2 またわたしは、火のまじったガラスの海のようなものを見た。そして、このガラスの海のそばに、獣とその像とその名の数字とにうち勝った人々が、神の立琴を手にして立っているのを見た。"},
{3, "3 彼らは、神の僕モーセの歌と小羊の歌とを歌って言った、「全能者にして主なる神よ。あなたのみわざは、大いなる、また驚くべきものであります。万民の王よ、あなたの道は正しく、かつ真実であります。"},
{4, "4 主よ、あなたをおそれず、御名をほめたたえない者が、ありましょうか。あなただけが聖なるかたであり、あらゆる国民はきて、あなたを伏し拝むでしょう。あなたの正しいさばきが、あらわれるに至ったからであります」。"},
{5, "5 その後、わたしが見ていると、天にある、あかしの幕屋の聖所が開かれ、"},
{6, "6 その聖所から、七つの災害を携えている七人の御使が、汚れのない、光り輝く亜麻布を身にまとい、金の帯を胸にしめて、出てきた。"},
{7, "7 そして、四つの生き物の一つが、世々限りなく生きておられる神の激しい怒りの満ちた七つの金の鉢を、七人の御使に渡した。"},
{8, "8 すると、聖所は神の栄光とその力とから立ちのぼる煙で満たされ、七人の御使の七つの災害が終ってしまうまでは、だれも聖所にはいることができなかった。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view16() {
struct jap16 poems[] = {
{1, "1 それから、大きな声が聖所から出て、七人の御使にむかい、「さあ行って、神の激しい怒りの七つの鉢を、地に傾けよ」と言うのを聞いた。"},
{2, "2 そして、第一の者が出て行って、その鉢を地に傾けた。すると、獣の刻印を持つ人々と、その像を拝む人々とのからだに、ひどい悪性のでき物ができた。"},
{3, "3 第二の者が、その鉢を海に傾けた。すると、海は死人の血のようになって、その中の生き物がみな死んでしまった。"},
{4, "4 第三の者がその鉢を川と水の源とに傾けた。すると、みな血になった。"},
{5, "5 それから、水をつかさどる御使がこう言うのを、聞いた、「今いまし、昔いませる聖なる者よ。このようにお定めになったあなたは、正しいかたであります。"},
{6, "6 聖徒と預言者との血を流した者たちに、血をお飲ませになりましたが、それは当然のことであります」。"},
{7, "7 わたしはまた祭壇がこう言うのを聞いた、「全能者にして主なる神よ。しかり、あなたのさばきは真実で、かつ正しいさばきであります」。"},
{8, "8 第四の者が、その鉢を太陽に傾けた。すると、太陽は火で人々を焼くことを許された。"},
{9, "9 人々は、激しい炎熱で焼かれたが、これらの災害を支配する神の御名を汚し、悔い改めて神に栄光を帰することをしなかった。"},
{10, "10 第五の者が、その鉢を獣の座に傾けた。すると、獣の国は暗くなり、人々は苦痛のあまり舌をかみ、"},
{11, "11 その苦痛とでき物とのゆえに、天の神をのろった。そして、自分の行いを悔い改めなかった。"},
{12, "12 第六の者が、その鉢を大ユウフラテ川に傾けた。すると、その水は、日の出る方から来る王たちに対し道を備えるために、かれてしまった。"},
{13, "13 また見ると、龍の口から、獣の口から、にせ預言者の口から、かえるのような三つの汚れた霊が出てきた。"},
{14, "14 これらは、しるしを行う悪霊の霊であって、全世界の王たちのところに行き、彼らを召集したが、それは、全能なる神の大いなる日に、戦いをするためであった。"},
{15, "15 (見よ、わたしは盗人のように来る。裸のままで歩かないように、また、裸の恥を見られないように、目をさまし着物を身に着けている者は、さいわいである。)"},
{16, "16 三つの霊は、ヘブル語でハルマゲドンという所に、王たちを召集した。"},
{17, "17 第七の者が、その鉢を空中に傾けた。すると、大きな声が聖所の中から、御座から出て、「事はすでに成った」と言った。"},
{18, "18 すると、いなずまと、もろもろの声と、雷鳴とが起り、また激しい地震があった。それは人間が地上にあらわれて以来、かつてなかったようなもので、それほどに激しい地震であった。"},
{19, "19 大いなる都は三つに裂かれ、諸国民の町々は倒れた。神は大いなるバビロンを思い起し、これに神の激しい怒りのぶどう酒の杯を与えられた。"},
{20, "20 島々はみな逃げ去り、山々は見えなくなった。"},
{21, "21 また一タラントの重さほどの大きな雹が、天から人々の上に降ってきた。人々は、この雹の災害のゆえに神をのろった。その災害が、非常に大きかったからである。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view17() {
struct jap17 poems[] = {
{1, "1 それから、七つの鉢を持つ七人の御使のひとりがきて、わたしに語って言った、「さあ、きなさい。多くの水の上にすわっている大淫婦に対するさばきを、見せよう。"},
{2, "2 地の王たちはこの女と姦淫を行い、地に住む人々はこの女の姦淫のぶどう酒に酔いしれている」。"},
{3, "3 御使は、わたしを御霊に感じたまま、荒野へ連れて行った。わたしは、そこでひとりの女が赤い獣に乗っているのを見た。その獣は神を汚すかずかずの名でおおわれ、また、それに七つの頭と十の角とがあった。"},
{4, "4 この女は紫と赤の衣をまとい、金と宝石と真珠とで身を飾り、憎むべきものと自分の姦淫の汚れとで満ちている金の杯を手に持ち、"},
{5, "5 その額には、一つの名がしるされていた。それは奥義であって、「大いなるバビロン、淫婦どもと地の憎むべきものらとの母」というのであった。"},
{6, "6 わたしは、この女が聖徒の血とイエスの証人の血に酔いしれているのを見た。この女を見た時、わたしは非常に驚きあやしんだ。"},
{7, "7 すると、御使はわたしに言った、「なぜそんなに驚くのか。この女の奥義と、女を乗せている七つの頭と十の角のある獣の奥義とを、話してあげよう。"},
{8, "8 あなたの見た獣は、昔はいたが、今はおらず、そして、やがて底知れぬ所から上ってきて、ついには滅びに至るものである。地に住む者のうち、世の初めからいのちの書に名をしるされていない者たちは、この獣が、昔はいたが今はおらず、やがて来るのを見て、驚きあやしむであろう。"},
{9, "9 ここに、知恵のある心が必要である。七つの頭は、この女のすわっている七つの山であり、また、七人の王のことである。"},
{10, "10 そのうちの五人はすでに倒れ、ひとりは今おり、もうひとりは、まだきていない。それが来れば、しばらくの間だけおることになっている。"},
{11, "11 昔はいたが今はいないという獣は、すなわち第八のものであるが、またそれは、かの七人の中のひとりであって、ついには滅びに至るものである。"},
{12, "12 あなたの見た十の角は、十人の王のことであって、彼らはまだ国を受けてはいないが、獣と共に、一時だけ王としての権威を受ける。"},
{13, "13 彼らは心をひとつにしている。そして、自分たちの力と権威とを獣に与える。"},
{14, "14 彼らは小羊に戦いをいどんでくるが、小羊は、主の主、王の王であるから、彼らにうち勝つ。また、小羊と共にいる召された、選ばれた、忠実な者たちも、勝利を得る」。"},
{15, "15 御使はまた、わたしに言った、「あなたの見た水、すなわち、淫婦のすわっている所は、あらゆる民族、群衆、国民、国語である。"},
{16, "16 あなたの見た十の角と獣とは、この淫婦を憎み、みじめな者にし、裸にし、彼女の肉を食い、火で焼き尽すであろう。"},
{17, "17 神は、御言が成就する時まで、彼らの心の中に、御旨を行い、思いをひとつにし、彼らの支配権を獣に与える思いを持つようにされたからである。"},
{18, "18 あなたの見たかの女は、地の王たちを支配する大いなる都のことである」。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view18() {
struct jap18 poems[] = {
{1, "1 この後、わたしは、もうひとりの御使が、大いなる権威を持って、天から降りて来るのを見た。地は彼の栄光によって明るくされた。"},
{2, "2 彼は力強い声で叫んで言った、「倒れた、大いなるバビロンは倒れた。そして、それは悪魔の住む所、あらゆる汚れた霊の巣くつ、また、あらゆる汚れた憎むべき鳥の巣くつとなった。"},
{3, "3 すべての国民は、彼女の姦淫に対する激しい怒りのぶどう酒を飲み、地の王たちは彼女と姦淫を行い、地上の商人たちは、彼女の極度のぜいたくによって富を得たからである」。"},
{4, "4 わたしはまた、もうひとつの声が天から出るのを聞いた、「わたしの民よ。彼女から離れ去って、その罪にあずからないようにし、その災害に巻き込まれないようにせよ。"},
{5, "5 彼女の罪は積り積って天に達しており、神はその不義の行いを覚えておられる。"},
{6, "6 彼女がしたとおりに彼女にし返し、そのしわざに応じて二倍に報復をし、彼女が混ぜて入れた杯の中に、その倍の量を、入れてやれ。"},
{7, "7 彼女が自ら高ぶり、ぜいたくをほしいままにしたので、それに対して、同じほどの苦しみと悲しみとを味わわせてやれ。彼女は心の中で『わたしは女王の位についている者であって、やもめではないのだから、悲しみを知らない』と言っている。"},
{8, "8 それゆえ、さまざまの災害が、死と悲しみとききんとが、一日のうちに彼女を襲い、そして、彼女は火で焼かれてしまう。彼女をさばく主なる神は、力強いかたなのである。"},
{9, "9 彼女と姦淫を行い、ぜいたくをほしいままにしていた地の王たちは、彼女が焼かれる火の煙を見て、彼女のために胸を打って泣き悲しみ、"},
{10, "10 彼女の苦しみに恐れをいだき、遠くに立って言うであろう、『ああ、わざわいだ、大いなる都、不落の都、バビロンは、わざわいだ。おまえに対するさばきは、一瞬にしてきた』。"},
{11, "11 また、地の商人たちも彼女のために泣き悲しむ。もはや、彼らの商品を買う者が、ひとりもないからである。"},
{12, "12 その商品は、金、銀、宝石、真珠、麻布、紫布、絹、緋布、各種の香木、各種の象牙細工、高価な木材、銅、鉄、大理石などの器、"},
{13, "13 肉桂、香料、香、におい油、乳香、ぶどう酒、オリブ油、麦粉、麦、牛、羊、馬、車、奴隷、そして人身などである。"},
{14, "14 おまえの心の喜びであったくだものはなくなり、あらゆるはでな、はなやかな物はおまえから消え去った。それらのものはもはや見られない。"},
{15, "15 これらの品々を売って、彼女から富を得た商人は、彼女の苦しみに恐れをいだいて遠くに立ち、泣き悲しんで言う、"},
{16, "16 『ああ、わざわいだ、麻布と紫布と緋布をまとい、金や宝石や真珠で身を飾っていた大いなる都は、わざわいだ。"},
{17, "17 これほどの富が、一瞬にして無に帰してしまうとは』。また、すべての船長、航海者、水夫、すべて海で働いている人たちは、遠くに立ち、"},
{18, "18 彼女が焼かれる火の煙を見て、叫んで言う、『これほどの大いなる都は、どこにあろう』。"},
{19, "19 彼らは頭にちりをかぶり、泣き悲しんで叫ぶ、『ああ、わざわいだ、この大いなる都は、わざわいだ。そのおごりによって、海に舟を持つすべての人が富を得ていたのに、この都も一瞬にして無に帰してしまった』。"},
{20, "20 天よ、聖徒たちよ、使徒たちよ、預言者たちよ。この都について大いに喜べ。神は、あなたがたのために、この都をさばかれたのである」。"},
{21, "21 すると、ひとりの力強い御使が、大きなひきうすのような石を持ちあげ、それを海に投げ込んで言った、「大いなる都バビロンは、このように激しく打ち倒され、そして、全く姿を消してしまう。"},
{22, "22 また、おまえの中では、立琴をひく者、歌を歌う者、笛を吹く者、ラッパを吹き鳴らす者の楽の音は全く聞かれず、あらゆる仕事の職人たちも全く姿を消し、また、ひきうすの音も、全く聞かれない。"},
{23, "23 また、おまえの中では、あかりもともされず、花婿、花嫁の声も聞かれない。というのは、おまえの商人たちは地上で勢力を張る者となり、すべての国民はおまえのまじないでだまされ、"},
{24, "24 また、預言者や聖徒の血、さらに、地上で殺されたすべての者の血が、この都で流されたからである」。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view19() {
struct jap19 poems[] = {
{1, "1 この後、わたしは天の大群衆が大声で唱えるような声を聞いた、「ハレルヤ、救と栄光と力とは、われらの神のものであり、"},
{2, "2 そのさばきは、真実で正しい。神は、姦淫で地を汚した大淫婦をさばき、神の僕たちの血の報復を彼女になさったからである」。"},
{3, "3 再び声があって、「ハレルヤ、彼女が焼かれる火の煙は、世々限りなく立ちのぼる」と言った。"},
{4, "4 すると、二十四人の長老と四つの生き物とがひれ伏し、御座にいます神を拝して言った、「アァメン、ハレルヤ」。"},
{5, "5 その時、御座から声が出て言った、「すべての神の僕たちよ、神をおそれる者たちよ。小さき者も大いなる者も、共に、われらの神をさんびせよ」。"},
{6, "6 わたしはまた、大群衆の声、多くの水の音、また激しい雷鳴のようなものを聞いた。それはこう言った、「ハレルヤ、全能者にして主なるわれらの神は、王なる支配者であられる。"},
{7, "7 わたしたちは喜び楽しみ、神をあがめまつろう。小羊の婚姻の時がきて、花嫁はその用意をしたからである。"},
{8, "8 彼女は、光り輝く、汚れのない麻布の衣を着ることを許された。この麻布の衣は、聖徒たちの正しい行いである」。"},
{9, "9 それから、御使はわたしに言った、「書きしるせ。小羊の婚宴に招かれた者は、さいわいである」。またわたしに言った、「これらは、神の真実の言葉である」。"},
{10, "10 そこで、わたしは彼の足もとにひれ伏して、彼を拝そうとした。すると、彼は言った、「そのようなことをしてはいけない。わたしは、あなたと同じ僕仲間であり、またイエスのあかしびとであるあなたの兄弟たちと同じ僕仲間である。ただ神だけを拝しなさい。イエスのあかしは、すなわち預言の霊である」。"},
{11, "11 またわたしが見ていると、天が開かれ、見よ、そこに白い馬がいた。それに乗っているかたは、「忠実で真実な者」と呼ばれ、義によってさばき、また、戦うかたである。"},
{12, "12 その目は燃える炎であり、その頭には多くの冠があった。また、彼以外にはだれも知らない名がその身にしるされていた。"},
{13, "13 彼は血染めの衣をまとい、その名は「神の言」と呼ばれた。"},
{14, "14 そして、天の軍勢が、純白で、汚れのない麻布の衣を着て、白い馬に乗り、彼に従った。"},
{15, "15 その口からは、諸国民を打つために、鋭いつるぎが出ていた。彼は、鉄のつえをもって諸国民を治め、また、全能者なる神の激しい怒りの酒ぶねを踏む。"},
{16, "16 その着物にも、そのももにも、「王の王、主の主」という名がしるされていた。"},
{17, "17 また見ていると、ひとりの御使が太陽の中に立っていた。彼は、中空を飛んでいるすべての鳥にむかって、大声で叫んだ、「さあ、神の大宴会に集まってこい。"},
{18, "18 そして、王たちの肉、将軍の肉、勇者の肉、馬の肉、馬に乗っている者の肉、また、すべての自由人と奴隷との肉、小さき者と大いなる者との肉をくらえ」。"},
{19, "19 なお見ていると、獣と地の王たちと彼らの軍勢とが集まり、馬に乗っているかたとその軍勢とに対して、戦いをいどんだ。"},
{20, "20 しかし、獣は捕えられ、また、この獣の前でしるしを行って、獣の刻印を受けた者とその像を拝む者とを惑わしたにせ預言者も、獣と共に捕えられた。そして、この両者とも、生きながら、硫黄の燃えている火の池に投げ込まれた。"},
{21, "21 それ以外の者たちは、馬に乗っておられるかたの口から出るつるぎで切り殺され、その肉を、すべての鳥が飽きるまで食べた。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view20() {
struct jap20 poems[] = {
{1, "1 またわたしが見ていると、ひとりの御使が、底知れぬ所のかぎと大きな鎖とを手に持って、天から降りてきた。"},
{2, "2 彼は、悪魔でありサタンである龍、すなわち、かの年を経たへびを捕えて千年の間つなぎおき、"},
{3, "3 そして、底知れぬ所に投げ込み、入口を閉じてその上に封印し、千年の期間が終るまで、諸国民を惑わすことがないようにしておいた。その後、しばらくの間だけ解放されることになっていた。"},
{4, "4 また見ていると、かず多くの座があり、その上に人々がすわっていた。そして、彼らにさばきの権が与えられていた。また、イエスのあかしをし神の言を伝えたために首を切られた人々の霊がそこにおり、また、獣をもその像をも拝まず、その刻印を額や手に受けることをしなかった人々がいた。彼らは生きかえって、キリストと共に千年の間、支配した。"},
{5, "5 (それ以外の死人は、千年の期間が終るまで生きかえらなかった。)これが第一の復活である。"},
{6, "6 この第一の復活にあずかる者は、さいわいな者であり、また聖なる者である。この人たちに対しては、第二の死はなんの力もない。彼らは神とキリストとの祭司となり、キリストと共に千年の間、支配する。"},
{7, "7 千年の期間が終ると、サタンはその獄から解放される。"},
{8, "8 そして、出て行き、地の四方にいる諸国民、すなわちゴグ、マゴグを惑わし、彼らを戦いのために召集する。その数は、海の砂のように多い。"},
{9, "9 彼らは地上の広い所に上ってきて、聖徒たちの陣営と愛されていた都とを包囲した。すると、天から火が下ってきて、彼らを焼き尽した。"},
{10, "10 そして、彼らを惑わした悪魔は、火と硫黄との池に投げ込まれた。そこには、獣もにせ預言者もいて、彼らは世々限りなく日夜、苦しめられるのである。"},
{11, "11 また見ていると、大きな白い御座があり、そこにいますかたがあった。天も地も御顔の前から逃げ去って、あとかたもなくなった。"},
{12, "12 また、死んでいた者が、大いなる者も小さき者も共に、御座の前に立っているのが見えた。かずかずの書物が開かれたが、もう一つの書物が開かれた。これはいのちの書であった。死人はそのしわざに応じ、この書物に書かれていることにしたがって、さばかれた。"},
{13, "13 海はその中にいる死人を出し、死も黄泉もその中にいる死人を出し、そして、おのおのそのしわざに応じて、さばきを受けた。"},
{14, "14 それから、死も黄泉も火の池に投げ込まれた。この火の池が第二の死である。"},
{15, "15 このいのちの書に名がしるされていない者はみな、火の池に投げ込まれた。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view21() {
struct jap21 poems[] = {
{1, "1 わたしはまた、新しい天と新しい地とを見た。先の天と地とは消え去り、海もなくなってしまった。"},
{2, "2 また、聖なる都、新しいエルサレムが、夫のために着飾った花嫁のように用意をととのえて、神のもとを出て、天から下って来るのを見た。"},
{3, "3 また、御座から大きな声が叫ぶのを聞いた、「見よ、神の幕屋が人と共にあり、神が人と共に住み、人は神の民となり、神自ら人と共にいまして、"},
{4, "4 人の目から涙を全くぬぐいとって下さる。もはや、死もなく、悲しみも、叫びも、痛みもない。先のものが、すでに過ぎ去ったからである」。"},
{5, "5 すると、御座にいますかたが言われた、「見よ、わたしはすべてのものを新たにする」。また言われた、「書きしるせ。これらの言葉は、信ずべきであり、まことである」。"},
{6, "6 そして、わたしに仰せられた、「事はすでに成った。わたしは、アルパでありオメガである。初めであり終りである。かわいている者には、いのちの水の泉から価なしに飲ませよう。"},
{7, "7 勝利を得る者は、これらのものを受け継ぐであろう。わたしは彼の神となり、彼はわたしの子となる。"},
{8, "8 しかし、おくびょうな者、信じない者、忌むべき者、人殺し、姦淫を行う者、まじないをする者、偶像を拝む者、すべて偽りを言う者には、火と硫黄の燃えている池が、彼らの受くべき報いである。これが第二の死である」。"},
{9, "9 最後の七つの災害が満ちている七つの鉢を持っていた七人の御使のひとりがきて、わたしに語って言った、「さあ、きなさい。小羊の妻なる花嫁を見せよう」。"},
{10, "10 この御使は、わたしを御霊に感じたまま、大きな高い山に連れて行き、聖都エルサレムが、神の栄光のうちに、神のみもとを出て天から下って来るのを見せてくれた。"},
{11, "11 その都の輝きは、高価な宝石のようであり、透明な碧玉のようであった。"},
{12, "12 それには大きな、高い城壁があって、十二の門があり、それらの門には、十二の御使がおり、イスラエルの子らの十二部族の名が、それに書いてあった。"},
{13, "13 東に三つの門、北に三つの門、南に三つの門、西に三つの門があった。"},
{14, "14 また都の城壁には十二の土台があり、それには小羊の十二使徒の十二の名が書いてあった。"},
{15, "15 わたしに語っていた者は、都とその門と城壁とを測るために、金の測りざおを持っていた。"},
{16, "16 都は方形であって、その長さと幅とは同じである。彼がその測りざおで都を測ると、一万二千丁であった。長さと幅と高さとは、いずれも同じである。"},
{17, "17 また城壁を測ると、百四十四キュビトであった。これは人間の、すなわち、御使の尺度によるのである。"},
{18, "18 城壁は碧玉で築かれ、都はすきとおったガラスのような純金で造られていた。"},
{19, "19 都の城壁の土台は、さまざまな宝石で飾られていた。第一の土台は碧玉、第二はサファイヤ、第三はめのう、第四は緑玉、"},
{20, "20 第五は縞めのう、第六は赤めのう、第七はかんらん石、第八は緑柱石、第九は黄玉石、第十はひすい、第十一は青玉、第十二は紫水晶であった。"},
{21, "21 十二の門は十二の真珠であり、門はそれぞれ一つの真珠で造られ、都の大通りは、すきとおったガラスのような純金であった。"},
{22, "22 わたしは、この都の中には聖所を見なかった。全能者にして主なる神と小羊とが、その聖所なのである。"},
{23, "23 都は、日や月がそれを照す必要がない。神の栄光が都を明るくし、小羊が都のあかりだからである。"},
{24, "24 諸国民は都の光の中を歩き、地の王たちは、自分たちの光栄をそこに携えて来る。"},
{25, "25 都の門は、終日、閉ざされることはない。そこには夜がないからである。"},
{26, "26 人々は、諸国民の光栄とほまれとをそこに携えて来る。"},
{27, "27 しかし、汚れた者や、忌むべきこと及び偽りを行う者は、その中に決してはいれない。はいれる者は、小羊のいのちの書に名をしるされている者だけである。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view22() {
struct jap22 poems[] = {
{1, "1 御使はまた、水晶のように輝いているいのちの水の川をわたしに見せてくれた。この川は、神と小羊との御座から出て、"},
{2, "2 都の大通りの中央を流れている。川の両側にはいのちの木があって、十二種の実を結び、その実は毎月みのり、その木の葉は諸国民をいやす。"},
{3, "3 のろわるべきものは、もはや何ひとつない。神と小羊との御座は都の中にあり、その僕たちは彼を礼拝し、"},
{4, "4 御顔を仰ぎ見るのである。彼らの額には、御名がしるされている。"},
{5, "5 夜は、もはやない。あかりも太陽の光も、いらない。主なる神が彼らを照し、そして、彼らは世々限りなく支配する。"},
{6, "6 彼はまた、わたしに言った、「これらの言葉は信ずべきであり、まことである。預言者たちのたましいの神なる主は、すぐにも起るべきことをその僕たちに示そうとして、御使をつかわされたのである。"},
{7, "7 見よ、わたしは、すぐに来る。この書の預言の言葉を守る者は、さいわいである」。"},
{8, "8 これらのことを見聞きした者は、このヨハネである。わたしが見聞きした時、それらのことを示してくれた御使の足もとにひれ伏して拝そうとすると、"},
{9, "9 彼は言った、「そのようなことをしてはいけない。わたしは、あなたや、あなたの兄弟である預言者たちや、この書の言葉を守る者たちと、同じ僕仲間である。ただ神だけを拝しなさい」。"},
{10, "10 またわたしに言った、「この書の預言の言葉を封じてはならない。時が近づいているからである。"},
{11, "11 不義な者はさらに不義を行い、汚れた者はさらに汚れたことを行い、義なる者はさらに義を行い、聖なる者はさらに聖なることを行うままにさせよ」。"},
{12, "12 「見よ、わたしはすぐに来る。報いを携えてきて、それぞれのしわざに応じて報いよう。"},
{13, "13 わたしはアルパであり、オメガである。最初の者であり、最後の者である。初めであり、終りである。"},
{14, "14 いのちの木にあずかる特権を与えられ、また門をとおって都にはいるために、自分の着物を洗う者たちは、さいわいである。"},
{15, "15 犬ども、まじないをする者、姦淫を行う者、人殺し、偶像を拝む者、また、偽りを好みかつこれを行う者はみな、外に出されている。"},
{16, "16 わたしイエスは、使をつかわして、諸教会のために、これらのことをあなたがたにあかしした。わたしは、ダビデの若枝また子孫であり、輝く明けの明星である」。"},
{17, "17 御霊も花嫁も共に言った、「きたりませ」。また、聞く者も「きたりませ」と言いなさい。かわいている者はここに来るがよい。いのちの水がほしい者は、価なしにそれを受けるがよい。"},
{18, "18 この書の預言の言葉を聞くすべての人々に対して、わたしは警告する。もしこれに書き加える者があれば、神はその人に、この書に書かれている災害を加えられる。"},
{19, "19 また、もしこの預言の書の言葉をとり除く者があれば、神はその人の受くべき分を、この書に書かれているいのちの木と聖なる都から、とり除かれる。"},
{20, "20 これらのことをあかしするかたが仰せになる、「しかり、わたしはすぐに来る」。アァメン、主イエスよ、きたりませ。"},
{21, "21 主イエスの恵みが、一同の者と共にあるように。"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
}; |
be982e38771612cf8a3351e5016cdd6e84489173 | cb55bd813c6f0203a226ed17091b295e830f531f | /lab2(actu week3) Q3(string).cpp | 1cb25e696ee88f6bea8ba4ab082bfced178c8d15 | [] | no_license | ALI-ZIA-KHAN/C-plus-plus | 83ceb71d59f405e579fcd1f5b84039ed2a170bba | cecc68145a6763464759d262c70dbd82a423a83e | refs/heads/master | 2022-12-05T14:56:03.852999 | 2020-08-28T21:51:50 | 2020-08-28T21:51:50 | 274,138,821 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 777 | cpp | lab2(actu week3) Q3(string).cpp | #include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
struct Student{
string firstname;
string lastname;
float score;
};
int main(){
Student s1;
cout<<"Enter your firstname"<<endl;
cin>>s1.firstname;
cout<<"Enter your lastname"<<endl;
cin>>s1.lastname;
cout<<"Enter your score"<<endl;
cin>>s1.score;
cout<<"The details are"<<endl;
cout<<"The first name is\t"<<s1.firstname<<endl;
cout<<"The last name is\t"<<s1.lastname<<endl;
cout<<"The score is\t"<<s1.score<<endl;
return 0;
}
/*output
Enter your firstname
Bill
Enter your lastname
Gates
Enter your score
90.5
The details are
The first name is Bill
The last name is Gates
The score is 90.5
*/
|
5a6f04602d898b1b192d13184bef3bd754799d4a | d065a83dfb5ca397d340a9034e8b1fabb5b1ba8e | /poo/TP/projeto/Territorio.h | 9bb11a9bcfb41177abf8e3eaca0a7e7d52fbacf3 | [] | no_license | rafaeljesusaraiva/isec-2021-1o-semestre | ae176c711e4f2d00b1a8454d96680c84072898b9 | 108057f1581101e9a7b7035188586f646c91840f | refs/heads/main | 2023-03-11T18:59:32.689936 | 2021-02-28T23:13:20 | 2021-02-28T23:13:20 | 301,668,779 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,567 | h | Territorio.h | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: Territorio.h
* Author: rafaeljesusaraiva
*
* Created on 8 de dezembro de 2020, 21:39
*/
#ifndef TERRITORIO_H
#define TERRITORIO_H
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;
class Territorio
{
int resistencia;
int cria_produto;
int cria_ouro;
string tipo;
vector<string> default_continente = {"castelo", "duna", "fortaleza", "mina", "montanha", "planicie"};
vector<string> default_continente_nome = {"Castelo", "Duna", "Fortaleza", "Mina", "Montanha", "Planicie"};
vector<int> default_continente_resistencia = {7, 4, 8, 5, 6, 5};
vector<int> default_continente_produto = {3, 1, 0, 0, 0, 1};
vector<int> default_continente_ouro = {1, 0, 0, 1, 0, 1};
vector<string> default_ilha = {"pescaria", "refugioDosPiratas"};
vector<string> default_ilha_nome = {"Pescaria", "Refugio dos Piratas"};
vector<int> default_ilha_resistencia = {9, 9};
vector<int> default_ilha_produto = {2, 0};
vector<int> default_ilha_ouro = {0, 1};
bool verifica_territorio(string nome);
public:
string nome;
Territorio(const string& n, string& tipo);
string getAsString() const;
string get_nome() const;
int get_resistencia() const;
int get_criaOuro() const;
int get_criaProduto() const;
};
#endif /* TERRITORIO_H */
|
06be8ea69adc438bfe5c0159cd29ed07929309df | d7906e84bda2bd386e074eab9f05479205e7d2a9 | /SDK/Examples/FilamentViewer/FilamentViewer/Wrappers/EngineSharedPtr.hpp | 8e91562edc3f93dcbbe0882cab8249b5f6fde8b5 | [
"BSD-3-Clause"
] | permissive | jwwalker/Quesa | 6fedd297a5a4dd1c21686e71bba3c68228f61724 | 1816b0772409c2faacdb70b40d5c02a55d643793 | refs/heads/master | 2023-07-27T16:36:55.757833 | 2023-07-06T23:55:10 | 2023-07-06T23:55:10 | 204,233,833 | 33 | 7 | BSD-3-Clause | 2023-09-09T23:17:36 | 2019-08-25T01:59:21 | C++ | UTF-8 | C++ | false | false | 6,007 | hpp | EngineSharedPtr.hpp | //
// EngineSharedPtr.hpp
// FilamentViewer
//
// Created by James Walker on 2/20/21.
//
/* ___________________________________________________________________________
COPYRIGHT:
Copyright (c) 2021, Quesa Developers. All rights reserved.
For the current release of Quesa, please see:
<https://github.com/jwwalker/Quesa>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
o Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
o Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
o Neither the name of Quesa nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
___________________________________________________________________________
*/
#ifndef EngineSharedPtr_hpp
#define EngineSharedPtr_hpp
#import <memory>
namespace filament
{
class IndexBuffer;
class VertexBuffer;
class Engine;
class Material;
class MaterialInstance;
class Texture;
class ColorGrading;
class IndirectLight;
class Renderer;
class Scene;
class SwapChain;
class View;
class RenderTarget;
class Skybox;
}
/*!
@class DestroyerByEngine
@abstract This helper object cleans up certain objects owned by the Engine.
*/
class DestroyerByEngine
{
public:
DestroyerByEngine( filament::Engine& inEngine );
DestroyerByEngine( const DestroyerByEngine& inOther );
~DestroyerByEngine() {}
void operator()( filament::VertexBuffer* vb ) const;
void operator()( filament::IndexBuffer* ib ) const;
void operator()( filament::MaterialInstance* mi ) const;
void operator()( filament::Texture* t ) const;
void operator()( filament::Material* x ) const;
void operator()( filament::IndirectLight* x ) const;
void operator()( filament::Renderer* x ) const;
void operator()( filament::Scene* x ) const;
void operator()( filament::SwapChain* x ) const;
void operator()( filament::View* x ) const;
void operator()( filament::ColorGrading* x ) const;
void operator()( filament::RenderTarget* x ) const;
void operator()( filament::Skybox* x ) const;
private:
filament::Engine& _engine;
};
/*!
@class EngineSharedPtr
@abstract A shared pointer type in which constructing or resetting with a non-null pointer
requires that you also provide an engine, so that proper cleanup can be done
when all references go away.
@discussion Using std::shared_ptr, one can provide a deleter object with the constructor or reset,
but this requires that the appropriate deleter be used.
*/
template <typename T, class Destroyer >
class EngineSharedPtr
{
public:
EngineSharedPtr()
: _engine( nullptr ) {}
EngineSharedPtr( const EngineSharedPtr& inOther )
: _ptr( inOther._ptr )
, _engine( inOther._engine ) {}
EngineSharedPtr( T* t, filament::Engine* inEngine )
: _ptr( t, Destroyer( *inEngine ) )
, _engine( inEngine ) {}
EngineSharedPtr& operator=( const EngineSharedPtr& inOther )
{
_ptr = inOther._ptr;
_engine = inOther._engine;
return *this;
}
T* operator->() const noexcept { return _ptr.get(); }
T* get() const noexcept { return _ptr.get(); }
T& operator*() const noexcept { return *_ptr; }
filament::Engine* engine() const noexcept { return _engine; }
void reset() noexcept
{
_ptr.reset();
_engine = nullptr;
}
void reset( T* t, filament::Engine* inEngine )
{
_engine = inEngine;
_ptr.reset( t, Destroyer( *_engine ) );
}
private:
std::shared_ptr< T > _ptr;
filament::Engine* _engine;
};
typedef EngineSharedPtr< filament::VertexBuffer, DestroyerByEngine > sharedVertexBuffer;
typedef EngineSharedPtr< filament::IndexBuffer, DestroyerByEngine > sharedIndexBuffer;
typedef EngineSharedPtr< filament::MaterialInstance, DestroyerByEngine > sharedMaterialInstance;
typedef EngineSharedPtr< filament::Texture, DestroyerByEngine > sharedTexture;
typedef EngineSharedPtr< filament::Material, DestroyerByEngine > sharedMaterial;
typedef EngineSharedPtr< filament::IndirectLight, DestroyerByEngine > sharedIndirectLight;
typedef EngineSharedPtr< filament::Renderer, DestroyerByEngine > sharedRenderer;
typedef EngineSharedPtr< filament::Scene, DestroyerByEngine > sharedScene;
typedef EngineSharedPtr< filament::SwapChain, DestroyerByEngine > sharedSwapChain;
typedef EngineSharedPtr< filament::View, DestroyerByEngine > sharedView;
typedef EngineSharedPtr< filament::ColorGrading, DestroyerByEngine > sharedColorGrading;
typedef EngineSharedPtr< filament::RenderTarget, DestroyerByEngine > sharedRenderTarget;
typedef EngineSharedPtr< filament::Skybox, DestroyerByEngine > sharedSkybox;
#endif /* EngineSharedPtr_hpp */
|
d8dd05ddf1ed5d014c5bbf563d9c592833d3d8c6 | 05159e869e4b457d78a6f3bc75424557e74d3c23 | /yandex_training/contest_200832/problemB/main.cpp | 6d88cea580d5af11687b208c43171e95551d9805 | [] | no_license | yuliy/sport_programming | 71b1c15939540561528e4d29eed8d2d90669b54c | 758a3497adaf314a69f7a8a0d0ffd3f9a0f3f2aa | refs/heads/master | 2023-06-23T05:14:26.548770 | 2023-06-14T22:32:17 | 2023-06-14T22:32:17 | 64,036,584 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,340 | cpp | main.cpp | #include <stdio.h>
#include <iostream>
#include <vector>
#include <deque>
#include <cstring>
#include <string>
#include <map>
#include <set>
#include <list>
#include <algorithm>
using namespace std;
int main() {
int a;
string s;
cin >> a >> s;
const int N = s.size();
vector<int> ps(s.size() + 1);
ps[0] = 0;
for (int i = 1; i <= N; ++i) {
ps[i] = ps[i-1] + int(s[i-1] - '0');
}
int zero_cnt = 0;
map<int, int> divisors;
for (int i = 1; i <= N; ++i) {
for (int j = i; j <= N; ++j) {
const int sum_ij = ps[j] - ps[i-1];
if (0 == sum_ij) {
++zero_cnt;
continue;
}
if (0 == a % sum_ij)
++divisors[sum_ij];
}
}
if (0 == a) {
cout << (N * (N+1) * (long long)zero_cnt - (long long)zero_cnt * zero_cnt) << endl;
return 0;
}
long long res = 0;
for (auto iter = divisors.begin(); iter != divisors.end(); ++iter) {
const int divisor = iter->first;
const long long cnt = iter->second;
const int supplementDivisor = a / divisor;
auto citer = divisors.find(supplementDivisor);
if (citer != divisors.end()) {
res += (cnt * citer->second);
}
}
cout << res << endl;
return 0;
}
|
022bfe2f6d65ece910e8a06eb69b2bc9ceda0c99 | a07e8ce8748e1c11dcb2fb4f1d8438759a791c0d | /year2/raytracing_reservecopy_05.04.2017/raytracing/primitive3d.cpp | c651ac481c79d359f8c2b626096ad5bfce3b62ca | [] | no_license | celidos/programming-mipt-2015-2017 | 7aef789009cf63dfe415070e6907c634a0b89c7a | cd27a7798f2f50164228b3ab0b7c3015a9c7c049 | refs/heads/master | 2021-06-16T14:22:29.455077 | 2017-05-13T15:33:58 | 2017-05-13T15:33:58 | 91,165,940 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 66 | cpp | primitive3d.cpp | #include "rtprimitive3d.h"
pindex Primitive3d::indexCounter = 1;
|
edfb0104240c3243d62c08d04a78a7941f2951a7 | 657baa6a8ec67b1d66f7861c6982096351cdad10 | /src/io/serial_port.cpp | 1a4772c3fccc60051bd8862409640d242cbdfd60 | [] | no_license | leismile/bittleet_ROS | 18f44aad129f8cdb1344a08bb3bb432632e0ef0f | 6cb16ff35cc520f3cab4545e3c2fff2cab61d810 | refs/heads/main | 2023-08-24T22:23:32.512902 | 2021-10-25T04:17:16 | 2021-10-25T04:17:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,070 | cpp | serial_port.cpp | //
// Serial Port
//
// Hoani Bryson (github.com/hoani)
// Copyright (c) 2021 Leetware Limited.
// License - MIT
//
#include "ros/ros.h"
#include "serial_port.h"
#include <pigpiod_if2.h>
SerialPortPigpio::SerialPortPigpio() {
_pi = pigpio_start("localhost", "8888");
if (_pi < 0) {
ROS_ERROR("Connecting to pigpiod failed");
return;
}
char serialPort[11] = "/dev/ttyS0";
_h = serial_open(_pi, serialPort, 115200, 0);
if (_h < 0) {
ROS_ERROR("Serial port unavaliable");
return;
}
}
SerialPortPigpio::~SerialPortPigpio() {
shutdown();
}
void SerialPortPigpio::shutdown() {
if (_h >= 0) {
serial_close(_pi, _h);
}
if (_pi >= 0) {
pigpio_stop(_pi);
}
_h = -1;
_pi = -1;
}
bool SerialPortPigpio::ready() const {
return ((_h >= 0) && (_pi >= 0));
}
bool SerialPortPigpio::write(const char* bytes, int len){
char toWrite[len];
std::memcpy(toWrite, bytes, len);
int result = serial_write(_pi, _h, toWrite, (unsigned)len);
return (result == 0);
}
|
9ff8cf6b9d9cce2c90825f3862c0383142d4ac7a | b95b7f8dad1984f1b4c62f6ddfd9985da165c642 | /newnotedialog.h | 09e0a67a3eb5bbe804d5661f4656bcbc93abe358 | [] | no_license | Aaltis/Note-File-Client | f4a17f953e7cf085cdeec7370eb5ca589db74cff | 7f233f2a7041ec8f807dd35bceef32077f269dfc | refs/heads/master | 2021-01-18T13:49:03.464942 | 2014-12-13T19:26:02 | 2014-12-13T19:26:02 | 29,674,012 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 503 | h | newnotedialog.h | #ifndef NEWNOTEDIALOG_H
#define NEWNOTEDIALOG_H
#include <QDialog>
#include <qmessagebox.h>
namespace Ui {
class NewNoteDialog;
}
class NewNoteDialog : public QDialog
{
Q_OBJECT
public:
explicit NewNoteDialog(QWidget *parent = 0);
~NewNoteDialog();
private slots:
void on_btnSave_clicked();
private:
Ui::NewNoteDialog *ui;
signals:
void noteCreated();
public slots:
void querySuccess(QString result);
void queryFailure(QString result);
};
#endif // NEWNOTEDIALOG_H
|
9b6a0014cdcdd8ff5eeeccd75ad1b494131af57d | cee49da9c32899a6dcb95cfab9118de7f64a51b3 | /exe2c/include/ClassManage.h | 551e6a4fefaa0ff4627a8be76d98a5ffd0803f98 | [
"BSD-3-Clause"
] | permissive | nemerle/exetoc_qt | 0ca5c7d23dd8494720352745e12439ec544ff19b | 3b82330ba56ec76d11b70373178948e524c567a3 | refs/heads/master | 2020-05-31T06:46:55.094143 | 2014-01-16T13:57:22 | 2014-01-16T13:57:22 | 831,681 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,686 | h | ClassManage.h | // Copyright(C) 1999-2005 LiuTaoTao,bookaa@rorsoft.com
#pragma once
#include <list>
#include <stdint.h>
typedef uint32_t ea_t;
#include "FuncType.h"
enum enumClassMemberAccess
{
nm_unknown = 0,
nm_private,
nm_protected,
nm_public,
nm_substruc,
nm_subunion,
nm_sub_end
};
struct st_Var_Declare
{ // 是对一个量的定义,包括数据类型和变量名
//Is a quantitative definition, including data type and variable name
// 可用于struct_struct中的item定义,和functoin parameter的定义等等
//Can be used to struct_struct the item definitions, and function parameter definitions, etc.
VarTypeID m_vartypeid;
SIZEOF m_size;
uint32_t m_offset_in_struc;
char m_name[80];
enumClassMemberAccess m_access; // 为class预留 //Reserved for the class
st_Var_Declare():m_vartypeid(0),m_size(0),m_offset_in_struc(0),m_access(nm_unknown)
{
m_name[0]=0;
}
};
// ----------------------------------------------------
// class
class Class_st
{
private:
public:
bool m_TclassFstruc; // TRUE means class, FALSE means struct
char m_name[80]; // class名 // class name
SIZEOF m_size; // class的size,数据部分 //Class's size, the data part of the
bool m_Fstruc_Tunion; //TRUE = union
ea_t m_Vftbl; //Virtual table addresses, if any,
std::vector<st_Var_Declare> m_DataItems; // member variables
std::vector<FuncType*> m_SubFuncs; //subroutine array
public:
Class_st();
~Class_st();
FuncType* LookUp_SubFunc(const char * name);
bool is_Constructor(const FuncType* pft) const;
bool is_Destructor(const FuncType* pft) const;
bool is_ConstructOrDestruct(const FuncType* pft) const;
const char * getclassitemname(uint32_t off);
st_Var_Declare* GetClassItem(uint32_t off);
// void prtout(CXmlPrt* prt);
void set_subfuncs();
bool IfThisName(const char * name) const;
const char * getname() const;
void log_display_structure();
};
class ClassManage
{
typedef std::list<Class_st *> CLASS_LIST;
CLASS_LIST m_classlist;
private:
static ClassManage* s_ClassManage;
ClassManage();
~ClassManage();
public:
static ClassManage* get();
FuncType* Get_SubFuncDefine_from_name(const char * classname, const char * funcname);
void add_class(Class_st* pnew);
Class_st* LoopUp_class_by_name(const char * name);
VarTypeID if_StrucName(const char * &p);
void new_struc(Class_st* pnew);
};
|
ed466163167c69161d9420df460b7ae7a1aec8cb | ece2e6cbd15a2b4fef15b6c5b0abbd4a938374e2 | /rollercoaster/pyramid.cpp | c75e989fe1f2c20541b96db32fbdd0bbaa1242c0 | [] | no_license | samkellett/rollercoaster | d81ea2dc00de36a605da1e48afe13a1cabe7acbe | 49ae681fcacb074295eaa6a37f1cd68e354bb652 | refs/heads/master | 2021-04-11T10:33:09.838809 | 2013-04-02T02:36:36 | 2013-04-02T02:36:36 | 249,011,492 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,568 | cpp | pyramid.cpp | #include "pyramid.h"
// Create the plane, including its geometry, texture mapping, normal, and colour
Pyramid::Pyramid(glm::vec2 position, float scale) : GameObject(),
position_(position.x, 0.0f, position.y), scale_(scale),
directory_("resources/textures/"),
filename_("pyramid.jpg"),
width_(10.0f),
height_(7.5f)
{
// Load the texture
texture_.load(directory_ + filename_, true);
// Set parameters for texturing using sampler object
texture_.setFiltering(TEXTURE_FILTER_MAG_BILINEAR, TEXTURE_FILTER_MIN_BILINEAR_MIPMAP);
texture_.setSamplerParameter(GL_TEXTURE_WRAP_S, GL_REPEAT);
texture_.setSamplerParameter(GL_TEXTURE_WRAP_T, GL_REPEAT);
// Use VAO to store state associated with vertices
glGenVertexArrays(1, &vao_);
glBindVertexArray(vao_);
// Create a VBO
vbo_.create();
vbo_.bind();
float half_width = width_ / 2.0f;
glm::vec3 a = glm::vec3(0.0f, height_, 0.0f);
glm::vec3 b = glm::vec3(half_width, 0.0f, -half_width);
glm::vec3 c = glm::vec3(-half_width, 0.0f, -half_width);
glm::vec3 d = glm::vec3(half_width, 0.0f, half_width);
glm::vec3 e = glm::vec3(-half_width, 0.0f, half_width);
// Vertex positions
glm::vec3 plane_vertices[12] = {
a, b, c,
a, d, b,
a, e, d,
a, c, e
};
// Texture coordinates
glm::vec2 texture_coords[3] = {
glm::vec2(0.5f, 1.0f),
glm::vec2(1.0f, 0.0f),
glm::vec2(0.0f, 0.0f)
};
glm::vec3 n1 = glm::normalize(glm::cross(c - a, b - a));
glm::vec3 n2 = glm::normalize(glm::cross(b - a, d - a));
glm::vec3 n3 = glm::normalize(glm::cross(d - a, e - a));
glm::vec3 n4 = glm::normalize(glm::cross(e - a, c - a));
glm::vec3 na = (n1 + n2 + n3 + n4) / 4.0f;
glm::vec3 nb = (n1 + n2) / 2.0f;
glm::vec3 nc = (n1 + n4) / 2.0f;
glm::vec3 nd = (n2 + n3) / 2.0f;
glm::vec3 ne = (n3 + n4) / 2.0f;
// Plane normal
glm::vec3 normals[12] = {
na, nb, nc,
na, nd, nb,
na, ne, nd,
na, nc, ne
};
// Put the vertex attributes in the VBO
for (int i = 0; i < 12; ++i) {
vbo_.addData(&plane_vertices[i], sizeof(glm::vec3));
vbo_.addData(&texture_coords[i % 3], sizeof(glm::vec2));
vbo_.addData(&normals[i], sizeof(glm::vec3));
}
// Upload the VBO to the GPU
vbo_.uploadDataToGPU(GL_STATIC_DRAW);
// Set the vertex attribute locations
GLsizei stride = sizeof(glm::vec3) + sizeof(glm::vec2) + sizeof(glm::vec3);
// Vertex positions
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, 0);
// Texture coordinates
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, stride, (void*) sizeof(glm::vec3));
// Normal vectors
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, stride, (void*) (sizeof(glm::vec3) + sizeof(glm::vec2)));
}
// Release resources
Pyramid::~Pyramid()
{
texture_.release();
glDeleteVertexArrays(1, &vao_);
vbo_.release();
}
void Pyramid::init(ShaderProgram *program)
{
GameObject::init(program);
Game &game = Game::instance();
position_ = glm::vec3(position_.x, game.height(position_) - 3.0f, position_.z);
}
void Pyramid::update(glutil::MatrixStack &, double)
{
}
void Pyramid::render(glutil::MatrixStack &modelview, ShaderProgram *program)
{
modelview.translate(position_);
modelview.scale(scale_);
Lighting::diffuseSpecular(program, 0.6f, 1.0f, 1.0f);
program->setUniform("matrices.modelview", modelview.top());
program->setUniform("not_textured", false);
glBindVertexArray(vao_);
texture_.bind();
glDrawArrays(GL_TRIANGLES, 0, 12);
}
|
d5e36c992ebcbab3ef56613812b9875a9a31e8db | 1f2890135af010d35c4e7aeb9257175197c6d834 | /include/suic/Skia/utils/SkThreadPool.h | a75bed8be44f538eeb87d3c21658f2de83290618 | [
"MIT"
] | permissive | OhmPopy/MPFUI | 311252a86c20c95250c18b4ed202ec15713ffcff | eac88d66aeb88d342f16866a8d54858afe3b6909 | refs/heads/master | 2020-03-27T09:52:41.798380 | 2019-12-03T02:21:13 | 2019-12-03T02:21:13 | 146,379,645 | 0 | 0 | MIT | 2018-08-28T02:17:26 | 2018-08-28T02:17:25 | null | UTF-8 | C++ | false | false | 6,056 | h | SkThreadPool.h | /*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkThreadPool_DEFINED
#define SkThreadPool_DEFINED
#include "SkCondVar.h"
#include "SkRunnable.h"
#include "SkTDArray.h"
#include "SkTInternalLList.h"
#include "SkThreadUtils.h"
#include "SkTypes.h"
#if defined(SK_BUILD_FOR_UNIX) || defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_ANDROID)
# include <unistd.h>
#endif
// Returns the number of cores on this machine.
static inline int num_cores() {
#if defined(SK_BUILD_FOR_WIN32)
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
return sysinfo.dwNumberOfProcessors;
#elif defined(SK_BUILD_FOR_UNIX) || defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_ANDROID)
return sysconf(_SC_NPROCESSORS_ONLN);
#else
return 1;
#endif
}
template <typename T>
class SkTThreadPool {
public:
/**
* Create a threadpool with count threads, or one thread per core if kThreadPerCore.
*/
static const int kThreadPerCore = -1;
explicit SkTThreadPool(int count);
~SkTThreadPool();
/**
* Queues up an SkRunnable to run when a thread is available, or synchronously if count is 0.
* Does not take ownership. NULL is a safe no-op. If T is not void, the runnable will be passed
* a reference to a T on the thread's local stack.
*/
void add(SkTRunnable<T>*);
/**
* Block until all added SkRunnables have completed. Once called, calling add() is undefined.
*/
void wait();
private:
struct LinkedRunnable {
SkTRunnable<T>* fRunnable; // Unowned.
SK_DECLARE_INTERNAL_LLIST_INTERFACE(LinkedRunnable);
};
enum State {
kRunning_State, // Normal case. We've been constructed and no one has called wait().
kWaiting_State, // wait has been called, but there still might be work to do or being done.
kHalting_State, // There's no work to do and no thread is busy. All threads can shut down.
};
SkTInternalLList<LinkedRunnable> fQueue;
SkCondVar fReady;
SkTDArray<SkThread*> fThreads;
State fState;
int fBusyThreads;
static void Loop(void*); // Static because we pass in this.
};
template <typename T>
SkTThreadPool<T>::SkTThreadPool(int count) : fState(kRunning_State), fBusyThreads(0) {
if (count < 0) {
count = num_cores();
}
// Create count threads, all running SkTThreadPool::Loop.
for (int i = 0; i < count; i++) {
SkThread* thread = SkNEW_ARGS(SkThread, (&SkTThreadPool::Loop, this));
*fThreads.append() = thread;
thread->start();
}
}
template <typename T>
SkTThreadPool<T>::~SkTThreadPool() {
if (kRunning_State == fState) {
this->wait();
}
}
namespace SkThreadPoolPrivate {
template <typename T>
struct ThreadLocal {
void run(SkTRunnable<T>* r) { r->run(data); }
T data;
};
template <>
struct ThreadLocal<void> {
void run(SkTRunnable<void>* r) { r->run(); }
};
} // namespace SkThreadPoolPrivate
template <typename T>
void SkTThreadPool<T>::add(SkTRunnable<T>* r) {
if (r == NULL) {
return;
}
if (fThreads.isEmpty()) {
SkThreadPoolPrivate::ThreadLocal<T> threadLocal;
threadLocal.run(r);
return;
}
LinkedRunnable* linkedRunnable = SkNEW(LinkedRunnable);
linkedRunnable->fRunnable = r;
fReady.lock();
SkASSERT(fState != kHalting_State); // Shouldn't be able to add work when we're halting.
fQueue.addToHead(linkedRunnable);
fReady.signal();
fReady.unlock();
}
template <typename T>
void SkTThreadPool<T>::wait() {
fReady.lock();
fState = kWaiting_State;
fReady.broadcast();
fReady.unlock();
// Wait for all threads to stop.
for (int i = 0; i < fThreads.count(); i++) {
fThreads[i]->join();
SkDELETE(fThreads[i]);
}
SkASSERT(fQueue.isEmpty());
}
template <typename T>
/*static*/ void SkTThreadPool<T>::Loop(void* arg) {
// The SkTThreadPool passes itself as arg to each thread as they're created.
SkTThreadPool<T>* pool = static_cast<SkTThreadPool<T>*>(arg);
SkThreadPoolPrivate::ThreadLocal<T> threadLocal;
while (true) {
// We have to be holding the lock to read the queue and to call wait.
pool->fReady.lock();
while(pool->fQueue.isEmpty()) {
// Does the client want to stop and are all the threads ready to stop?
// If so, we move into the halting state, and whack all the threads so they notice.
if (kWaiting_State == pool->fState && pool->fBusyThreads == 0) {
pool->fState = kHalting_State;
pool->fReady.broadcast();
}
// Any time we find ourselves in the halting state, it's quitting time.
if (kHalting_State == pool->fState) {
pool->fReady.unlock();
return;
}
// wait yields the lock while waiting, but will have it again when awoken.
pool->fReady.wait();
}
// We've got the lock back here, no matter if we ran wait or not.
// The queue is not empty, so we have something to run. Claim it.
LinkedRunnable* r = pool->fQueue.tail();
pool->fQueue.remove(r);
// Having claimed our SkRunnable, we now give up the lock while we run it.
// Otherwise, we'd only ever do work on one thread at a time, which rather
// defeats the point of this code.
pool->fBusyThreads++;
pool->fReady.unlock();
// OK, now really do the work.
threadLocal.run(r->fRunnable);
SkDELETE(r);
// Let everyone know we're not busy.
pool->fReady.lock();
pool->fBusyThreads--;
pool->fReady.unlock();
}
SkASSERT(false); // Unreachable. The only exit happens when pool->fState is kHalting_State.
}
typedef SkTThreadPool<void> SkThreadPool;
#endif
|
0f0f3b6f92f7879c3ad04088b85790c6100af10c | 51e44bc9d383823c7c2851592e4b0cb61e359522 | /【入门2】分支结构/P5715 【深基3.例8】三位数排序/P5715.cpp | ced27ea4fae11414d9b14de6b0b4faa4d1d6e597 | [] | no_license | VohsiLiu/Luogu-Problem-Set | bb861f05c5713900e89b2db98c6bd2e8c03cf08b | 5a9d6a3f543d6c0c2ab19e0b52283b0bc198a554 | refs/heads/main | 2023-07-18T09:49:38.167402 | 2021-09-09T13:15:46 | 2021-09-09T13:15:46 | 397,551,456 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 491 | cpp | P5715.cpp | #include <iostream>
#include <cstdio>
using namespace std;
//冒泡排序
void exchage(int *x, int *y){
int temp = *y;
*y =*x;
*x =temp;
}
int main(){
int a[3];
for (int i=0;i<3;i++){
cin >> a[i];
}
int len = sizeof(a)/sizeof(a[0]);
for (int i=0;i<len;i++){
for (int j=0;j<len-i-1;j++){
if (a[j]>a[j+1]){
exchage(&a[j],&a[j+1]);
}
}
}
printf("%d %d %d",a[0],a[1],a[2]);
return 0;
} |
06844eb2cd37a49289ebff039d0be445245bae66 | 72e7926d59a0aac90898071e597fc1b6be39e589 | /src/Constraint.h | 6d8b90ef49951cf9c2a715b45749f8366d6ac920 | [] | no_license | disbeat/roadef2010 | 43c1a46b294f5f36ed72aaeb6c50859785c3a08e | a541813ecf9d96962508c7f1d2656277b8239068 | refs/heads/master | 2021-01-22T12:08:40.963813 | 2011-03-23T21:51:00 | 2011-03-23T21:51:00 | 1,520,489 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 203 | h | Constraint.h | #pragma once
#include <stdio.h>
class Constraint
{
protected:
int index, type;
public:
//Constraint(FILE* inputFile);
Constraint();
virtual ~Constraint(void);
void readHeader(FILE* inputFile);
};
|
bb4745145c1ebbb5995e6b2117c39d7c328f9315 | c5c05c12d654573d1ce2bf10ad568fd0a1a38828 | /cpp05/ex03/PresidentialPardonForm.cpp | 58daed01dceecdee8e88d90689e03be2a28ad7d9 | [] | no_license | oelbourki/Cpp-pool | 57142583742b4752cda5eafe1e49ff7989cb88f6 | 2ba9f0336dd02d3355ce70197d391f5ee53d1e32 | refs/heads/master | 2023-02-18T11:25:15.863655 | 2021-01-08T15:00:51 | 2021-01-08T15:00:51 | 232,116,842 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,091 | cpp | PresidentialPardonForm.cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* PresidentialPardonForm.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: oel-bour <oel-bour@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/22 17:26:33 by oel-bour #+# #+# */
/* Updated: 2020/02/22 17:26:34 by oel-bour ### ########.fr */
/* */
/* ************************************************************************** */
#include "PresidentialPardonForm.hpp"
PresidentialPardonForm::PresidentialPardonForm() : Form("",5,25)
{
}
PresidentialPardonForm::PresidentialPardonForm(std::string target) : Form(target,5,25)
{
}
PresidentialPardonForm::~PresidentialPardonForm()
{
}
void PresidentialPardonForm::execute(Bureaucrat const & executor) const
{
if (this->getSigne() && (executor.getGrade() <= this->getEx_grade()))
std::cout << this->getName() << " has been pardoned by Zafod Beeblebrox." << std::endl;
else if (this->getSigne() == 0 && (executor.getGrade() <= this->getEx_grade()))
std::cout << "the form must be signed first" << std::endl;
else
throw Form::GradeTooLowException();
}
std::ostream &operator<<(std::ostream &out,PresidentialPardonForm &form)
{
out << "PresidentialPardonForm inforamtion:" << std::endl;
out << "name: " << form.getName() << std::endl;
out << "signing grade requirement: "<< form.getSig_grade() << std::endl;
out << "excution grade requirement: " << form.getEx_grade() << std::endl;
if (form.getSigne())
out << "form has been signed\n";
else
out << "form has been not signed yet\n";
return out;
} |
1b7691cdb841ce803d2c9448e198140d360de627 | 69a3bb3b7761235cdd32462fa0459525a74b0ec2 | /xennigan-shell.cxx | f92c5c5ba8eef2201d50f42dc577c6ca81e31282 | [] | no_license | bwesterb/xennigan | afdbbfefee80dd76a7c6fae3815381d2d4917a1e | bad53e4635be02b3cb63eac10fb0c361e755124a | refs/heads/master | 2022-01-26T09:57:02.500307 | 2021-12-29T10:19:29 | 2021-12-29T10:19:29 | 50,877,127 | 1 | 2 | null | 2016-03-28T14:30:10 | 2016-02-01T22:47:04 | Python | UTF-8 | C++ | false | false | 8,265 | cxx | xennigan-shell.cxx | #include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <boost/algorithm/string.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/regex.hpp>
#include <boost/format.hpp>
#include <readline/readline.h>
#include <readline/history.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
namespace po = boost::program_options;
const boost::regex dom_name_regex("[a-zA-Z0-9\\-][a-zA-Z0-9\\-.]*");
class Xennigan
{
std::string xl_path = "/usr/sbin/xl";
std::string domu_cfg_path_fmt = "/etc/xen/%1%.cfg";
const std::string config_file_path = "/etc/xennigan-shell.conf";
std::string dom_name;
std::string domu_cfg_path;
bool running = true;
const std::map<std::string, void (Xennigan::*)()> cmd_map = {
{"exit", &Xennigan::cmd_exit},
{"status", &Xennigan::cmd_list},
{"list", &Xennigan::cmd_list},
{"reboot", &Xennigan::cmd_reboot},
{"shutdown", &Xennigan::cmd_shutdown},
{"destroy", &Xennigan::cmd_destroy},
{"console", &Xennigan::cmd_console},
{"create", &Xennigan::cmd_create},
{"help", &Xennigan::cmd_help},
};
public:
int main(int argc, char* argv[])
{
// NOTE argc might be zero.
// We do not trust our environment.
if (clearenv() != 0)
return -6;
// First check if stdin, stdout and stderr are open. If not, exit.
if (fcntl(0, F_GETFL) == -1 || fcntl(1, F_GETFL) == -1
|| fcntl(2, F_GETFL) == -1)
return -5;
// Set umask to a sensible default.
umask(S_IWGRP | S_IWOTH);
// Set real uid of the process to 0 (root). If we do not do this, then
// bash reverts the effective uid of `xl' back to that of the
// xennigan user. See e.g.
// http://stackoverflow.com/questions/556194
if (setuid(0) != 0)
return -11;
// Load configuration file, if present.
if (!this->load_configuration_file())
return -7;
// Get name of the domu from the commandline.
if (argc != 2) {
std::cerr << "xennigan: Expected single commandline option"
<< std::endl;
return -1;
}
this->dom_name = std::string(argv[1]);
// Check name against regex
if (!boost::regex_match(this->dom_name, dom_name_regex)) {
std::cerr << "xennigan: invalid domain name"
<< std::endl;
return -3;
}
try {
this->domu_cfg_path = (boost::format(this->domu_cfg_path_fmt)
% this->dom_name).str();
} catch (std::exception& e) {
std::cerr << "Invalid domu-cfg-path: "
<< e.what() << std::endl;
return -9;
}
if (!boost::filesystem::exists(this->domu_cfg_path)) {
std::cerr << "xennigan: configuration file for domain not found"
<< std::endl;
return -4;
}
// Check if xl binary exists
if (!boost::filesystem::exists(this->xl_path)) {
std::cerr << this->xl_path << " does not exist. "
<< "Please adjust xl-path in "
<< this->config_file_path << std::endl;
return -8;
}
// Check if xl binary path is absolute
if (this->xl_path.substr(0, 1) != "/") {
std::cerr << "xl-path is not absolute." << std::endl;
return -10;
}
// Main loop of the shell
while (this->running) {
std::string prompt = dom_name + "> ";
const char* c_line = readline(prompt.c_str());
if (!c_line) {
std::cout << std::endl;
break;
}
add_history(c_line); // readline
std::string line(c_line);
if (line.empty())
continue;
// Split it into [command] [arg1] ...
std::vector<std::string> bits;
boost::split(bits, line, boost::is_any_of(" "));
// Find the command handler
auto it = this->cmd_map.find(bits[0]);
if (it == this->cmd_map.end()) {
std::cout << "Command not found. "
<< "Type `help' for a list of commands."
<< std::endl;
continue;
}
// Execute command handler
(this->*(it->second))();
}
return 0;
}
private:
void cmd_exit()
{
std::cout << "bye" << std::endl;
this->running = false;
}
void cmd_list()
{
this->run_xl({"list", this->dom_name});
}
void cmd_reboot()
{
this->run_xl({"reboot", this->dom_name});
}
void cmd_shutdown()
{
this->run_xl({"shutdown", this->dom_name});
}
void cmd_destroy()
{
this->run_xl({"destroy", this->dom_name});
}
void cmd_console()
{
this->run_xl({"console", this->dom_name});
}
void cmd_create()
{
this->run_xl({"create", this->domu_cfg_path});
}
void cmd_help()
{
std::cout << "Available commands:" << std::endl
<< " status shows status of domu" << std::endl
<< " shutdown sends shutdown signal to domu" << std::endl
<< " reboot sends reboot signal to domu" << std::endl
<< " console opens console to domu" << std::endl
<< " destroy immediate shutdown of domu" << std::endl
<< " create starts domu if not running" << std::endl
<< " exit exits shell" << std::endl;
}
void run_xl(std::initializer_list<std::string> args)
{
// TODO this is a bit C-y. Is there a C++ way?
// Copy arguments into buffer.
std::vector<const char*> c_args;
c_args.push_back(this->xl_path.c_str());
for (std::string const& arg : args)
c_args.push_back(arg.c_str());
c_args.push_back(nullptr);
pid_t child_pid = vfork();
if (child_pid == -1) {
std::cerr << "vfork() failed" << std::endl;
return;
}
if (child_pid > 0) {
int status;
waitpid(child_pid, &status, 0);
if (!WIFEXITED(status))
std::cerr << "xl did not exit properly" << std::endl;
else if (WEXITSTATUS(status) != 0)
std::cerr << "xl exited with code "
<< WEXITSTATUS(status) << std::endl;
return;
}
// TODO make path to executable configurable.
// TODO can we avoid the cast?
execv(this->xl_path.c_str(), const_cast<char**>(c_args.data()));
_exit(-2);
}
bool load_configuration_file()
{
if (!boost::filesystem::exists(this->config_file_path))
return true; // Use defaults
// Declare options for configuration file
po::options_description desc;
desc.add_options()
("xl-path", po::value<std::string>())
("domu-cfg-path", po::value<std::string>())
;
// Parse config file
// TODO handle fail conditions of f
std::ifstream f(this->config_file_path);
po::variables_map vm;
try {
po::store(po::parse_config_file(f, desc), vm);
} catch (po::error& e) {
std::cerr << "Failed to parse config file: "
<< e.what() << std::endl;
return false;
}
// Store
if (vm.count("xl-path"))
this->xl_path = vm["xl-path"].as<std::string>();
if (vm.count("domu-cfg-path"))
this->domu_cfg_path_fmt = vm["domu-cfg-path"].as<std::string>();
return true;
}
};
int main(int argc, char* argv[])
{
Xennigan program;
program.main(argc, argv);
}
|
c7cec6d6482608b08e9c56cafa9f14baae3eb091 | 0185b0451c89d8758af022f2e15225317dba85c8 | /CPP_module_00/ex01/phonebook.cpp | d89da9b9263c1798952a58e28047e35d0cfbae60 | [] | no_license | atomatoe/CPP_modules | 8c6acb03193f7ae39d732f44bd08a38678f6be7d | b0ca9d84a8fe4404caa1cc2e6f886abc151bb765 | refs/heads/master | 2023-03-24T05:47:03.209605 | 2021-03-16T20:21:22 | 2021-03-16T20:21:22 | 320,817,437 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,084 | cpp | phonebook.cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* phonebook.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: atomatoe <atomatoe@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/29 21:42:46 by atomatoe #+# #+# */
/* Updated: 2020/12/03 17:53:45 by atomatoe ### ########.fr */
/* */
/* ************************************************************************** */
#include "phonebook.hpp"
static int get_person(Joy *Koin, int i)
{
std::string buffer;
std::cout << "--- Записная книжка ---" << std::endl;
std::cout << "Введите ваш first name:" << std::endl;
std::getline(std::cin, buffer);
Koin[i].set_first_name(buffer);
std::cout << "Введите ваш last name:" << std::endl;
std::getline(std::cin, buffer);
Koin[i].set_last_name(buffer);
std::cout << "Введите ваш nickname:" << std::endl;
std::getline(std::cin, buffer);
Koin[i].set_nickname(buffer);
std::cout << "Введите ваш login:" << std::endl;
std::getline(std::cin, buffer);
Koin[i].set_login(buffer);
std::cout << "Введите ваш postal adress:" << std::endl;
std::getline(std::cin, buffer);
Koin[i].set_postal_adress(buffer);
std::cout << "Введите ваш email adress:" << std::endl;
std::getline(std::cin, buffer);
Koin[i].set_email_adress(buffer);
std::cout << "Введите ваш phone number:" << std::endl;
std::getline(std::cin, buffer);
Koin[i].set_phone_number(buffer);
std::cout << "Введите ваш birthday date:" << std::endl;
std::getline(std::cin, buffer);
Koin[i].set_birthday_date(buffer);
std::cout << "Введите ваш favorite meal:" << std::endl;
std::getline(std::cin, buffer);
Koin[i].set_favorite_meal(buffer);
std::cout << "Введите ваш underwear color:" << std::endl;
std::getline(std::cin, buffer);
Koin[i].set_underwear_color(buffer);
std::cout << "Введите ваш darkest secret:" << std::endl;
std::getline(std::cin, buffer);
Koin[i].set_darkest_secret(buffer);
if(Koin[i].get_first_name() == "" || Koin[i].get_last_name() == "" || Koin[i].get_nickname() == "")
{
i--;
std::cout << "Ошибка!\nНеобходимо заполнить первые три поля обязательно!" << std::endl;
}
else
std::cout << "Профиль " << Koin[i].get_first_name() << " " << Koin[i].get_last_name() << " создан!" << std::endl;
return(i);
}
static std::string string_len(std::string str)
{
if(str.length() >= 10)
str = str.substr(0, 9) + '.';
return(str);
}
static int ft_str_digit(std::string command)
{
for(int i = 0; command[i]; i++)
{
if(isdigit(command[i]) == 0)
return(-1);
if(i > 0)
return(-1);
}
return(0);
}
static void print_person(Joy *Koin, int i)
{
if(Koin[i].get_first_name() != "" && Koin[i].get_last_name() != "" && Koin[i].get_nickname() != "")
{
std::cout << "first name: " << Koin[i].get_first_name() << std::endl;
std::cout << "last name: " << Koin[i].get_last_name() << std::endl;
std::cout << "nickname: " << Koin[i].get_nickname() << std::endl;
std::cout << "login: " << Koin[i].get_login() << std::endl;
std::cout << "postaladress: " << Koin[i].get_postal_adress() << std::endl;
std::cout << "email adress: " << Koin[i].get_email_adress() << std::endl;
std::cout << "phone number: " << Koin[i].get_phone_number() << std::endl;
std::cout << "birthday date: " << Koin[i].get_birthday_date() << std::endl;
std::cout << "favorite meal: " << Koin[i].get_favorite_meal() << std::endl;
std::cout << "underwear color: " << Koin[i].get_underwear_color() << std::endl;
std::cout << "darkest secret: " << Koin[i].get_darkest_secret() << std::endl;
}
else
std::cout << "Вы ввели неправильный индекс! Повторите SEARCH" << std::endl;
}
static void ft_search(Joy *Koin, int i)
{
std::cout << "Ваша записная книжка:" << std::endl;
std::cout << "| ID | Имя | Фамилия | Никнейм |" << std::endl;
for(int index = 0; index < i;)
{
std::cout << "|" << std::setw(10) << index << "|" << std::setw(10) << string_len(Koin[index].get_first_name())
<< "|" << std::setw(10) << string_len(Koin[index].get_last_name()) << "|"
<< std::setw(10) << string_len(Koin[index].get_nickname()) << "|" << std::endl;
index++;
}
std::cout << "Введите индекс необходимого контакта:" << std::endl;
std::string command;
int index_contact;
while(1)
{
std::getline(std::cin >> std::ws, command);
if (command.compare(0, command.length(), "EXIT") == 0)
break ;
else if(ft_str_digit(command) == 0)
{
index_contact = std::stoi(command);
if(index_contact > 7 || index_contact > i)
std::cout << "Вы ввели неправильный индекс!" << std::endl;
else
{
print_person(Koin, index_contact);
break ;
}
}
else
std::cout << "Вы ввели неправильный индекс!" << std::endl;
}
}
int main()
{
Joy Koin[8];
std::string command;
for(int i = 0; 1;)
{
std::getline(std::cin >> std::ws, command);
if (command.compare(0, command.length(), "ADD") == 0 && i < 8)
{
i = get_person(Koin, i);
i++;
}
else if (command.compare(0, command.length(), "EXIT") == 0)
break ;
else if (command.compare(0, command.length(), "SEARCH") == 0)
ft_search(Koin, i);
}
return (0);
}
|
b8d26f0bf9f431bb0a906677a4caa3290dd78d50 | 9c932aa68c918d0148445f5e4da6e41190bdeab1 | /agents_evolution_and_learning/TTopologyAnalysis.cpp | 46ca020b40932e13a11102c4cd84f7c207159d7a | [] | no_license | klakhman/agents_evolution_and_learning | 69fa5c2c9a8f676772e109c4d763c45d521e56e5 | 120a6f2735af079240d1931b3322431709f79231 | refs/heads/master | 2020-05-18T03:20:04.048054 | 2014-02-24T09:25:20 | 2014-02-24T09:25:20 | 5,669,375 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,640 | cpp | TTopologyAnalysis.cpp | #include "TTopologyAnalysis.h"
#include <vector>
#include <map>
#include <cstdlib>
#include <string>
using namespace std;
TTopologyAnalysis::TTopologyAnalysis(){
}
/*std::vector<int> TTopologyAnalysis::getPoolId(int id){
return idArray[id];
}*/
map< int, vector<int> > TTopologyAnalysis::initializeIdArray(TPoolNetwork *network){
// номер поколения текущего пула
int currentGeneration = 1;
// порядковый номер потомка (как считает родитель)
int childNumber;
int currentPool;
int parentId;
vector<int> newId;
// добавляем id для первого пула
newId.push_back(currentGeneration);
std::map< int, std::vector<int> > idArray;
idArray.insert(pair< int, vector<int> >(network->getInputResolution() + network->getOutputResolution() + 1, newId));
// цикл по внутренним пулам
for(parentId = network->getInputResolution() + network->getOutputResolution() + 1; parentId <= network->getPoolsQuantity(); ++parentId){
childNumber = 0;
// цикл поиска пулов, родителем которых является текущий пул
for(currentPool = network->getInputResolution() + network->getOutputResolution() + 1; currentPool <= network->getPoolsQuantity(); ++currentPool){
if(network->getPoolRootPoolID(currentPool) == parentId){
++childNumber;
newId.clear();
currentGeneration = idArray[parentId][0] + 1;
// указываем поколение потомка
newId.push_back(currentGeneration);
// указываем id родителя (все, кроме его поколения)
for(int i = 1; i < currentGeneration - 1; ++i){
newId.push_back(idArray[parentId].at(i));
}
cout << "new ID: " << currentPool << ", ";
// указываем порядковый номер потомка
newId.push_back(childNumber);
for(unsigned int j = 0; j < newId.size(); j++)
cout << newId.at(j) << " ";
cout << endl;
// добавляем id для текущего пула в массив id сети
idArray.insert(pair< int, vector<int> >(currentPool, newId));
}
}
}
return idArray;
}
void printGraphNetworkMGraal(TPoolNetwork *network, map< int, vector<int> > idArray, string graphFilename){
ofstream hGraalGraphFile;
hGraalGraphFile.open((graphFilename + ".txt").c_str());
// Записываем связи
for (int currentPool = 1; currentPool <= network->getPoolsQuantity(); ++currentPool)
for (int currentConnection = 1; currentConnection <= network->getPoolInputConnectionsQuantity(currentPool); ++currentConnection)
if (network->getConnectionEnabled(currentPool, currentConnection)){
// работает только если у кажого из нейронов менее 10 потомков (одноразрядное число)
for(unsigned int i = 0; i < idArray[network->getConnectionPrePoolID(currentPool, currentConnection)].size(); ++i){
hGraalGraphFile << idArray[network->getConnectionPrePoolID(currentPool, currentConnection)][i];
}
hGraalGraphFile << " ";
for(unsigned int i = 0; i < idArray[network->getConnectionPostPoolID(currentPool, currentConnection)].size(); ++i){
hGraalGraphFile << idArray[network->getConnectionPostPoolID(currentPool, currentConnection)][i];
}
hGraalGraphFile << "\n";
}
hGraalGraphFile.close();
// system(("list2leda " + graphFilename + ".txt" + graphFilename + "leda.gw").c_str());
}
TTopologyAnalysis::~TTopologyAnalysis(){
}
|
4c8f40529020444872221e330757210d9fec2cad | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/admin/activec/samples/sdksamples/complete/space.cpp | 212d18484c0896ae6e544c0ac216ee1ea7b6cf4b | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 19,480 | cpp | space.cpp | //==============================================================;
//
// This source code is only intended as a supplement to
// existing Microsoft documentation.
//
//
//
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
//
// Copyright (C) 1999 Microsoft Corporation. All Rights Reserved.
//
//
//
//==============================================================;
#include <stdio.h>
#include <windows.h>
#include "Space.h"
#include "Comp.h"
#include "CompData.h"
#include "DataObj.h"
#include "globals.h"
#include "resource.h"
const GUID CSpaceVehicle::thisGuid = { 0xb95e11f4, 0x6be7, 0x11d3, {0x91, 0x56, 0x0, 0xc0, 0x4f, 0x65, 0xb3, 0xf9} };
const GUID CRocket::thisGuid = { 0xb95e11f5, 0x6be7, 0x11d3, {0x91, 0x56, 0x0, 0xc0, 0x4f, 0x65, 0xb3, 0xf9} };
//==============================================================
//
// CSpaceVehicle implementation
//
//
CSpaceVehicle::CSpaceVehicle() : m_cchildren(NUMBER_OF_CHILDREN)
{
for (int n = 0; n < m_cchildren; n++) {
children[n] = new CRocket(_T("Rocket"), n+1, 500000, 265, 75000, this);
}
}
CSpaceVehicle::~CSpaceVehicle()
{
for (int n = 0; n < m_cchildren; n++)
if (children[n]) {
delete children[n];
}
}
HRESULT CSpaceVehicle::OnShow(IConsole *pConsole, BOOL bShow, HSCOPEITEM scopeitem)
{
HRESULT hr = S_OK;
IHeaderCtrl *pHeaderCtrl = NULL;
IResultData *pResultData = NULL;
if (bShow) {
hr = pConsole->QueryInterface(IID_IHeaderCtrl, (void **)&pHeaderCtrl);
_ASSERT( SUCCEEDED(hr) );
hr = pConsole->QueryInterface(IID_IResultData, (void **)&pResultData);
_ASSERT( SUCCEEDED(hr) );
// Set the column headers in the results pane
hr = pHeaderCtrl->InsertColumn( 0, L"Rocket Class", 0, MMCLV_AUTO );
_ASSERT( S_OK == hr );
hr = pHeaderCtrl->InsertColumn( 1, L"Rocket Weight", 0, MMCLV_AUTO );
_ASSERT( S_OK == hr );
hr = pHeaderCtrl->InsertColumn( 2, L"Rocket Height", 0, MMCLV_AUTO );
_ASSERT( S_OK == hr );
hr = pHeaderCtrl->InsertColumn( 3, L"Rocket Payload", 0, MMCLV_AUTO );
_ASSERT( S_OK == hr );
hr = pHeaderCtrl->InsertColumn( 4, L"Status", 0, MMCLV_AUTO );
_ASSERT( S_OK == hr );
// insert items here
RESULTDATAITEM rdi;
hr = pResultData->DeleteAllRsltItems();
_ASSERT( SUCCEEDED(hr) );
if (!bExpanded) {
// create the child nodes, then expand them
for (int n = 0; n < m_cchildren; n++)
{
BOOL childDeleteStatus = children[n]->getDeletedStatus();
// If the child is deleted by the user do not insert it.
if ( !childDeleteStatus)
{
ZeroMemory(&rdi, sizeof(RESULTDATAITEM) );
rdi.mask = RDI_STR | // Displayname is valid
RDI_IMAGE |
RDI_PARAM; // nImage is valid
rdi.nImage = children[n]->GetBitmapIndex();
rdi.str = MMC_CALLBACK;
rdi.nCol = 0;
rdi.lParam = (LPARAM)children[n];
hr = pResultData->InsertItem( &rdi );
_ASSERT( SUCCEEDED(hr) );
}
}
}
pHeaderCtrl->Release();
pResultData->Release();
}
return hr;
}
HRESULT CSpaceVehicle::OnAddMenuItems(IContextMenuCallback *pContextMenuCallback, long *pInsertionsAllowed)
{
HRESULT hr = S_OK;
CONTEXTMENUITEM menuItemsNew[] =
{
{
L"New future vehicle", L"Add a new future vehicle",
IDM_NEW_SPACE, CCM_INSERTIONPOINTID_PRIMARY_NEW, 0, CCM_SPECIAL_DEFAULT_ITEM
},
{ NULL, NULL, 0, 0, 0 }
};
// Loop through and add each of the menu items, we
// want to add to new menu, so see if it is allowed.
if (*pInsertionsAllowed & CCM_INSERTIONALLOWED_NEW)
{
for (LPCONTEXTMENUITEM m = menuItemsNew; m->strName; m++)
{
hr = pContextMenuCallback->AddItem(m);
if (FAILED(hr))
break;
}
}
return hr;
}
HRESULT CSpaceVehicle::OnMenuCommand(IConsole *pConsole, IConsoleNameSpace *pConsoleNameSpace, long lCommandID, IDataObject *pDataObject)
{
switch (lCommandID)
{
case IDM_NEW_SPACE:
if (m_cchildren < MAX_NUMBER_OF_CHILDREN)
{ //create new Rocket
children[m_cchildren] = new CRocket(_T("Rocket"), m_cchildren+1, 500000, 265, 75000, this);
pConsole->MessageBox(L"Created a new future vehicle", L"Menu Command", MB_OK|MB_ICONINFORMATION, NULL);
m_cchildren++;
// We created a new object in result pane. We need to insert this object
// in all the views, call UpdateAllViews for this.
// Pass pointer to data object passed into OnMenuCommand.
HRESULT hr;
hr = pConsole->UpdateAllViews(pDataObject, m_hParentHScopeItem, UPDATE_SCOPEITEM);
_ASSERT( S_OK == hr);
}
else
pConsole->MessageBox(L"No more future vehicles allowed", L"Menu Command", MB_OK|MB_ICONWARNING, NULL);
break;
}
return S_OK;
}
//==============================================================
//
// CRocket implementation
//
//
CRocket::CRocket(_TCHAR *szName, int id, LONG lWeight, LONG lHeight, LONG lPayload, CSpaceVehicle *pParent)
: szName(NULL), lWeight(0), lHeight(0), lPayload(0), iStatus(STOPPED), m_pParent(pParent)
{
if (szName) {
this->szName = new _TCHAR[(_tcslen(szName) + 1) * sizeof(_TCHAR)];
_tcscpy(this->szName, szName);
}
this->nId = id;
this->lWeight = lWeight;
this->lHeight = lHeight;
this->lPayload = lPayload;
m_ppHandle = 0;
isDeleted = FALSE;
}
CRocket::~CRocket()
{
if (szName)
delete [] szName;
}
const _TCHAR *CRocket::GetDisplayName(int nCol)
{
static _TCHAR buf[128];
switch (nCol) {
case 0:
_stprintf(buf, _T("%s (#%d)"), szName ? szName : _T(""), nId);
break;
case 1:
_stprintf(buf, _T("%ld metric tons"), lWeight);
break;
case 2:
_stprintf(buf, _T("%ld meters"), lHeight);
break;
case 3:
_stprintf(buf, _T("%ld kilos"), lPayload);
break;
case 4:
_stprintf(buf, _T("%s"),
iStatus == RUNNING ? _T("running") :
iStatus == PAUSED ? _T("paused") :
iStatus == STOPPED ? _T("stopped") : _T("unknown"));
break;
}
return buf;
}
HRESULT CRocket::OnRename(LPOLESTR pszNewName)
{
HRESULT hr = S_FALSE;
if (szName)
{
delete [] szName;
szName = NULL;
}
MAKE_TSTRPTR_FROMWIDE(ptrname, pszNewName);
szName = new _TCHAR[(_tcslen(ptrname) + 1) * sizeof(_TCHAR)];
_tcscpy(szName, ptrname);
return hr;
}
// handle anything special when the user clicks Apply or Ok
// on the property sheet. This sample directly accesses the
// operated-on object, so there's nothing special to do...
// ...except to update all views
HRESULT CRocket::OnPropertyChange(IConsole *pConsole, CComponent *pComponent)
{
HRESULT hr = S_FALSE;
//Call IConsole::UpdateAllViews to redraw the item
//in all views. We need a data object because of the
//way UpdateAllViews is implemented, and because
//MMCN_PROPERTY_CHANGE doesn't give us one
LPDATAOBJECT pDataObject;
hr = pComponent->QueryDataObject((MMC_COOKIE)this, CCT_RESULT, &pDataObject );
_ASSERT( S_OK == hr);
hr = pConsole->UpdateAllViews(pDataObject, nId, UPDATE_RESULTITEM);
_ASSERT( S_OK == hr);
pDataObject->Release();
return hr;
}
HRESULT CRocket::OnSelect(CComponent *pComponent, IConsole *pConsole, BOOL bScope, BOOL bSelect)
{
// enable rename, refresh, and delete verbs
IConsoleVerb *pConsoleVerb;
HRESULT hr = pConsole->QueryConsoleVerb(&pConsoleVerb);
_ASSERT(SUCCEEDED(hr));
hr = pConsoleVerb->SetVerbState(MMC_VERB_RENAME, ENABLED, TRUE);
hr = pConsoleVerb->SetVerbState(MMC_VERB_REFRESH, ENABLED, TRUE);
hr = pConsoleVerb->SetVerbState(MMC_VERB_DELETE, ENABLED, TRUE);
// can't get to properties (via the standard methods) unless
// we tell MMC to display the Properties menu item and
// toolbar button, this will give the user a visual cue that
// there's "something" to do
hr = pConsoleVerb->SetVerbState(MMC_VERB_PROPERTIES, ENABLED, TRUE);
//also set MMC_VERB_PROPERTIES as the default verb
hr = pConsoleVerb->SetDefaultVerb(MMC_VERB_PROPERTIES);
pConsoleVerb->Release();
// now set toolbar button states
if (bSelect) {
switch (iStatus)
{
case RUNNING:
pComponent->getToolbar()->SetButtonState(ID_BUTTONSTART, BUTTONPRESSED, TRUE);
pComponent->getToolbar()->SetButtonState(ID_BUTTONSTART, ENABLED, FALSE);
pComponent->getToolbar()->SetButtonState(ID_BUTTONPAUSE, BUTTONPRESSED, FALSE);
pComponent->getToolbar()->SetButtonState(ID_BUTTONPAUSE, ENABLED, TRUE);
pComponent->getToolbar()->SetButtonState(ID_BUTTONSTOP, BUTTONPRESSED, FALSE);
pComponent->getToolbar()->SetButtonState(ID_BUTTONSTOP, ENABLED, TRUE);
break;
case PAUSED:
pComponent->getToolbar()->SetButtonState(ID_BUTTONSTART, BUTTONPRESSED, FALSE);
pComponent->getToolbar()->SetButtonState(ID_BUTTONSTART, ENABLED, TRUE);
pComponent->getToolbar()->SetButtonState(ID_BUTTONPAUSE, BUTTONPRESSED, TRUE);
pComponent->getToolbar()->SetButtonState(ID_BUTTONPAUSE, ENABLED, FALSE);
pComponent->getToolbar()->SetButtonState(ID_BUTTONSTOP, BUTTONPRESSED, FALSE);
pComponent->getToolbar()->SetButtonState(ID_BUTTONSTOP, ENABLED, TRUE);
break;
case STOPPED:
pComponent->getToolbar()->SetButtonState(ID_BUTTONSTART, BUTTONPRESSED, FALSE);
pComponent->getToolbar()->SetButtonState(ID_BUTTONSTART, ENABLED, TRUE);
pComponent->getToolbar()->SetButtonState(ID_BUTTONPAUSE, BUTTONPRESSED, FALSE);
pComponent->getToolbar()->SetButtonState(ID_BUTTONPAUSE, ENABLED, TRUE);
pComponent->getToolbar()->SetButtonState(ID_BUTTONSTOP, BUTTONPRESSED, TRUE);
pComponent->getToolbar()->SetButtonState(ID_BUTTONSTOP, ENABLED, FALSE);
break;
}
}
return S_OK;
}
// Implement the dialog proc
BOOL CALLBACK CRocket::DialogProc(
HWND hwndDlg, // handle to dialog box
UINT uMsg, // message
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
)
{
static CRocket *pRocket = NULL;
switch (uMsg) {
case WM_INITDIALOG:
// catch the "this" pointer so we can actually operate on the object
pRocket = reinterpret_cast<CRocket *>(reinterpret_cast<PROPSHEETPAGE *>(lParam)->lParam);
SetDlgItemText(hwndDlg, IDC_ROCKET_NAME, pRocket->szName);
SetDlgItemInt(hwndDlg, IDC_ROCKET_HEIGHT, pRocket->lHeight, FALSE);
SetDlgItemInt(hwndDlg, IDC_ROCKET_WEIGHT, pRocket->lWeight, FALSE);
SetDlgItemInt(hwndDlg, IDC_ROCKET_PAYLOAD, pRocket->lPayload, FALSE);
_ASSERT( CB_ERR != SendDlgItemMessage(hwndDlg, IDC_ROCKET_STATUS, CB_INSERTSTRING, 0, (LPARAM)_T("Running")) );
_ASSERT( CB_ERR != SendDlgItemMessage(hwndDlg, IDC_ROCKET_STATUS, CB_INSERTSTRING, 1, (LPARAM)_T("Paused")) );
_ASSERT( CB_ERR != SendDlgItemMessage(hwndDlg, IDC_ROCKET_STATUS, CB_INSERTSTRING, 2, (LPARAM)_T("Stopped")) );
SendDlgItemMessage(hwndDlg, IDC_ROCKET_STATUS, CB_SETCURSEL, (WPARAM)pRocket->iStatus, 0);
break;
case WM_COMMAND:
// turn the Apply button on
if (HIWORD(wParam) == EN_CHANGE ||
HIWORD(wParam) == CBN_SELCHANGE)
SendMessage(GetParent(hwndDlg), PSM_CHANGED, (WPARAM)hwndDlg, 0);
break;
case WM_DESTROY:
// tell MMC that we're done with the property sheet (we got this
// handle in CreatePropertyPages
MMCFreeNotifyHandle(pRocket->m_ppHandle);
break;
case WM_NOTIFY:
switch (((NMHDR *) lParam)->code) {
case PSN_APPLY:
// update the information
if (pRocket->szName) {
delete [] pRocket->szName;
pRocket->szName = NULL;
}
{
int n = SendDlgItemMessage(hwndDlg, IDC_ROCKET_NAME, WM_GETTEXTLENGTH, 0, 0);
if (n != 0) {
pRocket->szName = new _TCHAR[n + 1];
GetDlgItemText(hwndDlg, IDC_ROCKET_NAME, pRocket->szName, n + 1);
}
}
pRocket->lHeight = GetDlgItemInt(hwndDlg, IDC_ROCKET_HEIGHT, NULL, FALSE);
pRocket->lWeight = GetDlgItemInt(hwndDlg, IDC_ROCKET_WEIGHT, NULL, FALSE);
pRocket->lPayload = GetDlgItemInt(hwndDlg, IDC_ROCKET_PAYLOAD, NULL, FALSE);
pRocket->iStatus = (ROCKET_STATUS)SendDlgItemMessage(hwndDlg, IDC_ROCKET_STATUS, CB_GETCURSEL, 0, 0);
// ask MMC to send us a message (on the main thread) so
// we know the Apply button was clicked.
HRESULT hr = MMCPropertyChangeNotify(pRocket->m_ppHandle, (long)pRocket);
_ASSERT(SUCCEEDED(hr));
return PSNRET_NOERROR;
}
break;
}
return DefWindowProc(hwndDlg, uMsg, wParam, lParam);
}
HRESULT CRocket::HasPropertySheets()
{
// say "yes" when MMC asks if we have pages
return S_OK;
}
HRESULT CRocket::CreatePropertyPages(IPropertySheetCallback *lpProvider, LONG_PTR handle)
{
PROPSHEETPAGE psp;
HPROPSHEETPAGE hPage = NULL;
// cache this handle so we can call MMCPropertyChangeNotify
m_ppHandle = handle;
// create the property page for this node.
// NOTE: if your node has multiple pages, put the following
// in a loop and create multiple pages calling
// lpProvider->AddPage() for each page.
psp.dwSize = sizeof(PROPSHEETPAGE);
psp.dwFlags = PSP_DEFAULT | PSP_USETITLE | PSP_USEICONID;
psp.hInstance = g_hinst;
psp.pszTemplate = MAKEINTRESOURCE(IDD_PROPPAGE_LARGE);
psp.pfnDlgProc = DialogProc;
psp.lParam = reinterpret_cast<LPARAM>(this);
psp.pszTitle = MAKEINTRESOURCE(IDS_PST_ROCKET);
psp.pszIcon = MAKEINTRESOURCE(IDI_PSI_ROCKET);
hPage = CreatePropertySheetPage(&psp);
_ASSERT(hPage);
return lpProvider->AddPage(hPage);
}
HRESULT CRocket::GetWatermarks(HBITMAP *lphWatermark,
HBITMAP *lphHeader,
HPALETTE *lphPalette,
BOOL *bStretch)
{
return S_FALSE;
}
HRESULT CRocket::OnSetToolbar(IControlbar *pControlbar, IToolbar *pToolbar, BOOL bScope, BOOL bSelect)
{
HRESULT hr = S_OK;
if (bSelect) {
// Always make sure the menuButton is attached
hr = pControlbar->Attach(TOOLBAR, pToolbar);
} else {
// Always make sure the toolbar is detached
hr = pControlbar->Detach(pToolbar);
}
return hr;
}
HRESULT CRocket::OnToolbarCommand(IConsole *pConsole, MMC_CONSOLE_VERB verb, IDataObject *pDataObject)
{
_TCHAR szVehicle[128];
static _TCHAR buf[128];
_stprintf(buf, _T("%s (#%d)"), szName ? szName : _T(""), nId);
switch (verb)
{
case ID_BUTTONSTART:
iStatus = RUNNING;
break;
case ID_BUTTONPAUSE:
iStatus = PAUSED;
break;
case ID_BUTTONSTOP:
iStatus = STOPPED;
break;
}
wsprintf(szVehicle, _T("%s has been %s"), buf,
(long)verb == ID_BUTTONSTART ? _T("started") :
(long)verb == ID_BUTTONPAUSE ? _T("paused") :
(long)verb == ID_BUTTONSTOP ? _T("stopped") : _T("!!!unknown command!!!"));
int ret = 0;
MAKE_WIDEPTR_FROMTSTR_ALLOC(wszVehicle, szVehicle);
pConsole->MessageBox(wszVehicle,
L"Vehicle command", MB_OK | MB_ICONINFORMATION, &ret);
// Now call IConsole::UpdateAllViews to redraw the item in all views
HRESULT hr;
hr = pConsole->UpdateAllViews(pDataObject, nId, UPDATE_RESULTITEM);
_ASSERT( S_OK == hr);
return S_OK;
}
HRESULT CRocket::OnUpdateItem(IConsole *pConsole, long item, ITEM_TYPE itemtype)
{
HRESULT hr = S_FALSE;
_ASSERT(NULL != this || isDeleted || RESULT == itemtype);
//redraw the item
IResultData *pResultData = NULL;
hr = pConsole->QueryInterface(IID_IResultData, (void **)&pResultData);
_ASSERT( SUCCEEDED(hr) );
HRESULTITEM myhresultitem;
_ASSERT(NULL != &myhresultitem);
//lparam == this. See CSpaceStation::OnShow
hr = pResultData->FindItemByLParam( (LPARAM)this, &myhresultitem );
if ( FAILED(hr) )
{
// Failed : Reason may be that current view does not have this item.
// So exit gracefully.
hr = S_FALSE;
} else
{
hr = pResultData->UpdateItem( myhresultitem );
_ASSERT( SUCCEEDED(hr) );
}
pResultData->Release();
return hr;
}
HRESULT CRocket::OnRefresh(IConsole *pConsole)
{
//Call IConsole::UpdateAllViews to redraw all views
//owned by the parent scope item
IDataObject *dummy = NULL;
HRESULT hr;
hr = pConsole->UpdateAllViews(dummy, m_pParent->GetParentScopeItem(), UPDATE_SCOPEITEM);
_ASSERT( S_OK == hr);
return hr;
}
HRESULT CRocket::OnDelete(IConsole *pConsoleComp)
{
HRESULT hr;
//Delete the item
IResultData *pResultData = NULL;
hr = pConsoleComp->QueryInterface(IID_IResultData, (void **)&pResultData);
_ASSERT( SUCCEEDED(hr) );
HRESULTITEM myhresultitem;
//lparam == this. See CSpaceVehicle::OnShow
hr = pResultData->FindItemByLParam( (LPARAM)this, &myhresultitem );
if ( FAILED(hr) )
{
// Failed : Reason may be that current view does not have this item.
// So exit gracefully.
hr = S_FALSE;
} else
{
hr = pResultData->DeleteItem( myhresultitem, 0 );
_ASSERT( SUCCEEDED(hr) );
}
pResultData->Release();
//Now set isDeleted member so that the parent doesn't try to
//to insert it again in CSpaceVehicle::OnShow. Admittedly, a hack...
isDeleted = TRUE;
return hr;
}
|
b92eee816919f72c17684f4536150dfeba29e856 | 1ec086253005570c211cf55fe74c8886b2c483ef | /TKDGTT/Tuan 4/BT4.Nhom4/Bai 2/Bai 2.1/LietKeHoanViCua(n)PhanTu.cpp | e00e917b611f7f20cedf844cc072ec217814c232 | [] | no_license | Du0ngkylan/C-Cpp | 8be2fc9632bb1c49b0eaac6166f9ead5deac4c83 | 37d973d510bafc5512fce2f2a81b0a4aa746b2e3 | refs/heads/master | 2021-06-26T05:58:17.969765 | 2020-11-27T03:52:06 | 2020-11-27T03:52:06 | 172,220,624 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 769 | cpp | LietKeHoanViCua(n)PhanTu.cpp | //liet ke cac hoan vi cua n phan tu
#include"stdio.h"
#include"conio.h"
void in(int *a,int n)
{
int i;
for(i=1;i<=n;i++)
printf("%d\t",a[i]);
printf("\n");
}
void Try(int i,int *a,int *b,int n)
{
int j;
for(j=1;j<=n;j++)
{
if(b[j]==0)
{
b[j]=1;
a[i]=j;
if(i==n)
in(a,n);
else
Try(i+1,a,b,n);
b[j]=0;
}
}
}
void khoitao(int *a,int n)
{
int i;
for(i=1; i<=n;i++)
a[i]=0;
}
int main()
{
int n;
printf("nhap n=");
scanf("%d",&n);
int a[n],b[n];
khoitao(b,n);
Try(1,a,b,n);
getch();
return 0;
}
|
072e173d883a77b6447572cc84657d7fe7a6ef93 | c2b9b0ed5ad1527d6f880af5be7b23e58c68fff9 | /src/mlcommon/include/cachemanager/cachemanager.h | 094568eeee0fccd73960f62e4da3e6ad83d752cf | [] | no_license | magland/mountainview | 12954648745582b17346b09fd05a0cde0d0624cb | 67915d015327113b432e17427fe313c7a664d835 | refs/heads/master | 2021-01-23T16:55:48.331479 | 2017-09-07T14:53:43 | 2017-09-07T14:53:43 | 102,751,319 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,346 | h | cachemanager.h | /******************************************************
** See the accompanying README and LICENSE files
** Author(s): Jeremy Magland
** Created: 4/5/2016
*******************************************************/
#ifndef CACHEMANAGER_H
#define CACHEMANAGER_H
#include <QString>
#include <QVariant>
class CacheManagerPrivate;
class CacheManager {
public:
enum Duration {
ShortTerm,
LongTerm
};
friend class CacheManagerPrivate;
CacheManager();
virtual ~CacheManager();
void setLocalBasePath(const QString& path);
void setIntermediateFileFolder(const QString& folder);
//QString makeRemoteFile(const QString& mlproxy_url, const QString& file_name = "", Duration duration = ShortTerm);
QString makeLocalFile(const QString& file_name = "", Duration duration = ShortTerm);
QString makeIntermediateFile(const QString& file_name = "");
QString localTempPath();
void setTemporaryFileDuration(QString path, qint64 duration_sec);
void setTemporaryFileExpirePid(QString path, qint64 pid);
QString makeExpiringFile(QString file_name, qint64 duration_sec);
void removeExpiredFiles();
void cleanUp();
static CacheManager* globalInstance();
//private slots:
// void slot_remove_on_delete();
private:
CacheManagerPrivate* d;
};
#endif // CACHEMANAGER_H
|
f23627521fb770e55cb598a6cee0f78c0941050b | c8b3ac26583960332f5668eb0b51d028e8b69306 | /VVP/№3/А в 15(3.7).cpp | 03554d58dab071986be1f25a5b011c75af44a57f | [] | no_license | Tw0nky/Laboratory-work | 0e01fa853cbbb67b868fc67c7e2456e404b7ed93 | be2033cf72ebdfb8cdc4f728613429fdca4c8be3 | refs/heads/master | 2020-09-30T02:57:54.309661 | 2020-01-17T08:10:21 | 2020-01-17T08:10:21 | 227,185,383 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 230 | cpp | А в 15(3.7).cpp | #include <iostream>
#include <cmath>
using namespace std;
int main()
{
setlocale(0, "");
int a, n, b;
cout << "Введите число А: ";
cin >> a;
b = a * a;
n = b * a * a * a * pow(a, 10);
cout << n;
return 0;
} |
fbc7782f2f6ec4831663c087d01c42581a9dadbb | 31db2bbc3f598ddc90c30b33eeba0dfe58ea892f | /test/fold_left_test.hpp | 3028065b52fcd38fe9b353756e8cbabb5ae521e3 | [] | no_license | Corristo/tmp | 3ebeb5f6af70433a66fcb2ee290ae157bb02d34d | 5d5a0008663f5a1c6e3c19d66f6b09c97ecf239d | refs/heads/master | 2020-07-28T09:24:17.085162 | 2018-06-18T16:34:49 | 2018-06-18T16:34:49 | 209,379,308 | 0 | 0 | null | 2019-09-18T18:38:07 | 2019-09-18T18:38:07 | null | UTF-8 | C++ | false | false | 286 | hpp | fold_left_test.hpp | #include "../include/boost/tmp/algorithm/fold_left.hpp"
namespace fold_left_test {
using namespace boost::tmp;
template<typename T, typename U>
using intify = int;
int run() {
int lhs = call_<fold_left_<lift_<intify>>,bool,char>{};
return 0;
}
}
|
ec9e447b6441edaede1ceeda0eb93415a548788f | 86c1a486e011bff80d79bd2be6065d79f7558da9 | /Spline.h | aee35fec67fcddda8c0cb55b0babf03765ef9493 | [] | no_license | meabefir/regex | ece634c1ea45d7ee34720e12d6780f32733deccb | 492246e1540c856fb7b7df3a81c6fb66c4d76394 | refs/heads/master | 2023-04-04T04:31:03.440978 | 2021-04-22T06:58:18 | 2021-04-22T06:58:18 | 359,185,682 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 898 | h | Spline.h | #pragma once
#include "State.h"
#include "ArrowTip.h"
class Node;
class Transition;
class Spline
{
protected:
sf::Vector2f p0;
sf::Vector2f p1;
sf::Vector2f p2;
sf::Vector2f p3;
sf::Color defaultColor;
sf::Color highlightColor;
Transition* transition;
sf::Text* textRender;
int visibleCharacters;
bool textLimit = false;
int precision;
float step;
Node* from;
Node* to;
float absDist;
float offset;
float offsetScale;
float minOffset;
sf::VertexArray vertexArray;
ArrowTip tip;
public:
Spline(Transition* transition, Node*, Node*, sf::Text*);
virtual ~Spline();
virtual void updateAnchorPoints();
virtual void updateSplinePoints();
virtual void udpateTextPos(bool = true);
virtual void setVertexColor(sf::Color);
virtual sf::Vector2f getSplinePoint(float x);
virtual void draw(sf::RenderTarget*);
};
|
1599850616b9dcd4a75bd0c645542a9c4b747a41 | 69f9f78195e88270ed08ef8c5f4e9fdae17aa74d | /Book Allocation Problem.cpp | dda524da05de64aeaea06f5ccbc76637df56d7f7 | [] | no_license | Tarunverma504/cb_cpp | 45a03787b4f5b41aff6840bb4ba3d24c308a936c | 9c187b414409da8a40d3c80d162e9dcd07613cfc | refs/heads/main | 2023-08-21T10:51:23.422802 | 2021-10-09T10:50:15 | 2021-10-09T10:50:15 | 388,343,542 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,632 | cpp | Book Allocation Problem.cpp | /*
You are given number of pages in n different books and m students. The books are arranged in ascending order of number of pages. Every student is assigned to read some consecutive books. The task is to assign books in such a way that the maximum number of pages assigned to a student is minimum.
Input Format
First line contains integer t as number of test cases. Next t lines contains two lines. For each test case, 1st line contains two integers n and m which represents the number of books and students and 2nd line contains n space separated integers which represents the number of pages of n books in ascending order.
Constraints
1 < t < 50
1< n < 100
1< m <= 50
1 <= Ai <= 1000
Output Format
Print the maximum number of pages that can be assigned to students.
Sample Input
1
4 2
12 34 67 90
Sample Output
113
Explanation
1st students : 12 , 34, 67 (total = 113)
2nd students : 90 (total = 90)
Print max(113, 90)
*/
#include<iostream>
using namespace std;
bool isValid(int *arr,int n,int student,int capability ){
int pages=0;
for(int i=0;i<n;i++){
if(pages+arr[i]>capability){
pages=arr[i];
student--;
if(student<=0){
return false;
}
}
else{
pages+=arr[i];
}
}
return true;
}
int main() {
int t;
cin>>t;
while(t>0){
int n, m;
cin>>n>>m;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
int total_pages=0;
for(int i=0;i<n;i++)
total_pages+=arr[i];
int l=arr[n-1];
int r=total_pages;
int ans=-1;
while(l<=r){
int mid=(l+r)/2;
if(isValid(arr,n,m,mid)){
ans=mid;
r=mid-1;
}
else{
l=mid+1;
}
}
cout<<ans<<endl;
t--;
}
return 0;
}
|
047bf8f121c05c599bf58a01c0dd545454270e57 | 58e21d7a9f4fbaeac9cf0828c888fbdcadd10f97 | /s2e/tools/lib/BinaryReaders/TextModule.cpp | 0cb44aa579f0e5fddf914a269cf95c80806bebd2 | [] | no_license | yongjianchn/s2e-print-linux | ef74caa5ebe8114904f00ce319bad6577592eb2a | 42988a112c68c74bceb73bc9a2dd2bda7941e69b | refs/heads/master | 2020-04-15T16:04:05.419331 | 2013-07-09T08:23:07 | 2013-07-09T08:23:07 | 8,900,667 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,788 | cpp | TextModule.cpp | /*
* S2E Selective Symbolic Execution Framework
*
* Copyright (c) 2010, Dependable Systems Laboratory, EPFL
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Dependable Systems Laboratory, EPFL nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE DEPENDABLE SYSTEMS LABORATORY, EPFL BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Currently maintained by:
* Vitaly Chipounov <vitaly.chipounov@epfl.ch>
* Volodymyr Kuznetsov <vova.kuznetsov@epfl.ch>
*
* All contributors are listed in S2E-AUTHORS file.
*
*/
#include "TextModule.h"
#include <stdio.h>
#include <sstream>
#include <cassert>
namespace s2etools {
TextModule::TextModule(const std::string &fileName):ExecutableFile(fileName)
{
m_inited = false;
m_imageBase = 0;
m_imageSize = 0;
}
TextModule::~TextModule()
{
}
bool TextModule::initialize()
{
if (m_inited) {
return true;
}
if (!parseTextDescription(m_fileName + ".fcn")) {
return false;
}
m_inited = true;
return true;
}
bool TextModule::getInfo(uint64_t addr, std::string &source, uint64_t &line, std::string &function)
{
AddressRange ar;
ar.start = addr;
ar.end = addr + 1;
RangeToNameMap::const_iterator it = m_ObjectNames.find(ar);
if (it == m_ObjectNames.end()) {
return false;
}
function = (*it).second;
return true;
}
bool TextModule::inited() const
{
return m_inited;
}
bool TextModule::getModuleName(std::string &name) const
{
if (!m_inited) {
return false;
}
name = m_imageName;
return true;
}
uint64_t TextModule::getImageBase() const
{
return m_imageBase;
}
uint64_t TextModule::getImageSize() const
{
return m_imageSize;
}
bool TextModule::processTextDescHeader(const char *str)
{
if (str[0] != '#') {
return false;
}
std::istringstream is(str);
std::string type;
is >> type;
if (type == "#ImageBase") {
uint64_t base;
char c;
//Skip "0x" prefix
is >> c >> c >> std::hex >> base;
if (base) {
m_imageBase = base;
}
}else if (type == "#ImageName") {
std::string s;
is >> s;
m_imageName = s;
}else if (type == "#ImageSize") {
uint64_t size;
char c;
//Skip "0x" prefix
is >> c >> c >> std::hex >> size;
if (size) {
m_imageSize = size;
}
}
return true;
}
bool TextModule::parseTextDescription(const std::string &fileName)
{
FILE *f = fopen(fileName.c_str(), "r");
if (!f) {
return false;
}
while(!feof(f)) {
char buffer[1024];
std::string fcnName;
uint64_t start, end;
if (fgets(buffer, sizeof(buffer), f) != buffer){
break;
}
if (processTextDescHeader(buffer)) {
continue;
}
std::istringstream is(buffer);
char c;
is >> c >> c >> std::hex >> start >> c >> c >>
end;
is >> std::noskipws >> c;
while(is >> c) {
if (c=='\r' || c=='\n') {
break;
}
fcnName+=c;
}
//sscanf(buffer, "0x%"PRIx64" 0x%"PRIx64" %[^\n]s\n", &start, &end, fcnName);
AddressRange ar(start, end);
m_ObjectNames[ar] = fcnName;
m_Functions.insert(std::make_pair(fcnName, ar));
}
fclose(f);
return true;
}
}
|
95870fc4398486316abfb93dbe4454289e89205b | 1990adcbb3422a5416bcc9d10c9ffaca9f4e74aa | /Final_Fantasy_Mystery_World/Final_Fantasy_Mystery_World/e1Mage.h | 0996dc75e6c04e6da819253cb1f92cd602c99a51 | [
"MIT"
] | permissive | Nadine044/Final-Fantasy-Mystery-World | de1263a1262f6b15a988ae7b3eca00bbb5bd1407 | cf0eed03bbd6478c4fdd1eb074f48a2ceb78e0d6 | refs/heads/master | 2020-09-13T13:11:29.760160 | 2019-06-11T07:40:28 | 2019-06-11T07:40:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 429 | h | e1Mage.h | #ifndef _E1MAGE_H_
#define _E1MAGE_H_
#include "e1Particles.h"
#include "e1Player.h"
class e1Mage : public e1Player {
public:
e1Mage(const int &x, const int &y);
virtual ~e1Mage();
bool CleanUp();
void PrepareSpecialAttack1();
void SpecialAttack1();
void IdAnimToEnum();
void UpdateLevel();
void SetAbility1TilesPos();
private:
void SetFireBalls();
public:
e1Particles * fire_ball = nullptr;
};
#endif |
6b1b9ebecafe93d59b7cc60904e74cd6f5b88337 | ede423141fa816e2ad0d43d4a1a9fd91333e6a74 | /week2/day-1/21.cpp | ae601df1551b2cec067aec56369ddd542c253761 | [] | no_license | greenfox-zerda-sparta/nagyzsuska | a5dc1cfdb445cdba97bd664cdbc3bd5f77070ddc | 17bec1e7b244b77564945ce53afc16a222db84c4 | refs/heads/master | 2021-01-12T18:15:02.458312 | 2017-01-07T07:27:42 | 2017-01-07T07:27:42 | 71,350,927 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 578 | cpp | 21.cpp | //============================================================================
// Name : 21.cpp
// Author : Zsuzsanna Nagy
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <string>
using namespace std;
int main() {
int ab = 123;
int credits = 100;
bool is_bonus = true;
if ((credits >= 50)&& (!is_bonus)){
ab-=2;
} else if ((credits < 50)&& (!is_bonus)){
ab-=1;
}
cout << ab;
return 0;
}
|
46b6a94353462341711084c848c1454d82fe2b0d | 178528d48c951b58bc41f67ec7c145a6fb679fa2 | /lib/stokesys_cell_contact.cc | 9d06284b0b42dd93be50ceb16428bec3a51991ec | [] | no_license | WhiteTshirtXI/bem3d_ves_tube | aecca3d06d6ad82385f8c915fde56c1e301d1927 | fbbf0ec0afcc62f17e117cca62463562953f166d | refs/heads/master | 2021-01-22T05:51:03.726087 | 2015-09-04T04:15:40 | 2015-09-04T04:15:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,283 | cc | stokesys_cell_contact.cc | #include "cxxheaders.h"
#include "stokesys.h"
#include "ewald.h"
#include "mblas.h"
#include "param.h"
#include "geom_oper.h"
#include "debugfunc.h"
/* StokeSys::cellNoContact
* updateCldInfo */
namespace {
// collision information
// Use a link-list to store collision info for the same mesh point
struct Cld {
int ivert;
double dist, nrml[3];
Cld() : ivert(-1), dist(FLT_MAX)
{
nrml[0] = nrml[1] = nrml[2] = 0.0;
}
};
// Compare two collision
bool CldCmp(const Cld &c1, const Cld &c2) {
return ( (c1.ivert < c2.ivert) ||
(c1.ivert == c2.ivert && c1.dist < c2.dist) );
}
void updateCldInfo(NbrList &nlist, double DIST_EPS,
MArray<int,1> &pcld, vector<Cld> &clds);
};
/* Update collision information
* Arguments:
* nlist -- the neighborlist
* DIST_EPS -- threshhold distance
* pcld -- clds[pcld[i]] stores the collision info of the i-th point
* clds -- collisions */
void updateCldInfo(NbrList &nlist, double DIST_EPS, MArray<int,1> &pcld, vector<Cld> &clds)
{
for (int foo1 = 0; foo1 < nlist.verts.size(); foo1++) {
Point &vert = *nlist.verts[foo1];
int ivert = vert.Gindx;
double min_dist = FLT_MAX;
double min_nrml[3];
for (int foo2 = nlist.firstNbr[foo1]; foo2 < nlist.firstNbr[foo1+1]; foo2++) {
// Find the accurate distance to the face
Tri &face = *nlist.faces[foo2];
// exclude mesh self-contact
if (vert.mesh != NULL && vert.mesh == face.mesh) continue;
if (nlist.dists[foo2] > DIST_EPS || nlist.dists[foo2] > min_dist) continue;
double xi[3];
m_dcopy(3, vert.x, xi);
ewald::to_CloseBy(face.xc, xi);
double xtri[3][3];
for (int l = 0 ; l < 3; l++) m_dcopy(3, face.vert[l]->x, xtri[l]);
double rr, s0, t0;
rr = minDistToTri(xi, xtri, s0, t0);
// Update minimum separation and outward normal directions
if (rr < min_dist) {
min_dist = rr;
FOR_D3 {
double xtmp = (1.0-s0-t0)*xtri[0][d] + s0*xtri[1][d] + t0*xtri[2][d];
min_nrml[d] = xi[d] - xtmp;
}
normalizeVec3D(min_nrml);
}
} // foo2
if (min_dist > DIST_EPS) continue;
// Update collision list
int p = pcld(ivert);
if (p >= 0) {
Cld &cld = clds[p];
if (min_dist < cld.dist) {
cld.dist = min_dist;
FOR_I3 cld.nrml[i] = min_nrml[i];
}
}
else {
Cld newcld;
newcld.ivert = ivert;
newcld.dist = min_dist;
FOR_D3 newcld.nrml[d] = min_nrml[d];
clds.push_back(newcld);
pcld(ivert) = clds.size() - 1;
}
} // ivert
}
/* Prevent cells from contacting each other
* Arguments:
* DIST_EPS -- distance thresh hold */
void StokeSys::cellNoContact(double DIST_EPS)
{
int mpi_rank, mpi_size;
MPI_Comm_size(MPI_COMM_WORLD, &mpi_size);
MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);
// Get local collision information
int nvert = vertList[CELL].size();
vector<Cld> myclds;
MArray<int,1> pcld(nvert);
pcld = -1;
if (ewald::phys::active) {
::updateCldInfo(nlist_phys[CELL][CELL], DIST_EPS, pcld, myclds);
::updateCldInfo(nlist_phys[CELL][RIGID], DIST_EPS, pcld, myclds);
::updateCldInfo(nlist_phys[CELL][WALL], DIST_EPS, pcld, myclds);
}
// root collect all collision information
int nsend = myclds.size();
int *nrecv = new int[mpi_size];
int *displs = new int[mpi_size+1];
MPI_Gather(&nsend, 1, MPI_INT, nrecv, 1, MPI_INT, 0, MPI_COMM_WORLD);
displs[0] = 0;
for (int i = 1; i <= mpi_size; i++) {
displs[i] = displs[i-1] + nrecv[i-1];
}
Cld *sendbuf = new Cld[nsend];
std::copy(myclds.begin(), myclds.end(), sendbuf);
Cld *recvbuf = NULL;
if (mpi_rank == 0) recvbuf = new Cld[displs[mpi_size]];
MPI_Datatype MPI_CLD;
MPI_Type_contiguous(sizeof(Cld), MPI_CHAR, &MPI_CLD);
MPI_Type_commit(&MPI_CLD);
MPI_Gatherv(sendbuf, nsend, MPI_CLD,
recvbuf, nrecv, displs, MPI_CLD,
0, MPI_COMM_WORLD);
MPI_Type_free(&MPI_CLD);
double (*dx)[3] = new double[nvert][3];
m_dclear(3*nvert, *dx);
if (mpi_rank == 0) {
// First sort the collision information
std::sort(recvbuf, recvbuf+displs[mpi_size], CldCmp);
double dist_min = FLT_MAX;
int cnt = 0;
int last_ivert = -1;
for (int foo = 0; foo < displs[mpi_size]; foo++) {
Cld &cld = recvbuf[foo];
int ivert = cld.ivert;
// Each point is moved only once using the smallest separation
if (ivert == last_ivert) {
continue;
}
else {
cnt++;
last_ivert = ivert;
}
double ds = DIST_EPS - cld.dist;
FOR_J3 dx[ivert][j] = ds*cld.nrml[j];
dist_min = std::min(dist_min, cld.dist);
}
if (cnt > 0) {
printf(" cell-cell min sep = %.2E", dist_min);
printf(" %d mesh points moved\n", cnt);
}
}
MPI_Bcast(*dx, 3*nvert, MPI_DOUBLE, 0, MPI_COMM_WORLD);
for (int i = 0; i < nvert; i++) {
Point *vert = vertList[CELL][i];
m_dadd(3, dx[i], vert->x);
}
delete [] nrecv;
delete [] displs;
delete [] sendbuf;
delete [] recvbuf;
delete [] dx;
}
/* Check whether a point lies within a cell
* Argument:
* x0 -- the coordinate of the point
* whichCell -- index of the cell that the point penetrates
* Algorithm:
* -- If a point is outside a cell, the total spherical angle is 0 */
bool StokeSys::pointInsideSomeCell(const double *x0, int *whichCell)
{
bool is_interior = false;
if (whichCell) *whichCell = -1;
for (int icell = 0; icell < numCells(); icell++) {
Vesicle &cell = cells[icell];
double xtmp[3];
FOR_I3 xtmp[i] = x0[i];
ewald::to_CloseBy(cell.center, xtmp);
double xmin[3], xmax[3];
cell.getCoordRange(xmin, xmax);
if ( xtmp[0] < xmin[0] || xtmp[0] > xmax[0]
|| xtmp[1] < xmin[1] || xtmp[1] > xmax[1]
|| xtmp[2] < xmin[2] || xtmp[2] > xmax[2] ) continue;
double sangle = 0.0;
for (int iface = 0; iface < cell.numFaces(); iface++) {
Tri &face = cell.faces[iface];
double xtri[3][3];
FOR_I3 FOR_J3 xtri[i][j] = face.vert[i]->x[j];
sangle += tri_solidAngle(xtmp, xtri);
}
if (fabs(sangle) > 1.E-2) {
is_interior = true;
if (whichCell) *whichCell = icell;
break;
}
} // icell
return is_interior;
}
|
16b4241a04abca04936f5cca6e0a8b9a8614b399 | 1fa348cd4f70204f1c2dce87303761f731db857f | /Minecraft/src/render/Texture.h | 445b9cfcbc3729aeb1c288b2f5989bf84b29b3e4 | [] | no_license | kiroma/mcpp | a04ae67be6d9adcd796c9a5644b42f6c0b9b7b2e | 9ee1535f563e69996d5c2311d4d60a74cf1f911a | refs/heads/master | 2020-08-06T17:25:12.335428 | 2019-10-06T17:53:15 | 2019-10-06T17:53:15 | 213,091,948 | 0 | 0 | null | 2019-10-06T01:06:17 | 2019-10-06T01:06:16 | null | UTF-8 | C++ | false | false | 504 | h | Texture.h | #ifndef MINECRAFT_TEXTURE_H
#define MINECRAFT_TEXTURE_H
class Texture
{
public:
Texture(const char *filename);
~Texture();
unsigned int GetID() const
{ return id; }
int GetWidth() const
{ return width; }
int GetHeight() const
{ return height; }
int GetSize() const
{ return width > height ? width : height; }
int GetChannelCount() const
{ return channels; }
private:
int width, height, channels;
unsigned int id;
};
#endif //MINECRAFT_TEXTURE_H
|
2de8ff546b79bddb99e466ddbcfe3443e2b00b07 | db405e374ea25c3a630c41e8ac66b6609b4b8f6a | /player.cpp | 6a808a0771a08f9aa6d61364ab0448757a50847e | [] | no_license | handsomeTowne/mariopants11src | 06b966bf8b5a12eff3314541c684ce4234424628 | d5ee2deb9244167bbf74fbe8914514a98c94cb8d | refs/heads/master | 2020-03-18T21:10:23.892217 | 2018-05-29T08:17:22 | 2018-05-29T08:17:22 | 135,263,800 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,631 | cpp | player.cpp | // player.cpp
// audio generator for Song
#include <cstdlib> // NULL
#include <cmath> // pow
#include "player.h"
#include "data.h"
#include "os.h"
static unsigned int samplerate;
static bool playing;
static int beat; // current beat
static int next_beat; // samples to next beat
static int beat_length; // samples per beat
static const Song* song;
uint32 tuning; // tuning adjustment for samplerate
// mutex
struct AudioLock
{
AudioLock() { os::lock_audio(true); }
~AudioLock() { os::lock_audio(false); }
};
// mixing
struct Sampler
{
static const unsigned int FADE_POWER = 10; // 1024 sample fade to reduce clicks
static const unsigned int FADE_LEN = 1 << FADE_POWER;
// The fade is implemented to hide a "click" when a playing note is interrupted.
// On the SNES, samples were ADPCM, so an interrupted note would continue on
// as deltas from the interrupted position, possibly causing distortion in the
// attack, but obviating the click problem. This implementation is simply PCM
// samples, so the short fade covers the click normally inherent in an abrupt
// end of sample.
uint32 pos0; // 16:16 fixed point, primary sound
uint32 pos1; // 16:16 fixed point, fading sound
const sint16* sample0;
const sint16* sample1;
uint32 sample_len0;
uint32 sample_len1;
uint32 fade;
void play(unsigned char note, unsigned char inst)
{
// begin fade of previous sample
fade = FADE_LEN;
pos1 = pos0;
sample1 = sample0;
sample_len1 = sample_len0;
int si = (inst * 13) + (note - 1);
pos0 = 0;
sample0 = sampledata[si].d;
sample_len0 = sampledata[si].len;
}
void stop()
{
sample0 = NULL; // halt sample
sample1 = NULL;
}
inline signed int render()
{
if (sample0 == NULL) return 0; // sampler disabled
// calculate playback position
uint32 high_pos = pos0 >> 16;
if (high_pos >= sample_len0) // silence if sample is finished
{
sample0 = NULL;
return 0;
}
signed int output = sample0[high_pos]; // gather output sample
pos0 += tuning; // advance sample for next iteration
if (sample1 != NULL) // fading old sample to remove pop
{
high_pos = pos1 >> 16;
if (high_pos < sample_len1)
{
output += (sample1[high_pos] * fade) >> FADE_POWER;
pos1 += tuning;
--fade;
if (fade < 1) sample1 = NULL;
}
else sample1 = NULL;
}
return output;
}
};
const unsigned int CHANNEL_POWER = 2;
const unsigned int CHANNELS = 1 << CHANNEL_POWER;
Sampler sampler[CHANNELS];
void start_sample(unsigned int channel, unsigned char note, unsigned char inst)
{
sampler[channel].play(note,inst);
}
inline signed int mix()
{
signed int output = 0;
for (int i=0; i < CHANNELS; ++i)
output += sampler[i].render();
return output >> CHANNEL_POWER;
}
// internal play functions
void play_beat()
{
if (!playing) return;
for (int i=0; i<3; ++i)
{
unsigned char note = song->notes[(beat*6)+(i*2)+0];
unsigned char inst = song->notes[(beat*6)+(i*2)+1];
if (note >=1 && note <= 0x0D && inst <= 0x0E)
start_sample(i,note,inst);
}
++beat;
if (beat >= song->length)
{
if (song->loop) beat = 0;
else player::stop_song();
}
}
void update_tempo()
{
// samples per beat, based on lengths measured empirically,
// and then presuming tempo in mario paint is
// implemented as a 14 + the song->tempo added
// to an accumulater each frame that triggers a beat on overflow
double beat_samples = (690892.8 / double(14 + song->tempo));
beat_length = int(double(samplerate) * beat_samples / 32000.0);
}
// public interface
namespace player
{
void setup(const Song* song_)
{
set_samplerate(32000); // default samplerate
playing = false;
beat = 0;
next_beat = 0;
song = song_;
silence();
}
void set_samplerate(unsigned int sr)
{
AudioLock audio_lock;
samplerate = sr;
tuning = uint32(65536.0 * 32000.0 / double(sr)); // 16 bit fixed point adjustment
}
void silence()
{
AudioLock audio_lock;
for (int i=0; i < CHANNELS; ++i)
sampler[i].stop();
}
void apply_tempo()
{
AudioLock audio_lock;
update_tempo();
}
void set_beat(int beat_)
{
AudioLock audio_lock;
if (beat_ < 0 ) beat_ = 0;
if (beat_ >= song->length) beat_ = song->length;
beat = beat_;
}
void play_song()
{
AudioLock audio_lock;
if (song == NULL) return;
silence();
update_tempo();
playing = true;
beat = 0;
next_beat = 0;
}
void stop_song()
{
AudioLock audio_lock;
playing = false;
}
void play_note_immediate(unsigned char note, unsigned char inst)
{
AudioLock audio_lock;
start_sample(3,note,inst);
}
void play_beat_immediate(int b)
{
AudioLock audio_lock;
if (b < 0 || b >= song->length) return;
for (int i=0; i<3; ++i)
{
unsigned char note = song->notes[(b*6)+(i*2)+0];
unsigned char inst = song->notes[(b*6)+(i*2)+1];
if (note >=1 && note <= 0x0D && inst <= 0x0E)
start_sample(i,note,inst);
}
}
void render(sint16* buffer, int len)
{
// AudioLock audio_lock; render() is already called from a thread that has lock
if (!playing)
{
while(len)
{
*buffer = mix();
++buffer;
--len;
}
return;
}
while(len)
{
if (next_beat < len) // advance to beat if it occurs during len
{
while (next_beat > 0)
{
*buffer = mix();
++buffer;
--len;
--next_beat;
}
}
else // otherwise finish render to end off len
{
next_beat -= len;
while (len)
{
*buffer = mix();
++buffer;
--len;
}
return;
}
// time to play a beat
while (next_beat <= 0)
{
play_beat();
next_beat += beat_length;
}
}
}
unsigned int get_beat_length()
{
AudioLock audio_lock;
return beat_length;
}
} // namespace player
// end of file
|
6359c75d5a01bb9f75696add381bdbef99d7a228 | 925c241ffa16d5b7766f6814f1824695988a2f99 | /afficheur4_7seg/afficheur4_7seg.ino | a67097263bb95b08ae018b2332b3acb3959f6cbf | [
"Apache-2.0"
] | permissive | pihito/Arduino | 9359ec88f3487041d06424e7ec9536303d642054 | a8aff1e986a1046e837240a8d36de89cc09097fd | refs/heads/master | 2021-01-18T23:21:23.867528 | 2018-05-28T15:22:01 | 2018-05-28T15:22:01 | 29,911,697 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,180 | ino | afficheur4_7seg.ino |
/**
4 7segment vith 595 controler
-------------------------------
The MIT License (MIT)
Copyright (c) 2015 ArtOfCode
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-------------------------------
**/
// A
// F B
// G
// E C
// D DP
//FE = seg A
//FD = seg B
//FB = seg C
//F7 = seg D
//EF = seg E
//DF = seg F
//BF = seg G
//7F = seg DP
#define SEG_A 0xFE
#define SEG_B 0xFD
#define SEG_C 0xFB
#define SEG_D 0xF7
#define SEG_E 0xEF
#define SEG_F 0xDF
#define SEG_G 0xBF
#define SEG_DP = 0x7F
#define LED4 0x01
#define LED3 0x02
#define LED2 0x04
#define LED1 0x08
unsigned char LED_OFFSET[] = {LED1, LED2, LED3, LED4};
unsigned char LED_MATRICE[] =
{
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// 0 1 2 3 4 5 6 7 8 9 A b C d E F - L blank
0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90,0x88,0x83,0xC6,0xA1,0x86,0x8E,0xbf,0xC7, 0xFF
};
int SCLK = 3;
int RCLK = 4;
int DIO = 2;
void setup ()
{
pinMode(SCLK,OUTPUT);
pinMode(RCLK,OUTPUT);
pinMode(DIO,OUTPUT);
}
void loop()
{
unsigned char seg[] = {LED_MATRICE[18],LED_MATRICE[18],LED_MATRICE[18],LED_MATRICE[18]};
seg[0] = LED_MATRICE[2];
seg[1] = LED_MATRICE[9];
seg[2] = LED_MATRICE[9];
seg[3] = LED_MATRICE[18];
display(seg);
}
//ecris le tableau de 4 led sur la sortie
void display(unsigned char *led4)
{
for( int i = 0; i <=4 ; i++)
{
LED_OUT(led4[i]);
LED_OUT(LED_OFFSET[i]);
pulse(RCLK);
}
}
//Ecrit un afficheur
void LED_OUT(unsigned char X)
{
unsigned char i;
for(i=0;i<8;i++)
{
//on test le bit du haut pour voir si il est à 1 ou à 0
if (X&0x80)
{
digitalWrite(DIO,HIGH);
}
else
{
digitalWrite(DIO,LOW);
}
//on décale pour écrire le prochain bit
//(on injecte des 1 car 0 envoie low et c'est une cathode commune donc low pour allumer )
X<<=1;
pulse(SCLK);
}
}
//envoie une pulsation sur la pin SCLK / RCLK
void pulse(int pin)
{
digitalWrite(pin,LOW);
digitalWrite(pin,HIGH);
}
|
d80cffb9329ad9430d96a3e8ceed4bfe7e436aae | 2786c37ab338ed279aa2a535d9a8143aa2e82b57 | /libs/foe_graphics/libs/imgui/src/builtin_descriptor_sets.cpp | 95e4d01c693559782e7f851728f5d5edbb4dfa24 | [
"Apache-2.0",
"MIT"
] | permissive | StableCoder/foe-engine | 12cdcc226bb5d1941adb72b53f8fc159ed7533c6 | b494fad60a36f0b11c526a5648277643edd4095f | refs/heads/main | 2023-08-21T18:30:50.777210 | 2023-08-21T00:33:05 | 2023-08-21T00:33:05 | 307,215,754 | 16 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 586 | cpp | builtin_descriptor_sets.cpp | // Copyright (C) 2022-2023 George Cave.
//
// SPDX-License-Identifier: Apache-2.0
#include <foe/graphics/imgui/builtin_descriptor_sets.hpp>
#include <imgui.h>
void imgui_foeBuiltinDescriptorSetLayoutFlags(std::string const &label,
foeBuiltinDescriptorSetLayoutFlags const &data) {
char const *pLayoutStr =
builtin_set_layout_to_string((foeBuiltinDescriptorSetLayoutFlagBits)data);
if (pLayoutStr != NULL)
ImGui::Text("%s: %s", label.c_str(), pLayoutStr);
else
ImGui::Text("%s: N/A", label.c_str());
} |
fe2cebfe607ce6fded67bd9602d45d99ba5c1615 | 00abe2d53d67fe7eea24c9a7277d4d11e47ba7d5 | /repos/plywood/src/reflect/ply-reflect/TypeConverter.h | 1c4ca9f366f2da41ba4ea4221d29cd40709ed33b | [
"MIT"
] | permissive | arc80/plywood | 807e250ef321ed7560f57bf4a1eafe6ab383924a | 1face511f012c3c84a1b893e810fcc70a43f6b6d | refs/heads/main | 2023-09-02T04:01:25.216707 | 2022-10-12T15:26:41 | 2022-10-12T15:26:41 | 266,890,685 | 792 | 58 | MIT | 2023-05-22T16:12:54 | 2020-05-25T22:16:19 | C++ | UTF-8 | C++ | false | false | 629 | h | TypeConverter.h | /*------------------------------------
///\ Plywood C++ Framework
\\\/ https://plywood.arc80.com/
------------------------------------*/
#pragma once
#include <ply-reflect/Core.h>
#include <ply-reflect/TypeDescriptor.h>
namespace ply {
// void writeTypeSignature(BinaryBuffer& sig, const TypeDescriptor* typeDesc); disabled for now
void createConversionRecipe(OutStream* outs, const TypeDescriptor_Struct* dstStruct,
const ArrayView<TypeDescriptor_Struct*>& srcStructs);
void applyConversionRecipe(const BlockList::Footer* recipe, void* dstPtr, ArrayView<void*> srcPtrs);
} // namespace ply
|
40ad8fec91a91f31b8e0e4f31d17e3e388a8de2c | 08e29ebab8df03fdfe605b4d67231888a05bdbaf | /cpp/src/shape/shape.cpp | 9c9e4eac64eaae871cb5f06d69678010d0da1477 | [] | no_license | shellyShlomi/RD102 | f7118b63552a6078f145dd603c382e4870cde4a4 | efb8f4f3606219c0a880732e270c658dc3c70eba | refs/heads/master | 2023-08-21T03:45:15.352633 | 2021-10-10T06:37:04 | 2021-10-10T06:37:04 | 416,762,242 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,575 | cpp | shape.cpp | // Developer: Shelly Shlomi
// Status: Approved
// Reviewer: Eden .W.
// Group: RD102
// date: 24.8.21
// description: Implementation of Shape library
#include <iostream> // cout
#include <list> // list
#include "shapes.hpp"
static const int SPACE(1);
namespace ilrd
{
/**************************** Shapes interface impl ****************************/
void PrintShapes(const std::list<Shape *> &shape_list)
{
for (std::list<Shape *>::const_iterator it = shape_list.begin();
it != shape_list.end(); ++it)
{
(*it)->Move(SPACE);
}
std::cout << std::endl;
return;
}
Shape::~Shape()
{
//empty
}
void Shape::Move(size_t offset)
{
while (offset)
{
std::cout << ' ';
--offset;
}
Draw();
return;
}
/********************************* Circle impl *********************************/
Circle::Circle()
{
//empty
}
Circle::~Circle()
{
//empty
}
void Circle::Draw() const
{
std::cout << "Circle";
return;
}
/******************************* Rectangle impl *******************************/
Rectangle::Rectangle()
{
//empty
}
Rectangle::~Rectangle()
{
//empty
}
void Rectangle::Draw() const
{
std::cout << "Rectangle" ;
return;
}
/********************************** Line impl **********************************/
Line::Line()
{
//empty
}
Line::~Line()
{
//empty
}
void Line::Draw() const
{
std::cout << "Line";
return;
}
/********************************* Square impl *********************************/
Square::Square()
{
//empty
}
Square::~Square()
{
//empty
}
void Square::Draw() const
{
std::cout << "Square";
return;
}
} |
86d366d127d79738f00a55d4d93a500097485bae | 712e2c48c07f3343cd307b9ee06b1e5f4aab3f1b | /plugins/meminfo/MeminfoSaxParser.h | e79d4b4ee226da8394d46cf755eb64d7f267f4e2 | [
"BSD-3-Clause"
] | permissive | liororama/gossimon | 02f1b3284f450457f878628ca41334a61f285ea3 | 5d0d266677153c7d0f330438c8ee4942a98ae4e4 | refs/heads/master | 2020-05-20T06:49:29.390899 | 2014-01-02T06:15:12 | 2014-01-02T06:15:12 | 2,347,339 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,200 | h | MeminfoSaxParser.h | /*
* File: TopXMLParser.h
* Author: lior
*
* Created on November 28, 2011, 1:40 PM
*/
#ifndef TOPXMLPARSER_H
#define TOPXMLPARSER_H
#include <string>
#include <vector>
#include <Meminfo.h>
#include <libxml++/libxml++.h>
class MeminfoSaxParser : public xmlpp::SaxParser
{
public:
MeminfoSaxParser();
virtual ~MeminfoSaxParser();
bool parse(std::string str, Meminfo &mi);
protected:
//overrides:
virtual void on_start_document();
virtual void on_end_document();
virtual void on_start_element(const Glib::ustring& name,
const AttributeList& properties);
virtual void on_end_element(const Glib::ustring& name);
virtual void on_characters(const Glib::ustring& characters);
virtual void on_comment(const Glib::ustring& text);
virtual void on_warning(const Glib::ustring& text);
virtual void on_error(const Glib::ustring& text);
virtual void on_fatal_error(const Glib::ustring& text);
private:
int _mlog_id;
std::string _err_msg;
bool _in_meminfo_entry;
std::string _curr_value_string;
Meminfo _meminfo;
};
#endif /* TOPXMLPARSER_H */
|
5bf36daa3189a2188f9b4d2522902997d34ced63 | 21466370f83deecbeb2174b5969413ed007309a4 | /UnitTests/MockDataFactory.cc | f3f3672d69a465b37b5dcb5221a95d4e5aed9bc6 | [
"Apache-2.0"
] | permissive | quantmatt/nitrade-trading-cplusplus | 2511b55022f71836e86c047ffbb04161df2c41c3 | 89b99502dc686bec15ff08de16ce0b3df0b36636 | refs/heads/dev | 2020-05-19T17:39:40.801039 | 2019-05-29T03:34:45 | 2019-05-29T03:34:45 | 185,138,773 | 3 | 2 | Apache-2.0 | 2019-06-03T05:53:14 | 2019-05-06T06:44:08 | C++ | UTF-8 | C++ | false | false | 577 | cc | MockDataFactory.cc | #pragma once
#include "gmock/gmock.h" // Brings in Google Mock. - installed from nuget
#include "NitradeLib.h"
using namespace Nitrade;
using namespace std;
class MockDataFactory : public IDataFactory {
public:
// Inherited via IDataFactory
MOCK_METHOD1(getAssetData, unique_ptr<IAssetData>(Strategy* strategy));
MOCK_METHOD1(getBinaryChunkReader, unique_ptr<IBinaryChunkReader>(const string dataPath));
MOCK_METHOD2(getStrategySet, unique_ptr<IStrategySet>(Strategy* strategyDefinition, IAsset* asset));
MOCK_METHOD0(getTradeManager, unique_ptr<ITradeManager>());
}; |
a4160cd237716a82388a93daba98a880cd87ef0e | 1b034f4b496cceea10e3cf9c9909d771ccbbc516 | /localFlotador/1411AGenoma.cpp | 98082a0bdf9a589368d91c7e19546e58f2964e05 | [] | no_license | kailIII/acm-5 | 44b977377e9efb03180efceadc011f849cd6b381 | cc52aaa1a4334e117f13cc1064b1db134e75034d | refs/heads/master | 2021-01-22T11:15:55.667094 | 2015-02-24T22:13:09 | 2015-02-24T22:13:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,305 | cpp | 1411AGenoma.cpp | /*
* =====================================================================================
*
* Filename: 1411AGenoma.cpp
*
* Description:
*
* Version: 1.0
* Created: 11/10/13 17:26:19
* Revision: none
* Compiler: gcc
*
* Author: YOUR NAME (),
* Organization:
*
* =====================================================================================
*/
#include <iostream>
using namespace std;
int main()
{
int numberOfProblems, numberOfCreatures;
cin>>numberOfProblems;
string alienGeneSet, terrestrialGeneSet;
int marsNumber;
int contador = 1;
while(contador<=numberOfProblems)
{
cout<<"Case "<<contador<<endl;
cin>>alienGeneSet>>numberOfCreatures;
int terrestrialLength, alienLength;
while(numberOfCreatures>0)
{
cin>>terrestrialGeneSet;
marsNumber = 0;
terrestrialLength = terrestrialGeneSet.length();
alienLength = alienGeneSet.length();
for(int i = 0; i<(alienLength-terrestrialLength+1); i++)
{
if(alienGeneSet.substr(i,terrestrialLength) == terrestrialGeneSet)
{
marsNumber++;
}
}
if(marsNumber!=0)
{
cout<<marsNumber<<endl;
}else
{
cout<<"Darwin was right about this creature"<<endl;
}
numberOfCreatures--;
}
contador++;
}
}
|
0c5d79d25311707dd35506b6dc021a8967a786b1 | ee1423adcd4bfeb2703464996171d103542bad09 | /dali-toolkit/automated-tests/dali-test-suite/focus-manager/utc-Dali-FocusManager.cpp | 4ec250de1ff396c483f8f1f70593c589a268df39 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-flora-1.1"
] | permissive | sak0909/Dali | 26ac61a521ab1de26a7156c51afd3cc839cb705a | 0b383fc316b8b57afcf9a9e8bac6e24a4ba36e49 | refs/heads/master | 2020-12-30T12:10:51.930311 | 2017-05-16T21:56:24 | 2017-05-16T21:57:14 | 91,505,804 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 40,710 | cpp | utc-Dali-FocusManager.cpp | //
// Copyright (c) 2014 Samsung Electronics Co., Ltd.
//
// Licensed under the Flora License, Version 1.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://floralicense.org/license/
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an AS IS BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include <iostream>
#include <stdlib.h>
#include <tet_api.h>
#include <dali/dali.h>
#include <dali-toolkit/dali-toolkit.h>
#include <dali-toolkit-test-suite-utils.h>
using namespace Dali;
using namespace Toolkit;
namespace
{
static bool gObjectCreatedCallBackCalled;
static void TestCallback(BaseHandle handle)
{
gObjectCreatedCallBackCalled = true;
}
// Functors to test whether focus changed signal is emitted when the focus is changed
class FocusChangedCallback : public Dali::ConnectionTracker
{
public:
FocusChangedCallback(bool& signalReceived)
: mSignalVerified(signalReceived),
mOriginalFocusedActor(),
mCurrentFocusedActor()
{
}
void Callback(Actor originalFocusedActor, Actor currentFocusedActor)
{
tet_infoline("Verifying FocusChangedCallback()");
if(originalFocusedActor == mCurrentFocusedActor)
{
mSignalVerified = true;
}
mOriginalFocusedActor = originalFocusedActor;
mCurrentFocusedActor = currentFocusedActor;
}
void Reset()
{
mSignalVerified = false;
}
bool& mSignalVerified;
Actor mOriginalFocusedActor;
Actor mCurrentFocusedActor;
};
// Functors to test whether focus overshot signal is emitted when there is no way to move focus further.
class FocusOvershotCallback : public Dali::ConnectionTracker
{
public:
FocusOvershotCallback(bool& signalReceived)
: mSignalVerified(signalReceived),
mCurrentFocusedActor(),
mFocusOvershotDirection(Toolkit::FocusManager::OVERSHOT_NEXT)
{
}
void Callback(Actor currentFocusedActor, Toolkit::FocusManager::FocusOvershotDirection direction)
{
tet_infoline("Verifying FocusOvershotCallback()");
if(currentFocusedActor == mCurrentFocusedActor && direction == mFocusOvershotDirection)
{
mSignalVerified = true;
}
}
void Reset()
{
mSignalVerified = false;
}
bool& mSignalVerified;
Actor mCurrentFocusedActor;
Toolkit::FocusManager::FocusOvershotDirection mFocusOvershotDirection;
};
} // namespace
static void Startup();
static void Cleanup();
extern "C" {
void (*tet_startup)() = Startup;
void (*tet_cleanup)() = Cleanup;
}
enum {
POSITIVE_TC_IDX = 0x01,
NEGATIVE_TC_IDX,
};
#define MAX_NUMBER_OF_TESTS 10000
extern "C" {
struct tet_testlist tet_testlist[MAX_NUMBER_OF_TESTS];
}
// Add test functionality for all APIs in the class (Positive and Negative)
TEST_FUNCTION( UtcDaliFocusManagerGet, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliFocusManagerSetAndGetAccessibilityAttribute, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliFocusManagerSetAndGetFocusOrder, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliFocusManagerGenerateNewFocusOrder, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliFocusManagerGetActorByFocusOrder, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliFocusManagerSetAndGetCurrentFocusActor, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliFocusManagerGetCurrentFocusGroup, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliFocusManagerGetCurrentFocusOrder, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliFocusManagerMoveFocusForward, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliFocusManagerMoveFocusBackward, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliFocusManagerClearFocus, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliFocusManagerReset, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliFocusManagerFocusGroup, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliFocusManagerSetAndGetFocusIndicator, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliFocusManagerSignalFocusChanged, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliFocusManagerSignalFocusOvershot, POSITIVE_TC_IDX );
// Called only once before first test is run.
static void Startup()
{
}
// Called only once after last test is run
static void Cleanup()
{
}
static void UtcDaliFocusManagerGet()
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliFocusManagerGet");
FocusManager manager;
//Ensure object is created by checking if it's registered
ObjectRegistry registry = Stage::GetCurrent().GetObjectRegistry();
DALI_TEST_CHECK(registry);
gObjectCreatedCallBackCalled = false;
registry.ObjectCreatedSignal().Connect( &TestCallback );
{
manager = FocusManager::Get();
DALI_TEST_CHECK(manager);
}
DALI_TEST_CHECK( gObjectCreatedCallBackCalled );
FocusManager newManager = FocusManager::Get();
DALI_TEST_CHECK(newManager);
// Check that focus manager is a singleton
DALI_TEST_CHECK(manager == newManager);
}
static void UtcDaliFocusManagerSetAndGetAccessibilityAttribute()
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliFocusManagerSetAndGetAccessibilityAttribute");
FocusManager manager = FocusManager::Get();
DALI_TEST_CHECK(manager);
Actor actor = Actor::New();
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(actor, FocusManager::ACCESSIBILITY_LABEL) == "");
manager.SetAccessibilityAttribute(actor, FocusManager::ACCESSIBILITY_LABEL, "Description");
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(actor, FocusManager::ACCESSIBILITY_LABEL) == "Description");
manager.SetAccessibilityAttribute(actor, FocusManager::ACCESSIBILITY_LABEL, "New description");
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(actor, FocusManager::ACCESSIBILITY_LABEL) == "New description");
}
static void UtcDaliFocusManagerSetAndGetFocusOrder()
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliFocusManagerSetAndGetFocusOrder");
FocusManager manager = FocusManager::Get();
DALI_TEST_CHECK(manager);
Actor first = Actor::New();
Actor second = Actor::New();
DALI_TEST_CHECK(manager.GetFocusOrder(first) == 0);
DALI_TEST_CHECK(manager.GetFocusOrder(second) == 0);
// Set the focus order and description for the first actor
manager.SetFocusOrder(first, 1);
manager.SetAccessibilityAttribute(first, FocusManager::ACCESSIBILITY_LABEL, "first");
DALI_TEST_CHECK(manager.GetFocusOrder(first) == 1);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(first, FocusManager::ACCESSIBILITY_LABEL) == "first");
// Set the focus order and description for the second actor
manager.SetFocusOrder(second, 2);
manager.SetAccessibilityAttribute(second, FocusManager::ACCESSIBILITY_LABEL, "second");
DALI_TEST_CHECK(manager.GetFocusOrder(second) == 2);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(second, FocusManager::ACCESSIBILITY_LABEL) == "second");
// check that the focus order of the first actor is changed
manager.SetFocusOrder(first, 2);
DALI_TEST_CHECK(manager.GetFocusOrder(first) == 2);
// make sure the change of focus order doesn't affect the actor's description
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(first, FocusManager::ACCESSIBILITY_LABEL) == "first");
// check that the focus order of the second actor is increased to 3
DALI_TEST_CHECK(manager.GetFocusOrder(second) == 3);
// make sure the change of focus order doesn't affect the actor's description
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(second, FocusManager::ACCESSIBILITY_LABEL) == "second");
// check that the focus order of the second actor is changed to 1
manager.SetFocusOrder(second, 1);
DALI_TEST_CHECK(manager.GetFocusOrder(second) == 1);
// make sure the change of focus order doesn't affect the actor's description
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(second, FocusManager::ACCESSIBILITY_LABEL) == "second");
// Set the focus order and description for the third actor
Actor third = Actor::New();
manager.SetFocusOrder(third, 1);
manager.SetAccessibilityAttribute(third, FocusManager::ACCESSIBILITY_LABEL, "third");
DALI_TEST_CHECK(manager.GetFocusOrder(third) == 1);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(third, FocusManager::ACCESSIBILITY_LABEL) == "third");
// check that the focus order of the second actor is increased to 2.
DALI_TEST_CHECK(manager.GetFocusOrder(second) == 2);
// make sure the change of focus order doesn't affect the actor's description
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(second, FocusManager::ACCESSIBILITY_LABEL) == "second");
// check that the focus order of the first actor is increased to 3.
DALI_TEST_CHECK(manager.GetFocusOrder(first) == 3);
// make sure the change of focus order doesn't affect the actor's description
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(first, FocusManager::ACCESSIBILITY_LABEL) == "first");
}
static void UtcDaliFocusManagerGenerateNewFocusOrder()
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliFocusManagerGenerateNewFocusOrder");
FocusManager manager = FocusManager::Get();
DALI_TEST_CHECK(manager);
DALI_TEST_CHECK(1 == manager.GenerateNewFocusOrder());
DALI_TEST_CHECK(1 == manager.GenerateNewFocusOrder());
Actor first = Actor::New();
Actor second = Actor::New();
// Set the focus order for the first actor
manager.SetFocusOrder(first, 1);
manager.SetAccessibilityAttribute(first, FocusManager::ACCESSIBILITY_LABEL, "first");
DALI_TEST_CHECK(manager.GetFocusOrder(first) == 1);
//Test for new focus order
DALI_TEST_CHECK(2 == manager.GenerateNewFocusOrder());
// Set the focus order for the first actor
manager.SetFocusOrder(second, 2);
manager.SetAccessibilityAttribute(second, FocusManager::ACCESSIBILITY_LABEL, "first");
DALI_TEST_CHECK(manager.GetFocusOrder(second) == 2);
}
static void UtcDaliFocusManagerGetActorByFocusOrder()
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliFocusManagerGetActorByFocusOrder");
FocusManager manager = FocusManager::Get();
DALI_TEST_CHECK(manager);
// Create the actors and set their focus orders
Actor first = Actor::New();
manager.SetFocusOrder(first, 1);
Actor second = Actor::New();
manager.SetFocusOrder(second, 2);
Actor third = Actor::New();
manager.SetFocusOrder(third, 3);
// Check that we get an empty handle as no actor is added to the stage yet.
DALI_TEST_CHECK(manager.GetActorByFocusOrder(1) == Actor());
DALI_TEST_CHECK(manager.GetActorByFocusOrder(2) == Actor());
DALI_TEST_CHECK(manager.GetActorByFocusOrder(3) == Actor());
// Add the actors to the stage
Stage::GetCurrent().Add(first);
Stage::GetCurrent().Add(second);
Stage::GetCurrent().Add(third);
// Check that we get an empty handle because focus order 0 means undefined.
DALI_TEST_CHECK(manager.GetActorByFocusOrder(0) == Actor());
// Check that we get correct actors for the specified focus orders
DALI_TEST_CHECK(manager.GetActorByFocusOrder(1) == first);
DALI_TEST_CHECK(manager.GetActorByFocusOrder(2) == second);
DALI_TEST_CHECK(manager.GetActorByFocusOrder(3) == third);
// Change the focus order of the third actor to 1
manager.SetFocusOrder(third, 1);
// Check that we still get correct actors after changing their focus orders
DALI_TEST_CHECK(manager.GetActorByFocusOrder(1) == third);
DALI_TEST_CHECK(manager.GetActorByFocusOrder(2) == first);
DALI_TEST_CHECK(manager.GetActorByFocusOrder(3) == second);
// Check that we get an empty handle because no actor has a focus order of 4
DALI_TEST_CHECK(manager.GetActorByFocusOrder(4) == Actor());
}
static void UtcDaliFocusManagerSetAndGetCurrentFocusActor()
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliFocusManagerSetAndGetCurrentFocusActor");
FocusManager manager = FocusManager::Get();
DALI_TEST_CHECK(manager);
// Create the first actor and add it to the stage
Actor first = Actor::New();
manager.SetFocusOrder(first, 1);
Stage::GetCurrent().Add(first);
// Create the second actor and add it to the stage
Actor second = Actor::New();
manager.SetFocusOrder(second, 2);
Stage::GetCurrent().Add(second);
// Create the third actor but don't add it to the stage
Actor third = Actor::New();
manager.SetFocusOrder(third, 3);
// Check that no actor is being focused yet.
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == Actor());
// Check that it will fail to set focus on an invalid actor
DALI_TEST_CHECK(manager.SetCurrentFocusActor(Actor()) == false);
// Check that the focus is set on the first actor
DALI_TEST_CHECK(manager.SetCurrentFocusActor(first) == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == first);
// Check that the focus is set on the second actor
DALI_TEST_CHECK(manager.SetCurrentFocusActor(second) == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == second);
// Check that it will fail to set focus on the third actor as it's not in the stage
DALI_TEST_CHECK(manager.SetCurrentFocusActor(third) == false);
// Add the third actor to the stage
Stage::GetCurrent().Add(third);
// make the third actor invisible
third.SetVisible(false);
// flush the queue and render once
application.SendNotification();
application.Render();
// Check that it will fail to set focus on the third actor as it's invisible
DALI_TEST_CHECK(manager.SetCurrentFocusActor(third) == false);
// Make the third actor visible
third.SetVisible(true);
// flush the queue and render once
application.SendNotification();
application.Render();
// Make the third actor not focusable
Property::Index propertyActorFocusable = third.GetPropertyIndex("focusable");
third.SetProperty(propertyActorFocusable, false);
// flush the queue and render once
application.SendNotification();
application.Render();
// Check that it will fail to set focus on the third actor as it's not focusable
DALI_TEST_CHECK(manager.SetCurrentFocusActor(third) == false);
// Make the third actor focusable
third.SetProperty(propertyActorFocusable, true);
// flush the queue and render once
application.SendNotification();
application.Render();
// Check that the focus is successfully moved to the third actor
DALI_TEST_CHECK(manager.SetCurrentFocusActor(third) == true);
// Make the current focused actor to be not focusable by setting its focus order to be 0
manager.SetFocusOrder(third, 0);
// Check that the focus is automatically cleared
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == Actor());
// Set the focus order of the third actor again
manager.SetFocusOrder(third, 3);
// Check that the third actor can be focused successfully now
DALI_TEST_CHECK(manager.SetCurrentFocusActor(third) == true);
}
static void UtcDaliFocusManagerGetCurrentFocusGroup()
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliFocusManagerGetCurrentFocusGroup");
FocusManager manager = FocusManager::Get();
DALI_TEST_CHECK(manager);
// Create an actor with two child actors and add it to the stage
Actor parent = Actor::New();
Actor firstChild = Actor::New();
Actor secondChild = Actor::New();
parent.Add(firstChild);
parent.Add(secondChild);
Stage::GetCurrent().Add(parent);
// Create three actors and add them as the children of the first child actor
Actor firstGrandChild = Actor::New();
Actor secondGrandChild = Actor::New();
Actor thirdGrandChild = Actor::New();
firstChild.Add(firstGrandChild);
firstChild.Add(secondGrandChild);
firstChild.Add(thirdGrandChild);
// Set focus order to the actors
manager.SetFocusOrder(parent, 1);
manager.SetFocusOrder(firstChild, 2);
manager.SetFocusOrder(firstGrandChild, 3);
manager.SetFocusOrder(secondGrandChild, 4);
manager.SetFocusOrder(thirdGrandChild, 5);
manager.SetFocusOrder(secondChild, 6);
// Set the parent and the first child actor as focus groups
manager.SetFocusGroup(parent, true);
DALI_TEST_CHECK(manager.IsFocusGroup(parent) == true);
// Set focus to the first grand child actor
DALI_TEST_CHECK(manager.SetCurrentFocusActor(firstGrandChild) == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == firstGrandChild);
// The current focus group should be the parent, As it is the immediate parent which is also a focus group.
DALI_TEST_CHECK(manager.GetCurrentFocusGroup() == parent);
manager.SetFocusGroup(firstChild, true);
DALI_TEST_CHECK(manager.IsFocusGroup(firstChild) == true);
// The current focus group should be the firstChild, As it is the immediate parent which is also a focus group.
DALI_TEST_CHECK(manager.GetCurrentFocusGroup() == firstChild);
manager.SetFocusGroup(firstGrandChild, true);
DALI_TEST_CHECK(manager.IsFocusGroup(firstGrandChild) == true);
// The current focus group should be itself, As it is also a focus group.
DALI_TEST_CHECK(manager.GetCurrentFocusGroup() == firstGrandChild);
// Set focus to the second grand child actor
DALI_TEST_CHECK(manager.SetCurrentFocusActor(secondGrandChild) == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == secondGrandChild);
// The current focus group should be the firstChild, As it is the immediate parent which is also a
// focus group for the current focus actor.
DALI_TEST_CHECK(manager.GetCurrentFocusGroup() == firstChild);
}
static void UtcDaliFocusManagerGetCurrentFocusOrder()
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliFocusManagerGetCurrentFocusOrder");
FocusManager manager = FocusManager::Get();
DALI_TEST_CHECK(manager);
Actor first = Actor::New();
Stage::GetCurrent().Add(first);
Actor second = Actor::New();
Stage::GetCurrent().Add(second);
Actor third = Actor::New();
Stage::GetCurrent().Add(third);
// Set the focus order and description for the first actor
manager.SetFocusOrder(first, 1);
manager.SetAccessibilityAttribute(first, FocusManager::ACCESSIBILITY_LABEL, "first");
DALI_TEST_CHECK(manager.GetFocusOrder(first) == 1);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(first, FocusManager::ACCESSIBILITY_LABEL) == "first");
// Set the focus order and description for the second actor
manager.SetFocusOrder(second, 2);
manager.SetAccessibilityAttribute(second, FocusManager::ACCESSIBILITY_LABEL, "second");
DALI_TEST_CHECK(manager.GetFocusOrder(second) == 2);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(second, FocusManager::ACCESSIBILITY_LABEL) == "second");
// Set the focus order and description for the second actor
manager.SetFocusOrder(third, 3);
manager.SetAccessibilityAttribute(third, FocusManager::ACCESSIBILITY_LABEL, "third");
DALI_TEST_CHECK(manager.GetFocusOrder(third) == 3);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(third, FocusManager::ACCESSIBILITY_LABEL) == "third");
// Check that no actor is being focused yet.
DALI_TEST_CHECK(manager.GetCurrentFocusOrder() == 0);
// Set the focus on the first actor and test
DALI_TEST_CHECK(manager.SetCurrentFocusActor(first) == true);
DALI_TEST_CHECK(manager.GetCurrentFocusOrder() == 1);
// Move the focus forward to the second actor and test
manager.MoveFocusForward();
DALI_TEST_CHECK(manager.GetCurrentFocusOrder() == 2);
// Move the focus forward to the third actor and test
manager.MoveFocusForward();
DALI_TEST_CHECK(manager.GetCurrentFocusOrder() == 3);
// Clear focus and test
manager.ClearFocus();
DALI_TEST_CHECK(manager.GetCurrentFocusOrder() == 0);
}
static void UtcDaliFocusManagerMoveFocusForward()
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliFocusManagerMoveFocusForward");
FocusManager manager = FocusManager::Get();
DALI_TEST_CHECK(manager);
Actor first = Actor::New();
Stage::GetCurrent().Add(first);
Actor second = Actor::New();
Stage::GetCurrent().Add(second);
Actor third = Actor::New();
Stage::GetCurrent().Add(third);
// Set the focus order and description for the first actor
manager.SetFocusOrder(first, 1);
manager.SetAccessibilityAttribute(first, FocusManager::ACCESSIBILITY_LABEL, "first");
DALI_TEST_CHECK(manager.GetFocusOrder(first) == 1);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(first, FocusManager::ACCESSIBILITY_LABEL) == "first");
// Set the focus order and description for the second actor
manager.SetFocusOrder(second, 2);
manager.SetAccessibilityAttribute(second, FocusManager::ACCESSIBILITY_LABEL, "second");
DALI_TEST_CHECK(manager.GetFocusOrder(second) == 2);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(second, FocusManager::ACCESSIBILITY_LABEL) == "second");
// Set the focus order and description for the second actor
manager.SetFocusOrder(third, 3);
manager.SetAccessibilityAttribute(third, FocusManager::ACCESSIBILITY_LABEL, "third");
DALI_TEST_CHECK(manager.GetFocusOrder(third) == 3);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(third, FocusManager::ACCESSIBILITY_LABEL) == "third");
// Check that no actor is being focused yet.
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == Actor());
// Set the focus on the first actor
DALI_TEST_CHECK(manager.SetCurrentFocusActor(first) == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == first);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(manager.GetCurrentFocusActor(), FocusManager::ACCESSIBILITY_LABEL) == "first");
// Test the non-wrapped move first
manager.SetWrapMode(false);
DALI_TEST_CHECK(manager.GetWrapMode() == false);
// Move the focus forward to the second actor
manager.MoveFocusForward();
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == second);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(manager.GetCurrentFocusActor(), FocusManager::ACCESSIBILITY_LABEL) == "second");
// Move the focus forward to the third actor
manager.MoveFocusForward();
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == third);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(manager.GetCurrentFocusActor(), FocusManager::ACCESSIBILITY_LABEL) == "third");
// Check that it will fail to move the focus forward again as the third actor is the last
// focusable actor in the focus chain
manager.MoveFocusForward();
// The focus should still be set on the third actor
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == third);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(manager.GetCurrentFocusActor(), FocusManager::ACCESSIBILITY_LABEL) == "third");
// Now test the wrapped move
manager.SetWrapMode(true);
DALI_TEST_CHECK(manager.GetWrapMode() == true);
// Move the focus forward recursively and this time the first actor should be focused
manager.MoveFocusForward();
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == first);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(manager.GetCurrentFocusActor(), FocusManager::ACCESSIBILITY_LABEL) == "first");
// Make the second actor not focusable
Property::Index propertyActorFocusable = second.GetPropertyIndex("focusable");
second.SetProperty(propertyActorFocusable, false);
// flush the queue and render once
application.SendNotification();
application.Render();
// Move the focus forward and check that the second actor should be skipped and
// the third actor should be focused now.
manager.MoveFocusForward();
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == third);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(manager.GetCurrentFocusActor(), FocusManager::ACCESSIBILITY_LABEL) == "third");
// Make the first actor invisible
first.SetVisible(false);
// flush the queue and render once
application.SendNotification();
application.Render();
// Move the focus forward and check that the first actor should be skipped as it's
// invisible and the second actor should also be skipped as it's not focusable,
// so the focus will still be on the third actor
manager.MoveFocusForward();
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == third);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(manager.GetCurrentFocusActor(), FocusManager::ACCESSIBILITY_LABEL) == "third");
// Make the third actor invisible so that no actor can be focused.
third.SetVisible(false);
// flush the queue and render once
application.SendNotification();
application.Render();
// Check that the focus move is failed as all the three actors can not be focused
manager.MoveFocusForward();
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == third);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(manager.GetCurrentFocusActor(), FocusManager::ACCESSIBILITY_LABEL) == "third");
}
static void UtcDaliFocusManagerMoveFocusBackward()
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliFocusManagerMoveFocusBackward");
FocusManager manager = FocusManager::Get();
DALI_TEST_CHECK(manager);
Actor first = Actor::New();
Stage::GetCurrent().Add(first);
Actor second = Actor::New();
Stage::GetCurrent().Add(second);
Actor third = Actor::New();
Stage::GetCurrent().Add(third);
// Set the focus order and description for the first actor
manager.SetFocusOrder(first, 1);
manager.SetAccessibilityAttribute(first, FocusManager::ACCESSIBILITY_LABEL, "first");
DALI_TEST_CHECK(manager.GetFocusOrder(first) == 1);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(first, FocusManager::ACCESSIBILITY_LABEL) == "first");
// Set the focus order and description for the second actor
manager.SetFocusOrder(second, 2);
manager.SetAccessibilityAttribute(second, FocusManager::ACCESSIBILITY_LABEL, "second");
DALI_TEST_CHECK(manager.GetFocusOrder(second) == 2);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(second, FocusManager::ACCESSIBILITY_LABEL) == "second");
// Set the focus order and description for the second actor
manager.SetFocusOrder(third, 3);
manager.SetAccessibilityAttribute(third, FocusManager::ACCESSIBILITY_LABEL, "third");
DALI_TEST_CHECK(manager.GetFocusOrder(third) == 3);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(third, FocusManager::ACCESSIBILITY_LABEL) == "third");
// Check that no actor is being focused yet.
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == Actor());
// Set the focus on the third actor
DALI_TEST_CHECK(manager.SetCurrentFocusActor(third) == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == third);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(manager.GetCurrentFocusActor(), FocusManager::ACCESSIBILITY_LABEL) == "third");
// Test the non-wrapped move first
manager.SetWrapMode(false);
DALI_TEST_CHECK(manager.GetWrapMode() == false);
// Move the focus backward to the second actor
manager.MoveFocusBackward();
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == second);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(manager.GetCurrentFocusActor(), FocusManager::ACCESSIBILITY_LABEL) == "second");
// Move the focus backward to the first actor
manager.MoveFocusBackward();
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == first);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(manager.GetCurrentFocusActor(), FocusManager::ACCESSIBILITY_LABEL) == "first");
// Check that it will fail to move the focus backward again as the first actor is the first
// focusable actor in the focus chain
manager.MoveFocusBackward();
// The focus should still be set on the first actor
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == first);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(manager.GetCurrentFocusActor(), FocusManager::ACCESSIBILITY_LABEL) == "first");
// Now test the wrapped move
manager.SetWrapMode(true);
DALI_TEST_CHECK(manager.GetWrapMode() == true);
// Move the focus backward recursively and this time the third actor should be focused
manager.MoveFocusBackward();
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == third);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(manager.GetCurrentFocusActor(), FocusManager::ACCESSIBILITY_LABEL) == "third");
// Make the second actor not focusable
Property::Index propertyActorFocusable = second.GetPropertyIndex("focusable");
second.SetProperty(propertyActorFocusable, false);
// flush the queue and render once
application.SendNotification();
application.Render();
// Move the focus backward and check that the second actor should be skipped and
// the first actor should be focused now.
manager.MoveFocusBackward();
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == first);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(manager.GetCurrentFocusActor(), FocusManager::ACCESSIBILITY_LABEL) == "first");
// Make the third actor invisible
third.SetVisible(false);
// flush the queue and render once
application.SendNotification();
application.Render();
// Move the focus backward and check that the third actor should be skipped as it's
// invisible and the second actor should also be skipped as it's not focusable,
// so the focus will still be on the first actor
manager.MoveFocusBackward();
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == first);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(manager.GetCurrentFocusActor(), FocusManager::ACCESSIBILITY_LABEL) == "first");
// Make the first actor invisible so that no actor can be focused.
first.SetVisible(false);
// flush the queue and render once
application.SendNotification();
application.Render();
// Check that the focus move is failed as all the three actors can not be focused
manager.MoveFocusBackward();
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == first);
DALI_TEST_CHECK(manager.GetAccessibilityAttribute(manager.GetCurrentFocusActor(), FocusManager::ACCESSIBILITY_LABEL) == "first");
}
static void UtcDaliFocusManagerClearFocus()
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliFocusManagerClearFocus");
FocusManager manager = FocusManager::Get();
DALI_TEST_CHECK(manager);
// Create the first actor and add it to the stage
Actor first = Actor::New();
manager.SetFocusOrder(first, 1);
Stage::GetCurrent().Add(first);
// Create the second actor and add it to the stage
Actor second = Actor::New();
manager.SetFocusOrder(second, 2);
Stage::GetCurrent().Add(second);
// Check that no actor is being focused yet.
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == Actor());
// Check that the focus is set on the first actor
DALI_TEST_CHECK(manager.SetCurrentFocusActor(first) == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == first);
// Check that the focus is set on the second actor
DALI_TEST_CHECK(manager.SetCurrentFocusActor(second) == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == second);
// Clear the focus
manager.ClearFocus();
// Check that no actor is being focused now.
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == Actor());
}
static void UtcDaliFocusManagerReset()
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliFocusManagerReset");
FocusManager manager = FocusManager::Get();
DALI_TEST_CHECK(manager);
// Create the first actor and add it to the stage
Actor first = Actor::New();
manager.SetFocusOrder(first, 1);
Stage::GetCurrent().Add(first);
// Create the second actor and add it to the stage
Actor second = Actor::New();
manager.SetFocusOrder(second, 2);
Stage::GetCurrent().Add(second);
// Check that no actor is being focused yet.
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == Actor());
// Check that the focus is set on the first actor
DALI_TEST_CHECK(manager.SetCurrentFocusActor(first) == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == first);
// Check that the focus is set on the second actor
DALI_TEST_CHECK(manager.SetCurrentFocusActor(second) == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == second);
// Clear the focus
manager.Reset();
// Check that no actor is being focused now and the focus order of actors have been cleared
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == Actor());
DALI_TEST_CHECK(manager.GetFocusOrder(first) == 0);
DALI_TEST_CHECK(manager.GetFocusOrder(first) == 0);
}
static void UtcDaliFocusManagerFocusGroup()
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliFocusManagerFocusGroup");
FocusManager manager = FocusManager::Get();
DALI_TEST_CHECK(manager);
// Create an actor with two child actors and add it to the stage
Actor parent = Actor::New();
Actor firstChild = Actor::New();
Actor secondChild = Actor::New();
parent.Add(firstChild);
parent.Add(secondChild);
Stage::GetCurrent().Add(parent);
// Create three actors and add them as the children of the first child actor
Actor firstGrandChild = Actor::New();
Actor secondGrandChild = Actor::New();
Actor thirdGrandChild = Actor::New();
firstChild.Add(firstGrandChild);
firstChild.Add(secondGrandChild);
firstChild.Add(thirdGrandChild);
// Set focus order to the actors
manager.SetFocusOrder(parent, 1);
manager.SetFocusOrder(firstChild, 2);
manager.SetFocusOrder(firstGrandChild, 3);
manager.SetFocusOrder(secondGrandChild, 4);
manager.SetFocusOrder(thirdGrandChild, 5);
manager.SetFocusOrder(secondChild, 6);
// Set the parent and the first child actor as focus groups
manager.SetFocusGroup(parent, true);
DALI_TEST_CHECK(manager.IsFocusGroup(parent) == true);
// The focus group of the parent should be itself, as it is set to be a focus group.
DALI_TEST_CHECK(manager.GetFocusGroup(parent) == parent);
// The focus group of the firstChild should be its parent, as it is the immediate parent which is also a group.
DALI_TEST_CHECK(manager.GetFocusGroup(firstChild) == parent);
manager.SetFocusGroup(firstChild, true);
DALI_TEST_CHECK(manager.IsFocusGroup(firstChild) == true);
// The focus group of the firstChild should be itself, as it is set to be a focus group now.
DALI_TEST_CHECK(manager.GetFocusGroup(firstChild) == firstChild);
// Enable wrap mode for focus movement.
manager.SetWrapMode(true);
DALI_TEST_CHECK(manager.GetWrapMode() == true);
// Check that no actor is being focused yet.
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == Actor());
// Check that the focus is set on the parent actor.
DALI_TEST_CHECK(manager.SetCurrentFocusActor(parent) == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == parent);
// Check that group mode is disabled.
DALI_TEST_CHECK(manager.GetGroupMode() == false);
// Check that the focus movement is wrapped as normal.
DALI_TEST_CHECK(manager.MoveFocusForward() == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == firstChild);
DALI_TEST_CHECK(manager.MoveFocusForward() == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == firstGrandChild);
DALI_TEST_CHECK(manager.MoveFocusForward() == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == secondGrandChild);
DALI_TEST_CHECK(manager.MoveFocusForward() == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == thirdGrandChild);
DALI_TEST_CHECK(manager.MoveFocusForward() == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == secondChild);
DALI_TEST_CHECK(manager.MoveFocusForward() == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == parent);
DALI_TEST_CHECK(manager.MoveFocusForward() == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == firstChild);
DALI_TEST_CHECK(manager.MoveFocusForward() == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == firstGrandChild);
// Enable the group mode.
manager.SetGroupMode(true);
DALI_TEST_CHECK(manager.GetGroupMode() == true);
// Check that the focus movement is now limited to the current focus group.
DALI_TEST_CHECK(manager.MoveFocusForward() == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == secondGrandChild);
DALI_TEST_CHECK(manager.MoveFocusForward() == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == thirdGrandChild);
DALI_TEST_CHECK(manager.MoveFocusForward() == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == firstChild);
DALI_TEST_CHECK(manager.MoveFocusForward() == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == firstGrandChild);
}
static void UtcDaliFocusManagerSetAndGetFocusIndicator()
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliFocusManagerSetAndGetFocusIndicator");
FocusManager manager = FocusManager::Get();
DALI_TEST_CHECK(manager);
Actor defaultFocusIndicatorActor = manager.GetFocusIndicatorActor();
DALI_TEST_CHECK(defaultFocusIndicatorActor);
Actor newFocusIndicatorActor = Actor::New();
manager.SetFocusIndicatorActor(newFocusIndicatorActor);
DALI_TEST_CHECK(manager.GetFocusIndicatorActor() == newFocusIndicatorActor);
}
static void UtcDaliFocusManagerSignalFocusChanged()
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliFocusManagerSignalFocusChanged");
FocusManager manager = FocusManager::Get();
DALI_TEST_CHECK(manager);
bool signalVerified = false;
FocusChangedCallback callback(signalVerified);
manager.FocusChangedSignal().Connect( &callback, &FocusChangedCallback::Callback );
// Create the first actor and add it to the stage
Actor first = Actor::New();
manager.SetFocusOrder(first, 1);
Stage::GetCurrent().Add(first);
// Create the second actor and add it to the stage
Actor second = Actor::New();
manager.SetFocusOrder(second, 2);
Stage::GetCurrent().Add(second);
// Check that no actor is being focused yet.
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == Actor());
// Check that the focus is set on the first actor
DALI_TEST_CHECK(manager.SetCurrentFocusActor(first) == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == first);
DALI_TEST_CHECK(callback.mSignalVerified);
callback.Reset();
// Check that the focus is set on the second actor
DALI_TEST_CHECK(manager.SetCurrentFocusActor(second) == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == second);
DALI_TEST_CHECK(callback.mSignalVerified);
callback.Reset();
// Clear the focus
manager.ClearFocus();
// Check that no actor is being focused now.
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == Actor());
DALI_TEST_CHECK(callback.mSignalVerified);
}
static void UtcDaliFocusManagerSignalFocusOvershot()
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliFocusManagerSignalFocusOvershot");
FocusManager manager = FocusManager::Get();
DALI_TEST_CHECK(manager);
bool signalVerified = false;
FocusOvershotCallback callback(signalVerified);
manager.FocusOvershotSignal().Connect(&callback, &FocusOvershotCallback::Callback);
// Create the first actor and add it to the stage
Actor first = Actor::New();
manager.SetFocusOrder(first, 1);
Stage::GetCurrent().Add(first);
// Create the second actor and add it to the stage
Actor second = Actor::New();
manager.SetFocusOrder(second, 2);
Stage::GetCurrent().Add(second);
// Check that the wrap mode is disabled
DALI_TEST_CHECK(manager.GetWrapMode() == false);
// Check that the focus is set on the first actor
DALI_TEST_CHECK(manager.SetCurrentFocusActor(first) == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == first);
// Check that the focus is moved to the second actor successfully.
DALI_TEST_CHECK(manager.MoveFocusForward() == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == second);
// Check that the forward focus movement is overshot.
callback.mCurrentFocusedActor = second;
callback.mFocusOvershotDirection = Toolkit::FocusManager::OVERSHOT_NEXT;
DALI_TEST_CHECK(manager.MoveFocusForward() == false);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == second);
DALI_TEST_CHECK(signalVerified);
callback.Reset();
// Enable the wrap mode
manager.SetWrapMode(true);
DALI_TEST_CHECK(manager.GetWrapMode() == true);
// Check that the forward focus movement is wrapped and no overshot happens.
DALI_TEST_CHECK(manager.MoveFocusForward() == true);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == first);
DALI_TEST_CHECK(signalVerified == false);
// Disable the wrap mode
manager.SetWrapMode(false);
DALI_TEST_CHECK(manager.GetWrapMode() == false);
// Check that the backward focus movement is overshot.
callback.mCurrentFocusedActor = first;
callback.mFocusOvershotDirection = Toolkit::FocusManager::OVERSHOT_PREVIOUS;
DALI_TEST_CHECK(manager.MoveFocusBackward() == false);
DALI_TEST_CHECK(manager.GetCurrentFocusActor() == first);
DALI_TEST_CHECK(signalVerified);
}
|
bc702f2593e15c82d7b124d6e4f460e66cd0e7b3 | 090bdba8f0cd4b4c9499902ab5025a21b596a5dd | /String/Concat.hpp | c059b81f713ead6d04b6c6dc07a54a25eaefb643 | [] | no_license | Riyaaaaa/SpiralLibrary | ac7d9e3949b4877c64163eea62244a9c69fea4d2 | b5cc47dfd07dbe9a97def4eccd0bd4aa31387501 | refs/heads/master | 2021-01-19T01:35:51.937651 | 2018-05-19T08:27:31 | 2018-05-19T08:27:31 | 65,517,147 | 3 | 0 | null | 2018-02-17T14:50:17 | 2016-08-12T02:35:11 | C++ | UTF-8 | C++ | false | false | 1,629 | hpp | Concat.hpp | /*=============================================================================
Copyright (c) 2016 Riyaaaaa
https://github.com/Riyaaaaa/SpiralLibrary
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef Concat_h
#define Concat_h
#include "../Common/Macro.h"
#include "../Utility/IndexSequence.hpp"
#include "../Container/Array.hpp"
#include <string>
NS_LIBSPIRAL_BEGIN
namespace detail {
template<unsigned long N1, unsigned long ... I1, unsigned long N2, unsigned long ... I2>
constexpr libspiral::Array<char const, N1 + N2 - 1> concat(char const (&a1)[N1], char const (&a2)[N2], libspiral::index_sequence<I1...>, libspiral::index_sequence<I2...>) SPIRAL_NOEXCEPT {
return {{ a1[I1]..., a2[I2]... }};
}
}
template<unsigned long N1, unsigned long N2>
constexpr libspiral::Array<char const, N1 + N2 - 1> concat(const char (&a1)[N1], const char (&a2)[N2]) SPIRAL_NOEXCEPT {
return detail::concat(a1, a2, libspiral::make_index_sequence<N1 - 1>{}, libspiral::make_index_sequence<N2>{});
}
template<unsigned long N1, unsigned long N2>
std::string concatToString(const char (&a1)[N1], const char (&a2)[N2]) SPIRAL_NOEXCEPT {
return std::string(&detail::concat(a1, a2, libspiral::make_index_sequence<N1 - 1>{}, libspiral::make_index_sequence<N2>{})[0]);
}
template<unsigned long N1>
constexpr unsigned long length(const char (&a1)[N1]) SPIRAL_NOEXCEPT {
return N1;
}
NS_LIBSPIRAL_END
#endif /* Concat_h */
|
a82731d67b2f505eb1ee38bc76796d22aa00bdd8 | 2b4e3b6498c06a912a7b4306960355eca7e61f3b | /chapter 7/chap7_7.51/Source.cpp | cc52b62aafc9edaf1498e7a57133af4f7fe3772c | [] | no_license | nrqu/answersprimer | 9391510e19764bbafa9ce79b801567f680c1dcaf | a21e782e8c5b771c80b861c59a60f643bab9ab4a | refs/heads/master | 2022-11-14T13:52:43.742962 | 2020-07-13T21:58:30 | 2020-07-13T21:58:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 285 | cpp | Source.cpp | //Exercise 7.51: Why do you think vector defines its single - argument
//constructor as explicit, but string does not? probably because the data type of would make things complicated if its not sued correctly a string is basically the same thing as a char but a vector is not a number. |
f0c63ff27cb7dcd0af55fe6b101cdc54d4a624d6 | f38e1eeee8678d5b228d9340dbeab87edb6a9368 | /TeeNew/Builder2010/Legend_Image.cpp | 34a4e2f1bb46ad56a7ebfa5b4ec10a5fde343be1 | [] | no_license | Steema/TeeChart-VCL-samples | 383f28bfb7e6c812ed7d0db9768c5c1c64366831 | cb26790fa9e5b4c1e50e57922697813e43a0b0bc | refs/heads/master | 2021-11-17T07:02:23.895809 | 2021-09-14T07:43:04 | 2021-09-14T07:43:04 | 8,649,033 | 23 | 14 | null | null | null | null | UTF-8 | C++ | false | false | 1,116 | cpp | Legend_Image.cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Legend_Image.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "Base"
#pragma link "TeePolar"
#pragma link "TeeRose"
#pragma resource "*.dfm"
TLegendImage *LegendImage;
//---------------------------------------------------------------------------
__fastcall TLegendImage::TLegendImage(TComponent* Owner)
: TBaseForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TLegendImage::CheckBox1Click(TObject *Sender)
{
if (CheckBox1->Checked) Chart1->Legend->Brush->Image->Assign(Image1->Picture);
else Chart1->Legend->Brush->Image->Assign(NULL);
}
//---------------------------------------------------------------------------
void __fastcall TLegendImage::FormCreate(TObject *Sender)
{
Series1->FillSampleValues(8);
Chart1->Legend->Brush->Image->Assign(Image1->Picture);
}
//---------------------------------------------------------------------------
|
ff6635e43e0c1bbcab157fc11a9054d4ee5204f6 | d94d07ed47ee0453d9cf75b02428ee21ba56adc8 | /hearder/stl_hashtabletest.h | 579ef70bdc6df6ec5304f8b9079eacaeb2deb0bb | [] | no_license | qzqsmile/TinySTL | d7339dceef10098c4a81c28e42b844541b9a0d32 | 728fa6fb50c4f629459b0fec5c61ccb644252202 | refs/heads/master | 2021-01-10T04:52:04.190164 | 2016-02-02T14:50:04 | 2016-02-02T14:50:04 | 46,332,013 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 210 | h | stl_hashtabletest.h | #ifndef STL_HASHTABLETEST_H
#define STL_HASHTABLETEST_H
namespace hashtabletest{
void hashtabletest();
void hashsettest();
void hashmaptest();
void hash_multisettest();
void hash_multimaptest();
}
#endif |
fdd476f7e7149157c2c6027e95d96618f68a6d26 | 8f50c262f89d3dc4f15f2f67eb76e686b8f808f5 | /LArCalorimeter/LArGeoModel/LArGeoH6Cryostats/src/BPCConstruction.cxx | 47b9c16c98908747e4e4ae97e4dbedb5a05e190e | [
"Apache-2.0"
] | permissive | strigazi/athena | 2d099e6aab4a94ab8b636ae681736da4e13ac5c9 | 354f92551294f7be678aebcd7b9d67d2c4448176 | refs/heads/master | 2022-12-09T02:05:30.632208 | 2020-09-03T14:03:18 | 2020-09-03T14:03:18 | 292,587,480 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 17,743 | cxx | BPCConstruction.cxx | /*
Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration
*/
// This will construct a generic BPC for the H6 beamline that leads to the H1 cryostat.
// There are two kinds of BPCs - old and new one
#include "LArGeoH6Cryostats/BPCConstruction.h"
#include "GeoModelKernel/GeoElement.h"
#include "GeoModelKernel/GeoMaterial.h"
#include "GeoModelKernel/GeoFullPhysVol.h"
#include "GeoModelKernel/GeoVFullPhysVol.h"
#include "GeoModelKernel/GeoPhysVol.h"
#include "GeoModelKernel/GeoVPhysVol.h"
#include "GeoModelKernel/GeoLogVol.h"
#include "GeoModelKernel/GeoBox.h"
#include "GeoModelKernel/GeoTubs.h"
#include "GeoModelKernel/GeoTube.h"
#include "GeoModelKernel/GeoNameTag.h"
#include "GeoModelKernel/GeoTransform.h"
#include "GeoModelKernel/GeoSerialDenominator.h"
#include "GeoModelKernel/GeoSerialIdentifier.h"
#include "GeoModelKernel/GeoSerialTransformer.h"
#include "GeoModelKernel/GeoAlignableTransform.h"
#include "GeoModelKernel/GeoIdentifierTag.h"
#include "GeoModelKernel/GeoSerialDenominator.h"
#include "GeoModelKernel/GeoDefinitions.h"
#include "GeoModelKernel/Units.h"
#include "StoreGate/StoreGateSvc.h"
#include "GeoModelInterfaces/StoredMaterialManager.h"
#include "GeoModelKernel/GeoShapeUnion.h"
#include "GeoModelKernel/GeoShapeShift.h"
#include "GeoGenericFunctions/Variable.h"
// For the database:
#include "RDBAccessSvc/IRDBAccessSvc.h"
#include "RDBAccessSvc/IRDBRecord.h"
#include "RDBAccessSvc/IRDBRecordset.h"
#include "GeoModelInterfaces/IGeoModelSvc.h"
#include "StoreGate/StoreGateSvc.h"
#include "GaudiKernel/MsgStream.h"
#include "GaudiKernel/Bootstrap.h"
#include "GaudiKernel/SystemOfUnits.h"
#include <string>
#include <cmath>
#include <iostream>
LArGeo::BPCConstruction::BPCConstruction(bool old)
:m_BPCPhysical(0),
m_msg(0)
{
m_oldType = old;
}
LArGeo::BPCConstruction::~BPCConstruction()
{
}
GeoVPhysVol* LArGeo::BPCConstruction::GetEnvelope()
{
if (m_BPCPhysical) return m_BPCPhysical;
// Message service:
ISvcLocator *svcLocator = Gaudi::svcLocator();
IMessageSvc * msgSvc;
StatusCode status = svcLocator->service("MessageSvc", msgSvc);
if(!status.isFailure()){
m_msg = new MsgStream(msgSvc, "BPCConstruction");
} else {
throw std::runtime_error("BPCConstruction: cannot initialze message service");
}
(*m_msg) << MSG::INFO << "BPCConstruction - creating an BPC oldType: " << m_oldType << " ! " << endmsg;
StoreGateSvc *detStore;
if (svcLocator->service("DetectorStore", detStore, false )==StatusCode::FAILURE) {
throw std::runtime_error("Error in BPCConstruction, cannot access DetectorStore");
}
ServiceHandle<IGeoModelSvc> geoModelSvc ("GeoModelSvc", "BPCConstruction");
if (geoModelSvc.retrieve().isFailure()) {
throw std::runtime_error ("Cannot locate m_geoModelSvc!!");
}
// Get the materials from the material manager:-----------------------------------------------------//
// //
const StoredMaterialManager* materialManager = nullptr;
if (StatusCode::SUCCESS != detStore->retrieve(materialManager, std::string("MATERIALS"))) return NULL;
std::string name;
double density;
const GeoElement* W=materialManager->getElement("Wolfram");
GeoMaterial* Tungsten = new GeoMaterial(name="Tungsten", density=19.3*GeoModelKernelUnits::g/Gaudi::Units::cm3);
Tungsten->add(W,1.);
Tungsten->lock();
const GeoElement* Ar=materialManager->getElement("Argon");
const GeoElement* C=materialManager->getElement("Carbon");
const GeoElement* O=materialManager->getElement("Oxygen");
const GeoElement* H=materialManager->getElement("Hydrogen");
const GeoElement* Al=materialManager->getElement("Aluminium");
GeoMaterial* CO2 = new GeoMaterial(name="CO2", density=1.84E-03*GeoModelKernelUnits::g/Gaudi::Units::cm3);
CO2->add(C,0.273);
CO2->add(O,0.727);
CO2->lock();
GeoMaterial* ArCO2_1 = new GeoMaterial(name="ArCO2_1", density=(0.8*1.782e-03 + 0.2*1.84E-03)*GeoModelKernelUnits::g/Gaudi::Units::cm3);
ArCO2_1->add(Ar,0.8);
ArCO2_1->add(CO2,0.2);
ArCO2_1->lock();
GeoMaterial* ArCO2_2 = new GeoMaterial(name="ArCO2_2", density=(0.9*1.782e-03 + 0.1*1.84E-03)*GeoModelKernelUnits::g/Gaudi::Units::cm3);
ArCO2_2->add(Ar,0.9);
ArCO2_2->add(CO2,0.1);
ArCO2_2->lock();
// AlMylar AlC5H4O2 ??????
density = 1.39*GeoModelKernelUnits::g/Gaudi::Units::cm3;
GeoMaterial* AlMylar=new GeoMaterial(name="AlMylar",density=1.39*GeoModelKernelUnits::g/Gaudi::Units::cm3);
AlMylar->add(C,0.487980);
AlMylar->add(O,0.260014);
AlMylar->add(H,0.032761);
AlMylar->add(Al,0.219245);
AlMylar->lock();
const GeoMaterial *Air = materialManager->getMaterial("std::Air");
if (!Air) throw std::runtime_error("Error in BPCConstruction, std::Air is not found.");
const GeoMaterial *Aluminium = materialManager->getMaterial("std::Aluminium");
if (!Aluminium) throw std::runtime_error("Error in BPCConstruction, std::Aluminium is not found.");
const GeoMaterial *Mylar = materialManager->getMaterial("std::Mylar");
if (!Mylar) throw std::runtime_error("Error in BPCConstruction, std::Mylar is not found.");
//-------------------------------------------------------------------------------------------------//
std::string AtlasVersion = geoModelSvc->atlasVersion();
std::string LArVersion = geoModelSvc->LAr_VersionOverride();
std::string detectorKey = LArVersion.empty() ? AtlasVersion : LArVersion;
std::string detectorNode = LArVersion.empty() ? "ATLAS" : "LAr";
//////////////////////////////////////////////////////////////////
// Define geometry
//////////////////////////////////////////////////////////////////
double bpc_x = 15.0*Gaudi::Units::cm;
double bpc_y = 15.0*Gaudi::Units::cm;
double bpc_z = (8.684/2)*Gaudi::Units::cm;
double bpc_send = (1.14/2)*Gaudi::Units::cm;
double bpc_sen = (1.06)*Gaudi::Units::cm;
double bpc_div = 5.06*Gaudi::Units::mm;
//double bpc_space = 2.6*Gaudi::Units::mm;
double bpc_ml = 0.0010*Gaudi::Units::cm;
double bpc_alml = 0.0012*Gaudi::Units::cm;
double bpc_frame = 12.1*Gaudi::Units::mm;
double bpc_alframe = 8.*Gaudi::Units::mm;
double bpc_step = 0.6*Gaudi::Units::cm;
double bpc_cstep = 0.3*Gaudi::Units::cm;
double bpc_wd = 0.0020*Gaudi::Units::cm;
double bpc_cwd = 0.0100*Gaudi::Units::cm;
double bpc_old_x = 12.0*Gaudi::Units::cm;
double bpc_old_y = 12.0*Gaudi::Units::cm;
double bpc_old_z = (5.100/2)*Gaudi::Units::cm;
double bpc_old_div = 7.6*Gaudi::Units::mm;
double bpc_old_alml = 0.0020*Gaudi::Units::cm;
double bpc_old_ml = 0.0050*Gaudi::Units::cm;
double bpc_old_frame = 10.*Gaudi::Units::mm;
double bpc_old_alframe = 2.*Gaudi::Units::mm;
double bpc_old_alframe1 = 12.*Gaudi::Units::mm;
double bpc_old_send = (1.7/2)*Gaudi::Units::cm;
double bpc_old_sen = 0.5*Gaudi::Units::cm;
double bpc_old_space = 1.*Gaudi::Units::mm;
double bpc_old_step = 0.6*Gaudi::Units::cm;
double bpc_old_cstep = 0.3*Gaudi::Units::cm;
// Here we creat the envelope for the Moveable FrontBeam Instrumentation. This code is repeated
// createEnvelope() method below. There should be a way to avoid this repitition.
//------ Now create a BPC
(*m_msg) << MSG::INFO <<" Create BPC " << endmsg;
std::string BPCName;
if(m_oldType) BPCName = "LAr::TB::BPCOLD"; else BPCName = "LAr::TB::BPC";
// This creates a square chamber:
GeoBox* shape_bpc;
if(m_oldType) shape_bpc = new GeoBox(bpc_old_x, bpc_old_y, bpc_old_z);
else shape_bpc = new GeoBox(bpc_x, bpc_y, bpc_z);
GeoLogVol* log_bpc;
if(m_oldType) log_bpc = new GeoLogVol(BPCName, shape_bpc, ArCO2_2);
else log_bpc = new GeoLogVol(BPCName, shape_bpc, ArCO2_1);
m_BPCPhysical = new GeoPhysVol(log_bpc);
// AlMylar wall inside BPS
GeoBox* shape_bpc_almylar;
if(m_oldType) shape_bpc_almylar = new GeoBox(bpc_old_x, bpc_old_y, bpc_old_alml);
else shape_bpc_almylar = new GeoBox(bpc_x, bpc_y, bpc_alml);
GeoLogVol* log_bpc_almylar = new GeoLogVol(BPCName + "::bpcalmylar",shape_bpc_almylar, AlMylar);
GeoPhysVol* phys_bpc_almylar = new GeoPhysVol(log_bpc_almylar);
for(int i = 0; i < 2; i ++){
double mylar_pos = 0;
if(m_oldType) {
if(i == 0) mylar_pos = bpc_old_z - bpc_old_alml;
if(i == 1) mylar_pos = bpc_old_alml - bpc_old_z;
} else {
if(i == 0) mylar_pos = bpc_z - bpc_alml;
if(i == 1) mylar_pos = bpc_alml - bpc_z;
}
m_BPCPhysical->add( new GeoIdentifierTag( i ) );
m_BPCPhysical->add( new GeoTransform( GeoTrf::Translate3D(0., 0., mylar_pos) ) );
m_BPCPhysical->add( phys_bpc_almylar );
}
// Mylar wall inside BPC
GeoBox* shape_bpc_mylar;
if(m_oldType) shape_bpc_mylar = new GeoBox(bpc_old_x, bpc_old_y, bpc_old_ml);
else shape_bpc_mylar = new GeoBox(bpc_x, bpc_y, bpc_ml);
GeoLogVol* log_bpc_mylar = new GeoLogVol(BPCName + "::bpc_mylar", shape_bpc_mylar, Mylar);
GeoPhysVol* phys_bpc_mylar = new GeoPhysVol(log_bpc_mylar);
for(int i = 0; i < 2; ++i){
double mylar_pos = 0;
if(m_oldType) {
// if(i == 0) mylar_pos = bpc_old_z - bpc_old_frame - bpc_old_alframe - bpc_old_ml/2.;
// if(i == 1) mylar_pos = - bpc_old_z + bpc_old_ml/2. + bpc_old_frame + bpc_old_alframe1;
if(i == 0) mylar_pos = bpc_old_z - bpc_old_frame - bpc_old_alframe - bpc_old_ml + bpc_old_space;
if(i == 1) mylar_pos = - bpc_old_z + bpc_old_ml + bpc_old_frame + bpc_old_alframe1 - bpc_old_space;
} else {
if(i == 0) mylar_pos = bpc_z - bpc_frame - bpc_alframe - bpc_alml;
if(i == 1) mylar_pos = bpc_alml - bpc_z + bpc_frame + bpc_alframe;
}
m_BPCPhysical->add( new GeoIdentifierTag( i ) );
m_BPCPhysical->add( new GeoTransform( GeoTrf::Translate3D(0., 0., mylar_pos) ) );
m_BPCPhysical->add( phys_bpc_mylar );
}
// X sensitive plane (old has only one sensitive plane, so we choose X)
GeoBox* shape_bpc_xplane;
if(m_oldType) shape_bpc_xplane = new GeoBox(bpc_old_x, bpc_old_y, bpc_old_send);
else shape_bpc_xplane = new GeoBox(bpc_x, bpc_y, bpc_send);
GeoLogVol* log_bpc_xplane;
if(m_oldType) log_bpc_xplane = new GeoLogVol(BPCName + "::bpco_plane", shape_bpc_xplane, ArCO2_2);
else log_bpc_xplane = new GeoLogVol(BPCName + "::bpc_xplane", shape_bpc_xplane, ArCO2_1);
GeoPhysVol* phys_bpc_xplane = new GeoPhysVol(log_bpc_xplane);
m_BPCPhysical->add( new GeoIdentifierTag( 0 ) );
if(m_oldType) m_BPCPhysical->add( new GeoTransform( GeoTrf::Translate3D(0., 0., bpc_old_sen) ) );
else m_BPCPhysical->add( new GeoTransform( GeoTrf::Translate3D(0., 0., -bpc_sen-bpc_send) ) );
m_BPCPhysical->add(phys_bpc_xplane);
// division of X plane
int Ndiv;
if(m_oldType) Ndiv = int(2.0*bpc_old_x/bpc_old_step);
else Ndiv = int(2.0*bpc_x/bpc_step);
GeoBox* shape_bpc_xdiv;
if(m_oldType) shape_bpc_xdiv = new GeoBox(bpc_old_step/2., bpc_old_y, bpc_old_div);
else shape_bpc_xdiv = new GeoBox(bpc_step/2., bpc_y, bpc_div);
GeoLogVol* log_bpc_xdiv;
if(m_oldType) log_bpc_xdiv = new GeoLogVol(BPCName + "::bpco_div", shape_bpc_xdiv, ArCO2_2);
else log_bpc_xdiv = new GeoLogVol(BPCName + "::bpc_xdiv", shape_bpc_xdiv, ArCO2_1);
GeoPhysVol* phys_bpc_xdiv = new GeoPhysVol(log_bpc_xdiv);
GeoGenfun::Variable Index;
GeoXF::TRANSFUNCTION TXO = GeoXF::Pow(GeoTrf::TranslateX3D(1.0), -bpc_old_x+(2*Index+1)*bpc_old_step/2.);
GeoXF::TRANSFUNCTION TX = GeoXF::Pow(GeoTrf::TranslateX3D(1.0), -bpc_x+(2*Index+1)*bpc_step/2.);
phys_bpc_xplane->add( new GeoSerialIdentifier(0) );
if(m_oldType) phys_bpc_xplane->add( new GeoSerialTransformer(phys_bpc_xdiv, &TXO, Ndiv ) );
else phys_bpc_xplane->add( new GeoSerialTransformer(phys_bpc_xdiv, &TX, Ndiv ) );
// Y sensitive plane
GeoPhysVol* phys_bpc_yplane = 0;
GeoPhysVol* phys_bpc_ydiv = 0;
if(!m_oldType) {
GeoBox* shape_bpc_yplane = new GeoBox(bpc_x, bpc_y, bpc_send);
GeoLogVol* log_bpc_yplane = new GeoLogVol(BPCName + "::bpc_yplane",shape_bpc_yplane, ArCO2_1);
phys_bpc_yplane = new GeoPhysVol(log_bpc_yplane);
m_BPCPhysical->add( new GeoIdentifierTag( 0 ) );
m_BPCPhysical->add( new GeoTransform( GeoTrf::Translate3D(0., 0., bpc_sen+bpc_send) ) );
m_BPCPhysical->add( phys_bpc_yplane );
// division of Y plane
GeoBox* shape_bpc_ydiv = new GeoBox(bpc_x, bpc_step/2.,bpc_div);
GeoLogVol* log_bpc_ydiv = new GeoLogVol(BPCName + "::bpc_ydiv", shape_bpc_ydiv, ArCO2_1);
phys_bpc_ydiv = new GeoPhysVol(log_bpc_ydiv);
GeoXF::TRANSFUNCTION TY = GeoXF::Pow(GeoTrf::TranslateY3D(1.0), -bpc_y+(2*Index+1)*bpc_step/2);
phys_bpc_yplane->add( new GeoSerialIdentifier(0) );
phys_bpc_yplane->add( new GeoSerialTransformer(phys_bpc_ydiv, &TY, Ndiv ) );
}
// wires in each division
GeoTubs* shape_bpc_wire;
if(m_oldType) shape_bpc_wire = new GeoTubs(0., bpc_wd, bpc_old_x, 0.*Gaudi::Units::deg, 360.*Gaudi::Units::deg);
else shape_bpc_wire = new GeoTubs(0., bpc_wd, bpc_x, 0.*Gaudi::Units::deg, 360.*Gaudi::Units::deg);
GeoLogVol* log_bpc_wire;
if(m_oldType) log_bpc_wire = new GeoLogVol(BPCName + "::bpco_wire", shape_bpc_wire, Tungsten);
else log_bpc_wire = new GeoLogVol(BPCName + "::bpc_wire", shape_bpc_wire, Tungsten);
GeoPhysVol* phys_bpc_wire = new GeoPhysVol(log_bpc_wire);
phys_bpc_xdiv->add( new GeoIdentifierTag( 1 ) );
phys_bpc_xdiv->add( new GeoTransform( GeoTrf::RotateX3D( 90.*Gaudi::Units::deg ) ) );
phys_bpc_xdiv->add(phys_bpc_wire);
if(!m_oldType) {
phys_bpc_ydiv->add( new GeoIdentifierTag( 1 ) );
phys_bpc_ydiv->add( new GeoTransform( GeoTrf::RotateY3D( 90.*Gaudi::Units::deg ) ) );
phys_bpc_ydiv->add(phys_bpc_wire);
}
// cathode wires around each division
if(m_oldType) Ndiv = int(2.0*bpc_old_x/bpc_cstep);
else Ndiv = int(2.0*bpc_x/bpc_cstep);
GeoTubs* shape_bpc_cwire;
if(m_oldType) shape_bpc_cwire = new GeoTubs(0., bpc_cwd, bpc_old_x, 0.*Gaudi::Units::deg, 360.*Gaudi::Units::deg);
else shape_bpc_cwire = new GeoTubs( 0., bpc_cwd, bpc_x, 0.*Gaudi::Units::deg, 360.*Gaudi::Units::deg);
GeoLogVol* log_bpc_cwire;
if(m_oldType) log_bpc_cwire = new GeoLogVol(BPCName + "::bpco_cwire",shape_bpc_cwire, Tungsten);
else log_bpc_cwire = new GeoLogVol(BPCName + "::bpc_cwire",shape_bpc_cwire, Tungsten);
GeoPhysVol* phys_bpc_cwire = new GeoPhysVol(log_bpc_cwire);
// GeoXF::TRANSFUNCTION TXXMO = GeoTrf::RotateX3D( 90.*Gaudi::Units::deg ) * GeoXF::Pow(GeoTrf::TranslateX3D(1.0), -bpc_old_x+(2*Index+1)*bpc_old_cstep/2.) * GeoTrf::TranslateZ3D(-bpc_old_send-bpc_cwd+bpc_old_space);
// GeoXF::TRANSFUNCTION TXXPO = GeoTrf::RotateX3D( 90.*Gaudi::Units::deg ) * GeoXF::Pow(GeoTrf::TranslateX3D(1.0), -bpc_old_x+(2*Index+1)*bpc_old_cstep/2.) * GeoTrf::TranslateZ3D(bpc_old_send-bpc_old_space+bpc_cwd);
GeoXF::TRANSFUNCTION TXXMO = GeoXF::Pow(GeoTrf::TranslateX3D(1.0), -bpc_old_x+(2*Index+1)*bpc_old_cstep/2.) * GeoTrf::TranslateZ3D(-bpc_old_send-2.*bpc_cwd+bpc_old_space) * GeoTrf::RotateX3D( 90.*Gaudi::Units::deg );
GeoXF::TRANSFUNCTION TXXPO = GeoXF::Pow(GeoTrf::TranslateX3D(1.0), -bpc_old_x+(2*Index+1)*bpc_old_cstep/2.) * GeoTrf::TranslateZ3D(bpc_old_send-bpc_old_space+2.*bpc_cwd) * GeoTrf::RotateX3D( 90.*Gaudi::Units::deg );
// GeoXF::TRANSFUNCTION TXXM = GeoTrf::RotateX3D( 90.*Gaudi::Units::deg ) * GeoXF::Pow(GeoTrf::TranslateX3D(1.0), -bpc_x+(2*Index+1)*bpc_cstep/2.) * GeoTrf::TranslateZ3D(-bpc_div-bpc_cwd);
// GeoXF::TRANSFUNCTION TXXP = GeoTrf::RotateX3D( 90.*Gaudi::Units::deg ) * GeoXF::Pow(GeoTrf::TranslateX3D(1.0), -bpc_x+(2*Index+1)*bpc_cstep/2.) * GeoTrf::TranslateZ3D(bpc_div+bpc_cwd);
GeoXF::TRANSFUNCTION TXXM = GeoXF::Pow(GeoTrf::TranslateX3D(1.0), -bpc_x+(2*Index+1)*bpc_cstep/2.) * GeoTrf::TranslateZ3D(-bpc_div-bpc_cwd) * GeoTrf::RotateX3D( 90.*Gaudi::Units::deg );
GeoXF::TRANSFUNCTION TXXP = GeoXF::Pow(GeoTrf::TranslateX3D(1.0), -bpc_x+(2*Index+1)*bpc_cstep/2.) * GeoTrf::TranslateZ3D(bpc_div+bpc_cwd) * GeoTrf::RotateX3D( 90.*Gaudi::Units::deg );
phys_bpc_xplane->add( new GeoSerialIdentifier(0) );
if(m_oldType) phys_bpc_xplane->add( new GeoSerialTransformer(phys_bpc_cwire, &TXXMO, Ndiv) );
else phys_bpc_xplane->add( new GeoSerialTransformer(phys_bpc_cwire, &TXXM, Ndiv) );
phys_bpc_xplane->add( new GeoSerialIdentifier(Ndiv) );
if(m_oldType) phys_bpc_xplane->add( new GeoSerialTransformer(phys_bpc_cwire, &TXXPO, Ndiv) );
else phys_bpc_xplane->add( new GeoSerialTransformer(phys_bpc_cwire, &TXXP, Ndiv) );
if(!m_oldType) {
// GeoXF::TRANSFUNCTION TYYM = GeoTrf::RotateY3D( 90.*Gaudi::Units::deg ) * GeoXF::Pow(GeoTrf::TranslateY3D(1.0), -bpc_y+(2*Index+1)*bpc_cstep/2.) * GeoTrf::TranslateZ3D(-bpc_div-bpc_cwd);
// GeoXF::TRANSFUNCTION TYYP = GeoTrf::RotateY3D( 90.*Gaudi::Units::deg ) * GeoXF::Pow(GeoTrf::TranslateY3D(1.0), -bpc_y+(2*Index+1)*bpc_cstep/2.) * GeoTrf::TranslateZ3D(bpc_div+bpc_cwd);
GeoXF::TRANSFUNCTION TYYM = GeoXF::Pow(GeoTrf::TranslateY3D(1.0), -bpc_y+(2*Index+1)*bpc_cstep/2.) * GeoTrf::TranslateZ3D(-bpc_div-bpc_cwd) * GeoTrf::RotateY3D( 90.*Gaudi::Units::deg );
GeoXF::TRANSFUNCTION TYYP = GeoXF::Pow(GeoTrf::TranslateY3D(1.0), -bpc_y+(2*Index+1)*bpc_cstep/2.) * GeoTrf::TranslateZ3D(bpc_div+bpc_cwd) * GeoTrf::RotateY3D( 90.*Gaudi::Units::deg );
phys_bpc_yplane->add( new GeoSerialIdentifier(0) );
phys_bpc_yplane->add( new GeoSerialTransformer(phys_bpc_cwire, &TYYM, Ndiv) );
phys_bpc_yplane->add( new GeoSerialIdentifier(Ndiv) );
phys_bpc_yplane->add( new GeoSerialTransformer(phys_bpc_cwire, &TYYP, Ndiv) );
}
return m_BPCPhysical;
}
|
9261cb4a84ab90980eeca9f03c3d16636a1860d2 | 70ec29070494b6761350f34fbc5fd57341537d85 | /byself/byself/remove_element_27.hpp | 0706730aeb1af08ba0a0ffa2fabf2f7b42cc9d88 | [] | no_license | yunyou730/leetcode_practice | 741eb74ebda8de97a8d8a0d0e1b8b46db7d15d24 | ba8617e27083e26fbfbd981998a2b544bf564f50 | refs/heads/master | 2023-07-10T01:56:45.097290 | 2021-08-04T06:10:27 | 2021-08-04T06:10:27 | 291,006,911 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 408 | hpp | remove_element_27.hpp | #pragma once
#include <stdio.h>
#include <vector>
#include <set>
#include <map>
#include <deque>
using namespace std;
/*
一次 后面往前搬运 ,就能搬运成功
需要体会
*/
class Solution {
public:
int removeElement(vector<int>& nums, int val)
{
int i = 0;
for (int j = 0;j < nums.size();j++)
{
if (nums[j] != val)
{
nums[i] = nums[j];
i++;
}
}
return i;
}
};
|
d5f27137d2d0b3108a4f8942be7ccae598bbca98 | d46a933934fe3714651ae65298600ff6973ba08a | /tablicakrawedzi.h | 17bf27234f35e6d2aaaff46eb9be0fe93e381fd6 | [] | no_license | KrzysztofPawlinski/PAMSI_grafy | e7853afe37c53b528481f8ccb267b82fd0515cd2 | c66eca47c59bd424d260dc9e66f64efb63ddae5d | refs/heads/master | 2020-05-23T13:25:36.635806 | 2019-05-15T07:54:22 | 2019-05-15T07:54:22 | 186,776,698 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 611 | h | tablicakrawedzi.h | #ifndef TABLICAKRAWEDZI_H
#define TABLICAKRAWEDZI_H
#include <vector>
#include <iostream>
#include <iomanip>
#include "krawedz.h"
class tablicakrawedzi
{
public:
tablicakrawedzi();
std::vector<krawedz> _tablicaKrawedzi;
void dodajKrawedz(int dlugoscKrawedzi, int wierzcholekA, int wierzcholekB);
void usunKrawedz(int wierzcholekA, int wierzcholekB);
void usunKrawedzieWierzcholka(int wierzcholek);
std::vector<int> getKrawedzieID();
std::vector<int> krawedzieWierzcholka(int idWierzcholka);
void wypiszTabliceKrawedzi();
};
#endif // TABLICAKRAWEDZI_H
|
c7af0efa41a2ec9544a9c009816264b3629625dc | 0097efb7c50ebfbc6d9cf1589d3800ce75f5ce3c | /Control_Caldera_2016_Term/Control_Caldera_2016_Term.ino | ceda41b94c8ca2abdbbef4bc21f57ccbcc874845 | [] | no_license | zagipalma/Control_Caldera_2016_seb | 6f3f8bf7df4052a1f4639fe2d121564590138f53 | a531609bd391dee6695aba7f4a3e844a9aca517f | refs/heads/master | 2021-01-11T23:22:43.482866 | 2017-01-10T21:18:42 | 2017-01-10T21:18:42 | 78,573,843 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,788 | ino | Control_Caldera_2016_Term.ino | //Control Caldera SEB 2016 Termostato Ambiente
//Librerias LCD
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
#define I2C_ADDR 0x27
LiquidCrystal_I2C lcd(I2C_ADDR,2, 1, 0, 4, 5, 6, 7);
//Librerias Temperatura
#include <OneWire.h>
#include <DallasTemperature.h>
//Definicion Pines Control Reles
#define RELE1 2 // Bomba Recirculacion
#define RELE2 3 // Resistencia
#define RELE3 4 // Turbina
#define RELE4 5 // Sinfin - Pellet
//Definicion Sensores de Temperatura
#define ONE_WIRE_BUS 10
OneWire ourWire(ONE_WIRE_BUS);
DallasTemperature sensors(&ourWire);
//Definicion Control LLAMA
int isFlamePin = 6;
int isFlame = HIGH;
//Definicion Estado Temperatura
int t = 0; // Temperatura
int swt = 0; // Switch Temperatura
int swtt = 0; // Switch Select cambio Temperatura
int term = 7; // Termostato Ambiente Nest en Pin 7
int activo = 0; // Estado del caldeo
//Definicion Control servo motor turbina
Servo miServo;
void setup()
{
// Se configura el Servo en el pin 9
miServo.attach(9);
// Se configura PIN 7 para el control del Termostato y se activa como apagado
pinMode(term, INPUT);
digitalWrite(term, HIGH);
// Se configura PIN 6 para el control de la LLAMA
pinMode(isFlamePin, INPUT);
// Inicializar el display con 16 caraceres 2 lineas
lcd.begin (16,2);
lcd.setBacklightPin(3,POSITIVE);
lcd.setBacklight(HIGH);
lcd.home ();
//Inicializar Sensores Temperatura
sensors.begin();
// Se configuran los pines RELES como salidas
pinMode(RELE1, OUTPUT);
pinMode(RELE2, OUTPUT);
pinMode(RELE3, OUTPUT);
pinMode(RELE4, OUTPUT);
// Se colocan los estados de los Reles a HIGH (apagados)
digitalWrite(RELE1,HIGH);
digitalWrite(RELE2,HIGH);
digitalWrite(RELE3,HIGH);
digitalWrite(RELE4,HIGH);
// Se envia mensaje al LCD.
lcd.backlight();
lcd.setCursor (0,0);
lcd.print("Caldera Pellet");
delay(1000);
lcd.setCursor (0,1);
lcd.print("ZAGI PALMA 2016");
delay(2000);
}
//Bucle de puesta en marcha quemador y alimentacion pellet
void loop()
{
// tempdatos();
sensors.requestTemperatures();
t = (sensors.getTempCByIndex(0));
if(t<70 && swt==0) { swtt = 1; activo = 1; } //Caldera Fria. Arranque Inicial
if(t<70 && swt==1) { swtt = 2; activo = 1; } //Calentando hasta temperatura consigna alta (70º)
if(t>=70 && swt==1) { swtt = 3; activo =1; } //Caliente. Ha llegado a la temperatura de consigna alta (70º)
if(((t>50)&&(t<=65))&&(swt==2)) { swtt = 4; activo =1; } //Esperando. Espera la temperatura de consigna baja (50º)
if(t<=50 && swt==2) { swtt = 5; activo = 1; } // Detectado 50º o menos y empieza de nuevo la rutina.
if (digitalRead(term) == HIGH) {swtt = 6;} //Termostato en OFF
switch(swtt)
{
case(1):
// Control estado Termostato
cargainicial();
swt=1;
temptexto();
lcd.setCursor (0,0);
lcd.print("ESPERANDO LLAMA");
break;
case(2):
sensors.requestTemperatures(); tempdatos();
if(digitalRead(isFlamePin) == LOW)
{
digitalWrite(RELE2,HIGH); //rele resistencia
lcd.setCursor (0,0);
lcd.print(" ");
miServo.write(175);
carganormal();
lcd.setCursor (0,0);
lcd.print("ESPERANDO LLAMA");
}
break;
case(3):
swt=2;
lcd.setCursor (0,0); lcd.print("TURB. OFF EN ");
// Se apaga el rele de la Turbina de Aire
// Se espera 1 minutos
for (int i = 60; i >=0; i--)
{
lcd.setCursor (13,0); lcd.print(" ");
lcd.setCursor (13,0); lcd.print(i);
delay(800);
tempdatos();
}
digitalWrite(RELE3,HIGH);
delay(2000);
lcd.setCursor (0,0); lcd.print("ESPERANDO 50 Grd");
break;
case(4):
delay(1000);
tempdatos();
break;
case(5):
swt=0;
break;
case(6):
// lcd.clear();
lcd.setCursor (0,0);
lcd.print(" TERMOSTATO OFF ");
temptexto();
delay(1000);
tempdatos();
if (activo == 1) //Si termostato pasa a OFF y la caldera esta activa.
{
// Se enciende la turbina para limpieza
digitalWrite(RELE3,LOW);
lcd.setCursor (0,0);
lcd.print(" TERMOSTATO OFF ");
lcd.setCursor (0,1);
lcd.print("LIMPIEZA CALDERA");
// lcd.setCursor (8,1);
// lcd.print("T 1");
miServo.write(175);
// Se espera 1 MINUTO
delay(60000);
miServo.write(15);
// Se espera 1/2 MINUTO
delay(30000);
digitalWrite(RELE3,HIGH);
delay(4000);
miServo.write(6);
// lcd.setCursor (8,1);
// lcd.print("T 0");
// Se apaga el rele de la bomba de Recirculacion despues de 3 minutos
lcd.setCursor (0,1); lcd.print("RECC. OFF EN ");
// Se apaga el rele de la bomba de recirculacion
// Se espera 1 minutos
for (int i = 180; i >=0; i--)
{
lcd.setCursor (13,1); lcd.print(" ");
lcd.setCursor (13,1); lcd.print(i);
}
digitalWrite(RELE1,HIGH);
activo = 0; swt = 0; swtt = 0;
}
if (digitalRead(term) == LOW) {swt = 0;} //Termostato en ON
break;
}
}
//Funciones
void temptexto()
{
//lcd.clear();
lcd.setCursor (0,1);
lcd.print("C ");
lcd.setCursor (8,1);
lcd.print(" R ");
}
void tempdatos()
{
sensors.requestTemperatures(); // Send the command to get temperatures
lcd.setCursor (2,1);
lcd.print(sensors.getTempCByIndex(0));
lcd.setCursor (11,1);
lcd.print(sensors.getTempCByIndex(1));
}
void cargainicial()
{
// Inicio del Proceso :
// Colocacion Caracteres en Pantalla LCD
lcd.clear();
lcd.setCursor (1,0);
lcd.print("INICIO PROCESO");
lcd.setCursor (0,1);
lcd.print("B 0"); //Bomba Recirculacion
lcd.setCursor (4,1);
lcd.print("R 0"); //Resistencia
lcd.setCursor (8,1);
lcd.print("T 0"); //Turbina
lcd.setCursor (13,1);
lcd.print("P 0"); //Sinfin - Aporte Pellet
delay(6000);
// Se enciende el rele de la bomba de Recirculacion
digitalWrite(RELE1,LOW);
lcd.setCursor (0,0);
lcd.print("BOMBA RECIRCULA.");
lcd.setCursor (0,1);
lcd.print("B 1");
// Se espera 2 segundos
delay(2000);
// Se enciende la turbina para limpieza
digitalWrite(RELE3,LOW);
lcd.setCursor (0,0);
lcd.print("LIMPIEZA CALDERA");
lcd.setCursor (8,1);
lcd.print("T 1");
miServo.write(175);
// Se espera 1 MINUTO
delay(60000);
miServo.write(15);
// Se espera 1/2 MINUTO
delay(30000);
digitalWrite(RELE3,HIGH);
delay(4000);
miServo.write(6);
lcd.setCursor (8,1);
lcd.print("T 0");
// Se enciende el rele de la Resistencia
digitalWrite(RELE2,LOW);
lcd.setCursor (0,0);
lcd.print("RESISTENCIA ON");
lcd.setCursor (4,1);
lcd.print("R 1");
// Se espera 2 segundos
delay(2000);
// Se enciende el rele de Carga Inicial
digitalWrite(RELE4,LOW);
lcd.setCursor (0,0);
lcd.print("CARGA === PELLET");
lcd.setCursor (13,1);
lcd.print("P 1");
// Se espera 6 segundos
delay(6000);
// Se apaga el rele de Carga Inicial
digitalWrite(RELE4,HIGH);
lcd.setCursor (0,0);
lcd.print("PAUSA === PELLET");
lcd.setCursor (13,1);
lcd.print("P 0");
// Se espera 5 segundos
delay(5000);
// Se enciende el rele de Carga Inicial
digitalWrite(RELE4,LOW);
lcd.setCursor (0,0);
lcd.print("CARGA === PELLET");
lcd.setCursor (13,1);
lcd.print("P 1");
// Se espera 6 segundos
delay(6000);
// Se apaga el rele de Carga Inicial
digitalWrite(RELE4,HIGH);
lcd.setCursor (13,1);
lcd.print("P 0");
// Se espera 200 segundos.
lcd.setCursor (0,0);
lcd.print("CAL. RESIST. ");
for (int i = 200; i >=0; i--)
{
lcd.setCursor (13,0); lcd.print(" ");
lcd.setCursor (13,0); lcd.print(i);
if(i==120)
{ // Se enciende el rele de la Turbina de Aire
miServo.write(10
);
digitalWrite(RELE3,LOW);
lcd.setCursor (8,1);
lcd.print("T 1");
}
delay(1000);
}
// Se Apaga el rele de la Resistencia
digitalWrite(RELE2,HIGH);
lcd.setCursor (0,0);
lcd.print("RESISTENCIA OFF");
lcd.setCursor (4,1);
lcd.print("R 0");
}
void carganormal()
{
// Se enciende el rele de Carga
digitalWrite(RELE4,LOW);
lcd.setCursor (0,0); lcd.print("Carga Pellet ");
// Se espera 4 segundos
for (int i = 3; i >=0; i--)
{ lcd.setCursor (13,0); lcd.print(" ");
lcd.setCursor (14,0); lcd.print(i);
delay(500);
tempdatos();
}
// Se apaga el rele de Carga Inicial
digitalWrite(RELE4,HIGH);
lcd.setCursor (0,0); lcd.print("Pausa Pellet ");
// Se espera 25 segundos
for (int i = 24; i >=0; i--)
{
lcd.setCursor (13,0); lcd.print(" ");
lcd.setCursor (14,0); lcd.print(i);
delay(500);
tempdatos();
}
}
|
f555606e8586730bd757e8e9dc7536414b8b3336 | c7c73566784a7896100e993606e1bd8fdd0ea94e | /panda/src/collide/collisionParabola.cxx | 89678cad3c2c3e27d5ecdbfd8d5b0bd952866f1a | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | panda3d/panda3d | c3f94df2206ff7cfe4a3b370777a56fb11a07926 | 160ba090a5e80068f61f34fc3d6f49dbb6ad52c5 | refs/heads/master | 2023-08-21T13:23:16.904756 | 2021-04-11T22:55:33 | 2023-08-06T06:09:32 | 13,212,165 | 4,417 | 1,072 | NOASSERTION | 2023-09-09T19:26:14 | 2013-09-30T10:20:25 | C++ | UTF-8 | C++ | false | false | 7,204 | cxx | collisionParabola.cxx | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file collisionParabola.cxx
* @author drose
* @date 2007-10-11
*/
#include "collisionParabola.h"
#include "collisionEntry.h"
#include "datagram.h"
#include "datagramIterator.h"
#include "bamReader.h"
#include "bamWriter.h"
#include "geom.h"
#include "geomLinestrips.h"
#include "geomVertexWriter.h"
#include "boundingHexahedron.h"
#include "boundingSphere.h"
#include "look_at.h"
PStatCollector CollisionParabola::_volume_pcollector(
"Collision Volumes:CollisionParabola");
PStatCollector CollisionParabola::_test_pcollector(
"Collision Tests:CollisionParabola");
TypeHandle CollisionParabola::_type_handle;
/**
* Returns the point in space deemed to be the "origin" of the solid for
* collision purposes. The closest intersection point to this origin point is
* considered to be the most significant.
*/
LPoint3 CollisionParabola::
get_collision_origin() const {
return _parabola.calc_point(_t1);
}
/**
*
*/
CollisionSolid *CollisionParabola::
make_copy() {
return new CollisionParabola(*this);
}
/**
*
*/
PT(CollisionEntry) CollisionParabola::
test_intersection(const CollisionEntry &entry) const {
return entry.get_into()->test_intersection_from_parabola(entry);
}
/**
* Transforms the solid by the indicated matrix.
*/
void CollisionParabola::
xform(const LMatrix4 &mat) {
_parabola.xform(mat);
mark_viz_stale();
mark_internal_bounds_stale();
}
/**
* Returns a PStatCollector that is used to count the number of bounding
* volume tests made against a solid of this type in a given frame.
*/
PStatCollector &CollisionParabola::
get_volume_pcollector() {
return _volume_pcollector;
}
/**
* Returns a PStatCollector that is used to count the number of intersection
* tests made against a solid of this type in a given frame.
*/
PStatCollector &CollisionParabola::
get_test_pcollector() {
return _test_pcollector;
}
/**
*
*/
void CollisionParabola::
output(std::ostream &out) const {
out << _parabola << ", t1 = " << _t1 << ", t2 = " << _t2;
}
/**
*
*/
PT(BoundingVolume) CollisionParabola::
compute_internal_bounds() const {
LPoint3 p1 = _parabola.calc_point(get_t1());
LPoint3 p2 = _parabola.calc_point(get_t2());
LVector3 pdelta = p2 - p1;
// If p1 and p2 are sufficiently close, just put a sphere around them.
PN_stdfloat d2 = pdelta.length_squared();
if (d2 < collision_parabola_bounds_threshold * collision_parabola_bounds_threshold) {
LPoint3 pmid = (p1 + p2) * 0.5f;
return new BoundingSphere(pmid, csqrt(d2) * 0.5f);
}
// OK, the more general bounding volume. We use BoundingHexahedron to
// define a very thin box that roughly bounds the parabola's arc. We must
// use BoundingHexahedron instead of BoundingBox, because the box will not
// be axis-aligned, and might be inflated too large if we insist on using
// the axis-aligned BoundingBox.
// We first define "parabola space" as a coordinate space such that the YZ
// plane of parabola space corresponds to the plane of the parabola.
// We have to be explicit about the coordinate system--we specifically mean
// CS_zup_right here, to make the YZ plane.
LMatrix4 from_parabola;
look_at(from_parabola, pdelta, -_parabola.get_a(), CS_zup_right);
from_parabola.set_row(3, p1);
// The matrix that computes from world space to parabola space is the
// inverse of that which we just computed.
LMatrix4 to_parabola;
to_parabola.invert_from(from_parabola);
// Now convert the parabola itself into parabola space.
LParabola psp = _parabola;
psp.xform(to_parabola);
LPoint3 pp2 = psp.calc_point(get_t2());
PN_stdfloat max_y = pp2[1];
// We compute a few points along the parabola to attempt to get the minmax.
PN_stdfloat min_z = 0.0f;
PN_stdfloat max_z = 0.0f;
int num_points = collision_parabola_bounds_sample;
for (int i = 0; i < num_points; ++i) {
double t = (double)(i + 1) / (double)(num_points + 1);
LPoint3 p = psp.calc_point(get_t1() + t * (get_t2() - get_t1()));
min_z = std::min(min_z, p[2]);
max_z = std::max(max_z, p[2]);
}
// That gives us a simple bounding volume in parabola space.
PT(BoundingHexahedron) volume =
new BoundingHexahedron(LPoint3(-0.01, max_y, min_z), LPoint3(0.01, max_y, min_z),
LPoint3(0.01, max_y, max_z), LPoint3(-0.01, max_y, max_z),
LPoint3(-0.01, 0, min_z), LPoint3(0.01, 0, min_z),
LPoint3(0.01, 0, max_z), LPoint3(-0.01, 0, max_z));
// And convert that back into real space.
volume->xform(from_parabola);
return volume;
}
/**
* Fills the _viz_geom GeomNode up with Geoms suitable for rendering this
* solid.
*/
void CollisionParabola::
fill_viz_geom() {
if (collide_cat.is_debug()) {
collide_cat.debug()
<< "Recomputing viz for " << *this << "\n";
}
static const int num_points = 100;
PT(GeomVertexData) vdata = new GeomVertexData
("collision", GeomVertexFormat::get_v3c(),
Geom::UH_static);
GeomVertexWriter vertex(vdata, InternalName::get_vertex());
GeomVertexWriter color(vdata, InternalName::get_color());
for (int i = 0; i < num_points; i++) {
double t = ((double)i / (double)num_points);
vertex.add_data3(_parabola.calc_point(_t1 + t * (_t2 - _t1)));
color.add_data4(LColor(1.0f, 1.0f, 1.0f, 0.0f) +
t * LColor(0.0f, 0.0f, 0.0f, 1.0f));
}
PT(GeomLinestrips) line = new GeomLinestrips(Geom::UH_static);
line->add_next_vertices(num_points);
line->close_primitive();
PT(Geom) geom = new Geom(vdata);
geom->add_primitive(line);
_viz_geom->add_geom(geom, get_other_viz_state());
_bounds_viz_geom->add_geom(geom, get_other_bounds_viz_state());
}
/**
* Factory method to generate a CollisionParabola object
*/
void CollisionParabola::
register_with_read_factory() {
BamReader::get_factory()->register_factory(get_class_type(), make_from_bam);
}
/**
* Function to write the important information in the particular object to a
* Datagram
*/
void CollisionParabola::
write_datagram(BamWriter *manager, Datagram &me) {
CollisionSolid::write_datagram(manager, me);
_parabola.write_datagram(me);
me.add_stdfloat(_t1);
me.add_stdfloat(_t2);
}
/**
* Factory method to generate a CollisionParabola object
*/
TypedWritable *CollisionParabola::
make_from_bam(const FactoryParams ¶ms) {
CollisionParabola *me = new CollisionParabola;
DatagramIterator scan;
BamReader *manager;
parse_params(params, scan, manager);
me->fillin(scan, manager);
return me;
}
/**
* Function that reads out of the datagram (or asks manager to read) all of
* the data that is needed to re-create this object and stores it in the
* appropiate place
*/
void CollisionParabola::
fillin(DatagramIterator& scan, BamReader* manager) {
CollisionSolid::fillin(scan, manager);
_parabola.read_datagram(scan);
_t1 = scan.get_stdfloat();
_t2 = scan.get_stdfloat();
}
|
6a79a89c00fadcdd5bfedb2eb54b121af2e57968 | 0ab72b7740337ec0bcfec102aa7c740ce3e60ca3 | /include/nsim/system/content/with-e/interface.h | e8f4a8f0b2b5f086c1f27b77365e23447eae2c87 | [] | no_license | junwang-nju/mysimulator | 1d1af4ad7ddbe114433ebdadd92de8bb3a45c04f | 9c99970173ce87c249d2a2ca6e6df3a29dfc9b86 | refs/heads/master | 2021-01-10T21:43:01.198526 | 2012-12-15T23:22:56 | 2012-12-15T23:22:56 | 3,367,116 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 956 | h | interface.h |
#ifndef _System_Content_WithE_Interface_H_
#define _System_Content_WithE_Interface_H_
#include "system/content/eg-base/interface.h"
#include "system/content/data/e/interface.h"
namespace mysimulator {
template <typename T>
struct SystemContentWithE : public SystemContentEGBase<T,SystemContentDataE> {
public:
typedef SystemContentWithE<T> Type;
typedef SystemContentEGBase<T,SystemContentDataE> ParentType;
typedef SystemContentDataE<T> EGDataType;
SystemContentWithE() : ParentType() {}
~SystemContentWithE() { Clear(*this); }
bool IsValid() const {
return static_cast<const ParentType*>(this)->IsValid();
}
private:
SystemContentWithE(const Type&) {}
Type& operator=(const Type&) { return *this; }
};
template <typename T>
void Clear(SystemContentWithE<T>& C) {
Clear(static_cast<typename SystemContentWithE<T>::ParentType&>(C));
}
}
#endif
|
b9179662470561915a77060a93640a897bf89a0f | a77675f6834ebbc95570df0b5e19018401a8d28f | /codeforces/cf_598B.cpp | 5168da5a488d759903a4a6a7ac3ce4c50baa0cf1 | [] | no_license | ho-dor/cp-records | 1ea29b5d59d119f26b73be5a9663b1a5548ed687 | 45b6d2bd09ac6082ca722f7b0baea5d2ed10724a | refs/heads/master | 2021-06-14T05:19:22.129105 | 2020-08-13T17:40:30 | 2020-08-13T17:40:30 | 254,469,245 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 591 | cpp | cf_598B.cpp | #include<bits/stdc++.h>
using namespace std;
void leftrotate(string &s, int d)
{
reverse(s.begin(), s.begin()+d);
reverse(s.begin()+d, s.end());
reverse(s.begin(), s.end());
}
void rightrotate(string &s, int d)
{
leftrotate(s, s.length()-d);
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
string str;
cin>>str;
int t;
cin>>t;
while(t--){
int l,r,k;
cin>>l>>r>>k;
string substring = str.substr(l,r);
rightrotate(substring,k);
str.replace(l,r,substring);
}
reverse(str.begin(),str.end());
cout<<str<<"\n";
return 0;
}
|
6a4f1d9da29e749fc61c1444187ea27cf29701a7 | 4779fa27be6249a64d0c45bc94e4b1ee2b19d2e8 | /Receiver Project/files/src/ESP8266/RDP_WiFi_Firmware.ino | b40b76c299d8874b9d16097b9c3b7a714d975466 | [
"MIT"
] | permissive | DigitalConfections/Receiver-Development-Platform | 35be1b2a9d28575ac060b58ef25bbd7f96f90f6d | 56af6a824f694747ce24b12de9caea1fa993dc93 | refs/heads/master | 2021-09-23T12:21:26.107392 | 2021-09-15T01:23:12 | 2021-09-15T01:23:12 | 89,632,380 | 1 | 1 | null | 2021-09-15T01:23:13 | 2017-04-27T19:19:36 | C++ | UTF-8 | C++ | false | false | 34,140 | ino | RDP_WiFi_Firmware.ino | /**********************************************************************************************
* Copyright © 2017 Digital Confections LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in the
* Software without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
**********************************************************************************************
*
* Basic WiFi Functionality for Receiver Development Platform
*
* Hardware Target: Adafruit HUZZAH ESP8266
*
* This sketch provides the following functionality on the target hardware:
*
* 1. Receives commands over the UART0 port. Commands must start with $$$ as the escape sequence.
*
* 2. $$$m,#,val; <- this command allows the ATmega328p to set variables that the WiFi board
* will use; such as the SSID and password for a hotspot for Internet access.
*
* 3. $$$t; <- this tells the WiFi to connect to an Internet hotspot and attempt to read the current
* NIST time; if successful the WiFi sends a command to the ATmega328p telling it to update the time
* stored in the real-time clock.
*
* 4. $$$b; <- this tells the WiFi to set itself up as a UART-to-TCP bridge, and accept TCP connections
* from any clients (like a smartphone or PC)
*
*/
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include "esp8266.h"
/* #include <Wire.h> */
/* Global variables are always prefixed with g_ */
/*
* HUZZAH-specific Defines
*/
#define RED_LED (0)
#define BLUE_LED (2)
BOOL g_debug_prints_enabled = DEBUG_PRINTS_ENABLE_DEFAULT;
BOOL g_LEDs_enabled = LEDS_ENABLE_DEFAULT;
/*
* TCP to UART Bridge
*/
#define MAX_SRV_CLIENTS 3 /*how many clients should be able to telnet to this ESP8266 */
WiFiServer g_tcpServer(BRIDGE_TCP_PORT_DEFAULT.toInt());
WiFiClient g_tcpServerClients[MAX_SRV_CLIENTS];
String g_bridgeIPaddr = BRIDGE_IP_ADDR_DEFAULT;
String g_bridgeSSID = BRIDGE_SSID_DEFAULT;
String g_bridgePW = BRIDGE_PW_DEFAULT; /* minimum 8 characters */
String g_bridgeTCPport = BRIDGE_TCP_PORT_DEFAULT;
/*
* NIST Time Sync
* See https://www.arduino.cc/en/Tutorial/UdpNTPClient
* See http://tf.nist.gov/tf-cgi/servers.cgi
*/
/* TCP time query */
String g_hotspotSSID = HOTSPOT_SSID_DEFAULT;
String g_hotspotPW = HOTSPOT_PW_DEFAULT;
String g_timeHost = TIME_HOST_DEFAULT;
String g_timeHTTPport = TIME_HTTP_PORT_DEFAULT;
/* UDP time query */
#define NTP_PACKET_SIZE (48) // NTP time stamp is in the first 48 bytes of the message
WiFiUDP g_UDP; // A UDP instance to let us send and receive packets over UDP
unsigned int g_localPort = 2390; // local port to listen for UDP packets
/*
* Main Program Support
*/
unsigned long g_relativeTimeSeconds;
unsigned long g_lastAccessToNISTServers = 0;
BOOL g_timeWasSet = FALSE;
int g_blinkPeriodMillis = 500;
void setup()
{
Serial.begin(9600);
while(!Serial); // Wait for UART to initialize
pinMode(RED_LED, OUTPUT); /* Allow the red LED to be controlled */
pinMode(BLUE_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
digitalWrite(RED_LED, HIGH); /* Turn off red LED */
digitalWrite(BLUE_LED, HIGH); /* Turn off blue LED */
showSettings();
}
void setupTCP2UART()
{
WiFi.mode(WIFI_AP);
// Create a somewhat unique SSID
uint8_t mac[WL_MAC_ADDR_LENGTH];
WiFi.softAPmacAddress(mac);
String macID = String(mac[WL_MAC_ADDR_LENGTH - 2], HEX) +
String(mac[WL_MAC_ADDR_LENGTH - 1], HEX);
macID.toUpperCase();
String ap_NameString = g_bridgeSSID + macID;
IPAddress apIP = stringToIP(g_bridgeIPaddr);
if(apIP == IPAddress(-1, -1, -1, -1))
{
apIP = IPAddress(198, 168, 1, 1); // some reasonable default address
}
WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
WiFi.softAP(ap_NameString.c_str(), g_bridgePW.c_str());
/* Start TCP listener on port TCP_PORT */
g_tcpServer.begin();
g_tcpServer.setNoDelay(true);
if(g_debug_prints_enabled)
{
Serial.println(String("Ready! TCP to ") + g_bridgeIPaddr + String(" port ") + g_bridgeTCPport + String(" to connect"));
}
}
BOOL setupWiFiAPConnection()
{
BOOL err = FALSE;
int tries = 0;
/* We start by connecting to a WiFi network */
if(g_debug_prints_enabled)
{
Serial.println();
Serial.print("Connecting to ");
Serial.println(g_hotspotSSID);
}
WiFi.disconnect();
delay(1500);
WiFi.begin((const char*)g_hotspotSSID.c_str(), (const char*)g_hotspotPW.c_str());
while(WiFi.status() != WL_CONNECTED)
{
delay(500);
if(g_debug_prints_enabled) Serial.print(".");
tries++;
if(tries > 30)
{
err = TRUE;
break;
}
}
if(!err)
{
if(g_LEDs_enabled) digitalWrite(BLUE_LED, LOW); /* Turn on blue LED */
if(g_debug_prints_enabled)
{
Serial.println("");
Serial.println("WiFi connected!");
Serial.print("My assigned LAN IP address: ");
Serial.println(WiFi.localIP());
Serial.println();
}
}
return( err);
}
void loop()
{
int value = 0;
BOOL toggle = FALSE;
unsigned long holdTime;
int commaLoc;
int nextCommaLoc;
String arg1, arg2;
BOOL argumentsRcvd = FALSE;
BOOL commandInProgress = FALSE;
int escapeCount = 0;
BOOL done = FALSE;
while(!done)
{
if(commandInProgress)
{
int len;
String command;
command = Serial.readStringUntil(';');
len = command.length();
if(len)
{
value = command.c_str()[0];
if(g_debug_prints_enabled) Serial.println("Command received...");
/* Extract arguments from commands containing them */
if((value == 'M') || (value == 'm'))
{
argumentsRcvd = FALSE;
if(len > 1)
{
arg1 = "";
arg2 = "";
if(g_debug_prints_enabled) Serial.println("Parsing command...");
commaLoc = 1 + command.indexOf(",");
if(commaLoc > 1)
{
nextCommaLoc = command.indexOf(",", commaLoc);
if(nextCommaLoc > 0)
{
arg1 = command.substring(commaLoc, nextCommaLoc);
commaLoc = 1 + command.indexOf(",", nextCommaLoc);
if(commaLoc > 0)
{
nextCommaLoc = command.indexOf(",", commaLoc);
if(nextCommaLoc > 0)
{
arg2 = command.substring(commaLoc, nextCommaLoc);
}
else
{
arg2 = command.substring(commaLoc);
}
}
}
else
{
arg1 = command.substring(commaLoc);
}
}
if(g_debug_prints_enabled)
{
if(arg1.length() > 0)
{
Serial.println(arg1);
}
if(arg2.length() > 0)
{
Serial.println(arg2);
}
}
argumentsRcvd = ((arg1.length() > 0) && (arg2.length() > 0));
}
}
if(g_debug_prints_enabled) Serial.println(command + " " + String(value));
done = TRUE;
}
else
{
if(g_debug_prints_enabled) Serial.println("NULL command received...");
value = 'H';
done = TRUE;
}
commandInProgress = FALSE;
}
else if(Serial.available() > 0) /* search for escape sequency $$$ */
{
value = Serial.read();
if(value == '$')
{
escapeCount++;
if(g_debug_prints_enabled) Serial.println("$..." + String(escapeCount));
if(escapeCount == 3)
{
commandInProgress = TRUE;
escapeCount = 0;
g_blinkPeriodMillis = 250;
}
}
else
{
escapeCount = 0;
}
}
if(g_LEDs_enabled)
{
g_relativeTimeSeconds = millis() / g_blinkPeriodMillis;
if(holdTime != g_relativeTimeSeconds)
{
holdTime = g_relativeTimeSeconds;
toggle = !toggle;
digitalWrite(RED_LED, toggle); /* Blink red LED */
}
}
else
{
digitalWrite(RED_LED, HIGH); /* Turn off red LED */
}
}
switch(value)
{
/* Time: Sync to NIST */
case 'T':
case 't':
{
if(g_debug_prints_enabled) Serial.println("Processing T command...");
if(g_LEDs_enabled) digitalWrite(RED_LED, LOW); /* Turn on red LED */
if(setupWiFiAPConnection())
{
if(g_debug_prints_enabled) Serial.println("Error connecting to router!");
}
else
{
getNistTime();
}
if(g_timeWasSet)
{
digitalWrite(RED_LED, HIGH); /* Turn off red LED */
}
WiFi.disconnect();
digitalWrite(BLUE_LED, HIGH); /* Turn off blue LED */
done = FALSE;
}
break;
/* Bridge TCP to UART */
case 'b':
case 'B':
{
if(g_debug_prints_enabled) Serial.println("Processing B command...");
digitalWrite(RED_LED, HIGH); /* Turn off red LED */
setupTCP2UART();
tcp2UARTbridgeLoop();
done = FALSE;
}
break;
/* Memory: Set value of variables */
case 'M':
case 'm':
{
if(g_debug_prints_enabled) Serial.println("Processing M command...");
if(argumentsRcvd)
{
/* Allow text to substitute for numeric values */
if(arg1.equalsIgnoreCase("HOTSPOT_SSID"))
{
arg1 = String(HOTSPOT_SSID);
}
else if(arg1.equalsIgnoreCase("HOTSPOT_PW"))
{
arg1 = String(HOTSPOT_PW);
}
else if(arg1.equalsIgnoreCase("TIME_HOST"))
{
arg1 = String(TIME_HOST);
}
else if(arg1.equalsIgnoreCase("TIME_HTTP_PORT"))
{
arg1 = String(TIME_HTTP_PORT);
}
else if(arg1.equalsIgnoreCase("BRIDGE_IP_ADDR"))
{
arg1 = String(BRIDGE_IP_ADDR);
}
else if(arg1.equalsIgnoreCase("BRIDGE_SSID"))
{
arg1 = String(BRIDGE_SSID);
}
else if(arg1.equalsIgnoreCase("BRIDGE_PW"))
{
arg1 = String(BRIDGE_PW);
}
else if(arg1.equalsIgnoreCase("BRIDGE_TCP_PORT"))
{
arg1 = String(BRIDGE_TCP_PORT);
}
else if(arg1.equalsIgnoreCase("LEDS_ENABLE"))
{
arg1 = String(LEDS_ENABLE);
}
else if(arg1.equalsIgnoreCase("DEBUG_PRINTS_ENABLE"))
{
arg1 = String(DEBUG_PRINTS_ENABLE);
}
switch(arg1.toInt())
{
case HOTSPOT_SSID:
{
g_hotspotSSID = arg2;
}
break;
case HOTSPOT_PW:
{
g_hotspotPW = arg2;
}
break;
case TIME_HOST:
{
g_timeHost = arg2;
}
break;
case TIME_HTTP_PORT:
{
g_timeHTTPport = arg2;
}
break;
case BRIDGE_IP_ADDR:
{
g_bridgeIPaddr = arg2;
}
break;
case BRIDGE_SSID:
{
g_bridgeSSID = arg2;
}
break;
case BRIDGE_PW:
{
g_bridgePW = arg2;
}
break;
case BRIDGE_TCP_PORT:
{
g_bridgeTCPport = arg2;
}
break;
case LEDS_ENABLE:
{
g_LEDs_enabled = (BOOL)arg2.toInt();
if(g_LEDs_enabled != 0) g_LEDs_enabled = 1; // avoid strange behavior for non 0/1 values
}
break;
case DEBUG_PRINTS_ENABLE:
{
g_debug_prints_enabled = (BOOL)arg2.toInt();
if(g_debug_prints_enabled != 0) g_debug_prints_enabled = TRUE; // avoid strange behavior for non 0/1 values
}
default:
{
showSettings();
}
break;
}
}
if(g_debug_prints_enabled) Serial.println("Finished M command.");
argumentsRcvd = FALSE;
done = FALSE;
}
break;
case 'h':
case 'H':
default:
{
if(g_debug_prints_enabled) showSettings();
done = FALSE;
}
break;
}
}
#ifdef USE_UDP_FOR_TIME_RETRIEVAL
void getNistTime(void)
{
BOOL success = FALSE;
int bytesRead = 0;
int tries = 10;
int32_t timeVal = 0;
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets
success = g_UDP.begin(g_localPort);
if(success)
{
if(g_debug_prints_enabled) Serial.println("Successfully started WiFi UDP socket...");
}
else
{
if(g_debug_prints_enabled) Serial.println("Failed to start WiFi UDP socket. Aborting...");
return;
}
success = FALSE;
while(!success && tries--)
{
if(g_debug_prints_enabled) Serial.println("Sending NTP packet to " + g_timeHost + "...");
success = sendNTPpacket(g_timeHost, packetBuffer); // send an NTP packet to a time server
if(success)
{
int timeout = 0;
// wait to see if a reply is available
delay(1000);
while((bytesRead < 48) && (timeout < 40))
{
bytesRead = g_UDP.parsePacket();
delay(250);
timeout++;
if(g_debug_prints_enabled) Serial.print(".");
}
success = (bytesRead >= 48);
if(!success)
{
if(g_debug_prints_enabled) Serial.println("Timeout waiting for reply.");
}
}
else
{
if(g_debug_prints_enabled) Serial.println("Failed to send NTP packet.");
}
if(g_debug_prints_enabled)
{
if(!success)
{
if(tries)
{
Serial.println("Retrying...");
}
else
{
Serial.println("Failed!");
}
}
}
}
if(success)
{
String utcTimeSinceMidnight = "";
String tempStr;
if(g_debug_prints_enabled) Serial.println(String("Time packet received (") + String(bytesRead) + String(") bytes..."));
// We've received a packet, read the data from it
bytesRead = g_UDP.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
if(g_debug_prints_enabled)
{
Serial.println(String("Bytes retrieved: ") + String(bytesRead));
//the timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, esxtract the two words:
Serial.print("Here's what was received: ");
int i;
for(i=0; i<NTP_PACKET_SIZE; i++)
{
Serial.print(String(packetBuffer[i]) + " ");
}
Serial.println();
}
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
// combine the four bytes (two words) into a long integer NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
if(g_debug_prints_enabled) Serial.println("Seconds since 1 Jan 1900 = " + String(secsSince1900));
// Convert NTP time into common time formats:
const unsigned long seventyYears = 2208988800UL;
unsigned long epoch = secsSince1900 - seventyYears; // subtract seventy years:
if(g_debug_prints_enabled) Serial.println("Unix time: " + String(epoch)); // print Unix time:
// Calculate UTC in hh:mm:ss
utcTimeSinceMidnight += String((epoch % 86400L) / 3600) + ":";
if(((epoch % 3600) / 60) < 10)
{
// In the first 10 minutes of each hour, we'll want a leading '0'
utcTimeSinceMidnight += "0";
}
utcTimeSinceMidnight += String((epoch % 3600) / 60) + ":";
if((epoch % 60) < 10)
{
// In the first 10 seconds of each minute, we'll want a leading '0'
utcTimeSinceMidnight += "0";
}
utcTimeSinceMidnight += String(epoch %60);
if(g_debug_prints_enabled) Serial.println("UTC: " + utcTimeSinceMidnight);
timeVal = stringToTimeVal(utcTimeSinceMidnight);
tempStr = String("$TIM," + String(timeVal) + ";");
Serial.println(tempStr); // Send command to set time
g_timeWasSet = TRUE;
digitalWrite(RED_LED, HIGH); /* Turn off red LED */
}
else
{
if(g_debug_prints_enabled) Serial.println("Failed to receive response. Bytes read = " + String(bytesRead));
}
}
// Send an NTP request to the time server at the given address
// The NIST servers listen for a NTP request on port 123,and respond by sending a udp/ip
// data packet in the NTP format. The data packet includes a 64-bit timestamp containing
// the time in UTC seconds since January 1, 1900 with a resolution of 200 ps.
BOOL sendNTPpacket(String address, byte *packetBuffer)
{
BOOL success = FALSE;
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
//Serial.println("2");
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
if(g_debug_prints_enabled) Serial.println(address.c_str());
/* Prevent accessing NIST servers more often the once every 10 seconds */
g_relativeTimeSeconds = millis() / 1000;
while((g_relativeTimeSeconds - g_lastAccessToNISTServers) < 10) /* prevent servers being accessed more than once every 10 seconds */
{
if(g_debug_prints_enabled) Serial.println(String("Waiting..." + String(10 - (g_relativeTimeSeconds - g_lastAccessToNISTServers))));
delay(1000);
g_relativeTimeSeconds = millis() / 1000;
}
g_lastAccessToNISTServers = millis() / 1000;
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
if(g_UDP.beginPacket(address.c_str(), 123)) //NTP requests are to port 123
{
int bytesWritten;
bytesWritten = g_UDP.write(packetBuffer, NTP_PACKET_SIZE);
success = g_UDP.endPacket();
if(g_debug_prints_enabled) Serial.println("g_UDP.beginPacket: UDP remote connection successful!");
if(g_debug_prints_enabled) Serial.println(String("Bytes written: ") + String(bytesWritten));
if(success)
{
if(g_debug_prints_enabled) Serial.println("Packet was sent successfully!");
}
else
{
if(g_debug_prints_enabled) Serial.println("Packet failed to send!");
}
}
else
{
if(g_debug_prints_enabled) Serial.println("g_UDP.beginPacket: UDP remote connection failed!");
}
return success;
}
#else // USE_UDP_FOR_TIME_RETRIEVAL
void getNistTime(void)
{
String tempStr;
g_relativeTimeSeconds = millis() / 1000;
while((g_relativeTimeSeconds - g_lastAccessToNISTServers) < 10) /* prevent servers being accessed more than once every 10 seconds */
{
if(g_debug_prints_enabled) Serial.println(String("Waiting..." + String(10 - (g_relativeTimeSeconds - g_lastAccessToNISTServers))));
delay(1000);
g_relativeTimeSeconds = millis() / 1000;
}
tempStr = String("Connecting to " + g_timeHost + "...");
if(g_debug_prints_enabled) Serial.println(tempStr);
/* Use WiFiClient class to create TCP connections */
WiFiClient client;
while(!client.connect((const char*)g_timeHost.c_str(), g_timeHTTPport.toInt()))
{
if(g_debug_prints_enabled) Serial.println("Initial connection failed! Retrying...");
client.stop();
delay(5000);
}
do
{
delay(500); /* This delay seems to be required to ensure reliable return of the time string */
if(g_debug_prints_enabled) Serial.println("Requesting time...");
/* Read all the lines of the reply from server and print them to Serial
* Example: 57912 17-06-08 18:28:35 50 0 0 206.3 UTC(NIST) *
* JJJJJ YR-MO-DA HH:MM:SS TT L H msADV UTC(NIST) OTM
* where:
* JJJJJ is the Modified Julian Date (MJD). The MJD has a starting point of midnight on November 17, 1858.
* You can obtain the MJD by subtracting exactly 2 400 000.5 days from the Julian Date, which is an integer
* day number obtained by counting days from the starting point of noon on 1 January 4713 B.C. (Julian Day zero).
*
* YR-MO-DA is the date. It shows the last two digits of the year, the month, and the current day of month.
*
* HH:MM:SS is the time in hours, minutes, and seconds. The time is always sent as Coordinated Universal Time (UTC).
* An offset needs to be applied to UTC to obtain local time. For example, Mountain Time in the U. S. is 7 hours behind
* UTC during Standard Time, and 6 hours behind UTC during Daylight Saving Time.
*
* TT is a two digit code (00 to 99) that indicates whether the United States is on Standard Time (ST) or Daylight
* Saving Time (DST). It also indicates when ST or DST is approaching. This code is set to 00 when ST is in effect,
* or to 50 when DST is in effect. During the month in which the time change actually occurs, this number will decrement
* every day until the change occurs. For example, during the month of November, the U.S. changes from DST to ST.
* On November 1, the number will change from 50 to the actual number of days until the time change. It will decrement
* by 1 every day until the change occurs at 2 a.m. local time when the value is 1. Likewise, the spring change is at
* 2 a.m. local time when the value reaches 51.
*
* L is a one-digit code that indicates whether a leap second will be added or subtracted at midnight on the last day of the
* current month. If the code is 0, no leap second will occur this month. If the code is 1, a positive leap second will be added
* at the end of the month. This means that the last minute of the month will contain 61 seconds instead of 60. If the code is
* 2, a second will be deleted on the last day of the month. Leap seconds occur at a rate of about one per year. They are used
* to correct for irregularity in the earth's rotation. The correction is made just before midnight UTC (not local time).
*
* H is a health digit that indicates the health of the server. If H = 0, the server is healthy. If H = 1, then the server is
* operating properly but its time may be in error by up to 5 seconds. This state should change to fully healthy within 10 minutes.
* If H = 2, then the server is operating properly but its time is known to be wrong by more than 5 seconds. If H = 3, then a hardware
* or software failure has occurred and the amount of the time error is unknown. If H = 4 the system is operating in a special maintenance
* mode and both its accuracy and its response time may be degraded. This value is not used for production servers except in special
* circumstances. The transmitted time will still be correct to within ±1 second in this mode.
*
* msADV displays the number of milliseconds that NIST advances the time code to partially compensate for network delays. The advance
* is currently set to 50.0 milliseconds.
*
* The label UTC(NIST) is contained in every time code. It indicates that you are receiving Coordinated Universal Time (UTC) from the
* National Institute of Standards and Technology (NIST).
*
* OTM (on-time marker) is an asterisk (*). The time values sent by the time code refer to the arrival time of the OTM. In other words,
* if the time code says it is 12:45:45, this means it is 12:45:45 when the OTM arrives. */
done = 0;
int count = 0;
while(!done)
{
String tempStr;
String line = "";
while(client.available())
{
line = client.readStringUntil('\r');
}
if(line == "") /* no response from time server */
{
count++;
if(g_debug_prints_enabled) Serial.println("Request Timedout! Retrying...");
if(count > 2) /* If sending CR didn't help, try reconnecting */
{
if(g_debug_prints_enabled) Serial.println("Reconnecting...");
client.stop();
delay(2000);
while(!client.connect((const char*)g_timeHost.c_str(), g_timeHTTPport.toInt())) /* reconnect to the same host */
{
if(g_debug_prints_enabled) Serial.println("Connection failed! Retrying...");
client.stop();
delay(5000);
}
count = 0;
}
else /* Not sure if this helps, but try sending a CR to server */
{
if(g_debug_prints_enabled) Serial.println("Sending CR...");
client.write('\r');
delay(1000);
}
}
else
{
if(g_debug_prints_enabled) Serial.print("Received:");
if(g_debug_prints_enabled) Serial.print(line);
timeVal = stringToTimeVal(line);
tempStr = String("$TIM," + String(timeVal) + ";");
if(g_debug_prints_enabled) Serial.println(tempStr);
done = 1;
g_timeWasSet = TRUE;
digitalWrite(RED_LED, HIGH); /* Turn off red LED */
}
}
if(g_debug_prints_enabled) Serial.println("Closing connection");
if(g_debug_prints_enabled) Serial.println();
client.stop();
g_lastAccessToNISTServers = millis() / 1000;
}
while(0);
}
#endif // USE_UDP_FOR_TIME_RETRIEVAL
int32_t stringToTimeVal(String string)
{
int32_t time_sec = 0;
BOOL missingTens = FALSE;
uint8_t index = 0;
char field[3];
char *instr, *str;
char c_str[10];
strcpy(c_str, string.c_str());
str = c_str;
field[2] = '\0';
field[1] = '\0';
instr = strchr(str, ':');
if(instr == NULL)
{
return( time_sec);
}
if(str > (instr - 2)) /* handle case of time format #:##:## */
{
missingTens = TRUE;
str = instr - 1;
}
else
{
str = instr - 2;
}
/* hh:mm:ss or h:mm:ss */
field[0] = str[index++]; /* tens of hours or hours */
if(!missingTens)
{
field[1] = str[index++]; /* hours */
}
time_sec = SecondsFromHours(atol(field));
index++;
field[0] = str[index++];
field[1] = str[index++]; /* minutes */
time_sec += SecondsFromMinutes(atol(field));
index++;
field[0] = str[index++];
field[1] = str[index++]; /* seconds */
time_sec += atoi(field);
return(time_sec);
}
void tcp2UARTbridgeLoop()
{
uint8_t i, j;
char buf[1024];
int bytesAvail, bytesIn;
BOOL done = FALSE;
BOOL toggle = FALSE;
unsigned long holdTime;
BOOL clientConnected = FALSE;
int escapeCount = 0;
if(g_debug_prints_enabled) Serial.println("Bridge started");
while(!done)
{
/*check if there are any new clients */
if(g_tcpServer.hasClient())
{
for(i = 0; i < MAX_SRV_CLIENTS; i++)
{
/*find free/disconnected spot */
if(!g_tcpServerClients[i] || !g_tcpServerClients[i].connected())
{
if(g_tcpServerClients[i])
{
g_tcpServerClients[i].stop();
}
g_tcpServerClients[i] = g_tcpServer.available();
if(g_tcpServerClients[i].connected())
{
if(g_debug_prints_enabled) Serial.println("New client: #" + String(i+1));
}
continue;
}
}
/* no free/disconnected spot so reject */
WiFiClient g_tcpServerClient = g_tcpServer.available();
g_tcpServerClient.stop();
}
/*check clients for data */
clientConnected = FALSE;
for(i = 0; i < MAX_SRV_CLIENTS; i++)
{
if(g_tcpServerClients[i] && g_tcpServerClients[i].connected())
{
/*get data from the telnet client and push it to the UART */
while((bytesAvail = g_tcpServerClients[i].available()) > 0)
{
bytesIn = g_tcpServerClients[i].readBytes(buf, min(sizeof(buf), bytesAvail));
if(bytesIn > 0)
{
Serial.write(buf, bytesIn);
delay(0);
}
}
clientConnected = TRUE;
}
}
/*check UART for data */
while((bytesAvail = Serial.available()) > 0)
{
bytesIn = Serial.readBytes(buf, min(sizeof(buf), bytesAvail));
if(bytesIn > 0)
{
/*push UART data to all connected telnet clients */
for(i = 0; i < MAX_SRV_CLIENTS; i++)
{
if(g_tcpServerClients[i] && g_tcpServerClients[i].connected())
{
g_tcpServerClients[i].write((uint8_t*)buf, bytesIn);
delay(0);
}
for(j = 0; j < bytesIn; j++)
{
if(buf[j] == '$')
{
escapeCount++;
if(escapeCount == 3)
{
done = TRUE;
escapeCount = 0;
}
}
else
{
escapeCount = 0;
}
}
}
}
}
if(clientConnected && g_LEDs_enabled)
{
g_relativeTimeSeconds = millis() / g_blinkPeriodMillis;
if(holdTime != g_relativeTimeSeconds)
{
holdTime = g_relativeTimeSeconds;
toggle = !toggle;
digitalWrite(BLUE_LED, toggle); /* Blink blue LED */
}
}
else
{
digitalWrite(BLUE_LED, HIGH); /* Turn off blue LED */
}
}
}
void showSettings()
{
int i;
if(!g_debug_prints_enabled) return;
Serial.println("RDP WiFi firmware - v" + String(WIFI_SW_VERSION));
Serial.println("Baud Rate: 9600");
Serial.println();
Serial.println("Valid Commands:");
Serial.println("$$$m,id,value; - Set WiFi memory variable <id> to <value>; ex: $$$m,HOTSPOT_SSID,MyRouterSSID;");
Serial.println("$$$t; - Retrieve NIST time from Time Server");
Serial.println("$$$b; - Start/Cancel UART-to-TCP bridge");
Serial.println("$$$h; - This help message");
Serial.println();
Serial.println("HUZZAH Settings");
for(i=0; i<NUMBER_OF_SETTABLE_VARIABLES; i++)
{
switch(i)
{
case HOTSPOT_SSID:
{
Serial.println(String("Local Hotspot SSID (HOTSPOT_SSID) = \"") + g_hotspotSSID + "\"");
}
break;
case HOTSPOT_PW:
{
Serial.println("Local Hotspot Password (HOTSPOT_PW) = \"" + g_hotspotPW + "\"");
}
break;
case TIME_HOST:
{
Serial.println("Time Server URL (TIME_HOST) = " + g_timeHost);
}
break;
case TIME_HTTP_PORT:
{
Serial.println("Time Server Port Number (TIME_HTTP_PORT) = " + g_timeHTTPport);
}
break;
case BRIDGE_SSID:
{
Serial.println("UART-to-TCP Bridge SSID (BRIDGE_SSID) = \"" + g_bridgeSSID + "\"");
}
break;
case BRIDGE_IP_ADDR:
{
Serial.println("UART-to-TCP Bridge IP Address (BRIDGE_IP_ADDR) = \"" + g_bridgeIPaddr + "\"");
}
break;
case BRIDGE_PW:
{
Serial.println("UART-to-TCP Bridge Password (BRIDGE_PW) = \"" + g_bridgePW + "\"");
}
break;
case BRIDGE_TCP_PORT:
{
Serial.println("UART-to-TCP Bridge TCP Port number (BRIDGE_TCP_PORT) = " + g_bridgeTCPport);
}
break;
case LEDS_ENABLE:
{
Serial.println("LEDs Enabled (LEDS_ENABLE) = " + String(g_LEDs_enabled));
}
break;
case DEBUG_PRINTS_ENABLE:
{
Serial.println("Debug Prints Enabled (DEBUG_PRINTS_ENABLE) = " + String(g_debug_prints_enabled));
}
default:
break;
}
}
}
/*
* Converts a String containing a valid IP address into an IPAddress.
* Returns the IPAddress contained in addr, or returns "-1,-1,-1,-1" if the address is invalid
*/
IPAddress stringToIP(String addr)
{
IPAddress ipAddr = IPAddress(-1, -1, -1, -1);
int dot, nextDot;
// 129.6.15.28 = NIST, Gaithersburg, Maryland
String o1="129", o2="6", o3="15", o4="28"; // default to some reasonable IP address
dot = addr.indexOf(".", 0);
if(dot > 0)
{
o1 = addr.substring(0, dot);
if((o1.toInt() >= 0) && (o1.toInt() <= 255))
{
dot++;
nextDot = addr.indexOf(".", dot);
if(nextDot > 0)
{
o2 = addr.substring(dot, nextDot);
if((o2.toInt() >= 0) && (o2.toInt() <= 255))
{
nextDot++;
dot = addr.indexOf(".", nextDot);
if(dot > 0)
{
o3 = addr.substring(nextDot, dot);
dot++;
o4 = addr.substring(dot);
if(((o3.toInt() >= 0) && (o3.toInt() <= 255)) && ((o4.toInt() >= 0) && (o4.toInt() <= 255)))
ipAddr = IPAddress(o1.toInt(), o2.toInt(), o3.toInt(), o4.toInt());
}
}
}
}
}
return ipAddr;
}
|
dc320273b5c7a32d24b8b084dda8bbb7bd32b4e4 | e34b485dfa63c27351a87d979ff71382201f408f | /codeforces/599a.cpp | 71228f9c8984157c4c91ec1a1376b5d437d5de72 | [] | no_license | gabrielrussoc/competitive-programming | 223146586e181fdc93822d8462d56fd899d25567 | cd51b9af8daf5bab199b77d9642f7cd01bcaa8e3 | refs/heads/master | 2022-11-30T11:55:12.801388 | 2022-11-15T18:12:55 | 2022-11-15T18:12:55 | 44,883,370 | 10 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 542 | cpp | 599a.cpp | #include <bits/stdc++.h>
#define mp make_pair
#define pb push_back
#define eps 1e-8
#define pii pair<int,int>
#define pll pair<long long,long long>
#define inf INT_MAX
#define ff first
#define ss second
using namespace std;
typedef long long ll;
//////////////0123456789
const int N = 100005;
const int modn = 1000000007;
int main(){
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
int ans = INT_MAX;
ans = min(ans,a+a+b+b);
ans = min(ans,a+c+b);
ans = min(ans,b+b+c+c);
ans = min(ans,a+a+c+c);
printf("%d\n",ans);
}
|
68ca41fc5aaf61dfed06af791ede6bb6781a262a | e664a0f7a72d9e10b48b2ed57171bcc85482bb5e | /sources/aber-calc/src/Utils.cpp | 241140bdee16961cee225dbde08736af44d3f9b5 | [] | no_license | ahanika/aberration | f39bc035568c19ccaa9f0c4f5becded341d36bc9 | 14b9846b5ab397e931799548d524d693431e0d1d | refs/heads/master | 2020-04-20T22:02:51.647775 | 2019-05-09T13:19:21 | 2019-05-09T13:19:21 | 169,126,582 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 14,323 | cpp | Utils.cpp | #include "opencv2/opencv.hpp"
#include <vector>
#include <gsl/gsl_linalg.h>
#include "Utils.h"
// Функция расчета разницы между координатам в различных каналах
double calc_channel_diff(
cv::KeyPoint B,
cv::KeyPoint G,
cv::KeyPoint R)
{
return sqrt(
pow((G.pt.x - B.pt.x), 2)
+ pow((G.pt.y - B.pt.y), 2)
+ pow((G.pt.x - R.pt.x), 2)
+ pow((G.pt.y - R.pt.y), 2)
);
}
// Функция для поиска номера координат центра изображения в векторе
int get_image_center_number(std::vector<std::vector<cv::KeyPoint>> keypoints)
{
int number = 0;
double min = calc_channel_diff(
keypoints[0][0],
keypoints[1][0],
keypoints[2][0]
);
double current;
for (int i = 1; i < keypoints[0].size(); ++i)
{
current = calc_channel_diff(
keypoints[0][i],
keypoints[1][i],
keypoints[2][i]
);
if (current < min)
{
number = i;
min = current;
}
}
return number;
}
// Функция суммирования, возведенных в степень значений (матрица a)
double sum_pow_a(
std::vector<cv::KeyPoint> points_to_sum,
int x_pow_1,
int y_pow_1,
int x_pow_2,
int y_pow_2)
{
double result = 0;
for (int i = 0; i < points_to_sum.size(); ++i)
{
result += pow(points_to_sum[i].pt.x, x_pow_1)
* pow(points_to_sum[i].pt.y, y_pow_1)
* pow(points_to_sum[i].pt.x, x_pow_2)
* pow(points_to_sum[i].pt.y, y_pow_2);
}
return result;
}
// Функция суммирования, возведенных в степень значений (вектор y)
double sum_pow_y(
std::vector<cv::KeyPoint> points_to_sum_g,
std::vector<cv::KeyPoint> points_to_sum,
int x_pow,
int y_pow,
bool use_x)
{
double result = 0;
for (int i = 0; i < points_to_sum.size(); ++i)
{
double temp_sum;
if (use_x)
{
temp_sum = points_to_sum_g[i].pt.x;
}
else
{
temp_sum = points_to_sum_g[i].pt.y;
}
result += pow(points_to_sum[i].pt.x, x_pow)
* pow(points_to_sum[i].pt.y, y_pow)
* temp_sum;
}
return result;
}
// Функция для решения СЛУ
void solve_SLE(
double* result,
double* a_matr,
double* y_vec,
int size,
int refine)
{
// Решаем СЛУ
gsl_matrix_view m = gsl_matrix_view_array(a_matr, size, size);
gsl_vector_view b = gsl_vector_view_array(y_vec, size);
gsl_vector* x = gsl_vector_alloc(size);
int s;
gsl_permutation* p = gsl_permutation_alloc(size);
gsl_matrix_view LU = gsl_matrix_view_array(a_matr, size, size);
gsl_vector* work = gsl_vector_alloc(size);
gsl_linalg_LU_decomp(&LU.matrix, p, &s);
gsl_linalg_LU_solve(&LU.matrix, p, &b.vector, x);
// Улучшаем решением повторными вызовами функции gsl_linalg_LU_refine
for (int i = 0; i < refine; i++)
{
gsl_linalg_LU_refine(&m.matrix, &LU.matrix, p, &b.vector, x, work);
}
for (int i = 0; i < size; i++)
{
result[i] = x->data[i];
}
gsl_permutation_free(p);
gsl_vector_free(x);
gsl_vector_free(work);
}
// Функция для расчета коэффициентов полинома для каналов
void calc_pol(
double* result,
std::vector<cv::KeyPoint> channel_green,
std::vector<cv::KeyPoint> channel_to_calc,
int pol_number,
bool calc_x,
int max_power,
int refine_sol)
{
// Инициализируем промежуточные массивы для решения системы уравнений
double* a = new double[pol_number * pol_number];
double* y = new double[pol_number];
// Вычисляем коэффициенты матрицы a
int temp_x1 = max_power;
int temp_y1 = 0;
int temp_x2 = max_power;
int temp_y2 = 0;
for (int i = 0; i < pol_number; ++i)
{
temp_x2 = max_power;
temp_y2 = 0;
for (int j = 0; j < pol_number; ++j)
{
a[pol_number * i + j] = sum_pow_a(
channel_to_calc,
temp_x1,
temp_y1,
temp_x2,
temp_y2
);
if (temp_x2 == 0)
{
temp_x2 = temp_y2 - 1;
temp_y2 = 0;
}
else
{
--temp_x2;
++temp_y2;
}
}
if (temp_x1 == 0)
{
temp_x1 = temp_y1 - 1;
temp_y1 = 0;
}
else
{
--temp_x1;
++temp_y1;
}
}
// Вычисляем коэффициенты вектора y
int temp_x = max_power;
int temp_y = 0;
for (int i = 0; i < pol_number; ++i)
{
y[i] = sum_pow_y(
channel_green,
channel_to_calc,
temp_x,
temp_y,
calc_x
);
if (temp_x == 0)
{
temp_x = temp_y - 1;
temp_y = 0;
}
else
{
--temp_x;
++temp_y;
}
}
// Решаем СЛУ
solve_SLE(
result,
a,
y,
pol_number,
refine_sol
);
delete(y);
delete(a);
}
// Функция для вычисления новой координаты субпикселя полиномом
int calc_new_value_pol(
double old_value_x,
double old_value_y,
double* pol_values,
int pol_number,
int max_power,
float center)
{
double new_value = 0;
int pow_x = max_power;
int pow_y = 0;
for (int i = 0; i < pol_number; ++i)
{
new_value += pol_values[i]
* pow(old_value_x, pow_x)
* pow(old_value_y, pow_y);
if (pow_x == 0)
{
pow_x = pow_y - 1;
pow_y = 0;
}
else
{
--pow_x;
++pow_y;
}
}
return (int)round(new_value + center);
}
// Функция, заменяющая значения субпикселя по координате
void change_subpixel(
cv::Mat image,
int x,
int y,
int value,
int channel)
{
cv::Vec3b temp_vec;
switch (channel)
{
case 0:
temp_vec[0] = value;
temp_vec[1] = image.at<cv::Vec3b>(cv::Point(y, x))[1];
temp_vec[2] = image.at<cv::Vec3b>(cv::Point(y, x))[2];
break;
case 1:
temp_vec[0] = image.at<cv::Vec3b>(cv::Point(y, x))[0];
temp_vec[1] = value;
temp_vec[2] = image.at<cv::Vec3b>(cv::Point(y, x))[2];
break;
case 2:
temp_vec[0] = image.at<cv::Vec3b>(cv::Point(y, x))[0];
temp_vec[1] = image.at<cv::Vec3b>(cv::Point(y, x))[1];
temp_vec[2] = value;
break;
}
image.at<cv::Vec3b>(cv::Point(y, x)) = temp_vec;
}
// Функция для нахождения ближайшей окружности из вектора
int get_closest(
cv::KeyPoint point,
std::vector<cv::KeyPoint> channel,
int number)
{
int result = 0;
float min = sqrt(
pow((point.pt.x - channel[0].pt.x), 2)
+ pow((point.pt.y - channel[0].pt.y), 2)
);
float current = 0;
for (int i = 1; i < channel.size(); i++)
{
current = sqrt(
pow((point.pt.x - channel[i].pt.x), 2)
+ pow((point.pt.y - channel[i].pt.y), 2)
);
if (current < min)
{
min = current;
result = i;
}
}
return result;
}
// Выравниваем остальные каналу по зеленому
void align_keypoints_by_green(std::vector<std::vector<cv::KeyPoint>> &keypoints)
{
float temp = 0;
int closest = 0;
// Допускаем, что зеленый канал всегда правильный, т.е.
// отсортирован справа-налево снизу-вверх.
// Здесь можно добавить сортировку зеленого канала
for (int i = 0; i < keypoints[1].size(); i++)
{
// Синий канал
closest = get_closest(keypoints[1][i], keypoints[0], i);
if (closest != i)
{
temp = keypoints[0][i].pt.x;
keypoints[0][i].pt.x = keypoints[0][closest].pt.x;
keypoints[0][closest].pt.x = temp;
temp = keypoints[0][i].pt.y;
keypoints[0][i].pt.y = keypoints[0][closest].pt.y;
keypoints[0][closest].pt.y = temp;
}
// Красный канал
closest = get_closest(keypoints[1][i], keypoints[2], i);
if (closest != i)
{
temp = keypoints[2][i].pt.x;
keypoints[2][i].pt.x = keypoints[2][closest].pt.x;
keypoints[2][closest].pt.x = temp;
temp = keypoints[2][i].pt.y;
keypoints[2][i].pt.y = keypoints[2][closest].pt.y;
keypoints[2][closest].pt.y = temp;
}
}
}
// Функция для удаления аберрации с изображения
cv::Mat delete_abberation(
cv::Mat original,
double* pxb,
double* pyb,
double* pxr,
double* pyr,
int size,
int max_power,
cv::KeyPoint center)
{
int rows = original.rows;
int cols = original.cols;
// Инициализируем пустую картинку той же размерности, что и оригинальная
cv::Mat corrected(
rows,
cols,
original.type(),
cv::Scalar(0, 0, 0)
);
int new_x = 0;
int new_y = 0;
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j)
{
// Синий канал
new_x = calc_new_value_pol(
j - center.pt.x,
i - center.pt.y,
pxb,
size,
max_power,
center.pt.x
);
new_y = calc_new_value_pol(
j - center.pt.x,
i - center.pt.y,
pyb,
size,
max_power,
center.pt.y
);
if (new_x >= 0 && new_x < cols && new_y >= 0 && new_y < rows)
{
change_subpixel(
corrected,
new_x,
new_y,
original.at<cv::Vec3b>(cv::Point(i, j))[0],
0
);
}
// Зеленый канал
change_subpixel(
corrected,
j,
i,
original.at<cv::Vec3b>(cv::Point(i, j))[1],
1
);
// Красный канал
new_x = calc_new_value_pol(
j - center.pt.x,
i - center.pt.y,
pxr,
size,
max_power,
center.pt.x
);
new_y = calc_new_value_pol(
j - center.pt.x,
i - center.pt.y,
pyr,
size,
max_power,
center.pt.y
);
if (new_x >= 0 && new_x < cols && new_y >= 0 && new_y < rows)
{
change_subpixel(
corrected,
new_x,
new_y,
original.at<cv::Vec3b>(cv::Point(i, j))[2],
2
);
}
}
}
return corrected;
}
// Пишем коэффициенты полинома в файл для далнейшего переиспользования
void write_to_file(
std::string file,
int degree,
double* pxb,
double* pyb,
double* pxr,
double* pyr,
int arr_size,
float center_x,
float center_y)
{
std::ofstream out;
out.open(file);
out << degree << std::endl;
for (int i = 0; i < arr_size; i++)
{
out << pxb[i] << "\t";
}
out << std::endl;
for (int i = 0; i < arr_size; i++)
{
out << pyb[i] << "\t";
}
out << std::endl;
for (int i = 0; i < arr_size; i++)
{
out << pxr[i] << "\t";
}
out << std::endl;
for (int i = 0; i < arr_size; i++)
{
out << pyr[i] << "\t";
}
out << std::endl << center_x << "\t" << center_y << std::endl;
out.close();
}
// Функция чтения данных из файла параметров
int read_config(
char* path,
std::string& image_path,
int& max_power,
int& refine,
int& circles,
cv::SimpleBlobDetector::Params& params,
std::string& result_path,
bool& preview)
{
std::ifstream file;
file.open(path, std::ios::in);
if (!file.is_open())
{
return -1;
}
// Путь к изображению
file >> image_path;
// Максимальная степень полинома
file >> max_power;
// Количество вызовов функции для улучшения решения СЛУ
file >> refine;
// Количество кругов на изображении
file >> circles;
// Настраиваем параметры для blobDetector
file >> params.minThreshold;
file >> params.maxThreshold;
params.filterByArea = true;
file >> params.minArea;
file >> params.maxArea;
params.filterByCircularity = true;
file >> params.minCircularity;
params.filterByConvexity = true;
file >> params.minConvexity;
params.filterByInertia = true;
file >> params.minInertiaRatio;
// Путь к файлу, в который сохранятся результаты работы программы
file >> result_path;
// Выводим или не выводим превью изображения
file >> preview;
return 0;
}
|
f2744b92b2b81e1e7a52c4e4c0e1e2ff6f72e47a | fc86f3837769bda7270bba16f2ad99a8be9037ce | /src/simpaSRG_NAIVE.cpp | eb862fc50ee0d5e8352fa7d9d8e1deba0b69585d | [
"MIT"
] | permissive | Andyan0313/simpaSRG | d1012c53c415b8b0d5ae58006dfb8a3221e15227 | a38ef23973e15053414c7c8b4cdf61c09aa26bf1 | refs/heads/main | 2023-04-21T15:43:16.968279 | 2021-05-05T16:44:27 | 2021-05-05T16:44:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 46 | cpp | simpaSRG_NAIVE.cpp | //FILE simpaSRG.cpp
#include "commonSIMPA.h"
|
a7a6f172d421e1e5ea1ada5382fe1f3936c6e3fc | e106b3354ca00ef34c3dc77dd72965bbfe51467f | /river/person/Child.h | 643e19e4e91a318407b0e27666a1e4b8bfa133ed | [] | no_license | Ga-3tan/POO2_L3_Riviere | 965b3e073099a413f08d09f60f51ea6b26ff1eb9 | ef67213d3fe565262586864b0e027e6cd386e23e | refs/heads/main | 2023-04-18T20:57:48.244063 | 2021-05-03T09:55:29 | 2021-05-03T09:55:29 | 357,906,034 | 3 | 0 | null | 2021-05-02T14:40:23 | 2021-04-14T12:58:17 | C++ | UTF-8 | C++ | false | false | 1,154 | h | Child.h | /**
* Name : LAB003_Riviere
* File : Child.h
* Authors : Gaétan Zwick, Marco Maziero
* Date : 28.04.2021
*/
#ifndef POO2_L3_RIVIERE_CHILD_H
#define POO2_L3_RIVIERE_CHILD_H
#include "Person.h"
#include "../container/Container.h"
/**
* Represends a child (cannot drive and depends on their parents)
*/
class Child : public Person {
protected:
/**
* Represents a son
* @param name The name of the son
*/
explicit Child(const std::string& name);
public:
/**
* Checks if the current person can stay with
* the people contained in the given list
* @param c The container containing the people
* @return True if the person can get along with the others
*/
bool canStayWith(const Container& c) const override;
/**
* Returns the rule specific to the child if its a son or a daughter
* @param mother The mother is present with the child
* @param father The father is present with the child
* @return The child can stay with the given parents
*/
virtual bool parentsPresence(bool mother, bool father) const = 0;
};
#endif //POO2_L3_RIVIERE_CHILD_H
|
cb43a10ee2b08c45f69ec348ed481515f3fac050 | 60d1e0f935be26d4ba2687c2c454f0eaf3423177 | /cvMatTest.cpp | 3bf2ecfc6017e9f21180e575d6f5166ad48d9e2f | [] | no_license | ammarpk/opencv | 7beab065c05d9c6a69cb08a63fbca2d09b7651f4 | f4df5334b9f2eb6889a7e388f7c93955713666c9 | refs/heads/master | 2016-09-12T23:47:08.125251 | 2016-06-04T13:21:51 | 2016-06-04T13:21:51 | 56,590,904 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 385 | cpp | cvMatTest.cpp | #include "opencv/highgui.h"
#include "iostream"
using namespace std;
int main( int argc, char** argv ) {
int vals[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
CvMat cvmat1;
cvInitMatHeader(&cvmat1,4,4,CV_32SC1,vals);
for (int i=0;i<4;i++){
for (int j=0;j<4;j++){
int val= CV_MAT_ELEM(cvmat1,unsigned int,i,j);
cout << val << endl;
}
}
}
|
c70c42cef59049c3469b1d5b1dcb4df29d5d9078 | c7300b157b6b01761949dc742f45c16ed5723956 | /ScMedia/MediaFileIndex.cpp | 1892e98906cd688eb4a01249d8b680f9a181fd8d | [] | no_license | chxj1980/SimpleCpp | 64f3fe2272bae90e6202ac55f7cc8ad296bfdd23 | 5134f996421721cfde73d0c76890894a0a1462bf | refs/heads/master | 2021-09-07T20:13:40.289732 | 2018-02-28T10:51:20 | 2018-02-28T10:51:20 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 12,857 | cpp | MediaFileIndex.cpp | #include "StdAfx.h"
#include "MediaFileIndex.h"
#include "FfmpegCodec.h"
#include <stdlib.h>
#include "Charset.h"
#include "MediaStream.h"
extern "C" {
#include "sqlite3.h"
};
CMediaFileIndex::CMediaFileIndex(void)
: m_pSqliteDb(NULL)
, m_pStmtRead(NULL)
, m_nFps(25)
, m_nTimebaseDen(25)
, m_nTimebaseNum(1)
, m_s64StartTime(0)
, m_nWriteTmp(0)
, m_pStmtWrite(NULL)
, m_bComplete(false)
, m_s64TotalTime(0)
, m_s64LastWriteTimestamp(0)
, m_s64FileSize(0)
, m_s64EndTimestamp(-1)
, m_s64BeginTimestamp(-1)
, m_nFpsDen(1)
, m_nFpsNum(25)
{
//debug("%s\n", __FUNCTION__);
}
CMediaFileIndex::~CMediaFileIndex(void)
{
//debug("%s\n", __FUNCTION__);
if (m_pStmtRead)
{
sqlite3_finalize(m_pStmtRead);
m_pStmtRead = NULL;
}
if (m_pStmtWrite)
{
sqlite3_finalize(m_pStmtWrite);
m_pStmtWrite = NULL;
}
if (m_pSqliteDb)
{
char *pErrorMsg;
sqlite3_exec(m_pSqliteDb, "commit", 0, 0, &pErrorMsg);
sqlite3_close(m_pSqliteDb);
m_pSqliteDb = NULL;
}
}
//都是内存索引。
//
int CMediaFileIndex::Open(char *pSzFile)
{
if (m_pSqliteDb)
{
return -2;
}
char szDbUrl[256];
memset(szDbUrl, 0, sizeof(szDbUrl));
if (pSzFile == NULL
|| strlen(pSzFile) <= 0)
{
sprintf(szDbUrl, "file:%d?mode=memory", this );
}
else{
strcpy(szDbUrl, pSzFile);
//remove(szDbUrl);
}
//m_pSqliteDb = new sqlite3;
//不存在:创建,存在:打开
int nRet = 0;
CCharset charset;
char szFileUtf8[1024];
memset(szFileUtf8, 0, sizeof(szFileUtf8));
charset.From(szDbUrl, "gb18030");
nRet = charset.To(szFileUtf8, "utf-8");
if (nRet < 0)
return -3;
nRet = sqlite3_open(szFileUtf8, &m_pSqliteDb);
if (nRet != SQLITE_OK)
return -1;
char szSql[256];
memset(szSql, 0, sizeof(szSql));
//创建参数表
sprintf(szSql, "create table Param (ID integer primary key autoincrement, name nvarchar(64), value nvarchar(64) )");
char *pError = 0;
sqlite3_exec(m_pSqliteDb, szSql, NULL, NULL, &pError);
if (pError)
{
sqlite3_free(pError);
}
//数据表 stream0, stream1 stream2 ....
memset(szSql, 0, sizeof(szSql));
sprintf(szSql, "create table Stream0 (ID integer primary key autoincrement, \
Timestamp BIGINT, \
StreamId integer, \
FrameType integer,\
Position BIGINT, \
FrameLen integer, \
FrameData blob ) \
");
sqlite3_exec(m_pSqliteDb, szSql, NULL, NULL, &pError);
if (pError)
{
sqlite3_free(pError);
}
char *zErrorMsg;
sqlite3_exec(m_pSqliteDb, "begin", 0 , 0 ,& zErrorMsg);
m_nWriteTmp = 0;
LoadParams();
sqlite3_prepare(m_pSqliteDb, "select * from Stream0", -1, &m_pStmtRead, 0);
return 0;
}
int CMediaFileIndex::Close()
{
SaveParams();
if (m_pStmtRead)
{
sqlite3_finalize(m_pStmtRead);
m_pStmtRead = NULL;
}
if (m_pStmtWrite)
{
sqlite3_finalize(m_pStmtWrite);
m_pStmtWrite = NULL;
}
if (m_pSqliteDb)
{
char *pErrorMsg=0;
sqlite3_exec(m_pSqliteDb, "commit", 0, 0, &pErrorMsg);
sqlite3_close(m_pSqliteDb);
m_pSqliteDb = NULL;
}
return 0;
}
int CMediaFileIndex::Save(char *pSzFile)
{
if (!pSzFile || strlen(pSzFile) <= 0)
{
}
SaveParams();
return 0;
}
int CMediaFileIndex::Write(int nId, int64 s64Timestamp , int nStreamId, int nFrameType, int64 s64Pos, char* pData, int &nDataLen)
{
if (!m_pSqliteDb)
return -1;
if (m_s64BeginTimestamp < 0)
{
m_s64BeginTimestamp = s64Timestamp;
}
sqlite3_stmt *pStmt = NULL;//写二进制数据时要用的结构
sqlite3_prepare( m_pSqliteDb, "insert into Stream0( timestamp, StreamId, FrameType, Position, FrameLen) values( ?, ?, ?, ?, ? )",
-1, &pStmt, 0 );//准备插入数据
sqlite3_bind_int64(pStmt, 1, s64Timestamp);
sqlite3_bind_int(pStmt, 2, nStreamId);
sqlite3_bind_int(pStmt, 3, nFrameType);
sqlite3_bind_int64(pStmt, 4, s64Pos);
sqlite3_bind_int64(pStmt, 5, nDataLen);
//sqlite3_bind_blob( pStmt, 2, pFrame, nLen, NULL ); //把内容和字段绑定
int nRet = 0;
nRet = sqlite3_step( pStmt );//执行
sqlite3_finalize( pStmt );//释放内存
pStmt = NULL;
if (nRet != SQLITE_DONE)
{
const char *pErrorMsg = 0;
pErrorMsg = sqlite3_errmsg(m_pSqliteDb);
debug("%s, error: %s\n", __FUNCTION__, pErrorMsg);
return -1;
}
m_nWriteTmp++;
if (m_nWriteTmp %5000 == 0)
{
char *pErrorMsg = 0;
sqlite3_exec(m_pSqliteDb, "commit", 0, 0, &pErrorMsg);
sqlite3_exec(m_pSqliteDb, "begin", 0, 0, &pErrorMsg);
m_nWriteTmp = 0;
}
m_s64LastWriteTimestamp = s64Timestamp;
m_s64TotalTime = m_s64LastWriteTimestamp * 1000* m_nTimebaseNum/m_nTimebaseDen;
m_s64EndTimestamp = s64Timestamp;
return 0;
}
int CMediaFileIndex::Read(int &nId, int64 &s64Timestamp , int &nStreamId, int &nFrameType, int64 &s64Pos, char* pData, int &nDataLen)
{
if (!m_pSqliteDb )
return -1;
if (!m_pStmtRead)
{//没有, 重新 读取
return -1;
}
if (!m_pStmtRead)
return -1;
//一次取一行
int result = sqlite3_step ( m_pStmtRead );
if (result != SQLITE_ROW)
{
if (result == SQLITE_DONE)
{
sqlite3_finalize(m_pStmtRead);
m_pStmtRead = NULL;
//sqlite3_reset(m_pStmtRead);
}
return -2;
}
s64Timestamp = sqlite3_column_int64( m_pStmtRead, 1 );
nStreamId = sqlite3_column_int( m_pStmtRead, 2 );
nFrameType = sqlite3_column_int( m_pStmtRead, 3 );
s64Pos = sqlite3_column_int( m_pStmtRead, 4 );
nDataLen = sqlite3_column_int( m_pStmtRead, 5 );
/*
const void * pData = sqlite3_column_blob ( m_pStmtRead, 2 );
int nDataLen = sqlite3_column_bytes ( m_pStmtRead, 2 );
memcpy(pFrame, pData, nDataLen);
nLen = nDataLen;
*/
//debug("%s: timestamp: %I64d, Type: %d, Pos: %I64d, len: %d\n", __FUNCTION__, s64Timestamp, nFrameType, s64Pos, nDataLen);
return nDataLen;
}
int CMediaFileIndex::Seek(int64 s64Time, int nFlag/*=0*/)
{
int64 s64Timestamp = 0;
s64Timestamp = TimeToTimestamp(s64Time);
SeekToTimestamp(s64Timestamp, nFlag);
return 0;
}
int CMediaFileIndex::SeekToTimestamp(int64 s64Timestamp, int nFlag/*=0*/)
{
if (!m_pSqliteDb)
return -1;
char *pError = 0;
char **pResult = 0;
int nRows = 0, nCols = 0;
if (s64Timestamp < m_s64BeginTimestamp)
{
s64Timestamp = m_s64BeginTimestamp;
}
else if (s64Timestamp > m_s64EndTimestamp)
{
s64Timestamp = m_s64EndTimestamp;
}
char szSql[1024];
memset(szSql, 0, sizeof(szSql));
if ( !(nFlag & eSSF_Any) )
{
if ( nFlag &eSSF_Backward)
{
sprintf(szSql, "select * from Stream0 where timestamp >= \
(select timestamp from Stream0 where timestamp <= %I64d and FrameType=%d order by Timestamp Desc limit 1)",
s64Timestamp, eFFT_I);
}
else
{
sprintf(szSql, "select * from Stream0 where timestamp >= \
(select timestamp from Stream0 where timestamp >= %I64d and FrameType=%d limi 1)",
s64Timestamp, eFFT_I);
}
}
else
{
sprintf(szSql, "select * from Stream0 where timestamp >= %I64d ", s64Timestamp);
}
if (m_pStmtRead)
{
sqlite3_finalize(m_pStmtRead);
}
sqlite3_prepare(m_pSqliteDb, szSql, -1, &m_pStmtRead, 0);
return 0;
}
int CMediaFileIndex::SetFps(int nFps)
{
m_nFps = nFps;
return m_nFps;
}
int CMediaFileIndex::GetFps()
{
return m_nFps;
}
int64 CMediaFileIndex::TimeToTimestamp(int64 s64Time)
{
int64 s64Timestamp = 0;
s64Timestamp = s64Time*m_nTimebaseDen/1000.0/m_nTimebaseNum;
return s64Timestamp;
}
int64 CMediaFileIndex::TimestampToTime(int64 s64Timestamp)
{
int64 s64Time=0;
s64Time = s64Timestamp*(1000*m_nTimebaseNum/m_nTimebaseDen);
return s64Time;
}
int CMediaFileIndex::Flush()
{
if (!m_pSqliteDb)
return -1;
if (m_pStmtWrite)
{
char *pErrorMsg=0;
sqlite3_exec(m_pSqliteDb, "commit", 0, 0, &pErrorMsg);
sqlite3_exec(m_pSqliteDb, "begin", 0, 0, &pErrorMsg);
}
//SaveParams();
return 0;
}
void CMediaFileIndex::SaveParams()
{
char szValue[1024];
//m_s64TotalTime = m_s64LastWriteTimestamp*1000*m_nTimebaseNum/m_nTimebaseDen;
memset(szValue, 0, sizeof(szValue));
sprintf(szValue, "%I64d", m_s64TotalTime);
SaveParam("TotalTime", szValue);
memset(szValue, 0, sizeof(szValue));
sprintf(szValue, "%d", m_bComplete);
SaveParam("Complete", szValue);
memset(szValue, 0, sizeof(szValue));
sprintf(szValue, "%I64d", m_s64FileSize);
SaveParam("FileSize", szValue);
memset(szValue, 0, sizeof(szValue));
sprintf(szValue, "%I64d", m_s64BeginTimestamp);
SaveParam("BeginTimestamp", szValue);
memset(szValue, 0, sizeof(szValue));
sprintf(szValue, "%I64d", m_s64EndTimestamp);
SaveParam("EndTimestamp", szValue);
memset(szValue, 0, sizeof(szValue));
sprintf(szValue, "%d", m_nTimebaseNum);
SaveParam("TimebaseNum", szValue);
memset(szValue, 0, sizeof(szValue));
sprintf(szValue, "%d", m_nTimebaseDen);
SaveParam("TimebaseDen", szValue);
memset(szValue, 0, sizeof(szValue));
sprintf(szValue, "%d", m_nFpsNum);
SaveParam("FpsNum", szValue);
memset(szValue, 0, sizeof(szValue));
sprintf(szValue, "%d", m_nFpsDen);
SaveParam("FpsDen", szValue);
}
void CMediaFileIndex::LoadParams()
{
char szValue[1024];
memset(szValue, 0, sizeof(szValue));
LoadParam("TotalTime", szValue);
sscanf(szValue, "%I64d", &m_s64TotalTime);
memset(szValue, 0, sizeof(szValue));
LoadParam("Complete", szValue);
sscanf(szValue, "%d", &m_bComplete);
memset(szValue, 0, sizeof(szValue));
LoadParam("FileSize", szValue);
sscanf(szValue, "%I64d", &m_s64FileSize);
memset(szValue, 0, sizeof(szValue));
LoadParam("BeginTimestamp", szValue);
sscanf(szValue, "%I64d", &m_s64BeginTimestamp);
memset(szValue, 0, sizeof(szValue));
LoadParam("EndTimestamp", szValue);
sscanf(szValue, "%I64d", &m_s64EndTimestamp);
memset(szValue, 0, sizeof(szValue));
LoadParam("TimebaseNum", szValue);
sscanf(szValue, "%d", &m_nTimebaseNum);
memset(szValue, 0, sizeof(szValue));
LoadParam("TimebaseDen", szValue);
sscanf(szValue, "%d", &m_nTimebaseDen);
memset(szValue, 0, sizeof(szValue));
LoadParam("FpsDen", szValue);
sscanf(szValue, "%d", &m_nFpsDen);
memset(szValue, 0, sizeof(szValue));
LoadParam("FpsNum", szValue);
sscanf(szValue, "%d", &m_nFpsNum);
}
int CMediaFileIndex::SaveParam(char *pSzName, char *pSzValue)
{
if (!m_pSqliteDb)
return -1;
int nRet = 0;
if (IsParamExist(pSzName))
{
nRet = UpdateParam(pSzName, pSzValue);
}
else
{
nRet = InsertParam(pSzName, pSzValue);
}
return nRet;
}
int CMediaFileIndex::LoadParam(char *pSzName, char *pSzValue)
{
if (!m_pSqliteDb)
return -1;
int nRet = 0;
bool bExist = false;
char *pError = 0;
char **pResult = 0;
int nRows = 0, nCols = 0;
char *pSzSql = new char[1024];
memset(pSzSql, 0, 1024);
sprintf(pSzSql, "select * from param where name='%s' ", pSzName );
sqlite3_get_table(m_pSqliteDb, pSzSql, &pResult, &nRows, &nCols, &pError);
if (pError)
{
sqlite3_free(pError);
}
//TRACE("rows: %d, cols: %d, \n", nRows, nCols );
if (nRows > 0)
{
nRet = 0;
strcpy(pSzValue, pResult[3+2]);
}
else
{
nRet = -1;
}
sqlite3_free_table(pResult);
delete pSzSql;
//TRACE("%s: %s, %s \n", __FUNCTION__, pSzName, pSzValue);
return nRet;
}
bool CMediaFileIndex::IsParamExist(char *pSzName)
{
if (!m_pSqliteDb)
{
return false;
}
bool bExist = false;
char *pError = 0;
char **pResult = 0;
int nRows = 0, nCols = 0;
char *pSzSql = new char[1024];
memset(pSzSql, 0, 1024);
sprintf(pSzSql, "select * from param where name='%s' ", pSzName );
sqlite3_get_table(m_pSqliteDb, pSzSql, &pResult, &nRows, &nCols, &pError);
if (pError)
{
sqlite3_free(pError);
}
//TRACE("rows: %d, cols: %d, \n", nRows, nCols );
if (nRows > 0)
{
bExist = true;
}
sqlite3_free_table(pResult);
delete pSzSql;
return bExist;
}
int CMediaFileIndex::InsertParam(char *pSzName, char *pSzValue)
{
if (!m_pSqliteDb)
return -1;
int nRet = 0;
char *pError = 0;
char *pSzSql = new char[1024];
memset(pSzSql, 0, 1024);
sprintf(pSzSql, "insert into param (name, value) values('%s', '%s')", pSzName, pSzValue);
sqlite3_exec(m_pSqliteDb, pSzSql, NULL, NULL, &pError);
if (pError)
{
sqlite3_free(pError);
nRet = -1;
}
delete pSzSql;
//TRACE("%s: %s, %s \n", __FUNCTION__, pSzName, pSzValue);
return nRet;
}
int CMediaFileIndex::UpdateParam(char *pSzName, char *pSzValue)
{
if (!m_pSqliteDb)
return -1;
int nRet = 0;
char *pError = 0;
char *pSzSql = new char[1024];
memset(pSzSql, 0, 1024);
sprintf(pSzSql, "update param set value='%s' where name='%s'", pSzValue, pSzName );
sqlite3_exec(m_pSqliteDb, pSzSql, NULL, NULL, &pError);
if (pError)
{
sqlite3_free(pError);
nRet = -1;
}
delete pSzSql;
//TRACE("%s: %s, %s \n", __FUNCTION__, pSzName, pSzValue);
return nRet;
}
void CMediaFileIndex::SetComplete( bool bComplete/*=false*/ )
{
m_bComplete = bComplete;
}
int64 CMediaFileIndex::GetTotalTime()
{
return m_s64TotalTime;
}
bool CMediaFileIndex::IsComplete()
{
return m_bComplete;
}
int64 CMediaFileIndex::GetFileSize()
{
return m_s64FileSize;
}
void CMediaFileIndex::SetFileSize(int64 s64Size)
{
m_s64FileSize = s64Size;
}
void CMediaFileIndex::SetTimebase( int nNum, int nDen )
{
m_nTimebaseNum = nNum;
m_nTimebaseDen = nDen;
}
|
ef408a88c8b98def205b63d63a58ce8b911bc2b8 | c703a08d76783d68dc7f8b16ba445c26aee74cef | /HackerEarth/Practice/Graphs/one_way_street.cpp | dd3b189bfaba28828cf1eb0918903b023dd00d48 | [] | no_license | romilpunetha/Online-Judges | 7ab14efde8180a4cc0d22a263159b2c5486122d7 | f1eb05795e4eecad5910c534226f61d920f53a4d | refs/heads/master | 2023-08-18T01:16:15.299862 | 2023-08-09T13:48:25 | 2023-08-09T13:48:25 | 67,865,026 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,413 | cpp | one_way_street.cpp | #include <bits/stdc++.h>
#define endl '\n'
#define inf INT_MAX
#define pb push_back
#define der(c, x) ((c).find(x) != (c).end())
#define base 999983
#define baseinv 943912055
#define ff first
#define ss second
#define V vector
#define L list
#define P pair
#define MP map
#define ST set
#define UM unordered_map
#define MM multimap
#define UMM unordered_multimap
#define MS multiset
#define US unordered_set
#define UMS unordered_multiset
#define PQ priority_queue
#define Graph list<int> *
#define tr1(x) cerr << #x << ": " << x << endl;
#define tr2(x, y) cerr << #x << ": " << x << " | " << #y << ": " << y << endl;
#define tr3(x, y, z) cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl;
#define tr4(a, b, c, d) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl;
#define tr5(a, b, c, d, e) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << endl;
#define tr6(a, b, c, d, e, f) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << " | " << #f << ": " << f << endl;
#define all(a) (a).begin(), (a).end()
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef double dbl;
typedef long double ldbl;
ll maxn = 1e5 + 10, ln = 20;
V<V<int> > pa;
V<bool> visited;
V<int> level;
Graph g;
void dfs(int root, int parent, int depth) {
if (visited[root]) return;
visited[root] = 1;
level[root] = depth;
pa[0][root] = parent;
for (auto &it : g[root]) {
dfs(it, root, depth + 1);
}
}
ll lca(ll u, ll v) {
if (level[u] < level[v]) swap(u, v);
for (int i = ln - 1; i >= 0; i--) {
if (level[u] - (1 << i) >= level[v]) {
u = pa[i][u];
}
}
if (u == v) return u;
for (int i = ln - 1; i >= 0; i--) {
if (pa[i][u] != -1 && pa[i][u] != pa[i][v]) {
u = pa[i][u];
v = pa[i][v];
}
}
return pa[0][u];
}
int main() {
ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int test;
cin >> test;
while (test--) {
int n;
cin >> n;
g = new L<int>[n];
visited = V<bool>(maxn, 0);
pa = V<V<int> >(ln, V<int>(maxn, -1));
level = V<int>(maxn, 0);
for (int i = 0; i < n - 1; i++) {
int u, v;
cin >> u >> v;
u--, v--;
g[u].pb(v);
g[v].pb(u);
}
dfs(0, -1, 0);
for (int i = 1; i < ln; i++) {
for (int j = 0; j < n; j++) {
if (pa[i - 1][j] != -1) {
pa[i][j] = pa[i - 1][pa[i - 1][j]];
}
}
}
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
u--, v--;
int common = lca(u, v);
if (common == u || common == v) {
if (level[u] < level[v])
cout << 2 * (level[v] - level[u]) - 1 << endl;
else
cout << 2 * (level[u] - level[v]) << endl;
} else {
int cnt = level[u] + level[v] - 2 * level[common];
cout << 2 * cnt - 1 << endl;
}
}
}
return 0;
}
|
46e95a2a81f0c1c0b37c26ce7799a6966bb3f686 | 73d9d0441125e1fd333d11720fe58bde73405971 | /Fandi/two.h | 51a2e36a79a5e764a2cc37b032b584cd2c429639 | [] | no_license | fadhilelrizanda/pemrog2 | 4f3aa5080bfe016c7536cc8493f0a25b4eb1a402 | c6c3340cf2bb71cd2b6d58644af806d62e11a620 | refs/heads/master | 2022-12-29T06:51:21.378079 | 2020-10-12T05:29:47 | 2020-10-12T05:29:47 | 293,421,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 189 | h | two.h | #include <iostream>
using namespace std;
class Two
{
public:
int x;
char a;
Two(int q, char w);
int getX();
char getA();
void setX(int q);
void setA(char w);
}; |
537978c10ae14b1cd9da23681bfe83497857fe19 | 16e61a39fdacbea0db86958ea5d5e4dbea684bdb | /src/tpx3jui/tpx3jui_SpidrDaqJ.cpp | ba0098c19537798e23b12425980bfb3c5b9dd4d4 | [] | no_license | idarraga/TPX3JUI | 17711d28a80a43fa8b5f284d67c765b18e7a06b6 | 1443635918920a0ed936398f8a7e72cf475d3451 | refs/heads/master | 2021-01-10T20:05:12.406962 | 2014-01-29T13:11:36 | 2014-01-29T13:11:36 | 15,702,818 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,442 | cpp | tpx3jui_SpidrDaqJ.cpp | #ifndef __cplusplus
#define __cplusplus
#endif
#include "tpx3jui_SpidrDaqJ.h"
// TPX3
#include "SpidrController.h"
#include "SpidrDaq.h"
#include "tpx3defs.h"
#include "dacsdescr.h"
#include <string>
//#include <linux/j>
using namespace std;
// The globals
SpidrController * g_spidrController;
SpidrDaq * g_daq;
JNIEXPORT void JNICALL Java_tpx3jui_SpidrDaqJ_resetDevice
(JNIEnv *, jobject, jint dev_nr) {
g_spidrController->resetDevice((int) dev_nr);
}
JNIEXPORT void JNICALL Java_tpx3jui_SpidrDaqJ_resetDevices
(JNIEnv *, jobject) {
g_spidrController->resetDevices();
}
JNIEXPORT jint JNICALL Java_tpx3jui_SpidrDaqJ_getDeviceId
(JNIEnv *, jobject, jint dev_nr) {
int devId;
g_spidrController->getDeviceId((int)dev_nr, &devId);
return (jint)(devId);
}
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_setSenseDac
(JNIEnv *, jobject, jint dev_nr, jint dac_code) {
bool ret = g_spidrController->setSenseDac( dev_nr, dac_code );
return (jboolean) ret;
}
JNIEXPORT jint JNICALL Java_tpx3jui_SpidrDaqJ_getDac
(JNIEnv *, jobject, jint dev_nr, jint dac_code) {
int dac_val;
g_spidrController->getDac((int)dev_nr, (int)dac_code, &dac_val);
return (jint) dac_val;
}
JNIEXPORT void JNICALL Java_tpx3jui_SpidrDaqJ_setDac
(JNIEnv *, jobject, jint dev_nr, jint dac_code, jint dac_val) {
g_spidrController->setDac((int)dev_nr, (int)dac_code, (int)dac_val);
}
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_ChipConnect
(JNIEnv *, jobject) {
jboolean conn = false;
g_spidrController =
new SpidrController( 192,
168,
100,
10,
50000 );
if( g_spidrController->isConnected() ) {
conn = true;
}
return conn;
}
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_ChipDisconnect
(JNIEnv *, jobject){
if ( g_spidrController ) {
delete g_spidrController;
g_spidrController = 0;
}
return true;
}
JNIEXPORT jint JNICALL Java_tpx3jui_SpidrDaqJ_getDeviceCount
(JNIEnv *, jobject) {
int devCount;
g_spidrController->getDeviceCount( &devCount );
return (jint) (devCount);
}
JNIEXPORT jint JNICALL Java_tpx3jui_SpidrDaqJ_getDacCount
(JNIEnv *, jobject) {
return (jint) TPX3_DAC_COUNT_TO_SET;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: sequentialReadout
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_sequentialReadout
(JNIEnv *, jobject, jint tokens){
bool ret = g_spidrController->sequentialReadout( (int) tokens );
return (jboolean) ret;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: datadrivenReadout
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_datadrivenReadout
(JNIEnv *, jobject){
bool ret = g_spidrController->datadrivenReadout();
return (jboolean) ret;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: pauseReadout
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_pauseReadout
(JNIEnv *, jobject) {
bool ret = g_spidrController->pauseReadout();
return (jboolean) ret;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: dacName
* Signature: (I)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_tpx3jui_SpidrDaqJ_dacName
(JNIEnv * env, jobject, jint dac_code) {
string name = g_spidrController->dacName( dac_code );
return env->NewStringUTF( name.c_str() );
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: dacMax
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_tpx3jui_SpidrDaqJ_dacMax
(JNIEnv *, jobject, jint dac_code){
int max = g_spidrController->dacMax( dac_code );
return (jint) max;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: getAdc
* Signature: (III)Z
*/
JNIEXPORT jint JNICALL Java_tpx3jui_SpidrDaqJ_getAdc
(JNIEnv *, jobject, jint dev_nr, jint nr_of_samples) {
int adc_val;
g_spidrController->getAdc( (int)dev_nr, &adc_val, (int)nr_of_samples );
return (jint)(adc_val);
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: getRemoteTemp
* Signature: (I)Z
*/
JNIEXPORT jint JNICALL Java_tpx3jui_SpidrDaqJ_getRemoteTemp
(JNIEnv *, jobject){
int val;
g_spidrController->getRemoteTemp( &val );
return val;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: getLocalTemp
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_getLocalTemp
(JNIEnv *, jobject, jint) {
return true;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: getAvdd
* Signature: (III)Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_getAvdd
(JNIEnv *, jobject, jint, jint, jint) {
return true;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: getDvdd
* Signature: (III)Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_getDvdd
(JNIEnv *, jobject, jint, jint, jint) {
return true;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: getBiasVoltage
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_getBiasVoltage
(JNIEnv *, jobject, jint) {
return true;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: getVdda
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_getVdda
(JNIEnv *, jobject, jint) {
return true;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: getTpPeriodPhase
* Signature: (I[I)Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_getTpPeriodPhase
(JNIEnv * env, jobject, jint dev_nr, jintArray period__phase_2pars ) {
//jsize len = env->GetArrayLength(period__phase);
jboolean status = true;
// Get the current values
jboolean isCopy;
jint * vals = env->GetIntArrayElements(period__phase_2pars, &isCopy);
// Request the new ones
status = g_spidrController->getTpPeriodPhase( (int)dev_nr, &vals[0], &vals[1] );
// Set the new values in the array
env->SetIntArrayRegion(period__phase_2pars, 0, 2, vals);
return status;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: setTpPeriodPhase
* Signature: (III)Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_setTpPeriodPhase
(JNIEnv *, jobject, jint dev_nr, jint period, jint phase) {
jboolean status = true;
status = g_spidrController->setTpPeriodPhase((int)dev_nr, (int)period, (int)phase);
return status;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: getTpNumber
* Signature: (I[I)Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_getTpNumber
(JNIEnv * env, jobject, jint dev_nr, jintArray number) {
jboolean status = true;
int l_number;
status = g_spidrController->getTpNumber( (int)dev_nr, &l_number );
// Set the values in the array
jint * vals = new jint;
*vals = (jint)l_number;
env->SetIntArrayRegion(number, 0, 2, vals);
return status;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: setTpNumber
* Signature: (II)Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_setTpNumber
(JNIEnv *, jobject, jint dev_nr, jint number) {
jboolean status = true;
status = g_spidrController->setTpNumber( (int)dev_nr, (int)number );
return status;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: setCtprBit
* Signature: (II)Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_setCtprBit
(JNIEnv *, jobject, jint column, jint val = 1) {
jboolean status = true;
status = g_spidrController->setCtprBit( (int) column, (int)val );
return status;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: setCtprBits
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_setCtprBits
(JNIEnv *, jobject, jint val) {
jboolean status = true;
status = g_spidrController->setCtprBits( (int)val );
return status;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: setCtpr
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_setCtpr
(JNIEnv *, jobject, jint dev_nr) {
jboolean status = true;
status = g_spidrController->setCtpr( (int)dev_nr );
return status;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: getCtpr
* Signature: (I[C)Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_getCtpr
(JNIEnv *, jobject, jint dev_nr, jcharArray ctpr) {
jboolean status = true;
//unsigned char ** l_ctpr;
//status = g_spidrController->getCtpr( (int)dev_nr, l_ctpr );
return status;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: resetPixelConfig
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_tpx3jui_SpidrDaqJ_resetPixelConfig
(JNIEnv *, jobject) {
g_spidrController->resetPixelConfig();
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: setPixelThreshold
* Signature: (III)Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_setPixelThreshold
(JNIEnv *, jobject, jint x, jint y, jint threshold) {
jboolean status = true;
status = g_spidrController->setPixelThreshold((int) x, (int) y, (int) threshold);
return status;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: setPixelTestEna
* Signature: (IIZ)Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_setPixelTestEna
(JNIEnv *, jobject, jint x = ALL_PIXELS, jint y = ALL_PIXELS, jboolean b = true) {
jboolean status = true;
status = g_spidrController->setPixelTestEna( (int)x, (int)y, (bool)b );
return status;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: setPixelMask
* Signature: (IIZ)Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_setPixelMask
(JNIEnv *, jobject, jint x = ALL_PIXELS, jint y = ALL_PIXELS, jboolean b = true) {
jboolean status = true;
status = g_spidrController->setPixelMask( (int)x, (int)y, (bool)b );
return status;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: setPixelConfig
* Signature: (II)Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_setPixelConfig
(JNIEnv *, jobject, jint dev_nr, jint cols_per_packet = 2) {
jboolean status = true;
status = g_spidrController->setPixelConfig( (int)dev_nr, (int) cols_per_packet );
return status;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: getPixelConfig
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_getPixelConfig
(JNIEnv *, jobject, jint dev_nr) {
jboolean status = true;
status = g_spidrController->getPixelConfig( (int)dev_nr );
return status;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: resetPixels
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL Java_tpx3jui_SpidrDaqJ_resetPixels
(JNIEnv *, jobject, jint dev_nr) {
jboolean status = true;
status = g_spidrController->resetPixels( (int)dev_nr );
return status;
}
/*
* Class: tpx3jui_SpidrDaqJ
* Method: pixelConfig
* Signature: ()[C
*/
JNIEXPORT jcharArray JNICALL Java_tpx3jui_SpidrDaqJ_pixelConfig
(JNIEnv *, jobject) {
jcharArray config;
//unsigned char * l_config = g_spidrController->pixelConfig();
return config;
}
|
0205bd0cd7c534a930a7e0d32e8bf012fd9b0658 | 00add89b1c9712db1a29a73f34864854a7738686 | /packages/monte_carlo/collision/photon/src/MonteCarlo_SubshellDopplerBroadenedPhotonEnergyDistribution.cpp | cfb92cdfb7ff60d1fe037e4cfb89febca4e05fd0 | [
"BSD-3-Clause"
] | permissive | FRENSIE/FRENSIE | a4f533faa02e456ec641815886bc530a53f525f9 | 1735b1c8841f23d415a4998743515c56f980f654 | refs/heads/master | 2021-11-19T02:37:26.311426 | 2021-09-08T11:51:24 | 2021-09-08T11:51:24 | 7,826,404 | 11 | 6 | NOASSERTION | 2021-09-08T11:51:25 | 2013-01-25T19:03:09 | C++ | UTF-8 | C++ | false | false | 1,807 | cpp | MonteCarlo_SubshellDopplerBroadenedPhotonEnergyDistribution.cpp | //---------------------------------------------------------------------------//
//!
//! \file MonteCarlo_SubshellDopplerBroadenedPhotonEnergyDistribution.cpp
//! \author Alex Robinson
//! \brief The subshell Doppler broadened photon energy distribution decl.
//!
//---------------------------------------------------------------------------//
// FRENSIE Includes
#include "MonteCarlo_SubshellDopplerBroadenedPhotonEnergyDistribution.hpp"
#include "Utility_DesignByContract.hpp"
namespace MonteCarlo{
// Constructor
SubshellDopplerBroadenedPhotonEnergyDistribution::SubshellDopplerBroadenedPhotonEnergyDistribution(
const Data::SubshellType interaction_subshell,
const double subshell_occupancy,
const double subshell_binding_energy )
: d_interaction_subshell( interaction_subshell ),
d_subshell_occupancy( subshell_occupancy ),
d_subshell_binding_energy( subshell_binding_energy )
{
// Make sure the interaction subshell is valid
testPrecondition( interaction_subshell != Data::INVALID_SUBSHELL &&
interaction_subshell !=Data::UNKNOWN_SUBSHELL );
// Make sure the subshell occupancy is valid
testPrecondition( subshell_occupancy > 0.0 );
// Make sure the subshell binding energy is valid
testPrecondition( subshell_binding_energy > 0.0 );
}
// Check if the distribution is complete (all subshells)
bool SubshellDopplerBroadenedPhotonEnergyDistribution::isComplete() const
{
return false;
}
} // end MonteCarlo namespace
//---------------------------------------------------------------------------//
// end MonteCarlo_SubshellDopplerBroadenedPhotonEnergyDistribution.hpp
//---------------------------------------------------------------------------//
|
514fa0332496aec0d1aaec7fc563c7d25a374ba4 | fd3df43d126a3fa06b1ae5c85eb06c8303f5ae98 | /topcoder/593/250/main.cpp | 893d92e621aa6c65bc537db8f717dd867aef38d3 | [] | no_license | shinejose/online-judge-code | 2d336a12a159e6199aeaffa6f5118ef226b51a4c | e0d9047b6ec3a25eaba91f530947c3481815c934 | refs/heads/master | 2021-01-13T02:03:15.122691 | 2014-10-04T20:55:40 | 2014-10-04T20:55:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 762 | cpp | main.cpp | #include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<memory.h>
#include<algorithm>
#include<functional>
using namespace std;
#define fill(x,y) (memset(x,y,sizeof(x)))
#define sz(x) ((int) (x).size())
class
RaiseThisBarn
{
private:
public:
int calc(string str)
{
int n = str.size();
int count =0 ;
int ans =0 ;
for(int i=0;i<n;i++)
if(str[i]=='c')
count ++;
if(( count %2 ) != 0 )
return 0;
else
{
int count2 =0 ;
for(int i=0;i<n;i++)
{
if(str[i] =='c')
count2 ++;
if( i <n-1 &&i>0 &&count2==count/2 && str[i] == '.' )
{
ans ++;
}
}
return ans +1 ;
}
}
};
int main(int argc,char** argv)
{
return 0;
}
|
1278d8e4ef3977911dc01a8b3fb9e169f7345789 | 9fbab236cc14ec842fc1bd53d599009d3824fd3c | /Rush1DataOnly/Network.cpp | 0617674502a2eab7a3cd451e3e1709c7aab6aa7f | [] | no_license | So00/CPP | 7655cd55f56a6d3f69f88922f8257f16b1d434e0 | 751c33b5f164582be9f1584a2163d557642e7cdd | refs/heads/master | 2020-05-01T19:05:53.525740 | 2019-04-07T10:27:09 | 2019-04-07T10:27:09 | 177,639,562 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,080 | cpp | Network.cpp | #include "Network.hpp"
Network::Network(void)
{
return;
}
Network::Network(Network const & src)
{
*this = src;
return;
}
Network::~Network(void)
{
return;
}
Network & Network::operator=(Network const & rhs)
{
static_cast<void>(rhs);
return (*this);
}
void Network::fillActive(std::string act, std::string resp, std::string add)
{
std::string parseAct = act + " ";
std::string key = "Connection " + add;
parseAct += resp.substr(resp.find("inet ") + 5, resp.find("netmask") - 6 - resp.find("inet "));
this->_map["Network"]._data[key] = parseAct;
resp = resp.erase(0, resp.find("broadcast"));
parseAct = resp.substr(resp.find(" ") + 1, resp.find("\n") - resp.find(" ") - 1);
key = "Broadcast" + add;
this->_map["Network"]._data[key] = parseAct;
}
void Network::fillInactive(std::string act, std::string add)
{
std::string parseAct = act + " inactive";
std::string key = "Connection " + add;
this->_map["Network"]._data[key] = parseAct;
key = "Broadcast " + add;
this->_map["Network"]._data[key] = parseAct;
}
void Network::createData()
{
std::string split(this->_top);
split = split.erase(0, split.find("Networks:"));
split = split.erase(split.find("\n"), std::string::npos);
std::string out = split.substr(split.find("/") + 1, split.find("M") - split.find("/"));
this->_map["Network"]._data["Packets out"] = out;
split = split.erase(0, split.find(",") + 1);
std::string in = split.substr(split.find("/") + 1, split.find("M") - split.find("/"));
this->_map["Network"]._data["Packets in"] = in;
std::string en0 = this->exec("ifconfig en0");
if (en0.find("inactive") == std::string::npos)
this->fillActive("en0", en0, "Ethernet");
else
this->fillInactive("en0", "Ethernet");
std::string en1 = this->exec("ifconfig en1");
if (en1.find("inactive") == std::string::npos)
this->fillActive("en1", en1, "Wifi");
else
this->fillInactive("en1", "Wifi");
}
|
7d9ea2e9b316bf863964848c3ee80af91b21b436 | 3e1d99ff9d80cf10f363cc6b35b69ec18fd27cce | /NppExec/src/cpp/StrSplitT.h | e9b7388a9f402cbed378889e10d3d1572e2bf5eb | [] | no_license | d0vgan/nppexec | 09a4a02981667707a4d7f33a2111f5921f054b72 | 796f643e9e7fdac7f21c8f6f72350cb3b599a89a | refs/heads/master | 2023-08-17T16:28:59.853598 | 2023-08-14T15:44:28 | 2023-08-14T15:44:28 | 124,396,499 | 113 | 27 | null | 2023-09-13T10:04:21 | 2018-03-08T13:36:30 | C++ | UTF-8 | C++ | false | false | 14,974 | h | StrSplitT.h | #ifndef _str_split_t_h_
#define _str_split_t_h_
//----------------------------------------------------------------------------
#include "CStrT.h"
#include "CListT.h"
namespace StrSplitT
{
inline bool is_any_space_char(char ch)
{
switch ( ch )
{
case ' ':
case '\t':
case '\v':
case '\f':
return true;
}
return false;
}
inline bool is_any_space_char(wchar_t ch)
{
switch ( ch )
{
case L' ':
case L'\t':
case L'\v':
case L'\f':
return true;
}
return false;
}
}
// split to args, considering quotes
template <class T> int StrSplitToArgs(const T* str,
CListT< CStrT<T> >& outList, int max_items = 0)
{
outList.Clear();
if ( str )
{
const int MODE_TABSPACE = 0;
const int MODE_CHARACTER = 1;
const int MODE_DBLQUOTES = 2;
const int MODE_SGLQUOTE1 = 3;
const int MODE_SGLQUOTE2 = 4;
const T CHAR_DBLQUOTES = '\"';
const T CHAR_SGLQUOTE1 = '\'';
const T CHAR_SGLQUOTE2 = '`';
int mode = MODE_TABSPACE;
CStrT<T> S;
while ( *str )
{
const T ch = *str;
if ( mode == MODE_DBLQUOTES )
{
if ( ch == CHAR_DBLQUOTES )
{
mode = MODE_CHARACTER;
}
else
{
S.Append( ch );
}
++str;
continue;
}
if ( mode == MODE_SGLQUOTE1 )
{
if ( ch == CHAR_SGLQUOTE1 )
{
mode = MODE_CHARACTER;
}
else
{
S.Append( ch );
}
++str;
continue;
}
if ( mode == MODE_SGLQUOTE2 )
{
if ( ch == CHAR_SGLQUOTE2 )
{
mode = MODE_CHARACTER;
}
else
{
S.Append( ch );
}
++str;
continue;
}
if ( mode == MODE_TABSPACE )
{
if ( StrSplitT::is_any_space_char(ch) )
{
++str;
continue;
}
else
{
if ( max_items > 0 )
{
if ( --max_items == 0 )
{
outList.Add( str );
return outList.GetCount();
}
}
mode = MODE_CHARACTER;
}
}
if ( ch == CHAR_DBLQUOTES )
{
mode = MODE_DBLQUOTES;
}
else if ( ch == CHAR_SGLQUOTE1 )
{
mode = MODE_SGLQUOTE1;
}
else if ( ch == CHAR_SGLQUOTE2 )
{
mode = MODE_SGLQUOTE2;
}
else if ( StrSplitT::is_any_space_char(ch) )
{
mode = MODE_TABSPACE;
outList.Add( S );
S.Clear();
}
else
{
S.Append( ch );
}
++str;
}
if ( mode != MODE_TABSPACE )
{
outList.Add( S );
}
}
return outList.GetCount();
}
// split to args by separator, considering quotes
template <class T> int StrSplitAsArgs(const T* str,
CListT< CStrT<T> >& outList, const T sep, int max_items = 0)
{
outList.Clear();
if ( str )
{
const int MODE_TABSPACE = 0;
const int MODE_CHARACTER = 1;
const int MODE_DBLQUOTES = 2;
const int MODE_SGLQUOTE1 = 3;
const int MODE_SGLQUOTE2 = 4;
const T CHAR_DBLQUOTES = '\"';
const T CHAR_SGLQUOTE1 = '\'';
const T CHAR_SGLQUOTE2 = '`';
int n = 0;
int mode = MODE_TABSPACE;
CStrT<T> S;
while ( *str )
{
const T ch = *str;
if ( mode == MODE_DBLQUOTES )
{
if ( ch == CHAR_DBLQUOTES )
{
mode = MODE_CHARACTER;
}
else
{
S.Append( ch );
n = S.length(); // to keep quoted spaces, if any
}
++str;
continue;
}
if ( mode == MODE_SGLQUOTE1 )
{
if ( ch == CHAR_SGLQUOTE1 )
{
mode = MODE_CHARACTER;
}
else
{
S.Append( ch );
n = S.length(); // to keep quoted spaces, if any
}
++str;
continue;
}
if ( mode == MODE_SGLQUOTE2 )
{
if ( ch == CHAR_SGLQUOTE2 )
{
mode = MODE_CHARACTER;
}
else
{
S.Append( ch );
n = S.length(); // to keep quoted spaces, if any
}
++str;
continue;
}
if ( mode == MODE_TABSPACE )
{
if ( StrSplitT::is_any_space_char(ch) )
{
++str;
continue;
}
else
{
if ( max_items > 0 )
{
if ( --max_items == 0 )
{
outList.Add( str );
return outList.GetCount();
}
}
mode = MODE_CHARACTER;
}
}
if ( ch == CHAR_DBLQUOTES )
{
mode = MODE_DBLQUOTES;
}
else if ( ch == CHAR_SGLQUOTE1 )
{
mode = MODE_SGLQUOTE1;
}
else if ( ch == CHAR_SGLQUOTE2 )
{
mode = MODE_SGLQUOTE2;
}
else if ( ch == sep )
{
mode = MODE_TABSPACE;
int i = S.length() - 1;
while ( (i >= n) && StrSplitT::is_any_space_char(S.GetAt(i)) ) --i;
S.SetSize(i + 1);
outList.Add( S );
S.Clear();
n = 0;
}
else
{
S.Append( ch );
}
++str;
}
//if ( mode != MODE_TABSPACE )
{
outList.Add( S );
}
}
return outList.GetCount();
}
template <class T> int StrSplit(const CStrT<T>& str,
const T* separator, CListT< CStrT<T> >& outList, int max_items = 0)
{
outList.Clear();
if ( str.length() > 0 )
{
int sep_len = GetStrSafeLength(separator);
if ( sep_len > 0 )
{
CStrT<T> S;
int pos2, pos1 = 0;
if (max_items > 0)
{
--max_items;
while ( (outList.GetCount() < max_items) &&
((pos2 = str.Find(separator, pos1)) >= 0) )
{
S.Assign( str.c_str() + pos1, pos2 - pos1 );
outList.Add(S);
pos1 = pos2 + sep_len;
}
}
else
{
while ( (pos2 = str.Find(separator, pos1)) >= 0 )
{
S.Assign( str.c_str() + pos1, pos2 - pos1 );
outList.Add(S);
pos1 = pos2 + sep_len;
}
}
S.Assign( str.c_str() + pos1, str.length() - pos1 );
outList.Add(S);
}
}
return outList.GetCount();
}
//----------------------------------------------------------------------------
template <class T> class CStrSplitT
{
private:
CListT< CStrT<T> > m_argList;
mutable CStrT<T> m_tempStr;
static const CStrT<T> m_emptyStr;
public:
const CStrT<T>& Arg(int index) const;
CStrT<T>& Arg(int index);
const CStrT<T>& GetArg(int index) const;
int GetArgCount() const { return m_argList.GetCount(); }
const CStrT<T>& GetArgs() const; // string of Args without Arg[0]
const CStrT<T>& GetRArgs() const; // Args in reverse order
const CStrT<T>& GetRArg(int index) const; // GetRArg(0) is not valid!
const CStrT<T>& RArg(int index) const; // RArg(0) is not valid!
CStrT<T>& RArg(int index); // RArg(0) is not valid!
bool SetArg(int index, const T* S);
bool SetArg(int index, const CStrT<T>& S);
int SplitAsArgs(const T* str, const T separator, int max_items = 0);
int SplitAsArgs(const CStrT<T>& str, const T separator, int max_items = 0);
int SplitToArgs(const T* str, int max_items = 0);
int SplitToArgs(const CStrT<T>& str, int max_items = 0);
int Split(const T* str, const T* separator, int max_items = 0);
int Split(const CStrT<T>& str, const T* separator, int max_items = 0);
};
template <class T> const CStrT<T> CStrSplitT<T>::m_emptyStr;
template <class T> const CStrT<T>& CStrSplitT<T>::Arg(int index) const
{
if ( (index >= 0) && (index < m_argList.GetCount()) )
{
CListItemT< CStrT<T> > * p = m_argList.GetFirst();
while ( p && (index--) )
{
p = p->GetNext();
}
if ( p ) return p->GetItem();
}
return m_emptyStr;
}
template <class T> CStrT<T>& CStrSplitT<T>::Arg(int index)
{
if ( (index >= 0) && (index < m_argList.GetCount()) )
{
CListItemT< CStrT<T> > * p = m_argList.GetFirst();
while ( p && (index--) )
{
p = p->GetNext();
}
if ( p ) return p->GetItem();
}
m_tempStr.Clear();
return m_tempStr;
}
template <class T> const CStrT<T>& CStrSplitT<T>::GetArg(int index) const
{
return Arg(index);
}
template <class T> const CStrT<T>& CStrSplitT<T>::GetArgs() const
{
CListItemT< CStrT<T> > * p = m_argList.GetFirst();
if ( p )
{
m_tempStr.Clear();
p = p->GetNext();
while ( p )
{
if (m_tempStr.length() > 0)
m_tempStr.Append(' ');
const CStrT<T>& S = p->GetItem();
if ( (S.Find(' ') >= 0) || (S.Find('\t') >= 0) )
{
m_tempStr.Append( '\"' );
m_tempStr.Append( S );
m_tempStr.Append( '\"' );
}
else
{
m_tempStr.Append( S );
}
p = p->GetNext();
}
return m_tempStr;
}
return m_emptyStr;
}
template <class T> const CStrT<T>& CStrSplitT<T>::GetRArgs() const
{
CListItemT< CStrT<T> > * p = m_argList.GetLast();
if ( p )
{
m_tempStr.Clear();
while ( p && (p != m_argList.GetFirst()) )
{
if (m_tempStr.length() > 0)
m_tempStr.Append(' ');
const CStrT<T>& S = p->GetItem();
if ( (S.Find(' ') >= 0) || (S.Find('\t') >= 0) )
{
m_tempStr.Append( '\"' );
m_tempStr.Append( S );
m_tempStr.Append( '\"' );
}
else
{
m_tempStr.Append( S );
}
p = p->GetPrev();
}
return m_tempStr;
}
return m_emptyStr;
}
template <class T> const CStrT<T>& CStrSplitT<T>::GetRArg(int index) const
{
return RArg(index);
}
template <class T> const CStrT<T>& CStrSplitT<T>::RArg(int index) const
{
if ( (index > 0) && (index < m_argList.GetCount()) )
{
CListItemT< CStrT<T> > * p = m_argList.GetLast();
while ( p && (--index) )
{
p = p->GetPrev();
}
if ( p ) return p->GetItem();
}
return m_emptyStr;
}
template <class T> CStrT<T>& CStrSplitT<T>::RArg(int index)
{
if ( (index > 0) && (index < m_argList.GetCount()) )
{
CListItemT< CStrT<T> > * p = m_argList.GetLast();
while ( p && (--index) )
{
p = p->GetPrev();
}
if ( p ) return p->GetItem();
}
m_tempStr.Clear();
return m_tempStr;
}
template <class T> bool CStrSplitT<T>::SetArg(int index, const T* S)
{
return SetArg( index, CStrT<T>(S) );
}
template <class T> bool CStrSplitT<T>::SetArg(int index, const CStrT<T>& S)
{
if ( (index >= 0) && (index < m_argList.GetCount()) )
{
CListItemT< CStrT<T> > * p = m_argList.GetFirst();
while ( p && index )
{
--index;
p = p->GetNext();
}
if ( p )
{
p->SetItem(S);
return true;
}
}
return false;
}
template <class T> int CStrSplitT<T>::SplitAsArgs(const T* str, const T separator, int max_items)
{
return StrSplitAsArgs( str, m_argList, separator, max_items );
}
template <class T> int CStrSplitT<T>::SplitAsArgs(const CStrT<T>& str, const T separator, int max_items)
{
return StrSplitAsArgs( str.c_str(), m_argList, separator, max_items );
}
template <class T> int CStrSplitT<T>::SplitToArgs(const T* str, int max_items)
{
return StrSplitToArgs<T>( str, m_argList, max_items );
}
template <class T> int CStrSplitT<T>::SplitToArgs(const CStrT<T>& str, int max_items)
{
return StrSplitToArgs<T>( str.c_str(), m_argList, max_items );
}
template <class T> int CStrSplitT<T>::Split(const T* str, const T* separator, int max_items)
{
return StrSplit<T>( CStrT<T>(str), separator, m_argList, max_items );
}
template <class T> int CStrSplitT<T>::Split(const CStrT<T>& str, const T* separator, int max_items)
{
return StrSplit<T>( str, separator, m_argList, max_items );
}
//----------------------------------------------------------------------------
#endif
|
0c5c5508a051b313739f0d41c157fc911fd75462 | 5c68c8c058917b76f43f02a40f0c6e1a7f3c20fe | /src/extensions/service/aextguid.h | b3453431df096d3dfd5d456e117f9ec0df6f4293 | [] | no_license | app/ananas-labs-qt4 | 388d7046abc35f70776d1ef00b0a2c9945733066 | 197abe41bed277cadb72af06ea3c5d8465e7be5a | refs/heads/master | 2020-05-17T02:54:20.073166 | 2009-05-25T16:37:41 | 2009-05-25T16:37:41 | 93,703 | 6 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 1,583 | h | aextguid.h | /****************************************************************************
** $Id: aextguid.h,v 1.1 2009/05/24 18:34:42 app Exp $
**
** Header file of the Report Result Object of Ananas
** Designer and Engine applications
**
** Created : 20070819
**
** Copyright (C) 2005-2007 Grigory Panov <grigory.panov at gmail.com>, Moscow.
** Copyright (C) 2005-2007 Ananas Project.
**
** This file is part of the Library of the Ananas
** automation accounting system.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.leaderit.ru/page=ananas or email sales@leaderit.ru
** See http://www.leaderit.ru/gpl/ for GPL licensing information.
**
** Contact org@leaderit.ru if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#ifndef AEXTGUID_H
#define AEXTGUID_H
#include "aextension.h"
#include "aobject.h"
/**
* \en
* Class for generate GUID strings from Ananas Script.
* \_en
* \ru
* \brief Генерирует строку GUID в верхенм регистре.
*
*
* \_ru
*/
class ANANAS_EXPORT aExtGUID: public AExtension
{
Q_OBJECT
public:
aExtGUID();
~aExtGUID();
public slots:
QString Generate() const;
};
#endif
|
7dcd0afc62983f3da5493a320c2a2c8f333b7cb0 | f0d22137ab4aba3a70c25b42b628e3f09743d936 | /modules/gui/qt4/components/playlist/playlist_item.hpp | 8cbe3fc82b0b32e7a4a8b2606b59f8dcecf89be8 | [] | no_license | duxq/vlc_2.1.0-vs_2010 | 6da94eac73bb70604162558e46a266f9acfc0e56 | 218172f619c9e248b709e479e5c10e197127a88e | refs/heads/master | 2021-06-18T12:02:28.079902 | 2017-06-28T02:33:56 | 2017-06-28T02:33:56 | 118,862,081 | 1 | 0 | null | 2018-01-25T04:27:09 | 2018-01-25T04:27:08 | null | UTF-8 | C++ | false | false | 2,866 | hpp | playlist_item.hpp | /*****************************************************************************
* playlist_item.hpp : Item for a playlist tree
****************************************************************************
* Copyright (C) 2006-2011 the VideoLAN team
* $Id: 2ce9c7e7dc2b8e131a7dcb374d71b25c879ab6b8 $
*
* Authors: Clément Stenac <zorglub@videolan.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifndef _PLAYLIST_ITEM_H_
#define _PLAYLIST_ITEM_H_
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <QList>
class AbstractPLItem
{
friend class PLItem; /* super ugly glue stuff */
friend class MLItem;
friend class PLModel;
friend class MLModel;
public:
virtual ~AbstractPLItem() {}
protected:
virtual int id() const = 0;
int childCount() const { return children.count(); }
int indexOf( AbstractPLItem *item ) const { return children.indexOf( item ); };
int lastIndexOf( AbstractPLItem *item ) const { return children.lastIndexOf( item ); };
AbstractPLItem *parent() { return parentItem; }
virtual input_item_t *inputItem() = 0;
void insertChild( AbstractPLItem *item, int pos = -1 ) { children.insert( pos, item ); }
void appendChild( AbstractPLItem *item ) { insertChild( item, children.count() ); } ;
virtual AbstractPLItem *child( int id ) const = 0;
void clearChildren();
QList<AbstractPLItem *> children;
AbstractPLItem *parentItem;
};
class PLItem : public AbstractPLItem
{
friend class PLModel;
public:
virtual ~PLItem();
bool hasSameParent( PLItem *other ) { return parent() == other->parent(); }
bool operator< ( PLItem& );
private:
/* AbstractPLItem */
int id() const { return i_id; };
input_item_t *inputItem() { return p_input; }
AbstractPLItem *child( int id ) const { return children.value( id ); };
/* Local */
PLItem( playlist_item_t *, PLItem *parent );
int row();
void removeChild( PLItem * );
void takeChildAt( int );
PLItem( playlist_item_t * );
void init( playlist_item_t *, PLItem * );
int i_id;
input_item_t *p_input;
};
#endif
|
9738cf0e803acb94735333d39cb87984264d33da | 877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a | /app/src/main/cpp/dir7941/dir7942/dir8062/dir8063/dir12419/file12445.cpp | 87e1d4b063a11ba2d98e96e8ccb689603a586a62 | [] | no_license | tgeng/HugeProject | 829c3bdfb7cbaf57727c41263212d4a67e3eb93d | 4488d3b765e8827636ce5e878baacdf388710ef2 | refs/heads/master | 2022-08-21T16:58:54.161627 | 2020-05-28T01:54:03 | 2020-05-28T01:54:03 | 267,468,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 115 | cpp | file12445.cpp | #ifndef file12445
#error "macro file12445 must be defined"
#endif
static const char* file12445String = "file12445"; |
b07a810eae4d7bfd43e733ec08f79931436af876 | 3bb479517af27c2cb5721e14b91e637fdf764c35 | /sign wave.cpp | 7dbbfded22e642999557296b26e534118b2d3fff | [] | no_license | Arnie09/Codechef | 17feea20d709981db05879642ac004d7e2f4c3b3 | 9626f5396b552a8e77d43f6818e8999b4c2593f8 | refs/heads/master | 2020-08-03T07:42:12.375754 | 2016-04-30T22:40:14 | 2016-04-30T22:40:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 576 | cpp | sign wave.cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{int t;
cin>>t;
while(t--)
{
int s,c,k;
cin>>s>>c>>k;
long long ans=0;
if(s==0&&c==0)
ans=0;
if(s==0&&c)
{
if(k==1)
ans=pow(2,c+1)-2;
else
ans=0;
}
else if(k>s)
ans=0;
else if(c==0)
{
ans=pow(2,s+1-k)+1;
}
else if(s>c)
{
if(k>s-c)
ans=pow(2,s-k+2)+1;
else
ans=pow(2,s-k+1)+1;
}
else if(c>=s)
{
if(k==1)
ans=pow(2,c+1)+1;
else
ans=pow(2,s+2-k)+1;
}
cout<<ans<<endl;
}
return 0;
}
|
81ed25c62b6df4952e328c44263205b71ee6ad0c | 08bdd164c174d24e69be25bf952322b84573f216 | /opencores/client/foundation classes/j2sdk-1_4_2-src-scsl/hotspot/src/share/vm/code/oopRecorder.cpp | 50b387bbd9a52ffe27e27cbd2da02c8750546fb0 | [] | no_license | hagyhang/myforthprocessor | 1861dcabcf2aeccf0ab49791f510863d97d89a77 | 210083fe71c39fa5d92f1f1acb62392a7f77aa9e | refs/heads/master | 2021-05-28T01:42:50.538428 | 2014-07-17T14:14:33 | 2014-07-17T14:14:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,178 | cpp | oopRecorder.cpp | #ifdef USE_PRAGMA_IDENT_SRC
#pragma ident "@(#)oopRecorder.cpp 1.13 03/01/23 12:00:11 JVM"
#endif
/*
* Copyright 2003 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
# include "incls/_precompiled.incl"
# include "incls/_oopRecorder.cpp.incl"
OopRecorder::OopRecorder(Arena* arena) {
_handles_arena = arena;
_handles_size = 0;
_handles = NULL;
_handles_length = 0;
_complete = false;
}
int OopRecorder::oop_size() {
_complete = true;
return _handles_length * sizeof(oop);
}
void OopRecorder::copy_to(CodeBlob* code) {
#ifdef CORE
ShouldNotReachHere();
#else
assert(_complete, "must be frozen");
code->copy_oops(_handles, _handles_length);
#endif
}
int OopRecorder::allocate_index(jobject h) {
assert(!_complete, "cannot allocate more elements after size query");
if (_handles_arena == NULL) _nesting.check();
if (_handles_size == 0) {
_handles_size = 100;
if (_handles_arena == NULL)
_handles = NEW_RESOURCE_ARRAY(jobject, _handles_size);
else
_handles = (jobject*) _handles_arena->Amalloc(_handles_size * sizeof(jobject));
} else if (_handles_length == _handles_size) {
// Expand
int new_handles_size = _handles_size * 2;
if (_handles_arena == NULL)
_handles = REALLOC_RESOURCE_ARRAY(jobject, _handles, _handles_size, new_handles_size);
else
_handles = (jobject*)_handles_arena->Arealloc(_handles, _handles_size * sizeof(jobject), new_handles_size * sizeof(jobject));
_handles_size = new_handles_size;
}
assert(_handles_size > _handles_length, "There must be room for after expanding");
_handles[_handles_length++] = h;
// indexing uses 1 as an origin--0 means null
return _handles_length;
}
int OopRecorder::find_index(jobject h) {
assert(!_complete, "cannot allocate more elements after size query");
if (h == NULL) return 0;
const int old_oops_to_check = 10;
for (int i = MAX2(0, _handles_length - old_oops_to_check); i < _handles_length; i++) {
if (_handles[i] == h) return i+1; // indexing uses 1 as an origin--0 means null
}
return allocate_index(h);
}
|
d42afc0c79e412b2bba060ec231dfded6b665ebe | 249aa1abe2e9f715260b17c3b87cb9c7cdb27e06 | /ex 38 .cpp | ad0950d49f1d698ea53e7c085c9756a69769817d | [] | no_license | ergonlima/-List-with-exercises-in-C- | d8c83f46d8e617652c09be41d024cb59a447102e | d258ea897a905a30c328175b861368d151fbffb9 | refs/heads/master | 2022-12-09T10:48:11.384991 | 2020-07-27T14:45:30 | 2020-07-27T14:45:30 | 282,926,489 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 347 | cpp | ex 38 .cpp | #include<iostream>
using namespace std;
int main()
{
int a,i=2;
bool primo=true;
cout<<"digite A: ";
cin>>a;
while(i<a)
{
if(a%i==0)
{
primo=false;
}
i++;
}if(primo==true)
{
cout<<"numero primo";
}else
{
cout<<"numero nao primo";
}
}
|
7668539e517d097b1b867db0a4825f216338c8b1 | 2d98f202e981b1a49eb37b6697170d803f2d215f | /Src/FM79979Engine/Core/Sound/SoundManager.h | b68f9116b3c9955fcf3a01fa463500b3dfbd7384 | [] | no_license | fatmingwang/FM79979 | bb1274241605f490b8e216f930a2c5aaba86f669 | 735f204bd70773c2482e15b3105a8680cf119706 | refs/heads/master | 2023-07-09T00:47:02.782514 | 2023-06-23T10:23:27 | 2023-06-23T10:23:27 | 43,816,834 | 7 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,189 | h | SoundManager.h | #pragma once
#include "OpenAlWavFile.h"
#include "OpenAlOgg.h"
#include "../XML/XMLLoader.h"
//=============================
//current do not support streaming music
//=============================
//enum eSoundDataType
//{
// eSDT_WAV = 0,
// eSDT_STREAMING,
// eSDT_NONE
//};
namespace FATMING_CORE
{
class cSoundParser:public cNamedTypedObjectVector<cBasicSound>,public ISAXCallback
{
bool ActiveOpenAL();
#if defined(IOS) || defined(ANDROID) || defined(WASM) || defined(LINUX)
ALCdevice* m_pDevice;
ALCcontext* m_pContext;
#endif
virtual void HandleElementData(TiXmlElement*e_pTiXmlElement)override;
void ProcessStreamingData();
void ProcessStaticData();
void ProcessRootDirectory();
char m_strDestDirectory[TEMP_SIZE];
float m_fVolume;
public:
DEFINE_TYPE_INFO()
//reserve for BG sound
static int m_siReserveBGSourceCount;
//how many reserver BG sound ID is used
static bool* m_spbUsedBGSourceData;
//below for sort source ID,because the source hardearw is limited,so we have to assign the source dymanic
static int m_siNumSourceID;
static ALuint* m_psuiSourceID; //whole source ID,as many as m_siNumSoundManager
static ALuint* m_psuiSourceUsingIDIndex; //as many as m_siNumSoundManager
static int m_siNumSoundManager;
static float m_sfBGMVolume;
static float m_sfSoundEffectVolume;
//I have call alutInit (0,0); in the construction while sound manager is first time to create
cSoundParser();
virtual ~cSoundParser();
//the referance should be use cResourceStamp to instead but I am lazy to fix right now
cBasicSound* AddStaticSound(NamedTypedObject*e_pRef,const char*e_strFileName);
cBasicSound* AddStreamingSound(NamedTypedObject*e_pRef,const char*e_strFileName);
cBasicSound* AddSound(NamedTypedObject*e_pRef,const char*e_strFileName,bool e_bStreaming);
cBasicSound* AddSound(const char*e_strFileName,bool e_bStreaming);
virtual NamedTypedObject* GetObjectByFileName(const char*e_strFileName)override;
void Export(const char*e_strFileName);
//for 0 to 1
void SetVolume(float e_fVolume);
float GetVolume(){ return m_fVolume; }
void Pause(bool e_bPause); //all sound pause
void Stop(); //all sound stop
void SetSpeed(float e_fSpeed);
void Update(float e_fElpaseTime);
void RemoveAllBGM();
//SimpleGLTexture could't add into cNamedTypedObjectVector
//but cBasicSound is able to do this,so release got a bit bitter,so I am override RemoveObject
//for release working decent.
virtual bool RemoveObject(int e_iIndex)override;
using cNamedTypedObjectVector<cBasicSound>::RemoveObject;
//void IOSRecordContextSet(bool e_bStartToRecord);
};
}
//
//OpenAL gain means volume. So you have to change the AL_GAIN state to change the volume of a source (you can't change the volume of a buffer as far as I have seen, and it seems strange why you would).
//
//So
//
//// To set the volume of the source to max
//alSourcef(sourceID, AL_GAIN, 1.0f);
//
//// To set it to min
//alSourcef(sourceID, AL_GAIN, 0.0f);
//
//// And halfway
//alSourcef(sourceID, AL_GAIN, 0.5f); |
ef263bacfe5567f3daf61ee4a84ce7b69075f6e0 | 5df41e87d618fc5b8f3dacc3297178c3060d3a5d | /ProyectoII/Practica1/juegoPG.cpp | 3e904dc538e8de430daa0085d7c91752ccd6629d | [] | no_license | PatriciaCabrero/Galiakberova | 56da10108fcb00fc30ae7b257704ed5e541c7d64 | a3828aa1024892c5d6ab68a70f37acc880388cf2 | refs/heads/master | 2022-06-21T08:26:04.184482 | 2020-05-07T20:59:02 | 2020-05-07T20:59:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,655 | cpp | juegoPG.cpp | #include "juegoPG.h"
#include "checkML.h"
using namespace std; // Para cualificar automaticamente con std:: los identificadores de la librería estandar
//---------------------------------------------------------------------------------------------------------------
#include "GameOver.h"
#include "Pausa.h"
#include "MenuPG.h"
#include "Nivel1.h"
#include <typeinfo>
#include "Error.h"
#include <Windows.h>
#include <shlobj.h>
#include "Muerte.h"
#include <time.h>
juegoPG::juegoPG()
{
CHAR my_documents[MAX_PATH];
HRESULT result = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, my_documents);
path = (string)my_documents;
muerto = false;
srand(time(0));
pWin = nullptr; //The window we'll be rendering to
pRender = nullptr; //The renderer by the window
try{
initSDL(pWin, pRender);
}
catch (EInitTTF &msg){ SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "ERROR", msg.mensaje().c_str(), nullptr); }
vecTexturas.resize(61);
vecPaginas.resize(6);
initMedia();
//La vida de los pjs (al ser compartida va en el juego)
vida = 300;
nieblaRect = { 600,338,400,225 };
std::string auxStr = "cmd /c ..\\videos\\intro.exe /i1004 /x0 /y0 /w" + to_string(getScreenWidth()) + " /h" + to_string(getScreenHeight()) + " /u3";
const char* c = auxStr.c_str();
std::system(c);
estados.push(new MenuPG(this,0));
delay = 0;
}
void juegoPG::initMedia(){
//Cargamos las texturas
std::string str = "Textura";
for (unsigned int i = 0; i < vecTexturas.size(); i++){
vecTexturas[i] = new TexturasSDL;
vecTexturas[i]->load(pRender, "..\\bmps\\" + (str += to_string(i + 1)) + ".png");
str = "Textura";
}
str = "Pagina";
for (unsigned int i = 0; i < vecPaginas.size(); i++) {
vecPaginas[i] = new TexturasSDL;
vecPaginas[i]->load(pRender, "..\\bmps\\" + (str += to_string(i + 1)) + ".png");
str = "Pagina";
}
//Cargamos la fuente
try{
fuente = new TexturasSDL;
fuente->loadFuente("..\\bmps\\font.ttf", 50);
//Inicializamos el color para el texto
}
catch (ELoadFont &msg){ SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "ERROR", msg.mensaje().c_str(), nullptr); }
}
juegoPG::~juegoPG()
{
closeSDL(pWin, pRender);
for (unsigned int i = 0; i < vecTexturas.size(); i++)
delete vecTexturas[i];
delete fuente;
while (!estados.empty()){
delete estados.top();
estados.pop();
}
vecTexturas.clear();
system->release();
}
//--------------------------------------------------------------------------------------------------------------------
void juegoPG::run(){
Uint32 msUpdate = 16;
std::cout << "PLAY \n";
Uint32 lastUpdate = SDL_GetTicks();
render();
handle_event();
while (!exit) {
if (SDL_GetTicks() - lastUpdate >= msUpdate) { // while(elapsed >= MSxUpdate)
estados.top()->update(SDL_GetTicks() - lastUpdate);
estados.top()->lateUpdate(SDL_GetTicks() - lastUpdate);
render();
estados.top()->updateBorrarObj();
handle_event();
lastUpdate = SDL_GetTicks();
if (muerto) cargaPartida();
}
}
if (exit) cout << "EXIT \n";
}
//----------------------------------------------------------------------------------------------------------------------
void juegoPG::handle_event(){
const Uint8 *keystate = SDL_GetKeyboardState(NULL);
input.dDS = (keystate[SDL_SCANCODE_RIGHT] && keystate[SDL_SCANCODE_UP]);
input.dDI = (keystate[SDL_SCANCODE_RIGHT] && keystate[SDL_SCANCODE_DOWN]);
input.dIS = (keystate[SDL_SCANCODE_LEFT] && keystate[SDL_SCANCODE_UP]);
input.dII = (keystate[SDL_SCANCODE_LEFT] && keystate[SDL_SCANCODE_DOWN]);
input.arriba = keystate[SDL_SCANCODE_UP];
input.abajo = keystate[SDL_SCANCODE_DOWN];
input.derecha = keystate[SDL_SCANCODE_RIGHT];
input.izquierda = keystate[SDL_SCANCODE_LEFT];
input.enter = keystate[SDL_SCANCODE_RETURN] || keystate[SDL_SCANCODE_KP_ENTER];
int StickX, StickY;
bool hayMando = true;
int MaxJoysticks = SDL_NumJoysticks();
int ControllerIndex = 0;
for (int JoystickIndex = 0; JoystickIndex < MaxJoysticks; ++JoystickIndex)
{
if (!SDL_IsGameController(JoystickIndex))
{
continue;
}
if (ControllerIndex >= 2)
{
break;
}
Controller[ControllerIndex] = SDL_GameControllerOpen(JoystickIndex);
SDL_Joystick *JoystickHandle = SDL_GameControllerGetJoystick(Controller[ControllerIndex]);
RumbleHandles[ControllerIndex] = SDL_HapticOpenFromJoystick(JoystickHandle);
ControllerIndex++;
}
if (Controller[0] != NULL){
for (int ControllerIndex = 0; ControllerIndex < 2; ++ControllerIndex){
if (Controller[ControllerIndex] != 0 && SDL_GameControllerGetAttached(Controller[ControllerIndex]))
{
// NOTE: We have a controller with index ControllerIndex.
if (!input.arriba) input.arriba = SDL_GameControllerGetButton(Controller[ControllerIndex], SDL_CONTROLLER_BUTTON_DPAD_UP);
if (!input.abajo) input.abajo = SDL_GameControllerGetButton(Controller[ControllerIndex], SDL_CONTROLLER_BUTTON_DPAD_DOWN);
if (!input.izquierda)input.izquierda = SDL_GameControllerGetButton(Controller[ControllerIndex], SDL_CONTROLLER_BUTTON_DPAD_LEFT);
if (!input.derecha) input.derecha = SDL_GameControllerGetButton(Controller[ControllerIndex], SDL_CONTROLLER_BUTTON_DPAD_RIGHT);
//input.mcraft = SDL_GameControllerGetButton(Controller[ControllerIndex], SDL_CONTROLLER_BUTTON_START);
//bool Back = SDL_GameControllerGetButton(Controller[ControllerIndex], SDL_CONTROLLER_BUTTON_BACK);
bool LeftShoulder = SDL_GameControllerGetButton(Controller[ControllerIndex], SDL_CONTROLLER_BUTTON_LEFTSHOULDER);
bool RightShoulder = SDL_GameControllerGetButton(Controller[ControllerIndex], SDL_CONTROLLER_BUTTON_RIGHTSHOULDER);
if (!input.enter) input.enter = SDL_GameControllerGetButton(Controller[ControllerIndex], SDL_CONTROLLER_BUTTON_A);
/*bool BButton = SDL_GameControllerGetButton(Controller[ControllerIndex], SDL_CONTROLLER_BUTTON_B);
bool XButton = SDL_GameControllerGetButton(Controller[ControllerIndex], SDL_CONTROLLER_BUTTON_X);
bool YButton = SDL_GameControllerGetButton(Controller[ControllerIndex], SDL_CONTROLLER_BUTTON_Y);*/
/*StickX = SDL_GameControllerGetAxis(Controller[ControllerIndex], SDL_CONTROLLER_AXIS_LEFTX);
StickY = SDL_GameControllerGetAxis(Controller[ControllerIndex], SDL_CONTROLLER_AXIS_LEFTY);*/
if (SDL_HapticRumbleInit(RumbleHandles[ControllerIndex]) != 0)
{
SDL_HapticClose(RumbleHandles[ControllerIndex]);
RumbleHandles[ControllerIndex] = 0;
}
if (input.enter || LeftShoulder)
{
if (RumbleHandles[ControllerIndex])
{
SDL_HapticRumblePlay(RumbleHandles[ControllerIndex], 0.7f, 75);
}
}
}
else
{
// TODO: This controller is note plugged in.
}
}
}
else {
hayMando = false;
}
StickX = SDL_GameControllerGetAxis(Controller[0], SDL_CONTROLLER_AXIS_LEFTX);
StickY = SDL_GameControllerGetAxis(Controller[0], SDL_CONTROLLER_AXIS_LEFTY);
int xDir = 0, yDir = 0;
if (StickX < -JOYSTICK_DEAD_ZONE) xDir = -1;
else if (StickX > JOYSTICK_DEAD_ZONE) xDir = 1;
else xDir = 0;
if (StickY < -JOYSTICK_DEAD_ZONE) yDir = -1;
else if (StickY > JOYSTICK_DEAD_ZONE) yDir = 1;
else yDir = 0;
if (xDir == 1 && yDir == -1) input.dDS = true;
else if (xDir == 1 && yDir == 0) input.derecha = true;
else if (xDir == -1 && yDir == 0) input.izquierda = true;
else if (xDir == 1 && yDir == 1) input.dDI = true;
else if (xDir == -1 && yDir == -1) input.dIS = true;
else if (xDir == -1 && yDir == 1) input.dII = true;
else if (xDir == 0 && yDir == -1) input.arriba = true;
else if (xDir == 0 && yDir == 1) input.abajo = true;
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT){
onExit();
}
else if (e.type == SDL_KEYUP || (hayMando && e.type == SDL_CONTROLLERBUTTONUP)){
if (e.key.keysym.sym == SDLK_ESCAPE || e.cbutton.button == SDL_CONTROLLER_BUTTON_BACK){
if (dynamic_cast<Nivel1*>(estados.top()) != nullptr) {
SDL_Surface *sshot = SDL_CreateRGBSurface(0, getScreenWidth(), getScreenHeight(), 32, 0, 0, 0, 0);
SDL_RenderReadPixels(getRender(), NULL, SDL_PIXELFORMAT_ARGB8888, sshot->pixels, sshot->pitch);
std::string auxiliar = getPath() + "\\Galiakberova\\partidaGuardada\\temp\\screenshot.bmp";
const char * path1 = auxiliar.c_str();
SDL_SaveBMP(sshot, path1);
SDL_FreeSurface(sshot);
}
estados.top()->onKeyUp('s');
}
else if (e.key.keysym.sym == SDLK_TAB || (hayMando && e.cbutton.button == SDL_CONTROLLER_BUTTON_LEFTSHOULDER)){
//input.sw = true;
estados.top()->onKeyUp('t');
}
else if (e.key.keysym.sym == SDLK_e || (hayMando && e.cbutton.button == SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)) {
input.e = true;
}
else if (e.key.keysym.sym == SDLK_p){
estados.top()->onKeyUp('p');
}
else if (e.key.keysym.sym == SDLK_q || (hayMando && e.cbutton.button == SDL_CONTROLLER_BUTTON_START)) {
if (dynamic_cast<Nivel1*>(estados.top()) != nullptr) {
SDL_Surface *sshot = SDL_CreateRGBSurface(0, getScreenWidth(), getScreenHeight(), 32, 0, 0, 0, 0);
SDL_RenderReadPixels(getRender(), NULL, SDL_PIXELFORMAT_ARGB8888, sshot->pixels, sshot->pitch);
std::string auxiliar = getPath() + "\\Galiakberova\\partidaGuardada\\temp\\screenshot.bmp";
const char * path1 = auxiliar.c_str();
std::cout << path1 << "\n";
SDL_SaveBMP(sshot,path1);
SDL_FreeSurface(sshot);
}
estados.top()->onKeyUp('q');
}
else if (e.key.keysym.sym == SDLK_RETURN || (hayMando && e.cbutton.button == SDL_CONTROLLER_BUTTON_A)) {
estados.top()->onKeyUp('e');
}
else if (e.key.keysym.sym == SDLK_RIGHT || (hayMando && e.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) {
estados.top()->onKeyUp('d');
}
else if (e.key.keysym.sym == SDLK_LEFT || (hayMando && e.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_LEFT)) {
estados.top()->onKeyUp('i');
}
else if (e.key.keysym.sym == SDLK_UP || (hayMando &&e.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_UP)) {
estados.top()->onKeyUp('a');
}
else if (e.key.keysym.sym == SDLK_DOWN || (hayMando && e.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN)) {
estados.top()->onKeyUp('b');
}
else if (e.key.keysym.sym == SDLK_w) estados.top()->onKeyUp('w');
else if (e.key.keysym.sym == SDLK_r) estados.top()->onKeyUp('r');
else if (e.key.keysym.sym == SDLK_y) estados.top()->onKeyUp('y');
else if (e.key.keysym.sym == SDLK_u) estados.top()->onKeyUp('u');
else if (e.key.keysym.sym == SDLK_z) estados.top()->onKeyUp('z');
else if (e.key.keysym.sym == SDLK_o) estados.top()->onKeyUp('o');
else if (e.key.keysym.sym == SDLK_c) estados.top()->onKeyUp('c');
else if (e.key.keysym.sym == SDLK_x) estados.top()->onKeyUp('x');
else if (e.key.keysym.sym == SDLK_f) estados.top()->onKeyUp('f');
else if (e.key.keysym.sym == SDLK_g) estados.top()->onKeyUp('g');
else if (e.key.keysym.sym == SDLK_h) estados.top()->onKeyUp('h');
else if (e.key.keysym.sym == SDLK_j) estados.top()->onKeyUp('j');
else if (e.key.keysym.sym == SDLK_k) estados.top()->onKeyUp('k');
else if (e.key.keysym.sym == SDLK_l) estados.top()->onKeyUp('l');
else if (e.key.keysym.sym == SDLK_v) estados.top()->onKeyUp('v');
else if (e.key.keysym.sym == SDLK_s) estados.top()->onKeyUp('S');
else if (e.key.keysym.sym == SDLK_n) estados.top()->onKeyUp('n');
else if (e.key.keysym.sym == SDLK_1) estados.top()->onKeyUp('1');
else if (e.key.keysym.sym == SDLK_2)estados.top()->onKeyUp('2');
else if (e.key.keysym.sym == SDLK_3)estados.top()->onKeyUp('3');
else if (e.key.keysym.sym == SDLK_4)estados.top()->onKeyUp('4');
else if (e.key.keysym.sym == SDLK_a)estados.top()->onKeyUp('a');
else if (e.key.keysym.sym == SDLK_b)estados.top()->onKeyUp('b');
else if (e.key.keysym.sym == SDLK_c)estados.top()->onKeyUp('c');
else estados.top()->onKeyUp('ñ');
}
else if (e.type == SDL_KEYDOWN){
if (e.key.keysym.sym == SDLK_a){
std::cout << "a ";
}
if (e.key.keysym.sym == SDLK_s){
std::cout << "s";
}
if (e.key.keysym.sym == SDLK_f){
input.follow = true;
}
}
}
/*else {
input.sw = false;
}*/
}
//---------------------------------------------------------------------------------------------------------------------
void juegoPG::initSDL(SDL_Window* &pWindow, SDL_Renderer* &pRenderer) {
//Initialize SDL
if (SDL_Init(SDL_INIT_EVERYTHING | SDL_INIT_GAMECONTROLLER) < 0) {
cout << "SDL could not initialize! \nSDL_Error: " << SDL_GetError() << '\n';
throw EInitSDL("SDL could not initialize!");
}
else {
int MaxJoysticks = SDL_NumJoysticks();
int ControllerIndex = 0;
for (int JoystickIndex = 0; JoystickIndex < MaxJoysticks; ++JoystickIndex)
{
if (!SDL_IsGameController(JoystickIndex))
{
continue;
}
if (ControllerIndex >=2)
{
break;
}
Controller[ControllerIndex] = SDL_GameControllerOpen(JoystickIndex);
SDL_Joystick *JoystickHandle = SDL_GameControllerGetJoystick(Controller[ControllerIndex]);
RumbleHandles[ControllerIndex] = SDL_HapticOpenFromJoystick(JoystickHandle);
ControllerIndex++;
}
int x = SDL_GetCurrentDisplayMode(0,&pMode); //0 para poner en toda la pantalla;
if (x == 0){
SCREEN_HEIGHT = pMode.h;
SCREEN_WIDTH = pMode.w;
}
//Create window: SDL_CreateWindow("SDL Hello World", posX, posY, width, height, SDL_WINDOW_SHOWN);
pWindow = SDL_CreateWindow("Galiakberova", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (pWindow == nullptr){
cout << "Window could not be created! \nSDL_Error: " << SDL_GetError() << '\n';
throw EInitWindow("Window could not be created!");
}
else {
//Get window surface:
pRenderer = SDL_CreateRenderer(pWindow, -1, SDL_RENDERER_ACCELERATED);
SDL_SetRenderDrawColor(pRenderer, 0, 0, 0, 255); //Set background color to black
if (pRenderer == nullptr){
cout << "Renderer could not be created! \nSDL_Error: " << SDL_GetError() << '\n';
throw EInitRender("Renderer could not be created!");
}
}
}
if (TTF_Init() < 0){ //Inicializamos la libreria de fuentes
cout << "TTF could not be initialized! \nTTF_Error: " << TTF_GetError() << '\n';
throw EInitTTF("Font could not be initialized!, There will be no marker");
}
unsigned int version;
result = FMOD::System_Create(&system);
result = system->getVersion(&version);
if (version < FMOD_VERSION)
{
std::cout << ("FMOD lib version %08x doesn't match header version %08x", version, FMOD_VERSION);
}
system->init(100, FMOD_INIT_NORMAL, NULL);
//system->set3DSettings(1.0, 1.0f, 1.0f);
}
//-----------------------------------------------------------------------------------------------------------------
void juegoPG::closeSDL(SDL_Window* & pWindow, SDL_Renderer* & pRenderer) {
result = system->close();
result = system->release();
TTF_Quit();
for (int ControllerIndex = 0; ControllerIndex < 2; ++ControllerIndex)
{
if (RumbleHandles[ControllerIndex])
SDL_HapticClose(RumbleHandles[ControllerIndex]);
if (Controller[ControllerIndex])
{
SDL_GameControllerClose(Controller[ControllerIndex]);
}
}
SDL_DestroyRenderer(pRenderer);
pRenderer = nullptr;
SDL_DestroyWindow(pWindow);
pWindow = nullptr;
SDL_Quit();
}
//--------------------------------------------------------------------------------------------------------------------------
void juegoPG::render() const {
//Clear the window to background color
SDL_RenderClear(pRender);
//llamar al draw de encima de la pila
estados.top()->draw();
//Show the window
SDL_RenderPresent(pRender);
}
void juegoPG::onExit(){
exit = true;
}
void juegoPG::cambiaVida(int cambio) {
if (cambio >= 300){
vida = 300;
nieblaRect.w = 400 + 4 * (300 - vida);//Tamaño de text min + 4* vida total - vida actual
nieblaRect.h = 225 + 2.25 * (300 - vida);
nieblaRect.x = 1600 / 2 - nieblaRect.w / 2;
nieblaRect.y = 900 / 2 - nieblaRect.h / 2;
}
if (vida + cambio <= 300 && vida + cambio >= 0) {
vida += cambio;
nieblaRect.w = 400 + 4 * (300 - vida);//Tamaño de text min + 4* vida total - vida actual
nieblaRect.h = 225 + 2.25 * (300 - vida);
nieblaRect.x = 1600/2 - nieblaRect.w / 2;
nieblaRect.y = 900/2 - nieblaRect.h / 2;
if (vida <= 100) estados.top()->reproduceAmb("PocaVida", false);
}
if (vida <= 0) muerto = true;
}
void juegoPG::cargaPartida(){
muerto = false;
vida = 300;
nieblaRect = { 600, 338, 400, 225 };
estados.top()->paraMusica("", true);
estados.top()->paraAmb("", true);
EstadoJuego* borrar = estados.top();
dynamic_cast<Nivel1*>(borrar)->fadeOut(20);
estados.pop();
delete borrar;
estados.push(new Muerte(this));
} |
cf5f0d6852954d5309674d21d18f451d83419fc4 | ef03edfaaf3437b24d3492ac3865968fcfda7909 | /src/DesignPatterns/src/C++/002-GOFPatterns/003-BehavioralPatterns/001-TemplateMethod/GameApp/AbstractGame.h | a5644249593a0d9ab03167511093122deaefb094 | [] | no_license | durmazmehmet/CSD-UML-Design-Patterns | c60a6a008ec1b2de0cf5bdce74bc1336c4ceeb63 | ae25ec31452016025ff0407e6c6728322624b082 | refs/heads/main | 2023-07-25T23:02:24.703632 | 2021-08-31T23:18:19 | 2021-08-31T23:18:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 299 | h | AbstractGame.h | #ifndef ABSTRACTGAME_H_
#define ABSTRACTGAME_H_
class AbstractGame {
//...
public:
virtual void play() = 0;
virtual void pause() = 0;
virtual void save() = 0;
virtual void reset() = 0;
virtual ~AbstractGame() = default;
public:
void run();
};
#endif //ABSTRACTGAME_H_
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.