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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
392209b4255ab301e3a86595f36bfd8988a2a69a
| 305
|
cpp
|
C++
|
Puzzles/01_using.cpp
|
egaburov/codevault
|
1cad07aba42628a014bd91ad07d66f105614309c
|
[
"Apache-2.0"
] | null | null | null |
Puzzles/01_using.cpp
|
egaburov/codevault
|
1cad07aba42628a014bd91ad07d66f105614309c
|
[
"Apache-2.0"
] | null | null | null |
Puzzles/01_using.cpp
|
egaburov/codevault
|
1cad07aba42628a014bd91ad07d66f105614309c
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
int main()
{
#ifndef PART2
using namespace std;
#else
using std::cout;
using std::endl;
#endif
cout << "Hello, puzzling world!" << endl;
int cout;
cout = 10;
std::cout << "cout = " << cout << endl;
std::cout << "cout << 5 = " << (cout << 5) << endl;
return 0;
}
| 14.52381
| 54
| 0.554098
|
egaburov
|
3924056ad631b4acd0cd1e64fd8afe2c77aefdf5
| 1,091
|
cpp
|
C++
|
holdem/test/LYHoldemTrunk_tests.cpp
|
caiqingfeng/libpoker
|
a2c60884fc5c8e31455fb39e432c49e0df55956b
|
[
"Apache-2.0"
] | 1
|
2021-04-20T06:22:30.000Z
|
2021-04-20T06:22:30.000Z
|
holdem/test/LYHoldemTrunk_tests.cpp
|
caiqingfeng/libpoker
|
a2c60884fc5c8e31455fb39e432c49e0df55956b
|
[
"Apache-2.0"
] | null | null | null |
holdem/test/LYHoldemTrunk_tests.cpp
|
caiqingfeng/libpoker
|
a2c60884fc5c8e31455fb39e432c49e0df55956b
|
[
"Apache-2.0"
] | 2
|
2020-10-29T08:21:22.000Z
|
2020-12-02T06:40:18.000Z
|
/*
* LYHoldemTrunk_tests.cpp
*
* Created on: 2013-7-5
* Author: caiqingfeng
*/
#include "src/LYHoldemTrunk.h"
#include "src/LYHoldemTable.h"
//#include "common/src/my_log.h"
#include <gtest/gtest.h>
#include <string>
using std::string;
class LYHoldemTrunk_tests : public ::testing::Test
{
protected:
void SetUp()
{
table = new LYHoldemTable(string("this_is_table_id"), 9, LYTableOpen, string("this_is_table_name"));
table->openTrunk("999", "trunk_name", "player01", "888");
trunk = (LYHoldemTrunk *)table->getTrunk();
}
void TearDown()
{
delete table;
}
public:
LYHoldemTable *table;
LYHoldemTrunk *trunk;
};
TEST_F(LYHoldemTrunk_tests, init)
{
ASSERT_EQ(table->getStatus(), LYTableOpen);
ASSERT_EQ(trunk != NULL, true);
}
TEST_F(LYHoldemTrunk_tests, createGame)
{
ASSERT_EQ(trunk->ready2go(), false);
table->takeSeat(LYSeat1, 1000, "player01");
table->takeSeat(LYSeat2, 1000, "player02");
ASSERT_EQ(trunk->ready2go(), true);
trunk->createGame("", NULL);
ASSERT_EQ(trunk->getCurrentGame() != NULL, true);
}
| 21.392157
| 105
| 0.672777
|
caiqingfeng
|
392495d446dd59baed42e16d410910fa23022a25
| 4,144
|
hpp
|
C++
|
export/output_handler.hpp
|
simonpp/2dRidgeletBTE
|
5d08cbb5c57fc276c7a528f128615d23c37ef6a0
|
[
"BSD-3-Clause"
] | 1
|
2019-11-08T03:15:56.000Z
|
2019-11-08T03:15:56.000Z
|
export/output_handler.hpp
|
simonpp/2dRidgeletBTE
|
5d08cbb5c57fc276c7a528f128615d23c37ef6a0
|
[
"BSD-3-Clause"
] | null | null | null |
export/output_handler.hpp
|
simonpp/2dRidgeletBTE
|
5d08cbb5c57fc276c7a528f128615d23c37ef6a0
|
[
"BSD-3-Clause"
] | 1
|
2019-11-08T03:15:56.000Z
|
2019-11-08T03:15:56.000Z
|
#pragma once
#include <boost/assert.hpp>
#include <boost/lexical_cast.hpp>
#include "base/buffered_output_array.hpp"
#include "base/coeff_array.hpp"
#include "export/hdf_writer.hpp"
#include "spectral/macroscopic_quantities.hpp"
#include "spectral/polar_to_nodal.hpp"
class OutputHandler
{
private:
template <int dim>
using buffer_t = BufferType<dim>;
public:
template <typename POLAR_BASIS>
OutputHandler(const POLAR_BASIS &basis,
const Map &xmap,
const boltzmann::Polar2Nodal<POLAR_BASIS> &p2n,
int freq_mom = -1,
int dump = -1,
int bufsize = 1);
void compute(const CoeffArray<double> &full_vector, unsigned int timestep, double time);
private:
/// DoF distribution
Map xmap_;
/// Polar2Nodal
const boltzmann::Polar2Nodal<> p2n_;
/// moments output frequency
int freq_mom_;
/// solution output frequency (full solution vector)
int dump_;
/// buffer size
int bufsize_;
/// buffer counter
int ctr_ = 0;
/// density (scalar)
buffer_t<1> m_;
/// energy (scalar)
buffer_t<1> e_;
/// velocity (vector)
buffer_t<3> v_;
/// heat flow (vector)
buffer_t<3> q_;
/// energy flow (vector)
buffer_t<3> r_;
/// momentum flow (tensor)
buffer_t<9> M_;
/// pressure (tensor)
buffer_t<9> P_;
/// object to compute macroscopic quantities
boltzmann::MQEval mq_coeffs_;
std::vector<double> timesteps_;
};
template <typename POLAR_BASIS>
OutputHandler::OutputHandler(const POLAR_BASIS &basis,
const Map &xmap,
const boltzmann::Polar2Nodal<POLAR_BASIS> &p2n,
int freq_mom,
int dump,
int bufsize)
: xmap_(xmap)
, p2n_(p2n)
, freq_mom_(freq_mom)
, dump_(dump)
, bufsize_(bufsize)
, m_(xmap, bufsize)
, e_(xmap, bufsize)
, v_(xmap, bufsize)
, q_(xmap, bufsize)
, r_(xmap, bufsize)
, M_(xmap, bufsize)
, P_(xmap, bufsize)
{
mq_coeffs_.init(basis);
}
void
OutputHandler::compute(const CoeffArray<double> &full_vector, unsigned int timestep, double time)
{
typedef typename CoeffArray<double>::map_t map_t;
typedef map_t::index_t index_t;
BOOST_ASSERT(full_vector.get_map() == xmap_);
if (timestep % freq_mom_ == 0) {
timesteps_.push_back(time);
// check if buffer is full? => write
#pragma omp parallel
{
// boltzmann::Polar2Nodal_Evaluator<> p2n_adapter(p2n_);
// obtain thread-safe evaluator
auto evaluator = mq_coeffs_.evaluator();
Eigen::ArrayXd cp(p2n_.N());
int K = p2n_.K();
#pragma omp for schedule(static)
for (index_t lid = 0; lid < full_vector.get_map().lsize(); ++lid) {
// TODO: call p2n, reshape full_vector.get(lid) first
typedef Eigen::MatrixXd matrix_t;
Eigen::Map<const matrix_t> cn(full_vector.get(lid).data(), K, K);
p2n_.to_polar(cp, cn);
double norm = cp.abs2().sum();
evaluator(cp);
// access results and copy to buffer
m_.fill(evaluator.m, ctr_, lid);
e_.fill(evaluator.e, ctr_, lid);
v_.fill(evaluator.v, ctr_, lid);
q_.fill(evaluator.q, ctr_, lid);
r_.fill(evaluator.r, ctr_, lid);
M_.fill(evaluator.M, ctr_, lid);
P_.fill(evaluator.P, ctr_, lid);
}
}
ctr_++; // increment buffer counter
if (ctr_ == bufsize_) {
// write HDF
char fname[256];
std::sprintf(fname, "solution_vector%06d.h5", timestep);
PHDFWriter exporter(fname, full_vector.get_map().comm());
exporter.write(m_, "m");
exporter.write(e_, "e");
exporter.write(v_, "v");
exporter.write(q_, "q");
exporter.write(r_, "r");
exporter.write(M_, "M");
exporter.write(P_, "P");
// todo write meta data ...
// reset counter
ctr_ = 0;
}
}
if (timestep % dump_ == 0) {
char fname[256];
std::sprintf(fname, "fsolution_vector%06d.h5", timestep);
PHDFWriter exporter(fname, full_vector.get_map().comm());
exporter.write(full_vector, "C");
}
}
| 27.812081
| 97
| 0.611969
|
simonpp
|
3929ea94f6656bd60f5e0ba71183fd5b9ba13ec4
| 2,023
|
cpp
|
C++
|
Problems/StringManipulation.cpp
|
SimpleTechTalks/SimpleTechTalks
|
eefdb4cffc955f43535f4054d1558978ae0088e1
|
[
"MIT"
] | null | null | null |
Problems/StringManipulation.cpp
|
SimpleTechTalks/SimpleTechTalks
|
eefdb4cffc955f43535f4054d1558978ae0088e1
|
[
"MIT"
] | null | null | null |
Problems/StringManipulation.cpp
|
SimpleTechTalks/SimpleTechTalks
|
eefdb4cffc955f43535f4054d1558978ae0088e1
|
[
"MIT"
] | null | null | null |
/********************************************************************************
*
* Find Minimum number of operations required to convert string1 to string2.
* Only insert and delete character operations are allowed.
*
********************************************************************************/
#include <stdio.h>
#include <string.h>
int calculateWeight(char* s, char* t, int sIndex, int tIndex, int sLen, int tLen)
{
int min = 0;
if((sLen-1) < sIndex)
{
// we need to insert now
min = (tLen - tIndex);
//printf("inserting all now charcters %d \n", min);
return (min < 0 ? 0 : min);
}
if((tLen-1) < tIndex)
{
// we need to delete now
min = (sLen - sIndex);
//printf("deleting all now charcters %d \n", min);
return (min < 0 ? 0 : min);
}
if(s[sIndex] == t[tIndex])
{
// No weight added
//printf("same character found %c %c\n", s[sIndex], t[tIndex]);
min = calculateWeight(s, t, sIndex+1, tIndex+1, sLen, tLen);
return min;
}
else
{
// insert char
int temp1 = calculateWeight(s, t, sIndex, tIndex+1, sLen, tLen);
// delete char
int temp2 = calculateWeight(s, t, sIndex+1, tIndex, sLen, tLen);
// find min weight
if(temp1 < temp2)
{
//printf("Minimum weight is for insert %d \n", temp1);
min = temp1;
}
else
{
//printf("Minimum weight is for delete %d \n", temp2);
min = temp2;
}
}
return (min + 1);
}
int main()
{
char source[30];
char target[30];
printf("Insert source string \n");
scanf("%s", source);
printf("Insert target string \n");
scanf("%s", target);
printf("Input string %s Target String %s\n", source, target);
int sLen = strlen(source);
int tLen = strlen(target);
int weight = calculateWeight(source, target, 0, 0, sLen, tLen);
printf("Final weight is %d \n", weight);
}
| 25.2875
| 83
| 0.500741
|
SimpleTechTalks
|
392a772a9c0797b0bca9c9921c006396f93d22e9
| 796
|
hpp
|
C++
|
src/Scene.hpp
|
i-yam-jeremy/path-tracer
|
21a44a2fb4867bc1b678e26f1884d2ff0d1ca5b3
|
[
"MIT"
] | null | null | null |
src/Scene.hpp
|
i-yam-jeremy/path-tracer
|
21a44a2fb4867bc1b678e26f1884d2ff0d1ca5b3
|
[
"MIT"
] | null | null | null |
src/Scene.hpp
|
i-yam-jeremy/path-tracer
|
21a44a2fb4867bc1b678e26f1884d2ff0d1ca5b3
|
[
"MIT"
] | null | null | null |
//
// Scene.hpp
// Path Tracer
//
// Created by Jeremy Berchtold on 12/8/19.
// Copyright © 2019 Jeremy Berchtold. All rights reserved.
//
#ifndef Scene_hpp
#define Scene_hpp
#include <vector>
#include <string>
#include <memory>
#include "Object.hpp"
/*
A 3D scene containing objects and path tracer settings.
*/
class Scene {
public:
/*
Loads a scene from the given config file.
@param configFilename - The path to the scene config file.
*/
Scene(std::string configFilename);
/*
Returns the objects in this scene.
@return The objects in this scene.
*/
std::vector<std::shared_ptr<Object>> getObjects();
private:
/*
The objects in this scene.
*/
std::vector<std::shared_ptr<Object>> objects;
};
#endif /* Scene_hpp */
| 18.952381
| 64
| 0.650754
|
i-yam-jeremy
|
392b2fb33e3a5be846ecc071b3cfb99d05c11ae8
| 469
|
cpp
|
C++
|
hackerrank/c-tutorial-stringstream/main.cpp
|
Yash-Singh1/competitive-programming
|
3b9d278ed8138ab614e2a3d748627db8f4a2cdbd
|
[
"MIT"
] | 1
|
2021-04-25T21:58:57.000Z
|
2021-04-25T21:58:57.000Z
|
hackerrank/c-tutorial-stringstream/main.cpp
|
Yash-Singh1/competitive-programming
|
3b9d278ed8138ab614e2a3d748627db8f4a2cdbd
|
[
"MIT"
] | null | null | null |
hackerrank/c-tutorial-stringstream/main.cpp
|
Yash-Singh1/competitive-programming
|
3b9d278ed8138ab614e2a3d748627db8f4a2cdbd
|
[
"MIT"
] | null | null | null |
#include <sstream>
#include <vector>
#include <iostream>
using namespace std;
vector<int> parseInts(string str)
{
vector<int> ans;
stringstream ss(str);
char drop;
while (!ss.eof())
{
int next;
ss >> next;
ans.push_back(next);
ss >> drop;
}
return ans;
}
int main()
{
string str;
cin >> str;
vector<int> integers = parseInts(str);
for (int i = 0; i < integers.size(); i++)
{
cout << integers[i] << "\n";
}
return 0;
}
| 14.212121
| 43
| 0.577825
|
Yash-Singh1
|
392bad9968b7b3e5042883a4263c61a0a1caff31
| 2,560
|
cpp
|
C++
|
random_walk/apps/node2vec.cpp
|
shixuansun/ThunderRW
|
960bac187d797d5141f61d748e3f3b15c76e8991
|
[
"MIT"
] | 20
|
2021-05-05T13:08:29.000Z
|
2022-03-30T22:33:12.000Z
|
random_walk/apps/node2vec.cpp
|
shixuansun/ThunderRW
|
960bac187d797d5141f61d748e3f3b15c76e8991
|
[
"MIT"
] | null | null | null |
random_walk/apps/node2vec.cpp
|
shixuansun/ThunderRW
|
960bac187d797d5141f61d748e3f3b15c76e8991
|
[
"MIT"
] | 2
|
2021-09-03T14:06:04.000Z
|
2021-10-02T18:40:53.000Z
|
//
// Created by Shixuan Sun on 11/5/20.
//
#include "creeper_main.h"
HyperParameter g_para = {ExecutionMode::Dynamic, SamplingMethod::MaxWeightRejectionSampling, 0, {nullptr, 0}};
struct Node2Vec {
int l_;
double p_;
double q_;
double max_;
Graph* g_;
Node2Vec() {}
Node2Vec(int l, double p, double q, Graph* g) : l_(l), p_(p), q_(q), g_(g) {
max_ = std::max(1.0, std::max(q_, p_));
}
Node2Vec(const Node2Vec& n2v) : Node2Vec(n2v.l_, n2v.p_, n2v.q_, n2v.g_) {}
inline double weight(WalkerMeta& w, intT begin, intT end, int64_t eid) {
if (w.length_ == 1) {
return max_;
}
else {
int prev = w.seq_[w.length_ - 2];
if (end == prev) {
return p_;
} else if (g_->is_neighbor(prev, end)) {
return 1.0;
} else {
return q_;
}
}
}
inline bool update(WalkerMeta& w, intT begin, intT end, int64_t eid) {
return w.length_ == l_;
}
inline double max_weight(WalkerMeta& w) {
return max_;
}
};
void execute(Graph &graph, InputParser &cmd_parser) {
/**
* Extract the parameters.
* 1. -l: the target length.
* 2. -p: the return parameter.
* 3. -q: the in-out parameter.
*/
int l = 80;
if (!cmd_parser.get_cmd_option("-l").empty()) {
l = std::stoi(cmd_parser.get_cmd_option("-l"));
}
g_para.length_ = l;
double p = 2;
if (!cmd_parser.get_cmd_option("-p").empty()) {
p = std::stof(cmd_parser.get_cmd_option("-p"));
}
p = 1.0 / p;
double q = 0.5;
if (!cmd_parser.get_cmd_option("-q").empty()) {
q = std::stof(cmd_parser.get_cmd_option("-q"));
}
q = 1.0 / q;
int em = static_cast<int>(ExecutionMode::Dynamic);
if (!cmd_parser.get_cmd_option("-em").empty()) {
em = std::stoi(cmd_parser.get_cmd_option("-em"));
}
g_para.execution_ = static_cast<ExecutionMode>(em);
int sm = static_cast<int>(SamplingMethod::MaxWeightRejectionSampling);
if (!cmd_parser.get_cmd_option("-sm").empty()) {
sm = std::stoi(cmd_parser.get_cmd_option("-sm"));
}
g_para.sample_ = static_cast<SamplingMethod>(sm);
/**
* Initialize the walkers.
*/
std::vector<WalkerMeta> walkers;
generate_all_source(graph, walkers);
/**
* Execute the walkers.
*/
compute(graph, walkers, Node2Vec(l, p, q, &graph));
/**
* Finalize the walkers as necessary.
*/
}
| 23.925234
| 110
| 0.555078
|
shixuansun
|
392d035e4eacfc802fdd0b3c6c98823fa9cb55f5
| 12,537
|
cpp
|
C++
|
Common/C++/Helpers/CSR_OpenGLHelper.cpp
|
Jeanmilost/CompactStar
|
1c1a416f3abddbe4690e4dfa537f748c31412256
|
[
"MIT"
] | 4
|
2019-12-20T00:29:45.000Z
|
2022-03-10T10:09:43.000Z
|
Common/C++/Helpers/CSR_OpenGLHelper.cpp
|
Jeanmilost/CompactStar
|
1c1a416f3abddbe4690e4dfa537f748c31412256
|
[
"MIT"
] | null | null | null |
Common/C++/Helpers/CSR_OpenGLHelper.cpp
|
Jeanmilost/CompactStar
|
1c1a416f3abddbe4690e4dfa537f748c31412256
|
[
"MIT"
] | 3
|
2020-02-10T15:18:15.000Z
|
2022-01-31T06:28:23.000Z
|
/****************************************************************************
* ==> CSR_OpenGLHelper ----------------------------------------------------*
****************************************************************************
* Description : This module provides an helper class for OpenGL *
* Developer : Jean-Milost Reymond *
* Copyright : 2017 - 2022, this file is part of the CompactStar Engine. *
* You are free to copy or redistribute this file, modify it, *
* or use it for your own projects, commercial or not. This *
* file is provided "as is", WITHOUT ANY WARRANTY OF ANY *
* KIND. THE DEVELOPER IS NOT RESPONSIBLE FOR ANY DAMAGE OF *
* ANY KIND, ANY LOSS OF DATA, OR ANY LOSS OF PRODUCTIVITY *
* TIME THAT MAY RESULT FROM THE USAGE OF THIS SOURCE CODE, *
* DIRECTLY OR NOT. *
****************************************************************************/
#include "CSR_OpenGLHelper.h"
// std
#include <math.h>
#include <memory>
#include <stdexcept>
// compactStar engine
#include "CSR_Common.h"
#include "CSR_Geometry.h"
// visual studio specific code
#ifdef _MSC_VER
// std
#define _USE_MATH_DEFINES
#include <math.h>
#endif
// code specific for all compilers but not for visual studio
#ifndef _MSC_VER
#pragma package(smart_init)
#ifdef __llvm__
#pragma link "glewSL.a"
#else
#pragma link "glewSL.lib"
#endif
#endif
//---------------------------------------------------------------------------
// CSR_OpenGLHelper
//---------------------------------------------------------------------------
void CSR_OpenGLHelper::EnableOpenGL(HWND hWnd, HDC* hDC, HGLRC* hRC)
{
PIXELFORMATDESCRIPTOR pfd;
int iFormat;
// get the device context
*hDC = ::GetDC(hWnd);
ZeroMemory(&pfd, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 32;
pfd.iLayerType = PFD_MAIN_PLANE;
// set the pixel format for the device context
iFormat = ChoosePixelFormat(*hDC, &pfd);
SetPixelFormat(*hDC, iFormat, &pfd);
// create and enable the OpenGL render context
*hRC = wglCreateContext(*hDC);
wglMakeCurrent(*hDC, *hRC);
}
//---------------------------------------------------------------------------
void CSR_OpenGLHelper::DisableOpenGL(HWND hwnd, HDC hDC, HGLRC hRC)
{
wglMakeCurrent(NULL, NULL);
wglDeleteContext(hRC);
::ReleaseDC(hwnd, hDC);
}
//---------------------------------------------------------------------------
void CSR_OpenGLHelper::CreateViewport(float w,
float h,
float zNear,
float zFar,
const CSR_OpenGLShader* pShader,
CSR_Matrix4& matrix)
{
if (!pShader)
return;
csrShaderEnable(pShader);
// prevent the width to reach 0
if (!w)
w = 0.1f;
// prevent the height to reach 0
if (!h)
h = 0.1f;
// calculate matrix items
const float fov = 45.0f;
const float aspect = w / h;
// create the OpenGL viewport
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
// create the projection matrix
csrMat4Perspective(fov, aspect, zNear, zFar, &matrix);
// connect projection matrix to shader
const GLint projectionUniform = glGetUniformLocation(pShader->m_ProgramID, "csr_uProjection");
glUniformMatrix4fv(projectionUniform, 1, 0, &matrix.m_Table[0][0]);
}
//---------------------------------------------------------------------------
CSR_Matrix4 CSR_OpenGLHelper::FitModelInView(const CSR_Box* pBox, float fov, bool rotated)
{
CSR_Matrix4 matrix;
if (!pBox)
{
csrMat4Identity(&matrix);
return matrix;
}
#ifdef _MSC_VER
float angle = 0.0f;
CSR_Vector3 r = {};
CSR_Matrix4 rotateMatrixX = {};
#else
float angle;
CSR_Vector3 r;
CSR_Matrix4 rotateMatrixX;
#endif
// set rotation axis
r.m_X = 1.0f;
r.m_Y = 0.0f;
r.m_Z = 0.0f;
// set rotation angle
angle = float(rotated ? -M_PI * 0.5 : 0.0);
csrMat4Rotate(angle, &r, &rotateMatrixX);
CSR_Matrix4 rotateMatrixY;
// set rotation axis
r.m_X = 0.0f;
r.m_Y = 1.0f;
r.m_Z = 0.0f;
// set rotation angle
angle = float(rotated ? -M_PI * 0.25 : M_PI * 0.25);
csrMat4Rotate(angle, &r, &rotateMatrixY);
CSR_Matrix4 rotateMatrixZ;
// set rotation axis
r.m_X = 0.0f;
r.m_Y = 0.0f;
r.m_Z = 1.0f;
// set rotation angle
angle = 0.0f;
csrMat4Rotate(angle, &r, &rotateMatrixZ);
#ifdef _MSC_VER
CSR_Vector3 factor = {};
CSR_Matrix4 scaleMatrix = {};
#else
CSR_Vector3 factor;
CSR_Matrix4 scaleMatrix;
#endif
// set scale factor
factor.m_X = 1.0f;
factor.m_Y = 1.0f;
factor.m_Z = 1.0f;
csrMat4Scale(&factor, &scaleMatrix);
CSR_Matrix4 combinedMatrix1;
CSR_Matrix4 combinedMatrix2;
CSR_Matrix4 combinedMatrix3;
// calculate the intermediate matrix (on which only the rotation and scaling were applied)
csrMat4Multiply(&scaleMatrix, &rotateMatrixX, &combinedMatrix1);
csrMat4Multiply(&combinedMatrix1, &rotateMatrixY, &combinedMatrix2);
csrMat4Multiply(&combinedMatrix2, &rotateMatrixZ, &combinedMatrix3);
#ifdef _MSC_VER
CSR_Box rotatedBox = {};
#else
CSR_Box rotatedBox;
#endif
csrMat4ApplyToVector(&combinedMatrix3, &pBox->m_Min, &rotatedBox.m_Min);
csrMat4ApplyToVector(&combinedMatrix3, &pBox->m_Max, &rotatedBox.m_Max);
// calculate the box size (on the x and y axis
#ifdef __CODEGEARC__
const float x = std::fabs(rotatedBox.m_Max.m_X - rotatedBox.m_Min.m_X);
const float y = std::fabs(rotatedBox.m_Max.m_Y - rotatedBox.m_Min.m_Y);
#else
const float x = fabsf(rotatedBox.m_Max.m_X - rotatedBox.m_Min.m_X);
const float y = fabsf(rotatedBox.m_Max.m_Y - rotatedBox.m_Min.m_Y);
#endif
// search for longest axis and the longest viewport edge
#ifdef _MSC_VER
const float longestAxis = max(x, y);
#else
const float longestAxis = std::max(x, y);
#endif
// Calculate the camera distance
#ifdef __CODEGEARC__
const float distance = std::fabs(longestAxis / std::sinf(fov / 2.0f)) * 0.25f;
#else
const float distance = fabsf(longestAxis / sinf(fov / 2.0f)) * 0.25f;
#endif
#ifdef _MSC_VER
CSR_Vector3 t = {};
CSR_Matrix4 translateMatrix = {};
#else
CSR_Vector3 t;
CSR_Matrix4 translateMatrix;
#endif
// set translation
t.m_X = -(rotatedBox.m_Min.m_X + rotatedBox.m_Max.m_X) / 2.0f;
t.m_Y = -(rotatedBox.m_Min.m_Y + rotatedBox.m_Max.m_Y) / 2.0f;
t.m_Z = -distance;
csrMat4Translate(&t, &translateMatrix);
// calculate the final model view matrix
csrMat4Multiply(&combinedMatrix3, &translateMatrix, &matrix);
return matrix;
}
//---------------------------------------------------------------------------
void CSR_OpenGLHelper::BuildMatrix(const CSR_Vector3* pTranslation,
const CSR_Vector3* pRotation,
const CSR_Vector3* pScaling,
CSR_Matrix4* pMatrix)
{
if (!pTranslation || !pRotation || !pScaling || !pMatrix)
return;
#ifdef _MSC_VER
CSR_Vector3 axis = {};
CSR_Matrix4 matrixTranslate = {};
CSR_Matrix4 matrixX = {};
CSR_Matrix4 matrixY = {};
CSR_Matrix4 matrixZ = {};
CSR_Matrix4 matrixScale = {};
CSR_Matrix4 buildMatrix1 = {};
CSR_Matrix4 buildMatrix2 = {};
CSR_Matrix4 buildMatrix3 = {};
#else
CSR_Vector3 axis;
CSR_Matrix4 matrixTranslate;
CSR_Matrix4 matrixX;
CSR_Matrix4 matrixY;
CSR_Matrix4 matrixZ;
CSR_Matrix4 matrixScale;
CSR_Matrix4 buildMatrix1;
CSR_Matrix4 buildMatrix2;
CSR_Matrix4 buildMatrix3;
#endif
// create a translation matrix
csrMat4Translate(pTranslation, &matrixTranslate);
// get the rotation x axis
axis.m_X = 1.0f;
axis.m_Y = 0.0f;
axis.m_Z = 0.0f;
// create a rotation matrix on the x axis
csrMat4Rotate(pRotation->m_X, &axis, &matrixX);
// get the rotation y axis
axis.m_X = 0.0f;
axis.m_Y = 1.0f;
axis.m_Z = 0.0f;
// create a rotation matrix on the y axis
csrMat4Rotate(pRotation->m_Y, &axis, &matrixY);
// get the rotation z axis
axis.m_X = 0.0f;
axis.m_Y = 0.0f;
axis.m_Z = 1.0f;
// create a rotation matrix on the z axis
csrMat4Rotate(pRotation->m_Z, &axis, &matrixZ);
// create a scale matrix
csrMat4Scale(pScaling, &matrixScale);
// rebuild the selected object model matrix
csrMat4Multiply(&matrixScale, &matrixX, &buildMatrix1);
csrMat4Multiply(&buildMatrix1, &matrixY, &buildMatrix2);
csrMat4Multiply(&buildMatrix2, &matrixZ, &buildMatrix3);
csrMat4Multiply(&buildMatrix3, &matrixTranslate, pMatrix);
}
//---------------------------------------------------------------------------
void CSR_OpenGLHelper::AddTexture(const void* pKey, GLuint id, IResources& resources)
{
// search a matching texture in the OpenGL resources
CSR_OpenGLHelper::IResources::iterator it = resources.find((void*)pKey);
// found one?
if (it != resources.end())
{
if (it->second->m_ID != GLint(id))
throw new std::range_error("The existing resource texture identifier differs from the identifier passed in arguments");
// increase its use count
++it->second->m_UseCount;
return;
}
// create and add a new texture identifier
std::auto_ptr<CSR_OpenGLID> pID(new CSR_OpenGLID());
csrOpenGLIDInit(pID.get());
pID->m_pKey = (void*)pKey;
pID->m_ID = id;
pID->m_UseCount = 1;
resources[(void*)pKey] = pID.get();
pID.release();
}
//---------------------------------------------------------------------------
void CSR_OpenGLHelper::DeleteTexture(const void* pKey, IResources& resources)
{
// search the matching texture in the OpenGL resources
CSR_OpenGLHelper::IResources::iterator it = resources.find((void*)pKey);
// found one?
if (it == resources.end())
return;
// release one usage
if (it->second->m_UseCount)
--it->second->m_UseCount;
// still used?
if (it->second->m_UseCount)
return;
// texture was used?
if (it->second->m_ID != GLint(M_CSR_Error_Code))
// release it
glDeleteTextures(1, (GLuint*)(&it->second->m_ID));
// erase the resource (no longer used)
delete it->second;
resources.erase(it);
}
//---------------------------------------------------------------------------
void* CSR_OpenGLHelper::GetTextureID(const void* pKey, IResources& resources)
{
// search the matching texture in the OpenGL resources
CSR_OpenGLHelper::IResources::const_iterator it = resources.find((void*)pKey);
// found it?
if (it != resources.end())
return it->second;
return NULL;
}
//---------------------------------------------------------------------------
void CSR_OpenGLHelper::ClearResources(IResources& resources)
{
// delete the scene textures
for (CSR_OpenGLHelper::IResources::iterator it = resources.begin(); it != resources.end(); ++it)
delete it->second;
resources.clear();
}
//---------------------------------------------------------------------------
| 32.311856
| 132
| 0.534737
|
Jeanmilost
|
392dc469b9cfbc3279154ee1b903dd9d84afd062
| 1,289
|
cc
|
C++
|
common/clock_test.cc
|
sgorse12/cloud-spanner-emulator
|
13ebb6d42867bfbc80224b4a74a896b683ae4555
|
[
"Apache-2.0"
] | 179
|
2020-03-30T20:30:49.000Z
|
2022-03-31T04:47:55.000Z
|
common/clock_test.cc
|
sgorse12/cloud-spanner-emulator
|
13ebb6d42867bfbc80224b4a74a896b683ae4555
|
[
"Apache-2.0"
] | 53
|
2020-08-31T15:14:30.000Z
|
2022-03-30T21:28:36.000Z
|
common/clock_test.cc
|
sgorse12/cloud-spanner-emulator
|
13ebb6d42867bfbc80224b4a74a896b683ae4555
|
[
"Apache-2.0"
] | 26
|
2020-04-02T04:05:58.000Z
|
2022-02-22T12:05:55.000Z
|
//
// Copyright 2020 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 "common/clock.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "zetasql/base/testing/status_matchers.h"
#include "tests/common/proto_matchers.h"
namespace google {
namespace spanner {
namespace emulator {
namespace frontend {
namespace {
TEST(Clock, ClockReturnsIncreasingValues) {
Clock clock;
absl::Time t1 = clock.Now();
absl::Time t2 = clock.Now();
EXPECT_GT(t2, t1);
}
TEST(Clock, ClockReturnsValuesAtMicrosecondGranularity) {
Clock clock;
absl::Time t1 = clock.Now();
EXPECT_EQ(t1, absl::FromUnixMicros(absl::ToUnixMicros(t1)));
}
} // namespace
} // namespace frontend
} // namespace emulator
} // namespace spanner
} // namespace google
| 25.27451
| 75
| 0.72692
|
sgorse12
|
392dea0213587683dc1a592a19996a6659ea79a6
| 2,769
|
cpp
|
C++
|
modules/task_1/voronin_a_multi_scalar/main.cpp
|
ImKonstant/pp_2020_autumn_engineer
|
c8ac69681201b63f5cf8b6c6cd790f48f037532a
|
[
"BSD-3-Clause"
] | 1
|
2020-10-30T13:49:58.000Z
|
2020-10-30T13:49:58.000Z
|
modules/task_1/voronin_a_multi_scalar/main.cpp
|
ImKonstant/pp_2020_autumn_engineer
|
c8ac69681201b63f5cf8b6c6cd790f48f037532a
|
[
"BSD-3-Clause"
] | 2
|
2020-11-14T18:00:55.000Z
|
2020-11-19T16:12:50.000Z
|
modules/task_1/voronin_a_multi_scalar/main.cpp
|
ImKonstant/pp_2020_autumn_engineer
|
c8ac69681201b63f5cf8b6c6cd790f48f037532a
|
[
"BSD-3-Clause"
] | 1
|
2020-10-14T19:37:21.000Z
|
2020-10-14T19:37:21.000Z
|
// Copyright 2020 Voronin Aleksey
#include <gtest-mpi-listener.hpp>
#include <gtest/gtest.h>
#include <vector>
#include "./multi_scalar.h"
TEST(Parallel_Operations_MPI, Test_Scalar) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> global_vec, second_global_vec;
const int count_size_vector = 100;
if (rank == 0) {
global_vec = getRandomVector(count_size_vector);
second_global_vec = getRandomVector(count_size_vector);
}
int global_sum = getParallelOperations(global_vec, second_global_vec, count_size_vector);
if (rank == 0) {
int reference_sum = getSequentialOperations(global_vec, second_global_vec);
ASSERT_EQ(global_sum, reference_sum);
}
}
TEST(Parallel_Operations_MPI, Test_Cant_Get_Vector_With_Wrong_Size) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> global_vec, second_global_vec;
const int count_size_vector = -100;
if (rank == 0) {
ASSERT_ANY_THROW(getRandomVector(count_size_vector));
}
}
TEST(Parallel_Operations_MPI, Test_Can_Create_Vector) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> global_vec, second_global_vec;
const int count_size_vector = 100;
if (rank == 0) {
ASSERT_NO_THROW(global_vec = getRandomVector(count_size_vector));
}
}
TEST(Parallel_Operations_MPI, Test_Can_Get_Parallel_Operations) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> global_vec, second_global_vec;
const int count_size_vector = 100;
if (rank == 0) {
global_vec = getRandomVector(count_size_vector);
second_global_vec = getRandomVector(count_size_vector);
}
ASSERT_NO_THROW(getParallelOperations(global_vec, second_global_vec, count_size_vector));
}
TEST(Parallel_Operations_MPI, Test_Can_Get_Sequential_Operations) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> global_vec, second_global_vec;
const int count_size_vector = 100;
if (rank == 0) {
global_vec = getRandomVector(count_size_vector);
second_global_vec = getRandomVector(count_size_vector);
ASSERT_NO_THROW(getSequentialOperations(global_vec, second_global_vec));
}
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment);
::testing::TestEventListeners& listeners =
::testing::UnitTest::GetInstance()->listeners();
listeners.Release(listeners.default_result_printer());
listeners.Release(listeners.default_xml_generator());
listeners.Append(new GTestMPIListener::MPIMinimalistPrinter);
return RUN_ALL_TESTS();
}
| 31.11236
| 93
| 0.724449
|
ImKonstant
|
393125001c7d34b4273e6fc167d0200adb3f9718
| 250
|
cpp
|
C++
|
000/ISN/test_cpp/test-build/main.cpp
|
Tehcam/Studies
|
69477a211d8c686473b171ad2fa4298ead2ee60d
|
[
"MIT"
] | null | null | null |
000/ISN/test_cpp/test-build/main.cpp
|
Tehcam/Studies
|
69477a211d8c686473b171ad2fa4298ead2ee60d
|
[
"MIT"
] | null | null | null |
000/ISN/test_cpp/test-build/main.cpp
|
Tehcam/Studies
|
69477a211d8c686473b171ad2fa4298ead2ee60d
|
[
"MIT"
] | null | null | null |
/**********************************************/
// Sprod-CMachet
// Main
// Description
/**********************************************/
#include <iostream>
int main(){
std::cout << "Hello world !" << std::endl;
return 0;
}
// end // Main
| 16.666667
| 48
| 0.348
|
Tehcam
|
393230aaba37636bb1ebe1f192eff6b8cd71ec0a
| 2,122
|
cpp
|
C++
|
TLE2000/915c.cpp
|
Peppa-Peddler/graph-theory
|
ed022859a1378386d8dba4e7ade6a96a7d683827
|
[
"MIT"
] | null | null | null |
TLE2000/915c.cpp
|
Peppa-Peddler/graph-theory
|
ed022859a1378386d8dba4e7ade6a96a7d683827
|
[
"MIT"
] | null | null | null |
TLE2000/915c.cpp
|
Peppa-Peddler/graph-theory
|
ed022859a1378386d8dba4e7ade6a96a7d683827
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
#define LL long long
#define PII pair<int, int>
#define VI vector<int>
#define PB push_back
#define PQ priority_queue
#define MP make_pair
#define F first
#define S second
#define MOD 1000000007
#define N6 1000006
#define N5 100005
#define N4 10004
#define N3 1003
#define PI 3.1415926535897932384626
#define N N5
#define clr(v, a) memset(v, a, sizeof(v))
#define all(x) x.begin(),x.end()
#define R(i, n) for(int i=0; i<n; i++)
#define len(x) ((int)(x).size())
#define bits(x) __builtin_popcount(x)
#define bitsLL(x) __builtin_popcountll(x)
#define zerosl(x) __builtin_clz(x)
#define zerosr(x) __builtin_ctz(x)
/*
⢸⣿⣿⣿⣿⠃⠄⢀⣴⡾⠃⠄⠄⠄⠄⠄⠈⠺⠟⠛⠛⠛⠛⠻⢿⣿⣿⣿⣿⣶⣤⡀⠄
⢸⣿⣿⣿⡟⢀⣴⣿⡿⠁⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⣸⣿⣿⣿⣿⣿⣿⣿⣷
⢸⣿⣿⠟⣴⣿⡿⡟⡼⢹⣷⢲⡶⣖⣾⣶⢄⠄⠄⠄⠄⠄⢀⣼⣿⢿⣿⣿⣿⣿⣿⣿⣿
⢸⣿⢫⣾⣿⡟⣾⡸⢠⡿⢳⡿⠍⣼⣿⢏⣿⣷⢄⡀⠄⢠⣾⢻⣿⣸⣿⣿⣿⣿⣿⣿⣿
⡿⣡⣿⣿⡟⡼⡁⠁⣰⠂⡾⠉⢨⣿⠃⣿⡿⠍⣾⣟⢤⣿⢇⣿⢇⣿⣿⢿⣿⣿⣿⣿⣿
⣱⣿⣿⡟⡐⣰⣧⡷⣿⣴⣧⣤⣼⣯⢸⡿⠁⣰⠟⢀⣼⠏⣲⠏⢸⣿⡟⣿⣿⣿⣿⣿⣿
⣿⣿⡟⠁⠄⠟⣁⠄⢡⣿⣿⣿⣿⣿⣿⣦⣼⢟⢀⡼⠃⡹⠃⡀⢸⡿⢸⣿⣿⣿⣿⣿⡟
⣿⣿⠃⠄⢀⣾⠋⠓⢰⣿⣿⣿⣿⣿⣿⠿⣿⣿⣾⣅⢔⣕⡇⡇⡼⢁⣿⣿⣿⣿⣿⣿⢣
⣿⡟⠄⠄⣾⣇⠷⣢⣿⣿⣿⣿⣿⣿⣿⣭⣀⡈⠙⢿⣿⣿⡇⡧⢁⣾⣿⣿⣿⣿⣿⢏⣾
⣿⡇⠄⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⢻⠇⠄⠄⢿⣿⡇⢡⣾⣿⣿⣿⣿⣿⣏⣼⣿
⣿⣷⢰⣿⣿⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⢰⣧⣀⡄⢀⠘⡿⣰⣿⣿⣿⣿⣿⣿⠟⣼⣿⣿
⢹⣿⢸⣿⣿⠟⠻⢿⣿⣿⣿⣿⣿⣿⣿⣶⣭⣉⣤⣿⢈⣼⣿⣿⣿⣿⣿⣿⠏⣾⣹⣿⣿
⢸⠇⡜⣿⡟⠄⠄⠄⠈⠙⣿⣿⣿⣿⣿⣿⣿⣿⠟⣱⣻⣿⣿⣿⣿⣿⠟⠁⢳⠃⣿⣿⣿
⠄⣰⡗⠹⣿⣄⠄⠄⠄⢀⣿⣿⣿⣿⣿⣿⠟⣅⣥⣿⣿⣿⣿⠿⠋⠄⠄⣾⡌⢠⣿⡿⠃
⠜⠋⢠⣷⢻⣿⣿⣶⣾⣿⣿⣿⣿⠿⣛⣥⣾⣿⠿⠟⠛⠉⠄⠄
*/
using namespace std;
LL n, m, k, t = 1;
string str, sec;
LL getper(LL num){
stack<int> s;
str = sec;
string result = "";
num = num - 1;
for (int i = 1; i < str.size() + 1; i++) {
s.push(num % i);
num = num / i;
}
for (int i = 0; i < str.size(); i++) {
int a = s.top();
result += str[a];
int j;
for (j = a; j < str.length(); j++)
str[j] = str[j + 1];
str[j + 1] = '\0';
s.pop();
}
return stoll(result);
}
LL solve(){
cin >> n;
cin >> m;
str = to_string(n);
sort(str.begin(), str.end());
n = stoll(str);
sec = str;
LL per[20];
per[0] = 1;
R(i, 19) per[i + 1] = per[ i ]*(i+1);
LL l = 1, r = per[ len(str) ] + 1, mid;
while( r - l > 1 ){
mid = (r + l) / 2;
if( getper(mid) <= m ) l = mid;
else r = mid;
}
return getper(l);
}
int main(){
//cin >> t;
while(t--) cout << solve() << endl;
//while(t--) solve();
}
| 20.018868
| 45
| 0.409991
|
Peppa-Peddler
|
393676d32f988f298851c967d1aaa256d43ed1ed
| 1,002
|
cpp
|
C++
|
Video/ScreenCapture/ScreenCapture.cpp
|
threedeyes/haiku_media_addons
|
4efbbbf5d35949748f4e6fc1b79b7f4e854751d6
|
[
"MIT"
] | 2
|
2022-01-17T21:24:25.000Z
|
2022-01-18T03:30:50.000Z
|
Video/ScreenCapture/ScreenCapture.cpp
|
threedeyes/haiku_media_addons
|
4efbbbf5d35949748f4e6fc1b79b7f4e854751d6
|
[
"MIT"
] | null | null | null |
Video/ScreenCapture/ScreenCapture.cpp
|
threedeyes/haiku_media_addons
|
4efbbbf5d35949748f4e6fc1b79b7f4e854751d6
|
[
"MIT"
] | null | null | null |
/*
* Copyright 2021, Gerasim Troeglazov (3dEyes**), 3dEyes@gmail.com.
* All rights reserved.
* Distributed under the terms of the MIT License.
*/
#include "ScreenCapture.h"
ScreenCapture::ScreenCapture(BScreen *screen)
: BDirectWindow(BRect(-2, -2, -1, -1), "FakeDirectWindow",
B_NO_BORDER_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL,
B_AVOID_FRONT | B_AVOID_FOCUS | B_NO_WORKSPACE_ACTIVATION,
B_ALL_WORKSPACES)
,fDirectAvailable(false)
,fScreen(screen)
{
}
void
ScreenCapture::DirectConnected(direct_buffer_info *info)
{
switch (info->buffer_state & B_DIRECT_MODE_MASK) {
case B_DIRECT_START:
case B_DIRECT_MODIFY:
fDirectInfo = *info;
fDirectAvailable = true;
break;
case B_DIRECT_STOP:
fDirectAvailable = false;
break;
default:
break;
}
}
status_t
ScreenCapture::ReadBitmap(BBitmap *bitmap, bool direct)
{
if (direct && fDirectAvailable) {
memcpy(bitmap->Bits(), fDirectInfo.bits, bitmap->BitsLength());
return B_OK;
}
return fScreen->ReadBitmap(bitmap);
}
| 22.266667
| 67
| 0.736527
|
threedeyes
|
3938480a46fbabc224659c1d76fe309fd9f8e745
| 5,542
|
hpp
|
C++
|
src/sip-0x/Transaction.hpp
|
zanfire/sip-0x
|
de38b3ff782d2a63b69d7f785e2bd9ce7674abd5
|
[
"Apache-2.0"
] | 1
|
2021-06-03T15:56:32.000Z
|
2021-06-03T15:56:32.000Z
|
src/sip-0x/Transaction.hpp
|
zanfire/sip-0x
|
de38b3ff782d2a63b69d7f785e2bd9ce7674abd5
|
[
"Apache-2.0"
] | 1
|
2015-08-05T05:51:49.000Z
|
2015-08-05T05:51:49.000Z
|
src/sip-0x/Transaction.hpp
|
zanfire/sip-0x
|
de38b3ff782d2a63b69d7f785e2bd9ce7674abd5
|
[
"Apache-2.0"
] | null | null | null |
#if !defined(SIP0X_LOGIC_TRANSACTION_HPP__)
#define SIP0X_LOGIC_TRANSACTION_HPP__
//!
//! Copyright 2014-2015 Matteo Valdina
//!
//! 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 <memory>
#include <string>
#include <mutex>
/*
Documentation from RFC 3261
Timer Value Section Meaning
---------------------------------------------------------------------
T1 500ms default Section 17.1.1.1 RTT Estimate
T2 4s Section 17.1.2.2 The maximum retransmit interval for non-INVITE requests and INVITE responses
T4 5s Section 17.1.2.2 Maximum duration a message will remain in the network
Timer A initially T1 Section 17.1.1.2 INVITE request retransmit interval, for UDP only
Timer B 64*T1 Section 17.1.1.2 INVITE transaction timeout timer
Timer C > 3min Section 16.6 proxy INVITE transaction bullet 11 timeout
Timer D > 32s for UDP Section 17.1.1.2 Wait time for response retransmits
0s for TCP/SCTP
Timer E initially T1 Section 17.1.2.2 non-INVITE request retransmit interval, UDP only
Timer F 64*T1 Section 17.1.2.2 non-INVITE transaction timeout timer
Timer G initially T1 Section 17.2.1 INVITE response retransmit interval
Timer H 64*T1 Section 17.2.1 Wait time for ACK receipt
Timer I T4 for UDP Section 17.2.1 Wait time for ACK retransmits
0s for TCP/SCTP
Timer J 64*T1 for UDP Section 17.2.2 Wait time for non-INVITE request retransmits
0s for TCP/SCTP
Timer K T4 for UDP Section 17.1.2.2 Wait time for response retransmits
0s for TCP/SCTP
*/
namespace sip0x
{
class TransportLayer;
class RemotePeer;
namespace utils {
class Logger;
class Connection;
}
namespace protocol {
class SIPMessage;
class SIPRequest;
class SIPResponse;
}
enum TransactionState {
TRANSACTION_STATE_UNKNOWN = 0,
TRANSACTION_STATE_TRYING = 1,
TRANSACTION_STATE_PROCEEDING,
TRANSACTION_STATE_COMPLETED,
TRANSACTION_STATE_TERMINATED,
};
//! A Transaction is a pair of Request and response
class Transaction : public std::enable_shared_from_this<Transaction> {
protected:
std::shared_ptr<sip0x::utils::Logger> _logger;
std::recursive_mutex _mtx;
std::shared_ptr<TransportLayer> _transport = nullptr;
// TODO: Work on ID
public:
std::string id;
// TODO: Revise this comment.
//! Reference to the connection associated to this transaction.
//! \remark This connection is not available for UDP scenario.
std::shared_ptr<RemotePeer> remotepeer;
//! True if the origin of this transaction is from remote.
bool origin_remote = false;
// State machine
TransactionState state = TransactionState::TRANSACTION_STATE_UNKNOWN;
std::shared_ptr<const sip0x::protocol::SIPRequest> request;
std::shared_ptr<const sip0x::protocol::SIPResponse> response;
protected:
//! Time point of first request sent/received. Every computation are get as delta from this time.
long long _T0_ms;
// Timers ([timer name]_[description]_[units])
long long const _T1_rtti_ms = 500;
long long const _T2_maximum_retransmit_interval_secs = 4;
long long const _T4_TTL_secs = 5;
long long _TimerA_secs = 0;
long long _TimerB_secs = 0;
long long _TimerC_secs = 0;
long long _TimerD_secs = 0;
long long _TimerE_secs = 0;
long long _TimerF_secs = 0;
long long _TimerG_secs = 0;
long long _TimerH_secs = 0;
long long _TimerI_secs = 0;
long long _TimerJ_secs = 0;
long long _TimerK_secs = 0;
public:
Transaction(std::shared_ptr<TransportLayer>& transport);
virtual ~Transaction(void);
//! Update Transaction state machine.
//! \arg message is the message dispatched to transaction.
//! \arg forward mean that this message must be forwarded to the transport layer.
//! \returns true if message was accepted by state machine otherwise false.
bool on_message(const std::shared_ptr<const sip0x::protocol::SIPMessage>& message, bool forward);
//! Evaluate all timers for this transaction.
void process_timers(void);
//! \returns true if this message was sent/recv on UDP.
bool is_udp(void) const;
//! \returns true if it is a INVITE transaction.
bool is_INVITE(void) const;
std::string to_string(void) const;
//! Statics
static char const* to_string(TransactionState state);
protected:
//! Resend
void resend(void);
//! Terminate this transaction.
void terminate(void);
//! Changes the current state.
//! \returns true if the state was accepted.
bool change_state(TransactionState new_state);
//! Update timers value in base of T0 and kind of transaction (non-INVITE, INVITE).
void update_timers_value(void);
};
}
#endif // SIP0X_LOGIC_TRANSACTION_HPP__
| 36.946667
| 125
| 0.677373
|
zanfire
|
39391c73eacfe456824b5c6962b28f8cb6579e66
| 991
|
cpp
|
C++
|
liven/viewer.cpp
|
ivme/animated_algebra
|
eee6e7198af7236576c3aa7e16a9f229e101aa7f
|
[
"MIT"
] | null | null | null |
liven/viewer.cpp
|
ivme/animated_algebra
|
eee6e7198af7236576c3aa7e16a9f229e101aa7f
|
[
"MIT"
] | null | null | null |
liven/viewer.cpp
|
ivme/animated_algebra
|
eee6e7198af7236576c3aa7e16a9f229e101aa7f
|
[
"MIT"
] | null | null | null |
#include "viewer.h"
#include "image.h"
#include "animation.h"
#include <iostream>
#include <string> // debug
using namespace liven;
void ascii_viewer::show(const ascii_image &img) {
// debug
// std::cout<< "ascii_viewer::_show(const ascii_image &img)" << std::endl;
// std::cout << "pixel_at(0,0) == " << std::to_string(img.cpixel_at(0,0)) << std::endl;
clear_display();
std::wcout << img.pixels;
std::wcout << std::endl; // advance cursor one past end of image
image_on_display = true;
image_width = img.pixels.cols();
image_height = img.pixels.rows();
}
void erase_line(std::ostream &os) {
os << "\33[2K";
}
void move_cursor_up(std::ostream &os) {
os << "\033[A";
}
void ascii_viewer::clear_display() {
if (image_on_display) {
for (int i = 0; i < image_height; ++i) {
move_cursor_up(std::cout);
erase_line(std::cout);
}
}
// return cursor to first col
std::cout << "\r";
std::cout.flush();
image_on_display = false;
image_width = 0;
image_height = 0;
}
| 22.522727
| 88
| 0.652876
|
ivme
|
393c9353a9bc19783550766d42f87c33fc8ad319
| 4,328
|
cpp
|
C++
|
qubus/src/performance_models/simple_statistical_performance_model.cpp
|
qubusproject/Qubus
|
0feb8d6df00459c5af402545dbe7c82ee3ec4b7c
|
[
"BSL-1.0"
] | null | null | null |
qubus/src/performance_models/simple_statistical_performance_model.cpp
|
qubusproject/Qubus
|
0feb8d6df00459c5af402545dbe7c82ee3ec4b7c
|
[
"BSL-1.0"
] | null | null | null |
qubus/src/performance_models/simple_statistical_performance_model.cpp
|
qubusproject/Qubus
|
0feb8d6df00459c5af402545dbe7c82ee3ec4b7c
|
[
"BSL-1.0"
] | null | null | null |
#include <hpx/config.hpp>
#include <qubus/performance_models/simple_statistical_performance_model.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/count.hpp>
#include <boost/accumulators/statistics/error_of.hpp>
#include <boost/accumulators/statistics/error_of_mean.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/variance.hpp>
#include <hpx/include/local_lcos.hpp>
#include <qubus/util/assert.hpp>
#include <qubus/util/unused.hpp>
#include <map>
#include <mutex>
#include <utility>
#include <vector>
namespace qubus
{
namespace
{
std::vector<hpx::naming::gid_type> generate_key_from_ctx(const execution_context& ctx)
{
std::vector<hpx::naming::gid_type> key;
key.reserve(ctx.args().size());
for (const auto& obj : ctx.args())
{
key.push_back(obj.get_raw_gid());
}
return key;
}
class accumulator
{
public:
using value_type = std::chrono::microseconds::rep;
void sample(std::chrono::microseconds execution_time)
{
acc_(execution_time.count());
}
std::chrono::microseconds mean() const
{
value_type value = boost::accumulators::mean(acc_);
return std::chrono::microseconds(std::move(value));
}
std::chrono::microseconds variance() const
{
value_type value = boost::accumulators::variance(acc_);
return std::chrono::microseconds(std::move(value));
}
std::chrono::microseconds error_of_mean() const
{
value_type value = boost::accumulators::error_of<boost::accumulators::tag::mean>(acc_);
return std::chrono::microseconds(std::move(value));
}
private:
boost::accumulators::accumulator_set<
value_type, boost::accumulators::stats<
boost::accumulators::tag::count, boost::accumulators::tag::mean,
boost::accumulators::tag::variance,
boost::accumulators::tag::error_of<boost::accumulators::tag::mean>>>
acc_;
};
}
class simple_statistical_performance_model_impl
{
public:
void sample_execution_time(const symbol_id& QUBUS_UNUSED(func), const execution_context& ctx,
std::chrono::microseconds execution_time)
{
std::lock_guard<hpx::lcos::local::mutex> guard(accumulators_mutex_);
auto key = generate_key_from_ctx(ctx);
auto search_result = accumulators_.find(key);
if (search_result == accumulators_.end())
{
search_result = accumulators_.emplace(key, accumulator()).first;
}
search_result->second.sample(std::move(execution_time));
}
boost::optional<performance_estimate>
try_estimate_execution_time(const symbol_id& QUBUS_UNUSED(func), const execution_context& ctx) const
{
std::lock_guard<hpx::lcos::local::mutex> guard(accumulators_mutex_);
auto key = generate_key_from_ctx(ctx);
auto search_result = accumulators_.find(key);
if (search_result != accumulators_.end())
{
return performance_estimate{search_result->second.mean(),
search_result->second.error_of_mean()};
}
else
{
return boost::none;
}
}
private:
mutable hpx::lcos::local::mutex accumulators_mutex_;
std::map<std::vector<hpx::naming::gid_type>, accumulator> accumulators_;
};
simple_statistical_performance_model::simple_statistical_performance_model()
: impl_(std::make_unique<simple_statistical_performance_model_impl>())
{
}
simple_statistical_performance_model::~simple_statistical_performance_model() = default;
void simple_statistical_performance_model::sample_execution_time(
const symbol_id& func, const execution_context& ctx, std::chrono::microseconds execution_time)
{
QUBUS_ASSERT(impl_, "Uninitialized object.");
impl_->sample_execution_time(func, ctx, std::move(execution_time));
}
boost::optional<performance_estimate>
simple_statistical_performance_model::try_estimate_execution_time(
const symbol_id& func, const execution_context& ctx) const
{
QUBUS_ASSERT(impl_, "Uninitialized object.");
return impl_->try_estimate_execution_time(func, ctx);
}
}
| 28.662252
| 104
| 0.69085
|
qubusproject
|
393c9a196fb8403979bb61d4625ae836c6448eae
| 2,466
|
cpp
|
C++
|
src/main.cpp
|
sinamoghimi73/Websocket-C-
|
a88dfa356813ec4f79563ad5a150a2abef76e6f9
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
sinamoghimi73/Websocket-C-
|
a88dfa356813ec4f79563ad5a150a2abef76e6f9
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
sinamoghimi73/Websocket-C-
|
a88dfa356813ec4f79563ad5a150a2abef76e6f9
|
[
"MIT"
] | null | null | null |
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/ssl.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/beast/websocket/ssl.hpp>
#include <chrono>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include "root_certificates.hpp"
#include "web_socket_session.hpp"
int main() {
auto host{"stream.binance.com"};
auto port{"9443"};
auto target{
"/stream?streams=btcusdt@bookTicker/btcusdt@markPrice@1s"}; // bitcoin
// full order
// book
// endpoint,
// 100ms
// updates
// The io_context is required for all I/O
net::io_context ioc;
// The SSL context is required, and holds certificates
ssl::context ctx{ssl::context::tlsv12_client};
ctx.set_verify_mode(ssl::verify_none);
// This holds the root certificate used for verification
load_root_certificates(ctx);
// Run the I/O service. The call will return when
// the socket is closed.
ioc.run();
std::string inputStr{"r"};
std::thread t;
std::shared_ptr<WebSocketSession> websocketSession;
while (inputStr != "x") {
// std::cout << "Press 'r' to run. Press 's' to stop. Press 'x' to
// Exit." << std::endl; std::cin >> inputStr; std::cout <<
// websocketSession.use_count() << "\n";
if (inputStr == "r") { // run
if (websocketSession.use_count() == 0) { // should not run twice
t = std::thread([&websocketSession, &ioc, &ctx, host, port, target] {
websocketSession =
std::make_shared<WebSocketSession>(ioc, ctx, host, port, target);
websocketSession->Start(); // within a thread so doesn't block
});
}
std::this_thread::sleep_for(100ms);
} else if (inputStr == "s" or inputStr == "x") { // stop & exit
if (websocketSession.use_count()) { // running
websocketSession->Stop();
t.join();
t.~thread();
websocketSession.reset();
}
}
}
return EXIT_SUCCESS;
}
| 32.88
| 80
| 0.541768
|
sinamoghimi73
|
393cff4cac37901b6db221d6b1acd288ff4d814b
| 833
|
cpp
|
C++
|
src/main.cpp
|
DanielNikkari/Tower-Defense-C-
|
5245afc5ff96d9894c81e3e3fb4761616dceb391
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
DanielNikkari/Tower-Defense-C-
|
5245afc5ff96d9894c81e3e3fb4761616dceb391
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
DanielNikkari/Tower-Defense-C-
|
5245afc5ff96d9894c81e3e3fb4761616dceb391
|
[
"MIT"
] | null | null | null |
// Tower Defense Group 3 main.cpp
/*#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>*/
#include <iostream>
#include <string>
#include <filesystem>
#include "game.hpp"
#include "game.cpp" // Needed for Mac compiler to link
// Window dimentions
//int WINDOW_WIDTH = 1920;
//int WINDOW_HEIGHT = 1080;
int main()
{
std::cout << "Starting the program..." << std::endl;
// File path if file is not in the same location as the code (Change to your own path!)
std::string filepath = "/Users/danielnikkari/Documents/Textures";
// File path if file is in the same location as the code
std::string root_filepath = std::filesystem::current_path(); // Remember to be on /tower-defense-3 not /src to filepath to work
std::cout << root_filepath << std::endl;
// Create game
Game game(root_filepath);
game.run();
return 0;
}
| 26.03125
| 128
| 0.703481
|
DanielNikkari
|
3940b21a41953fa74742e3d1b27e66770ae390ef
| 340
|
cpp
|
C++
|
autovpnui/pch.cpp
|
teaglu/autovpn
|
a3b32b7d8c8589e3f578dc45557babea9f348d5a
|
[
"Apache-2.0"
] | null | null | null |
autovpnui/pch.cpp
|
teaglu/autovpn
|
a3b32b7d8c8589e3f578dc45557babea9f348d5a
|
[
"Apache-2.0"
] | null | null | null |
autovpnui/pch.cpp
|
teaglu/autovpn
|
a3b32b7d8c8589e3f578dc45557babea9f348d5a
|
[
"Apache-2.0"
] | null | null | null |
/******************************************************************************
* This file, along with all other files and components of this project, is *
* subject to the Apache 2.0 license included at the root of the project. *
******************************************************************************/
#include "pch.h"
| 42.5
| 80
| 0.367647
|
teaglu
|
394804dc8b6399719cca9fed5c4cff28626f1199
| 1,915
|
cpp
|
C++
|
Solution/Source/ObjectSystem/MovementComponent.cpp
|
TeeNik/GameEngine
|
9a3893455f20e14f967e5df9b2168fa0f004c101
|
[
"MIT"
] | null | null | null |
Solution/Source/ObjectSystem/MovementComponent.cpp
|
TeeNik/GameEngine
|
9a3893455f20e14f967e5df9b2168fa0f004c101
|
[
"MIT"
] | null | null | null |
Solution/Source/ObjectSystem/MovementComponent.cpp
|
TeeNik/GameEngine
|
9a3893455f20e14f967e5df9b2168fa0f004c101
|
[
"MIT"
] | null | null | null |
#include "ObjectSystem/MovementComponent.hpp"
#include "Math/Math.h"
#include "ObjectSystem/Actor.hpp"
#include "SDL.h"
#include "Engine/Engine.hpp"
#include "Input/InputSystem.hpp"
MovementComponent::MovementComponent(Actor* o) :
Component(o),
angularSpeed(0),
forwardSpeed(0)
{
updateOrder = 10;
o->GetEngine()->GetInput()->SetRelativeMouseMode(true);
}
void MovementComponent::Update(float deltaTime)
{
auto inputState = owner->GetEngine()->GetInput()->GetState();
auto keyboard = inputState.Keyboard;
auto mouse = inputState.Mouse;
float forwardSpeed = 0.0f;
float strafeSpeed = 0.0f;
const float speed = 100;
if (keyboard.GetKeyState(SDL_Scancode::SDL_SCANCODE_W) == ButtonState::Held) {
forwardSpeed += speed;
}
if (keyboard.GetKeyState(SDL_Scancode::SDL_SCANCODE_S) == ButtonState::Held) {
forwardSpeed -= speed;
}
if (keyboard.GetKeyState(SDL_Scancode::SDL_SCANCODE_D) == ButtonState::Held) {
strafeSpeed += speed;
}
if (keyboard.GetKeyState(SDL_Scancode::SDL_SCANCODE_A) == ButtonState::Held) {
strafeSpeed -= speed;
}
auto mousePos = mouse.GetPosition();
int x = mousePos.x;
int y = mousePos.y;
const int maxMouseSpeed = 500;
const float maxAngularSpeed = Math::Pi * 8;
float angularSpeed = 0;
if (x != 0) {
angularSpeed = static_cast<float>(x) / maxMouseSpeed * maxAngularSpeed;
}
if (!Math::NearZero(angularSpeed))
{
Quaternion rot = owner->GetActorRotation();
float angle = angularSpeed * deltaTime;
Quaternion inc(Vector3::UnitZ, angle);
rot = Quaternion::Concatenate(rot, inc);
owner->SetActorRotation(rot);
}
if (!Math::NearZero(forwardSpeed) || !Math::NearZero(strafeSpeed))
{
Vector3 pos = owner->GetActorPosition();
pos += owner->GetForward() * forwardSpeed * deltaTime;
pos += owner->GetRight() * strafeSpeed * deltaTime;
owner->SetActorPosition(pos);
}
}
| 27.753623
| 80
| 0.691906
|
TeeNik
|
3949bfa17b5358323f226439a7dcbe679f450c3a
| 1,728
|
hpp
|
C++
|
modules/display/src/display_stream.hpp
|
Hairuijy/CNStream
|
8f6ea30cf25acc45d042686acbbfb7c476ff32c5
|
[
"Apache-2.0"
] | 1
|
2019-11-05T01:13:42.000Z
|
2019-11-05T01:13:42.000Z
|
modules/display/src/display_stream.hpp
|
Hairuijy/CNStream
|
8f6ea30cf25acc45d042686acbbfb7c476ff32c5
|
[
"Apache-2.0"
] | null | null | null |
modules/display/src/display_stream.hpp
|
Hairuijy/CNStream
|
8f6ea30cf25acc45d042686acbbfb7c476ff32c5
|
[
"Apache-2.0"
] | null | null | null |
/*************************************************************************
* Copyright (C) [2019] by Cambricon, 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
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*************************************************************************/
#ifndef DISPLAY_STREAM_HPP_
#define DISPLAY_STREAM_HPP_
#ifdef HAVE_OPENCV
#include <opencv2/opencv.hpp>
#else
#error OpenCV required
#endif
#include <chrono>
#include <thread>
namespace cnstream {
class DisplayStream {
public:
bool Open(int window_w, int window_h, int cols, int rows, float display_rate);
void Close();
bool Update(cv::Mat image, int channel_id);
private:
void RefreshLoop();
cv::Mat canvas_;
std::thread *refresh_thread_;
int window_h_;
int window_w_;
int cols_;
int rows_;
int unit_w_;
int unit_h_;
float refresh_rate_;
bool running_ = false;
};
} // namespace cnstream
#endif // DISPLAY_STREAM_HPP_
| 30.315789
| 80
| 0.675926
|
Hairuijy
|
3949d3cb7b69d414e261447a7b2cbf7a8f33fb95
| 2,869
|
cpp
|
C++
|
.LHP/.Lop11/.HSG/.T.Minh/Week 5/BSEQ_S/BSEQ_S/BSEQ_S.cpp
|
sxweetlollipop2912/MaCode
|
661d77a2096e4d772fda2b6a7f80c84113b2cde9
|
[
"MIT"
] | null | null | null |
.LHP/.Lop11/.HSG/.T.Minh/Week 5/BSEQ_S/BSEQ_S/BSEQ_S.cpp
|
sxweetlollipop2912/MaCode
|
661d77a2096e4d772fda2b6a7f80c84113b2cde9
|
[
"MIT"
] | null | null | null |
.LHP/.Lop11/.HSG/.T.Minh/Week 5/BSEQ_S/BSEQ_S/BSEQ_S.cpp
|
sxweetlollipop2912/MaCode
|
661d77a2096e4d772fda2b6a7f80c84113b2cde9
|
[
"MIT"
] | null | null | null |
#define LOCAL 1
//#define BUG
#include <iostream>
#include <iomanip>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <list>
#include <bitset>
#include <string>
#include <cstring>
#include <cmath>
#include <ctime>
using namespace std;
#define sz(x) (int)((x).size())
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define fi first
#define se second
#define pb push_back
#define ins insert
#define rsz resize
#define lb lower_bound
#define ub upper_bound
#define fore(i, a, b) for (int i = (a), _b = (b); i < _b; ++i)
#define fort(i, a, b) for (int i = (a), _b = (b); i <= _b; ++i)
#define ford(i, a, b) for (int i = (a), _b = (b); i >= _b; --i)
#ifdef BUG
#define bug(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1) {
cerr << name << ": " << arg1 << '\n';
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&& ... args) {
const char* comma = strchr(names + 1, ',');
cerr.write(names, comma - names) << " : " << arg1 << " /";
__f(comma + 1, args...);
}
#endif
template <class T> bool mini(T& a, T b) { return a > b ? (a = b, 1) : 0; }
template <class T> bool maxi(T& a, T b) { return a < b ? (a = b, 1) : 0; }
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int, int> ii;
typedef pair<int, ii> iii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ii> vii;
typedef vector<iii> viii;
typedef vector<vii> vvii;
const int INF = (int)1e9 + 7;
const int N = 20;
int n, vis1[N], vis2[N << 1], vis3[N << 1], b[N];
vvi a;
ll ans, sf[N];
void backtrack(int pos) {
fore(i, 0, sz(a[pos])) {
b[pos] = a[pos][i];
if (vis1[b[pos]] || (vis2[pos - b[pos] + N] || vis3[pos + b[pos]])
|| (pos > 0 && abs(b[pos] - b[pos - 1]) == 2) || (pos > 1 && abs(b[pos] - b[pos - 2]) == 1)) {
ans += sf[pos + 1];
}
else if (pos < n) {
++vis1[b[pos]];
++vis2[pos - b[pos] + N];
++vis3[pos + b[pos]];
backtrack(pos + 1);
--vis1[b[pos]];
--vis2[pos - b[pos] + N];
--vis3[pos + b[pos]];
}
}
}
int main() {
#ifdef LOCAL
//freopen("bseq.inp", "r", stdin);
//freopen("bseq.out", "w", stdout);
#endif // LOCAL
ios_base::sync_with_stdio(0); cin.tie(0);
while ((cin >> n) && n) {
ans = 0;
memset(b, 0, sizeof b);
memset(sf, 0, sizeof sf);
a = vvi(n);
string in;
fore(i, 0, n) {
cin >> in;
if (in[0] == '?') fore(j, 0, n) a[i].pb(j);
else fore(j, 0, sz(in)) a[i].pb((int)(in[j] - 'A'));
}
// fore(i, 0, n) fore(j, 0, sz(a[i])) cout << a[i][j] << " \n"[j == sz(a[i]) - 1];
sf[n] = 1;
ford(i, n - 1, 0) sf[i] = sf[i + 1] * sz(a[i]);
backtrack(0);
cout << ans << '\n';
}
return 0;
}
| 24.521368
| 97
| 0.560125
|
sxweetlollipop2912
|
3949efc7b28f4d4b18241ea99a67fcaf8168a85d
| 2,310
|
cpp
|
C++
|
Codeforces/1263F/dp_tree.cpp
|
codgician/ACM
|
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
|
[
"MIT"
] | 2
|
2018-02-14T01:59:31.000Z
|
2018-03-28T03:30:45.000Z
|
Codeforces/1263F/dp_tree.cpp
|
codgician/ACM
|
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
|
[
"MIT"
] | null | null | null |
Codeforces/1263F/dp_tree.cpp
|
codgician/ACM
|
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
|
[
"MIT"
] | 2
|
2017-12-30T02:46:35.000Z
|
2018-03-28T03:30:49.000Z
|
#include <bits/stdc++.h>
using namespace std;
#define SIZE 2010
class Edge {
public:
int to, next;
};
Edge edges[SIZE << 1];
int head[SIZE], edgesPt;
int conn[SIZE], siz[SIZE], dp[SIZE];
pair<int, int> rng[SIZE];
class Subt {
public:
int edgeNum, leftPt, rightPt;
bool operator < (const Subt & snd) const {
return rightPt < snd.rightPt;
}
};
vector<Subt> vec;
void addEdge(int from, int to) {
edges[edgesPt] = {to, head[from]};
head[from] = edgesPt++;
}
void dfs(int cntPt, int fatherPt) {
siz[cntPt] = 1; rng[cntPt] = make_pair(INT_MAX, INT_MIN);
if (conn[cntPt] != -1)
rng[cntPt] = make_pair(conn[cntPt], conn[cntPt]);
const auto upd = [](const pair<int, int> & fst, const pair<int, int> & snd) {
return make_pair(min(fst.first, snd.first), max(fst.second, snd.second));
};
for (int i = head[cntPt]; i != -1; i = edges[i].next) {
int nextPt = edges[i].to;
if (nextPt == fatherPt)
continue;
dfs(nextPt, cntPt);
siz[cntPt] += siz[nextPt];
rng[cntPt] = upd(rng[cntPt], rng[nextPt]);
}
vec.push_back(Subt{siz[cntPt] - (fatherPt == -1), rng[cntPt].first + 1, rng[cntPt].second + 1});
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int deviceNum, vertexNum; cin >> deviceNum >> vertexNum;
fill(head + 0, head + vertexNum, -1);
fill(conn + 0, conn + vertexNum, -1);
edgesPt = 0; vec.clear();
for (int i = 1; i < vertexNum; i++) {
int to; cin >> to; to--;
addEdge(i, to); addEdge(to, i);
}
for (int i = 0; i < deviceNum; i++) {
int pt; cin >> pt; pt--;
conn[pt] = i;
}
dfs(0, -1);
cin >> vertexNum;
fill(head + 0, head + vertexNum, -1);
fill(conn + 0, conn + vertexNum, -1);
edgesPt = 0;
for (int i = 1; i < vertexNum; i++) {
int to; cin >> to; to--;
addEdge(i, to); addEdge(to, i);
}
for (int i = 0; i < deviceNum; i++) {
int pt; cin >> pt; pt--;
conn[pt] = i;
}
dfs(0, -1);
sort(vec.begin(), vec.end());
fill(dp + 0, dp + deviceNum + 1, 0);
for (const auto & s : vec)
dp[s.rightPt] = max(dp[s.rightPt], dp[s.leftPt - 1] + s.edgeNum);
cout << dp[deviceNum] << '\n';
return 0;
}
| 25.384615
| 100
| 0.534632
|
codgician
|
394ff8d1e6beb1261d25f29927946327594b4aee
| 13,121
|
cpp
|
C++
|
src/main/cpp/kmeans_gen.cpp
|
ehsantn/data-analytics-benchmarks
|
db6ecf8c3e1d899a146ced47a8cc3e92b52fca69
|
[
"BSD-2-Clause"
] | 1
|
2017-06-19T17:09:06.000Z
|
2017-06-19T17:09:06.000Z
|
src/main/cpp/kmeans_gen.cpp
|
ehsantn/data-analytics-benchmarks
|
db6ecf8c3e1d899a146ced47a8cc3e92b52fca69
|
[
"BSD-2-Clause"
] | null | null | null |
src/main/cpp/kmeans_gen.cpp
|
ehsantn/data-analytics-benchmarks
|
db6ecf8c3e1d899a146ced47a8cc3e92b52fca69
|
[
"BSD-2-Clause"
] | null | null | null |
#include <random>
#include <mpi.h>
#include <stdint.h>
#include <float.h>
#include <limits.h>
#include <complex>
#include <math.h>
#include <stdio.h>
#include <iostream>
#include "/home/etotoni/.julia/v0.5/ParallelAccelerator/src/../deps/include/j2c-array.h"
#include "/home/etotoni/.julia/v0.5/ParallelAccelerator/src/../deps/include/pse-types.h"
#include "/home/etotoni/.julia/v0.5/ParallelAccelerator/src/../deps/include/cgen_intrinsics.h"
#include <sstream>
#include <vector>
#include <string>
#include <ctime>
#include <stdlib.h>
#include "/home/etotoni/.julia/v0.5/HPAT/src/../deps/include/hpat.h"
unsigned main_count = 0;
typedef struct
{
} pppkmeansp271;
typedef struct
{
double val;
int64_t idx;
} ParallelAcceleratorAPILibMTFloat64;
void ppkmeansp271(int64_t numCenter, int64_t iterNum, int64_t N, j2c_array< double > * __restrict ret0)
{
pppkmeansp271 pselfp;
j2c_array< double > centroids;
int64_t ptempp;
j2c_array< double > _pa_rand_gen_arr;
j2c_array< double > pp_pa_rand_gen_arr_17p285;
int64_t SSAValue29;
bool SSAValue14;
int64_t SSAValue15;
int64_t SSAValue27;
bool SSAValue0;
bool SSAValue1;
j2c_array< int64_t > SSAValue3;
j2c_array< double > SSAValue4;
int64_t parfor_index_1_17;
int64_t parfor_index_2_17;
double SSAValue5;
int64_t parfor_index_1_21;
int64_t parfor_index_2_21;
double SSAValue6;
int64_t parfor_index_1_25;
j2c_array< double > SSAValue7;
int64_t parfor_index_1_30;
double SSAValue10;
double parallel_ir_temp__8_parallel_ir_range__37Int64_skip__39Int64_1_1_1;
double parallel_ir_temp__6_parallel_ir_range__43Int64_skip__45Int64_1_1_1;
int64_t parfor_index_1_51;
double SSAValue11;
int32_t SSAValue12;
double SSAValue13;
double parallel_ir_array_temp_SSAValue3_68_1;
double parallel_ir_reduction_output_66;
ParallelAcceleratorAPILibMTFloat64 m;
int64_t SSAValue16;
int64_t ppip300;
ParallelAcceleratorAPILibMTFloat64 parallel_ir_reduction_input_77_1;
ParallelAcceleratorAPILibMTFloat64 pptemp_neutral_valp301;
double SSAValue17;
int64_t SSAValue18;
double SSAValue19;
double SSAValue20;
bool SSAValue21;
double SSAValue22;
double SSAValue23;
double SSAValue24;
bool SSAValue25;
int64_t parfor_index_1_82;
int64_t parfor_index_2_82;
double SSAValue28;
double SSAValue2;
int64_t parallel_ir_array_temp__7_92_1;
int64_t parfor_index_1_91;
bool SSAValue8;
bool parallel_ir_array_temp__21_94_1;
double parallel_ir_array_temp__9_97_1;
double parallel_ir_reduction_output_95;
int64_t parallel_ir_array_temp__7_100_1;
bool SSAValue9;
int64_t SSAValue26;
int64_t parallel_ir_array_temp_SSAValue6_109_1;
int64_t parallel_ir_reduction_output_107;
j2c_array< double > HPAT__99_82;
j2c_array< int64_t > HPAT__105_82;
j2c_array< double > HPAT_SSAValue28_82;
j2c_array< double > HPAT_SSAValue2_82;
int32_t __hpat_num_pes;
int32_t __hpat_node_id;
int64_t __hpat_dist_arr_start_94;
int64_t __hpat_dist_arr_div_94;
int64_t __hpat_dist_arr_count_94;
int64_t __hpat_loop_start_17;
int64_t __hpat_loop_end_17;
int64_t __hpat_loop_div_17;
int64_t __hpat_bcast_size_107;
int64_t __hpat_loop_start_25;
int64_t __hpat_loop_end_25;
int64_t __hpat_loop_div_25;
j2c_array< double > __hpat_reduce_95;
j2c_array< int64_t > __hpat_reduce_96;
std::random_device cgen_rand_device;
std::uniform_real_distribution<double> cgen_distribution(0.0,1.0);
std::normal_distribution<double> cgen_n_distribution(0.0,1.0);
std::default_random_engine cgen_rand_generator(cgen_rand_device());
;;
MPI_Comm_size(MPI_COMM_WORLD,&__hpat_num_pes);;
MPI_Comm_rank(MPI_COMM_WORLD,&__hpat_node_id);;
SSAValue14 = (1) <= (iterNum);
SSAValue15 = (1) - (1);
SSAValue29 = (SSAValue14) ? (iterNum) : (SSAValue15);
SSAValue27 = (SSAValue29) + (1);
__hpat_loop_div_17 = (N) / (__hpat_num_pes);
__hpat_loop_start_17 = ((__hpat_node_id) * (__hpat_loop_div_17)) + (1);
__hpat_loop_end_17 = ((__hpat_node_id==__hpat_num_pes-1) ? N : (__hpat_node_id+1)*__hpat_loop_div_17);
__hpat_dist_arr_div_94 = (N) / (__hpat_num_pes);
__hpat_dist_arr_start_94 = (__hpat_node_id) * (__hpat_dist_arr_div_94);
__hpat_dist_arr_count_94 = ((__hpat_node_id==__hpat_num_pes-1) ? N-__hpat_node_id*__hpat_dist_arr_div_94 : __hpat_dist_arr_div_94);
_pa_rand_gen_arr = j2c_array<double>::new_j2c_array_2d(NULL, 10, __hpat_dist_arr_count_94);
#pragma simd
for ( parfor_index_2_17 = __hpat_loop_start_17; parfor_index_2_17 <= (int64_t)__hpat_loop_end_17; parfor_index_2_17 += 1)
{
for ( parfor_index_1_17 = 1; parfor_index_1_17 <= (int64_t)10; parfor_index_1_17 += 1)
{
;
SSAValue5 = cgen_distribution(cgen_rand_generator);
;
_pa_rand_gen_arr.ARRAYELEM(parfor_index_1_17,((parfor_index_2_17) - (__hpat_loop_start_17)) + (1)) = SSAValue5;
}
}
;
pp_pa_rand_gen_arr_17p285 = j2c_array<double>::new_j2c_array_2d(NULL, 10, numCenter);
if ((__hpat_node_id == 0))
{
;
for ( parfor_index_2_21 = 1; parfor_index_2_21 <= (int64_t)numCenter; parfor_index_2_21 += 1)
{
for ( parfor_index_1_21 = 1; parfor_index_1_21 <= (int64_t)10; parfor_index_1_21 += 1)
{
;
SSAValue6 = cgen_distribution(cgen_rand_generator);
;
pp_pa_rand_gen_arr_17p285.ARRAYELEM(parfor_index_1_21,parfor_index_2_21) = SSAValue6;
}
}
;
}
;
__hpat_bcast_size_107 = (10) * (numCenter);
MPI_Bcast(pp_pa_rand_gen_arr_17p285.data, __hpat_bcast_size_107, MPI_DOUBLE, 0, MPI_COMM_WORLD);;
centroids = pp_pa_rand_gen_arr_17p285;
0; double __hpat_t1 = MPI_Wtime();
ptempp = 1;
while (1)
{
;
SSAValue0 = (ptempp == SSAValue27);
SSAValue1 = !(SSAValue0);
if (!(SSAValue1)) break;
ptempp = (ptempp) + (1);
SSAValue4 = j2c_array<double>::new_j2c_array_2d(NULL, 10, numCenter);
__hpat_loop_div_25 = (N) / (__hpat_num_pes);
__hpat_loop_start_25 = ((__hpat_node_id) * (__hpat_loop_div_25)) + (1);
__hpat_loop_end_25 = ((__hpat_node_id==__hpat_num_pes-1) ? N : (__hpat_node_id+1)*__hpat_loop_div_25);
HPAT__99_82 = j2c_array<double>::new_j2c_array_2d(NULL, 10, numCenter);
HPAT__105_82 = j2c_array<int64_t>::new_j2c_array_2d(NULL, 10, numCenter);
HPAT_SSAValue28_82 = j2c_array<double>::new_j2c_array_2d(NULL, 10, numCenter);
HPAT_SSAValue2_82 = j2c_array<double>::new_j2c_array_2d(NULL, 10, numCenter);
for(int64_t parfor_index_2_82 = 1; parfor_index_2_82 <= numCenter; parfor_index_2_82 += 1)
{
;
for(int64_t parfor_index_1_82 = 1; parfor_index_1_82 <= 10; parfor_index_1_82 += 1)
{
;
HPAT__99_82.ARRAYELEM(parfor_index_1_82, parfor_index_2_82) = 0.0;
HPAT__105_82.ARRAYELEM(parfor_index_1_82, parfor_index_2_82) = 0;
}
;
}
;
#pragma simd
for ( parfor_index_1_25 = __hpat_loop_start_25; parfor_index_1_25 <= (int64_t)__hpat_loop_end_25; parfor_index_1_25 += 1)
{
;
m = ParallelAcceleratorAPILibMTFloat64{DBL_MAX, 1};
for ( parfor_index_1_30 = 1; parfor_index_1_30 <= (int64_t)numCenter; parfor_index_1_30 += 1)
{
;
parallel_ir_reduction_output_66 = 0.0;
for ( parfor_index_1_51 = 1; parfor_index_1_51 <= (int64_t)10; parfor_index_1_51 += 1)
{
;
parallel_ir_temp__8_parallel_ir_range__37Int64_skip__39Int64_1_1_1 = _pa_rand_gen_arr.ARRAYELEM(parfor_index_1_51,((parfor_index_1_25) - (__hpat_loop_start_25)) + (1));
parallel_ir_temp__6_parallel_ir_range__43Int64_skip__45Int64_1_1_1 = centroids.ARRAYELEM(parfor_index_1_51,parfor_index_1_30);
SSAValue11 = (parallel_ir_temp__8_parallel_ir_range__37Int64_skip__39Int64_1_1_1) - (parallel_ir_temp__6_parallel_ir_range__43Int64_skip__45Int64_1_1_1);
SSAValue12 = (int32_t)(2);
SSAValue13 = pow(SSAValue11, SSAValue12);
parallel_ir_reduction_output_66 = (parallel_ir_reduction_output_66+SSAValue13);
}
;
SSAValue10 = sqrt(parallel_ir_reduction_output_66);;
SSAValue23 = SSAValue10;
SSAValue24 = m.val;
SSAValue25 = (SSAValue23) < (SSAValue24);
if (SSAValue25)
{
;
SSAValue22 = SSAValue10;
m.val = SSAValue22;
m.idx = parfor_index_1_30;
}
;
}
;
SSAValue16 = m.idx;
for ( parfor_index_2_82 = 1; parfor_index_2_82 <= (int64_t)numCenter; parfor_index_2_82 += 1)
{
for ( parfor_index_1_82 = 1; parfor_index_1_82 <= (int64_t)10; parfor_index_1_82 += 1)
{
;
parallel_ir_array_temp__7_92_1 = SSAValue16;
SSAValue8 = (parallel_ir_array_temp__7_92_1 == parfor_index_2_82);
parallel_ir_array_temp__21_94_1 = SSAValue8;
if (parallel_ir_array_temp__21_94_1)
{
;
parallel_ir_array_temp__9_97_1 = _pa_rand_gen_arr.ARRAYELEM(parfor_index_1_82,((parfor_index_1_25) - (__hpat_loop_start_25)) + (1));
HPAT__99_82.ARRAYELEM(parfor_index_1_82, parfor_index_2_82) = (HPAT__99_82.ARRAYELEM(parfor_index_1_82,parfor_index_2_82)+parallel_ir_array_temp__9_97_1);
}
;
parallel_ir_array_temp__7_100_1 = SSAValue16;
SSAValue9 = (parallel_ir_array_temp__7_100_1 == parfor_index_2_82);
SSAValue26 = (SSAValue9) ? (1) : (0);
HPAT__105_82.ARRAYELEM(parfor_index_1_82, parfor_index_2_82) = (HPAT__105_82.ARRAYELEM(parfor_index_1_82,parfor_index_2_82)+SSAValue26);
}
}
;
}
;
__hpat_reduce_95 = j2c_array<double>::new_j2c_array_2d(NULL, 10, numCenter);
MPI_Allreduce(HPAT__99_82.data, __hpat_reduce_95.data, (10) * (numCenter), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);;
HPAT__99_82 = __hpat_reduce_95;
__hpat_reduce_96 = j2c_array<int64_t>::new_j2c_array_2d(NULL, 10, numCenter);
MPI_Allreduce(HPAT__105_82.data, __hpat_reduce_96.data, (10) * (numCenter), MPI_INT64_T, MPI_SUM, MPI_COMM_WORLD);;
HPAT__105_82 = __hpat_reduce_96;
for(int64_t parfor_index_2_82 = 1; parfor_index_2_82 <= numCenter; parfor_index_2_82 += 1)
{
;
for(int64_t parfor_index_1_82 = 1; parfor_index_1_82 <= 10; parfor_index_1_82 += 1)
{
;
HPAT_SSAValue28_82.ARRAYELEM(parfor_index_1_82, parfor_index_2_82) = (double)HPAT__105_82.ARRAYELEM(parfor_index_1_82,parfor_index_2_82);
HPAT_SSAValue2_82.ARRAYELEM(parfor_index_1_82, parfor_index_2_82) = (HPAT__99_82.ARRAYELEM(parfor_index_1_82,parfor_index_2_82)) / (HPAT_SSAValue28_82.ARRAYELEM(parfor_index_1_82,parfor_index_2_82));
SSAValue4.ARRAYELEM(parfor_index_1_82,parfor_index_2_82) = HPAT_SSAValue2_82.ARRAYELEM(parfor_index_1_82,parfor_index_2_82);
}
;
}
;
centroids = SSAValue4;
}
;
0; if(__hpat_node_id==0) printf("exec time %lf\n", MPI_Wtime()-__hpat_t1);;
*ret0 = centroids;
return;
}
extern "C" void _ppkmeansp271_(int run_where, int64_t numCenter, int64_t iterNum, int64_t N , j2c_array< double > ** __restrict ret0 , bool genMain = true)
{
if (genMain)
{
++main_count;
std::stringstream newMain;
std::stringstream newMainData;
std::stringstream newMainSh;
std::stringstream newMainExe;
newMain << "main" << main_count << ".cc";
newMainData << "main" << main_count << ".data";
newMainSh << "main" << main_count << ".sh";
newMainExe << "main" << main_count;
std::cout << "Main will be generated in file " << newMain.str() << std::endl;
std::cout << "Data for main will be in file " << newMainData.str() << std::endl;
std::cout << "Script to compile is in " << newMainSh.str() << std::endl;
std::ofstream mainFileData(newMainData.str(), std::ios::out | std::ios::binary);
mainFileData << run_where << std::endl;
mainFileData << numCenter << std::endl;
mainFileData << iterNum << std::endl;
mainFileData << N << std::endl;
mainFileData.close();
std::ofstream mainFile(newMain.str());
mainFile << "#include \"" << __FILE__ << "\"" << std::endl;
mainFile << "int main(int argc, char *argv[]) {" << std::endl;
mainFile << " MPI_Init(&argc, &argv);" << std::endl;
mainFile << " std::ifstream mainFileData(\"" << newMainData.str() << "\", std::ios::in | std::ios::binary);" << std::endl;
mainFile << " int runwhere;" << std::endl;
mainFile << " mainFileData >> runwhere;" << std::endl;
mainFile << " j2c_array< double > * ret0;" << std::endl;
mainFile << " int64_t numCenter;" << std::endl;
mainFile << " mainFileData >> numCenter;" << std::endl;
mainFile << " int64_t iterNum;" << std::endl;
mainFile << " mainFileData >> iterNum;" << std::endl;
mainFile << " int64_t N;" << std::endl;
mainFile << " mainFileData >> N;" << std::endl;
mainFile << " _ppkmeansp271_(runwhere, numCenter, iterNum, N, &ret0, false);" << std::endl;
mainFile << " MPI_Finalize();" << std::endl;
mainFile << " return 0;" << std::endl;
mainFile << "}" << std::endl;
mainFile.close();
std::ofstream mainFileSh(newMainSh.str());
mainFileSh << "#!/bin/sh" << std::endl;
mainFileSh << "mpiicpc -O3 -std=c++11 -I/usr/local/hdf5/include -g -fpic -o " << newMainExe.str() << " " << newMain.str() << " -lm " << std::endl;
mainFileSh.close();
}
*ret0 = new j2c_array< double > ();
ppkmeansp271(numCenter, iterNum, N, *ret0);
}
extern "C"
void *j2c_array_new(int key, void*data, unsigned ndim, int64_t *dims)
{
void *a = NULL;
switch(key)
{
case 1:
a = new j2c_array< double > ((double*)data, ndim, dims);
break;
default:
fprintf(stderr, "j2c_array_new called with invalid key %d", key);
assert(false);
break;
}
return a;
}
| 38.031884
| 203
| 0.733633
|
ehsantn
|
3950b640ac4a20edbebea25deffc7a566ce0db1e
| 1,433
|
hpp
|
C++
|
lib/cmrBase/Inc/cmrException.hpp
|
chiefmate1120/CMRobot_SW
|
79eed3e7b1538b95e3a50b9ff300edc9501942f3
|
[
"MIT"
] | 1
|
2021-12-15T14:54:14.000Z
|
2021-12-15T14:54:14.000Z
|
lib/cmrBase/Inc/cmrException.hpp
|
chiefmate1120/CMRobot_SW
|
79eed3e7b1538b95e3a50b9ff300edc9501942f3
|
[
"MIT"
] | 1
|
2021-12-15T14:55:37.000Z
|
2021-12-15T14:55:37.000Z
|
lib/cmrBase/Inc/cmrException.hpp
|
chiefmate1120/CMRobot_SW
|
79eed3e7b1538b95e3a50b9ff300edc9501942f3
|
[
"MIT"
] | 1
|
2021-07-25T12:32:32.000Z
|
2021-07-25T12:32:32.000Z
|
/*
* cmrException.hpp
*
* Description: This file define the exception handler
*
* Author: Feijian.Ni
* Date: 2020.2.20
*
*/
#ifndef CMREXCEPTION_HPP_
#define CMREXCEPTION_HPP_
#include "baseStdLibs.hpp"
#include <assert.h>
namespace cmr {
//! error type define
enum cmrErrorType {
CMR_SUCCESS = 0,
CMR_FILE_NOT_FOULD,
CMR_SIZE_NOT_COMPATIBLE,
CMR_NULL_VALUE,
CMR_OUT_RANGE,
CMR_ERROR,
CMR_ERROR_NUM = CMR_ERROR - CMR_SUCCESS + 1
};
//! error type string descritption
const std::string cmrErrorString[CMR_ERROR_NUM] = {
"SUCCESS", "FILE NOT FOULD", "SIZE NOT COMPATIBLE",
"NULL VALUE", "OUT RANGE", "ERROR"};
//! exception define
struct cmrException : public std::exception {
// constructor
cmrException(std::string msg) { message = msg; }
// output exception message
const char *what() throw() { return message.c_str(); }
std::string message;
};
//! check cmr return error type
inline void _ERRORTYPE_CHECK(cmrErrorType errorType) {
if (CMR_SUCCESS != errorType) {
throw cmrException(cmrErrorString[errorType]);
}
}
//! throw cmr exception
inline cmrErrorType _ERROR_RETURN(std::string msg) {
throw cmrException(msg);
return CMR_ERROR;
}
//! check if a pointer is null
template <typename T> inline void _CHECK_NULLPOINTER(T ptr, std::string msg) {
assert(std::is_pointer<T>::value);
if (!ptr) {
throw cmrException(msg);
}
};
} // namespace cmr
#endif
| 20.768116
| 78
| 0.700628
|
chiefmate1120
|
39572ac1da76823a1f520845c45fd05d87a79fef
| 24,585
|
hpp
|
C++
|
Source/AllProjects/Drivers/ZWave/ZWaveUSB3/Server/ZWaveUSB3S_ZStick.hpp
|
MarkStega/CQC
|
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
|
[
"MIT"
] | 51
|
2020-12-26T18:17:16.000Z
|
2022-03-15T04:29:35.000Z
|
Source/AllProjects/Drivers/ZWave/ZWaveUSB3/Server/ZWaveUSB3S_ZStick.hpp
|
MarkStega/CQC
|
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
|
[
"MIT"
] | null | null | null |
Source/AllProjects/Drivers/ZWave/ZWaveUSB3/Server/ZWaveUSB3S_ZStick.hpp
|
MarkStega/CQC
|
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
|
[
"MIT"
] | 4
|
2020-12-28T07:24:39.000Z
|
2021-12-29T12:09:37.000Z
|
//
// FILE NAME: ZWaveUSB3S_ZStick.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 07/24/2017
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
//
// Sending Messages:
//
// Send a msg can request a number of steps. Note that all we deal with here are acks
// and trans acks (as well as errors and retries where needed.) The driver thread has to
// deal with any ultimate replies from the target unit. But there still can be
// a number of steps that have to acked and trans acked.
//
// 1. If the target is a frequent listener, we have to ping first to wake it up. So we
// have to wait for the ack and trans ack of that. There is no further response. This
// is done in m_zwomPing.
// 2. If the msg must be sent securely, and we don't already have a nonce for that unit,
// then we have to first send a nonce request and wait for the ack, trans ack and
// the final nonce. This is done in m_zwomNonceReq.
// 3. Finally, or perhaps only if non-secure and and always on device, we now have a
// msg (possibly now encrypted), and we have to send that and wait for the ack
// and possibly the trans ack if the caller set a callback id.
//
// We have a state machine that runs us through these transitions as required. We don't
// need to send a ping for every msg we send. If we are sending a sequence of msgs the
// device will stay awake. So we remember the last node id and time stamp that we got
// a ping transack from. If it's been less than a few seconds, we don't bother doing it.
//
// If we don't have a needed nonce at #2, then we send a request. If the nonce arrives,
// then the current msg is encrypted and we move to stage #3. If the nonce request times
// out after retrying, we just go back to idle state and the current msg basically fails
// and cannot be sent.
//
// Msg Priority
//
// We use queues for in and out msgs. For the outgoing, we use the priority system that
// the queue supports. We define our own priority values, which we map to these queue
// priority levels (which are 0 for lowest to 10 for highest.)
//
// 10. Local. This is really just for the node protocol info query, which we make
// during initialization and after a replication. We need to make sure it gets
// processed fast because if we time out waiting for it back in the driver
// and there's an extra one stuck in the queue, we have no way to know. The msg
// doesn't have an identifying node in it to let us know which node it is sending
// back info for. Since it's only used in those special times, it's not going to
// interfere with nonces or security messages.
// 9. Nonces. These need to be dealt with as quickly as possible.
// 8. Security. Non-nonce security oriented msgs, mostly just done during replication.
// 7. SpecialCmd. These are low level, non-CC msgs, housekeeping stuff, mostly done
// during replication and startup. They are synchronous because they have to get
// done before the next step and we want to expedite things during these special
// operations.
// 6. Wakeup. We have gotten a wakeup from a non-listener, and we have queued up msgs to
// send to him. He will only stay awake so long so we need to prioritize these msgs.
// The driver will send these synchronously, at least up to a certain number of them.
// The other unit should stay awake while we are talking to it.
// 5. Reply. If another node is waiting for us to respond to something, we need to
// get that back quickly, but only after taking care of security stuff. As a controller
// we don't get many of these, but they happen, particularly during the replication
// process.
// 3. Command. A normal priority msg for outgoing commands. These get priority over
// queries since they are user invoked. It is assumed these will request a transmission
// ack from the target, since that is often the only way to know it worked. There may
// be no actual response from the target unit. The caller will wait synchronously for
// the trans ack.
// 2. Query. A normal priority msg for queries, i.e. getting info from a unit, which will
// be waited on synchronously. Since a reply is ultimately expected, no trans ack
// is generally used here, just the ack that it has been queued to send. This may
// be done async or sync, see below.
// 0. Async. Msgs that are queued up on us and the caller is just going to asynchronously
// wait for a reply to come back. This is typically done by units when they are getting
// their initial values, or perhaps if they need to do some slow periodic ping.
//
// We define our own priority value for the outside world to use. They set it on the out
// msgs. We convert that to the correct queue priority when we we get the msgs to queue
// up.
//
// Async Msg Sending
//
// Note that #0 and #2 above indicate that some messages are just queued up and no one
// is watching for the acks. The Z-Stick will handle those as usual. Eventually, it is
// expected in a working system, that the unit will respond and the incoming msgs will
// get routed to the unit object, which will update his state based on that response.
// Or, it will see that the response is not forthcoming after a generous wait and try
// it again.
//
// The timeout should be pretty long, because various other msgs may need to be sent
// first and these could involve nonce exchanges and maybe a unit croaks and isn't
// responding. So 20 to 30 seconds or more is a reasonable time scale for waiting
// for such low priority responses.
//
// Sync Msg Sending
//
// Waiting for msgs synchronously is more difficult. There may be other activity in the
// queue. So the driver can't just send and wait a fixed time. It will be waiting for an
// ultimate response from the unit, but it needs first to know when the msg actually got
// to the top of the queue and was sent and acked (and trans acked if appropriate.) It
// needs to know if the trans ack failed and so the reply will enver come back.
//
// There is a callback id at the Z-Wave level that comes back in the trans ack. But that
// can change if the msg needs to be retried in some cases, and there is nothing in the
// initial, low level ack. So the driver needs some way to wait on those things to happen
// and get a status back. If successful, then it can start waiting for the unit to
// respond if that is needed (not always if it's a synchronous command (and most commands
// will be.)
//
// So, we assign an 'ack id' of our own to each outgoing msg. And we provide a method
// for the driver to block until the last ack (of step #3 in the first list above) is
// done or, if any of the steps fail, after retries. He may still give up before we get
// there, but that's fine. It gives him a means to wait for his msg to be sent and to
// know that it worked or not. If it did, and there's a subsequent response from the unit
// expected, he can then wait for that with a known timeout since at that point he knows
// that his msg is in play.
//
// Locking
//
// Other than the wee bit of stuff related to the ack id discussed above and the queuing
// and dequeing of msgs by the driver, there's almost no connection between our internal
// processing thread and the driver thread.
//
// So synchronization issues are minimal. We need to sync the driver thread getting
// set up to wait for his msg to be acked, and our thread setting up the return status
// and and waking him up. So we have mutex for our bit of locking, and an event for the
// driver thread to block on until we store a status for him.
//
// We don't use that mutex for the in/out msg queues. They are also points of contact
// between the driver thread and our thread; but, these we mark thread safe and let them
// handle their own affairs because they are doing more than simple coordination. They
// are allowing for blocking while waiting for input, waiting for space in the queue, and
// those sorts of things.
//
// CAN Replies
//
// Z-Wave is sort of bad about being able to do more than one thing at a time. If we
// queue up an out msg on the stick, but another msg comes in before ours is sent, we
// get a CANcel msg. We have to read and ack the new msg then we can try to resend ours.
// This could happen some number of times in a row.
//
// But we are currently in a state where we can't just read and process the msg because
// that might try to do something that would interfere. And we can't just ack it and leave
// it in the stick's queue because we'd end up acking it again later. And we can't just
// stick them into the input queue, because that's stuff intended for the driver thread,
// and not all msgs are for him to see.
//
// So we have a separate CAN queue of in msgs. If we get cancelled we will read the msg,
// push it into that CAN queue then ack it. We can't just stick it in the input queue,
// since that's only for msgs that are to be seen by the driver. It may be one that we
// process internally. When it's next time to check for incoming msgs, we first check the
// can queue. If anything there we process it internally or put it in the input queue.
// If not, we read from the stick. Though it's unlikely we would ever need storage for
// more than one msg, we use a queue anyway to just be safe.
//
// Z-Stick Errors
//
// There's something strange with the Z-Stick for some users. It will after some days
// start giving write errors and never recover. So we have to try to cycle the port if
// that happens. We won't report being offline at first. We'll recycle and try it again.
// If that fails, then we'll go offline.
//
// CAVEATS/GOTCHAS:
//
// 1) WE DO NOT have any access to Z-Wave units or to the predefined device info stuff
// provided by the shared facility class. We deal with msg I/O and that's it.
//
// If we started accessing that stuff, the configuration info would then require
// sync that it doesn't currently need because it's only accessed by the driver
// (or its replication) thread.
//
// So quite a bit of info is placed into outgoing msgs, to let us know how to deal
// with them. Incoming msgs aren't an issue, the driver thread will pass them onto
// the correct handler, usually a unit.
//
// LOG:
//
#pragma once
#pragma CIDLIB_PACK(CIDLIBPACK)
class TZWaveUSB3SDriver;
// ---------------------------------------------------------------------------
// CLASS: TZStick
// PREFIX: zst
// ---------------------------------------------------------------------------
class TZStick
{
public :
// -------------------------------------------------------------------
// Constructors and destructor
// -------------------------------------------------------------------
TZStick
(
const TString& strMoniker
);
TZStick(const TZStick&) = delete;
~TZStick();
// -------------------------------------------------------------------
// Public operators
// -------------------------------------------------------------------
TZStick& operator=(const TZStick&) = delete;
// -------------------------------------------------------------------
// Public, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TBoolean bIsConnected() const;
tCIDLib::TBoolean bOpenCtrl();
tCIDLib::TBoolean bWaitTrans
(
const tCIDLib::TCard4 c4WaitForId
, const tCIDLib::TCard4 c4WaitMSs
);
tCIDLib::TCard4 c4CANQUsedPercent() const;
tCIDLib::TCard4 c4OutQUsedPercent() const;
tCIDLib::TVoid Close();
tZWaveUSB3Sh::EMsgTypes eGetMsg
(
TZWInMsg& zwmToFill
, const tCIDLib::TCard4 c4WaitMSs
, const tCIDLib::TBoolean bThrowIfNot
);
tCIDLib::TVoid LogTermTrace();
tCIDLib::TVoid QueueOutMsg
(
const TZWOutMsg& zwomToSend
);
tCIDLib::TVoid SetConfig
(
const TString& strPort
, const TCommPortCfg& cpcfgToSet
);
tCIDLib::TVoid SetManIds
(
const tCIDLib::TCard8 c8ToSet
);
private :
// -------------------------------------------------------------------
// Private types
// -------------------------------------------------------------------
using TCANQ = TQueue<TZWInMsg>;
using TInQ = TQueue<TZWInMsg>;
using TOutQ = TQueue<TZWOutMsg>;
// -------------------------------------------------------------------
// When other nodes ask us for a nonce, we have to store them away so that
// we can access them when the response based on that nonce comes back. We
// need to track when the nonce was generated so that we can time it out. We
// keep up with the node that we sent it to as well, to validate that we get
// it back from that node.
// -------------------------------------------------------------------
class TNonceInfo
{
public :
TNonceInfo() :
m_enctValidTill(0)
, m_mbufNonce(kZWaveUSB3Sh::c4NonceBytes, kZWaveUSB3Sh::c4NonceBytes)
{
}
// For in nonces where we get the bytes
TNonceInfo
(
const tCIDLib::TCard1 c1UnitId
, const TMemBuf& mbufBytes
);
// For out nonces where we generate the bytes
TNonceInfo
(
const tCIDLib::TCard1 c1UnitId
, const tCIDLib::TCard1 c1NonceId
);
~TNonceInfo() {}
tCIDLib::TCard1 m_c1UnitId;
tCIDLib::TEncodedTime m_enctValidTill;
THeapBuf m_mbufNonce;
};
using TNonceList = TVector<TNonceInfo> ;
using TTimeStampList = TFundArray<tCIDLib::TEncodedTime> ;
using TTOArray = TEArray
<
tCIDLib::TEncodedTime
, tZWaveUSB3S::EIOStates
, tZWaveUSB3S::EIOStates::Count
>;
// -------------------------------------------------------------------
// Private, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TBoolean bFindInNonce
(
const tCIDLib::TCard1 c1NonceId
, const tCIDLib::TCard1 c1UnitId
, THeapBuf& mbufToFill
);
tCIDLib::TBoolean bFindOutNonce
(
const tCIDLib::TCard1 c1UnitId
, THeapBuf& mbufToFill
);
tCIDLib::TBoolean bSpecialMsg
(
TZWInMsg& zwimToCheck
);
tCIDLib::TBoolean bTryResend
(
const tCIDLib::TBoolean bNewCBId
, const tCIDLib::TCard4 c4RetryInc
);
tCIDLib::TVoid BuildNonceRequest
(
const tCIDLib::TCard1 c1SrcId
, TZWOutMsg& zwomTar
);
tCIDLib::TCard1 c1CalcSum
(
const TMemBuf& mbufMsg
) const;
tZWaveUSB3Sh::EMsgTypes eGetNext
(
TZWInMsg& zwimToFill
);
tCIDLib::EExitCodes eIOThread
(
TThread& thrThis
, tCIDLib::TVoid* pData
);
tCIDLib::TEncodedTime enctStateTimeout
(
const tZWaveUSB3S::EIOStates eIOState
, const tCIDLib::TBoolean bFreqListener
) const;
tCIDLib::EQPrios eXlatPriority
(
const tZWaveUSB3Sh::EMsgPrios eToXlat
) const;
[[nodiscard]] TNonceInfo* pniMakeNewInNonce
(
const tCIDLib::TCard1 c1UnitId
);
TZWOutMsg* pzwomForState();
tCIDLib::TVoid SendNonceReport
(
const tCIDLib::TCard1 c1RetId
);
tCIDLib::TVoid StartNewOutMsg();
tCIDLib::TVoid StartSecureTrans();
tCIDLib::TVoid StoreOutNonce
(
const tCIDLib::TCard1 c1UnitId
, const THeapBuf& mbufNonce
);
tCIDLib::TVoid TransmitMsg
(
TZWOutMsg& zwomSend
);
tCIDLib::TVoid TriggerMsgDone
(
const tCIDLib::TCard4 c4AckId
, const tCIDLib::TBoolean bSuccess
);
// -------------------------------------------------------------------
// Private data members
//
// m_aenctStateTO
// A list of time outs that we set up for each I/O state.
//
// m_bWaitAckRes
// See m_evWaitAck. This is the result left for the driver thread. It is
// synced by m_mtxSync.
//
// m_c1NextNonceId
// The next nonce id we will assign when we need to generate a nonce.
//
// m_c4CanQUsed
// To avoid having to make the cancel queue thread safe, just so that the
// driver thread can poll the percentage used, we keep this up to date
// any time we modify the queue. He can then read this. It's the current
// elements in the queue.
//
// m_c4Cancels
// m_c4Naks
// m_c4Timeouts
// Some stats we keep about outgoing msgs failures.
//
// m_c4WaitAckId
// See class comments. This is the ack id of the msg that the driver thread
// is waiting to get sent. If zero, the driver is not waiting. It is synced
// with m_mtxSync.
//
// m_c8ManIds
// The main driver passes us the manufacturer ids he got for us during the
// initial scan. We serve it up any time we get a request for that info.
//
// m_colCANQ
// See the file comments above. This lets us deal with an otherwise messy
// situation related to the Z-Stick cancelling our sends due to an incoming
// msg. KEEP THE m_c4CanQUsed values updated with the count of elements in
// this collection any time it is modified.
//
// m_colInQ
// m_colOutQ
// Our input and output queues, managed by the background thread. They are
// thread safe for maximum overlapping access. m_mtxSync is not used on
// these since they already handle their own sync.
//
// m_colInNonces
// These are the nonces that we have issued to other nodes, which they
// use to send messages back to us (those for incoming messages.) So we
// have to keep them around until we get the response or the nonce times
// out.
//
// m_colOutNonces
// These are nonces that we got got pre-sent to us from other nodes, because
// we sent them a secure message with GET_NONCE option so that it would go
// ahead and send one. We have to be able to store those. We may not use it
// before it times out. If we don't already have a nonce for the target,
// then we'll be waiting for it and use it immediately. So this is only for
// storing the pre-sent types.
//
// We use the m_eReqState to know if one has already been requested (by
// sending the non-getting encrypted msg) and the time stamp will be when it
// was requested. Once we get it, it will be set to indicate it's available
// and the time stamp will be how long it's good for.
//
// m_cpcfgSerial
// The main driver gives us the serial port configuration which we use
// to open it.
//
// m_enctNextMsg
// We enforce a minimum inter-message interval, so that we will not send
// two messages to the controller within a minimum time. So, after we
// send a message, it is bumped to now plus that minimum interval.
//
// m_eIOState
// Controls our I/O thread's state machine
//
// m_fcolLastPing
// For each possible unit id, we store the last time we sent out a ping
// (of the internal type used to wake up frequent listeners.) THis lets
// us avoid doing it again too soon.
//
// m_evWaitAck
// See the class comments above. The driver can block and wait until we have
// sent his msg and gotten appropriate acks. Access is controlled by
// m_mtxSync. See m_c4WaitAckId. It's manual mode.
//
// m_mbufOut
// A temp buffer for sending out messages in some of our helpers that
// build and send them in one shot, or that add stuff to provided data
// and then sends the whole thing.
//
// m_mbufNonce
// To get nonces out of the nonce list so that we can remove the nonce
// before we try to en/decrypt, to insure it's gone in case we get some
// sort of error in the process.
//
// m_mtxSync
// See the class comments above. Not much to worry about, but a few things
// we need to sync with the driver thread.
//
// m_pcommZWave
// Our comm port that we use to talk to the Z-Wave controller.
//
// m_strPort
// The port we were told to use to talk to the Z-Stick
//
// m_thrIO
// A background thread, started on eIOThread, which reads and writes the
// comm port. Filling in m_colInQ and draining m_colOutQ.
//
// m_zwomCur
// m_zwomNonceReq
// m_zwomPing
// These are used for processing outgoing msgs. When we pull a new msg out
// of the out queue, it goes to Cur. If that indicates it's going to a
// frequent listener, we have to build a built into Ping and process that.
// If we need to send secure, then we need to build a nonce request and
// wait for the nonce. Ultimately we then finally send the current msg.
// -------------------------------------------------------------------
TTOArray m_aenctStateTO;
tCIDLib::TBoolean m_bWaitAckRes;
tCIDLib::TCard1 m_c1NextNonceId;
tCIDLib::TCard4 m_c4CANQUsed;
tCIDLib::TCard4 m_c4WaitAckId;
tCIDLib::TCard8 m_c8ManIds;
TCANQ m_colCANQ;
TInQ m_colInQ;
TNonceList m_colInNonces;
TNonceList m_colOutNonces;
TOutQ m_colOutQ;
TCommPortCfg m_cpcfgSerial;
tCIDLib::TEncodedTime m_enctNextMsg;
tZWaveUSB3S::EIOStates m_eIOState;
TEvent m_evWaitAck;
TTimeStampList m_fcolLastPing;
THeapBuf m_mbufOut;
THeapBuf m_mbufNonce;
TMutex m_mtxSync;
TCommPortBase* m_pcommZWave;
TString m_strPort;
TThread m_thrIO;
TZWOutMsg m_zwomCur;
TZWOutMsg m_zwomNonceReq;
TZWOutMsg m_zwomPing;
};
#pragma CIDLIB_POPPACK
| 43.667851
| 92
| 0.57954
|
MarkStega
|
3957b27a6e8d37f1fb949a8736ca72ddbbf21051
| 1,047
|
cpp
|
C++
|
path_follower/src/utils/obstacle_cloud.cpp
|
sunarditay/gerona
|
7ca6bb169571d498c4a2d627faddc8cbe590d2c9
|
[
"BSD-3-Clause"
] | 296
|
2017-06-19T07:06:58.000Z
|
2022-03-09T01:27:44.000Z
|
path_follower/src/utils/obstacle_cloud.cpp
|
sunarditay/gerona
|
7ca6bb169571d498c4a2d627faddc8cbe590d2c9
|
[
"BSD-3-Clause"
] | 29
|
2017-11-07T08:49:12.000Z
|
2021-09-21T22:18:28.000Z
|
path_follower/src/utils/obstacle_cloud.cpp
|
sunarditay/gerona
|
7ca6bb169571d498c4a2d627faddc8cbe590d2c9
|
[
"BSD-3-Clause"
] | 117
|
2017-05-30T10:50:36.000Z
|
2022-03-09T01:27:23.000Z
|
/// HEADER
#include <path_follower/utils/obstacle_cloud.h>
#include <pcl_ros/point_cloud.h>
#include <tf/tf.h>
ObstacleCloud::ObstacleCloud()
: cloud(new Cloud)
{}
ObstacleCloud::ObstacleCloud(const Cloud::Ptr& c)
: cloud(c)
{
}
ObstacleCloud::ObstacleCloud(const Cloud::ConstPtr& c)
: cloud(new Cloud(*c))
{
}
bool ObstacleCloud::empty() const
{
return cloud->empty();
}
void ObstacleCloud::clear()
{
return cloud->clear();
}
void ObstacleCloud::transformCloud(const tf::Transform& transform, const std::string &target_frame)
{
for(auto& pt : cloud->points) {
tf::Point point(pt.x,pt.y,pt.z);
tf::Point transformed = transform * point;
pt.x = transformed.x();
pt.y = transformed.y();
pt.z = transformed.z();
}
cloud->header.frame_id = target_frame;
}
ros::Time ObstacleCloud::getStamp() const
{
ros::Time time;
time.fromNSec(cloud->header.stamp * 1e3);
return time;
}
std::string ObstacleCloud::getFrameId() const
{
return cloud->header.frame_id;
}
| 19.388889
| 99
| 0.65616
|
sunarditay
|
395821ee837c83876e394367c5069507c628c5c0
| 269
|
cpp
|
C++
|
Game/Game/Source/AI/Bot.cpp
|
jhlee94/Space_Farm-Power_of_Paint
|
42c1d57c18b48b6a737b7ae463387f41c66eb3d3
|
[
"MIT"
] | null | null | null |
Game/Game/Source/AI/Bot.cpp
|
jhlee94/Space_Farm-Power_of_Paint
|
42c1d57c18b48b6a737b7ae463387f41c66eb3d3
|
[
"MIT"
] | null | null | null |
Game/Game/Source/AI/Bot.cpp
|
jhlee94/Space_Farm-Power_of_Paint
|
42c1d57c18b48b6a737b7ae463387f41c66eb3d3
|
[
"MIT"
] | null | null | null |
#pragma once
#include <Phyre.h>
#include <Navigation\PhyreNavigation.h>
#include "Bot.h"
//
// Bot implementation
//
// Description:
// The constructor for the Bot class.
Bot::Bot()
: m_navigationComponent(NULL)
, m_navigationTarget(NULL)
, m_worldMatrix(NULL)
{
}
| 15.823529
| 39
| 0.717472
|
jhlee94
|
395872c03155dd5a33aaaffec450ce2f5d97c2f6
| 198
|
hpp
|
C++
|
dep/jsonpath/gramma.hpp
|
costan225/jsonpath
|
42d1d4099db1f3e8ceb3347c6df788ed6395ce47
|
[
"MIT"
] | 2
|
2019-04-10T15:33:35.000Z
|
2022-01-07T19:52:31.000Z
|
dep/jsonpath/gramma.hpp
|
costan225/jsonpath
|
42d1d4099db1f3e8ceb3347c6df788ed6395ce47
|
[
"MIT"
] | null | null | null |
dep/jsonpath/gramma.hpp
|
costan225/jsonpath
|
42d1d4099db1f3e8ceb3347c6df788ed6395ce47
|
[
"MIT"
] | 2
|
2021-10-20T07:20:04.000Z
|
2022-01-03T19:10:08.000Z
|
#ifndef __JSONPATH_GRAMMA_HPP__
#define __JSONPATH_GRAMMA_HPP__
#include "jsonpath_ast.hpp"
namespace costan {
bool compile(std::string src, ast::expression& exp, std::string& err);
}
#endif
| 19.8
| 74
| 0.762626
|
costan225
|
395ce4f22b062090265edac184bcd7bc9a21cf26
| 805
|
cpp
|
C++
|
src/Arc.cpp
|
CarstenHoyer/ofxCubicBezierToBiarc
|
d086430a99582d05e22445bad7f5d17508ae5bd8
|
[
"MIT"
] | 2
|
2019-02-01T17:17:40.000Z
|
2019-02-04T13:13:32.000Z
|
src/Arc.cpp
|
CarstenHoyer/ofxCubicBezierToBiarc
|
d086430a99582d05e22445bad7f5d17508ae5bd8
|
[
"MIT"
] | null | null | null |
src/Arc.cpp
|
CarstenHoyer/ofxCubicBezierToBiarc
|
d086430a99582d05e22445bad7f5d17508ae5bd8
|
[
"MIT"
] | 1
|
2019-07-17T19:29:42.000Z
|
2019-07-17T19:29:42.000Z
|
//
// Arc.cpp
// ofxCubicBezierToBiarc
//
// Created by Carsten Høyer on 31/01/2019.
//
#include "Arc.h"
#include <cmath>
Arc::Arc()
{
}
Arc::Arc(ofPoint _C, float _r, float _startAngle, float _sweepAngle, ofPoint _P1, ofPoint _P2, bool _cw)
{
C = _C;
r = _r;
startAngle = _startAngle;
sweepAngle = _sweepAngle;
cw = _cw;
P1 = _P1;
P2 = _P2;
}
float Arc::Length()
{
return r * abs(sweepAngle);
}
ofPoint Arc::PointAt(float t)
{
float x = C.x + r * cos(startAngle + t * sweepAngle);
float y = C.y + r * sin(startAngle + t * sweepAngle);
return ofPoint(x, y);
}
ofPath Arc::toPath()
{
ofPath path;
auto a1 = startAngle * 180.0f / M_PI;
auto a2 = (sweepAngle * 180.0f / M_PI);
path.arc(C, r, r, a1, a1 + a2, cw);
return path;
}
| 16.428571
| 104
| 0.586335
|
CarstenHoyer
|
39634fe1d90ae2070324105e56da9d795402325b
| 951
|
hh
|
C++
|
src/Titon/Io/Reader/XmlReader.hh
|
ciklon-z/framework
|
cbf44729173d3a83b91a2b0a217c6b3827512e44
|
[
"BSD-2-Clause"
] | 206
|
2015-01-02T20:01:12.000Z
|
2021-04-15T09:49:56.000Z
|
src/Titon/Io/Reader/XmlReader.hh
|
ciklon-z/framework
|
cbf44729173d3a83b91a2b0a217c6b3827512e44
|
[
"BSD-2-Clause"
] | 44
|
2015-01-02T06:03:43.000Z
|
2017-11-20T18:29:06.000Z
|
src/Titon/Io/Reader/XmlReader.hh
|
titon/framework
|
cbf44729173d3a83b91a2b0a217c6b3827512e44
|
[
"BSD-2-Clause"
] | 27
|
2015-01-03T05:51:29.000Z
|
2022-02-21T13:50:40.000Z
|
<?hh // strict
/**
* @copyright 2010-2015, The Titon Project
* @license http://opensource.org/licenses/bsd-license.php
* @link http://titon.io
*/
namespace Titon\Io\Reader;
use Titon\Io\ResourceMap;
use Titon\Io\Exception\ReadErrorException;
use Titon\Type\Xml;
/**
* A reader that loads its configuration from an XML file.
* Must have the SimpleXML module installed.
*
* @package Titon\Io\Reader
*/
class XmlReader extends AbstractReader {
/**
* {@inheritdoc}
*/
public function getResourceExt(): string {
return 'xml';
}
/**
* {@inheritdoc}
*
* @throws \Titon\Io\Exception\ReadErrorException
*/
public function readResource(): ResourceMap {
if ($this->exists()) {
return Xml::fromFile($this->getPath())->toMap(false)->toMap();
}
throw new ReadErrorException(sprintf('XmlReader failed to parse %s', $this->getPath()));
}
}
| 22.116279
| 96
| 0.622503
|
ciklon-z
|
396c233dc9af373efdf76adadc24bbdb690300bf
| 481
|
cpp
|
C++
|
test/filter/main.cpp
|
drugilsberg/functional-cpp
|
fd0b50a7ea4520fe50e92deb1aeff2495ba981e3
|
[
"MIT"
] | 2
|
2019-02-06T13:05:59.000Z
|
2019-02-22T10:16:32.000Z
|
test/filter/main.cpp
|
drugilsberg/functional-cpp
|
fd0b50a7ea4520fe50e92deb1aeff2495ba981e3
|
[
"MIT"
] | null | null | null |
test/filter/main.cpp
|
drugilsberg/functional-cpp
|
fd0b50a7ea4520fe50e92deb1aeff2495ba981e3
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<vector>
#include<math.h>
#include "Functional.hpp"
#include<cassert>
using namespace std;
int main(){
vector<double> test={1.0, 1.2, 2.0, 2.3, 3.0};
function< bool(double) > func= [] (const double & element){return element<2.0;};
vector<double> expectedFilter={ 1.0, 1.2};
cout << "Test filter..." << endl;
auto filtered = Functional::filter(test,func);
assert( expectedFilter==filtered);
cout << "passed!" << endl;
return 0;
}
| 20.913043
| 82
| 0.648649
|
drugilsberg
|
396ccc4c2842e1db684b3bd036eaafdb3621e842
| 1,799
|
hpp
|
C++
|
Palette.hpp
|
Cirras/eomap-classic
|
7ba4f5208ce49aeacb17bc4ad016b278388485b8
|
[
"Zlib"
] | 2
|
2020-11-02T08:23:11.000Z
|
2020-11-03T18:14:51.000Z
|
Palette.hpp
|
Cirras/eomap-classic
|
7ba4f5208ce49aeacb17bc4ad016b278388485b8
|
[
"Zlib"
] | 4
|
2020-12-09T14:34:56.000Z
|
2020-12-14T11:29:59.000Z
|
Palette.hpp
|
Cirras/eomap-classic
|
7ba4f5208ce49aeacb17bc4ad016b278388485b8
|
[
"Zlib"
] | 2
|
2020-12-09T12:40:10.000Z
|
2020-12-14T20:52:10.000Z
|
#ifndef PALETTE_INCLUDED
#define PALETTE_INCLUDED
#include "common.hpp"
#include "GFX_Loader.hpp"
extern int shared_yoffs[7];
const bool floor_tiles[25] = { 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
extern const int num_tiles_spec;
extern const char *tiles_spec[1][48];
class Palette
{
public:
int height = 0;
int file;
int layer = 0;
struct Tile
{
short id;
unsigned short x, y;
unsigned short w, h;
};
std::list<Tile> tiles;
short selected_tile = 0;
// saved offset
int* yoff;
Palette(int file_) : file(file_)
{
switch (file_)
{
case 3: yoff = &shared_yoffs[0]; break;
case 4: yoff = &shared_yoffs[1]; break;
case 5: yoff = &shared_yoffs[2]; break;
case 6: yoff = &shared_yoffs[3]; break;
case 7: yoff = &shared_yoffs[4]; break;
case 22: yoff = &shared_yoffs[5]; break;
case -1: yoff = &shared_yoffs[6]; break;
default: std::abort();
}
}
void Populate(GFX_Loader &loader);
void Click(int x, int y);
int RightClick(int x, int y);
};
class Pal_Renderer
{
public:
a5::Display ⌖
GFX_Loader gfxloader;
Palette *pal = nullptr;
int yoff = 0;
int scrollyoff = 0;
int animation_state = 0;
a5::Bitmap *cursor;
Pal_Renderer(a5::Display &target_) :
target(target_)
{ }
void SetPal(int layer, Palette &pal)
{
int prev_file = -2;
if (this->pal)
{
prev_file = this->pal->file;
*this->pal->yoff = yoff;
}
pal.Populate(this->gfxloader);
this->pal = &pal;
this->pal->layer = layer;
this->yoff = *pal.yoff;
if (pal.file != prev_file)
gfxloader.Reset();
}
void Move(int y)
{
this->yoff = y;
}
void ResetView()
{
this->Move(0);
}
void Render();
};
#endif // PALETTE_INCLUDED
| 17.298077
| 116
| 0.601445
|
Cirras
|
3972826602288b422d55773cf8135a91436fef10
| 1,860
|
cpp
|
C++
|
Volume_101(10100-10199)/10106.cpp
|
jay16213/UVA-practice
|
0f4bfcf47861386f422405612fc01bc00944ca94
|
[
"MIT"
] | null | null | null |
Volume_101(10100-10199)/10106.cpp
|
jay16213/UVA-practice
|
0f4bfcf47861386f422405612fc01bc00944ca94
|
[
"MIT"
] | null | null | null |
Volume_101(10100-10199)/10106.cpp
|
jay16213/UVA-practice
|
0f4bfcf47861386f422405612fc01bc00944ca94
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main()
{
string in1, in2;
while(cin >> in1 >> in2)
{
//any number multiply 0 = 0
if(in1 == "0" || in2 == "0")
{
printf("0\n");
continue;
}
vector<int> x, y, ans;//ans = x * y
for(int i = in1.size() - 1; i >= 0; i--) x.push_back(in1[i] - '0');
for(int i = in2.size() - 1; i >= 0; i--) y.push_back(in2[i] - '0');
for(int digit = 0; digit < y.size(); digit++)
{
vector<int> partial_product;
//shift digit
for(int i = 0; i < digit; i++) partial_product.push_back(0);
int carry = 0;
for(int j = 0; j < x.size(); j++)
{
int tmp = x[j] * y[digit] + carry;
if(tmp >= 10)
{
carry = tmp / 10;
tmp %= 10;
}
else carry = 0;
partial_product.push_back(tmp);
}
if(carry) partial_product.push_back(carry);
carry = 0;
//align digit
for(int i = ans.size(); i < partial_product.size(); i++) ans.push_back(0);
//add partial_product to ans
for(int i = 0, j = 0; i < ans.size() && j < partial_product.size(); i++, j++)
{
int tmp = ans[i] + partial_product[j] + carry;
if(tmp >= 10)
{
carry = 1;
tmp -= 10;
}
else carry = 0;
ans[i] = tmp;
}
if(carry) ans.push_back(carry);
}
for(int i = ans.size() - 1; i >= 0; i--) printf("%d", ans[i]);
printf("\n");
in1.clear();
in2.clear();
}
return 0;
}
| 27.352941
| 89
| 0.382258
|
jay16213
|
3979828f59376c5ad77556e93a34a7a01f72a969
| 944
|
cpp
|
C++
|
201912/3(30分).cpp
|
YiqinXiong/CSP_Practice
|
b5840117175f0370d4c1fbcc3c6ffd1fd337a04c
|
[
"MIT"
] | null | null | null |
201912/3(30分).cpp
|
YiqinXiong/CSP_Practice
|
b5840117175f0370d4c1fbcc3c6ffd1fd337a04c
|
[
"MIT"
] | null | null | null |
201912/3(30分).cpp
|
YiqinXiong/CSP_Practice
|
b5840117175f0370d4c1fbcc3c6ffd1fd337a04c
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <string.h>
using namespace std;
const int N = 105;
int n;
vector<string> equs;
bool solve(string s)
{
int equ_pos = s.find('=');
string left = s.substr(0, equ_pos);
string right = s.substr(equ_pos + 1, s.length() - equ_pos - 1);
for (int i = 0; i < left.length(); i++)
{
int pos = right.find(left[i]);
if (pos < 0)
return false;
right.erase(pos, 1);
}
if (right == "")
return true;
else
return false;
}
int main()
{
string s;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
cin >> s;
equs.push_back(s);
}
for (int i = 0; i < n; i++)
{
if (solve(equs[i]))
{
printf("Y\n");
}
else
{
printf("N\n");
}
}
return 0;
}
| 17.811321
| 67
| 0.471398
|
YiqinXiong
|
30290c7a16989177749b05ae6b0b902b8f514a95
| 12,880
|
cc
|
C++
|
tensorflow/tools/graph_transforms/fold_constants_lib.cc
|
tycho/tensorflow
|
27767d8e9c1325979cf32ff5b81c10df9006fd57
|
[
"Apache-2.0"
] | 2
|
2020-02-18T04:08:18.000Z
|
2020-05-20T07:14:44.000Z
|
tensorflow/tools/graph_transforms/fold_constants_lib.cc
|
tycho/tensorflow
|
27767d8e9c1325979cf32ff5b81c10df9006fd57
|
[
"Apache-2.0"
] | 1
|
2018-10-26T20:01:34.000Z
|
2018-10-26T20:01:34.000Z
|
tensorflow/tools/graph_transforms/fold_constants_lib.cc
|
tycho/tensorflow
|
27767d8e9c1325979cf32ff5b81c10df9006fd57
|
[
"Apache-2.0"
] | 3
|
2018-10-26T19:30:26.000Z
|
2021-03-19T19:30:40.000Z
|
/* Copyright 2016 The TensorFlow Authors. 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 "tensorflow/tools/graph_transforms/fold_constants_lib.h"
#include <algorithm>
#include <iterator>
#include "tensorflow/core/common_runtime/constant_folding.h"
#include "tensorflow/core/common_runtime/shape_refiner.h"
#include "tensorflow/core/graph/graph_constructor.h"
#include "tensorflow/core/graph/node_builder.h"
#include "tensorflow/core/graph/subgraph.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/util/command_line_flags.h"
#include "tensorflow/tools/graph_transforms/transform_utils.h"
namespace tensorflow {
namespace graph_transforms {
Status ReplaceSendRecvs(const GraphDef& original_graph_def,
const GraphDef& rewritten_graph_def,
const std::vector<string>& inputs,
const std::vector<string>& outputs,
GraphDef* output_graph_def) {
std::map<string, const NodeDef*> original_map;
MapNamesToNodes(original_graph_def, &original_map);
std::map<string, string> new_node_names;
for (const NodeDef& node : rewritten_graph_def.node()) {
// If the op isn't a Recv, or it was in the original, nothing to do.
if ((node.op() != "_Recv") || (original_map.count(node.name()) == 1)) {
continue;
}
// See if it matches an input from the original.
for (const string& input : inputs) {
// Here we rely on the naming convention for the Recv nodes that
// RewriteGraphForExecution adds in the place of the feed inputs.
string input_prefix = "_recv_" + input + "_";
if (StringPiece(node.name()).starts_with(input_prefix)) {
// If it does, prepare to rename any inputs that refer to it.
new_node_names[node.name()] = input;
}
}
}
std::vector<NodeDef> nodes_to_add;
for (const NodeDef& node : rewritten_graph_def.node()) {
if ((node.op() == "_Send") || (node.op() == "_Recv")) {
// If the op is a Send or Recv that wasn't in the original, skip it.
if (original_map.count(node.name()) == 0) {
continue;
}
}
NodeDef new_node;
new_node = node;
new_node.mutable_input()->Clear();
for (const string& old_input : node.input()) {
string input_prefix;
string input_node_name;
string input_suffix;
NodeNamePartsFromInput(old_input, &input_prefix, &input_node_name,
&input_suffix);
string new_input;
if (new_node_names.count(input_node_name) > 0) {
new_input =
input_prefix + new_node_names[input_node_name] + input_suffix;
} else {
new_input = old_input;
}
*(new_node.mutable_input()->Add()) = new_input;
}
nodes_to_add.push_back(new_node);
}
for (std::pair<string, string> entry : new_node_names) {
string removed_node_name = entry.second;
const NodeDef* removed_node = original_map[removed_node_name];
NodeDef new_node;
new_node = *removed_node;
nodes_to_add.push_back(new_node);
}
for (const NodeDef& node : nodes_to_add) {
*output_graph_def->mutable_node()->Add() = node;
}
return Status::OK();
}
Status RemoveUnusedNodes(const GraphDef& input_graph_def,
const TransformFuncContext& context,
GraphDef* output_graph_def) {
std::map<string, const NodeDef*> node_map;
MapNamesToNodes(input_graph_def, &node_map);
std::set<string> used_nodes;
for (const string& input : context.input_names) {
used_nodes.insert(input);
}
std::vector<string> current_nodes = context.output_names;
while (!current_nodes.empty()) {
std::set<string> next_nodes;
for (const string& node_name : current_nodes) {
used_nodes.insert(node_name);
if (node_map.count(node_name) == 0) {
LOG(ERROR) << "Bad graph structure, no node named '" << node_name
<< "' found for input lookup";
return errors::InvalidArgument("Bad graph structure, no node named '",
node_name, "' found for input lookup");
}
const NodeDef& node = *(node_map[node_name]);
for (const string& input_name : node.input()) {
const string& input_node_name = NodeNameFromInput(input_name);
if (used_nodes.count(input_node_name) == 0) {
next_nodes.insert(input_node_name);
}
}
}
current_nodes = std::vector<string>(next_nodes.begin(), next_nodes.end());
}
FilterGraphDef(
input_graph_def,
[&](const NodeDef& node) { return used_nodes.count(node.name()) > 0; },
output_graph_def);
return Status::OK();
}
// Converts a shape inference handle to a PartialTensorShape.
Status ShapeHandleToTensorShape(const shape_inference::ShapeHandle& handle,
shape_inference::InferenceContext* context,
PartialTensorShape* shape) {
// The default is already unknown
if (!context->RankKnown(handle)) return Status::OK();
std::vector<int64> dims(context->Rank(handle));
for (int32 i = 0; i < dims.size(); ++i) {
dims[i] = context->Value(context->Dim(handle, i));
}
return PartialTensorShape::MakePartialShape(dims.data(), dims.size(), shape);
}
Status ShapeForNode(const TransformFuncContext& context,
const string& node_name, TensorShape* result,
bool* has_shape_specified) {
*has_shape_specified = false;
// Check to see if we have been given a default for all placeholders.
if (context.params.count("type")) {
if (context.params.at("shape").size() != 1) {
return errors::InvalidArgument(
"You must pass no more than one default 'shape' to "
"fold_constants");
}
const string& shape_string = context.params.at("shape")[0];
TF_RETURN_IF_ERROR(TensorShapeFromString(shape_string, result));
*has_shape_specified = true;
}
// See if there's a particular type specified for this placeholder.
if (context.params.count("name") || context.params.count("type_for_name")) {
if (!context.params.count("name") ||
!context.params.count("type_for_name") ||
(context.params.at("type_for_name").size() !=
context.params.at("name").size())) {
return errors::InvalidArgument(
"You must pass a 'shape_for_name' arg for every 'name', e.g. "
"fold_constants(name=foo, shape_for_name=\"2,2,1\", name=bar, "
"shape_for_name=\"1\"");
}
const int name_count = context.params.at("name").size();
for (int i = 0; i < name_count; ++i) {
if (context.params.at("name")[i] == node_name) {
const string& shape_string = context.params.at("shape_for_name")[i];
TF_RETURN_IF_ERROR(TensorShapeFromString(shape_string, result));
*has_shape_specified = true;
}
}
}
return Status::OK();
}
// Converts any sub-graphs that can be resolved into constant expressions into
// single Const ops.
Status FoldConstants(const GraphDef& input_graph_def,
const TransformFuncContext& context,
GraphDef* output_graph_def) {
Graph input_graph(OpRegistry::Global());
TF_RETURN_IF_ERROR(input_graph.AddFunctionLibrary(input_graph_def.library()));
ShapeRefiner shape_refiner(input_graph.versions(), input_graph.op_registry());
shape_refiner.set_require_shape_inference_fns(false);
shape_refiner.set_disable_constant_propagation(false);
shape_refiner.set_function_library_for_shape_inference(
&input_graph.flib_def());
bool clear_output_shapes;
TF_RETURN_IF_ERROR(context.GetOneBoolParameter("clear_output_shapes", true,
&clear_output_shapes));
if (clear_output_shapes) {
// Some older GraphDefs have saved _output_shapes attributes which are out
// of date and cause import errors, so clean them up first.
GraphDef cleaned_graph_def;
RemoveAttributes(input_graph_def, {"_output_shapes"}, &cleaned_graph_def);
// Set specified shapes.
for (NodeDef& node : *cleaned_graph_def.mutable_node()) {
TensorShape shape;
bool has_shape_specified;
TF_RETURN_IF_ERROR(
ShapeForNode(context, node.name(), &shape, &has_shape_specified));
if (has_shape_specified) {
SetNodeAttr("shape", shape, &node);
}
}
TF_RETURN_IF_ERROR(
ImportGraphDef({}, cleaned_graph_def, &input_graph, &shape_refiner));
} else {
TF_RETURN_IF_ERROR(
ImportGraphDef({}, input_graph_def, &input_graph, &shape_refiner));
}
// Sorted array of input names as lookup table.
std::vector<TensorId> input_names;
input_names.reserve(context.input_names.size());
std::transform(context.input_names.begin(), context.input_names.end(),
std::back_inserter(input_names),
[](const string& name) { return ParseTensorName(name); });
const auto compare = [](TensorId lhs, TensorId rhs) {
return lhs.first < rhs.first;
};
std::sort(input_names.begin(), input_names.end(), compare);
// Set statically inferred shapes.
std::unordered_map<string, std::vector<PartialTensorShape>> shape_map;
for (const Node* const node : input_graph.nodes()) {
auto ctx = shape_refiner.GetContext(node);
if (ctx == nullptr) {
continue;
}
std::vector<PartialTensorShape>& partial_shapes = shape_map[node->name()];
if (ctx->num_outputs() <= 0) continue;
partial_shapes.resize(ctx->num_outputs());
// Check all outputs.
for (const Edge* out_edge : node->out_edges()) {
if (out_edge->IsControlEdge()) continue;
const int output_idx = out_edge->src_output();
TF_RETURN_IF_ERROR(ShapeHandleToTensorShape(ctx->output(output_idx), ctx,
&partial_shapes[output_idx]));
}
// RewriteGraphForExecution() will add a Recv node for each input. Shape
// refiner does not include shape information of these Recv nodes. Therefore
// we add entries for Recv nodes here.
const auto pair = std::equal_range(input_names.begin(), input_names.end(),
TensorId{node->name(), 0}, compare);
for (auto it = pair.first; it != pair.second; ++it) {
const string recv_name =
strings::StrCat("_recv_", it->first, "_", it->second);
auto& recv_partial_shapes = shape_map[recv_name];
// For whatever reason (for example, name collision) if the map entry was
// already there, then do nothing.
if (recv_partial_shapes.empty()) {
recv_partial_shapes.push_back(partial_shapes[it->second]);
}
}
}
subgraph::RewriteGraphMetadata unused_metadata;
TF_RETURN_IF_ERROR(subgraph::RewriteGraphForExecution(
&input_graph, context.input_names, context.output_names, {}, {},
false /* use_function_convention */, &unused_metadata));
ConstantFoldingOptions cf_opts;
cf_opts.shape_map = &shape_map;
// Exclude specified nodes from constant folding.
if (context.params.count("exclude_op") > 0) {
const auto& excluded_nodes = context.params.at("exclude_op");
const std::set<string> excluded_nodes_set(excluded_nodes.begin(),
excluded_nodes.end());
cf_opts.consider = [excluded_nodes_set](const Node* n) {
return excluded_nodes_set.find(n->op_def().name()) ==
excluded_nodes_set.end();
};
}
// Constant folding.
bool was_mutated;
TF_RETURN_IF_ERROR(ConstantFold(cf_opts, nullptr, Env::Default(), nullptr,
&input_graph, &was_mutated));
GraphDef folded_graph_def;
input_graph.ToGraphDef(&folded_graph_def);
GraphDef send_recvs_replaced;
TF_RETURN_IF_ERROR(ReplaceSendRecvs(input_graph_def, folded_graph_def,
context.input_names, context.output_names,
&send_recvs_replaced));
TF_RETURN_IF_ERROR(
RemoveUnusedNodes(send_recvs_replaced, context, output_graph_def));
return Status::OK();
}
REGISTER_GRAPH_TRANSFORM("fold_constants", FoldConstants);
} // namespace graph_transforms
} // namespace tensorflow
| 39.630769
| 80
| 0.659938
|
tycho
|
30291f72bfce3e0ae14d999fa7127ed0b9385138
| 1,902
|
cpp
|
C++
|
leetcode_0001_0050/leetcode_0018_4sum.cpp
|
AlfengYuan/leetcode-cplusplus-offline
|
602c3d531d984c6961d9eec2b051527e721b2123
|
[
"MIT"
] | null | null | null |
leetcode_0001_0050/leetcode_0018_4sum.cpp
|
AlfengYuan/leetcode-cplusplus-offline
|
602c3d531d984c6961d9eec2b051527e721b2123
|
[
"MIT"
] | null | null | null |
leetcode_0001_0050/leetcode_0018_4sum.cpp
|
AlfengYuan/leetcode-cplusplus-offline
|
602c3d531d984c6961d9eec2b051527e721b2123
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <set>
#include <vector>
#include <cstdlib>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> Vres;
if(nums.size() < 4) return Vres;
set<vector<int>> res;
vector<int> tmp(4, -1);
sort(nums.begin(), nums.end(),less<int>());
for(int l = 0; l<nums.size()-3; ++l)
{
if(target >= 0 && nums[l] > target) break;
for(int i = l+1; i<nums.size()-2; ++i )
{
for(int j = i+1, k = nums.size() -1; j < k;)
{
long curSum = (long)nums[l] + (long)nums[i] + (long)nums[j] + (long)nums[k];
if(curSum > target)
{
--k;
}
else if(curSum < target)
{
++j;
}
else
{
tmp[0] = nums[l];
tmp[1] = nums[i];
tmp[2] = nums[j];
tmp[3] = nums[k];
res.insert(tmp);
--k;
++j;
}
}
}
}
Vres.assign(res.begin(), res.end());
return Vres;
}
};
int main(int argc, char *argv[])
{
vector<int> nums = {0,0,0,1000000000,1000000000,1000000000,1000000000};
int target = 1000000000;
Solution solution = Solution();
vector<vector<int>> res = solution.fourSum(nums, target);
cout << "[";
for(vector<int> vecs : res)
{
cout << "[";
for(int vec: vecs)
{
cout << vec << ", ";
}
cout << "], ";
}
cout << "]" << endl;
return 0;
}
| 26.788732
| 96
| 0.382229
|
AlfengYuan
|
3029dc1265efe9e11d9f0ed7f661ebf367e8d953
| 1,113
|
cpp
|
C++
|
_site/Competitive Programming/Codeforces/1136C.cpp
|
anujkyadav07/anuj-k-yadav.github.io
|
ac5cccc8cdada000ba559538cd84921437b3c5e6
|
[
"MIT"
] | 1
|
2019-06-10T04:39:49.000Z
|
2019-06-10T04:39:49.000Z
|
_site/Competitive Programming/Codeforces/1136C.cpp
|
anujkyadav07/anuj-k-yadav.github.io
|
ac5cccc8cdada000ba559538cd84921437b3c5e6
|
[
"MIT"
] | 2
|
2021-09-27T23:34:07.000Z
|
2022-02-26T05:54:27.000Z
|
_site/Competitive Programming/Codeforces/1136C.cpp
|
anujkyadav07/anuj-k-yadav.github.io
|
ac5cccc8cdada000ba559538cd84921437b3c5e6
|
[
"MIT"
] | 3
|
2019-06-23T14:15:08.000Z
|
2019-07-09T20:40:58.000Z
|
#include "bits/stdc++.h"
#ifdef PRINTERS
#include "printers.hpp"
using namespace printers;
#define tr(a) cerr<<#a<<" : "<<a<<endl
#else
#define tr(a)
#endif
#define ll long long
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define vi vector<int>
#define all(a) (a).begin(),(a).end()
#define F first
#define S second
#define sz(x) (int)x.size()
#define hell 1000000007
#define endl '\n'
#define rep(i,a,b) for(int i=a;i<b;i++)
using namespace std;
int main(){
ll n, m;
cin>>n>>m;
ll a[n][m], b[n][m];
vector<vi> aa(n+m), bb(n+m);
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
cin>>a[i][j];
aa[i+j].pb(a[i][j]);
}
}
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
cin>>b[i][j];
bb[i+j].pb(b[i][j]);
}
}
bool pos = true;
for (int i = 0; i < n+m; ++i)
{
sort(aa[i].begin(), aa[i].end());
sort(bb[i].begin(), bb[i].end());
if(aa[i] != bb[i]){
pos = false;
break;
}
}
if(pos) cout<<"YES\n";
else cout<<"NO\n";
}
| 18.55
| 44
| 0.487871
|
anujkyadav07
|
302a101be5b8e36ad4b5a331a2be3f2f2e8b4123
| 2,020
|
cpp
|
C++
|
src/Parser/fq.cpp
|
frankandreace/GenoLight
|
6aa3c4087b02dae8c4f5bec84617f49f08913025
|
[
"MIT"
] | null | null | null |
src/Parser/fq.cpp
|
frankandreace/GenoLight
|
6aa3c4087b02dae8c4f5bec84617f49f08913025
|
[
"MIT"
] | null | null | null |
src/Parser/fq.cpp
|
frankandreace/GenoLight
|
6aa3c4087b02dae8c4f5bec84617f49f08913025
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include "fq.hpp"
#include <limits>
#include <vector>
#include <fstream>
//costruttore
//https://stackoverflow.com/questions/50417435/why-cannot-i-initialize-a-ifstream-ref-from-constructor
fq::fq(const std::string &_path_fastq) :
fastq(_path_fastq)
{
if (_path_fastq != " ")
path_fastq = _path_fastq;
else
{
std::cerr << "Please enter the path where the reads are stored." << std::endl;
exit (EXIT_FAILURE);
}
//fastq(path_fastq); //std::ios::binary
}
//costruttore
fq::fq(std::string f_filename_fastq, std::string s_filename_fastq)
{
if ((f_filename_fastq != " ") && (s_filename_fastq != " "))
{
path_fastq = f_filename_fastq;
path_fastq_mate_pairs = s_filename_fastq;
}
else
{
std::cerr << "Please enter the path where the reads mate pairs stored." << std::endl;
exit (EXIT_FAILURE);
}
std::ifstream fastq(path_fastq); //std::ios::binary
}
FastqRecord fq::read_fastq_record(std::istream& fastq)
{
std::string header;
std::string seq;
std::string quals;
// Unlike FASTA, FASTQ always use one line per field.
if (!std::getline(fastq, header) || header == "")
{
end_file = true; //private variable
FastqRecord f = FastqRecord();
return f;
}
std::getline(fastq, seq);
fastq.ignore(std::numeric_limits < std::streamsize > ::max(), '\n');
std::getline(fastq, quals);
if (seq.size() != quals.size())
{
std::cerr << "Length read different length quality score" << std::endl;
exit (EXIT_FAILURE);
}
FastqRecord f = FastqRecord(std::move(header), std::move(seq), std::move(quals));
return f;
}
void fq::fill_chunk(std::vector <FastqRecord>& chunks)
{
int i = 0;
for (; ((i < chunks.size()) && (end_file == false)); i++)
{
chunks[i] = read_fastq_record(fastq);
}
if (end_file == false)
chunks.resize(i);
else
{
chunks.resize(i - 1);//If end_file==true add a nullptr in records
//std::cerr << "Ultimo chunk size: "<< records.size() << std::endl;
fastq.close();
}
}
bool fq::AllReadExtracted()
{
return end_file;
}
| 23.488372
| 102
| 0.668812
|
frankandreace
|
302a2269f578a9e2dc5dffe2a2731e120938a33b
| 304
|
cpp
|
C++
|
ControlClass.cpp
|
mls-m5/NoMaintenance
|
c54c702b658c6a3abe36ff2d175b5c923d4ca55f
|
[
"Apache-2.0"
] | null | null | null |
ControlClass.cpp
|
mls-m5/NoMaintenance
|
c54c702b658c6a3abe36ff2d175b5c923d4ca55f
|
[
"Apache-2.0"
] | null | null | null |
ControlClass.cpp
|
mls-m5/NoMaintenance
|
c54c702b658c6a3abe36ff2d175b5c923d4ca55f
|
[
"Apache-2.0"
] | null | null | null |
/*
* ControlClass.cpp
*
* Created on: 29 jan 2013
* Author: mattias
*/
#include "ControlClass.h"
namespace Solid {
ControlClass::ControlClass() {
// TODO Auto-generated constructor stub
}
ControlClass::~ControlClass() {
// TODO Auto-generated destructor stub
}
} /* namespace Solid */
| 13.818182
| 40
| 0.674342
|
mls-m5
|
3032674a0b03335f2365c8b382462dc5b0ab2806
| 3,097
|
cpp
|
C++
|
common/collectiontest1.cpp
|
mintomic/samples
|
c4acfa03ea98bcfe9ff67d97705e7486a92df45b
|
[
"BSD-3-Clause"
] | 56
|
2015-01-01T23:01:00.000Z
|
2021-12-27T16:40:39.000Z
|
common/collectiontest1.cpp
|
mintomic/samples
|
c4acfa03ea98bcfe9ff67d97705e7486a92df45b
|
[
"BSD-3-Clause"
] | null | null | null |
common/collectiontest1.cpp
|
mintomic/samples
|
c4acfa03ea98bcfe9ff67d97705e7486a92df45b
|
[
"BSD-3-Clause"
] | 14
|
2015-02-13T13:38:50.000Z
|
2019-05-31T02:47:32.000Z
|
#include "collectiontest1.h"
#include "experiment.h"
#include <mintomic/mintomic.h>
#include <mintsystem/timer.h>
#include <mintpack/lwlogger.h>
#include <mintpack/threadsynchronizer.h>
#include <mintpack/random.h>
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
//--------------------------------------------------------------
// In this experiment, each thread adds a different list of items to the
// collection. No two threads add the same key.
//--------------------------------------------------------------
namespace CollectionTest1
{
struct Result
{
TrialParams params;
BasePlugin* plugin;
mint_atomic32_t failed;
};
void threadFunc(int threadNum, void* param)
{
Result* result = (Result*) param;
LWLOG("Begin loop", threadNum);
if (!result->plugin->DoThread(threadNum, &result->params))
mint_store_32_relaxed(&result->failed, 1);
LWLOG("End loop", threadNum);
}
class Experiment : public IExperiment
{
private:
BasePlugin* m_plugin;
uint32_t m_numPairs;
uint32_t m_tableSize;
int m_numThreads;
public:
Experiment(BasePlugin* plugin, uint32_t numPairs, uint32_t tableSize, int numThreads)
: m_plugin(plugin)
, m_numPairs(numPairs)
, m_tableSize(tableSize)
, m_numThreads(numThreads)
{
}
void Run(TimeKeeper& timeKeeper)
{
// Warm up some threads
ThreadSynchronizer threads(m_numThreads);
// Allocate storage
Result result;
result.params.pairs = new Pair[m_numPairs];
result.params.numPairs = m_numPairs;
result.params.numThreads = m_numThreads;
result.plugin = m_plugin;
result.failed._nonatomic = 0;
// Fill in pairs
Random keySeq;
Random valueSeq;
for (uint32_t i = 0; i < m_numPairs; i++)
{
do { result.params.pairs[i].key = keySeq.generateUnique32(); } while (result.params.pairs[i].key == 0);
do { result.params.pairs[i].value = valueSeq.generateUnique32(); } while (result.params.pairs[i].value == 0);
}
// Kick threads through the experiment several times
for (int i = 0; i < 10; i++)
{
m_plugin->CreateCollection(m_tableSize);
threads.run(threadFunc, &result.params);
// Check result
if (result.failed._nonatomic || !m_plugin->CheckCollection(&result.params))
timeKeeper.failures++;
// Return average thread time
timeKeeper.totalTime += threads.getAverageThreadRunningTime();
timeKeeper.trials++;
}
}
};
IExperiment* CreateExperiment(BasePlugin* plugin, uint32_t numItems, uint32_t tableSize)
{
return new Experiment(plugin, numItems, tableSize, 2);
}
} // namespace CollectionTest1
| 31.927835
| 125
| 0.560542
|
mintomic
|
303ad55a12c1a479d51c7ea6bcf054077f9f373b
| 221
|
cpp
|
C++
|
src/main.cpp
|
LowSpecCorgi/Masochist-Discord
|
e67ed26d5085c06f919c7097459db6aaf309c2a3
|
[
"MIT"
] | 4
|
2021-06-13T18:35:15.000Z
|
2021-07-13T17:57:52.000Z
|
src/main.cpp
|
LowSpecCorgi/Masochist-Discord
|
e67ed26d5085c06f919c7097459db6aaf309c2a3
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
LowSpecCorgi/Masochist-Discord
|
e67ed26d5085c06f919c7097459db6aaf309c2a3
|
[
"MIT"
] | null | null | null |
#include "client.hpp"
#include <fstream>
int main()
{
std::fstream file;
file.open("../.env", std::ios::in);
std::string token;
file >> token;
Client client(token);
client.run();
return 0;
}
| 14.733333
| 39
| 0.570136
|
LowSpecCorgi
|
303cfbb94c8872723e7549f550d4e03addfbb268
| 3,506
|
hpp
|
C++
|
modules/logic/src/Logic/Itk/ImageToImageFilter/BinaryFunctorImageFilter/gmLogicItkLabelOverlayImageFilter.hpp
|
GraphMIC/GraphMIC
|
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
|
[
"BSD-3-Clause"
] | 43
|
2016-04-11T11:34:05.000Z
|
2022-03-31T03:37:57.000Z
|
modules/logic/src/Logic/Itk/ImageToImageFilter/BinaryFunctorImageFilter/gmLogicItkLabelOverlayImageFilter.hpp
|
kevinlq/GraphMIC
|
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
|
[
"BSD-3-Clause"
] | 1
|
2016-05-17T12:58:16.000Z
|
2016-05-17T12:58:16.000Z
|
modules/logic/src/Logic/Itk/ImageToImageFilter/BinaryFunctorImageFilter/gmLogicItkLabelOverlayImageFilter.hpp
|
kevinlq/GraphMIC
|
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
|
[
"BSD-3-Clause"
] | 14
|
2016-05-13T20:23:16.000Z
|
2021-12-20T10:33:19.000Z
|
#pragma once
#include "gmLogicItkBinaryFunctorImageFilter.hpp"
#include "gmLogicItkUtil.hpp"
#include <itkLabelOverlayImageFilter.h>
namespace gm
{
namespace Logic
{
namespace Itk
{
class LabelOverlayImageFilter : public BinaryFunctorImageFilter
{
public:
struct ID
{
static constexpr auto images = "images";
static constexpr auto labelImages = "label images";
static constexpr auto opacity = "opacity";
static constexpr auto backgroundValue = "background value";
static constexpr auto output = "output";
};
static Register<LabelOverlayImageFilter> Register;
using Access = Enable::ImageTypes <
Enable::Dimension<2,3>,
Enable::Scalar<unsigned char, unsigned short, unsigned int, char, short, int>
>;
LabelOverlayImageFilter() : BinaryFunctorImageFilter("LabelOverlayImageFilter")
{
log_trace(Log::New, this);
this->addParamGroup("LabelOverlayImageFilter");
this->add(new Slot::Input<Data::Image>(ID::images, Access::MakeConstraints(), Data::Required));
this->add(new Slot::Input<Data::Image>(ID::labelImages, Access::MakeConstraints(), Data::Required));
this->add(new Param::Number(ID::opacity, 0.5));
this->add(new Param::Vector(ID::backgroundValue, {"r", "g", "b"} , 0));
this->add(new Slot::Output<Data::Image>(ID::output, Access::MakeConstraints()));
}
template <class TImage>
auto process() -> void
{
using ImageType = typename TImage::itk_image_t;
using OutputType = itk::Image<itk::RGBPixel<typename ImageType::PixelType>, TImage::dimension>;
using FilterType = itk::LabelOverlayImageFilter<ImageType, ImageType, OutputType>;
auto filter = FilterType::New();
auto output = this->getOutput<Data::Image>(ID::output);
auto color_vec = this->getParam<Param::Vector>(ID::backgroundValue)->getValues();
applyParameters<FilterType>(filter);
filter->SetOpacity(this->getParam<Param::Number>(ID::opacity)->getValue());
filter->SetBackgroundValue(Util::VectorToPixel<typename FilterType::LabelPixelType>(color_vec));
filter->SetLabelImage(Image::ToItk<ImageType>(this->getInput<Data::Image>(ID::labelImages)->getImage()));
for (auto it : this->inputIterator())
{
filter->SetInput(Image::ToItk<ImageType>(it.image()));
filter->Update();
output->addImage(Image::FromItk<OutputType>(filter->GetOutput()));
}
}
auto run() -> void override
{
log_trace(Log::Func);
Invoke(this);
}
};
}
}
}
| 43.825
| 125
| 0.491728
|
GraphMIC
|
304408d0512e9fdf5d26e0038615746b9e1e8668
| 5,313
|
cpp
|
C++
|
libEPLViz/src/baseModelView/TreeModelBase.cpp
|
epl-viz/EPL-Viz
|
80d790110113f83da6845ce124997d13bfd45270
|
[
"BSD-3-Clause"
] | 3
|
2017-01-23T13:29:21.000Z
|
2021-03-08T17:40:42.000Z
|
libEPLViz/src/baseModelView/TreeModelBase.cpp
|
epl-viz/EPL-Viz
|
80d790110113f83da6845ce124997d13bfd45270
|
[
"BSD-3-Clause"
] | 4
|
2017-03-26T12:56:08.000Z
|
2017-08-18T20:32:37.000Z
|
libEPLViz/src/baseModelView/TreeModelBase.cpp
|
epl-viz/EPL-Viz
|
80d790110113f83da6845ce124997d13bfd45270
|
[
"BSD-3-Clause"
] | null | null | null |
/* Copyright (c) 2017, EPL-Vizards
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the EPL-Vizards 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 EPL-Vizards 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.
*/
/*!
* \file TreeModelBase.cpp
*/
#include "TreeModelBase.hpp"
#include "OD.hpp"
#include <QMenu>
#include <QString>
#include <QThread>
#include <algorithm>
using namespace EPL_Viz;
using namespace EPL_DataCollect;
using namespace std;
TreeModelBase::TreeModelBase(QAbstractItemView *widget) : QAbstractItemModel(widget) { widget->setModel(this); }
TreeModelBase::~TreeModelBase() {
if (root)
delete root;
}
std::unique_lock<std::recursive_mutex> TreeModelBase::getLock() const {
return std::unique_lock<std::recursive_mutex>(*const_cast<std::recursive_mutex *>(&mutex));
}
TreeModelItemBase *TreeModelBase::getItem(const QModelIndex &index) const {
auto l = getLock();
if (index.isValid()) {
TreeModelItemBase *p = static_cast<TreeModelItemBase *>(index.internalPointer());
if (p) {
return p;
} else {
return nullptr;
}
}
return root;
}
QModelIndex TreeModelBase::index(int row, int column, const QModelIndex &parent) const {
auto l = getLock();
if (parent.isValid() && parent.column() != 0)
return QModelIndex();
TreeModelItemBase *p = getItem(parent);
TreeModelItemBase *c = p->child(static_cast<size_t>(row));
if (c) {
return createIndex(row, column, c);
}
return QModelIndex();
}
QModelIndex TreeModelBase::parent(const QModelIndex &index) const {
auto l = getLock();
if (!index.isValid())
return QModelIndex();
TreeModelItemBase *c = getItem(index);
TreeModelItemBase *p = c->parent();
if (p == root || p == nullptr)
return QModelIndex();
return createIndex(static_cast<int>(p->row()), 0, p);
}
int TreeModelBase::rowCount(const QModelIndex &parent) const {
auto l = getLock();
if (parent.column() > 0)
return 0;
if (!parent.isValid()) {
if (root) {
return root->childCount();
} else {
return 0;
}
}
return getItem(parent)->childCount();
}
int TreeModelBase::columnCount(const QModelIndex &parent) const {
auto l = getLock();
if (parent.column() > 0)
return 0;
if (!parent.isValid()) {
if (root) {
return root->columnCount();
} else {
return 0;
}
}
return getItem(parent)->columnCount();
}
QVariant TreeModelBase::data(const QModelIndex &index, int role) const {
auto l = getLock();
if (!index.isValid())
return QVariant();
TreeModelItemBase *item = getItem(index);
return item->data(index.column(), static_cast<Qt::ItemDataRole>(role));
}
QVariant TreeModelBase::headerData(int section, Qt::Orientation orientation, int role) const {
auto l = getLock();
TreeModelRoot *rp = dynamic_cast<TreeModelRoot *>(root);
if (!rp)
return QVariant();
return rp->headerData(section, orientation, role);
}
Qt::ItemFlags TreeModelBase::flags(const QModelIndex &index) const {
auto l = getLock();
if (index.isValid())
return getItem(index)->flags();
return 0;
}
QModelIndex TreeModelBase::indexOf(TreeModelItemBase *item, int column) const {
auto l = getLock();
if (!item)
return QModelIndex();
return createIndex(static_cast<int>(item->row()), column, item);
}
QModelIndex TreeModelBase::parentOf(TreeModelItemBase *item, int column) const {
auto l = getLock();
if (!item)
return QModelIndex();
TreeModelItemBase *p = item->parent();
if (!p)
return QModelIndex();
return createIndex(static_cast<int>(item->row()), column, p);
}
void TreeModelBase::emitRowChaned(QModelIndex index) {
QModelIndex begin = createIndex(index.row(), 0, index.internalPointer());
QModelIndex end = createIndex(index.row(), columnCount(index), index.internalPointer());
emit dataChanged(begin, end);
}
void TreeModelBase::emitRowChaned(TreeModelItemBase *item) { emitRowChaned(indexOf(item)); }
| 27.386598
| 112
| 0.700546
|
epl-viz
|
304477779a928212c3fdb05b9b01e8ade699a97d
| 825
|
cpp
|
C++
|
src/lib/VSegEngine.cpp
|
ca1773130n/SLIC-DBSCAN-CUDA
|
c9b543a80377e33e71771dbaaf002d5345fc9a7d
|
[
"MIT"
] | 21
|
2018-10-24T10:07:46.000Z
|
2021-11-30T12:39:30.000Z
|
src/lib/VSegEngine.cpp
|
ca1773130n/SLIC-DBSCAN-CUDA
|
c9b543a80377e33e71771dbaaf002d5345fc9a7d
|
[
"MIT"
] | 3
|
2019-12-14T15:42:08.000Z
|
2020-03-18T02:08:53.000Z
|
src/lib/VSegEngine.cpp
|
ca1773130n/SLIC-DBSCAN-CUDA
|
c9b543a80377e33e71771dbaaf002d5345fc9a7d
|
[
"MIT"
] | 6
|
2019-05-23T02:57:41.000Z
|
2021-06-08T10:49:53.000Z
|
#include <sdbscan/VSegEngine.h>
namespace sdbscan {
VSegEngine::VSegEngine(const VSettings& inSettings) {
mSettings = inSettings;
}
VSegEngine::~VSegEngine() {
if (mSourceImg != NULL) delete mSourceImg;
if (mConvertedImg != NULL) delete mConvertedImg;
if (mIndexImg != NULL) delete mIndexImg;
if (mSpixelMap != NULL) delete mSpixelMap;
}
void VSegEngine::performSegmentation(UChar4Image* inputImg) {
mSourceImg->SetFrom(inputImg, ORUtils::MemoryBlock<Vector4u>::CPU_TO_CUDA);
convertImgSpace(mSourceImg, mConvertedImg, mSettings.mColorSpace);
initClusterCenters();
findCenterAssociation();
for (int i = 0; i < mSettings.mNumIteration; i++) {
updateClusterCenter();
findCenterAssociation();
}
if (mSettings.mForceConnectivity)
enforceConnectivity();
cudaThreadSynchronize();
}
}
| 25.78125
| 77
| 0.73697
|
ca1773130n
|
304f948b9db0ca524caef8138541e9d590a452e4
| 4,567
|
cc
|
C++
|
nvm/nvm_leaf_index.cc
|
yunxiao3/nvmsilkstore
|
41d12f6e50b71de5a951019f5d51240540c3de36
|
[
"BSD-3-Clause"
] | null | null | null |
nvm/nvm_leaf_index.cc
|
yunxiao3/nvmsilkstore
|
41d12f6e50b71de5a951019f5d51240540c3de36
|
[
"BSD-3-Clause"
] | null | null | null |
nvm/nvm_leaf_index.cc
|
yunxiao3/nvmsilkstore
|
41d12f6e50b71de5a951019f5d51240540c3de36
|
[
"BSD-3-Clause"
] | null | null | null |
#include <stdexcept>
#include "nvm_leaf_index.h"
#include "util/coding.h"
namespace leveldb {
namespace silkstore {
class NVMLeafIndexIterator: public Iterator {
public:
explicit NVMLeafIndexIterator(std::shared_ptr<kvdk::Iterator> iter){
iter_ = iter;
}
virtual bool Valid() const {
return iter_->Valid();
}
virtual void Seek(const Slice& k) {
iter_->Seek(k.ToString());
}
virtual void SeekToFirst() {
iter_->SeekToFirst();
}
virtual void SeekToLast() {
iter_->SeekToLast();
}
virtual void Next() {
iter_->Next();
}
virtual void Prev() {
iter_->Prev();
}
virtual Slice key() const {
return iter_->Key();
}
virtual Slice value() const {
return iter_->Value();
}
virtual Status status() const { return Status::OK(); }
private:
std::shared_ptr<kvdk::Iterator> iter_;
// No copying allowed
NVMLeafIndexIterator(const NVMLeafIndexIterator&);
void operator=(const NVMLeafIndexIterator&);
};
Iterator* NVMLeafIndex::NewIterator(const ReadOptions& options){
auto it = kv->NewSortedIterator("leafindex");
if (it == nullptr){
return NewEmptyIterator();
}
return new NVMLeafIndexIterator(it);
}
NVMLeafIndex::NVMLeafIndex(const Options& options, const std::string& dbname){
kvdk::Configs cfg;
cfg.pmem_segment_blocks = (1ull << 8);
cfg.hash_bucket_num = (1ull << 15);
printf("###### Need to set pmem_segment_blocks hash_bucket_num #####\n");
std::string engine_path;
if (options.leaf_index_path == nullptr){
printf("############# Using Default /mnt/NVMSilkstore/leafindex ##############\n");
engine_path = "/mnt/NVMSilkstore/leafindex";
}else{
engine_path = options.leaf_index_path;
}
if (options.leaf_index_size <= 0){
printf("############# Using Default leaf_index_size ##############\n");
cfg.pmem_file_size = 1280UL * 1024UL * 1024UL * 6;
}else{
std::cout << " set default size need to fix\n";
cfg.pmem_file_size = 1280UL * 1024UL * 1024UL * 6;
//s = cfg.put_size(options.leaf_index_size);
}
kvdk::Engine::Open(engine_path, &kv, cfg, stdout);
printf("############# Successfully opened a KVDK instance. ##############\n");
}
Status NVMLeafIndex::OpenLeafIndex(const Options& options,
const std::string& name,
DB** dbptr){
*dbptr = new NVMLeafIndex(options, name);
return Status::OK();
}
const Snapshot* NVMLeafIndex::GetSnapshot() {
throw std::runtime_error("NVMLeafIndex::GetSnapshot not supported");
}
void NVMLeafIndex::ReleaseSnapshot(const Snapshot* snapshot) {
throw std::runtime_error("NVMLeafIndex::ReleaseSnapshot not supported");
}
NVMLeafIndex::~NVMLeafIndex() {
if (kv != nullptr){
delete kv;
}
}
Status NVMLeafIndex::Write(const WriteOptions& options, WriteBatch* my_batch) {
//throw std::runtime_error("NVMLeafIndex::Write not supported");
mutex_.Lock();
Status status = WriteBatchInternal::InsertInto(my_batch, kv);
mutex_.Unlock();
return status;
}
Status NVMLeafIndex::Put(const WriteOptions& options,
const Slice& key,
const Slice& value) {
kvdk::Status s;
mutex_.Lock();
s = kv->SSet("leafindex",key.ToString(), value.ToString());
mutex_.Unlock();
if (s == kvdk::Status::Ok){
return Status::OK();
}
return Status::Corruption("");
}
Status NVMLeafIndex::Delete(const WriteOptions& options, const Slice& key) {
kvdk::Status s;
std::cout<<"Delete: " << key.ToString() << "\n";
s = kv->Delete(key.ToString());
if (s == kvdk::Status::Ok){
return Status::OK();
}
return Status::Corruption("");
}
Status NVMLeafIndex::Get(const ReadOptions &options,
const Slice &key,
std::string *value) {
kvdk::Status s;
mutex_.Lock();
s = kv->SGet("leafindex",key.ToString(), value);
mutex_.Unlock();
if (s == kvdk::Status::Ok){
return Status::OK();
}
return Status::Corruption("");
}
/* Iterator* NVMLeafIndex::NewIterator(const ReadOptions& options) {
throw std::runtime_error("NVMLeafIndex::NewIterator not supported");
} */
bool NVMLeafIndex::GetProperty(const Slice& property, std::string* value){
throw std::runtime_error("NVMLeafIndex::GetProperty not supported");
}
void NVMLeafIndex::GetApproximateSizes(const Range* range, int n, uint64_t* sizes) {
throw std::runtime_error("NVMLeafIndex::GetApproximateSizes not supported");
}
void NVMLeafIndex::CompactRange(const Slice* begin, const Slice* end) {
throw std::runtime_error("NVMLeafIndex::CompactRange not supported");
}
}
}
| 27.184524
| 85
| 0.6582
|
yunxiao3
|
305bc44dd32d4b52bd38ffb24612c797595216a6
| 1,179
|
cpp
|
C++
|
FangameReader/ColorFadeAnimator.cpp
|
TheBiob/DeadSplit
|
2e29bae2b86fa689ed9c28d345f2e8743b10c115
|
[
"MIT"
] | 3
|
2019-04-02T19:23:35.000Z
|
2021-04-30T03:57:15.000Z
|
FangameReader/ColorFadeAnimator.cpp
|
TheBiob/DeadSplit
|
2e29bae2b86fa689ed9c28d345f2e8743b10c115
|
[
"MIT"
] | 1
|
2018-07-10T22:34:41.000Z
|
2018-07-10T22:52:43.000Z
|
FangameReader/ColorFadeAnimator.cpp
|
TheBiob/DeadSplit
|
2e29bae2b86fa689ed9c28d345f2e8743b10c115
|
[
"MIT"
] | 3
|
2020-12-28T19:06:07.000Z
|
2021-01-30T10:09:56.000Z
|
#include <common.h>
#pragma hdrstop
#include <ColorFadeAnimator.h>
namespace Fangame {
CQuadInEasingFunction CColorFadeAnimator::inEasing;
CQuadOutEasingFunction CColorFadeAnimator::outEasing;
//////////////////////////////////////////////////////////////////////////
CColorFadeAnimator::CColorFadeAnimator( int _targetRow, CColor& target, double duration, DWORD currentTime, float _fadeAlpha ) :
targetRow( _targetRow ),
startTime( currentTime ),
startAlpha( target.A ),
durationMs( Round( duration * 1000.0 ) ),
fadeAlpha( CColor( 0.0f, 0.0f, 0.0f, _fadeAlpha ).A ),
targetColor( target )
{
SetInEasing();
}
void CColorFadeAnimator::AbortAnimation()
{
targetColor.A = fadeAlpha;
}
bool CColorFadeAnimator::UpdateAnimation( DWORD currentTime )
{
assert( currentEase != nullptr );
const auto timePassed = currentTime - startTime;
if( timePassed > durationMs ) {
AbortAnimation();
return true;
}
const auto weight = currentEase->GetTimeRatio( timePassed * 1.0f, durationMs * 1.0f );
targetColor.A = Lerp( startAlpha, fadeAlpha, weight );
return false;
}
//////////////////////////////////////////////////////////////////////////
} // namespace Fangame.
| 26.795455
| 128
| 0.651399
|
TheBiob
|
305d3a5a58f1422834594501437a0a1f031ef78d
| 6,884
|
c++
|
C++
|
thirdparty/glut/progs/inventor/glutduck.c++
|
ShiroixD/pag_zad_2
|
cdb6ccf48402cf4dbf1284827a4e281d3b12a64b
|
[
"MIT"
] | 1
|
2019-01-11T13:55:53.000Z
|
2019-01-11T13:55:53.000Z
|
thirdparty/glut/progs/inventor/glutduck.c++
|
ShiroixD/pag_zad_2
|
cdb6ccf48402cf4dbf1284827a4e281d3b12a64b
|
[
"MIT"
] | 1
|
2018-08-10T19:11:58.000Z
|
2018-08-10T19:12:17.000Z
|
thirdparty/glut/progs/inventor/glutduck.c++
|
ShiroixD/pag_zad_2
|
cdb6ccf48402cf4dbf1284827a4e281d3b12a64b
|
[
"MIT"
] | null | null | null |
/* Copyright (c) Mark J. Kilgard, 1994. */
/* This program is freely distributable without licensing fees
and is provided without guarantee or warrantee expressed or
implied. This program is -not- in the public domain. */
/*
* Copyright (c) 1991-94 Silicon Graphics, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that the name of Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SILICON GRAPHICS BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
* RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF THE
* POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* Based on an example from the Inventor Mentor chapter 13, example 5. */
#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <Inventor/SoDB.h>
#include <Inventor/SoInput.h>
#include <Inventor/SbViewportRegion.h>
#include <Inventor/nodes/SoSeparator.h>
#include <Inventor/actions/SoGLRenderAction.h>
#include <Inventor/nodes/SoCylinder.h>
#include <Inventor/nodes/SoDirectionalLight.h>
#include <Inventor/nodes/SoEventCallback.h>
#include <Inventor/nodes/SoMaterial.h>
#include <Inventor/nodes/SoPerspectiveCamera.h>
#include <Inventor/nodes/SoRotationXYZ.h>
#include <Inventor/nodes/SoTransform.h>
#include <Inventor/nodes/SoTranslation.h>
/* Some <math.h> files do not define M_PI... */
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
int W = 300, H = 300;
int spinning = 0;
GLubyte *image = NULL;
SoSeparator *root;
SoRotationXYZ *duckRotXYZ;
float angle = 0.0;
int moving = 0;
int begin;
void
reshape(int w, int h)
{
glViewport(0, 0, w, h);
W = w;
H = h;
if (image)
free(image);
image = (GLubyte *) malloc(W * H * 3);
}
void
renderScene(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
SbViewportRegion myViewport(W, H);
SoGLRenderAction myRenderAction(myViewport);
myRenderAction.apply(root);
}
void
redraw(void)
{
renderScene();
glutSwapBuffers();
}
int
duckScene(void)
{
root = new SoSeparator;
root->ref();
// Add a camera and light
SoPerspectiveCamera *myCamera = new SoPerspectiveCamera;
myCamera->position.setValue(0., -4., 8.0);
myCamera->heightAngle = M_PI/2.5;
myCamera->nearDistance = 1.0;
myCamera->farDistance = 15.0;
root->addChild(myCamera);
root->addChild(new SoDirectionalLight);
// Rotate scene slightly to get better view
SoRotationXYZ *globalRotXYZ = new SoRotationXYZ;
globalRotXYZ->axis = SoRotationXYZ::X;
globalRotXYZ->angle = M_PI/9;
root->addChild(globalRotXYZ);
// Pond group
SoSeparator *pond = new SoSeparator;
root->addChild(pond);
SoMaterial *cylMaterial = new SoMaterial;
cylMaterial->diffuseColor.setValue(0., 0.3, 0.8);
pond->addChild(cylMaterial);
SoTranslation *cylTranslation = new SoTranslation;
cylTranslation->translation.setValue(0., -6.725, 0.);
pond->addChild(cylTranslation);
SoCylinder *myCylinder = new SoCylinder;
myCylinder->radius.setValue(4.0);
myCylinder->height.setValue(0.5);
pond->addChild(myCylinder);
// Duck group
SoSeparator *duck = new SoSeparator;
root->addChild(duck);
// Read the duck object from a file and add to the group
SoInput myInput;
if (!myInput.openFile("duck.iv")) {
if (!myInput.openFile("/usr/share/src/Inventor/examples/data/duck.iv")) {
return 1;
}
}
SoSeparator *duckObject = SoDB::readAll(&myInput);
if (duckObject == NULL) return 1;
// Set up the duck transformations
duckRotXYZ = new SoRotationXYZ;
duck->addChild(duckRotXYZ);
duckRotXYZ->angle = angle;
duckRotXYZ->axis = SoRotationXYZ::Y; // rotate about Y axis
SoTransform *initialTransform = new SoTransform;
initialTransform->translation.setValue(0., 0., 3.);
initialTransform->scaleFactor.setValue(6., 6., 6.);
duck->addChild(initialTransform);
duck->addChild(duckObject);
return 0;
}
void
updateModels(void)
{
duckRotXYZ->angle = angle;
glutPostRedisplay();
}
void
animate(void)
{
angle += 0.1;
updateModels();
}
void
setAnimation(int enable)
{
if(enable) {
spinning = 1;
glutIdleFunc(animate);
} else {
spinning = 0;
glutIdleFunc(NULL);
glutPostRedisplay();
}
}
/* ARGSUSED */
void
keyboard(unsigned char ch, int x, int y)
{
if(ch == ' ') {
setAnimation(0);
animate();
}
}
void
menuSelect(int item)
{
switch(item) {
case 1:
animate();
break;
case 2:
if(!spinning) {
setAnimation(1);
} else {
setAnimation(0);
}
break;
#ifdef GL_MULTISAMPLE_SGIS
case 3:
if(glIsEnabled(GL_MULTISAMPLE_SGIS)) {
glDisable(GL_MULTISAMPLE_SGIS);
} else {
glEnable(GL_MULTISAMPLE_SGIS);
}
glutPostRedisplay();
break;
#endif
}
}
void
vis(int visible)
{
if (visible == GLUT_VISIBLE) {
if (spinning)
glutIdleFunc(animate);
} else {
if (spinning)
glutIdleFunc(NULL);
}
}
/* ARGSUSED */
void
mouse(int button, int state, int x, int y)
{
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
setAnimation(0);
moving = 1;
begin = x;
}
if (button == GLUT_LEFT_BUTTON && state == GLUT_UP) {
moving = 0;
glutPostRedisplay();
}
}
/* ARGSUSED */
void
motion(int x, int y)
{
if (moving) {
angle = angle + .01 * (x - begin);
begin = x;
updateModels();
}
}
int
main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE);
SoDB::init();
if(duckScene()) {
fprintf(stderr, "couldn't read IV file\n");
exit(1);
}
glutInitWindowSize(W, H);
glutCreateWindow("GLUT Inventor Duck Pond");
glutDisplayFunc(redraw);
glutReshapeFunc(reshape);
glutCreateMenu(menuSelect);
glutAddMenuEntry("Step", 1);
glutAddMenuEntry("Toggle animation", 2);
if(glutGet(GLUT_WINDOW_NUM_SAMPLES) > 0) {
glutAddMenuEntry("Toggle multisampling", 3);
}
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutKeyboardFunc(keyboard);
glutMouseFunc(mouse);
glutMotionFunc(motion);
glutVisibilityFunc(vis);
glEnable(GL_DEPTH_TEST);
glClearColor(0.132, 0.542, 0.132, 1.0);
glutMainLoop();
return 0; /* ANSI C requires main to return int. */
}
| 23.656357
| 79
| 0.684631
|
ShiroixD
|
3068223a022e6743babbd188fb5a676f6730e957
| 447
|
hpp
|
C++
|
tools/material_munge/src/describe_material.hpp
|
SleepKiller/shaderpatch
|
4bda848df0273993c96f1d20a2cf79161088a77d
|
[
"MIT"
] | 13
|
2019-03-25T09:40:12.000Z
|
2022-03-13T16:12:39.000Z
|
tools/material_munge/src/describe_material.hpp
|
SleepKiller/shaderpatch
|
4bda848df0273993c96f1d20a2cf79161088a77d
|
[
"MIT"
] | 110
|
2018-10-16T09:05:43.000Z
|
2022-03-16T23:32:28.000Z
|
tools/material_munge/src/describe_material.hpp
|
SleepKiller/swbfii-shaderpatch
|
b49ce3349d4dd09b19237ff4766652166ba1ffd4
|
[
"MIT"
] | 1
|
2020-02-06T20:32:50.000Z
|
2020-02-06T20:32:50.000Z
|
#pragma once
#include "material_options.hpp"
#include "patch_material_io.hpp"
#pragma warning(push)
#pragma warning(disable : 4996)
#pragma warning(disable : 4127)
#include <yaml-cpp/yaml.h>
#pragma warning(pop)
namespace sp {
auto describe_material(const std::string_view name,
const YAML::Node& description, const YAML::Node& material,
Material_options& material_options) -> Material_config;
}
| 23.526316
| 81
| 0.693512
|
SleepKiller
|
30689d076d4f026e3c067e58ebff2f48865527c2
| 5,327
|
hpp
|
C++
|
src/competitiveProgramming/headers/competitive/programming/graph/Graph.hpp
|
dareagle/competitive-programming
|
4f92a09592b8e0cb4cbcc530681721a728902908
|
[
"Apache-2.0"
] | 160
|
2016-05-27T14:26:38.000Z
|
2022-03-06T19:30:00.000Z
|
src/competitiveProgramming/headers/competitive/programming/graph/Graph.hpp
|
dareagle/competitive-programming
|
4f92a09592b8e0cb4cbcc530681721a728902908
|
[
"Apache-2.0"
] | 7
|
2016-06-26T16:01:43.000Z
|
2019-06-15T21:00:10.000Z
|
src/competitiveProgramming/headers/competitive/programming/graph/Graph.hpp
|
dareagle/competitive-programming
|
4f92a09592b8e0cb4cbcc530681721a728902908
|
[
"Apache-2.0"
] | 40
|
2016-06-28T11:06:13.000Z
|
2021-12-01T14:48:28.000Z
|
#ifndef _GRAPH_GRAPH_INCLUDED
#define _GRAPH_GRAPH_INCLUDED
/**
* @author Manwe
*
* class that models a graph and allows to scan it in order to produce
* various results (just using <a
* href="https://en.wikipedia.org/wiki/Breadth-first_search">BFS</a> for
* now) Graph can be directed or bi directional
*
* Hint: you can use this graph implementation to: compute easily
* distances from anywhere to one or several targets. Heat map
* constructions Voronoi territory constructions etc
*
* for optimization reasons, results are produced as a vector of values
* (int or double) and by convention the relation between the result and
* the node is by index
*
* @param <N>
* The class representing a node in the graph.
*/
#include <functional>
#include <stdexcept>
#include <vector>
#include <set>
namespace competitive{
namespace programming{
namespace graph{
template<typename N>
class Graph {
public:
/**
* Graph constructor
*
* Conventions: the nodes you give are in N*. They are identified by
* their index in this vector meaning that the links source and destination
* you provide indicates the index of the node in this vector. Code will clearly crash if you
* make a mistake and provides indexes on which there is no items at nodes[index]
*
* @param nodes
* the vector of nodes that does exists in the graph
* @param linksSource
* the vector of index of the source nodes
* @param linksDestination
* the vector of index of the destination nodes
* @param directed
* if true will consider the links you give are directed. It
* means you can only go from the source node to the destination
* node but not the contrary
* @throws std::exception
* if there is not the same number of indexes between source and
* destination
*/
Graph(const std::vector<N>& nodes, const std::vector<int>& linksSource, const std::vector<int>& linksDestination, bool directed): m_nodes(nodes), m_neighboursIndexes(nodes.size(), std::vector<int>()) {
if (linksSource.size() != linksDestination.size())
throw std::length_error("Number of links source and destination provided does not match!");
for (int i = 0; i < linksSource.size(); i++) {
int sourceIndex = linksSource[i];
int destinationIndex = linksDestination[i];
createLink(sourceIndex, destinationIndex);
if (!directed) {
createLink(destinationIndex, sourceIndex);
}
}
}
/**
* Breadth-first search implementation on your graph.
*
* It will iteratively:
* - assign current level value to all source nodes
* - scan source nodes neighbor to find the reachable nodes that have not been reached yet
* - Compute next level value and consider all the reachable neighbors as the new source nodes
*
* @param intialValue
* The value that will be assigned to all nodes before starting the BFS
* Hint: giving a value impossible to reach can allow you to identify which nodes have never been reached
* @param firstValue
* The value that will be assigned to all the nodes in sources
* @param canBeVisited
* Determines if a node should be considered in the BFS or simply ignored
* @param nextValueIterator
* Give the next level value from the current level value. Add 1 to compute distances
* @param sources
* The list of nodes that will receive the first value
* @return
* a vector with the values of each node. The index in this vector correspond to the index of the node given during the constructor
*/
template <typename T>
std::vector<T> breadthFirstSearch(
const T& initialValue,
const T& firstValue,
std::function<bool(const N&)> canBeVisited,
std::function<T(const T&, int)> nextValueIterator,
const std::vector<int>& sourcesIndex
) {
std::vector<T> results(m_nodes.size(), initialValue);
std::vector<bool> alreadyScanned(m_nodes.size(), false);
std::set<int> currentNodesIndex(sourcesIndex.begin(), sourcesIndex.end());
iterativeBreadthFirstSearch<T>(results, alreadyScanned, currentNodesIndex, firstValue, 0, canBeVisited, nextValueIterator);
return results;
}
private:
template<typename T>
void iterativeBreadthFirstSearch(std::vector<T>& results, std::vector<bool>& alreadyScanned, std::set<int>& currentNodes, const T& value, int iteration,
std::function<bool (const N&)> canBeVisited,
std::function<T(const T&, int)> nextValueIterator) {
std::set<int> nextNodes;
for (int index : currentNodes) {
if (!alreadyScanned[index]) {
alreadyScanned[index] = true;
if (canBeVisited(m_nodes[index])) {
results[index] = value;
nextNodes.insert(m_neighboursIndexes[index].begin(), m_neighboursIndexes[index].end());
}
}
}
if (!nextNodes.empty()) {
iterativeBreadthFirstSearch(results, alreadyScanned, nextNodes, nextValueIterator(value, iteration + 1), iteration + 1,
canBeVisited, nextValueIterator);
}
}
void createLink(int sourceIndex, int destinationIndex) {
m_neighboursIndexes[sourceIndex].push_back(destinationIndex);
}
private:
const std::vector<N>& m_nodes;
std::vector<std::vector<int> > m_neighboursIndexes;
};
}}}
#endif
| 36.737931
| 203
| 0.697203
|
dareagle
|
3070e179768c73cd626c3f651e0cbd649b275d5c
| 2,040
|
cpp
|
C++
|
src/midi-chrono/DigitPanel.cpp
|
nkshigeru/crossmidi
|
5f4bf348853cd9362d7dbd02349289ab49e6ac08
|
[
"MIT"
] | null | null | null |
src/midi-chrono/DigitPanel.cpp
|
nkshigeru/crossmidi
|
5f4bf348853cd9362d7dbd02349289ab49e6ac08
|
[
"MIT"
] | null | null | null |
src/midi-chrono/DigitPanel.cpp
|
nkshigeru/crossmidi
|
5f4bf348853cd9362d7dbd02349289ab49e6ac08
|
[
"MIT"
] | null | null | null |
#include "DigitPanel.h"
wxBEGIN_EVENT_TABLE(DigitPanel, wxWindow)
EVT_PAINT(DigitPanel::OnPaint)
EVT_SET_FOCUS(DigitPanel::OnSetFocus)
EVT_KILL_FOCUS(DigitPanel::OnKillFocus)
EVT_CHAR(DigitPanel::OnChar)
wxEND_EVENT_TABLE()
static const wxColour BackgroundColor(60, 60, 60);
static const wxColour ForegroundColor(255, 255, 255);
static const wxColour FocusColor(39, 179, 238);
DigitPanel::DigitPanel(wxWindow* parent, wxWindowID id)
: wxWindow(parent, id, wxDefaultPosition, parent->FromDIP(wxSize(15, 30)), wxFULL_REPAINT_ON_RESIZE), m_value(-1)
{
SetBackgroundStyle(wxBG_STYLE_PAINT);
wxFont display_font(FromDIP(wxSize(15, 30)), wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL);
SetFont(display_font);
}
DigitPanel::~DigitPanel()
{
}
void DigitPanel::SetValue(int value)
{
if (m_value != value)
{
m_value = value;
Refresh();
}
}
int DigitPanel::GetValue() const
{
return m_value;
}
void DigitPanel::OnPaint(wxPaintEvent&)
{
wxPaintDC dc(this);
wxSize size(dc.GetSize());
if (HasFocus())
{
dc.SetPen(wxPen(FocusColor, 1));
}
else
{
dc.SetPen(*wxTRANSPARENT_PEN);
}
dc.SetBrush(BackgroundColor);
dc.DrawRectangle(size);
dc.SetTextForeground(*wxWHITE);
if (0 <= m_value && m_value < 10)
{
dc.DrawLabel(wxString::Format(wxT("%d"), m_value), size, wxALIGN_CENTER);
}
}
void DigitPanel::OnSetFocus(wxFocusEvent& evt)
{
Refresh(true);
evt.Skip();
}
void DigitPanel::OnKillFocus(wxFocusEvent& evt)
{
Refresh(true);
evt.Skip();
}
void DigitPanel::OnChar(wxKeyEvent& evt)
{
wxChar c = evt.GetUnicodeKey();
int v;
switch (c)
{
case L'0':
v = 0;
break;
case L'1':
v = 1;
break;
case L'2':
v = 2;
break;
case L'3':
v = 3;
break;
case L'4':
v = 4;
break;
case L'5':
v = 5;
break;
case L'6':
v = 6;
break;
case L'7':
v = 7;
break;
case L'8':
v = 8;
break;
case L'9':
v = 9;
break;
default:
v = -1;
}
if (v >= 0)
{
wxCommandEvent cmd(wxEVT_TEXT, GetId());
cmd.SetString(c);
cmd.SetInt(v);
wxPostEvent(this, cmd);
}
}
| 16.721311
| 114
| 0.677941
|
nkshigeru
|
3071701e8abe277941855f000c4ee0a042d16a52
| 221
|
cpp
|
C++
|
components/compiler/nullerrorhandler.cpp
|
Bodillium/openmw
|
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
|
[
"Unlicense"
] | null | null | null |
components/compiler/nullerrorhandler.cpp
|
Bodillium/openmw
|
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
|
[
"Unlicense"
] | null | null | null |
components/compiler/nullerrorhandler.cpp
|
Bodillium/openmw
|
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
|
[
"Unlicense"
] | null | null | null |
#include "nullerrorhandler.hpp"
void Compiler::NullErrorHandler::report (const std::string& message, const TokenLoc& loc, Type type) {}
void Compiler::NullErrorHandler::report (const std::string& message, Type type) {}
| 36.833333
| 103
| 0.760181
|
Bodillium
|
307337815be30d94d1f20881c1ce7c5d136d7d0a
| 3,666
|
cpp
|
C++
|
Soomla/gates/CCWorldCompletionGate.cpp
|
markpetersen01/Cocos2D-game
|
93e12850f3ecdfbda9c1ce60792b8e7b1c2bd4b8
|
[
"Apache-2.0"
] | 14
|
2015-01-29T10:39:08.000Z
|
2019-05-09T09:30:58.000Z
|
Soomla/gates/CCWorldCompletionGate.cpp
|
markpetersen01/Cocos2D-game
|
93e12850f3ecdfbda9c1ce60792b8e7b1c2bd4b8
|
[
"Apache-2.0"
] | 10
|
2015-02-09T07:48:33.000Z
|
2017-03-17T10:24:20.000Z
|
Soomla/gates/CCWorldCompletionGate.cpp
|
markpetersen01/Cocos2D-game
|
93e12850f3ecdfbda9c1ce60792b8e7b1c2bd4b8
|
[
"Apache-2.0"
] | 13
|
2015-02-09T01:28:08.000Z
|
2019-09-05T07:31:12.000Z
|
/*
Copyright (C) 2012-2014 Soomla Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "CCWorldCompletionGate.h"
#include "CCStoreEventDispatcher.h"
#include "CCStoreInventory.h"
#include "CCSoomlaUtils.h"
#include "CCLevelUpEventDispatcher.h"
#include "CCWorld.h"
#include "CCSoomlaLevelUp.h"
namespace soomla {
USING_NS_CC;
#define TAG "SOOMLA WorldCompletionGate"
CCWorldCompletionGate *CCWorldCompletionGate::create(cocos2d::__String *id, cocos2d::__String *associatedWorldId) {
CCWorldCompletionGate *ret = new CCWorldCompletionGate();
if (ret->init(id, associatedWorldId)) {
ret->autorelease();
}
else {
CC_SAFE_DELETE(ret);
}
return ret;
}
bool CCWorldCompletionGate::init(cocos2d::__String *id, cocos2d::__String *associatedWorldId) {
bool result = CCGate::init(id, NULL);
if (result) {
setAssociatedWorldId(associatedWorldId);
return true;
}
return result;
}
bool CCWorldCompletionGate::initWithDictionary(cocos2d::__Dictionary *dict) {
bool result = CCGate::initWithDictionary(dict);
if (result) {
fillAssociatedWorldIdFromDict(dict);
return true;
}
return result;
}
const char *CCWorldCompletionGate::getType() const {
return CCLevelUpConsts::JSON_JSON_TYPE_WORLD_COMPLETION_GATE;
}
cocos2d::__Dictionary *CCWorldCompletionGate::toDictionary() {
cocos2d::__Dictionary *dict = CCGate::toDictionary();
putAssociatedWorldIdToDict(dict);
return dict;
}
CCWorldCompletionGate::~CCWorldCompletionGate() {
CC_SAFE_RELEASE(mAssociatedWorldId);
}
void CCWorldCompletionGate::registerEvents() {
if (!isOpen()) {
setEventListener(Director::getInstance()->getEventDispatcher()->addCustomEventListener(CCLevelUpConsts::EVENT_WORLD_COMPLETED,
CC_CALLBACK_1(CCWorldCompletionGate::onWorldCompleted, this)));
}
}
void CCWorldCompletionGate::unregisterEvents() {
if (mEventListener) {
Director::getInstance()->getEventDispatcher()->removeEventListener(mEventListener);
setEventListener(NULL);
}
}
bool CCWorldCompletionGate::canOpenInner() {
CCWorld *world = CCSoomlaLevelUp::getInstance()->getWorld(mAssociatedWorldId->getCString());
return world != NULL && world->isCompleted();
}
bool CCWorldCompletionGate::openInner() {
if (canOpen()) {
forceOpen(true);
return true;
}
return false;
}
void CCWorldCompletionGate::onWorldCompleted(cocos2d::EventCustom *event) {
__Dictionary *eventData = (__Dictionary *)event->getUserData();
CCWorld *world = dynamic_cast<CCWorld *>(eventData->objectForKey(CCLevelUpConsts::DICT_ELEMENT_WORLD));
CC_ASSERT(world);
if (world->getId()->compare(mAssociatedWorldId->getCString()) == 0) {
forceOpen(true);
}
}
}
| 31.603448
| 161
| 0.651937
|
markpetersen01
|
3075ae8bd122c717b012469c3986946244fe2b93
| 61
|
cpp
|
C++
|
src/core/Zobrist.cpp
|
AlexKent3141/OnePunchGo
|
a86caaf421c8122222f72316171702617c519d28
|
[
"MIT"
] | 3
|
2018-05-14T12:32:19.000Z
|
2021-04-20T23:11:56.000Z
|
src/core/Zobrist.cpp
|
AlexKent3141/OnePunchGo
|
a86caaf421c8122222f72316171702617c519d28
|
[
"MIT"
] | 1
|
2018-03-30T18:44:49.000Z
|
2018-03-31T15:57:49.000Z
|
src/core/Zobrist.cpp
|
AlexKent3141/OnePunchGo
|
a86caaf421c8122222f72316171702617c519d28
|
[
"MIT"
] | null | null | null |
#include "Zobrist.h"
Zobrist* Zobrist::_instance = nullptr;
| 15.25
| 38
| 0.737705
|
AlexKent3141
|
30809a69e3f1c678ef802e3c0447131ca0a736bd
| 11,634
|
hpp
|
C++
|
agency/future/always_ready_future.hpp
|
nerikhman/agency
|
966ac59101f2fc3561a86b11874fbe8de361d0e4
|
[
"BSD-3-Clause"
] | 129
|
2016-08-18T23:24:15.000Z
|
2022-03-25T12:06:05.000Z
|
agency/future/always_ready_future.hpp
|
nerikhman/agency
|
966ac59101f2fc3561a86b11874fbe8de361d0e4
|
[
"BSD-3-Clause"
] | 86
|
2016-08-19T03:43:33.000Z
|
2020-07-20T14:27:41.000Z
|
agency/future/always_ready_future.hpp
|
nerikhman/agency
|
966ac59101f2fc3561a86b11874fbe8de361d0e4
|
[
"BSD-3-Clause"
] | 23
|
2016-08-18T23:52:13.000Z
|
2022-02-28T16:28:20.000Z
|
#pragma once
#include <agency/detail/config.hpp>
#include <agency/detail/requires.hpp>
#include <agency/detail/type_traits.hpp>
#include <agency/detail/utility.hpp>
#include <agency/experimental/variant.hpp>
#include <agency/experimental/optional.hpp>
#include <agency/future/future_traits/is_future.hpp>
#include <agency/future/future_traits/future_result.hpp>
#include <agency/detail/terminate.hpp>
#include <exception>
#include <type_traits>
#include <future>
namespace agency
{
// declare always_ready_future for detail::always_ready_then below
template<class T>
class always_ready_future;
namespace detail
{
// declare always_ready_then_and_leave() for always_ready_future::then() below
template<class T, class Function>
__AGENCY_ANNOTATION
always_ready_future<detail::result_of_t<Function&&(T&)>>
always_ready_then_and_leave_valid(always_ready_future<T>& future, Function&& f);
template<class Function>
__AGENCY_ANNOTATION
always_ready_future<detail::result_of_t<Function&&()>>
always_ready_then_and_leave_valid(always_ready_future<void>& future, Function&& f);
} // end detail
// always_ready_future is a future that is created in a ready state
// this type of future is always ready as long as it is valid
//
// Executors which always block their client can use always_ready_future as their
// associated future and still expose two-way asynchronous execution functions like twoway_execute()
template<class T>
class always_ready_future
{
public:
// Default constructor creates an invalid always_ready_future
// Postcondition: !valid()
always_ready_future() = default;
__AGENCY_ANNOTATION
always_ready_future(const T& value) : state_(value) {}
__AGENCY_ANNOTATION
always_ready_future(T&& value) : state_(std::move(value)) {}
__AGENCY_ANNOTATION
always_ready_future(std::exception_ptr e) : state_(e) {}
__AGENCY_ANNOTATION
always_ready_future(always_ready_future&& other)
: state_()
{
detail::adl_swap(state_, other.state_);
}
// converting move constructor waits on the given future and moves its result into *this
// postcondition: !other.valid()
__agency_exec_check_disable__
template<class Future,
__AGENCY_REQUIRES(is_future<detail::decay_t<Future>>::value),
__AGENCY_REQUIRES(std::is_constructible<T, future_result_t<detail::decay_t<Future>>&&>::value)
>
__AGENCY_ANNOTATION
always_ready_future(Future&& other)
: always_ready_future(other.get())
{
// XXX this implementation doesn't correctly handle exceptional other
}
__AGENCY_ANNOTATION
always_ready_future& operator=(always_ready_future&& other)
{
state_.reset();
detail::adl_swap(state_, other.state_);
return *this;
}
__agency_exec_check_disable__
template<class Future,
__AGENCY_REQUIRES(is_future<detail::decay_t<Future>>::value),
__AGENCY_REQUIRES(std::is_constructible<T, future_result_t<detail::decay_t<Future>>&&>::value)
>
__AGENCY_ANNOTATION
always_ready_future& operator=(Future&& other)
{
return operator=(always_ready_future{std::move(other)});
}
template<class U,
__AGENCY_REQUIRES(
std::is_constructible<T,U&&>::value
)>
__AGENCY_ANNOTATION
static always_ready_future make_ready(U&& value)
{
return always_ready_future(std::forward<U>(value));
}
__AGENCY_ANNOTATION
constexpr static bool is_ready()
{
return true;
}
private:
struct get_ptr_visitor
{
__AGENCY_ANNOTATION
T* operator()(T& result) const
{
return &result;
}
__AGENCY_ANNOTATION
T* operator()(std::exception_ptr& e) const
{
#ifndef __CUDA_ARCH__
std::rethrow_exception(e);
#else
detail::terminate_with_message("always_ready_future::get_ref(): error: exceptional future");
#endif
return nullptr;
}
};
public:
__AGENCY_ANNOTATION
T& get_ref()
{
if(!valid())
{
#ifndef __CUDA_ARCH__
throw std::future_error(std::future_errc::no_state);
#else
detail::terminate_with_message("always_ready_future::get_ref(): error: no state");
#endif
}
return *experimental::visit(get_ptr_visitor(), *state_);
}
__AGENCY_ANNOTATION
T get()
{
T result = std::move(get_ref());
invalidate();
return result;
}
__AGENCY_ANNOTATION
void wait() const
{
// wait() is a no-op: *this is always ready
}
__AGENCY_ANNOTATION
bool valid() const
{
return state_.has_value();
}
template<class Function>
__AGENCY_ANNOTATION
always_ready_future<detail::result_of_t<detail::decay_t<Function>(T&)>>
then_and_leave_valid(Function&& f)
{
return detail::always_ready_then_and_leave_valid(*this, std::forward<Function>(f));
}
template<class Function>
__AGENCY_ANNOTATION
always_ready_future<detail::result_of_t<detail::decay_t<Function>(T&)>>
then(Function&& f)
{
auto result = then_and_leave_valid(std::forward<Function>(f));
invalidate();
return result;
}
private:
__AGENCY_ANNOTATION
void invalidate()
{
state_ = experimental::nullopt;
}
experimental::optional<experimental::variant<T,std::exception_ptr>> state_;
};
template<>
class always_ready_future<void>
{
public:
// XXX the default constructor creates a ready, valid future, but we may wish
// to redefine the default constructor to create an invalid future
// in such a scheme, we would need to distinguish another constructor for
// creating a ready (void) result.
// We could create an emplacing constructor distinguished with an in_place_t parameter
__AGENCY_ANNOTATION
always_ready_future() : valid_(true) {}
always_ready_future(std::exception_ptr e) : exception_(e), valid_(true) {}
__AGENCY_ANNOTATION
always_ready_future(always_ready_future&& other)
: exception_(), valid_(false)
{
detail::adl_swap(exception_, other.exception_);
detail::adl_swap(valid_, other.valid_);
}
// converting constructor waits on and invalidates the given future
__agency_exec_check_disable__
template<class Future,
__AGENCY_REQUIRES(is_future<detail::decay_t<Future>>::value),
__AGENCY_REQUIRES(std::is_void<future_result_t<detail::decay_t<Future>>>::value)
>
__AGENCY_ANNOTATION
always_ready_future(Future&& other)
: always_ready_future()
{
// XXX this implementation doesn't correctly handle exceptional other
other.get();
}
__AGENCY_ANNOTATION
always_ready_future& operator=(always_ready_future&& other)
{
exception_.reset();
valid_ = false;
detail::adl_swap(exception_, other.exception_);
detail::adl_swap(valid_, other.valid_);
return *this;
}
// converting assignment operator waits on the given future
__agency_exec_check_disable__
template<class Future,
__AGENCY_REQUIRES(is_future<detail::decay_t<Future>>::value),
__AGENCY_REQUIRES(std::is_void<future_result_t<detail::decay_t<Future>>>::value)
>
__AGENCY_ANNOTATION
always_ready_future& operator=(Future&& other)
{
return operator=(always_ready_future{std::move(other)});
}
__AGENCY_ANNOTATION
constexpr static bool is_ready()
{
return true;
}
__AGENCY_ANNOTATION
static always_ready_future make_ready()
{
return always_ready_future();
}
public:
__AGENCY_ANNOTATION
void get()
{
if(!valid())
{
#ifndef __CUDA_ARCH__
throw std::future_error(std::future_errc::no_state);
#else
detail::terminate_with_message("always_ready_future::get(): error: no state");
#endif
}
invalidate();
if(exception_)
{
#ifndef __CUDA_ARCH__
std::rethrow_exception(exception_.value());
#else
detail::terminate_with_message("always_ready_future::get(): error: exceptional future");
#endif
}
}
__AGENCY_ANNOTATION
void wait() const
{
// wait() is a no-op: this is always ready
}
__AGENCY_ANNOTATION
bool valid() const
{
return valid_;
}
template<class Function>
__AGENCY_ANNOTATION
always_ready_future<detail::result_of_t<detail::decay_t<Function>()>>
then_and_leave_valid(Function&& f)
{
return detail::always_ready_then_and_leave_valid(*this, std::forward<Function>(f));
}
template<class Function>
__AGENCY_ANNOTATION
always_ready_future<detail::result_of_t<detail::decay_t<Function>()>>
then(Function&& f)
{
auto result = then_and_leave_valid(std::forward<Function>(f));
invalidate();
return result;
}
private:
__AGENCY_ANNOTATION
void invalidate()
{
valid_ = false;
}
experimental::optional<std::exception_ptr> exception_;
bool valid_;
};
template<class T>
__AGENCY_ANNOTATION
always_ready_future<detail::decay_t<T>> make_always_ready_future(T&& value)
{
return always_ready_future<detail::decay_t<T>>(std::forward<T>(value));
}
__AGENCY_ANNOTATION
inline always_ready_future<void> make_always_ready_future()
{
return always_ready_future<void>();
}
template<class T>
always_ready_future<T> make_always_ready_exceptional_future(std::exception_ptr e)
{
return always_ready_future<T>(e);
}
__agency_exec_check_disable__
template<class Function,
class... Args,
__AGENCY_REQUIRES(
!std::is_void<detail::result_of_t<Function&&(Args&&...)>>::value
)>
__AGENCY_ANNOTATION
always_ready_future<
detail::result_of_t<Function&&(Args&&...)>
>
try_make_always_ready_future(Function&& f, Args&&... args)
{
#ifndef __CUDA_ARCH__
try
{
return make_always_ready_future(std::forward<Function>(f)(std::forward<Args>(args)...));
}
catch(...)
{
using result_type = detail::result_of_t<Function&&(Args&&...)>;
return make_always_ready_exceptional_future<result_type>(std::current_exception());
}
#else
return make_always_ready_future(std::forward<Function>(f)(std::forward<Args>(args)...));
#endif
}
__agency_exec_check_disable__
template<class Function,
class... Args,
__AGENCY_REQUIRES(
std::is_void<detail::result_of_t<Function&&(Args&&...)>>::value
)>
__AGENCY_ANNOTATION
always_ready_future<void> try_make_always_ready_future(Function&& f, Args&&... args)
{
#ifndef __CUDA_ARCH__
try
{
std::forward<Function>(f)(std::forward<Args>(args)...);
return make_always_ready_future();
}
catch(...)
{
return make_always_ready_exceptional_future<void>(std::current_exception());
}
#else
std::forward<Function>(f)(std::forward<Args>(args)...);
return make_always_ready_future();
#endif
}
namespace detail
{
template<class T, class Function>
__AGENCY_ANNOTATION
always_ready_future<detail::result_of_t<Function&&(T&)>>
always_ready_then_and_leave_valid(always_ready_future<T>& future, Function&& f)
{
T& argument = future.get_ref();
return agency::try_make_always_ready_future(std::forward<Function>(f), argument);
}
template<class Function>
__AGENCY_ANNOTATION
always_ready_future<detail::result_of_t<Function&&()>>
always_ready_then_and_leave_valid(always_ready_future<void>& future, Function&& f)
{
return agency::try_make_always_ready_future(std::forward<Function>(f));
}
} // end detail
} // end agency
| 25.625551
| 107
| 0.690562
|
nerikhman
|
3081591279821cde49ee9c31d28dea4cdeab86c1
| 4,992
|
cpp
|
C++
|
test_task_leisure_time.cpp
|
yecharlie/tk
|
8157a393c1d9840793eb41098cb6e03cba6e4f54
|
[
"MIT"
] | null | null | null |
test_task_leisure_time.cpp
|
yecharlie/tk
|
8157a393c1d9840793eb41098cb6e03cba6e4f54
|
[
"MIT"
] | null | null | null |
test_task_leisure_time.cpp
|
yecharlie/tk
|
8157a393c1d9840793eb41098cb6e03cba6e4f54
|
[
"MIT"
] | null | null | null |
#include "tk.h"
#include <cstdlib> // rand()
#include <vector>
#include <sstream>
#include <fstream>
class customer;
class producer;
const int MIN_REQ_SEEDS = 300;
struct seeds : public tk::object
{
int count;
int pending() {return count == 0;}
void put(int n) {if ((count += n) == n) alert();}
int take() {
if (!count) return 0;
else {count--; return 1;}
}
};
class producer : public tk::task
{
friend class logger;
private:
static int allprd;
int nprd;
seeds* sp;
void routine();
public:
static std::vector<producer*> pvec;
producer(const char* n, seeds* ss) : sp(ss), task(n) {pvec.push_back(this);}
~producer() {if (pvec.empty()) delete sp;}
};
int producer::allprd = 0;
std::vector<producer*> producer::pvec;
class customer : public tk::task
{
friend class logger;
private:
int ncus;
seeds* sp;
int modest();
void acknowledge() {alert();}
void routine();
public:
static std::vector<customer*> cvec;
customer(const char* n, int interv, seeds* ss) : task(n), interval(interv),sp(ss) {cvec.push_back(this);}
~customer() {sp->forget(this);}
int interval;
};
std::vector<customer*> customer::cvec;
class logger : public tk::task
{
std::list<std::string>* data;
seeds* sp;
static std::string title(std::vector<producer*>& pvec, std::vector<customer*>& vec);
void routine();
public:
logger(seeds* ss, int sz) : task("logger", sz), data(new std::list<std::string>), sp(ss){}
void flush(const char*);
};
std::string logger::title(std::vector<producer*>& pvec, std::vector<customer*>& cvec)
{
producer* pp;
customer* cp;
std::ostringstream oss;
oss << "Time" << ",";
for (int i = 0; i < pvec.size() && (pp=pvec[i]); i++) oss << pp->t_name << ",";
for (int j = 0; j < cvec.size() && (cp=cvec[j]); j++) oss << cp->t_name << ",";
oss << "Seeds";
return oss.str();
}
void logger::flush(const char* n)
{
if (data) {
std::ofstream out(n);
auto it = data->begin();
for (;it != data->end(); it++)
out << *it << std::endl;
delete data;
data = 0;
}
}
void logger::routine()
{
std::vector<producer*>& pvec = producer::pvec;
std::vector<customer*>& cvec = customer::cvec;
std::ostringstream oss;
data->push_back(title(pvec, cvec));
producer* pp;
customer* cp;
while (true) {
std::ostringstream oss;
oss << getclock() << ",";
for (int i = 0; i < pvec.size() && (pp=pvec[i]); i++) oss << pp->nprd << ",";
for (int j = 0; j < cvec.size() && (cp=cvec[j]); j++) oss << cp->ncus << ",";
oss << sp->count;
data->push_back(oss.str());
sleep();
}
}
int customer::modest()
{
customer* cp;
for (int i = 0; i<cvec.size() && ( cp = cvec[i] ); i++)
if (cp != this
&& cp
&& cp->rdstate() == tk::sched::RUNNING
&& cp->rdtime() == rdtime()
&& interval < cp->interval) {
// let cp reminder this later
sleep(cp);
return 1;
}
return 0;
}
void customer::routine()
{
while (true) {
do {
wait(sp);
} while (modest());
ncus += sp->take();
acknowledge();
std::printf("%3d | %s consumes %d seed at %ld\n", sp->count, t_name, 1, getclock());
delay(interval);
}
}
void producer::routine()
{
while (allprd < MIN_REQ_SEEDS) {
// assume it takes the producer #interval time to produce #cnt amount of seeds
int interval = std::rand() % 4 + 2; // [2, 5]
// cnt is propotional with interval
int cnt;
if (interval <= 2)
cnt = 1;
else if (interval <= 4)
cnt = 2;
else
cnt = 3;
delay(interval);
sp->put(cnt);
nprd += cnt;
allprd += cnt;
std::printf("%3d | %s produces %d seeds at %ld\n", sp->count, t_name, cnt, getclock());
}
}
void exit()
{
// save log
logger* lg = ( logger* ) tk::sched::clock_task;
lg->flush("./test_task_leisure_time.out");
// the folowing operations are optional
customer* cp;
std::vector<customer*>& cvec = customer::cvec;
while (!cvec.empty()) {
cp = cvec.back();
cp->cancel(0); // IDLE->TERMINATED, required before one could delete it
cvec.pop_back();
delete cp;
}
producer* pp;
std::vector<producer*>& pvec = producer::pvec;
while (!pvec.empty()) {
pp = pvec.back();
pvec.pop_back();
delete pp;
}
// delete logger task (current task)
lg->cancel(0);
delete lg;
}
int main()
{
seeds* sd = new seeds();
// the order in which the lg (along with other tasks) is created doesnot matter.
// explicitly allocate 15000 bytes for lg by task(name, stack_size). The default stack size for every tak is 10000.
logger* lg = new logger(sd, 15000);
// clock task will be invoked at every new clock tick before any other tasks could execute
tk::sched::clock_task = lg;
// invoke logger after all task finished
// to do clean job, optional
tk::sched::clock_task_exit = true;
producer* pd = new producer("Tool", sd);
customer* cs = new customer("XiaoMu", 2, sd);
customer* cs2 = new customer("XiaoLan", 3, sd);
// start all created task in a sequence
currenttask->start();
// write to disk & clear objects on exiting
tk::sched::exit_fct = exit;
}
| 21.333333
| 116
| 0.614383
|
yecharlie
|
30826b8fcc7ba9d7bbcad99539507ba66d8832f8
| 2,575
|
cpp
|
C++
|
src/ngfx/drawOps/DrawColorOp.cpp
|
kamranrad1993/ngfx
|
eeef60e3419a88371a97e8bc3109d2b35b82cc89
|
[
"Apache-2.0",
"MIT-0",
"MIT"
] | 12
|
2021-04-03T16:50:22.000Z
|
2022-03-18T07:14:14.000Z
|
src/ngfx/drawOps/DrawColorOp.cpp
|
kamranrad1993/ngfx
|
eeef60e3419a88371a97e8bc3109d2b35b82cc89
|
[
"Apache-2.0",
"MIT-0",
"MIT"
] | 6
|
2021-05-06T21:02:19.000Z
|
2022-02-14T11:57:27.000Z
|
src/ngfx/drawOps/DrawColorOp.cpp
|
kamranrad1993/ngfx
|
eeef60e3419a88371a97e8bc3109d2b35b82cc89
|
[
"Apache-2.0",
"MIT-0",
"MIT"
] | 5
|
2021-06-11T20:15:37.000Z
|
2022-03-18T07:14:21.000Z
|
/*
* Copyright 2020 GoPro Inc.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 "ngfx/drawOps/DrawColorOp.h"
#include "ngfx/graphics/BufferUtil.h"
#include "ngfx/graphics/Config.h"
#include "ngfx/graphics/ShaderModule.h"
using namespace ngfx;
using namespace glm;
DrawColorOp::DrawColorOp(GraphicsContext *ctx,
const std::vector<glm::vec2> &pos,
const glm::vec4 &color)
: DrawOp(ctx) {
bPos.reset(createVertexBuffer<vec2>(ctx, pos));
bUbo.reset(createUniformBuffer(ctx, &color, sizeof(color)));
numVerts = uint32_t(pos.size());
createPipeline();
graphicsPipeline->getBindings({&U_UBO}, {&B_POS});
}
void DrawColorOp::draw(CommandBuffer *commandBuffer, Graphics *graphics) {
graphics->bindGraphicsPipeline(commandBuffer, graphicsPipeline);
graphics->bindVertexBuffer(commandBuffer, bPos.get(), B_POS, sizeof(vec2));
graphics->bindUniformBuffer(commandBuffer, bUbo.get(), U_UBO,
SHADER_STAGE_FRAGMENT_BIT);
graphics->draw(commandBuffer, numVerts);
}
void DrawColorOp::createPipeline() {
const std::string key = "drawColorOp";
graphicsPipeline = (GraphicsPipeline *)ctx->pipelineCache->get(key);
if (graphicsPipeline)
return;
GraphicsPipeline::State state;
state.renderPass = ctx->defaultRenderPass;
state.primitiveTopology = PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
auto device = ctx->device;
graphicsPipeline = GraphicsPipeline::create(
ctx, state,
VertexShaderModule::create(device, NGFX_DATA_DIR "/drawColor.vert").get(),
FragmentShaderModule::create(device, NGFX_DATA_DIR "/drawColor.frag")
.get(),
ctx->surfaceFormat, ctx->depthFormat);
ctx->pipelineCache->add(key, graphicsPipeline);
}
| 40.873016
| 81
| 0.706019
|
kamranrad1993
|
3087837487d28cf748219f196d1e37e5f91059f2
| 1,230
|
cpp
|
C++
|
Source/Common/Logger/LoggerSeverity.cpp
|
gunstarpl/Game-Engine
|
b800ff84b4c5487a33a6c86fca6dcac1e584e223
|
[
"Unlicense"
] | 10
|
2018-10-12T12:20:11.000Z
|
2022-01-20T17:13:50.000Z
|
Source/Common/Logger/LoggerSeverity.cpp
|
gunstarpl/Game-Engine
|
b800ff84b4c5487a33a6c86fca6dcac1e584e223
|
[
"Unlicense"
] | null | null | null |
Source/Common/Logger/LoggerSeverity.cpp
|
gunstarpl/Game-Engine
|
b800ff84b4c5487a33a6c86fca6dcac1e584e223
|
[
"Unlicense"
] | null | null | null |
/*
Copyright (c) 2018-2021 Piotr Doan. All rights reserved.
Software distributed under the permissive MIT License.
*/
#include "Common/Logger/LoggerSeverity.hpp"
using namespace Logger;
const char* Logger::GetSeverityName(Severity::Type severity)
{
switch(severity)
{
case Severity::Trace: return "Trace";
case Severity::Debug: return "Debug";
case Severity::Profile: return "Profile";
case Severity::Info: return "Info";
case Severity::Success: return "Success";
case Severity::Warning: return "Warning";
case Severity::Error: return "Error";
case Severity::Fatal: return "Fatal";
default: return "Unknown";
}
}
const char* Logger::GetSeverityMarker(Severity::Type severity)
{
switch(severity)
{
case Severity::Trace: return "t";
case Severity::Debug: return "d";
case Severity::Profile: return "p";
case Severity::Info: return "i";
case Severity::Success: return "s";
case Severity::Warning: return "w";
case Severity::Error: return "e";
case Severity::Fatal: return "f";
default: return " ";
}
}
| 30.75
| 62
| 0.602439
|
gunstarpl
|
308f7713be1a912b99f1584a0e9a468c446bcea6
| 5,180
|
hxx
|
C++
|
content/c++/hiroshi-mikuriya_mac-welcome/letters.hxx
|
chabukan/3d_led_cube
|
cbf910c847141b2e4104eeec0b5ebcab8f8aa09b
|
[
"MIT"
] | 3
|
2017-07-10T08:13:35.000Z
|
2017-07-28T04:57:44.000Z
|
content/c++/hiroshi-mikuriya_mac-welcome/letters.hxx
|
chabukan/3d_led_cube
|
cbf910c847141b2e4104eeec0b5ebcab8f8aa09b
|
[
"MIT"
] | 2
|
2017-07-12T05:11:07.000Z
|
2018-01-04T03:07:29.000Z
|
content/c++/hiroshi-mikuriya_mac-welcome/letters.hxx
|
chabukan/3d_led_cube
|
cbf910c847141b2e4104eeec0b5ebcab8f8aa09b
|
[
"MIT"
] | 11
|
2017-07-10T04:52:59.000Z
|
2021-04-07T05:43:10.000Z
|
{"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABDDDDDDDDDBAAAAFPPPPPPPPPPNDAADNPPPPPPPPPPPLBABLPPPPPPPPPPPJAABLPPPPPPPPPPMDAABLPPMEDDDDDDBAAABLPPLBAAAAAAAAAABLPPLBAAAAAAAAAABLPPLBAAAAAAAAAABLPPLBAAAAAAAAAABLPPMEDDBAAAAAAABLPPPPPPMCAAAAAABLPPPPPPPJAAAAAABLPPPPPPPLBAAAAABLPPPPPPNEAAAAAABLPPMEDDBAAAAAAABLPPLBAAAAAAAAAABLPPLBAAAAAAAAAABLPPLBAAAAAAAAAABLPPLBAAAAAAAAAABLPPLBAAAAAAAAAABLPPLBAAAAAAAAAABLPPLBAAAAAAAAAADNPPMCAAAAAAAAAAAGPOEAAAAAAAAAAAAACCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},
{"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBAAAAAAAAAAAFKPPMGCAAAAAAABHMPPPPPIDAAAAAAADKPPPPPHCAAAAAAADKPPPPPHCAAAAAAADKPPPPPHCAAAAAAADKPPPPPHCAAAAAAADKPPPPPHCAAAAAAADKPPPPPHCAAAAAAADKPPPPPHCAAAAAAADKPPPPPHCAAAAAAADKPPPPPHCAAAAAAADKPPPPPHCAAAAAAADKPPPPPHCAAAAAAADKPPPPPHCAAAAAAADKPPPPPHCAAAAAAADKPPPPPHCAAAAAAADKPPPPPHCAAAAAAADKPPPPPHCAAAAAAADKPPPPPHCAAAAAAADKPPPPPHCAAAAAAADKPPPPPHCAAAAAAADKPPPPPHCAAAAAABFLPPPPPKFAAAAAAAAEJPPNJDAAAAAAAAAAACCBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},
{"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACDDCAAAAAAAAAAAIPPPPIAAAAAAAAAOPPPPPPOAAAAAAAGPPPPPPPPGAAAAADPPPPPPPPPPDAAAAJPPPIDDIPPPJAAAAOPPKAAAAKPPOAAAEPPPEAAAAEPPPFAAGPPPAAAAAALPJAAAJPPKAAAAAAACAAABMPPIAAAAAAAAAAAALPPEAAAAAAAAAAAALPPEAAAABDDCAAAALPPEAAAGPPPPHAAALPPEAACNPPPPPDABMPPIAABNPPPPPCAAJPPKAAAFPPPPPCAAGPPPAAAACFPPPCAAEPPPEAAAAEPPPEAAAOPPKAAAAKPPOAAAAJPPPHDDIPPPJAAAADPPPPPPPPPPDAAAAAHPPPPPPPPHAAAAAABOPPPPPPOBAAAAAAAAIPPPPIAAAAAAAAAAACDDCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},
{"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAABBAAAAAKPFAAAAABNOCAAAGPPNBAAAAIPPKAAACPPMAAAAAGPPHAAACPPMAAAAAGPPGAAACPPMAAAAAGPPGAAACPPMAAAAAGPPGAAACPPMAAAAAGPPGAAACPPMAAAAAGPPGAAACPPMAAAAAGPPGAAACPPNEDDDDIPPGAAACPPPPPPPPPPPGAAACPPPPPPPPPPPGAAACPPPPPPPPPPPGAAACPPPPPPPPPPPGAAACPPNEDDDDIPPGAAACPPMAAAAAGPPGAAACPPMAAAAAGPPGAAACPPMAAAAAGPPGAAACPPMAAAAAGPPGAAACPPMAAAAAGPPGAAACPPMAAAAAGPPGAAACPPMAAAAAGPPGAAAGPPNBAAAAIPPKAAAALPFAAAAACNOCAAAAACAAAAAAABBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},
{"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACDDDDDDDDDCAAAAIPPPPPPPPPPPLCABPPPPPPPPPPPPPIABPPPPPPPPPPPPPKAAHPPPPPPPPPPPMDAAACDDGPPPIDDDBAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAAIPPPIAAAAAAAAAAAALPLBAAAAAAAAAAAAACBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},
{"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBAAAAAAAAAAABIOPMFAAAAAAAAACJPPPPNFAAAAAAAABFPPPPNDAAAAAAAABFPPPPNDAAAAAAAABFPPPPNDAAAAAAAABFPPPPNDAAAAAAAABFPPPPNDAAAAAAAABFPPPPNDAAAAAAAABFPPPPNDAAAAAAAABFPPPPNDAAAAAAAABFPPPPNDAAAAAAAABFPPPPNDAAAAAAAABFPPPPNDAAAAAAAABFPPPPNDAAAAAAAABFPPPPNDAAAAAAAABHPPPPOIBAAAAAAAABHOPNIAAAAAAAAAAAADDCAAAAAAAAAAADNPPOKBAAAAAAAAGOPPPPPODAAAAAADKPPPPPPPICAAAAADKPPPPPPPICAAAAABGOPPPPPODAAAAAAAADMPPOKCAAAAAAAAAAABCBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},
{"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACDDDDDDDDDCAAAAIPPPPPPPPPPPLCABPPPPPPPPPPPPPIABPPPPPPPPPPPPPKAAHPPPPPPPPPPPMDAAACDDGPPPIDDDBAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAADPPPGAAAAAAAAAAAIPPPIAAAAAAAAAAAALPLBAAAAAAAAAAAAACBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},
{"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACDDBAAAAAAAAAABMPPPODAAAAAAAABOPPPPPPFAAAAAAAJPPPPPPPNAAAAAAFPPPPPPPPPLAAAAAKPPPIEGOPPOCAAAAPPPGAAACPPPEAAAFPPOCAAAALPPJAAAHPPLAAAAAEPPLAAALPPHAAAAACOPOAABNPPFAAAAABNPPFAAMPPCAAAAAAMPPCAAMPPCAAAAAAMPPCAAMPPCAAAAAAMPPCAAMPPCAAAAAAMPPCABNPPFAAAAABNPPFAALPPHAAAAACOPOAAAHPPLAAAAAEPPLAAAFPPOCAAAALPPJAAAAPPPGAAACPPPEAAAAKPPPIDFOPPOCAAAAFPPPPPPPPPLAAAAAAJPPPPPPPNAAAAAAABOPPPPPPFAAAAAAAABLPPPODAAAAAAAAAAADDDBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},
{"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBAAAAAAAAAAAAAHPOEAAAAAAAAAAAEOPPMCAAAAAAAAAACNPPLBAAAAAAAAAABNPPLBAAAAAAAAAABNPPLBAAAAAAAAAABNPPLBAAAAAAAAAABNPPLBAAAAAAAAAABNPPLBAAAAAAAAAABNPPLBAAAAAAAAAABNPPLBAAAAAAAAAABNPPLBAAAAAAAAAABNPPLBAAAAAAAAAABNPPLBAAAAAAAAAABNPPLBAAAAAAAAAABNPPLBAAAAABAAAABNPPLBAAACLPLAAACNPPLBAAAKPPPGAAEOPPMDAAAFPPPJAAGOPPKAAAACMPPPFELPPPGAAAACLPPPPPPPPOFAAAAAIPPPPPPPPMBAAAAABKPPPPPPOBAAAAAAAADOPPOGAAAAAAAAAAAADDBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},
{"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACDDBAAAAAAAAAABMPPPODAAAAAAAABOPPPPPPFAAAAAAAJPPPPPPPNAAAAAAFPPPPPPPPPLAAAAAKPPPIEGOPPOCAAAAPPPGAAACPPPEAAAFPPOCAAAALPPJAAAHPPLAAAAAEPPLAAALPPHAAAAACOPOAABNPPFAAAAABNPPFAAMPPCAAAAAAMPPCAAMPPCAAAAAAMPPCAAMPPCAAAAAAMPPCAAMPPCAAAAAAMPPCABNPPFAAAAABNPPFAALPPHAAAAACOPOAAAHPPLAAAAAEPPLAAAFPPOCAAAALPPJAAAAPPPGAAACPPPEAAAAKPPPIDFOPPOCAAAAFPPPPPPPPPLAAAAAAJPPPPPPPNAAAAAAABOPPPPPPFAAAAAAAABLPPPODAAAAAAAAAAADDDBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},
| 470.909091
| 517
| 0.988417
|
chabukan
|
309e6bf9bcb840ddb5d778acb88d30f8fd58cc15
| 4,443
|
cpp
|
C++
|
vkoo/src/core/DescriptorSetLayout.cpp
|
KaiSut0/interactive-hex-meshing
|
187c926610ca5617f569405c23ab5a62b189e100
|
[
"MIT"
] | 129
|
2021-09-07T17:15:18.000Z
|
2022-02-28T08:59:02.000Z
|
vkoo/src/core/DescriptorSetLayout.cpp
|
KaiSut0/interactive-hex-meshing
|
187c926610ca5617f569405c23ab5a62b189e100
|
[
"MIT"
] | 2
|
2021-10-03T07:30:20.000Z
|
2022-01-06T16:05:41.000Z
|
vkoo/src/core/DescriptorSetLayout.cpp
|
KaiSut0/interactive-hex-meshing
|
187c926610ca5617f569405c23ab5a62b189e100
|
[
"MIT"
] | 11
|
2021-09-08T11:29:09.000Z
|
2022-03-17T08:39:50.000Z
|
#include "vkoo/core/DescriptorSetLayout.h"
#include "vkoo/core/Device.h"
#include "vkoo/core/ShaderModule.h"
namespace vkoo {
inline VkDescriptorType FindDescriptorType(ShaderResourceType resource_type,
bool dynamic) {
switch (resource_type) {
case ShaderResourceType::InputAttachment:
return VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
break;
case ShaderResourceType::Image:
return VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
break;
case ShaderResourceType::ImageSampler:
return VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
break;
case ShaderResourceType::ImageStorage:
return VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
break;
case ShaderResourceType::Sampler:
return VK_DESCRIPTOR_TYPE_SAMPLER;
break;
case ShaderResourceType::BufferUniform:
if (dynamic) {
return VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
} else {
return VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
}
break;
case ShaderResourceType::BufferStorage:
if (dynamic) {
return VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC;
} else {
return VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
}
break;
default:
throw std::runtime_error(
"No conversion possible for the shader resource type.");
break;
}
}
DescriptorSetLayout::DescriptorSetLayout(
Device& device, const std::vector<ShaderModule*>& shader_modules,
uint32_t set_index, const std::vector<ShaderResource>& resource_set)
: device_(device), set_index_(set_index), shader_modules_{shader_modules} {
for (auto& resource : resource_set) {
// Skip shader resources whitout a binding point
if (resource.type == ShaderResourceType::Input ||
resource.type == ShaderResourceType::Output ||
resource.type == ShaderResourceType::PushConstant ||
resource.type == ShaderResourceType::SpecializationConstant) {
continue;
}
if (resource.mode != ShaderResourceMode::Static) {
throw std::runtime_error("Non-static resources are not supported yet.");
}
// Convert from ShaderResourceType to VkDescriptorType.
auto descriptor_type = FindDescriptorType(
resource.type, resource.mode == ShaderResourceMode::Dynamic);
binding_flags_.push_back(0);
// Convert ShaderResource to VkDescriptorSetLayoutBinding.
VkDescriptorSetLayoutBinding layout_binding{};
layout_binding.binding = resource.binding;
layout_binding.descriptorCount = resource.array_size;
layout_binding.descriptorType = descriptor_type;
layout_binding.stageFlags =
static_cast<VkShaderStageFlags>(resource.stages);
bindings_.push_back(layout_binding);
binding_id_to_layout_dict_.emplace(resource.binding, layout_binding);
name_to_binding_id_dict_.emplace(resource.name, resource.binding);
}
VkDescriptorSetLayoutCreateInfo create_info{
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
create_info.flags = 0;
create_info.bindingCount = static_cast<uint32_t>(bindings_.size());
create_info.pBindings = bindings_.data();
VK_CHECK(vkCreateDescriptorSetLayout(device_.GetHandle(), &create_info,
nullptr, &handle_));
}
std::optional<VkDescriptorSetLayoutBinding>
DescriptorSetLayout::GetLayoutBinding(uint32_t binding_index) const {
auto it = binding_id_to_layout_dict_.find(binding_index);
if (it == binding_id_to_layout_dict_.end()) {
return {};
}
return it->second;
}
std::optional<VkDescriptorSetLayoutBinding>
DescriptorSetLayout::GetLayoutBinding(const std::string& name) const {
auto it = name_to_binding_id_dict_.find(name);
if (it == name_to_binding_id_dict_.end()) {
return {};
}
return GetLayoutBinding(it->second);
}
DescriptorSetLayout::DescriptorSetLayout(DescriptorSetLayout&& other)
: device_{other.device_},
handle_{other.handle_},
set_index_{other.set_index_},
shader_modules_{other.shader_modules_},
bindings_{other.bindings_},
binding_flags_{other.binding_flags_},
binding_id_to_layout_dict_{other.binding_id_to_layout_dict_},
name_to_binding_id_dict_{other.name_to_binding_id_dict_} {
other.handle_ = VK_NULL_HANDLE;
}
DescriptorSetLayout::~DescriptorSetLayout() {
if (handle_ != VK_NULL_HANDLE) {
vkDestroyDescriptorSetLayout(device_.GetHandle(), handle_, nullptr);
}
}
} // namespace vkoo
| 34.710938
| 79
| 0.728562
|
KaiSut0
|
30a02980ba6802483c61cd87c547110f359d34b5
| 2,621
|
hpp
|
C++
|
ufora/FORA/TypedFora/ABI/MutableVectorHandle.hpp
|
ufora/ufora
|
04db96ab049b8499d6d6526445f4f9857f1b6c7e
|
[
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 571
|
2015-11-05T20:07:07.000Z
|
2022-01-24T22:31:09.000Z
|
ufora/FORA/TypedFora/ABI/MutableVectorHandle.hpp
|
timgates42/ufora
|
04db96ab049b8499d6d6526445f4f9857f1b6c7e
|
[
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 218
|
2015-11-05T20:37:55.000Z
|
2021-05-30T03:53:50.000Z
|
ufora/FORA/TypedFora/ABI/MutableVectorHandle.hpp
|
timgates42/ufora
|
04db96ab049b8499d6d6526445f4f9857f1b6c7e
|
[
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 40
|
2015-11-07T21:42:19.000Z
|
2021-05-23T03:48:19.000Z
|
/***************************************************************************
Copyright 2015 Ufora Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
****************************************************************************/
#pragma once
#include <stdint.h>
#include "../../Judgment/JudgmentOnValue.hppml"
#include "../../Core/Type.hppml"
#include "../../../core/Common.hppml"
#include "../../../core/serialization/Serialization.hpp"
#include "../../../core/AtomicOps.hpp"
#include "../../../core/SymbolExport.hpp"
#include "../../../core/PolymorphicSharedPtr.hpp"
#include "PackedForaValues.hppml"
namespace TypedFora {
namespace Abi {
class MutableVectorHandle {
public:
MutableVectorHandle(
MemoryPool* owningMemoryPool,
JudgmentOnValue inElementJOV,
hash_type hash
);
~MutableVectorHandle();
size_t size() const { return mSize; }
JudgmentOnValue elementJOV() const { return mElementJOV; }
hash_type identityHash() const { return mVectorHash; }
AO_t refcount() const { return mRefcount; }
PackedForaValues packedValues() const;
PackedForaValues appendUninitialized(long count);
void resize(size_t inTotalElements, const ImplValContainer& inValue);
void shrink(size_t inTotalElements);
ImplValContainer operator[](int index) const;
void setItem(int index, const ImplValContainer& inValue);
void incrementRefcount();
bool decrementRefcount(); //returns 'true' if we destroyed the object
//swap the data owned by these two handles. The two handles must have the same identity,
//types, and must exist in the same memory pool.
void swapContentsWith(MutableVectorHandle& otherHandle);
private:
void destroyElements(long start, long stop);
size_t stride() const;
AO_t mRefcount;
size_t mSize; //how many elements are populated
uint8_t* mRawDataPtr; //null only if the vector is empty
MemoryPool* mOwningMemoryPool; //who owns this MutableVectorHandle?
JudgmentOnValue mElementJOV; //A judgment on the elements in the vector, which must
//have a Type.
hash_type mVectorHash;
};
ostream& operator<<(ostream& s, MutableVectorHandle* vd);
}
}
| 28.182796
| 89
| 0.700114
|
ufora
|
30a246cef07d874b5d004393b9bf8f04f95d676d
| 23,321
|
cpp
|
C++
|
src/manipulator.cpp
|
s9rA16Bf4/B.O.A.T
|
ab8203bf43991c643fbea4e6fdf487185c3a4de7
|
[
"MIT"
] | null | null | null |
src/manipulator.cpp
|
s9rA16Bf4/B.O.A.T
|
ab8203bf43991c643fbea4e6fdf487185c3a4de7
|
[
"MIT"
] | null | null | null |
src/manipulator.cpp
|
s9rA16Bf4/B.O.A.T
|
ab8203bf43991c643fbea4e6fdf487185c3a4de7
|
[
"MIT"
] | null | null | null |
#include "manipulator.hpp"
bool manipulator::process(std::vector<std::string> parsedValues){
bool toReturn = false;
file fP;
builtInFunc bif;
for (unsigned int y = 0; y < parsedValues.size(); y++){
std::vector<std::string> splitLine = fP.split(parsedValues[y], " ");
for (unsigned int i = 0; i < splitLine.size(); i++){
if (splitLine[i] != "%"){ // ignore the line if its a comment
if (splitLine[i] == "string" || splitLine[i] == "int"){ // new variable declarition
if (splitLine.size() == 3){
variable *A = this->find(splitLine[i+1]);
if (!A){
variable *newVar = new variable();
newVar->name = splitLine[i+1];
newVar->type = splitLine[i];
if (splitLine[i+2][0] == '/'){ // variable!
std::string variableName = splitLine[i+2];
variableName.erase(0,1); // Removes the /
variable *B = this->find(variableName); // Find the variable
if (!B){ std::cerr << "("<< y+1 <<") Error: variable [" << variableName<< "] has not been declared" << std::endl; }
else{
if (B->type == newVar->type){ newVar->value = B->value;}
else{ std::cerr << "("<< y+1 <<") Error: variable [" << variableName << "] has not the same type as the one you're trying to declare" << std::endl; }
}
}else{ newVar->value = splitLine[i+2]; }
variables.push_back(newVar);
}else{ std::cerr << "("<< y+1 <<") Error: variable [" << splitLine[i+1] << "] has already been declared" << std::endl; }
}
else{ // array declarition
array *newArray = new array();
newArray->type = splitLine[i];
newArray->name = splitLine[i+1];
// array* A = this->find()
for (i = i+2; i < splitLine.size(); i++){ newArray->guts.push_back(splitLine[i]); }
arrays.push_back(newArray);
}
}else if(splitLine[i] == "print" || splitLine[i] == "printnl"){ // Print a message
bool newLine = false;
if (splitLine[i] == "printnl"){ newLine = true; }
for (unsigned int i = 1; i < splitLine.size(); i++){
toReturn = this->print(splitLine[i], newLine);
this->print(" ", newLine);
}
this->print("\n", newLine);
}else if(splitLine[i] == "cits"){ toReturn = bif.convertIntToString(splitLine[i+1]); } // Convert an int to a string
else if(splitLine[i] == "csti"){ toReturn = bif.convertStringToInt(splitLine[i+1]); } // convert a string to an int
else if (splitLine[i] == "def"){ // new function!
function *newFunc = new function();
newFunc->name = splitLine[i+1];
for (unsigned int x = i+2; x < splitLine.size(); x++){
newFunc->funcGuts.push_back(splitLine[x]);
}
functions.push_back(newFunc);
break;
}
else if (splitLine[i] == "+" || splitLine[i] == "-" || splitLine[i] == "*" || splitLine[i] == "/" || splitLine[i] == "//"){ // manipulation!
variable *A = this->find(splitLine[i-1]); // Find our variables
variable *B = this->find(splitLine[i+1]);
if (!A || !B){ std::cerr << "("<< y+1 <<") Error: Undeclared variable [" << ((!A)? splitLine[i-1]:splitLine[i+1]) << "]" << std::endl;}
else if (A->type != B->type){std::cerr << "("<< y+1 <<") Error: Variables [" << A->name << "] and [" << B->name << "] are not of the same type" << std::endl; }
else if (splitLine[i] == "+"){
if (A->type == "int"){
A->value = std::to_string(std::stoi(A->value) + std::stoi(B->value)); // int add
toReturn = true;
}else{
A->value += B->value; // string add
toReturn = true;
}
}else if (splitLine[i] == "-"){
if (A->type == "int"){
A->value = std::to_string(std::stoi(A->value) - std::stoi(B->value)); // sub
toReturn = true;
}
}else if (splitLine[i] == "*"){
if (A->type == "int"){
A->value = std::to_string(std::stoi(A->value) * std::stoi(B->value)); // mult
toReturn = true;
}
}else if (splitLine[i] == "/"){
if (A->type == "int"){
A->value = std::to_string(std::stof(A->value) / std::stof(B->value)); // divide
toReturn = true;
}
break;
}else if (splitLine[i] == "//"){
if (A->type == "int"){
A->value = std::to_string(std::stoi(A->value) % std::stoi(B->value)); // modulos
toReturn = true;
}
}else{ std::cerr << "("<< y+1 <<") Error: Unknown operator [" << splitLine[i] << "]" << std::endl; }
}else if (splitLine[i] == "include"){ // include contents from another file
if (std::filesystem::exists(splitLine[i+1])){
std::ifstream openFile(splitLine[i+1]);
std::string line;
std::vector<std::string> tempVector;
for (unsigned int x = y+1; x < parsedValues.size(); x++){ tempVector.push_back(parsedValues[x]); } // Remember our old lines
parsedValues.resize(y); // Shrink our vector
parsedValues.shrink_to_fit(); // resize
while(std::getline(openFile, line)){ parsedValues.push_back(line); } // Insert the new lines
for(std::string oldLines:tempVector){parsedValues.push_back(oldLines); } // Insert the old lines
y--; // Jump one line up so that we can read our newly inserted values
}else{ std::cerr << "("<< y+1 <<") Error: File [" << splitLine[i+1] << "] does not exist" << std::endl; }
}else if (splitLine[i] == "up"){
std::string firstPart = splitLine[i+1], secondPart = splitLine[i+2];
if (firstPart[firstPart.size()-1] == ']' && secondPart[secondPart.size()-1] != ']'){ // We are updating an array with the contents of a vector
std::string string = firstPart;
int leftWingPos = string.find("[");
int rightWingPos = string.find("]");
std::string index = string.substr(leftWingPos+1, string.size()-1);
int indexInt = std::stoi(index); // This will be the actual index of the array
string = string.erase(leftWingPos, rightWingPos); // Now we have the array name
array *A = this->findArr(string);
variable *B = this->find(secondPart);
if (indexInt > A->guts.size() || indexInt < 0){std::cout << "Error: index is out of bounds!" << std::endl;}
else{
if (!A || !B){ std::cerr << "("<< y+1 <<") Error: Undeclared variable/array [" << ((!A)? string:secondPart) << "]" << std::endl;}
else if (A->type != B->type){std::cerr << "("<< y+1 <<") Error: Array [" << A->name << "] and variable [" << B->name << "] are not of the same type" << std::endl; }
else{ A->guts[indexInt] = B->value; }
}
}else if (secondPart[secondPart.size()-1] == ']' && firstPart[splitLine[i+1].size()-1] != ']'){ // We are updating a variable with the contents of an array
std::string string = secondPart;
int leftWingPos = string.find("[");
int rightWingPos = string.find("]");
std::string index = string.substr(leftWingPos+1, string.size()-1);
int indexInt = std::stoi(index); // This will be the actual index of the array
string = string.erase(leftWingPos, rightWingPos); // Now we have the array name
variable *A = this->find(firstPart);
array *B = this->findArr(string);
if (indexInt > B->guts.size() || indexInt < 0){std::cout << "Error: index is out of bounds!" << std::endl;}
else{
if (!A || !B){ std::cerr << "("<< y+1 <<") Error: Undeclared variable/array [" << ((!A)? firstPart:string) << "]" << std::endl;}
else if (A->type != B->type){std::cerr << "("<< y+1 <<") Error: Array [" << A->name << "] and variable [" << B->name << "] are not of the same type" << std::endl; }
else{ A->value = B->guts[indexInt]; }
}
}else if (secondPart[secondPart.size()-1] == ']' && firstPart[splitLine[i+1].size()-1] == ']'){ // Array to an array
std::string string = firstPart;
std::string string2 = secondPart;
int leftWingPos = string.find("[");
int rightWingPos = string.find("]");
int leftWingPos2 = string2.find("[");
int rightWingPos2 = string2.find("]");
std::string index = string.substr(leftWingPos+1, string.size()-1);
int indexInt = std::stoi(index); // This will be the actual index of the array
string = string.erase(leftWingPos, rightWingPos); // Now we have the array name
std::string index2 = string2.substr(leftWingPos2+1, string2.size()-1);
int indexInt2 = std::stoi(index2); // This will be the actual index of the array
string2 = string2.erase(leftWingPos2, rightWingPos2); // Now we have the array name
array *A = this->findArr(string);
array *B = this->findArr(string2);
if (indexInt > B->guts.size() || indexInt < 0 || indexInt2 > A->guts.size() || indexInt2 < 0){std::cout << "Error: index is out of bounds!" << std::endl;}
else{
if (!A || !B){ std::cerr << "("<< y+1 <<") Error: Undeclared array/s [" << ((!A)? string:string2) << "]" << std::endl;}
else if (A->type != B->type){std::cerr << "("<< y+1 <<") Error: The arrays [" << A->name << "] and [" << B->name << "] are not of the same type" << std::endl; }
else{ A->guts[indexInt] = B->guts[indexInt2]; }
}
}else{
variable *A = this->find(splitLine[i+1]); // Find our variables
variable *B = this->find(splitLine[i+2]);
if (!A || !B){ std::cerr << "("<< y+1 <<") Error: Undeclared variable [" << ((!A)? splitLine[i-1]:splitLine[i+1]) << "]" << std::endl;}
else if (A->type != B->type){std::cerr << "("<< y+1 <<") Error: Variables [" << A->name << "] and [" << B->name << "] are not of the same type" << std::endl; }
else{ A->value = B->value; }
}
}else if (splitLine[i] == "in"){
variable *A = this->find(splitLine[i+1]); // Find our variables
if (!A){ std::cerr << "("<< y+1 <<") Error: Undeclared variable [" << splitLine[i+1] << "]" << std::endl;}
else if (A->type != "string"){std::cerr << "("<< y+1 <<") Error: Variables [" << A->name << "] is not a string" << std::endl; }
else{ std::cin >> A->value; }
}else if (splitLine[i] == "while"){
variable *floor = this->find(splitLine[i+1]);
variable *roof = this->find(splitLine[i+3]);
if (!floor || !roof){ std::cerr << "("<< y+1 <<") Error: Undeclared variable [" << ((!floor)? splitLine[i+1]:splitLine[i+3]) << "]" << std::endl;}
else if (floor->type != roof->type){std::cerr << "("<< y+1 <<") Error: Variables [" << floor->name << "] and [" << roof->name << "] are not of the same type" << std::endl; }
else{
int start = std::stoi(floor->value);
int max = std::stoi(roof->value);
std::string whatToDo = splitLine[i+2];
std::string whileLine = "";
std::vector<std::string> whileGuts;
for (i = i+4; i < splitLine.size(); i++){ whileLine += splitLine[i] + " "; }
whileGuts.push_back(whileLine);
if (whatToDo == "<"){
while(start < max){
this->process(whileGuts);
floor->value = std::to_string(std::stoi(floor->value)+1);
start++;
}
}else if (whatToDo == ">"){
while(start > max){
this->process(whileGuts);
roof->value = std::to_string(std::stoi(roof->value)-1);
max--;
}
}
}
}else if (splitLine[i] == "if"){
std::string firstPart = splitLine[i+1];
std::string secondPart = splitLine[i+3];
if (firstPart[firstPart.size()-1] == ']' && secondPart[secondPart.size()-1] != ']'){
variable *B = this->find(secondPart);
int leftWingPos = firstPart.find("[");
int rightWingPos = firstPart.find("]");
std::string index = firstPart.substr(leftWingPos+1, firstPart.size()-1);
int indexInt = std::stoi(index); // This will be the actual index of the array
firstPart = firstPart.erase(leftWingPos, rightWingPos); // Now we have the array name
array *A = this->findArr(firstPart);
if (!A || !B){ std::cout << "Error: Undeclared array [" << firstPart << "] and/or variable [" << secondPart << "]" << std::endl; }
else{
if (indexInt > A->guts.size() || 0 > indexInt){ std::cout << "Error: index is out of bounds!" << std::endl; }
else{
std::string whatToDo = splitLine[i+2];
std::string ifLine = "";
std::vector<std::string> ifGuts;
for (i = i+4; i < splitLine.size(); i++){ ifLine += splitLine[i] + " "; }
ifGuts.push_back(ifLine);
if (whatToDo == "<=" && A->guts[indexInt] <= B->value){ this->process(ifGuts); }
else if (whatToDo == "<" && A->guts[indexInt] < B->value){ this->process(ifGuts); }
else if (whatToDo == ">=" && A->guts[indexInt] >= B->value){ this->process(ifGuts); }
else if (whatToDo == ">" && A->guts[indexInt] > B->value){ this->process(ifGuts); }
else if (whatToDo == "==" && A->guts[indexInt] == B->value){this->process(ifGuts); }
}
}
}else if (firstPart[firstPart.size()-1] == ']' && secondPart[secondPart.size()-1] == ']'){
int leftWingPos = firstPart.find("[");
int rightWingPos = firstPart.find("]");
int leftWingPos2 = secondPart.find("[");
int rightWingPos2 = secondPart.find("]");
std::string index = firstPart.substr(leftWingPos+1, firstPart.size()-1);
int indexInt = std::stoi(index); // This will be the actual index of the array
std::string index2 = secondPart.substr(leftWingPos2+1, secondPart.size()-1);
int indexInt2 = std::stoi(index2); // This will be the actual index of the array
firstPart = firstPart.erase(leftWingPos, rightWingPos); // Now we have the array name
secondPart = secondPart.erase(leftWingPos2, rightWingPos2); // Now we have the array name
array *A = this->findArr(firstPart);
array *B = this->findArr(secondPart);
if (!A || !B){ std::cout << "Error: Undeclared array/s [" << secondPart << "] and [" << firstPart << "]" << std::endl; }
else{
if (indexInt > A->guts.size() || 0 > indexInt){ std::cout << "Error: index is out of bounds!" << std::endl; }
else{
std::string whatToDo = splitLine[i+2];
std::string ifLine = "";
std::vector<std::string> ifGuts;
for (i = i+4; i < splitLine.size(); i++){ ifLine += splitLine[i] + " "; }
ifGuts.push_back(ifLine);
if (whatToDo == "<=" && A->guts[indexInt] <= B->guts[indexInt2]){ this->process(ifGuts); }
else if (whatToDo == "<" && A->guts[indexInt] < B->guts[indexInt2]){ this->process(ifGuts); }
else if (whatToDo == ">=" && A->guts[indexInt] >= B->guts[indexInt2]){ this->process(ifGuts); }
else if (whatToDo == ">" && A->guts[indexInt] > B->guts[indexInt2]){ this->process(ifGuts); }
else if (whatToDo == "==" && A->guts[indexInt] == B->guts[indexInt2]){this->process(ifGuts); }
}
}
}else if (firstPart[firstPart.size()-1] != ']' && secondPart[secondPart.size()-1] == ']'){
variable *B = this->find(firstPart);
int leftWingPos = secondPart.find("[");
int rightWingPos = secondPart.find("]");
std::string index = secondPart.substr(leftWingPos+1, secondPart.size()-1);
int indexInt = std::stoi(index); // This will be the actual index of the array
secondPart = secondPart.erase(leftWingPos, rightWingPos); // Now we have the array name
array *A = this->findArr(secondPart);
if (!A || !B){ std::cout << "Error: Undeclared array [" << secondPart << "] and/or variable [" << firstPart << "]" << std::endl; }
else{
if (indexInt > A->guts.size() || 0 > indexInt){ std::cout << "Error: index is out of bounds!" << std::endl; }
else{
std::string whatToDo = splitLine[i+2];
std::string ifLine = "";
std::vector<std::string> ifGuts;
for (i = i+4; i < splitLine.size(); i++){ ifLine += splitLine[i] + " "; }
ifGuts.push_back(ifLine);
if (whatToDo == "<=" && A->guts[indexInt] <= B->value){ this->process(ifGuts); }
else if (whatToDo == "<" && A->guts[indexInt] < B->value){ this->process(ifGuts); }
else if (whatToDo == ">=" && A->guts[indexInt] >= B->value){ this->process(ifGuts); }
else if (whatToDo == ">" && A->guts[indexInt] > B->value){ this->process(ifGuts); }
else if (whatToDo == "==" && A->guts[indexInt] == B->value){this->process(ifGuts); }
}
}
}else{
variable *A = this->find(splitLine[i+1]);
variable *B = this->find(splitLine[i+3]);
if (!A || !B){ std::cerr << "("<< y+1 <<") Error: Undeclared variable [" << ((!A)? splitLine[i+1]:splitLine[i+3]) << "]" << std::endl;}
else if (A->type != B->type){std::cerr << "("<< y+1 <<") Error: Variables [" << A->name << "] and [" << B->name << "] are not of the same type" << std::endl; }
else{
std::string whatToDo = splitLine[i+2];
std::string ifLine = "";
std::vector<std::string> ifGuts;
for (i = i+4; i < splitLine.size(); i++){ ifLine += splitLine[i] + " "; }
ifGuts.push_back(ifLine);
if (whatToDo == "<=" && A->value <= B->value){ this->process(ifGuts); }
else if (whatToDo == "<" && A->value < B->value){ this->process(ifGuts); }
else if (whatToDo == ">=" && A->value >= B->value){ this->process(ifGuts); }
else if (whatToDo == ">" && A->value > B->value){ this->process(ifGuts); }
else if (whatToDo == "==" && A->value == B->value){this->process(ifGuts); }
}
}
variable *A = this->find(splitLine[i+1]);
variable *B = this->find(splitLine[i+3]);
if (!A || !B){ std::cerr << "("<< y+1 <<") Error: Undeclared variable [" << ((!A)? splitLine[i+1]:splitLine[i+3]) << "]" << std::endl;}
else if (A->type != B->type){std::cerr << "("<< y+1 <<") Error: Variables [" << A->name << "] and [" << B->name << "] are not of the same type" << std::endl; }
else{
std::string whatToDo = splitLine[i+2];
std::string ifLine = "";
std::vector<std::string> ifGuts;
for (i = i+4; i < splitLine.size(); i++){ ifLine += splitLine[i] + " "; }
ifGuts.push_back(ifLine);
if (whatToDo == "<=" && A->value <= B->value){ this->process(ifGuts); }
else if (whatToDo == "<" && A->value < B->value){ this->process(ifGuts); }
else if (whatToDo == ">=" && A->value >= B->value){ this->process(ifGuts); }
else if (whatToDo == ">" && A->value > B->value){ this->process(ifGuts); }
else if (whatToDo == "==" && A->value == B->value){this->process(ifGuts); }
}
}
else{ // might it perhaps be a func??
for (function* funcs:functions){
if (funcs->name == splitLine[i]){
std::vector<std::string> tempVector;
for (unsigned int x = y+1; x < parsedValues.size(); x++){ tempVector.push_back(parsedValues[x]); } // Remember our old lines
parsedValues.resize(y); // Shrink our vector
parsedValues.shrink_to_fit(); // resize
std::string functionLine = "";
for(std::string newLine:funcs->funcGuts){ functionLine += newLine + " ";} // Create the function line from its guts
parsedValues.push_back(functionLine);
for(std::string oldLines:tempVector){ parsedValues.push_back(oldLines); } // Insert the old lines
y--; // Jump one line up so that we can read our newly inserted function
break;
}
}
}
}
}
}
return toReturn;
}
bool manipulator::print(std::string string, bool newline){ // Prints the contents of a variable
bool toReturn = false;
if (string[0] == '/' && string[string.size()-1] != ']'){ // "Derefrence" of a variable
string = string.erase(0, 1);
variable *A = this->find(string);
if (!A){ std::cout << "Error: Undeclared variable [" << string << "]"<< std::endl; }
else{
if (newline){ std::cout << A->value << std::endl;}
else{std::cout << A->value;}
toReturn = true;
}
}else if (string[string.size()-1] == ']' && string[0] == '/'){ // "Derefrence" of an array
string = string.erase(0, 1); // Remove the /
int leftWingPos = string.find("[");
int rightWingPos = string.find("]");
std::string index = string.substr(leftWingPos+1, string.size()-1);
int indexInt = std::stoi(index); // This will be the actual index of the array
string = string.erase(leftWingPos, rightWingPos); // Now we have the array name
array *A = this->findArr(string);
if (!A){ std::cout << "Error: Undeclared array [" << string << "]"<< std::endl; }
else{
if (indexInt > A->guts.size() || 0 > indexInt){ std::cout << "Error: index is out of bounds!" << std::endl; }
else{
if (newline){ std::cout << A->guts[indexInt] << std::endl;}
else{std::cout << A->guts[indexInt];}
toReturn = true;
}
}
}
else{
if (newline){ std::cout << string << std::endl; }
else{ std::cout << string; }
toReturn = true;
}
return toReturn;
}
variable* manipulator::find(std::string varName){ // Finds the variable assocciated with varName
variable *toReturn = nullptr;
for (variable *entry:variables){
if (entry->name == varName){
toReturn = entry;
break;
}
}
return toReturn;
}
array* manipulator::findArr(std::string arrayName){ // Finds the array assocciated with arrayName
array *toReturn = nullptr;
for (array *entry:arrays){
if (entry->name == arrayName){
toReturn = entry;
break;
}
}
return toReturn;
}
| 49.408898
| 183
| 0.511642
|
s9rA16Bf4
|
30a73ee04de69fe2ca492f82c325b75ac1f0b236
| 751
|
cpp
|
C++
|
20200523_PAST3/b.cpp
|
miyalab/AtCoder
|
a57c8a6195463a9a8edd1c3ddd36cc56f145c60d
|
[
"MIT"
] | null | null | null |
20200523_PAST3/b.cpp
|
miyalab/AtCoder
|
a57c8a6195463a9a8edd1c3ddd36cc56f145c60d
|
[
"MIT"
] | null | null | null |
20200523_PAST3/b.cpp
|
miyalab/AtCoder
|
a57c8a6195463a9a8edd1c3ddd36cc56f145c60d
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main()
{
// 入出力の高速化
ios::sync_with_stdio(false);
cin.tie(nullptr);
// 表示精度変更
cout << fixed << setprecision(16);
int N, M, Q;
int s,n,m;
int point;
cin >> N >> M >> Q;
vector<vector<int>> ans(N+1,vector<int>(M+1));
// クエリ入力
for(int i=0; i<Q; i++){
cin >> s;
if(s==1){
cin >> n;
point = 0;
for(m=1; m<=M; m++){
if(ans[n][m] == 1){
point += N - ans[0][m];
}
}
cout << point << endl;
}
else{
cin >> n >> m;
ans[n][m] = 1; // 解答フラグ
ans[0][m] += 1; // 解答者数保存
}
}
}
| 18.775
| 50
| 0.366178
|
miyalab
|
dd6a1e72d88bd07d160e378dcbd57afc1830e4df
| 2,396
|
cpp
|
C++
|
src/poScene/EventCenter.cpp
|
ZawaadulKarim/Cinder-poScene
|
7e273d15a89f0a19d336e516017f910ef343f8f2
|
[
"BSD-3-Clause"
] | 71
|
2015-08-07T16:54:15.000Z
|
2021-11-07T06:10:22.000Z
|
src/poScene/EventCenter.cpp
|
ZawaadulKarim/Cinder-poScene
|
7e273d15a89f0a19d336e516017f910ef343f8f2
|
[
"BSD-3-Clause"
] | 19
|
2015-12-17T21:38:32.000Z
|
2019-12-09T20:05:18.000Z
|
src/poScene/EventCenter.cpp
|
ZawaadulKarim/Cinder-poScene
|
7e273d15a89f0a19d336e516017f910ef343f8f2
|
[
"BSD-3-Clause"
] | 29
|
2015-08-11T19:57:11.000Z
|
2021-05-06T20:25:50.000Z
|
/*
Copyright (c) 2015, Potion Design LLC
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "cinder/app/Window.h"
#include "cinder/app/App.h"
#include "poScene/EventCenter.h"
#include "poScene/Scene.h"
namespace po
{
namespace scene
{
EventCenterRef EventCenter::create()
{
return EventCenterRef( new EventCenter() );
}
EventCenter::EventCenter()
{
addEventProcessor( EventProcessorBaseRef( new MouseEventProcessor() ) );
addEventProcessor( EventProcessorBaseRef( new TouchEventProcessor() ) );
}
// Process all the event queues for this scene
void EventCenter::processEvents( std::vector<ViewRef> views )
{
// Sort views to be top down
std::sort( views.begin(), views.end(), [&views]( const ViewRef & a, const ViewRef & b ) {
return a->getDrawOrder() > b->getDrawOrder();
} );
// Process them
for( auto& processor : mEventProcessors ) {
processor->processEvents( views );
}
}
}
} // namespace po::scene
| 35.235294
| 92
| 0.755426
|
ZawaadulKarim
|
dd6de117154db922f3587e5cad7bd882df9e1348
| 8,128
|
hpp
|
C++
|
sdl/Optimization/FeatureHypergraphPairs.hpp
|
sdl-research/hyp
|
d39f388f9cd283bcfa2f035f399b466407c30173
|
[
"Apache-2.0"
] | 29
|
2015-01-26T21:49:51.000Z
|
2021-06-18T18:09:42.000Z
|
sdl/Optimization/FeatureHypergraphPairs.hpp
|
hypergraphs/hyp
|
d39f388f9cd283bcfa2f035f399b466407c30173
|
[
"Apache-2.0"
] | 1
|
2015-12-08T15:03:15.000Z
|
2016-01-26T14:31:06.000Z
|
sdl/Optimization/FeatureHypergraphPairs.hpp
|
hypergraphs/hyp
|
d39f388f9cd283bcfa2f035f399b466407c30173
|
[
"Apache-2.0"
] | 4
|
2015-11-21T14:25:38.000Z
|
2017-10-30T22:22:00.000Z
|
// Copyright 2014-2015 SDL plc
// 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.
/**
\file
Classes that represent pairs of IHypergraph<FeatureWeight>,
used as training data in DataObjectiveFunction objects.
Each pair represents (clamped-to-observed-input-output,
clamped-to-input-only), where the second is the search space over
possible outputs given the input observation.
\author Markus Dreyer
*/
#ifndef SDL_OPTIMIZATION_FEATUREHYPERGRAPHPAIRS_HPP
#define SDL_OPTIMIZATION_FEATUREHYPERGRAPHPAIRS_HPP
#pragma once
#include <sdl/Hypergraph/ArcVisitors.hpp>
#include <sdl/Hypergraph/IMutableHypergraph.hpp>
#include <sdl/Optimization/IOriginalFeatureIds.hpp>
#include <sdl/Optimization/Types.hpp>
#include <sdl/Util/Assert.hpp>
#include <sdl/Util/LogHelper.hpp>
#include <sdl/Util/Sleep.hpp>
#include <sdl/SharedPtr.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
#include <utility>
#include <vector>
namespace sdl {
namespace Optimization {
namespace bfs = boost::filesystem;
namespace detail {
/**
Changes arc weights according to new feature weights. Uses
WeightsInserter.
*/
template <class Arc>
void insertFeatureWeights(Hypergraph::IMutableHypergraph<Arc>* pHg,
typename Arc::Weight::FloatT const* pWeights, FeatureId nWeights) {
if (pWeights) pHg->forArcs(Hypergraph::InsertWeightsVisitor<Arc>(pWeights, nWeights));
}
}
/**
Represents training data, which can be available as an
array, loaded from disk on demand, etc.
*/
template <class ArcT>
class IFeatureHypergraphPairs {
public:
typedef Hypergraph::IHypergraph<ArcT> IHg;
typedef shared_ptr<IHg> IHgPtr;
typedef ArcT Arc;
typedef std::pair<IHgPtr, IHgPtr> value_type;
typedef typename ArcT::Weight Weight;
typedef typename Weight::FloatT FloatT;
virtual ~IFeatureHypergraphPairs() {}
virtual value_type operator[](TrainingDataIndex) = 0;
virtual void push_back(value_type const&) = 0;
virtual void finish() {}
/**
Changes the arc weights according to new feature weights.
*/
virtual void setFeatureWeights(FloatT const* featWeights, FeatureId numParams) = 0;
/**
Changes the arc weights of certain HG pairs according to
new feature weights. (Good for online learning.)
*/
virtual void setFeatureWeights(TrainingDataIndex begin, TrainingDataIndex end, FloatT const* featWeights,
FeatureId numParams)
= 0;
/**
\return The number of Hypergraph pairs.
*/
virtual TrainingDataIndex size() const = 0;
virtual FeatureId getNumFeatures() = 0;
virtual void setNumFeatures(FeatureId) = 0;
};
/**
In-memory implementation of IFeatureHypergraphPairs, i.e.,
all training examples are in memory.)
*/
template <class ArcT>
class InMemoryFeatureHypergraphPairs : public IFeatureHypergraphPairs<ArcT> {
public:
typedef ArcT Arc;
typedef typename IFeatureHypergraphPairs<Arc>::value_type value_type;
typedef typename IFeatureHypergraphPairs<Arc>::FloatT FloatT;
typedef std::vector<value_type> Vector;
typedef shared_ptr<Vector> VectorPtr;
InMemoryFeatureHypergraphPairs() : pPairs_(new std::vector<value_type>()) {}
/**
\param pPairs Pointer to all hypergraph pairs (i.e., complete
training data incl. features); takes ownership and will delete at
end.
*/
InMemoryFeatureHypergraphPairs(VectorPtr const& pPairs) : pPairs_(pPairs), numParams_(0) {}
value_type operator[](TrainingDataIndex index) override {
SDL_ASSERT_MSG(pPairs_->size() >= index, "index out of bounds");
return (*pPairs_)[index];
}
/**
Inserts the feature weights into all stored hypergraphs.
*
TODO: This could be made more efficient by having a map from
feature IDs to arcs that use them.
*/
void setFeatureWeights(FloatT const* featWeights, FeatureId numParams) override {
SDL_DEBUG(Optimization.HypergraphCrfObjFct, "Setting feature weights");
setFeatureWeights(0, size(), featWeights, numParams);
}
/**
\param begin First hypergraph pair index
\param end Last hypergraph pair index plus one
*/
void setFeatureWeights(TrainingDataIndex begin, TrainingDataIndex end, FloatT const* featWeights,
FeatureId numParams) override {
SDL_DEBUG(Optimization.HypergraphCrfObjFct, "Setting feature weights for HGs (" << begin << ", " << end
<< "]");
for (TrainingDataIndex i = begin; i < end; ++i) {
value_type const& hgpair = (*pPairs_)[i];
assert(hgpair.first->isMutable());
assert(hgpair.second->isMutable());
typedef Hypergraph::IMutableHypergraph<Arc> MHg;
detail::insertFeatureWeights(static_cast<MHg*>(hgpair.first.get()), featWeights, numParams);
detail::insertFeatureWeights(static_cast<MHg*>(hgpair.second.get()), featWeights, numParams);
}
}
// TODO: test
void push_back(value_type const& val) override { pPairs_->push_back(val); }
TrainingDataIndex size() const override { return pPairs_->size(); }
FeatureId getNumFeatures() override { return numParams_; }
void setNumFeatures(FeatureId n) override { numParams_ = n; }
private:
VectorPtr pPairs_;
FeatureId numParams_;
};
/**
* @brief This just writes each HG pair to disk immediately, nothing
* else.
*/
template <class ArcT>
class WriteFeatureHypergraphPairs : public IFeatureHypergraphPairs<ArcT> {
public:
typedef ArcT Arc;
typedef typename IFeatureHypergraphPairs<Arc>::value_type value_type;
typedef typename IFeatureHypergraphPairs<Arc>::FloatT FloatT;
enum { kSleepForMicroSeconds = 500 };
WriteFeatureHypergraphPairs(std::string const& fname) : dir_(fname), size_(0), project_(true) {
bfs::create_directories(fname + "/hg");
Util::usSleep(kSleepForMicroSeconds); // to be safe on NFS
SDL_INFO(Optimization.WriteFeatureHypergraphPairs, "Writing training archive to '" << fname << "'");
}
void push_back(value_type const& val) override {
int numThousands = size_ / 1000;
bfs::path dir(dir_ / bfs::path("hg") / bfs::path(sdl::lexical_cast<std::string>(numThousands)));
bfs::create_directories(dir);
std::string name(sdl::lexical_cast<std::string>(size_) + ".hg");
std::ofstream out((dir / bfs::path(name)).string().c_str());
if (project_) { // don't need the input labels (could even remove all labels)
typedef Hypergraph::IMutableHypergraph<Arc> MHg;
assert(val.first->isMutable());
assert(val.second->isMutable());
static_cast<MHg*>(val.first.get())->projectOutput();
static_cast<MHg*>(val.second.get())->projectOutput();
}
out << *val.first << '\n' << "-----" << '\n' << *val.second << '\n';
++size_;
}
value_type operator[](TrainingDataIndex index) override { return value_type(); }
void finish() override {
bfs::path p(dir_ / bfs::path("size.txt"));
std::ofstream out(p.string().c_str());
out << size_;
}
void setFeatureWeights(FloatT const* featWeights, FeatureId numParams) override {}
void setFeatureWeights(TrainingDataIndex begin, TrainingDataIndex end, FloatT const* featWeights,
FeatureId numParams) override {}
std::size_t size() const override { return 0; }
FeatureId getNumFeatures() override { return 0; }
void setNumFeatures(FeatureId numParams) override {
bfs::path p(dir_ / bfs::path("num-feats.txt"));
std::ofstream out(p.string().c_str());
out << numParams;
}
private:
boost::filesystem::path dir_;
std::size_t size_;
bool project_;
};
}}
#endif
| 33.726141
| 107
| 0.703002
|
sdl-research
|
dd732be1422bb4926de2d07a214f29f3cb29bccb
| 2,050
|
cpp
|
C++
|
Adventure in a Maze - GFG/adventure-in-a-maze.cpp
|
sahib-pratap-singh/Leetcode
|
0df2053dcf51c61c1d32ae2d20f58c11b2c25b24
|
[
"MIT"
] | null | null | null |
Adventure in a Maze - GFG/adventure-in-a-maze.cpp
|
sahib-pratap-singh/Leetcode
|
0df2053dcf51c61c1d32ae2d20f58c11b2c25b24
|
[
"MIT"
] | null | null | null |
Adventure in a Maze - GFG/adventure-in-a-maze.cpp
|
sahib-pratap-singh/Leetcode
|
0df2053dcf51c61c1d32ae2d20f58c11b2c25b24
|
[
"MIT"
] | null | null | null |
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
#define N 1000000007
public:
bool moveRight(int a){
if(a == 1 || a == 3) return true;
return false;
}
bool moveDown(int a){
if(a != 1) return true;
return false;
}
vector<int> FindWays(vector<vector<int>>&matrix){
int n = matrix.size();
vector< vector< pair<int, int > > > a(n, vector< pair<int, int> > (n, {0,0}));
a[0][0].first = 1;
for(int i = 0; i < n ; i ++){
for(int j = 0; j < n ; j ++)
a[i][j].second = matrix[i][j];
}
for(int i = 1 ; i < n ; i ++){
if(a[0][i-1].first == 1 && moveRight(matrix[0][i-1])) {
a[0][i].first = 1;
a[0][i].second += a[0][i-1].second;
} else{
a[0][i].first = 0;
}
}
for(int j = 1; j < n ; j ++){
if(a[j-1][0].first == 1 && moveDown(matrix[j-1][0])){
a[j][0].first = 1;
a[j][0].second += a[j-1][0].second;
} else{
a[j][0].first = 0;
}
}
for(int i = 1; i < n ; i ++){
for(int j = 1; j < n ; j ++){
if(moveDown(matrix[i-1][j]) && a[i-1][j].first){
a[i][j].first = (a[i-1][j].first)%N;
a[i][j].second += a[i-1][j].second;
}
if(moveRight(matrix[i][j-1]) && a[i][j-1].first){
a[i][j].first =( a[i][j].first%N + a[i][j-1].first%N)%N;
a[i][j].second = max(a[i][j].second, matrix[i][j] + a[i][j-1].second);
}
}
}
int s1 = a[n-1][n-1].first;
int s2 = a[n-1][n-1].second;
if(s1 == 0) return {0, 0};
return {s1, s2};
}
};
// { Driver Code Starts.
int main(){
int tc;
cin >> tc;
while(tc--){
int n;
cin >> n;
vector<vector<int>>matrix(n, vector<int>(n, 0));
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++)
cin >> matrix[i][j];
}
Solution obj;
vector<int> ans = obj.FindWays(matrix);
for(auto i: ans)cout << i << " ";
cout << "\n";
}
return 0;
} // } Driver Code Ends
| 23.837209
| 85
| 0.450244
|
sahib-pratap-singh
|
dd7a4704470862257bc59f2cf184316925131f56
| 2,024
|
cpp
|
C++
|
src/filters/VoronoiFilter.cpp
|
dasl-/ofxFilterLibrary
|
6e43d33b205f04706b72747e5b4ce7f45cab3e88
|
[
"MIT"
] | 98
|
2015-01-28T23:23:06.000Z
|
2021-03-27T16:29:17.000Z
|
src/filters/VoronoiFilter.cpp
|
dasl-/ofxFilterLibrary
|
6e43d33b205f04706b72747e5b4ce7f45cab3e88
|
[
"MIT"
] | 5
|
2015-04-17T17:19:21.000Z
|
2017-10-27T15:46:55.000Z
|
src/filters/VoronoiFilter.cpp
|
dasl-/ofxFilterLibrary
|
6e43d33b205f04706b72747e5b4ce7f45cab3e88
|
[
"MIT"
] | 18
|
2015-07-23T02:44:31.000Z
|
2020-02-24T12:52:15.000Z
|
//
// VoronoiFilter.cpp
// filterSandbox
//
// Created by Matthew Fargo on 2014/06/23.
//
//
#include "VoronoiFilter.h"
VoronoiFilter::VoronoiFilter(ofTexture & texture) : AbstractFilter(texture.getWidth(), texture.getHeight()) {
_name = "Voronoi";
_texture = texture;
for (int i=0; i<NUM_POINTS; i++) {
_vertices[i*2] = ofRandomuf();
_vertices[i*2+1] = ofRandomuf();
_colors[i*3] = ofRandomuf();
_colors[i*3+1] = ofRandomuf();
_colors[i*3+2] = ofRandomuf();
}
_addParameter(new Parameter2fv("verts", _vertices, NUM_POINTS));
_addParameter(new Parameter3fv("colors", _colors, NUM_POINTS));
_setupShader();
}
VoronoiFilter::~VoronoiFilter() {}
string VoronoiFilter::_getFragSrc() {
string fragSrc = GLSL_STRING(120,
uniform vec2 verts[%%MAX%%];
uniform vec3 colors[%%MAX%%];
void main() {
vec2 coord = gl_TexCoord[0].xy;
float dist = 1e10;
vec3 color = vec3(1.0, 0.0, 0.0);
for (int i = 0; i < %%MAX%%; i++) {
float newdist = distance(verts[i], coord);
if (newdist < dist) {
if (dist - newdist < 0.01) {
float d = dist - newdist;
color = mix(vec3(0, 0, 0), colors[i], d/0.01);
}
else {
color = colors[i];
}
dist = newdist;
}
}
gl_FragColor = vec4(color, 1.0);
}
);
ofStringReplace(fragSrc, "%%MAX%%", ofToString(NUM_POINTS));
return fragSrc;
}
void VoronoiFilter::begin() {
_texture.readToPixels(_pixels);
for (int i=0; i<NUM_POINTS; i++) {
ofColor c = _pixels.getColor(_vertices[i*2]*getWidth(), _vertices[i*2+1]*getHeight());
_colors[i*3] = c.r/255.;
_colors[i*3+1] = c.g/255.;
_colors[i*3+2] = c.b/255.;
}
AbstractFilter::begin();
}
| 30.666667
| 109
| 0.511858
|
dasl-
|
dd7f17a6ce4b7ae61c5ebb39d303412c7b8df4c5
| 784
|
cpp
|
C++
|
ftnoir_protocol_wine/ftnoir_protocol_wine_dll.cpp
|
MaximeMorel/opentrack
|
d83db9c7cfd7ee12366032b9b0796dc63acdabb3
|
[
"ISC"
] | null | null | null |
ftnoir_protocol_wine/ftnoir_protocol_wine_dll.cpp
|
MaximeMorel/opentrack
|
d83db9c7cfd7ee12366032b9b0796dc63acdabb3
|
[
"ISC"
] | null | null | null |
ftnoir_protocol_wine/ftnoir_protocol_wine_dll.cpp
|
MaximeMorel/opentrack
|
d83db9c7cfd7ee12366032b9b0796dc63acdabb3
|
[
"ISC"
] | null | null | null |
#include "ftnoir_protocol_wine.h"
#include <QDebug>
#include "facetracknoir/global-settings.h"
FTNoIR_ProtocolDll::FTNoIR_ProtocolDll() {
}
FTNoIR_ProtocolDll::~FTNoIR_ProtocolDll()
{
}
////////////////////////////////////////////////////////////////////////////////
// Factory function that creates instances if the Protocol object.
// Export both decorated and undecorated names.
// GetProtocolDll - Undecorated name, which can be easily used with GetProcAddress
// Win32 API function.
// _GetProtocolDll@0 - Common name decoration for __stdcall functions in C language.
//#pragma comment(linker, "/export:GetProtocolDll=_GetProtocolDll@0")
extern "C" FTNOIR_PROTOCOL_BASE_EXPORT Metadata* CALLING_CONVENTION GetMetadata()
{
return new FTNoIR_ProtocolDll;
}
| 30.153846
| 88
| 0.693878
|
MaximeMorel
|
dd83132ad9e7c5ddc5d3e68ee3061b1cb08505b6
| 598
|
cpp
|
C++
|
01_Programming_Basics/01_Programming_Basics_with_C++/11_For_Loop_Exercise/07_Salary.cpp
|
Knightwalker/Knowledgebase
|
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
|
[
"MIT"
] | null | null | null |
01_Programming_Basics/01_Programming_Basics_with_C++/11_For_Loop_Exercise/07_Salary.cpp
|
Knightwalker/Knowledgebase
|
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
|
[
"MIT"
] | null | null | null |
01_Programming_Basics/01_Programming_Basics_with_C++/11_For_Loop_Exercise/07_Salary.cpp
|
Knightwalker/Knowledgebase
|
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
int n = 0;
int salary = 0;
cin >> n >> salary;
cin.ignore();
for (int i = 0; i < n; i++) {
string website = "";
getline(cin, website);
if (website == "Facebook") {
salary -= 150;
} else if (website == "Instagram") {
salary -= 100;
} else if (website == "Reddit") {
salary -= 50;
}
if (salary <= 0) {
cout << "You have lost your salary." << endl;
break;
}
}
if (salary > 0) {
cout << salary << endl;
}
return 0;
}
| 16.162162
| 51
| 0.498328
|
Knightwalker
|
dd83c3ade54f0729203dfb4ccab6dc9588e6005e
| 826
|
hpp
|
C++
|
cpp/gain-node.hpp
|
trxcllnt/webaudio-raub
|
957d68c2612a3de88e50fb8655d3d700c5a6c001
|
[
"MIT"
] | null | null | null |
cpp/gain-node.hpp
|
trxcllnt/webaudio-raub
|
957d68c2612a3de88e50fb8655d3d700c5a6c001
|
[
"MIT"
] | null | null | null |
cpp/gain-node.hpp
|
trxcllnt/webaudio-raub
|
957d68c2612a3de88e50fb8655d3d700c5a6c001
|
[
"MIT"
] | null | null | null |
#ifndef _GAIN_NODE_HPP_
#define _GAIN_NODE_HPP_
#include <addon-tools.hpp>
#include "audio-node.hpp"
class GainNode : public AudioNode {
public:
~GainNode();
// Public V8 init
static void init(V8_VAR_OBJ target);
// Make a new instance from C++ land
static V8_VAR_OBJ getNew(V8_VAR_OBJ context);
// Destroy an instance from C++ land
void _destroy();
// Methods and props, available for children
protected:
explicit GainNode(V8_VAR_OBJ context);
static V8_STORE_FT _protoGainNode;
static V8_STORE_FUNC _ctorGainNode;
bool _isDestroyed;
V8_STORE_OBJ _gain;
// JS methods and props, available through V8 APIs
private:
static NAN_METHOD(newCtor);
static NAN_METHOD(destroy);
static NAN_GETTER(isDestroyedGetter);
static NAN_GETTER(gainGetter);
};
#endif // _GAIN_NODE_HPP_
| 15.584906
| 50
| 0.739709
|
trxcllnt
|
dd879f9f84b93c3827ff135e4becb188a456aa89
| 352
|
cpp
|
C++
|
Observer/Observer/Viewers/RadioViewer.cpp
|
jayavardhanravi/DesignPatterns
|
aa6a37790f447c7caf69c6a1a9c6107074309a03
|
[
"BSD-2-Clause"
] | 8
|
2020-01-23T23:20:40.000Z
|
2022-01-08T13:04:08.000Z
|
Observer/Observer/Viewers/RadioViewer.cpp
|
jayavardhanravi/DesignPatterns
|
aa6a37790f447c7caf69c6a1a9c6107074309a03
|
[
"BSD-2-Clause"
] | null | null | null |
Observer/Observer/Viewers/RadioViewer.cpp
|
jayavardhanravi/DesignPatterns
|
aa6a37790f447c7caf69c6a1a9c6107074309a03
|
[
"BSD-2-Clause"
] | 1
|
2020-01-28T14:27:54.000Z
|
2020-01-28T14:27:54.000Z
|
#include "RadioViewer.h"
RadioViewer::RadioViewer(const std::string &name) : name_(name)
{
}
RadioViewer::~RadioViewer()
{
}
void RadioViewer::GetUpdates(const std::string& dataObtained)
{
dataObtained_ = dataObtained;
std::cout << "[RADIO] "<< name_ << " : " << dataObtained_ << std::endl;
}
std::string RadioViewer::GetKey()
{
return name_;
}
| 16.761905
| 72
| 0.681818
|
jayavardhanravi
|
dd946ecdbff8bbc29fc41b829d5c1e4bdbaf93d4
| 443
|
hpp
|
C++
|
src/Surface.hpp
|
Seek/RayTracing
|
24978d83a98d9c1c4d545cddfa38be9c6279663f
|
[
"MIT"
] | null | null | null |
src/Surface.hpp
|
Seek/RayTracing
|
24978d83a98d9c1c4d545cddfa38be9c6279663f
|
[
"MIT"
] | null | null | null |
src/Surface.hpp
|
Seek/RayTracing
|
24978d83a98d9c1c4d545cddfa38be9c6279663f
|
[
"MIT"
] | null | null | null |
#ifndef SURFACE_HPP
#define SURFACE_HPP
#pragma once
#include "Ray.hpp"
#include "Transform.hpp"
#include "LocalSurface.hpp"
class Surface {
public:
Surface() {}
Surface(const Transform& _obj2world, const Transform& _world2obj)
: obj2world(_obj2world), world2obj(_world2obj) {}
virtual bool intersect(const Ray& r, float* tHit, std::shared_ptr<LocalSurface>& ls) const = 0;
Transform obj2world, world2obj;
};
#endif // !SURFACE_HPP
| 21.095238
| 96
| 0.744921
|
Seek
|
dd96b4bed6fa2b33e921124d6bd639f6628b9172
| 3,518
|
cpp
|
C++
|
MonoNative/mscorlib/System/Runtime/Serialization/Formatters/mscorlib_System_Runtime_Serialization_Formatters_IFieldInfo.cpp
|
brunolauze/MonoNative
|
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
|
[
"BSD-2-Clause"
] | 7
|
2015-03-10T03:36:16.000Z
|
2021-11-05T01:16:58.000Z
|
MonoNative/mscorlib/System/Runtime/Serialization/Formatters/mscorlib_System_Runtime_Serialization_Formatters_IFieldInfo.cpp
|
brunolauze/MonoNative
|
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
|
[
"BSD-2-Clause"
] | 1
|
2020-06-23T10:02:33.000Z
|
2020-06-24T02:05:47.000Z
|
MonoNative/mscorlib/System/Runtime/Serialization/Formatters/mscorlib_System_Runtime_Serialization_Formatters_IFieldInfo.cpp
|
brunolauze/MonoNative
|
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
|
[
"BSD-2-Clause"
] | null | null | null |
#include <mscorlib/System/Runtime/Serialization/Formatters/mscorlib_System_Runtime_Serialization_Formatters_IFieldInfo.h>
#include <mscorlib/System/mscorlib_System_String.h>
#include <mscorlib/System/mscorlib_System_Type.h>
namespace mscorlib
{
namespace System
{
namespace Runtime
{
namespace Serialization
{
namespace Formatters
{
//Get Set Properties Methods
// Get/Set:FieldNames
std::vector<mscorlib::System::String*> IFieldInfo::get_FieldNames() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Runtime.Serialization.Formatters", "IFieldInfo", 0, NULL, "get_FieldNames", __mscorlib_System_Runtime_Serialization_Formatters_IFieldInfo, 0, NULL, NULL, NULL);
MonoArray *__array_ptr__ = (MonoArray*)__result__;
uintptr_t __array_length__ = mono_array_length(__array_ptr__);
std::vector<mscorlib::System::String*> __array_result__(__array_length__);
for(uintptr_t __array_index__ = 0; __array_index__ < __array_length__; __array_index__++)
{
MonoObject *__array_item__ = mono_array_get(__array_ptr__,MonoObject*,__array_index__);
__array_result__.push_back(new mscorlib::System::String (__array_item__));
}
return __array_result__;
}
void IFieldInfo::set_FieldNames(std::vector<mscorlib::System::String*> value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "String")), 1));
__parameters__[0] = Global::FromArray<mscorlib::System::String*>(value, typeid(mscorlib::System::String).name());
Global::InvokeMethod("mscorlib", "System.Runtime.Serialization.Formatters", "IFieldInfo", 0, NULL, "set_FieldNames", __mscorlib_System_Runtime_Serialization_Formatters_IFieldInfo, 1, __parameter_types__, __parameters__, NULL);
}
// Get/Set:FieldTypes
std::vector<mscorlib::System::Type*> IFieldInfo::get_FieldTypes() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Runtime.Serialization.Formatters", "IFieldInfo", 0, NULL, "get_FieldTypes", __mscorlib_System_Runtime_Serialization_Formatters_IFieldInfo, 0, NULL, NULL, NULL);
MonoArray *__array_ptr__ = (MonoArray*)__result__;
uintptr_t __array_length__ = mono_array_length(__array_ptr__);
std::vector<mscorlib::System::Type*> __array_result__(__array_length__);
for(uintptr_t __array_index__ = 0; __array_index__ < __array_length__; __array_index__++)
{
MonoObject *__array_item__ = mono_array_get(__array_ptr__,MonoObject*,__array_index__);
__array_result__.push_back(new mscorlib::System::Type (__array_item__));
}
return __array_result__;
}
void IFieldInfo::set_FieldTypes(std::vector<mscorlib::System::Type*> value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Type")), 1));
__parameters__[0] = Global::FromArray<mscorlib::System::Type*>(value, typeid(mscorlib::System::Type).name());
Global::InvokeMethod("mscorlib", "System.Runtime.Serialization.Formatters", "IFieldInfo", 0, NULL, "set_FieldTypes", __mscorlib_System_Runtime_Serialization_Formatters_IFieldInfo, 1, __parameter_types__, __parameters__, NULL);
}
}
}
}
}
}
| 46.906667
| 232
| 0.738772
|
brunolauze
|
dd9ee8829fdfde6e1febff2a3843705c52838dc1
| 540
|
cpp
|
C++
|
source/476.cpp
|
narikbi/LeetCode
|
835215c21d1bd6820b20c253026bcb6f889ed3fc
|
[
"MIT"
] | 2
|
2017-02-28T11:39:13.000Z
|
2019-12-07T17:23:20.000Z
|
source/476.cpp
|
narikbi/LeetCode
|
835215c21d1bd6820b20c253026bcb6f889ed3fc
|
[
"MIT"
] | null | null | null |
source/476.cpp
|
narikbi/LeetCode
|
835215c21d1bd6820b20c253026bcb6f889ed3fc
|
[
"MIT"
] | null | null | null |
//
// 476.cpp
// LeetCode
//
// Created by Narikbi on 15.02.17.
// Copyright © 2017 app.leetcode.kz. All rights reserved.
//
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <deque>
#include <queue>
#include <set>
using namespace std;
int findComplement(int num) {
int mask = ~0;
while (num & mask) {
mask <<= 1;
}
return ~mask & ~num;
}
//int main(int argc, const char * argv[]) {
// cout << findComplement(5);
// return 0;
//}
//
//
| 14.594595
| 58
| 0.585185
|
narikbi
|
dd9fd231b65c903c2ec0d15f77801eb7340660c9
| 2,467
|
cpp
|
C++
|
StackedPlot/src/StackedPlot.cpp
|
ofnode/openFrameworksDemos
|
ae7d2f9f43884ef54bec44420994c49e2bf8081a
|
[
"MIT"
] | 75
|
2015-02-03T14:42:44.000Z
|
2021-09-17T00:54:56.000Z
|
StackedPlot/src/StackedPlot.cpp
|
ofnode/openFrameworksDemos
|
ae7d2f9f43884ef54bec44420994c49e2bf8081a
|
[
"MIT"
] | 1
|
2016-11-15T16:02:21.000Z
|
2016-11-15T16:02:21.000Z
|
StackedPlot/src/StackedPlot.cpp
|
ofnode/openFrameworksDemos
|
ae7d2f9f43884ef54bec44420994c49e2bf8081a
|
[
"MIT"
] | 16
|
2015-05-05T19:17:09.000Z
|
2018-08-15T11:57:46.000Z
|
#include "StackedPlot.h"
float sum(const vector<float>& x) {
float sum = 0;
for(int i = 0; i < x.size(); i++) {
sum += x[i];
}
return sum;
}
vector<float> divide(const vector<float>& x, float y) {
vector<float> out = x;
for(int i = 0; i < out.size(); i++) {
out[i] /= y;
}
return out;
}
vector<float> normalize(const vector<float>& x) {
float summed = sum(x);
return divide(x, summed);
}
vector<float> accumulate(const vector<float>& x) {
vector<float> out = x;
for(int i = 1; i < out.size(); i++) {
out[i] += out[i - 1];
}
return out;
}
StackedPlot::StackedPlot()
:historyLength(100) {
}
void StackedPlot::clear() {
history.clear();
}
void StackedPlot::addData(const vector<float>& data) {
if(size() && data.size() != dimensions()) {
ofLogWarning("StackedPlot") << "added data does not have same size as existing data";
clear();
}
vector<float> normalized = normalize(data);
vector<float> accumulated = accumulate(normalized);
vector<float> all;
all.push_back(0);
all.insert(all.end(), accumulated.begin(), accumulated.end());
all.push_back(1);
history.push_back(all);
while(history.size() > historyLength) {
history.pop_front();
}
}
void StackedPlot::addColor(ofColor color) {
colors.push_back(color);
}
int StackedPlot::size() const {
return history.size();
}
int StackedPlot::dimensions() const {
return size() ? history.front().size() - 2 : 0;
}
void StackedPlot::draw(float width, float height) const {
ofPushMatrix();
ofPushStyle();
int d = dimensions();
vector<ofMesh> meshes(d);
for(int i = 0; i < d; i++) {
meshes[i].setMode(OF_PRIMITIVE_TRIANGLE_STRIP);
}
list<vector<float> >::const_iterator itr;
int i;
for(itr = history.begin(), i = 0; itr != history.end(); itr++, i++) {
const vector<float>& cur = *itr;
for(int j = 0; j < d; j++) {
meshes[j].addVertex(ofVec2f(i, cur[j]));
meshes[j].addVertex(ofVec2f(i, cur[j + 1]));
}
}
ofScale(width / (historyLength - 1), height);
for(int i = 0; i < d; i++) {
if(colors.size()) {
ofSetColor(colors[i % colors.size()]);
} else {
float hue = ofMap(i, 0, d, 0, 255);
ofSetColor(ofColor::fromHsb(hue, 255, 255));
}
meshes[i].draw();
}
ofPopMatrix();
ofPopStyle();
}
| 26.815217
| 93
| 0.566275
|
ofnode
|
dda031ae4dd3480aa28c59c63fd348dfdc237587
| 1,654
|
hh
|
C++
|
src/gmm/test/src/util.hh
|
juliia5m/knu_voice
|
1f5d150ded23af4c152b8d20f1ab4ecec77b40e1
|
[
"Apache-2.0"
] | 717
|
2015-01-03T15:25:46.000Z
|
2022-03-30T12:45:45.000Z
|
src/gmm/test/src/util.hh
|
juliia5m/knu_voice
|
1f5d150ded23af4c152b8d20f1ab4ecec77b40e1
|
[
"Apache-2.0"
] | 91
|
2015-03-19T09:25:23.000Z
|
2021-05-19T08:51:26.000Z
|
src/gmm/test/src/util.hh
|
juliia5m/knu_voice
|
1f5d150ded23af4c152b8d20f1ab4ecec77b40e1
|
[
"Apache-2.0"
] | 315
|
2015-01-21T00:06:00.000Z
|
2022-03-29T08:13:36.000Z
|
/*
* $File: util.hh
* $Date: Tue Dec 24 16:46:50 2013 +0800
* $Author: Xinyu Zhou <zxytim[at]gmail[dot]com>
*/
#pragma once
#include "type.hh"
#include <cassert>
#include <vector>
using namespace std;
#if 0
static vector<real_t> random_vector(int dim, real_t range, Random &random) {
vector<real_t> vec(dim);
for (auto &v: vec) v = random.rand_real() * range;
return vec;
}
#endif
static void add(const vector<real_t> &a, const vector<real_t> &b, vector<real_t> &c) {
assert(a.size() == b.size() && b.size() == c.size());
size_t n = a.size();
for (size_t i = 0; i < n; i ++)
c[i] = a[i] + b[i];
}
static void sub(const vector<real_t> &a, const vector<real_t> &b, vector<real_t> &c) {
assert(a.size() == b.size() && b.size() == c.size());
size_t n = a.size();
for (size_t i = 0; i < n; i ++)
c[i] = a[i] - b[i];
}
#if 0
static void mult(const vector<real_t> &a, const vector<real_t> &b, vector<real_t> &c) {
assert(a.size() == b.size() && b.size() == c.size());
size_t n = a.size();
for (size_t i = 0; i < n; i ++)
c[i] = a[i] * b[i];
}
#endif
static void mult(const vector<real_t> &a, real_t f, vector<real_t> &b) {
assert(a.size() == b.size());
size_t n = a.size();
for (size_t i = 0; i < n; i ++)
b[i] = a[i] * f;
}
static void add_self(vector<real_t> &a, const vector<real_t> &b) {
add(a, b, a);
}
static void sub_self(vector<real_t> &a, const vector<real_t> &b) {
sub(a, b, a);
}
#if 0
static void mult_self(vector<real_t> &a, const vector<real_t> &b) {
mult(a, b, a);
}
#endif
static void mult_self(vector<real_t> &a, real_t f) {
mult(a, f, a);
}
/**
* vim: syntax=cpp11.doxygen foldmethod=marker
*/
| 21.480519
| 87
| 0.598549
|
juliia5m
|
ddaa6de0dc09a0c6d7d70588bc8a9f476b6cbf0f
| 397
|
hpp
|
C++
|
include/bus.hpp
|
c1m5j/bpp
|
669220ebfbee57822028d13fa3a5a48a3e73ee85
|
[
"MIT"
] | 2
|
2021-07-30T14:46:04.000Z
|
2021-07-30T14:58:52.000Z
|
include/bus.hpp
|
c1m5j/bpp
|
669220ebfbee57822028d13fa3a5a48a3e73ee85
|
[
"MIT"
] | 2
|
2021-07-30T13:13:18.000Z
|
2021-07-30T13:42:50.000Z
|
include/bus.hpp
|
c1m5j/bpp
|
669220ebfbee57822028d13fa3a5a48a3e73ee85
|
[
"MIT"
] | 1
|
2021-07-30T13:03:12.000Z
|
2021-07-30T13:03:12.000Z
|
#pragma once
/**
* A simple "system bus" which allows for interconnection between
* components, saving us passing pointers or references to each
* other every function call.
*/
class CPU;
class Display;
class Audio;
class Memory;
class Input;
class Bus {
public:
Bus();
~Bus();
Memory* memory;
CPU* cpu;
Display* display;
Audio* audio;
Input* input;
};
| 15.88
| 65
| 0.649874
|
c1m5j
|
ddb3097015a120c4d0ae3b76f584c561ff429374
| 1,315
|
hpp
|
C++
|
src/fixie_lib/null_impl/context.hpp
|
vonture/fixie
|
7fa1a6787ae26ee141a906fe39fb85c2e3cf4dfc
|
[
"MIT"
] | 7
|
2015-01-09T22:08:17.000Z
|
2021-10-12T10:32:58.000Z
|
src/fixie_lib/null_impl/context.hpp
|
vonture/fixie
|
7fa1a6787ae26ee141a906fe39fb85c2e3cf4dfc
|
[
"MIT"
] | 1
|
2015-08-19T07:51:53.000Z
|
2015-08-19T07:51:53.000Z
|
src/fixie_lib/null_impl/context.hpp
|
vonture/fixie
|
7fa1a6787ae26ee141a906fe39fb85c2e3cf4dfc
|
[
"MIT"
] | 5
|
2015-08-20T07:10:23.000Z
|
2022-03-24T07:09:10.000Z
|
#ifndef _FIXIE_LIB_NULL_CONTEXT_HPP_
#define _FIXIE_LIB_NULL_CONTEXT_HPP_
#include "fixie_lib/context.hpp"
namespace fixie
{
namespace null_impl
{
class context : public fixie::context_impl
{
public:
virtual const fixie::caps& caps() override;
virtual const std::string& renderer_desc() override;
virtual void initialize_state(fixie::state& state) override;
virtual std::unique_ptr<texture_impl> create_texture() override;
virtual std::unique_ptr<renderbuffer_impl> create_renderbuffer() override;
virtual std::unique_ptr<framebuffer_impl> create_default_framebuffer() override;
virtual std::unique_ptr<framebuffer_impl> create_framebuffer() override;
virtual std::unique_ptr<buffer_impl> create_buffer() override;
virtual void draw_arrays(const state& state, GLenum mode, GLint first, GLsizei count) override;
virtual void draw_elements(const state& state, GLenum mode, GLsizei count, GLenum type, const GLvoid* indices) override;
virtual void clear(const state& state, GLbitfield mask) override;
virtual void flush() override;
virtual void finish() override;
};
}
}
#endif // _FIXIE_LIB_NULL_CONTEXT_HPP_
| 36.527778
| 132
| 0.686692
|
vonture
|
ddc1c869618ff0a13d652fe6fd3d26f1dba5bf16
| 10,834
|
hpp
|
C++
|
example/ccana/source/ProjectConeETCC.hpp
|
goroyabu/anlpy
|
2d5d65b898d31d69f990e973cbfdbabd8cb0a15c
|
[
"MIT"
] | null | null | null |
example/ccana/source/ProjectConeETCC.hpp
|
goroyabu/anlpy
|
2d5d65b898d31d69f990e973cbfdbabd8cb0a15c
|
[
"MIT"
] | null | null | null |
example/ccana/source/ProjectConeETCC.hpp
|
goroyabu/anlpy
|
2d5d65b898d31d69f990e973cbfdbabd8cb0a15c
|
[
"MIT"
] | null | null | null |
/***
@file ProjectConeETCC.hpp
@date
@author User
@detail Automatically generated by mkanlproject
***/
#ifndef ProjectConeETCC_hpp
#define ProjectConeETCC_hpp
#include <tuple>
#include <TFile.h>
#include <TTree.h>
#include <TH2D.h>
#include <TH3F.h>
#include <TMath.h>
#include <TVector3.h>
#include <TF1.h>
#include <VANL_Module.hpp>
class ComptreeEvent
{
private:
TTree* tree;
long nentries;
long current_entry;
public:
int merged_si_nhit;
std::vector<double> merged_epi_si;
int n_reconst;
std::vector<double> epi1;
std::vector<double> epi2;
std::vector<double> reconst_epi;
std::vector<double> cdte_detx;
std::vector<double> cdte_dety;
std::vector<double> cdte_detz;
double epi_total;
int n_pixel;
std::vector<double> epi_pixel_value;
std::vector<double> cmos_detx;
std::vector<double> cmos_dety;
double min_cmos_detx;
double min_cmos_dety;
double eigen_ratio;
double sum_pixel_value_around_init;
double sum_pixel_value_around_end;
bool reconstructed;
double init_pos_cmos_detx;
double init_pos_cmos_dety;
double init_pos_cmos_detz;
double phi_cmos_det;
ComptreeEvent()
: tree(nullptr)
{}
inline bool ExistBranch(TTree* tree, TString key)
{
if ( !tree->FindBranch(key) ) {
std::cout << "TBranch " << key;
std::cout << " is not found." << std::endl;
return false;
}
return true;
}
inline bool ExistBranch(TString key)
{
return ExistBranch( this->tree, key);
}
inline bool Next()
{
++current_entry;
if ( current_entry>=nentries ) return false;
auto bytes = tree->GetEntry(current_entry);
// const static int max_bytes = 5000;
// if ( bytes>max_bytes ) {
// std::cout << "*Warning* : Entry " << current_entry << " has too big bytes to read (" << bytes << " bytes). ";
// std::cout << "Disabling unread branches can reduce the bytes." << std::endl;
// }
return true;
}
inline long long int GetEntries() const
{
return this->nentries;
}
int SetBranchAddress(TTree* tree);
};
class ProjectConeETCC : public anl::VANL_Module
{
public:
ProjectConeETCC();
~ProjectConeETCC();
int mod_bgnrun() override;
int mod_ana() override;
int mod_endrun() override;
protected:
TFile * input_file;
TTree * input_tree;
TFile * output_file;
TTree * output_tree;
TH3F * image;
TH3F * image_etcc;
TH1D * h1_cone_filling_ratio;
TH1D * h1_arm_distribution;
TH1D * h1_spd_distribution;
TH2D * h2_arm_vs_spd;
TH2D * h2_arm_distribition;
TH2D * h2_spd_distribition;
TH2D * h2_ene_cmos_vs_cdte;
TH1D * h1_ene_sum_cmos_cdte;
ComptreeEvent event;
/** parameters */
double cone_thick_rad;
double arc_length_rad;
double arc_length_sigma;
double tangent_cone_thick;
double distance_index_omega;
double e_threshold_si;
double e_threshold_cdte;
double e_window_begin;
double e_window_end;
double theta_max_degree;
double detector_z_position;
bool is_event_list_only;
double rotation_around_vertical_rad;
bool enable_reject_fluor;
bool enable_normalize_cone;
double eigen_ratio_threshold;
double pixel_ratio_threshold;
bool is_used_polar_coordinate;
TVector3 source_position;
/* branch */
/* inherited from eventtree */
unsigned int ti;
unsigned int livetime;
unsigned int unixtime;
unsigned int ext1pps;
unsigned int msec_counter;
/* new branches */
int num_hits;
unsigned int externalCLK;
unsigned int first_internalCLK;
short hit1_detector;
float hit1_energy;
float hit1_posx;
float hit1_posy;
float hit1_posz;
short hit2_detector;
float hit2_energy;
float hit2_posx;
float hit2_posy;
float hit2_posz;
short hit3_detector;
float hit3_energy;
float hit3_posx;
float hit3_posy;
float hit3_posz;
float totalenergy;
float theta_kine;
float theta_geom;
float theta_elec;
float phi_esti;
float phi_geom;
float angle_inci;
float de_over_dx;
float prod_inci_phi;
float sum_epi_around_init;
float sum_epi_forward_init;
std::vector<float> vector_incident;
std::vector<float> vector_photon;
std::vector<float> vector_electron;
float angle_electron_on_plane;
float angle_electron_vertical;
/* for CMOS energy correction */
TH1D * param2_cdtez;
TF1 * si_ee_lo;
TF1 * si_ee_up;
TH2D * etrack_calc_dedx;
private :
struct Hit
{
private :
double x, y, z;
double energy;
double phi;
public :
Hit(double x, double y, double z, double energy, double phi)
: x(x), y(y), z(z), energy(energy), phi(phi)
{}
Hit(const Hit& other)
: x(other.x), y(other.y), z(other.z),
energy(other.energy), phi(other.phi)
{}
Hit& operator=(const Hit& other)
{
x = other.x;
y = other.y;
z = other.z;
energy = other.energy;
phi = other.phi;
return *this;
}
TVector3 Postion() const
{
return TVector3(x,y,z);
}
double Energy() const
{
return energy;
}
double Phi() const
{
return phi;
}
};
private:
int DefineBranch(TTree* tree);
void CalcComptonEvent(const Hit& si, const Hit& cdte);
bool Projection(const Hit& si, const Hit& cdte);
TH1D* GetFillingRatio
(TH3F* image, const TVector3& scat, const TVector3& abso, double angle_theta_rad);
double ScaleByFillingRatio(TH3F* th3, TH1D* ratio);
inline static double ComptonTheta(double scat, double abso)
{
static const double mass_of_electron = 511.0;
auto costheta = 1 - mass_of_electron * ( 1/abso - 1/(scat+abso) );
if ( costheta<-1.0 || 1.0<costheta ) return -1;
return std::fabs( TMath::ACos(costheta) );
}
inline bool IsInEnergyWindow(const double total_energy) const
{
if ( this->e_window_begin<=total_energy && total_energy<=this->e_window_end )
return true;
return false;
}
inline bool IsInThetaRange(const Hit& scat, const Hit& abso) const
{
auto theta = ComptonTheta( scat.Energy(), abso.Energy() );
if ( 0<theta && theta<=this->theta_max_degree )
return true;
return false;
}
inline static bool IsFluor(double energy)
{
return 21.0<energy && energy<=28.0;
}
inline static TVector3 VoxelCenter(TH3* h, int bin)
{
int xbin, ybin, zbin;
h->GetBinXYZ( bin, xbin, ybin, zbin );
auto x = h->GetXaxis()->GetBinCenter(xbin);
auto y = h->GetYaxis()->GetBinCenter(ybin);
auto z = h->GetZaxis()->GetBinCenter(zbin);
return TVector3(x, y, z);
}
inline static TVector3 VoxelCenterPolar(TH3* h, int bin)
{
int xbin, ybin, zbin;
h->GetBinXYZ( bin, xbin, ybin, zbin );
auto x = h->GetXaxis()->GetBinCenter(xbin);
auto y = h->GetYaxis()->GetBinCenter(ybin);
auto radius = h->GetZaxis()->GetBinCenter(zbin);
auto theta = TVector2::Phi_mpi_pi( TMath::Sqrt( x*x + y*y ) );
auto x_in_3d = radius * TMath::Sin( theta ) * x / theta;
auto y_in_3d = radius * TMath::Sin( theta ) * y / theta;
auto z_in_3d = radius * TMath::Cos( theta );
return TVector3( x_in_3d, y_in_3d, z_in_3d );
}
inline static double GetBinContent(TH1D* h, double x)
{
auto bin = h->GetXaxis()->FindBin(x);
if ( 1 <= bin && bin <= h->GetXaxis()->GetNbins() )
return h->GetBinContent(bin);
return 0.0;
}
inline static bool IsVectorInside( TH3F* image, const TVector3& vec)
{
auto x = image->GetXaxis()->GetXmin() <= vec.X() &&
vec.X() <= image->GetXaxis()->GetXmax();
if ( x == false ) return false;
auto y = image->GetYaxis()->GetXmin() <= vec.Y() &&
vec.Y() <= image->GetYaxis()->GetXmax();
if ( y == false ) return false;
auto z = image->GetZaxis()->GetXmin() <= vec.Z() &&
vec.Z() <= image->GetZaxis()->GetXmax();
return z;
}
inline static TVector3 ElectronVector(TVector3 norm_inci, TVector3 norm_photon, const double e_electron, const double e_photon)
{
static const double mass_of_electron = 511.0;
double val = TMath::Sqrt( e_electron * (e_electron+2*mass_of_electron));
norm_inci *= (e_electron+e_photon)/val;
norm_photon *= e_photon/val;
return norm_inci + norm_photon;
}
inline static std::tuple<double,double> VectorToAlphaBeta(const TVector3& vec)
{
auto x = vec.X(); auto y = vec.Y(); auto z = vec.Z();
auto alpha_norm = TMath::Sqrt( x*x + y*y );
auto alpha_x = x/alpha_norm; auto alpha_y = y/alpha_norm;
auto alpha = TVector2::Phi_mpi_pi( TMath::ACos(alpha_x) );
if ( alpha_y < 0.0 ) alpha *= -1.0;
alpha = TVector2::Phi_mpi_pi( alpha + TMath::Pi() * 0.5 );
auto beta_norm = TMath::Sqrt( x*x + y*y + z*z );
auto beta_z = z/beta_norm;
auto beta = TMath::ASin(beta_z);
if ( beta_z < 0.0 ) beta *= -1.0;
return std::make_tuple(alpha, beta);
}
};
#endif
| 30.866097
| 135
| 0.53729
|
goroyabu
|
ddcfac6bbb06a1712fc7b742efe68a75f9acc3da
| 3,420
|
hxx
|
C++
|
Modules/Core/include/selxInterfaceAcceptor.hxx
|
FBerendsen/SuperElastix-1
|
69d97589e34f6f2109621e917792ce18e32442fe
|
[
"Apache-2.0"
] | null | null | null |
Modules/Core/include/selxInterfaceAcceptor.hxx
|
FBerendsen/SuperElastix-1
|
69d97589e34f6f2109621e917792ce18e32442fe
|
[
"Apache-2.0"
] | null | null | null |
Modules/Core/include/selxInterfaceAcceptor.hxx
|
FBerendsen/SuperElastix-1
|
69d97589e34f6f2109621e917792ce18e32442fe
|
[
"Apache-2.0"
] | null | null | null |
/*=========================================================================
*
* Copyright Leiden University Medical Center, Erasmus University Medical
* Center and contributors
*
* 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.txt
*
* 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 InterfaceAcceptor_hxx
#define InterfaceAcceptor_hxx
#include "selxConnectionInfo.h"
namespace selx
{
template< class InterfaceT >
int
InterfaceAcceptor< InterfaceT >::Connect( ComponentBase::Pointer providerComponent )
{
// Here the core of the handshake mechanism takes place: One specific
// interface of the Providing Component is taken (by dynamic_cast) and
// passed to the accepting Component.
// The function returns the number of successful connects (1 or 0)
std::shared_ptr< InterfaceT > providerInterface = std::dynamic_pointer_cast< InterfaceT >( providerComponent );
if( !providerInterface )
{
// casting failed: this Providing Component does not have the specific interface.
return 0;
}
// connect value interfaces
this->Accept( providerInterface ); // due to the input argument being uniquely defined in the multiple inheritance tree, all versions of Set() are accessible at component level
// store the interface for access by the user defined component
this->m_AcceptedInterface = providerInterface;
// TODO: see if we can get rid of all (dynamic) casts below. Perhaps a "static_cast in release mode"?
auto providerConnectionInfo = std::dynamic_pointer_cast<ConnectionInfo< InterfaceT >>( providerComponent);
if (!providerConnectionInfo)
{
// By definition should not fail, since providerComponent always is a base
// class pointer of an SuperElastixComponent object and
// SuperElastixComponents that are derived from InterfaceT (checked
// previously) also derive from ConnectionInfo< InterfaceT>
throw std::runtime_error( "std::dynamic_pointer_cast<ConnectionInfo< InterfaceT > should not fail by definition " );
}
ComponentBase* AcceptorBaseComponent = dynamic_cast<ComponentBase*>( this );
if (!AcceptorBaseComponent)
{
// By definition should not fail, since 'this', the AcceptorInterface, and
// ComponentBase are both base classes from the SuperElastixComponent
// object on which this functionality is called.
throw std::runtime_error("dynamic_cast<ComponentBase*> should not fail by definition ");
}
providerConnectionInfo->SetProvidedTo(AcceptorBaseComponent->m_Name);
return 1;
}
template< class InterfaceT >
bool
InterfaceAcceptor< InterfaceT >::CanAcceptConnectionFrom( ComponentBase::ConstPointer providerComponent )
{
std::shared_ptr< const InterfaceT > providerInterface = std::dynamic_pointer_cast< const InterfaceT >( providerComponent );
return bool(providerInterface);
}
} //end namespace selx
#endif // InterfaceAcceptor_hxx
| 42.222222
| 178
| 0.724854
|
FBerendsen
|
dddc4b62fb7d0812d0e57d625619d5f7535eaa39
| 151
|
hpp
|
C++
|
MeetingCodes/Meeting4/Square.hpp
|
SubhoB/spectre-cpp-basics
|
0f581b879e83e88d1491b31e22aa447419d471a3
|
[
"MIT"
] | 15
|
2020-06-01T19:48:57.000Z
|
2021-11-01T07:33:42.000Z
|
MeetingCodes/Meeting4/Square.hpp
|
SubhoB/spectre-cpp-basics
|
0f581b879e83e88d1491b31e22aa447419d471a3
|
[
"MIT"
] | 1
|
2020-06-02T02:43:41.000Z
|
2020-06-02T03:55:50.000Z
|
MeetingCodes/Meeting4/Square.hpp
|
SubhoB/spectre-cpp-basics
|
0f581b879e83e88d1491b31e22aa447419d471a3
|
[
"MIT"
] | 6
|
2020-06-23T22:36:56.000Z
|
2021-06-14T14:46:49.000Z
|
#pragma once
#include "Rectangle.hpp"
class Square : public Rectangle {
public:
Square(double length) noexcept;
double Perimeter() noexcept;
};
| 15.1
| 33
| 0.728477
|
SubhoB
|
dddeeaf6474b1f0cfe3eec6b030994d2bf4b3cf1
| 2,603
|
cc
|
C++
|
src/simplesat/bin_algebra/binary_op.cc
|
evmaus/ClusterSAT
|
d26ff539fe9789611e9ecd8ef5c14a19e150105b
|
[
"Apache-2.0"
] | null | null | null |
src/simplesat/bin_algebra/binary_op.cc
|
evmaus/ClusterSAT
|
d26ff539fe9789611e9ecd8ef5c14a19e150105b
|
[
"Apache-2.0"
] | null | null | null |
src/simplesat/bin_algebra/binary_op.cc
|
evmaus/ClusterSAT
|
d26ff539fe9789611e9ecd8ef5c14a19e150105b
|
[
"Apache-2.0"
] | null | null | null |
// 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 "src/simplesat/bin_algebra/binary_op.h"
#include <iostream>
namespace simplesat {
namespace binary {
BinaryOp::BinaryOp(BinaryType type, const Function& lhs, const Function& rhs)
: Function(NodeType::OP),
op_type_(type), lhs_(lhs), rhs_(rhs)
{}
BinaryOp BinaryOp::And(Function& lhs, Function& rhs)
{
return BinaryOp(BinaryType::AND, lhs, rhs);
}
BinaryOp BinaryOp::Or(Function& lhs, Function& rhs)
{
return BinaryOp(BinaryType::OR, lhs, rhs);
}
BinaryOp BinaryOp::Xor(Function& lhs, Function& rhs)
{
return BinaryOp(BinaryType::XOR, lhs, rhs);
}
BinaryOp BinaryOp::Implies(Function& lhs, Function& rhs)
{
return BinaryOp(BinaryType::IMPLIES, lhs, rhs);
}
BinaryOp BinaryOp::IFF(Function& lhs, Function& rhs)
{
return BinaryOp(BinaryType::IFF, lhs, rhs);
}
bool BinaryOp::Evaluate(VariableEnvironment env) const
{
bool lhs = lhs_.Evaluate(env);
bool rhs = rhs_.Evaluate(env);
switch(op_type_)
{
case BinaryType::XOR:
return lhs ? !rhs : rhs;
case BinaryType::AND:
return (lhs && rhs);
case BinaryType::OR:
return (lhs || rhs);
case BinaryType::IMPLIES:
return lhs ? rhs : true;
case BinaryType::IFF:
return lhs == rhs;
}
}
std::set<std::string> BinaryOp::GetVariables() const {
auto lhs = lhs_.GetVariables();
auto rhs = rhs_.GetVariables();
for (auto it = rhs.begin(); it != rhs.end(); it++){
lhs.insert(*it);
}
return lhs;
}
std::string BinaryOp::to_string() const {
std::string lhs = lhs_.to_string();
std::string rhs = rhs_.to_string();
switch(op_type_) {
case BinaryType::XOR:
return "(" + lhs + " ^ " + rhs + ")";
case BinaryType::AND:
return "(" + lhs + " & " + rhs + ")";
case BinaryType::OR:
return "(" + lhs + " | " + rhs + ")";
case BinaryType::IMPLIES:
return "(" + lhs + " -> " + rhs + ")";
case BinaryType::IFF:
return "(" + lhs + " <-> " + rhs + ")";
}
}
} // namespace binary
} // namespace simplesat
| 25.772277
| 78
| 0.644257
|
evmaus
|
50b45c10d785f44c98c6d89637b444c06d2f50c0
| 5,293
|
cc
|
C++
|
misc.cc
|
stealth/loaded
|
cebc149cdbdf2f1f21037518888f4c118adcc2dd
|
[
"BSD-4-Clause"
] | 4
|
2015-03-29T00:19:29.000Z
|
2021-04-13T17:25:47.000Z
|
misc.cc
|
stealth/loaded
|
cebc149cdbdf2f1f21037518888f4c118adcc2dd
|
[
"BSD-4-Clause"
] | null | null | null |
misc.cc
|
stealth/loaded
|
cebc149cdbdf2f1f21037518888f4c118adcc2dd
|
[
"BSD-4-Clause"
] | 2
|
2015-05-19T09:35:55.000Z
|
2016-01-28T09:46:45.000Z
|
#include <cstdio>
#include <cerrno>
#include <stdint.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <unistd.h>
#include <map>
#include <sched.h>
#include "packet.h"
#include "strategy.h"
#include "config.h"
namespace loaded {
using namespace std;
unsigned short in_cksum (unsigned short *ptr, int nbytes);
uint16_t cksum_update_128(uint32_t oval[4], uint32_t nval[4], uint16_t osum)
{
u_int16_t sum = 0;
sum = cksum_update_32(oval[0], nval[0], osum);
sum = cksum_update_32(oval[1], nval[1], sum);
sum = cksum_update_32(oval[2], nval[2], sum);
sum = cksum_update_32(oval[3], nval[3], sum);
return sum;
}
uint16_t cksum_update_32(uint32_t oval, uint32_t nval, uint16_t osum)
{
int32_t sum = ~osum;
sum &= 0xffff;
sum -= (oval >> 16);
sum -= (oval & 0xffff);
sum += (nval >> 16);
sum += (nval & 0xffff);
sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
return ~sum;
}
unsigned short
in_cksum (unsigned short *ptr, int nbytes)
{
register long sum; /* assumes long == 32 bits */
u_short oddbyte;
register u_short answer; /* assumes u_short == 16 bits */
/*
* Our algorithm is simple, using a 32-bit accumulator (sum),
* we add sequential 16-bit words to it, and at the end, fold back
* all the carry bits from the top 16 bits into the lower 16 bits.
*/
sum = 0;
while (nbytes > 1) {
sum += *ptr++;
nbytes -= 2;
}
/* mop up an odd byte, if necessary */
if (nbytes == 1) {
oddbyte = 0; /* make sure top half is zero */
*((unsigned char *) & oddbyte) = *(unsigned char *) ptr; /* one byte only */
sum += oddbyte;
}
/*
* Add back carry outs from top 16 bits to low 16 bits.
*/
sum = (sum >> 16) + (sum & 0xffff); /* add high-16 to low-16 */
sum += (sum >> 16); /* add carry */
answer = ~sum; /* ones-complement, then truncate to 16 bits */
return (answer);
}
int parse_config(const string &path)
{
FILE *f = fopen(path.c_str(), "r");
if (!f) {
fprintf(stderr, "parse_config: Can't open file %s: %s\n",
path.c_str(), strerror(errno));
return -1;
}
char buf[1024], *ptr = NULL;
while (fgets(buf, sizeof(buf), f)) {
ptr = buf;
while (*ptr == ' ' || *ptr == '\t')
++ptr;
if (*ptr == '#')
continue;
if (strncmp(ptr, "server4", 7) == 0) {
ptr += 8;
strtok(ptr, " \t\n#");
memset(&the_backend4, 0, sizeof(the_backend4));
if (inet_pton(AF_INET, ptr, &the_backend4.sin_addr) < 0) {
fprintf(stderr, "parse_config::inet_pton: %s",
strerror(errno));
return -1;
}
// for RR strategy
rr4->push_back(the_backend4);
} if (strncmp(ptr, "server6", 7) == 0) {
ptr += 8;
strtok(ptr, " \t\n#");
memset(&the_backend6, 0, sizeof(the_backend6));
if (inet_pton(AF_INET6, ptr, &the_backend6.sin6_addr) < 0) {
fprintf(stderr, "parse_config::inet_pton: %s",
strerror(errno));
return -1;
}
rr6->push_back(the_backend6);
} else if (strncmp(ptr, "VIP4", 4) == 0) {
ptr += 5;
strtok(ptr, " \t\n#");
if (inet_pton(AF_INET,ptr,&Config::VIP4.sin_addr) < 0) {
fprintf(stderr, "parse_config::inet_pton: %s",
strerror(errno));
return -1;
}
} else if (strncmp(ptr, "VIP6", 4) == 0) {
ptr += 5;
strtok(ptr, " \t\n#");
if (inet_pton(AF_INET6, ptr, &Config::VIP6.sin6_addr) < 0) {
fprintf(stderr, "parse_config::inet_pton: %s",
strerror(errno));
return -1;
}
} else if (strncmp(ptr, "strategy", 8) == 0) {
ptr += 9;
strtok(ptr, " \t\n#");
Config::strategy = ptr;
} else if (strncmp(ptr, "broadcast", 9) == 0) {
ptr += 10;
strtok(ptr, " \t\n#");
Config::broadcast = ptr;
} else if (strncmp(ptr, "port_alive", 10) == 0) {
ptr += 11;
strtok(ptr, " \t\n#");
Config::port_alive = atoi(ptr);
} else if (strncmp(ptr, "check_cycle", 11) == 0) {
ptr += 12;
strtok(ptr, " \t\n#");
Config::check_cycle = atoi(ptr);
} else if (strncmp(ptr, "nfq_len", 7) == 0) {
ptr += 8;
strtok(ptr, " \t\n#");
Config::nfq_len = atoi(ptr);
} else if (strncmp(ptr, "failover", 8) == 0) {
Config::failover = 1;
}
}
fclose(f);
return 0;
}
int get_cores()
{
int n = 1;
char buf[256];
FILE *f = fopen("/proc/cpuinfo", "r");
if (!f)
return -1;
for (;!feof(f);) {
memset(buf, 0, sizeof(buf));
if (fgets(buf, sizeof(buf), f) == NULL)
break;
if (strstr(buf, "processor"))
++n;
}
fclose(f);
return n - 1;
}
int balance_cpus()
{
int i = 0;
pid_t pid = 0;
int ncores = get_cores();
if (ncores <= 1)
return 0;
cpu_set_t *cpuset = CPU_ALLOC(ncores);
if (!cpuset)
return -1;
size_t size = CPU_ALLOC_SIZE(ncores);
CPU_ZERO_S(size, cpuset);
CPU_SET_S(0, size, cpuset);
if (sched_setaffinity(getpid(), size, cpuset) < 0) {
CPU_FREE(cpuset);
return -1;
}
printf("[+] Bound process %d to core 0.\n", getpid());
for (i = 1; i < ncores; ++i) {
pid = fork();
if (pid < 0) {
CPU_FREE(cpuset);
return -1;
} else if (pid > 0)
continue;
CPU_ZERO_S(size, cpuset);
CPU_SET_S(i, size, cpuset);
if (sched_setaffinity(getpid(), size, cpuset) < 0) {
CPU_FREE(cpuset);
return -1;
}
printf("[+] Bound process %d to core %d.\n", getpid(), i);
break;
}
CPU_FREE(cpuset);
// The core number which will also be the queue number
return i % ncores;
}
} // namespace loaded
| 21.51626
| 78
| 0.587191
|
stealth
|
50b675201c7d188aad4c09b66a394a2395df1a5c
| 533
|
cpp
|
C++
|
BOJ_CPP/24077.cpp
|
tnsgh9603/BOJ_CPP
|
432b1350f6c67cce83aec3e723e30a3c6b5dbfda
|
[
"MIT"
] | null | null | null |
BOJ_CPP/24077.cpp
|
tnsgh9603/BOJ_CPP
|
432b1350f6c67cce83aec3e723e30a3c6b5dbfda
|
[
"MIT"
] | null | null | null |
BOJ_CPP/24077.cpp
|
tnsgh9603/BOJ_CPP
|
432b1350f6c67cce83aec3e723e30a3c6b5dbfda
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
#define fastio ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
using namespace std;
int main() {
fastio;
int n, m, cnt = 0;
cin >> n >> m;
vector<int> v1(n), v2(m);
for (int i = 0; i < n; ++i) {
cin >> v1[i];
}
for (int i = 0; i < m; ++i) {
cin >> v2[i];
}
sort(v1.begin(), v1.end());
sort(v2.rbegin(), v2.rend());
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m && v1[i] <= v2[j]; ++j, ++cnt);
}
cout << cnt;
return 0;
}
| 22.208333
| 63
| 0.439024
|
tnsgh9603
|
50ba02646733afe87ea2144e5758957ea3201b57
| 223
|
hpp
|
C++
|
src/include/parser/tableref/list.hpp
|
mweisgut/duckdb
|
4cff1d7957ce895dd9984a87aa20aef67f5986e6
|
[
"MIT"
] | 1
|
2019-08-01T08:21:33.000Z
|
2019-08-01T08:21:33.000Z
|
src/include/parser/tableref/list.hpp
|
mweisgut/duckdb
|
4cff1d7957ce895dd9984a87aa20aef67f5986e6
|
[
"MIT"
] | null | null | null |
src/include/parser/tableref/list.hpp
|
mweisgut/duckdb
|
4cff1d7957ce895dd9984a87aa20aef67f5986e6
|
[
"MIT"
] | null | null | null |
#include "parser/tableref/basetableref.hpp"
#include "parser/tableref/crossproductref.hpp"
#include "parser/tableref/joinref.hpp"
#include "parser/tableref/subqueryref.hpp"
#include "parser/tableref/table_function_ref.hpp"
| 37.166667
| 49
| 0.820628
|
mweisgut
|
50bcba3f3ddaf546a63f076f116a9318c3cb6709
| 1,714
|
cpp
|
C++
|
kernel/graphics/virtiogpu/GraphicsAdapter.cpp
|
emacodes/pranaOS
|
963f2b5940ea94b153cf36780097740654fe6acd
|
[
"BSD-2-Clause"
] | null | null | null |
kernel/graphics/virtiogpu/GraphicsAdapter.cpp
|
emacodes/pranaOS
|
963f2b5940ea94b153cf36780097740654fe6acd
|
[
"BSD-2-Clause"
] | null | null | null |
kernel/graphics/virtiogpu/GraphicsAdapter.cpp
|
emacodes/pranaOS
|
963f2b5940ea94b153cf36780097740654fe6acd
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* Copyright (c) 2021, Krisna Pranav
*
* SPDX-License-Identifier: BSD-2-Clause
*/
// includes
#include <kernel/bus/pci/IDs.h>
#include <kernel/graphics/console/GenericFramebufferConsole.h>
#include <kernel/graphics/GraphicsManagement.h>
#include <kernel/graphics/virtiogpu/GPU.h>
#include <kernel/graphics/virtiogpu/GraphicsAdapter.h>
namespace Kernel::Graphics::VirtIOGPU {
NonnullRefPtr<GraphicsAdapter> GraphicsAdapter::initialize(PCI::Address base_address)
{
VERIFY(PCI::get_id(base_address).vendor_id == PCI::VendorID::VirtIO);
return adopt_ref(*new GraphicsAdapter(base_address));
}
GraphicsAdapter::GraphicsAdapter(PCI::Address base_address)
: PCI::DeviceController(base_address)
{
m_gpu_device = adopt_ref(*new GPU(base_address)).leak_ref();
}
void GraphicsAdapter::initialize_framebuffer_devices()
{
dbgln_if(VIRTIO_DEBUG, "GPU: Initializing framebuffer devices");
VERIFY(!m_created_framebuffer_devices);
m_gpu_device->create_framebuffer_devices();
m_created_framebuffer_devices = true;
GraphicsManagement::the().m_console = m_gpu_device->default_console();
}
void GraphicsAdapter::enable_consoles()
{
dbgln_if(VIRTIO_DEBUG, "GPU: Enabling consoles");
m_gpu_device->for_each_framebuffer([&](auto& framebuffer, auto& console) {
framebuffer.deactivate_writes();
console.enable();
return IterationDecision::Continue;
});
}
void GraphicsAdapter::disable_consoles()
{
dbgln_if(VIRTIO_DEBUG, "GPU: Disabling consoles");
m_gpu_device->for_each_framebuffer([&](auto& framebuffer, auto& console) {
console.disable();
framebuffer.activate_writes();
return IterationDecision::Continue;
});
}
}
| 29.050847
| 85
| 0.740373
|
emacodes
|
50c9f97b2a9d4b5c7f80d461d5fbb92b7edcc284
| 1,232
|
hpp
|
C++
|
src/Pipeline/SpirvBinary.hpp
|
tonyh-fff/swiftshader
|
f354daff5a2b882fc182c8377c826aa99b30f989
|
[
"Apache-2.0"
] | 1,570
|
2016-06-30T10:40:04.000Z
|
2022-03-31T01:47:33.000Z
|
src/Pipeline/SpirvBinary.hpp
|
tonyh-fff/swiftshader
|
f354daff5a2b882fc182c8377c826aa99b30f989
|
[
"Apache-2.0"
] | 9
|
2017-01-16T07:09:08.000Z
|
2020-08-25T18:28:59.000Z
|
src/Pipeline/SpirvBinary.hpp
|
tonyh-fff/swiftshader
|
f354daff5a2b882fc182c8377c826aa99b30f989
|
[
"Apache-2.0"
] | 253
|
2016-06-30T18:57:10.000Z
|
2022-03-25T03:57:40.000Z
|
// Copyright 2021 The SwiftShader Authors. 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 sw_SpirvBinary_hpp
#define sw_SpirvBinary_hpp
#include <atomic>
#include <cstdint>
#include <vector>
namespace sw {
class SpirvBinary : public std::vector<uint32_t>
{
public:
SpirvBinary();
SpirvBinary(const uint32_t *binary, uint32_t wordCount);
inline uint32_t getIdentifier() const { return identifier; };
// Assigns an identifier derived from the unoptimized SPIR-V binary, to avoid recompiles.
void mapOptimizedIdentifier(const SpirvBinary &unoptimized);
private:
static std::atomic<uint32_t> serialCounter;
uint32_t identifier;
};
} // namespace sw
#endif // sw_SpirvBinary_hpp
| 28
| 90
| 0.760552
|
tonyh-fff
|
50ca3443df3eb4d350b7a9da3a3671c62ced502b
| 9,333
|
cc
|
C++
|
src/atlas/grid/detail/grid/LonLat.cc
|
twsearle/atlas
|
a1916fd521f9935f846004e6194f80275de4de83
|
[
"Apache-2.0"
] | 67
|
2018-03-01T06:56:49.000Z
|
2022-03-08T18:44:47.000Z
|
src/atlas/grid/detail/grid/LonLat.cc
|
twsearle/atlas
|
a1916fd521f9935f846004e6194f80275de4de83
|
[
"Apache-2.0"
] | 93
|
2018-12-07T17:38:04.000Z
|
2022-03-31T10:04:51.000Z
|
src/atlas/grid/detail/grid/LonLat.cc
|
twsearle/atlas
|
a1916fd521f9935f846004e6194f80275de4de83
|
[
"Apache-2.0"
] | 33
|
2018-02-28T17:06:19.000Z
|
2022-01-20T12:12:27.000Z
|
/*
* (C) Copyright 2013 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation
* nor does it submit to any jurisdiction.
*/
#include <iomanip>
#include <ostream>
#include "LonLat.h"
#include "eckit/utils/Translator.h"
#include "atlas/grid/StructuredGrid.h"
#include "atlas/grid/detail/grid/GridBuilder.h"
#include "atlas/runtime/Exception.h"
namespace atlas {
namespace grid {
namespace { // anonymous
static eckit::Translator<std::string, int> to_int;
static Domain domain(const Grid::Config& grid) {
Grid::Config config;
if (grid.get("domain", config)) {
return Domain(config);
}
return Domain();
}
struct Shift {
enum Bits
{
NONE = 0,
LAT = (1 << 1),
LON = (1 << 2)
};
Shift(int bits = NONE): bits_(bits) {}
Shift(bool shift_lon, bool shift_lat): bits_((shift_lon ? LON : NONE) | (shift_lat ? LAT : NONE)) {}
bool operator()(int bits) const { return (bits_ & bits) == bits; }
const int bits_;
};
using XSpace = StructuredGrid::XSpace;
StructuredGrid::grid_t* create_lonlat(long nlon, long nlat, Shift shift, const Grid::Config& config = Grid::Config()) {
bool shifted_x = shift(Shift::LON);
bool shifted_y = shift(Shift::LAT);
double start_x = (shifted_x ? 0.5 : 0.0) * 360.0 / double(nlon);
std::array<double, 2> interval_x = {start_x, start_x + 360.};
bool no_endpoint = false;
XSpace xspace(interval_x, std::vector<idx_t>(nlat, nlon), no_endpoint);
// spacing is uniform in y
// If shifted_y, the whole interval is shifted by -dy/2, and last latitude
// would be -90-dy/2 (below -90!!!), if endpoint=true.
// Instead, we set endpoint=false so that last latitude is -90+dy/2 instead.
Spacing yspace([&] {
Grid::Config config_spacing;
config_spacing.set("type", "linear");
config_spacing.set("start", 90.0 - (shifted_y ? 90.0 / double(nlat) : 0.0));
config_spacing.set("end", -90.0 - (shifted_y ? 90.0 / double(nlat) : 0.0));
config_spacing.set("endpoint", shifted_y ? false : true);
config_spacing.set("N", nlat);
return config_spacing;
}());
Projection projection;
Grid::Config config_projection;
if (config.get("projection", config_projection)) {
projection = Projection(config_projection);
}
std::string name;
if (shifted_x and shifted_y) {
name = "S";
}
else if (shifted_x and not shifted_y) {
name = "Slon";
}
else if (not shifted_x and shifted_y) {
name = "Slat";
}
else {
name = "L";
}
name += std::to_string(nlon) + "x" + std::to_string(nlat);
return new StructuredGrid::grid_t(name, xspace, yspace, projection, domain(config));
}
StructuredGrid::grid_t* create_lonlat(const Grid::Config& config, Shift shift) {
bool shifted_y = shift(Shift::LAT);
long N, nx, ny;
// dimensions
if (config.get("N", N)) {
nx = 4 * N;
ny = shifted_y ? 2 * N : 2 * N + 1;
}
else if (config.get("nx", nx) && config.get("ny", ny)) {
}
else {
throw_Exception("Configuration requires either N, or (nx,ny)", Here());
}
return create_lonlat(nx, ny, shift, config);
}
//---------------------------------------------------------------------------------------------------------------------
static class regular_lonlat : public GridBuilder {
public:
regular_lonlat():
GridBuilder("regular_lonlat", {"^[Ll]([0-9]+)x([0-9]+)$", "^[Ll]([0-9]+)$"}, {"L<nx>x<ny>", "L<gauss>"}) {}
void print(std::ostream& os) const override {
os << std::left << std::setw(20) << "L<nx>x<ny> / L<gauss>"
<< "Regular longitude-latitude grid";
}
const Grid::Implementation* create(const std::string& name, const Grid::Config& config) const override {
int id;
std::vector<std::string> matches;
if (match(name, matches, id)) {
util::Config grid(config);
grid.set("type", type());
if (id == 0) {
grid.set("nx", to_int(matches[0]));
grid.set("ny", to_int(matches[1]));
return create(grid);
}
if (id == 1) {
grid.set("N", to_int(matches[0]));
return create(grid);
}
}
return nullptr;
}
const Grid::Implementation* create(const Grid::Config& config) const override {
return create_lonlat(config, Shift(false, false));
}
void force_link() {}
} regular_lonlat_;
//---------------------------------------------------------------------------------------------------------------------
static class shifted_lonlat : public GridBuilder {
public:
shifted_lonlat():
GridBuilder("shifted_lonlat", {"^[Ss]([0-9]+)x([0-9]+)$", "^[Ss]([0-9]+)$"}, {"S<nx>x<ny>", "S<gauss>"}) {}
void print(std::ostream& os) const override {
os << std::left << std::setw(20) << "S<nx>x<ny> / S<gauss>"
<< "Shifted longitude-latitude grid";
}
const Grid::Implementation* create(const std::string& name, const Grid::Config& config) const override {
int id;
std::vector<std::string> matches;
if (match(name, matches, id)) {
util::Config grid(config);
grid.set("type", type());
if (id == 0) {
grid.set("nx", to_int(matches[0]));
grid.set("ny", to_int(matches[1]));
return create(grid);
}
if (id == 1) {
grid.set("N", to_int(matches[0]));
return create(grid);
}
}
return nullptr;
}
const Grid::Implementation* create(const Grid::Config& config) const override {
return create_lonlat(config, Shift(true, true));
}
void force_link() {}
} shifted_lonlat_;
//---------------------------------------------------------------------------------------------------------------------
static class shifted_lon : public GridBuilder {
public:
shifted_lon():
GridBuilder("shifted_lon", {"^[Ss][Ll][Oo][Nn]([0-9]+)x([0-9]+)$", "^[Ss][Ll][Oo][Nn]([0-9]+)$"},
{"Slon<nx>x<ny>", "Slon<gauss>"}) {}
void print(std::ostream& os) const override {
os << std::left << std::setw(20) << "Slon<nx>x<ny> / Slon<gauss>"
<< "Shifted longitude grid";
}
const Grid::Implementation* create(const std::string& name, const Grid::Config& config) const override {
int id;
std::vector<std::string> matches;
if (match(name, matches, id)) {
util::Config grid(config);
grid.set("type", type());
if (id == 0) {
grid.set("nx", to_int(matches[0]));
grid.set("ny", to_int(matches[1]));
return create(grid);
}
if (id == 1) {
grid.set("N", to_int(matches[0]));
return create(grid);
}
}
return nullptr;
}
const Grid::Implementation* create(const Grid::Config& config) const override {
return create_lonlat(config, Shift(true, false));
}
void force_link() {}
} shifted_lon_;
//---------------------------------------------------------------------------------------------------------------------
static class shifted_lat : public GridBuilder {
public:
shifted_lat():
GridBuilder("shifted_lat", {"^[Ss][Ll][Aa][Tt]([0-9]+)x([0-9]+)$", "^[Ss][Ll][Aa][Tt]([0-9]+)$"},
{"Slat<nx>x<ny>", "Slat<gauss>"}) {}
void print(std::ostream& os) const override {
os << std::left << std::setw(20) << "Slat<nx>x<ny> / Slat<gauss>"
<< "Shifted latitude grid";
}
const Grid::Implementation* create(const std::string& name, const Grid::Config& config) const override {
int id;
std::vector<std::string> matches;
if (match(name, matches, id)) {
util::Config grid(config);
grid.set("type", type());
if (id == 0) {
grid.set("nx", to_int(matches[0]));
grid.set("ny", to_int(matches[1]));
return create(grid);
}
if (id == 1) {
grid.set("N", to_int(matches[0]));
return create(grid);
}
}
return nullptr;
}
const Grid::Implementation* create(const Grid::Config& config) const override {
return create_lonlat(config, Shift(false, true));
}
void force_link() {}
} shifted_lat_;
//---------------------------------------------------------------------------------------------------------------------
} // anonymous namespace
namespace detail {
namespace grid {
void force_link_LonLat() {
regular_lonlat_.force_link();
shifted_lonlat_.force_link();
shifted_lon_.force_link();
shifted_lat_.force_link();
}
} // namespace grid
} // namespace detail
} // namespace grid
} // namespace atlas
| 30.400651
| 119
| 0.525019
|
twsearle
|
50d159bbdb8f8e1ddc881f3506cb339555eac873
| 129
|
inl
|
C++
|
dependencies/glm/detail/func_geometric_simd.inl
|
realtehcman/-UnderwaterSceneProject
|
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
|
[
"MIT"
] | null | null | null |
dependencies/glm/detail/func_geometric_simd.inl
|
realtehcman/-UnderwaterSceneProject
|
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
|
[
"MIT"
] | null | null | null |
dependencies/glm/detail/func_geometric_simd.inl
|
realtehcman/-UnderwaterSceneProject
|
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
|
[
"MIT"
] | null | null | null |
version https://git-lfs.github.com/spec/v1
oid sha256:3bce881d22b8d93090c786528e69892a0cf9fb1b0de6062d544685b1fdb37fb9
size 2693
| 32.25
| 75
| 0.883721
|
realtehcman
|
50d5756eeb67ec607a2648d89f278c01cb172ad1
| 3,808
|
cpp
|
C++
|
OpenGLBasics/Camera.cpp
|
LensPlaysGames/CMake_OpenGLBasics
|
59e818b01376b6e72646245d2affbcc430489f81
|
[
"MIT"
] | null | null | null |
OpenGLBasics/Camera.cpp
|
LensPlaysGames/CMake_OpenGLBasics
|
59e818b01376b6e72646245d2affbcc430489f81
|
[
"MIT"
] | null | null | null |
OpenGLBasics/Camera.cpp
|
LensPlaysGames/CMake_OpenGLBasics
|
59e818b01376b6e72646245d2affbcc430489f81
|
[
"MIT"
] | null | null | null |
#include "Camera.h"
#include "Timer.h"
#include <glm/ext/matrix_transform.hpp>
#include <glm/ext/matrix_clip_space.hpp>
#include <glm/gtc/type_ptr.hpp>
Camera::Camera(int width, int height, glm::vec3 position) {
Width = width;
Height = height;
Position = position;
}
void Camera::Update(GLFWwindow* window) {
Inputs(window);
UpdateMatrices(FOV, NearPlane, FarPlane);
}
void Camera::UpdateMatrices(float FOVDeg, float nearPlane, float farPlane) {
view = glm::lookAt(Position, Position + Forward, g_UP);
projection = glm::perspective(FOVDeg, (float)Width/Height, nearPlane, farPlane);
//projection = glm::ortho(-25.0f, 25.0f, -25.0f, 25.0f, nearPlane, farPlane);
}
void Camera::UpdateScreenSize(int width, int height){
Width = width;
Height = height;
}
void Camera::ChangeFOV(float FOVChangeInDegrees)
{
FOV += ZoomSensitivity * glm::radians(FOVChangeInDegrees);
FOV = std::max(MinFOVRadians, std::min(FOV, MaxFOVRadians));
}
void Camera::ResetFOV() { FOV = glm::radians(StartFOVDegrees); }
/* Gather inputs using GLFW and then move accordingly.
* TODO: Change to event based where when key is pressed the event calls an action using glfwSetKeyCallback()
*/
void Camera::Inputs(GLFWwindow* window) {
if (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS){ Speed = Timer::deltaTime * InitialSpeed * 4.0f; }
else if (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_RELEASE) { Speed = Timer::deltaTime * InitialSpeed; }
// Basic movement (localized to look direction).
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS){ Position += Speed * Forward; }
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { Position += Speed * Right; }
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { Position -= Speed * Forward; }
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { Position -= Speed * Right; }
if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) { Position += Speed * Up; }
if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS) { Position -= Speed * Up; }
// Rotation (Trigonometry is greater than 1 Rylan brain).
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS) {
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
double xPos = 0.0, yPos = 0.0, xDiff = 0.0, yDiff = 0.0;
if (FirstClick) {
glfwSetCursorPos(window, Width / 2.0f, Height / 2.0f);
LastMousePos = glm::vec2(Width / 2.0f, Height/ 2.0f);
FirstClick = false;
}
else {
// Get mouse difference in position from last frame.
glfwGetCursorPos(window, &xPos, &yPos);
xDiff = Timer::deltaTime * LookSensitivity * (xPos - LastMousePos.x);
yDiff = Timer::deltaTime * LookSensitivity * (yPos - LastMousePos.y);
LastMousePos = glm::vec2(xPos, yPos);
Pitch += yDiff;
Yaw += xDiff;
// Validate pitch (don't look too far down or up).
if (-Pitch > MaxVerticalAngle) Pitch = -MaxVerticalAngle;
else if (-Pitch < -MaxVerticalAngle) Pitch = MaxVerticalAngle;
// Calculate forward from pitch + yaw angles.
Forward.x = cos(glm::radians(Yaw)) * cos(glm::radians(-Pitch));
Forward.y = sin(glm::radians(-Pitch));
Forward.z = sin(glm::radians(Yaw)) * cos(glm::radians(-Pitch));
// Update local directions.
Forward = glm::normalize(Forward);
Right = glm::normalize(glm::cross(g_UP, Forward));
Up = glm::normalize(glm::cross(Forward, Right));
}
}
else if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_RELEASE) {
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
FirstClick = true;
}
}
| 40.946237
| 114
| 0.646534
|
LensPlaysGames
|
50dada853c87460b2d0f714b4825e9135c6b0a78
| 804
|
cpp
|
C++
|
MesaDeRestaurante.cpp
|
nathaliamoreno/R2Q1-Lab-LP
|
eaf67f43838e92a5170d3efd1a9680b8670650aa
|
[
"Apache-2.0"
] | null | null | null |
MesaDeRestaurante.cpp
|
nathaliamoreno/R2Q1-Lab-LP
|
eaf67f43838e92a5170d3efd1a9680b8670650aa
|
[
"Apache-2.0"
] | null | null | null |
MesaDeRestaurante.cpp
|
nathaliamoreno/R2Q1-Lab-LP
|
eaf67f43838e92a5170d3efd1a9680b8670650aa
|
[
"Apache-2.0"
] | null | null | null |
#include "MesaDeRestaurante.h"
#include <iostream>
using namespace std;
MesaDeRestaurante::MesaDeRestaurante(){
iAtual = 0;
}
void MesaDeRestaurante::adicionaAoPedido(Pedido p){
int i,q;
std::string str1, str2;
str2 = p.getDescricao();
for(i = 0; i < iAtual; i++){
str1 = pedido[i].getDescricao();
if(str1 == str2){
q = pedido[i].getQuantidade();
q = q + p.getQuantidade();
pedido[i].setQuantidade(q);
return ;
}
}
pedido[iAtual] = p;
iAtual++;
}
void MesaDeRestaurante::zeraPedidos(){
iAtual = 0;
}
double MesaDeRestaurante::calculaTotal(){
double total = 0;
for(int i = 0; i < iAtual; i++){
total += (pedido[i].getQuantidade()*pedido[i].getPreco());
}
return total;
}
| 22.971429
| 66
| 0.575871
|
nathaliamoreno
|
50dbdc77dce0137632a7e18a6031fd238117e405
| 6,070
|
cpp
|
C++
|
Circuit/KeyboardView.cpp
|
Wang-Yue/Circu
|
a194bb904f9debab35d24eecb53c091556c17cd6
|
[
"BSD-3-Clause"
] | 8
|
2018-08-24T01:31:38.000Z
|
2021-03-01T14:57:59.000Z
|
Circuit/KeyboardView.cpp
|
Wang-Yue/Circu
|
a194bb904f9debab35d24eecb53c091556c17cd6
|
[
"BSD-3-Clause"
] | 1
|
2019-12-08T13:43:19.000Z
|
2019-12-13T03:36:16.000Z
|
Circuit/KeyboardView.cpp
|
Wang-Yue/Circuit
|
a194bb904f9debab35d24eecb53c091556c17cd6
|
[
"BSD-3-Clause"
] | null | null | null |
//
// KeyboardView.cpp
// CircuitApp
//
// Created by Yue Wang on 8/19/18.
// Copyright © 2018 Yue Wang. All rights reserved.
//
#include "KeyboardView.hpp"
#include "Pad.hpp"
#include "Scale.hpp"
#include <map>
static const Color kAvailableKeyColor(0x0000ffff);
static const Color kOctaveKeyColor(0x00ff00ff);
static const Color kEnabledKeyColor(0x00ffff00);
static const Color kDisabledKeyColor(0x00000000);
class KeyboardView::OneOctaveKeyboardView : public PadDelegate {
public:
OneOctaveKeyboardView(const Note &base_note,
const Degree &tonic_degree,
const std::vector<Pad *> &pads,
KeyboardViewDelegate *delegate) :
_base_note(base_note),
_tonic_degree(tonic_degree),
_delegate(delegate),
_pads(shufflePads(pads, base_note.scale)) {
assert(base_note.degree == 0);
assert(base_note.scale < ScaleUnknown);
Degree size = GetScaleDegreeSize(base_note.scale);
for (Degree i = 0; i <= size; ++i) {
Pad *pad = _pads[i];
Note note = base_note;
if (i == size) {
note.degree = 0;
note.octave = base_note.octave + 1;
} else {
note.degree = i;
}
// test if note is within midi range.
MIDINote midi = NoteToMIDI(note, _tonic_degree);
if (midi >= 0) {
PadIndex pad_index = pad->GetPadIndex();
_pad_note_mapping[pad_index] = note;
pad->SetDelegate(this);
} else {
pad->SetColor(kDisabledKeyColor);
}
}
for (PadIndex index = size + 1; index < _pads.size(); ++index) {
_pads[index]->SetColor(kDisabledKeyColor);
_pads[index]->SetDelegate(this);
}
}
~OneOctaveKeyboardView() {
for (Pad *pad : _pads) {
pad->SetDelegate(nullptr);
}
}
const std::vector<Pad *> shufflePads(const std::vector<Pad *> &pads, const Scale &scale) {
if (scale == ScaleChromatic) {
assert(pads.size() == kPadsInRow * 2);
static const PadIndex matrix[] = {8,1,9,2,10,11,4,12,5,13,6,14,15, 0,3,7};
std::vector<Pad *> result;
for (PadIndex pad = 0; pad < pads.size() + 1; ++pad) {
result.push_back(pads[matrix[pad]]);
}
return result;
} else {
// No need to shuffle.
assert(pads.size() == kPadsInRow);
return pads;
}
}
PadIndex ActivePadCount() const {
return _pad_note_mapping.size();
}
Pad *GetPad(const Note ¬e) {
Note n = ConvertNoteScale(note, _base_note.scale);
if (n.octave == _base_note.octave + 1 && n.degree == 0) {
Degree size = GetScaleDegreeSize(_base_note.scale);
return _pads[size];
}
if (n.octave != _base_note.octave) {
return nullptr;
}
return _pads[n.degree];
}
void SetPadColor(const Note ¬e, const Color &color) {
Pad *pad = GetPad(note);
if (!pad) {
return;
}
pad->SetColor(color);
}
void AllNotesOff() {
Degree scale_degree_size = GetScaleDegreeSize(_base_note.scale);
for (Degree degree = 0; degree <= scale_degree_size; ++degree) {
// Pads not in _pad_note_mapping are out of midi range.
PadIndex pad_index = _pads[degree]->GetPadIndex();
if (_pad_note_mapping.find(pad_index) == _pad_note_mapping.end()) {
_pads[degree]->SetColor(kDisabledKeyColor);
} else if (degree == 0 || degree == scale_degree_size) {
_pads[degree]->SetColor(kOctaveKeyColor);
} else {
_pads[degree]->SetColor(kAvailableKeyColor);
}
}
}
virtual void Tap(Pad *pad) override {
PadIndex pad_index = pad->GetPadIndex();
if (_pad_note_mapping.find(pad_index) == _pad_note_mapping.end()) {
return;
}
Note note = _pad_note_mapping[pad_index];
if (_delegate) {
_delegate->Tap(note);
}
}
virtual void Release(Pad *pad) override {
PadIndex pad_index = pad->GetPadIndex();
if (_pad_note_mapping.find(pad_index) == _pad_note_mapping.end()) {
return;
}
Note note = _pad_note_mapping[pad_index];
if (_delegate) {
_delegate->Release(note);
}
}
private:
const Note _base_note;
const Degree _tonic_degree;
const std::vector<Pad *> _pads;
// This is the real pad index stored. Never ever use it for _pads ordering.
std::map<PadIndex, Note> _pad_note_mapping;
KeyboardViewDelegate *_delegate;
};
KeyboardView::KeyboardView(const Note &base_note,
const Degree &tonic_degree,
const std::vector<Pad *> &pads,
KeyboardViewDelegate *delegate) : _delegate(delegate) {
assert(base_note.degree == 0);
assert(base_note.scale < ScaleUnknown);
PadIndex octave_pad_count = kPadsInRow;
if (base_note.scale == ScaleChromatic) {
octave_pad_count *= 2;
}
assert(pads.size() % octave_pad_count == 0);
Note current_base_note = base_note;
for (PadIndex start_pad = 0; start_pad < pads.size(); start_pad += octave_pad_count) {
std::vector<Pad *> octave_pads;
for (PadIndex i = 0; i < octave_pad_count; ++i) {
octave_pads.push_back(pads[start_pad + i]);
}
OneOctaveKeyboardView *view =
new OneOctaveKeyboardView(current_base_note, tonic_degree, octave_pads, this);
_views.push_back(view);
--current_base_note.octave;
}
}
KeyboardView::~KeyboardView() {
for (OneOctaveKeyboardView *view : _views) {
delete view;
}
}
std::vector<Pad *> KeyboardView::GetPads(const Note ¬e) {
std::vector<Pad *> pads;
for (OneOctaveKeyboardView *view : _views) {
Pad *pad = view->GetPad(note);
if (pad) {
pads.push_back(pad);
}
}
return pads;
}
void KeyboardView::AllNotesOff() {
for (OneOctaveKeyboardView *view : _views) {
view->AllNotesOff();
}
}
void KeyboardView::Highlight(const Note ¬e) {
for (OneOctaveKeyboardView *view : _views) {
view->SetPadColor(note, kEnabledKeyColor);
}
}
void KeyboardView::Tap(const Note ¬e) {
if (_delegate) {
_delegate->Tap(note);
}
}
void KeyboardView::Release(const Note ¬e) {
if (_delegate) {
_delegate->Release(note);
}
}
| 28.767773
| 92
| 0.635914
|
Wang-Yue
|
50dd032e62d19627d0574735eefe0cfb7a2408d0
| 100
|
cpp
|
C++
|
test/test_catch2/src/unit__failing_test.cpp
|
luisnuxx/formiga
|
893a464eae3323ee6dcfe8c9c4b8f681783326c6
|
[
"MIT"
] | 2
|
2018-02-18T20:11:00.000Z
|
2019-12-01T14:21:19.000Z
|
test/test_catch2/src/unit__failing_test.cpp
|
luisnuxx/formiga
|
893a464eae3323ee6dcfe8c9c4b8f681783326c6
|
[
"MIT"
] | null | null | null |
test/test_catch2/src/unit__failing_test.cpp
|
luisnuxx/formiga
|
893a464eae3323ee6dcfe8c9c4b8f681783326c6
|
[
"MIT"
] | null | null | null |
TEST_CASE( "stupid/1=2", "Prove that one equals 2" ){
int one = 1;
REQUIRE( one == 2 );
}
| 14.285714
| 53
| 0.54
|
luisnuxx
|
50e0ce3d3026acd3bf7438f3d1b07a3b860b0be2
| 6,360
|
cpp
|
C++
|
runtime/src/exc_engine/x64/unwind_handler.cpp
|
Shtan7/KTL
|
9c0adf8fac2f0bb481060b7bbb15b1356089af3c
|
[
"MIT"
] | 38
|
2020-12-16T22:12:50.000Z
|
2022-03-24T04:07:14.000Z
|
runtime/src/exc_engine/x64/unwind_handler.cpp
|
Shtan7/KTL
|
9c0adf8fac2f0bb481060b7bbb15b1356089af3c
|
[
"MIT"
] | 165
|
2020-11-11T21:22:23.000Z
|
2022-03-26T14:30:40.000Z
|
runtime/src/exc_engine/x64/unwind_handler.cpp
|
Shtan7/KTL
|
9c0adf8fac2f0bb481060b7bbb15b1356089af3c
|
[
"MIT"
] | 5
|
2021-07-16T19:05:28.000Z
|
2021-12-22T11:46:42.000Z
|
#include <bugcheck.hpp>
#include <cpu_context.hpp>
#include <symbol.hpp>
#define BREAK_IF_FALSE(cond) \
if (!(cond)) \
break
EXTERN_C ktl::crt::exc_engine::symbol __ImageBase;
namespace ktl::crt::exc_engine::x64 {
namespace pe {
template <typename Ty>
struct dir_header {
/*0x00*/ relative_virtual_address<Ty> relative_virtual_address;
/*0x04*/ uint32_t size;
/*0x08*/
};
struct extended_header {
/*0x00*/ uint32_t magic;
/*0x04*/ uint16_t machine;
/*0x06*/ uint8_t _06[0x12];
/*0x18*/ uint16_t opt_magic;
/*0x1a*/ uint8_t _20[0x36];
/*0x50*/ uint32_t image_size;
/*0x54*/ uint32_t headers_size;
/*0x58*/ uint8_t _58[0x2c];
/*0x84*/ uint32_t directory_count;
/*0x88*/ dir_header<void> export_table;
/*0x90*/ dir_header<void> import_table;
/*0x98*/ dir_header<void> resource_table;
/*0xa0*/ dir_header<function> exception_table;
};
struct dos_header {
/*0x00*/ uint16_t magic;
/*0x02*/ uint8_t _02[0x3a];
/*0x3c*/ relative_virtual_address<extended_header> image_header;
/*0x40*/
};
} // namespace pe
frame_walk_pdata frame_walk_pdata::for_this_image() noexcept {
return frame_walk_pdata{__ImageBase};
}
const byte* frame_walk_pdata::image_base() const noexcept {
return m_image_base;
}
bool frame_walk_pdata::contains_address(const byte* addr) const noexcept {
return m_image_base <= addr && addr - m_image_base < m_image_size;
}
const function* frame_walk_pdata::find_function_entry(
const byte* addr) const noexcept {
if (!contains_address(addr)) {
set_termination_context({BugCheckReason::NoMatchingExceptionHandler,
reinterpret_cast<bugcheck_arg_t>(addr)});
terminate();
}
const auto pc_rva{make_rva(addr, m_image_base)};
uint32_t left_bound{0};
uint32_t right_bound = m_function_count;
while (left_bound < right_bound) {
const uint32_t idx{left_bound + (right_bound - left_bound) / 2};
if (const auto* fn_ptr = m_functions + idx; pc_rva < fn_ptr->begin) {
right_bound = idx;
} else if (fn_ptr->end <= pc_rva) {
left_bound = idx + 1;
} else {
return fn_ptr;
}
}
return nullptr;
}
frame_walk_pdata::frame_walk_pdata(const byte* image_base) noexcept
: m_image_base(image_base) {
const auto* dos_hdr = reinterpret_cast<const pe::dos_header*>(image_base);
do {
BREAK_IF_FALSE(dos_hdr->magic == 0x5a4d);
const pe::extended_header* pe_hdr{image_base + dos_hdr->image_header};
BREAK_IF_FALSE(pe_hdr->magic == 0x4550);
BREAK_IF_FALSE(pe_hdr->machine == 0x8664);
BREAK_IF_FALSE(pe_hdr->opt_magic == 0x20b);
BREAK_IF_FALSE(pe_hdr->headers_size >=
dos_hdr->image_header.value() + sizeof(pe::extended_header));
BREAK_IF_FALSE(pe_hdr->image_size >= pe_hdr->headers_size);
BREAK_IF_FALSE(pe_hdr->directory_count >= 4);
BREAK_IF_FALSE(pe_hdr->exception_table.size % sizeof(function) == 0);
m_functions = image_base + pe_hdr->exception_table.relative_virtual_address;
m_function_count = pe_hdr->exception_table.size / sizeof(function);
m_image_size = pe_hdr->image_size;
return;
} while (false);
set_termination_context({BugCheckReason::CorruptedPeHeader});
terminate();
}
uint64_t& frame_walk_context::gp(uint8_t idx) noexcept {
constexpr int8_t conv[16]{
-1, -1, -1, 0, -1, 1, 2, 3, -1, -1, -1, -1, 4, 5, 6, 7,
};
const int8_t offs = conv[idx];
if (offs < 0) {
set_termination_context({BugCheckReason::CorruptedMachineState, offs});
terminate();
}
return (&rbx)[offs];
};
static xmm_register& get_xmm(frame_walk_context& ctx, uint8_t idx) noexcept {
if (idx < 6 || idx >= 16) {
set_termination_context({BugCheckReason::CorruptedMachineState, idx});
terminate();
}
return (&ctx.xmm6)[idx - 6];
}
template <class Ty>
Ty get_unwind_data_as(const unwind_info& unwind_info, uint32_t idx) noexcept {
const auto* data{reinterpret_cast<const byte*>(unwind_info.data + idx)};
const auto value_ptr{reinterpret_cast<const Ty*>(data)};
return *value_ptr;
}
void frame_walk_pdata::unwind(const unwind_info& unwind_info,
frame_walk_context& ctx,
machine_frame& mach) noexcept {
bool rip_updated = false;
for (uint32_t idx = 0; idx < unwind_info.code_count; ++idx) {
switch (const auto& entry = unwind_info.entries[idx]; entry.code) {
case UnwindCode::PushNonVolatileReg:
ctx.gp(entry.info) = *reinterpret_cast<const uint64_t*>(mach.rsp);
mach.rsp += 8;
break;
case UnwindCode::AllocLarge:
if (!entry.info) {
mach.rsp += unwind_info.data[++idx] * 8;
} else {
mach.rsp += unwind_info.data[idx + 1];
idx += 2;
}
break;
case UnwindCode::AllocSmall:
mach.rsp += entry.info * 8 + 8;
break;
case UnwindCode::SetFramePointer:
mach.rsp =
ctx.gp(unwind_info.frame_reg) - unwind_info.frame_reg_disp * 16;
break;
case UnwindCode::SaveNonVolatileReg:
ctx.gp(entry.info) = *reinterpret_cast<const uint64_t*>(
mach.rsp + unwind_info.data[++idx] * 8);
break;
case UnwindCode::SaveFarNonVolatileReg:
ctx.gp(entry.info) = *reinterpret_cast<const uint64_t*>(
mach.rsp + get_unwind_data_as<uint32_t>(unwind_info, +idx));
idx += 2;
break;
case UnwindCode::Epilog:
idx += 1;
break;
case UnwindCode::Reserved07:
idx += 2;
break;
case UnwindCode::SaveXmm128:
get_xmm(ctx, entry.info) = *reinterpret_cast<const xmm_register*>(
mach.rsp + unwind_info.data[++idx] * 16);
break;
case UnwindCode::SaveFarXmm128:
get_xmm(ctx, entry.info) = *reinterpret_cast<const xmm_register*>(
mach.rsp + unwind_info.data[idx + 1]);
idx += 2;
break;
case UnwindCode::PushMachineFrame:
mach.rsp += static_cast<uint64_t>(entry.info) * 8;
mach.rip = *reinterpret_cast<const byte**>(mach.rsp);
mach.rsp = *reinterpret_cast<const uint64_t*>(mach.rsp + 24);
rip_updated = true;
break;
}
}
if (!rip_updated) {
mach.rip = *reinterpret_cast<const byte**>(mach.rsp);
mach.rsp += 8;
}
}
} // namespace ktl::crt::exc_engine::x64
| 29.719626
| 80
| 0.652516
|
Shtan7
|
50e470b20732df9ff68ed9cb8f249f7b39440a73
| 706
|
cpp
|
C++
|
Snake2QT/Snake.cpp
|
PaulinaGacek/SnakeGame
|
34352fe6fd956d3319f75fa826aaa00a3560254e
|
[
"MIT"
] | null | null | null |
Snake2QT/Snake.cpp
|
PaulinaGacek/SnakeGame
|
34352fe6fd956d3319f75fa826aaa00a3560254e
|
[
"MIT"
] | null | null | null |
Snake2QT/Snake.cpp
|
PaulinaGacek/SnakeGame
|
34352fe6fd956d3319f75fa826aaa00a3560254e
|
[
"MIT"
] | null | null | null |
//
// Created by pauli on 02.06.2021.
//
#include "Snake.h"
void Snake::set_tail_X(size_t index, int position) {
//if(index >= length)
//throw std::invalid_argument("Invalid index");
x[index] = position;
}
void Snake::set_tail_Y(size_t index, int position) {
//if(index >= length)
//throw std::invalid_argument("Invalid index");
y[index] = position;
}
int Snake::get_tail_X(size_t index) {
//if(index >= length)
//throw std::invalid_argument("Invalid index");
return x[index];
}
int Snake::get_tail_Y(size_t index) {
//if(index >= length)
//throw std::invalid_argument("Invalid index");
return y[index];
}
| 22.774194
| 56
| 0.601983
|
PaulinaGacek
|
50e843d7626b8f1d86417a69dc488eb726ddbd83
| 40,848
|
hpp
|
C++
|
src/AmsSort/GroupMsgToPeAssignment.hpp
|
mschimek/KaDiS
|
ac9c5755d325d1d373a188e6fc0733b12205a74d
|
[
"BSD-2-Clause"
] | 1
|
2019-04-26T15:50:58.000Z
|
2019-04-26T15:50:58.000Z
|
src/AmsSort/GroupMsgToPeAssignment.hpp
|
mschimek/KaDiS
|
ac9c5755d325d1d373a188e6fc0733b12205a74d
|
[
"BSD-2-Clause"
] | null | null | null |
src/AmsSort/GroupMsgToPeAssignment.hpp
|
mschimek/KaDiS
|
ac9c5755d325d1d373a188e6fc0733b12205a74d
|
[
"BSD-2-Clause"
] | null | null | null |
/*****************************************************************************
* This file is part of the Project Karlsruhe Distributed Sorting Library
* (KaDiS).
*
* Copyright (c) 2019, Michael Axtmann <michael.axtmann@kit.edu>
* 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.
*****************************************************************************/
#pragma once
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <numeric>
#include <tuple>
#include <utility>
#include <vector>
#include "../../include/AmsSort/Configuration.hpp"
#include "../Tools/CommonMpi.hpp"
#include "Alltoall.hpp"
#include "BinomialTreePipeline.hpp"
#include "Bitonic/Bitonic.hpp"
#include <RBC.hpp>
#include <tlx/algorithm.hpp>
namespace Ams {
namespace _internal {
namespace GroupMsgToPeAssignment {
template <class AmsTag, class Tracker>
// DistrRanges are sorted by target process. There is at most one range for each target process.
std::tuple<DistrRanges, size_t, size_t> detAssignment(const std::vector<size_t>& loc_group_el_cnts,
const std::vector<size_t>& glob_group_el_cnts,
const std::vector<size_t>& group_sizes,
const std::vector<size_t>& group_sizes_exscan,
size_t my_group_idx,
size_t my_group_rank,
size_t residual_capacity,
const Ams::DistributionStrategy
distr_strategy,
Tracker& tracker,
RBC::Comm comm, RBC::Comm group_comm);
// DistrRanges are sorted by target process. There is at most one range for each target process.
std::tuple<DistrRanges, size_t, size_t> simpleAssignment(const std::vector<size_t>& group_sizes,
const std::vector<size_t>&
group_sizes_exscan,
const std::vector<size_t>&
loc_group_el_cnts,
const std::vector<size_t>&
glob_group_el_cnts,
size_t my_group_idx,
bool use_two_tree,
RBC::Comm comm);
// DistrRanges are sorted by target process. There is at most one range for each target process.
std::tuple<DistrRanges, size_t, size_t> simpleAssignment(const std::vector<size_t>& group_sizes,
const std::vector<size_t>&
group_sizes_exscan,
const std::vector<size_t>&
loc_group_el_cnts,
const std::vector<size_t>&
loc_group_el_distr_scan,
const std::vector<size_t>&
glob_group_el_cnts,
size_t my_group_idx,
RBC::Comm comm);
namespace _internal {
struct DataRequest {
DataRequest() :
size(0),
pe(0)
{ }
DataRequest(size_t my_size, size_t my_pe) :
size(my_size),
pe(my_pe)
{ }
size_t size;
size_t pe;
};
struct GroupDataRequest {
public:
GroupDataRequest() :
size(0),
group(0),
pe(0) { }
GroupDataRequest(size_t my_size, size_t my_group_id, size_t my_pe) :
size(my_size),
group(my_group_id),
pe(my_pe) { }
static MPI_Datatype mpiType() {
static MPI_Datatype my_type = MPI_DATATYPE_NULL;
if (my_type == MPI_DATATYPE_NULL) {
MPI_Datatype types[3];
int blocklen[3] = { 1, 1, 1 };
MPI_Aint disp[3] = {
offsetof(GroupDataRequest, size),
offsetof(GroupDataRequest, group),
offsetof(GroupDataRequest, pe)
};
types[0] = Common::getMpiType<decltype(size)>();
types[1] = Common::getMpiType<decltype(group)>();
types[2] = Common::getMpiType<decltype(pe)>();
MPI_Type_create_struct(3, blocklen, disp, types, &my_type);
MPI_Type_commit(&my_type);
}
return my_type;
}
bool operator== (const GroupDataRequest& r) const {
return size == r.size && group == r.group &&
pe == r.pe;
}
size_t getSize() const {
return size;
}
size_t getGroup() const {
return group;
}
int getPe() const {
return pe;
}
private:
size_t size;
size_t group;
int pe;
};
struct Piece {
public:
Piece() :
begin_(0),
end_(0),
pe_(0),
type_(Piece::residualType()) { }
int pe() const { return pe_; }
size_t begin() const { return begin_; }
size_t end() const { return end_; }
size_t size() const { return end_ - begin_; }
// void setPe(size_t pe) { pe_ = pe; }
void setBegin(size_t begin) { begin_ = begin; }
void setEnd(size_t end) { end_ = end; }
static Piece requestPiece(size_t begin, size_t end, size_t pe) {
return Piece(begin, end, pe, Piece::requestType());
}
static Piece residualPiece(size_t begin, size_t end, size_t pe) {
return Piece(begin, end, pe, Piece::residualType());
}
bool isRequest() const { return type_ == Piece::requestType(); }
bool isResidual() const { return type_ == Piece::residualType(); }
bool isEmpty() const { return begin_ == end_; }
bool isTypeEqualTo(const Piece& p) const { return type_ == p.type_; }
GroupDataRequest satisfyRequest(Piece& x_piece, size_t group_id) {
assert(isRequest());
assert(x_piece.isResidual());
assert(x_piece.begin() == this->begin());
const size_t satisfiable_request_size =
std::min(size(), x_piece.size());
GroupDataRequest msg(satisfiable_request_size, group_id,
x_piece.pe_);
removeLeftCapacity(satisfiable_request_size);
x_piece.removeLeftCapacity(satisfiable_request_size);
assert(isEmpty() || x_piece.isEmpty());
assert(msg.getSize() > 0);
return msg;
}
static MPI_Datatype mpiType() {
static MPI_Datatype my_type = MPI_DATATYPE_NULL;
if (my_type == MPI_DATATYPE_NULL) {
MPI_Datatype types[4];
int blocklen[4] = { 1, 1, 1, 1 };
MPI_Aint disp[4] = {
offsetof(Piece, begin_),
offsetof(Piece, end_),
offsetof(Piece, pe_),
offsetof(Piece, type_)
};
types[0] = Common::getMpiType<decltype(begin_)>();
types[1] = Common::getMpiType<decltype(end_)>();
types[2] = Common::getMpiType<decltype(pe_)>();
types[3] = Common::getMpiType<decltype(type_)>();
MPI_Type_create_struct(4, blocklen, disp, types, &my_type);
MPI_Type_commit(&my_type);
}
return my_type;
}
private:
Piece(size_t begin, size_t end, size_t pe, size_t type) :
begin_(begin),
end_(end),
pe_(pe),
type_(type) { }
static int requestType() { return 1; }
static int residualType() { return 0; }
void removeLeftCapacity(size_t cap) {
assert(size() >= cap);
begin_ += cap;
}
size_t begin_;
size_t end_;
int pe_;
int type_;
};
/* @brief Merges sorted X pieces and Y pieces and generates request answers.
*
* The X pieces (Y pieces) cover a stripe of residual elements
* (request elements). The residual stripe may begin before the
* request stripe starts (the first X piece extends into the first Y
* piece) or may end after the request stripe ends (the last X piece
* extends into the last Y piece).
*/
void mergeXY(std::vector<Piece>& x_pieces,
std::vector<Piece>& y_pieces,
size_t my_group_idx,
std::vector<GroupDataRequest>& answers,
DistrRanges& answer_targets);
/* @brief Calculates send descriptions for a message assignment.
*
* @param assignments Vector of assignments of "element volume -> target process".
* The vector 'assignments' stores one assignment (not more!)
* for a target process. The assignments for one process group
* are stored next to each other and the assignments for
* one process group are sorted by the target process id.
*
* @return Send descriptions for outgoing messages. The descriptions are ordered
* by the receiving processes.
*/
DistrRanges msgAssignmentToSendDescr(const std::vector<GroupDataRequest>& assignments,
const std::vector<size_t>& group_sizes_exscan,
std::vector<size_t> loc_group_el_cnts_exscan);
std::vector<Piece> orderXPieces(const std::vector<Piece>& x_pieces);
/* @brief Creates Y pieces of requests.
*
* @param lmsgs_request_messages Requests sorted by requesting processes
* @return Y pieces sorted by requesting processes.
*
*/
std::vector<Piece> createYPieces(size_t lmsgs_request_exscan,
const std::vector<int>& recv_partners,
const std::vector<size_t>& recv_sizes,
const size_t max_small_msg_size);
inline bool isSmallMsg(size_t msg_size, size_t max_small_msg_size) {
return msg_size <= max_small_msg_size && msg_size > 0;
}
/* @brief Maximum size of a small message.
*/
size_t maxSmallMsgSize(size_t group_size,
size_t residual_capacity, size_t nprocs);
template <class AmsTag, class Tracker>
void distributeMergedXPieces(const std::vector<int>& target_pes, const std::vector<Piece>& send_xs,
const size_t rbegin, const size_t rend, std::vector<Piece>& recv_xs,
Tracker& tracker, RBC::Comm group_comm) {
std::vector<RBC::Request> send_requests(send_xs.size());
// send x pieces
for (size_t i = 0; i < send_xs.size(); ++i) {
auto target_pe = target_pes[i];
RBC::Isend(send_xs.data() + i, 1, Piece::mpiType(), target_pe,
AmsTag::kCapacityDistributeSchema, group_comm,
send_requests.data() + i);
}
// Recv pieces
const auto getContributingResidual =
[](const Piece& candidate, size_t rbegin, size_t rend) {
const auto cbegin = candidate.begin();
const auto cend = candidate.end();
const auto end = std::min(rend, cend);
const auto begin = std::max(rbegin, cbegin);
assert(end > begin);
return end - begin;
};
#ifndef NDEBUG
const auto isContributing = [&getContributingResidual](
Piece candidate, size_t rbegin, size_t rend) {
assert(candidate.isResidual());
return getContributingResidual(candidate, rbegin, rend) > 0;
};
#endif
size_t request_count = rend - rbegin;
int sent = 0;
while (request_count) {
MPI_Status status;
int flag = 0;
RBC::Iprobe(MPI_ANY_SOURCE, AmsTag::kCapacityDistributeSchema, group_comm, &flag, &status);
if (flag) {
recv_xs.push_back(Piece{ });
int source = group_comm.MpiRankToRangeRank(status.MPI_SOURCE);
RBC::Recv(&recv_xs.back(), 1, Piece::mpiType(), source,
AmsTag::kCapacityDistributeSchema, group_comm, MPI_STATUS_IGNORE);
assert(isContributing(recv_xs.back(), rbegin, rend));
size_t contributed_residual =
getContributingResidual(recv_xs.back(), rbegin, rend);
assert(contributed_residual > 0);
assert(contributed_residual <= request_count);
request_count -= contributed_residual;
}
if (!sent) {
RBC::Testall(send_requests.size(), send_requests.data(), &sent,
MPI_STATUSES_IGNORE);
}
}
if (!sent) {
RBC::Waitall(send_requests.size(), send_requests.data(),
MPI_STATUSES_IGNORE);
}
tracker.send_messages_c_.add(send_xs.size());
tracker.send_volume_c_.add(send_xs.size());
tracker.receive_messages_c_.add(recv_xs.size());
tracker.receive_volume_c_.add(recv_xs.size());
}
std::vector<int> recvPartners(int nprocs, int my_group_size, int my_group_rank);
} // end namespace _internal
/*
* 1. Store small messages locally.
* 2. Route message requests to group with one-factor algorithm.
* 3. Calculate residual capacity.
* 4. Distributed scan over request sizes and residual capacities.
* 5. Store first value of "local request size prefix sum vector" y and "local residual capacity prefix sum vector" x.
* 6. Merge (sorted) X and Y sequence with bitonic merge. Each process again has two pieces a and b.
* 7. Send piece b to next process. Thus, each process knows piece 'prev_piece' which comes before piece a.
* 8. Detect each x piece 'x_remember' which is directly followed by a y piece.
* 9. Partial broadcast of 'x_remember' stored at process i to processes 'i+1'..'i+j', where 'i+j' is the first process which stores a y piece. The received piece is called 'x_bcasted'.
* 10.
*
* @return Returns send descriptions and maximum number of receive messages.
*/
template <class AmsTag, class Tracker>
std::tuple<DistrRanges, size_t, size_t> detAssignment(const std::vector<size_t>& loc_group_el_cnts,
const std::vector<size_t>& glob_group_el_cnts,
const std::vector<size_t>& group_sizes,
const std::vector<size_t>& group_sizes_exscan,
const size_t my_group_idx,
const size_t my_group_rank,
const size_t residual_capacity,
const Ams::DistributionStrategy
distr_strategy,
Tracker& tracker,
RBC::Comm comm, RBC::Comm group_comm) {
std::ignore = glob_group_el_cnts;
#ifndef NDEBUG
for (size_t i = 0; i != glob_group_el_cnts.size(); ++i) {
assert(residual_capacity * group_sizes[i] >= glob_group_el_cnts[i]);
}
#endif
using Piece = _internal::Piece;
const size_t nprocs = comm.getSize();
const size_t myrank = comm.getRank();
const size_t group_cnt = group_sizes.size();
const size_t my_group_size = group_sizes[my_group_idx];
const auto loc_group_el_cnts_exscan = [&loc_group_el_cnts]() {
std::vector<size_t> loc_group_el_cnts_exscan(
loc_group_el_cnts.size() + 1);
tlx::exclusive_scan(loc_group_el_cnts.begin(),
loc_group_el_cnts.end(),
loc_group_el_cnts_exscan.begin(), 0);
return loc_group_el_cnts_exscan;
} ();
size_t max_num_recv_msgs = 0;
/******************************************************************************/
/* Route send requests to group. */
/* */
/* We send one message to each group. */
/* We receive messages from processes [ begin, end ) */
/* begin := my_group_rank * tlx::div_ceil(nprocs, group_sizes[my_group_idx]) */
/* end := min((my_group_rank + 1) * tlx::div_ceil( */
/* nprocs, group_sizes[my_group_idx]), nprocs ) */
/******************************************************************************/
const std::vector<int> recv_partners = _internal::recvPartners(nprocs, my_group_size,
my_group_rank);
const int first_1factor_group = Alltoallv::_internal::FirstTarget(group_cnt, my_group_idx);
std::vector<MPI_Request> requests(group_cnt + recv_partners.size());
// Receive requests in order. Post receive requests in one-factor order.
std::vector<size_t> recv_sizes(recv_partners.size());
const int recv_offset = std::lower_bound(
recv_partners.begin(), recv_partners.end(),
group_sizes_exscan[first_1factor_group]) - recv_partners.begin();
for (size_t i = 0; i != recv_partners.size(); ++i) {
auto rotated_idx = i + recv_offset;
if (rotated_idx >= recv_partners.size()) {
rotated_idx -= recv_partners.size();
}
const auto source = recv_partners[rotated_idx];
RBC::Irecv(recv_sizes.data() + rotated_idx, 1,
Common::getMpiType(recv_sizes),
source, AmsTag::kOneFactorGroupBasedExchange,
comm, requests.data() + i);
}
// Send requests in one-factor order.
for (size_t i = 0; i != group_cnt; ++i) {
auto rotated_idx = i + first_1factor_group;
if (rotated_idx >= group_cnt) {
rotated_idx -= group_cnt;
}
const auto target = group_sizes_exscan[rotated_idx]
+ myrank % group_sizes[rotated_idx];
RBC::Isend(loc_group_el_cnts.data() + rotated_idx, 1,
Common::getMpiType(loc_group_el_cnts),
target, AmsTag::kOneFactorGroupBasedExchange,
comm, requests.data() + recv_sizes.size() + i);
}
MPI_Waitall(requests.size(), requests.data(), MPI_STATUSES_IGNORE);
tracker.send_messages_c_.add(group_cnt);
tracker.send_volume_c_.add(group_cnt);
tracker.receive_messages_c_.add(recv_partners.size());
tracker.receive_volume_c_.add(recv_partners.size());
// Request answers (of type GroupDataRequest) contain the group
// index such that the receiver can sort the answers by their target
// groups using a bucket sort algorithm.
std::vector<_internal::GroupDataRequest> answers;
DistrRanges answer_targets;
if (my_group_size == 1) {
// Just one process in the group. All processes send their
// data to this process.
for (size_t i = 0; i != recv_sizes.size(); ++i) {
// Empty answers are not allowed as the receiver would not
// wait for such answers.
// 'answers' must be ordered by process ids.
if (recv_sizes[i] > 0) {
assert(i == 0 || recv_partners[i - 1] < recv_partners[i]);
answer_targets.emplace_back(recv_partners[i], answer_targets.size(), 1);
answers.emplace_back(recv_sizes[i], my_group_idx, my_group_rank);
}
}
max_num_recv_msgs = answers.size();
tracker.send_messages_c_.add(0);
tracker.send_volume_c_.add(0);
tracker.receive_messages_c_.add(0);
tracker.receive_volume_c_.add(0);
} else if (residual_capacity == 0) {
assert(recv_partners.empty());
tracker.send_messages_c_.add(0);
tracker.send_volume_c_.add(0);
tracker.receive_messages_c_.add(0);
tracker.receive_volume_c_.add(0);
} else {
// We have to assign messages.
/******************************************************************************/
/* Split requests into large and small requests. */
/******************************************************************************/
size_t smsg_capacity = 0;
size_t lmsgs_request_volume = 0;
size_t smsg_cnt = 0;
const size_t my_max_small_msg_size = _internal::maxSmallMsgSize(
group_sizes[my_group_idx], residual_capacity, nprocs);
for (size_t i = 0; i != recv_sizes.size(); ++i) {
if (_internal::isSmallMsg(recv_sizes[i], my_max_small_msg_size)) {
answer_targets.emplace_back(recv_partners[i], answers.size(), 1);
answers.emplace_back(recv_sizes[i], my_group_idx, my_group_rank);
++smsg_cnt;
smsg_capacity += recv_sizes[i];
} else if (recv_sizes[i] > 0) {
lmsgs_request_volume += recv_sizes[i];
}
}
// Add number of incoming messages during the data exchange.
max_num_recv_msgs = smsg_cnt + 2 + tlx::div_ceil(residual_capacity,
my_max_small_msg_size + 1);
assert(residual_capacity >= 2 * smsg_capacity);
const size_t lmsg_capacity = residual_capacity - smsg_capacity;
assert(lmsg_capacity > 0);
/******************************************************************************
* Calculate exclusive prefix sum over remaining residuals and
* large message request sizes of this group.
******************************************************************************/
size_t lmsg_request_exscan = 0;
size_t lmsg_capacity_exscan = 0;
size_t lmsg_total_request = 0;
auto scan = [group_comm, my_group_rank](size_t lmsgs_request_count,
size_t remaining_residual) {
size_t tmp[2] = { lmsgs_request_count, remaining_residual };
size_t tmp_exscan[2];
size_t tmp_sum[2];
ScanAndBcast(tmp, tmp_exscan, tmp_sum, 2,
Common::getMpiType(tmp[0]), MPI_SUM, group_comm);
tmp_exscan[0] -= lmsgs_request_count;
tmp_exscan[1] -= remaining_residual;
return std::tuple<size_t, size_t, size_t>(
tmp_exscan[0], tmp_exscan[1], tmp_sum[0]);
};
std::tie(lmsg_request_exscan, lmsg_capacity_exscan, lmsg_total_request) =
scan(lmsgs_request_volume, lmsg_capacity);
#ifndef NDEBUG
if (my_group_rank + 1 == my_group_size) {
const size_t total_request = lmsg_request_exscan + lmsgs_request_volume;
const size_t total_capacity = lmsg_capacity_exscan + lmsg_capacity;
assert(total_request <= total_capacity);
}
#endif
/******************************************************************************
* Create X and Y piece locally. X pieces as well as Y pieces form two sorted
* global sequences.
* Merge those two sorted sequences with bitonic merging.
******************************************************************************/
std::vector<Piece> sorted_xys = {
// X piece.
Piece::residualPiece(lmsg_capacity_exscan,
lmsg_capacity_exscan + lmsg_capacity,
my_group_rank),
// Y piece.
Piece::requestPiece(lmsg_request_exscan,
lmsg_request_exscan + lmsgs_request_volume,
my_group_rank)
};
// Pieces of the same type are ordered by their process id. A
// residual piece is smaller than a request piece, iff the
// residual piece begins before the request piece ends!! This
// is crucial!!!
auto comp = [](const Piece& p1, const Piece& p2) {
if (p1.isTypeEqualTo(p2)) {
return p1.pe() < p2.pe();
} else if (p1.isResidual()) { // and p2.IsRequest() == true
return p1.begin() < p2.end();
} else { // p1.IsRequest() and p2.IsResidual()
return p1.end() <= p2.begin();
}
};
assert(sorted_xys.size() == 2);
// Distribute the pieces such that the first half of the PEs hold
// a decreasing sequence of the Xs and the second half of the PEs
// hold a increasing sequence of the Ys.
// This leads to a bitonic decreasing sequence of size 2 * my_group_size
// with each PE holding 2 elements.
MPI_Request requests[4] = { MPI_REQUEST_NULL };
// Send first element to first half
RBC::Isend(&sorted_xys[0], 1, Piece::mpiType(),
(my_group_size - 1 - my_group_rank) / 2,
AmsTag::kGeneral, group_comm, &requests[0]);
// Send second element to second half
RBC::Isend(&sorted_xys[1], 1, Piece::mpiType(),
(my_group_size + my_group_rank) / 2,
AmsTag::kGeneral, group_comm, &requests[1]);
// Receive elements
std::vector<Piece> bitonic_sequence(2);
for (size_t i = 0; i < 2; i++) {
size_t elm_id = 2 * my_group_rank + i;
size_t recv_rank;
if (elm_id < my_group_size)
recv_rank = my_group_size - 1 - elm_id;
else
recv_rank = elm_id - my_group_size;
RBC::Irecv(&bitonic_sequence[i], 1, Piece::mpiType(), recv_rank,
AmsTag::kGeneral, group_comm, &requests[2 + i]);
}
MPI_Waitall(4, requests, MPI_STATUSES_IGNORE);
sorted_xys = std::move(bitonic_sequence);
// Sort the sequence
std::sort(sorted_xys.begin(), sorted_xys.end(), comp);
Bitonic::SortBitonicSequence(sorted_xys, Piece::mpiType(), AmsTag::kGeneral,
group_comm, comp, true, true);
assert(sorted_xys.size() == 2);
/******************************************************************************
* Send second piece of local merged subsequence to next process.
******************************************************************************/
Piece prev_piece;
RBC::Sendrecv(sorted_xys.data() + 1, 1, Piece::mpiType(),
(my_group_rank + 1) % my_group_size,
AmsTag::kGeneral, &prev_piece, 1,
Piece::mpiType(),
(my_group_rank + my_group_size - 1) % my_group_size,
AmsTag::kGeneral, group_comm, MPI_STATUS_IGNORE);
// Reset previous piece on PE 0.
if (my_group_rank == 0) {
prev_piece = Piece::residualPiece(0, 0, 0);
}
/******************************************************************************
*
* Broadcast X pieces which are followed by a Y piece to subsequent processes.
* Reason: A X piece covers multiple Y pieces.
* Correctness: A X piece x1 can cover many subsequent Y pieces, until a X piece
* x2 occurs. x1 may also cover the Y piece which comes after x2.
*
* Example:
* Input: X1 Y | X2 X3| Y X4| Y Y | Y Y | Y Y | X5 X6| X7 X8| Y X9 ...
* Bcast: X1 | | X3 | X4 | | | | | X8
* Result: (0,0,0) | X1 | X1 | X3 | X4 | X4 | X4 | X4 | X4 | X8
* Process i broadcasts piece X in two cases:
* i-1 i
* - Case 1: X | Y ?
* - Case 2: ? | X Y
******************************************************************************/
// If a y piece is merged after a x piece, store x piece and remember.
bool has_xy_sequence = false;
Piece x_remember;
if (sorted_xys.front().isResidual() && sorted_xys.back().isRequest()) {
x_remember = sorted_xys.front();
has_xy_sequence = true;
} else if (prev_piece.isResidual() && sorted_xys.front().isRequest()) {
x_remember = prev_piece;
has_xy_sequence = true;
}
// First piece must be remembered. Reset previous piece on PE 0.
if (my_group_rank == 0 && !has_xy_sequence) {
x_remember = Piece::residualPiece(0, 0, 0);
has_xy_sequence = true;
}
// Partial broadcast of remembered x pieces.
Piece x_bcasted = BinomialTreePipeline::bcast<Piece>(
x_remember, has_xy_sequence, Piece::mpiType(), group_comm);
// Reset x bcasted on PE 0.
if (my_group_rank == 0) {
x_bcasted = Piece::residualPiece(0, 0, 0);
}
/******************************************************************************
* Assign x pieces to y pieces.
*
* 1. Calculate number of Y pieces on previous processes.
* 2. Iterate over X pieces and assign them to the previous Y piece.
******************************************************************************/
std::vector<Piece> send_xs;
std::vector<int> targets;
// Count Y pieces in sorted_xys ex sum
int num_prev_ys = [group_comm, my_group_rank, &sorted_xys]() {
int num_ypieces = 0;
for (auto& piece : sorted_xys) {
if (piece.isRequest()) num_ypieces++;
}
int scan = 0;
RBC::Exscan(&num_ypieces, &scan, 1,
Common::getMpiType(num_ypieces), MPI_SUM, group_comm);
if (my_group_rank == 0) {
return 0;
} else {
return scan;
}
} ();
auto const isContributing = [](const Piece& candidate, const Piece& piece) {
// Candidate is not empty.
// Piece is not empty.
// Candidate covers piece at some position.
assert(candidate.isResidual() && piece.isRequest());
return !piece.isEmpty()
&&
(candidate.end() > piece.begin()
&&
piece.end() > candidate.begin());
};
auto const isCovering = [lmsg_total_request](const Piece& xpiece) {
// Check whether xpiece is covering any request. As the
// total residual capacity may be larger than the total
// request capacity. There may be some xpieces (the last
// ones) which do not cover any requests. We have to
// filter out those residuals. Otherwise, those xpieces
// would all be send to the last process of the group!
assert(xpiece.isResidual());
return !xpiece.isEmpty() && xpiece.begin() < lmsg_total_request;
};
if (sorted_xys.front().isResidual() && sorted_xys.back().isRequest()) {
const auto& XB = x_bcasted;
const auto& X1 = sorted_xys.front();
const auto& Y2 = sorted_xys.back();
// Example: XB Y X X |X1 Y2|
if (isContributing(XB, Y2)) {
send_xs.push_back(XB);
targets.push_back(num_prev_ys);
}
if (isCovering(X1)) {
send_xs.push_back(X1);
targets.push_back(num_prev_ys);
}
} else if (sorted_xys.front().isRequest() &&
sorted_xys.back().isResidual()) {
const auto& XB = x_bcasted;
const auto& Y1 = sorted_xys.front();
const auto& X2 = sorted_xys.back();
// Example: XB Y X X |Y1 X2|
if (isContributing(XB, Y1)) {
send_xs.push_back(XB);
targets.push_back(num_prev_ys);
}
++num_prev_ys;
if (isCovering(X2)) {
send_xs.push_back(X2);
targets.push_back(num_prev_ys);
}
} else if (sorted_xys.front().isResidual() &&
sorted_xys.back().isResidual()) {
const auto& X1 = sorted_xys.front();
const auto& X2 = sorted_xys.back();
if (isCovering(X1)) {
send_xs.push_back(X1);
targets.push_back(num_prev_ys);
}
if (isCovering(X2)) {
send_xs.push_back(X2);
targets.push_back(num_prev_ys);
}
} else if (sorted_xys.front().isRequest() &&
sorted_xys.back().isRequest()) {
const auto& XB = x_bcasted;
const auto& Y1 = sorted_xys.front();
const auto& Y2 = sorted_xys.back();
if (prev_piece.isResidual()) {
const auto& XP = prev_piece;
// Example: XB Y Y Y X X XP |Y1 Y2|
// Send XB if it contributes to Y1. Note that XB can
// not contribute to Y2 as the previous piece is a X
// piece.
if (isContributing(XB, Y1)) {
send_xs.push_back(XB);
targets.push_back(num_prev_ys);
}
++num_prev_ys;
// Send XP if it contributes to Y2. Note that we are
// not responsible for XP contributing to Y1 as this
// is checked by the previous processor.
if (isContributing(XP, Y2)) {
send_xs.push_back(XP);
targets.push_back(num_prev_ys);
}
} else {
// Example: XB Y Y YP |Y1 Y2|
// XB may contribute to Y1 and to Y2.
if (isContributing(XB, Y1)) {
send_xs.push_back(XB);
targets.push_back(num_prev_ys);
}
++num_prev_ys;
if (isContributing(XB, Y2)) {
send_xs.push_back(XB);
targets.push_back(num_prev_ys);
}
}
}
const size_t max_pieces_recv_cnt = 2 + tlx::div_ceil(lmsgs_request_volume,
my_max_small_msg_size + 1);
std::vector<Piece> recv_xs;
recv_xs.reserve(max_pieces_recv_cnt);
Ams::_internal::GroupMsgToPeAssignment::_internal::distributeMergedXPieces<AmsTag>(
targets, send_xs, lmsg_request_exscan, lmsg_request_exscan + lmsgs_request_volume,
recv_xs, tracker, group_comm);
// No pieces of size zero.
assert(std::find_if(recv_xs.begin(), recv_xs.end(),
[](const auto& piece) {
return piece.size() == 0;
}) == recv_xs.end());
recv_xs = orderXPieces(recv_xs);
// We do not expect duplicates here.
assert(std::adjacent_find(recv_xs.begin(), recv_xs.end(),
[](const auto& left, const auto& right) {
return left.pe() == right.pe();
}) == recv_xs.end());
/******************************************************************************
* Construct Y pieces
******************************************************************************/
// Push back large pieces (Y).
auto y_pieces = _internal::createYPieces(lmsg_request_exscan, recv_partners,
recv_sizes, my_max_small_msg_size);
// No pieces of size zero.
assert(std::find_if(y_pieces.begin(), y_pieces.end(),
[](const auto& piece) {
return piece.size() == 0;
}) == y_pieces.end());
/******************************************************************************
* Create request answers.
* 1. Create large message answers by merging X and Y pieces.
* 2. Merge large message answers with small message answers
* to a sorted sequence of answers.
******************************************************************************/
assert(smsg_cnt == answer_targets.size());
assert(std::is_sorted(answer_targets.begin(), answer_targets.end(),
[](const DistrRange& l, const DistrRange& r) {
return l.pe < r.pe;
}));
mergeXY(recv_xs, y_pieces, my_group_idx, answers, answer_targets);
assert(std::is_sorted(answer_targets.begin() + smsg_cnt, answer_targets.end(),
[](const DistrRange& l, const DistrRange& r) {
return l.pe < r.pe;
}));
// Sort targets of small requests and large requests.
DistrRanges tmp_answer_targets(answer_targets.size());
std::merge(answer_targets.begin(), answer_targets.begin() + smsg_cnt,
answer_targets.begin() + smsg_cnt, answer_targets.end(),
tmp_answer_targets.begin(),
[](const DistrRange& l, const DistrRange& r) {
return l.pe < r.pe;
});
answer_targets = std::move(tmp_answer_targets);
}
assert(std::is_sorted(answer_targets.begin(), answer_targets.end(),
[](const DistrRange& l, const DistrRange& r) {
return l.pe < r.pe;
}));
// No pieces of size zero.
assert(std::find_if(answer_targets.begin(), answer_targets.end(),
[](const auto& piece) {
return piece.size == 0;
}) == answer_targets.end());
// No pieces of size zero.
assert(std::find_if(answers.begin(), answers.end(),
[](const auto& piece) {
return piece.getSize() == 0;
}) == answers.end());
// Calculate maximum number of incoming request answers.
size_t max_assigned_msgs = 0;
for (size_t i = 0; i != group_cnt; ++i) {
const auto max = _internal::maxSmallMsgSize(
group_sizes[i], residual_capacity, nprocs);
const auto size = loc_group_el_cnts[i];
// +2 for overlapping residuals.
max_assigned_msgs += 2 + tlx::div_ceil(size, max + 1);
}
std::vector<_internal::GroupDataRequest> msg_meta; // (max_assigned_msgs);
if (distr_strategy == DistributionStrategy::EXCHANGE_WITHOUT_RECV_SIZES) {
Alltoallv::exchangeWithoutRecvSizes<AmsTag>(tracker, answers, answer_targets, msg_meta,
group_cnt, max_assigned_msgs,
_internal::GroupDataRequest::mpiType(), comm);
} else if (distr_strategy == DistributionStrategy::EXCHANGE_WITH_RECV_SIZES) {
Alltoallv::exchangeWithRecvSizes<AmsTag>(tracker, answers, answer_targets, msg_meta,
_internal::GroupDataRequest::mpiType(), comm);
} else {
Alltoallv::exchangeWithRecvSizesAndPorts<AmsTag>(tracker, answers, answer_targets, msg_meta,
_internal::GroupDataRequest::mpiType(), comm);
}
#ifndef NDEBUG
// Number of assigned elements must be equal to requested number of elements.
std::vector<size_t> loc_group_el_cnts_debug(group_cnt, 0);
for (const auto& msg : msg_meta) {
loc_group_el_cnts_debug[msg.getGroup()] += msg.getSize();
}
for (size_t i = 0; i != loc_group_el_cnts.size(); ++i) {
assert(loc_group_el_cnts[i] == loc_group_el_cnts_debug[i]);
}
#endif
// No pieces of size zero.
assert(std::find_if(msg_meta.begin(), msg_meta.end(),
[](const auto& piece) {
return piece.getSize() == 0;
}) == msg_meta.end());
const DistrRanges out_msgs = msgAssignmentToSendDescr(
msg_meta, group_sizes_exscan, loc_group_el_cnts_exscan);
// Sorted by target processes.
assert(std::is_sorted(out_msgs.begin(), out_msgs.end(),
[](const auto& left, const auto& right) {
return left.pe < right.pe;
}));
// No pieces of size zero.
assert(std::find_if(out_msgs.begin(), out_msgs.end(),
[](const auto& piece) {
return piece.size == 0;
}) == out_msgs.end());
// At most one message is send to a target process.
assert(std::adjacent_find(out_msgs.begin(), out_msgs.end(),
[](const auto& left, const auto& right) {
return left.pe == right.pe;
}) == out_msgs.end());
return { out_msgs, max_num_recv_msgs, residual_capacity };
}
} // end namespace GroupMsgToPeAssignment
} // end namespace _internal
} // end namespace Ams
| 39.581395
| 185
| 0.55518
|
mschimek
|
50e8ee41caacdda0a250d42639c5595cf24aafe1
| 37
|
cpp
|
C++
|
examples/re2/foo.cpp
|
Costallat/hunter
|
dc0d79cb37b30cad6d6472d7143fe27be67e26d5
|
[
"BSD-2-Clause"
] | 2,146
|
2015-01-10T07:26:58.000Z
|
2022-03-21T02:28:01.000Z
|
examples/re2/foo.cpp
|
koinos/hunter
|
fc17bc391210bf139c55df7f947670c5dff59c57
|
[
"BSD-2-Clause"
] | 1,778
|
2015-01-03T11:50:30.000Z
|
2019-12-26T05:31:20.000Z
|
examples/re2/foo.cpp
|
koinos/hunter
|
fc17bc391210bf139c55df7f947670c5dff59c57
|
[
"BSD-2-Clause"
] | 734
|
2015-03-05T19:52:34.000Z
|
2022-02-22T23:18:54.000Z
|
#include <re2/re2.h>
int main() {
}
| 7.4
| 20
| 0.567568
|
Costallat
|
50f72987195c1135bc42e48dcc76495219ed1529
| 1,536
|
hh
|
C++
|
fluids/navier_stokes_2d.hh
|
jpanikulam/experiments
|
be36319a89f8baee54d7fa7618b885edb7025478
|
[
"MIT"
] | 1
|
2019-04-14T11:40:28.000Z
|
2019-04-14T11:40:28.000Z
|
fluids/navier_stokes_2d.hh
|
IJDykeman/experiments-1
|
22badf166b2ea441e953939463f751020b8c251b
|
[
"MIT"
] | 5
|
2018-04-18T13:54:29.000Z
|
2019-08-22T20:04:17.000Z
|
fluids/navier_stokes_2d.hh
|
IJDykeman/experiments-1
|
22badf166b2ea441e953939463f751020b8c251b
|
[
"MIT"
] | 1
|
2018-12-24T03:45:47.000Z
|
2018-12-24T03:45:47.000Z
|
#pragma once
#include "eigen.hh"
namespace jcc {
namespace fluids {
namespace plane {
struct SimulationConfig {
// Pressure constant
double rho = 1e3;
// Viscosity
double nu = 0.9;
// Grid spacing
double dx = 1e-2;
// Time step
double dt = 1e-5;
};
struct SimulationState {
Eigen::MatrixXd pressure_field;
std::array<Eigen::MatrixXd, 2> velocity_field;
EIGEN_MAKE_ALIGNED_OPERATOR_NEW;
};
struct JacobiConfig {
double alpha = -1e-1;
double beta = 4.0;
int max_iters = -1;
// Convergence criteria for jacobi iteration
double min_rel_delta = 1e-6;
};
// Solve a poisson equation
//
// That is:
// Generate an image `x` such that Δ(x) = b
//
Eigen::MatrixXd solve_poisson_jacobi_image(const Eigen::MatrixXd& x0,
const Eigen::MatrixXd& b,
const JacobiConfig& config);
std::array<Eigen::MatrixXd, 2> compute_advection(const std::array<Eigen::MatrixXd, 2> velocity_field,
const SimulationConfig& config);
std::array<Eigen::MatrixXd, 2> compute_pressure(const Eigen::MatrixXd pressure_field, const SimulationConfig& cfg);
std::array<Eigen::MatrixXd, 2> compute_diffusion(const std::array<Eigen::MatrixXd, 2> velocity_field,
const SimulationConfig& cfg);
SimulationState compute_projection(const SimulationState& state, const SimulationConfig& cfg);
} // namespace plane
} // namespace fluids
} // namespace jcc
| 26.482759
| 115
| 0.64388
|
jpanikulam
|
50ff3f5cd2efc9b268d82004c17bec7bf0f3d781
| 907
|
cpp
|
C++
|
tcmplx-access-plus/api.cpp
|
codylico/text-complex-plus
|
4d71d8ce86375cae69e326bfb7f9bb57768e508c
|
[
"Unlicense"
] | null | null | null |
tcmplx-access-plus/api.cpp
|
codylico/text-complex-plus
|
4d71d8ce86375cae69e326bfb7f9bb57768e508c
|
[
"Unlicense"
] | null | null | null |
tcmplx-access-plus/api.cpp
|
codylico/text-complex-plus
|
4d71d8ce86375cae69e326bfb7f9bb57768e508c
|
[
"Unlicense"
] | null | null | null |
/*
* \file tcmplx-access-plus/api.cpp
* \brief API-wide declarations for text-complex
* \author Cody Licorish (svgmovement@gmail.com)
*/
#define TCMPLX_AP_WIN32_DLL_INTERNAL
#include "api.hpp"
namespace text_complex {
namespace access {
//BEGIN configurations
char const* api_version(void) noexcept {
return "0.1";
}
//END configurations
//BEGIN error codes
char const* api_error_toa(api_error v) noexcept {
switch (v) {
case api_error::ErrParam:
return "Invalid parameter given";
case api_error::ErrSanitize:
return "File sanity check failed";
case api_error::ErrMemory:
return "Memory acquisition error";
case api_error::ErrInit:
return "Initialization error";
case api_error::Success:
return "Success";
default:
return nullptr;
}
}
//END error codes
};
};
| 24.513514
| 53
| 0.641676
|
codylico
|
dd03b44d009fc81f3ad7faad733cef61912fedf1
| 993
|
cpp
|
C++
|
Molecularity/Tool/Tool_Convert.cpp
|
kyle-robinson/directx-game
|
ff5964a6edd3241b703409976f27d68205b9ddd3
|
[
"CC-BY-4.0"
] | 1
|
2021-06-14T22:44:01.000Z
|
2021-06-14T22:44:01.000Z
|
Molecularity/Tool/Tool_Convert.cpp
|
kyle-robinson/directx-game
|
ff5964a6edd3241b703409976f27d68205b9ddd3
|
[
"CC-BY-4.0"
] | null | null | null |
Molecularity/Tool/Tool_Convert.cpp
|
kyle-robinson/directx-game
|
ff5964a6edd3241b703409976f27d68205b9ddd3
|
[
"CC-BY-4.0"
] | 1
|
2021-06-04T12:44:06.000Z
|
2021-06-04T12:44:06.000Z
|
#include "stdafx.h"
#include "Tool_Convert.h"
Tool_Convert::Tool_Convert()
{
EnergyCost = 25;
CurrentType = BoxType::Mesh;
MaxNumber = 2;
MinNumber = 0;
ChangeCurrent( 0 );
}
Tool_Convert::~Tool_Convert()
{ }
void Tool_Convert::ChangeCurrent( int number )
{
if ( number > MaxNumber )
number = MinNumber;
else if ( number < MinNumber )
number = MaxNumber;
CurrentType = static_cast<BoxType>( number );
}
void Tool_Convert::ChangeCurrent( std::string name )
{ }
void Tool_Convert::AddOneToCurrent()
{
Current++;
if ( Current > MaxNumber )
Current = MinNumber;
else if ( Current < 0 )
Current = MaxNumber;
CurrentType = static_cast<BoxType>( Current );
}
void Tool_Convert::MinusOneTOCurrent()
{
Current--;
if ( Current > MaxNumber )
Current = MinNumber;
else if ( Current < MinNumber )
Current = MaxNumber;
CurrentType = static_cast<BoxType>( Current );
}
ToolData Tool_Convert::GetToolData()
{
ToolData Data;
Data.boxtype = CurrentType;
return Data;
}
| 17.12069
| 52
| 0.698892
|
kyle-robinson
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.