hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b6d3feda37fa4e0f6bec953600d6261b6a710baf | 2,357 | cpp | C++ | src/core/header_chain.cpp | mbroemme/bamboo | 07e8a42fa90d9ddd4ea6cfc55f000277b65e5d1b | [
"MIT"
] | null | null | null | src/core/header_chain.cpp | mbroemme/bamboo | 07e8a42fa90d9ddd4ea6cfc55f000277b65e5d1b | [
"MIT"
] | null | null | null | src/core/header_chain.cpp | mbroemme/bamboo | 07e8a42fa90d9ddd4ea6cfc55f000277b65e5d1b | [
"MIT"
] | null | null | null | #include "header_chain.hpp"
#include "api.hpp"
#include "block.hpp"
#include "logger.hpp"
#include <iostream>
using namespace std;
HeaderChain::HeaderChain(string host) {
this->host = host;
this->failed = false;
this->totalWork = 0;
this->chainLength = 0;
}
bool HeaderChain::valid() {
return !this->failed && this->totalWork > 0;
}
string HeaderChain::getHost() {
return this->host;
}
Bigint HeaderChain::getTotalWork() {
if (this->failed) return 0;
return this->totalWork;
}
uint64_t HeaderChain::getChainLength() {
if (this->failed) return 0;
return this->chainLength;
}
void HeaderChain::load() {
uint64_t targetBlockCount;
try {
targetBlockCount = getCurrentBlockCount(this->host);
} catch (...) {
this->failed = true;
return;
}
SHA256Hash lastHash = NULL_SHA256_HASH;
uint64_t numBlocks = 0;
Bigint totalWork = 0;
// download any remaining blocks in batches
for(int i = 1; i <= targetBlockCount; i+=BLOCK_HEADERS_PER_FETCH) {
try {
int end = min(targetBlockCount, (uint64_t) i + BLOCK_HEADERS_PER_FETCH - 1);
bool failure = false;
vector<SHA256Hash>& hashes = this->blockHashes;
vector<BlockHeader> blockHeaders;
readRawHeaders(this->host, i, end, blockHeaders);
for (auto& b : blockHeaders) {
if (failure) return;
vector<Transaction> empty;
Block block(b, empty);
if (!block.verifyNonce()) {
failure = true;
break;
};
if (block.getLastBlockHash() != lastHash) {
failure = true;
break;
}
lastHash = block.getHash();
hashes.push_back(lastHash);
totalWork = addWork(totalWork, block.getDifficulty());
numBlocks++;
}
if (failure) {
this->failed = true;
return;
}
} catch (std::exception& e) {
this->failed = true;
return;
} catch (...) {
this->failed = true;
return;
}
}
this->chainLength = numBlocks;
this->totalWork = totalWork;
this->failed = false;
}
| 27.406977 | 88 | 0.536699 | mbroemme |
b6d4cc78319054635e348aded64612294078730c | 563 | cpp | C++ | July LeetCode Challenge/Day_19.cpp | mishrraG/100DaysOfCode | 3358af290d4f05889917808d68b95f37bd76e698 | [
"MIT"
] | 13 | 2020-08-10T14:06:37.000Z | 2020-09-24T14:21:33.000Z | July LeetCode Challenge/Day_19.cpp | mishrraG/DaysOfCP | 3358af290d4f05889917808d68b95f37bd76e698 | [
"MIT"
] | null | null | null | July LeetCode Challenge/Day_19.cpp | mishrraG/DaysOfCP | 3358af290d4f05889917808d68b95f37bd76e698 | [
"MIT"
] | 1 | 2020-05-31T21:09:14.000Z | 2020-05-31T21:09:14.000Z | class Solution {
public:
string addBinary(string a, string b) {
int n1 = a.size() - 1;
int n2 = b.size() - 1;
int carry = 0;
int sum = 0;
string s;
while (n1 >= 0 || n2 >= 0) {
int c1 = n1 >= 0 ? a[n1] - '0' : 0;
int c2 = n2 >= 0 ? b[n2] - '0' : 0;
sum = c1 + c2 + carry;
carry = 0;
if (sum == 2) {
sum = 0;
carry = 1;
}
if (sum == 3) {
sum = 1;
carry = 1;
}
s.push_back(sum + '0');
n1--;
n2--;
}
if (carry != 0) {
s.push_back(carry + '0');
}
reverse(s.begin(), s.end());
return s;
}
}; | 17.060606 | 39 | 0.436945 | mishrraG |
b6d8fcc2ea0b4a861850a233402fef00db4b63d6 | 643 | cpp | C++ | ares/ws/cpu/dma.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 153 | 2020-07-25T17:55:29.000Z | 2021-10-01T23:45:01.000Z | ares/ws/cpu/dma.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 245 | 2021-10-08T09:14:46.000Z | 2022-03-31T08:53:13.000Z | ares/ws/cpu/dma.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 44 | 2020-07-25T08:51:55.000Z | 2021-09-25T16:09:01.000Z | auto CPU::DMA::transfer() -> void {
//length of 0 or SRAM source address cause immediate termination
if(length == 0 || source.byte(2) == 1) {
enable = 0;
return;
}
self.step(5);
while(length) {
self.step(2);
u16 data = 0;
//once DMA is started; SRAM reads still incur time penalty, but do not transfer
if(source.byte(2) != 1) {
data |= self.read(source + 0) << 0;
data |= self.read(source + 1) << 8;
self.write(target + 0, data >> 0);
self.write(target + 1, data >> 8);
}
source += direction ? -2 : +2;
target += direction ? -2 : +2;
length -= 2;
};
enable = 0;
}
| 25.72 | 83 | 0.547434 | CasualPokePlayer |
b6e503221d683591490f46a242856e349da208ab | 402 | hpp | C++ | wrbb-v2lib-firm/firmware/gr_common/lib/ArduinoJson/ArduinoJson/Numbers/Integer.hpp | h7ga40/gr_citrus | 07d450b9cc857997c97519e962572b92501282d6 | [
"MIT"
] | 1 | 2018-12-04T02:38:37.000Z | 2018-12-04T02:38:37.000Z | wrbb-v2lib-firm/firmware/gr_common/lib/ArduinoJson/ArduinoJson/Numbers/Integer.hpp | h7ga40/gr_citrus | 07d450b9cc857997c97519e962572b92501282d6 | [
"MIT"
] | 3 | 2019-08-15T06:59:48.000Z | 2019-10-16T10:02:09.000Z | wrbb-v2lib-firm/firmware/gr_common/lib/ArduinoJson/ArduinoJson/Numbers/Integer.hpp | h7ga40/gr_citrus | 07d450b9cc857997c97519e962572b92501282d6 | [
"MIT"
] | 1 | 2019-02-22T08:27:15.000Z | 2019-02-22T08:27:15.000Z | // ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2019
// MIT License
#pragma once
#include "../Configuration.hpp"
#include <stdint.h> // int64_t
namespace ARDUINOJSON_NAMESPACE {
#if ARDUINOJSON_USE_LONG_LONG
typedef int64_t Integer;
typedef uint64_t UInt;
#else
typedef long Integer;
typedef unsigned long UInt;
#endif
} // namespace ARDUINOJSON_NAMESPACE
| 19.142857 | 39 | 0.738806 | h7ga40 |
b6e5fddc9312308e7f4772b027e76a4161050cde | 2,416 | hh | C++ | include/dsfs.hh | hspabla/DFS-FUSE | a47e30616f31a78fba23b2b1b0ddb25c97c7beea | [
"Apache-2.0"
] | 3 | 2020-04-08T10:32:44.000Z | 2022-02-17T07:04:07.000Z | include/dsfs.hh | hspabla/DFS-FUSE | a47e30616f31a78fba23b2b1b0ddb25c97c7beea | [
"Apache-2.0"
] | 1 | 2019-10-25T12:24:20.000Z | 2019-10-25T12:24:20.000Z | include/dsfs.hh | hspabla/DFS-FUSE | a47e30616f31a78fba23b2b1b0ddb25c97c7beea | [
"Apache-2.0"
] | null | null | null |
#ifndef dsfs_hh
#define dsfs_hh
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <fuse.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/xattr.h>
#include <unistd.h>
#include <vector>
#include <unordered_map>
#include "log.hh"
#include <map>
//using namespace std;
class DSFS {
private:
const char *_root;
static DSFS *_instance;
std::unordered_map<std::string, std::string> mount_map;
void AbsPath(char dest[PATH_MAX], const char *path);
// temp buffer we keep for files which are written but not yet fsync'ed
// Incase we have to retransmit the data
std::map<int, std::string> dataBuffer;
public:
static DSFS *Instance();
DSFS();
~DSFS();
void setRootDir(const char *path);
int Getattr(const char *path, struct stat *statbuf);
int Mknod(const char *path, mode_t mode, dev_t dev);
int Mkdir(const char *path, mode_t mode);
int Unlink(const char *path);
int Rmdir(const char *path);
int Rename(const char *path, const char *newpath);
int Chmod(const char *path, mode_t mode);
int Chown(const char *path, uid_t uid, gid_t gid);
int Truncate(const char *path, off_t newSize);
int Access(const char *path, int mask);
int Open(const char *path, struct fuse_file_info *fileInfo);
int Read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo);
int Write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo);
int Release(const char *path, struct fuse_file_info *fileInfo);
int Fsync(const char *path, int datasync, struct fuse_file_info *fi);
int Setxattr(const char *path, const char *name, const char *value, size_t size, int flags);
int Getxattr(const char *path, const char *name, char *value, size_t size);
int Listxattr(const char *path, char *list, size_t size);
int Removexattr(const char *path, const char *name);
int Readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fileInfo);
int Releasedir(const char *path, struct fuse_file_info *fileInfo);
int Init(struct fuse_conn_info *conn);
//int Flush(const char *path, struct fuse_file_info *fileInfo);
};
#endif //dsfs_hh
| 33.555556 | 120 | 0.682119 | hspabla |
b6e7e930580d7745467e975c038790b896bc10e2 | 1,167 | cpp | C++ | develop/patch.cpp | chriku/cserial | 70fb65373d73757ef58c92195d5b4de0a7f3ba87 | [
"BSD-3-Clause"
] | null | null | null | develop/patch.cpp | chriku/cserial | 70fb65373d73757ef58c92195d5b4de0a7f3ba87 | [
"BSD-3-Clause"
] | null | null | null | develop/patch.cpp | chriku/cserial | 70fb65373d73757ef58c92195d5b4de0a7f3ba87 | [
"BSD-3-Clause"
] | null | null | null | #include "cserial/patch.hpp"
#include "cserial/serialize.hpp"
#include <iostream>
using namespace std::literals;
struct file_content3 {
bool a = false;
};
template <>
struct cserial::serial<file_content3> : serializer<"file_content3", //
field<&file_content3::a, "a">> {};
struct file_content2 {
bool x = false;
};
template <> struct cserial::serial<file_content2> : converter<file_content2, file_content3> {
static void convert(const file_content2& a, file_content3& b) { b.a = a.x; }
static void unconvert(const file_content3& a, file_content2& b) { b.x = a.a; }
};
struct file_content {
file_content2 x;
std::optional<bool> y = true;
};
template <>
struct cserial::serial<file_content> : serializer<"file_content", //
field<&file_content::x, "x">, field<&file_content::y, "y">> {};
int main() {
file_content fc;
cserial::patch::patch p;
std::cout << std::boolalpha << fc.x.x << std::endl;
cserial::patch::apply<file_content>(fc, R"(
{"x":{"a": true},"y":{"1": true}}
)"_json);
std::cout << std::boolalpha << fc.x.x << std::endl;
}
| 30.710526 | 113 | 0.610968 | chriku |
b6ea3fb5ca44876eec9baa809f3cd0b2b23ab2cc | 3,806 | hpp | C++ | ModSource/breakingpoint_ui/config/unused/CfgCommunicationMenu.hpp | nrailuj/breakingpointmod | e102e106b849ca78deb3cb299f3ae18c91c3bfe9 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 70 | 2017-06-23T21:25:05.000Z | 2022-03-27T02:39:33.000Z | ModSource/breakingpoint_ui/config/unused/CfgCommunicationMenu.hpp | nrailuj/breakingpointmod | e102e106b849ca78deb3cb299f3ae18c91c3bfe9 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 84 | 2017-08-26T22:06:28.000Z | 2021-09-09T15:32:56.000Z | ModSource/breakingpoint_ui/config/unused/CfgCommunicationMenu.hpp | nrailuj/breakingpointmod | e102e106b849ca78deb3cb299f3ae18c91c3bfe9 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 71 | 2017-06-24T01:10:42.000Z | 2022-03-18T23:02:00.000Z | // Generated by unRap v1.06 by Kegetys
class CfgCommunicationMenu {
class Default {
text = "";
submenu = "";
expression = "";
icon = "\a3\Ui_f\data\GUI\Cfg\CommunicationMenu\call_ca.paa";
iconText = "";
cursor = "";
enable = "";
};
class A {
text = $STR_A3_RADIO_A;
iconText = "A";
expression = "%1";
};
class B {
text = $STR_A3_RADIO_B;
iconText = "B";
expression = "%1";
};
class C {
text = $STR_A3_RADIO_C;
iconText = "C";
expression = "%1";
};
class D {
text = $STR_A3_RADIO_D;
iconText = "D";
expression = "%1";
};
class E {
text = $STR_A3_RADIO_E;
iconText = "E";
expression = "%1";
};
class F {
text = $STR_A3_RADIO_F;
iconText = "F";
expression = "%1";
};
class G {
text = $STR_A3_RADIO_G;
iconText = "G";
expression = "%1";
};
class H {
text = $STR_A3_RADIO_H;
iconText = "H";
expression = "%1";
};
class I {
text = $STR_A3_RADIO_I;
iconText = "I";
expression = "%1";
};
class J {
text = $STR_A3_RADIO_J;
iconText = "J";
expression = "%1";
};
class K {
text = $STR_A3_RADIO_K;
iconText = "K";
expression = "%1";
};
class L {
text = $STR_A3_RADIO_L;
iconText = "L";
expression = "%1";
};
class M {
text = $STR_A3_RADIO_M;
iconText = "M";
expression = "%1";
};
class N {
text = $STR_A3_RADIO_N;
iconText = "N";
expression = "%1";
};
class O {
text = $STR_A3_RADIO_O;
iconText = "O";
expression = "%1";
};
class P {
text = $STR_A3_RADIO_P;
iconText = "P";
expression = "%1";
};
class Q {
text = $STR_A3_RADIO_Q;
iconText = "Q";
expression = "%1";
};
class R {
text = $STR_A3_RADIO_R;
iconText = "R";
expression = "%1";
};
class S {
text = $STR_A3_RADIO_S;
iconText = "S";
expression = "%1";
};
class T {
text = $STR_A3_RADIO_T;
iconText = "T";
expression = "%1";
};
class U {
text = $STR_A3_RADIO_U;
iconText = "U";
expression = "%1";
};
class V {
text = $STR_A3_RADIO_V;
iconText = "V";
expression = "%1";
};
class W {
text = $STR_A3_RADIO_W;
iconText = "W";
expression = "%1";
};
class X {
text = $STR_A3_RADIO_X;
iconText = "X";
expression = "%1";
};
class Y {
text = $STR_A3_RADIO_Y;
iconText = "Y";
expression = "%1";
};
class Z {
text = $STR_A3_RADIO_Z;
iconText = "Z";
expression = "%1";
};
class Call {
text = "$STR_A3_CfgCommunicationMenu_Call_0";
icon = "\a3\Ui_f\data\GUI\Cfg\CommunicationMenu\call_ca.paa";
expression = "%1";
};
class Attack {
text = "$STR_A3_CfgCommunicationMenu_Attack_0";
icon = "\a3\Ui_f\data\GUI\Cfg\CommunicationMenu\attack_ca.paa";
expression = "%1";
};
class Defend {
text = "$STR_A3_CfgCommunicationMenu_Defend_0";
icon = "\a3\Ui_f\data\GUI\Cfg\CommunicationMenu\defend_ca.paa";
expression = "%1";
};
class ArtilleryBase {
text = "$STR_A3_mdl_supp_disp_artillery";
icon = "\a3\Ui_f\data\GUI\Cfg\CommunicationMenu\artillery_ca.paa";
cursor = "\A3\ui_f\data\igui\cfg\cursors\iconCursorSupport_ca.paa";
};
class MortarBase {
icon = "\a3\Ui_f\data\GUI\Cfg\CommunicationMenu\mortar_ca.paa";
cursor = "\A3\ui_f\data\igui\cfg\cursors\iconCursorSupport_ca.paa";
};
class CASBase {
icon = "\a3\Ui_f\data\GUI\Cfg\CommunicationMenu\cas_ca.paa";
cursor = "\A3\ui_f\data\igui\cfg\cursors\iconCursorSupport_ca.paa";
};
class SupplyDropBase {
text = "$STR_A3_mdl_supp_disp_drop";
icon = "\a3\Ui_f\data\GUI\Cfg\CommunicationMenu\supplydrop_ca.paa";
cursor = "\A3\ui_f\data\igui\cfg\cursors\iconCursorSupport_ca.paa";
};
class TransportBase {
text = "$STR_A3_mdl_supp_disp_transport";
icon = "\a3\Ui_f\data\GUI\Cfg\CommunicationMenu\transport_ca.paa";
cursor = "\A3\ui_f\data\igui\cfg\cursors\iconCursorSupport_ca.paa";
};
};
| 17.62037 | 69 | 0.609827 | nrailuj |
b6eb570c9b2ac7a802c69f5765f523e67005bf39 | 1,565 | cpp | C++ | uploads/test/Disaster.cpp | l3lackclevil/ARIN-grader | fdfc1ff13402ae5cf327be32733a4cc1fdecf811 | [
"Apache-2.0"
] | null | null | null | uploads/test/Disaster.cpp | l3lackclevil/ARIN-grader | fdfc1ff13402ae5cf327be32733a4cc1fdecf811 | [
"Apache-2.0"
] | null | null | null | uploads/test/Disaster.cpp | l3lackclevil/ARIN-grader | fdfc1ff13402ae5cf327be32733a4cc1fdecf811 | [
"Apache-2.0"
] | null | null | null | #include<cstdio>
#include<iostream>
#include<vector>
using namespace std;
int countt[1000]={0},check[400]={0},c=0,n,sth=0,vc[400][400]={0};
char path[400][2],ans[400],bf;
vector<int>v[1000];
void walk(int p)
{
if(c==n+1)
{
if(sth==0)
{
for(int i=0;i<c;i++)
{
printf("%c ",ans[i]);
}
printf("\n");
sth=1;
}
}
else
{
for(int i=0;i<countt[p];i++)
{
if(v[p][i]!=bf and vc[p][v[p][i]]==0)
{
bf=p;
ans[c]=v[p][i];
c++;
vc[p][v[p][i]]=1;
walk(v[p][i]);
c--;
}
}
}
}
int main()
{
char st;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
char a,b;
scanf(" %c%c",&a,&b);
countt[a]++;
countt[b]++;
if(i==0)
{
st=a;
}
v[a].push_back(b);
v[b].push_back(a);
}
for(int i=0;i<1000;i++)
{
c=0;
if(countt[i]%2>0)
{
for(int j=0;j<400;j++)
{
for(int k=0;k<400;k++)
{
vc[j][k]=0;
}
}
ans[c]=i;
c++;
bf=i;
walk(i);
}
if(sth==1)
{
break;
}
}
if(sth==0)
{
c=0;
ans[c]=st;
bf=st;
c++;
walk(st);
}
return 0;
}
| 17.197802 | 66 | 0.292013 | l3lackclevil |
b6ed298b2b87dd2507cd67a323eb786ade9d90e3 | 14,732 | cpp | C++ | src/trace/D3DStadistics/StatsManager.cpp | attila-sim/attila-sim | a64b57240b4e10dc4df7f21eff0232b28df09532 | [
"BSD-3-Clause"
] | 23 | 2016-01-14T04:47:13.000Z | 2022-01-13T14:02:08.000Z | src/trace/D3DStadistics/StatsManager.cpp | attila-sim/attila-sim | a64b57240b4e10dc4df7f21eff0232b28df09532 | [
"BSD-3-Clause"
] | 2 | 2018-03-25T14:39:20.000Z | 2022-03-18T05:11:21.000Z | src/trace/D3DStadistics/StatsManager.cpp | attila-sim/attila-sim | a64b57240b4e10dc4df7f21eff0232b28df09532 | [
"BSD-3-Clause"
] | 17 | 2016-02-13T05:35:35.000Z | 2022-03-24T16:05:40.000Z | #ifdef WORKLOAD_STATS
#include "UserStats.h"
#include "StatsManager.h"
#include <fstream>
#include <iostream>
#include "support.h"
#include "Log.h"
using namespace std;
using namespace workloadStats;
/* Create singleton */
StatsManager& StatsManager::instance()
{
/**
* @fix
*
* Previous code caused a memory leak. The changes applied follow this
* article:
*
* http://gethelp.devx.com/techtips/cpp_pro/10min/10min0200.asp
*
* Previous code:
*
* if ( !sm )
* sm = new StatsManager();
* return *sm;
**/
static StatsManager sm;
return sm;
}
StatsManager::StatsManager(bool ownership) :
maxFrame(0),
minFrame(-1),
currentFrame(1),
currentBatch(0),
nBatches(0),
perBatchStats(true),
perFrameStats(true),
perTraceStats(true),
stillInFrame(false),
ownership(ownership),
pos(0)
{
int i;
batchesInFrameCount.reserve(1000); // optimization
}
StatsManager::~StatsManager()
{
if (ownership)
{
map<string, UserStat*>::iterator it = userStats.begin();
for ( ; it != userStats.end(); it++ )
{
delete (*it).second;
}
}
};
UserStat* StatsManager::addUserStat(UserStat* stat)
{
if(userStats.find(stat->getName()) == userStats.end())
{
userStats[stat->getName()] = stat;
return stat;
}
else
panic("StatsManager.cpp","addUserStat","Already exists another User Stat with the same name");
}
UserStat* StatsManager::getUserStat(string name)
{
map<string, UserStat*>::iterator returnStat;
if((returnStat = userStats.find(name)) != userStats.end())
{
return returnStat->second;
}
else
panic("StatsManager.cpp","getUserStat","User Stats does not exists");
}
void StatsManager::setPerTraceStats( bool mode )
{
perTraceStats = mode;
}
bool StatsManager::isPerTraceStats() const
{
return perTraceStats;
}
void StatsManager::setPerBatchStats( bool mode )
{
perBatchStats = mode;
}
bool StatsManager::isPerBatchStats() const
{
return perBatchStats;
}
void StatsManager::setPerFrameStats( bool mode )
{
perFrameStats = mode;
}
bool StatsManager::isPerFrameStats() const
{
return perFrameStats;
}
void StatsManager::init( int startFrame )
{
currentFrame = startFrame-1;
pos = 0;
stillInFrame = false;
}
void StatsManager::beginBatch()
{
//cout << "ENTERING BEGIN BATCH" << endl;
if ( pos == 0 )
{
if ( perBatchStats )
pos++;
}
else
{
panic("StatsManager", "startBatch()", "Error. We are already in a batch");
}
if (!stillInFrame)
stillInFrame = true;
}
void StatsManager::endBatch()
{
//cout << "ENTERING END BATCH" << endl;
vector<int> newVect;
map<string, UserStat*>::iterator it = userStats.begin();
for ( ; it != userStats.end(); it++ )
{
(*it).second->endBatch();
}
if ( pos == 1 )
pos--;
else
{
// pos != 1
if ( perBatchStats )
panic("StatsManager", "endBatch()", "Error. We are not in a batch");
// else: counting is already in current frame
// We do not have to add current batch counting to current frame counting
currentBatch++;
nBatches++;
return ;
}
/* increase frame counters with batch counting */
/* Can be optimized reducing the number of functions supported */
/* Reduce the code generator functions generated */
currentBatch ++; /* total batches in current frame */
nBatches++; /* total batches */
}
void StatsManager::endFrame()
{
//cout << "ENTERING END FRAME" << endl;
if ( pos != 0 )
panic("StatsManager","endFrame()", "Error. We are not in a frame");
stillInFrame = false;
int i;
map<string, UserStat*>::iterator it = userStats.begin();
for ( ; it != userStats.end(); it++ )
{
(*it).second->endFrame();
}
currentFrame++;
batchesInFrameCount.push_back(currentBatch);
currentBatch = 0; /* reset batch index */
}
void StatsManager::endTrace()
{
if (stillInFrame)
endFrame();
//cout << "ENTERING END TRACE" << endl;
map<string, UserStat*>::iterator it = userStats.begin();
for ( ; it != userStats.end(); it++ )
(*it).second->endTrace();
dumpBatchStats("statsPerBatch.csv", true, 0);
dumpFrameStats("statsPerFrame.csv", true, 0);
dumpTraceStats("statsTraceFile.csv", true);
}
bool StatsManager::dumpBatchStatsVertical( const char* file , int firstFrame, int firstBatch, int lastFrame, int lastBatch)
{
firstFrame--;
firstBatch--;
ofstream f;
f.open(file);
if ( !f.is_open() )
return false; // the file could not be opened to write
unsigned int i, j, k, nB;
f << "BATCH STATS";
// Prints user stats name
map<string, UserStat*>::iterator it = userStats.begin();
for ( ; it != userStats.end(); it++ )
{
f << ";" << (*it).second->getName();
}
f << "\n";
for ( i = firstFrame; i < lastFrame; i++ )
{
nB = batchesInFrameCount[i];
if (i == firstFrame && nB > firstBatch)
j = firstBatch;
else
j = 0;
if (i == lastFrame - 1 && nB > lastBatch)
nB = lastBatch;
for (; j < nB; j++ )
{
f << "Batch " << j+1 << " (F:" << i+1 << ");";
// Write Stats
map<string, UserStat*>::iterator it2 = userStats.begin();
for ( ; it2 != userStats.end(); it2++ )
{
if (it2 != userStats.begin())
f << ";";
(*it2).second->printBatchValue(f,i,j);
}
f << "\n";
}
}
f.close();
return true;
}
bool StatsManager::dumpBatchStatsHorizontal( const char* file , int firstFrame, int firstBatch, int lastFrame, int lastBatch)
{
firstFrame--;
firstBatch--;
ofstream f;
f.open(file);
if ( !f.is_open() )
return false; // the file could not be opened to write
int i, j, k, nB;
f << "BATCH STATS";
for ( i = firstFrame; i < lastFrame; i++ )
{
nB = batchesInFrameCount[i];
if (i == firstFrame && nB > firstBatch)
j = firstBatch;
else
j = 0;
if (i == lastFrame - 1 && nB > lastBatch)
nB = lastBatch;
for (; j < nB; j++ )
f << ";Batch " << j+1 << " (F:" << i+1 << ")";
}
f << endl;
// User Stats
map<string, UserStat*>::iterator it = userStats.begin();
for ( ; it != userStats.end(); it++ )
{
f << (*it).second->getName();
for ( i = firstFrame; i < lastFrame; i++ )
{
nB = batchesInFrameCount[i];
if (i == firstFrame && nB > firstBatch)
j = firstBatch;
else
j = 0;
if (i == lastFrame - 1 && nB > lastBatch)
nB = lastBatch;
for (; j < nB; j++ )
{
f << ";" ; (*it).second->printBatchValue(f,i,j);
}
}
f << endl;
}
f << endl;
f.close();
return true;
}
void StatsManager::dumpBatchStats(const char* file, bool vertical, int splitLevel)
{
if ( !perBatchStats )
{
LOG( 0, Log::log() << "Skipped (perBatchStats = DISABLED)\n")
return;
}
bool ok = true;
if ( splitLevel <= 0 )
{
if ( vertical )
ok = dumpBatchStatsVertical(file, 1, 1, currentFrame-1, currentBatch-1);
else
ok = dumpBatchStatsHorizontal(file, 1, 1, currentFrame-1, currentBatch-1);
}
else
{
unsigned int total_batches = 0;
for (unsigned int i=0; i < currentFrame; i++)
total_batches += batchesInFrameCount[i];
unsigned int iFile, nFiles;
char fileName[256];
unsigned int frameCount = 0;
unsigned int batchesCount = 0;
unsigned int frameBatchesCount = 0;
unsigned int firstFrame, firstBatch, lastFrame, lastBatch;
nFiles = (total_batches / (splitLevel+1)) +1; // splitLevel columns with data + 1 column with labels
while ( batchesCount < total_batches && ok )
{
firstFrame = frameCount;
firstBatch = frameBatchesCount;
frameBatchesCount += splitLevel;
while (frameBatchesCount >= batchesInFrameCount[frameCount])
{
frameBatchesCount =- batchesInFrameCount[frameCount];
frameCount++;
}
batchesCount += splitLevel;
lastFrame = frameCount;
lastBatch = frameBatchesCount;
sprintf(fileName,"%s_%d-%d_%d-%d.csv", file, firstFrame + 1, firstBatch + 1, lastFrame + 1, lastBatch + 1);
if ( vertical )
ok = dumpBatchStatsVertical(fileName, firstFrame + 1, firstBatch + 1, lastFrame, lastBatch);
else
ok = dumpBatchStatsHorizontal(fileName, firstFrame + 1, firstBatch + 1, lastFrame, lastBatch);
}
}
if ( ok )
{
LOG(0, Log::log() << " OK\n";)
}
else
{
LOG(0, Log::log() << " File could not be opened for writing (maybe was already opened)\n";)
}
}
bool StatsManager::dumpFrameStatsVertical( const char* file, int firstFrame, int lastFrame )
{
firstFrame--;
ofstream f;
f.open(file);
if ( !f.is_open() )
return false; // the file could not be opened to write
unsigned int i, j;
/* Create label row */
f << "FRAME STATS";
/* API Calls accounting dump */
f << ";BATCHES"; // It is a built-in stat
// Prints user stats name
map<string, UserStat*>::iterator it = userStats.begin();
for ( ; it != userStats.end(); it++ )
{
f << ";" << (*it).second->getName();
}
f << "\n";
/* Create data rows */
for ( i = firstFrame; i < lastFrame; i++ )
{
/* Write frame */
f << (i+1) << ";";
/* Write Stats */
f << batchesInFrameCount[i] << ";"; /* Batches */
map<string, UserStat*>::iterator it2 = userStats.begin();
for ( ; it2 != userStats.end(); it2++ )
{
if ( it2 != userStats.begin() )
f << ";";
(*it2).second->printFrameValue(f,i);
}
f << "\n";
}
f.close();
return true;
}
bool StatsManager::dumpFrameStatsHorizontal( const char* file, int firstFrame, int lastFrame )
{
firstFrame--;
ofstream f;
f.open(file);
if ( !f.is_open() )
return false;
int i, j;
/* Create labels for frame columns */
f << "FRAME STATS";
j = 0;
for ( i = firstFrame; i < lastFrame; i++ )
f << ";Frame " << i+1;
f << endl;
// Built-in Stats
f << "BATCHES";
for ( j = firstFrame; j < lastFrame; j++ )
{
f << ";" << batchesInFrameCount[j];
}
f << endl;
// The remain of built-in Stats
map<string, UserStat*>::iterator it = userStats.begin();
for ( ; it != userStats.end(); it++ )
{
f << (*it).second->getName();
for ( j = firstFrame; j < lastFrame; j++ )
{
f << ";" ; (*it).second->printFrameValue(f,j);
}
f << endl;
}
f << "\n";
f.close();
return true;
}
void StatsManager::dumpFrameStats( const char* file, bool vertical, int splitLevel )
{
if ( !perFrameStats )
{
LOG( 0, Log::log() << "Skipped (perFrameStats = DISABLED)\n")
return;
}
bool ok = true;
if ( splitLevel <= 0 )
{
if ( vertical )
ok = dumpFrameStatsVertical(file, 1, currentFrame-1);
else
ok = dumpFrameStatsHorizontal(file, 1, currentFrame-1);
}
else
{
int iFile, nFiles;
char fileName[256];
nFiles = (currentFrame / (splitLevel+1)) +1; /* splitLevel columns with data + 1 column with labels */
for ( iFile = 0; iFile < nFiles && ok; iFile++ )
{
int firstFrame = iFile * splitLevel + 1;
int lastFrame = ((iFile+1)*splitLevel > currentFrame ? currentFrame : (iFile+1)*splitLevel);
sprintf(fileName,"%s_%d_%d.csv", file, firstFrame, lastFrame);
if ( vertical )
ok = dumpFrameStatsVertical(fileName, firstFrame, lastFrame);
else
ok = dumpFrameStatsHorizontal(fileName, firstFrame, lastFrame);
}
}
if ( ok )
{
LOG(0, Log::log() << " OK\n";)
}
else
{
LOG(0, Log::log() << " File could not be opened for writing (maybe was already opened)\n";)
}
}
void StatsManager::dumpTraceStats( const char* file, bool vertical )
{
if ( !perTraceStats )
{
LOG( 0, Log::log() << "Skipped (perTraceStats = DISABLED)\n")
return;
}
ofstream f;
f.open(file);
if ( f.is_open() )
{
LOG(0, Log::log() << " OK\n";)
}
else
{
LOG(0, Log::log() << " File could not be opened for writing (maybe was already opened)\n";)
return;
}
/* Write Stats */
int i, j;
f << "TRACE STATS";
if (vertical)
{
f << ";FRAMES;BATCHES;";
map<string, UserStat*>::iterator it = userStats.begin();
for ( ; it != userStats.end(); it++ )
{
f << (*it).second->getName() << ";";
}
f << "\n;";
/* Print number of frames */
f << currentFrame-1 << ";";
unsigned int totalBatches = 0;
for(int i = 0; i < (currentFrame - 1); i++)
totalBatches += batchesInFrameCount[i];
f << totalBatches << ";";
it = userStats.begin();
for ( ; it != userStats.end(); it++ )
{
(*it).second->printTraceValue(f); f << ";";
}
f << "\n";
}
else // Horizontal dump
{
f << "\n";
f << "FRAMES;" << currentFrame-1 << "\n";
unsigned int totalBatches = 0;
for(int i = 0; i < (currentFrame - 1); i++)
totalBatches += batchesInFrameCount[i];
f << "BATCHES;" << totalBatches << "\n";
map<string, UserStat*>::iterator it = userStats.begin();
for ( ; it != userStats.end(); it++ )
{
f << (*it).second->getName() << ";"; (*it).second->printTraceValue(f); f << "\n";
}
}
f.close();
return;
};
#endif // WORKLOAD_STATS | 22.664615 | 125 | 0.523283 | attila-sim |
b6f5c1412e66019b23ff971ae9a9ed28e868d6b4 | 7,333 | cpp | C++ | src/FastRoute/third_party/pdrev/src/pdrev.cpp | ax3ghazy/OpenROAD | 2d41acd184d2fb5c551fbdb1f74bbe73a782de6f | [
"BSD-3-Clause-Clear"
] | null | null | null | src/FastRoute/third_party/pdrev/src/pdrev.cpp | ax3ghazy/OpenROAD | 2d41acd184d2fb5c551fbdb1f74bbe73a782de6f | [
"BSD-3-Clause-Clear"
] | null | null | null | src/FastRoute/third_party/pdrev/src/pdrev.cpp | ax3ghazy/OpenROAD | 2d41acd184d2fb5c551fbdb1f74bbe73a782de6f | [
"BSD-3-Clause-Clear"
] | null | null | null | #include "pdrev.h"
#include "aux.h"
namespace PD{
void PdRev::setAlphaPDII(float alpha){
alpha2 = alpha;
}
void PdRev::addNet(int numPins, std::vector<unsigned> x, std::vector<unsigned> y){
my_graphs.push_back(new Graph(numPins, verbose, alpha1, alpha2,
alpha3, alpha4, root_idx,
beta, margin, seed,
dist, x, y));
}
void PdRev::config(){
num_nets = my_graphs.size();
// measure.start_clock();
// cout << "\nGenerating nearest neighbor graph..." << endl;
for (unsigned i = 0; i < num_nets; ++i) {
// Guibas-Stolfi algorithm for computing nearest NE (north-east) neighbors
if (i == net_num || !runOneNet) {
my_graphs[i]-> buildNearestNeighborsForSPT(my_graphs[i]->num_terminals);
}
}
// cout << "\nFinished generating nearest neighbor graph..." << endl;
// measure.stop_clock("Graph generation");
}
void PdRev::runPDII(){
config();
// measure.start_clock();
// cout << "\nRunning PD-II... alpha = "
// << alpha2 << endl;
for (unsigned i = 0; i < num_nets; ++i) {
if (i == net_num || !runOneNet) {
my_graphs[i]-> PDBU_new_NN();
}
}
/* for (unsigned i = 0; i < num_nets; ++i) {
cout << " Net " << i
<< " WL = " << my_graphs[i]->pdbu_wl
<< " PL = " << my_graphs[i]->pdbu_pl
<< " DC = " << my_graphs[i]->pdbu_dc
<< endl;
}
cout << "Finished running PD-II..." << endl;
measure.stop_clock("PD-II"); */
runDAS();
}
void PdRev::runDAS(){
//measure.start_clock();
//cout << "\nRunning Steiner algorithm..." << endl;
for (unsigned i = 0; i < num_nets; ++i) {
if (i == net_num || !runOneNet) {
my_graphs[i]-> doSteiner_HoVW();
}
}
/* for (unsigned i = 0; i < num_nets; ++i) {
cout << " Net " << i
<< " WL = " << my_graphs[i]->st_wl
<< " PL = " << my_graphs[i]->st_pl
<< " DC = " << my_graphs[i]->st_dc
<< endl;
}
cout << "Finished Steiner algorithm..." << endl;
measure.stop_clock("HVW Steinerization");
cout << "\nRunning DAS algorithm..." << endl; */
for (unsigned i = 0; i < num_nets; ++i) {
if (i == net_num || !runOneNet) {
my_graphs[i]-> fix_max_dc();
}
}
/*for (unsigned i = 0; i < num_nets; ++i) {
cout << " Net " << i
<< " WL = " << my_graphs[i]->daf_wl
<< " PL = " << my_graphs[i]->daf_pl
<< " DC = " << my_graphs[i]->daf_dc
<< endl;
}
cout << "Finished DAS algorithm..." << endl;
measure.stop_clock("DAS"); */
}
void PdRev::replaceNode(int graph, int originalNode){
Graph * tree = my_graphs[graph];
std::vector<Node> & nodes = tree->nodes;
Node & node = nodes[originalNode];
int nodeParent = node.parent;
std::vector<int> & nodeChildren = node.children;
int newNode = tree->nodes.size();
Node newSP(newNode, node.x, node.y);
//Replace parent in old node children
//Add children to new node
for (int child : nodeChildren){
tree->replaceParent(tree->nodes[child], originalNode, newNode);
tree->addChild(newSP, child);
}
//Delete children from old node
nodeChildren.clear();
//Set new node as old node's parent
node.parent = newNode;
//Set new node parent
if (nodeParent != originalNode){
newSP.parent = nodeParent;
//Replace child in parent
tree->replaceChild(tree->nodes[nodeParent], originalNode, newNode);
} else
newSP.parent = newNode;
//Add old node as new node's child
tree->addChild(newSP, originalNode);
nodes.push_back(newSP);
}
void PdRev::transferChildren(int graph, int originalNode){
Graph * tree = my_graphs[graph];
std::vector<Node> & nodes = tree->nodes;
Node & node = nodes[originalNode];
std::vector<int> nodeChildren = node.children;
int newNode = tree->nodes.size();
Node newSP(newNode, node.x, node.y);
//Replace parent in old node children
//Add children to new node
int count = 0;
node.children.clear();
for (int child : nodeChildren){
if (count < 2){
tree->replaceParent(tree->nodes[child], originalNode, newNode);
tree->addChild(newSP, child);
} else {
tree->addChild(node, child);
}
count++;
}
newSP.parent = originalNode;
tree->addChild(node, newNode);
nodes.push_back(newSP);
}
Tree PdRev::translateTree(int nTree){
Graph* pdTree = my_graphs[nTree];
Tree fluteTree;
fluteTree.deg = pdTree->orig_num_terminals;
fluteTree.branch = (Branch *)malloc((2* fluteTree.deg -2 )* sizeof(Branch));
fluteTree.length = pdTree->daf_wl;
if (pdTree->orig_num_terminals > 2){
for (int i = 0; i < pdTree->orig_num_terminals; ++i){
Node & child = pdTree->nodes[i];
if (child.children.size() == 0 || (child.parent == i && child.children.size() == 1 && child.children[0] >= pdTree->orig_num_terminals))
continue;
replaceNode(nTree, i);
}
int nNodes = pdTree->nodes.size();
for (int i = pdTree->orig_num_terminals; i < nNodes; ++i){
Node & child = pdTree->nodes[i];
while (pdTree->nodes[i].children.size() > 3 || (pdTree->nodes[i].parent != i && pdTree->nodes[i].children.size() == 3)){
transferChildren(nTree,i);
}
}
pdTree->RemoveSTNodes();
}
for (int i = 0; i < pdTree->nodes.size(); ++i){
Node & child = pdTree->nodes[i];
int parent = child.parent;
Branch & newBranch = fluteTree.branch[i];
newBranch.x = (DTYPE) child.x;
newBranch.y = (DTYPE) child.y;
newBranch.n = parent;
}
my_graphs.clear();
return fluteTree;
}
void PdRev::printTree(Tree fluteTree){
int i;
for (i = 0; i < 2* fluteTree.deg-2; i++) {
printf("%d \n", i);
printf("%d %d\n", fluteTree.branch[i].x, fluteTree.branch[i].y);
printf("%d %d\n\n", fluteTree.branch[fluteTree.branch[i].n].x,
fluteTree.branch[fluteTree.branch[i].n].y);
}
}
}
| 37.798969 | 159 | 0.472931 | ax3ghazy |
b6f8076d7844f29d7572fd5a4900bdf2923288ef | 9,797 | cpp | C++ | EMA_HFODE/src/EMA_main.cpp | NctuICLab/GREMA | 1ded5168e644b6cf4e219e28320f7e84aa3dba84 | [
"MIT"
] | 3 | 2019-04-27T10:34:27.000Z | 2021-11-08T12:20:59.000Z | EMA_HFODE/src/EMA_main.cpp | NctuICLab/GREMA | 1ded5168e644b6cf4e219e28320f7e84aa3dba84 | [
"MIT"
] | null | null | null | EMA_HFODE/src/EMA_main.cpp | NctuICLab/GREMA | 1ded5168e644b6cf4e219e28320f7e84aa3dba84 | [
"MIT"
] | null | null | null | //
// EMA_main.cpp
// EMA_Hillsum_mask
//
// Created by Mingju on 2017/3/10.
// Copyright (c) 2015 Mingju. All rights reserved.
//
#include "Define.h"
#include "IGA.h"
#include "OrthogonalArray.h"
#include "Model.h"
#include "Getknowledge.h"
#include "Objfunction.h"
using namespace std;
int iteration;
int test_mode,cc_mode;
int ExecutionRuns;
int FUNC;
int GeneIndex;
int POP_SIZE;
int GENERATION;
int NO_timepoints;
int init_file_idx;
int knowledge_idx;
//test
void exit_with_help();
void parse_command_line(int argc, char **argv);
int main(int argc, char **argv)
{
parse_command_line(argc, argv);
Getknowledge *knowledge;
Model *hill;
COrthogonalArray *OA;
IGA *iga;
Objfunction *obj;
double **Chromosomes;
Chromosomes = NULL;
double **ModelParameters;
ModelParameters = NULL;
double *PopFitness;
PopFitness = NULL;
PopFitness = new double[POP_SIZE];
memset(PopFitness, 0, POP_SIZE*sizeof(double));
unsigned int seed;
seed = (unsigned int)time(NULL);
srand(seed);
//char DataFileName[30];
int i,j;
int time_step;
int bestIndex;
int NumReg = 0;
int NumVars;
int NumTFs;
int NumEncodeParam;
int TimePoints;
int ExpRepeat;
int *range = NULL;
int *choose = NULL;
int *LocMask = NULL;
//unsigned int ChromSize;
unsigned int execution_times;
unsigned int NumOrigParam;
//char str1[100];
char str2[100];
//FILE *ptr1,*ptr2,*ptr3;
FILE *ptr_Inputprofile;
FILE *ptr_EMAcalProfile;
//sprintf(str1,"%d_step%d.txt",GeneIndex,iteration);
//ptr2=fopen(str1,"w");
sprintf(str2,"calprofile%d_step%d.txt",GeneIndex,iteration);
ptr_EMAcalProfile=fopen(str2,"w");
hill = new Model();
//strcpy(DataFileName,"./data/GNdata.txt");
hill->SetGeneIndex(GeneIndex);
hill->ReadInitFromFile(argv[init_file_idx]);
if(hill->IsSimulated()){
hill->CalAllExpValues(); //produce simulated data and perturbation set
}
ptr_Inputprofile=fopen("printdata.txt","w");
hill->PrintAllExpXs(ptr_Inputprofile);//print expression data
//exit(0);
if(hill->IsSimulated()){time_step = hill->NumTrials()/NO_timepoints;}
else{time_step = 1;}
NumVars = hill->NumVariables();
NumTFs = hill->NumTFsVariables();
TimePoints = hill->NumTrials();
ExpRepeat = hill->NumRuns();
range = new int [NumVars];
memset(range,0,NumVars*sizeof(int));
choose = new int [NumVars];
memset(choose, 0, NumVars*sizeof(int));
LocMask = new int [NumVars];
memset(LocMask, 0, NumVars*sizeof(int));
/*
printf("initial\n");
for(int i=0; i<NumVars; i++){
printf("LockMask[%d]=%d\trange[%d]=%d\tchoose[%d]=%d\n",i,LocMask[i],i,range[i],i,choose[i]);
}
PAUSE;
*/
//============
knowledge = new Getknowledge();
knowledge->NumVars = NumVars;
knowledge->NumTFs = NumTFs;
//knowledge->initial_knowledge();
knowledge->Readknowledge(GeneIndex, iteration, LocMask, range, choose, argv[knowledge_idx]);
/*
printf("read knowledge of regulations file\n");
for(int i=0; i<NumVars; i++){
printf("LockMask[%d]=%d\trange[%d]=%d\tchoose[%d]=%d\n",i,LocMask[i],i,range[i],i,choose[i]);
}
PAUSE;
*/
NumReg = knowledge->get_Numconnections();
NumEncodeParam = 3*NumReg + 4;//Location, Nij, kij + bi, betai, degi
NumOrigParam = 2*NumVars +3;//Nij,kij + bi, betai, degi
//ChromSize = POP_SIZE * NumEncodeParam;
Chromosomes = new double* [POP_SIZE];
for(i=0; i<POP_SIZE; i++){
Chromosomes[i] = new double [NumEncodeParam];
memset(Chromosomes[i], 0, NumEncodeParam*sizeof(double));
}
ModelParameters = new double* [ExecutionRuns];
for(i=0; i<ExecutionRuns; i++){
ModelParameters[i] = new double [NumOrigParam+1];
memset(ModelParameters[i], 0, (NumOrigParam+1)*sizeof(double));
}
/*
printf("initial the chromosome value\n");
for(int i=0; i<POP_SIZE; i++){
for(int j=0; j<NumEncodeParam; j++){
printf("%f ",Chromosomes[i][j]);
}
printf("\n");
}
PAUSE;
*/
obj = new Objfunction();
obj->NumVars = NumVars;
obj->NumTFs = NumTFs;
obj->NumTrials = TimePoints;
obj->NumRuns = ExpRepeat;
obj->PARAM_NUM = NumEncodeParam;
obj->NumGeneParam = NumOrigParam;
obj->NO_POP = POP_SIZE;
obj->init_obj(time_step,FUNC,ExecutionRuns,cc_mode, NumReg,GeneIndex,hill,Chromosomes);
//==========================================
OA = new COrthogonalArray();
OA->initialOA(obj, Chromosomes, PopFitness);
//===========================================
//iga = new IGA(OA,hill,knowledge,obj);
iga = new IGA();
iga->NumVars = NumVars;
iga->NumTFs = NumTFs;
iga->NumRuns = ExpRepeat;
iga->NumTrials = TimePoints;
iga->Num_nochange = hill->NumNochange();
iga->NO_REG = NumReg;
iga->NO_POP = POP_SIZE;
iga->NO_GEN = GENERATION;
iga->PARAM_NUM = NumEncodeParam;
iga->NumGeneParam = NumOrigParam;
iga->set_parameter(GeneIndex,iteration,test_mode,OA,hill,knowledge,obj,Chromosomes,PopFitness,LocMask,choose,range, ModelParameters);
iga->initialIGA();
iga->RangeVariable();
//----------------------------------------------------------------------------
fprintf(ptr_EMAcalProfile,"Seed:%d\n",seed);
for(execution_times=0;execution_times<ExecutionRuns;execution_times++)
{
if(knowledge->get_noregulation())
{
for(i=0; i<POP_SIZE; i++){
for(j=0; j<NumEncodeParam; j++){
Chromosomes[i][j] = 0;
//printf("%f ",Chromosomes[i][j]);
}
//printf("\n");
}
}else{
iga->initialpop();
iga->run(execution_times);
}
for(i=0; i<ExpRepeat; i++)
{
fprintf(ptr_EMAcalProfile,"N:%d Run:%d ",execution_times,i);
for(j=0; j<TimePoints; j+=time_step)
{
fprintf(ptr_EMAcalProfile,"%g ",obj->cal_profile[i][j]);
}//end of NumTrials
bestIndex = iga->get_BestOne();
fprintf(ptr_EMAcalProfile,"%e %1.3f\n", PopFitness[bestIndex], obj->best_cc);
}
}
for(i=0;i<ExecutionRuns;i++)
{
for(j=0;j<=NumOrigParam;j++)
{
if(j==NumOrigParam)
printf("%e ",ModelParameters[i][j]);
else
printf("%f ",ModelParameters[i][j]);
}
printf("%1.3f\n",obj->best_cc);
}
if(ModelParameters)
{
for(i=0;i<ExecutionRuns;i++)
delete [] ModelParameters[i];
delete [] ModelParameters;
}
if(Chromosomes)
{
for(i=0;i<POP_SIZE;i++)
delete [] Chromosomes[i];
delete [] Chromosomes;
}
if(PopFitness)
delete [] PopFitness;
if(range)
delete [] range;
if(choose)
delete [] choose;
if(LocMask)
delete [] LocMask;
if(knowledge)
delete knowledge;
if(hill)
delete hill;
if(OA)
delete OA;
if(iga)
delete iga;
if(obj)
delete obj;
fclose(ptr_EMAcalProfile);
fclose(ptr_Inputprofile);
return 0;
}
void exit_with_help()
{
printf(
"Usage: HFODE_multiply [options] init_file kowledge_file\n"
"options:\n"
"-i : No.[?] of gene to run (Start from 0)\n"
"-n : Number of run (default 30)\n"
"-G : Number of generation (default 10000)\n"
"-I : set the iteration of EMA (default 0)\n"
"-F : Objective function (default 2)\n"
" 0 -- (Xcal-Xexp)/Xexp\n"
" 1 -- (Xcal-Xexp)\n"
" 2 -- delta_diff + f0\n"
" 3 -- delta_diff + f1\n"
" 4 -- delta_diff\n"
"-P : Number of popluation size (default 100)\n"
"-t : Time points (necessary in simulated exp., default 10)\n"
"-m change_mode : Test mode or RUN mode (default 1)\n"
" 0 -- RUN mode\n"
" 1 -- TEST mode\n"
"-c cc_mode : set the fitness function with cc or not (default 0)\n"
" 0 -- without cc mode\n"
" 1 -- with cc mode\n" );
exit(1);
}
void parse_command_line(int argc, char **argv)
{
int i;
if(argc <= 1)
exit_with_help();
//===default values=====//
GeneIndex=0;
ExecutionRuns=30;
GENERATION=10000;
NO_timepoints=10;
POP_SIZE=100;
FUNC=2;
test_mode=1;
cc_mode=0;
iteration = 0;
init_file_idx = 2;
knowledge_idx = 3;
i = 1;
//======================//
while(1)
{
if(argv[i][0] != '-')
break;
switch(argv[i][1])
{
case 'i':
GeneIndex = atoi(argv[i+1]);
i++;
break;
case 'n':
ExecutionRuns = atoi(argv[i+1]);
i++;
break;
case 'G':
GENERATION = atoi(argv[i+1]);
i++;
break;
case 'I':
iteration = atoi(argv[i+1]);
i++;
break;
case 'F':
FUNC = atoi(argv[i+1]);
i++;
break;
case 'P':
POP_SIZE = atoi(argv[i+1]);
i++;
break;
case 't':
NO_timepoints = atoi(argv[i+1]);
i++;
break;
case 'm':
test_mode = atoi(argv[i+1]);
i++;
break;
case 'c':
cc_mode = atoi(argv[i+1]);
i++;
break;
default:
fprintf(stderr,"Unknown option!!\n");
exit_with_help();
break;
}
i++;
}
if(i < argc)
init_file_idx = i++;
else{
fprintf(stderr, "No initial file!!\n");
exit_with_help();
}
if(i < argc)
knowledge_idx = i;
else{
fprintf(stderr, "No knowledge file!!\n");
exit_with_help();
}
}
| 27.213889 | 137 | 0.557109 | NctuICLab |
b6fa6bb10e760f6a1214161ac9d0ab9518d9fbcd | 12,390 | cpp | C++ | Codegen/RVInst.cpp | Yveh/Compiler-Mx_star | e00164537528858ed128dbc5a5c4cf7006d6276e | [
"MIT"
] | 1 | 2020-01-23T14:34:11.000Z | 2020-01-23T14:34:11.000Z | Codegen/RVInst.cpp | Yveh/Compiler-Mx_star | e00164537528858ed128dbc5a5c4cf7006d6276e | [
"MIT"
] | null | null | null | Codegen/RVInst.cpp | Yveh/Compiler-Mx_star | e00164537528858ed128dbc5a5c4cf7006d6276e | [
"MIT"
] | null | null | null | #include "RVInst.h"
RVFunction::RVFunction(std::string _name) : name(_name) {
regcnt = 0;
paramInStackOffset = 0;
}
std::string RVFunction::to_string() {
return name;
}
RVBlock::RVBlock(int _label) : label(_label) {}
std::string RVBlock::to_string() {
return "." + funcName + "_.bb" + std::to_string(label);
}
RVReg::RVReg(int _id, int _size, bool _is_global, bool _is_constString, bool _is_special) : id(_id), size(_size), is_global(_is_global), is_constString(_is_constString), is_special(_is_special) {}
std::string RVReg::to_string() {
if (is_special)
return regNames[id];
else if (is_constString)
return ".str." + std::to_string(id);
else if (is_global)
return "g" + std::to_string(id);
else
return "%" + std::to_string(id);
}
RVReg RVGReg(int _id, int _size) {return RVReg(_id, _size, 1, 0);}
RVReg RVSReg(int _id, int _size) {return RVReg(_id, _size, 1, 1);}
RVReg RVPReg(int _id) {return RVReg(_id, 0, 0, 0, 1);}
RVReg RVReg_zero() {return RVReg(0, 0, 0, 0, 1);}
RVReg RVReg_ra() {return RVReg(1, 0, 0, 0, 1);};
RVReg RVReg_a(int _id) {return RVReg(10 + _id, 0, 0, 0, 1);}
RVReg RVReg_sp() {return RVReg(2, 0, 0, 0, 1);}
RVImm::RVImm(int _id, Rop _op, bool _is_stack, bool _is_neg) : id(_id), op(_op), is_stack(_is_stack), is_neg(_is_neg) {}
std::string RVImm::to_string() {
if (op == Imm)
return std::to_string(id);
else if (op == Hi)
return "%hi(g" + std::to_string(id) + ")";
else
return "%lo(g" + std::to_string(id) + ")";
}
RVLi::RVLi(RVReg _rd, RVImm _value) : rd(_rd), value(_value) {}
RVSt::RVSt(RVReg _value, RVReg _addr, RVImm _offset, int _width) : value(_value), addr(_addr), offset(_offset), width(_width) {}
RVLui::RVLui(RVReg _rd, RVImm _value) : rd(_rd), value(_value) {}
RVMv::RVMv(RVReg _rd, RVReg _rs) : rd(_rd), rs(_rs) {}
RVLd::RVLd(RVReg _rd, RVReg _addr, RVImm _offset, int _width) : rd(_rd), addr(_addr), offset(_offset), width(_width) {}
RVJump::RVJump(std::shared_ptr<RVBlock> _offset) : offset(_offset) {}
RVBr::RVBr(RVReg _rs1, RVReg _rs2, Bop _op, std::shared_ptr<RVBlock> _offset) : rs1(_rs1), rs2(_rs2), op(_op), offset(_offset) {}
RVItype::RVItype(RVReg _rd, RVReg _rs, RVImm _imm, Sop _op) : rd(_rd), rs(_rs), imm(_imm), op(_op) {}
RVRtype::RVRtype(RVReg _rd, RVReg _rs1, RVReg _rs2, Sop _op) : rd(_rd), rs1(_rs1), rs2(_rs2), op(_op) {}
RVSz::RVSz(RVReg _rd, RVReg _rs, Szop _op) : rd(_rd), rs(_rs), op(_op) {}
RVCall::RVCall(std::shared_ptr<RVFunction> _func) : func(_func) {}
std::string RVBr::to_string() {
std::string ret = "b";
switch (op) {
case Bop::Eq : ret += "eq"; break;
case Bop::Ne : ret += "ne"; break;
case Bop::Ge : ret += "ge"; break;
case Bop::Gt : ret += "gt"; break;
case Bop::Le : ret += "le"; break;
case Bop::Lt : ret += "lt"; break;
}
ret += " " + rs1.to_string() + ", " + rs2.to_string() + ", " + offset->to_string();
return ret;
}
std::set<int> RVBr::getUse() {
return std::set<int>{rs1.is_special ? -rs1.id : rs1.id, rs2.is_special ? -rs2.id : rs2.id};
}
std::set<int> RVBr::getDef() {
return std::set<int>();
}
void RVBr::replaceUse(int a, int b) {
if (!rs1.is_special && rs1.id == a)
rs1.id = b;
if (!rs2.is_special && rs2.id == a)
rs2.id = b;
}
void RVBr::replaceDef(int a, int b) {}
void RVBr::replaceColor(int a, int b) {
if (!rs1.is_special && rs1.id == a) {
rs1.id = b;
rs1.is_special = 1;
}
if (!rs2.is_special && rs2.id == a) {
rs2.id = b;
rs2.is_special = 1;
}
}
std::string RVJump::to_string() {
return "j " + offset->to_string();
}
std::set<int> RVJump::getUse() {
return std::set<int>();
}
std::set<int> RVJump::getDef() {
return std::set<int>();
}
void RVJump::replaceUse(int a, int b) {}
void RVJump::replaceDef(int a, int b) {}
void RVJump::replaceColor(int a, int b) {}
std::string RVLd::to_string() {
if (width == 1) {
return "lb " + rd.to_string() + ", " + offset.to_string() + "(" + addr.to_string() + ")";
}
else {
return "lw " + rd.to_string() + ", " + offset.to_string() + "(" + addr.to_string() + ")";
}
}
std::set<int> RVLd::getUse() {
return std::set<int>{addr.is_special ? -addr.id : addr.id};
}
std::set<int> RVLd::getDef() {
return std::set<int>{rd.is_special ? -rd.id : rd.id};
}
void RVLd::replaceUse(int a, int b) {
if (!addr.is_special && addr.id == a)
addr.id = b;
}
void RVLd::replaceDef(int a, int b) {
if (!rd.is_special && rd.id == a)
rd.id = b;
}
void RVLd::replaceColor(int a, int b) {
if (!rd.is_special && rd.id == a) {
rd.id = b;
rd.is_special = 1;
}
if (!addr.is_special && addr.id == a) {
addr.id = b;
addr.is_special = 1;
}
}
std::string RVLui::to_string() {
return "lui " + rd.to_string() + ", " + value.to_string();
}
std::set<int> RVLui::getUse() {
return std::set<int>();
}
std::set<int> RVLui::getDef() {
return std::set<int>{rd.is_special ? -rd.id : rd.id};
}
void RVLui::replaceUse(int a, int b) {}
void RVLui::replaceDef(int a, int b) {
if (!rd.is_special && rd.id == a)
rd.id = b;
}
void RVLui::replaceColor(int a, int b) {
if (!rd.is_special && rd.id == a) {
rd.id = b;
rd.is_special = 1;
}
}
std::string RVLi::to_string() {
return "li " + rd.to_string() + ", " + value.to_string();
}
std::set<int> RVLi::getUse() {
return std::set<int>{};
}
std::set<int> RVLi::getDef() {
return std::set<int>{rd.is_special ? -rd.id : rd.id};
}
void RVLi::replaceUse(int a, int b) {}
void RVLi::replaceDef(int a, int b) {
if (!rd.is_special && rd.id == a)
rd.id = b;
}
void RVLi::replaceColor(int a, int b) {
if (!rd.is_special && rd.id == a) {
rd.id = b;
rd.is_special = 1;
}
}
std::string RVSt::to_string() {
if (width == 1) {
return "sb " + value.to_string() + ", " + offset.to_string() + "(" + addr.to_string() + ")";
}
else {
return "sw " + value.to_string() + ", " + offset.to_string() + "(" + addr.to_string() + ")";
}
}
std::set<int> RVSt::getUse() {
return std::set<int>{addr.is_special ? -addr.id : addr.id, value.is_special ? -value.id : value.id};
}
std::set<int> RVSt::getDef() {
return std::set<int>();
}
void RVSt::replaceUse(int a, int b) {
if (!addr.is_special && addr.id == a)
addr.id = b;
if (!value.is_special && value.id == a)
value.id = b;
}
void RVSt::replaceDef(int a, int b) {}
void RVSt::replaceColor(int a, int b) {
if (!addr.is_special && addr.id == a) {
addr.id = b;
addr.is_special = 1;
}
if (!value.is_special && value.id == a) {
value.id = b;
value.is_special = 1;
}
}
std::string RVSz::to_string() {
if (op == Seqz) {
return "seqz " + rd.to_string() + ", " + rs.to_string();
}
else {
return "snez " + rd.to_string() + ", " + rs.to_string();
}
}
std::set<int> RVSz::getUse() {
return std::set<int>{rs.is_special ? -rs.id : rs.id};
}
std::set<int> RVSz::getDef() {
return std::set<int>{rd.is_special ? -rd.id : rd.id};
}
void RVSz::replaceUse(int a, int b) {
if (!rs.is_special && rs.id == a)
rs.id = b;
}
void RVSz::replaceDef(int a, int b) {
if (!rd.is_special && rd.id == a)
rd.id = b;
}
void RVSz::replaceColor(int a, int b) {
if (!rd.is_special && rd.id == a) {
rd.id = b;
rd.is_special = 1;
}
if (!rs.is_special && rs.id == a) {
rs.id = b;
rs.is_special = 1;
}
}
std::string RVMv::to_string() {
return "mv " + rd.to_string() + ", " + rs.to_string();
}
std::set<int> RVMv::getUse() {
return std::set<int>{rs.is_special ? -rs.id : rs.id};
}
std::set<int> RVMv::getDef() {
return std::set<int>{rd.is_special ? -rd.id : rd.id};
}
void RVMv::replaceUse(int a, int b) {
if (!rs.is_special && rs.id == a)
rs.id = b;
}
void RVMv::replaceDef(int a, int b) {
if (!rd.is_special && rd.id == a)
rd.id = b;
}
void RVMv::replaceColor(int a, int b) {
if (!rd.is_special && rd.id == a) {
rd.id = b;
rd.is_special = 1;
}
if (!rs.is_special && rs.id == a) {
rs.id = b;
rs.is_special = 1;
}
}
std::string RVItype::to_string() {
std::string ret;
switch (op) {
case Sop::And: ret = "andi "; break;
case Sop::Or: ret = "ori "; break;
case Sop::Xor: ret = "xori "; break;
case Sop::Add: ret = "addi "; break;
case Sop::Sll: ret = "slli "; break;
case Sop::Sra: ret = "srli "; break;
case Sop::Slt: ret = "slti "; break;
}
ret += rd.to_string() + ", " + rs.to_string() + ", " + imm.to_string();
return ret;
}
std::set<int> RVItype::getUse() {
return std::set<int>{rs.is_special ? -rs.id : rs.id};
}
std::set<int> RVItype::getDef() {
return std::set<int>{rd.is_special ? -rd.id : rd.id};
}
void RVItype::replaceUse(int a, int b) {
if (!rs.is_special && rs.id == a)
rs.id = b;
}
void RVItype::replaceDef(int a, int b) {
if (!rd.is_special && rd.id == a)
rd.id = b;
}
void RVItype::replaceColor(int a, int b) {
if (!rs.is_special && rs.id == a) {
rs.id = b;
rs.is_special = 1;
}
if (!rd.is_special && rd.id == a) {
rd.id = b;
rd.is_special = 1;
}
}
std::string RVRtype::to_string() {
std::string ret;
switch (op) {
case Sop::And: ret = "and "; break;
case Sop::Or: ret = "or "; break;
case Sop::Xor: ret = "xor "; break;
case Sop::Add: ret = "add "; break;
case Sop::Sub: ret = "sub "; break;
case Sop::Sll: ret = "sll "; break;
case Sop::Sra: ret = "srl "; break;
case Sop::Mul: ret = "mul "; break;
case Sop::Div: ret = "div "; break;
case Sop::Rem: ret = "rem "; break;
case Sop::Slt: ret = "slt "; break;
}
ret += rd.to_string() + ", " + rs1.to_string() + ", " + rs2.to_string();
return ret;
}
std::set<int> RVRtype::getUse() {
return std::set<int>{rs1.is_special ? -rs1.id : rs1.id, rs2.is_special ? -rs2.id : rs2.id};
}
std::set<int> RVRtype::getDef() {
return std::set<int>{rd.is_special ? -rd.id : rd.id};
}
void RVRtype::replaceUse(int a, int b) {
if (!rs1.is_special && rs1.id == a)
rs1.id = b;
if (!rs2.is_special && rs2.id == a)
rs2.id = b;
}
void RVRtype::replaceDef(int a, int b) {
if (!rd.is_special && rd.id == a)
rd.id = b;
}
void RVRtype::replaceColor(int a, int b) {
if (!rs1.is_special && rs1.id == a) {
rs1.id = b;
rs1.is_special = 1;
}
if (!rs2.is_special && rs2.id == a) {
rs2.id = b;
rs2.is_special = 1;
}
if (!rd.is_special && rd.id == a) {
rd.id = b;
rd.is_special = 1;
}
}
std::string RVCall::to_string() {
return "call " + func->to_string();
}
std::set<int> RVCall::getUse() {
std::set<int> ret;
for (int i = 0; i < std::min(8, int(func->paras.size())); ++i) {
ret.insert(-10 - i);
}
return ret;
}
std::set<int> RVCall::getDef() {
return std::set<int>{-1, -5, -6, -7, -10, -11, -12, -13, -14, -15, -16, -17, -28, -29, -30, -31};
}
void RVCall::replaceUse(int a, int b) {}
void RVCall::replaceDef(int a, int b) {}
void RVCall::replaceColor(int a, int b) {}
RVRet::RVRet() {}
std::string RVRet::to_string() {
return std::string("ret");
}
std::set<int> RVRet::getUse() {
return std::set<int>{-1};
}
std::set<int> RVRet::getDef() {
return std::set<int>();
}
void RVRet::replaceUse(int a, int b) {}
void RVRet::replaceDef(int a, int b) {}
void RVRet::replaceColor(int a, int b) {}
RVLa::RVLa(RVReg _rd, RVReg _rs) : rd(_rd), rs(_rs) {}
std::string RVLa::to_string() {
return "la " + rd.to_string() + ", " + rs.to_string();
}
std::set<int> RVLa::getUse() {
return std::set<int>();
}
std::set<int> RVLa::getDef() {
return std::set<int>{rd.is_special ? -rd.id : rd.id};
}
void RVLa::replaceUse(int a, int b) {}
void RVLa::replaceDef(int a, int b) {
if (!rd.is_special && rd.id == a)
rd.id = b;
}
void RVLa::replaceColor(int a, int b) {
if (!rd.is_special && rd.id == a) {
rd.id = b;
rd.is_special = 1;
}
} | 25.030303 | 196 | 0.549395 | Yveh |
b6fe175e57a621f051f8f4632fb5265364b39c73 | 245 | hpp | C++ | Kmer.hpp | harkoslav/BioInformatics-Project-2019 | 65ce99e834c73cb1efc8021dbe2c5065050dd7f1 | [
"MIT"
] | null | null | null | Kmer.hpp | harkoslav/BioInformatics-Project-2019 | 65ce99e834c73cb1efc8021dbe2c5065050dd7f1 | [
"MIT"
] | null | null | null | Kmer.hpp | harkoslav/BioInformatics-Project-2019 | 65ce99e834c73cb1efc8021dbe2c5065050dd7f1 | [
"MIT"
] | null | null | null | #include <string>
#ifndef KMER
#define KMER
/*
Class representing k-mer substring and it's index
in the reference string.
*/
class Kmer {
public:
std::string str;
int index;
Kmer(std::string, int i);
};
#endif | 13.611111 | 49 | 0.616327 | harkoslav |
8e028d821a1e056348937e629dbb15b7cf0b9b05 | 2,775 | hpp | C++ | src/Main/mixing.hpp | pwang234/lsms | 6044153b6138512093e457bdc0c15c699c831778 | [
"BSD-3-Clause"
] | 16 | 2018-04-03T15:35:47.000Z | 2022-03-01T03:19:23.000Z | src/Main/mixing.hpp | pwang234/lsms | 6044153b6138512093e457bdc0c15c699c831778 | [
"BSD-3-Clause"
] | 8 | 2019-07-30T13:59:18.000Z | 2022-03-31T17:43:35.000Z | src/Main/mixing.hpp | pwang234/lsms | 6044153b6138512093e457bdc0c15c699c831778 | [
"BSD-3-Clause"
] | 9 | 2018-06-30T00:30:48.000Z | 2022-01-31T09:14:29.000Z | /* -*- c-file-style: "bsd"; c-basic-offset: 2; indent-tabs-mode: nil -*- */
#ifndef LSMS_MIXING_H
#define LSMS_MIXING_H
#include "Real.hpp"
#include "SystemParameters.hpp"
#include "SingleSite/AtomData.hpp"
// #include "Communication/LSMSCommunication.hpp"
#include <vector>
#include <deque>
#include <cmath>
#include "LAPACK.hpp"
struct MixingParameters {
// Different mixing quantities and algorithms
static const int numQuantities = 5;
enum mixQuantity {no_mixing = 0, charge = 1, potential = 2, moment_magnitude = 3,
moment_direction = 4};
enum mixAlgorithm {noAlgorithm = 0, simple = 1, broyden = 2};
// These parameters specify the which quantity(ies) is (are) being mixed and which algorithm(s) to used.
// The correspondances of the indices are specified in mixQuantity.
// bool values:
// 0 : quantity is not used for mixing
// 1 : quantity is used for mixing
bool quantity[numQuantities];
mixAlgorithm algorithm[numQuantities];
Real mixingParameter[numQuantities];
};
#include "Communication/LSMSCommunication.hpp"
template <typename T>
void simpleMixing(T *fold, T* fnew, int n, Real alpha)
{
if(alpha>1.0) alpha = 1.0;
if(alpha<0.0) alpha = 0.0;
Real beta = 1.0 - alpha;
for(int i=0; i<n; i++)
fold[i] = alpha * fnew[i] + beta * fold[i];
}
class MomentMixing {
public:
virtual void update(LSMSCommunication &comm, LSMSSystemParameters &lsms, std::vector<AtomData> &as) = 0;
};
class Mixing {
public:
MomentMixing *momentMixing = nullptr;
virtual ~Mixing() = 0;
// virtual void updateChargeDensity(LSMSSystemParameters &lsms, AtomData &a) = 0;
virtual void updateChargeDensity(LSMSCommunication &comm, LSMSSystemParameters &lsms, std::vector<AtomData> &as) = 0;
// virtual void updatePotential(LSMSSystemParameters &lsms, AtomData &a) = 0;
virtual void updatePotential(LSMSCommunication &comm, LSMSSystemParameters &lsms, std::vector<AtomData> &as) = 0;
void updateMoments(LSMSCommunication &comm, LSMSSystemParameters &lsms, std::vector<AtomData> &as)
{ if(momentMixing != nullptr) momentMixing->update(comm, lsms, as);
else {
for(int i=0; i<as.size(); i++)
{
Real evecMagnitude = std::sqrt(as[i].evec[0] * as[i].evec[0] +
as[i].evec[1] * as[i].evec[1] +
as[i].evec[2] * as[i].evec[2]);
as[i].evecNew[0] = as[i].evec[0] / evecMagnitude;
as[i].evecNew[1] = as[i].evec[1] / evecMagnitude;
as[i].evecNew[2] = as[i].evec[2] / evecMagnitude;
}
}
}
virtual void prepare(LSMSCommunication &comm, LSMSSystemParameters &lsms, std::vector<AtomData> &as) = 0;
};
void setupMixing(MixingParameters &mix, Mixing* &mixing, int iprint);
#endif
| 33.035714 | 119 | 0.667387 | pwang234 |
8e029220884062c1ec415c51f364117ed200c02a | 495 | cpp | C++ | lib/dtrsm.cpp | langou/latl | df838fb44a1ef5c77b57bf60bd46eaeff8db3492 | [
"BSD-3-Clause-Open-MPI"
] | 6 | 2015-12-13T09:10:11.000Z | 2022-02-09T23:18:22.000Z | lib/dtrsm.cpp | langou/latl | df838fb44a1ef5c77b57bf60bd46eaeff8db3492 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | lib/dtrsm.cpp | langou/latl | df838fb44a1ef5c77b57bf60bd46eaeff8db3492 | [
"BSD-3-Clause-Open-MPI"
] | 2 | 2019-02-01T06:46:36.000Z | 2022-02-09T23:18:24.000Z | //
// dtrsm.cpp
// Linear Algebra Template Library
//
// Created by Rodney James on 1/1/13.
// Copyright (c) 2013 University of Colorado Denver. All rights reserved.
//
#include "blas.h"
#include "trsm.h"
using LATL::TRSM;
int dtrsm_(char& side, char& uplo, char& trans, char& diag, int &m, int &n, double &alpha, double *A, int &ldA, double *B, int &ldB)
{
int info=-TRSM<double>(side,uplo,trans,diag,m,n,alpha,A,ldA,B,ldB);
if(info>0)
xerbla_("DTRSM ",info);
return 0;
}
| 23.571429 | 132 | 0.650505 | langou |
8e03ea38d25c8473485c5684c18025236108bbe2 | 3,260 | cpp | C++ | source_code/system_sys/source_code/gui/_Sys_Abstract_Base_Wid.cpp | dabachma/ProMaIDes_src | 3fa6263c46f89abbdb407f2e1643843d54eb6ccc | [
"BSD-3-Clause"
] | null | null | null | source_code/system_sys/source_code/gui/_Sys_Abstract_Base_Wid.cpp | dabachma/ProMaIDes_src | 3fa6263c46f89abbdb407f2e1643843d54eb6ccc | [
"BSD-3-Clause"
] | null | null | null | source_code/system_sys/source_code/gui/_Sys_Abstract_Base_Wid.cpp | dabachma/ProMaIDes_src | 3fa6263c46f89abbdb407f2e1643843d54eb6ccc | [
"BSD-3-Clause"
] | null | null | null | //#include "_Sys_Abstract_Base_Wid.h"
#include "Sys_Headers_Precompiled.h"
#include <QScrollBar>
//Default constructor
_Sys_Abstract_Base_Wid::_Sys_Abstract_Base_Wid(QWidget *parent): _Sys_Data_Wid(parent) {
//Qt stuff
this->setupUi(this);
this->ptr_database=NULL;
this->edit_icon = QIcon(":hydro/Preferences");
this->edit_action = new QAction(this->edit_icon, "Edit", &this->context_menu);
this->context_menu.addAction(this->edit_action);
this->context_menu.insertSeparator(this->edit_action);
this->set_spinBox->setKeyboardTracking(false);
QObject::connect(this->edit_action, SIGNAL(triggered()), this, SLOT(show_as_dialog()));
}
//Default destructor
_Sys_Abstract_Base_Wid::~_Sys_Abstract_Base_Wid(void) {
}
//__________
//public
//Set the possibility to edit the data to the given state
void _Sys_Abstract_Base_Wid::set_edit_action_disabled(const bool state) {
this->edit_action->setDisabled(state);
}
//Common getter for editable state
bool _Sys_Abstract_Base_Wid::is_editable(void) {
return this->editable;
}
//Set the spinbox range in the head widget
void _Sys_Abstract_Base_Wid::set_head_spinBox_range(const int max, const int min) {
if (max > 0) {
this->set_spinBox->setEnabled(true);
this->set_spinBox->setRange(min, max);
QString qtext;
QString qnum;
qtext = "(" + qnum.setNum(max) + ")";
this->behind_spinBox_label->setText(qtext);
}
else {
this->set_spinBox->setEnabled(false);
}
}
//Set the head spin box value
void _Sys_Abstract_Base_Wid::set_head_spinBox_value(const int value){
this->set_spinBox->setValue(value);
QObject::connect(this->set_spinBox, SIGNAL(valueChanged(int )), this, SLOT(recieve_head_spin_box_changed(int )), Qt::QueuedConnection);
}
//Get a pointer to the head spin box
QSpinBox* _Sys_Abstract_Base_Wid::get_ptr_head_spinbox(void){
return this->set_spinBox;
}
//Set the spinbox text in the head widget
void _Sys_Abstract_Base_Wid::set_head_spinBox_text(const string text) {
QString qtext = text.c_str();
this->spinBox_label->setText(qtext);
}
//this method sets the text of the big label on top of the widget
void _Sys_Abstract_Base_Wid::set_headLabel_text(const string title) {
QString qtext = title.c_str();
this->head_label->setText(qtext);
}
//this method sets the icon on top of the widget (left)
void _Sys_Abstract_Base_Wid::set_headPixmap(const QPixmap pic) {
this->head_pixmap->setPixmap(pic);
}
//Set the child widget
void _Sys_Abstract_Base_Wid::set_child(QWidget *child) {
this->mainLayout->addWidget(child);
}
//Set current scroll bars position (vertical, horizontal)
void _Sys_Abstract_Base_Wid::set_current_scroll_bar(const int ver_pos, const int hor_pos){
if(this->scroll_area!=NULL){
this->scroll_area->verticalScrollBar()->setSliderPosition(ver_pos);
this->scroll_area->horizontalScrollBar()->setSliderPosition(hor_pos);
}
}
//_____________
//private slots
//Recieve if the head spin box value is changed
void _Sys_Abstract_Base_Wid::recieve_head_spin_box_changed(int index){
if(this->scroll_area==NULL){
emit send_change_widget(index, this->id_item, 0, 0);
}
else{
emit send_change_widget(index, this->id_item, this->scroll_area->verticalScrollBar()->sliderPosition(), this->scroll_area->horizontalScrollBar()->sliderPosition());
}
}
| 33.265306 | 166 | 0.767485 | dabachma |
8e0afdfe586781c6848373db847af2aa113a764e | 753 | cpp | C++ | txttobmp.cpp | DBFritz/ParticleDetections | cd05979c58b79c27259479e948c445867a7a838f | [
"MIT"
] | 1 | 2018-04-05T02:26:57.000Z | 2018-04-05T02:26:57.000Z | txttobmp.cpp | DBFritz/ParticleDetections | cd05979c58b79c27259479e948c445867a7a838f | [
"MIT"
] | null | null | null | txttobmp.cpp | DBFritz/ParticleDetections | cd05979c58b79c27259479e948c445867a7a838f | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include "rawImages.hpp"
#include "rawFilters.hpp"
int main(int argc, char *argv[])
{
using namespace std;
using namespace raw;
if (argc <= 2) {
cout << "usage: " << argv[0] << " /path/to/photo.txt /path/to/new/photo.bmp [minValue] [maxValue]";
return -1;
}
rawPhoto_t photo(argv[1]);
pixelValue_t minimum = photo.minimum();
pixelValue_t maximum = photo.maximum();
if (argc>=4) minimum = strtol(argv[3],NULL,10);
else cout << "Minimum: " << minimum;
if (argc>=5) maximum = strtol(argv[4],NULL,10);
else cout << "\tMaximum: " << maximum;
photo.toBitMap_grayscale(argv[2],minimum,maximum);
//photo.toBitMap_grayscale(argv[2]);
return 0;
}
| 25.1 | 107 | 0.616202 | DBFritz |
8e0ef9add2847f1e92644c7e0dfbc0dd17287b3c | 9,211 | cpp | C++ | HTTPProxy.cpp | kytvi2p/i2pd | 73d402525636276ac78aa92ea88535911e21928c | [
"BSD-3-Clause"
] | 4 | 2015-09-28T16:01:55.000Z | 2021-04-08T19:26:50.000Z | HTTPProxy.cpp | kytvi2p/i2pd | 73d402525636276ac78aa92ea88535911e21928c | [
"BSD-3-Clause"
] | null | null | null | HTTPProxy.cpp | kytvi2p/i2pd | 73d402525636276ac78aa92ea88535911e21928c | [
"BSD-3-Clause"
] | null | null | null | #include <cstring>
#include <cassert>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include <string>
#include <atomic>
#include "HTTPProxy.h"
#include "util.h"
#include "Identity.h"
#include "Streaming.h"
#include "Destination.h"
#include "ClientContext.h"
#include "I2PEndian.h"
#include "I2PTunnel.h"
namespace i2p
{
namespace proxy
{
static const size_t http_buffer_size = 8192;
class HTTPProxyHandler: public i2p::client::I2PServiceHandler, public std::enable_shared_from_this<HTTPProxyHandler>
{
private:
enum state
{
GET_METHOD,
GET_HOSTNAME,
GET_HTTPV,
GET_HTTPVNL, //TODO: fallback to finding HOst: header if needed
DONE
};
void EnterState(state nstate);
bool HandleData(uint8_t *http_buff, std::size_t len);
void HandleSockRecv(const boost::system::error_code & ecode, std::size_t bytes_transfered);
void Terminate();
void AsyncSockRead();
void HTTPRequestFailed(/*std::string message*/);
void ExtractRequest();
bool ValidateHTTPRequest();
void HandleJumpServices();
bool CreateHTTPRequest(uint8_t *http_buff, std::size_t len);
void SentHTTPFailed(const boost::system::error_code & ecode);
void HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream);
uint8_t m_http_buff[http_buffer_size];
std::shared_ptr<boost::asio::ip::tcp::socket> m_sock;
std::string m_request; //Data left to be sent
std::string m_url; //URL
std::string m_method; //Method
std::string m_version; //HTTP version
std::string m_address; //Address
std::string m_path; //Path
int m_port; //Port
state m_state;//Parsing state
public:
HTTPProxyHandler(HTTPProxyServer * parent, std::shared_ptr<boost::asio::ip::tcp::socket> sock) :
I2PServiceHandler(parent), m_sock(sock)
{ EnterState(GET_METHOD); }
~HTTPProxyHandler() { Terminate(); }
void Handle () { AsyncSockRead(); }
};
void HTTPProxyHandler::AsyncSockRead()
{
LogPrint(eLogDebug,"--- HTTP Proxy async sock read");
if(m_sock) {
m_sock->async_receive(boost::asio::buffer(m_http_buff, http_buffer_size),
std::bind(&HTTPProxyHandler::HandleSockRecv, shared_from_this(),
std::placeholders::_1, std::placeholders::_2));
} else {
LogPrint(eLogError,"--- HTTP Proxy no socket for read");
}
}
void HTTPProxyHandler::Terminate() {
if (Kill()) return;
if (m_sock)
{
LogPrint(eLogDebug,"--- HTTP Proxy close sock");
m_sock->close();
m_sock = nullptr;
}
Done(shared_from_this());
}
/* All hope is lost beyond this point */
//TODO: handle this apropriately
void HTTPProxyHandler::HTTPRequestFailed(/*HTTPProxyHandler::errTypes error*/)
{
static std::string response = "HTTP/1.0 500 Internal Server Error\r\nContent-type: text/html\r\nContent-length: 0\r\n";
boost::asio::async_write(*m_sock, boost::asio::buffer(response,response.size()),
std::bind(&HTTPProxyHandler::SentHTTPFailed, shared_from_this(), std::placeholders::_1));
}
void HTTPProxyHandler::EnterState(HTTPProxyHandler::state nstate)
{
m_state = nstate;
}
void HTTPProxyHandler::ExtractRequest()
{
LogPrint(eLogDebug,"--- HTTP Proxy method is: ", m_method, "\nRequest is: ", m_url);
std::string server="";
std::string port="80";
boost::regex rHTTP("http://(.*?)(:(\\d+))?(/.*)");
boost::smatch m;
std::string path;
if(boost::regex_search(m_url, m, rHTTP, boost::match_extra))
{
server=m[1].str();
if (m[2].str() != "") port=m[3].str();
path=m[4].str();
}
LogPrint(eLogDebug,"--- HTTP Proxy server is: ",server, " port is: ", port, "\n path is: ",path);
m_address = server;
m_port = boost::lexical_cast<int>(port);
m_path = path;
}
bool HTTPProxyHandler::ValidateHTTPRequest()
{
if ( m_version != "HTTP/1.0" && m_version != "HTTP/1.1" )
{
LogPrint(eLogError,"--- HTTP Proxy unsupported version: ", m_version);
HTTPRequestFailed(); //TODO: send right stuff
return false;
}
return true;
}
void HTTPProxyHandler::HandleJumpServices()
{
static const char * helpermark1 = "?i2paddresshelper=";
static const char * helpermark2 = "&i2paddresshelper=";
size_t addressHelperPos1 = m_path.rfind (helpermark1);
size_t addressHelperPos2 = m_path.rfind (helpermark2);
size_t addressHelperPos;
if (addressHelperPos1 == std::string::npos)
{
if (addressHelperPos2 == std::string::npos)
return; //Not a jump service
else
addressHelperPos = addressHelperPos2;
}
else
{
if (addressHelperPos2 == std::string::npos)
addressHelperPos = addressHelperPos1;
else if ( addressHelperPos1 > addressHelperPos2 )
addressHelperPos = addressHelperPos1;
else
addressHelperPos = addressHelperPos2;
}
auto base64 = m_path.substr (addressHelperPos + strlen(helpermark1));
base64 = i2p::util::http::urlDecode(base64); //Some of the symbols may be urlencoded
LogPrint (eLogDebug,"Jump service for ", m_address, " found at ", base64, ". Inserting to address book");
//TODO: this is very dangerous and broken. We should ask the user before doing anything see http://pastethis.i2p/raw/pn5fL4YNJL7OSWj3Sc6N/
//TODO: we could redirect the user again to avoid dirtiness in the browser
i2p::client::context.GetAddressBook ().InsertAddress (m_address, base64);
m_path.erase(addressHelperPos);
}
bool HTTPProxyHandler::CreateHTTPRequest(uint8_t *http_buff, std::size_t len)
{
ExtractRequest(); //TODO: parse earlier
if (!ValidateHTTPRequest()) return false;
HandleJumpServices();
m_request = m_method;
m_request.push_back(' ');
m_request += m_path;
m_request.push_back(' ');
m_request += m_version;
m_request.push_back('\r');
m_request.push_back('\n');
m_request.append("Connection: close\r\n");
m_request.append(reinterpret_cast<const char *>(http_buff),len);
return true;
}
bool HTTPProxyHandler::HandleData(uint8_t *http_buff, std::size_t len)
{
assert(len); // This should always be called with a least a byte left to parse
while (len > 0)
{
//TODO: fallback to finding HOst: header if needed
switch (m_state)
{
case GET_METHOD:
switch (*http_buff)
{
case ' ': EnterState(GET_HOSTNAME); break;
default: m_method.push_back(*http_buff); break;
}
break;
case GET_HOSTNAME:
switch (*http_buff)
{
case ' ': EnterState(GET_HTTPV); break;
default: m_url.push_back(*http_buff); break;
}
break;
case GET_HTTPV:
switch (*http_buff)
{
case '\r': EnterState(GET_HTTPVNL); break;
default: m_version.push_back(*http_buff); break;
}
break;
case GET_HTTPVNL:
switch (*http_buff)
{
case '\n': EnterState(DONE); break;
default:
LogPrint(eLogError,"--- HTTP Proxy rejected invalid request ending with: ", ((int)*http_buff));
HTTPRequestFailed(); //TODO: add correct code
return false;
}
break;
default:
LogPrint(eLogError,"--- HTTP Proxy invalid state: ", m_state);
HTTPRequestFailed(); //TODO: add correct code 500
return false;
}
http_buff++;
len--;
if (m_state == DONE)
return CreateHTTPRequest(http_buff,len);
}
return true;
}
void HTTPProxyHandler::HandleSockRecv(const boost::system::error_code & ecode, std::size_t len)
{
LogPrint(eLogDebug,"--- HTTP Proxy sock recv: ", len);
if(ecode)
{
LogPrint(eLogWarning," --- HTTP Proxy sock recv got error: ", ecode);
Terminate();
return;
}
if (HandleData(m_http_buff, len))
{
if (m_state == DONE)
{
LogPrint(eLogInfo,"--- HTTP Proxy requested: ", m_url);
GetOwner()->CreateStream (std::bind (&HTTPProxyHandler::HandleStreamRequestComplete,
shared_from_this(), std::placeholders::_1), m_address, m_port);
}
else
AsyncSockRead();
}
}
void HTTPProxyHandler::SentHTTPFailed(const boost::system::error_code & ecode)
{
if (!ecode)
Terminate();
else
{
LogPrint (eLogError,"--- HTTP Proxy Closing socket after sending failure because: ", ecode.message ());
Terminate();
}
}
void HTTPProxyHandler::HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream)
{
if (stream)
{
if (Kill()) return;
LogPrint (eLogInfo,"--- HTTP Proxy New I2PTunnel connection");
auto connection = std::make_shared<i2p::client::I2PTunnelConnection>(GetOwner(), m_sock, stream);
GetOwner()->AddHandler (connection);
connection->I2PConnect (reinterpret_cast<const uint8_t*>(m_request.data()), m_request.size());
Done(shared_from_this());
}
else
{
LogPrint (eLogError,"--- HTTP Proxy Issue when creating the stream, check the previous warnings for more info.");
HTTPRequestFailed(); // TODO: Send correct error message host unreachable
}
}
HTTPProxyServer::HTTPProxyServer(int port, std::shared_ptr<i2p::client::ClientDestination> localDestination):
TCPIPAcceptor(port, localDestination ? localDestination : i2p::client::context.GetSharedLocalDestination ())
{
}
std::shared_ptr<i2p::client::I2PServiceHandler> HTTPProxyServer::CreateHandler(std::shared_ptr<boost::asio::ip::tcp::socket> socket)
{
return std::make_shared<HTTPProxyHandler> (this, socket);
}
}
}
| 30.703333 | 140 | 0.685159 | kytvi2p |
8e14d135e6b5fcd11430de516e3b4204aab09577 | 1,179 | cpp | C++ | GazeTracker/GazeTracker_Qt/GazeTracker.cpp | bernhardrieder/GazeTracker | b468a03cb986a4950ee1d2a49df759e17a80c5cc | [
"MIT"
] | null | null | null | GazeTracker/GazeTracker_Qt/GazeTracker.cpp | bernhardrieder/GazeTracker | b468a03cb986a4950ee1d2a49df759e17a80c5cc | [
"MIT"
] | null | null | null | GazeTracker/GazeTracker_Qt/GazeTracker.cpp | bernhardrieder/GazeTracker | b468a03cb986a4950ee1d2a49df759e17a80c5cc | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "GazeTracker.h"
GazeTracker::GazeTracker(int argc, char* argv[]) : qApplication(argc, argv)
{
CreateDirectory(LPWSTR(std::wstring(L"C:/GazeTracker").c_str()), NULL);
CreateDirectory(LPWSTR(std::wstring(L"C:/GazeTracker/Output").c_str()), NULL);
CreateDirectory(LPWSTR(std::wstring(L"C:/GazeTracker/tmp").c_str()), NULL); //DONT CHANGE
CreateDirectory(LPWSTR(std::wstring(L"C:/GazeTracker/tmp/template_matching").c_str()), NULL); //DONT CHANGE - OR CHANGE AND CHANGE DIR IN FACEDETECTION TEMPLATE MATCHING strings
gt::DataTrackingSystem::GetInstance()->DefaultStorageFolder = "C:\\GazeTracker\\Output";
}
GazeTracker::~GazeTracker()
{
gt::DataTrackingSystem::GetInstance()->CloseFile();
}
void GazeTracker::StartApplication() const
{
gt::UISystem::GetInstance()->GetStartUI()->show();
//gt::UISystem::GetInstance()->GetGazeTrackerUI()->show();
}
void GazeTracker::StopApplication() const
{
}
bool GazeTracker::IsDetecting() const
{
return gt::GazeTrackerManager::GetInstance()->GetActiveState() == gt::Running; //should check if application is in config or running mode
}
int GazeTracker::exec() const
{
return qApplication.exec();
} | 31.026316 | 178 | 0.737913 | bernhardrieder |
8e14d6363768e8360a9e08995d1ef621c8b61e7a | 2,508 | cpp | C++ | beringei/lib/BucketUtils.cpp | pidb/Gorilla | 75c3002b179d99c8709323d605e7d4b53484035c | [
"BSD-3-Clause"
] | 2,780 | 2016-12-22T19:25:26.000Z | 2018-05-21T11:29:42.000Z | beringei/lib/BucketUtils.cpp | pidb/Gorilla | 75c3002b179d99c8709323d605e7d4b53484035c | [
"BSD-3-Clause"
] | 57 | 2016-12-23T09:22:18.000Z | 2018-05-04T06:26:48.000Z | beringei/lib/BucketUtils.cpp | pidb/Gorilla | 75c3002b179d99c8709323d605e7d4b53484035c | [
"BSD-3-Clause"
] | 254 | 2016-12-22T20:53:12.000Z | 2018-05-16T06:14:10.000Z | /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "BucketUtils.h"
#include <folly/Format.h>
#include <glog/logging.h>
DEFINE_int32(gorilla_shards, 100, "Number of maps for gorilla to use");
namespace facebook {
namespace gorilla {
uint32_t
BucketUtils::bucket(uint64_t unixTime, uint64_t windowSize, int shardId) {
if (unixTime < shardId * windowSize / FLAGS_gorilla_shards) {
LOG(ERROR) << folly::sformat(
"Shard: {}. Window size: {}. TS {} falls into a negative bucket",
shardId,
windowSize,
unixTime);
return 0;
}
return (uint32_t)(
(unixTime - (shardId * windowSize / FLAGS_gorilla_shards)) / windowSize);
}
uint64_t
BucketUtils::timestamp(uint32_t bucket, uint64_t windowSize, int shardId) {
return bucket * windowSize + (shardId * windowSize / FLAGS_gorilla_shards);
}
uint64_t BucketUtils::duration(uint32_t buckets, uint64_t windowSize) {
return buckets * windowSize;
}
uint32_t BucketUtils::buckets(uint64_t duration, uint64_t windowSize) {
return duration / windowSize;
}
uint64_t BucketUtils::floorTimestamp(
uint64_t unixTime,
uint64_t windowSize,
int shardId) {
return timestamp(bucket(unixTime, windowSize, shardId), windowSize, shardId);
}
uint64_t BucketUtils::ceilTimestamp(
uint64_t unixTime,
uint64_t windowSize,
int shardId) {
// Check against first timestamp to avoid underflow, should never happen.
auto firstTimestamp = timestamp(0, windowSize, shardId);
if (unixTime <= firstTimestamp) {
return firstTimestamp;
}
auto b = bucket(unixTime - 1, windowSize, shardId);
return timestamp(b + 1, windowSize, shardId);
}
uint32_t BucketUtils::alignedBucket(uint64_t unixTime, uint64_t windowSize) {
return (uint32_t)(unixTime / windowSize);
}
uint64_t BucketUtils::alignedTimestamp(uint32_t bucket, uint64_t windowSize) {
return bucket * windowSize;
}
uint64_t BucketUtils::floorAlignedTimestamp(
uint64_t unixTime,
uint64_t windowSize) {
return alignedTimestamp(alignedBucket(unixTime, windowSize), windowSize);
}
bool BucketUtils::isAlignedBucketTimestamp(
uint64_t unixTime,
uint64_t windowSize) {
return unixTime % windowSize == 0;
}
} // namespace gorilla
} // namespace facebook
| 28.179775 | 79 | 0.732057 | pidb |
8e1d27d157cca0f5c76c77c661ae3e821bd5b046 | 1,641 | hh | C++ | transformations/base/ViewHistBased.hh | gnafit/gna | c1a58dac11783342c97a2da1b19c97b85bce0394 | [
"MIT"
] | 5 | 2019-10-14T01:06:57.000Z | 2021-02-02T16:33:06.000Z | transformations/base/ViewHistBased.hh | gnafit/gna | c1a58dac11783342c97a2da1b19c97b85bce0394 | [
"MIT"
] | null | null | null | transformations/base/ViewHistBased.hh | gnafit/gna | c1a58dac11783342c97a2da1b19c97b85bce0394 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include "GNAObject.hh"
#include "GNAObjectBind1N.hh"
#include <boost/optional.hpp>
namespace GNA{
namespace GNAObjectTemplates{
template<typename FloatType>
class ViewHistBasedT: public GNAObjectBind1N<FloatType>,
public TransformationBind<ViewHistBasedT<FloatType>,FloatType,FloatType> {
private:
using BaseClass = GNAObjectT<FloatType,FloatType>;
using typename BaseClass::TypesFunctionArgs;
using typename BaseClass::FunctionArgs;
public:
using ViewHistBasedType = ViewHistBasedT<FloatType>;
using typename BaseClass::SingleOutput;
using TransformationDescriptor = typename BaseClass::TransformationDescriptorType;
using OutputDescriptor = typename BaseClass::OutputDescriptor;
ViewHistBasedT(FloatType threshold, FloatType ceiling);
ViewHistBasedT(SingleOutput& output, FloatType threshold, FloatType ceiling);
void set(SingleOutput& hist){
hist.single() >> this->transformations.front().inputs.front();
}
TransformationDescriptor add_transformation(const std::string& name="");
protected:
void histTypes(TypesFunctionArgs& fargs);
void types(TypesFunctionArgs& fargs);
void init();
boost::optional<FloatType> m_threshold;
boost::optional<FloatType> m_ceiling;
boost::optional<size_t> m_start;
boost::optional<size_t> m_len;
size_t m_full_length;
};
}
}
| 34.914894 | 104 | 0.645338 | gnafit |
8e26a0fcbb823784a5633a2804b8d1e894e4486b | 1,562 | cpp | C++ | packages/+GT/GenericTargetCode/source/GenericTarget/TargetTime.cpp | RobertDamerius/GenericTarget | 6b26793c2d580797ac8104ca5368987cbb570ef8 | [
"MIT"
] | 1 | 2021-02-02T09:01:24.000Z | 2021-02-02T09:01:24.000Z | packages/+GT/GenericTargetCode/source/GenericTarget/TargetTime.cpp | RobertDamerius/GenericTarget | 6b26793c2d580797ac8104ca5368987cbb570ef8 | [
"MIT"
] | null | null | null | packages/+GT/GenericTargetCode/source/GenericTarget/TargetTime.cpp | RobertDamerius/GenericTarget | 6b26793c2d580797ac8104ca5368987cbb570ef8 | [
"MIT"
] | 2 | 2021-02-02T09:01:45.000Z | 2021-10-02T13:08:16.000Z | #include <TargetTime.hpp>
TimeInfo::TimeInfo(){
nanoseconds = 0;
second = 0;
minute = 0;
hour = 0;
mday = 1;
mon = 0;
year = 0;
wday = 1;
yday = 0;
isdst = -1;
}
TimeInfo::TimeInfo(const TimeInfo& time){
this->nanoseconds = time.nanoseconds;
this->second = time.second;
this->minute = time.minute;
this->hour = time.hour;
this->mday = time.mday;
this->mon = time.mon;
this->year = time.year;
this->wday = time.wday;
this->yday = time.yday;
this->isdst = time.isdst;
}
TimeInfo::~TimeInfo(){}
TimeInfo& TimeInfo::operator=(const TimeInfo& rhs){
this->nanoseconds = rhs.nanoseconds;
this->second = rhs.second;
this->minute = rhs.minute;
this->hour = rhs.hour;
this->mday = rhs.mday;
this->mon = rhs.mon;
this->year = rhs.year;
this->wday = rhs.wday;
this->yday = rhs.yday;
this->isdst = rhs.isdst;
return *this;
}
TargetTime::TargetTime(){
model = 0.0;
ticks = 0;
simulation = 0.0;
unix = 0.0;
}
TargetTime::TargetTime(const TargetTime& time){
this->utc = time.utc;
this->local = time.local;
this->model = time.model;
this->ticks = time.ticks;
this->simulation = time.simulation;
this->unix = time.unix;
}
TargetTime::~TargetTime(){}
TargetTime& TargetTime::operator=(const TargetTime& rhs){
this->utc = rhs.utc;
this->local = rhs.local;
this->model = rhs.model;
this->ticks = rhs.ticks;
this->simulation = rhs.simulation;
this->unix = rhs.unix;
return *this;
}
| 21.108108 | 57 | 0.597951 | RobertDamerius |
8e29bd542577cb6885007975f0ac9c79f5b4dcee | 1,010 | cpp | C++ | 1.cpp | nitin-maharana/CODE | 126826c36d8b7fa578c8e78e570117c53327e461 | [
"MIT"
] | 1 | 2016-03-05T11:40:39.000Z | 2016-03-05T11:40:39.000Z | 1.cpp | nitin-maharana/CODE | 126826c36d8b7fa578c8e78e570117c53327e461 | [
"MIT"
] | null | null | null | 1.cpp | nitin-maharana/CODE | 126826c36d8b7fa578c8e78e570117c53327e461 | [
"MIT"
] | null | null | null | /*
* Written by Nitin Kumar Maharana
* [email protected]
*/
#include <iostream>
using namespace std;
template <class T>
struct node
{
T val;
struct node *next;
};
template <class T>
class Stack
{
struct node<T> *top;
public:
Stack()
{
top = nullptr;
}
void push(T item)
{
struct node<T> *t;
t = new struct node<T>;
t->val = item;
t->next = top;
top = t;
}
void pop(void)
{
if(empty())
throw "There are no items in stack to pop!!!";
struct node<T> *t;
t = top;
top = top->next;
delete t;
}
T peek(void)
{
if(empty())
throw "There are no items in stack to peek!!!";
T item;
item = top->val;
return item;
}
bool empty(void)
{
return top == nullptr ? true : false;
}
};
int main(void)
{
Stack<int> s;
s.push(1);
s.push(2);
s.push(3);
cout << s.peek() << endl;
s.pop();
cout << s.peek() << endl;
cout << s.empty() << endl;
s.pop();
s.pop();
cout << s.empty() << endl;
return 0;
}
| 11.609195 | 51 | 0.541584 | nitin-maharana |
8e2dcdcaad06eec9461def636d8c13e1cabd2840 | 1,537 | cpp | C++ | Full.cpp | satans404/Project-2--CS205-C-C-Program-Design | 53f555145858bfa58564c57eee2706be60becf78 | [
"Apache-2.0"
] | null | null | null | Full.cpp | satans404/Project-2--CS205-C-C-Program-Design | 53f555145858bfa58564c57eee2706be60becf78 | [
"Apache-2.0"
] | null | null | null | Full.cpp | satans404/Project-2--CS205-C-C-Program-Design | 53f555145858bfa58564c57eee2706be60becf78 | [
"Apache-2.0"
] | null | null | null | #include "Full.h"
#include "Matrix.h"
using namespace std;
Full::Full():Layer(Layer::Type::Full)
{
this->inX=0;
this->inY=0;
this->inDimX=0;
this->inDimY=0;
this->outX=0;
this->outY=0;
this->outDimX=0;
this->outDimY=0;
this->pad=0;
}
Full::Full(int inDimX,int inDimY,int inX,int inY):Layer(Layer::Type::Full)
{
this->inX=inX;
this->inY=inY;
this->inDimX=inDimX;
this->inDimY=inDimY;
this->outX=1;
this->outY=1;
this->outDimX=inDimX;
this->outDimY=1;
this->pad=0;
this->result=Matrix(this->outDimX,this->outDimY,1,1);
}
void Full::setArgs(Matrix* bias, Matrix* kernal)
{
this->bias=bias;
this->kernal=kernal;
}
void Full::work(Matrix &input)
{
if(this->bias== nullptr || this->kernal== nullptr)
{
throw "Error!";
}
else
{
this->work(input,*(this->kernal),*(this->bias));
}
}
void Full::work(Matrix& input,Matrix& kernal,Matrix& bias)
{
int len=input.getLen(),start=0,len2=kernal.getLen();
float ans=0;
for(int t=0;t<this->inDimX;t++)
{
ans=0;
for(int i=0;i<len;i++)
{
ans+=input.getNum(i)*kernal.getNum(t*len+i);
}
this->result.setNum(t,0,0,0,ans+bias.getNum(t));
}
}
Matrix& Full::getResult()
{
return this->result;
}
void Full::display()
{
cout<<"Full: "<<endl;
this->result.display();
}
void Full::structure()
{
cout<<"Full"<<endl;
}
| 18.975309 | 75 | 0.540664 | satans404 |
8e2e58e183d0f3a0a3d3db1b893fa692e22e758c | 3,126 | cpp | C++ | Boss2D/element/boss_matrix.cpp | Yash-Wasalwar-07/Boss2D | 37c5ba0f1c83c89810359a207cabfa0905f803d2 | [
"MIT"
] | null | null | null | Boss2D/element/boss_matrix.cpp | Yash-Wasalwar-07/Boss2D | 37c5ba0f1c83c89810359a207cabfa0905f803d2 | [
"MIT"
] | null | null | null | Boss2D/element/boss_matrix.cpp | Yash-Wasalwar-07/Boss2D | 37c5ba0f1c83c89810359a207cabfa0905f803d2 | [
"MIT"
] | null | null | null | #include <boss.hpp>
#include "boss_matrix.hpp"
namespace BOSS
{
Matrix::Matrix()
{
m11 = 1;
m12 = 0;
m21 = 0;
m22 = 1;
dx = 0;
dy = 0;
}
Matrix::Matrix(const Matrix& rhs)
{
operator=(rhs);
}
Matrix::Matrix(float m11, float m12, float m21, float m22, float dx, float dy)
{
this->m11 = m11;
this->m12 = m12;
this->m21 = m21;
this->m22 = m22;
this->dx = dx;
this->dy = dy;
}
Matrix::~Matrix()
{
}
Matrix& Matrix::operator=(const Matrix& rhs)
{
m11 = rhs.m11;
m12 = rhs.m12;
m21 = rhs.m21;
m22 = rhs.m22;
dx = rhs.dx;
dy = rhs.dy;
return *this;
}
Matrix& Matrix::operator*=(const Matrix& rhs)
{
const float New_m11 = m11 * rhs.m11 + m12 * rhs.m21;
const float New_m12 = m11 * rhs.m12 + m12 * rhs.m22;
const float New_m21 = m21 * rhs.m11 + m22 * rhs.m21;
const float New_m22 = m21 * rhs.m12 + m22 * rhs.m22;
const float New_dx = dx * rhs.m11 + dy * rhs.m21 + rhs.dx;
const float New_dy = dx * rhs.m12 + dy * rhs.m22 + rhs.dy;
m11 = New_m11;
m12 = New_m12;
m21 = New_m21;
m22 = New_m22;
dx = New_dx;
dy = New_dy;
return *this;
}
Matrix Matrix::operator*(const Matrix& rhs) const
{
return Matrix(*this).operator*=(rhs);
}
bool Matrix::operator==(const Matrix& rhs) const
{
return (m11 == rhs.m11 && m12 == rhs.m12 && m21 == rhs.m21 && m22 == rhs.m22
&& dx == rhs.dx && dy == rhs.dy);
}
bool Matrix::operator!=(const Matrix& rhs) const
{
return !operator==(rhs);
}
void Matrix::AddOffset(const float x, const float y)
{
operator*=(Matrix(1, 0, 0, 1, x, y));
}
void Matrix::AddRotate(const float angle, const float cx, const float cy)
{
const float c = Math::Cos(angle);
const float s = Math::Sin(angle);
operator*=(Matrix(c, s, -s, c, (1 - c) * cx + s * cy, (1 - c) * cy - s * cx));
}
void Matrix::AddScale(const float w, const float h, const float cx, const float cy)
{
operator*=(Matrix(w, 0, 0, h, (1 - w) * cx, (1 - h) * cy));
}
void Matrix::AddByTouch(const float a1x, const float a1y, const float a2x, const float a2y,
const float b1x, const float b1y, const float b2x, const float b2y)
{
const float amx = (a1x + a2x) / 2;
const float amy = (a1y + a2y) / 2;
const float bmx = (b1x + b2x) / 2;
const float bmy = (b1y + b2y) / 2;
const float rotate = Math::Atan(b1x - bmx, b1y - bmy) - Math::Atan(a1x - amx, a1y - amy);
const float scale = Math::Distance(b1x, b1y, b2x, b2y)
/ Math::Distance(a1x, a1y, a2x, a2y);
AddOffset(bmx - amx, bmy - amy);
AddRotate(rotate, bmx, bmy);
AddScale(scale, scale, bmx, bmy);
}
}
| 28.162162 | 98 | 0.493282 | Yash-Wasalwar-07 |
8e33160405802224bf3cf0d56c8a29ca37336602 | 2,887 | hpp | C++ | libs/dmlf/include/dmlf/colearn/update_store.hpp | marcuswin/ledger | b79c5c4e7e92ff02ea4328fcc0885bf8ded2b8b2 | [
"Apache-2.0"
] | 1 | 2019-09-11T09:46:04.000Z | 2019-09-11T09:46:04.000Z | libs/dmlf/include/dmlf/colearn/update_store.hpp | qati/ledger | e05a8f2d62ea1b79a704867d220cf307ef6b93b9 | [
"Apache-2.0"
] | null | null | null | libs/dmlf/include/dmlf/colearn/update_store.hpp | qati/ledger | e05a8f2d62ea1b79a704867d220cf307ef6b93b9 | [
"Apache-2.0"
] | 1 | 2019-09-19T12:38:46.000Z | 2019-09-19T12:38:46.000Z | #pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//------------------------------------------------------------------------------
#include "dmlf/colearn/update_store_interface.hpp"
#include <queue>
#include <unordered_set>
#include <utility>
#include <vector>
#include "core/mutex.hpp"
namespace fetch {
namespace dmlf {
namespace colearn {
class UpdateStore : public UpdateStoreInterface
{
public:
UpdateStore() = default;
~UpdateStore() override = default;
UpdateStore(UpdateStore const &other) = delete;
UpdateStore &operator=(UpdateStore const &other) = delete;
void PushUpdate(ColearnURI const &uri, Data &&data, Metadata &&metadata) override;
void PushUpdate(Algorithm const &algo, UpdateType type, Data &&data, Source source,
Metadata &&metadata) override;
UpdatePtr GetUpdate(ColearnURI const &uri, Consumer consumer = "learner0") override;
UpdatePtr GetUpdate(Algorithm const &algo, UpdateType const &type,
Consumer consumer = "learner0") override;
UpdatePtr GetUpdate(ColearnURI const &uri, Criteria criteria,
Consumer consumer = "learner0") override;
UpdatePtr GetUpdate(Algorithm const &algo, UpdateType const &type, Criteria criteria,
Consumer consumer = "learner0") override;
std::size_t GetUpdateCount() const override;
std::size_t GetUpdateCount(Algorithm const &algo, UpdateType const &type) const override;
private:
using QueueId = std::string;
QueueId Id(Algorithm const &algo, UpdateType const &type) const;
Criteria Lifo = [](UpdatePtr const &update) -> double {
return static_cast<double>(-update->TimeSinceCreation().count());
};
using Mutex = fetch::Mutex;
using Lock = std::unique_lock<Mutex>;
using Store = std::vector<UpdatePtr>;
using AlgoMap = std::unordered_map<QueueId, Store>;
using Fingerprint = Update::Fingerprint;
using UpdateConsumers = std::unordered_set<Consumer>;
AlgoMap algo_map_;
mutable Mutex global_m_;
std::unordered_map<Fingerprint, UpdateConsumers> consumed_;
};
} // namespace colearn
} // namespace dmlf
} // namespace fetch
| 35.641975 | 91 | 0.656044 | marcuswin |
8e347e5be5d2d3f3c9e4cf2410cc925090f906a3 | 4,771 | cpp | C++ | test/network/TcpClient.cpp | kubasejdak/utils | efc491e5f682f365bf4752a26f086910c89d6b25 | [
"BSD-2-Clause"
] | null | null | null | test/network/TcpClient.cpp | kubasejdak/utils | efc491e5f682f365bf4752a26f086910c89d6b25 | [
"BSD-2-Clause"
] | null | null | null | test/network/TcpClient.cpp | kubasejdak/utils | efc491e5f682f365bf4752a26f086910c89d6b25 | [
"BSD-2-Clause"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////////////
///
/// @file
/// @author Kuba Sejdak
/// @copyright BSD 2-Clause License
///
/// Copyright (c) 2021-2021, Kuba Sejdak <[email protected]>
/// All rights reserved.
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions are met:
///
/// 1. Redistributions of source code must retain the above copyright notice, this
/// list of conditions and the following disclaimer.
///
/// 2. Redistributions in binary form must reproduce the above copyright notice,
/// this list of conditions and the following disclaimer in the documentation
/// and/or other materials provided with the distribution.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
/// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
/// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
/// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
/// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
/// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
/// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
/// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
///
/////////////////////////////////////////////////////////////////////////////////////
#include <utils/network/Error.hpp>
#include <utils/network/TcpClient.hpp>
#include <utils/network/TcpServer.hpp>
#include <catch2/catch.hpp>
#include <cstdint>
#include <vector>
TEST_CASE("1. Create TcpClient", "[unit][TcpClient]")
{
SECTION("1.1. Client is uninitialized") { utils::network::TcpClient client; }
SECTION("1.2. Client is initialized")
{
constexpr int cPort = 10101;
utils::network::TcpClient client("localhost", cPort);
}
}
TEST_CASE("2. Moving TcpClient around", "[unit][TcpClient]")
{
constexpr int cPort = 10101;
utils::network::TcpServer server(cPort);
auto error = server.start();
REQUIRE(!error);
utils::network::TcpClient client1("localhost", cPort);
utils::network::TcpClient client2(std::move(client1));
error = client2.connect();
REQUIRE(!error);
}
TEST_CASE("3. Performing operations in incorrect TcpClient state", "[unit][TcpClient]")
{
constexpr int cPort = 10101;
utils::network::TcpClient client("localhost", cPort);
SECTION("3.1. No remote endpoint")
{
auto error = client.connect();
REQUIRE(error == utils::network::Error::eConnectError);
}
SECTION("3.2. Client is already running")
{
utils::network::TcpServer server(cPort);
auto error = server.start();
REQUIRE(!error);
error = client.connect();
REQUIRE(!error);
error = client.connect();
REQUIRE(error == utils::network::Error::eClientRunning);
}
SECTION("3.3. Bad endpoint address")
{
auto error = client.connect("badAddress", cPort);
REQUIRE(error == utils::network::Error::eInvalidArgument);
}
SECTION("3.4. Getting local/remote endpoints when client is not connected")
{
auto localEndpoint = client.localEndpoint();
REQUIRE(localEndpoint.ip.empty());
REQUIRE(localEndpoint.port == 0);
REQUIRE(!localEndpoint.name);
auto remoteEndpoint = client.remoteEndpoint();
REQUIRE(remoteEndpoint.ip.empty());
REQUIRE(remoteEndpoint.port == 0);
REQUIRE(!remoteEndpoint.name);
}
SECTION("3.5. Reading when client is not connected")
{
constexpr std::size_t cSize = 15;
std::vector<std::uint8_t> bytes;
auto error = client.read(bytes, cSize);
REQUIRE(error == utils::network::Error::eClientDisconnected);
bytes.reserve(cSize);
std::size_t actualReadSize{};
error = client.read(bytes.data(), cSize, actualReadSize);
REQUIRE(error == utils::network::Error::eClientDisconnected);
}
SECTION("3.6. Writing when client is not connected")
{
std::vector<std::uint8_t> bytes{1, 2, 3};
auto error = client.write({1, 2, 3});
REQUIRE(error == utils::network::Error::eClientDisconnected);
error = client.write(bytes.data(), bytes.size());
REQUIRE(error == utils::network::Error::eClientDisconnected);
error = client.write("Hello world");
REQUIRE(error == utils::network::Error::eClientDisconnected);
}
}
| 35.340741 | 87 | 0.646405 | kubasejdak |
8e39bbf4687cfa58e7db8d9236e27f8c64514864 | 5,443 | cpp | C++ | solver.cpp | georgekouzi/solver-a | 594ea86eda750d20f6befe78b629a5c6bf06c6da | [
"MIT"
] | null | null | null | solver.cpp | georgekouzi/solver-a | 594ea86eda750d20f6befe78b629a5c6bf06c6da | [
"MIT"
] | null | null | null | solver.cpp | georgekouzi/solver-a | 594ea86eda750d20f6befe78b629a5c6bf06c6da | [
"MIT"
] | null | null | null | #include <iostream>
#include "solver.hpp"
using namespace std;
namespace solver{
double solve(RealVariable t){
return 1.0;
}
complex<double> solve(ComplexVariable) {
return complex<double>();
}
////////////////////////// func ComplexVariable/////////////////////////
///////////////////////////operator ==////////////////////////////////////////
ComplexVariable operator==(double num,ComplexVariable& t){
return ComplexVariable();
}
// ComplexVariable operator==(ComplexVariable& t,double num){
// return ComplexVariable();
// }
// ComplexVariable operator==(const std::complex<double>,const double num){
// return ComplexVariable();
// }
// ComplexVariable operator==(ComplexVariable& t,ComplexVariable& d){
// return ComplexVariable();
// }
/////////////////////// opertors+///////////////////////////
ComplexVariable operator+(double num,ComplexVariable t){
return ComplexVariable();
}
// ComplexVariable operator+(ComplexVariable& t,double num){
// return ComplexVariable();
// }
// ComplexVariable operator+(ComplexVariable& t,ComplexVariable& d){
// return ComplexVariable();
// }
/////////////////////// opertors*///////////////////////////
ComplexVariable operator*(double num,ComplexVariable& t){
cout<<"num-op:*: "<<num<<endl;
return ComplexVariable();
}
// ComplexVariable operator*(ComplexVariable& t,double num){
// return ComplexVariable();
// }
// ComplexVariable operator*(ComplexVariable& t,ComplexVariable& d){
// return ComplexVariable();
// }
////////////////////////////operator-///////////////////
ComplexVariable operator-(double num,ComplexVariable& t){
return ComplexVariable();
}
// ComplexVariable operator-(ComplexVariable& t,double num){
// return ComplexVariable();
// }
// ComplexVariable operator-(ComplexVariable& t,ComplexVariable& d){
// return ComplexVariable();
// }
/////////////////////// opertors^///////////////////////////
// ComplexVariable operator^(double num,ComplexVariable& t){
// return ComplexVariable();
// }
ComplexVariable operator^(ComplexVariable& t,double num){
return ComplexVariable();
}
// ComplexVariable operator^(ComplexVariable& t,ComplexVariable& d){
// return ComplexVariable();
// }
/////////////////////// opertors/ ///////////////////////////
// ComplexVariable operator/(double num,ComplexVariable& t){
// return ComplexVariable();
// }
// ComplexVariable operator/(ComplexVariable& t,double num){
// return ComplexVariable();
// }
// ComplexVariable operator/(ComplexVariable& t,ComplexVariable& d){
// return ComplexVariable();
// }
////////////////////////// func RealVariable/////////////////////////
///////////////////////////operator ==////////////////////////////////////////
// RealVariable operator ==(double& num,double num1){
// return RealVariable();
// }
RealVariable operator ==(double num,RealVariable& t){
return RealVariable();
}
// RealVariable operator ==(RealVariable& t,double num){
// return RealVariable();
// }
// RealVariable operator ==(RealVariable& t,RealVariable& d){
// return RealVariable();
// }
/////////////////////// opertors+///////////////////////////
RealVariable operator+(double num,RealVariable& t){
cout<<"double-num-op:+ "<<num<<endl;
return RealVariable(t._a,t._b,t._c+num);
}
// RealVariable operator+(RealVariable& t,double num){
// cout<<"RealVariable-num-op:+: "<<num<<endl;
// return RealVariable();
// }
// RealVariable operator+(RealVariable& t,RealVariable& d){
// return RealVariable();
// }
////////////////////////////operator-///////////////////
RealVariable operator-(double num,RealVariable& t){
return RealVariable();
}
// RealVariable operator-(RealVariable& t,int num){
// return RealVariable();
// }
// RealVariable operator-(RealVariable& t,RealVariable& d){
// return RealVariable();
// }
////////////////////////operator ^//////////////////
// RealVariable operator^(double num,RealVariable& t){
// return RealVariable();
// }
RealVariable operator^(RealVariable& t,double num){
return RealVariable();
}
// RealVariable operator^(RealVariable& t,RealVariable& d){
// return RealVariable();
// }
/////////////////////// operator/ //////////////
// RealVariable operator/(double num,RealVariable& t){
// return RealVariable();
// }
// RealVariable operator/(RealVariable& t,double num){
// return RealVariable();
// }
// RealVariable operator/(RealVariable& t,RealVariable& d){
// return RealVariable();
// }
////////////////////////operator*////////////////////
RealVariable operator*(double num, RealVariable& t){
cout<<"-00-double-num-op:*: "<<endl;
return RealVariable(t._a,t._b+num-1,t._c);
}
// RealVariable operator*(RealVariable& t,double num){
// return RealVariable();
// }
// RealVariable operator*(RealVariable& t,RealVariable& d){
// return RealVariable();
// }
}; | 28.952128 | 80 | 0.534815 | georgekouzi |
8e3c304af56aa9d35b80d3624e903c87bb898124 | 1,515 | cpp | C++ | libz/types/real64.cpp | kmc7468/zlang | 08f9ba5dab502224bea5baa6f7a78c546094b7d0 | [
"MIT"
] | 5 | 2017-01-11T03:20:57.000Z | 2017-01-15T11:20:30.000Z | libz/types/real64.cpp | kmc7468/zlang | 08f9ba5dab502224bea5baa6f7a78c546094b7d0 | [
"MIT"
] | null | null | null | libz/types/real64.cpp | kmc7468/zlang | 08f9ba5dab502224bea5baa6f7a78c546094b7d0 | [
"MIT"
] | null | null | null | #include "real64.hpp"
namespace libz::types
{
int real64::compare(const instance& ins) const
{
if (ins.type() == type::real64)
{
const real64& ins_conv = (const real64&)ins;
if (this->m_data == ins_conv.m_data) return 0;
else if (this->m_data > ins_conv.m_data) return 1;
else return -1;
}
throw exces::invalid_call();
}
ptr<instance> real64::add(const instance& ins) const
{
if (ins.type() == type::real64)
{
return std::make_shared<real64>(this->m_data + ((const real64&)ins).m_data);
}
throw exces::invalid_call();
}
ptr<instance> real64::sub(const instance& ins) const
{
if (ins.type() == type::real64)
{
return std::make_shared<real64>(this->m_data - ((const real64&)ins).m_data);
}
throw exces::invalid_call();
}
ptr<instance> real64::mul(const instance& ins) const
{
if (ins.type() == type::real64)
{
return std::make_shared<real64>(this->m_data * ((const real64&)ins).m_data);
}
throw exces::invalid_call();
}
ptr<instance> real64::div(const instance& ins) const
{
if (ins.type() == type::real64)
{
return std::make_shared<real64>(this->m_data / ((const real64&)ins).m_data);
}
throw exces::invalid_call();
}
ptr<instance> real64::mod(const instance& ins) const
{
if (ins.type() == type::real64)
{
return std::make_shared<real64>(fmod(this->m_data, ((const real64&)ins).m_data));
}
throw exces::invalid_call();
}
ptr<instance> real64::sign() const
{
return std::make_shared<real64>(-this->m_data);
}
} | 22.61194 | 84 | 0.648185 | kmc7468 |
8e40af3902e91b0044e56e6e8e3b1f00f27d7706 | 1,734 | hpp | C++ | openscenario/openscenario_interpreter/include/openscenario_interpreter/syntax/infrastructure_action.hpp | autocore-ai/scenario_simulator_v2 | bb9569043e20649f0e4390e9225b6bb7b4de10b6 | [
"Apache-2.0"
] | null | null | null | openscenario/openscenario_interpreter/include/openscenario_interpreter/syntax/infrastructure_action.hpp | autocore-ai/scenario_simulator_v2 | bb9569043e20649f0e4390e9225b6bb7b4de10b6 | [
"Apache-2.0"
] | null | null | null | openscenario/openscenario_interpreter/include/openscenario_interpreter/syntax/infrastructure_action.hpp | autocore-ai/scenario_simulator_v2 | bb9569043e20649f0e4390e9225b6bb7b4de10b6 | [
"Apache-2.0"
] | null | null | null | // Copyright 2015-2020 Tier IV, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef OPENSCENARIO_INTERPRETER__SYNTAX__INFRASTRUCTURE_ACTION_HPP_
#define OPENSCENARIO_INTERPRETER__SYNTAX__INFRASTRUCTURE_ACTION_HPP_
#include <openscenario_interpreter/syntax/traffic_signal_action.hpp>
#include <utility>
namespace openscenario_interpreter
{
inline namespace syntax
{
/* ---- InfrastructureAction ---------------------------------------------------
*
* <xsd:complexType name="InfrastructureAction">
* <xsd:all>
* <xsd:element name="TrafficSignalAction" type="TrafficSignalAction"/>
* </xsd:all>
* </xsd:complexType>
*
* -------------------------------------------------------------------------- */
struct InfrastructureAction : public ComplexType
{
template <typename... Ts>
explicit InfrastructureAction(Ts &&... xs)
: ComplexType(
readElement<TrafficSignalAction>("TrafficSignalAction", std::forward<decltype(xs)>(xs)...))
{
}
bool endsImmediately() const { return as<TrafficSignalAction>().endsImmediately(); }
};
} // namespace syntax
} // namespace openscenario_interpreter
#endif // OPENSCENARIO_INTERPRETER__SYNTAX__INFRASTRUCTURE_ACTION_HPP_
| 35.387755 | 97 | 0.700115 | autocore-ai |
8e4161ac8b1ff3c0ea278995007a8a776e1d52d0 | 3,909 | cpp | C++ | persist/tests/test_core/test_fsm/test_fsl.cpp | ketgo/persist | 623a5c32a9a0fd3e43987421aa1f91ab8284d356 | [
"MIT"
] | null | null | null | persist/tests/test_core/test_fsm/test_fsl.cpp | ketgo/persist | 623a5c32a9a0fd3e43987421aa1f91ab8284d356 | [
"MIT"
] | 11 | 2020-09-30T07:33:10.000Z | 2021-05-01T05:59:13.000Z | persist/tests/test_core/test_fsm/test_fsl.cpp | ketgo/persist | 623a5c32a9a0fd3e43987421aa1f91ab8284d356 | [
"MIT"
] | null | null | null | /**
* test_fsl.cpp - Persist
*
* Copyright 2021 Ketan Goyal
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* Free space list unit tests.
*/
#include <gtest/gtest.h>
#include <memory>
#include <string>
#include <persist/core/fsm/fsl.hpp>
#include <persist/core/page/creator.hpp>
#include <persist/core/storage/creator.hpp>
#include "persist/test/simple_page.hpp"
using namespace persist;
using namespace persist::test;
class FSLTestFixture : public ::testing::Test {
protected:
ByteBuffer input;
const size_t cache_size = 2;
const std::set<PageId> free_pages = {1, 2, 3};
const std::string path = "test_fsl_manager";
const PageId fsl_page_id = 1;
PageId full_page_id, empty_page_id_1, empty_page_id_2;
std::unique_ptr<FSLManager> fsl_manager;
std::unique_ptr<Storage<FSLPage>> storage;
std::unique_ptr<FSLPage> fsl_page;
std::unique_ptr<SimplePage> full_page, empty_page_1, empty_page_2;
void SetUp() override {
// Setup FSL Storage
storage = persist::CreateStorage<FSLPage>("file://" + path);
// Setup FSL page
fsl_page = persist::CreatePage<FSLPage>(1, DEFAULT_PAGE_SIZE);
fsl_page->free_pages = free_pages;
Insert();
// Setup FSL Manager
fsl_manager = std::make_unique<FSLManager>(*storage, cache_size);
fsl_manager->Start();
// Setup empty page
empty_page_id_1 = fsl_page->GetMaxPageId();
empty_page_1 =
persist::CreatePage<SimplePage>(empty_page_id_1, DEFAULT_PAGE_SIZE);
empty_page_id_2 = fsl_page->GetMaxPageId() + 1;
empty_page_2 =
persist::CreatePage<SimplePage>(empty_page_id_2, DEFAULT_PAGE_SIZE);
// Setup full page
full_page_id = 3;
full_page =
persist::CreatePage<SimplePage>(full_page_id, DEFAULT_PAGE_SIZE);
ByteBuffer record(full_page->GetFreeSpaceSize(Operation::INSERT), 'A');
full_page->SetRecord(record);
}
void TearDown() override {
storage->Remove();
fsl_manager->Stop();
}
private:
/**
* @brief Insert test data
*/
void Insert() {
storage->Open();
storage->Write(*fsl_page);
storage->Close();
}
};
TEST_F(FSLTestFixture, TestManagerGetPageId) {
ASSERT_EQ(fsl_manager->GetPageId(0), 3);
}
TEST_F(FSLTestFixture, TestManagerEmptyPage) {
fsl_manager->Manage(*empty_page_1);
ASSERT_EQ(storage->GetPageCount(), 1);
ASSERT_EQ(fsl_manager->GetPageId(0), empty_page_id_1);
// Test duplicate
fsl_manager->Manage(*empty_page_1);
ASSERT_EQ(storage->GetPageCount(), 1);
ASSERT_EQ(fsl_manager->GetPageId(0), empty_page_id_1);
// Test entry in new FSLPage
fsl_manager->Manage(*empty_page_2);
ASSERT_EQ(storage->GetPageCount(), 2);
ASSERT_EQ(fsl_manager->GetPageId(0), empty_page_id_2);
}
TEST_F(FSLTestFixture, TestManagerFullPage) {
fsl_manager->Manage(*full_page);
ASSERT_EQ(storage->GetPageCount(), 1);
ASSERT_EQ(fsl_manager->GetPageId(0), 2);
}
| 30.779528 | 80 | 0.724482 | ketgo |
8e41825b206c4b4d2de955950434199dd3f3720b | 4,864 | cpp | C++ | ige/src/plugin/physics/bullet3/BulletWorld.cpp | Arcahub/ige | b9f61209c924c7b683d2429a07e76251e6eb7b1b | [
"MIT"
] | 3 | 2021-06-05T00:36:50.000Z | 2022-02-27T10:23:53.000Z | ige/src/plugin/physics/bullet3/BulletWorld.cpp | Arcahub/ige | b9f61209c924c7b683d2429a07e76251e6eb7b1b | [
"MIT"
] | 11 | 2021-05-08T22:00:24.000Z | 2021-11-11T22:33:43.000Z | ige/src/plugin/physics/bullet3/BulletWorld.cpp | Arcahub/ige | b9f61209c924c7b683d2429a07e76251e6eb7b1b | [
"MIT"
] | 4 | 2021-05-20T12:41:23.000Z | 2021-11-09T14:19:18.000Z | #include "igepch.hpp"
#include "BulletGhostObject.hpp"
#include "BulletRigidBody.hpp"
#include "BulletWorld.hpp"
#include "ige/ecs/Entity.hpp"
#include "ige/ecs/World.hpp"
#include "ige/plugin/TransformPlugin.hpp"
#include "ige/plugin/physics/Constraint.hpp"
#include "ige/plugin/physics/GhostObject.hpp"
#include "ige/plugin/physics/PhysicsWorld.hpp"
#include "ige/plugin/physics/RigidBody.hpp"
using ige::bt::BulletGhostObject;
using ige::bt::BulletWorld;
using ige::ecs::EntityId;
using ige::ecs::World;
using ige::plugin::physics::Constraint;
using ige::plugin::physics::GhostObject;
using ige::plugin::physics::PhysicsWorld;
using ige::plugin::physics::RigidBody;
using ige::plugin::transform::Transform;
BulletWorld::BulletWorld(btVector3 gravity)
: m_dispatcher(&m_collision_config)
, m_broadphase(new btDbvtBroadphase)
, m_world(new btDiscreteDynamicsWorld(
&m_dispatcher, m_broadphase.get(), &m_solver, &m_collision_config))
{
m_world->setGravity(gravity);
m_world->setInternalTickCallback(tick_update, this);
}
void BulletWorld::clean_world()
{
for (int i = m_world->getNumConstraints() - 1; i >= 0; i--) {
m_world->removeConstraint(m_world->getConstraint(i));
}
for (int i = m_world->getNumCollisionObjects() - 1; i >= 0; i--) {
btCollisionObject* obj = m_world->getCollisionObjectArray()[i];
m_world->removeCollisionObject(obj);
}
}
void BulletWorld::new_rigidbody(
World& wld, const EntityId& entity, const RigidBody& rigidbody,
const Transform& transform)
{
wld.emplace_component<BulletRigidBody>(
entity, rigidbody, transform, m_world);
}
void BulletWorld::new_ghost_object(
World& wld, const EntityId& entity, const GhostObject& object,
const Transform& transform)
{
wld.emplace_component<BulletGhostObject>(
entity, object, transform, m_world);
}
void BulletWorld::new_constraint(World& wld, const Constraint& constraint)
{
auto rigidbody = wld.get_component<BulletRigidBody>(constraint.entity);
if (!rigidbody)
return;
auto constraint_ptr = static_cast<btGeneric6DofConstraint*>(
m_constraints
.insert(std::make_unique<btGeneric6DofConstraint>(
*rigidbody->body(), btTransform::getIdentity(), false))
.first->get());
m_world->addConstraint(constraint_ptr);
constraint_ptr->setDbgDrawSize(5.0f);
constraint_ptr->setAngularLowerLimit({
constraint.angular_lower_limit.x,
constraint.angular_lower_limit.y,
constraint.angular_lower_limit.z,
});
constraint_ptr->setAngularUpperLimit({
constraint.angular_upper_limit.x,
constraint.angular_upper_limit.y,
constraint.angular_upper_limit.z,
});
constraint_ptr->setLinearLowerLimit({
constraint.linear_lower_limit.x,
constraint.linear_lower_limit.y,
constraint.linear_lower_limit.z,
});
constraint_ptr->setLinearUpperLimit({
constraint.linear_upper_limit.x,
constraint.linear_upper_limit.y,
constraint.linear_upper_limit.z,
});
}
void BulletWorld::simulate(float time_step)
{
m_world->stepSimulation(time_step);
}
void BulletWorld::get_collisions(World& wld, PhysicsWorld& phys_world)
{
auto rigidbodies = wld.query<BulletRigidBody>();
auto ghost_objects = wld.query<BulletGhostObject>();
for (auto [fst_body, snd_body] : m_collisions) {
std::optional<EntityId> entity1;
std::optional<EntityId> entity2;
for (const auto& [entity, body] : rigidbodies) {
if (body == fst_body) {
entity1 = entity;
}
if (body == snd_body) {
entity2 = entity;
}
if (entity1 && entity2) {
break;
}
}
for (const auto& [entity, object] : ghost_objects) {
if (object == fst_body) {
entity1 = entity;
}
if (object == snd_body) {
entity2 = entity;
}
if (entity1 && entity2) {
break;
}
}
if (entity1 && entity2) {
phys_world.add_collision(entity1.value(), entity2.value());
}
}
}
void BulletWorld::tick_update(btDynamicsWorld* dynamicsWorld, btScalar)
{
auto self = static_cast<BulletWorld*>(dynamicsWorld->getWorldUserInfo());
self->m_collisions.clear();
auto& dispatcher = *dynamicsWorld->getDispatcher();
const int num_manifolds = dispatcher.getNumManifolds();
for (int manifold_idx = 0; manifold_idx < num_manifolds; ++manifold_idx) {
auto& manifold = *dispatcher.getManifoldByIndexInternal(manifold_idx);
self->m_collisions.push_back({
manifold.getBody0(),
manifold.getBody1(),
});
}
}
| 30.21118 | 78 | 0.657484 | Arcahub |
8e42ea4ea3f9f071a18200c6f3982101826ab673 | 44,791 | cpp | C++ | spheroidal/sphwv/common_spheroidal.cpp | SabininGV/scattering | 68ffea5605d9da87db0593ba7c56c7f60f6b3fae | [
"BSD-2-Clause"
] | 5 | 2016-05-02T11:51:54.000Z | 2021-10-04T14:35:58.000Z | spheroidal/sphwv/common_spheroidal.cpp | SabininGV/scattering | 68ffea5605d9da87db0593ba7c56c7f60f6b3fae | [
"BSD-2-Clause"
] | null | null | null | spheroidal/sphwv/common_spheroidal.cpp | SabininGV/scattering | 68ffea5605d9da87db0593ba7c56c7f60f6b3fae | [
"BSD-2-Clause"
] | 10 | 2016-03-17T03:58:52.000Z | 2021-10-04T14:36:00.000Z | //
// Copyright (c) 2014, Ross Adelman, Nail A. Gumerov, and Ramani Duraiswami
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
#include "adder.hpp"
#include "common_spheroidal.hpp"
#include <iostream>
#include "real.hpp"
#include <vector>
static real calculate_alphar(const real & c, const real & m, const real & r);
static real calculate_betar(const real & c, const real & m, const real & r);
static real calculate_gammar(const real & c, const real & m, const real & r);
static real calculate_betarm(const real & c, const real & m, const real & r);
static real calculate_gammarm(const real & c, const real & m, const real & r);
static real calculate_U(bool verbose, const real & c, const real & m, const real & n, const real & lambda);
static void calculate_zero(real & x, real & Ux, bool verbose, const real & c, const real & m, const real & n, real a, real Ua, real b, real Ub);
static real calculate_Nrm(bool verbose, const real & c, const real & m, const real & r, const real & lambda);
static real calculate_Arm(const real & c, const real & m, const real & r);
static real calculate_Brm(const real & c, const real & m, const real & lambda, const real & r);
static real calculate_Crm(const real & c, const real & m, const real & r);
static real get_dr(bool verbose, const real & c, const real & m, const real & n, const real & lambda, real & n_dr, std::vector<real> & dr, const real & r);
static real get_dr_neg(bool verbose, const real & c, const real & m, const real & n, const real & lambda, const real & n_dr, const std::vector<real> & dr, real & n_dr_neg, std::vector<real> & dr_neg, const real & r);
static real calculate_alphar(const real & c, const real & m, const real & r)
{
return (((real::TWO * m + r + real::TWO) * (real::TWO * m + r + real::ONE)) / ((real::TWO * m + real::TWO * r + real::FIVE) * (real::TWO * m + real::TWO * r + real::THREE))) * calculate_c_squared(c);
}
static real calculate_betar(const real & c, const real & m, const real & r)
{
return (m + r) * (m + r + real::ONE) + ((real::TWO * (m + r) * (m + r + real::ONE) - real::TWO * m * m - real::ONE) / ((real::TWO * m + real::TWO * r - real::ONE) * (real::TWO * m + real::TWO * r + real::THREE))) * calculate_c_squared(c);
}
static real calculate_gammar(const real & c, const real & m, const real & r)
{
return ((r * (r - real::ONE)) / ((real::TWO * m + real::TWO * r - real::THREE) * (real::TWO * m + real::TWO * r - real::ONE))) * calculate_c_squared(c);
}
static real calculate_betarm(const real & c, const real & m, const real & r)
{
return calculate_gammar(c, m, r) * calculate_alphar(c, m, r - real::TWO);
}
static real calculate_gammarm(const real & c, const real & m, const real & r)
{
return calculate_betar(c, m, r);
}
real calculate_continued_fraction(const real & b0, const std::vector<real> & a, const std::vector<real> & b)
{
real x;
x = real::ZERO;
if ((int)a.size() < (int)b.size())
{
for (int i = (int)a.size() - 1; i >= 0; --i)
{
x = a[i] / (b[i] - x);
}
}
else
{
for (int i = (int)b.size() - 1; i >= 0; --i)
{
x = a[i] / (b[i] - x);
}
}
x = b0 - x;
return x;
}
static real calculate_U(bool verbose, const real & c, const real & m, const real & n, const real & lambda)
{
real r;
real b0;
std::vector<real> a;
std::vector<real> b;
real U1;
real prev_U2;
real U2;
real U;
r = n - m;
b0 = calculate_gammarm(c, m, r) - lambda;
a.clear();
b.clear();
if (remainder(n - m, real::TWO) == real::ZERO)
{
for (real i = r; i >= real::TWO; i = i - real::TWO)
{
a.push_back(calculate_betarm(c, m, i));
b.push_back(calculate_gammarm(c, m, i - real::TWO) - lambda);
}
}
else
{
for (real i = r; i >= real::THREE; i = i - real::TWO)
{
a.push_back(calculate_betarm(c, m, i));
b.push_back(calculate_gammarm(c, m, i - real::TWO) - lambda);
}
}
U1 = calculate_continued_fraction(b0, a, b);
b0 = real::ZERO;
a.clear();
b.clear();
prev_U2 = real::NAN;
for (real i = r + real::TWO; ; i = i + real::TWO)
{
a.push_back(calculate_betarm(c, m, i));
b.push_back(calculate_gammarm(c, m, i) - lambda);
if (remainder(i - (r + real::TWO), real("100.0")) == real::ZERO)
{
U2 = calculate_continued_fraction(b0, a, b);
if (prev_U2 == prev_U2)
{
if (abs((U2 - prev_U2) / prev_U2) < real::SMALL_ENOUGH)
{
if (verbose)
{
std::cout << "calculate_U: " << ((U2 - prev_U2) / prev_U2).get_string(10) << std::endl;
}
break;
}
}
prev_U2 = U2;
}
}
U = U1 + U2;
return U;
}
static void calculate_zero(real & x, real & Ux, bool verbose, const real & c, const real & m, const real & n, real a, real Ua, real b, real Ub)
{
real prev_x;
for (int i = 0; ; ++i)
{
x = a - (Ua / (Ub - Ua)) * (b - a);
Ux = calculate_U(verbose, c, m, n, x);
if (Ux != real::ZERO)
{
if (Ua < real::ZERO && Ub > real::ZERO)
{
if (Ux < real::ZERO)
{
a = x;
Ua = Ux;
}
else
{
b = x;
Ub = Ux;
}
}
else
{
if (Ux > real::ZERO)
{
a = x;
Ua = Ux;
}
else
{
b = x;
Ub = Ux;
}
}
}
else
{
std::cout << "calculate_zero: U = 0.0" << std::endl;
return;
}
if (i > 0)
{
if (verbose)
{
std::cout << "calculate_zero: " << ((x - prev_x) / prev_x).get_string(10) << std::endl;
}
if (abs((x - prev_x) / prev_x) < real::SMALL_ENOUGH)
{
break;
}
}
prev_x = x;
}
}
void calculate_lambdamn(real & lambda, bool verbose, const real & c, const real & m, const real & n, const real & lambda_approx)
{
real x;
real Ux;
real d;
real a;
real Ua;
real b;
real Ub;
x = lambda_approx;
Ux = calculate_U(verbose, c, m, n, x);
d = pow(real::TWO, -real("100.0")) * x;
while (true)
{
a = x - d;
Ua = calculate_U(verbose, c, m, n, a);
b = x + d;
Ub = calculate_U(verbose, c, m, n, b);
if (verbose)
{
std::cout << "calculate_lambdamn: " << Ua.get_string(10) << ", " << Ub.get_string(10) << std::endl;
}
if ((Ua < real::ZERO && Ub > real::ZERO) || (Ua > real::ZERO && Ub < real::ZERO))
{
break;
}
d = real::TWO * d;
}
calculate_zero(x, Ux, verbose, c, m, n, a, Ua, b, Ub);
lambda = x;
}
static real calculate_Nrm(bool verbose, const real & c, const real & m, const real & r, const real & lambda)
{
real b0;
std::vector<real> a;
std::vector<real> b;
real N;
real prev_N;
b0 = real::ZERO;
a.clear();
b.clear();
for (real i = r; ; i = i + real::TWO)
{
a.push_back(calculate_betarm(c, m, i));
b.push_back(calculate_gammarm(c, m, i) - lambda);
N = -calculate_continued_fraction(b0, a, b);
if (i > r)
{
if (abs((N - prev_N) / prev_N) < real::SMALL_ENOUGH)
{
if (verbose)
{
std::cout << "calculate_Nrm: " << ((N - prev_N) / prev_N).get_string(10) << std::endl;
}
break;
}
}
prev_N = N;
}
return N;
}
void calculate_drmn(std::vector<real> & dr, bool verbose, const real & c, const real & m, const real & n, const real & lambda, real & n_dr, const real & dr_min)
{
real n_dr_orig;
real N;
bool converged;
real x;
adder x_adder;
real a;
real change;
real s;
real remove_where;
n_dr_orig = n_dr;
for ( ; ; n_dr = real::TWO * n_dr)
{
if (n_dr > n_dr_orig)
{
for (real r = n_dr / real::TWO; r <= n_dr - real::ONE; r = r + real::ONE)
{
dr.push_back(real::ZERO);
}
}
else
{
dr.clear();
for (real r = real::ZERO; r <= n_dr_orig - real::ONE; r = r + real::ONE)
{
dr.push_back(real::ZERO);
}
}
if (remainder(n - m, real::TWO) == real::ZERO)
{
dr[gzbi(n_dr - real::TWO)] = real::ONE;
for (real r = n_dr - real::TWO; r >= real::TWO; r = r - real::TWO)
{
if (r < n_dr - real::TWO)
{
N = calculate_betarm(c, m, r) / (calculate_gammarm(c, m, r) - lambda - N);
}
else
{
N = calculate_Nrm(verbose, c, m, r, lambda);
}
dr[gzbi(r - real::TWO)] = -(calculate_alphar(c, m, r - real::TWO) / N) * dr[gzbi(r)];
}
converged = false;
x = real::ZERO;
x_adder.clear();
for (real r = real::ZERO; r <= n_dr - real::TWO; r = r + real::TWO)
{
if (r > real::ZERO)
{
a = a * ((-real::ONE * (real::TWO * m + r - real::ONE) * (real::TWO * m + r)) / (real::FOUR * (m + r / real::TWO) * (r / real::TWO)));
}
else
{
a = factorial(real::TWO * m) / factorial(m);
}
change = dr[gzbi(r)] * a;
x = x + change;
x_adder.add(change);
if (r > real::ZERO && abs(change) > real::ZERO && abs(change / x) < real::SMALL_ENOUGH)
{
converged = true;
if (verbose)
{
std::cout << "calculate_drmn: " << (change / x).get_string(10) << ", " << ((x - x_adder.calculate_sum()) / x_adder.calculate_sum()).get_string(10) << ", " << (change / x_adder.calculate_sum()).get_string(10) << std::endl;
}
break;
}
}
x = x_adder.calculate_sum();
if (!converged)
{
if (verbose)
{
std::cout << "calculate_drmn: warning: x did not converge" << std::endl;
}
}
s = ((pow(-real::ONE, (n - m) / real::TWO) * factorial(n + m)) / (pow(real::TWO, n - m) * factorial((n + m) / real::TWO) * factorial((n - m) / real::TWO))) / x;
for (real r = real::ZERO; r <= n_dr - real::TWO; r = r + real::TWO)
{
dr[gzbi(r)] = s * dr[gzbi(r)];
}
if (converged && (dr_min == real::ZERO || abs(dr[gzbi(n_dr - real::TWO)]) < dr_min))
{
break;
}
}
else
{
dr[gzbi(n_dr - real::ONE)] = real::ONE;
for (real r = n_dr - real::ONE; r >= real::THREE; r = r - real::TWO)
{
if (r < n_dr - real::ONE)
{
N = calculate_betarm(c, m, r) / (calculate_gammarm(c, m, r) - lambda - N);
}
else
{
N = calculate_Nrm(verbose, c, m, r, lambda);
}
dr[gzbi(r - real::TWO)] = -(calculate_alphar(c, m, r - real::TWO) / N) * dr[gzbi(r)];
}
converged = false;
x = real::ZERO;
x_adder.clear();
for (real r = real::ONE; r <= n_dr - real::ONE; r = r + real::TWO)
{
if (r > real::ONE)
{
a = a * ((-real::ONE * (real::TWO * m + r) * (real::TWO * m + r + real::ONE)) / (real::FOUR * (m + r / real::TWO + real::ONE / real::TWO) * (r / real::TWO - real::ONE / real::TWO)));
}
else
{
a = factorial(real::TWO * m + real::TWO) / (real::TWO * factorial(m + real::ONE));
}
change = dr[gzbi(r)] * a;
x = x + change;
x_adder.add(change);
if (r > real::ZERO && abs(change) > real::ZERO && abs(change / x) < real::SMALL_ENOUGH)
{
converged = true;
if (verbose)
{
std::cout << "calculate_drmn: " << (change / x).get_string(10) << ", " << ((x - x_adder.calculate_sum()) / x_adder.calculate_sum()).get_string(10) << ", " << (change / x_adder.calculate_sum()).get_string(10) << std::endl;
}
break;
}
}
x = x_adder.calculate_sum();
if (!converged)
{
if (verbose)
{
std::cout << "calculate_drmn: warning: x did not converge" << std::endl;
}
}
s = ((pow(-real::ONE, (n - m - real::ONE) / real::TWO) * factorial(n + m + real::ONE)) / (pow(real::TWO, n - m) * factorial((n + m + real::ONE) / real::TWO) * factorial((n - m - real::ONE) / real::TWO))) / x;
for (real r = real::ONE; r <= n_dr - real::ONE; r = r + real::TWO)
{
dr[gzbi(r)] = s * dr[gzbi(r)];
}
if (converged && (dr_min == real::ZERO || abs(dr[gzbi(n_dr - real::ONE)]) < dr_min))
{
break;
}
}
}
if (dr_min > real::ZERO)
{
if (remainder(n - m, real::TWO) == real::ZERO)
{
for (real r = n_dr - real::TWO; r >= real::ZERO; r = r - real::TWO)
{
if (abs(dr[gzbi(r)]) >= dr_min)
{
remove_where = r + real::FOUR;
if (remove_where >= n_dr_orig && remove_where <= n_dr - real::TWO)
{
dr.erase(dr.begin() + gzbi(remove_where), dr.end());
n_dr = real((int)dr.size());
}
break;
}
}
}
else
{
for (real r = n_dr - real::ONE; r >= real::ONE; r = r - real::TWO)
{
if (abs(dr[gzbi(r)]) >= dr_min)
{
remove_where = r + real::THREE;
if (remove_where >= n_dr_orig && remove_where <= n_dr - real::TWO)
{
dr.erase(dr.begin() + gzbi(remove_where), dr.end());
n_dr = real((int)dr.size());
}
break;
}
}
}
}
}
static real calculate_Arm(const real & c, const real & m, const real & r)
{
return calculate_alphar(c, m, r - real::TWO);
}
static real calculate_Brm(const real & c, const real & m, const real & lambda, const real & r)
{
return calculate_betar(c, m, r) - lambda;
}
static real calculate_Crm(const real & c, const real & m, const real & r)
{
return calculate_gammar(c, m, r + real::TWO);
}
void calculate_drmn_neg(std::vector<real> & dr_neg, bool verbose, const real & c, const real & m, const real & n, const real & lambda, const real & n_dr, const std::vector<real> & dr, real & n_dr_neg, const real & dr_neg_min)
{
real n_dr_neg_orig;
real b0;
std::vector<real> a;
std::vector<real> b;
real N;
real prev_N;
real s;
real remove_where;
n_dr_neg_orig = n_dr_neg;
for ( ; ; n_dr_neg = real::TWO * n_dr_neg)
{
if (n_dr_neg > n_dr_neg_orig)
{
for (real r = -n_dr_neg / real::TWO - real::ONE; r >= -n_dr_neg; r = r - real::ONE)
{
dr_neg.push_back(real::ZERO);
}
}
else
{
dr_neg.clear();
for (real r = -real::ONE; r >= -n_dr_neg_orig; r = r - real::ONE)
{
dr_neg.push_back(real::ZERO);
}
}
if (remainder(n - m, real::TWO) == real::ZERO)
{
dr_neg[gnobi(-n_dr_neg)] = real::ONE;
for (real r = -n_dr_neg; r <= -real::TWO; r = r + real::TWO)
{
if (r > -n_dr_neg)
{
if (r != -real::TWO * m - real::TWO)
{
N = -calculate_Arm(c, m, r + real::TWO) / (calculate_Brm(c, m, lambda, r) + calculate_Crm(c, m, r - real::TWO) * N);
}
else
{
N = (calculate_c_squared(c) / ((real::TWO * m - real::ONE) * (real::TWO * m + real::ONE))) / (calculate_Brm(c, m, lambda, r) + calculate_Crm(c, m, r - real::TWO) * N);
}
}
else
{
b0 = real::ZERO;
a.clear();
b.clear();
if (r != -real::TWO * m - real::TWO)
{
a.push_back(calculate_Arm(c, m, r + real::TWO));
}
else
{
a.push_back(-calculate_c_squared(c) / ((real::TWO * m - real::ONE) * (real::TWO * m + real::ONE)));
}
b.push_back(calculate_Brm(c, m, lambda, r));
for (real i = r - real::TWO; ; i = i - real::TWO)
{
a.push_back(calculate_Crm(c, m, i) * calculate_Arm(c, m, i + real::TWO));
b.push_back(calculate_Brm(c, m, lambda, i));
N = calculate_continued_fraction(b0, a, b);
if (i < r - real::TWO)
{
if (abs((N - prev_N) / prev_N) < real::SMALL_ENOUGH)
{
if (verbose)
{
std::cout << "calculate_drmn_neg: " << ((N - prev_N) / prev_N).get_string(10) << std::endl;
}
break;
}
}
prev_N = N;
}
}
if (r < -real::TWO)
{
dr_neg[gnobi(r + real::TWO)] = dr_neg[gnobi(r)] / N;
if (r == -real::TWO * m - real::TWO)
{
N = real::ZERO;
}
}
}
s = dr[gzbi(real::ZERO)] / (dr_neg[gnobi(-real::TWO)] / N);
for (real r = -n_dr_neg; r <= -real::TWO; r = r + real::TWO)
{
dr_neg[gnobi(r)] = s * dr_neg[gnobi(r)];
}
if (dr_neg_min == real::ZERO || abs(dr_neg[gnobi(-n_dr_neg)]) < dr_neg_min)
{
break;
}
}
else
{
dr_neg[gnobi(-n_dr_neg + real::ONE)] = real::ONE;
for (real r = -n_dr_neg + real::ONE; r <= -real::ONE; r = r + real::TWO)
{
if (r > -n_dr_neg + real::ONE)
{
if (r != -real::TWO * m - real::ONE)
{
N = -calculate_Arm(c, m, r + real::TWO) / (calculate_Brm(c, m, lambda, r) + calculate_Crm(c, m, r - real::TWO) * N);
}
else
{
N = -(calculate_c_squared(c) / ((real::TWO * m - real::ONE) * (real::TWO * m - real::THREE))) / (calculate_Brm(c, m, lambda, r) + calculate_Crm(c, m, r - real::TWO) * N);
}
}
else
{
b0 = real::ZERO;
a.clear();
b.clear();
if (r != -real::TWO * m - real::ONE)
{
a.push_back(calculate_Arm(c, m, r + real::TWO));
}
else
{
a.push_back(calculate_c_squared(c) / ((real::TWO * m - real::ONE) * (real::TWO * m - real::THREE)));
}
b.push_back(calculate_Brm(c, m, lambda, r));
for (real i = r - real::TWO; ; i = i - real::TWO)
{
a.push_back(calculate_Crm(c, m, i) * calculate_Arm(c, m, i + real::TWO));
b.push_back(calculate_Brm(c, m, lambda, i));
N = calculate_continued_fraction(b0, a, b);
if (i < r - real::TWO)
{
if (abs((N - prev_N) / prev_N) < real::SMALL_ENOUGH)
{
if (verbose)
{
std::cout << "calculate_drmn_neg: " << ((N - prev_N) / prev_N).get_string(10) << std::endl;
}
break;
}
}
prev_N = N;
}
}
if (r < -real::ONE)
{
dr_neg[gnobi(r + real::TWO)] = dr_neg[gnobi(r)] / N;
if (r == -real::TWO * m - real::ONE)
{
N = real::ZERO;
}
}
}
s = dr[gzbi(real::ONE)] / (dr_neg[gnobi(-real::ONE)] / N);
for (real r = -n_dr_neg + real::ONE; r <= -real::ONE; r = r + real::TWO)
{
dr_neg[gnobi(r)] = s * dr_neg[gnobi(r)];
}
if (dr_neg_min == real::ZERO || abs(dr_neg[gnobi(-n_dr_neg + real::ONE)]) < dr_neg_min)
{
break;
}
}
}
if (dr_neg_min > real::ZERO)
{
if (remainder(n - m, real::TWO) == real::ZERO)
{
for (real r = -n_dr_neg; r <= -real::TWO; r = r + real::TWO)
{
if (abs(dr_neg[gnobi(r)]) >= dr_neg_min)
{
remove_where = r - real::THREE;
if (remove_where <= -n_dr_neg_orig - real::ONE && remove_where >= -n_dr_neg + real::ONE)
{
dr_neg.erase(dr_neg.begin() + gnobi(remove_where), dr_neg.end());
n_dr_neg = real((int)dr_neg.size());
}
break;
}
}
}
else
{
for (real r = -n_dr_neg + real::ONE; r <= -real::ONE; r = r + real::TWO)
{
if (abs(dr_neg[gnobi(r)]) >= dr_neg_min)
{
remove_where = r - real::FOUR;
if (remove_where <= -n_dr_neg_orig - real::ONE && remove_where >= -n_dr_neg + real::ONE)
{
dr_neg.erase(dr_neg.begin() + gnobi(remove_where), dr_neg.end());
n_dr_neg = real((int)dr_neg.size());
}
break;
}
}
}
}
}
static real get_dr(bool verbose, const real & c, const real & m, const real & n, const real & lambda, real & n_dr, std::vector<real> & dr, const real & r)
{
if (r >= n_dr)
{
while (r >= n_dr)
{
n_dr = real::TWO * n_dr;
}
calculate_drmn(dr, verbose, c, m, n, lambda, n_dr, real::ZERO);
}
return dr[gzbi(r)];
}
real calculate_Nmn(bool verbose, const real & c, const real & m, const real & n, const real & lambda, real & n_dr, std::vector<real> & dr)
{
real N;
adder N_adder;
real a;
real change;
N = real::ZERO;
N_adder.clear();
if (remainder(n - m, real::TWO) == real::ZERO)
{
for (real r = real::ZERO; ; r = r + real::TWO)
{
if (r > real::ZERO)
{
a = a * (((real::TWO * m + r - real::ONE) * (real::TWO * m + r)) / ((r - real::ONE) * r));
}
else
{
a = factorial(real::TWO * m);
}
change = get_dr(verbose, c, m, n, lambda, n_dr, dr, r) * get_dr(verbose, c, m, n, lambda, n_dr, dr, r) * (a / (real::TWO * m + real::TWO * r + real::ONE));
N = N + change;
N_adder.add(change);
if (r > real::ZERO && abs(change) > real::ZERO && abs(change / N) < real::SMALL_ENOUGH)
{
if (verbose)
{
std::cout << "calculate_Nmn: " << (change / N).get_string(10) << ", " << ((N - N_adder.calculate_sum()) / N_adder.calculate_sum()).get_string(10) << ", " << (change / N_adder.calculate_sum()).get_string(10) << std::endl;
}
break;
}
}
}
else
{
for (real r = real::ONE; ; r = r + real::TWO)
{
if (r > real::ONE)
{
a = a * (((real::TWO * m + r - real::ONE) * (real::TWO * m + r)) / ((r - real::ONE) * r));
}
else
{
a = factorial(real::TWO * m + real::ONE);
}
change = get_dr(verbose, c, m, n, lambda, n_dr, dr, r) * get_dr(verbose, c, m, n, lambda, n_dr, dr, r) * (a / (real::TWO * m + real::TWO * r + real::ONE));
N = N + change;
N_adder.add(change);
if (r > real::ONE && abs(change) > real::ZERO && abs(change / N) < real::SMALL_ENOUGH)
{
if (verbose)
{
std::cout << "calculate_Nmn: " << (change / N).get_string(10) << ", " << ((N - N_adder.calculate_sum()) / N_adder.calculate_sum()).get_string(10) << ", " << (change / N_adder.calculate_sum()).get_string(10) << std::endl;
}
break;
}
}
}
N = N_adder.calculate_sum();
N = real::TWO * N;
return N;
}
real calculate_Fmn(bool verbose, const real & c, const real & m, const real & n, const real & lambda, real & n_dr, std::vector<real> & dr)
{
real F;
adder F_adder;
real a;
real change;
F = real::ZERO;
F_adder.clear();
if (remainder(n - m, real::TWO) == real::ZERO)
{
for (real r = real::ZERO; ; r = r + real::TWO)
{
if (r > real::ZERO)
{
a = a * (((real::TWO * m + r - real::ONE) * (real::TWO * m + r)) / ((r - real::ONE) * r));
}
else
{
a = factorial(real::TWO * m);
}
change = get_dr(verbose, c, m, n, lambda, n_dr, dr, r) * a;
F = F + change;
F_adder.add(change);
if (r > real::ZERO && abs(change) > real::ZERO && abs(change / F) < real::SMALL_ENOUGH)
{
if (verbose)
{
std::cout << "calculate_Fmn: " << (change / F).get_string(10) << ", " << ((F - F_adder.calculate_sum()) / F_adder.calculate_sum()).get_string(10) << ", " << (change / F_adder.calculate_sum()).get_string(10) << std::endl;
}
break;
}
}
}
else
{
for (real r = real::ONE; ; r = r + real::TWO)
{
if (r > real::ONE)
{
a = a * (((real::TWO * m + r - real::ONE) * (real::TWO * m + r)) / ((r - real::ONE) * r));
}
else
{
a = factorial(real::TWO * m + real::ONE);
}
change = get_dr(verbose, c, m, n, lambda, n_dr, dr, r) * a;
F = F + change;
F_adder.add(change);
if (r > real::ONE && abs(change) > real::ZERO && abs(change / F) < real::SMALL_ENOUGH)
{
if (verbose)
{
std::cout << "calculate_Fmn: " << (change / F).get_string(10) << ", " << ((F - F_adder.calculate_sum()) / F_adder.calculate_sum()).get_string(10) << ", " << (change / F_adder.calculate_sum()).get_string(10) << std::endl;
}
break;
}
}
}
F = F_adder.calculate_sum();
return F;
}
//
// In the oblate case, there's an implicit factor of 1i ^ m when n - m is even
// and 1i ^ (m + 1) when n - m is odd.
//
real calculate_kmn1(bool verbose, const real & c, const real & m, const real & n, const real & n_dr, const std::vector<real> & dr, const real & F)
{
real k1;
if (remainder(n - m, real::TWO) == real::ZERO)
{
k1 = ((real::TWO * m + real::ONE) * factorial(m + n) * F) / (pow(real::TWO, m + n) * dr[gzbi(real::ZERO)] * pow(c, m) * factorial(m) * factorial((n - m) / real::TWO) * factorial((m + n) / real::TWO));
}
else
{
k1 = ((real::TWO * m + real::THREE) * factorial(m + n + real::ONE) * F) / (pow(real::TWO, m + n) * dr[gzbi(real::ONE)] * pow(c, m + real::ONE) * factorial(m) * factorial((n - m - real::ONE) / real::TWO) * factorial((m + n + real::ONE) / real::TWO));
}
return k1;
}
static real get_dr_neg(bool verbose, const real & c, const real & m, const real & n, const real & lambda, const real & n_dr, const std::vector<real> & dr, real & n_dr_neg, std::vector<real> & dr_neg, const real & r)
{
if (r <= -n_dr_neg - real::ONE)
{
while (r <= -n_dr_neg - real::ONE)
{
n_dr_neg = real::TWO * n_dr_neg;
}
calculate_drmn_neg(dr_neg, verbose, c, m, n, lambda, n_dr, dr, n_dr_neg, real::ZERO);
}
return dr_neg[gnobi(r)];
}
real calculate_kmn2(bool verbose, const real & c, const real & m, const real & n, const real & lambda, const real & n_dr, const std::vector<real> & dr, real & n_dr_neg, std::vector<real> & dr_neg, const real & F)
{
real dr1;
real k2;
if (remainder(n - m, real::TWO) == real::ZERO)
{
if (-real::TWO * m < real::ZERO)
{
dr1 = get_dr_neg(verbose, c, m, n, lambda, n_dr, dr, n_dr_neg, dr_neg, -real::TWO * m);
}
else
{
dr1 = dr[gzbi(real::ZERO)];
}
k2 = (pow(real::TWO, n - m) * factorial(real::TWO * m) * factorial((n - m) / real::TWO) * factorial((m + n) / real::TWO) * dr1 * F) / ((real::TWO * m - real::ONE) * factorial(m) * factorial(m + n) * pow(c, m - real::ONE));
}
else
{
if (-real::TWO * m + real::ONE < real::ONE)
{
dr1 = get_dr_neg(verbose, c, m, n, lambda, n_dr, dr, n_dr_neg, dr_neg, -real::TWO * m + real::ONE);
}
else
{
dr1 = dr[gzbi(real::ONE)];
}
k2 = -((pow(real::TWO, n - m) * factorial(real::TWO * m) * factorial((n - m - real::ONE) / real::TWO) * factorial((m + n + real::ONE) / real::TWO) * dr1 * F) / ((real::TWO * m - real::THREE) * (real::TWO * m - real::ONE) * factorial(m) * factorial(m + n + real::ONE) * pow(c, m - real::TWO)));
}
return k2;
}
void calculate_c2kmn(std::vector<real> & c2k, bool verbose, const real & c, const real & m, const real & n, const real & lambda, real & n_dr, std::vector<real> & dr, real & n_c2k, const real & c2k_min)
{
real n_c2k_orig;
real prev_n_c2k;
adder c2k_adder;
real a;
real a0;
real change;
real remove_where;
n_c2k_orig = n_c2k;
for (prev_n_c2k = real((int)c2k.size()); ; prev_n_c2k = n_c2k, n_c2k = real::TWO * n_c2k)
{
for (real k = prev_n_c2k; k <= n_c2k - real::ONE; k = k + real::ONE)
{
c2k.push_back(real::ZERO);
}
for (real k = prev_n_c2k; k <= n_c2k - real::ONE; k = k + real::ONE)
{
c2k[gzbi(k)] = real::ZERO;
c2k_adder.clear();
if (remainder(n - m, real::TWO) == real::ZERO)
{
for (real r = real::TWO * k; ; r = r + real::TWO)
{
if (r > real::TWO * k)
{
a = a * (((real::TWO * m + r - real::ONE) * (real::TWO * m + r) * (-r / real::TWO) * (m + r / real::TWO + k - real::ONE / real::TWO)) / ((r - real::ONE) * r * (-r / real::TWO + k) * (m + r / real::TWO - real::ONE / real::TWO)));
if (r == real::TWO * k + real::TWO)
{
a0 = a;
}
}
else
{
if (k > prev_n_c2k)
{
a = a0 * (-real::ONE) * (m + real::TWO * k - real::ONE / real::TWO);
}
else
{
a = (factorial(real::TWO * m + r) / factorial(r)) * pochhammer(-r / real::TWO, prev_n_c2k) * pochhammer(m + r / real::TWO + real::ONE / real::TWO, prev_n_c2k);
}
}
change = get_dr(verbose, c, m, n, lambda, n_dr, dr, r) * a;
c2k[gzbi(k)] = c2k[gzbi(k)] + change;
c2k_adder.add(change);
if (r > real::TWO * k && abs(change) > real::ZERO && abs(change / c2k[gzbi(k)]) < real::SMALL_ENOUGH)
{
if (verbose)
{
std::cout << "calculate_c2kmn: k = " << k.get_int() << ": " << (change / c2k[gzbi(k)]).get_string(10) << ", " << ((c2k[gzbi(k)] - c2k_adder.calculate_sum()) / c2k_adder.calculate_sum()).get_string(10) << ", " << (change / c2k_adder.calculate_sum()).get_string(10) << std::endl;
}
break;
}
}
}
else
{
for (real r = real::TWO * k + real::ONE; ; r = r + real::TWO)
{
if (r > real::TWO * k + real::ONE)
{
a = a * (((real::TWO * m + r - real::ONE) * (real::TWO * m + r) * (-r / real::TWO + real::ONE / real::TWO) * (m + r / real::TWO + k)) / ((r - real::ONE) * r * (-r / real::TWO + k + real::ONE / real::TWO) * (m + r / real::TWO)));
if (r == real::TWO * k + real::THREE)
{
a0 = a;
}
}
else
{
if (k > prev_n_c2k)
{
a = a0 * (-real::ONE) * (m + real::TWO * k + real::ONE / real::TWO);
}
else
{
a = (factorial(real::TWO * m + r) / factorial(r)) * pochhammer(-(r - real::ONE) / real::TWO, prev_n_c2k) * pochhammer(m + r / real::TWO + real::ONE, prev_n_c2k);
}
}
change = get_dr(verbose, c, m, n, lambda, n_dr, dr, r) * a;
c2k[gzbi(k)] = c2k[gzbi(k)] + change;
c2k_adder.add(change);
if (r > real::TWO * k + real::ONE && abs(change) > real::ZERO && abs(change / c2k[gzbi(k)]) < real::SMALL_ENOUGH)
{
if (verbose)
{
std::cout << "calculate_c2kmn: k = " << k.get_int() << ": " << (change / c2k[gzbi(k)]).get_string(10) << ", " << ((c2k[gzbi(k)] - c2k_adder.calculate_sum()) / c2k_adder.calculate_sum()).get_string(10) << ", " << (change / c2k_adder.calculate_sum()).get_string(10) << std::endl;
}
break;
}
}
}
c2k[gzbi(k)] = c2k_adder.calculate_sum();
c2k[gzbi(k)] = (real::ONE / (pow(real::TWO, m) * factorial(m + k) * factorial(k))) * c2k[gzbi(k)];
}
if (c2k_min == real::ZERO || abs(c2k[gzbi(n_c2k - real::ONE)]) < c2k_min)
{
break;
}
}
if (c2k_min > real::ZERO)
{
for (real k = n_c2k - real::ONE; k >= real::ZERO; k = k - real::ONE)
{
if (abs(c2k[gzbi(k)]) >= c2k_min)
{
remove_where = k + real::TWO;
if (remove_where >= n_c2k_orig && remove_where <= n_c2k - real::ONE)
{
c2k.erase(c2k.begin() + gzbi(remove_where), c2k.end());
n_c2k = real((int)c2k.size());
}
break;
}
}
}
}
void calculate_Smn1_1(real & S1, real & S1p, bool verbose, const real & c, const real & m, const real & n, const real & n_dr, const std::vector<real> & dr, const real & eta)
{
adder S1_adder;
adder S1p_adder;
real P0;
real P1;
real P0p;
real change;
real changep;
real P1p;
S1 = real::ZERO;
S1_adder.clear();
S1p = real::ZERO;
S1p_adder.clear();
P0 = real::ONE;
for (real v = real::ONE; v <= m; v = v + real::ONE)
{
P0 = -(real::TWO * v - real::ONE) * pow(real::ONE - eta * eta, real::ONE / real::TWO) * P0;
}
P1 = (real::TWO * m + real::ONE) * eta * P0;
if (remainder(n - m, real::TWO) == real::ZERO)
{
for (real r = real::ZERO; r <= n_dr - real::TWO; r = r + real::TWO)
{
if (r > real::ZERO)
{
P0 = (real::ONE / r) * (-(real::TWO * m + r - real::ONE) * P0 + (real::TWO * m + real::TWO * r - real::ONE) * eta * P1);
P1 = (real::ONE / (r + real::ONE)) * (-(real::TWO * m + r) * P1 + (real::TWO * m + real::TWO * r + real::ONE) * eta * P0);
}
if (abs(eta) < real::ONE)
{
P0p = (real::ONE / (real::ONE - eta * eta)) * ((m + r + real::ONE) * eta * P0 - (r + real::ONE) * P1);
}
else
{
if (m > real::TWO)
{
P0p = real::ZERO;
}
else if (m > real::ONE)
{
P0p = -((m + r - real::ONE) * (m + r) * (m + r + real::ONE) * (m + r + real::TWO)) / real::FOUR;
}
else if (m > real::ZERO)
{
P0p = real::INF;
}
else
{
P0p = ((m + r) * (m + r + real::ONE)) / real::TWO;
}
if (eta == -real::ONE)
{
P0p = -P0p;
}
}
change = dr[gzbi(r)] * P0;
S1 = S1 + change;
S1_adder.add(change);
changep = dr[gzbi(r)] * P0p;
S1p = S1p + changep;
S1p_adder.add(changep);
if (r > real::ZERO && abs(change) > real::ZERO && abs(change / S1) < real::SMALL_ENOUGH && abs(changep) > real::ZERO && abs(changep / S1p) < real::SMALL_ENOUGH)
{
if (verbose)
{
std::cout << "calculate_Smn1_1: " << (change / S1).get_string(10) << ", " << (changep / S1p).get_string(10) << ", " << ((S1 - S1_adder.calculate_sum()) / S1_adder.calculate_sum()).get_string(10) << ", " << ((S1p - S1p_adder.calculate_sum()) / S1p_adder.calculate_sum()).get_string(10) << ", " << (change / S1_adder.calculate_sum()).get_string(10) << ", " << (changep / S1p_adder.calculate_sum()).get_string(10) << std::endl;
}
break;
}
}
}
else
{
for (real r = real::ONE; r <= n_dr - real::ONE; r = r + real::TWO)
{
if (r > real::ONE)
{
P0 = (real::ONE / (r - real::ONE)) * (-(real::TWO * m + r - real::TWO) * P0 + (real::TWO * m + real::TWO * r - real::THREE) * eta * P1);
P1 = (real::ONE / r) * (-(real::TWO * m + r - real::ONE) * P1 + (real::TWO * m + real::TWO * r - real::ONE) * eta * P0);
}
if (abs(eta) < real::ONE)
{
P1p = (real::ONE / (real::ONE - eta * eta)) * ((real::TWO * m + r) * P0 - (m + r) * eta * P1);
}
else
{
if (m > real::TWO)
{
P1p = real::ZERO;
}
else if (m > real::ONE)
{
P1p = -((m + r - real::ONE) * (m + r) * (m + r + real::ONE) * (m + r + real::TWO)) / real::FOUR;
}
else if (m > real::ZERO)
{
P1p = real::INF;
}
else
{
P1p = ((m + r) * (m + r + real::ONE)) / real::TWO;
}
}
change = dr[gzbi(r)] * P1;
S1 = S1 + change;
S1_adder.add(change);
changep = dr[gzbi(r)] * P1p;
S1p = S1p + changep;
S1p_adder.add(changep);
if (r > real::ONE && abs(change) > real::ZERO && abs(change / S1) < real::SMALL_ENOUGH && abs(changep) > real::ZERO && abs(changep / S1p) < real::SMALL_ENOUGH)
{
if (verbose)
{
std::cout << "calculate_Smn1_1: " << (change / S1).get_string(10) << ", " << (changep / S1p).get_string(10) << ", " << ((S1 - S1_adder.calculate_sum()) / S1_adder.calculate_sum()).get_string(10) << ", " << ((S1p - S1p_adder.calculate_sum()) / S1p_adder.calculate_sum()).get_string(10) << ", " << (change / S1_adder.calculate_sum()).get_string(10) << ", " << (changep / S1p_adder.calculate_sum()).get_string(10) << std::endl;
}
break;
}
}
}
S1 = S1_adder.calculate_sum();
S1p = S1p_adder.calculate_sum();
}
void calculate_Smn1_2(real & S1, real & S1p, bool verbose, const real & c, const real & m, const real & n, const real & n_c2k, const std::vector<real> & c2k, const real & eta)
{
adder S1_adder;
real a;
real change;
adder S1p_adder;
real ap;
real changep;
S1 = real::ZERO;
S1_adder.clear();
for (real k = real::ZERO; k <= n_c2k - real::ONE; k = k + real::ONE)
{
if (k > real::ZERO)
{
a = a * (real::ONE - eta * eta);
}
else
{
a = real::ONE;
}
change = c2k[gzbi(k)] * a;
S1 = S1 + change;
S1_adder.add(change);
if (k > real::ZERO && abs(change) > real::ZERO && abs(change / S1) < real::SMALL_ENOUGH)
{
if (verbose)
{
std::cout << "calculate_Smn1_2: " << (change / S1).get_string(10) << ", " << ((S1 - S1_adder.calculate_sum()) / S1_adder.calculate_sum()).get_string(10) << ", " << (change / S1_adder.calculate_sum()).get_string(10) << std::endl;
}
break;
}
}
S1 = S1_adder.calculate_sum();
S1p = real::ZERO;
S1p_adder.clear();
for (real k = real::ONE; k <= n_c2k - real::ONE; k = k + real::ONE)
{
if (k > real::ONE)
{
ap = ap * (real::ONE - eta * eta);
}
else
{
ap = real::ONE;
}
changep = c2k[gzbi(k)] * k * ap * (-real::TWO * eta);
S1p = S1p + changep;
S1p_adder.add(changep);
if (k > real::ONE && abs(changep) > real::ZERO && abs(changep / S1p) < real::SMALL_ENOUGH)
{
if (verbose)
{
std::cout << "calculate_Smn1_2: " << (changep / S1p).get_string(10) << ", " << ((S1p - S1p_adder.calculate_sum()) / S1p_adder.calculate_sum()).get_string(10) << ", " << (changep / S1p_adder.calculate_sum()).get_string(10) << std::endl;
}
break;
}
}
S1p = S1p_adder.calculate_sum();
if (remainder(n - m, real::TWO) == real::ZERO)
{
if (m > real::ZERO)
{
S1p = pow(-real::ONE, m) * (m / real::TWO) * pow(real::ONE - eta * eta, m / real::TWO - real::ONE) * (-real::TWO * eta) * S1 + pow(-real::ONE, m) * pow(real::ONE - eta * eta, m / real::TWO) * S1p;
}
else
{
S1p = pow(-real::ONE, m) * S1p;
}
S1 = pow(-real::ONE, m) * pow(real::ONE - eta * eta, m / real::TWO) * S1;
}
else
{
if (m > real::ZERO)
{
S1p = pow(-real::ONE, m) * pow(real::ONE - eta * eta, m / real::TWO) * S1 + pow(-real::ONE, m) * eta * (m / real::TWO) * pow(real::ONE - eta * eta, m / real::TWO - real::ONE) * (-real::TWO * eta) * S1 + pow(-real::ONE, m) * eta * pow(real::ONE - eta * eta, m / real::TWO) * S1p;
}
else
{
S1p = pow(-real::ONE, m) * S1 + pow(-real::ONE, m) * eta * S1p;
}
S1 = pow(-real::ONE, m) * eta * pow(real::ONE - eta * eta, m / real::TWO) * S1;
}
}
void calculate_Rmn1_1_shared(real & R1, real & R1p, bool verbose, const real & c, const real & m, const real & n, const real & n_dr, const std::vector<real> & dr, const real & xi)
{
std::vector<real> jn;
real b0;
std::vector<real> a;
std::vector<real> b;
real N;
real prev_N;
real s;
std::vector<real> jnp;
adder R1_adder;
adder R1p_adder;
real d;
real change;
real changep;
if (xi > real::ZERO)
{
jn.clear();
for (real v = real::ZERO; v <= m + n_dr; v = v + real::ONE)
{
jn.push_back(real::ZERO);
}
jn[gzbi(m + n_dr)] = real::ONE;
for (real v = m + n_dr; v >= real::ONE; v = v - real::ONE)
{
if (v < m + n_dr)
{
N = real::ONE / ((real::TWO * v + real::ONE) / (c * xi) - N);
}
else
{
b0 = real::ZERO;
a.clear();
b.clear();
for (real i = v; i < v + real("10000.0"); i = i + real::ONE)
{
a.push_back(real::ONE);
b.push_back((real::TWO * i + real::ONE) / (c * xi));
N = -calculate_continued_fraction(b0, a, b);
if (i > v)
{
if (abs((N - prev_N) / prev_N) < real::SMALL_ENOUGH)
{
if (verbose)
{
std::cout << "calculate_Rmn1_1: " << ((N - prev_N) / prev_N).get_string(10) << std::endl;
}
break;
}
}
prev_N = N;
}
}
jn[gzbi(v - real::ONE)] = jn[gzbi(v)] / N;
}
s = (sin(c * xi) / (c * xi)) / jn[gzbi(real::ZERO)];
for (real v = real::ZERO; v <= m + n_dr; v = v + real::ONE)
{
jn[gzbi(v)] = s * jn[gzbi(v)];
}
jnp.clear();
for (real v = real::ZERO; v <= m + n_dr - real::ONE; v = v + real::ONE)
{
jnp.push_back(real::ZERO);
}
for (real v = real::ZERO; v <= m + n_dr - real::ONE; v = v + real::ONE)
{
jnp[gzbi(v)] = (v / (c * xi)) * jn[gzbi(v)] - jn[gzbi(v + real::ONE)];
}
}
else
{
jn.clear();
jnp.clear();
for (real v = real::ZERO; v <= m + n_dr - real::ONE; v = v + real::ONE)
{
jn.push_back(real::ZERO);
jnp.push_back(real::ZERO);
}
jn[gzbi(real::ZERO)] = real::ONE;
jnp[gzbi(real::ONE)] = real::ONE / real::THREE;
}
R1 = real::ZERO;
R1_adder.clear();
R1p = real::ZERO;
R1p_adder.clear();
if (remainder(n - m, real::TWO) == real::ZERO)
{
for (real r = real::ZERO; r <= n_dr - real::TWO; r = r + real::TWO)
{
if (r > real::ZERO)
{
d = d * -real::ONE * (((real::TWO * m + r - real::ONE) * (real::TWO * m + r)) / ((r - real::ONE) * r));
}
else
{
d = pow(-real::ONE, -(n - m) / real::TWO) * factorial(real::TWO * m);
}
change = d * dr[gzbi(r)] * jn[gzbi(m + r)];
R1 = R1 + change;
R1_adder.add(change);
changep = d * dr[gzbi(r)] * jnp[gzbi(m + r)] * c;
R1p = R1p + changep;
R1p_adder.add(changep);
if (r > real::ZERO && abs(change) > real::ZERO && abs(change / R1) < real::SMALL_ENOUGH && abs(changep) > real::ZERO && abs(changep / R1p) < real::SMALL_ENOUGH)
{
if (verbose)
{
std::cout << "calculate_Rmn1_1: " << (change / R1).get_string(10) << ", " << (changep / R1p).get_string(10) << ", " << ((R1 - R1_adder.calculate_sum()) / R1_adder.calculate_sum()).get_string(10) << ", " << ((R1p - R1p_adder.calculate_sum()) / R1p_adder.calculate_sum()).get_string(10) << ", " << (change / R1_adder.calculate_sum()).get_string(10) << ", " << (changep / R1p_adder.calculate_sum()).get_string(10) << std::endl;
}
break;
}
}
}
else
{
for (real r = real::ONE; r <= n_dr - real::ONE; r = r + real::TWO)
{
if (r > real::ONE)
{
d = d * -real::ONE * (((real::TWO * m + r - real::ONE) * (real::TWO * m + r)) / ((r - real::ONE) * r));
}
else
{
d = pow(-real::ONE, (real::ONE - (n - m)) / real::TWO) * factorial(real::TWO * m + real::ONE);
}
change = d * dr[gzbi(r)] * jn[gzbi(m + r)];
R1 = R1 + change;
R1_adder.add(change);
changep = d * dr[gzbi(r)] * jnp[gzbi(m + r)] * c;
R1p = R1p + changep;
R1p_adder.add(changep);
if (r > real::ONE && abs(change) > real::ZERO && abs(change / R1) < real::SMALL_ENOUGH && abs(changep) > real::ZERO && abs(changep / R1p) < real::SMALL_ENOUGH)
{
if (verbose)
{
std::cout << "calculate_Rmn1_1: " << (change / R1).get_string(10) << ", " << (changep / R1p).get_string(10) << ", " << ((R1 - R1_adder.calculate_sum()) / R1_adder.calculate_sum()).get_string(10) << ", " << ((R1p - R1p_adder.calculate_sum()) / R1p_adder.calculate_sum()).get_string(10) << ", " << (change / R1_adder.calculate_sum()).get_string(10) << ", " << (changep / R1p_adder.calculate_sum()).get_string(10) << std::endl;
}
break;
}
}
}
R1 = R1_adder.calculate_sum();
R1p = R1p_adder.calculate_sum();
}
void calculate_Rmn2_1_shared(real & R2, real & R2p, bool verbose, const real & c, const real & m, const real & n, const real & n_dr, const std::vector<real> & dr, const real & xi)
{
real y0;
real y1;
real y2;
adder R2_adder;
adder R2p_adder;
real a;
real y0p;
real change;
real changep;
real y1p;
y0 = -cos(c * xi) / (c * xi);
y1 = -cos(c * xi) / ((c * xi) * (c * xi)) - sin(c * xi) / (c * xi);
for (real v = real::ZERO; v <= m - real::ONE; v = v + real::ONE)
{
y2 = -y0 + ((real::TWO * v + real::THREE) / (c * xi)) * y1;
y0 = y1;
y1 = y2;
}
R2 = real::ZERO;
R2_adder.clear();
R2p = real::ZERO;
R2p_adder.clear();
if (remainder(n - m, real::TWO) == real::ZERO)
{
for (real r = real::ZERO; r <= n_dr - real::TWO; r = r + real::TWO)
{
if (r > real::ZERO)
{
a = a * -real::ONE * (((real::TWO * m + r - real::ONE) * (real::TWO * m + r)) / ((r - real::ONE) * r));
}
else
{
a = pow(-real::ONE, -(n - m) / real::TWO) * factorial(real::TWO * m);
}
y0p = ((m + r) / (c * xi)) * y0 - y1;
change = a * dr[gzbi(r)] * y0;
R2 = R2 + change;
R2_adder.add(change);
changep = a * dr[gzbi(r)] * y0p * c;
R2p = R2p + changep;
R2p_adder.add(changep);
if (r > real::ZERO && abs(change) > real::ZERO && abs(change / R2) < real::SMALL_ENOUGH && abs(changep) > real::ZERO && abs(changep / R2p) < real::SMALL_ENOUGH)
{
if (verbose)
{
std::cout << "calculate_Rmn2_1: " << (change / R2).get_string(10) << ", " << (changep / R2p).get_string(10) << ", " << ((R2 - R2_adder.calculate_sum()) / R2_adder.calculate_sum()).get_string(10) << ", " << ((R2p - R2p_adder.calculate_sum()) / R2p_adder.calculate_sum()).get_string(10) << ", " << (change / R2_adder.calculate_sum()).get_string(10) << ", " << (changep / R2p_adder.calculate_sum()).get_string(10) << std::endl;
}
break;
}
y0 = -y0 + ((real::TWO * (m + r) + real::THREE) / (c * xi)) * y1;
y1 = -y1 + ((real::TWO * (m + r + real::ONE) + real::THREE) / (c * xi)) * y0;
}
}
else
{
for (real r = real::ONE; r <= n_dr - real::ONE; r = r + real::TWO)
{
if (r > real::ONE)
{
a = a * -real::ONE * (((real::TWO * m + r - real::ONE) * (real::TWO * m + r)) / ((r - real::ONE) * r));
}
else
{
a = pow(-real::ONE, (real::ONE - (n - m)) / real::TWO) * factorial(real::TWO * m + real::ONE);
}
y1p = y0 - ((m + r + real::ONE) / (c * xi)) * y1;
change = a * dr[gzbi(r)] * y1;
R2 = R2 + change;
R2_adder.add(change);
changep = a * dr[gzbi(r)] * y1p * c;
R2p = R2p + changep;
R2p_adder.add(changep);
if (r > real::ONE && abs(change) > real::ZERO && abs(change / R2) < real::SMALL_ENOUGH && abs(changep) > real::ZERO && abs(changep / R2p) < real::SMALL_ENOUGH)
{
if (verbose)
{
std::cout << "calculate_Rmn2_1: " << (change / R2).get_string(10) << ", " << (changep / R2p).get_string(10) << ", " << ((R2 - R2_adder.calculate_sum()) / R2_adder.calculate_sum()).get_string(10) << ", " << ((R2p - R2p_adder.calculate_sum()) / R2p_adder.calculate_sum()).get_string(10) << ", " << (change / R2_adder.calculate_sum()).get_string(10) << ", " << (changep / R2p_adder.calculate_sum()).get_string(10) << std::endl;
}
break;
}
y0 = -y0 + ((real::TWO * (m + r - real::ONE) + real::THREE) / (c * xi)) * y1;
y1 = -y1 + ((real::TWO * (m + r) + real::THREE) / (c * xi)) * y0;
}
}
R2 = R2_adder.calculate_sum();
R2p = R2p_adder.calculate_sum();
}
| 30.826566 | 429 | 0.540979 | SabininGV |
8e4850d32d9150a7bd458a3aac406739d0b10131 | 1,900 | cpp | C++ | example/sqlite.cpp | vashman/data_pattern_sqlite | 8ed3d1fe3e86ea7165d43277feb05d84189f696e | [
"BSL-1.0"
] | null | null | null | example/sqlite.cpp | vashman/data_pattern_sqlite | 8ed3d1fe3e86ea7165d43277feb05d84189f696e | [
"BSL-1.0"
] | null | null | null | example/sqlite.cpp | vashman/data_pattern_sqlite | 8ed3d1fe3e86ea7165d43277feb05d84189f696e | [
"BSL-1.0"
] | null | null | null | //
// Copyright Sundeep S. Sangha 2015 - 2017.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <cassert>
#include <data_pattern/raw.hpp>
#include "../src/sqlite.cpp"
using data_pattern_sqlite::sqlite;
using data_pattern_sqlite::open_database;
using data_pattern_sqlite::sqlite_statement;
int main () {
sqlite db = open_database("testdata");
/* Create the table if it does not exist yet. */
sqlite_statement s1 (
db
, "CREATE TABLE IF NOT EXISTS test3"
"(Value INT, str TEXT, dec REAL, raw Blob);"
);
sqlite_statement query1 (
db
, "CREATE TABLE IF NOT EXISTS test"
"(ID INT PRIMARY KEY NOT NULL, Value INT);"
);
auto query2 = sqlite_statement (
db
, "INSERT INTO test3 "
"(Value, str, dec, raw) Values (?,?,?,?);"
);
bind(query2, 45);
bind(query2, std::string("test string"));
bind(query2, 12.04);
bind(query2, data_pattern::raw<>("0101", 4));
if (is_bind_done(query2)) step(query2);
auto query3 ( sqlite_statement (
db, "INSERT INTO test (ID, Value) Values (?, ?);" ));
bind(query3, 2);
bind(query3, 28);
if (is_bind_done(query3)) step(query3);
// Retrive data
auto select1 (
sqlite_statement (db, "SELECT ID, Value FROM test;"));
int tmp_int (column_int(select1));
int temp_int = column_int(select1);
assert (tmp_int == 2);
assert (temp_int == 28);
auto select2 ( sqlite_statement (
db
, "SELECT Value, dec, str, raw FROM test3;"
));
temp_int = column_int(select2);
double temp_dbl (column_double(select2));
auto temp_str = column_string(select2);
data_pattern::raw<> temp_raw = column_raw(select2);
assert (temp_int == 45);
assert (temp_str == sqlite_statement::string_t(reinterpret_cast<const unsigned char*>("test string")));
assert (temp_dbl == 12.04);
assert (temp_raw == data_pattern::raw<>("0101", 4));
return 0;
}
| 24.675325 | 103 | 0.692632 | vashman |
8e56dacb9ee6afeda813d52865390d9dae70ab66 | 956 | hpp | C++ | boost/network/protocol/http/message/wrappers/uri.hpp | sureandrew/cpp-netlib | a4dabd50dcd42f46ac152c733a3d39f32040185d | [
"BSL-1.0"
] | null | null | null | boost/network/protocol/http/message/wrappers/uri.hpp | sureandrew/cpp-netlib | a4dabd50dcd42f46ac152c733a3d39f32040185d | [
"BSL-1.0"
] | null | null | null | boost/network/protocol/http/message/wrappers/uri.hpp | sureandrew/cpp-netlib | a4dabd50dcd42f46ac152c733a3d39f32040185d | [
"BSL-1.0"
] | 1 | 2018-08-07T07:27:49.000Z | 2018-08-07T07:27:49.000Z | #ifndef BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_WRAPPERS_URI_HPP_20100620
#define BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_WRAPPERS_URI_HPP_20100620
// Copyright 2010 (c) Dean Michael Berris.
// Copyright 2010 (c) Sinefunc, Inc.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <network/uri/uri.hpp>
#include <boost/network/protocol/http/request/request_base.hpp>
namespace boost { namespace network { namespace http {
struct uri_wrapper {
explicit uri_wrapper(request_base const & request_);
operator std::string() const;
operator ::network::uri() const;
private:
request_base const & request_;
};
inline
uri_wrapper const
uri(request_base const & request) {
return uri_wrapper(request);
}
} // namespace http
} // namespace network
} // namespace boost
#endif // BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_WRAPPERS_URI_HPP_20100620
| 26.555556 | 71 | 0.781381 | sureandrew |
8e57e7856a533c08f12ef719a0868f644ad6d3f9 | 1,331 | cpp | C++ | core/main_thread.cpp | mail-ru-im/im-desktop | d6bb606650ad84b31046fe39b81db1fec4e6050b | [
"Apache-2.0"
] | 81 | 2019-09-18T13:53:17.000Z | 2022-03-19T00:44:20.000Z | core/main_thread.cpp | mail-ru-im/im-desktop | d6bb606650ad84b31046fe39b81db1fec4e6050b | [
"Apache-2.0"
] | 4 | 2019-10-03T15:17:00.000Z | 2019-11-03T01:05:41.000Z | core/main_thread.cpp | mail-ru-im/im-desktop | d6bb606650ad84b31046fe39b81db1fec4e6050b | [
"Apache-2.0"
] | 25 | 2019-09-27T16:56:02.000Z | 2022-03-14T07:11:14.000Z | #include "stdafx.h"
#include "main_thread.h"
#include "core.h"
#include "network_log.h"
using namespace core;
main_thread::main_thread()
: threadpool("core main", 1 )
{
set_task_finish_callback([](std::chrono::milliseconds _task_execute_time, const stack_vec& _st, std::string_view _name)
{
if (_task_execute_time > std::chrono::milliseconds(200) && !_st.empty())
{
std::stringstream ss;
ss << "ATTENTION! Core locked, ";
if (!_name.empty())
ss << "task name: " << _name << ", ";
ss << _task_execute_time.count() << " milliseconds\r\n\r\n";
for (const auto& s : _st)
{
ss << *s;
ss << "\r\n - - - - - \r\n";
}
g_core->write_string_to_network_log(ss.str());
}
});
}
main_thread::~main_thread() = default;
void main_thread::execute_core_context(stacked_task task)
{
push_back(std::move(task));
}
std::thread::id main_thread::get_core_thread_id() const
{
if (const auto& thread_ids = get_threads_ids(); thread_ids.size() == 1)
{
return thread_ids[0];
}
else
{
im_assert(thread_ids.size() == 1);
return std::thread::id(); // nobody
}
}
| 24.648148 | 124 | 0.53118 | mail-ru-im |
8e5cd80a6c178aa7527c6a86043feb6b5f7019f2 | 10,986 | cpp | C++ | src/entity/RTraceEntity.cpp | ouxianghui/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | 12 | 2021-03-26T03:23:30.000Z | 2021-12-31T10:05:44.000Z | src/entity/RTraceEntity.cpp | 15831944/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | null | null | null | src/entity/RTraceEntity.cpp | 15831944/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | 9 | 2021-06-23T08:26:40.000Z | 2022-01-20T07:18:10.000Z | /**
* Copyright (c) 2011-2016 by Andrew Mustun. All rights reserved.
*
* This file is part of the QCAD project.
*
* QCAD is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QCAD 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 QCAD.
*/
#include "RTraceEntity.h"
#include "RExporter.h"
#include "RLine.h"
RPropertyTypeId RTraceEntity::PropertyCustom;
RPropertyTypeId RTraceEntity::PropertyHandle;
RPropertyTypeId RTraceEntity::PropertyProtected;
RPropertyTypeId RTraceEntity::PropertyType;
RPropertyTypeId RTraceEntity::PropertyBlock;
RPropertyTypeId RTraceEntity::PropertyLayer;
RPropertyTypeId RTraceEntity::PropertyLinetype;
RPropertyTypeId RTraceEntity::PropertyLinetypeScale;
RPropertyTypeId RTraceEntity::PropertyLineweight;
RPropertyTypeId RTraceEntity::PropertyColor;
RPropertyTypeId RTraceEntity::PropertyDisplayedColor;
RPropertyTypeId RTraceEntity::PropertyDrawOrder;
RPropertyTypeId RTraceEntity::PropertyPoint1X;
RPropertyTypeId RTraceEntity::PropertyPoint1Y;
RPropertyTypeId RTraceEntity::PropertyPoint1Z;
RPropertyTypeId RTraceEntity::PropertyPoint2X;
RPropertyTypeId RTraceEntity::PropertyPoint2Y;
RPropertyTypeId RTraceEntity::PropertyPoint2Z;
RPropertyTypeId RTraceEntity::PropertyPoint3X;
RPropertyTypeId RTraceEntity::PropertyPoint3Y;
RPropertyTypeId RTraceEntity::PropertyPoint3Z;
RPropertyTypeId RTraceEntity::PropertyPoint4X;
RPropertyTypeId RTraceEntity::PropertyPoint4Y;
RPropertyTypeId RTraceEntity::PropertyPoint4Z;
RPropertyTypeId RTraceEntity::PropertyLength;
RPropertyTypeId RTraceEntity::PropertyTotalLength;
RTraceEntity::RTraceEntity(RDocument* document, const RTraceData& data) :
REntity(document), data(document, data) {
}
RTraceEntity::~RTraceEntity() {
}
void RTraceEntity::init() {
RTraceEntity::PropertyCustom.generateId(typeid(RTraceEntity), RObject::PropertyCustom);
RTraceEntity::PropertyHandle.generateId(typeid(RTraceEntity), RObject::PropertyHandle);
RTraceEntity::PropertyProtected.generateId(typeid(RTraceEntity), RObject::PropertyProtected);
RTraceEntity::PropertyType.generateId(typeid(RTraceEntity), REntity::PropertyType);
RTraceEntity::PropertyBlock.generateId(typeid(RTraceEntity), REntity::PropertyBlock);
RTraceEntity::PropertyLayer.generateId(typeid(RTraceEntity), REntity::PropertyLayer);
RTraceEntity::PropertyLinetype.generateId(typeid(RTraceEntity), REntity::PropertyLinetype);
RTraceEntity::PropertyLinetypeScale.generateId(typeid(RTraceEntity), REntity::PropertyLinetypeScale);
RTraceEntity::PropertyLineweight.generateId(typeid(RTraceEntity), REntity::PropertyLineweight);
RTraceEntity::PropertyColor.generateId(typeid(RTraceEntity), REntity::PropertyColor);
RTraceEntity::PropertyDisplayedColor.generateId(typeid(RTraceEntity), REntity::PropertyDisplayedColor);
RTraceEntity::PropertyDrawOrder.generateId(typeid(RTraceEntity), REntity::PropertyDrawOrder);
RTraceEntity::PropertyPoint1X.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 1"), QT_TRANSLATE_NOOP("REntity", "X"));
RTraceEntity::PropertyPoint1Y.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 1"), QT_TRANSLATE_NOOP("REntity", "Y"));
RTraceEntity::PropertyPoint1Z.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 1"), QT_TRANSLATE_NOOP("REntity", "Z"));
RTraceEntity::PropertyPoint2X.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 2"), QT_TRANSLATE_NOOP("REntity", "X"));
RTraceEntity::PropertyPoint2Y.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 2"), QT_TRANSLATE_NOOP("REntity", "Y"));
RTraceEntity::PropertyPoint2Z.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 2"), QT_TRANSLATE_NOOP("REntity", "Z"));
RTraceEntity::PropertyPoint3X.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 3"), QT_TRANSLATE_NOOP("REntity", "X"));
RTraceEntity::PropertyPoint3Y.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 3"), QT_TRANSLATE_NOOP("REntity", "Y"));
RTraceEntity::PropertyPoint3Z.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 3"), QT_TRANSLATE_NOOP("REntity", "Z"));
RTraceEntity::PropertyPoint4X.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 4"), QT_TRANSLATE_NOOP("REntity", "X"));
RTraceEntity::PropertyPoint4Y.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 4"), QT_TRANSLATE_NOOP("REntity", "Y"));
RTraceEntity::PropertyPoint4Z.generateId(typeid(RTraceEntity), QT_TRANSLATE_NOOP("REntity", "Point 4"), QT_TRANSLATE_NOOP("REntity", "Z"));
RTraceEntity::PropertyLength.generateId(typeid(RTraceEntity), "", QT_TRANSLATE_NOOP("REntity", "Length"));
RTraceEntity::PropertyTotalLength.generateId(typeid(RTraceEntity), "", QT_TRANSLATE_NOOP("REntity", "Total Length"));
}
bool RTraceEntity::setProperty(RPropertyTypeId propertyTypeId,
const QVariant& value, RTransaction* transaction) {
bool ret = REntity::setProperty(propertyTypeId, value, transaction);
if (propertyTypeId==PropertyPoint1X || propertyTypeId==PropertyPoint1Y || propertyTypeId==PropertyPoint1Z) {
RVector v = data.getVertexAt(0);
if (propertyTypeId==PropertyPoint1X) {
v.x = value.toDouble();
}
else if (propertyTypeId==PropertyPoint1Y) {
v.y = value.toDouble();
}
else if (propertyTypeId==PropertyPoint1Z) {
v.z = value.toDouble();
}
data.setVertexAt(0, v);
ret = true;
}
else if (propertyTypeId==PropertyPoint2X || propertyTypeId==PropertyPoint2Y || propertyTypeId==PropertyPoint2Z) {
RVector v = data.getVertexAt(1);
if (propertyTypeId==PropertyPoint2X) {
v.x = value.toDouble();
}
else if (propertyTypeId==PropertyPoint2Y) {
v.y = value.toDouble();
}
else if (propertyTypeId==PropertyPoint2Z) {
v.z = value.toDouble();
}
data.setVertexAt(1, v);
ret = true;
}
else if (propertyTypeId==PropertyPoint3X || propertyTypeId==PropertyPoint3Y || propertyTypeId==PropertyPoint3Z) {
RVector v = data.getVertexAt(2);
if (propertyTypeId==PropertyPoint3X) {
v.x = value.toDouble();
}
else if (propertyTypeId==PropertyPoint3Y) {
v.y = value.toDouble();
}
else if (propertyTypeId==PropertyPoint3Z) {
v.z = value.toDouble();
}
data.setVertexAt(2, v);
ret = true;
}
else if (propertyTypeId==PropertyPoint4X || propertyTypeId==PropertyPoint4Y || propertyTypeId==PropertyPoint4Z) {
if (data.countVertices()<4) {
data.appendVertex(RVector(0,0,0));
}
RVector v = data.getVertexAt(3);
if (propertyTypeId==PropertyPoint4X) {
v.x = value.toDouble();
}
else if (propertyTypeId==PropertyPoint4Y) {
v.y = value.toDouble();
}
else if (propertyTypeId==PropertyPoint4Z) {
v.z = value.toDouble();
}
data.setVertexAt(3, v);
ret = true;
}
return ret;
}
QPair<QVariant, RPropertyAttributes> RTraceEntity::getProperty(
RPropertyTypeId& propertyTypeId, bool humanReadable,
bool noAttributes) {
if (propertyTypeId == PropertyPoint1X) {
return qMakePair(QVariant(data.getVertexAt(0).x), RPropertyAttributes());
} else if (propertyTypeId == PropertyPoint1Y) {
return qMakePair(QVariant(data.getVertexAt(0).y), RPropertyAttributes());
} else if (propertyTypeId == PropertyPoint1Z) {
return qMakePair(QVariant(data.getVertexAt(0).z), RPropertyAttributes());
} else if (propertyTypeId == PropertyPoint2X) {
return qMakePair(QVariant(data.getVertexAt(1).x), RPropertyAttributes());
} else if (propertyTypeId == PropertyPoint2Y) {
return qMakePair(QVariant(data.getVertexAt(1).y), RPropertyAttributes());
} else if (propertyTypeId == PropertyPoint2Z) {
return qMakePair(QVariant(data.getVertexAt(1).z), RPropertyAttributes());
}else if (propertyTypeId == PropertyPoint3X) {
return qMakePair(QVariant(data.getVertexAt(2).x), RPropertyAttributes());
} else if (propertyTypeId == PropertyPoint3Y) {
return qMakePair(QVariant(data.getVertexAt(2).y), RPropertyAttributes());
} else if (propertyTypeId == PropertyPoint3Z) {
return qMakePair(QVariant(data.getVertexAt(2).z), RPropertyAttributes());
}else if (propertyTypeId == PropertyPoint4X) {
if (data.countVertices()<4) {
return qMakePair(QVariant(), RPropertyAttributes());
}
return qMakePair(QVariant(data.getVertexAt(3).x), RPropertyAttributes());
} else if (propertyTypeId == PropertyPoint4Y) {
if (data.countVertices()<4) {
return qMakePair(QVariant(), RPropertyAttributes());
}
return qMakePair(QVariant(data.getVertexAt(3).y), RPropertyAttributes());
} else if (propertyTypeId == PropertyPoint4Z) {
if (data.countVertices()<4) {
return qMakePair(QVariant(), RPropertyAttributes());
}
return qMakePair(QVariant(data.getVertexAt(3).z), RPropertyAttributes());
} else if (propertyTypeId==PropertyLength) {
return qMakePair(QVariant(data.getLength()), RPropertyAttributes(RPropertyAttributes::ReadOnly));
} else if (propertyTypeId==PropertyTotalLength) {
return qMakePair(QVariant(data.getLength()), RPropertyAttributes(RPropertyAttributes::Sum));
}
return REntity::getProperty(propertyTypeId, humanReadable, noAttributes);
}
void RTraceEntity::exportEntity(RExporter& e, bool preview, bool forceSelected) const {
Q_UNUSED(preview);
Q_UNUSED(forceSelected);
// note that order of fourth and third vertex is swapped:
RPolyline pl;
pl.appendVertex(data.getVertexAt(0));
pl.appendVertex(data.getVertexAt(1));
if (data.countVertices()>3) {
pl.appendVertex(data.getVertexAt(3));
}
pl.appendVertex(data.getVertexAt(2));
pl.setClosed(true);
e.exportPolyline(pl);
}
void RTraceEntity::print(QDebug dbg) const {
dbg.nospace() << "RTraceEntity(";
REntity::print(dbg);
dbg.nospace() << ", p1: " << getData().getVertexAt(0)
<< ", p2: " << getData().getVertexAt(1)
<< ", p3: " << getData().getVertexAt(2)
<< ", p4: " << getData().getVertexAt(3);
dbg.nospace() << ")";
}
| 47.558442 | 143 | 0.712725 | ouxianghui |
769defd8740a99022c6aa54d6f2c3fa273a2c056 | 2,595 | cpp | C++ | include/h3api/H3AdventureMap/H3TileVision.cpp | Patrulek/H3API | 91f10de37c6b86f3160706c1fdf4792f927e9952 | [
"MIT"
] | 14 | 2020-09-07T21:49:26.000Z | 2021-11-29T18:09:41.000Z | include/h3api/H3AdventureMap/H3TileVision.cpp | Day-of-Reckoning/H3API | a82d3069ec7d5127b13528608d5350d2b80d57be | [
"MIT"
] | 2 | 2021-02-12T15:52:31.000Z | 2021-02-12T16:21:24.000Z | include/h3api/H3AdventureMap/H3TileVision.cpp | Day-of-Reckoning/H3API | a82d3069ec7d5127b13528608d5350d2b80d57be | [
"MIT"
] | 8 | 2021-02-12T15:52:41.000Z | 2022-01-31T15:28:10.000Z | //////////////////////////////////////////////////////////////////////
// //
// Created by RoseKavalier: //
// [email protected] //
// Created or last updated on: 2021-02-02 //
// ***You may use or distribute these files freely //
// so long as this notice remains present.*** //
// //
//////////////////////////////////////////////////////////////////////
#include "h3api/H3AdventureMap/H3TileVision.hpp"
#include "h3api/H3GameData/H3Main.hpp"
#include "h3api/H3Defines/H3PrimitivePointers.hpp"
namespace h3
{
_H3API_ H3TileVision& H3TileVision::GetTile(INT32 x, INT32 y, INT32 z)
{
return FASTCALL_3(H3TileVision&, 0x4F8070, x, y, z);
}
_H3API_ H3TileVision& H3TileVision::GetTile(const H3Point& p)
{
return GetTile(p.x, p.y, p.z);
}
_H3API_ H3TileVision& H3TileVision::GetTile(const H3Position& p)
{
return GetTile(p.Unpack());
}
_H3API_ BOOL H3TileVision::CanViewTile(INT32 x, INT32 y, INT32 z, INT32 player /*= -1*/)
{
if (player < 0)
player = H3CurrentPlayerID::Get();
return GetTile(x, y, z).vision.bits & (1 << player);
}
_H3API_ BOOL H3TileVision::CanViewTile(const H3Point& p, INT32 player /*= -1*/)
{
return CanViewTile(p.x, p.y, p.z, player);
}
_H3API_ BOOL H3TileVision::CanViewTile(const H3Position& p, INT32 player /*= -1*/)
{
return CanViewTile(p.Unpack(), player);
}
_H3API_ VOID H3TileVision::RevealTile(INT32 x, INT32 y, INT32 z, INT32 player /*= -1*/)
{
if (player < 0)
player = H3CurrentPlayerID::Get();
GetTile(x, y, z).vision.bits |= (1 << player);
}
_H3API_ VOID H3TileVision::RevealTile(const H3Point& p, INT32 player /*= -1*/)
{
RevealTile(p.x, p.y, p.z, player);
}
_H3API_ VOID H3TileVision::RevealTile(const H3Position& p, INT32 player /*= -1*/)
{
RevealTile(p.Unpack(), player);
}
_H3API_ H3Map<H3TileVision> H3TileVision::GetMap()
{
return H3Map<H3TileVision>(Get(), H3MapSize::Get(), H3Main::Get()->mainSetup.hasUnderground);
}
_H3API_ H3FastMap<H3TileVision> H3TileVision::GetFastMap()
{
return H3FastMap<H3TileVision>(Get(), H3MapSize::Get(), H3Main::Get()->mainSetup.hasUnderground);
}
} /* namespace h3 */
| 34.144737 | 105 | 0.522158 | Patrulek |
76a737fb754ed01d961158bf576bab13ca7e6ebe | 887 | cpp | C++ | MPI2Send/MPI2Send27.cpp | bru1t/pt-for-mpi-2-answers | 81595465725db4cce848a1c45b3695203d97db03 | [
"Unlicense"
] | 2 | 2021-12-26T20:18:24.000Z | 2021-12-28T10:49:42.000Z | MPI2Send/MPI2Send27.cpp | bru1t/pt-for-mpi-2-answers | 81595465725db4cce848a1c45b3695203d97db03 | [
"Unlicense"
] | null | null | null | MPI2Send/MPI2Send27.cpp | bru1t/pt-for-mpi-2-answers | 81595465725db4cce848a1c45b3695203d97db03 | [
"Unlicense"
] | null | null | null | #include "pt4.h"
#include "mpi.h"
void Solve()
{
Task("MPI2Send27");
int flag;
MPI_Initialized(&flag);
if (flag == 0)
return;
int rank, size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int n;
pt >> n;
if (n == -1) {
int num = 0;
for (int i = 0; i < size - 1; ++i) {
if (rank == num)
++num;
double t;
MPI_Recv(&t, 1, MPI_DOUBLE, MPI_ANY_SOURCE, num, MPI_COMM_WORLD, MPI_STATUSES_IGNORE);
pt << t;
++num;
}
}
else {
double a;
pt >> a;
int num = 0;
MPI_Request req;
MPI_Issend(&a, 1, MPI_DOUBLE, n, rank, MPI_COMM_WORLD, &req);
MPI_Status status;
int check = 0;
while (check == 0) {
MPI_Test(&req, &check, &status);
++num;
}
Show(num);
}
}
| 16.127273 | 93 | 0.487035 | bru1t |
76a7965ffae35f6c73dacb9213b012580a657853 | 735 | cpp | C++ | include/general.cpp | denisjackman/Cee | 2176e9dccc17ac93463bd5473f437f1c76ba9c3c | [
"CC-BY-4.0"
] | null | null | null | include/general.cpp | denisjackman/Cee | 2176e9dccc17ac93463bd5473f437f1c76ba9c3c | [
"CC-BY-4.0"
] | 2 | 2016-06-30T14:31:43.000Z | 2016-07-01T08:43:03.000Z | include/general.cpp | denisjackman/game | 2176e9dccc17ac93463bd5473f437f1c76ba9c3c | [
"CC-BY-4.0"
] | null | null | null | #include <cstdlib>
#include <ctime>
#include <cmath>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <list>
using namespace std;
bool gDebugMode = false;
string gDebugLogFileLocation = "debug.log";
ofstream gDebugLogFile;
void DebugModeInitialise()
{
if (gDebugMode)
{
gDebugLogFile.open(gDebugLogFileLocation);
}
}
void DebugModeTerminate()
{
if (gDebugMode)
{
gDebugLogFile.close();
}
}
void Print(string OutputString)
{
if (gDebugMode)
{
gDebugLogFile << OutputString << endl;
}
cout << OutputString << endl;
}
void Pause()
{
do {
cout << endl << "Press the Enter key to continue.";
} while (cin.get() != '\n');
} | 15.978261 | 58 | 0.634014 | denisjackman |
76a7fad4d057925cfa08390226478c081f689f57 | 103 | cxx | C++ | tests/TestUtil/message_for_assert.cxx | SergeyKleyman/elastic-apm-agent-cpp-prototype | 67d2c7ad5a50e1a6b75d6725a89ae3fc5a92d517 | [
"Apache-2.0"
] | null | null | null | tests/TestUtil/message_for_assert.cxx | SergeyKleyman/elastic-apm-agent-cpp-prototype | 67d2c7ad5a50e1a6b75d6725a89ae3fc5a92d517 | [
"Apache-2.0"
] | null | null | null | tests/TestUtil/message_for_assert.cxx | SergeyKleyman/elastic-apm-agent-cpp-prototype | 67d2c7ad5a50e1a6b75d6725a89ae3fc5a92d517 | [
"Apache-2.0"
] | null | null | null | // TODO: Sergey Kleyman: Remove if I don't need it anymore
// #include "message_for_assert.hxx"
//
| 20.6 | 58 | 0.68932 | SergeyKleyman |
76a995b55aba98ae09015b150c7896960361cf93 | 15,342 | hpp | C++ | INCLUDE/Vcl/ibinstall.hpp | earthsiege2/borland-cpp-ide | 09bcecc811841444338e81b9c9930c0e686f9530 | [
"Unlicense",
"FSFAP",
"Apache-1.1"
] | 1 | 2022-01-13T01:03:55.000Z | 2022-01-13T01:03:55.000Z | INCLUDE/Vcl/ibinstall.hpp | earthsiege2/borland-cpp-ide | 09bcecc811841444338e81b9c9930c0e686f9530 | [
"Unlicense",
"FSFAP",
"Apache-1.1"
] | null | null | null | INCLUDE/Vcl/ibinstall.hpp | earthsiege2/borland-cpp-ide | 09bcecc811841444338e81b9c9930c0e686f9530 | [
"Unlicense",
"FSFAP",
"Apache-1.1"
] | null | null | null | // Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'IBInstall.pas' rev: 6.00
#ifndef IBInstallHPP
#define IBInstallHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <IBXConst.hpp> // Pascal unit
#include <IBIntf.hpp> // Pascal unit
#include <IBInstallHeader.hpp> // Pascal unit
#include <IB.hpp> // Pascal unit
#include <Classes.hpp> // Pascal unit
#include <SysUtils.hpp> // Pascal unit
#include <TypInfo.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Ibinstall
{
//-- type declarations -------------------------------------------------------
typedef int TIscError;
#pragma option push -b-
enum TIBInstallerError { ieSuccess, ieDelphiException, ieNoOptionsSet, ieNoDestinationDirectory, ieNosourceDirectory, ieNoUninstallFile, ieOptionNeedsClient, ieOptionNeedsServer, ieInvalidOption, ieInvalidOnErrorResult, ieInvalidOnStatusResult };
#pragma option pop
#pragma option push -b-
enum TMainOption { moServer, moClient, moConServer, moGuiTools, moDocumentation, moDevelopment };
#pragma option pop
#pragma option push -b-
enum TExamplesOption { exDB, exAPI };
#pragma option pop
#pragma option push -b-
enum TCmdOption { cmDBMgmt, cmDBQuery, cmUsrMgmt };
#pragma option pop
#pragma option push -b-
enum TConnectivityOption { cnODBC, cnOLEDB, cnJDBC };
#pragma option pop
typedef Set<TMainOption, moServer, moDevelopment> TMainOptions;
typedef Set<TExamplesOption, exDB, exAPI> TExamplesOptions;
typedef Set<TCmdOption, cmDBMgmt, cmUsrMgmt> TCmdOptions;
typedef Set<TConnectivityOption, cnODBC, cnJDBC> TConnectivityOptions;
#pragma option push -b-
enum TErrorResult { erAbort, erContinue, erRetry };
#pragma option pop
#pragma option push -b-
enum TStatusResult { srAbort, srContinue };
#pragma option pop
#pragma option push -b-
enum TWarningResult { wrAbort, wrContinue };
#pragma option pop
typedef TStatusResult __fastcall (__closure *TIBSetupOnStatus)(System::TObject* Sender, AnsiString StatusComment);
typedef TWarningResult __fastcall (__closure *TIBSetupOnWarning)(System::TObject* Sender, int WarningCode, AnsiString WarningMessage);
typedef TErrorResult __fastcall (__closure *TIBSetupOnError)(System::TObject* Sender, int IscCode, AnsiString ErrorMessage, AnsiString ErrorComment);
class DELPHICLASS EIBInstall;
class PASCALIMPLEMENTATION EIBInstall : public Sysutils::Exception
{
typedef Sysutils::Exception inherited;
private:
int FIscError;
TIBInstallerError FInstallerError;
public:
__fastcall virtual EIBInstall(int IscCode, AnsiString IscMessage)/* overload */;
__fastcall virtual EIBInstall(TIBInstallerError ECode, AnsiString EMessage)/* overload */;
__property int InstallError = {read=FIscError, nodefault};
__property TIBInstallerError InstallerError = {read=FInstallerError, nodefault};
public:
#pragma option push -w-inl
/* Exception.CreateFmt */ inline __fastcall EIBInstall(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size) : Sysutils::Exception(Msg, Args, Args_Size) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateRes */ inline __fastcall EIBInstall(int Ident)/* overload */ : Sysutils::Exception(Ident) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResFmt */ inline __fastcall EIBInstall(int Ident, const System::TVarRec * Args, const int Args_Size)/* overload */ : Sysutils::Exception(Ident, Args, Args_Size) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateHelp */ inline __fastcall EIBInstall(const AnsiString Msg, int AHelpContext) : Sysutils::Exception(Msg, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateFmtHelp */ inline __fastcall EIBInstall(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size, int AHelpContext) : Sysutils::Exception(Msg, Args, Args_Size, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResHelp */ inline __fastcall EIBInstall(int Ident, int AHelpContext)/* overload */ : Sysutils::Exception(Ident, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResFmtHelp */ inline __fastcall EIBInstall(System::PResStringRec ResStringRec, const System::TVarRec * Args, const int Args_Size, int AHelpContext)/* overload */ : Sysutils::Exception(ResStringRec, Args, Args_Size, AHelpContext) { }
#pragma option pop
public:
#pragma option push -w-inl
/* TObject.Destroy */ inline __fastcall virtual ~EIBInstall(void) { }
#pragma option pop
};
class DELPHICLASS EIBInstallError;
class PASCALIMPLEMENTATION EIBInstallError : public EIBInstall
{
typedef EIBInstall inherited;
public:
#pragma option push -w-inl
/* EIBInstall.Create */ inline __fastcall virtual EIBInstallError(int IscCode, AnsiString IscMessage)/* overload */ : EIBInstall(IscCode, IscMessage) { }
#pragma option pop
public:
#pragma option push -w-inl
/* Exception.CreateFmt */ inline __fastcall EIBInstallError(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size) : EIBInstall(Msg, Args, Args_Size) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateRes */ inline __fastcall EIBInstallError(int Ident)/* overload */ : EIBInstall(Ident) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResFmt */ inline __fastcall EIBInstallError(int Ident, const System::TVarRec * Args, const int Args_Size)/* overload */ : EIBInstall(Ident, Args, Args_Size) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateHelp */ inline __fastcall EIBInstallError(const AnsiString Msg, int AHelpContext) : EIBInstall(Msg, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateFmtHelp */ inline __fastcall EIBInstallError(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size, int AHelpContext) : EIBInstall(Msg, Args, Args_Size, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResHelp */ inline __fastcall EIBInstallError(int Ident, int AHelpContext)/* overload */ : EIBInstall(Ident, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResFmtHelp */ inline __fastcall EIBInstallError(System::PResStringRec ResStringRec, const System::TVarRec * Args, const int Args_Size, int AHelpContext)/* overload */ : EIBInstall(ResStringRec, Args, Args_Size, AHelpContext) { }
#pragma option pop
public:
#pragma option push -w-inl
/* TObject.Destroy */ inline __fastcall virtual ~EIBInstallError(void) { }
#pragma option pop
};
class DELPHICLASS EIBInstallerError;
class PASCALIMPLEMENTATION EIBInstallerError : public EIBInstall
{
typedef EIBInstall inherited;
public:
#pragma option push -w-inl
/* EIBInstall.Create */ inline __fastcall virtual EIBInstallerError(int IscCode, AnsiString IscMessage)/* overload */ : EIBInstall(IscCode, IscMessage) { }
#pragma option pop
public:
#pragma option push -w-inl
/* Exception.CreateFmt */ inline __fastcall EIBInstallerError(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size) : EIBInstall(Msg, Args, Args_Size) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateRes */ inline __fastcall EIBInstallerError(int Ident)/* overload */ : EIBInstall(Ident) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResFmt */ inline __fastcall EIBInstallerError(int Ident, const System::TVarRec * Args, const int Args_Size)/* overload */ : EIBInstall(Ident, Args, Args_Size) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateHelp */ inline __fastcall EIBInstallerError(const AnsiString Msg, int AHelpContext) : EIBInstall(Msg, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateFmtHelp */ inline __fastcall EIBInstallerError(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size, int AHelpContext) : EIBInstall(Msg, Args, Args_Size, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResHelp */ inline __fastcall EIBInstallerError(int Ident, int AHelpContext)/* overload */ : EIBInstall(Ident, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResFmtHelp */ inline __fastcall EIBInstallerError(System::PResStringRec ResStringRec, const System::TVarRec * Args, const int Args_Size, int AHelpContext)/* overload */ : EIBInstall(ResStringRec, Args, Args_Size, AHelpContext) { }
#pragma option pop
public:
#pragma option push -w-inl
/* TObject.Destroy */ inline __fastcall virtual ~EIBInstallerError(void) { }
#pragma option pop
};
class DELPHICLASS TInstallOptions;
class PASCALIMPLEMENTATION TInstallOptions : public Classes::TPersistent
{
typedef Classes::TPersistent inherited;
private:
TMainOptions FMainComponents;
TExamplesOptions FExamples;
TCmdOptions FCmdLineTools;
TConnectivityOptions FConnectivityClients;
__published:
__property TMainOptions MainComponents = {read=FMainComponents, write=FMainComponents, nodefault};
__property TCmdOptions CmdLineTools = {read=FCmdLineTools, write=FCmdLineTools, nodefault};
__property TConnectivityOptions ConnectivityClients = {read=FConnectivityClients, write=FConnectivityClients, nodefault};
__property TExamplesOptions Examples = {read=FExamples, write=FExamples, nodefault};
public:
#pragma option push -w-inl
/* TPersistent.Destroy */ inline __fastcall virtual ~TInstallOptions(void) { }
#pragma option pop
public:
#pragma option push -w-inl
/* TObject.Create */ inline __fastcall TInstallOptions(void) : Classes::TPersistent() { }
#pragma option pop
};
class DELPHICLASS TIBSetup;
class PASCALIMPLEMENTATION TIBSetup : public Classes::TComponent
{
typedef Classes::TComponent inherited;
private:
bool FIBInstallLoaded;
bool FRebootToComplete;
int FProgress;
AnsiString FMsgFilePath;
TIBSetupOnStatus FOnStatusChange;
void *FStatusContext;
TIBSetupOnError FOnError;
void *FErrorContext;
TIBSetupOnWarning FOnWarning;
void __fastcall SetMsgFilePath(const AnsiString Value);
protected:
int __fastcall StatusInternal(int Status, const char * ActionDescription);
int __fastcall ErrorInternal(int IscCode, const char * ActionDescription);
void __fastcall Call(int IscCode);
void __fastcall IBInstallError(int IscCode);
AnsiString __fastcall GetInstallMessage(int IscCode);
public:
__fastcall virtual TIBSetup(Classes::TComponent* AOwner);
__property bool RebootToComplete = {read=FRebootToComplete, nodefault};
__property int Progress = {read=FProgress, nodefault};
__property void * StatusContext = {read=FStatusContext, write=FStatusContext};
__property void * ErrorContext = {read=FErrorContext, write=FErrorContext};
__property AnsiString MsgFilePath = {read=FMsgFilePath, write=SetMsgFilePath};
__published:
__property TIBSetupOnWarning OnWarning = {read=FOnWarning, write=FOnWarning};
__property TIBSetupOnError OnError = {read=FOnError, write=FOnError};
__property TIBSetupOnStatus OnStatusChange = {read=FOnStatusChange, write=FOnStatusChange};
public:
#pragma option push -w-inl
/* TComponent.Destroy */ inline __fastcall virtual ~TIBSetup(void) { }
#pragma option pop
};
class DELPHICLASS TIBInstall;
class PASCALIMPLEMENTATION TIBInstall : public TIBSetup
{
typedef TIBSetup inherited;
private:
AnsiString FUnInstallFile;
AnsiString FSourceDir;
AnsiString FDestinationDir;
AnsiString FSuggestedDestination;
TInstallOptions* FInstallOptions;
void __fastcall GetOptionProperty(int InfoType, TExamplesOption Option, void * Buffer, unsigned BufferLen)/* overload */;
void __fastcall GetOptionProperty(int InfoType, TMainOption Option, void * Buffer, unsigned BufferLen)/* overload */;
void __fastcall GetOptionProperty(int InfoType, TConnectivityOption Option, void * Buffer, unsigned BufferLen)/* overload */;
void __fastcall GetOptionProperty(int InfoType, TCmdOption Option, void * Buffer, unsigned BufferLen)/* overload */;
void __fastcall InternalSetOptions(Ibinstallheader::POPTIONS_HANDLE pHandle);
void __fastcall SetDestination(const AnsiString Value);
void __fastcall SetSource(const AnsiString Value);
void __fastcall SetInstallOptions(const TInstallOptions* Value);
void __fastcall SuggestDestination(void);
public:
__fastcall virtual TIBInstall(Classes::TComponent* AOwner);
__fastcall virtual ~TIBInstall(void);
void __fastcall InstallCheck(void);
void __fastcall InstallExecute(void);
AnsiString __fastcall GetOptionDescription(TExamplesOption Option)/* overload */;
AnsiString __fastcall GetOptionDescription(TMainOption Option)/* overload */;
AnsiString __fastcall GetOptionDescription(TConnectivityOption Option)/* overload */;
AnsiString __fastcall GetOptionDescription(TCmdOption Option)/* overload */;
AnsiString __fastcall GetOptionName(TExamplesOption Option)/* overload */;
AnsiString __fastcall GetOptionName(TMainOption Option)/* overload */;
AnsiString __fastcall GetOptionName(TConnectivityOption Option)/* overload */;
AnsiString __fastcall GetOptionName(TCmdOption Option)/* overload */;
unsigned __fastcall GetOptionSpaceRequired(TExamplesOption Option)/* overload */;
unsigned __fastcall GetOptionSpaceRequired(TMainOption Option)/* overload */;
unsigned __fastcall GetOptionSpaceRequired(TConnectivityOption Option)/* overload */;
unsigned __fastcall GetOptionSpaceRequired(TCmdOption Option)/* overload */;
__property AnsiString UnInstallFile = {read=FUnInstallFile};
__property AnsiString SuggestedDestination = {read=FSuggestedDestination};
__published:
__property AnsiString SourceDirectory = {read=FSourceDir, write=SetSource};
__property AnsiString DestinationDirectory = {read=FDestinationDir, write=SetDestination};
__property TInstallOptions* InstallOptions = {read=FInstallOptions, write=SetInstallOptions};
};
class DELPHICLASS TIBUnInstall;
class PASCALIMPLEMENTATION TIBUnInstall : public TIBSetup
{
typedef TIBSetup inherited;
private:
AnsiString FUnInstallFile;
public:
void __fastcall UnInstallCheck(void);
void __fastcall UnInstallExecute(void);
__property AnsiString UnInstallFile = {read=FUnInstallFile, write=FUnInstallFile};
public:
#pragma option push -w-inl
/* TIBSetup.Create */ inline __fastcall virtual TIBUnInstall(Classes::TComponent* AOwner) : TIBSetup(AOwner) { }
#pragma option pop
public:
#pragma option push -w-inl
/* TComponent.Destroy */ inline __fastcall virtual ~TIBUnInstall(void) { }
#pragma option pop
};
//-- var, const, procedure ---------------------------------------------------
} /* namespace Ibinstall */
using namespace Ibinstall;
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // IBInstall
| 42.735376 | 253 | 0.752118 | earthsiege2 |
76ad7c947d4264f5fa2762a3d199e6addfc13541 | 5,471 | cpp | C++ | test/fibex/out.cpp | cepsdev/sm4ceps | e333a133ac3b3aff066a63046f0f8f7b339110e1 | [
"Apache-2.0"
] | 7 | 2021-02-25T19:06:27.000Z | 2022-01-18T03:46:27.000Z | test/fibex/out.cpp | cepsdev/sm4ceps | e333a133ac3b3aff066a63046f0f8f7b339110e1 | [
"Apache-2.0"
] | 10 | 2021-04-18T22:29:48.000Z | 2022-01-26T11:07:13.000Z | test/fibex/out.cpp | cepsdev/sm4ceps | e333a133ac3b3aff066a63046f0f8f7b339110e1 | [
"Apache-2.0"
] | 1 | 2021-09-16T14:21:14.000Z | 2021-09-16T14:21:14.000Z | /* out.cpp
CREATED Fri Mar 17 05:02:44 2017
GENERATED BY THE sm4ceps C++ GENERATOR VERSION 0.90.
BASED ON cepS (c) 2017 Tomas Prerovsky <[email protected]> VERSION 1.1 (Mar 10 2017) BUILT WITH GCC 5.2.1 20151010 on GNU/LINUX 64BIT (C) BY THE AUTHORS OF ceps (ceps is hosted at github: https://github.com/cepsdev/ceps.git)
Input files:
prelude.ceps
can3.xml
THIS IS A GENERATED FILE.
*** DO NOT MODIFY. ***
*/
#include "out.hpp"
#include<cmath>
using namespace std;
std::ostream& systemstates::operator << (std::ostream& o, systemstates::State<int> & v){
o << v.value();
return o;
}
std::ostream& systemstates::operator << (std::ostream& o, systemstates::State<double> & v){
o << v.value();
return o;
}
systemstates::State<int>& systemstates::set_value(systemstates::State<int>& lhs, Variant const & rhs){
if (rhs.what_ == sm4ceps_plugin_int::Variant::Double) {
int v = rhs.dv_;
lhs.set_changed(lhs.value() != v); lhs.value() = v;
} else if (rhs.what_ == sm4ceps_plugin_int::Variant::Int) {
lhs.set_changed(lhs.value() != rhs.iv_); lhs.value() = rhs.iv_;
}
return lhs;
}
systemstates::State<int>& systemstates::set_value(systemstates::State<int>& lhs, int rhs){lhs.set_changed(lhs.value() != rhs);lhs.value() = rhs; return lhs;}
systemstates::State<double>& systemstates::set_value(systemstates::State<double>& lhs, double rhs){lhs.set_changed(lhs.value() != rhs);lhs.value() = rhs; return lhs;}
systemstates::State<double>& systemstates::set_value(systemstates::State<double>& lhs, Variant const & rhs){
if (rhs.what_ == sm4ceps_plugin_int::Variant::Int) {
lhs.set_changed(lhs.value() != rhs.iv_); lhs.value() = rhs.iv_;}
else if (rhs.what_ == sm4ceps_plugin_int::Variant::Double){
lhs.set_changed(lhs.value() != rhs.dv_); lhs.value() = rhs.dv_;}
return lhs;
}
systemstates::State<std::string>& systemstates::set_value(systemstates::State<std::string>& lhs, std::string rhs){lhs.set_changed(lhs.value() != rhs);lhs.value() = rhs; return lhs;}
void init_frame_ctxts();
void user_defined_init(){
set_value(systemstates::rpm , 0);
set_value(systemstates::rpm_speed_src , 0);
set_value(systemstates::speed , 0);
init_frame_ctxts();
}
systemstates::State<double> systemstates::rpm;
systemstates::State<double> systemstates::rpm_speed_src;
systemstates::State<double> systemstates::speed;
void init_frame_ctxts(){
systemstates::Engine_RPM_in_ctxt.init();
}
//Frame Context Definitions
void systemstates::Engine_RPM_in_ctxt_t::update_sysstates(){
systemstates::rpm = rpm_;
systemstates::rpm_speed_src = rpm_speed_src_;
systemstates::speed = speed_;
}
void systemstates::Engine_RPM_in_ctxt_t::read_chunk(void* chunk,size_t){
raw_frm_dcls::Engine_RPM_in& in = *((raw_frm_dcls::Engine_RPM_in*)chunk);
rpm_ = in.pos_1;
speed_ = in.pos_2;
rpm_speed_src_ = in.pos_3;
}
bool systemstates::Engine_RPM_in_ctxt_t::match_chunk(void* chunk,size_t chunk_size){
if(chunk_size != 4) return false;
raw_frm_dcls::Engine_RPM_in& in = *((raw_frm_dcls::Engine_RPM_in*)chunk);
return true;
}
void systemstates::Engine_RPM_in_ctxt_t::init(){
rpm_ = systemstates::rpm;
rpm_speed_src_ = systemstates::rpm_speed_src;
speed_ = systemstates::speed;
}
sm4ceps_plugin_int::Framecontext* systemstates::Engine_RPM_in_ctxt_t::clone(){
return new Engine_RPM_in_ctxt_t(*this);
}
systemstates::Engine_RPM_in_ctxt_t::~Engine_RPM_in_ctxt_t (){
}
systemstates::Engine_RPM_in_ctxt_t systemstates::Engine_RPM_in_ctxt;
extern "C" void init_plugin(IUserdefined_function_registry* smc){
smcore_interface = smc->get_plugin_interface();
smc->register_global_init(user_defined_init);
}
std::ostream& operator << (std::ostream& o, systemstates::Variant const & v)
{
if (v.what_ == systemstates::Variant::Int)
o << v.iv_;
else if (v.what_ == systemstates::Variant::Double)
o << std::to_string(v.dv_);
else if (v.what_ == systemstates::Variant::String)
o << v.sv_;
else
o << "(Undefined)";
return o;
}
size_t globfuncs::argc(){
return smcore_interface->argc();
}sm4ceps_plugin_int::Variant globfuncs::argv(size_t j){
return smcore_interface->argv(j);
}
void globfuncs::start_timer(double t,sm4ceps_plugin_int::ev ev_){ smcore_interface->start_timer(t,ev_); }
void globfuncs::start_timer(double t,sm4ceps_plugin_int::ev ev_,sm4ceps_plugin_int::id id_){smcore_interface->start_timer(t,ev_,id_);}
void globfuncs::start_periodic_timer(double t ,sm4ceps_plugin_int::ev ev_){smcore_interface->start_periodic_timer(t,ev_);}
void globfuncs::start_periodic_timer(double t,sm4ceps_plugin_int::ev ev_,sm4ceps_plugin_int::id id_){smcore_interface->start_periodic_timer(t,ev_,id_);}
void globfuncs::start_periodic_timer(double t,sm4ceps_plugin_int::Variant (*fp)(),sm4ceps_plugin_int::id id_){smcore_interface->start_periodic_timer(t,fp,id_);}
void globfuncs::start_periodic_timer(double t,sm4ceps_plugin_int::Variant (*fp)()){smcore_interface->start_periodic_timer(t,fp);}
void globfuncs::stop_timer(sm4ceps_plugin_int::id id_){smcore_interface->stop_timer(id_);}
bool globfuncs::in_state(std::initializer_list<sm4ceps_plugin_int::id> state_ids){return smcore_interface->in_state(state_ids);}
raw_frm_dcls::Engine_RPM_out create_frame_Engine_RPM(){
raw_frm_dcls::Engine_RPM_out out = {0};
out.pos_1 = systemstates::rpm.value();
out.pos_2 = systemstates::speed.value();
out.pos_3 = systemstates::rpm_speed_src.value();
return out;
} | 36.473333 | 236 | 0.735149 | cepsdev |
76add05f31a823cb55f1e87e4914d8e3d2b4f9c1 | 2,299 | cpp | C++ | src/join.cpp | robhz786/strf-benchmarks | e783700317ef1fea0d9e7217c8c42884c3c0371e | [
"BSL-1.0"
] | 1 | 2021-07-19T11:07:24.000Z | 2021-07-19T11:07:24.000Z | src/join.cpp | robhz786/strf-benchmarks | e783700317ef1fea0d9e7217c8c42884c3c0371e | [
"BSL-1.0"
] | null | null | null | src/join.cpp | robhz786/strf-benchmarks | e783700317ef1fea0d9e7217c8c42884c3c0371e | [
"BSL-1.0"
] | null | null | null | // Distributed under the Boost Software License, Version 1.0.
// ( See accompanying file LICENSE or copy at
// http://www.boost.org/LICENSE_1_0.txt )
#include <benchmark/benchmark.h>
#include <strf/to_cfile.hpp>
#define CREATE_BENCHMARK(PREFIX) \
static void PREFIX (benchmark::State& state) { \
char dest[100]; \
for(auto _ : state) { \
(void) PREFIX ## _OP ; \
benchmark::DoNotOptimize(dest); \
benchmark::ClobberMemory(); \
} \
}
#define REGISTER_BENCHMARK(X) benchmark::RegisterBenchmark(STR(X ## _OP), X);
#define STR2(X) #X
#define STR(X) STR2(X)
#define BM_JOIN_4_OP strf::to(dest) (strf::join('a', 'b', 'c', 'd'))
#define BM_4_OP strf::to(dest) ('a', 'b', 'c', 'd')
#define BM_JOIN_8_OP strf::to(dest) (strf::join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'))
#define BM_8_OP strf::to(dest) ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
#define BM_JR_8_OP strf::to(dest) (strf::join_right(15)('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'))
#define BM_JR_STR_OP strf::to(dest) (strf::join_right(15)("Hello World"))
#define BM_JR2_STR_OP strf::to(dest) (strf::join("Hello World") > 15)
#define BM_STR_OP strf::to(dest) (strf::fmt("Hello World") > 15)
#define BM_JRI_OP strf::to(dest) (strf::join_right(4)(25))
#define BM_RI_OP strf::to(dest) (strf::dec(25) > 4)
CREATE_BENCHMARK(BM_JOIN_4);
CREATE_BENCHMARK(BM_4);
CREATE_BENCHMARK(BM_JOIN_8);
CREATE_BENCHMARK(BM_8);
CREATE_BENCHMARK(BM_JR_8);
CREATE_BENCHMARK(BM_JR_STR);
CREATE_BENCHMARK(BM_JR2_STR);
CREATE_BENCHMARK(BM_STR);
CREATE_BENCHMARK(BM_JRI);
CREATE_BENCHMARK(BM_RI);
int main(int argc, char** argv)
{
REGISTER_BENCHMARK(BM_JOIN_4);
REGISTER_BENCHMARK(BM_4);
REGISTER_BENCHMARK(BM_JOIN_8);
REGISTER_BENCHMARK(BM_8);
REGISTER_BENCHMARK(BM_JR_8);
REGISTER_BENCHMARK(BM_JR_STR);
REGISTER_BENCHMARK(BM_JR2_STR);
REGISTER_BENCHMARK(BM_STR);
REGISTER_BENCHMARK(BM_JRI);
REGISTER_BENCHMARK(BM_RI);
benchmark::Initialize(&argc, argv);
benchmark::RunSpecifiedBenchmarks();
return 0;
}
| 35.921875 | 100 | 0.597216 | robhz786 |
76b1757a87800c7b549d40adfcab3a6320719bd1 | 7,292 | cpp | C++ | 2004/samples/graphics/traits_dg/traits.cpp | kevinzhwl/ObjectARXMod | ef4c87db803a451c16213a7197470a3e9b40b1c6 | [
"MIT"
] | 1 | 2021-06-25T02:58:47.000Z | 2021-06-25T02:58:47.000Z | 2004/samples/graphics/traits_dg/traits.cpp | kevinzhwl/ObjectARXMod | ef4c87db803a451c16213a7197470a3e9b40b1c6 | [
"MIT"
] | null | null | null | 2004/samples/graphics/traits_dg/traits.cpp | kevinzhwl/ObjectARXMod | ef4c87db803a451c16213a7197470a3e9b40b1c6 | [
"MIT"
] | 3 | 2020-05-23T02:47:44.000Z | 2020-10-27T01:26:53.000Z | // (C) Copyright 1996,1998 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
// traits.cpp
//
// This sample demonstrates using many of the AcGiSubEntityTraits
// class functions for controlling the properties of the graphics
// primitives drawn during entity elaboration.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "aced.h"
#include "dbsymtb.h"
#include "dbapserv.h"
#include "acgi.h"
// function prototypes
//
// THE FOLLOWING CODE APPEARS IN THE SDK DOCUMENT.
static Acad::ErrorStatus
getLinetypeIdFromString(const char* str, AcDbObjectId& id);
static Acad::ErrorStatus
getLayerIdFromString(const char* str, AcDbObjectId& id);
// END CODE APPEARING IN SDK DOCUMENT.
// Helpful constants for setting attributes:
// COLOR
//
static const Adesk::UInt16 kColorByBlock = 0;
static const Adesk::UInt16 kRed = 1;
static const Adesk::UInt16 kYellow = 2;
static const Adesk::UInt16 kGreen = 3;
static const Adesk::UInt16 kCyan = 4;
static const Adesk::UInt16 kBlue = 5;
static const Adesk::UInt16 kMagenta = 6;
static const Adesk::UInt16 kWhite = 7;
static const Adesk::UInt16 kColorByLayer = 256;
class AsdkTraitsSamp: public AcDbEntity
{
public:
ACRX_DECLARE_MEMBERS(AsdkTraitsSamp);
virtual Adesk::Boolean worldDraw(AcGiWorldDraw *);
Acad::ErrorStatus transformBy(const AcGeMatrix3d &);
};
ACRX_DXF_DEFINE_MEMBERS(AsdkTraitsSamp,AcDbEntity,
AcDb::kDHL_CURRENT, AcDb::kMReleaseCurrent, 0,\
ASDKTRAITSSAMP,AsdkTraits Sample);
Acad::ErrorStatus AsdkTraitsSamp::transformBy(
const AcGeMatrix3d &xfm)
{
return Acad::eOk;
}
// THE FOLLOWING CODE APPEARS IN THE SDK DOCUMENT.
Adesk::Boolean
AsdkTraitsSamp::worldDraw(AcGiWorldDraw* pW)
{
// At this point, the current property traits are
// the entity's property traits. If the current
// property traits are changed and you want to
// reapply the entity's property traits, this is
// the place to save them.
//
Adesk::UInt16 entity_color
= pW->subEntityTraits().color();
AcDbObjectId entity_linetype
= pW->subEntityTraits().lineTypeId();
AcDbObjectId entity_layer
= pW->subEntityTraits().layerId();
// Override the current color and make it blue.
//
pW->subEntityTraits().setColor(kBlue);
// Draw a blue 3-point polyline.
//
int num_pts = 3;
AcGePoint3d *pVerts = new AcGePoint3d[num_pts];
pVerts[0] = AcGePoint3d(0.0, 0.0, 0);
pVerts[1] = AcGePoint3d(1.0, 0.0, 0);
pVerts[2] = AcGePoint3d(1.0, 1.0, 0);
pW->geometry().polyline(num_pts, pVerts);
// Force the current color to use current layer's color.
//
pW->subEntityTraits().setColor(kColorByLayer);
// Force current line type to "DASHDOT". If
// "DASHDOT" is not loaded, the current line
// type will still be in effect.
//
AcDbObjectId dashdotId;
if (getLinetypeIdFromString("DASHDOT", dashdotId)
== Acad::eOk)
{
pW->subEntityTraits().setLineType(dashdotId);
}
// Force current layer to "MY_LAYER". If
// "MY_LAYER" is not loaded, the current layer
// will still be in effect.
//
AcDbObjectId layerId;
if (getLayerIdFromString("MY_LAYER", layerId)
== Acad::eOk)
{
pW->subEntityTraits().setLayer(layerId);
}
// Draw a dashdot'd xline in "MY_LAYER"'s color.
//
pW->geometry().xline(pVerts[0], pVerts[2]);
delete [] pVerts;
return Adesk::kTrue;
}
// A useful function that gets the linetype ID from the
// linetype's name -- must be in upper case.
//
static Acad::ErrorStatus
getLinetypeIdFromString(const char* str, AcDbObjectId& id)
{
Acad::ErrorStatus err;
// Get the table of currently loaded linetypes.
//
AcDbLinetypeTable *pLinetypeTable;
err = acdbHostApplicationServices()->workingDatabase()
->getSymbolTable(pLinetypeTable, AcDb::kForRead);
if (err != Acad::eOk)
return err;
// Get the id of the linetype with the name that
// 'str' contains.
//
err = pLinetypeTable->getAt(str, id, Adesk::kTrue);
pLinetypeTable->close();
return err;
}
// A useful function that gets the layer ID from the
// layer's name -- must be in upper case.
//
static Acad::ErrorStatus
getLayerIdFromString(const char* str, AcDbObjectId& id)
{
Acad::ErrorStatus err;
// Get the table of currently loaded layers.
//
AcDbLayerTable *pLayerTable;
err = acdbHostApplicationServices()->workingDatabase()
->getSymbolTable(pLayerTable, AcDb::kForRead);
if (err != Acad::eOk)
return err;
// Get the ID of the layer with the name that 'str'
// contains.
//
err = pLayerTable->getAt(str, id, Adesk::kTrue);
pLayerTable->close();
return err;
}
// END CODE APPEARING IN SDK DOCUMENT.
void
addAsdkTraitsSampObject()
{
AsdkTraitsSamp *pNewObj = new AsdkTraitsSamp;
AcDbBlockTable *pBlockTable;
acdbHostApplicationServices()->workingDatabase()
->getSymbolTable(pBlockTable, AcDb::kForRead);
AcDbBlockTableRecord *pBlock;
pBlockTable->getAt(ACDB_MODEL_SPACE, pBlock,
AcDb::kForWrite);
AcDbObjectId objId;
pBlock->appendAcDbEntity(objId, pNewObj);
pBlockTable->close();
pBlock->close();
pNewObj->close();
}
static void initAsdkTraitsSamp()
{
AsdkTraitsSamp::rxInit();
acrxBuildClassHierarchy();
acedRegCmds->addCommand("ASDK_TRAITS_SAMP",
"ASDKTRAITSSAMP",
"TRAITSSAMP",
ACRX_CMD_TRANSPARENT,
addAsdkTraitsSampObject);
}
extern "C" AcRx::AppRetCode
acrxEntryPoint(AcRx::AppMsgCode msg, void* appId)
{
switch(msg) {
case AcRx::kInitAppMsg:
acrxDynamicLinker->unlockApplication(appId);
acrxDynamicLinker->registerAppMDIAware(appId);
initAsdkTraitsSamp();
break;
case AcRx::kUnloadAppMsg:
acedRegCmds->removeGroup("ASDK_TRAITS_SAMP");
deleteAcRxClass(AsdkTraitsSamp::desc());
}
return AcRx::kRetOK;
}
| 28.936508 | 73 | 0.652907 | kevinzhwl |
76b17f81649a6999c1a3fce0974c4946ee13a356 | 3,264 | cpp | C++ | src/StartUpDialog.cpp | Nodens-LOTGA/CircuitTester | 23438f49651f537c43cd78f64e61c2a5024ec8c8 | [
"MIT"
] | null | null | null | src/StartUpDialog.cpp | Nodens-LOTGA/CircuitTester | 23438f49651f537c43cd78f64e61c2a5024ec8c8 | [
"MIT"
] | null | null | null | src/StartUpDialog.cpp | Nodens-LOTGA/CircuitTester | 23438f49651f537c43cd78f64e61c2a5024ec8c8 | [
"MIT"
] | null | null | null | #include "startupdialog.h"
#include "./ui_startupdialog.h"
#include "Settings.h"
#include "tools.h"
#include <QCryptographicHash>
#include <QMessageBox>
#include <QRegExpValidator>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QSettings>
#include <QStyledItemDelegate>
StartUpDialog::StartUpDialog(QWidget *parent)
: QDialog(parent), ui(new Ui::StartUpDialog) {
ui->setupUi(this);
connect(ui->enterPB, SIGNAL(clicked()), this, SLOT(tryAccept()));
ui->pwLE->setValidator(new QRegExpValidator(QRegExp(".{8,32}"), this));
ui->nameLE->setValidator(
new QRegExpValidator(QRegExp(tr("[\\w\\s]+")), this));
// QSettings set;
// set.clear();
// ui->portCB->setItemDelegate(new QStyledItemDelegate());
// ui->userCB->setItemDelegate(new QStyledItemDelegate());
Settings sett;
ui->newUserChkB->setEnabled(sett.newUsers);
updateNames();
updatePorts();
}
StartUpDialog::~StartUpDialog() { delete ui; }
void StartUpDialog::updateNames() {
Settings sett;
int lastUserIndex{};
ui->userCB->clear();
QMap<QString, QVariant>::const_iterator i = sett.users.constBegin();
while (i != sett.users.constEnd()) {
ui->userCB->addItem(i.key(), i.value());
if (i.key() == sett.userName)
lastUserIndex = ui->userCB->count() - 1;
i++;
}
ui->userCB->setCurrentIndex(lastUserIndex);
}
void StartUpDialog::updatePorts() {
auto ports = QSerialPortInfo::availablePorts();
for (auto &i : ports)
ui->portCB->addItem(i.portName());
}
void StartUpDialog::tryAccept() {
Settings sett;
QString pw = ui->pwLE->text();
if (pw.length() < 8) {
QMessageBox::warning(
this, RU("Неверный пароль"),
RU("Пароль должен состоять не менее чем из 8 символов"));
return;
}
if (ui->newUserChkB->isChecked()) {
QString newUserName = ui->nameLE->text().simplified();
if (newUserName.isEmpty()) {
QMessageBox::warning(this, RU("Неверный пользователь"),
RU("Имя пользователя не должно быть пустым"));
return;
}
if (sett.users.contains(newUserName)) {
QMessageBox::warning(this, RU("Неверный пользователь"),
RU("Пользователь с таким именем уже существует"));
return;
}
sett.users[newUserName] = pw;
sett.userName = newUserName;
sett.isAdmin = false;
sett.save();
updateNames();
} else {
if (ui->userCB->currentText() == "") {
QMessageBox::warning(this, RU("Неверный пользователь"),
RU("Пожалуйста, выберите пользователя"));
return;
}
QString userName = ui->userCB->currentText();
if (sett.users.contains(userName)) {
if (sett.users[userName] != pw) {
QMessageBox::warning(this, RU("Неверный пароль"),
RU("Пароль не совпадает"));
return;
} else {
sett.userName = userName;
}
}
if (userName == sett.adminName)
sett.isAdmin = true;
else
sett.isAdmin = false;
}
// TODO:
if (ui->portCB->currentText() == "") {
QMessageBox::warning(this, RU("Неверный порт"),
RU("Пожалуйста, выберетие порт"));
return;
} else
sett.portName = ui->portCB->currentText();
sett.save();
accept();
} | 28.631579 | 77 | 0.620098 | Nodens-LOTGA |
76bc8541fdab340404c8957ff292fec175c6d853 | 163 | cpp | C++ | src/common.cpp | sdadia/deep-learning-and-optimization | b44be79de116e2d4b203452a161641519f18f580 | [
"MIT"
] | 1 | 2018-10-02T15:29:14.000Z | 2018-10-02T15:29:14.000Z | src/common.cpp | sdadia/deep-learning-and-optimization | b44be79de116e2d4b203452a161641519f18f580 | [
"MIT"
] | null | null | null | src/common.cpp | sdadia/deep-learning-and-optimization | b44be79de116e2d4b203452a161641519f18f580 | [
"MIT"
] | null | null | null |
#include "common.hpp"
#include <xtensor/xarray.hpp>
#include <xtensor/xio.hpp>
#include <xtensor/xtensor.hpp>
#include <glog/logging.h> // for check macro
| 20.375 | 50 | 0.705521 | sdadia |
76bf34c486ee92c78bf855f06a705c386d700b6e | 202 | cpp | C++ | application/src/main.cpp | EgorSidorov/EasySiteCreator | 100203b49386d6905a6e9456c9f2b7644f7f6ff0 | [
"Apache-2.0"
] | 1 | 2019-01-23T18:34:33.000Z | 2019-01-23T18:34:33.000Z | application/src/main.cpp | EgorSidorov/EasySiteCreator | 100203b49386d6905a6e9456c9f2b7644f7f6ff0 | [
"Apache-2.0"
] | null | null | null | application/src/main.cpp | EgorSidorov/EasySiteCreator | 100203b49386d6905a6e9456c9f2b7644f7f6ff0 | [
"Apache-2.0"
] | null | null | null | #include <QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication *app=new QApplication(argc,argv);
MainWindow window(app);
window.show();
app->exec();
}
| 16.833333 | 50 | 0.658416 | EgorSidorov |
76c93f51cbe86587f1467e4b4da18f7e80e39978 | 1,633 | hpp | C++ | AVLWordTree.hpp | SinaRaoufi/AVLWordTree | 87e18951175b9cf93fa9d2323e8df52de2e3c2ab | [
"MIT"
] | null | null | null | AVLWordTree.hpp | SinaRaoufi/AVLWordTree | 87e18951175b9cf93fa9d2323e8df52de2e3c2ab | [
"MIT"
] | null | null | null | AVLWordTree.hpp | SinaRaoufi/AVLWordTree | 87e18951175b9cf93fa9d2323e8df52de2e3c2ab | [
"MIT"
] | null | null | null | #ifndef AVL_WORD_TREE_IG
#define AVL_WORD_TREE_IG
#include <string>
#include <vector>
class AVLNode
{
public:
explicit AVLNode(const std::string &);
void setValue(const std::string &);
std::string getValue() const;
void setHeight(int);
int getHeight() const;
void setRightChild(AVLNode *);
void setLeftChild(AVLNode *);
AVLNode *getRightChild() const;
AVLNode *getLeftChild() const;
private:
std::string value;
int height;
AVLNode *rightChild;
AVLNode *leftChild;
};
class AVLWordTree
{
public:
void insert(std::string);
bool search(const std::string &) const;
void remove(const std::string &);
std::vector<std::string> start_with(const char &) const;
std::vector<std::string> end_with(const char &) const;
std::vector<std::string> contains(const std::string &) const;
void traversePreOrder() const;
void traverseInOrder() const;
void traversePostOrder() const;
void traverseLevelOrder() const;
bool isEmpty() const;
void clear();
~AVLWordTree();
private:
AVLNode *root = nullptr;
AVLNode *insert(AVLNode *, std::string);
AVLNode *remove(AVLNode *, const std::string &);
AVLNode *minNode(AVLNode *);
int compareTwoString(const std::string &, const std::string &) const;
void traversePreOrder(AVLNode *) const;
void traverseInOrder(AVLNode *) const;
void traversePostOrder(AVLNode *) const;
int heightOfAVLNode(AVLNode *) const;
int balanceFactor(AVLNode *) const;
AVLNode *balance(AVLNode *);
AVLNode *rightRotation(AVLNode *);
AVLNode *leftRotation(AVLNode *);
};
#endif | 27.216667 | 73 | 0.679731 | SinaRaoufi |
76caf89b9574be170f7fa9d2acaf3db9a0213ef2 | 10,283 | cpp | C++ | packages/Search/test/tstBoostGeometryAdapters.cpp | dalg24/DataTransferKit | 35c5943d8f2f516b1da5f4004cbd05d476a8744e | [
"BSD-3-Clause"
] | null | null | null | packages/Search/test/tstBoostGeometryAdapters.cpp | dalg24/DataTransferKit | 35c5943d8f2f516b1da5f4004cbd05d476a8744e | [
"BSD-3-Clause"
] | 4 | 2017-03-27T12:17:42.000Z | 2018-12-04T19:44:44.000Z | packages/Search/test/tstBoostGeometryAdapters.cpp | dalg24/DataTransferKit | 35c5943d8f2f516b1da5f4004cbd05d476a8744e | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
* Copyright (c) 2012-2019 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit 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 <DTK_DetailsAlgorithms.hpp>
#include <Teuchos_UnitTestHarness.hpp>
#include "DTK_BoostGeometryAdapters.hpp"
namespace bg = boost::geometry;
namespace dtk = DataTransferKit::Details;
// Conveniently importing Point and Box in DataTransferKit::Details:: namespace
// and declaring type aliases within boost::geometry:: so that we are able to
// just use dtk:: and bg:: to specify what geometry or algorithm we mean.
namespace DataTransferKit
{
namespace Details
{
using DataTransferKit::Box;
using DataTransferKit::Point;
} // namespace Details
} // namespace DataTransferKit
namespace boost
{
namespace geometry
{
using Point = model::point<double, 3, cs::cartesian>;
using Box = model::box<Point>;
} // namespace geometry
} // namespace boost
TEUCHOS_UNIT_TEST( BoostGeometryAdapters, equals )
{
dtk::Point point = {{1., 2., 3.}};
TEST_ASSERT( dtk::equals( point, {{1., 2., 3.}} ) );
TEST_ASSERT( !dtk::equals( point, {{0., 0., 0.}} ) );
TEST_ASSERT( bg::equals( point, bg::make<dtk::Point>( 1., 2., 3. ) ) );
TEST_ASSERT( !bg::equals( point, bg::make<dtk::Point>( 4., 5., 6. ) ) );
TEST_ASSERT( bg::equals( point, bg::make<bg::Point>( 1., 2., 3. ) ) );
TEST_ASSERT( !bg::equals( point, bg::make<bg::Point>( 0., 0., 0. ) ) );
dtk::Box box = {{{1., 2., 3.}}, {{4., 5., 6.}}};
TEST_ASSERT( dtk::equals( box, {{{1., 2., 3.}}, {{4., 5., 6.}}} ) );
TEST_ASSERT( !dtk::equals( box, {{{0., 0., 0.}}, {{1., 1., 1.}}} ) );
TEST_ASSERT( bg::equals( box, dtk::Box{{{1., 2., 3.}}, {{4., 5., 6.}}} ) );
TEST_ASSERT( !bg::equals( box, dtk::Box{{{0., 0., 0.}}, {{1., 1., 1.}}} ) );
TEST_ASSERT(
bg::equals( box, bg::Box( bg::make<bg::Point>( 1., 2., 3. ),
bg::make<bg::Point>( 4., 5., 6. ) ) ) );
TEST_ASSERT(
!bg::equals( box, bg::Box( bg::make<bg::Point>( 0., 0., 0. ),
bg::make<bg::Point>( 1., 1., 1. ) ) ) );
// Now just for fun compare the DTK box to a Boost.Geometry box composed of
// DTK points.
TEST_ASSERT( bg::equals(
box, bg::model::box<dtk::Point>( {{1., 2., 3.}}, {{4., 5., 6.}} ) ) );
TEST_ASSERT( !bg::equals(
box, bg::model::box<dtk::Point>( {{0., 0., 0.}}, {{0., 0., 0.}} ) ) );
}
TEUCHOS_UNIT_TEST( BoostGeometryAdapters, distance )
{
// NOTE unsure if should test for floating point equality here
dtk::Point a = {{0., 0., 0.}};
dtk::Point b = {{0., 1., 0.}};
TEST_EQUALITY( dtk::distance( a, b ), 1. );
TEST_EQUALITY( bg::distance( a, b ), 1. );
std::tie( a, b ) = std::make_pair<dtk::Point, dtk::Point>( {{0., 0., 0.}},
{{1., 1., 1.}} );
TEST_EQUALITY( dtk::distance( a, b ), std::sqrt( 3. ) );
TEST_EQUALITY( bg::distance( a, b ), std::sqrt( 3. ) );
TEST_EQUALITY( dtk::distance( a, a ), 0. );
TEST_EQUALITY( bg::distance( a, a ), 0. );
dtk::Box unit_box = {{{0., 0., 0.}}, {{1., 1., 1.}}};
dtk::Point p = {{.5, .5, .5}};
// NOTE DTK has no overload distance( Box, Point )
TEST_EQUALITY( dtk::distance( p, unit_box ), 0. );
// TEST_EQUALITY( dtk::distance( unit_box, p ), 0. );
TEST_EQUALITY( bg::distance( p, unit_box ), 0. );
TEST_EQUALITY( bg::distance( unit_box, p ), 0. );
p = {{-1., -1., -1.}};
TEST_EQUALITY( dtk::distance( p, unit_box ), std::sqrt( 3. ) );
TEST_EQUALITY( bg::distance( p, unit_box ), std::sqrt( 3. ) );
p = {{-1., .5, -1.}};
TEST_EQUALITY( dtk::distance( p, unit_box ), std::sqrt( 2. ) );
TEST_EQUALITY( bg::distance( p, unit_box ), std::sqrt( 2. ) );
p = {{-1., .5, .5}};
TEST_EQUALITY( dtk::distance( p, unit_box ), 1. );
TEST_EQUALITY( bg::distance( p, unit_box ), 1. );
}
TEUCHOS_UNIT_TEST( BoostGeometryAdapters, expand )
{
using dtk::equals;
dtk::Box box;
// NOTE even though not considered valid, default constructed DTK box can be
// expanded using Boost.Geometry algorithm.
TEST_ASSERT( !bg::is_valid( box ) );
bg::expand( box, dtk::Point{{0., 0., 0.}} );
dtk::expand( box, {{1., 1., 1.}} );
TEST_ASSERT( equals( box, {{{0., 0., 0.}}, {{1., 1., 1.}}} ) );
bg::expand( box, dtk::Box{{{1., 2., 3.}}, {{4., 5., 6.}}} );
dtk::expand( box, {{{-1., -2., -3.}}, {{0., 0., 0.}}} );
TEST_ASSERT( equals( box, {{{-1., -2., -3.}}, {{4., 5., 6.}}} ) );
}
TEUCHOS_UNIT_TEST( BoostGeometryAdapters, centroid )
{
using dtk::equals;
// For convenience define a function that returns the centroid.
// Boost.Geometry defines both `void centroid(Geometry const & geometry,
// Point &c )` and `Point return_centroid(Geometry const& geometry)`
auto const dtkReturnCentroid = []( dtk::Box b ) {
dtk::Point c;
dtk::centroid( b, c );
return c;
};
// Interestingly enough, even though for Boost.Geometry, the DTK default
// constructed "empty" box is not valid, it will still calculate its
// centroid. Admittedly, the result (centroid at origin) is garbage :)
dtk::Box empty_box = {};
TEST_ASSERT( !bg::is_valid( empty_box ) );
TEST_ASSERT( equals( bg::return_centroid<dtk::Point>( empty_box ),
{{0., 0., 0.}} ) );
TEST_ASSERT( equals( dtkReturnCentroid( empty_box ), {{0., 0., 0.}} ) );
dtk::Box unit_box = {{{0., 0., 0.}}, {{1., 1., 1.}}};
TEST_ASSERT(
equals( bg::return_centroid<dtk::Point>( unit_box ), {{.5, .5, .5}} ) );
TEST_ASSERT( equals( dtkReturnCentroid( unit_box ), {{.5, .5, .5}} ) );
// NOTE DTK does not have an overload of centroid() for Point at the
// moment.
dtk::Point a_point = {{1., 2., 3.}};
TEST_ASSERT(
equals( bg::return_centroid<dtk::Point>( a_point ), a_point ) );
// TEST_ASSERT( equals( dtk::centroid(
// []( dtk::Point p ) {
// dtk::Point c;
// dtk::centroid( p, c );
// return c;
// }( a_point ),
// a_point ) ) );
}
TEUCHOS_UNIT_TEST( BoostGeometryAdapters, is_valid )
{
// NOTE "empty" box is considered as valid in DataTransferKit but it is
// not according to Boost.Geometry
dtk::Box empty_box = {};
TEST_ASSERT( dtk::isValid( empty_box ) );
std::string message;
TEST_ASSERT( !bg::is_valid( empty_box, message ) );
TEST_EQUALITY( message, "Box has corners in wrong order" );
// Same issue with infinitesimal box around a point (here the origin)
dtk::Box a_box = {{{0., 0., 0.}}, {{0., 0., 0.}}};
TEST_ASSERT( dtk::isValid( a_box ) );
TEST_ASSERT( !bg::is_valid( a_box, message ) );
TEST_EQUALITY( message, "Geometry has wrong topological dimension" );
dtk::Box unit_box = {{{0., 0., 0.}}, {{1., 1., 1.}}};
TEST_ASSERT( dtk::isValid( unit_box ) );
TEST_ASSERT( bg::is_valid( unit_box ) );
dtk::Box invalid_box = {{{1., 2., 3.}}, {{4., NAN, 6.}}};
TEST_ASSERT( !dtk::isValid( invalid_box ) );
TEST_ASSERT( !bg::is_valid( invalid_box, message ) );
TEST_EQUALITY( message,
"Geometry has point(s) with invalid coordinate(s)" );
dtk::Point a_point = {{1., 2., 3.}};
TEST_ASSERT( dtk::isValid( a_point ) );
TEST_ASSERT( bg::is_valid( a_point ) );
auto const infty = std::numeric_limits<double>::infinity();
dtk::Point invalid_point = {{infty, 1.41, 3.14}};
TEST_ASSERT( !dtk::isValid( invalid_point ) );
TEST_ASSERT( !bg::is_valid( invalid_point, message ) );
TEST_EQUALITY( message,
"Geometry has point(s) with invalid coordinate(s)" );
// Also Boost.Geometry has a is_empty() algorithm but it has a different
// meaning, it checks whether a geometry is an empty set and always returns
// false for a point or a box.
TEST_ASSERT( !bg::is_empty( empty_box ) );
TEST_ASSERT( !bg::is_empty( a_box ) );
TEST_ASSERT( !bg::is_empty( unit_box ) );
}
TEUCHOS_UNIT_TEST( BoostGeometryAdapters, intersects )
{
dtk::Box const unit_box = {{{0., 0., 0.}}, {{1., 1., 1.}}};
// self-intersection
TEST_ASSERT( dtk::intersects( unit_box, unit_box ) );
TEST_ASSERT( bg::intersects( unit_box, unit_box ) );
// share a corner
dtk::Box other_box = {{{1., 1., 1.}}, {{2., 2., 2.}}};
TEST_ASSERT( dtk::intersects( unit_box, other_box ) );
TEST_ASSERT( bg::intersects( unit_box, other_box ) );
// share an edge
other_box = {{{1., 0., 1.}}, {{2., 1., 2.}}};
TEST_ASSERT( dtk::intersects( unit_box, other_box ) );
TEST_ASSERT( bg::intersects( unit_box, other_box ) );
// share a face
other_box = {{{0., -1., 0.}}, {{1., 0., 1.}}};
TEST_ASSERT( dtk::intersects( unit_box, other_box ) );
TEST_ASSERT( bg::intersects( unit_box, other_box ) );
// contains the other box
other_box = {{{.3, .3, .3}}, {{.6, .6, .6}}};
TEST_ASSERT( dtk::intersects( unit_box, other_box ) );
TEST_ASSERT( bg::intersects( unit_box, other_box ) );
// within the other box
other_box = {{{-1., -1., -1.}}, {{2., 2., 2.}}};
TEST_ASSERT( dtk::intersects( unit_box, other_box ) );
TEST_ASSERT( bg::intersects( unit_box, other_box ) );
// overlapping
other_box = {{{.5, .5, .5}}, {{2., 2., 2.}}};
TEST_ASSERT( dtk::intersects( unit_box, other_box ) );
TEST_ASSERT( bg::intersects( unit_box, other_box ) );
// disjoint
other_box = {{{1., 2., 3.}}, {{4., 5., 6.}}};
TEST_ASSERT( !dtk::intersects( unit_box, other_box ) );
TEST_ASSERT( !bg::intersects( unit_box, other_box ) );
}
| 41.297189 | 80 | 0.550715 | dalg24 |
76ccbf5bfac42b9745d142340f704e261e1b6276 | 119 | cpp | C++ | server/instance.cpp | irl-game/irl | ba507a93371ab172b705c1ede8cd062123fc96f5 | [
"MIT"
] | null | null | null | server/instance.cpp | irl-game/irl | ba507a93371ab172b705c1ede8cd062123fc96f5 | [
"MIT"
] | null | null | null | server/instance.cpp | irl-game/irl | ba507a93371ab172b705c1ede8cd062123fc96f5 | [
"MIT"
] | null | null | null | #include "instance.hpp"
Instance::Instance() : SimServer(static_cast<Sched &>(*this), static_cast<World &>(*this)) {}
| 29.75 | 93 | 0.697479 | irl-game |
76ce217b72a19bb05df50f736e02594e4669b538 | 2,493 | cpp | C++ | libs/server/server_base.cpp | caodhuan/CHServer | 823c4a006528a3aa1c88575c499eecda45d9022d | [
"Apache-2.0"
] | 6 | 2017-11-16T06:12:20.000Z | 2021-02-06T06:58:20.000Z | libs/server/server_base.cpp | caodhuan/CHServer | 823c4a006528a3aa1c88575c499eecda45d9022d | [
"Apache-2.0"
] | null | null | null | libs/server/server_base.cpp | caodhuan/CHServer | 823c4a006528a3aa1c88575c499eecda45d9022d | [
"Apache-2.0"
] | null | null | null | #include "server_base.h"
#include "event_dispatcher.h"
#include "session.h"
#include "log.h"
#include "socket_tcp.h"
#include "uv.h"
#include "timer_factory.h"
#include "resource _manager.h"
#include "config.h"
namespace CHServer {
template<>
ServerBase* SingletonInheritable<ServerBase>::m_Instance = 0;
ServerBase::ServerBase()
: m_dispatcher(NULL)
, m_Server(NULL) {
}
ServerBase::~ServerBase() {
}
bool ServerBase::Initilize(const char* path, const char* tableName) {
if (!BeforeInitilize()) {
return false;
}
if (m_dispatcher) {
CHERRORLOG("reinitilzed");
return false;
}
// 初始化脚本的搜索路径之类的
if (!ResourceManager::Instance()->Initialize(path, tableName)) {
CHERRORLOG("resource initialize failed!");
return false;
}
Config* config = ResourceManager::Instance()->GetConfig();
std::string logPath, logFileName;
if (config && config->ReadString("sLogPath", logPath) && config->ReadString("sLogFileName", logFileName)) {
CHLog::Instance()->InitLog(logPath.c_str(), logFileName.c_str());
} else {
CHERRORLOG("log initialize failed!");
return false;
}
m_dispatcher = new EventDispatcher();
TimerFactory::Instance()->InitTimerFactory(m_dispatcher);
m_Server = new SocketTCP(m_dispatcher);
m_Server->SetCallback(nullptr, [&] {
SocketTCP* tcpClient = m_Server->Accept();
Session* session = CreateSession(tcpClient);
CHDEBUGLOG("new client connected %s:%d", tcpClient->GetIP().c_str(), tcpClient->GetPort());
},
[&] {
// 这里目前没搞清楚为啥delete后,会造成this变量变得不可访问。
SocketBase* tmp = m_Server;
m_Server = nullptr;
CHWARNINGLOG("before delete %ld", this);
delete tmp;
CHWARNINGLOG("after delete %ld", this);
});
int32_t internalPort;
std::string internalIP;
if (!config->ReadInt("nInternalPort", internalPort)) {
CHERRORLOG("read internal port failed!");
return false;
}
if (!config->ReadString("sInternalIP", internalIP)) {
CHERRORLOG("read internal ip failed!");
return false;
}
std::vector<std::string> whiteList;
if (!config->ReadVector("sWhiteList", whiteList)) {
CHERRORLOG("read white list failed!");
return false;
}
m_Server->Listen(internalIP.c_str(), internalPort);
return AfterInitilize();
}
void ServerBase::Finalize() {
BeforeFinalize();
if (m_dispatcher) {
delete m_dispatcher;
m_dispatcher = NULL;
}
AfterFinalize();
CHLog::Instance()->UninitLog();
}
void ServerBase::Run() {
m_dispatcher->Run();
}
} | 21.307692 | 109 | 0.680706 | caodhuan |
76d55a9f58257315c5914ab7967a59c03c78b85c | 5,612 | cc | C++ | lesson4/compression.cc | Frzifus/hoema | c5f9ab6760f4a3f044c008b08e62eaab5760fb7b | [
"BSD-2-Clause"
] | null | null | null | lesson4/compression.cc | Frzifus/hoema | c5f9ab6760f4a3f044c008b08e62eaab5760fb7b | [
"BSD-2-Clause"
] | null | null | null | lesson4/compression.cc | Frzifus/hoema | c5f9ab6760f4a3f044c008b08e62eaab5760fb7b | [
"BSD-2-Clause"
] | null | null | null | // BSD 2-Clause License
//
// Copyright (c) 2016, frzifus
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <sys/stat.h>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <vector>
#include "./compression.h"
#define PI 3.1415926536
std::vector<Complex> Compression::transform(const std::vector<Complex> &vec,
std::size_t N, bool back) {
std::vector<Complex> n_vec;
const double AS = back ? 1 : -1;
for (std::size_t n = 0; n < N; n++) {
Complex res;
for (std::size_t k = 0; k < N; k++) {
res += vec.at(k) * Complex((AS * 2 * PI * static_cast<double>(k) *
static_cast<double>(n)) /
static_cast<double>(N));
}
res *= (1 / sqrt(static_cast<double>(N)));
n_vec.push_back(res);
}
return n_vec;
}
void Compression::compressFile(const std::string &src,
const std::string &dest) {
std::vector<Complex> vec = Compression::readFile(src);
std::vector<Complex> n_vec = Compression::transform(vec, vec.size());
Compression::writeFile(dest, n_vec, 0.1);
}
void Compression::decompressFile(const std::string &src,
const std::string &dest) {
std::vector<Complex> n_vec = Compression::readFile(src);
std::vector<Complex> o_vec =
Compression::transform(n_vec, n_vec.size(), DECOMPRESS);
Compression::writeFile(dest, o_vec);
}
std::vector<Complex> Compression::readFile(const std::string &file) {
std::size_t N, idx;
double re, im;
std::vector<Complex> value;
std::ifstream fp;
fp.open(file);
if(!fp) {
std::cout << "File not found." << std::endl;
exit(1);
}
fp >> N;
value.resize(N);
while (!fp.eof()) {
fp >> idx >> re >> im;
value[idx] = Complex(re, im);
}
fp.close();
return value;
}
void Compression::writeFile(const std::string &file,
const std::vector<Complex> &values,
const double &epsilon) {
std::ofstream fp;
fp.open(file);
fp << values.size() << std::endl;
for (std::size_t i{}; i < values.size(); ++i) {
if (values[i].length() > epsilon)
fp << i << "\t" << values[i].Re() << "\t" << values[i].Im() << std::endl;
}
fp.close();
}
long GetFileSize(std::string filename) {
struct stat stat_buf;
int rc = stat(filename.c_str(), &stat_buf);
return rc == 0 ? stat_buf.st_size : -1;
}
double Compression::testCompression(const std::string &src, const double &start,
const double &delta, const double &steps,
const double &tolerance) {
const std::string tmp = src + ".tmp";
std::cout << std::fixed;
double best_epsilon = start;
const long src_length = GetFileSize(src);
std::vector<Complex> origData = Compression::readFile(src);
for (double epsilon = start; epsilon < (start + delta * steps);
epsilon += delta) {
std::vector<Complex> comprData =
Compression::transform(origData, origData.size());
Compression::writeFile(tmp, comprData, epsilon);
comprData = Compression::readFile(tmp);
const long dest_lenght = GetFileSize(tmp);
std::vector<Complex> decomprData =
Compression::transform(comprData, comprData.size(), DECOMPRESS);
Compression::writeFile(tmp, decomprData);
decomprData = Compression::readFile(tmp);
double max_diff = 0;
for (unsigned int i = 0; i < origData.size(); i++) {
double diff = origData[i].Re() - decomprData[i].Re();
// std::cout << diff << std::endl;
// abs()
if (diff < 0) {
diff -= 2 * diff; // * -1 trololol....
}
if (diff > max_diff) max_diff = diff;
}
double compression = 100 - static_cast<double>(dest_lenght) /
static_cast<double>(src_length) * 100;
std::cout << "Max deviation for ε = " << std::setprecision(2) << epsilon
<< ": " << std::setprecision(5) << max_diff
<< "\tCompression Rate: " << std::setprecision(2) << compression
<< "%" << (max_diff < tolerance ? "\t OK" : "\tFAIL")
<< std::endl;
if (max_diff < tolerance) best_epsilon = epsilon;
}
remove(tmp.c_str());
return best_epsilon;
}
| 34.219512 | 80 | 0.619922 | Frzifus |
76d8f508e50a3ea1a907ea0847bd10b4754c935d | 650 | cpp | C++ | src/Utilization.cpp | mansonjones/CppND-System-Monitor | 269f9e189234cf7479f9eb1652af5600554cc017 | [
"MIT"
] | null | null | null | src/Utilization.cpp | mansonjones/CppND-System-Monitor | 269f9e189234cf7479f9eb1652af5600554cc017 | [
"MIT"
] | null | null | null | src/Utilization.cpp | mansonjones/CppND-System-Monitor | 269f9e189234cf7479f9eb1652af5600554cc017 | [
"MIT"
] | null | null | null | #include "Utilization.h"
#include "linux_parser.h"
#include <vector>
#include <thread>
#include <chrono>
long Utilization::Jiffies() const {
return LinuxParser::Jiffies();
}
long Utilization::IdleJiffies() const {
return LinuxParser::IdleJiffies();
}
void Utilization::setCachedActiveJiffies(long activeJiffies) {
cached_active_jiffies_ = activeJiffies;
}
long Utilization::getCachedActiveJiffies() const {
return cached_active_jiffies_;
}
void Utilization::setCachedIdleJiffies(long idleJiffies) {
cached_idle_jiffies_ = idleJiffies;
}
long Utilization::getCachedIdleJiffies() const {
return cached_idle_jiffies_;
}
| 20.967742 | 62 | 0.76 | mansonjones |
76db8866e4ef3b62abd03eb7c6d2101f35333389 | 19,878 | cpp | C++ | src/UserMenu.cpp | gryffyn/USW20_P2 | bfad201375a6388453b5b03633a12b5bba45c141 | [
"MIT"
] | null | null | null | src/UserMenu.cpp | gryffyn/USW20_P2 | bfad201375a6388453b5b03633a12b5bba45c141 | [
"MIT"
] | null | null | null | src/UserMenu.cpp | gryffyn/USW20_P2 | bfad201375a6388453b5b03633a12b5bba45c141 | [
"MIT"
] | null | null | null | //
// Created by gryffyn on 10/03/2020.
//
#include "UserMenu.hpp"
#include <mhash.h>
#include <Admin.hpp>
#include <DataTools.hpp>
#include <Lecturer.hpp>
#include <Student.hpp>
#include <User.hpp>
#include <boost/algorithm/string.hpp>
#include <ios>
#include <iostream>
#include <limits>
#include <mariadb++/connection.hpp>
#include <sstream>
#include "Announcement.hpp"
#include "Key.hpp"
#include "ObjStore.hpp"
namespace Color {
enum Code { // enum of terminal ASCII codes
FG_RED = 31,
FG_GREEN = 32,
FG_BLUE = 34,
FG_DEFAULT = 39,
ST_INVIS = 8,
ST_DEF = 0,
ST_BOLD = 1,
ST_UNDER = 4
};
// sets text style to given code
std::string startval(Code code) {
std::stringstream ss;
ss << "\033[" << code << "m";
return ss.str();
}
// resets text style to normal
std::string endval(Code code) {
std::string str;
if (code < 30) {
str = "\033[0m";
} else {
str = "\033[39m";
}
return str;
}
// sets input to whatever code
std::string setval(Code code, const std::string& input) {
std::stringstream ss;
ss << "\033[" << code << "m" << input << endval(code);
return ss.str();
}
std::string make_box(std::string msg) {
std::stringstream box_u, box_l, box_m, box_complete;
box_u << "┏━";
box_m << "┃ ";
box_l << "┗━";
for (int i = 0; i < msg.length(); i++) {
box_u << "━";
box_l << "━";
}
box_u << "━┓";
box_m << setval(ST_BOLD, msg) << " ┃";
box_l << "━┛";
box_complete << box_u.str() << "\n" << box_m.str() << "\n" << box_l.str() << "\n";
return box_complete.str();
}
} // namespace Color
using namespace Color;
// clears console
void clr() { std::cout << "\033[2J\033[1;1H"; }
// removes all characters that aren't alphanum
std::string sanitize_username(std::string input) {
std::stringstream output;
for (char c : input) {
if (isalnum(c)) {
output << c;
}
}
return output.str();
}
namespace Login {
// checks if user exists and if it does, returns true and the user_id. If not, returns false and -1
std::pair<bool, int> check_user(ObjStore& db, const std::string& username) {
std::pair<bool, int> retval;
retval.first = false;
try {
mariadb::result_set_ref user_result =
db.select("SELECT user_id, user FROM Users WHERE user = '" + username + "';");
user_result->next();
if (username == user_result->get_string(1)) {
retval.first = true;
retval.second = user_result->get_unsigned16(0);
}
} catch (std::out_of_range& e) {
retval.second = -1;
}
return retval;
}
// checks password
bool login(ObjStore& db, const int& user_id, std::string pass) {
bool valid = false;
mariadb::result_set_ref pass_result;
std::stringstream sql;
sql << "SELECT user_id, pwhash FROM Users WHERE user_id = " << user_id << ";";
try {
pass_result = db.select(sql.str());
pass_result->next();
std::string pwhash = pass_result->get_string(1);
valid = Key::verify_key(pwhash, pass);
} catch (std::out_of_range& e) {
}
return valid;
}
// gets name based on user_id
std::string get_name(ObjStore& db, const int& user_id) {
std::stringstream sql;
sql << "SELECT user_id, name FROM Users WHERE user_id = " << user_id << ";";
mariadb::result_set_ref result = db.select(sql.str());
result->next();
return result->get_string(1);
}
std::pair<std::string, int> login_menu(ObjStore& db) {
clr();
std::string username;
int user_id = 0;
bool user_success = false, pass_success = false;
std::string password;
std::cout << make_box("Welcome to the USW Cyber Lab.");
while (!user_success) {
std::cout << setval(ST_BOLD, "Username: ");
std::getline(std::cin, username);
std::string san_uname = sanitize_username(username);
std::pair<bool, int> check = check_user(db, san_uname);
if (!check.first) {
std::cout << std::endl << setval(FG_RED, "🗙") << " Username not found. Please try again.\n";
} else {
user_id = check.second;
user_success = true;
while (!pass_success) {
std::cout << setval(ST_BOLD, "Password: ");
std::getline(std::cin, password);
if (!login(db, user_id, password)) {
std::cout << std::endl;
std::cout << setval(FG_RED, "🗙") << " Password incorrect. Please try again.\n";
} else {
pass_success = true;
std::string name = get_name(db, user_id);
std::cout << "Logging in....." << std::endl;
// sleep(1);
clr();
std::cout << "Welcome, " << name.substr(0, name.find(' ')) << ".";
}
}
}
}
std::pair<std::string, int> final;
final.first = password;
final.second = user_id;
return final;
}
} // namespace Login
namespace UserMenu {
std::string getstring(std::string output) {
std::string str;
std::cout << output;
std::getline(std::cin, str);
return str;
}
// returns if row exists or not
bool exists_row(ObjStore& db, std::string sql) {
mariadb::result_set_ref result = db.select(sql);
if (result->next()) {
return true;
} else { return false; }
}
// checks the user type by looking in what table(s) the user_id exists, returns the types
std::vector<std::string> check_user_type(ObjStore& db, const int& user_id) {
std::vector<std::string> user_types{"Student", "Lecturer", "Admin"}, output;
std::stringstream sql;
for (std::string type : user_types) {
sql << "SELECT * from " << type << "s WHERE user_id = " << user_id << ";";
if (exists_row(db, sql.str())) {
output.emplace_back(type);
}
std::stringstream().swap(sql);
}
return output;
}
std::string set_user_type(const int& choice) {
if (choice == 1) {
return "Student";
} else if (choice == 2) {
return "Lecturer";
} else if (choice == 3) {
return "Admin";
} else {
std::cout << "Invalid choice.";
return "";
}
}
void create_user(ObjStore& db) {
std::cout << make_box("Create User");
std::string username, name, password, typechoice;
std::vector<int> typechoices;
// get user info
bool user_success = false;
while (!user_success) {
username = getstring(setval(ST_BOLD, "Username: "));
std::pair<bool, int> user_exists = Login::check_user(db, username);
if (user_exists.first) {
user_success = true;
} else {
std::cout << "Username has already been chosen. Please choose another username.";
}
}
name = getstring(setval(ST_BOLD, "Name: "));
Key pwhash;
bool pass_success{};
while (!pass_success) {
try {
pwhash.create_key(getstring(setval(ST_BOLD, "Password: ")));
pass_success = true;
} catch (Key::pass_exception& e) {
std::cout << e.what();
}
}
std::cout << setval(ST_BOLD, "User type(s):\n")
<< "1. Student\n"
<< "2. Lecturer\n"
<< "3. Admin\n";
typechoice = getstring("Enter comma separated list of user types: ");
for (char c : typechoice) {
if (isdigit(c)) {
typechoices.emplace_back(c - '0');
}
}
std::cout << "\nCreating user...";
for (int i : typechoices) {
if (i == 1) {
Student student(db, name, username, pwhash.get_key());
} else if (i == 2) {
Lecturer lecturer(db, name, username, pwhash.get_key());
} else if (i == 3) {
Admin admin(db, name, username, pwhash.get_key());
}
}
std::cout << "\nUser created.";
}
void list_users(ObjStore& db) {
std::cout << make_box("User List");
std::cout << setval(ST_UNDER, setval(ST_BOLD, "Username"));
std::cout << " " << setval(ST_BOLD, "-") << " ";
std::cout << setval(ST_UNDER, setval(ST_BOLD, "Name")) << std::endl;
mariadb::result_set_ref result = db.select("SELECT user, name FROM Users;");
while (result->next()) {
std::cout<< result->get_string("user") << " - " << result->get_string("name") << std::endl;
}
}
void delete_user(ObjStore& db) {
std::cout << make_box("Delete User");
std::string username = getstring("Username: ");
std::cout << "\nSelected username: " << username;
std::string confirm = getstring("Are you sure you want to delete this user?\nYou can't undo this action. (y/N)");
if (!confirm.empty()) { boost::algorithm::to_lower(confirm); }
if (confirm[0] == 'n' || confirm.empty()) {
std::cout << setval(ST_BOLD, "NOT") << " deleting user \"" << username << "\".";
} else if (confirm[0] == 'y') {
std::cout << "Deleting user \"" << username << "\"...";
db.execute("DELETE FROM Users WHERE user = '" + username + "';");
std::cout << std::endl << "User \"" << username << "\" deleted.";
}
}
void show_data(ObjStore& db, const int& user_id, const std::string& user_type, std::string password) {
std::stringstream sql;
sql << "SELECT data FROM " << user_type << "s WHERE user_id = " << user_id << ";";
std::string sql_s(sql.str());
mariadb::result_set_ref result = db.select(sql.str());
result->next();
std::cout << make_box("Data");
std::string data = result->get_string(0);
if (data.empty()) {
std::cout << setval(FG_RED, "🗙") << "No data found.";
} else {
std::cout << DataTools::get_data_xor(db, user_id, user_type, std::move(password));
}
}
void edit_data(ObjStore& db, const int& user_id, const std::string& user_type, std::string password) {
std::cout << make_box("Data");
std::stringstream sql;
std::string data;
std::string choice;
int choice_i = 0;
std::cout << setval(ST_BOLD, "1. ") << "Create data\n";
std::cout << setval(ST_BOLD, "2. ") << "Add to data\n";
std::cout << setval(ST_BOLD, "3. ") << "Go back\n";
std::cout << "\nSelect action: ";
// std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
std::getline(std::cin, choice);
choice_i = stoi(choice);
if (choice_i == 1) {
data = getstring("Input data: ");
DataTools::save_data_xor(db, user_id, user_type, data, std::move(password));
} else if (choice_i == 2) {
data = getstring("Data will be added to your existing data.\nInput data: ");
std::getline(std::cin, data);
std::string total_data = DataTools::get_data_xor(db, user_id, user_type, std::move(password)) + data;
sql << "UPDATE " << user_type << "s SET data = '"
<< DataTools::return_data_xor(db, user_id, total_data, std::move(password))
<< "' WHERE user_id = " << user_id << ";";
db.execute(sql.str());
}
}
bool back_or_exit() {
std::cout << "\nGo back (9) or exit (0): ";
char c;
std::cin >> c;
return (c == '9');
}
void show_announcements(ObjStore& db, const int& user_id, std::string user_type) {
std::cout << make_box("Announcements");
std::stringstream sql, sql2;
std::string data;
std::string choice;
int choice_i = 0;
std::cout << setval(ST_BOLD, "1. ") << "Show unread announcements\n";
std::cout << setval(ST_BOLD, "2. ") << "Show announcement by ID\n";
std::cout << setval(ST_BOLD, "3. ") << "Go back\n";
std::cout << "\nSelect action: ";
// std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
std::getline(std::cin, choice);
choice_i = stoi(choice);
if (choice_i == 1) {
clr();
std::cout << make_box("Announcements");
sql << "SELECT last_notif FROM " << user_type << "s WHERE user_id = " << user_id << ";";
mariadb::result_set_ref result = db.select(sql.str());
result->next();
mariadb::date_time last = result->get_date_time(0);
sql2 << "SELECT * FROM Announcements WHERE ann_time >= '" << last << "';";
mariadb::result_set_ref result2 = db.select(sql2.str());
while (result2->next()) {
std::stringstream time, sql3;
sql3 << "SELECT name FROM Users WHERE user_id = " << result2->get_string("ann_author") << ";";
mariadb::result_set_ref result3 = db.select(sql3.str());
result3->next();
time << result2->get_date_time("ann_time");
std::cout << std::endl << setval(ST_BOLD, result2->get_string("ann_title"))
<< std::endl << result3->get_string("name") << std::endl
<< setval(ST_UNDER, time.str()) << std::endl
<< result->get_string("ann_text");
}
std::stringstream newtime;
newtime << "UPDATE " << user_type << "s SET last_notif = '" << mariadb::date_time::now_utc() << "' WHERE user_id = "
<< user_id << ";";
db.insert(newtime.str());
std::cout << std::endl << "\nPress enter to continue...";
std::cin.ignore();
} else if (choice_i == 2) {
std::string ann_number = getstring("Enter announcement number: ");
/* std::stringstream ss;
for (char c : ann_number) {
if (isdigit(c)) {
ss << (c + '0');
}
} */
int ann_id = stoi(ann_number);
// Announcement ann(db);
std::stringstream ss;
ss << "SELECT * FROM Announcements WHERE ann_id = " << ann_id << ";";
try {
mariadb::result_set_ref result = db.select(ss.str());
result->next();
clr();
std::stringstream sql3;
sql3 << "SELECT name FROM Users WHERE user_id = " << result->get_string("ann_author") << ";";
mariadb::result_set_ref result3 = db.select(sql3.str());
result3->next();
std::cout << make_box("Announcement");
std::stringstream time2;
time2 << result->get_date_time("ann_time");
std::cout << std::endl << setval(ST_BOLD, result->get_string("ann_title"))
<< std::endl << result3->get_string("name") << std::endl
<< setval(ST_UNDER, time2.str()) << std::endl
<< result->get_string("ann_text");
std::cout << std::endl << "\nPress enter to continue...";
std::cin.ignore();
} catch (std::out_of_range& e) {
std::cout << std::endl << "No announcement found with that number.";
std::cout << std::endl << "Press enter to continue...";
std::cin.ignore();
}
}
}
void create_announcement(ObjStore& db, const int& user_id) {
make_box("Create Announcement");
std::string title,text;
title = getstring("Title: ");
text = getstring("Text: ");
Announcement ann(db, user_id, title, text);
std::cout << std::endl << "Announcement created.\nPress enter to continue...";
std::cin.ignore();
}
bool menu_admin(ObjStore& db, int& count, const int& user_id, std::string user_type) {
std::string choice;
int choice_i = 0;
std::cout << setval(ST_BOLD, "1. ") << "List Users\n";
std::cout << setval(ST_BOLD, "2. ") << "Create User\n";
std::cout << setval(ST_BOLD, "3. ") << "Delete User\n";
std::cout << setval(ST_BOLD, "4. ") << "Show announcements\n";
std::cout << setval(ST_BOLD, "5. ") << "Create announcement\n";
std::cout << setval(ST_BOLD, "6. ") << "Exit\n";
std::cout << "\nSelect action: ";
if (count != 0) { std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); }
std::getline(std::cin, choice);
choice_i = stoi(choice);
if (choice_i == 1) {
clr();
list_users(db);
if (!back_or_exit()) { return true; } else { clr(); return false; } // exits, or clears the screen and shows menu again
} else if (choice_i == 2) {
clr();
create_user(db);
if (!back_or_exit()) { return true; } else { clr(); return false; }
} else if (choice_i == 3) {
clr();
delete_user(db);
if (!back_or_exit()) { return true; } else { clr(); return false; }
} else if (choice_i == 4) {
clr();
show_announcements(db, user_id, user_type);
clr();
return false;
} else if (choice_i == 5) {
clr();
create_announcement(db, user_id);
clr();
return false;
}
else { return true; }
}
bool menu_student(ObjStore& db, int& count, const int& user_id, const std::string& student, std::string password) {
std::string choice;
int choice_i = 0;
std::cout << setval(ST_BOLD, "1. ") << "Show data\n";
std::cout << setval(ST_BOLD, "2. ") << "Set/edit data\n";
std::cout << setval(ST_BOLD, "3. ") << "Show announcements\n";
std::cout << setval(ST_BOLD, "4. ") << "Exit\n";
std::cout << "\nSelect action: ";
if (count != 0) { std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); }
std::getline(std::cin, choice);
choice_i = stoi(choice);
if (choice_i == 1) {
clr();
show_data(db, user_id, student, password);
if (!back_or_exit()) { return true; } else { clr(); return false;}
} else if (choice_i == 2) {
clr();
edit_data(db, user_id, student, password);
if (!back_or_exit()) { return true; } else { clr(); return false; }
} else if (choice_i == 3) {
clr();
show_announcements(db, user_id, student);
clr();
return false;
} else { return true; }
}
bool menu_lecturer(ObjStore& db, int& count, const int& user_id, const std::string& lecturer, std::string password) {
std::string choice;
int choice_i = 0;
std::cout << setval(ST_BOLD, "1. ") << "Show data\n";
std::cout << setval(ST_BOLD, "2. ") << "Set/edit data\n";
std::cout << setval(ST_BOLD, "3. ") << "Show announcements\n";
std::cout << setval(ST_BOLD, "4. ") << "Create announcement\n";
std::cout << setval(ST_BOLD, "5. ") << "Exit\n";
std::cout << "\nSelect action: ";
if (count != 0) { std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); }
std::getline(std::cin, choice);
choice_i = stoi(choice);
if (choice_i == 1) {
clr();
show_data(db, user_id, lecturer, password);
if (!back_or_exit()) { return true; } else { clr(); return false; }
} else if (choice_i == 2) {
clr();
edit_data(db, user_id, lecturer, password);
if (!back_or_exit()) { return true; } else { clr(); return false; }
} else if (choice_i == 3) {
clr();
show_announcements(db, user_id, lecturer);
clr();
return false;
} else if (choice_i == 4) {
clr();
create_announcement(db, user_id);
clr();
return false;
}
else { return true; }
}
void show_menu(ObjStore& db, const int& user_id, std::string password) {
std::vector<std::string> user_type = check_user_type(db, user_id);
std::cout << std::endl << make_box("Menu Options:") << std::endl;
bool exit = false;
int count = 0;
while (!exit) {
if (std::find(user_type.begin(), user_type.end(), "Admin") != user_type.end()) {
exit = menu_admin(db, count, user_id, "Admin");
} else if (std::find(user_type.begin(), user_type.end(), "Lecturer") != user_type.end()) {
exit = menu_lecturer(db, count, user_id, "Lecturer", password);
} else if (std::find(user_type.begin(), user_type.end(), "Student") != user_type.end()) {
exit = menu_student(db, count, user_id, "Student", password);
}
++count;
}
}
} // namespace UserMenu | 36.141818 | 127 | 0.558054 | gryffyn |
76e4bf332ff7106217b8ccef74c531a75e8aa3fa | 377 | hh | C++ | pipeline/include/hooya/pipeline/CountingSemaphore.hh | hooya-network/libhooya | bbc7b0f85b616bdbed99914023a45fe9a9adf2e9 | [
"MIT"
] | 1 | 2021-07-26T06:24:22.000Z | 2021-07-26T06:24:22.000Z | pipeline/include/hooya/pipeline/CountingSemaphore.hh | hooya-network/libhooya | bbc7b0f85b616bdbed99914023a45fe9a9adf2e9 | [
"MIT"
] | 1 | 2021-08-05T03:45:52.000Z | 2021-08-05T03:45:52.000Z | pipeline/include/hooya/pipeline/CountingSemaphore.hh | hooya-network/libhooya | bbc7b0f85b616bdbed99914023a45fe9a9adf2e9 | [
"MIT"
] | null | null | null | #pragma once
#include <cassert>
#include <mutex>
namespace hooya::pipeline {
/**
* A semaphore that counts how many times it has been raised
*/
class CountingSemaphore {
public:
CountingSemaphore();
/**
* Increment the semaphore
*/
void Raise();
/**
* Decrement the semaphore
*/
void Lower();
private:
std::mutex semGuard;
std::mutex sem;
int count;
}; }
| 13.464286 | 60 | 0.668435 | hooya-network |
76e64d1c519b3be8a71102594e35a23b1c6a7dec | 10,279 | hxx | C++ | the/lib/common/errors.hxx | deni64k/the | c9451f03fe690d456bae89ac2d4a9303317dd8cd | [
"Apache-2.0"
] | null | null | null | the/lib/common/errors.hxx | deni64k/the | c9451f03fe690d456bae89ac2d4a9303317dd8cd | [
"Apache-2.0"
] | null | null | null | the/lib/common/errors.hxx | deni64k/the | c9451f03fe690d456bae89ac2d4a9303317dd8cd | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <variant>
#include <utility>
#include "common.hxx"
// #define _GNU_SOURCE
// #define try
// #define catch(...)
// #include <boost/stacktrace.hpp>
// #undef _GNU_SOURCE
// #undef try
// #undef catch
namespace the {
struct Error {
virtual ~Error();
virtual void What(std::ostream &os) const noexcept = 0;
} __attribute__ ((packed));
std::ostream & operator << (std::ostream &, Error const &);
struct RuntimeError: public Error {
RuntimeError(char const *msg): message_(msg) {}
RuntimeError(std::string const &msg): message_(msg) {}
RuntimeError(std::string &&msg): message_(msg) {}
virtual ~RuntimeError() = default;
void What(std::ostream &os) const noexcept override {
os << message_;
}
// virtual boost::stacktrace::stacktrace const & Where() const noexcept;
protected:
std::string message_;
// boost::stacktrace::stacktrace stacktrace_;
};
/*
namespace details {
template <typename T, bool = std::is_literal_type_v<T>>
struct Uninitialized;
template <typename T>
struct Uninitialized<T, true> {
using ValueType = T;
template <typename ...Args>
constexpr Unnitialized(InPlaceIndexT<0>, Args && ...args)
: value_{std::forward<Args>(args)...} {}
constexpr ValueType const & Get() const & {
return value_;
}
constexpr ValueType & Get() & {
return value_;
}
constexpr ValueType const && Get() const && {
return std::move(value_);
}
constexpr ValueType && Get() && {
return std::move(value_);
}
ValueType value_;
};
template <typename T>
struct Uninitialized<T, false> {
using ValueType = T;
template <typename ...Args>
constexpr Unnitialized(InPlaceIndexT<0>, Args && ...args) {
::new (&value_) ValueType{std::forward<Args>(args)...};
}
constexpr ValueType const & Get() const & {
return *value_._M_ptr();
}
constexpr ValueType & Get() & {
return *value_._M_ptr();
}
constexpr ValueType const && Get() const && {
return std::move(*value_._M_ptr());
}
constexpr ValueType && Get() && {
return std::move(*value_._M_ptr());
}
// TODO: Portable way?
__gnu_cxx::__aligned_membuf<ValueType> value_;
};
struct InPlaceT {
explicit InPlaceT() = default;
};
inline constexpr InPlaceT InPlace{};
template <typename T>
struct InPlaceTypeT {
explicit InPlaceTypeT() = default;
};
template <typename T>
inline constexpr InPlaceTypeT<T> InPlaceType{};
template <std::size_t Index>
struct InPlaceIndexT {
explicit InPlaceIndexT() = default;
};
template <std::size_t Index>
inline constexpr InPlaceIndexT<Index> InPlaceIndex{};
template <typename ...Ts>
union VariadicUnion {};
template <typename T, typename ...Ts>
union VariadicUnion<T, ...Ts> {
constexpr VariadicUnion(): ts_{} {}
template <typename ...Args>
constexpr VariadicUnion(InPlaceIndexT<0>, Args && ...args)
: t{InPlaceIndex<0, std::forward<Args>(args)...} {}
template <std::size_t Index, typename ...Args>
constexpr VariadicUnion(InPlaceIndexT<Index>, Args && ...args)
: ts{InPlaceIndex<Index - 1>, std::forward<Args>(args)...} {}
template <std::size_t I> constexpr T const & Get() const & { return ts.Get<I-1>(); }
template <std::size_t I> constexpr T & Get() & { return ts.Get<I-1>(); }
template <> constexpr T const & Get<0>() const & { return t.Get(); }
template <> constexpr T & Get<0>() & { return t.Get(); }
template <std::size_t I> constexpr T const && Get() const && { return std::move(ts.Get<I-1>()); }
template <std::size_t I> constexpr T && Get() && { return std::move(ts.Get<I-1>()); }
template <> constexpr T const && Get<0>() const && { return std::move(t.Get()); }
template <> constexpr T && Get<0>() && { return std::move(t.Get()); }
template <typename U> constexpr U const & Get() const & { return ts.Get<U>(); }
template <typename U> constexpr U & Get() & { return ts.Get<U>(); }
template <> constexpr T const & Get() const & { return t.Get(); }
template <> constexpr T & Get() & { return t.Get(); }
template <typename U> constexpr U const & Get() const & { return std::move(ts.Get<U>()); }
template <typename U> constexpr U & Get() & { return std::move(ts.Get<U>()); }
template <> constexpr T const & Get() const & { return std::move(t.Get()); }
template <> constexpr T & Get() & { return std::move(t.Get()); }
Uninitialized<T> t;
VariadicUnion<Ts...> ts;
};
template <typename T, typename ...Es>
union FallibleStorage {
friend struct Fallible<T, Es...>;
using ValueType = T;
using ErrorType = VariadicUnion<Es...>;
FallibleStorage() {}
~FallibleStorage() {}
void ConstructValue(ValueType const &value) { new (&value_) ValueType(value); }
void ConstructValue(ValueType &&value) { new (&value_) ValueType(std::move(value)); }
void DestructValue() { &value_.~ValueType(); }
constexpr ValueType const & Value() const & { return value_; }
ValueType & Value() & { return value_; }
ValueType && Value() && { return std::move(value_); }
void ConstructError(ErrorType const &error) { new (&error_) ErrorType(error); }
void ConstructError(ErrorType &&error) { new (&error_) ErrorType(std::move(error)); }
void DestructError() { &error_.~ErrorType(); }
constexpr ErrorType const & Error() const { return error_; }
ErrorType & Error() { return error_; }
private:
ValueType value_;
ErrorType error_;
};
template <typename E>
union FallibleStorage<void, E> final {
friend struct Fallible<void, E>;
using ValueType = void;
using ErrorType = E;
FallibleStorage() {}
~FallibleStorage() {}
void ConstructError(ErrorType const &error) { new (&error_) ErrorType(error); }
void ConstructError(ErrorType &&error) { new (&error_) ErrorType(std::move(error)); }
void DestructError() { &error_.~ErrorType(); }
constexpr ErrorType const & Error() const { return error_; }
ErrorType & Error() { return error_; }
private:
ErrorType error_;
};
}
*/
template <typename T, typename ...Es>
struct [[nodiscard]] FallibleBase final {
using ValueType = T;
using ErrorTypes = std::tuple<Es...>;
using ErrorBaseType = Error;
constexpr FallibleBase() noexcept: storage_{ValueType{}} {}
// constexpr FallibleBase(FallibleBase const &) = delete;
constexpr FallibleBase(FallibleBase const &other) noexcept: storage_{other.storage_} {}
constexpr FallibleBase(FallibleBase &&other) noexcept: storage_{std::move(other.storage_)} {}
constexpr FallibleBase(ValueType const &v) noexcept: storage_{v} {}
constexpr FallibleBase(ValueType &&v) noexcept: storage_{std::forward<ValueType>(v)} {}
template <typename U> constexpr FallibleBase(U &&u) noexcept
requires (std::is_same<std::remove_cv_t<std::remove_reference_t<U>>, Es>::value || ...)
: storage_{std::forward<U>(u)} {}
operator bool () const {
return std::holds_alternative<ValueType>(storage_);
}
ErrorBaseType const & Err() const & { return std::get<1>(storage_); }
ErrorBaseType & Err() & { return std::get<1>(storage_); }
ErrorBaseType const && Err() const && { return std::move(std::get<1>(storage_)); }
ErrorBaseType && Err() && { return std::move(std::get<1>(storage_)); }
ValueType * operator -> () { return &std::get<0>(storage_); }
ValueType const * operator -> () const { return &std::get<0>(storage_); }
ValueType & operator * () & { return std::get<0>(storage_); }
ValueType const & operator * () const & { return std::get<0>(storage_); }
// std::pair<ValueType *, ErrorType *> Lift() {
// return std::make_pair(std::get_if<0>(this), std::get_if<1>(this));
// }
// std::pair<ValueType const *, ErrorType *> Lift() const {
// return std::make_pair(std::get_if<0>(this), std::get_if<1>(this));
// }
// template <typename ...Ess>
operator FallibleBase<std::monostate, Es...> () const &
requires (!std::is_same<ValueType, std::monostate>::value) {
using RetType = FallibleBase<std::monostate, Es...>;
return std::visit([](auto const &arg) -> decltype(auto) {
using Arg = std::decay_t<decltype(arg)>;
if constexpr (std::is_same_v<Arg, ValueType>) {
return RetType{};
} else {
return RetType{arg};
}
}, storage_);
}
// template <typename ...Ess>
operator FallibleBase<std::monostate, Es...> () &
requires (!std::is_same<ValueType, std::monostate>::value) {
using RetType = FallibleBase<std::monostate, Es...>;
return std::visit([](auto &arg) -> decltype(auto) {
using Arg = std::decay_t<decltype(arg)>;
if constexpr (std::is_same_v<Arg, ValueType>) {
return RetType{};
} else {
return RetType{arg};
}
}, storage_);
}
// operator FallibleBase<std::monostate, Es...> && () &&
// requires (!std::is_same<T, std::monostate>::value) {
// if (!*this)
// return {std::move(*this)};
// return std::move(FallibleBase<std::monostate, Es...>{});
// }
private:
std::variant<ValueType, Es...> storage_;
};
template <typename ...Es>
struct [[nodiscard]] FallibleBase<std::monostate, Es...> final {
using ErrorTypes = std::tuple<Es...>;
using ErrorBaseType = Error;
constexpr FallibleBase(): storage_{} {}
// constexpr FallibleBase(FallibleBase const &) = delete;
constexpr FallibleBase(FallibleBase const &other) noexcept: storage_{other.storage_} {}
constexpr FallibleBase(FallibleBase &&other) noexcept: storage_{std::move(other.storage_)} {}
template <typename U>
constexpr FallibleBase(U &&u) noexcept
requires (std::is_same<std::remove_cv_t<std::remove_reference_t<U>>, Es>::value || ...)
: storage_{std::forward<U>(u)} {}
operator bool () const {
return std::holds_alternative<std::monostate>(storage_);
}
ErrorBaseType const & Err() const & { return std::get<1>(storage_); }
ErrorBaseType & Err() & { return std::get<1>(storage_); }
private:
std::variant<std::monostate, Es...> storage_;
};
template <typename Value = std::monostate, typename ...Errors>
using Fallible = FallibleBase<Value, RuntimeError, Errors...>;
// template <> explicit Fallible() -> Fallible<void, Error>;
// template <typename T> explicit Fallible(T &&) -> Fallible<T, Error>;
// template <typename T, typename E> explicit Fallible(E &&) -> Fallible<T, E>;
[[noreturn]]
void Panic(Error const &err) noexcept;
}
| 32.222571 | 99 | 0.651814 | deni64k |
76e955ca1bbb753640623213e01ccc4e7537ab77 | 980 | cpp | C++ | UVA/UltraQuickSort.cpp | sourav025/algorithms-practices | 987932fe0b995c61fc40d1b5a7da18dce8492752 | [
"MIT"
] | null | null | null | UVA/UltraQuickSort.cpp | sourav025/algorithms-practices | 987932fe0b995c61fc40d1b5a7da18dce8492752 | [
"MIT"
] | null | null | null | UVA/UltraQuickSort.cpp | sourav025/algorithms-practices | 987932fe0b995c61fc40d1b5a7da18dce8492752 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
using namespace std;
#define MX 500009
#define ll long long
ll tree[MX+7],ar[MX+7],br[MX+7],n;
ll query(ll idx);
void update(ll idx, int x);
int main() {
while(scanf("%lld",&n)==1 && n)
{
memset(tree, 0, sizeof(tree));
for(int i=0;i<n;i++)
cin>>ar[i], br[i] = ar[i];
sort(br, br+n);
for(int i=0;i<n;i++){
int idx = (int) (lower_bound(br, br+n, ar[i])- br);
ar[i] = idx+1;
}
ll sm = 0;
for(ll i=n-1;i>=0;i--)
{
sm += query(ar[i]-1);
update(ar[i], 1);
}
cout<<sm<<endl;
}
return 0;
}
ll query(ll idx)
{
ll sum=0;
while(idx>0)
{
sum+=tree[idx];
idx -= (idx&-idx);
}
return sum;
}
void update(ll idx, int x)
{
while(idx<=n+1)
{
tree[idx]+=x;
idx += idx & (-idx);
}
} | 16.896552 | 63 | 0.443878 | sourav025 |
76f10ee3b54fdd34398caa407a9cc96c8ec5322e | 8,764 | cpp | C++ | mr.Sadman/Classes/GameAct/Objects/Tech/Saw.cpp | 1pkg/dump | 0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b | [
"MIT"
] | null | null | null | mr.Sadman/Classes/GameAct/Objects/Tech/Saw.cpp | 1pkg/dump | 0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b | [
"MIT"
] | 3 | 2020-12-11T10:01:27.000Z | 2022-02-13T22:12:05.000Z | mr.Sadman/Classes/GameAct/Objects/Tech/Saw.cpp | 1pkg/dump | 0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b | [
"MIT"
] | null | null | null | #include "Director.hpp"
#include "GameAct/Act.hpp"
#include "GameAct/Objects/Factories/ObjectsFactory.hpp"
#include "Saw.hpp"
#include "Resources/Cache/Cache.hpp"
#include <cmath>
namespace GameAct
{
namespace Tech
{
Saw::Saw()
: _decorator( Director::getInstance().getGameAct()->getObjectsFactory()->create( "Line" ) )
{
}
std::string
Saw::getName() const
{
return "Saw";
}
void
Saw::setPosition( cocos2d::Vec2 position )
{
float koef = 1.0f / sqrt( 2.0f );
cocos2d::Vec2 decPosit = position;
switch ( _direction )
{
case Direction::Right:
decPosit.x += _decorator->getSize().width / 2.0f;
break;
case Direction::Left:
decPosit.x -= _decorator->getSize().width / 2.0f;
break;
case Direction::Top:
decPosit.y += _decorator->getSize().width / 2.0f;
break;
case Direction::Bottom:
decPosit.y -= _decorator->getSize().width / 2.0f;
break;
case Direction::D45:
decPosit.y += _decorator->getSize().width / 2.0f * koef;
decPosit.x -= _decorator->getSize().width / 2.0f * koef;
break;
case Direction::D135:
decPosit.y += _decorator->getSize().width / 2.0f * koef;
decPosit.x += _decorator->getSize().width / 2.0f * koef;
break;
case Direction::D225:
decPosit.y -= _decorator->getSize().width / 2.0f * koef;
decPosit.x += _decorator->getSize().width / 2.0f * koef;
break;
case Direction::D315:
decPosit.y -= _decorator->getSize().width / 2.0f * koef;
decPosit.x -= _decorator->getSize().width / 2.0f * koef;
break;
case Direction::Circle:
decPosit.x += _decorator->getSize().width;
break;
default:
break;
}
_decorator->setPosition( decPosit );
Object::setPosition( position );
}
void
Saw::setSize( cocos2d::Size size )
{
float koef = 1.0f / sqrt( 2.0f );
cocos2d::Size decSize = size;
switch ( _direction )
{
case Direction::Left:
case Direction::Right:
case Direction::Top:
case Direction::Bottom:
case Direction::Circle:
decSize.width *= _lenth;
decSize.height /= 2.0f;
break;
case Direction::D45:
case Direction::D135:
case Direction::D225:
case Direction::D315:
decSize.width *= _lenth / koef;
decSize.height /= 2.0f;
break;
default:
break;
}
_decorator->setSize( decSize );
Object::setSize( size );
}
void
Saw::setAdditionalParam( std::string additionalParam )
{
int posit = additionalParam.find( ';' );
_lenth = std::stof( additionalParam.substr( 0, posit ) );
_time = std::stof( additionalParam.substr( posit + 1, additionalParam.length() - posit - 1 ) );
_decorator->setAdditionalParam( std::to_string( _time ) );
}
void
Saw::setDirection( Direction direction )
{
_decorator->setDirection( direction );
Object::setDirection( direction );
}
void
Saw::hide()
{
_decorator->hide();
Object::hide();
}
void
Saw::show()
{
_decorator->show();
Object::show();
}
void
Saw::attachToChunk( Chunk & chunk, int zIndex )
{
_decorator->attachToChunk( chunk, zIndex - 1 );
Object::attachToChunk( chunk, zIndex );
}
void
Saw::runAction( const std::string & action )
{
// horizontal init
cocos2d::Vec2 rightPos = cocos2d::Vec2( getSize().width * _lenth, 0.0f );
cocos2d::Vec2 leftPos = cocos2d::Vec2( getSize().width * -_lenth, 0.0f );
auto rotate = cocos2d::RotateBy::create( _time, 360.0f );
auto goRight = cocos2d::MoveBy::create( _time * 5.0f, rightPos );
auto goLeft = cocos2d::MoveBy::create( _time * 5.0f, leftPos );
auto spawnRight = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goRight, nullptr );
auto spawnLeft = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goLeft, nullptr );
// vertiacal init
cocos2d::Vec2 upPos = cocos2d::Vec2( 0.0f, getSize().width * _lenth );
cocos2d::Vec2 downPos = cocos2d::Vec2( 0.0f, getSize().width * -_lenth );
auto goUp = cocos2d::MoveBy::create( _time * 5.0f, upPos );
auto goDown = cocos2d::MoveBy::create( _time * 5.0f, downPos );
auto spawnUp = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goUp, nullptr );
auto spawnDown = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goDown, nullptr );
// angle init
float lineLenth = getSize().width * _lenth;
cocos2d::Action * sequence;
if( action == "Run" )
{
switch ( _direction )
{
case Direction::Left:
sequence = cocos2d::RepeatForever::create( cocos2d::Sequence::create( spawnLeft, spawnRight, nullptr ) );
break;
case Direction::Right:
sequence = cocos2d::RepeatForever::create( cocos2d::Sequence::create( spawnRight, spawnLeft, nullptr ) );
break;
case Direction::Top:
sequence = cocos2d::RepeatForever::create( cocos2d::Sequence::create( spawnUp, spawnDown, nullptr ) );
break;
case Direction::Bottom:
sequence = cocos2d::RepeatForever::create( cocos2d::Sequence::create( spawnDown, spawnUp, nullptr ) );
break;
case Direction::D45:
{
cocos2d::Vec2 pos1 = cocos2d::Vec2( -lineLenth, lineLenth );
cocos2d::Vec2 pos2 = cocos2d::Vec2( lineLenth, -lineLenth );
auto goPos1 = cocos2d::MoveBy::create( _time * 5.0f, pos1 );
auto goPos2 = cocos2d::MoveBy::create( _time * 5.0f, pos2 );
auto spawnPos1 = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goPos1, nullptr );
auto spawnPos2 = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goPos2, nullptr );
sequence = cocos2d::RepeatForever::create( cocos2d::Sequence::create( spawnPos1, spawnPos2, nullptr ) );
}
break;
case Direction::D135:
{
cocos2d::Vec2 pos1 = cocos2d::Vec2( lineLenth, lineLenth );
cocos2d::Vec2 pos2 = cocos2d::Vec2( -lineLenth, -lineLenth );
auto goPos1 = cocos2d::MoveBy::create( _time * 5.0f, pos1 );
auto goPos2 = cocos2d::MoveBy::create( _time * 5.0f, pos2 );
auto spawnPos1 = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goPos1, nullptr );
auto spawnPos2 = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goPos2, nullptr );
sequence = cocos2d::RepeatForever::create( cocos2d::Sequence::create( spawnPos1, spawnPos2, nullptr ) );
}
break;
case Direction::D225:
{
cocos2d::Vec2 pos1 = cocos2d::Vec2( lineLenth, -lineLenth );
cocos2d::Vec2 pos2 = cocos2d::Vec2( -lineLenth, lineLenth );
auto goPos1 = cocos2d::MoveBy::create( _time * 5.0f, pos1 );
auto goPos2 = cocos2d::MoveBy::create( _time * 5.0f, pos2 );
auto spawnPos1 = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goPos1, nullptr );
auto spawnPos2 = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goPos2, nullptr );
sequence = cocos2d::RepeatForever::create( cocos2d::Sequence::create( spawnPos1, spawnPos2, nullptr ) );
}
break;
case Direction::D315:
{
cocos2d::Vec2 pos1 = cocos2d::Vec2( -lineLenth, -lineLenth );
cocos2d::Vec2 pos2 = cocos2d::Vec2( lineLenth, lineLenth );
auto goPos1 = cocos2d::MoveBy::create( _time * 5.0f, pos1 );
auto goPos2 = cocos2d::MoveBy::create( _time * 5.0f, pos2 );
auto spawnPos1 = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goPos1, nullptr );
auto spawnPos2 = cocos2d::Spawn::create( cocos2d::Repeat::create( rotate, 5 ), goPos2, nullptr );
sequence = cocos2d::RepeatForever::create( cocos2d::Sequence::create( spawnPos1, spawnPos2, nullptr ) );
}
break;
case Direction::Circle:
{
cocos2d::Vec2 center = getPosition();
center.x += getSize().width * _lenth;
cocos2d::Vector< cocos2d::FiniteTimeAction * > _rotate;
auto posit = getPosition();
for( int i = 0; i < 100; ++i )
{
_rotate.pushBack( cocos2d::MoveTo::create( _time / 100, posit ) );
posit = rotatePoint( posit, center, 3.6f );
}
sequence = cocos2d::RepeatForever::create( cocos2d::Sequence::create( _rotate ) );
_decorator->runAction( "Rotate" );
}
default:
break;
}
_sprite->runAction( sequence );
_audio = Resources::Cache::getInstance().getObjectSound( getName(), "Def" );
}
if( action == "Stop" )
{
_sprite->stopAllActions();
_decorator->runAction( "Stop" );
}
}
cocos2d::Vec2
Saw::rotatePoint( cocos2d::Vec2 point, cocos2d::Vec2 center, float angle ) const
{
angle = (angle ) * ( M_PI / 180 );
float rotatedX = cos( angle ) * (point.x - center.x) + sin( angle ) * ( point.y - center.y ) + center.x;
float rotatedY = -sin( angle ) * ( point.x - center.x ) + cos( angle ) * ( point.y - center.y ) + center.y;
return cocos2d::Vec2( rotatedX, rotatedY );
}
}
} | 28.828947 | 112 | 0.637608 | 1pkg |
76f964cabbe329b0e3c09bcdbc775200858ce885 | 2,767 | cpp | C++ | Shader.cpp | HeckMina/CGI | 976dfe064ec8021ef615354c46ca93637c56b8c6 | [
"MIT"
] | 2 | 2021-07-06T01:01:55.000Z | 2021-07-07T01:30:31.000Z | Shader.cpp | HeckMina/CGI | 976dfe064ec8021ef615354c46ca93637c56b8c6 | [
"MIT"
] | null | null | null | Shader.cpp | HeckMina/CGI | 976dfe064ec8021ef615354c46ca93637c56b8c6 | [
"MIT"
] | 1 | 2021-03-31T05:36:27.000Z | 2021-03-31T05:36:27.000Z | #include "Shader.h"
#if ALICE_OGL_RENDERER
#include "utils.h"
namespace Alice {
void Shader::Init(const char* vs, const char* fs) {
int nFileSize = 0;
const char* vsCode = (char*)LoadFileContent(vs, nFileSize);
const char* fsCode = (char*)LoadFileContent(fs, nFileSize);
GLuint vsShader = CompileShader(GL_VERTEX_SHADER, vsCode);
if (vsShader == 0) {
return;
}
GLuint fsShader = CompileShader(GL_FRAGMENT_SHADER, fsCode);
if (fsShader == 0) {
return;
}
OGL_CALL(mProgram = CreateProgram(vsShader, fsShader));
OGL_CALL(glDeleteShader(vsShader));
OGL_CALL(glDeleteShader(fsShader));
if (mProgram != 0) {
OGL_CALL(mModelMatrixLocation = glGetUniformLocation(mProgram, "ModelMatrix"));
OGL_CALL(mViewMatrixLocation = glGetUniformLocation(mProgram, "ViewMatrix"));
OGL_CALL(mProjectionMatrixLocation = glGetUniformLocation(mProgram, "ProjectionMatrix"));
OGL_CALL(mITModelMatrixLocation = glGetUniformLocation(mProgram, "U_NormalMatrix"));
OGL_CALL(mPositionLocation = glGetAttribLocation(mProgram, "position"));
OGL_CALL(mTangentLocation = glGetAttribLocation(mProgram, "tangent"));
OGL_CALL(mTexcoordLocation = glGetAttribLocation(mProgram, "texcoord"));
OGL_CALL(mNormalLocation = glGetAttribLocation(mProgram, "normal"));
}
}
void Shader::BeginDraw(Camera* camera, const glm::mat4& model) {
OGL_CALL(glUseProgram(mProgram));
if (camera != nullptr) {
if (mViewMatrixLocation != -1) {
OGL_CALL(glUniformMatrix4fv(mViewMatrixLocation, 1, GL_FALSE, glm::value_ptr(camera->mViewMatrix)));
}
if (mProjectionMatrixLocation != -1) {
OGL_CALL(glUniformMatrix4fv(mProjectionMatrixLocation, 1, GL_FALSE, glm::value_ptr(camera->mProjectionMatrix)));
}
}
if (mModelMatrixLocation != -1) {
OGL_CALL(glUniformMatrix4fv(mModelMatrixLocation, 1, GL_FALSE, glm::value_ptr(model)));
}
if (mPositionLocation != -1) {
OGL_CALL(glEnableVertexAttribArray(mPositionLocation));
OGL_CALL(glVertexAttribPointer(mPositionLocation, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0));
}
if (mTexcoordLocation != -1) {
OGL_CALL(glEnableVertexAttribArray(mTexcoordLocation));
OGL_CALL(glVertexAttribPointer(mTexcoordLocation, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(float) * 4)));
}
if (mNormalLocation != -1) {
OGL_CALL(glEnableVertexAttribArray(mNormalLocation));
OGL_CALL(glVertexAttribPointer(mNormalLocation, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(float) * 8)));
}
if (mTangentLocation != -1) {
OGL_CALL(glEnableVertexAttribArray(mTangentLocation));
OGL_CALL(glVertexAttribPointer(mTangentLocation, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(float) * 12)));
}
}
void Shader::EndDraw() {
OGL_CALL(glUseProgram(0));
}
}
#endif | 42.569231 | 121 | 0.738345 | HeckMina |
0a012814f275542a7122359c744a11b78c54fc76 | 5,675 | cpp | C++ | src/cl-utils/str-args.cpp | codalogic/cl-utils | 996452272d4c09b8df7928abdaea75b0e786a244 | [
"BSD-3-Clause"
] | null | null | null | src/cl-utils/str-args.cpp | codalogic/cl-utils | 996452272d4c09b8df7928abdaea75b0e786a244 | [
"BSD-3-Clause"
] | null | null | null | src/cl-utils/str-args.cpp | codalogic/cl-utils | 996452272d4c09b8df7928abdaea75b0e786a244 | [
"BSD-3-Clause"
] | null | null | null | //----------------------------------------------------------------------------
// Copyright (c) 2016, Codalogic Ltd (http://www.codalogic.com)
// All rights reserved.
//
// The license for this file is based on the BSD-3-Clause license
// (http://www.opensource.org/licenses/BSD-3-Clause).
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// - Neither the name Codalogic Ltd nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//----------------------------------------------------------------------------
#include "cl-utils/str-args.h"
#include <cassert>
#include <cstring>
#include <algorithm>
namespace clutils {
namespace { // Implementation detail
class str_args_detail
{
private:
size_t i;
std::string * p_result;
const char * format;
const str_args::args_t & args;
public:
str_args_detail( std::string * p_out, const char * format, const str_args::args_t & args )
:
p_result( p_out ),
format( format ),
args( args )
{
try
{
p_result->reserve( p_result->size() + strlen( format ) );
for( i=0; format[i] != '\0'; safe_advance() )
{
if( format[i] != '%' )
p_result->append( 1, format[i] );
else
process_parameter_decl();
}
}
catch( std::out_of_range & )
{
assert( 0 ); // We've done something like %1 in our args string when args[1] doesn't exist. N.B. args are 0 based.
throw str_argsOutOfRangeException( "str_args args[] index out of range" );
}
}
void safe_advance()
{
if( format[i] != '\0' )
++i;
}
void process_parameter_decl()
{
safe_advance();
if( format[i] == '\0' ) // Malformed case, but be tolerant
p_result->append( 1, '%' );
else if( format[i] == '%' ) // %% -> %
p_result->append( 1, '%' );
else if( is_numerical_parameter() )
p_result->append( args.at( format[i] - '0' ) );
else if( format[i] == '{' )
process_long_form_parameter_decl();
else
silently_accept_standalone_parameter_indicator();
}
bool is_numerical_parameter()
{
return format[i] >= '0' && format[i] <= '9';
}
void process_long_form_parameter_decl()
{
safe_advance();
if( format[i] != '\0' )
{
if( is_numerical_parameter() )
process_numbered_long_form_parameter_decl();
else
process_named_long_form_parameter_decl();
}
}
void process_numbered_long_form_parameter_decl()
{
// Long form %{0:a description}
size_t index = read_numerical_parameter_index();
p_result->append( args.at( index ) );
skip_remainder_of_parameter_decl();
}
size_t read_numerical_parameter_index()
{
size_t index = 0;
while( is_numerical_parameter() )
index = 10 * index + format[i++] - '0';
return index;
}
void skip_remainder_of_parameter_decl()
{
for( ; format[i] != '\0' && format[i] != '}'; safe_advance() )
{} // Skip over rest of characters in format specifier
}
void process_named_long_form_parameter_decl()
{
// Named long form %{var-name}
std::string name = read_parameter_name();
str_args::args_t::const_iterator key_index = std::find( args.begin(), args.end(), name );
if( key_index != args.end() )
p_result->append( *(++key_index) );
skip_remainder_of_parameter_decl();
}
std::string read_parameter_name()
{
std::string name;
for( ; format[i] != '\0' && format[i] != '}'; safe_advance() )
name.append( 1, format[i] );
return name;
}
void silently_accept_standalone_parameter_indicator()
{
p_result->append( 1, '%' );
p_result->append( 1, format[i] );
}
std::string * result() const { return p_result; }
};
} // End of namespace { // Implementation detail
std::string * str_args::expand_append( std::string * p_out, const char * format ) const
{
return str_args_detail( p_out, format, args ).result();
}
} // namespace clutils
| 32.614943 | 127 | 0.597181 | codalogic |
0a023ff0a7846fabea47bb9f8bbce6955f1a5ffc | 734 | hpp | C++ | libs/options/include/fcppt/options/base_unique_ptr_fwd.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | libs/options/include/fcppt/options/base_unique_ptr_fwd.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | libs/options/include/fcppt/options/base_unique_ptr_fwd.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | // Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_OPTIONS_BASE_UNIQUE_PTR_FWD_HPP_INCLUDED
#define FCPPT_OPTIONS_BASE_UNIQUE_PTR_FWD_HPP_INCLUDED
#include <fcppt/unique_ptr_fwd.hpp>
#include <fcppt/options/base_fwd.hpp>
namespace fcppt
{
namespace options
{
/**
\brief A unique pointer for #fcppt::options::base.
\ingroup fcpptoptions
\tparam Result The result type of the parser. Must be an #fcppt::record::object.
*/
template<
typename Result
>
using
base_unique_ptr
=
fcppt::unique_ptr<
fcppt::options::base<
Result
>
>;
}
}
#endif
| 17.47619 | 80 | 0.741144 | pmiddend |
0a117fdeca03b2c8e3f53053fbe68a19b9187031 | 8,533 | cpp | C++ | 008_social_distancing.cpp | DreamVu/Code-Samples | 2fccd9e649fbe7d9895df7d799cb1ec33066d1c2 | [
"MIT"
] | null | null | null | 008_social_distancing.cpp | DreamVu/Code-Samples | 2fccd9e649fbe7d9895df7d799cb1ec33066d1c2 | [
"MIT"
] | null | null | null | 008_social_distancing.cpp | DreamVu/Code-Samples | 2fccd9e649fbe7d9895df7d799cb1ec33066d1c2 | [
"MIT"
] | null | null | null | /*
CODE SAMPLE # 008: Social Distancing
This code sample allows users to check if the distance between two people is within a limit or not.
>>>>>> Compile this code using the following command....
g++ 008_social_distancing.cpp /usr/src/tensorrt/bin/common/logger.o ../lib/libPAL.so ../lib/libPAL_CAMERA.so ../lib/libPAL_DEPTH_HQ.so ../lib/libPAL_DEPTH_128.so ../lib/libPAL_DE.so ../lib/libPAL_EDET.so `pkg-config --libs --cflags opencv` -g -o 008_social_distancing.out -I../include/ -lv4l2 -lpthread -lcudart -L/usr/local/cuda/lib64 -lnvinfer -lnvvpi -lnvparsers -lnvinfer_plugin -lnvonnxparser -lmyelin -lnvrtc -lcudart -lcublas -lcudnn -lrt -ldl -lstdc++fs
>>>>>> Execute the binary file by typing the following command...
./008_social_distancing.out
>>>>>> KEYBOARD CONTROLS:
Press ESC to close the window
Press f/F to toggle filter rgb property
Press d/D to toggle fast depth property
Press v/V to toggle vertical flip property
Press r/R to toggle near range property
Press l/L to switch floor mode
Press i/I to switch intermediate mode
Press t/T to switch table top mode
Press c/C to switch ceiling mode
Press a/A to switch auto mode
*/
# include <stdio.h>
# include <opencv2/opencv.hpp>
# include "PAL.h"
using namespace cv;
using namespace std;
namespace PAL
{
namespace Internal
{
void EnableDepth(bool flag);
void MinimiseCompute(bool flag);
}
}
//Function to compute distance between two persons
bool IsSociallyDistant(PAL::Loc3D p1, PAL::Loc3D p2, int threshold)
{
if((sqrt(pow(p1.x-p2.x,2.0)+pow(p1.y-p2.y,2.0)+pow(p1.z-p2.z,2.0))) <= threshold)
return false;
return true;
}
//Function to compute whether the detected persons are socially distant or not
void ComputeDistanceMatrix(std::vector<PAL::Loc3D> Loc3Ds, std::vector<bool>& DistantData, float threshold_distance)
{
int num_persons = Loc3Ds.size();
bool b = true;
for(int i=0; i<num_persons; i++)
{
for(int j = i+1; j<num_persons; j++)
{
//checking if location of two persons are larger or not than 100cm
b = IsSociallyDistant(Loc3Ds[i], Loc3Ds[j], threshold_distance);
if(!b)
DistantData[i] = DistantData[j] = false;
}
}
}
int main( int argc, char** argv )
{
namedWindow( "PAL Social Distancing", WINDOW_NORMAL ); // Create a window for display.
//Depth should be enabled for this code sample as a prerequisite
bool isDepthEnabled = true;
PAL::Internal::EnableDepth(isDepthEnabled);
PAL::Internal::MinimiseCompute(false);
int width, height;
if(PAL::Init(width, height,-1) != PAL::SUCCESS) //Connect to the PAL camera
{
printf("Camera Init failed\n");
return 1;
}
PAL::CameraProperties data;
PAL::Acknowledgement ack = PAL::LoadProperties("../Explorer/SavedPalProperties.txt");
if(ack != PAL::SUCCESS)
{
printf("Error Loading settings\n");
}
PAL::CameraProperties prop;
unsigned int flag = PAL::MODE;
flag = flag | PAL::FD;
flag = flag | PAL::NR;
flag = flag | PAL::FILTER_SPOTS;
flag = flag | PAL::VERTICAL_FLIP;
prop.mode = PAL::Mode::DETECTION;
prop.fd = 1;
prop.nr = 0;
prop.filter_spots = 1;
prop.vertical_flip =0;
PAL::SetCameraProperties(&prop, &flag);
float threshold = (argc>1) ? atof(argv[1]) : 0.35;
float threshold_distance = (argc>2) ? atof(argv[2]) : 100.0f; //threshold_distane should be between 1m to 2m.
if(threshold_distance > 200)
{
threshold_distance = 200;
printf("threshold distance set above maximum range. Setting to 2m");
}
else if(threshold_distance < 100)
{
threshold_distance = 100;
printf("threshold distance set below minumum range. Setting to 1m");
}
if(PAL::InitPersonDetection(threshold)!= PAL::SUCCESS) //Initialise object detection pipeline
{
printf("Social Distancing Init failed\n");
return 1;
}
//width and height are the dimensions of each panorama.
//Each of the panoramas are displayed at quarter their original resolution.
//Since the left+right+disparity are vertically stacked, the window height should be thrice the quarter-height
resizeWindow("PAL Social Distancing", width/4, (height/4)*3);
int key = ' ';
printf("Press ESC to close the window\n");
printf("Press f/F to toggle filter rgb property\n");
printf("Press d/D to toggle fast depth property\n");
printf("Press v/V to toggle vertical flip property\n");
printf("Press r/R to toggle near range property\n");
printf("Press l/L to switch floor mode\n");
printf("Press i/I to switch intermediate mode\n");
printf("Press t/T to switch table top mode\n");
printf("Press c/C to switch ceiling mode\n");
printf("Press a/A to switch auto mode\n");
bool flip = false;
bool fd = true;
bool nr = false;
bool filter_spots = true;
//27 = esc key. Run the loop until the ESC key is pressed
while(key != 27)
{
cv::Mat rgb, depth, output,right;
std::vector<PAL::BoundingBox> Boxes;
vector<float> DepthValues;
vector<PAL::Loc3D> Loc3Ds;
//Function to Query
//Image data: rgb & depth panoramas
//Person detection data: Bounding boxes and 3-D locations of each person detected.
PAL::GetPeopleDetection(rgb,right, depth, &Boxes, DepthValues, &Loc3Ds);
int num_of_persons = Boxes.size();
std::vector<bool> DistantData(num_of_persons, true);
//Computing if persons are socially distant or not in case of multiple detections using 3-D locations
if(num_of_persons>=2)
{
ComputeDistanceMatrix(Loc3Ds, DistantData, threshold_distance);
for(int i=0; i<num_of_persons; i++)
{
if(DistantData[i])
cv::rectangle(rgb,Point(Boxes[i].x1, Boxes[i].y1), Point(Boxes[i].x2, Boxes[i].y2), cv::Scalar(0,255,0),2); //Drawing GREEN box indicating the person is socially distant
else
cv::rectangle(rgb,Point(Boxes[i].x1, Boxes[i].y1), Point(Boxes[i].x2, Boxes[i].y2), cv::Scalar(0,0,255),2); //Drawing RED box indicating the person is not socially distant
}
}
else if(num_of_persons==1)
{
cv::rectangle(rgb,Point(Boxes[0].x1, Boxes[0].y1), Point(Boxes[0].x2, Boxes[0].y2), cv::Scalar(0,255,0), 2);
}
//Display the final output image
imshow( "PAL Social Distancing", rgb);
//Wait for the keypress - with a timeout of 1 ms
key = waitKey(1) & 255;
if (key == 'f' || key == 'F')
{
PAL::CameraProperties prop;
filter_spots = !filter_spots;
prop.filter_spots = filter_spots;
unsigned int flags = PAL::FILTER_SPOTS;
PAL::SetCameraProperties(&prop, &flags);
}
if (key == 'v' || key == 'V')
{
PAL::CameraProperties prop;
flip = !flip;
prop.vertical_flip = flip;
unsigned int flags = PAL::VERTICAL_FLIP;
PAL::SetCameraProperties(&prop, &flags);
}
if (key == 'l' || key == 'L')
{
PAL::CameraProperties prop;
prop.mode = PAL::Mode::DETECTION;
prop.detection_mode = PAL::FLOOR;
unsigned int flags = PAL::DETECTION_MODE | PAL::MODE;
PAL::SetCameraProperties(&prop, &flags);
}
if (key == 't' || key == 'T')
{
PAL::CameraProperties prop;
prop.mode = PAL::Mode::DETECTION;
prop.detection_mode = PAL::TABLE_TOP;
unsigned int flags = PAL::DETECTION_MODE | PAL::MODE;
PAL::SetCameraProperties(&prop, &flags);
}
if (key == 'c' || key == 'C')
{
PAL::CameraProperties prop;
prop.mode = PAL::Mode::DETECTION;
prop.detection_mode = PAL::CEILING;
unsigned int flags = PAL::DETECTION_MODE | PAL::MODE;
PAL::SetCameraProperties(&prop, &flags);
}
if (key == 'i' || key == 'I')
{
PAL::CameraProperties prop;
prop.mode = PAL::Mode::DETECTION;
prop.detection_mode = PAL::INTERMEDIATE;
unsigned int flags = PAL::DETECTION_MODE | PAL::MODE;
PAL::SetCameraProperties(&prop, &flags);
}
if (key == 'a' || key == 'A')
{
PAL::CameraProperties prop;
prop.mode = PAL::Mode::DETECTION;
prop.detection_mode = PAL::AUTO;
unsigned int flags = PAL::DETECTION_MODE | PAL::MODE;
PAL::SetCameraProperties(&prop, &flags);
}
if(key == 'd' || key == 'D')
{
PAL::CameraProperties prop;
fd = !fd;
prop.fd = fd;
unsigned int flags = PAL::FD;
PAL::SetCameraProperties(&prop, &flags);
}
if(key == 'r' || key == 'R')
{
PAL::CameraProperties prop;
nr = !nr;
prop.nr = nr;
unsigned int flags = PAL::NR;
PAL::SetCameraProperties(&prop, &flags);
}
PAL::CameraProperties properties;
GetCameraProperties(&properties);
filter_spots = properties.filter_spots;
flip = properties.vertical_flip;
fd = properties.fd;
nr = properties.nr;
}
printf("exiting the application\n");
PAL::Destroy();
return 0;
}
| 30.475 | 471 | 0.677253 | DreamVu |
0a119fc12cfcae022b721e0096cda6eac2b5ab21 | 1,470 | cpp | C++ | Rush/Platform.cpp | kayru/librush | 70fe4af6c8a635f4eac6ab20dbc1f251d299dc3a | [
"MIT"
] | 49 | 2015-01-18T17:24:44.000Z | 2022-03-31T01:31:38.000Z | Rush/Platform.cpp | kayru/librush | 70fe4af6c8a635f4eac6ab20dbc1f251d299dc3a | [
"MIT"
] | null | null | null | Rush/Platform.cpp | kayru/librush | 70fe4af6c8a635f4eac6ab20dbc1f251d299dc3a | [
"MIT"
] | 4 | 2015-05-22T21:22:18.000Z | 2019-07-31T23:18:04.000Z | #include "Platform.h"
#include "GfxDevice.h"
#include "UtilLog.h"
#include "Window.h"
namespace Rush
{
Window* g_mainWindow = nullptr;
GfxDevice* g_mainGfxDevice = nullptr;
GfxContext* g_mainGfxContext = nullptr;
void Platform_Startup(const AppConfig& cfg)
{
RUSH_ASSERT(g_mainWindow == nullptr);
RUSH_ASSERT(g_mainGfxDevice == nullptr);
RUSH_ASSERT(g_mainGfxContext == nullptr);
WindowDesc windowDesc;
windowDesc.width = cfg.width;
windowDesc.height = cfg.height;
windowDesc.resizable = cfg.resizable;
windowDesc.caption = cfg.name;
windowDesc.fullScreen = cfg.fullScreen;
windowDesc.maximized = cfg.maximized;
Window* window = Platform_CreateWindow(windowDesc);
g_mainWindow = window;
GfxConfig gfxConfig;
if (cfg.gfxConfig)
{
gfxConfig = *cfg.gfxConfig;
}
else
{
gfxConfig = GfxConfig(cfg);
}
g_mainGfxDevice = Gfx_CreateDevice(window, gfxConfig);
g_mainGfxContext = Gfx_AcquireContext();
}
void Platform_Shutdown()
{
RUSH_ASSERT(g_mainWindow != nullptr);
RUSH_ASSERT(g_mainGfxDevice != nullptr);
RUSH_ASSERT(g_mainGfxContext != nullptr);
Gfx_Release(g_mainGfxContext);
Gfx_Release(g_mainGfxDevice);
g_mainWindow->release();
}
int Platform_Main(const AppConfig& cfg)
{
Platform_Startup(cfg);
if (cfg.onStartup)
{
cfg.onStartup(cfg.userData);
}
Platform_Run(cfg.onUpdate, cfg.userData);
if (cfg.onShutdown)
{
cfg.onShutdown(cfg.userData);
}
Platform_Shutdown();
return 0;
}
}
| 18.846154 | 56 | 0.734694 | kayru |
0a13d15d930cc8b2f5140ad360b68e166490c565 | 1,594 | cpp | C++ | Chapter02/vector_access_fast_or_safe.cpp | raakasf/Cpp17-STL-Cookbook | bf889164c515094d37f18023af48fe86fcbb1824 | [
"MIT"
] | 480 | 2017-06-29T14:58:34.000Z | 2022-03-29T03:22:49.000Z | Chapter02/vector_access_fast_or_safe.cpp | raakasf/Cpp17-STL-Cookbook | bf889164c515094d37f18023af48fe86fcbb1824 | [
"MIT"
] | 10 | 2017-09-06T10:33:38.000Z | 2021-05-31T11:54:23.000Z | Chapter02/vector_access_fast_or_safe.cpp | raakasf/Cpp17-STL-Cookbook | bf889164c515094d37f18023af48fe86fcbb1824 | [
"MIT"
] | 133 | 2017-07-04T01:55:22.000Z | 2022-03-20T12:44:54.000Z | #include <iostream>
#include <vector>
#include <array>
#include <numeric> // for std::iota
int main()
{
constexpr size_t container_size {1000};
#if 0
std::vector<int> v (container_size);
// Fill the vector with rising numbers
std::iota(std::begin(v), std::end(v), 0);
// Chances are, that the following line will not lead to a crash...
std::cout << "Out of range element value: "
<< v[container_size + 10] << "\n";
try {
// This out of bounds access DOES lead to an exception...
std::cout << "Out of range element value: "
<< v.at(container_size + 10) << "\n";
} catch (const std::out_of_range &e) {
// ...which we catch here.
std::cout << "Ooops, out of range access detected: "
<< e.what() << "\n";
}
#endif
// The same access methods and rules apply to std::array:
std::array<int, container_size> a;
// Fill the vector with rising numbers
std::iota(std::begin(a), std::end(a), 0);
// Chances are, that the following line will not lead to a crash...
std::cout << "Out of range element value: "
<< a[container_size + 10] << "\n";
#if 0
try {
#endif
// This out of bounds access DOES lead to an exception...
std::cout << "Out of range element value: "
<< a.at(container_size + 10) << "\n";
#if 0
} catch (const std::out_of_range &e) {
// ...which we catch here.
std::cout << "Ooops, out of range access detected: "
<< e.what() << "\n";
}
#endif
}
| 27.964912 | 71 | 0.55207 | raakasf |
0a168dcda9d9249f937af3534e479e275c1f2bfb | 2,429 | cpp | C++ | test/testjson.cpp | StuffByDavid/Base | d37713fcf48655cb49032c576a1586c135e2e83d | [
"MIT"
] | null | null | null | test/testjson.cpp | StuffByDavid/Base | d37713fcf48655cb49032c576a1586c135e2e83d | [
"MIT"
] | null | null | null | test/testjson.cpp | StuffByDavid/Base | d37713fcf48655cb49032c576a1586c135e2e83d | [
"MIT"
] | null | null | null | #include "test.hpp"
#include "file/json.hpp"
#include "util/timer.hpp"
void Base::TestApp::testJSON()
{
cout << "testJSON" << endl;
// Loading and saving
try
{
Timer t1("JSON load");
JsonFile jf(((TextFile*)resHandler->get("hello.json"))->getText());
t1.stopAndPrint();
Timer t2("JSON save");
jf.save(FilePath("C:/Dev/Builds/base/out.json"));
t2.stopAndPrint();
cout << "foo: " << jf.getString("foo") << endl;
cout << "Bar: " << jf.getNumber("Bar") << endl;
JsonArray* arr = jf.getArray("Array");
cout << "Array length: " << arr->getCount() << endl;
cout << " 0: " << arr->getNumber(0) << endl;
cout << " 1: " << arr->getNumber(1) << endl;
cout << " 2: " << arr->getString(2) << endl;
cout << " 2 isNull: " << (arr->isNull(2) ? "true": "false") << endl;
JsonObject* obj = jf.getArray("Objects")->getObject(0);
cout << "Object int: " << obj->getNumber("int") << endl;
cout << "Object float: " << obj->getNumber("float") << endl;
cout << "Object str: " << obj->getString("str") << endl;
cout << "Object multilinestr: " << obj->getString("multilinestr") << endl;
cout << "Object multilinestr isNull: " << (obj->isNull("multilinestr") ? "true": "false") << endl;
cout << "Object null isNull: " << (obj->isNull("null") ? "true": "false") << endl;
cout << "Object bool: " << (obj->getBool("bool") ? "true": "false") << endl;
//JsonObject* nonExistant = jf.getArray("Objects")->getObject(1);
jf.save(FilePath("C:/Dev/Builds/base/out1.json"));
}
catch (const JsonException& ex)
{
cout << ex.what() << endl;
}
// Generating
try
{
Timer t1("JSON generate");
JsonFile jf;
JsonArray* arr = jf.addArray("elements");
repeat (5)
{
JsonObject* obj = arr->addObject();
obj->addString("name", "HelloWorld");
obj->addNumber("value", 14052);
obj->addObject("sub")->addNumber("cost", 100);
obj->addNull("null example");
}
t1.stopAndPrint();
Timer t2("JSON save");
jf.save(FilePath("C:/Dev/Builds/base/out2.json"));
t2.stopAndPrint();
}
catch (const JsonException& ex)
{
cout << ex.what() << endl;
}
cout << std::flush;
} | 32.824324 | 106 | 0.515438 | StuffByDavid |
0a174cfa21c3f4ce6d344c80a5f79f8b13fc4911 | 2,179 | cpp | C++ | kernel/archive/vga_text_buffer.cpp | drali/danos | 874438cf8c3331baaa3e6250fbadcbeaf240d75e | [
"MIT"
] | null | null | null | kernel/archive/vga_text_buffer.cpp | drali/danos | 874438cf8c3331baaa3e6250fbadcbeaf240d75e | [
"MIT"
] | null | null | null | kernel/archive/vga_text_buffer.cpp | drali/danos | 874438cf8c3331baaa3e6250fbadcbeaf240d75e | [
"MIT"
] | null | null | null | #include "vga_text_buffer.h"
#include "kernel/io.h"
#include "core/types.h"
namespace danos {
VgaTextBuffer::VgaTextBuffer(const VgaColor background, const VgaColor foreground) {
this->Clear();
this->SetColors(background, foreground);
this->UpdateCursor();
}
void VgaTextBuffer::UpdateCursor() const {
const Uint16 pos = current_row_ * kVgaWidth + current_column_;
IO::Out(0x3D4, 0x0F);
IO::Out(0x3D5, (Uint8) (pos & 0xFF));
IO::Out(0x3D4, 0x0E);
IO::Out(0x3D5, (Uint8) ((pos >> 8) & 0xFF));
}
void VgaTextBuffer::SetColors(const VgaColor background, const VgaColor foreground) {
for (Uint32 height = 0; height < kVgaHeight; ++height) {
for (Uint32 width = 0; width < kVgaWidth; ++width) {
buffer_[height * kVgaWidth + width].color = (Uint8)((Uint8)background << 4) | ((Uint8)foreground & 0x0f);
}
}
}
void VgaTextBuffer::Clear() {
for (Uint32 height = 0; height < kVgaHeight; ++height) {
for (Uint32 width = 0; width < kVgaWidth; ++width) {
buffer_[height * kVgaWidth + width].value = ' ';
}
}
current_column_ = 0;
current_row_ = 0;
this->UpdateCursor();
}
void VgaTextBuffer::IncreaseRow() {
if ((current_row_ + 1) == kVgaHeight) {
for (Uint32 i = 0; i < (kVgaHeight - 1); ++i) {
for (Uint32 j = 0; j < kVgaWidth; ++j) {
buffer_[i * kVgaWidth + j] = buffer_[(i + 1) * kVgaWidth + j];
}
}
for (Uint32 i = 0; i < kVgaWidth; ++i) {
buffer_[(kVgaHeight - 1) * kVgaWidth + i].value = ' ';
}
} else {
current_row_++;
}
current_column_ = 0;
}
void VgaTextBuffer::Print(const Char value) {
if (value == '\n') {
this->IncreaseRow();
this->UpdateCursor();
return;
}
buffer_[current_row_ * kVgaWidth + current_column_].value = value;
current_column_++;
if (current_column_ == kVgaWidth) {
this->IncreaseRow();
}
this->UpdateCursor();
}
void VgaTextBuffer::Print(const Char* string) {
while (*string != '\0') {
this->Print(*string);
string++;
}
}
} // namespace danos
| 26.901235 | 117 | 0.57687 | drali |
0a1a92656c83521198200ea0471eb3cf9e33d76e | 15,622 | cpp | C++ | project/Harman_T500/testform.cpp | happyrabbit456/Qt5_dev | 1812df2f04d4b6d24eaf0195ae25d4c67d4f3da2 | [
"MIT"
] | null | null | null | project/Harman_T500/testform.cpp | happyrabbit456/Qt5_dev | 1812df2f04d4b6d24eaf0195ae25d4c67d4f3da2 | [
"MIT"
] | null | null | null | project/Harman_T500/testform.cpp | happyrabbit456/Qt5_dev | 1812df2f04d4b6d24eaf0195ae25d4c67d4f3da2 | [
"MIT"
] | null | null | null | #include "testform.h"
#include "ui_testform.h"
#include "mainwindow.h"
TestForm::TestForm(QWidget *parent) :
QWidget(parent),
ui(new Ui::TestForm)
{
ui->setupUi(this);
m_mapString.insert(1,tr("Please set the parameters, then click Test button, the test can begin to go. "));
resetTestHandle();
clearMessagebox();
appendMessagebox(m_mapString[1]);
}
TestForm::~TestForm()
{
delete ui;
}
bool TestForm::updateIdleCurrent(bool bOK, string str)
{
if(bOK){
double d=atof(str.c_str());
d=qAbs(d*1000*1000); //uA
QString qstr=QString().sprintf("%5.3f",qAbs(d));
ui->editIdleCurrent->setText(qstr);
m_idlecurrent=qstr;
if(d<m_dMinIdleCurrent || d>m_dMaxIdleCurrent){
m_idlecurrentpf="F";
ui->labelIdleCurrentStatus->setVisible(true);
ui->labelIdleCurrentStatus->setStyleSheet("color: rgb(255, 192, 128);background:red");
ui->labelIdleCurrentStatus->setText("Fail");
QString strValue=QString("The idle current value is %1 uA , threshold exceeded, the test fail.").arg(qstr);
appendMessagebox(strValue);
}
else{
m_idlecurrentpf="P";
ui->labelIdleCurrentStatus->setVisible(true);
ui->labelIdleCurrentStatus->setStyleSheet("color: rgb(255, 192, 128);background:green");
ui->labelIdleCurrentStatus->setText("Pass");
QString strValue=QString("The idle current value is %1 uA , the test pass.").arg(qstr);
appendMessagebox(strValue);
}
return true;
}
return false;
}
bool TestForm::updateWorkCurrent(bool bOK, string str)
{
if(bOK){
double d=atof(str.c_str());
d=qAbs(d*1000); //mA
QString qstr=QString().sprintf("%5.3f",qAbs(d));
ui->editWorkCurrent->setText(qstr);
m_workcurrent=qstr;
if(d<m_dMinWorkCurrent || d>m_dMaxWorkCurrent){
m_workcurrentpf="F";
ui->labelWorkCurrentStatus->setVisible(true);
ui->labelWorkCurrentStatus->setStyleSheet("color: rgb(255, 192, 128);background:red");
ui->labelWorkCurrentStatus->setText("Fail");
QString strValue=QString("The work current value is %1 mA , threshold exceeded, the test fail.").arg(qstr);
appendMessagebox(strValue);
}
else{
m_workcurrentpf="P";
ui->labelWorkCurrentStatus->setVisible(true);
ui->labelWorkCurrentStatus->setStyleSheet("color: rgb(255, 192, 128);background:green");
ui->labelWorkCurrentStatus->setText("Pass");
QString strValue=QString("The work current value is %1 mA , the test pass.").arg(qstr);
appendMessagebox(strValue);
}
return true;
}
return false;
}
bool TestForm::updateChargeCurrent(bool bOK, string str)
{
if(bOK){
double d=atof(str.c_str());
d=qAbs(d*1000); //mA
QString qstr=QString().sprintf("%5.3f",qAbs(d));
ui->editChargeCurrent->setText(qstr);
m_chargecurrent=qstr;
if(d<m_dMinChargeCurrent || d>m_dMaxChargeCurrent){
m_chargecurrentpf="F";
ui->labelChargeCurrentStatus->setVisible(true);
ui->labelChargeCurrentStatus->setStyleSheet("color: rgb(255, 192, 128);background:red");
ui->labelChargeCurrentStatus->setText("Fail");
QString strValue=QString("The charge current value is %1 mA , threshold exceeded, the test fail.").arg(qstr);
appendMessagebox(strValue);
}
else{
m_chargecurrentpf="P";
ui->labelChargeCurrentStatus->setVisible(true);
ui->labelChargeCurrentStatus->setStyleSheet("color: rgb(255, 192, 128);background:green");
ui->labelChargeCurrentStatus->setText("Pass");
QString strValue=QString("The charge current value is %1 mA , the test pass.").arg(qstr);
appendMessagebox(strValue);
}
//update result label
if(m_idlecurrentpf.compare("P")==0
&&m_workcurrentpf.compare("P")==0
&&m_chargecurrentpf.compare("P")==0){
m_pf="P";
ui->labelResultStatus->setVisible(true);
ui->labelResultStatus->setStyleSheet("color: rgb(255, 192, 128);background:green");
ui->labelResultStatus->setText("Pass");
}
else{
m_pf="F";
ui->labelResultStatus->setVisible(true);
ui->labelResultStatus->setStyleSheet("color: rgb(255, 192, 128);background:red");
ui->labelResultStatus->setText("Fail");
}
return true;
}
return false;
}
bool TestForm::insertRecordHandle()
{
QString strQuery;
bool ret=false;
MainWindow* pMainWindow=MainWindow::getMainWindow();
int nSupportDatabase =pMainWindow->getSupportDatabase();
if(pMainWindow!=nullptr && (nSupportDatabase==enum_SQLite||nSupportDatabase==enum_SQLite_MSSQL)){
if(pMainWindow->m_bSQLLiteConnection){
// QString strTIME="(select strftime('%Y/%m/%d %H:%M','now','localtime'))";
QDateTime z_curDateTime = QDateTime::currentDateTime();
QString strTIME = z_curDateTime.toString(tr("yyyy/MM/dd hh:mm"));
// strQuery = QString("%1 %2 '%3', '%4', '%5', '%6', '%7', '%8', '%9', '%10', '%11', '%12', '%13', '%14', '%15', '%16')")
strQuery = QString("%1 '%2', '%3', '%4', '%5', '%6', '%7', '%8', '%9', '%10', '%11', '%12', '%13', '%14', '%15', '%16')")
.arg("insert into currentrecord values(NULL,")
// .arg("(select strftime('%Y/%m/%d %H:%M','now','localtime')),")
.arg(strTIME)
.arg(m_sn)
.arg(m_idlecurrent)
.arg(m_idlecurrentpf)
.arg(m_workcurrent)
.arg(m_workcurrentpf)
.arg(m_chargecurrent)
.arg(m_chargecurrentpf)
.arg(QString().sprintf("%5.3f",m_dMinIdleCurrent))
.arg(QString().sprintf("%5.3f",m_dMaxIdleCurrent))
.arg(QString().sprintf("%5.3f",m_dMinWorkCurrent))
.arg(QString().sprintf("%5.3f",m_dMaxWorkCurrent))
.arg(QString().sprintf("%5.3f",m_dMinChargeCurrent))
.arg(QString().sprintf("%5.3f",m_dMaxChargeCurrent))
.arg(m_pf);
qDebug()<<strQuery;
bool bInsertRecord=pMainWindow->m_querySQLite.exec(strQuery);
if(!bInsertRecord){
qDebug() << pMainWindow->m_querySQLite.lastError();
QMessageBox::warning(this,"warning",pMainWindow->m_querySQLite.lastError().text());
}
else{
//直接写到文件
writeRecordToExcel(strTIME);
return true;
}
}
}
if(pMainWindow!=nullptr && (nSupportDatabase==enum_MSSQL||nSupportDatabase==enum_SQLite_MSSQL)){
if(pMainWindow->m_bMSSQLConnection){
QString strTIME="(select CONVERT(varchar(100) , getdate(), 111 )+' '+ Datename(hour,GetDate())+ ':'+Datename(minute,GetDate()))";
}
}
return ret;
}
bool TestForm::conclusionHandle()
{
// ui->tableView->setUpdatesEnabled(false);//暂停界面刷新
bool bInsert=insertRecordHandle();
if(bInsert){
appendMessagebox("The test record is success to insert database.");
QString str=QString().sprintf("The test record is success to save to local file. The dir path: %s .","D:\\database\\Harman_T500");
appendMessagebox(str);
emit updateDatabaseTabelView();
}
else{
appendMessagebox("The test record is fail to insert database and save to local file. ");
}
return bInsert;
}
bool TestForm::getCurrentTestConclusion(QString &idleDCStatus, QString &workDCStatus, QString &chargeDCStatus)
{
idleDCStatus=m_idlecurrentpf;
workDCStatus=m_workcurrentpf;
chargeDCStatus=m_chargecurrentpf;
return true;
}
void TestForm::writeOnewRecord(QXlsx::Document &xlsx,int rowCount,int columnCount, QString strTIME,QVariant newIDValue)
{
int i=rowCount;
for(int j=1;j<=columnCount;j++){
switch (j) {
case 1:
xlsx.write(i + 1, j,newIDValue);
break;
case 2:
xlsx.write(i + 1, j,strTIME);
break;
case 3:
xlsx.write(i + 1, j,m_sn);
break;
case 4:
xlsx.write(i + 1, j,m_idlecurrent);
break;
case 5:
xlsx.write(i + 1, j,m_idlecurrentpf);
break;
case 6:
xlsx.write(i + 1, j,m_workcurrent);
break;
case 7:
xlsx.write(i + 1, j,m_workcurrentpf);
break;
case 8:
xlsx.write(i + 1, j,m_chargecurrent);
break;
case 9:
xlsx.write(i + 1, j,m_chargecurrentpf);
break;
case 10:
xlsx.write(i + 1, j,QString().sprintf("%5.3f",m_dMinIdleCurrent));
break;
case 11:
xlsx.write(i + 1, j,QString().sprintf("%5.3f",m_dMaxIdleCurrent));
break;
case 12:
xlsx.write(i + 1, j,QString().sprintf("%5.3f",m_dMinWorkCurrent));
break;
case 13:
xlsx.write(i + 1, j,QString().sprintf("%5.3f",m_dMaxWorkCurrent));
break;
case 14:
xlsx.write(i + 1, j,QString().sprintf("%5.3f",m_dMinChargeCurrent));
break;
case 15:
xlsx.write(i + 1, j,QString().sprintf("%5.3f",m_dMaxChargeCurrent));
break;
case 16:
xlsx.write(i + 1, j,m_pf);
break;
}
}
}
void TestForm::appendMessagebox(QString str)
{
ui->editMessagebox->appendPlainText(str);
}
void TestForm::clearMessagebox()
{
ui->editMessagebox->clear();
}
void TestForm::writeRecordToExcel(QString strTIME)
{
//直接写到文件
QString strDatabaseDir=QString().sprintf("%s","D:\\database\\Harman_T500");
QDateTime z_curDateTime = QDateTime::currentDateTime();
QString z_strCurTime = z_curDateTime.toString(tr("yyyyMMdd"));
QString fileName = strDatabaseDir+"\\"+QString("dc") + "_" + z_strCurTime + tr(".xlsx");
qDebug()<<"fileName:"<<fileName;
QDir dir(strDatabaseDir);
if(!dir.exists()){
bool ok = dir.mkpath(strDatabaseDir);//创建多级目录
qDebug()<<"dir.mkpath(strDatabaseDir) ok:"<<ok;
}
qDebug()<<"dir.exists() true";
QFile file(fileName);
if(file.exists())
{
qDebug()<<"file.exists() true";
//存在文件
QXlsx::Document xlsx(fileName); //OK
QXlsx::Workbook *workBook = xlsx.workbook();
QXlsx::Worksheet *workSheet = static_cast<QXlsx::Worksheet*>(workBook->sheet(0));
qDebug()<<"rowCount:"<<workSheet->dimension().rowCount();
qDebug()<<"columnCount:"<<workSheet->dimension().columnCount();
int rowCount=workSheet->dimension().rowCount();
int columnCount=workSheet->dimension().columnCount();
QVariant lastid= xlsx.read(rowCount,1);
int newid=lastid.toInt()+1;
QVariant newIDValue(newid);
writeOnewRecord(xlsx,rowCount,columnCount, strTIME,newIDValue);
xlsx.save();
}
else{
//不存在文件
QXlsx::Document z_xlsx;
QStringList z_titleList;
QXlsx::Format format1;/*设置该单元的样式*/
format1.setFontColor(QColor(Qt::blue));/*文字为红色*/
// format1.setPatternBackgroundColor(QColor(152,251,152));/*北京颜色*/
format1.setFontSize(15);/*设置字体大小*/
format1.setHorizontalAlignment(QXlsx::Format::AlignHCenter);/*横向居中*/
format1.setBorderStyle(QXlsx::Format::BorderThin);//QXlsx::Format::BorderDashDotDot);/*边框样式*/
// 设置excel任务标题
z_titleList << "id" << "time" << "sn" << "idlecurrent"<<"idlecurrentpf"
<<"workcurrent"<<"workcurrentpf"<<"chargecurrent"<< "chargecurrentpf"
<< "idlemincurrent"<<"idlemaxcurrent"<<"workmincurrent"<<"workmaxcurrent"
<<"chargemincurrent"<<"chargemaxcurrent"<<"pf";
for (int i = 0; i < z_titleList.size(); i++)
{
// z_xlsx.write(1, i+1, z_titleList.at(i));
z_xlsx.write(1, i+1, z_titleList.at(i),format1);
}
// 设置烈宽
for(int i=1;i<17;i++){
if(i==2 || i==3){
z_xlsx.setColumnWidth(i, 30);
}
else{
z_xlsx.setColumnWidth(i, 30);
}
}
int rowCount=2;
int columnCount=16;
int newid=1;
QVariant newIDValue(newid);
writeOnewRecord(z_xlsx,rowCount,columnCount, strTIME,newIDValue);
// 保存文件
z_xlsx.saveAs(fileName);
}
}
void TestForm::resetTestHandle()
{
ui->labelIdleCurrentStatus->setVisible(false);
ui->labelWorkCurrentStatus->setVisible(false);
ui->labelChargeCurrentStatus->setVisible(false);
ui->editIdleCurrent->setText("0.000");
ui->editWorkCurrent->setText("0.000");
ui->editChargeCurrent->setText("0.000");
ui->labelResultStatus->setVisible(false);
}
void TestForm::on_btnReset_clicked()
{
resetTestHandle();
clearMessagebox();
appendMessagebox(m_mapString[1]);
#ifdef USE_WIZARD
if(m_wizard!=nullptr){
if(m_wizard->currentId()>-1){
m_wizard->setVisible(false);
m_wizard->close();
}
}
#endif
}
void TestForm::on_btnTest_clicked()
{
resetTestHandle();
MainWindow *pMainWindow=MainWindow::getMainWindow();
if(pMainWindow->m_niVisaGPIB.m_mapGPIB.count()<=0){
QMessageBox::warning(nullptr,"warning","Could not open a session to the VISA Resource Manager!\n");
return;
}
#ifdef USE_WIZARD
m_wizard=new QWizard(this);
m_wizard->addPage(new SNPage(this));
m_wizard->addPage(new IdleCurrentPage(this));
m_wizard->addPage(new WorkCurrentPage(this));
m_wizard->addPage(new ChargeCurrentPage(this));
m_wizard->addPage(new ConclusionPage(this));
//设置导航样式
m_wizard->setWizardStyle( QWizard::ModernStyle );
//去掉向导页面按钮
m_wizard->setOption( QWizard::NoBackButtonOnStartPage );
m_wizard->setOption( QWizard::NoBackButtonOnLastPage );
m_wizard->setOption( QWizard::NoCancelButton );
//去掉BackButton
QList<QWizard::WizardButton> layout;
layout << QWizard::Stretch // << QWizard::BackButton << QWizard::CancelButton
<< QWizard::NextButton << QWizard::FinishButton;
m_wizard->setButtonLayout(layout);
m_wizard->resize(320,160);
QPoint pos=pMainWindow->pos();
QSize size=pMainWindow->size();
pos.setX(pos.x()+size.width()+5);
pos.setY(pos.y());
m_wizard->move(pos);
//禁用/隐藏/删除Qt对话框“标题栏”上的“?”帮助按钮这些按钮!
Qt::WindowFlags flags = m_wizard->windowFlags();
Qt::WindowFlags helpFlag =
Qt::WindowContextHelpButtonHint;
flags = flags & (~helpFlag);
m_wizard->setWindowFlags(flags);
m_wizard->setWindowTitle(QString::fromLocal8Bit("电流测试向导"));
m_wizard->show();
#else
m_snDlg=new SNDialog(this);
//禁用/隐藏/删除Qt对话框“标题栏”上的“?”帮助按钮这些按钮!
Qt::WindowFlags flags = m_snDlg->windowFlags();
Qt::WindowFlags helpFlag =
Qt::WindowContextHelpButtonHint;
flags = flags & (~helpFlag);
m_snDlg->setWindowFlags(flags);
m_snDlg->setWindowTitle("Get scan code");
m_snDlg->show();
#endif
}
| 32.545833 | 144 | 0.588657 | happyrabbit456 |
0a1acd486ffe2573706c39d2cc80b8c72acee621 | 307 | cpp | C++ | examples/example1.cpp | Lallapallooza/YACL | 4f2d56b5aef835e3da9aacf018e63f1a41316df7 | [
"MIT"
] | 11 | 2018-08-19T00:07:12.000Z | 2021-01-08T05:28:11.000Z | examples/example1.cpp | Lallapallooza/YACL | 4f2d56b5aef835e3da9aacf018e63f1a41316df7 | [
"MIT"
] | null | null | null | examples/example1.cpp | Lallapallooza/YACL | 4f2d56b5aef835e3da9aacf018e63f1a41316df7 | [
"MIT"
] | 2 | 2018-08-19T08:01:33.000Z | 2018-08-22T15:50:18.000Z | #include <iostream>
#include <YACL/config.h>
// CONFIG_PATH setted in CMakeLists.txt
const std::string config_path = CONFIG_PATH;
int main() {
const yacl::SettingsUniquePtr root =
yacl::Config::parseConfigFromFile(config_path + "/example.yacl");
yacl::Config::printConfig(*root);
return 0;
}
| 19.1875 | 69 | 0.71987 | Lallapallooza |
0a1f81157651a74e62edf4e74d91cc04a20d0d72 | 2,872 | cpp | C++ | test/core/test_read_integrator.cpp | yutakasi634/Mjolnir | ab7a29a47f994111e8b889311c44487463f02116 | [
"MIT"
] | 12 | 2017-02-01T08:28:38.000Z | 2018-08-25T15:47:51.000Z | test/core/test_read_integrator.cpp | Mjolnir-MD/Mjolnir | 043df4080720837042c6b67a5495ecae198bc2b3 | [
"MIT"
] | 60 | 2019-01-14T08:11:33.000Z | 2021-07-29T08:26:36.000Z | test/core/test_read_integrator.cpp | yutakasi634/Mjolnir | ab7a29a47f994111e8b889311c44487463f02116 | [
"MIT"
] | 8 | 2019-01-13T11:03:31.000Z | 2021-08-01T11:38:00.000Z | #define BOOST_TEST_MODULE "test_read_integrator"
#ifdef BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#else
#include <boost/test/included/unit_test.hpp>
#endif
#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/input/read_integrator.hpp>
BOOST_AUTO_TEST_CASE(read_velocity_verlet_integrator)
{
mjolnir::LoggerManager::set_default_logger("test_read_integrator.log");
using real_type = double;
using traits_type = mjolnir::SimulatorTraits<real_type, mjolnir::UnlimitedBoundary>;
constexpr real_type tol = 1e-8;
{
using namespace toml::literals;
const auto v = u8R"(
delta_t = 0.1
)"_toml;
const auto integr = mjolnir::read_velocity_verlet_integrator<traits_type>(v);
BOOST_TEST(integr.delta_t() == 0.1, boost::test_tools::tolerance(tol));
}
}
BOOST_AUTO_TEST_CASE(read_underdamped_langevin_integrator)
{
mjolnir::LoggerManager::set_default_logger("test_read_integrator.log");
using real_type = double;
using traits_type = mjolnir::SimulatorTraits<real_type, mjolnir::UnlimitedBoundary>;
constexpr real_type tol = 1e-8;
{
using namespace toml::literals;
const auto v = u8R"(
delta_t = 0.1
integrator.seed = 1234
integrator.parameters = [
{index = 0, gamma = 0.1},
{index = 1, gamma = 0.2},
]
)"_toml;
const auto integr = mjolnir::read_underdamped_langevin_integrator<traits_type>(v);
BOOST_TEST(integr.delta_t() == 0.1, boost::test_tools::tolerance(tol));
BOOST_TEST(integr.parameters().size() == 2u);
BOOST_TEST(integr.parameters().at(0) == 0.1, boost::test_tools::tolerance(tol));
BOOST_TEST(integr.parameters().at(1) == 0.2, boost::test_tools::tolerance(tol));
}
}
BOOST_AUTO_TEST_CASE(read_BAOAB_langevin_integrator)
{
mjolnir::LoggerManager::set_default_logger("test_read_integrator.log");
using real_type = double;
using traits_type = mjolnir::SimulatorTraits<real_type, mjolnir::UnlimitedBoundary>;
constexpr real_type tol = 1e-8;
{
using namespace toml::literals;
const auto v = u8R"(
delta_t = 0.1
integrator.seed = 1234
integrator.parameters = [
{index = 0, gamma = 0.1},
{index = 1, gamma = 0.2},
]
)"_toml;
const auto integr = mjolnir::read_underdamped_langevin_integrator<traits_type>(v);
BOOST_TEST(integr.delta_t() == 0.1, boost::test_tools::tolerance(tol));
BOOST_TEST(integr.parameters().size() == 2u);
BOOST_TEST(integr.parameters().at(0) == 0.1, boost::test_tools::tolerance(tol));
BOOST_TEST(integr.parameters().at(1) == 0.2, boost::test_tools::tolerance(tol));
}
}
| 35.45679 | 90 | 0.654596 | yutakasi634 |
0a23228e4cbe1410a64afc44bf67c9fddb7a7b97 | 5,364 | hpp | C++ | ProMini_Slave/include/ArduinoNano_Iic.hpp | RafaelReyesCarmona/DucoCluster | 755fa6ab57129afdc65050514e654660a6b9e8eb | [
"MIT"
] | null | null | null | ProMini_Slave/include/ArduinoNano_Iic.hpp | RafaelReyesCarmona/DucoCluster | 755fa6ab57129afdc65050514e654660a6b9e8eb | [
"MIT"
] | null | null | null | ProMini_Slave/include/ArduinoNano_Iic.hpp | RafaelReyesCarmona/DucoCluster | 755fa6ab57129afdc65050514e654660a6b9e8eb | [
"MIT"
] | null | null | null | /*
* Project: DuinoCoinRig
* File: ArduinoNano_Iic
* Version: 0.2
* Purpose: Communication with the master
* Author: Frank Niggemann
*/
/***********************************************************************************************************************
* Code Iic
**********************************************************************************************************************/
void iicSetup() {
pinMode(PIN_IIC_SDA, INPUT_PULLUP);
pinMode(PIN_IIC_SCL, INPUT_PULLUP);
Wire.begin();
for (int id=IIC_ID_MIN; id<IIC_ID_MAX; id++) {
Wire.beginTransmission(id);
int result = Wire.endTransmission();
if (result != 0) {
iic_id = id;
break;
}
}
Wire.end();
logMessage("Address ID: "+String(iic_id));
Wire.begin(iic_id);
Wire.onReceive(iicHandlerReceive);
Wire.onRequest(iicHandlerRequest);
ducoId = getDucoId();
logMessage("DUCO ID: "+ducoId);
ledBlink(PIN_LED_ADDRESS, 250, 250);
ledBlink(PIN_LED_ADDRESS, 250, 250);
setState(SLAVE_STATE_FREE);
}
void iicHandlerReceive(int numBytes) {
if (numBytes == 0)
{
return;
}
while (Wire.available()) {
char c = Wire.read();
bufferReceive.write(c);
}
}
void iicHandlerRequest() {
char c = '\n';
if (bufferRequest.available() > 0 && bufferRequest.indexOf('\n') != -1) {
c = bufferRequest.read();
}
Wire.write(c);
}
void iicWorker() {
if (bufferReceive.available() > 0 && bufferReceive.indexOf('\n') != -1) {
setState(SLAVE_STATE_WORKING);
logMessage("Request: "+String(bufferReceive));
String lastblockhash = bufferReceive.readStringUntil(',');
String newblockhash = bufferReceive.readStringUntil(',');
unsigned int difficulty = bufferReceive.readStringUntil('\n').toInt();
unsigned long startTime = micros();
unsigned int ducos1result = 0;
if (difficulty < 655) ducos1result = Ducos1a.work(lastblockhash, newblockhash, difficulty);
unsigned long endTime = micros();
unsigned long elapsedTime = endTime - startTime;
while (bufferRequest.available()) bufferRequest.read();
bufferRequest.print(String(ducos1result) + "," + String(elapsedTime) + "," + ducoId + "\n");
setState(SLAVE_STATE_FREE);
logMessage("Result: "+String(ducos1result) + "," + String(elapsedTime) + "," + ducoId);
}
}
/*
byte iic_id = 0;
StreamString bufferReceive;
String stringReceive = "";
StreamString bufferRequest;
String stringRequest = "";
String lastBlockHash = "";
String nextBlockHash = "";
unsigned int ducos1aResult = 0;
unsigned long microtimeStart = 0;
unsigned long microtimeEnd = 0;
unsigned long microtimeDifference = 0;
String ducoId = "";
void iicSetup() {
pinMode(WIRE_SDA, INPUT_PULLUP);
pinMode(WIRE_SCL, INPUT_PULLUP);
Wire.begin();
for (int id=IIC_ID_MIN; id<IIC_ID_MAX; id++) {
Wire.beginTransmission(id);
int result = Wire.endTransmission();
if (result != 0) {
iic_id = id;
break;
}
}
Wire.end();
logMessage("Use ID: "+String(iic_id));
Wire.begin(iic_id);
Wire.onReceive(iicHandlerReceive);
Wire.onRequest(iicHandlerRequest);
ducoId = getDucoId();
ledBlink(PIN_LED_ADDRESS, 250, 250);
ledBlink(PIN_LED_ADDRESS, 250, 250);
setState(SLAVE_STATE_FREE);
}
void iicHandlerReceive(int numBytes) {
if (numBytes != 0) {
while (Wire.available()) {
char c = Wire.read();
bufferReceive.write(c);
ledBlink(PIN_LED_ADDRESS, 100, 100);
}
}
}
void iicEvaluateBufferReceive() {
if (bufferReceive.available() > 0 && bufferReceive.indexOf('\n') != -1) {
if (bufferReceive.length() < 10) {
} else {
lastBlockHash = bufferReceive.readStringUntil(',');
nextBlockHash = bufferReceive.readStringUntil(',');
unsigned int difficulty = bufferReceive.readStringUntil('\n').toInt();
logMessage("Receive lastBlockHash: "+lastBlockHash);
logMessage("Receive nextBlockHash: "+nextBlockHash);
logMessage("Receive difficulty: "+String(difficulty));
if (lastBlockHash!="" && nextBlockHash!="") {
setState(SLAVE_STATE_WORKING);
digitalWrite(PIN_LED_WORKING, HIGH);
microtimeStart = micros();
ducos1aResult = 0;
if (difficulty < 655){
ducos1aResult = Ducos1a.work(lastBlockHash, nextBlockHash, difficulty);
}
logMessage("Calculated result: "+String(ducos1aResult));
microtimeEnd = micros();
microtimeDifference = microtimeEnd - microtimeStart;
setState(SLAVE_STATE_READY);
digitalWrite(PIN_LED_READY, HIGH);
delay(100);
iicSetBufferRequestStringJobResult();
} else {
setState(SLAVE_STATE_ERROR);
logMessage("ERROR");
}
}
}
}
void iicHandlerRequest() {
char c = '\n';
if (bufferRequest.available() > 0 && bufferRequest.indexOf('\n') != -1) {
c = bufferRequest.read();
}
Wire.write(c);
if (slaveState == SLAVE_STATE_RESULT_READY && bufferRequest.available() == 0) {
setState(SLAVE_STATE_RESULT_SENT);
}
}
void iicSetBufferRequestStringEmpty() {
String request = "";
}
void iicSetBufferRequestStringJobResult() {
while (bufferRequest.available()) bufferRequest.read();
String request = String(ducos1aResult)+":"+String(microtimeDifference)+":"+ducoId+"\n";
logMessage(request);
bufferRequest.print(request);
setState(SLAVE_STATE_RESULT_SENT);
}
*/
| 28.531915 | 120 | 0.634787 | RafaelReyesCarmona |
0a2426fc10dd21a7083989c1545325e579e1a868 | 153 | cpp | C++ | src/La Trop/map/map.cpp | branchwelder/SoftSysHedonisticHibiscus | c6c652191bb10fcbf2e6f990de84fa9a9211f459 | [
"MIT"
] | null | null | null | src/La Trop/map/map.cpp | branchwelder/SoftSysHedonisticHibiscus | c6c652191bb10fcbf2e6f990de84fa9a9211f459 | [
"MIT"
] | 2 | 2020-07-17T20:01:46.000Z | 2020-07-17T20:01:54.000Z | src/La Trop/map/map.cpp | branchwelder/SoftSysHedonisticHibiscus | c6c652191bb10fcbf2e6f990de84fa9a9211f459 | [
"MIT"
] | null | null | null | //
// map.cpp
// La Trop
//
// Created by Sam Myers on 4/24/17.
// Copyright © 2017 Hedonistic Hibiscus. All rights reserved.
//
#include "map.hpp"
| 15.3 | 62 | 0.633987 | branchwelder |
0a251785a9c469357a6cd7c1c93f59e78f6e22d1 | 243 | hpp | C++ | TemplateRPG/Items/special/other_items.hpp | davideberdin/Text-Turn-based-RPG-Template | 3b1e88b6498b7473b3928e7188157a7d7f1ba844 | [
"MIT"
] | 1 | 2015-11-29T04:47:29.000Z | 2015-11-29T04:47:29.000Z | TemplateRPG/Items/special/other_items.hpp | davideberdin/Text-Turn-based-RPG-Template | 3b1e88b6498b7473b3928e7188157a7d7f1ba844 | [
"MIT"
] | null | null | null | TemplateRPG/Items/special/other_items.hpp | davideberdin/Text-Turn-based-RPG-Template | 3b1e88b6498b7473b3928e7188157a7d7f1ba844 | [
"MIT"
] | null | null | null | //
// other_items.hpp
// TemplateRPG
//
// Created by Davide Berdin on 28/11/15.
// Copyright © 2015 Davide Berdin. All rights reserved.
//
#ifndef other_items_hpp
#define other_items_hpp
#include <stdio.h>
#endif /* other_items_hpp */
| 16.2 | 56 | 0.703704 | davideberdin |
0a2da9b4c2cc96a78f94d4e4b641a652457f26c5 | 8,737 | cpp | C++ | src/raytracer/misc/Computations.cpp | extramask93/RayTracer | ba7f46fb212971e47b296991a7a7e981fef50dda | [
"Unlicense"
] | null | null | null | src/raytracer/misc/Computations.cpp | extramask93/RayTracer | ba7f46fb212971e47b296991a7a7e981fef50dda | [
"Unlicense"
] | null | null | null | src/raytracer/misc/Computations.cpp | extramask93/RayTracer | ba7f46fb212971e47b296991a7a7e981fef50dda | [
"Unlicense"
] | null | null | null | //
// Created by damian on 10.07.2020.
//
#include "Computations.h"
#include <intersections/Intersections.h>
#include <thread>
#include <iostream>
#include <misc/Shader.h>
namespace rt {
Computations prepareComputations(const Intersection &i, const Ray &ray,const rt::Intersections &intersections){
(void)intersections;
Computations comp;
comp.t = i.t();
comp.object = i.object();
comp.point = ray.position(comp.t);
comp.eyev = -ray.direction();
comp.normalv = comp.object->normalAt(comp.point,
intersections.size() > 0 ? intersections.front() : rt::Intersection(0, nullptr));
comp.inside = false;
if(comp.normalv.dot(comp.eyev) < 0) {
comp.inside = true;
comp.normalv = -comp.normalv;
}
comp.reflectv = ray.direction().reflect(comp.normalv);
comp.overPoint = comp.point + comp.normalv*EPSILON;
comp.underPoint = comp.point - comp.normalv*EPSILON;
/*refraction logic*/
if(intersections.size() > 0 ) {
std::vector<const Shape *> containers;
for (const auto &ii : intersections) {
if (ii == i) {
if (containers.empty()) {
comp.n1 = 1.0;
} else {
comp.n1 = containers.back()->material().refractionIndex();
}
}
auto obj = std::find_if(containers.begin(), containers.end(), [&](const auto &o) { return o == i.object(); });
if (obj != containers.end()) {
containers.erase(obj);
} else {
containers.push_back(ii.object());
}
if (ii == i) {
if (containers.empty()) {
comp.n2 = 1.0;
} else {
comp.n2 = containers.back()->material().refractionIndex();
}
}
}
}
/******************/
return comp;
}
util::Color colorAt(const World &world, const Ray &ray, short callsLeft)
{
auto result = util::Color::BLACK;
auto intersections = world.intersect(ray);
if(intersections.hit().has_value()) {
auto comps = prepareComputations(intersections.hit().value(), ray, intersections);
result = result + rt::Shader::shadeHit(world, comps, callsLeft);
}
return result; //util::Color::BLACK;
}
/*Phong reflection model*/
util::Color lighting(const rt::Material &material,const rt::Shape &object, const rt::PointLight &light,
const util::Tuple &position, const util::Tuple &eye, const util::Tuple &normal, bool inShadow)
{
auto effectiveColor = material.color() * light.intensity();
if(material.pattern() != nullptr) {
effectiveColor = rt::patternAtObject(*material.pattern(), object, position);
}
//ambient is const
util::Color ambient = effectiveColor * material.ambient();
if(inShadow) {
return ambient;
}
auto lightVector = (light.position() - position).normalize();
auto light_dot_normal = lightVector.dot(normal);//cos(theta)
util::Color diffuse(0, 0, 0);
util::Color specular(0, 0, 0);
if (light_dot_normal < 0) {
diffuse = util::Color::BLACK;
specular = util::Color::BLACK;
} else {
diffuse = effectiveColor * material.diffuse() * light_dot_normal;
auto reflectVector = (-lightVector).reflect(normal);
auto reflect_dot_eye = reflectVector.dot(eye);
if (reflect_dot_eye <= 0) {
specular = util::Color::BLACK;
} else {
auto factor = std::pow(reflect_dot_eye, material.shininess());
specular = effectiveColor * material.specular() * factor;
}
}
return ambient + diffuse + specular;
}
util::Matrixd viewTransformation(const util::Tuple &from, const util::Tuple &to, const util::Tuple &up)
{
auto forwardv = (to - from).normalize();
auto upn = up.normalization();
auto leftv = forwardv.cross(upn);
auto trueupv = leftv.cross(forwardv);
auto orientationm = util::Matrixd(4,4);
//TODO research where it comes from, scratchpixel.com
orientationm << leftv.x(), leftv.y(), leftv.z(), 0,
trueupv.x(), trueupv.y(), trueupv.z(),0,
-forwardv.x(), -forwardv.y(), -forwardv.z(),0,
0,0,0,1;
return orientationm*util::Matrixd::translation(-from.x(), -from.y(), -from.z());
}
rt::Ray rayForPixel(const Camera &c, unsigned int px, unsigned int py)
{
double xoffset = (px + 0.5) * c.pixelSize();
double yoffset = (py + 0.5) * c.pixelSize();
double worldx = c.halfWidth() - xoffset;
double worldy = c.halfHeight() -yoffset;
auto pixel = c.transform().inverse() * util::Tuple::point(worldx,worldy,-1);
auto origin = c.transform().inverse()*util::Tuple::point(0,0,0);
auto direction = (pixel-origin).normalize();
return rt::Ray(origin, direction);
}
void renderSome(const unsigned from, const unsigned to,const Camera &c,
const World &world, util::Canvas &canvas) {
for(unsigned y = from; y < to; y++) {
for(unsigned x = 0; x < c.hsize(); x++) {
auto ray = rayForPixel(c,x,y);
auto color = rt::colorAt(world,ray);
canvas(x,y) = color;
}
}
}
util::Canvas render(const Camera &c, const World &world)
{
auto canvas = util::Canvas(c.hsize(),c.vsize());
const auto n = std::thread::hardware_concurrency();
std::vector<std::thread> threads;
const auto step = c.vsize() / n;
unsigned current =0;
for(unsigned i = 0; i < n; i++) {
threads.push_back(std::thread(renderSome,current, i == n-1? c.vsize(): current+step,std::ref(c),std::ref(world),
std::ref(canvas)));
current += step;
}
for(auto &thread: threads) {
thread.join();
}
return canvas;
}
bool isShadowed(const World &world, const util::Tuple &point)
{
(void)world;
(void)point;
auto direction = world.lights()[0].get()->position() - point;
auto distance = direction.magnitude();
auto ray = rt::Ray(point,direction.normalization());
auto intersection = world.intersect(ray);
if(intersection.hit().has_value() && intersection.hit()->t() < distance) {
return true;
}
return false;
}
util::Color patternAtObject(const Pattern &pattern, const Shape &shape, const util::Tuple &point)
{
auto pointInObjectSpace = shape.worldToObject(point);//shape.transform().inverse()* point;
auto pointInPatternSpace = pattern.transform().inverse() * pointInObjectSpace;
return pattern.patternAt(pointInPatternSpace);
}
util::Color reflectedColor(const World &world, const Computations &comps, short callsLeft)
{
if(comps.object->material().reflective() ==0 || callsLeft < 1) {
return util::Color(0,0,0);
}
auto reflectedRay = rt::Ray(comps.overPoint, comps.reflectv);
auto newColor = rt::colorAt(world,reflectedRay,callsLeft-1);
return newColor * comps.object->material().reflective();
}
util::Color refractedColor(const World &world, const Computations &comps, short callsLeft)
{
auto transparency = comps.object->material().transparency();
if(equal(transparency,0.0) || callsLeft < 1){
return util::Color(0,0,0);
}
/*from the definition of Snell's Law*/
auto ratio = comps.n1 / comps.n2;
auto cosi = comps.eyev.dot(comps.normalv);
auto sin2t = std::pow(ratio,2) * (1-std::pow(cosi,2));
if(sin2t > 1.0) { // critical angle of 90 deg, so we need sint > 1
return util::Color(0,0,0);
}
auto cos_t = sqrt(1.0-sin2t);
auto d = ratio*cosi- cos_t;
auto normal = comps.normalv *d;
auto eyeVector = comps.eyev *ratio;
auto direction = normal-eyeVector;
auto refractRay = rt::Ray(comps.underPoint,direction);
auto color = rt::colorAt(world,refractRay,callsLeft-1) * comps.object->material().transparency();
return color;
}
double schlick(const Computations &comps)
{
auto c = comps.eyev.dot(comps.normalv);
if(comps.n1 > comps.n2) {
auto n = comps.n1/comps.n2;
auto sin2t = pow(n,2) * (1.0-pow(c,2));
if(sin2t > 1.0) {
return 1.0;
}
auto cost = sqrt(1.0-sin2t);
c = cost;
}
auto r0 = pow((comps.n1 - comps.n2) / (comps.n1 + comps.n2),2);
return r0 + (1.0-r0) * pow(1.0-c,5);
}
bool equal(double x, double y)
{
return std::fabs(x-y) < std::numeric_limits<double>::epsilon()*EPSILON;
}
std::pair<double, double> spherical_map(const util::Tuple &point)
{
auto theta = std::atan2(point.x(),point.z());
auto vec = util::Tuple::vector(point.x(),point.y(),point.z());
auto radius = vec.magnitude();
auto phi = acos(point.y() / radius);
auto raw_u = theta / (2*math::pi<>);
auto u = 1 - (raw_u + 0.5);
auto v = 1 - phi / math::pi<>;
return std::pair<double, double>(u,v);
}
std::pair<double, double> planar_map(const util::Tuple &point)
{
double u = point.x() - floor(point.x());
double v = point.z() - floor(point.z());
return std::make_pair(u,v);
}
std::pair<double, double> cylindrical_map(const util::Tuple &point)
{
auto theta = std::atan2(point.x(), point.z());
auto rawU = theta / (2*math::pi<>);
auto u = 1 - (rawU + 0.5);
auto v = point.y() - floor(point.y());
return std::make_pair(u,v);
}
}
| 33.996109 | 119 | 0.643241 | extramask93 |
0a2e17982d67e6ab4bd9078d49fc7f981caa8c63 | 2,753 | cxx | C++ | vtk/8.1.0/src/ThirdParty/vtkm/vtk-m/vtkm/cont/testing/UnitTestRuntimeDeviceInformation.cxx | Fresher-Chen/tarsim | 9d2ec1001ee82ca11325e4b1edb8f2843e36518b | [
"Apache-2.0"
] | 1 | 2020-03-02T17:31:48.000Z | 2020-03-02T17:31:48.000Z | vtk/8.1.0/src/ThirdParty/vtkm/vtk-m/vtkm/cont/testing/UnitTestRuntimeDeviceInformation.cxx | Fresher-Chen/tarsim | 9d2ec1001ee82ca11325e4b1edb8f2843e36518b | [
"Apache-2.0"
] | 1 | 2019-06-03T17:04:59.000Z | 2019-06-05T15:13:28.000Z | ThirdParty/vtkm/vtk-m/vtkm/cont/testing/UnitTestRuntimeDeviceInformation.cxx | metux/vtk8 | 77f907913f20295e1eacdb3aba9ed72e2b3ae917 | [
"BSD-3-Clause"
] | 1 | 2020-07-20T06:43:49.000Z | 2020-07-20T06:43:49.000Z | //============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#include <vtkm/cont/RuntimeDeviceInformation.h>
//include all backends
#include <vtkm/cont/cuda/DeviceAdapterCuda.h>
#include <vtkm/cont/serial/DeviceAdapterSerial.h>
#include <vtkm/cont/tbb/DeviceAdapterTBB.h>
#include <vtkm/cont/testing/Testing.h>
namespace
{
template <bool>
struct DoesExist;
template <typename DeviceAdapterTag>
void detect_if_exists(DeviceAdapterTag tag)
{
using DeviceAdapterTraits = vtkm::cont::DeviceAdapterTraits<DeviceAdapterTag>;
DoesExist<DeviceAdapterTraits::Valid>::Exist(tag);
}
template <>
struct DoesExist<false>
{
template <typename DeviceAdapterTag>
static void Exist(DeviceAdapterTag)
{
//runtime information for this device should return false
vtkm::cont::RuntimeDeviceInformation<DeviceAdapterTag> runtime;
VTKM_TEST_ASSERT(runtime.Exists() == false,
"A backend with zero compile time support, can't have runtime support");
}
};
template <>
struct DoesExist<true>
{
template <typename DeviceAdapterTag>
static void Exist(DeviceAdapterTag)
{
//runtime information for this device should return true
vtkm::cont::RuntimeDeviceInformation<DeviceAdapterTag> runtime;
VTKM_TEST_ASSERT(runtime.Exists() == true,
"A backend with compile time support, should have runtime support");
}
};
void Detection()
{
using SerialTag = ::vtkm::cont::DeviceAdapterTagSerial;
using TBBTag = ::vtkm::cont::DeviceAdapterTagTBB;
using CudaTag = ::vtkm::cont::DeviceAdapterTagCuda;
//Verify that for each device adapter we compile code for, that it
//has valid runtime support.
detect_if_exists(CudaTag());
detect_if_exists(TBBTag());
detect_if_exists(SerialTag());
}
} // anonymous namespace
int UnitTestRuntimeDeviceInformation(int, char* [])
{
return vtkm::cont::testing::Testing::Run(Detection);
}
| 31.284091 | 93 | 0.6996 | Fresher-Chen |
0a432c95eaa8f35a40257072c7e15d9a4f7280d2 | 808 | hpp | C++ | lib/world/map.hpp | julienlopez/QCityBuilder | fe61a56bcdeda301211d49a9e358258eefafa14c | [
"MIT"
] | 1 | 2019-03-19T03:14:22.000Z | 2019-03-19T03:14:22.000Z | lib/world/map.hpp | julienlopez/QCityBuilder | fe61a56bcdeda301211d49a9e358258eefafa14c | [
"MIT"
] | 11 | 2015-01-27T17:35:12.000Z | 2018-08-13T07:48:35.000Z | lib/world/map.hpp | julienlopez/QCityBuilder | fe61a56bcdeda301211d49a9e358258eefafa14c | [
"MIT"
] | null | null | null | #ifndef MAP_HPP
#define MAP_HPP
#include "namespace_world.hpp"
#include <utils/array2d.hpp>
#include <utils/rect.hpp>
BEGIN_NAMESPACE_WORLD
class Map
{
public:
enum class SquareType : unsigned char
{
Empty = 0,
Building,
Road
};
using square_container_t = std::vector<utils::PointU>;
Map(utils::SizeU size_);
std::size_t width() const;
std::size_t height() const;
const utils::SizeU& size() const;
bool squareIsEmpty(const utils::PointU& p) const;
void placeBuilding(const utils::RectU& r);
SquareType squareType(const utils::PointU& p) const;
void addRoad(square_container_t squares);
private:
using type_container = utils::Array2D<SquareType>;
type_container m_squares;
};
END_NAMESPACE_WORLD
#endif // MAP_HPP
| 17.565217 | 58 | 0.683168 | julienlopez |
0a46dbeb7021722dceacef81b50700c9116d9984 | 574 | hh | C++ | src/Zynga/Framework/StorableObject/V1/Test/Mock/ValidNestedMap.hh | chintan-j-patel/zynga-hacklang-framework | d9893b8873e3c8c7223772fd3c94d2531760172a | [
"MIT"
] | 19 | 2018-04-23T09:30:48.000Z | 2022-03-06T21:35:18.000Z | src/Zynga/Framework/StorableObject/V1/Test/Mock/ValidNestedMap.hh | chintan-j-patel/zynga-hacklang-framework | d9893b8873e3c8c7223772fd3c94d2531760172a | [
"MIT"
] | 22 | 2017-11-27T23:39:25.000Z | 2019-08-09T08:56:57.000Z | src/Zynga/Framework/StorableObject/V1/Test/Mock/ValidNestedMap.hh | chintan-j-patel/zynga-hacklang-framework | d9893b8873e3c8c7223772fd3c94d2531760172a | [
"MIT"
] | 28 | 2017-11-16T20:53:56.000Z | 2021-01-04T11:13:17.000Z | <?hh // strict
namespace Zynga\Framework\StorableObject\V1\Test\Mock;
use Zynga\Framework\Type\V1\StringBox;
use Zynga\Framework\StorableObject\V1\Base as StorableObjectBase;
use Zynga\Framework\StorableObject\V1\StorableMap;
use Zynga\Framework\StorableObject\V1\Test\Mock\Valid;
class ValidNestedMap extends StorableObjectBase {
public StorableMap<StringBox> $stringMap;
public StorableMap<Valid> $validMap;
public function __construct() {
parent::__construct();
$this->stringMap = new StorableMap();
$this->validMap = new StorableMap();
}
}
| 22.076923 | 65 | 0.763066 | chintan-j-patel |
0a49edde0124a86c6ca945d3368947d26b181ae1 | 2,568 | cpp | C++ | SJF Scheduling.cpp | Anikcb/Operating-System | 3a39e86686fa24bfa72b56d5061c3c177a635863 | [
"MIT"
] | null | null | null | SJF Scheduling.cpp | Anikcb/Operating-System | 3a39e86686fa24bfa72b56d5061c3c177a635863 | [
"MIT"
] | null | null | null | SJF Scheduling.cpp | Anikcb/Operating-System | 3a39e86686fa24bfa72b56d5061c3c177a635863 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int burst_time[100];
int arrival_time[100];
int waiting_time[100];
int turnaround_time[100];
vector<int>v;
void space_fun(int num)
{
for(int i=1;i<=num;i++)cout<<" ";
}
int check(int st)
{
int mn=1e5,pos=-1,mn_arr=1e5,result;
for(int i=0;i<(int)v.size();i++)
{
if(arrival_time[v[i]]<=st)
{
if(burst_time[v[i]]<mn)mn=burst_time[v[i]],pos=i;
}
mn_arr=min(mn_arr,arrival_time[v[i]]);
}
if(pos==-1){
for(int i=0;i<(int)v.size();i++){
if(arrival_time[v[i]]<=mn_arr)
{
if(burst_time[v[i]]<mn)mn=burst_time[v[i]],pos=i;
}
}
}
result=v[pos];
v.erase(v.begin()+pos);
return result;
}
void avg_time(int num_pro)
{
int total_wait_time=0,starting_time=0,total_turnaround_time=0;
for(int i=1; i<=num_pro; i++)
{
int ch = check(starting_time);
if(starting_time>arrival_time[ch])
{
waiting_time[ch]=starting_time - arrival_time[ch];
starting_time+=burst_time[ch];
}
else
{
starting_time+=burst_time[ch];
}
turnaround_time[ch]=waiting_time[ch] + burst_time[ch];
total_wait_time+=waiting_time[ch];
total_turnaround_time+=turnaround_time[ch];
}
cout<<"\n\n\n"<<endl;
cout<<"Process"<<" "<<"Burst Time"<<" "<<"Arrival Time"<<" "<<"Waiting Time"<<" "<<"Turnaround Time"<<endl;
for(int i=1;i<=num_pro;i++)
{
cout<<" "<<i;
space_fun(10-(int)floor(log10(i) + 1));
cout<<burst_time[i];
space_fun(13-(int)floor(log10(burst_time[i]+1) + 1));
cout<<arrival_time[i];
space_fun(15-(int)floor(log10(arrival_time[i]+1) + 1));
cout<<waiting_time[i];
space_fun(15-(int)floor(log10(waiting_time[i]+1) + 1));
cout<<turnaround_time[i]<<endl;
}
cout<<"\n\n\n"<<endl;
cout<<"Average Waiting Time: "<<(float)total_wait_time/num_pro<<endl;
cout<<"Average Turnaround Time "<<(float)total_turnaround_time/num_pro<<endl;
}
int main()
{
int num_pro;
cout<<"Number of Process: ";
cin>>num_pro;
cout<<"Arrival Times: ";
for(int i=1; i<=num_pro; i++)
{
cin>>arrival_time[i];
v.push_back(i);
}
cout<<"Burst Times: ";
for(int i=1; i<=num_pro; i++)
{
cin>>burst_time[i];
}
avg_time(num_pro);
}
| 25.68 | 120 | 0.528816 | Anikcb |
0a4aef98c14edfb926ac99bf26b4209e22e0115f | 1,089 | cpp | C++ | src/ReadWrite/WriteImage.cpp | pateldeev/cs474 | 4aeb7c6a5317256e9e1f517d614a83b5b52f9f52 | [
"Xnet",
"X11"
] | null | null | null | src/ReadWrite/WriteImage.cpp | pateldeev/cs474 | 4aeb7c6a5317256e9e1f517d614a83b5b52f9f52 | [
"Xnet",
"X11"
] | null | null | null | src/ReadWrite/WriteImage.cpp | pateldeev/cs474 | 4aeb7c6a5317256e9e1f517d614a83b5b52f9f52 | [
"Xnet",
"X11"
] | null | null | null | #include <iostream>
#include <fstream>
#include "Image.h"
#include "ReadWrite.h"
int writeImage(const char fname[], const ImageType & image) {
int i, j;
int N, M, Q;
unsigned char * charImage;
std::ofstream ofp;
image.getImageInfo(N, M, Q);
charImage = (unsigned char *) new unsigned char [M * N];
// convert the integer values to unsigned char
int val;
for (i = 0; i < N; i++) {
for (j = 0; j < M; j++) {
image.getPixelVal(i, j, val);
charImage[i * M + j] = (unsigned char) val;
}
}
ofp.open(fname, std::ios::out | std::ios::binary);
if (!ofp) {
std::cout << "Can't open file: " << fname << std::endl;
exit(1);
}
ofp << "P5" << std::endl;
ofp << M << " " << N << std::endl;
ofp << Q << std::endl;
ofp.write(reinterpret_cast<char *> (charImage), (M * N) * sizeof (unsigned char));
if (ofp.fail()) {
std::cout << "Can't write image " << fname << std::endl;
exit(0);
}
ofp.close();
delete [] charImage;
return 1;
}
| 20.54717 | 86 | 0.513315 | pateldeev |
0a4ca286a8b0ca0c1b4f8da01c1c36ff51cf413b | 4,883 | cpp | C++ | src/minisef/networksystem/networkserver.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 6 | 2022-01-23T09:40:33.000Z | 2022-03-20T20:53:25.000Z | src/minisef/networksystem/networkserver.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | null | null | null | src/minisef/networksystem/networkserver.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 1 | 2022-02-06T21:05:23.000Z | 2022-02-06T21:05:23.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//===========================================================================//
#include "networkserver.h"
#include "networksystem.h"
#include "icvar.h"
#include "filesystem.h"
#include "UDP_Socket.h"
#include "sm_protocol.h"
#include "NetChannel.h"
#include "UDP_Process.h"
#include <winsock.h>
#include "networkclient.h"
//-----------------------------------------------------------------------------
//
// Implementation of CPlayer
//
//-----------------------------------------------------------------------------
CNetworkServer::CNetworkServer( )
{
m_pSocket = new CUDPSocket;
}
CNetworkServer::~CNetworkServer()
{
delete m_pSocket;
}
bool CNetworkServer::Init( int nServerPort )
{
if ( !m_pSocket->Init( nServerPort ) )
{
Warning( "CNetworkServer: Unable to create socket!!!\n" );
return false;
}
return true;
}
void CNetworkServer::Shutdown()
{
m_pSocket->Shutdown();
}
CNetChannel *CNetworkServer::FindNetChannel( const netadr_t& from )
{
CPlayer *pl = FindPlayerByAddress( from );
if ( pl )
return &pl->m_NetChan;
return NULL;
}
CPlayer *CNetworkServer::FindPlayerByAddress( const netadr_t& adr )
{
int c = m_Players.Count();
for ( int i = 0; i < c; ++i )
{
CPlayer *player = m_Players[ i ];
if ( player->GetRemoteAddress().CompareAdr( adr ) )
return player;
}
return NULL;
}
CPlayer *CNetworkServer::FindPlayerByNetChannel( INetChannel *chan )
{
int c = m_Players.Count();
for ( int i = 0; i < c; ++i )
{
CPlayer *player = m_Players[ i ];
if ( &player->m_NetChan == chan )
return player;
}
return NULL;
}
#define SPEW_MESSAGES
#if defined( SPEW_MESSAGES )
#define SM_SPEW_MESSAGE( code, remote ) \
Warning( "Message: %s from '%s'\n", #code, remote );
#else
#define SM_SPEW_MESSAGE( code, remote )
#endif
// process a connectionless packet
bool CNetworkServer::ProcessConnectionlessPacket( CNetPacket *packet )
{
int code = packet->m_Message.ReadByte();
switch ( code )
{
case c2s_connect:
{
SM_SPEW_MESSAGE( c2s_connect, packet->m_From.ToString() );
CPlayer *pl = FindPlayerByAddress( packet->m_From );
if ( pl )
{
Warning( "Player already exists for %s\n", packet->m_From.ToString() );
}
else
{
// Creates the connection
pl = new CPlayer( this, packet->m_From );
m_Players.AddToTail( pl );
// Now send the conn accepted message
AcceptConnection( packet->m_From );
}
}
break;
default:
{
Warning( "CNetworkServer::ProcessConnectionlessPacket: Unknown code '%i' from '%s'\n",
code, packet->m_From.ToString() );
}
break;
}
return true;
}
void CNetworkServer::AcceptConnection( const netadr_t& remote )
{
byte data[ 512 ];
bf_write buf( "CNetworkServer::AcceptConnection", data, sizeof( data ) );
buf.WriteLong( -1 );
buf.WriteByte( s2c_connect_accept );
m_pSocket->SendTo( remote, buf.GetData(), buf.GetNumBytesWritten() );
}
void CNetworkServer::ReadPackets( void )
{
UDP_ProcessSocket( m_pSocket, this, this );
int c = m_Players.Count();
for ( int i = c - 1; i >= 0 ; --i )
{
if ( m_Players[ i ]->m_bMarkedForDeletion )
{
CPlayer *pl = m_Players[ i ];
m_Players.Remove( i );
delete pl;
}
}
}
void CNetworkServer::SendUpdates()
{
int c = m_Players.Count();
for ( int i = 0; i < c; ++i )
{
m_Players[ i ]->SendUpdate();
}
}
void CNetworkServer::OnConnectionStarted( INetChannel *pChannel )
{
// Create a network event
NetworkConnectionEvent_t *pConnection = g_pNetworkSystemImp->CreateNetworkEvent< NetworkConnectionEvent_t >( );
pConnection->m_nType = NETWORK_EVENT_CONNECTED;
pConnection->m_pChannel = pChannel;
}
void CNetworkServer::OnConnectionClosing( INetChannel *pChannel, char const *reason )
{
Warning( "OnConnectionClosing '%s'\n", reason );
CPlayer *pPlayer = FindPlayerByNetChannel( pChannel );
if ( pPlayer )
{
pPlayer->Shutdown();
}
// Create a network event
NetworkDisconnectionEvent_t *pDisconnection = g_pNetworkSystemImp->CreateNetworkEvent< NetworkDisconnectionEvent_t >( );
pDisconnection->m_nType = NETWORK_EVENT_DISCONNECTED;
pDisconnection->m_pChannel = pChannel;
}
void CNetworkServer::OnPacketStarted( int inseq, int outseq )
{
}
void CNetworkServer::OnPacketFinished()
{
}
//-----------------------------------------------------------------------------
//
// Implementation of CPlayer
//
//-----------------------------------------------------------------------------
CPlayer::CPlayer( CNetworkServer *server, netadr_t& remote ) :
m_bMarkedForDeletion( false )
{
m_NetChan.Setup( true, &remote, server->m_pSocket, "player", server );
}
void CPlayer::Shutdown()
{
m_bMarkedForDeletion = true;
m_NetChan.Shutdown( "received disconnect\n" );
}
void CPlayer::SendUpdate()
{
if ( m_NetChan.CanSendPacket() )
{
m_NetChan.SendDatagram( NULL );
}
}
| 21.702222 | 121 | 0.632808 | cstom4994 |
0a4cb9edec566a07e3e86a91be221479c3978078 | 2,677 | cpp | C++ | Practice/2018/2018.9.27/Luogu1295.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | 4 | 2017-10-31T14:25:18.000Z | 2018-06-10T16:10:17.000Z | Practice/2018/2018.9.27/Luogu1295.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | Practice/2018/2018.9.27/Luogu1295.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
#define lson (now<<1)
#define rson (lson|1)
const int maxN=201000;
const int inf=2147483647;
const ll INF=1e17;
class SegmentData
{
public:
ll mnkey,mn,lz;
SegmentData(){
mnkey=INF;mn=lz=0;return;
}
};
int n,m;
ll Bk[maxN],Sm[maxN],Q[maxN];
SegmentData S[maxN<<2];
void Modify(int now,int l,int r,int pos,ll key);
void Replace(int now,int l,int r,int ql,int qr,ll mx);
ll Query(int now,int l,int r,int ql,int qr);
void Update(int now);
void PushDown(int now);
void Delta(int now,ll nmx);
void Outp(int now,int l,int r);
int main(){
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++) scanf("%lld",&Bk[i]),Sm[i]=Sm[i-1]+Bk[i];
Modify(1,0,n,0,0);
//Outp(1,0,n);
int L=1,R=1;Bk[0]=INF;
for (int i=1;i<=n;i++){
while ((L<=R)&&(Bk[Q[R]]<=Bk[i])) R--;
//cout<<"Q:"<<i<<" "<<Q[R]<<endl;
Replace(1,0,n,Q[R],i-1,Bk[i]);
Q[++R]=i;
int p=lower_bound(&Sm[0],&Sm[n+1],Sm[i]-m)-Sm;
while (Sm[p]<Sm[i]-m) p++;
if (p>=i) p=i-1;
ll f=Query(1,0,n,p,i-1);
//cout<<i<<":"<<p<<" "<<f<<endl;
Modify(1,0,n,i,f);
//Outp(1,0,n);
}
printf("%lld\n",Query(1,0,n,n,n));return 0;
}
void Modify(int now,int l,int r,int pos,ll key){
if (l==r){
S[now].mnkey=S[now].mn=key;return;
}
PushDown(now);
int mid=(l+r)>>1;
if (pos<=mid) Modify(lson,l,mid,pos,key);
else Modify(rson,mid+1,r,pos,key);
Update(now);return;
}
void Replace(int now,int l,int r,int ql,int qr,ll mx){
if ((l==ql)&&(r==qr)){
Delta(now,mx);return;
}
PushDown(now);
int mid=(l+r)>>1;
if (qr<=mid) Replace(lson,l,mid,ql,qr,mx);
else if (ql>=mid+1) Replace(rson,mid+1,r,ql,qr,mx);
else{
Replace(lson,l,mid,ql,mid,mx);
Replace(rson,mid+1,r,mid+1,qr,mx);
}
Update(now);return;
}
ll Query(int now,int l,int r,int ql,int qr){
if ((l==ql)&&(r==qr)) return S[now].mnkey;
PushDown(now);
int mid=(l+r)>>1;
if (qr<=mid) return Query(lson,l,mid,ql,qr);
else if (ql>=mid+1) return Query(rson,mid+1,r,ql,qr);
else return min(Query(lson,l,mid,ql,mid),Query(rson,mid+1,r,mid+1,qr));
}
void Update(int now){
S[now].mn=min(S[lson].mn,S[rson].mn);
S[now].mnkey=min(S[lson].mnkey,S[rson].mnkey);
return;
}
void PushDown(int now){
if (S[now].lz){
Delta(lson,S[now].lz);Delta(rson,S[now].lz);
S[now].lz=0;
}
return;
}
void Delta(int now,ll nmx){
S[now].mnkey=S[now].mn+nmx;
S[now].lz=nmx;return;
}
void Outp(int now,int l,int r){
if (l==r) cout<<"["<<l<<" "<<r<<"] "<<S[now].mnkey<<" "<<S[now].mn<<endl;
if (l==r) return;
int mid=(l+r)>>1;PushDown(now);
Outp(lson,l,mid);Outp(rson,mid+1,r);
return;
}
| 22.123967 | 74 | 0.605902 | SYCstudio |
aeaa8fe0a1f9ad2666609dc10d64678dacd55ecc | 1,682 | hpp | C++ | app/GUI/widgetPacks/CraftingWindow.hpp | isonil/survival | ecb59af9fcbb35b9c28fd4fe29a4628f046165c8 | [
"MIT"
] | 1 | 2017-05-12T10:12:41.000Z | 2017-05-12T10:12:41.000Z | app/GUI/widgetPacks/CraftingWindow.hpp | isonil/Survival | ecb59af9fcbb35b9c28fd4fe29a4628f046165c8 | [
"MIT"
] | null | null | null | app/GUI/widgetPacks/CraftingWindow.hpp | isonil/Survival | ecb59af9fcbb35b9c28fd4fe29a4628f046165c8 | [
"MIT"
] | 1 | 2019-01-09T04:05:36.000Z | 2019-01-09T04:05:36.000Z | #ifndef APP_CRAFTING_WINDOW_HPP
#define APP_CRAFTING_WINDOW_HPP
#include "engine/util/Vec2.hpp"
#include <vector>
namespace engine { namespace GUI { class Window; class Button; class RectWidget; class Image; class Label; } }
namespace app
{
class Character;
class Structure;
class CraftingWindow
{
public:
CraftingWindow(const std::shared_ptr <Character> &character);
CraftingWindow(const std::shared_ptr <Character> &character, const std::shared_ptr <Structure> &workbench);
void update();
bool isClosed() const;
bool hasWorkbench() const;
Character &getCharacter() const;
Structure &getWorkbench() const;
static const float k_maxCharacterDistanceToWorkbench;
private:
struct Row
{
std::shared_ptr <engine::GUI::RectWidget> rect;
std::shared_ptr <engine::GUI::Button> craftButton;
std::shared_ptr <engine::GUI::Image> itemImage;
std::shared_ptr <engine::GUI::Label> itemLabel;
std::shared_ptr <engine::GUI::Label> priceLabel;
std::shared_ptr <engine::GUI::Label> skillsRequirementLabel;
};
void init();
void recreateRows();
static const engine::IntVec2 k_size;
static const std::string k_title;
static const int k_rowsCountPerPage;
std::shared_ptr <Character> m_character;
std::shared_ptr <Structure> m_workbench;
std::shared_ptr <engine::GUI::Window> m_window;
std::shared_ptr <engine::GUI::Button> m_nextButton;
std::shared_ptr <engine::GUI::Button> m_previousButton;
std::shared_ptr <engine::GUI::Label> m_pageLabel;
std::vector <Row> m_rows;
int m_rowsOffset;
};
} // namespace app
#endif // APP_CRAFTING_WINDOW_HPP
| 26.28125 | 111 | 0.706302 | isonil |
aead11d0a4d5056f721fdf7cd09985ff74eac382 | 14,040 | cpp | C++ | src/crl_camera/CRLPhysicalCamera.cpp | M-Gjerde/MultiSense | 921a1a62757a4831bd51b2659e2bff670641d962 | [
"MIT"
] | null | null | null | src/crl_camera/CRLPhysicalCamera.cpp | M-Gjerde/MultiSense | 921a1a62757a4831bd51b2659e2bff670641d962 | [
"MIT"
] | null | null | null | src/crl_camera/CRLPhysicalCamera.cpp | M-Gjerde/MultiSense | 921a1a62757a4831bd51b2659e2bff670641d962 | [
"MIT"
] | null | null | null | //
// Created by magnus on 3/1/22.
//
#include <thread>
#include <bitset>
#include "CRLPhysicalCamera.h"
#include <iostream>
bool CRLPhysicalCamera::connect(const std::string& ip) {
if (cameraInterface == nullptr) {
cameraInterface = crl::multisense::Channel::Create(ip);
if (cameraInterface != nullptr) {
updateCameraInfo();
addCallbacks();
cameraInterface->setMtu(7200); // TODO Move and error check this line. Failed on Windows if Jumbo frames is disabled on ethernet device
online = true;
return true;
}
}
return false;
}
void CRLPhysicalCamera::start(std::string string, std::string dataSourceStr) {
crl::multisense::DataSource source = stringToDataSource(dataSourceStr);
// Check if the stream has already been enabled first
if (std::find(enabledSources.begin(), enabledSources.end(),
source) != enabledSources.end()) {
return;
}
uint32_t colorSource = crl::multisense::Source_Chroma_Rectified_Aux | crl::multisense::Source_Chroma_Rectified_Aux |
crl::multisense::Source_Chroma_Aux |
crl::multisense::Source_Chroma_Left | crl::multisense::Source_Chroma_Right;
if (source & colorSource)
enabledSources.push_back(crl::multisense::Source_Luma_Rectified_Aux);
enabledSources.push_back(source);
// Set mode first
std::string delimiter = "x";
size_t pos = 0;
std::string token;
std::vector<uint32_t> widthHeightDepth;
while ((pos = string.find(delimiter)) != std::string::npos) {
token = string.substr(0, pos);
widthHeightDepth.push_back(std::stoi(token));
string.erase(0, pos + delimiter.length());
}
if (widthHeightDepth.size() != 3) {
std::cerr << "Select valid mode\n";
return;
}
//this->selectDisparities(widthHeightDepth[2]);
//this->selectResolution(widthHeightDepth[0], widthHeightDepth[1]);
//this->selectFramerate(60);
// Start stream
for (auto src: enabledSources) {
bool status = cameraInterface->startStreams(src);
printf("Started stream %s status: %d\n", dataSourceToString(src).c_str(), status);
}
std::thread thread_obj(CRLPhysicalCamera::setDelayedPropertyThreadFunc, this);
thread_obj.join();
}
void CRLPhysicalCamera::setDelayedPropertyThreadFunc(void *context) {
auto *app = static_cast<CRLPhysicalCamera *>(context);
std::this_thread::sleep_until(std::chrono::system_clock::now() + std::chrono::seconds(1));
app->modeChange = true;
app->play = true;
}
void CRLPhysicalCamera::stop(std::string dataSourceStr) {
crl::multisense::DataSource src = stringToDataSource(dataSourceStr);
// Check if the stream has been enabled before we attempt to stop it
if (std::find(enabledSources.begin(), enabledSources.end(),
src) == enabledSources.end()) {
return;
}
std::vector<uint32_t>::iterator it;
it = std::remove(enabledSources.begin(), enabledSources.end(),
src);
enabledSources.erase(it);
/*
std::vector<uint32_t>::iterator it;
// Search and stop additional sources
it = std::find(enabledSources.begin(), enabledSources.end(), crl::multisense::Source_Chroma_Rectified_Aux);
if (it != enabledSources.end()) {
src |= crl::multisense::Source_Luma_Rectified_Aux;
}
*/
bool status = cameraInterface->stopStreams(src);
printf("Stopped stream %s status: %d\n", dataSourceStr.c_str(), status);
modeChange = true;
}
/*
CRLBaseCamera::PointCloudData *CRLPhysicalCamera::getStream() {
return meshData;
}
std::unordered_map<crl::multisense::DataSource, crl::multisense::image::Header> CRLPhysicalCamera::getImage() {
return imagePointers;
}
CRLPhysicalCamera::~CRLPhysicalCamera() {
if (meshData != nullptr && meshData->vertices != nullptr)
free(meshData->vertices);
}
CRLBaseCamera::CameraInfo CRLPhysicalCamera::getInfo() {
return CRLBaseCamera::cameraInfo;
}
// Pick an image size
crl::multisense::image::Config CRLPhysicalCamera::getImageConfig() const {
// Configure the sensor.
crl::multisense::image::Config cfg;
bool status = cameraInterface->getImageConfig(cfg);
if (crl::multisense::Status_Ok != status) {
printf("Failed to query image config: %d\n", status);
}
return cfg;
}
std::unordered_set<crl::multisense::DataSource> CRLPhysicalCamera::supportedSources() {
// this method effectively restrics the supported sources for the classice libmultisense api
std::unordered_set<crl::multisense::DataSource> ret;
if (cameraInfo.supportedSources & crl::multisense::Source_Raw_Left) ret.insert(crl::multisense::Source_Raw_Left);
if (cameraInfo.supportedSources & crl::multisense::Source_Raw_Right) ret.insert(crl::multisense::Source_Raw_Right);
if (cameraInfo.supportedSources & crl::multisense::Source_Luma_Left) ret.insert(crl::multisense::Source_Luma_Left);
if (cameraInfo.supportedSources & crl::multisense::Source_Luma_Right)
ret.insert(crl::multisense::Source_Luma_Right);
if (cameraInfo.supportedSources & crl::multisense::Source_Luma_Rectified_Left)
ret.insert(crl::multisense::Source_Luma_Rectified_Left);
if (cameraInfo.supportedSources & crl::multisense::Source_Luma_Rectified_Right)
ret.insert(crl::multisense::Source_Luma_Rectified_Right);
if (cameraInfo.supportedSources & crl::multisense::Source_Chroma_Aux)
ret.insert(crl::multisense::Source_Chroma_Aux);
if (cameraInfo.supportedSources & crl::multisense::Source_Chroma_Left)
ret.insert(crl::multisense::Source_Chroma_Left);
if (cameraInfo.supportedSources & crl::multisense::Source_Chroma_Right)
ret.insert(crl::multisense::Source_Chroma_Right);
if (cameraInfo.supportedSources & crl::multisense::Source_Disparity_Left)
ret.insert(crl::multisense::Source_Disparity_Left);
if (cameraInfo.supportedSources & crl::multisense::Source_Disparity_Right)
ret.insert(crl::multisense::Source_Disparity_Right);
if (cameraInfo.supportedSources & crl::multisense::Source_Disparity_Cost)
ret.insert(crl::multisense::Source_Disparity_Cost);
if (cameraInfo.supportedSources & crl::multisense::Source_Raw_Aux) ret.insert(crl::multisense::Source_Raw_Aux);
if (cameraInfo.supportedSources & crl::multisense::Source_Luma_Aux) ret.insert(crl::multisense::Source_Luma_Aux);
if (cameraInfo.supportedSources & crl::multisense::Source_Luma_Rectified_Aux)
ret.insert(crl::multisense::Source_Luma_Rectified_Aux);
if (cameraInfo.supportedSources & crl::multisense::Source_Chroma_Rectified_Aux)
ret.insert(crl::multisense::Source_Chroma_Rectified_Aux);
if (cameraInfo.supportedSources & crl::multisense::Source_Disparity_Aux)
ret.insert(crl::multisense::Source_Disparity_Aux);
return ret;
}
*/
std::string CRLPhysicalCamera::dataSourceToString(crl::multisense::DataSource d) {
switch (d) {
case crl::multisense::Source_Raw_Left:
return "Raw Left";
case crl::multisense::Source_Raw_Right:
return "Raw Right";
case crl::multisense::Source_Luma_Left:
return "Luma Left";
case crl::multisense::Source_Luma_Right:
return "Luma Right";
case crl::multisense::Source_Luma_Rectified_Left:
return "Luma Rectified Left";
case crl::multisense::Source_Luma_Rectified_Right:
return "Luma Rectified Right";
case crl::multisense::Source_Chroma_Left:
return "Color Left";
case crl::multisense::Source_Chroma_Right:
return "Source Color Right";
case crl::multisense::Source_Disparity_Left:
return "Disparity Left";
case crl::multisense::Source_Disparity_Cost:
return "Disparity Cost";
case crl::multisense::Source_Jpeg_Left:
return "Jpeg Left";
case crl::multisense::Source_Rgb_Left:
return "Source Rgb Left";
case crl::multisense::Source_Lidar_Scan:
return "Source Lidar Scan";
case crl::multisense::Source_Raw_Aux:
return "Raw Aux";
case crl::multisense::Source_Luma_Aux:
return "Luma Aux";
case crl::multisense::Source_Luma_Rectified_Aux:
return "Luma Rectified Aux";
case crl::multisense::Source_Chroma_Aux:
return "Color Aux";
case crl::multisense::Source_Chroma_Rectified_Aux:
return "Color Rectified Aux";
case crl::multisense::Source_Disparity_Aux:
return "Disparity Aux";
default:
return "Unknown";
}
}
crl::multisense::DataSource CRLPhysicalCamera::stringToDataSource(const std::string &d) {
if (d == "Raw Left") return crl::multisense::Source_Raw_Left;
if (d == "Raw Right") return crl::multisense::Source_Raw_Right;
if (d == "Luma Left") return crl::multisense::Source_Luma_Left;
if (d == "Luma Right") return crl::multisense::Source_Luma_Right;
if (d == "Luma Rectified Left") return crl::multisense::Source_Luma_Rectified_Left;
if (d == "Luma Rectified Right") return crl::multisense::Source_Luma_Rectified_Right;
if (d == "Color Left") return crl::multisense::Source_Chroma_Left;
if (d == "Source Color Right") return crl::multisense::Source_Chroma_Right;
if (d == "Disparity Left") return crl::multisense::Source_Disparity_Left;
if (d == "Disparity Cost") return crl::multisense::Source_Disparity_Cost;
if (d == "Jpeg Left") return crl::multisense::Source_Jpeg_Left;
if (d == "Source Rgb Left") return crl::multisense::Source_Rgb_Left;
if (d == "Source Lidar Scan") return crl::multisense::Source_Lidar_Scan;
if (d == "Raw Aux") return crl::multisense::Source_Raw_Aux;
if (d == "Luma Aux") return crl::multisense::Source_Luma_Aux;
if (d == "Luma Rectified Aux") return crl::multisense::Source_Luma_Rectified_Aux;
if (d == "Color Aux") return crl::multisense::Source_Chroma_Aux;
if (d == "Color Rectified Aux") return crl::multisense::Source_Chroma_Rectified_Aux;
if (d == "Disparity Aux") return crl::multisense::Source_Disparity_Aux;
throw std::runtime_error(std::string{} + "Unknown Datasource: " + d);
}
void CRLPhysicalCamera::update() {
for (auto src: enabledSources) {
if (src == crl::multisense::Source_Disparity_Left) {
// Reproject camera to 3D
//stream = &imagePointers[crl::multisense::Source_Disparity_Left];
}
}
}
void CRLPhysicalCamera::setup(uint32_t width, uint32_t height) {
crl::multisense::image::Config c = cameraInfo.imgConf;
kInverseMatrix =
glm::mat4(
glm::vec4(1 / c.fx(), 0, -(c.cx() * c.fx()) / (c.fx() * c.fy()), 0),
glm::vec4(0, 1 / c.fy(), -c.cy() / c.fy(), 0),
glm::vec4(0, 0, 1, 0),
glm::vec4(0, 0, 0, 1));
kInverseMatrix = glm::transpose(kInverseMatrix);
/*
kInverseMatrix = glm::mat4(glm::vec4(c.fy() * c.tx(), 0, 0, -c.fy() * c.cx() * c.tx()),
glm::vec4(0, c.fx() * c.tx(), 0, -c.fx() * c.cy() * c.tx()),
glm::vec4(0, 0, 0, c.fx() * c.fy() * c.tx()),
glm::vec4(0, 0, -c.fx(), c.fy() * 1));
kInverseMatrix =
glm::mat4(
glm::vec4(1/c.fx(), 0, -(c.cx()*c.fx())/(c.fx() * c.fy()), 0),
glm::vec4(0, 1/c.fy(), -c.cy() / c.fy(), 0),
glm::vec4(0, 0, 1, 0),
glm::vec4(0, 0, 0, 1));
*/
// Load calibration data
}
void CRLPhysicalCamera::updateCameraInfo() {
cameraInterface->getImageConfig(cameraInfo.imgConf);
cameraInterface->getNetworkConfig(cameraInfo.netConfig);
cameraInterface->getVersionInfo(cameraInfo.versionInfo);
cameraInterface->getDeviceInfo(cameraInfo.devInfo);
cameraInterface->getDeviceModes(cameraInfo.supportedDeviceModes);
cameraInterface->getImageCalibration(cameraInfo.camCal);
cameraInterface->getEnabledStreams(cameraInfo.supportedSources);
}
void CRLPhysicalCamera::streamCallback(const crl::multisense::image::Header &image) {
auto &buf = buffers_[image.source];
// TODO: make this a method of the BufferPair or something
std::scoped_lock lock(buf.swap_lock);
if (buf.inactiveCBBuf != nullptr) // initial state
{
cameraInterface->releaseCallbackBuffer(buf.inactiveCBBuf);
}
imagePointers[image.source] = image;
buf.inactiveCBBuf = cameraInterface->reserveCallbackBuffer();
buf.inactive = image;
}
void CRLPhysicalCamera::imageCallback(const crl::multisense::image::Header &header, void *userDataP) {
auto cam = reinterpret_cast<CRLPhysicalCamera *>(userDataP);
cam->streamCallback(header);
}
void CRLPhysicalCamera::addCallbacks() {
for (auto e: cameraInfo.supportedDeviceModes)
cameraInfo.supportedSources |= e.supportedDataSources;
// reserve double_buffers for each stream
uint_fast8_t num_sources = 0;
crl::multisense::DataSource d = cameraInfo.supportedSources;
while (d) {
num_sources += (d & 1);
d >>= 1;
}
// --- initializing our callback buffers ---
std::size_t bufSize = 1024 * 1024 * 10; // 10mb for every image, like in LibMultiSense
for (int i = 0;
i < (num_sources * 2 + 1); ++i) // double-buffering for each stream, plus one for handling if those are full
{
cameraInfo.rawImages.push_back(new uint8_t[bufSize]);
}
// use these buffers instead of the default
cameraInterface->setLargeBuffers(cameraInfo.rawImages, bufSize);
// finally, add our callback
if (cameraInterface->addIsolatedCallback(imageCallback, cameraInfo.supportedSources, this) !=
crl::multisense::Status_Ok) {
std::cerr << "Adding callback failed!\n";
}
}
| 39.327731 | 147 | 0.664245 | M-Gjerde |
aebb08a2b4518fcfd7b6e94719f4b0c2bad58865 | 2,306 | cpp | C++ | src/Telnet/CmdLineRegistry.cpp | vinthewrench/FooServer | 1e00a80df41235d29c6402cb8ae4d1f7bbbe07a6 | [
"MIT"
] | null | null | null | src/Telnet/CmdLineRegistry.cpp | vinthewrench/FooServer | 1e00a80df41235d29c6402cb8ae4d1f7bbbe07a6 | [
"MIT"
] | null | null | null | src/Telnet/CmdLineRegistry.cpp | vinthewrench/FooServer | 1e00a80df41235d29c6402cb8ae4d1f7bbbe07a6 | [
"MIT"
] | null | null | null | //
// CmdLineRegistry.cpp
//
// Created by Vincent Moscaritolo on 4/6/21.
//
#include <sstream>
#include <iostream>
#include <iomanip>
#include "CmdLineRegistry.hpp"
#include "CmdLineHelp.hpp"
CmdLineRegistry *CmdLineRegistry::sharedInstance = 0;
CmdLineRegistry::CmdLineRegistry(){
_commandMap.clear();
}
CmdLineRegistry::~CmdLineRegistry(){
_commandMap.clear();
}
void CmdLineRegistry::registerCommand(string_view name,
cmdHandler_t cb){
string str = string(name);
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
_commandMap[str] = cb;
}
void CmdLineRegistry::removeCommand(const string name){
string str = name;
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
_commandMap.erase(str);
};
vector<string> CmdLineRegistry::matchesForCmd( const string cmd){
vector<string> options = registeredCommands();
vector<string> results;
string search = cmd;
std::transform(search.begin(), search.end(), search.begin(), ::tolower);
for(auto str :options){
if(str.find(search) == 0){
results.push_back(str);
}
}
sort(results.begin(), results.end());
return results;
}
vector<string> CmdLineRegistry::registeredCommands(){
vector<string> results;
results.clear();
for(auto it = _commandMap.begin(); it != _commandMap.end(); ++it) {
// ignore built in commands.
if(it->first == CMD_WELCOME) continue;
results.push_back( string(it->first));
};
return results;
}
CmdLineRegistry::cmdHandler_t CmdLineRegistry::handlerForCmd( const string cmd){
cmdHandler_t func = NULL;
auto it = _commandMap.find(cmd);
if(it != _commandMap.end()){
func = it->second;
}
return func;
}
// MARK: - help
string CmdLineRegistry::helpForCmd( stringvector params){
std::ostringstream oss;
if(params.size() == 0){
// do generic help
auto str = CmdLineHelp::shared()->helpForCmd("");
oss << " ?\r\n" << str << "\r\n";
}
else {
string cmd = params.at(0);
std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::tolower);
if(cmd == "help"){
auto str = CmdLineHelp::shared()->helpForCmd(params.size() >1?params.at(1):"");
oss << "\r\n" << str << "\r\n";
}
else {
auto str = CmdLineHelp::shared()->helpForCmd(cmd);
oss << " ?\r\n" << str << "\r\n";
}
}
return oss.str();
}
| 20.589286 | 83 | 0.654814 | vinthewrench |
aebecd48c6f11466a99c5486da998a4bdeac832e | 1,755 | cpp | C++ | NYP_Framework_Week08_SOLUTION/Base/Source/SceneGraph/UpdateTransformation.cpp | KianMarvi/Assignment | 8133acec4dd65bc49316aec8deb3961035bdef27 | [
"MIT"
] | null | null | null | NYP_Framework_Week08_SOLUTION/Base/Source/SceneGraph/UpdateTransformation.cpp | KianMarvi/Assignment | 8133acec4dd65bc49316aec8deb3961035bdef27 | [
"MIT"
] | 8 | 2019-12-29T17:17:00.000Z | 2020-02-07T08:08:01.000Z | NYP_Framework_Week08_SOLUTION/Base/Source/SceneGraph/UpdateTransformation.cpp | KianMarvi/Assignment | 8133acec4dd65bc49316aec8deb3961035bdef27 | [
"MIT"
] | null | null | null | #include "UpdateTransformation.h"
CUpdateTransformation::CUpdateTransformation()
: curSteps(0)
, deltaSteps(1)
, minSteps(0)
, maxSteps(0)
{
Update_Mtx.SetToIdentity();
Update_Mtx_REVERSED.SetToIdentity();
}
CUpdateTransformation::~CUpdateTransformation()
{
}
// Reset the transformation matrix to identity matrix
void CUpdateTransformation::Reset(void)
{
Update_Mtx.SetToIdentity();
Update_Mtx_REVERSED.SetToIdentity();
}
// Update the steps
void CUpdateTransformation::Update(void)
{
curSteps += deltaSteps;
if ((curSteps >= maxSteps) || (curSteps <= minSteps))
{
deltaSteps *= -1;
}
}
// Apply a translation to the Update Transformation Matrix
void CUpdateTransformation::ApplyUpdate(const float dx, const float dy, const float dz)
{
Update_Mtx.SetToTranslation(dx, dy, dz);
Update_Mtx_REVERSED.SetToTranslation(-dx, -dy, -dz);
}
// Apply a rotation to the Update Transformation Matrix
void CUpdateTransformation::ApplyUpdate(const float angle, const float rx, const float ry, const float rz)
{
Update_Mtx.SetToRotation(angle, rx, ry, rz);
Update_Mtx_REVERSED.SetToRotation(-angle, rx, ry, rz);
}
// Set the minSteps and maxSteps
void CUpdateTransformation::SetSteps(const int minSteps, const int maxSteps)
{
this->minSteps = minSteps;
this->maxSteps = maxSteps;
}
// Get the minSteps and maxSteps
void CUpdateTransformation::GetSteps(int& minSteps, int& maxSteps)
{
minSteps = this->minSteps;
maxSteps = this->maxSteps;
}
// Get the direction of update
bool CUpdateTransformation::GetDirection(void) const
{
if (deltaSteps == -1)
return false;
return true;
}
// Get the Update_Mtx
Mtx44 CUpdateTransformation::GetUpdateTransformation(void)
{
if (deltaSteps == -1)
return Update_Mtx_REVERSED;
return Update_Mtx;
}
| 23.4 | 106 | 0.756695 | KianMarvi |
aec2cd8d25f33e6972d435b5b4c5d2b0780563a9 | 43,881 | cpp | C++ | ycsb-bench/FPTree/fptree.cpp | mkatsa/PENVMTool | c63de91036cd84d36cd8ac54f2033ea141a292dc | [
"Apache-2.0"
] | 1 | 2022-03-22T15:16:56.000Z | 2022-03-22T15:16:56.000Z | ycsb-bench/FPTree/fptree.cpp | mkatsa/PENVMTool | c63de91036cd84d36cd8ac54f2033ea141a292dc | [
"Apache-2.0"
] | null | null | null | ycsb-bench/FPTree/fptree.cpp | mkatsa/PENVMTool | c63de91036cd84d36cd8ac54f2033ea141a292dc | [
"Apache-2.0"
] | null | null | null | // Copyright (c) Simon Fraser University. All rights reserved.
// Licensed under the MIT license.
//
// Authors:
// George He <[email protected]>
// Duo Lu <[email protected]>
// Tianzheng Wang <[email protected]>
#include "fptree.h"
#ifdef PMEM
inline bool file_pool_exists(const std::string& name)
{
return ( access( name.c_str(), F_OK ) != -1 );
}
#endif
BaseNode::BaseNode()
{
this->isInnerNode = false;
}
InnerNode::InnerNode()
{
this->isInnerNode = true;
this->nKey = 0;
}
InnerNode::InnerNode(uint64_t key, BaseNode* left, BaseNode* right)
{
this->isInnerNode = true;
this->keys[0] = key;
this->p_children[0] = left;
this->p_children[1] = right;
this->nKey = 1;
}
void InnerNode::init(uint64_t key, BaseNode* left, BaseNode* right)
{
this->isInnerNode = true;
this->keys[0] = key;
this->p_children[0] = left;
this->p_children[1] = right;
this->nKey = 1;
}
InnerNode::InnerNode(const InnerNode& inner)
{
memcpy(this, &inner, sizeof(struct InnerNode));
}
InnerNode::~InnerNode()
{
for (size_t i = 0; i < this->nKey; i++) { delete this->p_children[i]; }
}
#ifndef PMEM
LeafNode::LeafNode()
{
this->isInnerNode = false;
this->bitmap.clear();
this->p_next = nullptr;
this->lock.store(0, std::memory_order_acquire);
}
LeafNode::LeafNode(const LeafNode& leaf)
{
memcpy(this, &leaf, sizeof(struct LeafNode));
}
LeafNode& LeafNode::operator=(const LeafNode& leaf)
{
memcpy(this, &leaf, sizeof(struct LeafNode));
return *this;
}
#endif
void InnerNode::removeKey(uint64_t index, bool remove_right_child = true)
{
assert(this->nKey > index && "Remove key index out of range!");
this->nKey--;
std::memmove(this->keys + index, this->keys + index + 1, (this->nKey-index)*sizeof(uint64_t));
if (remove_right_child)
index ++;
std::memmove(this->p_children + index, this->p_children + index + 1, (this->nKey - index + 1)*sizeof(BaseNode*));
}
void InnerNode::addKey(uint64_t index, uint64_t key, BaseNode* child, bool add_child_right = true)
{
assert(this->nKey >= index && "Insert key index out of range!");
std::memmove(this->keys+index+1, this->keys+index, (this->nKey-index)*sizeof(uint64_t)); // move keys
this->keys[index] = key;
if (add_child_right)
index ++;
std::memmove(this->p_children+index+1, this->p_children+index, (this->nKey-index+1)*sizeof(BaseNode*));
this->p_children[index] = child;
this->nKey++;
}
inline uint64_t InnerNode::findChildIndex(uint64_t key)
{
auto lower = std::lower_bound(this->keys, this->keys + this->nKey, key);
uint64_t idx = lower - this->keys;
if (idx < this->nKey && *lower == key)
idx++;
return idx;
}
inline void LeafNode::addKV(struct KV kv)
{
uint64_t idx = this->bitmap.first_zero();
assert(idx < MAX_LEAF_SIZE && "Insert kv out of bound!");
this->fingerprints[idx] = getOneByteHash(kv.key);
this->kv_pairs[idx] = kv;
this->bitmap.set(idx);
}
inline uint64_t LeafNode::findKVIndex(uint64_t key)
{
size_t key_hash = getOneByteHash(key);
for (uint64_t i = 0; i < MAX_LEAF_SIZE; i++)
{
if (this->bitmap.test(i) == 1 &&
this->fingerprints[i] == key_hash &&
this->kv_pairs[i].key == key)
{
return i;
}
}
return MAX_LEAF_SIZE;
}
uint64_t LeafNode::minKey()
{
uint64_t min_key = -1, i = 0;
for (; i < MAX_LEAF_SIZE; i++)
{
if (this->bitmap.test(i) && this->kv_pairs[i].key < min_key)
min_key = this->kv_pairs[i].key;
}
assert(min_key != -1 && "minKey called for empty leaf!");
return min_key;
}
void LeafNode::getStat(uint64_t key, LeafNodeStat& lstat)
{
lstat.count = 0;
lstat.min_key = -1;
lstat.kv_idx = MAX_LEAF_SIZE;
uint64_t cur_key = -1;
for (size_t counter = 0; counter < MAX_LEAF_SIZE; counter ++)
{
if (this->bitmap.test(counter)) // if find a valid entry
{
lstat.count ++;
cur_key = this->kv_pairs[counter].key;
if (cur_key == key) // if the entry is key
lstat.kv_idx = counter;
else if (cur_key < lstat.min_key)
lstat.min_key = cur_key;
}
}
}
inline LeafNode* FPtree::maxLeaf(BaseNode* node)
{
while(node->isInnerNode)
{
node = reinterpret_cast<InnerNode*> (node)->p_children[reinterpret_cast<InnerNode*> (node)->nKey];
}
return reinterpret_cast<LeafNode*> (node);
}
#ifdef PMEM
static TOID(struct Log) allocLogArray()
{
TOID(struct Log) array = POBJ_ROOT(pop, struct Log);
POBJ_ALLOC(pop, &array, struct Log, sizeof(struct Log) * sizeLogArray,
NULL, NULL);
if (TOID_IS_NULL(array)) { fprintf(stderr, "POBJ_ALLOC\n"); return OID_NULL; }
for (uint64_t i = 0; i < sizeLogArray; i++)
{
if (POBJ_ALLOC(pop, &D_RW(array)[i],
struct Log, sizeof(struct Log),
NULL, NULL))
{
fprintf(stderr, "pmemobj_alloc\n");
}
}
return array.oid;
}
static TOID(struct Log) root_LogArray;
void FPtree::recover()
{
root_LogArray = POBJ_ROOT(pop, struct Log);
for (uint64_t i = 1; i < sizeLogArray / 2; i++)
{
recoverSplit(&D_RW(root_LogArray)[i]);
}
for (uint64_t i = sizeLogArray / 2; i < sizeLogArray; i++)
{
recoverDelete(&D_RW(root_LogArray)[i]);
}
}
#endif
FPtree::FPtree()
{
root = nullptr;
#ifdef PMEM
const char *path = "/mnt/pmem1/test_pool";
if (file_pool_exists(path) == 0)
{
if ((pop = pmemobj_create(path, POBJ_LAYOUT_NAME(FPtree), PMEMOBJ_POOL_SIZE, 0666)) == NULL)
perror("failed to create pool\n");
root_LogArray = allocLogArray();
}
else
{
if ((pop = pmemobj_open(path, POBJ_LAYOUT_NAME(FPtree))) == NULL)
perror("failed to open pool\n");
else
{
recover();
bulkLoad(1);
}
}
root_LogArray = POBJ_ROOT(pop, struct Log); // Avoid push root object to Queue, i = 1
for (uint64_t i = 1; i < sizeLogArray / 2; i++) // push persistent array to splitLogQueue
{
D_RW(root_LogArray)[i].PCurrentLeaf = OID_NULL;
D_RW(root_LogArray)[i].PLeaf = OID_NULL;
splitLogQueue.push(&D_RW(root_LogArray)[i]);
}
for (uint64_t i = sizeLogArray / 2; i < sizeLogArray; i++) // second half of array use as delete log
{
D_RW(root_LogArray)[i].PCurrentLeaf = OID_NULL;
D_RW(root_LogArray)[i].PLeaf = OID_NULL;
deleteLogQueue.push(&D_RW(root_LogArray)[i]);
}
#else
bitmap_idx = MAX_LEAF_SIZE;
#endif
}
FPtree::FPtree(int i)
{
root = nullptr;
#ifdef PMEM
char path[50];
snprintf(path, 50, "/mnt/pmem1/test_pool%d", i);
path[strlen(path)] = '\0';
if (file_pool_exists(path) == 0)
{
if ((pop = pmemobj_create(path, POBJ_LAYOUT_NAME(FPtree), PMEMOBJ_POOL_SIZE, 0666)) == NULL)
perror("failed to create pool\n");
root_LogArray = allocLogArray();
}
else
{
if ((pop = pmemobj_open(path, POBJ_LAYOUT_NAME(FPtree))) == NULL)
perror("failed to open pool\n");
else
{
recover();
bulkLoad(1);
}
}
root_LogArray = POBJ_ROOT(pop, struct Log); // Avoid push root object to Queue, i = 1
for (uint64_t i = 1; i < sizeLogArray / 2; i++) // push persistent array to splitLogQueue
{
D_RW(root_LogArray)[i].PCurrentLeaf = OID_NULL;
D_RW(root_LogArray)[i].PLeaf = OID_NULL;
splitLogQueue.push(&D_RW(root_LogArray)[i]);
}
for (uint64_t i = sizeLogArray / 2; i < sizeLogArray; i++) // second half of array use as delete log
{
D_RW(root_LogArray)[i].PCurrentLeaf = OID_NULL;
D_RW(root_LogArray)[i].PLeaf = OID_NULL;
deleteLogQueue.push(&D_RW(root_LogArray)[i]);
}
#else
bitmap_idx = MAX_LEAF_SIZE;
#endif
}
FPtree::~FPtree()
{
#ifdef PMEM
pmemobj_close(pop);
#else
if (root != nullptr)
delete root;
#endif
}
inline static uint8_t getOneByteHash(uint64_t key)
{
uint8_t oneByteHashKey = std::_Hash_bytes(&key, sizeof(key), 1) & 0xff;
return oneByteHashKey;
}
#ifdef PMEM
static void showList()
{
TOID(struct List) ListHead = POBJ_ROOT(pop, struct List);
TOID(struct LeafNode) leafNode = D_RO(ListHead)->head;
while (!TOID_IS_NULL(leafNode))
{
for (size_t i = 0; i < MAX_LEAF_SIZE; i++)
{
if (D_RO(leafNode)->bitmap.test(i))
std::cout << "(" << D_RO(leafNode)->kv_pairs[i].key << " | " <<
D_RO(leafNode)->kv_pairs[i].value << ")" << ", ";
}
std::cout << std::endl;
leafNode = D_RO(leafNode)->p_next;
}
}
static int constructLeafNode(PMEMobjpool *pop, void *ptr, void *arg)
{
struct LeafNode *node = (struct LeafNode *)ptr;
struct argLeafNode *a = (struct argLeafNode *)arg;
node->isInnerNode = a->isInnerNode;
node->bitmap = a->bitmap;
memcpy(node->fingerprints, a->fingerprints, sizeof(a->fingerprints));
memcpy(node->kv_pairs, a->kv_pairs, sizeof(a->kv_pairs));
node->p_next = TOID_NULL(struct LeafNode);
node->lock = a->lock;
pmemobj_persist(pop, node, a->size);
return 0;
}
#endif
void FPtree::printFPTree(std::string prefix, BaseNode* root)
{
if (root)
{
if (root->isInnerNode)
{
InnerNode* node = reinterpret_cast<InnerNode*> (root);
printFPTree(" " + prefix, node->p_children[node->nKey]);
for (int64_t i = node->nKey-1; i >= 0; i--)
{
std::cout << prefix << node->keys[i] << std::endl;
printFPTree(" " + prefix, node->p_children[i]);
}
}
else
{
LeafNode* node = reinterpret_cast<LeafNode*> (root);
for (int64_t i = MAX_LEAF_SIZE-1; i >= 0; i--)
{
if (node->bitmap.test(i) == 1)
std::cout << prefix << node->kv_pairs[i].key << "," << node->kv_pairs[i].value << std::endl;
}
}
}
}
inline LeafNode* FPtree::findLeaf(uint64_t key)
{
if (!root)
return nullptr;
if (!root->isInnerNode)
return reinterpret_cast<LeafNode*> (root);
InnerNode* cursor = reinterpret_cast<InnerNode*> (root);
while (cursor->isInnerNode)
{
cursor = reinterpret_cast<InnerNode*> (cursor->p_children[cursor->findChildIndex(key)]);
}
return reinterpret_cast<LeafNode*> (cursor);
}
inline LeafNode* FPtree::findLeafAndPushInnerNodes(uint64_t key)
{
if (!root)
return nullptr;
stack_innerNodes.clear();
if (!root->isInnerNode)
{
stack_innerNodes.push(nullptr);
return reinterpret_cast<LeafNode*> (root);
}
InnerNode* cursor = reinterpret_cast<InnerNode*> (root);
while (cursor->isInnerNode)
{
stack_innerNodes.push(cursor);
cursor = reinterpret_cast<InnerNode*> (cursor->p_children[cursor->findChildIndex(key)]);
}
return reinterpret_cast<LeafNode*> (cursor);
}
uint64_t FPtree::find(uint64_t key)
{
LeafNode* pLeafNode;
volatile uint64_t idx;
tbb::speculative_spin_rw_mutex::scoped_lock lock_find;
while (true)
{
lock_find.acquire(speculative_lock, false);
if ((pLeafNode = findLeaf(key)) == nullptr) { lock_find.release(); break; }
if (pLeafNode->lock) { lock_find.release(); continue; }
idx = pLeafNode->findKVIndex(key);
lock_find.release();
return (idx != MAX_LEAF_SIZE ? pLeafNode->kv_pairs[idx].value : 0 );
}
return 0;
}
void FPtree::splitLeafAndUpdateInnerParents(LeafNode* reachedLeafNode, Result decision, struct KV kv,
bool updateFunc = false, uint64_t prevPos = MAX_LEAF_SIZE)
{
uint64_t splitKey;
#ifdef PMEM
TOID(struct LeafNode) insertNode = pmemobj_oid(reachedLeafNode);
#else
LeafNode* insertNode = reachedLeafNode;
#endif
if (decision == Result::Split)
{
splitKey = splitLeaf(reachedLeafNode); // split and link two leaves
if (kv.key >= splitKey) // select one leaf to insert
insertNode = reachedLeafNode->p_next;
}
#ifdef PMEM
uint64_t slot = D_RW(insertNode)->bitmap.first_zero();
assert(slot < MAX_LEAF_SIZE && "Slot idx out of bound");
D_RW(insertNode)->kv_pairs[slot] = kv;
D_RW(insertNode)->fingerprints[slot] = getOneByteHash(kv.key);
pmemobj_persist(pop, &D_RO(insertNode)->kv_pairs[slot], sizeof(struct KV));
pmemobj_persist(pop, &D_RO(insertNode)->fingerprints[slot], SIZE_ONE_BYTE_HASH);
if (!updateFunc)
{
D_RW(insertNode)->bitmap.set(slot);
}
else
{
Bitset tmpBitmap = D_RW(insertNode)->bitmap;
tmpBitmap.reset(prevPos); tmpBitmap.set(slot);
D_RW(insertNode)->bitmap = tmpBitmap;
}
pmemobj_persist(pop, &D_RO(insertNode)->bitmap, sizeof(D_RO(insertNode)->bitmap));
#else
if (updateFunc)
insertNode->kv_pairs[prevPos].value = kv.value;
else
insertNode->addKV(kv);
#endif
if (decision == Result::Split)
{
LeafNode* newLeafNode;
#ifdef PMEM
newLeafNode = (struct LeafNode *) pmemobj_direct((reachedLeafNode->p_next).oid);
#else
newLeafNode = reachedLeafNode->p_next;
#endif
tbb::speculative_spin_rw_mutex::scoped_lock lock_split;
uint64_t mid = MAX_INNER_SIZE / 2, new_splitKey, insert_pos;
InnerNode* cur, *parent, *newInnerNode;
BaseNode* child;
short i = 0, idx;
/*---------------- Second Critical Section -----------------*/
lock_split.acquire(speculative_lock);
if (!root->isInnerNode) // splitting when tree has only root
{
cur = new InnerNode();
cur->init(splitKey, reachedLeafNode, newLeafNode);
root = cur;
}
else // need to retraverse & update parent
{
cur = reinterpret_cast<InnerNode*> (root);
while(cur->isInnerNode)
{
inners[i] = cur;
idx = std::lower_bound(cur->keys, cur->keys + cur->nKey, kv.key) - cur->keys;
if (idx < cur->nKey && cur->keys[idx] == kv.key) // TODO: this should always be false
idx ++;
ppos[i++] = idx;
cur = reinterpret_cast<InnerNode*> (cur->p_children[idx]);
}
parent = inners[--i];
child = newLeafNode;
while (true)
{
insert_pos = ppos[i--];
if (parent->nKey < MAX_INNER_SIZE)
{
parent->addKey(insert_pos, splitKey, child);
break;
}
else
{
newInnerNode = new InnerNode();
parent->nKey = mid;
if (insert_pos != mid)
{
new_splitKey = parent->keys[mid];
std::copy(parent->keys + mid + 1, parent->keys + MAX_INNER_SIZE, newInnerNode->keys);
std::copy(parent->p_children + mid + 1, parent->p_children + MAX_INNER_SIZE + 1, newInnerNode->p_children);
newInnerNode->nKey = MAX_INNER_SIZE - mid - 1;
if (insert_pos < mid)
parent->addKey(insert_pos, splitKey, child);
else
newInnerNode->addKey(insert_pos - mid - 1, splitKey, child);
}
else
{
new_splitKey = splitKey;
std::copy(parent->keys + mid, parent->keys + MAX_INNER_SIZE, newInnerNode->keys);
std::copy(parent->p_children + mid, parent->p_children + MAX_INNER_SIZE + 1, newInnerNode->p_children);
newInnerNode->p_children[0] = child;
newInnerNode->nKey = MAX_INNER_SIZE - mid;
}
splitKey = new_splitKey;
if (parent == root)
{
cur = new InnerNode(splitKey, parent, newInnerNode);
root = cur;
break;
}
parent = inners[i];
child = newInnerNode;
}
}
}
newLeafNode->Unlock();
lock_split.release();
/*---------------- End of Second Critical Section -----------------*/
}
}
void FPtree::updateParents(uint64_t splitKey, InnerNode* parent, BaseNode* child)
{
uint64_t mid = floor(MAX_INNER_SIZE / 2);
uint64_t new_splitKey, insert_pos;
while (true)
{
if (parent->nKey < MAX_INNER_SIZE)
{
insert_pos = parent->findChildIndex(splitKey);
parent->addKey(insert_pos, splitKey, child);
return;
}
else
{
InnerNode* newInnerNode = new InnerNode();
insert_pos = std::lower_bound(parent->keys, parent->keys + MAX_INNER_SIZE, splitKey) - parent->keys;
if (insert_pos < mid) { // insert into parent node
new_splitKey = parent->keys[mid];
parent->nKey = mid;
std::memmove(newInnerNode->keys, parent->keys + mid + 1, (MAX_INNER_SIZE - mid - 1)*sizeof(uint64_t));
std::memmove(newInnerNode->p_children, parent->p_children + mid + 1, (MAX_INNER_SIZE - mid)*sizeof(BaseNode*));
newInnerNode->nKey = MAX_INNER_SIZE - mid - 1;
parent->addKey(insert_pos, splitKey, child);
}
else if (insert_pos > mid) { // insert into new innernode
new_splitKey = parent->keys[mid];
parent->nKey = mid;
std::memmove(newInnerNode->keys, parent->keys + mid + 1, (MAX_INNER_SIZE - mid - 1)*sizeof(uint64_t));
std::memmove(newInnerNode->p_children, parent->p_children + mid + 1, (MAX_INNER_SIZE - mid)*sizeof(BaseNode*));
newInnerNode->nKey = MAX_INNER_SIZE - mid - 1;
newInnerNode->addKey(insert_pos - mid - 1, splitKey, child);
}
else { // only insert child to new innernode, splitkey does not change
new_splitKey = splitKey;
parent->nKey = mid;
std::memmove(newInnerNode->keys, parent->keys + mid, (MAX_INNER_SIZE - mid)*sizeof(uint64_t));
std::memmove(newInnerNode->p_children, parent->p_children + mid, (MAX_INNER_SIZE - mid + 1)*sizeof(BaseNode*));
newInnerNode->p_children[0] = child;
newInnerNode->nKey = MAX_INNER_SIZE - mid;
}
splitKey = new_splitKey;
if (parent == root)
{
root = new InnerNode(splitKey, parent, newInnerNode);
return;
}
parent = stack_innerNodes.pop();
child = newInnerNode;
}
}
}
bool FPtree::update(struct KV kv)
{
tbb::speculative_spin_rw_mutex::scoped_lock lock_update;
LeafNode* reachedLeafNode;
volatile uint64_t prevPos;
volatile Result decision = Result::Abort;
while (decision == Result::Abort)
{
// std::this_thread::sleep_for(std::chrono::nanoseconds(1));
lock_update.acquire(speculative_lock, false);
if ((reachedLeafNode = findLeaf(kv.key)) == nullptr) { lock_update.release(); return false; }
if (!reachedLeafNode->Lock()) { lock_update.release(); continue; }
prevPos = reachedLeafNode->findKVIndex(kv.key);
if (prevPos == MAX_LEAF_SIZE) // key not found
{
reachedLeafNode->Unlock();
lock_update.release();
return false;
}
decision = reachedLeafNode->isFull() ? Result::Split : Result::Update;
lock_update.release();
}
splitLeafAndUpdateInnerParents(reachedLeafNode, decision, kv, true, prevPos);
reachedLeafNode->Unlock();
return true;
}
bool FPtree::insert(struct KV kv)
{
tbb::speculative_spin_rw_mutex::scoped_lock lock_insert;
if (!root) // if tree is empty
{
lock_insert.acquire(speculative_lock, true);
if (!root)
{
#ifdef PMEM
struct argLeafNode args(kv);
TOID(struct List) ListHead = POBJ_ROOT(pop, struct List);
TOID(struct LeafNode) *dst = &D_RW(ListHead)->head;
POBJ_ALLOC(pop, dst, struct LeafNode, args.size, constructLeafNode, &args);
D_RW(ListHead)->head = *dst;
pmemobj_persist(pop, &D_RO(ListHead)->head, sizeof(D_RO(ListHead)->head));
root = (struct BaseNode *) pmemobj_direct((*dst).oid);
#else
root = new LeafNode();
reinterpret_cast<LeafNode*>(root)->lock = 1;
reinterpret_cast<LeafNode*> (root)->addKV(kv);
reinterpret_cast<LeafNode*>(root)->lock = 0;
#endif
lock_insert.release();
return true;
}
lock_insert.release();
}
Result decision = Result::Abort;
InnerNode* cursor;
LeafNode* reachedLeafNode;
uint64_t nKey;
int idx;
/*---------------- First Critical Section -----------------*/
{
TBB_BEGIN:
lock_insert.acquire(speculative_lock, false);
reachedLeafNode = findLeaf(kv.key);
if (!reachedLeafNode->Lock())
{
lock_insert.release();
goto TBB_BEGIN;
}
idx = reachedLeafNode->findKVIndex(kv.key);
if (idx != MAX_LEAF_SIZE)
reachedLeafNode->Unlock();
else
decision = reachedLeafNode->isFull() ? Result::Split : Result::Insert;
lock_insert.release();
}
/*---------------- End of First Critical Section -----------------*/
if (decision == Result::Abort) // kv already exists
return false;
splitLeafAndUpdateInnerParents(reachedLeafNode, decision, kv);
reachedLeafNode->Unlock();
return true;
}
uint64_t FPtree::splitLeaf(LeafNode* leaf)
{
uint64_t splitKey = findSplitKey(leaf);
#ifdef PMEM
TOID(struct LeafNode) *dst = &(leaf->p_next);
TOID(struct LeafNode) nextLeafNode = leaf->p_next;
// Get uLog from splitLogQueue
Log* log;
if (!splitLogQueue.pop(log)) { assert("Split log queue pop error!"); }
//set uLog.PCurrentLeaf to persistent address of Leaf
log->PCurrentLeaf = pmemobj_oid(leaf);
pmemobj_persist(pop, &(log->PCurrentLeaf), SIZE_PMEM_POINTER);
// Copy the content of Leaf into NewLeaf
struct argLeafNode args(leaf);
log->PLeaf = *dst;
POBJ_ALLOC(pop, dst, struct LeafNode, args.size, constructLeafNode, &args);
for (size_t i = 0; i < MAX_LEAF_SIZE; i++)
{
if (D_RO(*dst)->kv_pairs[i].key < splitKey)
D_RW(*dst)->bitmap.reset(i);
}
// Persist(NewLeaf.Bitmap)
pmemobj_persist(pop, &D_RO(*dst)->bitmap, sizeof(D_RO(*dst)->bitmap));
// Leaf.Bitmap = inverse(NewLeaf.Bitmap)
leaf->bitmap = D_RO(*dst)->bitmap;
if constexpr (MAX_LEAF_SIZE != 1) leaf->bitmap.flip();
// Persist(Leaf.Bitmap)
pmemobj_persist(pop, &leaf->bitmap, sizeof(leaf->bitmap));
// Persist(Leaf.Next)
D_RW(*dst)->p_next = nextLeafNode;
pmemobj_persist(pop, &D_RO(*dst)->p_next, sizeof(D_RO(*dst)->p_next));
// reset uLog
log->PCurrentLeaf = OID_NULL;
log->PLeaf = OID_NULL;
pmemobj_persist(pop, &(log->PCurrentLeaf), SIZE_PMEM_POINTER);
pmemobj_persist(pop, &(log->PLeaf), SIZE_PMEM_POINTER);
splitLogQueue.push(log);
#else
LeafNode* newLeafNode = new LeafNode(*leaf);
for (size_t i = 0; i < MAX_LEAF_SIZE; i++)
{
if (newLeafNode->kv_pairs[i].key < splitKey)
newLeafNode->bitmap.reset(i);
}
leaf->bitmap = newLeafNode->bitmap;
leaf->bitmap.flip();
leaf->p_next = newLeafNode;
#endif
return splitKey;
}
uint64_t FPtree::findSplitKey(LeafNode* leaf)
{
KV tempArr[MAX_LEAF_SIZE];
memcpy(tempArr, leaf->kv_pairs, sizeof(leaf->kv_pairs));
// TODO: find median in one pass instead of sorting
std::sort(std::begin(tempArr), std::end(tempArr), [] (const KV& kv1, const KV& kv2){
return kv1.key < kv2.key;
});
uint64_t mid = floor(MAX_LEAF_SIZE / 2);
uint64_t splitKey = tempArr[mid].key;
return splitKey;
}
#ifdef PMEM
void FPtree::recoverSplit(Log* uLog)
{
if (TOID_IS_NULL(uLog->PCurrentLeaf))
{
return;
}
if (TOID_IS_NULL(uLog->PLeaf))
{
uLog->PCurrentLeaf = OID_NULL;
uLog->PLeaf = OID_NULL;
return;
}
else
{
LeafNode* leaf = (struct LeafNode *) pmemobj_direct((uLog->PCurrentLeaf).oid);
uint64_t splitKey = findSplitKey(leaf);
if (leaf->isFull()) // Crashed before inverse the current leaf
{
for (size_t i = 0; i < MAX_LEAF_SIZE; i++)
{
if (D_RO(uLog->PLeaf)->kv_pairs[i].key < splitKey)
D_RW(uLog->PLeaf)->bitmap.reset(i);
}
// Persist(NewLeaf.Bitmap)
pmemobj_persist(pop, &D_RO(uLog->PLeaf)->bitmap, sizeof(D_RO(uLog->PLeaf)->bitmap));
// Leaf.Bitmap = inverse(NewLeaf.Bitmap)
D_RW(uLog->PCurrentLeaf)->bitmap = D_RO(uLog->PLeaf)->bitmap;
if constexpr (MAX_LEAF_SIZE != 1) D_RW(uLog->PCurrentLeaf)->bitmap.flip();
// Persist(Leaf.Bitmap)
pmemobj_persist(pop, &D_RO(uLog->PCurrentLeaf)->bitmap, sizeof(D_RO(uLog->PCurrentLeaf)->bitmap));
// Persist(Leaf.Next)
D_RW(uLog->PCurrentLeaf)->p_next = uLog->PLeaf;
pmemobj_persist(pop, &D_RO(uLog->PLeaf)->p_next, sizeof(D_RO(uLog->PLeaf)->p_next));
// reset uLog
uLog->PCurrentLeaf = OID_NULL;
uLog->PLeaf = OID_NULL;
return;
}
else // Crashed after inverse the current leaf
{
// Leaf.Bitmap = inverse(NewLeaf.Bitmap)
if constexpr (MAX_LEAF_SIZE != 1) D_RW(uLog->PCurrentLeaf)->bitmap.flip();
// Persist(Leaf.Bitmap)
pmemobj_persist(pop, &D_RO(uLog->PCurrentLeaf)->bitmap, sizeof(D_RO(uLog->PCurrentLeaf)->bitmap));
// Persist(Leaf.Next)
D_RW(uLog->PCurrentLeaf)->p_next = uLog->PLeaf;
pmemobj_persist(pop, &D_RO(uLog->PLeaf)->p_next, sizeof(D_RO(uLog->PLeaf)->p_next));
// reset uLog
uLog->PCurrentLeaf = OID_NULL;
uLog->PLeaf = OID_NULL;
return;
}
}
}
#endif
void FPtree::removeLeafAndMergeInnerNodes(short i, short indexNode_level)
{
InnerNode* temp, *left, *right, *parent = inners[i];
uint64_t left_idx, new_key = 0, child_idx = ppos[i];
if (child_idx == 0)
{
new_key = parent->keys[0];
parent->removeKey(child_idx, false);
if (indexNode_level >= 0 && inners[indexNode_level] != parent)
inners[indexNode_level]->keys[ppos[indexNode_level] - 1] = new_key;
}
else
parent->removeKey(child_idx - 1, true);
while (!parent->nKey) // parent has no key, merge with sibling
{
if (parent == root) // entire tree stores 1 kv, convert the only leafnode into root
{
temp = reinterpret_cast<InnerNode*> (root);
root = parent->p_children[0];
delete temp;
break;
}
parent = inners[--i];
child_idx = ppos[i];
left_idx = child_idx;
if (!(child_idx != 0 && tryBorrowKey(parent, child_idx, child_idx-1)) &&
!(child_idx != parent->nKey && tryBorrowKey(parent, child_idx, child_idx+1))) // if cannot borrow from any siblings
{
if (left_idx != 0)
left_idx --;
left = reinterpret_cast<InnerNode*> (parent->p_children[left_idx]);
right = reinterpret_cast<InnerNode*> (parent->p_children[left_idx + 1]);
if (left->nKey == 0)
{
right->addKey(0, parent->keys[left_idx], left->p_children[0], false);
delete left;
parent->removeKey(left_idx, false);
}
else
{
left->addKey(left->nKey, parent->keys[left_idx], right->p_children[0]);
delete right;
parent->removeKey(left_idx);
}
}
else
break;
}
}
bool FPtree::deleteKey(uint64_t key)
{
LeafNode* leaf, *sibling;
InnerNode *parent, *cur;
tbb::speculative_spin_rw_mutex::scoped_lock lock_delete;
Result decision = Result::Abort;
LeafNodeStat lstat;
short i, idx, indexNode_level, sib_level;
while (decision == Result::Abort)
{
i = 0; indexNode_level = -1, sib_level = -1;
sibling = nullptr;
/*---------------- Critical Section -----------------*/
lock_delete.acquire(speculative_lock, true);
if (!root) { lock_delete.release(); return false;} // empty tree
cur = reinterpret_cast<InnerNode*> (root);
while (cur->isInnerNode)
{
inners[i] = cur;
idx = std::lower_bound(cur->keys, cur->keys + cur->nKey, key) - cur->keys;
if (idx < cur->nKey && cur->keys[idx] == key) // just found index node
{
indexNode_level = i;
idx ++;
}
if (idx != 0)
sib_level = i;
ppos[i++] = idx;
cur = reinterpret_cast<InnerNode*> (cur->p_children[idx]);
}
parent = inners[--i];
leaf = reinterpret_cast<LeafNode*> (cur);
if (!leaf->Lock()) { lock_delete.release(); continue; }
leaf->getStat(key, lstat);
if (lstat.kv_idx == MAX_LEAF_SIZE) // key not found
{
decision = Result::NotFound;
leaf->Unlock();
}
else if (lstat.count > 1) // leaf contains key and other keys
{
if (indexNode_level >= 0) // key appears in an inner node, need to replace
inners[indexNode_level]->keys[ppos[indexNode_level] - 1] = lstat.min_key;
decision = Result::Remove;
}
else // leaf contains key only
{
if (parent) // try lock left sibling if exist, then remove leaf from parent and update inner nodes
{
if (sib_level >= 0) // left sibling exists
{
cur = reinterpret_cast<InnerNode*> (inners[sib_level]->p_children[ppos[sib_level] - 1]);
while (cur->isInnerNode)
cur = reinterpret_cast<InnerNode*> (cur->p_children[cur->nKey]);
sibling = reinterpret_cast<LeafNode*> (cur);
if (!sibling->Lock())
{
lock_delete.release(); leaf->Unlock(); continue;
}
}
removeLeafAndMergeInnerNodes(i, indexNode_level);
}
decision = Result::Delete;
}
lock_delete.release();
/*---------------- Critical Section -----------------*/
}
if (decision == Result::Remove)
{
leaf->bitmap.reset(lstat.kv_idx);
#ifdef PMEM
TOID(struct LeafNode) lf = pmemobj_oid(leaf);
pmemobj_persist(pop, &D_RO(lf)->bitmap, sizeof(D_RO(lf)->bitmap));
#endif
leaf->Unlock();
}
else if (decision == Result::Delete)
{
#ifdef PMEM
TOID(struct LeafNode) lf = pmemobj_oid(leaf);
// Get uLog from deleteLogQueue
Log* log;
if (!deleteLogQueue.pop(log)) { assert("Delete log queue pop error!"); }
//set uLog.PCurrentLeaf to persistent address of Leaf
log->PCurrentLeaf = lf;
pmemobj_persist(pop, &(log->PCurrentLeaf), SIZE_PMEM_POINTER);
if (sibling) // set and persist sibling's p_next, then unlock sibling node
{
TOID(struct LeafNode) sib = pmemobj_oid(sibling);
log->PLeaf = sib;
pmemobj_persist(pop, &(log->PLeaf), SIZE_PMEM_POINTER);
D_RW(sib)->p_next = D_RO(lf)->p_next;
pmemobj_persist(pop, &D_RO(sib)->p_next, sizeof(D_RO(sib)->p_next));
sibling->Unlock();
}
else if (parent) // the node to delete is left most node, set and persist list head instead
{
TOID(struct List) ListHead = POBJ_ROOT(pop, struct List);
D_RW(ListHead)->head = D_RO(lf)->p_next;
pmemobj_persist(pop, &D_RO(ListHead)->head, sizeof(D_RO(ListHead)->head));
}
else
{
TOID(struct List) ListHead = POBJ_ROOT(pop, struct List);
D_RW(ListHead)->head = OID_NULL;
pmemobj_persist(pop, &D_RO(ListHead)->head, sizeof(D_RO(ListHead)->head));
root = nullptr;
}
POBJ_FREE(&lf);
// reset uLog
log->PCurrentLeaf = OID_NULL;
log->PLeaf = OID_NULL;
pmemobj_persist(pop, &(log->PCurrentLeaf), SIZE_PMEM_POINTER);
pmemobj_persist(pop, &(log->PLeaf), SIZE_PMEM_POINTER);
deleteLogQueue.push(log);
#else
if (sibling)
{
sibling->p_next = leaf->p_next;
sibling->Unlock();
}
else if (!parent)
root = nullptr;
delete leaf;
#endif
}
return decision != Result::NotFound;
}
#ifdef PMEM
void FPtree::recoverDelete(Log* uLog)
{
TOID(struct List) ListHead = POBJ_ROOT(pop, struct List);
TOID(struct LeafNode) PHead = D_RW(ListHead)->head;
if( (!TOID_IS_NULL(uLog->PCurrentLeaf)) && (!TOID_IS_NULL(PHead)) )
{
D_RW(uLog->PLeaf)->p_next = D_RO(uLog->PCurrentLeaf)->p_next;
pmemobj_persist(pop, &D_RO(uLog->PLeaf)->p_next, SIZE_PMEM_POINTER);
D_RW(uLog->PLeaf)->Unlock();
POBJ_FREE(&(uLog->PCurrentLeaf));
}
else
{
if ( (!TOID_IS_NULL(uLog->PCurrentLeaf)) &&
((struct LeafNode *) pmemobj_direct((uLog->PCurrentLeaf).oid) ==
(struct LeafNode *) pmemobj_direct(PHead.oid))
)
{
PHead = D_RO(uLog->PCurrentLeaf)->p_next;
pmemobj_persist(pop, &PHead, SIZE_PMEM_POINTER);
POBJ_FREE(&(uLog->PCurrentLeaf));
}
else
{
if ( (!TOID_IS_NULL(uLog->PCurrentLeaf)) &&
((struct LeafNode *) pmemobj_direct((D_RO(uLog->PCurrentLeaf)->p_next).oid) ==
(struct LeafNode *) pmemobj_direct(PHead.oid))
)
POBJ_FREE(&(uLog->PCurrentLeaf));
else { /* reset uLog */ }
}
}
// reset uLog
uLog->PCurrentLeaf = OID_NULL;
uLog->PLeaf = OID_NULL;
return;
}
#endif
bool FPtree::tryBorrowKey(InnerNode* parent, uint64_t receiver_idx, uint64_t sender_idx)
{
InnerNode* sender = reinterpret_cast<InnerNode*> (parent->p_children[sender_idx]);
if (sender->nKey <= 1) // sibling has only 1 key, cannot borrow
return false;
InnerNode* receiver = reinterpret_cast<InnerNode*> (parent->p_children[receiver_idx]);
if (receiver_idx < sender_idx) // borrow from right sibling
{
receiver->addKey(0, parent->keys[receiver_idx], sender->p_children[0]);
parent->keys[receiver_idx] = sender->keys[0];
sender->removeKey(0, false);
}
else // borrow from left sibling
{
receiver->addKey(0, receiver->keys[0], sender->p_children[sender->nKey], false);
parent->keys[sender_idx] = sender->keys[sender->nKey-1];
sender->removeKey(sender->nKey-1);
}
return true;
}
inline uint64_t FPtree::minKey(BaseNode* node)
{
while (node->isInnerNode)
node = reinterpret_cast<InnerNode*> (node)->p_children[0];
return reinterpret_cast<LeafNode*> (node)->minKey();
}
LeafNode* FPtree::minLeaf(BaseNode* node)
{
while(node->isInnerNode)
node = reinterpret_cast<InnerNode*> (node)->p_children[0];
return reinterpret_cast<LeafNode*> (node);
}
void FPtree::sortKV()
{
uint64_t j = 0;
for (uint64_t i = 0; i < MAX_LEAF_SIZE; i++)
if (this->current_leaf->bitmap.test(i))
this->volatile_current_kv[j++] = this->current_leaf->kv_pairs[i];
this->size_volatile_kv = j;
std::sort(std::begin(this->volatile_current_kv), std::begin(this->volatile_current_kv) + this->size_volatile_kv,
[] (const KV& kv1, const KV& kv2){
return kv1.key < kv2.key;
});
}
void FPtree::scanInitialize(uint64_t key)
{
if (!root)
return;
this->current_leaf = root->isInnerNode? findLeaf(key) : reinterpret_cast<LeafNode*> (root);
while (this->current_leaf != nullptr)
{
this->sortKV();
for (uint64_t i = 0; i < this->size_volatile_kv; i++)
{
if (this->volatile_current_kv[i].key >= key)
{
this->bitmap_idx = i;
return;
}
}
#ifdef PMEM
this->current_leaf = (struct LeafNode *) pmemobj_direct((this->current_leaf->p_next).oid);
#else
this->current_leaf = this->current_leaf->p_next;
#endif
}
}
KV FPtree::scanNext()
{
assert(this->current_leaf != nullptr && "Current scan node was deleted!");
struct KV kv = this->volatile_current_kv[this->bitmap_idx++];
if (this->bitmap_idx == this->size_volatile_kv)
{
#ifdef PMEM
this->current_leaf = (struct LeafNode *) pmemobj_direct((this->current_leaf->p_next).oid);
#else
this->current_leaf = this->current_leaf->p_next;
#endif
if (this->current_leaf != nullptr)
{
this->sortKV();
this->bitmap_idx = 0;
}
}
return kv;
}
bool FPtree::scanComplete()
{
return this->current_leaf == nullptr;
}
uint64_t FPtree::rangeScan(uint64_t key, uint64_t scan_size, char* result)
{
LeafNode* leaf, * next_leaf;
std::vector<KV> records;
records.reserve(scan_size);
uint64_t i;
tbb::speculative_spin_rw_mutex::scoped_lock lock_scan;
while (true)
{
lock_scan.acquire(speculative_lock, false);
if ((leaf = findLeaf(key)) == nullptr) { lock_scan.release(); return 0; }
if (!leaf->Lock()) { lock_scan.release(); continue; }
for (i = 0; i < MAX_LEAF_SIZE; i++)
if (leaf->bitmap.test(i) && leaf->kv_pairs[i].key >= key)
records.push_back(leaf->kv_pairs[i]);
while (records.size() < scan_size)
{
#ifdef PMEM
if (TOID_IS_NULL(leaf->p_next))
break;
next_leaf = (struct LeafNode *) pmemobj_direct((leaf->p_next).oid);
#else
if ((next_leaf = leaf->p_next) == nullptr)
break;
#endif
while (!next_leaf->Lock())
std::this_thread::sleep_for(std::chrono::nanoseconds(1));
leaf->Unlock();
leaf = next_leaf;
for (i = 0; i < MAX_LEAF_SIZE; i++)
if (leaf->bitmap.test(i))
records.push_back(leaf->kv_pairs[i]);
}
lock_scan.release();
break;
}
if (leaf && leaf->lock == 1)
leaf->Unlock();
std::sort(records.begin(), records.end(), [] (const KV& kv1, const KV& kv2) {
return kv1.key < kv2.key;
});
// result = new char[sizeof(KV) * records.size()];
i = records.size() > scan_size? scan_size : records.size();
memcpy(result, records.data(), sizeof(KV) * i);
return i;
}
#ifdef PMEM
bool FPtree::bulkLoad(float load_factor = 1)
{
TOID(struct List) ListHead = POBJ_ROOT(pop, struct List);
TOID(struct LeafNode) cursor = D_RW(ListHead)->head;
if (TOID_IS_NULL(cursor)) { this->root = nullptr; return true; }
if (TOID_IS_NULL(D_RO(cursor)->p_next))
{ root = (struct BaseNode *) pmemobj_direct(cursor.oid); return true;}
std::vector<uint64_t> min_keys;
std::vector<LeafNode*> child_nodes;
uint64_t total_leaves = 0;
LeafNode* temp_leafnode;
while(!TOID_IS_NULL(cursor)) // record min keys and leaf nodes
{
temp_leafnode = (struct LeafNode *) pmemobj_direct(cursor.oid);
child_nodes.push_back(temp_leafnode);
min_keys.push_back(temp_leafnode->minKey());
cursor = D_RW(cursor)->p_next;
}
total_leaves = min_keys.size();
min_keys.erase(min_keys.begin());
InnerNode* new_root = new InnerNode();
uint64_t idx = 0;
uint64_t root_size = total_leaves <= MAX_INNER_SIZE ?
total_leaves : MAX_INNER_SIZE + 1;
for (; idx < root_size; idx++) // recovery the root node
{
if (idx < root_size - 1)
new_root->keys[idx] = min_keys[idx];
new_root->p_children[idx] = child_nodes[idx];
}
new_root->nKey = root_size - 1;
this->root = reinterpret_cast<BaseNode*> (new_root);
if (total_leaves > MAX_INNER_SIZE)
{
idx--;
right_most_innnerNode = reinterpret_cast<InnerNode*>(this->root);
for (; idx < min_keys.size(); idx++) // Index entries for leaf pages always entered into right-most index page
{
findLeafAndPushInnerNodes(min_keys[idx]);
right_most_innnerNode = stack_innerNodes.pop();
updateParents(min_keys[idx], right_most_innnerNode, child_nodes[idx+1]);
}
}
return true;
}
#endif
/*
Use case
uint64_t tick = rdtsc();
Put program between
std::cout << rdtsc() - tick << std::endl;
*/
uint64_t rdtsc(){
unsigned int lo,hi;
__asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
return ((uint64_t)hi << 32) | lo;
}
| 33.471396 | 131 | 0.548825 | mkatsa |
aec41824da20a509025fbe466e62fd40970fc2aa | 3,221 | cc | C++ | driver/mmio/coherent_allocator.cc | ghollingworth/libedgetpu | d37e668cd9ef0e657b9e4e413df53f370532e87e | [
"Apache-2.0"
] | 99 | 2020-06-09T05:52:44.000Z | 2022-03-08T06:06:55.000Z | driver/mmio/coherent_allocator.cc | ghollingworth/libedgetpu | d37e668cd9ef0e657b9e4e413df53f370532e87e | [
"Apache-2.0"
] | 35 | 2020-06-09T15:00:26.000Z | 2022-03-15T10:22:32.000Z | driver/mmio/coherent_allocator.cc | ghollingworth/libedgetpu | d37e668cd9ef0e657b9e4e413df53f370532e87e | [
"Apache-2.0"
] | 23 | 2020-06-09T14:50:54.000Z | 2022-03-15T11:18:16.000Z | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "driver/mmio/coherent_allocator.h"
#include "api/buffer.h"
#include "port/aligned_malloc.h"
#include "port/errors.h"
#include "port/status_macros.h"
#include "port/std_mutex_lock.h"
#include "port/stringprintf.h"
namespace platforms {
namespace darwinn {
namespace driver {
namespace {
constexpr const size_t kDefaultMaxCoherentBytes = 0x10000;
constexpr const size_t kDefaultAlignmentBytes = 8;
} // namespace
CoherentAllocator::CoherentAllocator(int alignment_bytes, size_t size_bytes)
: alignment_bytes_(alignment_bytes), total_size_bytes_(size_bytes) {
CHECK_GT(total_size_bytes_, 0);
}
CoherentAllocator::CoherentAllocator()
: CoherentAllocator(kDefaultAlignmentBytes, kDefaultMaxCoherentBytes) {}
Status CoherentAllocator::Open() {
StdMutexLock lock(&mutex_);
if (coherent_memory_base_ != nullptr) {
return FailedPreconditionError("Device already open.");
}
ASSIGN_OR_RETURN(coherent_memory_base_, DoOpen(total_size_bytes_));
return Status(); // OK
}
StatusOr<char *> CoherentAllocator::DoOpen(size_t size_bytes) {
char *mem_base =
static_cast<char *>(aligned_malloc(total_size_bytes_, alignment_bytes_));
if (mem_base == nullptr) {
return FailedPreconditionError(
StringPrintf("Could not malloc %zu bytes.", total_size_bytes_));
}
memset(mem_base, 0, size_bytes);
return mem_base; // OK
}
StatusOr<Buffer> CoherentAllocator::Allocate(size_t size_bytes) {
StdMutexLock lock(&mutex_);
if (size_bytes == 0) {
return FailedPreconditionError("Allocate null size.");
}
if (coherent_memory_base_ == nullptr) {
return FailedPreconditionError("Not Opened.");
}
if ((allocated_bytes_ + size_bytes) > total_size_bytes_) {
return FailedPreconditionError(StringPrintf(
"CoherentAllocator: Allocate size = %zu and no memory (total = %zu).",
size_bytes, total_size_bytes_));
}
char *p = coherent_memory_base_ + allocated_bytes_;
// Power of 2 pointer arithmetic: align the block boundary on chip specific
// byte alignment
size_t mask = alignment_bytes_ - 1;
allocated_bytes_ += (size_bytes + mask) & ~mask;
return Buffer(p, size_bytes);
}
Status CoherentAllocator::DoClose(char *mem_base, size_t size_bytes) {
if (mem_base != nullptr) {
aligned_free(mem_base);
}
return Status(); // OK
}
Status CoherentAllocator::Close() {
StdMutexLock lock(&mutex_);
auto status = DoClose(coherent_memory_base_, total_size_bytes_);
// Resets state.
allocated_bytes_ = 0;
coherent_memory_base_ = nullptr;
return status;
}
} // namespace driver
} // namespace darwinn
} // namespace platforms
| 29.281818 | 79 | 0.737659 | ghollingworth |
aec4fa5f013ce3542d2a8234f7c2c087f2eb5e70 | 15,288 | cpp | C++ | ess/src/v20201111/model/FlowCreateApprover.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | ess/src/v20201111/model/FlowCreateApprover.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | ess/src/v20201111/model/FlowCreateApprover.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/ess/v20201111/model/FlowCreateApprover.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Ess::V20201111::Model;
using namespace std;
FlowCreateApprover::FlowCreateApprover() :
m_approverTypeHasBeenSet(false),
m_organizationNameHasBeenSet(false),
m_requiredHasBeenSet(false),
m_approverNameHasBeenSet(false),
m_approverMobileHasBeenSet(false),
m_approverIdCardNumberHasBeenSet(false),
m_approverIdCardTypeHasBeenSet(false),
m_recipientIdHasBeenSet(false),
m_userIdHasBeenSet(false),
m_isFullTextHasBeenSet(false),
m_preReadTimeHasBeenSet(false),
m_notifyTypeHasBeenSet(false),
m_verifyChannelHasBeenSet(false)
{
}
CoreInternalOutcome FlowCreateApprover::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("ApproverType") && !value["ApproverType"].IsNull())
{
if (!value["ApproverType"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `FlowCreateApprover.ApproverType` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_approverType = value["ApproverType"].GetInt64();
m_approverTypeHasBeenSet = true;
}
if (value.HasMember("OrganizationName") && !value["OrganizationName"].IsNull())
{
if (!value["OrganizationName"].IsString())
{
return CoreInternalOutcome(Core::Error("response `FlowCreateApprover.OrganizationName` IsString=false incorrectly").SetRequestId(requestId));
}
m_organizationName = string(value["OrganizationName"].GetString());
m_organizationNameHasBeenSet = true;
}
if (value.HasMember("Required") && !value["Required"].IsNull())
{
if (!value["Required"].IsBool())
{
return CoreInternalOutcome(Core::Error("response `FlowCreateApprover.Required` IsBool=false incorrectly").SetRequestId(requestId));
}
m_required = value["Required"].GetBool();
m_requiredHasBeenSet = true;
}
if (value.HasMember("ApproverName") && !value["ApproverName"].IsNull())
{
if (!value["ApproverName"].IsString())
{
return CoreInternalOutcome(Core::Error("response `FlowCreateApprover.ApproverName` IsString=false incorrectly").SetRequestId(requestId));
}
m_approverName = string(value["ApproverName"].GetString());
m_approverNameHasBeenSet = true;
}
if (value.HasMember("ApproverMobile") && !value["ApproverMobile"].IsNull())
{
if (!value["ApproverMobile"].IsString())
{
return CoreInternalOutcome(Core::Error("response `FlowCreateApprover.ApproverMobile` IsString=false incorrectly").SetRequestId(requestId));
}
m_approverMobile = string(value["ApproverMobile"].GetString());
m_approverMobileHasBeenSet = true;
}
if (value.HasMember("ApproverIdCardNumber") && !value["ApproverIdCardNumber"].IsNull())
{
if (!value["ApproverIdCardNumber"].IsString())
{
return CoreInternalOutcome(Core::Error("response `FlowCreateApprover.ApproverIdCardNumber` IsString=false incorrectly").SetRequestId(requestId));
}
m_approverIdCardNumber = string(value["ApproverIdCardNumber"].GetString());
m_approverIdCardNumberHasBeenSet = true;
}
if (value.HasMember("ApproverIdCardType") && !value["ApproverIdCardType"].IsNull())
{
if (!value["ApproverIdCardType"].IsString())
{
return CoreInternalOutcome(Core::Error("response `FlowCreateApprover.ApproverIdCardType` IsString=false incorrectly").SetRequestId(requestId));
}
m_approverIdCardType = string(value["ApproverIdCardType"].GetString());
m_approverIdCardTypeHasBeenSet = true;
}
if (value.HasMember("RecipientId") && !value["RecipientId"].IsNull())
{
if (!value["RecipientId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `FlowCreateApprover.RecipientId` IsString=false incorrectly").SetRequestId(requestId));
}
m_recipientId = string(value["RecipientId"].GetString());
m_recipientIdHasBeenSet = true;
}
if (value.HasMember("UserId") && !value["UserId"].IsNull())
{
if (!value["UserId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `FlowCreateApprover.UserId` IsString=false incorrectly").SetRequestId(requestId));
}
m_userId = string(value["UserId"].GetString());
m_userIdHasBeenSet = true;
}
if (value.HasMember("IsFullText") && !value["IsFullText"].IsNull())
{
if (!value["IsFullText"].IsBool())
{
return CoreInternalOutcome(Core::Error("response `FlowCreateApprover.IsFullText` IsBool=false incorrectly").SetRequestId(requestId));
}
m_isFullText = value["IsFullText"].GetBool();
m_isFullTextHasBeenSet = true;
}
if (value.HasMember("PreReadTime") && !value["PreReadTime"].IsNull())
{
if (!value["PreReadTime"].IsUint64())
{
return CoreInternalOutcome(Core::Error("response `FlowCreateApprover.PreReadTime` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_preReadTime = value["PreReadTime"].GetUint64();
m_preReadTimeHasBeenSet = true;
}
if (value.HasMember("NotifyType") && !value["NotifyType"].IsNull())
{
if (!value["NotifyType"].IsString())
{
return CoreInternalOutcome(Core::Error("response `FlowCreateApprover.NotifyType` IsString=false incorrectly").SetRequestId(requestId));
}
m_notifyType = string(value["NotifyType"].GetString());
m_notifyTypeHasBeenSet = true;
}
if (value.HasMember("VerifyChannel") && !value["VerifyChannel"].IsNull())
{
if (!value["VerifyChannel"].IsArray())
return CoreInternalOutcome(Core::Error("response `FlowCreateApprover.VerifyChannel` is not array type"));
const rapidjson::Value &tmpValue = value["VerifyChannel"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
m_verifyChannel.push_back((*itr).GetString());
}
m_verifyChannelHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void FlowCreateApprover::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_approverTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ApproverType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_approverType, allocator);
}
if (m_organizationNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "OrganizationName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_organizationName.c_str(), allocator).Move(), allocator);
}
if (m_requiredHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Required";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_required, allocator);
}
if (m_approverNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ApproverName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_approverName.c_str(), allocator).Move(), allocator);
}
if (m_approverMobileHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ApproverMobile";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_approverMobile.c_str(), allocator).Move(), allocator);
}
if (m_approverIdCardNumberHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ApproverIdCardNumber";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_approverIdCardNumber.c_str(), allocator).Move(), allocator);
}
if (m_approverIdCardTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ApproverIdCardType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_approverIdCardType.c_str(), allocator).Move(), allocator);
}
if (m_recipientIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RecipientId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_recipientId.c_str(), allocator).Move(), allocator);
}
if (m_userIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "UserId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_userId.c_str(), allocator).Move(), allocator);
}
if (m_isFullTextHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "IsFullText";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_isFullText, allocator);
}
if (m_preReadTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PreReadTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_preReadTime, allocator);
}
if (m_notifyTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "NotifyType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_notifyType.c_str(), allocator).Move(), allocator);
}
if (m_verifyChannelHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "VerifyChannel";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_verifyChannel.begin(); itr != m_verifyChannel.end(); ++itr)
{
value[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
}
int64_t FlowCreateApprover::GetApproverType() const
{
return m_approverType;
}
void FlowCreateApprover::SetApproverType(const int64_t& _approverType)
{
m_approverType = _approverType;
m_approverTypeHasBeenSet = true;
}
bool FlowCreateApprover::ApproverTypeHasBeenSet() const
{
return m_approverTypeHasBeenSet;
}
string FlowCreateApprover::GetOrganizationName() const
{
return m_organizationName;
}
void FlowCreateApprover::SetOrganizationName(const string& _organizationName)
{
m_organizationName = _organizationName;
m_organizationNameHasBeenSet = true;
}
bool FlowCreateApprover::OrganizationNameHasBeenSet() const
{
return m_organizationNameHasBeenSet;
}
bool FlowCreateApprover::GetRequired() const
{
return m_required;
}
void FlowCreateApprover::SetRequired(const bool& _required)
{
m_required = _required;
m_requiredHasBeenSet = true;
}
bool FlowCreateApprover::RequiredHasBeenSet() const
{
return m_requiredHasBeenSet;
}
string FlowCreateApprover::GetApproverName() const
{
return m_approverName;
}
void FlowCreateApprover::SetApproverName(const string& _approverName)
{
m_approverName = _approverName;
m_approverNameHasBeenSet = true;
}
bool FlowCreateApprover::ApproverNameHasBeenSet() const
{
return m_approverNameHasBeenSet;
}
string FlowCreateApprover::GetApproverMobile() const
{
return m_approverMobile;
}
void FlowCreateApprover::SetApproverMobile(const string& _approverMobile)
{
m_approverMobile = _approverMobile;
m_approverMobileHasBeenSet = true;
}
bool FlowCreateApprover::ApproverMobileHasBeenSet() const
{
return m_approverMobileHasBeenSet;
}
string FlowCreateApprover::GetApproverIdCardNumber() const
{
return m_approverIdCardNumber;
}
void FlowCreateApprover::SetApproverIdCardNumber(const string& _approverIdCardNumber)
{
m_approverIdCardNumber = _approverIdCardNumber;
m_approverIdCardNumberHasBeenSet = true;
}
bool FlowCreateApprover::ApproverIdCardNumberHasBeenSet() const
{
return m_approverIdCardNumberHasBeenSet;
}
string FlowCreateApprover::GetApproverIdCardType() const
{
return m_approverIdCardType;
}
void FlowCreateApprover::SetApproverIdCardType(const string& _approverIdCardType)
{
m_approverIdCardType = _approverIdCardType;
m_approverIdCardTypeHasBeenSet = true;
}
bool FlowCreateApprover::ApproverIdCardTypeHasBeenSet() const
{
return m_approverIdCardTypeHasBeenSet;
}
string FlowCreateApprover::GetRecipientId() const
{
return m_recipientId;
}
void FlowCreateApprover::SetRecipientId(const string& _recipientId)
{
m_recipientId = _recipientId;
m_recipientIdHasBeenSet = true;
}
bool FlowCreateApprover::RecipientIdHasBeenSet() const
{
return m_recipientIdHasBeenSet;
}
string FlowCreateApprover::GetUserId() const
{
return m_userId;
}
void FlowCreateApprover::SetUserId(const string& _userId)
{
m_userId = _userId;
m_userIdHasBeenSet = true;
}
bool FlowCreateApprover::UserIdHasBeenSet() const
{
return m_userIdHasBeenSet;
}
bool FlowCreateApprover::GetIsFullText() const
{
return m_isFullText;
}
void FlowCreateApprover::SetIsFullText(const bool& _isFullText)
{
m_isFullText = _isFullText;
m_isFullTextHasBeenSet = true;
}
bool FlowCreateApprover::IsFullTextHasBeenSet() const
{
return m_isFullTextHasBeenSet;
}
uint64_t FlowCreateApprover::GetPreReadTime() const
{
return m_preReadTime;
}
void FlowCreateApprover::SetPreReadTime(const uint64_t& _preReadTime)
{
m_preReadTime = _preReadTime;
m_preReadTimeHasBeenSet = true;
}
bool FlowCreateApprover::PreReadTimeHasBeenSet() const
{
return m_preReadTimeHasBeenSet;
}
string FlowCreateApprover::GetNotifyType() const
{
return m_notifyType;
}
void FlowCreateApprover::SetNotifyType(const string& _notifyType)
{
m_notifyType = _notifyType;
m_notifyTypeHasBeenSet = true;
}
bool FlowCreateApprover::NotifyTypeHasBeenSet() const
{
return m_notifyTypeHasBeenSet;
}
vector<string> FlowCreateApprover::GetVerifyChannel() const
{
return m_verifyChannel;
}
void FlowCreateApprover::SetVerifyChannel(const vector<string>& _verifyChannel)
{
m_verifyChannel = _verifyChannel;
m_verifyChannelHasBeenSet = true;
}
bool FlowCreateApprover::VerifyChannelHasBeenSet() const
{
return m_verifyChannelHasBeenSet;
}
| 30.273267 | 157 | 0.699241 | suluner |
aec6d145325c12f73507b85aeee31a2a9738846e | 1,330 | cpp | C++ | machine-learning/small-tasks/f-score.cpp | nothingelsematters/university | 5561969b1b11678228aaf7e6660e8b1a93d10294 | [
"WTFPL"
] | 1 | 2018-06-03T17:48:50.000Z | 2018-06-03T17:48:50.000Z | machine-learning/small-tasks/f-score.cpp | nothingelsematters/University | b1e188cb59e5a436731b92c914494626a99e1ae0 | [
"WTFPL"
] | null | null | null | machine-learning/small-tasks/f-score.cpp | nothingelsematters/University | b1e188cb59e5a436731b92c914494626a99e1ae0 | [
"WTFPL"
] | 14 | 2019-04-07T21:27:09.000Z | 2021-12-05T13:37:25.000Z | #include <iostream>
#include <iomanip>
long double harmonic_mean(long double a, long double b) {
return a + b == 0 ? 0 : 2 * a * b / (a + b);
}
int main() {
size_t size;
std::cin >> size;
unsigned int sum = 0;
unsigned int column[size] = {};
unsigned int row[size] = {};
unsigned int trace[size];
for (size_t i = 0; i < size; ++i) {
for (size_t j = 0; j < size; ++j) {
unsigned int value;
std::cin >> value;
if (i == j) {
trace[i] = value;
}
sum += value;
row[i] += value;
column[j] += value;
}
}
long double precision = 0;
long double recall = 0;
long double score = 0;
for (size_t i = 0; i < size; ++i) {
long double local_precision = row[i] == 0 ? 0 : (double) trace[i] / row[i];
long double local_recall = column[i] == 0 ? 0 : (double) trace[i] / column[i];
long double weight = row[i];
precision += local_precision * weight;
recall += local_recall * weight;
score += harmonic_mean(local_precision, local_recall) * weight;
}
std::cout
<< std::setprecision(9)
<< harmonic_mean(precision, recall) / sum << '\n' // macro
<< score / sum << '\n'; // micro
return 0;
}
| 25.09434 | 86 | 0.502256 | nothingelsematters |
aec923f14b582423c7c0faad661e1a3bfc8b1fa1 | 1,792 | tpp | C++ | src/hypro/algorithms/reachability/contexts/ContextFactory.tpp | hypro/hypro | 52ae4ffe0a8427977fce8d7979fffb82a1bc28f6 | [
"MIT"
] | 22 | 2016-10-05T12:19:01.000Z | 2022-01-23T09:14:41.000Z | src/hypro/algorithms/reachability/contexts/ContextFactory.tpp | hypro/hypro | 52ae4ffe0a8427977fce8d7979fffb82a1bc28f6 | [
"MIT"
] | 23 | 2017-05-08T15:02:39.000Z | 2021-11-03T16:43:39.000Z | src/hypro/algorithms/reachability/contexts/ContextFactory.tpp | hypro/hypro | 52ae4ffe0a8427977fce8d7979fffb82a1bc28f6 | [
"MIT"
] | 12 | 2017-06-07T23:51:09.000Z | 2022-01-04T13:06:21.000Z | #include "ContextFactory.h"
namespace hypro {
template <typename State>
IContext* ContextFactory<State>::createContext( const std::shared_ptr<Task<State>>& t,
const Strategy<State>& strat,
WorkQueue<std::shared_ptr<Task<State>>>* localQueue,
WorkQueue<std::shared_ptr<Task<State>>>* localCEXQueue,
Flowpipe<State>& localSegments,
hypro::ReachabilitySettings& settings ) {
if(SettingsProvider<State>::getInstance().getStrategy().getParameters(t->btInfo.btLevel).representation_type == representation_name::polytope_t){
DEBUG("hydra.worker", "Using TPoly context!");
return new TemplatePolyhedronContext<State>(t,strat,localQueue,localCEXQueue,localSegments,settings);
}
if ( SettingsProvider<State>::getInstance().useDecider() ) {
auto locType = SettingsProvider<State>::getInstance().getLocationTypeMap().find( t->treeNode->getStateAtLevel( t->btInfo.btLevel ).getLocation() )->second;
if ( locType == hypro::LOCATIONTYPE::TIMEDLOC ) {
// either use on full timed automa or if context switch is enabled
if ( SettingsProvider<State>::getInstance().isFullTimed() || SettingsProvider<State>::getInstance().useContextSwitch() ) {
DEBUG( "hydra.worker", "Using full timed context!" );
return new TimedContext<State>( t, strat, localQueue, localCEXQueue, localSegments, settings );
}
} else if ( locType == hypro::LOCATIONTYPE::RECTANGULARLOC ) {
DEBUG( "hydra.worker", "Using lti context, but actually is rectangular!" );
return new LTIContext<State>( t, strat, localQueue, localCEXQueue, localSegments, settings );
}
}
DEBUG( "hydra.worker", "Using standard LTI context!" );
return new LTIContext<State>( t, strat, localQueue, localCEXQueue, localSegments, settings );
}
} // namespace hypro
| 54.30303 | 157 | 0.719866 | hypro |
aed30bdabeeb57f2d1140cbb35e0babf9f062166 | 6,273 | cxx | C++ | xp_comm_proj/rd_dbase/dbfhdr.cxx | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | 3 | 2020-08-03T08:52:20.000Z | 2021-04-10T11:55:49.000Z | xp_comm_proj/rd_dbase/dbfhdr.cxx | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | null | null | null | xp_comm_proj/rd_dbase/dbfhdr.cxx | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | 1 | 2021-06-08T18:16:45.000Z | 2021-06-08T18:16:45.000Z | //
// This file contains the source code for the dBASE file header object.
// This object provides utilities to read and manage a dBASE (dbf)
// header record.
//
#include <stdio.h>
#ifdef MSDOS
#include <basetsd.h>
#endif
#include "dbfhdr.h"
#include "gsbyteu.h"
static DBF_ByteUtil_c ByteUtil; // used to swap bytes
//
// Define constant for the # of bytes in the first part of the
// header
//
const unsigned long HeaderPart1BufferLength = 12;
//
// Define constants for the start of header record items.
//
const unsigned long VersionStart = 0;
const unsigned long DateStart = 1;
const unsigned long NumberOfRowsStart = 4;
const unsigned long HeaderLengthStart = 8;
const unsigned long RowLengthStart = 10;
//
// Define constants for the lengths of header record items.
//
const unsigned long VersionSize = 1;
const unsigned long DateSize = 3;
const unsigned long NumberOfRowsSize = 4;
const unsigned long HeaderLengthSize = 2;
const unsigned long RowLengthSize = 2;
//
// The default constructor. If this is used, then the FileName method
// should be used to set the file name and the FileStream method MUST
// be used to set the file stream. The file must have already been
// opened before this constructor is called.
//
XP_GIS_DBF_Header_c::XP_GIS_DBF_Header_c()
{
_FileName = NULL;
_FileStream = NULL;
}
//
// The overloaded constructor. This version sets the file name and
// file stream. The file must have already been opened before this
// constructor is called.
//
XP_GIS_DBF_Header_c::XP_GIS_DBF_Header_c(const char *DBFFileName,
ifstream &DBFFileStream)
{
_FileName = NULL;
_FileStream = NULL;
FileName(DBFFileName);
FileStream(DBFFileStream);
ReadHeader();
}
//
// The destructor. When destroyed, this object does not close the file.
//
XP_GIS_DBF_Header_c::~XP_GIS_DBF_Header_c()
{
}
//
// The copy constructor.
//
XP_GIS_DBF_Header_c::XP_GIS_DBF_Header_c(const XP_GIS_DBF_Header_c &object)
{
*this = object;
}
//
// The assignment operator.
//
XP_GIS_DBF_Header_c &XP_GIS_DBF_Header_c::operator=(
const XP_GIS_DBF_Header_c &object)
{
strcpy(_FileName,object.FileName());
_FileStream = object._FileStream;
_Version = object._Version;
_HeaderLength = object._HeaderLength;
_RowLength = object._RowLength;
_NumberOfRows = object._NumberOfRows;
strcpy(_Date,object._Date);
return *this;
}
//
// Method to set the dBASE file name.
//
const char *XP_GIS_DBF_Header_c::FileName(const char *DBFFileName)
{
_FileName = (char *) DBFFileName;
return (_FileName);
}
//
// Method to set the dBASE file stream.
//
ifstream &XP_GIS_DBF_Header_c::FileStream(ifstream &DBFFileStream)
{
_FileStream = &DBFFileStream;
return *_FileStream;
}
//
// Method to read the dBASE file header.
// If succesful, this method returns XP_GIS_OK. Otherwise, it
// returns one of the following:
// XP_GIS_NOT_OPEN
// XP_GIS_SEEK_ERROR
// XP_GIS_EOF
// XP_GIS_READ_ERROR
// XP_GIS_IO_ERROR
// XP_GIS_BAD_MAGIC_NUMBER
//
unsigned long XP_GIS_DBF_Header_c::ReadHeader()
{
unsigned char HeaderPart1Buffer[HeaderPart1BufferLength];
unsigned short TemporaryShort;
#ifdef MSDOS
UINT32 TemporaryInt;
#else
uint32_t TemporaryInt;
#endif
//
// Make sure the file is open.
//
#ifdef MSDOS
if (!_FileStream->is_open())
{
return XP_GIS_NOT_OPEN;
}
#endif
//
// Seek to the start of the file.
//
if (!_FileStream->seekg(0,ios::beg))
{
return XP_GIS_SEEK_ERROR;
}
//
// Read the header.
//
if (!_FileStream->read((char*)HeaderPart1Buffer,HeaderPart1BufferLength))
{
if (_FileStream->eof())
{
return XP_GIS_EOF;
}
else
{
return XP_GIS_READ_ERROR;
}
}
if (_FileStream->gcount() != HeaderPart1BufferLength)
{
return XP_GIS_IO_ERROR;
}
//
// Parse out the magic number
//
if (HeaderPart1Buffer[VersionStart] != 3)
{
return XP_GIS_BAD_MAGIC_NUMBER;
}
_Version = (unsigned long) HeaderPart1Buffer[VersionStart];
//
// Parse out the date.
//
_Date[0] = '1';
_Date[1] = '9';
sprintf(&_Date[2],"%2.2d",(int) HeaderPart1Buffer[DateStart]);
_Date[4] = '/'; // separator
sprintf(&_Date[5],"%2.2d",(int) HeaderPart1Buffer[DateStart+1]);
_Date[7] = '/'; // separator
sprintf(&_Date[8],"%2.2d",(int) HeaderPart1Buffer[DateStart+2]);
_Date[10] = '\0'; // terminator
//
// Parse out the number of rows.
//
if (ByteUtil.ByteOrder() != DBF_ByteUtil_c::LITTLE_ENDIAN)
{
ByteUtil.SwapBytes4(NumberOfRowsSize, &HeaderPart1Buffer[NumberOfRowsStart]);
}
memcpy(&TemporaryInt, &HeaderPart1Buffer[NumberOfRowsStart], NumberOfRowsSize);
_NumberOfRows = (unsigned long) TemporaryInt;
//
// Parse out the number of bytes in the header
//
if (ByteUtil.ByteOrder() != DBF_ByteUtil_c::LITTLE_ENDIAN)
{
ByteUtil.SwapBytes2(HeaderLengthSize, &HeaderPart1Buffer[HeaderLengthStart]);
}
memcpy(&TemporaryShort, &HeaderPart1Buffer[HeaderLengthStart], HeaderLengthSize);
_HeaderLength = (unsigned long) TemporaryShort;
//
// Parse out the number of bytes in each row
//
if (ByteUtil.ByteOrder() != DBF_ByteUtil_c::LITTLE_ENDIAN)
{
ByteUtil.SwapBytes2(RowLengthSize, &HeaderPart1Buffer[RowLengthStart]);
}
memcpy(&TemporaryShort, &HeaderPart1Buffer[RowLengthStart], RowLengthSize);
_RowLength = (unsigned long) TemporaryShort;
return XP_GIS_OK;
}
//
// Method to print the file header.
//
void XP_GIS_DBF_Header_c::PrintHeader(ostream &PrintStream) const
{
PrintStream << "DBF file header for " << _FileName << endl;
PrintStream << " Version = " << _Version << endl;
PrintStream << " Date = " << _Date << endl;
PrintStream << " HeaderLength = " << _HeaderLength << endl;
PrintStream << " RowLength = " << _RowLength << endl;
PrintStream << " NumberOfRows = " << _NumberOfRows << endl;
}
| 23.671698 | 85 | 0.65774 | avs |
aed5f87bd00067fe657b6c61aee8dda14c13eb09 | 1,015 | cpp | C++ | src/console/src/console_gear.cpp | RoyAwesome/raoe | d9350cf50bb2cd1d313df2944fb6a48354142ae8 | [
"MIT"
] | null | null | null | src/console/src/console_gear.cpp | RoyAwesome/raoe | d9350cf50bb2cd1d313df2944fb6a48354142ae8 | [
"MIT"
] | null | null | null | src/console/src/console_gear.cpp | RoyAwesome/raoe | d9350cf50bb2cd1d313df2944fb6a48354142ae8 | [
"MIT"
] | null | null | null | /*
Copyright 2022 Roy Awesome's Open Engine (RAOE)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "console_gear.hpp"
#include "engine.hpp"
namespace RAOE::Gears
{
const std::string ConsoleGearName("Global::Console::ConsoleGear");
ConsoleGear::ConsoleGear(RAOE::Cogs::BaseCog& in_cog)
: RAOE::Cogs::Gear(in_cog)
, console_ptr(std::make_unique<RAOE::Console::DisplayConsole>(in_cog.engine()))
{
}
}
RAOE_DEFINE_GEAR(ConsoleGear, RAOE::Gears::ConsoleGear) | 30.757576 | 87 | 0.722167 | RoyAwesome |
aee05ae09abe8b68c650c5bfbaabeeeed0e20759 | 130 | hpp | C++ | include/git.hpp | fcharlie/git-analyze-sync | 1c974ac4b6f695c01ee666aff60d7817f6c0acaf | [
"MIT"
] | 1 | 2021-02-18T06:12:13.000Z | 2021-02-18T06:12:13.000Z | include/git.hpp | fcharlie/git-analyze-sync | 1c974ac4b6f695c01ee666aff60d7817f6c0acaf | [
"MIT"
] | 1 | 2021-08-28T14:08:30.000Z | 2021-08-28T14:09:32.000Z | include/git.hpp | fcharlie/git-analyze-sync | 1c974ac4b6f695c01ee666aff60d7817f6c0acaf | [
"MIT"
] | 1 | 2021-08-28T14:00:29.000Z | 2021-08-28T14:00:29.000Z | //// GIT BASE HEAD
#ifndef AZE_GIT_BASE_HPP
#define AZE_GIT_BASE_HPP
#include "details/git.hpp"
#include "details/git.ipp"
#endif
| 18.571429 | 26 | 0.769231 | fcharlie |
aee119ebe9faf08b7fb22f61ba2d49e1ba1003ba | 715 | cpp | C++ | SPOJ/NSTEPS(Adhoc maths).cpp | abusomani/DS-Algo | b81b592b4ccb6c1c8a1c5275f1411ba4e91977ba | [
"Unlicense"
] | null | null | null | SPOJ/NSTEPS(Adhoc maths).cpp | abusomani/DS-Algo | b81b592b4ccb6c1c8a1c5275f1411ba4e91977ba | [
"Unlicense"
] | null | null | null | SPOJ/NSTEPS(Adhoc maths).cpp | abusomani/DS-Algo | b81b592b4ccb6c1c8a1c5275f1411ba4e91977ba | [
"Unlicense"
] | null | null | null | //Sometimes I feel like giving up, then I remember I have a lot of motherfuckers to prove wrong!
//@BEGIN OF SOURCE CODE ( By Abhishek Somani)
#include <bits/stdc++.h>
using namespace std;
#define fastio ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
typedef long long ll;
ll MOD = 1000000007;
int main()
{
fastio;
//freopen('input.txt','r',stdin);
//freopen('output.txt','w',stdout);
ll T;
cin>>T;
while(T--)
{
ll N,K,x,y;
cin>>x>>y;
if(x%2 == 0 and ((x == y+2) or (x == y))) cout<<(x+y)<<endl;
else if(x%2 == 1 and ((x == y+2) or (x == y))) cout<<(x+y-1)<<endl;
else cout<<"No Number"<<endl;
}
return 0;
}
// END OF SOURCE CODE | 23.833333 | 96 | 0.562238 | abusomani |
aee92e6a1097cae65f1cdf7bd7db8e938d768b2c | 10,040 | cpp | C++ | glscene/source/ResourceRef.cpp | Morozov-5F/glsdk | bff2b5074681bf3d2c438216e612d8a0ed80cead | [
"MIT"
] | 2 | 2020-09-13T20:38:14.000Z | 2020-09-13T20:38:23.000Z | glscene/source/ResourceRef.cpp | Morozov-5F/glsdk | bff2b5074681bf3d2c438216e612d8a0ed80cead | [
"MIT"
] | 1 | 2021-01-10T13:39:51.000Z | 2021-01-12T10:50:56.000Z | glscene/source/ResourceRef.cpp | Morozov-5F/glsdk | bff2b5074681bf3d2c438216e612d8a0ed80cead | [
"MIT"
] | null | null | null |
#include "pch.h"
#include <glload/gl_all.hpp>
#include "glscene/ResourceRef.h"
#include "ResourceData.h"
namespace glscene
{
std::string ResourceMultiplyDefinedException::GetErrorName(
const std::string &resourceId, const std::string &resourceType )
{
return std::string("The resourceId '") + resourceId + "' is already in use in the '" + resourceType + "' system.";
}
std::string ResourceNotFoundException::GetErrorName( const std::string &resourceId,
const std::string &resourceType )
{
return std::string("The resourceId '") + resourceId + "' of type '" + resourceType + "' was not found.";
}
std::string UniformResourceTypeMismatchException::GetErrorName( const std::string &resourceId,
const std::string &uniformType, const std::string &givenType )
{
return std::string("Attempting to set the uniform resourceId '") + resourceId +
"', which is of type '" + uniformType + "', with a type of " + givenType + ".";
}
SamplerInfo::SamplerInfo()
: magFilter(gl::NEAREST)
, minFilter(gl::NEAREST)
, maxAniso(1.0f)
, compareFunc(boost::none)
, edgeFilterS(gl::CLAMP_TO_EDGE)
, edgeFilterT(gl::CLAMP_TO_EDGE)
, edgeFilterR(gl::CLAMP_TO_EDGE)
{}
void ResourceRef::DefineUniform( const boost::string_ref &resourceId, const std::string &uniformName, float data )
{
m_data.get().DefineUniform(resourceId, uniformName, VectorTypes(data));
}
void ResourceRef::DefineUniform( const boost::string_ref &resourceId, const std::string &uniformName, glm::vec2 data )
{
m_data.get().DefineUniform(resourceId, uniformName, VectorTypes(data));
}
void ResourceRef::DefineUniform( const boost::string_ref &resourceId, const std::string &uniformName, glm::vec3 data )
{
m_data.get().DefineUniform(resourceId, uniformName, VectorTypes(data));
}
void ResourceRef::DefineUniform( const boost::string_ref &resourceId, const std::string &uniformName, glm::vec4 data )
{
m_data.get().DefineUniform(resourceId, uniformName, VectorTypes(data));
}
void ResourceRef::DefineUniform( const boost::string_ref &resourceId, const std::string &uniformName, int data )
{
m_data.get().DefineUniform(resourceId, uniformName, IntVectorTypes(data));
}
void ResourceRef::DefineUniform( const boost::string_ref &resourceId, const std::string &uniformName, glm::ivec2 data )
{
m_data.get().DefineUniform(resourceId, uniformName, IntVectorTypes(data));
}
void ResourceRef::DefineUniform( const boost::string_ref &resourceId, const std::string &uniformName, glm::ivec3 data )
{
m_data.get().DefineUniform(resourceId, uniformName, IntVectorTypes(data));
}
void ResourceRef::DefineUniform( const boost::string_ref &resourceId, const std::string &uniformName, glm::ivec4 data )
{
m_data.get().DefineUniform(resourceId, uniformName, IntVectorTypes(data));
}
void ResourceRef::DefineUniform( const boost::string_ref &resourceId, const std::string &uniformName, unsigned int data )
{
m_data.get().DefineUniform(resourceId, uniformName, UIntVectorTypes(data));
}
void ResourceRef::DefineUniform( const boost::string_ref &resourceId, const std::string &uniformName, glm::uvec2 data )
{
m_data.get().DefineUniform(resourceId, uniformName, UIntVectorTypes(data));
}
void ResourceRef::DefineUniform( const boost::string_ref &resourceId, const std::string &uniformName, glm::uvec3 data )
{
m_data.get().DefineUniform(resourceId, uniformName, UIntVectorTypes(data));
}
void ResourceRef::DefineUniform( const boost::string_ref &resourceId, const std::string &uniformName, glm::uvec4 data )
{
m_data.get().DefineUniform(resourceId, uniformName, UIntVectorTypes(data));
}
void ResourceRef::DefineUniform( const boost::string_ref &resourceId, const std::string &uniformName, glm::mat2 data )
{
m_data.get().DefineUniform(resourceId, uniformName, MatrixTypes(data));
}
void ResourceRef::DefineUniform( const boost::string_ref &resourceId, const std::string &uniformName, glm::mat3 data )
{
m_data.get().DefineUniform(resourceId, uniformName, MatrixTypes(data));
}
void ResourceRef::DefineUniform( const boost::string_ref &resourceId, const std::string &uniformName, glm::mat4 data )
{
m_data.get().DefineUniform(resourceId, uniformName, MatrixTypes(data));
}
void ResourceRef::SetUniform( const boost::string_ref &resourceId, float data )
{
m_data.get().SetUniform(resourceId, VectorTypes(data));
}
void ResourceRef::SetUniform( const boost::string_ref &resourceId, glm::vec2 data )
{
m_data.get().SetUniform(resourceId, VectorTypes(data));
}
void ResourceRef::SetUniform( const boost::string_ref &resourceId, glm::vec3 data )
{
m_data.get().SetUniform(resourceId, VectorTypes(data));
}
void ResourceRef::SetUniform( const boost::string_ref &resourceId, glm::vec4 data )
{
m_data.get().SetUniform(resourceId, VectorTypes(data));
}
void ResourceRef::SetUniform( const boost::string_ref &resourceId, int data )
{
m_data.get().SetUniform(resourceId, IntVectorTypes(data));
}
void ResourceRef::SetUniform( const boost::string_ref &resourceId, glm::ivec2 data )
{
m_data.get().SetUniform(resourceId, IntVectorTypes(data));
}
void ResourceRef::SetUniform( const boost::string_ref &resourceId, glm::ivec3 data )
{
m_data.get().SetUniform(resourceId, IntVectorTypes(data));
}
void ResourceRef::SetUniform( const boost::string_ref &resourceId, glm::ivec4 data )
{
m_data.get().SetUniform(resourceId, IntVectorTypes(data));
}
void ResourceRef::SetUniform( const boost::string_ref &resourceId, unsigned int data )
{
m_data.get().SetUniform(resourceId, UIntVectorTypes(data));
}
void ResourceRef::SetUniform( const boost::string_ref &resourceId, glm::uvec2 data )
{
m_data.get().SetUniform(resourceId, UIntVectorTypes(data));
}
void ResourceRef::SetUniform( const boost::string_ref &resourceId, glm::uvec3 data )
{
m_data.get().SetUniform(resourceId, UIntVectorTypes(data));
}
void ResourceRef::SetUniform( const boost::string_ref &resourceId, glm::uvec4 data )
{
m_data.get().SetUniform(resourceId, UIntVectorTypes(data));
}
void ResourceRef::SetUniform( const boost::string_ref &resourceId, glm::mat2 data )
{
m_data.get().SetUniform(resourceId, MatrixTypes(data));
}
void ResourceRef::SetUniform( const boost::string_ref &resourceId, glm::mat3 data )
{
m_data.get().SetUniform(resourceId, MatrixTypes(data));
}
void ResourceRef::SetUniform( const boost::string_ref &resourceId, glm::mat4 data )
{
m_data.get().SetUniform(resourceId, MatrixTypes(data));
}
void ResourceRef::DefineTexture( const boost::string_ref &resourceId, GLuint textureObj, GLenum target,
bool claimOwnership )
{
m_data.get().DefineTexture(resourceId, textureObj, target, claimOwnership);
}
void ResourceRef::DefineTextureIncomplete( const boost::string_ref &resourceId )
{
m_data.get().DefineTextureIncomplete(resourceId);
}
void ResourceRef::DefineSampler( const boost::string_ref &resourceId, const SamplerInfo &data )
{
m_data.get().DefineSampler(resourceId, data);
}
void ResourceRef::SetSamplerLODBias( const boost::string_ref &resourceId, float bias )
{
m_data.get().SetSamplerLODBias(resourceId, bias);
}
void ResourceRef::DefineMesh( const boost::string_ref &resourceId, glmesh::Mesh *pMesh, bool claimOwnership )
{
m_data.get().DefineMesh(resourceId, pMesh, claimOwnership);
}
void ResourceRef::DefineMesh( const boost::string_ref &resourceId, glscene::Drawable *pMesh, bool claimOwnership /*= true*/ )
{
m_data.get().DefineMesh(resourceId, pMesh, claimOwnership);
}
void ResourceRef::DefineMeshIncomplete( const boost::string_ref &resourceId )
{
m_data.get().DefineMeshIncomplete(resourceId);
}
void ResourceRef::DefineProgram( const boost::string_ref &resourceId, GLuint program, const ProgramInfo &programInfo,
bool claimOwnership )
{
m_data.get().DefineProgram(resourceId, program, programInfo, claimOwnership);
}
void ResourceRef::DefineUniformBufferBinding( const boost::string_ref &resourceId, GLuint bufferObject,
GLintptr offset, GLsizeiptr size, bool claimOwnership )
{
m_data.get().DefineUniformBufferBinding(resourceId, bufferObject, offset, size, claimOwnership);
}
void ResourceRef::DefineUniformBufferBinding( const boost::string_ref &resourceId, GLuint bufferObject,
GLintptr offset, bool claimOwnership )
{
m_data.get().DefineUniformBufferBinding(resourceId, bufferObject, offset, claimOwnership);
}
void ResourceRef::DefineUniformBufferBindingIncomplete( const boost::string_ref &resourceId,
GLsizeiptr size )
{
m_data.get().DefineUniformBufferBindingIncomplete(resourceId, size);
}
void ResourceRef::DefineStorageBufferBinding( const boost::string_ref &resourceId, GLuint bufferObject,
GLintptr offset, GLsizeiptr size, bool claimOwnership )
{
m_data.get().DefineStorageBufferBinding(resourceId, bufferObject, offset, size, claimOwnership);
}
void ResourceRef::DefineStorageBufferBinding( const boost::string_ref &resourceId, GLuint bufferObject,
GLintptr offset, bool claimOwnership )
{
m_data.get().DefineStorageBufferBinding(resourceId, bufferObject, offset, claimOwnership);
}
void ResourceRef::DefineStorageBufferBindingIncomplete( const boost::string_ref &resourceId,
GLsizeiptr size )
{
m_data.get().DefineStorageBufferBindingIncomplete(resourceId, size);
}
void ResourceRef::DefineCamera( const boost::string_ref &resourceId, const glutil::ViewData &initialView,
const glutil::ViewScale &viewScale, glutil::MouseButtons actionButton, bool bRightKeyboardCtrls )
{
m_data.get().DefineCamera(resourceId, initialView, viewScale, actionButton, bRightKeyboardCtrls);
}
glutil::ViewPole & ResourceRef::GetCamera( const boost::string_ref &resourceId )
{
return m_data.get().GetCamera(resourceId);
}
}
| 36.245487 | 127 | 0.735159 | Morozov-5F |
aef187e33dbf7062d00aa0bb3907cf9eb6e92098 | 667 | cpp | C++ | c++_for_programmers/01_basics/3_enums.cpp | Joy110900/cpp | 3d8c582d5b1d3af47d44ae3cef2f6015e272f287 | [
"MIT"
] | null | null | null | c++_for_programmers/01_basics/3_enums.cpp | Joy110900/cpp | 3d8c582d5b1d3af47d44ae3cef2f6015e272f287 | [
"MIT"
] | null | null | null | c++_for_programmers/01_basics/3_enums.cpp | Joy110900/cpp | 3d8c582d5b1d3af47d44ae3cef2f6015e272f287 | [
"MIT"
] | null | null | null | /*Enum example*/
/*
Enum is a user defined datatype which is initialised as below.
*/
#include <iostream>
using namespace std;
int main()
{
//define MONTHS as having 12 possible values
enum MONTH {Jan, Feb, Mar, Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec}; // Jan is assigned 0, Feb is assigned 1 and so on.
//define bestMonth as a variable type MONTHS
MONTH bestMonth;
//assign bestMonth one of the values of MONTHS
bestMonth = Jan;
//now we can check the value of bestMonths just
//like any other variable
if(bestMonth == Jan)
{
cout<<"I'm not so sure January is the best month\n";
}
return 0;
} | 23 | 122 | 0.646177 | Joy110900 |
aef288d79580780fb962856320b1fb494d05d53f | 12,516 | cpp | C++ | BulletLeague3D/ModulePlayer.cpp | AaronGCProg/RacingBullet3D | d64b852b3b6eb53c1285d4e49746f842645e721a | [
"MIT"
] | null | null | null | BulletLeague3D/ModulePlayer.cpp | AaronGCProg/RacingBullet3D | d64b852b3b6eb53c1285d4e49746f842645e721a | [
"MIT"
] | null | null | null | BulletLeague3D/ModulePlayer.cpp | AaronGCProg/RacingBullet3D | d64b852b3b6eb53c1285d4e49746f842645e721a | [
"MIT"
] | null | null | null | #include "Globals.h"
#include "Application.h"
#include "ModulePlayer.h"
#include "Primitive.h"
#include "PhysBody3D.h"
#include "ModuleSceneIntro.h"
ModulePlayer::ModulePlayer(Application* app, bool start_enabled, int playerNum) : Module(app, start_enabled), vehicle(NULL), playerNum(playerNum)
{
turn = acceleration = brake = 0.0f;
groundRayCast = { 0,0,0 };
goalNum = 0;
// INPUTS FOR EACH PLAYER
Forward[0] = {SDL_SCANCODE_W };
Forward[1] = { SDL_SCANCODE_UP };
Backward[0] = { SDL_SCANCODE_S};
Backward[1] = { SDL_SCANCODE_DOWN };
Right[0] = { SDL_SCANCODE_D };
Right[1] = { SDL_SCANCODE_RIGHT };
Left[0] = { SDL_SCANCODE_A };
Left[1] = { SDL_SCANCODE_LEFT };
Jump[0] = { SDL_SCANCODE_SPACE };
Jump[1] = { SDL_SCANCODE_KP_0 };
Turbo[0] = { SDL_SCANCODE_LSHIFT };
Turbo[1] = { SDL_SCANCODE_RSHIFT };
Brake[0] = { SDL_SCANCODE_B };
Brake[1] = { SDL_SCANCODE_KP_1 };
SwapCamera[0] = { SDL_SCANCODE_R };
SwapCamera[1] = { SDL_SCANCODE_KP_5 };
switch (playerNum)
{
case 1:
initialPos = { 0, 6, -160 };
break;
case 2:
initialPos = { 0, 6, 160 };
break;
}
}
ModulePlayer::~ModulePlayer()
{}
// Load assets
bool ModulePlayer::Start()
{
LOG("Loading player");
// Car properties ----------------------------------------
//All chassis parts
car.num_chassis = 5;
car.chassis = new Chassis[car.num_chassis];
//front mudward
car.chassis[0].chassis_size.Set(2, 0.5, 1);
car.chassis[0].chassis_offset.Set(0, 1.f, 2.5f);
//back mudward
car.chassis[1].chassis_size.Set(2, 0.5, 1);
car.chassis[1].chassis_offset.Set(0, 1.f, -2.5f);
//spoiler
car.chassis[2].chassis_size.Set(0.1f, 0.6f, 0.2f);
car.chassis[2].chassis_offset.Set(-0.5, 1.6f, -2.75f);
car.chassis[3].chassis_size.Set(0.1f, 0.6f, 0.2f);
car.chassis[3].chassis_offset.Set(0.5, 1.6f, -2.75f);
car.chassis[4].chassis_size.Set(2.f, 0.2f, 0.4f);
car.chassis[4].chassis_offset.Set(0.f, 2.f, -2.75f);
car.chassis_size.Set(2, 1, 4);
car.chassis_offset.Set(0, 1, 0);
car.mass = 540.0f;
car.suspensionStiffness = 15.88f;
car.suspensionCompression = 0.83f;
car.suspensionDamping = 1.0f;
car.maxSuspensionTravelCm = 1000.0f;
car.frictionSlip = 50.5;
car.maxSuspensionForce = 6000.0f;
// Wheel properties ---------------------------------------
float connection_height = 1.2f;
float wheel_radius = 0.6f;
float wheel_width = 0.5f;
float suspensionRestLength = 0.8f;
// Don't change anything below this line ------------------
float half_width = car.chassis_size.x * 0.5f;
float half_length = car.chassis_size.z * 0.5f;
vec3 direction(0, -1, 0);
vec3 axis(-1, 0, 0);
car.num_wheels = 4;
car.wheels = new Wheel[car.num_wheels];
// FRONT-LEFT ------------------------
car.wheels[0].connection.Set(half_width - 0.3f * wheel_width, connection_height, half_length - wheel_radius);
car.wheels[0].direction = direction;
car.wheels[0].axis = axis;
car.wheels[0].suspensionRestLength = suspensionRestLength;
car.wheels[0].radius = wheel_radius;
car.wheels[0].width = wheel_width;
car.wheels[0].front = true;
car.wheels[0].drive = true;
car.wheels[0].brake = false;
car.wheels[0].steering = true;
// FRONT-RIGHT ------------------------
car.wheels[1].connection.Set(-half_width + 0.4f * wheel_width, connection_height, half_length - wheel_radius);
car.wheels[1].direction = direction;
car.wheels[1].axis = axis;
car.wheels[1].suspensionRestLength = suspensionRestLength;
car.wheels[1].radius = wheel_radius;
car.wheels[1].width = wheel_width;
car.wheels[1].front = true;
car.wheels[1].drive = true;
car.wheels[1].brake = false;
car.wheels[1].steering = true;
// REAR-LEFT ------------------------
car.wheels[2].connection.Set(half_width - 0.3f * wheel_width, connection_height, -half_length + wheel_radius);
car.wheels[2].direction = direction;
car.wheels[2].axis = axis;
car.wheels[2].suspensionRestLength = suspensionRestLength;
car.wheels[2].radius = wheel_radius;
car.wheels[2].width = wheel_width;
car.wheels[2].front = false;
car.wheels[2].drive = false;
car.wheels[2].brake = true;
car.wheels[2].steering = false;
// REAR-RIGHT ------------------------
car.wheels[3].connection.Set(-half_width + 0.3f * wheel_width, connection_height, -half_length + wheel_radius);
car.wheels[3].direction = direction;
car.wheels[3].axis = axis;
car.wheels[3].suspensionRestLength = suspensionRestLength;
car.wheels[3].radius = wheel_radius;
car.wheels[3].width = wheel_width;
car.wheels[3].front = false;
car.wheels[3].drive = false;
car.wheels[3].brake = true;
car.wheels[3].steering = false;
jumpImpulse = false;
canDrift = false;
secondJump = false;
turbo = INITIAL_TURBO;
vehicle = App->physics->AddVehicle(car);
vehicle->collision_listeners.add(this);
vehicle->cntType = CNT_VEHICLE;
vehicle->SetPos(initialPos.x, initialPos.y, initialPos.z);
if (playerNum == 2)
{
mat4x4 trans;
vehicle->GetTransform(&trans);
trans.rotate(180, {0, -1, 0});
vehicle->SetTransform(&trans);
}
return true;
}
// Unload assets
bool ModulePlayer::CleanUp()
{
LOG("Unloading player");
return true;
}
update_status ModulePlayer::PreUpdate(float dt)
{
if(App->scene_intro->state != MT_STOP && App->scene_intro->state != MT_RESTARTING)
PlayerInputs();
return UPDATE_CONTINUE;
}
// Update: draw background
update_status ModulePlayer::Update(float dt)
{
groundRayCast = App->physics->RayCast({ this->vehicle->GetPos().x,this->vehicle->GetPos().y+1, this->vehicle->GetPos().z }, vehicle->GetDown());
if (length(groundRayCast) < 2.f )
{
fieldContact = true;
secondJump = false;
jumpImpulse = false;
vehicle->Push(0.0f, -STICK_FORCE/4, 0.0f);
}
else
fieldContact = false;
return UPDATE_CONTINUE;
}
update_status ModulePlayer::PostUpdate(float dt)
{
return UPDATE_CONTINUE;
}
bool ModulePlayer::Draw()
{
vehicle->Render(playerNum);
return true;
}
// World to Local forces translation
btVector3 ModulePlayer::WorldToLocal(float x, float y, float z)
{
btVector3 relativeForce = btVector3(x, y, z);
btMatrix3x3& localRot = vehicle->myBody->getWorldTransform().getBasis();
btVector3 correctedForce = localRot * relativeForce;
return correctedForce;
}
void ModulePlayer::OnCollision(PhysBody3D* body1, PhysBody3D* body2)
{
if (body1->cntType == CNT_VEHICLE && body2->cntType == CNT_LITTLE_BOOST)
{
if (body2->sensorOnline)
{
turbo += 12.0f;
App->audio->PlayFx(App->scene_intro->boostUpFx);
}
}
if (body1->cntType == CNT_VEHICLE && body2->cntType == CNT_BIG_BOOST)
{
if (body2->sensorOnline)
{
turbo += 100.0f;
App->audio->PlayFx(App->scene_intro->boostUpFx);
}
}
if (turbo > 100.0f)
turbo = 100.0f;
}
bool ModulePlayer::Reset()
{
mat4x4 mat;
btTransform identity;
identity.setIdentity();
identity.getOpenGLMatrix(&mat);
switch (playerNum)
{
case 1:
break;
case 2:
mat.rotate(180, { 0, -1, 0 });
break;
}
vehicle->SetTransform(&mat);
vehicle->ResetSpeed();
vehicle->SetPos(initialPos.x, initialPos.y, initialPos.z);
this->turbo = 33.f;
return true;
}
void ModulePlayer::PlayerInputs()
{
turn = acceleration = brake = 0.0f;
if (App->input->GetKey(Forward[playerNum - 1]) == KEY_REPEAT && fieldContact && vehicle->GetKmh() < 180)
{
if(vehicle->GetKmh() <= 0)
acceleration = MAX_ACCELERATION * 5;
else
acceleration = MAX_ACCELERATION;
vehicle->Push(0.0f, -STICK_FORCE, 0.0f);
}
else if (App->input->GetKey(Forward[playerNum - 1]) == KEY_REPEAT && !fieldContact)
{
if (vehicle->myBody->getAngularVelocity().length() < CAP_ACROBATIC_SPEED)
{
if (vehicle->myBody->getAngularVelocity().length() < SMOOTH_ACROBATIC_SPEED)
vehicle->myBody->applyTorque(WorldToLocal(5000.0f, 0.0f, 0.0f));
else
vehicle->myBody->applyTorque(WorldToLocal(500.0f, 0.0f, 0.0f));
}
}
if (App->input->GetKey(Left[playerNum - 1]) == KEY_REPEAT && fieldContact)
{
if (turn < TURN_DEGREES && !canDrift)
turn += TURN_DEGREES;
else if (turn > -TURN_DEGREES && canDrift)
{
turn += TURN_DEGREES;
vehicle->myBody->applyTorque(WorldToLocal(0.0f, 20000.0f, 0.0f));
}
vehicle->Push(0.0f, -STICK_FORCE, 0.0f);
}
else if (App->input->GetKey(Left[playerNum - 1]) == KEY_REPEAT && !fieldContact)
{
if (vehicle->myBody->getAngularVelocity().length() < CAP_ACROBATIC_SPEED)
{
if (secondJump)
{
if (vehicle->myBody->getAngularVelocity().length() < SMOOTH_ACROBATIC_SPEED)
vehicle->myBody->applyTorque(WorldToLocal(0.0f, 0.0f, -5000.0f));
else
vehicle->myBody->applyTorque(WorldToLocal(0.0f, 0.0f, -500.0f));
}
else
{
if (vehicle->myBody->getAngularVelocity().length() < SMOOTH_ACROBATIC_SPEED)
vehicle->myBody->applyTorque(WorldToLocal(0.0f, 5000.0f, 0.0f));
else
vehicle->myBody->applyTorque(WorldToLocal(0.0f, 500.0f, 0.0f));
}
}
}
if (App->input->GetKey(Right[playerNum - 1]) == KEY_REPEAT && fieldContact)
{
if (turn > -TURN_DEGREES && !canDrift)
turn -= TURN_DEGREES;
else if (turn > -TURN_DEGREES && canDrift)
{
turn -= TURN_DEGREES;
vehicle->myBody->applyTorque(WorldToLocal(0.0f, -20000.0f, 0.0f));
}
vehicle->Push(0.0f, -STICK_FORCE, 0.0f);
}
else if (App->input->GetKey(Right[playerNum - 1]) == KEY_REPEAT && !fieldContact)
{
if (vehicle->myBody->getAngularVelocity().length() < CAP_ACROBATIC_SPEED)
{
if (secondJump)
{
if (vehicle->myBody->getAngularVelocity().length() < SMOOTH_ACROBATIC_SPEED)
vehicle->myBody->applyTorque(WorldToLocal(0.0f, 0.0f, 5000.0f));
else
vehicle->myBody->applyTorque(WorldToLocal(0.0f, 0.0f, 500.0f));
}
else
{
if (vehicle->myBody->getAngularVelocity().length() < SMOOTH_ACROBATIC_SPEED)
vehicle->myBody->applyTorque(WorldToLocal(0.0f, -5000.0f, 0.0f));
else
vehicle->myBody->applyTorque(WorldToLocal(0.0f, -500.0f, 0.0f));
}
}
}
if (App->input->GetKey(Backward[playerNum - 1]) == KEY_REPEAT && fieldContact && vehicle->GetKmh() > -120)
{
if (vehicle->GetKmh() >= 0)
acceleration = -MAX_ACCELERATION * 5;
else
acceleration = -MAX_ACCELERATION;
vehicle->Push(0.0f, -STICK_FORCE, 0.0f);
}
else if (App->input->GetKey(Backward[playerNum - 1]) == KEY_REPEAT && !fieldContact)
{
if (vehicle->myBody->getAngularVelocity().length() < CAP_ACROBATIC_SPEED)
{
if (vehicle->myBody->getAngularVelocity().length() < SMOOTH_ACROBATIC_SPEED)
vehicle->myBody->applyTorque(WorldToLocal(-5000.0f, 0.0f, 0.0f));
else
vehicle->myBody->applyTorque(WorldToLocal(-500.0f, 0.0f, 0.0f));
}
}
if (App->input->GetKey(Jump[playerNum - 1]) == KEY_DOWN && fieldContact)
{
vehicle->myBody->setAngularVelocity({ 0,0,0 });
vehicle->Push(0.0f, JUMP_FORCE, 0.0f);
fieldContact = false;
}
else if (App->input->GetKey(Jump[playerNum - 1]) == KEY_DOWN && !fieldContact && !secondJump)
{
secondJump = true;
vehicle->Push(0.0f, IMPULSE_FORCE, 0.0f);
if (App->input->GetKey(Forward[playerNum - 1]) == KEY_REPEAT)
{
jumpImpulse = true;
vehicle->myBody->applyCentralForce(WorldToLocal(0.0f, 0.0f, 300000.0f));
vehicle->myBody->applyTorque(WorldToLocal(115000.0f, 0.0f, 0.0f));
}
else if (App->input->GetKey(Backward[playerNum - 1]) == KEY_REPEAT)
{
jumpImpulse = true;
vehicle->myBody->applyCentralForce(WorldToLocal(0.0f, 0.0f, -300000.0f));
vehicle->myBody->applyTorque(WorldToLocal(-115000.0f, 0.0f, 0.0f));
}
else if (App->input->GetKey(Right[playerNum - 1]) == KEY_REPEAT)
{
jumpImpulse = true;
vehicle->myBody->applyCentralForce(WorldToLocal(-400000.0f, 0.0f, 0.0f));
vehicle->myBody->applyTorque(WorldToLocal(0.0f, 0.0f, 45000.0f));
}
else if (App->input->GetKey(Left[playerNum - 1]) == KEY_REPEAT)
{
jumpImpulse = true;
vehicle->myBody->applyCentralForce(WorldToLocal(400000.0f, 0.0f, 0.0f));
vehicle->myBody->applyTorque(WorldToLocal(0.0f, 0.0f, -45000.0f));
}
}
if (App->input->GetKey(Brake[playerNum - 1]) == KEY_REPEAT)
{
brake = BRAKE_POWER;
canDrift = true;
}
else if (App->input->GetKey(Brake[playerNum - 1]) == KEY_UP)
canDrift = false;
if (App->input->GetKey(Turbo[playerNum - 1]) == KEY_REPEAT && turbo > 0)
{
vehicle->myBody->applyCentralImpulse(WorldToLocal(0.0f, 0.0f, 125.0f));
turbo -= 0.5f;
}
if (App->input->GetKey(SwapCamera[playerNum - 1]) == KEY_DOWN)
{
if (playerNum == 1)
App->camera->lookAtBall = !App->camera->lookAtBall;
else
App->camera_2->lookAtBall = !App->camera_2->lookAtBall;
}
vehicle->ApplyEngineForce(acceleration);
vehicle->Turn(turn);
vehicle->Brake(brake);
} | 25.336032 | 145 | 0.669942 | AaronGCProg |
aef9ece3a8db2a41fdfd31d983bd33449d35f811 | 2,009 | hpp | C++ | include/GDE/Core/CoreTypes.hpp | genbetadev/Genbeta-Dev-Engine | 1bda1f92a927c7657df7fcc6460474c9ef8ac9cd | [
"MIT"
] | 3 | 2016-05-04T23:36:27.000Z | 2021-05-02T06:46:50.000Z | include/GDE/Core/CoreTypes.hpp | fordream/Genbeta-Dev-Engine | 1bda1f92a927c7657df7fcc6460474c9ef8ac9cd | [
"MIT"
] | 3 | 2015-01-13T22:45:29.000Z | 2019-03-07T16:35:37.000Z | include/GDE/Core/CoreTypes.hpp | fordream/Genbeta-Dev-Engine | 1bda1f92a927c7657df7fcc6460474c9ef8ac9cd | [
"MIT"
] | 4 | 2015-01-16T14:41:41.000Z | 2020-04-21T21:12:19.000Z | #ifndef GDE_CORE_TYPES_HPP
#define GDE_CORE_TYPES_HPP
#include <map>
#include <string>
namespace GDE
{
// Fowards Declarations
class App;
class Scene;
class SceneManager;
class ConfigReader;
class ConfigCreate;
/// Nivel o tipo de Log
enum LogLevel
{
Debug = 0,
Info = 1,
Warning = 2,
Error = 3
};
/// Enumaración con los posibles valores de retorno de la Aplicación
enum StatusType
{
// Values from -99 to 99 are common Error and Good status responses
StatusAppMissingAsset = -4, ///< Application failed due to missing asset file
StatusAppStackEmpty = -3, ///< Application States stack is empty
StatusAppInitFailed = -2, ///< Application initialization failed
StatusError = -1, ///< General error status response
StatusAppOK = 0, ///< Application quit without error
StatusNoError = 0, ///< General no error status response
StatusFalse = 0, ///< False status response
StatusTrue = 1, ///< True status response
StatusOK = 1 ///< OK status response
// Values from +-100 to +-199 are reserved for File status responses
};
/// Tipo de dato para identidicar las escenas
typedef std::string sceneID;
/// Declare NameValue typedef which is used for config section maps
typedef std::map<const std::string, const std::string> typeNameValue;
/// Declare NameValueIter typedef which is used for name,value pair maps
typedef std::map<const std::string, const std::string>::iterator typeNameValueIter;
/// Almacena el número de línea, nombre de archivo y nombre de función.
struct SourceContext
{
SourceContext (const char *file, unsigned int line, const char *function)
: file(file)
, line(line)
, function(function)
{ }
const char *file;
const int line;
const char *function;
};
typedef void (*LogHandler) (std::ostream &os,
GDE::LogLevel level,
const std::string &message,
const std::string &date,
const std::string &time,
const GDE::SourceContext &context
);
} // namespace GDE
#endif // GDE_CORE_TYPES_HPP
| 25.1125 | 83 | 0.708313 | genbetadev |
4e07ffded9aab7c634229dcf72f6f1acfc7061d6 | 403 | cpp | C++ | Applications/calculator/main.cpp | Butterzz1288/ButterOS | 4faee625eba83bd22bc8d180e0c4136f543c3404 | [
"BSD-2-Clause"
] | 5 | 2021-11-25T10:53:24.000Z | 2022-03-31T08:17:45.000Z | Applications/calculator/main.cpp | Butterzz1288/ButterOS | 4faee625eba83bd22bc8d180e0c4136f543c3404 | [
"BSD-2-Clause"
] | null | null | null | Applications/calculator/main.cpp | Butterzz1288/ButterOS | 4faee625eba83bd22bc8d180e0c4136f543c3404 | [
"BSD-2-Clause"
] | null | null | null | #include <Lemon/GUI/Window.h>
#include <Lemon/GUI/Messagebox.h>
#include <Lemon/System/Spawn.h>
Lemon::GUI::Window* window;
window = new Lemon::GUI::Window("Addition", {600, 348}, WINDOW_FLAGS_RESIZABLE, Lemon::GUI::WindowType::GUI);
box = new Lemon::GUI::textInput("Input 1")
box = new Lemon::GUI::textInput("Input 2")
type RES == Lemon::GUI::textInput("Input 1") + Lemon::GUI::textInput("Input 2")
| 36.636364 | 109 | 0.702233 | Butterzz1288 |
4e0e0a55682db38fc988fc71a7b830d5ba500dd4 | 9,786 | cpp | C++ | speedcc/lua-support/src/native/SCLuaRegisterSCDateTimeDate.cpp | kevinwu1024/SpeedCC | 7b32e3444236d8aebf8198ebc3fede8faf201dee | [
"MIT"
] | 7 | 2018-03-10T02:01:49.000Z | 2021-09-14T15:42:10.000Z | speedcc/lua-support/src/native/SCLuaRegisterSCDateTimeDate.cpp | kevinwu1024/SpeedCC | 7b32e3444236d8aebf8198ebc3fede8faf201dee | [
"MIT"
] | null | null | null | speedcc/lua-support/src/native/SCLuaRegisterSCDateTimeDate.cpp | kevinwu1024/SpeedCC | 7b32e3444236d8aebf8198ebc3fede8faf201dee | [
"MIT"
] | 1 | 2018-03-10T02:01:58.000Z | 2018-03-10T02:01:58.000Z | /****************************************************************************
Copyright (c) 2017-2020 Kevin Wu (Wu Feng)
github: http://github.com/kevinwu1024
Licensed under the MIT License (the "License"); you may not use this file except
in compliance with the License. You may obtain a copy of the License at
http://opensource.org/licenses/MIT
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "platform/CCPlatformConfig.h"
#include "../../../base/SCDateTime.h"
#include "../../../base/SCString.h"
#include "scripting/lua-bindings/manual/CCComponentLua.h"
#include "scripting/lua-bindings/manual/tolua_fix.h"
#include "scripting/lua-bindings/manual/LuaBasicConversions.h"
#include "SCLuaUtils.h"
NAMESPACE_SPEEDCC_BEGIN
#define SCLUA_MODULE "Date"
#define SCLUA_CLASSTYPE_LUA "sc.SCDateTime." SCLUA_MODULE
#define SCLUA_CLASSTYPE_CPP SCDateTime::Date
#define SCLUA_MODULE_BASE ""
#ifdef __cplusplus
extern "C" {
#endif
SCLUA_SCCREATE_FUNC_IMPLEMENT(SCDateTimeDate)
SCLUA_SCCLONE_FUNC_IMPLEMENT(SCDateTimeDate)
int lua_speedcc_SCDateTimeDate_createYMD(lua_State* tolua_S)
{
SCLUA_CHECK_LUA_TABLE(tolua_S);
auto nArgc = lua_gettop(tolua_S) - 1;
if (nArgc == 3)
{
int arg0,arg1,arg2;
bool ok = true;
ok = luaval_to_int32(tolua_S, 2, &arg0, "sc.SCDateTime.Date:createYMD");
SCLUA_CHECK_LUA_ARG(tolua_S, ok);
ok = luaval_to_int32(tolua_S, 3, &arg1, "sc.SCDateTime.Date:createYMD");
SCLUA_CHECK_LUA_ARG(tolua_S, ok);
ok = luaval_to_int32(tolua_S, 4, &arg2, "sc.SCDateTime.Date:createYMD");
SCLUA_CHECK_LUA_ARG(tolua_S, ok);
auto obj = SCMemAllocator::newObject<SCLUA_CLASSTYPE_CPP>(arg0, arg1, arg2);
tolua_pushusertype_and_takeownership(tolua_S, (void*)obj, SCLUA_CLASSTYPE_LUA);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", SCLUA_CLASSTYPE_LUA, nArgc, 3);
return 0;
}
int lua_speedcc_SCDateTimeDate_createWithJD(lua_State* tolua_S)
{
SCLUA_CHECK_LUA_TABLE(tolua_S);
auto nArgc = lua_gettop(tolua_S) - 1;
if (nArgc == 1)
{
INT64 arg0;
bool ok = true;
ok = luaval_to_long_long(tolua_S, 2, &arg0, "sc.SCDateTime.Date:createWithJD");
SCLUA_CHECK_LUA_ARG(tolua_S, ok);
auto obj = SCMemAllocator::newObject<SCLUA_CLASSTYPE_CPP>(arg0);
tolua_pushusertype_and_takeownership(tolua_S, (void*)obj, SCLUA_CLASSTYPE_LUA);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", SCLUA_CLASSTYPE_LUA, nArgc, 1);
return 0;
}
int lua_speedcc_SCDateTimeDate_isValid(lua_State* tolua_S)
{
SCLUA_CHECK_LUA_USERTYPE(tolua_S);
auto nArgc = lua_gettop(tolua_S) - 1;
if (nArgc == 0)
{
auto pInstance = (SCLUA_CLASSTYPE_CPP*)tolua_tousertype(tolua_S, 1, 0);
SCLUA_CHECK_LUA_INSTANCE(tolua_S, pInstance);
auto result = pInstance->isValid();
lua_pushboolean(tolua_S, result);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", SCLUA_CLASSTYPE_LUA, nArgc, 1);
return 0;
}
int lua_speedcc_SCDateTimeDate_getWeekCountOfYear(lua_State* tolua_S)
{
SCLUA_CHECK_LUA_USERTYPE(tolua_S);
auto nArgc = lua_gettop(tolua_S) - 1;
if (nArgc == 0)
{
auto pInstance = (SCLUA_CLASSTYPE_CPP*)tolua_tousertype(tolua_S, 1, 0);
SCLUA_CHECK_LUA_INSTANCE(tolua_S, pInstance);
auto result = pInstance->getWeekCountOfYear();
lua_pushinteger(tolua_S, result);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", SCLUA_CLASSTYPE_LUA, nArgc, 1);
return 0;
}
int lua_speedcc_SCDateTimeDate_getDayCountOfMonth(lua_State* tolua_S)
{
SCLUA_CHECK_LUA_USERTYPE(tolua_S);
auto nArgc = lua_gettop(tolua_S) - 1;
if (nArgc == 0)
{
auto pInstance = (SCLUA_CLASSTYPE_CPP*)tolua_tousertype(tolua_S, 1, 0);
SCLUA_CHECK_LUA_INSTANCE(tolua_S, pInstance);
auto result = pInstance->getDayCountOfMonth();
lua_pushinteger(tolua_S, result);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", SCLUA_CLASSTYPE_LUA, nArgc, 1);
return 0;
}
int lua_speedcc_SCDateTimeDate_getDayCountOfYear(lua_State* tolua_S)
{
SCLUA_CHECK_LUA_USERTYPE(tolua_S);
auto nArgc = lua_gettop(tolua_S) - 1;
if (nArgc == 0)
{
auto pInstance = (SCLUA_CLASSTYPE_CPP*)tolua_tousertype(tolua_S, 1, 0);
SCLUA_CHECK_LUA_INSTANCE(tolua_S, pInstance);
auto result = pInstance->getDayCountOfYear();
lua_pushinteger(tolua_S, result);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", SCLUA_CLASSTYPE_LUA, nArgc, 1);
return 0;
}
int lua_speedcc_SCDateTimeDate_getYear(lua_State* tolua_S)
{
SCLUA_CHECK_LUA_USERTYPE(tolua_S);
auto nArgc = lua_gettop(tolua_S) - 1;
if (nArgc == 0)
{
auto pInstance = (SCLUA_CLASSTYPE_CPP*)tolua_tousertype(tolua_S, 1, 0);
SCLUA_CHECK_LUA_INSTANCE(tolua_S, pInstance);
lua_pushinteger(tolua_S, pInstance->nYear);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", SCLUA_CLASSTYPE_LUA, nArgc, 0);
return 0;
}
int lua_speedcc_SCDateTimeDate_setYear(lua_State* tolua_S)
{
SCLUA_CHECK_LUA_USERTYPE(tolua_S);
auto nArgc = lua_gettop(tolua_S) - 1;
if (nArgc == 1)
{
auto pInstance = (SCLUA_CLASSTYPE_CPP*)tolua_tousertype(tolua_S, 1, 0);
SCLUA_CHECK_LUA_INSTANCE(tolua_S, pInstance);
int arg0;
bool ok = true;
ok = luaval_to_int32(tolua_S, 2, &arg0, "sc.SCDateTime.Date:createWithJD");
SCLUA_CHECK_LUA_ARG(tolua_S, ok);
pInstance->nYear = arg0;
lua_pushinteger(tolua_S, arg0);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", SCLUA_CLASSTYPE_LUA, nArgc, 1);
return 0;
}
int lua_speedcc_SCDateTimeDate_getMonth(lua_State* tolua_S)
{
SCLUA_CHECK_LUA_USERTYPE(tolua_S);
auto nArgc = lua_gettop(tolua_S) - 1;
if (nArgc == 1)
{
auto pInstance = (SCLUA_CLASSTYPE_CPP*)tolua_tousertype(tolua_S, 1, 0);
SCLUA_CHECK_LUA_INSTANCE(tolua_S, pInstance);
lua_pushinteger(tolua_S, pInstance->nMonth);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", SCLUA_CLASSTYPE_LUA, nArgc, 1);
return 0;
}
int lua_speedcc_SCDateTimeDate_setMonth(lua_State* tolua_S)
{
SCLUA_CHECK_LUA_USERTYPE(tolua_S);
auto nArgc = lua_gettop(tolua_S) - 1;
if (nArgc == 1)
{
auto pInstance = (SCLUA_CLASSTYPE_CPP*)tolua_tousertype(tolua_S, 1, 0);
SCLUA_CHECK_LUA_INSTANCE(tolua_S, pInstance);
int arg0;
bool ok = true;
ok = luaval_to_int32(tolua_S, 2, &arg0, "sc.SCDateTime.Date:createWithJD");
SCLUA_CHECK_LUA_ARG(tolua_S, ok);
pInstance->nMonth = arg0;
lua_pushinteger(tolua_S, arg0);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", SCLUA_CLASSTYPE_LUA, nArgc, 1);
return 0;
}
int lua_speedcc_SCDateTimeDate_getDay(lua_State* tolua_S)
{
SCLUA_CHECK_LUA_USERTYPE(tolua_S);
auto nArgc = lua_gettop(tolua_S) - 1;
if (nArgc == 1)
{
auto pInstance = (SCLUA_CLASSTYPE_CPP*)tolua_tousertype(tolua_S, 1, 0);
SCLUA_CHECK_LUA_INSTANCE(tolua_S, pInstance);
lua_pushinteger(tolua_S, pInstance->nDay);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", SCLUA_CLASSTYPE_LUA, nArgc, 1);
return 0;
}
int lua_speedcc_SCDateTimeDate_setDay(lua_State* tolua_S)
{
SCLUA_CHECK_LUA_USERTYPE(tolua_S);
auto nArgc = lua_gettop(tolua_S) - 1;
if (nArgc == 1)
{
auto pInstance = (SCLUA_CLASSTYPE_CPP*)tolua_tousertype(tolua_S, 1, 0);
SCLUA_CHECK_LUA_INSTANCE(tolua_S, pInstance);
int arg0;
bool ok = true;
ok = luaval_to_int32(tolua_S, 2, &arg0, "sc.SCDateTime.Date:createWithJD");
SCLUA_CHECK_LUA_ARG(tolua_S, ok);
pInstance->nDay = arg0;
lua_pushinteger(tolua_S, arg0);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", SCLUA_CLASSTYPE_LUA, nArgc, 1);
return 0;
}
SCLUA_SCDESTRUCT_FUNC_IMPLEMENT(SCDateTimeDate)
///------------ SCDateTime::Date
int lua_register_speedcc_SCDateTimeDate(lua_State* tolua_S)
{
tolua_usertype(tolua_S, SCLUA_CLASSTYPE_LUA);
tolua_cclass(tolua_S, SCLUA_MODULE, SCLUA_CLASSTYPE_LUA, SCLUA_MODULE_BASE, lua_speedcc_SCDateTimeDate_destruct);
tolua_beginmodule(tolua_S, SCLUA_MODULE);
tolua_function(tolua_S, "create", lua_speedcc_SCDateTimeDate_create);
tolua_function(tolua_S, "clone", lua_speedcc_SCDateTimeDate_clone);
tolua_function(tolua_S, "createYMD", lua_speedcc_SCDateTimeDate_createYMD);
tolua_function(tolua_S, "createWithJD", lua_speedcc_SCDateTimeDate_createWithJD);
tolua_function(tolua_S, "isValid", lua_speedcc_SCDateTimeDate_isValid);
tolua_function(tolua_S, "getWeekCountOfYear", lua_speedcc_SCDateTimeDate_getWeekCountOfYear);
tolua_function(tolua_S, "getDayCountOfMonth", lua_speedcc_SCDateTimeDate_getDayCountOfMonth);
tolua_function(tolua_S, "getDayCountOfYear", lua_speedcc_SCDateTimeDate_getDayCountOfYear);
tolua_variable(tolua_S, "year", lua_speedcc_SCDateTimeDate_getYear, lua_speedcc_SCDateTimeDate_setYear);
tolua_variable(tolua_S, "month", lua_speedcc_SCDateTimeDate_getMonth, lua_speedcc_SCDateTimeDate_setMonth);
tolua_variable(tolua_S, "day", lua_speedcc_SCDateTimeDate_getDay, lua_speedcc_SCDateTimeDate_setDay);
tolua_endmodule(tolua_S);
return 1;
}
#ifdef __cplusplus
}
#endif
NAMESPACE_SPEEDCC_END | 28.614035 | 114 | 0.747394 | kevinwu1024 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.