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 108 | 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 67k ⌀ | 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2c1800df98fe466062565c9d0429f2c4745c0b53 | 1,501 | cpp | C++ | Bleach/main.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | 11 | 2015-08-29T13:41:22.000Z | 2020-01-08T20:34:06.000Z | Bleach/main.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | null | null | null | Bleach/main.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | 5 | 2016-01-20T18:17:01.000Z | 2019-10-30T11:57:15.000Z | #include <fstream>
#include <vector>
#include <bitset>
#include <queue>
using namespace std;
const char infile[] = "bleach.in";
const char outfile[] = "bleach.out";
ifstream fin(infile);
ofstream fout(outfile);
const int MAXN = 4005;
const int oo = 0x3f3f3f3f;
typedef vector<int> Graph[MAXN];
typedef vector<int> :: iterator It;
const inline int min(const int &a, const int &b) { if( a > b ) return b; return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b; return a; }
const inline void Get_min(int &a, const int b) { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b) { if( a < b ) a = b; }
int main() {
priority_queue <long long, vector<long long>, greater<long long> > Q;
long long N, K;
fin >> N >> K;
for(int i = 1 ; i <= K ; ++ i) {
long long x;
fin >> x;
Q.push(x);
}
long long A = 0;
long long add = 0;
/// A = puterea de acum;
for(long long i = K + 1 ; i <= N ; ++ i) {
long long x;
fin >> x;
Q.push(x);
long long B = Q.top();
if(A >= B)
A += B;
else {
add += (B - A);
A = 2 * B;
}
Q.pop();
}
while(!Q.empty()) {
long long B = Q.top();
if(A >= B)
A += B;
else {
add += (B - A);
A = 2 * B;
}
Q.pop();
}
fout << add << '\n';
fin.close();
fout.close();
return 0;
}
| 23.092308 | 86 | 0.477682 | rusucosmin |
2c1d2ce066a00712239431ee98b984e96cd7c364 | 476 | cpp | C++ | src/RESTAPI_unknownRequestHandler.cpp | shimmy568/wlan-cloud-ucentralgw | 806e24e1e666c31175c059373440ae029d9fff67 | [
"BSD-3-Clause"
] | null | null | null | src/RESTAPI_unknownRequestHandler.cpp | shimmy568/wlan-cloud-ucentralgw | 806e24e1e666c31175c059373440ae029d9fff67 | [
"BSD-3-Clause"
] | null | null | null | src/RESTAPI_unknownRequestHandler.cpp | shimmy568/wlan-cloud-ucentralgw | 806e24e1e666c31175c059373440ae029d9fff67 | [
"BSD-3-Clause"
] | null | null | null | //
// License type: BSD 3-Clause License
// License copy: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE
//
// Created by Stephane Bourque on 2021-03-04.
// Arilia Wireless Inc.
//
#include "RESTAPI_unknownRequestHandler.h"
void RESTAPI_UnknownRequestHandler::handleRequest(Poco::Net::HTTPServerRequest& Request, Poco::Net::HTTPServerResponse& Response)
{
if(!IsAuthorized(Request,Response))
return;
BadRequest(Response);
} | 28 | 129 | 0.754202 | shimmy568 |
2c1eb109ecfb359f640fce24cc599ef65144777a | 3,316 | cpp | C++ | test/unit/misc/bit_reversal.cpp | Nemo1369/libcds | 6c96ab635067b2018b14afe5dd0251b9af3ffddf | [
"BSD-2-Clause"
] | null | null | null | test/unit/misc/bit_reversal.cpp | Nemo1369/libcds | 6c96ab635067b2018b14afe5dd0251b9af3ffddf | [
"BSD-2-Clause"
] | null | null | null | test/unit/misc/bit_reversal.cpp | Nemo1369/libcds | 6c96ab635067b2018b14afe5dd0251b9af3ffddf | [
"BSD-2-Clause"
] | null | null | null | /*
This file is a part of libcds - Concurrent Data Structures library
(C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2017
Source code repo: http://github.com/khizmax/libcds/
Download: http://sourceforge.net/projects/libcds/files/
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cds_test/ext_gtest.h>
#include <cds/algo/bit_reversal.h>
namespace {
template <typename UInt>
class bit_reversal: public ::testing::Test
{
typedef UInt uint_type;
static std::vector<uint_type> arr_;
static size_t const c_size = 100'000'000;
public:
static void SetUpTestCase()
{
arr_.resize( c_size );
for ( size_t i = 0; i < c_size; ++i )
arr_[i] = static_cast<uint_type>((i << 32) + (~i));
}
static void TearDownTestCase()
{
arr_.resize( 0 );
}
template <typename Algo>
void test()
{
Algo f;
for ( auto i : arr_ ) {
EXPECT_EQ( i, f( f( i )));
}
}
template <typename Algo>
void test_eq()
{
Algo f;
for ( auto i : arr_ ) {
EXPECT_EQ( cds::algo::bit_reversal::swar()( i ), f( i ) ) << "i=" << i;
}
}
};
template <typename UInt> std::vector<UInt> bit_reversal<UInt>::arr_;
typedef bit_reversal<uint32_t> bit_reversal32;
typedef bit_reversal<uint64_t> bit_reversal64;
#define TEST_32BIT( x ) \
TEST_F( bit_reversal32, x ) { test<cds::algo::bit_reversal::x>(); } \
TEST_F( bit_reversal32, x##_eq ) { test_eq<cds::algo::bit_reversal::x>(); }
#define TEST_64BIT( x ) \
TEST_F( bit_reversal64, x ) { test<cds::algo::bit_reversal::x>(); } \
TEST_F( bit_reversal64, x##_eq ) { test_eq<cds::algo::bit_reversal::x>(); }
TEST_32BIT( swar )
TEST_32BIT( lookup )
TEST_32BIT( muldiv )
TEST_64BIT( swar )
TEST_64BIT( lookup )
TEST_64BIT( muldiv )
} // namespace
| 34.185567 | 87 | 0.642039 | Nemo1369 |
2c24b8af8865154153a12f626942b5190dbabeef | 4,069 | hpp | C++ | methods/islet/islet_npx.hpp | ambrad/COMPOSE | 0bda7aeaf2b8494c7de8cd179c22e340b08eda6e | [
"BSD-3-Clause"
] | 3 | 2018-12-30T20:01:25.000Z | 2020-07-22T23:44:14.000Z | methods/islet/islet_npx.hpp | E3SM-Project/COMPOSE | 0bda7aeaf2b8494c7de8cd179c22e340b08eda6e | [
"BSD-3-Clause"
] | 8 | 2019-02-06T19:08:31.000Z | 2020-04-24T03:40:49.000Z | methods/islet/islet_npx.hpp | ambrad/COMPOSE | 0bda7aeaf2b8494c7de8cd179c22e340b08eda6e | [
"BSD-3-Clause"
] | 2 | 2019-01-16T03:58:31.000Z | 2019-02-06T22:45:43.000Z | #ifndef INCLUDE_ISLET_NPX_HPP
#define INCLUDE_ISLET_NPX_HPP
#include "islet_util.hpp"
#include "islet_types.hpp"
#include "islet_tables.hpp"
#include "islet_interpmethod.hpp"
template <typename Scalar>
void eval_lagrange_poly (const Scalar* x_gll, const Int& np, const Scalar& x,
Scalar* const y) {
for (int i = 0; i < np; ++i) {
Scalar f = 1;
for (int j = 0; j < np; ++j)
f *= (i == j) ?
1 :
(x - x_gll[j]) / (x_gll[i] - x_gll[j]);
y[i] = f;
}
}
template <typename Scalar=Real>
struct npx {
static void eval (const Int np, const Scalar& x, Scalar* const v) {
eval_lagrange_poly(islet::get_x_gll(np), np, x, v);
}
};
template <typename Scalar=Real>
struct npxstab : public npx<Scalar> {
template <int np, int nreg>
static void eval (const std::array<int, nreg>& order,
const std::array<int, nreg>& os,
const Scalar& x, Scalar* const v) {
if (x > 0) {
eval<np, nreg>(order, os, -x, v);
for (int i = 0; i < np/2; ++i)
std::swap(v[i], v[np-i-1]);
return;
}
const auto x_gll = islet::get_x_gll(np);
bool done = false;
for (Int i = 0; i < nreg; ++i)
if (x < x_gll[i+1]) {
std::fill(v, v + np, 0);
eval_lagrange_poly(x_gll + os[i], order[i], x, v + os[i]);
done = true;
break;
}
if ( ! done)
eval_lagrange_poly(x_gll, np, x, v);
}
static void eval(const Int& np, const Scalar& x, Scalar* const v);
static int ooa_vs_np (const int np) {
if (np == 5) return 2;
return np - 1 - ((np-1)/3);
}
template <int np, int nreg, int alphanp>
static void eval (const std::array<int, nreg>& subnp,
const std::array<int, nreg>& os,
const std::array<Scalar, nreg*alphanp>& alphac,
const Scalar& x, Scalar* const v) {
if (x > 0) {
eval<np, nreg, alphanp>(subnp, os, alphac, -x, v);
for (int i = 0; i < np/2; ++i)
std::swap(v[i], v[np-i-1]);
return;
}
const auto x_gll = islet::get_x_gll(np);
bool done = false;
for (int i = 0; i < nreg; ++i)
if (x < x_gll[i+1]) {
eval_lagrange_poly(x_gll, np, x, v);
if (subnp[i] < np) {
Real w[12] = {0};
eval_lagrange_poly(x_gll + os[i], subnp[i], x, w + os[i]);
Real alpha = 0;
if (alphanp == 1)
alpha = alphac[i];
else {
assert(alphanp <= 3);
const auto alpha_r_gll = islet::get_x_gll(alphanp);
const auto r = (x - x_gll[i]) / (x_gll[i+1] - x_gll[i]);
Real a[3];
eval_lagrange_poly(alpha_r_gll, alphanp, r, a);
for (int j = 0; j < alphanp; ++j)
alpha += alphac[alphanp*i + j] * a[j];
}
for (int j = 0; j < np; ++j)
v[j] = alpha*v[j] + (1 - alpha)*w[j];
}
done = true;
break;
}
if ( ! done)
eval_lagrange_poly(x_gll, np, x, v);
}
};
struct InterpMethod {
typedef std::shared_ptr<InterpMethod> Ptr;
enum Type { notype, npx, npxstab, user };
Int np;
Type type;
std::shared_ptr<UserInterpMethod> uim;
static Type convert (const std::string& s) {
if (s == "npx") return npx;
if (s == "npxstab") return npxstab;
if (s == "user") return user;
throw std::runtime_error(std::string("Not an InterpMethod::Type: ") + s);
}
static std::string convert (const Type& t) {
if (t == npx) return "npx";
if (t == npxstab) return "npxstab";
if (t == user) return "user";
throw std::runtime_error("Not an InterpMethod::Type.");
}
InterpMethod () : np(-1), type(notype) {}
InterpMethod (Int inp, Type itype) : np(inp), type(itype) {}
InterpMethod (const std::shared_ptr<UserInterpMethod>& iuim)
: np(iuim->get_np()), type(user), uim(iuim) {}
const Real* get_xnodes() const {
return uim ? uim->get_xnodes() : islet::get_x_gll(np);
};
};
void op_eval(const InterpMethod& im, const Real a_src, Real* v);
#endif
| 29.485507 | 77 | 0.539936 | ambrad |
2c2564a4ccd403b51385fd91c1d0dcc9e6f6bf71 | 1,201 | hpp | C++ | code/AssetLib/XNAlara/XnalaraImporter.hpp | bradosia/assimp-XNAlara | db8963c06e6bcfd9433b0894a2bce98df069bc7a | [
"MIT"
] | 1 | 2020-12-25T02:43:29.000Z | 2020-12-25T02:43:29.000Z | code/AssetLib/XNAlara/XnalaraImporter.hpp | bradosia/assimp-XNAlara | db8963c06e6bcfd9433b0894a2bce98df069bc7a | [
"MIT"
] | null | null | null | code/AssetLib/XNAlara/XnalaraImporter.hpp | bradosia/assimp-XNAlara | db8963c06e6bcfd9433b0894a2bce98df069bc7a | [
"MIT"
] | 1 | 2020-12-25T02:43:31.000Z | 2020-12-25T02:43:31.000Z | #ifndef XNALARA_FILE_IMPORTER_H
#define XNALARA_FILE_IMPORTER_H
// C++
#include <sstream>
#include <vector>
/* assimp 5.0.1
* License: BSD
*/
#include <assimp/BaseImporter.h>
#include <assimp/IOSystem.hpp>
#include <assimp/material.h>
#include <assimp/scene.h>
// Local Project
#include "read_bin_xps.hpp"
namespace assimpXnalara {
/* @class XnalaraImporter
* @brief Imports Xnalara a .xps/.mesh/.mesh.ascii file
*/
class XnalaraImporter : public Assimp::BaseImporter {
public:
XnalaraImporter();
~XnalaraImporter();
public:
/* @brief Returns whether the class can handle the format of the given file.
* @remark See BaseImporter::CanRead() for details.
*/
bool CanRead(const std::string &pFile, Assimp::IOSystem *pIOHandler,
bool checkSig) const;
private:
/* @brief Appends the supported extension.
*/
const aiImporterDesc *GetInfo() const;
/* @brief File import implementation.
*/
void InternReadFile(const std::string &pFile, aiScene *pScene,
Assimp::IOSystem *pIOHandler);
};
// ------------------------------------------------------------------------------------------------
} // namespace assimpXnalara
#endif
| 22.660377 | 99 | 0.638634 | bradosia |
2c2772b33e1e11c89aba7847b2966eb1abf03591 | 2,085 | cpp | C++ | Codeforces/Goodbye 2020/1466E.cpp | ApocalypseMac/CP | b2db9aa5392a362dc0d979411788267ed9a5ff1d | [
"MIT"
] | null | null | null | Codeforces/Goodbye 2020/1466E.cpp | ApocalypseMac/CP | b2db9aa5392a362dc0d979411788267ed9a5ff1d | [
"MIT"
] | null | null | null | Codeforces/Goodbye 2020/1466E.cpp | ApocalypseMac/CP | b2db9aa5392a362dc0d979411788267ed9a5ff1d | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
typedef long long ll;
const int maxn = 500005;
const ll MOD = 1e9 + 7;
ll x[maxn];
int bitcnt[63];
int n, d, dm;
ll tmp, res, l, r;
ll m[63];
int main(){
ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
for (int i = 0; i < 63; ++i){
m[i] = (1LL << i) % MOD;
}
int T;
cin >> T;
for (; T > 0; --T){
// int n;
cin >> n;
// ll x[n];
memset(bitcnt, 0, sizeof(bitcnt));
// ll bitcnt[63] = {0LL};
// int d;
// int dm = 0;
dm = 0;
// ll tmp;
for (int i = 0; i < n; ++i){
d = 0;
cin >> x[i];
tmp = x[i];
while (tmp){
if (tmp & 1){
++bitcnt[d];
}
++d;
tmp >>= 1;
}
dm = max(dm, d + 1);
}
// ll res = 0LL;
res = 0LL;
// for (int j = 0; j < 62; ++j){
// cout << bitcnt[j] << " ";
// }
// bool isone[dm] = {0};
for (int i = 0; i < n; ++i){
l = 0LL; r = 0LL;
// cout << " " << x[i] << " ";
tmp = x[i];
// memset(isone, 0, sizeof(isone));
// d = 0;
// while (tmp){
// if (tmp & 1){
// isone[d] = true;
// }
// ++d;
// tmp >>= 1;
// }
for (int j = 0; j < dm; ++j){
if (tmp & 1){
l += bitcnt[j] * m[j];
r += n * m[j];
}
else{
r += bitcnt[j] * m[j];
}
tmp >>= 1;
l %= MOD;
r %= MOD;
}
res += l * r;
res %= MOD;
// cout << " " << l << " " << r << " " << res << endl;
}
cout << res << endl;
}
return 0;
} | 26.0625 | 76 | 0.302638 | ApocalypseMac |
2c2791889d601ee8bd542f686cdeb888398ab3c3 | 19,164 | cpp | C++ | src/SNC-Meister/SNC-Meister.cpp | timmyzhu/SNC-Meister | 7ecb5de94b4dae1c3c31d699bfe2289ab9f29abd | [
"MIT"
] | 5 | 2016-09-28T19:45:01.000Z | 2020-04-19T08:01:28.000Z | src/SNC-Meister/SNC-Meister.cpp | timmyzhu/SNC-Meister | 7ecb5de94b4dae1c3c31d699bfe2289ab9f29abd | [
"MIT"
] | null | null | null | src/SNC-Meister/SNC-Meister.cpp | timmyzhu/SNC-Meister | 7ecb5de94b4dae1c3c31d699bfe2289ab9f29abd | [
"MIT"
] | 4 | 2017-02-12T05:59:25.000Z | 2020-06-15T08:18:49.000Z | // SNC-Meister.cpp - SNC-Meister admission control server.
// Performs admission control for a network based on Stochastic Network Calculus (SNC) using SNC-Library.
// When a set of tenants (a.k.a. clients) seeks admission, their latency is calculated using SNC and compared against their SLO.
// Also, other clients that are affected by the new clients are checked to see if they meet their SLOs.
// If the new clients and affected clients meet their SLOs, then the new clients are admitted.
// If admitted and enforcerAddr/dstAddr/srcAddr are set in a client's flow (see "addrPrefix" option in SNC-ConfigGen), then NetEnforcer will be updated with its network priority.
// Priority is determined with the BySLO policy (i.e., with the tightest SLO getting the highest priority).
//
// Copyright (c) 2016 Timothy Zhu.
// Licensed under the MIT License. See LICENSE file for details.
//
#include <cassert>
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <sys/socket.h>
#include <netdb.h>
#include <rpc/rpc.h>
#include <rpc/pmap_clnt.h>
#include "../prot/SNC_Meister_prot.h"
#include "../prot/NetEnforcer_prot.h"
#include "../json/json.h"
#include "../SNC-Library/NC.hpp"
#include "../SNC-Library/SNC.hpp"
#include "../SNC-Library/priorityAlgoBySLO.hpp"
using namespace std;
// Global network calculus calculator
NC* nc;
// Global storage for clientInfos
map<ClientId, Json::Value> clientInfoStore;
// Convert a string internet address to an IP address
unsigned long addrInfo(string addr)
{
unsigned long s_addr = 0;
struct addrinfo* result;
int err = getaddrinfo(addr.c_str(), NULL, NULL, &result);
if ((err != 0) || (result == NULL)) {
cerr << "Error in getaddrinfo: " << err << endl;
} else {
for (struct addrinfo* res = result; res != NULL; res = res->ai_next) {
if (result->ai_addr->sa_family == AF_INET) {
s_addr = ((struct sockaddr_in*)result->ai_addr)->sin_addr.s_addr;
break;
}
}
freeaddrinfo(result);
}
return s_addr;
}
// Send RPC to NetEnforcer to update client
void updateClient(string enforcerAddr, string dstAddr, string srcAddr, unsigned int priority)
{
// Connect to enforcer
CLIENT* cl;
if ((cl = clnt_create(enforcerAddr.c_str(), NET_ENFORCER_PROGRAM, NET_ENFORCER_V1, "tcp")) == NULL) {
clnt_pcreateerror(enforcerAddr.c_str());
return;
}
// Call RPC
NetClientUpdate arg;
arg.client.s_dstAddr = addrInfo(dstAddr);
arg.client.s_srcAddr = addrInfo(srcAddr);
arg.priority = priority;
NetUpdateClientsArgs args = {1, &arg};
if (net_enforcer_update_clients_1(args, cl) == NULL) {
clnt_perror(cl, "Failed network RPC");
}
// Destroy client
clnt_destroy(cl);
}
// Send RPC to NetEnforcer to remove client
void removeClient(string enforcerAddr, string dstAddr, string srcAddr)
{
// Connect to enforcer
CLIENT* cl;
if ((cl = clnt_create(enforcerAddr.c_str(), NET_ENFORCER_PROGRAM, NET_ENFORCER_V1, "tcp")) == NULL) {
clnt_pcreateerror(enforcerAddr.c_str());
return;
}
// Call RPC
NetClient arg;
arg.s_dstAddr = addrInfo(dstAddr);
arg.s_srcAddr = addrInfo(srcAddr);
NetRemoveClientsArgs args = {1, &arg};
if (net_enforcer_remove_clients_1(args, cl) == NULL) {
clnt_perror(cl, "Failed network RPC");
}
// Destroy client
clnt_destroy(cl);
}
// Check the JSON flowInfo objects.
// Returns error for invalid arguments.
SNCStatus checkFlowInfo(set<string>& flowNames, const Json::Value& flowInfo)
{
// Check name
if (!flowInfo.isMember("name")) {
return SNC_ERR_MISSING_ARGUMENT;
}
string name = flowInfo["name"].asString();
if (nc->getFlowIdByName(name) != InvalidFlowId) {
return SNC_ERR_FLOW_NAME_IN_USE;
}
if (flowNames.find(name) != flowNames.end()) {
return SNC_ERR_FLOW_NAME_IN_USE;
}
flowNames.insert(name);
// Check queues
if (!flowInfo.isMember("queues")) {
return SNC_ERR_MISSING_ARGUMENT;
}
const Json::Value& flowQueues = flowInfo["queues"];
if (!flowQueues.isArray()) {
return SNC_ERR_INVALID_ARGUMENT;
}
for (unsigned int index = 0; index < flowQueues.size(); index++) {
string queueName = flowQueues[index].asString();
if (nc->getQueueIdByName(queueName) == InvalidQueueId) {
return SNC_ERR_QUEUE_NAME_NONEXISTENT;
}
}
// Check arrivalInfo
if (!flowInfo.isMember("arrivalInfo")) {
return SNC_ERR_MISSING_ARGUMENT;
}
return SNC_SUCCESS;
}
// Check the JSON clientInfo objects.
// Returns error for invalid arguments.
SNCStatus checkClientInfo(set<string>& clientNames, set<string>& flowNames, const Json::Value& clientInfo)
{
// Check name
if (!clientInfo.isMember("name")) {
return SNC_ERR_MISSING_ARGUMENT;
}
string name = clientInfo["name"].asString();
if (nc->getClientIdByName(name) != InvalidClientId) {
return SNC_ERR_CLIENT_NAME_IN_USE;
}
if (clientNames.find(name) != clientNames.end()) {
return SNC_ERR_CLIENT_NAME_IN_USE;
}
clientNames.insert(name);
// Check SLO
if (!clientInfo.isMember("SLO")) {
return SNC_ERR_MISSING_ARGUMENT;
}
double SLO = clientInfo["SLO"].asDouble();
if (SLO <= 0) {
return SNC_ERR_INVALID_ARGUMENT;
}
// Check SLOpercentile
if (clientInfo.isMember("SLOpercentile")) {
double SLOpercentile = clientInfo["SLOpercentile"].asDouble();
if (!((0 < SLOpercentile) && (SLOpercentile < 100))) {
return SNC_ERR_INVALID_ARGUMENT;
}
}
// Check client's flows
if (!clientInfo.isMember("flows")) {
return SNC_ERR_MISSING_ARGUMENT;
}
const Json::Value& clientFlows = clientInfo["flows"];
if (!clientFlows.isArray()) {
return SNC_ERR_INVALID_ARGUMENT;
}
for (unsigned int flowIndex = 0; flowIndex < clientFlows.size(); flowIndex++) {
SNCStatus status = checkFlowInfo(flowNames, clientFlows[flowIndex]);
if (status != SNC_SUCCESS) {
return status;
}
}
return SNC_SUCCESS;
}
// Check list of JSON clientInfo objects.
// Returns error for invalid arguments.
SNCStatus checkClientInfos(const Json::Value& clientInfos)
{
// Check clientInfos is an array
if (!clientInfos.isArray()) {
return SNC_ERR_INVALID_ARGUMENT;
}
set<string> clientNames; // ensure no duplicate names
set<string> flowNames; // ensure no duplicate names
for (unsigned int i = 0; i < clientInfos.size(); i++) {
SNCStatus status = checkClientInfo(clientNames, flowNames, clientInfos[i]);
if (status != SNC_SUCCESS) {
return status;
}
}
return SNC_SUCCESS;
}
// Adds dependencies between clients based on the RPC arguments.
// Returns error for invalid arguments.
SNCStatus addDependencies(const Json::Value& clientInfo)
{
if (clientInfo.isMember("dependencies")) {
const Json::Value& dependencies = clientInfo["dependencies"];
if (!dependencies.isArray()) {
return SNC_ERR_INVALID_ARGUMENT;
}
ClientId clientId = nc->getClientIdByName(clientInfo["name"].asString());
assert(clientId != InvalidClientId);
for (unsigned int i = 0; i < dependencies.size(); i++) {
ClientId dependency = nc->getClientIdByName(dependencies[i].asString());
if (dependency == InvalidClientId) {
return SNC_ERR_CLIENT_NAME_NONEXISTENT;
}
nc->addDependency(clientId, dependency);
}
}
return SNC_SUCCESS;
}
// FlowIndex less than function
bool operator< (const FlowIndex& fi1, const FlowIndex& fi2)
{
if (fi1.flowId == fi2.flowId) {
return (fi1.index < fi2.index);
}
return (fi1.flowId < fi2.flowId);
}
// Mark flows affected at a priority level starting from a flow at a given index.
void markAffectedFlows(set<FlowIndex>& affectedFlows, const FlowIndex& fi, unsigned int priority)
{
const Flow* f = nc->getFlow(fi.flowId);
// If f is higher priority, it is unaffected
if (f->priority < priority) {
return;
}
// If we've already marked flow at given index, stop
if (affectedFlows.find(fi) != affectedFlows.end()) {
return;
}
affectedFlows.insert(fi);
// Loop through queues affected by flow starting at index
for (unsigned int index = fi.index; index < f->queueIds.size(); index++) {
const Queue* q = nc->getQueue(f->queueIds[index]);
// Try marking other flows sharing queue
for (vector<FlowIndex>::const_iterator itFi = q->flows.begin(); itFi != q->flows.end(); itFi++) {
markAffectedFlows(affectedFlows, *itFi, f->priority);
}
}
}
// AddClients RPC - performs admission control check on a set of clients and adds clients to system if admitted.
SNCAddClientsRes* snc_meister_add_clients_svc(SNCAddClientsArgs* argp, struct svc_req* rqstp)
{
static SNCAddClientsRes result;
// Initialize result
result.admitted = true;
result.status = SNC_SUCCESS;
// Parse input
Json::Reader reader;
Json::Value clientInfos;
string clientInfosStr(argp->clientInfos);
if (!reader.parse(clientInfosStr, clientInfos)) {
result.status = SNC_ERR_INVALID_ARGUMENT;
result.admitted = false;
return &result;
}
// Check parameters
result.status = checkClientInfos(clientInfos);
if (result.status != SNC_SUCCESS) {
result.admitted = false;
return &result;
}
// Add clients
set<ClientId> clientIds;
for (unsigned int i = 0; i < clientInfos.size(); i++) {
const Json::Value& clientInfo = clientInfos[i];
ClientId clientId = nc->addClient(clientInfo);
clientIds.insert(clientId);
clientInfoStore[clientId] = clientInfo;
}
// Add dependencies
for (unsigned int i = 0; i < clientInfos.size(); i++) {
result.status = addDependencies(clientInfos[i]);
if (result.status != SNC_SUCCESS) {
result.admitted = false;
break;
}
}
if (result.status == SNC_SUCCESS) {
// Configure priorities
configurePrioritiesBySLO(nc);
// Check latency of added clients
set<FlowIndex> affectedFlows;
for (set<ClientId>::const_iterator it = clientIds.begin(); it != clientIds.end(); it++) {
ClientId clientId = *it;
nc->calcClientLatency(clientId);
const Client* c = nc->getClient(clientId);
if (c->latency > c->SLO) {
result.admitted = false;
break;
}
// Add affected flows
for (vector<FlowId>::const_iterator itF = c->flowIds.begin(); itF != c->flowIds.end(); itF++) {
FlowIndex fi;
fi.flowId = *itF;
fi.index = 0;
markAffectedFlows(affectedFlows, fi, 0);
}
}
if (result.admitted) {
// Get clientIds of affected flows
set<ClientId> affectedClientIds;
for (set<FlowIndex>::const_iterator it = affectedFlows.begin(); it != affectedFlows.end(); it++) {
const Flow* f = nc->getFlow(it->flowId);
affectedClientIds.insert(f->clientId);
}
// Check latency of other affected clients
for (set<ClientId>::const_iterator it = affectedClientIds.begin(); it != affectedClientIds.end(); it++) {
ClientId clientId = *it;
if (clientIds.find(clientId) == clientIds.end()) {
nc->calcClientLatency(clientId);
const Client* c = nc->getClient(clientId);
if (c->latency > c->SLO) {
result.admitted = false;
break;
}
}
}
}
}
if (result.admitted) {
// Send RPC to NetEnforcer to update client
for (unsigned int i = 0; i < clientInfos.size(); i++) {
const Json::Value& clientInfo = clientInfos[i];
const Json::Value& clientFlows = clientInfo["flows"];
for (unsigned int flowIndex = 0; flowIndex < clientFlows.size(); flowIndex++) {
const Json::Value& flowInfo = clientFlows[flowIndex];
if (flowInfo.isMember("enforcerAddr") && flowInfo.isMember("dstAddr") && flowInfo.isMember("srcAddr")) {
FlowId flowId = nc->getFlowIdByName(flowInfo["name"].asString());
const Flow* f = nc->getFlow(flowId);
updateClient(flowInfo["enforcerAddr"].asString(), flowInfo["dstAddr"].asString(), flowInfo["srcAddr"].asString(), f->priority);
}
}
}
} else {
// Delete clients
for (set<ClientId>::const_iterator it = clientIds.begin(); it != clientIds.end(); it++) {
ClientId clientId = *it;
clientInfoStore.erase(clientId);
nc->delClient(clientId);
}
}
return &result;
}
// DelClient RPC - delete a client from system.
SNCDelClientRes* snc_meister_del_client_svc(SNCDelClientArgs* argp, struct svc_req* rqstp)
{
static SNCDelClientRes result;
string name(argp->name);
ClientId clientId = nc->getClientIdByName(name);
// Check that client exists
if (clientId == InvalidClientId) {
result.status = SNC_ERR_CLIENT_NAME_NONEXISTENT;
return &result;
}
// Send RPC to NetEnforcer to remove client
assert(clientInfoStore.find(clientId) != clientInfoStore.end());
const Json::Value& clientInfo = clientInfoStore[clientId];
const Json::Value& clientFlows = clientInfo["flows"];
for (unsigned int flowIndex = 0; flowIndex < clientFlows.size(); flowIndex++) {
const Json::Value& flowInfo = clientFlows[flowIndex];
if (flowInfo.isMember("enforcerAddr") && flowInfo.isMember("dstAddr") && flowInfo.isMember("srcAddr")) {
removeClient(flowInfo["enforcerAddr"].asString(), flowInfo["dstAddr"].asString(), flowInfo["srcAddr"].asString());
}
}
// Delete client
clientInfoStore.erase(clientId);
nc->delClient(clientId);
result.status = SNC_SUCCESS;
return &result;
}
// AddQueue RPC - add a queue to system.
SNCAddQueueRes* snc_meister_add_queue_svc(SNCAddQueueArgs* argp, struct svc_req* rqstp)
{
static SNCAddQueueRes result;
// Parse input
Json::Reader reader;
Json::Value queueInfo;
string queueInfoStr(argp->queueInfo);
if (!reader.parse(queueInfoStr, queueInfo)) {
result.status = SNC_ERR_INVALID_ARGUMENT;
return &result;
}
// Check for valid name
if (!queueInfo.isMember("name")) {
result.status = SNC_ERR_MISSING_ARGUMENT;
return &result;
}
if (nc->getQueueIdByName(queueInfo["name"].asString()) != InvalidQueueId) {
result.status = SNC_ERR_QUEUE_NAME_IN_USE;
return &result;
}
// Check for valid bandwidth
if (!queueInfo.isMember("bandwidth")) {
result.status = SNC_ERR_MISSING_ARGUMENT;
return &result;
}
if (queueInfo["bandwidth"].asDouble() <= 0) {
result.status = SNC_ERR_INVALID_ARGUMENT;
return &result;
}
// Add queue
nc->addQueue(queueInfo);
result.status = SNC_SUCCESS;
return &result;
}
// DelQueue RPC - delete a queue from system.
SNCDelQueueRes* snc_meister_del_queue_svc(SNCDelQueueArgs* argp, struct svc_req* rqstp)
{
static SNCDelQueueRes result;
string name(argp->name);
QueueId queueId = nc->getQueueIdByName(name);
// Check that queue exists
if (queueId == InvalidQueueId) {
result.status = SNC_ERR_QUEUE_NAME_NONEXISTENT;
return &result;
}
// Check that queue is empty
const Queue* q = nc->getQueue(queueId);
assert(q != NULL);
if (!q->flows.empty()) {
result.status = SNC_ERR_QUEUE_HAS_ACTIVE_FLOWS;
return &result;
}
// Delete queue
nc->delQueue(queueId);
result.status = SNC_SUCCESS;
return &result;
}
// Main RPC handler
void snc_meister_program(struct svc_req* rqstp, register SVCXPRT* transp)
{
union {
SNCAddClientsArgs snc_meister_add_clients_arg;
SNCDelClientArgs snc_meister_del_client_arg;
SNCAddQueueArgs snc_meister_add_queue_arg;
SNCDelQueueArgs snc_meister_del_queue_arg;
} argument;
char* result;
xdrproc_t _xdr_argument, _xdr_result;
char* (*local)(char*, struct svc_req*);
switch (rqstp->rq_proc) {
case SNC_MEISTER_NULL:
svc_sendreply(transp, (xdrproc_t)xdr_void, (caddr_t)NULL);
return;
case SNC_MEISTER_ADD_CLIENTS:
_xdr_argument = (xdrproc_t)xdr_SNCAddClientsArgs;
_xdr_result = (xdrproc_t)xdr_SNCAddClientsRes;
local = (char* (*)(char*, struct svc_req*))snc_meister_add_clients_svc;
break;
case SNC_MEISTER_DEL_CLIENT:
_xdr_argument = (xdrproc_t)xdr_SNCDelClientArgs;
_xdr_result = (xdrproc_t)xdr_SNCDelClientRes;
local = (char* (*)(char*, struct svc_req*))snc_meister_del_client_svc;
break;
case SNC_MEISTER_ADD_QUEUE:
_xdr_argument = (xdrproc_t)xdr_SNCAddQueueArgs;
_xdr_result = (xdrproc_t)xdr_SNCAddQueueRes;
local = (char* (*)(char*, struct svc_req*))snc_meister_add_queue_svc;
break;
case SNC_MEISTER_DEL_QUEUE:
_xdr_argument = (xdrproc_t)xdr_SNCDelQueueArgs;
_xdr_result = (xdrproc_t)xdr_SNCDelQueueRes;
local = (char* (*)(char*, struct svc_req*))snc_meister_del_queue_svc;
break;
default:
svcerr_noproc(transp);
return;
}
memset((char*)&argument, 0, sizeof(argument));
if (!svc_getargs(transp, (xdrproc_t)_xdr_argument, (caddr_t)&argument)) {
svcerr_decode(transp);
return;
}
result = (*local)((char*)&argument, rqstp);
if (result != NULL && !svc_sendreply(transp, (xdrproc_t)_xdr_result, result)) {
svcerr_systemerr(transp);
}
if (!svc_freeargs(transp, (xdrproc_t)_xdr_argument, (caddr_t)&argument)) {
cerr << "Unable to free arguments" << endl;
}
}
int main(int argc, char** argv)
{
// Create NC
nc = new SNC();
// Unregister SNC-Meister RPC handlers
pmap_unset(SNC_MEISTER_PROGRAM, SNC_MEISTER_V1);
// Replace tcp RPC handlers
register SVCXPRT *transp;
transp = svctcp_create(RPC_ANYSOCK, 0, 0);
if (transp == NULL) {
cerr << "Failed to create tcp service" << endl;
delete nc;
return 1;
}
if (!svc_register(transp, SNC_MEISTER_PROGRAM, SNC_MEISTER_V1, snc_meister_program, IPPROTO_TCP)) {
cerr << "Failed to register tcp SNC-Meister" << endl;
delete nc;
return 1;
}
// Run proxy
svc_run();
cerr << "svc_run returned" << endl;
delete nc;
return 1;
}
| 35.554731 | 178 | 0.632749 | timmyzhu |
2c287d1d11f64b02c40201ad39367c8cf8ae089b | 7,015 | cc | C++ | onnxruntime/core/optimizer/conv_bn_fusion.cc | csteegz/onnxruntime | a36810471b346ec862ac6e4de7f877653f49525e | [
"MIT"
] | 1 | 2020-07-12T15:23:49.000Z | 2020-07-12T15:23:49.000Z | onnxruntime/core/optimizer/conv_bn_fusion.cc | ajinkya933/onnxruntime | 0e799a03f2a99da6a1b87a2cd37facb420c482aa | [
"MIT"
] | null | null | null | onnxruntime/core/optimizer/conv_bn_fusion.cc | ajinkya933/onnxruntime | 0e799a03f2a99da6a1b87a2cd37facb420c482aa | [
"MIT"
] | 1 | 2020-09-09T06:55:51.000Z | 2020-09-09T06:55:51.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/graph/graph_utils.h"
#include "core/optimizer/initializer.h"
#include "core/optimizer/conv_bn_fusion.h"
using namespace ONNX_NAMESPACE;
using namespace ::onnxruntime::common;
namespace onnxruntime {
Status ConvBNFusion::Apply(Graph& graph, Node& node, RewriteRuleEffect& rule_effect) const {
auto& conv_node = node;
const Node& bn_node = *conv_node.OutputNodesBegin();
// Get value of attribute epsilon
const onnxruntime::NodeAttributes& attributes = bn_node.GetAttributes();
const ONNX_NAMESPACE::AttributeProto* attr = &(attributes.find("epsilon")->second);
if (attr == nullptr || attr->type() != AttributeProto_AttributeType_FLOAT) {
return Status::OK();
}
float epsilon = static_cast<float>(attr->f());
// Get initializers of BatchNormalization
const auto& bn_inputs = bn_node.InputDefs();
const auto* bn_scale_tensor_proto = graph_utils::GetConstantInitializer(graph, bn_inputs[1]->Name());
ORT_ENFORCE(bn_scale_tensor_proto);
const auto* bn_B_tensor_proto = graph_utils::GetConstantInitializer(graph, bn_inputs[2]->Name());
ORT_ENFORCE(bn_B_tensor_proto);
const auto* bn_mean_tensor_proto = graph_utils::GetConstantInitializer(graph, bn_inputs[3]->Name());
ORT_ENFORCE(bn_mean_tensor_proto);
const auto* bn_var_tensor_proto = graph_utils::GetConstantInitializer(graph, bn_inputs[4]->Name());
ORT_ENFORCE(bn_var_tensor_proto);
const auto& conv_inputs = conv_node.InputDefs();
const auto* conv_W_tensor_proto = graph_utils::GetConstantInitializer(graph, conv_inputs[1]->Name());
ORT_ENFORCE(conv_W_tensor_proto);
// Currently, fusion is only supported for float or double data type.
if (!Initializer::IsSupportedDataType(bn_scale_tensor_proto) ||
!Initializer::IsSupportedDataType(bn_B_tensor_proto) ||
!Initializer::IsSupportedDataType(bn_mean_tensor_proto) ||
!Initializer::IsSupportedDataType(bn_var_tensor_proto) ||
!Initializer::IsSupportedDataType(conv_W_tensor_proto) ||
bn_scale_tensor_proto->dims_size() != 1 ||
bn_B_tensor_proto->dims_size() != 1 ||
bn_mean_tensor_proto->dims_size() != 1 ||
bn_var_tensor_proto->dims_size() != 1 ||
bn_scale_tensor_proto->dims(0) != bn_B_tensor_proto->dims(0) ||
bn_B_tensor_proto->dims(0) != bn_mean_tensor_proto->dims(0) ||
bn_mean_tensor_proto->dims(0) != bn_var_tensor_proto->dims(0) ||
bn_scale_tensor_proto->data_type() != bn_B_tensor_proto->data_type() ||
bn_B_tensor_proto->data_type() != bn_mean_tensor_proto->data_type() ||
bn_mean_tensor_proto->data_type() != bn_var_tensor_proto->data_type() ||
conv_W_tensor_proto->data_type() != bn_scale_tensor_proto->data_type() ||
!(conv_W_tensor_proto->dims_size() > 2 && conv_W_tensor_proto->dims(0) == bn_scale_tensor_proto->dims(0))) {
return Status::OK();
}
auto bn_scale = onnxruntime::make_unique<Initializer>(bn_scale_tensor_proto);
auto bn_B = onnxruntime::make_unique<Initializer>(bn_B_tensor_proto);
auto bn_mean = onnxruntime::make_unique<Initializer>(bn_mean_tensor_proto);
auto bn_var = onnxruntime::make_unique<Initializer>(bn_var_tensor_proto);
auto conv_W = onnxruntime::make_unique<Initializer>(conv_W_tensor_proto);
std::unique_ptr<Initializer> conv_B = nullptr;
const ONNX_NAMESPACE::TensorProto* conv_B_tensor_proto = nullptr;
if (conv_inputs.size() == 3) {
conv_B_tensor_proto = graph_utils::GetConstantInitializer(graph, conv_inputs[2]->Name());
ORT_ENFORCE(conv_B_tensor_proto);
if (!Initializer::IsSupportedDataType(conv_B_tensor_proto) ||
conv_B_tensor_proto->dims_size() != 1 ||
conv_B_tensor_proto->dims(0) != bn_B_tensor_proto->dims(0) ||
conv_B_tensor_proto->data_type() != bn_B_tensor_proto->data_type()) {
return Status::OK();
}
conv_B = onnxruntime::make_unique<Initializer>(conv_B_tensor_proto);
}
// Calculate new value of initializers of conv node
bn_var->add(epsilon);
bn_var->sqrt();
bn_scale->div(*bn_var);
conv_W->scale_by_axis(*bn_scale, 1);
if (conv_inputs.size() == 3) {
conv_B->sub(*bn_mean);
conv_B->mul(*bn_scale);
conv_B->add(*bn_B);
} else {
bn_mean->mul(*bn_scale);
bn_B->sub(*bn_mean);
}
// Create new initializers of conv
ONNX_NAMESPACE::TensorProto new_conv_W_tensor_proto(*conv_W_tensor_proto);
conv_W->ToProto(&new_conv_W_tensor_proto);
ONNX_NAMESPACE::TensorProto new_conv_B_tensor_proto;
NodeArg* bn_B_node_arg = nullptr;
if (conv_inputs.size() == 3) {
conv_B->ToProto(&new_conv_B_tensor_proto);
} else {
bn_B->ToProto(&new_conv_B_tensor_proto);
bn_B_node_arg = graph.GetNodeArg(bn_B_tensor_proto->name());
if (bn_B_node_arg == nullptr) {
return Status::OK();
}
}
// Replace initializers of conv node
graph_utils::ReplaceInitializer(graph, conv_W_tensor_proto->name(), new_conv_W_tensor_proto);
if (conv_inputs.size() == 3) {
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 6011) // Not deferencing null pointer. conv_B_tensor_proto is set on line 93
#endif
graph_utils::ReplaceInitializer(graph, conv_B_tensor_proto->name(), new_conv_B_tensor_proto);
#ifdef _MSC_VER
#pragma warning(pop)
#endif
} else {
graph_utils::ReplaceInitializer(graph, bn_B_tensor_proto->name(), new_conv_B_tensor_proto);
conv_node.MutableInputDefs().push_back(bn_B_node_arg);
conv_node.MutableInputArgsCount()[2] = 1;
}
// Remove BN node.
auto* bn_node_to_remove = graph.GetNode(bn_node.Index());
if (graph_utils::RemoveNode(graph, *bn_node_to_remove)) {
rule_effect = RewriteRuleEffect::kModifiedRestOfGraph;
}
return Status::OK();
}
bool ConvBNFusion::SatisfyCondition(const Graph& graph, const Node& node) const {
if (!graph_utils::IsSupportedOptypeVersionAndDomain(node, "Conv", {1, 11}) ||
node.GetOutputEdgesCount() != 1) {
return false;
}
const auto& next_node = *node.OutputNodesBegin();
if (!graph_utils::IsSupportedOptypeVersionAndDomain(next_node, "BatchNormalization", {7, 9}) ||
next_node.GetInputEdgesCount() != 1 || graph.IsNodeOutputsInGraphOutputs(next_node) ||
// Make sure the two nodes do not span execution providers.
next_node.GetExecutionProviderType() != node.GetExecutionProviderType()) {
return false;
}
// Check that the appropriate inputs to the Conv and BN nodes are constants.
if (!graph_utils::NodeArgIsConstant(graph, *node.InputDefs()[1]) ||
(node.InputDefs().size() == 3 && !graph_utils::NodeArgIsConstant(graph, *node.InputDefs()[2])) ||
!graph_utils::NodeArgIsConstant(graph, *next_node.InputDefs()[1]) ||
!graph_utils::NodeArgIsConstant(graph, *next_node.InputDefs()[2]) ||
!graph_utils::NodeArgIsConstant(graph, *next_node.InputDefs()[3]) ||
!graph_utils::NodeArgIsConstant(graph, *next_node.InputDefs()[4])) {
return false;
}
return true;
}
} // namespace onnxruntime
| 41.023392 | 114 | 0.728154 | csteegz |
2c2e2fcea640fc1ca20ba422ea384917d32a9de9 | 16,588 | cpp | C++ | pyqstrat/cpp/text_file_parsers.cpp | vishalbelsare/pyqstrat | 10a94ae7275609a2b89e309222089932293bfe6f | [
"BSD-3-Clause"
] | 284 | 2018-08-16T19:16:28.000Z | 2022-03-28T15:01:10.000Z | pyqstrat/cpp/text_file_parsers.cpp | vishalbelsare/pyqstrat | 10a94ae7275609a2b89e309222089932293bfe6f | [
"BSD-3-Clause"
] | 20 | 2018-08-29T15:54:08.000Z | 2022-01-16T20:45:55.000Z | pyqstrat/cpp/text_file_parsers.cpp | vishalbelsare/pyqstrat | 10a94ae7275609a2b89e309222089932293bfe6f | [
"BSD-3-Clause"
] | 47 | 2018-09-06T23:50:39.000Z | 2022-03-26T14:01:05.000Z |
#include "text_file_parsers.hpp"
#include "date.hpp"
using namespace std;
#define parse_error(msg) \
{ \
std::ostringstream os; \
os << msg << " file: " << __FILE__ << "line: " << __LINE__ ; \
throw ParseException(os.str().c_str()); \
}
FormatTimestampParser::FormatTimestampParser(int64_t base_date, const std::string& time_format, bool micros) :
_base_date(base_date),
_micros(micros) {
_time_format = "%Y-%m-%dT" + time_format;
}
int64_t FormatTimestampParser::call(const std::string& time) {
ostringstream ostr;
ostr << "1970-01-01T" << time;
int64_t timestamp = str_to_timestamp(ostr.str(), _time_format, _micros);
if (_micros) timestamp += _base_date * 1000;
else timestamp += _base_date;
return timestamp;
}
ParseException::ParseException(const char* m) : std::runtime_error(m) { }
TextQuoteParser::TextQuoteParser(CheckFields* is_quote,
int64_t base_date,
const vector<int>& timestamp_indices,
int bid_offer_idx,
int price_idx,
int qty_idx,
const vector<int>& id_field_indices,
const vector<int>& meta_field_indices,
const vector<TimestampParser*>& timestamp_parsers,
const string& bid_str,
const string& offer_str,
float price_multiplier,
bool strip_id,
bool strip_meta) :
_is_quote(is_quote),
_base_date(base_date),
_timestamp_indices(timestamp_indices),
_bid_offer_idx(bid_offer_idx),
_price_idx(price_idx),
_qty_idx(qty_idx),
_id_field_indices(id_field_indices),
_meta_field_indices(meta_field_indices),
_timestamp_parsers(timestamp_parsers),
_bid_str(bid_str),
_offer_str(offer_str),
_price_multiplier(price_multiplier),
_strip_id(strip_id),
_strip_meta(strip_meta) {
if (timestamp_parsers.size() != timestamp_indices.size()) error("size of timestamp_parsers vector and timestamp_indices must match");
}
shared_ptr<Record> TextQuoteParser::call(const vector<string>& fields) {
if (_is_quote && !_is_quote->call(fields)) return nullptr;
int64_t timestamp = _base_date;
int i = 0;
for (auto idx : _timestamp_indices) {
timestamp += _timestamp_parsers[i++]->call(fields[idx]);
}
const string& bid_offer_str = fields[_bid_offer_idx];
bool bid;
if (bid_offer_str == _bid_str) bid = true;
else if (bid_offer_str == _offer_str) bid = false;
else parse_error("unknown bid offer string: " << bid_offer_str);
float price = str_to_float(fields[_price_idx]) / _price_multiplier;
float qty = str_to_float(fields[_qty_idx]);
string id = join_fields(fields, _id_field_indices, '|', _strip_id);
string meta = join_fields(fields, _meta_field_indices, '|', _strip_meta);
return shared_ptr<Record>(new QuoteRecord(id, timestamp, bid, qty, price, meta));
}
TextQuotePairParser::TextQuotePairParser(CheckFields* is_quote_pair,
int64_t base_date,
const vector<int>& timestamp_indices,
int bid_price_idx,
int bid_qty_idx,
int ask_price_idx,
int ask_qty_idx,
const vector<int>& id_field_indices,
const vector<int>& meta_field_indices,
const vector<TimestampParser*>& timestamp_parsers,
float price_multiplier,
bool strip_id,
bool strip_meta) :
_is_quote_pair(is_quote_pair),
_base_date(base_date),
_timestamp_indices(timestamp_indices),
_bid_price_idx(bid_price_idx),
_bid_qty_idx(bid_qty_idx),
_ask_price_idx(ask_price_idx),
_ask_qty_idx(ask_qty_idx),
_id_field_indices(id_field_indices),
_meta_field_indices(meta_field_indices),
_timestamp_parsers(timestamp_parsers),
_price_multiplier(price_multiplier),
_strip_id(strip_id),
_strip_meta(strip_meta) {
if (timestamp_parsers.size() != timestamp_indices.size()) error("size of timestamp_parsers vector and timestamp_indices must match");
}
shared_ptr<Record> TextQuotePairParser::call(const vector<string>& fields) {
if (_is_quote_pair && !_is_quote_pair->call(fields)) return nullptr;
int64_t timestamp = _base_date;
int i = 0;
for (auto idx : _timestamp_indices) {
timestamp += _timestamp_parsers[i++]->call(fields[idx]);
}
float bid_price = str_to_float(fields[_bid_price_idx]) / _price_multiplier;
float bid_qty = str_to_float(fields[_bid_qty_idx]);
float ask_price = str_to_float(fields[_ask_price_idx]) / _price_multiplier;
float ask_qty = str_to_float(fields[_ask_qty_idx]);
string id = join_fields(fields, _id_field_indices, '|', _strip_id);
string meta = join_fields(fields, _meta_field_indices, '|', _strip_meta);
return shared_ptr<Record>(new QuotePairRecord(id, timestamp, bid_price, bid_qty, ask_price, ask_qty, meta));
}
TextTradeParser::TextTradeParser(CheckFields* is_trade,
int64_t base_date,
const vector<int>& timestamp_indices,
int price_idx,
int qty_idx,
const vector<int>& id_field_indices,
const vector<int>& meta_field_indices,
const vector<TimestampParser*>& timestamp_parsers,
float price_multiplier,
bool strip_id,
bool strip_meta) :
_is_trade(is_trade),
_base_date(base_date),
_timestamp_indices(timestamp_indices),
_price_idx(price_idx),
_qty_idx(qty_idx),
_id_field_indices(id_field_indices),
_meta_field_indices(meta_field_indices),
_timestamp_parsers(timestamp_parsers),
_price_multiplier(price_multiplier),
_strip_id(strip_id),
_strip_meta(strip_meta) {
if (timestamp_parsers.size() != timestamp_indices.size()) error("size of timestamp_parsers vector and timestamp_indices must match");
}
shared_ptr<Record> TextTradeParser::call(const vector<string>& fields) {
if (_is_trade && !_is_trade->call(fields)) return nullptr;
int64_t timestamp = _base_date;
int i = 0;
for (auto idx : _timestamp_indices) {
timestamp += _timestamp_parsers[i++]->call(fields[idx]);
}
float price = str_to_float(fields[_price_idx]) / _price_multiplier;
float qty = str_to_float(fields[_qty_idx]);
string id = join_fields(fields, _id_field_indices, '|', _strip_id);
string meta = join_fields(fields, _meta_field_indices, '|', _strip_meta);
return shared_ptr<Record>(new TradeRecord(id, timestamp, qty, price, meta));
}
TextOpenInterestParser::TextOpenInterestParser(CheckFields* is_open_interest,
int64_t base_date,
const vector<int>& timestamp_indices,
int qty_idx,
const vector<int>& id_field_indices,
const vector<int>& meta_field_indices,
const vector<TimestampParser*>& timestamp_parsers,
bool strip_id,
bool strip_meta) :
_is_open_interest(is_open_interest),
_base_date(base_date),
_timestamp_indices(timestamp_indices),
_qty_idx(qty_idx),
_id_field_indices(id_field_indices),
_meta_field_indices(meta_field_indices),
_timestamp_parsers(timestamp_parsers),
_strip_id(strip_id),
_strip_meta(strip_meta) {
if (timestamp_parsers.size() != timestamp_indices.size()) error("size of timestamp_parsers vector and timestamp_indices must match");
}
shared_ptr<Record> TextOpenInterestParser::call(const vector<string>& fields) {
if (_is_open_interest && !_is_open_interest->call(fields)) return nullptr;
int64_t timestamp = _base_date;
int i = 0;
for (auto idx : _timestamp_indices) {
timestamp += _timestamp_parsers[i++]->call(fields[idx]);
}
float qty = str_to_float(fields[_qty_idx]);
string id = join_fields(fields, _id_field_indices, '|', _strip_id);
string meta = join_fields(fields, _meta_field_indices, '|', _strip_meta);
return shared_ptr<Record>(new OpenInterestRecord(id, timestamp, qty, meta));
}
TextOtherParser::TextOtherParser(CheckFields* is_other,
int64_t base_date,
const vector<int>& timestamp_indices,
const vector<int>& id_field_indices,
const vector<int>& meta_field_indices,
const vector<TimestampParser*>& timestamp_parsers,
bool strip_id,
bool strip_meta) :
_is_other(is_other),
_base_date(base_date),
_timestamp_indices(timestamp_indices),
_id_field_indices(id_field_indices),
_meta_field_indices(meta_field_indices),
_timestamp_parsers(timestamp_parsers),
_strip_id(strip_id),
_strip_meta(strip_meta) {
if (timestamp_parsers.size() != timestamp_indices.size()) error("size of timestamp_parsers vector and timestamp_indices must match");
}
shared_ptr<Record> TextOtherParser::call(const vector<string>& fields) {
if (_is_other && !_is_other->call(fields)) return nullptr;
int64_t timestamp = _base_date;
int i = 0;
for (auto idx : _timestamp_indices) {
timestamp += _timestamp_parsers[i++]->call(fields[idx]);
}
string id = join_fields(fields, _id_field_indices, '|', _strip_id);
string meta = join_fields(fields, _meta_field_indices, '|', _strip_meta);
return shared_ptr<Record>(new OtherRecord(id, timestamp, meta));
}
TextRecordParser::TextRecordParser(std::vector<RecordFieldParser*> parsers, bool exclusive, char separator) :
_parsers(parsers),
_exclusive(exclusive),
_separator(separator),
_parse_index(0) {
if (parsers.empty()) error("at least one parser must be specified");
}
void TextRecordParser::add_line(const std::string& line) {
_fields = tokenize(line.c_str(), _separator);
_parse_index = 0;
}
shared_ptr<Record> TextRecordParser::parse() {
shared_ptr<Record> record;
for (;;) {
_parse_index++; // Make sure this gets incremented even if next line throws
if (_parse_index == (_parsers.size() + 1)) break;
record = _parsers[_parse_index - 1]->call(_fields);
if (record) {
//If exclusive don't try any parsers for the line after the first one that succeeds
if (_exclusive) _parse_index = static_cast<int>(_parsers.size());
return record;
}
}
return record;
}
int get_time_part(const std::string& time, int start, int size) {
if (start < 0 || size <= 0) {
return 0;
}
int ret = str_to_int(time.substr(start, size).c_str());
return ret;
}
struct DateTime { // hold date/time (interpreted as UTC), to be converted to time_point
int year;
int month;
int day;
int hour = 0;
int min = 0;
int sec = 0;
};
// convert date/time from UTC, to time_point
std::chrono::system_clock::time_point datetime_utc_to_timepoint(const DateTime &dt)
{
using namespace std::chrono;
using namespace date;
auto ymd = year(dt.year)/dt.month/dt.day; // year_month_day type
if (!ymd.ok()) error("Invalid date");
return sys_days(ymd);
}
FixedWidthTimeParser::FixedWidthTimeParser(
bool micros,
int years_start,
int years_size,
int months_start,
int months_size,
int days_start,
int days_size,
int hours_start,
int hours_size,
int minutes_start,
int minutes_size,
int seconds_start,
int seconds_size,
int millis_start,
int millis_size,
int micros_start,
int micros_size) :
_micros(micros),
_years_start(years_start),
_years_size(years_size),
_months_start(months_start),
_months_size(months_size),
_days_start(days_start),
_days_size(days_size),
_hours_start(hours_start),
_hours_size(hours_size),
_minutes_start(minutes_start),
_minutes_size(minutes_size),
_seconds_start(seconds_start),
_seconds_size(seconds_size),
_millis_start(millis_start),
_millis_size(millis_size),
_micros_start(micros_start),
_micros_size(micros_size)
{}
int64_t FixedWidthTimeParser::parse_date(const std::string& date) {
if (date.empty()) return 0;
auto it = _parsed_date_cache.find(date);
if (it != _parsed_date_cache.end()) return it->second;
int year = get_time_part(date, _years_start, _years_size);
if (_years_size == 2) year += 2000;
int month = get_time_part(date, _months_start, _months_size);
int day = get_time_part(date, _days_start, _days_size);
DateTime datetime;
datetime.year = year; datetime.month = month; datetime.day = day;
if (year == 0 || month == 0 || day == 0) return 0;
auto the_date = datetime_utc_to_timepoint(datetime);
auto ms = std::chrono::time_point_cast<std::chrono::milliseconds>(the_date);
auto ret = ms.time_since_epoch().count();
_parsed_date_cache.insert(make_pair(date, ret));
return ret;
}
int64_t FixedWidthTimeParser::parse_time(const std::string& time) {
if (time.empty()) return 0;
int hours = get_time_part(time, _hours_start, _hours_size);
int minutes = get_time_part(time, _minutes_start, _minutes_size);
int seconds = get_time_part(time, _seconds_start, _seconds_size);
int millis = get_time_part(time, _millis_start, _millis_size);
int micros = get_time_part(time, _micros_start, _micros_size);
return (static_cast<int64_t>(hours) * 60 * 60 + minutes * 60 + seconds) * 1000000 + millis * 1000 + micros;
}
int64_t FixedWidthTimeParser::call(const std::string& timestamp) {
int64_t date_micros = parse_date(timestamp) * 1000;
int64_t time_micros = parse_time(timestamp);
if (_micros) return static_cast<int64_t>(date_micros + time_micros);
return static_cast<int64_t>(round((date_micros + time_micros) / 1000.0));
}
void test_fixed_width_time_parser() {
FixedWidthTimeParser parser(false, 0, 4, 5, 2, 8, 2, 11, 2, 14, 2, 17, 2, 20, 3);
auto millisecs = parser.call("2018-01-01 00:00:01.238");
assert(millisecs == 1514764801238);
if (millisecs == 1) cout << "hello"; // Keep unused warnings away
auto millisecs_cached = parser.call("2018-01-01 00:00:02.238");
assert(millisecs_cached == 1514764802238);
if (millisecs_cached == 1) cout << "hello"; // Keep unused warnings away
FixedWidthTimeParser time_parser(false, -1, -1, -1, -1, -1, -1, 0, 2, 3, 2, 6, 2, 9, 3);
auto millisecs_2 = time_parser.call("08:33:22.123");
assert(millisecs_2 == 30802123);
if (millisecs_2 == 1) cout << "hello"; // Keep unused warnings away
FixedWidthTimeParser time_parser3(false, -1, -1, -1, -1, -1, -1, 0, 2, 3, 2);
auto millisecs_3 = time_parser3.call("18:00");
assert(millisecs_3 == 18 * 60 * 60 * 1000);
if (millisecs_3 == 1) cout << "hello"; // Keep unused warnings away
}
| 43.310705 | 138 | 0.606884 | vishalbelsare |
2c2e80972f9620a4a4cdcc2f888ae94e800545a3 | 1,530 | cpp | C++ | myoddtest/os/testipcdata_wstring.cpp | FFMG/myoddweb.piger | 6c5e9dff6ab8e2e02d6990c1959450f087acf371 | [
"MIT"
] | 18 | 2016-03-04T15:44:24.000Z | 2021-12-31T11:06:25.000Z | myoddtest/os/testipcdata_wstring.cpp | FFMG/myoddweb.piger | 6c5e9dff6ab8e2e02d6990c1959450f087acf371 | [
"MIT"
] | 49 | 2016-02-29T17:59:52.000Z | 2019-05-05T04:59:26.000Z | myoddtest/os/testipcdata_wstring.cpp | FFMG/myoddweb.piger | 6c5e9dff6ab8e2e02d6990c1959450f087acf371 | [
"MIT"
] | 2 | 2016-07-30T10:17:12.000Z | 2016-08-11T20:31:46.000Z | #include "os\ipcdata.h"
#include "..\testcommon.h"
#include <gtest/gtest.h>
const struct test_wstring
{
std::wstring uuid;
typedef std::vector<std::wstring> VALUE_TYPE;
VALUE_TYPE values;
};
struct MyoddOsWStringTest : testing::Test, testing::WithParamInterface<test_wstring>
{
myodd::os::IpcData* ipc;
MyoddOsWStringTest() : ipc(nullptr)
{
ipc = new myodd::os::IpcData(GetParam().uuid);
auto values = GetParam().values;
for (auto it = values.begin(); it != values.end(); ++it)
{
ipc->Add(*it);
}
}
~MyoddOsWStringTest()
{
delete ipc;
}
};
TEST_P(MyoddOsWStringTest, CheckWStringValues)
{
auto param = GetParam();
ASSERT_EQ(param.uuid, ipc->GetGuid());
auto values = GetParam().values;
unsigned int index = 0;
ASSERT_EQ(values.size(), ipc->GetNumArguments());
for (auto it = values.begin(); it != values.end(); ++it)
{
ASSERT_EQ(*it, ipc->Get<std::wstring>(index));
ASSERT_TRUE(ipc->IsString(index));
index++;
}
}
INSTANTIATE_TEST_CASE_P(Default_wstring, MyoddOsWStringTest,
testing::Values(
test_wstring{ Uuid(),{ L"" } },
test_wstring{ Uuid(),{ L"Hello world" } },
test_wstring{ Uuid(),{ L" " } },
test_wstring{ Uuid(),{ L" \n \t " } },
test_wstring{ Uuid(),{ L"\0" } }
));
INSTANTIATE_TEST_CASE_P(Multiple_stringValues, MyoddOsWStringTest,
testing::Values(
test_wstring{ Uuid(),{ L"", L" ", L"Hello", L"!@#$%^&*(" } },
test_wstring{ Uuid(),{ L"12345", L" ", L"Hello", L"!@#$%^&*(" } }
)); | 24.285714 | 84 | 0.615686 | FFMG |
2c2eca04b6faf0e89a4a5dfa93e683582976219f | 4,373 | hpp | C++ | modules/core/predicates/include/nt2/core/functions/common/isequaln.hpp | pbrunet/nt2 | 2aeca0f6a315725b335efd5d9dc95d72e10a7fb7 | [
"BSL-1.0"
] | 2 | 2016-09-14T00:23:53.000Z | 2018-01-14T12:51:18.000Z | modules/core/predicates/include/nt2/core/functions/common/isequaln.hpp | pbrunet/nt2 | 2aeca0f6a315725b335efd5d9dc95d72e10a7fb7 | [
"BSL-1.0"
] | null | null | null | modules/core/predicates/include/nt2/core/functions/common/isequaln.hpp | pbrunet/nt2 | 2aeca0f6a315725b335efd5d9dc95d72e10a7fb7 | [
"BSL-1.0"
] | null | null | null | //==============================================================================
// Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_CORE_FUNCTIONS_COMMON_ISEQUALN_HPP_INCLUDED
#define NT2_CORE_FUNCTIONS_COMMON_ISEQUALN_HPP_INCLUDED
#include <nt2/core/functions/isequaln.hpp>
#include <nt2/include/functions/numel.hpp>
#include <nt2/include/functions/havesamesize.hpp>
#include <nt2/include/functions/colvect.hpp>
#include <nt2/include/functions/all.hpp>
#include <nt2/include/functions/is_equal_with_equal_nans.hpp>
#include <nt2/include/functions/first_index.hpp>
namespace nt2 { namespace ext
{
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::isequaln_, tag::cpu_
, (A0)(A1)
, ((ast_<A0, nt2::container::domain>))
((ast_<A1, nt2::container::domain>))
)
{
typedef bool result_type;
BOOST_DISPATCH_FORCE_INLINE
result_type operator()(const A0& a0, const A1& a1) const
{
if (!havesamesize(a0, a1)) return false;
return nt2::all(colvect(is_equal_with_equal_nans(a0,a1)))(1);
}
};
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::isequaln_, tag::cpu_
, (A0)(A1)
, (scalar_<unspecified_<A0> >)
((ast_<A1, nt2::container::domain>))
)
{
typedef bool result_type;
BOOST_DISPATCH_FORCE_INLINE
result_type operator()(const A0& a0, const A1& a1) const
{
if(numel(a1)!= 1u) return false;
return is_equal_with_equal_nans(a0, A0(a1(nt2::first_index<1>(a1))));
}
};
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::isequaln_, tag::cpu_
, (A0)(A1)
, ((ast_<A0, nt2::container::domain>))
(scalar_<unspecified_<A1> >)
)
{
typedef bool result_type;
BOOST_DISPATCH_FORCE_INLINE
result_type operator()(const A0& a0, const A1& a1) const
{
if(numel(a0)!= 1u) return false;
return is_equal_with_equal_nans(A1(a0(nt2::first_index<1>(a0))), a1);
}
};
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::isequaln_, tag::cpu_
, (A0)
, (scalar_<unspecified_<A0> >)
(scalar_<unspecified_<A0> >)
)
{
typedef bool result_type;
BOOST_DISPATCH_FORCE_INLINE
result_type operator()(const A0& a0, const A0& a1) const
{
return is_equal_with_equal_nans(a0,a1);
}
};
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::isequaln_, tag::cpu_
, (A0)(A1)
, (unspecified_<A0>)
(unspecified_<A1>)
)
{
typedef bool result_type;
BOOST_DISPATCH_FORCE_INLINE
result_type operator()(const A0& a0, const A1& a1) const
{
return a0 == a1;
}
};
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::isequaln_, tag::cpu_
, (A0)(A1)(X)
, ((simd_< unspecified_<A0>, X>))
((simd_< unspecified_<A1>, X>))
)
{
typedef bool result_type;
BOOST_DISPATCH_FORCE_INLINE
result_type operator()(const A0& a0, const A1& a1) const
{
return nt2::all(is_equal_with_equal_nans(a0, a1));
}
};
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::isequaln_, tag::cpu_
, (A0)(A1)(X)(T0)(N0)(T1)(N1)
, ((expr_< simd_< unspecified_<A0>, X>, T0, N0>))
((expr_< simd_< unspecified_<A1>, X>, T1, N1>))
)
{
typedef bool result_type;
BOOST_DISPATCH_FORCE_INLINE
result_type operator()(const A0& a0, const A1& a1) const
{
return nt2::all(is_equal_with_equal_nans(a0, a1))();
}
};
} }
#endif
| 32.879699 | 80 | 0.520924 | pbrunet |
2c2f0b90f898c860a18f98181ff9042b8d79f81f | 9,794 | cpp | C++ | ic.cpp | Allabakshu-shaik/Mercedes-POC | b338c471870830ba4b4fb26e4dc1097e0882a8e2 | [
"MIT"
] | 46 | 2020-01-08T16:38:46.000Z | 2022-03-30T21:08:07.000Z | ic.cpp | Allabakshu-shaik/Mercedes-POC | b338c471870830ba4b4fb26e4dc1097e0882a8e2 | [
"MIT"
] | 2 | 2020-03-28T08:26:29.000Z | 2020-08-06T10:52:57.000Z | ic.cpp | Allabakshu-shaik/Mercedes-POC | b338c471870830ba4b4fb26e4dc1097e0882a8e2 | [
"MIT"
] | 9 | 2020-03-13T20:53:02.000Z | 2021-08-31T08:50:20.000Z | //
// Created by ashcon on 10/5/19.
//
#include "ic.h"
#include "debug.h"
//#define START_IN_DIAG_MODE
/**
* Sets the refresh rate for scrolling text. If text is static (8 chars),
* refresh rate is locked to every 2 seconds
*
* @param rate Desired rate to scroll across text
*/
void IC_DISPLAY::setRefreshRate(int rate) {
this->scrollRefreshRate = rate;
// If text is shorter than MAX_STR_LENGTH, then leave the refresh rate as static interval
if (currText.length() > MAX_STR_LENGTH) {
this->currentRefreshRate = this->scrollRefreshRate;
} else {
this->currentRefreshRate = this->staticRefreshRate;
}
}
/**
* Static value to hold the current page displayed on the IC display
*/
IC_DISPLAY::clusterPage IC_DISPLAY::currentPage = Audio;
IC_DISPLAY::IC_DISPLAY(CanbusComm *c) {
this->diagData = "DIAG MODE";
#ifdef START_IN_DIAG_MODE
this->inDiagMode = true;
#else
this->inDiagMode = false;
#endif
this->sendFirst = false;
this->c = c;
this->staticRefreshRate = 1000;
this->scrollRefreshRate = 150;
this->currText = " ";
this->setBodyText("BT = NA!", true);
this->lastTime = millis();
this->diag = new DIAG_DISPLAY(this->c);
this->diagScreen = 0;
}
/**
* Displays the 3 character header text on the IC page
* @param text Chars to display as the header
*/
void IC_DISPLAY::sendHeader(char header[]) {
String msg = resize(header, 4, 8);
curr_frame.can_id = IC_SEND_PID;
curr_frame.can_dlc = 0x08;
uint8_t checkSumBit = calculateBodyCheckSum(header);
uint8_t buffer[14] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
buffer[0] = msg.length() + 5;
buffer[1] = msg.length() - 1;
buffer[2] = 0x29;
buffer[3] = 0x00;
for (int i = 0; i < msg.length(); i++) {
buffer[i+4] = msg[i];
}
buffer[msg.length()+4] = 0x00;
buffer[msg.length()+5] = checkSumBit;
curr_frame.data[0] = 0x10;
for (int i = 1; i < 7; i++) {
curr_frame.data[i+1] = buffer[i];
}
c->sendFrame(CAN_BUS_B, &curr_frame);
delay(7);
curr_frame.data[0] = 0x21;
for (int i = 7; i < 14; i++) {
curr_frame.data[i-6] = buffer[i];
}
c->sendFrame(CAN_BUS_B, &curr_frame);
delay(7);
}
String IC_DISPLAY::resize(String s, int lb, int ub) {
String ret = "";
if (s.length() < lb) {
ret = s;
for (int i = 0; i < lb - s.length(); i++) {
ret += " ";
}
}
// If text is longer than MAX_STR_LENGTH chars, crop it to MAX_STR_LENGTH chars long
else if (s.length() > ub) {
for (int i = 0; i < ub; i++) {
ret += s[i];
}
} else {
ret = s;
}
return ret;
}
/**
* Sends body packets to the IC display to display a maximum of MAX_STR_LENGTH characters at a lastTime
* @param text Text to be displayed. If longer than 8 characters, it is cropped to be 8 characters long
*/
void IC_DISPLAY::sendBody(char text[]) {
curr_frame.can_id = IC_SEND_PID;
curr_frame.can_dlc = 0x08;
if (strlen(text) == 7) {
text += ' ';
}
char msg[] = resize(text, 5, MAX_STR_LENGTH);
// Stores the Sum of all ASCII Chars in text. Needed for validation packet
int asciiTotal = 0;
// Stores the number of bytes for actual data for the IC to process. Message length (ASCII) + Validation byte + null termination byte
uint8_t totalMsgLength = msg.length() + 2;
// Number of bytes to send across multiple packets to the IC
uint8_t numberOfBytes = 7 + totalMsgLength;
// Buffer to hold datawe will send to the IC across 2 packets
uint8_t bodyData[14] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
// Start of string
bodyData[0] = 0x10;
// fAdd in all the body text
for (int i = 0; i < msg.length(); i++) {
bodyData[i+1] = msg[i];
asciiTotal += msg[i];
}
// Add null termination to the bodydata
bodyData[msg.length()+1] = 0x00;
// Finally, add the validation byte to the bodyData
bodyData[msg.length() + 2] = calculateBodyCheckSum(msg);
// Pre-text packet for body text
curr_frame.data[0] = 0x10;
curr_frame.data[1] = numberOfBytes;
curr_frame.data[2] = 0x03;
curr_frame.data[3] = 0x26;
curr_frame.data[4] = 0x01;
curr_frame.data[5] = 0x00;
curr_frame.data[6] = 0x01;
curr_frame.data[7] = totalMsgLength;
c->sendFrame(CAN_BUS_B, &curr_frame);
delay(7); // Wait 5 MS for IC to process request (+2ms for time taken for the IC to receive packet)
curr_frame.data[0] = 0x21;
for (int i = 0; i < 7; i++) {
curr_frame.data[i+1] = bodyData[i];
}
c->sendFrame(CAN_BUS_B, &curr_frame);
delay(2);
curr_frame.data[0] = 0x22;
for (int i = 7; i < 14; i++) {
curr_frame.data[i-6] = bodyData[i];
}
c->sendFrame(CAN_BUS_B, &curr_frame);
delay(7);
}
/**
* calculates the header text validation byte
*/
uint8_t IC_DISPLAY::calculateHeaderCheckSum(const char *text) {
int sum = 0;
for (int i = 0; i < 3; i++) {
sum += int(text[i]);
}
return 407 - (sum);
}
/**
* Calculates the body text validation byte
*/
uint8_t IC_DISPLAY::calculateBodyCheckSum(const char text[]){
uint8_t charCount = strlen(text);
// Lookup table valid checksum + ASCII Total values
uint16_t NINE_CHAR_TOTAL_LOOKUP[] = {1073, 817, 561, 561};
uint16_t EIGHT_CHAR_TOTAL_LOOKUP[] = {1090, 834, 578, 322};
uint16_t SEVEN_CHAR_TOTAL_LOOKUP[] = {1136, 880, 624, 368};
uint16_t SIX_CHAR_TOTAL_LOOKUP[] = {1121, 865, 609, 353};
uint16_t FIVE_CHAR_TOTAL_LOOKUP[] = {1135, 879, 623, 367};
uint16_t FOUR_CHAR_TOTAL_LOOKUP[] = {439, 439, 439, 439};
int strTotal = 0;
for(int i = 0; i < charCount; i++) {
strTotal += text[i];
}
if(charCount == 9) {
for(uint16_t k : NINE_CHAR_TOTAL_LOOKUP) {
if(k - strTotal <= 256) {
DPRINTLN("K: "+String(k)+" SUM: "+String(strTotal)+" Num Chars: 9");
return (k-strTotal);
}
}
}else if(charCount == 8) {
for(uint16_t k : EIGHT_CHAR_TOTAL_LOOKUP) {
if(k - strTotal <= 256) {
DPRINTLN("K: "+String(k)+" SUM: "+String(strTotal)+" Num Chars: 8");
return (k-strTotal);
}
}
} else if (charCount == 7) {
for(uint16_t k : SEVEN_CHAR_TOTAL_LOOKUP) {
if(k - strTotal <= 256) {
DPRINTLN("K: "+String(k)+" SUM: "+String(strTotal)+" Num Chars: 7");
return (k-strTotal);
}
}
} else if (charCount == 6) {
for(uint16_t k : SIX_CHAR_TOTAL_LOOKUP) {
if(k - strTotal <= 256) {
DPRINTLN("K: "+String(k)+" SUM: "+String(strTotal)+" Num Chars: 6");
return (k-strTotal);
}
}
} else if (charCount == 5) {
for(uint16_t k : FIVE_CHAR_TOTAL_LOOKUP) {
if(k - strTotal <= 256) {
DPRINTLN("K: "+String(k)+" SUM: "+String(strTotal)+" Num Chars: 5");
return (k-strTotal);
}
}
} else if (charCount == 4) {
for(uint16_t k : FOUR_CHAR_TOTAL_LOOKUP) {
if(k - strTotal <= 256) {
DPRINTLN("K: "+String(k)+" SUM: "+String(strTotal)+" Num Chars: 4");
return (k-strTotal);
}
}
}
return 0;
}
/**
* Method to update the contents of the IC based on data within the class
*/
void IC_DISPLAY::update() {
if (!inDiagMode) {
if (millis() - lastTime > currentRefreshRate) {
lastTime = millis();
if(currentPage == clusterPage::Audio) {
sendBody(currText.c_str());
if(this->currText.length() > MAX_STR_LENGTH) {
this->currText = shiftString();
}
} else if (!sendFirst) {
sendBody(currText);
this->sendFirst = true;
}
}
} else {
switch (this->diagScreen)
{
case 0:
diagData = "DIAG MODE";
break;
case 1:
diagData = diag->getSpeed();
break;
case 2:
diagData = diag->getRPM();
break;
case 3:
diagData = diag->getCoolantTemp();
break;
default:
break;
}
if (millis() - lastTime > DIAG_REFRESH_RATE) {
lastTime = millis();
sendBody(diagData);
}
}
}
String IC_DISPLAY::getText() {
return this->currText;
}
/**
* Sets body text for the IC
*/
void IC_DISPLAY::setBodyText(String text, bool addSpace) {
this->currText = text;
if (text.length() > MAX_STR_LENGTH) {
if (addSpace) {
this->currText += " ";
}
this->currentRefreshRate = scrollRefreshRate;
} else {
this->sendBody(currText);
this->currentRefreshRate = staticRefreshRate;
}
this->sendFirst = false;
}
/**
* Shifts string by 1 to the left
*/
String IC_DISPLAY::shiftString() {
char x = currText[0];
String tmp;
for (int i = 1; i < currText.length(); i++) {
tmp += currText[i];
}
tmp += x;
return tmp;
}
void IC_DISPLAY::nextDiagScreen() {
if (diagScreen < diag->screens) {
diagScreen++;
} else if (diagScreen == diag->screens) {
diagScreen = 0;
}
}
void IC_DISPLAY::prevDiagScreen() {
if (diagScreen > 0) {
diagScreen--;
} else if (diagScreen == 0) {
diagScreen = diag->screens;
}
}
| 29.768997 | 137 | 0.559016 | Allabakshu-shaik |
2c3292a1a81828ee830fbe28e5dbc0185a32cead | 5,857 | cxx | C++ | Graphics/Testing/Cxx/TestQuadraturePointStatistics.cxx | garyc618/GitTagBug | 0b1cdbf5a6f6b9b23fa03ff1d9f4a84953831864 | [
"BSD-3-Clause"
] | 1 | 2019-05-31T06:45:40.000Z | 2019-05-31T06:45:40.000Z | Graphics/Testing/Cxx/TestQuadraturePointStatistics.cxx | garyc618/GitTagBug | 0b1cdbf5a6f6b9b23fa03ff1d9f4a84953831864 | [
"BSD-3-Clause"
] | null | null | null | Graphics/Testing/Cxx/TestQuadraturePointStatistics.cxx | garyc618/GitTagBug | 0b1cdbf5a6f6b9b23fa03ff1d9f4a84953831864 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Visualization Toolkit
Module: TestQuadraturePointStatistics.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// This example demonstrates the capabilities of vtkQuadraturePointInterpolator
// vtkQuadraturePointsGenerator and the class required to suppport their
// addition.
//
// The command line arguments are:
// -I => run in interactive mode; unless this is used, the program will
// not allow interaction and exit
// -D <path> => path to the data; the data should be in <path>/Data/
#include "vtkTesting.h"
#include "vtkUnstructuredGrid.h"
#include "vtkTable.h"
#include "vtkXMLUnstructuredGridReader.h"
#include "vtkUnstructuredGridReader.h"
#include "vtkPointData.h"
#include "vtkQuadratureSchemeDictionaryGenerator.h"
#include "vtkQuadraturePointInterpolator.h"
#include "vtkQuadraturePointStatistics.h"
#include "vtkDoubleArray.h"
#include "vtkDataObject.h"
#include "vtkstd/string"
using vtkstd::string;
// Compare doubles.
bool Equal(double l, double r);
// Test a column of the table.
int TestColumn(double *column, double *expected, char *name);
int TestQuadraturePointStatistics(int argc,char *argv[])
{
vtkTesting *testHelper=vtkTesting::New();
testHelper->AddArguments(argc,const_cast<const char **>(argv));
if (!testHelper->IsFlagSpecified("-D"))
{
cerr << "Error: -D /path/to/data was not specified.";
return 1;
}
string dataRoot=testHelper->GetDataRoot();
string tempDir=testHelper->GetTempDirectory();
string inputFileName=dataRoot+"/Data/Quadratic/CylinderQuadratic.vtk";
testHelper->Delete();
// Raed, xml or legacy file.
vtkUnstructuredGrid *input=0;
vtkXMLUnstructuredGridReader *xusgr=vtkXMLUnstructuredGridReader::New();
xusgr->SetFileName(inputFileName.c_str());
vtkUnstructuredGridReader *lusgr=vtkUnstructuredGridReader::New();
lusgr->SetFileName(inputFileName.c_str());
if (xusgr->CanReadFile(inputFileName.c_str()))
{
input=xusgr->GetOutput();
input->Update();
input->Register(0);
}
else if (lusgr->IsFileValid("unstructured_grid"))
{
lusgr->SetFileName(inputFileName.c_str());
input=lusgr->GetOutput();
input->Update();
input->Register(0);
}
xusgr->Delete();
lusgr->Delete();
if (input==0)
{
cerr << "Error: Could not read file " << inputFileName << "." << endl;
return 1;
}
// Add a quadrature scheme dictionary to the data set. This filter is
// solely for our convinience. Typically we would expect that users
// provide there own in XML format and use the readers or to generate
// them on the fly.
vtkQuadratureSchemeDictionaryGenerator *dictGen=vtkQuadratureSchemeDictionaryGenerator::New();
dictGen->SetInput(input);
input->Delete();
// Interpolate fields to the quadrature points. This generates new field data
// arrays, but not a set of points.
vtkQuadraturePointInterpolator *fieldInterp=vtkQuadraturePointInterpolator::New();
fieldInterp->SetInput(dictGen->GetOutput());
dictGen->Delete();
// Connect the statistics filter.
vtkQuadraturePointStatistics *stats=vtkQuadraturePointStatistics::New();
stats->SetInput(fieldInterp->GetOutput());
fieldInterp->Delete();
stats->Update();
// Get the columns of table of statistics produced.
vtkTable *results=stats->GetOutput();
vtkDoubleArray *ss=vtkDoubleArray::SafeDownCast(results->GetColumn(1));
vtkDoubleArray *vsm=vtkDoubleArray::SafeDownCast(results->GetColumn(2));
vtkDoubleArray *vs0=vtkDoubleArray::SafeDownCast(results->GetColumn(3));
vtkDoubleArray *vs1=vtkDoubleArray::SafeDownCast(results->GetColumn(4));
vtkDoubleArray *vs2=vtkDoubleArray::SafeDownCast(results->GetColumn(5));
// Expected results.
double expected[5][3]={
{ 3.059852414448038e-02, 9.956630332424743e-01, 4.029730492116645e-01},
{-2.269918310038044e-01, 2.024122131787856e-01, -4.004585517533307e-04},
{-2.021326110317450e-01, 2.234015215692812e-01, 4.329055382852992e-05},
{-9.956377843500491e-01, -3.021884798540561e-02, -4.023756660384976e-01},
{-4.848191252082387e+01, 5.931853206950250e+03, 2.031073976434023e+03}};
int passFlag=0x1;
// Test and display.
passFlag&=TestColumn(ss->GetPointer(0) ,expected[0],ss->GetName() );
passFlag&=TestColumn(vsm->GetPointer(0),expected[1],vsm->GetName());
passFlag&=TestColumn(vs0->GetPointer(0),expected[2],vs0->GetName());
passFlag&=TestColumn(vs1->GetPointer(0),expected[3],vs1->GetName());
passFlag&=TestColumn(vs2->GetPointer(0),expected[4],vs2->GetName());
stats->Delete();
return !passFlag;
}
//-----------------------------------------------------------------------------
int TestColumn(double *column, double *expected, char *name)
{
if (!Equal(column[0],expected[0])
|| !Equal(column[1],expected[1])
|| !Equal(column[2],expected[2]))
{
cerr << "Test of column " << name << " failed." << endl;
cerr.precision(15);
cerr.setf(ios::scientific,ios::floatfield);
cerr << column[0] << " == " << expected[0] << endl;
cerr << column[1] << " == " << expected[1] << endl;
cerr << column[2] << " == " << expected[2] << endl;
return 0;
}
return 1;
}
//-----------------------------------------------------------------------------
bool Equal(double l, double r)
{
double d=fabs(fabs(l)-fabs(r))/fabs(l<r?r:l);
if (d<1E-13) return true;
return false;
}
| 37.787097 | 96 | 0.673041 | garyc618 |
2c37db840a6a20342a022d28eca3c2eb3d8cfe27 | 247 | hpp | C++ | intrusive/pair_fwd.hpp | awonnacott/data-structures | 90bfa3994812b433a69ee0996952fcb874ca9184 | [
"MIT"
] | 1 | 2021-04-27T19:12:27.000Z | 2021-04-27T19:12:27.000Z | intrusive/pair_fwd.hpp | awonnacott/data-structures | 90bfa3994812b433a69ee0996952fcb874ca9184 | [
"MIT"
] | null | null | null | intrusive/pair_fwd.hpp | awonnacott/data-structures | 90bfa3994812b433a69ee0996952fcb874ca9184 | [
"MIT"
] | null | null | null | #pragma once
#include <utility> // pair
namespace intrusive {
template <typename A, typename B> class pair;
template <typename A, typename B>
constexpr std::pair<pair<A, B>, pair<B, A>> make_pair(const A&, const B&);
} // namespace intrusive
| 19 | 74 | 0.704453 | awonnacott |
2c38e4eaf551b31c7d1e6cbc759347ccdd2d0126 | 3,042 | cpp | C++ | src/search_engine/relja_retrival/v2/retrieval/wgc.cpp | kaloyan13/vise2 | 833a8510c7cbac3cbb8ac4569fd51448906e62f3 | [
"BSD-2-Clause"
] | 43 | 2017-07-06T23:44:39.000Z | 2022-03-25T06:53:29.000Z | src/search_engine/relja_retrival/v2/retrieval/wgc.cpp | kaloyan13/vise2 | 833a8510c7cbac3cbb8ac4569fd51448906e62f3 | [
"BSD-2-Clause"
] | 2 | 2018-11-09T03:52:14.000Z | 2020-03-25T14:08:33.000Z | src/search_engine/relja_retrival/v2/retrieval/wgc.cpp | kaloyan13/vise2 | 833a8510c7cbac3cbb8ac4569fd51448906e62f3 | [
"BSD-2-Clause"
] | 9 | 2017-07-27T10:55:55.000Z | 2020-12-15T13:42:43.000Z | /*
==== Author:
Relja Arandjelovic (relja@robots.ox.ac.uk)
Visual Geometry Group,
Department of Engineering Science
University of Oxford
==== Copyright:
The library belongs to Relja Arandjelovic and the University of Oxford.
No usage or redistribution is allowed without explicit permission.
*/
#include "wgc.h"
#include <fstream>
#include <boost/filesystem.hpp>
#include "tfidf_v2.h"
#include "tfidf_data.pb.h"
#include "timing.h"
#include "weighter_v2.h"
wgc::wgc( protoIndex const &iidx, protoIndex const *fidx, std::string wgcFn ) : retrieverFromIter(&iidx, fidx, false, true), iidx_(&iidx) {
if ( wgcFn.length()>0 && boost::filesystem::exists( wgcFn ) ){
tfidfV2::load(wgcFn, idf_, docL2_);
numDocs_= docL2_.size();
} else {
tfidfV2::computeIdf(*iidx_, idf_, fidx_);
computeDocL2();
numDocs_= docL2_.size();
if (wgcFn.length()>0)
tfidfV2::save(wgcFn, idf_, docL2_);
}
}
void
wgc::queryExecute( rr::indexEntry &queryRep, ueIterator *ueIter, std::vector<indScorePair> &queryRes, uint32_t toReturn ) const {
std::vector<double> scores;
queryExecute(queryRep, ueIter, scores);
retriever::sortResults( scores, queryRes, toReturn );
}
void
wgc::queryExecute( rr::indexEntry &queryRep, ueIterator *ueIter, std::vector<double> &scores ) const {
// weight query BoW with idf
tfidfV2::weightStatic(queryRep, NULL, &idf_);
// query
weighterV2::queryExecuteWGC(queryRep, ueIter, idf_, docL2_, scores, 128);
}
void
wgc::computeDocL2() {
uint32_t numWords= iidx_->numIDs();
ASSERT(fidx_!=NULL); // if needed, this could be replaced by computing numDocs as max(all ids)
uint32_t numDocs= fidx_->numIDs();
docL2_.clear();
docL2_.resize( numDocs, 0.0 );
std::vector<rr::indexEntry> entries;
uint32_t numWords_printStep= std::max(static_cast<uint32_t>(1),numWords/20);
std::cout<<"wgc::computeDocL2\n";
double time= timing::tic();
for (uint32_t wordID= 0; wordID < numWords; ++wordID){
if (wordID % numWords_printStep == 0)
std::cout<<"wgc::computeDocL2: wordID= "<<wordID<<" / "<<numWords<<" "<<timing::toc(time)<<" ms\n";
iidx_->getEntries( wordID, entries );
for (uint32_t iEntry= 0; iEntry<entries.size(); ++iEntry){
rr::indexEntry &entry= entries[iEntry];
// set/add weights and multiply by idf
tfidfV2::weightStatic(entry, &idf_[wordID], NULL);
for (int i= 0; i<entry.id_size(); ++i)
docL2_[ entry.id(i) ]+= entry.weight(i) * entry.weight(i);
}
}
for (uint32_t docID= 0; docID < numDocs; ++docID){
if ( docL2_[docID] <= 1e-7 )
docL2_[docID]= 1.0;
else
docL2_[docID]= sqrt( docL2_[docID] );
}
std::cout<<"wgc::computeDocL2: DONE ("<<timing::toc(time)<<" ms)\n";
}
| 26.224138 | 139 | 0.602564 | kaloyan13 |
2c3973599e108bbf66163a086cef4667593a6296 | 287 | hpp | C++ | src/Gui/single/Layouts/HBoxLayout.hpp | classix-ps/sfml-widgets | 0556f9d95ee2c5a5bc34e2182cf7f16290c102cf | [
"MIT"
] | null | null | null | src/Gui/single/Layouts/HBoxLayout.hpp | classix-ps/sfml-widgets | 0556f9d95ee2c5a5bc34e2182cf7f16290c102cf | [
"MIT"
] | null | null | null | src/Gui/single/Layouts/HBoxLayout.hpp | classix-ps/sfml-widgets | 0556f9d95ee2c5a5bc34e2182cf7f16290c102cf | [
"MIT"
] | null | null | null | #ifndef GUI_HBOXLAYOUT_SINGLE_HPP
#define GUI_HBOXLAYOUT_SINGLE_HPP
#include "Layout.hpp"
namespace guiSingle
{
/**
* Horizontally stacked layout
*/
class HBoxLayout: public Layout
{
public:
private:
void recomputeGeometry() override;
};
}
#endif // GUI_HBOXLAYOUT_SINGLE_HPP
| 13.045455 | 38 | 0.766551 | classix-ps |
2c3b7a67403f2106a4bc907fc69d6e00b801dc06 | 1,542 | cpp | C++ | UVa Online Judge/v119/11926.cpp | mjenrungrot/algorithm | e0e8174eb133ba20931c2c7f5c67732e4cb2b703 | [
"MIT"
] | 1 | 2021-12-08T08:58:43.000Z | 2021-12-08T08:58:43.000Z | UVa Online Judge/v119/11926.cpp | mjenrungrot/algorithm | e0e8174eb133ba20931c2c7f5c67732e4cb2b703 | [
"MIT"
] | null | null | null | UVa Online Judge/v119/11926.cpp | mjenrungrot/algorithm | e0e8174eb133ba20931c2c7f5c67732e4cb2b703 | [
"MIT"
] | null | null | null | /*=============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 11926.cpp
# Description: UVa Online Judge - 11926
=============================================================================*/
#include <cstdio>
#include <cstring>
using namespace std;
bool B[1000005];
int main() {
// freopen("in","r",stdin);
int N, M;
while (scanf("%d %d", &N, &M) == 2) {
if (N == 0 and M == 0) break;
bool possible = true;
memset(B, 0, sizeof B);
for (int i = 1; i <= N; i++) {
int aa, bb;
scanf("%d %d", &aa, &bb);
for (int j = aa; j < bb and possible; j++) {
if (B[j] == true) {
possible = false;
break;
}
B[j] = true;
}
}
for (int i = 1; i <= M; i++) {
int aa, bb, cc;
scanf("%d %d %d", &aa, &bb, &cc);
for (int j = aa; j <= 1000000 and possible; j += cc) {
for (int k = j; k < j + bb - aa and k <= 1000000 and possible;
k++) {
if (B[k] == true) {
possible = false;
break;
}
B[k] = true;
}
}
}
if (possible)
printf("NO CONFLICT\n");
else
printf("CONFLICT\n");
}
return 0;
} | 30.235294 | 79 | 0.330739 | mjenrungrot |
2c3d51d5ad9f12e395c8d87e4a8bda13cc46f228 | 1,820 | cc | C++ | function_ref/snippets/snippet-member-function-without-type-erasure-usage.cc | descender76/cpp_proposals | 2eb7e2f59257b376dadd1b66464e076c3de23ab1 | [
"BSL-1.0"
] | 1 | 2022-01-21T20:10:46.000Z | 2022-01-21T20:10:46.000Z | function_ref/snippets/snippet-member-function-without-type-erasure-usage.cc | descender76/cpp_proposals | 2eb7e2f59257b376dadd1b66464e076c3de23ab1 | [
"BSL-1.0"
] | null | null | null | function_ref/snippets/snippet-member-function-without-type-erasure-usage.cc | descender76/cpp_proposals | 2eb7e2f59257b376dadd1b66464e076c3de23ab1 | [
"BSL-1.0"
] | null | null | null | struct delegateTest
{
int state = 0;
long current(int i, long l, char c) const
{
return state + i + l;
}
long test(int i, long l, char c)
{
state += i;
return state + l;
}
};
int main()
{
delegateTest dt;
function_ref_prime<long(delegateTest*, int, long, char)> frp = this_as_pointer<&delegateTest::test>::make_function_ref();
std::cout << frp(&dt, 7800, 91, 'l') << std::endl;// 7891
frp = this_as_pointer<&delegateTest::current>::make_function_ref();
std::cout << frp(&dt, 7800, 91, 'l') << std::endl;// 15691
function_ref_prime<long(delegateTest&, int, long, char)> frp1 = this_as_ref<&delegateTest::test>::make_function_ref();
std::cout << frp1(dt, 7800, 91, 'l') << std::endl;// 15691
frp1 = this_as_ref<&delegateTest::current>::make_function_ref();
std::cout << frp1(dt, 7800, 91, 'l') << std::endl;// 23491
function_ref_prime<long(delegateTest, int, long, char)> frp2 = this_as_value<&delegateTest::test>::make_function_ref();
std::cout << frp2(dt, 7800, 91, 'l') << std::endl;// 23491
frp2 = this_as_value<&delegateTest::current>::make_function_ref();
std::cout << frp2(dt, 7800, 91, 'l') << std::endl;// 23491
function_ref_prime<long(const delegateTest*, int, long, char)> frp3 = this_as_cpointer<&delegateTest::current>::make_function_ref();
std::cout << frp3(&dt, 7800, 91, 'l') << std::endl;// 23491
function_ref_prime<long(const delegateTest&, int, long, char)> frp4 = this_as_cref<&delegateTest::current>::make_function_ref();
std::cout << frp4(dt, 7800, 91, 'l') << std::endl;// 23491
function_ref_prime<long(const delegateTest, int, long, char)> frp5 = this_as_cvalue<&delegateTest::current>::make_function_ref();
std::cout << frp5(dt, 7800, 91, 'l') << std::endl;// 23491
}
| 49.189189 | 136 | 0.642857 | descender76 |
2c4111c6c34aecbcce335b8f9828ecbf4959b04e | 1,943 | cpp | C++ | Laburi/Lab12/p1/State.cpp | teodutu/PA | 9abaf9f0ebbce8beac274edd672473a17575fe03 | [
"MIT"
] | 7 | 2019-02-12T15:14:12.000Z | 2020-05-05T13:48:52.000Z | Laburi/Lab12/p1/State.cpp | teodutu/PA | 9abaf9f0ebbce8beac274edd672473a17575fe03 | [
"MIT"
] | null | null | null | Laburi/Lab12/p1/State.cpp | teodutu/PA | 9abaf9f0ebbce8beac274edd672473a17575fe03 | [
"MIT"
] | 7 | 2020-03-22T09:46:19.000Z | 2021-03-11T20:53:19.000Z | #include "State.h"
#include <cmath>
bool State::has_same_state(const State& other) {
return x == other.x && y == other.y;
}
int State::approx_distance(const State other) {
int approx_distance = 0;
/*TODO: functie admisibila care sa estimeze costul pana la starea finala*/
approx_distance = ABS(x - other.x) + ABS(y - other.y);
return approx_distance;
}
State* State::create_State(int next_i, int next_j) {
State* next = new State(*this);
next->set_parent(this);
next->x = next_i;
next->y = next_j;
next->set_distance(distance() + 1);
return next;
}
void State::expand(std::vector<State*>& expanded) {
const int i = x;
const int j = y;
/* Exista maxim 4 vecini posibili: */
/* 1. Patratelul de deasupra spatiului alb este interschimbat. */
if (i > 0 && matrix[i-1][j]) {
expanded.push_back(create_State(i - 1, j));
}
/* 2. Patratelul de dedesubtul spatiului alb este interschimbat. */
if (i < M - 1 && matrix[i+1][j]) {
expanded.push_back(create_State(i + 1, j));
}
/* 3. Patratelul de la stanga spatiului alb este interschimbat. */
if (j > 0 && matrix[i][j-1]) {
expanded.push_back(create_State(i, j - 1));
}
/* 4. Patratelul de la dreapta spatiului alb este interschimbat. */
if (j < N - 1 && matrix[i][j+1]) {
expanded.push_back(create_State(i, j + 1));
}
}
void State::print_path() {
int moves = State::print_partial_path(this);
std::cout << moves << " mutari" << std::endl;
}
int State::print_partial_path(State* state) {
if (state == NULL) {
return 0;
}
const int moves = print_partial_path(state->parent());
std::cout << *state << std::endl;
return moves + 1;
}
/* I/O operators. */
std::ostream& operator<< (std::ostream& out, const State& state) {
std::cout << state.x << " " << state.y;
std::cout << std::endl;
return out;
}
std::istream& operator>> (std::istream& in, State& state) {
in >> state.x >> state.y;
return in;
}
| 24.910256 | 75 | 0.630983 | teodutu |
2c42b90f863c17c776d7db965a8e80f3db6cb20e | 4,972 | hpp | C++ | txml/applications/json/include/SchemaSerializer.hpp | SergeyIvanov87/templatedXML | 2873fff802979113de102cd6ff5c2184720ee107 | [
"MIT"
] | 4 | 2020-09-30T10:41:44.000Z | 2022-03-14T19:12:26.000Z | txml/applications/json/include/SchemaSerializer.hpp | SergeyIvanov87/templatedXML | 2873fff802979113de102cd6ff5c2184720ee107 | [
"MIT"
] | 3 | 2021-11-03T18:46:24.000Z | 2021-11-03T18:47:09.000Z | txml/applications/json/include/SchemaSerializer.hpp | SergeyIvanov87/templatedXML | 2873fff802979113de102cd6ff5c2184720ee107 | [
"MIT"
] | null | null | null | #ifndef TXML_APPLICATION_JSON_SCHEMA_SERIALIZER_HPP
#define TXML_APPLICATION_JSON_SCHEMA_SERIALIZER_HPP
#include <txml/include/engine/SchemaSerializerBase.hpp>
#include <txml/applications/json/include/fwd/SchemaSerializer.h>
#include <txml/applications/json/include/SerializerCore.hpp>
#include <txml/applications/json/include/utils.hpp>
namespace json
{
#define TEMPL_ARGS_DECL class Impl, class ...SerializedItems
#define TEMPL_ARGS_DEF Impl, SerializedItems...
template<TEMPL_ARGS_DECL>
SchemaToJSON<TEMPL_ARGS_DEF>::SchemaToJSON(std::shared_ptr<std::stack<json>> shared_object_stack) :
SerializerCore(shared_object_stack)
{
}
template<TEMPL_ARGS_DECL>
SchemaToJSON<TEMPL_ARGS_DEF>::~SchemaToJSON() = default;
template<TEMPL_ARGS_DECL>
template<class SerializedItem, class Tracer>
void SchemaToJSON<TEMPL_ARGS_DEF>::serialize_schema_impl(txml::details::SchemaTag<SerializedItem>, Tracer tracer)
{
static_cast<Impl*>(this)->template serialize_schema_tag_impl<SerializedItem>(typename SerializedItem::tags_t {}, tracer);
}
template<TEMPL_ARGS_DECL>
template<class SerializedItem, class Tracer>
void SchemaToJSON<TEMPL_ARGS_DEF>::serialize_schema_tag_impl(const txml::ArrayTag&, Tracer &tracer)
{
//TODO
json cur_json_element = json::array();
auto mediator = get_shared_mediator_object();
size_t stack_size_before = mediator->size();
tracer.trace(__FUNCTION__, " - begin 'ArrayTag': ", SerializedItem::class_name(),
", stack size: ", stack_size_before);
SerializedItem::schema_serialize_elements(* static_cast<Impl*>(this), tracer);
size_t stack_size_after = mediator->size();
tracer.trace(__FUNCTION__, " - end 'ArrayTag': ", SerializedItem::class_name(),
", stack size: ", stack_size_after);
for (size_t i = stack_size_before; i < stack_size_after; i++)
{
json &serialized_element = mediator->top();
cur_json_element.insert(cur_json_element.end(), std::move(serialized_element));
mediator->pop();
}
mediator->push({{SerializedItem::class_name(), std::move(cur_json_element)}});
tracer.trace(__FUNCTION__, " - 'ArrayTag' merged: ", SerializedItem::class_name(),
", from elements count: ", stack_size_after - stack_size_before);
}
template<TEMPL_ARGS_DECL>
template<class SerializedItem, class Tracer>
void SchemaToJSON<TEMPL_ARGS_DEF>::serialize_schema_tag_impl(const txml::ContainerTag&, Tracer &tracer)
{
json cur_json_element = json::object({});
auto mediator = get_shared_mediator_object();
size_t stack_size_before = mediator->size();
tracer.trace(__FUNCTION__, " - begin 'ContainerTag': ", SerializedItem::class_name(),
", stack size: ", stack_size_before);
SerializedItem::schema_serialize_elements(* static_cast<Impl*>(this), tracer);
size_t stack_size_after = mediator->size();
tracer.trace(__FUNCTION__, " - end 'ContainerTag': ", SerializedItem::class_name(),
", stack size: ", stack_size_after);
for (size_t i = stack_size_before; i < stack_size_after; i++)
{
json &serialized_element = mediator->top();
if (serialized_element.type() == nlohmann::json::value_t::array)
{
tracer.trace(__FUNCTION__, " - ", SerializedItem::class_name(), "::emplace array");
cur_json_element.emplace(SerializedItem::class_name(), std::move(serialized_element));
}
else
{
auto f = serialized_element.begin();
auto l = serialized_element.end();
tracer.trace(__FUNCTION__, " - insert objects count: ", std::distance(f, l));
cur_json_element.insert(f, l);
}
mediator->pop();
}
mediator->push({{SerializedItem::class_name(), std::move(cur_json_element)}});
tracer.trace(__FUNCTION__, " - 'ContainerTag' merged: ", SerializedItem::class_name(),
", from elements count: ", stack_size_after - stack_size_before);
}
template<TEMPL_ARGS_DECL>
template<class SerializedItem, class Tracer>
void SchemaToJSON<TEMPL_ARGS_DEF>::serialize_schema_tag_impl(const txml::LeafTag&, Tracer &tracer)
{
auto mediator = get_shared_mediator_object();
tracer.trace(__FUNCTION__, " - begin 'LeafTag': ", SerializedItem::class_name(),
", stack size: ", mediator->size());
json element({{SerializedItem::class_name(),
utils::json_type_to_cstring(utils::type_to_json_type<typename SerializedItem::value_t>()) }});
tracer.trace("'", SerializedItem::class_name(), "' created, value: ", element.dump());
mediator->push(std::move(element));
tracer.trace(__FUNCTION__, " - end 'LeafTag': ", SerializedItem::class_name(),
", stack size: ", mediator->size());
}
} // namespace json
#endif // TXML_APPLICATION_JSON_SCHEMA_SERIALIZER_HPP
| 43.234783 | 125 | 0.684232 | SergeyIvanov87 |
2c46911871cb067b5962b902321a3cb14d06d461 | 6,165 | cpp | C++ | platform/wii/dir_access_wii.cpp | xchellx/godot | d7beb5790eb9a01e6acdd7fd4838df3d2a303619 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | platform/wii/dir_access_wii.cpp | xchellx/godot | d7beb5790eb9a01e6acdd7fd4838df3d2a303619 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | platform/wii/dir_access_wii.cpp | xchellx/godot | d7beb5790eb9a01e6acdd7fd4838df3d2a303619 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | #include "dir_access_wii.h"
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
Error DirAccessWii::list_dir_begin()
{
list_dir_end(); //close any previous dir opening!
//char real_current_dir_name[2048]; //is this enough?!
//getcwd(real_current_dir_name,2048);
//chdir(current_path.utf8().get_data());
dir_stream = opendir(current_dir.utf8().get_data());
//chdir(real_current_dir_name);
if (!dir_stream)
return ERR_CANT_OPEN; //error!
return OK;
}
bool DirAccessWii::file_exists(String p_file) {
GLOBAL_LOCK_FUNCTION
if (p_file.is_rel_path())
p_file = current_dir.plus_file(p_file);
p_file = fix_path(p_file);
struct stat flags;
bool success = (stat(p_file.utf8().get_data(), &flags) == 0);
if (success && S_ISDIR(flags.st_mode)) {
success = false;
}
return success;
}
bool DirAccessWii::dir_exists(String p_dir) {
GLOBAL_LOCK_FUNCTION
if (p_dir.is_rel_path())
p_dir = get_current_dir().plus_file(p_dir);
p_dir = fix_path(p_dir);
struct stat flags;
bool success = (stat(p_dir.utf8().get_data(), &flags) == 0);
return (success && S_ISDIR(flags.st_mode));
}
uint64_t DirAccessWii::get_modified_time(String p_file) {
if (p_file.is_rel_path())
p_file = current_dir.plus_file(p_file);
p_file = fix_path(p_file);
struct stat flags;
bool success = (stat(p_file.utf8().get_data(), &flags) == 0);
if (success) {
return flags.st_mtime;
} else {
ERR_FAIL_V(0);
};
return 0;
};
String DirAccessWii::get_next() {
if (!dir_stream)
return "";
dirent *entry = readdir(dir_stream);
if (entry == NULL) {
list_dir_end();
return "";
}
String fname = fix_unicode_name(entry->d_name);
// Look at d_type to determine if the entry is a directory, unless
// its type is unknown (the file system does not support it) or if
// the type is a link, in that case we want to resolve the link to
// known if it points to a directory. stat() will resolve the link
// for us.
if (entry->d_type == DT_UNKNOWN || entry->d_type == DT_LNK) {
String f = current_dir.plus_file(fname);
struct stat flags;
if (stat(f.utf8().get_data(), &flags) == 0) {
_cisdir = S_ISDIR(flags.st_mode);
} else {
_cisdir = false;
}
} else {
_cisdir = (entry->d_type == DT_DIR);
}
_cishidden = (fname != "." && fname != ".." && fname.begins_with("."));
return fname;
}
bool DirAccessWii::current_is_dir() const {
return _cisdir;
}
bool DirAccessWii::current_is_hidden() const {
return _cishidden;
}
void DirAccessWii::list_dir_end() {
if (dir_stream)
closedir(dir_stream);
dir_stream = 0;
_cisdir = false;
}
int DirAccessWii::get_drive_count()
{
return 0;
}
String DirAccessWii::get_drive(int p_drive)
{
return "";
}
Error DirAccessWii::change_dir(String p_dir)
{
GLOBAL_LOCK_FUNCTION
p_dir = fix_path(p_dir);
// prev_dir is the directory we are changing out of
String prev_dir;
char real_current_dir_name[2048];
ERR_FAIL_COND_V(getcwd(real_current_dir_name, 2048) == NULL, ERR_BUG);
if (prev_dir.parse_utf8(real_current_dir_name))
prev_dir = real_current_dir_name; //no utf8, maybe latin?
// try_dir is the directory we are trying to change into
String try_dir = "";
if (p_dir.is_rel_path()) {
String next_dir = current_dir.plus_file(p_dir);
next_dir = next_dir.simplify_path();
try_dir = next_dir;
} else {
try_dir = p_dir;
}
bool worked = (chdir(try_dir.utf8().get_data()) == 0); // we can only give this utf8
if (!worked) {
return ERR_INVALID_PARAMETER;
}
String base = _get_root_path();
if (base != String() && !try_dir.begins_with(base)) {
ERR_FAIL_COND_V(getcwd(real_current_dir_name, 2048) == NULL, ERR_BUG);
String new_dir;
new_dir.parse_utf8(real_current_dir_name);
if (!new_dir.begins_with(base)) {
try_dir = current_dir; //revert
}
}
// the directory exists, so set current_dir to try_dir
current_dir = try_dir;
ERR_FAIL_COND_V(chdir(prev_dir.utf8().get_data()) != 0, ERR_BUG);
return OK;
}
String DirAccessWii::get_current_dir()
{
String base = _get_root_path();
if (base != "") {
String bd = current_dir.replace_first(base, "");
if (bd.begins_with("/"))
return _get_root_string() + bd.substr(1, bd.length());
else
return _get_root_string() + bd;
}
return current_dir;
}
Error DirAccessWii::make_dir(String p_dir)
{
GLOBAL_LOCK_FUNCTION
if (p_dir.is_rel_path())
p_dir = get_current_dir().plus_file(p_dir);
p_dir = fix_path(p_dir);
bool success = (mkdir(p_dir.utf8().get_data(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0);
int err = errno;
if (success) {
return OK;
};
if (err == EEXIST) {
return ERR_ALREADY_EXISTS;
};
return ERR_CANT_CREATE;
}
size_t DirAccessWii::get_space_left() {
struct statvfs vfs;
if (statvfs(current_dir.utf8().get_data(), &vfs) != 0) {
return 0;
};
return vfs.f_bfree * vfs.f_bsize;
};
Error DirAccessWii::rename(String p_path, String p_new_path)
{
if (p_path.is_rel_path())
p_path = get_current_dir().plus_file(p_path);
p_path = fix_path(p_path);
if (p_new_path.is_rel_path())
p_new_path = get_current_dir().plus_file(p_new_path);
p_new_path = fix_path(p_new_path);
return ::rename(p_path.utf8().get_data(), p_new_path.utf8().get_data()) == 0 ? OK : FAILED;
}
Error DirAccessWii::remove(String p_path) {
if (p_path.is_rel_path())
p_path = get_current_dir().plus_file(p_path);
p_path = fix_path(p_path);
struct stat flags;
if ((stat(p_path.utf8().get_data(), &flags) != 0))
return FAILED;
if (S_ISDIR(flags.st_mode))
return ::rmdir(p_path.utf8().get_data()) == 0 ? OK : FAILED;
else
return ::unlink(p_path.utf8().get_data()) == 0 ? OK : FAILED;
}
String DirAccessWii::get_filesystem_type() const {
return ""; //TODO this should be implemented
}
DirAccessWii::DirAccessWii() {
dir_stream = 0;
_cisdir = false;
/* determine drive count */
// set current directory to an absolute path of the current directory
char real_current_dir_name[2048];
ERR_FAIL_COND(getcwd(real_current_dir_name, 2048) == NULL);
if (current_dir.parse_utf8(real_current_dir_name))
current_dir = real_current_dir_name;
change_dir(current_dir);
}
DirAccessWii::~DirAccessWii() {
list_dir_end();
} | 21.555944 | 93 | 0.696026 | xchellx |
2c477440c48b3026acfd0921201aa493ff5335ad | 2,197 | cpp | C++ | drape/utils/gpu_mem_tracker.cpp | marceldallagnol/omim | 774de15a3b8c369acbf412f15a1db61717358262 | [
"Apache-2.0"
] | 2 | 2019-01-24T15:36:20.000Z | 2019-12-26T10:03:48.000Z | drape/utils/gpu_mem_tracker.cpp | marceldallagnol/omim | 774de15a3b8c369acbf412f15a1db61717358262 | [
"Apache-2.0"
] | 1 | 2018-03-07T15:05:23.000Z | 2018-03-07T15:05:23.000Z | drape/utils/gpu_mem_tracker.cpp | marceldallagnol/omim | 774de15a3b8c369acbf412f15a1db61717358262 | [
"Apache-2.0"
] | 1 | 2019-08-09T21:31:29.000Z | 2019-08-09T21:31:29.000Z | #include "drape/utils/gpu_mem_tracker.hpp"
#include "std/tuple.hpp"
#include "std/sstream.hpp"
namespace dp
{
string GPUMemTracker::GPUMemorySnapshot::ToString() const
{
ostringstream ss;
ss << " Summary Allocated = " << m_summaryAllocatedInMb << "Mb\n";
ss << " Summary Used = " << m_summaryUsedInMb << "Mb\n";
ss << " Tags registered = " << m_tagStats.size() << "\n";
for (auto const it : m_tagStats)
{
ss << " Tag = " << it.first << " \n";
ss << " Object count = " << it.second.m_objectsCount << "\n";
ss << " Allocated = " << it.second.m_alocatedInMb << "Mb\n";
ss << " Used = " << it.second.m_usedInMb << "Mb\n";
}
return ss.str();
}
GPUMemTracker & GPUMemTracker::Inst()
{
static GPUMemTracker s_inst;
return s_inst;
}
GPUMemTracker::GPUMemorySnapshot GPUMemTracker::GetMemorySnapshot()
{
GPUMemorySnapshot memStat;
{
threads::MutexGuard g(m_mutex);
for (auto const it : m_memTracker)
{
TagMemorySnapshot & tagStat = memStat.m_tagStats[it.first.first];
tagStat.m_objectsCount++;
tagStat.m_alocatedInMb += it.second.first;
tagStat.m_usedInMb += it.second.second;
memStat.m_summaryAllocatedInMb += it.second.first;
memStat.m_summaryUsedInMb += it.second.second;
}
}
float byteToMb = static_cast<float>(1024 * 1024);
for (auto & it : memStat.m_tagStats)
{
it.second.m_alocatedInMb /= byteToMb;
it.second.m_usedInMb /= byteToMb;
}
memStat.m_summaryAllocatedInMb /= byteToMb;
memStat.m_summaryUsedInMb /= byteToMb;
return memStat;
}
void GPUMemTracker::AddAllocated(string const & tag, uint32_t id, uint32_t size)
{
threads::MutexGuard g(m_mutex);
m_memTracker[make_pair(tag, id)].first = size;
}
void GPUMemTracker::SetUsed(string const & tag, uint32_t id, uint32_t size)
{
threads::MutexGuard g(m_mutex);
TAlocUsedMem & node = m_memTracker[make_pair(tag, id)];
node.second = size;
ASSERT_LESS_OR_EQUAL(node.second, node.first, ("Can't use more than allocated"));
}
void GPUMemTracker::RemoveDeallocated(string const & tag, uint32_t id)
{
threads::MutexGuard g(m_mutex);
m_memTracker.erase(make_pair(tag, id));
}
} // namespace dp
| 26.154762 | 83 | 0.672736 | marceldallagnol |
2c47b6b4bb3baaa25ce739a3f867f3876115a95c | 2,697 | cpp | C++ | tests/Unit/Helpers/PointwiseFunctions/GeneralRelativity/TestHelpers.cpp | macedo22/spectre | 97b2b7ae356cf86830258cb5f689f1191fdb6ddd | [
"MIT"
] | 2 | 2021-04-11T04:07:42.000Z | 2021-04-11T05:07:54.000Z | tests/Unit/Helpers/PointwiseFunctions/GeneralRelativity/TestHelpers.cpp | macedo22/spectre | 97b2b7ae356cf86830258cb5f689f1191fdb6ddd | [
"MIT"
] | 4 | 2018-06-04T20:26:40.000Z | 2018-07-27T14:54:55.000Z | tests/Unit/Helpers/PointwiseFunctions/GeneralRelativity/TestHelpers.cpp | macedo22/spectre | 97b2b7ae356cf86830258cb5f689f1191fdb6ddd | [
"MIT"
] | 1 | 2019-01-03T21:47:04.000Z | 2019-01-03T21:47:04.000Z | // Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Helpers/PointwiseFunctions/GeneralRelativity/TestHelpers.hpp"
#include "DataStructures/DataVector.hpp" // IWYU pragma: keep
#include "DataStructures/Tensor/Tensor.hpp" // IWYU pragma: keep
#include "Helpers/DataStructures/MakeWithRandomValues.hpp"
#include "Utilities/GenerateInstantiations.hpp"
#include "Utilities/Gsl.hpp"
namespace TestHelpers::gr {
template <typename DataType>
Scalar<DataType> random_lapse(const gsl::not_null<std::mt19937*> generator,
const DataType& used_for_size) noexcept {
std::uniform_real_distribution<> distribution(0.0, 3.0);
return make_with_random_values<Scalar<DataType>>(
generator, make_not_null(&distribution), used_for_size);
}
template <size_t Dim, typename DataType>
tnsr::I<DataType, Dim> random_shift(
const gsl::not_null<std::mt19937*> generator,
const DataType& used_for_size) noexcept {
std::uniform_real_distribution<> distribution(-1.0, 1.0);
return make_with_random_values<tnsr::I<DataType, Dim>>(
generator, make_not_null(&distribution), used_for_size);
}
template <size_t Dim, typename DataType, typename Fr>
tnsr::ii<DataType, Dim, Fr> random_spatial_metric(
const gsl::not_null<std::mt19937*> generator,
const DataType& used_for_size) noexcept {
std::uniform_real_distribution<> distribution(-0.05, 0.05);
auto spatial_metric = make_with_random_values<tnsr::ii<DataType, Dim, Fr>>(
generator, make_not_null(&distribution), used_for_size);
for (size_t d = 0; d < Dim; ++d) {
spatial_metric.get(d, d) += 1.0;
}
return spatial_metric;
}
#define DTYPE(data) BOOST_PP_TUPLE_ELEM(0, data)
#define DIM(data) BOOST_PP_TUPLE_ELEM(1, data)
#define INSTANTIATE_SCALARS(_, data) \
template Scalar<DTYPE(data)> random_lapse( \
const gsl::not_null<std::mt19937*> generator, \
const DTYPE(data) & used_for_size) noexcept;
GENERATE_INSTANTIATIONS(INSTANTIATE_SCALARS, (double, DataVector))
#define INSTANTIATE_TENSORS(_, data) \
template tnsr::I<DTYPE(data), DIM(data)> random_shift( \
const gsl::not_null<std::mt19937*> generator, \
const DTYPE(data) & used_for_size) noexcept; \
template tnsr::ii<DTYPE(data), DIM(data)> random_spatial_metric( \
const gsl::not_null<std::mt19937*> generator, \
const DTYPE(data) & used_for_size) noexcept;
GENERATE_INSTANTIATIONS(INSTANTIATE_TENSORS, (double, DataVector), (1, 2, 3))
#undef INSTANTIATE_SCALARS
#undef INSTANTIATE_TENSORS
#undef DIM
#undef DTYPE
} // namespace TestHelpers::gr
| 39.661765 | 77 | 0.708194 | macedo22 |
2c481bd2bd7b05816bcfae573030a18d98461e1e | 890 | inl | C++ | src/Engine/Renderer/RenderTechnique/RenderParameters.inl | nmellado/Radium-Engine | 6e42e4be8d14bcd496371a5f58d483f7d03f9cf4 | [
"Apache-2.0"
] | null | null | null | src/Engine/Renderer/RenderTechnique/RenderParameters.inl | nmellado/Radium-Engine | 6e42e4be8d14bcd496371a5f58d483f7d03f9cf4 | [
"Apache-2.0"
] | null | null | null | src/Engine/Renderer/RenderTechnique/RenderParameters.inl | nmellado/Radium-Engine | 6e42e4be8d14bcd496371a5f58d483f7d03f9cf4 | [
"Apache-2.0"
] | null | null | null | #include <Engine/Renderer/RenderTechnique/RenderParameters.hpp>
#include <Engine/Renderer/RenderTechnique/ShaderProgram.hpp>
namespace Ra
{
namespace Engine
{
template <typename T>
inline void RenderParameters::UniformBindableVector<T>::bind(const ShaderProgram* shader ) const
{
for ( auto& value : *this )
{
value.second.bind( shader );
}
}
template <typename T>
inline void RenderParameters::TParameter<T>::bind(const ShaderProgram* shader ) const
{
shader->setUniform( m_name, m_value );
}
inline void RenderParameters::TextureParameter::bind(const ShaderProgram* shader ) const
{
shader->setUniform( m_name, m_texture, m_texUnit );
}
} // namespace Engine
} // namespace Ra
| 28.709677 | 105 | 0.589888 | nmellado |
2c492deee70eb7e4a73c88bf04ed9c49a1d7416a | 2,104 | cpp | C++ | modules/task_2/ermakov_p_grackham_omp/Main.cpp | allnes/pp_2022_spring | 159191f9c2f218f8b8487f92853cc928a7652462 | [
"BSD-3-Clause"
] | null | null | null | modules/task_2/ermakov_p_grackham_omp/Main.cpp | allnes/pp_2022_spring | 159191f9c2f218f8b8487f92853cc928a7652462 | [
"BSD-3-Clause"
] | null | null | null | modules/task_2/ermakov_p_grackham_omp/Main.cpp | allnes/pp_2022_spring | 159191f9c2f218f8b8487f92853cc928a7652462 | [
"BSD-3-Clause"
] | 2 | 2022-03-31T17:48:22.000Z | 2022-03-31T18:06:07.000Z | // Copyright 2022 Ermakov Pavel
#include "../../../modules/task_2/ermakov_p_grackham_omp/grackham.h"
#include "gtest/gtest.h"
#define THREAD_NUM 4
TEST(grackham_seq, test_size_0) {
std::vector<std::pair<double, double>> dots;
int size = 0;
dots = gen_dots(size);
std::vector<std::pair<double, double>> seq_res;
seq_res = grackham_seq(dots.begin(), dots.end());
ASSERT_EQ(seq_res, seq_res);
}
TEST(grackham_seq, test_size_100) {
std::vector<std::pair<double, double>> dots;
int size = 100;
dots = gen_dots(size);
std::vector<std::pair<double, double>> seq_res;
std::vector<std::pair<double, double>> omp_res;
seq_res = grackham_seq(dots.begin(), dots.end());
omp_res = grackham_omp(dots.begin(), dots.end(), THREAD_NUM);
ASSERT_EQ(seq_res, seq_res);
}
TEST(grackham_seq, test_size_200) {
std::vector<std::pair<double, double>> dots;
int size = 200;
dots = gen_dots(size);
std::vector<std::pair<double, double>> seq_res;
std::vector<std::pair<double, double>> omp_res;
seq_res = grackham_seq(dots.begin(), dots.end());
omp_res = grackham_omp(dots.begin(), dots.end(), THREAD_NUM);
ASSERT_EQ(seq_res, seq_res);
}
TEST(grackham_seq, test_size_400) {
std::vector<std::pair<double, double>> dots;
int size = 400;
dots = gen_dots(size);
std::vector<std::pair<double, double>> seq_res;
std::vector<std::pair<double, double>> omp_res;
seq_res = grackham_seq(dots.begin(), dots.end());
omp_res = grackham_omp(dots.begin(), dots.end(), THREAD_NUM);
ASSERT_EQ(seq_res, seq_res);
}
TEST(grackham_seq, test_size_1000) {
std::vector<std::pair<double, double>> dots;
int size = 1000;
dots = gen_dots(size);
std::vector<std::pair<double, double>> seq_res;
std::vector<std::pair<double, double>> omp_res;
seq_res = grackham_seq(dots.begin(), dots.end());
omp_res = grackham_omp(dots.begin(), dots.end(), THREAD_NUM);
ASSERT_EQ(seq_res, seq_res);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 29.633803 | 68 | 0.664924 | allnes |
2c4c07131285fad5893fd08084a675afc9b15192 | 525 | cpp | C++ | Aula08/ex-02-16.cpp | cgcosta/scaling-barnacle | 2477436768ccb75b66feb6c0a837314f1ffa9dd3 | [
"MIT"
] | null | null | null | Aula08/ex-02-16.cpp | cgcosta/scaling-barnacle | 2477436768ccb75b66feb6c0a837314f1ffa9dd3 | [
"MIT"
] | 1 | 2018-04-27T23:42:44.000Z | 2018-04-27T23:42:44.000Z | Aula08/ex-02-16.cpp | cgcosta/scaling-barnacle | 2477436768ccb75b66feb6c0a837314f1ffa9dd3 | [
"MIT"
] | null | null | null | /*
Escreva um programa que solicita ao usuário inserir dois números, obtém os dois números do usuário imprime a soma, produto, diferença e quociente dos dois números.
Cassio
*/
#include <iostream>
using namespace std;
int main()
{
float a;
float b;
cout << "Informe o valor de A: ";
cin >> a;
cout << "Informe o valor de B: ";
cin >> b;
cout << "Soma= " << a + b << endl;
cout << "Produto= " << a * b << endl;
cout << "Diferença= " << a - b << endl;
cout << "Quociente= " << a / b << endl;
return 0;
}
| 16.935484 | 163 | 0.6 | cgcosta |
2c4ca4be579e70582211ec5ab8862f8bf4d2c3fe | 4,008 | cpp | C++ | src/cpp/XMLParser.cpp | YuriySavchenko/Test_Task | 206fd75800767ad18027a6d9934a3f5be50f7526 | [
"Apache-2.0"
] | null | null | null | src/cpp/XMLParser.cpp | YuriySavchenko/Test_Task | 206fd75800767ad18027a6d9934a3f5be50f7526 | [
"Apache-2.0"
] | null | null | null | src/cpp/XMLParser.cpp | YuriySavchenko/Test_Task | 206fd75800767ad18027a6d9934a3f5be50f7526 | [
"Apache-2.0"
] | null | null | null | //
// Created by yuriy on 10/7/18.
//
#include "../headers/XMLParser.h"
/* implementation of method for parsing *.xml files */
void XMLParser::parseFile(std::vector<Interval> &intervals) {
if (fin.is_open()) {
std::vector<std::string> text = splitString(buffer, '\n');
// we are checking if first and second tags are <root>
if (cmpString(text[0], "<root>") && cmpString(text[text.size()], "</root>")) {
for (int i=1; i < text.size(); i++) {
if (cmpString(text[i], "<intervals>")) {
int endIntervals = 0;
// loop which allows looking for end of section { <intervals> ... </intervals> }
for (int j=i+1; j < text.size(); j++) {
if (cmpString(text[j], "</intervals>")) {
endIntervals = j;
break;
}
}
// revising each tag until end of section
for (int j=i+1; j < endIntervals; j++) {
if (cmpString(text[j], "<interval>")) {
// variables for saving integer values
std::string lowStr = "";
std::string highStr = "";
// if we have in first tag construction { <low> num </low> }
// we are transforming string between tags into number
int pos = indexString(5, (int) text[j+1].length(), '<', text[j+1]);
if (cmpString(text[j+1].substr(0, 5), "<low>") &&
cmpString(text[j+1].substr(pos, pos+8), "</low>"))
lowStr = digitString(text[j+1]);
// if we have in second tag construction { <high> num </high> }
// we are transforming string between tags into number
pos = indexString(6, (int) text[j+2].length(), '<', text[j+2]);
if (cmpString(text[j+2].substr(0, 6), "<high>") &&
cmpString(text[j+2].substr(pos, pos+6), "</high>"))
highStr = digitString(text[j+2]);
// if both strings can to be transforming into numbers, then add them into vector
int low = std::stoi(lowStr);
int high = std::stoi(highStr);
if ((low > 2) && (high > 2)) {
intervals.push_back(Interval{low, high});
}
}
// case which looking for others <interval> into <intervals>
if (cmpString(text[j], "</interval>")) {
continue;
}
}
}
}
}
}
}
/* implementation of particular constructor */
XMLParser::XMLParser(std::string name) {
this->name = name;
}
/* implementation of destructor */
XMLParser::~XMLParser() {
}
/* redefined function for opening file */
void XMLParser::openFile() {
if (!this->fin.is_open())
this->fin.open(this->name);
}
/* function for reading from file */
void XMLParser::readFile() {
if (this->fin.is_open()) {
std::string text = "";
std::string line;
while(std::getline(fin, line))
text += line + '\n';
this->buffer = text;
}
}
/* redefined function for closing file */
void XMLParser::closeFile() {
if (fin.is_open())
fin.close();
}
/* function which allows getting value from private variable { fin } */
const std::ifstream &XMLParser::getFin() const {
return fin;
}
/* function which allows getting value from private variable { buffer } */
const std::string &XMLParser::getBuffer() const {
return buffer;
}
| 30.830769 | 109 | 0.460329 | YuriySavchenko |
2c50c0972b3eabeab1e35cad10068396972e061b | 1,525 | cpp | C++ | compiler/src/parser/symboltable.cpp | Excse/ArkoiL | d075ddd83b218f4e21df6141cca549bc75f46419 | [
"Apache-2.0"
] | 8 | 2020-04-15T19:57:29.000Z | 2022-03-18T21:09:12.000Z | compiler/src/parser/symboltable.cpp | Excse/ArkoiL | d075ddd83b218f4e21df6141cca549bc75f46419 | [
"Apache-2.0"
] | 4 | 2020-06-28T22:20:45.000Z | 2020-08-15T13:31:08.000Z | compiler/src/parser/symboltable.cpp | Excse/ArkoiL | d075ddd83b218f4e21df6141cca549bc75f46419 | [
"Apache-2.0"
] | 3 | 2020-04-15T19:40:11.000Z | 2021-01-18T20:02:09.000Z | //
// Created by timo on 8/7/20.
//
#include "../../include/parser/symboltable.h"
#include <iostream>
#include <utility>
#include "../../include/parser/astnodes.h"
SymbolTable::SymbolTable(SharedSymbolTable parent)
: m_Parent(std::move(parent)), m_Table({}) {}
SymbolTable::SymbolTable(const SymbolTable &other)
: m_Parent(nullptr), m_Table(other.m_Table) {}
void SymbolTable::insert(const std::string &id, const SharedASTNode &node) {
auto iterator = m_Table.find(id);
if (iterator != m_Table.end()) {
iterator->second.emplace_back(node);
} else {
Symbols symbols{};
symbols.emplace_back(node);
m_Table.emplace(id, symbols);
}
}
void SymbolTable::all(Symbols &symbols, const std::string &id,
const SymbolTable::Predicate &predicate) {
scope(symbols, id, predicate);
if (!symbols.empty())
return;
if (m_Parent)
return m_Parent->all(symbols, id, predicate);
}
void SymbolTable::scope(Symbols &symbols, const std::string &id,
const SymbolTable::Predicate &predicate) {
auto iterator = m_Table.find(id);
if (iterator == m_Table.end())
return;
for (const auto &node : iterator->second) {
if (predicate && !predicate(node))
continue;
symbols.emplace_back(node);
}
}
const SharedSymbolTable &SymbolTable::getParent() const {
return m_Parent;
}
const SymbolTable::Table &SymbolTable::getTable() const {
return m_Table;
} | 25.416667 | 76 | 0.633443 | Excse |
2c5449f1599c8e1b05acff2e28f6d6b8f2c18ac5 | 6,192 | cxx | C++ | c++/laolrt/laol/rt/array.cxx | gburdell/laol | 4ba457b2d4fa25525173cd045aa57ff4485ef7ae | [
"MIT"
] | null | null | null | c++/laolrt/laol/rt/array.cxx | gburdell/laol | 4ba457b2d4fa25525173cd045aa57ff4485ef7ae | [
"MIT"
] | null | null | null | c++/laolrt/laol/rt/array.cxx | gburdell/laol | 4ba457b2d4fa25525173cd045aa57ff4485ef7ae | [
"MIT"
] | null | null | null | /*
* The MIT License
*
* Copyright 2017 kpfalzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <algorithm>
#include <sstream>
#include "laol/rt/array.hxx"
#include "laol/rt/range.hxx"
#include "laol/rt/string.hxx"
#include "laol/rt/exception.hxx"
namespace laol {
namespace rt {
using std::to_string;
Laol::METHOD_BY_NAME IArray::stMethodByName;
Laol::METHOD_BY_NAME Array::stMethodByName;
IArray::~IArray() {
}
Array::Array() {
}
Array::Array(Args v)
: PTArray<LaolObj>(v) {
}
Array::Array(const LaolObj& v)
: Array(v.isA<Array>() ? v.toType<Array>().m_ar : toV(v)) {
}
const Laol::METHOD_BY_NAME&
IArray::getMethodByName() {
if (stMethodByName.empty()) {
stMethodByName = join(stMethodByName,
METHOD_BY_NAME({
{"length", reinterpret_cast<TPMethod> (&IArray::length)},
{"empty?", reinterpret_cast<TPMethod> (&IArray::empty_PRED)},
{"foreach", reinterpret_cast<TPMethod> (&IArray::foreach)}
}));
}
return stMethodByName;
}
Ref
IArray::empty_PRED(const LaolObj& self, const LaolObj& args) const {
return isEmpty();
}
Ref
IArray::length(const LaolObj& self, const LaolObj& args) const {
return xlength();
}
size_t
IArray::actualIndex(long int ix) const {
return laol::rt::actualIndex(ix, xlength());
}
const Laol::METHOD_BY_NAME&
Array::getMethodByName() {
if (stMethodByName.empty()) {
stMethodByName = join(stMethodByName,
IArray::getMethodByName(),
METHOD_BY_NAME({
{"left_shift", reinterpret_cast<TPMethod> (&Array::left_shift)},
{"right_shift", reinterpret_cast<TPMethod> (&Array::right_shift)},
{"reverse", reinterpret_cast<TPMethod> (&Array::reverse)},
{"reverse!", reinterpret_cast<TPMethod> (&Array::reverse_SELF)}
}));
}
return stMethodByName;
}
LaolObj
Array::left_shift(const LaolObj& self, const LaolObj& opB) const {
unconst(this)->m_ar.push_back(opB);
return self;
}
LaolObj
Array::right_shift(const LaolObj& self, const LaolObj& opB) const {
unconst(this)->m_ar.insert(m_ar.begin(), opB);
return self;
}
#ifdef TODO
LaolObj
Array::toString(const LaolObj& self, const LaolObj&) const {
std::ostringstream oss;
oss << "[";
bool doComma = false;
for (const LaolObj& ele : m_ar) {
if (doComma) {
oss << ", ";
}
oss << ele.toQString();
doComma = true;
}
oss << "]";
return new String(oss.str());
}
#endif
// Local iterator over int range
template<typename FUNC>
void iterate(const Range& rng, FUNC forEach) {
auto i = rng.m_begin.toLongInt(), end = rng.m_end.toLongInt();
const auto incr = (end > i) ? 1 : -1;
while (true) {
forEach(i);
if (i == end) {
return;
}
i += incr;
}
}
const Array::Vector
Array::toVector(const LaolObj& opB) {
return opB.isA<Array>() ? opB.toType<Array>().m_ar : toV(opB);
}
/*
* opB : scalar or Array of vals...
*/
Ref
Array::subscript(const LaolObj&, const LaolObj& opB) const {
const Vector args = toVector(opB);
//degenerate case of single index
if ((1 == args.size()) && args[0].isInt()) {
return &m_ar[actualIndex(args[0].toLongInt())];
}
//else, build up ArrayOfRef
ArrayOfRef* pRefs = new ArrayOfRef();
for (const LaolObj& ix : args) {
if (ix.isInt()) {
pRefs->push_back(&m_ar[actualIndex(ix.toLongInt())]);
} else if (ix.isA<Range>()) {
iterate(ix.toType<Range>(), [this, &pRefs](auto i) {
//this-> work around gcc 5.1.0 bug
pRefs->push_back(&m_ar[this->actualIndex(i)]);
});
} else {
ASSERT_NEVER; //todo: error
}
}
return LaolObj(pRefs);
}
Ref
ArrayOfRef::subscript(const LaolObj& self, const LaolObj& opB) const {
const Array::Vector args = Array::toVector(opB);
if ((1 == args.size()) && args[0].isInt()) {
return &m_ar[actualIndex(args[0].toLongInt())];
}
ASSERT_NEVER; //todo
return self; //todo
}
}
}
| 32.93617 | 86 | 0.531008 | gburdell |
2c55204f2eca4f64f796c17d14fba6d7b0fbd1d9 | 4,195 | cpp | C++ | tools/engine_hook/window_hooks.cpp | mouzedrift/alive | 7c297a39c60e930933c0a93ea373226907f8b1c7 | [
"MIT"
] | null | null | null | tools/engine_hook/window_hooks.cpp | mouzedrift/alive | 7c297a39c60e930933c0a93ea373226907f8b1c7 | [
"MIT"
] | null | null | null | tools/engine_hook/window_hooks.cpp | mouzedrift/alive | 7c297a39c60e930933c0a93ea373226907f8b1c7 | [
"MIT"
] | null | null | null | #include "window_hooks.hpp"
#include "debug_dialog.hpp"
#include "resource.h"
#include <memory>
#include <vector>
#include "anim_logger.hpp"
#include <WinUser.h>
bool gCollisionsEnabled = true;
bool gGridEnabled = false;
static WNDPROC g_pOldProc = 0;
std::unique_ptr<DebugDialog> gDebugUi;
extern HMODULE gDllHandle;
namespace Hooks
{
Hook<decltype(&::SetWindowLongA)> SetWindowLong(::SetWindowLongA);
}
LRESULT CALLBACK NewWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if (!gDebugUi)
{
gDebugUi = std::make_unique<DebugDialog>();
gDebugUi->Create(gDllHandle, MAKEINTRESOURCE(IDD_MAIN));
gDebugUi->Show();
CenterWnd(gDebugUi->Hwnd());
gDebugUi->OnReloadAnimJson([&]() { GetAnimLogger().ReloadJson(); });
}
switch (message)
{
case WM_CREATE:
abort();
break;
case WM_ERASEBKGND:
{
RECT rcWin;
HDC hDC = GetDC(hwnd);
GetClipBox((HDC)wParam, &rcWin);
FillRect(hDC, &rcWin, GetSysColorBrush(COLOR_DESKTOP)); // hBrush can be obtained by calling GetWindowLong()
}
return TRUE;
case WM_GETICON:
case WM_MOUSEACTIVATE:
case WM_NCLBUTTONDOWN:
case WM_NCMOUSELEAVE:
case WM_KILLFOCUS:
case WM_SETFOCUS:
case WM_ACTIVATEAPP:
case WM_NCHITTEST:
case WM_ACTIVATE:
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_LBUTTONDBLCLK:
case WM_NCCALCSIZE:
case WM_MOVE:
case WM_WINDOWPOSCHANGED:
case WM_WINDOWPOSCHANGING:
case WM_NCMOUSEMOVE:
case WM_MOUSEMOVE:
return DefWindowProc(hwnd, message, wParam, lParam);
case WM_KEYDOWN:
{
if (GetAsyncKeyState('G'))
{
gGridEnabled = !gGridEnabled;
}
if (GetAsyncKeyState('H'))
{
gCollisionsEnabled = !gCollisionsEnabled;
}
return g_pOldProc(hwnd, message, wParam, lParam);
}
case WM_SETCURSOR:
{
// Set the cursor so the resize cursor or whatever doesn't "stick"
// when we move the mouse over the game window.
static HCURSOR cur = LoadCursor(0, IDC_ARROW);
if (cur)
{
SetCursor(cur);
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
case WM_PAINT:
{
PAINTSTRUCT ps;
BeginPaint(hwnd, &ps);
EndPaint(hwnd, &ps);
}
return FALSE;
}
if (message == WM_DESTROY && gDebugUi)
{
gDebugUi->Destroy();
}
return g_pOldProc(hwnd, message, wParam, lParam);
}
void CenterWnd(HWND wnd)
{
RECT r, r1;
GetWindowRect(wnd, &r);
GetWindowRect(GetDesktopWindow(), &r1);
MoveWindow(wnd, ((r1.right - r1.left) - (r.right - r.left)) / 2,
((r1.bottom - r1.top) - (r.bottom - r.top)) / 2,
(r.right - r.left), (r.bottom - r.top), 0);
}
void SubClassWindow()
{
HWND wnd = FindWindow("ABE_WINCLASS", NULL);
g_pOldProc = (WNDPROC)SetWindowLong(wnd, GWL_WNDPROC, (LONG)NewWindowProc);
for (int i = 0; i < 70; ++i)
{
ShowCursor(TRUE);
}
SetWindowLongA(wnd, GWL_STYLE, WS_OVERLAPPEDWINDOW | WS_VISIBLE);
RECT rc;
SetRect(&rc, 0, 0, 640, 460);
AdjustWindowRectEx(&rc, WS_OVERLAPPEDWINDOW | WS_VISIBLE, TRUE, 0);
SetWindowPos(wnd, NULL, 0, 0, rc.right - rc.left, rc.bottom - rc.top,
SWP_SHOWWINDOW);
ShowWindow(wnd, SW_HIDE);
CenterWnd(wnd);
ShowWindow(wnd, SW_SHOW);
InvalidateRect(GetDesktopWindow(), NULL, TRUE);
}
void PatchWindowTitle()
{
HWND wnd = FindWindow("ABE_WINCLASS", NULL);
if (wnd)
{
const int length = GetWindowTextLength(wnd) + 1;
std::vector< char > titleBuffer(length + 1);
if (GetWindowText(wnd, titleBuffer.data(), length))
{
std::string titleStr(titleBuffer.data());
titleStr += " under ALIVE hook";
SetWindowText(wnd, titleStr.c_str());
}
}
}
LONG WINAPI Hook_SetWindowLongA(HWND hWnd, int nIndex, LONG dwNewLong)
{
if (nIndex == GWL_STYLE)
{
dwNewLong = WS_OVERLAPPEDWINDOW | WS_VISIBLE;
}
return Hooks::SetWindowLong.Real()(hWnd, nIndex, dwNewLong);
}
| 24.389535 | 117 | 0.618832 | mouzedrift |
2c57c5a03651bea61c96f288b8fec0f0d8f5d104 | 2,220 | cpp | C++ | acm-template/4 Math/FFT/lrj.cpp | joshua-xia/noip | 0603a75c7be6e9b21fcabbba4260153cf776c32f | [
"Apache-2.0"
] | null | null | null | acm-template/4 Math/FFT/lrj.cpp | joshua-xia/noip | 0603a75c7be6e9b21fcabbba4260153cf776c32f | [
"Apache-2.0"
] | null | null | null | acm-template/4 Math/FFT/lrj.cpp | joshua-xia/noip | 0603a75c7be6e9b21fcabbba4260153cf776c32f | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
#define mem(ar,num) memset(ar,num,sizeof(ar))
#define me(ar) memset(ar,0,sizeof(ar))
#define lowbit(x) (x&(-x))
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const int prime = 999983;
const int INF = 0x7FFFFFFF;
const LL INFF =0x7FFFFFFFFFFFFFFF;
//const double pi = acos(-1.0);
const double inf = 1e18;
const double eps = 1e-6;
const LL mod = 1e9 + 7;
int dr[2][4] = {1,-1,0,0,0,0,-1,1};
// UVa12298 Super Poker II
// Rujia Liu
const long double PI = acos(0.0) * 2.0;
typedef complex<double> CD;
// Cooley-Tukey的FFT算法,迭代实现。inverse = false时计算逆FFT
inline void FFT(vector<CD> &a, bool inverse) {
int n = a.size();
// 原地快速bit reversal
for(int i = 0, j = 0; i < n; i++) {
if(j > i) swap(a[i], a[j]);
int k = n;
while(j & (k >>= 1)) j &= ~k;
j |= k;
}
double pi = inverse ? -PI : PI;
for(int step = 1; step < n; step <<= 1) {
// 把每相邻两个“step点DFT”通过一系列蝴蝶操作合并为一个“2*step点DFT”
double alpha = pi / step;
// 为求高效,我们并不是依次执行各个完整的DFT合并,而是枚举下标k
// 对于一个下标k,执行所有DFT合并中该下标对应的蝴蝶操作,即通过E[k]和O[k]计算X[k]
// 蝴蝶操作参考:http://en.wikipedia.org/wiki/Butterfly_diagram
for(int k = 0; k < step; k++) {
// 计算omega^k. 这个方法效率低,但如果用每次乘omega的方法递推会有精度问题。
// 有更快更精确的递推方法,为了清晰起见这里略去
CD omegak = exp(CD(0, alpha*k));
for(int Ek = k; Ek < n; Ek += step << 1) { // Ek是某次DFT合并中E[k]在原始序列中的下标
int Ok = Ek + step; // Ok是该DFT合并中O[k]在原始序列中的下标
CD t = omegak * a[Ok]; // 蝴蝶操作:x1 * omega^k
a[Ok] = a[Ek] - t; // 蝴蝶操作:y1 = x0 - t
a[Ek] += t; // 蝴蝶操作:y0 = x0 + t
}
}
}
if(inverse)
for(int i = 0; i < n; i++) a[i] /= n;
}
// 用FFT实现的快速多项式乘法
inline vector<double> operator * (const vector<double>& v1, const vector<double>& v2) {
int s1 = v1.size(), s2 = v2.size(), S = 2;
while(S < s1 + s2) S <<= 1;
vector<CD> a(S,0), b(S,0); // 把FFT的输入长度补成2的幂,不小于v1和v2的长度之和
for(int i = 0; i < s1; i++) a[i] = v1[i];
FFT(a, false);
for(int i = 0; i < s2; i++) b[i] = v2[i];
FFT(b, false);
for(int i = 0; i < S; i++) a[i] *= b[i];
FFT(a, true);
vector<double> res(s1 + s2 - 1);
for(int i = 0; i < s1 + s2 - 1; i++) res[i] = a[i].real(); // 虚部均为0
return res;
}
| 30.410959 | 87 | 0.564414 | joshua-xia |
2c5b1dbafc7604151a63e9eeffcca4a56b1c0087 | 1,490 | hpp | C++ | src/utils/Log.hpp | gflix/LegoLwpProxy | 289fd32ddadf3dbfbfba85b42dbbab4fd026c813 | [
"MIT"
] | null | null | null | src/utils/Log.hpp | gflix/LegoLwpProxy | 289fd32ddadf3dbfbfba85b42dbbab4fd026c813 | [
"MIT"
] | null | null | null | src/utils/Log.hpp | gflix/LegoLwpProxy | 289fd32ddadf3dbfbfba85b42dbbab4fd026c813 | [
"MIT"
] | null | null | null | #ifndef UTILS_LOG_HPP_
#define UTILS_LOG_HPP_
#include <sstream>
#include <string>
#include <models/LogLevel.hpp>
namespace Lego
{
class Log
{
public:
Log();
explicit Log(LogLevel logLevel);
virtual ~Log() = default;
void error(std::string logMessage) const;
void warning(std::string logMessage) const;
void notice(std::string logMessage) const;
void info(std::string logMessage) const;
void debug(std::string logMessage) const;
void setLogLevel(LogLevel logLevel);
LogLevel getLogLevel(void) const;
static Log instance;
private:
bool toTty;
LogLevel logLevel;
std::string getTimestamp(void) const;
void determineOutputMode(void);
};
#define LOG_ERROR(message) { \
std::stringstream tempLogStream; tempLogStream << message; Lego::Log::instance.error(tempLogStream.str()); \
}
#define LOG_WARNING(message) { \
std::stringstream tempLogStream; tempLogStream << message; Lego::Log::instance.warning(tempLogStream.str()); \
}
#define LOG_NOTICE(message) { \
std::stringstream tempLogStream; tempLogStream << message; Lego::Log::instance.notice(tempLogStream.str()); \
}
#define LOG_INFO(message) { \
std::stringstream tempLogStream; tempLogStream << message; Lego::Log::instance.info(tempLogStream.str()); \
}
#define LOG_DEBUG(message) { \
std::stringstream tempLogStream; tempLogStream << message; Lego::Log::instance.debug(tempLogStream.str()); \
}
} /* namespace Lego */
#endif /* UTILS_LOG_HPP_ */
| 26.607143 | 114 | 0.713423 | gflix |
2c5fdd407fe564619ddb7888110d9c37b061f55f | 1,498 | cpp | C++ | module05/ex01/Form.cpp | M-Philippe/cpp_piscine | 9584ebcb030c54ca522dbcf795bdcb13a0325f77 | [
"MIT"
] | null | null | null | module05/ex01/Form.cpp | M-Philippe/cpp_piscine | 9584ebcb030c54ca522dbcf795bdcb13a0325f77 | [
"MIT"
] | null | null | null | module05/ex01/Form.cpp | M-Philippe/cpp_piscine | 9584ebcb030c54ca522dbcf795bdcb13a0325f77 | [
"MIT"
] | null | null | null | #include "Form.hpp"
/*
** Canonical Form
*/
Form::Form(int signGrad, int executionGrad)
: _signGrad(signGrad), _executionGrad(executionGrad) {}
Form::Form(const std::string& name, int signGrad, int executionGrad)
: _name(name), _signGrad(signGrad), _executionGrad(executionGrad), _isSigned(false) {
if (signGrad <= 0 || executionGrad <= 0)
throw Form::GradeTooLowException();
if (signGrad > 150 || executionGrad > 150)
throw Form::GradeTooHighException();
}
Form::Form(const Form& org)
:_name(org._name), _signGrad(org._signGrad), _executionGrad(org._executionGrad), _isSigned(org._isSigned) {}
Form& Form::operator=(const Form& org) {
_isSigned = org._isSigned;
return (*this);
}
Form::~Form() {}
/* *** */
std::string Form::getName() const { return (_name); }
bool Form::getIsSigned() const { return (_isSigned); }
int Form::getSignGrad() const { return (_signGrad); }
int Form::getExecutionGrad() const { return (_executionGrad); }
void Form::beSigned(const Bureaucrat& br) {
if (_signGrad < br.getGrade()) {
br.signForm(getName(), "grade is too low", false);
throw Form::GradeTooLowException();
}
_isSigned = true;
br.signForm(getName(), "", true);
}
std::ostream& operator<<(std::ostream& os, const Form& f) {
os << f.getName() << " is a ";
(f.getIsSigned()) ? os << "signed" : os << "non-signed";
os << " form. [signGrad : " << f.getSignGrad() << "]";
os << ", [executionGrad : " << f.getExecutionGrad() << "]" << std::endl;
return (os);
} | 28.264151 | 108 | 0.655541 | M-Philippe |
2c61f3b774c8b976cdcf7bb565d93724a2bba6da | 5,863 | cc | C++ | src/ThreadPool.cc | isabella232/mod_dup | 531382c8baeaa6781ddd1cfe4748b2dd0dbf328c | [
"Apache-2.0"
] | 16 | 2015-07-17T15:50:38.000Z | 2022-02-14T23:01:07.000Z | src/ThreadPool.cc | Orange-OpenSource/mod_dup | 531382c8baeaa6781ddd1cfe4748b2dd0dbf328c | [
"Apache-2.0"
] | 4 | 2016-04-19T20:27:04.000Z | 2018-02-21T11:48:05.000Z | src/ThreadPool.cc | isabella232/mod_dup | 531382c8baeaa6781ddd1cfe4748b2dd0dbf328c | [
"Apache-2.0"
] | 5 | 2015-01-26T14:49:47.000Z | 2021-06-22T09:59:11.000Z | /*
* mod_dup - duplicates apache requests
*
* Copyright (C) 2017 Orange
*
* 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 "ThreadPool.hh"
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include "RequestInfo.hh"
#include "Log.hh"
using namespace boost::posix_time;
namespace DupModule {
template <typename QueueT> ThreadPool<QueueT>::ThreadPool(tQueueWorker pWorker, const QueueT &pPoisonItem) :
mManagerThread(NULL),
mMinThreads(1), mMaxThreads(10),
mMinQueued(1), mMaxQueued(10),
mBeingKilled(0),
mStatsInterval(10000000),
mWorker(pWorker),
mPoisonItem(pPoisonItem),
mRunning(false),
mProgramName("ModDup")
{
}
template <typename QueueT> ThreadPool<QueueT>::~ThreadPool()
{
stop();
}
template <typename QueueT> void ThreadPool<QueueT>::newThread()
{
mThreads.push_back(new boost::thread(mWorker, boost::ref(this->mQueue)));
}
template <typename QueueT> void ThreadPool<QueueT>::poisonThread()
{
Log::debug("Dropping a poison pill.");
mQueue.push_front(mPoisonItem);
mBeingKilled++;
}
template <typename QueueT> void ThreadPool<QueueT>::collectKilled()
{
time_duration shortWait(0, 0, 0, 10000); // wait for 0h,0min,0s,10ms
std::list<boost::thread *>::iterator it = mThreads.begin();
while (it != mThreads.end()) {
if ((*it)->timed_join(shortWait)) {
Log::debug("Removing a terminated thread from pool.");
delete *it;
it = mThreads.erase(it);
mBeingKilled--;
}
else {
++it;
}
}
}
template <typename QueueT> void ThreadPool<QueueT>::run()
{
unsigned pid = getpid();
unsigned iterationsSinceStats = 0;
while (mRunning) {
size_t lQueued = mQueue.size();
float lQueuedPerThread = static_cast<float>(mQueue.size()) / mThreads.size();
collectKilled();
if ((lQueuedPerThread > mMaxQueued) && (mThreads.size() < mMaxThreads)) {
newThread();
}
else if ((lQueuedPerThread < mMinQueued) && ((mThreads.size() - mBeingKilled) > mMinThreads)) {
poisonThread();
}
if (++iterationsSinceStats * mManageInterval >= mStatsInterval) {
unsigned lInCount, lOutCount, lDropCount;
mQueue.getCounters(lInCount, lOutCount, lDropCount);
// FIXME: Hardcoding retrieval of only additional stats for now. This should become more generic.
std::map<std::string, tStatProvider>::const_iterator lStatsIter = mAdditionalStats.find("#TmOut");
const std::string lTimeoutCount = lStatsIter == mAdditionalStats.end() ? "??" : lStatsIter->second();
lStatsIter = mAdditionalStats.find("#DupReq");
const std::string lDuplicateCount = lStatsIter == mAdditionalStats.end() ? "??" : lStatsIter->second();
Log::notice(201, "%s - %u - %zu - %zu - %u - %u - %u - %s - %s",
mProgramName.c_str(), pid, lQueued, mThreads.size(), lInCount, lOutCount,
lDropCount, lTimeoutCount.c_str(), lDuplicateCount.c_str());
if (lDropCount > 0) {
Log::warn(301, "Pool %u dropped %d requests during last cycle!", pid, lDropCount);
}
iterationsSinceStats = 0;
}
usleep(mManageInterval);
}
// Poison all threads, not an issue if some were already exiting
for (unsigned i = 0; i < mThreads.size(); ++i) {
poisonThread();
}
collectKilled();
}
template <typename QueueT> void ThreadPool<QueueT>::setStatsInterval(const unsigned pStatsInterval)
{
mStatsInterval = pStatsInterval;
}
template <typename QueueT> void ThreadPool<QueueT>::addStat(const std::string &pStatName, tStatProvider pStatProvider)
{
mAdditionalStats[pStatName] = pStatProvider;
}
template <typename QueueT> void ThreadPool<QueueT>::setProgramName(const std::string &pProgramName)
{
mProgramName = pProgramName;
}
template <typename QueueT> void ThreadPool<QueueT>::setThreads(const size_t pMinThreads, const size_t pMaxThreads)
{
mMinThreads = pMinThreads;
mMaxThreads = pMaxThreads;
}
template <typename QueueT> void ThreadPool<QueueT>::setQueue(const size_t pMinQueued, const size_t pMaxQueued)
{
mMinQueued = pMinQueued;
mMaxQueued = pMaxQueued;
}
template <typename QueueT> void ThreadPool<QueueT>::start()
{
mRunning = true;
mQueue.setDropSize(mMaxQueued * mMaxThreads);
Log::debug("Started thread pool %p", this);
for (unsigned i = 0; i < mMinThreads; ++i) {
newThread();
}
mManagerThread = new boost::thread(boost::bind(&ThreadPool::run, this));
}
template <typename QueueT> void ThreadPool<QueueT>::stop()
{
mRunning = false;
mQueue.stop();
if (mManagerThread) {
// TODO improve this part.
// The process can be stuck here if curl calls do not terminate
mManagerThread->join();
delete mManagerThread;
mManagerThread = NULL;
}
}
template <typename QueueT> void ThreadPool<QueueT>::push(const QueueT &pItem)
{
mQueue.push(pItem);
}
template <typename QueueT> size_t ThreadPool<QueueT>::getThreadCount()
{
return mThreads.size();
}
// Explicitly instantiate the ones we use
template class ThreadPool<boost::shared_ptr<RequestInfo>>;
template class ThreadPool<int>;
}
| 31.021164 | 118 | 0.662118 | isabella232 |
2c6336949785352075fae63e49653788b7b3047e | 964 | cpp | C++ | utils.cpp | caminek/Gilligan | c7546d647a1fa9e4add929fa813f62c227fcb600 | [
"MIT"
] | null | null | null | utils.cpp | caminek/Gilligan | c7546d647a1fa9e4add929fa813f62c227fcb600 | [
"MIT"
] | null | null | null | utils.cpp | caminek/Gilligan | c7546d647a1fa9e4add929fa813f62c227fcb600 | [
"MIT"
] | null | null | null | #include <iostream>
#include "utils.hpp"
Status status;
uint8_t Utils::rol(uint8_t nibble)
{
uint8_t retval;
bool previous_carry = status.carry_flag;
status.carry_flag = nibble >> 7;
retval = (nibble << 1) | previous_carry;
return retval;
}
uint8_t Utils::ror(uint8_t bit)
{
uint8_t retval;
bool previous_carry = status.carry_flag;
status.carry_flag = static_cast<bool>(bit & 0x01);
retval = bit >> 1;
retval = static_cast<uint8_t>(previous_carry ? retval | 0x80 : retval);
return retval;
}
uint8_t Utils::asl(uint8_t bit)
{
status.carry_flag = bit >> 7;
return bit << 1;
}
uint8_t Utils::adc(uint8_t val1, uint8_t val2)
{
uint8_t result = val1 + val2 + status.carry_flag;
if (result < val1 || result < val2)
status.carry_flag = true;
return result;
}
void Utils::output_password(const uint8_t password[])
{
for (int i = 0; i < 8; ++i)
std::cout << (int)password[i] << " ";
std::cout << std::endl;
}
| 16.338983 | 73 | 0.659751 | caminek |
2c63f1cde72b706915e05701a8f3c4a026b96846 | 861 | cpp | C++ | leetcode/72.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | leetcode/72.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | leetcode/72.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int sloveDP(string w1, string w2)
{
int w1Len = w1.size(), w2Len = w2.size();
vector<vector<int>> dp(w1Len+1, vector<int>(w2Len+1));
auto mins = [](int v1, int v2, int v3){
return min(min(v1,v2), v3);
};
for(int i = 0; i <= w1Len; i++) {
dp[i][0] = i;
}
for(int i = 0; i <= w2Len; i++) {
dp[0][i] = i;
}
for(int i = 1; i <= w1Len; i++){
for(int j = 1; j <= w2Len; j++) {
if(w1[i-1] == w2[j-1]) {
dp[i][j] = 1 + mins(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]-1);
}else{
dp[i][j] = 1 + mins(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]);
}
}
}
return dp[w1Len][w2Len];
}
int main()
{
string w1, w2;
cin >> w1 >> w2;
cout << sloveDP(w1, w2) << endl;
return 0;
}
| 23.916667 | 76 | 0.425087 | freedomDR |
2c673e1281ebca671c418f0740f114b73aeff04f | 11,214 | cpp | C++ | tests/test_matrix_traits.cpp | fancidev/euler | a74e3ddf46034718253259eac4880472c58a7b22 | [
"MIT"
] | null | null | null | tests/test_matrix_traits.cpp | fancidev/euler | a74e3ddf46034718253259eac4880472c58a7b22 | [
"MIT"
] | null | null | null | tests/test_matrix_traits.cpp | fancidev/euler | a74e3ddf46034718253259eac4880472c58a7b22 | [
"MIT"
] | null | null | null | #include <array>
#include <cstdint>
#include <type_traits>
#include <vector>
//#include "euler/matrix.hpp"
#include "euler/matrix_traits.hpp"
//#include "euler/matrix_adaptor.hpp"
#include "euler/matrix_algorithm.hpp"
#include "gtest/gtest.h"
#define MYTEST(functionName, testAspect) \
TEST(matrix ## __ ## functionName, testAspect)
MYTEST(matrix_traits, non_matrix)
{
static_assert(!euler::is_matrix_v<int>, "is_matrix_v fails");
static_assert(!euler::is_matrix_v<int[2]>, "is_matrix_v fails");
static_assert(!euler::is_matrix_v<int&>, "is_matrix_v fails");
static_assert(!euler::is_matrix_v<int&&>, "is_matrix_v fails");
static_assert(!euler::is_matrix_v<int*>, "is_matrix_v fails");
static_assert(!euler::is_matrix_v<int**>, "is_matrix_v fails");
}
MYTEST(matrix_traits, static)
{
// Test matrix traits with static c array
using type = int[3][5];
using traits = euler::matrix_traits<type>;
static_assert(
traits::rank == 2,
"matrix_traits::rank failed");
static_assert(
std::is_same<typename traits::value_type, int>::value,
"matrix_traits::value_type failed");
static_assert(
std::is_same<typename traits::reference, int&>::value,
"matrix_traits::reference failed");
static_assert(
std::is_same<typename traits::const_reference, const int&>::value,
"matrix_traits::const_reference failed");
static_assert(euler::has_static_extent<type, 0>::value,
"has_static_extent<0>::value fails");
static_assert(euler::has_static_extent<type, 1>::value,
"has_static_extent<1>::value fails");
static_assert(euler::has_static_extent_v<type, 0>,
"has_static_extent_v<0> fails");
static_assert(euler::has_static_extent_v<type, 1>,
"has_static_extent_v<1> fails");
static_assert(!euler::has_dynamic_extent<type, 0>::value,
"has_dynamic_extent<0>::value fails");
static_assert(!euler::has_dynamic_extent<type, 1>::value,
"has_dynamic_extent<1>::value fails");
static_assert(!euler::has_dynamic_extent_v<type, 0>,
"has_dynamic_extent_v<0> fails");
static_assert(!euler::has_dynamic_extent_v<type, 1>,
"has_dynamic_extent_v<1> fails");
static_assert(euler::is_matrix<type>::value,
"is_matrix::value fails");
static_assert(euler::is_matrix_v<type>,
"is_matrix_v fails");
int a[3][2] = { {1, 2}, {3, 4}, {5, 6} };
EXPECT_EQ(3, euler::matrix_traits<decltype(a)>::at(a, 1, 0));
}
MYTEST(matrix_traits, mixed)
{
// Test matrix traits for matrix with fixed number of columns but variable
// number of rows.
using type = std::vector<std::array<int, 2>>;
using traits = euler::matrix_traits<type>;
static_assert(
traits::rank == 2,
"matrix_traits::rank failed");
static_assert(
std::is_same<typename traits::value_type, int>::value,
"matrix_traits::value_type failed");
static_assert(
std::is_same<typename traits::reference, int&>::value,
"matrix_traits::reference failed");
static_assert(
std::is_same<typename traits::const_reference, const int&>::value,
"matrix_traits::const_reference failed");
static_assert(!euler::has_static_extent<type, 0>::value,
"has_static_extent<0>::value fails");
static_assert(euler::has_static_extent<type, 1>::value,
"has_static_extent<1>::value fails");
static_assert(!euler::has_static_extent_v<type, 0>,
"has_static_extent_v<0> fails");
static_assert(euler::has_static_extent_v<type, 1>,
"has_static_extent_v<1> fails");
static_assert(euler::has_dynamic_extent<type, 0>::value,
"has_dynamic_extent<0>::value fails");
static_assert(!euler::has_dynamic_extent<type, 1>::value,
"has_dynamic_extent<1>::value fails");
static_assert(euler::has_dynamic_extent_v<type, 0>,
"has_dynamic_extent_v<0> fails");
static_assert(!euler::has_dynamic_extent_v<type, 1>,
"has_dynamic_extent_v<1> fails");
static_assert(euler::is_matrix<type>::value,
"is_matrix::value fails");
static_assert(euler::is_matrix_v<type>,
"is_matrix_v fails");
type a{ {1, 2}, {3, 4}, {5, 6} };
EXPECT_EQ(3, euler::matrix_traits<decltype(a)>::at(a, 1, 0));
}
MYTEST(extent, static)
{
// Static matrix
int a[3][2] = { {1, 2}, {3, 4}, {5, 6} };
EXPECT_EQ(3, euler::extent<0>(a));
EXPECT_EQ(2, euler::extent<1>(a));
}
MYTEST(extent, mixed)
{
// Matrix with fixed number of columns but variable number of rows.
std::vector<std::array<int, 2>> a;
EXPECT_EQ(0, euler::extent<0>(a));
EXPECT_EQ(2, euler::extent<1>(a));
a.push_back(std::array<int, 2>{1, 2});
EXPECT_EQ(1, euler::extent<0>(a));
EXPECT_EQ(2, euler::extent<1>(a));
}
#if 0
TEST(matrix, common_extent)
{
int A[3][2] = { {1, 2}, {3, 4}, {5, 6} };
int B[3][2] = { {1, 2}, {3, 4}, {5, 6} };
EXPECT_EQ(3u, euler::common_extent<0>(A, B));
EXPECT_EQ(2u, euler::common_extent<1>(A, B));
EXPECT_EQ(0u, euler::common_extent<2>(A, B));
const int C[1][2] { };
EXPECT_EQ(0u, euler::common_extent<0>(A, C));
EXPECT_EQ(2u, euler::common_extent<1>(B, C));
EXPECT_EQ(0u, euler::common_extent<2>(A, C));
}
#endif
MYTEST(diagonal_matrix, static)
{
auto a = euler::diagonal_matrix(2, 5);
static_assert(euler::is_matrix_v<decltype(a)>, "type mismatch");
EXPECT_EQ(2, euler::extent<0>(a));
EXPECT_EQ(2, euler::extent<1>(a));
EXPECT_EQ(5, euler::mat(a, 0, 0));
EXPECT_EQ(0, euler::mat(a, 0, 1));
EXPECT_EQ(0, euler::mat(a, 1, 0));
EXPECT_EQ(5, euler::mat(a, 1, 1));
}
MYTEST(msum, nonempty)
{
int a[3][2] = { {1, 2}, {3, 4}, {5, 6} };
EXPECT_EQ(21, euler::msum(a));
}
MYTEST(msum, empty)
{
std::vector<std::array<int, 5>> a;
EXPECT_EQ(0, euler::msum(a));
EXPECT_EQ(5, euler::msum(5, a));
}
#if 0
TEST(matrix, meq)
{
const int A[3][2] = { {1, 2}, {3, 4}, {5, 6} };
const int B[3][2] = { {1, 2}, {3, 4}, {5, 6} };
EXPECT_EQ(true, euler::mall(euler::meq(A, B)));
}
TEST(matrix, madd)
{
const int A[3][2] = { {1, 2}, {3, 4}, {5, 6} };
const int B[3][2] = { {7, 8}, {9, 0}, {3, 5} };
int A_add_B[3][2] = { {8, 10}, {12, 4}, {8, 11} };
EXPECT_EQ(true, euler::mall(euler::meq(A_add_B, euler::madd(A, B))));
}
TEST(matrix, msub)
{
const int A[3][2] = { {1, 2}, {3, 4}, {5, 6} };
const int B[3][2] = { {7, 8}, {9, 0}, {3, 5} };
int A_sub_B[3][2] = { {-6, -6}, {-6, 4}, {2, 1} };
EXPECT_EQ(true, euler::mall(euler::meq(A_sub_B, euler::msub(A, B))));
}
MYTEST(make_lazy_vector, basic)
{
// basic usage
auto v = euler::make_lazy_vector(3, [](size_t i) { return i; });
EXPECT_EQ(0, v[0]);
EXPECT_EQ(1, v[1]);
EXPECT_EQ(2, v[2]);
}
MYTEST(make_lazy_vector, mutable)
{
// elements in lazy vector are mutable if functor returns mutable object
int a[3] = { 1, 2, 3 };
auto v = euler::make_lazy_vector(3, [&a](size_t i) -> int&
{
return a[i];
});
v[1] = 4;
EXPECT_EQ(1, v[0]);
EXPECT_EQ(4, v[1]);
EXPECT_EQ(3, v[2]);
}
MYTEST(make_lazy_vector, void)
{
// functor may return void
int a[3] = { 1, 2, 3 };
auto v = euler::make_lazy_vector(3, [&a](size_t i) { ++a[i]; });
static_assert(std::is_same<void, decltype(v[0])>::value, "");
v[1];
v[1];
EXPECT_EQ(1, a[0]);
EXPECT_EQ(4, a[1]);
EXPECT_EQ(3, a[2]);
}
MYTEST(make_lazy_vector, cv_irrelevant_for_lambda)
{
// cv-qualifier of vector does not propagate to lambda
int a[3] = { 1, 2, 3 };
const auto &v = euler::make_lazy_vector(3, [&a](size_t i) -> int&
{
return a[i];
});
v[1] = 4;
EXPECT_EQ(1, v[0]);
EXPECT_EQ(4, v[1]);
EXPECT_EQ(3, v[2]);
}
MYTEST(make_lazy_vector, cv_irrelevant_for_functor)
{
// cv-qualifier of vector does not propagate to functor
struct C
{
int *a;
double *b;
int &operator()(size_t i) { return a[i]; }
double &operator()(size_t i) const { return b[i]; }
};
int a[3] = { 1, 2, 3 };
double b[3] = { 1.25, 3.75, 5.50 };
auto v1 = euler::make_lazy_vector(3, C{a, b});
v1[2] *= 6;
EXPECT_EQ(18, a[2]);
EXPECT_EQ(5.50, b[2]);
const auto &v2 = euler::make_lazy_vector(3, C{a, b});
v2[1] *= 2;
EXPECT_EQ(4, a[1]);
EXPECT_EQ(3.75, b[1]);
}
MYTEST(make_lazy_vector, cv_irrelevant_for_reference)
{
// cv-qualifier of vector is not propagated to reference of functor
struct C
{
int *a;
double *b;
int &operator()(size_t i) { return a[i]; }
double &operator()(size_t i) const { return b[i]; }
};
int a[4] = { 1, 2, 3, 4 };
double b[4] = { 1.25, 3.75, 5.50, 8.125 };
C c{a, b};
auto v1 = euler::make_lazy_vector<C&>(4, c);
v1[2] *= 6;
EXPECT_EQ(18, a[2]);
EXPECT_EQ(5.50, b[2]);
const auto &v2 = euler::make_lazy_vector<C&>(4, c);
v2[1] *= 2;
EXPECT_EQ(4, a[1]);
EXPECT_EQ(3.75, b[1]);
auto v3 = euler::make_lazy_vector<const C &>(4, c);
v3[3] *= 7;
EXPECT_EQ(4, a[3]);
EXPECT_EQ(8.125*7, b[3]);
const auto &v4 = euler::make_lazy_vector<const C &>(4, c);
v4[0] *= 11;
EXPECT_EQ(1, a[0]);
EXPECT_EQ(1.25*11, b[0]);
}
MYTEST(make_lazy_vector, reference)
{
// functor may be stored by reference (already implicitly tested above)
struct C
{
explicit C(int k) : k(k) { }
C(const C &) = delete;
C(C&&) = delete;
int operator()(size_t i) { return i * k; }
private:
int k;
};
C c(3);
auto v = euler::make_lazy_vector(100, c);
EXPECT_EQ(15, v[5]);
}
MYTEST(make_lazy_matrix, basic)
{
// basic usage of lazy matrix
auto a = euler::make_lazy_matrix(2, 3, std::plus<size_t>());
EXPECT_EQ(0, a[0][0]);
EXPECT_EQ(1, a[0][1]);
EXPECT_EQ(2, a[0][2]);
EXPECT_EQ(1, a[1][0]);
EXPECT_EQ(2, a[1][1]);
EXPECT_EQ(3, a[1][2]);
}
MYTEST(make_lazy_matrix, mutable)
{
// matrix elements are mutable if functor returns mutable object
int a[2][3] = { {10, 20, 30}, {40, 50, 60} };
auto v = euler::make_lazy_matrix(2, 3, [&a](size_t i, size_t j) -> int&
{
return a[i][j];
});
v[1][2] /= 5;
EXPECT_EQ(50, v[1][1]);
EXPECT_EQ(12, v[1][2]);
}
MYTEST(make_lazy_matrix, cv_irrelevant_for_lambda)
{
// cv-qualifier of matrix does not propagate to lambda
int a[2][3] = { {10, 20, 30}, {40, 50, 60} };
const auto &v = euler::make_lazy_matrix(2, 3,
[&a](size_t i, size_t j) -> int&
{
return a[i][j];
});
v[1][2] /= 5;
EXPECT_EQ(50, a[1][1]);
EXPECT_EQ(12, a[1][2]);
}
MYTEST(make_lazy_matrix, cv_irrelevant_for_functor)
{
// cv-qualifier of matrix does not propagate to functor
int a[5] = { 1, 2, 3, 4, 5 };
double b[5] = { 1.25, 3.75, 5.50, 8.125, 2.00 };
struct C
{
int *a;
double *b;
int &operator()(size_t i, size_t j) { return a[i + j]; }
double &operator()(size_t i, size_t j) const { return b[i + j]; }
};
auto v1 = euler::make_lazy_matrix(3, 3, C{a, b});
v1[2][1] *= 6;
EXPECT_EQ(24, a[3]);
EXPECT_EQ(8.125, b[3]);
const auto &v2 = euler::make_lazy_matrix(3, 3, C{a, b});
v2[2][2] *= 2;
EXPECT_EQ(10, a[4]);
EXPECT_EQ(2.0, b[4]);
}
MYTEST(make_lazy_matrix, reference)
{
// functor may be stored by reference (already implicitly tested above)
struct C
{
explicit C(int k) : k(k) { }
C(const C &) = delete;
C(C&&) = delete;
int operator()(size_t i) { return i * k; }
private:
int k;
};
C c(3);
auto v = euler::make_lazy_vector(100, c);
EXPECT_EQ(15, v[5]);
}
#endif
| 25.958333 | 76 | 0.618423 | fancidev |
ef1ad2b46e0fa27ba7309124db2bd4a4e43a5c38 | 756 | cc | C++ | tests/CompileTests/ElsaTestCases/t0502.cc | maurizioabba/rose | 7597292cf14da292bdb9a4ef573001b6c5b9b6c0 | [
"BSD-3-Clause"
] | 488 | 2015-01-09T08:54:48.000Z | 2022-03-30T07:15:46.000Z | tests/CompileTests/ElsaTestCases/t0502.cc | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | 174 | 2015-01-28T18:41:32.000Z | 2022-03-31T16:51:05.000Z | tests/CompileTests/ElsaTestCases/t0502.cc | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | 146 | 2015-04-27T02:48:34.000Z | 2022-03-04T07:32:53.000Z | // t0502.cc
// invoke method on non-dependent class with dependent base
template <class T>
struct A {
struct B : T {};
void f()
{
B b;
b.foo();
};
};
struct C {
void foo();
};
void f()
{
A<C> a;
a.f();
}
// ---------------
// in contrast, this would be error; gcc diagnoses, icc does not
template <class T>
struct D {
void f()
{
C c; // C has no dependent bases
//ERROR(1): c.bar(); // and no method 'bar'
};
};
// there is an intermediate variant where C is a nested class but
// still has no dependent bases; since gcc does not diagnose that
// case, I am not going to add a test requiring that Elsa diagnose it,
// even though right now it does (the standard allows both behaviors)
| 17.581395 | 70 | 0.59127 | maurizioabba |
ef1bb44fb921624b5cf6e776d8e9051d5afe4df9 | 3,845 | hpp | C++ | include/stl2/detail/concepts/object.hpp | marehr/cmcstl2 | 7a7cae1e23beacb18fd786240baef4ae121d813f | [
"MIT"
] | null | null | null | include/stl2/detail/concepts/object.hpp | marehr/cmcstl2 | 7a7cae1e23beacb18fd786240baef4ae121d813f | [
"MIT"
] | null | null | null | include/stl2/detail/concepts/object.hpp | marehr/cmcstl2 | 7a7cae1e23beacb18fd786240baef4ae121d813f | [
"MIT"
] | null | null | null | // cmcstl2 - A concept-enabled C++ standard library
//
// Copyright Casey Carter 2015
// Copyright Eric Niebler 2015
//
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/caseycarter/cmcstl2
//
#ifndef STL2_DETAIL_CONCEPTS_OBJECT_HPP
#define STL2_DETAIL_CONCEPTS_OBJECT_HPP
#include <stl2/detail/fwd.hpp>
#include <stl2/detail/meta.hpp>
#include <stl2/detail/concepts/core.hpp>
#include <stl2/detail/concepts/object/assignable.hpp>
#include <stl2/detail/concepts/object/regular.hpp>
STL2_OPEN_NAMESPACE {
///////////////////////////////////////////////////////////////////////////
// __f [Implementation detail, at least for now]
//
// Utility alias that simplifies the specification of forwarding functions
// whose target will eventually accept a parameter by value. E.g., the
// range overload of find:
//
// template<InputRange Rng, class T, class Proj = identity>
// requires IndirectRelation<equal_to<>,
// projected<iterator_t<Rng>, Proj>, const T*>()
// safe_iterator_t<Rng>
// find(Rng&& rng, const T& value, Proj proj = Proj{});
//
// can be implemented to perfect-forward to the iterator overload as:
//
// template<InputRange Rng, class T, class Proj = identity>
// requires IndirectRelation<equal_to<>,
// projected<iterator_t<Rng>, __f<Proj>>, // NW: __f<Proj>
// const T*>()
// safe_iterator_t<Rng>
// find(Rng&& rng, const T& value, Proj&& proj = Proj{}) {
// return find(begin(rng), end(rng), value, forward<Proj>(proj));
// }
//
// __f<Proj> is an alias for the decayed type that will eventually
// be used in the target function, and its constraints ensure that
// the decayed type can in fact be constructed from the actual type.
//
template<class T>
requires Constructible<decay_t<T>, T>
using __f = decay_t<T>;
namespace ext {
///////////////////////////////////////////////////////////////////////////
// 'structible object concepts
//
template<class T>
concept bool DestructibleObject = Object<T> && Destructible<T>;
template<class T, class... Args>
concept bool ConstructibleObject = Object<T> && Constructible<T, Args...>;
template<class T>
concept bool DefaultConstructibleObject = Object<T> && DefaultConstructible<T>;
template<class T>
concept bool MoveConstructibleObject = Object<T> && MoveConstructible<T>;
template<class T>
concept bool CopyConstructibleObject = Object<T> && CopyConstructible<T>;
///////////////////////////////////////////////////////////////////////////
// TriviallyFoo concepts
//
template<class T>
concept bool TriviallyDestructible =
Destructible<T> && _Is<T, is_trivially_destructible>;
template<class T, class... Args>
concept bool TriviallyConstructible =
Constructible<T, Args...> &&
_Is<T, is_trivially_constructible, Args...>;
template<class T>
concept bool TriviallyDefaultConstructible =
DefaultConstructible<T> &&
_Is<T, is_trivially_default_constructible>;
template<class T>
concept bool TriviallyMoveConstructible =
MoveConstructible<T> && _Is<T, is_trivially_move_constructible>;
template<class T>
concept bool TriviallyCopyConstructible =
CopyConstructible<T> &&
TriviallyMoveConstructible<T> &&
_Is<T, is_trivially_copy_constructible>;
template<class T>
concept bool TriviallyMovable =
Movable<T> &&
TriviallyMoveConstructible<T> &&
_Is<T, is_trivially_move_assignable>;
template<class T>
concept bool TriviallyCopyable =
Copyable<T> &&
TriviallyMovable<T> &&
TriviallyCopyConstructible<T> &&
_Is<T, is_trivially_copy_assignable>;
}
} STL2_CLOSE_NAMESPACE
#endif
| 32.863248 | 81 | 0.668661 | marehr |
ef1d20dd2d6215d9a198a449b4827b7db8ad6224 | 31,091 | cpp | C++ | circe/gl/graphics/ibl.cpp | gui-works/circe | c126a8f9521dca1eb23ac47c8f2e8081f2102f17 | [
"MIT"
] | 1 | 2021-09-17T18:12:47.000Z | 2021-09-17T18:12:47.000Z | circe/gl/graphics/ibl.cpp | gui-works/circe | c126a8f9521dca1eb23ac47c8f2e8081f2102f17 | [
"MIT"
] | null | null | null | circe/gl/graphics/ibl.cpp | gui-works/circe | c126a8f9521dca1eb23ac47c8f2e8081f2102f17 | [
"MIT"
] | 2 | 2021-09-17T18:13:02.000Z | 2021-09-17T18:16:21.000Z | /// Copyright (c) 2021, FilipeCN.
///
/// The MIT License (MIT)
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to
/// deal in the Software without restriction, including without limitation the
/// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
/// sell copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
/// IN THE SOFTWARE.
///
///\file irradiance_map.cpp.c
///\author FilipeCN (filipedecn@gmail.com)
///\date 2021-05-16
///
///\brief
#include "ibl.h"
#include <circe/gl/io/framebuffer.h>
#include <circe/gl/scene/scene_model.h>
#include <circe/gl/graphics/shader.h>
#include <circe/scene/shapes.h>
namespace circe::gl {
void renderToCube(Framebuffer &framebuffer,
Program &program,
const Texture &envmap,
Texture &cubemap,
GLint mip_level,
const hermes::size2 &resolution) {
SceneModel cube;
cube = circe::Shapes::box({{-1, -1, -1}, {1, 1, 1}});
auto projection = hermes::Transform::perspective(90, 1, 0.1, 10);
hermes::Transform views[] = {
hermes::Transform::lookAt({}, {1, 0, 0}, {0, -1, 0}),
hermes::Transform::lookAt({}, {-1, 0, 0}, {0, -1, 0}),
hermes::Transform::lookAt({}, {0, 1, 0}, {0, 0, -1}),
hermes::Transform::lookAt({}, {0, -1, 0}, {0, 0, 1}),
hermes::Transform::lookAt({}, {0, 0, -1}, {0, -1, 0}),
hermes::Transform::lookAt({}, {0, 0, 1}, {0, -1, 0}),
};
framebuffer.resize(resolution);
framebuffer.enable();
glViewport(0, 0, resolution.width, resolution.height);
envmap.bind(GL_TEXTURE0);
program.use();
program.setUniform("environmentMap", 0);
program.setUniform("projection", projection);
for (u32 i = 0; i < 6; ++i) {
program.setUniform("view", views[i]);
framebuffer.attachColorBuffer(cubemap.textureObjectId(),
GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
GL_COLOR_ATTACHMENT0,
mip_level);
framebuffer.enable();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
cube.draw();
}
Framebuffer::disable();
}
Texture IBL::irradianceMap(const Texture &texture, const hermes::size2 &resolution) {
Texture imap;
std::string vs = "#version 330 core \n"
"layout (location = 0) in vec3 aPos; \n"
"out vec3 localPos; \n"
"uniform mat4 projection; \n"
"uniform mat4 view; \n"
"void main() { \n"
" localPos = aPos; \n"
" gl_Position = projection * view * vec4(localPos, 1.0); \n"
"}";
std::string fs = "#version 330 core \n"
"out vec4 FragColor; \n"
"in vec3 localPos; \n"
"uniform samplerCube environmentMap; \n"
"const float PI = 3.14159265359; \n"
"void main(){ \n"
" // the sample direction equals the hemisphere's orientation \n"
" vec3 N = normalize(localPos); \n"
"vec3 irradiance = vec3(0.0); \n"
"vec3 up = vec3(0.0, 1.0, 0.0); \n"
"vec3 right = normalize(cross(up, N)); \n"
"up = normalize(cross(N, right)); \n"
"float sampleDelta = 0.025; \n"
"float nrSamples = 0.0; \n"
"for(float phi = 0.0; phi < 2.0 * PI; phi += sampleDelta) { \n"
" for(float theta = 0.0; theta < 0.5 * PI; theta += sampleDelta) { \n"
" // spherical to cartesian (in tangent space) \n"
" vec3 tangentSample = vec3(sin(theta) * cos(phi), sin(theta) * sin(phi), cos(theta)); \n"
" // tangent space to world \n"
" vec3 sampleVec = tangentSample.x * right + tangentSample.y * up + tangentSample.z * N; \n"
" irradiance += texture(environmentMap, sampleVec).rgb * cos(theta) * sin(theta); \n"
" nrSamples++; \n"
" } \n"
"} \n"
"irradiance = PI * irradiance * (1.0 / float(nrSamples)); \n"
" FragColor = vec4(irradiance, 1.0); \n"
"}";
Program program;
program.attach(Shader(GL_VERTEX_SHADER, vs));
program.attach(Shader(GL_FRAGMENT_SHADER, fs));
if (!program.link())
std::cerr << "failed to compile irradiance map shader!\n" << program.err << std::endl;
// copy attributes
imap.setTarget(texture.target());
imap.setInternalFormat(texture.internalFormat());
imap.setFormat(texture.format());
imap.setType(texture.type());
imap.resize(resolution);
imap.bind();
Texture::View(GL_TEXTURE_CUBE_MAP).apply();
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
Framebuffer frambuffer;
frambuffer.setRenderBufferStorageInternalFormat(GL_DEPTH_COMPONENT24);
renderToCube(frambuffer, program, texture, imap, 0, resolution);
return imap;
}
Texture IBL::preFilteredEnvironmentMap(const Texture &input, const hermes::size2 &resolution) {
////////////////////////////////////// prepare texture //////////////////////////////////////////
Texture prefilter_map;
prefilter_map.setTarget(GL_TEXTURE_CUBE_MAP);
prefilter_map.setInternalFormat(input.internalFormat());
prefilter_map.setFormat(input.format());
prefilter_map.setType(input.type());
prefilter_map.resize(resolution);
prefilter_map.bind();
Texture::View view(GL_TEXTURE_CUBE_MAP);
view[GL_TEXTURE_MIN_FILTER] = GL_LINEAR_MIPMAP_LINEAR;
view.apply();
prefilter_map.generateMipmap();
prefilter_map.bind();
////////////////////////////////////// prepare shader //////////////////////////////////////////
std::string vs = "#version 330 core \n"
"layout (location = 0) in vec3 aPos; \n"
"out vec3 localPos; \n"
"uniform mat4 projection; \n"
"uniform mat4 view; \n"
"void main() { \n"
" localPos = aPos; \n"
" gl_Position = projection * view * vec4(localPos, 1.0); \n"
"}";
std::string fs = "#version 330 core \n"
"out vec4 FragColor; \n"
"in vec3 localPos; \n"
"uniform samplerCube environmentMap; \n"
"uniform float roughness; \n"
"const float PI = 3.14159265359; \n"
"float DistributionGGX(vec3 N, vec3 H, float roughness) { \n"
" float a = roughness*roughness; \n"
" float a2 = a*a; \n"
" float NdotH = max(dot(N, H), 0.0); \n"
" float NdotH2 = NdotH*NdotH; \n"
" float nom = a2; \n"
" float denom = (NdotH2 * (a2 - 1.0) + 1.0); \n"
" denom = PI * denom * denom; \n"
" return nom / denom; \n"
"} \n"
"float RadicalInverse_VdC(uint bits) { \n"
" bits = (bits << 16u) | (bits >> 16u); \n"
" bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); \n"
" bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); \n"
" bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); \n"
" bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); \n"
" return float(bits) * 2.3283064365386963e-10; // / 0x100000000 \n"
"} \n"
"vec2 Hammersley(uint i, uint N) { \n"
" return vec2(float(i)/float(N), RadicalInverse_VdC(i)); \n"
"} \n"
"vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness) { \n"
" float a = roughness*roughness; \n"
" float phi = 2.0 * PI * Xi.x; \n"
" float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (a*a - 1.0) * Xi.y)); \n"
" float sinTheta = sqrt(1.0 - cosTheta*cosTheta); \n"
" // from spherical coordinates to cartesian coordinates \n"
" vec3 H; \n"
" H.x = cos(phi) * sinTheta; \n"
" H.y = sin(phi) * sinTheta; \n"
" H.z = cosTheta; \n"
" // from tangent-space vector to world-space sample vector \n"
" vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); \n"
" vec3 tangent = normalize(cross(up, N)); \n"
" vec3 bitangent = cross(N, tangent); \n"
" vec3 sampleVec = tangent * H.x + bitangent * H.y + N * H.z; \n"
" return normalize(sampleVec); \n"
"} \n"
"void main() { \n"
" vec3 N = normalize(localPos); \n"
" vec3 R = N; \n"
" vec3 V = R; \n"
" const uint SAMPLE_COUNT = 1024u; \n"
" float totalWeight = 0.0; \n"
" vec3 prefilteredColor = vec3(0.0); \n"
" for(uint i = 0u; i < SAMPLE_COUNT; ++i) { \n"
" vec2 Xi = Hammersley(i, SAMPLE_COUNT); \n"
" vec3 H = ImportanceSampleGGX(Xi, N, roughness); \n"
" vec3 L = normalize(2.0 * dot(V, H) * H - V); \n"
" float NdotL = max(dot(N, L), 0.0); \n"
" if(NdotL > 0.0) { \n"
" // sample from the environment's mip level based on roughness/pdf \n"
" float D = DistributionGGX(N, H, roughness); \n"
" float NdotH = max(dot(N, H), 0.0); \n"
" float HdotV = max(dot(H, V), 0.0); \n"
" float pdf = D * NdotH / (4.0 * HdotV) + 0.0001; \n"
" float resolution = 512.0; // resolution of source cubemap (per face) \n"
" float saTexel = 4.0 * PI / (6.0 * resolution * resolution); \n"
" float saSample = 1.0 / (float(SAMPLE_COUNT) * pdf + 0.0001); \n"
" float mipLevel = roughness == 0.0 ? 0.0 : 0.5 * log2(saSample / saTexel); \n"
" prefilteredColor += textureLod(environmentMap, L, mipLevel).rgb * NdotL; \n"
" totalWeight += NdotL; \n"
" } \n"
" } \n"
" prefilteredColor = prefilteredColor / totalWeight; \n"
" FragColor = vec4(prefilteredColor, 1.0); \n"
"}";
Program program;
program.attach(Shader(GL_VERTEX_SHADER, vs));
program.attach(Shader(GL_FRAGMENT_SHADER, fs));
if (!program.link())
std::cerr << "failed to compile IBL::prefilter map shader!\n" << program.err << std::endl;
////////////////////////////////////// prepare shader //////////////////////////////////////////
Framebuffer framebuffer;
framebuffer.setRenderBufferStorageInternalFormat(GL_DEPTH_COMPONENT24);
////////////////////////////////////// filter /////////////////////////////////////////////////
glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
unsigned int max_mip_levels = 5;
for (unsigned int mip = 0; mip < max_mip_levels; ++mip) {
u32 mip_width = 128 * std::pow(0.5, mip);
u32 mip_height = 128 * std::pow(0.5, mip);
f32 roughness = (float) mip / (float) (max_mip_levels - 1);
program.use();
program.setUniform("roughness", roughness);
renderToCube(framebuffer, program, input, prefilter_map, mip, {mip_width, mip_height});
}
return prefilter_map;
}
Texture IBL::brdfIntegrationMap(const hermes::size2 &resolution) {
////////////////////////////////////// prepare shader //////////////////////////////////////////
std::string vs = "#version 330 core \n"
"layout (location = 0) in vec3 aPos; \n"
"layout (location = 1) in vec2 aTexCoords; \n"
"out vec2 TexCoords; \n"
"void main() { \n"
" TexCoords = aTexCoords; \n"
" gl_Position = vec4(aPos, 1.0); \n"
"}";
std::string fs = "#version 330 core \n"
"out vec2 FragColor; \n"
"in vec2 TexCoords; \n"
"const float PI = 3.14159265359; \n"
"float RadicalInverse_VdC(uint bits) { \n"
" bits = (bits << 16u) | (bits >> 16u); \n"
" bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); \n"
" bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); \n"
" bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); \n"
" bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); \n"
" return float(bits) * 2.3283064365386963e-10; // / 0x100000000 \n"
"} \n"
"vec2 Hammersley(uint i, uint N) { \n"
" return vec2(float(i)/float(N), RadicalInverse_VdC(i)); \n"
"} \n"
"vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness) { \n"
" float a = roughness*roughness; \n"
" float phi = 2.0 * PI * Xi.x; \n"
" float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (a*a - 1.0) * Xi.y)); \n"
" float sinTheta = sqrt(1.0 - cosTheta*cosTheta); \n"
" // from spherical coordinates to cartesian coordinates \n"
" vec3 H; \n"
" H.x = cos(phi) * sinTheta; \n"
" H.y = sin(phi) * sinTheta; \n"
" H.z = cosTheta; \n"
" // from tangent-space vector to world-space sample vector \n"
" vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); \n"
" vec3 tangent = normalize(cross(up, N)); \n"
" vec3 bitangent = cross(N, tangent); \n"
" vec3 sampleVec = tangent * H.x + bitangent * H.y + N * H.z; \n"
" return normalize(sampleVec); \n"
"} \n"
"float GeometrySchlickGGX(float NdotV, float roughness) { \n"
" // note that we use a different k for IBL \n"
" float a = roughness; \n"
" float k = (a * a) / 2.0; \n"
" float nom = NdotV; \n"
" float denom = NdotV * (1.0 - k) + k; \n"
" return nom / denom; \n"
"} \n"
"float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness) { \n"
" float NdotV = max(dot(N, V), 0.0); \n"
" float NdotL = max(dot(N, L), 0.0); \n"
" float ggx2 = GeometrySchlickGGX(NdotV, roughness); \n"
" float ggx1 = GeometrySchlickGGX(NdotL, roughness); \n"
" return ggx1 * ggx2; \n"
"} \n"
"vec2 IntegrateBRDF(float NdotV, float roughness) { \n"
" vec3 V; \n"
" V.x = sqrt(1.0 - NdotV*NdotV); \n"
" V.y = 0.0; \n"
" V.z = NdotV; \n"
" float A = 0.0; \n"
" float B = 0.0; \n"
" vec3 N = vec3(0.0, 0.0, 1.0); \n"
" const uint SAMPLE_COUNT = 1024u; \n"
" for(uint i = 0u; i < SAMPLE_COUNT; ++i) { \n"
" // generates a sample vector that's biased towards the \n"
" // preferred alignment direction (importance sampling). \n"
" vec2 Xi = Hammersley(i, SAMPLE_COUNT); \n"
" vec3 H = ImportanceSampleGGX(Xi, N, roughness); \n"
" vec3 L = normalize(2.0 * dot(V, H) * H - V); \n"
" float NdotL = max(L.z, 0.0); \n"
" float NdotH = max(H.z, 0.0); \n"
" float VdotH = max(dot(V, H), 0.0); \n"
" if(NdotL > 0.0) { \n"
" float G = GeometrySmith(N, V, L, roughness); \n"
" float G_Vis = (G * VdotH) / (NdotH * NdotV); \n"
" float Fc = pow(1.0 - VdotH, 5.0); \n"
" A += (1.0 - Fc) * G_Vis; \n"
" B += Fc * G_Vis; \n"
" } \n"
" } \n"
" A /= float(SAMPLE_COUNT); \n"
" B /= float(SAMPLE_COUNT); \n"
" return vec2(A, B); \n"
"} \n"
"void main() { \n"
" vec2 integratedBRDF = IntegrateBRDF(TexCoords.x, TexCoords.y); \n"
" FragColor = integratedBRDF; \n"
"}";
Program program;
program.attach(Shader(GL_VERTEX_SHADER, vs));
program.attach(Shader(GL_FRAGMENT_SHADER, fs));
if (!program.link())
std::cerr << "failed to compile IBL::brdfIntegration map shader!\n" << program.err << std::endl;
////////////////////////////////////// prepare texture //////////////////////////////////////////
Texture brdf_i_map;
brdf_i_map.setTarget(GL_TEXTURE_2D);
brdf_i_map.setInternalFormat(GL_RG16F);
brdf_i_map.setFormat(GL_RG);
brdf_i_map.setType(GL_FLOAT);
brdf_i_map.resize(resolution);
brdf_i_map.bind();
Texture::View().apply();
////////////////////////////////////// generate texture /////////////////////////////////////////
SceneModel quad;
quad = Shapes::box({{-1, -1}, {1, 1}}, shape_options::uv);
program.use();
Framebuffer framebuffer;
framebuffer.setRenderBufferStorageInternalFormat(GL_DEPTH_COMPONENT24);
framebuffer.resize(resolution);
glViewport(0, 0, resolution.width, resolution.height);
framebuffer.attachTexture(brdf_i_map);
framebuffer.enable();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
quad.draw();
return brdf_i_map;
}
}
| 81.603675 | 119 | 0.298511 | gui-works |
ef1fc4f106139ad96d30385eb27447b40fdc5987 | 7,026 | cxx | C++ | source/boomhs/ui_debug.cxx | bjadamson/BoomHS | 60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4 | [
"MIT"
] | 2 | 2016-07-22T10:09:21.000Z | 2017-09-16T06:50:01.000Z | source/boomhs/ui_debug.cxx | bjadamson/BoomHS | 60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4 | [
"MIT"
] | 14 | 2016-08-13T22:45:56.000Z | 2018-12-16T03:56:36.000Z | source/boomhs/ui_debug.cxx | bjadamson/BoomHS | 60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4 | [
"MIT"
] | null | null | null | #include <boomhs/bounding_object.hpp>
#include <boomhs/camera.hpp>
#include <boomhs/components.hpp>
#include <boomhs/engine.hpp>
#include <boomhs/entity.hpp>
#include <boomhs/frame_time.hpp>
#include <boomhs/level_manager.hpp>
#include <boomhs/player.hpp>
#include <boomhs/tree.hpp>
#include <boomhs/view_frustum.hpp>
#include <extlibs/fmt.hpp>
#include <extlibs/glm.hpp>
#include <extlibs/imgui.hpp>
using namespace boomhs;
using namespace opengl;
using namespace gl_sdl;
namespace
{
void
draw_entity_editor(char const* prefix, int const window_flags, EngineState& es, LevelManager& lm,
EntityRegistry& registry, Camera& camera, glm::mat4 const& view_mat,
glm::mat4 const& proj_mat)
{
auto& logger = es.logger;
auto& zs = lm.active();
auto& gfx_state = zs.gfx_state;
auto& draw_handles = gfx_state.draw_handles;
auto& sps = gfx_state.sps;
auto& uistate = es.ui_state.debug;
auto const draw = [&]() {
std::optional<EntityID> selected;
for (auto const eid : find_all_entities_with_component<Selectable>(registry)) {
auto const& sel = registry.get<Selectable>(eid);
if (sel.selected) {
selected = eid;
break;
}
}
std::string const eid_str = selected ? std::to_string(*selected) : "none";
ImGui::Text("eid: %s", eid_str.c_str());
if (!selected) {
return;
}
ImGui::Checkbox("Lock Selected", &uistate.lock_debugselected);
auto const eid = *selected;
{
auto& isr = registry.get<IsRenderable>(eid).hidden;
ImGui::Checkbox("Hidden From Rendering", &isr);
}
if (registry.has<AABoundingBox>(eid) && registry.has<Transform>(eid)) {
auto const& tr = registry.get<Transform>(eid);
auto const& bbox = registry.get<AABoundingBox>(eid);
// TODO: view/proj matrix
bool const bbox_inside = ViewFrustum::bbox_inside(view_mat, proj_mat, tr, bbox);
std::string const msg = fmt::sprintf("In ViewFrustum: %i", bbox_inside);
ImGui::Text("%s", msg.c_str());
}
if (ImGui::Button("Inhabit Selected")) {
auto& transform = registry.get<Transform>(eid);
// camera.set_target(transform);
}
if (registry.has<Name>(eid)) {
auto& name = registry.get<Name>(eid).value;
char buffer[128] = {'0'};
FOR(i, name.size()) { buffer[i] = name[i]; }
ImGui::InputText(name.c_str(), buffer, IM_ARRAYSIZE(buffer));
}
if (registry.has<AABoundingBox>(eid)) {
if (ImGui::CollapsingHeader("BoundingBox Editor")) {
auto const& bbox = registry.get<AABoundingBox>(eid).cube;
ImGui::Text("min: %s", glm::to_string(bbox.min).c_str());
ImGui::Text("max: %s", glm::to_string(bbox.max).c_str());
}
}
if (ImGui::CollapsingHeader("Transform Editor")) {
auto& transform = registry.get<Transform>(eid);
ImGui::InputFloat3("pos:", glm::value_ptr(transform.translation));
{
glm::vec3 buffer = transform.get_rotation_degrees();
if (ImGui::InputFloat3("quat rot:", glm::value_ptr(buffer))) {
transform.rotation = glm::quat{glm::radians(buffer)};
}
ImGui::Text("euler rot:%s", glm::to_string(transform.get_rotation_degrees()).c_str());
}
ImGui::InputFloat3("scale:", glm::value_ptr(transform.scale));
}
if (registry.has<TreeComponent>(eid) && ImGui::CollapsingHeader("Tree Editor")) {
auto const make_str = [](char const* text, auto const num) {
return text + std::to_string(num);
};
auto& tc = registry.get<TreeComponent>(eid);
auto const edit_treecolor = [&](char const* name, auto const num_colors,
auto const& get_color) {
FOR(i, num_colors)
{
auto const text = make_str(name, i);
ImGui::ColorEdit4(text.c_str(), get_color(i), ImGuiColorEditFlags_Float);
}
};
edit_treecolor("Trunk", tc.num_trunks(),
[&tc](auto const i) { return tc.trunk_color(i).data(); });
edit_treecolor("Stem", tc.num_stems(),
[&tc](auto const i) { return tc.stem_color(i).data(); });
edit_treecolor("Leaves", tc.num_leaves(),
[&tc](auto const i) { return tc.leaf_color(i).data(); });
auto& sn = registry.get<ShaderName>(eid);
auto& va = sps.ref_sp(logger, sn.value).va();
auto& dinfo = draw_handles.lookup_entity(logger, eid);
Tree::update_colors(logger, va, dinfo, tc);
}
if (registry.has<PointLight>(eid) && ImGui::CollapsingHeader("Pointlight")) {
auto& transform = registry.get<Transform>(eid);
auto& pointlight = registry.get<PointLight>(eid);
auto& light = pointlight.light;
ImGui::InputFloat3("position:", glm::value_ptr(transform.translation));
ImGui::ColorEdit3("diffuse:", light.diffuse.data());
ImGui::ColorEdit3("specular:", light.specular.data());
ImGui::Separator();
ImGui::Text("Attenuation");
auto& attenuation = pointlight.attenuation;
ImGui::InputFloat("constant:", &attenuation.constant);
ImGui::InputFloat("linear:", &attenuation.linear);
ImGui::InputFloat("quadratic:", &attenuation.quadratic);
if (registry.has<LightFlicker>(eid)) {
ImGui::Separator();
ImGui::Text("Light Flicker");
auto& flicker = registry.get<LightFlicker>(eid);
ImGui::InputFloat("speed:", &flicker.current_speed);
FOR(i, flicker.colors.size())
{
auto& light = flicker.colors[i];
ImGui::ColorEdit4("color:", light.data(), ImGuiColorEditFlags_Float);
ImGui::Separator();
}
}
}
if (registry.has<Material>(eid) && ImGui::CollapsingHeader("Material")) {
auto& material = registry.get<Material>(eid);
ImGui::ColorEdit3("ambient:", glm::value_ptr(material.ambient));
ImGui::ColorEdit3("diffuse:", glm::value_ptr(material.diffuse));
ImGui::ColorEdit3("specular:", glm::value_ptr(material.specular));
ImGui::SliderFloat("shininess:", &material.shininess, 0.0f, 1.0f);
}
};
auto const title = std::string{prefix} + ":Entity Editor Window";
imgui_cxx::with_window(draw, title.c_str(), nullptr, window_flags);
}
} // namespace
namespace boomhs::ui_debug
{
void
draw(char const* prefix, int const window_flags, EngineState& es, LevelManager& lm, Camera& camera,
FrameTime const& ft)
{
auto& uistate = es.ui_state.debug;
auto& zs = lm.active();
auto& registry = zs.registry;
auto& ldata = zs.level_data;
auto& player = find_player(registry);
if (uistate.show_entitywindow) {
auto const fs = FrameState::from_camera(es, zs, camera, camera.view_settings_ref(), es.frustum);
auto const& view_mat = fs.view_matrix();
auto const& proj_mat = fs.projection_matrix();
draw_entity_editor(prefix, window_flags, es, lm, registry, camera, view_mat, proj_mat);
}
}
} // namespace boomhs::ui_debug
| 35.846939 | 100 | 0.62895 | bjadamson |
ef20e5ad3c6caee5688e920381e0bed7342f98e1 | 10,865 | cpp | C++ | install/TexGen/Core/StaggeredPeriodicBoundaries.cpp | dalexa10/puma | ca02309c9f5c71e2e80ad8d64155dd6ca936c667 | [
"NASA-1.3"
] | 14 | 2021-06-17T17:17:07.000Z | 2022-03-26T05:20:20.000Z | install/TexGen/Core/StaggeredPeriodicBoundaries.cpp | dalexa10/puma | ca02309c9f5c71e2e80ad8d64155dd6ca936c667 | [
"NASA-1.3"
] | 6 | 2021-11-01T20:37:39.000Z | 2022-03-11T17:18:53.000Z | install/TexGen/Core/StaggeredPeriodicBoundaries.cpp | dalexa10/puma | ca02309c9f5c71e2e80ad8d64155dd6ca936c667 | [
"NASA-1.3"
] | 8 | 2021-07-20T09:24:23.000Z | 2022-02-26T16:32:00.000Z | /*=============================================================================
TexGen: Geometric textile modeller.
Copyright (C) 2010 Louise Brown
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
=============================================================================*/
#include "PrecompiledHeaders.h"
#include "TexGen.h"
#include "StaggeredPeriodicBoundaries.h"
using namespace TexGen;
using namespace std;
CStaggeredPeriodicBoundaries::CStaggeredPeriodicBoundaries(int NumEdges, int NumVertices)
:CPeriodicBoundaries(NumEdges, NumVertices)
{
}
CStaggeredPeriodicBoundaries::~CStaggeredPeriodicBoundaries(void)
{
}
void CStaggeredPeriodicBoundaries::SetFaceD( vector<int>& D1, vector<int>& D2 )
{
m_FaceD = make_pair( D1, D2 );
}
void CStaggeredPeriodicBoundaries::OutputFaceSets( ostream& Output )
{
CPeriodicBoundaries::OutputFaceSets( Output );
OutputSets( Output, m_FaceD.first, "FaceG" );
OutputSets( Output, m_FaceD.second, "FaceH" );
}
void CStaggeredPeriodicBoundaries::OutputEquations( ostream& Output, int iBoundaryConditions )
{
Output << "***************************" << endl;
Output << "*** BOUNDARY CONDITIONS ***" << endl;
Output << "***************************" << endl;
Output << "*** Name: Translation stop Vertex 1 Type: Displacement/Rotation" << endl;
Output << "*Boundary" << endl;
Output << "MasterNode1, 1, 1" << endl;
Output << "MasterNode1, 2, 2" << endl;
Output << "MasterNode1, 3, 3" << endl;
Output << endl;
Output << "*****************" << endl;
Output << "*** EQUATIONS ***" << endl;
Output << "*****************" << endl;
Output << "*parameter" << endl;
Output << "***unit cell X dimension" << endl;
Output << "BX=" << m_DomSize.x << endl;
Output << "***Unit cel Y dimension " << endl;
Output << "BY=" << m_DomSize.y << endl;
Output << "***unit cell X offset1" << endl;
Output << "OFF1=" << m_DomSize.x*m_Offset << endl;
Output << "***unit cell X length - offset1" << endl;
Output << "OFF2=" << m_DomSize.x*(1.0 - m_Offset) << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "FaceF,1,1.0,FaceE,1,-1.0,ConstraintsDriver0,1,-<BX>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "FaceF,2,1.0,FaceE,2,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "FaceF,3,1.0,FaceE,3,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "4" << endl;
Output << "FaceD,1,1.0,FaceA,1,-1.0,ConstraintsDriver0,1,-<OFF1>,ConstraintsDriver3,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "FaceD,2,1.0,FaceA,2,-1.0,ConstraintsDriver1,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "FaceD,3,1.0,FaceA,3,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "4" << endl;
Output << "FaceC,1,1.0,FaceB,1,-1.0,ConstraintsDriver0,1,<OFF2>,ConstraintsDriver3,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "FaceC,2,1.0,FaceB,2,-1.0,ConstraintsDriver1,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "FaceC,3,1.0,FaceB,3,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "Edge1,1,1.0,Edge2,1,-1.0,ConstraintsDriver0,1,-<BX>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "Edge1,2,1.0,Edge2,2,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "Edge1,3,1.0,Edge2,3,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "4" << endl;
Output << "Edge3,1,1.0,Edge4,1,-1.0,ConstraintsDriver0,1,-<OFF1>,ConstraintsDriver3,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "Edge3,2,1.0,Edge4,2,-1.0,ConstraintsDriver1,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "Edge3,3,1.0,Edge4,3,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "4" << endl;
Output << "Edge5,1,1.0,Edge6,1,-1.0,ConstraintsDriver0,1,<OFF2>,ConstraintsDriver3,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "Edge5,2,1.0,Edge6,2,-1.0,ConstraintsDriver1,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "Edge5,3,1.0,Edge6,3,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "Edge7,1,1.0,Edge8,1,-1.0,ConstraintsDriver0,1,-<BX>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "Edge7,2,1.0,Edge8,2,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "Edge7,3,1.0,Edge8,3,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "4" << endl;
Output << "Edge9,1,1.0,Edge10,1,-1.0,ConstraintsDriver0,1,-<OFF1>,ConstraintsDriver3,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "Edge9,2,1.0,Edge10,2,-1.0,ConstraintsDriver1,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "Edge9,3,1.0,Edge10,3,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "4" << endl;
Output << "Edge11,1,1.0,Edge12,1,-1.0,ConstraintsDriver0,1,<OFF2>,ConstraintsDriver3,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "Edge11,2,1.0,Edge12,2,-1.0,ConstraintsDriver1,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "Edge11,3,1.0,Edge12,3,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "Edge17,1,1.0,Edge18,1,-1.0,ConstraintsDriver0,1,-<BX>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "Edge17,2,1.0,Edge18,2,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "Edge17,3,1.0,Edge18,3,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "4" << endl;
Output << "Edge14,1,1.0,Edge18,1,-1.0,ConstraintsDriver0,1,-<OFF1>,ConstraintsDriver3,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "Edge14,2,1.0,Edge18,2,-1.0,ConstraintsDriver1,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "Edge14,3,1.0,Edge18,3,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "4" << endl;
Output << "Edge15,1,1.0,Edge13,1,-1.0,ConstraintsDriver0,1,-<OFF1>,ConstraintsDriver3,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "Edge15,2,1.0,Edge13,2,-1.0,ConstraintsDriver1,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "Edge15,3,1.0,Edge13,3,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "4" << endl;
Output << "Edge16,1,1.0,Edge13,1,-1.0,ConstraintsDriver0,1,<OFF2>,ConstraintsDriver3,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "Edge16,2,1.0,Edge13,2,-1.0,ConstraintsDriver1,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "Edge16,3,1.0,Edge13,3,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "MasterNode3,1,1.0,MasterNode1,1,-1.0,ConstraintsDriver0,1,-<BX>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "MasterNode3,2,1.0,MasterNode1,2,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "MasterNode3,3,1.0,MasterNode1,3,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "4" << endl;
Output << "MasterNode11,1,1.0,MasterNode1,1,-1.0,ConstraintsDriver0,1,-<OFF1>,ConstraintsDriver3,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "MasterNode11,2,1.0,MasterNode1,2,-1.0,ConstraintsDriver1,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "MasterNode11,3,1.0,MasterNode1,3,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "4" << endl;
Output << "MasterNode5,1,1.0,MasterNode9,1,-1.0,ConstraintsDriver0,1,-<OFF1>,ConstraintsDriver3,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "MasterNode5,2,1.0,MasterNode9,2,-1.0,ConstraintsDriver1,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "MasterNode5,3,1.0,MasterNode9,3,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "4" << endl;
Output << "MasterNode7,1,1.0,MasterNode9,1,-1.0,ConstraintsDriver0,1,<OFF2>,ConstraintsDriver3,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "MasterNode7,2,1.0,MasterNode9,2,-1.0,ConstraintsDriver1,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "MasterNode7,3,1.0,MasterNode9,3,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "MasterNode4,1,1.0,MasterNode2,1,-1.0,ConstraintsDriver0,1,-<BX>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "MasterNode4,2,1.0,MasterNode2,2,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "MasterNode4,3,1.0,MasterNode2,3,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "4" << endl;
Output << "MasterNode12,1,1.0,MasterNode2,1,-1.0,ConstraintsDriver0,1,-<OFF1>,ConstraintsDriver3,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "MasterNode12,2,1.0,MasterNode2,2,-1.0,ConstraintsDriver1,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "MasterNode12,3,1.0,MasterNode2,3,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "4" << endl;
Output << "MasterNode6,1,1.0,MasterNode10,1,-1.0,ConstraintsDriver0,1,-<OFF1>,ConstraintsDriver3,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "MasterNode6,2,1.0,MasterNode10,2,-1.0,ConstraintsDriver1,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "MasterNode6,3,1.0,MasterNode10,3,-1.0" << endl;
Output << "*EQUATION" << endl;
Output << "4" << endl;
Output << "MasterNode8,1,1.0,MasterNode10,1,-1.0,ConstraintsDriver0,1,<OFF2>,ConstraintsDriver3,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "3" << endl;
Output << "MasterNode8,2,1.0,MasterNode10,2,-1.0,ConstraintsDriver1,1,-<BY>" << endl;
Output << "*EQUATION" << endl;
Output << "2" << endl;
Output << "MasterNode8,3,1.0,MasterNode10,3,-1.0" << endl;
} | 41.311787 | 115 | 0.607731 | dalexa10 |
ef22a4f91c9d675b92178ebbcdccb2c5858fc8ed | 4,160 | cc | C++ | ortools/lp_data/model_reader.cc | yingzong/or-tools | e8287052b6108f92cdde70b7b1f2c1476e2b2f01 | [
"Apache-2.0"
] | 3 | 2021-12-11T12:30:09.000Z | 2021-12-30T09:49:45.000Z | ortools/lp_data/model_reader.cc | yingzong/or-tools | e8287052b6108f92cdde70b7b1f2c1476e2b2f01 | [
"Apache-2.0"
] | null | null | null | ortools/lp_data/model_reader.cc | yingzong/or-tools | e8287052b6108f92cdde70b7b1f2c1476e2b2f01 | [
"Apache-2.0"
] | null | null | null | // Copyright 2010-2017 Google
// 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 "ortools/lp_data/model_reader.h"
#include "ortools/base/file.h"
#include "ortools/lp_data/mps_reader.h"
#include "ortools/lp_data/proto_utils.h"
#include "ortools/util/file_util.h"
namespace operations_research {
namespace glop {
bool LoadLinearProgramFromMps(const std::string& input_file_path,
const std::string& forced_mps_format,
LinearProgram* linear_program) {
LinearProgram linear_program_fixed;
LinearProgram linear_program_free;
MPSReader mps_reader;
mps_reader.set_log_errors(forced_mps_format == "free" ||
forced_mps_format == "fixed");
bool fixed_read = forced_mps_format != "free" &&
mps_reader.LoadFileWithMode(input_file_path, false,
&linear_program_fixed);
const bool free_read =
forced_mps_format != "fixed" &&
mps_reader.LoadFileWithMode(input_file_path, true, &linear_program_free);
if (!fixed_read && !free_read) {
LOG(ERROR) << "Error while parsing the mps file '" << input_file_path
<< "' Use the --forced_mps_format flags to see the errors.";
return false;
}
if (fixed_read && free_read) {
if (linear_program_fixed.name() != linear_program_free.name()) {
VLOG(1) << "Name of the model differs between fixed and free forms. "
<< "Fallbacking to free form.";
fixed_read = false;
}
}
if (!fixed_read) {
VLOG(1) << "Read file in free format.";
linear_program->PopulateFromLinearProgram(linear_program_free);
} else {
VLOG(1) << "Read file in fixed format.";
linear_program->PopulateFromLinearProgram(linear_program_fixed);
if (free_read) {
// TODO(user): Dump() take ages on large program, so we need an efficient
// comparison function between two linear programs. Using
// GetProblemStats() for now.
if (linear_program_free.GetProblemStats() !=
linear_program_fixed.GetProblemStats()) {
LOG(ERROR) << "Could not decide if '" << input_file_path
<< "' is in fixed or free format.";
return false;
}
}
}
return true;
}
bool LoadLinearProgramFromModelOrRequest(const std::string& input_file_path,
LinearProgram* linear_program) {
MPModelProto model_proto;
MPModelRequest request_proto;
ReadFileToProto(input_file_path, &model_proto);
ReadFileToProto(input_file_path, &request_proto);
// If the input proto is in binary format, both ReadFileToProto could return
// true. Instead use the actual number of variables found to test the
// correct format of the input.
const bool is_model_proto = model_proto.variable_size() > 0;
const bool is_request_proto = request_proto.model().variable_size() > 0;
if (!is_model_proto && !is_request_proto) {
LOG(ERROR) << "Failed to parse '" << input_file_path
<< "' as an MPModelProto or an MPModelRequest.";
return false;
} else {
if (is_model_proto && is_request_proto) {
LOG(ERROR) << input_file_path
<< " is parsing as both MPModelProto and MPModelRequest";
return false;
}
if (is_request_proto) {
VLOG(1) << "Read input proto as an MPModelRequest.";
model_proto.Swap(request_proto.mutable_model());
} else {
VLOG(1) << "Read input proto as an MPModelProto.";
}
}
MPModelProtoToLinearProgram(model_proto, linear_program);
return true;
}
} // namespace glop
} // namespace operations_research
| 39.245283 | 79 | 0.669712 | yingzong |
ef22b4d7cab72e966ec25a0ddc7833335d80dc35 | 4,488 | cpp | C++ | open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/CProviderExecutor.cpp | mrehman29/open-vm-tools | 03f35e3209b3a73cf8e43a74ac764f22526723a0 | [
"X11"
] | 2 | 2020-07-23T06:01:37.000Z | 2021-02-25T06:48:42.000Z | open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/CProviderExecutor.cpp | mrehman29/open-vm-tools | 03f35e3209b3a73cf8e43a74ac764f22526723a0 | [
"X11"
] | null | null | null | open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/CProviderExecutor.cpp | mrehman29/open-vm-tools | 03f35e3209b3a73cf8e43a74ac764f22526723a0 | [
"X11"
] | 1 | 2020-11-11T12:54:06.000Z | 2020-11-11T12:54:06.000Z | /*
* Author: bwilliams
* Created: Oct 22, 2010
*
* Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential
*/
#include "stdafx.h"
#include "CProviderExecutorRequest.h"
#include "Common/IAppContext.h"
#include "IBean.h"
#include "Integration/Core/CErrorHandler.h"
#include "Integration/IChannelResolver.h"
#include "Integration/IDocument.h"
#include "Integration/IIntMessage.h"
#include "Integration/IIntegrationComponent.h"
#include "Integration/IIntegrationComponentInstance.h"
#include "Integration/IIntegrationObject.h"
#include "Integration/ITransformer.h"
#include "Exception/CCafException.h"
#include "CProviderExecutor.h"
using namespace Caf;
CProviderExecutor::CProviderExecutor() :
_isInitialized(false),
CAF_CM_INIT_LOG("CProviderExecutor") {
}
CProviderExecutor::~CProviderExecutor() {
}
void CProviderExecutor::initializeBean(
const IBean::Cargs& ctorArgs,
const IBean::Cprops& properties) {
CAF_CM_FUNCNAME_VALIDATE("initializeBean");
CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized);
CAF_CM_VALIDATE_STL_EMPTY(ctorArgs);
IBean::Cprops::const_iterator itr = properties.find("beginImpersonationBeanRef");
if (itr != properties.end()) {
_beginImpersonationBeanId = itr->second;
}
itr = properties.find("endImpersonationBeanRef");
if (itr != properties.end()) {
_endImpersonationBeanId = itr->second;
}
_isInitialized = true;
}
void CProviderExecutor::terminateBean() {
}
void CProviderExecutor::wire(const SmartPtrIAppContext& appContext,
const SmartPtrIChannelResolver& channelResolver) {
CAF_CM_FUNCNAME_VALIDATE("wire");
CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
CAF_CM_VALIDATE_INTERFACE(appContext);
CAF_CM_VALIDATE_INTERFACE(channelResolver);
if (AppConfigUtils::getOptionalBoolean(_sManagementAgentArea, "use_impersonation")) {
_beginImpersonationTransformer = loadTransformer(_beginImpersonationBeanId, appContext, channelResolver);
_endImpersonationTransformer = loadTransformer(_endImpersonationBeanId, appContext, channelResolver);
}
SmartPtrCErrorHandler errorHandler;
errorHandler.CreateInstance();
errorHandler->initialize(channelResolver, channelResolver->resolveChannelName("errorChannel"));
_errorHandler = errorHandler;
}
SmartPtrITransformer CProviderExecutor::loadTransformer(
const std::string& id,
const SmartPtrIAppContext& appContext,
const SmartPtrIChannelResolver& channelResolver) {
CAF_CM_FUNCNAME("loadTransformer");
CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
CAF_CM_VALIDATE_INTERFACE(appContext);
CAF_CM_VALIDATE_STRING(id);
SmartPtrITransformer transformer;
if (!id.empty()) {
const SmartPtrIBean bean = appContext->getBean(id);
SmartPtrIIntegrationComponent integrationComponent;
integrationComponent.QueryInterface(bean, false);
if (!integrationComponent) {
CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, 0,
"Bean is not an integration component - %s", id.c_str());
}
SmartPtrIDocument configSection;
SmartPtrIIntegrationObject integrationObject;
integrationObject = integrationComponent->createObject(configSection);
SmartPtrIIntegrationComponentInstance integrationComponentInstance;
integrationComponentInstance.QueryInterface(integrationObject, false);
if (!integrationComponentInstance.IsNull()) {
integrationComponentInstance->wire(appContext, channelResolver);
}
transformer.QueryInterface(integrationObject, false);
CAF_CM_VALIDATE_INTERFACE(transformer);
}
return transformer;
}
void CProviderExecutor::handleMessage(const SmartPtrIIntMessage& message) {
CAF_CM_FUNCNAME_VALIDATE("handleMessage");
CAF_CM_PRECOND_ISINITIALIZED(_isInitialized);
CAF_CM_VALIDATE_SMARTPTR(message);
CAF_CM_LOG_DEBUG_VA0("Called");
SmartPtrCProviderExecutorRequest executorRequest;
executorRequest.CreateInstance();
executorRequest->initialize(message);
const std::string& providerUri = executorRequest->getProviderUri();
SmartPtrCProviderExecutorRequestHandler handler = _handlers[providerUri];
if (handler == NULL) {
SmartPtrCProviderExecutorRequestHandler requestHandler;
requestHandler.CreateInstance();
requestHandler->initialize(providerUri, _beginImpersonationTransformer,
_endImpersonationTransformer, _errorHandler);
_handlers[providerUri] = requestHandler;
handler = requestHandler;
}
handler->handleRequest(executorRequest);
}
SmartPtrIIntMessage CProviderExecutor::getSavedMessage() const {
return NULL;
}
void CProviderExecutor::clearSavedMessage() {
}
| 30.739726 | 107 | 0.807487 | mrehman29 |
ef274bc17b75be462d3a98a34a54ecc2fbb62165 | 3,266 | cpp | C++ | src/util/pfx_mass.cpp | erwincoumans/test2 | cb78f36ae4002d79f21d21c759d07e2e23aabf15 | [
"BSD-3-Clause"
] | 5 | 2017-10-08T16:06:35.000Z | 2020-10-08T23:30:34.000Z | src/util/pfx_mass.cpp | erwincoumans/test2 | cb78f36ae4002d79f21d21c759d07e2e23aabf15 | [
"BSD-3-Clause"
] | null | null | null | src/util/pfx_mass.cpp | erwincoumans/test2 | cb78f36ae4002d79f21d21c759d07e2e23aabf15 | [
"BSD-3-Clause"
] | null | null | null | /*
Physics Effects Copyright(C) 2010 Sony Computer Entertainment Inc.
All rights reserved.
Physics Effects is open software; you can redistribute it and/or
modify it under the terms of the BSD License.
Physics Effects is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the BSD License for more details.
A copy of the BSD License is distributed with
Physics Effects under the filename: physics_effects_license.txt
*/
#include "../../include/physics_effects/util/pfx_mass.h"
namespace sce {
namespace PhysicsEffects {
///////////////////////////////////////////////////////////////////////////////
// Box
PfxFloat pfxCalcMassBox(PfxFloat density,const PfxVector3 &halfExtent)
{
return density * halfExtent[0] * halfExtent[1] * halfExtent[2] * 8;
}
PfxMatrix3 pfxCalcInertiaBox(const PfxVector3 &halfExtent,PfxFloat mass)
{
PfxVector3 sqrSz = halfExtent * 2.0f;
sqrSz = mulPerElem(sqrSz,sqrSz);
PfxMatrix3 inertia = PfxMatrix3::identity();
inertia[0][0] = (mass*(sqrSz[1]+sqrSz[2]))/12.0f;
inertia[1][1] = (mass*(sqrSz[0]+sqrSz[2]))/12.0f;
inertia[2][2] = (mass*(sqrSz[0]+sqrSz[1]))/12.0f;
return inertia;
}
///////////////////////////////////////////////////////////////////////////////
// Sphere
PfxFloat pfxCalcMassSphere(PfxFloat density,PfxFloat radius)
{
return (4.0f/3.0f) * SCE_PFX_PI * radius * radius * radius * density;
}
PfxMatrix3 pfxCalcInertiaSphere(PfxFloat radius,PfxFloat mass)
{
PfxMatrix3 inertia = PfxMatrix3::identity();
inertia[0][0] = inertia[1][1] = inertia[2][2] = 0.4f * mass * radius * radius;
return inertia;
}
///////////////////////////////////////////////////////////////////////////////
// Cylinder
PfxFloat pfxCalcMassCylinder(PfxFloat density,PfxFloat halfLength,PfxFloat radius)
{
return SCE_PFX_PI * radius * radius * 2.0f * halfLength * density;
}
static inline
PfxMatrix3 pfxCalcInertiaCylinder(PfxFloat halfLength,PfxFloat radius,PfxFloat mass,int axis)
{
PfxMatrix3 inertia = PfxMatrix3::identity();
inertia[0][0] = inertia[1][1] = inertia[2][2] = 0.25f * mass * radius * radius + 0.33f * mass * halfLength * halfLength;
inertia[axis][axis] = 0.5f * mass * radius * radius;
return inertia;
}
PfxMatrix3 pfxCalcInertiaCylinderX(PfxFloat halfLength,PfxFloat radius,PfxFloat mass)
{
return pfxCalcInertiaCylinder(radius,halfLength,mass,0);
}
PfxMatrix3 pfxCalcInertiaCylinderY(PfxFloat halfLength,PfxFloat radius,PfxFloat mass)
{
return pfxCalcInertiaCylinder(radius,halfLength,mass,1);
}
PfxMatrix3 pfxCalcInertiaCylinderZ(PfxFloat halfLength,PfxFloat radius,PfxFloat mass)
{
return pfxCalcInertiaCylinder(radius,halfLength,mass,2);
}
///////////////////////////////////////////////////////////////////////////////
PfxMatrix3 pfxMassTranslate(PfxFloat mass,const PfxMatrix3 &inertia,const PfxVector3 &translation)
{
PfxMatrix3 m = crossMatrix(translation);
return inertia + mass * (-m*m);
}
PfxMatrix3 pfxMassRotate(const PfxMatrix3 &inertia,const PfxMatrix3 &rotate)
{
return rotate * inertia * transpose(rotate);
}
} //namespace PhysicsEffects
} //namespace sce
| 31.708738 | 123 | 0.663503 | erwincoumans |
ef2c6225de520e9b2e85c92fd692cec7bd0bdfed | 1,139 | cpp | C++ | src/cxx/basic_client.cpp | basho-labs/riak-cxx-client | 88f7196f8c30f35ec784c6e051e82082927acc77 | [
"Apache-2.0"
] | 8 | 2015-11-05T15:28:34.000Z | 2021-08-03T10:23:07.000Z | src/cxx/basic_client.cpp | basho-labs/riak-cxx-client | 88f7196f8c30f35ec784c6e051e82082927acc77 | [
"Apache-2.0"
] | 3 | 2015-03-31T12:26:25.000Z | 2015-04-15T10:50:18.000Z | src/cxx/basic_client.cpp | basho-labs/riak-cxx-client | 88f7196f8c30f35ec784c6e051e82082927acc77 | [
"Apache-2.0"
] | 3 | 2017-05-01T01:21:48.000Z | 2020-10-20T13:13:40.000Z | /*
Copyright 2011 Basho Technologies, 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 <riak_client/cxx/basic/basic_client.hpp>
#include "pbc_client.hpp"
#include <boost/thread/thread.hpp>
#include <functional>
#include <tr1/functional>
#include <iostream>
#include <sstream>
#include <string>
namespace riak {
uint32_t tss_client_id()
{
std::stringstream ostr;
ostr << boost::this_thread::get_id();
std::tr1::hash<std::string> h;
return h(ostr.str());
}
client_ptr new_client(const std::string& host, const std::string& port, const protocol p)
{
return client_ptr(new pbc::pbc_client(host, port));
}
} // ::riak
| 26.488372 | 89 | 0.740123 | basho-labs |
ef2fbaf2e29bf8fbcd9036a80241574ad9edd5ad | 1,384 | cpp | C++ | src/main/cpp/commands/ShooterHood/SetHoodAngle.cpp | FIRSTTeam102/Robot2022 | 2a3224fd9bf7e4e9b469214fdf141a3d25d9094c | [
"BSD-3-Clause"
] | null | null | null | src/main/cpp/commands/ShooterHood/SetHoodAngle.cpp | FIRSTTeam102/Robot2022 | 2a3224fd9bf7e4e9b469214fdf141a3d25d9094c | [
"BSD-3-Clause"
] | null | null | null | src/main/cpp/commands/ShooterHood/SetHoodAngle.cpp | FIRSTTeam102/Robot2022 | 2a3224fd9bf7e4e9b469214fdf141a3d25d9094c | [
"BSD-3-Clause"
] | null | null | null | #include "commands/ShooterHood/SetHoodAngle.h"
// SetHoodAngle based on hardcoded value
SetHoodAngle::SetHoodAngle(double degrees, ShooterHood* pShooterHood) :
mDegrees{degrees}, mpShooterHood{pShooterHood}, mpLimelight{NULL}, mpNTEntry{NULL} {
SetName("SetHoodAngle");
AddRequirements(pShooterHood);
}
// SetHoodAngle based on distance from target determined by Limelight
SetHoodAngle::SetHoodAngle(ShooterHood* pShooterHood, Limelight* pLimelight) :
mDegrees{0}, mpShooterHood{pShooterHood}, mpLimelight{pLimelight}, mpNTEntry{NULL} {
SetName("SetHoodAngle");
AddRequirements(pShooterHood);
}
SetHoodAngle::SetHoodAngle(ShooterHood* pShooterHood, nt::NetworkTableEntry* pNTEntry) :
mDegrees{0}, mpShooterHood{pShooterHood}, mpLimelight{NULL}, mpNTEntry{pNTEntry} {
SetName("SetHoodAngle");
AddRequirements(pShooterHood);
}
// Called when the command is initially scheduled.
void SetHoodAngle::Initialize() {
if (mpLimelight) mDegrees = mpLimelight->getServoAngle();
else if (mpNTEntry) mDegrees = mpNTEntry->GetDouble(0.0);
mpShooterHood->setAngle(mDegrees);
}
// Called repeatedly when this Command is scheduled to run
void SetHoodAngle::Execute() {}
// Called once the command ends or is interrupted.
void SetHoodAngle::End(bool interrupted) {}
// Returns true when the command should end.
bool SetHoodAngle::IsFinished() {
return mpShooterHood->isAtTarget();
}
| 33.756098 | 88 | 0.78396 | FIRSTTeam102 |
ef32badf6a2beccf2075ac54bfaf5f610cd2c05f | 19,139 | cpp | C++ | MathTL/numerics/w_method.cpp | kedingagnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | 3 | 2018-05-20T15:25:58.000Z | 2021-01-19T18:46:48.000Z | MathTL/numerics/w_method.cpp | agnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | null | null | null | MathTL/numerics/w_method.cpp | agnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | 2 | 2019-04-24T18:23:26.000Z | 2020-09-17T10:00:27.000Z | // implementation for w_method.h
#include <cmath>
#include <iostream>
#include <utils/array1d.h>
using std::cout;
using std::endl;
namespace MathTL
{
//template <class VECTOR>
template <class VECTOR, class IVP>
WMethodStageEquationHelper<VECTOR, IVP>::~WMethodStageEquationHelper()
{
}
template <class VECTOR>
WMethodPreprocessRHSHelper<VECTOR>::~WMethodPreprocessRHSHelper()
{
}
template <class VECTOR, class IVP>
WMethod<VECTOR, IVP>::WMethod(const Method method,
const WMethodStageEquationHelper<VECTOR,IVP>* s)
: stage_equation_helper(s), preprocessor(0)
{
LowerTriangularMatrix<double> Alpha, Gamma;
Vector<double> b, bhat;
double gamma;
switch(method)
{
case ROS2:
Alpha.resize(2,2);
Alpha.set_entry(1, 0, 1.0);
Gamma.resize(2,2);
gamma = 1.0 + M_SQRT1_2;
Gamma.set_entry(0, 0, gamma);
Gamma.set_entry(1, 0, -2*gamma);
Gamma.set_entry(1, 1, gamma);
b.resize(2);
b[0] = b[1] = 0.5;
bhat.resize(2);
bhat[0] = 1.0;
transform_coefficients(Alpha, Gamma, b, bhat,
A, C, m, e, alpha_vector, gamma_vector);
p = 2;
break;
case RODAS3:
Alpha.resize(4,4);
Alpha.set_entry(2, 0, 1.);
Alpha.set_entry(3, 0, 3./4.);
Alpha.set_entry(3, 1, -1./4.);
Alpha.set_entry(3, 2, 1./2.);
Gamma.resize(4,4);
gamma = 0.5;
Gamma.set_entry(0, 0, gamma);
Gamma.set_entry(1, 0, 1.);
Gamma.set_entry(1, 1, gamma);
Gamma.set_entry(2, 0, -1./4.);
Gamma.set_entry(2, 1, -1./4.);
Gamma.set_entry(2, 2, gamma);
Gamma.set_entry(3, 0, 1./12.);
Gamma.set_entry(3, 1, 1./12.);
Gamma.set_entry(3, 2, -2./3.);
Gamma.set_entry(3, 3, gamma);
b.resize(4);
b[0] = 5./6.;
b[1] = b[2] = -1./6.;
b[3] = 1./2.;
bhat.resize(4);
bhat[0] = 3./4.;
bhat[1] = -1./4.;
bhat[2] = 1./2.;
transform_coefficients(Alpha, Gamma, b, bhat,
A, C, m, e, alpha_vector, gamma_vector);
p = 3;
break;
case ROS3P:
Alpha.resize(3,3);
Alpha.set_entry(1, 0, 1.);
Alpha.set_entry(2, 0, 1.);
Gamma.resize(3,3);
gamma = 0.5 + sqrt(3.)/6.;
Gamma.set_entry(0, 0, gamma);
Gamma.set_entry(1, 0, -1.);
Gamma.set_entry(1, 1, gamma);
Gamma.set_entry(2, 0, -gamma);
Gamma.set_entry(2, 1, 0.5-2*gamma);
Gamma.set_entry(2, 2, gamma);
b.resize(3);
b[0] = 2./3.;
b[2] = 1./3.;
bhat.resize(3);
bhat[0] = bhat[1] = bhat[2] = 1./3.;
transform_coefficients(Alpha, Gamma, b, bhat,
A, C, m, e, alpha_vector, gamma_vector);
p = 3;
break;
case ROWDA3:
Alpha.resize(3,3);
Alpha.set_entry(1, 0, 0.7);
Alpha.set_entry(2, 0, 0.7);
Gamma.resize(3,3);
gamma = 0.43586652150845899941601945119356; // gamma^3-3*gamma^2+1.5*gamma-1/6=0
Gamma.set_entry(0, 0, gamma);
Gamma.set_entry(1, 0, 0.1685887625570998);
Gamma.set_entry(1, 1, gamma);
Gamma.set_entry(2, 0, 4.943922277836421);
Gamma.set_entry(2, 1, 1.);
Gamma.set_entry(2, 2, gamma);
b.resize(3);
b[0] = 0.3197278911564624;
b[1] = 0.7714777906171382;
b[2] = -0.09120568177360061;
bhat.resize(3);
bhat[0] = 0.926163587124091;
bhat[1] = 0.073836412875909;
transform_coefficients(Alpha, Gamma, b, bhat,
A, C, m, e, alpha_vector, gamma_vector);
p = 3;
break;
case ROS3:
gamma = 0.43586652150845899941601945119356; // gamma^3-3*gamma^2+1.5*gamma-1/6=0
Alpha.resize(3,3);
Alpha.set_entry(1, 0, gamma);
Alpha.set_entry(2, 0, gamma);
Gamma.resize(3,3);
Gamma.set_entry(0, 0, gamma);
Gamma.set_entry(1, 0, -0.19294655696029095575009695436041);
Gamma.set_entry(1, 1, gamma);
Gamma.set_entry(2, 1, 1.74927148125794685173529749738960);
Gamma.set_entry(2, 2, gamma);
b.resize(3);
b[0] = -0.75457412385404315829818998646589;
b[1] = 1.94100407061964420292840123379419;
b[2] = -0.18642994676560104463021124732829;
bhat.resize(3);
bhat[0] = -1.53358745784149585370766523913002;
bhat[1] = 2.81745131148625772213931745457622;
bhat[2] = -0.28386385364476186843165221544619;
transform_coefficients(Alpha, Gamma, b, bhat,
A, C, m, e, alpha_vector, gamma_vector);
p = 3;
break;
case ROS3Pw:
gamma = 0.5 + sqrt(3.)/6.;
Alpha.resize(3,3);
Alpha.set_entry(1, 0, 2*gamma);
Alpha.set_entry(2, 0, 0.5);
Gamma.resize(3,3);
Gamma.set_entry(0, 0, gamma);
Gamma.set_entry(1, 0, -2*gamma);
Gamma.set_entry(1, 1, gamma);
Gamma.set_entry(2, 0, -.67075317547305480);
Gamma.set_entry(2, 1, -.17075317547305482);
Gamma.set_entry(2, 2, gamma);
b.resize(3);
b[0] = 0.10566243270259355;
b[1] = 0.049038105676657971;
b[2] = 0.84529946162074843;
bhat.resize(3);
bhat[0] = -0.17863279495408180;
bhat[1] = 1./3.;
bhat[2] = 0.84529946162074843;
transform_coefficients(Alpha, Gamma, b, bhat,
A, C, m, e, alpha_vector, gamma_vector);
p = 3;
break;
case ROSI2P2:
gamma = 0.43586652150845899941601945119356; // gamma^3-3*gamma^2+1.5*gamma-1/6=0
Alpha.resize(4,4);
Alpha.set_entry(1, 0, 0.5);
Alpha.set_entry(2, 0, -0.51983699657507165);
Alpha.set_entry(2, 1, 1.5198369965750715);
Alpha.set_entry(3, 0, -0.51983699657507165);
Alpha.set_entry(3, 1, 1.5198369965750715);
Gamma.resize(4,4);
Gamma.set_entry(0, 0, gamma);
Gamma.set_entry(1, 0, -0.5);
Gamma.set_entry(1, 1, gamma);
Gamma.set_entry(2, 0, -0.40164172503011392);
Gamma.set_entry(2, 1, 1.174271852697665);
Gamma.set_entry(2, 2, gamma);
Gamma.set_entry(3, 0, 1.1865036632417383);
Gamma.set_entry(3, 1, -1.5198369965750715);
Gamma.set_entry(3, 2, -0.10253318817512568);
Gamma.set_entry(3, 3, gamma);
b.resize(4);
b[0] = 2./3.;
b[2] = -0.10253318817512568;
b[3] = 0.435866521508459;
bhat.resize(4);
bhat[0] = -0.95742384859111473;
bhat[1] = 2.9148476971822297;
bhat[2] = 0.5;
bhat[3] = -1.4574238485911146;
transform_coefficients(Alpha, Gamma, b, bhat,
A, C, m, e, alpha_vector, gamma_vector);
p = 3;
break;
case ROSI2PW:
gamma = 0.43586652150845899941601945119356; // gamma^3-3*gamma^2+1.5*gamma-1/6=0
Alpha.resize(4,4);
Alpha.set_entry(1, 0, 8.7173304301691801e-1);
Alpha.set_entry(2, 0, -7.9937335839852708e-1);
Alpha.set_entry(2, 1, -7.9937335839852708e-1);
Alpha.set_entry(3, 0, 7.0849664917601007e-1);
Alpha.set_entry(3, 1, 3.1746327955312481e-1);
Alpha.set_entry(3, 2, -2.5959928729134892e-2);
Gamma.resize(4,4);
Gamma.set_entry(0, 0, gamma);
Gamma.set_entry(1, 0, -8.7173304301691801e-1);
Gamma.set_entry(1, 1, gamma);
Gamma.set_entry(2, 0, 3.0647867418622479);
Gamma.set_entry(2, 1, 3.0647867418622479);
Gamma.set_entry(2, 2, gamma);
Gamma.set_entry(3, 0, -1.0424832458800504e-1);
Gamma.set_entry(3, 1, -3.1746327955312481e-1);
Gamma.set_entry(3, 2, -1.4154917367329144e-2);
Gamma.set_entry(3, 3, gamma);
b.resize(4);
b[0] = 6.0424832458800504e-1;
b[2] = -4.0114846096464034e-2;
b[3] = 4.3586652150845900e-1;
bhat.resize(4);
bhat[0] = bhat[1] = 4.4315753191688778e-1;
bhat[3] = 1.1368493616622447e-1;
transform_coefficients(Alpha, Gamma, b, bhat,
A, C, m, e, alpha_vector, gamma_vector);
p = 3;
break;
case GRK4T:
A.resize(4,4); // corresponds to the [HW] notation
A(1,0) = 0.2000000000000000e+01;
A(2,0) = A(3,0) = 0.4524708207373116e+01;
A(2,1) = A(3,1) = 0.4163528788597648e+01;
C.resize(4,4); // corresponds to the [HW] notation
C(0,0) = C(1,1) = C(2,2) = C(3,3) = 0.231; // gamma
C(1,0) = -0.5071675338776316e+01;
C(2,0) = 0.6020152728650786e+01;
C(2,1) = 0.1597506846727117e+00;
C(3,0) = -0.1856343618686113e+01;
C(3,1) = -0.8505380858179826e+01;
C(3,2) = -0.2084075136023187e+01;
gamma_vector.resize(4); // corresponds to Di in [HW]
gamma_vector[0] = 0.2310000000000000e+00;
gamma_vector[1] = -0.3962966775244303e-01;
gamma_vector[2] = 0.5507789395789127e+00;
gamma_vector[3] = -0.5535098457052764e-01;
alpha_vector.resize(4); // corresponds to Ci in [HW]
alpha_vector[1] = 0.4620000000000000e+00;
alpha_vector[2] = alpha_vector[3]
= 0.8802083333333334e+00;
m.resize(4); // corresponds to Bi in [HW] (the m_i in the [HW II] book)
m[0] = 0.3957503746640777e+01;
m[1] = 0.4624892388363313e+01;
m[2] = 0.6174772638750108e+00;
m[3] = 0.1282612945269037e+01;
e.resize(4);
e[0] = 0.2302155402932996e+01;
e[1] = 0.3073634485392623e+01;
e[2] = -0.8732808018045032e+00;
e[3] = -0.1282612945269037e+01;
p = 4;
break;
case RODAS:
A.resize(6,6);
// values from KARDOS:
A(1,0) = 1.5440000000000000;
A(2,0) = 0.9466785281022800;
A(2,1) = 0.2557011699000000;
A(3,0) = 3.3148251870787937;
A(3,1) = 2.8961240159798773;
A(3,2) = 0.9986419140000000;
A(4,0) = 1.2212245090707980;
A(4,1) = 6.0191344810926299;
A(4,2) = 12.5370833291149566;
A(4,3) = -0.6878860361200000;
A(5,0) = 1.2212245092986209;
A(5,1) = 6.0191344813485754;
A(5,2) = 12.5370833293196604;
A(5,3) = -0.6878860360800001;
A(5,4) = 1.0000000000000000;
C.resize(6, 6);
C(0,0) = C(1,1) = C(2,2) = C(3,3)
= C(4,4) = C(5,5) = 0.25; // = gamma
C(1,0) = -5.6688000000000000;
C(2,0) = -2.4300933568670464;
C(2,1) = -0.2063599157120000;
C(3,0) = -0.1073529065055983;
C(3,1) = -9.5945622510667228;
C(3,2) = -20.4702861487999996;
C(4,0) = 7.4964433159050206;
C(4,1) = -10.2468043146053738;
C(4,2) = -33.9999035259299589;
C(4,3) = 11.7089089319999999;
C(5,0) = 8.0832467990118602;
C(5,1) = -7.9811329880455499;
C(5,2) = -31.5215943254324245;
C(5,3) = 16.3193054312706352;
C(5,4) = -6.0588182388799998;
// values from KARDOS:
gamma_vector.resize(6);
gamma_vector[0] = 0.2500000000000000;
gamma_vector[1] = -0.1043000000000000;
gamma_vector[2] = 0.1034999999980000;
gamma_vector[3] = -0.0362000000000000;
gamma_vector[4] = 0.0000000000000000;
gamma_vector[5] = 0.0000000000000000;
// values from KARDOS:
alpha_vector.resize(6);
alpha_vector[0] = 0.0000000000000000;
alpha_vector[1] = 0.3860000000000000;
alpha_vector[2] = 0.2100000000000000;
alpha_vector[3] = 0.6300000000000000;
alpha_vector[4] = 1.0000000000000000;
alpha_vector[5] = 1.0000000000000000;
// values from KARDOS:
m.resize(6);
m[0] = 1.2212245092981915;
m[1] = 6.0191344813101981;
m[2] = 12.5370833292377792;
m[3] = -0.6878860360960002;
m[4] = 1.0000000000000000;
m[5] = 1.0000000000000000;
e.resize(6);
e[0] = 0.0;
e[1] = 0.0;
e[2] = 0.0;
e[3] = 0.0;
e[4] = 0.0;
e[5] = m[5];
p = 4;
break;
case RODASP:
A.resize(6, 6);
// values from KARDOS:
A(1,0) = 3.0000000000000000;
A(2,0) = 1.8310367935359999;
A(2,1) = 0.4955183967600000;
A(3,0) = 2.3043765826379414;
A(3,1) = -0.0524927524844542;
A(3,2) = -1.1767987618400000;
A(4,0) = -7.1704549640449367;
A(4,1) = -4.7416366720041934;
A(4,2) = -16.3100263134518535;
A(4,3) = -1.0620040441200000;
A(5,0) = -7.1704549641649340;
A(5,1) = -4.7416366720441925;
A(5,2) = -16.3100263134518570;
A(5,3) = -1.0620040441200000;
A(5,4) = 1.0000000000000000;
C.resize(6, 6);
C(0,0) = C(1,1) = C(2,2) = C(3,3)
= C(4,4) = C(5,5) = 0.25; // = gamma
// values from KARDOS:
C(1,0) = -12.0000000000000000;
C(2,0) = -8.7917951740800000;
C(2,1) = -2.2078655870400000;
C(3,0) = 10.8179305689176530;
C(3,1) = 6.7802706116824574;
C(3,2) = 19.5348594463999987;
C(4,0) = 34.1909500739412096;
C(4,1) = 15.4967115394459682;
C(4,2) = 54.7476087604061235;
C(4,3) = 14.1600539214399994;
C(5,0) = 34.6260583162319335;
C(5,1) = 15.3008497633150125;
C(5,2) = 56.9995557863878588;
C(5,3) = 18.4080700977581699;
C(5,4) = -5.7142857142399999;
// values from KARDOS:
gamma_vector.resize(6);
gamma_vector[0] = 0.2500000000000000;
gamma_vector[1] = -0.5000000000000000;
gamma_vector[2] = -0.0235040000000000;
gamma_vector[3] = -0.0362000000000000;
gamma_vector[4] = 0.0 ;
gamma_vector[5] = 0.0 ;
// values from KARDOS:
alpha_vector.resize(6);
alpha_vector[0] = 0.0;
alpha_vector[1] = 0.75;
alpha_vector[2] = 0.21;
alpha_vector[3] = 0.63;
alpha_vector[4] = 1.0;
alpha_vector[5] = 1.0;
// values from KARDOS:
m.resize(6);
m[0] = -7.1704549641649322;
m[1] = -4.7416366720441925;
m[2] = -16.3100263134518570;
m[3] = -1.0620040441200000;
m[4] = 1.0000000000000000;
m[5] = 1.0000000000000000;
e.resize(6);
e[0] = 0.0;
e[1] = 0.0;
e[2] = 0.0;
e[3] = 0.0;
e[4] = 0.0;
e[5] = m[5];
p = 4;
break;
default:
break;
}
}
template <class VECTOR, class IVP>
void
WMethod<VECTOR, IVP>::transform_coefficients(const LowerTriangularMatrix<double>& Alpha,
const LowerTriangularMatrix<double>& Gamma,
const Vector<double>& b,
const Vector<double>& bhat,
LowerTriangularMatrix<double>& A,
LowerTriangularMatrix<double>& C,
Vector<double>& m,
Vector<double>& e,
Vector<double>& alpha_vector,
Vector<double>& gamma_vector)
{
const unsigned int s = Alpha.row_dimension();
alpha_vector.resize(s, true);
for (unsigned int i = 0; i < s; i++) {
double alphai = 0;
for (unsigned int j = 0; j < i; j++) alphai += Alpha.get_entry(i, j);
alpha_vector[i] = alphai;
}
gamma_vector.resize(s, true);
for (unsigned int i = 0; i < s; i++) {
double gammai = 0;
// note that here, we use "j<=i" (compare order condition check below):
for (unsigned int j = 0; j <= i; j++) gammai += Gamma.get_entry(i, j);
gamma_vector[i] = gammai;
}
Gamma.inverse(C);
A.resize(s, s);
A = Alpha * C; // A = Alpha * Gamma^{-1}
m.resize(s, false);
C.apply_transposed(b, m); // m^T = b^T * Gamma^{-1}
e.resize(s, true);
C.apply_transposed(bhat, e);
e.sadd(-1.0, m); // e = m-mhat
C.scale(-1.0);
for (unsigned int i = 0; i < s; i++)
C.set_entry(i, i, Gamma.get_entry(0,0)); // gamma
// cout << "* coefficients after transform_coefficients():" << endl;
// cout << "alpha_vector=" << alpha_vector << endl;
// cout << "gamma_vector=" << gamma_vector << endl;
// cout << "A=" << endl << A;
// cout << "C=" << endl << C;
// cout << "m=" << m << endl;
// cout << "e=" << e << endl;
// check_order_conditions(Alpha, Gamma, b, bhat, false);
}
template <class VECTOR, class IVP>
void
WMethod<VECTOR, IVP>::check_order_conditions(const LowerTriangularMatrix<double>& Alpha,
const LowerTriangularMatrix<double>& Gamma,
const Vector<double>& b,
const Vector<double>& bhat,
const bool wmethod)
{
cout << "* checking algebraic order conditions for a ROW method:" << endl;
const unsigned int s = Alpha.row_dimension();
double help, gamma = Gamma.get_entry(0,0);
LowerTriangularMatrix<double> Beta(s, s);
for (unsigned int i = 0; i < s; i++)
for (unsigned int j = 0; j < i; j++)
Beta.set_entry(i, j, Alpha.get_entry(i, j) + Gamma.get_entry(i, j));
Vector<double> alpha_vector(s);
for (unsigned int i = 0; i < s; i++) {
double alphai = 0;
for (unsigned int j = 0; j < i; j++) alphai += Alpha.get_entry(i, j);
alpha_vector[i] = alphai;
}
cout << " alpha_vector=" << alpha_vector << endl;
Vector<double> gamma_vector(s);
for (unsigned int i = 0; i < s; i++) {
double gammai = 0;
// for the order conditions, we use gamma_i=sum_{j<i}gamma_j (not "<=" as in transform_coefficients())
for (unsigned int j = 0; j < i; j++) gammai += Gamma.get_entry(i, j);
gamma_vector[i] = gammai;
}
cout << " gamma_vector=" << gamma_vector << endl;
Vector<double> beta_vector(alpha_vector+gamma_vector);
cout << " beta_vector=" << beta_vector << endl;
cout << " (A1) (sum_i b_i)-1=";
help = 0;
for (unsigned int i = 0; i < s; i++) help += b[i];
cout << help-1 << endl;
cout << " (A2) (sum_i b_i beta_i)-(1/2-gamma)=";
help = 0;
for (unsigned int i = 0; i < s; i++) help += b[i] * beta_vector[i];
cout << help-(0.5-gamma) << endl;
cout << " (A3a) (sum_i b_i alpha_i^2)-1/3=";
help = 0;
for (unsigned int i = 0; i < s; i++) help += b[i] * alpha_vector[i] * alpha_vector[i];
cout << help-1./3. << endl;
cout << " (A3b) (sum_{i,j} b_i beta_{i,j} beta_j)-(1/6-gamma+gamma^2)=";
help = 0;
for (unsigned int i = 0; i < s; i++)
for (unsigned int j = 0; j < i; j++)
help += b[i] * Beta.get_entry(i,j) * beta_vector[j];
cout << help-1./6.+gamma-gamma*gamma << endl;
cout << " (A1) (sum_i bhat_i)-1=";
help = 0;
for (unsigned int i = 0; i < s; i++) help += bhat[i];
cout << help-1 << endl;
cout << " (A2) (sum_i bhat_i beta_i)-(0.5-gamma)=";
help = 0;
for (unsigned int i = 0; i < s; i++) help += bhat[i] * beta_vector[i];
cout << help-(0.5-gamma) << endl;
cout << " (A3a) (sum_i bhat_i alpha_i^2)-1/3=";
help = 0;
for (unsigned int i = 0; i < s; i++) help += bhat[i] * alpha_vector[i] * alpha_vector[i];
cout << help-1./3. << endl;
cout << " (A3b) (sum_{i,j} bhat_i beta_{i,j} beta_j)-(1/6-gamma+gamma^2)=";
help = 0;
for (unsigned int i = 0; i < s; i++)
for (unsigned int j = 0; j < i; j++)
help += bhat[i] * Beta.get_entry(i,j) * beta_vector[j];
cout << help-1./6.+gamma-gamma*gamma << endl;
}
template <class VECTOR, class IVP>
void
WMethod<VECTOR, IVP>::increment(IVP* ivp,
const double t_m, const VECTOR& u_m,
const double tau,
VECTOR& u_mplus1,
VECTOR& error_estimate,
const double tolerance) const
{
const unsigned int stages = A.row_dimension(); // for readability
Array1D<VECTOR> u(stages);
u[0] = u_m; u[0].scale(0.0); // ensures correct size
for (unsigned int i = 1; i < stages; i++)
u[i] = u[0];
VECTOR rhs(u[0]), help(u[0]); // ensures correct size
// solve stage equations (TODO: adjust the tolerances appropriately)
for (unsigned int i(0); i < stages; i++) {
// setup i-th right-hand side
// f(t_m + \tau * \alpha_i, u^{(m)} + \sum_{j=1}^{i-1} a_{i,j} * u_j)
// + \sum_{j=1}^{i-1} \frac{c_{i,j}}{\tau} * u_j
// + \tau * \gamma_i * g
help = u_m;
for (unsigned int j(0); j < i; j++)
help.add(A(i,j), u[j]);
ivp->evaluate_f(t_m+tau*alpha_vector[i], help, tolerance/(4*stages), rhs);
if (preprocessor == 0) { // no preprocessing necessary
for (unsigned int j(0); j < i; j++)
rhs.add(C(i,j)/tau, u[j]);
} else {
help.scale(0.0);
for (unsigned int j(0); j < i; j++)
help.add(C(i,j)/tau, u[j]);
preprocessor->preprocess_rhs_share(help, tolerance/(4*stages));
rhs.add(help);
}
stage_equation_helper->approximate_ft(ivp, t_m, u_m, tolerance/(4*stages), help);
rhs.add(tau*gamma_vector[i], help);
// solve i-th stage equation
// (\tau*\gamma_{i,i})^{-1}I - T) u_i = rhs
stage_equation_helper->solve_W_stage_equation(ivp, t_m, u_m, 1./(tau*C(i,i)), rhs, tolerance/(4*stages), u[i]);
}
// update u^{(m)} -> u^{(m+1)} by the k_i
u_mplus1 = u_m;
for (unsigned int i(0); i < stages; i++)
u_mplus1.add(m[i], u[i]);
// error estimate
error_estimate = u_m; error_estimate.scale(0.0); // ensures correct size
for (unsigned int i = 0; i < stages; i++)
error_estimate.add(e[i], u[i]);
}
}
| 28.27031 | 117 | 0.613512 | kedingagnumerikunimarburg |
ef35db23d27540f9fc1d94ec79eedfe7ddd43041 | 2,566 | cc | C++ | asylo/platform/primitives/untrusted_primitives.cc | mzohreva/asylo | f6c79ec9775f5579cf5587745f5c64243898e136 | [
"Apache-2.0"
] | null | null | null | asylo/platform/primitives/untrusted_primitives.cc | mzohreva/asylo | f6c79ec9775f5579cf5587745f5c64243898e136 | [
"Apache-2.0"
] | null | null | null | asylo/platform/primitives/untrusted_primitives.cc | mzohreva/asylo | f6c79ec9775f5579cf5587745f5c64243898e136 | [
"Apache-2.0"
] | null | null | null | /*
*
* Copyright 2018 Asylo authors
*
* 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 "asylo/platform/primitives/untrusted_primitives.h"
#include <unistd.h>
#include <cstdint>
#include <memory>
#include <utility>
#include "asylo/platform/primitives/extent.h"
#include "asylo/platform/primitives/primitive_status.h"
#include "asylo/platform/primitives/primitives.h"
#include "asylo/platform/primitives/util/status_conversions.h"
#include "asylo/util/asylo_macros.h"
#include "asylo/util/status.h"
#include "asylo/util/statusor.h"
namespace asylo {
namespace primitives {
thread_local Client *Client::current_client_ = nullptr;
Client::ScopedCurrentClient::~ScopedCurrentClient() {
if (pid_ != getpid()) {
// This is a process forked during an enclave entry, we should not restore
// the old client.
current_client_ = nullptr;
return;
}
current_client_ = saved_client_;
}
void Client::SetCurrentClient() { current_client_ = this; }
Status Client::EnclaveCall(uint64_t selector, MessageWriter *input,
MessageReader *output) {
if (IsClosed()) {
return Status{error::GoogleError::FAILED_PRECONDITION,
"Cannot make an enclave call to a closed enclave."};
}
ScopedCurrentClient scoped_client(this);
return EnclaveCallInternal(selector, input, output);
}
PrimitiveStatus Client::ExitCallback(uint64_t untrusted_selector,
MessageReader *in, MessageWriter *out) {
if (!current_client_->exit_call_provider()) {
return PrimitiveStatus{error::GoogleError::FAILED_PRECONDITION,
"Exit call provider not set yet"};
}
return MakePrimitiveStatus(
current_client_->exit_call_provider()->InvokeExitHandler(
untrusted_selector, in, out, current_client_));
}
// This provides a default, no-op implementation if this function is not
// overridden for any backend.
Status Client::RegisterExitHandlers() { return Status::OkStatus(); }
} // namespace primitives
} // namespace asylo
| 32.481013 | 78 | 0.718628 | mzohreva |
ef36853504465cdbf282b73dc51349ef6e5f84c0 | 4,893 | cpp | C++ | catkin_ws/src/srrg2_core/srrg2_core/src/srrg_data_structures/path_matrix.cpp | laaners/progetto-labiagi_pick_e_delivery | 3453bfbc1dd7562c78ba06c0f79b069b0a952c0e | [
"MIT"
] | null | null | null | catkin_ws/src/srrg2_core/srrg2_core/src/srrg_data_structures/path_matrix.cpp | laaners/progetto-labiagi_pick_e_delivery | 3453bfbc1dd7562c78ba06c0f79b069b0a952c0e | [
"MIT"
] | null | null | null | catkin_ws/src/srrg2_core/srrg2_core/src/srrg_data_structures/path_matrix.cpp | laaners/progetto-labiagi_pick_e_delivery | 3453bfbc1dd7562c78ba06c0f79b069b0a952c0e | [
"MIT"
] | null | null | null | #include "path_matrix.h"
#include <srrg_system_utils/shell_colors.h>
namespace srrg2_core {
using namespace std;
float PathMatrix::maxValue(const Type channel) const {
float max_val = 0;
for (const PathMatrixCell& cell : _data) {
if (!cell.parent) {
continue;
}
switch (channel) {
case Distance:
max_val = std::max(max_val, cell.distance);
break;
case Cost:
max_val = std::max(max_val, cell.cost);
break;
case Parent:
throw std::runtime_error("unhandled enum");
}
}
return max_val;
}
void PathMatrix::toImage(BaseImage& dest_, const Type channel) const {
if (channel == Parent) {
if (dest_.type() != ImageType::TYPE_32SC1) {
throw std::runtime_error("exporting parent only supports type TYPE_32SC1");
}
ImageInt& dest = dynamic_cast<ImageInt&>(dest_);
dest.resize(rows(), cols());
const PathMatrixCell* start = &(_data[0]);
for (size_t i = 0; i < data().size(); ++i) {
int d;
const PathMatrixCell& cell = _data[i];
const PathMatrixCell* parent = cell.parent;
if (!parent) {
d = -1;
} else {
d = (parent - start) % 65536;
}
dest.data()[i] = d;
}
return;
}
if (channel == Distance) {
if (dest_.type() == ImageType::TYPE_32FC1) {
ImageFloat& dest = dynamic_cast<ImageFloat&>(dest_);
dest.resize(rows(), cols());
for (size_t i = 0; i < _data.size(); ++i) {
dest.data()[i] = data()[i].distance;
}
return;
}
if (dest_.type() == ImageType::TYPE_8UC1) {
ImageUInt8& dest = dynamic_cast<ImageUInt8&>(dest_);
dest.resize(rows(), cols());
float md = maxValue(channel);
float id = 255. / sqrt(md);
for (size_t i = 0; i < _data.size(); ++i) {
dest.data()[i] = std::max(255 - id * sqrt(data()[i].distance), 0.f);
}
return;
}
}
if (channel == Cost) {
if (dest_.type() == ImageType::TYPE_32FC1) {
ImageFloat& dest = dynamic_cast<ImageFloat&>(dest_);
dest.resize(rows(), cols());
for (size_t i = 0; i < _data.size(); ++i) {
dest.data()[i] = data()[i].cost;
}
return;
}
if (dest_.type() == ImageType::TYPE_8UC1) {
ImageUInt8& dest = dynamic_cast<ImageUInt8&>(dest_);
dest.resize(rows(), cols());
float md = maxValue(channel) /* / 127*/;
float id = 255. / md;
for (size_t i = 0; i < _data.size(); ++i) {
dest.data()[i] = std::max(255 - id * data()[i].cost, 0.f);
}
return;
}
}
throw std::runtime_error("unsupported export");
}
void PathMatrix::fromImage(const BaseImage& src_, const Type channel) {
if (channel == Parent) {
if (src_.type() != ImageType::TYPE_32SC1) {
throw std::runtime_error("exporting parent only supports type TYPE_32SC1");
}
const ImageInt& src = dynamic_cast<const ImageInt&>(src_);
resize(src.rows(), src.cols());
// const int* start=&(src.data()[0]);
for (size_t i = 0; i < data().size(); ++i) {
PathMatrixCell& cell = _data[i];
size_t idx = src.data()[i];
if (idx < 0 || idx > src.data().size()) {
cell.parent = 0;
cell.distance = std::numeric_limits<float>::max();
continue;
}
cell.parent = &(data()[idx]);
}
return;
}
if (channel == Distance) {
if (src_.type() == ImageType::TYPE_32FC1) {
const ImageFloat& src = dynamic_cast<const ImageFloat&>(src_);
resize(src.rows(), src.cols());
for (size_t i = 0; i < _data.size(); ++i) {
data()[i].distance = src.data()[i];
}
return;
}
if (src_.type() == ImageType::TYPE_8UC1) {
const ImageUInt8& src = dynamic_cast<const ImageUInt8&>(src_);
resize(src.rows(), src.cols());
for (size_t i = 0; i < _data.size(); ++i) {
const int c = 127 - src.data()[i];
_data[i].distance = c * c;
}
return;
}
}
if (channel == Cost) {
if (src_.type() == ImageType::TYPE_32FC1) {
const ImageFloat& src = dynamic_cast<const ImageFloat&>(src_);
resize(src.rows(), src.cols());
for (size_t i = 0; i < _data.size(); ++i) {
_data[i].cost = src.data()[i];
}
return;
}
if (src_.type() == ImageType::TYPE_8UC1) {
const ImageUInt8& src = dynamic_cast<const ImageUInt8&>(src_);
resize(src.rows(), src.cols());
for (size_t i = 0; i < _data.size(); ++i) {
const int c = 255 - src.data()[i];
_data[i].cost = c;
}
return;
}
}
}
} // namespace srrg2_core
| 31.567742 | 83 | 0.517065 | laaners |
ef394300d536a95e9ba8a0a364041c1b17a7529e | 1,047 | hpp | C++ | NYPR/CharacterSegment/NYCharacterPartition.hpp | iwwee/PLR_Vision | bda2384c10546479860bcc351757737385c9a251 | [
"Apache-2.0"
] | 3 | 2021-04-30T06:05:38.000Z | 2022-02-16T08:06:33.000Z | NYPR/CharacterSegment/NYCharacterPartition.hpp | iwwee/PLR_Vision | bda2384c10546479860bcc351757737385c9a251 | [
"Apache-2.0"
] | null | null | null | NYPR/CharacterSegment/NYCharacterPartition.hpp | iwwee/PLR_Vision | bda2384c10546479860bcc351757737385c9a251 | [
"Apache-2.0"
] | 1 | 2021-04-30T06:05:51.000Z | 2021-04-30T06:05:51.000Z | //
// NYCharacterPartition.hpp
// NYPlateRecognition
//
// Created by NathanYu on 28/01/2018.
// Copyright © 2018 NathanYu. All rights reserved.
//
#ifndef NYCharacterPartition_hpp
#define NYCharacterPartition_hpp
#include <stdio.h>
#include <algorithm>
#include "NYPlateDetect.hpp"
class NYCharacterPartition {
public:
// 划分车牌上的字符
vector<NYCharacter> divideCharacters(NYPlate &plate);
private:
void sortCharsRects(vector<cv::Rect> rectVec, vector<cv::Rect> &outRect);
// 清除车牌上的柳钉
bool clearLiuDing(Mat &src);
// 清除车牌上下边框并记录字符上下边缘
void clearTopAndBottomBorder(Mat &src, vector<int> &borderVec);
// 清除车牌左右边框,并记录每个字符的左右侧位置
void clearLeftAndRightBorder(Mat &src, vector<int> &borderVec);
// 判断车牌字符尺寸
bool verifyCharSizes(Mat src);
// 寻找字符分割点
void findSplitPoints(Mat src, vector<int> &charsLoc);
// 将字符Mat调整为标准尺寸
Mat resizeToNormalCharSize(Mat char_mat);
};
#endif /* NYCharacterPartition_hpp */
| 13.96 | 77 | 0.663801 | iwwee |
ef3ada0d1ed4c47e4dcaa1ef310eb0f57b1a94b7 | 5,355 | cc | C++ | veins/src/pveins_providencia/ExampleProvidencia.cc | molguin92/paramics_traci | adcc38785c165ec4b668e2b587f615cf5461e1b0 | [
"BSD-3-Clause"
] | null | null | null | veins/src/pveins_providencia/ExampleProvidencia.cc | molguin92/paramics_traci | adcc38785c165ec4b668e2b587f615cf5461e1b0 | [
"BSD-3-Clause"
] | null | null | null | veins/src/pveins_providencia/ExampleProvidencia.cc | molguin92/paramics_traci | adcc38785c165ec4b668e2b587f615cf5461e1b0 | [
"BSD-3-Clause"
] | null | null | null | //
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include <veins/modules/application/pveins_providencia/ExampleProvidencia.h>
#include "ExtTraCIScenarioManagerLaunchd.h"
#include <veins/modules/mobility/traci/TraCIColor.h>
#include <veins/modules/application/pveins/json.hpp>
#include <veins/modules/mobility/traci/TraCIScenarioManager.h>
#include <cstdlib>
#include <algorithm>
using json = nlohmann::json;
Define_Module(ExampleProvidencia);
//std::mutex ExampleProvidencia::lock;
bool ExampleProvidencia::accident_car_set = false;
void ExampleProvidencia::initialize(int stage)
{
BaseWaveApplLayer::initialize(stage);
switch (stage)
{
case 0:
// init
mobility = Veins::TraCIMobilityAccess().get(getParentModule());
traci = mobility->getCommandInterface();
traciVehicle = mobility->getVehicleCommandInterface();
accident_car = false;
stopped = false;
rerouted = false;
break;
case 1:
{
// schedule selfbeacons
SimTime beginTime = SimTime(uniform(0.001, 1.0));
selfbeacon = new cMessage();
ping_interval = SimTime(0.1);
scheduleAt(simTime() + ping_interval + beginTime, selfbeacon);
accident_road = par("AccidentRoad").stringValue();
accident_distance = par("AccidentDistance").doubleValue();
alternative_road = par("AlternativeRoad").stringValue();
const char* dests = par("AffectedDestinations").stringValue();
warning_interval = par("WarningInterval").longValue();
destinations = cStringTokenizer(dests).asIntVector();
const char* roads_s = par("AffectedRoads").stringValue();
roads = cStringTokenizer(roads_s).asVector();
sent_warnings = 0;
rcvd_warnings = 0;
}
break;
default:
break;
}
}
void ExampleProvidencia::finish()
{
BaseWaveApplLayer::finish();
ExtTraCIScenarioManagerLaunchd* sceman = dynamic_cast<ExtTraCIScenarioManagerLaunchd*>(mobility->getManager());
bool arrived;
if (sceman->shuttingDown())
arrived = false;
else arrived = true;
recordScalar("ArrivedAtDest", arrived);
recordScalar("SentWarnings", sent_warnings);
recordScalar("RcvdWarnings", rcvd_warnings);
}
void ExampleProvidencia::handleSelfMsg(cMessage *msg){
if (!accident_car)
{
if(accident_car_set)
{
cancelAndDelete(selfbeacon);
return;
}
else if (!accident_car_set && traciVehicle->getRoadId() == accident_road)
{
accident_car = true;
accident_car_set = true;
warning_msg = prepareWSM("data", beaconLengthBits, type_CCH, beaconPriority, -1, -1);
warning_msg->setWsmData("WARNING");
}
else if (!accident_car_set)
{
scheduleAt(simTime() + ping_interval, selfbeacon);
return;
}
}
if(accident_car)
{
if(!stopped && traciVehicle->getRoadId() == accident_road && traciVehicle->getLanePosition() >= accident_distance)
{
// stop
traciVehicle->setColor(Veins::TraCIColor::fromTkColor("red"));
traciVehicle->setSpeed(0.0);
stopped = true;
ping_interval = SimTime(warning_interval, SIMTIME_S);
scheduleAt(simTime() + ping_interval, selfbeacon);
}
else if (stopped)
{
// send warning message
sendWSM((WaveShortMessage*)warning_msg->dup());
sent_warnings++;
scheduleAt(simTime() + ping_interval, selfbeacon);
}
else
scheduleAt(simTime() + ping_interval, selfbeacon);
}
}
void ExampleProvidencia::changeRoute()
{
// first, check if we're on a potentially affected road
std::string current_road = traciVehicle->getRoadId();
if (std::find(roads.begin(), roads.end(), current_road) == roads.end())
return;
// check if destination is affected
std::list<std::string> route = traciVehicle->getPlannedRoadIds();
int dest = atoi(&route.back()[0u]);
if(std::find(destinations.begin(), destinations.end(), dest) == destinations.end())
return;
// set new route
std::list<std::string> new_route = { current_road, alternative_road };
if (traciVehicle->changeVehicleRoute(new_route))
{
traciVehicle->setColor(Veins::TraCIColor::fromTkColor("purple"));
rerouted = true;
}
}
void ExampleProvidencia::onData(WaveShortMessage *wsm)
{
if (!accident_car)
{
if(!rerouted)
changeRoute();
rcvd_warnings++;
}
delete wsm;
}
void ExampleProvidencia::onBeacon(WaveShortMessage *wsm){
}
| 30.6 | 122 | 0.64986 | molguin92 |
ef3aefc073928005abc8d0961302b01c4a423a88 | 682 | cpp | C++ | kattis/problems/the_easiest_problem_is_this_one.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-07-16T01:46:38.000Z | 2020-07-16T01:46:38.000Z | kattis/problems/the_easiest_problem_is_this_one.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | null | null | null | kattis/problems/the_easiest_problem_is_this_one.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-05-27T14:30:43.000Z | 2020-05-27T14:30:43.000Z | #include <iostream>
using namespace std;
inline
void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
unsigned int digits_sum(unsigned int number)
{
unsigned int sum {0};
for (unsigned int i {number}; i > 0; i /= 10)
{
sum += i % 10;
}
return sum;
}
int main()
{
use_io_optimizations();
for (unsigned int number; cin >> number && number != 0; )
{
unsigned int sum {digits_sum(number)};
unsigned int multiplier {11};
while (sum != digits_sum(number * multiplier))
{
++multiplier;
}
cout << multiplier << '\n';
}
return 0;
}
| 15.860465 | 61 | 0.555718 | Rkhoiwal |
ef3bcf31d6bf69c0f6f86ef376438b0dbeb757d7 | 5,115 | hpp | C++ | src/main/generic_format/helper.hpp | foobar27/generic_format | a44ce919b9c296ce66c0b54a51a61c884ddb78dd | [
"BSL-1.0"
] | null | null | null | src/main/generic_format/helper.hpp | foobar27/generic_format | a44ce919b9c296ce66c0b54a51a61c884ddb78dd | [
"BSL-1.0"
] | null | null | null | src/main/generic_format/helper.hpp | foobar27/generic_format | a44ce919b9c296ce66c0b54a51a61c884ddb78dd | [
"BSL-1.0"
] | null | null | null | /**
@file
@copyright
Copyright Sebastien Wagener 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#pragma once
#include <type_traits>
#include <functional>
namespace generic_format {
/// @brief Depending on the value of the bool, return T1 or T2.
template <bool b, typename T1, typename T2>
struct conditional_type {
using type = T1;
};
template <typename T1, typename T2>
struct conditional_type<false, T1, T2> {
using type = T2;
};
namespace detail {
// This will get easier with C++14.
template <class Operator, typename... Ts>
struct folder;
template <class Operator>
struct folder<Operator> {
using value_type = typename Operator::result_type;
constexpr folder(Operator)
: result{} { }
value_type result;
};
template <class Operator, typename T>
struct folder<Operator, T> {
using value_type = typename Operator::result_type;
constexpr folder(Operator, T t)
: result{t} { }
value_type result;
};
template <class Operator, typename T1, typename T2, typename... Ts>
struct folder<Operator, T1, T2, Ts...> {
using value_type = typename Operator::result_type;
constexpr folder(Operator op, T1 t1, T2 t2, Ts... ts)
: result{folder<Operator, value_type, Ts...>(op, op(t1, t2), ts...).result} { }
value_type result;
};
template <class T>
struct constexpr_plus {
constexpr T operator()(const T& x, const T& y) const {
return x + y;
}
typedef T first_argument_type;
typedef T second_argument_type;
typedef T result_type;
};
} // end namespace detail
template <class Operator, typename... Ts>
constexpr typename Operator::result_type fold_left(Operator op, Ts... ts) {
return detail::folder<Operator, Ts...>(op, ts...).result;
}
template <class T, typename... Ts>
constexpr T sum(T initial_value, Ts... ts) {
return fold_left(detail::constexpr_plus<T>(), initial_value, ts...);
}
namespace variadic {
template <class... Elements>
struct generic_list { };
/// @brief Insert an element at the end of a generic list.
template <class List, class NewElement>
struct append_element;
template <class NewElement, class... Elements>
struct append_element<generic_list<Elements...>, NewElement> {
using type = generic_list<Elements..., NewElement>;
};
/// @brief Merge two generic lists
template <class List1, class List2>
struct merge_generic_lists;
template <class... Elements>
struct merge_generic_lists<generic_list<Elements...>, generic_list<>> {
using type = generic_list<Elements...>;
};
template <class List1, class Element2, class... Elements2>
struct merge_generic_lists<List1, generic_list<Element2, Elements2...>> {
using new_list1 = typename append_element<List1, Element2>::type;
using new_list2 = generic_list<Elements2...>;
using type = typename merge_generic_lists<new_list1, new_list2>::type;
};
// TODO(sw) document
template <template <class> class Function, class List, class Acc = generic_list<>>
struct transform;
template <template <class> class Function, class Acc>
struct transform<Function, generic_list<>, Acc> {
using type = Acc;
};
template <template <class> class Function, class Acc, class Element, class... Elements>
struct transform<Function, generic_list<Element, Elements...>, Acc> {
private:
using new_acc = typename append_element<Acc, typename Function<Element>::type>::type;
using new_list = generic_list<Elements...>;
public:
using type = typename transform<Function, new_list, new_acc>::type;
};
/** @brief Tests whether a predicate holds for some variadic arguments.
*
* Provides the member constant value equal true if Predicate holds for at least one argument, else value is false.
*/
template <template <class> class Predicate, class... Args>
struct for_any : std::false_type { };
template <template <class> class Predicate, class Arg, class... Args>
struct for_any<Predicate, Arg, Args...> : std::integral_constant<bool, Predicate<Arg>::value || for_any<Predicate, Args...>::value> { };
namespace detail {
template <template <class> class Predicate, std::size_t N, class... Args>
struct index_of_helper : std::integral_constant<std::size_t, N> { };
template <template <class> class Predicate, std::size_t N, class Arg, class... Args>
struct index_of_helper<Predicate, N, Arg, Args...>
: std::integral_constant<std::size_t, Predicate<Arg>::value ? N : index_of_helper<Predicate, N + 1, Args...>::value> { };
} // end namespace detail
/** @brief Finds an argument matching a predicate.
*
* Provides the index of the first occurrence of Args satisfying Predicate.
* Fails at compile-time if not argument matches the predicate.
*/
template <template <class> class Predicate, class... Args>
struct index_of {
static constexpr auto value = detail::index_of_helper<Predicate, 0, Args...>::value;
static_assert(value < sizeof...(Args), "Item not found in variadic argument list!");
};
} // end namespace variadic
} // end namespace generic_format
| 31.189024 | 136 | 0.709677 | foobar27 |
ef3c43278e3760f822c1bea5894813bae7deb9b6 | 94 | cpp | C++ | bin/lib/base/main.cpp | johnsonyl/cpps | ed91be2c1107e3cfa8e91d159be81931eacfec19 | [
"MIT"
] | 18 | 2017-09-01T04:59:23.000Z | 2021-09-23T06:42:50.000Z | bin/lib/base/main.cpp | johnsonyl/cpps | ed91be2c1107e3cfa8e91d159be81931eacfec19 | [
"MIT"
] | null | null | null | bin/lib/base/main.cpp | johnsonyl/cpps | ed91be2c1107e3cfa8e91d159be81931eacfec19 | [
"MIT"
] | 4 | 2017-06-15T08:46:07.000Z | 2021-06-09T15:03:55.000Z | #include <lib/base/colorprint.cpp>
#include <lib/base/io.cpp>
#include <lib/base/thread.cpp> | 31.333333 | 35 | 0.734043 | johnsonyl |
ef3cc80b1bd0993ec639212984eb355dd5bcf1af | 490 | cpp | C++ | GameObject.cpp | JetBrains/cpp-russia-2017-clion | 9322bb9ae34476e744f38c61f0ef89bed26e60ba | [
"Apache-2.0"
] | 7 | 2017-05-15T12:31:54.000Z | 2021-11-08T09:49:53.000Z | GameObject.cpp | JetBrains/cpp-russia-2017-clion | 9322bb9ae34476e744f38c61f0ef89bed26e60ba | [
"Apache-2.0"
] | null | null | null | GameObject.cpp | JetBrains/cpp-russia-2017-clion | 9322bb9ae34476e744f38c61f0ef89bed26e60ba | [
"Apache-2.0"
] | 4 | 2019-02-03T17:49:24.000Z | 2022-03-19T06:44:48.000Z | #include "Ball.h"
#include "GameObject.h"
GameObject::GameObject(const QPointF& pos, const QPointF& speed) :
pos_(pos), speed_(speed) {}
const QPointF& GameObject::getPos() const {
return pos_;
}
const QPointF& GameObject::getSpeed() const {
return speed_;
}
void GameObject::calc(int msec) {
pos_ += speed_ * (msec / 1000.);
}
void GameObject::setPos(const QPointF& pos) {
pos_ = pos;
}
void GameObject::setSpeed(const QPointF& speed) {
speed_ = speed;
}
| 18.846154 | 66 | 0.663265 | JetBrains |
ef4236b6fc400ab751ba4cfcec44914237579f1c | 1,080 | cpp | C++ | external/keko_enhanced_movement/babe_em/func/config.cpp | kellerkompanie/kellerkompanie-mods | f15704710f77ba6c018c486d95cac4f7749d33b8 | [
"MIT"
] | 6 | 2018-05-05T22:28:57.000Z | 2019-07-06T08:46:51.000Z | external/keko_enhanced_movement/babe_em/func/config.cpp | Schwaggot/kellerkompanie-mods | 7a389e49e3675866dbde1b317a44892926976e9d | [
"MIT"
] | 107 | 2018-04-11T19:42:27.000Z | 2019-09-13T19:05:31.000Z | external/keko_enhanced_movement/babe_em/func/config.cpp | kellerkompanie/kellerkompanie-mods | f15704710f77ba6c018c486d95cac4f7749d33b8 | [
"MIT"
] | 3 | 2018-10-03T11:54:46.000Z | 2019-02-28T13:30:16.000Z | ////////////////////////////////////////////////////////////////////
//DeRap: babe_em\func\config.bin
//Produced from mikero's Dos Tools Dll version 6.44
//'now' is Tue Jun 12 14:55:49 2018 : 'file' last modified on Thu May 10 19:35:42 2018
//http://dev-heaven.net/projects/list_files/mikero-pbodll
////////////////////////////////////////////////////////////////////
#define _ARMA_
class DefaultEventhandlers;
class CfgPatches
{
class BABE_EM_FNC
{
units[] = {};
weapons[] = {};
requiredVersion = 0.1;
requiredAddons[] = {"A3_BaseConfig_F","babe_core_fnc"};
};
};
class CfgFunctions
{
class BABE_EM
{
tag = "BABE_EM";
class core
{
file = "\babe_em\func\core";
class init{};
};
class EH
{
file = "\babe_em\func\EH";
class handledamage_nofd{};
class animdone{};
};
class move
{
file = "\babe_em\func\mov";
class em{};
class exec_em{};
class finish_em{};
class exec_drop{};
class finish_drop{};
class jump{};
class jump_only{};
class detect{};
class detect_cl_only{};
class walkonstuff{};
};
};
};
| 20.377358 | 86 | 0.558333 | kellerkompanie |
ef43b35466b5d8e230902957ac50c0ebe03f5326 | 1,961 | cpp | C++ | websocket_core_client.cpp | branislavhesko/Websocket_synchronization | 0adc0e336d300130574dd71eb840c9448c954572 | [
"Apache-2.0"
] | null | null | null | websocket_core_client.cpp | branislavhesko/Websocket_synchronization | 0adc0e336d300130574dd71eb840c9448c954572 | [
"Apache-2.0"
] | null | null | null | websocket_core_client.cpp | branislavhesko/Websocket_synchronization | 0adc0e336d300130574dd71eb840c9448c954572 | [
"Apache-2.0"
] | null | null | null | //
// Created by brani on 14.02.20.
//
#include <iostream>
#include <ixwebsocket/IXWebSocket.h>
#include <chrono>
#include <thread>
#include <string>
#include <queue>
#include "json.hpp"
#include "request_handler.hpp"
int main() {
using namespace std::chrono_literals;
using json = nlohmann::json;
bool server_running = true;
// Our websocket object
ix::WebSocket webSocket;
std::string url("ws://127.0.0.1:3000");
webSocket.setUrl(url);
// Optional heart beat, sent every 45 seconds when there is not any traffic
// to make sure that load balancers do not kill an idle connection.
webSocket.setHeartBeatPeriod(45);
// Per message deflate connection is enabled by default. You can tweak its parameters or disable it
webSocket.disablePerMessageDeflate();
// Setup a callback to be fired when a message or an event (open, close, error) is received
webSocket.setOnMessageCallback([&webSocket](const ix::WebSocketMessagePtr &msg) {
if (msg->type == ix::WebSocketMessageType::Message) {
std::cout << "CLIENT RECEIVED: " << msg->str << std::endl;
std::string action, method;
std::tie(action, method) = GeneralRequestHandler::parse_request(json::parse(msg->str)["action"]);
webSocket.send(SupportedRequest().get_request(method)(msg->str));
}
}
);
// Now that our callback is setup, we can start our background thread and receive messages
webSocket.start();
webSocket.connect(1);
// Send a message to the server (default to TEXT mode)
while(server_running) {
std::this_thread::sleep_for(300ms);
webSocket.send("I want a request!");
}
// ... finally ...
// Stop the connection
webSocket.stop();
} | 33.237288 | 140 | 0.600714 | branislavhesko |
ef44804e128e517c125819af527d098733abacf0 | 1,670 | cpp | C++ | inetsrv/intlwb/chs2/src/chsbrkr.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/intlwb/chs2/src/chsbrkr.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/intlwb/chs2/src/chsbrkr.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*============================================================================
Microsoft Simplified Chinese WordBreaker
Microsoft Confidential.
Copyright 1997-1999 Microsoft Corporation. All Rights Reserved.
Component: DLL Main and exported functions
Purpose: DLL Main and exported functions
Remarks:
Owner: i-shdong@microsoft.com
Platform: Win32
Revise: First created by: i-shdong 11/17/1999
============================================================================*/
#include "MyAfx.h"
#include "Registry.h"
#include "CFactory.h"
HINSTANCE v_hInst = NULL;
// DLL module information
BOOL APIENTRY DllMain(HINSTANCE hModule,
DWORD dwReason,
void* lpReserved )
{
switch (dwReason) {
case DLL_PROCESS_ATTACH:
CFactory::s_hModule = hModule ;
v_hInst = hModule;
DisableThreadLibraryCalls(hModule);
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE ;
}
// Exported functions
STDAPI DllCanUnloadNow()
{
return CFactory::CanUnloadNow() ;
}
// Get class factory
STDAPI DllGetClassObject(const CLSID& clsid,
const IID& iid,
void** ppv)
{
return CFactory::GetClassObject(clsid, iid, ppv) ;
}
// Server registration
STDAPI DllRegisterServer()
{
HRESULT hr;
hr = CFactory::RegisterAll() ;
if (hr != S_OK) {
return hr;
}
return hr;
}
STDAPI DllUnregisterServer()
{
HRESULT hr;
hr = CFactory::UnregisterAll() ;
if (hr != S_OK) {
return hr;
}
return hr;
}
| 22.266667 | 79 | 0.542515 | npocmaka |
ef471770ed2b53556fee90c2e5eb8a7d224ffb83 | 801 | hpp | C++ | stan/math/opencl/rev/as_column_vector_or_scalar.hpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | stan/math/opencl/rev/as_column_vector_or_scalar.hpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | stan/math/opencl/rev/as_column_vector_or_scalar.hpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_MATH_OPENCL_REV_AS_COLUMN_VECTOR_OR_SCALAR_HPP
#define STAN_MATH_OPENCL_REV_AS_COLUMN_VECTOR_OR_SCALAR_HPP
#ifdef STAN_OPENCL
#include <stan/math/opencl/kernel_generator.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/rev/core.hpp>
namespace stan {
namespace math {
/**
* Converts kernel generator expression row or column vector to a column vector.
*
* @tparam T kernel generator expression.
* @param m Specified input.
* @return input converted to a column vector.
*/
template <typename T,
require_all_nonscalar_prim_or_rev_kernel_expression_t<T>* = nullptr,
require_any_var_t<T>* = nullptr>
inline auto as_column_vector_or_scalar(const T& m) {
return m.as_column_vector_or_scalar();
}
} // namespace math
} // namespace stan
#endif
#endif
| 25.83871 | 80 | 0.765293 | LaudateCorpus1 |
ef48161b9469a60d2066b60b1488814f11acffaf | 7,616 | hpp | C++ | Source/FFTMeter.hpp | hotwatermorning/LevelMeter | b052f51445870ea9135fcd65bc64542e237ac81c | [
"MIT"
] | 7 | 2016-08-04T08:30:01.000Z | 2021-07-13T02:16:20.000Z | Source/FFTMeter.hpp | hotwatermorning/LevelMeter | b052f51445870ea9135fcd65bc64542e237ac81c | [
"MIT"
] | null | null | null | Source/FFTMeter.hpp | hotwatermorning/LevelMeter | b052f51445870ea9135fcd65bc64542e237ac81c | [
"MIT"
] | null | null | null | /*
==============================================================================
FFTMeter.h
Created: 19 Jan 2016 4:11:43pm
Author: yuasa
==============================================================================
*/
#ifndef FFTMETER_H_INCLUDED
#define FFTMETER_H_INCLUDED
#include <limits>
#include "./ILevelMeter.hpp"
#include "../JuceLibraryCode/JuceHeader.h"
#include "./ZeroIterator.hpp"
#include "./PeakHoldValue.hpp"
#include "./MovingAverageValue.hpp"
#include "./Linear_dB.hpp"
//! FFTメーターを実現するクラス
struct FFTMeter
: public ILevelMeter
{
typedef int millisec;
typedef double dB_t;
static int const kDefaultReleaseSpeed = -96 / 2;
static dB_t GetLowestLevel()
{
return std::numeric_limits<dB_t>::lowest();
}
//! コンストラクタ
/*!
@param release_speed ピークホールドしたピーク値が、peak_hold_time後に一秒間に下降するスピード
*/
FFTMeter(int sampling_rate, int order, int moving_average, millisec peak_hold_time, dB_t release_speed = kDefaultReleaseSpeed)
: order_(order)
, fft_()
{
sampling_rate_ = sampling_rate;
moving_average_ = moving_average;
peak_hold_time_ = peak_hold_time;
release_speed_ = release_speed;
SetFFTOrder(order);
}
size_t GetSize() const
{
return fft_->getSize();
}
void SetSamples(float const *samples, size_t num_samples) override
{
doSetSample(samples, samples + num_samples);
}
void SetSamples(double const *samples, size_t num_samples) override
{
doSetSample(samples, samples + num_samples);
}
void Consume(size_t num_samples) override
{
doSetSample(ZeroIterator(num_samples), ZeroIterator());
}
void SetFFTOrder(int order)
{
fft_ = std::make_unique<juce::dsp::FFT>(order);
assert(order >= 6); // 64サンプル以上
fft_work_.clear();
fft_output_.clear();
fft_work_.reserve(pow(2, order));
fft_output_.resize(pow(2, order));
window_.resize(pow(2, order));
bool use_window_function = true;
if(use_window_function) {
//! hanning window
for(int i = 0; i < window_.size(); ++i) {
window_[i] = 0.5 - 0.5 * cos(2 * juce::MathConstants<double>::pi * i / (window_.size() - 1));
}
double amplitude_correction_factor = 0;
double power_correction_factor = 0;
for(int i = 0; i < window_.size(); ++i) {
amplitude_correction_factor += window_[i];
power_correction_factor += (window_[i] * window_[i]);
}
amplitude_correction_factor = amplitude_correction_factor / GetSize();
power_correction_factor = power_correction_factor / GetSize();
//! 窓関数を掛けたことでFFT後の信号のパワーが変わってしまうのを補正
for(int i = 0; i < window_.size(); ++i) {
window_[i] /= amplitude_correction_factor;
}
enbw_correction_factor_ = power_correction_factor / (amplitude_correction_factor * amplitude_correction_factor);
} else {
std::fill(window_.begin(), window_.end(), 1.0);
enbw_correction_factor_ = 1.0;
}
current_spectrum_.resize(pow(2, order), MovingAverageValue<float>(moving_average_, -640));
peak_spectrum_.resize(pow(2, order), PeakHoldValue(sampling_rate_, peak_hold_time_, release_speed_));
}
int GetMovingAverage() const
{
return moving_average_;
}
void SetMovingAverage(int moving_average)
{
moving_average_ = moving_average;
for(auto &a: current_spectrum_) {
a = MovingAverageValue<float>(moving_average, -640);
}
}
void SetPeakHoldTime(millisec peak_hold_time)
{
peak_hold_time_ = peak_hold_time;
for(auto &peak: peak_spectrum_) {
peak.SetPeakHoldTime(peak_hold_time_);
}
}
millisec GetPeakHoldTime() const
{
return peak_hold_time_;
}
dB_t GetReleaseSpeed() const
{
return release_speed_;
}
void SetReleaseSpeed(dB_t release_speed)
{
release_speed_ = release_speed;
}
//! 指定した周波数ビンの移動平均されたパワースペクトルを取得
dB_t GetSpectrum(int index)
{
return current_spectrum_[index].GetAverage();
}
//! 指定した周波数ビンのパワースペクトルのピークホールド値を取得
dB_t GetPeakSpectrum(int index)
{
return peak_spectrum_[index].GetPeak();
}
private:
template<class RandomAccessIterator>
void doSetSample(RandomAccessIterator begin, RandomAccessIterator end)
{
for(auto it = begin; it != end; ++it) {
juce::dsp::Complex<float> c = { (float)(*it), 0.0 };
fft_work_.push_back(c);
if(fft_work_.size() == GetSize()) {
double const power_scaling = GetSize() * GetSize();
double const freq_step = sampling_rate_ / (double)GetSize();
//! 虚数部分のデータには0を埋める
static juce::dsp::Complex<float> const zero = { 0.0, 0.0 };
std::fill(fft_output_.begin(), fft_output_.end(), zero);
//! windowing
for(int i = 0; i < GetSize(); ++i) {
fft_work_[i].real(fft_work_[i].real() * window_[i]);
}
//! FFT実行
fft_->perform(fft_work_.data(), fft_output_.data(), false);
for(int i = 0; i < GetSize() / 2; ++i) {
//! スペクトルの絶対値を計算
auto point_abs = juce_hypot(fft_output_[i].real(), fft_output_[i].imag());
//! FFTの次数や窓関数によるパワー値のズレを補正
float power = point_abs / (power_scaling * freq_step * enbw_correction_factor_);
//! 片側パワースペクトルにする
if(i != 0 && i != GetSize() / 2 - 1) {
power *= 2;
}
float const spectrum = sqrt(power);
current_spectrum_[i].Push(linear_to_dB(spectrum));
peak_spectrum_[i].PushPeakValue(linear_to_dB(spectrum));
}
fft_work_.clear();
} else {
//! FFTを実行していないときは、ピークホールドの状態のみ更新する
for(int i = 0; i < GetSize() / 2; ++i) {
peak_spectrum_[i].PushPeakValue(GetLowestLevel());
}
}
}
}
int sampling_rate_;
int order_;
std::unique_ptr<juce::dsp::FFT> fft_;
std::vector<juce::dsp::Complex<float>> fft_work_;
std::vector<juce::dsp::Complex<float>> fft_output_;
std::vector<float> window_;
double amplitude_correction_factor_;
// 参考: http://ecd-assist.com/index.php?%E7%AA%93%E9%96%A2%E6%95%B0%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6
double enbw_correction_factor_;
std::vector<MovingAverageValue<float>> current_spectrum_;
std::vector<PeakHoldValue> peak_spectrum_;
dB_t release_speed_;
millisec peak_hold_time_;
int moving_average_;
};
#endif // FFTMETER_H_INCLUDED
| 31.733333 | 131 | 0.531119 | hotwatermorning |
ef4c6326f5e4f95cbc981302de52df5defec4561 | 1,777 | cpp | C++ | tests/TcpServer_test.cpp | yangzecai/Web-Server | 8a26bc1ad7db5c3e4825fc8c37d83f53d0c98f7f | [
"MIT"
] | 2 | 2021-08-24T00:35:42.000Z | 2022-02-23T13:20:23.000Z | tests/TcpServer_test.cpp | yangzecai/Web-Server | 8a26bc1ad7db5c3e4825fc8c37d83f53d0c98f7f | [
"MIT"
] | null | null | null | tests/TcpServer_test.cpp | yangzecai/Web-Server | 8a26bc1ad7db5c3e4825fc8c37d83f53d0c98f7f | [
"MIT"
] | null | null | null | #include "Address.h"
#include "EventLoop.h"
#include "Log.h"
#include "TcpConnection.h"
#include "TcpServer.h"
#include <cstdio>
#include <chrono>
#include <unistd.h>
EventLoop* g_loop;
std::string message1;
std::string message2;
void onConnection(const TcpConnectionPtr& conn)
{
printf("onConnection(): new connection from %s\n",
conn->getClientAddr().getAddressStr().c_str());
conn->send(message1);
}
void onClose(const TcpConnectionPtr& conn)
{
printf("onClose() : disconnect connection from %s\n",
conn->getClientAddr().getAddressStr().c_str());
}
void onMessage(const TcpConnectionPtr& conn, Buffer& recvBuffer)
{
printf("onMessage(): received %zd bytes from connection [%s]\n",
recvBuffer.getReadableBytes(),
conn->getClientAddr().getAddressStr().c_str());
recvBuffer.retrieveAll();
}
void onWriteComplete(const TcpConnectionPtr& conn)
{
// printf("onWriteComplete()\n");
conn->send(message1);
}
int main(int argc, char* argv[])
{
log::setLevel(log::TRACE);
printf("main(): pid = %d\n", ::getpid());
int len1 = 100;
int len2 = 200;
if (argc > 2) {
len1 = atoi(argv[1]);
len2 = atoi(argv[2]);
}
message1.resize(len1);
message2.resize(len2);
std::fill(message1.begin(), message2.end(), 'A');
std::fill(message2.begin(), message2.end(), 'B');
Address listenAddr(Address::createIPv4Address(9981));
EventLoop loop;
g_loop = &loop;
TcpServer server(&loop, listenAddr);
server.setConnectionCallback(onConnection);
server.setWriteCompleteCallback(onWriteComplete);
server.setCloseCallback(onClose);
server.setMessageCallback(onMessage);
server.setThreadNum(1);
server.start();
loop.loop();
} | 23.381579 | 68 | 0.65785 | yangzecai |
ef4ceed48da58f8e2e578d1fbb0801b4caf7233c | 9,222 | cpp | C++ | 3rd_party_libs/chai3d-2.1/src/devices/CVirtualDevice.cpp | atp42/jks-ros-pkg | 367fc00f2a9699f33d05c7957d319a80337f1ed4 | [
"FTL"
] | 3 | 2017-02-02T13:27:45.000Z | 2018-06-17T11:52:13.000Z | 3rd_party_libs/chai3d-2.1/src/devices/CVirtualDevice.cpp | salisbury-robotics/jks-ros-pkg | 367fc00f2a9699f33d05c7957d319a80337f1ed4 | [
"FTL"
] | null | null | null | 3rd_party_libs/chai3d-2.1/src/devices/CVirtualDevice.cpp | salisbury-robotics/jks-ros-pkg | 367fc00f2a9699f33d05c7957d319a80337f1ed4 | [
"FTL"
] | null | null | null | //===========================================================================
/*
This file is part of the CHAI 3D visualization and haptics libraries.
Copyright (C) 2003-2010 by CHAI 3D. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License("GPL") version 2
as published by the Free Software Foundation.
For using the CHAI 3D libraries with software that can not be combined
with the GNU GPL, and for taking advantage of the additional benefits
of our support services, please contact CHAI 3D about acquiring a
Professional Edition License.
\author <http://www.chai3d.org>
\author Francois Conti
\version 2.1.0 $Rev: 322 $
*/
//===========================================================================
//---------------------------------------------------------------------------
#include "extras/CGlobals.h"
#include "devices/CVirtualDevice.h"
//---------------------------------------------------------------------------
#if defined(_ENABLE_VIRTUAL_DEVICE_SUPPORT)
//---------------------------------------------------------------------------
//===========================================================================
/*!
Constructor of cVirtualDevice.
\fn cVirtualDevice::cVirtualDevice()
*/
//===========================================================================
cVirtualDevice::cVirtualDevice()
{
// settings:
m_specifications.m_manufacturerName = "CHAI 3D";
m_specifications.m_modelName = "virtual";
m_specifications.m_maxForce = 10.0; // [N]
m_specifications.m_maxForceStiffness = 2000.0; // [N/m]
m_specifications.m_maxTorque = 0.0; // [N*m]
m_specifications.m_maxTorqueStiffness = 0.0; // [N*m/Rad]
m_specifications.m_maxGripperTorque = 0.0; // [N]
m_specifications.m_maxGripperTorqueStiffness = 0.0; // [N/m]
m_specifications.m_workspaceRadius = 0.15; // [m]
m_specifications.m_sensedPosition = true;
m_specifications.m_sensedRotation = false;
m_specifications.m_sensedGripper = false;
m_specifications.m_actuatedPosition = true;
m_specifications.m_actuatedRotation = false;
m_specifications.m_actuatedGripper = false;
m_specifications.m_leftHand = true;
m_specifications.m_rightHand = true;
m_systemAvailable = false;
m_systemReady = false;
// search for virtual device
m_hMapFile = OpenFileMapping(
FILE_MAP_ALL_ACCESS,
FALSE,
"dhdVirtual");
// no virtual device available
if (m_hMapFile == NULL)
{
m_systemReady = false;
m_systemAvailable = false;
return;
}
// open connection to virtual device
m_lpMapAddress = MapViewOfFile(
m_hMapFile,
FILE_MAP_ALL_ACCESS,
0,
0,
0);
// check whether connection succeeded
if (m_lpMapAddress == NULL)
{
m_systemReady = false;
m_systemAvailable = false;
return;
}
// map memory
m_pDevice = (cVirtualDeviceData*)m_lpMapAddress;
// virtual device is available
m_systemAvailable = true;
}
//===========================================================================
/*!
Destructor of cVirtualDevice.
\fn cVirtualDevice::~cVirtualDevice()
*/
//===========================================================================
cVirtualDevice::~cVirtualDevice()
{
if (m_systemAvailable)
{
CloseHandle(m_hMapFile);
}
}
//===========================================================================
/*!
Open connection to virtual device.
\fn int cVirtualDevice::open()
\return Return 0 is operation succeeds, -1 if an error occurs.
*/
//===========================================================================
int cVirtualDevice::open()
{
if (m_systemAvailable)
{
m_systemReady = true;
}
return (0);
}
//===========================================================================
/*!
Close connection to virtual device
\fn int cVirtualDevice::close()
\return Return 0 is operation succeeds, -1 if an error occurs.
*/
//===========================================================================
int cVirtualDevice::close()
{
m_systemReady = false;
return (0);
}
//===========================================================================
/*!
Initialize virtual device. a_resetEncoders is ignored
\fn void cVirtualDevice::initialize(const bool a_resetEncoders=false)
\param a_resetEncoders ignored
\return Return 0 is operation succeeds, -1 if an error occurs.
*/
//===========================================================================
int cVirtualDevice::initialize(const bool a_resetEncoders)
{
if (m_systemReady)
{
return (0);
}
else
{
return (-1);
}
}
//===========================================================================
/*!
Returns the number of devices available from this class of device.
\fn unsigned int cVirtualDevice::getNumDevices()
\return Returns the result
*/
//===========================================================================
unsigned int cVirtualDevice::getNumDevices()
{
// only one device can be enabled
int result;
if (m_systemAvailable)
{
result = 1;
}
else
{
result = 0;
}
return (result);
}
//===========================================================================
/*!
Read the position of the device. Units are meters [m].
\fn int cVirtualDevice::getPosition(cVector3d& a_position)
\param a_position Return value.
*/
//===========================================================================
int cVirtualDevice::getPosition(cVector3d& a_position)
{
if (!m_systemReady)
{
a_position.set(0, 0, 0);
return (-1);
}
double x,y,z;
x = (double)(*m_pDevice).PosX;
y = (double)(*m_pDevice).PosY;
z = (double)(*m_pDevice).PosZ;
a_position.set(x, y, z);
return (0);
}
//===========================================================================
/*!
Read the orientation frame of the device end-effector.
\fn int cVirtualDevice::getRotation(cMatrix3d& a_rotation)
\param a_rotation Return value.
*/
//===========================================================================
int cVirtualDevice::getRotation(cMatrix3d& a_rotation)
{
if (!m_systemReady)
{
a_rotation.identity();
return (-1);
}
a_rotation.identity();
return (0);
}
//===========================================================================
/*!
Send a force [N] to the haptic device.
\fn int cVirtualDevice::setForce(cVector3d& a_force)
\param a_force Force command to be applied to device.
*/
//===========================================================================
int cVirtualDevice::setForce(cVector3d& a_force)
{
if (!m_systemReady) return (-1);
((*m_pDevice).ForceX) = a_force.x;
((*m_pDevice).ForceY) = a_force.y;
((*m_pDevice).ForceZ) = a_force.z;
return (0);
}
//===========================================================================
/*!
Return the last force sent to the device.
\fn int cVirtualDevice::getForce(cVector3d& a_force)
\param a_force Return value.
*/
//===========================================================================
int cVirtualDevice::getForce(cVector3d& a_force)
{
if (!m_systemReady)
{
a_force.set(0,0,0);
return (-1);
}
a_force.x = ((*m_pDevice).ForceX);
a_force.y = ((*m_pDevice).ForceY);
a_force.z = ((*m_pDevice).ForceZ);
return (0);
}
//===========================================================================
/*!
Read the status of the user switch [\b true = \e ON / \b false = \e OFF].
\fn int cVirtualDevice::getUserSwitch(int a_switchIndex, bool& a_status)
\param a_switchIndex index number of the switch.
\param a_status result value from reading the selected input switch.
*/
//===========================================================================
int cVirtualDevice::getUserSwitch(int a_switchIndex, bool& a_status)
{
if (!m_systemReady)
{
a_status = false;
return (-1);
}
a_status = ((bool)(*m_pDevice).Button0);
return (0);
}
//---------------------------------------------------------------------------
#endif // _ENABLE_VIRTUAL_DEVICE_SUPPORT
//---------------------------------------------------------------------------
| 29.557692 | 81 | 0.447951 | atp42 |
ef4fb0837a804f8aa1b82254932d0c1492cd9418 | 20 | cpp | C++ | vendor/kult/kult.cpp | emdavoca/wee | 60344dd646a2e27d1cfdb1131dd679558d9cfa2b | [
"MIT"
] | 1 | 2019-02-11T12:18:39.000Z | 2019-02-11T12:18:39.000Z | vendor/kult/kult.cpp | emdavoca/wee | 60344dd646a2e27d1cfdb1131dd679558d9cfa2b | [
"MIT"
] | 1 | 2021-11-11T07:27:58.000Z | 2021-11-11T07:27:58.000Z | vendor/kult/kult.cpp | emdavoca/wee | 60344dd646a2e27d1cfdb1131dd679558d9cfa2b | [
"MIT"
] | 1 | 2021-11-11T07:22:12.000Z | 2021-11-11T07:22:12.000Z | #include "kult.hpp"
| 10 | 19 | 0.7 | emdavoca |
ef513d30412be923701d932668aa2e1a39d3828c | 3,012 | hh | C++ | src/faodel-common/BootstrapImplementation.hh | faodel/faodel | ef2bd8ff335433e695eb561d7ecd44f233e58bf0 | [
"MIT"
] | 2 | 2019-01-25T21:21:07.000Z | 2021-04-29T17:24:00.000Z | src/faodel-common/BootstrapImplementation.hh | faodel/faodel | ef2bd8ff335433e695eb561d7ecd44f233e58bf0 | [
"MIT"
] | 8 | 2018-10-09T14:35:30.000Z | 2020-09-30T20:09:42.000Z | src/faodel-common/BootstrapImplementation.hh | faodel/faodel | ef2bd8ff335433e695eb561d7ecd44f233e58bf0 | [
"MIT"
] | 2 | 2019-04-23T19:01:36.000Z | 2021-05-11T07:44:55.000Z | // Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
#ifndef FAODEL_COMMON_BOOTSTRAPINTERNAL_HH
#define FAODEL_COMMON_BOOTSTRAPINTERNAL_HH
#include <string>
#include <map>
#include <vector>
#include "faodel-common/Bootstrap.hh"
#include "faodel-common/Configuration.hh"
#include "faodel-common/LoggingInterface.hh"
namespace faodel {
namespace bootstrap {
namespace internal {
//Holds info on each component
typedef struct {
std::string name;
std::vector<std::string> requires;
std::vector<std::string> optional;
fn_init init_function;
fn_start start_function;
fn_fini fini_function;
BootstrapInterface *optional_component_ptr;
} bstrap_t;
/**
* @brief A class for registering how FAODEL components are started/stopped
*/
class Bootstrap
: public LoggingInterface {
public:
Bootstrap();
~Bootstrap() override;
void SetNodeID(NodeID nodeid) { my_node_id = nodeid; }
void RegisterComponent(std::string name,
std::vector<std::string> requires,
std::vector<std::string> optional,
fn_init init_function,
fn_start start_function,
fn_fini fini_function,
bool allow_overwrites);
void RegisterComponent(BootstrapInterface *component, bool allow_overwrites);
BootstrapInterface * GetComponentPointer(std::string name);
bool CheckDependencies(std::string *info_message=nullptr);
std::vector<std::string> GetStartupOrder();
bool Init(const Configuration &config);
void Start();
void Start(const Configuration &config); //Init and Start
void Finish(bool clear_list_of_bootstrap_users);
std::string GetState() const;
bool IsStarted() const { return state==State::STARTED; }
Configuration GetConfiguration() const { return configuration; }
int GetNumberOfUsers() const;
bool HasComponent(const std::string &component_name) const;
void dumpStatus() const;
void dumpInfo(faodel::ReplyStream &rs) const;
private:
void finish_(bool clear_list_of_bootstrap_users);
Configuration configuration;
bool show_config_at_init;
bool halt_on_shutdown;
bool status_on_shutdown;
bool mpisyncstop_enabled;
uint64_t sleep_seconds_before_shutdown;
nodeid_t my_node_id;
bool expandDependencies(std::map<std::string, std::set<std::string>> &dep_lut,
std::stringstream &emsg);
bool sortDependencies(std::stringstream &emsg);
std::vector<bstrap_t> bstraps;
faodel::MutexWrapper *state_mutex; //!< Protects num_init_callers and State
int num_init_callers; //!< Number of entities that have called init (or start)
enum class State { UNINITIALIZED, INITIALIZED, STARTED };
State state;
};
} // namespace internal
} // namespace bootstrap
} // namespace faodel
#endif // FAODEL_COMMON_BOOTSTRAPINTERNAL_HH
| 28.149533 | 80 | 0.722112 | faodel |
ef571c5b57d325d297c173d275539cd1416142e0 | 1,117 | cpp | C++ | eventset.cpp | rao1219/qt-SON | b8a28c8358dda55c3e5e01d199f2276b71dc2646 | [
"MIT"
] | 11 | 2015-08-31T15:53:43.000Z | 2021-12-24T13:25:05.000Z | eventset.cpp | rao1219/qt-SON | b8a28c8358dda55c3e5e01d199f2276b71dc2646 | [
"MIT"
] | null | null | null | eventset.cpp | rao1219/qt-SON | b8a28c8358dda55c3e5e01d199f2276b71dc2646 | [
"MIT"
] | 5 | 2017-06-30T07:18:44.000Z | 2020-04-17T16:08:15.000Z | #include "eventset.h"
#include "ui_eventset.h"
#include <QDebug>
eventSet::eventSet(QWidget *parent) :
QDialog(parent),
ui(new Ui::eventSet)
{
ui->setupUi(this);
QPalette bgpal = palette();
bgpal.setColor (QPalette::Background, QColor (29, 15, 29));
//bgpal.setColor (QPalette::Background, Qt::transparent);
bgpal.setColor (QPalette::Foreground, QColor(255,255,255,255));
setPalette (bgpal);
this->accepted=false;
ui->comboBox->addItem("User number increases suddenly in some area.");
ui->comboBox->addItem("User number decreases suddenly in some area.");
ui->comboBox->addItem("Signals dies away suddenly in some area.");
ui->comboBox->addItem("AP's frequency changes suddenly in some area");
ui->comboBox_2->addItem("轻微");
ui->comboBox_2->addItem("正常");
ui->comboBox_2->addItem("严重");
}
eventSet::~eventSet()
{
delete ui;
}
void eventSet::on_buttonBox_accepted()
{
this->accepted=true;
this->eventitem=ui->comboBox->currentText();
this->serious=ui->comboBox_2->currentIndex();
this->eventType=ui->comboBox->currentIndex();
}
| 27.925 | 74 | 0.678603 | rao1219 |
ef58705892b12d6d7b05589554de923073d5681b | 3,331 | cpp | C++ | src/base/logger.cpp | wanchuanheng/wtaf | 90410ecb6b9e8213c0e2b2b87f72438d24ef8836 | [
"Apache-2.0"
] | null | null | null | src/base/logger.cpp | wanchuanheng/wtaf | 90410ecb6b9e8213c0e2b2b87f72438d24ef8836 | [
"Apache-2.0"
] | null | null | null | src/base/logger.cpp | wanchuanheng/wtaf | 90410ecb6b9e8213c0e2b2b87f72438d24ef8836 | [
"Apache-2.0"
] | null | null | null | #include <cstdarg>
#include <unistd.h>
#include <chrono>
#include <ctime>
#include <sys/stat.h>
#include <sys/types.h>
#include <thread>
#include "base/logger.h"
namespace wtaf {
namespace base {
void Logger::init(LOG_LEVEL level, const std::string &app, const std::string &path)
{
m_level = level;
struct timeval tv;
gettimeofday(&tv, NULL);
struct tm tm;
localtime_r(&tv.tv_sec, &tm);
m_year.store(1900 + tm.tm_year, std::memory_order_relaxed);
m_month.store(1 + tm.tm_mon, std::memory_order_relaxed);
m_day.store(tm.tm_mday, std::memory_order_relaxed);
m_file_name = path + app;
m_file_full_name = path + app + ".log";
m_file = fopen(m_file_full_name.c_str(), "rb");
if(m_file != NULL)
{
int32 fd = fileno(m_file);
struct stat st;
fstat(fd, &st);
struct tm tm_1;
localtime_r(&st.st_mtim.tv_sec, &tm_1);
uint32 year = 1900 + tm_1.tm_year;
uint32 month = 1 + tm_1.tm_mon;
uint32 day = tm_1.tm_mday;
if(year != m_year.load(std::memory_order_relaxed)
|| month != m_month.load(std::memory_order_relaxed)
|| day != m_day.load(std::memory_order_relaxed))
{
char file_name[64];
sprintf(file_name, "%s_%d-%02d-%02d.log", m_file_name.c_str(), year, month, day);
fclose(m_file);
std::rename(m_file_full_name.c_str(), file_name);
}
}
m_file = fopen(m_file_full_name.c_str(), "ab");
}
void Logger::_log(uint32 year, uint32 month, uint32 day, const char *format, ...)
{
if(year != m_year.load(std::memory_order_relaxed) || month != m_month.load(std::memory_order_relaxed)
|| day != m_day.load(std::memory_order_relaxed))
{
m_enter_num.fetch_sub(1, std::memory_order_relaxed);
while(m_enter_num.load(std::memory_order_relaxed) > 0)
{
std::this_thread::yield();
};
std::lock_guard<std::mutex> guard(m_mutex);
uint32 y = m_year.load(std::memory_order_relaxed);
uint32 m = m_month.load(std::memory_order_relaxed);
uint32 d = m_day.load(std::memory_order_relaxed);
//double-checked
if(year != y || month != m || day != d)
{
char file_name[64];
sprintf(file_name, "%s_%d-%02d-%02d.log", m_file_name.c_str(), y, m, d);
fclose(m_file);
std::rename(m_file_full_name.c_str(), file_name);
m_file = fopen(m_file_full_name.c_str(), "ab");
m_year.store(year, std::memory_order_relaxed);
m_month.store(month, std::memory_order_relaxed);
m_day.store(day, std::memory_order_relaxed);
}
va_list args;
va_start(args, format);
vfprintf(m_file, format, args);
va_end(args);
fflush(m_file);
}
else
{
va_list args;
va_start(args, format);
vfprintf(m_file, format, args);
va_end(args);
fflush(m_file);
m_enter_num.fetch_sub(1, std::memory_order_relaxed);
}
/**************** for debug ******************/
va_list args;
va_start(args, format);
vfprintf(stdout, format, args);
va_end(args);
/******************* for debug ******************/
}
}
}
| 30.842593 | 105 | 0.576704 | wanchuanheng |
ef59a5a79969c9e6a25ec6bbd597e3381684b289 | 201 | hpp | C++ | include/test_language_features.hpp | jdtaylor7/quetzal | 23d2dfe1c6620c6dc115710445307ddc241d4456 | [
"MIT"
] | null | null | null | include/test_language_features.hpp | jdtaylor7/quetzal | 23d2dfe1c6620c6dc115710445307ddc241d4456 | [
"MIT"
] | null | null | null | include/test_language_features.hpp | jdtaylor7/quetzal | 23d2dfe1c6620c6dc115710445307ddc241d4456 | [
"MIT"
] | null | null | null | #ifndef TEST_LANGUAGE_FEATURES_HPP
#define TEST_LANGUAGE_FEATURES_HPP
bool test_uninit_globals();
bool test_init_globals();
bool test_all_language_features();
#endif /* TEST_LANGUAGE_FEATURES_HPP */
| 22.333333 | 39 | 0.840796 | jdtaylor7 |
ef61347ea66adf304ba1a46f6ddb0c243f63cf81 | 11,863 | cpp | C++ | AADC/src/adtfUser/dev/src/util/history.cpp | AADC-Fruit/AADC_2015_FRUIT | 88bd18871228cb48c46a3bd803eded6f14dbac08 | [
"BSD-3-Clause"
] | 1 | 2018-05-10T22:35:25.000Z | 2018-05-10T22:35:25.000Z | AADC/src/adtfUser/dev/src/util/history.cpp | AADC-Fruit/AADC_2015_FRUIT | 88bd18871228cb48c46a3bd803eded6f14dbac08 | [
"BSD-3-Clause"
] | null | null | null | AADC/src/adtfUser/dev/src/util/history.cpp | AADC-Fruit/AADC_2015_FRUIT | 88bd18871228cb48c46a3bd803eded6f14dbac08 | [
"BSD-3-Clause"
] | null | null | null | #include "history.h"
#include <assert.h>
// -------------------------------------------------------------------------------------------------
bool History::insert(HistoryEntry new_entry) {
// -------------------------------------------------------------------------------------------------
if(entries_.size() > history_size_){
entries_.pop_back();
entries_.insert(entries_.begin(), new_entry);
} else entries_.insert(entries_.begin(), new_entry);
return true;
}
// -------------------------------------------------------------------------------------------------
int History::left_get_weighted_x() {
// -------------------------------------------------------------------------------------------------
double weighted_x = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).left_available_){
weighted_x += entries_.at(i).left_x_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (int)(weighted_x/devisor);
}
// -------------------------------------------------------------------------------------------------
double History::left_get_weighted_slope() {
// -------------------------------------------------------------------------------------------------
double weighted_slope = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).left_available_){
weighted_slope += entries_.at(i).left_slope_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (weighted_slope/(double)(devisor));
}
// -------------------------------------------------------------------------------------------------
double History::left_get_length() {
// -------------------------------------------------------------------------------------------------
double length = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).left_available_){
length += entries_.at(i).left_length_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (length/(double)(devisor));
}
// -------------------------------------------------------------------------------------------------
int History::mid_get_weighted_x() {
// -------------------------------------------------------------------------------------------------
double weighted_x = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).mid_available_){
weighted_x += entries_.at(i).mid_x_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (int)(weighted_x/devisor);
}
// -------------------------------------------------------------------------------------------------
double History::mid_get_weighted_slope() {
// -------------------------------------------------------------------------------------------------
double weighted_slope = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).mid_available_){
weighted_slope += entries_.at(i).mid_slope_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (weighted_slope/(double)(devisor));
}
// -------------------------------------------------------------------------------------------------
double History::mid_get_length() {
// -------------------------------------------------------------------------------------------------
double length = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).mid_available_){
length += entries_.at(i).mid_length_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (length/(double)(devisor));
}
// -------------------------------------------------------------------------------------------------
int History::mid_next_get_weighted_x() {
// -------------------------------------------------------------------------------------------------
double weighted_x = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).mid_next_available_){
weighted_x += entries_.at(i).mid_next_x_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (int)(weighted_x/devisor);
}
// -------------------------------------------------------------------------------------------------
double History::mid_next_get_weighted_slope() {
// -------------------------------------------------------------------------------------------------
double weighted_slope = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).mid_next_available_){
weighted_slope += entries_.at(i).mid_next_slope_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (weighted_slope/(double)(devisor));
}
// -------------------------------------------------------------------------------------------------
int History::mid_prev_get_weighted_x() {
// -------------------------------------------------------------------------------------------------
double weighted_x = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).mid_prev_available_){
weighted_x += entries_.at(i).mid_prev_x_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (int)(weighted_x/devisor);
}
// -------------------------------------------------------------------------------------------------
double History::mid_prev_get_weighted_slope() {
// -------------------------------------------------------------------------------------------------
double weighted_slope = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).mid_prev_available_){
weighted_slope += entries_.at(i).mid_prev_slope_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (weighted_slope/(double)(devisor));
}
// -------------------------------------------------------------------------------------------------
int History::right_get_weighted_x() {
// -------------------------------------------------------------------------------------------------
double weighted_x = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).right_available_){
weighted_x += entries_.at(i).right_x_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (int)(weighted_x/devisor);
}
// -------------------------------------------------------------------------------------------------
double History::right_get_weighted_slope() {
// -------------------------------------------------------------------------------------------------
double weighted_slope = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).right_available_){
weighted_slope += entries_.at(i).right_slope_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (weighted_slope/(double)(devisor));
}
// -------------------------------------------------------------------------------------------------
double History::right_get_length() {
// -------------------------------------------------------------------------------------------------
double length = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).right_available_){
length += entries_.at(i).right_length_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (length/(double)(devisor));
}
// -------------------------------------------------------------------------------------------------
bool History::left_empty() {
// -------------------------------------------------------------------------------------------------
for(size_t i = 0; i < entries_.size(); i++) if(entries_.at(i).left_available_) return false;
return true;
}
// -------------------------------------------------------------------------------------------------
bool History::mid_empty() {
// -------------------------------------------------------------------------------------------------
for(size_t i = 0; i < entries_.size(); i++) if(entries_.at(i).mid_available_) return false;
return true;
}
// -------------------------------------------------------------------------------------------------
bool History::mid_next_empty() {
// -------------------------------------------------------------------------------------------------
for(size_t i = 0; i < entries_.size(); i++) if(entries_.at(i).mid_next_available_) return false;
return true;
}
// -------------------------------------------------------------------------------------------------
bool History::mid_prev_empty() {
// -------------------------------------------------------------------------------------------------
for(size_t i = 0; i < entries_.size(); i++) if(entries_.at(i).mid_prev_available_) return false;
return true;
}
// -------------------------------------------------------------------------------------------------
bool History::right_empty() {
// -------------------------------------------------------------------------------------------------
for(size_t i = 0; i < entries_.size(); i++) if(entries_.at(i).right_available_) return false;
return true;
}
// -------------------------------------------------------------------------------------------------
int History::get_size() {
// -------------------------------------------------------------------------------------------------
return entries_.size();
}
// -------------------------------------------------------------------------------------------------
bool History::jumpSegment() {
// -------------------------------------------------------------------------------------------------
for(size_t i = 0; i < entries_.size(); i++){
entries_.at(i).passDataOn();
}
return true;
}
// -------------------------------------------------------------------------------------------------
int History::get_left_x() {
// -------------------------------------------------------------------------------------------------
if(entries_.size() > 0) return entries_[0].left_avg_x_;
return 0;
}
// -------------------------------------------------------------------------------------------------
int History::get_left_y() {
// -------------------------------------------------------------------------------------------------
if(entries_.size() > 0) return entries_[0].left_avg_y_;
return 0;
}
// -------------------------------------------------------------------------------------------------
int History::get_mid_x() {
// -------------------------------------------------------------------------------------------------
if(entries_.size() > 0) return entries_[0].mid_avg_x_;
return 0;
}
// -------------------------------------------------------------------------------------------------
int History::get_mid_y() {
// -------------------------------------------------------------------------------------------------
if(entries_.size() > 0) return entries_[0].mid_avg_y_;
return 0;
}
// -------------------------------------------------------------------------------------------------
int History::get_right_x() {
// -------------------------------------------------------------------------------------------------
if(entries_.size() > 0) return entries_[0].right_avg_x_;
return 0;
}
// -------------------------------------------------------------------------------------------------
int History::get_right_y() {
// -------------------------------------------------------------------------------------------------
if(entries_.size() > 0) return entries_[0].right_avg_y_;
return 0;
}
| 41.190972 | 101 | 0.33811 | AADC-Fruit |
ef6459388f3b5ed605e46e28d1055259b9dafa26 | 1,824 | cpp | C++ | prog/prj/src/MacierzOb.cpp | MarutTomasz/ZadaniePodwodnyDron | 669ac1d10be228cd2d2e1517e5b56f9742abd421 | [
"MIT"
] | null | null | null | prog/prj/src/MacierzOb.cpp | MarutTomasz/ZadaniePodwodnyDron | 669ac1d10be228cd2d2e1517e5b56f9742abd421 | [
"MIT"
] | null | null | null | prog/prj/src/MacierzOb.cpp | MarutTomasz/ZadaniePodwodnyDron | 669ac1d10be228cd2d2e1517e5b56f9742abd421 | [
"MIT"
] | null | null | null | #include "MacierzOb.hh"
/*!
* \file
* \brief Definicja metod klasy MacierzOb
*
* Plik zawiera definicje metod działających
* na macierzach obrotu.
*/
MacierzOb::MacierzOb(const Macierz3D &M) : Macierz3D(M) {
double epsilon = 0.000000001;
if(abs(tab[0] * tab[1]) > epsilon){
cout << "Macierz nie jest ortonormalna" << endl;
exit(1);
}
if(abs(tab[1] * tab[2]) > epsilon){
cout << "Macierz nie jest ortonormalna" << endl;
exit(1);
}
if(abs(tab[0] * tab[2]) > epsilon){
cout << "Macierz nie jest ortonormalna" << endl;
exit(1);
}
if(abs((*this).wyznacznik(Laplace) - 1) > epsilon){
cout << "Macierz nie jest ortonormalna" << endl;
exit(1);
}
}
MacierzOb::MacierzOb(){
(*this).MacierzJednostkowa();
}
MacierzOb::MacierzOb(char os, double stopnie){
switch(os){
case 'z' : {
tab[0][0] = cos(stopnie * PI/180);
tab[0][1] = -sin(stopnie * PI/180);
tab[0][2] = 0.0;
tab[1][0] = sin(stopnie * PI/180);
tab[1][1] = cos(stopnie * PI/180);
tab[1][2] = 0.0;
tab[2][0] = 0.0;
tab[2][1] = 0.0;
tab[2][2] = 1.0;
break;
}
case 'x' : {
tab[0][0] = 1.0;
tab[0][1] = 0.0;
tab[0][2] = 0.0;
tab[1][0] = 0.0;
tab[1][1] = cos(stopnie * PI/180);
tab[1][2] = -sin(stopnie * PI/180);
tab[2][0] = 0.0;
tab[2][1] = sin(stopnie * PI/180);
tab[2][2] = cos(stopnie * PI/180);
break;
}
case 'y' : {
tab[0][0] = cos(stopnie * PI/180);
tab[0][1] = 0.0;
tab[0][2] = sin(stopnie * PI/180);
tab[1][0] = 0.0;
tab[1][1] = 1.0;
tab[1][2] = 0.0;
tab[2][0] = -sin(stopnie * PI/180);
tab[2][1] = 0.0;
tab[2][2] = cos(stopnie * PI/180);
break;
}
default: {
cout << "Nieprawidlowa os obtoru. Nie mozna stworzyc macierzy." << endl;
exit(1);
break;
}
}
}
| 22.518519 | 76 | 0.524123 | MarutTomasz |
ef6a4232e6f2491c3b33091fce6da0f114e5fe9b | 4,118 | ipp | C++ | include/External/stlib/packages/shortest_paths/GraphDijkstra.ipp | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | include/External/stlib/packages/shortest_paths/GraphDijkstra.ipp | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | include/External/stlib/packages/shortest_paths/GraphDijkstra.ipp | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | // -*- C++ -*-
#if !defined(__GraphDijkstra_ipp__)
#error This file is an implementation detail of the class GraphDijkstra.
#endif
namespace shortest_paths {
//
// Mathematical operations
//
template <typename WeightType, typename HeapType>
inline
void
GraphDijkstra<WeightType, HeapType>::
build() {
// Allocate memory for the half edges.
{
half_edge_container temp(edges().size());
_half_edges.swap(temp);
_half_edges.clear();
}
// Sort the edges by source vertex.
EdgeSourceCompare<edge_type> comp;
std::sort(edges().begin(), edges().end(), comp);
// Add the half edges.
edge_const_iterator edge_iter = edges().begin();
edge_const_iterator edge_end = edges().end();
vertex_iterator vert_iter = vertices().begin();
const vertex_iterator vert_end = vertices().end();
for (; vert_iter != vert_end; ++vert_iter) {
vert_iter->set_adjacent_edges(&*_half_edges.end());
while (edge_iter != edge_end &&
edge_iter->source() == &*vert_iter) {
_half_edges.push_back(half_edge_type(edge_iter->target(),
edge_iter->weight()));
++edge_iter;
}
}
// Clear the edges.
{
edge_container temp;
edges().swap(temp);
}
}
template <typename WeightType, typename HeapType>
inline
void
GraphDijkstra<WeightType, HeapType>::
initialize(const int source_index) {
// Initialize the data in each vertex.
vertex_iterator
iter = vertices().begin(),
iter_end = vertices().end();
for (; iter != iter_end; ++iter) {
iter->initialize();
}
// Set the source vertex to known.
vertex_type& source = vertices()[source_index];
source.set_status(KNOWN);
source.set_distance(0);
source.set_predecessor(0);
}
template <typename WeightType, typename HeapType>
inline
void
GraphDijkstra<WeightType, HeapType>::
dijkstra(const int root_vertex_index) {
// Initialize the graph.
initialize(root_vertex_index);
// The heap of labeled unknown vertices.
heap_type labeled;
// Label the adjacent neighbors of the root vertex.
label_adjacent(labeled, &vertices()[root_vertex_index]);
// All vertices are known when there are no labeled vertices left.
// Loop while there are labeled vertices left.
vertex_type* min_vertex;
while (labeled.size()) {
// The labeled vertex with minimum distance becomes known.
min_vertex = labeled.top();
labeled.pop();
min_vertex->set_status(KNOWN);
// Label the adjacent neighbors of the known vertex.
label_adjacent(labeled, min_vertex);
}
}
template <typename WeightType, typename HeapType>
inline
void
GraphDijkstra<WeightType, HeapType>::
label(heap_type& heap, vertex_type& vertex, const vertex_type& known_vertex,
weight_type edge_weight) {
if (vertex.status() == UNLABELED) {
vertex.set_status(LABELED);
vertex.set_distance(known_vertex.distance() + edge_weight);
vertex.set_predecessor(&known_vertex);
heap.push(&vertex);
}
else { // _status == LABELED
weight_type new_distance = known_vertex.distance() + edge_weight;
if (new_distance < vertex.distance()) {
vertex.set_distance(new_distance);
vertex.set_predecessor(&known_vertex);
heap.decrease(vertex.heap_ptr());
}
}
}
template <typename WeightType, typename HeapType>
inline
void
GraphDijkstra<WeightType, HeapType>::
label_adjacent(heap_type& heap, const vertex_type* known_vertex) {
vertex_type* adjacent;
half_edge_const_iterator iter(known_vertex->adjacent_edges());
half_edge_const_iterator iter_end((known_vertex + 1)->adjacent_edges());
// Loop over the adjacent edges.
for (; iter != iter_end; ++iter) {
adjacent = static_cast<vertex_type*>(iter->vertex());
if (adjacent->status() != KNOWN) {
label(heap, *adjacent, *known_vertex, iter->weight());
}
}
}
} // namespace shortest_paths
// End of file.
| 29.625899 | 77 | 0.654201 | bxl295 |
ef724a5fee6c341680ca5427d5697d2fe7cf8fba | 2,445 | inl | C++ | GLShader.inl | ffhighwind/DeferredShading | c8b765c5d1126ef8f337047db50e2eb63308baf9 | [
"Apache-2.0"
] | 1 | 2019-10-18T13:45:05.000Z | 2019-10-18T13:45:05.000Z | GLShader.inl | ffhighwind/DeferredShading | c8b765c5d1126ef8f337047db50e2eb63308baf9 | [
"Apache-2.0"
] | 1 | 2019-10-18T13:44:49.000Z | 2019-11-29T23:26:27.000Z | GLShader.inl | ffhighwind/DeferredShading | c8b765c5d1126ef8f337047db50e2eb63308baf9 | [
"Apache-2.0"
] | null | null | null | /*
* GLShader class for OpenGL 4.3
*
* Copyright (c) 2013 Wesley Hamilton
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#ifndef GLSHADER_INL
#define GLSHADER_INL
#include "GLShader.hpp"
namespace opengl {
inline bool GLShader::operator==(const GLShader &other) const {
return _id == other._id;
}
inline void GLShader::Create(ShaderType shaderType) {
_id = glCreateShader((GLenum)shaderType);
}
inline void GLShader::Destroy() {
glDeleteShader(_id);
_id = 0;
}
inline int GLShader::Id() const {
return _id;
}
inline ShaderType GLShader::Type() const {
ShaderType _type = (ShaderType)0;
glGetShaderiv(_id, GL_SHADER_TYPE, (int *)&_type);
return _type;
}
inline bool GLShader::Exists() const {
return _id != 0 && glIsShader(_id) != GL_FALSE;
}
inline void GLShader::GetVertexPrecision(ShaderPrecision format, int &min, int &max, int &precision) {
int minMax[2] = { 0, 0 };
precision = 0;
glGetShaderPrecisionFormat(GL_VERTEX_SHADER, (GLenum)format, minMax, &precision);
min = minMax[0];
max = minMax[1];
}
inline void GLShader::GetFragmentPrecision(ShaderPrecision format, int &min, int &max, int &precision) {
int minMax[2] = { 0, 0 };
precision = 0;
glGetShaderPrecisionFormat(GL_FRAGMENT_SHADER, (GLenum)format, minMax, &precision);
min = minMax[0];
max = minMax[1];
}
inline void GLShader::ReleaseCompiler() {
glReleaseShaderCompiler();
}
} // namespace opengl
#endif // GLSHADER_INL | 29.817073 | 104 | 0.745603 | ffhighwind |
ef72922217abbf859e05423495f1e87fc30d3ce5 | 2,870 | cpp | C++ | trains/train.cpp | mtlbaur/coursework_cpp | e86670df99a7e283c86bf702c708f92db6cfe0bf | [
"MIT"
] | null | null | null | trains/train.cpp | mtlbaur/coursework_cpp | e86670df99a7e283c86bf702c708f92db6cfe0bf | [
"MIT"
] | null | null | null | trains/train.cpp | mtlbaur/coursework_cpp | e86670df99a7e283c86bf702c708f92db6cfe0bf | [
"MIT"
] | null | null | null | // Name: Matthias Baur
// File Name: train.cpp
// Date: 3 October, 2017
// This is the source file for the header file "train.h".
#include "train.h"
using namespace std;
// This function is responsible for adding a car the the end of a train.
void addToEnd(TrainCar* &head, TrainCar* carToAdd)
{
if (head == NULL)
{
head = carToAdd;
head->next = NULL;
}
else
{
TrainCar* preCar = findEnd(head);
preCar->next = carToAdd;
preCar->next->next = NULL;
preCar = NULL;
}
}
// This function is responsible for adding a car to the beginning of a train.
void addToBeginning(TrainCar* &head, TrainCar* carToAdd)
{
carToAdd->next = head;
head = carToAdd;
}
// This function is responsible for adding a car in the correct spot in a train.
// The correct spot is determined by weight - it is sorted into ascending order.
// It utilizes the weight_findCar and addToBeginning functions.
void addInAscendingWeight(TrainCar* &head, TrainCar* carToAdd)
{
TrainCar* preCar = weight_findCar(head, carToAdd); // Finds the car after which to add the new car.
if (preCar == NULL)
addToBeginning(head, carToAdd);
else
{
carToAdd->next = preCar->next;
preCar->next = carToAdd;
}
}
// This function is responsible for switching a car from one train to another.
// It utilizes the addToBeginning functions.
void switchTrains(TrainCar* &srcHead, TrainCar* &dstHead)
{
TrainCar* switchCar = srcHead;
if (switchCar != NULL)
{
srcHead = srcHead->next;
addToBeginning(dstHead, switchCar);
}
switchCar = NULL;
}
// This functions simply displays a the current configuration of a train.
void displayTrain(TrainCar* head)
{
TrainCar* walker = head;
while(walker != NULL)
{
cout << walker->id;
if (walker->next != NULL)
cout << "->";
walker = walker->next;
}
walker = NULL;
}
// This function simply displays the weight of a train.
void printTrainWeight(TrainCar* head)
{
float totalWeight = 0;
TrainCar* walker = head;
while(walker != NULL)
{
totalWeight += walker->weight;
walker = walker->next;
}
cout << totalWeight;
walker = NULL;
}
// This function returns the location of the last car in a train.
TrainCar* findEnd(TrainCar* head)
{
TrainCar* walker = head;
if (walker == NULL)
return walker;
else
{
while(walker->next != NULL)
walker = walker->next;
return walker;
}
}
// This function returns the car after which to add the new car.
// It is integral to the addInAscendingWeight() function.
TrainCar* weight_findCar(TrainCar* head, TrainCar* carToAdd)
{
bool found = false;
TrainCar* walker = head;
TrainCar* preCar = NULL;
while (!found)
{
if (walker == NULL)
found = true;
else if (walker->weight > carToAdd->weight)
found = true;
else
{
preCar = walker;
walker = walker->next;
}
}
walker = NULL;
return preCar;
}
| 18.75817 | 101 | 0.677352 | mtlbaur |
ef72c546e444ddc8238e9eea281d6e40f6d15209 | 1,367 | cpp | C++ | Kiwi/Private/Emulator.cpp | WhoBrokeTheBuild/Kiwi | 12370043032d07fa825e8c80ad11c931ce71235b | [
"MIT"
] | null | null | null | Kiwi/Private/Emulator.cpp | WhoBrokeTheBuild/Kiwi | 12370043032d07fa825e8c80ad11c931ce71235b | [
"MIT"
] | null | null | null | Kiwi/Private/Emulator.cpp | WhoBrokeTheBuild/Kiwi | 12370043032d07fa825e8c80ad11c931ce71235b | [
"MIT"
] | null | null | null | #include <Kiwi/Emulator.hpp>
#include <Kiwi/Log.hpp>
#include <QKeyEvent>
#include <QCoreApplication>
#include <chrono>
#include <typeinfo>
namespace kiwi {
using namespace std::chrono_literals;
Emulator::Emulator()
{
}
Emulator::~Emulator()
{
stop();
}
void Emulator::start()
{
if (_running) {
return;
}
_running = true;
_thread = std::thread([this]() {
run();
});
}
void Emulator::stop()
{
_running = false;
_thread.join();
}
void Emulator::run()
{
auto target = 1'000'000'000ns / targetFPS();
while (_running) {
auto before = std::chrono::high_resolution_clock::now();
doFrame();
auto after = std::chrono::high_resolution_clock::now();
auto elapsed = after - before;
auto difference = target - elapsed;
if (difference.count() > 1'000'000) {
std::this_thread::sleep_for(target - elapsed);
}
else {
Log(KIWI_ANCHOR, "sleep_for cannot sleep for less than 1ms");
}
}
}
void Emulator::keyPressEvent(QKeyEvent * event)
{
if (_mainWindow) {
// TODO: Improve?
QKeyEvent * copy = new QKeyEvent(event->type(), event->key(), event->modifiers(), event->text(), event->isAutoRepeat(), event->count());
QCoreApplication::postEvent(_mainWindow, copy);
}
}
} // namespace kiwi | 18.986111 | 144 | 0.596196 | WhoBrokeTheBuild |
ef74ccd4f99a3b33143694b3a68aa242cb4b5397 | 6,650 | cc | C++ | Geometry/MTDNumberingBuilder/plugins/MTDGeometricTimingDetExtraESModule.cc | flodamas/cmssw | fff9de2a54e62debab81057f8d6f8c82c2fd3dd6 | [
"Apache-2.0"
] | null | null | null | Geometry/MTDNumberingBuilder/plugins/MTDGeometricTimingDetExtraESModule.cc | flodamas/cmssw | fff9de2a54e62debab81057f8d6f8c82c2fd3dd6 | [
"Apache-2.0"
] | null | null | null | Geometry/MTDNumberingBuilder/plugins/MTDGeometricTimingDetExtraESModule.cc | flodamas/cmssw | fff9de2a54e62debab81057f8d6f8c82c2fd3dd6 | [
"Apache-2.0"
] | null | null | null | #include "Geometry/MTDNumberingBuilder/plugins/MTDGeometricTimingDetExtraESModule.h"
#include "Geometry/MTDNumberingBuilder/plugins/DDDCmsMTDConstruction.h"
#include "CondFormats/GeometryObjects/interface/PGeometricTimingDet.h"
#include "CondFormats/GeometryObjects/interface/PGeometricTimingDetExtra.h"
#include "Geometry/Records/interface/IdealGeometryRecord.h"
#include "Geometry/Records/interface/PGeometricTimingDetExtraRcd.h"
#include "DetectorDescription/Core/interface/DDCompactView.h"
#include "DetectorDescription/Core/interface/DDSolid.h"
#include "DetectorDescription/Core/interface/DDMaterial.h"
#include "ExtractStringFromDDD.h"
#include "CondDBCmsMTDConstruction.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Framework/interface/ESTransientHandle.h"
#include "FWCore/Framework/interface/ModuleFactory.h"
#include "FWCore/Framework/interface/ESProducer.h"
#include <memory>
using namespace edm;
MTDGeometricTimingDetExtraESModule::MTDGeometricTimingDetExtraESModule(const edm::ParameterSet & p)
: fromDDD_(p.getParameter<bool>("fromDDD"))
{
setWhatProduced(this);
}
MTDGeometricTimingDetExtraESModule::~MTDGeometricTimingDetExtraESModule() {}
std::shared_ptr<std::vector<GeometricTimingDetExtra> >
MTDGeometricTimingDetExtraESModule::produce(const IdealGeometryRecord & iRecord) {
auto gde = std::make_shared<std::vector<GeometricTimingDetExtra> >();
// get the GeometricTimingDet which has a nav_type
edm::ESHandle<GeometricTimingDet> gd;
iRecord.get ( gd );
if (fromDDD_) {
// traverse all components from the tracker down;
// read the DD if from DD
const GeometricTimingDet* tracker = &(*gd);
edm::ESTransientHandle<DDCompactView> cpv;
iRecord.get( cpv );
DDExpandedView ev(*cpv);
ev.goTo(tracker->navType());
putOne((*gde), tracker, ev, 0);
std::vector<const GeometricTimingDet*> tc = tracker->components();
int count=0;
int lev = 1;
// CmsMTDStringToEnum ctst
gde->reserve(tracker->deepComponents().size());
for( const auto* git : tc ) {
ev.goTo(git->navType());
putOne((*gde), git, ev, lev);
std::vector<const GeometricTimingDet*> inone = git->components();
if ( inone.empty() ) ++count;
++lev;
for( const auto* git2 : inone ) {
ev.goTo(git2->navType());
putOne((*gde), git2, ev, lev);
std::vector<const GeometricTimingDet*> intwo= git2->components();
if ( intwo.empty() ) ++count;
++lev;
for( const auto* git3 : intwo ) {
ev.goTo(git3->navType());
putOne((*gde), git3, ev, lev);
std::vector<const GeometricTimingDet*> inthree= git3->components();
if ( inthree.empty() ) ++count;
++lev;
for( const auto* git4 : inthree ) {
ev.goTo(git4->navType());
putOne((*gde), git4, ev, lev);
std::vector<const GeometricTimingDet*> infour= git4->components();
if ( infour.empty() ) ++count;
++lev;
for( const auto* git5 : infour ) {
ev.goTo(git5->navType());
putOne((*gde), git5, ev, lev);
std::vector<const GeometricTimingDet*> infive= git5->components();
if ( infive.empty() ) ++count;
++lev;
for( const auto* git6 : infive ) {
ev.goTo(git6->navType());
putOne((*gde), git6, ev, lev);
std::vector<const GeometricTimingDet*> insix= git6->components();
if ( insix.empty() ){
++count;
} else {
edm::LogError("GeometricTimingDetExtra") << "Hierarchy has exceeded hard-coded level 6 for Tracker " ;
}
} // level 6
--lev;
} // level 5
--lev;
} // level 4
--lev;
} //level 3
--lev;
} // level 2
--lev;
}
}else{
// if it is not from the DD, then just get the GDE from ES and match w/ GD.
edm::ESHandle<PGeometricTimingDetExtra> pgde;
iRecord.getRecord<PGeometricTimingDetExtraRcd>().get(pgde);
std::map<uint32_t, const GeometricTimingDet*> helperMap;
const GeometricTimingDet* tracker = &(*gd);
helperMap[gd->geographicalID()] = tracker;
std::vector<const GeometricTimingDet*> tc = tracker->components();
for( const auto* git : tc ) { // level 1
helperMap[git->geographicalID()] = git;
std::vector<const GeometricTimingDet*> inone = git->components();
for( const auto* git2 : inone ) { // level 2
helperMap[git2->geographicalID()] = git2;
std::vector<const GeometricTimingDet*> intwo= git2->components();
for( const auto* git3 : intwo ) { // level 3
helperMap[git3->geographicalID()] = git3;
std::vector<const GeometricTimingDet*> inthree= git3->components();
for( const auto* git4 : inthree ) { // level 4
helperMap[git4->geographicalID()] = git4;
std::vector<const GeometricTimingDet*> infour= git4->components();
for( const auto* git5 : infour ) { // level 5
helperMap[git5->geographicalID()] = git5;
std::vector<const GeometricTimingDet*> infive= git5->components();
for( const auto* git6 : infive ) { // level 6
helperMap[git6->geographicalID()] = git6;
if ( !git6->components().empty() ){
edm::LogError("GeometricTimingDetExtra") << "Hierarchy has exceeded hard-coded level of 6 for Tracker " ;
}
} // level 6
} // level 5
} // level 4
} //level 3
} // level 2
}
const std::vector<PGeometricTimingDetExtra::Item>& pgdes = pgde->pgdes_;
gde->reserve(pgdes.size());
std::vector<DDExpandedNode> evs; //EMPTY
std::string nm; //EMPTY
for (const auto & pgde : pgdes) {
gde->emplace_back( GeometricTimingDetExtra(helperMap[pgde.geographicalId_], pgde.geographicalId_, evs
, pgde.volume_, pgde.density_, pgde.weight_, pgde.copy_
, pgde.material_, nm));
}
}
return std::shared_ptr<std::vector<GeometricTimingDetExtra> >(gde);
}
void MTDGeometricTimingDetExtraESModule::putOne(std::vector<GeometricTimingDetExtra> & gde, const GeometricTimingDet* gd, const DDExpandedView& ev, int lev ) {
std::string matname = ((ev.logicalPart()).material()).name().fullname();
std::string lpname = ((ev.logicalPart()).name().fullname());
std::vector<DDExpandedNode> evs = GeometricTimingDetExtra::GeoHistory(ev.geoHistory().begin(),ev.geoHistory().end());
gde.emplace_back(GeometricTimingDetExtra( gd, gd->geographicalId(), evs,
((ev.logicalPart()).solid()).volume(), ((ev.logicalPart()).material()).density(),
((ev.logicalPart()).material()).density() * ( ((ev.logicalPart()).solid()).volume() / 1000.),
ev.copyno(), matname, lpname, true ));
}
DEFINE_FWK_EVENTSETUP_MODULE(MTDGeometricTimingDetExtraESModule);
| 41.304348 | 171 | 0.67218 | flodamas |
ef74fc893c803120b15a589f3a0539fe520fed3b | 59,119 | cpp | C++ | meshoptimizer/demo/miniz.cpp | FAETHER/VEther | 081f0df2c4279c21e1d55bfc336a43bc96b5f1c3 | [
"MIT"
] | 3 | 2019-12-07T23:57:47.000Z | 2019-12-31T19:46:41.000Z | meshoptimizer/demo/miniz.cpp | FAETHER/VEther | 081f0df2c4279c21e1d55bfc336a43bc96b5f1c3 | [
"MIT"
] | null | null | null | meshoptimizer/demo/miniz.cpp | FAETHER/VEther | 081f0df2c4279c21e1d55bfc336a43bc96b5f1c3 | [
"MIT"
] | null | null | null | /* This is miniz.c with removal of all zlib/zip like functionality - only tdefl/tinfl APIs are left
For maximum compatibility unaligned load/store and 64-bit register paths have been removed so this is slower than miniz.c
miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing
See "unlicense" statement at the end of this file.
Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013
Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt
*/
// clang-format off
#include "miniz.h"
#ifndef MINIZ_HEADER_FILE_ONLY
typedef unsigned char mz_validate_uint16[sizeof(mz_uint16)==2 ? 1 : -1];
typedef unsigned char mz_validate_uint32[sizeof(mz_uint32)==4 ? 1 : -1];
typedef unsigned char mz_validate_uint64[sizeof(mz_uint64)==8 ? 1 : -1];
#include <string.h>
#include <assert.h>
#define MZ_ASSERT(x) assert(x)
#ifdef MINIZ_NO_MALLOC
#define MZ_MALLOC(x) NULL
#define MZ_FREE(x) (void)x, ((void)0)
#define MZ_REALLOC(p, x) NULL
#else
#define MZ_MALLOC(x) malloc(x)
#define MZ_FREE(x) free(x)
#define MZ_REALLOC(p, x) realloc(p, x)
#endif
#define MZ_MAX(a,b) (((a)>(b))?(a):(b))
#define MZ_MIN(a,b) (((a)<(b))?(a):(b))
#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj))
#define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))
#define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U))
#ifdef _MSC_VER
#define MZ_FORCEINLINE __forceinline
#elif defined(__GNUC__)
#define MZ_FORCEINLINE inline __attribute__((__always_inline__))
#else
#define MZ_FORCEINLINE inline
#endif
#ifdef __cplusplus
extern "C" {
#endif
mz_uint32 mz_adler32(mz_uint32 adler, const unsigned char *ptr, size_t buf_len)
{
mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16);
size_t block_len = buf_len % 5552;
if (!ptr) return MZ_ADLER32_INIT;
while (buf_len)
{
for (i = 0; i + 7 < block_len; i += 8, ptr += 8)
{
s1 += ptr[0], s2 += s1;
s1 += ptr[1], s2 += s1;
s1 += ptr[2], s2 += s1;
s1 += ptr[3], s2 += s1;
s1 += ptr[4], s2 += s1;
s1 += ptr[5], s2 += s1;
s1 += ptr[6], s2 += s1;
s1 += ptr[7], s2 += s1;
}
for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1;
s1 %= 65521U, s2 %= 65521U;
buf_len -= block_len;
block_len = 5552;
}
return (s2 << 16) + s1;
}
void mz_free(void *p)
{
MZ_FREE(p);
}
// ------------------- Low-level Decompression (completely independent from all compression API's)
#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)
#define TINFL_MEMSET(p, c, l) memset(p, c, l)
#define TINFL_CR_BEGIN switch(r->m_state) { case 0:
#define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END
#define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END
#define TINFL_CR_FINISH }
// TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never
// reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario.
#define TINFL_GET_BYTE(state_index, c) do { \
if (pIn_buf_cur >= pIn_buf_end) { \
for ( ; ; ) { \
if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \
TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \
if (pIn_buf_cur < pIn_buf_end) { \
c = *pIn_buf_cur++; \
break; \
} \
} else { \
c = 0; \
break; \
} \
} \
} else c = *pIn_buf_cur++; } MZ_MACRO_END
#define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n))
#define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END
#define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END
// TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2.
// It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a
// Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the
// bit buffer contains >=15 bits (deflate's max. Huffman code size).
#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \
do { \
temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \
if (temp >= 0) { \
code_len = temp >> 9; \
if ((code_len) && (num_bits >= code_len)) \
break; \
} else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \
code_len = TINFL_FAST_LOOKUP_BITS; \
do { \
temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
} while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \
} TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \
} while (num_bits < 15);
// TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read
// beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully
// decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32.
// The slow path is only executed at the very end of the input buffer.
#define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \
int temp; mz_uint code_len, c; \
if (num_bits < 15) { \
if ((pIn_buf_end - pIn_buf_cur) < 2) { \
TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \
} else { \
bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \
} \
} \
if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \
code_len = temp >> 9, temp &= 511; \
else { \
code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \
} sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END
tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags)
{
static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 };
static const int s_length_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };
static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};
static const int s_dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
static const mz_uint8 s_length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
static const int s_min_table_sizes[3] = { 257, 1, 4 };
tinfl_status status = TINFL_STATUS_FAILED;
mz_uint32 num_bits, dist, counter, num_extra;
tinfl_bit_buf_t bit_buf;
const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size;
mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size;
size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start;
// Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter).
if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start))
{
*pIn_buf_size = *pOut_buf_size = 0;
return TINFL_STATUS_BAD_PARAM;
}
num_bits = r->m_num_bits;
bit_buf = r->m_bit_buf;
dist = r->m_dist;
counter = r->m_counter;
num_extra = r->m_num_extra;
dist_from_out_buf_start = r->m_dist_from_out_buf_start;
TINFL_CR_BEGIN
bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0;
r->m_z_adler32 = r->m_check_adler32 = 1;
if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)
{
TINFL_GET_BYTE(1, r->m_zhdr0);
TINFL_GET_BYTE(2, r->m_zhdr1);
counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8));
if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (mz_uint32)(1U << (8U + (r->m_zhdr0 >> 4)))));
if (counter)
{
TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED);
}
}
do
{
TINFL_GET_BITS(3, r->m_final, 3);
r->m_type = r->m_final >> 1;
if (r->m_type == 0)
{
TINFL_SKIP_BITS(5, num_bits & 7);
for (counter = 0; counter < 4; ++counter)
{
if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8);
else TINFL_GET_BYTE(7, r->m_raw_header[counter]);
}
if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8))))
{
TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED);
}
while ((counter) && (num_bits))
{
TINFL_GET_BITS(51, dist, 8);
while (pOut_buf_cur >= pOut_buf_end)
{
TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT);
}
*pOut_buf_cur++ = (mz_uint8)dist;
counter--;
}
while (counter)
{
size_t n;
while (pOut_buf_cur >= pOut_buf_end)
{
TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT);
}
while (pIn_buf_cur >= pIn_buf_end)
{
if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT)
{
TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT);
}
else
{
TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED);
}
}
n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter);
TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n);
pIn_buf_cur += n;
pOut_buf_cur += n;
counter -= (mz_uint)n;
}
}
else if (r->m_type == 3)
{
TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED);
}
else
{
if (r->m_type == 1)
{
mz_uint8 *p = r->m_tables[0].m_code_size;
mz_uint i;
r->m_table_sizes[0] = 288;
r->m_table_sizes[1] = 32;
TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32);
for ( i = 0; i <= 143; ++i) *p++ = 8;
for ( ; i <= 255; ++i) *p++ = 9;
for ( ; i <= 279; ++i) *p++ = 7;
for ( ; i <= 287; ++i) *p++ = 8;
}
else
{
for (counter = 0; counter < 3; counter++)
{
TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]);
r->m_table_sizes[counter] += s_min_table_sizes[counter];
}
MZ_CLEAR_OBJ(r->m_tables[2].m_code_size);
for (counter = 0; counter < r->m_table_sizes[2]; counter++)
{
mz_uint s;
TINFL_GET_BITS(14, s, 3);
r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s;
}
r->m_table_sizes[2] = 19;
}
for ( ; (int)r->m_type >= 0; r->m_type--)
{
int tree_next, tree_cur;
tinfl_huff_table *pTable;
mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16];
pTable = &r->m_tables[r->m_type];
MZ_CLEAR_OBJ(total_syms);
MZ_CLEAR_OBJ(pTable->m_look_up);
MZ_CLEAR_OBJ(pTable->m_tree);
for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++;
used_syms = 0, total = 0;
next_code[0] = next_code[1] = 0;
for (i = 1; i <= 15; ++i)
{
used_syms += total_syms[i];
next_code[i + 1] = (total = ((total + total_syms[i]) << 1));
}
if ((65536 != total) && (used_syms > 1))
{
TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED);
}
for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index)
{
mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index];
if (!code_size) continue;
cur_code = next_code[code_size]++;
for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1);
if (code_size <= TINFL_FAST_LOOKUP_BITS)
{
mz_int16 k = (mz_int16)((code_size << 9) | sym_index);
while (rev_code < TINFL_FAST_LOOKUP_SIZE)
{
pTable->m_look_up[rev_code] = k;
rev_code += (1 << code_size);
}
continue;
}
if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)]))
{
pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next;
tree_cur = tree_next;
tree_next -= 2;
}
rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1);
for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--)
{
tree_cur -= ((rev_code >>= 1) & 1);
if (!pTable->m_tree[-tree_cur - 1])
{
pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next;
tree_cur = tree_next;
tree_next -= 2;
}
else tree_cur = pTable->m_tree[-tree_cur - 1];
}
tree_cur -= ((rev_code >>= 1) & 1);
pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;
}
if (r->m_type == 2)
{
for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]); )
{
mz_uint s;
TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]);
if (dist < 16)
{
r->m_len_codes[counter++] = (mz_uint8)dist;
continue;
}
if ((dist == 16) && (!counter))
{
TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED);
}
num_extra = "\02\03\07"[dist - 16];
TINFL_GET_BITS(18, s, num_extra);
s += "\03\03\013"[dist - 16];
TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s);
counter += s;
}
if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter)
{
TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED);
}
TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]);
TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]);
}
}
for ( ; ; )
{
mz_uint8 *pSrc;
for ( ; ; )
{
if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2))
{
TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]);
if (counter >= 256)
break;
while (pOut_buf_cur >= pOut_buf_end)
{
TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT);
}
*pOut_buf_cur++ = (mz_uint8)counter;
}
else
{
int sym2;
mz_uint code_len;
if (num_bits < 15)
{
bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
pIn_buf_cur += 2;
num_bits += 16;
}
if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)
code_len = sym2 >> 9;
else
{
code_len = TINFL_FAST_LOOKUP_BITS;
do
{
sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
}
while (sym2 < 0);
}
counter = sym2;
bit_buf >>= code_len;
num_bits -= code_len;
if (counter & 256)
break;
if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)
code_len = sym2 >> 9;
else
{
code_len = TINFL_FAST_LOOKUP_BITS;
do
{
sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
}
while (sym2 < 0);
}
bit_buf >>= code_len;
num_bits -= code_len;
pOut_buf_cur[0] = (mz_uint8)counter;
if (sym2 & 256)
{
pOut_buf_cur++;
counter = sym2;
break;
}
pOut_buf_cur[1] = (mz_uint8)sym2;
pOut_buf_cur += 2;
}
}
if ((counter &= 511) == 256) break;
num_extra = s_length_extra[counter - 257];
counter = s_length_base[counter - 257];
if (num_extra)
{
mz_uint extra_bits;
TINFL_GET_BITS(25, extra_bits, num_extra);
counter += extra_bits;
}
TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]);
num_extra = s_dist_extra[dist];
dist = s_dist_base[dist];
if (num_extra)
{
mz_uint extra_bits;
TINFL_GET_BITS(27, extra_bits, num_extra);
dist += extra_bits;
}
dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;
if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))
{
TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED);
}
pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask);
if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end)
{
while (counter--)
{
while (pOut_buf_cur >= pOut_buf_end)
{
TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT);
}
*pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask];
}
continue;
}
do
{
pOut_buf_cur[0] = pSrc[0];
pOut_buf_cur[1] = pSrc[1];
pOut_buf_cur[2] = pSrc[2];
pOut_buf_cur += 3;
pSrc += 3;
}
while ((int)(counter -= 3) > 2);
if ((int)counter > 0)
{
pOut_buf_cur[0] = pSrc[0];
if ((int)counter > 1)
pOut_buf_cur[1] = pSrc[1];
pOut_buf_cur += counter;
}
}
}
}
while (!(r->m_final & 1));
if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)
{
TINFL_SKIP_BITS(32, num_bits & 7);
for (counter = 0; counter < 4; ++counter)
{
mz_uint s;
if (num_bits) TINFL_GET_BITS(41, s, 8);
else TINFL_GET_BYTE(42, s);
r->m_z_adler32 = (r->m_z_adler32 << 8) | s;
}
}
TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE);
TINFL_CR_FINISH
common_exit:
r->m_num_bits = num_bits;
r->m_bit_buf = bit_buf;
r->m_dist = dist;
r->m_counter = counter;
r->m_num_extra = num_extra;
r->m_dist_from_out_buf_start = dist_from_out_buf_start;
*pIn_buf_size = pIn_buf_cur - pIn_buf_next;
*pOut_buf_size = pOut_buf_cur - pOut_buf_next;
if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0))
{
const mz_uint8 *ptr = pOut_buf_next;
size_t buf_len = *pOut_buf_size;
mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16;
size_t block_len = buf_len % 5552;
while (buf_len)
{
for (i = 0; i + 7 < block_len; i += 8, ptr += 8)
{
s1 += ptr[0], s2 += s1;
s1 += ptr[1], s2 += s1;
s1 += ptr[2], s2 += s1;
s1 += ptr[3], s2 += s1;
s1 += ptr[4], s2 += s1;
s1 += ptr[5], s2 += s1;
s1 += ptr[6], s2 += s1;
s1 += ptr[7], s2 += s1;
}
for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1;
s1 %= 65521U, s2 %= 65521U;
buf_len -= block_len;
block_len = 5552;
}
r->m_check_adler32 = (s2 << 16) + s1;
if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH;
}
return status;
}
// Higher level helper functions.
size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags)
{
tinfl_decompressor decomp;
tinfl_status status;
tinfl_init(&decomp);
status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf, &src_buf_len, (mz_uint8*)pOut_buf, (mz_uint8*)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len;
}
int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)
{
int result = 0;
tinfl_decompressor decomp;
mz_uint8 *pDict = (mz_uint8*)MZ_MALLOC(TINFL_LZ_DICT_SIZE);
size_t in_buf_ofs = 0, dict_ofs = 0;
if (!pDict)
return TINFL_STATUS_FAILED;
tinfl_init(&decomp);
for ( ; ; )
{
size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;
tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,
(flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)));
in_buf_ofs += in_buf_size;
if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user)))
break;
if (status != TINFL_STATUS_HAS_MORE_OUTPUT)
{
result = (status == TINFL_STATUS_DONE);
break;
}
dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1);
}
MZ_FREE(pDict);
*pIn_buf_size = in_buf_ofs;
return result;
}
// ------------------- Low-level Compression (independent from all decompression API's)
// Purposely making these tables static for faster init and thread safety.
static const mz_uint16 s_tdefl_len_sym[256] =
{
257,258,259,260,261,262,263,264,265,265,266,266,267,267,268,268,269,269,269,269,270,270,270,270,271,271,271,271,272,272,272,272,
273,273,273,273,273,273,273,273,274,274,274,274,274,274,274,274,275,275,275,275,275,275,275,275,276,276,276,276,276,276,276,276,
277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,
279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,
281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,
282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,
283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,
284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,285
};
static const mz_uint8 s_tdefl_len_extra[256] =
{
0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,0
};
static const mz_uint8 s_tdefl_small_dist_sym[512] =
{
0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,
13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14,
14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16,
16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17
};
static const mz_uint8 s_tdefl_small_dist_extra[512] =
{
0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7
};
static const mz_uint8 s_tdefl_large_dist_sym[128] =
{
0,0,18,19,20,20,21,21,22,22,22,22,23,23,23,23,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26,
26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,
28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29
};
static const mz_uint8 s_tdefl_large_dist_extra[128] =
{
0,0,8,8,9,9,9,9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13
};
// Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values.
typedef struct
{
mz_uint16 m_key, m_sym_index;
} tdefl_sym_freq;
static tdefl_sym_freq* tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq* pSyms0, tdefl_sym_freq* pSyms1)
{
mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2];
tdefl_sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1;
MZ_CLEAR_OBJ(hist);
for (i = 0; i < num_syms; i++)
{
mz_uint freq = pSyms0[i].m_key;
hist[freq & 0xFF]++;
hist[256 + ((freq >> 8) & 0xFF)]++;
}
while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--;
for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8)
{
const mz_uint32* pHist = &hist[pass << 8];
mz_uint offsets[256], cur_ofs = 0;
for (i = 0; i < 256; i++)
{
offsets[i] = cur_ofs;
cur_ofs += pHist[i];
}
for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i];
{
tdefl_sym_freq* t = pCur_syms;
pCur_syms = pNew_syms;
pNew_syms = t;
}
}
return pCur_syms;
}
// tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996.
static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n)
{
int root, leaf, next, avbl, used, dpth;
if (n==0) return;
else if (n==1)
{
A[0].m_key = 1;
return;
}
A[0].m_key += A[1].m_key;
root = 0;
leaf = 2;
for (next=1; next < n-1; next++)
{
if (leaf>=n || A[root].m_key<A[leaf].m_key)
{
A[next].m_key = A[root].m_key;
A[root++].m_key = (mz_uint16)next;
}
else A[next].m_key = A[leaf++].m_key;
if (leaf>=n || (root<next && A[root].m_key<A[leaf].m_key))
{
A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key);
A[root++].m_key = (mz_uint16)next;
}
else A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key);
}
A[n-2].m_key = 0;
for (next=n-3; next>=0; next--) A[next].m_key = A[A[next].m_key].m_key+1;
avbl = 1;
used = dpth = 0;
root = n-2;
next = n-1;
while (avbl>0)
{
while (root>=0 && (int)A[root].m_key==dpth)
{
used++;
root--;
}
while (avbl>used)
{
A[next--].m_key = (mz_uint16)(dpth);
avbl--;
}
avbl = 2*used;
dpth++;
used = 0;
}
}
// Limits canonical Huffman code table's max code size.
enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 };
static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size)
{
int i;
mz_uint32 total = 0;
if (code_list_len <= 1) return;
for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i];
for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i));
while (total != (1UL << max_code_size))
{
pNum_codes[max_code_size]--;
for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i])
{
pNum_codes[i]--;
pNum_codes[i + 1] += 2;
break;
}
total--;
}
}
static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table)
{
int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE];
mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1];
MZ_CLEAR_OBJ(num_codes);
if (static_table)
{
for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++;
}
else
{
tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms;
int num_used_syms = 0;
const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0];
for (i = 0; i < table_len; i++) if (pSym_count[i])
{
syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i];
syms0[num_used_syms++].m_sym_index = (mz_uint16)i;
}
pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1);
tdefl_calculate_minimum_redundancy(pSyms, num_used_syms);
for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++;
tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit);
MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]);
MZ_CLEAR_OBJ(d->m_huff_codes[table_num]);
for (i = 1, j = num_used_syms; i <= code_size_limit; i++)
for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i);
}
next_code[1] = 0;
for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1);
for (i = 0; i < table_len; i++)
{
mz_uint rev_code = 0, code, code_size;
if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue;
code = next_code[code_size]++;
for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1);
d->m_huff_codes[table_num][i] = (mz_uint16)rev_code;
}
}
#define TDEFL_PUT_BITS(b, l) do { \
mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \
d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \
while (d->m_bits_in >= 8) { \
if (d->m_pOutput_buf < d->m_pOutput_buf_end) \
*d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \
d->m_bit_buffer >>= 8; \
d->m_bits_in -= 8; \
} \
} MZ_MACRO_END
#define TDEFL_RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \
if (rle_repeat_count < 3) { \
d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \
while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \
} else { \
d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \
} rle_repeat_count = 0; } }
#define TDEFL_RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \
if (rle_z_count < 3) { \
d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \
} else if (rle_z_count <= 10) { \
d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \
} else { \
d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \
} rle_z_count = 0; } }
static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
static void tdefl_start_dynamic_block(tdefl_compressor *d)
{
int num_lit_codes, num_dist_codes, num_bit_lengths;
mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index;
mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF;
d->m_huff_count[0][256] = 1;
tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE);
tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE);
for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break;
for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break;
memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes);
memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes);
total_code_sizes_to_pack = num_lit_codes + num_dist_codes;
num_packed_code_sizes = 0;
rle_z_count = 0;
rle_repeat_count = 0;
memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2);
for (i = 0; i < total_code_sizes_to_pack; i++)
{
mz_uint8 code_size = code_sizes_to_pack[i];
if (!code_size)
{
TDEFL_RLE_PREV_CODE_SIZE();
if (++rle_z_count == 138)
{
TDEFL_RLE_ZERO_CODE_SIZE();
}
}
else
{
TDEFL_RLE_ZERO_CODE_SIZE();
if (code_size != prev_code_size)
{
TDEFL_RLE_PREV_CODE_SIZE();
d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1);
packed_code_sizes[num_packed_code_sizes++] = code_size;
}
else if (++rle_repeat_count == 6)
{
TDEFL_RLE_PREV_CODE_SIZE();
}
}
prev_code_size = code_size;
}
if (rle_repeat_count)
{
TDEFL_RLE_PREV_CODE_SIZE();
}
else
{
TDEFL_RLE_ZERO_CODE_SIZE();
}
tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE);
TDEFL_PUT_BITS(2, 2);
TDEFL_PUT_BITS(num_lit_codes - 257, 5);
TDEFL_PUT_BITS(num_dist_codes - 1, 5);
for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break;
num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1));
TDEFL_PUT_BITS(num_bit_lengths - 4, 4);
for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3);
for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes; )
{
mz_uint code = packed_code_sizes[packed_code_sizes_index++];
MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2);
TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]);
if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]);
}
}
static void tdefl_start_static_block(tdefl_compressor *d)
{
mz_uint i;
mz_uint8 *p = &d->m_huff_code_sizes[0][0];
for (i = 0; i <= 143; ++i) *p++ = 8;
for ( ; i <= 255; ++i) *p++ = 9;
for ( ; i <= 279; ++i) *p++ = 7;
for ( ; i <= 287; ++i) *p++ = 8;
memset(d->m_huff_code_sizes[1], 5, 32);
tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE);
tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE);
TDEFL_PUT_BITS(1, 2);
}
static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };
static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d)
{
mz_uint flags;
mz_uint8 *pLZ_codes;
flags = 1;
for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1)
{
if (flags == 1)
flags = *pLZ_codes++ | 0x100;
if (flags & 1)
{
mz_uint sym, num_extra_bits;
mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8));
pLZ_codes += 3;
MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]);
if (match_dist < 512)
{
sym = s_tdefl_small_dist_sym[match_dist];
num_extra_bits = s_tdefl_small_dist_extra[match_dist];
}
else
{
sym = s_tdefl_large_dist_sym[match_dist >> 8];
num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8];
}
MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);
TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);
}
else
{
mz_uint lit = *pLZ_codes++;
MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
}
}
TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
return (d->m_pOutput_buf < d->m_pOutput_buf_end);
}
static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block)
{
if (static_block)
tdefl_start_static_block(d);
else
tdefl_start_dynamic_block(d);
return tdefl_compress_lz_codes(d);
}
static int tdefl_flush_block(tdefl_compressor *d, int flush)
{
mz_uint saved_bit_buf, saved_bits_in;
mz_uint8 *pSaved_output_buf;
mz_bool comp_block_succeeded = MZ_FALSE;
int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size;
mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf;
d->m_pOutput_buf = pOutput_buf_start;
d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16;
MZ_ASSERT(!d->m_output_flush_remaining);
d->m_output_flush_ofs = 0;
d->m_output_flush_remaining = 0;
*d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left);
d->m_pLZ_code_buf -= (d->m_num_flags_left == 8);
if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index))
{
TDEFL_PUT_BITS(0x78, 8);
TDEFL_PUT_BITS(0x01, 8);
}
TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1);
pSaved_output_buf = d->m_pOutput_buf;
saved_bit_buf = d->m_bit_buffer;
saved_bits_in = d->m_bits_in;
if (!use_raw_block)
comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48));
// If the block gets expanded, forget the current contents of the output buffer and send a raw block instead.
if ( ((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) &&
((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size) )
{
mz_uint i;
d->m_pOutput_buf = pSaved_output_buf;
d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
TDEFL_PUT_BITS(0, 2);
if (d->m_bits_in)
{
TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
}
for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF)
{
TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16);
}
for (i = 0; i < d->m_total_lz_bytes; ++i)
{
TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8);
}
}
// Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes.
else if (!comp_block_succeeded)
{
d->m_pOutput_buf = pSaved_output_buf;
d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
tdefl_compress_block(d, MZ_TRUE);
}
if (flush)
{
if (flush == TDEFL_FINISH)
{
if (d->m_bits_in)
{
TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
}
if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER)
{
mz_uint i, a = d->m_adler32;
for (i = 0; i < 4; i++)
{
TDEFL_PUT_BITS((a >> 24) & 0xFF, 8);
a <<= 8;
}
}
}
else
{
mz_uint i, z = 0;
TDEFL_PUT_BITS(0, 3);
if (d->m_bits_in)
{
TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
}
for (i = 2; i; --i, z ^= 0xFFFF)
{
TDEFL_PUT_BITS(z & 0xFFFF, 16);
}
}
}
MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end);
memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
d->m_pLZ_code_buf = d->m_lz_code_buf + 1;
d->m_pLZ_flags = d->m_lz_code_buf;
d->m_num_flags_left = 8;
d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes;
d->m_total_lz_bytes = 0;
d->m_block_index++;
if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0)
{
if (d->m_pPut_buf_func)
{
*d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user))
return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED);
}
else if (pOutput_buf_start == d->m_output_buf)
{
int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs));
memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy);
d->m_out_buf_ofs += bytes_to_copy;
if ((n -= bytes_to_copy) != 0)
{
d->m_output_flush_ofs = bytes_to_copy;
d->m_output_flush_remaining = n;
}
}
else
{
d->m_out_buf_ofs += n;
}
}
return d->m_output_flush_remaining;
}
static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len)
{
mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len;
mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
const mz_uint8 *s = d->m_dict + pos, *p, *q;
mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1];
MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN);
if (max_match_len <= match_len) return;
for ( ; ; )
{
for ( ; ; )
{
if (--num_probes_left == 0) return;
#define TDEFL_PROBE \
next_probe_pos = d->m_next[probe_pos]; \
if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \
probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break;
TDEFL_PROBE;
TDEFL_PROBE;
TDEFL_PROBE;
}
if (!dist) break;
p = s;
q = d->m_dict + probe_pos;
for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break;
if (probe_len > match_len)
{
*pMatch_dist = dist;
if ((*pMatch_len = match_len = probe_len) == max_match_len) return;
c0 = d->m_dict[pos + match_len];
c1 = d->m_dict[pos + match_len - 1];
}
}
}
static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit)
{
d->m_total_lz_bytes++;
*d->m_pLZ_code_buf++ = lit;
*d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1);
if (--d->m_num_flags_left == 0)
{
d->m_num_flags_left = 8;
d->m_pLZ_flags = d->m_pLZ_code_buf++;
}
d->m_huff_count[0][lit]++;
}
static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist)
{
mz_uint32 s0, s1;
MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE));
d->m_total_lz_bytes += match_len;
d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN);
match_dist -= 1;
d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF);
d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8);
d->m_pLZ_code_buf += 3;
*d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80);
if (--d->m_num_flags_left == 0)
{
d->m_num_flags_left = 8;
d->m_pLZ_flags = d->m_pLZ_code_buf++;
}
s0 = s_tdefl_small_dist_sym[match_dist & 511];
s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127];
d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++;
if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++;
}
static mz_bool tdefl_compress_normal(tdefl_compressor *d)
{
const mz_uint8 *pSrc = d->m_pSrc;
size_t src_buf_left = d->m_src_buf_left;
tdefl_flush flush = d->m_flush;
while ((src_buf_left) || ((flush) && (d->m_lookahead_size)))
{
mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos;
// Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN.
if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1))
{
mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2;
mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK];
mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size);
const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process;
src_buf_left -= num_bytes_to_process;
d->m_lookahead_size += num_bytes_to_process;
while (pSrc != pSrc_end)
{
mz_uint8 c = *pSrc++;
d->m_dict[dst_pos] = c;
if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);
d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];
d->m_hash[hash] = (mz_uint16)(ins_pos);
dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
ins_pos++;
}
}
else
{
while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN))
{
mz_uint8 c = *pSrc++;
mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;
src_buf_left--;
d->m_dict[dst_pos] = c;
if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN)
{
mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2;
mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);
d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];
d->m_hash[hash] = (mz_uint16)(ins_pos);
}
}
}
d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size);
if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN))
break;
// Simple lazy/greedy parsing state machine.
len_to_move = 1;
cur_match_dist = 0;
cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1);
cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS))
{
if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))
{
mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK];
cur_match_len = 0;
while (cur_match_len < d->m_lookahead_size)
{
if (d->m_dict[cur_pos + cur_match_len] != c) break;
cur_match_len++;
}
if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0;
else cur_match_dist = 1;
}
}
else
{
tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len);
}
if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5)))
{
cur_match_dist = cur_match_len = 0;
}
if (d->m_saved_match_len)
{
if (cur_match_len > d->m_saved_match_len)
{
tdefl_record_literal(d, (mz_uint8)d->m_saved_lit);
if (cur_match_len >= 128)
{
tdefl_record_match(d, cur_match_len, cur_match_dist);
d->m_saved_match_len = 0;
len_to_move = cur_match_len;
}
else
{
d->m_saved_lit = d->m_dict[cur_pos];
d->m_saved_match_dist = cur_match_dist;
d->m_saved_match_len = cur_match_len;
}
}
else
{
tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist);
len_to_move = d->m_saved_match_len - 1;
d->m_saved_match_len = 0;
}
}
else if (!cur_match_dist)
tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]);
else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128))
{
tdefl_record_match(d, cur_match_len, cur_match_dist);
len_to_move = cur_match_len;
}
else
{
d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)];
d->m_saved_match_dist = cur_match_dist;
d->m_saved_match_len = cur_match_len;
}
// Move the lookahead forward by len_to_move bytes.
d->m_lookahead_pos += len_to_move;
MZ_ASSERT(d->m_lookahead_size >= len_to_move);
d->m_lookahead_size -= len_to_move;
d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (int)TDEFL_LZ_DICT_SIZE);
// Check if it's time to flush the current LZ codes to the internal output buffer.
if ( (d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) ||
( (d->m_total_lz_bytes > 31*1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) )
{
int n;
d->m_pSrc = pSrc;
d->m_src_buf_left = src_buf_left;
if ((n = tdefl_flush_block(d, 0)) != 0)
return (n < 0) ? MZ_FALSE : MZ_TRUE;
}
}
d->m_pSrc = pSrc;
d->m_src_buf_left = src_buf_left;
return MZ_TRUE;
}
static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d)
{
if (d->m_pIn_buf_size)
{
*d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
}
if (d->m_pOut_buf_size)
{
size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining);
memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n);
d->m_output_flush_ofs += (mz_uint)n;
d->m_output_flush_remaining -= (mz_uint)n;
d->m_out_buf_ofs += n;
*d->m_pOut_buf_size = d->m_out_buf_ofs;
}
return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY;
}
tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush)
{
if (!d)
{
if (pIn_buf_size) *pIn_buf_size = 0;
if (pOut_buf_size) *pOut_buf_size = 0;
return TDEFL_STATUS_BAD_PARAM;
}
d->m_pIn_buf = pIn_buf;
d->m_pIn_buf_size = pIn_buf_size;
d->m_pOut_buf = pOut_buf;
d->m_pOut_buf_size = pOut_buf_size;
d->m_pSrc = (const mz_uint8 *)(pIn_buf);
d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0;
d->m_out_buf_ofs = 0;
d->m_flush = flush;
if ( ((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) ||
(d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf) )
{
if (pIn_buf_size) *pIn_buf_size = 0;
if (pOut_buf_size) *pOut_buf_size = 0;
return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM);
}
d->m_wants_to_finish |= (flush == TDEFL_FINISH);
if ((d->m_output_flush_remaining) || (d->m_finished))
return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
if (!tdefl_compress_normal(d))
return d->m_prev_return_status;
if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf))
d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf);
if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining))
{
if (tdefl_flush_block(d, flush) < 0)
return d->m_prev_return_status;
d->m_finished = (flush == TDEFL_FINISH);
if (flush == TDEFL_FULL_FLUSH)
{
MZ_CLEAR_OBJ(d->m_hash);
MZ_CLEAR_OBJ(d->m_next);
d->m_dict_size = 0;
}
}
return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
}
tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush)
{
MZ_ASSERT(d->m_pPut_buf_func);
return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush);
}
tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)
{
d->m_pPut_buf_func = pPut_buf_func;
d->m_pPut_buf_user = pPut_buf_user;
d->m_flags = (mz_uint)(flags);
d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3;
d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0;
d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3;
if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash);
d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0;
d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0;
d->m_pLZ_code_buf = d->m_lz_code_buf + 1;
d->m_pLZ_flags = d->m_lz_code_buf;
d->m_num_flags_left = 8;
d->m_pOutput_buf = d->m_output_buf;
d->m_pOutput_buf_end = d->m_output_buf;
d->m_prev_return_status = TDEFL_STATUS_OKAY;
d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0;
d->m_adler32 = 1;
d->m_pIn_buf = NULL;
d->m_pOut_buf = NULL;
d->m_pIn_buf_size = NULL;
d->m_pOut_buf_size = NULL;
d->m_flush = TDEFL_NO_FLUSH;
d->m_pSrc = NULL;
d->m_src_buf_left = 0;
d->m_out_buf_ofs = 0;
memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
return TDEFL_STATUS_OKAY;
}
tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d)
{
return d->m_prev_return_status;
}
mz_uint32 tdefl_get_adler32(tdefl_compressor *d)
{
return d->m_adler32;
}
mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)
{
tdefl_compressor *pComp;
mz_bool succeeded;
if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE;
pComp = (tdefl_compressor*)MZ_MALLOC(sizeof(tdefl_compressor));
if (!pComp) return MZ_FALSE;
succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY);
succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE);
MZ_FREE(pComp);
return succeeded;
}
typedef struct
{
size_t m_size, m_capacity;
mz_uint8 *m_pBuf;
} tdefl_output_buffer;
static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser)
{
tdefl_output_buffer *p = (tdefl_output_buffer *)pUser;
size_t new_size = p->m_size + len;
if (new_size > p->m_capacity) return MZ_FALSE;
memcpy((mz_uint8*)p->m_pBuf + p->m_size, pBuf, len);
p->m_size = new_size;
return MZ_TRUE;
}
size_t tdefl_compress_bound(size_t source_len)
{
// This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.)
return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5);
}
size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags)
{
tdefl_output_buffer out_buf;
MZ_CLEAR_OBJ(out_buf);
if (!pOut_buf) return 0;
out_buf.m_pBuf = (mz_uint8*)pOut_buf;
out_buf.m_capacity = out_buf_len;
if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0;
return out_buf.m_size;
}
static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 };
// level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files).
mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy)
{
mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0);
if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER;
if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS;
else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES;
else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK;
else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS;
else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES;
return comp_flags;
}
#ifdef __cplusplus
}
#endif
#endif // MINIZ_HEADER_FILE_ONLY
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.
For more information, please refer to <http://unlicense.org/>
*/
| 37.679414 | 217 | 0.667907 | FAETHER |
ef783296e7654ad982da2ac3500b56fe53fec725 | 2,422 | cpp | C++ | WinAPIWrapperWiz/VCWizards/WinAPIWrapperWiz/templates/1033/document_window.cpp | cdragan/WinAPI-Wrapper | 5d9b0a3f70932b55b08fbe2700e611f466af9f0b | [
"MIT"
] | 15 | 2015-10-09T04:26:12.000Z | 2022-03-17T21:09:11.000Z | WinAPIWrapperWiz/VCWizards/WinAPIWrapperWiz/templates/1033/document_window.cpp | cdragan/WinAPI-Wrapper | 5d9b0a3f70932b55b08fbe2700e611f466af9f0b | [
"MIT"
] | null | null | null | WinAPIWrapperWiz/VCWizards/WinAPIWrapperWiz/templates/1033/document_window.cpp | cdragan/WinAPI-Wrapper | 5d9b0a3f70932b55b08fbe2700e611f466af9f0b | [
"MIT"
] | 7 | 2015-10-09T04:33:23.000Z | 2022-01-27T00:38:22.000Z |
#include "StdAfx.h"
#include "document_window.h"
using namespace WinAPI;
[!if PURE_WRAPPER || ON_GENERIC]
int DocumentWindow::HandleMessage( int uMsg, int wParam, int lParam )
{
switch ( uMsg ) {
[!if !PURE_WRAPPER]
case WM_USER: // Replace this with your messages
[!endif]
[!if PURE_WRAPPER]
case WM_CREATE:
return 0;
[!if ON_COMMAND]
case WM_COMMAND:
return 0;
[!endif]
[!if ON_NOTIFY]
case WM_NOTIFY:
return 0;
[!endif]
[!if ON_PAINT]
case WM_PAINT:
{ PaintDC dc( *this );
dc.TextOut( WPoint(50,50), "Hello, World!" );
}
return 0;
[!endif]
[!if ON_SIZE]
case WM_SIZE:
return MDIChildWindow::HandleMessage( uMsg, wParam, lParam );
[!endif]
[!if ON_MOUSE_MOVE]
case WM_MOUSEMOVE:
return 0;
[!endif]
[!if ON_KEY_UP_DOWN]
case WM_KEYDOWN:
return 0;
case WM_KEYUP:
return 0;
[!endif]
[!endif]
default:
return MDIChildWindow::HandleMessage( uMsg, wParam, lParam );
}
}
[!endif]
[!if !PURE_WRAPPER]
[!if ON_CREATE]
bool DocumentWindow::OnCreate( LPCREATESTRUCT lpCreateStruct )
{
return true;
}
[!endif]
[!if ON_COMMAND]
void DocumentWindow::OnCommand( int nIdentifier, int nNotifyCode, HWND hwndControl )
{
switch ( nIdentifier ) {
case 50: // Replace this with your commands
default:
break;
}
}
[!endif]
[!if ON_NOTIFY]
int DocumentWindow::OnNotify( int nIdentifier, LPNMHDR pnmh )
{
return 0;
}
[!endif]
[!if ON_PAINT]
void DocumentWindow::OnPaint()
{
PaintDC dc( *this );
dc.TextOut( WPoint(50,50), "Hello, World!" );
}
[!endif]
[!if ON_SIZE]
void DocumentWindow::OnSize( int sizing, WSize new_size )
{
// Required for the child window to maximize properly
MDIChildWindow::OnSize( sizing, new_size );
}
[!endif]
[!if ON_MOUSE_MOVE]
void DocumentWindow::OnMouseMove( WPoint point, int keys )
{
}
[!endif]
[!if ON_MOUSE_DOWN]
void DocumentWindow::OnMouseDown( WPoint point, int keys, int button )
{
}
[!endif]
[!if ON_MOUSE_UP]
void DocumentWindow::OnMouseUp( WPoint point, int keys, int button )
{
}
[!endif]
[!if ON_MOUSE_DBL_CLK]
void DocumentWindow::OnMouseDblClk( WPoint point, int keys, int button )
{
}
[!endif]
[!if !DIALOG_APP]
[!if ON_KEY_UP_DOWN]
void DocumentWindow::OnKeyDown( int key, int keyData )
{
}
void DocumentWindow::OnKeyUp( int key, int keyData )
{
}
[!endif]
[!endif]
[!endif]
| 16.703448 | 85 | 0.656069 | cdragan |
ef7d0231a32890c7fb46352c97d49ee75b80770c | 5,933 | cpp | C++ | molequeue/app/testing/oartest.cpp | kwon-young/molequeue | 1dfed97fd34a26cb4ba9ee901b441d89f732bc64 | [
"BSD-3-Clause"
] | null | null | null | molequeue/app/testing/oartest.cpp | kwon-young/molequeue | 1dfed97fd34a26cb4ba9ee901b441d89f732bc64 | [
"BSD-3-Clause"
] | null | null | null | molequeue/app/testing/oartest.cpp | kwon-young/molequeue | 1dfed97fd34a26cb4ba9ee901b441d89f732bc64 | [
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
This source file is part of the MoleQueue project.
Copyright 2013 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 <QtTest>
#include "queues/oar.h"
class QueueOarTest : public QObject
{
Q_OBJECT
private:
MoleQueue::QueueOar m_queue;
private slots:
/// Called before the first test function is executed.
void initTestCase();
/// Called after the last test function is executed.
void cleanupTestCase();
/// Called before each test function is executed.
void init();
/// Called after every test function.
void cleanup();
void sanityCheck();
void testParseJobId();
void testParseQueueLine_data();
void testParseQueueLine();
};
void QueueOarTest::initTestCase()
{
}
void QueueOarTest::cleanupTestCase()
{
}
void QueueOarTest::init()
{
}
void QueueOarTest::cleanup()
{
}
void QueueOarTest::sanityCheck()
{
QCOMPARE(m_queue.typeName(), QString("OAR"));
QString testString = "some.host.somewhere";
m_queue.setHostName(testString);
QCOMPARE(m_queue.hostName(), testString);
testString = "aUser";
m_queue.setUserName(testString);
QCOMPARE(m_queue.userName(), testString);
m_queue.setSshPort(6887);
QCOMPARE(m_queue.sshPort(), 6887);
testString = "/some/path";
m_queue.setWorkingDirectoryBase(testString);
QCOMPARE(m_queue.workingDirectoryBase(), testString);
testString = "subComm";
m_queue.setSubmissionCommand(testString);
QCOMPARE(m_queue.submissionCommand(), testString);
testString = "reqComm";
m_queue.setRequestQueueCommand(testString);
QCOMPARE(m_queue.requestQueueCommand(), testString);
}
void QueueOarTest::testParseJobId()
{
QString submissionOutput = "SSH finished (94739270797056) Exit code: 0\n[ADMISSION RULE] Modify resource description with type constraints\n[ADMISSION RULE] Automatically add the constraint to go on the 'intuidoc' and 'none' dedicated nodes.\n[ADMISSION_RULE] Resources properties : \\{'property' => '(type = \\'default\\') AND max_walltime >= 5','resources' => [{'value' => '1','resource' => 'core'}]}\n[ADMISSION RULE] Job properties : ((((desktop_computing = 'NO') AND maintenance = 'NO') AND interactive = 'MIXED') AND dedicated IN ('intuidoc','none')) AND gpu = 'NO'\nGenerate a job key...\nOAR_JOB_ID=8160421\n";
MoleQueue::IdType jobId;
QVERIFY(m_queue.parseQueueId(submissionOutput, &jobId));
QCOMPARE(jobId, static_cast<MoleQueue::IdType>(8160421));
submissionOutput = "SSH finished (94739270797056) Exit code: 0\n[ADMISSION RULE] Modify resource description with type constraints\n[ADMISSION RULE] Automatically add the constraint to go on the 'intuidoc' and 'none' dedicated nodes.\n[ADMISSION_RULE] Resources properties : \\{'property' => '(type = \\'default\\') AND max_walltime >= 5','resources' => [{'value' => '1','resource' => 'core'}]}\n[ADMISSION RULE] Job properties : ((((desktop_computing = 'NO') AND maintenance = 'NO') AND interactive = 'MIXED') AND dedicated IN ('intuidoc','none')) AND gpu = 'NO'\nGenerate a job key...\nOAR_JOB_ID=816042\n";
QVERIFY(m_queue.parseQueueId(submissionOutput, &jobId));
QCOMPARE(jobId, static_cast<MoleQueue::IdType>(816042));
}
void QueueOarTest::testParseQueueLine_data()
{
QTest::addColumn<QString>("data");
QTest::addColumn<bool>("canParse");
QTest::addColumn<MoleQueue::IdType>("jobId");
QTest::addColumn<MoleQueue::JobState>("state");
QTest::newRow("Header")
<< "Job id S User Duration System message"
<< false
<< MoleQueue::InvalidId
<< MoleQueue::Unknown;
QTest::newRow("Status: Accepted, leading whitespace")
<< " 8160394 L kchoi 0:01:18 R=1,W=0:10:0,J=B (Karma=0.000)"
<< true
<< static_cast<MoleQueue::IdType>(8160394)
<< MoleQueue::Accepted;
QTest::newRow("Status: Accepted, no leading whitespace")
<< "8160394 L kchoi 0:01:18 R=1,W=0:10:0,J=B (Karma=0.000)"
<< true
<< static_cast<MoleQueue::IdType>(8160394)
<< MoleQueue::Accepted;
QTest::newRow("Status: Error")
<< "8160394 E kchoi 0:01:18 R=1,W=0:10:0,J=B (Karma=0.000)"
<< true
<< static_cast<MoleQueue::IdType>(8160394)
<< MoleQueue::Error;
QTest::newRow("Status: Submitted")
<< "8160394 W kchoi 0:01:18 R=1,W=0:10:0,J=B (Karma=0.000)"
<< true
<< static_cast<MoleQueue::IdType>(8160394)
<< MoleQueue::Submitted;
QTest::newRow("Status: RunningRemote")
<< "8160394 R kchoi 0:01:18 R=1,W=0:10:0,J=B (Karma=0.000)"
<< true
<< static_cast<MoleQueue::IdType>(8160394)
<< MoleQueue::RunningRemote;
QTest::newRow("Status: Finished")
<< "8160394 T kchoi 0:01:18 R=1,W=0:10:0,J=B (Karma=0.000)"
<< true
<< static_cast<MoleQueue::IdType>(8160394)
<< MoleQueue::Finished;
QTest::newRow("Status: Finished")
<< "8160394 F kchoi 0:01:18 R=1,W=0:10:0,J=B (Karma=0.000)"
<< true
<< static_cast<MoleQueue::IdType>(8160394)
<< MoleQueue::Finished;
}
void QueueOarTest::testParseQueueLine()
{
QFETCH(QString, data);
QFETCH(bool, canParse);
QFETCH(MoleQueue::IdType, jobId);
QFETCH(MoleQueue::JobState, state);
MoleQueue::IdType parsedJobId;
MoleQueue::JobState parsedState;
QCOMPARE(m_queue.parseQueueLine(data, &parsedJobId, &parsedState), canParse);
QCOMPARE(parsedJobId, jobId);
QCOMPARE(parsedState, state);
}
QTEST_MAIN(QueueOarTest)
#include "oartest.moc"
| 34.9 | 620 | 0.670319 | kwon-young |
ef7f1a2dc27a339c0f1d609f315f4008e0cea273 | 2,870 | cpp | C++ | Code/C++/LCA/hdu4547_LCAODA.cpp | EdmundLuan/NOIP14-16 | c4277dfc7467346d6c67dd4cfae9a9caa08b487c | [
"MIT"
] | null | null | null | Code/C++/LCA/hdu4547_LCAODA.cpp | EdmundLuan/NOIP14-16 | c4277dfc7467346d6c67dd4cfae9a9caa08b487c | [
"MIT"
] | null | null | null | Code/C++/LCA/hdu4547_LCAODA.cpp | EdmundLuan/NOIP14-16 | c4277dfc7467346d6c67dd4cfae9a9caa08b487c | [
"MIT"
] | null | null | null | /*LCA Online Doubling Algorithm*/
#include <cstdio>
#include <cctype>
#include <queue>
#include <cstring>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
const int maxn = 100010;
struct EDGE {
int to, next;
} edge[maxn << 1];
map<string, int>mapping;
int index, n, m, root, Num;
int ancestor[maxn][20], depth[maxn], head[maxn], indegree[maxn];//dist[maxn];
void addedge(const int &a, const int &b) {
edge[index].to = b;
edge[index].next = head[a];
head[a] = index++;
}
void bfs() {
queue<int>q;
bool vst[maxn];
fill(vst, vst + n + 1, 0);
//fill(dist, dist + n + 1, 0);
fill(depth, depth + n + 1, 0);
while (!q.empty())
q.pop();
q.push(root); vst[root] = true; depth[root] = 0;
while (!q.empty()) {
int u = q.front();
q.pop();
for (int i = head[u]; i != -1; i = edge[i].next) {
int v = edge[i].to;
if (vst[v])
continue;
vst[v] = true;
ancestor[v][0] = u;
//dist[v] = dist[u] + w;
depth[v] = depth[u] + 1;
q.push(v);
}
}
/*for(int i=0;i<n;i++)
printf("Father:%d Son:%d\n", ancestor[i][0], i);*/
}
int capture(string s) {
if (mapping.find(s) == mapping.end()) {
mapping[s] = ++Num;
return Num;
}
else
return mapping[s];
}
void init() {
int u, v, w;
char s1[50], s2[50];
scanf("%d%d", &n, &m); index = 0; Num = 0; mapping.clear();
fill(head, head + n + 1, -1); fill(indegree, indegree + n + 1, 0);
for (int i = 1; i < n; i++) {
scanf("%s", s1); v = capture(s1);
scanf("%s", s2); u = capture(s2);
/*if (v == -1) {
root = u;
continue;
}*/
addedge(u, v); indegree[v]++;
addedge(v, u);
}
for (int i = 1; i <= n; i++)
if (!indegree[i]) {
root = i;
break;
}
for (int j = 0; (1 << j) <= n; j++)
for (int i = 1; i <= n; i++)
ancestor[i][j] = -1;
}
void init2() {
for (int j = 1; (1 << j) <= n; j++)
for (int i = 1; i <= n; i++)
if (ancestor[i][j - 1] != -1)
ancestor[i][j] = ancestor[ancestor[i][j - 1]][j - 1];
}
int lca(int a, int b) {
int bottom, top;
if (depth[a] < depth[b])
swap(a, b);
for (bottom = 0; (1 << bottom) <= depth[a]; bottom++);
bottom--;
for (top = bottom; top >= 0; top--) {
if (depth[a] - (1 << top) >= depth[b])
a = ancestor[a][top];
}
if (a == b)
return a;
for (top = bottom; top >= 0; top--) {
if (ancestor[a][top] != -1 && ancestor[a][top] != ancestor[b][top]) {
a = ancestor[a][top];
b = ancestor[b][top];
}
}
return ancestor[a][0];
}
int main() {
int u, v, tmp, T, ans;
char s1[50], s2[50];
//freopen("input.txt", "r", stdin);
scanf("%d", &T);
while (T--) {
init();
bfs();
init2();
for (int i = 0; i < m; i++) {
scanf("%s", s1); u = capture(s1);
scanf("%s", s2); v = capture(s2);
tmp = lca(u, v);
ans = depth[u] - depth[tmp];
if (v != tmp) {
ans++;
}
if (u == v)
ans = 0;
printf("%d\n", ans);
}
}
//fclose(stdin);
return 0;
}
| 20.35461 | 77 | 0.510105 | EdmundLuan |
ef811b7e4ac3e007270ac15ba8404e9b64a77758 | 8,596 | cpp | C++ | c10/test/core/impl/InlineStreamGuard_test.cpp | brooks-anderson/pytorch | dd928097938b6368fc7e2dc67721550d50ab08ea | [
"Intel"
] | 7 | 2021-05-29T16:31:51.000Z | 2022-02-21T18:52:25.000Z | c10/test/core/impl/InlineStreamGuard_test.cpp | stas00/pytorch | 6a085648d81ce88ff59d6d1438fdb3707a0d6fb7 | [
"Intel"
] | 1 | 2021-03-25T13:42:15.000Z | 2021-03-25T13:42:15.000Z | c10/test/core/impl/InlineStreamGuard_test.cpp | stas00/pytorch | 6a085648d81ce88ff59d6d1438fdb3707a0d6fb7 | [
"Intel"
] | 1 | 2021-12-26T23:20:06.000Z | 2021-12-26T23:20:06.000Z | #include <gtest/gtest.h>
#include <c10/core/impl/FakeGuardImpl.h>
#include <c10/core/impl/InlineStreamGuard.h>
using namespace c10;
using namespace c10::impl;
constexpr auto TestDeviceType = DeviceType::CUDA;
using TestGuardImpl = FakeGuardImpl<TestDeviceType>;
static Device dev(DeviceIndex index) {
return Device(TestDeviceType, index);
}
static Stream stream(DeviceIndex index, StreamId sid) {
return Stream(Stream::UNSAFE, dev(index), sid);
}
// -- InlineStreamGuard -------------------------------------------------------
using TestGuard = InlineStreamGuard<TestGuardImpl>;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(InlineStreamGuard, Constructor) {
TestGuardImpl::setDeviceIndex(0);
TestGuardImpl::resetStreams();
{
TestGuard g(stream(1, 2));
ASSERT_EQ(TestGuardImpl::getDeviceIndex(), 1);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 2);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
ASSERT_EQ(g.original_stream(), stream(0, 0));
ASSERT_EQ(g.current_stream(), stream(1, 2));
ASSERT_EQ(g.original_device(), dev(0));
ASSERT_EQ(g.current_device(), dev(1));
}
ASSERT_EQ(TestGuardImpl::getDeviceIndex(), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(InlineStreamGuard, ResetStreamSameSameDevice) {
TestGuardImpl::setDeviceIndex(0);
TestGuardImpl::resetStreams();
{
TestGuard g(stream(0, 2));
g.reset_stream(stream(0, 3));
ASSERT_EQ(TestGuardImpl::getDeviceIndex(), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 3);
ASSERT_EQ(g.original_stream(), stream(0, 0));
ASSERT_EQ(g.current_stream(), stream(0, 3));
ASSERT_EQ(g.original_device(), dev(0));
ASSERT_EQ(g.current_device(), dev(0));
}
ASSERT_EQ(TestGuardImpl::getDeviceIndex(), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(InlineStreamGuard, ResetStreamDifferentSameDevice) {
TestGuardImpl::setDeviceIndex(0);
TestGuardImpl::resetStreams();
{
TestGuard g(stream(1, 2));
g.reset_stream(stream(1, 3));
ASSERT_EQ(TestGuardImpl::getDeviceIndex(), 1);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 3);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
ASSERT_EQ(g.original_stream(), stream(0, 0));
ASSERT_EQ(g.current_stream(), stream(1, 3));
ASSERT_EQ(g.original_device(), dev(0));
ASSERT_EQ(g.current_device(), dev(1));
}
ASSERT_EQ(TestGuardImpl::getDeviceIndex(), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(InlineStreamGuard, ResetStreamDifferentDevice) {
TestGuardImpl::setDeviceIndex(0);
TestGuardImpl::resetStreams();
{
TestGuard g(stream(1, 2));
g.reset_stream(stream(2, 3));
ASSERT_EQ(TestGuardImpl::getDeviceIndex(), 2);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(2), 3);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
ASSERT_EQ(g.original_stream(), stream(0, 0));
ASSERT_EQ(g.current_stream(), stream(2, 3));
ASSERT_EQ(g.original_device(), dev(0));
ASSERT_EQ(g.current_device(), dev(2));
}
ASSERT_EQ(TestGuardImpl::getDeviceIndex(), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(2), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
}
// -- OptionalInlineStreamGuard
// -------------------------------------------------------
using OptionalTestGuard = InlineOptionalStreamGuard<TestGuardImpl>;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(InlineOptionalStreamGuard, Constructor) {
TestGuardImpl::setDeviceIndex(0);
TestGuardImpl::resetStreams();
{
OptionalTestGuard g(stream(1, 2));
ASSERT_EQ(TestGuardImpl::getDeviceIndex(), 1);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 2);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
ASSERT_EQ(g.original_stream(), make_optional(stream(0, 0)));
ASSERT_EQ(g.current_stream(), make_optional(stream(1, 2)));
}
ASSERT_EQ(TestGuardImpl::getDeviceIndex(), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
{
OptionalTestGuard g(make_optional(stream(1, 2)));
ASSERT_EQ(TestGuardImpl::getDeviceIndex(), 1);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 2);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
ASSERT_EQ(g.original_stream(), make_optional(stream(0, 0)));
ASSERT_EQ(g.current_stream(), make_optional(stream(1, 2)));
}
ASSERT_EQ(TestGuardImpl::getDeviceIndex(), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
{
OptionalTestGuard g;
ASSERT_EQ(TestGuardImpl::getDeviceIndex(), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
}
ASSERT_EQ(TestGuardImpl::getDeviceIndex(), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(InlineOptionalStreamGuard, ResetStreamSameDevice) {
TestGuardImpl::setDeviceIndex(0);
TestGuardImpl::resetStreams();
{
OptionalTestGuard g;
g.reset_stream(stream(1, 3));
ASSERT_EQ(TestGuardImpl::getDeviceIndex(), 1);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 3);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
ASSERT_EQ(g.original_stream(), make_optional(stream(0, 0)));
ASSERT_EQ(g.current_stream(), make_optional(stream(1, 3)));
}
ASSERT_EQ(TestGuardImpl::getDeviceIndex(), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(InlineOptionalStreamGuard, ResetStreamDifferentDevice) {
TestGuardImpl::setDeviceIndex(0);
TestGuardImpl::resetStreams();
{
OptionalTestGuard g;
g.reset_stream(stream(2, 3));
ASSERT_EQ(TestGuardImpl::getDeviceIndex(), 2);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(2), 3);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
ASSERT_EQ(g.original_stream(), make_optional(stream(0, 0)));
ASSERT_EQ(g.current_stream(), make_optional(stream(2, 3)));
}
ASSERT_EQ(TestGuardImpl::getDeviceIndex(), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(2), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
}
// -- InlineMultiStreamGuard
// -------------------------------------------------------
using MultiTestGuard = InlineMultiStreamGuard<TestGuardImpl>;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(InlineMultiStreamGuard, Constructor) {
TestGuardImpl::resetStreams();
{
std::vector<Stream> streams;
MultiTestGuard g(streams);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 0);
}
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 0);
{
std::vector<Stream> streams = {stream(0, 2)};
MultiTestGuard g(streams);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 2);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 0);
}
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 0);
{
std::vector<Stream> streams = {stream(1, 3)};
MultiTestGuard g(streams);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 3);
}
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 0);
{
std::vector<Stream> streams = {stream(0, 2), stream(1, 3)};
MultiTestGuard g(streams);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 2);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 3);
}
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(0), 0);
ASSERT_EQ(TestGuardImpl::getCurrentStreamIdFor(1), 0);
}
| 38.375 | 79 | 0.727315 | brooks-anderson |
ef8238f0bd5700a762652ad239facb74f7ff7063 | 498 | cpp | C++ | tests/ds18b20/main/ds18b20.cpp | chegewara/esp32sx-c-plus-wrappers | dcc61fc057d6d07b354b4bd352956240707ca482 | [
"MIT"
] | 3 | 2021-12-15T10:24:08.000Z | 2022-03-10T14:34:10.000Z | tests/ds18b20/main/ds18b20.cpp | chegewara/esp32sx-c-plus-wrappers | dcc61fc057d6d07b354b4bd352956240707ca482 | [
"MIT"
] | null | null | null | tests/ds18b20/main/ds18b20.cpp | chegewara/esp32sx-c-plus-wrappers | dcc61fc057d6d07b354b4bd352956240707ca482 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include "ds18b20.hpp"
DS18B20 sensor(1);
extern "C" void app_main(void)
{
sensor.init(GPIO_NUM_14);
sensor.read();
sensor.addSensors();
sensor.removeSensors();
sensor.addSensors();
while (1)
{
sensor.read();
printf("Temperature readings (degrees C):\n");
for (size_t i = 0; i <= sensor.getCount(); i++)
{
printf("\t%d: %.2f\n", i, sensor.getTemp(i));
}
vTaskDelay(100);
}
}
| 19.153846 | 57 | 0.532129 | chegewara |
ef82a602364d0663ddfc1520af0a05bce17e5979 | 14,810 | cpp | C++ | contracts/eosio.system/src/voting.cpp | guilledk/telos.contracts | eff3dc89c6904196f0cf0591df2c2313e2f57800 | [
"MIT"
] | 11 | 2020-01-01T00:14:35.000Z | 2022-03-08T10:50:32.000Z | contracts/eosio.system/src/voting.cpp | guilledk/telos.contracts | eff3dc89c6904196f0cf0591df2c2313e2f57800 | [
"MIT"
] | 8 | 2020-11-28T06:16:09.000Z | 2022-03-28T11:53:00.000Z | contracts/eosio.system/src/voting.cpp | guilledk/telos.contracts | eff3dc89c6904196f0cf0591df2c2313e2f57800 | [
"MIT"
] | 11 | 2020-01-03T00:47:43.000Z | 2022-01-23T10:07:40.000Z | #include <eosio.system/eosio.system.hpp>
#include <eosio/eosio.hpp>
#include <eosio/datastream.hpp>
#include <eosio/serialize.hpp>
#include <eosio/multi_index.hpp>
#include <eosio/privileged.hpp>
#include <eosio/singleton.hpp>
#include <eosio/transaction.hpp>
#include <eosio.token/eosio.token.hpp>
#include <boost/container/flat_map.hpp>
#include "system_rotation.cpp"
#include <algorithm>
#include <cmath>
namespace eosiosystem {
using eosio::const_mem_fun;
using eosio::current_time_point;
using eosio::indexed_by;
using eosio::microseconds;
using eosio::singleton;
void system_contract::regproducer( const name& producer, const eosio::public_key& producer_key, const std::string& url, uint16_t location ) {
check( url.size() < 512, "url too long" );
check( producer_key != eosio::public_key(), "public key should not be the default value" );
require_auth( producer );
const auto ct = current_time_point();
auto prod = _producers.find(producer.value);
if ( prod != _producers.end() ) {
_producers.modify( prod, producer, [&]( producer_info& info ) {
auto now = block_timestamp(current_time_point());
block_timestamp penalty_expiration_time = block_timestamp(info.last_time_kicked.to_time_point() + time_point(hours(int64_t(info.kick_penalty_hours))));
check(now.slot > penalty_expiration_time.slot,
std::string("Producer is not allowed to register at this time. Please fix your node and try again later in: "
+ std::to_string( uint32_t((penalty_expiration_time.slot - now.slot) / 2 ))
+ " seconds").c_str());
info.producer_key = producer_key;
info.url = url;
info.location = location;
info.is_active = true;
info.unreg_reason = "";
});
} else {
_producers.emplace( producer, [&]( producer_info& info ){
info.owner = producer;
info.total_votes = 0;
info.producer_key = producer_key;
info.is_active = true;
info.url = url;
info.location = location;
info.last_claim_time = ct;
info.unreg_reason = "";
});
}
}
void system_contract::unregprod( const name& producer ) {
require_auth( producer );
const auto& prod = _producers.get( producer.value, "producer not found" );
_producers.modify( prod, same_payer, [&]( producer_info& info ){
info.deactivate();
});
}
void system_contract::unregreason( name producer, std::string reason ) {
check( reason.size() < 255, "The reason is too long. Reason should not have more than 255 characters.");
require_auth( producer );
const auto& prod = _producers.get( producer.value, "producer not found" );
_producers.modify( prod, same_payer, [&]( producer_info& info ){
info.deactivate();
info.unreg_reason = reason;
});
}
void system_contract::update_elected_producers( const block_timestamp& block_time ) {
_gstate.last_producer_schedule_update = block_time;
auto idx = _producers.get_index<"prototalvote"_n>();
uint32_t totalActiveVotedProds = uint32_t(std::distance(idx.begin(), idx.end()));
totalActiveVotedProds = totalActiveVotedProds > MAX_PRODUCERS ? MAX_PRODUCERS : totalActiveVotedProds;
std::vector<eosio::producer_key> prods;
prods.reserve(size_t(totalActiveVotedProds));
for ( auto it = idx.cbegin(); it != idx.cend() && prods.size() < totalActiveVotedProds && it->total_votes > 0 && it->active(); ++it ) {
prods.emplace_back( eosio::producer_key{it->owner, it->producer_key} );
}
std::vector<eosio::producer_key> top_producers = check_rotation_state(prods, block_time);
/// sort by producer name
std::sort( top_producers.begin(), top_producers.end() );
auto schedule_version = set_proposed_producers(top_producers);
if (schedule_version >= 0) {
print("\n**new schedule was proposed**");
_gstate.last_proposed_schedule_update = block_time;
_gschedule_metrics.producers_metric.erase( _gschedule_metrics.producers_metric.begin(), _gschedule_metrics.producers_metric.end());
std::vector<producer_metric> psm;
std::for_each(top_producers.begin(), top_producers.end(), [&psm](auto &tp) {
auto bp_name = tp.producer_name;
psm.emplace_back(producer_metric{ bp_name, 12 });
});
_gschedule_metrics.producers_metric = psm;
_gstate.last_producer_schedule_size = static_cast<decltype(_gstate.last_producer_schedule_size)>(top_producers.size());
}
}
/*
* This function caculates the inverse weight voting.
* The maximum weighted vote will be reached if an account votes for the maximum number of registered producers (up to 30 in total).
*/
double system_contract::inverse_vote_weight(double staked, double amountVotedProducers) {
if (amountVotedProducers == 0.0) {
return 0;
}
double percentVoted = amountVotedProducers / MAX_VOTE_PRODUCERS;
double voteWeight = (sin(M_PI * percentVoted - M_PI_2) + 1.0) / 2.0;
return (voteWeight * staked);
}
void system_contract::voteproducer( const name& voter_name, const name& proxy, const std::vector<name>& producers ) {
require_auth( voter_name );
vote_stake_updater( voter_name );
update_votes( voter_name, proxy, producers, true );
// auto rex_itr = _rexbalance.find( voter_name.value ); Remove requirement to vote 21 BPs or select a proxy to stake to REX
// if( rex_itr != _rexbalance.end() && rex_itr->rex_balance.amount > 0 ) {
// check_voting_requirement( voter_name, "voter holding REX tokens must vote for at least 21 producers or for a proxy" );
// }
}
void system_contract::update_votes( const name& voter_name, const name& proxy, const std::vector<name>& producers, bool voting ) {
//validate input
if ( proxy ) {
check( producers.size() == 0, "cannot vote for producers and proxy at same time" );
check( voter_name != proxy, "cannot proxy to self" );
} else {
check( producers.size() <= 30, "attempt to vote for too many producers" );
for( size_t i = 1; i < producers.size(); ++i ) {
check( producers[i-1] < producers[i], "producer votes must be unique and sorted" );
}
}
auto voter = _voters.find( voter_name.value );
check( voter != _voters.end(), "user must stake before they can vote" ); /// staking creates voter object
check( !proxy || !voter->is_proxy, "account registered as a proxy is not allowed to use a proxy" );
auto totalStaked = voter->staked;
if(voter->is_proxy){
totalStaked += voter->proxied_vote_weight;
}
// when unvoting, set the stake used for calculations to 0
// since it is the equivalent to retracting your stake
if(voting && !proxy && producers.size() == 0){
totalStaked = 0;
}
// when a voter or a proxy votes or changes stake, the total_activated stake should be re-calculated
// any proxy stake handling should be done when the proxy votes or on weight propagation
// if(_gstate.thresh_activated_stake_time == 0 && !proxy && !voter->proxy){
if(!proxy && !voter->proxy){
_gstate.total_activated_stake += totalStaked - voter->last_stake;
}
auto new_vote_weight = inverse_vote_weight((double)totalStaked, (double) producers.size());
boost::container::flat_map<name, std::pair< double, bool > > producer_deltas;
// print("\n Voter : ", voter->last_stake, " = ", voter->last_vote_weight, " = ", proxy, " = ", producers.size(), " = ", totalStaked, " = ", new_vote_weight);
//Voter from second vote
if ( voter->last_stake > 0 ) {
//if voter account has set proxy to another voter account
if( voter->proxy ) {
auto old_proxy = _voters.find( voter->proxy.value );
check( old_proxy != _voters.end(), "old proxy not found" ); //data corruption
_voters.modify( old_proxy, same_payer, [&]( auto& vp ) {
vp.proxied_vote_weight -= voter->last_stake;
});
// propagate weight here only when switching proxies
// otherwise propagate happens in the case below
if( proxy != voter->proxy ) {
_gstate.total_activated_stake += totalStaked - voter->last_stake;
propagate_weight_change( *old_proxy );
}
} else {
for( const auto& p : voter->producers ) {
auto& d = producer_deltas[p];
d.first -= voter->last_vote_weight;
d.second = false;
}
}
}
if( proxy ) {
auto new_proxy = _voters.find( proxy.value );
check( new_proxy != _voters.end(), "invalid proxy specified" ); //if ( !voting ) { data corruption } else { wrong vote }
check( !voting || new_proxy->is_proxy, "proxy not found" );
_voters.modify( new_proxy, same_payer, [&]( auto& vp ) {
vp.proxied_vote_weight += voter->staked;
});
if((*new_proxy).last_vote_weight > 0){
_gstate.total_activated_stake += totalStaked - voter->last_stake;
propagate_weight_change( *new_proxy );
}
} else {
if( new_vote_weight >= 0 ) {
for( const auto& p : producers ) {
auto& d = producer_deltas[p];
d.first += new_vote_weight;
d.second = true;
}
}
}
for( const auto& pd : producer_deltas ) {
auto pitr = _producers.find( pd.first.value );
if( pitr != _producers.end() ) {
if( voting && !pitr->active() && pd.second.second /* from new set */ ) {
check( false, ( "producer " + pitr->owner.to_string() + " is not currently registered" ).data() );
}
_producers.modify( pitr, same_payer, [&]( auto& p ) {
p.total_votes += pd.second.first;
if ( p.total_votes < 0 ) { // floating point arithmetics can give small negative numbers
p.total_votes = 0;
}
_gstate.total_producer_vote_weight += pd.second.first;
//check( p.total_votes >= 0, "something bad happened" );
});
} else {
if( pd.second.second ) {
check( false, ( "producer " + pd.first.to_string() + " is not registered" ).data() );
}
}
}
_voters.modify( voter, same_payer, [&]( auto& av ) {
av.last_vote_weight = new_vote_weight;
av.last_stake = int64_t(totalStaked);
av.producers = producers;
av.proxy = proxy;
});
}
void system_contract::regproxy( const name& proxy, bool isproxy ) {
//require_auth( proxy );
check ( !isproxy, "proxy voting is disabled" );
auto pitr = _voters.find( proxy.value );
if ( pitr != _voters.end() ) {
check( isproxy != pitr->is_proxy, "action has no effect" );
check( !isproxy || !pitr->proxy, "account that uses a proxy is not allowed to become a proxy" );
_voters.modify( pitr, same_payer, [&]( auto& p ) {
p.is_proxy = isproxy;
});
update_votes(pitr->owner, pitr->proxy, pitr->producers, true);
} else {
_voters.emplace( proxy, [&]( auto& p ) {
p.owner = proxy;
p.is_proxy = isproxy;
});
}
}
void system_contract::propagate_weight_change( const voter_info& voter ) {
check( voter.proxy == name(0) || !voter.is_proxy, "account registered as a proxy is not allowed to use a proxy");
auto totalStake = voter.staked;
if(voter.is_proxy){
totalStake += voter.proxied_vote_weight;
}
double new_weight = inverse_vote_weight((double)totalStake, voter.producers.size());
double delta = new_weight - voter.last_vote_weight;
if (voter.proxy) { // this part should never happen since the function is called only on proxies
if(voter.last_stake != totalStake){
auto &proxy = _voters.get(voter.proxy.value, "proxy not found"); // data corruption
_voters.modify(proxy, same_payer, [&](auto &p) {
p.proxied_vote_weight += totalStake - voter.last_stake;
});
propagate_weight_change(proxy);
}
} else {
for (auto acnt : voter.producers) {
auto &pitr = _producers.get(acnt.value, "producer not found"); // data corruption
_producers.modify(pitr, same_payer, [&](auto &p) {
p.total_votes += delta;
_gstate.total_producer_vote_weight += delta;
});
}
}
_voters.modify(voter, same_payer, [&](auto &v) {
v.last_vote_weight = new_weight;
v.last_stake = totalStake;
});
}
void system_contract::recalculate_votes(){
if (_gstate.total_producer_vote_weight <= -0.1){ // -0.1 threshold for floating point calc ?
_gstate.total_producer_vote_weight = 0;
_gstate.total_activated_stake = 0;
for(auto producer = _producers.begin(); producer != _producers.end(); ++producer){
_producers.modify(producer, same_payer, [&](auto &p) {
p.total_votes = 0;
});
}
boost::container::flat_map< name, bool> processed_proxies;
for (auto voter = _voters.begin(); voter != _voters.end(); ++voter) {
if(voter->proxy && !processed_proxies[voter->proxy]){
auto proxy = _voters.find(voter->proxy.value);
_voters.modify( proxy, same_payer, [&]( auto& av ) {
av.last_vote_weight = 0;
av.last_stake = 0;
av.proxied_vote_weight = 0;
});
processed_proxies[voter->proxy] = true;
}
if(!voter->is_proxy || !processed_proxies[voter->owner]){
_voters.modify( voter, same_payer, [&]( auto& av ) {
av.last_vote_weight = 0;
av.last_stake = 0;
av.proxied_vote_weight = 0;
});
processed_proxies[voter->owner] = true;
}
update_votes(voter->owner, voter->proxy, voter->producers, true);
}
}
}
} /// namespace eosiosystem
| 41.836158 | 164 | 0.594261 | guilledk |
ef86603267050f3b4f30e94dfe5e4ada8d338f80 | 8,130 | cc | C++ | llcc/front-end/src/lexical_analyzer.cc | toy-compiler/toy_js_compiler | 4267c96cd65b2359b6ba70dad7ee1f17114e88fc | [
"MIT"
] | 2 | 2019-03-12T07:42:33.000Z | 2019-03-12T07:42:41.000Z | llcc/front-end/src/lexical_analyzer.cc | toy-compiler/awesomeCC | 4267c96cd65b2359b6ba70dad7ee1f17114e88fc | [
"MIT"
] | null | null | null | llcc/front-end/src/lexical_analyzer.cc | toy-compiler/awesomeCC | 4267c96cd65b2359b6ba70dad7ee1f17114e88fc | [
"MIT"
] | 1 | 2019-11-29T11:13:22.000Z | 2019-11-29T11:13:22.000Z | /**
* @file lexical_analyzer.cc
* @brief 词法分析器,具体实现
*/
#include "../include/lexical_analyzer.h"
/**
* @brief LexicalAnalyzer类构造函数
*/
LexicalAnalyzer::LexicalAnalyzer() {
in_comment = false;
};
/**
* @brief 判断curPos处是否为空字符
* @return
* -<em>true</em> 是空字符
* -<em>false</em> 不是空字符
*/
bool LexicalAnalyzer::_isBlank() {
char cur_char = sentence[cur_pos];
return (cur_char == '\t' ||
cur_char == '\n' ||
cur_char == '\r' ||
cur_char == ' ');
}
/**
* @brief 判断curPos处是是不是备注开始
* @return
* -<em>true</em> 是备注开始
* -<em>false</em> 不是
*/
bool LexicalAnalyzer::_isCommentStart() {
return (sentence[cur_pos] == '/' &&
cur_pos + 1 < len &&
sentence[cur_pos + 1] == '*');
}
/**
* @brief 判断curPos处是是不是备注结束
* @return
* -<em>true</em> 是备注结束
* -<em>false</em> 不是
*/
bool LexicalAnalyzer::_isCommentEnd() {
return (sentence[cur_pos] == '*' &&
cur_pos + 1 < len &&
sentence[cur_pos + 1] == '/');
}
/**
* @brief 自增curPos直到不为空且不为注释中
*/
void LexicalAnalyzer::_skipBlank() {
while (cur_pos < len &&
(_isBlank() || // 是空字符
(in_comment && ! _isCommentEnd()))) // 或者在评论里
cur_pos ++;
if (cur_pos < len && _isCommentEnd()) { // 判断是不是评论的结束
in_comment = false; // 读取 `*/`
cur_pos += 2;
if (cur_pos < len)
_skipBlank(); // 读完注释后继续跳过
}
}
/**
* @brief 设置等待分析的句子,初始化
* @param _sentence string, 等待分析的句子
*/
void LexicalAnalyzer::_init(string _sentence) {
len = int(_sentence.length());
sentence = _sentence;
tokens.clear();
cur_pos = 0;
}
/**
* @brief 判断是否是关键词
* @param word string, 等待分析的词
* @return
* -<em>true</em> 是关键词
* -<em>false</em> 不是关键词
*/
bool LexicalAnalyzer::_isKeyword(string word) {
for (string kw: Token::KEYWORDS)
if (kw == word)
return true;
return false;
}
/**
* @brief 判断是否是分隔符
* @param ch char, 等待分析的字符
* @return
* -<em>true</em> 是分隔符
* -<em>false</em> 不是分隔符
*/
bool LexicalAnalyzer::_isSeparator(char ch) {
for (char sp: Token::SEPARATORS)
if (sp == ch)
return true;
return false;
}
/**
* @brief 判断是否是运算符
* @param ch char, 等待分析的字符
* @return
* -<em>true</em> 是运算符
* -<em>false</em> 不是运算符
*/
bool LexicalAnalyzer::_isOperator(char ch) {
for (auto o: Token::OPERATORS)
if (ch == o[0])
return true;
return false;
}
/**
* @brief 分析当前句子
*/
void LexicalAnalyzer::_analyze() {
char cur_char;
while (cur_pos < len) {
_skipBlank();
cur_char = sentence[cur_pos];
// 处理注释
if (_isCommentStart()) {
in_comment = true;
cur_pos += 2;
continue;
}
// 关键字 和 标识符
else if (isalpha(cur_char) || cur_char == '_') {
// 找结尾
int temp_len = 0;
while (cur_pos + temp_len <= len &&
(isalpha(sentence[cur_pos + temp_len]) || // 字母
sentence[cur_pos + temp_len] == '_' || // _
isdigit(sentence[cur_pos + temp_len]))) // 数字
temp_len ++;
// 截取 并 加入token列表
string temp_str = sentence.substr(cur_pos, temp_len);
tokens.emplace_back(Token(temp_str,
_isKeyword(temp_str) ? TOKEN_TYPE_ENUM::KEYWORD : TOKEN_TYPE_ENUM::IDENTIFIER,
cur_pos, cur_line_number));
cur_pos += temp_len;
continue;
}
// 数字常量
else if (isdigit(cur_char) || cur_char == '.') {
// 找结尾
int temp_len = 0;
bool hasDot = false;
while (cur_pos + temp_len <= len &&
(isdigit(sentence[cur_pos + temp_len]) || sentence[cur_pos + temp_len] == '.')) {
if (sentence[cur_pos + temp_len] == '.') {
if (not hasDot)
hasDot = true;
else
throw Error("in digit constant, too many dots in one number",
cur_line_number, cur_pos);
}
temp_len ++;
}
// 截取 并 加入token列表
tokens.emplace_back(Token(sentence.substr(cur_pos, temp_len),
TOKEN_TYPE_ENUM::DIGIT_CONSTANT,
cur_pos, cur_line_number));
cur_pos += temp_len;
continue;
}
// 分隔符 和 字符串常量
else if (_isSeparator(cur_char)) {
// 先加入token列表
string temp_str = sentence.substr(cur_pos, 1);
tokens.emplace_back(Token(temp_str, TOKEN_TYPE_ENUM::SEPARATOR,
cur_pos, cur_line_number));
// 如果是 `'`或者`"` 需要考虑一下匹配
int temp_len = 0;
if (cur_char == '\"' || cur_char == '\'') {
cur_pos ++;
while (cur_pos + temp_len < len &&
sentence[cur_pos + temp_len] != cur_char)
temp_len ++;
// 匹配不上
if (cur_pos + temp_len >= len || sentence[cur_pos + temp_len] != cur_char)
throw Error("in string constant, lack of " + char2string(cur_char),
cur_line_number, cur_pos);
tokens.emplace_back(Token(sentence.substr(cur_pos, temp_len),
TOKEN_TYPE_ENUM::STRING_CONSTANT,
cur_pos + 1, cur_line_number));
cur_pos += temp_len;
tokens.emplace_back(Token(temp_str, TOKEN_TYPE_ENUM::SEPARATOR,
cur_pos + 1, cur_line_number));
}
cur_pos ++;
continue;
}
// 运算符
else if (_isOperator(cur_char)) {
// ++ -- << >> && || ==
if ((cur_char == '+' || cur_char == '-' || cur_char == '<' || cur_char == '>' ||
cur_char == '&' || cur_char == '|' || cur_char == '=') &&
cur_pos + 1 < len && sentence[cur_pos + 1] == cur_char) {
tokens.emplace_back(Token(sentence.substr(cur_pos, 2), TOKEN_TYPE_ENUM::OPERATOR,
cur_pos, cur_line_number));
cur_pos += 2;
}
// <= >= !=
else if ((cur_char == '<' || cur_char == '>' || cur_char == '!') &&
cur_pos + 1 < len &&
sentence[cur_pos + 1] == '=') {
tokens.emplace_back(Token(sentence.substr(cur_pos, 2), TOKEN_TYPE_ENUM::OPERATOR,
cur_pos, cur_line_number));
cur_pos += 2;
}
// 一位的运算符
else {
tokens.emplace_back(Token(sentence.substr(cur_pos, 1), TOKEN_TYPE_ENUM::OPERATOR,
cur_pos, cur_line_number));
cur_pos ++;
}
continue;
}
cur_pos ++;
}
}
/**
* @brief 分析一个程序(很多句子),如果正确生成Token列表,如果错误生成错误列表
* @param _sentences vector string, 等待分析的程序
* @param verbose bool, 是否就地输出tokens
*/
void LexicalAnalyzer::analyze(vector<string> _sentences, bool verbose) {
cur_line_number = 0;
in_comment = false;
all_tokens.clear();
try {
for (auto _s: _sentences) {
cur_line_number ++;
_init(_s);
_analyze();
for (auto t: tokens)
all_tokens.emplace_back(t);
}
if (verbose) {
cout << "Tokens\n";
for (auto t: all_tokens)
cout << t;
}
}
catch (Error & e) {
cout << "Lexical analyze errors" << endl;
cout << e;
exit(0);
}
}
/**
* @brief 得到Token列表
* @return vector<Token>
*/
vector<Token> LexicalAnalyzer::getAllTokens() {
return all_tokens;
}
| 26.057692 | 116 | 0.473924 | toy-compiler |
ef87441c699a7e1538738802e33fc97990ab8394 | 6,790 | cpp | C++ | module5/sw_parallel.cpp | madsbk/hpc_course | 8480e2992de2e617d061b0460f27b69c7f251bf8 | [
"MIT"
] | null | null | null | module5/sw_parallel.cpp | madsbk/hpc_course | 8480e2992de2e617d061b0460f27b69c7f251bf8 | [
"MIT"
] | null | null | null | module5/sw_parallel.cpp | madsbk/hpc_course | 8480e2992de2e617d061b0460f27b69c7f251bf8 | [
"MIT"
] | null | null | null | #include <vector>
#include <iostream>
#include <fstream>
#include <chrono>
#include <cmath>
#include <numeric>
#include <cassert>
#include <array>
#include <algorithm>
using real_t = float;
constexpr size_t NX = 512, NY = 512; //World Size
using grid_t = std::array<std::array<real_t, NX>, NY>;
class Sim_Configuration {
public:
int iter = 1000; // Number of iterations
double dt = 0.05; // Size of the integration time step
real_t g = 9.80665; // Gravitational acceleration
real_t dx = 1; // Integration step size in the horizontal direction
real_t dy = 1; // Integration step size in the vertical direction
int data_period = 100; // how often to save coordinate to file
std::string filename = "sw_output.data"; // name of the output file with history
Sim_Configuration(std::vector <std::string> argument){
for (long unsigned int i = 1; i<argument.size() ; i += 2){
std::string arg = argument[i];
if(arg=="-h"){ // Write help
std::cout << "./par --iter <number of iterations> --dt <time step>"
<< " --g <gravitational const> --dx <x grid size> --dy <y grid size>"
<< "--fperiod <iterations between each save> --out <name of output file>\n";
exit(0);
} else if (i == argument.size() - 1)
throw std::invalid_argument("The last argument (" + arg +") must have a value");
else if(arg=="--iter"){
if ((iter = std::stoi(argument[i+1])) < 0)
throw std::invalid_argument("iter most be a positive integer (e.g. -iter 1000)");
} else if(arg=="--dt"){
if ((dt = std::stod(argument[i+1])) < 0)
throw std::invalid_argument("dt most be a positive real number (e.g. -dt 0.05)");
} else if(arg=="--g"){
g = std::stod(argument[i+1]);
} else if(arg=="--dx"){
if ((dx = std::stod(argument[i+1])) < 0)
throw std::invalid_argument("dx most be a positive real number (e.g. -dx 1)");
} else if(arg=="--dy"){
if ((dy = std::stod(argument[i+1])) < 0)
throw std::invalid_argument("dy most be a positive real number (e.g. -dy 1)");
} else if(arg=="--fperiod"){
if ((data_period = std::stoi(argument[i+1])) < 0)
throw std::invalid_argument("dy most be a positive integer (e.g. -fperiod 100)");
} else if(arg=="--out"){
filename = argument[i+1];
} else{
std::cout << "---> error: the argument type is not recognized \n";
}
}
}
};
/** Representation of a water world including ghost lines, which is a "1-cell padding" of rows and columns
* around the world. These ghost lines is a technique to implement periodic boundary conditions. */
class Water {
public:
grid_t u{}; // The speed in the horizontal direction.
grid_t v{}; // The speed in the vertical direction.
grid_t e{}; // The water elevation.
Water() {
for (size_t i = 1; i < NY - 1; ++i)
for (size_t j = 1; j < NX - 1; ++j) {
real_t ii = 100.0 * (i - (NY - 2.0) / 2.0) / NY;
real_t jj = 100.0 * (j - (NX - 2.0) / 2.0) / NX;
e[i][j] = std::exp(-0.02 * (ii * ii + jj * jj));
}
}
};
/* Write a history of the water heights to an ASCII file
*
* @param water_history Vector of the all water worlds to write
* @param filename The output filename of the ASCII file
*/
void to_file(const std::vector<grid_t> &water_history, const std::string &filename){
std::ofstream file(filename);
file.write((const char*)(water_history.data()), sizeof(grid_t)*water_history.size());
}
/** Exchange the horizontal ghost lines i.e. copy the second data row to the very last data row and vice versa.
*
* @param data The data update, which could be the water elevation `e` or the speed in the horizontal direction `u`.
* @param shape The shape of data including the ghost lines.
*/
void exchange_horizontal_ghost_lines(grid_t& data) {
for (uint64_t j = 0; j < NX; ++j) {
data[0][j] = data[NY-2][j];
data[NY-1][j] = data[1][j];
}
}
/** Exchange the vertical ghost lines i.e. copy the second data column to the rightmost data column and vice versa.
*
* @param data The data update, which could be the water elevation `e` or the speed in the vertical direction `v`.
* @param shape The shape of data including the ghost lines.
*/
void exchange_vertical_ghost_lines(grid_t& data) {
for (uint64_t i = 0; i < NY; ++i) {
data[i][0] = data[i][NX-2];
data[i][NX-1] = data[i][1];
}
}
/** One integration step
*
* @param w The water world to update.
*/
void integrate(Water &w, const real_t dt, const real_t dx, const real_t dy, const real_t g) {
exchange_horizontal_ghost_lines(w.e);
exchange_horizontal_ghost_lines(w.v);
exchange_vertical_ghost_lines(w.e);
exchange_vertical_ghost_lines(w.u);
for (uint64_t i = 0; i < NY - 1; ++i)
for (uint64_t j = 0; j < NX - 1; ++j) {
w.u[i][j] -= dt / dx * g * (w.e[i][j+1] - w.e[i][j]);
w.v[i][j] -= dt / dy * g * (w.e[i + 1][j] - w.e[i][j]);
}
for (uint64_t i = 1; i < NY - 1; ++i)
for (uint64_t j = 1; j < NX - 1; ++j) {
w.e[i][j] -= dt / dx * (w.u[i][j] - w.u[i][j-1])
+ dt / dy * (w.v[i][j] - w.v[i-1][j]);
}
}
/** Simulation of shallow water
*
* @param num_of_iterations The number of time steps to simulate
* @param size The size of the water world excluding ghost lines
* @param output_filename The filename of the written water world history (HDF5 file)
*/
void simulate(const Sim_Configuration config) {
Water water_world = Water();
std::vector <grid_t> water_history;
auto begin = std::chrono::steady_clock::now();
for (uint64_t t = 0; t < config.iter; ++t) {
integrate(water_world, config.dt, config.dx, config.dy, config.g);
if (t % config.data_period == 0) {
water_history.push_back(water_world.e);
}
}
auto end = std::chrono::steady_clock::now();
to_file(water_history, config.filename);
std::cout << "checksum: " << std::accumulate(water_world.e.front().begin(), water_world.e.back().end(), 0.0) << std::endl;
std::cout << "elapsed time: " << (end - begin).count() / 1000000000.0 << " sec" << std::endl;
}
/** Main function that parses the command line and start the simulation */
int main(int argc, char **argv) {
auto config = Sim_Configuration({argv, argv+argc});
simulate(config);
return 0;
}
| 40.416667 | 126 | 0.57511 | madsbk |
ef8ed27b080958b77bfb153ebd32cd746fc9ef86 | 5,633 | cc | C++ | mysql-server/router/src/mock_server/src/mock_server_plugin.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/router/src/mock_server/src/mock_server_plugin.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/router/src/mock_server/src/mock_server_plugin.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | /*
Copyright (c) 2018, 2020, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "mock_server_plugin.h"
#include <array>
#include <climits> // PATH_MAX
#include <stdexcept>
#include <string>
#include <system_error> // error_code
#include "mysql/harness/config_parser.h"
#include "mysql/harness/logging/logging.h"
#include "mysql/harness/plugin.h"
#include "mysql/harness/stdx/filesystem.h"
#include "mysql_server_mock.h"
#include "mysqlrouter/plugin_config.h"
IMPORT_LOG_FUNCTIONS()
static constexpr const char kSectionName[]{"mock_server"};
class PluginConfig : public mysqlrouter::BasePluginConfig {
public:
std::string trace_filename;
std::string module_prefix;
std::string srv_address;
uint16_t srv_port;
std::string srv_protocol;
explicit PluginConfig(const mysql_harness::ConfigSection *section)
: mysqlrouter::BasePluginConfig(section),
trace_filename(get_option_string(section, "filename")),
module_prefix(get_option_string(section, "module_prefix")),
srv_address(get_option_string(section, "bind_address")),
srv_port(get_uint_option<uint16_t>(section, "port")),
srv_protocol(get_option_string(section, "protocol")) {}
std::string get_default(const std::string &option) const override {
std::error_code ec;
const auto cwd = stdx::filesystem::current_path(ec);
if (ec) {
throw std::system_error(ec);
}
const std::map<std::string, std::string> defaults{
{"bind_address", "0.0.0.0"},
{"module_prefix", cwd.native()},
{"port", "3306"},
{"protocol", "classic"},
};
auto it = defaults.find(option);
if (it == defaults.end()) {
return std::string();
}
return it->second;
}
bool is_required(const std::string &option) const override {
if (option == "filename") return true;
return false;
}
};
static std::map<std::string, std::shared_ptr<server_mock::MySQLServerMock>>
mock_servers;
static void init(mysql_harness::PluginFuncEnv *env) {
const mysql_harness::AppInfo *info = get_app_info(env);
try {
if (info->config != nullptr) {
for (const mysql_harness::ConfigSection *section :
info->config->sections()) {
if (section->name != kSectionName) {
continue;
}
PluginConfig config{section};
const std::string key = section->name + ":" + section->key;
mock_servers.emplace(std::make_pair(
key,
std::make_shared<server_mock::MySQLServerMock>(
config.trace_filename, config.module_prefix, config.srv_address,
config.srv_port, config.srv_protocol, 0)));
MockServerComponent::get_instance().register_server(
mock_servers.at(key));
}
}
} catch (const std::invalid_argument &exc) {
set_error(env, mysql_harness::kConfigInvalidArgument, "%s", exc.what());
} catch (const std::exception &exc) {
set_error(env, mysql_harness::kRuntimeError, "%s", exc.what());
} catch (...) {
set_error(env, mysql_harness::kUndefinedError, "Unexpected exception");
}
}
static void start(mysql_harness::PluginFuncEnv *env) {
const mysql_harness::ConfigSection *section = get_config_section(env);
std::string name;
if (!section->key.empty()) {
name = section->name + ":" + section->key;
} else {
name = section->name;
}
try {
auto srv = mock_servers.at(name);
srv->run(env);
} catch (const std::invalid_argument &exc) {
set_error(env, mysql_harness::kConfigInvalidArgument, "%s", exc.what());
} catch (const std::runtime_error &exc) {
set_error(env, mysql_harness::kRuntimeError, "%s: %s", name.c_str(),
exc.what());
} catch (const std::exception &exc) {
set_error(env, mysql_harness::kUndefinedError, "%s: %s", name.c_str(),
exc.what());
} catch (...) {
set_error(env, mysql_harness::kUndefinedError, "Unexpected exception");
}
}
static const std::array<const char *, 2> required = {{
"logger",
"router_protobuf",
}};
extern "C" {
mysql_harness::Plugin MOCK_SERVER_EXPORT harness_plugin_mock_server = {
mysql_harness::PLUGIN_ABI_VERSION, // abi-version
mysql_harness::ARCHITECTURE_DESCRIPTOR, // arch
"Routing MySQL connections between MySQL clients/connectors and "
"servers", // name
VERSION_NUMBER(0, 0, 1),
// requires
required.size(), required.data(),
// conflicts
0, nullptr,
init, // init
nullptr, // deinit
start, // start
nullptr, // stop
true, // declares_readiness
};
}
| 32.75 | 80 | 0.679034 | silenc3502 |
ef8fb8f51b907e2072632953e558b3c0a16d7b9d | 56 | hpp | C++ | src/boost_wave_grammars_cpp_expression_value.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_wave_grammars_cpp_expression_value.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_wave_grammars_cpp_expression_value.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/wave/grammars/cpp_expression_value.hpp>
| 28 | 55 | 0.839286 | miathedev |
ef9059aafa477bd01466cb3170654a32160d5cd4 | 12,745 | cpp | C++ | src/video_compress/dxt_glsl.cpp | thpryrchn/UltraGrid | f9fdd96ff73e05888d26c40aaaccdf4eb5fe7289 | [
"BSD-3-Clause"
] | 370 | 2016-10-05T15:19:00.000Z | 2022-03-29T22:12:28.000Z | src/video_compress/dxt_glsl.cpp | thpryrchn/UltraGrid | f9fdd96ff73e05888d26c40aaaccdf4eb5fe7289 | [
"BSD-3-Clause"
] | 165 | 2016-11-21T13:01:36.000Z | 2022-03-31T20:01:20.000Z | src/video_compress/dxt_glsl.cpp | thpryrchn/UltraGrid | f9fdd96ff73e05888d26c40aaaccdf4eb5fe7289 | [
"BSD-3-Clause"
] | 63 | 2016-10-13T12:07:45.000Z | 2022-03-23T19:46:10.000Z | /**
* @file video_compress/dxt_glsl.cpp
* @author Martin Pulec <pulec@cesnet.cz>
*/
/*
* Copyright (c) 2011-2014 CESNET, z. s. p. o.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, is permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of CESNET 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 AUTHORS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESSED 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 AUTHORS 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#include "config_unix.h"
#include "config_win32.h"
#endif // HAVE_CONFIG_H
#include <stdlib.h>
#include "gl_context.h"
#include "debug.h"
#include "dxt_compress/dxt_encoder.h"
#include "dxt_compress/dxt_util.h"
#include "host.h"
#include "lib_common.h"
#include "module.h"
#include "utils/video_frame_pool.h"
#include "video.h"
#include "video_compress.h"
#include <memory>
using namespace std;
namespace {
struct state_video_compress_rtdxt {
struct module module_data;
struct dxt_encoder **encoder;
int encoder_count;
decoder_t decoder;
unique_ptr<char []> decoded;
unsigned int configured:1;
unsigned int interlaced_input:1;
codec_t color_spec;
int encoder_input_linesize;
struct gl_context gl_context;
video_frame_pool pool;
};
static int configure_with(struct state_video_compress_rtdxt *s, struct video_frame *frame);
static void dxt_glsl_compress_done(struct module *mod);
static int configure_with(struct state_video_compress_rtdxt *s, struct video_frame *frame)
{
unsigned int x;
enum dxt_format format;
for (x = 0; x < frame->tile_count; ++x) {
if (vf_get_tile(frame, x)->width != vf_get_tile(frame, 0)->width ||
vf_get_tile(frame, x)->width != vf_get_tile(frame, 0)->width) {
fprintf(stderr,"[RTDXT] Requested to compress tiles of different size!");
exit_uv(EXIT_FAILURE);
return FALSE;
}
}
if (get_bits_per_component(frame->color_spec) > 8) {
LOG(LOG_LEVEL_NOTICE) << "[RTDXT] Converting from " << get_bits_per_component(frame->color_spec) <<
" to 8 bits. You may directly capture 8-bit signal to improve performance.\n";
}
switch (frame->color_spec) {
case RGB:
s->decoder = vc_memcpy;
format = DXT_FORMAT_RGB;
break;
case RGBA:
s->decoder = vc_memcpy;
format = DXT_FORMAT_RGBA;
break;
case R10k:
s->decoder = (decoder_t) vc_copyliner10k;
format = DXT_FORMAT_RGBA;
break;
case YUYV:
s->decoder = (decoder_t) vc_copylineYUYV;
format = DXT_FORMAT_YUV422;
break;
case UYVY:
s->decoder = vc_memcpy;
format = DXT_FORMAT_YUV422;
break;
case v210:
s->decoder = (decoder_t) vc_copylinev210;
format = DXT_FORMAT_YUV422;
break;
case DVS10:
s->decoder = (decoder_t) vc_copylineDVS10;
format = DXT_FORMAT_YUV422;
break;
case DPX10:
s->decoder = (decoder_t) vc_copylineDPX10toRGBA;
format = DXT_FORMAT_RGBA;
break;
default:
fprintf(stderr, "[RTDXT] Unknown codec: %d\n", frame->color_spec);
exit_uv(EXIT_FAILURE);
return FALSE;
}
int data_len = 0;
s->encoder = (struct dxt_encoder **) calloc(frame->tile_count, sizeof(struct dxt_encoder *));
if(s->color_spec == DXT1) {
for(int i = 0; i < (int) frame->tile_count; ++i) {
s->encoder[i] =
dxt_encoder_create(DXT_TYPE_DXT1, frame->tiles[0].width, frame->tiles[0].height, format,
s->gl_context.legacy);
}
data_len = dxt_get_size(frame->tiles[0].width, frame->tiles[0].height, DXT_TYPE_DXT1);
} else if(s->color_spec == DXT5){
for(int i = 0; i < (int) frame->tile_count; ++i) {
s->encoder[i] =
dxt_encoder_create(DXT_TYPE_DXT5_YCOCG, frame->tiles[0].width, frame->tiles[0].height, format,
s->gl_context.legacy);
}
data_len = dxt_get_size(frame->tiles[0].width, frame->tiles[0].height, DXT_TYPE_DXT5_YCOCG);
}
s->encoder_count = frame->tile_count;
for(int i = 0; i < (int) frame->tile_count; ++i) {
if(s->encoder[i] == NULL) {
fprintf(stderr, "[RTDXT] Unable to create decoder.\n");
exit_uv(EXIT_FAILURE);
return FALSE;
}
}
s->encoder_input_linesize = frame->tiles[0].width;
switch(format) {
case DXT_FORMAT_RGBA:
s->encoder_input_linesize *= 4;
break;
case DXT_FORMAT_RGB:
s->encoder_input_linesize *= 3;
break;
case DXT_FORMAT_YUV422:
s->encoder_input_linesize *= 2;
break;
case DXT_FORMAT_YUV:
/* not used - just not compilator to complain */
abort();
break;
}
assert(data_len > 0);
assert(s->encoder_input_linesize > 0);
struct video_desc compressed_desc;
compressed_desc = video_desc_from_frame(frame);
compressed_desc.color_spec = s->color_spec;
/* We will deinterlace the output frame */
if(frame->interlacing == INTERLACED_MERGED) {
compressed_desc.interlacing = PROGRESSIVE;
s->interlaced_input = TRUE;
fprintf(stderr, "[DXT compress] Enabling automatic deinterlacing.\n");
} else {
s->interlaced_input = FALSE;
}
s->pool.reconfigure(compressed_desc, data_len);
s->decoded = unique_ptr<char []>(new char[4 * compressed_desc.width * compressed_desc.height]);
s->configured = TRUE;
return TRUE;
}
static bool dxt_is_supported()
{
struct gl_context gl_context;
if (!init_gl_context(&gl_context, GL_CONTEXT_ANY)) {
return false;
} else {
destroy_gl_context(&gl_context);
return true;
}
}
struct module *dxt_glsl_compress_init(struct module *parent, const char *opts)
{
struct state_video_compress_rtdxt *s;
if(strcmp(opts, "help") == 0) {
printf("DXT GLSL comperssion usage:\n");
printf("\t-c RTDXT:DXT1\n");
printf("\t\tcompress with DXT1\n");
printf("\t-c RTDXT:DXT5\n");
printf("\t\tcompress with DXT5 YCoCg\n");
return &compress_init_noerr;
}
s = new state_video_compress_rtdxt();
if (strcasecmp(opts, "DXT5") == 0) {
s->color_spec = DXT5;
} else if (strcasecmp(opts, "DXT1") == 0) {
s->color_spec = DXT1;
} else if (opts[0] == '\0') {
s->color_spec = DXT1;
} else {
fprintf(stderr, "Unknown compression: %s\n", opts);
delete s;
return NULL;
}
if(!init_gl_context(&s->gl_context, GL_CONTEXT_ANY)) {
fprintf(stderr, "[RTDXT] Error initializing GL context");
delete s;
return NULL;
}
gl_context_make_current(NULL);
module_init_default(&s->module_data);
s->module_data.cls = MODULE_CLASS_DATA;
s->module_data.priv_data = s;
s->module_data.deleter = dxt_glsl_compress_done;
module_register(&s->module_data, parent);
return &s->module_data;
}
shared_ptr<video_frame> dxt_glsl_compress(struct module *mod, shared_ptr<video_frame> tx)
{
struct state_video_compress_rtdxt *s = (struct state_video_compress_rtdxt *) mod->priv_data;
int i;
unsigned char *line1, *line2;
unsigned int x;
gl_context_make_current(&s->gl_context);
if(!s->configured) {
int ret;
ret = configure_with(s, tx.get());
if(!ret)
return NULL;
}
shared_ptr<video_frame> out_frame = s->pool.get_frame();
for (x = 0; x < tx->tile_count; ++x) {
struct tile *in_tile = vf_get_tile(tx.get(), x);
struct tile *out_tile = vf_get_tile(out_frame.get(), x);
line1 = (unsigned char *) in_tile->data;
line2 = (unsigned char *) s->decoded.get();
for (i = 0; i < (int) in_tile->height; ++i) {
s->decoder(line2, line1, s->encoder_input_linesize,
0, 8, 16);
line1 += vc_get_linesize(in_tile->width, tx->color_spec);
line2 += s->encoder_input_linesize;
}
if(s->interlaced_input)
vc_deinterlace((unsigned char *) s->decoded.get(), s->encoder_input_linesize,
in_tile->height);
dxt_encoder_compress(s->encoder[x],
(unsigned char *) s->decoded.get(),
(unsigned char *) out_tile->data);
}
gl_context_make_current(NULL);
return out_frame;
}
static void dxt_glsl_compress_done(struct module *mod)
{
struct state_video_compress_rtdxt *s = (struct state_video_compress_rtdxt *) mod->priv_data;
if(s->encoder) {
for(int i = 0; i < s->encoder_count; ++i) {
if(s->encoder[i])
dxt_encoder_destroy(s->encoder[i]);
}
}
destroy_gl_context(&s->gl_context);
delete s;
}
const struct video_compress_info rtdxt_info = {
"RTDXT",
dxt_glsl_compress_init,
dxt_glsl_compress,
NULL,
NULL,
NULL,
NULL,
NULL,
[] {
return dxt_is_supported() ? list<compress_preset>{
{ "DXT1", 35, [](const struct video_desc *d){return (long)(d->width * d->height * d->fps * 4.0);},
{75, 0.3, 25}, {15, 0.1, 10} },
{ "DXT5", 50, [](const struct video_desc *d){return (long)(d->width * d->height * d->fps * 8.0);},
{75, 0.3, 35}, {15, 0.1, 20} },
} : list<compress_preset>{};
},
NULL
};
REGISTER_MODULE(rtdxt, &rtdxt_info, LIBRARY_CLASS_VIDEO_COMPRESS, VIDEO_COMPRESS_ABI_VERSION);
} // end of anonymous namespace
| 36.104816 | 126 | 0.537466 | thpryrchn |
ef91c55817be5168e77058674085a768af6a087d | 628 | cpp | C++ | 5_lesson/run.cpp | JonMuehlst/INTROCPP | 5f394c58c66a873bafb11dce54207a1dd580c916 | [
"MIT"
] | null | null | null | 5_lesson/run.cpp | JonMuehlst/INTROCPP | 5f394c58c66a873bafb11dce54207a1dd580c916 | [
"MIT"
] | null | null | null | 5_lesson/run.cpp | JonMuehlst/INTROCPP | 5f394c58c66a873bafb11dce54207a1dd580c916 | [
"MIT"
] | null | null | null | #include <iostream>
#include "binom.h"
#include "selection_sort.h"
#include "gtest/gtest.h"
int main(int argc, char **argv) {
/*
Selection sort
*/
int arr[MAX_ARR_SIZE]; // static allocation
int arr_size= getArrayFromInput(arr, MAX_ARR_SIZE);
printArr(arr, 0, arr_size);
sort(arr, arr_size);
printArr(arr, 0, arr_size);
/*
Binom
*/
int n = 5, k = 3, ans = 0;
ans = binom(n,k);
std::cout << "n choose k equals: " << ans << std::endl;
/*
run tests
*/
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | 16.972973 | 59 | 0.55414 | JonMuehlst |
ef91e7b0d3d6ba358e8bef8f3d02c4fd91c08ddf | 3,039 | cpp | C++ | src/public/src/fssimplewindow/samples/sample02-echo/sample02-echo.cpp | rothberg-cmu/rothberg-run | a42df5ca9fae97de77753864f60d05295d77b59f | [
"MIT"
] | 1 | 2019-08-10T00:24:09.000Z | 2019-08-10T00:24:09.000Z | samples/fssimplewindow/samples/sample02-echo/sample02-echo.cpp | captainys/MMLPlayer | ce1d1a2a349b50f240527ca686e24f8ce2446449 | [
"BSD-3-Clause"
] | null | null | null | samples/fssimplewindow/samples/sample02-echo/sample02-echo.cpp | captainys/MMLPlayer | ce1d1a2a349b50f240527ca686e24f8ce2446449 | [
"BSD-3-Clause"
] | 2 | 2019-05-01T03:11:10.000Z | 2019-05-01T03:30:35.000Z | /* ////////////////////////////////////////////////////////////
File Name: sample02-echo.cpp
Copyright (c) 2017 Soji Yamakawa. All rights reserved.
http://www.ysflight.com
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//////////////////////////////////////////////////////////// */
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#endif
#ifndef __APPLE__
#include <GL/gl.h>
#include <GL/glu.h>
#else
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#endif
#include <fssimplewindow.h>
#include <ysglfontdata.h>
int main(void)
{
FsOpenWindow(32,32,800,600,1); // 800x600 pixels, useDoubleBuffer=1
int listBase;
listBase=glGenLists(256);
YsGlUseFontBitmap8x12(listBase);
glListBase(listBase);
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glDepthFunc(GL_ALWAYS);
int nChr;
char str[256];
nChr=0;
str[0]=0;
FsPassedTime();
while(1)
{
int passedTime;
int keyCode,charCode;
FsPollDevice();
keyCode=FsInkey();
charCode=FsInkeyChar();
if(isprint(charCode) && nChr<255)
{
str[nChr]=charCode;
nChr++;
str[nChr]=0;
}
if(keyCode==FSKEY_ESC)
{
break;
}
else if(keyCode==FSKEY_BS && nChr>0)
{
nChr--;
str[nChr]=0;
}
int wid,hei;
FsGetWindowSize(wid,hei);
glViewport(0,0,wid,hei);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0,(float)wid-1,(float)hei-1,0,-1,1);
glClearColor(0.0,0.0,0.0,0.0);
glClear(GL_COLOR_BUFFER_BIT);
const char *msg="Type Keys:";
glColor3ub(255,255,255);
glRasterPos2i(32,32);
glCallLists(strlen(msg),GL_UNSIGNED_BYTE,msg);
glRasterPos2i(32,48);
glCallLists(nChr,GL_UNSIGNED_BYTE,str);
FsSwapBuffers();
passedTime=FsPassedTime();
FsSleep(20-passedTime);
}
return 0;
}
| 23.55814 | 81 | 0.708128 | rothberg-cmu |
ef947b93d9c89103f82c52d600b4fc8345b36f5a | 6,953 | cpp | C++ | src/tools/gripper-control.cpp | Rascof/sot-core | 281ed2a1b40b7945b5a3d5735f785b9004b19f87 | [
"BSD-2-Clause"
] | 12 | 2016-03-28T07:15:27.000Z | 2022-01-05T13:41:06.000Z | src/tools/gripper-control.cpp | Rascof/sot-core | 281ed2a1b40b7945b5a3d5735f785b9004b19f87 | [
"BSD-2-Clause"
] | 121 | 2015-02-17T08:38:25.000Z | 2021-12-01T10:54:05.000Z | src/tools/gripper-control.cpp | Rascof/sot-core | 281ed2a1b40b7945b5a3d5735f785b9004b19f87 | [
"BSD-2-Clause"
] | 24 | 2015-07-01T16:25:24.000Z | 2021-11-08T15:06:58.000Z | /*
* Copyright 2010,
* François Bleibel,
* Olivier Stasse,
*
* CNRS/AIST
*
*/
#define ENABLE_RT_LOG
#include <sot/core/debug.hh>
#include <sot/core/factory.hh>
#include <sot/core/gripper-control.hh>
#include <sot/core/macros-signal.hh>
#include <dynamic-graph/all-commands.h>
#include <dynamic-graph/real-time-logger.h>
using namespace dynamicgraph::sot;
using namespace dynamicgraph;
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(GripperControlPlugin, "GripperControl");
/* --- PLUGIN --------------------------------------------------------------- */
/* --- PLUGIN --------------------------------------------------------------- */
/* --- PLUGIN --------------------------------------------------------------- */
#define SOT_FULL_TO_REDUCED(sotName) \
sotName##FullSizeSIN(NULL, "GripperControl(" + name + \
")::input(vector)::" + #sotName + "FullIN"), \
sotName##ReduceSOUT(SOT_INIT_SIGNAL_2(GripperControlPlugin::selector, \
sotName##FullSizeSIN, \
dynamicgraph::Vector, \
selectionSIN, Flags), \
"GripperControl(" + name + \
")::input(vector)::" + #sotName + "ReducedOUT")
const double GripperControl::OFFSET_DEFAULT = 0.9;
// TODO: hard coded
const double DT = 0.005;
GripperControl::GripperControl(void)
: offset(GripperControl::OFFSET_DEFAULT), factor() {}
GripperControlPlugin::GripperControlPlugin(const std::string &name)
: Entity(name), calibrationStarted(false),
positionSIN(NULL,
"GripperControl(" + name + ")::input(vector)::position"),
positionDesSIN(NULL, "GripperControl(" + name +
")::input(vector)::positionDes"),
torqueSIN(NULL, "GripperControl(" + name + ")::input(vector)::torque"),
torqueLimitSIN(NULL, "GripperControl(" + name +
")::input(vector)::torqueLimit"),
selectionSIN(NULL, "GripperControl(" + name + ")::input(vector)::selec")
,
SOT_FULL_TO_REDUCED(position), SOT_FULL_TO_REDUCED(torque),
SOT_FULL_TO_REDUCED(torqueLimit),
desiredPositionSOUT(
SOT_MEMBER_SIGNAL_4(GripperControl::computeDesiredPosition,
positionSIN, dynamicgraph::Vector, positionDesSIN,
dynamicgraph::Vector, torqueSIN,
dynamicgraph::Vector, torqueLimitSIN,
dynamicgraph::Vector),
"GripperControl(" + name + ")::output(vector)::reference") {
sotDEBUGIN(5);
positionSIN.plug(&positionReduceSOUT);
torqueSIN.plug(&torqueReduceSOUT);
torqueLimitSIN.plug(&torqueLimitReduceSOUT);
signalRegistration(
positionSIN << positionDesSIN << torqueSIN << torqueLimitSIN
<< selectionSIN << desiredPositionSOUT << positionFullSizeSIN
<< torqueFullSizeSIN << torqueLimitFullSizeSIN);
sotDEBUGOUT(5);
initCommands();
}
GripperControlPlugin::~GripperControlPlugin(void) {}
std::string GripperControlPlugin::getDocString() const {
std::string docstring = "Control of gripper.";
return docstring;
}
/* --- SIGNALS -------------------------------------------------------------- */
/* --- SIGNALS -------------------------------------------------------------- */
/* --- SIGNALS -------------------------------------------------------------- */
void GripperControl::computeIncrement(
const dynamicgraph::Vector &torques,
const dynamicgraph::Vector &torqueLimits,
const dynamicgraph::Vector ¤tNormVel) {
const dynamicgraph::Vector::Index SIZE = currentNormVel.size();
// initialize factor, if needed.
if (factor.size() != SIZE) {
factor.resize(SIZE);
factor.fill(1.);
}
// Torque not provided?
if (torques.size() == 0) {
dgRTLOG() << "torque is not provided " << std::endl;
return;
}
for (int i = 0; i < SIZE; ++i) {
// apply a reduction factor if the torque limits are exceeded
// and the velocity goes in the same way
if ((torques(i) > torqueLimits(i)) && (currentNormVel(i) > 0)) {
factor(i) *= offset;
} else if ((torques(i) < -torqueLimits(i)) && (currentNormVel(i) < 0)) {
factor(i) *= offset;
}
// otherwise, release smoothly the reduction if possible/needed
else {
factor(i) /= offset;
}
// ensure factor is in )0,1(
factor(i) = std::min(1., std::max(factor(i), 0.));
}
}
dynamicgraph::Vector &
GripperControl::computeDesiredPosition(const dynamicgraph::Vector ¤tPos,
const dynamicgraph::Vector &desiredPos,
const dynamicgraph::Vector &torques,
const dynamicgraph::Vector &torqueLimits,
dynamicgraph::Vector &referencePos) {
const dynamicgraph::Vector::Index SIZE = currentPos.size();
// if( (SIZE==torques.size()) )
// { /* ERROR ... */ }
// compute the desired velocity
dynamicgraph::Vector velocity = (desiredPos - currentPos) * (1. / DT);
computeIncrement(torques, torqueLimits, velocity);
sotDEBUG(25) << " velocity " << velocity << std::endl;
sotDEBUG(25) << " factor " << factor << std::endl;
// multiply the velocity elmt per elmt
dynamicgraph::Vector weightedVel(SIZE);
weightedVel = velocity * factor;
sotDEBUG(25) << " weightedVel " << weightedVel << std::endl;
// integrate the desired velocity
referencePos.resize(SIZE);
referencePos = currentPos + weightedVel * DT;
return referencePos;
}
dynamicgraph::Vector &
GripperControl::selector(const dynamicgraph::Vector &fullsize,
const Flags &selec, dynamicgraph::Vector &desPos) {
int size = 0;
for (int i = 0; i < fullsize.size(); ++i) {
if (selec(i))
size++;
}
int curs = 0;
desPos.resize(size);
for (int i = 0; i < fullsize.size(); ++i) {
if (selec(i))
desPos(curs++) = fullsize(i);
}
return desPos;
}
/* --- COMMANDLINE ---------------------------------------------------------- */
/* --- COMMANDLINE ---------------------------------------------------------- */
/* --- COMMANDLINE ---------------------------------------------------------- */
void GripperControlPlugin::initCommands() {
namespace dc = ::dynamicgraph::command;
addCommand("offset",
dc::makeCommandVoid1(*this, &GripperControlPlugin::setOffset,
"set the offset (should be in )0, 1( )."));
}
void GripperControlPlugin::setOffset(const double &value) {
if ((value > 0) && (value < 1))
offset = value;
else
throw std::invalid_argument("The offset should be in )0, 1(.");
}
| 35.840206 | 80 | 0.543506 | Rascof |
ef96a27368bdf6cc5d46d48282657c043274d62c | 3,432 | cpp | C++ | Data Struct Programming/Experiment 2/CarParking/main.cpp | xianfei/SSE18_Homework | 7ef4ccbbaf012224ceb190bf31593a2732a44405 | [
"WTFPL"
] | 62 | 2019-11-07T01:46:55.000Z | 2022-03-28T02:27:02.000Z | Data Struct Programming/Experiment 2/CarParking/main.cpp | WongBa/SSE18_Homework | 7ef4ccbbaf012224ceb190bf31593a2732a44405 | [
"WTFPL"
] | null | null | null | Data Struct Programming/Experiment 2/CarParking/main.cpp | WongBa/SSE18_Homework | 7ef4ccbbaf012224ceb190bf31593a2732a44405 | [
"WTFPL"
] | 9 | 2020-06-17T11:39:48.000Z | 2022-02-09T07:06:27.000Z | #include <iostream>
#include <stdexcept>
template <class T>
struct Stack{
const int DEFAULT_SIZE=10;
T* array=(T*)malloc(DEFAULT_SIZE*sizeof(T));
int size=0;
int capacity=DEFAULT_SIZE;
T getTop(){
if(size==0)throw std::out_of_range("stack is empty");
return array[size-1];
}
void push(const T &num){
if(size>=capacity-1){
array=(T*)realloc(array,2*capacity*sizeof(T));
if(!array)throw std::overflow_error("stack overflow");
capacity*=2;
}
array[size++]=num;
}
T pop(){
if(size==0)throw std::out_of_range("stack is empty");
return array[--size];
}
bool isEmpty(){ return size==0;}
};
template <class T>
struct LkQueue{
struct Node{
Node *next= nullptr;
T data;
};
Node* rear= nullptr;
Node* front= nullptr;
void enqueue(const T& data){
Node* newNode = new Node;
if(rear== nullptr){
newNode->data=data;
rear=front=newNode;
return;
}
newNode->data=data;
rear->next=newNode;
rear=newNode;
}
T dequeue(){
Node* willDequeue = front;
if(willDequeue== nullptr)throw std::out_of_range("queue is empty");
front = front->next;
T willReturn=willDequeue->data;
delete(willDequeue);
return willReturn;
}
};
struct Car{
int id,time;
Car(int id, int time) : id(id), time(time) {}
Car() = default;
};
struct Parking{
Stack<Car> parkingLot;
Stack<Car> temp;
LkQueue<Car> road;
int n=2,roadN=0,moneyPerTime=0;
Parking(int n_,int moneyPerTime_):n(n_),moneyPerTime(moneyPerTime_){}
bool operate(const char *str){
char opt;
int id_,time_;
sscanf(str,"('%c',%d,%d)",&opt,&id_,&time_);
switch (opt){
case 'A':
if(parkingLot.size<2){ // in stack
parkingLot.push(Car(id_,time_));
printf("Parking at parking lot at position %d.\n",parkingLot.size);
return true;
}else{ // in queue
road.enqueue(Car(id_,time_));
roadN++;
printf("Parking at road side at position %d.\n",roadN);
return true;
}
case 'D':
while(!parkingLot.isEmpty()){
Car tempCar=parkingLot.pop();
if(tempCar.id!=id_){
temp.push(tempCar);
}else{
printf("Leaving time:%d,need pay %d.\n",time_-tempCar.time,(time_-tempCar.time)*moneyPerTime);
}
}
while(!temp.isEmpty())parkingLot.push(temp.pop());
while(parkingLot.size<2&&road.front!= nullptr){
Car tempCar=road.dequeue();
// 在马路边上停着不计费 所以更改时间为入栈时间
tempCar.time=time_;
parkingLot.push(tempCar);
roadN--;
}
return true;
case 'E':
puts("Program exit.");
return false;
}
}
};
int main() {
Parking p(2,5); // 第一个2为停车场的大小 第二个5为单位时间的费用
char str[20]={0};
do{
scanf("%s",str);
}while(p.operate(str)); //operate 函数的返回值为是否应该继续循环,bool类型
return 0;
} | 29.084746 | 118 | 0.499709 | xianfei |
aab393d2a0cd27bda04c2653a88688c3872b8608 | 8,461 | cpp | C++ | src/jet/volume_particle_emitter3.cpp | Whitemane/fluid-engine-dev | 93c3e942182cd73d54b74b7c2a283854e79911be | [
"MIT"
] | 1 | 2018-04-16T13:09:03.000Z | 2018-04-16T13:09:03.000Z | src/jet/volume_particle_emitter3.cpp | Whitemane/fluid-engine-dev | 93c3e942182cd73d54b74b7c2a283854e79911be | [
"MIT"
] | null | null | null | src/jet/volume_particle_emitter3.cpp | Whitemane/fluid-engine-dev | 93c3e942182cd73d54b74b7c2a283854e79911be | [
"MIT"
] | null | null | null | // Copyright (c) 2018 Doyub Kim
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include <pch.h>
#include <jet/bcc_lattice_point_generator.h>
#include <jet/point_hash_grid_searcher3.h>
#include <jet/samplers.h>
#include <jet/surface_to_implicit3.h>
#include <jet/volume_particle_emitter3.h>
using namespace jet;
static const size_t kDefaultHashGridResolution = 64;
VolumeParticleEmitter3::VolumeParticleEmitter3(
const ImplicitSurface3Ptr& implicitSurface,
const BoundingBox3D& bounds,
double spacing,
const Vector3D& initialVel,
size_t maxNumberOfParticles,
double jitter,
bool isOneShot,
bool allowOverlapping,
uint32_t seed) :
_rng(seed),
_implicitSurface(implicitSurface),
_bounds(bounds),
_spacing(spacing),
_initialVel(initialVel),
_maxNumberOfParticles(maxNumberOfParticles),
_jitter(jitter),
_isOneShot(isOneShot),
_allowOverlapping(allowOverlapping) {
_pointsGen = std::make_shared<BccLatticePointGenerator>();
}
void VolumeParticleEmitter3::onUpdate(
double currentTimeInSeconds,
double timeIntervalInSeconds) {
UNUSED_VARIABLE(currentTimeInSeconds);
UNUSED_VARIABLE(timeIntervalInSeconds);
auto particles = target();
if (particles == nullptr) {
return;
}
if (_numberOfEmittedParticles > 0 && _isOneShot) {
return;
}
Array1<Vector3D> newPositions;
Array1<Vector3D> newVelocities;
emit(particles, &newPositions, &newVelocities);
particles->addParticles(newPositions, newVelocities);
}
void VolumeParticleEmitter3::emit(
const ParticleSystemData3Ptr& particles,
Array1<Vector3D>* newPositions,
Array1<Vector3D>* newVelocities) {
// Reserving more space for jittering
const double j = jitter();
const double maxJitterDist = 0.5 * j * _spacing;
if (_allowOverlapping || _isOneShot) {
_pointsGen->forEachPoint(
_bounds,
_spacing,
[&] (const Vector3D& point) {
Vector3D randomDir = uniformSampleSphere(
random(),
random());
Vector3D offset = maxJitterDist * randomDir;
Vector3D candidate = point + offset;
if (_implicitSurface->signedDistance(candidate) <= 0.0) {
// printf("%f/%f - %f, %f, %f\n", _implicitSurface->signedDistance(candidate), _spacing, candidate.x, candidate.y, candidate.z);
if (_numberOfEmittedParticles < _maxNumberOfParticles) {
newPositions->append(candidate);
++_numberOfEmittedParticles;
} else {
return false;
}
}
return true;
});
} else {
// Use serial hash grid searcher for continuous update.
PointHashGridSearcher3 neighborSearcher(
Size3(
kDefaultHashGridResolution,
kDefaultHashGridResolution,
kDefaultHashGridResolution),
2.0 * _spacing);
if (!_allowOverlapping) {
neighborSearcher.build(particles->positions());
}
_pointsGen->forEachPoint(
_bounds,
_spacing,
[&] (const Vector3D& point) {
Vector3D randomDir = uniformSampleSphere(
random(),
random());
Vector3D offset = maxJitterDist * randomDir;
Vector3D candidate = point + offset;
if (_implicitSurface->signedDistance(candidate) <= 0.0 &&
(!_allowOverlapping &&
!neighborSearcher.hasNearbyPoint(candidate, _spacing))) {
if (_numberOfEmittedParticles < _maxNumberOfParticles) {
newPositions->append(candidate);
neighborSearcher.add(candidate);
++_numberOfEmittedParticles;
} else {
return false;
}
}
return true;
});
}
newVelocities->resize(newPositions->size());
newVelocities->set(_initialVel);
}
void VolumeParticleEmitter3::setPointGenerator(
const PointGenerator3Ptr& newPointsGen) {
_pointsGen = newPointsGen;
}
double VolumeParticleEmitter3::jitter() const {
return _jitter;
}
void VolumeParticleEmitter3::setJitter(double newJitter) {
_jitter = clamp(newJitter, 0.0, 1.0);
}
bool VolumeParticleEmitter3::isOneShot() const {
return _isOneShot;
}
void VolumeParticleEmitter3::setIsOneShot(bool newValue) {
_isOneShot = newValue;
}
bool VolumeParticleEmitter3::allowOverlapping() const {
return _allowOverlapping;
}
void VolumeParticleEmitter3::setAllowOverlapping(bool newValue) {
_allowOverlapping = newValue;
}
size_t VolumeParticleEmitter3::maxNumberOfParticles() const {
return _maxNumberOfParticles;
}
void VolumeParticleEmitter3::setMaxNumberOfParticles(
size_t newMaxNumberOfParticles) {
_maxNumberOfParticles = newMaxNumberOfParticles;
}
double VolumeParticleEmitter3::spacing() const {
return _spacing;
}
void VolumeParticleEmitter3::setSpacing(double newSpacing) {
_spacing = newSpacing;
}
Vector3D VolumeParticleEmitter3::initialVelocity() const {
return _initialVel;
}
void VolumeParticleEmitter3::setInitialVelocity(const Vector3D& newInitialVel) {
_initialVel = newInitialVel;
}
double VolumeParticleEmitter3::random() {
std::uniform_real_distribution<> d(0.0, 1.0);
return d(_rng);
}
VolumeParticleEmitter3::Builder VolumeParticleEmitter3::builder() {
return Builder();
}
VolumeParticleEmitter3::Builder&
VolumeParticleEmitter3::Builder::withImplicitSurface(
const ImplicitSurface3Ptr& implicitSurface) {
_implicitSurface = implicitSurface;
if (!_isBoundSet) {
_bounds = _implicitSurface->boundingBox();
}
return *this;
}
VolumeParticleEmitter3::Builder&
VolumeParticleEmitter3::Builder::withSurface(
const Surface3Ptr& surface) {
_implicitSurface = std::make_shared<SurfaceToImplicit3>(surface);
if (!_isBoundSet) {
_bounds = surface->boundingBox();
}
return *this;
}
VolumeParticleEmitter3::Builder&
VolumeParticleEmitter3::Builder::withMaxRegion(const BoundingBox3D& bounds) {
_bounds = bounds;
_isBoundSet = true;
return *this;
}
VolumeParticleEmitter3::Builder&
VolumeParticleEmitter3::Builder::withSpacing(double spacing) {
_spacing = spacing;
return *this;
}
VolumeParticleEmitter3::Builder&
VolumeParticleEmitter3::Builder::withInitialVelocity(
const Vector3D& initialVel) {
_initialVel = initialVel;
return *this;
}
VolumeParticleEmitter3::Builder&
VolumeParticleEmitter3::Builder::withMaxNumberOfParticles(
size_t maxNumberOfParticles) {
_maxNumberOfParticles = maxNumberOfParticles;
return *this;
}
VolumeParticleEmitter3::Builder&
VolumeParticleEmitter3::Builder::withJitter(double jitter) {
_jitter = jitter;
return *this;
}
VolumeParticleEmitter3::Builder&
VolumeParticleEmitter3::Builder::withIsOneShot(bool isOneShot) {
_isOneShot = isOneShot;
return *this;
}
VolumeParticleEmitter3::Builder&
VolumeParticleEmitter3::Builder::withAllowOverlapping(bool allowOverlapping) {
_allowOverlapping = allowOverlapping;
return *this;
}
VolumeParticleEmitter3::Builder&
VolumeParticleEmitter3::Builder::withRandomSeed(uint32_t seed) {
_seed = seed;
return *this;
}
VolumeParticleEmitter3 VolumeParticleEmitter3::Builder::build() const {
return VolumeParticleEmitter3(
_implicitSurface,
_bounds,
_spacing,
_initialVel,
_maxNumberOfParticles,
_jitter,
_isOneShot,
_allowOverlapping,
_seed);
}
VolumeParticleEmitter3Ptr VolumeParticleEmitter3::Builder::makeShared() const {
return std::shared_ptr<VolumeParticleEmitter3>(
new VolumeParticleEmitter3(
_implicitSurface,
_bounds,
_spacing,
_initialVel,
_maxNumberOfParticles,
_jitter,
_isOneShot,
_allowOverlapping),
[] (VolumeParticleEmitter3* obj) {
delete obj;
});
}
| 28.392617 | 147 | 0.663279 | Whitemane |
aab3d8b8a09a2743d0de5116ee225498ed961872 | 2,822 | cpp | C++ | Packer/RepetitionFinder.cpp | BartoszMilewski/CodeCoop | 7d29f53ccf65b0d29ea7d6781a74507b52c08d0d | [
"MIT"
] | 67 | 2018-03-02T10:50:02.000Z | 2022-03-23T18:20:29.000Z | Packer/RepetitionFinder.cpp | BartoszMilewski/CodeCoop | 7d29f53ccf65b0d29ea7d6781a74507b52c08d0d | [
"MIT"
] | null | null | null | Packer/RepetitionFinder.cpp | BartoszMilewski/CodeCoop | 7d29f53ccf65b0d29ea7d6781a74507b52c08d0d | [
"MIT"
] | 9 | 2018-03-01T16:38:28.000Z | 2021-03-02T16:17:09.000Z | //-------------------------------------
// (c) Reliable Software 1999-2003
// ------------------------------------
#include "precompiled.h"
#include "RepetitionFinder.h"
#include "Repetitions.h"
#include "ForgetfulHashTable.h"
#include "Statistics.h"
#include "Bucketizer.h"
#include <Ex/WinEx.h>
RepetitionFinder::RepetitionFinder (char const * buf,
File::Size size,
Repetitions & repetitions,
ForgetfulHashTable & hashtable)
: _buf (buf),
_size (size.Low ()),
_scanEnd (size.Low () - MinRepetitionLength - 1),
_repetitions (repetitions),
_hashtable (hashtable),
_current (0)
{
if (size.IsLarge ())
throw Win::Exception ("File size exceeds 4GB", 0, 0);
if (_size <= MinRepetitionLength)
_scanEnd = _size - 1;
}
void RepetitionFinder::Find (Statistics & stats)
{
while (_current < _scanEnd)
{
if (FoundRepetition ())
{
_repetitions.Add (_curRepetition);
stats.RecordRepetition (_curRepetition.GetLen (), _curRepetition.GetBackwardDist ());
_current += _curRepetition.GetLen ();
}
else
{
stats.RecordLiteral (_buf [_current++]);
}
}
while (_current < _size)
{
stats.RecordLiteral (_buf [_current++]);
}
}
bool RepetitionFinder::FoundRepetition ()
{
_curRepetition.SetTarget (_current);
_curRepetition.SetLen (MinRepetitionLength - 1);
ForgetfulHashTable::PositionListIter iter = _hashtable.Save (Hash (), _current);
// Go over all found so far repetitions and check if they match the current byte sequence
for ( ; !iter.AtEnd () && _curRepetition.GetLen () < 10; iter.Advance ())
{
unsigned int repStart = iter.GetPosition ();
Assert (_current > repStart);
unsigned int backwardDist = _current - repStart;
if (backwardDist > RepDistBucketizer::GetMaxRepetitionDistance ())
{
// Repetition is too far away from the current position in the buffer.
// Remove repetitions that are too far away from the hash table.
iter.ShortenList ();
break;
}
// Close enough -- check if long enough
if (_buf [_current + _curRepetition.GetLen ()] == _buf [repStart + _curRepetition.GetLen ()])
{
unsigned int thisRepLen = 0;
for ( ; thisRepLen < RepLenBucketizer::GetMaxRepetitionLength (); ++thisRepLen)
{
if ((_current + thisRepLen == _scanEnd) ||
(_buf [repStart + thisRepLen] != _buf [_current + thisRepLen]))
{
break;
}
}
if (thisRepLen > _curRepetition.GetLen ())
{
_curRepetition.SetLen (thisRepLen);
_curRepetition.SetFrom (repStart);
}
}
}
// We have found repetition if it is long enough and at economical
// distance for repetitions of lenght greater then 3
return _curRepetition.GetLen () >= MinRepetitionLength &&
(_curRepetition.GetLen () > 3 || _curRepetition.GetBackwardDist () < EconomicalDistanceFor3ByteRepetitionLength);
}
| 30.021277 | 118 | 0.668675 | BartoszMilewski |
aab3fb72d062e9215459ab412efd3751d795aac5 | 5,466 | cpp | C++ | editor/audio/Player.cpp | minhvien5059/congnghe_Vietnam | 06d6efce856ba369db340a2d834e003fe5a99fa0 | [
"BSD-3-Clause"
] | 40 | 2015-09-03T05:50:42.000Z | 2022-02-25T10:00:01.000Z | editor/audio/Player.cpp | minhvien5059/congnghe_Vietnam | 06d6efce856ba369db340a2d834e003fe5a99fa0 | [
"BSD-3-Clause"
] | 1 | 2017-10-24T14:30:13.000Z | 2017-11-07T02:14:10.000Z | editor/audio/Player.cpp | minhvien5059/congnghe_Vietnam | 06d6efce856ba369db340a2d834e003fe5a99fa0 | [
"BSD-3-Clause"
] | 7 | 2017-03-13T07:08:19.000Z | 2021-06-01T01:06:05.000Z | /* Player.cpp from QTau http://github.com/qtau-devgroup/editor by digited, BSD license */
#include "audio/Player.h"
#include "audio/Source.h"
#include "audio/Mixer.h"
#include "Utils.h"
#include <QAudioOutput>
#include <QThread>
#include <QTimer>
#include <QDebug>
#include <QApplication>
qtmmPlayer::qtmmPlayer() :
audioOutput(nullptr), mixer(nullptr), stopTimer(nullptr), volume(50)
{
vsLog::d("QtMultimedia :: supported output devices and codecs:");
QList<QAudioDeviceInfo> advs = QAudioDeviceInfo::availableDevices(QAudio::AudioOutput);
foreach (QAudioDeviceInfo i, advs)
vsLog::d(QString("%1 %2").arg(i.deviceName()).arg(i.supportedCodecs().join(' ')));
open(QIODevice::ReadOnly);
}
qtmmPlayer::~qtmmPlayer()
{
close();
delete stopTimer;
delete audioOutput;
delete mixer;
}
qint64 qtmmPlayer::size() const
{
return mixer->bytesAvailable();
}
void qtmmPlayer::threadedInit()
{
stopTimer = new QTimer();
stopTimer->setSingleShot(true);
connect(stopTimer, &QTimer::timeout, this, &qtmmPlayer::stop);
mixer = new qtauSoundMixer();
connect(mixer, &qtauSoundMixer::effectEnded, this, &qtmmPlayer::onEffectEnded);
connect(mixer, &qtauSoundMixer::trackEnded, this, &qtmmPlayer::onTrackEnded);
connect(mixer, &qtauSoundMixer::allEffectsEnded, this, &qtmmPlayer::onAllEffectsEnded);
connect(mixer, &qtauSoundMixer::allTracksEnded, this, &qtmmPlayer::onAllTracksEnded);
QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
QAudioFormat fmt = mixer->getAudioFormat();
if (info.isFormatSupported(fmt))
{
QAudioDeviceInfo di(QAudioDeviceInfo::defaultOutputDevice());
audioOutput = new QAudioOutput(di, fmt, this);
audioOutput->setVolume((qreal)volume / 100.f);
connect(audioOutput, SIGNAL(stateChanged(QAudio::State)), SLOT(onQtmmStateChanged(QAudio::State)));;
connect(audioOutput, SIGNAL(notify()), SLOT(onTick()));
}
else vsLog::e("Default audio format not supported by QtMultimedia backend, cannot play audio.");
}
void qtmmPlayer::addEffect(qtauAudioSource *e, bool replace, bool smoothly, bool copy)
{
qtauAudioSource *added = e;
if (copy)
added = new qtauAudioSource(e->data(), e->getAudioFormat());
effects.append(added);
mixer->addEffect(added, replace, smoothly);
}
void qtmmPlayer::addTrack (qtauAudioSource *t, bool replace, bool smoothly, bool copy)
{
qtauAudioSource *added = t;
if (copy)
added = new qtauAudioSource(t->data(), t->getAudioFormat());
tracks.append(added);
mixer->addTrack(added, replace, smoothly);
}
qint64 qtmmPlayer::readData(char *data, qint64 maxlen)
{
qint64 result = mixer->read(data, maxlen);
if (result < maxlen)
{
if (result == 0)
stopTimer->start(500);
memset(data + result, 0, maxlen - result); // silence
result = maxlen; // else it'll complain on "buffer underflow"... and will keep asking for more
}
return result;
}
void qtmmPlayer::play()
{
stopTimer->stop();
if (audioOutput->state() == QAudio::SuspendedState)
audioOutput->resume();
else
if (audioOutput->state() != QAudio::ActiveState)
{
audioOutput->reset();
audioOutput->start(this);
}
}
void qtmmPlayer::pause()
{
stopTimer->stop();
audioOutput->suspend();
}
void qtmmPlayer::stop()
{
stopTimer->stop();
audioOutput->stop();
if (!mixer->atEnd())
mixer->clear();
}
void qtmmPlayer::setVolume(int level)
{
level = qMax(qMin(level, 100), 0);
volume = level;
if (audioOutput)
audioOutput->setVolume((qreal)level / 100.f);
}
void qtmmPlayer::onEffectEnded(qtauAudioSource* e)
{
int ind = effects.indexOf(e);
if (ind != -1)
{
delete e;
effects.removeAt(ind);
}
}
void qtmmPlayer::onTrackEnded(qtauAudioSource* t)
{
int ind = tracks.indexOf(t);
if (ind != -1)
{
delete t;
tracks.removeAt(ind);
}
}
void qtmmPlayer::onAllEffectsEnded()
{
if (!effects.isEmpty())
{
for (auto &e: effects)
delete e;
effects.clear();
}
}
void qtmmPlayer::onAllTracksEnded()
{
if (!tracks.isEmpty())
{
for (auto &t: tracks)
delete t;
tracks.clear();
}
emit playbackEnded();
}
inline QString audioStatusToString(QAudio::State st)
{
QString result = QStringLiteral("unknown");
switch (st)
{
case QAudio::ActiveState: result = QStringLiteral("active"); break;
case QAudio::IdleState: result = QStringLiteral("idle"); break;
case QAudio::StoppedState: result = QStringLiteral("stopped"); break;
case QAudio::SuspendedState: result = QStringLiteral("suspended"); break;
default:
break;
}
return result;
}
void qtmmPlayer::onQtmmStateChanged(QAudio::State /*st*/)
{
// qDebug() << "audio status:" << audioStatusToString(st);
// switch (st) // doesn't really matter now
// {
// case QAudio::ActiveState:
// case QAudio::SuspendedState:
// break;
// case QAudio::StoppedState:
// case QAudio::IdleState:
// mixer->clear();
// break;
// default:
// vsLog::e(QString("Unknown Qtmm Audio state: %1").arg(st));
// break;
// }
}
void qtmmPlayer::onTick() { emit tick(audioOutput->processedUSecs()); }
| 23.973684 | 108 | 0.637029 | minhvien5059 |
aab56c1cca596c00a4365ee563d586d8b22f860e | 6,262 | hpp | C++ | tools/seec-view/ExplanationViewer.hpp | seec-team/seec | 4b92456011e86b70f9d88833a95c1f655a21cf1a | [
"MIT"
] | 7 | 2018-06-25T12:06:13.000Z | 2022-01-18T09:20:13.000Z | tools/seec-view/ExplanationViewer.hpp | seec-team/seec | 4b92456011e86b70f9d88833a95c1f655a21cf1a | [
"MIT"
] | 20 | 2016-12-01T23:46:12.000Z | 2019-08-11T02:41:04.000Z | tools/seec-view/ExplanationViewer.hpp | seec-team/seec | 4b92456011e86b70f9d88833a95c1f655a21cf1a | [
"MIT"
] | 1 | 2020-10-19T03:20:05.000Z | 2020-10-19T03:20:05.000Z | //===- tools/seec-trace-view/ExplanationViewer.hpp ------------------------===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#ifndef SEEC_TRACE_VIEW_EXPLANATIONVIEWER_HPP
#define SEEC_TRACE_VIEW_EXPLANATIONVIEWER_HPP
#include "seec/Clang/MappedValue.hpp"
#include "seec/ClangEPV/ClangEPV.hpp"
#include "seec/Util/Observer.hpp"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Path.h"
#include <wx/wx.h>
#include <wx/panel.h>
#include <wx/stc/stc.h>
#include <memory>
#include <string>
// Forward declarations.
namespace clang {
class Decl;
class Stmt;
} // namespace clang
namespace seec {
namespace cm {
class FunctionState;
class ProcessState;
}
}
class ActionRecord;
class ActionReplayFrame;
class ColourScheme;
class ContextNotifier;
class IndexedAnnotationText;
class OpenTrace;
class StateAccessToken;
/// \brief ExplanationViewer.
///
class ExplanationViewer final : public wxStyledTextCtrl
{
/// The trace that this viewer will display states from.
OpenTrace *Trace;
/// The central handler for context notifications.
ContextNotifier *Notifier;
/// Registration to ColourSchemeSettings changes.
seec::observer::registration m_ColourSchemeSettingsRegistration;
/// Used to record user interactions.
ActionRecord *Recording;
/// Holds the current annotation text.
std::unique_ptr<IndexedAnnotationText> Annotation;
/// Holds the byte length of displayed annotation text.
long AnnotationLength;
/// Hold current explanatory material.
std::unique_ptr<seec::clang_epv::Explanation> Explanation;
/// Caches the current mouse position.
int CurrentMousePosition;
/// Currently highlighted Decl.
::clang::Decl const *HighlightedDecl;
/// Currently highlighted Stmt.
::clang::Stmt const *HighlightedStmt;
/// Is the mouse currently hovering on a URL?
bool URLHover;
/// The URL that the mouse is hovering over.
std::string URLHovered;
/// Is the mouse on the same URL as when the left button was clicked?
bool URLClick;
/// \brief Get byte offset range from "whole character" range.
///
std::pair<int, int> getAnnotationByteOffsetRange(int32_t Start, int32_t End);
/// \brief Get byte offset range from "whole character" range.
///
std::pair<int, int> getExplanationByteOffsetRange(int32_t Start, int32_t End);
/// \brief Set the annotation text.
///
void setAnnotationText(wxString const &Value);
/// \brief Set the explanation text.
///
void setExplanationText(wxString const &Value);
/// \brief Set indicators for the interactive text areas in the current
/// \c Explanation.
///
void setExplanationIndicators();
/// \brief Handle mouse moving over a link to a \c clang::Decl.
///
void mouseOverDecl(clang::Decl const *);
/// \brief Handle mouse moving over a link to a \c clang::Stmt.
///
void mouseOverStmt(clang::Stmt const *);
/// \brief Handle mouse moving over a hyperlink.
///
void mouseOverHyperlink(UnicodeString const &);
/// \brief Clear the current information.
///
void clearCurrent();
/// \brief Update this viewer to the given \c ColourScheme.
///
void updateColourScheme(ColourScheme const &Scheme);
public:
/// \brief Construct without creating.
///
ExplanationViewer()
: wxStyledTextCtrl(),
Trace(nullptr),
Notifier(nullptr),
m_ColourSchemeSettingsRegistration(),
Recording(nullptr),
Annotation(nullptr),
AnnotationLength(0),
Explanation(),
CurrentMousePosition(wxSTC_INVALID_POSITION),
HighlightedDecl(nullptr),
HighlightedStmt(nullptr),
URLHover(false),
URLHovered(),
URLClick(false)
{}
/// \brief Construct and create.
///
ExplanationViewer(wxWindow *Parent,
OpenTrace &WithTrace,
ContextNotifier &WithNotifier,
ActionRecord &WithRecording,
ActionReplayFrame &WithReplay,
wxWindowID ID = wxID_ANY,
wxPoint const &Position = wxDefaultPosition,
wxSize const &Size = wxDefaultSize)
: ExplanationViewer()
{
Create(Parent, WithTrace, WithNotifier, WithRecording, WithReplay, ID,
Position, Size);
}
/// \brief Destructor.
///
virtual ~ExplanationViewer();
/// \brief Create the viewer.
///
bool Create(wxWindow *Parent,
OpenTrace &WithTrace,
ContextNotifier &WithNotifier,
ActionRecord &WithRecording,
ActionReplayFrame &WithReplay,
wxWindowID ID = wxID_ANY,
wxPoint const &Position = wxDefaultPosition,
wxSize const &Size = wxDefaultSize);
/// \name Mouse events.
/// @{
void OnMotion(wxMouseEvent &Event);
void OnEnterWindow(wxMouseEvent &Event);
void OnLeaveWindow(wxMouseEvent &Event);
void OnLeftDown(wxMouseEvent &Event);
void OnLeftUp(wxMouseEvent &Event);
/// @} (Mouse events)
/// \name Mutators.
/// @{
private:
/// \brief Show annotations for this state.
/// \return true iff ClangEPV explanation should be suppressed.
///
bool showAnnotations(seec::cm::ProcessState const &Process,
seec::cm::ThreadState const &Thread);
public:
void show(std::shared_ptr<StateAccessToken> Access,
seec::cm::ProcessState const &Process,
seec::cm::ThreadState const &Thread);
/// \brief Attempt to show an explanation for the given Decl.
///
void showExplanation(::clang::Decl const *Decl);
/// \brief Attempt to show an explanation for the given Stmt.
///
/// pre: Caller must have locked access to the state containing InFunction.
///
void showExplanation(::clang::Stmt const *Statement,
::seec::cm::FunctionState const &InFunction);
/// \brief Clear the display.
///
void clearExplanation();
/// @} (Mutators)
};
#endif // SEEC_TRACE_VIEW_EXPLANATIONVIEWER_HPP
| 26.091667 | 80 | 0.648195 | seec-team |
aab69f4adc8f9f080ac7d2c22e5750e4b92a7393 | 10,793 | cpp | C++ | deform_control/external_libs/OpenSceneGraph-2.8.5/examples/osgshaderterrain/osgshaderterrain.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 3 | 2018-08-20T12:12:43.000Z | 2021-06-06T09:43:27.000Z | deform_control/external_libs/OpenSceneGraph-2.8.5/examples/osgshaderterrain/osgshaderterrain.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | null | null | null | deform_control/external_libs/OpenSceneGraph-2.8.5/examples/osgshaderterrain/osgshaderterrain.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 1 | 2022-03-31T03:12:23.000Z | 2022-03-31T03:12:23.000Z | /* OpenSceneGraph example, osgshaderterrain.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <osg/AlphaFunc>
#include <osg/Billboard>
#include <osg/BlendFunc>
#include <osg/Depth>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/GL2Extensions>
#include <osg/Material>
#include <osg/Math>
#include <osg/MatrixTransform>
#include <osg/PolygonOffset>
#include <osg/Program>
#include <osg/Projection>
#include <osg/Shader>
#include <osg/ShapeDrawable>
#include <osg/StateSet>
#include <osg/Switch>
#include <osg/Texture2D>
#include <osg/Uniform>
#include <osgDB/ReadFile>
#include <osgDB/FileUtils>
#include <osgUtil/SmoothingVisitor>
#include <osgText/Text>
#include <osgViewer/Viewer>
#include <iostream>
// for the grid data..
#include "../osghangglide/terrain_coords.h"
osg::Node* createScene()
{
osg::Group* scene = new osg::Group;
unsigned int numColumns = 38;
unsigned int numRows = 39;
unsigned int r;
unsigned int c;
osg::Vec3 origin(0.0f,0.0f,0.0f);
osg::Vec3 size(1000.0f,1000.0f,250.0f);
osg::Vec3 scaleDown(1.0f/size.x(),1.0f/size.y(),1.0f/size.z());
// ---------------------------------------
// Set up a StateSet to texture the objects
// ---------------------------------------
osg::StateSet* stateset = new osg::StateSet();
osg::Uniform* originUniform = new osg::Uniform("terrainOrigin",origin);
stateset->addUniform(originUniform);
osg::Uniform* sizeUniform = new osg::Uniform("terrainSize",size);
stateset->addUniform(sizeUniform);
osg::Uniform* scaleDownUniform = new osg::Uniform("terrainScaleDown",scaleDown);
stateset->addUniform(scaleDownUniform);
osg::Uniform* terrainTextureSampler = new osg::Uniform("terrainTexture",0);
stateset->addUniform(terrainTextureSampler);
osg::Uniform* baseTextureSampler = new osg::Uniform("baseTexture",1);
stateset->addUniform(baseTextureSampler);
osg::Uniform* treeTextureSampler = new osg::Uniform("treeTexture",1);
stateset->addUniform(treeTextureSampler);
// compute z range of z values of grid data so we can scale it.
float min_z = FLT_MAX;
float max_z = -FLT_MAX;
for(r=0;r<numRows;++r)
{
for(c=0;c<numColumns;++c)
{
min_z = osg::minimum(min_z,vertex[r+c*numRows][2]);
max_z = osg::maximum(max_z,vertex[r+c*numRows][2]);
}
}
float scale_z = size.z()/(max_z-min_z);
osg::Image* terrainImage = new osg::Image;
terrainImage->allocateImage(numColumns,numRows,1,GL_LUMINANCE, GL_FLOAT);
terrainImage->setInternalTextureFormat(GL_LUMINANCE_FLOAT32_ATI);
for(r=0;r<numRows;++r)
{
for(c=0;c<numColumns;++c)
{
*((float*)(terrainImage->data(c,r))) = (vertex[r+c*numRows][2]-min_z)*scale_z;
}
}
osg::Texture2D* terrainTexture = new osg::Texture2D;
terrainTexture->setImage(terrainImage);
terrainTexture->setFilter(osg::Texture2D::MIN_FILTER, osg::Texture2D::NEAREST);
terrainTexture->setFilter(osg::Texture2D::MAG_FILTER, osg::Texture2D::NEAREST);
terrainTexture->setResizeNonPowerOfTwoHint(false);
stateset->setTextureAttributeAndModes(0,terrainTexture,osg::StateAttribute::ON);
osg::Image* image = osgDB::readImageFile("Images/lz.rgb");
if (image)
{
osg::Texture2D* texture = new osg::Texture2D;
texture->setImage(image);
stateset->setTextureAttributeAndModes(1,texture,osg::StateAttribute::ON);
}
{
std::cout<<"Creating terrain...";
osg::Geode* geode = new osg::Geode();
geode->setStateSet( stateset );
{
osg::Program* program = new osg::Program;
stateset->setAttribute(program);
#if 1
// use inline shaders
///////////////////////////////////////////////////////////////////
// vertex shader using just Vec4 coefficients
char vertexShaderSource[] =
"uniform sampler2D terrainTexture;\n"
"uniform vec3 terrainOrigin;\n"
"uniform vec3 terrainScaleDown;\n"
"\n"
"varying vec2 texcoord;\n"
"\n"
"void main(void)\n"
"{\n"
" texcoord = gl_Vertex.xy - terrainOrigin.xy;\n"
" texcoord.x *= terrainScaleDown.x;\n"
" texcoord.y *= terrainScaleDown.y;\n"
"\n"
" vec4 position;\n"
" position.x = gl_Vertex.x;\n"
" position.y = gl_Vertex.y;\n"
" position.z = texture2D(terrainTexture, texcoord).r;\n"
" position.w = 1.0;\n"
" \n"
" gl_Position = gl_ModelViewProjectionMatrix * position;\n"
" gl_FrontColor = vec4(1.0,1.0,1.0,1.0);\n"
"}\n";
//////////////////////////////////////////////////////////////////
// fragment shader
//
char fragmentShaderSource[] =
"uniform sampler2D baseTexture; \n"
"varying vec2 texcoord;\n"
"\n"
"void main(void) \n"
"{\n"
" gl_FragColor = texture2D( baseTexture, texcoord); \n"
"}\n";
program->addShader(new osg::Shader(osg::Shader::VERTEX, vertexShaderSource));
program->addShader(new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource));
#else
// get shaders from source
program->addShader(osg::Shader::readShaderFile(osg::Shader::VERTEX, osgDB::findDataFile("shaders/terrain.vert")));
program->addShader(osg::Shader::readShaderFile(osg::Shader::FRAGMENT, osgDB::findDataFile("shaders/terrain.frag")));
#endif
// get shaders from source
}
{
osg::Geometry* geometry = new osg::Geometry;
osg::Vec3Array& v = *(new osg::Vec3Array(numColumns*numRows));
osg::Vec4ubArray& color = *(new osg::Vec4ubArray(1));
color[0].set(255,255,255,255);
float rowCoordDelta = size.y()/(float)(numRows-1);
float columnCoordDelta = size.x()/(float)(numColumns-1);
float rowTexDelta = 1.0f/(float)(numRows-1);
float columnTexDelta = 1.0f/(float)(numColumns-1);
osg::Vec3 pos = origin;
osg::Vec2 tex(0.0f,0.0f);
int vi=0;
for(r=0;r<numRows;++r)
{
pos.x() = origin.x();
tex.x() = 0.0f;
for(c=0;c<numColumns;++c)
{
v[vi].set(pos.x(),pos.y(),pos.z());
pos.x()+=columnCoordDelta;
tex.x()+=columnTexDelta;
++vi;
}
pos.y() += rowCoordDelta;
tex.y() += rowTexDelta;
}
geometry->setVertexArray(&v);
geometry->setColorArray(&color);
geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
for(r=0;r<numRows-1;++r)
{
osg::DrawElementsUShort& drawElements = *(new osg::DrawElementsUShort(GL_QUAD_STRIP,2*numColumns));
geometry->addPrimitiveSet(&drawElements);
int ei=0;
for(c=0;c<numColumns;++c)
{
drawElements[ei++] = (r+1)*numColumns+c;
drawElements[ei++] = (r)*numColumns+c;
}
}
geometry->setInitialBound(osg::BoundingBox(origin, origin+size));
geode->addDrawable(geometry);
scene->addChild(geode);
}
}
std::cout<<"done."<<std::endl;
return scene;
}
class TestSupportOperation: public osg::GraphicsOperation
{
public:
TestSupportOperation():
osg::GraphicsOperation("TestSupportOperation",false),
_supported(true),
_errorMessage() {}
virtual void operator () (osg::GraphicsContext* gc)
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);
unsigned int contextID = gc->getState()->getContextID();
osg::GL2Extensions* gl2ext = osg::GL2Extensions::Get(contextID,true);
if( gl2ext )
{
if( !gl2ext->isGlslSupported() )
{
_supported = false;
_errorMessage = "ERROR: GLSL not supported by OpenGL driver.";
}
GLint numVertexTexUnits = 0;
glGetIntegerv( GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &numVertexTexUnits );
if( numVertexTexUnits <= 0 )
{
_supported = false;
_errorMessage = "ERROR: vertex texturing not supported by OpenGL driver.";
}
}
else
{
_supported = false;
_errorMessage = "ERROR: GLSL not supported.";
}
}
OpenThreads::Mutex _mutex;
bool _supported;
std::string _errorMessage;
};
int main(int, char **)
{
// construct the viewer.
osgViewer::Viewer viewer;
osg::Node* node = createScene();
// add model to viewer.
viewer.setSceneData( node );
viewer.setUpViewAcrossAllScreens();
osg::ref_ptr<TestSupportOperation> testSupportOperation = new TestSupportOperation;
#if 0
// temporily commenting out as its causing the viewer to crash... no clue yet to why
viewer.setRealizeOperation(testSupportOperation.get());
#endif
// create the windows and run the threads.
viewer.realize();
if (!testSupportOperation->_supported)
{
osg::notify(osg::WARN)<<testSupportOperation->_errorMessage<<std::endl;
return 1;
}
return viewer.run();
}
| 32.509036 | 128 | 0.575095 | UM-ARM-Lab |
aab78b191f13689ed92ce23c9b2dcdcb50f90706 | 42,735 | cpp | C++ | src/genicam_device_nodelet.cpp | roboception/rc_genicam_driver_ros | 68e97903d72c5a840b93425903031d336ae97db8 | [
"BSD-3-Clause"
] | 1 | 2020-10-13T17:35:41.000Z | 2020-10-13T17:35:41.000Z | src/genicam_device_nodelet.cpp | roboception/rc_genicam_driver_ros | 68e97903d72c5a840b93425903031d336ae97db8 | [
"BSD-3-Clause"
] | null | null | null | src/genicam_device_nodelet.cpp | roboception/rc_genicam_driver_ros | 68e97903d72c5a840b93425903031d336ae97db8 | [
"BSD-3-Clause"
] | 1 | 2022-02-23T12:37:44.000Z | 2022-02-23T12:37:44.000Z | /*
* Copyright (c) 2020 Roboception GmbH
* All rights reserved
*
* Author: Heiko Hirschmueller
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "genicam_device_nodelet.h"
#include "publishers/camera_info_publisher.h"
#include "publishers/camera_param_publisher.h"
#include "publishers/image_publisher.h"
#include "publishers/disparity_publisher.h"
#include "publishers/disparity_color_publisher.h"
#include "publishers/depth_publisher.h"
#include "publishers/confidence_publisher.h"
#include "publishers/error_disparity_publisher.h"
#include "publishers/error_depth_publisher.h"
#include "publishers/points2_publisher.h"
#include <rc_genicam_api/device.h>
#include <rc_genicam_api/stream.h>
#include <rc_genicam_api/buffer.h>
#include <rc_genicam_api/config.h>
#include <rc_genicam_api/pixel_formats.h>
#include <pluginlib/class_list_macros.h>
#include <exception>
#include <sstream>
#include <stdexcept>
#include <ros/ros.h>
#include <rc_common_msgs/ReturnCodeConstants.h>
#include <rc_common_msgs/CameraParam.h>
namespace rc
{
GenICamDeviceNodelet::GenICamDeviceNodelet()
{
scomponents = 0;
scolor = 0;
running = false;
gev_packet_size = 0;
connection_loss_total = 0;
complete_buffers_total = 0;
incomplete_buffers_total = 0;
image_receive_timeouts_total = 0;
current_reconnect_trial = 0;
streaming = false;
}
GenICamDeviceNodelet::~GenICamDeviceNodelet()
{
NODELET_INFO("Shutting down");
// signal running threads and wait until they finish
running = false;
if (grab_thread.joinable())
{
grab_thread.join();
}
rcg::System::clearSystems();
}
void GenICamDeviceNodelet::onInit()
{
NODELET_INFO("Initialization started");
std::string ns = ros::this_node::getNamespace();
if (ns.size() > 0 && ns[0] == '/')
{
ns = ns.substr(1);
}
if (ns.size() > 0)
{
frame_id = ns + "_camera";
}
else
{
frame_id = "camera";
}
// get parameter configuration
ros::NodeHandle pnh(getPrivateNodeHandle());
ros::NodeHandle nh(getNodeHandle(), "");
std::string id = "*";
std::string access = "control";
pnh.param("device", id, id);
pnh.param("gev_access", access, access);
rcg::Device::ACCESS access_id;
if (access == "exclusive")
{
access_id = rcg::Device::EXCLUSIVE;
}
else if (access == "control")
{
access_id = rcg::Device::CONTROL;
}
else
{
NODELET_FATAL_STREAM("Access must be 'control' or 'exclusive': " << access);
return;
}
// setup services
trigger_service =
pnh.advertiseService("depth_acquisition_trigger", &GenICamDeviceNodelet::depthAcquisitionTrigger, this);
// add callbacks for diagnostics publishing
updater.add("Connection", this, &GenICamDeviceNodelet::publishConnectionDiagnostics);
updater.add("Device", this, &GenICamDeviceNodelet::publishDeviceDiagnostics);
// start grabbing thread
running = true;
grab_thread = std::thread(&GenICamDeviceNodelet::grab, this, id, access_id);
NODELET_INFO("Initialization done");
}
bool GenICamDeviceNodelet::depthAcquisitionTrigger(rc_common_msgs::Trigger::Request& req,
rc_common_msgs::Trigger::Response& res)
{
std::lock_guard<std::recursive_mutex> lock(device_mtx);
if (nodemap)
{
if (config.depth_acquisition_mode != "Continuous")
{
try
{
NODELET_DEBUG("Triggering stereo matching");
rcg::callCommand(nodemap, "DepthAcquisitionTrigger", true);
res.return_code.value = rc_common_msgs::ReturnCodeConstants::SUCCESS;
res.return_code.message = "Stereo matching was triggered.";
}
catch (const std::exception& ex)
{
res.return_code.value = rc_common_msgs::ReturnCodeConstants::INTERNAL_ERROR;
res.return_code.message = ex.what();
NODELET_ERROR_STREAM(ex.what());
}
}
else
{
res.return_code.value = rc_common_msgs::ReturnCodeConstants::NOT_APPLICABLE;
res.return_code.message = "Triggering stereo matching is only possible if acquisition_mode is set to SingleFrame "
"or SingleFrameOut1!";
NODELET_DEBUG_STREAM("" << res.return_code.message);
}
}
else
{
res.return_code.value = rc_common_msgs::ReturnCodeConstants::NOT_APPLICABLE;
res.return_code.message = "Not connected";
}
return true;
}
void GenICamDeviceNodelet::initConfiguration()
{
std::lock_guard<std::recursive_mutex> lock(device_mtx);
ros::NodeHandle pnh(getPrivateNodeHandle());
// get current camera configuration
config.camera_fps = rcg::getFloat(nodemap, "AcquisitionFrameRate", 0, 0, true);
std::string v = rcg::getEnum(nodemap, "ExposureAuto", true);
config.camera_exp_auto = (v != "Off");
if (config.camera_exp_auto)
{
if (v == "Continuous")
{
config.camera_exp_auto_mode = "Normal";
}
else
{
config.camera_exp_auto_mode = v;
}
}
config.camera_exp_max = rcg::getFloat(nodemap, "ExposureTimeAutoMax", 0, 0, true) / 1000000;
try
{
config.camera_exp_auto_average_max = rcg::getFloat(nodemap, "RcExposureAutoAverageMax", 0, 0, true);
config.camera_exp_auto_average_min = rcg::getFloat(nodemap, "RcExposureAutoAverageMin", 0, 0, true);
}
catch (const std::exception&)
{
config.camera_exp_auto_average_max = 0.75f;
config.camera_exp_auto_average_min = 0.25f;
}
config.camera_exp_width = rcg::getInteger(nodemap, "ExposureRegionWidth", 0, 0, true);
config.camera_exp_height = rcg::getInteger(nodemap, "ExposureRegionHeight", 0, 0, true);
config.camera_exp_offset_x = rcg::getInteger(nodemap, "ExposureRegionOffsetX", 0, 0, true);
config.camera_exp_offset_y = rcg::getInteger(nodemap, "ExposureRegionOffsetY", 0, 0, true);
config.camera_exp_value = rcg::getFloat(nodemap, "ExposureTime", 0, 0, true) / 1000000;
rcg::setEnum(nodemap, "GainSelector", "All", false);
config.camera_gain_value = rcg::getFloat(nodemap, "Gain", 0, 0, true);
try
{
std::string v = rcg::getEnum(nodemap, "BalanceWhiteAuto", true);
config.camera_wb_auto = (v != "Off");
rcg::setEnum(nodemap, "BalanceRatioSelector", "Red", true);
config.camera_wb_ratio_red = rcg::getFloat(nodemap, "BalanceRatio", 0, 0, true);
rcg::setEnum(nodemap, "BalanceRatioSelector", "Blue", true);
config.camera_wb_ratio_blue = rcg::getFloat(nodemap, "BalanceRatio", 0, 0, true);
}
catch (const std::exception&)
{
config.camera_wb_auto = true;
config.camera_wb_ratio_red = 1.2;
config.camera_wb_ratio_blue = 2.4;
}
// get depth image configuration
config.depth_acquisition_mode = rcg::getEnum(nodemap, "DepthAcquisitionMode", true);
config.depth_quality = rcg::getEnum(nodemap, "DepthQuality", true);
config.depth_static_scene = rcg::getBoolean(nodemap, "DepthStaticScene", true);
config.depth_double_shot = rcg::getBoolean(nodemap, "DepthDoubleShot", false);
config.depth_seg = rcg::getInteger(nodemap, "DepthSeg", 0, 0, true);
config.depth_smooth = rcg::getBoolean(nodemap, "DepthSmooth", true);
config.depth_fill = rcg::getInteger(nodemap, "DepthFill", 0, 0, true);
config.depth_minconf = rcg::getFloat(nodemap, "DepthMinConf", 0, 0, true);
config.depth_mindepth = rcg::getFloat(nodemap, "DepthMinDepth", 0, 0, true);
config.depth_maxdepth = rcg::getFloat(nodemap, "DepthMaxDepth", 0, 0, true);
config.depth_maxdeptherr = rcg::getFloat(nodemap, "DepthMaxDepthErr", 0, 0, true);
config.ptp_enabled = rcg::getBoolean(nodemap, "PtpEnable", false);
rcg::setEnum(nodemap, "LineSelector", "Out1", true);
config.out1_mode = rcg::getEnum(nodemap, "LineSource", true);
rcg::setEnum(nodemap, "LineSelector", "Out2", false);
config.out2_mode = rcg::getEnum(nodemap, "LineSource", true);
try
{
config.depth_exposure_adapt_timeout = rcg::getFloat(nodemap, "DepthExposureAdaptTimeout", 0, 0, true);
}
catch (const std::exception&)
{
NODELET_WARN("rc_visard_driver: rc_visard has an older firmware, depth_exposure_adapt_timeout is not available.");
}
// try to get ROS parameters: if parameter is not set in parameter server
// default to current sensor configuration
pnh.param("camera_fps", config.camera_fps, config.camera_fps);
pnh.param("camera_exp_auto", config.camera_exp_auto, config.camera_exp_auto);
pnh.param("camera_exp_auto_mode", config.camera_exp_auto_mode, config.camera_exp_auto_mode);
pnh.param("camera_exp_max", config.camera_exp_max, config.camera_exp_max);
pnh.param("camera_exp_auto_average_max", config.camera_exp_auto_average_max, config.camera_exp_auto_average_max);
pnh.param("camera_exp_auto_average_min", config.camera_exp_auto_average_min, config.camera_exp_auto_average_min);
pnh.param("camera_exp_value", config.camera_exp_value, config.camera_exp_value);
pnh.param("camera_gain_value", config.camera_gain_value, config.camera_gain_value);
pnh.param("camera_exp_offset_x", config.camera_exp_offset_x, config.camera_exp_offset_x);
pnh.param("camera_exp_offset_y", config.camera_exp_offset_y, config.camera_exp_offset_y);
pnh.param("camera_exp_width", config.camera_exp_width, config.camera_exp_width);
pnh.param("camera_exp_height", config.camera_exp_height, config.camera_exp_height);
pnh.param("camera_wb_auto", config.camera_wb_auto, config.camera_wb_auto);
pnh.param("camera_wb_ratio_red", config.camera_wb_ratio_red, config.camera_wb_ratio_red);
pnh.param("camera_wb_ratio_blue", config.camera_wb_ratio_blue, config.camera_wb_ratio_blue);
pnh.param("depth_acquisition_mode", config.depth_acquisition_mode, config.depth_acquisition_mode);
pnh.param("depth_quality", config.depth_quality, config.depth_quality);
pnh.param("depth_static_scene", config.depth_static_scene, config.depth_static_scene);
pnh.param("depth_double_shot", config.depth_double_shot, config.depth_double_shot);
pnh.param("depth_seg", config.depth_seg, config.depth_seg);
pnh.param("depth_smooth", config.depth_smooth, config.depth_smooth);
pnh.param("depth_fill", config.depth_fill, config.depth_fill);
pnh.param("depth_minconf", config.depth_minconf, config.depth_minconf);
pnh.param("depth_mindepth", config.depth_mindepth, config.depth_mindepth);
pnh.param("depth_maxdepth", config.depth_maxdepth, config.depth_maxdepth);
pnh.param("depth_maxdeptherr", config.depth_maxdeptherr, config.depth_maxdeptherr);
pnh.param("depth_exposure_adapt_timeout", config.depth_exposure_adapt_timeout, config.depth_exposure_adapt_timeout);
pnh.param("ptp_enabled", config.ptp_enabled, config.ptp_enabled);
pnh.param("out1_mode", config.out1_mode, config.out1_mode);
pnh.param("out2_mode", config.out2_mode, config.out2_mode);
// set parameters on parameter server so that dynamic reconfigure picks them up
pnh.setParam("camera_fps", config.camera_fps);
pnh.setParam("camera_exp_auto", config.camera_exp_auto);
pnh.setParam("camera_exp_auto_mode", config.camera_exp_auto_mode);
pnh.setParam("camera_exp_max", config.camera_exp_max);
pnh.setParam("camera_exp_auto_average_max", config.camera_exp_auto_average_max);
pnh.setParam("camera_exp_auto_average_min", config.camera_exp_auto_average_min);
pnh.setParam("camera_exp_value", config.camera_exp_value);
pnh.setParam("camera_gain_value", config.camera_gain_value);
pnh.setParam("camera_exp_offset_x", config.camera_exp_offset_x);
pnh.setParam("camera_exp_offset_y", config.camera_exp_offset_y);
pnh.setParam("camera_exp_width", config.camera_exp_width);
pnh.setParam("camera_exp_height", config.camera_exp_height);
pnh.setParam("camera_wb_auto", config.camera_wb_auto);
pnh.setParam("camera_wb_ratio_red", config.camera_wb_ratio_red);
pnh.setParam("camera_wb_ratio_blue", config.camera_wb_ratio_blue);
pnh.setParam("depth_acquisition_mode", config.depth_acquisition_mode);
pnh.setParam("depth_quality", config.depth_quality);
pnh.setParam("depth_static_scene", config.depth_static_scene);
pnh.setParam("depth_double_shot", config.depth_double_shot);
pnh.setParam("depth_seg", config.depth_seg);
pnh.setParam("depth_smooth", config.depth_smooth);
pnh.setParam("depth_fill", config.depth_fill);
pnh.setParam("depth_minconf", config.depth_minconf);
pnh.setParam("depth_mindepth", config.depth_mindepth);
pnh.setParam("depth_maxdepth", config.depth_maxdepth);
pnh.setParam("depth_maxdeptherr", config.depth_maxdeptherr);
pnh.setParam("depth_exposure_adapt_timeout", config.depth_exposure_adapt_timeout);
pnh.setParam("ptp_enabled", config.ptp_enabled);
pnh.setParam("out1_mode", config.out1_mode);
pnh.setParam("out2_mode", config.out2_mode);
}
void GenICamDeviceNodelet::reconfigure(rc_genicam_driver::rc_genicam_driverConfig& c, uint32_t level)
{
std::lock_guard<std::recursive_mutex> lock(device_mtx);
try
{
if (nodemap)
{
if (level & 1)
{
rcg::setFloat(nodemap, "AcquisitionFrameRate", c.camera_fps, true);
}
if (level & 2)
{
if (c.camera_exp_auto)
{
// Normal means continuous and off must be controlled with exp_auto
if (c.camera_exp_auto_mode == "Off" || c.camera_exp_auto_mode == "Normal")
{
c.camera_exp_auto_mode = "Continuous";
}
// find user requested auto exposure mode in the list of enums
std::vector<std::string> list;
rcg::getEnum(nodemap, "ExposureAuto", list, false);
std::string mode = "Continuous";
for (size_t i = 0; i < list.size(); i++)
{
if (c.camera_exp_auto_mode == list[i])
{
mode = list[i];
}
}
// set auto exposure mode
rcg::setEnum(nodemap, "ExposureAuto", mode.c_str(), true);
// Continuous means normal
if (mode == "Continuous")
{
mode = "Normal";
}
c.camera_exp_auto_mode = mode;
}
else
{
rcg::setEnum(nodemap, "ExposureAuto", "Off", true);
usleep(100 * 1000);
c.camera_exp_value = rcg::getFloat(nodemap, "ExposureTime", 0, 0, true, true) / 1000000;
c.camera_gain_value = rcg::getFloat(nodemap, "Gain", 0, 0, true, true);
}
}
if (level & 4)
{
rcg::setFloat(nodemap, "ExposureTimeAutoMax", 1000000 * c.camera_exp_max, true);
}
if (level & 8)
{
if (!rcg::setFloat(nodemap, "RcExposureAutoAverageMax", c.camera_exp_auto_average_max, false))
{
NODELET_WARN("rc_visard does not support parameter 'exp_auto_average_max'");
c.camera_exp_auto_average_max = 0.75f;
}
}
if (level & 16)
{
if (!rcg::setFloat(nodemap, "RcExposureAutoAverageMin", c.camera_exp_auto_average_min, false))
{
NODELET_WARN("rc_visard does not support parameter 'exp_auto_average_min'");
c.camera_exp_auto_average_min = 0.25f;
}
}
if (level & 32)
{
rcg::setFloat(nodemap, "ExposureTime", 1000000 * c.camera_exp_value, true);
}
c.camera_gain_value = round(c.camera_gain_value / 6) * 6;
if (level & 64)
{
rcg::setFloat(nodemap, "Gain", c.camera_gain_value, true);
}
if (level & 128)
{
rcg::setInteger(nodemap, "ExposureRegionOffsetX", c.camera_exp_offset_x, true);
}
if (level & 256)
{
rcg::setInteger(nodemap, "ExposureRegionOffsetY", c.camera_exp_offset_y, true);
}
if (level & 512)
{
rcg::setInteger(nodemap, "ExposureRegionWidth", c.camera_exp_width, true);
}
if (level & 1024)
{
rcg::setInteger(nodemap, "ExposureRegionHeight", c.camera_exp_height, true);
}
bool color_ok = true;
if (level & 2048)
{
if (c.camera_wb_auto)
{
color_ok = rcg::setEnum(nodemap, "BalanceWhiteAuto", "Continuous", false);
}
else
{
color_ok = rcg::setEnum(nodemap, "BalanceWhiteAuto", "Off", false);
usleep(100 * 1000);
rcg::setEnum(nodemap, "BalanceRatioSelector", "Red", false);
c.camera_wb_ratio_red = rcg::getFloat(nodemap, "BalanceRatio", 0, 0, false, true);
rcg::setEnum(nodemap, "BalanceRatioSelector", "Blue", false);
c.camera_wb_ratio_blue = rcg::getFloat(nodemap, "BalanceRatio", 0, 0, false, true);
}
}
if (level & 4096)
{
rcg::setEnum(nodemap, "BalanceRatioSelector", "Red", false);
color_ok = rcg::setFloat(nodemap, "BalanceRatio", c.camera_wb_ratio_red, false);
}
if (level & 8192)
{
rcg::setEnum(nodemap, "BalanceRatioSelector", "Blue", false);
color_ok = rcg::setFloat(nodemap, "BalanceRatio", c.camera_wb_ratio_blue, false);
}
if (!color_ok)
{
c.camera_wb_auto = true;
c.camera_wb_ratio_red = 1.2;
c.camera_wb_ratio_blue = 2.4;
}
if (level & 16384)
{
// correct configuration strings if needed
if (c.depth_acquisition_mode == "S" || c.depth_acquisition_mode == "SingleFrame")
{
c.depth_acquisition_mode = "SingleFrame";
}
else if (c.depth_acquisition_mode == "O" || c.depth_acquisition_mode == "SingleFrameOut1")
{
c.depth_acquisition_mode = "SingleFrameOut1";
}
else if (c.depth_acquisition_mode == "C" || c.depth_acquisition_mode == "Continuous")
{
c.depth_acquisition_mode = "Continuous";
}
else
{
c.depth_acquisition_mode = "Continuous";
}
rcg::setEnum(nodemap, "DepthAcquisitionMode", c.depth_acquisition_mode.c_str(), true);
}
if (level & 32768)
{
if (c.depth_quality == "Full" || c.depth_quality == "F")
{
c.depth_quality = "Full";
}
else if (c.depth_quality == "High" || c.depth_quality == "H")
{
c.depth_quality = "High";
}
else if (c.depth_quality == "Medium" || c.depth_quality == "M")
{
c.depth_quality = "Medium";
}
else if (c.depth_quality == "Low" || c.depth_quality == "L")
{
c.depth_quality = "Low";
}
else
{
c.depth_quality = "High";
}
try
{
rcg::setEnum(nodemap, "DepthQuality", c.depth_quality.c_str(), true);
}
catch (const std::exception&)
{
c.depth_quality = "High";
rcg::setEnum(nodemap, "DepthQuality", c.depth_quality.c_str(), false);
NODELET_ERROR("Cannot set full quality. Sensor may have no 'stereo_plus' license!");
}
}
if (level & 65536)
{
rcg::setBoolean(nodemap, "DepthStaticScene", c.depth_static_scene, true);
}
if (level & 131072)
{
try
{
rcg::setBoolean(nodemap, "DepthDoubleShot", c.depth_double_shot, true);
}
catch (const std::exception&)
{
c.depth_double_shot = false;
NODELET_ERROR("Cannot set double shot mode. Please update the sensor to version >= 20.11.0!");
}
}
if (level & 262144)
{
rcg::setInteger(nodemap, "DepthSeg", c.depth_seg, true);
}
if (level & 524288 && c.depth_smooth != config.depth_smooth)
{
try
{
rcg::setBoolean(nodemap, "DepthSmooth", c.depth_smooth, true);
}
catch (const std::exception&)
{
c.depth_smooth = false;
rcg::setBoolean(nodemap, "DepthSmooth", c.depth_smooth, false);
NODELET_ERROR("Cannot switch on smoothing. Sensor may have no 'stereo_plus' license!");
}
}
if (level & 1048576)
{
rcg::setInteger(nodemap, "DepthFill", c.depth_fill, true);
}
if (level & 2097152)
{
rcg::setFloat(nodemap, "DepthMinConf", c.depth_minconf, true);
}
if (level & 4194304)
{
rcg::setFloat(nodemap, "DepthMinDepth", c.depth_mindepth, true);
}
if (level & 8388608)
{
rcg::setFloat(nodemap, "DepthMaxDepth", c.depth_maxdepth, true);
}
if (level & 16777216)
{
rcg::setFloat(nodemap, "DepthMaxDepthErr", c.depth_maxdeptherr, true);
}
if ((level & 33554432) && c.ptp_enabled != config.ptp_enabled)
{
if (!rcg::setBoolean(nodemap, "PtpEnable", c.ptp_enabled, false))
{
NODELET_ERROR("Cannot change PTP.");
c.ptp_enabled = false;
}
}
if ((level & 67108864) && c.out1_mode != config.out1_mode)
{
if (c.out1_mode != "Low" && c.out1_mode != "High" && c.out1_mode != "ExposureActive" &&
c.out1_mode != "ExposureAlternateActive")
{
c.out1_mode = "Low";
}
rcg::setEnum(nodemap, "LineSelector", "Out1", true);
if (!rcg::setEnum(nodemap, "LineSource", c.out1_mode.c_str(), false))
{
c.out1_mode = "Low";
NODELET_ERROR("Cannot change out1 mode. Sensor may have no 'iocontrol' license!");
}
}
if (level & 134217728 && c.out2_mode != config.out2_mode)
{
if (c.out2_mode != "Low" && c.out2_mode != "High" && c.out2_mode != "ExposureActive" &&
c.out2_mode != "ExposureAlternateActive")
{
c.out2_mode = "Low";
}
if (rcg::setEnum(nodemap, "LineSelector", "Out2", false))
{
if (!rcg::setEnum(nodemap, "LineSource", c.out2_mode.c_str(), false))
{
c.out2_mode = "Low";
NODELET_ERROR("Cannot change out2 mode. Sensor may have no 'iocontrol' license!");
}
}
}
if (level & 268435456)
{
try
{
rcg::setFloat(nodemap, "DepthExposureAdaptTimeout", c.depth_exposure_adapt_timeout, true);
}
catch (const std::exception&)
{
c.depth_exposure_adapt_timeout = 0.0;
NODELET_ERROR("Cannot set depth_exposure_adapt_timeout. Please update the sensor to version >= 21.10!");
}
}
}
}
catch (const std::exception& ex)
{
NODELET_ERROR_STREAM(ex.what());
}
config = c;
}
void GenICamDeviceNodelet::updateSubscriptions(bool force)
{
std::lock_guard<std::recursive_mutex> lock(device_mtx);
// collect required components and color
int rcomponents = 0;
bool rcolor = false;
for (auto&& p : pub)
{
p->requiresComponents(rcomponents, rcolor);
}
// Intensity is contained in IntensityCombined
if (rcomponents & GenICam2RosPublisher::ComponentIntensityCombined)
{
rcomponents &= ~GenICam2RosPublisher::ComponentIntensity;
}
// enable or disable components as required
const static struct
{
const char* name;
int flag;
} comp[] = { { "Intensity", GenICam2RosPublisher::ComponentIntensity },
{ "IntensityCombined", GenICam2RosPublisher::ComponentIntensityCombined },
{ "Disparity", GenICam2RosPublisher::ComponentDisparity },
{ "Confidence", GenICam2RosPublisher::ComponentConfidence },
{ "Error", GenICam2RosPublisher::ComponentError },
{ 0, 0 } };
for (size_t i = 0; comp[i].name != 0; i++)
{
if (((rcomponents ^ scomponents) & comp[i].flag) || force)
{
rcg::setEnum(nodemap, "ComponentSelector", comp[i].name, true);
rcg::setBoolean(nodemap, "ComponentEnable", (rcomponents & comp[i].flag), true);
const char* status = "disabled";
if (rcomponents & comp[i].flag)
status = "enabled";
if (!force)
{
NODELET_INFO_STREAM("Component '" << comp[i].name << "' " << status);
}
}
}
// enable or disable color
if (rcolor != scolor || force)
{
std::string format = "Mono8";
if (rcolor)
{
format = color_format;
}
rcg::setEnum(nodemap, "ComponentSelector", "Intensity", true);
rcg::setEnum(nodemap, "PixelFormat", format.c_str(), false);
rcg::setEnum(nodemap, "ComponentSelector", "IntensityCombined", true);
rcg::setEnum(nodemap, "PixelFormat", format.c_str(), false);
}
// store current settings
scomponents = rcomponents;
scolor = rcolor;
}
void GenICamDeviceNodelet::subChanged()
{
updateSubscriptions(false);
}
void GenICamDeviceNodelet::publishConnectionDiagnostics(diagnostic_updater::DiagnosticStatusWrapper& stat)
{
stat.add("connection_loss_total", connection_loss_total);
stat.add("complete_buffers_total", complete_buffers_total);
stat.add("incomplete_buffers_total", incomplete_buffers_total);
stat.add("image_receive_timeouts_total", image_receive_timeouts_total);
stat.add("current_reconnect_trial", current_reconnect_trial);
// general connection status
if (device_serial.empty())
{
stat.summary(diagnostic_msgs::DiagnosticStatus::ERROR, "Disconnected");
return;
}
// at least we are connected to gev server
stat.add("ip_interface", device_interface);
stat.add("ip_address", device_ip);
stat.add("gev_packet_size", gev_packet_size);
if (scomponents)
{
if (streaming)
{
// someone subscribed to images, and we actually receive data via GigE vision
stat.summary(diagnostic_msgs::DiagnosticStatus::OK, "Streaming");
}
else
{
// someone subscribed to images, but we do not receive any data via GigE vision (yet)
stat.summary(diagnostic_msgs::DiagnosticStatus::WARN, "No data");
}
}
else
{
// no one requested images -> node is ok but stale
stat.summary(diagnostic_msgs::DiagnosticStatus::OK, "Idle");
}
}
void GenICamDeviceNodelet::publishDeviceDiagnostics(diagnostic_updater::DiagnosticStatusWrapper& stat)
{
if (device_serial.empty())
{
stat.summary(diagnostic_msgs::DiagnosticStatus::ERROR, "Unknown");
}
else
{
stat.summary(diagnostic_msgs::DiagnosticStatus::OK, "Info");
stat.add("model", device_model);
stat.add("image_version", device_version);
stat.add("serial", device_serial);
stat.add("mac", device_mac);
stat.add("user_id", device_name);
}
}
namespace
{
std::vector<std::shared_ptr<rcg::Device> > getSupportedDevices(const std::string& devid,
const std::vector<std::string>& iname)
{
std::vector<std::shared_ptr<rcg::System> > system = rcg::System::getSystems();
std::vector<std::shared_ptr<rcg::Device> > ret;
for (size_t i = 0; i < system.size(); i++)
{
system[i]->open();
std::vector<std::shared_ptr<rcg::Interface> > interf = system[i]->getInterfaces();
for (size_t k = 0; k < interf.size(); k++)
{
if (interf[k]->getTLType() == "GEV" &&
(iname.size() == 0 || std::find(iname.begin(), iname.end(), interf[k]->getID()) != iname.end()))
{
interf[k]->open();
std::vector<std::shared_ptr<rcg::Device> > device = interf[k]->getDevices();
for (size_t j = 0; j < device.size(); j++)
{
if ((device[j]->getVendor() == "Roboception GmbH" ||
device[j]->getModel().substr(0, 9) == "rc_visard" || device[j]->getModel().substr(0, 7) == "rc_cube") &&
(devid == "*" || device[j]->getID() == devid || device[j]->getSerialNumber() == devid ||
device[j]->getDisplayName() == devid))
{
ret.push_back(device[j]);
}
}
interf[k]->close();
}
}
system[i]->close();
}
return ret;
}
class NoDeviceException : public std::invalid_argument
{
public:
NoDeviceException(const char* msg) : std::invalid_argument(msg)
{
}
};
void split(std::vector<std::string>& list, const std::string& s, char delim, bool skip_empty = true)
{
std::stringstream in(s);
std::string elem;
while (getline(in, elem, delim))
{
if (!skip_empty || elem.size() > 0)
{
list.push_back(elem);
}
}
}
} // namespace
void GenICamDeviceNodelet::grab(std::string id, rcg::Device::ACCESS access)
{
try
{
device_model = "";
device_version = "";
device_serial = "";
device_mac = "";
device_name = "";
device_interface = "";
device_ip = "";
gev_packet_size = 0;
current_reconnect_trial = 1;
NODELET_INFO_STREAM("Grabbing thread started for device '" << id << "'");
// loop until nodelet is killed
while (running)
{
streaming = false;
// report standard exceptions and try again
try
{
std::shared_ptr<GenApi::CChunkAdapter> chunkadapter;
{
std::lock_guard<std::recursive_mutex> lock(device_mtx);
// open device and get nodemap
std::vector<std::string> iname; // empty
std::string dname = id;
{
size_t i = dname.find(':');
if (i != std::string::npos)
{
if (i > 0)
{
iname.push_back(id.substr(0, i));
}
dname = dname.substr(i + 1);
}
}
std::vector<std::shared_ptr<rcg::Device> > devices = getSupportedDevices(dname, iname);
if (devices.size() == 0)
{
throw NoDeviceException(("Cannot find device '" + id + "'").c_str());
}
if (devices.size() > 1)
{
throw std::invalid_argument("Too many devices, please specify unique ID");
}
dev = devices[0];
dev->open(access);
nodemap = dev->getRemoteNodeMap();
// check if device is ready
if (!rcg::getBoolean(nodemap, "RcSystemReady", true, true))
{
throw std::invalid_argument("Device is not yet ready");
}
// get serial number and IP
device_interface = dev->getParent()->getID();
device_serial = dev->getSerialNumber();
device_mac = rcg::getString(nodemap, "GevMACAddress", false);
device_name = rcg::getString(nodemap, "DeviceUserID", true);
device_ip = rcg::getString(nodemap, "GevCurrentIPAddress", false);
NODELET_INFO_STREAM(""
<< "Connecting to sensor '" << device_interface << ":" << device_serial << "' alias "
<< dev->getDisplayName());
updater.setHardwareID(device_serial);
// ensure that device version >= 20.04
device_version = rcg::getString(nodemap, "DeviceVersion");
std::vector<std::string> list;
split(list, device_version, '.');
if (list.size() < 3 || std::stoi(list[0]) < 20 || (std::stoi(list[0]) == 20 && std::stoi(list[1]) < 4))
{
running = false;
throw std::invalid_argument("Device version must be 20.04 or higher: " + device_version);
}
// get model type of the device
device_model = rcg::getString(nodemap, "DeviceModelName");
// initialise configuration and start dynamic reconfigure server
if (!reconfig)
{
initConfiguration();
reconfig = new dynamic_reconfigure::Server<rc_genicam_driver::rc_genicam_driverConfig>(
reconfig_mtx, getPrivateNodeHandle());
}
// initialize some values as the old values are checked in the
// reconfigure callback
config.depth_smooth = rcg::getBoolean(nodemap, "DepthSmooth", true);
rcg::setEnum(nodemap, "LineSelector", "Out1", true);
config.out1_mode = rcg::getEnum(nodemap, "LineSource", true);
rcg::setEnum(nodemap, "LineSelector", "Out2", false);
config.out2_mode = rcg::getEnum(nodemap, "LineSource", true);
config.ptp_enabled = rcg::getBoolean(nodemap, "PtpEnable", false);
// assign callback each time to trigger resetting all values
dynamic_reconfigure::Server<rc_genicam_driver::rc_genicam_driverConfig>::CallbackType cb;
cb = boost::bind(&GenICamDeviceNodelet::reconfigure, this, _1, _2);
reconfig->setCallback(cb);
}
// enable chunk data and multipart
rcg::setEnum(nodemap, "AcquisitionAlternateFilter", "Off", false);
rcg::setEnum(nodemap, "AcquisitionMultiPartMode", "SingleComponent", true);
rcg::setBoolean(nodemap, "ChunkModeActive", true, true);
// set up chunk adapter
chunkadapter = rcg::getChunkAdapter(nodemap, dev->getTLType());
// check for color and iocontrol
bool color = false;
{
std::vector<std::string> formats;
rcg::setEnum(nodemap, "ComponentSelector", "Intensity", true);
rcg::getEnum(nodemap, "PixelFormat", formats, true);
for (auto&& format : formats)
{
if (format == "YCbCr411_8")
{
color_format = "YCbCr411_8";
color = true;
break;
}
if (format == "RGB8")
{
color_format = "RGB8";
color = true;
break;
}
}
}
bool iocontrol_avail = nodemap->_GetNode("LineSource")->GetAccessMode() == GenApi::RW;
if (!color)
{
NODELET_INFO("Not a color camera. wb_auto, wb_ratio_red and wb_ratio_blue are without "
"function.");
}
if (nodemap->_GetNode("DepthSmooth")->GetAccessMode() != GenApi::RW)
{
NODELET_WARN("No stereo_plus license on device. quality=full and smoothing is not available.");
}
if (!iocontrol_avail)
{
NODELET_WARN("No iocontrol license on device. out1_mode and out2_mode are without function.");
}
// advertise publishers
ros::NodeHandle nh(getNodeHandle(), "stereo");
image_transport::ImageTransport it(nh);
std::function<void()> callback = std::bind(&GenICamDeviceNodelet::subChanged, this);
pub.clear();
scomponents = 0;
scolor = false;
pub.push_back(std::make_shared<CameraInfoPublisher>(nh, frame_id, true, callback));
pub.push_back(std::make_shared<CameraInfoPublisher>(nh, frame_id, false, callback));
pub.push_back(std::make_shared<CameraParamPublisher>(nh, frame_id, true, callback));
pub.push_back(std::make_shared<CameraParamPublisher>(nh, frame_id, false, callback));
pub.push_back(std::make_shared<ImagePublisher>(it, frame_id, true, false, iocontrol_avail, callback));
pub.push_back(std::make_shared<ImagePublisher>(it, frame_id, false, false, iocontrol_avail, callback));
if (color)
{
pub.push_back(std::make_shared<ImagePublisher>(it, frame_id, true, true, iocontrol_avail, callback));
pub.push_back(std::make_shared<ImagePublisher>(it, frame_id, false, true, iocontrol_avail, callback));
}
pub.push_back(std::make_shared<DisparityPublisher>(nh, frame_id, callback));
pub.push_back(std::make_shared<DisparityColorPublisher>(it, frame_id, callback));
pub.push_back(std::make_shared<DepthPublisher>(nh, frame_id, callback));
pub.push_back(std::make_shared<ConfidencePublisher>(nh, frame_id, callback));
pub.push_back(std::make_shared<ErrorDisparityPublisher>(nh, frame_id, callback));
pub.push_back(std::make_shared<ErrorDepthPublisher>(nh, frame_id, callback));
pub.push_back(std::make_shared<Points2Publisher>(nh, frame_id, callback));
// make nodemap available to publshers
for (auto&& p : pub)
{
p->setNodemap(nodemap);
}
// update subscriptions
updateSubscriptions(true);
// start streaming
std::vector<std::shared_ptr<rcg::Stream> > stream = dev->getStreams();
if (stream.size() == 0)
{
throw std::invalid_argument("Device does not offer streams");
}
stream[0]->open();
stream[0]->startStreaming();
current_reconnect_trial = 1;
updater.force_update();
NODELET_INFO_STREAM("Start streaming images");
// grabbing and publishing
while (running)
{
// grab next buffer
const rcg::Buffer* buffer = stream[0]->grab(500);
std::string out1_mode_on_sensor;
// process buffer
if (buffer)
{
streaming = true;
if (buffer->getIsIncomplete())
{
incomplete_buffers_total++;
out1_mode_on_sensor = "";
}
else
{
complete_buffers_total++;
std::lock_guard<std::recursive_mutex> lock(device_mtx);
if (gev_packet_size == 0)
{
gev_packet_size = rcg::getInteger(nodemap, "GevSCPSPacketSize", 0, 0, false, false);
}
// attach buffer to nodemap to access chunk data
chunkadapter->AttachBuffer(reinterpret_cast<std::uint8_t*>(buffer->getGlobalBase()),
buffer->getSizeFilled());
// get out1 mode on device, which may have changed
rcg::setEnum(nodemap, "ChunkLineSelector", "Out1", true);
out1_mode_on_sensor = rcg::getEnum(nodemap, "ChunkLineSource", true);
// publish all parts of buffer
uint32_t npart = buffer->getNumberOfParts();
for (uint32_t part = 0; part < npart; part++)
{
if (buffer->getImagePresent(part))
{
uint64_t pixelformat = buffer->getPixelFormat(part);
for (auto&& p : pub)
{
p->publish(buffer, part, pixelformat);
}
}
}
// detach buffer from nodemap
chunkadapter->DetachBuffer();
}
}
else
{
image_receive_timeouts_total++;
streaming = false;
// get out1 mode from sensor (this is also used to check if the
// connection is still valid)
std::lock_guard<std::recursive_mutex> lock(device_mtx);
rcg::setEnum(nodemap, "LineSelector", "Out1", true);
out1_mode_on_sensor = rcg::getString(nodemap, "LineSource", true, true);
}
{
std::lock_guard<std::recursive_mutex> lock(device_mtx);
// update out1 mode, if it is different to current settings on sensor
// (which is the only GEV parameter which could have changed outside this code,
// i.e. on the rc_visard by the stereomatching module)
if (out1_mode_on_sensor.size() == 0)
{
// use current settings if the value on the sensor cannot be determined
out1_mode_on_sensor = config.out1_mode;
}
if (out1_mode_on_sensor != config.out1_mode)
{
config.out1_mode = out1_mode_on_sensor;
reconfig->updateConfig(config);
}
}
updater.update();
}
pub.clear();
// stop streaming
stream[0]->stopStreaming();
stream[0]->close();
// stop publishing
device_model = "";
device_version = "";
device_serial = "";
device_mac = "";
device_name = "";
device_interface = "";
device_ip = "";
gev_packet_size = 0;
streaming = false;
updater.force_update();
}
catch (const NoDeviceException& ex)
{
// report error, wait and retry
NODELET_WARN_STREAM(ex.what());
current_reconnect_trial++;
streaming = false;
pub.clear();
updater.force_update();
sleep(3);
}
catch (const std::exception& ex)
{
// close everything and report error
if (device_ip.size() > 0)
{
connection_loss_total++;
}
device_model = "";
device_version = "";
device_serial = "";
device_mac = "";
device_name = "";
device_interface = "";
device_ip = "";
gev_packet_size = 0;
streaming = false;
current_reconnect_trial++;
pub.clear();
NODELET_ERROR_STREAM(ex.what());
updater.force_update();
sleep(3);
}
// close device
{
std::lock_guard<std::recursive_mutex> lock(device_mtx);
if (dev)
dev->close();
dev.reset();
nodemap.reset();
}
}
}
catch (const std::exception& ex)
{
NODELET_FATAL_STREAM(ex.what());
}
catch (...)
{
NODELET_FATAL("Unknown exception");
}
device_model = "";
device_version = "";
device_serial = "";
device_mac = "";
device_name = "";
device_interface = "";
device_ip = "";
gev_packet_size = 0;
streaming = false;
updater.force_update();
running = false;
NODELET_INFO("Grabbing thread stopped");
}
} // namespace rc
PLUGINLIB_EXPORT_CLASS(rc::GenICamDeviceNodelet, nodelet::Nodelet)
| 31.307692 | 120 | 0.626255 | roboception |
aab965312397f90f3c18b850ecf341fe64ca32e9 | 2,825 | cpp | C++ | Tekken-7-Frames-To-Speech/audio.cpp | n-o-u/Tekken-7-Frames-To-Speech | b0c794464f34e0c0cdc3a848be3b51fc7e33ca1d | [
"MIT"
] | 1 | 2021-01-28T22:12:28.000Z | 2021-01-28T22:12:28.000Z | Tekken-7-Frames-To-Speech/audio.cpp | n-o-u/Tekken-7-Frames-To-Speech | b0c794464f34e0c0cdc3a848be3b51fc7e33ca1d | [
"MIT"
] | null | null | null | Tekken-7-Frames-To-Speech/audio.cpp | n-o-u/Tekken-7-Frames-To-Speech | b0c794464f34e0c0cdc3a848be3b51fc7e33ca1d | [
"MIT"
] | 1 | 2021-01-28T22:12:59.000Z | 2021-01-28T22:12:59.000Z | #include "frames-to-speech.h"
#include "resource.h"
#include "audio.h"
void playFramesAudio(int frames) {
LPCWSTR path = getWavResourcePath(frames);
if (path != 0) {
PlaySound(path, GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
//PlaySound(path, GetModuleHandle(NULL), SND_FILENAME | SND_ASYNC); //directly from a file
}
//PlaySound(path, GetModuleHandle(NULL), SND_FILENAME | SND_ASYNC);
//char* buffer = loadWavFile((char*)WAV_14_PATH);
//PlaySound(buffer, GetModuleHandle(NULL), SND_MEMORY);
}
LPCWSTR getWavResourcePath(int frames) {
LPCWSTR path = 0;
switch (frames) {
case 10:
path = MAKEINTRESOURCE(IDR_WAVE10);
break;
case 11:
path = MAKEINTRESOURCE(IDR_WAVE11);
break;
case 12:
path = MAKEINTRESOURCE(IDR_WAVE12);
break;
case 13:
path = MAKEINTRESOURCE(IDR_WAVE13);
break;
case 14:
path = MAKEINTRESOURCE(IDR_WAVE14);
break;
case 15:
path = MAKEINTRESOURCE(IDR_WAVE15);
break;
case 16:
path = MAKEINTRESOURCE(IDR_WAVE16);
break;
case 17:
path = MAKEINTRESOURCE(IDR_WAVE17);
break;
case 18:
path = MAKEINTRESOURCE(IDR_WAVE18);
break;
case 19:
path = MAKEINTRESOURCE(IDR_WAVE19);
break;
case 20:
path = MAKEINTRESOURCE(IDR_WAVE20);
break;
case 21:
path = MAKEINTRESOURCE(IDR_WAVE21);
break;
case 22:
path = MAKEINTRESOURCE(IDR_WAVE22);
break;
case 23:
path = MAKEINTRESOURCE(IDR_WAVE23);
break;
case 24:
path = MAKEINTRESOURCE(IDR_WAVE24);
break;
}
return path;
}
// not used
LPCWSTR getWavFilePath(int frames) {
LPCWSTR path = 0;
switch (frames) {
case 10:
path = WAV_10_PATH;
break;
case 11:
path = WAV_11_PATH;
break;
case 12:
path = WAV_12_PATH;
break;
case 13:
path = WAV_13_PATH;
break;
case 14:
path = WAV_14_PATH;
break;
case 15:
path = WAV_15_PATH;
break;
case 16:
path = WAV_16_PATH;
break;
case 17:
path = WAV_17_PATH;
break;
case 18:
path = WAV_18_PATH;
break;
case 19:
path = WAV_19_PATH;
break;
case 20:
path = WAV_20_PATH;
break;
case 21:
path = WAV_21_PATH;
break;
case 22:
path = WAV_22_PATH;
break;
case 23:
path = WAV_23_PATH;
break;
case 24:
path = WAV_24_PATH;
break;
}
return path;
}
// not used
WavFiles* loadWavFiles() {
WavFiles* result;
return result;
}
// not used
char* loadWavFile(char* path) {
char* result;
FILE* file;
unsigned long sizeFile, i;
char c;
errno_t errorCode;
if (0 != (errorCode = fopen_s(&file, path, "r"))) {
printf("Error, code: %d, loadWavFile(char*) failed to open file: %s\n", errorCode, path);
system("pause");
exit(0);
}
fseek(file, 0L, SEEK_END);
sizeFile = ftell(file);
rewind(file);
result = (char*) malloc((sizeFile + 1) * sizeof(char));
i = 0;
while ( (c = fgetc(file)) != EOF) {
result[i] = fgetc(file);
i++;
}
result[++i] = '\0';
return result;
}
| 17.993631 | 92 | 0.670088 | n-o-u |
aaba67aa05441d448ae0e0977586a10f1dc7c29d | 64 | cpp | C++ | src/ui/src/comms/dfcomms.cpp | Terebinth/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 117 | 2015-01-13T14:48:49.000Z | 2022-03-16T01:38:19.000Z | src/ui/src/comms/dfcomms.cpp | darongE/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 4 | 2015-05-01T13:09:53.000Z | 2017-07-22T09:11:06.000Z | src/ui/src/comms/dfcomms.cpp | darongE/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 78 | 2015-01-13T09:27:47.000Z | 2022-03-18T14:39:09.000Z | /*
UI Comms Driver stuff (ALL of it which is NOT part of VU)
*/
| 16 | 57 | 0.671875 | Terebinth |
aabca80b93a778881b4f513e64b9466519e11487 | 4,813 | hpp | C++ | src/sprite/llvm/type.hpp | andyjost/Sprite | 7ecd6fc7d48d7f62da644e48c12c7b882e1a2929 | [
"MIT"
] | 1 | 2022-03-16T16:37:11.000Z | 2022-03-16T16:37:11.000Z | src/sprite/llvm/type.hpp | andyjost/Sprite | 7ecd6fc7d48d7f62da644e48c12c7b882e1a2929 | [
"MIT"
] | null | null | null | src/sprite/llvm/type.hpp | andyjost/Sprite | 7ecd6fc7d48d7f62da644e48c12c7b882e1a2929 | [
"MIT"
] | null | null | null | #pragma once
#include "sprite/llvm/config.hpp"
#include "sprite/llvm/fwd.hpp"
#include "sprite/llvm/llvmobj.hpp"
#include "sprite/llvm/array_ref.hpp"
#include "sprite/llvm/special_values.hpp"
#include "sprite/llvm/type_traits.hpp"
#include "llvm/IR/DerivedTypes.h"
#include <iostream>
#include <vector>
namespace sprite { namespace llvm
{
/**
* @brief Wrapper for @p Type objects.
*
* Elaborated types can be created by using the @p * operator (to create
* pointers), the @p [] operator (to create arrays), or the @p () operator
* (to create functions).
*
* Constant values can be created using the call operator, as in
* <tt>i32(42)</tt> to create a 32-bit integer constant with value @p 42
* (assuming @p i32 is a type wrapper for the 32-bit integer type).
*/
struct type : llvmobj<Type, custodian<Type, no_delete>>
{
// Inherit constructors.
using llvmobj_base_type::llvmobj;
/// Creates a pointer type.
type operator*() const;
/// Creates a vector type.
type operator*(size_t) const;
friend type operator*(size_t, type);
/// Creates an array type.
type operator[](size_t) const;
/// Creates a function type.
type make_function(
std::vector<Type*> const &, bool is_varargs = false
) const;
#ifdef TEMPORARILY_DISABLED
template<
typename... Args
, SPRITE_ENABLE_FOR_ALL_FUNCTION_PROTOTYPES(Args...)
>
type operator()(Args &&... argtypes) const;
/**
* @brief Creates a constant of the type represented by @p this, using @p
* arg as the initializer.
*
* Synonymous with @p get_constant. Implemented in get_constant.hpp.
*/
template<
typename Arg
, SPRITE_ENABLE_FOR_ALL_CONSTANT_INITIALIZERS(Arg)
>
constant operator()(Arg &&) const;
/**
* @brief Creates a constant of the (array) type represented by @p this,
* using @p arg as the initializer.
*
* Synonymous with @p get_constant. Implemented in get_constant.hpp. This
* needs to be mentioned explicitly so that @p std::initializer_list will
* be accepted.
*/
constant operator()(any_array_ref const &) const;
#endif
};
bool operator==(type const &, type const &);
bool operator!=(type const &, type const &);
}}
namespace sprite { namespace llvm { namespace types
{
/// Creates an integer type of the specified bit width.
type int_(size_t numBits);
/// Creates an integer type the width of a native int.
type int_();
/// Creates an integer type the width of a native long.
type long_();
/// Creates an integer type the width of a native long long.
type longlong();
/// Creates a char type.
type char_();
/// Creates a bool type.
type bool_();
/**
* @brief Creates a floating-point type (32-bit, by default).
*
* @p numBits should be 32, 64 or 128.
*/
type float_(size_t numBits);
/// Creates the 32-bit floating-point type.
type float_();
/// Creates the 64-bit floating-point type.
type double_();
/// Creates the 128-bit floating-point type.
type longdouble();
/// Creates the void type.
type void_();
#ifdef TEMPORARILY_DISABLED
/// Creates the label type (for holding a @p block_address).
type label();
#endif
/// Creates an anonymous struct (uniqued by structural equivalence).
type struct_(std::vector<type> const & elements);
/**
* @brief Gets a struct by name.
*
* If the struct has not been created, a new opaque struct will be created.
*/
type struct_(std::string const & name);
/**
* @brief Defines a struct.
*
* The struct must not already have a body (though, it may exist and be
* opaque).
*/
type struct_(
std::string const & name, std::vector<type> const & elements
);
}}}
namespace sprite { namespace llvm
{
/// Returns the array extents.
std::vector<size_t> array_extents(type const &);
/// Indicates whether the specified cast is permitted.
bool is_castable(type src, type dst);
/// Indicates whether the specified bitcast is permitted.
bool is_bitcastable(type src, type dst);
/**
* @brief Applies type transformations as when passing a value to a function.
*
* See std::type_traits::decay.
*/
type decay(type);
/**
* @brief Determines the common type of a group of types.
*
* See std::type_traits::common_type.
*/
type common_type(std::vector<type> const &);
/// Returns the size in bytes (with alignment padding).
size_t sizeof_(type const &);
/// Returns the size in bits (without padding).
size_t bitwidth(type const &);
/// Returns the name for struct types.
std::string struct_name(type const &);
/// Returns the subtypes, as defined by LLVM.
std::vector<type> subtypes(type const &);
}}
| 26.157609 | 79 | 0.658633 | andyjost |