blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905 values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 115 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d1d8cc3cc3e285ddb4e51385e1e92efde4eebe5b | 5e589788298de2adef7e0119b650885f0ee703c6 | /BridgePattern/BridgePattern/main.cpp | badf369d137d4cf306aeb588bc663385ce71a64a | [] | no_license | dy0314/designpattern_study | 8f2394dcf09cba442943e77975d7af4389e142e3 | cd7929b61dd01c339b162005b0c4de3d236a31e4 | refs/heads/master | 2020-12-14T17:18:53.016263 | 2020-01-19T01:41:10 | 2020-01-19T01:41:10 | 234,822,659 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,462 | cpp | //
// main.cpp
// BridgePattern
//
// Created by daeyong Lee on 13/10/2019.
// Copyright © 2019 daeyong Lee. All rights reserved.
//
#include <iostream>
using namespace std;
class DisplayImpl { //Implementor
public:
virtual void showDisplay() = 0;
virtual void setHeight() = 0;
virtual void setWidth() = 0;
};
class Tablet9DisplayImpl : public DisplayImpl { //ConcreteImplementor
public:
virtual void showDisplay() override final {
cout<<"show 9 Inches tablet"<<endl;
}
virtual void setHeight() override final {
cout<<"set for 9 Inches tablet height"<<endl;
}
virtual void setWidth() override final {
cout<<"set for 9 Inches tablet weight"<<endl;
}
};
class Tablet11DisplayImpl : public DisplayImpl { //ConcreteImplementor
public:
virtual void showDisplay() override final {
cout<<"show 11 Inches tablet"<<endl;
}
virtual void setHeight() override final {
cout<<"set for 11 Inches tablet height"<<endl;
}
virtual void setWidth() override final {
cout<<"set for 11 Inches tablet weight"<<endl;
}
};
class Tablet13DisplayImpl : public DisplayImpl { //ConcreteImplementor
public:
virtual void showDisplay() override final {
cout<<"show 13 Inches tablet"<<endl;
}
virtual void setHeight() override final {
cout<<"set for 13 Inches tablet height"<<endl;
}
virtual void setWidth() override final {
cout<<"set for 13 Inches tablet weight"<<endl;
}
};
class TabletDisplay { //Abstraction
public:
TabletDisplay(DisplayImpl* displayImpl) {
this->displayImpl = displayImpl;
}
void setTabletDisplayImpl(DisplayImpl* displayImpl) {
this->displayImpl = displayImpl;
}
void show() {
displayImpl->showDisplay();
}
void setWidth() {
displayImpl->setWidth();
}
void setHeight() {
displayImpl->setHeight();
}
private:
DisplayImpl* displayImpl;
};
class GalaxyTabDisplay : public TabletDisplay { //ConcreteAbstraction
public:
GalaxyTabDisplay(DisplayImpl* displayImpl) : TabletDisplay(displayImpl){
}
void showMyDisplay() {
setWidth();
setHeight();
show();
}
};
class A {
public:
virtual void doSomething(int a) {
cout<<"A do"<<endl;
}
};
class B : public A{
public:
virtual void doSomething(float b) { //compile ok
cout<<"B do"<<endl;
}
};
class GrandParent {
public:
virtual void useMail() {
cout<<"send mail"<<endl;
}
virtual void useMessanger() {
cout<<"use text message"<<endl;
}
};
class Parent : GrandParent{
public:
virtual void useMail() override final{
cout<<"send e-mail"<<endl;
}
virtual void useMessanger() override {
cout<<"use kakao talk"<<endl;
}
};
class Child : Parent {
public:
virtual void useMail() override { //Declaration of 'useMail' overrides a 'final' function
}
virtual void useMessanger() override {
cout<<"use facebook messanger"<<endl;
}
};
int main(int argc, const char * argv[]) {
GalaxyTabDisplay* myTablet = new GalaxyTabDisplay(new Tablet9DisplayImpl());
myTablet->showMyDisplay();
myTablet->setTabletDisplayImpl(new Tablet11DisplayImpl());
myTablet->showMyDisplay();
myTablet->setTabletDisplayImpl(new Tablet13DisplayImpl());
myTablet->showMyDisplay();
return 0;
}
| [
"dy0314@gmail.com"
] | dy0314@gmail.com |
2c52d7c79d9d97014b996947b28f546eafd49f32 | da89726ee5d4b307c56027ce6546e5f6fc693209 | /control.cpp | 686533352d29a533144d99b3f6f4e9ff998f620b | [] | no_license | ImaginationZ/physics-simulation-engine | 0ab9dc216ca80e1168819101dad55d0cc704316c | 9cabf49081d7a1c7d9fa8701f10d781455b8c090 | refs/heads/master | 2020-06-12T21:24:30.633789 | 2013-06-27T10:19:05 | 2013-06-27T10:19:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,228 | cpp | #include "control.h"
coordinate control::get_position(point* p){
return p->ask_position();
}
coordinate control::get_velosity(point* p){
return p->ask_velosity();
}
coordinate control::get_accelerate(point* p){
return p->ask_acceleration();
}
void control::moveto(point* p, const coordinate& c) {
p->moveto(c);
}
void control::set_accelarate(point* p, const coordinate& c) {
p->set_acceleration(c);
}
void control::set_velosity(point* p, const coordinate& c) {
p->set_velosity(c);
}
coordinate control::get_direction(point* a, point* b) {
coordinate dis = b->ask_position() - a->ask_position();
return dis.unit();
}
double control::get_distance( point* a, point* b ){
coordinate dis = b->ask_position() - a->ask_position();
return dis.length();
}
double control::get_mass(mass_point* p){
return p->get_mass();
}
void control::set_gravity(mass_point* p, const coordinate& g){
p->set_force(g * p->get_mass());
}
double control::get_radius(ball* b) {
return b->get_radius();
}
bool control::if_touched(ball* a, ball* b) {
if (get_distance(a,b) > a->get_radius() + b->get_radius()) return false;
return true;
}
void control::set_elastic_force( elastic_ball* a, elastic_ball* b, double delta_time){
coordinate direction = get_direction(a,b);
double proportional = a->get_radius() + b->get_radius() - get_distance(a,b);
if( proportional < 0 ) return;
double v = dot(a->ask_velosity() - b->ask_velosity(),direction.unit( ));
if(v>0 &&( 2*v*delta_time > direction.length() ||a->get_radius()+b->get_radius()> 10*direction.length()) ){
coordinate hforce = 2/(a->get_mass()+b->get_mass())*v * direction / delta_time;
a->set_force( -hforce *b->get_mass() );
b->set_force( hforce*a->get_mass() );
}
coordinate force =( ( a->get_stiffness() + b->get_stiffness() ) / 2 * proportional ) * direction;
a->set_force(-force);
a->set_force(-delta_time* a->ask_velosity());
b->set_force(force);
b->set_force(-delta_time* b->ask_velosity());
}
void control::arrange(elastic_ball* a,elastic_ball* b,double delta_time){
coordinate direction = get_direction(a,b);
double proportional = a->get_radius() + b->get_radius() - get_distance(a,b);
if( proportional < 0 ) return;
double v = dot(a->ask_velosity() - b->ask_velosity(),direction.unit( ));
if(v>0) {
coordinate hforce = v * direction / delta_time;
a->set_force( -hforce );
b->set_force( hforce );
}
}
void control::arrange(elastic_ball* a,cylinder* c,double delta_time){
coordinate p = c->get_nearest(a);
coordinate direction = a->ask_position() - p;
double proportional = a->get_radius() - direction.length();
if(proportional<0) return;
double v = dot(a->ask_velosity() - c->get_velosity( p ),-direction.unit());
coordinate hforce = v*direction.unit() / delta_time;
a->set_force(hforce);
coordinate force = proportional * a->get_stiffness() * direction.unit();
a->set_force(force);
}
void control::set_elastic_force(elastic_ball* a,cylinder* c,double delta_time){
coordinate p = c->get_nearest(a);
coordinate direction = a->ask_position() - p;
double proportional = a->get_radius() - direction.length();
if(proportional<0) return;
double v = dot(a->ask_velosity() - c->get_velosity( p ),-direction.unit());
if(v>0 && (4 * v *delta_time> direction.length() || direction.length()<0.9*a->get_radius())){
coordinate hforce = 2/(a->get_mass()+c->get_mass())*v*direction.unit() / delta_time;
a->set_force(c->get_mass()*hforce);
c->set_force(-a->get_mass()*hforce * cos_angle(c->get_axis(),c->ask_position() -p));
c->set_moment( cross( p - c->ask_position( ), -hforce ) );
}
coordinate force = proportional * a->get_stiffness() * direction.unit();
coordinate moment = cross(p - c->ask_position(),-force);
a->set_force(force);
c->set_force(-force * cos_angle(c->get_axis(),c->ask_position() -p));
a->set_force(-a->ask_velosity()*delta_time);
c->set_force(-c->get_velosity(p)*delta_time);
c->set_moment(-c->get_speed() *delta_time);
c->set_moment(moment);
}
| [
"frequencyhzs@gmail.com"
] | frequencyhzs@gmail.com |
5c40396bbc9c3cd4051c2328dc2a0a7572c9ebef | 6a11aa0bb2eaba51354149322172ee6cefb29ed6 | /lemoneditor/src/main.cpp | 7af1e4e14eba5b53c04e9292693b0e9d7b433556 | [
"Apache-2.0"
] | permissive | ra2u18/lemon | 59dd19e14702aea3b836492fbc6749523d292498 | f5ea85c3d30367f9d14df5c9385bc57870ed515a | refs/heads/main | 2023-07-17T20:48:20.969869 | 2021-08-25T10:00:31 | 2021-08-25T10:00:31 | 399,194,651 | 0 | 0 | Apache-2.0 | 2021-08-25T10:00:32 | 2021-08-23T17:38:12 | Lua | UTF-8 | C++ | false | false | 220 | cpp | #include "lemon/engine.h"
#include <iostream>
int main()
{
lemon::Engine& engine = lemon::Engine::Instance();
engine.Run();
std::cout << "Press ENTER to continue...";
std::cin.ignore();
return 0;
} | [
"riccardo.andronache14@gmail.com"
] | riccardo.andronache14@gmail.com |
5cc0ab00156a47b1c0540d424a096fb3afd6afb4 | 0e8d57f10639b0bdcab2c89b307029697c909863 | /aoj/ITP2/ITP2-10C/main.cpp | 075c0c05b15373ab253ade81ea19b11d9cf92fa7 | [
"Apache-2.0"
] | permissive | xirc/cp-algorithm | 07a6faf5228e07037920f5011326c16091a9157d | e83ea891e9f8994fdd6f704819c0c69f5edd699a | refs/heads/main | 2021-12-25T16:19:57.617683 | 2021-12-22T12:06:49 | 2021-12-22T12:06:49 | 226,591,291 | 15 | 1 | Apache-2.0 | 2021-12-22T12:06:50 | 2019-12-07T23:53:18 | C++ | UTF-8 | C++ | false | false | 1,340 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
bitset<64> bits;
int Q;
cin >> Q;
int t, i;
while (Q--, Q >= 0) {
cin >> t;
if (t == 0) {
// test i
cin >> i;
auto ans = (bits[i] ? 1 : 0);
cout << ans << endl;
} else if (t == 1) {
// set i
cin >> i;
bits[i] = true;
} else if (t == 2) {
// clear i
cin >> i;
bits[i] = false;
} else if (t == 3) {
// flip i
cin >> i;
bits[i].flip();
} else if (t == 4) {
// all
auto ans = bits.all() ? 1 : 0;
cout << ans << endl;
} else if (t == 5) {
// any
auto ans = bits.any() ? 1 : 0;
cout << ans << endl;
} else if (t == 6) {
// none
auto ans = bits.none() ? 1 : 0;
cout << ans << endl;
} else if (t == 7) {
// count
auto ans = bits.count();
cout << ans << endl;
} else if (t == 8) {
// val
auto ans = bits.to_ullong();
cout << ans << endl;
} else throw;
}
return 0;
} | [
"xirckey@gmail.com"
] | xirckey@gmail.com |
5e05c4e08ce61cec3fb1d73aeef8b39f492099bb | cd470ad61c4dbbd37ff004785fd6d75980987fe9 | /Luogu/3857 [TJOI2008]彩灯/线性基/std.cpp | 6417a6aa4496bf72070a7eeec537e9f16efd9447 | [] | no_license | AutumnKite/Codes | d67c3770687f3d68f17a06775c79285edc59a96d | 31b7fc457bf8858424172bc3580389badab62269 | refs/heads/master | 2023-02-17T21:33:04.604104 | 2023-02-17T05:38:57 | 2023-02-17T05:38:57 | 202,944,952 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 789 | cpp | #include <cstdio>
#include <cctype>
#include <algorithm>
#include <cstring>
int read(){
register int x = 0;
register char f = 1, ch = getchar();
for (; !isdigit(ch); ch = getchar()) if (ch == '-') f = !f;
for (; isdigit(ch); ch = getchar()) x = (x << 3) + (x << 1) + (ch ^ '0');
return f ? x : -x;
}
int n, m;
char s[60];
long long a[60];
void insert(long long x){
for (register int i = m - 1; ~i; --i)
if (x >> i & 1) if (a[i]) x ^= a[i]; else return a[i] = x, void(0);
}
int main(){
m = read(), n = read();
for (register int i = 1; i <= n; ++i){
scanf("%s", s + 1);
long long x = 0;
for (register int j = 1; j <= m; ++j) x = x << 1 | (s[j] == 'O');
insert(x);
}
int s = 0;
for (register int i = 0; i < m; ++i)
if (a[i]) ++s;
printf("%lld\n", (1ll << s) % 2008);
} | [
"1790397194@qq.com"
] | 1790397194@qq.com |
3428b906afed20ebdd0434d5f688a5a7b44a12f8 | 88eb1d1e85698ec3c3d3c3198b3caff1a036e88e | /src/MBC.cpp | c4790100be61e0587a535f87471066911b9b8f82 | [] | no_license | Lordelbert/GBpp | 153aafc4c26869493c00fea398a8996ec94e7bee | 0defa1c8b0599f3944faac4c0f2ba6f95f8dbc2f | refs/heads/master | 2022-12-04T20:29:44.618409 | 2020-08-21T14:40:38 | 2020-08-21T14:40:38 | 275,627,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,499 | cpp | #include "MBC.hpp"
// TODO change nbr with enum to make code more explicit
auto MBC1::swap_bank_rom_high()
{
for(size_t i = 0; i < 2; ++i) {
MBC1_Partition::section mem_part{&m_memory[reg1_2() * 16_kB + i * 8_kB],
&m_memory[reg1_2() * 16_kB + i * 8_kB + 8_kB]};
m_memory_partition.swap(i + 2, std::move(mem_part));
}
return;
}
auto MBC1::swap_bank_rom_low()
{
const size_t addr = (mode()) ? (reg2() << 5) * 16_kB : 0b0;
for(size_t i = 0; i < 2; ++i) {
MBC1_Partition::section mem_part{&m_memory[addr + i * 8_kB],
&m_memory[addr + i * 8_kB + 8_kB]};
m_memory_partition.swap(i, std::move(mem_part));
}
return;
}
auto MBC1::swap_bank_ram()
{
const size_t addr = (mode()) ? reg2() * 8_kB : 0b0;
MBC1_Partition::section mem_part{&m_memory[addr], &m_memory[addr + 8_kB]};
m_memory_partition.swap(5, std::move(mem_part));
return;
}
auto MBC1::ramg_enable(std::uint8_t value) noexcept -> void
{
m_ramg_enable = ((value & 0x0F) == 0x0A) ? true : false;
}
auto MBC1::bank_reg1(std::uint8_t value) noexcept -> void
{
const std::uint8_t _val = (value & 0b0001'1111);
m_bank_selector = (m_bank_selector & 0b1110'0000) | ((_val == 0) ? 0b1 : _val);
swap_bank_rom_high();
}
// note can also be used for bank in ram :
auto MBC1::bank_reg2(std::uint8_t value) noexcept -> void
{
m_bank_selector = (m_bank_selector & 0b1001'1111) | ((value & 0b11) << 5);
swap_bank_rom_high();
swap_bank_rom_low();
if(m_ram > 8_kB) swap_bank_ram();
}
auto MBC1::bank_mode(std::uint8_t value) noexcept -> void
{
m_bank_selector = set_bit(m_bank_selector, 7, static_cast<std::uint8_t>(value & 0b1));
swap_bank_rom_high();
swap_bank_rom_low();
if(m_ram > 8_kB) swap_bank_ram();
}
[[nodiscard]] auto MBC1::read(std::uint16_t addr) const noexcept -> std::uint8_t
{
if(addr >= SWI_RAM_base and addr < SWI_RAM_ul) {
return (m_ramg_enable) ? m_memory_partition[addr] : m_distrib(m_gen);
}
return m_memory_partition[addr];
}
auto MBC1::write(std::uint16_t addr, std::uint8_t value) noexcept -> void
{
if(addr < IROM1_ul) {
if(addr < 0x2000) {
ramg_enable(value);
return;
}
if(addr < 0x4000) {
bank_reg1(value);
return;
}
if(addr < 0x6000) {
bank_reg2(value);
return;
}
if(addr < 0x8000) {
bank_mode(value);
return;
}
}
if(addr >= SWI_RAM_base and addr < SWI_RAM_ul) {
if(m_ramg_enable) {
m_memory_partition[addr] = value;
}
}
m_memory_partition[addr] = value;
return;
}
| [
"lordelbert@gmail.com"
] | lordelbert@gmail.com |
64a23bce7022e9d1e6f16cd00723d3412807879e | 62d2961f1e1af919eaa0b83b559a8a4fec342287 | /LT228/LT228.cpp | 196bbe8cb88b6a324eb75cad7f77de3f30100141 | [] | no_license | z7059652/LT228 | 9b9109fcf7433e590257ee66905e40f3c720992e | 0c9fdd0df68fbd1597626577aff9fa2c84748e8c | refs/heads/master | 2021-01-21T14:08:51.845878 | 2016-03-31T02:02:35 | 2016-03-31T02:02:35 | 41,524,791 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,385 | cpp | // LT228.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <vector>
#include <string>
using namespace std;
void stringformat(string& str,int a,int b)
{
char buf[10];
memset(buf, 0, 10);
if (a==b)
{
sprintf(buf, "%d", a);
}
else
sprintf(buf, "%d->%d", a, b);
str = buf;
}
vector<string> summaryRanges(vector<int>& nums)
{
vector<string> res;
if (nums.size() == 0)
{
return res;
}
int startpos = 0, endpos = 0;
int ifirst, ilast;
for (int i = 0; i < nums.size() - 1; i++)
{
// ifirst = ilast = nums[i];
startpos = endpos = i;
while (i < nums.size() - 1)
{
if (nums[i + 1] - nums[i] == 1)
{
i++;
endpos = i;
}
else
{
string temp;
stringformat(temp, nums[startpos], nums[endpos]);
res.push_back(temp);
break;
}
}
}
string temp;
if (endpos == nums.size() - 1)
stringformat(temp, nums[startpos], nums[endpos]);
else
stringformat(temp, nums[endpos + 1], nums[endpos + 1]);
res.push_back(temp);
return res;
}
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> nums;
nums.push_back(0);
nums.push_back(1);
nums.push_back(2);
nums.push_back(3);
nums.push_back(5);
nums.push_back(6);
nums.push_back(7);
nums.push_back(8);
nums.push_back(11);
nums.push_back(12);
nums.push_back(13);
nums.push_back(18);
vector<string> res = summaryRanges(nums);
return 0;
}
| [
"7059652@163.com"
] | 7059652@163.com |
2ba54f2dc45228690e20a666fb2e1ce8267b94e7 | 37cca16f12e7b1d4d01d6f234da6d568c318abee | /src/org/mpisws/p2p/transport/direct/DirectAppSocket_DirectAppSocketEndpoint.cpp | 911a12644e992155485c5e308a251e46e3da5421 | [] | no_license | subhash1-0/thirstyCrow | e48155ce68fc886f2ee8e7802567c1149bc54206 | 78b7e4e3d2b9a9530ad7d66b44eacfe73ceea582 | refs/heads/master | 2016-09-06T21:25:54.075724 | 2015-09-21T17:21:15 | 2015-09-21T17:21:15 | 42,881,521 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,509 | cpp | // Generated from /pastry-2.1/src/org/mpisws/p2p/transport/direct/DirectAppSocket.java
#include <org/mpisws/p2p/transport/direct/DirectAppSocket_DirectAppSocketEndpoint.hpp>
#include <java/io/IOException.hpp>
#include <java/lang/ClassCastException.hpp>
#include <java/lang/Math.hpp>
#include <java/lang/NullPointerException.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/String.hpp>
#include <java/lang/StringBuilder.hpp>
#include <java/nio/ByteBuffer.hpp>
#include <java/util/Iterator.hpp>
#include <java/util/LinkedList.hpp>
#include <java/util/Map.hpp>
#include <org/mpisws/p2p/transport/P2PSocketReceiver.hpp>
#include <org/mpisws/p2p/transport/direct/DirectAppSocket_DirectAppSocketEndpoint_register_3.hpp>
#include <org/mpisws/p2p/transport/direct/DirectAppSocket_DirectAppSocketEndpoint_register_4.hpp>
#include <org/mpisws/p2p/transport/direct/DirectAppSocket_DirectAppSocketEndpoint_shutdownOutput_5.hpp>
#include <org/mpisws/p2p/transport/direct/DirectAppSocket_DirectAppSocketEndpoint_read_1.hpp>
#include <org/mpisws/p2p/transport/direct/DirectAppSocket_DirectAppSocketEndpoint_write_2.hpp>
#include <org/mpisws/p2p/transport/direct/DirectAppSocket.hpp>
#include <org/mpisws/p2p/transport/direct/GenericNetworkSimulator.hpp>
#include <rice/environment/logging/Logger.hpp>
#include <Array.hpp>
template<typename T, typename U>
static T java_cast(U* u)
{
if(!u) return static_cast<T>(nullptr);
auto t = dynamic_cast<T>(u);
if(!t) throw new ::java::lang::ClassCastException();
return t;
}
template<typename T>
static T* npc(T* t)
{
if(!t) throw new ::java::lang::NullPointerException();
return t;
}
extern void lock(::java::lang::Object *);
extern void unlock(::java::lang::Object *);
namespace
{
struct synchronized
{
synchronized(::java::lang::Object *o) : o(o) { ::lock(o); }
~synchronized() { ::unlock(o); }
private:
synchronized(const synchronized&); synchronized& operator=(const synchronized&);
::java::lang::Object *o;
};
}
org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::DirectAppSocket_DirectAppSocketEndpoint(DirectAppSocket *DirectAppSocket_this, const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
, DirectAppSocket_this(DirectAppSocket_this)
{
clinit();
}
org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::DirectAppSocket_DirectAppSocketEndpoint(DirectAppSocket *DirectAppSocket_this, ::java::lang::Object* localNodeHandle, ::rice::environment::logging::Logger* logger)
: DirectAppSocket_DirectAppSocketEndpoint(DirectAppSocket_this, *static_cast< ::default_init_tag* >(0))
{
ctor(localNodeHandle,logger);
}
void org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::init()
{
seq = int32_t(0);
bytesInFlight = int32_t(0);
byteDeliveries = new ::java::util::LinkedList();
firstOffset = int32_t(0);
}
void org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::ctor(::java::lang::Object* localNodeHandle, ::rice::environment::logging::Logger* logger)
{
super::ctor();
init();
this->localNodeHandle = localNodeHandle;
this->logger = logger;
}
void org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::setCounterpart(DirectAppSocket_DirectAppSocketEndpoint* counterpart)
{
this->counterpart = counterpart;
}
java::lang::Object* org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::getRemoteNodeHandle()
{
return java_cast< ::java::lang::Object* >(npc(counterpart)->localNodeHandle);
}
int64_t org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::read(::java::nio::ByteBuffer* dsts) /* throws(IOException) */
{
auto lengthRead = int32_t(0);
{
synchronized synchronized_0(this);
{
if(npc(byteDeliveries)->isEmpty()) {
return 0;
}
if(java_cast< ::int8_tArray* >(npc(byteDeliveries)->getFirst()) == DirectAppSocket::EOF_()) {
return -int32_t(1);
}
auto i = npc(byteDeliveries)->iterator();
while (npc(i)->hasNext()) {
auto msg = java_cast< ::int8_tArray* >(java_cast< ::int8_tArray* >(npc(i)->next()));
auto curBuffer = dsts;
auto lengthToPut = npc(curBuffer)->remaining();
if(lengthToPut > (npc(msg)->length - firstOffset)) {
lengthToPut = npc(msg)->length - firstOffset;
}
npc(curBuffer)->put(msg, firstOffset, lengthToPut);
firstOffset += lengthToPut;
lengthRead += lengthToPut;
if(firstOffset == npc(msg)->length) {
npc(i)->remove();
firstOffset = 0;
} else {
break;
}
}
}
}
bytesInFlight -= lengthRead;
if(npc(logger)->level <= ::rice::environment::logging::Logger::FINER)
npc(logger)->log(::java::lang::StringBuilder().append(static_cast< ::java::lang::Object* >(this))->append(u".write("_j)
->append(static_cast< ::java::lang::Object* >(dsts))
->append(u") len:"_j)
->append(lengthRead)
->append(u" inFlight:"_j)
->append(bytesInFlight)->toString());
npc(DirectAppSocket_this->simulator)->enqueueDelivery(new DirectAppSocket_DirectAppSocketEndpoint_read_1(this), 0);
return lengthRead;
}
int64_t org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::write(::java::nio::ByteBuffer* srcs) /* throws(IOException) */
{
if(outputClosed)
return -int32_t(1);
if(!npc(DirectAppSocket_this->simulator)->isAlive(java_cast< ::java::lang::Object* >(npc(counterpart)->localNodeHandle))) {
return -int32_t(1);
}
auto availableToWrite = npc(srcs)->remaining();
int32_t lengthToWrite;
{
synchronized synchronized_1(counterpart);
{
lengthToWrite = DirectAppSocket::MAX_BYTES_IN_FLIGHT - npc(counterpart)->bytesInFlight;
if(lengthToWrite > availableToWrite)
lengthToWrite = availableToWrite;
npc(counterpart)->bytesInFlight += lengthToWrite;
}
}
auto const msg = new ::int8_tArray(lengthToWrite);
auto remaining = lengthToWrite;
while (remaining > 0) {
auto lengthToReadFromBuffer = npc(srcs)->remaining();
if(remaining < lengthToReadFromBuffer)
lengthToReadFromBuffer = remaining;
npc(srcs)->get(msg, lengthToWrite - remaining, lengthToReadFromBuffer);
remaining -= lengthToReadFromBuffer;
}
if(npc(logger)->level <= ::rice::environment::logging::Logger::FINER)
npc(logger)->log(::java::lang::StringBuilder().append(static_cast< ::java::lang::Object* >(this))->append(u".write("_j)
->append(static_cast< ::java::lang::Object* >(srcs))
->append(u") len:"_j)
->append(lengthToWrite)
->append(u" inFlight:"_j)
->append(npc(counterpart)->bytesInFlight)->toString());
npc(DirectAppSocket_this->simulator)->enqueueDelivery(new DirectAppSocket_DirectAppSocketEndpoint_write_2(this, msg), static_cast< int32_t >(::java::lang::Math::round(npc(DirectAppSocket_this->simulator)->networkDelay(java_cast< ::java::lang::Object* >(localNodeHandle), java_cast< ::java::lang::Object* >(npc(counterpart)->localNodeHandle)))));
return lengthToWrite;
}
void org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::addToReadQueue(::int8_tArray* msg)
{
{
synchronized synchronized_2(this);
{
if(npc(logger)->level <= ::rice::environment::logging::Logger::FINE) {
if(msg == DirectAppSocket::EOF_()) {
npc(logger)->log(::java::lang::StringBuilder().append(static_cast< ::java::lang::Object* >(this))->append(u": addToReadQueue(EOF)"_j)->toString());
} else {
npc(logger)->log(::java::lang::StringBuilder().append(static_cast< ::java::lang::Object* >(this))->append(u": addToReadQueue("_j)
->append(npc(msg)->length)
->append(u")"_j)->toString());
}
}
npc(byteDeliveries)->addLast(static_cast< ::java::lang::Object* >(msg));
}
}
notifyCanRead();
}
void org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::notifyCanWrite()
{
if(writer == nullptr)
return;
if(npc(counterpart)->bytesInFlight < DirectAppSocket::MAX_BYTES_IN_FLIGHT) {
auto temp = writer;
writer = nullptr;
try {
if(npc(logger)->level <= ::rice::environment::logging::Logger::FINEST)
npc(logger)->log(::java::lang::StringBuilder().append(static_cast< ::java::lang::Object* >(this))->append(u".notifyCanWrite()"_j)->toString());
npc(temp)->receiveSelectResult(this, false, true);
} catch (::java::io::IOException* ioe) {
npc(logger)->logException(::java::lang::StringBuilder().append(u"Error in "_j)->append(static_cast< ::java::lang::Object* >(temp))->toString(), ioe);
}
}
}
void org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::notifyCanRead()
{
if(npc(byteDeliveries)->isEmpty())
return;
if(reader != nullptr) {
auto temp = reader;
reader = nullptr;
try {
if(npc(logger)->level <= ::rice::environment::logging::Logger::FINEST)
npc(logger)->log(::java::lang::StringBuilder().append(static_cast< ::java::lang::Object* >(this))->append(u".notifyCanRead()"_j)->toString());
npc(temp)->receiveSelectResult(this, true, false);
} catch (::java::io::IOException* ioe) {
npc(logger)->logException(::java::lang::StringBuilder().append(u"Error in "_j)->append(static_cast< ::java::lang::Object* >(temp))->toString(), ioe);
}
}
}
void org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::register_(bool wantToRead, bool wantToWrite, ::org::mpisws::p2p::transport::P2PSocketReceiver* receiver)
{
if(wantToWrite) {
writer = receiver;
npc(DirectAppSocket_this->simulator)->enqueueDelivery(new DirectAppSocket_DirectAppSocketEndpoint_register_3(this), 0);
}
if(wantToRead) {
reader = receiver;
npc(DirectAppSocket_this->simulator)->enqueueDelivery(new DirectAppSocket_DirectAppSocketEndpoint_register_4(this), 0);
}
}
void org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::shutdownOutput()
{
if(npc(logger)->level <= ::rice::environment::logging::Logger::FINER)
npc(logger)->log(::java::lang::StringBuilder().append(static_cast< ::java::lang::Object* >(this))->append(u".shutdownOutput()"_j)->toString());
outputClosed = true;
if(!npc(DirectAppSocket_this->simulator)->isAlive(java_cast< ::java::lang::Object* >(npc(counterpart)->localNodeHandle)))
return;
npc(DirectAppSocket_this->simulator)->enqueueDelivery(new DirectAppSocket_DirectAppSocketEndpoint_shutdownOutput_5(this), static_cast< int32_t >(::java::lang::Math::round(npc(DirectAppSocket_this->simulator)->networkDelay(java_cast< ::java::lang::Object* >(localNodeHandle), java_cast< ::java::lang::Object* >(npc(counterpart)->localNodeHandle)))));
}
void org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::shutdownInput()
{
}
void org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::close()
{
shutdownOutput();
shutdownInput();
}
java::lang::String* org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::toString()
{
return ::java::lang::StringBuilder().append(u"DAS{"_j)->append(static_cast< ::java::lang::Object* >(java_cast< ::java::lang::Object* >(localNodeHandle)))
->append(u":"_j)
->append(npc(DirectAppSocket_this->simulator)->isAlive(java_cast< ::java::lang::Object* >(localNodeHandle)))
->append(u"->"_j)
->append(static_cast< ::java::lang::Object* >(java_cast< ::java::lang::Object* >(npc(counterpart)->localNodeHandle)))
->append(u":"_j)
->append(npc(DirectAppSocket_this->simulator)->isAlive(java_cast< ::java::lang::Object* >(npc(counterpart)->localNodeHandle)))
->append(u" w:"_j)
->append(static_cast< ::java::lang::Object* >(writer))
->append(u" r:"_j)
->append(static_cast< ::java::lang::Object* >(reader))
->append(u"}"_j)->toString();
}
java::lang::Object* org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::getIdentifier()
{
return java_cast< ::java::lang::Object* >(getRemoteNodeHandle());
}
java::util::Map* org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::getOptions()
{
return DirectAppSocket_this->options;
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::class_()
{
static ::java::lang::Class* c = ::class_(u"org.mpisws.p2p.transport.direct.DirectAppSocket.DirectAppSocketEndpoint", 71);
return c;
}
java::lang::Class* org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::getClass0()
{
return class_();
}
| [
"sgurjar@adobe.com"
] | sgurjar@adobe.com |
1974822aa8296803ec88670928d68208817a580e | b60776fe3c35b48485b3e9fd85c38e2954e0186b | /Recursion/histogramOfOutcomesOFNDiceRolls.cpp | 90d3c6ef08c0e8ac0d7ee1653f9bd7745d443903 | [] | no_license | aniket-gore/practice-codes | 88994ef1719f21f1b1ae4c21b6fd7ad80d581e6b | 4b3fbfb73da8cd1f2786717e4e8927bac69eefb2 | refs/heads/master | 2021-01-17T21:24:00.879741 | 2017-08-17T01:37:32 | 2017-08-17T01:37:32 | 36,997,219 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,340 | cpp | #include<iostream>
#include<map>
using namespace std;
/*
Given N dice with m sides, print histogram of all outcomes of dice throws.
e.g. N=2, m = 3
(1, 1) -> 2
(1, 2) -> 3
(1, 3) -> 4
(2, 1) -> 3
(2, 2) -> 4
(2, 3) -> 5
(3, 1) -> 4
(3, 2) -> 5
(3, 3) -> 6
And the function should return:
2: 1
3: 2
4: 3
5: 2
6: 1
*/
void histogramOfOutComesOfNDiceRolls(int N, int sides, int outcomes[], int index, map<int,int> &histogram){
if(index == -1){
int sum=0;
for(int i=0; i<N; i++){
sum += outcomes[i];
}
if(histogram.find(sum) != histogram.end()){
histogram[sum]++;
}
else{
histogram.insert(make_pair(sum,1));
}
return;
}
for(int i=1; i<=sides; i++){
outcomes[index] = i;
histogramOfOutComesOfNDiceRolls(N,sides,outcomes,index-1,histogram);
}
}
/*
int main(){
int outcomes[2] = {0}; //size = no. of dice
map<int,int> histogram;
// 4th parameter : index = index in the array denoting which dice
// we start with last dice, and decrement till 0th by filling values from 1 to m
histogramOfOutComesOfNDiceRolls(2,3,outcomes,1,histogram);
cout<<"histogram = ";
map<int,int>::iterator iter;
for(iter = histogram.begin(); iter != histogram.end(); iter++){
cout<<endl<<iter->first<<" : "<<iter->second;
}
cout<<endl;
return 1;
}*/ | [
"aniketgore05@gmail.com"
] | aniketgore05@gmail.com |
615f9861eba483a35585d9f1ce67d92c549576a0 | a5095c14cf28ffd97ccb478dd1781a476bef0413 | /Client/Game/States/PreGameState.cpp | 9d6a7c91251d1fb1a063c7368685d87a03b097f9 | [
"CC-BY-3.0",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-3-Clause"
] | permissive | Katipo007/diorama_roguelite | 4bf1bfc96a4a00192f58e599594cd44b27b2c994 | 81b2bd282507cbffb8c90a3793a7b97f395e8584 | refs/heads/master | 2023-06-04T02:59:26.469544 | 2021-06-28T11:04:19 | 2021-06-28T11:04:19 | 347,273,548 | 2 | 0 | null | 2021-06-06T03:44:41 | 2021-03-13T04:39:12 | C++ | UTF-8 | C++ | false | false | 269 | cpp | #include "PreGameState.hpp"
namespace Game::States
{
fsm::Might<fsm::TransitionTo<MainMenuState>> PreGameState::HandleEvent( const Events::FrameEvent& )
{
// TODO: only transition after we've loaded starting stuff
return fsm::TransitionTo<MainMenuState>();
}
}
| [
"ben@steadfast.co.nz"
] | ben@steadfast.co.nz |
4d6e30e0405a021843ec8250c70d80bdf92d5e72 | b2f31a8dd5675da82fc74ce613a6b78e59addc95 | /MotLB/src/graphics/VertexArray.cpp | 79b67c401ad0a311692f6d25d7c9e9c5aa39851d | [] | no_license | samuelxyz/motlb | d2d0d99680b57840a7a4b8c343f0cd753ea8e235 | f7b919d17bc01c86602651ddc9a16cbcbdc16ef7 | refs/heads/master | 2020-03-23T18:59:14.772758 | 2018-09-07T14:52:37 | 2018-09-07T14:52:37 | 141,946,608 | 0 | 0 | null | 2018-08-07T20:07:23 | 2018-07-23T01:35:36 | C | UTF-8 | C++ | false | false | 1,925 | cpp | /*
* VertexArray.cpp
*
* Created on: Jul 30, 2018
* Author: Samuel Tan
*/
#include "../graphics/VertexArray.h"
#include <cassert>
namespace graphics
{
GLuint VertexArray::currentlyBound = 0;
VertexArray::VertexArray()
: stride(0)
{
glGenVertexArrays(1, &ID);
}
VertexArray::~VertexArray()
{
if (currentlyBound == ID)
currentlyBound = 0;
glDeleteVertexArrays(1, &ID);
}
void VertexArray::addAttribute(const std::string& varName, GLenum dataType, GLuint numComponents)
{
attributes.push_back({ varName, dataType, numComponents });
stride += (numComponents * getSizeOfType(dataType));
}
void VertexArray::applyAttributesWithBuffer(const VertexBuffer& vb, const ShaderProgram& sp)
{
vb.bind();
bind();
unsigned int offset = 0;
for (auto& attribute : attributes)
{
GLuint varPos = glGetAttribLocation(sp.getID(), attribute.varName.c_str());
glEnableVertexAttribArray(varPos);
glVertexAttribPointer(varPos, attribute.numComponents,
attribute.dataType, GL_FALSE, stride, (const void*)offset);
offset += attribute.numComponents * getSizeOfType(attribute.dataType);
}
}
void VertexArray::bind() const
{
if (currentlyBound != ID)
forceBind();
}
void VertexArray::forceBind() const
{
glBindVertexArray(ID);
currentlyBound = ID;
}
void VertexArray::unbind() const
{
glBindVertexArray(0);
currentlyBound = 0;
}
GLsizei VertexArray::getSizeOfType(GLenum dataType)
{
switch (dataType)
{
case GL_FLOAT:
return sizeof(GLfloat);
case GL_UNSIGNED_INT:
return sizeof(GLuint);
case GL_UNSIGNED_BYTE:
return sizeof(GLbyte);
}
// should be done before here
assert(false);
return 0;
}
} /* namespace render */
| [
"xinyizhentan@gmail.com"
] | xinyizhentan@gmail.com |
3cc2f633ea81f21713c64577301cc281c0761b96 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_1484496_0/C++/jasy/gcj2012R1BC.cpp | 1e942dd42a1586ea0127aa4fd46b8be4fbd0eb1a | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,932 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
typedef unsigned long long vtype;
static void solve ()
{
int N;
std::cin >> N;
std::vector<vtype> S(N);
vtype s = 0;
for (int i=0; i<N; ++i) {
std::cin >> S[i];
s+=S[i];
}
s/=2;
std::sort(S.begin(), S.end());
const vtype mx = 1<<N;
for (vtype x = 1; x<mx; ++x) {
std::vector<vtype> a;
vtype A = 0;
std::vector<vtype> b;
{
vtype d = 1;
for (int i=0; d<=x; d<<=1,++i) {
const vtype s = S[i];
if (x&d) {
a.push_back(s);
A += s;
}
else {
b.push_back(s);
}
}
}
if (A>s) {
continue;
}
const vtype mxb = 1<<b.size();
for (vtype xb = 1; xb<mxb; ++xb) {
vtype B = 0;
vtype d = 1;
std::vector<vtype> b2;
for (int i=0; d<=xb; d<<=1,++i) {
if (xb&d) {
B += b[i];
b2.push_back(b[i]);
}
}
if (A==B) {
for (int i=0; i<a.size(); ++i) {
if (i!=0) {
std::cout << " ";
}
std::cout << a[i];
}
std::cout << "\n";
for (int i=0; i<b2.size(); ++i) {
if (i!=0) {
std::cout << " ";
}
std::cout << b2[i];
}
std::cout << "\n";
return;
}
}
}
std::cout << "Impossible\n";
}
int main ()
{
int T;
std::cin >> T;
for (int i=1; i<=T; ++i) {
std::cout << "Case #" << i << ":\n";
solve();
}
return 0;
}
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
128ed46c64486585829cce0b0c2d3eb8e850b7a4 | 2e86b8c70e2d3b1b98b7acab5ffe86137e8fb363 | /vga_train/snd/step.cpp | 1ef7d06f80f154a9dfe01454d5f31ad87c856011 | [] | no_license | pavel-krivanek/PicoVGA | c5ecfe768395f48485a4626453a655fd97ead04a | c09c387abff827c0d59cc70db7fe5e9fde3c6e76 | refs/heads/main | 2023-05-29T09:22:21.481369 | 2021-06-10T17:07:49 | 2021-06-10T17:07:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,832 | cpp | #include "include.h"
// sound format: PCM mono 8-bit 22050Hz
const u8 StepSnd[2243] = {
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7C, 0x7E, 0x7C, 0x7E,
0x7C, 0x7D, 0x88, 0xFF, 0x68, 0x55, 0xFF, 0x79, 0x4E, 0xFF, 0x8B, 0x44, 0xFF, 0x97, 0x41, 0xFF,
0xAB, 0x41, 0xFF, 0xBF, 0x3D, 0xF6, 0xCB, 0x3A, 0xE9, 0xD8, 0x37, 0xE2, 0xF1, 0xF9, 0x88, 0x5A,
0xB9, 0xF2, 0xF7, 0x56, 0x7F, 0xC5, 0xFF, 0xC1, 0x45, 0x9B, 0xDC, 0xFF, 0x85, 0x53, 0xAE, 0xF2,
0xF1, 0x5C, 0x68, 0xC2, 0xF9, 0xDE, 0xD7, 0xE4, 0xB6, 0x35, 0x9A, 0x7B, 0xF6, 0xDD, 0xE5, 0x7E,
0x41, 0x90, 0x83, 0xFF, 0xC2, 0xDF, 0x46, 0x5B, 0x74, 0xA2, 0xF8, 0xB7, 0xC2, 0x20, 0x91, 0xF8,
0xB0, 0xCE, 0x60, 0x34, 0x78, 0x5B, 0xE4, 0xC1, 0xB4, 0x94, 0x17, 0x66, 0x4C, 0xA0, 0xDE, 0x95,
0xB5, 0x2B, 0x3D, 0x51, 0x65, 0xE0, 0x9F, 0x9B, 0x9A, 0x99, 0x9F, 0x96, 0xA9, 0x64, 0x16, 0x58,
0x43, 0x52, 0x3F, 0xD1, 0xA1, 0x8F, 0x8A, 0x99, 0x63, 0x0A, 0x49, 0x37, 0x47, 0x2F, 0xBB, 0xA1,
0x7E, 0x88, 0x82, 0x8A, 0x85, 0x8D, 0x86, 0x94, 0x70, 0x0A, 0x3F, 0x39, 0x40, 0x34, 0x3B, 0x2D,
0xBD, 0x94, 0x7B, 0x7E, 0x82, 0x7C, 0x8E, 0x4F, 0x0B, 0x3D, 0x31, 0x38, 0x2F, 0x32, 0x2C, 0x2D,
0x29, 0x29, 0x26, 0x25, 0x23, 0x22, 0x20, 0x1F, 0x1E, 0x1D, 0x1C, 0x1C, 0x1B, 0x1A, 0x1A, 0x19,
0x19, 0x19, 0x18, 0x18, 0x19, 0x18, 0x19, 0x19, 0x19, 0x1A, 0x1A, 0x1B, 0x1B, 0x1C, 0x1D, 0x1D,
0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x26, 0x27, 0x28, 0x29, 0x2B, 0x2C, 0x2E, 0x2F, 0x31,
0x32, 0x34, 0x36, 0x37, 0x39, 0x3B, 0x3C, 0x3E, 0x40, 0x41, 0x43, 0x45, 0x47, 0x48, 0x4A, 0x4C,
0x4E, 0x50, 0x51, 0x53, 0x55, 0x57, 0x58, 0x5A, 0x5C, 0x5E, 0x5F, 0x61, 0x63, 0x65, 0x66, 0x68,
0x69, 0x6B, 0x6D, 0x6E, 0x70, 0x71, 0x73, 0x74, 0x76, 0x77, 0x79, 0x7A, 0x7B, 0x7D, 0x7E, 0x7F,
0x80, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F, 0x8F,
0x90, 0x91, 0x91, 0x92, 0x93, 0x93, 0x94, 0x94, 0x95, 0x95, 0x96, 0x96, 0x96, 0x97, 0x97, 0x97,
0x98, 0x98, 0x98, 0x98, 0x98, 0x98, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x98, 0x98, 0x98, 0x98,
0x98, 0x98, 0x98, 0x98, 0x97, 0x97, 0x97, 0x97, 0x96, 0x96, 0x96, 0x95, 0x95, 0x95, 0x94, 0x94,
0x93, 0x93, 0x93, 0x92, 0x92, 0x91, 0x91, 0x90, 0x90, 0x8F, 0x8F, 0x8E, 0x8E, 0x8E, 0x8D, 0x8D,
0x8C, 0x8B, 0x8B, 0x8B, 0x8A, 0x8A, 0x89, 0x89, 0x88, 0x88, 0x87, 0x86, 0x86, 0x85, 0x85, 0x85,
0x84, 0x84, 0x83, 0x83, 0x82, 0x82, 0x81, 0x81, 0x81, 0x80, 0x80, 0x7F, 0x7F, 0x7E, 0x7E, 0x7E,
0x7D, 0x7D, 0x7D, 0x7C, 0x7C, 0x7C, 0x7B, 0x7B, 0x7B, 0x7A, 0x7A, 0x7A, 0x7A, 0x79, 0x79, 0x79,
0x79, 0x78, 0x78, 0x78, 0x78, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x76, 0x76, 0x76, 0x76,
0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76,
0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
0x77, 0x77, 0x77, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x79, 0x79, 0x79, 0x79, 0x79, 0x79,
0x7A, 0x7A, 0x7A, 0x7A, 0x7A, 0x7A, 0x7B, 0x7B, 0x7B, 0x7B, 0x7B, 0x7B, 0x7C, 0x7C, 0x7C, 0x7C,
0x7C, 0x7C, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E,
0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
0x80, 0x80, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81,
0x81, 0x81, 0x82, 0x81, 0x81, 0x82, 0x81, 0x82, 0x82, 0x81, 0x82, 0x81, 0x82, 0x82, 0x82, 0x82,
0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x81, 0x81, 0x82, 0x81,
0x82, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81,
0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x80, 0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7F, 0x7F,
0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F,
0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F,
0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7E, 0x7F, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E,
0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E,
0x7F, 0x7E, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7E, 0x7E, 0x7F, 0x7E, 0x7F, 0x7F, 0x7F, 0x7F, 0x7E,
0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F,
0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F,
0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F,
0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F,
0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F,
0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F,
0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F,
0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F,
0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F,
0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F,
0x7F, 0x7E, 0x7E, 0x7F, 0x7F, 0x7E, 0x7F, 0x7E, 0x7F, 0x7F, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7E,
0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7F,
0x7E, 0x7E, 0x7F, 0x7E, 0x7F, 0x7E, 0x7F, 0x7F, 0x7F, 0x7E, 0x7E, 0x7F, 0x7E, 0x7F, 0x7E, 0x7E,
0x7E, 0x7E, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7E, 0x7E,
0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7F, 0x7E,
0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E,
0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D,
0x7D, 0x7D, 0x7D,
};
| [
"Panda38@seznam.cz"
] | Panda38@seznam.cz |
67233f2d9b8c826b442bf1d8c6cae68cb4f18e05 | 88001ef8e6023558ea35870b431ee207b5c48f3e | /Source/ToonTanks/Actors/ProjectileBase.h | bbca002033ffa9ce3ced40784955244ef47e4222 | [] | no_license | ZhiyuanGu/ToonTanks | ca153cdceb2fac29feccfac0222673764cd86544 | aa68629ce200c01c42c8f7d27269547fccb7c75b | refs/heads/main | 2023-06-17T21:53:49.008085 | 2021-06-27T22:18:35 | 2021-06-27T22:18:35 | 380,847,372 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,901 | h | // Zhiyuan Gu 2020 All Rights Reserved
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "ProjectileBase.generated.h"
class UProjectileMovementComponent;
class UParticleSystemComponent;
UCLASS()
class TOONTANKS_API AProjectileBase : public AActor
{
GENERATED_BODY()
private:
// COMPONENTS
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components", meta = (AllowPrivateAccess = "true"))
UProjectileMovementComponent* ProjectileMovement;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components", meta = (AllowPrivateAccess = "true"))
UStaticMeshComponent* ProjectileMesh;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components", meta = (AllowPrivateAccess = "true"))
UParticleSystemComponent* ParticleTrail; // use component for trail so it can be attached and follow the projectile movement
// VARIABLES
UPROPERTY(EditAnywhere, Category = "Effects")
UParticleSystem* HitParticle;
UPROPERTY(EditDefaultsOnly, Category = "Damage")
TSubclassOf<UDamageType> DamageType;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Move", meta = (AllowPrivateAccess = "true"))
float MovementSpeed = 1300.0f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Damage", meta = (AllowPrivateAccess = "true"))
float Damage = 50.0f;
UPROPERTY(EditAnywhere, Category = "Effects")
USoundBase* LaunchSound;
UPROPERTY(EditAnywhere, Category = "Effects")
USoundBase* HitSound;
UPROPERTY(EditAnywhere, Category = "Effects")
TSubclassOf<UCameraShake> HitShake;
// FUNCTIONS
UFUNCTION()
void OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit);
public:
// Sets default values for this actor's properties
AProjectileBase();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
};
| [
"42496605+ZhiyuanGu@users.noreply.github.com"
] | 42496605+ZhiyuanGu@users.noreply.github.com |
134c7a99d461dc1c252a5247d4247e4fefde1ba3 | b2dbadcfecc50c7328196fe3632b4cc87042c635 | /ext/avif/ext/aom/test/error_block_test.cc | 3664ccf29f95f653fb6860c6d51b06e8da43cc0e | [
"BSL-1.0",
"LicenseRef-scancode-alliance-open-media-patent-1.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | EwoutH/colorist | ce6af59a9ad6ee17a5d112da637e1626c6488b21 | 8e8b586aceac9f54fecb648e94f6e4ad19593c76 | refs/heads/master | 2023-04-15T15:37:50.943391 | 2019-04-23T23:39:44 | 2019-04-23T23:39:44 | 185,622,495 | 0 | 0 | BSL-1.0 | 2019-05-08T14:31:15 | 2019-05-08T14:29:00 | C | UTF-8 | C++ | false | false | 8,137 | cc | /*
* Copyright (c) 2016, Alliance for Open Media. All rights reserved
*
* This source code is subject to the terms of the BSD 2 Clause License and
* the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
* was not distributed with this source code in the LICENSE file, you can
* obtain it at www.aomedia.org/license/software. If the Alliance for Open
* Media Patent License 1.0 was not distributed with this source code in the
* PATENTS file, you can obtain it at www.aomedia.org/license/patent.
*/
#include <cmath>
#include <cstdlib>
#include <string>
#include "third_party/googletest/src/googletest/include/gtest/gtest.h"
#include "config/aom_config.h"
#include "config/av1_rtcd.h"
#include "test/acm_random.h"
#include "test/clear_system_state.h"
#include "test/register_state_check.h"
#include "test/util.h"
#include "av1/common/entropy.h"
#include "aom/aom_codec.h"
#include "aom/aom_integer.h"
using libaom_test::ACMRandom;
namespace {
const int kNumIterations = 1000;
typedef int64_t (*ErrorBlockFunc)(const tran_low_t *coeff,
const tran_low_t *dqcoeff,
intptr_t block_size, int64_t *ssz, int bps);
typedef ::testing::tuple<ErrorBlockFunc, ErrorBlockFunc, aom_bit_depth_t>
ErrorBlockParam;
class ErrorBlockTest : public ::testing::TestWithParam<ErrorBlockParam> {
public:
virtual ~ErrorBlockTest() {}
virtual void SetUp() {
error_block_op_ = GET_PARAM(0);
ref_error_block_op_ = GET_PARAM(1);
bit_depth_ = GET_PARAM(2);
}
virtual void TearDown() { libaom_test::ClearSystemState(); }
protected:
aom_bit_depth_t bit_depth_;
ErrorBlockFunc error_block_op_;
ErrorBlockFunc ref_error_block_op_;
};
TEST_P(ErrorBlockTest, OperationCheck) {
ACMRandom rnd(ACMRandom::DeterministicSeed());
DECLARE_ALIGNED(16, tran_low_t, coeff[4096]);
DECLARE_ALIGNED(16, tran_low_t, dqcoeff[4096]);
int err_count_total = 0;
int first_failure = -1;
intptr_t block_size;
int64_t ssz;
int64_t ret;
int64_t ref_ssz;
int64_t ref_ret;
const int msb = bit_depth_ + 8 - 1;
for (int i = 0; i < kNumIterations; ++i) {
int err_count = 0;
block_size = 16 << (i % 9); // All block sizes from 4x4, 8x4 ..64x64
for (int j = 0; j < block_size; j++) {
// coeff and dqcoeff will always have at least the same sign, and this
// can be used for optimization, so generate test input precisely.
if (rnd(2)) {
// Positive number
coeff[j] = rnd(1 << msb);
dqcoeff[j] = rnd(1 << msb);
} else {
// Negative number
coeff[j] = -rnd(1 << msb);
dqcoeff[j] = -rnd(1 << msb);
}
}
ref_ret =
ref_error_block_op_(coeff, dqcoeff, block_size, &ref_ssz, bit_depth_);
ASM_REGISTER_STATE_CHECK(
ret = error_block_op_(coeff, dqcoeff, block_size, &ssz, bit_depth_));
err_count += (ref_ret != ret) | (ref_ssz != ssz);
if (err_count && !err_count_total) {
first_failure = i;
}
err_count_total += err_count;
}
EXPECT_EQ(0, err_count_total)
<< "Error: Error Block Test, C output doesn't match optimized output. "
<< "First failed at test case " << first_failure;
}
TEST_P(ErrorBlockTest, ExtremeValues) {
ACMRandom rnd(ACMRandom::DeterministicSeed());
DECLARE_ALIGNED(16, tran_low_t, coeff[4096]);
DECLARE_ALIGNED(16, tran_low_t, dqcoeff[4096]);
int err_count_total = 0;
int first_failure = -1;
intptr_t block_size;
int64_t ssz;
int64_t ret;
int64_t ref_ssz;
int64_t ref_ret;
const int msb = bit_depth_ + 8 - 1;
int max_val = ((1 << msb) - 1);
for (int i = 0; i < kNumIterations; ++i) {
int err_count = 0;
int k = (i / 9) % 9;
// Change the maximum coeff value, to test different bit boundaries
if (k == 8 && (i % 9) == 0) {
max_val >>= 1;
}
block_size = 16 << (i % 9); // All block sizes from 4x4, 8x4 ..64x64
for (int j = 0; j < block_size; j++) {
if (k < 4) {
// Test at positive maximum values
coeff[j] = k % 2 ? max_val : 0;
dqcoeff[j] = (k >> 1) % 2 ? max_val : 0;
} else if (k < 8) {
// Test at negative maximum values
coeff[j] = k % 2 ? -max_val : 0;
dqcoeff[j] = (k >> 1) % 2 ? -max_val : 0;
} else {
if (rnd(2)) {
// Positive number
coeff[j] = rnd(1 << 14);
dqcoeff[j] = rnd(1 << 14);
} else {
// Negative number
coeff[j] = -rnd(1 << 14);
dqcoeff[j] = -rnd(1 << 14);
}
}
}
ref_ret =
ref_error_block_op_(coeff, dqcoeff, block_size, &ref_ssz, bit_depth_);
ASM_REGISTER_STATE_CHECK(
ret = error_block_op_(coeff, dqcoeff, block_size, &ssz, bit_depth_));
err_count += (ref_ret != ret) | (ref_ssz != ssz);
if (err_count && !err_count_total) {
first_failure = i;
}
err_count_total += err_count;
}
EXPECT_EQ(0, err_count_total)
<< "Error: Error Block Test, C output doesn't match optimized output. "
<< "First failed at test case " << first_failure;
}
TEST_P(ErrorBlockTest, DISABLED_Speed) {
ACMRandom rnd(ACMRandom::DeterministicSeed());
DECLARE_ALIGNED(16, tran_low_t, coeff[4096]);
DECLARE_ALIGNED(16, tran_low_t, dqcoeff[4096]);
intptr_t block_size;
int64_t ssz;
int num_iters = 100000;
int64_t ref_ssz;
int k;
const int msb = bit_depth_ + 8 - 1;
for (int i = 0; i < 9; ++i) {
block_size = 16 << (i % 9); // All block sizes from 4x4, 8x4 ..64x64
for (k = 0; k < 9; k++) {
for (int j = 0; j < block_size; j++) {
if (k < 5) {
if (rnd(2)) {
// Positive number
coeff[j] = rnd(1 << msb);
dqcoeff[j] = rnd(1 << msb);
} else {
// Negative number
coeff[j] = -rnd(1 << msb);
dqcoeff[j] = -rnd(1 << msb);
}
} else {
if (rnd(2)) {
// Positive number
coeff[j] = rnd(1 << 14);
dqcoeff[j] = rnd(1 << 14);
} else {
// Negative number
coeff[j] = -rnd(1 << 14);
dqcoeff[j] = -rnd(1 << 14);
}
}
}
aom_usec_timer ref_timer, test_timer;
aom_usec_timer_start(&ref_timer);
for (int i = 0; i < num_iters; ++i) {
ref_error_block_op_(coeff, dqcoeff, block_size, &ref_ssz, bit_depth_);
}
aom_usec_timer_mark(&ref_timer);
const int elapsed_time_c =
static_cast<int>(aom_usec_timer_elapsed(&ref_timer));
aom_usec_timer_start(&test_timer);
for (int i = 0; i < num_iters; ++i) {
error_block_op_(coeff, dqcoeff, block_size, &ssz, bit_depth_);
}
aom_usec_timer_mark(&test_timer);
const int elapsed_time_simd =
static_cast<int>(aom_usec_timer_elapsed(&test_timer));
printf(
" c_time=%d \t simd_time=%d \t "
"gain=%d \n",
elapsed_time_c, elapsed_time_simd,
(elapsed_time_c / elapsed_time_simd));
}
}
}
#if (HAVE_SSE2 || HAVE_AVX)
using ::testing::make_tuple;
INSTANTIATE_TEST_CASE_P(
SSE2, ErrorBlockTest,
::testing::Values(make_tuple(&av1_highbd_block_error_sse2,
&av1_highbd_block_error_c, AOM_BITS_10),
make_tuple(&av1_highbd_block_error_sse2,
&av1_highbd_block_error_c, AOM_BITS_12),
make_tuple(&av1_highbd_block_error_sse2,
&av1_highbd_block_error_c, AOM_BITS_8)));
#endif // HAVE_SSE2
#if (HAVE_AVX2)
using ::testing::make_tuple;
INSTANTIATE_TEST_CASE_P(
AVX2, ErrorBlockTest,
::testing::Values(make_tuple(&av1_highbd_block_error_avx2,
&av1_highbd_block_error_c, AOM_BITS_10),
make_tuple(&av1_highbd_block_error_avx2,
&av1_highbd_block_error_c, AOM_BITS_12),
make_tuple(&av1_highbd_block_error_avx2,
&av1_highbd_block_error_c, AOM_BITS_8)));
#endif // HAVE_AVX2
} // namespace
| [
"jdrago@netflix.com"
] | jdrago@netflix.com |
fed5f5e7ecd746027411948d6c64d730253a4c9a | 0f3cd546c1f60b1a47d045c9cbc6ab005d039aa9 | /Intro/Langplay.cpp | 148db6da5e8c8d2933d69c9815341ea0d31e2f30 | [] | no_license | isliulin/legacy-vc6 | 62ea49025c519227af6cf73e5a4d1cc451568eb0 | 5d16f6e0bd71e3dff474cc2394263482c014ae56 | refs/heads/master | 2023-07-07T20:55:51.067797 | 2015-12-17T21:30:53 | 2015-12-17T21:30:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,050 | cpp | #define INC_OLE2
#include <windows.h>
#include <windowsx.h>
#include <mmsystem.h>
#include <commdlg.h>
#include <string.h>
#include <stdlib.h>
#include <direct.h>
#include <digitalv.h>
#include <vfw.h>
#include "langplay.h"
#include <profiles.h>
#include <int2str.h>
HWND hwndMovie; /* window handle of the movie */
char szAppName [] = "IntroPlay";
/* function declarations */
long FAR PASCAL WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
void exitintro();
HWND initApp(HINSTANCE hInstance, HINSTANCE hPrevInstance, int nCmdShow)
{
HWND hWnd; /* window handle to return */
int iWinHeight;
WORD wVer;
char tmpstr[64];
/* first let's make sure we are running on 1.1 */
wVer = HIWORD(VideoForWindowsVersion());
if (wVer < 0x010a){
/* oops, we are too old, blow out of here */
MessageBeep(MB_ICONHAND);
MessageBox(NULL, "Video for Windows version is too old",
"LangPlay Error", MB_OK|MB_ICONSTOP);
return FALSE;
}
if (!hPrevInstance){
WNDCLASS wndclass;
wndclass.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon (hInstance, "AppIcon");
wndclass.hCursor = LoadCursor (NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
wndclass.lpszMenuName = szAppName;
wndclass.lpszClassName = szAppName;
if (!RegisterClass(&wndclass)){
MessageBox(NULL, "RegisterClass failure", szAppName, MB_OK);
return NULL;
}
}
iWinHeight = GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CYMENU) +
(GetSystemMetrics(SM_CYFRAME) * 2);
/* create the main window for the app */
hWnd = CreateWindow(szAppName, szAppName, //WS_SYSMENU |
WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, 320, 240,
NULL, NULL, hInstance, NULL);
if (hWnd == NULL){
MessageBox(NULL, "CreateWindow failure", szAppName, MB_OK);
return NULL;
}
/* Show the main window */
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
/* create the movie window using MCIWnd that has no file open initially */
hwndMovie = MCIWndCreate(hWnd, hInstance, MCIWNDF_NOPLAYBAR |WS_CHILD |WS_VISIBLE | MCIWNDF_NOOPEN |
MCIWNDF_NOERRORDLG | MCIWNDF_NOTIFYSIZE|MCIWNDF_NOTIFYMODE , NULL);
if (!hwndMovie){
/* we didn't get the movie window, destroy the app's window and bail out */
DestroyWindow(hWnd);
exitintro();
return NULL;
}
GetPrivateProfileStringCurrentDir("config.ini","intro","avifile",tmpstr,64);
if (MCIWndOpen(hwndMovie, tmpstr, 0) == 0){
/* we opened the file o.k., now set up to */
/* play it. */
ShowWindow(hwndMovie, SW_SHOW);
} else {
/* generic error for open */
MessageBox(hWnd, "Unable to open Movie", NULL,
MB_ICONEXCLAMATION|MB_OK);
exitintro();
}
MCIWndPlay(hwndMovie);
return hWnd;
}
/*--------------------------------------------------------------+
| WinMain - main routine. |
| |
+--------------------------------------------------------------*/
int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpszCmdParam, int nCmdShow)
{
HWND hWnd;
MSG msg;
if ((hWnd = initApp(hInstance, hPrevInstance,nCmdShow)) == NULL)
return 0; /* died initializing, bail out */
while (GetMessage(&msg, NULL, 0, 0)){
TranslateMessage(&msg);
DispatchMessage(&msg);
//MCIWndPlay(hwndMovie);
}
return msg.wParam;
}
/*--------------------------------------------------------------+
| WndProc - window proc for the app |
| |
+--------------------------------------------------------------*/
long FAR PASCAL WndProc (HWND hWnd, UINT message, WPARAM wParam,
LPARAM lParam)
{
PAINTSTRUCT ps;
RECT rect;
POINT size;
switch (message){
case WM_KEYDOWN:
switch(wParam)
{
case VK_ESCAPE:
exitintro();
break;
}
case WM_CREATE:
return 0;
case WM_INITMENUPOPUP:
break;
case WM_COMMAND:
return 0;
case WM_PAINT:
BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
return 0;
case WM_SIZE:
break;
case WM_DESTROY:
exitintro();
return 0;
case MCIWNDM_NOTIFYSIZE:
GetWindowRect(hwndMovie,&rect);
AdjustWindowRect(&rect,WS_OVERLAPPEDWINDOW |WS_CLIPCHILDREN,FALSE);
size.x=rect.right-rect.left;
size.y=rect.bottom-rect.top;
rect.left=GetSystemMetrics(SM_CXSCREEN)/2-size.x/2;
rect.right=rect.left+size.x;
rect.top=GetSystemMetrics(SM_CYSCREEN)/2-size.y/2;
rect.bottom=rect.top+size.y;
SetWindowPos(hWnd,HWND_TOP,rect.left,rect.top,rect.right-rect.left,rect.bottom-rect.top,SWP_DRAWFRAME);
break;
case MCIWNDM_NOTIFYMODE:
if((LONG)lParam==525)
exitintro();
break;
case WM_ACTIVATE:
case WM_QUERYNEWPALETTE:
case WM_PALETTECHANGED:
//
// Forward palette-related messages through to the MCIWnd,
// so it can do the right thing.
//
if (hwndMovie)
return SendMessage(hwndMovie, message, wParam, lParam);
break;
} /* switch */
return DefWindowProc(hWnd, message, wParam, lParam);
}
void exitintro()
{
char tmpstr[64];
MCIWndClose(hwndMovie); // close an open movie
MCIWndDestroy(hwndMovie); // now destroy the MCIWnd window
PostQuitMessage(0);
GetPrivateProfileStringCurrentDir("config.ini","intro","startfile",tmpstr,64);
WinExec(tmpstr,SW_SHOW);
} | [
"sebastian.kotulla@gmx.de"
] | sebastian.kotulla@gmx.de |
413539e5136e5d91176f0d572b159e5466723e56 | 845d3e85651ad3bf8c730b0a3add807894631119 | /Satisfiability/Solvers/OKsolver/SAT2002/plans/milestones.hpp | 22e3ff6ef041bc0ce53b95c968f26a003eabe808 | [] | no_license | PJames/oklibrary | 6516e1150fd1d040a91a2ba7e48d9b3eba976edf | 38983feadd7e54ab19a2c2a94b6b39887265de17 | refs/heads/master | 2020-12-24T13:20:36.195708 | 2008-10-29T21:09:01 | 2008-10-29T21:09:01 | 69,392 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,018 | hpp | // Oliver Kullmann, 18.8.2007 (Swansea)
/* Copyright 2007, 2008 Oliver Kullmann
This file is part of the OKlibrary. OKlibrary is free software; you can redistribute
it and/or modify it under the terms of the GNU General Public License as published by
the Free Software Foundation and included in this library; either version 3 of the
License, or any later version. */
/*!
\file Solvers/OKsolver/SAT2002/plans/milestones.hpp
\module_version OKsolver/SAT2002 0.9.4 (16.9.2008)
\par Version 0.9.5
\par
In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled:
- OUTPUTTREEDATAXML
\par Version 0.9.6
\par
In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled:
- Documentation problems
- Language standards
\par Version 0.9.7
\par
In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled:
- Buildsystem
\par Version 0.9.8
\par
In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled:
- Complete the help facilities of the OKsolver
\par Version 0.9.9
\par
In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled:
- Write docus-pages
\par Version 1.0
\par
Create a tag, stating that the basically unaltered original OKsolver
has now been made fully available.
\par Version 1.0.1
\par
In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled:
- Add doxygen-documentation
- Eliminate old history in code
\par Version 1.0.2
\par
In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled:
- Create systematic application tests
\par Version 1.0.3
\par
In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled:
- Add asserts throughout
\par Version 1.0.4
\par
In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled:
- Investigate unit-testing
\par Version 1.0.5
\par
In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled:
- Correct computation of basic statistics
\par Version 1.0.6
\par
In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled:
- Incorrect output of monitoring-data to files
\par Version 1.1
\par
The fully tested and specified original OKsolver (parallel in C and
in Maxima).
\par Version 1.2.1
\par
In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled:
- Improve statistics
\par Version 1.2.2
\par
In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled:
- Declare variable as close to their first usage as possible
\par Version 1.2.3
\par
In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled:
- Use const-qualification
\par Version 1.2.4
\par
In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled:
- Use restrict-qualification
\par Version 1.2.5
\par
In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled:
- Elimination of compile-time options
\par Version 1.3
\par
The fully cleaned-up and documented original OKsolver.
\par Version 1.4
\par
Make nearly everything also available at the Maxima-level, and make
sure that both levels fully coincide.
\par Version 1.5
\par
In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled:
- Enable finding all solutions
\par Version 1.5.1
\par
In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled:
- Apply time-measurements
\par Version 1.6
\par
We have timing-date available.
\par Version 1.7
\par
Document the extensive database-data.
\par Version 2.0
\par
Now the original OKsolver is also fully reflected and fully specified.
-------------------------------------------------------------------------------------------------------------------------------------
\par Version history
- 0.9 : 18.8.2007; initial version number (the old OKsolver mainly unchanged since SAT2002; a bug found by Marijn Heule showed up with newer versions of gcc)
- 0.9.1 : 20.8.2007; two bugs corrected, linking behaviour corrected, basic code maintenance performed, and basic application tests written and executed. The OKsolver in the standard version appears now to be bug-free.
- 0.9.2 : 14.9.2007; basic tests for main variants established. Now also the main variants appear to be bug-free.
- 0.9.3 : 22.9.2007; completed planning for counting all satisfying assignments (implementation postponed), and on the way also code and documentation maintenance.
- 0.9.4 : 16.9.2008; various "spontaneous" workings: improved the build, extended plans, created application tests, basic code overhauls, using SIGINT instead of SIGUSR2, better documentation, corrected output of statistics.
*/
| [
"O.Kullmann@Swansea.ac.uk"
] | O.Kullmann@Swansea.ac.uk |
d03a49d30c5c9323359bc7b5c8cf5d200d488d8b | c3ffa07567d3d29a7439e33a6885a5544e896644 | /CodeForce/100482-C.cpp | 4d060a3635c286f969057e4f8b9bef66a9ae6650 | [] | no_license | a00012025/Online_Judge_Code | 398c90c046f402218bd14867a06ae301c0c67687 | 7084865a7050fc09ffb0e734f77996172a93d3ce | refs/heads/master | 2018-01-08T11:33:26.352408 | 2015-10-10T23:20:35 | 2015-10-10T23:20:35 | 44,031,127 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 828 | cpp | #include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
char s[200010] ;
main()
{
int T,cnt=0,a[30];
scanf("%d",&T) ;
while(++cnt && cnt<=T)
{
gets(s) ; int q ;
while(s[0]=='\0' || s[0]==49 || s[0]=='\n') gets(s) ;
printf("Case #%d:\n",cnt) ;
scanf("%d",&q) ;
while(q--)
{
char c; int l,r ;
scanf("%c",&c) ;
while(c!='g' && c!='s') scanf("%c",&c) ;
scanf("%d %d",&l,&r) ;
if(c=='s') sort(s+l,s+r+1) ;
else
{
memset(a,0,sizeof(a)) ;
for(int i=l;i<=r;i++) a[s[i]-'A'+1]++ ;
for(int i=1;i<=26;i++) printf("%d ",a[i]);
printf("\n") ;
}
}
}
}
| [
"a00012025@gmail.com"
] | a00012025@gmail.com |
494a99e22d762554335b6f084408077c6a5f00c1 | dff1748a78a317af81cc4e2a721bcda9915a538b | /Regelungscontroller-neu2/IO.ino | a0f5e59cfe16dd7ed8a00a1dcfc0e08cb69735e8 | [] | no_license | lumascet/supercharger | 1985cdd53e2ba4fd0fa4194c4efbab1d7b134018 | 2f936554cb3002a4903d4be40527fe933a493038 | refs/heads/master | 2020-07-30T01:10:25.450349 | 2020-05-15T14:58:50 | 2020-05-15T14:58:50 | 210,030,994 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,766 | ino | //---Input & Output operations---
void initPins(){
//PIN Setup
pinMode(PIN_PWOK, INPUT);
pinMode(PIN_PSON, OUTPUT);
digitalWrite(PIN_PSON, HIGH);
pinMode(PIN_RX, INPUT_PULLUP);
pinMode(PIN_TX, INPUT_PULLUP);
pinMode(PIN_VSENSE, INPUT);
pinMode(PIN_LEDCURR, OUTPUT);
digitalWrite(PIN_LEDCURR, LOW);
pinMode(PIN_LEDVOLT, OUTPUT);
digitalWrite(PIN_LEDVOLT, LOW);
pinMode(PIN_DACSS, OUTPUT);
digitalWrite(PIN_DACSS, HIGH);
pinMode(PIN_ADCSS, OUTPUT);
digitalWrite(PIN_ADCSS, HIGH);
pinMode(PIN_CNV, OUTPUT);
adcConversion();
pinMode(PIN_BUSY, INPUT);
}
void setOutput(bool state){//set output State
if(state) digitalWrite(PIN_PSON, LOW);
else digitalWrite(PIN_PSON, HIGH);
}
void changeMode(uint8_t mode){//change ADC inputs according to mode
if(output_state == 0){
adc_voltage_port = 0;
return;
}
switch(mode){
case 0:
adc_voltage_port = 0;
adc_current_port = 3;
Serial.println("Mode 0");
break;
case 1:
if(external_measure)adc_voltage_port = 1;
else adc_voltage_port = 2;
adc_current_port = 3;
Serial.println("Mode 1");
break;
case 2:
if(external_measure)adc_voltage_port = 5;
else adc_current_port = 4;
adc_current_port = 3;
Serial.println("Mode 2");
break;
case 3:
//not implemented
break;
}
}
void fanState(bool state){//normal or high fan state
if (state) {
controlStatusRegister |= (1 << FAN_HI_BIT);
setControlStatusRegister(controlStatusRegister); // SET FAN HIGH
delay(I2C_MESSAGE_DELAY);
} else {
controlStatusRegister &= ~(1 << FAN_HI_BIT);
setControlStatusRegister(controlStatusRegister); // SET FAN LOW
delay(I2C_MESSAGE_DELAY);
}
}
| [
"lukas.schroeer@gmx.at"
] | lukas.schroeer@gmx.at |
8e7f62fb16b3cf57f23d3eaaf66833a9fdd10fb9 | 70de48a6e65e468e2b30a0c0fd74e591b242a16c | /Basic Searching and Sorting Algorithms/Selection Sort/selection_sort(iterative).cpp | 318cddf2fbf3a01dc79a786924db71a5d3af201f | [] | no_license | ihjohny/Algorithms-Implementation | 130be91380f96af05fdaada813d57321b859d24b | c30aefdee716c4a45780299b10f24b5351c01ea2 | refs/heads/master | 2020-03-22T10:18:03.439914 | 2019-10-22T06:29:59 | 2019-10-22T06:29:59 | 139,894,399 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 721 | cpp | //selection_sort(iterative)
/*
* Unstable
* In place
* Worst case complexity O(n^2)
* Space complexityO (1)
*
*/
#include<iostream>
#include<cstdio>
#define SZ 10
using namespace std;
int main()
{
int Arra[SZ]={777,55,45,2,14,878,4,145,14,99};
int i,j,k,temp;
int count=0; //for counting time complixty (how many time the loop iterate)
for(i=0;i<SZ-1;i++)
{
for(j=i+1;j<SZ;j++)
{
count++; //for counting loop intertion
if(Arra[j]<Arra[k])
{
k=j;
}
}
if(k!=i)
{
//swaping
temp=Arra[i];
Arra[i]=Arra[k];
Arra[k]=temp;
}
}
//print
for(i=0;i<SZ;i++)
{
cout<<Arra[i]<<" ";
}
cout<<endl;
cout<<"time compxity (loop iteration) "<<count<<endl;
return 0;
}
| [
"ihjony23@gmail.com"
] | ihjony23@gmail.com |
9e7aa2a14024f4050fae1cb37fa93bb6736fe185 | 79eb737b20cfd332c84d5a6926365868f94ebdad | /src/PortWriter.cpp | 81f43bf841943ea35b896da45e75ec6d74ee8f5a | [] | no_license | johnty/libYARP_OS_iOS | 70d6555d8e0bc05b7feaa8711fca6efe9277e16c | 65bc7bf382e3de1004acff408b110808da3ff9c0 | refs/heads/master | 2020-08-26T20:08:47.955399 | 2014-02-12T01:02:00 | 2014-02-12T01:02:00 | 16,746,103 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 402 | cpp | // -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-
/*
* Copyright (C) 2006 RobotCub Consortium
* Authors: Paul Fitzpatrick
* CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT
*/
#include <yarp/os/PortWriter.h>
yarp::os::PortWriter::~PortWriter() {
}
void yarp::os::PortWriter::onCompletion() {
}
void yarp::os::PortWriter::onCommencement() {
}
| [
"johntywang@gmail.com"
] | johntywang@gmail.com |
46d49d79978ab4fdfa2308c874fb5934dd3f4ade | 153b3230aa3235a5003642d07e114fb6bdf36caa | /Assignment2/Program/build-HFractal-Desktop_Qt_5_11_3_MinGW_32bit-Debug/debug/moc_gtextarea.cpp | cd2bbc116e57a4637596f2d525f47c0a1ffd496b | [] | no_license | MeloYang05/CUHK-CSC3002-Assignment | dc6e4c4e73194a0de324ece850880d22c6f84373 | a5156f4edf13b59291647e566b7766ec42faccd3 | refs/heads/master | 2020-07-12T13:05:42.498424 | 2019-08-28T01:54:34 | 2019-08-28T01:54:34 | 204,825,810 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,935 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'gtextarea.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.11.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../H-Fractal/lib/StanfordCPPLib/graphics/gtextarea.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'gtextarea.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.11.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata__Internal_QTextEdit_t {
QByteArrayData data[5];
char stringdata0[57];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata__Internal_QTextEdit_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata__Internal_QTextEdit_t qt_meta_stringdata__Internal_QTextEdit = {
{
QT_MOC_LITERAL(0, 0, 19), // "_Internal_QTextEdit"
QT_MOC_LITERAL(1, 20, 12), // "handleScroll"
QT_MOC_LITERAL(2, 33, 0), // ""
QT_MOC_LITERAL(3, 34, 5), // "value"
QT_MOC_LITERAL(4, 40, 16) // "handleTextChange"
},
"_Internal_QTextEdit\0handleScroll\0\0"
"value\0handleTextChange"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data__Internal_QTextEdit[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 1, 24, 2, 0x0a /* Public */,
4, 0, 27, 2, 0x0a /* Public */,
// slots: parameters
QMetaType::Void, QMetaType::Int, 3,
QMetaType::Void,
0 // eod
};
void _Internal_QTextEdit::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
_Internal_QTextEdit *_t = static_cast<_Internal_QTextEdit *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->handleScroll((*reinterpret_cast< int(*)>(_a[1]))); break;
case 1: _t->handleTextChange(); break;
default: ;
}
}
}
QT_INIT_METAOBJECT const QMetaObject _Internal_QTextEdit::staticMetaObject = {
{ &QTextEdit::staticMetaObject, qt_meta_stringdata__Internal_QTextEdit.data,
qt_meta_data__Internal_QTextEdit, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *_Internal_QTextEdit::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *_Internal_QTextEdit::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata__Internal_QTextEdit.stringdata0))
return static_cast<void*>(this);
if (!strcmp(_clname, "_Internal_QWidget"))
return static_cast< _Internal_QWidget*>(this);
return QTextEdit::qt_metacast(_clname);
}
int _Internal_QTextEdit::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QTextEdit::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 2)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 2;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"lianyixiaofan@foxmail.com"
] | lianyixiaofan@foxmail.com |
cf9a69466e94f8f5753d83b7db8e5ac25b40b19b | 044f85c8f00da4ad6001ed53363d829e034849a8 | /32.cpp | 0919c8095f48afeda42a655770cd0eac914f7ebd | [] | no_license | anand9git/DSA-code | 877c30d779d9de492d29f58ab37650105b070395 | e90a64ee8469754eda8d734e203ea16d4c53f174 | refs/heads/master | 2023-02-27T17:08:40.928070 | 2021-02-03T18:12:46 | 2021-02-03T18:12:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 541 | cpp | #include <bits/stdc++.h>
#include <iostream>
using namespace std;
int main(){
//program to find first row with max no of 1s if all rows are sorted and contain only 0 and 1 in O(m+n) time.
int m, n;
cin>>m>>n;
int arr[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++)cin>>arr[i][j];
}
int ans = 0;
int j = n-1;
for(int i=0;i<m;i++){
while(j>=0 && arr[i][j]==1){
j--;
ans = i;
}
}
if(arr[ans][j+1]==0) cout<<-1;
cout<<ans<<endl;
return 0;
}
| [
"aggarwalanand9@gmail.com"
] | aggarwalanand9@gmail.com |
8b9fa02c363dd4f82ddd8cb1b2c25dd19d53b15e | 5880f1fa2a1d572050c2ccd63a3761dd1f75caa1 | /07.Strings/02.AnagramsUsingCountCharacters.cpp | 2a8f8732a159d5210fe91020481e9f454b626179 | [] | no_license | mayank8200/Data-Structure-and-Algo-for-Interview-Preparation | 3bd7856530da92182a4afde0a15cfc6a932fc7f6 | 9e830ec03c8dec5f4069168b290fcaff8d1167ea | refs/heads/master | 2022-10-11T23:20:22.105296 | 2020-06-09T09:20:02 | 2020-06-09T09:20:02 | 263,544,924 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 730 | cpp | #include <bits/stdc++.h>
using namespace std;
bool anagrams(string s1,string s2)
{
int a = s1.length();
int b = s2.length();
if(a!=b)
{
return false;
}
int c1[256] = {0};
int c2[256] = {0};
for(int i=0;i<a;i++)
{
c1[s1[i]]++;
c2[s2[i]]++;
}
for(int i=0;i<256;i++)
{
if(c1[i]!=c2[i])
return false;
}
return true;
}
int main()
{
string s1,s2;
cout << "Enter two strings to check:";
cin >> s1 >> s2;
if (anagrams(s1, s2))
cout << "The two strings are anagram of each other";
else
cout << "The two strings are not anagram of each other";
return 0;
} | [
"41484766+mayank8200@users.noreply.github.com"
] | 41484766+mayank8200@users.noreply.github.com |
43cefc03da549c578619f90e9a87150ce85fc211 | 893f7883bc472570e1c407ccdee6da9f3df78580 | /src/assert/test/testAssertWithNDEBUG.h | 9d769f6f327d25421365deee04076c2ed300c03d | [
"MIT"
] | permissive | dpicken/utils | a7bde29d760daff4947a599a20db7d0a640b5c08 | 53d214cd81d45c29578e3165c1b188057e6ac9e1 | refs/heads/master | 2021-07-17T07:46:05.881675 | 2020-04-23T22:58:58 | 2020-04-30T04:52:58 | 133,750,175 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 237 | h | #ifndef assert_test_testAssertWithNDEBUG_h
#define assert_test_testAssertWithNDEBUG_h
namespace assert { namespace test {
void testAssertWithNDEBUG();
} } // namespace assert::test
#endif // ifndef assert_test_testAssertWithNDEBUG_h
| [
"dpicken@users.noreply.github.com"
] | dpicken@users.noreply.github.com |
2032a759845d3a2b24b6361ef5b463f0727a655f | 9ded4c4fc135c2154ea85bc6a8fb4dcf2ce84863 | /wikioi/1701.cpp | ec4b5147c274d28b18cf32eea483d81965b8083e | [] | no_license | yanhuanwang/codekata | 5389a1e958c7c2d79582098b89a26648dcc188ba | 9369f7461ddcc731b318bc701b2f17ad2990f285 | refs/heads/master | 2016-09-06T01:17:37.255599 | 2014-06-19T12:31:06 | 2014-06-19T12:31:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,623 | cpp | ///*
// * A.cpp
// *
// * Created on: Apr 26, 2014
// * Author: ecaiyan
// */
//
//#include <cstdio>
//#include <cstdlib>
//#include <memory.h>
//#include <algorithm>
//#include <string>
//#include <map>
////#include <unordered_map>
////#include <unordered_set>
//#include <set>
//#include <vector>
//#include <cmath>
//#include <climits>
//#include <queue>
//#include <cassert>
//#include <iostream>
//#include <sstream>
//#include <utility>
//#include <bitset>
//using namespace std;
//#define PI 3.14159265358979323846264338327950288
//vector<string> Tokenize(string s, string ch) {
// vector<string> ret;
// for (int p = 0, p2; p < s.size(); p = p2 + 1) {
// p2 = s.find_first_of(ch, p);
// if (p2 == -1)
// p2 = s.size();
// if (p2 - p > 0)
// ret.push_back(s.substr(p, p2 - p));
// }
// return ret;
//}
//int my_abs(int a) {
// int i = a >> 31;
// return ((a ^ i) - i);
//}
//
//vector<int> TokenizeInt(string s, string ch) {
// vector<int> ret;
// vector<string> p = Tokenize(s, ch);
// for (int i = 0; i < p.size(); i++)
// ret.push_back(atoi(p[i].c_str()));
// return ret;
//}
//int process(int A, int B, int K) {
// int res = 0;
// return res;
//}
//unsigned long f[50005] = { 0, 1 };
//void set1() {
// unsigned long i = 2, j, k = 2, p = 2;
// while (1) {
// for (j = 1; j <= p; j++) {
// f[i] = (f[i - 1] + k) % 10000;
// i++;
// if (i > 50000)
// return;
// }
// k = k * 2;
// k = k % 10000;
// p++;
// }
//}
//int main() {
// set1();
// long n;
// cin>>n;
// cout<<f[n];
//// while (scanf("%ld", &n) != EOF) {
//// printf("%ld\n", f[n]);
//// }
//// return 0;
// return 0;
//}
//
| [
"martin.yan.seu@gmail.com"
] | martin.yan.seu@gmail.com |
2cb5aab6457963a2bb65d0b02f65951196504d48 | 97d1bfba6adafc0fbdd68bdfbeb314d33aa364be | /astar/2012-2013/121211/b/b.cpp | f63f0ca4e44f72cbb340499d73623a084df04f9b | [] | no_license | github188/MyCode-1 | 26069f08222b154c08308a72a61f8e9f879a447e | 2227b9dd9a13114a1b2b294c3e70253b16f88538 | refs/heads/master | 2020-12-24T11:24:54.215740 | 2014-04-21T04:15:54 | 2014-04-21T04:15:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,736 | cpp | #include<stdio.h>
#define p 2012
int a[251],c[2001][2001],f[251][2001][2],h[2012][2012],ans[251];
int main()
{
a[1]=1;
for (int i=2;i<=250;i++) a[i]=a[i-1]+2;
for (int i=0;i<p;i++)
for (int j=0;j<p;j++) h[i][j]=i*j%p;
c[0][0]=1;
for (int i=1;i<=2000;i++)
for (int j=0;j<=2000;j++)
{
c[i][j]=c[i-1][j];
if (j>0) c[i][j]+=c[i-1][j-1];
if (c[i][j]>=p) c[i][j]-=p;
}
f[1][0][0]=f[1][1][1]=1;
for (int i=2;i<=250;i++)
for (int j=0;j<=a[i];j++)
for (int k=0;(k<=a[i]-j)&&(k<=a[i-1]);k++)
{
if (a[i]-k-1>=j)
{
f[i][j][0]+=h[f[i-1][k][0]][c[a[i]-k-1][j]];
if (f[i][j][0]>=p) f[i][j][0]-=p;
if (a[i]-k-2>=j)
{
f[i][j][0]+=h[f[i-1][k][1]][c[a[i]-k-2][j]];
if (f[i][j][0]>=p) f[i][j][0]-=p;
}
}
if (j>0)
{
f[i][j][1]+=h[f[i-1][k][0]][c[a[i]-k-1][j-1]];
if (f[i][j][1]>=p) f[i][j][1]-=p;
if (a[i]-k-1>=j)
{
f[i][j][1]+=h[f[i-1][k][1]][c[a[i]-k-2][j-1]];
if (f[i][j][1]>=p) f[i][j][1]-=p;
}
}
}
for (int i=1;i<=250;i++)
{
for (int j=0;j<=a[i];j++)
{
ans[i]+=f[i][j][0];
if (ans[i]>=p) ans[i]-=p;
ans[i]+=f[i][j][1];
if (ans[i]>=p) ans[i]-=p;
}
int tmp=1;
for (int k=0;k<4;k++) tmp=tmp*ans[i]%p;
ans[i]=tmp;
}
int n;
while (scanf("%d",&n)!=EOF)
{
printf("%d\n",ans[n/2]);
}
return 0;
}
| [
"wcwswswws@gmail.com"
] | wcwswswws@gmail.com |
06a865379f6476139a32622c57b134feb32a8877 | 8854f8f28b44f16b136a8d728c397b22ccbd3599 | /chapter_3/3.11.cpp | 339bbcd64edea0494d638477d0cc781de42cc6d8 | [] | no_license | Hannahhiendo/C-programming | 33bc1a13b05421a0daca727c1931134ea1c89b79 | a106792dc68dd19ffd10674d29631c7b82538d4b | refs/heads/master | 2021-07-09T10:48:57.538146 | 2019-02-14T03:42:04 | 2019-02-14T03:42:04 | 144,395,449 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 275 | cpp | #include <iostream>
#include <cstdlib>
using namespace std;
int main ()
{
int income = 10500;
double tax;
if ( income <= 10000)
tax = income * 0.1;
else if (income > 10000 && income <= 20000)
tax = 1000 + (income - 10000) * 0.15;
cout << tax << '\n';
return 0;
} | [
"marinahiendo@gmail.com"
] | marinahiendo@gmail.com |
e366f7f42b16bd07146cda27c3a280f0d70d704a | d508027427b9a11a6bab0722479ee8d7b7eda72b | /src/dbghlp/chart.cpp | 9d1a5ac99f58dabbba39b0dd2a31be2f3b40ccbc | [] | no_license | gaoyakun/atom3d | 421bc029ee005f501e0adb6daed778662eb73bac | 129adf3ceca175faa8acf715c05e3c8f099399fe | refs/heads/master | 2021-01-10T18:28:50.562540 | 2019-12-06T13:17:00 | 2019-12-06T13:17:00 | 56,327,530 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,764 | cpp | #include "StdAfx.h"
#include <ATOM_thread.h>
#include "stl.h"
#include "chart.h"
#if defined(_MSC_VER)
# pragma warning(disable:4786)
#endif
#define WMU_CS_CREATE (WM_APP + 1)
#define WMU_CS_DESTROY (WM_APP + 2)
#define WMU_CS_SHOW (WM_APP + 3)
#define WMU_CS_UPDATE (WM_APP + 4)
struct ChartThreadParams
{
DWORD request;
ATOM_Chart *chart;
bool isshown;
char name[256];
unsigned w;
unsigned h;
unsigned vw;
unsigned vh;
unsigned ww;
unsigned wh;
HANDLE hRequestEvent;
HANDLE hFinishEvent;
ATOM_FastMutex lock;
};
static HANDLE chartserviceEndEvent = 0;
static ATOM_VECTOR<ChartThreadParams> chartserviceParamsIn;
static ATOM_VECTOR<ChartThreadParams> chartserviceParamsProc;
static ATOM_VECTOR<ChartThreadParams> *ParamIn = &chartserviceParamsIn;
static ATOM_VECTOR<ChartThreadParams> *ParamProc = &chartserviceParamsProc;
static ATOM_FastMutex paramMutex;
unsigned __stdcall ChartService (void*)
{
for (;;)
{
for (unsigned i = 0; i < ParamProc->size(); ++i)
{
const ChartThreadParams ¶ms = (*ParamProc)[i];
switch (params.request)
{
case WMU_CS_CREATE:
params.chart->_create (
params.name,
params.w,
params.h,
params.vw,
params.vh,
params.ww,
params.wh
);
break;
case WMU_CS_DESTROY:
params.chart->_destroy ();
break;
case WMU_CS_SHOW:
params.chart->_show (params.isshown);
break;
case WMU_CS_UPDATE:
params.chart->_update ();
break;
default:
break;
}
}
ParamProc->resize(0);
{
ATOM_FastMutex::ScopeMutex l(paramMutex);
ATOM_VECTOR<ChartThreadParams> *tmp = ParamIn;
ParamIn = ParamProc;
ParamProc = tmp;
}
{
MSG msg;
while (::PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
{
::TranslateMessage (&msg);
::DispatchMessage (&msg);
}
}
if (::WaitForSingleObject (chartserviceEndEvent, 0) == WAIT_OBJECT_0)
{
break;
}
::Sleep (50);
}
return 0;
};
static HANDLE chartserviceThread = 0;
static unsigned chartserviceThreadId = 0;
void ATOM_Chart::startChartService (void)
{
chartserviceEndEvent = ::CreateEvent (0, FALSE, FALSE, 0);
chartserviceThread = (HANDLE)::_beginthreadex (0, 0, &ChartService, 0, 0, &chartserviceThreadId);
}
void ATOM_Chart::stopChartService (void)
{
if (chartserviceThread)
{
::SetEvent (chartserviceEndEvent);
::WaitForSingleObject (chartserviceThread, INFINITE);
::CloseHandle (chartserviceThread);
chartserviceThread = 0;
}
}
bool ATOM_Chart::ChartServiceRunning (void)
{
return chartserviceThread != NULL;
}
ATOM_Chart::ATOM_Chart (void)
{
if (!ChartServiceRunning())
{
startChartService ();
}
m_isshown = false;
m_hWnd = 0;
m_memDC = 0;
m_memBitmap = 0;
m_width = 0;
m_height = 0;
m_virtual_width = 0;
m_virtual_height = 0;
m_pos_x = 0;
m_pos_y = 0;
m_bkcallback = 0;
m_bkcallback_param = 0;
m_window_w = 0;
m_window_h = 0;
}
ATOM_Chart::~ATOM_Chart (void)
{
destroy ();
}
static const char *CHART_WNDCLASS = "ATOM_CHART_WCLASS";
LRESULT CALLBACK ATOM_ChartWindowProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
static void _ChartRegisterClass (void)
{
WNDCLASS wc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hbrBackground = (HBRUSH)::GetStockObject(DKGRAY_BRUSH);
wc.hCursor = (HCURSOR)::LoadCursor(NULL, IDC_ARROW);
wc.hIcon = (HICON)::LoadIcon(NULL, IDI_WINLOGO);
wc.hInstance = (HINSTANCE)::GetModuleHandle (NULL);
wc.lpfnWndProc = &ATOM_ChartWindowProc;
wc.lpszClassName = CHART_WNDCLASS;
wc.lpszMenuName = 0;
wc.style = CS_VREDRAW|CS_HREDRAW;
::RegisterClass (&wc);
}
static ATOM_MAP<HWND, ATOM_Chart*> chartWindows;
static ATOM_FastMutex chartWindowLock;
LRESULT CALLBACK ATOM_ChartWindowProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
ATOM_Chart *chart = 0;
if (msg == WM_CREATE)
{
CREATESTRUCT *cs = (CREATESTRUCT*)lParam;
chart = (ATOM_Chart*)cs->lpCreateParams;
{
ATOM_FastMutex::ScopeMutex l(chartWindowLock);
chartWindows[hWnd] = chart;
}
}
else if (msg == WM_DESTROY)
{
ATOM_FastMutex::ScopeMutex l(chartWindowLock);
ATOM_MAP<HWND, ATOM_Chart*>::iterator it = chartWindows.find (hWnd);
if (it != chartWindows.end())
{
chartWindows.erase (it);
}
}
else
{
ATOM_FastMutex::ScopeMutex l(chartWindowLock);
ATOM_MAP<HWND, ATOM_Chart*>::iterator it = chartWindows.find (hWnd);
chart = (it != chartWindows.end()) ? it->second : 0;
}
LRESULT lresult = 0;
if (!chart || !chart->processMessage (msg, wParam, lParam, &lresult))
{
lresult = ::DefWindowProc (hWnd, msg, wParam, lParam);
}
return lresult;
}
bool ATOM_Chart::create (const char *name, unsigned w, unsigned h, unsigned vw, unsigned vh, unsigned win_w, unsigned win_h)
{
if (!ChartServiceRunning ())
{
return false;
}
ChartThreadParams params;
params.request = WMU_CS_CREATE;
params.chart = this;
strcpy (params.name, name);
params.w = w;
params.h = h;
params.vw = vw;
params.vh = vh;
params.ww = win_w;
params.wh = win_h;
{
ATOM_FastMutex::ScopeMutex l(paramMutex);
ParamIn->push_back (params);
}
return true;
}
bool ATOM_Chart::_create (const char *name, unsigned w, unsigned h, unsigned vw, unsigned vh, unsigned win_w, unsigned win_h)
{
_destroy ();
_ChartRegisterClass ();
DWORD style = WS_CAPTION|WS_SYSMENU|WS_MINIMIZE;
RECT rc;
rc.left = 0;
rc.top = 0;
rc.right = win_w;
rc.bottom = win_h;
::AdjustWindowRect (&rc, style, FALSE);
win_w = rc.right - rc.left;
win_h = rc.bottom - rc.top;
m_hWnd = ::CreateWindowA (CHART_WNDCLASS, name, style, CW_USEDEFAULT, CW_USEDEFAULT, win_w, win_h, NULL, NULL, ::GetModuleHandle(NULL), this);
if (!m_hWnd)
{
return false;
}
m_window_w = win_w;
m_window_h = win_h;
HDC hDC = ::GetDC (m_hWnd);
m_memDC = ::CreateCompatibleDC (hDC);
m_memBitmap = ::CreateCompatibleBitmap (hDC, win_w, win_h);
::SelectObject (m_memDC, m_memBitmap);
::ReleaseDC (m_hWnd, hDC);
m_width = w;
m_height = h;
m_virtual_width = vw ? vw : w;
m_virtual_height = vh ? vh : h;
m_pos_x = 0;
m_pos_y = 0;
return true;
}
void ATOM_Chart::destroy (void)
{
if (!ChartServiceRunning ())
{
return;
}
if (m_hWnd )
{
ChartThreadParams params;
params.request = WMU_CS_DESTROY;
params.chart = this;
{
ATOM_FastMutex::ScopeMutex l(paramMutex);
ParamIn->push_back (params);
}
}
}
void ATOM_Chart::_destroy (void)
{
if (m_hWnd)
{
::DestroyWindow (m_hWnd);
m_hWnd = 0;
::DeleteDC (m_memDC);
m_memDC = 0;
::DeleteObject (m_memBitmap);
m_memBitmap = 0;
}
}
void ATOM_Chart::update (void)
{
if (!ChartServiceRunning ())
{
return;
}
if (m_hWnd )
{
ChartThreadParams params;
params.request = WMU_CS_UPDATE;
params.chart = this;
{
ATOM_FastMutex::ScopeMutex l(paramMutex);
ParamIn->push_back (params);
}
}
}
void ATOM_Chart::_update (void)
{
if (m_hWnd)
{
InvalidateRect (m_hWnd, NULL, FALSE);
}
}
void ATOM_Chart::show (bool show)
{
if (!ChartServiceRunning ())
{
return;
}
if (m_hWnd )
{
ChartThreadParams params;
params.request = WMU_CS_SHOW;
params.chart = this;
params.isshown = show;
{
ATOM_FastMutex::ScopeMutex l(paramMutex);
ParamIn->push_back (params);
}
m_isshown = show;
}
}
void ATOM_Chart::_show (bool show)
{
if (m_hWnd)
{
::ShowWindow (m_hWnd, show ? SW_SHOW : SW_HIDE);
::UpdateWindow (m_hWnd);
}
}
bool ATOM_Chart::isShown (void) const
{
return m_isshown;
}
bool ATOM_Chart::_isShown (void) const
{
return m_hWnd && ::IsWindowVisible (m_hWnd);
}
void ATOM_Chart::setPosition (unsigned x, unsigned y)
{
if (m_pos_x != x || m_pos_y != y)
{
m_pos_x = x;
m_pos_y = y;
update ();
}
}
void ATOM_Chart::drawBackground (HDC hdc)
{
if (m_bkcallback)
{
for (unsigned i = 0; i < m_window_w; ++i)
for (unsigned j = 0; j < m_window_h; ++j)
{
m_bkcallback (hdc, i, j, m_bkcallback_param);
}
}
else
{
drawDefaultBackground (hdc);
}
}
void ATOM_Chart::drawDefaultBackground (HDC hdc)
{
HBRUSH hbr = (HBRUSH)::GetStockObject(GRAY_BRUSH);
RECT rc;
rc.left = 0;
rc.top = 0;
rc.right = m_window_w;
rc.bottom = m_window_h;
::FillRect (hdc, &rc, hbr);
}
bool ATOM_Chart::processMessage (UINT msg, WPARAM wParam, LPARAM lParam, LRESULT *result)
{
switch (msg)
{
case WM_ERASEBKGND:
*result = 1;
return true;
case WM_PAINT:
{
PAINTSTRUCT ps;
paint (m_memDC);
::BeginPaint (m_hWnd, &ps);
::BitBlt (ps.hdc, 0, 0, m_window_w, m_window_h, m_memDC, 0, 0, SRCCOPY);
::EndPaint (m_hWnd, &ps);
*result = 0;
return true;
}
case WM_CLOSE:
_show (false);
*result = 0;
return true;
default:
break;
}
return false;
}
/////////////////////////////////////////ATOM_ChartLines///////////////////////////////////////////
ATOM_ChartLines::ATOM_ChartLines (void)
{
m_clearback = true;
}
bool ATOM_ChartLines::newPath (const char *path, int linestyle, int width, COLORREF color)
{
ATOM_HASHMAP<ATOM_STRING, PathInfo>::iterator it = m_pathes.find (path);
if (it != m_pathes.end ())
{
return false;
}
PathInfo &pi = m_pathes[path];
pi.pen = ::CreatePen (linestyle, width, color);
return true;
}
void ATOM_ChartLines::insertPoint (const char *path, unsigned x, unsigned y, bool linknext)
{
if (!isShown())
{
return;
}
ATOM_FastMutex::ScopeMutex l(m_lock);
ATOM_HASHMAP<ATOM_STRING, PathInfo>::iterator it = m_pathes.find (path);
if (it == m_pathes.end ())
{
return;
}
Point pt;
pt.pt.x = x;
pt.pt.y = y;
pt.linknext = linknext;
it->second.points.push_back (pt);
}
void ATOM_ChartLines::clearPoints (void)
{
ATOM_FastMutex::ScopeMutex l(m_lock);
for (ATOM_HASHMAP<ATOM_STRING, PathInfo>::iterator it = m_pathes.begin(); it != m_pathes.end(); ++it)
{
it->second.points.resize(0);
}
m_clearback = true;
}
void ATOM_ChartLines::clear (void)
{
ATOM_FastMutex::ScopeMutex l(m_lock);
for (ATOM_HASHMAP<ATOM_STRING, PathInfo>::iterator it = m_pathes.begin(); it != m_pathes.end(); ++it)
{
::DeleteObject (it->second.pen);
}
m_pathes.clear ();
m_clearback = true;
}
void ATOM_ChartLines::paint (HDC hdc)
{
// fill background
if (m_clearback)
{
m_clearback = false;
drawBackground (hdc);
}
// draw mark
HBRUSH hbrMark[2] = {
(HBRUSH)::GetStockObject(WHITE_BRUSH),
(HBRUSH)::GetStockObject(DKGRAY_BRUSH)
};
static int mark = 0;
RECT rc;
rc.left = 0;
rc.top = 0;
rc.right = 10;
rc.bottom = 10;
::FillRect (hdc, &rc, hbrMark[mark++%2]);
// draw lines
{
ATOM_FastMutex::ScopeMutex l(m_lock);
for (ATOM_HASHMAP<ATOM_STRING, PathInfo>::iterator it = m_pathes.begin(); it != m_pathes.end(); ++it)
{
PathInfo &pi = it->second;
if (pi.points.size() > 1)
{
HGDIOBJ oldPen = ::SelectObject (hdc, (HGDIOBJ)pi.pen);
for (unsigned i = 0; i < pi.points.size()-1; ++i)
{
if (pi.points[i].linknext)
{
::MoveToEx (hdc, pi.points[i].pt.x, pi.points[i].pt.y, 0);
::LineTo (hdc, pi.points[i+1].pt.x, pi.points[i+1].pt.y);
}
else
{
continue;
}
}
::SelectObject (hdc, oldPen);
Point pt = pi.points.back();
pi.points.resize(0);
pi.points.push_back (pt);
}
}
}
}
| [
"80844871@qq.com"
] | 80844871@qq.com |
8634c08b685081d89aaf09b80e9f1a5a1402cfb5 | 07eb399da1ce4374deedb339117299d321305b55 | /freespace2/include/multi_pause.h | ee3b46dd5e2df826afc04791ac1d1916e729e4b6 | [] | no_license | lubomyr/freespace2 | 222474acb364f4f2e5ad36ecad0450244196220d | a959fcf403400f5c5d933fba66a41d8e96b02811 | refs/heads/master | 2021-01-15T08:58:58.113252 | 2016-11-06T14:53:59 | 2016-11-06T14:53:59 | 52,396,527 | 11 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,556 | h | /*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on
* the source.
*/
/*
* $Logfile: /Freespace2/code/Network/multi_pause.h $
* $Revision: 110 $
* $Date: 2002-06-09 07:41:30 +0300 (нд, 09 чер 2002) $
* $Author: relnev $
*
* $Log$
* Revision 1.2 2002/06/09 04:41:14 relnev
* added copyright header
*
* Revision 1.1.1.1 2002/05/03 03:28:12 root
* Initial import.
*
*
* 3 10/13/98 9:29a Dave
* Started neatening up freespace.h. Many variables renamed and
* reorganized. Added AlphaColors.[h,cpp]
*
* 2 10/07/98 10:53a Dave
* Initial checkin.
*
* 1 10/07/98 10:50a Dave
*
* 2 5/07/98 6:26p Dave
* Fix strange boundary conditions which arise when players die/respawn
* while the game is being ended. Spiff up the chatbox doskey thing a bit.
*
* 1 4/14/98 12:18p Dave
*
*
* $NoKeywords: $
*/
#ifndef _MULTI_PAUSE_HEADER_FILE
#define _MULTI_PAUSE_HEADER_FILE
// ----------------------------------------------------------------------------------
// PAUSE DEFINES/VARS
//
class UI_WINDOW;
struct net_player;
// state of the game (paused or not) on _my_ machine. Obviously this is important for the server
// call multi_pause_reset() to reinitialize
extern int Multi_pause_status;
// who paused the game
extern net_player *Multi_pause_pauser;
// ----------------------------------------------------------------------------------
// PAUSE FUNCTIONS
//
// re-initializes the pause system. call before entering the mission to reset
void multi_pause_reset();
// send a request to pause or unpause a game (all players should use this function)
void multi_pause_request(int pause);
// (client) call when receiving a packet indicating we should pause
void multi_pause_pause();
// (client) call when receiving a packet indicating we should unpause
void multi_pause_unpause();
// (server) evaluate a pause request from the given player (should call for himself as well)
void multi_pause_server_eval_request(net_player *pl, int pause);
// if we still want to eat keys
int multi_pause_eat_keys();
// ----------------------------------------------------------------------------------
// PAUSE UI FUNCTIONS
//
// initialize multi pause screen
void multi_pause_init(UI_WINDOW *Ui_window);
// do frame for the multi pause screen
void multi_pause_do();
// close the multi pause screen
void multi_pause_close();
#endif
| [
"lubomyr31@gmail.com"
] | lubomyr31@gmail.com |
9ebdad0ecb0eb9aabdb8894534caf73b2b33f6d2 | b8c4c902e8ac17a59719efedb87efb79c56394db | /oop/VirtualFunctions/CoutOperator.cpp | 06e2235f5a6803b66230af9c04fdf0ed0da06360 | [] | no_license | dibolsoni/LearningCpp | ab61a87d9c45b190f65e7aff8616ca9bee6565b9 | d485a7d06183f0df9d188c4326105ff76c89ce76 | refs/heads/master | 2023-08-20T08:34:11.917654 | 2021-10-13T18:45:38 | 2021-10-13T18:45:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 969 | cpp | #include <iostream>
class Base
{
public:
Base() {}
// Here's our overloaded operator<<
friend std::ostream& operator<<(std::ostream &out, const Base &b)
{
// Delegate printing responsibility for printing to member function print()
return b.print(out);
}
// We'll rely on member function print() to do the actual printing
// Because print is a normal member function, it can be virtualized
virtual std::ostream& print(std::ostream& out) const
{
out << "Base";
return out;
}
};
class Derived : public Base
{
public:
Derived() {}
// Here's our override print function to handle the Derived case
virtual std::ostream& print(std::ostream& out) const override
{
out << "Derived";
return out;
}
};
int main()
{
Base b;
std::cout << b << '\n';
Derived d;
std::cout << d << '\n'; // note that this works even with no operator<< that explicitly handles Derived objects
Base &bref = d;
std::cout << bref << '\n';
return 0;
} | [
"dibolsoni@gmail.com"
] | dibolsoni@gmail.com |
e6b9db3b3e728d14803a2acfc24e0cb2b5aee303 | b227d23f889f5dc04b7eef4bc3eb514732ccef55 | /PTA/PAT_A/Cpp11/A1015_AC.cc | f75a5d2e720596508a2f1b8d46198c2cdde3a241 | [
"MIT"
] | permissive | StrayDragon/OJ-Solutions | e5dd953781237197b98fa83711a818cd705c3fdc | b31b11c01507544aded2302923da080b39cf2ba8 | refs/heads/master | 2020-04-26T17:17:04.605568 | 2019-12-24T08:03:18 | 2019-12-24T08:03:18 | 173,708,012 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 915 | cc | // ---
// id : 1015
// title : Reversible Primes
// difficulty : Easy
// score : 20
// tag : TODO
// keyword : TODO
// status : AC
// from : PAT (Advanced Level) Practice
// ---
#include <cmath>
#include <iostream>
bool is_prime(int n) {
if (n <= 1)
return false;
int bound = (int)std::sqrt(1.0 * n);
for (int i = 2; i <= bound; ++i)
if (n % i == 0)
return false;
return true;
}
int digits[110];
int reverse_redix_convert(int n, int d) {
int len = 0;
do {
digits[len++] = n % d;
n /= d;
} while (n != 0);
for (int i = 0; i < len; i++) {
n = n * d + digits[i];
}
return n;
}
using namespace std;
int main() {
int n, d;
while (true) {
cin >> n;
if (n < 0)
break;
cin >> d;
if (is_prime(n) && is_prime(reverse_redix_convert(n, d)))
cout << "Yes\n";
else
cout << "No\n";
}
return 0;
} | [
"straydragonl@foxmail.com"
] | straydragonl@foxmail.com |
5addeb853ffd246d1a5811a7cc41bc6fdb3a3722 | ab9b1af430728a52a8fd91279f9a9093a2701604 | /sword_to_offer_010_ex/sword_to_offer_010_ex/sword_to_offer_010_ex.cpp | 707e31ab6b829606b69176c96f770ba4d908cda6 | [] | no_license | wuyong66/sword_to_offer | 3a59677b9965a08db8aa516c0ccc48070347c264 | db436d2772cc4873ab696162b495113f1d1cec48 | refs/heads/master | 2020-03-19T10:47:30.232106 | 2018-07-25T14:47:56 | 2018-07-25T14:47:56 | 136,401,309 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 764 | cpp | #include <iostream>
#include <string>
#include <vector>
using namespace std;
bool IsPowOf2(int num);
int MChangeToN(int m, int n);
int main()
{
cout << IsPowOf2(8) << endl;
cout << MChangeToN(8, 4) << endl;
system("pause");
return 0;
}
//判定某个数是否是2的指数得到的
bool IsPowOf2(int num)
{
unsigned int flag = 1;
unsigned int count = 0;
while (flag)
{
if (num & flag)
++count;
flag = flag << 1;
}
if (count == 1)
return true;
else
return false;
}
//得出用以表示M的二进制通过变换多少位可以变换为表示N二进制数
int MChangeToN(int m, int n)
{
int num = m ^ n;
unsigned int flag = 1;
unsigned int count = 0;
while (flag)
{
if (num & flag)
++count;
flag = flag << 1;
}
return count;
} | [
"1062073083@qq.com"
] | 1062073083@qq.com |
5e02ee8bee47050190672a5ec52f15926e9d067b | 0f171cb8ebcae3acf824fae38608df156cd512a2 | /src/rpc/core_rpc_server.cpp | 80bc210f6e8dfb70600b0dcb52c62392e1db8713 | [
"BSD-3-Clause"
] | permissive | projekgallus/galluscoin | 55c136574a3a0aec6b0c2a9599ed602644fd8bef | 84c33ab8cf2d187d514957110060114bc66cb944 | refs/heads/master | 2020-03-07T05:06:22.648000 | 2018-07-09T22:10:40 | 2018-07-09T22:10:40 | 127,286,033 | 5 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 57,438 | cpp | // Copyright (c) 2014-2017, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. 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.
//
// 3. Neither the name of the copyright holder 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 HOLDER 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.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
#include <boost/foreach.hpp>
#include "include_base_utils.h"
using namespace epee;
#include "core_rpc_server.h"
#include "common/command_line.h"
#include "cryptonote_core/cryptonote_format_utils.h"
#include "cryptonote_core/account.h"
#include "cryptonote_core/cryptonote_basic_impl.h"
#include "misc_language.h"
#include "crypto/hash.h"
#include "core_rpc_server_error_codes.h"
#define MAX_RESTRICTED_FAKE_OUTS_COUNT 40
#define MAX_RESTRICTED_GLOBAL_FAKE_OUTS_COUNT 500
namespace cryptonote
{
//-----------------------------------------------------------------------------------
void core_rpc_server::init_options(boost::program_options::options_description& desc)
{
command_line::add_arg(desc, arg_rpc_bind_ip);
command_line::add_arg(desc, arg_rpc_bind_port);
command_line::add_arg(desc, arg_testnet_rpc_bind_port);
command_line::add_arg(desc, arg_restricted_rpc);
command_line::add_arg(desc, arg_user_agent);
}
//------------------------------------------------------------------------------------------------------------------------------
core_rpc_server::core_rpc_server(
core& cr
, nodetool::node_server<cryptonote::t_cryptonote_protocol_handler<cryptonote::core> >& p2p
)
: m_core(cr)
, m_p2p(p2p)
{}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::handle_command_line(
const boost::program_options::variables_map& vm
)
{
auto p2p_bind_arg = m_testnet ? arg_testnet_rpc_bind_port : arg_rpc_bind_port;
m_bind_ip = command_line::get_arg(vm, arg_rpc_bind_ip);
m_port = command_line::get_arg(vm, p2p_bind_arg);
m_restricted = command_line::get_arg(vm, arg_restricted_rpc);
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::init(
const boost::program_options::variables_map& vm
)
{
m_testnet = command_line::get_arg(vm, command_line::arg_testnet_on);
std::string m_user_agent = command_line::get_arg(vm, command_line::arg_user_agent);
m_net_server.set_threads_prefix("RPC");
bool r = handle_command_line(vm);
CHECK_AND_ASSERT_MES(r, false, "Failed to process command line in core_rpc_server");
return epee::http_server_impl_base<core_rpc_server, connection_context>::init(m_port, m_bind_ip, m_user_agent);
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::check_core_busy()
{
if(m_p2p.get_payload_object().get_core().get_blockchain_storage().is_storing_blockchain())
{
return false;
}
return true;
}
#define CHECK_CORE_BUSY() do { if(!check_core_busy()){res.status = CORE_RPC_STATUS_BUSY;return true;} } while(0)
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::check_core_ready()
{
if(!m_p2p.get_payload_object().is_synchronized())
{
return false;
}
return check_core_busy();
}
#define CHECK_CORE_READY() do { if(!check_core_ready()){res.status = CORE_RPC_STATUS_BUSY;return true;} } while(0)
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_height(const COMMAND_RPC_GET_HEIGHT::request& req, COMMAND_RPC_GET_HEIGHT::response& res)
{
CHECK_CORE_BUSY();
res.height = m_core.get_current_blockchain_height();
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_info(const COMMAND_RPC_GET_INFO::request& req, COMMAND_RPC_GET_INFO::response& res)
{
CHECK_CORE_BUSY();
crypto::hash top_hash;
if (!m_core.get_blockchain_top(res.height, top_hash))
{
res.status = "Failed";
return false;
}
++res.height; // turn top block height into blockchain height
res.top_block_hash = string_tools::pod_to_hex(top_hash);
res.target_height = m_core.get_target_blockchain_height();
res.difficulty = m_core.get_blockchain_storage().get_difficulty_for_next_block();
res.target = DIFFICULTY_TARGET;
res.tx_count = m_core.get_blockchain_storage().get_total_transactions() - res.height; //without coinbase
res.tx_pool_size = m_core.get_pool_transactions_count();
res.alt_blocks_count = m_core.get_blockchain_storage().get_alternative_blocks_count();
uint64_t total_conn = m_p2p.get_connections_count();
res.outgoing_connections_count = m_p2p.get_outgoing_connections_count();
res.incoming_connections_count = total_conn - res.outgoing_connections_count;
res.white_peerlist_size = m_p2p.get_peerlist_manager().get_white_peers_count();
res.grey_peerlist_size = m_p2p.get_peerlist_manager().get_gray_peers_count();
res.testnet = m_testnet;
res.cumulative_difficulty = m_core.get_blockchain_storage().get_db().get_block_cumulative_difficulty(res.height - 1);
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_blocks(const COMMAND_RPC_GET_BLOCKS_FAST::request& req, COMMAND_RPC_GET_BLOCKS_FAST::response& res)
{
CHECK_CORE_BUSY();
std::list<std::pair<block, std::list<transaction> > > bs;
if(!m_core.find_blockchain_supplement(req.start_height, req.block_ids, bs, res.current_height, res.start_height, COMMAND_RPC_GET_BLOCKS_FAST_MAX_COUNT))
{
res.status = "Failed";
return false;
}
BOOST_FOREACH(auto& b, bs)
{
res.blocks.resize(res.blocks.size()+1);
res.blocks.back().block = block_to_blob(b.first);
res.output_indices.push_back(COMMAND_RPC_GET_BLOCKS_FAST::block_output_indices());
res.output_indices.back().indices.push_back(COMMAND_RPC_GET_BLOCKS_FAST::tx_output_indices());
bool r = m_core.get_tx_outputs_gindexs(get_transaction_hash(b.first.miner_tx), res.output_indices.back().indices.back().indices);
if (!r)
{
res.status = "Failed";
return false;
}
size_t txidx = 0;
BOOST_FOREACH(auto& t, b.second)
{
res.blocks.back().txs.push_back(tx_to_blob(t));
res.output_indices.back().indices.push_back(COMMAND_RPC_GET_BLOCKS_FAST::tx_output_indices());
bool r = m_core.get_tx_outputs_gindexs(b.first.tx_hashes[txidx++], res.output_indices.back().indices.back().indices);
if (!r)
{
res.status = "Failed";
return false;
}
}
}
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_hashes(const COMMAND_RPC_GET_HASHES_FAST::request& req, COMMAND_RPC_GET_HASHES_FAST::response& res)
{
CHECK_CORE_BUSY();
NOTIFY_RESPONSE_CHAIN_ENTRY::request resp;
resp.start_height = req.start_height;
if(!m_core.find_blockchain_supplement(req.block_ids, resp))
{
res.status = "Failed";
return false;
}
res.current_height = resp.total_height;
res.start_height = resp.start_height;
res.m_block_ids = std::move(resp.m_block_ids);
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_random_outs(const COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::request& req, COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::response& res)
{
CHECK_CORE_BUSY();
res.status = "Failed";
if (m_restricted)
{
if (req.amounts.size() > 100 || req.outs_count > MAX_RESTRICTED_FAKE_OUTS_COUNT)
{
res.status = "Too many outs requested";
return true;
}
}
if(!m_core.get_random_outs_for_amounts(req, res))
{
return true;
}
res.status = CORE_RPC_STATUS_OK;
std::stringstream ss;
typedef COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount outs_for_amount;
typedef COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::out_entry out_entry;
std::for_each(res.outs.begin(), res.outs.end(), [&](outs_for_amount& ofa)
{
ss << "[" << ofa.amount << "]:";
CHECK_AND_ASSERT_MES(ofa.outs.size(), ;, "internal error: ofa.outs.size() is empty for amount " << ofa.amount);
std::for_each(ofa.outs.begin(), ofa.outs.end(), [&](out_entry& oe)
{
ss << oe.global_amount_index << " ";
});
ss << ENDL;
});
std::string s = ss.str();
LOG_PRINT_L2("COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS: " << ENDL << s);
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_outs_bin(const COMMAND_RPC_GET_OUTPUTS_BIN::request& req, COMMAND_RPC_GET_OUTPUTS_BIN::response& res)
{
CHECK_CORE_BUSY();
res.status = "Failed";
if (m_restricted)
{
if (req.outputs.size() > MAX_RESTRICTED_GLOBAL_FAKE_OUTS_COUNT)
{
res.status = "Too many outs requested";
return true;
}
}
if(!m_core.get_outs(req, res))
{
return true;
}
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_outs(const COMMAND_RPC_GET_OUTPUTS::request& req, COMMAND_RPC_GET_OUTPUTS::response& res)
{
CHECK_CORE_BUSY();
res.status = "Failed";
if (m_restricted)
{
if (req.outputs.size() > MAX_RESTRICTED_GLOBAL_FAKE_OUTS_COUNT)
{
res.status = "Too many outs requested";
return true;
}
}
cryptonote::COMMAND_RPC_GET_OUTPUTS_BIN::request req_bin;
req_bin.outputs = req.outputs;
cryptonote::COMMAND_RPC_GET_OUTPUTS_BIN::response res_bin;
if(!m_core.get_outs(req_bin, res_bin))
{
return true;
}
// convert to text
for (const auto &i: res_bin.outs)
{
res.outs.push_back(cryptonote::COMMAND_RPC_GET_OUTPUTS::outkey());
cryptonote::COMMAND_RPC_GET_OUTPUTS::outkey &outkey = res.outs.back();
outkey.key = epee::string_tools::pod_to_hex(i.key);
outkey.mask = epee::string_tools::pod_to_hex(i.mask);
outkey.unlocked = i.unlocked;
}
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_random_rct_outs(const COMMAND_RPC_GET_RANDOM_RCT_OUTPUTS::request& req, COMMAND_RPC_GET_RANDOM_RCT_OUTPUTS::response& res)
{
CHECK_CORE_BUSY();
res.status = "Failed";
if(!m_core.get_random_rct_outs(req, res))
{
return true;
}
res.status = CORE_RPC_STATUS_OK;
std::stringstream ss;
typedef COMMAND_RPC_GET_RANDOM_RCT_OUTPUTS::out_entry out_entry;
CHECK_AND_ASSERT_MES(res.outs.size(), true, "internal error: res.outs.size() is empty");
std::for_each(res.outs.begin(), res.outs.end(), [&](out_entry& oe)
{
ss << oe.global_amount_index << " ";
});
ss << ENDL;
std::string s = ss.str();
LOG_PRINT_L2("COMMAND_RPC_GET_RANDOM_RCT_OUTPUTS: " << ENDL << s);
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_indexes(const COMMAND_RPC_GET_TX_GLOBAL_OUTPUTS_INDEXES::request& req, COMMAND_RPC_GET_TX_GLOBAL_OUTPUTS_INDEXES::response& res)
{
CHECK_CORE_BUSY();
bool r = m_core.get_tx_outputs_gindexs(req.txid, res.o_indexes);
if(!r)
{
res.status = "Failed";
return true;
}
res.status = CORE_RPC_STATUS_OK;
LOG_PRINT_L2("COMMAND_RPC_GET_TX_GLOBAL_OUTPUTS_INDEXES: [" << res.o_indexes.size() << "]");
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_transactions(const COMMAND_RPC_GET_TRANSACTIONS::request& req, COMMAND_RPC_GET_TRANSACTIONS::response& res)
{
CHECK_CORE_BUSY();
std::vector<crypto::hash> vh;
BOOST_FOREACH(const auto& tx_hex_str, req.txs_hashes)
{
blobdata b;
if(!string_tools::parse_hexstr_to_binbuff(tx_hex_str, b))
{
res.status = "Failed to parse hex representation of transaction hash";
return true;
}
if(b.size() != sizeof(crypto::hash))
{
res.status = "Failed, size of data mismatch";
return true;
}
vh.push_back(*reinterpret_cast<const crypto::hash*>(b.data()));
}
std::list<crypto::hash> missed_txs;
std::list<transaction> txs;
bool r = m_core.get_transactions(vh, txs, missed_txs);
if(!r)
{
res.status = "Failed";
return true;
}
LOG_PRINT_L2("Found " << txs.size() << "/" << vh.size() << " transactions on the blockchain");
// try the pool for any missing txes
size_t found_in_pool = 0;
std::unordered_set<crypto::hash> pool_tx_hashes;
if (!missed_txs.empty())
{
std::list<transaction> pool_txs;
bool r = m_core.get_pool_transactions(pool_txs);
if(r)
{
for (std::list<transaction>::const_iterator i = pool_txs.begin(); i != pool_txs.end(); ++i)
{
crypto::hash tx_hash = get_transaction_hash(*i);
std::list<crypto::hash>::iterator mi = std::find(missed_txs.begin(), missed_txs.end(), tx_hash);
if (mi != missed_txs.end())
{
pool_tx_hashes.insert(tx_hash);
missed_txs.erase(mi);
txs.push_back(*i);
++found_in_pool;
}
}
}
LOG_PRINT_L2("Found " << found_in_pool << "/" << vh.size() << " transactions in the pool");
}
std::list<std::string>::const_iterator txhi = req.txs_hashes.begin();
std::vector<crypto::hash>::const_iterator vhi = vh.begin();
BOOST_FOREACH(auto& tx, txs)
{
res.txs.push_back(COMMAND_RPC_GET_TRANSACTIONS::entry());
COMMAND_RPC_GET_TRANSACTIONS::entry &e = res.txs.back();
crypto::hash tx_hash = *vhi++;
e.tx_hash = *txhi++;
blobdata blob = t_serializable_object_to_blob(tx);
e.as_hex = string_tools::buff_to_hex_nodelimer(blob);
if (req.decode_as_json)
e.as_json = obj_to_json_str(tx);
e.in_pool = pool_tx_hashes.find(tx_hash) != pool_tx_hashes.end();
if (e.in_pool)
{
e.block_height = std::numeric_limits<uint64_t>::max();
}
else
{
e.block_height = m_core.get_blockchain_storage().get_db().get_tx_block_height(tx_hash);
}
// fill up old style responses too, in case an old wallet asks
res.txs_as_hex.push_back(e.as_hex);
if (req.decode_as_json)
res.txs_as_json.push_back(e.as_json);
// output indices too if not in pool
if (pool_tx_hashes.find(tx_hash) == pool_tx_hashes.end())
{
bool r = m_core.get_tx_outputs_gindexs(tx_hash, e.output_indices);
if (!r)
{
res.status = "Failed";
return false;
}
}
}
BOOST_FOREACH(const auto& miss_tx, missed_txs)
{
res.missed_tx.push_back(string_tools::pod_to_hex(miss_tx));
}
LOG_PRINT_L2(res.txs.size() << " transactions found, " << res.missed_tx.size() << " not found");
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_is_key_image_spent(const COMMAND_RPC_IS_KEY_IMAGE_SPENT::request& req, COMMAND_RPC_IS_KEY_IMAGE_SPENT::response& res)
{
CHECK_CORE_BUSY();
std::vector<crypto::key_image> key_images;
BOOST_FOREACH(const auto& ki_hex_str, req.key_images)
{
blobdata b;
if(!string_tools::parse_hexstr_to_binbuff(ki_hex_str, b))
{
res.status = "Failed to parse hex representation of key image";
return true;
}
if(b.size() != sizeof(crypto::key_image))
{
res.status = "Failed, size of data mismatch";
}
key_images.push_back(*reinterpret_cast<const crypto::key_image*>(b.data()));
}
std::vector<bool> spent_status;
bool r = m_core.are_key_images_spent(key_images, spent_status);
if(!r)
{
res.status = "Failed";
return true;
}
res.spent_status.clear();
for (size_t n = 0; n < spent_status.size(); ++n)
res.spent_status.push_back(spent_status[n] ? COMMAND_RPC_IS_KEY_IMAGE_SPENT::SPENT_IN_BLOCKCHAIN : COMMAND_RPC_IS_KEY_IMAGE_SPENT::UNSPENT);
// check the pool too
std::vector<cryptonote::tx_info> txs;
std::vector<cryptonote::spent_key_image_info> ki;
r = m_core.get_pool_transactions_and_spent_keys_info(txs, ki);
if(!r)
{
res.status = "Failed";
return true;
}
for (std::vector<cryptonote::spent_key_image_info>::const_iterator i = ki.begin(); i != ki.end(); ++i)
{
crypto::hash hash;
crypto::key_image spent_key_image;
if (parse_hash256(i->id_hash, hash))
{
memcpy(&spent_key_image, &hash, sizeof(hash)); // a bit dodgy, should be other parse functions somewhere
for (size_t n = 0; n < res.spent_status.size(); ++n)
{
if (res.spent_status[n] == COMMAND_RPC_IS_KEY_IMAGE_SPENT::UNSPENT)
{
if (key_images[n] == spent_key_image)
{
res.spent_status[n] = COMMAND_RPC_IS_KEY_IMAGE_SPENT::SPENT_IN_POOL;
break;
}
}
}
}
}
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_send_raw_tx(const COMMAND_RPC_SEND_RAW_TX::request& req, COMMAND_RPC_SEND_RAW_TX::response& res)
{
CHECK_CORE_READY();
std::string tx_blob;
if(!string_tools::parse_hexstr_to_binbuff(req.tx_as_hex, tx_blob))
{
LOG_PRINT_L0("[on_send_raw_tx]: Failed to parse tx from hexbuff: " << req.tx_as_hex);
res.status = "Failed";
return true;
}
cryptonote_connection_context fake_context = AUTO_VAL_INIT(fake_context);
tx_verification_context tvc = AUTO_VAL_INIT(tvc);
if(!m_core.handle_incoming_tx(tx_blob, tvc, false, false) || tvc.m_verifivation_failed)
{
if (tvc.m_verifivation_failed)
{
LOG_PRINT_L0("[on_send_raw_tx]: tx verification failed");
}
else
{
LOG_PRINT_L0("[on_send_raw_tx]: Failed to process tx");
}
res.status = "Failed";
if ((res.low_mixin = tvc.m_low_mixin))
res.reason = "mixin too low";
if ((res.high_mixin = tvc.m_high_mixin))
res.reason = "mixin too high";
if ((res.double_spend = tvc.m_double_spend))
res.reason = "double spend";
if ((res.invalid_input = tvc.m_invalid_input))
res.reason = "invalid input";
if ((res.invalid_output = tvc.m_invalid_output))
res.reason = "invalid output";
if ((res.too_big = tvc.m_too_big))
res.reason = "too big";
if ((res.overspend = tvc.m_overspend))
res.reason = "overspend";
if ((res.fee_too_low = tvc.m_fee_too_low))
res.reason = "fee too low";
if ((res.not_rct = tvc.m_not_rct))
res.reason = "tx is not ringct";
if ((res.invalid_tx_version = tvc.m_invalid_tx_version))
res.reason = "invalid tx version";
return true;
}
if(!tvc.m_should_be_relayed || req.do_not_relay)
{
LOG_PRINT_L0("[on_send_raw_tx]: tx accepted, but not relayed");
res.reason = "Not relayed";
res.not_relayed = true;
res.status = CORE_RPC_STATUS_OK;
return true;
}
NOTIFY_NEW_TRANSACTIONS::request r;
r.txs.push_back(tx_blob);
m_core.get_protocol()->relay_transactions(r, fake_context);
//TODO: make sure that tx has reached other nodes here, probably wait to receive reflections from other nodes
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_start_mining(const COMMAND_RPC_START_MINING::request& req, COMMAND_RPC_START_MINING::response& res)
{
CHECK_CORE_READY();
cryptonote::address_parse_info info;
if (!get_account_address_from_str(info, m_testnet, req.miner_address))
{
res.status = "Failed, wrong address";
LOG_PRINT_L0(res.status);
return true;
}
if (info.is_subaddress)
{
res.status = "Mining to subaddress isn't supported yet";
LOG_PRINT_L0(res.status);
return true;
}
boost::thread::attributes attrs;
attrs.set_stack_size(THREAD_STACK_SIZE);
if (!m_core.get_miner().start(info.address, static_cast<size_t>(req.threads_count), attrs))
{
res.status = "Failed, mining not started";
LOG_PRINT_L0(res.status);
return true;
}
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_stop_mining(const COMMAND_RPC_STOP_MINING::request& req, COMMAND_RPC_STOP_MINING::response& res)
{
if(!m_core.get_miner().stop())
{
res.status = "Failed, mining not stopped";
LOG_PRINT_L0(res.status);
return true;
}
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_mining_status(const COMMAND_RPC_MINING_STATUS::request& req, COMMAND_RPC_MINING_STATUS::response& res)
{
CHECK_CORE_READY();
const miner& lMiner = m_core.get_miner();
res.active = lMiner.is_mining();
if ( lMiner.is_mining() ) {
res.speed = lMiner.get_speed();
res.threads_count = lMiner.get_threads_count();
const account_public_address& lMiningAdr = lMiner.get_mining_address();
res.address = get_account_address_as_str(m_testnet, false, lMiningAdr);
}
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_save_bc(const COMMAND_RPC_SAVE_BC::request& req, COMMAND_RPC_SAVE_BC::response& res)
{
CHECK_CORE_BUSY();
if( !m_core.get_blockchain_storage().store_blockchain() )
{
res.status = "Error while storing blockhain";
return true;
}
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_peer_list(const COMMAND_RPC_GET_PEER_LIST::request& req, COMMAND_RPC_GET_PEER_LIST::response& res)
{
std::list<nodetool::peerlist_entry> white_list;
std::list<nodetool::peerlist_entry> gray_list;
m_p2p.get_peerlist_manager().get_peerlist_full(gray_list, white_list);
for (auto & entry : white_list)
{
res.white_list.emplace_back(entry.id, entry.adr.ip, entry.adr.port, entry.last_seen);
}
for (auto & entry : gray_list)
{
res.gray_list.emplace_back(entry.id, entry.adr.ip, entry.adr.port, entry.last_seen);
}
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_set_log_hash_rate(const COMMAND_RPC_SET_LOG_HASH_RATE::request& req, COMMAND_RPC_SET_LOG_HASH_RATE::response& res)
{
if(m_core.get_miner().is_mining())
{
m_core.get_miner().do_print_hashrate(req.visible);
res.status = CORE_RPC_STATUS_OK;
}
else
{
res.status = CORE_RPC_STATUS_NOT_MINING;
}
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_set_log_level(const COMMAND_RPC_SET_LOG_LEVEL::request& req, COMMAND_RPC_SET_LOG_LEVEL::response& res)
{
if (req.level < LOG_LEVEL_MIN || req.level > LOG_LEVEL_MAX)
{
res.status = "Error: log level not valid";
}
else
{
epee::log_space::log_singletone::get_set_log_detalisation_level(true, req.level);
int otshell_utils_log_level = 100 - (req.level * 20);
gCurrentLogger.setDebugLevel(otshell_utils_log_level);
res.status = CORE_RPC_STATUS_OK;
}
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_transaction_pool(const COMMAND_RPC_GET_TRANSACTION_POOL::request& req, COMMAND_RPC_GET_TRANSACTION_POOL::response& res)
{
CHECK_CORE_BUSY();
m_core.get_pool_transactions_and_spent_keys_info(res.transactions, res.spent_key_images);
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_stop_daemon(const COMMAND_RPC_STOP_DAEMON::request& req, COMMAND_RPC_STOP_DAEMON::response& res)
{
// FIXME: replace back to original m_p2p.send_stop_signal() after
// investigating why that isn't working quite right.
m_p2p.send_stop_signal();
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_getblockcount(const COMMAND_RPC_GETBLOCKCOUNT::request& req, COMMAND_RPC_GETBLOCKCOUNT::response& res)
{
CHECK_CORE_BUSY();
res.count = m_core.get_current_blockchain_height();
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_getblockhash(const COMMAND_RPC_GETBLOCKHASH::request& req, COMMAND_RPC_GETBLOCKHASH::response& res, epee::json_rpc::error& error_resp)
{
if(!check_core_busy())
{
error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY;
error_resp.message = "Core is busy";
return false;
}
if(req.size() != 1)
{
error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM;
error_resp.message = "Wrong parameters, expected height";
return false;
}
uint64_t h = req[0];
if(m_core.get_current_blockchain_height() <= h)
{
error_resp.code = CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT;
error_resp.message = std::string("Too big height: ") + std::to_string(h) + ", current blockchain height = " + std::to_string(m_core.get_current_blockchain_height());
}
res = string_tools::pod_to_hex(m_core.get_block_id_by_height(h));
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
// equivalent of strstr, but with arbitrary bytes (ie, NULs)
// This does not differentiate between "not found" and "found at offset 0"
uint64_t slow_memmem(const void* start_buff, size_t buflen,const void* pat,size_t patlen)
{
const void* buf = start_buff;
const void* end=(const char*)buf+buflen;
if (patlen > buflen || patlen == 0) return 0;
while(buflen>0 && (buf=memchr(buf,((const char*)pat)[0],buflen-patlen+1)))
{
if(memcmp(buf,pat,patlen)==0)
return (const char*)buf - (const char*)start_buff;
buf=(const char*)buf+1;
buflen = (const char*)end - (const char*)buf;
}
return 0;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_getblocktemplate(const COMMAND_RPC_GETBLOCKTEMPLATE::request& req, COMMAND_RPC_GETBLOCKTEMPLATE::response& res, epee::json_rpc::error& error_resp)
{
if(!check_core_ready())
{
error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY;
error_resp.message = "Core is busy";
return false;
}
if(req.reserve_size > 255)
{
error_resp.code = CORE_RPC_ERROR_CODE_TOO_BIG_RESERVE_SIZE;
error_resp.message = "To big reserved size, maximum 255";
return false;
}
cryptonote::address_parse_info info;
if (!req.wallet_address.size() || !cryptonote::get_account_address_from_str(info, m_testnet, req.wallet_address))
{
error_resp.code = CORE_RPC_ERROR_CODE_WRONG_WALLET_ADDRESS;
error_resp.message = "Failed to parse wallet address";
return false;
}
if (info.is_subaddress)
{
error_resp.code = CORE_RPC_ERROR_CODE_MINING_TO_SUBADDRESS;
error_resp.message = "Mining to subaddress is not supported yet";
return false;
}
block b = AUTO_VAL_INIT(b);
cryptonote::blobdata blob_reserve;
blob_reserve.resize(req.reserve_size, 0);
if(!m_core.get_block_template(b, info.address, res.difficulty, res.height, blob_reserve))
{
error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
error_resp.message = "Internal error: failed to create block template";
LOG_ERROR("Failed to create block template");
return false;
}
blobdata block_blob = t_serializable_object_to_blob(b);
crypto::public_key tx_pub_key = cryptonote::get_tx_pub_key_from_extra(b.miner_tx);
if(tx_pub_key == null_pkey)
{
error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
error_resp.message = "Internal error: failed to create block template";
LOG_ERROR("Failed to tx pub key in coinbase extra");
return false;
}
res.reserved_offset = slow_memmem((void*)block_blob.data(), block_blob.size(), &tx_pub_key, sizeof(tx_pub_key));
if(!res.reserved_offset)
{
error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
error_resp.message = "Internal error: failed to create block template";
LOG_ERROR("Failed to find tx pub key in blockblob");
return false;
}
res.reserved_offset += sizeof(tx_pub_key) + 3; //3 bytes: tag for TX_EXTRA_TAG_PUBKEY(1 byte), tag for TX_EXTRA_NONCE(1 byte), counter in TX_EXTRA_NONCE(1 byte)
if(res.reserved_offset + req.reserve_size > block_blob.size())
{
error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
error_resp.message = "Internal error: failed to create block template";
LOG_ERROR("Failed to calculate offset for ");
return false;
}
blobdata hashing_blob = get_block_hashing_blob(b);
res.prev_hash = string_tools::pod_to_hex(b.prev_id);
res.blocktemplate_blob = string_tools::buff_to_hex_nodelimer(block_blob);
res.blockhashing_blob = string_tools::buff_to_hex_nodelimer(hashing_blob);
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_submitblock(const COMMAND_RPC_SUBMITBLOCK::request& req, COMMAND_RPC_SUBMITBLOCK::response& res, epee::json_rpc::error& error_resp)
{
CHECK_CORE_READY();
if(req.size()!=1)
{
error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM;
error_resp.message = "Wrong param";
return false;
}
blobdata blockblob;
if(!string_tools::parse_hexstr_to_binbuff(req[0], blockblob))
{
error_resp.code = CORE_RPC_ERROR_CODE_WRONG_BLOCKBLOB;
error_resp.message = "Wrong block blob";
return false;
}
// Fixing of high orphan issue for most pools
// Thanks Boolberry!
block b = AUTO_VAL_INIT(b);
if(!parse_and_validate_block_from_blob(blockblob, b))
{
error_resp.code = CORE_RPC_ERROR_CODE_WRONG_BLOCKBLOB;
error_resp.message = "Wrong block blob";
return false;
}
// Fix from Boolberry neglects to check block
// size, do that with the function below
if(!m_core.check_incoming_block_size(blockblob))
{
error_resp.code = CORE_RPC_ERROR_CODE_WRONG_BLOCKBLOB_SIZE;
error_resp.message = "Block bloc size is too big, rejecting block";
return false;
}
if(!m_core.handle_block_found(b))
{
error_resp.code = CORE_RPC_ERROR_CODE_BLOCK_NOT_ACCEPTED;
error_resp.message = "Block not accepted";
return false;
}
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
uint64_t core_rpc_server::get_block_reward(const block& blk)
{
uint64_t reward = 0;
BOOST_FOREACH(const tx_out& out, blk.miner_tx.vout)
{
reward += out.amount;
}
return reward;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::fill_block_header_response(const block& blk, bool orphan_status, uint64_t height, const crypto::hash& hash, block_header_response& response)
{
response.major_version = blk.major_version;
response.minor_version = blk.minor_version;
response.timestamp = blk.timestamp;
response.prev_hash = string_tools::pod_to_hex(blk.prev_id);
response.nonce = blk.nonce;
response.orphan_status = orphan_status;
response.height = height;
response.depth = m_core.get_current_blockchain_height() - height - 1;
response.hash = string_tools::pod_to_hex(hash);
response.difficulty = m_core.get_blockchain_storage().block_difficulty(height);
response.reward = get_block_reward(blk);
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_last_block_header(const COMMAND_RPC_GET_LAST_BLOCK_HEADER::request& req, COMMAND_RPC_GET_LAST_BLOCK_HEADER::response& res, epee::json_rpc::error& error_resp)
{
if(!check_core_busy())
{
error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY;
error_resp.message = "Core is busy.";
return false;
}
uint64_t last_block_height;
crypto::hash last_block_hash;
bool have_last_block_hash = m_core.get_blockchain_top(last_block_height, last_block_hash);
if (!have_last_block_hash)
{
error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
error_resp.message = "Internal error: can't get last block hash.";
return false;
}
block last_block;
bool have_last_block = m_core.get_block_by_hash(last_block_hash, last_block);
if (!have_last_block)
{
error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
error_resp.message = "Internal error: can't get last block.";
return false;
}
bool response_filled = fill_block_header_response(last_block, false, last_block_height, last_block_hash, res.block_header);
if (!response_filled)
{
error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
error_resp.message = "Internal error: can't produce valid response.";
return false;
}
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_block_header_by_hash(const COMMAND_RPC_GET_BLOCK_HEADER_BY_HASH::request& req, COMMAND_RPC_GET_BLOCK_HEADER_BY_HASH::response& res, epee::json_rpc::error& error_resp){
if(!check_core_busy())
{
error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY;
error_resp.message = "Core is busy.";
return false;
}
crypto::hash block_hash;
bool hash_parsed = parse_hash256(req.hash, block_hash);
if(!hash_parsed)
{
error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM;
error_resp.message = "Failed to parse hex representation of block hash. Hex = " + req.hash + '.';
return false;
}
block blk;
bool have_block = m_core.get_block_by_hash(block_hash, blk);
if (!have_block)
{
error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
error_resp.message = "Internal error: can't get block by hash. Hash = " + req.hash + '.';
return false;
}
if (blk.miner_tx.vin.front().type() != typeid(txin_gen))
{
error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
error_resp.message = "Internal error: coinbase transaction in the block has the wrong type";
return false;
}
uint64_t block_height = boost::get<txin_gen>(blk.miner_tx.vin.front()).height;
bool response_filled = fill_block_header_response(blk, false, block_height, block_hash, res.block_header);
if (!response_filled)
{
error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
error_resp.message = "Internal error: can't produce valid response.";
return false;
}
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_block_headers_range(const COMMAND_RPC_GET_BLOCK_HEADERS_RANGE::request& req, COMMAND_RPC_GET_BLOCK_HEADERS_RANGE::response& res, epee::json_rpc::error& error_resp){
if(!check_core_busy())
{
error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY;
error_resp.message = "Core is busy.";
return false;
}
const uint64_t bc_height = m_core.get_current_blockchain_height();
if (req.start_height >= bc_height || req.end_height >= bc_height || req.start_height > req.end_height)
{
error_resp.code = CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT;
error_resp.message = "Invalid start/end heights.";
return false;
}
for (uint64_t h = req.start_height; h <= req.end_height; ++h)
{
crypto::hash block_hash = m_core.get_block_id_by_height(h);
block blk;
bool have_block = m_core.get_block_by_hash(block_hash, blk);
if (!have_block)
{
error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
error_resp.message = "Internal error: can't get block by height. Height = " + boost::lexical_cast<std::string>(h) + ". Hash = " + epee::string_tools::pod_to_hex(block_hash) + '.';
return false;
}
if (blk.miner_tx.vin.front().type() != typeid(txin_gen))
{
error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
error_resp.message = "Internal error: coinbase transaction in the block has the wrong type";
return false;
}
uint64_t block_height = boost::get<txin_gen>(blk.miner_tx.vin.front()).height;
if (block_height != h)
{
error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
error_resp.message = "Internal error: coinbase transaction in the block has the wrong height";
return false;
}
res.headers.push_back(block_header_response());
bool responce_filled = fill_block_header_response(blk, false, block_height, block_hash, res.headers.back());
if (!responce_filled)
{
error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
error_resp.message = "Internal error: can't produce valid response.";
return false;
}
}
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_block_header_by_height(const COMMAND_RPC_GET_BLOCK_HEADER_BY_HEIGHT::request& req, COMMAND_RPC_GET_BLOCK_HEADER_BY_HEIGHT::response& res, epee::json_rpc::error& error_resp){
if(!check_core_busy())
{
error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY;
error_resp.message = "Core is busy.";
return false;
}
if(m_core.get_current_blockchain_height() <= req.height)
{
error_resp.code = CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT;
error_resp.message = std::string("Too big height: ") + std::to_string(req.height) + ", current blockchain height = " + std::to_string(m_core.get_current_blockchain_height());
return false;
}
crypto::hash block_hash = m_core.get_block_id_by_height(req.height);
block blk;
bool have_block = m_core.get_block_by_hash(block_hash, blk);
if (!have_block)
{
error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
error_resp.message = "Internal error: can't get block by height. Height = " + std::to_string(req.height) + '.';
return false;
}
bool response_filled = fill_block_header_response(blk, false, req.height, block_hash, res.block_header);
if (!response_filled)
{
error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
error_resp.message = "Internal error: can't produce valid response.";
return false;
}
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_block(const COMMAND_RPC_GET_BLOCK::request& req, COMMAND_RPC_GET_BLOCK::response& res, epee::json_rpc::error& error_resp){
if(!check_core_busy())
{
error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY;
error_resp.message = "Core is busy.";
return false;
}
crypto::hash block_hash;
if (!req.hash.empty())
{
bool hash_parsed = parse_hash256(req.hash, block_hash);
if(!hash_parsed)
{
error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM;
error_resp.message = "Failed to parse hex representation of block hash. Hex = " + req.hash + '.';
return false;
}
}
else
{
if(m_core.get_current_blockchain_height() <= req.height)
{
error_resp.code = CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT;
error_resp.message = std::string("Too big height: ") + std::to_string(req.height) + ", current blockchain height = " + std::to_string(m_core.get_current_blockchain_height());
return false;
}
block_hash = m_core.get_block_id_by_height(req.height);
}
block blk;
bool have_block = m_core.get_block_by_hash(block_hash, blk);
if (!have_block)
{
error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
error_resp.message = "Internal error: can't get block by hash. Hash = " + req.hash + '.';
return false;
}
if (blk.miner_tx.vin.front().type() != typeid(txin_gen))
{
error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
error_resp.message = "Internal error: coinbase transaction in the block has the wrong type";
return false;
}
uint64_t block_height = boost::get<txin_gen>(blk.miner_tx.vin.front()).height;
bool response_filled = fill_block_header_response(blk, false, block_height, block_hash, res.block_header);
if (!response_filled)
{
error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
error_resp.message = "Internal error: can't produce valid response.";
return false;
}
for (size_t n = 0; n < blk.tx_hashes.size(); ++n)
{
res.tx_hashes.push_back(epee::string_tools::pod_to_hex(blk.tx_hashes[n]));
}
res.blob = string_tools::buff_to_hex_nodelimer(t_serializable_object_to_blob(blk));
res.json = obj_to_json_str(blk);
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_connections(const COMMAND_RPC_GET_CONNECTIONS::request& req, COMMAND_RPC_GET_CONNECTIONS::response& res, epee::json_rpc::error& error_resp)
{
if(!check_core_busy())
{
error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY;
error_resp.message = "Core is busy.";
return false;
}
res.connections = m_p2p.get_payload_object().get_connections();
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_info_json(const COMMAND_RPC_GET_INFO::request& req, COMMAND_RPC_GET_INFO::response& res, epee::json_rpc::error& error_resp)
{
if(!check_core_busy())
{
error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY;
error_resp.message = "Core is busy.";
return false;
}
crypto::hash top_hash;
if (!m_core.get_blockchain_top(res.height, top_hash))
{
res.status = "Failed";
return false;
}
++res.height; // turn top block height into blockchain height
res.top_block_hash = string_tools::pod_to_hex(top_hash);
res.target_height = m_core.get_target_blockchain_height();
res.difficulty = m_core.get_blockchain_storage().get_difficulty_for_next_block();
res.target = DIFFICULTY_TARGET;
res.tx_count = m_core.get_blockchain_storage().get_total_transactions() - res.height; //without coinbase
res.tx_pool_size = m_core.get_pool_transactions_count();
res.alt_blocks_count = m_core.get_blockchain_storage().get_alternative_blocks_count();
uint64_t total_conn = m_p2p.get_connections_count();
res.outgoing_connections_count = m_p2p.get_outgoing_connections_count();
res.incoming_connections_count = total_conn - res.outgoing_connections_count;
res.white_peerlist_size = m_p2p.get_peerlist_manager().get_white_peers_count();
res.grey_peerlist_size = m_p2p.get_peerlist_manager().get_gray_peers_count();
res.testnet = m_testnet;
res.cumulative_difficulty = m_core.get_blockchain_storage().get_db().get_block_cumulative_difficulty(res.height - 1);
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_hard_fork_info(const COMMAND_RPC_HARD_FORK_INFO::request& req, COMMAND_RPC_HARD_FORK_INFO::response& res, epee::json_rpc::error& error_resp)
{
if(!check_core_busy())
{
error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY;
error_resp.message = "Core is busy.";
return false;
}
const Blockchain &blockchain = m_core.get_blockchain_storage();
uint8_t version = req.version > 0 ? req.version : blockchain.get_next_hard_fork_version();
res.version = blockchain.get_current_hard_fork_version();
res.enabled = blockchain.get_hard_fork_voting_info(version, res.window, res.votes, res.threshold, res.earliest_height, res.voting);
res.state = blockchain.get_hard_fork_state();
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_bans(const COMMAND_RPC_GETBANS::request& req, COMMAND_RPC_GETBANS::response& res, epee::json_rpc::error& error_resp)
{
if(!check_core_busy())
{
error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY;
error_resp.message = "Core is busy.";
return false;
}
auto now = time(nullptr);
std::map<uint32_t, time_t> blocked_ips = m_p2p.get_blocked_ips();
for (std::map<uint32_t, time_t>::const_iterator i = blocked_ips.begin(); i != blocked_ips.end(); ++i)
{
if (i->second > now) {
COMMAND_RPC_GETBANS::ban b;
b.ip = i->first;
b.seconds = i->second - now;
res.bans.push_back(b);
}
}
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_set_bans(const COMMAND_RPC_SETBANS::request& req, COMMAND_RPC_SETBANS::response& res, epee::json_rpc::error& error_resp)
{
if(!check_core_busy())
{
error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY;
error_resp.message = "Core is busy.";
return false;
}
for (auto i = req.bans.begin(); i != req.bans.end(); ++i)
{
if (i->ban)
m_p2p.block_ip(i->ip, i->seconds);
else
m_p2p.unblock_ip(i->ip);
}
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_flush_txpool(const COMMAND_RPC_FLUSH_TRANSACTION_POOL::request& req, COMMAND_RPC_FLUSH_TRANSACTION_POOL::response& res, epee::json_rpc::error& error_resp)
{
if(!check_core_busy())
{
error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY;
error_resp.message = "Core is busy.";
return false;
}
bool failed = false;
std::list<crypto::hash> txids;
if (req.txids.empty())
{
std::list<transaction> pool_txs;
bool r = m_core.get_pool_transactions(pool_txs);
if (!r)
{
res.status = "Failed to get txpool contents";
return true;
}
for (const auto &tx: pool_txs)
{
txids.push_back(cryptonote::get_transaction_hash(tx));
}
}
else
{
for (const auto &str: req.txids)
{
cryptonote::blobdata txid_data;
if(!epee::string_tools::parse_hexstr_to_binbuff(str, txid_data))
{
failed = true;
}
crypto::hash txid = *reinterpret_cast<const crypto::hash*>(txid_data.data());
txids.push_back(txid);
}
}
if (!m_core.get_blockchain_storage().flush_txes_from_pool(txids))
{
res.status = "Failed to remove one more tx";
return false;
}
if (failed)
{
res.status = "Failed to parse txid";
return false;
}
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_output_histogram(const COMMAND_RPC_GET_OUTPUT_HISTOGRAM::request& req, COMMAND_RPC_GET_OUTPUT_HISTOGRAM::response& res, epee::json_rpc::error& error_resp)
{
if(!check_core_busy())
{
error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY;
error_resp.message = "Core is busy.";
return false;
}
std::map<uint64_t, std::tuple<uint64_t, uint64_t, uint64_t>> histogram;
try
{
histogram = m_core.get_blockchain_storage().get_output_histogram(req.amounts, req.unlocked, req.recent_cutoff);
}
catch (const std::exception &e)
{
res.status = "Failed to get output histogram";
return true;
}
res.histogram.clear();
res.histogram.reserve(histogram.size());
for (const auto &i: histogram)
{
if (std::get<0>(i.second) >= req.min_count && (std::get<0>(i.second) <= req.max_count || req.max_count == 0))
res.histogram.push_back(COMMAND_RPC_GET_OUTPUT_HISTOGRAM::entry(i.first, std::get<0>(i.second), std::get<1>(i.second), std::get<2>(i.second)));
}
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_version(const COMMAND_RPC_GET_VERSION::request& req, COMMAND_RPC_GET_VERSION::response& res, epee::json_rpc::error& error_resp)
{
res.version = CORE_RPC_VERSION;
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_coinbase_tx_sum(const COMMAND_RPC_GET_COINBASE_TX_SUM::request& req, COMMAND_RPC_GET_COINBASE_TX_SUM::response& res, epee::json_rpc::error& error_resp)
{
std::pair<uint64_t, uint64_t> amounts = m_core.get_coinbase_tx_sum(req.height, req.count);
res.emission_amount = amounts.first;
res.fee_amount = amounts.second;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_get_per_kb_fee_estimate(const COMMAND_RPC_GET_PER_KB_FEE_ESTIMATE::request& req, COMMAND_RPC_GET_PER_KB_FEE_ESTIMATE::response& res, epee::json_rpc::error& error_resp)
{
res.fee = m_core.get_blockchain_storage().get_dynamic_per_kb_fee_estimate(req.grace_blocks);
res.status = CORE_RPC_STATUS_OK;
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_out_peers(const COMMAND_RPC_OUT_PEERS::request& req, COMMAND_RPC_OUT_PEERS::response& res)
{
// TODO
/*if (m_p2p.get_outgoing_connections_count() > req.out_peers)
{
m_p2p.m_config.m_net_config.connections_count = req.out_peers;
if (m_p2p.get_outgoing_connections_count() > req.out_peers)
{
int count = m_p2p.get_outgoing_connections_count() - req.out_peers;
m_p2p.delete_connections(count);
}
}
else
m_p2p.m_config.m_net_config.connections_count = req.out_peers;
*/
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_start_save_graph(const COMMAND_RPC_START_SAVE_GRAPH::request& req, COMMAND_RPC_START_SAVE_GRAPH::response& res)
{
m_p2p.set_save_graph(true);
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
bool core_rpc_server::on_stop_save_graph(const COMMAND_RPC_STOP_SAVE_GRAPH::request& req, COMMAND_RPC_STOP_SAVE_GRAPH::response& res)
{
m_p2p.set_save_graph(false);
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
const command_line::arg_descriptor<std::string> core_rpc_server::arg_rpc_bind_ip = {
"rpc-bind-ip"
, "IP for RPC server"
, "127.0.0.1"
};
const command_line::arg_descriptor<std::string> core_rpc_server::arg_rpc_bind_port = {
"rpc-bind-port"
, "Port for RPC server"
, std::to_string(config::RPC_DEFAULT_PORT)
};
const command_line::arg_descriptor<std::string> core_rpc_server::arg_testnet_rpc_bind_port = {
"testnet-rpc-bind-port"
, "Port for testnet RPC server"
, std::to_string(config::testnet::RPC_DEFAULT_PORT)
};
const command_line::arg_descriptor<bool> core_rpc_server::arg_restricted_rpc = {
"restricted-rpc"
, "Restrict RPC to view only commands"
, false
};
const command_line::arg_descriptor<std::string> core_rpc_server::arg_user_agent = {
"user-agent"
, "Restrict RPC to clients using this user agent"
, ""
};
} // namespace cryptonote
| [
""
] | |
be26cb5e563ca8a301dec40afb3bff14e0714909 | d7b2eef3c363d735afc14abefe88a0d6426cd133 | /dynamic_programming/C.cpp | 8254f1fe9965c13919972f735b18c79111a1234b | [] | no_license | AndreyBocharnikov/Algorithms-and-Data-structures | ab5d6a4552f59bcae567ca76c14370230d75b0b5 | 0eb404fa8521c0550d4a23d563649c49d2cc56bc | refs/heads/master | 2023-06-04T16:51:01.401711 | 2021-06-15T09:57:28 | 2021-06-15T09:57:28 | 250,284,061 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,845 | cpp | #include <fstream>
#include <vector>
#include <algorithm>
#define ll long long
#define f first
#define s second
using namespace std;
ll dp[2001][2001], w[2001];
int R[2001][2001];
vector <string> ans;
void find_ans(int l, int r) {
if (l == r)
return;
int mid = R[l][r];
// cout << l << " " << mid << " " << r << '\n';
for (int i = l; i <= mid; i++)
ans[i] += '0';
for (int i = mid + 1; i <= r; i++)
ans[i] += '1';
find_ans(l, mid);
find_ans(mid + 1, r);
}
int main() {
ifstream cin("optimalcode.in");
ofstream cout("optimalcode.out");
int n;
ll inf = 1e18;
cin >> n;
ans.resize(n);
vector <ll> f(n);
for (int i = 0; i < 2001; i++)
for (int j = 0; j < 2001; j++)
dp[i][j] = inf;
for (int i = 0; i < n; i++)
cin >> f[i],
dp[i][i] = 0;
for (int i = 0; i < n; i++)
w[i] = f[i];
for (int i = 1; i < n; i++)
w[i] += w[i - 1];
for (int i = 0; i < n; i++)
R[i][i] = i;
for (int len = 2; len <= n; len++) {
for (int i = 0; i <= n - len; i++) {
int j = i + len - 1;
int l = R[i][j - 1], r = R[i + 1][j];
ll val = i == 0 ? w[j] : w[j] - w[i - 1];
// cout << i << " " << j << " " << l << " " << r << '\n';
for (int k = l; k <= r; k++) {
if (k + 1 <= j && dp[i][k] + dp[k + 1][j] < dp[i][j])
dp[i][j] = dp[i][k] + dp[k + 1][j],
R[i][j] = k;
}
dp[i][j] += val;
// cout << i << " " << j << " " << dp[i][j] << '\n';
}
}
cout << dp[0][n - 1] << '\n';
find_ans(0, n - 1);
for (int i = 0; i < n; i++) {
cout << ans[i] << '\n';
}
}
| [
"a-bocharnikov@bk.ru"
] | a-bocharnikov@bk.ru |
d6053c911037b737af040af6165b9a9817b98856 | 9d364070c646239b2efad7abbab58f4ad602ef7b | /platform/external/chromium_org/chrome/browser/sync/test/integration/themes_helper.h | 587f790635b6ce04c5478c43385507e55d28b89c | [
"BSD-3-Clause"
] | permissive | denix123/a32_ul | 4ffe304b13c1266b6c7409d790979eb8e3b0379c | b2fd25640704f37d5248da9cc147ed267d4771c2 | refs/heads/master | 2021-01-17T20:21:17.196296 | 2016-08-16T04:30:53 | 2016-08-16T04:30:53 | 65,786,970 | 0 | 2 | null | 2020-03-06T22:00:52 | 2016-08-16T04:15:54 | null | UTF-8 | C++ | false | false | 1,201 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_SYNC_TEST_INTEGRATION_THEMES_HELPER_H_
#define CHROME_BROWSER_SYNC_TEST_INTEGRATION_THEMES_HELPER_H_
#include <string>
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
class Profile;
namespace themes_helper {
std::string GetCustomTheme(int index) WARN_UNUSED_RESULT;
std::string GetThemeID(Profile* profile) WARN_UNUSED_RESULT;
bool UsingCustomTheme(Profile* profile) WARN_UNUSED_RESULT;
bool UsingDefaultTheme(Profile* profile) WARN_UNUSED_RESULT;
bool UsingSystemTheme(Profile* profile) WARN_UNUSED_RESULT;
bool ThemeIsPendingInstall(
Profile* profile, const std::string& id) WARN_UNUSED_RESULT;
void UseCustomTheme(Profile* profile, int index);
void UseDefaultTheme(Profile* profile);
void UseSystemTheme(Profile* profile);
bool AwaitThemeIsPendingInstall(Profile* profile, const std::string& theme);
bool AwaitUsingSystemTheme(Profile* profile);
bool AwaitUsingDefaultTheme(Profile* profile);
}
#endif
| [
"allegrant@mail.ru"
] | allegrant@mail.ru |
5c08bf721268856c2037578406d82a5c85bb4708 | bcf138c82fcba9acc7d7ce4d3a92618b06ebe7c7 | /gta5/0xAA0A52D24FB98293.cpp | a5cb865f044fc64cb0cbee54deebd2d665db09e8 | [] | no_license | DeepWolf413/additional-native-data | aded47e042f0feb30057e753910e0884c44121a0 | e015b2500b52065252ffbe3c53865fe3cdd3e06c | refs/heads/main | 2023-07-10T00:19:54.416083 | 2021-08-12T16:00:12 | 2021-08-12T16:00:12 | 395,340,507 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 821 | cpp | // am_imp_exp.ysc @ L8276
void func_189(int iParam0, int iParam1, int iParam2)
{
int iVar0;
int iVar1;
int iVar2;
var uVar3;
HUD::GET_HUD_COLOUR(iParam2, &iVar0, &iVar1, &iVar2, &uVar3);
if (iParam1 == 0)
{
}
VEHICLE::TRACK_VEHICLE_VISIBILITY(iParam0);
if (func_14(PLAYER::PLAYER_ID(), 1, 1))
{
if (VEHICLE::IS_VEHICLE_DRIVEABLE(iParam0, false))
{
if (func_190(iParam0) == 0)
{
if (!PED::IS_PED_IN_VEHICLE(PLAYER::PLAYER_PED_ID(), iParam0, false))
{
if (VEHICLE::IS_VEHICLE_VISIBLE(iParam0))
{
GRAPHICS::ADD_ENTITY_ICON(iParam0, "MP_Arrow");
GRAPHICS::SET_ENTITY_ICON_COLOR(iParam0, iVar0, iVar1, iVar2, 190);
GRAPHICS::SET_ENTITY_ICON_VISIBILITY(iParam0, true);
}
}
}
}
}
} | [
"jesper15fuji@live.dk"
] | jesper15fuji@live.dk |
10c2c399ba3cac69feeb154d609d98e5f171e55b | e1383b70afaacf030012f04480f5e0b2608ebb42 | /ESP-Now/espnow-gateway/espnow-gateway.ino | 93c3cb62fd89177f8529458583c1e2c97a002098 | [
"CC0-1.0"
] | permissive | px4ugs/IoT | 025dfa291f5c6efbbe8854235d7d8882c96303c9 | 8b078b4a5663dd31603e70df603ae2457d442018 | refs/heads/master | 2020-06-20T13:03:10.874306 | 2017-05-06T12:03:22 | 2017-05-06T12:03:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,107 | ino | /*
Testing ESP-Now
See https://espressif.com/en/products/software/esp-now/overview
ESP-Now enables fast lightwieght connectionless communication between ESP8266's.
So for example a remote sensor node could send a reading using ESP-Now in just a few
hundred milliseconds and deepSleep the rest of the time and so get increased battery
life compared to the node using a regular WiFi connection which could take 10 times
as long to connect to WiFi and send a sensor reading.
ESP-Now has the concept of controllers and slaves. AFAICT the controller is the remote
sensor node and the slave is the always on "gateway" node that listens for sensor node readings.
*** Note: to compile ESP-Now (with arduino/esp8266 release 2.3.0) need to edit
* ~/Library/Arduino15/packages/esp8266/hardware/esp8266/2.1.0/platform.txt
* Search "compiler.c.elf.libs", and append "-lespnow" at the end of the line.
* See: http://www.esp8266.com/viewtopic.php?p=44161#p44161
***
**** This skecth is the slave/gateway node ****
Ant Elder
License: Apache License v2
*/
#include <ESP8266WiFi.h>
extern "C" {
#include <espnow.h>
}
const char* ssid = "BTHub5-72W5";
const char* password = "xxxxxxxxxx";
#define WIFI_CHANNEL 1
// keep in sync with sensor struct
struct SENSOR_DATA {
float temp;
float hum;
float t;
float pressure;
};
void setup() {
Serial.begin(115200); Serial.println();
initWifi();
if (esp_now_init()!=0) {
Serial.println("*** ESP_Now init failed");
ESP.restart();
}
Serial.print("This node AP mac: "); Serial.print(WiFi.softAPmacAddress());
Serial.print(", STA mac: "); Serial.println(WiFi.macAddress());
// Note: When ESP8266 is in soft-AP+station mode, this will communicate through station interface
// if it is in slave role, and communicate through soft-AP interface if it is in controller role,
// so you need to make sure the remote nodes use the correct MAC address being used by this gateway.
esp_now_set_self_role(ESP_NOW_ROLE_SLAVE);
esp_now_register_recv_cb([](uint8_t *mac, uint8_t *data, uint8_t len) {
Serial.print("recv_cb, from mac: ");
char macString[50] = {0};
sprintf(macString, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
Serial.print(macString);
getReading(data, len);
});
}
void loop() {
}
void getReading(uint8_t *data, uint8_t len) {
SENSOR_DATA tmp;
memcpy(&tmp, data, sizeof(tmp));
Serial.print(", parsed data, t="); Serial.println(tmp.t);
}
void initWifi() {
WiFi.mode(WIFI_AP_STA);
WiFi.softAP("MyGateway", "12345678", WIFI_CHANNEL, 1);
Serial.print("Connecting to "); Serial.print(ssid);
if (strcmp (WiFi.SSID().c_str(), ssid) != 0) {
WiFi.begin(ssid, password);
}
int retries = 20; // 10 seconds
while ((WiFi.status() != WL_CONNECTED) && (retries-- > 0)) {
delay(500);
Serial.print(".");
}
Serial.println("");
if (retries < 1) {
Serial.print("*** WiFi connection failed");
ESP.restart();
}
Serial.print("WiFi connected, IP address: "); Serial.println(WiFi.localIP());
}
| [
"ant.elder@uk.ibm.com"
] | ant.elder@uk.ibm.com |
9a453052e9369e618a723a5a3baad7de3cdedb42 | 385cb76729b67994db6ce40b70e6f6806c5f4303 | /RomiRobot_MovementAndMapping_v1.5/button.h | 4331c6538c701bd0b2455217e40084fba326cbb3 | [
"MIT"
] | permissive | meisben/RomiRobot_MovementAndMapping | f638f8d26fd846558bbfa66ed4edadc4de60e690 | 993d3c5c2fc067f343343662a3a0dc31a8e133ce | refs/heads/master | 2020-05-17T14:10:02.422730 | 2019-05-08T19:46:51 | 2019-05-08T19:46:51 | 183,757,226 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,348 | h | // Arduino Button Library
// https://github.com/JChristensen/JC_Button
// Copyright (C) 2018 by Jack Christensen and licensed under
// GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html
#ifndef JC_BUTTON_H_INCLUDED
#define JC_BUTTON_H_INCLUDED
//#include <Arduino.h>
class Button
{
public:
// Button(pin, dbTime, puEnable, invert) instantiates a button object.
//
// Required parameter:
// pin The Arduino pin the button is connected to
//
// Optional parameters:
// dbTime Debounce time in milliseconds (default 25ms)
// puEnable true to enable the AVR internal pullup resistor (default true)
// invert true to interpret a low logic level as pressed (default true)
Button(uint8_t pin, uint32_t dbTime=25, uint8_t puEnable=true, uint8_t invert=true)
: m_pin(pin), m_dbTime(dbTime), m_puEnable(puEnable), m_invert(invert) {}
// Initialize a Button object and the pin it's connected to
void begin();
// Returns the current debounced button state, true for pressed,
// false for released. Call this function frequently to ensure
// the sketch is responsive to user input.
bool read();
// Returns true if the button state was pressed at the last call to read().
// Does not cause the button to be read.
bool isPressed();
// Returns true if the button state was released at the last call to read().
// Does not cause the button to be read.
bool isReleased();
// Returns true if the button state at the last call to read() was pressed,
// and this was a change since the previous read.
bool wasPressed();
// Returns true if the button state at the last call to read() was released,
// and this was a change since the previous read.
bool wasReleased();
// Returns true if the button state at the last call to read() was pressed,
// and has been in that state for at least the given number of milliseconds.
bool pressedFor(uint32_t ms);
// Returns true if the button state at the last call to read() was released,
// and has been in that state for at least the given number of milliseconds.
bool releasedFor(uint32_t ms);
// Returns the time in milliseconds (from millis) that the button last
// changed state.
uint32_t lastChange();
private:
uint8_t m_pin; // arduino pin number connected to button
uint32_t m_dbTime; // debounce time (ms)
bool m_puEnable; // internal pullup resistor enabled
bool m_invert; // if true, interpret logic low as pressed, else interpret logic high as pressed
bool m_state; // current button state, true=pressed
bool m_lastState; // previous button state
bool m_changed; // state changed since last read
uint32_t m_time; // time of current state (ms from millis)
uint32_t m_lastChange; // time of last state change (ms)
};
/*----------------------------------------------------------------------*
/ initialize a Button object and the pin it's connected to. *
/-----------------------------------------------------------------------*/
void Button::begin()
{
pinMode(m_pin, m_puEnable ? INPUT_PULLUP : INPUT);
m_state = digitalRead(m_pin);
if (m_invert) m_state = !m_state;
m_time = millis();
m_lastState = m_state;
m_changed = false;
m_lastChange = m_time;
}
/*----------------------------------------------------------------------*
/ returns the state of the button, true if pressed, false if released. *
/ does debouncing, captures and maintains times, previous state, etc. *
/-----------------------------------------------------------------------*/
bool Button::read()
{
uint32_t ms = millis();
bool pinVal = digitalRead(m_pin);
if (m_invert) pinVal = !pinVal;
if (ms - m_lastChange < m_dbTime)
{
m_changed = false;
}
else
{
m_lastState = m_state;
m_state = pinVal;
m_changed = (m_state != m_lastState);
if (m_changed) m_lastChange = ms;
}
m_time = ms;
return m_state;
}
/*----------------------------------------------------------------------*
* isPressed() and isReleased() check the button state when it was last *
* read, and return false (0) or true (!=0) accordingly. *
* These functions do not cause the button to be read. *
*----------------------------------------------------------------------*/
bool Button::isPressed()
{
return m_state;
}
bool Button::isReleased()
{
return !m_state;
}
/*----------------------------------------------------------------------*
* wasPressed() and wasReleased() check the button state to see if it *
* changed between the last two reads and return false (0) or *
* true (!=0) accordingly. *
* These functions do not cause the button to be read. *
*----------------------------------------------------------------------*/
bool Button::wasPressed()
{
return m_state && m_changed;
}
bool Button::wasReleased()
{
return !m_state && m_changed;
}
/*----------------------------------------------------------------------*
* pressedFor(ms) and releasedFor(ms) check to see if the button is *
* pressed (or released), and has been in that state for the specified *
* time in milliseconds. Returns false (0) or true (!=0) accordingly. *
* These functions do not cause the button to be read. *
*----------------------------------------------------------------------*/
bool Button::pressedFor(uint32_t ms)
{
return m_state && m_time - m_lastChange >= ms;
}
bool Button::releasedFor(uint32_t ms)
{
return !m_state && m_time - m_lastChange >= ms;
}
/*----------------------------------------------------------------------*
* lastChange() returns the time the button last changed state, *
* in milliseconds. *
*----------------------------------------------------------------------*/
uint32_t Button::lastChange()
{
return m_lastChange;
}
#endif
| [
"afunnyllama@gmail.com"
] | afunnyllama@gmail.com |
f946afd96f40ff7139a3862761ad0d6dc557c013 | 438cd59a4138cd87d79dcd62d699d563ed976eb9 | /mame/src/mame/includes/atarig42.h | d1aa27dbc638d6ec70b6f2d0c4e5bf6be06db9c5 | [] | no_license | clobber/UME | 031c677d49634b40b5db27fbc6e15d51c97de1c5 | 9d4231358d519eae294007133ab3eb45ae7e4f41 | refs/heads/master | 2021-01-20T05:31:28.376152 | 2013-05-01T18:42:59 | 2013-05-01T18:42:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,299 | h | /*************************************************************************
Atari G42 hardware
*************************************************************************/
#include "machine/atarigen.h"
class atarig42_state : public atarigen_state
{
public:
atarig42_state(const machine_config &mconfig, device_type type, const char *tag)
: atarigen_state(mconfig, type, tag),
m_mo_command(*this, "mo_command") { }
UINT16 m_playfield_base;
UINT16 m_current_control;
UINT8 m_playfield_tile_bank;
UINT8 m_playfield_color_bank;
UINT16 m_playfield_xscroll;
UINT16 m_playfield_yscroll;
UINT8 m_analog_data;
required_shared_ptr<UINT16> m_mo_command;
int m_sloop_bank;
int m_sloop_next_bank;
int m_sloop_offset;
int m_sloop_state;
UINT16 * m_sloop_base;
device_t * m_rle;
UINT32 m_last_accesses[8];
virtual void update_interrupts();
virtual void scanline_update(screen_device &screen, int scanline);
DECLARE_READ16_MEMBER(special_port2_r);
DECLARE_WRITE16_MEMBER(a2d_select_w);
DECLARE_READ16_MEMBER(a2d_data_r);
DECLARE_WRITE16_MEMBER(io_latch_w);
DECLARE_WRITE16_MEMBER(mo_command_w);
DECLARE_READ16_MEMBER(roadriot_sloop_data_r);
DECLARE_WRITE16_MEMBER(roadriot_sloop_data_w);
DECLARE_READ16_MEMBER(guardians_sloop_data_r);
DECLARE_WRITE16_MEMBER(guardians_sloop_data_w);
void roadriot_sloop_tweak(int offset);
void guardians_sloop_tweak(int offset);
DECLARE_DIRECT_UPDATE_MEMBER(atarig42_sloop_direct_handler);
DECLARE_DRIVER_INIT(roadriot);
DECLARE_DRIVER_INIT(guardian);
TILE_GET_INFO_MEMBER(get_alpha_tile_info);
TILE_GET_INFO_MEMBER(get_playfield_tile_info);
TILEMAP_MAPPER_MEMBER(atarig42_playfield_scan);
DECLARE_MACHINE_START(atarig42);
DECLARE_MACHINE_RESET(atarig42);
DECLARE_VIDEO_START(atarig42);
UINT32 screen_update_atarig42(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
void screen_eof_atarig42(screen_device &screen, bool state);
};
/*----------- defined in video/atarig42.c -----------*/
DECLARE_WRITE16_HANDLER( atarig42_mo_control_w );
void atarig42_scanline_update(screen_device &screen, int scanline);
| [
"brymaster@gmail.com"
] | brymaster@gmail.com |
186465f9cd35fcf9ff7b50a436459d05d19d50ec | bc15567a31a80adf9027710cfc1c04e6c2735b3c | /src/test/checkblock_tests.cpp | 57a2fc2fd6a9ab72e7f6059dae4bf4b42d666844 | [
"MIT"
] | permissive | shadowOz/stargate-guru-test | a012770acf941111cce415af9e02406d879421a3 | 41716cd5142df5d598775139c4a3313bc3c917ac | refs/heads/master | 2020-03-15T13:57:18.983505 | 2018-05-06T13:32:11 | 2018-05-06T13:32:11 | 132,179,190 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,901 | cpp | // Copyright (c) 2013-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientversion.h"
#include "consensus/validation.h"
#include "validation.h" // For CheckBlock
#include "primitives/block.h"
#include "test/test_stargate.h"
#include "utiltime.h"
#include <cstdio>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(CheckBlock_tests, BasicTestingSetup)
bool read_block(const std::string& filename, CBlock& block)
{
namespace fs = boost::filesystem;
fs::path testFile = fs::current_path() / "data" / filename;
#ifdef TEST_DATA_DIR
if (!fs::exists(testFile))
{
testFile = fs::path(BOOST_PP_STRINGIZE(TEST_DATA_DIR)) / filename;
}
#endif
FILE* fp = fopen(testFile.string().c_str(), "rb");
if (!fp) return false;
fseek(fp, 8, SEEK_SET); // skip msgheader/size
CAutoFile filein(fp, SER_DISK, CLIENT_VERSION);
if (filein.IsNull()) return false;
filein >> block;
return true;
}
BOOST_AUTO_TEST_CASE(May15)
{
// Putting a 1MB binary file in the git repository is not a great
// idea, so this test is only run if you manually download
// test/data/Mar12Fork.dat from
// http://sourceforge.net/projects/bitcoin/files/Bitcoin/blockchain/Mar12Fork.dat/download
unsigned int tMay15 = 1368576000;
SetMockTime(tMay15); // Test as if it was right at May 15
CBlock forkingBlock;
if (read_block("Mar12Fork.dat", forkingBlock))
{
CValidationState state;
// After May 15'th, big blocks are OK:
forkingBlock.nTime = tMay15; // Invalidates PoW
BOOST_CHECK(CheckBlock(forkingBlock, state, false, false));
}
SetMockTime(0);
}
BOOST_AUTO_TEST_SUITE_END()
| [
"38054148+shadowOz@users.noreply.github.com"
] | 38054148+shadowOz@users.noreply.github.com |
0dcebbc472ea2ff9bee964db7b2760231d91ff56 | ed0fb471daca59daa6255d75d4c68508e58e3454 | /recognition/include/pcl/recognition/distance_map.h | ac68e5b4ed81036bfd823775d271c9227326713a | [
"BSD-3-Clause"
] | permissive | mujin/pcl | ec9de205e1ee5940fd0a55a012733984a0bb1ff2 | 9a13da19c792ce1f9dfcb752bc92300f40270bec | refs/heads/master | 2023-06-09T13:49:51.928549 | 2022-04-18T01:03:29 | 2022-04-18T01:03:29 | 32,294,758 | 4 | 2 | NOASSERTION | 2023-05-09T03:41:42 | 2015-03-16T01:43:16 | C++ | UTF-8 | C++ | false | false | 3,929 | h | /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* 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 Willow Garage, Inc. 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 PCL_RECOGNITION_DISTANCE_MAP
#define PCL_RECOGNITION_DISTANCE_MAP
namespace pcl
{
/** \brief Represents a distance map obtained from a distance transformation.
* \author Stefan Holzer
*/
class DistanceMap
{
public:
/** \brief Constructor. */
DistanceMap () : data_ (0), width_ (0), height_ (0) {}
/** \brief Destructor. */
virtual ~DistanceMap () {}
/** \brief Returns the width of the map. */
inline size_t
getWidth () const
{
return (width_);
}
/** \brief Returns the height of the map. */
inline size_t
getHeight () const
{
return (height_);
}
/** \brief Returns a pointer to the beginning of map. */
inline float *
getData ()
{
return (&data_[0]);
}
/** \brief Resizes the map to the specified size.
* \param[in] width the new width of the map.
* \param[in] height the new height of the map.
*/
void
resize (const size_t width, const size_t height)
{
data_.resize (width*height);
width_ = width;
height_ = height;
}
/** \brief Operator to access an element of the map.
* \param[in] col_index the column index of the element to access.
* \param[in] row_index the row index of the element to access.
*/
inline float &
operator() (const size_t col_index, const size_t row_index)
{
return (data_[row_index*width_ + col_index]);
}
/** \brief Operator to access an element of the map.
* \param[in] col_index the column index of the element to access.
* \param[in] row_index the row index of the element to access.
*/
inline const float &
operator() (const size_t col_index, const size_t row_index) const
{
return (data_[row_index*width_ + col_index]);
}
protected:
/** \brief The storage for the distance map data. */
std::vector<float> data_;
/** \brief The width of the map. */
size_t width_;
/** \brief The height of the map. */
size_t height_;
};
}
#endif
| [
"holzers@in.tum.de"
] | holzers@in.tum.de |
4576b56b3a9ff0da8fa0ba63f368ca8998155b62 | cde72953df2205c2322aac3debf058bb31d4f5b9 | /win10.19042/System32/msvproc.dll.cpp | fafb10df5a7b0312e3c195ae9b4d3eaa2fdb3841 | [] | no_license | v4nyl/dll-exports | 928355082725fbb6fcff47cd3ad83b7390c60c5a | 4ec04e0c8f713f6e9a61059d5d87abc5c7db16cf | refs/heads/main | 2023-03-30T13:49:47.617341 | 2021-04-10T20:01:34 | 2021-04-10T20:01:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 280 | cpp | #print comment(linker, "/export:DllCanUnloadNow=\"C:\\Windows\\System32\\msvproc.dll\"")
#print comment(linker, "/export:DllGetActivationFactory=\"C:\\Windows\\System32\\msvproc.dll\"")
#print comment(linker, "/export:DllGetClassObject=\"C:\\Windows\\System32\\msvproc.dll\"")
| [
"magnus@stubman.eu"
] | magnus@stubman.eu |
cae933c60c16dae64e96cc7a48e6b330ee534d91 | 069ea34f9980dd0d0445202dcaa16d1a553a3e23 | /HDACMer/Buildings/main.cpp | d17145f540bb395b31a5932654b4e1cb4121fdcd | [] | no_license | theJinFei/C-Test | fe9c3b1236f3c40b8f0d1c7b1f90b517723d1b14 | e2e26578e7df245f1c1f35a74fd8c02966690f94 | refs/heads/master | 2021-09-01T17:11:07.727227 | 2017-12-28T02:14:05 | 2017-12-28T02:14:05 | 114,580,401 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 578 | cpp | #include <iostream>
#include <vector>
#include <stdio.h>
#include <algorithm>
#include <iomanip>
#include <string>
#include <cstdio>
#include <string.h>
#include <set>
#include <cmath>
using namespace std;
int main()
{
int N;
cin>>N;
while(N-->0){
int a,b;
cin>>a>>b;
int array[a][b],sum=0;
for(int i=0;i<a;i++){
for(int j=0;j<b;j++){
cin>>array[i][j];
if(array[i][j]==1){
sum++;
}
}
}
cout<<sum<<endl;
}
return 0;
}
| [
"luojinfei_study@163.com"
] | luojinfei_study@163.com |
6d15cafe514d886b84547382bd95847972d37c7f | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_10710.cpp | 542a39d6f5a2e9db385a2fbd0a1ab113cbf60190 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 103 | cpp | {
ci->folders[i].digest_defined = digest.defineds[i];
ci->folders[i].digest = digest.digests[i];
} | [
"993273596@qq.com"
] | 993273596@qq.com |
b07a35e1e7d1737a41dbd736258e12b374575f9e | 338a9f8e5f6d8b5b79b9c32b6319af16b02ff7b7 | /tests/src/utility/LambdaFunctionWithCapturesBadCase.hpp | 9cb71d085766876d48cf907c3eed16e97f63b78c | [
"MIT"
] | permissive | ddovod/jet-live | 26b60783cbd5ab76015c4386318731e49cbcdc00 | 59c38997f7c16f54ddf9e68a189384bd11878568 | refs/heads/master | 2022-08-26T18:52:46.584817 | 2022-01-28T09:00:25 | 2022-01-28T09:00:25 | 163,978,787 | 394 | 33 | MIT | 2020-01-18T10:28:27 | 2019-01-03T13:47:39 | C++ | UTF-8 | C++ | false | false | 110 | hpp |
#pragma once
#include <functional>
std::function<int(int, int)> createLambdaFunctionWithCapturesBadCase();
| [
"ddovod@gmail.com"
] | ddovod@gmail.com |
74415afe8b1b79b79598229727852d99f28d52db | c50d61136efbd74c97d939468542e40e0fbb79e1 | /core/vendor/pytorch-release/include/nvfuser_resources/grid_reduction.h | 4e7a1260996db3ff758c6bcc358336c3240333d4 | [] | no_license | Ajblast/GameEngine | e95836d631fa2e2057ab9a5219ceb57fcbf5b23f | db2473add049125f7e2c21965a3957e4f3d74ffc | refs/heads/main | 2023-09-01T17:31:20.655818 | 2021-10-17T13:03:45 | 2021-10-17T13:03:45 | 327,814,676 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,226 | h | // Generated from "C:/w/b/windows/pytorch/torch/csrc/jit/codegen/cuda/runtime/grid_reduction.cu"
// 2021-09-14 15:01:05
namespace nvfuser_resources {
constexpr const char* grid_reduction_cu = R"(
// Inter-block reduction.
//
// Function gridReduce performs point-wise reductions of scalars across thread
// blocks. Thread blocks are disjointly partitioned into groups of thread
// blocks, "reduction segments," that are collectively defined by boolean
// template parameters, X_BLOCK, Y_BLOCK and Z_BLOCK. Each of X/Y/Z_BLOCK
// determines whether thread blocks along the dimension should be grouped into
// the same reduction segment. Cross-block reducitons are independently done
// within each segment and generates distinctive results per segment. For
// instance, if all of X/Y/Z_BLOCK are true, reductions will be done across all
// thread blocks since there will be just a single segment consisting of all
// thread blocks. If none of them are true, each thread block will become a
// segment by itself, so no reduction will be performed.
//
// The input scalars to reduce within each segment are a certain subset of
// thread-private scalars provided as part of the gridReduce function
// parameters. Boolean template parameters, X_THREAD, Y_THREAD and Z_THREAD,
// determine which subset of the scalars should be used for inter-block
// reductions. Specifically, all the input scalars of threads along each
// dimension will be used when X/Y/Z_THREAD are true. Otherwise, only the value
// held at offset 0 of each dimension will be used. Thus, for example, if all of
// X/Y/Z_THREAD are true, the scalars of all threads in each block will
// participate in inter-block reductions. If all of them are false, only one
// scalar of the thread at threadIdx.x == threadIdx.y == threadIdx.z == 0 will
// be used. In the code below, we call the subset of threads a "reduction
// block."
//
// Inter-block reductions perform point-wise reductions of scalars of reduction
// blocks within each reduction segment. More specifically, let rb be a
// reduction block and rs be a reduction segment. Let IN(thread_idx, block_idx)
// denote the input scalar of thread at thread_idx and block_idx. The result of
// each reduction segment, OUT(thread_idx, block_idx_out), is defined only for
// each thread_idx in thread block block_idx_out in the segment as follows:
//
// OUT(thread_idx, block_idx_out) =
// Reduction of IN(thread_idx, block_idx) for
// all block_idx in a reduction segment
//
// OUT is not given for all threads that are not in block_idx_out and the
// reduction block.
//
// See also the function comment of gridReduce.
namespace reduction {
// Utility functions
template <typename _dim3>
__device__ __forceinline__ size_t size(const _dim3& d) {
return (size_t)d.x * (size_t)d.y * (size_t)d.z;
}
#define isize(d) d.x* d.y* d.z
template <typename _dim3pos, typename _dim3dim>
__device__ __forceinline__ size_t
offset(const _dim3pos& pos, const _dim3dim& dim) {
return (size_t)pos.x + (size_t)pos.y * (size_t)dim.x +
(size_t)pos.z * (size_t)dim.x * (size_t)dim.y;
}
#define ioffset(pos, dim) pos.x + pos.y* dim.x + pos.z* dim.x* dim.y
// Returns dim3 of each reduction segment.
template <bool X_BLOCK, bool Y_BLOCK, bool Z_BLOCK, typename _dim3>
__device__ dim3 dimension_of_reduction_segment(const _dim3& grid_dim) {
return dim3{
X_BLOCK ? (unsigned)grid_dim.x : 1U,
Y_BLOCK ? (unsigned)grid_dim.y : 1U,
Z_BLOCK ? (unsigned)grid_dim.z : 1U};
}
// Returns the number of blocks in each reduction segment.
template <bool X_BLOCK, bool Y_BLOCK, bool Z_BLOCK, typename _dim3>
__device__ size_t size_of_reduction_segment(const _dim3& grid_dim) {
return size(
dimension_of_reduction_segment<X_BLOCK, Y_BLOCK, Z_BLOCK>(grid_dim));
}
// Returns the total number of reduction segments.
template <bool X_BLOCK, bool Y_BLOCK, bool Z_BLOCK, typename _dim3>
__device__ size_t number_of_reduction_segments(const _dim3& grid_dim) {
return (X_BLOCK ? 1 : grid_dim.x) * (Y_BLOCK ? 1 : grid_dim.y) *
(Z_BLOCK ? 1 : grid_dim.z);
}
// Returns the 1-D index of the segment of thread block of block_idx.
template <
bool X_BLOCK,
bool Y_BLOCK,
bool Z_BLOCK,
typename _dim3bi,
typename _dim3gd>
__device__ size_t
index_of_reduction_segment(const _dim3bi& block_idx, const _dim3gd& grid_dim) {
size_t seg_idx = 0;
if (!Z_BLOCK)
seg_idx += block_idx.z;
if (!Y_BLOCK)
seg_idx = seg_idx * grid_dim.y + block_idx.y;
if (!X_BLOCK)
seg_idx = seg_idx * grid_dim.x + block_idx.x;
return seg_idx;
}
// Returns the offset of thread block in its reduction segment.
template <
bool X_BLOCK,
bool Y_BLOCK,
bool Z_BLOCK,
typename _dim3bi,
typename _dim3gd>
__device__ size_t
offset_in_reduction_segment(const _dim3bi& block_idx, const _dim3gd& grid_dim) {
size_t offset = 0;
if (Z_BLOCK)
offset = offset * grid_dim.z + block_idx.z;
if (Y_BLOCK)
offset = offset * grid_dim.y + block_idx.y;
if (X_BLOCK)
offset = offset * grid_dim.x + block_idx.x;
return offset;
}
// Returns dim3 of each reduction block.
template <bool X_THREAD, bool Y_THREAD, bool Z_THREAD, typename _dim3>
__device__ dim3 dimension_of_reduction_block(const _dim3& block_dim) {
return dim3{
X_THREAD ? (unsigned)block_dim.x : 1U,
Y_THREAD ? (unsigned)block_dim.y : 1U,
Z_THREAD ? (unsigned)block_dim.z : 1U};
}
// Returns the number of threads of each reduction block.
template <bool X_THREAD, bool Y_THREAD, bool Z_THREAD, typename _dim3>
__device__ int size_of_reduction_block(const _dim3& block_dim) {
auto tmp_dim =
dimension_of_reduction_block<X_THREAD, Y_THREAD, Z_THREAD>(block_dim);
return isize(tmp_dim);
}
// Returns the linear offset of a thread in a reduction block.
template <
bool X_THREAD,
bool Y_THREAD,
bool Z_THREAD,
typename _dim3ti,
typename _dim3bd>
__device__ int offset_in_reduction_block(
const _dim3ti& thread_idx,
const _dim3bd& block_dim) {
int offset = 0;
if (Z_THREAD)
offset += thread_idx.z;
if (Y_THREAD)
offset = offset * block_dim.y + thread_idx.y;
if (X_THREAD)
offset = offset * block_dim.x + thread_idx.x;
return offset;
}
// Reduces all the reduction blocks in each reduction segment.
//
// This is only used by one thread block per reduction segment. The input
// reduction blocks of the segment are stored in an intermediate buffer pointed
// by parameter in. Template parameters X/Y/Z_THREAD denote how the reduction
// block is formed.
//
// The size of a reduction block is by definition smaller or equal to the size
// of a thread block. We use the remaining threads to parallelize reductions
// across reduction blocks. For example, when X/Y/Z_THREAD = {true, false,
// false}, we use blockDim.y*blockDim.z threads for each output value. This is
// done first by loading the input values in parallel and then by reducing
// across threads of dimensions whose XYZ_THREAD are false.
//
// Note that what is done here after the loading from global memory is similar
// to what the existing blockReduce function does. The main difference is that
// the logical block to reduce is a 2D domain where the leading dimension is the
// size of a reduction block and the second dimension is the remaining factor in
// each thread block. For example, when X/Y/Z_THREAD = {false, true, false}, the
// threads are arranged as (blockDim.y, blockDim.x*blockDim.z). We do not reduce
// along the first dimension but only the second dimension. So, it is possible
// to reuse the existing blockReduce with dim3{blockDim.y,
// blockDim.x*blockDim.z} instead of blockDim and with X_THREAD and Y_THREAD
// being false and true, respectively. Also, it still need to shuffle the final
// output values to their actual corresponding threads. In the case of when
// X/Y/Z_THREAD = {false, true, false}, after the intra-block reduction, the
// final results will still be held by the first blockDim.y threads, which need
// to be transferred to threads at threadIdx.x == 0 and threadIdx.z == 0.
template <
bool X_THREAD,
bool Y_THREAD,
bool Z_THREAD,
typename T,
typename Func>
__device__ void gridReduceLastBlock(
T& out,
const T* in,
const size_t in_size,
Func reduction_op,
T* shared_buf,
bool read_write_pred,
T init_val) {
const int tid = ioffset(threadIdx, blockDim);
const int block_size = isize(blockDim);
const int rblock_size =
size_of_reduction_block<X_THREAD, Y_THREAD, Z_THREAD>(blockDim);
T inp = init_val;
if (tid < in_size) {
inp = in[tid];
}
for (size_t i = tid + block_size; i < in_size; i += block_size) {
reduction_op(inp, in[i]);
}
const auto should_write = (X_THREAD || threadIdx.x == 0) &&
(Y_THREAD || threadIdx.y == 0) && (Z_THREAD || threadIdx.z == 0);
auto rem_size = block_size / rblock_size;
if (rem_size > 1) {
const int rblock_offset = tid % rblock_size;
const int rblock_idx = tid / rblock_size;
blockReduce<false, true, false>(
inp,
inp,
reduction_op,
dim3{(unsigned)rblock_offset, (unsigned)rblock_idx, 0},
dim3{(unsigned)rblock_size, (unsigned)rem_size},
shared_buf,
true,
init_val);
__syncthreads();
if (tid < rblock_size) {
shared_buf[tid] = inp;
}
__syncthreads();
if (should_write) {
inp = shared_buf[offset_in_reduction_block<X_THREAD, Y_THREAD, Z_THREAD>(
threadIdx, blockDim)];
}
}
if (should_write && read_write_pred) {
out = inp;
}
}
// Reduces per-thread values across thread blocks.
//
// Function parameters:
// - out: Per-thread output location
// - inp_val: Per-thread input value
// - reduction_op: Scalar reduction function
// - work_buf: Temporary buffer for cross-block reductions
// - sync_flags: A vector of integers for synchronizations
// - shared_buf: Shared memory buffer for intra-block reduction
//
// Return true when the thread block has the valid result.
//
// Template parameters:
// - X/Y/Z_BLOCK: When true, reduces across thread blocks along the X/Y/Z
// dimensions
// - X/Y/Z_THREAD: When true, all threads along the X/Y/Z dimensions participate
// in the cross-block reduction. Otherwise, only threads at offset 0 do.
// - T: Scalar data type of input/output data
// - Func: Type of scalara reduction function
//
// Template parameters X/Y/Z_BLOCK define a group of thread blocks that are
// reduced together. We call it a reduction segment. Some examples are:
//
// Case 1: X/Y/Z_BLOCK == true/true/true -> There is only one segment, which
// includes all thread blocks. It is effecively the same as the grid.
//
// Case 2: X/Y/Z_BLOCK == false/false/false -> Each thread block comprises an
// individual segment by itself.
//
// Case 3: X/Y/Z_BLOCK == true/false/false -> Each segment contains thread
// blocks that have the same blockDim.x. There will be blockDim.y*blockDim.z
// such segments.
//
// X/Y/Z_THREAD defines a sub region of a thread block that should be reduced
// with the sub regions of other thread blocks. We call it a reduction block.
// E.g.,
//
// Case 1: X/Y/Z_THREAD == false/false/false -> Only thread 0 participates in
// the cross-block reductions. The reduction block is 1x1x1 with thread 0.
//
// Case 2: X/Y/Z_THREAD == true/true/true-> All threads in a thread block
// participate in the cross-block reductions. The reduction block in this case
// is equivalent to the thread block.
//
// After the function completes, only one thread block per reduction segment
// gets valid reduction results. There is no guarantee which particular block
// gets the final results.
//
template <
bool X_BLOCK,
bool Y_BLOCK,
bool Z_BLOCK,
bool X_THREAD,
bool Y_THREAD,
bool Z_THREAD,
typename T,
typename Func>
__device__ bool gridReduce(
T& out,
T inp_val,
Func reduction_op,
volatile T* work_buf,
Tensor<int64_t, 1> sync_flags,
T* shared_buf,
bool read_write_pred,
T init_val) {
// Number of values to reduce in the grid dimensions
const auto seg_size =
size_of_reduction_segment<X_BLOCK, Y_BLOCK, Z_BLOCK>(gridDim);
// Index of the reduction we're performing out of the seg_size
const auto seg_idx =
index_of_reduction_segment<X_BLOCK, Y_BLOCK, Z_BLOCK>(blockIdx, gridDim);
// Number of threads we can use in final reduction, Seems to assume all
// threads in the block participate
const auto rblock_size =
size_of_reduction_block<X_THREAD, Y_THREAD, Z_THREAD>(blockDim);
// advance to the offset for this segment
// index of reduction * size of the reduction * size of threads
work_buf += seg_idx * seg_size * rblock_size;
if ((X_THREAD || threadIdx.x == 0) && (Y_THREAD || threadIdx.y == 0) &&
(Z_THREAD || threadIdx.z == 0)) {
auto rblock_offset = offset_in_reduction_segment<X_BLOCK, Y_BLOCK, Z_BLOCK>(
blockIdx, gridDim);
auto thread_offset =
offset_in_reduction_block<X_THREAD, Y_THREAD, Z_THREAD>(
threadIdx, blockDim);
auto work_buf_offset = rblock_size * rblock_offset + thread_offset;
if (read_write_pred) {
work_buf[work_buf_offset] = inp_val;
} else {
work_buf[work_buf_offset] = init_val;
}
}
__syncthreads();
__shared__ bool last_block;
if (threadIdx.x == 0 && threadIdx.y == 0 && threadIdx.z == 0) {
__threadfence();
// printf("%ld\n", sync_flags[seg_idx]);
auto old = (int64_t)atomicAdd((unsigned long long*)&sync_flags[seg_idx], 1);
last_block = old + 1 == seg_size;
// printf("Last_block = %d + 1 == %d\n", (int)old, (int)seg_size);
}
__syncthreads();
if (last_block) {
// printf("Last block %d %d %d %d\n", blockIdx.x, blockIdx.y, blockIdx.z);
// final reduction
gridReduceLastBlock<X_THREAD, Y_THREAD, Z_THREAD>(
out,
(T*)work_buf,
seg_size * rblock_size,
reduction_op,
shared_buf,
read_write_pred,
init_val);
return true;
} else {
// printf("Not last block %d %d %d\n", blockIdx.x, blockIdx.y, blockIdx.z);
return false;
}
}
} // namespace reduction
)";
} // namespace nvfuser_resources
| [
"46971018+Ajblast@users.noreply.github.com"
] | 46971018+Ajblast@users.noreply.github.com |
50ce1362bf441a420469de87853c389deb4baa06 | b0f2c26360815e94da1aad9b931174be6019f2f2 | /pasha/lect_17/reg_expression/main.cpp | 34c8724445ea02458e8d6d422b39fce96813a6b9 | [] | no_license | tarstars/prog_course_2013 | aa2c1f21a06db40cd6fa84622a9f5fb29578dda5 | 60caba18ef418fe97e8d69e831864732a24fdd71 | refs/heads/master | 2020-05-17T12:44:06.451902 | 2013-12-17T10:52:03 | 2013-12-17T10:52:03 | 8,088,769 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 958 | cpp | #include <iostream>
#include <QRegExp>
#include <QImage>
using namespace std;
int main(int, char **) {
QRegExp reCircle("circle\\((\\-?[0-9]+),(\\-?[0-9]+)\\),([0-9]+)");
QRegExp reLine("line\\(([0-9]+),([0-9]+)\\)\\-\\(([0-9]+),([0-9]+)\\)");
QRegExp reCls("cls");
int n = 800;
QImage img(n, n, QImage::Format_ARGB32_Premultiplied);
string command;
while(getline(cin, command)) {
if (reCircle.exactMatch(QString::fromStdString(command))) {
int cx = reCircle.cap(1).toInt();
int cy = reCircle.cap(2).toInt();
int cr = reCircle.cap(3).toInt();
cout << "circle with x = " << cx << " y = " << cy << " r = " << cr << endl;
for(int p = 0; p < n; ++p) {
for(int q = 0; q < n; ++q) {
int dx = cx - q;
int dy = cy - p;
if (dx * dx + dy * dy < cr * cr) {
img.setPixel(q, p, qRgb(0,255,0));
}
}
}
} else {
cout << "no match" << endl;
}
}
img.save("a.png");
return 0;
}
| [
"nikitin.pavel.a@gmail.com"
] | nikitin.pavel.a@gmail.com |
1317f73678771bc2df6a5a0e04b762c5a5f56f3a | 4dbfab72ec685805d94c95fb2fefc3525011caa2 | /compiler_optimizations/copy_elision__initialization_with_temporary_variable.cpp | de4d0a2b78fb0c433417afafa495dbeacce80e20 | [] | no_license | init931/yandex.praktikum | 53dc83d3e2a442c43e1e9f8f88abadc06c37aa55 | 454616cbc490990034157c65dfd585b9c62ef7bb | refs/heads/main | 2023-08-05T03:31:06.759141 | 2021-09-15T10:02:48 | 2021-09-15T10:02:48 | 357,801,199 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,666 | cpp | #include <iostream>
#include <string>
using namespace std;
// класс кота Шрёдингера
class SchrodingerCat {
private:
string color_;
public:
SchrodingerCat() : color_("black"s) {
cout << "Default Ctor cat"s << endl;
}
SchrodingerCat(const SchrodingerCat& other)
: color_(other.color_)
{
cout << "Copy Ctor cat"s << endl;
}
~SchrodingerCat() {
cout << "Dtor cat"s << endl;
}
};
// класс Коробки
class Box {
private:
bool is_empty_;
SchrodingerCat cat_;
public:
Box() : cat_({}), is_empty_(false) {
cout << "Default Ctor box"s << endl;
}
~Box() {
cout << "Dtor box"s << endl;
}
// кота из коробки можно вытащить
SchrodingerCat GetCat() {
is_empty_ = true;
cout << "GetCat box"s << endl;
return cat_;
}
bool HasCat() {
cout << "HasCat box"s << endl;
return !is_empty_;
}
};
int main() {
Box black_box = {};
if (black_box.HasCat()) {
SchrodingerCat fluffy = black_box.GetCat();
cout << "end if"s << endl;
}
cout << "end main"s << endl;
return 0;
}
/*
(pytorch4) test$ ./a.out
Default Ctor cat
Default Ctor box
HasCat box
GetCat box
Copy Ctor cat
end if
Dtor cat
end main
Dtor box
Dtor cat
(pytorch4) test$ g++ -fno-elide-constructors test_cat.cpp
(pytorch4) villedepommes@devfair044:/scratch/villedepommes/github/pytorch4/test$ ./a.out
Default Ctor cat
Copy Ctor cat
Dtor cat
Default Ctor box
HasCat box
GetCat box
Copy Ctor cat
Copy Ctor cat
Dtor cat
end if
Dtor cat
end main
Dtor box
Dtor cat
*/ | [
"friendskenny72@gmail.com"
] | friendskenny72@gmail.com |
58f49af56745f7fadd6dea66251948f3e08633f3 | 8e2e2996ca91988e4c2e65e1ded8ff08952ab4ad | /src/MoviePriceType.h | bf34138b3937bb84dfa5be96c6c4990153376b2d | [] | no_license | GEN-BGroupeD/Labo5 | 77604e2d71d096afd411fd739e3778b4dba502d5 | c45cf1befa83621568b4c8c0d97b6898b1ba9222 | refs/heads/master | 2022-11-08T10:50:15.171530 | 2020-06-21T10:00:01 | 2020-06-21T10:00:01 | 272,814,521 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 357 | h | #ifndef MOVIEPRICETYPE_H
#define MOVIEPRICETYPE_H
class MoviePriceType {
public:
explicit MoviePriceType(double price) : price(price) {}
virtual double getPrice(double daysRented) = 0;
virtual int getBonus(){
return 0;
}
virtual ~MoviePriceType() = default;
protected:
const double price;
};
#endif //MOVIEPRICETYPE_H
| [
"helene.dubuis@heig-vd.ch"
] | helene.dubuis@heig-vd.ch |
4e0704eaeea9a7843426775a42f1b0ef399e2a4a | 97eb00d7b35076b1efce57b21ad51636ac2a920c | /ABC/162/d.cpp | 8f73a46f29c2d9ab5830ac7000a7cf39dc005205 | [] | no_license | jimjin73/compro | 43199716dc857f52c10d3237908e70c1801e7fb4 | b194b4414752fff3debc838f4ee70af8e2e43f34 | refs/heads/master | 2021-05-18T01:02:39.338377 | 2020-08-06T12:25:20 | 2020-08-06T12:25:20 | 251,037,702 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,078 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll N;
string s;
vector<ll> v[3];
int main(){
cin >> N;
cin >> s;
for(int i=0;i<N;i++){
if(s[i] == 'R') v[0].push_back(i);
if(s[i] == 'G') v[1].push_back(i);
if(s[i] == 'B') v[2].push_back(i);
}
ll sum = 0;
for(int i=0;i<N;i++){
for(int j=i+1;j<N;j++){
if(s[i] == s[j]) continue;
ll diff = j - i;
ll index = -1;
if((s[i] == 'R' || s[i] == 'G') && (s[j] == 'R' || s[j] == 'G')){
index = 2;
}
if((s[i] == 'R' || s[i] == 'B') && (s[j] == 'R' || s[j] == 'B')){
index = 1;
}
if((s[i] == 'B' || s[i] == 'G') && (s[j] == 'B' || s[j] == 'G')){
index = 0;
}
auto itr = upper_bound(v[index].begin(),v[index].end(),j);
sum += v[index].end() - itr;
if(binary_search(v[index].begin(),v[index].end(),j + diff)) sum--;
}
}
cout << sum << endl;
return 0;
} | [
"j.kam.j.kan.w.jmj@gmail.com"
] | j.kam.j.kan.w.jmj@gmail.com |
21b1a6a06a9745bf40c4feb2a30da1148d55f4e3 | 8903cb76cedac12995249e2e613af65365be7cf2 | /ares/n64/controller/gamepad/gamepad.cpp | 4b33563b8620b4c637287bb886f442f65437a0fe | [
"ISC"
] | permissive | kirwinia/ares-emu-v121 | 0c1e21e073f291741406cd1ed01acca43acd56d7 | 722aa227caf943a4a64f1678c1bdd07b38b15caa | refs/heads/main | 2023-06-09T15:28:23.665934 | 2021-06-28T06:10:46 | 2021-06-28T06:10:46 | 380,923,321 | 0 | 0 | ISC | 2021-06-28T06:05:04 | 2021-06-28T06:05:04 | null | UTF-8 | C++ | false | false | 6,300 | cpp | Gamepad::Gamepad(Node::Port parent) {
node = parent->append<Node::Peripheral>("Gamepad");
port = node->append<Node::Port>("Pak");
port->setFamily("Nintendo 64");
port->setType("Pak");
port->setHotSwappable(true);
port->setAllocate([&](auto name) { return allocate(name); });
port->setConnect([&] { return connect(); });
port->setDisconnect([&] { return disconnect(); });
port->setSupported({"Controller Pak", "Rumble Pak"});
x = node->append<Node::Input::Axis> ("X-Axis");
y = node->append<Node::Input::Axis> ("Y-Axis");
up = node->append<Node::Input::Button>("Up");
down = node->append<Node::Input::Button>("Down");
left = node->append<Node::Input::Button>("Left");
right = node->append<Node::Input::Button>("Right");
b = node->append<Node::Input::Button>("B");
a = node->append<Node::Input::Button>("A");
cameraUp = node->append<Node::Input::Button>("C-Up");
cameraDown = node->append<Node::Input::Button>("C-Down");
cameraLeft = node->append<Node::Input::Button>("C-Left");
cameraRight = node->append<Node::Input::Button>("C-Right");
l = node->append<Node::Input::Button>("L");
r = node->append<Node::Input::Button>("R");
z = node->append<Node::Input::Button>("Z");
start = node->append<Node::Input::Button>("Start");
}
Gamepad::~Gamepad() {
disconnect();
}
auto Gamepad::save() -> void {
if(!slot) return;
if(slot->name() == "Controller Pak") {
ram.save(pak->write("save.pak"));
}
}
auto Gamepad::allocate(string name) -> Node::Peripheral {
if(name == "Controller Pak") return slot = port->append<Node::Peripheral>("Controller Pak");
if(name == "Rumble Pak" ) return slot = port->append<Node::Peripheral>("Rumble Pak");
return {};
}
auto Gamepad::connect() -> void {
if(!slot) return;
if(slot->name() == "Controller Pak") {
node->setPak(pak = platform->pak(node));
ram.allocate(32_KiB);
formatControllerPak();
if(auto fp = pak->read("save.pak")) {
if(fp->attribute("loaded").boolean()) {
ram.load(pak->read("save.pak"));
}
}
}
if(slot->name() == "Rumble Pak") {
motor = node->append<Node::Input::Rumble>("Rumble");
}
}
auto Gamepad::disconnect() -> void {
if(!slot) return;
if(slot->name() == "Controller Pak") {
save();
ram.reset();
}
if(slot->name() == "Rumble Pak") {
rumble(false);
node->remove(motor);
motor.reset();
}
port->remove(slot);
slot.reset();
}
auto Gamepad::rumble(bool enable) -> void {
if(!motor) return;
motor->setEnable(enable);
platform->input(motor);
}
auto Gamepad::read() -> n32 {
platform->input(x);
platform->input(y);
platform->input(up);
platform->input(down);
platform->input(left);
platform->input(right);
platform->input(b);
platform->input(a);
platform->input(cameraUp);
platform->input(cameraDown);
platform->input(cameraLeft);
platform->input(cameraRight);
platform->input(l);
platform->input(r);
platform->input(z);
platform->input(start);
//scale {-32768 ... +32767} to {-84 ... +84}
auto ax = x->value() * 85.0 / 32767.0;
auto ay = y->value() * 85.0 / 32767.0;
//create scaled circular dead-zone in range {-15 ... +15}
auto length = sqrt(ax * ax + ay * ay);
if(length < 16.0) {
length = 0.0;
} else if(length > 85.0) {
length = 85.0 / length;
} else {
length = (length - 16.0) * 85.0 / 69.0 / length;
}
ax *= length;
ay *= length;
//bound diagonals to an octagonal range {-68 ... +68}
if(ax != 0.0 && ay != 0.0) {
auto slope = ay / ax;
auto edgex = copysign(85.0 / (abs(slope) + 16.0 / 69.0), ax);
auto edgey = copysign(min(abs(edgex * slope), 85.0 / (1.0 / abs(slope) + 16.0 / 69.0)), ay);
edgex = edgey / slope;
auto scale = sqrt(edgex * edgex + edgey * edgey) / 85.0;
ax *= scale;
ay *= scale;
}
n32 data;
data.byte(0) = -ay;
data.byte(1) = +ax;
data.bit(16) = cameraRight->value();
data.bit(17) = cameraLeft->value();
data.bit(18) = cameraDown->value();
data.bit(19) = cameraUp->value();
data.bit(20) = r->value();
data.bit(21) = l->value();
data.bit(22) = 0; //GND
data.bit(23) = 0; //RST
data.bit(24) = right->value() & !left->value();
data.bit(25) = left->value() & !right->value();
data.bit(26) = down->value() & !up->value();
data.bit(27) = up->value() & !down->value();
data.bit(28) = start->value();
data.bit(29) = z->value();
data.bit(30) = b->value();
data.bit(31) = a->value();
//when L+R+Start are pressed: the X/Y axes are zeroed, RST is set, and Start is cleared
if(l->value() && r->value() && start->value()) {
data.byte(0) = 0; //Y-Axis
data.byte(1) = 0; //X-Axis
data.bit(23) = 1; //RST
data.bit(28) = 0; //Start
}
return data;
}
//controller paks contain 32KB of SRAM split into 128 pages of 256 bytes each.
//the first 5 pages are for storing system data, and the remaining 123 for game data.
auto Gamepad::formatControllerPak() -> void {
ram.fill(0x00);
//page 0 (system area)
n6 fieldA = random();
n19 fieldB = random();
n27 fieldC = random();
for(u32 area : array<u8[4]>{1,3,4,6}) {
ram.write<Byte>(area * 0x20 + 0x01, fieldA); //unknown
ram.write<Word>(area * 0x20 + 0x04, fieldB); //serial# hi
ram.write<Word>(area * 0x20 + 0x08, fieldC); //serial# lo
ram.write<Half>(area * 0x20 + 0x18, 0x0001); //device ID
ram.write<Byte>(area * 0x20 + 0x1a, 0x01); //banks (0x01 = 32KB)
ram.write<Byte>(area * 0x20 + 0x1b, 0x00); //version#
u16 checksum = 0;
u16 inverted = 0;
for(u32 half : range(14)) {
u16 data = ram.read<Half>(area * 0x20 + half * 2);
checksum += data;
inverted += ~data;
}
ram.write<Half>(area * 0x20 + 0x1c, checksum);
ram.write<Half>(area * 0x20 + 0x1e, inverted);
}
//pages 1+2 (inode table)
for(u32 page : array<u8[2]>{1,2}) {
ram.write<Byte>(0x100 * page + 0x01, 0x71); //unknown
for(u32 slot : range(5,128)) {
ram.write<Byte>(0x100 * page + slot * 2 + 0x01, 0x03); //0x01 = stop, 0x03 = empty
}
}
//pages 3+4 (note table)
//pages 5-127 (game saves)
}
auto Gamepad::serialize(serializer& s) -> void {
s(ram);
rumble(false);
}
| [
"ecallaghan@protonmail.com"
] | ecallaghan@protonmail.com |
a1acf14ea89349a7685ab8ea39532fd9a0dc372e | 5b1b25a0c1fbb384064cbb0500e7b74926111fe0 | /ZeroNetServer/zeroserver.h | 6bfb24f945835d33692ba7b00f661a5201aa9a5a | [] | no_license | Yuanyiis/ZeroNet | 9f0c1e92b09dfe07e545dc4203014602e15e3c64 | 763c5f2774628e0bb74c5d74d4e08549c788731a | refs/heads/master | 2021-04-30T10:03:08.319246 | 2018-01-21T03:50:32 | 2018-01-21T03:50:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,220 | h | /*
* Author: 752049643@qq.com
* Date: 2017-12-24
* Brief: Zero远控主要服务端
*
*/
#ifndef ZEROSERVER_H
#define ZEROSERVER_H
#include <QObject>
#include "TcpServer.h"
#include "ZeroClient.h"
#include <QHash>
class ZeroServer : public QObject
{
Q_OBJECT
public:
explicit ZeroServer(QObject *parent = 0);
// 启动或停止服务端
void start(int port);
void stop();
// 用id来获取ZeroClient
ZeroClient *client(int id) {
return mClients[id];
}
TcpServer *server() {
return mServer;
}
private:
TcpServer *mServer; // Tcp服务端
QHash<int, ZeroClient*> mClients; // 用ID来索引相应的客户
// 生成新的id
int generateId();
signals:
// 客户登入或登出,主要是告诉窗口控件
void clientLogin(int id, QString userName,
QString ip,int port, QString system);
void clientLogout(int id);
public slots:
// 新客户连接
void newConnection(QTcpSocket *sock);
// 客户登入
void login(ZeroClient*, QString userName,
QString ip, int port, QString system);
// 客户登出
void logout(int id);
};
#endif // ZEROSERVER_H
| [
"zhjf1996@163.com"
] | zhjf1996@163.com |
a7fd1c7d655189dd8e7b8892ea08b5853da16664 | 7844379f018944f9be77cc213a8985372eff0848 | /src/saiga/core/image/png_wrapper.cpp | 7d7acaeb1e2d3341c3e316dea327af241618ca90 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | muetimueti/saiga | 344306e2340f4668b9fece1e3d0d934cd189feb2 | 32b54a8fc7b1251368e07e7d31c15ac90cee3b32 | refs/heads/master | 2020-07-31T12:42:29.096235 | 2019-09-25T16:50:09 | 2019-09-25T16:50:09 | 210,607,609 | 0 | 0 | MIT | 2019-09-24T13:17:44 | 2019-09-24T13:17:38 | null | UTF-8 | C++ | false | false | 14,662 | cpp | /**
* Copyright (c) 2017 Darius Rückert
* Licensed under the MIT License.
* See LICENSE file for more information.
*/
#include "png_wrapper.h"
#include "saiga/core/util/assert.h"
#include <cstring> // for memcpy
#include <iostream>
#ifdef SAIGA_USE_PNG
# include "internal/noGraphicsAPI.h"
# include <png.h>
namespace Saiga
{
namespace PNG
{
struct PNGLoadStore
{
// temp variables for libpng. Don't modify them!!!
uchar** row_pointers;
void* png_ptr;
void* info_ptr;
FILE* infile;
FILE* outfile;
jmp_buf jmpbuf;
};
static void writepng_error_handler(png_structp png_ptr, png_const_charp msg)
{
PNGLoadStore* image;
/* This function, aside from the extra step of retrieving the "error
* pointer" (below) and the fact that it exists within the application
* rather than within libpng, is essentially identical to libpng's
* default error handler. The second point is critical: since both
* setjmp() and longjmp() are called from the same code, they are
* guaranteed to have compatible notions of how big a jmp_buf is,
* regardless of whether _BSD_SOURCE or anything else has (or has not)
* been defined. */
fprintf(stderr, "writepng libpng error: %s\n", msg);
fflush(stderr);
image = static_cast<PNGLoadStore*>(png_get_error_ptr(png_ptr));
if (image == NULL)
{ /* we are completely hosed now */
fprintf(stderr, "writepng severe error: jmpbuf not recoverable; terminating.\n");
fflush(stderr);
SAIGA_ASSERT(0);
}
longjmp(image->jmpbuf, 1);
}
bool readPNG(PngImage* img, const std::string& path, bool invertY)
{
PNGLoadStore pngls;
png_structp png_ptr;
png_infop info_ptr;
unsigned int sig_read = 0;
int interlace_type;
if ((pngls.infile = fopen(path.c_str(), "rb")) == NULL) return false;
/* Create and initialize the png_struct
* with the desired error handler
* functions. If you want to use the
* default stderr and longjump method,
* you can supply NULL for the last
* three parameters. We also supply the
* the compiler header file version, so
* that we know if the application
* was compiled with a compatible version
* of the library. REQUIRED
*/
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (png_ptr == NULL)
{
fclose(pngls.infile);
return false;
}
/* Allocate/initialize the memory
* for image information. REQUIRED. */
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL)
{
fclose(pngls.infile);
png_destroy_read_struct(&png_ptr, NULL, NULL);
return false;
}
/* Set error handling if you are
* using the setjmp/longjmp method
* (this is the normal method of
* doing things with libpng).
* REQUIRED unless you set up
* your own error handlers in
* the png_create_read_struct()
* earlier.
*/
if (setjmp(png_jmpbuf(png_ptr)))
{
/* Free all of the memory associated
* with the png_ptr and info_ptr */
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
fclose(pngls.infile);
/* If we get here, we had a
* problem reading the file */
return false;
}
/* Set up the output control if
* you are using standard C streams */
png_init_io(png_ptr, pngls.infile);
/* If we have already
* read some of the signature */
png_set_sig_bytes(png_ptr, sig_read);
/*
* If you have enough memory to read
* in the entire image at once, and
* you need to specify only
* transforms that can be controlled
* with one of the PNG_TRANSFORM_*
* bits (this presently excludes
* dithering, filling, setting
* background, and doing gamma
* adjustment), then you can read the
* entire image (including pixels)
* into the info structure with this
* call
*
* PNG_TRANSFORM_STRIP_16 |
* PNG_TRANSFORM_PACKING forces 8 bit
* PNG_TRANSFORM_EXPAND forces to
* expand a palette into RGB
*/
png_read_png(png_ptr, info_ptr,
// PNG_TRANSFORM_STRIP_16 | //Strip 16-bit samples to 8 bits
PNG_TRANSFORM_SWAP_ENDIAN | // png byte order is big endian!
PNG_TRANSFORM_PACKING | // Expand 1, 2 and 4-bit samples to bytes
PNG_TRANSFORM_EXPAND // Perform set_expand()
,
NULL);
png_uint_32 pw, ph;
png_get_IHDR(png_ptr, info_ptr, &pw, &ph, &img->bit_depth, &img->color_type, &interlace_type, NULL, NULL);
SAIGA_ASSERT(interlace_type == PNG_INTERLACE_NONE);
img->width = pw;
img->height = ph;
unsigned int row_bytes = png_get_rowbytes(png_ptr, info_ptr);
// we want to row-align the image in our output data
int rowPadding = (img->rowAlignment - (row_bytes % img->rowAlignment)) % img->rowAlignment;
img->bytesPerRow = row_bytes + rowPadding;
img->data.resize(img->bytesPerRow * img->height);
png_bytepp row_pointers = png_get_rows(png_ptr, info_ptr);
if (invertY)
{
for (unsigned int i = 0; i < img->height; i++)
{
memcpy(img->data.data() + (img->bytesPerRow * (img->height - 1 - i)), row_pointers[i], row_bytes);
}
}
else
{
for (unsigned int i = 0; i < img->height; i++)
{
memcpy(img->data.data() + (img->bytesPerRow * i), row_pointers[i], row_bytes);
}
}
/* Clean up after the read,
* and free any memory allocated */
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
/* Close the file */
fclose(pngls.infile);
/* That's it */
return true;
}
/* returns 0 for success, 2 for libpng problem, 4 for out of memory, 11 for
* unexpected pnmtype; note that outfile might be stdout */
static int writepng_init(const Image& img, PNGLoadStore* pngls)
{
png_structp png_ptr; /* note: temporary variables! */
png_infop info_ptr;
int interlace_type;
/* could also replace libpng warning-handler (final NULL), but no need: */
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, writepng_error_handler, NULL);
if (!png_ptr) return 4; /* out of memory */
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr)
{
png_destroy_write_struct(&png_ptr, NULL);
return 4; /* out of memory */
}
/* setjmp() must be called in every function that calls a PNG-writing
* libpng function, unless an alternate error handler was installed--
* but compatible error handlers must either use longjmp() themselves
* (as in this program) or exit immediately, so here we go: */
if (setjmp(pngls->jmpbuf))
{
png_destroy_write_struct(&png_ptr, &info_ptr);
return 2;
}
/* make sure outfile is (re)opened in BINARY mode */
png_init_io(png_ptr, pngls->outfile);
/* set the compression levels--in general, always want to leave filtering
* turned on (except for palette images) and allow all of the filters,
* which is the default; want 32K zlib window, unless entire image buffer
* is 16K or smaller (unknown here)--also the default; usually want max
* compression (NOT the default); and remaining compression flags should
* be left alone */
// png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
/*
>> this is default for no filtering; Z_FILTERED is default otherwise:
png_set_compression_strategy(png_ptr, Z_DEFAULT_STRATEGY);
>> these are all defaults:
png_set_compression_mem_level(png_ptr, 8);
png_set_compression_window_bits(png_ptr, 15);
png_set_compression_method(png_ptr, 8);
*/
/* set the image parameters appropriately */
interlace_type = PNG_INTERLACE_NONE; // PNG_INTERLACE_ADAM7
int bit_depth = bitsPerChannel(img.type);
int color_type = 0;
switch (channels(img.type))
{
case 1:
color_type = PNG_COLOR_TYPE_GRAY;
break;
case 2:
color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
break;
case 3:
color_type = PNG_COLOR_TYPE_RGB;
break;
case 4:
color_type = PNG_COLOR_TYPE_RGB_ALPHA;
break;
default:
SAIGA_ASSERT(0);
}
png_set_IHDR(png_ptr, info_ptr, img.width, img.height, bit_depth, color_type, interlace_type,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
// Higher is more compression
// PNG_TEXT_Z_DEFAULT_STRATEGY
png_set_compression_level(png_ptr, 1);
// One of the following
// PNG_FAST_FILTERS, PNG_FILTER_NONE, PNG_ALL_FILTERS
png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, PNG_FILTER_NONE);
/* write all chunks up to (but not including) first IDAT */
png_write_info(png_ptr, info_ptr);
/* if we wanted to write any more text info *after* the image data, we
* would set up text struct(s) here and call png_set_text() again, with
* just the new data; png_set_tIME() could also go here, but it would
* have no effect since we already called it above (only one tIME chunk
* allowed) */
/* set up the transformations: for now, just pack low-bit-depth pixels
* into bytes (one, two or four pixels per byte) */
png_set_packing(png_ptr);
/* png_set_shift(png_ptr, &sig_bit); to scale low-bit-depth values */
if (bit_depth == 16 || bit_depth == 32) png_set_swap(png_ptr);
// std::cout << "bit depth " << bit_depth << std::endl;
/* make sure we save our pointers for use in writepng_encode_image() */
pngls->png_ptr = png_ptr;
pngls->info_ptr = info_ptr;
SAIGA_ASSERT(pngls->png_ptr);
SAIGA_ASSERT(pngls->info_ptr);
return 0;
}
static void writepng_encode_image(const Image& img, PNGLoadStore* pngls, bool invertY)
{
png_structp png_ptr = (png_structp)pngls->png_ptr;
png_infop info_ptr = (png_infop)pngls->info_ptr;
for (int i = 0; i < img.height; i++)
{
auto j = invertY ? img.height - i - 1 : i;
auto offset = j * img.pitchBytes;
auto rowPtr = img.data8() + offset;
# if 0
std::vector<unsigned char> dataTest(img.pitchBytes);
for (auto c : img.colRange())
{
png_save_uint_16(dataTest.data() + c * sizeof(short), ((unsigned short*)rowPtr)[c]);
}
# endif
png_write_row(png_ptr, rowPtr);
// png_write_row(png_ptr, dataTest.data());
}
png_write_end(png_ptr, NULL);
png_destroy_write_struct(&png_ptr, &info_ptr);
}
# if 0
bool writePNG(PngImage *img, const std::string &path, bool invertY)
{
PNGLoadStore pngls;
FILE *fp = fopen(path.c_str(), "wb");
if (!fp)
{
std::cout << "could not open file: " << path.c_str() << std::endl;
return false;
}
pngls.outfile = fp;
if(writepng_init(img,&pngls)!=0)
{
std::cout<<"error write png init"<<std::endl;
}
writepng_encode_image(img,&pngls,invertY);
fclose(fp);
return true;
}
# endif
ImageType PngImage::saigaType() const
{
int channels = -1;
switch (color_type)
{
case PNG_COLOR_TYPE_GRAY:
channels = 1;
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
channels = 2;
break;
case PNG_COLOR_TYPE_RGB:
channels = 3;
break;
case PNG_COLOR_TYPE_RGB_ALPHA:
channels = 4;
break;
}
SAIGA_ASSERT(channels != -1);
ImageElementType elementType = IET_ELEMENT_UNKNOWN;
switch (bit_depth)
{
case 8:
elementType = IET_UCHAR;
break;
case 16:
elementType = IET_USHORT;
break;
case 32:
elementType = IET_UINT;
break;
}
SAIGA_ASSERT(elementType != IET_ELEMENT_UNKNOWN);
return getType(channels, elementType);
}
void PngImage::fromSaigaType(ImageType t)
{
switch (channels(t))
{
case 1:
color_type = PNG_COLOR_TYPE_GRAY;
break;
case 2:
color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
break;
case 3:
color_type = PNG_COLOR_TYPE_RGB;
break;
case 4:
color_type = PNG_COLOR_TYPE_RGB_ALPHA;
break;
default:
color_type = PNG_COLOR_TYPE_RGB;
SAIGA_ASSERT(0);
}
switch (elementType(t))
{
case IET_UCHAR:
bit_depth = 8;
break;
case IET_USHORT:
bit_depth = 16;
break;
case IET_UINT:
bit_depth = 32;
break;
default:
bit_depth = 0;
SAIGA_ASSERT(0);
}
}
void convert(PNG::PngImage& src, Image& dest)
{
dest.width = src.width;
dest.height = src.height;
dest.type = src.saigaType();
dest.create();
for (int i = 0; i < dest.rows; ++i)
{
memcpy(dest.rowPtr(i), src.rowPtr(i), std::min(dest.pitchBytes, src.bytesPerRow));
}
}
void convert(Image& src, PNG::PngImage& dest)
{
dest.width = src.width;
dest.height = src.height;
dest.fromSaigaType(src.type);
// The rows must be 4-aligned
SAIGA_ASSERT(src.pitchBytes % 4 == 0);
dest.bytesPerRow = iAlignUp(elementSize(src.type) * src.width, 4);
// dest.data.resize(dest.bytesPerRow * src.height);
dest.data2 = src.data8();
for (int i = 0; i < src.rows; ++i)
{
// memcpy(dest.rowPtr(i),src.rowPtr(i), std::min(src.pitchBytes,dest.bytesPerRow));
}
}
bool save(const Image& img, const std::string& path, bool invertY)
{
// PNG::PngImage pngimg;
// PNG::convert(img,pngimg);
// return PNG::writePNG(&pngimg,path,invertY);
PNGLoadStore pngls;
FILE* fp = fopen(path.c_str(), "wb");
if (!fp)
{
std::cout << "could not open file: " << path.c_str() << std::endl;
return false;
}
pngls.outfile = fp;
if (writepng_init(img, &pngls) != 0)
{
std::cout << "error write png init" << std::endl;
}
writepng_encode_image(img, &pngls, invertY);
fclose(fp);
return true;
}
bool load(Image& img, const std::string& path, bool invertY)
{
PNG::PngImage pngimg;
bool erg = PNG::readPNG(&pngimg, path, invertY);
if (erg) PNG::convert(pngimg, img);
return erg;
}
} // namespace PNG
} // namespace Saiga
#endif
| [
"darius.rueckert@fau.de"
] | darius.rueckert@fau.de |
68fd5121b0bec95d4c52f4c809fb5587905e0b82 | fca68c5fec6df6f999408571315c2b8e7c4b8ce9 | /service/supersialign_home/src/Suez/SuezMain.cc | b1a3b9837e382bdeb4293afdc5bd6bc40812a018 | [] | no_license | jpivarski-talks/1999-2006_gradschool-3 | 8b2ea0b6babef104b0281c069994fc9894a05b14 | 57e80d601c0519f9e01a07ecb53d367846e8306e | refs/heads/master | 2022-11-19T12:01:42.959599 | 2020-07-25T01:19:59 | 2020-07-25T01:19:59 | 282,235,559 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,471 | cc | // -*- C++ -*-
//
// Package: Suez
// Module: SuezMain
//
// Description: The main "Main" in the Suez World
//
// Implimentation:
// <Notes on implimentation>
//
// Author: Martin Lohner
// Created: Thu Mar 20 15:13:11 EST 1997
// $Id: SuezMain.cc,v 1.67 2002/01/03 21:07:26 cdj Exp $
//
// Revision history (at end of file)
//
#include "Experiment/Experiment.h"
// system include files
#include <assert.h>
#include <fstream.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdexcept>
#if defined(XALLOC_NON_STANDARD_EXCEPTION_BUG)
#include <exception.h>
#endif
#if defined(STL_TEMPLATE_DEFAULT_PARAMS_FIRST_BUG)
#include <deque>
#include <map>
#endif
// user include files
#include "Suez/testBoolean.h"
#include "Suez/forceLinkStorageManagement.h"
#include "Experiment/report.h"
#include "DataHandler/FrameLogger.h"
#include "JobControl/JobControl.h"
#include "Suez/UserApplication.h"
#include "JobControl/ReportModule.h"
#include "Interpreter/TclInterpreter.h"
#include "Utility/StringTokenizer.h"
// signal handling
#include "Signal/SignalHandler.h"
#include "Signal/SIGINT_Handler.h"
// exceptions
#include "DAException/DAException.h"
// STL includes
#include <deque>
int TheMain( int argc, char** argv );
DABoolean SuezInit( Interpreter& interpreter,
const string& runFile = "",
DABoolean runSetupFile = false );
// typedefs, enums, constants
#include "Suez/externConst.h"
//static const char* const kFacilityString = "Suez.SuezMain";
static const char* const IdString
= "$Id: SuezMain.cc,v 1.67 2002/01/03 21:07:26 cdj Exp $";
static const char* const TagString
= "$Name: $";
static const char* const VersionString
= "$Version$";
static string welcomeMsg =
string( "// -----------------------------------------------------------\n" )+
string( "// Welcome to Suez, the CLEO III data access program \n" )+
string( "// -----------------------------------------------------------\n" );
//-----------------
// Main
//-----------------
int
main( int argc, char** argv )
{
// install SignalHandlers
DABoolean callExit;
SIGINT_Handler sigint_handler( callExit=true );
SignalHandler::instance()->registerHandler( SignalHandler::kSigInt,
&sigint_handler );
#ifndef CLEO_DEBUG
// catch all (uncaught) exceptions and print message
// catch first specific ones, then less specific
try {
#endif
TheMain( argc, argv );
#ifndef CLEO_DEBUG
}
// all specific logic_error exceptions
catch( length_error& thisException )
{
cerr << "ERROR: Suez caught \"length_error\" exception:\n\""
<< thisException.what() << "\"\n ... exiting program" << endl;
}
catch( domain_error& thisException )
{
cerr << "ERROR: Suez caught \"domain_error\" exception:\n\""
<< thisException.what() << "\"\n ... exiting program" << endl;
}
catch( out_of_range& thisException )
{
cerr << "ERROR: Suez caught \"out_of_range\" exception:\n\""
<< thisException.what() << "\"\n ... exiting program" << endl;
}
catch( invalid_argument& thisException )
{
cerr << "ERROR: Suez caught \"invalid_argument\" exception:\n\""
<< thisException.what() << "\"\n ... exiting program" << endl;
}
// now catch all other logic_error exceptions
catch( logic_error& thisException )
{
cerr << "ERROR: Suez caught \"logic_error\" exception:\n\""
<< thisException.what() << "\"\n ... exiting program" << endl;
}
// now all non-logic_error, non-runtime_error exceptions
#if !defined(UNDEF_BAD_ALLOC_EXCEPT_BUG)
catch( bad_alloc& thisException )
{
cerr << "ERROR: Suez caught \"bad_alloc\" exception:\n\""
<< thisException.what() << "\"\n ... exiting program" << endl;
}
#else
#if defined(XALLOC_NON_STANDARD_EXCEPTION_BUG)
catch( xalloc& thisException )
{
cerr << "ERROR: Suez caught \"xalloc\" exception:\n\""
<< thisException.why() << "\"\n ... exiting program" << endl;
}
#endif
#endif
#if !defined(UNDEF_BAD_EXCEPTION_EXCEPT_BUG)
catch( bad_exception& thisException )
{
cerr << "ERROR: Suez caught \"bad_exception\" exception:\n\""
<< thisException.what() << "\"\n ... exiting program" << endl;
}
#endif
#if !defined(UNDEF_IOS_BASE_FAILURE_EXCEPT_BUG)
catch( ios_base::failure& thisException )
{
cerr << "ERROR: Suez caught \"ios_base::failure\" exception:\n\""
<< thisException.what() << "\"\n ... exiting program" << endl;
}
#endif
#if !defined(UNDEF_BAD_TYPEID_EXCEPT_BUG)
catch( bad_typeid& thisException )
{
cerr << "ERROR: Suez caught \"bad_typeid\" exception:\n\""
<< thisException.what() << "\"\n ... exiting program" << endl;
}
#endif
#if !defined(UNDEF_BAD_CAST_EXCEPT_BUG)
catch( bad_cast& thisException )
{
cerr << "ERROR: Suez caught \"bad_cast\" exception:\n\""
<< thisException.what() << "\"\n ... exiting program" << endl;
}
#endif
// all specific runtime_error exceptions
#if !defined(UNDEF_UNDERFLOW_ERROR_EXCEPT_BUG)
catch( underflow_error& thisException )
{
cerr << "ERROR: Suez caught \"underflow_error\" exception:\n\""
<< thisException.what() << "\"\n ... exiting program" << endl;
}
#endif
#if !defined(UNDEF_OVERFLOW_ERROR_EXCEPT_BUG)
catch( overflow_error& thisException )
{
cerr << "ERROR: Suez caught \"overflow_error\" exception:\n\""
<< thisException.what() << "\"\n ... exiting program" << endl;
}
#endif
#if !defined(UNDEFINED_RANGE_ERROR_EXCEPT_BUG)
catch( range_error& thisException )
{
cerr << "ERROR: Suez caught \"range_error\" exception:\n\""
<< thisException.what() << "\"\n ... exiting program" << endl;
}
#endif
// now catch all other runtime_error exceptions
catch( runtime_error& thisException )
{
cerr << "ERROR: Suez caught \"runtime_error\" exception:\n\""
<< thisException.what() << "\"\n ... exiting program" << endl;
}
// now catch DAExceptions
catch( DAExceptionBase& thisException )
{
cerr << "ERROR: Suez caught a DAException:\n\""
<< thisException.what() << "\"\n ... exiting program" << endl;
}
// catch non-standard exceptions
#if defined(XALLOC_NON_STANDARD_EXCEPTION_BUG)
catch( xmsg& thisException )
{
cerr << "ERROR: Suez caught \"xmsg\" exception:\n\""
<< thisException.why() << "\"\n ... exiting program" << endl;
}
#endif
// now just catch anything
catch( ... )
{
cerr << "ERROR: Suez caught an (unknown/user-defined?) exception:\n"
<< " ... exiting program" << endl;
}
#endif /* in debug mode don't catch exceptions */
return 0;
}
int TheMain( int argc, char** argv )
{
// setup message logger
//FrameLogger logger( reportLevel, cout );
//MessageLog::Tie( "." , logger );
// try new logging via ReportModule
ReportModule* reportModule = new ReportModule( INFO );
// test proper Boolean behavior; if no good, will exit
testBoolean();
// force-link StorageManagement, so that nobody has else to
forceLinkStorageManagement();
// handle options
DABoolean runGUI = false, runSetupFile = true;
string runFile( "" );
// handle options using the getopt standard function; if
int option;
optarg = 0;
const char* const ARGS = "f:xq";
while( true )
{
option = getopt( argc, argv, ARGS );
if( option == -1 ) break;
switch( option ) {
case 'f': {
runFile = optarg;
break;
}
case 'x': {
runGUI = true;
break;
}
case 'q': {
runSetupFile = false;
break;
}
case '?': { // ignore
break;
}
default: {
report( WARNING, kFacilityString )
<< "don't understand option: " << option << endl;
}
}
}
// print out any other non-option arguments (since we won't process them!)
if( optind < argc ) {
ostream& os = report( ERROR, kFacilityString );
os <<"ignoring non-option ARGV-elements: \n";
while( optind < argc ) {
os << argv[optind++] << "\n";
}
os << "continuing..." << endl;
}
// --------- welcome user -------------
report( INFO, kFacilityString ) << "\n" << welcomeMsg << endl;
report( INFO, kFacilityString ) << IdString << "\n"
//<< TagString << "\n"
//<< VersionString << "\n"
<< endl;
// create Interpreter
Interpreter::setInterpreter( new TclInterpreter() );
Interpreter* interpreter = Interpreter::interpreter();
assert( 0 != interpreter );
// --------- Initialize Suez Application -----------------
JobControl* jobControl = JobControl::instance();
assert( 0 != jobControl );
jobControl->setName( "Suez" );
jobControl->addModule( reportModule, false ); // not owned by JobControl
jobControl->initLogger( reportModule->logger() );
// ------------------ create user application ----------------
// create on the stack, no need to control deletion
UserApplication userApplication( jobControl );
if( true == runGUI )
{
report( INFO, kFacilityString )
<< "starting suez in gui mode..." << endl;
report( ERROR, kFacilityString )
<< "not supported at the moment!" << endl;
//// Need to enable commands before running initialization scripts
////interpreter->initialize( false, argc, argv );
////jobControl->enableCommands();
//SuezInit( *interpreter, runFile, runSetupFile );
//interpreter->initialize( runGUI, argc, argv );
}
else // default is pure cli mode
{
// Need to enable commands before running initialization scripts
interpreter->initialize( false, argc, argv );
interpreter->pushActiveModule(jobControl);
SuezInit( *interpreter, runFile, runSetupFile );
// ------------ Main Interaction Loop with User -----------
userApplication.runEmbeddedCommands( *interpreter );
if( true == userApplication.interactiveMode() ) {
interpreter->loop();
}
}
// -------------- Clean Up --------------------------------
jobControl->finalizeLogger( reportModule->logger() );
jobControl->destroy();
delete interpreter;
delete reportModule; // finally delete ReportModule (to be last!)
return 0;
}
DABoolean
SuezInit( Interpreter& interpreter,
const string& runFile,
DABoolean runSetupFile )
{
DABoolean status = true;
if( true == runSetupFile ) { // turn setup file off if requested
// if file was specified from command line, run that.
if( runFile != "" ) {
interpreter.runCommandFile( runFile.c_str() );
}
else {
// Run any initialization scripts (official, home directory etc.)
// only run official startup script if personal doesn't exist
const char* const HOME = getenv( "HOME" );
if( 0 != HOME ) {
string personalStartupScript = string( HOME ) + string( "/.suezrc" );
ifstream ifs( personalStartupScript.c_str() );
if( ifs ) { // personal file exists
ifs.close();
interpreter.runCommandFile( personalStartupScript.c_str() );
}
else { // no personal file exists; run official
const char* const C3_SUEZRC = getenv( "C3_SUEZRC" );
if( 0 == C3_SUEZRC ) {
report( WARNING, kFacilityString )
<< "cannot find C3_SUEZRC environment variable!\n "
<< "May not be able to initialize properly!" << endl;
}
else {
// need to find first entry in C3_SUEZRC string
StringTokenizer c3_suezrc_tokens( C3_SUEZRC );
if( c3_suezrc_tokens.hasMoreElements() ) {
// now assemble file name
string officialStartupScript
= c3_suezrc_tokens.nextElement() + string( "/suezrc" );
interpreter.runCommandFile( officialStartupScript.c_str() );
}
}
}
}
else {
report( WARNING, kFacilityString )
<< "cannot find HOME environment variable!\n "
<< "May not be able to initialize properly!" << endl;
}
} // specified script on command-line or not
} // run setup file or not
return status;
}
// ----------------------------------------------------------------------
// Revision history
//
// $Log: SuezMain.cc,v $
// Revision 1.67 2002/01/03 21:07:26 cdj
// updated to work with new Interpreter handling
//
// Revision 1.66 2000/12/01 20:33:59 cdj
// updated to work with DynamicLoader package
//
// Revision 1.65 2000/07/29 17:02:28 mkl
// catch non-standard Solaris exceptions (base class and out-of-memory)
//
// Revision 1.64 2000/03/31 16:52:37 mkl
// for online benefit: print warning, but ignore any illegal options
//
// Revision 1.63 2000/03/14 22:52:06 mkl
// UserApplication header now comes from Suez
//
// Revision 1.62 2000/03/14 20:55:21 mkl
// new UserApplication functionality: new embeddedCommand and interactiveMode methods for running Suez in standalone mode in online
//
// Revision 1.61 2000/03/02 16:59:59 mkl
// new StringTokenizer parse handling
//
// Revision 1.60 2000/01/27 03:46:18 mkl
// create UserApplication on the stack, no need to control deletion
//
// Revision 1.59 2000/01/17 19:03:58 mkl
// run_file was not working correctly together with -f flag
//
// Revision 1.58 2000/01/03 19:00:07 mkl
// print 'ERROR' as part of exception-handling message
//
// Revision 1.57 1999/12/06 16:17:18 mkl
// name change: CleoException-->DAException
//
// Revision 1.56 1999/12/03 19:10:43 mkl
// reflect move of CleoException to its own package
//
// Revision 1.55 1999/12/02 23:36:43 mkl
// have to catch CleoExceptions now (as last resort)
//
// Revision 1.54 1999/11/05 17:43:52 mkl
// move force-link to StorageManagement into its own file (for better maintainance)
//
// Revision 1.53 1999/11/04 20:42:11 mkl
// force link to StorageManagement, so that nobody else has to
//
// Revision 1.52 1999/09/08 19:50:19 mkl
// ReportModule has to be deleted last so that all messages get put out
//
// Revision 1.51 1999/09/07 14:47:50 mkl
// move to new Histogram Interface
//
// Revision 1.50 1999/08/31 23:10:04 mkl
// removed deprecated report level option; fixed up handling of explicitly specified executable
//
// Revision 1.49 1999/08/26 03:02:03 mkl
// better than rethrow: dont catch in debug mode
//
// Revision 1.48 1999/08/26 02:29:29 mkl
// rethrow caught exceptions so that gdb can properly work
//
// Revision 1.47 1999/08/25 21:27:46 mkl
// ReportModule allows setting of report level and logging to files
//
// Revision 1.46 1999/05/12 20:34:21 mkl
// change default report level to INFO
//
// Revision 1.45 1999/05/02 02:45:46 mkl
// use new Signal library
//
// Revision 1.44 1999/04/30 18:09:25 mkl
// catch all exceptions
//
// Revision 1.43 1999/04/29 19:54:42 mkl
// take out MAILTO line from test scripts
//
// Revision 1.42 1999/04/19 18:01:50 mkl
// added info on tcl via web pages
//
// Revision 1.41 1999/02/12 15:53:10 mkl
// simplify nooption error
//
// Revision 1.40 1999/02/12 00:12:59 mkl
// allow run-time control over report level
//
// Revision 1.39 1999/01/27 23:02:54 mkl
// trivial change to get rid of insure++ complaint about null parameter
//
// Revision 1.38 1998/12/16 03:17:59 mkl
// print 'Welcome to Suez' instead of 'SUEZ' as a test for release system
//
// Revision 1.37 1998/12/09 22:46:43 mkl
// Logger now logs everything above DEBUG severity level.
//
// Revision 1.36 1998/11/30 20:38:18 mkl
// test TagString
//
// Revision 1.35 1998/11/30 19:51:11 mkl
// properly format SuezMain
//
| [
"jpivarski@gmail.com"
] | jpivarski@gmail.com |
917a1cfeb76a9146b509b34f3daa9298b195ceeb | f1103e383f37e9e2f3695cbe6475d8a4cc8416ea | /sketch_mar13a/build/sketch_mar13a.cpp | 668c214d6bdc51cfc45684cf01ec9e4093c4597a | [] | no_license | ajparedes10/arquisoft | 140cfaec7d6b7b22097fb73c11be1c6a8c118cae | 19a3a53163a41315c9103981960ace2b89e6b717 | refs/heads/master | 2021-01-22T10:07:22.657248 | 2017-05-01T20:16:19 | 2017-05-01T20:16:19 | 81,987,093 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,017 | cpp | /*
Obtiene un numero aleatorio y lo muestra en monitor serie
*/
//Variable donde almacenaremos el numero aleatorio
#include "WProgram.h"
void setup();
void loop();
long randomNumber;
long randomNumber2;
long randomNumber3;
long randomNumber4;
//Funci\u00f3n de inicializaci\u00f3n
void setup() {
//Inicializamos la comunicaci\u00f3n serial
Serial.begin(9600);
//Escribimos por el puerto serie mensaje de inicio
Serial.println("Inicio de sketch - secuencia de numeros aleatorios");
}
//Bucle principal
void loop() {
//Genera un numero aleatorio entre 1 y 100
randomNumber = random(50,150);
randomNumber2 = random(50,150);
randomNumber4 = random(50,150);
randomNumber3 = random(1,10);
//Escribimos el numero aleatorio por el puerto serie
Serial.print(randomNumber);
Serial.print("@");
Serial.print(randomNumber2);
Serial.print("@");
Serial.print(randomNumber4);
Serial.print("@");
Serial.print(randomNumber3);
Serial.println(" ");
delay(2000);
}
| [
"cc.novoa11@sis.virtual.uniandes.edu.co"
] | cc.novoa11@sis.virtual.uniandes.edu.co |
cc8f7e42234cd1e9a3997375ffef055952e239cf | c5a98c662bf46ca465d621810275a81c2372e9e9 | /Arduino/WifiModule/WifiModule.ino | f48e510e3087393bffcf899c084836ca42dac7e2 | [] | no_license | AllanFontaine/Pot-App | 241a01a44858e4af509d08546488aa58503eb02e | f28e64ff24c25076a0f71eb4a0c60bc4c4e875b2 | refs/heads/master | 2023-01-31T14:21:09.979306 | 2020-12-17T13:23:21 | 2020-12-17T13:23:21 | 296,675,344 | 2 | 0 | null | 2020-12-17T13:23:22 | 2020-09-18T16:33:54 | CSS | UTF-8 | C++ | false | false | 5,253 | ino | #include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
const char* ssid = "PDC";
const char* password = "Scott44572Glenn";
//Your Domain name with URL path or IP address with path
String serverDonneesParcelle = "https://api.pot-app.be/api/donnees-parcelle/";
String serverDonneesUser = "https://api.pot-app.be/api/donnees-user/";
String serverName = "";
String userCode = "codeCelia";
// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;
float temp_exterieure;
float hum_exterieure;
float id_parcelle_1;
float hum_sol_parcelle_1;
float quantite_eau_parcelle_1;
float id_parcelle_2;
float hum_sol_parcelle_2;
float quantite_eau_parcelle_2;
float id_parcelle_3;
float hum_sol_parcelle_3;
float quantite_eau_parcelle_3;
boolean newData = false;
void postToParcel(String parcelleId, String humidite_sol, String quantite_eau){
if(WiFi.status()== WL_CONNECTED){
HTTPClient http;
WiFiClientSecure client;
client.setInsecure(); //the magic line, use with caution
client.connect(serverDonneesUser, 443);
// Your Domain name with URL path or IP address with path
http.begin(client, serverDonneesParcelle);
// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Data to send with HTTP POST
// If you need an HTTP request with a content type: application/json, use the following:
http.addHeader("Content-Type", "application/json");
String jsonObject = "{\"parcelleId\":" + parcelleId + ",\"humidite_sol\":" + humidite_sol + ",\"quantite_eau_litre\": \"" + quantite_eau + "\",\"code\": \"" + userCode + "\"}";
int httpResponseCode = http.POST(jsonObject);
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
// Free resources
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
}
void postToUser(String temperature_exterieur, String humidite_exterieur){
if(WiFi.status()== WL_CONNECTED){
HTTPClient http;
WiFiClientSecure client;
client.setInsecure(); //the magic line, use with caution
client.connect(serverDonneesUser, 443);
// Your Domain name with URL path or IP address with path
http.begin(client, serverDonneesUser);
// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Data to send with HTTP POST
// If you need an HTTP request with a content type: application/json, use the following:
http.addHeader("Content-Type", "application/json");
String jsonObject = "{\"userId\":\" 1 \",\"temperature_exterieur\":" + temperature_exterieur + ",\"humidite_exterieur\": \"" + humidite_exterieur + "\",\"code\": \"" + userCode + "\"}";
int httpResponseCode = http.POST(jsonObject);
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
String payload = http.getString();
Serial.println(payload);
// Free resources
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}
void loop() {
//Send an HTTP POST request every 10 minutes
newData = true;
Serial.println("NewData true");
delay(5000);
if (newData) {
postToParcel("5", "80", "2.5");
delay(2000);
postToParcel("5", "80", "2.5");
delay(2000);
postToUser("22.5","25");
newData = false;
Serial.println("NewData false");
}
//GET REQUEST NOT USED
if (false) {
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
HTTPClient http;
String serverPath = serverName + "?code=codeCelia";
WiFiClientSecure client;
client.setInsecure(); //the magic line, use with caution
client.connect(serverPath, 443);
Serial.println(serverPath);
// Your Domain name with URL path or IP address with path
http.begin(client, serverPath.c_str());
// Send HTTP GET request
int httpResponseCode = http.GET();
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
String payload = http.getString();
Serial.println(payload);
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
lastTime = millis();
}
}
| [
"mr.glennichou@gmail.com"
] | mr.glennichou@gmail.com |
f733850e64d7344c9534c56b41f99252c311693b | bdd9f3cdabe0c768641cf61855a6f24174735410 | /src/engine/client/library/clientAudio/src/win32/Audio.h | 6b717613b0ff7ef5a57b53e74a527b03993e363a | [] | no_license | SWG-Source/client-tools | 4452209136b376ab369b979e5c4a3464be28257b | 30ec3031184243154c3ba99cedffb2603d005343 | refs/heads/master | 2023-08-31T07:44:22.692402 | 2023-08-28T04:34:07 | 2023-08-28T04:34:07 | 159,086,319 | 15 | 47 | null | 2022-04-15T16:20:34 | 2018-11-25T23:57:31 | C++ | UTF-8 | C++ | false | false | 13,614 | h | // ============================================================================
//
// Audio.h
// Copyright Sony Online Entertainment
//
// ============================================================================
#ifndef INCLUDED_Audio_H
#define INCLUDED_Audio_H
#include "clientAudio/SoundId.h"
class AudioSampleInformation;
class CellProperty;
class CrcString;
class Iff;
class Object;
class SampleId;
class Vector;
class Plane;
namespace AudioCapture
{
class ICallback;
}
// ============================================================================
//
// Audio
//
// ============================================================================
//-----------------------------------------------------------------------------
class Audio
{
// These classes are friends to access the protected functions of this class
friend class Sound2;
friend class Sound2d;
friend class Sound3d;
friend class ConfigClientAudio;
friend class SoundTemplate;
friend class Sound2dTemplate;
friend class SoundTemplateWidget;
friend class Sample2d;
friend class Sample3d;
friend class SampleStream;
public:
enum AttenuationMethod
{
AM_none,
AM_2d,
AM_3d
};
enum PlayBackStatus
{
PS_doesNotExist = 0,
PS_notStarted,
PS_playing,
PS_done
};
enum SoundCategory
{
SC_ambient = 0,
SC_explosion,
SC_item,
SC_movement,
SC_userInterface,
SC_vehicle,
SC_vocalization,
SC_weapon,
SC_backGroundMusic,
SC_playerMusic,
SC_machine,
SC_installation,
SC_combatMusic,
SC_voiceover,
SC_bufferedSound,
SC_bufferedMusic,
SC_count
};
enum RoomType
{
RT_alley = 0,
RT_arena,
RT_auditorium,
RT_bathRoom,
RT_carpetedHallway,
RT_cave,
RT_city,
RT_concertHall,
RT_dizzy,
RT_drugged,
RT_forest,
RT_generic,
RT_hallway,
RT_hangar,
RT_livingRoom,
RT_mountains,
RT_paddedCell,
RT_parkingLot,
RT_plain,
RT_psychotic,
RT_quarry,
RT_room,
RT_sewerPipe,
RT_stoneCorridor,
RT_stoneRoom,
RT_underWater,
RT_notSupported
};
public:
// Setup
//----------------------------------
static bool install();
static void remove();
static void lock();
static void unLock();
static void setLargePreMixBuffer();
static void setNormalPreMixBuffer();
static void silenceAllNonBackgroundMusic();
static void unSilenceAllNonBackgroundMusic();
static void fadeAllNonVoiceover();
static void unFadeAllNonVoiceover();
static void fadeAll();
static void unfadeAll();
static void setSoundFallOffPower(int const power);
// Enabled/Disable the entire audio system
static bool isEnabled();
static void setEnabled(bool enabled);
static bool isMilesEnabled();
static void * getMilesDigitalDriver();
static void setRequestedMaxNumberOfSamples(int const max);
static int getRequestedMaxNumberOfSamples();
static void setMaxCached2dSampleSize(int bytes);
static int getMaxCached2dSampleSize();
//static void setMaxCacheSize(int bytes);
//static int getMaxCacheSize();
// Update
//----------------------------------
static void alter(float const deltaTime, Object const *listener);
static void serve();
// Volumes
//----------------------------------
static void setSoundVolume(SoundId const &soundId, float volume);
static void setSoundPitchDelta(SoundId const &soundId, float pitchDelta);
static void setMasterVolume(float volume);
static float getMasterVolume();
static float getDefaultMasterVolume();
static void setSoundEffectVolume(float volume);
static float getSoundEffectVolume();
static float getDefaultSoundEffectVolume();
static void setBackGroundMusicVolume(float volume);
static float getBackGroundMusicVolume();
static float getDefaultBackGroundMusicVolume();
static void setPlayerMusicVolume(float volume);
static float getPlayerMusicVolume();
static float getDefaultPlayerMusicVolume();
static void setUserInterfaceVolume(float volume);
static float getUserInterfaceVolume();
static float getDefaultUserInterfaceVolume();
static void setFadeAllFactor(float factor);
static float getFadeAllFactor();
static float getDefaultFadeAllFactor();
static void setBufferedSoundVolume(float volume);
static void setBufferedMusicVolume(float volume);
static void setAmbientEffectVolume(float volume);
static float getAmbientEffectVolume();
static float getDefaultAmbientEffectVolume();
// Sounds
//----------------------------------
static SoundId playSound(char const * const path); // Only use for stereo sounds
static SoundId playSound(char const *path, CellProperty const * const parentCell);
static SoundId playSound(char const *path, Vector const &position, CellProperty const * const parentCell);
static SoundId attachSound(char const *path, Object const *object, char const *hardPointName = NULL);
static SoundId createSoundId(char const *path);
static void playSound(SoundId &soundId, Vector const *position, CellProperty const * const parentCell);
static void playBufferedSound(char const * const buffer, uint32 bufferLength, char const * const extension);
static void playBufferedMusic(char const * const buffer, uint32 bufferLength, char const * const extension);
static void stopBufferedSound();
static void stopBufferedMusic();
static void silenceNonBufferedMusic(bool silence);
static SoundId restartSound(char const *path, Vector const *position = NULL, float const fadeOutTime = 0.0f);
static void restartSound(SoundId &soundId, Vector const *position = NULL, float const fadeOutTime = 0.0f);
static void detachSound(SoundId const &soundId, float const fadeOutTime = 0.0f);
static void detachSound(Object const &object, float const fadeOutTime = 0.0f);
static void stopSound(SoundId const &soundId, float const fadeOutTime = 0.0f);
static void stopAllSounds(float const fadeOutTime = 0.0f);
static bool isSoundPlaying(SoundId const &soundId);
static void setAutoDelete(SoundId const &soundId, bool const autoDelete);
static void setCurrentSoundTime(SoundId const &soundId, int const milliSecond);
static bool getCurrentSoundTime(SoundId const &soundId, int &totalMilliSeconds, int ¤tMilliSeconds);
static bool getCurrentSoundTime(SoundId const &soundId, int &milliSecond);
static bool getTotalSoundTime(SoundId const &soundId, int &milliSecond);
static void setSoundPosition_w(SoundId const &soundId, Vector const &position_w);
static Vector getSoundPosition_w(SoundId const &soundId);
typedef void (*EndOfSampleCallBack)();
static void setEndOfSampleCallBack(SoundId const &soundId, EndOfSampleCallBack callBack);
typedef stdvector<Sound2*>::fwd SoundVector;
static void getSoundsAttachedToObject (const Object & obj, SoundVector & sv);
static Sound2 * getSoundById (const SoundId & soundId);
static void transferOwnershipOfSounds(Object const & previousOwner, Object const & newOwner, Plane const * partition);
// Sound Status
//----------------------------------
static PlayBackStatus getSoundPlayBackStatus(SoundId const &soundId);
// Environmental effects
//----------------------------------
static void setRoomType(RoomType const roomType);
static RoomType getRoomType();
static char const * const getRoomTypeString();
static bool isRoomTypeSupported();
static void setSampleOcclusion(SampleId const &sampleId, float const occlusion);
static void setSampleObstruction(SampleId const &sampleId, float const obstruction);
// Providers of 3d
//----------------------------------
static std::string const & getCurrent3dProvider();
static bool set3dProvider(std::string const &provider);
static bool setDefault3dProvider();
static stdvector<std::string>::fwd get3dProviders();
// Utilities
//----------------------------------
static Object const * const getListener();
static Vector const & getListenerPosition();
static int getCacheHitCount();
static int getCacheMissCount();
static int getCachedSampleCount();
static int getCurrentCacheSize();
static void getCurrentSample(SoundId const &soundId, TemporaryCrcString &path);
static void getCurrentSampleTime(SoundId const &soundId, float &timeTotal, float &timeCurrent);
static int getDigitalCpuPercent();
static int getDigitalLatency();
static int getMaxDigitalMixerChannels();
static std::string getMilesVersion();
static int getSample2dCount();
static int getSample3dCount();
static AudioSampleInformation getSampleInformation(std::string const &path);
static int getSampleSize(char const *path);
static int getSampleStreamCount();
static int getSampleCount();
static std::string getSampleType(void *fileImage, int fileSize);
static int getSoundCount();
static float getSoundTemplateVolume(SoundId const &soundId);
static float getSoundAttenuation(SoundId const &soundId);
static float getSoundVolume(SoundId const &soundId);
static float getSoundPitchDelta(SoundId const &soundId); // Adjustment in half steps
static bool getLoopOffsets(CrcString const &path, int &loopStartOffset, int &loopEndOffset);
static bool isSampleAtEnd(SoundId const &soundId);
static float getDistanceAtVolumeCutOff(SoundId const &soundId);
static bool isToolApplication();
static void setToolApplication(bool const toolApplication);
// SoundEditor access
//----------------------------------
static SoundId playSound(Iff &iff);
static SoundId playSound(Iff &iff, Vector const &position);
static float getFallOffDistance(float const minDistance);
static bool isSampleValid(SampleId const &sampleId);
static bool isSoundValid(SoundId const &soundId);
static bool isSampleForSoundIdPlaying(SoundId const &soundId);
static void releaseSampleId(Sound2 const &sound);
static bool queueSample(Sound2 &sound, bool const soundIsAlreadyPlaying);
static void setDebugEnabled(bool const enabled);
static bool isDebugEnabled();
// AudioCapture
//----------------------------------
#if PRODUCTION == 0
static bool getAudioCaptureConfig(int& samplesPerSec, int& bitsPerSample, int& channels);
static bool startAudioCapture(AudioCapture::ICallback* pCallback);
static void stopAudioCapture();
#endif // PRODUCTION
protected:
// Helper functions that friend classes access, these are the only functions
// that friend classes should access
static SoundId attachSound(Iff &iff, Object const *object, char const *hardPointName=0);
static PlayBackStatus getSamplePlayBackStatus(SampleId const &sampleId);
static float getSampleVolume(SampleId const &sampleId);
static int getSamplePlayBackRate(SampleId const &sampleId);
static void getSampleTime(SampleId const &sampleId, float &timeTotal, float &timeCurrent);
static int getSampleCurrentTime(SampleId const &sampleId);
static void setSampleCurrentTime(SampleId const &sampleId, int const milliSeconds);
static int getSampleTotalTime(SampleId const &sampleId);
static void setSamplePlayBackRate(SampleId const &sampleId, int const playBackRate, float const playBackRateDelta = 0.0f);
static void setSampleVolume(SampleId const &sampleId, float const volume);
static float getSampleEffectsLevel(SampleId const &sampleId);
static void setSampleEffectsLevel(SampleId const &sampleId, float const effectLevel);
static void setSamplePosition_w(SampleId const &sampleId, Vector const &position_w);
static bool getSoundWorldPosition(SoundId const &soundId, Vector &position);
static CrcString const *increaseReferenceCount(const char *path, bool const cacheSample);
static void decreaseReferenceCount(CrcString const &path);
static float getObstruction();
static float getOcclusion();
#ifdef _DEBUG
// Runtime statistics
static void showAudioDebug();
static void debugDumpAudioText();
#endif // _DEBUG
private:
static SoundId playSound(Iff &iff, Vector const * const position, CellProperty const * const parentCell);
static SoundId playSound(char const *path, Vector const * const position, CellProperty const * const parentCell);
static void startSample(Sound2 & sound);
// Disabled
Audio();
Audio(Audio const &);
Audio &operator=(Audio const &);
~Audio();
};
// ============================================================================
#endif // INCLUDED_Audio_H
| [
"swgmaster@india.com"
] | swgmaster@india.com |
ab73ff22eecbfa21f8634bcaae44b447d8868912 | c51febc209233a9160f41913d895415704d2391f | /library/ATF/_trunk_pw_hint_index_request_clzo.hpp | 7d3675575cb35a175fa55dd52a612b19cc4dcbe7 | [
"MIT"
] | permissive | roussukke/Yorozuya | 81f81e5e759ecae02c793e65d6c3acc504091bc3 | d9a44592b0714da1aebf492b64fdcb3fa072afe5 | refs/heads/master | 2023-07-08T03:23:00.584855 | 2023-06-29T08:20:25 | 2023-06-29T08:20:25 | 463,330,454 | 0 | 0 | MIT | 2022-02-24T23:15:01 | 2022-02-24T23:15:00 | null | UTF-8 | C++ | false | false | 270 | hpp | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
struct _trunk_pw_hint_index_request_clzo
{
char byDummy;
};
END_ATF_NAMESPACE
| [
"b1ll.cipher@yandex.ru"
] | b1ll.cipher@yandex.ru |
e83f433c55b5407e67c655d0178c4be9d49500f9 | bd8dff663c463faa69e2bfa9ee177b50c617f701 | /B1026.cpp | 188dde3997113610d65191376e9b87ff441e3a5d | [] | no_license | Gabriel-18/PAT | 94b8b0b02955458f736f781246d91b9c6ee25794 | f66e5f6c6db22e1be28b738523cb589e9ce12b11 | refs/heads/master | 2022-12-07T08:15:11.181501 | 2020-09-05T01:27:38 | 2020-09-05T01:28:18 | 198,178,163 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 432 | cpp | #include<cstdio>
// 模拟
// 四舍五入
int main() {
int c1, c2;
scanf("%d%d",&c1, &c2);
int ans = c2 - c1;
//四舍五入
if(ans % 100 >= 50) {
// 傻逼写法 ans /= 100 + 1
ans = ans / 100 + 1;
} else {
ans /= 100;
}
//ans / 3600 直接得到小时数
//ans % 3600 除去小时数剩下的部分
//ans % 60 剩下的秒数
printf("%02d:%02d:%02d", ans / 3600, ans % 3600 / 60 ,ans % 60);
return 0;
}
| [
"644050173@qq.com"
] | 644050173@qq.com |
7c2c588f30b18f3454647da23347af5f93b2b4c7 | 89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04 | /media/formats/mp4/mp4_stream_parser_unittest.cc | d7b23181681d90ae1a5df19abf1384aaa90865a3 | [
"BSD-3-Clause"
] | permissive | bino7/chromium | 8d26f84a1b6e38a73d1b97fea6057c634eff68cb | 4666a6bb6fdcb1114afecf77bdaa239d9787b752 | refs/heads/master | 2022-12-22T14:31:53.913081 | 2016-09-06T10:05:11 | 2016-09-06T10:05:11 | 67,410,510 | 1 | 3 | BSD-3-Clause | 2022-12-17T03:08:52 | 2016-09-05T10:11:59 | null | UTF-8 | C++ | false | false | 22,185 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/formats/mp4/mp4_stream_parser.h"
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <memory>
#include <string>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/time/time.h"
#include "media/base/audio_decoder_config.h"
#include "media/base/decoder_buffer.h"
#include "media/base/media_track.h"
#include "media/base/media_tracks.h"
#include "media/base/mock_media_log.h"
#include "media/base/stream_parser.h"
#include "media/base/stream_parser_buffer.h"
#include "media/base/test_data_util.h"
#include "media/base/text_track_config.h"
#include "media/base/video_decoder_config.h"
#include "media/formats/mp4/es_descriptor.h"
#include "media/formats/mp4/fourccs.h"
#include "media/media_features.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::InSequence;
using ::testing::StrictMock;
using base::TimeDelta;
namespace media {
namespace mp4 {
// Matchers for verifying common media log entry strings.
MATCHER_P(VideoCodecLog, codec_string, "") {
return CONTAINS_STRING(arg, "Video codec: " + std::string(codec_string));
}
MATCHER_P(AudioCodecLog, codec_string, "") {
return CONTAINS_STRING(arg, "Audio codec: " + std::string(codec_string));
}
MATCHER(SampleEncryptionInfoUnavailableLog, "") {
return CONTAINS_STRING(arg, "Sample encryption info is not available.");
}
MATCHER_P(ErrorLog, error_string, "") {
return CONTAINS_STRING(arg, error_string);
}
class MP4StreamParserTest : public testing::Test {
public:
MP4StreamParserTest()
: media_log_(new StrictMock<MockMediaLog>()),
configs_received_(false),
lower_bound_(
DecodeTimestamp::FromPresentationTime(base::TimeDelta::Max())) {
std::set<int> audio_object_types;
audio_object_types.insert(kISO_14496_3);
parser_.reset(new MP4StreamParser(audio_object_types, false));
}
protected:
scoped_refptr<StrictMock<MockMediaLog>> media_log_;
std::unique_ptr<MP4StreamParser> parser_;
bool configs_received_;
std::unique_ptr<MediaTracks> media_tracks_;
AudioDecoderConfig audio_decoder_config_;
VideoDecoderConfig video_decoder_config_;
DecodeTimestamp lower_bound_;
StreamParser::TrackId audio_track_id_;
StreamParser::TrackId video_track_id_;
bool AppendData(const uint8_t* data, size_t length) {
return parser_->Parse(data, length);
}
bool AppendDataInPieces(const uint8_t* data,
size_t length,
size_t piece_size) {
const uint8_t* start = data;
const uint8_t* end = data + length;
while (start < end) {
size_t append_size = std::min(piece_size,
static_cast<size_t>(end - start));
if (!AppendData(start, append_size))
return false;
start += append_size;
}
return true;
}
void InitF(const StreamParser::InitParameters& expected_params,
const StreamParser::InitParameters& params) {
DVLOG(1) << "InitF: dur=" << params.duration.InMicroseconds()
<< ", autoTimestampOffset=" << params.auto_update_timestamp_offset;
EXPECT_EQ(expected_params.duration, params.duration);
EXPECT_EQ(expected_params.timeline_offset, params.timeline_offset);
EXPECT_EQ(expected_params.auto_update_timestamp_offset,
params.auto_update_timestamp_offset);
EXPECT_EQ(expected_params.liveness, params.liveness);
EXPECT_EQ(expected_params.detected_audio_track_count,
params.detected_audio_track_count);
EXPECT_EQ(expected_params.detected_video_track_count,
params.detected_video_track_count);
EXPECT_EQ(expected_params.detected_text_track_count,
params.detected_text_track_count);
}
bool NewConfigF(std::unique_ptr<MediaTracks> tracks,
const StreamParser::TextTrackConfigMap& tc) {
configs_received_ = true;
CHECK(tracks.get());
DVLOG(1) << "NewConfigF: got " << tracks->tracks().size() << " tracks";
for (const auto& track : tracks->tracks()) {
const auto& track_id = track->bytestream_track_id();
if (track->type() == MediaTrack::Audio) {
audio_track_id_ = track_id;
audio_decoder_config_ = tracks->getAudioConfig(track_id);
DVLOG(1) << "track_id=" << track_id << " audio config="
<< (audio_decoder_config_.IsValidConfig()
? audio_decoder_config_.AsHumanReadableString()
: "INVALID");
} else if (track->type() == MediaTrack::Video) {
video_track_id_ = track_id;
video_decoder_config_ = tracks->getVideoConfig(track_id);
DVLOG(1) << "track_id=" << track_id << " video config="
<< (video_decoder_config_.IsValidConfig()
? video_decoder_config_.AsHumanReadableString()
: "INVALID");
}
}
media_tracks_ = std::move(tracks);
return true;
}
bool NewBuffersF(const StreamParser::BufferQueueMap& buffer_queue_map) {
DecodeTimestamp lowest_end_dts = kNoDecodeTimestamp();
for (const auto& it : buffer_queue_map) {
DVLOG(3) << "Buffers for track_id=" << it.first;
DCHECK(!it.second.empty());
if (lowest_end_dts == kNoDecodeTimestamp() ||
lowest_end_dts > it.second.back()->GetDecodeTimestamp())
lowest_end_dts = it.second.back()->GetDecodeTimestamp();
for (const auto& buf : it.second) {
DVLOG(3) << " track_id=" << buf->track_id()
<< ", size=" << buf->data_size()
<< ", pts=" << buf->timestamp().InSecondsF()
<< ", dts=" << buf->GetDecodeTimestamp().InSecondsF()
<< ", dur=" << buf->duration().InSecondsF();
// Ensure that track ids are properly assigned on all emitted buffers.
EXPECT_EQ(it.first, buf->track_id());
}
}
EXPECT_NE(lowest_end_dts, kNoDecodeTimestamp());
if (lower_bound_ != kNoDecodeTimestamp() && lowest_end_dts < lower_bound_) {
return false;
}
lower_bound_ = lowest_end_dts;
return true;
}
void KeyNeededF(EmeInitDataType type, const std::vector<uint8_t>& init_data) {
DVLOG(1) << "KeyNeededF: " << init_data.size();
EXPECT_EQ(EmeInitDataType::CENC, type);
EXPECT_FALSE(init_data.empty());
}
void NewSegmentF() {
DVLOG(1) << "NewSegmentF";
lower_bound_ = kNoDecodeTimestamp();
}
void EndOfSegmentF() {
DVLOG(1) << "EndOfSegmentF()";
lower_bound_ =
DecodeTimestamp::FromPresentationTime(base::TimeDelta::Max());
}
void InitializeParserWithInitParametersExpectations(
StreamParser::InitParameters params) {
parser_->Init(
base::Bind(&MP4StreamParserTest::InitF, base::Unretained(this), params),
base::Bind(&MP4StreamParserTest::NewConfigF, base::Unretained(this)),
base::Bind(&MP4StreamParserTest::NewBuffersF, base::Unretained(this)),
true,
base::Bind(&MP4StreamParserTest::KeyNeededF, base::Unretained(this)),
base::Bind(&MP4StreamParserTest::NewSegmentF, base::Unretained(this)),
base::Bind(&MP4StreamParserTest::EndOfSegmentF, base::Unretained(this)),
media_log_);
}
StreamParser::InitParameters GetDefaultInitParametersExpectations() {
// Most unencrypted test mp4 files have zero duration and are treated as
// live streams.
StreamParser::InitParameters params(kInfiniteDuration);
params.liveness = DemuxerStream::LIVENESS_LIVE;
params.detected_audio_track_count = 1;
params.detected_video_track_count = 1;
params.detected_text_track_count = 0;
return params;
}
void InitializeParserAndExpectLiveness(DemuxerStream::Liveness liveness) {
auto params = GetDefaultInitParametersExpectations();
params.liveness = liveness;
InitializeParserWithInitParametersExpectations(params);
}
void InitializeParser() {
InitializeParserWithInitParametersExpectations(
GetDefaultInitParametersExpectations());
}
bool ParseMP4File(const std::string& filename, int append_bytes) {
scoped_refptr<DecoderBuffer> buffer = ReadTestDataFile(filename);
EXPECT_TRUE(AppendDataInPieces(buffer->data(),
buffer->data_size(),
append_bytes));
return true;
}
};
TEST_F(MP4StreamParserTest, UnalignedAppend) {
// Test small, non-segment-aligned appends (small enough to exercise
// incremental append system)
EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001F"));
EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2"));
InitializeParser();
ParseMP4File("bear-1280x720-av_frag.mp4", 512);
}
TEST_F(MP4StreamParserTest, BytewiseAppend) {
// Ensure no incremental errors occur when parsing
EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001F"));
EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2"));
InitializeParser();
ParseMP4File("bear-1280x720-av_frag.mp4", 1);
}
TEST_F(MP4StreamParserTest, MultiFragmentAppend) {
// Large size ensures multiple fragments are appended in one call (size is
// larger than this particular test file)
EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001F"));
EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2"));
InitializeParser();
ParseMP4File("bear-1280x720-av_frag.mp4", 768432);
}
TEST_F(MP4StreamParserTest, Flush) {
// Flush while reading sample data, then start a new stream.
EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001F")).Times(2);
EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2")).Times(2);
InitializeParser();
scoped_refptr<DecoderBuffer> buffer =
ReadTestDataFile("bear-1280x720-av_frag.mp4");
EXPECT_TRUE(AppendDataInPieces(buffer->data(), 65536, 512));
parser_->Flush();
EXPECT_TRUE(AppendDataInPieces(buffer->data(),
buffer->data_size(),
512));
}
TEST_F(MP4StreamParserTest, Reinitialization) {
EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001F")).Times(2);
EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2")).Times(2);
InitializeParser();
scoped_refptr<DecoderBuffer> buffer =
ReadTestDataFile("bear-1280x720-av_frag.mp4");
EXPECT_TRUE(AppendDataInPieces(buffer->data(),
buffer->data_size(),
512));
EXPECT_TRUE(AppendDataInPieces(buffer->data(),
buffer->data_size(),
512));
}
TEST_F(MP4StreamParserTest, MPEG2_AAC_LC) {
InSequence s;
std::set<int> audio_object_types;
audio_object_types.insert(kISO_13818_7_AAC_LC);
parser_.reset(new MP4StreamParser(audio_object_types, false));
EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.67"));
EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2"));
auto params = GetDefaultInitParametersExpectations();
params.detected_video_track_count = 0;
InitializeParserWithInitParametersExpectations(params);
ParseMP4File("bear-mpeg2-aac-only_frag.mp4", 512);
}
// Test that a moov box is not always required after Flush() is called.
TEST_F(MP4StreamParserTest, NoMoovAfterFlush) {
EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001F"));
EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2"));
InitializeParser();
scoped_refptr<DecoderBuffer> buffer =
ReadTestDataFile("bear-1280x720-av_frag.mp4");
EXPECT_TRUE(AppendDataInPieces(buffer->data(),
buffer->data_size(),
512));
parser_->Flush();
const int kFirstMoofOffset = 1307;
EXPECT_TRUE(AppendDataInPieces(buffer->data() + kFirstMoofOffset,
buffer->data_size() - kFirstMoofOffset,
512));
}
// Test an invalid file where there are encrypted samples, but
// SampleEncryptionBox (senc) and SampleAuxiliaryInformation{Sizes|Offsets}Box
// (saiz|saio) are missing.
// The parser should fail instead of crash. See http://crbug.com/361347
TEST_F(MP4StreamParserTest, MissingSampleEncryptionInfo) {
InSequence s;
// Encrypted test mp4 files have non-zero duration and are treated as
// recorded streams.
auto params = GetDefaultInitParametersExpectations();
params.duration = base::TimeDelta::FromMicroseconds(23219);
params.liveness = DemuxerStream::LIVENESS_RECORDED;
params.detected_video_track_count = 0;
InitializeParserWithInitParametersExpectations(params);
scoped_refptr<DecoderBuffer> buffer =
ReadTestDataFile("bear-1280x720-a_frag-cenc_missing-saiz-saio.mp4");
EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2")).Times(2);
EXPECT_MEDIA_LOG(SampleEncryptionInfoUnavailableLog());
EXPECT_FALSE(AppendDataInPieces(buffer->data(), buffer->data_size(), 512));
}
// Test a file where all video samples start with an Access Unit
// Delimiter (AUD) NALU.
TEST_F(MP4StreamParserTest, VideoSamplesStartWithAUDs) {
EXPECT_MEDIA_LOG(VideoCodecLog("avc1.4D4028"));
auto params = GetDefaultInitParametersExpectations();
params.detected_audio_track_count = 0;
InitializeParserWithInitParametersExpectations(params);
ParseMP4File("bear-1280x720-av_with-aud-nalus_frag.mp4", 512);
}
TEST_F(MP4StreamParserTest, HEVC_in_MP4_container) {
#if BUILDFLAG(ENABLE_HEVC_DEMUXING)
bool expect_success = true;
EXPECT_MEDIA_LOG(VideoCodecLog("hevc"));
#else
bool expect_success = false;
EXPECT_MEDIA_LOG(ErrorLog("Parse unsupported video format hev1"));
#endif
auto params = GetDefaultInitParametersExpectations();
params.duration = base::TimeDelta::FromMicroseconds(1002000);
params.liveness = DemuxerStream::LIVENESS_RECORDED;
params.detected_audio_track_count = 0;
InitializeParserWithInitParametersExpectations(params);
scoped_refptr<DecoderBuffer> buffer = ReadTestDataFile("bear-hevc-frag.mp4");
EXPECT_EQ(expect_success,
AppendDataInPieces(buffer->data(), buffer->data_size(), 512));
}
// Sample encryption information is stored as CencSampleAuxiliaryDataFormat
// (ISO/IEC 23001-7:2015 8) inside 'mdat' box. No SampleEncryption ('senc') box.
TEST_F(MP4StreamParserTest, CencWithEncryptionInfoStoredAsAuxDataInMdat) {
// Encrypted test mp4 files have non-zero duration and are treated as
// recorded streams.
auto params = GetDefaultInitParametersExpectations();
params.duration = base::TimeDelta::FromMicroseconds(2736066);
params.liveness = DemuxerStream::LIVENESS_RECORDED;
params.detected_audio_track_count = 0;
InitializeParserWithInitParametersExpectations(params);
scoped_refptr<DecoderBuffer> buffer =
ReadTestDataFile("bear-1280x720-v_frag-cenc.mp4");
EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001F"));
EXPECT_TRUE(AppendDataInPieces(buffer->data(), buffer->data_size(), 512));
}
TEST_F(MP4StreamParserTest, CencWithSampleEncryptionBox) {
// Encrypted test mp4 files have non-zero duration and are treated as
// recorded streams.
auto params = GetDefaultInitParametersExpectations();
params.duration = base::TimeDelta::FromMicroseconds(2736066);
params.liveness = DemuxerStream::LIVENESS_RECORDED;
params.detected_audio_track_count = 0;
InitializeParserWithInitParametersExpectations(params);
scoped_refptr<DecoderBuffer> buffer =
ReadTestDataFile("bear-640x360-v_frag-cenc-senc.mp4");
EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001E"));
EXPECT_TRUE(AppendDataInPieces(buffer->data(), buffer->data_size(), 512));
}
TEST_F(MP4StreamParserTest, NaturalSizeWithoutPASP) {
auto params = GetDefaultInitParametersExpectations();
params.duration = base::TimeDelta::FromMicroseconds(1000966);
params.liveness = DemuxerStream::LIVENESS_RECORDED;
params.detected_audio_track_count = 0;
InitializeParserWithInitParametersExpectations(params);
scoped_refptr<DecoderBuffer> buffer =
ReadTestDataFile("bear-640x360-non_square_pixel-without_pasp.mp4");
EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001E"));
EXPECT_TRUE(AppendDataInPieces(buffer->data(), buffer->data_size(), 512));
EXPECT_EQ(gfx::Size(639, 360), video_decoder_config_.natural_size());
}
TEST_F(MP4StreamParserTest, NaturalSizeWithPASP) {
auto params = GetDefaultInitParametersExpectations();
params.duration = base::TimeDelta::FromMicroseconds(1000966);
params.liveness = DemuxerStream::LIVENESS_RECORDED;
params.detected_audio_track_count = 0;
InitializeParserWithInitParametersExpectations(params);
scoped_refptr<DecoderBuffer> buffer =
ReadTestDataFile("bear-640x360-non_square_pixel-with_pasp.mp4");
EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001E"));
EXPECT_TRUE(AppendDataInPieces(buffer->data(), buffer->data_size(), 512));
EXPECT_EQ(gfx::Size(639, 360), video_decoder_config_.natural_size());
}
TEST_F(MP4StreamParserTest, DemuxingAC3) {
std::set<int> audio_object_types;
audio_object_types.insert(kAC3);
parser_.reset(new MP4StreamParser(audio_object_types, false));
#if BUILDFLAG(ENABLE_AC3_EAC3_AUDIO_DEMUXING)
bool expect_success = true;
#else
bool expect_success = false;
EXPECT_MEDIA_LOG(ErrorLog("Unsupported audio format 0x61632d33 in stsd box"));
#endif
auto params = GetDefaultInitParametersExpectations();
params.duration = base::TimeDelta::FromMicroseconds(1045000);
params.liveness = DemuxerStream::LIVENESS_RECORDED;
params.detected_video_track_count = 0;
InitializeParserWithInitParametersExpectations(params);
scoped_refptr<DecoderBuffer> buffer =
ReadTestDataFile("bear-ac3-only-frag.mp4");
EXPECT_EQ(expect_success,
AppendDataInPieces(buffer->data(), buffer->data_size(), 512));
}
TEST_F(MP4StreamParserTest, DemuxingEAC3) {
std::set<int> audio_object_types;
audio_object_types.insert(kEAC3);
parser_.reset(new MP4StreamParser(audio_object_types, false));
#if BUILDFLAG(ENABLE_AC3_EAC3_AUDIO_DEMUXING)
bool expect_success = true;
#else
bool expect_success = false;
EXPECT_MEDIA_LOG(ErrorLog("Unsupported audio format 0x65632d33 in stsd box"));
#endif
auto params = GetDefaultInitParametersExpectations();
params.duration = base::TimeDelta::FromMicroseconds(1045000);
params.liveness = DemuxerStream::LIVENESS_RECORDED;
params.detected_video_track_count = 0;
InitializeParserWithInitParametersExpectations(params);
scoped_refptr<DecoderBuffer> buffer =
ReadTestDataFile("bear-eac3-only-frag.mp4");
EXPECT_EQ(expect_success,
AppendDataInPieces(buffer->data(), buffer->data_size(), 512));
}
TEST_F(MP4StreamParserTest, FourCCToString) {
// A real FOURCC should print.
EXPECT_EQ("mvex", FourCCToString(FOURCC_MVEX));
// Invalid FOURCC should also print whenever ASCII values are printable.
EXPECT_EQ("fake", FourCCToString(static_cast<FourCC>(0x66616b65)));
// Invalid FORCC with non-printable values should not give error message.
EXPECT_EQ("0x66616b00", FourCCToString(static_cast<FourCC>(0x66616b00)));
}
TEST_F(MP4StreamParserTest, MediaTrackInfoSourcing) {
EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001F"));
EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2"));
InitializeParser();
ParseMP4File("bear-1280x720-av_frag.mp4", 4096);
EXPECT_EQ(media_tracks_->tracks().size(), 2u);
const MediaTrack& video_track = *(media_tracks_->tracks()[0]);
EXPECT_EQ(video_track.type(), MediaTrack::Video);
EXPECT_EQ(video_track.bytestream_track_id(), 1);
EXPECT_EQ(video_track.kind(), "main");
EXPECT_EQ(video_track.label(), "VideoHandler");
EXPECT_EQ(video_track.language(), "und");
const MediaTrack& audio_track = *(media_tracks_->tracks()[1]);
EXPECT_EQ(audio_track.type(), MediaTrack::Audio);
EXPECT_EQ(audio_track.bytestream_track_id(), 2);
EXPECT_EQ(audio_track.kind(), "main");
EXPECT_EQ(audio_track.label(), "SoundHandler");
EXPECT_EQ(audio_track.language(), "und");
}
TEST_F(MP4StreamParserTest, TextTrackDetection) {
auto params = GetDefaultInitParametersExpectations();
params.detected_text_track_count = 1;
InitializeParserWithInitParametersExpectations(params);
scoped_refptr<DecoderBuffer> buffer =
ReadTestDataFile("bear-1280x720-avt_subt_frag.mp4");
EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2"));
EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001F"));
EXPECT_TRUE(AppendDataInPieces(buffer->data(), buffer->data_size(), 512));
}
TEST_F(MP4StreamParserTest, MultiTrackFile) {
auto params = GetDefaultInitParametersExpectations();
params.duration = base::TimeDelta::FromMilliseconds(4248);
params.liveness = DemuxerStream::LIVENESS_RECORDED;
params.detected_audio_track_count = 2;
params.detected_video_track_count = 2;
InitializeParserWithInitParametersExpectations(params);
EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64000D")).Times(2);
EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2")).Times(2);
ParseMP4File("bbb-320x240-2video-2audio.mp4", 4096);
EXPECT_EQ(media_tracks_->tracks().size(), 4u);
const MediaTrack& video_track1 = *(media_tracks_->tracks()[0]);
EXPECT_EQ(video_track1.type(), MediaTrack::Video);
EXPECT_EQ(video_track1.bytestream_track_id(), 1);
EXPECT_EQ(video_track1.kind(), "main");
EXPECT_EQ(video_track1.label(), "VideoHandler");
EXPECT_EQ(video_track1.language(), "und");
const MediaTrack& audio_track1 = *(media_tracks_->tracks()[1]);
EXPECT_EQ(audio_track1.type(), MediaTrack::Audio);
EXPECT_EQ(audio_track1.bytestream_track_id(), 2);
EXPECT_EQ(audio_track1.kind(), "main");
EXPECT_EQ(audio_track1.label(), "SoundHandler");
EXPECT_EQ(audio_track1.language(), "und");
const MediaTrack& video_track2 = *(media_tracks_->tracks()[2]);
EXPECT_EQ(video_track2.type(), MediaTrack::Video);
EXPECT_EQ(video_track2.bytestream_track_id(), 3);
EXPECT_EQ(video_track2.kind(), "");
EXPECT_EQ(video_track2.label(), "VideoHandler");
EXPECT_EQ(video_track2.language(), "und");
const MediaTrack& audio_track2 = *(media_tracks_->tracks()[3]);
EXPECT_EQ(audio_track2.type(), MediaTrack::Audio);
EXPECT_EQ(audio_track2.bytestream_track_id(), 4);
EXPECT_EQ(audio_track2.kind(), "");
EXPECT_EQ(audio_track2.label(), "SoundHandler");
EXPECT_EQ(audio_track2.language(), "und");
}
} // namespace mp4
} // namespace media
| [
"bino.zh@gmail.com"
] | bino.zh@gmail.com |
f1d1e139fcdd08bdafdf0cb4170f83db117f7a6f | 0254f2ee4fde7362762a32cf8e59612271c63c87 | /src/plugins/server/cache.h | ddda11011834bd9b466d4692415e4747611baddd | [] | no_license | alexey-zayats/athletic | 9a97f7f221bd3671df43ac65642df2916ba42a0b | 0c65552d32a7bf581b03f0311e6764aaa60e1690 | refs/heads/master | 2020-05-22T01:31:14.186306 | 2017-07-10T12:06:58 | 2017-07-10T12:06:58 | 64,463,265 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,466 | h | #ifndef SERVER_CACHE
#define SERVER_CACHE
#include "cacheentry.h"
#include "server_global.h"
class QReadWriteLock;
namespace Server
{
/** @brief A read-write-locked cache structure.
*
* Depending on the Server configuration, this will use one of
* several backends; for example, QCache-based, or memcached-based.
*
* If QCache is used, the cache will be shared between all threads in
* the current process. If memcached is used, the cache will:
* - Perform better (honestly, even though it's out of process)
* - Be shared with any other instances of the same application using
* the same memcached pool.
*
* All backends should lock as neccessary, but you may want to lock at
* an outer scope for performance.
*
* Keep in mind that even with a recursive lock, the locks must be of
* the same type; for example, all the writing calls will deadlock
* if called while a read lock is open.
*
* @section settings Settings
*
* @todo A configuration interface for these needs to be added (probably --configure-cache?)
*
* In the settings file (.ApplicationName), there are several settings for this:
@verbatim
[cache]
backend={RamCache|MemcachedCache}
@endverbatim
*
* RamCache is always available, and gives a cache shared between all requests in the current process.
* Memcached performs better, and depending on the configuration, can be used by multiple processes,
* or even multiple machines.
*
* @subsection ramcache RamCache
*
* RamCache is a simple QCache-backed cache, with just one setting:
*
@verbatim
[RamCache]
maxSize=numberOfBytes
@endverbatim
*
* This allows you to configure the maximum size of the cache
*
* @subsection memcached MemcachedCache
*
* This backend performs better, can be shared amongst a cluster, but is only available if
* Server was built with -DWITH_MEMCACHED_SUPPORT=ON
*
@verbatim
[MemcachedServers]
size=numberOfServers
0/host=foo
0/port=11211
1/host=bar
1/port=11211
...
@endverbatim
*
* If a port is not set, Server uses libmemcached's default - normally 11211.
*
* If the size is zero, or this section is omitted, Server will try to connect to
* a memcached server on localhost, on the default port. If this does not work, the
* application will exit.
*
* @ingroup plugins
*/
class SERVER_EXPORT Cache
{
public:
/// Construct a Cache with the given name.
Cache(const QString& cacheName);
/// Destroy a cache.
~Cache();
/// Remove a key from the cache.
void remove(const QString& key);
/** Retrieve a value from the cache.
*
* If the entry isnt' in the cache, an invalid
* CacheEntry will be returned.
*/
CacheEntry value(const QString& key) const;
/** Set a value in the cache.
*
* If a value already exists with the given key, it is
* overwritten.
*/
void setValue(const QString& key, const CacheEntry& object);
protected:
/// Return a pointer to the QReadWriteLock.
QReadWriteLock* readWriteLock() const;
private:
class Private;
Private* d;
};
}
#endif // SERVER_CACHE
| [
"alexey.zayats@gmail.com"
] | alexey.zayats@gmail.com |
72c8b6139f2f383cad00448c0b5beb49ddd8d5c4 | f4bc78d304fcebd766a7a7d161e6b72d61e10d9a | /code/compiler/include/allscale/compiler/frontend/allscale_frontend.h | 1f5f32405524045b25d1fd071791b8d99a30b13e | [] | no_license | allscale/allscale_compiler | 6a02d655e1a101a9a6afa0c79df7e772fc8abcd6 | 12e5dada431e574b025c572ae5f8819047be12aa | refs/heads/master | 2021-01-12T06:53:34.553070 | 2019-03-19T12:43:15 | 2019-03-19T12:43:15 | 76,847,596 | 5 | 1 | null | 2017-12-01T11:39:58 | 2016-12-19T09:26:03 | C++ | UTF-8 | C++ | false | false | 195 | h |
#pragma once
#include "insieme/frontend/frontend.h"
namespace allscale {
namespace compiler {
namespace frontend {
void configureConversionJob(insieme::frontend::ConversionJob& job);
}
}
}
| [
"peterz@dps.uibk.ac.at"
] | peterz@dps.uibk.ac.at |
d204cabbbdb0d57be2b53ac4a1251e24f1b58838 | b4c2ea1c4edc0b635ecde4f353a0ab390050f6fc | /src/trading-bot/server/if.h | a946ba9f14e0d4bf5e8db422e5d636d7eba6a6dd | [
"ISC",
"MIT",
"LicenseRef-scancode-generic-cla"
] | permissive | KenYuan1987/Krypto-trading-bot | ab5adf0a103d8ad669d90d45d27414defbd564cc | e88cd71a978f2c5db32cb6cabe49aa6af3736b93 | refs/heads/master | 2020-03-29T01:50:31.027125 | 2018-09-18T23:28:11 | 2018-09-18T23:28:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,808 | h | #ifndef K_IF_H_
#define K_IF_H_
namespace K {
class Screen {
public:
virtual void pressme(const mHotkey&, function<void()>) = 0;
virtual void printme(mToScreen *const) = 0;
virtual void waitForUser() = 0;
virtual const int error(const string&, const string&, const bool& = false) = 0;
virtual const string stamp() = 0;
virtual void logWar(string, string, string = " Warrrrning: ") = 0;
virtual void logUI(const string&) = 0;
virtual void logUIsess(int, string) = 0;
virtual void log(const string&, const string&, const string& = "") = 0;
virtual void switchOff() = 0;
} *screen = nullptr;
class Events {
public:
virtual void deferred(const function<void()>&) = 0;
} *events = nullptr;
class Sqlite {
public:
virtual void backup(mFromDb *const) = 0;
} *sqlite = nullptr;
class Client {
public:
uWS::Hub* socket = nullptr;
virtual void timer_Xs() = 0;
virtual void welcome(mToClient&) = 0;
virtual void clickme(mFromClient&, function<void(const json&)>) = 0;
} *client = nullptr;
class Engine {
#define SQLITE_BACKUP \
SQLITE_BACKUP_LIST \
( SQLITE_BACKUP_CODE )
#define SQLITE_BACKUP_CODE(data) sqlite->backup(&data);
#define SQLITE_BACKUP_LIST(code) \
code( qp ) \
code( wallet.target ) \
code( wallet.safety.trades ) \
code( wallet.profits ) \
code( levels.stats.ewma.fairValue96h ) \
code( levels.stats.ewma ) \
code( levels.stats.stdev )
#define SCREEN_PRINTME \
SCREEN_PRINTME_LIST \
( SCREEN_PRINTME_CODE )
#define SCREEN_PRINTME_CODE(data) screen->printme(&data);
#define SCREEN_PRINTME_LIST(code) \
code( *gw ) \
code( orders ) \
code( wallet.target ) \
code( wallet.safety.trades ) \
code( levels.stats.fairPrice ) \
code( levels.stats.ewma ) \
code( broker.semaphore ) \
code( broker.calculon.quotes ) \
code( broker.calculon.dummyMM )
#define SCREEN_PRESSME \
SCREEN_PRESSME_LIST \
( SCREEN_PRESSME_CODE )
#define SCREEN_PRESSME_CODE(key, fn) screen->pressme(mHotkey::key, [&]() { fn(); });
#define SCREEN_PRESSME_LIST(code) \
code( Q , gw->quit ) \
code( q , gw->quit ) \
code( ESC , broker.semaphore.toggle )
#define CLIENT_WELCOME \
CLIENT_WELCOME_LIST \
( CLIENT_WELCOME_CODE )
#define CLIENT_WELCOME_CODE(data) client->welcome(data);
#define CLIENT_WELCOME_LIST(code) \
code( qp ) \
code( monitor ) \
code( monitor.product ) \
code( orders ) \
code( wallet.target ) \
code( wallet.safety ) \
code( wallet.safety.trades ) \
code( wallet ) \
code( levels.diff ) \
code( levels.stats.takerTrades ) \
code( levels.stats.fairPrice ) \
code( levels.stats ) \
code( broker.semaphore ) \
code( broker.calculon ) \
code( btn.notepad )
#define CLIENT_CLICKME \
CLIENT_CLICKME_LIST \
( CLIENT_CLICKME_CODE )
#define CLIENT_CLICKME_CODE(btn, fn, val) \
client->clickme(btn, [&](const json &butterfly) { fn(val); });
#define CLIENT_CLICKME_LIST(code) \
code( qp , savedQuotingParameters , ) \
code( broker.semaphore , void , ) \
code( btn.notepad , void , ) \
code( btn.submit , manualSendOrder , butterfly ) \
code( btn.cancel , manualCancelOrder , butterfly ) \
code( btn.cancelAll , cancelOrders , ) \
code( btn.cleanTrade , wallet.safety.trades.clearOne , butterfly ) \
code( btn.cleanTradesClosed , wallet.safety.trades.clearClosed , ) \
code( btn.cleanTrades , wallet.safety.trades.clearAll , )
public:
mButtons btn;
mMonitor monitor;
mOrders orders;
mMarketLevels levels;
mWalletPosition wallet;
mBroker broker;
Engine()
: levels(orders, monitor.product)
, wallet(orders, levels.stats.ewma.targetPositionAutoPercentage, levels.fairValue)
, broker(orders, monitor.product, levels, wallet)
{};
void savedQuotingParameters() {
broker.calculon.dummyMM.mode("saved");
levels.stats.ewma.calcFromHistory();
};
void timer_1s(const unsigned int &tick) {
if (levels.warn_empty()) return;
levels.timer_1s();
if (!(tick % 60)) {
levels.timer_60s();
monitor.timer_60s();
}
wallet.safety.timer_1s();
calcQuotes();
};
void calcQuotes() {
if (broker.ready() and levels.ready() and wallet.ready()) {
if (broker.calcQuotes()) {
quote2orders(broker.calculon.quotes.ask);
quote2orders(broker.calculon.quotes.bid);
} else cancelOrders();
}
broker.clear();
};
void quote2orders(mQuote "e) {
const vector<mOrder*> abandoned = broker.abandon(quote);
const bool replace = gw->askForReplace
and !(quote.empty() or abandoned.empty());
for_each(
abandoned.begin(), abandoned.end() - (replace ? 1 : 0),
[&](mOrder *const it) {
cancelOrder(it);
}
);
if (quote.empty()) return;
if (replace)
replaceOrder(quote.price, quote.isPong, abandoned.back());
else placeOrder(mOrder(
gw->randId(), quote.side, quote.price, quote.size, quote.isPong
));
monitor.tick_orders();
};
void cancelOrders() {
for (mOrder *const it : orders.working())
cancelOrder(it);
};
void manualSendOrder(mOrder raw) {
raw.orderId = gw->randId();
placeOrder(raw);
};
void manualCancelOrder(const mRandId &orderId) {
cancelOrder(orders.find(orderId));
};
private:
void placeOrder(const mOrder &raw) {
gw->place(orders.upsert(raw));
};
void replaceOrder(const mPrice &price, const bool &isPong, mOrder *const order) {
if (orders.replace(price, isPong, order))
gw->replace(order);
};
void cancelOrder(mOrder *const order) {
if (orders.cancel(order))
gw->cancel(order);
};
} *engine = nullptr;
}
#endif | [
"ctubio@users.noreply.github.com"
] | ctubio@users.noreply.github.com |
9eeac77a900e9bac8838f010d6d4fb70a015e4cb | bd3bcdce42c9e28364bfcc0615c4955a41fc7c1a | /vfd_demo/vfd_demo.ino | 782e8254a5f6d9417d60a33e8a5bfdfc3cdfbf1f | [] | no_license | DevSeq/hp-VFD | 8a91f34ded77dc3d56cf11b47ab0f12adbb55840 | 238c058adb41148dacef9c56b1bff8214108f65b | refs/heads/master | 2021-05-26T18:51:44.576644 | 2013-06-27T11:45:14 | 2013-06-27T11:45:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,010 | ino | /*
M66004Vfd and HpLaserJetControl libraries - Demo
Demonstrates the use a control/display panel from a
HP LaserJet 4 printer.
This sketch:
* Sets all pixels and flashes the LEDs for approximately 1 second.
* Prints "Hello, world!" to the display and flahses a heart beat.
* Sets LEDs on/off based on button presses.
Not all models of printer have the same pinout. For the model tested,
the 10 pin dual row connector was connected as follows:
* Pins 1, 2 and/or 3 connected to Arduino ground.
* Pins 4 and/or 5 connected to Arduino +5V.
* Pins 6 through 10 connected to Arduino pins 6 through 10 respectively.
Originally created 21 March 2011
This example code is in the public domain.
http://arduino.cc/playground/Main/M66004Vfd
*/
#include <M66004Vfd.h> // VFD library.
#include <HpLaserJetControl.h> // Button and LED library.
M66004Vfd vfd(8, 6, 7);
HpLaserJetControl control(9, 6, 7, 10);
//control.wasButtonPressed(#) is a toggle
//control.isButtonPressed(#) is a continuous function
//control.wasButtonReleased(#) is a toggle
// Out custom characters.
byte openHeart[8] = {
0b00000,
0b01010,
0b10101,
0b10001,
0b01010,
0b00100,
0b00000,
0b00000
};
byte filledHeart[8] = {
0b00000,
0b01010,
0b11111,
0b11111,
0b01110,
0b00100,
0b00000,
0b00000
};
// Does a flashing sequence with the LEDs.
void StartupLedSequence()
{
static const uint8_t LED_ON_TIME_IN_MS = 75;
for (uint8_t i=0; i < 5; i++)
{
control.setLedState(1, HIGH);
delay(LED_ON_TIME_IN_MS);
control.setLedState(1, LOW);
control.setLedState(2, HIGH);
delay(LED_ON_TIME_IN_MS);
control.setLedState(2, LOW);
control.setLedState(0, HIGH);
delay(LED_ON_TIME_IN_MS);
control.setLedState(0, LOW);
}
delay(LED_ON_TIME_IN_MS);
for (uint8_t i=0; i < 2; i++)
{
delay(LED_ON_TIME_IN_MS);
control.setLedState(0, HIGH);
control.setLedState(1, HIGH);
control.setLedState(2, HIGH);
delay(LED_ON_TIME_IN_MS * (i*2+1));
control.setLedState(0, LOW);
control.setLedState(1, LOW);
control.setLedState(2, LOW);
}
}
// We call this each frame to process button presses and update LED's accordingly.
void UpdateButtonsAndLeds()
{
// Top row of buttons being pressed toggles.
if (control.wasButtonPressed(0))
{
Serial.println("button 0 pressed");
}
if (control.wasButtonPressed(1) && !control.isButtonPressed(7))
{
Serial.println("button 1 pressed");
}
if (control.wasButtonPressed(2))
{
Serial.println("button 2 pressed");
}
if (control.wasButtonPressed(3))
{
Serial.println("button 3 pressed");
}
if (control.wasButtonPressed(4))
{
Serial.println("button 4 pressed");
}
if (control.wasButtonPressed(5))
{
Serial.println("button 5 pressed");
}
if (control.wasButtonPressed(6))
{
Serial.println("button 6 pressed");
}
if (control.wasButtonPressed(7) && !control.isButtonPressed(1))
{
Serial.println("button 7 pressed");
}
if ((control.wasButtonPressed(7) && control.isButtonPressed(7)) || (control.wasButtonPressed(1) && control.isButtonPressed(7)))
{
Serial.println("button 8 pressed");
}
}
void setup() {
Serial.begin(9600);
// Prepare the VFD library for use.
vfd.begin(16, 1);
// Create open as custom character 0. Note that this display supports 16 custom characters.
vfd.createChar(0, openHeart);
// Create filled heart as custom character 1.
vfd.createChar(1, filledHeart);
if (control.isDeviceAttached()) // Test that isDeviceAttached() works correctly
{
// Sets all pixels on the display.
vfd.allDisplay();
// LED flashing sequence.
StartupLedSequence();
// Enables normal character display.
vfd.display();
}
// Print some text to the display.
vfd.print("Hello, world!");
}
void loop() {
UpdateButtonsAndLeds();
// Draw heart beat.
vfd.setCursor(14, 0);
vfd.write(((millis() % 1000) < 250) ? 1 : 0);
}
| [
"abzman2000@gmail.com"
] | abzman2000@gmail.com |
57a36d4fe0d245a5190e0ca3e8a498921939056b | fa4c26316e29e18e8b34f8ee22011d748985dae0 | /Native/animcontrol.h | 3531eb11cfec8c94f1288f3adaa4c70f74091520 | [] | no_license | shoff/ShadowbaneCacheViewer | 6024a412a57d5790bd89f893e03562027f00165e | cc42629430adff108015fca9d04a7b8b237f5aed | refs/heads/main | 2023-05-25T19:03:31.569467 | 2022-08-27T19:33:43 | 2022-08-27T19:33:43 | 37,615,646 | 7 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 401 | h |
#pragma once
#include "stdafx.h"
#include "skeleton.h"
#include "enums.h"
class AnimControl: public wxWindow
{
DECLARE_CLASS(AnimControl)
DECLARE_EVENT_TABLE()
wxComboBox *animList;
unsigned int selectedAnim;
Skeleton *skeleton;
public:
AnimControl(wxWindow* parent, wxWindowID id);
~AnimControl();
void OnAnim(wxCommandEvent &event);
void UpdateSkeleton(Skeleton *s);
};
// -- | [
"smhoff256@gmail.com"
] | smhoff256@gmail.com |
f723322f6962769feb404d5d81ac24ec1216abdc | e572189d60a70df27b95fc84b63cc24048b90d09 | /bjoj/3143.cpp | 9eba49e8eee23c9e4979c1b79aad4a8db683c0eb | [] | no_license | namhong2001/Algo | 00f70a0f6132ddf7a024aa3fc98ec999fef6d825 | a58f0cb482b43c6221f0a2dd926dde36858ab37e | refs/heads/master | 2020-05-22T12:29:30.010321 | 2020-05-17T06:16:14 | 2020-05-17T06:16:14 | 186,338,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 500 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> aset(n);
vector<pair<int,int>> bset(n);
for (int i=0; i<n; ++i) {
cin >> aset[i];
}
for (int i=0; i<n; ++i) {
int a, b;
cin >> a >> b;
bset[i] = {a,b};
}
sort(aset.begin(), aset.end());
sort(bset.begin(), bset.end());
priority_queue<pair<int,int>> pq;
int ans = 0;
int bidx = 0;
for (int a : aset) {
| [
"namhong2001@gmail.com"
] | namhong2001@gmail.com |
1ed3c7a4038fd2644b65bbfe9c83598e55c993af | 677ee07ddf148ccb7de362ca6e4f55e56ba77171 | /FrogPlay/RealWndDlg_URL.h | 2f5324fdd67b8279d2c6cfbd79cef3daa32b2e10 | [
"MIT"
] | permissive | zhuyanbing/SouiDemo | 126d0c00af4ec13fb0d4e8ebc7c5399997ad7be2 | 09b0151a81e5d1552b05938b7aede0f7a9617cc4 | refs/heads/master | 2020-03-30T05:38:09.272310 | 2018-06-30T11:44:17 | 2018-06-30T11:44:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 915 | h | #pragma once
#include "MainDlg.h"
class CRealWndDlg_URL : public SHostWnd
{
public:
CRealWndDlg_URL():SHostWnd(_T("LAYOUT:XML_Readwnd_url")) {}
~CRealWndDlg_URL(void){}
void On_Open_URLBtn()
{
SEdit *m_URL_text = FindChildByID2<SEdit>(8001);
if (m_URL_text)
{
if (m_URL_text->GetWindowTextW().IsEmpty())
{
CRect rc = m_URL_text->GetWindowRect();
ClientToScreen(&rc);
CTipWnd::ShowTip(rc.right, rc.top, CTipWnd::AT_LEFT_BOTTOM, _T("地址错误!\\n地址为空,无法解析"));
return;
}
::SendMessageW(SApplication::getSingleton().GetMainWnd(), MS_REALWND_URLPLAY, 0, (LPARAM)(LPCTSTR)m_URL_text->GetWindowTextW());
}
}
protected:
//soui消息
EVENT_MAP_BEGIN()
EVENT_ID_COMMAND(8000, On_Open_URLBtn)
EVENT_MAP_END()
//消息映射表
BEGIN_MSG_MAP_EX(CRealWndDlg_URL)
CHAIN_MSG_MAP(SHostWnd)
REFLECT_NOTIFICATIONS_EX()
END_MSG_MAP()
private:
};
| [
"kklvzl@gmail.com"
] | kklvzl@gmail.com |
1c306778e44d9a6cfa9a9d27954a5b91a57ca770 | 8d0b9126c6a6002ef3d228e024f7b5bd4742aaad | /hammerblade/torch/kernel/kernel_conv.cpp | 59ed857fe518cfaa6ee0fb5d50c0d0c7b076fdf1 | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | mchao409/hb-pytorch | f667b3857b3d7ed7c40ac7c985fd9700a61da3c1 | 3c28bb5b3d79e51a719e523fbe108fdd1915d3cd | refs/heads/master | 2021-05-23T11:07:24.432230 | 2020-05-26T01:45:20 | 2020-05-26T01:45:22 | 253,257,752 | 0 | 0 | NOASSERTION | 2020-04-05T14:45:09 | 2020-04-05T14:45:09 | null | UTF-8 | C++ | false | false | 8,884 | cpp | //====================================================================
// Convolution kernel
// 03/08/2020 Bandhav Veluri
//====================================================================
#include <kernel_common.hpp>
// We wrap all external-facing C++ kernels with `extern "C"` to
// prevent name mangling
extern "C" {
__attribute__ ((noinline)) int tensorlib_convolution_forward(
hb_tensor_t* output,
hb_tensor_t* input,
hb_tensor_t* weight,
hb_vector_t* padding,
hb_vector_t* strides) {
auto y = HBTensor<float>(output);
auto x = HBTensor<float>(input);
auto w = HBTensor<float>(weight);
auto p = HBVector<uint32_t>(padding);
auto s = HBVector<uint32_t>(strides);
// Conv2d parameters
auto N = y.dim(0); // number of minibatches
auto Cout = y.dim(1); // number of output channels
auto Hout = y.dim(2);
auto Wout = y.dim(3);
auto Cin = x.dim(1); // number of input channels
auto Hin = x.dim(2);
auto Win = x.dim(3);
auto Kh = w.dim(2);
auto Kw = w.dim(3);
auto Sh = s[0];
auto Sw = s[1];
auto Ph = p[0];
auto Pw = p[1];
// Start profiling
bsg_cuda_print_stat_kernel_start();
// Preliminary single tile implementation
//
// Grows O(^5) with image size:
// N x Cout x Cin x H x W
// Kernel loops are constant-time
if(__bsg_id == 0) {
for(uint32_t n = 0; n < N; ++n)
for(uint32_t co = 0; co < Cout; ++co)
for(uint32_t yh = 0; yh < Hout; ++yh)
for(uint32_t yw = 0; yw < Wout; ++yw)
for(uint32_t ci = 0; ci < Cin; ++ci)
for(uint32_t kh = 0; kh < Kh; ++kh)
for(uint32_t kw = 0; kw < Kw; ++kw) {
if((ci + kh + kw) == 0) {
y(n, co, yh, yw) = 0.0;
}
int32_t xh = Sh * yh - Ph + kh;
int32_t xw = Sw * yw - Pw + kw;
if(xh >= 0 && xh < Hin && xw >= 0 && xw < Win) {
y(n, co, yh, yw) += x(n, ci, xh, xw) * w(co, ci, kh, kw);
} // else 0
}
}
// End profiling
bsg_cuda_print_stat_kernel_end();
return 0;
}
__attribute__ ((noinline)) int tensorlib_convolution_add_bias(
hb_tensor_t* output,
hb_tensor_t* bias) {
auto y = (float*) ((intptr_t) output->data);
auto y_strides = (uint32_t*) ((intptr_t) output->strides);
auto b = (float*) ((intptr_t) bias->data);
auto N = output->N; // total number of elements in the output
auto out_ch_stride = y_strides[1]; // output channel stride
auto nb = bias->N; // number of elements in the bias
// Calculate elements per tile
uint32_t len_per_tile = N / (bsg_tiles_X * bsg_tiles_Y) + 1;
uint32_t start = len_per_tile * __bsg_id;
uint32_t end = start + len_per_tile;
end = (end > N) ? N : end;
// Start profiling
bsg_cuda_print_stat_kernel_start();
for(int i = start; i < end; ++i) {
float bias = b[(i / out_ch_stride) % nb];
y[i] += bias;
}
// End profiling
bsg_cuda_print_stat_kernel_end();
return 0;
}
__attribute__ ((noinline)) int tensorlib_convolution_backward_input(
hb_tensor_t* grad_input,
hb_tensor_t* grad_output,
hb_tensor_t* weight,
hb_vector_t* padding,
hb_vector_t* strides) {
auto x = HBTensor<float>(grad_input);
auto y = HBTensor<float>(grad_output);
auto w = HBTensor<float>(weight);
auto p = HBVector<uint32_t>(padding);
auto s = HBVector<uint32_t>(strides);
// Conv2d parameters
auto N = y.dim(0); // number of minibatches
auto Cout = y.dim(1); // number of output channels
auto Hout = y.dim(2);
auto Wout = y.dim(3);
auto Cin = x.dim(1); // number of input channels
auto Hin = x.dim(2);
auto Win = x.dim(3);
auto Kh = w.dim(2);
auto Kw = w.dim(3);
auto Sh = s[0];
auto Sw = s[1];
auto Ph = p[0];
auto Pw = p[1];
// Start profiling
bsg_cuda_print_stat_kernel_start();
// Preliminary single tile implementation
//
// Grows O(^5) with image size:
// N x Cout x Cin x H x W
// Kernel loops are constant-time
if(__bsg_id == 0) {
// init input grads
for(uint32_t n = 0; n < N; ++n)
for(uint32_t ci = 0; ci < Cin; ++ci)
for(uint32_t xh = 0; xh < Hin; ++xh)
for(uint32_t xw = 0; xw < Win; ++xw)
x(n, ci, xh, xw) = 0.0;
for(uint32_t n = 0; n < N; ++n)
for(uint32_t co = 0; co < Cout; ++co)
for(uint32_t yh = 0; yh < Hout; ++yh)
for(uint32_t yw = 0; yw < Wout; ++yw)
for(uint32_t ci = 0; ci < Cin; ++ci)
for(uint32_t kh = 0; kh < Kh; ++kh)
for(uint32_t kw = 0; kw < Kw; ++kw) {
int32_t xh = Sh * yh - Ph + kh;
int32_t xw = Sw * yw - Pw + kw;
if(xh >= 0 && xh < Hin && xw >= 0 && xw < Win) {
x(n, ci, xh, xw) += y(n, co, yh, yw) * w(co, ci, kh, kw);
} // else 0
}
}
// End profiling
bsg_cuda_print_stat_kernel_end();
return 0;
}
__attribute__ ((noinline)) int tensorlib_convolution_backward_weight(
hb_tensor_t* grad_weight,
hb_tensor_t* grad_output,
hb_tensor_t* input,
hb_vector_t* padding,
hb_vector_t* strides) {
auto x = HBTensor<float>(input);
auto y = HBTensor<float>(grad_output);
auto w = HBTensor<float>(grad_weight);
auto p = HBVector<uint32_t>(padding);
auto s = HBVector<uint32_t>(strides);
// Conv2d parameters
auto N = y.dim(0); // number of minibatches
auto Cout = y.dim(1); // number of output channels
auto Hout = y.dim(2);
auto Wout = y.dim(3);
auto Cin = x.dim(1); // number of input channels
auto Hin = x.dim(2);
auto Win = x.dim(3);
auto Kh = w.dim(2);
auto Kw = w.dim(3);
auto Sh = s[0];
auto Sw = s[1];
auto Ph = p[0];
auto Pw = p[1];
// Start profiling
bsg_cuda_print_stat_kernel_start();
// Preliminary single tile implementation
//
// Grows O(^5) with image size:
// N x Cout x Cin x H x W
// Kernel loops are constant-time
if(__bsg_id == 0) {
// init weight grad
for(uint32_t ci = 0; ci < Cin; ++ci)
for(uint32_t co = 0; co < Cout; ++co)
for(uint32_t kh = 0; kh < Kh; ++kh)
for(uint32_t kw = 0; kw < Kw; ++kw)
w(co, ci, kh, kw) = 0.0f;
for(uint32_t n = 0; n < N; ++n)
for(uint32_t co = 0; co < Cout; ++co)
for(uint32_t yh = 0; yh < Hout; ++yh)
for(uint32_t yw = 0; yw < Wout; ++yw)
for(uint32_t ci = 0; ci < Cin; ++ci)
for(uint32_t kh = 0; kh < Kh; ++kh)
for(uint32_t kw = 0; kw < Kw; ++kw) {
int32_t xh = Sh * yh - Ph + kh;
int32_t xw = Sw * yw - Pw + kw;
if(xh >= 0 && xh < Hin && xw >= 0 && xw < Win) {
w(co, ci, kh, kw) += y(n, co, yh, yw) * x(n, ci, xh, xw);
} // else 0
}
}
// End profiling
bsg_cuda_print_stat_kernel_end();
return 0;
}
__attribute__ ((noinline)) int tensorlib_convolution_backward_bias(
hb_tensor_t* grad_bias,
hb_tensor_t* grad_output) {
auto gb = HBTensor<float>(grad_bias);
auto y = HBTensor<float>(grad_output);
auto N = y.dim(0); // number of minibatches
auto Cout = y.dim(1); // number of output channels
auto Hout = y.dim(2);
auto Wout = y.dim(3);
// Start profiling
bsg_cuda_print_stat_kernel_start();
if(__bsg_id == 0) {
for(uint32_t n = 0; n < N; ++n)
for(uint32_t co = 0; co < Cout; ++co)
for(uint32_t yh = 0; yh < Hout; ++yh)
for(uint32_t yw = 0; yw < Wout; ++yw) {
if((n + yh + yw) == 0)
gb(co) = 0.0f;
gb(co) += y(n, co, yh, yw);
}
}
// End profiling
bsg_cuda_print_stat_kernel_end();
return 0;
}
HB_EMUL_REG_KERNEL(tensorlib_convolution_forward,
hb_tensor_t*, hb_tensor_t*, hb_tensor_t*,
hb_vector_t*, hb_vector_t*);
HB_EMUL_REG_KERNEL(tensorlib_convolution_add_bias,
hb_tensor_t*, hb_tensor_t*);
HB_EMUL_REG_KERNEL(tensorlib_convolution_backward_input,
hb_tensor_t*, hb_tensor_t*, hb_tensor_t*,
hb_vector_t*, hb_vector_t*);
HB_EMUL_REG_KERNEL(tensorlib_convolution_backward_weight,
hb_tensor_t*, hb_tensor_t*, hb_tensor_t*,
hb_vector_t*, hb_vector_t*);
HB_EMUL_REG_KERNEL(tensorlib_convolution_backward_bias,
hb_tensor_t*, hb_tensor_t*);
}
| [
"bandhav.veluri00@gmail.com"
] | bandhav.veluri00@gmail.com |
ba12f11349c9275c670c072561987c8dbc469656 | e53074d668e8eea241e2afa5aa42890bedb78cd9 | /Project1/Project1/Source/Engine/GraphicsSystem/Description/CommandQueueDesc.h | 5581c2dab347b8348fbe1bbcd4b1c8b53fe8b249 | [] | no_license | ReU1107/Project1 | 9f1e2ab128744c321f56219679cdb2a33072dd9f | dfae75c51981c29a5a578b1e754524476d1a6809 | refs/heads/master | 2020-12-26T19:13:20.864694 | 2020-10-29T11:51:13 | 2020-10-29T11:51:13 | 237,610,628 | 1 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 293 | h | #pragma once
#include <cstdint>
namespace Engine
{
namespace GraphicsSystem
{
enum class CommandQueuePriority : uint8_t;
enum class CommandListType : uint8_t;
struct CommandQueueDesc
{
CommandListType type; // タイプ
CommandQueuePriority priority; // 優先度
};
}
} | [
"reu1107@yahoo.co.jp"
] | reu1107@yahoo.co.jp |
94598c38fdbf5bc9e8eabec4987a841b45b0a945 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /src/library/kernel_serializer.cpp | 1f9880ac3fb5f38022fe8e4af51d400fd9066b73 | [
"Apache-2.0"
] | permissive | soonhokong/lean | cb8aa01055ffe2af0fb99a16b4cda8463b882cd1 | 38607e3eb57f57f77c0ac114ad169e9e4262e24f | refs/heads/master | 2021-01-21T00:01:24.081719 | 2015-12-22T06:45:37 | 2016-10-10T18:02:27 | 11,513,992 | 2 | 0 | null | 2014-06-03T02:38:22 | 2013-07-18T21:17:15 | C++ | UTF-8 | C++ | false | false | 15,292 | cpp | /*
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <string>
#include "util/object_serializer.h"
#include "kernel/expr.h"
#include "kernel/declaration.h"
#include "library/annotation.h"
#include "library/max_sharing.h"
#include "library/kernel_serializer.h"
// Procedures for serializing and deserializing kernel objects (levels, exprs, declarations)
namespace lean {
// Universe level serialization
class level_serializer : public object_serializer<level, level::ptr_hash, level::ptr_eq> {
typedef object_serializer<level, level::ptr_hash, level::ptr_eq> super;
public:
void write(level const & l) {
super::write(l, [&]() {
serializer & s = get_owner();
auto k = kind(l);
s << static_cast<char>(k);
switch (k) {
case level_kind::Zero: break;
case level_kind::Param: s << param_id(l); break;
case level_kind::Global: s << global_id(l); break;
case level_kind::Meta: s << meta_id(l); break;
case level_kind::Max: write(max_lhs(l)); write(max_rhs(l)); break;
case level_kind::IMax: write(imax_lhs(l)); write(imax_rhs(l)); break;
case level_kind::Succ: write(succ_of(l)); break;
}
});
}
};
class level_deserializer : public object_deserializer<level> {
typedef object_deserializer<level> super;
public:
level read() {
return super::read([&]() -> level {
deserializer & d = get_owner();
auto k = static_cast<level_kind>(d.read_char());
switch (k) {
case level_kind::Zero:
return mk_level_zero();
case level_kind::Param:
return mk_param_univ(read_name(d));
case level_kind::Global:
return mk_global_univ(read_name(d));
case level_kind::Meta:
return mk_meta_univ(read_name(d));
case level_kind::Max: {
level lhs = read();
return mk_max(lhs, read());
}
case level_kind::IMax: {
level lhs = read();
return mk_imax(lhs, read());
}
case level_kind::Succ:
return mk_succ(read());
}
throw corrupted_stream_exception();
});
}
};
struct level_sd {
unsigned m_s_extid;
unsigned m_d_extid;
level_sd() {
m_s_extid = serializer::register_extension([](){
return std::unique_ptr<serializer::extension>(new level_serializer());
});
m_d_extid = deserializer::register_extension([](){
return std::unique_ptr<deserializer::extension>(new level_deserializer());
});
}
};
static level_sd * g_level_sd = nullptr;
serializer & operator<<(serializer & s, level const & n) {
s.get_extension<level_serializer>(g_level_sd->m_s_extid).write(n);
return s;
}
level read_level(deserializer & d) { return d.get_extension<level_deserializer>(g_level_sd->m_d_extid).read(); }
serializer & operator<<(serializer & s, levels const & ls) { return write_list<level>(s, ls); }
levels read_levels(deserializer & d) { return read_list<level>(d, read_level); }
// Expression serialization
typedef std::unordered_map<std::string, macro_definition_cell::reader> macro_readers;
static macro_readers * g_macro_readers = nullptr;
macro_readers & get_macro_readers() {
return *g_macro_readers;
}
void register_macro_deserializer(std::string const & k, macro_definition_cell::reader rd) {
macro_readers & readers = get_macro_readers();
lean_assert(readers.find(k) == readers.end());
readers[k] = rd;
}
static expr read_macro_definition(deserializer & d, unsigned num, expr const * args) {
auto k = d.read_string();
macro_readers & readers = get_macro_readers();
auto it = readers.find(k);
lean_assert(it != readers.end());
return it->second(d, num, args);
}
serializer & operator<<(serializer & s, binder_info const & i) {
unsigned w =
(i.is_rec() ? 8 : 0) +
(i.is_implicit() ? 4 : 0) +
(i.is_strict_implicit() ? 2 : 0) +
(i.is_inst_implicit() ? 1 : 0);
s.write_char(w);
return s;
}
static binder_info read_binder_info(deserializer & d) {
unsigned w = d.read_char();
bool rec = (w & 8) != 0;
bool imp = (w & 4) != 0;
bool s_imp = (w & 2) != 0;
bool i_imp = (w & 1) != 0;
return binder_info(imp, s_imp, i_imp, rec);
}
static name * g_binder_name = nullptr;
class expr_serializer : public object_serializer<expr, expr_hash_alloc, expr_eqp> {
typedef object_serializer<expr, expr_hash_alloc, expr_eqp> super;
max_sharing_fn m_max_sharing_fn;
unsigned m_next_id;
void write_binder_name(serializer & s, name const & a) {
// make sure binding names are atomic string
if (!a.is_atomic() || a.is_numeral()) {
s << g_binder_name->append_after(m_next_id);
m_next_id++;
} else {
s << a;
}
}
void write_core(expr const & a) {
auto k = a.kind();
super::write_core(a, static_cast<char>(k), [&]() {
serializer & s = get_owner();
switch (k) {
case expr_kind::Var:
s << var_idx(a);
break;
case expr_kind::Constant:
lean_assert(!const_name(a).is_anonymous());
s << const_name(a) << const_levels(a);
break;
case expr_kind::Sort:
s << sort_level(a);
break;
case expr_kind::Macro:
s << macro_num_args(a);
for (unsigned i = 0; i < macro_num_args(a); i++) {
write_core(macro_arg(a, i));
}
macro_def(a).write(s);
break;
case expr_kind::App:
write_core(app_fn(a)); write_core(app_arg(a));
break;
case expr_kind::Lambda: case expr_kind::Pi:
lean_assert(!binding_name(a).is_anonymous());
write_binder_name(s, binding_name(a));
s << binding_info(a); write_core(binding_domain(a)); write_core(binding_body(a));
break;
case expr_kind::Let:
s << let_name(a);
write_core(let_type(a)); write_core(let_value(a)); write_core(let_body(a));
break;
case expr_kind::Meta:
lean_assert(!mlocal_name(a).is_anonymous());
s << mlocal_name(a); write_core(mlocal_type(a));
break;
case expr_kind::Local:
lean_assert(!mlocal_name(a).is_anonymous());
lean_assert(!local_pp_name(a).is_anonymous());
s << mlocal_name(a) << local_pp_name(a) << local_info(a); write_core(mlocal_type(a));
break;
}
});
}
public:
expr_serializer() { m_next_id = 0; }
void write(expr const & a) {
write_core(m_max_sharing_fn(a));
}
};
class expr_deserializer : public object_deserializer<expr> {
typedef object_deserializer<expr> super;
public:
expr read_binding(expr_kind k) {
deserializer & d = get_owner();
name n = read_name(d);
binder_info i = read_binder_info(d);
expr t = read();
return mk_binding(k, n, t, read(), i);
}
expr read() {
return super::read_core([&](char c) {
deserializer & d = get_owner();
auto k = static_cast<expr_kind>(c);
switch (k) {
case expr_kind::Var:
return mk_var(d.read_unsigned());
case expr_kind::Constant: {
auto n = read_name(d);
return mk_constant(n, read_levels(d));
}
case expr_kind::Sort:
return mk_sort(read_level(d));
case expr_kind::Macro: {
unsigned n = d.read_unsigned();
buffer<expr> args;
for (unsigned i = 0; i < n; i++) {
args.push_back(read());
}
return read_macro_definition(d, args.size(), args.data());
}
case expr_kind::App: {
expr f = read();
return mk_app(f, read());
}
case expr_kind::Lambda: case expr_kind::Pi:
return read_binding(k);
case expr_kind::Let: {
name n = read_name(d);
expr t = read();
expr v = read();
return mk_let(n, t, v, read());
}
case expr_kind::Meta: {
name n = read_name(d);
return mk_metavar(n, read());
}
case expr_kind::Local: {
name n = read_name(d);
name pp_n = read_name(d);
binder_info bi = read_binder_info(d);
return mk_local(n, pp_n, read(), bi);
}}
throw corrupted_stream_exception(); // LCOV_EXCL_LINE
});
}
};
struct expr_sd {
unsigned m_s_extid;
unsigned m_d_extid;
expr_sd() {
m_s_extid = serializer::register_extension([](){ return std::unique_ptr<serializer::extension>(new expr_serializer()); });
m_d_extid = deserializer::register_extension([](){ return std::unique_ptr<deserializer::extension>(new expr_deserializer()); });
}
};
static expr_sd * g_expr_sd = nullptr;
serializer & operator<<(serializer & s, expr const & n) {
s.get_extension<expr_serializer>(g_expr_sd->m_s_extid).write(n);
return s;
}
expr read_expr(deserializer & d) {
return d.get_extension<expr_deserializer>(g_expr_sd->m_d_extid).read();
}
// Declaration serialization
serializer & operator<<(serializer & s, level_param_names const & ps) { return write_list<name>(s, ps); }
level_param_names read_level_params(deserializer & d) { return read_list<name>(d); }
serializer & operator<<(serializer & s, declaration const & d) {
char k = 0;
if (d.is_definition()) {
k |= 1;
if (d.use_conv_opt())
k |= 2;
}
if (d.is_theorem() || d.is_axiom())
k |= 4;
s << k << d.get_name() << d.get_univ_params() << d.get_type();
if (d.is_definition()) {
s << d.get_value();
s << d.get_height();
}
return s;
}
declaration read_declaration(deserializer & d) {
char k = d.read_char();
bool has_value = (k & 1) != 0;
bool is_th_ax = (k & 4) != 0;
name n = read_name(d);
level_param_names ps = read_level_params(d);
expr t = read_expr(d);
if (has_value) {
expr v = read_expr(d);
unsigned w = d.read_unsigned();
if (is_th_ax) {
return mk_theorem(n, ps, t, v, w);
} else {
bool use_conv_opt = (k & 2) != 0;
return mk_definition(n, ps, t, v, w, use_conv_opt);
}
} else {
if (is_th_ax)
return mk_axiom(n, ps, t);
else
return mk_constant_assumption(n, ps, t);
}
}
using inductive::certified_inductive_decl;
using inductive::inductive_decl;
using inductive::intro_rule;
using inductive::inductive_decl_name;
using inductive::inductive_decl_type;
using inductive::inductive_decl_intros;
using inductive::intro_rule_name;
using inductive::intro_rule_type;
serializer & operator<<(serializer & s, certified_inductive_decl::comp_rule const & r) {
s << r.m_num_bu << r.m_comp_rhs;
return s;
}
certified_inductive_decl::comp_rule read_comp_rule(deserializer & d) {
unsigned n; expr e;
d >> n >> e;
return certified_inductive_decl::comp_rule(n, e);
}
serializer & operator<<(serializer & s, inductive_decl const & d) {
s << inductive_decl_name(d) << inductive_decl_type(d) << length(inductive_decl_intros(d));
for (intro_rule const & r : inductive_decl_intros(d))
s << intro_rule_name(r) << intro_rule_type(r);
return s;
}
inductive_decl read_inductive_decl(deserializer & d) {
name d_name = read_name(d);
expr d_type = read_expr(d);
unsigned num_intros = d.read_unsigned();
buffer<intro_rule> rules;
for (unsigned j = 0; j < num_intros; j++) {
name r_name = read_name(d);
expr r_type = read_expr(d);
rules.push_back(inductive::mk_intro_rule(r_name, r_type));
}
return inductive_decl(d_name, d_type, to_list(rules.begin(), rules.end()));
}
serializer & operator<<(serializer & s, certified_inductive_decl::data const & d) {
s << d.m_decl << d.m_K_target << d.m_num_indices;
write_list<certified_inductive_decl::comp_rule>(s, d.m_comp_rules);
return s;
}
certified_inductive_decl::data read_certified_inductive_decl_data(deserializer & d) {
inductive_decl decl = read_inductive_decl(d);
bool K = d.read_bool();
unsigned nind = d.read_unsigned();
auto rs = read_list<certified_inductive_decl::comp_rule>(d, read_comp_rule);
return certified_inductive_decl::data(decl, K, nind, rs);
}
serializer & operator<<(serializer & s, certified_inductive_decl const & d) {
s << d.get_univ_params() << d.get_num_params() << d.get_num_ACe()
<< d.elim_prop_only() << d.has_dep_elim();
write_list<expr>(s, d.get_elim_types());
write_list<certified_inductive_decl::data>(s, d.get_decl_data());
return s;
}
class read_certified_inductive_decl_fn {
public:
certified_inductive_decl operator()(deserializer & d) {
level_param_names ls = read_list<name>(d, read_name);
unsigned nparams = d.read_unsigned();
unsigned nACe = d.read_unsigned();
bool elim_prop = d.read_bool();
bool dep_elim = d.read_bool();
list<expr> ets = read_list<expr>(d, read_expr);
auto ds = read_list<certified_inductive_decl::data>(d, read_certified_inductive_decl_data);
return certified_inductive_decl(ls, nparams, nACe, elim_prop, dep_elim, ets, ds);
}
};
certified_inductive_decl read_certified_inductive_decl(deserializer & d) {
return read_certified_inductive_decl_fn()(d);
}
void initialize_kernel_serializer() {
g_level_sd = new level_sd();
g_macro_readers = new macro_readers();
g_binder_name = new name("a");
g_expr_sd = new expr_sd();
}
void finalize_kernel_serializer() {
delete g_expr_sd;
delete g_binder_name;
delete g_macro_readers;
delete g_level_sd;
}
}
| [
"leonardo@microsoft.com"
] | leonardo@microsoft.com |
e791f74651ee1ab7bb2912f310514e66e9526c04 | 942aea90ecc3cd50ec8e34de08a9b77876ae80ce | /Dynamic Programming/FloydWarshall.cpp | 07930625bc0128e1cba96a5972f336dcb7871bf1 | [] | no_license | somenathmaji/github-upload | 0f6546997325cab049e299c7b16987d2dafe364d | ab213a8a4118a7b716621253ff23e85fcb0682e6 | refs/heads/master | 2020-05-01T09:12:28.216905 | 2019-03-24T14:50:15 | 2019-03-24T14:50:15 | 177,394,570 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,830 | cpp | #include<iostream>
using namespace std;
#define MAX 9999
// graph implementation using adj matrix
class Graph
{
private:
int V;
int E;
bool isDirected;
int **adjMat;
public:
Graph(int v, int e=0, bool d=false)
{
V = v;
E = e;
isDirected = d;
*adjMat = new int[V];
for(int i=0; i<V; i++)
adjMat[i] = new int[V];
for(int i=0; i<V; i++)
{
for(int j=0; j<V; j++)
adjMat[i][j] = MAX;
}
}
bool addEdge(int src, int dst, int w=1)
{
E++;
adjMat[src][dst] = w;
if(!isDirected)
adjMat[dst][src] = w;
}
void printAdjMat()
{
cout<<"The graph represented as adj matrix : "<<endl;
for(int i=0; i<V; i++)
{
for(int j=0; j<V; j++)
{
if(adjMat[i][j]==MAX)
cout<<"x"<<" ";
else
cout<<adjMat[i][j]<<" ";
}
cout<<endl;
}
}
void floydWarshall()
{
int table[V][V];
// initialize same as adj matrix
for(int i=0; i<V; i++)
{
for(int j=0; j<V; j++)
{
table[i][j] = adjMat[i][j];
}
}
// pick an intermediate vertex
for(int k=0; k<V; k++)
{
// pick a source vertex
for(int i=0; i<V; i++)
{
// pick a destination vertex
for(int j=0; j<V; j++)
{
// if we can get to destination using intermediate vertex and that is shortest
if(table[i][k] + table[k][j] < table[i][j])
table[i][j] = table[i][k] + table[k][j];
}
}
}
// print the solution matrix
cout<<"the solution matrix is : "<<endl;
for(int i=0; i<V; i++)
{
for(int j=0; j<V; j++)
{
if(table[i][j]==MAX)
cout<<"x"<<" ";
else
cout<<table[i][j]<<" ";
}
cout<<endl;
}
}
};
int main()
{
Graph g(5, 0, true);
g.addEdge(0, 1, 1);
g.addEdge(0, 2, 4);
g.addEdge(1, 2, 3);
g.addEdge(1, 3, 2);
g.addEdge(1, 4, 2);
g.addEdge(3, 2, 5);
g.addEdge(3, 1, 1);
g.addEdge(4, 3, 3);
g.printAdjMat();
g.floydWarshall();
return 0;
} | [
"live.somenath@gmail.com"
] | live.somenath@gmail.com |
ab729b4774b1911158b0aa98e06ab772de0a6519 | a6d934968dca366bde7e3d41c05acfcb3606afad | /misc/seaVote.cpp | 1aac7fc77ef39edd1132403a5cfe76ebaae1912a | [] | no_license | nishant-nimbare/cp | ec392e643973f57946601aca5b9bcb6ffe5e8c8e | 55107bede1d6f9bb958c7c0c7da6b9319c8f2dc3 | refs/heads/master | 2022-04-30T15:46:04.549480 | 2022-03-12T15:51:03 | 2022-03-12T15:51:03 | 229,908,243 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 869 | cpp | // https://www.codechef.com/problems/SEAVOTE
#include <iostream>
#include <bits/stdc++.h>
#include <vector>
#include <fstream>
using namespace std;
// inputs
// 3
// 3
// 30 30 30
// 4
// 25 25 25 25
// 2
// 50 51
int main(int argc, char const *argv[])
{
int t;
std::fstream myfile("./input.txt", std::ios_base::in);
myfile>> t;
while(t--){
int n,total=0;
myfile >> n;
int num = n;
while(n--){
int a;
myfile >>a;
total += a;
if(a == 0) num--;
}
cout<<"total "<<total<<endl;
if(total < 100){
cout<<"NO"<<endl;
continue;
}
if(total == 100){
cout<<"YES"<<endl;
continue;
}
if(total > 100){
// cout<<"total >100 "<<total<<" n "<<num<<endl;
if(total<num+100){
// cout<<"total >100 "<<total-100<<endl;
cout<<"YES"<<endl;
}else{
cout<<"NO"<<endl;
}
}
}
return 0;
} | [
"nishantnimbare@gmail.com"
] | nishantnimbare@gmail.com |
94056f408497ba1fc66ed12ccdb3cd06aac5e9cf | f0d560c9bb443e24a707347ac498d386d9b274e3 | /scene.h | aabe6ba59bc393a7d54312ddbf903e7749f6774c | [] | no_license | seamanj/ARAP | e5d7d4166b517fde92965e3a972f12908cbe3e6a | 3a5b1b19a912ff9260ef1d88972bedf860566e0f | refs/heads/master | 2020-05-02T22:12:34.374982 | 2019-06-08T13:37:10 | 2019-06-08T13:37:10 | 178,244,972 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 810 | h | #ifndef SCENE_H
#define SCENE_H
#include "scenenode.h"
#include "scenenodeiterator.h"
#include <QObject>
class Scene : public QObject
{
Q_OBJECT
public:
Scene();
virtual ~Scene();
virtual void render();
SceneNode* root() { return m_root; }
SceneNodeIterator begin() const;
void loadMesh(const QString &filename, glm::mat4 CTM=glm::mat4());
void reset();
void deleteSelectedNodes();
void deleteSelectedMeshes();
void roiSelectedParticles();
void deroiSelectedParticles();
void controlSelectedParticles();
void decontrolSelectedParticles();
void selectPriorGroup();
void selectNextGroup();
void clearSelection();
signals:
void updateTool();
private:
SceneNode* m_root;
void setupLights();
};
#endif // SCENE_H
| [
"tjiang.work@gmail.com"
] | tjiang.work@gmail.com |
f51fbcf85eca2b4e787cb0112626e09730e08e8a | ba8b8f21c24009749dbf1145d0dd6169929e3173 | /src/libraries/xvnode/src/xvnode_manager.cpp | 11f335e814f51736f5f7b603e8417ba2d67cc35f | [] | no_license | Alipipe/TOP-chain | 8acbc370738af887ebf4a3d1ccee52b2813d3511 | d88c18893bfa88ead5752b74874693819cdf406f | refs/heads/main | 2023-07-02T22:37:07.787601 | 2021-02-11T06:50:46 | 2021-02-11T06:50:46 | 357,528,232 | 0 | 0 | null | 2021-04-13T11:29:16 | 2021-04-13T11:29:15 | null | UTF-8 | C++ | false | false | 11,146 | cpp | // Copyright (c) 2017-2018 Telos Foundation & contributors
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "xvnode/xvnode_manager.h"
#include "xcodec/xmsgpack_codec.hpp"
#include "xcrypto/xckey.h"
#include "xdata/xcodec/xmsgpack/xelection_result_store_codec.hpp"
#include "xdata/xdata_common.h"
#include "xstore/xaccount_context.h"
#include "xstore/xstore_error.h"
#include "xvnode/xvnode_factory.h"
#include "xvnode/xvnode.h"
#include <algorithm>
#include <cinttypes>
NS_BEG2(top, vnode)
xtop_vnode_manager::xtop_vnode_manager(observer_ptr<elect::ElectMain> const & elect_main,
observer_ptr<mbus::xmessage_bus_face_t> const & mbus,
observer_ptr<store::xstore_face_t> const & store,
observer_ptr<base::xvblockstore_t> const & block_store,
observer_ptr<time::xchain_time_face_t> const & logic_timer,
observer_ptr<router::xrouter_face_t> const & router,
observer_ptr<vnetwork::xvhost_face_t> const & vhost,
observer_ptr<sync::xsync_object_t> const & sync_object,
observer_ptr<grpcmgr::xgrpc_mgr_t> const & grpc_mgr,
observer_ptr<xunit_service::xcons_service_mgr_face> const & cons_mgr,
observer_ptr<xtxpool_service::xtxpool_service_mgr_face> const & txpool_service_mgr,
observer_ptr<xtxpool::xtxpool_face_t> const & txpool,
observer_ptr<election::cache::xdata_accessor_face_t> const & election_cache_data_accessor)
: m_logic_timer{logic_timer}
, m_vhost{vhost}
, m_vnode_factory{top::make_unique<xvnode_factory_t>(elect_main,
mbus,
store,
block_store,
logic_timer,
router,
vhost,
sync_object,
grpc_mgr,
cons_mgr,
txpool_service_mgr,
txpool,
election_cache_data_accessor)} {
}
xtop_vnode_manager::xtop_vnode_manager(observer_ptr<time::xchain_time_face_t> logic_timer,
observer_ptr<vnetwork::xvhost_face_t> vhost,
std::unique_ptr<xvnode_factory_face_t> vnode_factory)
: m_logic_timer{std::move(logic_timer)}, m_vhost{std::move(vhost)}, m_vnode_factory{std::move(vnode_factory)} {
assert(m_vnode_factory != nullptr);
}
void xtop_vnode_manager::start() {
assert(m_logic_timer != nullptr);
m_logic_timer->watch(chain_timer_watch_name, 1, std::bind(&xtop_vnode_manager::on_timer, this, std::placeholders::_1));
assert(!running());
running(true);
}
void xtop_vnode_manager::stop() {
assert(running());
running(false);
assert(m_logic_timer != nullptr);
m_logic_timer->unwatch(chain_timer_watch_name);
}
std::vector<common::xip2_t> xtop_vnode_manager::handle_election_data(std::unordered_map<common::xcluster_address_t, election::cache::xgroup_update_result_t> const & election_data) {
// if (!running()) {
// xwarn("[vnode mgr] is not running");
// return {};
// }
assert(!election_data.empty());
auto const & host_node_id = m_vhost->host_node_id();
xdbg("[vnode mgr] host %s sees election data size %zu", host_node_id.value().c_str(), election_data.size());
std::vector<common::xip2_t> outdated_xips;
XLOCK(m_nodes_mutex);
for (auto const & group_info : election_data) {
auto const & cluster_address = top::get<common::xcluster_address_t const>(group_info);
auto const & group_update_result = top::get<election::cache::xgroup_update_result_t>(group_info);
auto const & outdated_group = group_update_result.outdated;
auto const & faded_group = group_update_result.faded;
auto const & added_group = group_update_result.added;
assert(added_group != nullptr);
bool vnode_outdated{false};
if (outdated_group != nullptr && outdated_group->contains(host_node_id)) {
auto const & address = outdated_group->node_element(host_node_id)->address();
assert(address.slot_id().has_value());
auto const it = m_all_nodes.find(address);
if (it != std::end(m_all_nodes)) {
vnode_outdated = true;
auto & vnode = top::get<std::shared_ptr<xvnode_face_t>>(*it);
vnode->rotation_status(common::xrotation_status_t::outdated, outdated_group->outdate_time());
xwarn("[vnode mgr] vnode (%p) at address %s will outdate at logic time %" PRIu64, vnode.get(), vnode->address().to_string().c_str(), vnode->outdate_time());
}
}
if (faded_group != nullptr && faded_group->contains(host_node_id)) {
auto const & address = faded_group->node_element(host_node_id)->address();
assert(address.slot_id().has_value());
auto const & it = m_all_nodes.find(address);
if (it != std::end(m_all_nodes)) {
vnode_outdated = false;
auto & vnode = top::get<std::shared_ptr<xvnode_face_t>>(*it);
vnode->rotation_status(common::xrotation_status_t::faded, faded_group->fade_time());
xwarn("[vnode mgr] vnode (%p) at address %s will fade at logic time %" PRIu64, vnode.get(), vnode->address().to_string().c_str(), vnode->fade_time());
}
}
if (added_group->contains(host_node_id)) {
vnode_outdated = false;
auto const & address = added_group->node_element(host_node_id)->address();
assert(address.slot_id().has_value());
auto const it = m_all_nodes.find(address);
if (it != std::end(m_all_nodes)) {
continue;
}
assert(m_vnode_factory);
auto vnode = m_vnode_factory->create_vnode_at(added_group);
assert(vnode->address() == address);
vnode->rotation_status(common::xrotation_status_t::started, added_group->start_time());
xwarn("[vnode mgr] vnode (%p) at address %s will start at logic time %" PRIu64 " associated election blk height %" PRIu64,
vnode.get(),
vnode->address().to_string().c_str(),
vnode->start_time(),
vnode->address().associated_blk_height());
vnode->synchronize();
xwarn("[vnode mgr] vnode (%p) at address %s starts synchronizing", vnode.get(), vnode->address().to_string().c_str());
XATTRIBUTE_MAYBE_UNUSED auto ret = m_all_nodes.insert({address, vnode});
assert(top::get<bool>(ret));
(void)ret;
}
if (vnode_outdated) {
xwarn("[vnode mgr] vnode at address %s is outdated", cluster_address.to_string().c_str());
common::xip2_t xip{cluster_address.network_id(), cluster_address.zone_id(), cluster_address.cluster_id(), cluster_address.group_id()};
outdated_xips.push_back(std::move(xip));
}
}
return outdated_xips;
}
void xtop_vnode_manager::on_timer(time::xchain_time_st const & timer_data) {
if (!running()) {
xwarn("[vnode mgr] is not running");
return;
}
assert(m_election_notify_thread_id != std::this_thread::get_id());
XLOCK_GUARD(m_nodes_mutex) {
// make sure:
// 1. outdate first
// 2. fade second
// 3. start third
for (auto it = std::begin(m_all_nodes); it != std::end(m_all_nodes);) {
auto & vnode = top::get<std::shared_ptr<xvnode_face_t>>(*it);
assert(vnode != nullptr);
switch (vnode->rotation_status(timer_data.xtime_round)) {
case common::xrotation_status_t::outdated: {
vnode->stop();
xwarn("[vnode mgr] vnode (%p) at address %s outdates at logic time %" PRIu64 " current logic time %" PRIu64,
vnode.get(),
vnode->address().to_string().c_str(),
vnode->outdate_time(),
timer_data.xtime_round);
it = m_all_nodes.erase(it);
break;
}
default: {
++it;
break;
}
}
}
for (auto it = std::begin(m_all_nodes); it != std::end(m_all_nodes); ++it) {
auto & vnode = top::get<std::shared_ptr<xvnode_face_t>>(*it);
assert(vnode != nullptr);
switch (vnode->rotation_status(timer_data.xtime_round)) {
case common::xrotation_status_t::outdated: {
assert(false);
break;
}
case common::xrotation_status_t::faded: {
if (!vnode->faded() && vnode->running()) {
vnode->fade();
xwarn("[vnode mgr] vnode (%p) at address %s fades at logic time %" PRIu64 " current logic time %" PRIu64,
vnode.get(),
vnode->address().to_string().c_str(),
vnode->fade_time(),
timer_data.xtime_round);
}
break;
}
default: {
break;
}
}
}
for (auto it = std::begin(m_all_nodes); it != std::end(m_all_nodes); ++it) {
auto & vnode = top::get<std::shared_ptr<xvnode_face_t>>(*it);
assert(vnode != nullptr);
switch (vnode->rotation_status(timer_data.xtime_round)) {
case common::xrotation_status_t::outdated: {
assert(false);
break;
}
case common::xrotation_status_t::started: {
if (!vnode->running()) {
vnode->start();
xwarn("[vnode mgr] vnode (%p) at address %s starts at logic time %" PRIu64 " current logic time %" PRIu64,
vnode.get(),
vnode->address().to_string().c_str(),
vnode->start_time(),
timer_data.xtime_round);
}
break;
}
default: {
break;
}
}
}
}
}
NS_END2
| [
"zql0114@gmail.com"
] | zql0114@gmail.com |
b5cc33a1a4978fab006e31d404737d57aa3df27b | f7c673d103a0a7261246dbdde75490f8eed918ab | /source/Client/old/source/editor/subscene/GroupedTilePreview.cpp | 19e92d3295b86e9cde70642a62ed2b38b65a17ca | [] | no_license | phisn/PixelJumper2 | 2c69faf83c09136b81befd7a930c19ea0ab521f6 | 842878cb3e44113cc2753abe889de62921242266 | refs/heads/master | 2022-11-14T04:44:00.690120 | 2020-07-06T09:38:38 | 2020-07-06T09:38:38 | 277,490,158 | 0 | 0 | null | 2020-07-06T09:38:42 | 2020-07-06T08:48:52 | C++ | UTF-8 | C++ | false | false | 32 | cpp | #include "GroupedTilePreview.h"
| [
"phisn@outlook.de"
] | phisn@outlook.de |
bde8c42c31a8d046b7e260cb2d0f507fb1880669 | 239f22dcc4b79d7afb86796bee42128025ec5aae | /trainingthread.cpp | e8339823d2f772b7142548a8685eb4d545b27119 | [
"LicenseRef-scancode-public-domain"
] | permissive | 2php/ConvolutionalNeuralNetworkDemo | aef1dd4f616f3287fc3e0cad713b9b67fbabfe04 | 13331cfa8888dc28d5f5b55322eb1c21ee45c571 | refs/heads/master | 2021-01-21T03:38:37.649203 | 2016-07-19T14:40:06 | 2016-07-19T14:40:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,703 | cpp | #include "trainingthread.h"
TrainingThread::TrainingThread(MainWindow *_window, double _learningRate, double _momentum, double _weightDecay)
{
stopRequested=false;
window=_window;
mutex=new QMutex();
learningRate=_learningRate;
momentum=_momentum;
weightDecay=_weightDecay;
}
TrainingThread::~TrainingThread()
{
mutex->unlock();
delete mutex;
}
void TrainingThread::run()
{
srand(time(0));
for(/*;;*/uint64_t cycle=0;cycle<100000000;cycle++)
{
if(stopRequested)
break;
uint32_t imageId=((double)rand())/((double)RAND_MAX)*IMAGES_PER_BATCH*BATCH_COUNT;
uint8_t imageLabel=window->imageLabels[imageId];
//forwardPass(imageId);
// Input for first layer: Image data
double ***previousLayerOutput=window->imageInputData[imageId];
// Forward pass
// MODIFY IN MAINWINDOW.CPP, TOO!
for(uint32_t layerIndex=0;layerIndex<LAYER_COUNT;layerIndex++)
{
CNNLayer *thisLayer=window->layers[layerIndex];
double ***output=thisLayer->forwardPass(previousLayerOutput);
if(layerIndex>0)
CNNLayer::freeArray(previousLayerOutput,thisLayer->previousLayerFeatureMapCount,thisLayer->previousLayerSingleFeatureMapHeight);
previousLayerOutput=output;
}
// previousLayerOutput now contains the output of the last layer
// Backward pass
double ***higherLayerInputDiffs=0;
for(uint32_t _layerIndex=LAYER_COUNT;_layerIndex>0;_layerIndex--) // _layerIndex is of type uint32_t and cannot be <0, therefore we have to artificially increment it by 1
{
uint32_t layerIndex=_layerIndex-1; // The actual index of this layer
CNNLayer *thisLayer=window->layers[layerIndex];
CNNLayer *higherLayer=layerIndex<LAYER_COUNT-1?window->layers[layerIndex+1]:0;
double ***inputDiffs=0;
double ****weightDiffs=0;
double *biasDiffs=0;
// Error in calculateDiffs (tested)
thisLayer->calculateDiffs(weightDiffs,biasDiffs,higherLayerInputDiffs,inputDiffs,imageLabel);
thisLayer->applyDiffs(weightDiffs,biasDiffs,learningRate,momentum,weightDecay);
if(weightDiffs!=0)
{
if(thisLayer->type==CNN_LAYER_TYPE_CONV)
CNNLayer::freeWeightTypeArray(weightDiffs,thisLayer->previousLayerFeatureMapCount,thisLayer->featureMapCount,thisLayer->receptiveFieldHeight,thisLayer->receptiveFieldWidth);
else if(thisLayer->type==CNN_LAYER_TYPE_FC)
CNNLayer::freeWeightTypeArray(weightDiffs,thisLayer->previousLayerFeatureMapCount,thisLayer->previousLayerSingleFeatureMapHeight,thisLayer->previousLayerSingleFeatureMapWidth,thisLayer->featureMapCount);
}
if(biasDiffs!=0)
CNNLayer::freeBiasTypeArray(biasDiffs);
if(layerIndex<LAYER_COUNT-1)
CNNLayer::freeArray(higherLayerInputDiffs,higherLayer->previousLayerFeatureMapCount,higherLayer->previousLayerSingleFeatureMapHeight);
higherLayerInputDiffs=inputDiffs; // Will be freed when processing the next layer
}
if(higherLayerInputDiffs!=window->desiredOutputValueCache[imageLabel]&&higherLayerInputDiffs!=0)
CNNLayer::freeArray(higherLayerInputDiffs,window->layers[0]->previousLayerFeatureMapCount,window->layers[0]->previousLayerSingleFeatureMapHeight);
// previousLayerOutput now contains the output of the last layer
iterationFinished(imageId,previousLayerOutput);
}
stopRequested=false;
window->training=false;
}
| [
"a.niedental@outlook.com"
] | a.niedental@outlook.com |
ec71fe441e7d08320ce7af0dc763a52006dec537 | 12ac0673d43abcc55c9b7d7a81d0f47848386a6f | /src/Commands/moveServos.cpp | 6bf6dcb0adc1f9610f0aaa0138f8afbdd2cd245d | [] | no_license | plahera/RobotTestNew | c7e425584626a18aaf8240c429fef2fef06109d9 | d2ed375aca7ed8f57c08f9fce88137e9e17bfebb | refs/heads/master | 2021-01-10T06:21:28.745492 | 2016-03-04T01:48:27 | 2016-03-04T01:48:27 | 52,684,882 | 0 | 1 | null | 2016-03-04T01:48:28 | 2016-02-27T19:32:55 | C++ | UTF-8 | C++ | false | false | 2,662 | cpp | // RobotBuilder Version: 2.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// C++ from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
#define hi
#include "moveServos.h"
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR
moveServos::moveServos(): Command() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
Requires(Robot::intakeSubsystem.get());
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
}
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR
// Called just before this Command runs the first time
void moveServos::Initialize() {
}
// Called repeatedly when this Command is scheduled to run
void moveServos::Execute() {
#ifdef hi
if (Robot::oi->getDriveJoy()->GetPOV()==270||Robot::oi->getDriveJoy()->GetPOV()==90) // goes middle
{
//Robot::intakeSubsystem->MoveServoLeft(140);
//Robot::intakeSubsystem->MoveServoRight(50);
Robot::intakeSubsystem->MoveServoLeft(90);
Robot::intakeSubsystem->MoveServoRight(90);
Wait(.05);
//should open it
}
else if (Robot::oi->getDriveJoy()->GetPOV()==0) // goes out.
{
//Robot::intakeSubsystem->MoveServoLeft(180);
//Robot::intakeSubsystem->MoveServoRight(0);
Robot::intakeSubsystem->MoveServoLeft(0);
Robot::intakeSubsystem->MoveServoRight(180);
Wait(.05);
//should close it, first action
}
else if (Robot::oi->getDriveJoy()->GetPOV()==180) //currently goes up
{
//Robot::intakeSubsystem->MoveServoLeft(00);
//Robot::intakeSubsystem->MoveServoRight(180);
Robot::intakeSubsystem->MoveServoLeft(180);
Robot::intakeSubsystem->MoveServoRight(0);
//should go to middle
Wait(.05);
}
SmartDashboard::PutNumber("POV thing", Robot::oi->getDriveJoy()->GetPOV());
#endif
//225-315 left
//315-45 top
//right: 45 -135
//bottom: 135-225
}
// Make this return true when this Command no longer needs to run execute()
bool moveServos::IsFinished() {
return false;
}
// Called once after isFinished returns true
void moveServos::End() {
//Robot::intakeSubsystem->ChangeServoSpeed(0);
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void moveServos::Interrupted() {
//Robot::intakeSubsystem->ChangeServoSpeed(0);
}
| [
"plahera1@hwemail.com"
] | plahera1@hwemail.com |
782a87564857298b1016cf990ca9eaa60b487f43 | 8425574e87365bba72bc45ab9eab9f29b9f3568d | /src/basicMath/Math.h | 078ca914af6a1c403c455616df905677c7344905 | [] | no_license | melisaadin/modedock | 92dd3714928f18f70c621de4760facb43f05b376 | 28fc1398ea8022b85883979a2da6d6451a0a7472 | refs/heads/master | 2023-03-15T15:28:47.042591 | 2019-02-19T07:06:18 | 2019-02-19T07:06:18 | 522,142,100 | 1 | 0 | null | 2022-08-07T07:10:36 | 2022-08-07T07:10:36 | null | UTF-8 | C++ | false | false | 14,575 | h | #ifndef MATH_H_
#define MATH_H_
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <iostream>
#include <GL/gl.h>
using std::vector;
using std::string;
#ifndef MAXFLOAT
#define MAXFLOAT 1.0E+20
#endif
static const double
smallEPS = 1.01E-10,
mediumEPS = 1.01E-5,
largeEPS = 1.01E-3,
Pi = 3.14159265358979,
PiSquared = Pi * Pi,
TwoPi = 2.0 * Pi,
twoPiSqrt = sqrt(2.0*Pi),
FourPi = 4.0 * Pi,
PiOverTwo = Pi / 2.0,
PiOverThree = Pi / 3.0,
TwoPiOverThree= Pi / 1.5, // 120.0
PiOverFour = Pi / 4.0,
OverPi = 1.0 / Pi,
OverTwoPi = 1.0 / TwoPi,
OverFourPi = 1.0 / FourPi,
Infinity = MAXFLOAT,
Tiny = 1.0 / MAXFLOAT,
DegreesToRad = Pi / 180.0,
deg2Rad = DegreesToRad,
RadToDegrees = 180.0 / Pi,
rad2Deg = RadToDegrees,
X = 0.525731112119133606,
Z = 0.850650808352039932
;
static const unsigned short
dim2 = 2,
dim3= 3,
dim4= 4,
dim5 = 5,
dim6 = 6,
dim7 = 7,
dim8 = 8,
dim9 = 9,
dim10 = 10,
dim12 = 12,
dim13 = 13,
dim15 = 15,
dim20 = 20,
dim30 = 30;
static const double sqrt2 = sqrt(2.0);
static const double sqrt2OverTwo = 0.50 * sqrt2;
static const double sqrt3 = sqrt(3.0);
static const double PiOverSix = 0.50 *PiOverThree;
const static double vdata[12][3] = {
{-X, 0.0, Z}, {X, 0.0, Z}, {-X, 0.0, -Z}, {X, 0.0, -Z},
{0.0, Z, X}, {0.0, Z, -X}, {0.0, -Z, X}, {0.0, -Z, -X},
{Z, X, 0.0}, {-Z, X, 0.0}, {Z, -X, 0.0}, {-Z, -X, 0.0}
};
const static unsigned short tindices[20][3] = {
{0,4,1}, {0,9,4}, {9,5,4}, {4,5,8}, {4,8,1},
{8,10,1}, {8,3,10}, {5,3,8}, {5,2,3}, {2,7,3},
{7,10,3}, {7,6,10}, {7,11,6}, {11,0,6}, {0,1,6},
{6,1,10}, {9,0,11}, {9,11,2}, {9,2,5}, {7,2,11}
};
const static unsigned short icosahedronEdge[30][2] = {
{0, 1}, {0, 4}, {0, 6}, {0, 9}, {0, 11}, {1, 4}, {1, 6}, {1, 8},
{1, 10}, {2, 3}, {2, 5}, {2, 7}, {2, 9}, {2, 11}, {3, 5}, {3, 7},
{3, 8}, {3, 10}, {4, 5}, {4, 8}, {4, 9}, {5, 8}, {5, 9}, {6, 7},
{6, 10}, {6, 11}, {7, 10}, {7, 11}, {8, 10}, {9, 11}
};
inline int Odd ( int k ) { return k & 1; }
inline int Even ( int k ) { return !(k & 1); }
inline float Abs ( int x ) { return x > 0 ? x : -x; }
inline float Abs ( float x ) { return x > 0. ? x : -x; }
inline float Abs ( double x ) { return x > 0. ? x : -x; }
inline int iMin ( int x, int y ) { return x < y ? x : y; }
inline int iMax ( int x, int y ) { return x > y ? x : y; }
inline float fMin ( float x, float y ) { return x < y ? x : y; }
inline float fMax ( float x, float y ) { return x > y ? x : y; }
inline double dMin ( double x, double y ) { return x < y ? x : y; }
inline double dMax ( double x, double y ) { return x > y ? x : y; }
inline float Sqr ( int x ) { return x * x; }
inline float Sqr ( float x ) { return x * x; }
inline float Sqr ( double x ) { return x * x; }
inline float Sqrt ( double x ) { return x > 0. ? sqrt(x) : 0.; }
inline float Cubed ( float x ) { return x * x * x; }
inline int Sign ( float x ) { return x > 0. ? 1 : (x < 0. ? -1 : 0); }
inline void Swap ( float &a, float &b ) { float c = a; a = b; b = c; }
inline void Swap ( int &a, int &b ) { int c = a; a = b; b = c; }
inline double Sin ( double x, int n ) { return pow( sin(x), n ); }
inline double Cos ( double x, int n ) { return pow( cos(x), n ); }
inline float ToSin ( double x ) { return Sqrt( 1.0 - Sqr(x) ); }
inline float ToCos ( double x ) { return Sqrt( 1.0 - Sqr(x) ); }
inline float Pythag( double x, double y ) { return Sqrt( x*x + y*y ); }
inline double ArcCos( double x ){
double y;
if( -1.0 <= x && x <= 1.0 ) y = acos( x );
else if( x > 1.0 ) y = 0.0;
else if( x < -1.0 ) y = Pi;
return y;
}
inline double ArcSin( double x ){
if( x < -1.0 ) x = -1.0;
if( x > 1.0 ) x = 1.0;
return asin( x );
}
inline float Clamp( float min, float &x, float max ){
if( x < min ) x = min; else
if( x > max ) x = max;
return x;
}
inline double Clamp( float min, double &x, float max ){
if( x < min ) x = min; else
if( x > max ) x = max;
return x;
}
inline int iMax( int x, int y, int z ){
int t;
if( x >= y && x >= z ) t = x;
else if( y >= z ) t = y;
else t = z;
return t;
}
inline int iMin( int x, int y, int z ){
int t;
if( x <= y && x <= z ) t = x;
else if( y <= z ) t = y;
else t = z;
return t;
}
inline float fMax( float x, float y, float z ){
float t;
if( x >= y && x >= z ) t = x;
else if( y >= z ) t = y;
else t = z;
return t;
}
inline float fMin( float x, float y, float z ){
float t;
if( x <= y && x <= z ) t = x;
else if( y <= z ) t = y;
else t = z;
return t;
}
inline double dMax( double x, double y, double z ){
double t;
if( x >= y && x >= z ) t = x;
else if( y >= z ) t = y;
else t = z;
return t;
}
inline double dMin( double x, double y, double z ){
double t;
if( x <= y && x <= z ) t = x;
else if( y <= z ) t = y;
else t = z;
return t;
}
inline float Pythag( float x, float y, float z ){
return sqrt( x * x + y * y + z * z );
}
/** calculate the angles between two vectors v1 and v2
* The returned angle is in the [0,Pi] range or the cosine value (not the value of angle).
*/
inline double interAngle(double * const v1, double * const v2, const int dim){
double v1Len = 0.0, v2Len = 0.0;
for (int i = 0; i < dim; i++)
v1Len += v1[i]*v1[i];
// v1Len = sqrt(v1Len);
for (int i = 0; i < dim; i++)
v2Len += v2[i]*v2[i];
// v2Len = sqrt(v2Len);
if ( v1Len < Tiny || v2Len < Tiny){
std::cout<<"divide by ZERO in interAngle \n";
exit(1);
}
return ( (v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]) / ( sqrt(v1Len * v2Len) ) );
// return Math.acos(c); //acos [0, PI] so should be OK
}
/** calculate the angles between two vectors v1 and v2
* The returned angle is in the [0,Pi] range or the cosine value (not the value of angle).
*/
inline bool interAngle(double *v1, double *v2, const int dim, double &angle){
double v1Len = 0.0, v2Len = 0.0;
for (int i = 0; i < dim; i++)
v1Len += v1[i]*v1[i];
// v1Len = sqrt(v1Len);
for (int i = 0; i < dim; i++)
v2Len += v2[i]*v2[i];
// v2Len = sqrt(v2Len);
if ( v1Len < Tiny || v2Len < Tiny){
std::cout<<"divide by ZERO in interAngle \n";
return false;
}
angle = (v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]) / ( sqrt(v1Len * v2Len) ) ;
return true;
// return Math.acos(c); //acos [0, PI] so should be OK
}
inline double interAngleF(float *v1, float *v2, const int dim){
float v1Len = 0.0, v2Len = 0.0;
for (int i = 0; i < dim; i++)
v1Len += v1[i]*v1[i];
v1Len = sqrt(v1Len);
for (int i = 0; i < dim; i++)
v2Len += v2[i]*v2[i];
v2Len = sqrt(v2Len);
if ( v1Len < Tiny || v2Len < Tiny){
std::cout<<"divide by ZERO in interAngle \n";
exit(1);
}
return ( (v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]) / (v1Len * v2Len) );
// return Math.acos(c); //acos [0, PI] so should be OK
}
//
//inline bool interAngleD( double *const v1, double *const v2,
// const size_t dim, double& angle){
// double v1Len = 0.0, v2Len = 0.0;
// for (unsigned int i = 0; i < dim; i++)
// v1Len += v1[i] * v1[i];
// v1Len = sqrt(v1Len);
// for (unsigned int i = 0; i < dim; i++)
// v2Len += v2[i] * v2[i];
// v2Len = sqrt(v2Len);
// if ( v1Len < Tiny || v2Len < Tiny){
// cout<<"divide by ZERO in interAngle \n";
// return false;
// }
// double cosValue = 0.0;
// for (unsigned int i = 0; i < dim; i++)
// cosValue += v1[i] * v2[i];
// angle = cosValue / (v1Len * v2Len) ;
// return true;
// // return Math.acos(c); //acos [0, PI] so should be OK
//}
/** cal the directioal cosines of the vector vec */
inline double* dirCos(double *vec, int dim) {
double len = 0.0;
double *dirs = new double[dim];
for (int i = 0; i < dim; i++)
len += vec[i] * vec[i];
len = sqrt(len);
if ( len < Tiny ){
std::cout<<"divide by ZERO in interAngle \n";
exit(1);
}
for (int j=0; j<dim; j++)
dirs[j] = vec[j] / len;
return dirs;
}
/** cal the polar coordinate of the vector vec */
inline double* polarCoord(double *vec, int dim) {
double len = 0.0;
double *dirs = new double[dim];
for (int i = 0; i < dim; i++)
len += vec[i] * vec[i];
len = sqrt(len);
if ( len < Tiny ){
std::cout<<"divide by ZERO in interAngle \n";
exit(1);
}
if ( dim != 3 ){
std::cout<<"This polar function only for 3D \n";
exit(1);
}
for (int j=0; j<dim; j++)
dirs[j] = vec[j] / len;
dirs[0] = acos( sqrt (dirs[0] * dirs[0] + dirs[1] * dirs[1] ) / len);
if ( dirs[2] < 0)
dirs[0] = Pi - dirs[0];
if ( fabs(dirs[0] ) < Tiny){
dirs[1] = 0.0;
return dirs;
}
double sinF = vec[1] / ( len * dirs[0] );
double cosF = vec[0] / ( len * dirs[0] );
if( sinF >= 0.0)
dirs[1] = acos(cosF);
else
dirs[1] = TwoPi - acos(cosF);
return dirs;
}
/** cal the polar coordinate of the vector vec */
inline float* polarCoordF(float *vec, int dim) {
float len = 0.0;
float *dirs = new float[dim];
for (int i = 0; i < dim; i++)
len += vec[i] * vec[i];
len = sqrt(len);
if ( len < Tiny ){
std::cout<<"divide by ZERO in interAngle \n";
exit(1);
}
if ( dim != 3 ){
std::cout<<"This polar function only for 3D \n";
exit(1);
}
for (int j=0; j<dim; j++)
dirs[j] = vec[j] / len;
dirs[0]= acos( dirs[2]);
float sinT = sqrt( 1.0 - dirs[2] * dirs[2]); // 1 - cos^2_{theta}
if ( fabs(sinT ) < Tiny){
dirs[1] = 0.0;
dirs[2] = len;
return dirs;
}
float sinF = vec[1] / ( len * sinT );
float cosF = vec[0] / ( len * sinT);
// cout<<sinF<<" "<<cosF<<endl;
if( sinF >= 0.0)
dirs[1] = acos(cosF);
else
dirs[1] = TwoPi - acos(cosF);
dirs[2] = len;
return dirs;
}
/**
* A method for generating the internuclear vector between two atoms
@param n1 the coordinate for the nucleus of the atom 1
@param n2 the coordinate for the nucleus of the atom 2
@return a vector from n1->n2
*/
inline double Distance(double *n1, double *n2, const size_t dim = 3){
double sum =0.0;
for (unsigned int i = 0; i < dim; i++)
sum += ( n2[i] - n1[i] ) * ( n2[i] - n1[i] ) ;
return sqrt(sum);
}
inline float DistanceF(float *n1, float *n2, const size_t dim = 3){
float sum =0.0;
for (unsigned int i = 0; i < dim; i++)
sum += ( n2[i] - n1[i] ) * ( n2[i] - n1[i] ) ;
return sqrt(sum);
}
inline double Distsq(double *n1, double *n2, const size_t dim = 3){
double sum =0.0;
for (unsigned int i = 0; i < dim; i++)
sum += ( n2[i] - n1[i] ) * ( n2[i] - n1[i] ) ;
return sum;
}
inline void Norm(double *x, double *xnorm) {
/* RETURNS INPUT VECTOR X NORMALIZED TO UNIT LENGTH.
XNORM IS THE ORIGINAL LENGTH OF X. */
double TEMP, TEMP1, TEMP2;
TEMP = x[0];
TEMP1 = x[1];
TEMP2 = x[2];
*xnorm = TEMP * TEMP + TEMP1 * TEMP1 + TEMP2 * TEMP2;
if (*xnorm <= 0.0)
return;
*xnorm = sqrt(*xnorm);
x[0] /= *xnorm;
x[1] /= *xnorm;
x[2] /= *xnorm;
}
inline void Diff( const double *const x, const double *const y,
double *z, const size_t dim = 3){
for ( unsigned int i = 0; i < dim; i++ )
z[i]= x[i] - y[i];
}
inline double Dot(const double *const x, const double *const y) {
return x[0] * y[0] + x[1] * y[1] + x[2] * y[2];
}
inline void Cross(const double *const x, const double *const y, double *z){
z[0] = x[1] * y[2] - y[1] * x[2];
z[1] = x[2] * y[0] - y[2] * x[0];
z[2] = x[0] * y[1] - y[0] * x[1];
}
inline float *addCoords( float*n1, float*n2, int dim){
float *sum = new float[dim];
for (int i = 0; i < dim; i++)
sum[i] = n2[i] + n1[i];
return sum;
}
inline float *aveCoords(float *n1, float *n2, int dim){
float *ave = new float[dim];
for (int i = 0; i < dim; i++)
ave[i] = 0.50 * ( n2[i] + n1[i] );
return ave;
}
inline float *internuclearVec( float*n1, float*n2, int dim){
float *sum = new float[dim];
for (int i = 0; i < dim; i++)
sum[i] = n2[i] - n1[i];
return sum;
}
inline void internuclearVec( double *const n1, double *const n2,
double sum[], int dim ){
for (int i = 0; i < dim; i++)
sum[i] = n2[i] - n1[i];
}
inline vector<double> n1ToN2VecD( double *n1, double *n2, int dim){
vector<double> sum(dim, 0.0);
for (int i = 0; i < dim; i++)
sum[i] = n2[i] - n1[i];
return sum;
}
// inline float *internuclearVec( float*n1, const vector<float>&n1, int dim){
// float *sum = new float[dim];
// for (int i = 0; i < dim; i++)
// sum[i] = n2[i] - n1[i];
// return sum;
// }
inline float norm( float *vec, int dim){
float len = 0.0;
for (int i=0; i< dim; i++)
len += vec[i] * vec[i];
return sqrt(len);
}
inline double norm( vector<float>& vec, const size_t dim){
double len = 0.0;
for (unsigned int i=0; i< dim; i++)
len += vec[i] * vec[i];
len = sqrt(len);
for (unsigned int i=0; i< dim; i++)
vec[i] /= len;
return len;
}
inline double norm( vector<double>& vec, const size_t dim){
double len = 0.0;
for (unsigned int i=0; i< dim; i++)
len += vec[i] * vec[i];
len = sqrt(len);
for (unsigned int i=0; i< dim; i++)
vec[i] /= len;
return len;
}
inline float normSquare( float*vec, int dim){
float len = 0.0;
for (int i=0; i< dim; i++)
len += vec[i] * vec[i];
return len;
}
inline void printArray(string name, double *const n1, int d){
printf("%5s", name.c_str() );
for (int i=0; i<d; i++)
printf("%10.5f", n1[i]);
printf("\n");
}
inline void printArray(string name, const vector<double> &n1 ){
printf("%5s", name.c_str() );
for (int i=0; i< n1.size(); i++)
printf("%10.5f", n1[i]);
printf("\n");
}
inline void printArray(double *const n1, int d){
for (int i=0; i<d; i++)
printf("%16.8f", n1[i]);
printf("\n");
}
inline void printArray(const vector<double> &n1 ){
for (int i=0; i< n1.size(); i++)
printf("%16.8f", n1[i]);
printf("\n");
}
inline float InvSqrt (float x){
float xhalf = 0.5f*x;
int i = *(int*)&x;
i = 0x5f3759df - (i>>1);
x = *(float*)&i;
x = x*(1.5f - xhalf*x*x);
return x;
}
#ifndef ABS
#define ABS( x ) ((x) > 0 ? (x) : -(x))
#endif
#ifndef MAX
#define MAX( x, y ) ((x) > (y) ? (x) : (y))
#endif
#ifndef MIN
#define MIN( x, y ) ((x) < (y) ? (x) : (y))
#endif
#endif /*MATH_H_*/
| [
"xushutan@gmail.com"
] | xushutan@gmail.com |
2a973c3dee806fdeb7bbb4481e16a4ee86fd4e40 | 896d897a135f7ae7175ceed28ce4f439d7a74cc8 | /tstring.hpp | bbb9c3018add1d37c68321a207b94717cc4446f9 | [] | no_license | zby123/bookstore | b1489ad36172c0c0a2b895405503982e01cd0815 | 4b7210f12a386a6f2cc604fdf6f35ba574b3e0de | refs/heads/master | 2021-08-31T18:47:09.744446 | 2017-12-22T12:16:23 | 2017-12-22T12:16:23 | 115,112,653 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,617 | hpp | #ifndef tstring_hpp
#define tstring_hpp
#include <string>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
template <int size>
class tstring {
private:
char m[size];
int len = 0;
public:
tstring() {
len = 0;
}
tstring(int t) {
if (t == 0) {
len = 0;
}
else{
len = size;
for(int i = 0; i < size; i++) m[i] = 127;
}
}
tstring (const char *b) {
len = min(size, (int)strlen(b));
for(int i = 0; i < len; i++) m[i] = b[i];
}
tstring (char *b) {
len = min(size, (int)strlen(b));
for(int i = 0; i < len; i++) m[i] = b[i];
}
tstring(string &b) {
len = min(size, (int)b.length());
for(int i = 0; i < len; i++) m[i] = b[i];
}
int getLen() {
return len;
}
void print() {
for(int i = 0; i < len; i++) cout << m[i];
}
template <int s2>
tstring(tstring<s2> &b) {
len = min(b.getLen(), size);
for(int i = 0; i < len; i++) m[i] = b[i];
}
operator bool () const {
return len != 0;
}
operator string () const {
string ret = "";
for(int i = 0; i < len; i++) ret += m[i];
return ret;
}
char operator [] (int pos) {
if (pos > len) return '\0';
return m[pos];
}
template <int s2>
bool operator == (tstring<s2> &b) {
if (b.getLen() != len) return false;
for(int i = 0; i < len; i++) {
if (m[i] != b[i]) return false;
}
return true;
}
template <int s2>
bool operator < (tstring<s2> &b) {
int tlen = min(len, b.getLen());
for(int i = 0; i < tlen; i++) {
if (m[i] < b[i]) return true;
if (m[i] > b[i]) return false;
}
if (len < b.getLen()) return true;
return false;
}
};
#endif | [
"ZengBiyang@sjtu.edu.cn"
] | ZengBiyang@sjtu.edu.cn |
88ebead79c333d626927b02b39e028ebff29007e | 621f90d90f4a046136411c75b3ebc4889b640f23 | /src/Samples/SpiLcd.h | be912cc43a8863b4f72893923a29c4b69563f1e3 | [] | no_license | suspect-devices/eXodusino | 2e6548cb47f3e94c9088c2bbcb2b25ea42a7a379 | 5c9eb1b24ed4cfa7eae59ffbc24bdbbce814ba35 | refs/heads/master | 2020-04-05T23:32:49.259284 | 2012-09-25T12:32:32 | 2012-09-25T12:32:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,811 | h | /*
* SpiLcd.h
*
* Created on: 2012/08/01
* Author: lynxeyed
*/
#ifndef SPILCD_H_
#define SPILCD_H_
/**************************************************************************//**
* @file SpiLcd.h
* @brief Arduino-like library for Cortex-M0 Series
* @version v.0.50
* @date 1. August 2011.
* @author lynxeyed
* @note Copyright (c) 2012 Lynx-EyED's Klavier and Craft-works. <BR>
* 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: <BR>
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.<BR>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
******************************************************************************/
#include "SPI.h"
#include "gpio.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {ST7735,Nokia6610,Nokia6100,PCF8833} LCD_DEVICES; // Defaults:ST7735
class SPILCD {
private:
SSP_PORT port;
LCD_DEVICES device;
int LCD_VCC_ON;
int LCD_CS;
int LCD_RES;
int _row;
int _column;
int _foreground;
int _background;
int _width;
int _height;
public:
SPILCD(); // announce the constructor to initialize
~SPILCD();
void reset();
void reset(SSP_PORT port);
void command( int value );
void data( int value );
void _window( int x, int y, int width, int height );
void locate(int column, int row);
void newline();
void _putp( int colour );
int _putc( int value );
void cls( void );
void window( int x, int y, int width, int height );
void WindowReset(void);
void putp( int colour );
void pixel( int x, int y, int colour );
void fill( int x, int y, int width, int height, int colour );
void blit( int x, int y, int width, int height, const int* colour );
void bitblit( int x, int y, int width, int height, const char* bitstream );
void foreground(int c);
void background(int c);
int width();
int height();
int columns();
int rows();
};
extern SPILCD slcd;
#ifdef __cplusplus
}
#endif
#endif /* SPILCD_H_ */
| [
"lynxeyed@xj9.so-net.ne.jp"
] | lynxeyed@xj9.so-net.ne.jp |
394062aafb0dd7b620729fce9b89e4234ff0217c | bba488ad3c516f5545def334cab2eea90d5220e2 | /Game_windows.cpp | e7eef3bc453e3f128f1461fd7c8e4bc1f5949430 | [] | no_license | quoji/FlipFlaps | ccc0a38dd7b4561ee2270b9de801c999f91aa7ba | 16bd592edb457b5ca5ac51493116e2c9a41abf0e | refs/heads/master | 2023-02-18T15:37:41.598752 | 2023-02-10T00:02:57 | 2023-02-10T00:02:57 | 34,549,077 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,563 | cpp | /*
Ruben Cardenas, Stephen Brownlee, Pedro Alvarez
Game_windows.cpp
To be used with FlipFlaps
*/
#include "std_lib_facilities_4.h"
#include "Game_windows.h"
#include "Window.h"
#include "Graph.h"
#include "GUI.h"
#include "find_solution.h"
#include "High_scores.h"
//----------------------------------------------------------------------------
using namespace Graph_lib;
auto width = 500; //size for home page buttons
auto height = 100;
auto offset = 80;
int diff_width = 80; //difficulty button sizes
int diff_height = 50;
int num_flips = 0; //player's flip count
int score = 0, num_arranged = 0; //score tracking
string player_name = ""; //stores initials
fstream scores; //high score stream
//----------------------------------------------------------------------------
Color brown_trim(fl_rgb_color(255, 222, 176));
Color dark_brown(fl_rgb_color(176,102,5));
Color light_brown(fl_rgb_color(217,140,33));
//----------------------------------------------------------------------------
vector<Flip_wrapper> flip_info; //stores objects used in game loop
vector<Rectangle*> pancakes;
vector<Line*> lines;
vector<int> widths, *solution;
vector<High_scores> player_scores;
//----------------------------------------------------------------------------
Image main_screen(Point(0, 0), "FlipFlaps.jpg"); //background images
Image trophy(Point(300,150),"winner.gif");
Image defeat(Point(400,250),"defeat.gif");
//----------------------------------------------------------------------------
Rectangle background(Point(0, 0), x_max(), y_max()); //UI objects
Rectangle initials_screen_1(Point(0, 270), x_max(), 529);
Rectangle initials_screen_2(Point(0, 0), 429, y_max());
Rectangle initials_screen_3(Point(0, 0), x_max(), 219);
Rectangle initials_screen_4(Point(630, 0), 370, y_max());
Rectangle tabletop(Point(250,800-250), 500, 80);
Rectangle tableleg(Point(275,800-250), 50, 200);
Rectangle tableleg2(Point(675,800-250), 50, 200);
Text score_1(Point (400, 200), "");
Text score_2(Point(400, 275), "");
Text score_3(Point(400, 350), "");
Text score_4(Point(400, 425), "");
Text score_5(Point(400, 500), "");
Text inst_1(Point(x_max() / 2 - 300, 100), "");
Text inst_2(Point(50, 180), "");
Text inst_3(Point(50, 220), "");
Text inst_4(Point(50, 260), "");
Text inst_5(Point(50, 300), "");
Text inst_6(Point(50, 340), "");
Text inst_7(Point(50, 380), "");
Text inst_8(Point(50, 420), "");
Text no_high(Point(300, 100), "");
Text you_win_txt(Point(260, 140), "");
Text you_lose_txt(Point(400, 200), "");
Text your_score(Point(50,50), "");
Text min_needed(Point(50, 75), "");
Text flips_to_win(Point(50,100), "");
Text lvl_diff(Point(410,485), "");
Text player_initials(Point(390, 300), "");
Text username(Point(430, 200), "");
Text team_num(Point(50, 780), "");
Text high_score_title(Point(200, 100), "");
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
Game_windows::Game_windows(Point xy, int w, int h, const string& title) : //create game window
Window(xy, w, h, title),
play(Point((x_max() / 2 - (width - 100) / 2), 330), width - 100, height - 30, "Play", cb_play_game),
instructions(Point((x_max() / 2 - (width - 100) / 2), 430), width - 100, height - 30, "Instructions", cb_show_inst),
highscores(Point((x_max() / 2 - (width - 100) / 2), 530), width - 100, height - 30, "Highscores", cb_show_high),
exit(Point((x_max() / 2 - (width - 100) / 2), 630), width - 100, height - 30, "Exit", cb_exit_game),
Ok(Point((x_max() / 2 - width / 2 + 75), 635), width - 150, height - 50, "Return To Menu", cb_go_back),
replay(Point(400+(x_max() / 2 - width / 2), 600), width / 2, height, "Play Again", cb_replay),
menu_button(Point((x_max() / 2 - width / 2)-100, 600), width / 2, height, "Main Menu", cb_game_go_back),
enter(Point(530, 220), 100, 50, "Enter", cb_enter_initials),
Initials(Point(430,220), 100,50, ""),
lvl_2(Point(100+offset*1,500), diff_width, diff_height, "2", cb_hard2),
lvl_3(Point(100+offset*2,500), diff_width, diff_height, "3", cb_hard3),
lvl_4(Point(100+offset*3,500), diff_width, diff_height, "4", cb_hard4),
lvl_5(Point(100+offset*4,500), diff_width, diff_height, "5", cb_hard5),
lvl_6(Point(100+offset*5,500), diff_width, diff_height, "6", cb_hard6),
lvl_7(Point(100+offset*6,500), diff_width, diff_height, "7", cb_hard7),
lvl_8(Point(100+offset*7,500), diff_width, diff_height, "8", cb_hard8),
lvl_9(Point(100+offset*8,500), diff_width, diff_height, "9", cb_hard9)
{
attach(Initials);
attach(main_screen);
attach(play); //Shows and hides all of the buttons for the main menu
attach(instructions);
attach(highscores);
attach(exit);
team_num.set_label("Team 39");
team_num.set_color(light_brown);
attach(team_num);
attach_hard_menu();
attach(enter);
detach(enter);
detach(Initials);
detach_hard_menu();
}
void Game_windows::play_game() //takes difficulty and initial inputs to prepare game
{
username.set_label("Enter Initials");
username.set_font_size(30);
player_initials.set_label("Your initials are: ");
player_initials.set_font_size(30);
lvl_diff.set_label("Select Difficulty");
lvl_diff.set_font_size(30);
detach_menu();
detach(background);
attach(Initials);
attach(enter);
initials_background();
attach(lvl_diff);
attach(player_initials);
attach(username);
attach_hard_menu();
attach(Ok);
}
void Game_windows::show_inst() //Goes to instruction page when button clicked
{
detach_menu();
detach(background);
set_background();
get_inst();
attach(Ok);
}
void Game_windows::show_high() //Goes to highscores page when button clicked
{
detach_menu();
detach(background);
set_background();
attach(Ok);
high_score_title.set_font_size(50);
high_score_title.set_label("FLIPPIN' HALL OF FAME");
attach(high_score_title);
no_high.set_label("No Highscores Yet");
no_high.set_font_size(50);
scores.open("Scores.txt", ios::in);
if (!scores.is_open())
{
make_file();
attach(no_high);
}
else
read_from_file();
}
void Game_windows::make_file()
{
scores.clear();
scores.open("Scores.txt", ios::out);
scores.close();
scores.open("Scores.txt", ios::in);
scores.close();
}
void Game_windows::read_from_file()
{
string initials;
int points, length;
initials = "";
points = 0;
scores.seekg(0, ios::end);
length = scores.tellg();
if (length == 0)
attach(no_high);
else
{
scores.seekg(0);
if (!scores.eof())
{
while (!scores.eof())
{
scores >> initials >> points;
player_scores.push_back(High_scores(initials, points));
}
sort(player_scores.begin(), player_scores.end(),
[](High_scores &sc_1, High_scores &sc_2){return sc_1.get_score() > sc_2.get_score();});
if (player_scores.size() >= 5)
set_score(5);
else
set_score(player_scores.size());
}
}
scores.close();
}
void Game_windows::write_to_file()
{
scores.open("Scores.txt", ios::app);
if (!scores.is_open())
{
make_file();
scores.open("Scores.txt");
}
if (player_name.size() != 0)
{
scores << player_name << ' ' << to_string(score);
scores.close();
}
else
scores.close();
}
void Game_windows::set_score(int num) //sends scores to high score screen
{
switch (num)
{
case 5:
score_5.set_label(get_info(4));
score_5.set_font_size(30);
attach(score_5);
case 4:
score_4.set_label(get_info(3));
score_4.set_font_size(30);
attach(score_4);
case 3:
score_3.set_label(get_info(2));
score_3.set_font_size(30);
attach(score_3);
case 2:
score_2.set_label(get_info(1));
score_2.set_font_size(30);
attach(score_2);
case 1:
score_1.set_label(get_info(0));
score_1.set_font_size(30);
attach(score_1);
}
}
string Game_windows::get_info(int which_one) //gets player name and high score
{
string player, together;
int points;
player = player_scores[which_one].get_initials();
points = player_scores[which_one].get_score();
together = player + ' ' + to_string(points);
return together;
}
void Game_windows::exit_game() //Exits the game
{
hide();
}
void Game_windows::enter_initials()
{
string three_initials;
player_name = Initials.get_string();
three_initials = player_name.substr(0, 3); //takes 3 initials
player_initials.set_label("Your initials are: " + three_initials);
Fl::redraw();
}
void Game_windows::detach_menu() //takes off the menu buttons
{
detach(main_screen);
detach(play);
detach(instructions);
detach(highscores);
detach(exit);
}
//----------------------------------------------------------------------------
void Game_windows::cb_play_game(Address, Address pw) //Callbacks for FLTK
{
reference_to<Game_windows>(pw).redraw();
reference_to<Game_windows>(pw).play_game();
}
void Game_windows::cb_show_inst(Address, Address pw)
{
reference_to<Game_windows>(pw).redraw();
reference_to<Game_windows>(pw).show_inst();
}
void Game_windows::cb_show_high(Address, Address pw)
{
reference_to<Game_windows>(pw).redraw();
reference_to<Game_windows>(pw).show_high();
}
void Game_windows::cb_exit_game(Address, Address pw)
{
reference_to<Game_windows>(pw).redraw();
reference_to<Game_windows>(pw).exit_game();
}
void Game_windows::cb_enter_initials(Address, Address pw)
{
reference_to<Game_windows>(pw).redraw();
reference_to<Game_windows>(pw).enter_initials();
}
//----------------------------------------------------------------------------
void Game_windows::go_back() //goes back to the main menu
{
num_flips = 0;
detach(Ok);
detach(enter);
detach_inst();
detach_hard_menu();
detach(high_score_title);
detach(no_high);
detach(you_win_txt);
detach(you_lose_txt);
detach(lvl_diff);
detach(username);
detach(player_initials);
detach_scores();
detach_game();
detach(trophy);
detach(defeat);
detach(Initials);
detach_background();
attach(main_screen);
attach(play);
attach(instructions);
attach(highscores);
attach(exit);
attach(team_num);
}
void Game_windows::cb_go_back(Address, Address pw) //callbacks for FLTK
{
reference_to<Game_windows>(pw).redraw();
reference_to<Game_windows>(pw).go_back();
}
void Game_windows::detach_scores() //hides high score screen
{
detach(score_1);
detach(score_2);
detach(score_3);
detach(score_4);
detach(score_5);
player_scores.erase(player_scores.begin(), player_scores.end());
}
//----------------------------------------------------------------------------
void Game_windows::get_inst() //game instructions text
{
inst_1.set_label("How To Play");
inst_2.set_label("The purpose of the game is to flip an unordered stack of pancakes until they are in the ");
inst_3.set_label("correct order while trying to use the least number of flips. When you start the game, a stack of");
inst_4.set_label("unordered pancakes will appear before your eyes. Click the buttons next to the pancakes to ");
inst_5.set_label("indicate where you want to flip the stack. Once you're able to get the stack in the correct");
inst_6.set_label("order, the game will be over and your score will be displayed. However, the game will also be");
inst_7.set_label("over if you make more moves than the ones that are necessary. At this point, the game will stop,");
inst_8.set_label("and you will no longer be able to continue.");
inst_1.set_font(FL_SCREEN);
inst_2.set_font(FL_SCREEN);
inst_3.set_font(FL_SCREEN);
inst_4.set_font(FL_SCREEN);
inst_5.set_font(FL_SCREEN);
inst_6.set_font(FL_SCREEN);
inst_7.set_font(FL_SCREEN);
inst_8.set_font(FL_SCREEN);
inst_1.set_font_size(42);
inst_2.set_font_size(21);
inst_3.set_font_size(21);
inst_4.set_font_size(21);
inst_5.set_font_size(21);
inst_6.set_font_size(21);
inst_7.set_font_size(21);
inst_8.set_font_size(21);
attach(inst_1);
attach(inst_2);
attach(inst_3);
attach(inst_4);
attach(inst_5);
attach(inst_6);
attach(inst_7);
attach(inst_8);
}
void Game_windows::detach_inst() //takes off instructions when 'Ok' clicked
{
detach(inst_1);
detach(inst_2);
detach(inst_3);
detach(inst_4);
detach(inst_5);
detach(inst_6);
detach(inst_7);
detach(inst_8);
}
void Game_windows::attach_hard_menu() //attaches difficulty buttons
{
attach(lvl_2);
attach(lvl_3);
attach(lvl_4);
attach(lvl_5);
attach(lvl_6);
attach(lvl_7);
attach(lvl_8);
attach(lvl_9);
}
void Game_windows::detach_hard_menu()
{
lvl_2.hide();
lvl_3.hide();
lvl_4.hide();
lvl_5.hide();
lvl_6.hide();
lvl_7.hide();
lvl_8.hide();
lvl_9.hide();
}
//----------------------------------------------------------------------------
void Game_windows::set_background() //makes colored background
{
background.set_fill_color(Color::dark_cyan);
background.set_color(Color::black);
attach(background);
}
void Game_windows::initials_background() //used to solve flickering initial box
{
initials_screen_1.set_fill_color(Color::dark_cyan);
initials_screen_1.set_color(Color::dark_cyan);
initials_screen_2.set_fill_color(Color::dark_cyan);
initials_screen_2.set_color(Color::dark_cyan);
initials_screen_3.set_fill_color(Color::dark_cyan);
initials_screen_3.set_color(Color::dark_cyan);
initials_screen_4.set_fill_color(Color::dark_cyan);
initials_screen_4.set_color(Color::dark_cyan);
attach(initials_screen_1);
attach(initials_screen_2);
attach(initials_screen_3);
attach(initials_screen_4);
}
void Game_windows::detach_background()
{
detach(initials_screen_1);
detach(initials_screen_2);
detach(initials_screen_4);
detach(initials_screen_4);
}
//----------------------------------------------------------------------------
void Game_windows::cb_hard2(Address, Address pw) //callbacks for difficulty buttons
{
reference_to<Game_windows>(pw).redraw();
reference_to<Game_windows>(pw).set_difficulty(2);
}
void Game_windows::cb_hard3(Address, Address pw)
{
reference_to<Game_windows>(pw).redraw();
reference_to<Game_windows>(pw).set_difficulty(3);
}
void Game_windows::cb_hard4(Address, Address pw)
{
reference_to<Game_windows>(pw).redraw();
reference_to<Game_windows>(pw).set_difficulty(4);
}
void Game_windows::cb_hard5(Address, Address pw)
{
reference_to<Game_windows>(pw).redraw();
reference_to<Game_windows>(pw).set_difficulty(5);
}
void Game_windows::cb_hard6(Address, Address pw)
{
reference_to<Game_windows>(pw).redraw();
reference_to<Game_windows>(pw).set_difficulty(6);
}
void Game_windows::cb_hard7(Address, Address pw)
{
reference_to<Game_windows>(pw).redraw();
reference_to<Game_windows>(pw).set_difficulty(7);
}
void Game_windows::cb_hard8(Address, Address pw)
{
reference_to<Game_windows>(pw).redraw();
reference_to<Game_windows>(pw).set_difficulty(8);
}
void Game_windows::cb_hard9(Address, Address pw)
{
reference_to<Game_windows>(pw).redraw();
reference_to<Game_windows>(pw).set_difficulty(9);
}
//----------------------------------------------------------------------------
void Game_windows::set_difficulty(int diff)
{
detach_hard_menu();
detach(username);
detach(lvl_diff);
detach(Initials);
detach(enter);
detach_background();
set_background();
int num_pancakes = diff;
run_game(diff);
}
//----------------------------------------------------------------------------
int Game_windows::run_game(int p_cakes) //makes the pancakes, starts the game
{
int pwidth, pheight, table, wscaler, pancakeY;
int flip_Y, flip_X, flip_width, flip_height;
bool lose;
wscaler = 50; //pancake width
table = 250; //bottom margin. Pancakes rest on this
pheight = 50; //height for all pancakes
flip_X = 160;
flip_width = 80;
flip_height = 50; //same as pancake height
lose = false;
handle_pancakes(p_cakes, pwidth, wscaler, pancakeY, table, pheight); //shuffles pancakes
generate_flip_buttons(p_cakes, pancakeY, table, pheight, flip_Y, //generate flip buttons
flip_X, flip_width,flip_height);
score = calculate_score(0); //set initial score
your_score.set_label("Score: "+ to_string(score));
your_score.set_font_size(20);
tableleg.set_fill_color(dark_brown); //makes a table
tableleg2.set_fill_color(dark_brown);
tabletop.set_fill_color(dark_brown);
attach(flips_to_win);
attach(min_needed);
attach(your_score);
attach(tableleg);
attach(tableleg2);
attach(tabletop);
}
void Game_windows::flip() //happens when a button is clicked
{
bool lose = false;
bool win = false;
++num_flips;
score = calculate_score(num_flips);
your_score.set_label("Score: "+ to_string(score));
handle_flip(lose); //updates pancakes and score
check_win_condition(lose, win, score);
}
void Game_windows::cb_flip(Address, Address pw)
{
reference_to<Game_windows>(pw).flip();
}
//----------------------------------------------------------------------------
int Game_windows::calculate_score(int flips)
{
int score, min_flips;
reverse(widths.begin(), widths.end());
solution = find_solution(widths);
reverse(widths.begin(), widths.end());
min_flips = solution->size();
flips_to_win.set_label("You've used " + to_string(flips) + " flip(s)");
flips_to_win.set_font_size(20);
min_needed.set_label("Can be done in " + to_string(min_flips) + " flip(s)");
min_needed.set_font_size(20);
return score = (100 - 10 * (flips - min_flips)) * 6;
}
void Game_windows::you_win() //what happens when pancakes are sorted
{
score = calculate_score(num_flips);
you_win_txt.set_label("You Win! Score: " + to_string(score));
you_win_txt.set_font_size(50);
attach(you_win_txt);
attach(replay);
attach(menu_button);
attach(trophy);
detach(tabletop);
detach(tableleg);
detach(tableleg2);
write_to_file();
num_flips = 0;
num_arranged = 0;
detach_game();
}
void Game_windows::you_lose() //what happens when player fails to sort pancakes
{
score = calculate_score(num_flips);
you_lose_txt.set_label("You Lose!");
you_lose_txt.set_font_size(50);
attach(you_lose_txt);
attach(replay);
attach(menu_button);
attach(defeat);
detach(tabletop);
detach(tableleg);
detach(tableleg2);
write_to_file();
num_flips = 0;
num_arranged = 0;
detach_game();
}
void Game_windows::detach_game() //returns to main menu, exits game
{
for (int i = 0; i < pancakes.size(); ++i)
{
Rectangle* pancake = (pancakes[i]); //dereferences all objects to detach
Rectangle& pancake_ref = (*pancake);
Button* flip_button = (flip_info[i].button_ptr);
Button& flip_ref = (*flip_button);
Line* line = lines[i];
Line& line_ref = (*line);
detach(line_ref);
detach(pancake_ref);
detach(flip_ref);
detach(your_score);
detach(flips_to_win);
detach(min_needed);
}
pancakes.erase(pancakes.begin(), pancakes.end()); //clear all arrays
flip_info.erase(flip_info.begin(), flip_info.end());
lines.erase(lines.begin(),lines.end());
widths.erase(widths.begin(), widths.end());
detach(Ok);
}
//----------------------------------------------------------------------------
void Game_windows::do_flip(int flip_id) //moves pancake positions
{
int num_to_flip = flip_id;
int midpoint = num_to_flip / 2;
int p_cakes = flip_info.size(); //how many pancakes there are
odd_flip(num_to_flip, p_cakes, midpoint);
even_flip(num_to_flip, p_cakes, midpoint);
}
void Game_windows::handle_pancakes(int p_cakes, int pwidth, int wscaler,
int pancakeY, int table, int pheight)
{
random_device rd; //used for shuffling our vector
mt19937 generator(rd()); //random generator parameter
for (int i = 1; i <= p_cakes; ++i) //our widths, which will be scaled by wscaler
widths.push_back(i);
shuffle(widths.begin(), widths.end(), generator); //shuffles our vector
for (int i = 1; i <= p_cakes; ++i)
{
pwidth = widths[i-1] * wscaler;
pancakeY = (y_max() - table) - pheight * i;
Rectangle* pancake = new Rectangle(Point(x_max() / 2 - pwidth / 2, pancakeY), pwidth, pheight);
pancake->set_fill_color(light_brown);
pancake->set_color(brown_trim);
Rectangle& pancake_ref = (*pancake);
pancakes.push_back(pancake); //send pancakes to global vector
attach(pancake_ref);
}
}
void Game_windows::generate_flip_buttons(int p_cakes, int pancakeY, int table, int pheight, int flip_Y,
int flip_X, int flip_width, int flip_height)
{
int line_width = 300 / p_cakes;
for (int i = 0; i < p_cakes; ++i)
{
pancakeY = (y_max() - table) - pheight * i;
flip_Y = pancakeY - pheight / 2;
Button* flip_button = new Button(Point(flip_X, flip_Y), flip_width, flip_height, "FLIP", cb_flip);
Button& flip_ref = (*flip_button);
flip_info.push_back({i + 1, flip_button}); //stores buttons in vector
Line* line= new Line(Point(flip_X + flip_width, flip_Y + flip_height / 2),
Point(flip_X + flip_width + line_width, flip_Y + flip_height / 2));
line->set_style(Line_style(Line_style::dash, 3));
Line& line_ref = (*line);
lines.push_back(line);
attach(line_ref);
attach(flip_ref);
}
}
void Game_windows::cb_replay(Address, Address pw) //callback for FLTK
{
reference_to<Game_windows>(pw).redraw();
reference_to<Game_windows>(pw).do_replay();
}
void Game_windows::cb_game_go_back(Address, Address pw) //callback for FLTK
{
reference_to<Game_windows>(pw).redraw();
reference_to<Game_windows>(pw).game_go_back();
}
void Game_windows::game_go_back() //for back buttons
{
score = 0;
detach(menu_button);
detach(replay);
go_back();
}
void Game_windows::do_replay() //for replay button
{
detach(replay);
detach(menu_button);
go_back();
play_game();
}
void Game_windows::odd_flip(int num_to_flip, int p_cakes, int midpoint)
{
int yposa, yposb, move, swapY;
if (num_to_flip % 2 == 1) //odd num flip
{
for (int i = 0; i < midpoint + 1; ++i) //see even flip comments
{
yposa = pancakes[p_cakes - midpoint + i - 1]->yPos();
yposb = pancakes[p_cakes - midpoint - i - 1]->yPos();
move = yposb - yposa;
pancakes[p_cakes - midpoint + i - 1]->move(0, move);
pancakes[p_cakes - midpoint - i - 1]->move(0, -move);
swapY = yposa; //assign new swapped y values
pancakes[p_cakes - midpoint + i - 1]->set_yPos(yposb);
pancakes[p_cakes - midpoint - i - 1]->set_yPos(swapY);
swap(pancakes[p_cakes - midpoint + i - 1], //swap rects in array
pancakes[p_cakes - midpoint - i - 1]);
}
Fl::redraw();
}
}
void Game_windows::even_flip(int num_to_flip, int p_cakes, int midpoint)
{
int yposa, yposb, move, swapY;
if (num_to_flip % 2 == 0) //even number flip
{
for (int i = 0; i < midpoint; ++i)
{
yposa = pancakes[p_cakes - midpoint + i]->yPos();//get y's
yposb = pancakes[p_cakes - midpoint - i - 1]->yPos();
move = yposb - yposa;
//moves the pancakes to the other's position
pancakes[p_cakes - midpoint + i]->move(0, move);
pancakes[p_cakes - midpoint - i - 1]->move(0, -move);
//assigns new swapped y values since move doesn't record
// them :(
swapY = yposa;
pancakes[p_cakes-midpoint + i]->set_yPos(yposb);
pancakes[p_cakes-midpoint - i - 1]->set_yPos(swapY);
//swaps addresses of each pancake so that they occupy
//the other's array index, used to reflect the new
//structure of pancakes in the array itself, ie
//if bot pancake is now top, its index goes [0] to [last]
//so next time we can find it when the loop does its logic
swap(pancakes[p_cakes - midpoint + i],
pancakes[p_cakes - midpoint - i - 1]);
}
Fl::redraw();//save cycles? by redrawing only once
}
}
void Game_windows::handle_flip(bool lose) //calculates flip button
{
if (!lose)
{
int flip_id, pheight, pancakeY, flip_Y, h, table;
pheight = 50;
table = 250;
pancakeY = (y_max() - table) - pheight * flip_info.size();
h = 50; //pancakes height
flip_Y = pheight + pancakeY - pheight / 2;
if (Fl::event_y() > flip_Y) //if a flip button below the first button's Y is clicked
{
int flip_id = 1 + ((Fl::event_y() - flip_Y) / h); //calculates which button clicked
do_flip(flip_id);
}
}
}
void Game_windows::check_win_condition(bool lose, bool win, int score)
{
if (!lose && !win) //check for win
{
for (int i = 0; i < widths.size() - 1; ++i) //check if game has been won
{
if (pancakes[i]->width() > pancakes[i + 1]->width())
++num_arranged;
}
if (num_arranged == widths.size() - 1)
{
win = true;
you_win();
}
else
{
num_arranged = 0;
if(score == 0 && !win)
{
you_lose();
lose = true;
}
}
}
else if (score == 0 || score < 0)
{
you_lose();
lose = true;
}
} | [
"sbrownlee90@gmail.com"
] | sbrownlee90@gmail.com |
8329846914eb5a16bfa22aa78eccfb09b0683793 | 34d44a9ca7e6eb63495247ed2aed146b55f1c7db | /QuestionAns/rs_learner/1574.cc | 1190afe1fe9def33138a8c2ae3299e70a0f33afe | [] | no_license | sdustlug/OpenJudge | 2419c00824f29144864571e1d25c9de1a09350d2 | a6550441691470df505f6a971bc9661ced1b0773 | refs/heads/master | 2023-09-03T11:48:01.041727 | 2021-10-18T13:47:57 | 2021-10-18T13:47:57 | 418,521,703 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,246 | cc | #include<iostream>
#include<cstring>
#include<iomanip>
using namespace std;
class Date
{
private:
int year,month,day;
public:
Date(int _year,int _month,int _day):year(_year),month(_month),day(_day){}
~Date(){}
void showDate()
{
cout<<year<<"-"<<setw(2)<<setfill('0')<<setw(2)<<month<<"-"<<setw(2)<<day;
}
};
class Time
{
private:
int h,m,s;
public:
Time(int _h,int _m,int _s):h(_h),m(_m),s(_s){}
~Time(){}
void showTime()
{
cout<<setw(2)<<setfill('0')<<h<<":"<<setw(2)<<m<<":"<<setw(2)<<s;
}
};
int main()
{
int cases;
cin >> cases;
for(int ca = 0; ca < cases; ca++)
{
int year, month, day;
cin >> year >> month >> day;
Date date(year, month, day);
date.showDate();
cout << " ";
int hour, minute, second;
cin >> hour >> minute >> second;
Time time(hour, minute, second);
time.showTime();
cout << endl;
}
}
/**************************************************************
Problem: 1574
User: 201801020908
Language: C++
Result: Accepted
Time:1340 ms
Memory:1268 kb
****************************************************************/
| [
"if.nicer@gmail.com"
] | if.nicer@gmail.com |
b2a0eca102dc1f4f33334c695f9c37401a4c3fe2 | f001a867881a910f09b30b924d88897a4ba51799 | /STFT/stft_src/invSTFT.hpp | 8f9b86e3f3ff49f93b60eeb7e454c2c6a3eb3e31 | [] | no_license | tachi-hi/timefreq | 9cce9e1e7bf572900f33a3cab7e8d76e266ee8c2 | 98d6d3f1b9d3e1f9ce787a17cc4e31f6ce071fa0 | refs/heads/master | 2016-09-15T14:47:58.760843 | 2016-05-15T17:36:43 | 2016-05-15T17:36:43 | 4,710,764 | 5 | 0 | null | 2016-05-15T17:36:43 | 2012-06-19T07:35:57 | C++ | UTF-8 | C++ | false | false | 368 | hpp |
#pragma once
#include<vector>
#include<complex>
#include"twoDimArray.h"
//inv stft
void invSTFT(
const twoDimArray<double>& abs,
const twoDimArray<std::complex<double> >& phase,
std::vector<double>* output,
int frame, int shift,
double(*win)(int, int) );
// Normalize signal
void normalization(std::vector<double>* signal1, std::vector<double>* signal2);
| [
"tachi-hi@users.noreply.github.com"
] | tachi-hi@users.noreply.github.com |
db74c012ad9b27d2bbabf8e336ad5b4dac3d0dbc | c15f70c2e3f2a57debd14e4d8a9d40d9d9ad8c35 | /Embedded/libraries/dh_controlled_types/ControlledLED.h | 2093973cc32ff65cb990ca4d73b0b94e264a877c | [] | no_license | davehummel/tredbot | b26db2ad2151ea1030f8354bee7811cc6d191d77 | d4dd6690c5f8bc75ab5e63c7c17b8a2633f63841 | refs/heads/master | 2020-04-12T07:24:15.572006 | 2017-02-20T19:14:53 | 2017-02-20T19:14:53 | 28,069,188 | 0 | 0 | null | 2015-01-13T01:22:53 | 2014-12-16T03:46:02 | Java | UTF-8 | C++ | false | false | 3,203 | h | #ifndef DH_CONTROLLEDLED_H__
#define DH_CONTROLLEDLED_H__
#include "dh_controller.h"
class ControlledLED: public Controller::Controlled{
public:
ControlledLED(){
}
void begin(void){
}
void execute(uint32_t time,uint32_t id,char command[]){
bool isPWM = true;
uint16_t temp;
switch (command[0]){
case 'B':
isPWM = false;
case 'P':{
uint8_t letter;
uint8_t pID;
if (command[4] >= 'a' && command[4] <= 'z'){
letter = command[4] - 'a';
}else if (command[4] >= 'A' && command[4] <= 'Z'){
letter = command[4] - 'A';
} else {
controller->getErrorLogger()->println("PWM/Bin must be assigned to 'a' to 'z' var.");
return;
}
temp = 6;
if (!Controller::parse_uint8(pID,temp,command)){
controller->getErrorLogger()->println("PWM/Bin must be set to a pin");
return;
}
pinID[letter] = pID;
pinVal[letter] = 0;
pinPWM[letter] = isPWM;
if (pID!=0){
pinMode(pID,OUTPUT);
if (isPWM)
analogWrite(pID,0);
else
digitalWrite(pID,LOW);
}
break;}
case 'F':{
uint8_t pin;
uint32_t sampleRate;
temp = 4;
if (!Controller::parse_uint8(pin,temp,command)){
controller->getErrorLogger()->println("FRQ must be set to a number.");
return;
}
temp++;
if (!Controller::parse_uint32(sampleRate,temp,command)){
controller->getErrorLogger()->println("FRQ must be set to a number.");
return;
}
setFreq(pin,sampleRate);
break;}
case 'R':{
uint8_t resolution;
temp = 4;
if (!Controller::parse_uint8(resolution,temp,command)){
controller->getErrorLogger()->println("RES must be set to a number.");
return;
}
if (resolution<2)
resolution = 2;
if (resolution>16)
resolution = 16;
analogWriteResolution(resolution);
break;}
default:
controller->getErrorLogger()->print("Bad ControlledLED command:");
controller->getErrorLogger()->println(command);
}
}
void startSchedule(char command[], uint32_t id){
}
void endSchedule(char command[], uint32_t id){
}
uint8_t readB(ADDR1 addr,uint8_t addr2){
return pinVal[addr.addr%26];
}
uint16_t readU(ADDR1 addr,uint8_t addr2){
return pinVal[addr.addr%26];
}
uint32_t readT(ADDR1 addr,uint8_t addr2){
return pinVal[addr.addr%26];
}
void write(ADDR1 addr,uint8_t val){
uint8_t letter = addr.addr%26;
if (pinID[letter] == 0)
return;
if (pinPWM[letter]) {
analogWrite(pinID[letter],pinVal[letter]=val);
}else{
digitalWrite(pinID[letter],(pinVal[letter]=(val!=0)));
}
}
void write(ADDR1 addr,uint16_t val){
uint8_t letter = addr.addr%26;
if (pinID[letter] == 0)
return;
if (pinPWM[letter]) {
analogWrite(pinID[letter],pinVal[letter]=val);
}else{
digitalWrite(pinID[letter],(pinVal[letter]=(val!=0)));
Serial.println(pinVal[letter]);
}
}
private:
void setFreq(uint8_t pin,uint32_t freq){
if (pin == 0){
analogWriteFrequency(5, freq);
analogWriteFrequency(3, freq);
analogWriteFrequency(25, freq);
} else {
analogWriteFrequency(pin, freq);
}
}
uint8_t pinID[26] = {0};
uint32_t pinVal[26] = {0};
bool pinPWM[26] = {false};
};
#endif
| [
"dmhummel@gmail.com"
] | dmhummel@gmail.com |
53977febe64a1c1f97a8c06ddcf3765c08580987 | 85221a64ad699e9f4d4d3bc508fa776c6b2e1d16 | /DummyClients/DummyClients/include/aws/gamelift/model/ListAliasesResult.h | 7c66479a2ddf34c6b924b2bf8d51ede4f2bde171 | [
"MIT"
] | permissive | joonhochoi/GameLift | bf6dbabcba868540bd9cf834623b189c65628b39 | 81bbad1e922d977bd885cdaa37f2e05d4fe2b966 | refs/heads/master | 2020-12-24T12:06:37.600884 | 2016-10-27T06:47:53 | 2016-10-27T06:47:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,093 | h | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#pragma once
#include <aws/gamelift/GameLift_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/gamelift/model/Alias.h>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace GameLift
{
namespace Model
{
/**
* <p>Represents the returned data in response to a request action.</p>
*/
class AWS_GAMELIFT_API ListAliasesResult
{
public:
ListAliasesResult();
ListAliasesResult(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
ListAliasesResult& operator=(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>Collection of alias records that match the list request. </p>
*/
inline const Aws::Vector<Alias>& GetAliases() const{ return m_aliases; }
/**
* <p>Collection of alias records that match the list request. </p>
*/
inline void SetAliases(const Aws::Vector<Alias>& value) { m_aliases = value; }
/**
* <p>Collection of alias records that match the list request. </p>
*/
inline void SetAliases(Aws::Vector<Alias>&& value) { m_aliases = value; }
/**
* <p>Collection of alias records that match the list request. </p>
*/
inline ListAliasesResult& WithAliases(const Aws::Vector<Alias>& value) { SetAliases(value); return *this;}
/**
* <p>Collection of alias records that match the list request. </p>
*/
inline ListAliasesResult& WithAliases(Aws::Vector<Alias>&& value) { SetAliases(value); return *this;}
/**
* <p>Collection of alias records that match the list request. </p>
*/
inline ListAliasesResult& AddAliases(const Alias& value) { m_aliases.push_back(value); return *this; }
/**
* <p>Collection of alias records that match the list request. </p>
*/
inline ListAliasesResult& AddAliases(Alias&& value) { m_aliases.push_back(value); return *this; }
/**
* <p>Token indicating where to resume retrieving results on the next call to this
* action. If no token is returned, these results represent the end of the
* list.</p> <note> <p>If a request has a limit that exactly matches the number of
* remaining results, a token is returned even though there are no more results to
* retrieve.</p> </note>
*/
inline const Aws::String& GetNextToken() const{ return m_nextToken; }
/**
* <p>Token indicating where to resume retrieving results on the next call to this
* action. If no token is returned, these results represent the end of the
* list.</p> <note> <p>If a request has a limit that exactly matches the number of
* remaining results, a token is returned even though there are no more results to
* retrieve.</p> </note>
*/
inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }
/**
* <p>Token indicating where to resume retrieving results on the next call to this
* action. If no token is returned, these results represent the end of the
* list.</p> <note> <p>If a request has a limit that exactly matches the number of
* remaining results, a token is returned even though there are no more results to
* retrieve.</p> </note>
*/
inline void SetNextToken(Aws::String&& value) { m_nextToken = value; }
/**
* <p>Token indicating where to resume retrieving results on the next call to this
* action. If no token is returned, these results represent the end of the
* list.</p> <note> <p>If a request has a limit that exactly matches the number of
* remaining results, a token is returned even though there are no more results to
* retrieve.</p> </note>
*/
inline void SetNextToken(const char* value) { m_nextToken.assign(value); }
/**
* <p>Token indicating where to resume retrieving results on the next call to this
* action. If no token is returned, these results represent the end of the
* list.</p> <note> <p>If a request has a limit that exactly matches the number of
* remaining results, a token is returned even though there are no more results to
* retrieve.</p> </note>
*/
inline ListAliasesResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}
/**
* <p>Token indicating where to resume retrieving results on the next call to this
* action. If no token is returned, these results represent the end of the
* list.</p> <note> <p>If a request has a limit that exactly matches the number of
* remaining results, a token is returned even though there are no more results to
* retrieve.</p> </note>
*/
inline ListAliasesResult& WithNextToken(Aws::String&& value) { SetNextToken(value); return *this;}
/**
* <p>Token indicating where to resume retrieving results on the next call to this
* action. If no token is returned, these results represent the end of the
* list.</p> <note> <p>If a request has a limit that exactly matches the number of
* remaining results, a token is returned even though there are no more results to
* retrieve.</p> </note>
*/
inline ListAliasesResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}
private:
Aws::Vector<Alias> m_aliases;
Aws::String m_nextToken;
};
} // namespace Model
} // namespace GameLift
} // namespace Aws
| [
"spacesun@naver.com"
] | spacesun@naver.com |
2d4b9e8a79b204aec4d1de65544a128d936073e5 | 0b61d90afd0c72155a9b28951995ed23eae70e16 | /Source/SmartSPS/SmartSPS/node_blfrs.h | 7f97b63d167ecfb6cfcdec4b7a0b12ab9887a469 | [
"MIT"
] | permissive | RBEGamer/HomePLC | 76aaf1b9386bf1faee63c2d5172f61d5e1a03eb5 | 65dbf7224563878d0550dea9a8df731437d4f83c | refs/heads/master | 2023-02-23T17:30:02.378516 | 2023-02-06T16:07:01 | 2023-02-06T16:07:01 | 47,475,515 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 999 | h | #pragma once
#include "single_node_include.h"
class node_blfrs : public base_node
{
public:
node_blfrs(int id, bool us, const int con_count, std::string params, bool is_static, bool ut);
~node_blfrs();
void update(float timestep = 0.0f);
void init();
void load_node_parameters(std::string params);
connector* p_connections;
int connection_count;
void set_connection(int pos, base_node* ptr, int dest_pos);
virtual void serial_income(std::string message);
//PARAMS
//VALUES
bool p0_a_input; //pos 0
bool p1_b_input;
bool last_set_a;
bool p2_c_output;
bool outuput_updated;
bool last_state_a;
bool last_state_b;
bool update_v;
bool last_set_b;
void set_value(int position, float value);
void set_value(int position, int value);
void set_value(int position, bool value);
void set_value(int position, std::string value);
float get_value_f(int position);
int get_value_i(int position);
bool get_value_b(int position);
std::string get_value_s(int position);
private:
};
| [
"marcel.ochsendorf@gmail.com"
] | marcel.ochsendorf@gmail.com |
f108a73935c7a1a8fcdbe75035e97d96b7f6f200 | 31738a884a8d66abef58459247cbbd8d8e4355ed | /src/pair.h | a369e027e5c8f5d1d1f00a8c2e64eee673b0b97f | [] | no_license | kyho4515/FinalProject | 9a563dd548a9679179cc1e9dee064045d73fa126 | 473473d10883846cd28b5829871ab10595e7a9b2 | refs/heads/master | 2020-06-08T16:33:49.160471 | 2015-09-06T07:38:44 | 2015-09-06T07:38:44 | 39,369,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,429 | h | #ifndef POTENTIALPAIR
#define POTENTIALPAIR
#include "Gate.h"
#include "util.h"
#include <fstream>
#include <algorithm>
#include <math.h>
#include <stack>
class PotentialPair{
public:
PotentialPair(vector<vector<Wire*>*>);//input為_FECpair
~PotentialPair(){
for(int i=0;i<pair.size();i++){
delete pair[i];
delete commonIn[i];
}
delete number;
}
void Out();
private:
vector<vector<Wire*>*> pair;
vector<vector<Gate*>*> commonIn;//每一組pair的common input
vector<Gate*>differentIn;
vector<Gate*>store;
vector<int> overflowpair;
vector<vector<Gate*> > temDFSlist;
int start;
int *number;
fstream output;
bool RepeatInPair(int starting,Wire* unfind);//從pair中找到wire可能的位置
void FindCommonInput(Wire*,Wire*,int);//找相同的input
void FindCommonInput(Wire*,int);//
bool ProveDontCare(Wire*,Wire*,int);//證明不同的input為dont care term
bool ProveFunction(Wire*,Wire*,int);//證明function相同或相反
void DFS(Gate*);//做DFS
bool ProveEqual(Wire*,Wire*,int);
bool InSameLine(Wire*,Wire*);//證明wire沒有上下關係
bool DFSFind(Gate*,Gate*);//DFS尋找後面的wire
void cleanstore();
static bool sortcompare(const Wire* l,const Wire* r){ //sort的判斷式
return l->gateLevel < r->gateLevel;
}
void GiveNumber(vector<Gate*>*,int,bool);//10個input以內用確定的證明,超過10個用隨機證明
};
#endif
| [
"willywsm1013@gmail.com"
] | willywsm1013@gmail.com |
50832aad5d2a4ee9254f1091652e2e939497efd0 | f267b24a6bcab15be3ff54e733e2e38acaf22576 | /C/12. login.cpp | 083a96384aafe354f8e5f3b9f32df1cfca442462 | [] | no_license | BusBang/Practice-PythonAndR | b5fb5f29fe2c6fa8afc6154c7da30689d9bdf518 | b79cbd31ab009c63562746f595f30ef103511255 | refs/heads/master | 2022-12-31T03:36:35.916456 | 2020-10-21T14:55:25 | 2020-10-21T14:55:25 | 284,936,368 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 279 | cpp | #include <stdio.h>
int main(void) {
int x = 50, y = 30;
printf("x가 y보다 크고, y는 40 미만입니까? %d\n", (x>y) && (y<40));
printf("x가 y보다 작거나, y는 30입니까? %d\n", (x<y) || (y<30));
printf("x가 50이 아닙니까? %d", x!= 50);
return 0;
}
| [
"58544672+BusBang@users.noreply.github.com"
] | 58544672+BusBang@users.noreply.github.com |
7bd0ab8a7b33cca727d918e63f2b72e341c42ade | caf55812511d43016cfe908a279ef60915f3428a | /Source/BWEB/Wall.cpp | 1d44f6995319300ff71dc407fd5ef59bfaaf85d5 | [
"MIT"
] | permissive | impie66/McRave | 8572655d65b1bbf1bceba79431b222e724c431cb | 51ff5a0768dc553f4adea109784035b5d6020fd1 | refs/heads/master | 2022-12-08T23:04:16.276859 | 2020-08-31T12:48:34 | 2020-08-31T12:48:34 | 291,378,719 | 2 | 0 | null | 2020-08-30T01:36:49 | 2020-08-30T01:36:48 | null | UTF-8 | C++ | false | false | 49,559 | cpp | #include "BWEB.h"
#include <chrono>
using namespace std;
using namespace BWAPI;
namespace BWEB {
namespace {
map<const BWEM::ChokePoint *, Wall> walls;
bool logInfo = true;
int failedPlacement = 0;
int failedAngle = 0;
int failedPath = 0;
int failedTight = 0;
int failedSpawn = 0;
int failedPower = 0;
int resourceGrid[256][256];
int testGrid[256][256];
}
Position Wall::findCentroid()
{
// Create current centroid using all buildings except Pylons
auto currentCentroid = Position(0, 0);
auto sizeWall = int(rawBuildings.size());
for (auto &[tile, type] : bestLayout) {
if (type != UnitTypes::Protoss_Pylon)
currentCentroid += Position(tile) + Position(type.tileSize()) / 2;
else
sizeWall--;
}
// Create a centroid if we only have a Pylon wall
if (sizeWall == 0) {
sizeWall = bestLayout.size();
for (auto &[tile, type] : bestLayout)
currentCentroid += Position(tile) + Position(type.tileSize()) / 2;
}
return (currentCentroid / sizeWall);
}
TilePosition Wall::findOpening()
{
if (!openWall)
return TilePositions::Invalid;
// Set any tiles on the path as reserved so we don't build on them
auto currentPath = findPathOut();
auto currentOpening = TilePositions::Invalid;
// Check which tile is closest to each part on the path, set as opening
auto distBest = DBL_MAX;
for (auto &pathTile : currentPath.getTiles()) {
const auto closestChokeGeo = Map::getClosestChokeTile(choke, Position(pathTile));
const auto dist = closestChokeGeo.getDistance(Position(pathTile));
const auto centerPath = Position(pathTile) + Position(16, 16);
auto angleOkay = true;
auto distOkay = false;
// Check if the angle and distance is okay
for (auto &[tileLayout, typeLayout] : currentLayout) {
if (typeLayout == UnitTypes::Protoss_Pylon)
continue;
const auto centerPiece = Position(tileLayout) + Position(typeLayout.tileWidth() * 16, typeLayout.tileHeight() * 16);
const auto openingAngle = Map::getAngle(make_pair(centerPiece, centerPath));
const auto openingDist = centerPiece.getDistance(centerPath);
if (abs(chokeAngle - openingAngle) > 35.0)
angleOkay = false;
if (openingDist < 320.0)
distOkay = true;
}
if (distOkay && angleOkay && dist < distBest) {
distBest = dist;
currentOpening = pathTile;
}
}
// If we don't have an opening, assign closest path tile to wall centroid as opening
if (!currentOpening.isValid()) {
for (auto &pathTile : currentPath.getTiles()) {
const auto p = Position(pathTile);
const auto dist = centroid.getDistance(p);
if (dist < distBest) {
distBest = dist;
currentOpening = pathTile;
}
}
}
return currentOpening;
}
Path Wall::findPathOut()
{
// Check that the path points are possible to reach
checkPathPoints();
const auto startCenter = Position(pathStart) + Position(16, 16);
const auto endCenter = Position(pathEnd) + Position(16, 16);
// Get a new path
BWEB::Path newPath(endCenter, startCenter, UnitTypes::Protoss_Dragoon);
allowLifted = false;
newPath.generateBFS([&](const auto &t) { return wallWalkable(t); }, false);
return newPath;
}
bool Wall::powerCheck(const UnitType type, const TilePosition here)
{
if (type != UnitTypes::Protoss_Pylon || pylonWall)
return true;
// TODO: Create a generic BWEB function that takes 2 tiles and tells you if the 1st tile will power the 2nd tile
for (auto &[tileLayout, typeLayout] : currentLayout) {
if (typeLayout == UnitTypes::Protoss_Pylon)
continue;
if (typeLayout.tileWidth() == 4) {
auto powersThis = false;
if (tileLayout.y - here.y == -5 || tileLayout.y - here.y == 4) {
if (tileLayout.x - here.x >= -4 && tileLayout.x - here.x <= 1)
powersThis = true;
}
if (tileLayout.y - here.y == -4 || tileLayout.y - here.y == 3) {
if (tileLayout.x - here.x >= -7 && tileLayout.x - here.x <= 4)
powersThis = true;
}
if (tileLayout.y - here.y == -3 || tileLayout.y - here.y == 2) {
if (tileLayout.x - here.x >= -8 && tileLayout.x - here.x <= 5)
powersThis = true;
}
if (tileLayout.y - here.y >= -2 && tileLayout.y - here.y <= 1) {
if (tileLayout.x - here.x >= -8 && tileLayout.x - here.x <= 6)
powersThis = true;
}
if (!powersThis)
return false;
}
else {
auto powersThis = false;
if (tileLayout.y - here.y == 4) {
if (tileLayout.x - here.x >= -3 && tileLayout.x - here.x <= 2)
powersThis = true;
}
if (tileLayout.y - here.y == -4 || tileLayout.y - here.y == 3) {
if (tileLayout.x - here.x >= -6 && tileLayout.x - here.x <= 5)
powersThis = true;
}
if (tileLayout.y - here.y >= -3 && tileLayout.y - here.y <= 2) {
if (tileLayout.x - here.x >= -7 && tileLayout.x - here.x <= 6)
powersThis = true;
}
if (!powersThis)
return false;
}
}
return true;
}
bool Wall::angleCheck(const UnitType type, const TilePosition here)
{
const auto centerHere = Position(here) + Position(type.tileWidth() * 16, type.tileHeight() * 16);
// If we want a closed wall, we don't care the angle of the buildings
if (!openWall || (type == UnitTypes::Protoss_Pylon && !pylonWall && !pylonWallPiece))
return true;
// Check if the angle is okay between all pieces in the current layout
for (auto &[tileLayout, typeLayout] : currentLayout) {
if (typeLayout == UnitTypes::Protoss_Pylon)
continue;
const auto centerPiece = Position(tileLayout) + Position(typeLayout.tileWidth() * 16, typeLayout.tileHeight() * 16);
const auto wallAngle = Map::getAngle(make_pair(centerPiece, centerHere));
if (abs(chokeAngle - wallAngle) > 20.0)
return false;
}
return true;
}
bool Wall::placeCheck(const UnitType type, const TilePosition here)
{
// Allow Pylon to overlap station defenses
if (type == UnitTypes::Protoss_Pylon) {
if (closestStation && closestStation->getDefenseLocations().find(here) != closestStation->getDefenseLocations().end())
return true;
}
// Check if placement is valid
if (Map::isReserved(here, type.tileWidth(), type.tileHeight())
|| !Map::isPlaceable(type, here)
|| (!openWall && Map::tilesWithinArea(area, here, type.tileWidth(), type.tileHeight()) == 0)
|| (openWall && Map::tilesWithinArea(area, here, type.tileWidth(), type.tileHeight()) == 0 && (type == UnitTypes::Protoss_Pylon || (Map::mapBWEM.GetArea(here) && choke->GetAreas().first != Map::mapBWEM.GetArea(here) && choke->GetAreas().second != Map::mapBWEM.GetArea(here)))))
return false;
return true;
}
bool Wall::tightCheck(const UnitType type, const TilePosition here)
{
// If this is a powering pylon and we are not making a pylon wall, we don't care if it's tight
if (type == UnitTypes::Protoss_Pylon && !pylonWall && !pylonWallPiece)
return true;
// Dimensions of current buildings UnitType
const auto dimL = (type.tileWidth() * 16) - type.dimensionLeft();
const auto dimR = (type.tileWidth() * 16) - type.dimensionRight() - 1;
const auto dimU = (type.tileHeight() * 16) - type.dimensionUp();
const auto dimD = (type.tileHeight() * 16) - type.dimensionDown() - 1;
const auto walkHeight = type.tileHeight() * 4;
const auto walkWidth = type.tileWidth() * 4;
// Dimension of UnitType to check tightness for
const auto vertTight = (tightType == UnitTypes::None) ? 32 : tightType.height();
const auto horizTight = (tightType == UnitTypes::None) ? 32 : tightType.width();
// Checks each side of the building to see if it is valid for walling purposes
const auto checkL = dimL < horizTight;
const auto checkR = dimR < horizTight;
const auto checkU = dimU < vertTight;
const auto checkD = dimD < vertTight;
// Figures out how many extra tiles we can check tightness for
const auto extraL = pylonWall || !requireTight ? 0 : max(0, (horizTight - dimL) / 8);
const auto extraR = pylonWall || !requireTight ? 0 : max(0, (horizTight - dimR) / 8);
const auto extraU = pylonWall || !requireTight ? 0 : max(0, (vertTight - dimU) / 8);
const auto extraD = pylonWall || !requireTight ? 0 : max(0, (vertTight - dimD) / 8);
// Setup boundary WalkPositions to check for tightness
const auto left = WalkPosition(here) - WalkPosition(1 + extraL, 0);
const auto right = WalkPosition(here) + WalkPosition(walkWidth + extraR, 0);
const auto up = WalkPosition(here) - WalkPosition(0, 1 + extraU);
const auto down = WalkPosition(here) + WalkPosition(0, walkHeight + extraD);
// Used for determining if the tightness we found is suitable
const auto firstBuilding = currentLayout.size() == 0;
const auto lastBuilding = currentLayout.size() == (rawBuildings.size() - 1);
auto terrainTight = false;
auto parentTight = false;
auto p1Tight = 0;
auto p2Tight = 0;
// Functions for each dimension check
const auto gapRight = [&](UnitType parent) {
return (parent.tileWidth() * 16) - parent.dimensionLeft() + dimR;
};
const auto gapLeft = [&](UnitType parent) {
return (parent.tileWidth() * 16) - parent.dimensionRight() - 1 + dimL;
};
const auto gapUp = [&](UnitType parent) {
return (parent.tileHeight() * 16) - parent.dimensionDown() - 1 + dimU;
};
const auto gapDown = [&](UnitType parent) {
return (parent.tileHeight() * 16) - parent.dimensionUp() + dimD;
};
// Check if the building is terrain tight when placed here
const auto terrainTightCheck = [&](WalkPosition w, bool check) {
const auto t = TilePosition(w);
// If the walkposition is invalid or unwalkable
if (tightType != UnitTypes::None && check && (!w.isValid() || !Broodwar->isWalkable(w)))
return true;
// If we don't care about walling tight and the tile isn't walkable
if (!requireTight && !Map::isWalkable(t))
return true;
// If there's a mineral field or geyser here
if (Map::isUsed(t).isResourceContainer())
return true;
return false;
};
// Iterate vertical tiles adjacent of this placement
const auto checkVerticalSide = [&](WalkPosition start, bool check, const auto gap) {
for (auto x = start.x - 1; x < start.x + walkWidth + 1; x++) {
const WalkPosition w(x, start.y);
const auto t = TilePosition(w);
const auto parent = Map::isUsed(t);
const auto leftCorner = x < start.x;
const auto rightCorner = x >= start.x + walkWidth;
// If this is a corner
if (leftCorner || rightCorner) {
// Check if it's tight with the terrain
if (!terrainTight && terrainTightCheck(w, check) && leftCorner ? terrainTightCheck(w, checkL) : terrainTightCheck(w, checkR))
terrainTight = true;
// Check if it's tight with a parent
if (!parentTight && find(rawBuildings.begin(), rawBuildings.end(), parent) != rawBuildings.end() && (!requireTight || (gap(parent) < vertTight && (leftCorner ? gapLeft(parent) < horizTight : gapRight(parent) < horizTight))))
parentTight = true;
}
else {
// Check if it's tight with the terrain
if (!terrainTight && terrainTightCheck(w, check))
terrainTight = true;
// Check if it's tight with a parent
if (!parentTight && find(rawBuildings.begin(), rawBuildings.end(), parent) != rawBuildings.end() && (!requireTight || gap(parent) < vertTight))
parentTight = true;
}
// Check to see which node it is closest to (0 is don't check, 1 is not tight, 2 is tight)
if (!openWall && !Map::isWalkable(t) && w.getDistance(choke->Center()) < 4) {
if (w.getDistance(choke->Pos(choke->end1)) < w.getDistance(choke->Pos(choke->end2))) {
if (p1Tight == 0)
p1Tight = 1;
if (terrainTight)
p1Tight = 2;
}
else if (p2Tight == 0) {
if (p2Tight == 0)
p2Tight = 1;
if (terrainTight)
p2Tight = 2;
}
}
}
};
// Iterate horizontal tiles adjacent of this placement
const auto checkHorizontalSide = [&](WalkPosition start, bool check, const auto gap) {
for (auto y = start.y - 1; y < start.y + walkHeight + 1; y++) {
const WalkPosition w(start.x, y);
const auto t = TilePosition(w);
const auto parent = Map::isUsed(t);
const auto topCorner = y < start.y;
const auto downCorner = y >= start.y + walkHeight;
// If this is a corner
if (topCorner || downCorner) {
// Check if it's tight with the terrain
if (!terrainTight && terrainTightCheck(w, check) && topCorner ? terrainTightCheck(w, checkU) : terrainTightCheck(w, checkD))
terrainTight = true;
// Check if it's tight with a parent
if (!parentTight && find(rawBuildings.begin(), rawBuildings.end(), parent) != rawBuildings.end() && (!requireTight || (gap(parent) < horizTight && (topCorner ? gapUp(parent) < vertTight : gapDown(parent) < vertTight))))
parentTight = true;
}
else {
// Check if it's tight with the terrain
if (!terrainTight && terrainTightCheck(w, check))
terrainTight = true;
// Check if it's tight with a parent
if (!parentTight && find(rawBuildings.begin(), rawBuildings.end(), parent) != rawBuildings.end() && (!requireTight || gap(parent) < horizTight))
parentTight = true;
}
// Check to see which node it is closest to (0 is don't check, 1 is not tight, 2 is tight)
if (!openWall && !Map::isWalkable(t) && w.getDistance(choke->Center()) < 4) {
if (w.getDistance(choke->Pos(choke->end1)) < w.getDistance(choke->Pos(choke->end2))) {
if (p1Tight == 0)
p1Tight = 1;
if (terrainTight)
p1Tight = 2;
}
else if (p2Tight == 0) {
if (p2Tight == 0)
p2Tight = 1;
if (terrainTight)
p2Tight = 2;
}
}
}
};
// For each side, check if it's terrain tight or tight with any adjacent buildings
checkVerticalSide(up, checkU, gapUp);
checkVerticalSide(down, checkD, gapDown);
checkHorizontalSide(left, checkL, gapLeft);
checkHorizontalSide(right, checkR, gapRight);
// If we want a closed wall, we need all buildings to be tight at the tightness resolution...
if (!openWall) {
if (!lastBuilding && !firstBuilding) // ...to the parent if not first building
return parentTight;
if (firstBuilding) // ...to the terrain if first building
return terrainTight && p1Tight != 1 && p2Tight != 1;
if (lastBuilding) // ...to the parent and terrain if last building
return terrainTight && parentTight && p1Tight != 1 && p2Tight != 1;
}
// If we want an open wall, we need this building to be tight at tile resolution to a parent or terrain
else if (openWall)
return (terrainTight || parentTight);
return false;
}
bool Wall::spawnCheck(const UnitType type, const TilePosition here)
{
// TODO: Check if units spawn in bad spots, just returns true for now
checkPathPoints();
const auto startCenter = Position(pathStart) + Position(16, 16);
const auto endCenter = Position(pathEnd) + Position(16, 16);
Path pathOut;
return true;
}
bool Wall::wallWalkable(const TilePosition& tile)
{
// Checks for any collision and inverts the return value
if (!tile.isValid()
|| (Map::mapBWEM.GetArea(tile) && Map::mapBWEM.GetArea(tile) != area && find(accessibleNeighbors.begin(), accessibleNeighbors.end(), Map::mapBWEM.GetArea(tile)) == accessibleNeighbors.end())
|| Map::isReserved(tile)
|| !Map::isWalkable(tile)
|| (allowLifted && Map::isUsed(tile) != UnitTypes::Terran_Barracks && Map::isUsed(tile) != UnitTypes::None)
|| (!allowLifted && Map::isUsed(tile) != UnitTypes::None && Map::isUsed(tile) != UnitTypes::Zerg_Larva)
//|| (openWall && (tile).getDistance(pathEnd) - 96.0 > jpsDist / 32)
|| resourceGrid[tile.x][tile.y] > 0)
return false;
return true;
}
void Wall::initialize()
{
// Clear failed counters
failedPlacement = 0;
failedAngle = 0;
failedPath = 0;
failedTight = 0;
failedSpawn = 0;
failedPower = 0;
// Set BWAPI::Points to invalid (default constructor is None)
centroid = BWAPI::Positions::Invalid;
opening = BWAPI::TilePositions::Invalid;
pathStart = BWAPI::TilePositions::Invalid;
pathEnd = BWAPI::TilePositions::Invalid;
initialPathStart = BWAPI::TilePositions::Invalid;
initialPathEnd = BWAPI::TilePositions::Invalid;
// Set important terrain features
bestWallScore = 0;
accessibleNeighbors = area->AccessibleNeighbours();
chokeAngle = Map::getAngle(make_pair(Position(choke->Pos(choke->end1)) + Position(4, 4), Position(choke->Pos(choke->end2)) + Position(4, 4)));
pylonWall = count(rawBuildings.begin(), rawBuildings.end(), BWAPI::UnitTypes::Protoss_Pylon) > 1;
creationStart = TilePosition(choke->Center());
base = !area->Bases().empty() ? &area->Bases().front() : nullptr;
flatRamp = Broodwar->isBuildable(TilePosition(choke->Center()));
closestStation = Stations::getClosestStation(TilePosition(choke->Center()));
// Setup a resource grid that prevents pathing through mineral lines
if (base) {
for (auto &mineral : base->Minerals()) {
for (int x = -1; x < 3; x++) {
for (int y = -1; y < 3; y++) {
resourceGrid[mineral->TopLeft().x + x][mineral->TopLeft().y + y] = 1;
}
}
}
}
// Check if a Pylon should be put in the wall to help the size of the Wall or away from the wall for protection
auto p1 = choke->Pos(choke->end1);
auto p2 = choke->Pos(choke->end2);
pylonWallPiece = abs(p1.x - p2.x) * 8 >= 320 || abs(p1.y - p2.y) * 8 >= 256 || p1.getDistance(p2) * 8 >= 288;
// Initiliaze path points and check them
initializePathPoints();
checkPathPoints();
// Create a jps path for limiting BFS exploration using the distance of the jps path
Path jpsPath(Position(pathStart), Position(pathEnd), UnitTypes::Zerg_Zergling);
jpsPath.generateJPS([&](const TilePosition &t) { return jpsPath.unitWalkable(t); });
jpsDist = jpsPath.getDistance();
// Create notable locations to keep Wall pieces within proxmity of
if (base)
notableLocations ={ base->Center(), Position(initialPathStart) + Position(16,16), (base->Center() + Position(initialPathStart)) / 2 };
else
notableLocations ={ Position(initialPathStart) + Position(16,16), Position(initialPathEnd) + Position(16,16) };
// Sort all the pieces and iterate over them to find the best wall - by Hannes
if (find(rawBuildings.begin(), rawBuildings.end(), UnitTypes::Protoss_Pylon) != rawBuildings.end()) {
sort(rawBuildings.begin(), rawBuildings.end(), [](UnitType l, UnitType r) { return (l == UnitTypes::Protoss_Pylon) < (r == UnitTypes::Protoss_Pylon); }); // Moves pylons to end
sort(rawBuildings.begin(), find(rawBuildings.begin(), rawBuildings.end(), UnitTypes::Protoss_Pylon)); // Sorts everything before pylons
}
else if (find(rawBuildings.begin(), rawBuildings.end(), UnitTypes::Zerg_Hatchery) != rawBuildings.end()) {
sort(rawBuildings.begin(), rawBuildings.end(), [](UnitType l, UnitType r) { return (l == UnitTypes::Zerg_Hatchery) > (r == UnitTypes::Zerg_Hatchery); }); // Moves hatchery to start
sort(find(rawBuildings.begin(), rawBuildings.end(), UnitTypes::Zerg_Hatchery), rawBuildings.begin()); // Sorts everything after hatchery
}
else
sort(rawBuildings.begin(), rawBuildings.end());
// If there is a base in this area and we're creating an open wall, move creation start within 10 tiles of it
if (openWall && base) {
auto startCenter = Position(creationStart) + Position(16, 16);
auto distBest = DBL_MAX;
auto moveTowards = (Position(initialPathStart) + base->Center()) / 2;
// Iterate 3x3 around the current TilePosition and try to get within 5 tiles
auto triedCount = 0;
while (startCenter.getDistance(moveTowards) > 320.0 && triedCount < 50) {
triedCount++;
const auto initialStart = creationStart;
for (int x = initialStart.x - 1; x <= initialStart.x + 1; x++) {
for (int y = initialStart.y - 1; y <= initialStart.y + 1; y++) {
const TilePosition t(x, y);
if (!t.isValid())
continue;
const auto p = Position(t) + Position(16, 16);
const auto dist = p.getDistance(moveTowards);
if (dist < distBest) {
distBest = dist;
creationStart = t;
startCenter = p;
movedStart = true;
}
}
}
}
}
// If the creation start position isn't buildable, move towards the top of this area to find a buildable location
if (openWall) {
auto triedCount = 0;
while (!Broodwar->isBuildable(creationStart) && triedCount < 50) {
triedCount++;
auto distBest = DBL_MAX;
const auto initialStart = creationStart;
for (int x = initialStart.x - 1; x <= initialStart.x + 1; x++) {
for (int y = initialStart.y - 1; y <= initialStart.y + 1; y++) {
const TilePosition t(x, y);
if (!t.isValid())
continue;
const auto p = Position(t);
const auto dist = p.getDistance(Position(area->Top()));
if (dist < distBest) {
distBest = dist;
creationStart = t;
movedStart = true;
}
}
}
}
}
}
void Wall::initializePathPoints()
{
auto line = make_pair(Position(choke->Pos(choke->end1)) + Position(4, 4), Position(choke->Pos(choke->end2)) + Position(4, 4));
auto perpLine = openWall ? Map::perpendicularLine(line, 160.0) : Map::perpendicularLine(line, 96.0);
auto lineStart = perpLine.first.getDistance(Position(area->Top())) > perpLine.second.getDistance(Position(area->Top())) ? perpLine.second : perpLine.first;
auto lineEnd = perpLine.first.getDistance(Position(area->Top())) > perpLine.second.getDistance(Position(area->Top())) ? perpLine.first : perpLine.second;
auto isMain = closestStation && closestStation->isMain();
auto isNatural = closestStation && closestStation->isNatural();
// If it's a natural wall, path between the closest main and end of the perpendicular line
if (isNatural) {
Station * closestMain = Stations::getClosestMainStation(TilePosition(choke->Center()));
initialPathStart = closestMain ? TilePosition(Map::mapBWEM.GetPath(closestStation->getBase()->Center(), closestMain->getBase()->Center()).front()->Center()) : TilePosition(lineStart);
initialPathEnd = TilePosition(lineEnd);
}
// If it's a main wall, path between a point between the roughly the choke and the area top
else if (isMain) {
initialPathEnd = (TilePosition(choke->Center()) + TilePosition(lineEnd)) / 2;
initialPathStart = (TilePosition(area->Top()) + TilePosition(lineStart)) / 2;
}
// Other walls
else {
initialPathStart = TilePosition(lineStart);
initialPathEnd = TilePosition(lineEnd);
}
pathStart = initialPathStart;
pathEnd = initialPathEnd;
}
void Wall::checkPathPoints()
{
const auto neighbourArea = [&](const BWEM::Area * area) {
for (auto subArea : area->AccessibleNeighbours()) {
if (area == subArea)
return true;
}
return false;
};
const auto notValidPathPoint = [&](const TilePosition testTile) {
return !testTile.isValid()
|| !Map::isWalkable(testTile)
|| Map::isReserved(testTile)
|| Map::isUsed(testTile) != UnitTypes::None;
};
// Push the path start as far from the path end if it's not in a valid location
auto distBest = 0.0;
if (notValidPathPoint(pathStart)) {
for (auto x = initialPathStart.x - 4; x < initialPathStart.x + 4; x++) {
for (auto y = initialPathStart.y - 4; y < initialPathStart.y + 4; y++) {
const TilePosition t(x, y);
const auto dist = t.getDistance(initialPathEnd);
if (notValidPathPoint(t))
continue;
if (dist > distBest) {
pathStart = t;
distBest = dist;
}
}
}
}
// Push the path end as far from the path start if it's not in a valid location
distBest = 0.0;
if (notValidPathPoint(pathEnd)) {
for (auto x = initialPathEnd.x - 4; x < initialPathEnd.x + 4; x++) {
for (auto y = initialPathEnd.y - 4; y < initialPathEnd.y + 4; y++) {
const TilePosition t(x, y);
const auto dist = t.getDistance(initialPathStart);
if (notValidPathPoint(t))
continue;
if (dist > distBest) {
pathEnd = t;
distBest = dist;
}
}
}
}
}
void Wall::addPieces()
{
// For each permutation, try to make a wall combination that is better than the current best
do {
currentLayout.clear();
typeIterator = rawBuildings.begin();
addNextPiece(creationStart);
} while (Broodwar->self()->getRace() == Races::Zerg ? next_permutation(find(rawBuildings.begin(), rawBuildings.end(), UnitTypes::Zerg_Hatchery), rawBuildings.end())
: next_permutation(rawBuildings.begin(), find(rawBuildings.begin(), rawBuildings.end(), UnitTypes::Protoss_Pylon)));
for (auto &[tile, type] : bestLayout) {
addToWallPieces(tile, type);
Map::addReserve(tile, type.tileWidth(), type.tileHeight());
Map::addUsed(tile, type);
}
}
void Wall::addNextPiece(TilePosition start)
{
const auto type = *typeIterator;
const auto radius = (openWall || typeIterator == rawBuildings.begin()) ? 8 : 4;
for (auto x = start.x - radius; x < start.x + radius; x++) {
for (auto y = start.y - radius; y < start.y + radius; y++) {
const TilePosition tile(x, y);
if (!tile.isValid())
continue;
const auto center = Position(tile) + Position(type.tileWidth() * 16, type.tileHeight() * 16);
const auto closestGeo = Map::getClosestChokeTile(choke, center);
// Open walls need to be placed within proximity of notable features
if (openWall) {
auto closestNotable = Positions::Invalid;
auto closestNotableDist = DBL_MAX;
for (auto & pos : notableLocations) {
auto dist = pos.getDistance(center);
if (dist < closestNotableDist) {
closestNotable = pos;
closestNotableDist = dist;
}
}
if (center.getDistance(closestNotable) >= 288.0 || center.getDistance(closestNotable) >= closestGeo.getDistance(closestNotable) + 48.0)
continue;
}
// Try not to seal the wall poorly
if (!openWall && flatRamp) {
auto dist = min({ Position(tile).getDistance(Position(choke->Center())),
Position(tile + TilePosition(type.tileWidth(), 0)).getDistance(Position(choke->Center())),
Position(tile + TilePosition(type.tileWidth(), type.tileHeight())).getDistance(Position(choke->Center())),
Position(tile + TilePosition(0, type.tileHeight())).getDistance(Position(choke->Center())) });
if (dist < 64.0)
continue;
}
// Required checks for this wall to be valid
if (!powerCheck(type, tile)) {
failedPower++;
continue;
}
if (!angleCheck(type, tile)) {
failedAngle++;
continue;
}
if (!placeCheck(type, tile)) {
failedPlacement++;
continue;
}
if (!tightCheck(type, tile)) {
failedTight++;
continue;
}
if (!spawnCheck(type, tile)) {
failedSpawn++;
continue;
}
// 1) Store the current type, increase the iterator
currentLayout[tile] = type;
Map::addUsed(tile, type);
typeIterator++;
// 2) If at the end, score wall
if (typeIterator == rawBuildings.end())
scoreWall();
else
openWall ? addNextPiece(start) : addNextPiece(tile);
// 3) Erase this current placement and repeat
if (typeIterator != rawBuildings.begin())
typeIterator--;
currentLayout.erase(tile);
Map::removeUsed(tile, type.tileWidth(), type.tileHeight());
}
}
}
void Wall::addDefenses()
{
// Prevent adding defenses if we don't have a wall
if (bestLayout.empty())
return;
// Find the furthest non Pylon building to the chokepoint
auto furthest = 0.0;
for (auto &tile : largeTiles) {
const auto center = Position(tile) + Position(64, 48);
const auto closestGeo = Map::getClosestChokeTile(choke, center);
const auto dist = center.getDistance(closestGeo);
if (dist > furthest)
furthest = dist;
}
for (auto &tile : mediumTiles) {
const auto center = Position(tile) + Position(48, 32);
const auto closestGeo = Map::getClosestChokeTile(choke, center);
const auto dist = center.getDistance(closestGeo);
if (dist > furthest)
furthest = dist;
}
// Find the furthest Pylon building to the chokepoint if it's a Pylon wall
if (pylonWall) {
for (auto &tile : smallTiles) {
const auto center = Position(tile) + Position(32, 32);
const auto closestGeo = Map::getClosestChokeTile(choke, center);
const auto dist = center.getDistance(closestGeo);
if (dist > furthest)
furthest = dist;
}
}
auto closestStation = Stations::getClosestStation(TilePosition(choke->Center()));
for (auto &building : rawDefenses) {
const auto start = TilePosition(centroid);
const auto width = building.tileWidth() * 32;
const auto height = building.tileHeight() * 32;
const auto openingCenter = Position(opening) + Position(16, 16);
const auto arbitraryCloseMetric = Broodwar->self()->getRace() == Races::Zerg ? 32.0 : 160.0;
// Iterate around wall centroid to find a suitable position
auto scoreBest = DBL_MAX;
auto tileBest = TilePositions::Invalid;
for (auto x = start.x - 12; x <= start.x + 12; x++) {
for (auto y = start.y - 12; y <= start.y + 12; y++) {
const TilePosition t(x, y);
const auto center = Position(t) + Position(width / 2, height / 2);
const auto closestGeo = Map::getClosestChokeTile(choke, center);
const auto overlapsDefense = closestStation && closestStation->getDefenseLocations().find(t) != closestStation->getDefenseLocations().end() && defenses.find(t) == defenses.end();
const auto dist = center.getDistance(closestGeo);
const auto tooClose = dist < furthest || center.getDistance(openingCenter) < arbitraryCloseMetric;
const auto tooFar = center.getDistance(centroid) > 200.0;
if (!overlapsDefense) {
if (!t.isValid()
|| Map::isReserved(t, building.tileWidth(), building.tileHeight())
|| !Map::isPlaceable(building, t)
|| Map::tilesWithinArea(area, t, building.tileWidth(), building.tileHeight()) == 0
|| tooClose
|| tooFar)
continue;
}
const auto score = dist + center.getDistance(openingCenter);
if (score < scoreBest) {
Map::addUsed(t, building);
auto &pathOut = findPathOut();
if ((openWall && pathOut.isReachable()) || !openWall) {
tileBest = t;
scoreBest = score;
}
Map::removeUsed(t, building.tileWidth(), building.tileHeight());
}
}
}
// If tile is valid, add to wall
if (tileBest.isValid()) {
defenses.insert(tileBest);
Map::addReserve(tileBest, building.tileWidth(), building.tileHeight());
}
// Otherwise we can't place anymore
else
break;
}
}
void Wall::scoreWall()
{
// Create a path searching for an opening
auto pathOut = findPathOut();
// If we want an open wall and it's not reachable, or we want a closed wall and it is reachable
if ((openWall && !pathOut.isReachable()) || (!openWall && pathOut.isReachable())) {
failedPath++;
return;
}
// Find distance for each piece to the closest choke tile to the path start point
auto dist = 1.0;
auto optimalChokeTile = pathStart.getDistance(TilePosition(choke->Pos(choke->end1))) < pathStart.getDistance(TilePosition(choke->Pos(choke->end2))) ? Position(choke->Pos(choke->end1)) : Position(choke->Pos(choke->end2));
for (auto &[tile, type] : currentLayout) {
const auto center = Position(tile) + Position(type.tileWidth() * 16, type.tileHeight() * 16);
const auto chokeDist = optimalChokeTile.getDistance(center);
(type == UnitTypes::Protoss_Pylon && !pylonWall && !pylonWallPiece) ? dist += -chokeDist : dist += chokeDist;
}
// Calculate current centroid if a closed wall
auto currentCentroid = findCentroid();
auto currentOpening = Position(findOpening()) + Position(16, 16);
// Score wall and store if better than current best layout
const auto score = !openWall ? dist : 1.0 / dist;
if (score > bestWallScore) {
bestLayout = currentLayout;
bestWallScore = score;
}
}
void Wall::cleanup()
{
// Add a reserved path
if (openWall && !bestLayout.empty()) {
auto ¤tPath = findPathOut();
for (auto &tile : currentPath.getTiles())
Map::addReserve(tile, 1, 1);
}
// Remove used from tiles
for (auto &tile : smallTiles)
Map::removeUsed(tile, 2, 2);
for (auto &tile : mediumTiles)
Map::removeUsed(tile, 3, 2);
for (auto &tile : largeTiles)
Map::removeUsed(tile, 4, 3);
for (auto &tile : defenses)
Map::removeUsed(tile, 2, 2);
}
int Wall::getGroundDefenseCount()
{
// Returns how many visible ground defensive structures exist in this Walls defense locations
int count = 0;
for (auto &defense : defenses) {
auto &type = Map::isUsed(defense);
if (type == UnitTypes::Protoss_Photon_Cannon
|| type == UnitTypes::Zerg_Sunken_Colony
|| type == UnitTypes::Terran_Bunker)
count++;
}
return count;
}
int Wall::getAirDefenseCount()
{
// Returns how many visible air defensive structures exist in this Walls defense locations
int count = 0;
for (auto &defense : defenses) {
auto &type = Map::isUsed(defense);
if (type == UnitTypes::Protoss_Photon_Cannon
|| type == UnitTypes::Zerg_Spore_Colony
|| type == UnitTypes::Terran_Missile_Turret)
count++;
}
return count;
}
void Wall::draw()
{
set<Position> anglePositions;
int color = Broodwar->self()->getColor();
int textColor = color == 185 ? textColor = Text::DarkGreen : Broodwar->self()->getTextColor();
// Draw boxes around each feature
auto drawBoxes = true;
if (drawBoxes) {
for (auto &tile : smallTiles) {
Broodwar->drawBoxMap(Position(tile), Position(tile) + Position(65, 65), color);
Broodwar->drawTextMap(Position(tile) + Position(4, 4), "%cW", Broodwar->self()->getTextColor());
anglePositions.insert(Position(tile) + Position(32, 32));
}
for (auto &tile : mediumTiles) {
Broodwar->drawBoxMap(Position(tile), Position(tile) + Position(97, 65), color);
Broodwar->drawTextMap(Position(tile) + Position(4, 4), "%cW", Broodwar->self()->getTextColor());
anglePositions.insert(Position(tile) + Position(48, 32));
}
for (auto &tile : largeTiles) {
Broodwar->drawBoxMap(Position(tile), Position(tile) + Position(129, 97), color);
Broodwar->drawTextMap(Position(tile) + Position(4, 4), "%cW", Broodwar->self()->getTextColor());
anglePositions.insert(Position(tile) + Position(64, 48));
}
for (auto &tile : defenses) {
Broodwar->drawBoxMap(Position(tile), Position(tile) + Position(65, 65), color);
Broodwar->drawTextMap(Position(tile) + Position(4, 4), "%cW", Broodwar->self()->getTextColor());
}
}
// Draw angles of each piece
auto drawAngles = false;
if (drawAngles) {
for (auto &pos1 : anglePositions) {
for (auto &pos2 : anglePositions) {
if (pos1 == pos2)
continue;
const auto angle = Map::getAngle(make_pair(pos1, pos2));
Broodwar->drawLineMap(pos1, pos2, color);
Broodwar->drawTextMap((pos1 + pos2) / 2, "%c%.2f", textColor, angle);
}
}
}
// Draw opening
Broodwar->drawBoxMap(Position(opening), Position(opening) + Position(33, 33), color, true);
// Draw the line and angle of the ChokePoint
auto p1 = choke->Pos(choke->end1);
auto p2 = choke->Pos(choke->end2);
auto angle = Map::getAngle(make_pair(p1, p2));
Broodwar->drawTextMap(Position(choke->Center()), "%c%.2f", Text::Grey, angle);
Broodwar->drawLineMap(Position(p1), Position(p2), Colors::Grey);
// Draw the path points
Broodwar->drawCircleMap(Position(pathStart), 6, Colors::Black, true);
Broodwar->drawCircleMap(Position(pathEnd), 6, Colors::White, true);
}
}
namespace BWEB::Walls {
Wall* createWall(vector<UnitType>& buildings, const BWEM::Area * area, const BWEM::ChokePoint * choke, const UnitType tightType, const vector<UnitType>& defenses, const bool openWall, const bool requireTight)
{
ofstream writeFile;
string buffer;
auto timePointNow = chrono::system_clock::now();
auto timeNow = chrono::system_clock::to_time_t(timePointNow);
// Print the clock position of this Wall
auto clock = abs(round((Map::getAngle(make_pair(Map::mapBWEM.Center(), Position(area->Top()))) + 90) / 30));
if (Position(area->Top()).x < Map::mapBWEM.Center().x)
clock+= 6;
// Open the log file if desired and write information
if (logInfo) {
writeFile.open("bwapi-data/write/BWEB_Wall.txt", std::ios::app);
writeFile << ctime(&timeNow);
writeFile << Broodwar->mapFileName().c_str() << endl;
writeFile << "At: " << clock << " o'clock." << endl;
writeFile << endl;
writeFile << "Buildings:" << endl;
for (auto &building : buildings)
writeFile << building.c_str() << endl;
writeFile << endl;
}
// Verify inputs are correct
if (!area) {
writeFile << "BWEB: Can't create a wall without a valid BWEM::Area" << endl;
return nullptr;
}
if (!choke) {
writeFile << "BWEB: Can't create a wall without a valid BWEM::Chokepoint" << endl;
return nullptr;
}
if (buildings.empty()) {
writeFile << "BWEB: Can't create a wall with an empty vector of UnitTypes." << endl;
return nullptr;
}
// Verify not attempting to create a Wall in the same Area/ChokePoint combination
for (auto &[_, wall] : walls) {
if (wall.getArea() == area && wall.getChokePoint() == choke) {
writeFile << "BWEB: Can't create a Wall where one already exists." << endl;
return &wall;
}
}
// Create a Wall
Wall wall(area, choke, buildings, defenses, tightType, requireTight, openWall);
// Verify the Wall creation was successful
auto wallFound = (wall.getSmallTiles().size() + wall.getMediumTiles().size() + wall.getLargeTiles().size()) == wall.getRawBuildings().size();
// Log information
if (logInfo) {
writeFile << "Failure Reasons:" << endl;
writeFile << "Power: " << failedPower << endl;
writeFile << "Angle: " << failedAngle << endl;
writeFile << "Placement: " << failedPlacement << endl;
writeFile << "Tight: " << failedTight << endl;
writeFile << "Path: " << failedPath << endl;
writeFile << "Spawn: " << failedSpawn << endl;
writeFile << endl;
double dur = std::chrono::duration <double, std::milli>(chrono::system_clock::now() - timePointNow).count();
writeFile << "Generation Time: " << dur << "ms and " << (wallFound ? "succesful." : "failed.") << endl;
writeFile << "--------------------" << endl;
}
// If we found a suitable Wall, push into container and return pointer to it
if (wallFound) {
walls.emplace(choke, wall);
return &walls.at(choke);
}
return nullptr;
}
Wall* createFFE()
{
vector<UnitType> buildings ={ UnitTypes::Protoss_Forge, UnitTypes::Protoss_Gateway, UnitTypes::Protoss_Pylon };
vector<UnitType> defenses(10, UnitTypes::Protoss_Photon_Cannon);
return createWall(buildings, Map::getNaturalArea(), Map::getNaturalChoke(), UnitTypes::None, defenses, true, false);
}
Wall* createZSimCity()
{
vector<UnitType> buildings ={ UnitTypes::Zerg_Hatchery, UnitTypes::Zerg_Evolution_Chamber };
vector<UnitType> defenses(10, UnitTypes::Zerg_Sunken_Colony);
return createWall(buildings, Map::getNaturalArea(), Map::getNaturalChoke(), UnitTypes::None, defenses, true, false);
}
Wall* createTWall()
{
vector<UnitType> buildings ={ UnitTypes::Terran_Supply_Depot, UnitTypes::Terran_Supply_Depot, UnitTypes::Terran_Barracks };
vector<UnitType> defenses;
auto type = Broodwar->enemy() && Broodwar->enemy()->getRace() == Races::Protoss ? UnitTypes::Protoss_Zealot : UnitTypes::Zerg_Zergling;
return createWall(buildings, Map::getMainArea(), Map::getMainChoke(), type, defenses, false, true);
}
Wall* getClosestWall(TilePosition here)
{
auto distBest = DBL_MAX;
Wall * bestWall = nullptr;
for (auto &[_, wall] : walls) {
const auto dist = here.getDistance(TilePosition(wall.getChokePoint()->Center()));
if (dist < distBest) {
distBest = dist;
bestWall = &wall;
}
}
return bestWall;
}
Wall* getWall(const BWEM::ChokePoint * choke)
{
if (!choke)
return nullptr;
for (auto &[_, wall] : walls) {
if (wall.getChokePoint() == choke)
return &wall;
}
return nullptr;
}
map<const BWEM::ChokePoint *, Wall>& getWalls() {
return walls;
}
void draw()
{
for (auto &[_, wall] : walls)
wall.draw();
}
}
| [
"christianmccrave@gmail.com"
] | christianmccrave@gmail.com |
d3d715a9bfc478371559cb79b2ba909fd6628049 | 622a77a2fb79273fe9dec286e137503c63670402 | /SimpleDeformer.cpp | b3be4543d636b1858f394a0b9326e50d8b8588f5 | [] | no_license | tinytangent/TinyMoeFace_Qt | c976235661ec3016a1f523b9cfff6957cfddd551 | 339de99f1b1d4a31acb7c34208a8330a3ca5fb98 | refs/heads/master | 2021-06-13T03:33:26.350950 | 2017-03-05T03:02:21 | 2017-03-05T03:02:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,695 | cpp | #include <QDebug>
#include "SimpleDeformer.h"
SimpleDeformer::SimpleDeformer(CDT& triangleMesh)
:AbstractDeformer(triangleMesh)
{
}
void SimpleDeformer::updateVertices()
{
for(auto i = triangleMesh.vertices_begin(); i != triangleMesh.vertices_end(); i++)
{
Vertex_handle vertexHandle = i;
if(constrainedVertices.contains(vertexHandle))
{
modifiedVertexPos[vertexHandle] = constrainedVertices[vertexHandle];
}
else
{
modifiedVertexPos[i] = originalVertexPos[i];
/*int count = 0;
for(auto j = triangleMesh.incident_vertices(i); j != triangleMesh.vertices_end(); j++)
{
count++;
}
qDebug() << count;*/
for(auto j : constrainedVertices.keys())
{
auto deltaJ = constrainedVertices[j] - originalVertexPos[j];
auto deltaVec = originalVertexPos[j] - originalVertexPos[i];
auto dist2 = deltaVec.x() * deltaVec.x() + deltaVec.y() * deltaVec.y();
modifiedVertexPos[i] += deltaJ * 0.5 * exp(- dist2 / 1000.0);//deltaJ * exp(-dist2 / 1000.0);
}
}
/*int count = 0;
for(auto j = triangleMesh.incident_vertices(i); j != triangleMesh.vertices_end(); j++)
{
count++;
}
qDebug() << count;*/
/*Vertex_handle p = i;
if(cgalOutlinesSet.contains(p))
{
painter.setBrush(QBrush(Qt::red));
}
else
{
painter.setBrush(QBrush(Qt::yellow));
}
painter.drawEllipse(CGALUtil::toQtPointF(p->point()), 2, 2);*/
}
}
| [
"tansinan_1995@163.com"
] | tansinan_1995@163.com |
1c851635e3444e751862272a271e9fc34aef7d59 | 04c45ab4591bd1129f5f6ffd104b36db32deaced | /catkin_ws/devel/include/beginner_tutorials/AddTwoIntsRequest.h | 713d70910df78cf1b6cc6c94b045b66f554cf2ea | [] | no_license | aladdinmck/ROS | 547b35ce27d00db0fb8521af8d11cc02cf4fa1e6 | 1caf2226e274fae8e5f1440366cd39a696e2a5fb | refs/heads/master | 2020-05-23T19:10:14.249098 | 2019-06-02T00:04:23 | 2019-06-02T00:04:23 | 186,905,970 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,420 | h | // Generated by gencpp from file beginner_tutorials/AddTwoIntsRequest.msg
// DO NOT EDIT!
#ifndef BEGINNER_TUTORIALS_MESSAGE_ADDTWOINTSREQUEST_H
#define BEGINNER_TUTORIALS_MESSAGE_ADDTWOINTSREQUEST_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace beginner_tutorials
{
template <class ContainerAllocator>
struct AddTwoIntsRequest_
{
typedef AddTwoIntsRequest_<ContainerAllocator> Type;
AddTwoIntsRequest_()
: a(0)
, b(0) {
}
AddTwoIntsRequest_(const ContainerAllocator& _alloc)
: a(0)
, b(0) {
(void)_alloc;
}
typedef int64_t _a_type;
_a_type a;
typedef int64_t _b_type;
_b_type b;
typedef boost::shared_ptr< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> const> ConstPtr;
}; // struct AddTwoIntsRequest_
typedef ::beginner_tutorials::AddTwoIntsRequest_<std::allocator<void> > AddTwoIntsRequest;
typedef boost::shared_ptr< ::beginner_tutorials::AddTwoIntsRequest > AddTwoIntsRequestPtr;
typedef boost::shared_ptr< ::beginner_tutorials::AddTwoIntsRequest const> AddTwoIntsRequestConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace beginner_tutorials
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'beginner_tutorials': ['/home/aladdinmck/ROS/catkin_ws/src/beginner_tutorials/msg'], 'std_msgs': ['/opt/ros/melodic/share/std_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> >
{
static const char* value()
{
return "36d09b846be0b371c5f190354dd3153e";
}
static const char* value(const ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x36d09b846be0b371ULL;
static const uint64_t static_value2 = 0xc5f190354dd3153eULL;
};
template<class ContainerAllocator>
struct DataType< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> >
{
static const char* value()
{
return "beginner_tutorials/AddTwoIntsRequest";
}
static const char* value(const ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> >
{
static const char* value()
{
return "int64 a\n"
"int64 b\n"
;
}
static const char* value(const ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.a);
stream.next(m.b);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct AddTwoIntsRequest_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator>& v)
{
s << indent << "a: ";
Printer<int64_t>::stream(s, indent + " ", v.a);
s << indent << "b: ";
Printer<int64_t>::stream(s, indent + " ", v.b);
}
};
} // namespace message_operations
} // namespace ros
#endif // BEGINNER_TUTORIALS_MESSAGE_ADDTWOINTSREQUEST_H
| [
"haa55387@uga.edu"
] | haa55387@uga.edu |
a301cd389c3dc1c17a5b34056eed86a2fbf8cd95 | d739bf4fdc0281286d0deb7c18738784bd43d4e2 | /day10/6.28homework/person.h | 11cdac9a9412feadf39a2cda9f6799342f5bb32c | [] | no_license | hewei-bit/cpp_learning | 4b50e0cb520ddb00c55eab58c7d5b9076579bdcf | 098ef4fbc7d487f94c802fc8703e85aedf75d1c5 | refs/heads/master | 2022-11-17T17:27:41.873882 | 2020-06-28T03:24:12 | 2020-06-28T03:24:12 | 271,423,628 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 291 | h | #ifndef PERSON_H
#define PERSON_H
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
Person(){}
Person(string name,int age)
{
this->m_Name = name;
this->m_Age = age;
}
string m_Name;
int m_Age;
};
#endif // PERSON_H
| [
"1003826976@qq.com"
] | 1003826976@qq.com |
c0fcb440f925083ae5e85fecc2f2a05b9453ca8e | 5b617ac80e9f18b8243a867baaae82deae9b7e23 | /movement.hpp | d26b6b8009dccf260ec9077a5a5204c5aba3d1c2 | [] | no_license | adil-olin/Falcon-6T---Kinght | e7a7592d068f05877d1987320859f9d750faaa86 | b3bde9094f3d966a9c7e89c23a5e95f8ab452fc4 | refs/heads/main | 2023-05-31T11:11:05.866257 | 2021-06-26T15:16:14 | 2021-06-26T15:16:14 | 380,530,688 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,590 | hpp | #pragma once
#ifndef movement_hpp
#define movement_hpp
#include <SDL2/SDL.h>
#include<SDL2/SDL_image.h>
#include<SDL2/SDL_mixer.h>
#include<bits/stdc++.h>
using namespace std;
static void spawnenemy(void)
{
if(--enemyspawntimer<=0)
{
Entity temp_enemy;
memset(&temp_enemy,0,sizeof(Entity));
temp_enemy.side=SIDE_ALIEN;
temp_enemy.health=1+5*level;
temp_enemy.w=80;
temp_enemy.h=77;
temp_enemy.y=0;
temp_enemy.x= rand() % SCREEN_WIDTH;
temp_enemy.texture = enemyTexture;
//SDL_QueryTexture(temp_enemy.texture, NULL, NULL, &temp_enemy.x, temp_enemy.y);
temp_enemy.dy = (2 + (rand() % 4));
temp_enemy.dx = 0;
enemyspawntimer = 100-level + (rand() % 60);
temp_enemy.reload = FPS-level;
stage.Fighter.push_back(temp_enemy);
}
}
//stage.Fighter[0] is same as player id. So, we have to update them both to keep them same
static void fireBullet(void)
{
Entity temp_bullet;
memset(&temp_bullet,0,sizeof(Entity));
temp_bullet.side=SIDE_PLAYER;
temp_bullet.x = player.x;
temp_bullet.y = player.y;
temp_bullet.w=30;
temp_bullet.h=53;
temp_bullet.x += (player.w / 2) - (temp_bullet.w / 2);
temp_bullet.y -= temp_bullet.h;
temp_bullet.health=10+level*10;
temp_bullet.dx=0;
temp_bullet.dy= - PLAYER_BULLET_SPEED;
temp_bullet.texture = bulletTexture;
stage.Bullet.push_back(temp_bullet);
player.reload=8;
stage.Fighter[0].reload=8;
}
void movePlayer()
{
if(!isplayernull)
{
player.dx = player.dy = 0;
stage.Fighter[0].dx = stage.Fighter[0].dy=0;
if (player.reload > 0)
{
player.reload--;
stage.Fighter[0].reload--;
}
if (app.keyboard[SDL_SCANCODE_UP])
{
player.dy = -PLAYER_SPEED;
stage.Fighter[0].dy = -PLAYER_SPEED;
}
if (app.keyboard[SDL_SCANCODE_DOWN])
{
player.dy = PLAYER_SPEED;
stage.Fighter[0].dy = PLAYER_SPEED;
}
if (app.keyboard[SDL_SCANCODE_LEFT])
{
player.dx = -PLAYER_SPEED;
stage.Fighter[0].dx = -PLAYER_SPEED;
}
if (app.keyboard[SDL_SCANCODE_RIGHT])
{
player.dx = PLAYER_SPEED;
stage.Fighter[0].dx = PLAYER_SPEED;
}
if((app.keyboard[SDL_SCANCODE_LSHIFT] || app.keyboard[SDL_SCANCODE_RSHIFT]))
{
player.dx*=1.5;
player.dy*=1.5;
stage.Fighter[0].dy*=1.5;
stage.Fighter[0].dx*=1.5;
}
if (player.reload == 0)
{
if(!(app.keyboard[SDL_SCANCODE_LSHIFT] || app.keyboard[SDL_SCANCODE_RSHIFT]))
{
fireBullet();
}
}
player.x += player.dx;
player.y += player.dy;
stage.Fighter[0].x+=stage.Fighter[0].dx;
stage.Fighter[0].y+=stage.Fighter[0].dy;
//checking so that player don't go outside of the screen
if(player.x<0)
{
player.x=0;
stage.Fighter[0].x=0;
}
if(player.x>SCREEN_WIDTH-player.w)
{
player.x=SCREEN_WIDTH-player.w;
stage.Fighter[0].x = SCREEN_WIDTH-player.w;
}
if(player.y<0)
{
player.y=0;
stage.Fighter[0].y=0;
}
if(player.y>SCREEN_HEIGHT-player.w)
{
player.y = SCREEN_HEIGHT-player.w;
stage.Fighter[0].y = SCREEN_HEIGHT-player.w;
}
}
}
#endif
| [
"olinafseradil@gmail.com"
] | olinafseradil@gmail.com |
873c6d031afe140768f5cdcee2a4c6b9b1319f60 | 89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04 | /chrome/browser/android/thumbnail/scoped_ptr_expiring_cache.h | 00a680178da2c4240377a56fde619376d4ba1221 | [
"BSD-3-Clause"
] | permissive | bino7/chromium | 8d26f84a1b6e38a73d1b97fea6057c634eff68cb | 4666a6bb6fdcb1114afecf77bdaa239d9787b752 | refs/heads/master | 2022-12-22T14:31:53.913081 | 2016-09-06T10:05:11 | 2016-09-06T10:05:11 | 67,410,510 | 1 | 3 | BSD-3-Clause | 2022-12-17T03:08:52 | 2016-09-05T10:11:59 | null | UTF-8 | C++ | false | false | 1,942 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_ANDROID_THUMBNAIL_SCOPED_PTR_EXPIRING_CACHE_H_
#define CHROME_BROWSER_ANDROID_THUMBNAIL_SCOPED_PTR_EXPIRING_CACHE_H_
#include <stddef.h>
#include <memory>
#include "base/macros.h"
#include "net/base/linked_hash_map.h"
template <class Key, class Value>
class ScopedPtrExpiringCache {
private:
typedef linked_hash_map<Key, Value*> LinkedHashMap;
public:
typedef typename LinkedHashMap::iterator iterator;
explicit ScopedPtrExpiringCache(size_t max_cache_size)
: max_cache_size_(max_cache_size) {}
~ScopedPtrExpiringCache() {}
void Put(const Key& key, std::unique_ptr<Value> value) {
Remove(key);
map_[key] = value.release();
EvictIfFull();
}
Value* Get(const Key& key) {
iterator iter = map_.find(key);
if (iter != map_.end())
return iter->second;
return NULL;
}
std::unique_ptr<Value> Remove(const Key& key) {
iterator iter = map_.find(key);
std::unique_ptr<Value> value;
if (iter != map_.end()) {
value.reset(iter->second);
map_.erase(key);
}
return std::move(value);
}
void Clear() {
for (iterator iter = map_.begin(); iter != map_.end(); iter++) {
delete iter->second;
}
map_.clear();
}
iterator begin() { return map_.begin(); }
iterator end() { return map_.end(); }
size_t MaximumCacheSize() const { return max_cache_size_; }
size_t size() const { return map_.size(); }
private:
void EvictIfFull() {
while (map_.size() > max_cache_size_) {
iterator it = map_.begin();
delete it->second;
map_.erase(it);
}
}
size_t max_cache_size_;
LinkedHashMap map_;
DISALLOW_COPY_AND_ASSIGN(ScopedPtrExpiringCache);
};
#endif // CHROME_BROWSER_ANDROID_THUMBNAIL_SCOPED_PTR_EXPIRING_CACHE_H_
| [
"bino.zh@gmail.com"
] | bino.zh@gmail.com |
12ebee85824bb93d8a22f2ab9276e183c87c4ec4 | d1c8b118241bfda690e99fbbc64de579f7cfed7d | /jbw/agents/reward_upper_bound.cpp | 0e44b98d70b5fda8345d8e223e7c56388a726c03 | [
"Apache-2.0"
] | permissive | framinmansour/jelly-bean-world | a3825e9729dcc3724385afb029d2fac9c43b4805 | 8afb48daf22a44c4ff19f7d0f6ed7a2c190df6b4 | refs/heads/master | 2022-08-22T01:06:05.612046 | 2020-05-24T00:27:15 | 2020-05-24T00:27:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,663 | cpp | #include <jbw/simulator.h>
#include <set>
#include <thread>
using namespace core;
using namespace jbw;
inline unsigned int get_distance(const unsigned int* distances,
unsigned int start_vertex, direction start_direction,
unsigned int end_vertex, direction end_direction,
unsigned int vertex_count)
{
return distances[((start_vertex * (uint_fast8_t) direction::COUNT + (uint_fast8_t) start_direction)
* vertex_count + end_vertex) * (uint_fast8_t) direction::COUNT + (uint_fast8_t) end_direction];
}
inline unsigned int* get_row(unsigned int* distances,
unsigned int start_vertex, direction start_direction,
unsigned int vertex_count)
{
return &distances[((start_vertex * (uint_fast8_t) direction::COUNT + (uint_fast8_t) start_direction) * vertex_count) * (uint_fast8_t) direction::COUNT];
}
struct fixed_length_shortest_path_state
{
unsigned int vertex_id;
direction dir;
unsigned int distance;
unsigned int length;
struct less_than {
inline bool operator () (const fixed_length_shortest_path_state left, const fixed_length_shortest_path_state right) {
return left.distance < right.distance;
}
};
};
unsigned int fixed_length_shortest_path(
unsigned int start_vertex, direction start_direction,
unsigned int end_vertex, direction end_direction,
const unsigned int* distances, unsigned int vertex_count,
const unsigned int k, const unsigned int* disallowed_vertices,
const unsigned int disallowed_vertex_count)
{
unsigned int state_count = vertex_count * (k + 1) * (uint_fast8_t) direction::COUNT;
unsigned int* smallest_costs = (unsigned int*) malloc(sizeof(unsigned int) * state_count);
for (unsigned int i = 0; i < state_count; i++)
smallest_costs[i] = UINT_MAX;
std::multiset<fixed_length_shortest_path_state, fixed_length_shortest_path_state::less_than> queue;
fixed_length_shortest_path_state initial_state;
initial_state.vertex_id = start_vertex;
initial_state.dir = start_direction;
initial_state.distance = 1; /* we want to include the cost of moving into this region from the previous region */
initial_state.length = 0;
smallest_costs[(initial_state.vertex_id * (k + 1) + initial_state.length) * (uint_fast8_t) direction::COUNT + (uint_fast8_t) initial_state.dir] = initial_state.distance;
queue.insert(initial_state);
unsigned int shortest_distance = UINT_MAX;
while (!queue.empty()) {
auto first = queue.cbegin();
fixed_length_shortest_path_state state = *first;
queue.erase(first);
if (state.vertex_id == end_vertex) {
if (state.length != k)
fprintf(stderr, "fixed_length_shortest_path WARNING: Completed path does not have length `k`.\n");
if (state.dir != end_direction)
fprintf(stderr, "fixed_length_shortest_path WARNING: Completed path does not have direction `end_direction` in the last state.\n");
shortest_distance = state.distance;
break;
}
if (state.length == k - 1) {
/* we need the next vertex to be the `end_vertex` */
unsigned int new_distance = state.distance + get_distance(distances, state.vertex_id, state.dir, end_vertex, end_direction, vertex_count);
if (new_distance < smallest_costs[(end_vertex * (k + 1) + k) * (uint_fast8_t) direction::COUNT + (uint_fast8_t) end_direction]) {
smallest_costs[(end_vertex * (k + 1) + k) * (uint_fast8_t) direction::COUNT + (uint_fast8_t) end_direction] = new_distance;
fixed_length_shortest_path_state new_state;
new_state.vertex_id = end_vertex;
new_state.dir = end_direction;
new_state.length = state.length + 1;
new_state.distance = new_distance;
queue.insert(new_state);
}
} else if (state.length >= k) {
fprintf(stderr, "fixed_length_shortest_path WARNING: This path has length at least `k`.\n");
} else {
for (unsigned int i = 0; i < vertex_count; i++) {
if (i == start_vertex || i == end_vertex || i == state.vertex_id) continue;
if (index_of(i, disallowed_vertices, disallowed_vertex_count) < disallowed_vertex_count) continue;
for (uint_fast8_t d = 0; d < (uint_fast8_t) direction::COUNT; d++) {
direction dir = (direction) d;
unsigned int new_distance = state.distance + get_distance(distances, state.vertex_id, state.dir, i, dir, vertex_count);
if (new_distance < smallest_costs[(i * (k + 1) + state.length + 1) * (uint_fast8_t) direction::COUNT + d]) {
smallest_costs[(i * (k + 1) + state.length + 1) * (uint_fast8_t) direction::COUNT + d] = new_distance;
fixed_length_shortest_path_state new_state;
new_state.vertex_id = i;
new_state.dir = dir;
new_state.length = state.length + 1;
new_state.distance = new_distance;
queue.insert(new_state);
}
}
}
}
}
free(smallest_costs);
return shortest_distance;
}
struct optimal_path_state
{
unsigned int vertex_id;
direction dir;
unsigned int distance;
float priority;
optimal_path_state* prev;
unsigned int reference_count;
static inline void free(optimal_path_state& state) {
state.reference_count--;
if (state.reference_count == 0 && state.prev != nullptr) {
core::free(*state.prev);
if (state.prev->reference_count == 0)
core::free(state.prev);
}
}
struct less_than {
inline bool operator () (const optimal_path_state* left, const optimal_path_state* right) {
return left->priority < right->priority;
}
};
};
inline float upper_bound(
const unsigned int* distances,
const unsigned int vertex_count,
const unsigned int end_vertex_id,
const direction end_direction,
const optimal_path_state& new_state,
const unsigned int* remaining_vertices,
const unsigned int remaining_vertex_count,
unsigned int* visited_vertices,
unsigned int visited_vertex_count)
{
float best_reward_rate = (float) (visited_vertex_count + 1 - 2) / new_state.distance;
if (new_state.vertex_id == end_vertex_id) return best_reward_rate;
for (unsigned int k = 1; k < remaining_vertex_count; k++) {
unsigned int distance = fixed_length_shortest_path(new_state.vertex_id, new_state.dir,
end_vertex_id, end_direction, distances, vertex_count, k + 1, visited_vertices, visited_vertex_count);
float reward_rate = (float) (visited_vertex_count + k + 1 - 2) / (new_state.distance + distance);
if (reward_rate > best_reward_rate)
best_reward_rate = reward_rate;
}
return best_reward_rate;
}
optimal_path_state* find_optimal_path(
const unsigned int* distances, unsigned int vertex_count,
unsigned int start_vertex_id, direction start_direction,
unsigned int end_vertex_id, direction end_direction)
{
std::multiset<optimal_path_state*, optimal_path_state::less_than> queue;
optimal_path_state* initial_state = (optimal_path_state*) malloc(sizeof(optimal_path_state));
initial_state->vertex_id = start_vertex_id;
initial_state->dir = start_direction;
initial_state->distance = 1; /* we want to include the cost of moving into this region from the previous region */
unsigned int distance_to_target = get_distance(distances, start_vertex_id, start_direction, end_vertex_id, end_direction, vertex_count);
initial_state->priority = (float) (vertex_count - 2) / (initial_state->distance + distance_to_target);
initial_state->prev = nullptr;
initial_state->reference_count = 1;
queue.insert(initial_state);
unsigned int visited_vertex_count = 0, remaining_vertex_count = 0;
unsigned int* visited_vertices = (unsigned int*) malloc(sizeof(unsigned int) * vertex_count);
unsigned int* remaining_vertices = (unsigned int*) malloc(sizeof(unsigned int) * vertex_count);
unsigned int* vertex_ids = (unsigned int*) malloc(sizeof(unsigned int) * vertex_count);
for (unsigned int i = 0; i < vertex_count; i++)
vertex_ids[i] = i;
float best_score = -1.0f;
optimal_path_state* best_path = nullptr;
float last_priority = std::numeric_limits<float>::max();
while (!queue.empty()) {
auto last = queue.cend(); last--;
optimal_path_state* state = *last;
if (state->priority <= best_score) {
/* the search priority is at most the best score, so we have found the optimum */
break;
}
queue.erase(last);
if (state->priority > last_priority)
fprintf(stderr, "parse WARNING: Search is not monotonic.\n");
visited_vertex_count = 0;
remaining_vertex_count = 0;
optimal_path_state* curr = state;
while (curr != nullptr) {
visited_vertices[visited_vertex_count++] = curr->vertex_id;
curr = curr->prev;
}
insertion_sort(visited_vertices, visited_vertex_count);
set_subtract(remaining_vertices, remaining_vertex_count,
vertex_ids, vertex_count, visited_vertices, visited_vertex_count);
/* check if we reached the `end_vertex_id` */
if (state->vertex_id == end_vertex_id && state->dir == end_direction) {
/* we reached `end_vertex_id`, so we can stop the search */
float score = (double) (visited_vertex_count - 2) / state->distance;
if (score > best_score) {
if (best_path != nullptr) {
free(*best_path);
if (best_path->reference_count == 0)
free(best_path);
}
best_path = state;
best_path->reference_count++;
best_score = score;
}
} else {
for (unsigned int i = 0; i < remaining_vertex_count; i++) {
unsigned int next_vertex = remaining_vertices[i];
for (uint_fast8_t d = (uint_fast8_t) direction::UP; d < (uint_fast8_t) direction::COUNT; d++) {
direction dir = (direction) d;
if (next_vertex == end_vertex_id && dir != end_direction) continue;
unsigned int next_distance = get_distance(distances, state->vertex_id, state->dir, next_vertex, dir, vertex_count);
if (next_distance == UINT_MAX) continue;
optimal_path_state* new_state = (optimal_path_state*) malloc(sizeof(optimal_path_state));
new_state->vertex_id = next_vertex;
new_state->dir = dir;
new_state->distance = state->distance + next_distance;
//unsigned int distance_to_target = get_distance(distances, next_vertex, dir, end_vertex_id, end_direction, vertex_count);
//new_state->priority = (float) (visited_vertex_count + remaining_vertex_count - 2) / (new_state->distance + distance_to_target);
new_state->priority = upper_bound(distances, vertex_count, end_vertex_id, end_direction,
*new_state, remaining_vertices, remaining_vertex_count, visited_vertices, visited_vertex_count);
new_state->prev = state;
new_state->reference_count = 1;
++state->reference_count;
queue.insert(new_state);
}
}
}
/* remove states from the queue with strictly worse bound than the best score we have so far */
/*while (!queue.empty()) {
auto first = queue.cbegin();
optimal_path_state* state = *first;
if (state->priority >= best_score)
break;
queue.erase(first);
free(*state);
if (state->reference_count == 0)
free(state);
}*/
free(*state);
if (state->reference_count == 0)
free(state);
}
for (auto state : queue) {
free(*state);
if (state->reference_count == 0)
free(state);
}
free(visited_vertices);
free(remaining_vertices);
free(vertex_ids);
return best_path;
}
struct shortest_path_state
{
unsigned int cost;
unsigned int x, y;
direction dir;
struct less_than {
inline bool operator () (const shortest_path_state left, const shortest_path_state right) {
return left.cost < right.cost;
}
};
};
inline void move_forward(
unsigned int x, unsigned int y, direction dir,
unsigned int max_x, unsigned int max_y,
unsigned int& new_x, unsigned int& new_y)
{
new_x = x;
new_y = y;
if (dir == direction::UP) {
++new_y;
if (new_y > max_y) new_y = UINT_MAX;
} else if (dir == direction::DOWN) {
if (new_y == 0) new_y = UINT_MAX;
else --new_y;
} else if (dir == direction::LEFT) {
if (new_x == 0) new_x = UINT_MAX;
else --new_x;
} else if (dir == direction::RIGHT) {
++new_x;
if (new_x > max_x) new_x = UINT_MAX;
}
}
inline direction turn_left(direction dir) {
if (dir == direction::UP) return direction::LEFT;
else if (dir == direction::DOWN) return direction::RIGHT;
else if (dir == direction::LEFT) return direction::DOWN;
else if (dir == direction::RIGHT) return direction::UP;
fprintf(stderr, "turn_left: Unrecognized direction.\n");
exit(EXIT_FAILURE);
}
inline direction turn_right(direction dir) {
if (dir == direction::UP) return direction::RIGHT;
else if (dir == direction::DOWN) return direction::LEFT;
else if (dir == direction::LEFT) return direction::UP;
else if (dir == direction::RIGHT) return direction::DOWN;
fprintf(stderr, "turn_right: Unrecognized direction.\n");
exit(EXIT_FAILURE);
}
void compute_shortest_distances(
unsigned int start_x, unsigned int start_y,
direction start_direction,
unsigned int max_x, unsigned int max_y,
const array<position>& goals,
const array<position>& walls,
unsigned int* shortest_distances)
{
unsigned int state_count = (max_y + 1) * (max_x + 1) * (uint_fast8_t) direction::COUNT;
unsigned int* smallest_costs = (unsigned int*) malloc(sizeof(unsigned int) * state_count);
for (unsigned int i = 0; i < state_count; i++)
smallest_costs[i] = UINT_MAX;
for (unsigned int i = 0; i < (goals.length + 1) * (uint_fast8_t) direction::COUNT; i++)
shortest_distances[i] = UINT_MAX;
std::multiset<shortest_path_state, shortest_path_state::less_than> queue;
shortest_path_state initial_state;
initial_state.cost = 0;
initial_state.x = start_x;
initial_state.y = start_y;
initial_state.dir = start_direction;
smallest_costs[(start_x * (max_y + 1) + start_y) * (uint_fast8_t) direction::COUNT + (uint_fast8_t) start_direction] = 0;
queue.insert(initial_state);
while (!queue.empty()) {
auto first = queue.cbegin();
shortest_path_state state = *first;
queue.erase(first);
/* check if we found a jellybean */
unsigned int goal_index = goals.index_of({state.x, state.y});
if (goal_index < goals.length) {
/* we found a jellybean */
shortest_distances[goal_index * (uint_fast8_t) direction::COUNT + (uint_fast8_t) state.dir] = state.cost;
} if (state.y == max_y) {
/* we reached the top row */
shortest_distances[goals.length * (uint_fast8_t) direction::COUNT + (uint_fast8_t) state.dir] =
min(shortest_distances[goals.length * (uint_fast8_t) direction::COUNT + (uint_fast8_t) state.dir], state.cost);
}
/* consider moving forward */
unsigned int new_x, new_y;
direction new_dir = state.dir;
move_forward(state.x, state.y, state.dir, max_x, max_y, new_x, new_y);
if (new_x != UINT_MAX && new_y != UINT_MAX) {
/* check if there is a wall in the new position */
if (!walls.contains({new_x, new_y})) {
/* there is no wall, so continue considering this movement */
unsigned int new_cost = state.cost + 1;
if (new_cost < smallest_costs[(new_x * (max_y + 1) + new_y) * (uint_fast8_t) direction::COUNT + (uint_fast8_t) new_dir]) {
smallest_costs[(new_x * (max_y + 1) + new_y) * (uint_fast8_t) direction::COUNT + (uint_fast8_t) new_dir] = new_cost;
shortest_path_state new_state;
new_state.cost = new_cost;
new_state.x = new_x;
new_state.y = new_y;
new_state.dir = new_dir;
queue.insert(new_state);
}
}
}
/* consider turning left */
unsigned int new_cost = state.cost + 1;
new_x = state.x;
new_y = state.y;
new_dir = turn_left(state.dir);
if (new_cost < smallest_costs[(new_x * (max_y + 1) + new_y) * (uint_fast8_t) direction::COUNT + (uint_fast8_t) new_dir]) {
smallest_costs[(new_x * (max_y + 1) + new_y) * (uint_fast8_t) direction::COUNT + (uint_fast8_t) new_dir] = new_cost;
shortest_path_state new_state;
new_state.cost = new_cost;
new_state.x = new_x;
new_state.y = new_y;
new_state.dir = new_dir;
queue.insert(new_state);
}
/* consider turning right */
new_cost = state.cost + 1;
new_x = state.x;
new_y = state.y;
new_dir = turn_right(state.dir);
if (new_cost < smallest_costs[(new_x * (max_y + 1) + new_y) * (uint_fast8_t) direction::COUNT + (uint_fast8_t) new_dir]) {
smallest_costs[(new_x * (max_y + 1) + new_y) * (uint_fast8_t) direction::COUNT + (uint_fast8_t) new_dir] = new_cost;
shortest_path_state new_state;
new_state.cost = new_cost;
new_state.x = new_x;
new_state.y = new_y;
new_state.dir = new_dir;
queue.insert(new_state);
}
}
free(smallest_costs);
}
struct empty_data {
static inline void move(const empty_data& src, empty_data& dst) { }
static inline void free(empty_data& data) { }
};
constexpr bool init(empty_data& data) { return true; }
template<typename PerPatchData, typename ItemType>
void generate_map(
map<PerPatchData, ItemType>& world,
const position& bottom_left_corner,
const position& top_right_corner)
{
/* make sure enough of the world is generated */
patch<PerPatchData>* neighborhood[4]; position patch_positions[4];
for (int64_t x = bottom_left_corner.x; x <= top_right_corner.x; x += world.n) {
for (int64_t y = bottom_left_corner.y; y <= top_right_corner.y; y += world.n)
world.get_fixed_neighborhood(position(x, y), neighborhood, patch_positions);
world.get_fixed_neighborhood(position(x, top_right_corner.y), neighborhood, patch_positions);
}
for (int64_t y = bottom_left_corner.y; y <= top_right_corner.y; y += world.n)
world.get_fixed_neighborhood(position(top_right_corner.x, y), neighborhood, patch_positions);
world.get_fixed_neighborhood(top_right_corner, neighborhood, patch_positions);
}
inline void set_interaction_args(
item_properties* item_types, unsigned int first_item_type,
unsigned int second_item_type, interaction_function interaction,
std::initializer_list<float> args)
{
item_types[first_item_type].interaction_fns[second_item_type].fn = interaction;
item_types[first_item_type].interaction_fns[second_item_type].arg_count = (unsigned int) args.size();
item_types[first_item_type].interaction_fns[second_item_type].args = (float*) malloc(max((size_t) 1, sizeof(float) * args.size()));
unsigned int counter = 0;
for (auto i = args.begin(); i != args.end(); i++)
item_types[first_item_type].interaction_fns[second_item_type].args[counter++] = *i;
}
inline void compute_optimal_reward_rate(
const unsigned int worker_id,
const unsigned int n,
const unsigned int mcmc_iterations,
const item_properties* item_types,
const unsigned int item_type_count,
const unsigned int jellybean_index,
position bottom_left_corner,
position top_right_corner,
position agent_start_position,
std::mutex& lock, std::minstd_rand& rng,
array<float>& reward_rates)
{
lock.lock();
unsigned int seed = rng();
lock.unlock();
auto m = map<empty_data, item_properties>(n, mcmc_iterations, item_types, item_type_count, seed);
generate_map(m, bottom_left_corner, top_right_corner);
position bottom_left_patch_position, top_right_patch_position;
m.world_to_patch_coordinates(bottom_left_corner, bottom_left_patch_position);
m.world_to_patch_coordinates(top_right_corner, top_right_patch_position);
array<position> goals(64), walls(64);
apply_contiguous(m.patches, bottom_left_patch_position.y,
top_right_patch_position.y - bottom_left_patch_position.y + 1,
[&](const array_map<int64_t, patch<empty_data>>& row, int64_t y)
{
return apply_contiguous(row, bottom_left_patch_position.x,
top_right_patch_position.x - bottom_left_patch_position.x + 1,
[&](const patch<empty_data>& patch, int64_t x)
{
for (const item& i : patch.items) {
if (i.location.x >= bottom_left_corner.x && i.location.x <= top_right_corner.x
&& i.location.y >= bottom_left_corner.y && i.location.y <= top_right_corner.y)
{
if (item_types[i.item_type].blocks_movement) walls.add(i.location);
else if (i.item_type == jellybean_index) goals.add(i.location);
}
}
return true;
});
});
/* the first vertex is the agent starting position, and the last vertex is the upper row of the map region */
unsigned int* distances = (unsigned int*) malloc(sizeof(unsigned int) * (goals.length + 2) * (goals.length + 2) * (uint_fast8_t) direction::COUNT * (uint_fast8_t) direction::COUNT);
for (uint_fast8_t d = 0; d < (uint_fast8_t) direction::COUNT; d++) {
unsigned int* row = get_row(distances, 0, (direction) d, goals.length + 2);
for (uint_fast8_t e = 0; e < (uint_fast8_t) direction::COUNT; e++) {
if (e == d) {
row[e] = 0;
} else if ((direction) e == turn_left((direction) d) || (direction) e == turn_right((direction) d)) {
row[e] = 1;
} else {
row[e] = 2;
}
}
if ((direction) d != direction::UP) {
for (unsigned int i = 0; i < (goals.length + 1) * (uint_fast8_t) direction::COUNT; i++)
row[(uint_fast8_t) direction::COUNT + i] = UINT_MAX;
}
}
for (uint_fast8_t d = 0; d < (uint_fast8_t) direction::COUNT; d++) {
unsigned int* row = get_row(distances, goals.length + 1, (direction) d, goals.length + 2);
for (uint_fast8_t e = 0; e < (uint_fast8_t) direction::COUNT; e++) {
if (e == d) {
row[(goals.length + 1) * (uint_fast8_t) direction::COUNT + e] = 0;
} else if ((direction) e == turn_left((direction) d) || (direction) e == turn_right((direction) d)) {
row[(goals.length + 1) * (uint_fast8_t) direction::COUNT + e] = 1;
} else {
row[(goals.length + 1) * (uint_fast8_t) direction::COUNT + e] = 2;
}
}
if ((direction) d != direction::UP) {
for (unsigned int i = 0; i < (goals.length + 1) * (uint_fast8_t) direction::COUNT; i++)
row[i] = UINT_MAX;
}
}
compute_shortest_distances(agent_start_position.x, agent_start_position.y,
direction::UP, top_right_corner.x, top_right_corner.y, goals, walls,
distances + (uint_fast8_t) direction::COUNT);
for (unsigned int i = 0; i < goals.length; i++) {
for (uint_fast8_t d = 0; d < (uint_fast8_t) direction::COUNT; d++) {
unsigned int* row = get_row(distances, i + 1, (direction) d, goals.length + 2);
for (uint_fast8_t e = 0; e < (uint_fast8_t) direction::COUNT; e++)
row[e] = UINT_MAX; /* don't allow movement back to the agent "vertex" */
compute_shortest_distances(goals[i].x, goals[i].y,
(direction) d, top_right_corner.x, top_right_corner.y,
goals, walls, row + (uint_fast8_t) direction::COUNT);
}
}
fprintf(stderr, "[thread %u] Finding optimal path with jellybean count: %zu\n", worker_id, goals.length);
optimal_path_state* path = find_optimal_path(distances, goals.length + 2, 0, direction::UP, goals.length + 1, direction::UP);
unsigned int path_length = 0; /* in vertices, including endpoints */
optimal_path_state* curr = path;
while (curr != nullptr) {
path_length++;
curr = curr->prev;
}
lock.lock();
reward_rates.add((float) (path_length - 2) / path->distance);
float mean = 0.0f;
for (float x : reward_rates)
mean += x;
mean /= reward_rates.length;
float variance = 0.0f;
for (float x : reward_rates)
variance += (x - mean) * (x - mean);
variance /= (reward_rates.length + 1);
fprintf(stderr, "[n: %lu] Avg reward rate: %f, stddev: %f, stddev of avg: %f\n", reward_rates.length, mean, sqrt(variance), sqrt(variance / reward_rates.length));
lock.unlock();
}
int main(int argc, const char** argv)
{
static constexpr int n = 32;
static constexpr unsigned int item_type_count = 4;
static constexpr unsigned int mcmc_iterations = 4000;
static constexpr unsigned int scent_dimension = 3;
static constexpr unsigned int color_dimension = 3;
item_properties* item_types = (item_properties*) alloca(sizeof(item_properties) * item_type_count);
item_types[0].name = "banana";
item_types[0].scent = (float*) calloc(scent_dimension, sizeof(float));
item_types[0].color = (float*) calloc(color_dimension, sizeof(float));
item_types[0].required_item_counts = (unsigned int*) calloc(item_type_count, sizeof(unsigned int));
item_types[0].required_item_costs = (unsigned int*) calloc(item_type_count, sizeof(unsigned int));
item_types[0].scent[1] = 1.0f;
item_types[0].color[1] = 1.0f;
item_types[0].required_item_counts[0] = 1;
item_types[0].blocks_movement = false;
item_types[0].visual_occlusion = 0.0;
item_types[1].name = "onion";
item_types[1].scent = (float*) calloc(scent_dimension, sizeof(float));
item_types[1].color = (float*) calloc(color_dimension, sizeof(float));
item_types[1].required_item_counts = (unsigned int*) calloc(item_type_count, sizeof(unsigned int));
item_types[1].required_item_costs = (unsigned int*) calloc(item_type_count, sizeof(unsigned int));
item_types[1].scent[0] = 1.0f;
item_types[1].color[0] = 1.0f;
item_types[1].required_item_counts[1] = 1;
item_types[1].blocks_movement = false;
item_types[1].visual_occlusion = 0.0;
item_types[2].name = "jellybean";
item_types[2].scent = (float*) calloc(scent_dimension, sizeof(float));
item_types[2].color = (float*) calloc(color_dimension, sizeof(float));
item_types[2].required_item_counts = (unsigned int*) calloc(item_type_count, sizeof(unsigned int));
item_types[2].required_item_costs = (unsigned int*) calloc(item_type_count, sizeof(unsigned int));
item_types[2].scent[2] = 1.0f;
item_types[2].color[2] = 1.0f;
item_types[2].blocks_movement = false;
item_types[2].visual_occlusion = 0.0;
item_types[3].name = "wall";
item_types[3].scent = (float*) calloc(scent_dimension, sizeof(float));
item_types[3].color = (float*) calloc(color_dimension, sizeof(float));
item_types[3].required_item_counts = (unsigned int*) calloc(item_type_count, sizeof(unsigned int));
item_types[3].required_item_costs = (unsigned int*) calloc(item_type_count, sizeof(unsigned int));
item_types[3].color[0] = 0.52f;
item_types[3].color[1] = 0.22f;
item_types[3].color[2] = 0.16f;
item_types[3].required_item_counts[3] = 1;
item_types[3].blocks_movement = true;
item_types[3].visual_occlusion = 1.0f;
item_types[0].intensity_fn.fn = constant_intensity_fn;
item_types[0].intensity_fn.arg_count = 1;
item_types[0].intensity_fn.args = (float*) malloc(sizeof(float) * 1);
item_types[0].intensity_fn.args[0] = -5.3f;
item_types[0].interaction_fns = (energy_function<interaction_function>*)
malloc(sizeof(energy_function<interaction_function>) * item_type_count);
item_types[1].intensity_fn.fn = constant_intensity_fn;
item_types[1].intensity_fn.arg_count = 1;
item_types[1].intensity_fn.args = (float*) malloc(sizeof(float) * 1);
item_types[1].intensity_fn.args[0] = -5.0f;
item_types[1].interaction_fns = (energy_function<interaction_function>*)
malloc(sizeof(energy_function<interaction_function>) * item_type_count);
item_types[2].intensity_fn.fn = constant_intensity_fn;
item_types[2].intensity_fn.arg_count = 1;
item_types[2].intensity_fn.args = (float*) malloc(sizeof(float) * 1);
item_types[2].intensity_fn.args[0] = -5.3f;
item_types[2].interaction_fns = (energy_function<interaction_function>*)
malloc(sizeof(energy_function<interaction_function>) * item_type_count);
item_types[3].intensity_fn.fn = constant_intensity_fn;
item_types[3].intensity_fn.arg_count = 1;
item_types[3].intensity_fn.args = (float*) malloc(sizeof(float) * 1);
item_types[3].intensity_fn.args[0] = 0.0f;
item_types[3].interaction_fns = (energy_function<interaction_function>*)
malloc(sizeof(energy_function<interaction_function>) * item_type_count);
set_interaction_args(item_types, 0, 0, piecewise_box_interaction_fn, {10.0f, 200.0f, 0.0f, -6.0f});
set_interaction_args(item_types, 0, 1, piecewise_box_interaction_fn, {200.0f, 0.0f, -6.0f, -6.0f});
set_interaction_args(item_types, 0, 2, piecewise_box_interaction_fn, {10.0f, 200.0f, 2.0f, -100.0f});
set_interaction_args(item_types, 0, 3, zero_interaction_fn, {});
set_interaction_args(item_types, 1, 0, piecewise_box_interaction_fn, {200.0f, 0.0f, -6.0f, -6.0f});
set_interaction_args(item_types, 1, 1, zero_interaction_fn, {});
set_interaction_args(item_types, 1, 2, piecewise_box_interaction_fn, {200.0f, 0.0f, -100.0f, -100.0f});
set_interaction_args(item_types, 1, 3, zero_interaction_fn, {});
set_interaction_args(item_types, 2, 0, piecewise_box_interaction_fn, {10.0f, 200.0f, 2.0f, -100.0f});
set_interaction_args(item_types, 2, 1, piecewise_box_interaction_fn, {200.0f, 0.0f, -100.0f, -100.0f});
set_interaction_args(item_types, 2, 2, piecewise_box_interaction_fn, {10.0f, 200.0f, 0.0f, -6.0f});
set_interaction_args(item_types, 2, 3, zero_interaction_fn, {});
set_interaction_args(item_types, 3, 0, zero_interaction_fn, {});
set_interaction_args(item_types, 3, 1, zero_interaction_fn, {});
set_interaction_args(item_types, 3, 2, zero_interaction_fn, {});
set_interaction_args(item_types, 3, 3, cross_interaction_fn, {10.0f, 15.0f, 20.0f, -200.0f, -20.0f, 1.0f});
unsigned int jellybean_index = item_type_count;
for (unsigned int i = 0; i < item_type_count; i++) {
if (item_types[i].name == "jellybean") {
jellybean_index = i;
break;
}
}
if (jellybean_index == item_type_count) {
fprintf(stderr, "ERROR: There is no item named 'jellybean'.\n");
return EXIT_FAILURE;
}
position bottom_left_corner = {0, 0};
position top_right_corner = {32, 32};
position agent_start_position = {top_right_corner.x / 2, bottom_left_corner.y};
#if defined(NDEBUG)
unsigned int seed = milliseconds();
#else
unsigned int seed = 0;
#endif
std::minstd_rand rng(seed);
std::mutex lock;
array<float> reward_rates(512);
constexpr unsigned int thread_count = 32;
std::thread workers[thread_count];
for (unsigned int i = 0; i < thread_count; i++)
workers[i] = std::thread([&,i]() {
while (true) {
compute_optimal_reward_rate(i, n, mcmc_iterations, item_types, item_type_count, jellybean_index,
bottom_left_corner, top_right_corner, agent_start_position, lock, rng, reward_rates);
}
});
for (unsigned int i = 0; i < thread_count; i++) {
if (workers[i].joinable()) {
try {
workers[i].join();
} catch (...) { }
}
}
for (unsigned int i = 0; i < item_type_count; i++)
free(item_types[i], item_type_count);
return EXIT_SUCCESS;
}
| [
"abulhair.saparov@gmail.com"
] | abulhair.saparov@gmail.com |
39cd4b3e8680b9573a3ac51561fd0ff94dac387d | 4cb788cbd03e7cefccace693cebb86322f467f78 | /esp8266_sniffer/esp8266_sniffer.ino | 6ba7176156b99012d6b42437ce283147cfcfa16e | [] | no_license | michaelmalinowski/density-tracker | e9101a18c7fc10d089def60de0d0700a06cb05f9 | 7dfd6c62e4a19a2e8c6fcbe072a05c2ac18be262 | refs/heads/master | 2023-03-18T04:44:00.065745 | 2021-03-07T00:56:48 | 2021-03-07T00:56:48 | 275,963,670 | 5 | 0 | null | 2020-07-14T22:02:50 | 2020-06-30T01:16:09 | C++ | UTF-8 | C++ | false | false | 7,760 | ino | extern "C" {
#include <user_interface.h>
}
#include <Arduino.h>
#include <Wire.h>
#include <LiquidCrystal.h>
#define ON_WIFI 0 //scanning devices connected to a network or not
#define SCAN_CHANNEL 6
#define BLACKLIST_MODE_COUNTDOWN 10 //seconds to press button to enter blacklist mode
//ON_WIFI=1
#define DEVICE_TIMEOUT 5 //scanned device timeout in minutes
#define DEVICE_TIMEOUT_SCAN 1 //timeout checker in minutes
//ON_WIFI=0
#define BURST_DURATION 30 //duration of a burst in seconds
#define BURST_AVERAGE 2 // how many bursts to average over
#define SEND_DATA 0 //0 for lcd function and 1 for sending data to another board
struct frameControl {
unsigned protocol: 2;
unsigned type: 2;
unsigned subtype: 4;
unsigned toDS: 1;
unsigned fromDS: 1;
unsigned frag: 1;
unsigned retry: 1;
unsigned pwrManage: 1;
unsigned moreData: 1;
unsigned proFrame: 1;
unsigned order: 1;
};
struct rxControl {
signed rssi:8;
unsigned rate:4;
unsigned is_group:1;
unsigned:1;
unsigned sig_mode:2;
unsigned legacy_length:12;
unsigned damatch0:1;
unsigned damatch1:1;
unsigned bssidmatch0:1;
unsigned bssidmatch1:1;
unsigned MCS:7;
unsigned CWB:1;
unsigned HT_length:16;
unsigned Smoothing:1;
unsigned Not_Sounding:1;
unsigned:1;
unsigned Aggregation:1;
unsigned STBC:2;
unsigned FEC_CODING:1;
unsigned SGI:1;
unsigned rxend_state:8;
unsigned ampdu_cnt:8;
unsigned channel:4;
unsigned:12;
};
struct snifferStream {
struct rxControl rx_control;
uint8_t buf[112];
uint16_t count;
uint16_t length;
};
struct device {
uint8_t mac[6];
unsigned long last_seen;
};
struct deviceList {
device list[200];
uint8_t len = 0;
};
static deviceList device_list;
static deviceList black_list;
uint8_t bursts[BURST_AVERAGE];
uint8_t burst_number = 0;
uint8_t previous_burst_total = 0;
static unsigned long current_time;
static unsigned long clear_time;
const char MAC_FORMAT[] = "%02X:%02X:%02X:%02X:%02X:%02X\n";
bool mode = false;
LiquidCrystal lcd(2,0,4,5,13,12);
//checks if mac address is within the list and return the mac address if it isnt
//prints rssi and channel from rxControl to serial
void printRxControl(rxControl data){
Serial.printf("rssi: %d\n", data.rssi);
Serial.printf("channel: %d\n", data.channel);
}
//Keeps the device in blacklist mode until a button press changes the mode
void blacklistMode(){
bool buttonPressed = false;
wifi_init();
while(mode){
lcd.setCursor(0,1);
buttonPressed = (digitalRead(15) == HIGH);
delay(100);
if (buttonPressed) {
mode = false;
lcd.clear();
lcd.print("Exited");
delay(500);
break;
}
lcd.print(black_list.len);
lcd.print(" ");
}
}
//prints three mac addresses to serial
void printMacAddresses(char* mac1, char* mac2, char* mac3){
Serial.printf("Receiver: ");
Serial.printf(MAC_FORMAT, mac1[0], mac1[1], mac1[2], mac1[3], mac1[4], mac1[5]);
Serial.printf("Sender: ");
Serial.printf(MAC_FORMAT, mac2[0], mac2[1], mac2[2], mac2[3], mac2[4], mac2[5]);
Serial.printf("Filter: ");
Serial.printf(MAC_FORMAT, mac3[0], mac3[1], mac3[2], mac3[3], mac3[4], mac3[5]);
}
//saves a mac address to a deviceList
void saveMacAddress(uint8_t* mac, deviceList* devices, rxControl data, bool print=false){
uint8_t i;
if (!mode) {
for (i = 0; i < devices->len; ++i){
if (memcmp(mac, devices->list[i].mac, 6) == 0) {
devices->list[i].last_seen = current_time;
return;
}
}
}
if (blacklistedDevice(mac)) {
device new_device;
memcpy(new_device.mac, mac, 6);
new_device.last_seen = current_time;
devices->list[devices->len] = new_device;
devices->len += 1;
if (print) {
Serial.printf(MAC_FORMAT, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
printRxControl(data);
}
}
return;
}
//checks if a device has expired with a deviceList
uint8_t expiredDevices(deviceList* devices=&device_list){
//Serial.printf("Expired device check\n");
uint8_t i;
uint8_t shift = 0, expired = 0;
for(i = 0; i < devices->len; ++i){
if (shift > 0) {
devices->list[i - shift] = devices->list[i];
}
if (current_time - devices->list[i].last_seen > DEVICE_TIMEOUT * 60000) {
++expired;
++shift;
}
}
devices->len -= expired;
return expired;
}
//checks if a device is in the blacklist
bool blacklistedDevice(uint8_t* mac){
uint8_t i;
for (i = 0; i < black_list.len; ++i){
if (memcmp(mac, black_list.list[i].mac, 6) == 0) {
black_list.list[i].last_seen = current_time;
return false;
}
}
return true;
}
//callback function.
//Analyzes packet data
void packetAnalyzer(uint8_t* buf, uint16_t len){
if (len == 12) {
return;
} else if (len == 128) {
uint8_t mac1[6];
uint8_t mac2[6];
uint8_t mac3[6];
snifferStream *data = (snifferStream*) buf;
frameControl *frame = (frameControl*) data->buf;
//Probe request
if (frame->type == 0 && frame->subtype == 4){
uint8_t i;
for (i = 0; i < 6; ++i) {
mac1[i] = data->buf[i + 10];
}
if (mode == 0) {
saveMacAddress(mac1, &device_list, data->rx_control);
}
//probe response
} else {
uint8_t i;
for (i = 0; i < 6; ++i) {
mac1[i] = data->buf[i + 4];
}
for (i = 0; i < 6; ++i) {
mac2[i] = data->buf[i + 10];
}
for (i = 0; i < 6; ++i) {
mac3[i] = data->buf[i + 16];
}
}
if (mode) {
saveMacAddress(mac1, &black_list, data->rx_control);
}
}
}
//formats device mac address into a single uint8_t array
void formatDevices(uint8_t* deviceArray){
uint8_t i, k, indexPoint;
for (i = 0; i < device_list.len; ++i) {
indexPoint = i * 6;
for (k = 0; k < 6; ++k) {
deviceArray[indexPoint + k] = device_list.list[i].mac[k];
}
}
}
//prints num to an lcd
void printDevices(uint8_t num){
lcd.clear();
lcd.print("Active Devices:");
lcd.setCursor(0,1);
lcd.print(num);
delay(250);
}
//prints num to serial
void sendDevices(uint8_t num){
if(Serial.available() > 0){
char incomingData = Serial.read();
if (incomingData == '1') {
Serial.printf("%d", num);
}
}
}
//transmits device number data
void transmitData(uint8_t num, uint8_t type=SEND_DATA){
if (type) {
sendDevices(num);
} else {
printDevices(num);
}
}
//wifi initilatization function
void wifi_init(){
wifi_set_opmode(STATION_MODE);
wifi_set_channel(SCAN_CHANNEL);
wifi_set_promiscuous_rx_cb(packetAnalyzer);
delay(100);
wifi_promiscuous_enable(1);
}
void setup(){
Serial.begin(115200);
delay(100);
//LCD INIT
lcd.begin(16, 2);
lcd.print("Scanner Screen");
delay(250);
lcd.clear();
//WIFI
lcd.print("BlackList Mode?");
current_time = millis();
bool buttonPressed = false;
while(BLACKLIST_MODE_COUNTDOWN > (current_time/1000)){
current_time = millis();
lcd.setCursor(0,1);
lcd.print((long)floor((BLACKLIST_MODE_COUNTDOWN - (current_time/1000))));
lcd.print(" ");
buttonPressed = digitalRead(15);
if (buttonPressed) {
lcd.clear();
lcd.print("BlackListed:");
mode = true;
break;
}
yield();
}
blacklistMode();
lcd.clear();
lcd.print("Scanner Started");
clear_time = current_time;
}
void loop(){
yield();
current_time = millis();
if (current_time - clear_time > DEVICE_TIMEOUT_SCAN * 60000 && ON_WIFI) {
clear_time = current_time;
expiredDevices();
transmitData(device_list.len);
}
if (ON_WIFI == 0) {
if (current_time - clear_time > BURST_DURATION * 1000) {
bursts[burst_number] = device_list.len;
device_list.len = 0;
++burst_number;
clear_time = current_time;
}
if (burst_number >= BURST_AVERAGE) {
burst_number = 0;
uint8_t i;
int average = 0;
for (i = 0; i < BURST_AVERAGE; ++i){
average += bursts[i];
}
previous_burst_total = (uint8_t)average/BURST_AVERAGE;
}
transmitData(previous_burst_total);
}
}
| [
"mike.m7@hotmail.com"
] | mike.m7@hotmail.com |
d799212681fc4a6aeb5468e935686f8dcb8d05ae | 1df9106e475d7f1b4de615cb4f8122cc93305b7b | /Engine/LightComponent.cpp | ea441229c94af62e4965d0f78ae73ed2d4ec9283 | [] | no_license | mcferront/anttrap-engine | 54517007911389a347e25542c928a0dd4276b730 | c284f7800becaa973101a14bf0b7ffb0d6b732b4 | refs/heads/master | 2021-06-26T08:48:59.814404 | 2019-02-16T05:37:43 | 2019-02-16T05:37:43 | 148,593,261 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,902 | cpp | #include "EnginePch.h"
#include "LightComponent.h"
#include "Node.h"
#include "RenderWorld.h"
DefineComponentType( LightComponent, NULL );
DefineComponentType( DirectionalLightComponent, new DirectionalLightComponentSerializer );
DefineComponentType( AmbientLightComponent, new AmbientLightComponentSerializer );
DefineComponentType( SpotLightComponent, new SpotLightComponentSerializer );
DefineComponentType( PointLightComponent, new PointLightComponentSerializer );
void LightComponent::Destroy( void )
{
Component::Destroy( );
}
void LightComponent::AddToScene( void )
{
if ( false == GetParent( )->IsInScene( ) ) return;
Component::AddToScene( );
m_Light.AddToScene( );
}
void LightComponent::RemoveFromScene( void )
{
m_Light.RemoveFromScene( );
Component::RemoveFromScene( );
}
void DirectionalLightComponent::Create(
const IdList &renderGroups,
Vector color,
float nits
)
{
LightDesc desc;
desc.color = color;
desc.nits = nits;
desc.inner = FLT_MAX;
desc.outer = FLT_MAX;
desc.range = FLT_MAX;
desc.cast = LightDesc::CastDirectional;
LightComponent::Create( renderGroups, desc );
}
void AmbientLightComponent::Create(
const IdList &renderGroups,
Vector color,
float nits
)
{
LightDesc desc;
desc.color = color;
desc.nits = nits;
desc.inner = FLT_MAX;
desc.outer = FLT_MAX;
desc.range = FLT_MAX;
desc.cast = LightDesc::CastAmbient;
LightComponent::Create( renderGroups, desc );
}
void SpotLightComponent::Create(
const IdList &renderGroups,
Vector color,
float nits,
float inner,
float outer,
float range
)
{
LightDesc desc;
desc.color = color;
desc.nits = nits;
desc.inner = inner;
desc.outer = outer;
desc.range = range;
desc.cast = LightDesc::CastSpot;
LightComponent::Create( renderGroups, desc );
}
void PointLightComponent::Create(
const IdList &renderGroups,
Vector color,
float nits,
float range
)
{
LightDesc desc;
desc.color = color;
desc.nits = nits;
desc.inner = FLT_MAX;
desc.outer = FLT_MAX;
desc.range = range;
desc.cast = LightDesc::CastOmni;
LightComponent::Create( renderGroups, desc );
}
void PointLightComponent::SetColor(
const Vector &color
)
{
m_Light.SetColor( color );
}
ISerializable *DirectionalLightComponentSerializer::Deserialize(
Serializer *pSerializer,
ISerializable *pSerializable
)
{
return NULL;
//if ( NULL == pSerializable ) pSerializable = new DirectionalLightComponent;
//DirectionalLightComponent *pDirectionalLightComponent = (DirectionalLightComponent *) pSerializable;
//Id id;
//IdList renderGroups;
//Color color;
//float nits;
//id = Id::Deserialize( pSerializer->GetInputStream( ) );
//Id::DeserializeList( pSerializer->GetInputStream( ), &renderGroups );
//pSerializer->GetInputStream( )->Read( &color, sizeof( color ) );
//pSerializer->GetInputStream( )->Read( &nits, sizeof( nits ) );
//pDirectionalLightComponent->Create( renderGroups, Vector( color.r / 255.0f, color.g / 255.0f, color.b / 255.0f, color.a / 255.0f ), nits );
//return pSerializable;
}
ISerializable *AmbientLightComponentSerializer::Deserialize(
Serializer *pSerializer,
ISerializable *pSerializable
)
{
return NULL;
//if ( NULL == pSerializable ) pSerializable = new AmbientLightComponent;
//AmbientLightComponent *pAmbientLightComponent = (AmbientLightComponent *) pSerializable;
//Id id;
//Color color;
//IdList renderGroups;
//id = Id::Deserialize( pSerializer->GetInputStream( ) );
//Id::DeserializeList( pSerializer->GetInputStream( ), &renderGroups );
//pSerializer->GetInputStream( )->Read( &color, sizeof( color ) );
//pAmbientLightComponent->Create( renderGroups, Vector( color.r / 255.0f, color.g / 255.0f, color.b / 255.0f, color.a / 255.0f ) );
//return pSerializable;
}
ISerializable *SpotLightComponentSerializer::Deserialize(
Serializer *pSerializer,
ISerializable *pSerializable
)
{
return NULL;
// if ( NULL == pSerializable ) pSerializable = new SpotLightComponent;
//
// SpotLightComponent *pSpotLightComponent = (SpotLightComponent *) pSerializable;
//
// Id id;
// IdList renderGroups;
// Color color;
// float nits, inner, outer, range;
//
// id = Id::Deserialize( pSerializer->GetInputStream( ) );
// Id::DeserializeList( pSerializer->GetInputStream( ), &renderGroups );
// pSerializer->GetInputStream( )->Read( &color, sizeof( color ) );
// pSerializer->GetInputStream( )->Read( &nits, sizeof( nits ) );
// pSerializer->GetInputStream( )->Read( &inner, sizeof( inner ) );
// pSerializer->GetInputStream( )->Read( &outer, sizeof( outer ) );
// pSerializer->GetInputStream( )->Read( &range, sizeof( range ) );
//
// pSpotLightComponent->Create( renderGroups, Vector( color.r / 255.0f, color.g / 255.0f, color.b / 255.0f, color.a / 255.0f ), nits, inner, outer, range );
//
// return pSerializable;
}
ISerializable *PointLightComponentSerializer::Deserialize(
Serializer *pSerializer,
ISerializable *pSerializable
)
{
return NULL;
//if ( NULL == pSerializable ) pSerializable = new PointLightComponent;
//PointLightComponent *pPointLightComponent = (PointLightComponent *) pSerializable;
//Id id;
//IdList renderGroups;
//Color color;
//float nits, range;
//id = Id::Deserialize( pSerializer->GetInputStream( ) );
//Id::DeserializeList( pSerializer->GetInputStream( ), &renderGroups );
//pSerializer->GetInputStream( )->Read( &color, sizeof( color ) );
//pSerializer->GetInputStream( )->Read( &nits, sizeof( nits ) );
//pSerializer->GetInputStream( )->Read( &range, sizeof( range ) );
//pPointLightComponent->Create( renderGroups, Vector( color.r / 255.0f, color.g / 255.0f, color.b / 255.0f, color.a / 255.0f ), nits, range );
//return pSerializable;
}
| [
"trapper@trapzz.com"
] | trapper@trapzz.com |
4df51688e303a1074f08da42088d544a16909127 | 4e22253a4f2a834783e465d951f80e30c18d0a03 | /list.h | 58e47be5ef2fe71c80598f0a9f345416c07d7fc8 | [] | no_license | BraveY/Quadrangle | 953b570d3e9e3e7e850c4b57ebf82510017844c1 | f09a3c56c3a22c35128fc916eb6076b14f2a5e4b | refs/heads/master | 2021-01-11T21:34:03.725153 | 2017-01-13T02:21:50 | 2017-01-13T02:21:50 | 78,807,512 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,141 | h | #pragma once
#ifndef __LIST__
#define __LIST__
#include "cont.h"
template<typename T>
class List :public Container<T>
{
protected:
struct Node
{
T data;
Node *next;
} *head, *tail;
public:
List()
{
head=NULL;
tail= NULL;
};
List(const List&l) :head(l.head), tail(l.tail) {};
~List() { clear(); }
size_t size() const
{
Node*p = head;
size_t i = 0;
while (p != NULL)
{
p = p->next;
++i;
}
return i;
}
operator bool() const
{
return head != NULL;
}
List& push_back(const T& data)
{
Node *p = new Node();
p->data = data;
p->next = NULL;
if (tail == NULL) head = tail = p;
else
{
tail->next = p;
tail = p;
}
return *this;
}
T operator[](int index)
{
Node *p = head;
for (int i = 0;i!=index; i++)
{
p = p->next;
}
return p->data;
}
List& operator=(const List&s)
{
head = s.head;
tail = s.tail;
return *this;
}
void pop_back()
{
Node *p = head, *q=p->next;
while (q->next != tail)
{
p = p->next;
q=p->next;
}
p->next = tail;
delete q;
}
void clear()
{
Node *p = head, *q;
while (p != NULL)
{
q = p;
p = p->next;
delete p;
}
head = tail = NULL;
}
List& operator +=(const T& data)
{
push_back(data);
return *this;
}
void traverse()
{
Node*p = head;
while (p != NULL)
{
p->data->draw();
p = p->next;
}
}
friend class listIterator;
class listIterator
{
private:
List<T> *plist;
typename List<T>::Node *p;
public:
listIterator(const List<T>&list) :plist(const_cast<List<T>*>(&list)), p(list.head) {}
listIterator(const listIterator &itr) :plist(itr.plist), p(itr.p) {}
listIterator() :plist(NULL), p(NULL) {}
listIterator & begin()
{
p = plist->List<T>::head;
return *this;
}
listIterator end()
{
return listIterator();
}
listIterator & operator=(const listIterator&itr)
{
return p != itr.p;
}
listIterator &operator++()
{
p = p->next;
return *this;
}
listIterator &operator+(int i)
{
for (int n = 0;n < i;n++)
{
p = p->next;
}
return *this;
}
T& operator *()
{
return p->data;
}
};
};
#endif | [
"lsz_yky@163.com"
] | lsz_yky@163.com |
bc62e1fbc3ba4150fb90873e05ec09939f274ccc | a81c07a5663d967c432a61d0b4a09de5187be87b | /ash/system/message_center/arc/arc_notification_content_view.h | caaa5712feb4c122b76686610c758592491f984e | [
"BSD-3-Clause"
] | permissive | junxuezheng/chromium | c401dec07f19878501801c9e9205a703e8643031 | 381ce9d478b684e0df5d149f59350e3bc634dad3 | refs/heads/master | 2023-02-28T17:07:31.342118 | 2019-09-03T01:42:42 | 2019-09-03T01:42:42 | 205,967,014 | 2 | 0 | BSD-3-Clause | 2019-09-03T01:48:23 | 2019-09-03T01:48:23 | null | UTF-8 | C++ | false | false | 7,921 | h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_SYSTEM_MESSAGE_CENTER_ARC_ARC_NOTIFICATION_CONTENT_VIEW_H_
#define ASH_SYSTEM_MESSAGE_CENTER_ARC_ARC_NOTIFICATION_CONTENT_VIEW_H_
#include <memory>
#include <string>
#include "ash/system/message_center/arc/arc_notification_item.h"
#include "ash/system/message_center/arc/arc_notification_surface_manager.h"
#include "base/macros.h"
#include "ui/aura/window_observer.h"
#include "ui/message_center/views/notification_background_painter.h"
#include "ui/message_center/views/notification_control_buttons_view.h"
#include "ui/views/controls/native/native_view_host.h"
#include "ui/views/widget/widget_observer.h"
namespace message_center {
class Notification;
class NotificationControlButtonsView;
} // namespace message_center
namespace ui {
class LayerTreeOwner;
}
namespace views {
class FocusTraversable;
class Widget;
} // namespace views
namespace ash {
class ArcNotificationSurface;
// ArcNotificationContentView is a view to host NotificationSurface and show the
// content in itself. This is implemented as a child of ArcNotificationView.
class ArcNotificationContentView
: public views::NativeViewHost,
public aura::WindowObserver,
public ArcNotificationItem::Observer,
public ArcNotificationSurfaceManager::Observer,
public views::WidgetObserver {
public:
static const char kViewClassName[];
ArcNotificationContentView(ArcNotificationItem* item,
const message_center::Notification& notification,
message_center::MessageView* message_view);
~ArcNotificationContentView() override;
// views::View overrides:
const char* GetClassName() const override;
void Update(const message_center::Notification& notification);
message_center::NotificationControlButtonsView* GetControlButtonsView();
void UpdateControlButtonsVisibility();
void UpdateCornerRadius(int top_radius, int bottom_radius);
void OnSlideChanged(bool in_progress);
void OnContainerAnimationStarted();
void OnContainerAnimationEnded();
void ActivateWidget(bool activate);
private:
friend class ArcNotificationViewTest;
friend class ArcNotificationContentViewTest;
FRIEND_TEST_ALL_PREFIXES(ArcNotificationContentViewTest,
ActivateWhenRemoteInputOpens);
class EventForwarder;
class MouseEnterExitHandler;
class SettingsButton;
class SlideHelper;
void CreateCloseButton();
void CreateSettingsButton();
void MaybeCreateFloatingControlButtons();
void SetSurface(ArcNotificationSurface* surface);
void UpdatePreferredSize();
void UpdateSnapshot();
void AttachSurface();
void SetExpanded(bool expanded);
bool IsExpanded() const;
void SetManuallyExpandedOrCollapsed(bool value);
bool IsManuallyExpandedOrCollapsed() const;
void ShowCopiedSurface();
void HideCopiedSurface();
// Generates a mask using |top_radius_| and |bottom_radius_| and installs it.
void UpdateMask(bool force_update);
// views::NativeViewHost
void ViewHierarchyChanged(
const views::ViewHierarchyChangedDetails& details) override;
void Layout() override;
void OnPaint(gfx::Canvas* canvas) override;
void OnMouseEntered(const ui::MouseEvent& event) override;
void OnMouseExited(const ui::MouseEvent& event) override;
void OnFocus() override;
void OnBlur() override;
views::FocusTraversable* GetFocusTraversable() override;
void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
void OnAccessibilityEvent(ax::mojom::Event event) override;
void AddedToWidget() override;
void RemovedFromWidget() override;
// aura::WindowObserver
void OnWindowBoundsChanged(aura::Window* window,
const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds,
ui::PropertyChangeReason reason) override;
void OnWindowDestroying(aura::Window* window) override;
// views::WidgetObserver:
void OnWidgetClosing(views::Widget* widget) override;
// ArcNotificationItem::Observer
void OnItemDestroying() override;
void OnItemContentChanged(
arc::mojom::ArcNotificationShownContents content) override;
void OnRemoteInputActivationChanged(bool activated) override;
// ArcNotificationSurfaceManager::Observer:
void OnNotificationSurfaceAdded(ArcNotificationSurface* surface) override;
void OnNotificationSurfaceRemoved(ArcNotificationSurface* surface) override;
// If |item_| is null, we may be about to be destroyed. In this case,
// we have to be careful about what we do.
ArcNotificationItem* item_;
ArcNotificationSurface* surface_ = nullptr;
arc::mojom::ArcNotificationShownContents shown_content_ =
arc::mojom::ArcNotificationShownContents::CONTENTS_SHOWN;
// The flag to prevent an infinite loop of changing the visibility.
bool updating_control_buttons_visibility_ = false;
const std::string notification_key_;
// A pre-target event handler to forward events on the surface to this view.
// Using a pre-target event handler instead of a target handler on the surface
// window because it has descendant aura::Window and the events on them need
// to be handled as well.
// TODO(xiyuan): Revisit after exo::Surface no longer has an aura::Window.
std::unique_ptr<EventForwarder> event_forwarder_;
// A handler which observes mouse entered and exited events for the floating
// control buttons widget.
std::unique_ptr<ui::EventHandler> mouse_enter_exit_handler_;
// A helper to observe slide transform/animation and use surface layer copy
// when a slide is in progress and restore the surface when it finishes.
std::unique_ptr<SlideHelper> slide_helper_;
// Whether the notification is being slid or is at the origin. This stores the
// latest value of the |in_progress| from OnSlideChanged callback, which is
// called during both manual swipe and automatic slide on dismissing or
// resetting back to the origin.
// This value is synced with the visibility of the copied surface. If the
// value is true, the copied surface is visible instead of the original
// surface itself. Copied surgace doesn't have control buttons so they must be
// hidden if it's true.
// This value is stored in case of the change of surface. When a new surface
// sets, if this value is true, the copy of the new surface gets visible
// instead of the copied surface itself.
bool slide_in_progress_ = false;
// A control buttons on top of NotificationSurface. Needed because the
// aura::Window of NotificationSurface is added after hosting widget's
// RootView thus standard notification control buttons are always below
// it.
std::unique_ptr<views::Widget> floating_control_buttons_widget_;
// The message view which wrapps thie view. This must be the parent of this
// view.
message_center::MessageView* const message_view_;
// This view is owned by client (this).
message_center::NotificationControlButtonsView control_buttons_view_;
// Protects from call loops between Layout and OnWindowBoundsChanged.
bool in_layout_ = false;
// Widget which this view tree is currently attached to.
views::Widget* attached_widget_ = nullptr;
base::string16 accessible_name_;
// If it's true, the surface gets active when attached to this view.
bool activate_on_attach_ = false;
// Radiuses of rounded corners. These values are used in UpdateMask().
int top_radius_ = 0;
int bottom_radius_ = 0;
// Current insets of mask layer.
base::Optional<gfx::Insets> mask_insets_;
std::unique_ptr<ui::LayerTreeOwner> surface_copy_;
DISALLOW_COPY_AND_ASSIGN(ArcNotificationContentView);
};
} // namespace ash
#endif // ASH_SYSTEM_MESSAGE_CENTER_ARC_ARC_NOTIFICATION_CONTENT_VIEW_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.