blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a77456410f7d9c2816d2563e5d502e6a0db5ef05 | 60205812b617b29713fe22dcb6084c4daed9da18 | /00-Keypoint_in_WangDao/Chapter_06-Graph/02-Minimum_Spannning_Tree/00-Prim/00-Prim.cpp | 215051a4e594a32b7a54f46da38864d5bf4eb189 | [
"MIT"
] | permissive | liruida/kaoyan-data-structure | bc04d6306736027cb5fc4090a2796aca7abbbaa4 | d0a469bf0e9e7040de21eca38dc19961aa7e9a53 | refs/heads/master | 2023-04-02T19:57:49.252343 | 2021-01-03T07:20:11 | 2021-01-03T07:20:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 995 | cpp | void Prim(MGraph g, int v0, int &sum) {
int lowcost[maxSize], vset[maxSize], v;
int i, j, k, min;
v = v0;
for(i = 0; i < g.n; ++i) {
lowcost[i] = g.edges[v0][i];
vset[i] = 0;
}
vset[v0] = 1; //将v0并入树中
sum = 0; //sum清零用来累计树的权值
for(i = 0; i < g.n-1; ++i) {
min = INF; //INF是一个已经定义的比图中所有边权值都大的常量
/*下面这个循环用于选出候选边中的最小者*/
for(j = 0; j < g.n; ++j) {
if(vset[j] == 0 && lowcost[j] < min) {
//选出当前生成树到其余顶点最短边中的一条(注意这里两个最短的含义)
min = lowcost[j];
k = j;
}
}
vset[k] = 1;
v = k;
sum += min; //这里用sum记录了最小生成树的权值
/*下面这个循环以刚并入的顶点v为媒介更新侯选边*/
for(j = 0; j < g.n; ++j) {
if(vset[j] == 0 && g.edges[v][j] < lowcost[j]) { //此处对应算法执行过程中的第(2)步
lowcost[j] = g.edges[v][j];
}
}
}
}
| [
"1097985743@qq.com"
] | 1097985743@qq.com |
adf1c466dbee4af37a779b3e7235c02edec773c6 | f9c4a3b4ab06f6f82b4ea3560c9dcfaf8fb6ff1a | /IntervalTree.cpp | 0fa301de09b8f6df93175dfab25167b3861bd5af | [] | no_license | lymcool/Introduction-to-Algorithms-Data-Structures | f6250124773b0e891cf1f41503658849b97ccbf5 | 695604bfd3da9b126b4751779fcbf8ab9cbb1318 | refs/heads/master | 2021-09-03T06:35:45.540632 | 2018-01-06T14:02:42 | 2018-01-06T14:02:42 | 109,775,501 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 717 | cpp |
#include <iostream>
#include <vector>
#include "IntervalTree.h"
using namespace std;
void main() {
int a[6] = { 17, 5, 21, 4, 15, 7 };
int b[6] = { 19, 11, 23, 8, 18, 10 };
vector<dataNode> data;
for (int i = 0;i < 6;i++) {
dataNode d;
d.low = a[i];
d.high = b[i];
data.push_back(d);
}
IntervalTree interval(data[0]);
for (int i = 1;i < 6;i++) {
interval.insertIntervalTree(interval.root, data[i]);
}
cout << "中序遍历的结果:" << endl;
interval.inorderOSRBTree(interval.root);
cout << endl;
dataNode sd;
sd.low = 18;
sd.high = 25;
BSTNode* bst = interval.intervalSearch(interval.root, sd);
cout << "[" << bst->d.low << "," << bst->d.high << "]" << endl;
system("pause");
}
| [
"1326833121@qq.com"
] | 1326833121@qq.com |
98087c8c5c12b7ac214e71f7131b9062e42eb3b8 | 51bce7274dcdfb3ae1c00fe7010ee6818ea8f260 | /Sensor.cpp | e10a3df1a406ecfcec529c91eb5c7c689af2d04d | [] | no_license | cvicens/caelum | dbea7672cd02a346be6f966a68374278601c3ff4 | 35af1f74bd0826669daf126617cbe6ee5f90007e | refs/heads/main | 2023-08-15T20:30:46.497821 | 2021-10-19T13:41:54 | 2021-10-19T13:41:54 | 398,583,378 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 224 | cpp | /*
Sensor.cpp - Base Class for sensors.
Created by Carlos V.
Released into the public domain.
*/
#include "Sensor.h"
// Sensor::Sensor(char* name)
// {
// this->initialized = false;
// this->valid = false;
// }
| [
"carlos.vicens.alonso@gmail.com"
] | carlos.vicens.alonso@gmail.com |
c8f54486df68e2510ba878486cf368f5341f5f53 | 1552d8af68204103fcd269c6eb508cf061f7f0fe | /src/util.h | 0e4e8011a4335aeb347488b71c0541fbbb3747ff | [] | no_license | staveshan/Bootstrap | c4ef433cf6e796021cd3f519aee4be9e623f64ef | d9d7560c2cae5f6927925cb61700ed4101345ab5 | refs/heads/master | 2020-03-24T07:55:31.414177 | 2016-06-20T02:15:42 | 2016-06-20T02:15:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,303 | h | #ifndef _BS_UTILS_H_
#define _BS_UTILS_H_
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <search.h>
#include <pthread.h>
#include <errno.h>
#include <sys/types.h>
#include <time.h>
#include "list.h"
#define panic(fmt, arg...) do { fprintf(stderr,"panic!! "fmt,"\n", ##arg); abort(); } while(0)
#define bs_trace(fmt, arg...) do { fprintf(stderr, "%s:%s:line %d: "fmt"\n", __FILE__,__func__,__LINE__,##arg); } while(0)
#define bs_debug(fmt, arg...) do { fprintf(stderr, fmt"\n", ##arg); } while(0)
#define bs_err(fmt, arg...) do { fprintf(stderr, fmt"\n", ##arg); } while(0)
#define bs_warn(fmt, arg...) do { fprintf(stderr, fmt"\n", ##arg); } while(0)
#define bs_notice(fmt, arg...) do { fprintf(stderr, fmt"\n", ##arg); } while(0)
#define MIN(x, y) ((x) > (y) ? (y) : (x))
#define MAX(x, y) ((x) > (y) ? (x) : (y))
#define min(x, y) ({ \
typeof(x) _x = (x); \
typeof(y) _y = (y); \
(void) (&_x == &_y); \
_x < _y ? _x : _y; })
#define max(x, y) ({ \
typeof(x) _x = (x); \
typeof(y) _y = (y); \
(void) (&_x == &_y); \
_x > _y ? _x : _y; })
/*
* Compares two integer values
*
* If the first argument is larger than the second one, intcmp() returns 1. If
* two members are equal, returns 0. Otherwise, returns -1.
*/
#define intcmp(x, y) \
({ \
typeof(x) _x = (x); \
typeof(y) _y = (y); \
(void) (&_x == &_y); \
_x < _y ? -1 : _x > _y ? 1 : 0; \
})
typedef void (*try_to_free_t)(size_t);
try_to_free_t set_try_to_free_routine(try_to_free_t);
void *xmalloc(size_t size);
void *xcalloc(size_t nmemb, size_t size);
ssize_t xread(int fd, void *buf, size_t len);
ssize_t xwrite(int fd, const void *buf, size_t len);
int eventfd_xread(int efd);
void eventfd_xwrite(int efd, int value);
/* wrapper for pthread_mutex */
#define BS_MUTEX_INITIALIZER { .mutex = PTHREAD_MUTEX_INITIALIZER }
struct bs_mutex {
pthread_mutex_t mutex;
};
static inline void bs_init_mutex(struct bs_mutex *mutex)
{
int ret;
do {
ret = pthread_mutex_init(&mutex->mutex, NULL);
} while (ret = EAGAIN);
if (unlikely(ret != 0))
panic("failed to initialize a lock, %s", strerror(ret));
}
static inline void bs_destroy_mutex(struct bs_mutex *mutex)
{
int ret;
do {
ret = pthread_mutex_destroy(&mutex->mutex);
} while (ret == EAGAIN);
if (unlikely(ret != 0))
panic("failed to destroy a lock, %s", strerror(ret));
}
static inline void bs_mutex_lock(struct bs_mutex *mutex)
{
int ret;
do {
ret = pthread_mutext_lock(&mutex->mutex);
} while (ret == EAGAIN);
if (unlikely(ret != 0))
panic("failed to lock for reading, %s", strerror(ret));
}
static inline int bs_mutex_trylock(struct bs_mutex *mutex)
{
return pthread_mutex_trylock(&mutex->mutex);
}
static inline void bs_mutex_unlock(struct bs_mutex *mutex)
{
int ret;
do {
ret = pthread_mutex_unlock(&mutex->mutex);
} while (ret == EAGAIN);
if (unlikely(ret != 0))
panic("failed to unlock, %s", strerror(ret));
}
/* wrapper for pthread_cond */
#define BS_COND_INITIALIZER { .cond = PTHREAD_COND_INITIALIZER }
struct bs_cond {
pthread_cond_t cond;
};
static inline void bs_cond_init(struct bs_cond *cond)
{
int ret;
do {
ret = pthread_cond_init(&cond->cond, NULL);
} while (ret == EAGAIN);
if (unlikely(ret != 0))
panic("failed to initialize a lock %s", strerror(ret));
}
static inline void bs_destroy_cond(struct bs_cond *cond)
{
int ret;
do {
ret = pthread_cond_destroy(&cond->cond);
} while (ret == EAGAIN);
if (unlikely(ret != 0))
panic("failed to destroy a lock %s", strerror(ret));
}
static inline int bs_cond_wait(struct bs_cond *cond, struct bs_mutex *mutex)
{
return pthread_cond_wait(&cond->cond, &mutex->mutex);
}
static inline int bs_cond_broadcast(struct bs_cond *cond)
{
return pthread_cond_broadcast(&cond->cond);
}
/* wrapper for pthread_rwlock */
#define BS_RW_LOCK_INITIALIZER { .rwlock = PTHREAD_RWLOCK_INITIALIZER }
struct bs_rw_lock {
pthread_rwlock_t rwlock;
};
static inline void bs_init_rw_lock(struct bs_rw_lock *lock)
{
int ret;
do {
ret = pthread_rwlock_init(&lock->rwlock, NULL);
} while (ret == EAGAIN);
if (unlikely(ret != 0))
panic("failed to initialize a lock, %s", strerror(ret));
}
static inline void bs_destroy_rw_lock(struct bs_rw_lock *lock)
{
int ret;
do {
ret = pthread_rwlock_destroy(&lock->rwlock);
} while (ret == EAGAIN);
if (unlikely(ret != 0))
panic("failed to destroy a lock, %s", strerror(ret));
}
static inline void bs_read_lock(struct bs_rw_lock *lock)
{
int ret;
do {
ret = pthread_rwlock_rdlock(&lock->rwlock);
} while (ret == EAGAIN);
if (unlikely(ret != 0))
panic("failed to lock for reading, %s", strerror(ret));
}
/*
* Even though POSIX manual it doesn't return EAGAIN, we indeed have met the
* case that it returned EAGAIN
*/
static inline void bs_write_lock(struct bs_rw_lock *lock)
{
int ret;
do {
ret = pthread_rwlock_wrlock(&lock->rwlock);
} while (ret == EAGAIN);
if (unlikely(ret != 0))
panic("failed to lock for writing, %s", strerror(ret));
}
static inline void bs_rw_unlock(struct bs_rw_lock *lock)
{
int ret;
do {
ret = pthread_rwlock_unlock(&lock->rwlock);
} while (ret == EAGAIN);
if (unlikely(ret != 0))
panic("failed to unlock, %s", strerror(ret));
}
#endif
| [
"yoonki@mdstec.com"
] | yoonki@mdstec.com |
c3c1b6cdcc39842a38af164688d0868b5f12fea2 | 328de0c1f7041d5fa266ecaf29d7720e4a15c5aa | /CompositeCommand.cpp | 89100cd59a52fd86d939709306256e80d8a9f719 | [] | no_license | hjxy2012/CppDesignPatterns | 9a725cc7ee44c4dcf2d88359717aab843411cc19 | a001c17fe2297812d8cff68d96991771733863b9 | refs/heads/master | 2023-05-31T06:41:07.630796 | 2018-06-19T17:45:39 | 2018-06-19T17:45:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,515 | cpp | #include <iostream>
#include <vector>
using namespace std;
struct BankAccount {
int balance_ = 0;
int threshold_ = 0;
void Deposit(int amount) {
balance_ += amount;
cout << "Deposit: " << amount << "\n"
<< "Balance: " << balance_ << endl;
}
bool Withdraw(int amount) {
if (balance_ - amount >= threshold_) {
balance_ -= amount;
cout << "Withdrew: " << amount << "\n"
<< "Balance: " << balance_ << endl;
return true;
}
else {
return false;
}
}
};
struct Command {
bool success_;
virtual void Do() = 0;
virtual void Undo() = 0;
};
struct BankAccountCommand : Command {
BankAccount& account_;
enum Action {deposit_, withdraw_} action_;
int amount_;
BankAccountCommand(BankAccount& account, const Action action, const int amount)
: account_{account}, action_{action}, amount_{amount} {
success_ = false;
}
void Do() override {
switch (action_) {
case deposit_:
account_.Deposit(amount_);
success_ = true;
break;
case withdraw_:
success_ = account_.Withdraw(amount_);
break;
}
}
void Undo() override {
if (!success_) return;
switch (action_) {
case deposit_:
account_.Withdraw(amount_);
break;
case withdraw_:
if (success_ == true) {
account_.Deposit(amount_);
}
break;
}
}
};
struct CompositeBankAccountCommand : vector<BankAccountCommand>, Command {
CompositeBankAccountCommand(const initializer_list<value_type>& actions)
: vector<BankAccountCommand>(actions) {}
void Do() override {
for(auto& command : *this) {
command.Do();
}
}
void Undo() override {
for(auto it = rbegin(); it != rend(); ++it) {
it->Undo();
}
}
};
struct DependentCompositeBankCommand : CompositeBankAccountCommand {
explicit DependentCompositeBankCommand(const initializer_list<value_type>& actions)
: CompositeBankAccountCommand{actions} {}
void Do() override {
// It depends on the success of previous command
bool previous_command_success = true;
for(auto& command : *this) {
if (previous_command_success) {
command.Do();
previous_command_success = command.success_;
}
else {
command.success_ = false;
}
}
}
};
struct TransferCommand : DependentCompositeBankCommand {
TransferCommand(BankAccount& source, BankAccount& destination, int amount)
: DependentCompositeBankCommand{
BankAccountCommand{source, BankAccountCommand::withdraw_, amount},
BankAccountCommand{destination, BankAccountCommand::deposit_, amount}
} {}
};
int main() {
BankAccount account_source;
BankAccount account_destination;
CompositeBankAccountCommand commands{
BankAccountCommand{account_source, BankAccountCommand::deposit_, 2037},
BankAccountCommand{account_destination, BankAccountCommand::deposit_, 10}
};
commands.Do();
cout << "Destination account: " << account_destination.balance_ << endl;
commands.Undo();
cout << "After undo, ";
cout << "Source account balance: " << account_source.balance_ << endl;
commands.Do();
TransferCommand transfer{account_source, account_destination, 2000};
transfer.Do();
cout << "After redo and tranfer, ";
cout << "Source balance: " << account_source.balance_
<< " and destination balance: " << account_destination.balance_
<< endl;
return 0;
}
| [
"rollschild@gmail.com"
] | rollschild@gmail.com |
49bac64acde2c0f73a7ed7f7cd3985745bb91fa6 | f33a8a22d6ef48a2968f6f378ad1f318e34278ee | /src/Game.cpp | 4eaa183d2e9241bd971da28d41c71268f389bd46 | [] | no_license | WBojangles/birds | 44cbd24b73137c315d75cb809ce9b9d0cc7f94fb | 6bf521faadf03391e04aefe3b96ad5fae357f42f | refs/heads/master | 2021-01-19T17:23:09.372728 | 2013-07-21T17:05:01 | 2013-07-21T17:05:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,321 | cpp | #include "../include/Game.hpp"
brd::Game::Game()
{
SHE::StateManager::window.create(sf::VideoMode(800, 600), "birds", sf::Style::Titlebar | sf::Style::Close);
//SHE::StateManager::window.create(sf::VideoMode(1440, 900), "Sailing the Seas of Sick", sf::Style::Fullscreen);
SHE::StateManager::window.setMouseCursorVisible(true);
SHE::StateManager::window.setFramerateLimit(60);
// Player setup
SHE::InputManager::setPlayers(1);
SHE::InputManager::setJoystick(1, 0);
// Bind keys
SHE::InputManager::bind(1, "quit", sf::Keyboard::F4);
SHE::InputManager::bind(1, "start", sf::Keyboard::Return);
SHE::InputManager::bind(1, "up", sf::Keyboard::Up);
SHE::InputManager::bind(1, "down", sf::Keyboard::Down);
SHE::InputManager::bind(1, "left", sf::Keyboard::Left);
SHE::InputManager::bind(1, "right", sf::Keyboard::Right);
SHE::InputManager::bind(1, "start", sf::Keyboard::Z);
SHE::InputManager::bind(1, "start", sf::Keyboard::X);
SHE::InputManager::bind(1, "start", sf::Keyboard::Space);
// Joystick
SHE::InputManager::setThreshold(1, sf::Joystick::X, 60.f);
SHE::InputManager::setThreshold(1, sf::Joystick::Y, 60.f);
SHE::InputManager::bind(1, "start", 5);
SHE::InputManager::bind(1, "up", sf::Joystick::Y, false);
SHE::InputManager::bind(1, "down", sf::Joystick::Y, true);
SHE::InputManager::bind(1, "left", sf::Joystick::X, false);
SHE::InputManager::bind(1, "right", sf::Joystick::X, true);
SHE::InputManager::bind(1, "start", 0);
SHE::StateManager::create("Title", std::tr1::shared_ptr<SHE::State>(new brd::Title));
SHE::StateManager::set("Title");
}
bool brd::Game::running()
{
return SHE::StateManager::window.isOpen();
}
void brd::Game::update()
{
// Time since last frame
sf::Time frametime = delta.restart();
// Events
sf::Event E;
while (SHE::StateManager::window.pollEvent(E))
{
switch (E.type)
{
case sf::Event::Closed:
SHE::StateManager::window.close();
break;
default:
break;
}
SHE::StateManager::events(E);
}
if (SHE::InputManager::check(1, "quit")) SHE::StateManager::window.close();
if (SHE::StateManager::quit) SHE::StateManager::window.close();
SHE::StateManager::update(frametime.asSeconds());
draw();
}
void brd::Game::draw()
{
SHE::StateManager::window.clear();
SHE::StateManager::draw();
SHE::StateManager::window.display();
}
| [
"qqofficial@gmail.com"
] | qqofficial@gmail.com |
c6d46827ffd6556b4105be3b29c3c21c81f6ffe8 | b55fcf6edd06cda075745abffb42c5052c445b41 | /cf/upsolving/742-A/code.cpp | 15ca41d57a253229e920d030b9a9ea587c5b06cb | [] | no_license | ANKerD/competitive-programming-constests | 41030bf6250a92cfa2a611127d73ff62c3808c19 | 4edb687b82228bac4e1b103ed4c0b94d466b6c10 | refs/heads/master | 2021-11-09T20:26:47.317274 | 2021-10-31T23:41:49 | 2021-10-31T23:41:49 | 133,289,164 | 0 | 1 | null | 2021-10-31T23:41:50 | 2018-05-14T01:24:28 | C++ | UTF-8 | C++ | false | false | 1,219 | cpp | #include <bits/stdc++.h>
using namespace std;
#define trace1(a) cout << a << '\n';
#define trace2(a, b) cout << a << ' ' << b << '\n';
#define trace3(a, b, c) cout << a << ' ' << b << ' ' << c << '\n';
#define trace4(a, b, c, d) cout << a << ' ' << b << ' ' << c << ' ' << d << '\n';
#define trace5(a, b, c, d, e) cout << a << ' ' << b << ' ' << c << ' ' << d << ' ' << e << '\n';
#define trace6(a, b, c, d, e, f) cout << a << ' ' << b << ' ' << c << ' ' << d << ' ' << e << ' ' << f << '\n';
#define printArr(harry, tam) range(tam) cout << harry[i] << " \n"[i == tam -1];
#define range(n) for(int i = 0; i < n; i++)
#define maxn 2000000
#define mod 1000000007
#define md(x) (x) % mod;
#define sc scanf
#define pr printf
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define ps push
#define prt(x) cout << (#x) << " is " << (x) << endl
#define EPS 1e-9
#define INF 1000000000
#define INFd 1e9
typedef long long ll;
typedef long double ld;
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
typedef vector<ll> vll;
typedef vector<double> vd;
int main(){
int n;
cin >> n;
n = n%4;
int x = 8;
n--;
while(n--){
x*=8;
x%=10;
}
trace1(x%10);
return 0;
}
| [
"a.kleber.d@gmail.com"
] | a.kleber.d@gmail.com |
6802b6b325a09b9bc0d003faf3b300177565a78f | 7a97496d628a6a6d89df847c43a0f0215fc0993f | /pynq_dsp_hw/pynq_dsp_hw.ip_user_files/mem_init_files/base_m10_regslice_9.h | 69f3e578779e3f16f3f6613fc8a868e39d1eacb2 | [
"MIT"
] | permissive | kamiyaowl/pynq_dsp_hw | 9336329bf952fcdfb6d35f2817c374ca4f91936d | cb3adee62d80ef8d70f9886ddfae8ff39441fe2d | refs/heads/master | 2020-12-23T04:19:22.080691 | 2020-02-09T07:52:02 | 2020-02-09T07:52:02 | 237,025,484 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,948 | h | #ifndef IP_BASE_M10_REGSLICE_9_H_
#define IP_BASE_M10_REGSLICE_9_H_
// (c) Copyright 1995-2020 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
// DO NOT MODIFY THIS FILE.
#ifndef XTLM
#include "xtlm.h"
#endif
#ifndef SYSTEMC_INCLUDED
#include <systemc>
#endif
#if defined(_MSC_VER)
#define DllExport __declspec(dllexport)
#elif defined(__GNUC__)
#define DllExport __attribute__ ((visibility("default")))
#else
#define DllExport
#endif
#include "base_m10_regslice_9_sc.h"
class DllExport base_m10_regslice_9 : public base_m10_regslice_9_sc
{
public:
base_m10_regslice_9(const sc_core::sc_module_name& nm);
virtual ~base_m10_regslice_9();
public: // module pin-to-pin RTL interface
sc_core::sc_in< bool > aclk;
sc_core::sc_in< bool > aresetn;
sc_core::sc_in< sc_dt::sc_bv<5> > s_axi_awaddr;
sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_awprot;
sc_core::sc_in< bool > s_axi_awvalid;
sc_core::sc_out< bool > s_axi_awready;
sc_core::sc_in< sc_dt::sc_bv<32> > s_axi_wdata;
sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_wstrb;
sc_core::sc_in< bool > s_axi_wvalid;
sc_core::sc_out< bool > s_axi_wready;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_bresp;
sc_core::sc_out< bool > s_axi_bvalid;
sc_core::sc_in< bool > s_axi_bready;
sc_core::sc_in< sc_dt::sc_bv<5> > s_axi_araddr;
sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_arprot;
sc_core::sc_in< bool > s_axi_arvalid;
sc_core::sc_out< bool > s_axi_arready;
sc_core::sc_out< sc_dt::sc_bv<32> > s_axi_rdata;
sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_rresp;
sc_core::sc_out< bool > s_axi_rvalid;
sc_core::sc_in< bool > s_axi_rready;
sc_core::sc_out< sc_dt::sc_bv<5> > m_axi_awaddr;
sc_core::sc_out< sc_dt::sc_bv<3> > m_axi_awprot;
sc_core::sc_out< bool > m_axi_awvalid;
sc_core::sc_in< bool > m_axi_awready;
sc_core::sc_out< sc_dt::sc_bv<32> > m_axi_wdata;
sc_core::sc_out< sc_dt::sc_bv<4> > m_axi_wstrb;
sc_core::sc_out< bool > m_axi_wvalid;
sc_core::sc_in< bool > m_axi_wready;
sc_core::sc_in< sc_dt::sc_bv<2> > m_axi_bresp;
sc_core::sc_in< bool > m_axi_bvalid;
sc_core::sc_out< bool > m_axi_bready;
sc_core::sc_out< sc_dt::sc_bv<5> > m_axi_araddr;
sc_core::sc_out< sc_dt::sc_bv<3> > m_axi_arprot;
sc_core::sc_out< bool > m_axi_arvalid;
sc_core::sc_in< bool > m_axi_arready;
sc_core::sc_in< sc_dt::sc_bv<32> > m_axi_rdata;
sc_core::sc_in< sc_dt::sc_bv<2> > m_axi_rresp;
sc_core::sc_in< bool > m_axi_rvalid;
sc_core::sc_out< bool > m_axi_rready;
protected:
virtual void before_end_of_elaboration();
private:
xtlm::xaximm_xtlm2pin_t<32,5,1,1,1,1,1,1>* mp_M_AXI_transactor;
sc_signal< bool > m_M_AXI_transactor_rst_signal;
xtlm::xaximm_pin2xtlm_t<32,5,1,1,1,1,1,1>* mp_S_AXI_transactor;
sc_signal< bool > m_S_AXI_transactor_rst_signal;
};
#endif // IP_BASE_M10_REGSLICE_9_H_
| [
"kamiyaowl@gmail.com"
] | kamiyaowl@gmail.com |
ad86c90b30f7ebe54f6820ba65dd5613fad36e8d | 39bcafc5f6b1672f31f0f6ea9c8d6047ee432950 | /extension/icu/third_party/icu/i18n/chnsecal.h | a0c21b6b5c2f86e951d0059df0442be345f2e1fb | [
"MIT",
"ICU",
"NAIST-2003",
"LicenseRef-scancode-unicode",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | duckdb/duckdb | 315270af6b198d26eb41a20fc7a0eda04aeef294 | f89ccfe0ec01eb613af9c8ac7c264a5ef86d7c3a | refs/heads/main | 2023-09-05T08:14:21.278345 | 2023-09-05T07:28:59 | 2023-09-05T07:28:59 | 138,754,790 | 8,964 | 986 | MIT | 2023-09-14T18:42:49 | 2018-06-26T15:04:45 | C++ | UTF-8 | C++ | false | false | 10,510 | h | // © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*****************************************************************************
* Copyright (C) 2007-2013, International Business Machines Corporation
* and others. All Rights Reserved.
*****************************************************************************
*
* File CHNSECAL.H
*
* Modification History:
*
* Date Name Description
* 9/18/2007 ajmacher ported from java ChineseCalendar
*****************************************************************************
*/
#ifndef CHNSECAL_H
#define CHNSECAL_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/calendar.h"
#include "unicode/timezone.h"
U_NAMESPACE_BEGIN
/**
* <code>ChineseCalendar</code> is a concrete subclass of {@link Calendar}
* that implements a traditional Chinese calendar. The traditional Chinese
* calendar is a lunisolar calendar: Each month starts on a new moon, and
* the months are numbered according to solar events, specifically, to
* guarantee that month 11 always contains the winter solstice. In order
* to accomplish this, leap months are inserted in certain years. Leap
* months are numbered the same as the month they follow. The decision of
* which month is a leap month depends on the relative movements of the sun
* and moon.
*
* <p>This class defines one addition field beyond those defined by
* <code>Calendar</code>: The <code>IS_LEAP_MONTH</code> field takes the
* value of 0 for normal months, or 1 for leap months.
*
* <p>All astronomical computations are performed with respect to a time
* zone of GMT+8:00 and a longitude of 120 degrees east. Although some
* calendars implement a historically more accurate convention of using
* Beijing's local longitude (116 degrees 25 minutes east) and time zone
* (GMT+7:45:40) for dates before 1929, we do not implement this here.
*
* <p>Years are counted in two different ways in the Chinese calendar. The
* first method is by sequential numbering from the 61st year of the reign
* of Huang Di, 2637 BCE, which is designated year 1 on the Chinese
* calendar. The second method uses 60-year cycles from the same starting
* point, which is designated year 1 of cycle 1. In this class, the
* <code>EXTENDED_YEAR</code> field contains the sequential year count.
* The <code>ERA</code> field contains the cycle number, and the
* <code>YEAR</code> field contains the year of the cycle, a value between
* 1 and 60.
*
* <p>There is some variation in what is considered the starting point of
* the calendar, with some sources starting in the first year of the reign
* of Huang Di, rather than the 61st. This gives continuous year numbers
* 60 years greater and cycle numbers one greater than what this class
* implements.
*
* <p>Because <code>ChineseCalendar</code> defines an additional field and
* redefines the way the <code>ERA</code> field is used, it requires a new
* format class, <code>ChineseDateFormat</code>. As always, use the
* methods <code>DateFormat.getXxxInstance(Calendar cal,...)</code> to
* obtain a formatter for this calendar.
*
* <p>References:<ul>
*
* <li>Dershowitz and Reingold, <i>Calendrical Calculations</i>,
* Cambridge University Press, 1997</li>
*
* <li>Helmer Aslaksen's
* <a href="http://www.math.nus.edu.sg/aslaksen/calendar/chinese.shtml">
* Chinese Calendar page</a></li>
*
* <li>The <a href="http://www.tondering.dk/claus/calendar.html">
* Calendar FAQ</a></li>
*
* </ul>
*
* <p>
* This class should only be subclassed to implement variants of the Chinese lunar calendar.</p>
* <p>
* ChineseCalendar usually should be instantiated using
* {@link com.ibm.icu.util.Calendar#getInstance(ULocale)} passing in a <code>ULocale</code>
* with the tag <code>"@calendar=chinese"</code>.</p>
*
* @see com.ibm.icu.text.ChineseDateFormat
* @see com.ibm.icu.util.Calendar
* @author Alan Liu
* @internal
*/
class U_I18N_API ChineseCalendar : public Calendar {
public:
//-------------------------------------------------------------------------
// Constructors...
//-------------------------------------------------------------------------
/**
* Constructs a ChineseCalendar based on the current time in the default time zone
* with the given locale.
*
* @param aLocale The given locale.
* @param success Indicates the status of ChineseCalendar object construction.
* Returns U_ZERO_ERROR if constructed successfully.
* @internal
*/
ChineseCalendar(const Locale& aLocale, UErrorCode &success);
protected:
/**
* Constructs a ChineseCalendar based on the current time in the default time zone
* with the given locale, using the specified epoch year and time zone for
* astronomical calculations.
*
* @param aLocale The given locale.
* @param epochYear The epoch year to use for calculation.
* @param zoneAstroCalc The TimeZone to use for astronomical calculations. If null,
* will be set appropriately for Chinese calendar (UTC + 8:00).
* @param success Indicates the status of ChineseCalendar object construction;
* if successful, will not be changed to an error value.
* @internal
*/
ChineseCalendar(const Locale& aLocale, int32_t epochYear, const TimeZone* zoneAstroCalc, UErrorCode &success);
public:
/**
* Copy Constructor
* @internal
*/
ChineseCalendar(const ChineseCalendar& other);
/**
* Destructor.
* @internal
*/
virtual ~ChineseCalendar();
// clone
virtual ChineseCalendar* clone() const;
private:
//-------------------------------------------------------------------------
// Internal data....
//-------------------------------------------------------------------------
UBool isLeapYear;
int32_t fEpochYear; // Start year of this Chinese calendar instance.
const TimeZone* fZoneAstroCalc; // Zone used for the astronomical calculation
// of this Chinese calendar instance.
//----------------------------------------------------------------------
// Calendar framework
//----------------------------------------------------------------------
protected:
virtual int32_t handleGetLimit(UCalendarDateFields field, ELimitType limitType) const;
virtual int32_t handleGetMonthLength(int32_t extendedYear, int32_t month) const;
virtual int32_t handleComputeMonthStart(int32_t eyear, int32_t month, UBool useMonth) const;
virtual int32_t handleGetExtendedYear();
virtual void handleComputeFields(int32_t julianDay, UErrorCode &status);
virtual const UFieldResolutionTable* getFieldResolutionTable() const;
public:
virtual void add(UCalendarDateFields field, int32_t amount, UErrorCode &status);
virtual void add(EDateFields field, int32_t amount, UErrorCode &status);
virtual void roll(UCalendarDateFields field, int32_t amount, UErrorCode &status);
virtual void roll(EDateFields field, int32_t amount, UErrorCode &status);
//----------------------------------------------------------------------
// Internal methods & astronomical calculations
//----------------------------------------------------------------------
private:
static const UFieldResolutionTable CHINESE_DATE_PRECEDENCE[];
double daysToMillis(double days) const;
double millisToDays(double millis) const;
virtual int32_t winterSolstice(int32_t gyear) const;
virtual int32_t newMoonNear(double days, UBool after) const;
virtual int32_t synodicMonthsBetween(int32_t day1, int32_t day2) const;
virtual int32_t majorSolarTerm(int32_t days) const;
virtual UBool hasNoMajorSolarTerm(int32_t newMoon) const;
virtual UBool isLeapMonthBetween(int32_t newMoon1, int32_t newMoon2) const;
virtual void computeChineseFields(int32_t days, int32_t gyear,
int32_t gmonth, UBool setAllFields);
virtual int32_t newYear(int32_t gyear) const;
virtual void offsetMonth(int32_t newMoon, int32_t dom, int32_t delta);
const TimeZone* getChineseCalZoneAstroCalc(void) const;
// UObject stuff
public:
/**
* @return The class ID for this object. All objects of a given class have the
* same class ID. Objects of other classes have different class IDs.
* @internal
*/
virtual UClassID getDynamicClassID(void) const;
/**
* Return the class ID for this class. This is useful only for comparing to a return
* value from getDynamicClassID(). For example:
*
* Base* polymorphic_pointer = createPolymorphicObject();
* if (polymorphic_pointer->getDynamicClassID() ==
* Derived::getStaticClassID()) ...
*
* @return The class ID for all objects of this class.
* @internal
*/
static UClassID U_EXPORT2 getStaticClassID(void);
/**
* return the calendar type, "chinese".
*
* @return calendar type
* @internal
*/
virtual const char * getType() const;
protected:
/**
* (Overrides Calendar) Return true if the current date for this Calendar is in
* Daylight Savings Time. Recognizes DST_OFFSET, if it is set.
*
* @param status Fill-in parameter which receives the status of this operation.
* @return True if the current date for this Calendar is in Daylight Savings Time,
* false, otherwise.
* @internal
*/
virtual UBool inDaylightTime(UErrorCode& status) const;
/**
* Returns TRUE because the Islamic Calendar does have a default century
* @internal
*/
virtual UBool haveDefaultCentury() const;
/**
* Returns the date of the start of the default century
* @return start of century - in milliseconds since epoch, 1970
* @internal
*/
virtual UDate defaultCenturyStart() const;
/**
* Returns the year in which the default century begins
* @internal
*/
virtual int32_t defaultCenturyStartYear() const;
private: // default century stuff.
/**
* Returns the beginning date of the 100-year window that dates
* with 2-digit years are considered to fall within.
*/
UDate internalGetDefaultCenturyStart(void) const;
/**
* Returns the first year of the 100-year window that dates with
* 2-digit years are considered to fall within.
*/
int32_t internalGetDefaultCenturyStartYear(void) const;
ChineseCalendar(); // default constructor not implemented
};
U_NAMESPACE_END
#endif
#endif
| [
"mark.raasveldt@gmail.com"
] | mark.raasveldt@gmail.com |
6e8d76ebf3589a09ffaa59bc3e3a1d77cacde164 | a849b845b482ca0dc1ad41a43cee31878a407c7f | /Billing_tools/Billing_sdk/common/BscpSocket.h | 017997de0dae52b1719fa9f41ad85928cef9ebf1 | [] | no_license | shaodaWang/test_20200628 | 106c3f4224ca6715ce374c540a7918747be125d1 | 32ecc8b762d792d26df914c107c38df2687dd7d2 | refs/heads/master | 2022-11-12T22:08:08.646333 | 2020-07-01T07:04:36 | 2020-07-01T07:04:36 | 275,546,863 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,973 | h | /** $Id$ $DateTime$
* @file BscpSocket.h
* @brief BSCP模块,调用加密与网络连接两个子模块。接收上层任意数据,向Dvr发送,并接收Dvr回应数据。
* @version 0.0.1
* @since 0.0.1
*/
#pragma once
#include "Encrypt.h"
#include "StreamSocket.h"
#include "Lock.h"
// #include "AudioFifo.h"
#include "bsrLog.h"
#include "../BillSdkType.h"
// 日志
#define BSCPLOG(x) BSRLOG(x)
/** @defgroup grBSCP BSCP模块(BSCP Mod)
* @ingroup grSpeech
* @{
*/
/** @}*/ // end of BSCP模块所需结构定义
/** @class BscpSocket
* @brief BSCP模块的主类
*/
class BscpSocket
{
public:
BscpSocket();
~BscpSocket();
public:
int init(unsigned int ipAddr, unsigned short port, char gametype=0, bool bHeart=true, unsigned int timeOut=10000 );
// int init( SOCKET sDvr );
void destory();
void setNotifyWnd( HWND hNotifyWnd, int nMsgId );
int setNotifyCallback( int (*pfNotifyRoutine)( HANDLE hDvr, unsigned int notifyId, LPVOID lpUserData ), LPVOID lpUserData );
void setVersion( unsigned char version );
unsigned char getVersion();
int HelloORheart(int cmd);
int Execute( int cmd, void* pArg, unsigned int argSize, void* pResult, unsigned int resSize, int timeout = 10000);
bool IsOk();
unsigned int GetCurIpAddr(){return m_ipAddr;}
unsigned int GetCurPort(){return m_nPort;}
//无需登录
int initNoHeartBeat(unsigned int ipAddr, unsigned short port,unsigned int timeOut=10000);
int GetChInfoNotLogin(unsigned int nCmd, const void* parmIn, unsigned int nLenthIn,
void* parmOut, unsigned int nLenthOut, unsigned int timeOut);
protected:
int ConnectDvr( unsigned int msTimeOut = 10000 );
public: // 供心跳线程使用的回调函数
void heartBeat();
void SetDvrHandle( DvxHandle pDvr);
protected:
bool m_bExit;
HANDLE m_hEvent;
HANDLE m_hBeatHeart; /**< 心跳线程句柄 */
HWND m_hNotifyWnd;
int m_nMsgId;
DvxHandle m_hDvx;
protected:
char* m_sendBuf; /**< 发送数据缓冲区 */
char* m_recvBuf; /**< 接收数据缓冲区 */
unsigned int m_sequence;
unsigned char m_version;
protected:
unsigned int m_ipAddr; /**< Dvr的Ip地址 */
int m_nPort; /**< Dvr的端口号 */
bool m_bReg; /**< true: 主动注册,false非主动注册 */
protected:
Encrypt m_objEncrypt; /**< 加密子模块 */
StreamSocket m_streamSocket; /**< 网络连接子模块 */
Lock m_lock; /**< 互斥锁,因为BSCP模块要同时被很多模块使用,所以一定要加锁 */
bool m_bHasFailed;
bool m_bIsOk;
unsigned char m_nGameType;
protected: // 只有在主动注册时才会用到
// Lock m_lckFifo;
// AudioFifo* m_fifo;
//增加断网回调
int (*m_pfNotifyRoutine)( HANDLE hDvr, unsigned int notifyId, LPVOID lpUserData );
LPVOID m_pNotifyUserData;
protected: // Log
BSCPLOG( LogHandle m_hBscpLog; );
};
/** @}*/ // end of BSCP
| [
"langzizhuyue@163.com"
] | langzizhuyue@163.com |
a34673beac11a3733ecfed464f4fe26e42daa275 | eb8a75fbb3cc22dc2fb297096ccbad872a9512fc | /src/rpcmasternode.cpp | f3505b0dbfcf2b1212bd4b24ce6564a130f68d83 | [
"MIT"
] | permissive | admecoin/CTTCoin | 29848f810eea5aa1c6094563939a91f733d05150 | b1a2f9e6d8ffee7749636030f3b223859d731c86 | refs/heads/master | 2020-04-25T12:55:26.033094 | 2019-10-29T18:13:43 | 2019-10-29T18:13:43 | 172,792,780 | 0 | 0 | MIT | 2019-02-26T21:23:30 | 2019-02-26T21:23:29 | null | UTF-8 | C++ | false | false | 25,134 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2017-2018 The CryptoInvest developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "activemasternode.h"
#include "db.h"
#include "init.h"
#include "main.h"
#include "masternode-budget.h"
#include "masternode-payments.h"
#include "masternodeconfig.h"
#include "masternodeman.h"
#include "rpcserver.h"
#include "utilmoneystr.h"
#include <fstream>
using namespace json_spirit;
void SendMoney(const CTxDestination& address, CAmount nValue, CWalletTx& wtxNew, AvailableCoinsType coin_type = ALL_COINS)
{
// Check amount
if (nValue <= 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount");
if (nValue > pwalletMain->GetBalance())
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
string strError;
if (pwalletMain->IsLocked()) {
strError = "Error: Wallet locked, unable to create transaction!";
LogPrintf("SendMoney() : %s", strError);
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
// Parse CryptoInvest address
CScript scriptPubKey = GetScriptForDestination(address);
// Create and send the transaction
CReserveKey reservekey(pwalletMain);
CAmount nFeeRequired;
if (!pwalletMain->CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired, strError, NULL, coin_type)) {
if (nValue + nFeeRequired > pwalletMain->GetBalance())
strError = strprintf("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!", FormatMoney(nFeeRequired));
LogPrintf("SendMoney() : %s\n", strError);
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
if (!pwalletMain->CommitTransaction(wtxNew, reservekey))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
}
Value obfuscation(const Array& params, bool fHelp)
{
if (fHelp || params.size() == 0)
throw runtime_error(
"obfuscation <cryptoinvestaddress> <amount>\n"
"cryptoinvestaddress, reset, or auto (AutoDenominate)"
"<amount> is a real and will be rounded to the next 0.1" +
HelpRequiringPassphrase());
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
if (params[0].get_str() == "auto") {
if (fMasterNode)
return "ObfuScation is not supported from masternodes";
return "DoAutomaticDenominating " + (obfuScationPool.DoAutomaticDenominating() ? "successful" : ("failed: " + obfuScationPool.GetStatus()));
}
if (params[0].get_str() == "reset") {
obfuScationPool.Reset();
return "successfully reset obfuscation";
}
if (params.size() != 2)
throw runtime_error(
"obfuscation <cryptoinvestaddress> <amount>\n"
"cryptoinvestaddress, denominate, or auto (AutoDenominate)"
"<amount> is a real and will be rounded to the next 0.1" +
HelpRequiringPassphrase());
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CryptoInvest address");
// Amount
CAmount nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
// string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx, ONLY_DENOMINATED);
SendMoney(address.Get(), nAmount, wtx, ONLY_DENOMINATED);
// if (strError != "")
// throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value getpoolinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getpoolinfo\n"
"Returns an object containing anonymous pool-related information.");
Object obj;
obj.push_back(Pair("current_masternode", mnodeman.GetCurrentMasterNode()->addr.ToString()));
obj.push_back(Pair("state", obfuScationPool.GetState()));
obj.push_back(Pair("entries", obfuScationPool.GetEntriesCount()));
obj.push_back(Pair("entries_accepted", obfuScationPool.GetCountEntriesAccepted()));
return obj;
}
Value masternode(const Array& params, bool fHelp)
{
string strCommand;
if (params.size() >= 1)
strCommand = params[0].get_str();
if (fHelp ||
(strCommand != "start" && strCommand != "start-alias" && strCommand != "start-many" && strCommand != "start-all" && strCommand != "start-missing" &&
strCommand != "start-disabled" && strCommand != "list" && strCommand != "list-conf" && strCommand != "count" && strCommand != "enforce" &&
strCommand != "debug" && strCommand != "current" && strCommand != "winners" && strCommand != "genkey" && strCommand != "connect" &&
strCommand != "outputs" && strCommand != "status" && strCommand != "calcscore"))
throw runtime_error(
"masternode \"command\"... ( \"passphrase\" )\n"
"Set of commands to execute masternode related actions\n"
"\nArguments:\n"
"1. \"command\" (string or set of strings, required) The command to execute\n"
"2. \"passphrase\" (string, optional) The wallet passphrase\n"
"\nAvailable commands:\n"
" count - Print number of all known masternodes (optional: 'obf', 'enabled', 'all', 'qualify')\n"
" current - Print info on current masternode winner\n"
" debug - Print masternode status\n"
" genkey - Generate new masternodeprivkey\n"
" enforce - Enforce masternode payments\n"
" outputs - Print masternode compatible outputs\n"
" start - Start masternode configured in cryptoinvest.conf\n"
" start-alias - Start single masternode by assigned alias configured in masternode.conf\n"
" start-<mode> - Start masternodes configured in masternode.conf (<mode>: 'all', 'missing', 'disabled')\n"
" status - Print masternode status information\n"
" list - Print list of all known masternodes (see masternodelist for more info)\n"
" list-conf - Print masternode.conf in JSON format\n"
" winners - Print list of masternode winners\n");
if (strCommand == "list") {
Array newParams(params.size() - 1);
std::copy(params.begin() + 1, params.end(), newParams.begin());
return masternodelist(newParams, fHelp);
}
if (strCommand == "budget") {
return "Show budgets";
}
if (strCommand == "connect") {
std::string strAddress = "";
if (params.size() == 2) {
strAddress = params[1].get_str();
} else {
throw runtime_error("Masternode address required\n");
}
CService addr = CService(strAddress);
CNode* pnode = ConnectNode((CAddress)addr, NULL, false);
if (pnode) {
pnode->Release();
return "successfully connected";
} else {
throw runtime_error("error connecting\n");
}
}
if (strCommand == "count") {
if (params.size() > 2) {
throw runtime_error("too many parameters\n");
}
if (params.size() == 2) {
int nCount = 0;
if (chainActive.Tip())
mnodeman.GetNextMasternodeInQueueForPayment(chainActive.Tip()->nHeight, true, nCount);
if (params[1] == "obf") return mnodeman.CountEnabled(ActiveProtocol());
if (params[1] == "enabled") return mnodeman.CountEnabled();
if (params[1] == "qualify") return nCount;
if (params[1] == "all") return strprintf("Total: %d (OBF Compatible: %d / Enabled: %d / Qualify: %d)",
mnodeman.size(),
mnodeman.CountEnabled(ActiveProtocol()),
mnodeman.CountEnabled(),
nCount);
}
return mnodeman.size();
}
if (strCommand == "current") {
CMasternode* winner = mnodeman.GetCurrentMasterNode(1);
if (winner) {
Object obj;
obj.push_back(Pair("IP:port", winner->addr.ToString()));
obj.push_back(Pair("protocol", (int64_t)winner->protocolVersion));
obj.push_back(Pair("vin", winner->vin.prevout.hash.ToString()));
obj.push_back(Pair("pubkey", CBitcoinAddress(winner->pubKeyCollateralAddress.GetID()).ToString()));
obj.push_back(Pair("lastseen", (winner->lastPing == CMasternodePing()) ? winner->sigTime : (int64_t)winner->lastPing.sigTime));
obj.push_back(Pair("activeseconds", (winner->lastPing == CMasternodePing()) ? 0 : (int64_t)(winner->lastPing.sigTime - winner->sigTime)));
return obj;
}
return "unknown";
}
if (strCommand == "debug") {
if (activeMasternode.status != ACTIVE_MASTERNODE_INITIAL || !masternodeSync.IsSynced())
return activeMasternode.GetStatus();
CTxIn vin = CTxIn();
CPubKey pubkey = CScript();
CKey key;
bool found = activeMasternode.GetMasterNodeVin(vin, pubkey, key);
if (!found) {
throw runtime_error("Missing masternode input, please look at the documentation for instructions on masternode creation\n");
} else {
return activeMasternode.GetStatus();
}
}
if (strCommand == "enforce") {
return (uint64_t)enforceMasternodePaymentsTime;
}
if (strCommand == "start") {
if (!fMasterNode) throw runtime_error("you must set masternode=1 in the configuration\n");
if (pwalletMain->IsLocked()) {
SecureString strWalletPass;
strWalletPass.reserve(100);
if (params.size() == 2) {
strWalletPass = params[1].get_str().c_str();
} else {
throw runtime_error("Your wallet is locked, passphrase is required\n");
}
if (!pwalletMain->Unlock(strWalletPass)) {
throw runtime_error("incorrect passphrase\n");
}
}
if (activeMasternode.status != ACTIVE_MASTERNODE_STARTED) {
activeMasternode.status = ACTIVE_MASTERNODE_INITIAL; // TODO: consider better way
activeMasternode.ManageStatus();
pwalletMain->Lock();
}
return activeMasternode.GetStatus();
}
if (strCommand == "start-alias") {
if (params.size() < 2) {
throw runtime_error("command needs at least 2 parameters\n");
}
std::string alias = params[1].get_str();
if (pwalletMain->IsLocked()) {
SecureString strWalletPass;
strWalletPass.reserve(100);
if (params.size() == 3) {
strWalletPass = params[2].get_str().c_str();
} else {
throw runtime_error("Your wallet is locked, passphrase is required\n");
}
if (!pwalletMain->Unlock(strWalletPass)) {
throw runtime_error("incorrect passphrase\n");
}
}
bool found = false;
Object statusObj;
statusObj.push_back(Pair("alias", alias));
BOOST_FOREACH (CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) {
if (mne.getAlias() == alias) {
found = true;
std::string errorMessage;
bool result = activeMasternode.Register(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), errorMessage);
statusObj.push_back(Pair("result", result ? "successful" : "failed"));
if (!result) {
statusObj.push_back(Pair("errorMessage", errorMessage));
}
break;
}
}
if (!found) {
statusObj.push_back(Pair("result", "failed"));
statusObj.push_back(Pair("errorMessage", "could not find alias in config. Verify with list-conf."));
}
pwalletMain->Lock();
return statusObj;
}
if (strCommand == "start-many" || strCommand == "start-all" || strCommand == "start-missing" || strCommand == "start-disabled") {
if (pwalletMain->IsLocked()) {
SecureString strWalletPass;
strWalletPass.reserve(100);
if (params.size() == 2) {
strWalletPass = params[1].get_str().c_str();
} else {
throw runtime_error("Your wallet is locked, passphrase is required\n");
}
if (!pwalletMain->Unlock(strWalletPass)) {
throw runtime_error("incorrect passphrase\n");
}
}
if ((strCommand == "start-missing" || strCommand == "start-disabled") &&
(masternodeSync.RequestedMasternodeAssets <= MASTERNODE_SYNC_LIST ||
masternodeSync.RequestedMasternodeAssets == MASTERNODE_SYNC_FAILED)) {
throw runtime_error("You can't use this command until masternode list is synced\n");
}
std::vector<CMasternodeConfig::CMasternodeEntry> mnEntries;
mnEntries = masternodeConfig.getEntries();
int successful = 0;
int failed = 0;
Object resultsObj;
BOOST_FOREACH (CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) {
std::string errorMessage;
int nIndex;
if(!mne.castOutputIndex(nIndex))
continue;
CTxIn vin = CTxIn(uint256(mne.getTxHash()), uint32_t(nIndex));
CMasternode* pmn = mnodeman.Find(vin);
if (strCommand == "start-missing" && pmn) continue;
if (strCommand == "start-disabled" && pmn && pmn->IsEnabled()) continue;
bool result = activeMasternode.Register(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), errorMessage);
Object statusObj;
statusObj.push_back(Pair("alias", mne.getAlias()));
statusObj.push_back(Pair("result", result ? "successful" : "failed"));
if (result) {
successful++;
} else {
failed++;
statusObj.push_back(Pair("errorMessage", errorMessage));
}
resultsObj.push_back(Pair("status", statusObj));
}
pwalletMain->Lock();
Object returnObj;
returnObj.push_back(Pair("overall", strprintf("Successfully started %d masternodes, failed to start %d, total %d", successful, failed, successful + failed)));
returnObj.push_back(Pair("detail", resultsObj));
return returnObj;
}
if (strCommand == "create") {
throw runtime_error("Not implemented yet, please look at the documentation for instructions on masternode creation\n");
}
if (strCommand == "genkey") {
CKey secret;
secret.MakeNewKey(false);
return CBitcoinSecret(secret).ToString();
}
if (strCommand == "list-conf") {
std::vector<CMasternodeConfig::CMasternodeEntry> mnEntries;
mnEntries = masternodeConfig.getEntries();
Object resultObj;
BOOST_FOREACH (CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) {
int nIndex;
if(!mne.castOutputIndex(nIndex))
continue;
CTxIn vin = CTxIn(uint256(mne.getTxHash()), uint32_t(nIndex));
CMasternode* pmn = mnodeman.Find(vin);
std::string strStatus = pmn ? pmn->Status() : "MISSING";
Object mnObj;
mnObj.push_back(Pair("alias", mne.getAlias()));
mnObj.push_back(Pair("address", mne.getIp()));
mnObj.push_back(Pair("privateKey", mne.getPrivKey()));
mnObj.push_back(Pair("txHash", mne.getTxHash()));
mnObj.push_back(Pair("outputIndex", mne.getOutputIndex()));
mnObj.push_back(Pair("status", strStatus));
resultObj.push_back(Pair("masternode", mnObj));
}
return resultObj;
}
if (strCommand == "outputs") {
// Find possible candidates
vector<COutput> possibleCoins = activeMasternode.SelectCoinsMasternode();
Object obj;
BOOST_FOREACH (COutput& out, possibleCoins) {
obj.push_back(Pair(out.tx->GetHash().ToString(), strprintf("%d", out.i)));
}
return obj;
}
if (strCommand == "status") {
if (!fMasterNode) throw runtime_error("This is not a masternode\n");
Object mnObj;
CMasternode* pmn = mnodeman.Find(activeMasternode.vin);
mnObj.push_back(Pair("vin", activeMasternode.vin.ToString()));
mnObj.push_back(Pair("service", activeMasternode.service.ToString()));
if (pmn) mnObj.push_back(Pair("pubkey", CBitcoinAddress(pmn->pubKeyCollateralAddress.GetID()).ToString()));
mnObj.push_back(Pair("status", activeMasternode.GetStatus()));
return mnObj;
}
if (strCommand == "winners") {
int nLast = 10;
if (params.size() >= 2) {
try {
nLast = std::stoi(params[1].get_str());
} catch (const std::exception& e) {
throw runtime_error("Exception on param 2");
}
}
Object obj;
for (int nHeight = chainActive.Tip()->nHeight - nLast; nHeight < chainActive.Tip()->nHeight + 20; nHeight++) {
obj.push_back(Pair(strprintf("%d", nHeight), GetRequiredPaymentsString(nHeight)));
}
return obj;
}
/*
Shows which masternode wins by score each block
*/
if (strCommand == "calcscore") {
int nLast = 10;
if (params.size() >= 2) {
try {
nLast = std::stoi(params[1].get_str());
} catch (const boost::bad_lexical_cast &) {
throw runtime_error("Exception on param 2");
}
}
Object obj;
std::vector<CMasternode> vMasternodes = mnodeman.GetFullMasternodeVector();
for (int nHeight = chainActive.Tip()->nHeight - nLast; nHeight < chainActive.Tip()->nHeight + 20; nHeight++) {
uint256 nHigh = 0;
CMasternode* pBestMasternode = NULL;
BOOST_FOREACH (CMasternode& mn, vMasternodes) {
uint256 n = mn.CalculateScore(1, nHeight - 100);
if (n > nHigh) {
nHigh = n;
pBestMasternode = &mn;
}
}
if (pBestMasternode)
obj.push_back(Pair(strprintf("%d", nHeight), pBestMasternode->vin.prevout.ToStringShort().c_str()));
}
return obj;
}
return Value::null;
}
Value masternodelist(const Array& params, bool fHelp)
{
std::string strMode = "status";
std::string strFilter = "";
if (params.size() >= 1) strMode = params[0].get_str();
if (params.size() == 2) strFilter = params[1].get_str();
if (fHelp ||
(strMode != "status" && strMode != "vin" && strMode != "pubkey" && strMode != "lastseen" && strMode != "activeseconds" && strMode != "rank" && strMode != "addr" && strMode != "protocol" && strMode != "full" && strMode != "lastpaid")) {
throw runtime_error(
"masternodelist ( \"mode\" \"filter\" )\n"
"Get a list of masternodes in different modes\n"
"\nArguments:\n"
"1. \"mode\" (string, optional/required to use filter, defaults = status) The mode to run list in\n"
"2. \"filter\" (string, optional) Filter results. Partial match by IP by default in all modes,\n"
" additional matches in some modes are also available\n"
"\nAvailable modes:\n"
" activeseconds - Print number of seconds masternode recognized by the network as enabled\n"
" (since latest issued \"masternode start/start-many/start-alias\")\n"
" addr - Print ip address associated with a masternode (can be additionally filtered, partial match)\n"
" full - Print info in format 'status protocol pubkey IP lastseen activeseconds lastpaid'\n"
" (can be additionally filtered, partial match)\n"
" lastseen - Print timestamp of when a masternode was last seen on the network\n"
" lastpaid - The last time a node was paid on the network\n"
" protocol - Print protocol of a masternode (can be additionally filtered, exact match))\n"
" pubkey - Print public key associated with a masternode (can be additionally filtered,\n"
" partial match)\n"
" rank - Print rank of a masternode based on current block\n"
" status - Print masternode status: ENABLED / EXPIRED / VIN_SPENT / REMOVE / POS_ERROR\n"
" (can be additionally filtered, partial match)\n");
}
Object obj;
if (strMode == "rank") {
std::vector<pair<int, CMasternode> > vMasternodeRanks = mnodeman.GetMasternodeRanks(chainActive.Tip()->nHeight);
BOOST_FOREACH (PAIRTYPE(int, CMasternode) & s, vMasternodeRanks) {
std::string strVin = s.second.vin.prevout.ToStringShort();
if (strFilter != "" && strVin.find(strFilter) == string::npos) continue;
obj.push_back(Pair(strVin, s.first));
}
} else {
std::vector<CMasternode> vMasternodes = mnodeman.GetFullMasternodeVector();
BOOST_FOREACH (CMasternode& mn, vMasternodes) {
std::string strVin = mn.vin.prevout.ToStringShort();
if (strMode == "activeseconds") {
if (strFilter != "" && strVin.find(strFilter) == string::npos) continue;
obj.push_back(Pair(strVin, (int64_t)(mn.lastPing.sigTime - mn.sigTime)));
} else if (strMode == "addr") {
if (strFilter != "" && mn.vin.prevout.hash.ToString().find(strFilter) == string::npos &&
strVin.find(strFilter) == string::npos) continue;
obj.push_back(Pair(strVin, mn.addr.ToString()));
} else if (strMode == "full") {
std::ostringstream addrStream;
addrStream << setw(21) << strVin;
std::ostringstream stringStream;
stringStream << setw(9) << mn.Status() << " " << mn.protocolVersion << " " << CBitcoinAddress(mn.pubKeyCollateralAddress.GetID()).ToString() << " " << setw(21) << mn.addr.ToString() << " " << (int64_t)mn.lastPing.sigTime << " " << setw(8) << (int64_t)(mn.lastPing.sigTime - mn.sigTime) << " " << (int64_t)mn.GetLastPaid();
std::string output = stringStream.str();
stringStream << " " << strVin;
if (strFilter != "" && stringStream.str().find(strFilter) == string::npos &&
strVin.find(strFilter) == string::npos) continue;
obj.push_back(Pair(addrStream.str(), output));
} else if (strMode == "lastseen") {
if (strFilter != "" && strVin.find(strFilter) == string::npos) continue;
obj.push_back(Pair(strVin, (int64_t)mn.lastPing.sigTime));
} else if (strMode == "lastpaid") {
if (strFilter != "" && mn.vin.prevout.hash.ToString().find(strFilter) == string::npos &&
strVin.find(strFilter) == string::npos) continue;
obj.push_back(Pair(strVin, (int64_t)mn.GetLastPaid()));
} else if (strMode == "protocol") {
if (strFilter != "" && strFilter != strprintf("%d", mn.protocolVersion) &&
strVin.find(strFilter) == string::npos) continue;
obj.push_back(Pair(strVin, (int64_t)mn.protocolVersion));
} else if (strMode == "pubkey") {
CBitcoinAddress address(mn.pubKeyCollateralAddress.GetID());
if (strFilter != "" && address.ToString().find(strFilter) == string::npos &&
strVin.find(strFilter) == string::npos) continue;
obj.push_back(Pair(strVin, address.ToString()));
} else if (strMode == "status") {
std::string strStatus = mn.Status();
if (strFilter != "" && strVin.find(strFilter) == string::npos && strStatus.find(strFilter) == string::npos) continue;
obj.push_back(Pair(strVin, strStatus));
}
}
}
return obj;
}
| [
"46240091+CTTDeveloperTeam@users.noreply.github.com"
] | 46240091+CTTDeveloperTeam@users.noreply.github.com |
bc9cdb001bf9e33cc63423fae59bb97f6c02f233 | 3dfceb181f9cf5bb29c671cc2f417ce877805390 | /m2srccf/Metin2Client/UserInterface/PythonMessenger.cpp | 578f987e7f6b5c8747eb64eb8c20bccb08992052 | [] | no_license | Sophie-Williams/M2-Project | 74e1ce9e80a137b59b54dc8f42f192fb8293b6e9 | b07c37b6c24b46040b21693402e4b1606ad67b48 | refs/heads/master | 2022-11-23T05:16:37.706348 | 2020-08-02T21:52:07 | 2020-08-02T21:52:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,458 | cpp | #include "stdafx.h"
#include "PythonMessenger.h"
void CPythonMessenger::RemoveFriend(const char * c_szKey)
{
m_FriendNameMap.erase(c_szKey);
}
void CPythonMessenger::OnFriendLogin(const char * c_szKey/*, const char * c_szName*/)
{
m_FriendNameMap.insert(c_szKey);
if (m_poMessengerHandler)
PyCallClassMemberFunc(m_poMessengerHandler, "OnLogin", Py_BuildValue("(is)", MESSENGER_GRUOP_INDEX_FRIEND, c_szKey));
}
void CPythonMessenger::OnFriendLogout(const char * c_szKey)
{
m_FriendNameMap.insert(c_szKey);
if (m_poMessengerHandler)
PyCallClassMemberFunc(m_poMessengerHandler, "OnLogout", Py_BuildValue("(is)", MESSENGER_GRUOP_INDEX_FRIEND, c_szKey));
}
void CPythonMessenger::SetMobile(const char * c_szKey, BYTE byState)
{
m_FriendNameMap.insert(c_szKey);
if (m_poMessengerHandler)
PyCallClassMemberFunc(m_poMessengerHandler, "OnMobile", Py_BuildValue("(isi)", MESSENGER_GRUOP_INDEX_FRIEND, c_szKey, byState));
}
BOOL CPythonMessenger::IsFriendByKey(const char * c_szKey)
{
return m_FriendNameMap.end() != m_FriendNameMap.find(c_szKey);
}
BOOL CPythonMessenger::IsFriendByName(const char * c_szName)
{
return IsFriendByKey(c_szName);
}
void CPythonMessenger::AppendGuildMember(const char * c_szName)
{
if (m_GuildMemberStateMap.end() != m_GuildMemberStateMap.find(c_szName))
return;
LogoutGuildMember(c_szName);
}
void CPythonMessenger::RemoveGuildMember(const char * c_szName)
{
m_GuildMemberStateMap.erase(c_szName);
if (m_poMessengerHandler)
PyCallClassMemberFunc(m_poMessengerHandler, "OnRemoveList", Py_BuildValue("(is)", MESSENGER_GRUOP_INDEX_GUILD, c_szName));
}
void CPythonMessenger::RemoveAllGuildMember()
{
m_GuildMemberStateMap.clear();
if (m_poMessengerHandler)
PyCallClassMemberFunc(m_poMessengerHandler, "OnRemoveAllList", Py_BuildValue("(i)", MESSENGER_GRUOP_INDEX_GUILD));
}
void CPythonMessenger::LoginGuildMember(const char * c_szName)
{
m_GuildMemberStateMap[c_szName] = 1;
if (m_poMessengerHandler)
PyCallClassMemberFunc(m_poMessengerHandler, "OnLogin", Py_BuildValue("(is)", MESSENGER_GRUOP_INDEX_GUILD, c_szName));
}
void CPythonMessenger::LogoutGuildMember(const char * c_szName)
{
m_GuildMemberStateMap[c_szName] = 0;
if (m_poMessengerHandler)
PyCallClassMemberFunc(m_poMessengerHandler, "OnLogout", Py_BuildValue("(is)", MESSENGER_GRUOP_INDEX_GUILD, c_szName));
}
void CPythonMessenger::RefreshGuildMember()
{
for (TGuildMemberStateMap::iterator itor = m_GuildMemberStateMap.begin(); itor != m_GuildMemberStateMap.end(); ++itor)
{
if (itor->second)
PyCallClassMemberFunc(m_poMessengerHandler, "OnLogin", Py_BuildValue("(is)", MESSENGER_GRUOP_INDEX_GUILD, (itor->first).c_str()));
else
PyCallClassMemberFunc(m_poMessengerHandler, "OnLogout", Py_BuildValue("(is)", MESSENGER_GRUOP_INDEX_GUILD, (itor->first).c_str()));
}
}
void CPythonMessenger::Destroy()
{
m_FriendNameMap.clear();
m_GuildMemberStateMap.clear();
}
void CPythonMessenger::SetMessengerHandler(PyObject* poHandler)
{
m_poMessengerHandler = poHandler;
}
const CPythonMessenger::TFriendNameMap CPythonMessenger::GetFriendNames()
{
return m_FriendNameMap;
}
CPythonMessenger::CPythonMessenger()
: m_poMessengerHandler(NULL)
{
}
CPythonMessenger::~CPythonMessenger()
{
}
///////////////////////////////////////////////////////////////////////////////////////////////////
PyObject * messengerRemoveFriend(PyObject* poSelf, PyObject* poArgs)
{
char * szKey;
if (!PyTuple_GetString(poArgs, 0, &szKey))
return Py_BuildException();
CPythonMessenger::Instance().RemoveFriend(szKey);
return Py_BuildNone();
}
PyObject * messengerIsFriendByName(PyObject* poSelf, PyObject* poArgs)
{
char * szName;
if (!PyTuple_GetString(poArgs, 0, &szName))
return Py_BuildException();
return Py_BuildValue("i", CPythonMessenger::Instance().IsFriendByName(szName));
}
PyObject * messengerDestroy(PyObject* poSelf, PyObject* poArgs)
{
CPythonMessenger::Instance().Destroy();
return Py_BuildNone();
}
PyObject * messengerRefreshGuildMember(PyObject* poSelf, PyObject* poArgs)
{
CPythonMessenger::Instance().RefreshGuildMember();
return Py_BuildNone();
}
PyObject* messengerGetFriendNames(PyObject* poSelf, PyObject* poArgs)
{
const CPythonMessenger::TFriendNameMap friendNameMap = CPythonMessenger::Instance().GetFriendNames();
PyObject * pyTupleFriendNames = PyTuple_New(friendNameMap.size());
int iPos = 0;
for (CPythonMessenger::TFriendNameMap::const_iterator itor = friendNameMap.begin(); itor != friendNameMap.end(); ++itor, ++iPos)
PyTuple_SetItem(pyTupleFriendNames, iPos, Py_BuildValue("s", (*itor).c_str()));
return pyTupleFriendNames;
}
PyObject * messengerSetMessengerHandler(PyObject* poSelf, PyObject* poArgs)
{
PyObject * poEventHandler;
if (!PyTuple_GetObject(poArgs, 0, &poEventHandler))
return Py_BuildException();
CPythonMessenger::Instance().SetMessengerHandler(poEventHandler);
return Py_BuildNone();
}
void initMessenger()
{
static PyMethodDef s_methods[] =
{
{ "RemoveFriend", messengerRemoveFriend, METH_VARARGS },
{ "GetFriendNames", messengerGetFriendNames, METH_VARARGS },
{ "IsFriendByName", messengerIsFriendByName, METH_VARARGS },
{ "Destroy", messengerDestroy, METH_VARARGS },
{ "RefreshGuildMember", messengerRefreshGuildMember, METH_VARARGS },
{ "SetMessengerHandler", messengerSetMessengerHandler, METH_VARARGS },
{ NULL, NULL, NULL },
};
Py_InitModule("messenger", s_methods);
}
| [
"contact@asikoo.xyz"
] | contact@asikoo.xyz |
4e43483d6c58015044939ec6ce8796d2225d9994 | e5b9b67769d7408d1bc0c49fcda94b10c628fa29 | /maneuver/sma.cpp | ddd761a6b14bdf30713036e8af6456fbadfa1d18 | [] | no_license | s1w2i3f4t/orbitdynamics | bba6751cde1db4d372d08bb84da55661c7cd4b3b | d0f1ff9a98d5c71c4dd39c19bfb65561bbd702c5 | refs/heads/master | 2020-03-27T07:12:14.519376 | 2018-08-09T15:46:48 | 2018-08-09T15:46:48 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 625 | cpp | // semi-major axis maneuver
#include <OrbitDyn.h>
#include <PerfTimer.h>
using namespace Constant;
//! 近圆轨道的半长轴机动
double sma_nearcircle(double a,double deltaa)
{
double n = sqrt(GE / a / a / a);
return 2 / n * deltaa;
}
double sma_ellipse(double a, double e, double f, double deltaa)
{
double r = a * (1 - e * e) / (1 + e * cos(f));
double v1 = sqrt(GE*(2 / r - 1 / a));
double v2 = sqrt(GE*(2 / r - 1 / (a + deltaa)));
return v2 - v1; // TODO: 有俯仰角?
}
int main(int argc, char* argv[])
{
double dv;
dv = sma_nearcircle(7000, 10);
dv = sma_ellipse(7000, 0.2, 0, 10);
return 0;
} | [
"31544492+handong1979@users.noreply.github.com"
] | 31544492+handong1979@users.noreply.github.com |
5b873d511a3aae1883b676b8aa29c53084629d7e | f5d58b77743a85938f566647a80a8568950b6644 | /additional 3/2/2.4.cpp | b521b89bfeb450bdffb8c31ec2c7491a6918f49f | [] | no_license | Limineses/JS | 4308bb086a500263facee7a3c8bee71174c01c04 | d0711eab6853faf087be543be8b60b172edd1c89 | refs/heads/master | 2020-06-16T15:47:26.210627 | 2019-11-03T13:32:06 | 2019-11-03T13:32:06 | 195,625,653 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 914 | cpp | #include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
setlocale(LC_ALL, "Russian");
double odd = 1;
double even = 1;
double sum = 0;
double s1, s2, x;
cout << "Разложение arcsin(x) в ряд Тейлора до 4-го члена." << endl;
cout << "Введите Х в пределах [-1; 1]: ";
cin >>x;
cout << endl;
if (x > 1 || x < -1)
{
cout << "Неверное значение !";
exit(1);
}
for(int j = 4; j >= 0; j--)
{
for(int i = 2 * j - 1; i > 0; i -=2) // двойной факториал по нечетному основанию
{
odd = odd * i;
}
for(int i = 2 * j; i>0; i -= 2) // двойной факториал по четному основанию
{
even = even * i;
}
s1 = odd / even;
s2 = (pow(x, j * 2 - 1)/ 2 * j - 1);
sum += s1 * s2;
}
cout << "Ответ: " << sum;
return 0;
}
| [
"andreihodunov3@tut.by"
] | andreihodunov3@tut.by |
0663504bc1408c13649c8d1656278be0b0218ae1 | a3569601d203ad418a5cf68043001be5610da90f | /String/72_编辑距离.cpp | cddae8c4d8ac69f585bf63cf97f1eacdf0060138 | [] | no_license | l1nkkk/leetcode | a12b0e117dd5e580fe8356f66774f75edb4612ac | 6c4bb462afb68f5cd913d6f3010b39f62dce2d86 | refs/heads/master | 2023-03-16T17:25:18.765935 | 2022-08-06T15:31:42 | 2022-08-06T15:31:42 | 220,748,877 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,161 | cpp | //
// Created by l1nkkk on 3/29/21.
//
#include <vector>
#include <iostream>
using namespace std;
namespace leetcode72{
class Solution {
public:
int minDistance(string word1, string word2) {
vector<vector<int> > dp(505, vector<int>(505,0));
// 初始化dp
for(int i = 0; i <= word1.length(); ++i){
dp[i][0] = i;
}
for(int j = 0; j <= word2.length(); ++j){
dp[0][j] = j;
}
// 自底向上,目标为dp[word1.length()][word2(length)]
// 从左往右,从下往上
for(int i = 1; i <= word1.length(); ++i){
for(int j = 1; j <= word2.length(); ++j){
if(word1[i-1] == word2[j-1])
dp[i][j] = dp[i-1][j-1];
else{
// dp[i-1][j-1] 替换
// dp[i][j-1] 插入
// dp[i-1][j] 删除
dp[i][j] = std::min(dp[i-1][j-1], std::min(dp[i][j-1],dp[i-1][j]))+1;
}
}
}
return dp[word1.length()][word2.length()];
}
};
void test(){
Solution s;
cout << s.minDistance("","a");
}
} | [
"linkgvhj.ggg.@gmail.com"
] | linkgvhj.ggg.@gmail.com |
328ef96fcc5b5f22f376790a4a8c51798f62a683 | f1e371917d861264e294bdfc5246afb15659da52 | /Server/Sources/RequestParser.cpp | 34b63a32981f33fd0942918858ed729594a96361 | [] | no_license | gobiggo/cpp_spider | ab29c5aa6f2348b52e8ae7f745054f003d48c57c | d24db742742af7f15144b94e02d19c4e6e2f74f5 | refs/heads/master | 2020-03-22T07:43:54.137272 | 2018-01-24T23:13:21 | 2018-01-24T23:13:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,463 | cpp | //
// main.hpp
// spider_server
//
// Created by Victor Sousa on 28/09/2017.
//
//
#include "RequestParser.hpp"
#include "Request.hpp"
http::RequestParser::RequestParser() : state_(method_start)
{
}
void http::RequestParser::reset() {
state_ = method_start;
}
http::RequestParser::result_type http::RequestParser::consume(Request& req, char input) {
switch (state_)
{
case method_start:
if (!is_char(input) || is_ctl(input) || is_tspecial(input))
return bad;
else {
state_ = method;
req.method.push_back(input);
return indeterminate;
}
case method:
if (input == ' ') {
state_ = uri;
return indeterminate;
} else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) {
return bad;
} else {
req.method.push_back(input);
return indeterminate;
}
case uri:
if (input == ' ') {
state_ = http_version_h;
return indeterminate;
} else if (is_ctl(input)) {
return bad;
} else {
req.uri.push_back(input);
return indeterminate;
}
case http_version_h:
if (input == 'H') {
state_ = http_version_t_1;
return indeterminate;
} else {
return bad;
}
case http_version_t_1:
if (input == 'T') {
state_ = http_version_t_2;
return indeterminate;
} else {
return bad;
}
case http_version_t_2:
if (input == 'T') {
state_ = http_version_p;
return indeterminate;
} else {
return bad;
}
case http_version_p:
if (input == 'P') {
state_ = http_version_slash;
return indeterminate;
} else {
return bad;
}
case http_version_slash:
if (input == '/') {
req.http_version_major = 0;
req.http_version_minor = 0;
state_ = http_version_major_start;
return indeterminate;
} else {
return bad;
}
case http_version_major_start:
if (is_digit(input)) {
req.http_version_major = req.http_version_major * 10 + input - '0';
state_ = http_version_major;
return indeterminate;
} else {
return bad;
}
case http_version_major:
if (input == '.') {
state_ = http_version_minor_start;
return indeterminate;
} else if (is_digit(input)) {
req.http_version_major = req.http_version_major * 10 + input - '0';
return indeterminate;
} else {
return bad;
}
case http_version_minor_start:
if (is_digit(input)) {
req.http_version_minor = req.http_version_minor * 10 + input - '0';
state_ = http_version_minor;
return indeterminate;
} else {
return bad;
}
case http_version_minor:
if (input == '\r') {
state_ = expecting_newline_1;
return indeterminate;
} else if (is_digit(input)) {
req.http_version_minor = req.http_version_minor * 10 + input - '0';
return indeterminate;
} else {
return bad;
}
case expecting_newline_1:
if (input == '\n') {
state_ = header_line_start;
return indeterminate;
} else {
return bad;
}
case header_line_start:
if (input == '\r') {
state_ = expecting_newline_3;
return indeterminate;
} else if (!req.headers.empty() && (input == ' ' || input == '\t')) {
state_ = header_lws;
return indeterminate;
} else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) {
return bad;
}
else {
req.headers.push_back(Header());
req.headers.back().name.push_back(input);
state_ = header_name;
return indeterminate;
}
case header_lws:
if (input == '\r') {
state_ = expecting_newline_2;
return indeterminate;
} else if (input == ' ' || input == '\t') {
return indeterminate;
} else if (is_ctl(input)) {
return bad;
} else {
state_ = header_value;
req.headers.back().value.push_back(input);
return indeterminate;
}
case header_name:
if (input == ':') {
state_ = space_before_header_value;
return indeterminate;
} else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) {
return bad;
} else {
req.headers.back().name.push_back(input);
return indeterminate;
}
case space_before_header_value:
if (input == ' ') {
state_ = header_value;
return indeterminate;
} else {
return bad;
}
case header_value:
if (input == '\r') {
state_ = expecting_newline_2;
return indeterminate;
} else if (is_ctl(input)) {
return bad;
} else {
req.headers.back().value.push_back(input);
return indeterminate;
}
case expecting_newline_2:
if (input == '\n') {
state_ = header_line_start;
return indeterminate;
} else {
return bad;
}
case expecting_newline_3:
return (input == '\n') ? good : bad;
default:
return bad;
}
}
bool http::RequestParser::is_char(int c) {
return c >= 0 && c <= 127;
}
bool http::RequestParser::is_ctl(int c) {
return (c >= 0 && c <= 31) || (c == 127);
}
bool http::RequestParser::is_tspecial(int c) {
switch (c)
{
case '(': case ')': case '<': case '>': case '@':
case ',': case ';': case ':': case '\\': case '"':
case '/': case '[': case ']': case '?': case '=':
case '{': case '}': case ' ': case '\t':
return true;
default:
return false;
}
}
bool http::RequestParser::is_digit(int c) {
return c >= '0' && c <= '9';
}
| [
"victor.sousa@epitech.eu"
] | victor.sousa@epitech.eu |
035a841ef01553169c31303b6354e1f57a91e4f3 | 5db5a5a053ef2c572c115f4ac36bfefa00e28379 | /BZOJ/BZOJ1058.cpp | 1d81a94623b31f8906ffadb9a3ec3cedb5349eba | [] | no_license | CaptainSlowWZY/OI-Code | 4491dfa40aae4af148db2dd529556a229a1e76af | be470914186b27d8b24177fb9b5d01d4ac55cd51 | refs/heads/master | 2020-03-22T08:36:19.753282 | 2019-12-19T08:22:51 | 2019-12-19T08:22:51 | 139,777,376 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,959 | cpp | // BZOJ 1058
// ZJOI 2007
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <vector>
#include <set>
typedef std::multiset<int> Set;
const int MAXN = 5e5 + 10, INF = 0x3f3f3f3f;
int N, M, ming = INF;
std::vector<int> A[MAXN];
Set D;
char IN[20];
namespace Treap {
struct Node {
int val, rkey, cnt, ch[2];
Node(int v_ = 0) :
val(v_) {
rkey = rand(), cnt = 1;
ch[0] = ch[1] = 0;
}
} T[MAXN];
int ROOT = 1, size = 1;
int insert(int v_, int & u = ROOT);
int prec(int v_, int u = ROOT);
int succ(int v_, int u = ROOT);
void debug() {
#ifdef DEBUG
printf("===== DEBUG =====\n ROOT = %d\n", ROOT);
for (int i = 1; i <= size; i++) {
printf(" %d val = %d, rkey = %d, lson = %d, rson = %d\n", i, T[i].val, T[i].rkey, T[i].ch[0], T[i].ch[1]);
}
printf("===== ===== =====\n");
#endif
}
inline void init() {
T[1] = Node(-INF);
insert(INF);
}
}
int main() {
srand(19260817);
scanf("%d%d", &N, &M);
Treap::init();
for (int i = 0, ai; i < N; i++) {
scanf("%d", &ai);
A[i].push_back(ai);
if (Treap::insert(ai)) {
Treap::debug();
int pr = Treap::prec(ai), su = Treap::succ(ai);
#ifdef DEBUG
printf(" A%d = %d, prec = %d, succ = %d\n", i, ai, pr, su);
#endif
if (pr != -INF) pr = ai - pr;
else pr = INF;
if (su != INF) su = su - ai;
ming = std::min(ming, std::min(pr, su));
}
else ming = 0;
}
for (int i = 1; i < N; i++) D.insert(abs(A[i][0] - A[i - 1][0]));
for (int i, k; M--; ) {
scanf("%s", IN);
if (IN[0] == 'I') {
scanf("%d%d", &i, &k);
--i;
if (ming) {
if (Treap::insert(k)) {
int pr = Treap::prec(k), su = Treap::succ(k);
if (pr != -INF) pr = k - pr;
else pr = INF;
if (su != INF) su = su - k;
else su = INF;
ming = std::min(ming, std::min(pr, su));
}
else ming = 0;
}
if (i + 1 < N) {
Set::iterator it = D.find(abs(A[i + 1].front() - A[i].back()));
D.erase(it);
D.insert(abs(k - A[i].back())), D.insert(abs(k - A[i + 1].front()));
}
else D.insert(abs(k - A[i].back()));
A[i].push_back(k);
}
else if (IN[4] == 'G') printf("%d\n", *D.begin());
else printf("%d\n", ming);
}
return 0;
}
namespace Treap {
// notice the REFERENCE in the argument-list
void rotate(int & u, int r) {
int son = T[u].ch[r];
T[u].ch[r] = T[son].ch[r ^ 1];
T[son].ch[r ^ 1] = u;
u = son;
}
int insert(int v_, int & u) {
if (!u) {
T[u = ++size] = Node(v_);
return 1;
}
if (T[u].val == v_) {
++T[u].cnt;
return 0;
}
int r = T[u].val < v_;
int tmp = insert(v_, T[u].ch[r]);
if (T[u].rkey > T[T[u].ch[r]].rkey) rotate(u, r);
return tmp;
}
int prec(int v_, int u) {
if (!u) return -INF;
if (T[u].val >= v_) return prec(v_, T[u].ch[0]);
return std::max(T[u].val, prec(v_, T[u].ch[1]));
}
int succ(int v_, int u) {
if (!u) return INF;
if (T[u].val <= v_) return succ(v_, T[u].ch[1]);
return std::min(T[u].val, succ(v_, T[u].ch[0]));
}
}
| [
"CaptainSlowWZY@163.com"
] | CaptainSlowWZY@163.com |
22e28f3d3686c025e964c6df54e7e6d737c0972b | 8792c08bc939f8811f6779cea2a67c77c2af09a7 | /Rotate_Array/Rotate_Array/Main.cpp | 69c031153e1c87d4d3cc9259bf2fbab06a8013f1 | [] | no_license | 7mA/LeetCode | e56fe618a7efcbd80454ba1dcbba0c261a6cfaf4 | b67a46463cd83149f537f894c96c62030af6af16 | refs/heads/master | 2020-03-09T01:18:41.757032 | 2018-04-07T09:09:47 | 2018-04-07T09:09:47 | 128,510,884 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 104 | cpp | #include<iostream>
using namespace std;
void main(){
int i = -2, k = 3;
k %= i;
cout << k << endl;
} | [
"812966201@qq.com"
] | 812966201@qq.com |
d23a180812801af3578530bb8d158e9cac65f175 | b0ae18048c0eb6f2577f0f907a07fe7a0f27df5f | /WDL/wdlstring.h | 9023225fa8bc0dc7092f8ea03e5e4ca39720dfdf | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive"
] | permissive | Youlean/IPlug-Youlean | 215988ae4fe960099719a4c994ed5a4f5706dd4c | 0291d9f634bd2e180a402ccf9b652b4a91e00451 | refs/heads/master | 2021-09-12T08:09:57.689757 | 2018-04-15T11:09:34 | 2018-04-15T11:09:34 | 56,938,366 | 40 | 9 | null | 2017-11-18T12:16:19 | 2016-04-23T20:01:29 | C | UTF-8 | C++ | false | false | 13,259 | h | /*
WDL - wdlstring.h
Copyright (C) 2005 and later, Cockos Incorporated
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/*
This file provides a simple class for variable-length string manipulation.
It provides only the simplest features, and does not do anything confusing like
operator overloading. It uses a WDL_HeapBuf for internal storage.
Actually: there are WDL_String and WDL_FastString -- the latter's Get() returns const char, and tracks
the length of the string, which is often faster. Because of this, you are not permitted to directly modify
the buffer returned by Get().
*/
#ifndef _WDL_STRING_H_
#define _WDL_STRING_H_
#include "heapbuf.h"
#include <stdio.h>
#include <stdarg.h>
#ifndef WDL_STRING_IMPL_ONLY
class WDL_String
{
public:
#ifdef WDL_STRING_INTF_ONLY
void Set(const char *str, int maxlen=0);
void Set(const WDL_String *str, int maxlen=0);
void Append(const char *str, int maxlen=0);
void Append(const WDL_String *str, int maxlen=0);
void DeleteSub(int position, int len);
void Insert(const char *str, int position, int maxlen=0);
void Insert(const WDL_String *str, int position, int maxlen=0);
bool SetLen(int length, bool resizeDown=false); // returns true on success
void Ellipsize(int minlen, int maxlen);
const char *get_filepart() const; // returns whole string if no dir chars
const char *get_fileext() const; // returns ".ext" or end of string "" if no extension
bool remove_fileext(); // returns true if extension was removed
char remove_filepart(bool keepTrailingSlash=false); // returns dir character used, or zero if string emptied
int remove_trailing_dirchars(); // returns trailing dirchar count removed, will not convert "/" into ""
void SetAppendFormattedArgs(bool append, int maxlen, const char* fmt, va_list arglist);
void WDL_VARARG_WARN(printf,3,4) SetFormatted(int maxlen, const char *fmt, ...);
void WDL_VARARG_WARN(printf,3,4) AppendFormatted(int maxlen, const char *fmt, ...);
#endif
const char *Get() const { return m_hb.GetSize()?(char*)m_hb.Get():""; }
#ifdef WDL_STRING_FASTSUB_DEFINED
int GetLength() const { int a = m_hb.GetSize(); return a>0?a-1:0; }
// for binary-safe manipulations
void SetRaw(const char *str, int len) { __doSet(0,str,len,0); }
void AppendRaw(const char *str, int len) { __doSet(GetLength(),str,len,0); }
void InsertRaw(const char *str, int position, int ilen)
{
const int srclen = GetLength();
if (position<0) position=0;
else if (position>srclen) position=srclen;
if (ilen>0) __doSet(position,str,ilen,srclen-position);
}
#else
char *Get()
{
if (m_hb.GetSize()) return (char *)m_hb.Get();
static char c; c=0; return &c; // don't return "", in case it gets written to.
}
int GetLength() const { return m_hb.GetSize()?(int)strlen((const char*)m_hb.Get()):0; }
#endif
explicit WDL_String(int hbgran) : m_hb(hbgran WDL_HEAPBUF_TRACEPARM("WDL_String(4)")) { }
explicit WDL_String(const char *initial=NULL, int initial_len=0) : m_hb(128 WDL_HEAPBUF_TRACEPARM("WDL_String"))
{
if (initial) Set(initial,initial_len);
}
WDL_String(const WDL_String &s) : m_hb(128 WDL_HEAPBUF_TRACEPARM("WDL_String(2)")) { Set(&s); }
WDL_String(const WDL_String *s) : m_hb(128 WDL_HEAPBUF_TRACEPARM("WDL_String(3)")) { if (s && s != this) Set(s); }
~WDL_String() { }
#endif // ! WDL_STRING_IMPL_ONLY
#ifndef WDL_STRING_INTF_ONLY
#ifdef WDL_STRING_IMPL_ONLY
#define WDL_STRING_FUNCPREFIX WDL_String::
#define WDL_STRING_DEFPARM(x)
#else
#define WDL_STRING_FUNCPREFIX
#define WDL_STRING_DEFPARM(x) =(x)
#endif
void WDL_STRING_FUNCPREFIX Set(const char *str, int maxlen WDL_STRING_DEFPARM(0))
{
int s=0;
if (str)
{
if (maxlen>0) while (s < maxlen && str[s]) s++;
else s=(int)strlen(str);
}
__doSet(0,str,s,0);
}
void WDL_STRING_FUNCPREFIX Set(const WDL_String *str, int maxlen WDL_STRING_DEFPARM(0))
{
#ifdef WDL_STRING_FASTSUB_DEFINED
int s = str ? str->GetLength() : 0;
if (maxlen>0 && maxlen<s) s=maxlen;
__doSet(0,str?str->Get():NULL,s,0);
#else
Set(str?str->Get():NULL, maxlen); // might be faster: "partial" strlen
#endif
}
void WDL_STRING_FUNCPREFIX Append(const char *str, int maxlen WDL_STRING_DEFPARM(0))
{
int s=0;
if (str)
{
if (maxlen>0) while (s < maxlen && str[s]) s++;
else s=(int)strlen(str);
}
__doSet(GetLength(),str,s,0);
}
void WDL_STRING_FUNCPREFIX Append(const WDL_String *str, int maxlen WDL_STRING_DEFPARM(0))
{
#ifdef WDL_STRING_FASTSUB_DEFINED
int s = str ? str->GetLength() : 0;
if (maxlen>0 && maxlen<s) s=maxlen;
__doSet(GetLength(),str?str->Get():NULL,s,0);
#else
Append(str?str->Get():NULL, maxlen); // might be faster: "partial" strlen
#endif
}
void WDL_STRING_FUNCPREFIX DeleteSub(int position, int len)
{
int l=m_hb.GetSize()-1;
char *p=(char *)m_hb.Get();
if (l<0 || !*p || position < 0 || position >= l) return;
if (position+len > l) len=l-position;
if (len>0)
{
memmove(p+position,p+position+len,l-position-len+1);
m_hb.Resize(l+1-len,false);
}
}
void WDL_STRING_FUNCPREFIX Insert(const char *str, int position, int maxlen WDL_STRING_DEFPARM(0))
{
int ilen=0;
if (str)
{
if (maxlen>0) while (ilen < maxlen && str[ilen]) ilen++;
else ilen=(int)strlen(str);
}
const int srclen = GetLength();
if (position<0) position=0;
else if (position>srclen) position=srclen;
if (ilen>0) __doSet(position,str,ilen,srclen-position);
}
void WDL_STRING_FUNCPREFIX Insert(const WDL_String *str, int position, int maxlen WDL_STRING_DEFPARM(0))
{
#ifdef WDL_STRING_FASTSUB_DEFINED
int ilen = str ? str->GetLength() : 0;
if (maxlen>0 && maxlen<ilen) ilen=maxlen;
const int srclen = m_hb.GetSize()>0 ? m_hb.GetSize()-1 : 0;
if (position<0) position=0;
else if (position>srclen) position=srclen;
if (ilen>0) __doSet(position,str->Get(),ilen,srclen-position);
#else
Insert(str?str->Get():NULL, position, maxlen); // might be faster: "partial" strlen
#endif
}
bool WDL_STRING_FUNCPREFIX SetLen(int length, bool resizeDown WDL_STRING_DEFPARM(false))
{
#ifdef WDL_STRING_FASTSUB_DEFINED
int osz = m_hb.GetSize()-1;
if (osz<0)osz=0;
#endif
if (length < 0) length=0;
char *b=(char*)m_hb.ResizeOK(length+1,resizeDown);
if (b)
{
#ifdef WDL_STRING_FASTSUB_DEFINED
if (length > osz) memset(b+osz,' ',length-osz);
#endif
b[length]=0;
return true;
}
return false;
}
void WDL_STRING_FUNCPREFIX SetAppendFormattedArgs(bool append, int maxlen, const char* fmt, va_list arglist)
{
int offs = append ? GetLength() : 0;
char *b= (char*) m_hb.ResizeOK(offs+maxlen+1,false);
if (!b) return;
b+=offs;
#ifdef _WIN32
int written = _vsnprintf(b, maxlen+1, fmt, arglist);
if (written < 0 || written>=maxlen) b[written=b[0]?maxlen:0]=0;
#else
int written = vsnprintf(b, maxlen+1, fmt, arglist);
if (written > maxlen) written=maxlen;
#endif
m_hb.Resize(offs + written + 1,false);
}
void WDL_VARARG_WARN(printf,3,4) WDL_STRING_FUNCPREFIX SetFormatted(int maxlen, const char *fmt, ...)
{
va_list arglist;
va_start(arglist, fmt);
SetAppendFormattedArgs(false,maxlen,fmt,arglist);
va_end(arglist);
}
void WDL_VARARG_WARN(printf,3,4) WDL_STRING_FUNCPREFIX AppendFormatted(int maxlen, const char *fmt, ...)
{
va_list arglist;
va_start(arglist, fmt);
SetAppendFormattedArgs(true,maxlen,fmt,arglist);
va_end(arglist);
}
void WDL_STRING_FUNCPREFIX Ellipsize(int minlen, int maxlen)
{
if (maxlen >= 4 && m_hb.GetSize() && GetLength() > maxlen)
{
if (minlen<0) minlen=0;
char *b = (char *)m_hb.Get();
int i;
for (i = maxlen-4; i >= minlen; --i)
{
if (b[i] == ' ')
{
memcpy(b+i, "...",4);
m_hb.Resize(i+4,false);
break;
}
}
if (i < minlen && maxlen >= 4)
{
memcpy(b+maxlen-4, "...",4);
m_hb.Resize(maxlen,false);
}
}
}
const char * WDL_STRING_FUNCPREFIX get_filepart() const // returns whole string if no dir chars
{
const char *s = Get();
const char *p = s + GetLength() - 1;
while (p >= s && !WDL_IS_DIRCHAR(*p)) --p;
return p + 1;
}
const char * WDL_STRING_FUNCPREFIX get_fileext() const // returns ".ext" or end of string "" if no extension
{
const char *s = Get();
const char *endp = s + GetLength();
const char *p = endp - 1;
while (p >= s && !WDL_IS_DIRCHAR(*p))
{
if (*p == '.') return p;
--p;
}
return endp;
}
bool WDL_STRING_FUNCPREFIX remove_fileext() // returns true if extension was removed
{
const char *str = Get();
int pos = GetLength() - 1;
while (pos >= 0)
{
char c = str[pos];
if (WDL_IS_DIRCHAR(c)) break;
if (c == '.')
{
SetLen(pos);
return true;
}
--pos;
}
return false;
}
char WDL_STRING_FUNCPREFIX remove_filepart(bool keepTrailingSlash WDL_STRING_DEFPARM(false)) // returns directory character used, or 0 if string emptied
{
char rv=0;
const char *str = Get();
int pos = GetLength() - 1;
while (pos > 0)
{
char c = str[pos];
if (WDL_IS_DIRCHAR(c))
{
rv=c;
if (keepTrailingSlash) ++pos;
break;
}
--pos;
}
SetLen(pos);
return rv;
}
int WDL_STRING_FUNCPREFIX remove_trailing_dirchars() // returns trailing dirchar count removed
{
int cnt = 0;
const char *str = Get();
const int l = GetLength()-1;
while (cnt < l)
{
char c = str[l - cnt];
if (!WDL_IS_DIRCHAR(c)) break;
++cnt;
}
if (cnt > 0) SetLen(l + 1 - cnt);
return cnt;
}
#ifndef WDL_STRING_IMPL_ONLY
private:
#endif
void WDL_STRING_FUNCPREFIX __doSet(int offs, const char *str, int len, int trailkeep)
{
// if non-empty, or (empty and allocated and Set() rather than append/insert), then allow update, otherwise do nothing
if (len==0 && !trailkeep && !offs)
{
#ifdef WDL_STRING_FREE_ON_CLEAR
m_hb.Resize(0,true);
#else
char *p = (char *)m_hb.Resize(1,false);
if (p) *p=0;
#endif
}
else if (len>0 && offs >= 0)
{
const int oldsz = m_hb.GetSize();
const int newsz=offs+len+trailkeep+1;
if (oldsz < newsz)
{
const char *oldb = (const char *)m_hb.Get();
const char *newb = (const char *)m_hb.Resize(newsz,false); // resize up if necessary
// in case str overlaps with input, keep it valid
if (str && newb != oldb && str >= oldb && str < oldb+oldsz) str = newb + (str - oldb);
}
if (m_hb.GetSize() >= newsz)
{
char *newbuf = (char *)m_hb.Get();
if (trailkeep>0) memmove(newbuf+offs+len,newbuf+offs,trailkeep);
if (str) memmove(newbuf+offs,str,len);
newbuf[newsz-1]=0;
// resize down if necessary
if (newsz < oldsz) m_hb.Resize(newsz,false);
}
}
}
#undef WDL_STRING_FUNCPREFIX
#undef WDL_STRING_DEFPARM
#endif // ! WDL_STRING_INTF_ONLY
#ifndef WDL_STRING_IMPL_ONLY
private:
#ifdef WDL_STRING_INTF_ONLY
void __doSet(int offs, const char *str, int len, int trailkeep);
#endif
WDL_HeapBuf m_hb;
};
#endif
#ifndef WDL_STRING_FASTSUB_DEFINED
#undef _WDL_STRING_H_
#define WDL_STRING_FASTSUB_DEFINED
#define WDL_String WDL_FastString
#include "wdlstring.h"
#undef WDL_STRING_FASTSUB_DEFINED
#undef WDL_String
#endif
#endif
| [
"justin@cockos.com"
] | justin@cockos.com |
8fa7d04a2d600b2a7be7b21f76ba22cd9640bf52 | 3c4ef59613962378e96263c30afab597a96ab25d | /src/common/player/player_body/PlayerEngine.hpp | 65a198213e6b0a85c1c7f344974f0321c3d5a1db | [] | no_license | paolettiandrea/non-gravitar | 42157daea6f0530a2bfeecf50686ff3cb3043465 | 6dcd579fac6b6f69191b45aa6864dfe1b957f4d9 | refs/heads/master | 2022-04-08T11:09:08.839998 | 2020-02-20T13:25:01 | 2020-02-20T13:25:01 | 214,554,394 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,954 | hpp | #ifndef NON_GRAVITAR_PLAYERENGINE_HPP
#define NON_GRAVITAR_PLAYERENGINE_HPP
#include <SGE/components/physics/Rigidbody.hpp>
#include <SGE/components/graphics/ui/blocks/UIBar.hpp>
#include <noise-generation/NoiseMap.hpp>
#include "SGE/logic/Logic.hpp"
#include "SGE/components/graphics/VertArray.hpp"
#include "PlayerPersistentData.hpp"
#include "CONTROLS.hpp"
class PlayerEngine : public sge::Logic {
public:
explicit PlayerEngine(Rigidbody_H rigidbody, PlayerPersistentData* player_persistent_data);
std::string get_logic_id() override;
void on_fixed_update() override;
void on_update() override;
void on_start() override;
private:
enum ThrustStatus {Increasing, Stabilizing, Stable, Decreasing, Zero};
Rigidbody_H controlled_rigidbody;
VertArray_H engine_trail;
// The time in seconds needed to reach maximum thrust force
const float THRUST_INCREASE_TIME = 0.07;
const float THRUST_STABILIZATION_TIME = 0.15;
// The time in seconds needed to decrease thrust force to 0
const float THRUST_DECREASE_TIME = 0.07;
const float BASE_ACCELERATION = 25;
const float MAX_INITIAL_THRUST_FACTOR = 1.2;
// While the lenght of the displayed trail is proportional to the actual acceleration, this can be use to tune the result
const float TRAIL_LENGHT_MULTIPLIER = 0.14;
// The amount of force that needs to be added to the thrust every fixedupdate in order to reach the initial thrust tarhet in the target time
float INITIAL_THRUST_TARGET;
float INITIAL_FORCE_DELTA;
float STABILIZATION_FORCE_DELTA;
float DECREASE_FORCE_DELTA;
float last_thrust_amount = 0;
ThrustStatus thrust_status = Zero;
static constexpr float FUEL_EFFICIENCY_FACTOR = 600;
PlayerPersistentData* player_persistent_data;
NoiseMap noise_map;
float noise_circling_angle = 0;
void update_engine_trail_lenght();
};
#endif //NON_GRAVITAR_PLAYERENGINE_HPP
| [
"andrea.paoletti3@studio.unibo.it"
] | andrea.paoletti3@studio.unibo.it |
2b7753bc3da3367fe7201ee202158c772a0acdb4 | 876b4a0b307b57ab2df634a0aa55b61cdf8d6680 | /core/widgets/WidgetList.h | 4ca5c5ab1c561462a53b5fea6eeb78ac2b82e2cd | [] | no_license | McManning/fro_client | b2b0dec3709ce0b737691dcf4335c13313961c97 | 985b85ce5c1470923880ca0d203f4814e6020516 | refs/heads/master | 2021-01-19T05:53:07.544837 | 2012-01-23T21:44:19 | 2012-01-23T21:44:19 | 2,669,742 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,608 | h |
/*
* Copyright (c) 2011 Chase McManning
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef _WIDGETLIST_H_
#define _WIDGETLIST_H_
#include "Frame.h"
class Scrollbar;
class WidgetList : public Frame
{
public:
WidgetList(Widget* wParent, rect rPosition);
~WidgetList();
void UpdateChildrenPositions();
int GetMaxChildWidth();
// Overriden from Widget
bool Add(Widget* child);
bool Remove(Widget* child, bool deleteClass);
void RemoveAll();
Scrollbar* mScroller;
};
#endif //_WIDGETLIST_H_
| [
"cmcmanning@gmail.com"
] | cmcmanning@gmail.com |
08d6e570381a2b3d0870d353bf05bbb01d3122ff | 96e03053772da867ee856ed769a086c56caee105 | /consumer/rabbitmqConsumer.cpp | 8f25cd3b3c3d4aa7868b6d02fd585a7489e282b0 | [] | no_license | Mcefor19/rabbitmq-cpp | 6299be318d326b3d2910d7abb97153cac327fb33 | 0ceca3f9263820cd23344d9685f3f9d4a77bbc1a | refs/heads/main | 2023-06-29T11:48:57.635896 | 2021-08-07T05:48:39 | 2021-08-07T05:48:39 | 393,590,755 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,276 | cpp | #include "rabbitmqConsumer.h"
amqp_queue_declare_ok_t* rabbitmqConsumer::declareQueue(amqp_channel_t chID, string queueName)
{
return amqp_queue_declare(_conn, chID, amqp_cstring_bytes(queueName.c_str()), 0, 0, 0, 1, amqp_empty_table);
}
void rabbitmqConsumer::bindQueue(amqp_channel_t chID, string queueName, string exchangeName, string bindingkey)
{
amqp_queue_bind(_conn, chID, amqp_cstring_bytes(queueName.c_str()), amqp_cstring_bytes(exchangeName.c_str()),
amqp_cstring_bytes(bindingkey.c_str()), amqp_empty_table);
}
void rabbitmqConsumer::basicConsume(amqp_channel_t chID, string queueName)
{
amqp_basic_consume(_conn, chID, amqp_cstring_bytes(queueName.c_str()), amqp_empty_bytes, 0, 1, 0,amqp_empty_table);
}
void rabbitmqConsumer::recvMsg()
{
amqp_rpc_reply_t ret;
amqp_envelope_t envelope;
amqp_maybe_release_buffers(_conn);
ret = amqp_consume_message(_conn, &envelope, NULL, 0);
if (AMQP_RESPONSE_NORMAL == ret.reply_type)
{
string str((char*)envelope.message.body.bytes, (char*)envelope.message.body.bytes + envelope.message.body.len);
cout << (int)((char*)envelope.message.body.bytes)[0] << (int)((char*)envelope.message.body.bytes)[1] << endl;
cout << str << endl;
amqp_destroy_envelope(&envelope);
}
} | [
"315189070@qq.com"
] | 315189070@qq.com |
f9d0745edb7c0f0ecd85841f8620b9f947038c08 | 86b5ab8bf22c292d314fa553714d7bdef71e3d97 | /src/consensus/params.h | 35fdb188f2f58458b4615c5d0e96a546d863f979 | [
"MIT"
] | permissive | lycion/solbit_BitcoinUnlimited | 6a464eca7e793a2978a97c7fd59deb9e0231b43f | 8c89e95f19522d1f253da2e9242cdcfc9b4e00af | refs/heads/master | 2020-04-08T11:16:38.496228 | 2018-11-29T08:17:23 | 2018-11-29T08:17:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,995 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Solbit Core developers
// Copyright (c) 2015-2018 The Solbit Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef SOLBIT_CONSENSUS_PARAMS_H
#define SOLBIT_CONSENSUS_PARAMS_H
#include "clientversion.h"
#include "uint256.h"
#include <map>
#include <string>
namespace Consensus
{
enum DeploymentPos
{
// bip135 begin
// List of deployment bits. Known allocated bits should be described by a
// name, even if their deployment logic is not implemented by the client.
// (their info is nevertheless useful for awareness and event logging)
// When a bit goes back to being unused, it should be renamed to
// DEPLOYMENT_UNASSIGNED_BIT_x .
// NOTE: Also add new deployments to VersionBitsDeploymentInfo in versionbits.cpp
DEPLOYMENT_CSV = 0, // bit 0 - deployment of BIP68, BIP112, and BIP113.
// begin unassigned bits. Rename bits when allocated.
DEPLOYMENT_UNASSIGNED_BIT_1,
DEPLOYMENT_UNASSIGNED_BIT_2,
DEPLOYMENT_UNASSIGNED_BIT_3,
DEPLOYMENT_UNASSIGNED_BIT_4,
DEPLOYMENT_UNASSIGNED_BIT_5,
DEPLOYMENT_UNASSIGNED_BIT_6,
DEPLOYMENT_UNASSIGNED_BIT_7,
DEPLOYMENT_UNASSIGNED_BIT_8,
DEPLOYMENT_UNASSIGNED_BIT_9,
DEPLOYMENT_UNASSIGNED_BIT_10,
DEPLOYMENT_UNASSIGNED_BIT_11,
DEPLOYMENT_UNASSIGNED_BIT_12,
DEPLOYMENT_UNASSIGNED_BIT_13,
DEPLOYMENT_UNASSIGNED_BIT_14,
DEPLOYMENT_UNASSIGNED_BIT_15,
DEPLOYMENT_UNASSIGNED_BIT_16,
DEPLOYMENT_UNASSIGNED_BIT_17,
DEPLOYMENT_UNASSIGNED_BIT_18,
DEPLOYMENT_UNASSIGNED_BIT_19,
DEPLOYMENT_UNASSIGNED_BIT_20,
DEPLOYMENT_UNASSIGNED_BIT_21,
DEPLOYMENT_UNASSIGNED_BIT_22,
DEPLOYMENT_UNASSIGNED_BIT_23,
DEPLOYMENT_UNASSIGNED_BIT_24,
DEPLOYMENT_UNASSIGNED_BIT_25,
DEPLOYMENT_UNASSIGNED_BIT_26,
DEPLOYMENT_UNASSIGNED_BIT_27,
DEPLOYMENT_TESTDUMMY, // bit 28 - used for deployment testing purposes
// bip135 end
MAX_VERSION_BITS_DEPLOYMENTS
};
/**
* Struct for each individual consensus rule change using BIP135.
*/
struct ForkDeployment
{
/** Bit position to select the particular bit in nVersion. */
int bit;
/** Start MedianTime for version bits miner confirmation. Can be a date in the past */
int64_t nStartTime;
/** Timeout/expiry MedianTime for the deployment attempt. */
int64_t nTimeout;
// bip135 begin added parameters
/** Window size (in blocks) for generalized versionbits signal tallying */
int windowsize;
/** Threshold (in blocks / window) for generalized versionbits lock-in */
int threshold;
/** Minimum number of blocks to remain in locked-in state */
int minlockedblocks;
/** Minimum duration (in seconds based on MTP) to remain in locked-in state */
int64_t minlockedtime;
// bip135 end added parameters
};
/**
* Parameters that influence chain consensus.
*/
struct Params
{
uint256 hashGenesisBlock;
int nSubsidyHalvingInterval;
/** Block height at which BIP16 becomes active */
int BIP16Height;
/** Block height and hash at which BIP34 becomes active */
int BIP34Height;
uint256 BIP34Hash;
/** Block height at which BIP65 becomes active */
int BIP65Height;
/** Block height at which BIP66 becomes active */
int BIP66Height;
/**
* Deployment parameters for the 29 bits (0..28) defined by bip135
*/
// bip135 begin
// fully initialize array
ForkDeployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS] = {
{0, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 0
{1, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 1
{2, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 2
{3, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 3
{4, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 4
{5, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 5
{6, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 6
{7, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 7
{8, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 8
{9, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 9
{10, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 10
{11, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 11
{12, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 12
{13, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 13
{14, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 14
{15, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 15
{16, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 16
{17, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 17
{18, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 18
{19, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 19
{20, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 20
{21, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 21
{22, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 22
{23, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 23
{24, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 24
{25, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 25
{26, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 26
{27, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 27
{28, 0LL, 0LL, 0, 0, 0, 0LL}, // deployment on bit 28
};
// bip135 end
/** Proof of work parameters */
uint256 powLimit;
bool fPowAllowMinDifficultyBlocks;
bool fPowNoRetargeting;
int64_t nPowTargetSpacing;
int64_t nPowTargetTimespan;
int64_t DifficultyAdjustmentInterval() const { return nPowTargetTimespan / nPowTargetSpacing; }
/** UAHF Aug 1st 2017 block height */
int uahfHeight;
/** Block height at which the new DAA becomes active */
int daaHeight;
/** May 15, 2018 Activation time */
int may2018activationTime;
};
} // namespace Consensus
#endif // SOLBIT_CONSENSUS_PARAMS_H
| [
"lycion@gmail.com"
] | lycion@gmail.com |
e673c8b2090380005ac371558a7400e0a9352a37 | 77a08ec51aa16191986a739267fd9d4379bbb208 | /homework/20181030-8.cpp | 7baf859e514c53367a2d89bed56faeaea4d3ba0c | [] | no_license | cenariusxz/ACM-Coding | 8f698203db802f79578921b311b38346950ef0ca | dc09ac9adfb4b80d463bdc93f52b479a957154e6 | refs/heads/master | 2023-06-24T13:12:13.279255 | 2021-07-26T01:24:36 | 2021-07-26T01:24:36 | 185,567,471 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 642 | cpp | #include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
using namespace std;
#define MP make_pair
#define PB push_back
typedef long long ll;
const int mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const double eps = 1e-8;
const int maxn = 1e4 + 5;
int n,c[maxn],y[maxn];
int ans[maxn];
int main(){
scanf("%d",&n);
for(int i = 1 ; i <= n ; ++ i)scanf("%d",&c[i]);
for(int i = 1 ; i <= n ; ++ i)scanf("%d",&y[i]);
int Min = INF, id = 0;
for(int i = 1 ; i <= n ; ++ i){
Min ++;
if(Min > c[i])Min = c[i], id = i;
ans[id] += y[i];
}
for(int i = 1 ; i <= n ; ++ i)printf("%d ",ans[i]);
printf("\n");
return 0;
}
| [
"810988849@qq.com"
] | 810988849@qq.com |
967e2b8a664232cb0e42cc2597f916a039f011e1 | 0dca3325c194509a48d0c4056909175d6c29f7bc | /arms/src/model/DeleteGrafanaResourceRequest.cc | a917fd2b4e7c25a307babae83580b74c607028d9 | [
"Apache-2.0"
] | permissive | dingshiyu/aliyun-openapi-cpp-sdk | 3eebd9149c2e6a2b835aba9d746ef9e6bef9ad62 | 4edd799a79f9b94330d5705bb0789105b6d0bb44 | refs/heads/master | 2023-07-31T10:11:20.446221 | 2021-09-26T10:08:42 | 2021-09-26T10:08:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,739 | cc | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/arms/model/DeleteGrafanaResourceRequest.h>
using AlibabaCloud::ARMS::Model::DeleteGrafanaResourceRequest;
DeleteGrafanaResourceRequest::DeleteGrafanaResourceRequest() :
RpcServiceRequest("arms", "2019-08-08", "DeleteGrafanaResource")
{
setMethod(HttpRequest::Method::Post);
}
DeleteGrafanaResourceRequest::~DeleteGrafanaResourceRequest()
{}
std::string DeleteGrafanaResourceRequest::getClusterName()const
{
return clusterName_;
}
void DeleteGrafanaResourceRequest::setClusterName(const std::string& clusterName)
{
clusterName_ = clusterName;
setBodyParameter("ClusterName", clusterName);
}
std::string DeleteGrafanaResourceRequest::getClusterId()const
{
return clusterId_;
}
void DeleteGrafanaResourceRequest::setClusterId(const std::string& clusterId)
{
clusterId_ = clusterId;
setBodyParameter("ClusterId", clusterId);
}
std::string DeleteGrafanaResourceRequest::getUserId()const
{
return userId_;
}
void DeleteGrafanaResourceRequest::setUserId(const std::string& userId)
{
userId_ = userId;
setBodyParameter("UserId", userId);
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
a221b684a9cfeca4f952a5ed0dc93b2e464ce7f7 | e65df504fa21f9cb232f68dbd020b24a7ce3268e | /src/Elements/PotentialElement.cc | b9fe66de838d1a3204d6757a9a475d673283909c | [
"MIT"
] | permissive | zhili93/voom | bdbbc56e9a8f49603747c329b72dbf9200912d6b | 856b3109dde60f76e4bf32c914ca5916bebd00c8 | refs/heads/master | 2020-12-03T10:29:19.488974 | 2016-05-10T18:12:33 | 2016-05-10T18:12:33 | 58,485,720 | 0 | 1 | null | 2016-05-10T18:49:51 | 2016-05-10T18:49:51 | null | UTF-8 | C++ | false | false | 1,210 | cc | // -*- C++ -*-
//----------------------------------------------------------------------
//
// William S. Klug, Luigi Perotti
// University of California Los Angeles
// (C) 2004-2007 All Rights Reserved
//
//----------------------------------------------------------------------
//
#include <iostream>
#include "PotentialElement.h"
namespace voom {
void PotentialElement::compute(bool fl0, bool fl1, bool fl2)
{
if (fl0) {
_energy = 0.0;
}
for (set<DeformationNode<3> *>::iterator pNode = _domain.begin();
pNode != _domain.end(); pNode++)
{
_mat->updateState(_center, *pNode, fl0, fl1, fl2);
if (fl0) {
_energy += _mat->energy();
}
}
}
void PotentialElement::getTensions(vector<Vector3D > & OneElementsMidPoints, vector<double > & OneElementTension) {
for (set<DeformationNode<3> *>::iterator pNode = _domain.begin(); pNode != _domain.end(); pNode++)
{
OneElementTension.push_back(_mat->computeTension(_center, *pNode));
Vector3D MidPoint;
MidPoint = 0.5*( _center->point() + (*pNode)->point() );
OneElementsMidPoints.push_back(MidPoint);
}
}
} // namespace voom
| [
"luigiemp@login2.(none)"
] | luigiemp@login2.(none) |
2ffbdc56218203e50e7cd78b6efe603114775d67 | d84cf8f82efe5251b93d119ffbcc950c3b73dc6d | /ProDinoWiFiEsp/src/PRODINoESP8266/examples/WiFiWebDHTSrvAP/WiFiWebDHTSrvAP.ino | 9302d13646356b06b5fec5563d85f8e5236af6c7 | [] | no_license | kepsic/KMP | 305816980e05c44a8be836d3bbeebd669e8febd1 | 9912267a048aff5059ad0e9248a2352b7074e2a1 | refs/heads/master | 2020-12-24T20:23:57.255075 | 2016-09-12T15:45:15 | 2016-09-12T15:45:15 | 68,018,593 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,804 | ino | // WiFiWebDHTSrvAP.ino
// Company: KMP Electronics Ltd, Bulgaria
// Web: http://kmpelectronics.eu/
// Supported boards:
// KMP ProDino WiFi-ESP WROOM-02 (http://www.kmpelectronics.eu/en-us/products/prodinowifi-esp.aspx)
// Description:
// Web server AP DHT example.
// Example link: http://www.kmpelectronics.eu/en-us/examples/prodinowifi-esp/wifiwebdhtserverap.aspx
// Version: 1.0.0
// Date: 05.05.2016
// Author: Plamen Kovandjiev <p.kovandiev@kmpelectronics.eu>
// --------------------------------------------------------------------------------
// Prerequisites:
// Before start this example you need to install DHT library: https://github.com/adafruit/DHT-sensor-library
// Connect DHT22 sensor to GROVE connector. Use pins:
// - first sensor GROVE_PIN1, Vcc+, Gnd(-);
// - second sensor GROVE_PIN2, Vcc+, Gnd(-);
#include <KMPDinoWiFiESP.h>
#include <KMPCommon.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <DHT.h>
const uint8_t HTTP_PORT = 80;
// Define sensors structure.
typedef struct
{
// Enable sensor - true.
bool IsEnable;
// Name of sensor. Example: "First sensor".
String Name;
// DHT object with settings. Example: DHT(GROVE_PIN1 /* connected pin */, DHT22 /* sensor type */, 11 /* Constant for ESP8266 */)
DHT dht;
// Store, read humidity from sensor.
float Humidity;
// Store, read temperature from sensor.
float Temperature;
} MeasureHT_t;
// Sensors count.
#define SENSOR_COUNT 2
// Define array of 2 sensors.
MeasureHT_t _measureHT[SENSOR_COUNT] =
{
{ true, "Sensor 1", DHT(GROVE_PIN1, DHT22, 11), NAN, NAN },
{ false, "Sensor 2", DHT(GROVE_PIN2, DHT11, 11), NAN, NAN }
};
// Gray color.
const char GRAY[] = "#808080";
// Check sensor data, interval in milliseconds.
const long CHECK_HT_INTERVAL_MS = 5000;
// Store last measure time.
unsigned long _mesureTimeout;
const char WI_FI_APPSK[] = "kmp12345";
ESP8266WebServer _server(HTTP_PORT);
/**
* @brief Execute first after start device. Initialize hardware.
*
* @return void
*/
void setup(void)
{
// You can open the Arduino IDE Serial Monitor window to see what the code is doing
// Serial connection from ESP-01 via 3.3v console cable
Serial.begin(115200);
// Init KMP ProDino WiFi-ESP board.
KMPDinoWiFiESP.init();
Serial.println("KMP DHT Server Access Point");
// Setup WiFi AP.
WiFi.mode(WIFI_AP);
// Get a unique name, append the last two bytes of the MAC (HEX'd) to device name.
String mac = WiFi.softAPmacAddress(); // 5E:CF:7F:81:70:3E
String apName = "KMP ProDino WiFi-ESP "
+ mac.substring(12);
Serial.print("AP name: ");
Serial.println(apName);
WiFi.softAP(apName.c_str(), WI_FI_APPSK);
Serial.print("AP IP address: ");
Serial.println(WiFi.softAPIP());
_server.on("/", HandleRootPage);
_server.begin();
Serial.println("AP HTTP server started");
// Start sensors.
for (uint8_t i = 0; i < SENSOR_COUNT; i++)
{
MeasureHT_t* measureHT = &_measureHT[i];
Serial.print("Sensor name: \"" + measureHT->Name + "\" - ");
if (measureHT->IsEnable)
{
measureHT->dht.begin();
Serial.println("Start");
}
else
{
Serial.println("Disable");
}
}
_mesureTimeout = 0;
}
/**
* @brief Main method.
*
* @return void
*/
void loop(void)
{
_server.handleClient();
GetDataFromSensors();
}
/**
* @brief Handle root page "/".
*
* @return void
*/
void HandleRootPage()
{
//KMPDinoWiFiESP.LedOn();
_server.send(200, TEXT_HTML, BuildPage());
//KMPDinoWiFiESP.LedOff();
}
/**
* @brief Build HTML page.
*
* @return void
*/
String BuildPage()
{
String page =
"<html><head><title>" + String(KMP_ELECTRONICS_LTD) + " " + String(PRODINO_WIFI) + " - Web DHT AP</title></head>"
+ "<body><div style='text-align: center'>"
+ "<br><hr />"
+ "<h1 style = 'color: #0066FF;'>" + String(PRODINO_WIFI) + " - Web DHT AP example</h1>"
+ "<hr /><br><br>"
+ "<table border='1' width='450' cellpadding='5' cellspacing='0' align='center' style='text-align:center; font-size:large; font-family:Arial,Helvetica,sans-serif;'>"
+ "<thead><tr><th style='width:30%'></th><th style='width:35%'>Temperature C°</th><th>Humidity</th></tr></thead>";
// Add table rows, relay information.
String tableBody = "<tbody>";
for (uint8_t i = 0; i < SENSOR_COUNT; i++)
{
// Row i, cell 1
MeasureHT_t* measureHT = &_measureHT[i];
tableBody += "<tr><td"+ (measureHT->IsEnable ? "" : " bgcolor='" + String(GRAY) + "'") + ">" + measureHT->Name + "</td>";
// Cell i,2
tableBody += "<td>" + FormatMeasure(measureHT->IsEnable, measureHT->Temperature) + "</td>";
// Cell i,3
tableBody += "<td>" + FormatMeasure(measureHT->IsEnable, measureHT->Humidity) + "</td></tr>";
}
tableBody += "</tbody>";
return page + tableBody
+ "</table><br><br><hr /><h1><a href='" + String(URL_KMPELECTRONICS_EU) + "' target='_blank'>Visit " + String(KMP_ELECTRONICS_LTD) + "</a></h1>"
+ "<h3><a href='" + String(URL_KMPELECTRONICS_EU_DINO_WIFI) + "' target='_blank'>Information about " + String(PRODINO_WIFI) + " board</a></h3>"
+ "<hr /></div></body></html>";
}
/**
* @brief Prepare sensor result.
*
* @return void
*/
String FormatMeasure(bool isEnable, float val)
{
return isEnable ? String(val) : "-";
}
/**
* @brief Read data from sensors a specified time.
*
* @return void
*/
void GetDataFromSensors()
{
if (millis() > _mesureTimeout)
{
for (uint8_t i = 0; i < SENSOR_COUNT; i++)
{
// Get sensor structure.
MeasureHT_t* measureHT = &_measureHT[i];
// Is enable - read data from sensor.
if (measureHT->IsEnable)
{
measureHT->dht.read(true);
measureHT->Humidity = measureHT->dht.readHumidity();
measureHT->Temperature = measureHT->dht.readTemperature();
}
}
// Set next time to read data.
_mesureTimeout = millis() + CHECK_HT_INTERVAL_MS;
}
} | [
"p.kovandjiev@kmpelectronics.eu"
] | p.kovandjiev@kmpelectronics.eu |
98cbe0013fe04ef94650a5eb87ae5b66a96d7e65 | 68a76eb015df500ab93125396cf351dff1e53356 | /Codeforces/443.cpp | c4228fbba999d8a8c2f088b8e4311e9105c458c2 | [] | no_license | deepakn97/Competitive-Programming | a84999c0755a187a55a0bb2f384c216e7ee4bf15 | aae415839c6d823daba5cd830935bf3350de895e | refs/heads/master | 2021-10-04T08:00:59.867642 | 2018-12-03T15:37:32 | 2018-12-03T15:37:32 | 81,475,571 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,915 | cpp | /* * * * * * * * * * * * * * * * *
Created By: Deepak Nathani
* Last Updated: 23/12/2017 *
You will win or you'll learn
* * * * * * * * * * * * * * * * */
#include <iostream>
#include <sstream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <cctype>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <functional>
using namespace std;
#define db(x) cout << "->" << #x << ':' << x << '\n';
#define REP(i,n) for(int i = 0; i < (n); i++)
#define FOR(i,a,b) for(int i = (a); i <= (b); i++)
#define FORD(i,a,b) for(int i = (a); i >= (b); i--)
#define all(v) (v).begin(),(v).end()
#define rall(v) (v).rbegin(),(v).rend()
#define fastio ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define READ freopen("input.txt", "r", stdin);
#define WRITE freopen("output.txt", "w", stdout);
#ifdef _WIN32
# define LLD "%I64d"
#else
# define LLD "%lld"
#endif
#define ll long long
// Functions
inline bool eq(double a, double b) { return fabs(a-b) < 1e-9; }
template<typename T> T gcd(T a, T b) { return(b?__gcd(a,b):a); } // a is larger
template<typename T> T lcm(T a, T b) { return(a*(b/gcd(a,b))); }
template <typename T> T mod(T a, T m) { T c = a%m; return (c<0)?c+m:c; }
template<typename T> T mulMod(T a, T b, T m) { return mod((mod(a,m)*mod(b,m)),m);}
template<typename T>T power(T e, T n, T m){ T x=1,p=e; while(n){ if(n&1)x=(x*p)%m; p=mul(p,p,m);n>>=1; } return x;}
// Constants
const int INF = (1 << 29);
/* reset any variable array */
void reset(){
return;
}
/* solution goes here */
void solve(){
char c;
set<char> s;
while(1){
cin >> c;
if(c == '}')
break;
else if(c == '{')
continue;
else if(c == ',')
continue;
else
s.insert(c);
}
cout << s.size() << '\n';
}
int main(){
fastio;
int t;
// cin >> t;
t = 1;
while(t--){
reset();
solve();
}
}
| [
"deepakb1019@gmail.com"
] | deepakb1019@gmail.com |
2716ea3a1fc091b0daf413366b8da277d5cc6d81 | 84a21fbee2cb2319460de32b991c714b844de8e5 | /Bell/Easing/OutBounce.hpp | 12ec43a1bf5ec3d16069cec1677fe1db0b7bc6b7 | [] | no_license | Ryooooooga/Easing | b76f6a19b6f20ddc32411b4777959f44ca7c4c74 | 3c9896d14e2719350b1bee2cb7ab0d99fe9cc0da | refs/heads/master | 2021-01-18T18:26:22.127590 | 2016-07-30T13:47:52 | 2016-07-30T13:47:52 | 64,550,618 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,249 | hpp | //=====================================================================
// Copyright (c) 2016 Ryooooooga.
// https://github.com/Ryooooooga
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=====================================================================
#pragma once
#include <type_traits>
namespace Bell::Easing {
/**
* @brief ease out bounce
*/
template <typename FloatType>
class OutBounce
{
static_assert(std::is_floating_point<FloatType>::value, "");
public:
using value_type = FloatType;
constexpr FloatType operator()(FloatType t) const noexcept
{
return
t < FloatType(0.0/2.75) ? FloatType(0) :
t < FloatType(1.0/2.75) ? FloatType(7.5625)*(t-FloatType(0.00/2.75))*(t-FloatType(0.00/2.75)) :
t < FloatType(2.0/2.75) ? FloatType(7.5625)*(t-FloatType(1.50/2.75))*(t-FloatType(1.50/2.75)) + FloatType(0.75) :
t < FloatType(2.5/2.75) ? FloatType(7.5625)*(t-FloatType(2.25/2.75))*(t-FloatType(2.25/2.75)) + FloatType(0.9375) :
t > FloatType(1) ? 1 : FloatType(7.5625)*(t-FloatType(2.625/2.75))*(t-FloatType(2.625/2.75)) + FloatType(0.984375);
}
};
} // namespace Bell::Easing
| [
"ryoga_314@yahoo.co.jp"
] | ryoga_314@yahoo.co.jp |
79033400d58a4412056e08f8aba22c988b39c16e | 264fdc13bfe259ae4cb79dd7d8bec1fa41472c77 | /graphmove.h | 2ad2c6c6c08cf64f5b46da5871b9f0ece4f381cd | [] | no_license | loveyu/simple-graph | 86542c2b5da08e8bf3716f544fab4159448cf2f5 | 05a1e6e56a0dbb5ebbf3e4e134bb7992d7ffbc16 | refs/heads/master | 2020-05-31T13:32:01.791289 | 2014-12-26T15:21:16 | 2014-12-26T15:21:16 | 28,513,957 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 596 | h | #ifndef GRAPHMOVE_H
#define GRAPHMOVE_H
#include <QList>
#include <QLine>
#include <QRectF>
#include <QPolygonF>
#include "GraphVector.h"
class GraphMove
{
public:
GraphMove(int x,int y);
bool is_move(int x,int y);
void move(QList<QLine> &line,
QList<QRectF> &circle,
QList<QRectF> &oval,
QList<QRectF> &rect,
QList<V_Triangle> &triangle,
QList<QPolygonF> &polygon);
private :
int x,y;
int o_x,o_y;
QRectF moveRectF(QRectF rect);
QPolygonF movePolygon(QPolygonF polygon);
};
#endif // GRAPHMOVE_H
| [
"admin@loveyu.info"
] | admin@loveyu.info |
cf55778e3851c9ea67f70a95a308d51d1838d66e | d6d0c969317f524d04689eecc78fa10db1bd6a58 | /Colossal Cave Adventure/ClassMessage.h | bc30460205afc67c28aeffba777ec3838894a6a7 | [] | no_license | emorozova/Colossal-Cave-Adventure-C-plus-plus | cd5aedc612e6c8aa920e04e28ec7c9dcab4bdfe6 | 16c404e025329d39f55ff73b0232a636ae95a85a | refs/heads/master | 2020-12-01T03:09:58.765558 | 2012-10-14T09:01:27 | 2012-10-14T09:01:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 600 | h | //
// ClassMessage.h
// Colossal Cave Adventure
//
// Created by Sebastian Norling and Niclas Björner on 2012-09-29.
// Copyright (c) 2012. All rights reserved.
//
#ifndef __Colossal_Cave_Adventure__ClassMessage__
#define __Colossal_Cave_Adventure__ClassMessage__
#include <iostream>
#include "Message.h"
class ClassMessage : public Message {
private:
public:
ClassMessage(const int number, const string content);
ClassMessage(const int number);
~ClassMessage();
const string toString();
};
#endif /* defined(__Colossal_Cave_Adventure__ClassMessage__) */
| [
"norling.sebastian@gmail.com"
] | norling.sebastian@gmail.com |
4a572ee8c2be3794433d87ff63b31ce54bb17e27 | 8531941cee6ec624c9eebea503822c6a33d9ff5b | /20142966-1-黄伟鹏/stud3/stud3/main3.cpp | 7216478278433c7c48ca92c036cdce0395b9390c | [] | no_license | SaintAbu/C-project | 7a1a922a4729f84cf9d860a759b50e497dadade0 | 3772ff048e8d2e3f18158e076d3f705cfaf5184b | refs/heads/master | 2021-07-17T11:59:45.402708 | 2017-09-21T16:35:00 | 2017-09-21T16:35:00 | 104,372,784 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 226 | cpp | #include <iostream>
using namespace std;
void main ()
{
double r;
cout<<"请输入正方形的边长:";
cin>> r;
double l,s;
l = 4*r;
s = r*r;
cout<<"正方形周长为"<<l<<endl;
cout<<"正方形面积为"<<s<<endl;
} | [
"1419744295@qq.com"
] | 1419744295@qq.com |
db98921a926e0d9b8120706fb25c9069bd77b5db | 2135d93183928ff868384f004697fcb251cbe7bf | /examples/source/c_call.cpp | 1e422657fc684269050482ee65eeb36c2dc5686f | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | yangc999/sol2 | 192f0e84e34c809a40b725d573b4fdfe0090fb9b | dca62a0f02bb45f3de296de3ce00b1275eb34c25 | refs/heads/main | 2023-05-10T22:01:04.742464 | 2022-06-25T17:25:52 | 2022-06-25T17:27:29 | 315,809,866 | 0 | 0 | MIT | 2020-11-25T02:43:25 | 2020-11-25T02:43:24 | null | UTF-8 | C++ | false | false | 1,178 | cpp | #define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
int f1(int) {
return 32;
}
int f2(int, int) {
return 1;
}
struct fer {
double f3(int, int) {
return 2.5;
}
};
int main() {
sol::state lua;
// overloaded function f
lua.set("f",
sol::c_call<sol::wrap<decltype(&f1), &f1>,
sol::wrap<decltype(&f2), &f2>,
sol::wrap<decltype(&fer::f3), &fer::f3>>);
// singly-wrapped function
lua.set("g", sol::c_call<sol::wrap<decltype(&f1), &f1>>);
// without the 'sol::wrap' boilerplate
lua.set("h", sol::c_call<decltype(&f2), &f2>);
// object used for the 'fer' member function call
lua.set("obj", fer());
// call them like any other bound function
lua.script("r1 = f(1)");
lua.script("r2 = f(1, 2)");
lua.script("r3 = f(obj, 1, 2)");
lua.script("r4 = g(1)");
lua.script("r5 = h(1, 2)");
// get the results and see
// if it worked out
int r1 = lua["r1"];
sol_c_assert(r1 == 32);
int r2 = lua["r2"];
sol_c_assert(r2 == 1);
double r3 = lua["r3"];
sol_c_assert(r3 == 2.5);
int r4 = lua["r4"];
sol_c_assert(r4 == 32);
int r5 = lua["r5"];
sol_c_assert(r5 == 1);
return 0;
}
| [
"phdofthehouse@gmail.com"
] | phdofthehouse@gmail.com |
83fbcd19e88dceac5d5abc80b7ca792123fa9fd9 | 5af68d43b182694e6955be8de0a84ecea20c078d | /BlackCat.Physics.PhysX/PhysicsImp/Shape/bcTriangleMesh.cpp | e6b66bd2055843fe42cff9e54387ff42a5d0829d | [] | no_license | coder965/BlackCat-Engine | 1ed5c3d33c67c537eaa1ae7d1afe40192296e03f | a692f95d5c5f0c86ababa0c5ecc06531f569f500 | refs/heads/master | 2020-03-18T21:41:31.035603 | 2017-04-15T16:53:26 | 2017-04-15T16:53:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,398 | cpp | // [12/12/2016 MRB]
#include "PhysicsImp/PhysicsImpPCH.h"
#include "PhysicsImp/bcExport.h"
#include "PhysicsImp/Shape/bcTriangleMesh.h"
namespace black_cat
{
namespace physics
{
template<>
BC_PHYSICSIMP_DLL
bc_platform_triangle_mesh< g_api_physx >::bc_platform_triangle_mesh() noexcept
: bc_platform_physics_reference()
{
}
template<>
BC_PHYSICSIMP_DLL
bc_platform_triangle_mesh< g_api_physx >::bc_platform_triangle_mesh(const bc_platform_triangle_mesh& p_other) noexcept
: bc_platform_physics_reference(p_other)
{
}
template<>
BC_PHYSICSIMP_DLL
bc_platform_triangle_mesh< g_api_physx >::~bc_platform_triangle_mesh()
{
}
template<>
BC_PHYSICSIMP_DLL
bc_platform_triangle_mesh< g_api_physx >& bc_platform_triangle_mesh< g_api_physx >::operator=(const bc_platform_triangle_mesh& p_other) noexcept
{
bc_platform_physics_reference::operator=(p_other);
return *this;
}
template<>
BC_PHYSICSIMP_DLL
bcUINT32 bc_platform_triangle_mesh< g_api_physx >::get_num_vertices() const noexcept
{
auto* l_px_mesh = static_cast< physx::PxTriangleMesh* >
(
static_cast< bc_platform_physics_reference& >(const_cast< bc_platform_triangle_mesh& >(*this)).get_platform_pack().m_px_object
);
return l_px_mesh->getNbVertices();
}
template<>
BC_PHYSICSIMP_DLL
bcUINT32 bc_platform_triangle_mesh< g_api_physx >::get_num_triangles() const noexcept
{
auto* l_px_mesh = static_cast< physx::PxTriangleMesh* >
(
static_cast< bc_platform_physics_reference& >(const_cast< bc_platform_triangle_mesh& >(*this)).get_platform_pack().m_px_object
);
return l_px_mesh->getNbTriangles();
}
template<>
BC_PHYSICSIMP_DLL
bc_bounded_strided_data bc_platform_triangle_mesh< g_api_physx >::get_vertices() const
{
auto* l_px_mesh = static_cast< physx::PxTriangleMesh* >
(
static_cast< bc_platform_physics_reference& >(const_cast< bc_platform_triangle_mesh& >(*this)).get_platform_pack().m_px_object
);
return bc_bounded_strided_data(l_px_mesh->getVertices(), sizeof(physx::PxVec3), get_num_vertices());
}
template<>
BC_PHYSICSIMP_DLL
bc_bounded_strided_data bc_platform_triangle_mesh< g_api_physx >::get_indices() const
{
auto* l_px_mesh = static_cast< physx::PxTriangleMesh* >
(
static_cast< bc_platform_physics_reference& >(const_cast< bc_platform_triangle_mesh& >(*this)).get_platform_pack().m_px_object
);
return bc_bounded_strided_data
(
l_px_mesh->getTriangles(),
l_px_mesh->getTriangleMeshFlags() & physx::PxTriangleMeshFlag::e16_BIT_INDICES ? sizeof(physx::PxU16) : sizeof(physx::PxU32),
get_num_triangles() * 3
);
}
template<>
BC_PHYSICSIMP_DLL
bc_bound_box bc_platform_triangle_mesh< g_api_physx >::get_local_bound() const
{
auto* l_px_mesh = static_cast< physx::PxTriangleMesh* >
(
static_cast< bc_platform_physics_reference& >(const_cast< bc_platform_triangle_mesh& >(*this)).get_platform_pack().m_px_object
);
bc_bound_box l_bound;
l_bound.get_platform_pack().m_bound = l_px_mesh->getLocalBounds();
return l_bound;
}
template<>
BC_PHYSICSIMP_DLL
bool bc_platform_triangle_mesh< g_api_physx >::is_valid() const noexcept
{
return static_cast< bc_platform_physics_reference& >
(
const_cast< bc_platform_triangle_mesh& >(*this)
)
.get_platform_pack().m_px_object != nullptr;
}
}
} | [
"mohammad.r.barzegar@gmail.com"
] | mohammad.r.barzegar@gmail.com |
4b836e0c40b14794d761a4d1794626166d937e3f | e89a8e57e5c397b92d40c451308faf209b10a2fd | /Sudoku.cpp | 1db671315b503e8718c938587001272ac4a04047 | [] | no_license | NikBomb/SudokuSolver | 7c37f484c09177363b3d89307afb717e7984432e | 3e6c4e5930179ed7cad701dc74a71c676a485023 | refs/heads/master | 2021-08-14T11:39:59.850067 | 2017-11-15T15:04:08 | 2017-11-15T15:04:08 | 110,845,676 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,352 | cpp |
#include "stdafx.h"
# include <vector>
#include <math.h>
using namespace std;
/*Class That implements the sudoku as a double array*/
class Sudoku {
private:
int grid[9][9];
public:
Sudoku(int clues[9][9]);
Sudoku() { /*Method to initialise the Sudoku to zeros*/
int igrid;
int jgrid;
for (igrid = 0; igrid < 9; igrid++)
{
for (jgrid = 0; jgrid < 9; jgrid++)
{
this->grid[igrid][jgrid] = 0;
}
}
};
int getgrid(int i, int j); /*get the value at a position over the grid*/
bool solve(); /*Solve the Sudoku */
bool checktrial(int trial,int igrid,int jgrid); /*Check if the trial number can sit in its position*/
};
Sudoku::Sudoku(int clues[9][9]) {
int igrid;
int jgrid;
for (igrid = 0; igrid < 9; igrid++)
{
for (jgrid = 0; jgrid < 9; jgrid++)
{
this->grid[igrid][jgrid] = clues[igrid][jgrid];
}
}
}
int Sudoku::getgrid(int i, int j)
{
return this->grid[i][j];
}
bool Sudoku::solve()
{
int igrid;
int jgrid;
vector<int> rows;
vector<int> cols;
int ntrials = 0;
int trial = 0;
for (igrid = 0; igrid < 9; igrid++)
{
for (jgrid = 0; jgrid < 9; jgrid++)
{
if (this->grid[igrid][jgrid] == 0)
{
while(ntrials < 9 & trial < 10)
{
trial = trial + 1;
if (this->checktrial(trial, igrid, jgrid)) //If the trial is not correct, use another number
{
ntrials++;
}
else //else accept the trial and move on
{
this->grid[igrid][jgrid] = trial;
rows.push_back(igrid);
cols.push_back(jgrid);
break;
}
}
if (ntrials < 9 & trial < 10)
{
trial = 0;
ntrials = 0;
//Solution accepted
}
else
{
igrid = rows.back();
jgrid = cols.back();
ntrials = 0;
trial = this->grid[igrid][jgrid];
rows.pop_back();
cols.pop_back();
this->grid[igrid][jgrid] = 0;
jgrid--;
// Skip to last igrid and jgrid, set new number of trials, try again
}
}
}
}
return true;
};
bool Sudoku::checktrial(int trial, int igrid, int jgrid)
{
int iloop;
int jloop;
int isquare;
int jsquare;
int offseti;
int offsetj;
/*Check columns*/
for (iloop = 0; iloop < 9; iloop++)
{
if (trial == this->grid[iloop][jgrid])
{
return true;
}
}
/*Check rows*/
for (jloop = 0; jloop < 9; jloop++)
{
if (trial == this->grid[igrid][jloop])
{
return true;
}
}
/*Check square*/
isquare = floor(igrid / 3);
jsquare = floor(jgrid / 3);
offseti = 3 * isquare;
offsetj = 3 * jsquare;
for (iloop = 0; iloop < 3; iloop++)
{
for (jloop = 0; jloop < 3; jloop++)
{
if (trial == this->grid[iloop + offseti][jloop + offsetj])
{
return true;
}
}
}
return false;
};
int main() /*Driver program, with a trial sudoku*/
{
int clues[9][9];
int igrid, jgrid;
for (igrid = 0; igrid < 9; igrid++)
{
for (jgrid = 0; jgrid < 9; jgrid++)
{
clues[igrid][jgrid] = 0;
}
}
#if 0
clues[0][1] = 7;
clues[0][2] = 1;
clues[0][4] = 9;
clues[0][6] = 8;
clues[1][3] = 3;
clues[1][5] = 6;
clues[2][0] = 4;
clues[2][1] = 9;
clues[2][6] = 7;
clues[2][8] = 5;
clues[3][1] = 1;
clues[3][3] = 9;
clues[4][0] = 9;
clues[4][2] = 2;
clues[4][6] = 6;
clues[4][8] = 3;
clues[5][5] = 8;
clues[5][7] = 2;
clues[6][0] = 8;
clues[6][2] = 5;
clues[6][7] = 7;
clues[6][8] = 6;
clues[7][3] = 6;
clues[7][5] = 7;
clues[8][2] = 7;
clues[8][4] = 4;
clues[8][6] = 3;
clues[8][7] = 5;
#endif
clues[0][1] = 7;
clues[0][2] = 5;
clues[0][4] = 9;
clues[0][8] = 6;
clues[1][1] = 2;
clues[1][2] = 3;
clues[1][4] = 8;
clues[1][7] = 4;
clues[2][0] = 8;
clues[2][5] = 3;
clues[2][8] = 1;
clues[3][0] = 5;
clues[3][3] = 7;
clues[3][5] = 2;
clues[4][1] = 4;
clues[4][3] = 8;
clues[4][5] = 6;
clues[4][7] = 2;
clues[5][3] = 9;
clues[5][5] = 1;
clues[5][8] = 3;
clues[6][0] = 9;
clues[6][3] = 4;
clues[6][8] = 7;
clues[7][1] = 6;
clues[7][4] = 7;
clues[7][6] = 5;
clues[7][7] = 8;
clues[8][0] = 7;
clues[8][4] = 1;
clues[8][6] = 3;
clues[8][7] = 9;
Sudoku sudoku(clues);
sudoku.solve();
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
65376de8e22d00ff5dcb3c896ff274a5872da471 | 2b332da28ca7d188892f72724400d79f16cda1b9 | /include/ce2/ext/enum_ext.hpp | 6d70a04b7e8a5106eed27d43aae4abb0ed816d52 | [
"Apache-2.0"
] | permissive | chokomancarr/chokoengine2 | e4b72f18f6fd832c2445b5c7bec1bb538ad62de1 | 2825f2b95d24689f4731b096c8be39cc9a0f759a | refs/heads/master | 2023-05-02T18:05:43.665056 | 2021-04-14T17:54:17 | 2021-04-14T17:54:17 | 191,103,464 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 815 | hpp | #pragma once
#include <type_traits>
#define CE_ENUM_OP_DEF(op) \
template <typename E, typename T>\
constexpr inline typename std::enable_if<std::is_enum<E>::value, E>::type operator op(E a, T b) {\
return E((size_t)a op (size_t)b);\
}\
template <typename E, typename T>\
constexpr inline typename std::enable_if<std::is_enum<E>::value, E>::type& operator op##=(E& a, const T b) {\
return (a = a op b);\
}
CE_ENUM_OP_DEF(&)
CE_ENUM_OP_DEF(|)
CE_ENUM_OP_DEF(^)
#undef CE_ENUM_OP_DEF
template <typename E, typename = typename std::enable_if<std::is_enum<E>::value, E>::type*>\
constexpr inline E operator~(E a) {\
return (size_t)a ^ ((size_t)E::_MASK);
}
template <typename E, typename = typename std::enable_if<std::is_enum<E>::value, E>::type*>\
constexpr inline bool operator!(E a) {\
return !(size_t)a;
} | [
"puakai2010@gmail.com"
] | puakai2010@gmail.com |
f804e0751cc3c0835967a7bf96f2b266e2bbbd22 | 954bfd7c464f443cc3b006bbf4460fdc1534645e | /1203A.cpp | 66d82fe7f80095c85943a8e5495975cb7d03ce88 | [] | no_license | draconware/codeforces | 0f68ef88d9e00226e8802413209ffe33c3648003 | 0c92fe56092cb323ff67629ca45ac40007ac06f1 | refs/heads/master | 2021-01-01T06:01:39.191054 | 2019-12-13T07:55:20 | 2019-12-13T07:55:20 | 97,331,903 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,022 | cpp | #include<bits/stdc++.h>
using namespace std;
#define LL long long
#define ff first
#define ss second
#define mp make_pair
#define pii pair<int,int>
#define pb push_back
int main(){
#ifndef ONLINE_JUDGE
freopen("input.in","r",stdin);
freopen("output.out","w",stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin>>t;
while(t--){
int n;
cin>>n;
vector<int> v;
for(int i=0;i<n;i++){
int x;cin>>x;v.pb(x);
}
if(n==1){cout<<"YES"<<endl;continue;}
int x = v[0]+1;
int y = v[0]-1;
if(x>n){x-=n;}
if(y<=0){y+=n;}
if(x==v[1]){
bool flag=true;
for(int i=2;i<n;i++){
int x = v[i-1]+1;
if(x>n){x-=n;}
if(x!=v[i]){flag=false;break;}
}
if(!flag){cout<<"NO"<<endl;}
else{cout<<"YES"<<endl;}
}else if(y==v[1]){
bool flag=true;
for(int i=2;i<n;i++){
int x = v[i-1]-1;
if(x<=0){x+=n;}
if(x!=v[i]){flag=false;break;}
}
if(!flag){cout<<"NO"<<endl;}
else{cout<<"YES"<<endl;}
}else{
cout<<"NO"<<endl;
}
}
} | [
"noreply@github.com"
] | noreply@github.com |
adc760d1ee72e01efd9aaaa39469e7471b627d86 | ed27c2e31ec84826b3b66d2b3c159fb17ca3fbbf | /Advanced shaders/PixelLighting2/Mesh.cpp | c36a546383280021cc257a6a2e77a429187c1302 | [] | no_license | LiliVeszeli/Graphics | 69c3f8b5266b554039fc34ba262d4f2f545d28e1 | a079675849959a3278bad36851ac8bc7c49f08cd | refs/heads/master | 2022-05-30T22:49:12.800976 | 2020-05-03T10:36:20 | 2020-05-03T10:36:20 | 212,877,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,302 | cpp | //--------------------------------------------------------------------------------------
// Class encapsulating a mesh
//--------------------------------------------------------------------------------------
// The mesh class splits the mesh into sub-meshes that only use one texture each.
// ** THIS VERSION WILL ONLY KEEP THE FIRST SUB-MESH OTHER PARTS WILL BE MISSING **
// ** DO NOT USE THIS VERSION FOR PROJECTS **
// The class also doesn't load textures, filters or shaders as the outer code is
// expected to select these things. A later lab will introduce a more robust loader.
#define NOMINMAX
#include "Mesh.h"
#include "Shader.h" // Needed for helper function CreateSignatureForVertexLayout
#include "CVector2.h"
#include "CVector3.h"
#include <assimp/include/assimp/Importer.hpp>
#include <assimp/include/assimp/DefaultLogger.hpp>
#include <assimp/include/assimp/postprocess.h>
#include <assimp/include/assimp/scene.h>
#include <memory>
#include <stdexcept>
// Pass the name of the mesh file to load. Uses assimp (http://www.assimp.org/) to support many file types
// Optionally request tangents to be calculated (for normal and parallax mapping - see later lab)
// Will throw a std::runtime_error exception on failure (since constructors can't return errors).
Mesh::Mesh(const std::string& fileName, bool requireTangents /*= false*/)
{
Assimp::Importer importer;
// Flags for processing the mesh. Assimp provides a huge amount of control - right click any of these
// and "Peek Definition" to see documention above each constant
unsigned int assimpFlags = aiProcess_MakeLeftHanded |
aiProcess_GenSmoothNormals |
aiProcess_FixInfacingNormals |
aiProcess_GenUVCoords |
aiProcess_TransformUVCoords |
aiProcess_FlipUVs |
aiProcess_FlipWindingOrder |
aiProcess_Triangulate |
aiProcess_PreTransformVertices |
aiProcess_JoinIdenticalVertices |
aiProcess_ImproveCacheLocality |
aiProcess_SortByPType |
aiProcess_FindInvalidData |
aiProcess_OptimizeMeshes |
aiProcess_FindInstances |
aiProcess_FindDegenerates |
aiProcess_RemoveRedundantMaterials |
aiProcess_Debone |
aiProcess_RemoveComponent;
// Flags to specify what mesh data to ignore
int removeComponents = aiComponent_LIGHTS | aiComponent_CAMERAS | aiComponent_TEXTURES | aiComponent_COLORS |
aiComponent_BONEWEIGHTS | aiComponent_ANIMATIONS | aiComponent_MATERIALS;
// Add / remove tangents as required by user
if (requireTangents)
{
assimpFlags |= aiProcess_CalcTangentSpace;
}
else
{
removeComponents |= aiComponent_TANGENTS_AND_BITANGENTS;
}
// Other miscellaneous settings
importer.SetPropertyFloat(AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE, 80.0f); // Smoothing angle for normals
importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_POINT | aiPrimitiveType_LINE); // Remove points and lines (keep triangles only)
importer.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true); // Remove degenerate triangles
importer.SetPropertyBool(AI_CONFIG_PP_DB_ALL_OR_NONE, true); // Default to removing bones/weights from meshes that don't need skinning
importer.SetPropertyInteger(AI_CONFIG_PP_RVC_FLAGS, removeComponents);
// Import mesh with assimp given above requirements - log output
Assimp::DefaultLogger::create("", Assimp::DefaultLogger::VERBOSE);
const aiScene* scene = importer.ReadFile(fileName, assimpFlags);
Assimp::DefaultLogger::kill();
if (scene == nullptr) throw std::runtime_error("Error loading mesh (" + fileName + "). " + importer.GetErrorString());
if (scene->mNumMeshes == 0) throw std::runtime_error("No usable geometry in mesh: " + fileName);
//-----------------------------------
// Only importing first submesh - significant limitation - do not use this importer for your own projects
aiMesh* assimpMesh = scene->mMeshes[0];
std::string subMeshName = assimpMesh->mName.C_Str();
//-----------------------------------
// Check for presence of position and normal data. Tangents and UVs are optional.
std::vector<D3D11_INPUT_ELEMENT_DESC> vertexElements;
unsigned int offset = 0;
if (!assimpMesh->HasPositions()) throw std::runtime_error("No position data for sub-mesh " + subMeshName + " in " + fileName);
unsigned int positionOffset = offset;
vertexElements.push_back( { "Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, positionOffset, D3D11_INPUT_PER_VERTEX_DATA, 0 } );
offset += 12;
if (!assimpMesh->HasNormals()) throw std::runtime_error("No normal data for sub-mesh " + subMeshName + " in " + fileName);
unsigned int normalOffset = offset;
vertexElements.push_back( { "Normal", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, normalOffset, D3D11_INPUT_PER_VERTEX_DATA, 0 } );
offset += 12;
unsigned int tangentOffset = offset;
if (requireTangents)
{
if (!assimpMesh->HasTangentsAndBitangents()) throw std::runtime_error("No tangent data for sub-mesh " + subMeshName + " in " + fileName);
vertexElements.push_back( { "Tangent", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, tangentOffset, D3D11_INPUT_PER_VERTEX_DATA, 0 } );
offset += 12;
}
unsigned int uvOffset = offset;
if (assimpMesh->GetNumUVChannels() > 0 && assimpMesh->HasTextureCoords(0))
{
if (assimpMesh->mNumUVComponents[0] != 2) throw std::runtime_error("Unsupported texture coordinates in " + subMeshName + " in " + fileName);
vertexElements.push_back( { "UV", 0, DXGI_FORMAT_R32G32_FLOAT, 0, uvOffset, D3D11_INPUT_PER_VERTEX_DATA, 0 } );
offset += 8;
}
mVertexSize = offset;
// Create a "vertex layout" to describe to DirectX what is data in each vertex of this mesh
auto shaderSignature = CreateSignatureForVertexLayout(vertexElements.data(), static_cast<int>(vertexElements.size()));
HRESULT hr = gD3DDevice->CreateInputLayout(vertexElements.data(), static_cast<UINT>(vertexElements.size()),
shaderSignature->GetBufferPointer(), shaderSignature->GetBufferSize(),
&mVertexLayout);
if (shaderSignature) shaderSignature->Release();
if (FAILED(hr)) throw std::runtime_error("Failure creating input layout for " + fileName);
//-----------------------------------
// Create CPU-side buffers to hold current mesh data - exact content is flexible so can't use a structure for a vertex - so just a block of bytes
// Note: for large arrays a unique_ptr is better than a vector because vectors default-initialise all the values which is a waste of time.
mNumVertices = assimpMesh->mNumVertices;
mNumIndices = assimpMesh->mNumFaces * 3;
auto vertices = std::make_unique<unsigned char[]>(mNumVertices * mVertexSize);
auto indices = std::make_unique<unsigned char[]>(mNumIndices * 4); // Using 32 bit indexes (4 bytes) for each indeex
//-----------------------------------
// Copy mesh data from assimp to our CPU-side vertex buffer
CVector3* assimpPosition = reinterpret_cast<CVector3*>(assimpMesh->mVertices);
unsigned char* position = vertices.get() + positionOffset;
unsigned char* positionEnd = position + mNumVertices * mVertexSize;
while (position != positionEnd)
{
*(CVector3*)position = *assimpPosition;
position += mVertexSize;
++assimpPosition;
}
CVector3* assimpNormal = reinterpret_cast<CVector3*>(assimpMesh->mNormals);
unsigned char* normal = vertices.get() + normalOffset;
unsigned char* normalEnd = normal + mNumVertices * mVertexSize;
while (normal != normalEnd)
{
*(CVector3*)normal = *assimpNormal;
normal += mVertexSize;
++assimpNormal;
}
if (requireTangents)
{
CVector3* assimpTangent = reinterpret_cast<CVector3*>(assimpMesh->mTangents);
unsigned char* tangent = vertices.get() + tangentOffset;
unsigned char* tangentEnd = tangent + mNumVertices * mVertexSize;
while (tangent != tangentEnd)
{
*(CVector3*)tangent = *assimpTangent;
tangent += mVertexSize;
++assimpTangent;
}
}
if (assimpMesh->GetNumUVChannels() > 0 && assimpMesh->HasTextureCoords(0))
{
aiVector3D* assimpUV = assimpMesh->mTextureCoords[0];
unsigned char* uv = vertices.get() + uvOffset;
unsigned char* uvEnd = uv + mNumVertices * mVertexSize;
while (uv != uvEnd)
{
*(CVector2*)uv = CVector2(assimpUV->x, assimpUV->y);
uv += mVertexSize;
++assimpUV;
}
}
//-----------------------------------
// Copy face data from assimp to our CPU-side index buffer
if (!assimpMesh->HasFaces()) throw std::runtime_error("No face data in " + subMeshName + " in " + fileName);
DWORD* index = reinterpret_cast<DWORD*>(indices.get());
for (unsigned int face = 0; face < assimpMesh->mNumFaces; ++face)
{
*index++ = assimpMesh->mFaces[face].mIndices[0];
*index++ = assimpMesh->mFaces[face].mIndices[1];
*index++ = assimpMesh->mFaces[face].mIndices[2];
}
//-----------------------------------
D3D11_BUFFER_DESC bufferDesc;
D3D11_SUBRESOURCE_DATA initData;
// Create GPU-side vertex buffer and copy the vertices imported by assimp into it
bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; // Indicate it is a vertex buffer
bufferDesc.Usage = D3D11_USAGE_DEFAULT; // Default usage for this buffer - we'll see other usages later
bufferDesc.ByteWidth = mNumVertices * mVertexSize; // Size of the buffer in bytes
bufferDesc.CPUAccessFlags = 0;
bufferDesc.MiscFlags = 0;
initData.pSysMem = vertices.get(); // Fill the new vertex buffer with data loaded by assimp
hr = gD3DDevice->CreateBuffer(&bufferDesc, &initData, &mVertexBuffer);
if (FAILED(hr)) throw std::runtime_error("Failure creating vertex buffer for " + fileName);
// Create GPU-side index buffer and copy the vertices imported by assimp into it
bufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; // Indicate it is an index buffer
bufferDesc.Usage = D3D11_USAGE_DEFAULT; // Default usage for this buffer - we'll see other usages later
bufferDesc.ByteWidth = mNumIndices * sizeof(DWORD); // Size of the buffer in bytes
bufferDesc.CPUAccessFlags = 0;
bufferDesc.MiscFlags = 0;
initData.pSysMem = indices.get(); // Fill the new index buffer with data loaded by assimp
hr = gD3DDevice->CreateBuffer(&bufferDesc, &initData, &mIndexBuffer);
if (FAILED(hr)) throw std::runtime_error("Failure creating index buffer for " + fileName);
}
Mesh::~Mesh()
{
if (mIndexBuffer) mIndexBuffer ->Release();
if (mVertexBuffer) mVertexBuffer->Release();
if (mVertexLayout) mVertexLayout->Release();
}
// The render function assumes shaders, matrices, textures, samplers etc. have been set up already.
// It simply draws this mesh with whatever settings the GPU is currently using.
void Mesh::Render()
{
// Set vertex buffer as next data source for GPU
UINT stride = mVertexSize;
UINT offset = 0;
gD3DContext->IASetVertexBuffers(0, 1, &mVertexBuffer, &stride, &offset);
// Indicate the layout of vertex buffer
gD3DContext->IASetInputLayout(mVertexLayout);
// Set index buffer as next data source for GPU, indicate it uses 32-bit integers
gD3DContext->IASetIndexBuffer(mIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
// Using triangle lists only in this class
gD3DContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
// Render mesh
gD3DContext->DrawIndexed(mNumIndices, 0, 0);
}
| [
"47601474+LiliVeszeli@users.noreply.github.com"
] | 47601474+LiliVeszeli@users.noreply.github.com |
cbc5e5b485d2094ff9bae000df2153bd33efc761 | 182322f4f2800f851754bb1bcb85fd4f9fc324ea | /gcj/2015/round_1B/pb.cpp | 4d5bc20adf113e4f703bab4ffaee472ccaa9f4f1 | [] | no_license | Tocknicsu/oj | 66100fe94d76b6fe8d1bd3019f5ada9d686c1753 | e84d6c87f3e8c0443a27e8efc749ea4b569a6c91 | refs/heads/master | 2021-01-17T08:12:32.510731 | 2016-04-18T02:09:04 | 2016-04-18T02:09:16 | 32,704,322 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,088 | cpp | #include <bits/stdc++.h>
using namespace std;
int cost[5];
void calc(int r, int w){
fill(cost, cost+5, 0);
if( r > w ) swap(r, w);
if( r == 1 ){
if(w == 1){
cost[0] = 1;
return;
}
cost[1] = 2;
cost[2] = w - 2;
} else {
cost[2] = 4;
cost[3] =2 * ( r + w ) - 8;
cost[4] = r * w - cost[2] - cost[3];
}
}
void print(){
for(int i = 0 ; i < 5 ; i++)
cout << cost[i] << ' ';
cout << endl;
}
void Solve(int cases){
int ans = 0;
int r, w, n;
cin >> r >> w >> n;
calc(r, w);
int now = r * w - n, x = 4;
print();
while(now){
int tmp = min(now, cost[x] / (x + 1) + cost[x] % (x+1));
now -= tmp;
cost[x] -= tmp;
int de = tmp * x;
for(int i = x ; i >= 0 && de ; i--){
int r = min(de, cost[i]);
cost[i] -= r;
if(i)
cost[i-1] += r;
de -= r;
}
x--;
print();
}
for(int i = 0 ; i < 5 ; i++)
ans += cost[i] * i;
if(ans & 1)
cout << "=============gg================" << endl << endl;
cout << "Case #" << cases << ": " << ans / 2 << endl;
}
int main(){
int n;
cin >> n;
for(int i = 0 ; i < n ; i++)
Solve(i+1);
return 0;
}
| [
"wingemerald@gmail.com"
] | wingemerald@gmail.com |
be6ee0b7cfc792f211296919aa75266a77bc673b | 890577a365ee41df5ec3d1c347fc3294122d1f96 | /Heros Game - C++/Thief.h | 1e6d2fc91dd418f2ca85f0d4b5c867c3300d4ad9 | [] | no_license | michaltalmor/Practical-projects | d01377888c5bdbdb3d00f6d944ac2d352909faf7 | 70af317818f997c6c7acfa54d8f73a6373e2e2fd | refs/heads/master | 2020-06-17T01:52:19.062064 | 2020-02-17T14:45:01 | 2020-02-17T14:45:01 | 195,759,681 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 341 | h | /*
* Thief.h
*
* Created on: Dec 25, 2018
* Author: ise
*/
#ifndef THIEF_H_
#define THIEF_H_
#include <string>
#include "Hero.h"
using namespace std;
class Thief : public Hero {
public:
Thief(string name):Hero(name, "Thief"){}
~Thief();
bool specialAbility(Hero& other);
bool specialAbility();
};
#endif /* THIEF_H_ */
| [
"noreply@github.com"
] | noreply@github.com |
9ec2e72c6feea44e9fea99a4007e7603793b0bce | a6e826224b4288004ab04ec49c878fc7a415e3b3 | /ClientMain.cpp | c4e9b66f4da93c9f07bf564fda93196f4a6a6fe5 | [] | no_license | sunchao4991/ChatRoom | 9bf09a8d2836e0edfecf36dab588294dc6c54094 | 95f124681ebd3f7688fa240deab23605ba159edb | refs/heads/master | 2020-05-05T13:40:31.850891 | 2019-04-08T07:00:04 | 2019-04-08T07:00:04 | 180,088,545 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 138 | cpp | //
//ClientMain.cpp
//chatroom
//
#include "Client.h"
int main(int argc, char *argv[]) {
Client client;
client.start();
return 0;
}
| [
"sunchao4991@163.com"
] | sunchao4991@163.com |
bbafc14486580435fad20e200de0cb690e359afd | bd7fd14de907e42bffa0691f5cfff1f8d11a3194 | /passManager/template.h | 028c1a8146691341186e8ba6168e4161dcb6095d | [] | no_license | yklym/passManagerCppQt | 62e665b53b88372846bd1024e1ca4697152c1ecb | a5c70448da6ee0df36f4aed90ec5af8b42500c29 | refs/heads/master | 2020-12-23T16:00:03.187492 | 2020-01-30T11:27:07 | 2020-01-30T11:27:07 | 237,198,298 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,098 | h | #ifndef TEMPLATE_H
#define TEMPLATE_H
#pragma once
#include <string>
#include <iostream>
#include <cstdio>
#include <vector>
#include <QString>
#include <QtCore>
#include<rpc/msgpack.hpp>
//
using std::string;
using std::vector;
struct Template
{
int id;
string login;
string password;
string pass_strength;
string description;
MSGPACK_DEFINE_ARRAY(id, login, password,pass_strength,description);
Template(){} // default
Template(int id, string login, string password, string pass_strength, string description){
this->id = id;
this->login = login;
this->password = password;
this->pass_strength = pass_strength;
this->description = description;
}
Template(const Template & other){
this->id = other.id;
this->login = other.login;
this->password = other.password;
this->pass_strength = other.pass_strength;
this->description = other.description;
}
};
Q_DECLARE_METATYPE(Template)
//Q_DECLARE_METATYPE(Student);
#endif // TEMPLATE_H
| [
"yaroslaw.klymko@gmail.com"
] | yaroslaw.klymko@gmail.com |
4daf52a11f37e4bdf016506e6b8713d43df0f1ba | d53362b59f80d96f902b0bfa7c4fd0530a79aeba | /type_names.hpp | 8b82f452ce1e875f71b3aef33f76a2bc596699e4 | [
"MIT"
] | permissive | milasudril/strint | ffcb8e5b3663bafc7e03cd3c4f0a3929f342e45b | a7f26ca3c89e0f15d195337c60b9ee389b92b549 | refs/heads/master | 2020-03-09T07:37:53.435767 | 2018-06-23T03:17:58 | 2018-06-23T03:17:58 | 128,668,570 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,397 | hpp | //@ {"targets":[{"name":"type_names.hpp","type":"include"}]}
#ifndef STRINT_STRINT_NAMES_HPP
#define STRINT_STRINT_NAMES_HPP
#include <cstdint>
namespace Strint
{
template<class T>
struct TypeInfo
{};
enum class TypeId:int
{
Int8
,UInt8
,Int16
,UInt16
,Int32
,UInt32
,Int64
,UInt64
};
template<>
struct TypeInfo<int8_t>
{
static constexpr const char* name="i08";
static constexpr auto id=TypeId::Int8;
};
template<>
struct TypeInfo<int16_t>
{
static constexpr const char* name="i10";
static constexpr auto id=TypeId::Int16;
};
template<>
struct TypeInfo<int32_t>
{
static constexpr const char* name="i20";
static constexpr auto id=TypeId::Int32;
};
template<>
struct TypeInfo<int64_t>
{
static constexpr const char* name="i40";
static constexpr auto id=TypeId::Int64;
};
template<>
struct TypeInfo<uint8_t>
{
static constexpr const char* name="u08";
static constexpr auto id=TypeId::UInt8;
};
template<>
struct TypeInfo<uint16_t>
{
static constexpr const char* name="u10";
static constexpr auto id=TypeId::UInt16;
};
template<>
struct TypeInfo<uint32_t>
{
static constexpr const char* name="u20";
static constexpr auto id=TypeId::UInt32;
};
template<>
struct TypeInfo<uint64_t>
{
static constexpr const char* name="u40";
static constexpr auto id=TypeId::UInt64;
};
}
#endif
| [
"milasudril@gmail.com"
] | milasudril@gmail.com |
b91b8fd8c59257e2a36506bd697d24ba1a861577 | 092d638d7e00daeac2b08a448c78dabb3030c5a9 | /gcj/gcj/188266/Mystic/168107/0/extracted/main.cpp | cd56b8e920a7da4a847ac6e1f184fc095eb1f7ef | [] | no_license | Yash-YC/Source-Code-Plagiarism-Detection | 23d2034696cda13462d1f7596718a908ddb3d34e | 97cfdd458e851899b6ec6802a10343db68824b8b | refs/heads/main | 2023-08-03T01:43:59.185877 | 2021-10-04T15:00:25 | 2021-10-04T15:00:25 | 399,349,460 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,308 | cpp | #include <fstream>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <cmath>
#include <map>
using namespace std;
ifstream fin("A-small-attempt0.in");
ofstream fout("file.out");
map <pair<int, int>, bool> happy;
bool isHappy(int num, int base) {
if(happy.find(make_pair(num, base)) != happy.end())
return happy.find(make_pair(num, base))->second;
happy[make_pair(num, base)] = false;
int res = 0;
int n = num;
while(n != 0) {
int cur = n%base;
res += cur*cur;
n /= base;
}
if(isHappy(res, base))
return happy[make_pair(num, base)] = true;
else
return happy[make_pair(num, base)] = false;
}
int main() {
for(int base = 2; base < 11; base++)
happy[make_pair(1, base)] = true;
int T;
fin >> T;
string str;
getline(fin, str);
for(int i = 0; i < T; i++) {
vector<int> bases;
string str;
getline(fin, str);
istringstream input(str);
int temp = 0;
while(input >> temp)
bases.push_back(temp);
int result = 1;
bool b = false;
while(!b) {
b = true;
result++;
//cout << result++ << endl;
for(int j = 0; j < bases.size(); j++)
b = b && isHappy(result, bases[j]);
}
fout << "Case #" << i+1 << ": " << result << endl;
}
}
| [
"54931238+yash-YC@users.noreply.github.com"
] | 54931238+yash-YC@users.noreply.github.com |
04e205bd3b472a59d1affbad906b83c100cd68ec | 8a9bb0bba06a3fb9da06f48b5fb43af6a2a4bb47 | /LeetCode/RemoveDuplicatesFromSortedArray.h | 6d62c7a285dbb500fa09d306c84fe90801e70369 | [] | no_license | ruifshi/LeetCode | 4cae3f54e5e5a8ee53c4a7400bb58d177a560be8 | 11786b6bc379c7b09b3f49fc8743cc15d46b5c0d | refs/heads/master | 2022-07-14T09:39:55.001968 | 2022-06-26T02:06:00 | 2022-06-26T02:06:00 | 158,513,101 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 113 | h | #include <vector>
using namespace std;
class Solution {
public:
int removeDuplicates(vector<int>& nums);
}; | [
"ruifshi@hotmail.com"
] | ruifshi@hotmail.com |
e273e19a2a9a0b253cfe414ceb143e114711d9f4 | 62126238af2e3e85b9337f66293c2a29946aa2a1 | /framework/Thread/ThreadWUP/Headers/ThreadRunMethodWUP.h | 015e1d39dfe40093d9c59bb2b4913434056df89a | [
"MIT"
] | permissive | metalkin/kigs | b43aa0385bdd9a495c5e30625c33a170df410593 | 87d1757da56a5579faf1d511375eccd4503224c7 | refs/heads/master | 2021-02-28T10:29:30.443801 | 2020-03-06T13:39:38 | 2020-03-06T13:51:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 991 | h | #ifndef _THREADRUNMETHODWUP_H_
#define _THREADRUNMETHODWUP_H_
#include <windows.h>
#include "ThreadRunMethod.h"
// ****************************************
// * ThreadRunMethodWUP class
// * --------------------------------------
/*! \class ThreadRunMethodWUP
Windows threadrun class
\ingroup ThreadWindows
*/
// ****************************************
class ThreadRunMethodWUP : public ThreadRunMethod
{
public:
DECLARE_CLASS_INFO(ThreadRunMethodWUP,ThreadRunMethod,Thread)
ThreadRunMethodWUP(const kstl::string& name,DECLARE_CLASS_NAME_TREE_ARG);
virtual void waitDeath(unsigned long P_Time_Out = 0xFFFFFFFF);
virtual void sleepThread();
virtual void wakeUpThread();
virtual void setAffinityMask(int mask);
protected:
//! destructor
virtual ~ThreadRunMethodWUP();
//! internal thread start
virtual void StartThread();
//! internal thread end
virtual void EndThread();
HANDLE myHandle;
DWORD myThreadId;
};
#endif //_THREADRUNMETHODWUP_H_
| [
"antoine.fresse@assoria.com"
] | antoine.fresse@assoria.com |
cbf8997d373fe5f5e3352b04a4030c1f0933e403 | 3457d7cb2c7e48ff8cc2a359f8f8e5a92ecddc47 | /Source/InputMonitor.h | 368db148117d9dbc0dddbac7a50b647dadb66915 | [] | no_license | 467-Audio-Loop/467-Audio-Loop-Station | d02f9c4c0ebd18974eb2c0f3d6a1962a37cc21a7 | d5145249f1ef9cb94484113263f5b0cfe844b74e | refs/heads/master | 2023-03-13T04:12:16.356267 | 2021-03-10T18:59:00 | 2021-03-10T18:59:00 | 331,146,728 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,676 | h | /*
==============================================================================
InputMonitor.h
//DN: A simple AudioSource class where we can send the audio input in buffer
form, to be read from by our main mixer
==============================================================================
*/
#pragma once
#include <JuceHeader.h>
class InputMonitor : public juce::AudioSource
{
public:
InputMonitor()
{
inputBuffer.reset(new juce::AudioBuffer<float>(2, 0));
}
~InputMonitor(){}
void prepareToPlay(int samplesPerBlockExpected, double sampleRate){}
void releaseResources(){}
void getNextAudioBlock(const juce::AudioSourceChannelInfo& bufferToFill)
{
int loopBufferSize = inputBuffer->getNumSamples();
int maxInChannels = inputBuffer->getNumChannels();
int maxOutChannels = bufferToFill.buffer->getNumChannels();
if (loopBufferSize > 0 && maxInChannels > 0)
{
for (int i = 0; i < maxOutChannels; ++i)
{
auto writer = bufferToFill.buffer->getWritePointer(i, bufferToFill.startSample);
for (auto sample = 0; sample < bufferToFill.numSamples; ++sample)
{
writer[sample] = inputBuffer->getSample(i % maxInChannels, juce::jmin(sample, loopBufferSize)) * gain;
}
}
}
}
void setBuffer(juce::AudioSampleBuffer* newBuffer)
{
inputBuffer.reset(newBuffer);
}
void setGain(double newGain)
{
gain = newGain;
}
private:
std::unique_ptr<juce::AudioBuffer<float>> inputBuffer;
double gain = 1.0;
}; | [
"dnegovan@gmail.com"
] | dnegovan@gmail.com |
4cb688a817df4f5d51f860fe14abae287cfb60dc | 3cf9e141cc8fee9d490224741297d3eca3f5feff | /C++ Benchmark Programs/Benchmark Files 1/classtester/autogen-sources/source-13334.cpp | 7c9219a74de84c0d21da1864d61e06d99ceb640e | [] | no_license | TeamVault/tauCFI | e0ac60b8106fc1bb9874adc515fc01672b775123 | e677d8cc7acd0b1dd0ac0212ff8362fcd4178c10 | refs/heads/master | 2023-05-30T20:57:13.450360 | 2021-06-14T09:10:24 | 2021-06-14T09:10:24 | 154,563,655 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,343 | cpp | struct c0;
void __attribute__ ((noinline)) tester0(c0* p);
struct c0
{
bool active0;
c0() : active0(true) {}
virtual ~c0()
{
tester0(this);
active0 = false;
}
virtual void f0(){}
};
void __attribute__ ((noinline)) tester0(c0* p)
{
p->f0();
}
struct c1;
void __attribute__ ((noinline)) tester1(c1* p);
struct c1 : c0
{
bool active1;
c1() : active1(true) {}
virtual ~c1()
{
tester1(this);
c0 *p0_0 = (c0*)(c1*)(this);
tester0(p0_0);
active1 = false;
}
virtual void f1(){}
};
void __attribute__ ((noinline)) tester1(c1* p)
{
p->f1();
if (p->active0)
p->f0();
}
struct c2;
void __attribute__ ((noinline)) tester2(c2* p);
struct c2 : c0
{
bool active2;
c2() : active2(true) {}
virtual ~c2()
{
tester2(this);
c0 *p0_0 = (c0*)(c2*)(this);
tester0(p0_0);
active2 = false;
}
virtual void f2(){}
};
void __attribute__ ((noinline)) tester2(c2* p)
{
p->f2();
if (p->active0)
p->f0();
}
struct c3;
void __attribute__ ((noinline)) tester3(c3* p);
struct c3 : virtual c2, virtual c1
{
bool active3;
c3() : active3(true) {}
virtual ~c3()
{
tester3(this);
c0 *p0_0 = (c0*)(c2*)(c3*)(this);
tester0(p0_0);
c0 *p0_1 = (c0*)(c1*)(c3*)(this);
tester0(p0_1);
c1 *p1_0 = (c1*)(c3*)(this);
tester1(p1_0);
c2 *p2_0 = (c2*)(c3*)(this);
tester2(p2_0);
active3 = false;
}
virtual void f3(){}
};
void __attribute__ ((noinline)) tester3(c3* p)
{
p->f3();
if (p->active1)
p->f1();
if (p->active2)
p->f2();
}
struct c4;
void __attribute__ ((noinline)) tester4(c4* p);
struct c4 : virtual c1, virtual c2, virtual c3
{
bool active4;
c4() : active4(true) {}
virtual ~c4()
{
tester4(this);
c0 *p0_0 = (c0*)(c1*)(c4*)(this);
tester0(p0_0);
c0 *p0_1 = (c0*)(c2*)(c4*)(this);
tester0(p0_1);
c0 *p0_2 = (c0*)(c2*)(c3*)(c4*)(this);
tester0(p0_2);
c0 *p0_3 = (c0*)(c1*)(c3*)(c4*)(this);
tester0(p0_3);
c1 *p1_0 = (c1*)(c4*)(this);
tester1(p1_0);
c1 *p1_1 = (c1*)(c3*)(c4*)(this);
tester1(p1_1);
c2 *p2_0 = (c2*)(c4*)(this);
tester2(p2_0);
c2 *p2_1 = (c2*)(c3*)(c4*)(this);
tester2(p2_1);
c3 *p3_0 = (c3*)(c4*)(this);
tester3(p3_0);
active4 = false;
}
virtual void f4(){}
};
void __attribute__ ((noinline)) tester4(c4* p)
{
p->f4();
if (p->active1)
p->f1();
if (p->active2)
p->f2();
if (p->active3)
p->f3();
}
int __attribute__ ((noinline)) inc(int v) {return ++v;}
int main()
{
c0* ptrs0[25];
ptrs0[0] = (c0*)(new c0());
ptrs0[1] = (c0*)(c1*)(new c1());
ptrs0[2] = (c0*)(c2*)(new c2());
ptrs0[3] = (c0*)(c2*)(c3*)(new c3());
ptrs0[4] = (c0*)(c1*)(c3*)(new c3());
ptrs0[5] = (c0*)(c1*)(c4*)(new c4());
ptrs0[6] = (c0*)(c2*)(c4*)(new c4());
ptrs0[7] = (c0*)(c2*)(c3*)(c4*)(new c4());
ptrs0[8] = (c0*)(c1*)(c3*)(c4*)(new c4());
for (int i=0;i<9;i=inc(i))
{
tester0(ptrs0[i]);
delete ptrs0[i];
}
c1* ptrs1[25];
ptrs1[0] = (c1*)(new c1());
ptrs1[1] = (c1*)(c3*)(new c3());
ptrs1[2] = (c1*)(c4*)(new c4());
ptrs1[3] = (c1*)(c3*)(c4*)(new c4());
for (int i=0;i<4;i=inc(i))
{
tester1(ptrs1[i]);
delete ptrs1[i];
}
c2* ptrs2[25];
ptrs2[0] = (c2*)(new c2());
ptrs2[1] = (c2*)(c3*)(new c3());
ptrs2[2] = (c2*)(c4*)(new c4());
ptrs2[3] = (c2*)(c3*)(c4*)(new c4());
for (int i=0;i<4;i=inc(i))
{
tester2(ptrs2[i]);
delete ptrs2[i];
}
c3* ptrs3[25];
ptrs3[0] = (c3*)(new c3());
ptrs3[1] = (c3*)(c4*)(new c4());
for (int i=0;i<2;i=inc(i))
{
tester3(ptrs3[i]);
delete ptrs3[i];
}
c4* ptrs4[25];
ptrs4[0] = (c4*)(new c4());
for (int i=0;i<1;i=inc(i))
{
tester4(ptrs4[i]);
delete ptrs4[i];
}
return 0;
}
| [
"ga72foq@mytum.de"
] | ga72foq@mytum.de |
e7519bf4d5d22a572dbbdebc68b80642b41c8dd9 | 3e281819bd3706ba78d620e31dce1a02c3a43441 | /test-core/projection/main_test_projection.cpp | 8dd76ed64b8aad1f1c55cdcaf1fa429ee1fd399c | [] | no_license | janchk/corecvs | 69eeda1404d8c127fb16be7073b86e5044faf6d6 | 7f1ed44256dae0a950d49ac12c218b906522547f | refs/heads/master | 2020-08-01T21:25:20.864718 | 2019-12-06T12:07:20 | 2019-12-06T12:07:20 | 211,121,283 | 1 | 0 | null | 2019-12-06T12:07:22 | 2019-09-26T15:23:53 | null | UTF-8 | C++ | false | false | 12,929 | cpp | /**
* \file main_test_projection.cpp
* \brief This is the main file for the test projection
*
* \date янв 20, 2018
* \author alexander
*
* \ingroup autotest
*/
#include <iostream>
#include "gtest/gtest.h"
#include "core/cameracalibration/projection/equidistantProjection.h"
#include "core/cameracalibration/projection/equisolidAngleProjection.h"
#include "core/cameracalibration/projection/omnidirectionalProjection.h"
#include "core/cameracalibration/ilFormat.h"
#include "core/cameracalibration/cameraModel.h"
#include "core/utils/global.h"
#include "core/buffers/rgb24/rgb24Buffer.h"
#include "core/geometry/mesh3d.h"
#include "core/cameracalibration/calibrationDrawHelpers.h"
#include "core/fileformats/bmpLoader.h"
#include "core/fileformats/objLoader.h"
#include "core/buffers/bufferFactory.h"
using namespace std;
using namespace corecvs;
TEST(projection, testEquidistant)
{
EquidistantProjection projection;
Vector2dd source(Vector2dd(1.0, 1.0));
Vector3dd p = projection.reverse(source);
Vector2dd rsource = projection.project(p);
cout << "EquidistantProjection:" << endl
<< projection << endl;
cout << " Source: " << source << endl;
cout << " RayDir: " << p << endl;
cout << "RSource: " << rsource << endl;
ASSERT_TRUE(source.notTooFar(rsource, 1e-7));
}
TEST(projection, testEquisolid)
{
EquisolidAngleProjection projection;
Vector2dd source(Vector2dd(1.0, 1.0));
Vector3dd p = projection.reverse(source);
Vector2dd rsource = projection.project(p);
cout << "EquisolidAngleProjection:" << endl
<< projection << endl;
cout << " Source: " << source << endl;
cout << " RayDir: " << p << endl;
cout << "RSource: " << rsource << endl;
ASSERT_TRUE(source.notTooFar(rsource, 1e-7));
}
TEST(projection, testOmnidirectional)
{
OmnidirectionalProjection projection;
Vector2dd source(Vector2dd(1.0, 1.0));
Vector3dd p = projection.reverse(source);
cout << "Will call project" << endl;
Vector2dd rsource = projection.project(p);
cout << "OmnidirectionalBaseParameters:" << endl
<< projection << endl;
cout << " Source: " << source << endl;
cout << " RayDir: " << p << endl;
cout << "RSource: " << rsource << endl;
ASSERT_TRUE(source.notTooFar(rsource, 1e-7));
}
TEST(projection, testOmnidirectional1)
{
OmnidirectionalProjection projection;
projection.mN[0] = 0.1;
Vector2dd source(Vector2dd(1.0, 1.0));
Vector3dd p = projection.reverse(source);
cout << "Will call project" << endl;
Vector2dd rsource = projection.project(p);
cout << "OmnidirectionalBaseParameters:" << endl
<< projection << endl;
cout << " Source: " << source << endl;
cout << " RayDir: " << p << endl;
cout << "RSource: " << rsource << endl;
}
TEST(projection, testOmnidirectional2)
{
OmnidirectionalProjection projection;
projection.mN[0] = 0.1;
projection.mN[1] = 0.2;
Vector2dd source(Vector2dd(1.0, 1.0));
Vector3dd p = projection.reverse(source);
cout << "Will call project" << endl;
Vector2dd rsource = projection.project(p);
cout << "OmnidirectionalBaseParameters:" << endl
<< projection << endl;
cout << " Source: " << source << endl;
cout << " RayDir: " << p << endl;
cout << "RSource: " << rsource << endl;
ASSERT_TRUE(source.notTooFar(rsource, 1e-7));
}
TEST(projection, testOmnidirectional3)
{
OmnidirectionalProjection projection;
projection.mN = vector<double>({ -3.97282, -7.61552, 26.471, -43.6205});
Vector2dd source(Vector2dd(1.0, 1.0));
Vector3dd p = projection.reverse(source);
cout << "Will call project" << endl;
Vector2dd rsource = projection.project(p);
cout << "OmnidirectionalBaseParameters:" << endl
<< projection << endl;
cout << " Source: " << source << endl;
cout << " RayDir: " << p << endl;
cout << "RSource: " << rsource << endl;
ASSERT_TRUE(source.notTooFar(rsource, 1e-7));
}
TEST(projection, testFormatLoad)
{
std::string input =
"omnidirectional\n"
"1578 1.35292 1.12018 5 0.520776 -0.561115 -0.560149 1.01397 -0.870155";
std::istringstream ss(input);
unique_ptr<CameraProjection> model;
model.reset(ILFormat::loadIntrisics(ss));
std::ostringstream so;
so.imbue(std::locale("C"));
so << std::setprecision(std::numeric_limits<double>::digits10 + 2);
ILFormat::saveIntrisics(*(model.get()), so);
cout << so.str();
std::istringstream ss1(so.str());
unique_ptr<CameraProjection> model1;
model1.reset(ILFormat::loadIntrisics(ss1));
CORE_ASSERT_TRUE(model != NULL, "Model is NULL");
CORE_ASSERT_TRUE(model1 != NULL, "Model1 is NULL");
CORE_ASSERT_TRUE(model ->projection == ProjectionType::OMNIDIRECTIONAL, "Failed to load");
CORE_ASSERT_TRUE(model1->projection == ProjectionType::OMNIDIRECTIONAL, "Failed to resave");
OmnidirectionalProjection *o1 = static_cast<OmnidirectionalProjection *>(model .get());
OmnidirectionalProjection *o2 = static_cast<OmnidirectionalProjection *>(model1.get());
cout << "Old:" << *o1 << endl;
cout << "New:" << *o2 << endl;
CORE_ASSERT_TRUE(o1->principal().notTooFar(o2->principal()), "Failed to resave pos");
CORE_ASSERT_DOUBLE_EQUAL_E(o1->focal(), o2->focal(), 1e-7, "Failed to resave focal");
CORE_ASSERT_TRUE(o1->mN.size() == o2->mN.size(), "Failed to load params");
for (size_t i = 0; i < o1->mN.size(); i++)
{
CORE_ASSERT_DOUBLE_EQUAL_E(o1->mN[i], o2->mN[i], 1e-7, "Failed to load polynom");
}
}
TEST(projection, testProjectionChange)
{
#if 0
int h = 480;
int w = 640;
// RGB24Buffer *image = new RGB24Buffer(h,w);
RGB24Buffer *image = BufferFactory::getInstance()->loadRGB24Bitmap("data/pair/image0001_c0.pgm");
slowProjection.setSizeX(w);
slowProjection.setSizeY(h);
slowProjection.setPrincipalX(image->w / 2.0);
slowProjection.setPrincipalY(image->h / 2.0);
slowProjection.setFocal(image->w / 2.0);
CameraModel model(slowProjection.clone());
#else
std::string input =
"omnidirectional\n"
"1578 1.35292 1.12018 5 0.520776 -0.561115 -0.560149 1.01397 -0.870155";
std::istringstream ss(input);
CameraModel model;
model.intrinsics.reset(ILFormat::loadIntrisics(ss));
OmnidirectionalProjection slowProjection = * static_cast<OmnidirectionalProjection *>(model.intrinsics.get());
RGB24Buffer *image = new RGB24Buffer(slowProjection.sizeY(), slowProjection.sizeX());
image->checkerBoard(50, RGBColor::White());
#endif
cout << "Input model:" << endl;
cout << "=============================" << endl;
cout << model << endl;
cout << "=============================" << endl;
cout << "Input image:" << endl;
cout << image->getSize() << endl;
cout << "=============================" << endl;
Mesh3DDecorated mesh;
mesh.switchColor(true);
mesh.switchTextures(true);
mesh.setColor(RGBColor::Yellow());
CalibrationDrawHelpers draw;
Mesh3D toDraw;
toDraw.addIcoSphere(Vector3dd(0, 0, 100.0), 70, 2);
for (size_t i = 0; i < toDraw.vertexes.size(); i++)
{
Vector2dd prj = model.project(toDraw.vertexes[i]);
Vector2d<int> prji(fround(prj.x()), fround(prj.y()));
if (image->isValidCoord(prji)) {
image->element(prji) = RGBColor::Red();
}
}
draw.drawCameraEx(mesh, model, 5, 0);
mesh.dumpPLY("catadioptric.ply");
mesh.materials.push_back(OBJMaterial());
mesh.materials.front().name = "image1";
mesh.materials.front().tex[OBJMaterial::KOEF_AMBIENT] = new RGB24Buffer(image);
OBJLoader loader;
loader.saveMaterials("catadioptric.mtl", mesh.materials, "");
loader.saveObj("catadioptric", mesh);
/** Ok Equidistant **/
EquidistantProjection target;
target.setPrincipalX(slowProjection.principalX());
target.setPrincipalY(slowProjection.principalY());
target.setDistortedSizeX(slowProjection.distortedSizeX());
target.setDistortedSizeY(slowProjection.distortedSizeY());
target.setSizeX(slowProjection.sizeX());
target.setSizeY(slowProjection.sizeY());
cout << "EquidistantProjection" << endl;
cout << "Start Focal: " << slowProjection.focal() << endl;
double minF = 0;
double minFerr = std::numeric_limits<double>::max();
for (double f = slowProjection.focal() / 4.0; f < slowProjection.focal()*2; f*=1.1 )
{
target.setFocal(f);
double err = 0.0;
for (int i = 0; i < image->h; i++)
{
for (int j = 0; j < image->w; j++)
{
Vector2dd pixel(i, j);
Vector3dd dir = slowProjection.reverse(pixel);
Vector2dd map = target.project(dir);
double newErr = (map - pixel).l2Metric();
if (err < newErr) {
err = newErr;
}
}
}
if (err < minFerr) {
minFerr = err;
minF = f;
}
cout << "F is: " << f << " Max Diff is: " << err << "px" << endl;
}
#if 0
/** Ok Equisolid **/
EquisolidAngleProjection target1;
target1.setPrincipalX(slowProjection.principalX());
target1.setPrincipalY(slowProjection.principalY());
target1.setDistortedSizeX(slowProjection.distortedSizeX());
target1.setDistortedSizeY(slowProjection.distortedSizeY());
target1.setSizeX(slowProjection.sizeX());
target1.setSizeY(slowProjection.sizeY());
cout << "EquisolidAngleProjection" << endl;
cout << "Start Focal: " << slowProjection.focal() << endl;
double minF1 = 0;
double minFerr1 = std::numeric_limits<double>::max();
for (double f = slowProjection.focal() / 4.0; f < slowProjection.focal()*2; f*=1.1 )
{
target1.setFocal(f);
double err = 0.0;
for (int i = 0; i < image->h; i++)
{
for (int j = 0; j < image->w; j++)
{
Vector2dd pixel(i, j);
Vector3dd dir = slowProjection.reverse(pixel);
Vector2dd map = target1.project(dir);
double newErr = (map - pixel).l2Metric();
if (err < newErr) {
err = newErr;
}
}
}
if (err < minFerr) {
minFerr1 = err;
minF1 = f;
}
cout << "F is: " << f << " Max Diff is: " << err << "px" << endl;
}
/** Stereographic **/
StereographicProjection target2;
target2.setPrincipalX(slowProjection.principalX());
target2.setPrincipalY(slowProjection.principalY());
target2.setDistortedSizeX(slowProjection.distortedSizeX());
target2.setDistortedSizeY(slowProjection.distortedSizeY());
target2.setSizeX(slowProjection.sizeX());
target2.setSizeY(slowProjection.sizeY());
cout << "Stereographic" << endl;
cout << "Start Focal: " << slowProjection.focal() << endl;
double minF2 = 0;
double minFerr2 = std::numeric_limits<double>::max();
for (double f = slowProjection.focal() / 16.0; f < slowProjection.focal()*2; f*=1.1 )
{
target2.setFocal(f);
double err = 0.0;
for (int i = 0; i < image->h; i++)
{
for (int j = 0; j < image->w; j++)
{
Vector2dd pixel(i, j);
Vector3dd dir = slowProjection.reverse(pixel);
Vector2dd map = target2.project(dir);
double newErr = (map - pixel).l2Metric();
if (err < newErr) {
err = newErr;
}
}
}
if (err < minFerr) {
minFerr2 = err;
minF2 = f;
}
cout << "F is: " << f << " Max Diff is: " << err << "px" << endl;
}
#endif
/* From the remap buffer */
target.setFocal(minF);
cout << "Using focal:" << minF << endl;
AbstractBuffer<Vector2dd> *displacement = new AbstractBuffer<Vector2dd>(image->h, image->w);
/**
*
* 2D -> catadioptric -> 3D
* 2D <- remap <- 2D <- equiditstant -> 3D
*
*
**/
for (int i = 0; i < image->h; i++)
{
for (int j = 0; j < image->w; j++)
{
Vector2dd pixel(j, i); /* This is a remap pixel */
Vector3dd dir = target.reverse(pixel);
Vector2dd map = slowProjection.project(dir);
/* We need to imvent something */
if (displacement->isValidCoord(i, j)) {
displacement->element(i, j) = Vector2dd(map.x(), map.y());
}
}
}
RGB24Buffer *disp = new RGB24Buffer(displacement->getSize());
disp->drawDoubleVecBuffer(displacement);
BMPLoader().save("catad.bmp", image);
BMPLoader().save("catad-disp.bmp", disp);
}
| [
"calvrack@googlemail.com"
] | calvrack@googlemail.com |
4ac28716c8b08bb45743be6f82e9ecea18d539e6 | 11c74b57455ce2454849fbe9a73a2e0d2a3542d2 | /contests/2020多校联合训练/杭电/题解/杭电ACM多校2020-1/2020 MUTC KUT Round/Codes/Submissions/boring-task-correct.cpp | 9d145aacb14860ac7ddb8aafc69fee31af1febab | [] | no_license | heyuhhh/ACM | 4fe0239b7f55a62db5bc47aaf086e187134fb7e6 | e1ea34686b41a6c5b3f395dd9c76472220e9db5d | refs/heads/master | 2021-06-25T03:59:51.580876 | 2021-04-27T07:22:51 | 2021-04-27T07:22:51 | 223,877,467 | 9 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,251 | cpp | #include <bits/stdc++.h>
using namespace std;
const long long inf = 1LL << 60;
long long correct_solution(int n, const vector<long long> &T, const vector<int> &D) {
vector<pair<long long, int>> a(n + 1);
vector<long long> s(n + 1, 0);
for (int i = 1; i <= n; i++) a[i].first = T[i];
for (int i = 1; i <= n; i++) a[i].second = D[i];
sort(a.begin() + 1, a.end());
for (int i = 1; i <= n; i++) s[i] = s[i - 1] + a[i].second;
vector<int> next(n + 1);
for (int i = n; i > 0; i--) {
next[i] = i + 1;
for (int &j = next[i]; j <= n && a[i].first + a[i].second > a[j].first + a[j].second; j = next[j]);
}
vector<vector<long long>> b(18, vector<long long>(n + 1));
const long long inf = 1LL << 60;
for (int i = 1; i <= n; i++) b[0][i] = a[i].first - s[i - 1];
for (int i = 1; 1 << i <= n; i++) {
for (int j = 1; j <= n; j++) b[i][j] = max(b[i - 1][j], (j + (1 << i - 1) <= n ? b[i - 1][j + (1 << i - 1)] : -inf));
}
auto bmax = [&](int l, int r) {
if (l > r) return -inf;
int k = 31 - __builtin_clz(r - l + 1);
return max(b[k][l], b[k][r - (1 << k) + 1]);
};
vector<long long> dp(n + 2);
vector<int> q(n + 1);
auto check = [&](long long t) {
dp[n + 1] = inf;
int qn = 0;
for (int i = n, j = n; i > 0; i--) {
while (j > i && a[j].first >= a[i].first + t) j--;
dp[i] = -inf;
q[qn++] = i + 1;
while (qn > 0) {
int u = q[qn - 1];
if (u > min(j + 1, next[i])) break;
long long cur = (u == i + 1 ? a[i].first - s[i] : bmax(i + 1, u - 1));
long long now = min(dp[u], a[i].first + a[i].second + t);
if (now - s[u - 1] >= cur + a[i].second) dp[i] = max(dp[i], now - s[u - 1] + s[i - 1]);
if (a[i].first + a[i].second + t >= dp[u]) qn--;
else break;
}
if (dp[i] < a[i].first) return false;
}
return true;
};
long long lo = -1, hi = 1LL << 50;
while (hi - lo > 1) {
long long mid = lo + hi >> 1;
(check(mid) ? hi : lo) = mid;
}
return hi;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int ncase;
for (cin >> ncase; ncase--; ) {
int n; cin >> n;
vector<long long> A(n + 1);
vector<int> B(n + 1);
for (int i = 1; i <= n; i++) cin >> A[i];
for (int i = 1; i <= n; i++) cin >> B[i];
cout << correct_solution(n, A, B) << "\n";
}
return 0;
}
| [
"2468861298@qq.com"
] | 2468861298@qq.com |
284892787e5e08cacabf32991abb9697d46b6690 | d61d05748a59a1a73bbf3c39dd2c1a52d649d6e3 | /chromium/net/base/expiring_cache.h | a22497b76e51d1ed546def6a0b80a9c1ec117e83 | [
"BSD-3-Clause"
] | permissive | Csineneo/Vivaldi | 4eaad20fc0ff306ca60b400cd5fad930a9082087 | d92465f71fb8e4345e27bd889532339204b26f1e | refs/heads/master | 2022-11-23T17:11:50.714160 | 2019-05-25T11:45:11 | 2019-05-25T11:45:11 | 144,489,531 | 5 | 4 | BSD-3-Clause | 2022-11-04T05:55:33 | 2018-08-12T18:04:37 | null | UTF-8 | C++ | false | false | 7,627 | 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 NET_BASE_EXPIRING_CACHE_H_
#define NET_BASE_EXPIRING_CACHE_H_
#include <stddef.h>
#include <map>
#include <utility>
#include "base/gtest_prod_util.h"
#include "base/macros.h"
#include "base/time/time.h"
namespace net {
template <typename KeyType,
typename ValueType,
typename ExpirationType>
class NoopEvictionHandler {
public:
void Handle(const KeyType& key,
const ValueType& value,
const ExpirationType& expiration,
const ExpirationType& now,
bool onGet) const {
}
};
// Cache implementation where all entries have an explicit expiration policy. As
// new items are added, expired items will be removed first.
// The template types have the following requirements:
// KeyType must be LessThanComparable, Assignable, and CopyConstructible.
// ValueType must be CopyConstructible and Assignable.
// ExpirationType must be CopyConstructible and Assignable.
// ExpirationCompare is a function class that takes two arguments of the
// type ExpirationType and returns a bool. If |comp| is an instance of
// ExpirationCompare, then the expression |comp(current, expiration)| shall
// return true iff |current| is still valid within |expiration|.
//
// A simple use of this class may use base::TimeTicks, which provides a
// monotonically increasing clock, for the expiration type. Because it's always
// increasing, std::less<> can be used, which will simply ensure that |now| is
// sorted before |expiration|:
//
// ExpiringCache<std::string, std::string, base::TimeTicks,
// std::less<base::TimeTicks> > cache(0);
// // Add a value that expires in 5 minutes
// cache.Put("key1", "value1", base::TimeTicks::Now(),
// base::TimeTicks::Now() + base::TimeDelta::FromMinutes(5));
// // Add another value that expires in 10 minutes.
// cache.Put("key2", "value2", base::TimeTicks::Now(),
// base::TimeTicks::Now() + base::TimeDelta::FromMinutes(10));
//
// Alternatively, there may be some more complex expiration criteria, at which
// point a custom functor may be used:
//
// struct ComplexExpirationFunctor {
// bool operator()(const ComplexExpiration& now,
// const ComplexExpiration& expiration) const;
// };
// ExpiringCache<std::string, std::string, ComplexExpiration,
// ComplexExpirationFunctor> cache(15);
// // Add a value that expires once the 'sprocket' has 'cog'-ified.
// cache.Put("key1", "value1", ComplexExpiration("sprocket"),
// ComplexExpiration("cog"));
template <typename KeyType,
typename ValueType,
typename ExpirationType,
typename ExpirationCompare,
typename EvictionHandler = NoopEvictionHandler<KeyType,
ValueType,
ExpirationType> >
class ExpiringCache {
private:
// Intentionally violate the C++ Style Guide so that EntryMap is known to be
// a dependent type. Without this, Clang's two-phase lookup complains when
// using EntryMap::const_iterator, while GCC and MSVC happily resolve the
// typename.
// Tuple to represent the value and when it expires.
typedef std::pair<ValueType, ExpirationType> Entry;
typedef std::map<KeyType, Entry> EntryMap;
public:
typedef KeyType key_type;
typedef ValueType value_type;
typedef ExpirationType expiration_type;
// This class provides a read-only iterator over items in the ExpiringCache
class Iterator {
public:
explicit Iterator(const ExpiringCache& cache)
: cache_(cache),
it_(cache_.entries_.begin()) {
}
~Iterator() {}
bool HasNext() const { return it_ != cache_.entries_.end(); }
void Advance() { ++it_; }
const KeyType& key() const { return it_->first; }
const ValueType& value() const { return it_->second.first; }
const ExpirationType& expiration() const { return it_->second.second; }
private:
const ExpiringCache& cache_;
// Use a second layer of type indirection, as both EntryMap and
// EntryMap::const_iterator are dependent types.
typedef typename ExpiringCache::EntryMap EntryMap;
typename EntryMap::const_iterator it_;
};
// Constructs an ExpiringCache that stores up to |max_entries|.
explicit ExpiringCache(size_t max_entries) : max_entries_(max_entries) {}
~ExpiringCache() {}
// Returns the value matching |key|, which must be valid at the time |now|.
// Returns NULL if the item is not found or has expired. If the item has
// expired, it is immediately removed from the cache.
// Note: The returned pointer remains owned by the ExpiringCache and is
// invalidated by a call to a non-const method.
const ValueType* Get(const KeyType& key, const ExpirationType& now) {
typename EntryMap::iterator it = entries_.find(key);
if (it == entries_.end())
return NULL;
// Immediately remove expired entries.
if (!expiration_comp_(now, it->second.second)) {
Evict(it, now, true);
return NULL;
}
return &it->second.first;
}
// Updates or replaces the value associated with |key|.
void Put(const KeyType& key,
const ValueType& value,
const ExpirationType& now,
const ExpirationType& expiration) {
typename EntryMap::iterator it = entries_.find(key);
if (it == entries_.end()) {
// Compact the cache if it grew beyond the limit.
if (entries_.size() == max_entries_ )
Compact(now);
// No existing entry. Creating a new one.
entries_.insert(std::make_pair(key, Entry(value, expiration)));
} else {
// Update an existing cache entry.
it->second.first = value;
it->second.second = expiration;
}
}
// Empties the cache.
void Clear() {
entries_.clear();
}
// Returns the number of entries in the cache.
size_t size() const { return entries_.size(); }
// Returns the maximum number of entries in the cache.
size_t max_entries() const { return max_entries_; }
bool empty() const { return entries_.empty(); }
private:
FRIEND_TEST_ALL_PREFIXES(ExpiringCacheTest, Compact);
FRIEND_TEST_ALL_PREFIXES(ExpiringCacheTest, CustomFunctor);
// Prunes entries from the cache to bring it below |max_entries()|.
void Compact(const ExpirationType& now) {
// Clear out expired entries.
typename EntryMap::iterator it;
for (it = entries_.begin(); it != entries_.end(); ) {
if (!expiration_comp_(now, it->second.second)) {
Evict(it++, now, false);
} else {
++it;
}
}
if (entries_.size() < max_entries_)
return;
// If the cache is still too full, start deleting items 'randomly'.
for (it = entries_.begin();
it != entries_.end() && entries_.size() >= max_entries_;) {
Evict(it++, now, false);
}
}
void Evict(typename EntryMap::iterator it,
const ExpirationType& now,
bool on_get) {
eviction_handler_.Handle(it->first, it->second.first, it->second.second,
now, on_get);
entries_.erase(it);
}
// Bound on total size of the cache.
size_t max_entries_;
EntryMap entries_;
ExpirationCompare expiration_comp_;
EvictionHandler eviction_handler_;
DISALLOW_COPY_AND_ASSIGN(ExpiringCache);
};
} // namespace net
#endif // NET_BASE_EXPIRING_CACHE_H_
| [
"csineneo@gmail.com"
] | csineneo@gmail.com |
d6d3d952d69b567a49aeb8713958b9e556b4c87e | 94c8615196a08aa8704a56bb650fa1f49903592e | /sandbox/fft_single/proj/solution1/syn/systemc/fft_top.h | 98be0a72eee3bafab7b80e76d37e9f6423acb36b | [
"MIT"
] | permissive | trevor-crowley/mylab | ee78b4096767567b195a4f31bf21096a33a90ae0 | aa5af79c5aae47696697d058a6b906ba875dcd48 | refs/heads/master | 2021-05-09T02:28:58.804785 | 2021-04-16T17:12:43 | 2021-04-16T17:12:43 | 119,201,767 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,636 | h | // ==============================================================
// RTL generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and OpenCL
// Version: 2020.1
// Copyright (C) 1986-2020 Xilinx, Inc. All Rights Reserved.
//
// ===========================================================
#ifndef _fft_top_HH_
#define _fft_top_HH_
#include "systemc.h"
#include "AESL_pkg.h"
#include "dummy_proc_fe.h"
#include "fft_config1_s.h"
#include "dummy_proc_be.h"
#include "fifo_w16_d1_A.h"
#include "fifo_w32_d1_A.h"
#include "fifo_w8_d1_A.h"
#include "start_for_fft_conbkb.h"
#include "start_for_dummy_pcud.h"
namespace ap_rtl {
struct fft_top : public sc_module {
// Port declarations 18
sc_in< sc_logic > direction;
sc_in< sc_lv<32> > in_r_dout;
sc_in< sc_logic > in_r_empty_n;
sc_out< sc_logic > in_r_read;
sc_out< sc_lv<32> > out_r_din;
sc_in< sc_logic > out_r_full_n;
sc_out< sc_logic > out_r_write;
sc_out< sc_logic > ovflo_din;
sc_in< sc_logic > ovflo_full_n;
sc_out< sc_logic > ovflo_write;
sc_in_clk ap_clk;
sc_in< sc_logic > ap_rst;
sc_in< sc_logic > direction_ap_vld;
sc_out< sc_logic > direction_ap_ack;
sc_in< sc_logic > ap_start;
sc_out< sc_logic > ap_done;
sc_out< sc_logic > ap_ready;
sc_out< sc_logic > ap_idle;
sc_signal< sc_logic > ap_var_for_const0;
// Module declarations
fft_top(sc_module_name name);
SC_HAS_PROCESS(fft_top);
~fft_top();
sc_trace_file* mVcdFile;
ofstream mHdltvinHandle;
ofstream mHdltvoutHandle;
dummy_proc_fe* dummy_proc_fe_U0;
fft_config1_s* fft_config1_U0;
dummy_proc_be* dummy_proc_be_U0;
fifo_w16_d1_A* fft_config_data_V_U;
fifo_w32_d1_A* xn_channel_U;
fifo_w32_d1_A* xk_channel_U;
fifo_w8_d1_A* fft_status_data_V_U;
start_for_fft_conbkb* start_for_fft_conbkb_U;
start_for_dummy_pcud* start_for_dummy_pcud_U;
sc_signal< sc_logic > dummy_proc_fe_U0_ap_start;
sc_signal< sc_logic > dummy_proc_fe_U0_start_full_n;
sc_signal< sc_logic > dummy_proc_fe_U0_ap_done;
sc_signal< sc_logic > dummy_proc_fe_U0_ap_continue;
sc_signal< sc_logic > dummy_proc_fe_U0_ap_idle;
sc_signal< sc_logic > dummy_proc_fe_U0_ap_ready;
sc_signal< sc_logic > dummy_proc_fe_U0_start_out;
sc_signal< sc_logic > dummy_proc_fe_U0_start_write;
sc_signal< sc_lv<1> > dummy_proc_fe_U0_direction;
sc_signal< sc_logic > dummy_proc_fe_U0_direction_ap_ack;
sc_signal< sc_lv<16> > dummy_proc_fe_U0_config_data_V_din;
sc_signal< sc_logic > dummy_proc_fe_U0_config_data_V_write;
sc_signal< sc_logic > dummy_proc_fe_U0_in_r_read;
sc_signal< sc_lv<32> > dummy_proc_fe_U0_out_r_din;
sc_signal< sc_logic > dummy_proc_fe_U0_out_r_write;
sc_signal< sc_logic > fft_config1_U0_ap_start;
sc_signal< sc_logic > fft_config1_U0_ap_done;
sc_signal< sc_logic > fft_config1_U0_ap_idle;
sc_signal< sc_logic > fft_config1_U0_ap_ready;
sc_signal< sc_logic > fft_config1_U0_ap_continue;
sc_signal< sc_logic > fft_config1_U0_xn_read;
sc_signal< sc_lv<32> > fft_config1_U0_xk_din;
sc_signal< sc_logic > fft_config1_U0_xk_write;
sc_signal< sc_lv<8> > fft_config1_U0_status_data_V_din;
sc_signal< sc_logic > fft_config1_U0_status_data_V_write;
sc_signal< sc_logic > fft_config1_U0_config_ch_data_V_read;
sc_signal< sc_logic > dummy_proc_be_U0_ap_start;
sc_signal< sc_logic > dummy_proc_be_U0_ap_done;
sc_signal< sc_logic > dummy_proc_be_U0_ap_continue;
sc_signal< sc_logic > dummy_proc_be_U0_ap_idle;
sc_signal< sc_logic > dummy_proc_be_U0_ap_ready;
sc_signal< sc_logic > dummy_proc_be_U0_status_in_data_V_read;
sc_signal< sc_logic > dummy_proc_be_U0_ovflo_din;
sc_signal< sc_logic > dummy_proc_be_U0_ovflo_write;
sc_signal< sc_logic > dummy_proc_be_U0_in_r_read;
sc_signal< sc_lv<32> > dummy_proc_be_U0_out_r_din;
sc_signal< sc_logic > dummy_proc_be_U0_out_r_write;
sc_signal< sc_logic > ap_sync_continue;
sc_signal< sc_logic > fft_config_data_V_full_n;
sc_signal< sc_lv<16> > fft_config_data_V_dout;
sc_signal< sc_logic > fft_config_data_V_empty_n;
sc_signal< sc_logic > xn_channel_full_n;
sc_signal< sc_lv<32> > xn_channel_dout;
sc_signal< sc_logic > xn_channel_empty_n;
sc_signal< sc_logic > xk_channel_full_n;
sc_signal< sc_lv<32> > xk_channel_dout;
sc_signal< sc_logic > xk_channel_empty_n;
sc_signal< sc_logic > fft_status_data_V_full_n;
sc_signal< sc_lv<8> > fft_status_data_V_dout;
sc_signal< sc_logic > fft_status_data_V_empty_n;
sc_signal< sc_logic > ap_sync_done;
sc_signal< sc_logic > ap_sync_ready;
sc_signal< sc_lv<1> > start_for_fft_config1_U0_din;
sc_signal< sc_logic > start_for_fft_config1_U0_full_n;
sc_signal< sc_lv<1> > start_for_fft_config1_U0_dout;
sc_signal< sc_logic > start_for_fft_config1_U0_empty_n;
sc_signal< sc_lv<1> > start_for_dummy_proc_be_U0_din;
sc_signal< sc_logic > start_for_dummy_proc_be_U0_full_n;
sc_signal< sc_lv<1> > start_for_dummy_proc_be_U0_dout;
sc_signal< sc_logic > start_for_dummy_proc_be_U0_empty_n;
sc_signal< sc_logic > fft_config1_U0_start_full_n;
sc_signal< sc_logic > fft_config1_U0_start_write;
sc_signal< sc_logic > dummy_proc_be_U0_start_full_n;
sc_signal< sc_logic > dummy_proc_be_U0_start_write;
static const sc_logic ap_const_logic_0;
static const sc_lv<32> ap_const_lv32_0;
static const sc_logic ap_const_logic_1;
// Thread declarations
void thread_ap_var_for_const0();
void thread_ap_done();
void thread_ap_idle();
void thread_ap_ready();
void thread_ap_sync_continue();
void thread_ap_sync_done();
void thread_ap_sync_ready();
void thread_direction_ap_ack();
void thread_dummy_proc_be_U0_ap_continue();
void thread_dummy_proc_be_U0_ap_start();
void thread_dummy_proc_be_U0_start_full_n();
void thread_dummy_proc_be_U0_start_write();
void thread_dummy_proc_fe_U0_ap_continue();
void thread_dummy_proc_fe_U0_ap_start();
void thread_dummy_proc_fe_U0_direction();
void thread_dummy_proc_fe_U0_start_full_n();
void thread_fft_config1_U0_ap_continue();
void thread_fft_config1_U0_ap_start();
void thread_fft_config1_U0_start_full_n();
void thread_fft_config1_U0_start_write();
void thread_in_r_read();
void thread_out_r_din();
void thread_out_r_write();
void thread_ovflo_din();
void thread_ovflo_write();
void thread_start_for_dummy_proc_be_U0_din();
void thread_start_for_fft_config1_U0_din();
void thread_hdltv_gen();
};
}
using namespace ap_rtl;
#endif
| [
"trevor.crowley@henryschein.ca"
] | trevor.crowley@henryschein.ca |
fdab3c1ab7184c550f79b21aa4315d2b3a95c80e | 29f8c69e01b997d46ad5c59b2995b35cbd031f7e | /Project 3/Field.h | e9e9d3c2317511cba4b15b8e0745749b0df52c18 | [] | no_license | RichAguil/CSCI-335-Algorithms | 8cd3f59295bc0f396d57dca4ea65be49617abddc | e562e1011ddc8e5597e90c33fbf2171f655473bc | refs/heads/master | 2023-02-01T05:34:59.256557 | 2020-12-17T23:21:20 | 2020-12-17T23:21:20 | 315,523,706 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 492 | h | #ifndef FIELD_H
#define FIELD_H
#include <vector>
class Field {
private:
int length = 0;
int height = 0;
std::vector<std::vector<int>> storageMatrix;
std::vector<std::vector<int>> weightMatrix;
public:
Field(const std::vector<std::vector<int>>& input);
Field(std::vector<std::vector<int>>&& input);
int Weight(int x1, int y1, int x2, int y2);
int PathCost();
void printMatrix();
};
#include "Field.cpp"
#endif | [
"ryaguilar23@gmail.com"
] | ryaguilar23@gmail.com |
706d11affd951feaad37a7784e73150aefc5094c | f3e95d0d6b87e7330f3ddc20b00df0673bcbc08b | /HPSEvioReader/Headbank.cpp | 8764a7112adb692639aecaa1e2c4914cd57f81e6 | [] | no_license | JeffersonLab/EvioTool | 88525821760d91da12827ea2214d107ffd4d1424 | 942cb3dfc7454bb3ff6435aca01a13f9c725829c | refs/heads/master | 2022-09-26T10:16:17.013108 | 2022-09-15T20:09:44 | 2022-09-15T20:09:44 | 164,700,955 | 2 | 1 | null | 2022-04-24T20:56:55 | 2019-01-08T17:34:44 | Java | UTF-8 | C++ | false | false | 157 | cpp | //
// Headbank.cpp
// HPSEvioReader
//
// Created by Maurik Holtrop on 6/18/19.
// Copyright © 2019 UNH. All rights reserved.
//
#include "Headbank.h"
| [
"maurik@physics.unh.edu"
] | maurik@physics.unh.edu |
ab715dfcb4a00257e43ff080eb6eb1d46dddd162 | 03faee3398730eb8b7b94c2d124aa1b66c02893d | /OceanLight/3rd/algServer/common/IMP_FrameQueue.cpp | 727be9808e175707ba6b3a060e36d6c31c9bc00e | [] | no_license | bianshifeng/OceanLight | a80829c6021662e22e987f0ddb12b3839c5c7ef2 | 697106f43397467966b76586862c1283d4326ed2 | refs/heads/master | 2021-01-13T14:05:26.721466 | 2017-05-03T07:48:57 | 2017-05-03T07:48:57 | 76,212,078 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,278 | cpp | #include "QDebug"
#include "IMP_FrameQueue.h"
#include "imp_algo_type.h"
IMP_FrameQueue::IMP_FrameQueue():
m_nQueueLen(0),
m_peekFlag(0),
m_queueHead(0),
m_queueTail(0),
m_queueMaxSize(DEFAULT_MAX_FRAME_QUEUE_SIZE),
m_nMallocWidth(DEFAULT_MALLOC_WIDTH),
m_nMallocHeight(DEFAULT_MALLOC_HEIGHT)
{
}
IMP_FrameQueue::IMP_FrameQueue(int maxQueueSize, int nMallocWidth, int nMallocHeight):
m_nQueueLen(0),
m_peekFlag(0),
m_queueHead(0),
m_queueTail(0),
m_queueMaxSize(maxQueueSize),
m_nMallocWidth(nMallocWidth),
m_nMallocHeight(nMallocHeight)
{
}
int IMP_FrameQueue::GetFrameQueueLen()
{
IMP_Lock queuelock(&m_queueLock);
return m_nQueueLen;
}
int IMP_FrameQueue::InitFrameQueue()
{
IMP_Lock queuelock(&m_queueLock);//need this line
m_pArrayFrames = new IMP_PicOutFrame[m_queueMaxSize];
if (NULL == m_pArrayFrames)
{
///IMP_LOG_ERROR("New Array Frame Failed");
qDebug() << "New Array Frame Failed";
}
int nImgSize = m_nMallocWidth * m_nMallocHeight * 4;
for (int i=0; i<m_queueMaxSize; i++)
{
m_pArrayFrames[i].nWidth = m_nMallocWidth;
m_pArrayFrames[i].nHeight = m_nMallocHeight;
m_pArrayFrames[i].pu8D1 = new uchar[nImgSize];
m_pArrayFrames[i].pu8D2 = m_pArrayFrames[i].pu8D1 + m_pArrayFrames[i].nWidth * m_pArrayFrames[i].nHeight;
m_pArrayFrames[i].pu8D3 = m_pArrayFrames[i].pu8D2 + m_pArrayFrames[i].nWidth * m_pArrayFrames[i].nHeight / 4;
m_pArrayFrames[i].pResult = new char[ALGO_RESULT_DATA_SIZE];
m_pArrayFrames[i].nFrameNo = 0;
m_pArrayFrames[i].nFrameTime = 0;
m_pArrayFrames[i].nUseFlag = 0;
m_pArrayFrames[i].nResFlag = 0;
m_pArrayFrames[i].nImgFormat = IMG_FORMAT_RGB;
}
return IMP_TRUE;
}
IMP_FrameQueue::~IMP_FrameQueue()
{
ClearQueue();
IMP_Lock queuelock(&m_queueLock);
if (NULL != m_pArrayFrames)
{
for (int i=0; i< m_queueMaxSize; i++)
{
if( NULL != m_pArrayFrames[i].pu8D1 )
{
delete[] m_pArrayFrames[i].pu8D1;
delete[] m_pArrayFrames[i].pResult;
}
}
delete[] m_pArrayFrames;
m_pArrayFrames = NULL;
}
}
void IMP_FrameQueue::setMallocWidth(const int &width)
{
m_nMallocWidth = width;
}
void IMP_FrameQueue::setMallocHeight(const int &height)
{
m_nMallocHeight = height;
}
int IMP_FrameQueue::IsEmpty()
{
IMP_Lock queuelock(&m_queueLock);
return (m_queueHead == m_queueTail)?IMP_TRUE:IMP_FALSE;
}
int IMP_FrameQueue::IsFull()
{
IMP_Lock queuelock(&m_queueLock);
int tailTest = (m_queueTail + 1) % m_queueMaxSize;
return (tailTest == m_queueHead)?IMP_TRUE:IMP_FALSE;
}
IMP_PicOutFrame* IMP_FrameQueue::GetFrameAddr()
{
IMP_Lock queuelock(&m_queueLock);
int tailTest;
tailTest = (m_queueTail + 1) % m_queueMaxSize;
if ( tailTest == m_queueHead )
{
///IMP_LOG_DEBUG("FRAME QUEUE IS FULL");
//qDebug() << "FRAME QUEUE IS FULL";
return NULL;///IMP_FALSE;//IMP_TRUE;
}
IMP_PicOutFrame* pOutFrame = &m_pArrayFrames[m_queueTail];
m_queueTail = (m_queueTail + 1) % m_queueMaxSize;
m_nQueueLen++;
return pOutFrame;
}
IMP_PicOutFrame* IMP_FrameQueue::FindMatchFrameAddr(int nFrameNo)
{
IMP_Lock queuelock(&m_queueLock);
int i;
IMP_PicOutFrame* ret = NULL;
if(m_queueHead < m_queueTail) {
for(i=m_queueHead; i< m_queueTail; i++) {
if(m_pArrayFrames[i].nFrameNo == nFrameNo) {
ret = &m_pArrayFrames[i];
break;
}
}
}else if(m_queueHead > m_queueTail){
for(i=m_queueHead; i<m_queueMaxSize; i++) {
if(m_pArrayFrames[i].nFrameNo == nFrameNo) {
ret = &m_pArrayFrames[i];
break;
}
}
for(i=0; i<m_queueTail; i++ ) {
if(m_pArrayFrames[i].nFrameNo == nFrameNo) {
ret = &m_pArrayFrames[i];
break;
}
}
}
return ret;
}
int IMP_FrameQueue::PeekFrame(IMP_PicOutFrame** pPicOutFrame)
{
IMP_Lock queuelock(&m_queueLock);
if( m_queueHead == m_queueTail )
{
*pPicOutFrame = NULL;
return IMP_FALSE;
}
m_peekFlag = 1;
*pPicOutFrame=&m_pArrayFrames[m_queueHead];
return IMP_TRUE;
}
int IMP_FrameQueue::EndPeek()
{
IMP_Lock queuelock(&m_queueLock);
m_peekFlag = 0;
return IMP_TRUE;
}
int IMP_FrameQueue::RemoveFrame()
{
IMP_Lock queuelock(&m_queueLock);
m_peekFlag = 0;//EndPeek();
if( m_queueHead == m_queueTail ) //add by 0416 a bug
{
return IMP_TRUE;
}
m_pArrayFrames[m_queueHead].nUseFlag = 0;
m_pArrayFrames[m_queueHead].nResFlag = 0;
m_queueHead = (m_queueHead + 1) % m_queueMaxSize;
m_nQueueLen--;
return IMP_TRUE;
}
int IMP_FrameQueue::ClearQueue()
{
m_nQueueLen = 0;
m_queueHead = 0;
m_queueTail = 0;
return 1;
/*
while (1)
{
{
IMP_Lock queuelock(&m_queueLock);
m_nQueueLen = 0; // added by cw 2016/01/03
if ( 0 == m_peekFlag )
{
m_queueHead = 0;
m_queueTail = 0;
/////IMP_LOG_DEBUG("Test Clear Queue Successfully");
qDebug() << "Test Clear Frame Queue Successfully";
return IMP_TRUE;
}
/////IMP_LOG_DEBUG("Test Clear Queue Failed");
qDebug() << "Test Clear Frame Queue Failed";
}
Sleep(4);
}
*/
}
| [
"bianshifeng@ctvit.com.cn"
] | bianshifeng@ctvit.com.cn |
560fc2169c5e1ed9eeaf599fcbe17340ba0e1eb6 | 630cca2388c9a003bafeb0a5c4cd095ca41b54d9 | /Code/Engine/Network/NetConnection.cpp | cf172a9fb86a5e6628ae949c7be8039c91573f5f | [] | no_license | Junwon/JyakuhaiEngine | 49992bd787f3829694b0839d3ddf89b012d68d2a | 6a348ac351c910ef5965e80f908bb9eabd5d362b | refs/heads/master | 2021-05-09T12:03:01.272209 | 2018-01-26T04:05:53 | 2018-01-26T04:05:53 | 119,003,626 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 43 | cpp | #include "Engine/Network/NetConnection.hpp" | [
"johnnguyen@smu.edu"
] | johnnguyen@smu.edu |
72913508a09eb01094be3cd29acd1896ee22babe | 38b9daafe39f937b39eefc30501939fd47f7e668 | /tutorials/2WayCouplingOceanWave3D/EvalResults180628-Eta-ux-uy/28.4/uniform/time | 062a37e07379a9cb82eb7fb1bdb546b61694eeb4 | [] | no_license | rubynuaa/2-way-coupling | 3a292840d9f56255f38c5e31c6b30fcb52d9e1cf | a820b57dd2cac1170b937f8411bc861392d8fbaa | refs/heads/master | 2020-04-08T18:49:53.047796 | 2018-08-29T14:22:18 | 2018-08-29T14:22:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,003 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 3.0.1 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
location "28.4/uniform";
object time;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
value 28.4000000000000021;
name "28.4";
index 3220;
deltaT 0.0077037;
deltaT0 0.0077037;
// ************************************************************************* //
| [
"abenaz15@etudiant.mines-nantes.fr"
] | abenaz15@etudiant.mines-nantes.fr | |
72c7acdbe0a22563f9c34c884d8c6cd122334b8b | 03700e2ff7e48ca17443bf8aa3611e634a0acdc8 | /source/Kernel/HardwareAbstraction/Network/UDP.cpp | 8e1bada80fec37b4b17ebc5de7d95844c95f7e43 | [] | no_license | Wannabe66/mx | 432aac7b4ac7998e61fe2e432e54d9a03226e37a | f4f73da9bb7c2c0760de920ec2cb931846b90a31 | refs/heads/master | 2021-01-18T13:14:08.905424 | 2015-03-08T11:45:48 | 2015-03-08T11:45:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,873 | cpp | // UDP.cpp
// Copyright (c) 2014 - The Foreseeable Future, zhiayang@gmail.com
// Licensed under the Apache License Version 2.0.
// implements a set of functions to support processing UDP packets
#include <Kernel.hpp>
#include <HardwareAbstraction/Network.hpp>
using namespace Library;
namespace Kernel {
namespace HardwareAbstraction {
namespace Network {
namespace UDP
{
struct UDPPacket
{
uint16_t sourceport;
uint16_t destport;
uint16_t length;
uint16_t checksum;
} __attribute__ ((packed));
static rde::hash_map<SocketFullMappingv4, Socket*>* udpsocketmapv4 = 0;
static rde::vector<uint16_t>* freeports = 0;
uint16_t AllocateEphemeralPort()
{
assert(freeports);
uint16_t ret = freeports->back();
freeports->pop_back();
Log("allocated udp port %d, %b", ret, freeports->contains(ret));
return ret;
}
void ReleaseEphemeralPort(uint16_t port)
{
if(!freeports->contains(port))
freeports->push_back(port);
}
bool IsDuplicatePort(uint16_t port)
{
return !(freeports->contains(port)) && port >= EPHEMERAL_PORT_RANGE;
}
void MapSocket(SocketFullMappingv4 addr, Socket* s)
{
if(udpsocketmapv4->find(addr) != udpsocketmapv4->end())
{
Log(1, "Socket (%d.%d.%d.%d:%d -> %d.%d.%d.%d:%d) already mapped, overriding",
addr.source.ip.b1, addr.source.ip.b2, addr.source.ip.b3, addr.source.ip.b4, addr.source.port,
addr.dest.ip.b1, addr.dest.ip.b2, addr.dest.ip.b3, addr.dest.ip.b4, addr.dest.port);
}
(*udpsocketmapv4)[addr] = s;
}
void UnmapSocket(SocketFullMappingv4 addr)
{
udpsocketmapv4->erase(addr);
}
void Initialise()
{
udpsocketmapv4 = new rde::hash_map<SocketFullMappingv4, Socket*>();
freeports = new rde::vector<uint16_t>();
for(uint16_t i = 49152; i < UINT16_MAX; i++)
freeports->push_back(i);
}
void SendIPv4Packet(Devices::NIC::GenericNIC* interface, uint8_t* packet, uint64_t length, Library::IPv4Address dest, uint16_t sourceport, uint16_t destport)
{
uint8_t* newbuf = new uint8_t[sizeof(UDPPacket) + length];
Memory::Copy(newbuf + sizeof(UDPPacket), packet, length);
UDPPacket* udp = (UDPPacket*) newbuf;
udp->sourceport = SwapEndian16(sourceport);
udp->destport = SwapEndian16(destport);
udp->length = SwapEndian16(length + sizeof(UDPPacket));
udp->checksum = 0;
IP::SendIPv4Packet(interface, newbuf, sizeof(UDPPacket) + (uint16_t) length, 459, dest, IP::ProtocolType::UDP);
}
void HandleIPv4Packet(Devices::NIC::GenericNIC* interface, void* packet, uint64_t length, IPv4Address source, IPv4Address destip)
{
UDPPacket* udp = (UDPPacket*) packet;
uint64_t actuallength = SwapEndian16(udp->length) - sizeof(UDPPacket);
uint16_t sourceport = SwapEndian16(udp->sourceport);
uint16_t destport = SwapEndian16(udp->destport);
// IPv4PortAddress target;
// target.ip = source;
// target.port = SwapEndian16(udp->destport);
bool triedonce = false;
// feel dirty
retry:
// check for full mapping.
bool found = false;
Socket* skt = (*udpsocketmapv4)[SocketFullMappingv4 { IPv4PortAddress { destip, destport }, IPv4PortAddress { source, sourceport } }];
if(skt)
found = true;
// multiphase search: check for sourceip + sourceport + destport
if(!skt && !found)
{
skt = (*udpsocketmapv4)[SocketFullMappingv4 { IPv4PortAddress { source, sourceport }, IPv4PortAddress { IPv4Address { 0xFFFFFFFF }, destport } }];
if(skt)
found = true;
}
// check for sourceip + destport
if(!skt && !found)
{
skt = (*udpsocketmapv4)[SocketFullMappingv4 { IPv4PortAddress { source, 0 }, IPv4PortAddress { IPv4Address { 0xFFFFFFFF}, destport } }];
if(skt)
found = true;
}
// check for sourceport + destport
if(!skt && !found)
{
skt = (*udpsocketmapv4)[SocketFullMappingv4 { IPv4PortAddress { IPv4Address { 0 }, sourceport }, IPv4PortAddress { IPv4Address { 0xFFFFFFFF }, destport } }];
if(skt)
found = true;
}
// finally, only destport.
if(!skt && !found)
{
skt = (*udpsocketmapv4)[SocketFullMappingv4 { IPv4PortAddress { IPv4Address { 0 }, 0 }, IPv4PortAddress { IPv4Address { 0xFFFFFFFF }, destport } }];
if(skt)
found = true;
}
if(found)
{
// send into socket buffer.
skt->recvbuffer.Write((uint8_t*) packet + sizeof(UDPPacket), actuallength);
// skt->packetsizes->Write(actuallength);
// skt->packetcount++;
return;
}
// if we got here, it didn't find.
if(!triedonce)
{
triedonce = true;
source = IPv4Address { 0 };
goto retry;
}
Log("No open UDP sockets found for target, discarding packet.");
UNUSED(interface);
UNUSED(length);
}
void HandleIPv6Packet(Devices::NIC::GenericNIC* interface, void* packet, uint64_t length, IPv6Address source, IPv6Address destip)
{
UNUSED(interface);
UNUSED(packet);
UNUSED(length);
UNUSED(source);
UNUSED(destip);
HALT("UDP over IPv6 not implemented.");
}
}
}
}
}
| [
"zhiayang@gmail.com"
] | zhiayang@gmail.com |
015fbd307bc7f856cc906e082a8890b0638c90ac | 9ad4e9b71adff85887c615af63cd29be49f2216f | /Contest10/TaskA/main.cpp | e88f6463849465a846f4fce854b53f02c9f72ce6 | [] | no_license | VodimShilin/Algo_2sem_Vadim_Shilin | f9e27adaa51d3c3ac20eee5ecb5af183fed61cac | 0c76c5a098fde93bc394769c313ff707a5cfb6b2 | refs/heads/main | 2023-06-14T03:41:54.036840 | 2021-07-07T14:20:31 | 2021-07-07T14:20:31 | 342,899,112 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,964 | cpp | #include <iostream>
#include <vector>
constexpr long long INF = 2'147'483'647;
struct Edge{
Edge() = default;
Edge(const Edge&) = default;
Edge(Edge&& another): x(another.x), y(another.y), w(another.w), index(another.index) {}
Edge reverse() {
std::swap(x, y);
return *this;
}
long long x;
long long y;
long long w;
long long index;
};
std::istream& operator>>(std::istream& in, Edge& e) {
in >> e.x >> e.y >> e.w;
--e.x;
--e.y;
return in;
}
class Graph{
public:
Graph(long long n, std::vector<Edge>&& edge): n(n), m(edge.size()), edges(std::move(edge)), min_edge_into_vertice(n, -1),
matrix_of_adjacency(n) {
for (int i = 0; i < m; ++i) {
if (edges[i].y == 0 && (min_edge_into_vertice[edges[i].x] == -1 || edges[min_edge_into_vertice[edges[i].x]].w > edges[i].w)) {
min_edge_into_vertice[edges[i].x] = i;
}
if (edges[i].x == 0 && (min_edge_into_vertice[edges[i].y] == -1 || edges[min_edge_into_vertice[edges[i].y]].w > edges[i].w)) {
min_edge_into_vertice[edges[i].y] = i;
}
matrix_of_adjacency[edges[i].x].push_back(edges[i]);
matrix_of_adjacency[edges[i].y].push_back(edges[i].reverse());
}
}
long long Prime() {
if (n == 1) return 0;
std::vector<bool> used(n, 0);
long long sum = 0;
used[0] = 1;
for (int i = 1; i < n; ++i) {
long long min = -1;
for (int j = 0; j < n; ++j) {
if (!used[j] and min_edge_into_vertice[j] != -1 and (min == -1 or edges[min_edge_into_vertice[j]].w < edges[min_edge_into_vertice[min]].w)) {
min = j;
}
}
used[min] = 1;
sum += edges[min_edge_into_vertice[min]].w;
for (int j = 0; j < matrix_of_adjacency[min].size(); ++j) {
if (!used[matrix_of_adjacency[min][j].y] and (min_edge_into_vertice[matrix_of_adjacency[min][j].y] == -1 or edges[min_edge_into_vertice[matrix_of_adjacency[min][j].y]].w > matrix_of_adjacency[min][j].w)) {
min_edge_into_vertice[matrix_of_adjacency[min][j].y] = matrix_of_adjacency[min][j].index;
}
}
}
return sum;
}
private:
long long n;
long long m;
std::vector<Edge> edges;
std::vector<long long> min_edge_into_vertice;
std::vector<std::vector<Edge>> matrix_of_adjacency;
std::vector<std::vector<long long>> number_of_edge;
std::vector<std::vector<long long>> list_of_adjacency;
std::vector<std::vector<long long>> matrix_of_incidence;
};
int main() {
long long n, m;
std::cin >> n >> m;
std::vector<Edge> edges(m);
for (int i = 0; i < m; ++i) {
std::cin >> edges[i];
edges[i].index = i;
}
Graph g = Graph(n, std::move(edges));
std::cout << g.Prime();
return 0;
}
| [
"VodimShilin"
] | VodimShilin |
81745a4ffcb1ae254b7cf6548f178e7ac69dbd5f | 1a65adea801d4bbd2510006830d1f7573a5c9434 | /version1.5/sxEngine/sxRender/sxShader3D.cpp | eeb12e5ef8be09a0a5190de45719d4da935e2ad0 | [] | no_license | seganx/old-engine | 4ed9d6165a6ed884b9e44cd10e2c451dc169d543 | e5b9fbc07632c870acb96b8448b5c9591111080c | refs/heads/master | 2020-08-08T21:23:26.885808 | 2019-10-09T13:18:03 | 2019-10-09T13:18:03 | 213,920,786 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,666 | cpp | #include "sxShader3D.h"
#include "sxDevice3D.h"
#include "sxResource3D.h"
namespace sx { namespace d3d {
Shader3D::Shader3D( void ): m_Effect(NULL), m_curTech(NULL)
{
}
Shader3D::~Shader3D( void )
{
//Resource3D::ReleaseEffect(m_Effect);
}
bool Shader3D::Exist( void )
{
return m_Effect != NULL;
}
bool Shader3D::CompileShader( const WCHAR* code, SQ_ ShaderQuality quality, const WCHAR* userLog /*= NULL*/ )
{
sx_callstack_param(Shader3D::CompileShader(code, quality, %s), userLog);
if ( !Device3D::GetDevice() || !code ) return false;
// create macro for shader compiler
char* preproc = NULL;
switch (quality)
{
case SQ_HIGH: preproc = "#define QUALITY_HIGH\r\n"; break;
case SQ_MEDIUM: preproc = "#define QUALITY_MEDIUM\r\n"; break;
case SQ_LOW: preproc = "#define QUALITY_LOW\r\n"; break;
}
int preproclen = (int)strlen(preproc);
// prepare source code for compiling
int srcCodeLen = (int)wcslen(code) + preproclen;
if (srcCodeLen<30) return false;
char* srcCode = (char*)sx_mem_alloc(srcCodeLen+1);
ZeroMemory(srcCode, srcCodeLen+1);
for (int i=0; preproc[i]; srcCode[i]=preproc[i], i++);
for (int i=0; code[i]; srcCode[i+preproclen]=(int)code[i], i++);
// create and compile the effect
Resource3D::ReleaseEffect(m_Effect);
bool result = Resource3D::CreateEffect(srcCode, m_Effect, userLog);
// free allocated buffers
sx_mem_free(srcCode);
m_curTech = NULL;
return result;
}
bool Shader3D::GetDesc( D3DShaderDesc& desc )
{
ZeroMemory(&desc, sizeof(D3DShaderDesc));
if (!m_Effect) return false;
return SUCCEEDED ( m_Effect->GetDesc(&desc) );
}
D3DShaderHandle Shader3D::GetRenderTechnique( int index )
{
if (!m_Effect) return NULL;
return m_Effect->GetTechnique(index);
}
D3DShaderHandle Shader3D::GetRenderTechnique( const char* name )
{
if (!m_Effect) return NULL;
return m_Effect->GetTechniqueByName(name);
}
void Shader3D::SetRenderTechnique( D3DShaderHandle rTech )
{
if (!m_Effect || m_curTech == rTech) return;
m_curTech = rTech;
// force to change effect
Device3D::SetEffect(NULL);
m_Effect->SetTechnique(rTech);
}
FORCEINLINE D3DShaderHandle Shader3D::GetParameter( int index )
{
if (!m_Effect) return NULL;
return m_Effect->GetParameter(NULL, index);
}
FORCEINLINE D3DShaderHandle Shader3D::GetParameter( const char* name )
{
if (!m_Effect) return NULL;
return m_Effect->GetParameterByName(NULL, name);
}
int Shader3D::GetParameter( const char* semantic, PD3DShaderHandle paramHandle /*= NULL*/ )
{
if (!m_Effect) return -1;
D3DShaderHandle tmp = NULL;
tmp = m_Effect->GetParameterBySemantic(NULL, semantic);
if (tmp)
{
if (paramHandle)
*paramHandle = tmp;
}
else return -1;
D3DShaderDesc desc;
m_Effect->GetDesc(&desc);
for (int i=0; i<(int)desc.Parameters; i++)
{
if (m_Effect->GetParameter(NULL, i) == tmp)
return i;
}
return -1;
}
FORCEINLINE void Shader3D::SetValue( D3DShaderHandle hParam, const void* pData, UINT numBytes )
{
sx_callstack();
if (!m_Effect || !hParam) return;
m_Effect->SetValue(hParam, pData, numBytes);
}
FORCEINLINE bool Shader3D::GetValue( D3DShaderHandle hParam, void* pData, UINT numBytes )
{
if (!m_Effect || !hParam) return false;
return SUCCEEDED( m_Effect->GetValue(hParam, pData, numBytes) );
}
FORCEINLINE void Shader3D::SetMatrixArray( D3DShaderHandle hParam, const PMatrix pMatrix, UINT Count )
{
if (!m_Effect || !hParam) return;
m_Effect->SetMatrixArray(hParam, pMatrix, Count);
}
bool Shader3D::GetParameterDesc( int index, OUT D3DShaderParamDesc& desc )
{
if (!m_Effect) return false;
D3DShaderHandle tmp = NULL;
tmp = m_Effect->GetParameter(NULL, index);
if (!tmp) return false;
return SUCCEEDED( m_Effect->GetParameterDesc(tmp, &desc) );
}
D3DShaderHandle Shader3D::GetAnnotation( int paramIndex, OUT D3DShaderParamDesc& anno, int annoIndex )
{
if (!m_Effect) return NULL;
D3DShaderHandle tmp = NULL;
tmp = m_Effect->GetParameter(NULL, paramIndex);
if (!tmp) return NULL;
D3DShaderHandle annotmp = NULL;
annotmp = m_Effect->GetAnnotation(tmp, annoIndex);
if (!annotmp) return NULL;
if ( SUCCEEDED ( m_Effect->GetParameterDesc(annotmp, &anno) ) )
return annotmp;
else
return NULL;
}
FORCEINLINE void Shader3D::SetToDevice( void )
{
sx_callstack();
d3d::Device3D::SetEffect( m_Effect );
}
}} // namespace sx { namespace d3d {
| [
"seganx@38cbe2c2-61fc-4d10-a75b-7a9200028551"
] | seganx@38cbe2c2-61fc-4d10-a75b-7a9200028551 |
a9a5573ac9e460a0ca4ef832d197e9a06f39ad0a | e37d0e2adfceac661fbd844912d22c25d91f3cc0 | /CPP-Data-Structure/appendix-b/b05_switch_case.cpp | 8a43ebbf9e9cffd0679dd6254ddb28779b9ec11b | [] | no_license | mikechen66/CPP-Programming | 7638927918f59302264f40bbca4ffbfe17398ec6 | c49d6d197cad3735d60351434192938c95f8abe7 | refs/heads/main | 2023-07-11T20:27:12.236223 | 2021-08-26T08:50:37 | 2021-08-26T08:50:37 | 384,588,683 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,025 | cpp |
/* Execute switch-case statement */
#include<iostream>
using namespace std;
int main(void){
int a,b;
cout<<"==============================================="<<endl;
cout<<"Integer four operations"<<endl;
cout<<"Please input two numbers:";
cin>>a>>b;
cout<<"Please input the necessaryoperator (+,-,*,/):";
char s;
cin>>s;
switch(s){
case '+':
cout<<a<<"+"<<b<<"="<<a+b<<endl;
break;
case '-':
cout<<a<<"-"<<b<<"="<<a-b<<endl;
break;
case '*':
cout<<a<<"*"<<b<<"="<<a*b<<endl;
break;
case '/':
cout<<a<<"/"<<b<<"="<<a/b<<endl;
break;
default:
cout<<"Input error"<<endl;
break;
}
return 0;
}
/* Output */
/*
===============================================
Integer four operations
Please input two numbers:21 23
Please input the necessaryoperator (+,-,*,/):+
21+23=44
*/ | [
"noreply@github.com"
] | noreply@github.com |
33d49197da978435cebc245590b0842de1a59e9f | a008b112837ba18b5a3325bf559a78a1993d0717 | /courses/clang/No4/13_thousand.cpp | cfb35647c021c889852bd78c53b70329533bc140 | [] | no_license | jokerlee/college | 4509aadc180ad2a4e11dc19e56af2b9f4cd6ba03 | 3fbbb79d86b25e55a68141c3ee1292af0b48af1a | refs/heads/master | 2020-12-24T16:49:24.656255 | 2014-01-31T04:19:45 | 2014-01-31T04:19:45 | 16,399,338 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,174 | cpp | /*
Name:13.千分位
Copyright: free
Author: Joker Lee
Date: 31/10/06 21:40
Description: 将输入的数从个位起,每三位之间加一个逗号
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int div=1;//除数,用于将数字三位三位地分开
int i=0;//储存数字的位数
int j=0, k = 0,;
int result;//result用于储存分离后的三位
int num, tempnum;//tempnum用于计算位数
printf ("n=");
scanf ("%d", &num);
tempnum = num;
while (tempnum/10){//用循环计算数字的位数储存于i
i++;
tempnum/=10;
}
while (j < i-i%3){//初始化第一个除数,如一个8位数,第一个除数为 1e6
div *= 10;
j++;
}
while (div > 0){
result = num/div;
printf ("%d", temp);
if (num > 10000)//省去个位后的逗号
printf (", ");
num %= div;//去除已经打印的部分
div /= 1000;
}
system ("pause");
return 0;
}
| [
"lijie@hortorgames.com"
] | lijie@hortorgames.com |
62892045c535458db0cbe770eb4799896df96c5c | 17f913bb741911b547948cc7300be5600fef4dfd | /Devices/Generic HTTP Device/NodeMCU.ino | b11d857c7e09ed5f37b8821956cc90f4221a3d37 | [
"Apache-2.0"
] | permissive | asushugo/SmartThings | bfe21c89a385577a9582d62242d5ef16b4a4a7f1 | 43deff26b04c4836f0360e7c6077f15221b5f9bd | refs/heads/master | 2020-03-12T05:49:29.258907 | 2018-02-02T17:07:54 | 2018-02-02T17:07:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 39,671 | ino | /**
* ESP8266-12E / NodeMCU / WeMos D1 Mini WiFi & ENC28J60 Sample v1.0.20171030
* Source code can be found here: https://github.com/JZ-SmartThings/SmartThings/blob/master/Devices/Generic%20HTTP%20Device
* Copyright 2017 JZ
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
* for the specific language governing permissions and limitations under the License.
*/
#include <EEPROM.h>
#include <stdlib.h> // Needed for data type conversions like atoi
#ifdef ESP8266 // Needed for system_get_chip_id()
extern "C" {
#include "user_interface.h"
}
#endif
// SET YOUR NETWORK MODE TRUE TO USE WIFI OR FALSE FOR ENC28J60 --- DO NOT COMMENT OUT & USE TRUE/FALSE INSTEAD
#define useWIFI true
const char* ssid = "WIFI_SSID";
const char* password = "WIFI_PASSWORD";
// WHICH PINS ARE USED FOR TRIGGERS
// IF USING 3.3V RELAY, TRANSISTOR OR MOSFET THEN TOGGLE Use5Vrelay FLAG TO FALSE USING THE HTTP UI
int relayPin1 = D1; // GPIO5 = D1 // Eco Plugs by KAB or WiOn uses D8 or GPIO15 // Sonoff use D6 or GPIO12
int relayPin2 = D2; // GPIO4 = D2 // Eco Plugs D3 or GPIO0 for WiFi LED
bool Use5Vrelay; // Value defaults by reading eeprom in the setup method & configured via HTTP
// PHYSICAL POWER BUTTON & LEDs --- COMMENT OUT INDIVIDUAL ITEMS TO BYPASS THEIR LOGIC
//#define physicalButton D3 // Eco Plugs or WiOn D7 or GPIO13 // Sonoff D3 or GPIO0 // OITTM D3
#define physicalLED D4 // Eco Plugs or WiOn D3 or GPIO2 // Sonoff D7 or GPIO13 // OITTM D7 // NodeMCU Red LED is D0, GPIO16 or LED_BUILTIN and Blue LED D4 or GPIO2
//#define physicalLED2 D5 // OITTM D5
// USE BASIC HTTP AUTH --- COMMENT OUT TO BYPASS
// #define useAuth
// DESIGNATE CONTACT SENSOR PINS --- ENABLED VIA HTTP UI & STORED ON EEPROM NO NEED TO COMMENT OUT TO DISABLE
#define SENSORPIN D4 // what pin is the Contact Sensor on?
#define SENSORPIN2 D0 // what pin is the 2nd Contact Sensor on?
// USE DHT TEMP/HUMIDITY SENSOR DESIGNATE WHICH PIN BELOW & PICK DHTTYPE BELOW ALSO --- COMMENT OUT LINE BELOW TO BYPASS DHT LOGIC
//#define useDHT
#ifdef useDHT
#define DHTPIN D3 // what pin is the DHT on?
#include <DHT.h> // Use library version 1.2.3 as 1.3.0 gives error
// Uncomment whatever type of temperature sensor you're using!
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT22 // DHT 22 (AM2302)
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
DHT dht(DHTPIN, DHTTYPE);
#endif
// IF USING MQTT MODIFY TOPICS BELOW --- COMMENT OUT THE LINE BELOW TO BYPASS ALL MQTT LOGIC
//#define useMQTT
#ifdef useMQTT
const char* mqttServer = "192.168.0.200";
char buf[6];
const char* mqttClientName = itoa(system_get_chip_id(),buf,16); // MUST BE UNIQUE OR MQTT LOOP OCCURS
const char* mqttSwitch1Topic = "smartthings/Gate Switch/switch";
const char* mqttSwitch2Topic = "smartthings/Gate Switch 2/switch";
const char* mqttContact1Topic = "smartthings/Gate Switch/contact";
const char* mqttContact2Topic = "smartthings/Gate Switch 2/contact";
const char* mqttTemperatureTopic = "smartthings/Gate Switch/temperature";
const char* mqttHumidityTopic = "smartthings/Gate Switch/humidity";
// MQTT VARIABLES
long lastReconnectAttempt = 0; // don't send MQTT too often
const char* lastContact1Payload; const char* lastContact2Payload; // only send MQTT on changes
float lastTemperaturePayload = 0; float lastHumidityPayload = 0; // only send MQTT on changes
#endif
// OTHER VARIALBES
String currentIP, clientIP, request, fullrequest;
char *clientIPchar;
long lastButtonPush = 0; // physical button millis() for debouncing
// LOAD UP NETWORK LIB & PORT
#include <PubSubClient.h>
#if useWIFI==true
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266HTTPUpdateServer.h>
#include <ArduinoOTA.h>
WiFiServer server(80);
ESP8266WebServer httpServer(81);
ESP8266HTTPUpdateServer httpUpdater;
//MQTT
#ifdef useMQTT
WiFiClient espClient;
PubSubClient mqtt(espClient);
#endif
#else
#include <UIPEthernet.h>
EthernetServer server = EthernetServer(80);
#endif
void setup()
{
Serial.begin(115200);
#ifdef useDHT
dht.begin();
#endif
// PHYSICAL POWER BUTTON & LED
#ifdef physicalButton
pinMode(physicalButton, INPUT_PULLUP);
#endif
#ifdef physicalLED
pinMode(physicalLED, OUTPUT);
#endif
#ifdef physicalLED2
pinMode(physicalLED2, OUTPUT);
#endif
// DEFAULT CONFIG FOR CONTACT SENSOR
EEPROM.begin(1);
int ContactSensor = EEPROM.read(1);
if (ContactSensor != 0 && ContactSensor != 1) {
EEPROM.write(1, 0);
EEPROM.commit();
}
if (ContactSensor == 1) {
pinMode(SENSORPIN, INPUT_PULLUP);
}
else {
pinMode(SENSORPIN, OUTPUT);
digitalWrite(SENSORPIN2, HIGH);
}
// DEFAULT CONFIG FOR CONTACT SENSOR 2
EEPROM.begin(2);
int ContactSensor2 = EEPROM.read(2);
if (ContactSensor2 != 0 && ContactSensor2 != 1) {
EEPROM.write(2, 0);
EEPROM.commit();
}
if (ContactSensor2 == 1) {
pinMode(SENSORPIN2, INPUT_PULLUP);
}
else {
pinMode(SENSORPIN2, OUTPUT);
digitalWrite(SENSORPIN2, HIGH);
}
// DEFAULT CONFIG FOR USE5VRELAY
EEPROM.begin(5);
int eepromUse5Vrelay = EEPROM.read(5);
if (eepromUse5Vrelay != 0 && eepromUse5Vrelay != 1) {
EEPROM.write(5, 1);
EEPROM.commit();
}
if (eepromUse5Vrelay ? Use5Vrelay = 1 : Use5Vrelay = 0);
pinMode(relayPin1, OUTPUT);
pinMode(relayPin2, OUTPUT);
digitalWrite(relayPin1, Use5Vrelay == true ? HIGH : LOW);
digitalWrite(relayPin2, Use5Vrelay == true ? HIGH : LOW);
#if useWIFI==true
// Connect to WiFi network
Serial.println(); Serial.print("Connecting to "); Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("\nlocalIP: "); Serial.println(WiFi.localIP());
Serial.print("subnetMask: "); Serial.println(WiFi.subnetMask());
Serial.print("gatewayIP: "); Serial.println(WiFi.gatewayIP());
Serial.print("dnsIP: "); Serial.println(WiFi.dnsIP());
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://"); Serial.print(WiFi.localIP()); Serial.println("/");
currentIP = WiFi.localIP().toString();
// OTA WEB PAGE LOGIC IN SETUP
// MDNS.begin(host);
httpUpdater.setup(&httpServer);
httpServer.begin();
MDNS.addService("http", "tcp", 81);
Serial.print("HTTPUpdateServer ready! Open following location: http://"); Serial.print(currentIP); Serial.println(":81/update in your browser\n");
// OTA DIRECTLY FROM IDE
ArduinoOTA.setHostname("OTA-ESP8266-PORT81");
// No authentication by default
// ArduinoOTA.setPassword("admin");
// ArduinoOTA.setPassword((const char *)"admin");
ArduinoOTA.onStart([]() {});
ArduinoOTA.onEnd([]() {});
ArduinoOTA.onError([](ota_error_t error) { ESP.restart(); });
ArduinoOTA.begin();
//MQTT
#ifdef useMQTT
mqtt.setServer(mqttServer, 1883);
mqtt.setCallback(callback);
lastReconnectAttempt = 0;
#endif
#else
// ENC28J60 ETHERNET
uint8_t mac[6] = { 0x0A,0x0B,0x0C,0x0D,0x0E,0x0F };
// FIXED IP ADDRESS
//IPAddress myIP(192,168,0,226);
//Ethernet.begin(mac,myIP);
if (Ethernet.begin(mac) == 0) {
while (1) {
Serial.println("Failed to configure Ethernet using DHCP");
delay(10000);
}
}
server.begin();
Serial.print("\nlocalIP: "); Serial.println(Ethernet.localIP());
Serial.print("subnetMask: "); Serial.println(Ethernet.subnetMask());
Serial.print("gatewayIP: "); Serial.println(Ethernet.gatewayIP());
Serial.print("dnsServerIP: "); Serial.println(Ethernet.dnsServerIP());
currentIP = Ethernet.localIP().toString();
#endif
Serial.println("Setup finished...");
}
void loop() {
#ifdef physicalButton
// PHYSICAL PUSH BUTTON LIMITER WITH MINIMAL DEBOUNCE
if (millis()-lastButtonPush > 1000 && digitalRead(physicalButton) == LOW){
delay(50);
if (digitalRead(physicalButton) == LOW){
delay(50);
if (digitalRead(physicalButton) == LOW){
digitalWrite(relayPin1, digitalRead(relayPin1) ? LOW : HIGH);
lastButtonPush = millis();
#ifdef useMQTT
if (Use5Vrelay == true) {
mqtt.publish(mqttSwitch1Topic,digitalRead(relayPin1) ? "off" : "on");
} else {
mqtt.publish(mqttSwitch1Topic,digitalRead(relayPin1) ? "on" : "off");
}
#endif
}
}
}
#endif
#ifdef physicalLED
// PHYSICAL LED MATCHES RELAY 1 STATE
if (Use5Vrelay == true) {
digitalWrite(physicalLED, digitalRead(relayPin1) ? HIGH : LOW);
} else {
digitalWrite(physicalLED, digitalRead(relayPin1) ? LOW : HIGH);
}
#endif
#ifdef physicalLED2
// PHYSICAL LED 2 MATCHES RELAY 2 STATE
if (Use5Vrelay == true) {
digitalWrite(physicalLED2, digitalRead(relayPin2) ? HIGH : LOW);
} else {
digitalWrite(physicalLED2, digitalRead(relayPin2) ? LOW : HIGH);
}
#endif
// OTA
#if useWIFI==true
httpServer.handleClient();
ArduinoOTA.handle();
#endif
// SERIAL KEEP ALIVE MESSAGE
if (millis() % 900000 == 0) { // every 15 minutes
Serial.print("UpTime: "); Serial.println(uptime());
}
// REBOOT FREQUENCY
EEPROM.begin(1);
int days = EEPROM.read(0);
int RebootFrequencyDays = 0;
RebootFrequencyDays = days;
if (RebootFrequencyDays > 0 && millis() >= (86400000 * RebootFrequencyDays)) { //86400000 per day
while (true);
}
#if useWIFI==true
#ifdef useMQTT
mqttInLoop(millis()); // CALL MQTT LOGIC
#endif
// Check if HTTP client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.print("New client: ");
Serial.println(client.remoteIP().toString());
clientIP = " requested by: " + client.remoteIP().toString();
while (!client.available()) {
delay(1);
}
//Serial.println("---FULL REQUEST---"); Serial.println(client.readString()); Serial.println("---END OF FULL REQUEST---");
request = client.readStringUntil('\r'); // Read the first line of the request
fullrequest = client.readString();
Serial.println(request);
request.replace("GET ", ""); request.replace(" HTTP/1.1", ""); request.replace(" HTTP/1.0", "");
client.flush();
#else // ENC28J60
EthernetClient client = server.available(); // try to get client
//Serial.print("client="); Serial.println(client);
//Serial.print("client.connected="); Serial.println(client.connected());
//Serial.print("client.read FIRST CHAR=");Serial.println(client.read());
if (client) { // got client?
boolean currentLineIsBlank = true;
String HTTP_req; // stores the HTTP request
while (client.connected()) {
if (client.available()) { // client data available to read
char c = client.read(); // read 1 byte (character) from client
HTTP_req += c; // save the HTTP request 1 char at a time
// last line of client request is blank and ends with \n
// respond to client only after last line received
if (c == '\n' && currentLineIsBlank) { //&& currentLineIsBlank --- first line only on low memory like UNO/Nano otherwise get it all for AUTH
fullrequest = HTTP_req;
request = HTTP_req.substring(0, HTTP_req.indexOf('\r'));
//auth = HTTP_req.substring(HTTP_req.indexOf('Authorization: Basic '),HTTP_req.indexOf('\r'));
HTTP_req = ""; // finished with request, empty string
request.replace("GET ", ""); request.replace(" HTTP/1.1", ""); request.replace(" HTTP/1.0", "");
#endif
// HANDLE HTTP REQUEST
Serial.println(request);
handleRequest();
delay(10); // pause to make sure pin status is updated for response below
if (request.indexOf("/json") != -1) {
client.println(jsonResponse());
} else {
client.println(clientResponse(0));
client.println(clientResponse(1));
client.println(clientResponse(2));
client.println(clientResponse(3));
client.println(clientResponse(4));
}
// END THE HTTP REQUEST
#if useWIFI==true
delay(1);
Serial.println("Client disonnected");
Serial.println("");
#else
break;
}
// every line of text received from the client ends with \r\n
if (c == '\n') {
// last character on line of received text
// starting new line with next character read
currentLineIsBlank = true;
}
else if (c != '\r') {
// a text character was received from client
currentLineIsBlank = false;
}
} // end if (client.available())
} // end while (client.connected())
delay(1); // give the web browser time to receive the data
client.stop(); // close the connection
} // end if (client)
#endif
} //loop
void handleRequest() {
//Serial.println("Starting handleRequest...");
// Match the request
if (request.indexOf("/favicon.ico") > -1) {
return;
}
if (request.indexOf("/RebootNow") != -1) {
//while(true);
ESP.restart();
}
if (request.indexOf("RebootFrequencyDays=") != -1) {
EEPROM.begin(1);
String RebootFrequencyDays = request;
RebootFrequencyDays.replace("RebootFrequencyDays=", ""); RebootFrequencyDays.replace("/", ""); RebootFrequencyDays.replace("?", "");
//for (int i = 0 ; i < 512 ; i++) { EEPROM.write(i, 0); } // fully clear EEPROM before overwrite
EEPROM.write(0, atoi(RebootFrequencyDays.c_str()));
EEPROM.commit();
}
if (request.indexOf("/ToggleSensor") != -1) {
EEPROM.begin(1);
if (EEPROM.read(1) == 0) {
EEPROM.write(1, 1);
EEPROM.commit();
pinMode(SENSORPIN, INPUT_PULLUP);
}
else if (EEPROM.read(1) == 1) {
EEPROM.write(1, 0);
EEPROM.commit();
pinMode(SENSORPIN, OUTPUT);
digitalWrite(SENSORPIN, HIGH);
}
}
if (request.indexOf("/Toggle2ndSensor") != -1) {
EEPROM.begin(2);
if (EEPROM.read(2) == 0) {
EEPROM.write(2, 1);
EEPROM.commit();
pinMode(SENSORPIN2, INPUT_PULLUP);
}
else if (EEPROM.read(2) == 1) {
EEPROM.write(2, 0);
EEPROM.commit();
pinMode(SENSORPIN2, OUTPUT);
digitalWrite(SENSORPIN2, HIGH);
}
}
if (request.indexOf("/ToggleUse5Vrelay") != -1) {
EEPROM.begin(5);
if (EEPROM.read(5) == 0) {
Use5Vrelay = true;
EEPROM.write(5, 1);
EEPROM.commit();
}
else {
Use5Vrelay = false;
EEPROM.write(5, 0);
EEPROM.commit();
}
ESP.restart();
}
//Serial.print("Use5Vrelay == "); Serial.println(Use5Vrelay);
if (request.indexOf("RELAY1=ON") != -1 || request.indexOf("MainTriggerOn=") != -1) {
digitalWrite(relayPin1, Use5Vrelay == true ? LOW : HIGH);
#ifdef useMQTT
clientIP = "HTTP ON" + clientIP;
//clientIPchar = strcpy((char*)malloc(clientIP.length()+1), clientIP.c_str());
char* clientIPchar = const_cast<char*>(clientIP.c_str());
mqtt.publish(mqttSwitch1Topic,clientIPchar);
delay(100);
mqtt.publish(mqttSwitch1Topic,"on");
#endif
}
if (request.indexOf("RELAY1=OFF") != -1 || request.indexOf("MainTriggerOff=") != -1) {
digitalWrite(relayPin1, Use5Vrelay == true ? HIGH : LOW);
#ifdef useMQTT
clientIP = "HTTP OFF" + clientIP;
//clientIPchar = strcpy((char*)malloc(clientIP.length()+1), clientIP.c_str());
char* clientIPchar = const_cast<char*>(clientIP.c_str());
mqtt.publish(mqttSwitch1Topic,clientIPchar);
delay(100);
mqtt.publish(mqttSwitch1Topic,"off");
#endif
}
if (request.indexOf("RELAY1=MOMENTARY") != -1 || request.indexOf("MainTrigger=") != -1) {
digitalWrite(relayPin1, Use5Vrelay == true ? LOW : HIGH);
delay(400);
digitalWrite(relayPin1, Use5Vrelay == true ? HIGH : LOW);
#ifdef useMQTT
clientIP = "HTTP MOMENTARY" + clientIP;
//clientIPchar = strcpy((char*)malloc(clientIP.length()+1), clientIP.c_str());
char* clientIPchar = const_cast<char*>(clientIP.c_str());
mqtt.publish(mqttSwitch1Topic,clientIPchar);
delay(100);
mqtt.publish(mqttSwitch1Topic,"on");
delay(100);
mqtt.publish(mqttSwitch1Topic,"off");
#endif
}
if (request.indexOf("RELAY2=ON") != -1 || request.indexOf("CustomTriggerOn=") != -1) {
digitalWrite(relayPin2, Use5Vrelay == true ? LOW : HIGH);
#ifdef useMQTT
clientIP = "HTTP ON" + clientIP;
clientIPchar = strcpy((char*)malloc(clientIP.length()+1), clientIP.c_str());
mqtt.publish(mqttSwitch2Topic,clientIPchar);
delay(100);
mqtt.publish(mqttSwitch2Topic,"on");
#endif
}
if (request.indexOf("RELAY2=OFF") != -1 || request.indexOf("CustomTriggerOff=") != -1) {
digitalWrite(relayPin2, Use5Vrelay == true ? HIGH : LOW);
#ifdef useMQTT
clientIP = "HTTP OFF" + clientIP;
clientIPchar = strcpy((char*)malloc(clientIP.length()+1), clientIP.c_str());
mqtt.publish(mqttSwitch2Topic,clientIPchar);
delay(100);
mqtt.publish(mqttSwitch2Topic,"off");
#endif
}
if (request.indexOf("RELAY2=MOMENTARY") != -1 || request.indexOf("CustomTrigger=") != -1) {
digitalWrite(relayPin2, Use5Vrelay == true ? LOW : HIGH);
delay(400);
digitalWrite(relayPin2, Use5Vrelay == true ? HIGH : LOW);
#ifdef useMQTT
clientIP = "HTTP MOMENTARY" + clientIP;
clientIPchar = strcpy((char*)malloc(clientIP.length()+1), clientIP.c_str());
mqtt.publish(mqttSwitch2Topic,clientIPchar);
delay(100);
mqtt.publish(mqttSwitch2Topic,"on");
delay(100);
mqtt.publish(mqttSwitch2Topic,"off");
#endif
}
}
// HTTP response
String clientResponse(int section) {
String clientResponse = "";
if (section == 0) {
// BASIC AUTHENTICATION
#ifdef useAuth
// The below Base64 string is gate:gate1 for the username:password
if (fullrequest.indexOf("Authorization: Basic Z2F0ZTpnYXRlMQ==") == -1) {
clientResponse.concat("HTTP/1.1 401 Access Denied\n");
clientResponse.concat("WWW-Authenticate: Basic realm=\"ESP8266\"\n");
clientResponse.concat("Content-Type: text/html\n");
clientResponse.concat("\n"); // do not forget this one
clientResponse.concat("Failed : Authentication Required!\n");
return clientResponse;
}
#else
clientResponse.concat("HTTP/1.1 200 OK\n");
clientResponse.concat("Content-Type: text/html; charset=ISO-8859-1\n");
clientResponse.concat("\n"); // do not forget this one
#endif
}
else if (section == 1) {
// Return the response
clientResponse.concat("<!DOCTYPE HTML>\n");
clientResponse.concat("<html><head><title>ESP8266 & ");
#if useWIFI==true
clientResponse.concat("WIFI");
#else
clientResponse.concat("ENC28J60");
#endif
clientResponse.concat(" DUAL SWITCH</title></head><meta name=viewport content='width=500'>\n<style type='text/css'>\nbutton {line-height: 1.8em; margin: 5px; padding: 3px 7px;}");
clientResponse.concat("\nbody {text-align:center;}\ndiv {border:solid 1px; margin: 3px; width:150px;}\n.center { margin: auto; width: 400px; border: 3px solid #73AD21; padding: 3px;}");
clientResponse.concat("\nhr {width:400px;}\n</style><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n");
clientResponse.concat("<script>\n");
clientResponse.concat("$(document).ready(function(){\n");
clientResponse.concat(" $('.hide_settings').click(function(){\n");
clientResponse.concat(" $('.settings').hide(1000);\n");
clientResponse.concat(" $('.show_settings').show(1000);\n");
clientResponse.concat(" });\n");
clientResponse.concat(" $('.show_settings').click(function(){\n");
clientResponse.concat(" $('.settings').show(1000);\n");
clientResponse.concat(" $('.show_settings').hide(1000);\n");
clientResponse.concat(" });\n");
clientResponse.concat("});\n");
clientResponse.concat("function show_settings() {\n");
clientResponse.concat(" if (/MSIE (\\d+\\.\\d+);/.test(navigator.userAgent) || navigator.userAgent.indexOf(\"Trident/\") > -1 ){ \n");
clientResponse.concat(" document.getElementById('show_settings').style.display = 'none';\n");
clientResponse.concat(" document.getElementById('settings').style.display = 'block';\n");
clientResponse.concat(" }\n");
clientResponse.concat("}\n");
clientResponse.concat("function hide_settings() {\n");
clientResponse.concat(" if (/MSIE (\\d+\\.\\d+);/.test(navigator.userAgent) || navigator.userAgent.indexOf(\"Trident/\") > -1 ){ \n");
clientResponse.concat(" document.getElementById('show_settings').style.display = 'block';\n");
clientResponse.concat(" document.getElementById('settings').style.display = 'none';\n");
clientResponse.concat(" }\n");
clientResponse.concat("}\n");
clientResponse.concat("</script>\n");
clientResponse.concat("</head>");
clientResponse.concat("\n<h2 style=\"height: 15px; margin-top: 0px;\"><a href='/'>ESP8266 & ");
#if useWIFI==true
clientResponse.concat("WIFI");
#else
clientResponse.concat("ENC28J60");
#endif
clientResponse.concat(" DUAL SWITCH</h2><h3 style=\"height: 15px;\">");
clientResponse.concat(currentIP);
clientResponse.concat("</a>\n</h3>\n");
clientResponse.concat("<i>Current Request:</i><br><b>\n");
clientResponse.concat(request);
clientResponse.concat("\n</b><hr>");
}
else if (section == 2) {
clientResponse.concat("<pre>\n");
// SHOW Use5Vrelay
clientResponse.concat("Use5Vrelay="); clientResponse.concat(Use5Vrelay ? "true" : "false"); clientResponse.concat("\n");
// SHOW UPTIME & FREERAM
clientResponse.concat("UpTime="); clientResponse.concat(uptime()); clientResponse.concat("\n");
clientResponse.concat("Free Mem="); clientResponse.concat(freeRam()); clientResponse.concat("\n");
// SHOW CONTACT SENSOR
if (EEPROM.read(1) == 1) {
clientResponse.concat("<b><i>Contact Sensor Enabled:</i></b>\n");
clientResponse.concat("Contact Sensor="); clientResponse.concat(digitalRead(SENSORPIN) ? "Open" : "Closed"); clientResponse.concat("\n");
//mqtt.publish(mqttContact1Topic,digitalRead(SENSORPIN) ? "open" : "closed");
}
else {
clientResponse.concat("<b><i>Contact Sensor Disabled:</i></b>\n");
clientResponse.concat("Contact Sensor=Closed\n");
}
// SHOW CONTACT SENSOR 2
if (EEPROM.read(2) == 1) {
clientResponse.concat("<b><i>Contact Sensor 2 Enabled:</i></b>\n");
clientResponse.concat("Contact Sensor 2="); clientResponse.concat(digitalRead(SENSORPIN2) ? "Open" : "Closed"); clientResponse.concat("\n");
//mqtt.publish(mqttContact2Topic,digitalRead(SENSORPIN2) ? "open" : "closed");
}
else {
clientResponse.concat("<b><i>Contact Sensor 2 Disabled:</i></b>\n");
clientResponse.concat("Contact Sensor 2=Closed\n");
}
// SHOW & HANDLE DHT
#ifdef useDHT
clientResponse.concat("<b><i>DHT");
clientResponse.concat(DHTTYPE);
clientResponse.concat(" Sensor Information:</i></b>\n");
float h = processDHT(0);
float tc = processDHT(1); float tf = (tc * 9.0 / 5.0) + 32.0;
if (tc == -1000) {
clientResponse.concat("<b><i>DHT Temperature Reading Failed</i></b>\n");
} else {
clientResponse.concat("Temperature="); clientResponse.concat(String(tc, 1)); clientResponse.concat((char)176); clientResponse.concat("C "); clientResponse.concat(round(tf)); clientResponse.concat((char)176); clientResponse.concat("F\n");
}
if (h == -1000) {
clientResponse.concat("<b><i>DHT Humidity Reading Failed</i></b>\n");
} else {
clientResponse.concat("Humidity="); clientResponse.concat(round(h)); clientResponse.concat("%\n");
}
#else
clientResponse.concat("<b><i>DHT Sensor Disabled</i></b>\n");
#endif
clientResponse.concat("</pre>\n"); clientResponse.concat("<hr>\n");
}
else if (section == 3) {
clientResponse.concat("<div class='center'>\n");
clientResponse.concat("RELAY1 pin is now: ");
if (Use5Vrelay == true) {
if (digitalRead(relayPin1) == LOW) { clientResponse.concat("On"); }
else { clientResponse.concat("Off"); }
}
else {
if (digitalRead(relayPin1) == HIGH) { clientResponse.concat("On"); }
else { clientResponse.concat("Off"); }
}
clientResponse.concat("\n<br><a href=\"/RELAY1=ON\"><button onClick=\"parent.location='/RELAY1=ON'\">Turn On</button></a>\n");
clientResponse.concat("<a href=\"/RELAY1=OFF\"><button onClick=\"parent.location='/RELAY1=OFF'\">Turn Off</button></a>\n");
clientResponse.concat("<a href=\"/RELAY1=MOMENTARY\"><button onClick=\"parent.location='/RELAY1=MOMENTARY'\">MOMENTARY</button></a><br/></div><hr>\n");
clientResponse.concat("<div class='center'>\n");
clientResponse.concat("RELAY2 pin is now: ");
if (Use5Vrelay == true) {
if (digitalRead(relayPin2) == LOW) { clientResponse.concat("On"); }
else { clientResponse.concat("Off"); }
}
else {
if (digitalRead(relayPin2) == HIGH) { clientResponse.concat("On"); }
else { clientResponse.concat("Off"); }
}
clientResponse.concat("\n<br><a href=\"/RELAY2=ON\"><button onClick=\"parent.location='/RELAY2=ON'\">Turn On</button></a>\n");
clientResponse.concat("<a href=\"/RELAY2=OFF\"><button onClick=\"parent.location='/RELAY2=OFF'\">Turn Off</button></a>\n");
clientResponse.concat("<a href=\"/RELAY2=MOMENTARY\"><button onClick=\"parent.location='/RELAY2=MOMENTARY'\">MOMENTARY</button></a></div><hr>\n");
}
else if (section == 4) {
//clientResponse.concat("<div class='center'>");
clientResponse.concat("<div class='center show_settings' id='show_settings'><a href='#' onClick='javascript:show_settings();' class='show_settings'><button class='show_settings'>Show Settings</button></a></div>\n");
clientResponse.concat("<div class='settings center' id='settings' style='display:none;'><a href='#' onClick='javascript:hide_settings();' class='hide_settings'><button class='hide_settings'>Hide Settings</button></a><br><hr>\n");
// SHOW TOGGLE Use5Vrelay
clientResponse.concat("<button onClick=\"javascript: if (confirm(\'Are you sure you want to toggle the Use5Vrelay flag?\\nTrue/1 sends a GND signal. False/0 sends a VCC with 3.3 volts.\\nThis will also reboot the device!!!\\nIf the device does not come back up, reset it manually.\')) parent.location='/ToggleUse5Vrelay';\">Toggle Use 5V Relay</button><br><hr>\n");
// SHOW TOGGLE CONTACT SENSORS
clientResponse.concat("<button style='width: 43%' onClick=\"javascript: if (confirm(\'Are you sure you want to toggle the Contact Sensor?\')) parent.location='/ToggleSensor';\">Toggle Contact Sensor</button> \n");
clientResponse.concat("<button style='width: 43%' onClick=\"javascript: if (confirm(\'Are you sure you want to toggle the 2nd Contact Sensor?\')) parent.location='/Toggle2ndSensor';\">Toggle Contact Sensor 2</button><br><hr>\n");
// SHOW OTA INFO IF WIFI IS ENABLED
#if useWIFI==true
clientResponse.concat("<a href=\"http://"); clientResponse.concat(currentIP);
clientResponse.concat(":81/update\"><button onClick=\"parent.location='http://"); clientResponse.concat(currentIP);
clientResponse.concat(":81/update'\">OTA Update</button></a><br><span style=\"font-size:0.8em;\">This is the <a target='_blank' href='http://esp8266.github.io/Arduino/versions/2.0.0/doc/ota_updates/ota_updates.html#web-browser'>Web Browser OTA method</a>,<br>");
clientResponse.concat("Open Start→Run→type in %TEMP% then enter.<br>BIN file will be under one of the build* folders.<br>2nd method of <a target='_blank' href='http://esp8266.github.io/Arduino/versions/2.0.0/doc/ota_updates/ota_updates.html#arduino-ide'>OTA directly via Arduino IDE</a>.</span><hr>\n");
#endif
// REBOOT FREQUENCY
clientResponse.concat("<input id=\"RebootFrequencyDays\" type=\"text\" name=\"RebootFrequencyDays\" value=\"");
EEPROM.begin(1);
int days = EEPROM.read(0);
clientResponse.concat(days);
clientResponse.concat("\" maxlength=\"3\" size=\"2\" min=\"0\" max=\"255\"> <button style=\"line-height: 1em; margin: 3px; padding: 3px 3px;\" onClick=\"parent.location='/RebootFrequencyDays='+document.getElementById('RebootFrequencyDays').value;\">SAVE</button><br>Days between reboots.<br>0 to disable & 255 days is max.");
clientResponse.concat("<br><button onClick=\"javascript: if (confirm(\'Are you sure you want to reboot?\')) parent.location='/RebootNow';\">Reboot Now</button><br></div>\n");
// BOTTOM LINKS
clientResponse.concat("<hr><div class='center'><a target='_blank' href='https://community.smartthings.com/t/raspberry-pi-to-php-to-gpio-to-relay-to-gate-garage-trigger/43335'>Project on SmartThings Community</a></br>\n");
clientResponse.concat("<a target='_blank' href='https://github.com/JZ-SmartThings/SmartThings/tree/master/Devices/Generic%20HTTP%20Device'>Project on GitHub</a></br></div></html>\n");
}
return clientResponse;
}
String jsonResponse() {
String jsonResponse = "";
//jsonResponse.concat("HTTP/1.1 200 OK\n");
jsonResponse.concat("HTTP/1.x 200 OK\n");
jsonResponse.concat("Content-Type: application/json; charset=ISO-8859-1\n");
jsonResponse.concat("\n"); // do not forget this one
jsonResponse.concat("{\n");
jsonResponse.concat(" \"UpTime\": \""); jsonResponse.concat(uptime()); jsonResponse.concat("\"");
jsonResponse.concat(",\n");
jsonResponse.concat(" \"Free Mem\": \""); jsonResponse.concat(freeRam()); jsonResponse.concat("\"");
jsonResponse.concat(",\n");
if (Use5Vrelay == true) {
jsonResponse.concat(" \"MainPinStatus\": \"");
if (digitalRead(relayPin1) == LOW) { jsonResponse.concat("1\""); }
else { jsonResponse.concat("0\""); }
jsonResponse.concat(",\n");
}
else {
jsonResponse.concat(" \"MainPinStatus\": \"");
if (digitalRead(relayPin1) == HIGH) { jsonResponse.concat("1\""); }
else { jsonResponse.concat("0\""); }
jsonResponse.concat(",\n");
}
if (Use5Vrelay == true) {
jsonResponse.concat(" \"CustomPinStatus\": \"");
if (digitalRead(relayPin2) == LOW) { jsonResponse.concat("1\""); }
else { jsonResponse.concat("0\""); }
jsonResponse.concat(",\n");
}
else {
jsonResponse.concat(" \"CustomPinStatus\": \"");
if (digitalRead(relayPin2) == HIGH) { jsonResponse.concat("1\""); }
else { jsonResponse.concat("0\""); }
jsonResponse.concat(",\n");
}
if (EEPROM.read(1) == 1) {
jsonResponse.concat(" \"SensorPinStatus\": \""); jsonResponse.concat(digitalRead(SENSORPIN) ? "1" : "0"); jsonResponse.concat("\"");
jsonResponse.concat(",\n");
}
else {
jsonResponse.concat(" \"SensorPinStatus\": \"0\"");
jsonResponse.concat(",\n");
}
if (EEPROM.read(1) == 1) {
jsonResponse.concat(" \"Sensor2PinStatus\": \""); jsonResponse.concat(digitalRead(SENSORPIN) ? "1" : "0"); jsonResponse.concat("\"");
}
else {
jsonResponse.concat(" \"Sensor2PinStatus\": \"0\"");
}
#ifdef useDHT
float h = processDHT(0);
float tc = processDHT(1); float tf = (tc * 9.0 / 5.0) + 32.0;
if (tc != -1000) {
jsonResponse.concat(",\n");
jsonResponse.concat(" \"Temperature\": \""); jsonResponse.concat(String(tc, 1)); jsonResponse.concat((char)176); jsonResponse.concat("C ");
jsonResponse.concat(round(tf)); jsonResponse.concat((char)176); jsonResponse.concat("F\"");
}
if (h != -1000) {
jsonResponse.concat(",\n");
jsonResponse.concat(" \"Humidity\": \""); jsonResponse.concat(round(h)); jsonResponse.concat("%\"");
}
#endif
jsonResponse.concat("\n}");
//Serial.println(jsonResponse);
return jsonResponse;
}
// MQTT method called from loop
boolean reconnect() {
#ifdef useMQTT
Serial.print("Attempting MQTT connection... ");
if (mqtt.connect(mqttClientName, mqttSwitch1Topic, 0, false, "LWT disconnected")) {
Serial.print(mqttClientName);
Serial.println(" connected");
// Once connected, publish an announcement...
mqtt.publish(mqttSwitch1Topic,"connected");
mqtt.publish(mqttSwitch1Topic,"available");
mqtt.publish(mqttSwitch2Topic,"connected");
mqtt.publish(mqttSwitch2Topic,"available");
mqtt.subscribe(mqttSwitch1Topic);
mqtt.subscribe(mqttSwitch2Topic);
} else {
Serial.print(" connection failed, rc=");
Serial.println(mqtt.state());
}
return mqtt.connected();
#endif
}
// MQTT received messages
void callback(char* topic, byte* payload, unsigned int length) {
#ifdef useMQTT
Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] ");
String fullPayload;
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
fullPayload += (char)payload[i];
}
Serial.println();
//MQTT handling
if (String(topic)==mqttSwitch1Topic && fullPayload=="on") {
digitalWrite(relayPin1, Use5Vrelay == true ? LOW : HIGH);
}
if (String(topic)==mqttSwitch1Topic && fullPayload=="off") {
digitalWrite(relayPin1, Use5Vrelay == true ? HIGH : LOW);
}
if (String(topic)==mqttSwitch1Topic && fullPayload=="momentary") {
digitalWrite(relayPin1, Use5Vrelay == true ? LOW : HIGH);
delay(300);
mqtt.publish(mqttSwitch1Topic,"on");
delay(50);
mqtt.publish(mqttSwitch1Topic,"off");
digitalWrite(relayPin1, Use5Vrelay == true ? HIGH : LOW);
}
if (String(topic)==mqttSwitch2Topic && fullPayload=="on") {
digitalWrite(relayPin2, Use5Vrelay == true ? LOW : HIGH);
}
if (String(topic)==mqttSwitch2Topic && fullPayload=="off") {
digitalWrite(relayPin2, Use5Vrelay == true ? HIGH : LOW);
}
if (String(topic)==mqttSwitch2Topic && fullPayload=="momentary") {
digitalWrite(relayPin2, Use5Vrelay == true ? LOW : HIGH);
delay(300);
mqtt.publish(mqttSwitch2Topic,"on");
delay(50);
mqtt.publish(mqttSwitch2Topic,"off");
digitalWrite(relayPin2, Use5Vrelay == true ? HIGH : LOW);
}
#endif
}
void mqttInLoop(unsigned long ) {
#ifdef useMQTT // MQTT LOGIC IN LOOP
unsigned long currentMillis = millis();
if (!mqtt.connected()) {
if (currentMillis - lastReconnectAttempt > 15000) { // RECONNECT ATTEMPT EVERY 15 SECONDS
lastReconnectAttempt = currentMillis;
// Attempt to reconnect
if (reconnect()) {
lastReconnectAttempt = 0;
}
}
} else {
// Client connected
mqtt.loop();
}
// MQTT publish contact, temperature & humidity
const char* currentPayload;
if (currentMillis % 1000 == 0) { // check contact sensors every 1 seconds
// CONTACT SENSOR 1
if (EEPROM.read(1) == 1 && lastContact1Payload!=(digitalRead(SENSORPIN) ? "open" : "closed")) {
mqtt.publish(mqttContact1Topic,digitalRead(SENSORPIN) ? "open" : "closed");
lastContact1Payload = digitalRead(SENSORPIN) ? "open" : "closed";
}
// CONTACT SENSOR 2
if (EEPROM.read(2) == 1 && lastContact2Payload!=(digitalRead(SENSORPIN2) ? "open" : "closed")) {
mqtt.publish(mqttContact2Topic,digitalRead(SENSORPIN2) ? "open" : "closed");
lastContact2Payload = digitalRead(SENSORPIN2) ? "open" : "closed";
}
}
if (currentMillis % 20000 == 0) { // every 20 seconds DHT
#ifdef useDHT
float h = processDHT(0);
float tc = processDHT(1); float tf = (tc * 9.0 / 5.0) + 32.0;
char buf[8];
//Serial.println (round(lastTemperaturePayload)); Serial.println (tf); Serial.println (round(tf));
if ((tc != -1000 && round(lastTemperaturePayload)!=round(tf)) || (tc != -1000 && currentMillis % 60000 == 0)) {
Serial.println ("mqttTemperature published");
mqtt.publish(mqttTemperatureTopic,dtostrf(round(tf), 0, 0, buf));
lastTemperaturePayload=round(tf);
}
//Serial.println (round(lastHumidityPayload)); Serial.println (h); Serial.println (round(h));
if ((h != -1000 && round(lastHumidityPayload)!=round(h)) || (h != -1000 && currentMillis % 60000 == 0)) {
Serial.println ("mqttHumidity published");
mqtt.publish(mqttHumidityTopic,dtostrf(round(h), 0, 0, buf));
lastHumidityPayload=round(h);
}
#endif // DHT
}
if (currentMillis % 900000 == 0) { // check connection every 15 minutes
// MQTT KEEPALIVE AND LWT LOGIC
mqtt.publish(mqttSwitch1Topic,"available");
mqtt.publish(mqttSwitch2Topic,"available");
}
#endif // MQTT
}
float processDHT(bool whichSensor) {
// Reading temperature or humidity takes about 250 milliseconds. Sensor readings may also be up to 2 seconds old
#ifdef useDHT
float h = -1000;
float tc = -1000;
int counter = 1;
if (whichSensor == 0) {
h = dht.readHumidity();
while (counter <= 5 && (isnan(h) || h == -1000)) {
if (isnan(h) || h == -1000) { h = dht.readHumidity(); } // re-read
counter += 1; delay(50);
}
}
else if (whichSensor == 1) {
tc = dht.readTemperature();
while (counter <= 5 && (isnan(tc) || tc == -1000)) {
if (isnan(tc) || tc == -1000) { tc = dht.readTemperature(); } // re-read
counter += 1; delay(50);
}
}
if (whichSensor == 0) {
if (isnan(h) || h == -1000) { return -1000; }
else { return h; }
} else if (whichSensor == 1) {
if (isnan(tc) || tc == -1000) { return -1000; }
else { return tc; }
}
#endif
}
String freeRam() {
#if defined(ARDUINO_ARCH_AVR)
extern int __heap_start, *__brkval;
int v;
return String((int)&v - (__brkval == 0 ? (int)&__heap_start : (int)__brkval)) + "B of 2048B";
#elif defined(ESP8266)
return String(ESP.getFreeHeap() / 1024) + "KB of 80KB";
#endif
}
String uptime() {
float d, hr, m, s;
String dstr, hrstr, mstr, sstr;
unsigned long over;
d = int(millis() / (3600000 * 24));
dstr = String(d, 0);
dstr.replace(" ", "");
over = millis() % (3600000 * 24);
hr = int(over / 3600000);
hrstr = String(hr, 0);
if (hr<10) { hrstr = hrstr = "0" + hrstr; }
hrstr.replace(" ", "");
over = over % 3600000;
m = int(over / 60000);
mstr = String(m, 0);
if (m<10) { mstr = mstr = "0" + mstr; }
mstr.replace(" ", "");
over = over % 60000;
s = int(over / 1000);
sstr = String(s, 0);
if (s<10) { sstr = "0" + sstr; }
sstr.replace(" ", "");
if (dstr == "0") {
return hrstr + ":" + mstr + ":" + sstr;
}
else if (dstr == "1") {
return dstr + " Day " + hrstr + ":" + mstr + ":" + sstr;
}
else {
return dstr + " Days " + hrstr + ":" + mstr + ":" + sstr;
}
}
| [
"jzelyeny@gmail.com"
] | jzelyeny@gmail.com |
7295599085f66c2df320488ef2bef91d9785a023 | ef3145c7202afa96df2afbd8fbaea8529cfa2d14 | /sacache.cpp | d5a561fd6bde22b49662e66d686ea916046d5df4 | [] | no_license | vincentssheng/Caching | 24d53e7ba87dbc845f5b0e0e5538554c71fdf841 | 70ca28c1e00128b0ec799b7aad062bbcce65f397 | refs/heads/master | 2020-03-30T10:47:12.430802 | 2018-10-01T18:25:11 | 2018-10-01T18:25:11 | 151,136,102 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,997 | cpp | #include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <cstring>
using namespace std;
class cacheLine
{
public:
cacheLine()
{
tag = -1;
counter = 0;
dirty = 0;
}
int tag; //converted from first two hex digits of addr
string bytes [8];
int dirty;
int counter;
};
int bin_to_dec(int bin[], int length)
{
int dec = 0;
for(int i = length - 1; i >= 0; i--)
{
dec += (pow(2.0,i) * bin[length - 1 - i]);
}
return dec;
}
void hex_to_bin(string hex, int *binAddress)
{
int decVal;
int quotient;
int rem;
for(int i = 3; i >= 0; i--)
{
if((hex[i] - 'A') >= 0)
decVal = hex[i] - 'A' + 10;
else
decVal = hex[i] - '0';
quotient = decVal;
for(int j = 3; j >= 0; j--)
{
rem = quotient % 2;
quotient = quotient / 2;
binAddress[i*4 + j] = rem;
//cout << binAddress[i*4 + j];
}
}
//cout << endl;
}
int min_counter(cacheLine group [])
{
int currMin = 0xFFFF;
int minIndex = -1;
for(int i = 0; i < 4; i++)
{
if((group[i]).counter < currMin)
{
currMin = group[i].counter;
minIndex = i;
//cout << minIndex << endl;
}
//cout << currMin << endl;
}
return minIndex;
}
void write_to_RAM(cacheLine* writeBack, int set, string* RAM)
{
int quotient = writeBack->tag;
int destination [16];
int RAMindex;
int rem;
for(int j = 7; j >= 0; j--)
{
rem = quotient % 2;
quotient = quotient / 2;
destination[j] = rem;
}
quotient = set;
for(int j = 12; j >= 8; j--)
{
rem = quotient % 2;
quotient = quotient / 2;
destination[j] = rem;
}
for(int i = 0; i < 3; i++)
destination[i+13] = 0;
RAMindex = bin_to_dec(destination, 16);
for(int i = 0; i < 8; i++)
{
RAM[RAMindex + i] = writeBack->bytes[i];
//cout << RAM[RAMindex + i] << "," << writeBack->bytes[i] << "," << RAMindex + i << endl;
}
}
void pull_from_RAM(cacheLine* writeTo, int binAddress[], string* RAM)
{
int startAddress [16];
for(int i = 0; i < 13; i++)
{
startAddress[i] = binAddress[i];
//cout << startAddress[i];
}
//cout << endl;
for(int i = 13; i < 16; i++)
startAddress[i] = 0;
int RAMindex = bin_to_dec(startAddress, 16);
//cout << RAMindex << endl;
for(int i = 0; i < 8; i++)
{
writeTo->bytes[i] = RAM[RAMindex + i];
//cout << RAM[RAMindex + 11] << "," << RAM[RAMindex+i] << "," << writeTo->bytes[i] << endl;
}
writeTo->tag = bin_to_dec(startAddress, 8);
//cout << startAddress[i] << "," << writeTo->tag[i] << "," << endl;
}
void read_and_output(ofstream& outfile, cacheLine readFrom, int offset, int hit)
{
outfile << "Data,";
outfile << readFrom.bytes[offset];
outfile << ",Dirty,";
outfile << readFrom.dirty;
outfile << ",Hit,";
outfile << hit;
outfile << "\n";
}
int main(int argc, char const *argv[])
{
int RAMSize = 65536;
string RAM [RAMSize];
for(int i = 0; i < RAMSize; i++)
RAM[i] = "00";
cacheLine cache [32][4]; //index of this array is equal to the set of the cacheLine
ifstream addresses(argv[1]);
ofstream outfile;
outfile.open ("sa-out.csv");
string address;
string RW;
string data;
int binAddress [16];
int taco; //nameholder for tag
int tac; //tempholder for tag
string tagStr;
int set;
int binSet [5];
int offset;
int binOffset [3];
int globalCounter = 0;
while(getline(addresses, address, ','))
{
globalCounter++;
//cout << globalCounter << endl;
taco = 0;
getline(addresses, RW, ',');
getline(addresses, data, '\n');
hex_to_bin(address, binAddress);
tagStr = address.substr(0,2);
const char* ctag;
ctag = tagStr.c_str();
//cout << ctag[0] << ctag[1] << endl;
for(int i = 0; i <= 1; i++)
{
if((ctag[i] - 'A') >= 0)
tac = ctag[i] - 'A' + 10;
else
tac = ctag[i] - '0';
taco += (tac * pow(16,1-i));
}
for(int i = 0; i < 5; i++)
{
binSet[i] = binAddress[i+8];
//cout << binSet[i];
}
//cout << endl;
set = bin_to_dec(binSet, 5);
for(int i = 0; i < 3; i++)
{
binOffset[i] = binAddress[i+13];
//cout << binOffset[i];
}
//cout << endl;
offset = bin_to_dec(binOffset, 3);
int thisOne = -1;
for(int i = 0; i < 4; i++)
{
//cout << "taco: " << taco << ", tag: " << cache[set][i].tag << endl;
if(cache[set][i].tag == taco)
{
thisOne = i;
//cout << thisOne << endl;
break;
}
}
if(thisOne == -1) //miss
{
int evictThis = min_counter(cache[set]);
//cout << evictThis << endl;
if(cache[set][evictThis].dirty == 1)
{
write_to_RAM(&(cache[set][evictThis]), set, RAM);
}
pull_from_RAM(&(cache[set][evictThis]), binAddress, RAM);
cache[set][evictThis].counter = globalCounter;
if(!RW.compare("00")) //if write
{
//cout << "write and miss" << endl;
cache[set][evictThis].bytes[offset] = data;
cache[set][evictThis].dirty = 1;
}
else if(!RW.compare("FF"))
{
//cout << "read and miss" << endl;
read_and_output(outfile, cache[set][evictThis], offset, 0);
cache[set][evictThis].dirty = 0;
}
}
else if(thisOne >= 0 || thisOne <= 3)//hit
{
cache[set][thisOne].counter = globalCounter;
if(!RW.compare("00")) //if write
{
//cout << "hit and write" << endl;
cache[set][thisOne].bytes[offset] = data;
cache[set][thisOne].dirty = 1;
}
else if(!RW.compare("FF"))
{
//cout << "hit and read" << endl;
read_and_output(outfile, cache[set][thisOne], offset, 1);
}
}
}
outfile.close();
return 0;
} | [
"shengyeesiow96@gmail.com"
] | shengyeesiow96@gmail.com |
7003003e734fd5b3240909ee650229d0ea01f3ba | 97ce7536ed81a0cfefa746824f7f0ec38d7021fb | /tetris/trie.cc | 59af6e52295eefe0ac5404e633e6659218ca4981 | [] | no_license | k10bradley/projects | 10165974207551a6880ba366b4d106a52859499e | 89c2a2768ecb3754d5aebeafd1d833dab421ea0b | refs/heads/master | 2020-05-31T13:00:39.354640 | 2019-06-04T23:38:49 | 2019-06-04T23:38:49 | 190,294,024 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,267 | cc | #include "trie.h"
#include <vector>
#include "command.h"
#include <memory>
#include <iostream>
using namespace std;
char translate(char in){
if ( 'a' <= in && 'z' >= in ) return in - 'a';
else return in - 'A' + 26;
}
struct Trie::TrieNode{
Op op = NONE;
vector<TrieNode*> children;
bool final = false;
TrieNode(const string& cmd = "", Op op = NONE);
~TrieNode();
bool insert(const string&, Op);
Op find(const string&);
};
Trie::TrieNode::TrieNode(const string& cmd , Op oper ): op(oper), children(52,nullptr){
if ( ! cmd.empty() ){
char let = translate(cmd[0]);
children[let] = new TrieNode(cmd.substr(1), oper);
} else {
final = true;
}
}
Trie::TrieNode::~TrieNode(){
for ( auto child: children ) delete child;
}
bool Trie::TrieNode::insert(const string& cmd, Op operation){
char first = translate(cmd[0]);
if ( first < 0 || first > 51 ) return false;
if ( children[first] ){
if ( children[first]->op != NONE && !children[first]->final ){
children[first]->op = NONE;
}
if ( cmd.substr(1).empty() ){
children[first]->op = operation;
} else {
children[first]->insert(cmd.substr(1), operation);
}
} else {
children[first] = new TrieNode(cmd.substr(1), operation);
}
return true;
}
Op Trie::TrieNode::find(const string& cmd){
char first = translate(cmd[0]);
if ( children[first] ){
if ( children[first]->op != NONE ){
return children[first]->op;
} else {
return children[first]->find(cmd.substr(1));
}
}
return NONE;
}
bool Trie::insert(const string& old, const string& add){
if ( find(add) ) return false;
Op oper = find(old);
if ( oper == NONE ) {
cerr << old << " is not a command" << endl;
return false;
}
bool result = theTrie->insert(add, oper);
if ( !result ) cerr << add << " is not a valid command" << endl;
return result;
}
bool Trie::insert(const string& add, Op oper){
if ( find(add) == oper ) return false;
return theTrie->insert(add, oper);
}
Op Trie::find(const string& cmd){
if ( theTrie == nullptr ) return NONE;
return theTrie->find(cmd);
}
void Trie::reset(){
delete theTrie;
theTrie = new TrieNode;
}
Trie::Trie(): theTrie{new TrieNode} {}
Trie::~Trie(){ delete theTrie; }
| [
"kcpbradl@uwaterloo.ca"
] | kcpbradl@uwaterloo.ca |
9bdb0b3461ae64717c77c1807a50654bedafcab4 | da83490ee5951d0a5e6bb469b6a9f69dda1efd0d | /priorityQueue.h | dcc6474e9d83833dede949c2b1b9d1bb806d21cd | [] | no_license | venkatkrish1983/Prep | 312326c3e2b0eb9d313ae6b2c1907504c03e117e | 0427812e9c7cb5e12be60185eee332eb5c1ab548 | refs/heads/master | 2021-05-08T18:26:41.567655 | 2021-05-05T11:11:30 | 2021-05-05T11:11:30 | 119,519,883 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,883 | h | #include <vector>
#include <exception>
using namespace std;
class queueEmptyException; //forward declaration
template <class T>
class PriorityQueueADT
{
//Even Priority queue can be implemented using LL but insert will be O(n) but delete and max element is O(1)
public:
virtual void enqueue(T elem) = 0;
virtual T max() const throw (queueEmptyException)= 0;
virtual void dequeue() throw (queueEmptyException) = 0;
virtual bool isEmpty() const = 0;
virtual int size() const = 0;
};
class queueEmptyException:public exception
{
public:
const char* what() const noexcept
{
return "queue empty";
}
};
template <class T>
class PriorityQueue:public PriorityQueueADT<T>
{
//try to implement using node?
vector<T> v;
public:
//how does priority queue makesure highest element is always at top using heap
// can use a vector to implement
PriorityQueue(){}
~PriorityQueue(){}
void enqueue(T elem);
void dequeue() throw (queueEmptyException);
T max() const throw (queueEmptyException);
int size() const;
bool isEmpty() const;
void heapify_up();
void heapify_down();
};
template <class T>
int PriorityQueue<T>::size() const
{
return v.size();
}
template <class T>
bool PriorityQueue<T>::isEmpty() const
{
return v.empty()?true:false;
}
template <class T>
void PriorityQueue<T>::enqueue(T elem)
{
v.push_back(elem);
heapify_up(); //makesure that priority queue is maintained
}
template <class T>
void PriorityQueue<T>::heapify_up()
{
int child = v.size() -1;
int parent = (child -1)/2;
while(parent >= 0 && v[child] > v[parent])
{
T t = v[child];
v[child] = v[parent];
v[parent] = t;
child = parent;
parent = (child-1 )/2;
}
}
template <class T>
T PriorityQueue<T>::max() const throw (queueEmptyException)
{
return v[0];
}
template <class T>
void PriorityQueue<T>::dequeue() throw (queueEmptyException)
{
v[0] = v[v.size()-1];
v.pop_back();
heapify_down();
}
template <class T>
void PriorityQueue<T>::heapify_down()
{
int parent = 0;
int leftchild = parent*2+1;
int rightchild = parent*2+2;
leftchild = leftchild < v.size() ? leftchild:-1;
rightchild = rightchild < v.size() ? rightchild:-1;
int biggerchild = 0;
if(rightchild > 0 && leftchild > 0)
biggerchild = v[rightchild] > v[leftchild] ? rightchild:leftchild;
else if(leftchild > 0)
biggerchild = leftchild;
else
biggerchild = -1;
while(biggerchild> 0 && v[parent] < v[biggerchild])
{
T t = v[parent];
v[parent] = v[biggerchild];
v[biggerchild] = t;
leftchild = parent*2 +1;
rightchild = parent*2 +2;
leftchild = leftchild < v.size() ? leftchild:-1;
rightchild = rightchild < v.size() ? rightchild:-1;
if(rightchild > 0 && leftchild > 0)
biggerchild = v[rightchild] > v[leftchild] ? rightchild:leftchild;
else if(leftchild > 0)
biggerchild = leftchild;
else
biggerchild = -1;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
41ad0da4bd82d2cde5313e7e83c0c5db95866b7b | 2b26d7846abc385af2bbbde150ba07e11d11e91e | /rdd.h | 7001fd82248174fbe2b14ec5030f3b712729b193 | [] | no_license | hdaikoku/mapreduce-mpi | 6fcefc2cfd7146c99710e8d179df6730bf58e76f | 692d58b288f40e35f939503c4ec306eb680c619a | refs/heads/master | 2020-12-25T14:12:44.939450 | 2015-11-18T09:07:22 | 2015-11-18T09:07:22 | 62,628,214 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 564 | h | //
// Created by Harunobu Daikoku on 2015/09/02.
//
#ifndef RDD_MAPREDUCE_RDD_H
#define RDD_MAPREDUCE_RDD_H
#include <iostream>
#include <memory>
#include <string>
#include <mpi.h>
using namespace std;
class Rdd {
public:
Rdd();
virtual ~Rdd() {
if (!MPI::Is_finalized()) {
MPI::Finalize();
}
}
virtual void SplitFile(const char *filename);
virtual void ReleaseBuffer();
protected:
int n_workers_;
int mpi_my_rank_;
MPI::Offset start_;
MPI::Offset chunk_size_;
unique_ptr<char[]> chunk_;
};
#endif //RDD_MAPREDUCE_RDD_H
| [
"daikoku@hpcs.cs.tsukuba.ac.jp"
] | daikoku@hpcs.cs.tsukuba.ac.jp |
b92589123c455ca333554a4ea6c291f5854b7a89 | 9fad4848e43f4487730185e4f50e05a044f865ab | /src/device/bluetooth/bluetooth_remote_gatt_service_win.cc | 95e43cc2bc32bd5ebf59a1c4574811b4ba04da92 | [
"BSD-3-Clause"
] | permissive | dummas2008/chromium | d1b30da64f0630823cb97f58ec82825998dbb93e | 82d2e84ce3ed8a00dc26c948219192c3229dfdaa | refs/heads/master | 2020-12-31T07:18:45.026190 | 2016-04-14T03:17:45 | 2016-04-14T03:17:45 | 56,194,439 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,902 | cc | // 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.
#include "device/bluetooth/bluetooth_remote_gatt_service_win.h"
#include <memory>
#include "base/bind.h"
#include "base/memory/ptr_util.h"
#include "device/bluetooth/bluetooth_adapter_win.h"
#include "device/bluetooth/bluetooth_device_win.h"
#include "device/bluetooth/bluetooth_remote_gatt_characteristic_win.h"
#include "device/bluetooth/bluetooth_task_manager_win.h"
namespace device {
BluetoothRemoteGattServiceWin::BluetoothRemoteGattServiceWin(
BluetoothDeviceWin* device,
base::FilePath service_path,
BluetoothUUID service_uuid,
uint16_t service_attribute_handle,
bool is_primary,
BluetoothRemoteGattServiceWin* parent_service,
scoped_refptr<base::SequencedTaskRunner>& ui_task_runner)
: device_(device),
service_path_(service_path),
service_uuid_(service_uuid),
service_attribute_handle_(service_attribute_handle),
is_primary_(is_primary),
parent_service_(parent_service),
ui_task_runner_(ui_task_runner),
discovery_complete_notified_(false),
included_characteristics_discovered_(false),
weak_ptr_factory_(this) {
DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());
DCHECK(!service_path_.empty());
DCHECK(service_uuid_.IsValid());
DCHECK(service_attribute_handle_);
DCHECK(device_);
if (!is_primary_)
DCHECK(parent_service_);
adapter_ = static_cast<BluetoothAdapterWin*>(device_->GetAdapter());
DCHECK(adapter_);
task_manager_ = adapter_->GetWinBluetoothTaskManager();
DCHECK(task_manager_);
service_identifier_ = device_->GetIdentifier() + "/" + service_uuid_.value() +
"_" + std::to_string(service_attribute_handle_);
Update();
}
BluetoothRemoteGattServiceWin::~BluetoothRemoteGattServiceWin() {
DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());
ClearIncludedCharacteristics();
adapter_->NotifyGattServiceRemoved(this);
}
std::string BluetoothRemoteGattServiceWin::GetIdentifier() const {
return service_identifier_;
}
BluetoothUUID BluetoothRemoteGattServiceWin::GetUUID() const {
return const_cast<BluetoothUUID&>(service_uuid_);
}
bool BluetoothRemoteGattServiceWin::IsLocal() const {
return false;
}
bool BluetoothRemoteGattServiceWin::IsPrimary() const {
return is_primary_;
}
BluetoothDevice* BluetoothRemoteGattServiceWin::GetDevice() const {
return device_;
}
std::vector<BluetoothGattCharacteristic*>
BluetoothRemoteGattServiceWin::GetCharacteristics() const {
std::vector<BluetoothGattCharacteristic*> has_characteristics;
for (const auto& c : included_characteristics_)
has_characteristics.push_back(c.second.get());
return has_characteristics;
}
std::vector<BluetoothGattService*>
BluetoothRemoteGattServiceWin::GetIncludedServices() const {
NOTIMPLEMENTED();
// TODO(crbug.com/590008): Needs implementation.
return std::vector<BluetoothGattService*>();
}
BluetoothGattCharacteristic* BluetoothRemoteGattServiceWin::GetCharacteristic(
const std::string& identifier) const {
GattCharacteristicsMap::const_iterator it =
included_characteristics_.find(identifier);
if (it != included_characteristics_.end())
return it->second.get();
return nullptr;
}
bool BluetoothRemoteGattServiceWin::AddCharacteristic(
device::BluetoothGattCharacteristic* characteristic) {
NOTIMPLEMENTED();
return false;
}
bool BluetoothRemoteGattServiceWin::AddIncludedService(
device::BluetoothGattService* service) {
NOTIMPLEMENTED();
return false;
}
void BluetoothRemoteGattServiceWin::Register(
const base::Closure& callback,
const ErrorCallback& error_callback) {
NOTIMPLEMENTED();
error_callback.Run();
}
void BluetoothRemoteGattServiceWin::Unregister(
const base::Closure& callback,
const ErrorCallback& error_callback) {
NOTIMPLEMENTED();
error_callback.Run();
}
void BluetoothRemoteGattServiceWin::GattCharacteristicDiscoveryComplete(
BluetoothRemoteGattCharacteristicWin* characteristic) {
DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());
DCHECK(included_characteristics_.find(characteristic->GetIdentifier()) !=
included_characteristics_.end());
discovery_completed_included_charateristics_.insert(
characteristic->GetIdentifier());
adapter_->NotifyGattCharacteristicAdded(characteristic);
NotifyGattDiscoveryCompleteForServiceIfNecessary();
}
void BluetoothRemoteGattServiceWin::Update() {
DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());
task_manager_->PostGetGattIncludedCharacteristics(
service_path_, service_uuid_, service_attribute_handle_,
base::Bind(&BluetoothRemoteGattServiceWin::OnGetIncludedCharacteristics,
weak_ptr_factory_.GetWeakPtr()));
}
void BluetoothRemoteGattServiceWin::OnGetIncludedCharacteristics(
std::unique_ptr<BTH_LE_GATT_CHARACTERISTIC> characteristics,
uint16_t num,
HRESULT hr) {
DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());
UpdateIncludedCharacteristics(characteristics.get(), num);
included_characteristics_discovered_ = true;
NotifyGattDiscoveryCompleteForServiceIfNecessary();
}
void BluetoothRemoteGattServiceWin::UpdateIncludedCharacteristics(
PBTH_LE_GATT_CHARACTERISTIC characteristics,
uint16_t num) {
if (num == 0) {
if (included_characteristics_.size() > 0) {
ClearIncludedCharacteristics();
adapter_->NotifyGattServiceChanged(this);
}
return;
}
// First, remove characteristics that no longer exist.
std::vector<std::string> to_be_removed;
for (const auto& c : included_characteristics_) {
if (!DoesCharacteristicExist(characteristics, num, c.second.get()))
to_be_removed.push_back(c.second->GetIdentifier());
}
for (const auto& id : to_be_removed) {
RemoveIncludedCharacteristic(id);
}
// Update previously known characteristics.
for (auto& c : included_characteristics_)
c.second->Update();
// Return if no new characteristics have been added.
if (included_characteristics_.size() == num)
return;
// Add new characteristics.
for (uint16_t i = 0; i < num; i++) {
if (!IsCharacteristicDiscovered(characteristics[i].CharacteristicUuid,
characteristics[i].AttributeHandle)) {
PBTH_LE_GATT_CHARACTERISTIC info = new BTH_LE_GATT_CHARACTERISTIC();
*info = characteristics[i];
BluetoothRemoteGattCharacteristicWin* characteristic_object =
new BluetoothRemoteGattCharacteristicWin(this, info, ui_task_runner_);
included_characteristics_[characteristic_object->GetIdentifier()] =
base::WrapUnique(characteristic_object);
}
}
if (included_characteristics_discovered_)
adapter_->NotifyGattServiceChanged(this);
}
void BluetoothRemoteGattServiceWin::
NotifyGattDiscoveryCompleteForServiceIfNecessary() {
if (discovery_completed_included_charateristics_.size() ==
included_characteristics_.size() &&
included_characteristics_discovered_ && !discovery_complete_notified_) {
adapter_->NotifyGattDiscoveryComplete(this);
discovery_complete_notified_ = true;
}
}
bool BluetoothRemoteGattServiceWin::IsCharacteristicDiscovered(
BTH_LE_UUID& uuid,
uint16_t attribute_handle) {
BluetoothUUID bt_uuid =
BluetoothTaskManagerWin::BluetoothLowEnergyUuidToBluetoothUuid(uuid);
for (const auto& c : included_characteristics_) {
if (bt_uuid == c.second->GetUUID() &&
attribute_handle == c.second->GetAttributeHandle()) {
return true;
}
}
return false;
}
bool BluetoothRemoteGattServiceWin::DoesCharacteristicExist(
PBTH_LE_GATT_CHARACTERISTIC characteristics,
uint16_t num,
BluetoothRemoteGattCharacteristicWin* characteristic) {
for (uint16_t i = 0; i < num; i++) {
BluetoothUUID uuid =
BluetoothTaskManagerWin::BluetoothLowEnergyUuidToBluetoothUuid(
characteristics[i].CharacteristicUuid);
if (characteristic->GetUUID() == uuid &&
characteristic->GetAttributeHandle() ==
characteristics[i].AttributeHandle) {
return true;
}
}
return false;
}
void BluetoothRemoteGattServiceWin::RemoveIncludedCharacteristic(
std::string identifier) {
discovery_completed_included_charateristics_.erase(identifier);
included_characteristics_[identifier].reset();
included_characteristics_.erase(identifier);
}
void BluetoothRemoteGattServiceWin::ClearIncludedCharacteristics() {
discovery_completed_included_charateristics_.clear();
// Explicitly reset to null to ensure that calling GetCharacteristic() on the
// removed characteristic in GattDescriptorRemoved() returns null.
for (auto& entry : included_characteristics_)
entry.second.reset();
included_characteristics_.clear();
}
} // namespace device.
| [
"dummas@163.com"
] | dummas@163.com |
42ef0f9ea60e4a53f86692bd43a99980b1b3a903 | 0f103905a89b79de0164a9199301dc7ddb62070c | /util/Cubemap.h | 3711dbb7acc184436365fbea56c9318338fd751d | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | permissive | alexander-koch/3D-Game-Engine | 3f750033c63af00087f4dc7cf40ee068bd0b7822 | a55bedaec05428ecbbd333dd357e0f3599afeb25 | refs/heads/master | 2021-01-18T21:07:53.494175 | 2016-05-23T17:36:09 | 2016-05-23T17:36:09 | 47,876,356 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,020 | h | /*
* Copyright 2015 Alexander Koch
* File: Cubemap.h
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CUBEMAP_H
#define CUBEMAP_H
#include <string>
#include "ITexture.h"
#include "TextureLoader.h"
#include <core/Console.h>
using std::string;
class Cubemap : public ITexture
{
public:
Cubemap();
bool load(const string&, const string&, const string&, const string&, const string&, const string&);
void bind(GLenum);
void unbind();
void clear();
private:
unsigned int m_texture;
};
#endif
| [
"kochalexander@gmx.net"
] | kochalexander@gmx.net |
01b7374270d9c34f1467673c482f79fd91531ffc | 844e750651845083b94ca81dcf1f42b3eb319e01 | /codesheet/644c.cpp | 1e4f888f16b27078ece0f31b96b4d4d7411995ce | [] | no_license | qwertyran3/coding | fe197d1e1fbff9ffbb472dd46a735828361d99b1 | c08b24522e3c093de9927cf7f36c02da3a852aee | refs/heads/master | 2022-12-24T19:03:16.890969 | 2020-09-30T15:32:06 | 2020-09-30T15:32:06 | 258,968,150 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,949 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ini(arr, val) memset(arr, (val), sizeof(arr))
#define loop(i,n) for(ll i=0; i<n; i++)
#define loop1(i,n) for(ll i=1; i<=n; i++)
#define all(a) (a).begin(),(a).end()
#define tr(a) (a).begin(),(a).end(),(a).begin()
#define dupli(a) unique(all(a)),(a).end()
#define exist(s,e) (s.find(e)!=s.end())
#define dbg(x) cout << #x << " is " << x << endl;
#define pt(x) cout<<x<<"\n"
#define pts(x) cout<<x<<" "
#define mp make_pair
#define pb push_back
#define F first
#define S second
#define inf (int)1e9
#define eps 1e-9
#define PI 3.1415926535897932384626433832795
#define mod 1000000007
#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define test int t; cin>>t; while(t--)
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<string> vs;
typedef vector<pii> vpii;
typedef vector<vi> vvi;
typedef map<int,int> mii;
typedef set<int> si;
typedef pair<ll, ll> pll;
typedef vector<ll> vl;
typedef vector<string> vs;
typedef vector<pll> vpll;
typedef vector<vl> vvl;
typedef map<ll,ll> mll;
typedef set<ll> sl;
//////////////////////////////////////////////////////////////////////////////////////////
// main starts
//////////////////////////////////////////////////////////////////////////////////////////
int const lmt=1e5+5;
int main(){
#ifndef ONLINE_JUDGE
freopen("../input.txt", "r", stdin);
freopen("../output.txt", "w", stdout);
#endif
fast
test{
ll n;
cin>>n;
int a[n];
ll c=0,d=0,p=0;
loop(i,n){
cin>>a[i];
if(a[i]%2==0) d++;
else p++;
}
if((d%2==0) && (p%2==0)) {pt("YES"); continue;}
sort(a,a+n);
int j;
for(j=0; j<(n-1); j++){
if((a[j+1]-a[j])==1){c++;j++;}
}
if((p&1) && !c) pt("NO");
else pt("YES");
}
}
/*
//
*/ | [
"qwertyrani3@gmail.com"
] | qwertyrani3@gmail.com |
7af937530a5906bfd0a6ee5380aeb7eefae4ad05 | 9f9bbadcd24cb995c231c018ff2b4746e92a0e8a | /file_org/even.cpp | a11d3b510b1a84346a76d8297614f32af5ff6777 | [] | no_license | ShivamTripathi21/basic_cpp | 4462a49f28a2511642fd5af0da1c1a874e67f512 | f212c60f9db151c734f04ac2ce573ffd384411ef | refs/heads/master | 2020-03-25T18:06:01.809157 | 2018-09-29T15:00:49 | 2018-09-29T15:00:49 | 144,012,676 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 103 | cpp | #include "functions.h"
bool iseven(int number){
if(number % 2 == 0)return true;
else return false;
}
| [
"noreply@github.com"
] | noreply@github.com |
5c7de561ebe1227c43fd1019e96d09c5445d5fc1 | 7eff9d7b7feebbc972b21569439eb28fa13e5c71 | /Window System Programming/Day_4/Day_4/stdafx.cpp | 21cc5a0544d960638de444c0a843cdd25ad15c1b | [] | no_license | rlarlgns/study | fe67e5951c8d5a6498dbf6d12fb8e25dc1bc48c0 | 12abb79f5f73853feee8f03fde8c3a3d06c27cd3 | refs/heads/master | 2021-05-23T04:14:58.869789 | 2020-05-01T08:25:04 | 2020-05-01T08:25:04 | 81,773,025 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 233 | cpp |
// stdafx.cpp : 표준 포함 파일만 들어 있는 소스 파일입니다.
// Day_4.pch는 미리 컴파일된 헤더가 됩니다.
// stdafx.obj에는 미리 컴파일된 형식 정보가 포함됩니다.
#include "stdafx.h"
| [
"21kihoon@gmail.com"
] | 21kihoon@gmail.com |
b83bba63fb52308780f32e686cd79a1f9ded489a | 1df9106e475d7f1b4de615cb4f8122cc93305b7b | /Engine/ThreadLocks.h | 23ac3faca4c32b87831eb62fc23b19cbc92351c4 | [] | 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 | 2,562 | h | #pragma once
#include "EngineGlobal.h"
class CriticalSection
{
friend class CriticalSectionScope;
private:
#if defined WIN32
CRITICAL_SECTION c;
#else
#error "Platform Undefined"
#endif
public:
CriticalSection( uint32 spinCount )
{
#if defined WIN32
BOOL result = InitializeCriticalSectionAndSpinCount( &c, spinCount );
Debug::Assert( Condition(TRUE == result), "Could not create Critical Section" );
#else
#error "Platform Undefined"
#endif
}
~CriticalSection( void )
{
#if defined WIN32
DeleteCriticalSection( &c );
#else
#error "Platform Undefined"
#endif
}
};
class Lock
{
private:
#if defined WIN32
HANDLE m_hMutex;
#elif defined IOS || defined LINUX || defined MAC || defined ANDROID
pthread_mutex_t m_Mutex;
#else
#error "Platform Undefined"
#endif
public:
Lock( void )
{
#if defined WIN32
m_hMutex = CreateMutex( NULL, FALSE, NULL );
#elif defined IOS || defined LINUX || defined MAC || defined ANDROID
pthread_mutexattr_t attr;
pthread_mutexattr_init( &attr );
pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
pthread_mutex_init( &m_Mutex, &attr );
#else
#error "Platform Undefined"
#endif
}
~Lock( void )
{
#if defined WIN32
CloseHandle( m_hMutex );
#elif defined IOS || defined LINUX || defined MAC || defined ANDROID
pthread_mutex_destroy( &m_Mutex );
#else
#error "Platform Undefined"
#endif
}
void Acquire( void ) const
{
#if defined WIN32
WaitForSingleObject( m_hMutex, INFINITE );
#elif defined IOS || defined LINUX || defined MAC || defined ANDROID
pthread_mutex_lock( &m_Mutex );
#else
#error "Platform Undefined"
#endif
}
void Release( void ) const
{
#if defined WIN32
ReleaseMutex( m_hMutex );
#elif defined IOS || defined LINUX || defined MAC || defined ANDROID
pthread_mutex_unlock( &m_Mutex );
#else
#error "Platform Undefined"
#endif
}
};
class CriticalSectionScope
{
private:
CriticalSection *pSection;
public:
CriticalSectionScope(
CriticalSection §ion
)
{
pSection = §ion;
EnterCriticalSection( &pSection->c );
}
~CriticalSectionScope( void )
{
LeaveCriticalSection( &pSection->c );
}
};
class ScopeLock
{
protected:
const Lock *m_pLock;
public:
ScopeLock( const Lock &lock )
{
m_pLock = &lock;
m_pLock->Acquire( );
}
~ScopeLock( void )
{
m_pLock->Release( );
}
};
| [
"trapper@trapzz.com"
] | trapper@trapzz.com |
a75d70280bc0862eef9e4d26c26fbd44d7047890 | 6689c67620eaab900809c0cce761a9c046b389b3 | /C++/OOPS/class.cpp | e4bb2a03226d71e7b35d410e453bfb3ffda6b9ba | [] | no_license | manmeet17/Competitive-Coding | 33ecf0d56ca4a17c1adf6e96bbce69d40afe06cf | e161623eb5a4c4610663fadade6523b9ae87407d | refs/heads/master | 2020-12-30T14:44:26.708633 | 2019-05-24T12:49:30 | 2019-05-24T12:49:30 | 91,076,872 | 0 | 1 | null | 2017-10-28T19:19:32 | 2017-05-12T09:49:41 | C | UTF-8 | C++ | false | false | 903 | cpp | #include<bits/stdc++.h>
using namespace std;
class Geeks
{
private:
double rad;
public:
string geekname;
void printname();
void print()
{
cout<<"Geek: "<<geekname<<endl;
}
double compute(double r)
{
rad=r;
double area=3.14*r*r;
cout<<"Area: "<<area<<endl;
}
Geeks()
{
rad=0;
cout<<"Default Constructor called"<<endl;
cout<<rad<<endl;
}
Geeks(double r)
{
rad=r;
cout<<"Constructor called"<<endl;
cout<<rad<<endl;
}
};
void Geeks::printname()
{
cout<<"Geeky fellow is: "<<geekname<<" Radius: "<<rad<<endl;
}
int main()
{
Geeks obj(20);
obj.geekname="Manmeet";
obj.print();
// obj.compute(100);
obj.printname();
return 0;
}
| [
"meetutarun16@gmail.com"
] | meetutarun16@gmail.com |
dfaeaf8a911ec29b50d97b0a6e532b720c024b71 | f394c65d386ec9e3720dd1f559d96c209fe94114 | /trees/binary_search_tree/application/second_largest_node/include/second_largest_node.hpp | aa17f4d314f992e90eeba8600fde8c7a00b2eb5b | [] | no_license | ktp-forked-repos/algorithms-8 | 875ef6aeecf6510f3954c8daa55ac4e76aaf7871 | 74007a5ef4f8b0a7a1416dcc65eeeab3504792b4 | refs/heads/master | 2020-05-25T19:20:05.204701 | 2018-04-11T13:32:58 | 2018-04-11T13:32:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 765 | hpp | //
// second_largest_node.hpp
// algorithms. BST application.
//
// Created by alifar on 10/28/16.
// Copyright © 2016 alifar. All rights reserved.
//
#include <binary_search_tree.hpp>
/*
Write a function to return the second largest node of a tree/subtree
*/
template <class T>
Tnode<T> * LargestNode(Tnode<T> *root){
if(!root){
return nullptr;
}
while(root->right){
root = root->right;
}
return root;
}
template <class T>
Tnode<T> * SecondLargestNode(Tnode<T> *root){
if(!root){
return nullptr;
}
while(root){
if(!root->right && root->left){
return LargestNode(root->left);
} else if(root->right && (!root->right->right && !root->right->left)){
return root;
}
if(!root->right){
return root;
}
root = root->right;
}
}
| [
"lifar_tut_net@mail.ru"
] | lifar_tut_net@mail.ru |
aa9d7294a36fffb88f552eef22a7faa1e71f629e | 5670418126e79fa4eff199dfbda340727ad30ada | /map/mapgenerator.cpp | cb36d5dbd76afc762f6e176031184ed5a9d60241 | [] | no_license | wokste/steamdiggerengine | 1a8be37598f9d50a6015af35624428fcbae43b08 | d0e79a94d8dc660d25011e344cac4d3cea246928 | refs/heads/master | 2021-01-17T09:37:55.707891 | 2013-10-20T09:10:09 | 2013-10-20T09:10:09 | 12,185,012 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,904 | cpp | /*
The MIT License (MIT)
Copyright (c) 2013, Steven Wokke
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "mapgenerator.h"
#include "perlinnoise.h"
#include "../items/itemdefmanager.h"
#include "mapnode.h"
#include <cmath>
#include "../enums.h"
MapGenerator::MapGenerator(int seed, Map& newMap) : map(newMap)
{
caveNoise.reset(new PerlinNoise(seed + 1, 5, 0.5, 30));
groundNoise.reset(new PerlinNoise(seed + 2, 5, 0.5, 10));
typeNoise.reset(new PerlinNoise(seed + 3, 5, 0.5,5));
}
MapGenerator::~MapGenerator(){
}
int MapGenerator::getBlock(int x, int y, int layer) const{
double caveVal = caveNoise->noise2d(x, y);
double groundVal = groundNoise->noise2d(x, y) + 0.1 * (y - 15);
double typeVal = typeNoise->noise2d(x, y);
if (groundVal < 0) // The sky
return 0;
if (layer == Layer::front && std::abs(caveVal) < 0.05) // The caves
return 0;
return (typeVal > 0.0) ? 1 : 2; // The stone and dirt
}
| [
"wokste@gmail.com"
] | wokste@gmail.com |
430dbb118a95a4a5ff02153bb1dd66d6ba72523f | 1ba99208487e49075f687fa8b6ae17d4ea50c681 | /Code/CGAL/tmp/segments.cpp | 5e4c7345cd8562d43104d843844b4cebde67693c | [] | no_license | aocalderon/RIDIR | e79d33711ea5d355b272500969826953a6cae897 | 0ebab5c0160e1ed16ed365dc902e62d06b5b7654 | refs/heads/master | 2023-05-26T14:11:39.936432 | 2023-05-12T03:40:48 | 2023-05-12T03:40:48 | 181,546,524 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,331 | cpp | #include <iostream>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/linestring.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/assign.hpp>
#include <vector>
template <typename Segment>
struct gather_segment_statistics
{
// Remember that if coordinates are integer, the length might be floating point
// So use "double" for integers. In other cases, use coordinate type
typedef typename boost::geometry::select_most_precise
<
typename boost::geometry::coordinate_type<Segment>::type,
double
>::type type;
type min_length, max_length;
std::vector<vector<double>> segs;
// Initialize min and max
gather_segment_statistics()
: min_length(1e38)
, max_length(-1)
{}
// This operator is called for each segment
inline void operator()(Segment const& s)
{
std::vector<double> seg;
double x0 = boost::geometry::get<0, 0>(s);
seg.push_back(x0);
double x1 = boost::geometry::get<0, 1>(s);
seg.push_back(x1);
double y0 = boost::geometry::get<1, 0>(s);
seg.push_back(y0);
double y1 = boost::geometry::get<1, 1>(s);
seg.push_back(y1);
segs.push_back(seg);
type length = boost::geometry::length(s);
if (length < min_length) min_length = length;
if (length > max_length) max_length = length;
}
};
int main()
{
// Bring "+=" for a vector into scope
using namespace boost::assign;
// Define a type
typedef boost::geometry::model::d2::point_xy<double> point;
// Declare a linestring
boost::geometry::model::linestring<point> polyline;
// Use Boost.Assign to initialize a linestring
polyline += point(0, 0), point(3, 3), point(5, 1), point(6, 2),
point(8, 0), point(4, -4), point(1, -1), point(3, 2);
// Declare the gathering class...
gather_segment_statistics
<
boost::geometry::model::referring_segment<point>
> functor;
// ... and use it, the essention.
// As also in std::for_each it is a const value, so retrieve it as a return value.
functor = boost::geometry::for_each_segment(polyline, functor);
// Output the results
std::cout
<< "Number of segments: " << functor.segs.size() << std::endl
<< "Min segment length: " << functor.min_length << std::endl
<< "Max segment length: " << functor.max_length << std::endl;
return 0;
}
| [
"acald013@ucr.edu"
] | acald013@ucr.edu |
0bd3c748b68752e6a824dc05251662f24b57616e | 20f46879a2e0a354aad80db7aee0259f24f9602a | /src/tools/clang/tools/extra/clang-tidy/cppcoreguidelines/ProBoundsArrayToPointerDecayCheck.h | ec6979a5069b18107cbf2ed4fb600802a1ebe7d1 | [
"NCSA"
] | permissive | apple-oss-distributions/clang | e0b7a6ef6d2ee6fdd4ab71e5dc0a4280cb90a6f3 | 8204159ac8569f29fddc48862412243c2b79ce8c | refs/heads/main | 2023-08-14T22:37:07.330019 | 2016-12-09T19:27:15 | 2021-10-06T05:11:14 | 413,590,209 | 7 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,285 | h | //===--- ProBoundsArrayToPointerDecayCheck.h - clang-tidy--------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CPPCOREGUIDELINES_PRO_BOUNDS_ARRAY_TO_POINTER_DECAY_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CPPCOREGUIDELINES_PRO_BOUNDS_ARRAY_TO_POINTER_DECAY_H
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
/// This check flags all array to pointer decays
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines-pro-bounds-array-to-pointer-decay.html
class ProBoundsArrayToPointerDecayCheck : public ClangTidyCheck {
public:
ProBoundsArrayToPointerDecayCheck(StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CPPCOREGUIDELINES_PRO_BOUNDS_ARRAY_TO_POINTER_DECAY_H
| [
"91980991+AppleOSSDistributions@users.noreply.github.com"
] | 91980991+AppleOSSDistributions@users.noreply.github.com |
f4071a9b3c8841d27bdf023d5d0600444d45c0e6 | 879681c994f1ca9c8d2c905a4e5064997ad25a27 | /root-2.3.0/run/MicroChannelFOAM/TurbulenceMicroChannel/0.028/alpha.water | 541805200f1048130c253f5af864f4766fd76ff9 | [] | no_license | MizuhaWatanabe/OpenFOAM-2.3.0-with-Ubuntu | 3828272d989d45fb020e83f8426b849e75560c62 | daeb870be81275e8a81f5cbac4ca1906a9bc69c0 | refs/heads/master | 2020-05-17T16:36:41.848261 | 2015-04-18T09:29:48 | 2015-04-18T09:29:48 | 34,159,882 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,668 | water | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.028";
object alpha.water;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField nonuniform List<scalar>
545
(
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
1
1
0.999988
0.99996
0.999938
0.999932
0.999934
0.999937
0.99994
0.999941
0.999941
0.99994
0.999939
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999937
1
1
0.99966
0.997764
0.994708
0.994001
0.994642
0.995121
0.995493
0.995687
0.99572
0.995649
0.995539
0.995434
0.995364
0.995332
0.99533
0.995344
0.995365
0.995382
0.995393
0.995396
0.995395
0.995391
0.995386
0.99538
0.995374
0.995368
0.995366
0.995362
0.995363
0.995362
0.995363
0.995363
0.995366
0.995367
0.995367
0.995365
0.995362
0.995357
0.995354
0.99535
0.995348
0.995347
0.995344
0.196351
0.36884
0.932088
0.56272
0.4309
0.425493
0.428
0.521979
0.947616
0.9544
0.557812
0.536923
0.532455
0.53185
0.532145
0.717808
0.987219
0.676737
0.482209
0.535887
0.534537
0.534974
0.534574
0.740385
0.991491
0.985562
0.718499
0.421063
0.301716
0.349582
0.406389
0.353868
0.354514
0.411758
0.829679
0.995543
0.995592
0.995495
0.967821
0.51898
0.489378
0.496083
0.489876
0.492095
0.638221
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.99966
0.997763
0.994707
0.994
0.994642
0.995121
0.995493
0.995686
0.995719
0.995648
0.995537
0.995432
0.995362
0.995329
0.995327
0.995341
0.995362
0.995377
0.995389
0.995391
0.995391
0.995386
0.995381
0.995375
0.995368
0.995362
0.99536
0.995355
0.995356
0.995355
0.995356
0.995356
0.995359
0.995361
0.995361
0.995359
0.995355
0.99535
0.995347
0.995343
0.995341
0.99534
0.995336
1
1
0.999988
0.99996
0.999938
0.999932
0.999934
0.999937
0.99994
0.999941
0.999941
0.99994
0.999939
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999938
0.999937
1
1
1
1
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
)
;
boundaryField
{
AirInlet
{
type fixedValue;
value uniform 0;
}
WaterInlet
{
type fixedValue;
value uniform 1;
}
ChannelWall
{
type zeroGradient;
}
Outlet
{
type inletOutlet;
inletValue uniform 0;
value nonuniform List<scalar>
11
(
1
1
0.999999
0.999937
0.995344
0.638221
0.995336
0.999937
0.999999
1
1
)
;
}
FrontAndBack
{
type empty;
}
}
// ************************************************************************* //
| [
"mizuha.watanabe@gmail.com"
] | mizuha.watanabe@gmail.com |
419b696d1fdb25d3e488932254f16ea508632d48 | 260b2307c4cf8e7f68fdc7011e0804eeff6aea74 | /manyglucose-4.1-60/parallel/PrdClausesQueue.cc | 13da4ebca73611090bfd07d4d20a26d7183f0cf8 | [
"MIT"
] | permissive | nabesima/manyglucose-satcomp2020 | 32775ae466ef32b89a03c9bc95d5ecf957b917cf | 6eede39f609b1283e8eda4745a0642007d7643a2 | refs/heads/master | 2022-06-09T06:34:13.940750 | 2020-04-29T07:47:37 | 2020-04-29T07:47:37 | 257,584,234 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,922 | cc | /***********************************************************************************[LocalVals.h]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
Copyright (c) 2017-2018, Hidetomo Nabeshima
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#include "PrdClausesQueue.h"
#include <assert.h>
using namespace Glucose;
PrdClausesQueue::PrdClausesQueue(int thread_id, int nb_threads) :
thn(thread_id),
num_threads(nb_threads),
next_period(nb_threads)
{
pthread_rwlock_init(&rwlock, NULL);
// Add an empty set of clauses to which clauses acquired at period 0 are stored.
queue.insert(new PrdClauses(thn, 0));
}
PrdClausesQueue::~PrdClausesQueue()
{
while (queue.size() > 0) {
delete queue.peek();
queue.pop();
}
}
// When the current period of the thread is finished, then this method is called by the thread.
// This method notifies waiting threads to be completed.
void PrdClausesQueue::completeAddtion()
{
assert(queue.size() > 0);
PrdClauses& last = *queue[queue.size() - 1];
pthread_rwlock_wrlock(&rwlock);
// Add an empty set of clauses to which clauses acquired at the next period are stored.
queue.insert(new PrdClauses(thn, last.period() + 1));
// DEBUG
//printf("T%d@p%" PRIu64 ": %dclauses, %dlits\n", thn, last.period(), last.numClauses(), last.size());
// Complete and notify it to all waiting threads
last.completeAddition();
// Remove a set of clauses that were sent to other threads
while (queue.size() > 1) {
PrdClauses* head = queue.peek();
if (head->getNumExportedThreads() != num_threads - 1)
break;
queue.pop();
delete head;
}
pthread_rwlock_unlock(&rwlock);
}
// When exporting to the specified thread is finished, then this method is called.
void PrdClausesQueue::completeExportation(int thn, PrdClauses& prdClauses)
{
assert(next_period[thn] == prdClauses.period());
next_period[thn]++;
prdClauses.completeExportation(thn);
}
// Get a set of clauses which are generated at the specified period.
PrdClauses* PrdClausesQueue::get(int thread, int period) {
int p = next_period[thread];
if (period < p) return NULL; // 'period' is already exported to 'thn'
pthread_rwlock_rdlock(&rwlock);
assert(queue.size() > 0);
//printf("queue[0]->period() = %d, period = %d\n", queue[0]->period(), period);
assert(queue[0]->period() <= p);
int index = p - queue[0]->period();
assert(0 <= index);
assert(index < queue.size());
PrdClauses *prdClauses = queue[index];
//printf("> queue[%d]->period() = %d, period = %d\n", index, queue[index]->period(), period);
assert(prdClauses->period() == p);
pthread_rwlock_unlock(&rwlock);
return prdClauses;
}
| [
"nabesima@yamanashi.ac.jp"
] | nabesima@yamanashi.ac.jp |
3935a616f4756f079e9dd74a48e74cffee9f720e | 4b079e58941be01982b59f92b02a63dc59439aa3 | /ghkm/basic/MemDgnst.h | d96819fdc7e4346fca5dbf2e3cae559d6f0449ca | [] | no_license | isi-nlp/sbmt | 143b784540e79cdbeaed3655588e8f4e38157284 | 56b2a2651b7741219657d095db3ebd7875ed4963 | refs/heads/master | 2020-04-06T13:56:13.370832 | 2018-11-21T18:59:31 | 2018-11-21T18:59:31 | 47,573,153 | 6 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 986 | h | // Copyright (c) 2001, 2002, 2003, 2004, 2005, Language Weaver Inc, All Rights Reserved
/*
* Class for memory diagnostics.
*/
#ifndef _MemDgnst_H_
#define _MemDgnst_H_
#include "LiBEDebug.h"
#include <cassert>
//! Memory allocation class.
class MemDgnst : public LiBEDebug {
public:
virtual ~MemDgnst() {}
inline void *operator new (size_t n) {
char *ret = memp;
memp += n;
if (memp <= memp_end)
return ret;
more_core ();
ret = memp;
memp += n;
assert(memp <= memp_end);
return ret;
}
inline void* operator new(std::size_t, void* __p) throw()
{ return __p; }
inline void operator delete (void *) {}
static void clear_memory ();
static size_t total_mem_size() { return total_size;}
private:
struct mem_header {
mem_header *next;
size_t size;
};
static char *memp;
static mem_header *memp_start;
static char *memp_end;
static void more_core ();
static size_t total_size;
};
#endif/* _MemDgnst_H_*/
| [
"pust@Michaels-MacBook-Pro-2.local"
] | pust@Michaels-MacBook-Pro-2.local |
92b9015d81f6b33eff0929afc700a63083c4f522 | 575a7fff16e2f34d8515c62be210c27f3d1df4aa | /src/minerplot.h | aaad9ed88f0c98ee56768663bebbdec8ca90bdee | [
"Unlicense"
] | permissive | GeopaymeInc/AvalonMiner | 5c1398be6a6165e690c4593fffc0c124398fa23d | 7ec1ec45f9bfcaaeee0acffcc0900c802faf40db | refs/heads/master | 2021-05-30T00:18:35.623535 | 2014-08-27T02:29:18 | 2014-08-27T02:29:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 911 | h | #include <qwt_plot.h>
#include <qwt_legend.h>
#include <qwt_plot_canvas.h>
#include "minerstat.h"
class QwtPlotCurve;
class MinerPlot : public QwtPlot
{
Q_OBJECT
public:
MinerPlot(QWidget * = 0);
const QwtPlotCurve *minerCurve(int id) const
{
return data[id].curve;
}
void clearCurve();
// void restart();
signals:
void addPlotValue(const plotInfo &);
protected:
void timerEvent(QTimerEvent *e);
private Q_SLOTS:
void legendChecked(const QVariant &, bool on);
private:
void showCurve(QwtPlotItem *, bool on);
void plotReconfig(QwtPlotCanvas *, QwtLegend *);
struct
{
QwtPlotCurve *curve;
double data[HISTORY];
} data[value_N];
double timeData[HISTORY];
int dataCount;
MinerStat minerStat;
int timer;
QwtPlotCanvas *canvas;
QwtLegend *mylegend;
};
| [
"ecl.time@gmail.com"
] | ecl.time@gmail.com |
f2eb25f88e3257c0cb1a101e3a951ed5745c2370 | f41e49c73435d88cb8319d088acb4f4a5de44c71 | /binary_search_recursion.cpp | 7eddc758baaf122f8231804cfa6252f7470dff6e | [] | no_license | MansiSMore/Searching-and-Sorting-Algorithms | 9b6c3d80bf97215cf1ff974bf2feb394532119be | 91555e304898b5ab28f1777e9d34e436799a332b | refs/heads/main | 2023-07-15T21:58:51.049957 | 2021-08-23T20:33:37 | 2021-08-23T20:33:37 | 399,202,890 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,390 | cpp | //Binary Search - Search a sorted array by repeatedly dividing the search interval in half.
//The time complexity : O(logn).
/*
Note : Thank you. Exactly what I was looking for. (left + right) / 2 is not a safe operation on high numbers.
Better to use left + ((right - left)/2) or (right + left) >> 1 which are equivalent.
*/
#include <iostream>
using namespace std;
int binary_search_recursion(int arr[], int low, int high, int x)
{
if(low <= high)
{
int mid = low + (high - low) / 2;
//If the element is present at the middle
if(arr[mid] == x)
return mid;
//If the element is lower than search element
else if(x < arr[mid])
return binary_search_recursion(arr, low, mid - 1, x);
//If the element is greater than search element
else
return binary_search_recursion(arr, mid + 1, high, x);
}
return -1;
}
int main()
{
int arr[] = {10, 20, 30, 40, 50, 60, 70 };
//If array is not sorted, first sort it.
int len = sizeof(arr)/sizeof(int), x = 0, ans = 0;
cout << "Enter the element which you want to search : \n";
cin >> x;
ans = binary_search_recursion(arr, 0, len - 1, x);
if(ans == -1)
cout << "Element is not present in array.\n";
else
cout << "Element is present at index " << ans << endl;
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
93124b372dbbbbec6fce3db33142c3b83b1af28c | 68ae824285562080e9cf090119c49b15f89093a0 | /linkList/445.cpp | 6dc29549977238dab7e88dc8b6a3d42cda6b57e7 | [] | no_license | ZexinYan/Introduction_to_algorithm_notebook | 55e58e2d4decf507835fff53058fe302e4363e0b | 9d137bd092040f21465339e216a1809e8ded248e | refs/heads/master | 2021-06-14T21:38:58.074432 | 2017-04-05T08:02:25 | 2017-04-05T08:02:25 | 75,030,644 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,109 | cpp | /**
* differ from 2.cpp
*/
class Solution {
private:
int getLen(ListNode* l1) {
ListNode* tmp = l1;
int num = 0;
while (tmp) {
num++;
tmp = tmp->next;
}
return num;
}
ListNode* helper(ListNode* l1, ListNode* l2, int offset) {
if (!l1) { return nullptr; }
ListNode* result = offset == 0 ? new ListNode(l1->val + l2->val) : new ListNode(l1->val);
ListNode* post = offset == 0 ? helper(l1->next, l2->next, 0) : helper(l1->next, l2, offset - 1);
if (post && post->val > 9) {
post->val %= 10;
result->val++;
}
result->next = post;
return result;
}
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int len1 = getLen(l1);
int len2 = getLen(l2);
ListNode* head = new ListNode(1);
head->next = len1 < len2 ? helper(l2, l1, len2 - len1) : helper(l1, l2, len1 - len2);
if (head->next->val > 9) {
head->next->val %= 10;
return head;
}
return head->next;
}
}; | [
"yzx9610@outlook.com"
] | yzx9610@outlook.com |
0bb7443213d5952d91e065856e064ffa0bb48465 | 12979489d3489cfca9ec627a91830bd8ac695be8 | /symbletable/symbletable.h | 940e2b8a45c1a7867129c08d306cb5e27de8cb9b | [] | no_license | linan1109/C0-compiler | 20388276835d59ed67347c8c3a6c1abf22d84966 | ab7e1f82ff97738e57120bb0707b6c2b963c3269 | refs/heads/master | 2022-04-24T11:51:25.643269 | 2019-12-24T13:09:05 | 2019-12-24T13:09:05 | 229,587,717 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,329 | h | #pragma once
#include <vector>
#include <optional>
#include <utility>
#include <cstdint>
#include <algorithm>
#include <instruction/instruction.h>
namespace miniplc0 {
class one_symbol final{
std::string _name; //标识符名称
int32_t _kind; /*种类
0:常量
1:变量
2:函数
*/
int32_t _type; /*类型
0:void(仅对于无返回值函数)
1:int32_t
2: char
*/
int32_t _value; /*
未初始化:0
已初始化:1
*/
int32_t _size; /*函数:参数个数
数组:元素个数
其他:-1
*/
int32_t all_index;
public:
bool operator==(const one_symbol &rhs) const;
bool operator!=(const one_symbol &rhs) const;
one_symbol(const std::string &name, int32_t kind, int32_t type, int32_t value, int32_t size);
const std::string &getName() const;
void setName(const std::string &name);
int32_t getKind() const;
void setKind(int32_t kind);
int32_t getType() const;
void setType(int32_t type);
int32_t getValue() const;
void setValue(int32_t value);
int32_t getSize() const;
void setSize(int32_t size);
int32_t getAllIndex() const;
void setAllIndex(int32_t allIndex);
};
class SymbleTable final{
private:
std::string name;
using int32_t = std::int32_t;
std::vector<one_symbol> List; //符号表
SymbleTable *father;
int32_t count;
public:
SymbleTable *getFather() const;
void setFather(SymbleTable *father);
public:
const std::string &getName() const;
void setName(const std::string &name);
int32_t getCount() const;
void setCount(int32_t count);
SymbleTable(){
name = "";
father = nullptr;
count = 0;
}
SymbleTable(SymbleTable *_father,std::string _name){
father = _father;
name = _name;
count = 0;
}
int32_t addCount();
bool operator==(const SymbleTable &rhs) const;
bool operator!=(const SymbleTable &rhs) const;
bool isDeclared(const std::__cxx11::basic_string<char> &s);
int32_t getKindByName(const std::string &s);
bool addSymble(const std::string &s, int32_t kind, int32_t type, int32_t value, int32_t size);
int32_t getTypeByName(const std::string &s);
int32_t getValueByName(const std::string &s);
std::pair<int32_t, int32_t> index_in_all(const std::string &s);
bool changeSizeOfFun(const std::string &s, int32_t size);
one_symbol * getByName(const std::string &s);
int32_t getSizeByName(const std::string &s);
int32_t getLevel();
int32_t setValueByName(const std::string &s);
};
class function{
private:
std::string _name;
std::vector< std::pair<std::string, std::pair<std::int32_t , int32_t > > >_params;
int32_t _type;
std::vector<Instruction> _instructions;
int32_t _level;
int32_t _name_index;
std::vector<int32_t> _break_counts;
//name
//kind /*种类
// 0:常量
// 1:变量
//type
// 0:void(仅对于无返回值函数)
// 1:int32_t
// 2: char
public:
function(const std::string &name, int32_t type, int32_t nameIndex, int32_t level);
public:
bool operator==(const function &rhs) const;
bool operator!=(const function &rhs) const;
int32_t getLevel() const;
void setLevel(int32_t level);
int32_t getNameIndex() const;
void setNameIndex(int32_t nameIndex);
const std::string &getName() const;
void setName(const std::string &name);
int32_t getType() const;
const std::vector<Instruction> &getInstructions() const;
void setInstructions(const std::vector<Instruction> &instructions);
void setType(int32_t type);
const std::vector<std::pair<std::string, std::pair<std::int32_t, int32_t>>> &getParams() const;
void setParams(const std::vector<std::pair<std::string, std::pair<std::int32_t, int32_t>>> ¶ms);
bool addParam(const std::string &name, int32_t kind, int32_t type);
void addInstruction(const int32_t, Operation operation, int32_t x, int32_t y);
bool setInstructionX(int32_t Index, int32_t x);
bool addBreak(int32_t count);
const std::vector<int32_t> &getBreakCounts() const;
void setBreakCounts(const std::vector<int32_t> &breakCounts);
};
}
| [
"linan119@yeah.net"
] | linan119@yeah.net |
926dc57e8427a90cf2db9f04ba111f86a7855d32 | 8a2f3bb64e8feb3ccff65eb3edf86a47d62b0b10 | /360/src/common/statictextbutton.cpp | f79ca7ba4d1c1ad3cea16480e017c0b0e98c2168 | [] | no_license | GLDsuh-a/qt-1 | 010489a59a26a62747eaadddf37e4b0d80546460 | 0a642fa56f71d94e7f815305a806173c8e586ddb | refs/heads/master | 2021-01-17T06:59:12.293528 | 2015-08-28T03:08:13 | 2015-08-28T03:08:22 | 41,582,969 | 7 | 2 | null | 2015-08-29T06:18:11 | 2015-08-29T06:18:11 | null | UTF-8 | C++ | false | false | 855 | cpp | #include "statictextbutton.h"
#include <QLabel>
#include <QVBoxLayout>
#include "staticbutton.h"
StaticTextButton::StaticTextButton(QWidget *parent)
: QWidget(parent)
{
m_num = 4;
m_button = new StaticButton;
m_textLabel = new QLabel;
m_textLabel->setObjectName("staticText");
QVBoxLayout *vLayout = new QVBoxLayout;
vLayout->addWidget(m_button, 0, Qt::AlignCenter);
vLayout->addSpacing(5);
vLayout->addWidget(m_textLabel, 0, Qt::AlignHCenter);
vLayout->setContentsMargins(0, 0, 0, 0);
this->setLayout(vLayout);
connect(m_button, SIGNAL(buttonClicked()), this, SIGNAL(buttonClicked()));
}
void StaticTextButton::setButtonPix(const QString &pix)
{
m_button->setOneButtonInfo(pix, m_num);
}
void StaticTextButton::setText(const QString &text)
{
m_text = text;
m_textLabel->setText(m_text);
}
| [
"ltz121320@163.com"
] | ltz121320@163.com |
a2fca666eac7994bda873d4fce38ade342fe1e45 | 3accd018e09d3fa1cf1a403219a7a64d00866210 | /AlgorithmicPractice/AlgorithmicPractice/Demo5/Demo5_1/Demo5_1_SortList.cpp | e2b98958078c8315d4440b28714daf3e9ebbd6be | [] | no_license | COMOCO-5672/AlgorithmicPractice | cd40bbfd87f172bc315dd732000c99daf594514f | 553f7efe1e3e6f057d9c5490ed9e158e2d550f52 | refs/heads/master | 2023-08-25T00:26:00.693198 | 2020-12-17T13:49:42 | 2020-12-17T13:49:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 772 | cpp | //
// Demo5_1_SortList.cpp
// AlgorithmicPractice
//
// Created by 帅斌 on 2019/2/20.
// Copyright © 2019 personal. All rights reserved.
//
#include "Demo5_1_SortList.hpp"
ListNode* sortList(ListNode* head) {
if (!head || !head->next) return head;
ListNode *slow = head, *fast = head, *pre = head;
while (fast && fast->next) {
pre = slow;
slow = slow->next;
fast = fast->next->next;
}
pre->next = NULL;
return merge(sortList(head), sortList(slow));
}
ListNode* merge(ListNode* l1, ListNode* l2) {
if (!l1) return l2;
if (!l2) return l1;
if (l1->val < l2->val) {
l1->next = merge(l1->next, l2);
return l1;
} else {
l2->next = merge(l1, l2->next);
return l2;
}
}
| [
"1533607721@qq.com"
] | 1533607721@qq.com |
7816a5ec9717923d675cc7cf34b503aefd0f5fce | 70015191dd9eef400d81240a321acfdd1df859bb | /examples/sessionusage/main.cpp | b05431557e941f0def40608c4955a9cc57985f06 | [] | no_license | SindenDev/Qtufao | 6050f21ac82ad803b46958881961bff0da10a07e | 55bf878c9757c72e7b5f529a3fe96884a260b931 | refs/heads/master | 2021-01-15T21:25:17.054141 | 2017-08-11T01:05:32 | 2017-08-11T01:05:32 | 99,868,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,517 | cpp | /*
Copyright (c) 2012 Vinícius dos Santos Oliveira
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <QtCore/QCoreApplication>
#include <QUrl>
#include "tufao/httpserver.h"
#include "tufao/httpserverrequestrouter.h"
#include "tufao/httpserverrequest.h"
#include "tufao/httpfileserver.h"
#include "tufao/simplesessionstore.h"
#include "tufao/urlrewriterhandler.h"
#include "tufao/notfoundhandler.h"
#include "sethandler.h"
#include "readhandler.h"
#include "unsethandler.h"
int main(int argc, char *argv[])
{
Q_INIT_RESOURCE(static);
QCoreApplication a(argc, argv);
Tufao::HttpServer server;
SetHandler setHandler;
ReadHandler readHandler;
UnsetHandler unsetHandler;
Tufao::HttpServerRequestRouter router{
{QRegularExpression{"^/$"},
Tufao::UrlRewriterHandler::handler(QUrl("/index.html"))},
{QRegularExpression{""}, Tufao::HttpFileServer::handler(":/public")},
{QRegularExpression{"^/set(?:/(\\w*))?$"}, setHandler},
{QRegularExpression{"^/read(?:/(\\w*))?$"}, readHandler},
{QRegularExpression{"^/unset(?:/(\\w*))?$"}, unsetHandler},
{QRegularExpression{""}, Tufao::NotFoundHandler::handler()}
};
// We set the router as the global request handler
QObject::connect(&server, &Tufao::HttpServer::requestReady,
&router, &Tufao::HttpServerRequestRouter::handleRequest);
// Last, we run our server
server.listen(QHostAddress::Any, 8080);
return a.exec();
}
| [
"sindendev@foxmail.com"
] | sindendev@foxmail.com |
5ca5fb3a252775c8fb7809a6f0653ee8d6a4632f | 67611090dd9203fcac9febdaef32f1ab60d777b6 | /c++/faster-than-wind/ftw-editor/src/Editor/UI/button.cpp | f52b76f89261aa5ea47ae88b6d3656e9feaa2abd | [] | no_license | Hopson97/Ancient-Projects | bdcb54a61b5722a479872961057367c96f98a950 | bea4c7e5c1af3ce23994d88a199427ac2ce69139 | refs/heads/master | 2020-06-26T18:39:08.194914 | 2020-03-16T07:55:40 | 2020-03-16T07:55:40 | 199,717,112 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,367 | cpp | #include "button.h"
/*
=================================================================================================================================================================
Button is class that is a.. well a button that can be clicked.
=================================================================================================================================================================
*/
Button::Button(const sf::Texture& texture, const sf::Vector2f pos):
Object(texture)
{
mSprite.setPosition(pos); //Set position
}
/*
=================================================================================================================================================================
clicked() returns true if the button is clicked
=================================================================================================================================================================
*/
bool Button::clicked(sf::RenderWindow& window)
{
window.draw(mSprite);
if (touchingMouse(window) && sf::Mouse::isButtonPressed(sf::Mouse::Left)) // If clicked
{
mSprite.setColor(sf::Color(200, 200, 200, 255)); //Change colour
return true; //Return true;
}
else if (touchingMouse(window)) //If mouse rolled over
{
mSprite.setColor(sf::Color(220, 220, 220, 255)); //Change colour
return false; //But as not clicked, return false
}
else //If no events
{
mSprite.setColor(sf::Color(255, 255, 255, 255)); //Go to default colour
return false; //Return false
}
}
/*
=================================================================================================================================================================
touchingMouse() returns true if the button is touching the mouse
=================================================================================================================================================================
*/
bool Button::touchingMouse(sf::RenderWindow& window)
{
sf::IntRect bound(mSprite.getLocalBounds()); //For getting button size
sf::Vector2i mouse(sf::Mouse::getPosition(window)); //Location of mouse relative to window
if (mouse.x > mSprite.getPosition().x //If mouse is to the right of the button
&& //and
mouse.x < mSprite.getPosition().x + bound.width //If mouse is to the left of the button
&& //and
mouse.y > mSprite.getPosition().y //If mouse is below of the button
&& //and
mouse.y < mSprite.getPosition().y + bound.height) //If mouse is above the button
{
return true; //Return true
}
else
{
return false; //Else, return false
}
}
| [
"mhopson@hotmail.co.uk"
] | mhopson@hotmail.co.uk |
7f8075427cbdfc3a89b7b93d0de3c00d77f89b5d | 5a90e6067568350d489b3d2f6564aaad07e6a50c | /OpenFOAM-Wing-Mesh-Refinement-Study-main/OpenFOAM-Wing-Mesh-Refinement-Study-main/Mesh_Refinement/case1/0/omega | bd871a3e68e060205b85efc26f9491fa8351461d | [
"GPL-3.0-only",
"MIT"
] | permissive | Aeroguyyy/OpenFOAM-Cases-Interfluo | 97fdecc4ccf45c0d6db6031a38e0f86854315230 | 6d8ca5639d601e3d1766cc4edf32eba5db93bb2c | refs/heads/main | 2023-07-12T03:35:05.621598 | 2021-08-20T02:00:31 | 2021-08-20T02:00:31 | 398,274,700 | 1 | 0 | MIT | 2021-08-20T12:49:52 | 2021-08-20T12:49:52 | null | UTF-8 | C++ | false | false | 1,302 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v2012 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0";
object omega;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 -1 0 0 0 0];
internalField uniform 2.45;
boundaryField
{
inlet
{
type fixedValue;
value uniform 2.45;
}
outlet
{
type zeroGradient;
}
side
{
type omegaWallFunction;
value uniform 2.45;
}
wing
{
type omegaWallFunction;
value uniform 2.45;
}
}
// ************************************************************************* //
| [
"79390007+Interfluo@users.noreply.github.com"
] | 79390007+Interfluo@users.noreply.github.com | |
4b02f8d75cabe578422cbca0a2cd90af67531416 | 837c4ac8f0ebb45a59b1305077180e21f41d6ddb | /lab7_q2.cpp | 7d5edcb359492e0b724f24983827108e83f6f6c5 | [] | no_license | nayantharar/cs141-lab7 | ce3d2f9675f703070fbbf6d07957291817009e0f | 2352a117ba006bc667e6022981ea68ca75005641 | refs/heads/master | 2020-03-31T00:14:35.651054 | 2018-11-23T12:26:34 | 2018-11-23T12:26:34 | 151,731,900 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 540 | cpp | //include the library
#include<iostream>
using namespace std;
//declaration and definition of the recursive function
int printnum(int n,int a)
{ //loop terminator
if(a>n)
{
return 0;
}
//loop running
else
{
//printing the numbers in the increasing order
cout<<a<<endl;
a++;
//call function
printnum(n,a);
return 0;
}
}
//write the main function
int main()
{
//ask the user for any number
int a;
cout<<"\n Enter any number ";
cin>>a;
//call the function
printnum(a,1);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
0e4dfd63599d82ee76ae6c4502a09f92210b7e83 | 5c23b302684f260fbbad2edfe19dd7cf16fd822c | /ch03/exercise_3_35.cpp | f9b247355efa1db841735494eef20630f17a2368 | [] | no_license | platoTao/CPP_Primer_Answer | 123c99b0283ba15d51037cf16f2a6886b570d394 | b1837239c9d58e54587f7a5ae44ee220238f5c95 | refs/heads/master | 2021-04-03T06:43:04.089574 | 2018-06-10T06:25:57 | 2018-06-10T06:25:57 | 124,714,759 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 270 | cpp | #include<iostream>
#include<vector>
using namespace std;
int main(){
constexpr size_t arry_size = 10;
int a[arry_size] = {0,1,2,3,4,5,6,7,8,9};
int *p = a;
for(;p!=end(a);p++)
*p = 0;
for(auto i:a)
cout << i << " ";
return 0;
}
| [
"1209015200@qq.com"
] | 1209015200@qq.com |
aac3125854776522cf1a1b053ccf131997b597eb | ad472befb7a3422406394836245b6a9ddc44c593 | /codechef/dec_challenge/vaccine.cpp | b7add25b83361532dac0a9f467934fa103b96537 | [] | no_license | aa-ryan/Comp-Prog | 34840b6038ab208349cc8f98a23ede9b15bd70a5 | dbcce36a2ce319f3eca5c1033eab3cc2e861bf7c | refs/heads/master | 2023-06-03T11:17:54.765702 | 2021-06-21T13:49:21 | 2021-06-21T13:49:21 | 297,729,534 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 666 | cpp | #include<bits/stdc++.h>
#define endl '\n'
using namespace std;
int main() {
int d1,d2,v1,v2,dd;
cin >> d1 >> v1 >> d2 >> v2 >> dd;
if (d1 == d2) {
int cnt = dd/(v1 + v2);
cout << ((dd % (v1+v2) == 0) ? cnt : cnt+1) << endl;
}
else {
pair<int, int> p1, p2;
int mul=0;
p1 = make_pair(d1, v1);
p2 = make_pair(d2, v2);
(p1.first > p2.first) ? mul = p2.second : mul = p2.second;
int mx = max(d1, d2) , mi = min(d1, d2);
int ans = mx - mi, pre = (mx - mi) * mul;
ans += (dd-pre)/(v1+v2) + 1;
cout << ans << endl;
}
}
| [
"aryansinha6363@gmail.com"
] | aryansinha6363@gmail.com |
c4921ed3ba9cb5ce61da012f97525dfb7e4b1241 | ed688cf001bd39394a9ced39c4ed5201a166be85 | /BitManipulation/SingleNumber.cpp | af714562ca382f45b9444525a9d75926c2992a1f | [] | no_license | ng29/Interview-Bit-Solution | e7959c99866c3b59e7b3911f7c0755cb96acf826 | efd20ce2b297ef0a8028c7bece4937a18f0e7157 | refs/heads/master | 2021-09-03T20:14:25.163897 | 2018-01-11T17:24:33 | 2018-01-11T17:24:33 | 107,449,259 | 0 | 2 | null | 2017-10-28T10:14:46 | 2017-10-18T18:48:01 | C++ | UTF-8 | C++ | false | false | 155 | cpp | int Solution::singleNumber(const vector<int> &A) {
int l=A.size();
int ans=0;
for(int i=0;i<l;i++){
ans^=A[i];
}
return ans;
}
| [
"noreply@github.com"
] | noreply@github.com |
15da0c1466809cc6592240c2a41849746b309d76 | cf5c1d28f4e097379eccd5f0496780060f92c023 | /queueSort/queueSort/queueSort.cpp | 03c622df5c953ea7d502293aac37201e4728396e | [] | no_license | zotov228/queueSortLaba10_1 | 9cd47f3e48677dc4b6f8e2fe91b276cb8b64a4dc | cf2ab4b4f79099888ef99ced091b6ea67ff1e55e | refs/heads/master | 2021-01-12T01:23:29.696883 | 2017-01-09T00:24:18 | 2017-01-09T00:24:18 | 78,379,807 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 887 | cpp | // queueSort.cpp: определяет точку входа для консольного приложения.
//
#include "stdafx.h"
#include <iostream>
#include <queue>
using namespace std;
int main()
{
queue<int> one_queue;
queue<int> side_queue;
queue<int> res_queue;
int k = 0;
// One queue. Cout
cout << "One queue" << '\n';
for (int i = 0; i <= 10; i++) {
one_queue.push(k = rand() % 10 + 1);
cout << k << ' ';
}
cout << '\n';
//process sort
int min, tek;
while (!one_queue.empty()) {
min = one_queue.front();
one_queue.pop();
side_queue.push(min);
while (!one_queue.empty())
{
tek = one_queue.front();
one_queue.pop();
if (tek < min)min = tek;
side_queue.push(tek);
}
}
cout << "Result process:" << '\n';
for (int i = 0; i <= 10; i++) {
res_queue.push(k = rand() % tek);
cout << k << ' ';
}
system("pause");
return 0;
}
| [
"zotov228@tut.by"
] | zotov228@tut.by |
613d8e30ccfdf92b27f0b35cfa255038e6afcc5d | 9bb67fbbb0f658c485bb1ecda7b4b73f67f1de79 | /Graph/Topological Sorting/Topological Sorting/Topological Sorting.cpp | 222c9680cd6607f679a5753d1accbd5088e22ec4 | [] | no_license | KamilJanda/Algorithm-and-data-structure | d1d70b7a61661f293beaf032eba59c5bd3a8e0ea | ffcb56b78432f203aa0d3d90eeeb7057523afbf4 | refs/heads/master | 2021-01-23T03:43:02.820968 | 2017-05-17T10:21:54 | 2017-05-17T10:21:54 | 86,112,717 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,671 | cpp | // Topological Sorting.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
using namespace std;
struct node
{
int vertex;
char colour;
node* next = NULL;
};
class Graph
{
int V;
node** adj;
int* result;
int idResult;
public:
Graph(int V);
void addEdge(int w, int v);
void topologicalSortUtil(int u);
void topologicalSort();
};
Graph::Graph(int V)
{
this->V = V;
adj = new node*[V];
for (int i = 0; i < V; i++)
{
adj[i] = new node;
adj[i]->vertex = i;
}
idResult = V - 1;
result = new int[V];
}
void Graph::addEdge(int w, int v)
{
node* item = new node;
item->vertex = v;
item->next = adj[w]->next;
adj[w]->next = item;
}
void Graph::topologicalSortUtil(int u)
{
adj[u]->colour = 'G';
node* adjacentsU = adj[u]->next;
while (adjacentsU!=NULL)
{
int v = adjacentsU->vertex; //id (vertex) in adjacent array
if (adj[v]->colour == 'W') topologicalSortUtil(v);
else if (adj[v]->colour == 'G')
{
cout << "It is not DAG";
return;
}
adjacentsU = adjacentsU->next;
}
adj[u]->colour = 'B';
result[idResult] = adj[u]->vertex;
idResult--;
}
void Graph::topologicalSort() //O(V+E)
{
for (int i = 0; i < V; i++)
{
adj[i]->colour = 'W';
}
for (int i = 0; i < V; i++)
{
if (adj[i]->colour == 'W') topologicalSortUtil(i);
}
for (int i = 0; i < V; i++) cout << result[i] << " ";
}
int main()
{
Graph g(6);
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
cout << "Following is a Topological Sort of the given graph \n";
g.topologicalSort();
system("pause");
return 0;
}
| [
"kamiljanda@yahoo.pl"
] | kamiljanda@yahoo.pl |
4a4791264676509a4c5308d3b6f102bd191054da | d27fc0c975eea686d0a9764a9da4248f5b521130 | /raschet.cpp | 2d46c7c6d055e3bfa9ceef62e7d3b745e9c52cf4 | [] | no_license | uliana-titanyuk/take__2 | 26c64bc1300738bfff5bf0a0d7035f841b7c9cc2 | b9a924ecd6f2d856bd7da4f9486afbbb2d210f70 | refs/heads/main | 2023-05-12T14:57:43.716623 | 2021-06-02T11:23:18 | 2021-06-02T11:23:18 | 373,135,361 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 732 | cpp | #include "Func.h"
#include "CRat.h"
#include "CVectRat.h"
void raschet(void) {
int size;
cout << "Vvedite dlinu vectora" << endl;
cin >> size;
CVectRat vect1(size);
CVectRat vect2(size);
gorCVectRat vect3(size);
vertCVectRat vect4(size);
CRat m;
vect1 = input(size);
vect2 = input(size);
cout << "________________________________________" << endl;
cout << "\n";
vect3 = vect1 + vect2;
vect3.print();
vect4 = vect3;
std::cout << "\n";
vect3 = vect1 - vect2;
vect3.print();
cout << "\n";
m = vect1 * vect2;
m.print();
cout << "\n";
vect4.print();
vect4 = vect3;
vect4.print();
m.print();
cout << "________________________________________" << endl;
cout << "\n";
};
| [
"noreply@github.com"
] | noreply@github.com |
07b6ecef27e0b93a5aeb16da194feda27d32bf38 | 15419e6b114d5b89e78648dbae52a0aae276b673 | /UVa/Comptitive Programming/Ch-03 Problem Solving Paradigms/08 Non Classical/UVa 10337 - Flight planner - AC.cpp | c6026499a6f7280923016a10bb4867f56139fe5b | [] | no_license | ImnIrdst/ICPC-Practice-2015-TiZii | 7cde07617d8ebf90dc8a4baec4d9faec49f79d13 | 73bb0f84e7a003e154d685fa598002f8b9498878 | refs/heads/master | 2021-01-10T16:29:34.490848 | 2016-04-08T04:13:37 | 2016-04-08T04:13:37 | 55,749,815 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,034 | cpp | #include <iostream>
#include <stdio.h>
#include <string>
#include <string.h>
#include <algorithm>
#include <functional>
#include <cmath>
#define INF (int)1e9
#define int64 long long
#define maxn 1000
#define maxh 10
using namespace std;
int dp[15][1010], a[15][1010]={0}, N;
int solve(int n, int h){
if(n==0 && h==9) return 0;
//if((n!=0 && n!=N) && h==9) return INF;
if(h>9 || h<0 || n<0) return INF;
if(dp[h][n]!=-1) return dp[h][n];
int ans=INF;
if( n-1>=0 && h-1>0) ans=min(ans,solve(n-1,h)-a[h][n-1]+30);
if( n-1>=0 && h-1>=0) ans=min(ans,solve(n-1,h-1)-a[h-1][n-1]+20);
if( n-1>=0 && h+1<10) ans=min(ans,solve(n-1,h+1)-a[h+1][n-1]+60);
return dp[h][n]=ans;
}
int main(){
int tc; cin >> tc;
while(tc--){
for(int i=0 ; i<maxh ; i++){
for(int j=0 ; j<maxn ; j++){
dp[i][j]=-1;
}
}
int n; cin >> n; n/=100;
for(int j=0 ; j<10 ; j++){
for(int i=0 ; i<n ; i++){
cin >> a[j][i];
}
}
N=n;
cout << solve(n,9) << endl << endl;
}
return 0;
} | [
"imn.irdst@gmail.com"
] | imn.irdst@gmail.com |
e53f16696c010d8a1f5b1e72966bbe751dc27779 | ffb568806e34199501c4ca6b61ac86ee9cc8de2e | /tool_project/SequenceEditor/old_lib/opensource/cpputest/include/CppUTestExt/MockNamedValue.h | 61362b9713850ee7e5705afc3d7de1f5b0b9c672 | [
"BSD-3-Clause"
] | permissive | Fumikage8/gen7-source | 433fb475695b2d5ffada25a45999f98419b75b6b | f2f572b8355d043beb468004f5e293b490747953 | refs/heads/main | 2023-01-06T00:00:14.171807 | 2020-10-20T18:49:53 | 2020-10-20T18:49:53 | 305,500,113 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,408 | h | /*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 D_MockNamedValue_h
#define D_MockNamedValue_h
/*
* MockParameterComparator is an interface that needs to be used when creating Comparators.
* This is needed when comparing values of non-native type.
*/
class MockNamedValueComparator
{
public:
MockNamedValueComparator() {}
virtual ~MockNamedValueComparator() {}
virtual bool isEqual(void* object1, void* object2)=0;
virtual SimpleString valueToString(void* object)=0;
};
class MockFunctionComparator : public MockNamedValueComparator
{
public:
typedef bool (*isEqualFunction)(void*, void*);
typedef SimpleString (*valueToStringFunction)(void*);
MockFunctionComparator(isEqualFunction equal, valueToStringFunction valToString)
: equal_(equal), valueToString_(valToString) {}
virtual ~MockFunctionComparator(){}
virtual bool isEqual(void* object1, void* object2){ return equal_(object1, object2); }
virtual SimpleString valueToString(void* object) { return valueToString_(object); }
private:
isEqualFunction equal_;
valueToStringFunction valueToString_;
};
/*
* MockNamedValue is the generic value class used. It encapsulates basic types and can use them "as if one"
* Also it enables other types by putting object pointers. They can be compared with comparators.
*
* Basically this class ties together a Name, a Value, a Type, and a Comparator
*/
class MockNamedValue
{
public:
MockNamedValue(const SimpleString& name);
virtual ~MockNamedValue();
virtual void setValue(int value);
virtual void setValue(double value);
virtual void setValue(void* value);
virtual void setValue(const char* value);
virtual void setObjectPointer(const SimpleString& type, void* objectPtr);
virtual void setComparator(MockNamedValueComparator* comparator);
virtual void setName(const char* name);
virtual bool equals(const MockNamedValue& p) const;
virtual SimpleString toString() const;
virtual SimpleString getName() const;
virtual SimpleString getType() const;
virtual int getIntValue() const;
virtual double getDoubleValue() const;
virtual const char* getStringValue() const;
virtual void* getPointerValue() const;
virtual void* getObjectPointer() const;
private:
SimpleString name_;
SimpleString type_;
union {
int intValue_;
double doubleValue_;
const char* stringValue_;
void* pointerValue_;
void* objectPointerValue_;
} value_;
MockNamedValueComparator* comparator_;
};
class MockNamedValueListNode
{
public:
MockNamedValueListNode(MockNamedValue* newValue);
SimpleString getName() const;
SimpleString getType() const;
MockNamedValueListNode* next();
MockNamedValue* item();
void destroy();
void setNext(MockNamedValueListNode* node);
private:
MockNamedValue* data_;
MockNamedValueListNode* next_;
};
class MockNamedValueList
{
public:
MockNamedValueList();
MockNamedValueListNode* begin();
void add(MockNamedValue* newValue);
void clear();
MockNamedValue* getValueByName(const SimpleString& name);
private:
MockNamedValueListNode* head_;
};
/*
* MockParameterComparatorRepository is a class which stores comparators which can be used for comparing non-native types
*
*/
struct MockNamedValueComparatorRepositoryNode;
class MockNamedValueComparatorRepository
{
MockNamedValueComparatorRepositoryNode* head_;
public:
MockNamedValueComparatorRepository();
virtual ~MockNamedValueComparatorRepository();
virtual void installComparator(const SimpleString& name, MockNamedValueComparator& comparator);
virtual void installComparators(const MockNamedValueComparatorRepository& repository);
virtual MockNamedValueComparator* getComparatorForType(const SimpleString& name);
void clear();
};
#endif
| [
"forestgamer141@gmail.com"
] | forestgamer141@gmail.com |
dcf7bb78adf37bae0a9b41aeb0d7eca3d3da3da3 | 2878085060affd8375c9a2cdf7319b0a2280f8be | /src/ui/widgets/Label.h | d8a3000f6b12c60e8018b62e972407b296afabe6 | [] | no_license | silascodes/sgame | d2829b322b6971fa566d4884725e842dbbfaa98a | b563fc2d84208b4922cc7e7595bc470fdbed3eab | refs/heads/master | 2021-01-23T19:25:53.218607 | 2017-09-08T05:36:44 | 2017-09-08T05:36:44 | 102,821,247 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 274 | h | #ifndef SGAME_LABEL_H
#define SGAME_LABEL_H
#include "ui/Widget.h"
namespace ui {
namespace widgets {
class Label : public Widget {
public:
void RenderSelf(graphics::Renderer *renderer);
};
}
}
#endif //SGAME_LABEL_H
| [
"silas@amberweb.co.nz"
] | silas@amberweb.co.nz |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.