blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 941
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 142
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 121
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6121382505592535a09b239e90ed50ff680fc2e6 | 91fcb836ee5af301a2125624ddb96cf49b19494d | /queue/restoreQueue.cpp | 2e49fc23784e34f26b2deade801fe414d1b21cb1 | [] | no_license | hellozxs/C | fe11911222595ffcdc425218407711bbe59a3b10 | 1f3815966a8d5668f149ff9957672819a2d2b57d | refs/heads/master | 2020-04-06T07:03:14.596000 | 2016-09-18T10:25:27 | 2016-09-18T10:25:27 | 65,121,708 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,272 | cpp | //对一个队列执行以下操作后,发现输出为 1,2,3,4,……,n
// 操作:(如果队列不为空)
// 1:取队头元素,放入队尾,将队头pop
// 2;输出队头,将队头pop
// 输入n,求原始队列?
//
//输入:z -> 表示将要输入的数据的个数
//输入z个n的具体值
#include <iostream>
#include <vector>
using namespace std;
typedef struct MyData
{
int _data;
bool _flag;
}MyData;
int main()
{
int z;
cin >> z;
vector<int> arr(z);
for (int i = 0; i < z; i++)
{
cin >> arr[i];
}
int i = 0;
for (i = 0; i< z; i++)
{
if (arr[i] == 1)
cout << 1 << endl;
else
{
vector<MyData> a(arr[i]);
int j = 0;
int count = arr[i];
int tmp = 1;
for (; count--; j ++)
{
int flag = 1;
while (flag)
{
if (j == arr[i])
j = 0;
if (a[j]._flag == false)
flag--;
j++;
}
if (j == arr[i])
j = 0;
while (a[j]._flag == true)
{
j++;
if (j == arr[i])
j = 0;
}
a[j]._data =tmp++;
a[j]._flag = true;
}
int k = 0;
for (; k < arr[i]; k++)
cout << a[k]._data << " ";
cout << endl;
}
}
return 0;
}
| [
"[email protected]"
] | |
9b6b1ec168b70a357f4e47169b73b0f2e0538b9b | 6565182c28637e21087007f09d480a70b387382e | /code/901.股票价格跨度.cpp | 61b63105d48efcafe008368d50a272d85d3e8c15 | [] | no_license | liu-jianhao/leetcode | 08c070f0f140b2dd56cffbbaf25868364addfe53 | 7cbbe0585778517c88aa6ac1d2f2f8478cc931e5 | refs/heads/master | 2021-07-17T05:54:58.228000 | 2020-08-17T07:03:52 | 2020-08-17T07:03:52 | 188,854,718 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 792 | cpp | /*
* @lc app=leetcode.cn id=901 lang=cpp
*
* [901] 股票价格跨度
*/
class StockSpanner {
public:
StockSpanner() {
}
int next(int price) {
if(_i == 0 || price < _prices.back())
{
_dp.push_back(1);
}
else
{
int j = _i - 1;
while(j >= 0 && price >= _prices[j])
{
j -= _dp[j];
}
_dp.push_back(_i - j);
}
++_i;
_prices.push_back(price);
return _dp.back();
}
private:
vector<int> _dp;
vector<int> _prices;
int _i = 0;
};
/**
* Your StockSpanner object will be instantiated and called as such:
* StockSpanner* obj = new StockSpanner();
* int param_1 = obj->next(price);
*/
| [
"[email protected]"
] | |
b8319da5f12cfbbbd8ce6c9a50bab4c69b92531e | c4a320a9519cd63bad9be9bcfc022a4fcab5267b | /TETRIS_VS/TETRIS_VS/LobbyBoard.cpp | 4e7ef9e1f59c43158f02345d8f894a183007f43e | [] | no_license | shield1203/TETRIS_VS | 79dc3d8db0a1107352e46e69a96482a49490a290 | 3f67f0436674a10f9d37a98286a1f3531e6f7730 | refs/heads/master | 2020-12-22T00:11:37.323000 | 2020-03-05T15:28:32 | 2020-03-05T15:28:32 | 236,593,352 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 401 | cpp | #include "stdafx.h"
#include "LobbyBoard.h"
#include "InputSystem.h"
#include "PacketManager.h"
LobbyBoard::LobbyBoard()
{
m_packetManager = PacketManager::getInstance();
m_inputSystem = new InputSystem();
}
LobbyBoard::~LobbyBoard()
{
SafeDelete(m_inputSystem);
}
void LobbyBoard::Update()
{
m_inputSystem->CheckKeyboardPressed();
if (m_inputSystem->IsEnterPressed())
{
m_on = true;
}
} | [
"[email protected]"
] | |
36ffd69f21bf2277cef7fea364841c3a12967399 | d04b3793ed3611d5bdc8e3bc990bf9eb8562cece | /CheatSheet.cpp | e00970193f00ed69d57e398e36db43427aaf83b0 | [] | no_license | nebulou5/CppExamples | c7198cdc24ba1d681cc20738a3b21e2b17b98498 | 98044227b888a7f9faa8934ab76bb3cac443b75e | refs/heads/master | 2023-09-01T18:55:44.584000 | 2016-01-25T17:57:40 | 2016-01-25T17:57:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,222 | cpp | #include <iostream>
using namespace std;
void printI(int &i) {
cout << "Printing i: " << i << endl;
}
int main() {
// defining a basic 10 integer array
int x[10];
int xLen = sizeof(x) / sizeof(x[0]);
for (int i = 0; i < xLen; i++) {
cout << x[i] << endl;
}
// defining an array in place
float v[] = {1.1, 2.2, 3.3};
int vLen = sizeof(v) / sizeof(v[0]);
for (int i = 0; i < vLen; i++ ) {
cout << v[i] << endl;
}
// multidimensional array
float ab[3][3];
int abLen = sizeof(ab) / sizeof(ab[0]);
for (int i = 0; i < abLen; i++) {
printI(i);
for (int j = 0; j < abLen; j++) {
cout << "Element: " << i << ", " << j << ": " << ab[i][j] << endl;
}
}
// array allocated at runtime
int someUserDefinedSize = 3;
float* rta = new float[someUserDefinedSize]; // pointer dynamically allocates memory at runtime
delete[] rta; // but programmer must clean up the memory afterwards
// basic pointer usage
int i = 3;
int *j = &i; // store address of i @ "j"
int k = *j; // dereference address stored @ "j"
// initializing a nullptr
// valid in c++ 11 and beyond
int *nullPointer = nullptr;
int *nullPointerSynonymous{}; // also sets a nullptr
}
| [
"[email protected]"
] | |
0293e83add680ed3f8e92ecea17c897a91d1270b | 1ca3477d99bddb6611f2feb67c8ce0c4569d8a4b | /Memendo.cc | 7ac722a8f7b952968a9ec15d38a1c9bbc3afc637 | [] | no_license | TaoJun724/DesignPattern | 0da37a3a34fba54ba21cb809875b20d9eeba3443 | b0c62668cfad5b48b85b413e78ee9334812a74b2 | refs/heads/master | 2020-06-30T08:57:32.156000 | 2019-08-07T07:42:09 | 2019-08-07T07:42:09 | 200,785,533 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,461 | cc | #include <stdio.h>
#include<string>
class Memento {
public:
Memento(int n, std::string s) {
_s = s;
_money = n;
}
void setMoney(int n) {
_money = n;
}
int getMoney() {
return _money;
}
void setState(std::string s) {
_s = s;
}
std::string getState() {
return _s;
}
private:
int _money;
std::string _s;
};
class Worker {
public:
Worker(std::string name, int money, std::string s) {
_name = name;
_money = money;
_s = s;
}
void show() {
printf("%s现在有钱%d元,生活状态%s!\n", _name.c_str(), _money, _s.c_str());
}
void setState(int money, std::string s) {
_money = money;
_s = s;
}
Memento* createMemnto() {
return new Memento(_money,_s);
}
void restoreMemnto(Memento* m) {
_money = m->getMoney();
_s = m->getState();
}
private:
std::string _name;
int _money;
std::string _s;
};
class WorkerStorage {
public:
void setMemento(Memento* m) {
_memento = m;
}
Memento* getMement() {
return _memento;
}
private:
Memento* _memento;
};
int main() {
Worker* zhangsan = new Worker("张三", 10000, "富裕");
zhangsan->show();
//记住张三现在的状态
WorkerStorage* storage = new WorkerStorage;
storage->setMemento(zhangsan->createMemnto());
//张三赌博输了钱,只剩下10元
zhangsan->setState(10, "贫困");
zhangsan->show();
//经过努力张三又回到了之前的状态。
zhangsan->restoreMemnto(storage->getMement());
zhangsan->show();
return 0;
}
| [
"[email protected]"
] | |
f45da0032ec95894d113360f36e2c7e74a3b4bd2 | be522f6110d4ed6f330da41a653460e4fb1ed3a7 | /runtime/nf/httpparser/Buffer.cc | e4717f524b583c4cfdc3f533c545bdec74c3946c | [] | no_license | yxd886/nfa | 2a796b10e6e2085470e54dd4f9a4a3721c0d27a9 | 209fd992ab931f955afea11562673fec943dd8a6 | refs/heads/master | 2020-06-17T22:09:37.259000 | 2017-03-24T03:07:38 | 2017-03-24T03:07:38 | 74,966,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 981 | cc |
#include "Buffer.h"
void CBuffer_Reset(struct CBuffer& Cbuf){
if(!Cbuf.buf){
Cbuf.buf = (char*) malloc(BUFFER_SIZE);
memset(Cbuf.buf,0x00,Cbuf._free);
}
if(Cbuf.len > BUFFER_SIZE * 2 && Cbuf.buf){
//如果目前buf的大小是默认值的2倍,则对其裁剪内存,保持buf的大小为默认值,减小内存耗费
char* newbuf = (char*) realloc(Cbuf.buf,BUFFER_SIZE);
if(newbuf != Cbuf.buf)
Cbuf.buf = newbuf;
}
Cbuf.len = 0;
Cbuf._free = BUFFER_SIZE;
}
bool Append(struct CBuffer& Cbuf,char* p, size_t size){
if(!p || !size)
return true;
if(size < Cbuf._free){
memcpy(Cbuf.buf + Cbuf.len, p , size);
Cbuf.len += size;
Cbuf._free -= size;
}else{
return false;
}
return true;
}
char* GetBuf(struct CBuffer Cbuf,uint32_t& size){
size = Cbuf.len;
return Cbuf.buf;
}
uint32_t GetBufLen(struct CBuffer Cbuf){
return Cbuf.len;
}
void Buf_init(struct CBuffer& Cbuf){
Cbuf.len=0;
Cbuf._free=0;
Cbuf.buf=0;
CBuffer_Reset(Cbuf);
}
| [
"[email protected]"
] | |
2700f3690854eaf5a2187d2d57c0ce1df9fa0f9f | 29288023bde7829066f810540963a7b35573fa31 | /BstUsingSet.cpp | 4f984176f775caa7499cc3e20cab43944733c536 | [] | no_license | Sohail-khan786/Competitve-Programming | 6e56bdd8fb7b3660edec50c72f680b6ed2c41a0f | e90dcf557778a4c0310e03539e4f3c1c939bb3a1 | refs/heads/master | 2022-10-08T06:55:46.637000 | 2020-06-07T18:39:20 | 2020-06-07T18:39:20 | 254,899,456 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 718 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int flag=1;
set<int> s;
set<int>::iterator it;
int x;
while(flag!=3)
{
cout<<"1.Insert 2.Delete 3.Exit"<<endl;
cin>>flag;
cout<<"value\t";
cin>>x;
if(flag==1)
{
s.insert(x);
}
else if(flag==2)
{
s.erase(x);
}
cout<<"Extracting max n min from a set"<<cout<<endl;
//s.end has iterator to last element of the set which is the size of the set and hence decrement it by one to get the maximum element present in the set;
it = s.end();
it--;
cout<<"maxx = "<<*(it)<<" minn ="<<*s.begin();
cout<<endl;
}
return 0;
}
| [
"[email protected]"
] | |
c1be7ed8331d413fbb32c4f4da225eabb0c94905 | 2d4346d0da0a4145f6bcc91a8cb2c0ab4d669d7e | /chat-up-server/src/Authentication/AuthenticationService.h | b172c8a7281e736007294715851af51947b6b669 | [] | no_license | xgallom/chat-up | 5570d069a495acf6398bdf1f62b1fb1d91289376 | 7cb664ce745cf041fb508b04165d2179563aa010 | refs/heads/master | 2020-04-18T05:40:58.487000 | 2019-01-29T22:36:04 | 2019-01-29T22:36:04 | 167,287,878 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 608 | h | //
// Created by xgallom on 1/27/19.
//
#ifndef CHAT_UP_AUTHENTICATIONSERVICE_H
#define CHAT_UP_AUTHENTICATIONSERVICE_H
#include <Messaging/Message.h>
#include <Messaging/MessageSender.h>
#include <Outcome.h>
#include <Authentication/User.h>
class AuthenticationStorage;
class AuthenticationService {
AuthenticationStorage &m_storage;
User m_user = User();
public:
AuthenticationService() noexcept;
Outcome::Enum run(MessageSender &sender, const Message &message);
bool registerUser(const User &user);
User user() const noexcept;
};
#endif //CHAT_UP_AUTHENTICATIONSERVICE_H
| [
"[email protected]"
] | |
e58b6df0e5b4c66f0d095c33c45ddcbea6ffceae | 9929f9f832b21f641f41fc91cbf604643f9770dd | /src/txt/mainRegressionP.cpp | 16ad10a2e0e2cf8996b46a19dd9d38b275156452 | [] | no_license | JeanSar/rogue | 1cd4d8d18fe8ae6ba7d32f3af556259f5a65b2fc | a4c8945a8ae09984a4b417a3bac5ffd029e46fa7 | refs/heads/master | 2023-03-01T01:24:12.351000 | 2021-01-28T19:53:17 | 2021-01-28T19:53:17 | 331,929,934 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,062 | cpp | #include "Personnages.h"
using namespace std;
int main(){
srand(time(NULL));
int ok = 0;
Hero* h = new Hero("Player");
Ennemi* e = new Ennemi(4);
cout << "Hero : " << h->getName() << endl
<< "x : " << h->getX() << endl
<< "y : " << h->getY() << endl
<< "pv : " << h->getPv() << endl
<< "lv : " << h->getLv() << endl
<< "atk : " << h->getAtk() << endl
<< "def : " << h->getDef() << "\n\n"
<< "Ennemi :" << endl
<< "x : " << e->getX() << endl
<< "y : " << e->getY() << endl
<< "pv : " << e->getPv() << endl
<< "lv : " << e->getLv() << endl
<< "atk : " << e->getAtk() << endl
<< "def : " << e->getDef() << "\n\n";
assert(ok == h->lvUp());
cout << "lv : " << h->getLv() << endl
<< "atk : " << h->getAtk() << endl
<< "def : " << h->getDef() << endl;
assert(ok == h->combat(e));
cout << "Ennemie - pv : " << e->getPv() << endl;
assert(ok == h->setName("Terrine"));
assert(ok == e->combat(h));
cout << h->getName() << " - pv : " << h->getPv();
delete e;
delete h;
return 0;
}
| [
"="
] | = |
ab5bc031413c9ef1306cacfd08a9878b7b902ed5 | 35e79b51f691b7737db254ba1d907b2fd2d731ef | /AtCoder/ABC/007/D.cpp | 1f7d6ef9dd955d37b91e67aebfabda6b728594c7 | [] | no_license | rodea0952/competitive-programming | 00260062d00f56a011f146cbdb9ef8356e6b69e4 | 9d7089307c8f61ea1274a9f51d6ea00d67b80482 | refs/heads/master | 2022-07-01T02:25:46.897000 | 2022-06-04T08:44:42 | 2022-06-04T08:44:42 | 202,485,546 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,189 | cpp | #include <bits/stdc++.h>
#define chmin(a, b) ((a)=min((a), (b)))
#define chmax(a, b) ((a)=max((a), (b)))
#define fs first
#define sc second
#define eb emplace_back
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef tuple<int, int, int> T;
const ll MOD=1e9+7;
const ll INF=1e18;
int dx[]={1, -1, 0, 0};
int dy[]={0, 0, 1, -1};
template <typename T> inline string toString(const T &a){ostringstream oss; oss<<a; return oss.str();};
ll solve(string &s){
int n=s.size();
ll dp[20][2][2];
// dp[決めた桁数][未満フラグ][4または9を含むか] := 求める総数
memset(dp, 0, sizeof(dp));
dp[0][0][0]=1;
for(int i=0; i<n; i++){ // 桁
int D=s[i]-'0';
for(int j=0; j<2; j++){ // 未満フラグ
for(int k=0; k<2; k++){ // k=1 のとき4または9を含む
for(int d=0; d<=(j?9:D); d++){
dp[i+1][j || (d<D)][k || d==4 || d==9]+=dp[i][j][k];
}
}
}
}
return dp[n][0][1]+dp[n][1][1];
}
int main(){
ll a, b; cin>>a>>b;
string A=toString(a-1), B=toString(b);
cout << solve(B) - solve(A) << endl;
}
| [
"[email protected]"
] | |
819eb928fa03acd974c3e18443532022f13c2f05 | 711b11d08abdb3a7df2574b0b4c86af21c5c6750 | /dest.h | e06af74e0264187915ab70b86b0e67aa85d2a79f | [] | no_license | nflath/MSP430Emulator | 4aee9e093113cc41d9041a1728eedd742fd786b2 | a97a1b97b895b3533597bcdb69bec8b75db395df | refs/heads/master | 2021-01-13T01:54:55.258000 | 2015-08-25T05:10:04 | 2015-08-25T05:10:04 | 41,343,926 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,382 | h | #include <assert.h>
#ifndef DEST_H
#define DEST_H
#include "error.h"
// Classes representing 'Destinations' types in MSP430 - See the section
// 'MSP430 addressing modes' in https://en.wikipedia.org/wiki/TI_MSP430#MSP430_CPU
class State;
class Dest {
// Virtual base clase.
public:
virtual void set(short value) { notimplemented(); }
// Sets the value of this destination
virtual void setByte(unsigned char value) { notimplemented(); }
// Sets the value of this destination (byte addressing mode)
virtual short value() { notimplemented(); return 0;}
// Returns the value of this destination
virtual unsigned char valueByte() { notimplemented(); return 0;}
// Returns the value of this destination(byte addressing mode)
virtual std::string toString() = 0;
// Returns a string representation of this destination
virtual bool usedExtensionWord() { return false; }
// Whether an extension word was used to represent this destination
virtual unsigned char size() { return usedExtensionWord() ? 2 : 0; }
// How many extra bytes this destination took up in the assembly
};
class RegisterDest : public Dest {
// Destination representing a register (r14)
public:
virtual std::string toString();
virtual void set(short value);
virtual void setByte(unsigned char value);
virtual short value();
virtual unsigned char valueByte();
RegisterDest(unsigned short reg_) : reg(reg_) {}
unsigned short reg;
};
class RegisterOffsetDest : public RegisterDest {
// Destination representing the memory address at a register plus an offset (0x40(r14))
public:
virtual std::string toString();
virtual bool usedExtensionWord() { return true; }
virtual void set(short value);
virtual void setByte(unsigned char value);
virtual short value();
virtual unsigned char valueByte();
RegisterOffsetDest(unsigned short reg_, short offset_) :
RegisterDest(reg_),
offset(offset_) {
}
short offset;
};
class AbsoluteDest : public Dest {
// Destination that is just a memory address (&0x4400)
public:
virtual std::string toString();
virtual bool usedExtensionWord() { return true; }
virtual void set(short value);
virtual void setByte(unsigned char value);
virtual unsigned char valueByte();
AbsoluteDest(unsigned short address_) :
address(address_) {
}
unsigned short address;
};
extern State* s;
#endif
| [
"[email protected]"
] | |
49d04327f2bb77b7681762dfab736d8274441b2c | d1dc3c6ec24ce3291a257b16bd1f2aa6bd791d2e | /Project1/src/Main66.cpp | e774f1c5c93157824bc10e4e8b6864ae00497def | [] | no_license | wrapdavid/Cherno_practice | 8248bbcedee31a48c536dbd191eca5265178e762 | e95ff1857fd72fc195a0e4c57c15a5965287ea69 | refs/heads/master | 2020-09-08T10:32:04.088000 | 2020-02-11T02:29:49 | 2020-02-11T02:29:49 | 221,109,286 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 242 | cpp | #include<iostream>
template<typename T, char N>
class Array {
private:
T m_Array[N];
public:
char GetArray() const { return N; }
};
int main() {
Array<int, 61> array;
std::cout << array.GetArray() << std::endl;
std::cin.get();
} | [
"[email protected]"
] | |
f974d4af50705dd6f63c51d6d7a1ee1c85bf7cd3 | 414c6adb394c3c7ef4b80ab9b62cfc238ff726e2 | /tutorial/spinny/main.cc | 39f9f8736922a4b8a41c9e0c1c9d1bf851f0a4b6 | [] | no_license | akeley98/vkme | 68ca6db6c246fe8b4a25a3fb0982ff2552d8ef9b | 1b8e7df2a8290a0cc7bd97bf82c88a6eeff40be1 | refs/heads/master | 2022-12-23T19:53:47.583000 | 2020-09-29T05:34:32 | 2020-09-29T05:34:32 | 291,925,536 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,670 | cc | #include "window.hh"
#include "render.hh"
#include "util.hh"
using namespace myricube;
// Absolute path of the executable, minus the -bin or .exe, plus -data/
// This is where shaders and stuff are stored.
std::string data_directory;
std::string expand_filename(const std::string& in)
{
if (data_directory.size() == 0) {
throw std::logic_error("Cannot call expand_filename before main");
}
return in[0] == '/' ? in : data_directory + in;
}
bool ends_with_bin_or_exe(const std::string& in)
{
auto sz = in.size();
if (sz < 4) return false;
const char* suffix = &in[sz - 4];
return strcmp(suffix, "-bin") == 0 or strcmp(suffix, ".exe") == 0;
}
bool paused = false;
int target_fragments = 0;
void add_key_targets(Window& window, Camera& camera)
{
static float speed = 8.0f;
static float sprint_mod = 1.0f;
struct Position
{
glm::dvec3 eye = glm::dvec3(0);
float theta = 1.5707f;
float phi = 1.5707f;
};
static Position old_positions_ring_buffer[256];
static Position future_positions_ring_buffer[256];
static uint8_t old_idx = 0;
static uint8_t future_idx = 0;
static auto get_camera_position = [&camera] () -> Position
{
Position p;
p.eye = camera.get_eye();
p.theta = camera.get_theta();
p.phi = camera.get_phi();
return p;
};
static auto push_camera_position = [&]
{
old_positions_ring_buffer[--old_idx] = get_camera_position();
};
static auto push_camera_position_callback = [&] (KeyArg arg)
{
if (arg.repeat) return false;
push_camera_position();
return true;
};
KeyTarget pop_old_camera, pop_future_camera;
pop_old_camera.down = [&] (KeyArg) -> bool
{
future_positions_ring_buffer[--future_idx] =
get_camera_position();
Position p = old_positions_ring_buffer[old_idx++];
camera.set_eye(p.eye);
camera.set_theta(p.theta);
camera.set_phi(p.phi);
return true;
};
pop_future_camera.down = [&] (KeyArg) -> bool
{
old_positions_ring_buffer[--old_idx] =
get_camera_position();
Position p = future_positions_ring_buffer[future_idx++];
camera.set_eye(p.eye);
camera.set_theta(p.theta);
camera.set_phi(p.phi);
return true;
};
window.add_key_target("pop_old_camera", pop_old_camera);
window.add_key_target("pop_future_camera", pop_future_camera);
KeyTarget forward, backward, leftward, rightward, upward, downward;
forward.down = push_camera_position_callback;
forward.per_frame = [&] (KeyArg arg) -> bool
{
camera.frenet_move(0, 0, +arg.dt * speed * sprint_mod);
return true;
};
backward.down = push_camera_position_callback;
backward.per_frame = [&] (KeyArg arg) -> bool
{
camera.frenet_move(0, 0, -arg.dt * speed * sprint_mod);
return true;
};
leftward.down = push_camera_position_callback;
leftward.per_frame = [&] (KeyArg arg) -> bool
{
camera.frenet_move(-arg.dt * speed * sprint_mod, 0, 0);
return true;
};
rightward.down = push_camera_position_callback;
rightward.per_frame = [&] (KeyArg arg) -> bool
{
camera.frenet_move(+arg.dt * speed * sprint_mod, 0, 0);
return true;
};
upward.down = push_camera_position_callback;
upward.per_frame = [&] (KeyArg arg) -> bool
{
camera.frenet_move(0, +arg.dt * speed * sprint_mod, 0);
return true;
};
downward.down = push_camera_position_callback;
downward.per_frame = [&] (KeyArg arg) -> bool
{
camera.frenet_move(0, -arg.dt * speed * sprint_mod, 0);
return true;
};
window.add_key_target("forward", forward);
window.add_key_target("backward", backward);
window.add_key_target("leftward", leftward);
window.add_key_target("rightward", rightward);
window.add_key_target("upward", upward);
window.add_key_target("downward", downward);
KeyTarget sprint, speed_up, slow_down;
sprint.down = [&] (KeyArg) -> bool
{
sprint_mod = 7.0f;
return true;
};
sprint.up = [&] (KeyArg) -> bool
{
sprint_mod = 1.0f;
return true;
};
speed_up.down = [&] (KeyArg arg) -> bool
{
if (!arg.repeat) speed *= 2.0f;
return !arg.repeat;
};
slow_down.down = [&] (KeyArg arg) -> bool
{
if (!arg.repeat) speed *= 0.5f;
return !arg.repeat;
};
window.add_key_target("sprint", sprint);
window.add_key_target("speed_up", speed_up);
window.add_key_target("slow_down", slow_down);
KeyTarget vertical_scroll, horizontal_scroll, look_around;
look_around.down = push_camera_position_callback;
look_around.per_frame = [&] (KeyArg arg) -> bool
{
camera.inc_theta(arg.mouse_rel_x * arg.dt * 0.01f);
camera.inc_phi(arg.mouse_rel_y * arg.dt * 0.01f);
return true;
};
vertical_scroll.down = [&] (KeyArg arg) -> bool
{
camera.inc_phi(arg.amount * -0.05f);
return true;
};
horizontal_scroll.down = [&] (KeyArg arg) -> bool
{
camera.inc_theta(arg.amount * -0.05f);
return true;
};
window.add_key_target("look_around", look_around);
window.add_key_target("vertical_scroll", vertical_scroll);
window.add_key_target("horizontal_scroll", horizontal_scroll);
}
// Given the full path of a key binds file, parse it for key bindings
// and add it to the window's database of key bindings (physical
// key/mouse button to KeyTarget name associations).
//
// Syntax: the file should consist of lines of pairs of key names and
// KeyTarget names. Blank (all whitespace) lines are allowed as well
// as comments, which go from a # character to the end of the line.
//
// Returns true iff successful (check errno on false).
bool add_key_binds_from_file(Window& window, std::string filename) noexcept
{
FILE* file = fopen(filename.c_str(), "r");
if (file == nullptr) {
fprintf(stderr, "Could not open %s\n", filename.c_str());
return false;
}
int line_number = 0;
auto skip_whitespace = [file]
{
int c;
while (1) {
c = fgetc(file);
if (c == EOF) return;
if (c == '\n' or !isspace(c)) {
ungetc(c, file);
return;
}
}
};
errno = 0;
bool eof = false;
while (!eof) {
std::string key_name;
std::string target_name;
++line_number;
int c;
skip_whitespace();
// Parse key name (not case sensitive -- converted to lower case)
while (1) {
c = fgetc(file);
if (c == EOF) {
if (errno != 0 and errno != EAGAIN) goto bad_eof;
eof = true;
goto end_line;
}
if (c == '\n') goto end_line;
if (isspace(c)) break;
if (c == '#') goto comment;
key_name.push_back(c);
}
skip_whitespace();
// Parse target name (case sensitive)
while (1) {
c = fgetc(file);
if (c == EOF) {
if (errno != 0 and errno != EAGAIN) goto bad_eof;
eof = true;
goto end_line;
}
if (c == '\n') goto end_line;
if (isspace(c)) break;
if (c == '#') goto comment;
target_name.push_back(c);
}
skip_whitespace();
// Check for unexpected cruft at end of line.
c = fgetc(file);
if (c == EOF) {
if (errno != 0 and errno != EAGAIN) goto bad_eof;
eof = true;
goto end_line;
}
else if (c == '#') {
goto comment;
}
else if (c == '\n') {
goto end_line;
}
else {
fprintf(stderr, "%s:%i unexpected third token"
" starting with '%c'\n",
filename.c_str(), line_number, c);
errno = EINVAL;
goto bad_eof;
}
// Skip over comment characters from # to \n
comment:
while (1) {
c = fgetc(file);
if (c == EOF) {
if (errno != 0 and errno != EAGAIN) goto bad_eof;
eof = true;
goto end_line;
}
if (c == '\n') {
break;
}
}
end_line:
// skip blank lines silently.
if (key_name.size() == 0) continue;
// Complain if only one token is provided on a line.
if (target_name.size() == 0) {
fprintf(stderr, "%s:%i key name without target name.\n",
filename.c_str(), line_number);
errno = EINVAL;
goto bad_eof;
}
auto keycode = keycode_from_name(key_name);
if (keycode == 0) {
fprintf(stderr, "%s:%i unknown key name %s.\n",
filename.c_str(), line_number, key_name.c_str());
errno = EINVAL;
goto bad_eof;
}
fprintf(stderr, "Binding %s (%i) to %s\n",
key_name.c_str(), keycode, target_name.c_str());
window.bind_keycode(keycode, target_name);
}
if (fclose(file) != 0) {
fprintf(stderr, "Error closing %s\n", filename.c_str());
return false;
}
return true;
bad_eof:
fprintf(stderr, "Warning: unexpected end of parsing.\n");
int eof_errno = errno;
fclose(file);
errno = eof_errno;
return true; // I'm getting bogus EOF fails all the time so fake success :/
}
void bind_keys(Window& window)
{
auto default_file = expand_filename("default-keybinds.txt");
auto user_file = expand_filename("keybinds.txt");
bool default_okay = add_key_binds_from_file(window, default_file);
if (!default_okay) {
fprintf(stderr, "Failed to parse %s\n", default_file.c_str());
fprintf(stderr, "%s (%i)\n", strerror(errno), errno);
exit(2);
}
bool user_okay = add_key_binds_from_file(window, user_file);
if (!user_okay) {
if (errno == ENOENT) {
fprintf(stderr, "Custom keybinds file %s not found.\n",
user_file.c_str());
}
else {
fprintf(stderr, "Failed to parse %s\n", user_file.c_str());
fprintf(stderr, "%s (%i)\n", strerror(errno), errno);
exit(2);
}
}
}
int main(int argc, char** argv)
{
// Data directory (where shaders are stored) is the path of this
// executable, with the -bin or .exe file extension replaced with
// -data. Construct that directory name here.
data_directory = argv[0];
if (!ends_with_bin_or_exe(data_directory)) {
fprintf(stderr, "%s should end with '-bin' or '.exe'\n",
data_directory.c_str());
return 1;
}
for (int i = 0; i < 4; ++i) data_directory.pop_back();
data_directory += "-data/";
// Instantiate the camera.
Camera camera;
// Create a window; callback ensures these window dimensions stay accurate.
int screen_x = 0, screen_y = 0;
auto on_window_resize = [&camera, &screen_x, &screen_y] (int x, int y)
{
camera.set_window_size(x, y);
screen_x = x;
screen_y = y;
};
Window window(on_window_resize);
Renderer* renderer = new_renderer(window);
add_key_targets(window, camera);
bind_keys(window);
while (window.frame_update()) draw_frame(renderer, camera);
delete_renderer(renderer);
}
| [
"[email protected]"
] | |
cbee84c2e52dc1341528f8254aaf41ac321f936c | 2869112fdc836e565f9fe68e290affc1e223c1d8 | /pythran/pythonic/include/__builtin__/set/isdisjoint.hpp | 10ac38270e03ff35d15b79143e6164321a7b5afb | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | coyotte508/pythran | ab26e9ddb9a9e00e77b457df316aa33dc8435914 | a5da78f2aebae712a2c6260ab691dab7d09e307c | refs/heads/master | 2021-01-15T10:07:09.597000 | 2015-05-01T07:00:42 | 2015-05-01T07:00:42 | 35,020,532 | 0 | 0 | null | 2015-05-04T07:27:29 | 2015-05-04T07:27:29 | null | UTF-8 | C++ | false | false | 621 | hpp | #ifndef PYTHONIC_INCLUDE_BUILTIN_SET_ISDISJOINT_HPP
#define PYTHONIC_INCLUDE_BUILTIN_SET_ISDISJOINT_HPP
#include "pythonic/utils/proxy.hpp"
#include "pythonic/types/set.hpp"
namespace pythonic {
namespace __builtin__ {
namespace set {
template<class T, class U>
bool
isdisjoint(types::set<T> const& calling_set, U const& arg_set);
template<class U>
bool
isdisjoint(types::empty_set const& calling_set, U const& arg_set);
PROXY_DECL(pythonic::__builtin__::set, isdisjoint);
}
}
}
#endif
| [
"[email protected]"
] | |
334f0712fc8566ea028524f0cd56702b83f8dbd4 | 9b273539e02cca8d408e8cf793007ee84e6637d5 | /ext/bliss/src/iterators/edge_iterator.hpp | 2217a705bef1dc4b94ba3493a6facab66fe6ad3e | [
"Apache-2.0"
] | permissive | tuan1225/parconnect_sc16 | 23b82c956eed4dabe5deec8bd48cc8ead91af615 | bcd6f99101685d746cf30e22fa3c3f63ddd950c9 | refs/heads/master | 2020-12-24T12:01:13.846000 | 2016-11-07T16:51:29 | 2016-11-07T16:51:29 | 73,055,274 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,760 | hpp | /*
* edge_iterator.hpp
*
* Created on: Aug 4, 2015
* Author: yongchao
*/
#ifndef EDGE_ITERATOR_HPP_
#define EDGE_ITERATOR_HPP_
#include <iterator>
#include "common/alphabets.hpp"
namespace bliss
{
namespace iterator
{
// careful with the use of enable_if. evaluation should occur at function call time,
// i.e. class template params will be evaluated with no substitution.
// instead, a function should declare a template parameter proxy for the class template parameter.
// then enable_if evaluates using the proxy.
// e.g. template< class c = C; typename std::enable_if<std::is_same<c, std::string>::value, int>::type x = 0>
/**
* @class edge_iterator
* @brief given a k-mer position, retrieve its left and right bases, including the dummy bases at both ends
* @details specializations of this class uses a byte to manage the edge info.
* upper 4 bits holds the left base (encoded), lower 4 bits holds the right base (encoded)
*
* no reverse complement or reordering is applied.
*
* edge iterator should be valid for std::distance(_data_end - _data_start - k + 1) iterations.
*/
template<typename IT, typename ALPHA = bliss::common::DNA16>
class edge_iterator : public ::std::iterator<::std::forward_iterator_tag, uint8_t>
{
protected:
// curr position
IT _curr;
//previous position
IT _left;
//a position of distance k from the _curr on the right
IT _right;
/*data*/
const IT _data_start;
const IT _data_end;
public:
typedef ALPHA Alphabet;
typedef edge_iterator<IT, ALPHA> self_type; /*define edge iterator type*/
typedef uint8_t edge_type; //type to represent an edge
// accessors
IT& getBase()
{
return _curr;
}
//constructor
edge_iterator(IT data_start, IT data_end, const uint32_t k)
: _curr (data_start), _left(data_end), _right(data_start), _data_start(data_start), _data_end(data_end)
{
/*compute the offset*/
::std::advance(_curr, k - 1);
_right = _curr;
::std::advance(_right, 1);
}
edge_iterator(IT data_end)
: _curr(data_end), _left(data_end), _right(data_end), _data_start(data_end), _data_end(data_end)
{
}
/// copy constructor
edge_iterator(const self_type& Other)
: _curr (Other._curr), _left(Other._left), _right(Other._right),
_data_start(Other._data_start), _data_end(Other._data_end)
{
/*do nothing*/
}
/// copy assignment iterator
self_type& operator=(const self_type& Other)
{
_curr = Other._curr;
_left = Other._left;
_right = Other._right;
_data_start = Other._data_start;
_data_end = Other._data_end;
return *this;
}
/// increment to next matching element in base iterator
self_type& operator++()
{ // if _curr at end, subsequent calls should not move _curr.
// on call, if not at end, need to move first then evaluate.
if (_curr == _data_end){ // if at end, don't move it.
return *this;
}
/*save the previous position*/
if (_left == _data_end) _left = _data_start;
else ++_left;
/*move forward by 1*/
++_curr;
/*ensure that _right does not exceed _end*/
if(_right != _data_end){
++_right;
}
return *this;
}
/**
* post increment. make a copy then increment that.
*/
self_type operator++(int)
{
self_type output(*this);
this->operator++();
return output;
}
/// compare 2 filter iterators
inline bool operator==(const self_type& rhs)
{
return _curr == rhs._curr;
}
/// compare 2 filter iterators
inline bool operator!=(const self_type& rhs)
{
return _curr != rhs._curr;
}
/// dereference operator. _curr is guaranteed to be valid
inline edge_type operator*()
{
/*using four bits to represent an edge*/
if(_left != _data_end && _right != _data_end){
/*internal k-mer node*/
return (ALPHA::FROM_ASCII[*_left] << 4) | ALPHA::FROM_ASCII[*_right];
}else if(_left == _data_end && _right != _data_end){ /*the left-most k-mer node*/
return ALPHA::FROM_ASCII[*_right];
}else if(_left != _data_end && _right == _data_end){ /*the rigth-most k-mer node*/
return ALPHA::FROM_ASCII[*_left] << 4;
}
/*if(_left == _end && _right == _end)*/
return 0;
}
};
template<typename IT>
using DNA16_edge_iterator = edge_iterator<IT, bliss::common::DNA16>;
template<typename IT>
using DNA_IUPAC_edge_iterator = edge_iterator<IT, bliss::common::DNA_IUPAC>;
// not suitable for edge iterator since there is no value for unknown char.
template<typename IT>
using DNA_edge_iterator = edge_iterator<IT, bliss::common::DNA>;
template<typename IT>
using DNA5_edge_iterator = edge_iterator<IT, bliss::common::DNA5>;
// not suitable for edge iterator since there is no value for unknown char.
template<typename IT>
using RNA_edge_iterator = edge_iterator<IT, bliss::common::RNA>;
template<typename IT>
using RNA5_edge_iterator = edge_iterator<IT, bliss::common::RNA5>;
/*EdgeType = short unsigned int*/
template<typename IT>
class edge_iterator<IT, bliss::common::ASCII>: public ::std::iterator<::std::forward_iterator_tag, uint16_t>
{
protected:
// curr position
IT _curr;
//previous position
IT _left;
//a position of distance k from the _curr on the right
IT _right;
/*data*/
const IT _data_start;
const IT _data_end;
public:
typedef bliss::common::ASCII Alphabet;
typedef edge_iterator<IT, bliss::common::ASCII> self_type; /*define edge iterator type*/
typedef uint16_t edge_type; //type to represent an edge
// accessors
IT& getBase()
{
return _curr;
}
//constructor
edge_iterator(IT data_start, IT data_end, const uint32_t k)
: _curr (data_start), _left(data_end), _right(data_start), _data_start(data_start), _data_end(data_end)
{
/*compute the offset*/
::std::advance(_curr, k-1);
_right = _curr;
::std::advance(_right, 1);
}
edge_iterator(IT data_end)
: _curr(data_end), _left(data_end), _right(data_end), _data_start(data_end), _data_end(data_end)
{
}
/// copy constructor
edge_iterator(const self_type& Other)
: _curr (Other._curr), _left(Other._left), _right(Other._right),
_data_start(Other._data_start), _data_end(Other._data_end)
{
/*do nothing*/
}
/// copy assignment iterator
self_type& operator=(const self_type& Other)
{
_curr = Other._curr;
_left = Other._left;
_right = Other._right;
_data_start = Other._data_start;
_data_end = Other._data_end;
return *this;
}
/// increment to next matching element in base iterator
self_type& operator++()
{ // if _curr at end, subsequent calls should not move _curr.
// on call, if not at end, need to move first then evaluate.
if (_curr == _data_end){ // if at end, don'IT move it.
return *this;
}
/*save the previous position*/
if (_left == _data_end) _left = _data_start;
else ++_left;
/*move forward by 1*/
++_curr;
/*ensure that _right does not exceed _end*/
if(_right != _data_end){
++_right;
}
return *this;
}
/**
* post increment. make a copy then increment that.
*/
self_type operator++(int)
{
self_type output(*this);
this->operator++();
return output;
}
/// compare 2 filter iterators
inline bool operator==(const self_type& rhs)
{
return _curr == rhs._curr;
}
/// compare 2 filter iterators
inline bool operator!=(const self_type& rhs)
{
return _curr != rhs._curr;
}
/// dereference operator. _curr is guaranteed to be valid
inline edge_type operator*()
{
/*using 8 bits to represent an edge*/
if(_left != _data_end && _right != _data_end){
/*internal k-mer node*/
return (*_left << 8) | *_right;
}else if(_left == _data_end && _right != _data_end){ /*the left-most k-mer node*/
return *_right & 0x0ff;
}else if(_left != _data_end && _right == _data_end){ /*the rigth-most k-mer node*/
return *_left << 8;
}
/*if(_left == _end && _right == _end)*/
return 0;
}
};
template<typename IT>
using raw_edge_iterator = edge_iterator<IT, bliss::common::ASCII>;
} // iterator
} // bliss
#endif /* EDGE_ITERATOR_HPP_ */
| [
"[email protected]"
] | |
bba7327fa47b292b7a2a12379dbea888640a0e70 | 58790459d953a3e4b6722ed3ee939f82d9de8c3e | /my/PDF插件/sdkDC_v1_win/Adobe/Acrobat DC SDK/Version 1/PluginSupport/PIBrokerSDK/simple-ipc-lib/src/pipe_win.h | 4625bef0dc76752fdcc7b3a4966d087839cbd12f | [] | no_license | tisn05/VS | bb84deb993eb18d43d8edaf81afb753afa3d3188 | da56d392a518ba21edcb1a367b4b4378d65506f0 | refs/heads/master | 2020-09-25T05:49:31.713000 | 2016-08-22T01:22:16 | 2016-08-22T01:22:16 | 66,229,337 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,659 | h | // Copyright (c) 2010 Google Inc.
//
// 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 SIMPLE_IPC_PIPE_WIN_H_
#define SIMPLE_IPC_PIPE_WIN_H_
#include "os_includes.h"
#include "ipc_constants.h"
class PipePair {
public:
PipePair(bool inherit_fd2 = false);
HANDLE fd1() const { return srv_; }
HANDLE fd2() const { return cln_; }
static HANDLE OpenPipeServer(const wchar_t* name, bool low_integrity = false);
static HANDLE OpenPipeClient(const wchar_t* name, bool inherit, bool impersonate);
private:
HANDLE srv_;
HANDLE cln_;
};
class PipeWin {
public:
PipeWin();
~PipeWin();
bool OpenClient(HANDLE pipe);
bool OpenServer(HANDLE pipe, bool connect = false);
bool Write(const void* buf, size_t sz);
bool Read(void* buf, size_t* sz);
bool IsConnected() const { return INVALID_HANDLE_VALUE != pipe_; }
private:
HANDLE pipe_;
};
class PipeTransport : public PipeWin {
public:
static const size_t kBufferSz = 4096;
size_t Send(const void* buf, size_t sz) {
return Write(buf, sz) ? ipc::RcOK : ipc::RcErrTransportWrite;
}
char* Receive(size_t* size);
private:
IPCCharVector buf_;
};
#endif // SIMPLE_IPC_PIPE_WIN_H_
| [
"[email protected]"
] | |
36a545137c7c8972f084997716e578ad86d3ac15 | afcce85e08d8fc5141a840fe77bf7bf93f49df54 | /tests/2015-09-10/fft_shift/main.cpp | 5fd27aab9e2480a56af1d2bf0dfe2ab2e4eeaa98 | [] | no_license | icopavan/Automatic-Modulation-Classification-ELEN4012 | ff8f58a467129b371a9d2b042169fc99620b2959 | d72e3b4d36ad88b2872a8b33606c120f18b974e6 | refs/heads/master | 2021-01-12T21:07:15.807000 | 2015-10-09T21:29:56 | 2015-10-09T21:29:56 | 44,043,227 | 2 | 1 | null | 2015-10-11T07:30:41 | 2015-10-11T07:30:40 | null | UTF-8 | C++ | false | false | 910 | cpp | #include "mainwindow.h"
#include <QApplication>
#include <fftw3.h>
#include <cmath>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
double PI = 4 * atan(1);
int N = 512; // number of samples
double fs = 10e3; // sampling frequency
double fc = 1000; // signal frequency
double t[N];
fftw_complex * x = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
double f[N];
// calculation
for (int n = 0; n < N; ++n)
{
t[n] = n/fs;
x[n][0] = cos(2*PI*fc*t[n]);
x[n][1] = 0;
f[n] = (n - N/2) * fs / (N-1);
}
fftw_complex *out;
fftw_plan plan_forward;
out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
plan_forward = fftw_plan_dft_1d(N, x, out, FFTW_FORWARD, FFTW_ESTIMATE);
fftw_execute(plan_forward);
w.plot(f, out, N);
return a.exec();
}
| [
"[email protected]"
] | |
33fa115e3d756b655d4b8fd3fc840eb94198c8be | 012784e8de35581e1929306503439bb355be4c4f | /problems/37. 解数独/3.cc | 84bf778bd32645766fc6275be6ca3a9a288a96dc | [] | no_license | silenke/my-leetcode | 7502057c9394e41ddeb2e7fd6c1b8261661639e0 | d24ef0970785c547709b1d3c7228e7d8b98b1f06 | refs/heads/master | 2023-06-05T02:05:48.674000 | 2021-07-01T16:18:29 | 2021-07-01T16:18:29 | 331,948,127 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,979 | cc | #include "..\..\leetcode.h"
class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
row = col = box = vector<int>(9);
int count = 0;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == '.') count++;
else fill(i, j, i / 3 * 3 + j / 3, board[i][j] - '1');
}
}
dfs(count, board);
}
private:
vector<int> row, col, box;
void fill(int i, int j, int k, int n) {
row[i] |= 1 << n;
col[j] |= 1 << n;
box[k] |= 1 << n;
}
void zero(int i, int j, int k, int n) {
row[i] &= ~(1 << n);
col[j] &= ~(1 << n);
box[k] &= ~(1 << n);
}
int possible(int i, int j) {
return ~(row[i] | col[j] | box[i / 3 * 3 + j / 3]) & ((1 << 9) - 1);
}
pair<int, int> next(vector<vector<char>>& board) {
pair<int, int> res;
int min_count = INT_MAX;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] != '.') continue;
int c = count(possible(i, j));
if (c < min_count) {
min_count = c;
res = {i, j};
}
}
}
return res;
}
bool dfs(int count, vector<vector<char>>& board) {
if (count == 0) return true;
auto [i, j] = next(board);
int p = possible(i, j);
int k = i / 3 * 3 + j / 3;
while (p) {
int n = __builtin_ctz(p & -p);
board[i][j] = n + '1';
fill(i, j, k, n);
if (dfs(count - 1, board)) return true;
board[i][j] = '.';
zero(i, j, k, n);
p &= p - 1;
}
return false;
}
int count(int p) {
int count = 0;
while (p) {
count++;
p &= p - 1;
}
return count;
}
}; | [
"[email protected]"
] | |
0f14955c67c8ded4e0b25301b31b8648ae16b52f | 4985aad8ecfceca8027709cf488bc2c601443385 | /build/Android/Debug/app/src/main/include/Fuse.Resources.Resour-7da5075.h | bb740adfa48c8d9b5e34d9b3bf2a2c23882e8030 | [] | no_license | pacol85/Test1 | a9fd874711af67cb6b9559d9a4a0e10037944d89 | c7bb59a1b961bfb40fe320ee44ca67e068f0a827 | refs/heads/master | 2021-01-25T11:39:32.441000 | 2017-06-12T21:48:37 | 2017-06-12T21:48:37 | 93,937,614 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 883 | h | // This file was generated based on '../../AppData/Local/Fusetools/Packages/Fuse.Nodes/1.0.2/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.h>
namespace g{namespace Fuse{namespace Resources{struct ResourceConverters;}}}
namespace g{namespace Uno{namespace Collections{struct Dictionary;}}}
namespace g{
namespace Fuse{
namespace Resources{
// internal static class ResourceConverters :3538
// {
uClassType* ResourceConverters_typeof();
void ResourceConverters__Get_fn(uType* __type, uObject** __retval);
struct ResourceConverters : uObject
{
static uSStrong< ::g::Uno::Collections::Dictionary*> _converters_;
static uSStrong< ::g::Uno::Collections::Dictionary*>& _converters() { return ResourceConverters_typeof()->Init(), _converters_; }
static uObject* Get(uType* __type);
};
// }
}}} // ::g::Fuse::Resources
| [
"[email protected]"
] | |
aad85aa770183929d8ccd9df0aacf59df35f147f | 465a87bdead9aee133a7b36b0c2e826ece517cbb | /ARStudy(Image processing)/ARStudy/main.cpp | 5ebb0f7ee747397046be8ca1b609d9d04b460e5c | [] | no_license | kshy9598/ARStudy | a5b55f3808d1e64cc96ee3e9266e4f4c23c3d611 | c55ce51cb595f677eb07549203d0032430a90aef | refs/heads/master | 2020-06-29T05:20:21.879000 | 2016-12-08T16:22:03 | 2016-12-08T16:22:03 | 74,446,922 | 0 | 1 | null | null | null | null | UHC | C++ | false | false | 4,927 | cpp | #include <iostream>
#include <fstream>
#include <cmath>
#include "opencv2\highgui\highgui.hpp"
#include "opencv2\opencv.hpp"
#pragma comment(lib, "opencv_world300d.lib")
const double PI = 3.14159265;
using namespace std;
using namespace cv;
bool bLBDown = false; // 마우스 버튼 눌렀는지 체크
bool checkDrag; // 드래그가 이루어졌는지 체크
CvRect box; // 드래그로 그린 박스
// 사각형 그리기
void draw_box(IplImage* img, CvRect rect)
{
cvRectangle(img, cvPoint(rect.x, rect.y),
cvPoint(rect.x + rect.width, rect.y + rect.height),
cvScalar(0xff, 0x00, 0x00));
}
// 마우스 드래그
void on_mouse(int event, int x, int y, int flag, void* params)
{
IplImage* image = (IplImage*)params;
if (event == CV_EVENT_LBUTTONDOWN){ // 왼쪽 버튼 눌렀을 시, 박스 초기화
bLBDown = true;
box = cvRect(x, y, 0, 0);
}
else if (event == CV_EVENT_LBUTTONUP){ // 왼쪽 버튼 눌렀다가 뗐을 때, 박스의 넓이, 높이를 설정한다.
bLBDown = false;
checkDrag = true;
if (box.width < 0)
{
box.x += box.width;
box.width *= -1;
}
if (box.height < 0)
{
box.y += box.height;
box.height *= -1;
}
draw_box(image, box);
}
else if (event == CV_EVENT_MOUSEMOVE && bLBDown){ // 드래그 중에는 박스의 넓이, 높이를 갱신한다.
box.width = x - box.x;
box.height = y - box.y;
}
}
// 이미지 복사
Mat copyMat(Mat source)
{
// source의 Mat을 result로 복사하는 작업
// opencv에 이미 구현이 되어있는 작업이다.
// source.copyTo(result);
Mat result = Mat::zeros(source.size(), source.type());
for (int i = 0; i < source.cols; i++){
for (int j = 0; j < source.rows; j++){
result.at<Vec3b>(j, i) = source.at<Vec3b>(j, i);
}
}
return result;
}
// 박스내 이미지 복사
Mat copyBoxMat(Mat source)
{
return source(box);
}
// y축반전
Mat yReflecting(Mat source)
{
Mat result = copyMat(source);
for (int i = 0; i < box.width; i++){
for (int j = 0; j < box.height; j++){
result.at<Vec3b>((box.y + j), (box.x + i)) = source.at<Vec3b>(box.y + j, (box.width + box.x - 1) - i);
}
}
return result;
}
// x축반전
Mat xReflecting(Mat source)
{
Mat result = copyMat(source);
for (int i = 0; i < box.width; i++){
for (int j = 0; j < box.height; j++){
result.at<Vec3b>((box.y + j), (box.x + i)) = source.at<Vec3b>((box.height + box.y - 1) - j, (box.x + i));
}
}
return result;
}
// 회전
Mat rotating(Mat source, double degree)
{
Mat result = copyMat(source);
int x0 = box.x + (box.width / 2);
int y0 = box.y + (box.height / 2);
double cosd = cos(degree*PI / 180);
double sind = sin(degree*PI / 180);
// 원본에 덮어씌우는 부분으로 인해 왼쪽 90도, 오른쪽 90도만 가능
for (int i = 0; i < box.width; i++){
for (int j = 0; j < box.height; j++){
int x1 = (box.x + i);
int y1 = (box.y + j);
int x = ((cosd * (x1 - x0)) - (sind * (y1 - y0)) + x0);
int y = ((sind * (x1 - x0)) - (cosd * (y1 - y0)) + y0);
result.at<Vec3b>(y, x) = source.at<Vec3b>((box.y + j), (box.x + i));
}
}
return result;
}
// 확대
Mat scaling(Mat source, Mat boxMat, double scale)
{
Mat result = copyMat(source);
Mat scaleBoxMat;
// 사각형 안의 Mat의 크기를 scale배 늘린다.
int boxWidth = (int)(boxMat.size().width * scale);
int boxHeight = (int)(boxMat.size().height * scale);
cv::resize(boxMat, scaleBoxMat, Size(boxWidth, boxHeight));
// 붙여넣을 때 시작 위치 정보를 갱신한다.
int x = box.x - (box.width / 2);
int y = box.y - (box.height / 2);
for (int i = 0; i < boxWidth; i++){
for (int j = 0; j < boxHeight; j++){
result.at<Vec3b>((y + j), (x + i)) = scaleBoxMat.at<Vec3b>(j, i);
}
}
return result;
}
int main()
{
IplImage copy;
IplImage * resultImage;
Mat resultMat, xReflectMat, yReflectMat, leftRotateMat, scaleMat, boxMat;
// 이미지 불러오기
Mat gMatImage = imread("./picture/pic.jpg", 1);
// Mat 이미지를 IplImage 로 복사한다.
copy = gMatImage;
resultImage = ©
checkDrag = false;
namedWindow("image");
setMouseCallback("image", on_mouse, resultImage);
cvShowImage("image", resultImage);
//드래그 대기
while (!checkDrag){
waitKey(100);
}
cvShowImage("image", resultImage);
//사각형 추가된 사진 저장
resultMat = cvarrToMat(resultImage);
boxMat = copyBoxMat(resultMat);
cout << box.x << ' ' << box.y << ' ' << box.width << ' ' << box.height << endl;
yReflectMat = yReflecting(resultMat); // y축 반전
xReflectMat = xReflecting(resultMat); // x축 반전
scaleMat = scaling(resultMat, boxMat, 1.5); // 크기 변경
leftRotateMat = rotating(resultMat, -90.0); // 90도 회전
waitKey(2000);
imshow("y반전 이미지", yReflectMat);
imshow("x반전 이미지", xReflectMat);
imshow("왼쪽 90도 회전 이미지", leftRotateMat);
imshow("1.5배 확대 이미지", scaleMat);
waitKey(0);
return 0;
} | [
"[email protected]"
] | |
0e5baca75fdd2c54621542f6cf7b7bde1bdf4164 | fdebe3129bb47afc1924e45e1ed3c97ee9213ac4 | /GA-TSP/test.cpp | 3bbfaacce92afe022185cf0c23ee0c0d44e5e17d | [] | no_license | SYSU532/artificial-intelligence | 3604e07b3670555d65ac2d36dbbf458f69658a07 | e0847fb1d181415137580e1c3e529e2120ed09d4 | refs/heads/master | 2020-04-05T20:26:14.953000 | 2019-01-11T12:50:27 | 2019-01-11T12:50:27 | 157,179,948 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,044 | cpp | #include <node.h>
namespace demo{
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
using v8::Number;
// Method1 实现一个 输出"hello world ONE !" 的方法
void Method1(const FunctionCallbackInfo<Value>& args){
Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world ONE !"));
}
// Method2 实现一个 加一 的方法
void Method2(const FunctionCallbackInfo<Value>& args){
Isolate* isolate = args.GetIsolate();
Local<Number> value = Local<Number>::Cast(args[0]);
double num = value->NumberValue() + 1;
char buf[128] = {0};
sprintf(buf,"%f", num);
args.GetReturnValue().Set(String::NewFromUtf8(isolate, buf));
}
void init(Local<Object> exports){
NODE_SET_METHOD(exports, "hello1", Method1);
NODE_SET_METHOD(exports, "addOne", Method2);
}
NODE_MODULE(addon, init)
} | [
"[email protected]"
] | |
b13420aa4004b14e74a53305e3368b5f4ee9dc92 | 72d1b579366934a24af7aff13ebf9b8cdaf58d8c | /ReadImages.cpp | a8f247f3d5b7fd89ce0c49662b42f6ef479207a1 | [] | no_license | hgpvision/Keypoint-Matcher | 48496a59dbaffefe6e89e8e14efabdb9883848bb | bf265aba62b325fab300aba2bad357ff7321ba4a | refs/heads/master | 2021-01-15T15:05:50.913000 | 2017-08-08T14:45:53 | 2017-08-08T14:45:53 | 99,702,359 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 1,454 | cpp | /*
* 文件名称:ReadImages.cpp
* 摘 要:读取图片类,图片序列放入到一个文件夹中,如"C:\\imgFile",按一定格式命名,比如"0001.jpg","00010.jpg","1.jpg"
* 使用实例:
* 包含头文件: #include "ReadImages.h"
* 先声明要给读入图片类:ReadImages imageReader("C:\\imgFile", "", ".jpg");
* 读入图片: Mat prev = imageReader.loadImage(1,0); //将读入"1.jpg"图片,灰度格式
* 2016.05.23
*/
#include "ReadImages.h"
#pragma once
ReadImages::ReadImages(std::string basepath, const std::string imagename, const std::string suffix)
{
//将路径中的文件夹分隔符统一为'/'(可以不需要这个for循环,会自动统一,该语句使用的命令参考C++ Primer)
for (auto &c : basepath)
{
if (c == '\\')
{
c = '/';
}
}
_imgSource._basepath = basepath + "/"; //这里采用'/',而不是'\\'
_imgSource._imagename = imagename; //图片名(不含编号)
_imgSource._suffix = suffix; //图像扩展名
}
//读入单张图片
//输入:imgId,一般要读入序列图片,图片都有个编号
cv::Mat ReadImages::loadImage(int imgId, int imgType)
{
//将图片编号转好字符串
std::stringstream ss;
std::string imgNum;
ss << imgId;
ss >> imgNum;
//得到图片的完整绝对路径
std::string path = _imgSource._basepath + _imgSource._imagename + imgNum + _imgSource._suffix;
cv::Mat img = cv::imread(path,imgType);
return img;
} | [
"[email protected]"
] | |
06c1ab5ff8ab138987ba9ad1ed0f423d945bafe7 | 6817617489ef291d4d53ac844ba7a2b14cc17ae2 | /11942.cpp | dcc6c32bd3395a76801df96fb6b8693215e020ec | [] | no_license | Asad51/UVA-Problem-Solving | 1932f2cd73261cd702f58d4f189a4a134dbd6286 | af28ae36a2074d4e2a67670dbbbd507438c56c3e | refs/heads/master | 2020-03-23T14:52:49.420000 | 2019-10-24T17:03:37 | 2019-10-24T17:03:37 | 120,592,261 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 449 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(int argc, char const *argv[])
{
int t;
cin>>t;
cout<<"Lumberjacks:\n";
while(t--){
bool in = true;
bool dec = true;
int p;
for(int i=0; i<10; i++){
int n;
cin>>n;
if(!i){
p = n;
continue;
}
if(n<p || !in)
in = false;
if(n>p || !dec)
dec = false;
p = n;
}
if(!in && !dec)
cout<<"Unordered\n";
else
cout<<"Ordered\n";
}
return 0;
}
| [
"[email protected]"
] | |
376f659de9de4170c19135d4e5e6f4fa7d95e938 | bc33abf80f11c4df023d6b1f0882bff1e30617cf | /CPP/other/李泉彰/hhh.cpp | 0e114bad33f893d5b9c3e166e74c22c9172ffe76 | [] | no_license | pkuzhd/ALL | 0fad250c710b4804dfd6f701d8f45381ee1a5d11 | c18525decdfa70346ec32ca2f47683951f4c39e0 | refs/heads/master | 2022-07-11T18:20:26.435000 | 2019-11-20T13:25:24 | 2019-11-20T13:25:24 | 119,031,607 | 0 | 0 | null | 2022-06-21T21:10:42 | 2018-01-26T09:19:23 | C++ | UTF-8 | C++ | false | false | 6,060 | cpp | #include <stdio.h>
#include <iostream>
using namespace std;
int qipan[15][15] = { 0 };
int times = 0;
int print();
bool is_win(int x, int y, int flag);
bool is_near(int x, int y);
bool AI_set(int flag);
int calc_value(int x, int y, int flag, int depth, int _max_value);
int qixing(int x, int y);
int main(int argc, char **argv)
{
int flag = 1;
while (true)
{
++times;
print();
int x, y;
if (flag == 1)
{
while (true)
{
cin >> x >> y;
if (!qipan[x][y] || x < 0 || x >= 15 || y < 0 || y >= 15)
break;
}
qipan[x][y] = flag;
if (is_win(x, y, flag))
break;
}
else
{
if (AI_set(flag))
break;
}
flag *= -1;
}
if (flag == 1)
{
printf("black\n");
}
else
{
printf("white\n");
}
system("pause");
return 0;
}
int print()
{
for (int i = 0; i < 15; ++i)
{
for (int j = 0; j < 15; ++j)
cout << (qipan[i][j] ? (qipan[i][j] == 1 ? "*" : "#") : "0");
cout << endl;
}
cout << endl;
return 0;
}
bool is_win(int x, int y, int flag)
{
int number = 1;
for (int i = x + 1; i < 15; ++i)
{
if (qipan[i][y] == flag)
++number;
else
break;
}
for (int i = x - 1; i >= 0; --i)
{
if (qipan[i][y] == flag)
++number;
else
break;
}
if (number >= 5)
return true;
number = 1;
for (int i = y + 1; i < 15; ++i)
{
if (qipan[x][i] == flag)
++number;
else
break;
}
for (int i = y - 1; i >= 0; --i)
{
if (qipan[x][i] == flag)
++number;
else
break;
}
if (number >= 5)
return true;
number = 1;
for (int j = 1; x + j < 15 && y + j < 15; ++j)
{
if (qipan[x + j][y + j] == flag)
++number;
else
break;
}
for (int j = 1; x - j >= 0 && y - j >= 0; ++j)
{
if (qipan[x - j][y - j] == flag)
++number;
else
break;
}
if (number >= 5)
return true;
number = 1;
for (int j = 1; x + j < 15 && y - j >= 0; ++j)
{
if (qipan[x + j][y - j] == flag)
++number;
else
break;
}
for (int j = 1; x - j >= 0 && y + j < 15; ++j)
{
if (qipan[x - j][y + j] == flag)
++number;
else
break;
}
if (number >= 5)
return true;
return false;
}
bool is_near(int x, int y)
{
// cout << x << " " << y << endl;
int _near = 2;
for (int i = (x - _near >= 0 ? x - _near : 0); i <= (x + _near < 15 ? x + _near : 14); ++i)
{
for (int j = (y - _near >= 0 ? y - _near : 0); j <= (y + _near < 15 ? y + _near : 14); ++j)
{
if (qipan[i][j])
return true;
}
}
return false;
}
bool AI_set(int flag)
{
int max_value = -10000000;
int x = 7, y = 7;
for (int i = 0; i < 15; ++i)
{
for (int j = 0; j < 15; ++j)
{
if (qipan[i][j])
continue;
if (!is_near(i, j))
continue;
int t_value = calc_value(i, j, flag, 0, max_value);
if (is_win(i, j, flag))
{
qipan[i][j] = flag;
return true;
}
if (t_value > max_value)
{
max_value = t_value;
x = i;
y = j;
}
}
}
qipan[x][y] = flag;
cout << x << " " << y << " " << flag << " " << is_win(x, y, flag)<< endl;
return false;
}
int calc_value(int x, int y, int flag, int depth, int _max_value)
{
int _value = 0;
qipan[x][y] = flag;
if (depth < 4)
{
int max_value = -10000000;
for (int i = 0; i < 15; ++i)
{
for (int j = 0; j < 15; ++j)
{
if (qipan[i][j] || !is_near(i, j))
continue;
int t_value = calc_value(i, j, -flag, depth + 1, max_value);
if (t_value > -_max_value)
{
qipan[x][y] = 0;
return t_value;
}
if (is_win(i, j, -flag))
{
qipan[x][y] = 0;
return -10000000;
}
if (t_value > max_value)
{
max_value = t_value;
}
}
}
_value -= max_value;
}
else
_value += qixing(x, y);
qipan[x][y] = 0;
return _value;
}
int qixing(int x, int y)
{
int flag = qipan[x][y];
bool dead = false;
int number = 1;
int _value = 0;
int sz_qixing[2][6] = { 0 };
// x 方向
number = 1;
dead = false;
for (int i = x + 1; ; ++i)
{
if (i < 15 && qipan[i][y] == flag)
++number;
else
{
if (i >= 15 || qipan[i][y])
dead = true;
break;
}
}
for (int i = x - 1; i >= 0; --i)
{
if (i >= 0 && qipan[i][y] == flag)
++number;
else
{
if ((i < 0 || qipan[i][y]) && dead)
break;
else
{
if (dead || qipan[i][y])
dead = true;
++sz_qixing[dead][number];
}
}
}
// y方向
number = 1;
dead = false;
for (int i = y + 1; ; ++i)
{
if (i < 15 && qipan[x][i] == flag)
++number;
else
{
if (i >= 15 || qipan[x][i])
dead = true;
break;
}
}
for (int i = y - 1; i >= 0; --i)
{
if (i >= 0 && qipan[x][i] == flag)
++number;
else
{
if ((i < 0 || qipan[x][i]) && dead)
break;
else
{
if (dead || qipan[x][i])
dead = true;
++sz_qixing[dead][number];
}
}
}
// x y 方向
number = 1;
dead = false;
for (int i = 1; ; ++i)
{
if (x + i < 15 && y + i < 15 && qipan[x + i][y + i] == flag)
++number;
else
{
if (x + i >= 15 || y + i >= 15 || qipan[x + i][y + i])
dead = true;
break;
}
}
for (int i = 1; ; ++i)
{
if (x - i >= 0 && y - i >= 0 && qipan[x - i][y - i] == flag)
++number;
else
{
if ((x - i < 0 || y - i < 0 || qipan[x - i][y - i]) && dead)
break;
else
{
if (dead || qipan[x - i][y - i])
dead = true;
++sz_qixing[dead][number];
}
}
}
// x -y 方向
number = 1;
dead = false;
for (int i = 1; ; ++i)
{
if (x + i < 15 && y - i >= 0 && qipan[x + i][y - i] == flag)
++number;
else
{
if (x + i >= 15 || y - i < 0 || qipan[x + i][y - i])
dead = true;
break;
}
}
for (int i = 1; ; ++i)
{
if (x - i >= 0 && y + i < 15 && qipan[x - i][y + i] == flag)
++number;
else
{
if ((x - i < 0 || y + i >= 15 || qipan[x - i][y + i]) && dead)
break;
else
{
if (dead || qipan[x - i][y + i])
dead = true;
++sz_qixing[dead][number];
}
}
}
if (sz_qixing[false][4] || (sz_qixing[true][4] + sz_qixing[false][3]) >= 2)
_value += 1000000;
_value += sz_qixing[false][3] * 10000;
_value += sz_qixing[true][3] * 1000;
_value += sz_qixing[false][2] * 100;
_value += sz_qixing[true][2] * 10;
return _value;
}
| [
"[email protected]"
] | |
95534aae2f06adbc3b44e859658780f8bf0cf800 | 3f9081b23333e414fb82ccb970e15b8e74072c54 | /bs2k/behaviors/skills/oneortwo_step_kick_bms.h | e7f968c14d8092e86a4e41ed23b6e7ac3a2558ab | [] | no_license | rc2dcc/Brainstormers05PublicRelease | 5c8da63ac4dd3b84985bdf791a4e5580bbf0ba59 | 2141093960fad33bf2b3186d6364c08197e9fe8e | refs/heads/master | 2020-03-22T07:32:36.757000 | 2018-07-04T18:28:32 | 2018-07-04T18:28:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,945 | h | /*
Brainstormers 2D (Soccer Simulation League 2D)
PUBLIC SOURCE CODE RELEASE 2005
Copyright (C) 1998-2005 Neuroinformatics Group,
University of Osnabrueck, Germany
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef _ONEORTWO_STEP_KICK_BMS_H_
#define _ONEORTWO_STEP_KICK_BMS_H_
/* This behavior is a port of Move_1or2_Step_Kick into the behavior
framework. get_cmd will try to kick in one step and otherwise return
a cmd that will start a two-step kick. There are some functions
that return information about the reachable velocities and the needed
steps, so that you can prepare in your code for what this behavior will
do.
This behavior usually takes the current player position as reference point,
but you can override this by calling set_state() prior to any other function.
This makes it possible to "fake" the player's position during the current cycle.
Use reset_state to re-read the WS information, or wait until the next cycle.
Note that kick_to_pos_with_final_vel() is rather unprecise concerning the
final velocity of the ball. I don't know how to calculate the needed starting
vel precisely, so I have taken the formula from the original Neuro_Kick2 move
(which was even more unprecise...) and tweaked it a bit, but it is still
not perfect.
Note also that this behavior, as opposed to the original move, has a working
collision check - the original move ignored the player's vel...
(w) 2002 Manuel Nickschas
*/
#include "../base_bm.h"
#include "one_step_kick_bms.h"
#include "angle.h"
#include "Vector.h"
#include "tools.h"
#include "cmd.h"
#include "n++.h"
#include "macro_msg.h"
#include "valueparser.h"
#include "options.h"
#include "ws_info.h"
#include "log_macros.h"
#include "mystate.h"
#include "../../policy/abstract_mdp.h"
class OneOrTwoStepKickItrActions {
static const Value kick_pwr_min = 20;
static const Value kick_pwr_inc = 10;
static const Value kick_pwr_max = 100;
static const Value kick_ang_min = 0;
static const Value kick_ang_inc = 2*PI/8.;
// static const Value kick_ang_inc = 2*PI/36.; // ridi: I think it should be as much! too much
static const Value kick_ang_max = 2*PI-kick_ang_inc;
static const Value dash_pwr_min = 20;
static const Value dash_pwr_inc = 20;
static const Value dash_pwr_max = 100;
static const Value turn_ang_min = 0;
static const Value turn_ang_inc = 2*PI/18.;
// static const Value turn_ang_max = 2*PI-turn_ang_inc;
static const Value turn_ang_max = 0; // ridi: do not allow turns
static const Value kick_pwr_steps = (kick_pwr_max-kick_pwr_min)/kick_pwr_inc + 1;
static const Value dash_pwr_steps = (dash_pwr_max-dash_pwr_min)/dash_pwr_inc + 1;
static const Value turn_ang_steps = (turn_ang_max-turn_ang_min)/turn_ang_inc + 1;
static const Value kick_ang_steps = (kick_ang_max-kick_ang_min)/kick_ang_inc + 1;
Cmd_Main action;
Value kick_pwr,dash_pwr;
ANGLE kick_ang,turn_ang;
int kick_pwr_done,kick_ang_done,dash_pwr_done,turn_ang_done;
public:
void reset() {
kick_pwr_done=0;kick_ang_done=0;dash_pwr_done=0;turn_ang_done=0;
kick_pwr=kick_pwr_min;kick_ang= ANGLE(kick_ang_min);dash_pwr=dash_pwr_min;
turn_ang=ANGLE(turn_ang_min);
}
Cmd_Main *next() {
if(kick_pwr_done<kick_pwr_steps && kick_ang_done<kick_ang_steps) {
action.unset_lock();
action.unset_cmd();
action.set_kick(kick_pwr,kick_ang.get_value_mPI_pPI());
kick_ang+= ANGLE(kick_ang_inc);
if(++kick_ang_done>=kick_ang_steps) {
kick_ang=ANGLE(kick_ang_min);
kick_ang_done=0;
kick_pwr+=kick_pwr_inc;
kick_pwr_done++;
}
return &action;
}
if(dash_pwr_done<dash_pwr_steps) {
action.unset_lock();
action.unset_cmd();
action.set_dash(dash_pwr);
dash_pwr+=dash_pwr_inc;
dash_pwr_done++;
return &action;
}
if(turn_ang_done<turn_ang_steps) {
action.unset_lock();
action.unset_cmd();
action.set_turn(turn_ang);
turn_ang+= ANGLE(turn_ang_inc);
turn_ang_done++;
return &action;
}
return NULL;
}
};
class OneOrTwoStepKick: public BaseBehavior {
static bool initialized;
#if 0
struct MyState {
Vector my_vel;
Vector my_pos;
ANGLE my_angle;
Vector ball_pos;
Vector ball_vel;
Vector op_pos;
ANGLE op_bodydir;
};
#endif
OneStepKick *onestepkick;
OneOrTwoStepKickItrActions itr_actions;
Cmd_Main result_cmd1,result_cmd2;
Value result_vel1,result_vel2;
bool result_status;
bool need_2_steps;
long set_in_cycle;
Vector target_pos;
ANGLE target_dir;
Value target_vel;
bool kick_to_pos;
bool calc_done;
MyState fake_state;
long fake_state_time;
void get_ws_state(MyState &state);
MyState get_cur_state();
bool calculate(const MyState &state,Value vel,const ANGLE &dir,const Vector &pos,bool to_pos,
Cmd_Main &res_cmd1,Value &res_vel1,Cmd_Main &res_cmd2,Value &res_vel2,
bool &need_2steps);
bool do_calc();
public:
/** This makes it possible to "fake" WS information.
This must be called _BEFORE_ any of the kick functions, and is valid for
the current cycle only.
*/
void set_state(const Vector &mypos,const Vector &myvel,const ANGLE &myang,
const Vector &ballpos,const Vector &ballvel,
const Vector &op_pos = Vector(1000,1000),
const ANGLE &op_bodydir = ANGLE(0),
const int op_bodydir_age = 1000);
void set_state( const AState & state );
/** Resets the current state to that found in WS.
This must be called _BEFORE_ any of the kick functions.
*/
void reset_state();
void kick_in_dir_with_initial_vel(Value vel,const ANGLE &dir);
void kick_in_dir_with_max_vel(const ANGLE &dir);
void kick_to_pos_with_initial_vel(Value vel,const Vector &point);
void kick_to_pos_with_final_vel(Value vel,const Vector &point);
void kick_to_pos_with_max_vel(const Vector &point);
/** false is returned if we do not reach our desired vel within two cycles.
Note that velocities are set to zero if the resulting pos is not ok,
meaning that even if a cmd would reach the desired vel, we will ignore
it if the resulting pos is not ok.
*/
bool get_vel(Value &vel_1step,Value &vel_2step);
bool get_cmd(Cmd &cmd_1step,Cmd &cmd_2step);
bool get_vel(Value &best_vel); // get best possible vel (1 or 2 step)
bool get_cmd(Cmd &best_cmd); // get best possible cmd (1 or 2 step)
// returns 0 if kick is not possible, 1 if kick in 1 step is possible, 2 if in 2 steps. probably modifies vel
int is_kick_possible(Value &speed,const ANGLE &dir);
bool need_two_steps();
bool can_keep_ball_in_kickrange();
static bool init(char const * conf_file, int argc, char const* const* argv) {
if(initialized) return true;
initialized = true;
if(OneStepKick::init(conf_file,argc,argv)) {
cout << "\nOneOrTwoStepKick behavior initialized.";
} else {
ERROR_OUT << "\nCould not initialize OneStepKick behavior - stop loading.";
exit(1);
}
return true;
}
OneOrTwoStepKick() {
set_in_cycle = -1;
onestepkick = new OneStepKick();
onestepkick->set_log(false); // we don't want OneStepKick-Info in our logs!
}
virtual ~OneOrTwoStepKick() {
delete onestepkick;
}
};
#endif
| [
"[email protected]"
] | |
a4107844dad660b1e38707bc33b03c52f16b4cbd | 61442c0297fef23453b7bc43ab5bbd6a52c95fa7 | /grappletation/Source/Grappletation/Gem.cpp | 44c2698bb81fe1bfc4a986a9d39c8944aae59d65 | [] | no_license | AshleyThew/GameProgramming | c9cf634ef81dd7e1753b3ef45d56a6ee38b9a072 | 22032cf7b141222d498c083527e81a854864e694 | refs/heads/main | 2023-08-23T15:51:59.141000 | 2021-10-25T10:01:57 | 2021-10-25T10:01:57 | 420,814,528 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 778 | cpp | #include "Gem.h"
#include "Entity.h"
#include "Renderer.h"
#include "Sprite.h"
Gem::Gem(int x, int y)
{
id.x = x;
id.y = y;
}
Gem::~Gem()
{
}
bool
Gem::Initialise(Renderer& renderer, const char* gemType, float scale)
{
m_pSprite = renderer.CreateSprite(gemType);
m_pSprite->SetScale(scale);
m_position.x = (scale * 8) + (id.x * scale * 16);
m_position.y = (scale * 8) + (id.y * scale * 16);
Reset();
return false;
}
void
Gem::Process(float deltaTime)
{
Entity::Process(deltaTime);
}
void
Gem::Draw(Renderer& renderer)
{
Entity::Draw(renderer);
}
bool
Gem::GetCollected()
{
return collected;
}
void
Gem::SetCollected()
{
collected = true;
SetDead(true);
}
void
Gem::Reset()
{
collected = false;
SetDead(false);
}
Vector2
Gem::GetID()
{
return id;
}
| [
"[email protected]"
] | |
b7c78a511904d321aa74ab25ce20a44c3a3f0a0e | d51d72f1b6e834d89c8551bb07487bed84cdaa31 | /src/output/osg/customCode/osg/AnimationPath_pmoc.cpp | dc66ae9496a4b899d13c9038f85bec5d8cc50019 | [] | no_license | wangfeilong321/osg4noob | 221204aa15efa18f1f049548ad076ef27371ecad | 99a15c3fd2523c4bd537fa3afb0b47e15c8f335a | refs/heads/master | 2021-01-12T20:00:43.854000 | 2015-11-06T15:37:01 | 2015-11-06T15:37:01 | 48,840,543 | 0 | 1 | null | 2015-12-31T07:56:31 | 2015-12-31T07:56:31 | null | UTF-8 | C++ | false | false | 1,778 | cpp | #include <osg/AnimationPath>
//includes
#include <MetaQQuickLibraryRegistry.h>
#include <customCode/osg/AnimationPath_pmoc.hpp>
using namespace pmoc;
osg::QMLAnimationPath::QMLAnimationPath(pmoc::Instance *i,QObject* parent):QReflect_AnimationPath(i,parent){
//custom initializations
}
QQuickItem* osg::QMLAnimationPath::connect2View(QQuickItem*i){
this->_view=QReflect_AnimationPath::connect2View(i);
///connect this's signals/slot to its qml component////////////////////////////////////////////////////////////////
///CustomiZE here
return this->_view;
}
void osg::QMLAnimationPath::updateModel(){
QReflect_AnimationPath::updateModel();
///update this according to state of _model when it has been changed via pmoc/////////////////////////////////////////////
///CustomiZE here
}
#ifndef AUTOMOCCPP
#define AUTOMOCCPP 1
#include "moc_AnimationPath_pmoc.cpp"
#endif
#include <MetaQQuickLibraryRegistry.h>
#include <customCode/osg/AnimationPath_pmoc.hpp>
using namespace pmoc;
osg::QMLAnimationPathCallback::QMLAnimationPathCallback(pmoc::Instance *i,QObject* parent):QReflect_AnimationPathCallback(i,parent){
//custom initializations
}
QQuickItem* osg::QMLAnimationPathCallback::connect2View(QQuickItem*i){
this->_view=QReflect_AnimationPathCallback::connect2View(i);
///connect this's signals/slot to its qml component////////////////////////////////////////////////////////////////
///CustomiZE here
return this->_view;
}
void osg::QMLAnimationPathCallback::updateModel(){
QReflect_AnimationPathCallback::updateModel();
///update this according to state of _model when it has been changed via pmoc/////////////////////////////////////////////
///CustomiZE here
}
#ifndef AUTOMOCCPP
#define AUTOMOCCPP 1
#include "moc_AnimationPath_pmoc.cpp"
#endif
| [
"[email protected]"
] | |
cb50f617109e0944e114883af3fc3af8be9a6b7e | 9030ce2789a58888904d0c50c21591632eddffd7 | /SDK/ARKSurvivalEvolved_Buff_PreventDismount_functions.cpp | 7e18c4f1010b3ae0b9f98e0ea4d779d40e1340ba | [
"MIT"
] | permissive | 2bite/ARK-SDK | 8ce93f504b2e3bd4f8e7ced184980b13f127b7bf | ce1f4906ccf82ed38518558c0163c4f92f5f7b14 | refs/heads/master | 2022-09-19T06:28:20.076000 | 2022-09-03T17:21:00 | 2022-09-03T17:21:00 | 232,411,353 | 14 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,490 | cpp | // ARKSurvivalEvolved (332.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_Buff_PreventDismount_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function Buff_PreventDismount.Buff_PreventDismount_C.UserConstructionScript
// ()
void ABuff_PreventDismount_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function Buff_PreventDismount.Buff_PreventDismount_C.UserConstructionScript");
ABuff_PreventDismount_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Buff_PreventDismount.Buff_PreventDismount_C.ExecuteUbergraph_Buff_PreventDismount
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void ABuff_PreventDismount_C::ExecuteUbergraph_Buff_PreventDismount(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function Buff_PreventDismount.Buff_PreventDismount_C.ExecuteUbergraph_Buff_PreventDismount");
ABuff_PreventDismount_C_ExecuteUbergraph_Buff_PreventDismount_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
e701e032706c6d0b6712cbf46f97a1491037c069 | 509ed385d3faa95ed92957f0f691fc3fe1d6816a | /src/Workers/Worker.h | db1536697c5f967497dfa8fe487e786329ac19ec | [] | no_license | xrenoder/Node-InfrastructureTorrent | d6540c725cb9239bcf421a7891e7ebbeb6505701 | 21c3eb739d0b41cb6858d747cd108708bbfdb73d | refs/heads/master | 2023-08-29T01:02:15.760000 | 2021-09-20T10:03:30 | 2021-09-20T10:03:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 504 | h | #ifndef WORKER_H_
#define WORKER_H_
#include <memory>
#include <optional>
#include "OopUtils.h"
namespace torrent_node_lib {
struct BlockInfo;
class Worker: public common::no_copyable, common::no_moveable{
public:
virtual void start() = 0;
virtual void process(std::shared_ptr<BlockInfo> bi, std::shared_ptr<std::string> dump) = 0;
virtual std::optional<size_t> getInitBlockNumber() const = 0;
virtual ~Worker() = default;
};
}
#endif // WORKER_H_
| [
"[email protected]"
] | |
b1bcf5c96e5da91d67fb19ffdce0f2269d7bd395 | cbb3ef472b4f4bbf1480552160aedbd88f230ee3 | /Carpeta_de_proyectos_Arduino_copia_de_seguridad/NodemCU_Firebase_central/NodemCU_Firebase_central.ino | 27d5e0ce48b73f435a3d2f3cb93ee7104a25d57a | [] | no_license | agrgal/ARDUINO_CS | 5a68e236ec660b7ce4e34ee1253b1c0ed27033f0 | f94200dceb4a8d7d27332a3045301daecbb6c979 | refs/heads/master | 2022-09-13T08:06:10.458000 | 2022-08-29T14:30:27 | 2022-08-29T14:30:27 | 242,396,006 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,424 | ino |
/*
* Created by Aurelio Gallardo Rodríguez
* Based on: K. Suwatchai (Mobizt)
*
* Email: [email protected]
*
* CENTRAL. Lectura
*
* Julio - 2019
*
*/
//FirebaseESP8266.h must be included before ESP8266WiFi.h
#include "FirebaseESP8266.h"
#include <ESP8266WiFi.h>
#define FIREBASE_HOST "botonpanicoseritium.firebaseio.com"
#define FIREBASE_AUTH "Y0QVBot29hCVGZJQbpVUMr3IKngc7GacE2355bdy"
#define WIFI_SSID "JAZZTEL_shny"
#define WIFI_PASSWORD "3z7s5tvbtu4s"
//Define FirebaseESP8266 data object
FirebaseData bd;
String path = "/Estaciones"; // path a FireBase
char *estaciones[]= {"A","B","C","D","E"}; // Estaciones que voy a controlar
int i=1; // contador general
int activo=0; // Alarma
#define LED 5 // D1(gpio5)
void setup()
{
Serial.begin(115200);
pinMode(LED, OUTPUT);
// conectando a la WIFI
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Conectando a la WiFi");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(300);
}
Serial.println();
Serial.print("Conectado con IP: ");
Serial.println(WiFi.localIP());
Serial.println();
// Conectando a la bd real Time Firebase
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
Firebase.reconnectWiFi(true);
//Set database read timeout to 1 minute (max 15 minutes)
Firebase.setReadTimeout(bd, 1000 * 60);
//tiny, small, medium, large and unlimited.
//Size and its write timeout e.g. tiny (1s), small (10s), medium (30s) and large (60s).
Firebase.setwriteSizeLimit(bd, "unlimited");
}
// Bucle principal
void loop() {
activo=0; // reinicializo la variable
for(i=0;i<=4;i++) {
delay(1);
activo=activo+rFB("/"+(String) estaciones[i]);
}
digitalWrite(LED,(activo>=1)); // activo el LED si es mayor o igual a 1.
}
// Función de lectura
int rFB(String estacion){// lee el dato de la entrada correspondiente
int valor=0;
if (Firebase.getInt(bd, path+estacion)) {
if (bd.dataType() == "int") {
Serial.println("Dato leído: "+ path+estacion +" --> " + (String) bd.intData());
valor = bd.intData(); // retorna el valor
}
} else {
// Si no existe el dato de la estación, salta el error
// Pero el error se muestra en pantalla (bd.errorReason()) Y REINICIALIZA LA UNIDAD, lo cual no quiero.
Serial.println("Estoy dando un error... ojo");
// Serial.println(bd.errorReason());
}
return valor;
}
| [
"[email protected]"
] | |
bcee12c3aa60f8c1d8f0802c1bfdfe7600a1e3ef | 067b197860f7712e3f92564d0f8d88b0cf34f9d7 | /ext/hera/wasserstein/include/dnn/parallel/tbb.h | 64c59e0ee985223027151daa201d626258eb299b | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | tgebhart/dionysus_tensorflow | be8757369beb4997b12246c5c7d3cbdbb2fd84bb | 344769bb6d5446c8fd43462b1dfd6a08d35631a8 | refs/heads/master | 2021-09-28T10:03:56.406000 | 2018-11-16T17:15:34 | 2018-11-16T17:15:34 | 112,226,756 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,126 | h | #ifndef PARALLEL_H
#define PARALLEL_H
//#include <iostream>
#include <vector>
#include <boost/range.hpp>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#ifdef TBB
#include <tbb/tbb.h>
#include <tbb/concurrent_hash_map.h>
#include <tbb/scalable_allocator.h>
#include <boost/serialization/split_free.hpp>
#include <boost/serialization/collections_load_imp.hpp>
#include <boost/serialization/collections_save_imp.hpp>
namespace dnn
{
using tbb::mutex;
using tbb::task_scheduler_init;
using tbb::task_group;
using tbb::task;
template<class T>
struct vector
{
typedef tbb::concurrent_vector<T> type;
};
template<class T>
struct atomic
{
typedef tbb::atomic<T> type;
static T compare_and_swap(type& v, T n, T o) { return v.compare_and_swap(n,o); }
};
template<class Iterator, class F>
void do_foreach(Iterator begin, Iterator end, const F& f) { tbb::parallel_do(begin, end, f); }
template<class Range, class F>
void for_each_range_(const Range& r, const F& f)
{
for (typename Range::iterator cur = r.begin(); cur != r.end(); ++cur)
f(*cur);
}
template<class F>
void for_each_range(size_t from, size_t to, const F& f)
{
//static tbb::affinity_partitioner ap;
//tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::range_type, F>, _1, f), ap);
tbb::parallel_for(from, to, f);
}
template<class Container, class F>
void for_each_range(const Container& c, const F& f)
{
//static tbb::affinity_partitioner ap;
//tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::range_type, F>, _1, f), ap);
tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::const_range_type, F>, _1, f));
}
template<class Container, class F>
void for_each_range(Container& c, const F& f)
{
//static tbb::affinity_partitioner ap;
//tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::range_type, F>, _1, f), ap);
tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::range_type, F>, _1, f));
}
template<class ID, class NodePointer, class IDTraits, class Allocator>
struct map_traits
{
typedef tbb::concurrent_hash_map<ID, NodePointer, IDTraits, Allocator> type;
typedef typename type::range_type range;
};
struct progress_timer
{
progress_timer(): start(tbb::tick_count::now()) {}
~progress_timer()
{ std::cout << (tbb::tick_count::now() - start).seconds() << " s" << std::endl; }
tbb::tick_count start;
};
}
// Serialization for tbb::concurrent_vector<...>
namespace boost
{
namespace serialization
{
template<class Archive, class T, class A>
void save(Archive& ar, const tbb::concurrent_vector<T,A>& v, const unsigned int file_version)
{ stl::save_collection(ar, v); }
template<class Archive, class T, class A>
void load(Archive& ar, tbb::concurrent_vector<T,A>& v, const unsigned int file_version)
{
stl::load_collection<Archive,
tbb::concurrent_vector<T,A>,
stl::archive_input_seq< Archive, tbb::concurrent_vector<T,A> >,
stl::reserve_imp< tbb::concurrent_vector<T,A> >
>(ar, v);
}
template<class Archive, class T, class A>
void serialize(Archive& ar, tbb::concurrent_vector<T,A>& v, const unsigned int file_version)
{ split_free(ar, v, file_version); }
template<class Archive, class T>
void save(Archive& ar, const tbb::atomic<T>& v, const unsigned int file_version)
{ T v_ = v; ar << v_; }
template<class Archive, class T>
void load(Archive& ar, tbb::atomic<T>& v, const unsigned int file_version)
{ T v_; ar >> v_; v = v_; }
template<class Archive, class T>
void serialize(Archive& ar, tbb::atomic<T>& v, const unsigned int file_version)
{ split_free(ar, v, file_version); }
}
}
#else
#include <algorithm>
#include <map>
#include <boost/progress.hpp>
namespace dnn
{
template<class T>
struct vector
{
typedef ::std::vector<T> type;
};
template<class T>
struct atomic
{
typedef T type;
static T compare_and_swap(type& v, T n, T o) { if (v != o) return v; v = n; return o; }
};
template<class Iterator, class F>
void do_foreach(Iterator begin, Iterator end, const F& f) { std::for_each(begin, end, f); }
template<class F>
void for_each_range(size_t from, size_t to, const F& f)
{
for (size_t i = from; i < to; ++i)
f(i);
}
template<class Container, class F>
void for_each_range(Container& c, const F& f)
{
BOOST_FOREACH(const typename Container::value_type& i, c)
f(i);
}
template<class Container, class F>
void for_each_range(const Container& c, const F& f)
{
BOOST_FOREACH(const typename Container::value_type& i, c)
f(i);
}
struct mutex
{
struct scoped_lock
{
scoped_lock() {}
scoped_lock(mutex& ) {}
void acquire(mutex& ) const {}
void release() const {}
};
};
struct task_scheduler_init
{
task_scheduler_init(unsigned) {}
void initialize(unsigned) {}
static const unsigned automatic = 0;
static const unsigned deferred = 0;
};
struct task_group
{
template<class Functor>
void run(const Functor& f) const { f(); }
void wait() const {}
};
template<class ID, class NodePointer, class IDTraits, class Allocator>
struct map_traits
{
typedef std::map<ID, NodePointer,
typename IDTraits::Comparison,
Allocator> type;
typedef type range;
};
using boost::progress_timer;
}
#endif // TBB
namespace dnn
{
template<class Range, class F>
void do_foreach(const Range& range, const F& f) { do_foreach(boost::begin(range), boost::end(range), f); }
}
#endif
| [
"[email protected]"
] | |
a702a5d40a3a672624e691115d63b4a004c979d0 | 7aa189c718f8a63c256685a435d027ace3833f6b | /include/ogonek/error.h++ | ca7ff1f2bc1d6ac11fcbdaacee61fbdef1c7430d | [
"CC0-1.0"
] | permissive | rmartinho/ogonek | d5523145108de1255298a17c1c25065beb19b82c | 0042f30c6c674effd21d379c53658c88054c58b9 | refs/heads/devel | 2020-05-21T15:17:39.490000 | 2019-09-29T10:58:31 | 2019-09-29T10:58:31 | 8,255,019 | 16 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 4,549 | // Ogonek
//
// Written in 2017 by Martinho Fernandes <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
/**
* Error handling
* ==============
*/
#ifndef OGONEK_ERROR_HPP
#define OGONEK_ERROR_HPP
#include <ogonek/error_fwd.h++>
#include <ogonek/concepts.h++>
#include <ogonek/types.h++>
#include <ogonek/encoding.h++>
#include <range/v3/range_concepts.hpp>
#include <range/v3/range_traits.hpp>
#include <stdexcept>
namespace ogonek {
/**
* .. class:: unicode_error
*
* The base class for all Unicode-related errors.
*/
struct unicode_error
: virtual std::exception {
char const* what() const noexcept override {
return u8"Unicode error";
}
};
/**
* .. class:: template <EncodingForm Encoding>\
* encode_error : virtual unicode_error
*
* :thrown: when an error occurs during an encoding operation.
*/
template <typename Encoding>
struct encode_error
: virtual unicode_error {
CONCEPT_ASSERT(EncodingForm<Encoding>());
char const* what() const noexcept override {
return u8"encoding failed ";
}
};
/**
* .. class:: template <EncodingForm Encoding>\
* decode_error : virtual unicode_error
*
* :thrown: when an error occurs during a decoding operation.
*/
template <typename Encoding>
struct decode_error
: virtual unicode_error {
CONCEPT_ASSERT(EncodingForm<Encoding>());
char const* what() const noexcept override {
return u8"decoding failed";
}
};
/**
* .. var:: auto assume_valid
*
* A tag used to request that encoding/decoding functions assume the
* input has been validated before.
*
* .. warning::
*
* Using this tag with input that isn't actually valid yields
* undefined behavior.
*/
struct assume_valid_t {} constexpr assume_valid {};
/**
* .. var:: auto discard_errors
*
* An error handler for encoding/decoding functions that simply
* discards the portions of the input that have errors.
*/
struct discard_errors_t {
template <typename E>
optional<code_point> operator()(E) const {
return {};
}
} constexpr discard_errors {};
CONCEPT_ASSERT(EncodeErrorHandler<discard_errors_t, archetypes::EncodingForm>());
CONCEPT_ASSERT(DecodeErrorHandler<discard_errors_t, archetypes::EncodingForm>());
/**
* .. var:: auto replace_errors
*
* An error handler for encoding/decoding functions that replaces
* portions of the input that have errors with a replacement character.
* When decoding, this is |u-fffd|, but when encoding and the target
* doesn't support it, some encoding-specific character is used
* instead.
*/
struct replace_errors_t {
template <typename Encoding,
CONCEPT_REQUIRES_(EncodingForm<Encoding>())>
optional<code_point> operator()(encode_error<Encoding>) const {
return replacement_character_v<Encoding>;
}
template <typename Encoding,
CONCEPT_REQUIRES_(EncodingForm<Encoding>())>
optional<code_point> operator()(decode_error<Encoding>) const {
return { U'\uFFFD' };
}
} constexpr replace_errors {};
CONCEPT_ASSERT(EncodeErrorHandler<replace_errors_t, archetypes::EncodingForm>());
CONCEPT_ASSERT(DecodeErrorHandler<replace_errors_t, archetypes::EncodingForm>());
/**
* .. var:: auto throw_error
*
* An error handler for encoding/decoding functions that throws when an
* error is found in the input.
*/
struct throw_error_t {
template <typename E>
optional<code_point> operator()(E e) const {
throw e;
}
} constexpr throw_error {};
CONCEPT_ASSERT(EncodeErrorHandler<throw_error_t, archetypes::EncodingForm>());
CONCEPT_ASSERT(DecodeErrorHandler<throw_error_t, archetypes::EncodingForm>());
} // namespace ogonek
#endif // OGONEK_ERROR_HPP
| [
"[email protected]"
] | ||
fa606684822edaeb65a3facbab4e69b8044c96ef | 6aeccfb60568a360d2d143e0271f0def40747d73 | /sandbox/SOC/2011/simd/boost/simd/toolbox/constant/include/constants/minexponent.hpp | 0fd6c857f2cef5aa7fcc1f22aca4daf4a5f7a9c3 | [] | no_license | ttyang/sandbox | 1066b324a13813cb1113beca75cdaf518e952276 | e1d6fde18ced644bb63e231829b2fe0664e51fac | refs/heads/trunk | 2021-01-19T17:17:47.452000 | 2013-06-07T14:19:55 | 2013-06-07T14:19:55 | 13,488,698 | 1 | 3 | null | 2023-03-20T11:52:19 | 2013-10-11T03:08:51 | C++ | UTF-8 | C++ | false | false | 232 | hpp | #ifndef BOOST_SIMD_TOOLBOX_CONSTANT_INCLUDE_CONSTANTS_MINEXPONENT_HPP_INCLUDED
#define BOOST_SIMD_TOOLBOX_CONSTANT_INCLUDE_CONSTANTS_MINEXPONENT_HPP_INCLUDED
#include <boost/simd/toolbox/constant/constants/minexponent.hpp>
#endif
| [
"[email protected]"
] | |
d906994d3f90133151039af0434882e3553ba719 | 1c02e13a776e5e8bc3e2a6182b5df4efb2c71d32 | /core/unit_test/tstDeepCopy.hpp | b3fdab4da5ef0b61357d256cf996dae1b69884f0 | [
"BSD-3-Clause"
] | permissive | junghans/Cabana | 91b82827dd9fb8321bea9ea3750c196946a6aac0 | 7b9078f81bde68c949fd6ae913ce80eeaf0f8f8a | refs/heads/master | 2021-06-14T09:57:01.658000 | 2019-01-04T22:24:45 | 2019-01-04T22:24:45 | 150,330,482 | 1 | 1 | BSD-3-Clause | 2019-01-07T16:24:20 | 2018-09-25T21:17:53 | C++ | UTF-8 | C++ | false | false | 5,252 | hpp | /****************************************************************************
* Copyright (c) 2018 by the Cabana authors *
* All rights reserved. *
* *
* This file is part of the Cabana library. Cabana is distributed under a *
* BSD 3-clause license. For the licensing terms see the LICENSE file in *
* the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#include <Cabana_DeepCopy.hpp>
#include <Cabana_AoSoA.hpp>
#include <Cabana_Types.hpp>
#include <gtest/gtest.h>
namespace Test
{
//---------------------------------------------------------------------------//
// Check the data given a set of values.
template<class aosoa_type>
void checkDataMembers(
aosoa_type aosoa,
const float fval, const double dval, const int ival,
const int dim_1, const int dim_2, const int dim_3 )
{
auto slice_0 = aosoa.template slice<0>();
auto slice_1 = aosoa.template slice<1>();
auto slice_2 = aosoa.template slice<2>();
auto slice_3 = aosoa.template slice<3>();
for ( std::size_t idx = 0; idx < aosoa.size(); ++idx )
{
// Member 0.
for ( int i = 0; i < dim_1; ++i )
for ( int j = 0; j < dim_2; ++j )
for ( int k = 0; k < dim_3; ++k )
EXPECT_EQ( slice_0( idx, i, j, k ),
fval * (i+j+k) );
// Member 1.
EXPECT_EQ( slice_1( idx ), ival );
// Member 2.
for ( int i = 0; i < dim_1; ++i )
EXPECT_EQ( slice_2( idx, i ), dval * i );
// Member 3.
for ( int i = 0; i < dim_1; ++i )
for ( int j = 0; j < dim_2; ++j )
EXPECT_EQ( slice_3( idx, i, j ), dval * (i+j) );
}
}
//---------------------------------------------------------------------------//
// Perform a deep copy test.
template<class DstMemorySpace, class SrcMemorySpace,
int DstVectorLength, int SrcVectorLength>
void testDeepCopy()
{
// Data dimensions.
const int dim_1 = 3;
const int dim_2 = 2;
const int dim_3 = 4;
// Declare data types.
using DataTypes =
Cabana::MemberTypes<float[dim_1][dim_2][dim_3],
int,
double[dim_1],
double[dim_1][dim_2]
>;
// Declare the AoSoA types.
using DstAoSoA_t = Cabana::AoSoA<DataTypes,DstMemorySpace,DstVectorLength>;
using SrcAoSoA_t = Cabana::AoSoA<DataTypes,SrcMemorySpace,SrcVectorLength>;
// Create AoSoAs.
int num_data = 357;
DstAoSoA_t dst_aosoa( num_data );
SrcAoSoA_t src_aosoa( num_data );
// Initialize data with the rank accessors.
float fval = 3.4;
double dval = 1.23;
int ival = 1;
auto slice_0 = src_aosoa.template slice<0>();
auto slice_1 = src_aosoa.template slice<1>();
auto slice_2 = src_aosoa.template slice<2>();
auto slice_3 = src_aosoa.template slice<3>();
for ( std::size_t idx = 0; idx < src_aosoa.size(); ++idx )
{
// Member 0.
for ( int i = 0; i < dim_1; ++i )
for ( int j = 0; j < dim_2; ++j )
for ( int k = 0; k < dim_3; ++k )
slice_0( idx, i, j, k ) = fval * (i+j+k);
// Member 1.
slice_1( idx ) = ival;
// Member 2.
for ( int i = 0; i < dim_1; ++i )
slice_2( idx, i ) = dval * i;
// Member 3.
for ( int i = 0; i < dim_1; ++i )
for ( int j = 0; j < dim_2; ++j )
slice_3( idx, i, j ) = dval * (i+j);
}
// Deep copy
Cabana::deep_copy( dst_aosoa, src_aosoa );
// Check values.
checkDataMembers( dst_aosoa, fval, dval, ival, dim_1, dim_2, dim_3 );
}
//---------------------------------------------------------------------------//
// TESTS
//---------------------------------------------------------------------------//
TEST_F( TEST_CATEGORY, deep_copy_to_host_same_layout_test )
{
testDeepCopy<Cabana::HostSpace,TEST_MEMSPACE,16,16>();
}
//---------------------------------------------------------------------------//
TEST_F( TEST_CATEGORY, deep_copy_from_host_same_layout_test )
{
testDeepCopy<TEST_MEMSPACE,Cabana::HostSpace,16,16>();
}
//---------------------------------------------------------------------------//
TEST_F( TEST_CATEGORY, deep_copy_to_host_different_layout_test )
{
testDeepCopy<Cabana::HostSpace,TEST_MEMSPACE,16,32>();
testDeepCopy<Cabana::HostSpace,TEST_MEMSPACE,64,8>();
}
//---------------------------------------------------------------------------//
TEST_F( TEST_CATEGORY, deep_copy_from_host_different_layout_test )
{
testDeepCopy<TEST_MEMSPACE,Cabana::HostSpace,64,8>();
testDeepCopy<TEST_MEMSPACE,Cabana::HostSpace,16,32>();
}
//---------------------------------------------------------------------------//
} // end namespace Test
| [
"[email protected]"
] | |
483636595ef27a032fb65294e55c02e76cef77eb | 89421a99baeeb9a368104340ad4efa5f68e2268b | /cpp/Fem1d/Fem1d.cpp | 1795d3ce24e60bc2e100e31feb3145252abc3cbc | [] | no_license | mtsodf/ppgi_elem | c16c510c3f78c1e0eb363a36178f79be60818c0a | 910155619cb94423eb47dfe793f64be01e750c5a | refs/heads/master | 2021-09-06T07:20:18.995000 | 2018-02-03T18:24:21 | 2018-02-03T18:24:21 | 105,206,139 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,068 | cpp | #include "Fem1d.h"
#include "../definitions.h"
#include <stdlib.h>
#include "../LinearAlgebra/Jacobi.h"
#include "../LinearAlgebra/Operations.h"
#include <cmath>
#include "../Utils/Utils.h"
using namespace std;
class UndefinedFuncForm: public exception
{
virtual const char* what() const throw()
{
return "Undefined func form";
}
};
real FuncForm(real qsi, char func){
if(func == 0) return (1.0 - qsi)/2.0;
if(func == 1) return (1.0 + qsi)/2.0;
UndefinedFuncForm ex;
throw ex;
}
real DFuncForm(real qsi, char func){
if(func == 0) return -1.0/2.0;
if(func == 1) return 1.0/2.0;
UndefinedFuncForm ex;
throw ex;
}
void LocalMatrix(real alpha, real beta, real he, real* lm){
real w;
w = sqrt(3.0)/3.0;
for (size_t i = 0; i < 2; i++)
{
for (size_t j = 0; j < 2; j++)
{
lm[2*i+j] = (he/2)*beta*(FuncForm(-w,i)*FuncForm(-w,j)) + (2/he)*alpha*(DFuncForm(-w,i)*DFuncForm(-w,j));
lm[2*i+j] += (he/2)*beta*(FuncForm( w,i)*FuncForm( w,j)) + (2/he)*alpha*(DFuncForm( w,i)*DFuncForm( w,j));
}
}
}
void GlobalMatrix(int n, real alpha, real beta, real *K, int boundary){
real * hs;
real h = 1.0/n;
hs = (real*) malloc(sizeof(real)*n);
for (size_t i = 0; i < n; i++)
{
hs[i] = h;
}
GlobalMatrix(n, alpha, beta, hs, K, boundary);
}
void GlobalMatrix(int n, real alpha, real beta, real* hs, real *K, int boundary){
real lm[4];
int ndofs = n + 1;
for (size_t i = 0; i < n; i++)
{
LocalMatrix(alpha, beta, hs[i], lm);
K[DIM(i,i,ndofs)] += lm[0];
K[DIM(i,i+1,ndofs)] += lm[1];
K[DIM(i+1,i,ndofs)] += lm[2];
K[DIM(i+1,i+1,ndofs)] += lm[3];
}
if(boundary == DIRICHLET || boundary == DIRICHLET_NEUMANN){
K[DIM(0,0,ndofs)] = 1.0;
K[DIM(0,1,ndofs)] = 0.0;
K[DIM(1,0,ndofs)] = 0.0;
}
if(boundary == DIRICHLET || boundary == NEUMANN_DIRICHLET){
K[DIM(ndofs-1,ndofs-2,ndofs)] = 0.0;
K[DIM(ndofs-2,ndofs-1,ndofs)] = 0.0;
K[DIM(ndofs-1,ndofs-1,ndofs)] = 1.0;
}
}
void RhsLocal(real he, real f1, real f2, real *Fe){
real w = sqrt(3)/3.0;
Fe[0] = f1*(he/2)*(FuncForm(-w,0) * FuncForm(-w,0) + FuncForm(w,0) * FuncForm(w,0));
Fe[0] += f2*(he/2)*(FuncForm(-w,0) * FuncForm(-w,1) + FuncForm(w,0) * FuncForm(w,1));
Fe[1] = f1*(he/2)*(FuncForm(-w,1) * FuncForm(-w,0) + FuncForm(w,1) * FuncForm(w,0));
Fe[1] += f2*(he/2)*(FuncForm(-w,1) * FuncForm(-w,1) + FuncForm(w,1) * FuncForm(w,1));
}
void RhsGlobal(int n, real h, real *fs, real *F, real p, real q, real alpha, real beta, int boundary){
real *hs = (real*) malloc(n*sizeof(real));
for (size_t i = 0; i < n; i++)
{
hs[i] = h;
}
RhsGlobal(n, hs, fs, F, p, q, alpha, beta, boundary);
free(hs);
}
void RhsGlobal(int n, real *hs, real *fs, real *F, real p, real q, real alpha, real beta, int boundary){
int ndofs = n + 1;
for (size_t i = 0; i < ndofs; i++)
{
F[i] = 0.0;
}
real Fe[2];
for (size_t i = 0; i < n; i++)
{
RhsLocal(hs[i], fs[i], fs[i+1], Fe);
F[i] += Fe[0];
F[i+1] += Fe[1];
}
if(boundary == DIRICHLET || boundary == DIRICHLET_NEUMANN){
F[0] = p;
real w = sqrt(3)/3.0; real he = hs[0];
F[1] -= p*((he/2)*beta*(FuncForm(-w,0)*FuncForm(-w,1)) + (2/he)*alpha*(DFuncForm(-w,0)*DFuncForm(-w,1)));
F[1] -= p*((he/2)*beta*(FuncForm( w,0)*FuncForm( w,1)) + (2/he)*alpha*(DFuncForm( w,0)*DFuncForm( w,1)));
}
if(boundary == DIRICHLET || boundary == NEUMANN_DIRICHLET){
real w = sqrt(3)/3.0; real he = hs[n-1];
F[ndofs - 1] = q;
F[ndofs-2] -= q*((he/2)*beta*(FuncForm(-w,0)*FuncForm(-w,1)) + (2/he)*alpha*(DFuncForm(-w,0)*DFuncForm(-w,1)));
F[ndofs-2] -= q*((he/2)*beta*(FuncForm( w,0)*FuncForm( w,1)) + (2/he)*alpha*(DFuncForm( w,0)*DFuncForm( w,1)));
}
if(boundary == NEUMANN || boundary == NEUMANN_DIRICHLET){
F[0] -= alpha*p;
}
if(boundary == NEUMANN || boundary == DIRICHLET_NEUMANN){
F[ndofs-1] += alpha*q;
}
}
extern "C"{
real * Fem1dTest(int n, int entrada){
real *x, *F, *fs, *sol;
real *K;
real alpha, beta, p, q;
int boundary;
int unknowns = n + 1;
real h = 1.0/n;
zero(unknowns, &x);
zero(unknowns, &F);
zero(unknowns, &fs);
zero(unknowns, &sol);
zero(unknowns*unknowns, &K);
x[0] = 0.0;
for (size_t i = 1; i < unknowns; i++)
{
x[i] = x[i-1] + h;
}
/*
######################################################################
# Selecao da entrada
######################################################################
*/
for (size_t i = 0; i < unknowns; i++)
{
switch (entrada)
{
case 0:
alpha = 1.0;
beta = 1.0;
fs[i] = 4*M_PI*M_PI*sin(2*M_PI*x[i]) + sin(2*M_PI*x[i]);
sol[i] = sin(2*M_PI*x[i]);
boundary = DIRICHLET;
p = 0.0;
q = 0.0;
break;
case 1:
alpha = 1.0;
beta = 0.0;
fs[i] = 2*alpha;
boundary = DIRICHLET;
p = 0.0;
q = 0.0;
break;
case 2:
alpha = 1.0;
beta = 0.5;
boundary = DIRICHLET;
fs[i] = 0.5*x[i];
p = 0.0;
q = 1.0;
break;
case 3:
alpha = 0.0;
beta = 1.0;
boundary = DIRICHLET;
fs[i] = beta*x[i]*(1-x[i]);
p = 0.0;
q = 0.0;
break;
case 4:
alpha = 2.0;
beta = 1.0;
boundary = DIRICHLET;
fs[i] = -7*exp(2*x[i]);
p = 1.0;
q = exp(2.0);
break;
case 5:
alpha = 2.0;
beta = 1.0;
boundary = NEUMANN;
fs[i] = -7*exp(2*x[i]);
p = 2.0;
q = 2*exp(2.0);
break;
case 6:
alpha = 2.0;
beta = 1.0;
boundary = NEUMANN_DIRICHLET;
fs[i] = -7*exp(2*x[i]);
p = 2.0;
q = exp(2.0);
break;
case 7:
alpha = 2.0;
beta = 1.0;
boundary = DIRICHLET_NEUMANN;
fs[i] = -7*exp(2*x[i]);
p = 1.0;
q = 2*exp(2.0);
break;
case 8:
alpha = 1.0;
beta = 1.0;
boundary = NEUMANN;
fs[i] = 4*M_PI*M_PI*sin(2*M_PI*x[i]) + sin(2*M_PI*x[i]);
p = 2*M_PI;
q = 2*M_PI;
break;
default:
break;
}
}
/*
######################################################################
# Criando Matriz Global
######################################################################
*/
GlobalMatrix(n, alpha, beta, K, boundary);
/*
######################################################################
# Criando Lado Direito
######################################################################
*/
RhsGlobal(n, h, fs, F, p, q, alpha, beta, boundary);
/*
######################################################################
# Solucao do Sistema Linear
######################################################################
*/
real * calc;
zero(unknowns, &calc);
cg(unknowns, K, F, calc);
free(x);
free(F);
free(fs);
free(sol);
free(K);
return calc;
}
}
| [
"[email protected]"
] | |
e583e7116773107273d5fb8024b730ef48f23333 | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/pdfium/xfa/fxfa/parser/cxfa_solid.cpp | da8de3f6aca0fae9e6ba41523e382edcb9d6be21 | [
"BSD-3-Clause",
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844000 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 1,216 | cpp | // Copyright 2017 The PDFium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "xfa/fxfa/parser/cxfa_solid.h"
#include "fxjs/xfa/cjx_node.h"
#include "xfa/fxfa/parser/cxfa_document.h"
namespace {
const CXFA_Node::PropertyData kSolidPropertyData[] = {
{XFA_Element::Extras, 1, {}},
};
const CXFA_Node::AttributeData kSolidAttributeData[] = {
{XFA_Attribute::Id, XFA_AttributeType::CData, nullptr},
{XFA_Attribute::Use, XFA_AttributeType::CData, nullptr},
{XFA_Attribute::Usehref, XFA_AttributeType::CData, nullptr},
};
} // namespace
CXFA_Solid::CXFA_Solid(CXFA_Document* doc, XFA_PacketType packet)
: CXFA_Node(doc,
packet,
{XFA_XDPPACKET::kTemplate, XFA_XDPPACKET::kForm},
XFA_ObjectType::Node,
XFA_Element::Solid,
kSolidPropertyData,
kSolidAttributeData,
cppgc::MakeGarbageCollected<CJX_Node>(
doc->GetHeap()->GetAllocationHandle(),
this)) {}
CXFA_Solid::~CXFA_Solid() = default;
| [
"[email protected]"
] | |
efee5b91d30e90f44f56ca962bc4d6b383191c2d | e86c079391367e0e401482eb43a850685ac54056 | /ex05/Human.cpp | f99f1bbfa2e2506c59f393e4c073e71ef72e65d8 | [] | no_license | atronk/cpp-01 | c85155abd9cf83b5de370ed1c033ba831f4207b8 | 533a01c039235b436d461df8169169d70c8b97b9 | refs/heads/master | 2023-05-25T17:51:51.451000 | 2021-05-22T17:14:38 | 2021-05-22T17:14:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 312 | cpp | #include "Human.hpp"
Human::Human() {
std::cout << "A Human is created!" << std::endl;
}
Human::~Human() {
std::cout << "A Human is destroyed" << std::endl;
}
const Brain& Human::getBrain() const {
return (this->_brain);
}
const std::string& Human::identify() const {
return(this->getBrain().identify());
} | [
"[email protected]"
] | |
80e9638e9a9955c45831c86dc3497224eea00c9c | 4f2f4ca1cb010ab79ad3933e73dce6671f012054 | /SK-Lib/test_sk_header.cpp | 2491fbed63d9441372bd23eb682d72c41f371115 | [] | no_license | sksavigit/CPP-Progs | f95cfbea5a3caa40baca8637d55e9c1d5a000670 | 178a414d3c424a18cfe8cf6f9c3df697dffe2993 | refs/heads/master | 2023-02-17T15:01:02.283000 | 2021-01-16T13:09:01 | 2021-01-16T13:09:01 | 328,104,206 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 485 | cpp | #include<iostream>
#include "sklib_numbers.h"
#include "sklib_iostream.h"
using namespace std;
int main(){
char n1[]="0000000000000000000000000001";
char n2[]="1111123424324243234234234324";
cout << "\n Num1:" <<n1;
cout << "\n Num2:" <<n2;
cout << "\n Outp:";
int n1Size=sizeof(n1)/sizeof(n1[0]);
int n2Size=sizeof(n2)/sizeof(n2[0]);
char res[n1Size>n2Size ? n1Size:n2Size];
sum_two_big_numbers(n1,n2,res);
cout << res<< "\n";
return 0;
}
| [
"[email protected]"
] | |
f387d41d0e3251ca4e290372f77e819aa8f41c08 | 8c8ea797b0821400c3176add36dd59f866b8ac3d | /AOJ/aoj0578.cpp | 9b35642e4fd0541224a11ccbbf275376f137bc2c | [] | no_license | fushime2/competitive | d3d6d8e095842a97d4cad9ca1246ee120d21789f | b2a0f5957d8ae758330f5450306b629006651ad5 | refs/heads/master | 2021-01-21T16:00:57.337000 | 2017-05-20T06:45:46 | 2017-05-20T06:45:46 | 78,257,409 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 682 | cpp | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
using namespace std;
int N;
bool isName(string shop, string board) {
int m = board.length();
for(int step=1; step<=m; step++) {
for(int i=0; i<m; i++) {
string s = "";
for(int j=i; j<m; j+=step) {
s += board[j];
}
if(s.find(shop) != string::npos) return true;
}
}
return false;
}
int main(void) {
cin >> N;
string shop, board;
cin >> shop;
int ans = 0;
for(int i=0; i<N; i++) {
cin >> board;
if(isName(shop, board)) ans++;
}
cout << ans << endl;
return 0;
}
| [
"[email protected]"
] | |
8bfe178d65efb2f52470e306b87737b39f700ce6 | f80d267d410b784458e61e4c4603605de368de9b | /TESTONE/exampleios/usr/local/include/fit_developer_field_description.hpp | a5af5c51d16055664f81433af69b821385dd83c5 | [] | no_license | bleeckerj/Xcode-FIT-TEST | 84bdb9e1969a93a6380a9c64dce0a0e715d81fe8 | 37490e3b1e913dc3dfabdae39b48bddea24f1023 | refs/heads/master | 2021-01-20T14:39:53.249000 | 2017-02-22T05:59:28 | 2017-02-22T05:59:28 | 82,766,547 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,772 | hpp | ////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2017 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 20.24Release
// Tag = production/akw/20.24.01-0-g5fa480b
////////////////////////////////////////////////////////////////////////////////
#if !defined(FIT_DEVELOPER_FIELD_DESCRIPTION_HPP)
#define FIT_DEVELOPER_FIELD_DESCRIPTION_HPP
#include "fit_field_description_mesg.hpp"
#include "fit_developer_data_id_mesg.hpp"
#include <vector>
namespace fit
{
class DeveloperFieldDescription
{
public:
DeveloperFieldDescription() = delete;
DeveloperFieldDescription(const DeveloperFieldDescription& other);
DeveloperFieldDescription(const FieldDescriptionMesg& desc, const DeveloperDataIdMesg& developer);
virtual ~DeveloperFieldDescription();
FIT_UINT32 GetApplicationVersion() const;
FIT_UINT8 GetFieldDefinitionNumber() const;
std::vector<FIT_UINT8> GetApplicationId() const;
private:
FieldDescriptionMesg* description;
DeveloperDataIdMesg* developer;
};
} // namespace fit
#endif // defined(FIT_FIELD_DEFINITION_HPP)
| [
"[email protected]"
] | |
a0a7716d5870fb0a5b552fb6115b6e7b7937b018 | c22dbf8b58f205c5b748eeff49dfaf04e3a40f39 | /Cantera/clib/src/Storage.cpp | d5462bccbfad490f8de02daa46dd5a4a7f8d90af | [] | no_license | VishalKandala/Cantera1.8-Radcal | ee9fc49ae18ffb406be6cf6854daf2427e29c9ab | 1d7c90244e80185910c88fdf247193ad3a1745f3 | refs/heads/main | 2023-01-20T17:07:23.385000 | 2020-11-29T05:50:51 | 2020-11-29T05:50:51 | 301,748,576 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,004 | cpp | /**
* @file Storage.cpp
*/
/*
* $Id: Storage.cpp,v 1.6 2009/07/11 17:16:09 hkmoffa Exp $
*/
// Cantera includes
#include "Kinetics.h"
#include "TransportFactory.h"
#include "Storage.h"
using namespace std;
using namespace Cantera;
Storage::Storage() {
addThermo(new ThermoPhase);
addKinetics(new Kinetics);
addTransport(newTransportMgr());
}
Storage::~Storage() { clear(); }
int Storage::addThermo(thermo_t* th) {
if (th->index() >= 0)
return th->index();
__thtable.push_back(th);
int n = static_cast<int>(__thtable.size()) - 1;
th->setIndex(n);
//string id = th->id();
//if (__thmap.count(id) == 0) {
// __thmap[id] = n;
// th->setID(id);
//}
//else {
// throw CanteraError("Storage::addThermo","id already used");
// return -1;
//}
return n;
}
int Storage::nThermo() {
return static_cast<int>(__thtable.size());
}
int Storage::addKinetics(Kinetics* kin) {
if (kin->index() >= 0)
return kin->index();
__ktable.push_back(kin);
int n = static_cast<int>(__ktable.size()) - 1;
kin->setIndex(n);
return n;
}
int Storage::addTransport(Transport* tr) {
if (tr->index() >= 0)
return tr->index();
__trtable.push_back(tr);
int n = static_cast<int>(__trtable.size()) - 1;
tr->setIndex(n);
return n;
}
// int Storage::addNewTransport(int model, char* dbase, int th,
// int loglevel) {
// try {
// ThermoPhase* thrm = __thtable[th];
// Transport* tr = newTransportMgr(model,
// string(dbase), thrm, loglevel);
// __trtable.push_back(tr);
// return __trtable.size() - 1;
// }
// catch (CanteraError) {return -1;}
// catch (...) {return ERR;}
// }
int Storage::clear() {
int i, n;
n = static_cast<int>(__thtable.size());
for (i = 1; i < n; i++) {
if (__thtable[i] != __thtable[0]) {
delete __thtable[i];
__thtable[i] = __thtable[0];
}
}
n = static_cast<int>(__ktable.size());
for (i = 1; i < n; i++) {
if (__ktable[i] != __ktable[0]) {
delete __ktable[i];
__ktable[i] = __ktable[0];
}
}
n = static_cast<int>(__trtable.size());
for (i = 1; i < n; i++) {
if (__trtable[i] != __trtable[0]) {
delete __trtable[i];
__trtable[i] = __trtable[0];
}
}
return 0;
}
void Storage::deleteKinetics(int n) {
if (n == 0) return;
if (__ktable[n] != __ktable[0])
delete __ktable[n];
__ktable[n] = __ktable[0];
}
void Storage::deleteThermo(int n) {
if (n == 0) return;
if (n < 0 || n >= (int) __thtable.size())
throw CanteraError("deleteThermo","illegal index");
__thtable[n] = __thtable[0];
}
void Storage::deleteTransport(int n) {
if (n == 0) return;
if (__trtable[n] != __trtable[0])
delete __trtable[n];
__trtable[n] = __trtable[0];
}
Storage* Storage::__storage = 0;
| [
"[email protected]"
] | |
83881de53e405fca71ff23806072066608fcd793 | 4dd6c13f3fc50d0d0ff84ba3d442eee2d3dae742 | /Engine/Managers/EventManager.cpp | b7d2c47d7e90411950603f29a5718646637d73c3 | [] | no_license | Marcos30004347/AzgardEngine | 570773ad3c3f99628708ff06e4f0674dab0b8977 | ee5f4e3de1b8bcefdab01b0b71e3d4fcca86b4e3 | refs/heads/master | 2022-12-08T17:06:06.632000 | 2020-08-29T01:44:12 | 2020-08-29T01:44:12 | 289,409,420 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,180 | cpp | #include<iostream>
#include<assert.h>
#include "EventManager.hpp"
#include "definitions.hpp"
#ifdef SDL2_IMP
#include <SDL2/SDL.h>
SDL_Event sdl2_event;
#endif
EventManager* EventManager::gInstance = nullptr;
EventManager::EventManager() {}
EventManager::~EventManager() {}
EventManager* EventManager::GetSingletonPtr(void) {
assert(EventManager::gInstance);
return EventManager::gInstance;
}
EventManager& EventManager::GetSingleton(void) {
assert(EventManager::gInstance);
return *EventManager::gInstance;
}
void EventManager::StartUp() {
std::cout << "starting up event manager" << std::endl;
EventManager::gInstance = new EventManager();
}
void EventManager::ShutDown() {
std::cout << "shuting down event manager" << std::endl;
delete EventManager::gInstance;
}
bool EventManager::Pool(Event *event) {
#ifdef SDL2_IMP
int pedding = SDL_PollEvent(&sdl2_event);
switch (sdl2_event.type)
{
case SDL_QUIT:
event->type = QUIT_EVENT;
break;
default:
event->type = NULL_EVENT;
break;
}
#else
#error IMPLEMENTATION NOT DEFINED
#endif
return pedding;
} | [
"[email protected]"
] | |
849e17e440d0e9523fb0dd1a5f7f9d2bf5e1f416 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5686313294495744_0/C++/vidhan13j07/test.cpp | 5edfd10037fb916f2f5fbdef7cf9305b0b29d5b9 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417000 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,489 | cpp | #include<bits/stdc++.h>
#define sc(v) v.size()
#define eb push_back
#define pb pop_back
#define f(i,a,b) for(int i=a;i<b;i++)
#define TC() int t;cin>>t;while(t--)
#define all(x) x.begin(),x.end()
#define mk make_pair
#define fi first
#define se second
#define endl "\n"
#define eps 1e-9
#define pw(x) (1ll<<(x))
#define trace1(x) cout <<#x<<": "<<x<<endl;
#define trace2(x, y) cout <<#x<<": "<<x<<" | "<<#y<<": "<<y<< endl;
#define trace3(x, y, z) cout <<#x<<": "<<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<endl;
#define trace4(a, b, c, d) cout <<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<endl;
#define trace5(a, b, c, d, e) cout <<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<<": "<<e<<endl;
using namespace std;
typedef long long int ll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<string,string> pi;
typedef pair<ll,ll> pll;
inline bool EQ(double a,double b) { return fabs(a - b) < 1e-9; }
inline void set_bit(int & n, int b) { n |= pw(b); }
inline void unset_bit(int & n, int b) { n &= ~pw(b); }
int main()
{
#ifndef ONLINE_JUDGE
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
#endif
clock_t tStart = clock();
int tc = 1;
int n;
map< pi,int > mp;
vector< pi > v;
set< pi > vv;
vector<string> f,rr;
string x,y;
set<string> a,b;
TC()
{
printf("Case #%d: ", tc++);
mp.clear();
v.clear();
a.clear();
b.clear();
scanf("%d",&n);
f(i,0,n)
{
cin>>x>>y;
v.eb(mk(x,y));
mp[mk(x,y)] = 1;
}
int ans = 0;
f(i,0,1 << n)
{
f.clear();
rr.clear();
vv.clear();
int c = 0;
f(j,0,n)
if(i&(1 << j))
{
f.eb(v[j].fi);
rr.eb(v[j].se);
vv.insert(v[j]);
}
f(j,0,sc(f))
f(k,0,sc(rr))
{
if(vv.find(mk(f[j],rr[k])) != vv.end())
continue;
if(mp[mk(f[j],rr[k])])
c++;
}
ans = max(ans,c);
}
printf("%d\n",ans);
}
//printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
return 0;
}
| [
"[email protected]"
] | |
8b494503d9bf74ff5d28e840affc467e8a440a51 | 34a3165ded55c6ac5ffe2ff17c9996c66e0e80b5 | /cpp/ETProtect.cpp | 989ebb94e3100accc0e0e0fd02bff4f34144df29 | [] | no_license | monkeyde17/et-protect-package | d806a3196c28c4176374bc21e7ec5769faa72347 | 77e04d1834d0723c2de7f424a1cbc1efd2321991 | refs/heads/master | 2016-09-06T05:53:58.824000 | 2014-12-07T02:29:37 | 2014-12-07T02:29:37 | 27,655,865 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,888 | cpp | //
// ETProtect.cpp
// testcpp
//
// Created by etond on 14/12/3.
//
//
#include "ETProtect.h"
bool ETProtect::isOriginPackage()
{
unsigned int uHashValue = calculateValueFromFile();
unsigned int uReadValue = readValueFromFile();
#if (ETPROTECTDEBUG)
CCLOG("[log] -- hash %u", uHashValue);
CCLOG("[log] -- read %u", uReadValue);
#endif
if (uReadValue == 0 || uHashValue == 0)
{
return false;
}
return uReadValue == uHashValue;
}
unsigned int ETProtect::readValueFromFile(std::string filename /* default = config.et */)
{
unsigned int uValue = 0;
Data data = FileUtils::getInstance()->getDataFromFile(filename);
if (data.getSize() > 0)
{
uValue = ((ETProtectData *)data.getBytes())->getHashValue();
}
return uValue;
}
unsigned int ETProtect::calculateValueFromFile(unsigned int seed /* default = 0x12345678 */)
{
std::string path = "";
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
JniMethodInfo minfo;
bool isHave = JniHelper::getStaticMethodInfo(minfo,
"org/cocos2dx/cpp/AppActivity",
"getPath",
"()Ljava/lang/String;");
if (isHave)
{
jobject jobj = minfo.env->CallStaticObjectMethod(minfo.classID, minfo.methodID);
/* get the return value */
path = JniHelper::jstring2string((jstring)jobj).c_str();
CCLOG("JNI SUCCESS!");
}
#endif
unsigned int value = 0;
if (path.length() > 0)
{
ssize_t len = 0;
unsigned char *buf = FileUtils::getInstance()->getFileDataFromZip(path, "classes.dex", &len);
if (buf)
{
value = XXH32(buf, len, seed);
}
delete[] buf;
}
return value;
}
| [
"[email protected]"
] | |
77e95d74adb0d91068d318a9f567bd723eb4bd30 | 8a970882a0be9f3d85edbf6ecec0050b762e8d80 | /GazEngine/gazengine/Entity.h | ded187d2149547f453fc7c141f5bfa9b3cc59aa9 | [] | no_license | simplegsb/gazengine | 472d1de8d300c8406ffec148844911fd21d5c1e0 | b0a7300aa535b14494789fb88c16d6dda1c4e622 | refs/heads/master | 2016-09-05T21:02:49.531000 | 2013-04-29T08:33:16 | 2013-04-29T08:33:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,553 | h | #ifndef ENTITY_H_
#define ENTITY_H_
#include <memory>
#include <string>
#include <vector>
class Component;
class Entity
{
public:
static const unsigned short UNCATEGORIZED = 0;
Entity(unsigned short category = UNCATEGORIZED, const std::string& name = std::string());
virtual ~Entity();
/**
* <p>
* Adds a component.
* </p>
*
* @param component The component to add.
*/
void addComponent(Component* component);
unsigned short getCategory() const;
/**
* <p>
* Retrieves the components.
* </p>
*
* @return The components.
*/
template<typename ComponentType>
std::vector<ComponentType*> getComponents() const;
unsigned int getId() const;
/**
* <p>
* Retrieves the name of this <code>Entity</code>.
* </p>
*
* @return The name of this <code>Entity</code>.
*/
const std::string& getName() const;
/**
* <p>
* Retrieves a single component.
* </p>
*
* @return The single component.
*/
template<typename ComponentType>
ComponentType* getSingleComponent() const;
/**
* <p>
* Removes a component.
* </p>
*
* @param component The component to remove.
*/
void removeComponent(const Component& component);
private:
unsigned short category;
/**
* <p>
* The components.
* </p>
*/
std::vector<Component*> components;
unsigned int id;
/**
* <p>
* The name of this <code>Entity</code>.
* </p>
*/
std::string name;
static unsigned int nextId;
};
#include "Entity.tpp"
#endif /* ENTITY_H_ */
| [
"[email protected]"
] | |
41411ede81a3f14d5f5efda3aad396093d6910f8 | 16337b0d88df96767281cbc0024ed4e5e0dc2309 | /Tic-Tac-bigToe.cpp | ccd6f979a725f324386a94cc966771516cbbf2ac | [] | no_license | Xephoney/Tic-Tac-bigToe | 8c3c5d93a5f49799d90034a428a61d509b672883 | 3ea53e4f72486c476eb673a8f1736b24f3f5442c | refs/heads/master | 2022-12-24T15:47:03.404000 | 2020-09-27T19:22:51 | 2020-09-27T19:22:51 | 298,370,665 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 12,368 | cpp | #include <iostream>
#include <string>
#include <vector> //This is included for the use of vectors
#include <time.h> //This is for random number generation
//Here we declare the functions that i will define further down.
//these functions are tied to the gameplay loop
void DisplayGrid();
void InputAndExec();
void PlayerSwitch();
int WinConditionCheck();
void CalculateComputerMove(char);
//These are the main functions between games.
void GamePvP();
void GamePvE();
void MainMenu();
//The reason i went with global variables was to limit the amount of calls, and passing variables to functions and getting...
//the right return variables. Only the important variables are global.
std::vector<char> grid { '1','2','3','4','5','6','7','8','9' };
char players[2] { 'X', 'O' };
int playerIndex = 1;
int main()
{
srand(time(NULL));
//Greeting when first running the application
std::cout << "Welcome to Tic-Tac-(Big)Toe \n";
MainMenu();
return 0;
}
void MainMenu()
{
int answer = NULL;
std::cout << "What would you like to play? \n";
std::cout << " 1 : Player VS Player \n" << " 2 : Player VS CPU \n \n" << " 8 : Exit Game \n";
std::cout << "Select a gamemode : ";
std::cin >> answer;
//here we do the corresponding code execution based on what the user typed in.
// I wanted to avoid using a while loop here, because of the thought that it would be a loop, in a loop, in a loop... for ever.
// So instead i just kept to Functions executions.
// I don't know for sure whether this is the best solution or not, but it works! :D
//Here i get then input from the player and execute the right code that was selected from the player.
switch (answer)
{
case 0:
//I have to include cin.clear and cin.ignore before calling MainMenu() again, to stop it from looping forever.
system("CLS");
std::cin.clear();
std::cin.ignore(10000, '\n');
MainMenu();
break;
case 1:
system("CLS");
GamePvP();
break;
case 2:
system("CLS");
GamePvE();
break;
case 8:
std::cout << "Closing Game";
return;
default:
//I have to include cin.clear and cin.ignore before calling MainMenu() again, to stop it from looping forever.
system("CLS");
std::cin.clear();
std::cin.ignore(10000, '\n');
MainMenu();
break;
}
}
int moves = 0;
void GamePvP()
{
playerIndex = 0;
bool GameOver = false;
moves = 0;
//The reason why i fill out the grid here, is because everytime the game restarts...
//I need to make sure its a new grid. so it clears the board from the last game.
grid = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
do
{
//as the functions says it displays the grid.
DisplayGrid();
//This is for getting input, aswell as
InputAndExec();
//Here i run the Win Condition function and store the result of that test in my X variable.
//Then we proceed to check weather that the winner was either X or O.
int x = WinConditionCheck();
if (x == 0 || x == 1)
{
//The reason for Display Grid is just to update the display so you could see where the
//Where the winning connections were!
DisplayGrid();
std::cout << "\nPlayer " << players[x] << " wins! Congrats! \n";
GameOver = true;
system("pause");
}
//I keep a count of the total amount of moves. and if the total number of moves is 9, and wincheck returns false. then it has to be a tie.
else if (moves == 9)
{
//Tie
DisplayGrid();
std::cout << "\n [- TIE -] \n";
GameOver = true;
system("pause");
}
} while (!GameOver);
//Clears screen and returns to Main Menu
system("CLS");
MainMenu();
}
void GamePvE()
{
playerIndex = 0;
bool GameOver = false;
moves = 0;
grid = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char answer = 'æ';
int computer = -1;
int player = -1;
std::cout << "Do you want to be X or O? \n ";
std::cout << "X / O : ";
std::cin >> answer;
answer = toupper(answer);
//This is just to make sure that the input is a Char value.
//Initial game setup. The player selects their desigered and the cpu gets
if (answer == players[0])
{
computer = 1;
player = 0;
std::cout << "Okay, You = X CPU = O \n When you are ready ";
}
else if (answer == players[1])
{
computer = 0;
player = 1;
std::cout << "Okay, CPU = X You = O \n When you are ready ";
}
else //This is just to remove the possibility of a rogue exec without the right variables.
{
std::cin.clear();
std::cin.ignore(10000, '\n');
GamePvE();
return;
}
system("pause");
//This do-while loop goes aslong as GameOver is false.
do
{
DisplayGrid();
if (playerIndex == computer)
{
//this just ends up passing through what character the computer has.
//So it can do the right placement in the grid.
CalculateComputerMove(players[computer]);
}
else
{
InputAndExec();
}
//This is the section of the gameloop that checks for wins or if the game is a tie.
int x = WinConditionCheck();
if (x == computer)
{
//The reason for Display Grid is just to update the display so you could see where the
//Where the winning connections were!
DisplayGrid();
std::cout << "\n [- CPU WON -] ";
GameOver = true;
system("pause");
}
else if (x == player)
{
DisplayGrid();
std::cout << "\n [- YOU WON -] ";
GameOver = true;
system("pause");
}
else if (moves == 9)
{
DisplayGrid();
std::cout << "\n [- TIE -] \n";
GameOver = true;
system("pause");
}
} while (!GameOver);
system("CLS");
MainMenu();
}
//Game Loop functions
void DisplayGrid()
{
system("CLS");
for (auto x = 0; x < grid.size(); x++)
{
std::cout << "| " << grid.at(x) << " ";
if (x == 2 || x == 5 || x == 8)
{
std::cout << "|" << std::endl;
}
}
}
void InputAndExec()
{
//The reason for this being a long long int, is because i kept getting build errors because i was doing a arithmetic overflow warning
//So i then "upgraded" to this to remove that error.
long long int playerInput = 0;
std::cout << "[" << players[playerIndex] << "] turn : ";
//Gets input from console and store the answer in the playerInput variable
std::cin >> playerInput;
if (playerInput-1 <= 8 && playerInput-1 >= 0)
{
if (grid.at(playerInput-1) == 'X' || grid.at(playerInput-1) == 'O')
{
std::cout << "Invalid selection, you cannot select a place that has already been taken! \n";
InputAndExec();
return;
}
else
{
grid[playerInput-1] = players[playerIndex];
moves++;
PlayerSwitch();
return;
}
}
else // This else is to catch any input that isn't an integer. then repeat.
{
std::cin.clear();
std::cin.ignore(10000, '\n');
std::cout << "Invalid input! Choose a number from the grid above! \n";
}
}
int WinConditionCheck()
{
//Here im just creating a variable that checks for winner, and then returns the player index number...
//which corresponds with a char in players[].
char winner = 'Ø';
char a, b, c;
//Horizontal
for (long int i = 1; i <= 7; i+=3)
{
// These variables are temp just for storing values so the if statement further down stays relativly clean and easy to debug.
a = grid.at(i);
b = grid.at(i-1);
c = grid.at(i+1);
//What these variables check store is what is in the grid at the spesific point. They only hold that info based on the current iteration.
//This if statement then checks weather or not they are all the same, it doesn't matter if its X or O. Aslong as all of them are the same...
//it then continues to the next check
if (a == b && b == c)
{
//Here we grab the character value of the winning row, then we do a check as to who won. then return a int value.
//This int value that is returned, corresponds with the index of the players[], where X = 0, and O = 1.
winner = grid.at(i);
if (winner == 'X')
{
return 0;
}
else
{
return 1;
}
}
}
//Vertical win check
for (long int i = 0; i < 3; i++)
{
//Here i grab a the current iterator and add the required grid locations to make a check.
//im just using a, b and c because it really doesn't require to be that spesific. These are temp variables that...
//have a single purpose, which is to check weather or not they are the same.
a = grid.at(i);
b = grid.at(i + 3);
c = grid.at(i + 6);
//This if statement just checks that all the temp variables are the same, and by that we can determine that we have a winner.
//Since the temp varibles are set to check the one beneath another, this then checks the colum for a win condition.
if (a == b && b == c)
{
//Here we grab the character value of the winning row, then we do a check as to who won. then return a int value.
//This int value that is returned, corresponds with the index of the players[], where X = 0, and O = 1.
winner = grid.at(i);
if (winner == 'X')
{
return 0;
}
else
{
return 1;
}
}
}
//For the diagonal checks, all i have to do, since there are only two options. i will hardcode those checks.
//The reason for that is because of time, i could most likly come up with a clever solution, however it would end up taking way longer..
//Than simply writing it out. This is only Tic-Tac-Toe.
#pragma region DiagonalChecks
//Diagonal Check 1
a = grid.at(2);
b = grid.at(4);
c = grid.at(6);
std::cout << a << b << c;
if (a == b && b == c)
{
//Same as before, we grab the variable at a this time, and return the correct index in players[].
winner = b;
if (winner == 'X')
{
return 0;
}
else
{
return 1;
}
}
//Diagonal Check 2
a = grid.at(0);
b = grid.at(4);
c = grid.at(8);
if (a == b && b == c)
{
//Same as before, we grab the variable at a this time, and return the correct index in players[].
winner = b;
if (winner == 'X')
{
return 0;
}
else
{
return 1;
}
}
#pragma endregion
return 2;
}
void PlayerSwitch()
{
//This function just inverts the player index. I think there is a better and prettier way to do this, however this will do for now.
//Its not pretty, but i added an easter-egg incase something went horribly wrong!
switch (playerIndex)
{
case 0 :
playerIndex = 1;
break;
case 1 :
playerIndex = 0;
break;
default:
std::cout << "WTF just happened, im just gonna try something\n";
playerIndex = 0;
break;
}
}
void CalculateComputerMove(char CPUchar)
{
//Just initializing a seed(time) for my random number generator.
int selected = (rand() % 8 + 1)-1;
if (grid.at(selected) == 'X' || grid.at(selected) == 'O')
{
CalculateComputerMove(CPUchar);
return;
}
else
{
grid.at(selected) = CPUchar;
moves++;
PlayerSwitch();
return;
}
} | [
"[email protected]"
] | |
921e1b5170f7720987763bafac17b4348a900a5c | 9053a16ac04bc9b1273c8d8c31ab9d6e299ba1c6 | /unittest/test_boxqp.cpp | c40951d78f74638bfead8aaa863057b94743abff | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ggory15/crocoddyl | 7b734313b46a137b44f33d5448057507e23a7fa1 | 4708428676f596f93ffe2df739faeb5cc38d2326 | refs/heads/master | 2021-02-08T06:08:35.739000 | 2020-08-03T15:06:49 | 2020-08-05T13:46:45 | 244,117,610 | 0 | 0 | BSD-3-Clause | 2020-03-01T09:02:49 | 2020-03-01T09:02:48 | null | UTF-8 | C++ | false | false | 6,040 | cpp | ///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (C) 2019-2020, University of Edinburgh
// Copyright note valid unless otherwise stated in individual files.
// All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#include <boost/random.hpp>
#include "crocoddyl/core/solvers/box-qp.hpp"
#include "unittest_common.hpp"
using namespace boost::unit_test;
using namespace crocoddyl::unittest;
void test_constructor() {
// Setup the test
std::size_t nx = random_int_in_range(1, 100);
crocoddyl::BoxQP boxqp(nx);
// Test dimension of the decision vector
BOOST_CHECK(boxqp.get_nx() == nx);
}
void test_unconstrained_qp_with_identity_hessian() {
std::size_t nx = random_int_in_range(2, 5);
crocoddyl::BoxQP boxqp(nx);
boxqp.set_reg(0.);
Eigen::MatrixXd hessian = Eigen::MatrixXd::Identity(nx, nx);
Eigen::VectorXd gradient = Eigen::VectorXd::Random(nx);
Eigen::VectorXd lb = -std::numeric_limits<double>::infinity() * Eigen::VectorXd::Ones(nx);
Eigen::VectorXd ub = std::numeric_limits<double>::infinity() * Eigen::VectorXd::Ones(nx);
Eigen::VectorXd xinit = Eigen::VectorXd::Random(nx);
crocoddyl::BoxQPSolution sol = boxqp.solve(hessian, gradient, lb, ub, xinit);
// Checking the solution of the problem. Note that it the negative of the gradient since Hessian
// is identity matrix
BOOST_CHECK((sol.x + gradient).isMuchSmallerThan(1.0, 1e-9));
// Checking the solution against a regularized case
double reg = random_real_in_range(1e-9, 1e2);
boxqp.set_reg(reg);
crocoddyl::BoxQPSolution sol_reg = boxqp.solve(hessian, gradient, lb, ub, xinit);
BOOST_CHECK((sol_reg.x + gradient / (1 + reg)).isMuchSmallerThan(1.0, 1e-9));
// Checking the all bounds are free and zero clamped
BOOST_CHECK(sol.free_idx.size() == nx);
BOOST_CHECK(sol.clamped_idx.size() == 0);
BOOST_CHECK(sol_reg.free_idx.size() == nx);
BOOST_CHECK(sol_reg.clamped_idx.size() == 0);
}
void test_unconstrained_qp() {
std::size_t nx = random_int_in_range(2, 5);
crocoddyl::BoxQP boxqp(nx);
boxqp.set_reg(0.);
Eigen::MatrixXd H = Eigen::MatrixXd::Random(nx, nx);
Eigen::MatrixXd hessian = H.transpose() * H;
hessian = 0.5 * (hessian + hessian.transpose()).eval();
Eigen::VectorXd gradient = Eigen::VectorXd::Random(nx);
Eigen::VectorXd lb = -std::numeric_limits<double>::infinity() * Eigen::VectorXd::Ones(nx);
Eigen::VectorXd ub = std::numeric_limits<double>::infinity() * Eigen::VectorXd::Ones(nx);
Eigen::VectorXd xinit = Eigen::VectorXd::Random(nx);
crocoddyl::BoxQPSolution sol = boxqp.solve(hessian, gradient, lb, ub, xinit);
// Checking the solution against the KKT solution
Eigen::VectorXd xkkt = -hessian.inverse() * gradient;
BOOST_CHECK((sol.x - xkkt).isMuchSmallerThan(1.0, 1e-9));
// Checking the solution against a regularized KKT problem
double reg = random_real_in_range(1e-9, 1e2);
boxqp.set_reg(reg);
crocoddyl::BoxQPSolution sol_reg = boxqp.solve(hessian, gradient, lb, ub, xinit);
Eigen::VectorXd xkkt_reg = -(hessian + reg * Eigen::MatrixXd::Identity(nx, nx)).inverse() * gradient;
BOOST_CHECK((sol_reg.x - xkkt_reg).isMuchSmallerThan(1.0, 1e-9));
// Checking the all bounds are free and zero clamped
BOOST_CHECK(sol.free_idx.size() == nx);
BOOST_CHECK(sol.clamped_idx.size() == 0);
BOOST_CHECK(sol_reg.free_idx.size() == nx);
BOOST_CHECK(sol_reg.clamped_idx.size() == 0);
}
void test_box_qp_with_identity_hessian() {
std::size_t nx = random_int_in_range(2, 5);
crocoddyl::BoxQP boxqp(nx);
boxqp.set_reg(0.);
Eigen::MatrixXd hessian = Eigen::MatrixXd::Identity(nx, nx);
Eigen::VectorXd gradient = Eigen::VectorXd::Ones(nx);
for (std::size_t i = 0; i < nx; ++i) {
gradient(i) *= random_real_in_range(-1., 1.);
}
Eigen::VectorXd lb = Eigen::VectorXd::Zero(nx);
Eigen::VectorXd ub = Eigen::VectorXd::Ones(nx);
Eigen::VectorXd xinit = Eigen::VectorXd::Random(nx);
crocoddyl::BoxQPSolution sol = boxqp.solve(hessian, gradient, lb, ub, xinit);
// The analytical solution is the a bounded, and negative, gradient
Eigen::VectorXd negbounded_gradient(nx), negbounded_gradient_reg(nx);
std::size_t nf = nx, nc = 0, nf_reg = nx, nc_reg = 0;
double reg = random_real_in_range(1e-9, 1e2);
for (std::size_t i = 0; i < nx; ++i) {
negbounded_gradient(i) = std::max(std::min(-gradient(i), ub(i)), lb(i));
negbounded_gradient_reg(i) = std::max(std::min(-gradient(i) / (1 + reg), ub(i)), lb(i));
if (negbounded_gradient(i) != -gradient(i)) {
nc += 1;
nf -= 1;
}
if (negbounded_gradient_reg(i) != -gradient(i) / (1 + reg)) {
nc_reg += 1;
nf_reg -= 1;
}
}
// Checking the solution of the problem. Note that it the negative of the gradient since Hessian
// is identity matrix
BOOST_CHECK((sol.x - negbounded_gradient).isMuchSmallerThan(1.0, 1e-9));
// Checking the solution against a regularized case
boxqp.set_reg(reg);
crocoddyl::BoxQPSolution sol_reg = boxqp.solve(hessian, gradient, lb, ub, xinit);
BOOST_CHECK((sol_reg.x - negbounded_gradient / (1 + reg)).isMuchSmallerThan(1.0, 1e-9));
// Checking the all bounds are free and zero clamped
BOOST_CHECK(sol.free_idx.size() == nf);
BOOST_CHECK(sol.clamped_idx.size() == nc);
BOOST_CHECK(sol_reg.free_idx.size() == nf_reg);
BOOST_CHECK(sol_reg.clamped_idx.size() == nc_reg);
}
void register_unit_tests() {
framework::master_test_suite().add(BOOST_TEST_CASE(boost::bind(&test_constructor)));
framework::master_test_suite().add(BOOST_TEST_CASE(boost::bind(&test_unconstrained_qp_with_identity_hessian)));
framework::master_test_suite().add(BOOST_TEST_CASE(boost::bind(&test_unconstrained_qp)));
framework::master_test_suite().add(BOOST_TEST_CASE(boost::bind(&test_box_qp_with_identity_hessian)));
}
bool init_function() {
register_unit_tests();
return true;
}
int main(int argc, char* argv[]) { return ::boost::unit_test::unit_test_main(&init_function, argc, argv); }
| [
"[email protected]"
] | |
95790908e8d1d2460d9b4d434899e825f5607a16 | 34bbcd08f3d14f265c507b49746e2997d74ec519 | /SFML-MashSim/Spring.cpp | eef2414f96c2c0fe7ea2e01d2dc4757e9a9b4d57 | [] | no_license | SenKetZu/SFML-MashSim | cd866d6dc083d1b064f365511fbdcb79aca7f8b0 | 532b6ca3341888efc0b2a62bdc59301a92075711 | refs/heads/master | 2023-05-27T23:01:36.185000 | 2021-06-09T02:57:41 | 2021-06-09T02:57:41 | 374,864,394 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 809 | cpp | #include "Spring.h"
#include "DrawAgent.h"
Spring::Spring(MassPoint& anchor, MassPoint& exterior):
_Anchor(anchor),
_Exterior(exterior),
_Spring(exterior<<=anchor),
_SpringLenght(100.0f),
_K(10.0f),
_Damping(1.0f),
_TimeSP(.01f),
//variables trancicion
_SpringForce(0.0f),
_DampForce(0.0f),
_Accel(0.0f),
_Vel(0.0f),
_Force(0.0f)
{}
void Spring::Update()
{
//get timesp
_TimeSP = DrawAgent::getInstance().DeltaTime()*100.0f;
//calcular spring
_Spring = _Exterior <<= _Anchor;
//calculo de fuerzas
_SpringForce = _K * (_Spring.getMagnitude() - _SpringLenght);
_DampForce = _Damping * _Vel;
_Force = _SpringForce +10 /*massXgrav*/ - _DampForce;
_Accel = _Force / 1 /*mass*/;
_Vel += _Accel * _TimeSP;
//push masspoint
_Exterior.push(MathVector(_Vel*_TimeSP,_Spring.getAngle()));
} | [
"[email protected]"
] | |
19203a417004197a3b51e22fe5a3dc21d6bcd8c4 | 57f87cd5fb9448bc6cdbf10769365393efae3a00 | /firmware_v5/telelogger/teleclient.h | a6433b87bd84452fb52cfd90b903677e97fb909f | [] | no_license | NatroNx/Freematics | 6a366805aef406d6f4deae050414f9611bbe710e | 011ae3212f57fdee7648eb34171e141c55a413ed | refs/heads/master | 2020-03-25T02:15:51.919000 | 2018-07-31T13:14:23 | 2018-07-31T13:14:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,569 | h | class TeleClient
{
public:
virtual void reset()
{
txCount = 0;
txBytes = 0;
rxBytes = 0;
}
virtual bool notify(byte event, const char* serverKey, const char* payload = 0) { return true; }
virtual bool connect() { return true; }
virtual bool transmit(const char* packetBuffer, unsigned int packetSize) { return true; }
virtual void inbound() {}
virtual bool begin() { return true; }
virtual void end() {}
uint32_t txCount = 0;
uint32_t txBytes = 0;
uint32_t rxBytes = 0;
uint32_t lastSyncTime = 0;
uint32_t lastSentTime = 0;
uint16_t feedid = 0;
};
class TeleClientUDP : public TeleClient
{
public:
bool notify(byte event, const char* serverKey, const char* payload = 0);
bool connect();
bool transmit(const char* packetBuffer, unsigned int packetSize);
void inbound();
bool verifyChecksum(char* data);
#if NET_DEVICE == NET_WIFI
UDPClientWIFI net;
#elif NET_DEVICE == NET_SIM800
UDPClientSIM800 net;
#elif NET_DEVICE == NET_SIM5360
UDPClientSIM5360 net;
#elif NET_DEVICE == NET_SIM7600
UDPClientSIM7600 net;
#else
NullClient net;
#endif
};
class TeleClientHTTP : public TeleClient
{
public:
bool connect();
bool transmit(const char* packetBuffer, unsigned int packetSize);
#if NET_DEVICE == NET_WIFI
HTTPClientWIFI net;
#elif NET_DEVICE == NET_SIM800
HTTPClientSIM800 net;
#elif NET_DEVICE == NET_SIM5360
HTTPClientSIM5360 net;
#elif NET_DEVICE == NET_SIM7600
HTTPClientSIM7600 net;
#else
NullClient net;
#endif
}; | [
"[email protected]"
] | |
73bbdcfbe50a724cb152edeb3ed8f2aed3d76d69 | 28b90ad96790edd30edc5ba95137cc20261599b5 | /nodemcu/MPU_6050_flask_json/MPU_6050_flask_json.ino | 134d2fabdbfb2a13cb534495c378ee4397e38c4e | [] | no_license | anshulahuja98/Codefundo-18-IITJ | b09e1b200a5e5d9bbe23f58addc3460a1a19d732 | bfae0dde99cd9133bdeabd06fdb73b512214b1f9 | refs/heads/master | 2020-03-30T01:52:30.166000 | 2019-02-10T04:34:35 | 2019-02-10T04:34:35 | 150,599,578 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 5,804 | ino |
#include <Wire.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
const uint8_t MPU6050SlaveAddress = 0x68;
const uint8_t scl = D1;
const uint8_t sda = D2;
const uint16_t AccelScaleFactor = 16384;
const uint16_t GyroScaleFactor = 131;
const uint8_t MPU6050_REGISTER_SMPLRT_DIV = 0x19;
const uint8_t MPU6050_REGISTER_USER_CTRL = 0x6A;
const uint8_t MPU6050_REGISTER_PWR_MGMT_1 = 0x6B;
const uint8_t MPU6050_REGISTER_PWR_MGMT_2 = 0x6C;
const uint8_t MPU6050_REGISTER_CONFIG = 0x1A;
const uint8_t MPU6050_REGISTER_GYRO_CONFIG = 0x1B;
const uint8_t MPU6050_REGISTER_ACCEL_CONFIG = 0x1C;
const uint8_t MPU6050_REGISTER_FIFO_EN = 0x23;
const uint8_t MPU6050_REGISTER_INT_ENABLE = 0x38;
const uint8_t MPU6050_REGISTER_ACCEL_XOUT_H = 0x3B;
const uint8_t MPU6050_REGISTER_SIGNAL_PATH_RESET = 0x68;
int16_t AccelX, AccelY, AccelZ, Temperature, GyroX, GyroY, GyroZ;
String flag_payload = "";
int o =0;
void setup() {
Serial.begin(115200);
Wire.begin(sda, scl);
MPU6050_Init();
WiFi.begin("null", "patanahi1");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.println("Waiting for connection");
}
pinMode(10 , OUTPUT);
digitalWrite(10, LOW);
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
double Ax, Ay, Az, T, Gx, Gy, Gz, dev_id;
Read_RawValue(MPU6050SlaveAddress, MPU6050_REGISTER_ACCEL_XOUT_H);
//divide each with their sensititvity scale factor
Ax = (double)AccelX / AccelScaleFactor;
Ay = (double)AccelY / AccelScaleFactor;
Az = (double)AccelZ / AccelScaleFactor;
T = (double)Temperature / 340 + 36.53; //temperature formula
Gx = (double)GyroX / GyroScaleFactor;
Gy = (double)GyroY / GyroScaleFactor;
Gz = (double)GyroZ / GyroScaleFactor;
dev_id = 2222;
Serial.print("Ax: "); Serial.print(Ax);
Serial.print(" Ay: "); Serial.print(Ay);
Serial.print(" Az: "); Serial.print(Az);
Serial.print(" T: "); Serial.print(T);
Serial.print(" Gx: "); Serial.print(Gx);
Serial.print(" Gy: "); Serial.print(Gy);
Serial.print(" Gz: "); Serial.println(Gz);
StaticJsonBuffer<300> JSONbuffer; //Declaring static JSON buffer
JsonObject& JSONencoder = JSONbuffer.createObject();
JSONencoder["Sensor type"] = "Acceleration";
JSONencoder["deviceid"] = dev_id;
JsonArray& values = JSONencoder.createNestedArray("values"); //JSON array
values.add(Ax); //Add value to array
values.add(Ay); //Add value to array
values.add(Az); //Add value to array
values.add(T); //Add value to array
JsonArray& timestamps = JSONencoder.createNestedArray("direction1"); //JSON array
timestamps.add("x direction"); //Add value to array
timestamps.add("y direction"); //Add value to array
timestamps.add("z direction"); //Add value to array
timestamps.add("Temperature"); //Add vaues to array
char JSONmessageBuffer[300];
JSONencoder.prettyPrintTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
Serial.println(JSONmessageBuffer);
HTTPClient http; //Declare object of class HTTPClient
http.begin("http://192.168.43.75:8090/post"); //Specify request destination
http.addHeader("Content-Type", "application/json"); //Specify content-type header
int httpCode = http.POST(JSONmessageBuffer); //Send the request
String payload = http.getString(); //Get the response payload
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
http.end(); //Close connection
http.begin("http://192.168.43.75:8090/get");
int httpCode1 = http.GET(); //Send the request
String payload_get = http.getString();
Serial.println(httpCode1); //Print HTTP return code
Serial.println(payload_get); //Print request response payload
if (payload_get == "1")
{
Serial.println("lasjdf liasdj fli");
o = 1;
}
http.end(); //Close connection
if (o == 1)
{
digitalWrite(10, HIGH);
}
}
else
{
Serial.println("Error in WiFi connection");
}
delay(100);
}
void I2C_Write(uint8_t deviceAddress, uint8_t regAddress, uint8_t data) {
Wire.beginTransmission(deviceAddress);
Wire.write(regAddress);
Wire.write(data);
Wire.endTransmission();
}
// read all 14 register
void Read_RawValue(uint8_t deviceAddress, uint8_t regAddress) {
Wire.beginTransmission(deviceAddress);
Wire.write(regAddress);
Wire.endTransmission();
Wire.requestFrom(deviceAddress, (uint8_t)14);
AccelX = (((int16_t)Wire.read() << 8) | Wire.read());
AccelY = (((int16_t)Wire.read() << 8) | Wire.read());
AccelZ = (((int16_t)Wire.read() << 8) | Wire.read());
Temperature = (((int16_t)Wire.read() << 8) | Wire.read());
GyroX = (((int16_t)Wire.read() << 8) | Wire.read());
GyroY = (((int16_t)Wire.read() << 8) | Wire.read());
GyroZ = (((int16_t)Wire.read() << 8) | Wire.read());
}
//configure MPU6050
void MPU6050_Init() {
delay(150);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_SMPLRT_DIV, 0x07);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_PWR_MGMT_1, 0x01);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_PWR_MGMT_2, 0x00);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_CONFIG, 0x00);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_GYRO_CONFIG, 0x00);//set +/-250 degree/second full scale
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_ACCEL_CONFIG, 0x00);// set +/- 2g full scale
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_FIFO_EN, 0x00);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_INT_ENABLE, 0x01);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_SIGNAL_PATH_RESET, 0x00);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_USER_CTRL, 0x00);
}
| [
"[email protected]"
] | |
7726abf0e5e7eb0906fdf74387dd474018ac3154 | 81f6419ea475836b1f1b24bcd2de77a316bc46a1 | /codeforces/BEducational25-06-2020.cpp | 03fd55ab7c09117fe485917441cb42c7ab252cb1 | [] | no_license | Pramodjais517/competitive-coding | f4e0f6f238d98c0a39f8a9c940265f886ce70cb3 | 2a8ad013246f2db72a4dd53771090d931ab406cb | refs/heads/master | 2023-02-25T12:09:47.382000 | 2021-01-28T06:57:26 | 2021-01-28T06:57:26 | 208,445,032 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,335 | cpp | #include<bits/stdc++.h>
using namespace std;
// template starts here
#define ll long long
#define ull unsigned long long
#define rs reserve
#define pb push_back
#define ff first
#define ss second
#define mp make_pair
#define fi(i,s,e,inc) for(auto i=s;i<e;i+=inc)
#define fie(i,s,e,inc) for(auto i=s;i<=e;i+=inc)
#define fd(i,s,e,dec) for(auto i=s;i>e;i-=dec)
#define fde(i,s,e,dec) for(auto i=s;i>=e;i-=dec)
#define itr(i,ar) for(auto i=ar.begin();i!=ar.end();i++)
#define mod 1000000007
ll N = 1000000;
vector<bool> prime(N+1,true);
void sieve()
{
prime[0] = false,prime[1] = false;
for(ll i=2;i*i <= N;i++)
{
if(prime[i])
{
for(ll j = i*i; j<= N ;j+=i)
prime[j] = false;
}
}
}
ll pow(ll a, ll b)
{
if(b==0)
return 1;
if(b==1)
return a;
ll r = pow(a,b/2);
if(b&1)
return r*a*r;
return r*r;
}
// template ends here
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin>>t;
while(t--)
{
string s;
cin>>s;
ll n=0;
ll a[s.length()];
memset(a,0,sizeof(a));
if(s[0]=='-')
a[0] = -1;
else
a[0] = 1;
fi(i,1,s.length(),1)
{
if(s[i]=='-')
a[i] = a[i-1]-1;
else
a[i] = a[i-1] + 1;
}
ll b[s.length()];
fi(i,0,s.length(),1)
{
b[i] = (a[i] + i);
}
ll ans=0,i=0;
while(i<s.length() and b[i]<0)
{
ans+=(i+1);
i++;
}
ans+=s.length();
cout<<ans<<"\n";
}
return 0;
}
| [
"[email protected]"
] |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 185