hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
09382a2a8eeaaf7d9fc703e2b52252e18075a2fc | 1,757 | cpp | C++ | tris_steki.cpp | IvarsSaudinis/alkoritmi-un-datu-strukturas | d3856b1428894843f2c80f27661ca6fb86ded878 | [
"MIT"
] | null | null | null | tris_steki.cpp | IvarsSaudinis/alkoritmi-un-datu-strukturas | d3856b1428894843f2c80f27661ca6fb86ded878 | [
"MIT"
] | null | null | null | tris_steki.cpp | IvarsSaudinis/alkoritmi-un-datu-strukturas | d3856b1428894843f2c80f27661ca6fb86ded878 | [
"MIT"
] | null | null | null | /*
* Papildināt nodarbībā veidoto C++ programmu, kas izveido
* stekus A, B un C. Stekos A un B tiek ierakstīti pa 15 gadījuma
* skaitļiem. Stekā C ieraksta vispirms visus steka A elementus
* un pēc tam - visus steka B elementus (kopā - stekā C jābūt 30
* elementiem).Izdrukāt visu trīs steku vērtības ekrānā.
*
* --
* build with Geany & gcc version 6.3.0 20170516 (Debian 6.3.0-18+deb9u1)
*/
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
struct Steks
{
int Data;
Steks *Next;
};
void Create(Steks* &S);
void Push(Steks* &S, int D);
void Pop(Steks* &S);
int Top(Steks* &S);
bool isEmpty(Steks* &S);
int main()
{
Steks *StA; srand(time(0)); int Num;
cout << "Steks A:" << endl;
Create(StA);
for (int i=0; i<15; i++)
{
Num = rand() % 99 + 1;
cout << Num << " ";
Push(StA, Num);
}
cout << endl << "Steks B:" << endl;
Steks *StB;
Create(StB);
for (int i=0; i<15; i++)
{
Num = rand() % 99 + 1;
cout << Num << " ";
Push(StB, Num);
}
// izveidojam jauno -> iztīram
Steks *StC; Create(StC);
cout << endl << "Steks C:" << endl;
while(!isEmpty(StB)){
Push(StC,Top(StB)); Pop(StB);
}
while(!isEmpty(StA)){
Push(StC,Top(StA)); Pop(StA);
}
while(!isEmpty(StC)){
cout << Top(StC) << " "; Pop(StC);
}
return 0;
}
void Create(Steks* &S)
{ S = NULL; }
void Push(Steks* &S, int D)
{
if (S == NULL)
{
S = new Steks;
S->Data = D; S->Next = NULL;
}
else
{
Steks *p; p = new Steks;
p->Data = D; p->Next = S; S = p;
}
}
void Pop(Steks* &S)
{
if (S != NULL)
{
Steks *p; p = S;
S = S->Next;
delete p;
}
}
int Top(Steks* &S)
{
return (S==NULL) ? -1 : S->Data;
}
bool isEmpty(Steks* &S)
{
return (S==NULL) ? true : false;
}
| 16.894231 | 75 | 0.561753 | IvarsSaudinis |
093feacf0a31201073c2c500c11fdfa15b6e253f | 1,663 | cpp | C++ | src/g2553/launchpad/tlc59731_test/main.cpp | ab2tech/msp430 | 5565f20f7ad7821ee6d8e0cdc7be3904a8df38b3 | [
"Apache-2.0"
] | 24 | 2015-01-04T19:03:41.000Z | 2022-03-11T05:50:19.000Z | src/g2553/launchpad/tlc59731_test/main.cpp | ab2tech/msp430 | 5565f20f7ad7821ee6d8e0cdc7be3904a8df38b3 | [
"Apache-2.0"
] | null | null | null | src/g2553/launchpad/tlc59731_test/main.cpp | ab2tech/msp430 | 5565f20f7ad7821ee6d8e0cdc7be3904a8df38b3 | [
"Apache-2.0"
] | 14 | 2015-05-05T22:47:14.000Z | 2021-10-12T13:11:14.000Z | #include "main.h"
int main(void)
{
clock(DCO_F_16MHz);
easyset tlc59731 = easyset(p1_0, 3);
for (;;) //ever
{
for (uint16_t i=0; i<255; i++)
{
tlc59731.rgbData(0, i, 0, 0);
tlc59731.rgbData(1, i, 0, 0);
tlc59731.rgbData(2, i, 0, 0);
tlc59731.update();
clock::delayMS(20);
}
//clock::delayS(1);
for (uint16_t i=0; i<255; i++)
{
tlc59731.rgbData(0, 0, i, 0);
tlc59731.rgbData(1, 0, i, 0);
tlc59731.rgbData(2, 0, i, 0);
tlc59731.update();
clock::delayMS(20);
}
//clock::delayS(1);
for (uint16_t i=0; i<255; i++)
{
tlc59731.rgbData(0, 0, 0, i);
tlc59731.rgbData(1, 0, 0, i);
tlc59731.rgbData(2, 0, 0, i);
tlc59731.update();
clock::delayMS(20);
}
for (uint16_t i=0; i<255; i++)
{
tlc59731.rgbData(0, i, 0, 0);
tlc59731.rgbData(1, 0, i, 0);
tlc59731.rgbData(2, 0, 0, i);
tlc59731.update();
clock::delayMS(20);
}
//clock::delayS(1);
for (uint16_t i=0; i<255; i++)
{
tlc59731.rgbData(0, 0, i, 0);
tlc59731.rgbData(1, 0, 0, i);
tlc59731.rgbData(2, i, 0, 0);
tlc59731.update();
clock::delayMS(20);
}
//clock::delayS(1);
for (uint16_t i=0; i<255; i++)
{
tlc59731.rgbData(0, 0, 0, i);
tlc59731.rgbData(1, i, 0, 0);
tlc59731.rgbData(2, 0, i, 0);
tlc59731.update();
clock::delayMS(20);
}
for (uint16_t i=0; i<255; i++)
{
tlc59731.rgbData(0, i, 0, i);
tlc59731.rgbData(1, i, 0, 0);
tlc59731.rgbData(2, 0, i, 0);
tlc59731.update();
clock::delayMS(20);
}
//clock::delayS(1);
}
}
| 22.472973 | 39 | 0.51353 | ab2tech |
093ffc5d26e4d364be09dbf388eafa0f9b073ace | 3,367 | cpp | C++ | misc/make_oid_table/scanner.cpp | sttr00/crypto | ef290e4d1b93bb3a659d2d0cafec291ee50df0e8 | [
"BSD-2-Clause"
] | null | null | null | misc/make_oid_table/scanner.cpp | sttr00/crypto | ef290e4d1b93bb3a659d2d0cafec291ee50df0e8 | [
"BSD-2-Clause"
] | null | null | null | misc/make_oid_table/scanner.cpp | sttr00/crypto | ef290e4d1b93bb3a659d2d0cafec291ee50df0e8 | [
"BSD-2-Clause"
] | null | null | null | #include "scanner.h"
#include "oid_parser.h"
#include "asn1_lexer.h"
#include "asn1_keywords.h"
#include <platform/file.h>
#include <iostream>
#include <string.h>
#include <stdio.h>
using std::string;
using namespace asn1_tokens;
static void count_lines(int &line_number, const char *data, size_t &pos)
{
for (;;)
{
if (!pos) break;
const char *next = static_cast<const char*>(memchr(data, '\n', pos));
if (!next)
{
pos++; // position starts from 1
return;
}
next++;
size_t size = next - data;
pos -= size;
data += size;
line_number++;
}
}
static string print_oid(const oid_info &oid)
{
string result = "{";
for (oid_info::const_iterator it = oid.begin(); it != oid.end(); it++)
{
result += ' ';
if (!it->id.empty())
{
result += it->id;
result += '(';
}
char tmp[64];
int len = sprintf(tmp, "%u", it->number);
result.append(tmp, len);
if (!it->id.empty()) result += ')';
}
result += " }";
return result;
}
static string print_oid(named_oid_map::iterator it)
{
string result;
if (it->second.flags & oid_info_ex::FLAG_NO_EXPORT)
result += "-- no-export\n";
result += it->first;
result += " OBJECT IDENTIFIER ::= ";
result += print_oid(it->second.oid);
result += '\n';
return result;
}
bool scan_file(oid_parser &parser, const char *filename)
{
platform::file_t f = platform::open_file(filename);
if (f == platform::INVALID_FILE)
{
std::cerr << "Can't open input file '" << filename << "'\n";
return false;
}
char buf[4096];
asn1_lexer lexer;
token_list tl;
int line_number = 1;
bool process_definition = false;
for (;;)
{
int rd_size = platform::read_file(f, buf, sizeof(buf));
if (rd_size < 0)
{
std::cerr << "Error reading input file\n";
platform::close_file(f);
return false;
}
if (!rd_size)
{
platform::close_file(f);
break;
}
size_t size = rd_size;
size_t pos = 0;
while (pos < size)
{
size_t prev_pos = pos;
int result = lexer.process_buffer(buf, size, pos);
if (result == asn1_lexer::RESULT_ERROR)
{
count_lines(line_number, buf, pos);
std::cerr << "Error #" << lexer.get_error() << " at line " << line_number << " pos " << pos << '\n';
platform::close_file(f);
return false;
}
if (result == asn1_lexer::RESULT_TOKEN)
{
const string &token = lexer.get_token();
if (process_definition)
{
if (!parser.process_token(lexer.get_token_type(), token))
{
count_lines(line_number, buf, prev_pos);
std::cerr << "Invalid OID definition at line " << line_number << " pos " << prev_pos << '\n';
platform::close_file(f);
return false;
}
if (parser.is_finished())
{
parser.clear();
std::cout << print_oid(parser.get_inserted_element());
process_definition = false;
}
} else
if (token == "::=" &&
get_prev_token(tl, 0, NULL) == TOKEN_KW_IDENTIFIER &&
get_prev_token(tl, 1, NULL) == TOKEN_KW_OBJECT &&
get_prev_token(tl, 2, NULL) == TOKEN_IDENTIFIER)
{
remove_tokens(tl, 2);
if (!parser.start(tl))
{
std::cerr << "Internal error\n";
platform::close_file(f);
return false;
}
process_definition = true;
} else add_token(tl, lexer.get_token_type(), token);
lexer.clear_token();
}
}
count_lines(line_number, buf, size);
}
return true;
}
| 23.381944 | 104 | 0.608257 | sttr00 |
09449481da85643dca2b24f36b111fc35b91673b | 679 | hpp | C++ | libs/gfxtk_core/src/gfxtk/StorageTextureBindingLayout.hpp | NostalgicGhoul/gfxtk | 6662d6d1b285e20806ecfef3cdcb620d6605e478 | [
"BSD-2-Clause"
] | null | null | null | libs/gfxtk_core/src/gfxtk/StorageTextureBindingLayout.hpp | NostalgicGhoul/gfxtk | 6662d6d1b285e20806ecfef3cdcb620d6605e478 | [
"BSD-2-Clause"
] | null | null | null | libs/gfxtk_core/src/gfxtk/StorageTextureBindingLayout.hpp | NostalgicGhoul/gfxtk | 6662d6d1b285e20806ecfef3cdcb620d6605e478 | [
"BSD-2-Clause"
] | null | null | null | #ifndef GFXTK_STORAGETEXTUREBINDINGLAYOUT_HPP
#define GFXTK_STORAGETEXTUREBINDINGLAYOUT_HPP
#include "microsoft_fix.hpp"
#include "PixelFormat.hpp"
#include "TextureViewType.hpp"
namespace gfxtk {
enum class StorageTextureAccess {
WriteOnly,
};
struct GFXTK_EXPORT StorageTextureBindingLayout {
StorageTextureAccess access;
PixelFormat pixelFormat;
TextureViewType viewType;
StorageTextureBindingLayout(StorageTextureAccess access, PixelFormat pixelFormat, TextureViewType viewType)
: access(access), pixelFormat(pixelFormat), viewType(viewType) {}
};
}
#endif //GFXTK_STORAGETEXTUREBINDINGLAYOUT_HPP
| 27.16 | 115 | 0.755523 | NostalgicGhoul |
094733f8111f8d97bec015d59b4ec3e6f2e3faa6 | 735 | cpp | C++ | codeforces/31B.cpp | Shisir/Online-Judge | e58c32eeb7ca18a19cc2a83ef016f9c3b124370a | [
"MIT"
] | null | null | null | codeforces/31B.cpp | Shisir/Online-Judge | e58c32eeb7ca18a19cc2a83ef016f9c3b124370a | [
"MIT"
] | null | null | null | codeforces/31B.cpp | Shisir/Online-Judge | e58c32eeb7ca18a19cc2a83ef016f9c3b124370a | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
char ch[202];
int main()
{
vector<char>email;
scanf("%s",ch);
int l=strlen(ch),in=0;
bool f=true;
ch[l]='a';
for(int i=0; i<l; i++)email.push_back(ch[i]);
if(ch[0]=='@' || ch[l-1]=='@') return printf("No solution\n"),0;
for(int i=1; i<l; i++)
{
if(ch[i]=='@')
{
f=false;
if(ch[i+1]=='@' || ch[i+2]=='@' )return printf("No solution\n"),0;
}
}
if(f) return printf("No solution\n"),0;
for(int i=email.size()-1; i>-1; i--) if(email[i]=='@'){ in=i;break;}
for (int i = 0; i <in; ++i)
{
if(email[i]=='@') printf("@%c,",email[i+1]),i++;
else printf("%c",email[i]);
}
for(int i=in; i<email.size(); i++) printf("%c",email[i] );
printf("\n");
return 0;
}
| 21.617647 | 69 | 0.515646 | Shisir |
0948b5ebeb444e95e3315f504d80843de4723b39 | 19,081 | cpp | C++ | compiler/resolution/initializerResolution.cpp | krishnakeshav/chapel | c7840d76944cfb1b63878e51e81138d1a0c808cf | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | compiler/resolution/initializerResolution.cpp | krishnakeshav/chapel | c7840d76944cfb1b63878e51e81138d1a0c808cf | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | compiler/resolution/initializerResolution.cpp | krishnakeshav/chapel | c7840d76944cfb1b63878e51e81138d1a0c808cf | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright 2004-2017 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 "initializerResolution.h"
#include "astutil.h"
#include "caches.h"
#include "callInfo.h"
#include "expr.h"
#include "initializerRules.h"
#include "passes.h"
#include "resolution.h"
#include "stlUtil.h"
#include "stmt.h"
#include "stringutil.h"
#include "symbol.h"
#include "type.h"
#include "view.h"
#include "visibleCandidates.h"
#include "visibleFunctions.h"
static
void resolveInitializer(CallExpr* call);
static
void resolveInitCall(CallExpr* call);
static
void resolveMatch(FnSymbol* fn);
/* Stolen from function resolution */
static void
filterInitCandidate(Vec<ResolutionCandidate*>& candidates,
ResolutionCandidate* currCandidate,
CallInfo& info);
static void
filterInitCandidate(Vec<ResolutionCandidate*>& candidates,
FnSymbol* fn,
CallInfo& info);
static FnSymbol*
instantiateInitSig(FnSymbol* fn, SymbolMap& subs, CallExpr* call);
static bool isRefWrapperForNonGenericRecord(AggregateType* at);
// Rewrite of instantiateSignature, for initializers. Removed some bits,
// modified others.
/** Instantiate enough of the function for it to make it through the candidate
* filtering and disambiguation process.
*
* \param fn Generic function to instantiate
* \param subs Type substitutions to be made during instantiation
* \param call Call that is being resolved
*/
static FnSymbol*
instantiateInitSig(FnSymbol* fn, SymbolMap& subs, CallExpr* call) {
//
// Handle tuples explicitly
// (_build_tuple, tuple type constructor, tuple default constructor)
//
FnSymbol* tupleFn = createTupleSignature(fn, subs, call);
if (tupleFn) return tupleFn;
form_Map(SymbolMapElem, e, subs) {
if (TypeSymbol* ts = toTypeSymbol(e->value)) {
// This line is modified from instantiateSignature to allow the "this"
// arg to remain generic until we have finished resolving the generic
// portions of the initializer body's Phase 1.
if (ts->type->symbol->hasFlag(FLAG_GENERIC) &&
!e->key->hasFlag(FLAG_ARG_THIS))
INT_FATAL(fn, "illegal instantiation with a generic type");
TypeSymbol* nts = getNewSubType(fn, e->key, ts);
if (ts != nts)
e->value = nts;
}
}
//
// determine root function in the case of partial instantiation
//
FnSymbol* root = determineRootFunc(fn);
//
// determine all substitutions (past substitutions in a partial
// instantiation plus the current substitutions) and change the
// substitutions to refer to the root function's formal arguments
//
SymbolMap all_subs;
determineAllSubs(fn, root, subs, all_subs);
//
// use cached instantiation if possible
//
if (FnSymbol* cached = checkCache(genericsCache, root, &all_subs)) {
if (cached != (FnSymbol*)gVoid) {
checkInfiniteWhereInstantiation(cached);
return cached;
} else
return NULL;
}
SET_LINENO(fn);
//
// instantiate function
//
SymbolMap map;
FnSymbol* newFn = instantiateFunction(fn, root, all_subs, call, subs, map);
fixupTupleFunctions(fn, newFn, call);
if (newFn->numFormals() > 1 && newFn->getFormal(1)->type == dtMethodToken) {
newFn->getFormal(2)->type->methods.add(newFn);
}
newFn->tagIfGeneric();
if (newFn->hasFlag(FLAG_GENERIC) == false &&
evaluateWhereClause(newFn) == false) {
//
// where clause evaluates to false so cache gVoid as a function
//
replaceCache(genericsCache, root, (FnSymbol*)gVoid, &all_subs);
return NULL;
}
explainAndCheckInstantiation(newFn, fn);
return newFn;
}
/** Candidate filtering logic specific to concrete functions.
*
* \param candidates The list to add possible candidates to.
* \param currCandidate The current candidate to consider.
* \param info The CallInfo object for the call site.
*/
static void
filterInitConcreteCandidate(Vec<ResolutionCandidate*>& candidates,
ResolutionCandidate* currCandidate,
CallInfo& info) {
currCandidate->fn = expandIfVarArgs(currCandidate->fn, info);
if (!currCandidate->fn) return;
resolveTypedefedArgTypes(currCandidate->fn);
if (!currCandidate->computeAlignment(info)) {
return;
}
// We should reject this candidate if any of the situations handled by this
// function are violated.
if (checkResolveFormalsWhereClauses(currCandidate) == false)
return;
candidates.add(currCandidate);
}
/** Candidate filtering logic specific to generic functions.
*
* \param candidates The list to add possible candidates to.
* \param currCandidate The current candidate to consider.
* \param info The CallInfo object for the call site.
*/
static void
filterInitGenericCandidate(Vec<ResolutionCandidate*>& candidates,
ResolutionCandidate* currCandidate,
CallInfo& info) {
currCandidate->fn = expandIfVarArgs(currCandidate->fn, info);
if (!currCandidate->fn) return;
if (!currCandidate->computeAlignment(info)) {
return;
}
if (checkGenericFormals(currCandidate) == false)
return;
// Compute the param/type substitutions for generic arguments.
currCandidate->computeSubstitutions(true);
/*
* If no substitutions were made we can't instantiate this generic, and must
* reject it.
*/
if (currCandidate->substitutions.n > 0) {
/*
* Instantiate just enough of the generic to get through the rest of the
* filtering and disambiguation processes.
*/
currCandidate->fn = instantiateInitSig(currCandidate->fn, currCandidate->substitutions, info.call);
if (currCandidate->fn != NULL) {
filterInitCandidate(candidates, currCandidate, info);
}
}
}
/** Tests to see if a function is a candidate for resolving a specific call. If
* it is a candidate, we add it to the candidate lists.
*
* This version of filterInitCandidate is called by other versions of
* filterInitCandidate, and shouldn't be called outside this family of functions.
*
* \param candidates The list to add possible candidates to.
* \param currCandidate The current candidate to consider.
* \param info The CallInfo object for the call site.
*/
static void
filterInitCandidate(Vec<ResolutionCandidate*>& candidates,
ResolutionCandidate* currCandidate,
CallInfo& info) {
if (currCandidate->fn->hasFlag(FLAG_GENERIC)) {
filterInitGenericCandidate(candidates, currCandidate, info);
} else {
filterInitConcreteCandidate(candidates, currCandidate, info);
}
}
/** Tests to see if a function is a candidate for resolving a specific call. If
* it is a candidate, we add it to the candidate lists.
*
* This version of filterInitCandidate is called by code outside the filterInitCandidate
* family of functions.
*
* \param candidates The list to add possible candidates to.
* \param currCandidate The current candidate to consider.
* \param info The CallInfo object for the call site.
*/
static void
filterInitCandidate(Vec<ResolutionCandidate*>& candidates, FnSymbol* fn,
CallInfo& info) {
ResolutionCandidate* currCandidate = new ResolutionCandidate(fn);
filterInitCandidate(candidates, currCandidate, info);
if (candidates.tail() != currCandidate) {
// The candidate was not accepted. Time to clean it up.
delete currCandidate;
}
}
static void
doGatherInitCandidates(Vec<ResolutionCandidate*>& candidates,
Vec<FnSymbol*>& visibleFns,
CallInfo& info,
bool compilerGenerated) {
forv_Vec(FnSymbol, visibleFn, visibleFns) {
// Only consider user functions or compiler-generated functions
if (visibleFn->hasFlag(FLAG_COMPILER_GENERATED) == compilerGenerated) {
// Some expressions might resolve to methods without parenthesis.
// If the call is marked with methodTag, it indicates the called
// function should be a no-parens function or a type constructor.
// (a type constructor call without parens uses default arguments)
if (info.call->methodTag) {
if (visibleFn->hasEitherFlag(FLAG_NO_PARENS, FLAG_TYPE_CONSTRUCTOR)) {
// OK
} else {
// Skip this candidate
continue;
}
}
if (fExplainVerbose &&
((explainCallLine && explainCallMatch(info.call)) ||
info.call->id == explainCallID))
{
USR_PRINT(visibleFn, "Considering function: %s", toString(visibleFn));
if( info.call->id == breakOnResolveID ) {
gdbShouldBreakHere();
}
}
filterInitCandidate(candidates, visibleFn, info);
}
}
}
static void
gatherInitCandidates(Vec<ResolutionCandidate*>& candidates,
Vec<FnSymbol*>& visibleFns,
CallInfo& info) {
// Search user-defined (i.e. non-compiler-generated) functions first.
doGatherInitCandidates(candidates, visibleFns, info, false);
// If no results, try again with any compiler-generated candidates.
if (candidates.n == 0) {
doGatherInitCandidates(candidates, visibleFns, info, true);
}
}
/* end of function resolution steal */
void modAndResolveInitCall (CallExpr* call, AggregateType* typeToNew) {
// Convert the PRIM_NEW to a normal call
call->primitive = NULL;
call->baseExpr = call->get(1)->remove();
parent_insert_help(call, call->baseExpr);
VarSymbol* new_temp = newTemp("new_temp", typeToNew);
DefExpr* def = new DefExpr(new_temp);
if (isBlockStmt(call->parentExpr) == true) {
call->insertBefore(def);
} else {
call->parentExpr->insertBefore(def);
}
// Invoking an instance method
call->insertAtHead(new NamedExpr("this", new SymExpr(new_temp)));
call->insertAtHead(new SymExpr(gMethodToken));
resolveInitializer(call);
// Because initializers determine the type they utilize based on the
// execution of Phase 1, if the type is generic we will need to update the
// type of the actual we are sending in for the this arg
if (typeToNew->symbol->hasFlag(FLAG_GENERIC) == true) {
new_temp->type = call->isResolved()->_this->type;
if (isClass(typeToNew) == true) {
// use the allocator instead of directly calling the init method
// Need to convert the call into the right format
call->baseExpr->replace(new UnresolvedSymExpr("_new"));
call->get(1)->replace(new SymExpr(new_temp->type->symbol));
call->get(2)->remove();
// Need to resolve the allocator
resolveCall(call);
resolveFns(call->isResolved());
def->remove();
}
}
}
static
void resolveInitializer(CallExpr* call) {
// From resolveExpr() (removed the tryStack stuff)
callStack.add(call);
resolveInitCall(call);
INT_ASSERT(call->isResolved());
resolveMatch(call->isResolved());
callStack.pop();
}
static
void resolveInitCall(CallExpr* call) {
// From resolveNormalCall()
if( call->id == breakOnResolveID ) {
printf("breaking on resolve call:\n");
print_view(call);
gdbShouldBreakHere();
}
temporaryInitializerFixup(call);
resolveDefaultGenericType(call);
// Make a CallInfo which doesn't care if the this argument is
// generic, but otherwise should result in the same behavior.
CallInfo info(call, false, true);
Vec<FnSymbol*> visibleFns; // visible functions
findVisibleFunctions(info, visibleFns);
// Modified narrowing down the candidates to operate in an
// initializer-specific manner
Vec<ResolutionCandidate*> candidates;
gatherInitCandidates(candidates, visibleFns, info);
explainGatherCandidate(candidates, info, call);
// Removed a whole bunch of stuff that resolveNormalCall did that I didn't
// need, including ref/value pairs, some checkonly stuff, a match against
// the name being "=", and stuff related to modifying const fields that
// doesn't apply to initializers (which permit it in phase 1, but prevent it
// in phase 2)
Expr* scope = (info.scope) ? info.scope : getVisibilityBlock(call);
bool explain = fExplainVerbose &&
((explainCallLine && explainCallMatch(call)) ||
info.call->id == explainCallID);
DisambiguationContext DC(&info.actuals, scope, explain);
ResolutionCandidate* best = disambiguateByMatch(candidates, DC, FIND_NOT_REF_OR_CONST_REF);
if (best && best->fn) {
/*
* Finish instantiating the body. This is a noop if the function wasn't
* partially instantiated.
*/
instantiateBody(best->fn);
if (explainCallLine && explainCallMatch(call)) {
USR_PRINT(best->fn, "best candidate is: %s", toString(best->fn));
}
}
// Future work note: the repeated check to best and best->fn means that we
// could probably restructure this function to a better form.
if (call->partialTag && (!best || !best->fn ||
!best->fn->hasFlag(FLAG_NO_PARENS))) {
if (best != NULL) {
// MPF 2016-0106 - this appears to be dead code
// at least in a full single-locale test run.
// best is deleted below with the other candidates
best = NULL;
}
} else if (!best) {
if (candidates.n > 0) {
Vec<FnSymbol*> candidateFns;
forv_Vec(ResolutionCandidate*, candidate, candidates) {
candidateFns.add(candidate->fn);
}
printResolutionErrorAmbiguous(candidateFns, &info);
} else {
printResolutionErrorUnresolved(visibleFns, &info);
}
}
// removed the creation of wrappers and the lvalue check call, as resolving
// the _new call will handle all that stuff for us.
// NOTE: This is unlikely to work for generic records.
FnSymbol* resolvedFn = best != NULL ? best->fn : NULL;
forv_Vec(ResolutionCandidate*, candidate, candidates) {
delete candidate;
}
if (call->partialTag) {
if (!resolvedFn) {
return;
}
call->partialTag = false;
}
if (!resolvedFn) {
INT_FATAL(call, "unable to resolve call");
}
if (resolvedFn && call->parentSymbol) {
SET_LINENO(call);
call->baseExpr->replace(new SymExpr(resolvedFn));
}
checkForStoringIntoTuple(call, resolvedFn);
resolveNormalCallCompilerWarningStuff(resolvedFn);
}
// Copied from resolveFns(FnSymbol* fn) in functionResolution.
// Removed code for extern functions (since I don't think it will apply),
// iterators, type constructors, and FLAG_PRIVATIZED_CLASS.
void resolveMatch(FnSymbol* fn) {
if (fn->isResolved())
return;
if (fn->id == breakOnResolveID) {
printf("breaking on resolve fn:\n");
print_view(fn);
gdbShouldBreakHere();
}
fn->addFlag(FLAG_RESOLVED);
insertFormalTemps(fn);
bool wasGeneric = fn->_this->type->symbol->hasFlag(FLAG_GENERIC);
if (wasGeneric) {
AggregateType* at = toAggregateType(fn->_this->type);
INT_ASSERT(at);
bool res = at->setNextGenericField();
INT_ASSERT(res);
}
resolveBlockStmt(fn->body);
if (wasGeneric == true && isClass(fn->_this->type) == true) {
FnSymbol* classAlloc = buildClassAllocator(fn);
normalize(classAlloc);
}
if (tryFailure) {
fn->removeFlag(FLAG_RESOLVED);
return;
}
resolveReturnType(fn);
toAggregateType(fn->_this->type)->initializerResolved = true;
//
// insert casts as necessary
//
insertAndResolveCasts(fn);
//
// make sure methods are in the methods list
//
ensureInMethodList(fn);
}
void temporaryInitializerFixup(CallExpr* call) {
if (UnresolvedSymExpr* usym = toUnresolvedSymExpr(call->baseExpr)) {
// Support super.init() calls (for instance) when the super type does not
// define either an initializer or a constructor. Also ignores errors from
// improperly inserted .init() calls (so be sure to check here if something
// is behaving oddly - Lydia, 08/19/16)
if (strcmp(usym->unresolved, "init") == 0 &&
call->numActuals() >= 2 &&
!isNamedExpr(call->get(2))) {
// Arg 2 will be a NamedExpr to "this" if we're in an intentionally
// inserted initializer call
SymExpr* _mt = toSymExpr(call->get(1));
SymExpr* sym = toSymExpr(call->get(2));
INT_ASSERT(sym != NULL);
if (AggregateType* ct = toAggregateType(sym->symbol()->type)) {
if (isRefWrapperForNonGenericRecord(ct) == false &&
ct->initializerStyle == DEFINES_NONE_USE_DEFAULT) {
// This code should be removed when the compiler generates
// initializers as the default method of construction and
// initialization for a type (Lydia note, 08/19/16)
usym->unresolved = astr("_construct_", ct->symbol->name);
_mt->remove();
}
}
}
}
}
//
// Noakes 2017/03/26
// The function temporaryInitializerFixup is designed to update
// certain calls to init() while the initializer update matures.
//
// Unfortunately this transformation is triggered incorrectly for uses of
// this.init(...);
//
// inside initializers for non-generic records.
//
// For those uses of init() the "this" argument has currently has type
// _ref(<Record>) rather than <Record>
//
// This rather unfortunate function catches this case and enables the
// transformation to be skipped.
//
static bool isRefWrapperForNonGenericRecord(AggregateType* at) {
bool retval = false;
if (isClass(at) == true &&
strncmp(at->symbol->name, "_ref(", 5) == 0 &&
at->fields.length == 1) {
Symbol* sym = toDefExpr(at->fields.head)->sym;
if (strcmp(sym->name, "_val") == 0) {
retval = isNonGenericRecordWithInitializers(sym->type);
}
}
return retval;
}
void removeAggTypeFieldInfo() {
forv_Vec(AggregateType, at, gAggregateTypes) {
if (at->symbol->defPoint && at->symbol->defPoint->parentSymbol) {
// Still in the tree
if (at->initializerStyle == DEFINES_INITIALIZER) {
// Defined an initializer (so we left its init and exprType information
// in the tree)
for_fields(field, at) {
if (field->defPoint->exprType) {
field->defPoint->exprType->remove();
}
if (field->defPoint->init) {
field->defPoint->init->remove();
}
// Remove the init and exprType information.
}
}
}
}
}
| 29.628882 | 103 | 0.673445 | krishnakeshav |
094e3e3a23256ad05a6708ccd234469eae5dbeba | 7,954 | cxx | C++ | Modules/Learning/Supervised/test/otbLabelMapClassifier.cxx | lfyater/Orfeo | eb3d4d56089065b99641d8ae7338d2ed0358d28a | [
"Apache-2.0"
] | 2 | 2019-02-13T14:48:19.000Z | 2019-12-03T02:54:28.000Z | Modules/Learning/Supervised/test/otbLabelMapClassifier.cxx | lfyater/Orfeo | eb3d4d56089065b99641d8ae7338d2ed0358d28a | [
"Apache-2.0"
] | 3 | 2015-10-14T10:11:38.000Z | 2015-10-15T08:26:23.000Z | Modules/Learning/Supervised/test/otbLabelMapClassifier.cxx | CS-SI/OTB | 5926aca233ff8a0fb11af1a342a6f5539cd5e376 | [
"Apache-2.0"
] | 2 | 2015-10-08T12:04:06.000Z | 2018-06-19T08:00:47.000Z | /*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include <fstream>
#include <iostream>
#include "otbVectorImage.h"
#include "otbAttributesMapLabelObjectWithClassLabel.h"
#include "itkLabelImageToLabelMapFilter.h"
#include "otbShapeAttributesLabelMapFilter.h"
#include "otbBandsStatisticsAttributesLabelMapFilter.h"
#include "otbLabelMapWithClassLabelToLabeledSampleListFilter.h"
#include "otbLibSVMMachineLearningModel.h"
#include "otbLabelMapClassifier.h"
#include "otbLabelMapWithClassLabelToClassLabelImageFilter.h"
const unsigned int Dimension = 2;
typedef unsigned short LabelType;
typedef double DoublePixelType;
typedef otb::AttributesMapLabelObjectWithClassLabel<LabelType, Dimension, double, LabelType> LabelObjectType;
typedef itk::LabelMap<LabelObjectType> LabelMapType;
typedef otb::VectorImage<DoublePixelType, Dimension> VectorImageType;
typedef otb::Image<unsigned int, 2> LabeledImageType;
typedef otb::ImageFileReader<VectorImageType> ReaderType;
typedef otb::ImageFileReader<LabeledImageType> LabeledReaderType;
typedef otb::ImageFileWriter<VectorImageType> WriterType;
typedef otb::ImageFileWriter<LabeledImageType> LabeledWriterType;
typedef itk::LabelImageToLabelMapFilter<LabeledImageType, LabelMapType> LabelMapFilterType;
typedef otb::ShapeAttributesLabelMapFilter<LabelMapType> ShapeFilterType;
typedef otb::BandsStatisticsAttributesLabelMapFilter<LabelMapType, VectorImageType> BandsStatisticsFilterType;
// SVM model estimation
typedef itk::VariableLengthVector<double> VectorType;
typedef itk::FixedArray<LabelType, 1> TrainingVectorType;
typedef itk::Statistics::ListSample<VectorType> ListSampleType;
typedef itk::Statistics::ListSample<TrainingVectorType> TrainingListSampleType;
typedef otb::LabelMapWithClassLabelToLabeledSampleListFilter<LabelMapType, ListSampleType, TrainingListSampleType>
ListSampleFilterType;
typedef otb::LibSVMMachineLearningModel<double,LabelType> SVMType;
typedef otb::LabelMapClassifier<LabelMapType> ClassifierType;
typedef otb::LabelMapWithClassLabelToClassLabelImageFilter
<LabelMapType, LabeledImageType> ClassifImageGeneratorType;
LabelObjectType::Pointer makeTrainingSample(LabelMapType* labelMap, LabelType labelObjectId, LabelType classLabel)
{
LabelObjectType::Pointer newLabelObject = LabelObjectType::New();
newLabelObject->CopyAllFrom( labelMap->GetLabelObject(labelObjectId) );
newLabelObject->SetClassLabel(classLabel);
return newLabelObject;
}
int otbLabelMapClassifierNew(int itkNotUsed(argc), char * itkNotUsed(argv)[])
{
ClassifierType::Pointer classifier = ClassifierType::New();
return EXIT_SUCCESS;
}
int otbLabelMapClassifier(int itkNotUsed(argc), char * argv[])
{
const char * infname = argv[1];
const char * lfname = argv[2];
const char * outfname = argv[3];
// Filters instantiation
ReaderType::Pointer reader = ReaderType::New();
LabeledReaderType::Pointer labeledReader = LabeledReaderType::New();
LabelMapFilterType::Pointer filter = LabelMapFilterType::New();
ShapeFilterType::Pointer shapeFilter = ShapeFilterType::New();
BandsStatisticsFilterType::Pointer radiometricFilter = BandsStatisticsFilterType::New();
LabelMapType::Pointer trainingLabelMap = LabelMapType::New();
ListSampleFilterType::Pointer labelMap2SampleList = ListSampleFilterType::New();
SVMType::Pointer model = SVMType::New();
ClassifierType::Pointer classifier = ClassifierType::New();
ClassifImageGeneratorType::Pointer imGenerator = ClassifImageGeneratorType::New();
LabeledWriterType::Pointer writer = LabeledWriterType::New();
// Read inputs
reader->SetFileName(infname);
labeledReader->SetFileName(lfname);
// Make a LabelMap out of it
filter->SetInput(labeledReader->GetOutput());
filter->SetBackgroundValue(itk::NumericTraits<LabelType>::max());
//Compute shape and radimometric attributes
shapeFilter->SetInput(filter->GetOutput());
radiometricFilter->SetInput(shapeFilter->GetOutput());
radiometricFilter->SetFeatureImage(reader->GetOutput());
radiometricFilter->Update();
// Build a sub-LabelMap with class-labeled LabelObject
LabelMapType::Pointer labelMap = radiometricFilter->GetOutput();
// The following is very specific to the input specified in CMakeLists
// water
trainingLabelMap->PushLabelObject(makeTrainingSample(labelMap, 13, 0));
// road
trainingLabelMap->PushLabelObject(makeTrainingSample(labelMap, 88, 1));
trainingLabelMap->PushLabelObject(makeTrainingSample(labelMap, 114, 1));
trainingLabelMap->PushLabelObject(makeTrainingSample(labelMap, 144, 1));
// boat
trainingLabelMap->PushLabelObject(makeTrainingSample(labelMap, 52, 2));
trainingLabelMap->PushLabelObject(makeTrainingSample(labelMap, 31, 2));
trainingLabelMap->PushLabelObject(makeTrainingSample(labelMap, 11, 2));
// roof
trainingLabelMap->PushLabelObject(makeTrainingSample(labelMap, 58, 3));
trainingLabelMap->PushLabelObject(makeTrainingSample(labelMap, 60, 3));
trainingLabelMap->PushLabelObject(makeTrainingSample(labelMap, 27, 3));
trainingLabelMap->PushLabelObject(makeTrainingSample(labelMap, 81, 3));
// vegetation
trainingLabelMap->PushLabelObject(makeTrainingSample(labelMap, 161, 4));
trainingLabelMap->PushLabelObject(makeTrainingSample(labelMap, 46, 4));
// Make a ListSample out of trainingLabelMap
labelMap2SampleList->SetInputLabelMap(trainingLabelMap);
std::vector<std::string> attributes = labelMap->GetLabelObject(0)->GetAvailableAttributes();
std::vector<std::string>::const_iterator attrIt;
for (attrIt = attributes.begin(); attrIt != attributes.end(); ++attrIt)
{
labelMap2SampleList->GetMeasurementFunctor().AddAttribute((*attrIt).c_str());
}
labelMap2SampleList->Update();
// Estimate SVM model
model->SetInputListSample(const_cast<SVMType::InputListSampleType*>(labelMap2SampleList->GetOutputSampleList()));
model->SetTargetListSample(const_cast<SVMType::TargetListSampleType*>(labelMap2SampleList->GetOutputTrainingSampleList()));
model->Train();
// Classify using the whole LabelMap with estimated model
classifier->SetInput(labelMap);
classifier->SetModel(model);
for (attrIt = attributes.begin(); attrIt != attributes.end(); ++attrIt)
{
classifier->GetMeasurementFunctor().AddAttribute((*attrIt).c_str());
}
classifier->Update();
// Make a labeled image with the classification result
imGenerator->SetInput(classifier->GetOutput());
writer->SetInput(imGenerator->GetOutput());
writer->SetFileName(outfname);
writer->Update();
return EXIT_SUCCESS;
}
| 44.937853 | 125 | 0.722404 | lfyater |
094f60fb317a6c1fae312a99f13cc61acb2eb35c | 171 | cpp | C++ | atcoder.jp/abc129/abc129_a/Main.cpp | shikij1/AtCoder | 7ae2946efdceaea3cc8725e99a2b9c137598e2f8 | [
"MIT"
] | null | null | null | atcoder.jp/abc129/abc129_a/Main.cpp | shikij1/AtCoder | 7ae2946efdceaea3cc8725e99a2b9c137598e2f8 | [
"MIT"
] | null | null | null | atcoder.jp/abc129/abc129_a/Main.cpp | shikij1/AtCoder | 7ae2946efdceaea3cc8725e99a2b9c137598e2f8 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main()
{
int p, q, r;
cin >> p >> q >> r;
cout << min({p + q, r + q, p + r, q + r, r + p, q + p}) << endl;
}
| 19 | 68 | 0.438596 | shikij1 |
09504c994d1eb27fcb53af4eb6dc5df9737f03a1 | 9,943 | hpp | C++ | esl/economics/markets/quote.hpp | rht/ESL | f883155a167d3c48e5ecdca91c8302fefc901c22 | [
"Apache-2.0"
] | null | null | null | esl/economics/markets/quote.hpp | rht/ESL | f883155a167d3c48e5ecdca91c8302fefc901c22 | [
"Apache-2.0"
] | null | null | null | esl/economics/markets/quote.hpp | rht/ESL | f883155a167d3c48e5ecdca91c8302fefc901c22 | [
"Apache-2.0"
] | 1 | 2021-01-27T12:11:48.000Z | 2021-01-27T12:11:48.000Z | /// \file walras.hpp
///
/// \brief A quote is the variable along which trade negotation takes place
///
/// \authors Maarten P. Scholl
/// \date 2019-04-04
/// \copyright Copyright 2017-2019 The Institute for New Economic Thinking,
/// Oxford Martin School, University of Oxford
///
/// 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.
///
/// You may obtain instructions to fulfill the attribution
/// requirements in CITATION.cff
///
#ifndef ESL_QUOTE_HPP
#define ESL_QUOTE_HPP
#include <variant>
#include <utility>
#include <type_traits>
#include <esl/economics/exchange_rate.hpp>
#include <esl/economics/price.hpp>
#include <esl/exception.hpp>
namespace esl::economics::markets {
///
/// \brief A quote is a numerical value around which the market is
/// organised. Most commonly, this is a monetary value
/// (a price), but different markets may use different types of
/// quotes such as interest rates in a mortgage market, or a ratio
/// (exchange rate) when bartering.
///
///
struct quote
{
private:
constexpr void assert_equal_type_(const quote& other) const
{
if(type.index() != other.type.index()){
throw esl::exception("comparing quotes of different types");
}
}
public:
std::variant<exchange_rate, price> type;
uint64_t lot;
explicit quote(const exchange_rate &er = exchange_rate(),
uint64_t lot = 1)
: type(er)
, lot(lot)
{
if(0 >= lot){
throw esl::exception("lot size must be strictly positive");
}
}
///
/// \param p
/// \param lot
explicit quote(const price &p, uint64_t lot = 1)
: type(p)
, lot(lot )
{
if(0 >= lot){
throw esl::exception("lot size must be strictly positive");
}
}
explicit quote(double f, const quote &similar)
{
*this = std::visit([&] (const auto& k) {
using variant_ = std::decay_t<decltype(k)>;
return quote(variant_(f, k), similar.lot);
}, similar.type);
}
quote(const quote &q)
: type(q.type)
, lot(q.lot)
{
if(0 >= lot){
throw esl::exception("lot size must be strictly positive");
}
}
///
/// \brief When converting to floating point, we divide by the lot size
/// so that we get the quote per unit of goods.
///
/// \tparam floating_point_t_
/// \return
template<typename floating_point_t_>
explicit operator floating_point_t_() const
{
return std::visit(
[this](auto &&arg) { return floating_point_t_(arg) / lot; },
type);
}
///
/// \param o
/// \return
quote &operator = (const quote &o) = default;
///
/// \param other
/// \return
[[nodiscard]] constexpr bool operator == (const quote &other) const
{
assert_equal_type_(other);
return std::visit([&] (const auto& k) {
using variant_ = std::decay_t<decltype(k)>;
if(auto *vp = std::get_if<variant_>(&other.type) ){
return (lot * k) == ( (*vp) * other.lot );
}
throw esl::exception("quote variants do not match");
}, type);
}
[[nodiscard]] constexpr bool operator != (const quote &other) const
{
assert_equal_type_(other);
return std::visit([&] (const auto& k) {
using variant_ = std::decay_t<decltype(k)>;
if(auto *vp = std::get_if<variant_>(&other.type) ){
return (lot * k) != ((*vp) * other.lot );
}
throw esl::exception("quote variants do not match");
}, type);
}
[[nodiscard]] constexpr bool operator < (const quote &other) const
{
assert_equal_type_(other);
return std::visit([&] (const auto& k) {
using variant_ = std::decay_t<decltype(k)>;
//return (lot * k) < (std::get<variant_>(other.type) * other.lot );
if(auto *vp = std::get_if<variant_>(&other.type) ){
return (lot * k) < ((*vp) * other.lot );
}
throw esl::exception("quote variants do not match");
}, type);
}
[[nodiscard]] constexpr bool operator > (const quote &other) const
{
assert_equal_type_(other);
return std::visit([&] (const auto& k) {
using variant_ = std::decay_t<decltype(k)>;
//return (lot * k) > (std::get<variant_>(other.type) * other.lot );
if(auto *vp = std::get_if<variant_>(&other.type) ){
return (lot * k) > ((*vp) * other.lot );
}
throw esl::exception("quote variants do not match");
}, type);
}
[[nodiscard]] constexpr bool operator <= (const quote &other) const
{
assert_equal_type_(other);
return std::visit([&] (const auto& k) {
using variant_ = std::decay_t<decltype(k)>;
//return (lot * k) <= (std::get<variant_>(other.type) * other.lot );
if(auto *vp = std::get_if<variant_>(&other.type) ){
return (lot * k) <= ((*vp) * other.lot );
}
throw esl::exception("quote variants do not match");
}, type);
}
[[nodiscard]] constexpr bool operator >= (const quote &other) const
{
assert_equal_type_(other);
return std::visit([&] (const auto& k) {
using variant_ = std::decay_t<decltype(k)>;
//return (lot * k) >= (std::get<variant_>(other.type) * other.lot );
if(auto *vp = std::get_if<variant_>(&other.type) ){
return (lot * k) >= ((*vp) * other.lot );
}
throw esl::exception("quote variants do not match");
}, type);
}
template<class archive_t>
void save(archive_t &archive, const unsigned int version) const
{
(void)version;
archive << BOOST_SERIALIZATION_NVP(lot);
size_t index_ = type.index();
archive &BOOST_SERIALIZATION_NVP(index_);
switch(index_) {
case 0:
if(auto *vp = std::get_if<exchange_rate>(&type) ){
archive << boost::serialization::make_nvp(
"exchange_rate", (vp));
break;
}
case 1:
if(auto *vp = std::get_if<price>(&type) ){
archive << boost::serialization::make_nvp(
"price", *vp);
break;
}
default:
throw esl::exception("variant quote not supported");
}
}
template<class archive_t>
void load(archive_t &archive, const unsigned int version)
{
(void)version;
archive >> BOOST_SERIALIZATION_NVP(lot);
size_t index_ = 0;
archive >> BOOST_SERIALIZATION_NVP(index_);
if(0 == index_) {
exchange_rate re;
archive >> boost::serialization::make_nvp("exchange_rate", re);
type.emplace<0>(re);
} else if(1 == index_) {
price p;
archive >> boost::serialization::make_nvp("price", p);
type.emplace<1>(p);
}
}
template<class archive_t>
void serialize(archive_t &archive, const unsigned int version)
{
boost::serialization::split_member(archive, *this, version);
}
// std::ostream &operator << (std::ostream &stream) const
// {
// stream << lot << '@';
// std::visit([&](const auto &elem)
// {
// stream << elem;
// },
// type);
// return stream;
// }
friend std::ostream &operator << (std::ostream &stream, const quote &q)
{
stream << q.lot << '@';
std::visit([&](const auto &elem)
{
stream << elem;
},
q.type);
return stream;
}
};
} // namespace esl::economics
#ifdef WITH_MPI
#include <boost/mpi.hpp>
namespace boost { namespace mpi {
template<>
struct is_mpi_datatype<esl::economics::markets::quote>
: public boost::mpl::true_//is_mpi_datatype<std::variant<esl::economics::exchange_rate
// , esl::economics::price>>::value
{
};
}} // namespace boost::mpi
#endif // WITH_MPI
#endif // ESL_QUOTE_HPP
| 32.923841 | 90 | 0.491703 | rht |
0950cf3e3a138040f24e35e74e06a7b9bf67d4ff | 13,609 | cpp | C++ | src/kits/tracker/TaskLoop.cpp | stasinek/BHAPI | 5d9aa61665ae2cc5c6e34415957d49a769325b2b | [
"BSD-3-Clause",
"MIT"
] | 3 | 2018-05-21T15:32:32.000Z | 2019-03-21T13:34:55.000Z | src/kits/tracker/TaskLoop.cpp | stasinek/BHAPI | 5d9aa61665ae2cc5c6e34415957d49a769325b2b | [
"BSD-3-Clause",
"MIT"
] | null | null | null | src/kits/tracker/TaskLoop.cpp | stasinek/BHAPI | 5d9aa61665ae2cc5c6e34415957d49a769325b2b | [
"BSD-3-Clause",
"MIT"
] | null | null | null | /*
Open Tracker License
Terms and Conditions
Copyright (c) 1991-2000, Be Incorporated. All rights reserved.
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 applies to all licensees
and 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 TITLE, MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
BE INCORPORATED 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.
Except as contained in this notice, the name of Be Incorporated shall not be
used in advertising or otherwise to promote the sale, use or other dealings in
this Software without prior written authorization from Be Incorporated.
Tracker(TM), Be(R), BeOS(R), and BeIA(TM) are trademarks or registered trademarks
of Be Incorporated in the United States and other countries. Other brand product
names are registered trademarks or trademarks of their respective holders.
All rights reserved.
*/
#include <kits/debug/Debug.h>
#include <InterfaceDefs.h>
#include <AutoLock.h>
#include <TaskLoop.h>
const float kTaskOverhead = 0.01f;
// this should really be specified by the task itself
const float kIdleTreshold = 0.15f;
const bigtime_t kInfinity = B_INFINITE_TIMEOUT;
static bigtime_t
ActivityLevel()
{
// stolen from roster server
bigtime_t time = 0;
system_info sinfo;
get_system_info(&sinfo);
cpu_info* cpuInfos = new cpu_info[sinfo.cpu_count];
get_cpu_info(0, sinfo.cpu_count, cpuInfos);
for (uint32 index = 0; index < sinfo.cpu_count; index++)
time += cpuInfos[index].active_time;
delete[] cpuInfos;
return time / ((bigtime_t) sinfo.cpu_count);
}
class AccumulatedOneShotDelayedTask : public OneShotDelayedTask {
// supports accumulating functors
public:
AccumulatedOneShotDelayedTask(AccumulatingFunctionObject* functor,
bigtime_t delay, bigtime_t maxAccumulatingTime = 0,
int32 maxAccumulateCount = 0)
:
OneShotDelayedTask(functor, delay),
maxAccumulateCount(maxAccumulateCount),
accumulateCount(1),
maxAccumulatingTime(maxAccumulatingTime),
initialTime(system_time())
{
}
bool CanAccumulate(const AccumulatingFunctionObject* accumulateThis) const
{
if (maxAccumulateCount && accumulateCount > maxAccumulateCount)
// don't accumulate if too may accumulated already
return false;
if (maxAccumulatingTime && system_time() > initialTime
+ maxAccumulatingTime) {
// don't accumulate if too late past initial task
return false;
}
return static_cast<AccumulatingFunctionObject*>(fFunctor)->
CanAccumulate(accumulateThis);
}
virtual void Accumulate(AccumulatingFunctionObject* accumulateThis,
bigtime_t delay)
{
fRunAfter = system_time() + delay;
// reset fRunAfter
accumulateCount++;
static_cast<AccumulatingFunctionObject*>(fFunctor)->
Accumulate(accumulateThis);
}
private:
int32 maxAccumulateCount;
int32 accumulateCount;
bigtime_t maxAccumulatingTime;
bigtime_t initialTime;
};
// #pragma mark - DelayedTask
DelayedTask::DelayedTask(bigtime_t delay)
:
fRunAfter(system_time() + delay)
{
}
DelayedTask::~DelayedTask()
{
}
// #pragma mark - OneShotDelayedTask
OneShotDelayedTask::OneShotDelayedTask(FunctionObject* functor,
bigtime_t delay)
:
DelayedTask(delay),
fFunctor(functor)
{
}
OneShotDelayedTask::~OneShotDelayedTask()
{
delete fFunctor;
}
bool OneShotDelayedTask::RunIfNeeded(bigtime_t currentTime)
{
if (currentTime < fRunAfter)
return false;
(*fFunctor)();
return true;
}
// #pragma mark - PeriodicDelayedTask
PeriodicDelayedTask::PeriodicDelayedTask(
FunctionObjectWithResult<bool>* functor, bigtime_t initialDelay,
bigtime_t period)
:
DelayedTask(initialDelay),
fPeriod(period),
fFunctor(functor)
{
}
PeriodicDelayedTask::~PeriodicDelayedTask()
{
delete fFunctor;
}
bool PeriodicDelayedTask::RunIfNeeded(bigtime_t currentTime)
{
if (currentTime < fRunAfter)
return false;
fRunAfter = currentTime + fPeriod;
(*fFunctor)();
return fFunctor->Result();
}
PeriodicDelayedTaskWithTimeout::PeriodicDelayedTaskWithTimeout(
FunctionObjectWithResult<bool>* functor, bigtime_t initialDelay,
bigtime_t period, bigtime_t timeout)
:
PeriodicDelayedTask(functor, initialDelay, period),
fTimeoutAfter(system_time() + timeout)
{
}
bool PeriodicDelayedTaskWithTimeout::RunIfNeeded(bigtime_t currentTime)
{
if (currentTime < fRunAfter)
return false;
fRunAfter = currentTime + fPeriod;
(*fFunctor)();
if (fFunctor->Result())
return true;
// if call didn't terminate the task yet, check if timeout is due
return currentTime > fTimeoutAfter;
}
// #pragma mark - RunWhenIdleTask
RunWhenIdleTask::RunWhenIdleTask(FunctionObjectWithResult<bool>* functor,
bigtime_t initialDelay, bigtime_t idleFor, bigtime_t heartBeat)
:
PeriodicDelayedTask(functor, initialDelay, heartBeat),
fIdleFor(idleFor),
fState(kInitialDelay),
fActivityLevelStart(0),
fActivityLevel(0),
fLastCPUTooBusyTime(0)
{
}
RunWhenIdleTask::~RunWhenIdleTask()
{
}
bool RunWhenIdleTask::RunIfNeeded(bigtime_t currentTime)
{
if (currentTime < fRunAfter)
return false;
fRunAfter = currentTime + fPeriod;
// PRINT(("runWhenIdle: runAfter %Ld, current time %Ld, period %Ld\n",
// fRunAfter, currentTime, fPeriod));
if (fState == kInitialDelay) {
// PRINT(("run when idle task - past intial delay\n"));
ResetIdleTimer(currentTime);
} else if (fState == kInIdleState && !StillIdle(currentTime)) {
fState = kInitialIdleWait;
ResetIdleTimer(currentTime);
} else if (fState != kInitialIdleWait || IdleTimerExpired(currentTime)) {
fState = kInIdleState;
(*fFunctor)();
return fFunctor->Result();
}
return false;
}
void RunWhenIdleTask::ResetIdleTimer(bigtime_t currentTime)
{
fActivityLevel = ActivityLevel();
fActivityLevelStart = currentTime;
fLastCPUTooBusyTime = currentTime;
fState = kInitialIdleWait;
}
bool RunWhenIdleTask::IsIdle(bigtime_t currentTime, float taskOverhead)
{
bigtime_t currentActivityLevel = ActivityLevel();
float load = (float)(currentActivityLevel - fActivityLevel)
/ (float)(currentTime - fActivityLevelStart);
fActivityLevel = currentActivityLevel;
fActivityLevelStart = currentTime;
load -= taskOverhead;
bool idle = true;
if (load > kIdleTreshold) {
// PRINT(("not idle enough %f\n", load));
idle = false;
} else if ((currentTime - fLastCPUTooBusyTime) < fIdleFor
|| idle_time() < fIdleFor) {
// PRINT(("load %f, not idle long enough %Ld, %Ld\n", load,
// currentTime - fLastCPUTooBusyTime,
// idle_time()));
idle = false;
}
#if xDEBUG
else
PRINT(("load %f, idle for %Ld sec, go\n", load,
(currentTime - fLastCPUTooBusyTime) / 1000000));
#endif
return idle;
}
bool RunWhenIdleTask::IdleTimerExpired(bigtime_t currentTime)
{
return IsIdle(currentTime, 0);
}
bool RunWhenIdleTask::StillIdle(bigtime_t currentTime)
{
return IsIdle(currentTime, kIdleTreshold);
}
// #pragma mark - TaskLoop
TaskLoop::TaskLoop(bigtime_t heartBeat)
:
fTaskList(10, true),
fHeartBeat(heartBeat)
{
}
TaskLoop::~TaskLoop()
{
}
void TaskLoop::RunLater(DelayedTask* task)
{
AddTask(task);
}
void TaskLoop::RunLater(FunctionObject* functor, bigtime_t delay)
{
RunLater(new OneShotDelayedTask(functor, delay));
}
void TaskLoop::RunLater(FunctionObjectWithResult<bool>* functor,
bigtime_t delay, bigtime_t period)
{
RunLater(new PeriodicDelayedTask(functor, delay, period));
}
void TaskLoop::RunLater(FunctionObjectWithResult<bool>* functor, bigtime_t delay,
bigtime_t period, bigtime_t timeout)
{
RunLater(new PeriodicDelayedTaskWithTimeout(functor, delay, period,
timeout));
}
void TaskLoop::RunWhenIdle(FunctionObjectWithResult<bool>* functor,
bigtime_t initialDelay, bigtime_t idleTime, bigtime_t heartBeat)
{
RunLater(new RunWhenIdleTask(functor, initialDelay, idleTime, heartBeat));
}
// #pragma mark - TaskLoop
void TaskLoop::AccumulatedRunLater(AccumulatingFunctionObject* functor,
bigtime_t delay, bigtime_t maxAccumulatingTime, int32 maxAccumulateCount)
{
AutoLock<BLocker> autoLock(&fLock);
if (!autoLock.IsLocked())
return;
int32 count = fTaskList.CountItems();
for (int32 index = 0; index < count; index++) {
AccumulatedOneShotDelayedTask* task
= dynamic_cast<AccumulatedOneShotDelayedTask*>(
fTaskList.ItemAt(index));
if (task == NULL)
continue;
else if (task->CanAccumulate(functor)) {
task->Accumulate(functor, delay);
return;
}
}
RunLater(new AccumulatedOneShotDelayedTask(functor, delay,
maxAccumulatingTime, maxAccumulateCount));
}
bool TaskLoop::Pulse()
{
ASSERT(fLock.IsLocked());
int32 count = fTaskList.CountItems();
if (count > 0) {
bigtime_t currentTime = system_time();
for (int32 index = 0; index < count; ) {
DelayedTask* task = fTaskList.ItemAt(index);
// give every task a try
if (task->RunIfNeeded(currentTime)) {
// if done, remove from list
RemoveTask(task);
count--;
} else
index++;
}
}
return count == 0 && !KeepPulsingWhenEmpty();
}
bigtime_t
TaskLoop::LatestRunTime() const
{
ASSERT(fLock.IsLocked());
bigtime_t result = kInfinity;
#if xDEBUG
DelayedTask* nextTask = 0;
#endif
int32 count = fTaskList.CountItems();
for (int32 index = 0; index < count; index++) {
bigtime_t runAfter = fTaskList.ItemAt(index)->RunAfterTime();
if (runAfter < result) {
result = runAfter;
#if xDEBUG
nextTask = fTaskList.ItemAt(index);
#endif
}
}
#if xDEBUG
if (nextTask)
PRINT(("latestRunTime : next task %s\n", typeid(*nextTask).name));
else
PRINT(("latestRunTime : no next task\n"));
#endif
return result;
}
void TaskLoop::RemoveTask(DelayedTask* task)
{
ASSERT(fLock.IsLocked());
// remove the task
fTaskList.RemoveItem(task);
}
void TaskLoop::AddTask(DelayedTask* task)
{
AutoLock<BLocker> autoLock(&fLock);
if (!autoLock.IsLocked()) {
delete task;
return;
}
fTaskList.AddItem(task);
StartPulsingIfNeeded();
}
// #pragma mark - StandAloneTaskLoop
StandAloneTaskLoop::StandAloneTaskLoop(bool keepThread, bigtime_t heartBeat)
:
TaskLoop(heartBeat),
fNeedToQuit(false),
fScanThread(-1),
fKeepThread(keepThread)
{
}
StandAloneTaskLoop::~StandAloneTaskLoop()
{
fLock.Lock();
fNeedToQuit = true;
bool easyOut = (fScanThread == -1);
fLock.Unlock();
if (!easyOut)
for (int32 timeout = 10000; ; timeout--) {
// use a 10 sec timeout value in case the spawned
// thread is stuck somewhere
if (!timeout) {
PRINT(("StandAloneTaskLoop timed out, quitting abruptly"));
break;
}
bool done;
fLock.Lock();
done = (fScanThread == -1);
fLock.Unlock();
if (done)
break;
snooze(1000);
}
}
void StandAloneTaskLoop::StartPulsingIfNeeded()
{
ASSERT(fLock.IsLocked());
if (fScanThread < 0) {
// no loop thread yet, spawn one
fScanThread = spawn_thread(StandAloneTaskLoop::RunBinder,
"TrackerTaskLoop", B_LOW_PRIORITY, this);
resume_thread(fScanThread);
}
}
bool StandAloneTaskLoop::KeepPulsingWhenEmpty() const
{
return fKeepThread;
}
status_t StandAloneTaskLoop::RunBinder(void* castToThis)
{
StandAloneTaskLoop* self = (StandAloneTaskLoop*)castToThis;
self->Run();
return B_OK;
}
void StandAloneTaskLoop::Run()
{
for(;;) {
AutoLock<BLocker> autoLock(&fLock);
if (!autoLock)
return;
if (fNeedToQuit) {
// task loop being deleted, let go of the thread allowing the
// to go through deletion
fScanThread = -1;
return;
}
if (Pulse()) {
fScanThread = -1;
return;
}
// figure out when to run next by checking out when the different
// tasks wan't to be woken up, snooze until a little bit before that
// time
bigtime_t now = system_time();
bigtime_t latestRunTime = LatestRunTime() - 1000;
bigtime_t afterHeartBeatTime = now + fHeartBeat;
bigtime_t snoozeTill = latestRunTime < afterHeartBeatTime ?
latestRunTime : afterHeartBeatTime;
autoLock.Unlock();
if (snoozeTill > now)
snooze_until(snoozeTill, B_SYSTEM_TIMEBASE);
else
snooze(1000);
}
}
void StandAloneTaskLoop::AddTask(DelayedTask* delayedTask)
{
_inherited::AddTask(delayedTask);
if (fScanThread < 0)
return;
// wake up the loop thread if it is asleep
thread_info info;
get_thread_info(fScanThread, &info);
if (info.state == B_THREAD_ASLEEP) {
suspend_thread(fScanThread);
snooze(1000); // snooze because BeBook sez so
resume_thread(fScanThread);
}
}
// #pragma mark - PiggybackTaskLoop
PiggybackTaskLoop::PiggybackTaskLoop(bigtime_t heartBeat)
:
TaskLoop(heartBeat),
fNextHeartBeatTime(0),
fPulseMe(false)
{
}
PiggybackTaskLoop::~PiggybackTaskLoop()
{
}
void PiggybackTaskLoop::PulseMe()
{
if (!fPulseMe)
return;
bigtime_t time = system_time();
if (fNextHeartBeatTime < time) {
AutoLock<BLocker> autoLock(&fLock);
if (Pulse())
fPulseMe = false;
fNextHeartBeatTime = time + fHeartBeat;
}
}
bool PiggybackTaskLoop::KeepPulsingWhenEmpty() const
{
return false;
}
void PiggybackTaskLoop::StartPulsingIfNeeded()
{
fPulseMe = true;
}
| 21.397799 | 81 | 0.739364 | stasinek |
0950e4dae1fbde08a13c1853c1c1de614d0aedc6 | 5,186 | cc | C++ | bubblesmp/rrtplan.cc | adnanademovic/bubbles-motion-planning | 0532e557913053f57e859f7b5aa7b8d4467fac09 | [
"BSD-2-Clause"
] | null | null | null | bubblesmp/rrtplan.cc | adnanademovic/bubbles-motion-planning | 0532e557913053f57e859f7b5aa7b8d4467fac09 | [
"BSD-2-Clause"
] | null | null | null | bubblesmp/rrtplan.cc | adnanademovic/bubbles-motion-planning | 0532e557913053f57e859f7b5aa7b8d4467fac09 | [
"BSD-2-Clause"
] | null | null | null | //
// Copyright (c) 2015, Adnan Ademovic
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#include <chrono>
#include <cstdio>
#include <string>
#include <queue>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <google/protobuf/stubs/common.h>
#include "bubblesmp/rrt.h"
#include "bubblesmp/tree-node.h"
DEFINE_bool(verbose, false, "Print verification progress information");
DEFINE_string(output_type, "",
"Set the information that should be returned in the output ("
"path - array of configurations, "
"times - duration of each step in microseconds, "
"progress - progress information for the current case to stderr, "
"an empty string results in no output"
")");
namespace {
static bool ValidateOutputType(const char* flagname, const std::string& value) {
if (value != "path" && value != "times" && value != "progress"
&& value != "") {
printf("Invalid value for --%s: %s\nOptions are: \"\", path, times\n",
flagname, value.c_str());
return false;
}
return true;
}
static const bool simulation_case_dummy = google::RegisterFlagValidator(
&FLAGS_output_type, &ValidateOutputType);
} // namespace
using namespace com::ademovic::bubblesmp;
void OutputPath(std::vector<std::shared_ptr<TreePoint> > points) {
for (const std::shared_ptr<TreePoint> q : points) {
for (double qi : q->position())
printf(" %lf", qi);
printf("\n");
}
}
void OutputTimes(const std::vector<long int>& times) {
for (long int t : times)
printf("%ld\n", t);
}
template<typename T = std::chrono::microseconds>
struct TimeMeasure
{
template<typename F, typename ...Args>
static typename T::rep Run(F func, Args&&... args)
{
auto start = std::chrono::system_clock::now();
func(std::forward<Args>(args)...);
auto duration = std::chrono::duration_cast<T>
(std::chrono::system_clock::now() - start);
return duration.count();
}
};
void DoStep(Rrt* rrt, bool* done) {
*done = rrt->Step();
}
std::string MakeUsage(const char* argv0) {
std::string usage;
usage += "determines a motion plan for the given task.\n"
"Usage: ";
usage += argv0;
usage += " [OPTION]... [FILE]...\n"
"Try \'";
usage += argv0;
usage += " --help' for more information.";
return usage;
}
int main(int argc, char** argv) {
google::SetUsageMessage(MakeUsage("rrtplan"));
google::SetVersionString("");
google::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(google::GetArgv0());
if (argc < 2) {
fprintf(stdout, "%s: %s\n",
google::ProgramInvocationShortName(), google::ProgramUsage());
return 2;
}
LOG(INFO) << "Number of configurations to open: " << argc - 1;
LOG(INFO) << "Verifying configurations...";
for (int task = 1; task < argc; ++task) {
if (FLAGS_verbose)
LOG(INFO) << "Verifying " << argv[task];
Rrt rrt_verification(argv[task]);
}
LOG(INFO) << "All configurations are valid";
for (int task = 1; task < argc; ++task) {
Rrt rrt(argv[task]);
LOG(INFO) << "Running case: " << argv[task];
if (FLAGS_output_type == "progress")
fprintf(stderr, "Begin: %s\n", argv[task]);
int step = 0;
bool done = false;
std::vector<long int> durations;
while (!done) {
durations.push_back(static_cast<long int>(
TimeMeasure<std::chrono::microseconds>::Run(
DoStep, &rrt, &done)));
}
step = 0;
for (long int t : durations)
LOG(INFO) << "Step " << ++step << " took " << t << " us";
if (FLAGS_output_type == "progress")
fprintf(stderr, "End: %s\n", argv[task]);
if (FLAGS_output_type == "path")
OutputPath(rrt.GetSolution());
else if (FLAGS_output_type == "times")
OutputTimes(durations);
}
google::protobuf::ShutdownProtobufLibrary();
google::ShutdownGoogleLogging();
google::ShutDownCommandLineFlags();
return 0;
}
| 33.458065 | 81 | 0.668531 | adnanademovic |
095c1de8f26bd733392bec6965501f89ad060eee | 15,565 | cpp | C++ | src/core/NEON/kernels/arm_conv/depthwise/kernels/sve_s8qs_nhwc_3x3_s1_output2x2_dot_depthfirst/generic.cpp | MaximMilashchenko/ComputeLibrary | 91ee4d0a9ef128b16936921470a0e3ffef347536 | [
"MIT"
] | 2,313 | 2017-03-24T16:25:28.000Z | 2022-03-31T03:00:30.000Z | src/core/NEON/kernels/arm_conv/depthwise/kernels/sve_s8qs_nhwc_3x3_s1_output2x2_dot_depthfirst/generic.cpp | MaximMilashchenko/ComputeLibrary | 91ee4d0a9ef128b16936921470a0e3ffef347536 | [
"MIT"
] | 952 | 2017-03-28T07:05:58.000Z | 2022-03-30T09:54:02.000Z | src/core/NEON/kernels/arm_conv/depthwise/kernels/sve_s8qs_nhwc_3x3_s1_output2x2_dot_depthfirst/generic.cpp | MaximMilashchenko/ComputeLibrary | 91ee4d0a9ef128b16936921470a0e3ffef347536 | [
"MIT"
] | 714 | 2017-03-24T22:21:51.000Z | 2022-03-18T19:49:57.000Z | /*
* Copyright (c) 2021 Arm Limited.
*
* SPDX-License-Identifier: 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.
*/
#if defined(ARM_COMPUTE_ENABLE_SVE)
#include "arm_gemm.hpp"
#include <cstdint>
namespace arm_conv {
namespace depthwise {
void sve_s8qs_nhwc_3x3_s1_output2x2_dot_depthfirst_impl(const int8_t *const *const inptrs, int8_t *const *const outptrs, const void *params, const uint64_t n_channels, const arm_gemm::Requantize32& qp)
{
__asm__ __volatile__(
"ldp x11, x10, [%x[inptrs], #0x0]\n"
"ptrue p2.b\n"
"ldp x9, x28, [%x[inptrs], #0x10]\n"
"addvl SP, SP, #-8\n"
"ldp x27, x26, [%x[inptrs], #0x20]\n"
"mov x25, #0x0\n"
"ldp x24, x23, [%x[inptrs], #0x30]\n"
"whilelt p1.b, x25, %x[n_channels]\n"
"ldp x22, x21, [%x[outptrs], #0x0]\n"
"ldp x20, x19, [%x[outptrs], #0x10]\n"
"ld1rw { z6.s }, p2/Z, [%x[qp], %[offsetof_Requantize32_minval]]\n"
"ld1rw { z5.s }, p2/Z, [%x[qp], %[offsetof_Requantize32_maxval]]\n"
"ld1rw { z4.s }, p2/Z, [%x[qp], %[offsetof_Requantize32_c_offset]]\n"
"1:" // Loop
"ld1b { z19.b }, p1/Z, [x11, x25]\n"
"whilelt p0.s, x25, %x[n_channels]\n"
"ld1b { z18.b }, p1/Z, [x10, x25]\n"
"ldp x11, x10, [%x[inptrs], #0x40]\n"
"ld1b { z16.b }, p1/Z, [x9, x25]\n"
"zip1 z21.b, z19.b, z16.b\n"
"ld1b { z17.b }, p1/Z, [x28, x25]\n"
"zip2 z19.b, z19.b, z16.b\n"
"ldp x9, x28, [%x[inptrs], #0x50]\n"
"ld1b { z23.b }, p1/Z, [x27, x25]\n"
"zip1 z16.b, z18.b, z17.b\n"
"ld1b { z20.b }, p1/Z, [x26, x25]\n"
"zip2 z18.b, z18.b, z17.b\n"
"ldp x27, x26, [%x[inptrs], #0x60]\n"
"zip1 z3.b, z21.b, z16.b\n"
"ld1b { z17.b }, p1/Z, [x24, x25]\n"
"zip2 z2.b, z21.b, z16.b\n"
"ld1b { z16.b }, p1/Z, [x23, x25]\n"
"zip1 z29.b, z19.b, z18.b\n"
"ldp x24, x23, [%x[inptrs], #0x70]\n"
"zip2 z28.b, z19.b, z18.b\n"
"ld1b { z22.b }, p1/Z, [x11, x25]\n"
"zip1 z19.b, z23.b, z17.b\n"
"ld1b { z21.b }, p1/Z, [x10, x25]\n"
"zip2 z27.b, z23.b, z17.b\n"
"ldp x11, x10, [%x[inptrs], #0x0]\n"
"zip1 z18.b, z20.b, z16.b\n"
"ld1b { z17.b }, p1/Z, [x9, x25]\n"
"zip2 z20.b, z20.b, z16.b\n"
"ld1b { z16.b }, p1/Z, [x28, x25]\n"
"zip1 z1.b, z19.b, z18.b\n"
"ldp x9, x28, [%x[inptrs], #0x10]\n"
"zip2 z0.b, z19.b, z18.b\n"
"ld1b { z19.b }, p1/Z, [x27, x25]\n"
"zip1 z26.b, z22.b, z17.b\n"
"ld1b { z25.b }, p1/Z, [x26, x25]\n"
"zip2 z24.b, z22.b, z17.b\n"
"ldp x27, x26, [%x[inptrs], #0x20]\n"
"zip1 z23.b, z21.b, z16.b\n"
"ld1b { z18.b }, p1/Z, [x24, x25]\n"
"zip2 z22.b, z21.b, z16.b\n"
"ld1b { z21.b }, p1/Z, [x23, x25]\n"
"zip1 z17.b, z27.b, z20.b\n"
"ldp x24, x23, [%x[inptrs], #0x30]\n"
"zip2 z16.b, z27.b, z20.b\n"
"st1b { z29.b }, p2, [SP]\n"
"zip1 z20.b, z19.b, z18.b\n"
"st1b { z28.b }, p2, [SP, #1, MUL VL]\n"
"zip2 z19.b, z19.b, z18.b\n"
"st1b { z17.b }, p2, [SP, #2, MUL VL]\n"
"zip1 z18.b, z25.b, z21.b\n"
"st1b { z16.b }, p2, [SP, #3, MUL VL]\n"
"zip2 z17.b, z25.b, z21.b\n"
"ld1w { z31.s }, p2/Z, [%x[params]]\n"
"zip1 z30.b, z26.b, z23.b\n"
"ld1b { z29.b }, p2/Z, [%x[params], #1, MUL VL]\n"
"zip2 z28.b, z26.b, z23.b\n"
"ld1b { z27.b }, p2/Z, [%x[params], #2, MUL VL]\n"
"zip1 z16.b, z24.b, z22.b\n"
"st1b { z16.b }, p2, [SP, #4, MUL VL]\n"
"zip2 z16.b, z24.b, z22.b\n"
"st1b { z16.b }, p2, [SP, #5, MUL VL]\n"
"zip1 z26.b, z20.b, z18.b\n"
"ld1b { z25.b }, p2/Z, [%x[params], #3, MUL VL]\n"
"zip2 z24.b, z20.b, z18.b\n"
"ld1w { z23.s }, p2/Z, [%x[params], #4, MUL VL]\n"
"zip1 z16.b, z19.b, z17.b\n"
"st1b { z16.b }, p2, [SP, #6, MUL VL]\n"
"zip2 z16.b, z19.b, z17.b\n"
"st1b { z16.b }, p2, [SP, #7, MUL VL]\n"
"mov z22.d, z31.d\n"
"ld1w { z21.s }, p2/Z, [%x[params], #5, MUL VL]\n"
"mov z20.d, z31.d\n"
"mov z19.d, z31.d\n"
"sdot z31.s, z29.b, z3.b\n"
"sdot z20.s, z29.b, z1.b\n"
"ext z3.b, z3.b, z3.b, #0x1\n"
"sdot z31.s, z27.b, z1.b\n"
"ext z1.b, z1.b, z1.b, #0x1\n"
"sdot z20.s, z27.b, z30.b\n"
"sdot z22.s, z29.b, z3.b\n"
"ld1b { z3.b }, p2/Z, [SP]\n"
"sdot z31.s, z25.b, z30.b\n"
"ext z30.b, z30.b, z30.b, #0x1\n"
"sdot z20.s, z25.b, z26.b\n"
"ext z26.b, z26.b, z26.b, #0x1\n"
"sdot z19.s, z29.b, z1.b\n"
"ld1b { z29.b }, p2/Z, [%x[params], #7, MUL VL]\n"
"sdot z22.s, z27.b, z1.b\n"
"ld1b { z1.b }, p2/Z, [SP, #2, MUL VL]\n"
".inst 0x04b777ff // sqrdmulh z31.s, z31.s, z23.s\n"
".inst 0x04b77694 // sqrdmulh z20.s, z20.s, z23.s\n"
"sdot z19.s, z27.b, z30.b\n"
"sdot z22.s, z25.b, z30.b\n"
"ld1b { z30.b }, p2/Z, [SP, #4, MUL VL]\n"
"and z16.d, z31.d, z21.d\n"
"asr z16.s, z16.s, #0x1f\n"
"sdot z19.s, z25.b, z26.b\n"
"ld1b { z26.b }, p2/Z, [SP, #6, MUL VL]\n"
".inst 0x04b776d6 // sqrdmulh z22.s, z22.s, z23.s\n"
"and z18.d, z20.d, z21.d\n"
"asr z18.s, z18.s, #0x1f\n"
".inst 0x04b77673 // sqrdmulh z19.s, z19.s, z23.s\n"
"sqadd z31.s, z31.s, z16.s\n"
"and z17.d, z22.d, z21.d\n"
"asr z17.s, z17.s, #0x1f\n"
"and z16.d, z19.d, z21.d\n"
"sqadd z20.s, z20.s, z18.s\n"
"asr z16.s, z16.s, #0x1f\n"
".inst 0x44828abf // srshl z31.s, p2/M, z31.s, z21.s\n"
"sqadd z22.s, z22.s, z17.s\n"
".inst 0x44828ab4 // srshl z20.s, p2/M, z20.s, z21.s\n"
"add z31.s, z31.s, z4.s\n"
"sqadd z19.s, z19.s, z16.s\n"
"add z20.s, z20.s, z4.s\n"
".inst 0x44828ab6 // srshl z22.s, p2/M, z22.s, z21.s\n"
"smax z31.s, p2/M, z31.s, z6.s\n"
"smax z20.s, p2/M, z20.s, z6.s\n"
".inst 0x44828ab3 // srshl z19.s, p2/M, z19.s, z21.s\n"
"add z22.s, z22.s, z4.s\n"
"smin z31.s, p2/M, z31.s, z5.s\n"
"st1b { z31.s }, p0, [x22, x25]\n"
"add z19.s, z19.s, z4.s\n"
"smax z22.s, p2/M, z22.s, z6.s\n"
"ld1w { z31.s }, p2/Z, [%x[params], #6, MUL VL]\n"
"addvl %x[params], %x[params], #16\n"
"smin z20.s, p2/M, z20.s, z5.s\n"
"ld1b { z27.b }, p2/Z, [%x[params], #-8, MUL VL]\n"
"ld1b { z25.b }, p2/Z, [%x[params], #-7, MUL VL]\n"
"smax z19.s, p2/M, z19.s, z6.s\n"
"ld1w { z23.s }, p2/Z, [%x[params], #-6, MUL VL]\n"
"smin z22.s, p2/M, z22.s, z5.s\n"
"ld1w { z21.s }, p2/Z, [%x[params], #-5, MUL VL]\n"
"smin z19.s, p2/M, z19.s, z5.s\n"
"st1b { z20.s }, p0, [x20, x25]\n"
"mov z20.d, z31.d\n"
"st1b { z22.s }, p0, [x21, x25]\n"
"mov z22.d, z31.d\n"
"st1b { z19.s }, p0, [x19, x25]\n"
"mov z19.d, z31.d\n"
"incw x25\n"
"sdot z31.s, z29.b, z2.b\n"
"whilelt p0.s, x25, %x[n_channels]\n"
"sdot z20.s, z29.b, z0.b\n"
"ext z2.b, z2.b, z2.b, #0x1\n"
"sdot z31.s, z27.b, z0.b\n"
"sdot z20.s, z27.b, z28.b\n"
"ext z0.b, z0.b, z0.b, #0x1\n"
"sdot z22.s, z29.b, z2.b\n"
"ld1b { z2.b }, p2/Z, [SP, #1, MUL VL]\n"
"sdot z31.s, z25.b, z28.b\n"
"sdot z20.s, z25.b, z24.b\n"
"ext z28.b, z28.b, z28.b, #0x1\n"
"ext z24.b, z24.b, z24.b, #0x1\n"
"sdot z19.s, z29.b, z0.b\n"
"ld1b { z29.b }, p2/Z, [%x[params], #-3, MUL VL]\n"
"sdot z22.s, z27.b, z0.b\n"
"ld1b { z0.b }, p2/Z, [SP, #3, MUL VL]\n"
".inst 0x04b777ff // sqrdmulh z31.s, z31.s, z23.s\n"
".inst 0x04b77694 // sqrdmulh z20.s, z20.s, z23.s\n"
"sdot z19.s, z27.b, z28.b\n"
"ld1b { z27.b }, p2/Z, [%x[params], #-2, MUL VL]\n"
"sdot z22.s, z25.b, z28.b\n"
"ld1b { z28.b }, p2/Z, [SP, #5, MUL VL]\n"
"and z16.d, z31.d, z21.d\n"
"asr z16.s, z16.s, #0x1f\n"
"sdot z19.s, z25.b, z24.b\n"
"ld1b { z25.b }, p2/Z, [%x[params], #-1, MUL VL]\n"
".inst 0x04b776d6 // sqrdmulh z22.s, z22.s, z23.s\n"
"ld1b { z24.b }, p2/Z, [SP, #7, MUL VL]\n"
"and z18.d, z20.d, z21.d\n"
"asr z18.s, z18.s, #0x1f\n"
".inst 0x04b77673 // sqrdmulh z19.s, z19.s, z23.s\n"
"ld1w { z23.s }, p2/Z, [%x[params]]\n"
"sqadd z31.s, z31.s, z16.s\n"
"and z17.d, z22.d, z21.d\n"
"asr z17.s, z17.s, #0x1f\n"
"and z16.d, z19.d, z21.d\n"
"sqadd z20.s, z20.s, z18.s\n"
"asr z16.s, z16.s, #0x1f\n"
".inst 0x44828abf // srshl z31.s, p2/M, z31.s, z21.s\n"
"sqadd z22.s, z22.s, z17.s\n"
".inst 0x44828ab4 // srshl z20.s, p2/M, z20.s, z21.s\n"
"add z31.s, z31.s, z4.s\n"
"sqadd z19.s, z19.s, z16.s\n"
"add z20.s, z20.s, z4.s\n"
".inst 0x44828ab6 // srshl z22.s, p2/M, z22.s, z21.s\n"
"smax z31.s, p2/M, z31.s, z6.s\n"
"smax z20.s, p2/M, z20.s, z6.s\n"
".inst 0x44828ab3 // srshl z19.s, p2/M, z19.s, z21.s\n"
"ld1w { z21.s }, p2/Z, [%x[params], #1, MUL VL]\n"
"add z22.s, z22.s, z4.s\n"
"smin z31.s, p2/M, z31.s, z5.s\n"
"st1b { z31.s }, p0, [x22, x25]\n"
"add z19.s, z19.s, z4.s\n"
"smax z22.s, p2/M, z22.s, z6.s\n"
"ld1w { z31.s }, p2/Z, [%x[params], #-4, MUL VL]\n"
"smin z20.s, p2/M, z20.s, z5.s\n"
"st1b { z20.s }, p0, [x20, x25]\n"
"mov z20.d, z31.d\n"
"smin z22.s, p2/M, z22.s, z5.s\n"
"st1b { z22.s }, p0, [x21, x25]\n"
"mov z22.d, z31.d\n"
"sdot z20.s, z29.b, z1.b\n"
"smax z19.s, p2/M, z19.s, z6.s\n"
"sdot z20.s, z27.b, z30.b\n"
"smin z19.s, p2/M, z19.s, z5.s\n"
"st1b { z19.s }, p0, [x19, x25]\n"
"mov z19.d, z31.d\n"
"incw x25\n"
"sdot z31.s, z29.b, z3.b\n"
"whilelt p0.s, x25, %x[n_channels]\n"
"sdot z20.s, z25.b, z26.b\n"
"ext z3.b, z3.b, z3.b, #0x1\n"
"ext z26.b, z26.b, z26.b, #0x1\n"
"sdot z31.s, z27.b, z1.b\n"
"ext z1.b, z1.b, z1.b, #0x1\n"
"sdot z22.s, z29.b, z3.b\n"
".inst 0x04b77694 // sqrdmulh z20.s, z20.s, z23.s\n"
"sdot z31.s, z25.b, z30.b\n"
"ext z30.b, z30.b, z30.b, #0x1\n"
"sdot z19.s, z29.b, z1.b\n"
"ld1b { z29.b }, p2/Z, [%x[params], #3, MUL VL]\n"
"sdot z22.s, z27.b, z1.b\n"
"and z18.d, z20.d, z21.d\n"
"asr z18.s, z18.s, #0x1f\n"
"sdot z19.s, z27.b, z30.b\n"
"ld1b { z27.b }, p2/Z, [%x[params], #4, MUL VL]\n"
"sdot z22.s, z25.b, z30.b\n"
".inst 0x04b777ff // sqrdmulh z31.s, z31.s, z23.s\n"
"sdot z19.s, z25.b, z26.b\n"
"ld1b { z25.b }, p2/Z, [%x[params], #5, MUL VL]\n"
"and z16.d, z31.d, z21.d\n"
"asr z16.s, z16.s, #0x1f\n"
".inst 0x04b776d6 // sqrdmulh z22.s, z22.s, z23.s\n"
"sqadd z20.s, z20.s, z18.s\n"
".inst 0x04b77673 // sqrdmulh z19.s, z19.s, z23.s\n"
"ld1w { z23.s }, p2/Z, [%x[params], #6, MUL VL]\n"
"and z17.d, z22.d, z21.d\n"
"asr z17.s, z17.s, #0x1f\n"
"sqadd z31.s, z31.s, z16.s\n"
"and z16.d, z19.d, z21.d\n"
"asr z16.s, z16.s, #0x1f\n"
".inst 0x44828ab4 // srshl z20.s, p2/M, z20.s, z21.s\n"
".inst 0x44828abf // srshl z31.s, p2/M, z31.s, z21.s\n"
"sqadd z22.s, z22.s, z17.s\n"
"add z20.s, z20.s, z4.s\n"
"add z31.s, z31.s, z4.s\n"
"sqadd z19.s, z19.s, z16.s\n"
".inst 0x44828ab6 // srshl z22.s, p2/M, z22.s, z21.s\n"
"smax z20.s, p2/M, z20.s, z6.s\n"
"smax z31.s, p2/M, z31.s, z6.s\n"
".inst 0x44828ab3 // srshl z19.s, p2/M, z19.s, z21.s\n"
"ld1w { z21.s }, p2/Z, [%x[params], #7, MUL VL]\n"
"add z22.s, z22.s, z4.s\n"
"smin z20.s, p2/M, z20.s, z5.s\n"
"st1b { z20.s }, p0, [x20, x25]\n"
"add z19.s, z19.s, z4.s\n"
"smin z31.s, p2/M, z31.s, z5.s\n"
"st1b { z31.s }, p0, [x22, x25]\n"
"smax z22.s, p2/M, z22.s, z6.s\n"
"smax z19.s, p2/M, z19.s, z6.s\n"
"ld1w { z31.s }, p2/Z, [%x[params], #2, MUL VL]\n"
"addvl %x[params], %x[params], #8\n"
"mov z20.d, z31.d\n"
"smin z22.s, p2/M, z22.s, z5.s\n"
"st1b { z22.s }, p0, [x21, x25]\n"
"mov z22.d, z31.d\n"
"sdot z20.s, z29.b, z0.b\n"
"smin z19.s, p2/M, z19.s, z5.s\n"
"st1b { z19.s }, p0, [x19, x25]\n"
"mov z19.d, z31.d\n"
"incw x25\n"
"sdot z31.s, z29.b, z2.b\n"
"whilelt p0.s, x25, %x[n_channels]\n"
"sdot z20.s, z27.b, z28.b\n"
"ext z2.b, z2.b, z2.b, #0x1\n"
"sdot z31.s, z27.b, z0.b\n"
"sdot z20.s, z25.b, z24.b\n"
"ext z0.b, z0.b, z0.b, #0x1\n"
"ext z24.b, z24.b, z24.b, #0x1\n"
"sdot z22.s, z29.b, z2.b\n"
"sdot z31.s, z25.b, z28.b\n"
"ext z28.b, z28.b, z28.b, #0x1\n"
"sdot z19.s, z29.b, z0.b\n"
"sdot z22.s, z27.b, z0.b\n"
".inst 0x04b777ff // sqrdmulh z31.s, z31.s, z23.s\n"
".inst 0x04b77694 // sqrdmulh z20.s, z20.s, z23.s\n"
"sdot z19.s, z27.b, z28.b\n"
"sdot z22.s, z25.b, z28.b\n"
"and z16.d, z31.d, z21.d\n"
"asr z16.s, z16.s, #0x1f\n"
"sdot z19.s, z25.b, z24.b\n"
".inst 0x04b776d6 // sqrdmulh z22.s, z22.s, z23.s\n"
"and z18.d, z20.d, z21.d\n"
"asr z18.s, z18.s, #0x1f\n"
"and z17.d, z22.d, z21.d\n"
".inst 0x04b77673 // sqrdmulh z19.s, z19.s, z23.s\n"
"asr z17.s, z17.s, #0x1f\n"
"sqadd z31.s, z31.s, z16.s\n"
"and z16.d, z19.d, z21.d\n"
"asr z16.s, z16.s, #0x1f\n"
"sqadd z20.s, z20.s, z18.s\n"
".inst 0x44828abf // srshl z31.s, p2/M, z31.s, z21.s\n"
"sqadd z22.s, z22.s, z17.s\n"
"add z31.s, z31.s, z4.s\n"
".inst 0x44828ab4 // srshl z20.s, p2/M, z20.s, z21.s\n"
"sqadd z19.s, z19.s, z16.s\n"
".inst 0x44828ab6 // srshl z22.s, p2/M, z22.s, z21.s\n"
"smax z31.s, p2/M, z31.s, z6.s\n"
"add z20.s, z20.s, z4.s\n"
".inst 0x44828ab3 // srshl z19.s, p2/M, z19.s, z21.s\n"
"add z22.s, z22.s, z4.s\n"
"smin z31.s, p2/M, z31.s, z5.s\n"
"st1b { z31.s }, p0, [x22, x25]\n"
"add z19.s, z19.s, z4.s\n"
"smax z22.s, p2/M, z22.s, z6.s\n"
"smax z20.s, p2/M, z20.s, z6.s\n"
"smax z19.s, p2/M, z19.s, z6.s\n"
"smin z22.s, p2/M, z22.s, z5.s\n"
"st1b { z22.s }, p0, [x21, x25]\n"
"smin z20.s, p2/M, z20.s, z5.s\n"
"smin z19.s, p2/M, z19.s, z5.s\n"
"st1b { z20.s }, p0, [x20, x25]\n"
"st1b { z19.s }, p0, [x19, x25]\n"
"incw x25\n"
"whilelt p1.b, x25, %x[n_channels]\n"
"b.any 1b\n"
"addvl SP, SP, #8\n"
: [params] "+&r" (params)
: [inptrs] "r" (inptrs), [n_channels] "r" (n_channels), [offsetof_Requantize32_c_offset] "I" (offsetof(arm_gemm::Requantize32, c_offset)), [offsetof_Requantize32_maxval] "I" (offsetof(arm_gemm::Requantize32, maxval)), [offsetof_Requantize32_minval] "I" (offsetof(arm_gemm::Requantize32, minval)), [outptrs] "r" (outptrs), [qp] "r" (&qp)
: "cc", "memory", "p0", "p1", "p2", "x9", "x10", "x11", "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28", "z0", "z1", "z2", "z3", "z4", "z5", "z6", "z16", "z17", "z18", "z19", "z20", "z21", "z22", "z23", "z24", "z25", "z26", "z27", "z28", "z29", "z30", "z31"
);
}
} // namespace depthwise
} // namespace arm_conv
#endif // defined(ARM_COMPUTE_ENABLE_SVE)
| 40.012853 | 340 | 0.531192 | MaximMilashchenko |
8231b94ae1cb5098998b7626a9890b8d3eb6a308 | 2,895 | cpp | C++ | plugin/game_plugin/game_plugin/command/TriggerCommand.cpp | thetodd/em5_bma | c5fdfbe1101dce1f0de223a2d5b935b4470cd360 | [
"MIT"
] | 2 | 2016-07-07T11:45:19.000Z | 2021-03-19T06:15:51.000Z | plugin/game_plugin/game_plugin/command/TriggerCommand.cpp | thetodd/em5_bma | c5fdfbe1101dce1f0de223a2d5b935b4470cd360 | [
"MIT"
] | 9 | 2016-07-07T11:57:28.000Z | 2016-07-18T15:56:41.000Z | plugin/game_plugin/game_plugin/command/TriggerCommand.cpp | thetodd/em5_bma | c5fdfbe1101dce1f0de223a2d5b935b4470cd360 | [
"MIT"
] | null | null | null | // Copyright (C) 2012-2015 Promotion Software GmbH
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "game_plugin/PrecompiledHeader.h"
#include "game_plugin/command/TriggerCommand.h"
#include <em5/action/ActionPriority.h>
#include <em5/map/EntityHelper.h>
#include <qsf_game/command/CommandContext.h>
#include "em5/component/vehicle/RoadVehicleComponent.h"
#include <em5/freeplay/FreeplaySystem.h>
#include <em5/EM5Helper.h>
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace flo11
{
//[-------------------------------------------------------]
//[ Public definitions ]
//[-------------------------------------------------------]
const uint32 TriggerCommand::PLUGINABLE_ID = qsf::StringHash("flo11::TriggerCommand");
//[-------------------------------------------------------]
//[ Private definitions ]
//[-------------------------------------------------------]
const uint32 TriggerCommand::ACTION_PRIORITY = em5::action::COMMAND_STD;
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
TriggerCommand::TriggerCommand(qsf::game::CommandManager* commandManager) :
em5::Command(commandManager, PLUGINABLE_ID)
{
mIconSettings.mTooltip = QT_TR_NOOP("ID_CMD_TRIGGER_BMA_EVENT");
mIconSettings.mShowAsGuiButton = true;
mIconSettings.mButtonIconPath = "police_megaphone";
}
//[-------------------------------------------------------]
//[ Public virtual em5::Command methods ]
//[-------------------------------------------------------]
bool TriggerCommand::checkAvailable()
{
// Command is always available
return true;
}
bool TriggerCommand::checkCaller(qsf::Entity& caller)
{
return true;
}
bool TriggerCommand::checkContext(const qsf::game::CommandContext& context)
{
// Self-executed command check
if (!context.mAllowSelfExecution) {
return false;
}
//Don't execute on caller with right click
if (context.mTargetEntity == context.mCaller) {
return false;
}
return true;
}
void TriggerCommand::execute(const qsf::game::CommandContext& context)
{
// Access the caller's action plan
//qsf::ActionComponent& actionComponent = getActionComponent(*context.mCaller);
EM5_FREEPLAY.triggerEventByPath("BMAEvent_Definitions/BMAFireEvent");
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // user
| 34.464286 | 87 | 0.462867 | thetodd |
82355b0a08fd90fcd564b2614ee7868fc49b2236 | 460 | cpp | C++ | client/src/bindings/LocalPlayer.cpp | LennartF22/altv-js-module | f3951ffccedad4e929818faaa5c154f761bf9355 | [
"MIT"
] | 1 | 2021-09-27T19:23:39.000Z | 2021-09-27T19:23:39.000Z | client/src/bindings/LocalPlayer.cpp | xxshady/altv-js-module | 64f5b23ff417b25a65d56e92fd39f28fb23dead7 | [
"MIT"
] | null | null | null | client/src/bindings/LocalPlayer.cpp | xxshady/altv-js-module | 64f5b23ff417b25a65d56e92fd39f28fb23dead7 | [
"MIT"
] | null | null | null | #include "V8Helpers.h"
#include "V8Class.h"
#include "V8Entity.h"
#include "V8ResourceImpl.h"
#include "V8BindHelpers.h"
#include "cpp-sdk/objects/ILocalPlayer.h"
extern V8Class v8Player;
extern V8Class v8LocalPlayer("LocalPlayer", v8Player, [](v8::Local<v8::FunctionTemplate> tpl) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
V8::SetAccessor<alt::ILocalPlayer, uint16_t, &alt::ILocalPlayer::GetCurrentAmmo>(isolate, tpl, "currentAmmo");
});
| 30.666667 | 114 | 0.736957 | LennartF22 |
8236463ff579a348d4a1f6cb7a82e38309a7f117 | 16,096 | hh | C++ | Fleece/Tree/MutableNode.hh | tophatch/fleece | 8853b610575c1a7d68681a792188bab9c0c1ec7d | [
"Apache-2.0"
] | 134 | 2016-05-09T19:42:55.000Z | 2022-01-16T13:05:18.000Z | Fleece/Tree/MutableNode.hh | tophatch/fleece | 8853b610575c1a7d68681a792188bab9c0c1ec7d | [
"Apache-2.0"
] | 70 | 2016-05-09T05:16:46.000Z | 2022-03-08T19:43:30.000Z | Fleece/Tree/MutableNode.hh | tophatch/fleece | 8853b610575c1a7d68681a792188bab9c0c1ec7d | [
"Apache-2.0"
] | 32 | 2016-05-19T10:38:06.000Z | 2022-01-30T22:45:25.000Z | //
// MutableNode.hh
// Fleece
//
// Created by Jens Alfke on 6/22/18.
// Copyright 2018-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
//
#pragma once
#include "NodeRef.hh"
#include "PlatformCompat.hh"
#include "RefCounted.hh"
#include "fleece/Mutable.hh"
#include "fleece/slice.hh"
#include "TempArray.hh"
#include "betterassert.hh"
namespace fleece { namespace hashtree {
using namespace std;
using offset_t = int32_t;
// Base class of nodes within a MutableHashTree.
class MutableNode {
public:
MutableNode(unsigned capacity)
:_capacity(int8_t(capacity))
{
assert_precondition(capacity <= kMaxChildren);
}
bool isLeaf() const FLPURE {return _capacity == 0;}
static void encodeOffset(offset_t &o, size_t curPos) {
assert_precondition((ssize_t)curPos > o);
o = endian::encLittle32(offset_t(curPos - o));
}
protected:
uint8_t capacity() const FLPURE {
assert_precondition(_capacity > 0);
return _capacity;
}
int8_t _capacity;
};
// A leaf node that holds a single key and value.
class MutableLeaf : public MutableNode {
public:
MutableLeaf(const Target &t, Value v)
:MutableNode(0)
,_key(t.key)
,_hash(t.hash)
,_value(v)
{ }
bool matches(Target target) const {
return _hash == target.hash && _key == target.key;
}
uint32_t writeTo(Encoder &enc, bool writeKey) {
if (writeKey)
enc.writeString(_key);
else
enc.writeValue(_value);
return (uint32_t)enc.finishItem();
}
void dump(std::ostream &out, unsigned indent) {
char hashStr[30];
sprintf(hashStr, "{%08x ", _hash);
out << string(2*indent, ' ') << hashStr << '"';
out.write((char*)_key.buf, _key.size);
out << "\"=" << _value.toJSONString() << "}";
}
alloc_slice const _key;
hash_t const _hash;
RetainedValue _value;
};
// An interior node holds a small compact hash table mapping to Nodes.
class MutableInterior : public MutableNode {
public:
static MutableInterior* newRoot(const HashTree *imTree) {
if (imTree)
return mutableCopy(imTree->rootNode());
else
return newNode(kMaxChildren);
}
unsigned childCount() const {
return _bitmap.bitCount();
}
NodeRef childAtIndex(unsigned index) {
assert_precondition(index < capacity());
return _children[index];
}
void deleteTree() {
unsigned n = childCount();
for (unsigned i = 0; i < n; ++i) {
auto child = _children[i].asMutable();
if (child) {
if (child->isLeaf())
delete (MutableLeaf*)child;
else
((MutableInterior*)child)->deleteTree();
}
}
delete this;
}
unsigned leafCount() const {
unsigned count = 0;
unsigned n = childCount();
for (unsigned i = 0; i < n; ++i) {
auto child = _children[i];
if (child.isMutable()) {
if (child.asMutable()->isLeaf())
count += 1;
else
count += ((MutableInterior*)child.asMutable())->leafCount();
} else {
if (child.asImmutable()->isLeaf())
count += 1;
else
count += child.asImmutable()->interior.leafCount();
}
}
return count;
}
NodeRef findNearest(hash_t hash) const {
unsigned bitNo = childBitNumber(hash);
if (!hasChild(bitNo))
return NodeRef();
NodeRef child = childForBitNumber(bitNo);
if (child.isLeaf()) {
return child;
} else if (child.isMutable()) {
auto mchild = child.asMutable();
return ((MutableInterior*)mchild)->findNearest(hash >> kBitShift); // recurse...
} else {
auto ichild = child.asImmutable();
return ichild->interior.findNearest(hash >> kBitShift);
}
}
// Recursive insertion method. On success returns either 'this', or a new node that
// replaces 'this'. On failure (i.e. callback returned nullptr) returns nullptr.
MutableInterior* insert(const Target &target, unsigned shift) {
assert_precondition(shift + kBitShift < 8*sizeof(hash_t));//FIX: //TODO: Handle hash collisions
unsigned bitNo = childBitNumber(target.hash, shift);
if (!hasChild(bitNo)) {
// No child -- add a leaf:
Value val = (*target.insertCallback)(nullptr);
if (!val)
return nullptr;
return addChild(bitNo, new MutableLeaf(target, val));
}
NodeRef &childRef = childForBitNumber(bitNo);
if (childRef.isLeaf()) {
if (childRef.matches(target)) {
// Leaf node matches this key; update or copy it:
Value val = (*target.insertCallback)(childRef.value());
if (!val)
return nullptr;
if (childRef.isMutable())
((MutableLeaf*)childRef.asMutable())->_value = val;
else
childRef = new MutableLeaf(target, val);
return this;
} else {
// Nope, need to promote the leaf to an interior node & add new key:
MutableInterior *node = promoteLeaf(childRef, shift);
auto insertedNode = node->insert(target, shift+kBitShift);
if (!insertedNode) {
delete node;
return nullptr;
}
childRef = insertedNode;
return this;
}
} else {
// Progress down to interior node...
auto child = (MutableInterior*)childRef.asMutable();
if (!child)
child = mutableCopy(&childRef.asImmutable()->interior, 1);
child = child->insert(target, shift+kBitShift);
if (child)
childRef = child;
//FIX: This can leak if child is created by mutableCopy, but then
return this;
}
}
bool remove(Target target, unsigned shift) {
assert_precondition(shift + kBitShift < 8*sizeof(hash_t));
unsigned bitNo = childBitNumber(target.hash, shift);
if (!hasChild(bitNo))
return false;
unsigned childIndex = childIndexForBitNumber(bitNo);
NodeRef childRef = _children[childIndex];
if (childRef.isLeaf()) {
// Child is a leaf -- is it the right key?
if (childRef.matches(target)) {
removeChild(bitNo, childIndex);
delete (MutableLeaf*)childRef.asMutable();
return true;
} else {
return false;
}
} else {
// Recurse into child node...
auto child = (MutableInterior*)childRef.asMutable();
if (child) {
if (!child->remove(target, shift+kBitShift))
return false;
} else {
child = mutableCopy(&childRef.asImmutable()->interior);
if (!child->remove(target, shift+kBitShift)) {
delete child;
return false;
}
_children[childIndex] = child;
}
if (child->_bitmap.empty()) {
removeChild(bitNo, childIndex); // child node is now empty, so remove it
delete child;
}
return true;
}
}
static offset_t encodeImmutableOffset(const Node *inode, offset_t off, const Encoder &enc) {
ssize_t o = (((char*)inode - (char*)enc.base().buf) - off) - enc.base().size;
assert(o < 0 && o > INT32_MIN);
return offset_t(o);
}
Interior writeTo(Encoder &enc) {
unsigned n = childCount();
// `nodes` is an in-memory staging area for the child nodes I'll write.
// The offsets in it are absolute positions in the encoded output,
// except for ones that are bitmaps.
TempArray(nodes, Node, n);
// Write interior nodes, then leaf node Values, then leaf node keys.
// This keeps the keys near me, for better locality of reference.
for (unsigned i = 0; i < n; ++i) {
if (!_children[i].isLeaf())
nodes[i] = _children[i].writeTo(enc);
}
for (unsigned i = 0; i < n; ++i) {
if (_children[i].isLeaf())
nodes[i].leaf._valueOffset = _children[i].writeTo(enc, false);
}
for (unsigned i = 0; i < n; ++i) {
if (_children[i].isLeaf())
nodes[i].leaf._keyOffset = _children[i].writeTo(enc, true);
}
// Convert the Nodes' absolute positions into offsets:
const offset_t childrenPos = (offset_t)enc.nextWritePos();
auto curPos = childrenPos;
for (unsigned i = 0; i < n; ++i) {
auto &node = nodes[i];
if (_children[i].isLeaf())
node.leaf.makeRelativeTo(curPos);
else
node.interior.makeRelativeTo(curPos);
curPos += sizeof(nodes[i]);
}
// Write the list of children, and return its position & my bitmap:
enc.writeRaw({nodes, n * sizeof(nodes[0])});
return Interior(bitmap_t(_bitmap), childrenPos);
}
offset_t writeRootTo(Encoder &enc) {
auto intNode = writeTo(enc);
auto curPos = (offset_t)enc.nextWritePos();
intNode.makeRelativeTo(curPos);
enc.writeRaw({&intNode, sizeof(intNode)});
return offset_t(curPos);
}
void dump(std::ostream &out, unsigned indent =1) const {
unsigned n = childCount();
out << string(2*indent, ' ') << "{";
for (unsigned i = 0; i < n; ++i) {
out << "\n";
_children[i].dump(out, indent+1);
}
out << " }";
}
static void operator delete(void* ptr) {
::operator delete(ptr);
}
private:
MutableInterior() = delete;
MutableInterior(const MutableInterior& i) = delete;
MutableInterior(MutableInterior&& i) = delete;
MutableInterior& operator=(const MutableInterior&) = delete;
static MutableInterior* newNode(unsigned capacity, MutableInterior *orig =nullptr) {
return new (capacity) MutableInterior(capacity, orig);
}
static void* operator new(size_t size, unsigned capacity) {
return ::operator new(size + capacity*sizeof(NodeRef));
}
static void operator delete(void* ptr, unsigned capacity) {
::operator delete(ptr);
}
static MutableInterior* mutableCopy(const Interior *iNode, unsigned extraCapacity =0) {
auto childCount = iNode->childCount();
auto node = newNode(childCount + extraCapacity);
node->_bitmap = asBitmap(iNode->bitmap());
for (unsigned i = 0; i < childCount; ++i)
node->_children[i] = NodeRef(iNode->childAtIndex(i));
return node;
}
static MutableInterior* promoteLeaf(NodeRef& childLeaf, unsigned shift) {
unsigned level = shift / kBitShift;
MutableInterior* node = newNode(2 + (level<1) + (level<3));
unsigned childBitNo = childBitNumber(childLeaf.hash(), shift+kBitShift);
node = node->addChild(childBitNo, childLeaf);
return node;
}
MutableInterior(unsigned cap, MutableInterior* orig =nullptr)
:MutableNode(cap)
,_bitmap(orig ? orig->_bitmap : Bitmap<bitmap_t>{})
{
if (orig)
memcpy(_children, orig->_children, orig->capacity()*sizeof(NodeRef));
else
memset(_children, 0, cap*sizeof(NodeRef));
}
MutableInterior* grow() {
assert_precondition(capacity() < kMaxChildren);
auto replacement = (MutableInterior*)realloc(this,
sizeof(MutableInterior) + (capacity()+1)*sizeof(NodeRef));
if (!replacement)
throw std::bad_alloc();
replacement->_capacity++;
return replacement;
}
static unsigned childBitNumber(hash_t hash, unsigned shift =0) {
return (hash >> shift) & (kMaxChildren - 1);
}
unsigned childIndexForBitNumber(unsigned bitNo) const {
return _bitmap.indexOfBit(bitNo);
}
bool hasChild(unsigned bitNo) const {
return _bitmap.containsBit(bitNo);
}
NodeRef& childForBitNumber(unsigned bitNo) {
auto i = childIndexForBitNumber(bitNo);
assert(i < capacity());
return _children[i];
}
NodeRef const& childForBitNumber(unsigned bitNo) const {
return const_cast<MutableInterior*>(this)->childForBitNumber(bitNo);
}
MutableInterior* addChild(unsigned bitNo, NodeRef child) {
return addChild(bitNo, childIndexForBitNumber(bitNo), child);
}
MutableInterior* addChild(unsigned bitNo, unsigned childIndex, NodeRef child) {
MutableInterior* node = (childCount() < capacity()) ? this : grow();
return node->_addChild(bitNo, childIndex, child);
}
MutableInterior* _addChild(unsigned bitNo, unsigned childIndex, NodeRef child) {
assert_precondition(child);
memmove(&_children[childIndex+1], &_children[childIndex],
(capacity() - childIndex - 1)*sizeof(NodeRef));
_children[childIndex] = child;
_bitmap.addBit(bitNo);
return this;
}
void removeChild(unsigned bitNo, unsigned childIndex) {
assert_precondition(childIndex < capacity());
memmove(&_children[childIndex], &_children[childIndex+1], (capacity() - childIndex - 1)*sizeof(NodeRef));
_bitmap.removeBit(bitNo);
}
Bitmap<bitmap_t> _bitmap {0};
#ifdef _MSC_VER
#pragma warning(push)
// warning C4200: nonstandard extension used: zero-sized array in struct/union
// note: This member will be ignored by a defaulted constructor or copy/move assignment operator
// Jim: So keep the default copy, move, and constructor deleted, and use care if they are overriden
#pragma warning(disable : 4200)
#endif
NodeRef _children[0]; // Variable-size array; size is given by _capacity
#ifdef _MSC_VER
#pragma warning(pop)
#endif
};
} }
| 35.610619 | 117 | 0.529697 | tophatch |
823b257f8521e661e50da3c78277b3fc07ec54ed | 975 | cpp | C++ | src/util/converter.cpp | tomezpl/EasyGIF | 22c7ae30b16e9a4d4facf8374be3bf32813c8a23 | [
"MIT"
] | null | null | null | src/util/converter.cpp | tomezpl/EasyGIF | 22c7ae30b16e9a4d4facf8374be3bf32813c8a23 | [
"MIT"
] | 3 | 2016-09-02T22:15:25.000Z | 2016-12-24T17:34:03.000Z | src/util/converter.cpp | tomezpl/EasyGIF | 22c7ae30b16e9a4d4facf8374be3bf32813c8a23 | [
"MIT"
] | null | null | null | // converter.cpp
// Author: Tomasz Zajac
#include "converter.hpp"
using namespace EasyGIF::Utility;
sf::Image Converter::ImgFrameToSFImage(::EasyGIF::ImageFrame frame)
{
sf::Image ret;
ret.create(frame.GetWidth(), frame.GetHeight(), sf::Color::White);
uint8_t* buf = frame.GetBuffer();
for(unsigned long y = 0; y < frame.GetHeight(); y++)
{
unsigned long realX = 0;
for(unsigned long x = y * 4 * frame.GetWidth(); x < (y + 1) * frame.GetWidth() * 4; x += 4)
{
uint8_t currR = buf[x];
uint8_t currG = buf[x + 1];
uint8_t currB = buf[x + 2];
ret.setPixel(realX, y, sf::Color((int)(currR), (int)(currG), (int)(currB), 255));
/*std::cout << "Pixel (" << x+1 << ", " << y+1 << ") has colour ("
<< (int)(m_Image.getPixel(x, y).r) << ", "
<< (int)(m_Image.getPixel(x, y).g) << ", "
<< (int)(m_Image.getPixel(x, y).b) << ", "
<< (int)(m_Image.getPixel(x, y).a) << ")"
<< std::endl;*/
realX++;
}
}
return ret;
}
| 25.657895 | 93 | 0.558974 | tomezpl |
823efe5ae679a8c58010af24a9c300abcbcc952b | 29,425 | cpp | C++ | gen/blink/bindings/modules/v8/V8HTMLMediaElementPartial.cpp | gergul/MiniBlink | 7a11c52f141d54d5f8e1a9af31867cd120a2c3c4 | [
"Apache-2.0"
] | 8 | 2019-05-05T16:38:05.000Z | 2021-11-09T11:45:38.000Z | gen/blink/bindings/modules/v8/V8HTMLMediaElementPartial.cpp | gergul/MiniBlink | 7a11c52f141d54d5f8e1a9af31867cd120a2c3c4 | [
"Apache-2.0"
] | null | null | null | gen/blink/bindings/modules/v8/V8HTMLMediaElementPartial.cpp | gergul/MiniBlink | 7a11c52f141d54d5f8e1a9af31867cd120a2c3c4 | [
"Apache-2.0"
] | 4 | 2018-12-14T07:52:46.000Z | 2021-06-11T18:06:09.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "V8HTMLMediaElementPartial.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/ScriptPromise.h"
#include "bindings/core/v8/ScriptState.h"
#include "bindings/core/v8/V8AbstractEventListener.h"
#include "bindings/core/v8/V8DOMConfiguration.h"
#include "bindings/core/v8/V8EventListenerList.h"
#include "bindings/core/v8/V8HTMLMediaElement.h"
#include "bindings/core/v8/V8ObjectConstructor.h"
#include "bindings/core/v8/V8Uint8Array.h"
#include "bindings/modules/v8/V8MediaKeys.h"
#include "bindings/modules/v8/V8MediaSession.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "core/frame/UseCounter.h"
#include "modules/audio_output_devices/HTMLMediaElementAudioOutputDevice.h"
#include "modules/encryptedmedia/HTMLMediaElementEncryptedMedia.h"
#include "modules/mediasession/HTMLMediaElementMediaSession.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace blink {
namespace HTMLMediaElementPartialV8Internal {
static void sinkIdAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLMediaElement* impl = V8HTMLMediaElement::toImpl(holder);
v8SetReturnValueString(info, HTMLMediaElementAudioOutputDevice::sinkId(*impl), info.GetIsolate());
}
static void sinkIdAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLMediaElementPartialV8Internal::sinkIdAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onwebkitkeyaddedAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLMediaElement* impl = V8HTMLMediaElement::toImpl(holder);
EventListener* cppValue(HTMLMediaElementEncryptedMedia::onwebkitkeyadded(*impl));
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onwebkitkeyaddedAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLMediaElementPartialV8Internal::onwebkitkeyaddedAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onwebkitkeyaddedAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLMediaElement* impl = V8HTMLMediaElement::toImpl(holder);
HTMLMediaElementEncryptedMedia::setOnwebkitkeyadded(*impl, V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onwebkitkeyaddedAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLMediaElementPartialV8Internal::onwebkitkeyaddedAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onwebkitkeyerrorAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLMediaElement* impl = V8HTMLMediaElement::toImpl(holder);
EventListener* cppValue(HTMLMediaElementEncryptedMedia::onwebkitkeyerror(*impl));
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onwebkitkeyerrorAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLMediaElementPartialV8Internal::onwebkitkeyerrorAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onwebkitkeyerrorAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLMediaElement* impl = V8HTMLMediaElement::toImpl(holder);
HTMLMediaElementEncryptedMedia::setOnwebkitkeyerror(*impl, V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onwebkitkeyerrorAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLMediaElementPartialV8Internal::onwebkitkeyerrorAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onwebkitkeymessageAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLMediaElement* impl = V8HTMLMediaElement::toImpl(holder);
EventListener* cppValue(HTMLMediaElementEncryptedMedia::onwebkitkeymessage(*impl));
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onwebkitkeymessageAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLMediaElementPartialV8Internal::onwebkitkeymessageAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onwebkitkeymessageAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLMediaElement* impl = V8HTMLMediaElement::toImpl(holder);
HTMLMediaElementEncryptedMedia::setOnwebkitkeymessage(*impl, V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onwebkitkeymessageAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLMediaElementPartialV8Internal::onwebkitkeymessageAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onwebkitneedkeyAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLMediaElement* impl = V8HTMLMediaElement::toImpl(holder);
EventListener* cppValue(HTMLMediaElementEncryptedMedia::onwebkitneedkey(*impl));
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onwebkitneedkeyAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLMediaElementPartialV8Internal::onwebkitneedkeyAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onwebkitneedkeyAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLMediaElement* impl = V8HTMLMediaElement::toImpl(holder);
HTMLMediaElementEncryptedMedia::setOnwebkitneedkey(*impl, V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onwebkitneedkeyAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLMediaElementPartialV8Internal::onwebkitneedkeyAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void mediaKeysAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLMediaElement* impl = V8HTMLMediaElement::toImpl(holder);
v8SetReturnValueFast(info, WTF::getPtr(HTMLMediaElementEncryptedMedia::mediaKeys(*impl)), impl);
}
static void mediaKeysAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLMediaElementPartialV8Internal::mediaKeysAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onencryptedAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLMediaElement* impl = V8HTMLMediaElement::toImpl(holder);
EventListener* cppValue(HTMLMediaElementEncryptedMedia::onencrypted(*impl));
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onencryptedAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLMediaElementPartialV8Internal::onencryptedAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onencryptedAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLMediaElement* impl = V8HTMLMediaElement::toImpl(holder);
HTMLMediaElementEncryptedMedia::setOnencrypted(*impl, V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onencryptedAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLMediaElementPartialV8Internal::onencryptedAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void sessionAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLMediaElement* impl = V8HTMLMediaElement::toImpl(holder);
v8SetReturnValueFast(info, WTF::getPtr(HTMLMediaElementMediaSession::session(*impl)), impl);
}
static void sessionAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLMediaElementPartialV8Internal::sessionAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void sessionAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "session", "HTMLMediaElement", holder, info.GetIsolate());
HTMLMediaElement* impl = V8HTMLMediaElement::toImpl(holder);
MediaSession* cppValue = V8MediaSession::toImplWithTypeCheck(info.GetIsolate(), v8Value);
if (!cppValue && !isUndefinedOrNull(v8Value)) {
exceptionState.throwTypeError("The provided value is not of type 'MediaSession'.");
exceptionState.throwIfNeeded();
return;
}
HTMLMediaElementMediaSession::setSession(*impl, WTF::getPtr(cppValue));
}
static void sessionAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLMediaElementPartialV8Internal::sessionAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void setSinkIdMethodPromise(const v8::FunctionCallbackInfo<v8::Value>& info, ExceptionState& exceptionState)
{
if (UNLIKELY(info.Length() < 1)) {
setMinimumArityTypeError(exceptionState, 1, info.Length());
return;
}
HTMLMediaElement* impl = V8HTMLMediaElement::toImpl(info.Holder());
V8StringResource<> sinkId;
{
sinkId = info[0];
if (!sinkId.prepare(exceptionState))
return;
}
ScriptState* scriptState = ScriptState::current(info.GetIsolate());
ScriptPromise result = HTMLMediaElementAudioOutputDevice::setSinkId(scriptState, *impl, sinkId);
v8SetReturnValue(info, result.v8Value());
}
static void setSinkIdMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "setSinkId", "HTMLMediaElement", info.Holder(), info.GetIsolate());
setSinkIdMethodPromise(info, exceptionState);
if (exceptionState.hadException())
v8SetReturnValue(info, exceptionState.reject(ScriptState::current(info.GetIsolate())).v8Value());
}
static void setSinkIdMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
HTMLMediaElementPartialV8Internal::setSinkIdMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void webkitGenerateKeyRequestMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "webkitGenerateKeyRequest", "HTMLMediaElement", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 1)) {
setMinimumArityTypeError(exceptionState, 1, info.Length());
exceptionState.throwIfNeeded();
return;
}
HTMLMediaElement* impl = V8HTMLMediaElement::toImpl(info.Holder());
V8StringResource<TreatNullAndUndefinedAsNullString> keySystem;
DOMUint8Array* initData;
{
keySystem = info[0];
if (!keySystem.prepare())
return;
if (UNLIKELY(info.Length() <= 1)) {
HTMLMediaElementEncryptedMedia::webkitGenerateKeyRequest(*impl, keySystem, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
return;
}
initData = info[1]->IsUint8Array() ? V8Uint8Array::toImpl(v8::Local<v8::Uint8Array>::Cast(info[1])) : 0;
}
HTMLMediaElementEncryptedMedia::webkitGenerateKeyRequest(*impl, keySystem, initData, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
}
static void webkitGenerateKeyRequestMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
UseCounter::countDeprecationIfNotPrivateScript(info.GetIsolate(), callingExecutionContext(info.GetIsolate()), UseCounter::PrefixedMediaGenerateKeyRequest);
HTMLMediaElementPartialV8Internal::webkitGenerateKeyRequestMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void webkitAddKeyMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "webkitAddKey", "HTMLMediaElement", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 2)) {
setMinimumArityTypeError(exceptionState, 2, info.Length());
exceptionState.throwIfNeeded();
return;
}
HTMLMediaElement* impl = V8HTMLMediaElement::toImpl(info.Holder());
V8StringResource<TreatNullAndUndefinedAsNullString> keySystem;
DOMUint8Array* key;
DOMUint8Array* initData;
V8StringResource<> sessionId;
{
keySystem = info[0];
if (!keySystem.prepare())
return;
key = info[1]->IsUint8Array() ? V8Uint8Array::toImpl(v8::Local<v8::Uint8Array>::Cast(info[1])) : 0;
if (UNLIKELY(info.Length() <= 2)) {
HTMLMediaElementEncryptedMedia::webkitAddKey(*impl, keySystem, key, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
return;
}
initData = info[2]->IsUint8Array() ? V8Uint8Array::toImpl(v8::Local<v8::Uint8Array>::Cast(info[2])) : 0;
if (!info[3]->IsUndefined()) {
sessionId = info[3];
if (!sessionId.prepare())
return;
} else {
sessionId = nullptr;
}
}
HTMLMediaElementEncryptedMedia::webkitAddKey(*impl, keySystem, key, initData, sessionId, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
}
static void webkitAddKeyMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
UseCounter::countDeprecationIfNotPrivateScript(info.GetIsolate(), callingExecutionContext(info.GetIsolate()), UseCounter::PrefixedMediaAddKey);
HTMLMediaElementPartialV8Internal::webkitAddKeyMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void webkitCancelKeyRequestMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "webkitCancelKeyRequest", "HTMLMediaElement", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 1)) {
setMinimumArityTypeError(exceptionState, 1, info.Length());
exceptionState.throwIfNeeded();
return;
}
HTMLMediaElement* impl = V8HTMLMediaElement::toImpl(info.Holder());
V8StringResource<TreatNullAndUndefinedAsNullString> keySystem;
V8StringResource<> sessionId;
{
keySystem = info[0];
if (!keySystem.prepare())
return;
if (!info[1]->IsUndefined()) {
sessionId = info[1];
if (!sessionId.prepare())
return;
} else {
sessionId = nullptr;
}
}
HTMLMediaElementEncryptedMedia::webkitCancelKeyRequest(*impl, keySystem, sessionId, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
}
static void webkitCancelKeyRequestMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
UseCounter::countDeprecationIfNotPrivateScript(info.GetIsolate(), callingExecutionContext(info.GetIsolate()), UseCounter::PrefixedMediaCancelKeyRequest);
HTMLMediaElementPartialV8Internal::webkitCancelKeyRequestMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void setMediaKeysMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 1)) {
v8SetReturnValue(info, ScriptPromise::rejectRaw(ScriptState::current(info.GetIsolate()), createMinimumArityTypeErrorForMethod(info.GetIsolate(), "setMediaKeys", "HTMLMediaElement", 1, info.Length())));
return;
}
HTMLMediaElement* impl = V8HTMLMediaElement::toImpl(info.Holder());
MediaKeys* mediaKeys;
{
mediaKeys = V8MediaKeys::toImplWithTypeCheck(info.GetIsolate(), info[0]);
if (!mediaKeys && !isUndefinedOrNull(info[0])) {
v8SetReturnValue(info, ScriptPromise::rejectRaw(ScriptState::current(info.GetIsolate()), V8ThrowException::createTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("setMediaKeys", "HTMLMediaElement", "parameter 1 is not of type 'MediaKeys'."))));
return;
}
}
ScriptState* scriptState = ScriptState::current(info.GetIsolate());
ScriptPromise result = HTMLMediaElementEncryptedMedia::setMediaKeys(scriptState, *impl, mediaKeys);
v8SetReturnValue(info, result.v8Value());
}
static void setMediaKeysMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
HTMLMediaElementPartialV8Internal::setMediaKeysMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
} // namespace HTMLMediaElementPartialV8Internal
void V8HTMLMediaElementPartial::installV8HTMLMediaElementTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
V8HTMLMediaElement::installV8HTMLMediaElementTemplate(functionTemplate, isolate);
v8::Local<v8::Signature> defaultSignature;
if (!RuntimeEnabledFeatures::mediaEnabled())
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "HTMLMediaElement", v8::Local<v8::FunctionTemplate>(), V8HTMLMediaElement::internalFieldCount, 0, 0, 0, 0, 0, 0);
else
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "HTMLMediaElement", v8::Local<v8::FunctionTemplate>(), V8HTMLMediaElement::internalFieldCount,
0, 0,
0, 0,
0, 0);
v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instanceTemplate);
v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototypeTemplate);
if (RuntimeEnabledFeatures::audioOutputDevicesEnabled()) {
static const V8DOMConfiguration::AccessorConfiguration accessorConfiguration =\
{"sinkId", HTMLMediaElementPartialV8Internal::sinkIdAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorConfiguration);
}
if (RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled()) {
static const V8DOMConfiguration::AccessorConfiguration accessorConfiguration =\
{"onwebkitkeyadded", HTMLMediaElementPartialV8Internal::onwebkitkeyaddedAttributeGetterCallback, HTMLMediaElementPartialV8Internal::onwebkitkeyaddedAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorConfiguration);
}
if (RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled()) {
static const V8DOMConfiguration::AccessorConfiguration accessorConfiguration =\
{"onwebkitkeyerror", HTMLMediaElementPartialV8Internal::onwebkitkeyerrorAttributeGetterCallback, HTMLMediaElementPartialV8Internal::onwebkitkeyerrorAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorConfiguration);
}
if (RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled()) {
static const V8DOMConfiguration::AccessorConfiguration accessorConfiguration =\
{"onwebkitkeymessage", HTMLMediaElementPartialV8Internal::onwebkitkeymessageAttributeGetterCallback, HTMLMediaElementPartialV8Internal::onwebkitkeymessageAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorConfiguration);
}
if (RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled()) {
static const V8DOMConfiguration::AccessorConfiguration accessorConfiguration =\
{"onwebkitneedkey", HTMLMediaElementPartialV8Internal::onwebkitneedkeyAttributeGetterCallback, HTMLMediaElementPartialV8Internal::onwebkitneedkeyAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorConfiguration);
}
if (RuntimeEnabledFeatures::encryptedMediaEnabled()) {
static const V8DOMConfiguration::AccessorConfiguration accessorConfiguration =\
{"mediaKeys", HTMLMediaElementPartialV8Internal::mediaKeysAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorConfiguration);
}
if (RuntimeEnabledFeatures::encryptedMediaEnabled()) {
static const V8DOMConfiguration::AccessorConfiguration accessorConfiguration =\
{"onencrypted", HTMLMediaElementPartialV8Internal::onencryptedAttributeGetterCallback, HTMLMediaElementPartialV8Internal::onencryptedAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorConfiguration);
}
if (RuntimeEnabledFeatures::mediaSessionEnabled()) {
static const V8DOMConfiguration::AccessorConfiguration accessorConfiguration =\
{"session", HTMLMediaElementPartialV8Internal::sessionAttributeGetterCallback, HTMLMediaElementPartialV8Internal::sessionAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorConfiguration);
}
if (RuntimeEnabledFeatures::audioOutputDevicesEnabled()) {
const V8DOMConfiguration::MethodConfiguration setSinkIdMethodConfiguration = {
"setSinkId", HTMLMediaElementPartialV8Internal::setSinkIdMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts,
};
V8DOMConfiguration::installMethod(isolate, prototypeTemplate, defaultSignature, v8::None, setSinkIdMethodConfiguration);
}
if (RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled()) {
const V8DOMConfiguration::MethodConfiguration webkitGenerateKeyRequestMethodConfiguration = {
"webkitGenerateKeyRequest", HTMLMediaElementPartialV8Internal::webkitGenerateKeyRequestMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts,
};
V8DOMConfiguration::installMethod(isolate, prototypeTemplate, defaultSignature, v8::None, webkitGenerateKeyRequestMethodConfiguration);
}
if (RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled()) {
const V8DOMConfiguration::MethodConfiguration webkitAddKeyMethodConfiguration = {
"webkitAddKey", HTMLMediaElementPartialV8Internal::webkitAddKeyMethodCallback, 0, 2, V8DOMConfiguration::ExposedToAllScripts,
};
V8DOMConfiguration::installMethod(isolate, prototypeTemplate, defaultSignature, v8::None, webkitAddKeyMethodConfiguration);
}
if (RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled()) {
const V8DOMConfiguration::MethodConfiguration webkitCancelKeyRequestMethodConfiguration = {
"webkitCancelKeyRequest", HTMLMediaElementPartialV8Internal::webkitCancelKeyRequestMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts,
};
V8DOMConfiguration::installMethod(isolate, prototypeTemplate, defaultSignature, v8::None, webkitCancelKeyRequestMethodConfiguration);
}
if (RuntimeEnabledFeatures::encryptedMediaEnabled()) {
const V8DOMConfiguration::MethodConfiguration setMediaKeysMethodConfiguration = {
"setMediaKeys", HTMLMediaElementPartialV8Internal::setMediaKeysMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts,
};
V8DOMConfiguration::installMethod(isolate, prototypeTemplate, defaultSignature, v8::None, setMediaKeysMethodConfiguration);
}
}
void V8HTMLMediaElementPartial::preparePrototypeObject(v8::Isolate* isolate, v8::Local<v8::Object> prototypeObject, v8::Local<v8::FunctionTemplate> interfaceTemplate)
{
V8HTMLMediaElement::preparePrototypeObject(isolate, prototypeObject, interfaceTemplate);
}
void V8HTMLMediaElementPartial::initialize()
{
// Should be invoked from initModules.
V8HTMLMediaElement::updateWrapperTypeInfo(
&V8HTMLMediaElementPartial::installV8HTMLMediaElementTemplate,
&V8HTMLMediaElementPartial::preparePrototypeObject);
}
} // namespace blink
| 54.289668 | 394 | 0.76401 | gergul |
824016a5c1506a5d9e65f7f6cf5576ad420f0f03 | 3,170 | cpp | C++ | ui/src/audioeditor.cpp | pixeldoc2000/qlcplus | 21b2921360c249f3f8aae707bb35b6db5e619b43 | [
"Apache-2.0"
] | null | null | null | ui/src/audioeditor.cpp | pixeldoc2000/qlcplus | 21b2921360c249f3f8aae707bb35b6db5e619b43 | [
"Apache-2.0"
] | null | null | null | ui/src/audioeditor.cpp | pixeldoc2000/qlcplus | 21b2921360c249f3f8aae707bb35b6db5e619b43 | [
"Apache-2.0"
] | null | null | null | /*
Q Light Controller
audioeditor.cpp
Copyright (c) Massimo Callegari
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <QLineEdit>
#include <QLabel>
#include <QDebug>
#include "audiodecoder.h"
#include "audioeditor.h"
#include "audio.h"
#include "doc.h"
AudioEditor::AudioEditor(QWidget* parent, Audio *audio, Doc* doc)
: QWidget(parent)
, m_doc(doc)
, m_audio(audio)
{
Q_ASSERT(doc != NULL);
Q_ASSERT(audio != NULL);
setupUi(this);
m_nameEdit->setText(m_audio->name());
m_nameEdit->setSelection(0, m_nameEdit->text().length());
m_fadeInEdit->setText(Function::speedToString(audio->fadeInSpeed()));
m_fadeOutEdit->setText(Function::speedToString(audio->fadeOutSpeed()));
connect(m_nameEdit, SIGNAL(textEdited(const QString&)),
this, SLOT(slotNameEdited(const QString&)));
connect(m_fadeInEdit, SIGNAL(returnPressed()),
this, SLOT(slotFadeInEdited()));
connect(m_fadeOutEdit, SIGNAL(returnPressed()),
this, SLOT(slotFadeOutEdited()));
AudioDecoder *adec = m_audio->getAudioDecoder();
m_filenameLabel->setText(m_audio->getSourceFileName());
if (adec != NULL)
{
AudioParameters ap = adec->audioParameters();
m_durationLabel->setText(Function::speedToString(m_audio->getDuration()));
m_srateLabel->setText(QString("%1 Hz").arg(ap.sampleRate()));
m_channelsLabel->setText(QString("%1").arg(ap.channels()));
m_bitrateLabel->setText(QString("%1 kb/s").arg(adec->bitrate()));
}
// Set focus to the editor
m_nameEdit->setFocus();
}
AudioEditor::~AudioEditor()
{
}
void AudioEditor::slotNameEdited(const QString& text)
{
m_audio->setName(text);
m_doc->setModified();
}
void AudioEditor::slotFadeInEdited()
{
uint newValue;
QString text = m_fadeInEdit->text();
if (text.contains(".") || text.contains("s") ||
text.contains("m") || text.contains("h"))
newValue = Function::stringToSpeed(text);
else
{
newValue = (text.toDouble() * 1000);
m_fadeInEdit->setText(Function::speedToString(newValue));
}
m_audio->setFadeInSpeed(newValue);
m_doc->setModified();
}
void AudioEditor::slotFadeOutEdited()
{
uint newValue;
QString text = m_fadeOutEdit->text();
if (text.contains(".") || text.contains("s") ||
text.contains("m") || text.contains("h"))
newValue = Function::stringToSpeed(text);
else
{
newValue = (text.toDouble() * 1000);
m_fadeOutEdit->setText(Function::speedToString(newValue));
}
m_audio->setFadeOutSpeed(newValue);
m_doc->setModified();
}
| 28.053097 | 82 | 0.667823 | pixeldoc2000 |
824586b6639fb944c49c192c691ef1433c8670b9 | 35,107 | cpp | C++ | 2004/samples/entity/curvetext/curvetext_db/CurveText.cpp | kevinzhwl/ObjectARXMod | ef4c87db803a451c16213a7197470a3e9b40b1c6 | [
"MIT"
] | 1 | 2021-06-25T02:58:47.000Z | 2021-06-25T02:58:47.000Z | 2004/samples/entity/curvetext/curvetext_db/CurveText.cpp | kevinzhwl/ObjectARXMod | ef4c87db803a451c16213a7197470a3e9b40b1c6 | [
"MIT"
] | null | null | null | 2004/samples/entity/curvetext/curvetext_db/CurveText.cpp | kevinzhwl/ObjectARXMod | ef4c87db803a451c16213a7197470a3e9b40b1c6 | [
"MIT"
] | 3 | 2020-05-23T02:47:44.000Z | 2020-10-27T01:26:53.000Z | // (C) Copyright 1993-2002 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
#include "stdafx.h"
#include "CurveText.h"
#include "utils.h"
#include "curvetextIterator.h"
#include <sys/types.h>
#include <sys/timeb.h>
// Object Version
#define VERSION 1
#define kClassName "AsdkCurveText"
ACRX_DXF_DEFINE_MEMBERS(AsdkCurveText, AcDbCurve,
AcDb::kDHL_CURRENT,
AcDb::kMReleaseCurrent,
0,
ASDKCURVETEXT,
"CurveTextDBX\
|Product Desc: curvetext object enabler\
|Company: Autodesk,Inc.\
|WEB Address: www.autodesk.com");
////////////////////////////////////////////////////////////////////
// constructors / destructor
////////////////////////////////////////////////////////////////////
AsdkCurveText::AsdkCurveText()
{
m_normal = AcGeVector3d(0.0, 0.0, 1.0);
m_string = "";
m_showCurve = true;
m_showText = true;
m_fit = false;
m_reverse = false;
m_repeat = false;
m_size = 1.0;
m_space = 1.0;
m_startDist = m_length = 0.0;
m_position = ABOVE;
m_isInJig = false;
setStyle("standard");
// The curve pointer is set to NULL.
// This implies that an AcDbCurve object created using
// this constructor is not usable until this pointer,
// is set.
//
m_pCurve = NULL;
}
AsdkCurveText::AsdkCurveText(AcDbCurve *pCurve)
{
m_normal = AcGeVector3d(0.0, 0.0, 1.0);
m_string = "";
m_showCurve = true;
m_showText = true;
m_fit = false;
m_reverse = false;
m_repeat = false;
m_size = 1.0;
m_space = 1.0;
m_startDist = m_length = 0.0;
m_position = ABOVE;
m_isInJig = false;
// Make sure the curve pointer is not NULL
// since we need this object to live...
//
assert(pCurve);
m_pCurve = pCurve;
// common properties
//
setProperties();
}
AsdkCurveText::AsdkCurveText(AcDbCurve *pCurve, const AsdkCurveText *pCurveText)
{
m_normal = pCurveText->getNormal();
m_string = pCurveText->getString();
m_styleId = pCurveText->getStyle();
m_showCurve = pCurveText->isCurveShown();
m_showText = pCurveText->isTextShown();
m_fit = pCurveText->isFit();
m_reverse = pCurveText->isReversed();
m_space = pCurveText->getSpace();
m_startDist = pCurveText->getStartDist();
m_position = pCurveText->getPosition();
m_repeat = pCurveText->isRepeatText();
m_length = pCurveText->getLength();
m_size = pCurveText->getSize();
m_isInJig = false;
// Make sure the curve pointer is not NULL
// since we need this object to live...
//
assert(pCurve);
m_pCurve = pCurve;
// common properties
//
setProperties();
}
AsdkCurveText::~AsdkCurveText()
{
// We delete the curve if it is not in the database.
// (which should always be the case).
//
if(m_pCurve != NULL &&
m_pCurve->objectId() == AcDbObjectId::kNull)
{
delete m_pCurve;
m_pCurve = NULL;
}
}
////////////////////////////////////////////////////////////////////
// AcDbEntity methods
////////////////////////////////////////////////////////////////////
Adesk::Boolean
AsdkCurveText::worldDraw(AcGiWorldDraw* wd)
{
if(!m_showText && !wd->isDragging() && !m_isInJig)
m_showCurve = TRUE;
// if m_space is 0, then force it to 1 !
// m_space is the scale factor applied to the space
// betwee n two characters. If m_space is 0, than all the
// characters will display on top of each other.
//
if(!m_space)
m_space = 1.0;
AcDbVoidPtrArray ptrArray;
// AcGiFiler is a general purpose function used for worldDraw()
// but also for explode() and saveAs().
//
return AcGiFiler(wd, AcDb::kNoSave, ptrArray);
}
void
AsdkCurveText::saveAs(AcGiWorldDraw* wd, AcDb::SaveType st )
{
// if m_space is 0, then force it to 1 !
if(!m_space)
m_space = 1.0;
// see comment in AsdkCurveText::worldDraw about
// AcGiFiler
//
AcDbVoidPtrArray ptrArray;
AcGiFiler(wd, st, ptrArray);
}
Acad::ErrorStatus
AsdkCurveText::transformBy(const AcGeMatrix3d& xform)
{
assertWriteEnabled();
// apply the transformation to the curve
//
assert(m_pCurve);
ISOK(m_pCurve->transformBy(xform));
// and to our normal
//
if(m_normal.isUnitLength() != Acad::eOk)
m_normal.normalize();
m_normal.transformBy(xform);
// In case of scaling, update the character
// size and spacement.
//
double length = m_normal.length();
m_size *= length;
m_normal.normalize();
// if space between characters is default,
// leave it this way.
//
if(m_space != 1.0)
m_space *= length;
return Acad::eOk;
}
Acad::ErrorStatus
AsdkCurveText::dxfInFields(AcDbDxfFiler* filer)
{
assertWriteEnabled();
// super message to the parent class
//
ISOK(AcDbCurve::dxfInFields(filer));
// swallow the subclass marker
//
if (!filer->atSubclassData(kClassName))
return Acad::eBadDxfSequence;
// get the curvetext information
// being order independant
//
struct resbuf rb;
Acad::ErrorStatus es = Acad::eOk;
while (es == Acad::eOk)
{
// when we will reach the embedded object,
// readItem will return eEndOfFile
//
if ((es = filer->readItem(&rb)) == Acad::eOk)
{
switch(rb.restype) {
// Object Version
//
case AcDb::kDxfInt16:
Adesk::Int16 version;
version = rb.resval.rint;
if (version > VERSION)
return Acad::eMakeMeProxy;
break;
// Normal
//
case AcDb::kDxfNormalX:
m_normal.set(rb.resval.rpoint[0],
rb.resval.rpoint[1],
rb.resval.rpoint[2]);
break;
// string
//
case AcDb::kDxfXTextString:
m_string = rb.resval.rstring;
break;
// text style Id
//
case AcDb::kDxfHardPointerId:
ads_name styleEname;
styleEname[0] = rb.resval.rlname[0];
styleEname[1] = rb.resval.rlname[1];
acdbGetObjectId(m_styleId, styleEname);
break;
// text size
//
case AcDb::kDxfTxtSize:
m_size = rb.resval.rreal;
break;
// space between characters
//
case AcDb::kDxfReal+1:
m_space = rb.resval.rreal;
break;
// start distance
//
case AcDb::kDxfReal+2:
m_startDist = rb.resval.rreal;
break;
// length along the curve
// to display the string
//
case AcDb::kDxfReal+3:
m_length = rb.resval.rreal;
break;
// position w/r/t/ the curve (Above, on or below)
//
case AcDb::kDxfInt8:
m_position = (char)rb.resval.rint;
break;
// repeat the text ?
//
case AcDb::kDxfBool:
if(rb.resval.rint)
m_repeat = true;
else
m_repeat = false;
break;
// show the curve ?
//
case AcDb::kDxfBool+1:
if(rb.resval.rint)
m_showCurve = true;
else
m_showCurve = false;
break;
// show the text?
//
case AcDb::kDxfBool+2:
if(rb.resval.rint)
m_showText = true;
else
m_showText = false;
break;
// fit the text?
//
case AcDb::kDxfBool+3:
if(rb.resval.rint)
m_fit = true;
else
m_fit = false;
break;
// reverse the text?
//
case AcDb::kDxfBool+4:
if(rb.resval.rint)
m_reverse = true;
else
m_reverse = false;
break;
// curve class name
//
case AcDb::kDxfXTextString +1:
// All we know is that the embedded object is a curve
// (AcDbCurve) which is an abstract class.
// We need to get the class descriptor object using the
// class name we saved to reconstruct the exact object.
//
CString className;
className = rb.resval.rstring;
AcRxClass *pRxClass;
pRxClass = AcRxClass::cast(acrxClassDictionary->at(className));
m_pCurve = AcDbCurve::cast(pRxClass->create());
break;
}
}
}
// Swallow the embedded object marker
//
if (!filer->atEmbeddedObjectStart())
return Acad::eBadDxfSequence;
// file the information in.
//
assert(m_pCurve);
ISOK(m_pCurve->dxfInFields(filer));
// We need to ensure that the common properties
// (like color, layer, line weight, etc.)
// are properly set for the curve itself.
//
ISOK(m_pCurve->setPropertiesFrom(this));
return filer->filerStatus();
}
Acad::ErrorStatus
AsdkCurveText::dxfOutFields(AcDbDxfFiler* filer) const
{
assertReadEnabled();
ISOK(AcDbCurve::dxfOutFields(filer));
ISOK(filer->writeItem(AcDb::kDxfSubclass, kClassName));
// Object Version
Adesk::Int16 version = VERSION;
ISOK(filer->writeItem(AcDb::kDxfInt16, version));
ISOK(filer->writeItem(AcDb::kDxfNormalX, m_normal));
ISOK(filer->writeItem(AcDb::kDxfXTextString, m_string));
ISOK(filer->writeItem(AcDb::kDxfHardPointerId, m_styleId));
ISOK(filer->writeItem(AcDb::kDxfTxtSize, m_size));
ISOK(filer->writeItem(AcDb::kDxfReal +1, m_space));
ISOK(filer->writeItem(AcDb::kDxfReal +2, m_startDist));
ISOK(filer->writeItem(AcDb::kDxfReal +3, m_length));
ISOK(filer->writeItem(AcDb::kDxfInt8, m_position));
ISOK(filer->writeItem(AcDb::kDxfBool, m_repeat));
ISOK(filer->writeItem(AcDb::kDxfBool +1, m_showCurve));
ISOK(filer->writeItem(AcDb::kDxfBool +2, m_showText));
ISOK(filer->writeItem(AcDb::kDxfBool +3, m_fit));
ISOK(filer->writeItem(AcDb::kDxfBool +4, m_reverse));
// We need to save what kind of curve we are pointing to.
// to be able to recreate the object on the other side
//
assert(m_pCurve);
ISOK(filer->writeItem(AcDb::kDxfXTextString+1, m_pCurve->isA()->name()));
ISOK(filer->writeEmbeddedObjectStart());
ISOK(m_pCurve->dxfOutFields(filer));
return filer->filerStatus();
}
Acad::ErrorStatus
AsdkCurveText::dwgInFields(AcDbDwgFiler* filer)
{
assertWriteEnabled();
ISOK(AcDbCurve::dwgInFields(filer));
char *buffer = NULL;
if (filer->filerType() == AcDb::kIdXlateFiler)
{
ISOK(filer->readItem(&m_styleId));
// Apply Xlate into embedded object
ISOK(m_pCurve->setPropertiesFrom(this));
return filer->filerStatus();
}
// Object Version
//
Adesk::Int16 version;
filer->readItem(&version);
if (version > VERSION)
return Acad::eMakeMeProxy;
// Normal
//
ISOK(filer->readItem(&m_normal));
// get the text string
//
buffer = NULL;
ISOK(filer->readItem(&buffer));
m_string = buffer;
acdbFree(buffer);
ISOK(filer->readItem(&m_styleId));
ISOK(filer->readItem(&m_size));
ISOK(filer->readItem(&m_space));
ISOK(filer->readItem(&m_startDist));
ISOK(filer->readItem(&m_length));
ISOK(filer->readItem(&m_position));
ISOK(filer->readItem(&m_repeat));
ISOK(filer->readItem(&m_showCurve));
ISOK(filer->readItem(&m_showText));
ISOK(filer->readItem(&m_fit));
ISOK(filer->readItem(&m_reverse));
// Get a pointer of the class
// descriptor object using the class name
// saved.
//
buffer = NULL;
filer->readItem(&buffer);
AcRxClass *pRxClass;
pRxClass = AcRxClass::cast(acrxClassDictionary->at(buffer));
acdbFree(buffer);
// Create an instance of this class if we have to.
// In case of kIdXlateFiler, there is not need to recreate the object.
//
m_pCurve = AcDbCurve::cast(pRxClass->create());
assert(m_pCurve);
// Fill it with the information saved
//
ISOK(m_pCurve->dwgInFields(filer));
ISOK(m_pCurve->setPropertiesFrom(this));
return filer->filerStatus();
}
Acad::ErrorStatus
AsdkCurveText::dwgOutFields(AcDbDwgFiler* filer) const
{
assertReadEnabled();
ISOK(AcDbCurve::dwgOutFields(filer));
if (filer->filerType() == AcDb::kIdXlateFiler)
{
ISOK(filer->writeItem(m_styleId));
return filer->filerStatus();
}
// Object Version
//
Adesk::Int16 version = VERSION;
ISOK(filer->writeItem(version));
ISOK(filer->writeItem(m_normal));
ISOK(filer->writeItem(m_string));
ISOK(filer->writeItem(m_styleId));
ISOK(filer->writeItem(m_size));
ISOK(filer->writeItem(m_space));
ISOK(filer->writeItem(m_startDist));
ISOK(filer->writeItem(m_length));
ISOK(filer->writeItem(m_position));
ISOK(filer->writeItem(m_repeat));
ISOK(filer->writeItem(m_showCurve));
ISOK(filer->writeItem(m_showText));
ISOK(filer->writeItem(m_fit));
ISOK(filer->writeItem(m_reverse));
// We need to tell which curve we are dealing with
//
ISOK(filer->writeItem(m_pCurve->isA()->name()));
ISOK(m_pCurve->dwgOutFields(filer));
return filer->filerStatus();
}
void
AsdkCurveText::list() const
{
assertReadEnabled();
AcDbCurve::list();
acutPrintf(" string: %s\n", m_string);
CString textStyleName;
getTextStyleName(textStyleName, m_styleId);
acutPrintf(" style: %s\n", textStyleName);
acutPrintf(" start distance: %f\n", m_startDist);
acutPrintf(" end distance: %f\n", m_startDist + m_length);
acutPrintf(" test size: %f\n", m_size);
if(m_space != 1.0)
acutPrintf(" space between characters: %f\n", m_space);
else
acutPrintf(" space between caracters: default\n");
if(m_reverse)
acutPrintf(" reversed: true\n", m_size);
else
acutPrintf(" reversed: false\n", m_size);
if(m_showCurve)
acutPrintf(" curve visible: true\n", m_size);
else
acutPrintf(" curve visible: false\n", m_size);
if(m_showText)
acutPrintf(" text visible: true\n", m_size);
else
acutPrintf(" text visible: false\n", m_size);
if(m_fit)
acutPrintf(" fit: true\n", m_size);
else
acutPrintf(" fit: false\n", m_size);
if(m_repeat)
acutPrintf(" text repetition: true\n", m_size);
else
acutPrintf(" text repetition: false\n", m_size);
acutPrintf(" EMBEDED CURVE:\n", m_size);
m_pCurve->list();
}
/////////////////////////////////////////////////////////
// Many AcDbEntity and AcDbCurve methods simply delegate
// to the embedded curve.
/////////////////////////////////////////////////////////
Acad::ErrorStatus
AsdkCurveText::getGeomExtents(AcDbExtents& extents) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getGeomExtents(extents);
}
Acad::ErrorStatus
AsdkCurveText::explode(AcDbVoidPtrArray& entitySet) const
{
assertReadEnabled();
Acad::ErrorStatus es;
assert(m_pCurve);
es = m_pCurve->explode(entitySet);
// If the curve does not explode, than it became itself
// (or actually its clone), a part of the entity set
// resulting from the opreration
//
if(entitySet.isEmpty())
{
AcDbCurve *pNewCurve;
pNewCurve = AcDbCurve::cast(m_pCurve->clone());
entitySet.append(pNewCurve);
}
AcGiFiler(NULL, AcDb::kR12Save, entitySet);
return Acad::eOk;
}
Acad::ErrorStatus
AsdkCurveText::getGripPoints(AcGePoint3dArray& gripPoints,
AcDbIntArray& osnapModes,
AcDbIntArray& geomIds) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getGripPoints(gripPoints, osnapModes, geomIds);
}
Acad::ErrorStatus
AsdkCurveText::getOsnapPoints(AcDb::OsnapMode osnapMode,
int gsSelectionMark,
const AcGePoint3d& pickPoint,
const AcGePoint3d& lastPoint,
const AcGeMatrix3d& viewXform,
AcGePoint3dArray& snapPoints,
AcDbIntArray& geomIds) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getOsnapPoints(osnapMode, gsSelectionMark, pickPoint, lastPoint,
viewXform, snapPoints, geomIds);
}
Acad::ErrorStatus
AsdkCurveText::getGsMarkersAtSubentPath(const AcDbFullSubentPath& subPath,
AcDbIntArray& gsMarkers) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getGsMarkersAtSubentPath(subPath, gsMarkers);
}
Acad::ErrorStatus
AsdkCurveText::getSubentPathsAtGsMarker(AcDb::SubentType type,
int gsMark,
const AcGePoint3d& pickPoint,
const AcGeMatrix3d& viewXform,
int& numPaths,
AcDbFullSubentPath* subentPaths,
int numInserts,
AcDbObjectId* entAndInsertStack) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getSubentPathsAtGsMarker(type, gsMark, pickPoint, viewXform, numPaths,
subentPaths, numInserts, entAndInsertStack);
}
Acad::ErrorStatus
AsdkCurveText::getStretchPoints(AcGePoint3dArray& stretchPoints) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getStretchPoints(stretchPoints);
}
Acad::ErrorStatus
AsdkCurveText::moveGripPointsAt(const AcDbIntArray& indices, const AcGeVector3d& offset)
{
assertWriteEnabled();
assert(m_pCurve);
return m_pCurve->moveGripPointsAt(indices, offset);
}
Acad::ErrorStatus
AsdkCurveText::moveStretchPointsAt(const AcDbIntArray& indices, const AcGeVector3d& offset)
{
assertWriteEnabled();
assert(m_pCurve);
return m_pCurve->moveStretchPointsAt(indices, offset);
}
Acad::ErrorStatus
AsdkCurveText::boundingBoxIntersectWith(const AcDbEntity* pEnt,
AcDb::Intersect intType,
AcGePoint3dArray& points,
int thisGsMarker,
int otherGsMarker) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->boundingBoxIntersectWith(pEnt, intType, points,
thisGsMarker, otherGsMarker);
}
Acad::ErrorStatus
AsdkCurveText::boundingBoxIntersectWith(const AcDbEntity* pEnt,
AcDb::Intersect intType,
const AcGePlane& projPlane,
AcGePoint3dArray& points,
int thisGsMarker,
int otherGsMarker) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->boundingBoxIntersectWith(pEnt, intType, projPlane,
points, thisGsMarker, otherGsMarker);
}
Acad::ErrorStatus
AsdkCurveText::intersectWith(const AcDbEntity* pEnt,
AcDb::Intersect intType,
const AcGePlane& projPlane,
AcGePoint3dArray& points,
int thisGsMarker,
int otherGsMarker) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->intersectWith(pEnt, intType, projPlane, points, thisGsMarker, otherGsMarker);
}
Acad::ErrorStatus
AsdkCurveText::intersectWith(const AcDbEntity* pEnt,
AcDb::Intersect intType,
AcGePoint3dArray& points,
int thisGsMarker,
int otherGsMarker) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->intersectWith(pEnt, intType, points, thisGsMarker, otherGsMarker);
}
AcDbEntity*
AsdkCurveText::subentPtr(const AcDbFullSubentPath& path) const
{
assertReadEnabled();
assert(m_pCurve);
AcDbEntity *pEnt = m_pCurve->subentPtr(path);
return pEnt;
}
Acad::ErrorStatus
AsdkCurveText::getTransformedCopy(const AcGeMatrix3d& xform,
AcDbEntity*& pEnt) const
{
assertReadEnabled();
// We need to check the value returned
// by the curve getTransformedCopy because
// for example AcDbPolyline will return
// eExplodeBeforeTransform.
// In es is not eOk, we simply return es;
//
Acad::ErrorStatus es;
assert(m_pCurve);
es = m_pCurve->getTransformedCopy(xform, pEnt);
if(es != Acad::eOk)
return es;
AsdkCurveText *pCurveText = new AsdkCurveText(AcDbCurve::cast(pEnt), this);
pEnt = AcDbEntity::cast(pCurveText);
return Acad::eOk;
}
void
AsdkCurveText::getEcs(AcGeMatrix3d& retVal) const
{
assertReadEnabled();
assert(m_pCurve);
m_pCurve->getEcs(retVal);
}
////////////////////////////////////////////////////////////////////
// AcDbCurve methods
////////////////////////////////////////////////////////////////////
Adesk::Boolean
AsdkCurveText::isClosed() const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->isClosed();
}
Adesk::Boolean
AsdkCurveText::isPeriodic() const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->isPeriodic();
}
Adesk::Boolean
AsdkCurveText::isPlanar() const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->isPlanar();
}
Acad::ErrorStatus
AsdkCurveText::getPlane(AcGePlane& plane, AcDb::Planarity& planarity) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getPlane(plane, planarity);
}
Acad::ErrorStatus
AsdkCurveText::getStartParam(double& param) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getStartParam(param);
}
Acad::ErrorStatus
AsdkCurveText::getEndParam(double& param) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getEndParam(param);
}
Acad::ErrorStatus
AsdkCurveText::getStartPoint(AcGePoint3d& point) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getStartPoint(point);
}
Acad::ErrorStatus
AsdkCurveText::getEndPoint(AcGePoint3d& point) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getEndPoint(point);
}
Acad::ErrorStatus
AsdkCurveText::getPointAtParam(double param, AcGePoint3d& point) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getPointAtParam(param, point);
}
Acad::ErrorStatus
AsdkCurveText::getParamAtPoint(const AcGePoint3d& point, double& param) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getParamAtPoint(point, param);
}
Acad::ErrorStatus
AsdkCurveText::getDistAtParam(double param, double& dist) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getDistAtParam(param, dist);
}
Acad::ErrorStatus
AsdkCurveText::getParamAtDist(double dist , double& param) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getParamAtDist(dist, param);
}
Acad::ErrorStatus
AsdkCurveText::getDistAtPoint(const AcGePoint3d& point, double& dist) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getDistAtPoint(point, dist);
}
Acad::ErrorStatus
AsdkCurveText::getPointAtDist(double dist, AcGePoint3d& point) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getPointAtDist(dist, point);
}
Acad::ErrorStatus
AsdkCurveText::getFirstDeriv(double param, AcGeVector3d& vect) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getFirstDeriv(param, vect);
}
Acad::ErrorStatus
AsdkCurveText::getFirstDeriv(const AcGePoint3d& point, AcGeVector3d& vect)const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getFirstDeriv(point, vect);
}
Acad::ErrorStatus
AsdkCurveText::getSecondDeriv(double dist, AcGeVector3d& vect) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getSecondDeriv(dist, vect);
}
Acad::ErrorStatus
AsdkCurveText::getSecondDeriv(const AcGePoint3d& point, AcGeVector3d& vect) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getSecondDeriv(point, vect);
}
Acad::ErrorStatus
AsdkCurveText::getClosestPointTo(const AcGePoint3d& pt, AcGePoint3d& ptres,
Adesk::Boolean log) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getClosestPointTo(pt, ptres, log);
}
Acad::ErrorStatus
AsdkCurveText::getClosestPointTo(const AcGePoint3d& pt, const AcGeVector3d& dir,
AcGePoint3d& ptres, Adesk::Boolean log) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getClosestPointTo(pt, dir, ptres, log);
}
Acad::ErrorStatus
AsdkCurveText::getOrthoProjectedCurve(const AcGePlane& plane, AcDbCurve*& curve) const
{
assertReadEnabled();
Acad::ErrorStatus es;
assert(m_pCurve);
es = m_pCurve->getOrthoProjectedCurve(plane, curve);
AsdkCurveText *pCurveText;
pCurveText = new AsdkCurveText(curve, this);
curve = AcDbCurve::cast(pCurveText);
return es;
}
Acad::ErrorStatus
AsdkCurveText::getProjectedCurve(const AcGePlane& plane, const AcGeVector3d& dir,
AcDbCurve*& curve) const
{
assertReadEnabled();
Acad::ErrorStatus es;
assert(m_pCurve);
es = m_pCurve->getProjectedCurve(plane, dir, curve);
AsdkCurveText *pCurveText;
pCurveText = new AsdkCurveText(curve, this);
curve = AcDbCurve::cast(pCurveText);
return es;
}
Acad::ErrorStatus
AsdkCurveText::getOffsetCurves(double offset, AcDbVoidPtrArray& offsetCurves) const
{
assertReadEnabled();
Acad::ErrorStatus es;
assert(m_pCurve);
es = m_pCurve->getOffsetCurves(offset, offsetCurves);
if(es != Acad::eOk)
return es;
int length = offsetCurves.length();
AsdkCurveText *pCurveText;
AcDbCurve *pOffsetCurve;
for(int i=0; i<length; i++)
{
pOffsetCurve = AcDbCurve::cast((AcRxObject *)offsetCurves[i]);
if(pOffsetCurve == NULL)
continue;
pCurveText = new AsdkCurveText(pOffsetCurve, this);
offsetCurves[i] = pCurveText;
}
return Acad::eOk;
}
Acad::ErrorStatus
AsdkCurveText::getSpline(AcDbSpline*& spline) const
{
assertReadEnabled();
Acad::ErrorStatus es;
assert(m_pCurve);
es = m_pCurve->getSpline(spline);
AsdkCurveText* pCurveText;
pCurveText = new AsdkCurveText( AcDbCurve::cast(spline), this);
spline = AcDbSpline::cast(pCurveText);
return es;
}
Acad::ErrorStatus
AsdkCurveText::getSplitCurves(const AcGeDoubleArray& darray,
AcDbVoidPtrArray& curveSegments) const
{
assertReadEnabled();
Acad::ErrorStatus es;
assert(m_pCurve);
es = m_pCurve->getSplitCurves(darray, curveSegments);
if(es != Acad::eOk)
return es;
int length = curveSegments.length();
AsdkCurveText *pCurveText;
for(int i =0; i<length; i++)
{
pCurveText = new AsdkCurveText( AcDbCurve::cast((AcRxObject *)curveSegments[i]), this);
curveSegments[i] = pCurveText;
}
return Acad::eOk;
}
Acad::ErrorStatus
AsdkCurveText::getSplitCurves(const AcGePoint3dArray& parray,
AcDbVoidPtrArray& curveSegments) const
{
assertReadEnabled();
Acad::ErrorStatus es;
assert(m_pCurve);
es = m_pCurve->getSplitCurves(parray, curveSegments);
if(es != Acad::eOk)
return es;
int length = curveSegments.length();
AsdkCurveText *pCurveText;
for(int i =0; i<length; i++)
{
pCurveText = new AsdkCurveText( AcDbCurve::cast((AcRxObject *)curveSegments[i]), this);
curveSegments[i] = pCurveText;
}
return Acad::eOk;
}
Acad::ErrorStatus
AsdkCurveText::extend(double newParam)
{
assertWriteEnabled();
assert(m_pCurve);
return m_pCurve->extend(newParam);
}
Acad::ErrorStatus
AsdkCurveText::extend(Adesk::Boolean extendStart,
const AcGePoint3d& toPoint)
{
assertWriteEnabled();
assert(m_pCurve);
return m_pCurve->extend(extendStart, toPoint);
}
Acad::ErrorStatus
AsdkCurveText::getArea(double& area) const
{
assertReadEnabled();
assert(m_pCurve);
return m_pCurve->getArea(area);
}
////////////////////////////////////////////////////////////////////
// AsdkCurveText specific methods
////////////////////////////////////////////////////////////////////
void
AsdkCurveText::setCurvePtr(AcDbCurve* pCurve)
{
assertWriteEnabled();
assert(pCurve != NULL);
m_pCurve = pCurve;
setProperties();
}
void
AsdkCurveText::setProperties()
{
assertWriteEnabled();
// common entity properties
//
AOK(setPropertiesFrom(m_pCurve));
}
Acad::ErrorStatus
AsdkCurveText::setLineWeight(AcDb::LineWeight newVal, Adesk::Boolean doSubents)
{
assertWriteEnabled();
if(m_pCurve != NULL)
AOK(m_pCurve->setLineWeight(newVal, doSubents));
return AcDbEntity::setLineWeight(newVal, doSubents);
}
Acad::ErrorStatus
AsdkCurveText::setLayer(AcDbObjectId newVal, Adesk::Boolean doSubents)
{
assertWriteEnabled();
if(m_pCurve != NULL)
AOK(m_pCurve->setLayer(newVal, doSubents));
return AcDbEntity::setLayer(newVal, doSubents);
}
Acad::ErrorStatus
AsdkCurveText::setLayer(const char* newVal, Adesk::Boolean doSubents)
{
assertWriteEnabled();
if(m_pCurve != NULL)
AOK(m_pCurve->setLayer(newVal, doSubents));
return AcDbEntity::setLayer(newVal, doSubents);
}
Acad::ErrorStatus
AsdkCurveText::setLinetype(AcDbObjectId newVal, Adesk::Boolean doSubents)
{
assertWriteEnabled();
if(m_pCurve != NULL)
AOK(m_pCurve->setLinetype(newVal, doSubents));
return AcDbEntity::setLinetype(newVal, doSubents);
}
Acad::ErrorStatus
AsdkCurveText::setLinetype(const char* newVal, Adesk::Boolean doSubents)
{
assertWriteEnabled();
if(m_pCurve != NULL)
AOK(m_pCurve->setLinetype(newVal, doSubents));
return AcDbEntity::setLinetype(newVal, doSubents);
}
Acad::ErrorStatus
AsdkCurveText::setColor(const AcCmColor& color, Adesk::Boolean doSubents)
{
assertWriteEnabled();
if(m_pCurve != NULL)
AOK(m_pCurve->setColor(color, doSubents));
return AcDbEntity::setColor(color, doSubents);
}
Acad::ErrorStatus
AsdkCurveText::setLinetypeScale(const double ltscale, Adesk::Boolean doSubents)
{
assertWriteEnabled();
if(m_pCurve != NULL)
AOK(m_pCurve->setLinetypeScale(ltscale, doSubents));
return AcDbEntity::setLinetypeScale(ltscale, doSubents);
}
void
AsdkCurveText::setStyle(CString string)
{
assertWriteEnabled();
AcDbDatabase * pDb = database();
if(pDb == NULL)
pDb = acdbHostApplicationServices()->workingDatabase();
if(pDb == NULL)
acrx_abort("!%s@%d: %s", __FILE__, __LINE__, "No database!");
AcDbTextStyleTable *pTsTable;
AOK(pDb->getTextStyleTable(pTsTable, AcDb::kForRead));
AOK(pTsTable->getAt(string, m_styleId));
pTsTable->close();
}
Acad::ErrorStatus
AsdkCurveText::getStyle(CString styleName) const
{
assertReadEnabled();
// getTextStyleName is defined in utils.h
ISOK(getTextStyleName(styleName, m_styleId));
return Acad::eOk;
}
Adesk::Boolean
AsdkCurveText::AcGiFiler(AcGiWorldDraw* wd, AcDb::SaveType st, AcDbVoidPtrArray &entitySet) const
{
assertReadEnabled();
// Checks if m_pCurve is of type AsdkCurveText.
// in which case we'll take special precautions.
//
assert(m_pCurve);
AsdkCurveText *pct = AsdkCurveText::cast(m_pCurve);
if(NULL != pct)
{
pct->showCurve(isCurveShown());
pct->showText(isTextShown());
pct->worldDraw(wd);
}
// The only case where the AcGiWorldDraw parameter would be NULL
// is when we are called from explode.
//
if(NULL != wd)
{
// This is not explode
//
// Draw the curve only if we have to.
//
if((m_showCurve && !m_isInJig) ||
(!m_showCurve && wd->isDragging() && !m_isInJig))
{
if(st == AcDb::kNoSave)
{
if(NULL == pct)
{
wd->geometry().draw(m_pCurve);
}
}
else
m_pCurve->saveAs(wd, st);
}
if(!m_showText && !wd->isDragging() && !m_isInJig)
{
// The text is not displayed, we are not dragging
// and we are not being called from the jig.
// In this case, that's all we need to do.
//
return Adesk::kTrue;
}
}
CcurvetextIterator* pCtIt = new CcurvetextIterator(this, wd);
assert(pCtIt);
AcGePoint3d currentPoint;
short ctrl = GetKeyState(VK_CONTROL);
ctrl = ctrl >> 1;
// If the conditions below are satisfied, we swtich to the
// "fast display" mode which draws the start point and end point
// of the text instead of each character
//
Acad::ErrorStatus es;
if(!ctrl && !global.dynamicDisplay && wd)
{
if(m_isInJig || wd->isDragging())
{
es = pCtIt->getCurrentPosition(currentPoint);
if(es != Acad::eOk)
{
delete pCtIt;
return Adesk::kTrue;
}
AcGePoint3d endPoint;
es = pCtIt->getEndPosition(endPoint);
if(es != Acad::eOk)
{
delete pCtIt;
return Adesk::kTrue;
}
AcGeVector3d xAxis, yAxis;
xAxis = m_size * acdbHostApplicationServices()->workingDatabase()->ucsxdir();
yAxis = m_size * acdbHostApplicationServices()->workingDatabase()->ucsydir();
// The horizontal and vertical line segments
// for the crosses to draw.
//
AcGePoint3d X[2], Y[2];
wd->subEntityTraits().setColor(1);
X[0] = endPoint + xAxis;
X[1] = endPoint - xAxis;
Y[0] = endPoint + yAxis;
Y[1] = endPoint - yAxis;
wd->geometry().polyline(2, X);
wd->geometry().polyline(2, Y);
// repeat for the start point
// with a different color (green)
//
wd->subEntityTraits().setColor(3);
X[0] = currentPoint + xAxis;
X[1] = currentPoint - xAxis;
Y[0] = currentPoint + yAxis;
Y[1] = currentPoint - yAxis;
wd->geometry().polyline(2, X);
wd->geometry().polyline(2, Y);
delete pCtIt;
return Adesk::kTrue;
}
}
AcGeVector3d currentDirection, perp;
char string[2];
string[1] = '\0';
AcGeMatrix3d rotate;
if(m_position)
rotate.setToRotation(-PI / 2.0, m_normal);
for ( ; !pCtIt->done(); pCtIt->step())
{
es = pCtIt->getCurrentPosition(currentPoint);
if(es != Acad::eOk)
{
delete pCtIt;
return Adesk::kTrue;
}
es = pCtIt->getCurrentDirection(currentDirection);
if(es != Acad::eOk)
{
delete pCtIt;
return Adesk::kTrue;
}
if(m_position)
{
perp = currentDirection;
perp.normalize();
perp.transformBy(rotate);
if(m_position == 1)
currentPoint = currentPoint + (perp * (m_size / 2.0));
else
currentPoint = currentPoint + perp * m_size;
}
string[0] = pCtIt->getCurrentCharacter();
if(wd != NULL)
{
wd->geometry().text(currentPoint, m_normal, currentDirection, string, 1, Adesk::kTrue, pCtIt->getTextStyle());
}
else
{
// case of explode
//
AcGePlane plane(currentPoint, m_normal);
AcGeVector3d textXaxis, textYaxis;
plane.getCoordSystem(currentPoint, textXaxis, textYaxis);
double angle = textXaxis.angleTo(currentDirection, m_normal);
AcDbText* pText = new AcDbText(currentPoint, string, m_styleId, m_size, angle);
ASSERT(pText);
pText->setNormal(m_normal);
entitySet.append(pText);
}
}
delete pCtIt;
return Adesk::kTrue;
}
| 26.043769 | 114 | 0.653032 | kevinzhwl |
824595dce4e9bcffb6b6821f353bda30965a0c7f | 506 | cpp | C++ | codechef/the_one_on_the_last_night.cpp | k10tetry/data-structure-algorithm | 56af1e648ace71877874e45afad787a90beb4455 | [
"MIT"
] | 1 | 2021-09-30T19:14:59.000Z | 2021-09-30T19:14:59.000Z | codechef/the_one_on_the_last_night.cpp | k10tetry/data-structure-algorithm | 56af1e648ace71877874e45afad787a90beb4455 | [
"MIT"
] | null | null | null | codechef/the_one_on_the_last_night.cpp | k10tetry/data-structure-algorithm | 56af1e648ace71877874e45afad787a90beb4455 | [
"MIT"
] | 1 | 2021-10-01T14:29:20.000Z | 2021-10-01T14:29:20.000Z | #include<bits/stdc++.h>
using namespace std;
/* https://www.codechef.com/problems/S06E06 */
/* Successfully build the logic, but forgot to set the condition in the first attempt */
int main(){
int t;
cin >> t;
while(t--){
int n, k;
vector<int> v;
cin >> n >> k;
while(n){
v.push_back(n%10);
n /= 10;
}
while(k--){
sort(v.begin(),v.end());
if(v[0] != 9){
v[0]++;
}
}
int res = 1;
for(int num : v){
res *= num;
}
cout << res << '\n';
}
return 0;
} | 13.315789 | 88 | 0.517787 | k10tetry |
824cab22b063640f7ad981eccd6485843caeabae | 1,805 | cpp | C++ | OpenTESArena/src/Interface/PauseMenuUiView.cpp | michealccc/OpenTESArena | 7b4fd688677abea2ef03fa655b6d1669b1c8d77d | [
"MIT"
] | 742 | 2016-03-09T17:18:55.000Z | 2022-03-21T07:23:47.000Z | OpenTESArena/src/Interface/PauseMenuUiView.cpp | michealccc/OpenTESArena | 7b4fd688677abea2ef03fa655b6d1669b1c8d77d | [
"MIT"
] | 196 | 2016-06-07T15:19:21.000Z | 2021-12-12T16:50:58.000Z | OpenTESArena/src/Interface/PauseMenuUiView.cpp | michealccc/OpenTESArena | 7b4fd688677abea2ef03fa655b6d1669b1c8d77d | [
"MIT"
] | 85 | 2016-04-17T13:25:16.000Z | 2022-03-25T06:45:15.000Z | #include "PauseMenuUiView.h"
#include "../Assets/ArenaPaletteName.h"
#include "../Assets/ArenaTextureName.h"
#include "../Assets/TextureAssetReference.h"
namespace
{
const std::string DummyVolumeText = "100"; // Worst-case text size for sound/music volume.
}
TextBox::InitInfo PauseMenuUiView::getSoundTextBoxInitInfo(const FontLibrary &fontLibrary)
{
return TextBox::InitInfo::makeWithCenter(
DummyVolumeText,
PauseMenuUiView::SoundTextBoxCenterPoint,
PauseMenuUiView::VolumeFontName,
PauseMenuUiView::VolumeColor,
PauseMenuUiView::VolumeTextAlignment,
fontLibrary);
}
TextBox::InitInfo PauseMenuUiView::getMusicTextBoxInitInfo(const FontLibrary &fontLibrary)
{
return TextBox::InitInfo::makeWithCenter(
DummyVolumeText,
PauseMenuUiView::MusicTextBoxCenterPoint,
PauseMenuUiView::VolumeFontName,
PauseMenuUiView::VolumeColor,
PauseMenuUiView::VolumeTextAlignment,
fontLibrary);
}
TextBox::InitInfo PauseMenuUiView::getOptionsTextBoxInitInfo(const std::string_view &text, const FontLibrary &fontLibrary)
{
const TextRenderUtils::TextShadowInfo shadow(
PauseMenuUiView::OptionsButtonTextShadowOffsetX,
PauseMenuUiView::OptionsButtonTextShadowOffsetY,
PauseMenuUiView::OptionsButtonTextShadowColor);
return TextBox::InitInfo::makeWithCenter(
text,
PauseMenuUiView::OptionsTextBoxCenterPoint,
PauseMenuUiView::OptionsButtonFontName,
PauseMenuUiView::OptionsButtonTextColor,
PauseMenuUiView::OptionsButtonTextAlignment,
shadow,
0,
fontLibrary);
}
TextureAssetReference PauseMenuUiView::getBackgroundPaletteTextureAssetRef()
{
return TextureAssetReference(std::string(ArenaPaletteName::Default));
}
TextureAssetReference PauseMenuUiView::getBackgroundTextureAssetRef()
{
return TextureAssetReference(std::string(ArenaTextureName::PauseBackground));
}
| 30.59322 | 122 | 0.820499 | michealccc |
824dc120ab029b5da5fd99e9966ff54676ad85d8 | 1,654 | cpp | C++ | src/plugins/opencv/nodes/sequence/max_index.cpp | LIUJUN-liujun/possumwood | 745e48eb44450b0b7f078ece81548812ab1ccc63 | [
"MIT"
] | 1 | 2020-10-06T08:40:10.000Z | 2020-10-06T08:40:10.000Z | src/plugins/opencv/nodes/sequence/max_index.cpp | LIUJUN-liujun/possumwood | 745e48eb44450b0b7f078ece81548812ab1ccc63 | [
"MIT"
] | null | null | null | src/plugins/opencv/nodes/sequence/max_index.cpp | LIUJUN-liujun/possumwood | 745e48eb44450b0b7f078ece81548812ab1ccc63 | [
"MIT"
] | null | null | null | #include <possumwood_sdk/node_implementation.h>
#include <tbb/parallel_for.h>
#include "sequence.h"
namespace {
dependency_graph::InAttr<possumwood::opencv::Sequence> a_in;
dependency_graph::OutAttr<possumwood::opencv::Frame> a_out;
dependency_graph::State compute(dependency_graph::Values& data) {
const possumwood::opencv::Sequence& in = data.get(a_in);
if(!in.isValid())
throw std::runtime_error("Input sequence does not have consistent size or type.");
cv::Mat out = cv::Mat::zeros(in.rows(), in.cols(), CV_8UC1);
if(in.size() > 1) {
if(in.type() != CV_32FC1)
throw std::runtime_error("Only 1-channel float images supported for the moment.");
const int cols = in.cols();
const int rows = in.rows();
tbb::parallel_for(0, rows, [&](int r) {
for(int c = 0; c < cols; ++c) {
auto it = in.begin();
std::size_t max_id = 0;
float max = (*it)->at<float>(r, c);
++it;
while(it != in.end()) {
const float current = (*it)->at<float>(r, c);
if(max < current) {
max = current;
max_id = it - in.begin();
}
++it;
}
out.at<unsigned char>(r, c) = max_id;
}
});
}
else
throw std::runtime_error("At least two frames in the input sequence required!");
data.set(a_out, possumwood::opencv::Frame(out));
return dependency_graph::State();
}
void init(possumwood::Metadata& meta) {
meta.addAttribute(a_in, "in");
meta.addAttribute(a_out, "out", possumwood::opencv::Frame(), possumwood::AttrFlags::kVertical);
meta.addInfluence(a_in, a_out);
meta.setCompute(compute);
}
possumwood::NodeImplementation s_impl("opencv/sequence/max_index", init);
} // namespace
| 23.971014 | 96 | 0.65659 | LIUJUN-liujun |
824e2206ec37b27018dfbf95e6c86cc8a5312f53 | 787 | cc | C++ | Cplusplus/Bootcamp/03_MoreBasics/3_Exercise/main.cc | Kreijeck/learning | eaffee08e61f2a34e01eb8f9f04519aac633f48c | [
"MIT"
] | null | null | null | Cplusplus/Bootcamp/03_MoreBasics/3_Exercise/main.cc | Kreijeck/learning | eaffee08e61f2a34e01eb8f9f04519aac633f48c | [
"MIT"
] | null | null | null | Cplusplus/Bootcamp/03_MoreBasics/3_Exercise/main.cc | Kreijeck/learning | eaffee08e61f2a34e01eb8f9f04519aac633f48c | [
"MIT"
] | null | null | null | #include "exercise.h"
#include <iostream>
struct Dataset
{
int mean_array_a;
double mean_array_b;
};
int main()
{
// Exercise 1
const unsigned int array_elements = 5;
int array_a[array_elements] = {1, 2, 3, 4, 5};
double array_b[array_elements] = {1.0, 2.5, 3.5, 4.5, 10.0};
double mean_array_a = computation::mean_array_value(array_a, array_elements);
double mean_array_b = computation::mean_array_value(array_b, array_elements);
std::cout << "Mean Array A: " << mean_array_a << std::endl;
std::cout << "Mean Array B: " << mean_array_b << std::endl;
//Exercise 2
computation::Dataset data{mean_array_a, mean_array_b};
std::cout << data.mean_array_a << std::endl;
std::cout << data.mean_array_b << std::endl;
return 0;
}
| 26.233333 | 81 | 0.656925 | Kreijeck |
824fe3afbc6a7de485b781af37843e95752e729a | 11,208 | cpp | C++ | SimpleTextBlock.cpp | briangreenery/useless-text-editor | 3e0bf11a9f833b88a0a69f2e6f564743b2f9e5b3 | [
"Unlicense"
] | 4 | 2018-05-17T11:17:26.000Z | 2021-12-01T00:48:43.000Z | SimpleTextBlock.cpp | briangreenery/useless-text-editor | 3e0bf11a9f833b88a0a69f2e6f564743b2f9e5b3 | [
"Unlicense"
] | null | null | null | SimpleTextBlock.cpp | briangreenery/useless-text-editor | 3e0bf11a9f833b88a0a69f2e6f564743b2f9e5b3 | [
"Unlicense"
] | 1 | 2021-05-31T19:08:00.000Z | 2021-05-31T19:08:00.000Z | // SimpleTextBlock.cpp
#include "SimpleTextBlock.h"
#include "VisualPainter.h"
#include "TextStyleRegistry.h"
#include "TextDocumentReader.h"
#include "TextStyleReader.h"
#include "CharBuffer.h"
#include <algorithm>
SimpleTextBlock::SimpleTextBlock( SimpleLayoutDataPtr data, const TextStyleRegistry& styleRegistry )
: m_data( std::move( data ) )
, m_styleRegistry( styleRegistry )
{
}
void SimpleTextBlock::DrawBackground( VisualPainter& painter, RECT rect ) const
{
size_t firstLine = rect.top / m_styleRegistry.LineHeight();
rect.top = firstLine * m_styleRegistry.LineHeight();
for ( size_t line = firstLine; line < m_data->lines.size() && !IsRectEmpty( &rect ); ++line )
{
DrawLineBackground( line, painter, rect );
DrawLineSelection ( line, painter, rect );
DrawLineSquiggles ( line, painter, rect );
DrawLineHighlights( line, painter, rect );
rect.top += m_styleRegistry.LineHeight();
}
}
void SimpleTextBlock::DrawText( VisualPainter& painter, RECT rect ) const
{
size_t firstLine = rect.top / m_styleRegistry.LineHeight();
rect.top = firstLine * m_styleRegistry.LineHeight();
for ( size_t line = firstLine; line < m_data->lines.size() && !IsRectEmpty( &rect ); ++line )
{
DrawLineText( line, painter, rect );
rect.top += m_styleRegistry.LineHeight();
}
}
void SimpleTextBlock::DrawLineBackground( size_t line, VisualPainter& painter, RECT rect ) const
{
size_t pos = TextStart( line );
int xStart = 0;
ArrayRef<const TextStyleRun> styles = painter.styleReader.Classes( painter.textStart + pos, TextEnd( line ) - pos );
for ( const TextStyleRun* it = styles.begin(); it != styles.end() && xStart < rect.right; ++it )
{
int xEnd = CPtoX( line, pos + it->count - 1, true );
DrawLineRect( painter, rect, xStart, xEnd, m_styleRegistry.Style( it->styleid ).bkColor );
pos += it->count;
xStart = xEnd;
}
}
void SimpleTextBlock::DrawLineSelection( size_t line, VisualPainter& painter, RECT rect ) const
{
if ( painter.selection.Intersects( TextStart( line ), TextEnd( line ) ) )
{
size_t start = (std::max)( painter.selection.Min(), TextStart( line ) );
size_t end = (std::min)( painter.selection.Max(), TextEnd ( line ) );
int xStart = CPtoX( line, start, false );
int xEnd = CPtoX( line, end - 1, true );
DrawLineRect( painter, rect, xStart, xEnd, m_styleRegistry.Theme().selectionColor );
}
if ( line == m_data->lines.size() - 1
&& painter.selection.Intersects( TextEnd( line ), m_data->length )
&& m_data->endsWithNewline )
{
int xStart = LineWidth( line );
int xEnd = LineWidth( line ) + m_styleRegistry.AvgCharWidth();
DrawLineRect( painter, rect, xStart, xEnd, m_styleRegistry.Theme().selectionColor );
}
}
void SimpleTextBlock::DrawLineSquiggles( size_t line, VisualPainter& painter, RECT rect ) const
{
size_t textStart = TextStart( line );
size_t textEnd = TextEnd ( line );
ArrayRef<const CharRange> squiggles = painter.styleReader.Squiggles( painter.textStart + textStart, textEnd - textStart );
for ( const CharRange* it = squiggles.begin(); it != squiggles.end(); ++it )
{
int xStart = CPtoX( line, it->start - painter.textStart, false );
int xEnd = CPtoX( line, it->start - painter.textStart + it->count - 1, true );
if ( xStart >= rect.right )
break;
painter.DrawSquiggles( xStart, xEnd, rect );
}
}
void SimpleTextBlock::DrawLineHighlights( size_t line, VisualPainter& painter, RECT rect ) const
{
size_t textStart = TextStart( line );
size_t textEnd = TextEnd( line );
ArrayRef<const CharRange> highlights = painter.styleReader.Highlights( painter.textStart + textStart, textEnd - textStart );
for ( const CharRange* it = highlights.begin(); it != highlights.end(); ++it )
{
int xStart = CPtoX( line, it->start - painter.textStart, false );
int xEnd = CPtoX( line, it->start - painter.textStart + it->count - 1, true );
if ( xStart >= rect.right )
break;
painter.DrawHighlight( xStart, xEnd, rect );
}
}
void SimpleTextBlock::DrawLineText( size_t line, VisualPainter& painter, RECT rect ) const
{
size_t lineStart = TextStart( line );
size_t lineEnd = TextEnd( line );
ArrayRef<const SimpleTextRun> runs = LineRuns( line );
ArrayRef<const TextStyleRun> styles = painter.styleReader.Classes( painter.textStart + lineStart, lineEnd - lineStart );
int xRunStart = 0;
for ( const SimpleTextRun* run = runs.begin(); run != runs.end() && xRunStart < rect.right; ++run )
{
ArrayRef<const wchar_t> text = painter.charBuffer.Read( painter.textStart + run->textStart, run->textCount );
SelectObject( painter.hdc, m_styleRegistry.Font( run->fontid ).hfont );
ArrayRef<const TextStyleRun> runStyles = RunStyles( painter.textStart, *run, styles );
for ( const TextStyleRun* style = runStyles.begin(); style != runStyles.end(); ++style )
{
size_t overlapStart = (std::max)( style->start - painter.textStart, run->textStart );
size_t overlapEnd = (std::min)( style->start - painter.textStart + style->count, run->textStart + run->textCount );
int xStart = xRunStart + RunCPtoX( *run, overlapStart, false );
if ( xStart >= rect.right )
break;
painter.SetTextColor( m_styleRegistry.Style( style->styleid ).textColor );
ExtTextOutW( painter.hdc,
xStart,
rect.top,
ETO_CLIPPED,
&rect,
text.begin() + ( overlapStart - run->textStart ),
overlapEnd - overlapStart,
NULL );
}
xRunStart += RunWidth( run );
}
}
ArrayRef<const TextStyleRun> SimpleTextBlock::RunStyles( size_t blockStart, const SimpleTextRun& run, ArrayRef<const TextStyleRun> styles ) const
{
struct StyleRunEqual
{
StyleRunEqual( size_t blockStart ) : m_blockStart( blockStart ) {}
bool operator()( const TextStyleRun& a, const TextStyleRun& b ) const { return a.start + a.count < b.start; }
bool operator()( const TextStyleRun& a, const SimpleTextRun& b ) const { return a.start + a.count <= m_blockStart + b.textStart; }
bool operator()( const SimpleTextRun& a, const TextStyleRun& b ) const { return m_blockStart + a.textStart + a.textCount <= b.start; }
size_t m_blockStart;
};
std::pair<const TextStyleRun*, const TextStyleRun*> range = std::equal_range( styles.begin(), styles.end(), run, StyleRunEqual( blockStart ) );
return ArrayRef<const TextStyleRun>( range.first, range.second );
}
void SimpleTextBlock::DrawLineRect( VisualPainter& painter, RECT rect, int xStart, int xEnd, COLORREF color ) const
{
if ( color == TextStyle::useDefault )
return;
RECT drawRect = { std::max<int>( xStart, rect.left ),
rect.top,
std::min<int>( xEnd, rect.right ),
rect.top + m_styleRegistry.LineHeight() };
if ( !IsRectEmpty( &drawRect ) )
painter.FillRect( drawRect, color );
}
size_t SimpleTextBlock::LineCount() const
{
return m_data->lines.size();
}
size_t SimpleTextBlock::LineContaining( size_t pos ) const
{
size_t line = 0;
while ( line < m_data->lines.size() && TextEnd( line ) <= pos )
++line;
return line;
}
size_t SimpleTextBlock::LineStart( int y ) const
{
int line = y / m_styleRegistry.LineHeight();
assert( line >= 0 && size_t( line ) < m_data->lines.size() );
return TextStart( line );
}
size_t SimpleTextBlock::LineEnd( int y ) const
{
int line = y / m_styleRegistry.LineHeight();
assert( line >= 0 && size_t( line ) < m_data->lines.size() );
return TextEnd( line );
}
POINT SimpleTextBlock::PointFromChar( size_t pos, bool advancing ) const
{
POINT result;
bool trailingEdge = advancing;
if ( pos == 0 )
trailingEdge = false;
else if ( pos >= TextEnd( m_data->lines.size() - 1 ) )
trailingEdge = true;
if ( trailingEdge )
--pos;
size_t line = LineContaining( pos );
assert( line < m_data->lines.size() );
result.x = CPtoX( line, pos, trailingEdge );
result.y = line * m_styleRegistry.LineHeight();
return result;
}
size_t SimpleTextBlock::CharFromPoint( POINT* point ) const
{
int line = point->y / m_styleRegistry.LineHeight();
if ( line < 0 || size_t( line ) >= m_data->lines.size() )
line = m_data->lines.size() - 1;
point->y = line * m_styleRegistry.LineHeight();
return XtoCP( line, &point->x );
}
size_t SimpleTextBlock::Length() const
{
return m_data->length;
}
int SimpleTextBlock::Height() const
{
return m_data->lines.size() * m_styleRegistry.LineHeight();
}
bool SimpleTextBlock::EndsWithNewline() const
{
return m_data->endsWithNewline;
}
ArrayRef<const SimpleTextRun> SimpleTextBlock::LineRuns( size_t line ) const
{
assert( line < m_data->lines.size() );
const SimpleTextRun* runStart = &m_data->runs[line == 0 ? 0 : m_data->lines[line - 1]];
return ArrayRef<const SimpleTextRun>( runStart, &m_data->runs.front() + m_data->lines[line] );
}
size_t SimpleTextBlock::TextStart( size_t line ) const
{
ArrayRef<const SimpleTextRun> runs = LineRuns( line );
return runs[0].textStart;
}
size_t SimpleTextBlock::TextEnd( size_t line ) const
{
ArrayRef<const SimpleTextRun> runs = LineRuns( line );
return runs[runs.size() - 1].textStart + runs[runs.size() - 1].textCount;
}
int SimpleTextBlock::LineWidth( size_t line ) const
{
ArrayRef<const SimpleTextRun> runs = LineRuns( line );
int width = 0;
for ( const SimpleTextRun* run = runs.begin(); run != runs.end(); ++run )
width += RunWidth( run );
return width;
}
int SimpleTextBlock::RunWidth( const SimpleTextRun* run ) const
{
return m_data->xOffsets[run->textStart + run->textCount - 1];
}
int SimpleTextBlock::CPtoX( size_t line, size_t cp, bool trailingEdge ) const
{
ArrayRef<const SimpleTextRun> runs = LineRuns( line );
int x = 0;
const SimpleTextRun* run = runs.begin();
while ( run != runs.end() && run->textStart + run->textCount <= cp )
{
x += RunWidth( run );
run++;
}
assert( run != runs.end() );
return x + RunCPtoX( *run, cp, trailingEdge );
}
int SimpleTextBlock::RunCPtoX( const SimpleTextRun& run, size_t cp, bool trailingEdge ) const
{
assert( cp >= run.textStart );
assert( cp < run.textStart + run.textCount );
if ( trailingEdge )
return m_data->xOffsets[cp];
if ( cp == run.textStart )
return 0;
return m_data->xOffsets[cp - 1];
}
size_t SimpleTextBlock::XtoCP( size_t line, LONG* x ) const
{
ArrayRef<const SimpleTextRun> runs = LineRuns( line );
int xStart = 0;
const SimpleTextRun* run = runs.begin();
while ( run != runs.end() && xStart + RunWidth( run ) <= *x )
{
xStart += RunWidth( run );
run++;
}
if ( run == runs.end() )
{
*x = LineWidth( line );
return TextEnd( line );
}
size_t cp = run->textStart;
int xOffset = 0;
while ( cp < run->textStart + run->textCount && xStart + xOffset + ( m_data->xOffsets[cp] - xOffset ) / 2 < *x )
{
xOffset = m_data->xOffsets[cp];
++cp;
}
*x = xStart + xOffset;
return cp;
}
| 31.133333 | 146 | 0.65596 | briangreenery |
82503df944f34af64f3e8271303aad8c9481514d | 3,942 | cpp | C++ | lib/game/src/Application.cpp | MarkRDavison/zeno | cea002e716e624d28130e836bf56e9f2f1d2e484 | [
"MIT"
] | null | null | null | lib/game/src/Application.cpp | MarkRDavison/zeno | cea002e716e624d28130e836bf56e9f2f1d2e484 | [
"MIT"
] | null | null | null | lib/game/src/Application.cpp | MarkRDavison/zeno | cea002e716e624d28130e836bf56e9f2f1d2e484 | [
"MIT"
] | null | null | null | #include <zeno/Game/Application.hpp>
#include <zeno/Core/Clock.hpp>
#include <zeno/Window/Window.hpp>
#include <iostream>
namespace ze {
bool Application::startSplash(const VideoMode& _videoMode, Scene* _splashScene) {
m_StartingMode = _videoMode;
m_SplashShowing = true;
VideoMode splashVideoMode = _videoMode;
splashVideoMode.fullscreen = false;
splashVideoMode.decorated = false;
splashVideoMode.width = 800;
splashVideoMode.height = 400;
if (!m_Window.initialise(splashVideoMode)) {
std::cerr << "Failed to initialise splash screen." << std::endl;
return false;
}
if (!ze::Shader::createDefaultShaders()) {
std::cerr << "Failed to initialise default shaders." << std::endl;
return false;
}
setScene(_splashScene);
return true;
}
void Application::renderSplash() {
render(m_Window, 0.0f);
}
bool Application::splashFinished() {
return splashFinished(m_StartingMode);
}
bool Application::splashFinished(const VideoMode& _videoMode) {
m_Window.clear();
if (m_Window.getWindowFullscreen()) {
m_Window.setWindowFullscreen(_videoMode.fullscreen);
}
else {
m_Window.setSize(ze::Vector2u(_videoMode.width, _videoMode.height));
m_Window.setWindowDecorated(_videoMode.decorated);
m_Window.center();
}
setScene(nullptr);
m_Initialised = true;
return true;
}
bool Application::initialise(const Vector2u& _resolution, const std::string& _name) {
VideoMode mode{ _resolution, _name };
mode.contextMajor = 4;
mode.contextMinor = 5;
return initialise(mode);
}
bool Application::initialise(const VideoMode& _videoMode) {
if (m_Initialised) {
std::cerr << "Cannot initalise an application twice." << std::endl;
return false;
}
if (!m_Window.initialise(_videoMode)) {
std::cerr << "Failed to initialise window." << std::endl;
return false;
}
if (!ze::Shader::createDefaultShaders()) {
std::cerr << "Failed to initialise default shaders." << std::endl;
return false;
}
m_StartingMode = _videoMode;
m_Initialised = true;
return true;
}
void Application::update(float _delta) {
if (m_Scene != nullptr) {
m_Scene->update(_delta);
}
}
void Application::render(RenderTarget& _target, float _alpha) {
RenderInfo info{};
info.projection = Mat4x4::Orthographic3D(0.0f, static_cast<float>(_target.getSize().x), static_cast<float>(_target.getSize().y), 0.0f, -1.0f, +1.0f);
info.alpha = _alpha;
m_Window.clear();
if (m_Scene != nullptr) {
m_Scene->render(_target, info);
}
m_Window.display();
}
void Application::start() {
if (!m_Initialised) {
std::cerr << "Cannot start application without initialising it." << std::endl;
return;
}
m_Running = true;
Clock clock{};
const float delta = 1.0f / 60.0f;
float accumulator = 0.0f;
float statsAccumulator = 0.0f;
unsigned int fps = 0;
unsigned int ups = 0;
while (m_Running) {
float frameTime = clock.restart<float>();
if (frameTime > 0.5f) {
frameTime = 0.5f;
}
accumulator += frameTime;
statsAccumulator += frameTime;
if (statsAccumulator >= 1.0f) {
//std::cout << "FPS: " << fps << " UPS: " << ups << std::endl;
statsAccumulator -= 1.0f;
fps = 0;
ups = 0;
}
while (accumulator >= delta) {
ze::Event event;
m_Window.pumpEvents();
while (m_Window.pollEvent(event)) {
if (event.type == ze::Event::EventType::WindowClosed) {
stop();
}
if (m_Scene != nullptr) {
m_Scene->handleEvent(event);
}
}
// Update
update(delta);
ups++;
accumulator -= delta;
}
// Render
render(m_Window, accumulator / delta);
fps++;
}
m_Window.close();
}
void Application::stop() {
m_Running = false;
}
void Application::setScene(Scene* _scene) {
m_Scene = _scene;
}
RenderWindow& Application::getWindow() {
return m_Window;
}
const RenderWindow& Application::getWindow() const {
return m_Window;
}
}
| 23.052632 | 151 | 0.664637 | MarkRDavison |
82577a9d827055ed131d67f1d8ff8595c7247d5c | 550 | cpp | C++ | GraphicsProject/IntRect.cpp | Megarev/TypeArt | 68b2ce6b69ff3bc61f0090bab14bfac962875a74 | [
"MIT"
] | 2 | 2020-07-06T12:09:30.000Z | 2020-10-22T08:47:39.000Z | IntRect.cpp | Megarev/TypeArt | 68b2ce6b69ff3bc61f0090bab14bfac962875a74 | [
"MIT"
] | null | null | null | IntRect.cpp | Megarev/TypeArt | 68b2ce6b69ff3bc61f0090bab14bfac962875a74 | [
"MIT"
] | null | null | null | #include "IntRect.h"
IntRect::IntRect() {}
IntRect::IntRect(int x, int y, int w, int h) {
pos = { x, y };
size = { w, h };
}
bool IntRect::IsPointInBounds(const olc::vi2d& point) {
return (point.x > pos.x && point.y > pos.y && point.x < (pos.x + size.x) && point.y < (pos.y + size.y));
}
void IntRect::SetPosition(const olc::vi2d& p) {
pos = p;
}
void IntRect::SetSize(const olc::vi2d& s) {
size = s;
}
olc::vi2d IntRect::GetPosition() const {
return pos;
}
olc::vi2d IntRect::GetSize() const {
return size;
} | 19.642857 | 106 | 0.58 | Megarev |
8266f26ac392da4aaaae6e1ab7eb34d945c946a2 | 5,736 | cpp | C++ | Project_JTF/Intermediate/Build/Win64/UE4Editor/Inc/Project_JTF/C_Recruit.gen.cpp | wnrmsah328/Project_JTF | 72ff1efb116ce19f0575c3db4f99c860ddae26e8 | [
"MIT"
] | null | null | null | Project_JTF/Intermediate/Build/Win64/UE4Editor/Inc/Project_JTF/C_Recruit.gen.cpp | wnrmsah328/Project_JTF | 72ff1efb116ce19f0575c3db4f99c860ddae26e8 | [
"MIT"
] | null | null | null | Project_JTF/Intermediate/Build/Win64/UE4Editor/Inc/Project_JTF/C_Recruit.gen.cpp | wnrmsah328/Project_JTF | 72ff1efb116ce19f0575c3db4f99c860ddae26e8 | [
"MIT"
] | null | null | null | // Copyright Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "Project_JTF/01_Player_Character/C_Recruit.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeC_Recruit() {}
// Cross Module References
PROJECT_JTF_API UClass* Z_Construct_UClass_AC_Recruit_NoRegister();
PROJECT_JTF_API UClass* Z_Construct_UClass_AC_Recruit();
ENGINE_API UClass* Z_Construct_UClass_ACharacter();
UPackage* Z_Construct_UPackage__Script_Project_JTF();
ENGINE_API UClass* Z_Construct_UClass_UCameraComponent_NoRegister();
ENGINE_API UClass* Z_Construct_UClass_USkeletalMeshComponent_NoRegister();
// End Cross Module References
void AC_Recruit::StaticRegisterNativesAC_Recruit()
{
}
UClass* Z_Construct_UClass_AC_Recruit_NoRegister()
{
return AC_Recruit::StaticClass();
}
struct Z_Construct_UClass_AC_Recruit_Statics
{
static UObject* (*const DependentSingletons[])();
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_FPCamera_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_FPCamera;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_FPMesh_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_FPMesh;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_AC_Recruit_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_ACharacter,
(UObject* (*)())Z_Construct_UPackage__Script_Project_JTF,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AC_Recruit_Statics::Class_MetaDataParams[] = {
{ "HideCategories", "Navigation" },
{ "IncludePath", "01_Player_Character/C_Recruit.h" },
{ "ModuleRelativePath", "01_Player_Character/C_Recruit.h" },
};
#endif
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AC_Recruit_Statics::NewProp_FPCamera_MetaData[] = {
{ "Category", "C_Recruit" },
{ "EditInline", "true" },
{ "ModuleRelativePath", "01_Player_Character/C_Recruit.h" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_AC_Recruit_Statics::NewProp_FPCamera = { "FPCamera", nullptr, (EPropertyFlags)0x00400000000b0009, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AC_Recruit, FPCamera), Z_Construct_UClass_UCameraComponent_NoRegister, METADATA_PARAMS(Z_Construct_UClass_AC_Recruit_Statics::NewProp_FPCamera_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_AC_Recruit_Statics::NewProp_FPCamera_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AC_Recruit_Statics::NewProp_FPMesh_MetaData[] = {
{ "Category", "Mesh" },
{ "EditInline", "true" },
{ "ModuleRelativePath", "01_Player_Character/C_Recruit.h" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_AC_Recruit_Statics::NewProp_FPMesh = { "FPMesh", nullptr, (EPropertyFlags)0x00400000000b0009, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AC_Recruit, FPMesh), Z_Construct_UClass_USkeletalMeshComponent_NoRegister, METADATA_PARAMS(Z_Construct_UClass_AC_Recruit_Statics::NewProp_FPMesh_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_AC_Recruit_Statics::NewProp_FPMesh_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_AC_Recruit_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AC_Recruit_Statics::NewProp_FPCamera,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AC_Recruit_Statics::NewProp_FPMesh,
};
const FCppClassTypeInfoStatic Z_Construct_UClass_AC_Recruit_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<AC_Recruit>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_AC_Recruit_Statics::ClassParams = {
&AC_Recruit::StaticClass,
"Game",
&StaticCppClassTypeInfo,
DependentSingletons,
nullptr,
Z_Construct_UClass_AC_Recruit_Statics::PropPointers,
nullptr,
UE_ARRAY_COUNT(DependentSingletons),
0,
UE_ARRAY_COUNT(Z_Construct_UClass_AC_Recruit_Statics::PropPointers),
0,
0x009000A4u,
METADATA_PARAMS(Z_Construct_UClass_AC_Recruit_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_AC_Recruit_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_AC_Recruit()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_AC_Recruit_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(AC_Recruit, 1211598298);
template<> PROJECT_JTF_API UClass* StaticClass<AC_Recruit>()
{
return AC_Recruit::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_AC_Recruit(Z_Construct_UClass_AC_Recruit, &AC_Recruit::StaticClass, TEXT("/Script/Project_JTF"), TEXT("AC_Recruit"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(AC_Recruit);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
| 49.025641 | 507 | 0.806311 | wnrmsah328 |
8266f59ed6df71e87481b43c9e88fa8d05ecc0a9 | 2,956 | cpp | C++ | src/common/fpmath_mode.cpp | JackAKirk/oneDNN | 432c3f0c1c265a0fa96aa46c256d150ea670eb5a | [
"Apache-2.0"
] | 971 | 2020-04-03T19:48:05.000Z | 2022-03-31T19:42:43.000Z | src/common/fpmath_mode.cpp | JackAKirk/oneDNN | 432c3f0c1c265a0fa96aa46c256d150ea670eb5a | [
"Apache-2.0"
] | 583 | 2020-04-04T02:37:25.000Z | 2022-03-31T00:12:03.000Z | src/common/fpmath_mode.cpp | JackAKirk/oneDNN | 432c3f0c1c265a0fa96aa46c256d150ea670eb5a | [
"Apache-2.0"
] | 295 | 2020-04-03T20:07:00.000Z | 2022-03-30T13:10:15.000Z | /*******************************************************************************
* Copyright 2021 Intel Corporation
*
* 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 "oneapi/dnnl/dnnl.h"
#include "c_types_map.hpp"
#include "utils.hpp"
namespace dnnl {
namespace impl {
static setting_t<fpmath_mode_t> default_fpmath {fpmath_mode::strict};
void init_fpmath_mode() {
const int len = 10;
char val[len];
static int fpmath_mode_val = getenv("DNNL_DEFAULT_FPMATH_MODE", val, len);
if (fpmath_mode_val > 0) {
if (std::strcmp(val, "STRICT") == 0)
default_fpmath.set(fpmath_mode::strict, true);
if (std::strcmp(val, "BF16") == 0)
default_fpmath.set(fpmath_mode::bf16, true);
if (std::strcmp(val, "F16") == 0)
default_fpmath.set(fpmath_mode::f16, true);
if (std::strcmp(val, "ANY") == 0)
default_fpmath.set(fpmath_mode::any, true);
}
}
status_t check_fpmath_mode(fpmath_mode_t mode) {
if (utils::one_of(mode, fpmath_mode::strict, fpmath_mode::bf16,
fpmath_mode::f16, fpmath_mode::any))
return status::success;
return status::invalid_arguments;
}
bool is_fpsubtype(data_type_t sub_dt, data_type_t dt) {
using namespace dnnl::impl::utils;
using namespace dnnl::impl::data_type;
switch (dt) {
case f32: return one_of(sub_dt, f32, bf16, f16);
case bf16: return one_of(sub_dt, bf16);
case f16: return one_of(sub_dt, f16);
default: return false;
}
}
fpmath_mode_t get_fpmath_mode() {
init_fpmath_mode();
auto mode = default_fpmath.get();
// Should always be proper, since no way to set invalid mode
assert(check_fpmath_mode(mode) == status::success);
return mode;
}
} // namespace impl
} // namespace dnnl
dnnl_status_t dnnl_set_default_fpmath_mode(dnnl_fpmath_mode_t mode) {
using namespace dnnl::impl;
auto st = check_fpmath_mode(mode);
if (st == status::success) default_fpmath.set(mode);
return st;
}
dnnl_status_t dnnl_get_default_fpmath_mode(dnnl_fpmath_mode_t *mode) {
using namespace dnnl::impl;
if (mode == nullptr) return status::invalid_arguments;
auto m = get_fpmath_mode();
// Should always be proper, since no way to set invalid mode
auto st = check_fpmath_mode(m);
if (st == status::success) *mode = m;
return st;
}
| 33.590909 | 80 | 0.647835 | JackAKirk |
826742b49e2b730f4f29c2d9c01169d3ad43944d | 2,214 | hpp | C++ | include/depthai/openvino/OpenVINO.hpp | diablodale/depthai-core | 9f5d0861c07fea580c652f435c7e1422473ae079 | [
"MIT"
] | null | null | null | include/depthai/openvino/OpenVINO.hpp | diablodale/depthai-core | 9f5d0861c07fea580c652f435c7e1422473ae079 | [
"MIT"
] | null | null | null | include/depthai/openvino/OpenVINO.hpp | diablodale/depthai-core | 9f5d0861c07fea580c652f435c7e1422473ae079 | [
"MIT"
] | null | null | null | #pragma once
#include <algorithm>
#include <exception>
#include <map>
#include <string>
#include <utility>
#include <vector>
namespace dai {
/// Support for basic OpenVINO related actions like version identification of neural network blobs,...
class OpenVINO {
public:
/// OpenVINO Version supported version information
enum Version { VERSION_2020_1, VERSION_2020_2, VERSION_2020_3, VERSION_2020_4, VERSION_2021_1, VERSION_2021_2 };
/**
* @returns Supported versions
*/
static std::vector<Version> getVersions();
/**
* Returns string representation of a given version
* @param version OpenVINO version
* @returns Name of a given version
*/
static std::string getVersionName(Version version);
/**
* Creates Version from string representation.
* Throws if not possible.
* @param versionString Version as string
* @returns Version object if successful
*/
static Version parseVersionName(const std::string& versionString);
/**
* Returns a list of potentionally supported versions for a specified blob major and minor versions.
* @param majorVersion Major version from OpenVINO blob
* @param minorVersion Minor version from OpenVINO blob
* @returns Vector of potentionally supported versions
*/
static std::vector<Version> getBlobSupportedVersions(std::uint32_t majorVersion, std::uint32_t minorVersion);
/**
* Returns latest potentionally supported version by a given blob version.
* @param majorVersion Major version from OpenVINO blob
* @param minorVersion Minor version from OpenVINO blob
* @returns Latest potentionally supported version
*/
static Version getBlobLatestSupportedVersion(std::uint32_t majorVersion, std::uint32_t minorVersion);
/**
* Checks whether two blob versions are compatible
*/
static bool areVersionsBlobCompatible(Version v1, Version v2);
private:
static const std::map<std::pair<std::uint32_t, std::uint32_t>, Version> blobVersionToLatestOpenvinoMapping;
static const std::map<std::pair<std::uint32_t, std::uint32_t>, std::vector<Version>> blobVersionToOpenvinoMapping;
};
} // namespace dai
| 34.061538 | 118 | 0.720416 | diablodale |
826f35e882c0422d04e9be2dd267f4bc1e01f4a8 | 2,584 | cxx | C++ | Code/Numerics/Statistics/itkDenseFrequencyContainer.cxx | dtglidden/ITK | ef0c16fee4fac904d6ab706b8f7d438d4062cd96 | [
"BSD-3-Clause"
] | 1 | 2017-07-31T18:41:02.000Z | 2017-07-31T18:41:02.000Z | Code/Numerics/Statistics/itkDenseFrequencyContainer.cxx | dtglidden/ITK | ef0c16fee4fac904d6ab706b8f7d438d4062cd96 | [
"BSD-3-Clause"
] | null | null | null | Code/Numerics/Statistics/itkDenseFrequencyContainer.cxx | dtglidden/ITK | ef0c16fee4fac904d6ab706b8f7d438d4062cd96 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkDenseFrequencyContainer.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#include "itkDenseFrequencyContainer.h"
namespace itk{
namespace Statistics{
DenseFrequencyContainer
::DenseFrequencyContainer()
{
m_FrequencyContainer = FrequencyContainerType::New();
m_TotalFrequency = NumericTraits< TotalFrequencyType >::Zero;
}
void
DenseFrequencyContainer
::Initialize(unsigned long length)
{
m_FrequencyContainer->Reserve(length);
this->SetToZero();
}
void
DenseFrequencyContainer
::SetToZero()
{
m_FrequencyContainer->Fill( NumericTraits< FrequencyType >::Zero );
m_TotalFrequency = NumericTraits< TotalFrequencyType >::Zero;
}
bool
DenseFrequencyContainer
::SetFrequency(const InstanceIdentifier id, const FrequencyType value)
{
if( id >= m_FrequencyContainer->Size() )
{
return false;
}
FrequencyType frequency = this->GetFrequency(id);
(*m_FrequencyContainer)[id] = value;
m_TotalFrequency += (value - frequency);
return true;
}
DenseFrequencyContainer::FrequencyType
DenseFrequencyContainer
::GetFrequency(const InstanceIdentifier id) const
{
if( id >= m_FrequencyContainer->Size() )
{
return NumericTraits< FrequencyType >::Zero;
}
return (*m_FrequencyContainer)[id];
}
bool
DenseFrequencyContainer
::IncreaseFrequency(const InstanceIdentifier id, const FrequencyType value)
{
if( id >= m_FrequencyContainer->Size() )
{
return false;
}
FrequencyType frequency = this->GetFrequency(id);
const FrequencyType largestIntegerThatFitsInFloat = 16777216;
if( largestIntegerThatFitsInFloat - frequency < value )
{
itkExceptionMacro("Frequency container saturated for Instance ");
}
else
{
(*m_FrequencyContainer)[id] = frequency + value;
}
m_TotalFrequency += value;
return true;
}
void
DenseFrequencyContainer
::PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf(os,indent);
}
} // end of namespace Statistics
} // end of namespace itk
| 24.609524 | 76 | 0.693498 | dtglidden |
8279076fdeb9f2e7db2014cead15d16883b8b1da | 8,371 | hpp | C++ | poc/tstvc2/thread_cv.hpp | upenn-acg/barracuda | db2549b62593934d81e3e8141302dd344f85a407 | [
"BSD-3-Clause"
] | 3 | 2020-05-08T04:37:48.000Z | 2021-01-31T15:57:15.000Z | poc/tstvc2/thread_cv.hpp | upenn-acg/barracuda | db2549b62593934d81e3e8141302dd344f85a407 | [
"BSD-3-Clause"
] | 1 | 2020-11-22T18:24:12.000Z | 2020-11-22T18:24:12.000Z | poc/tstvc2/thread_cv.hpp | upenn-acg/barracuda | db2549b62593934d81e3e8141302dd344f85a407 | [
"BSD-3-Clause"
] | 2 | 2019-12-04T05:43:51.000Z | 2019-12-04T07:57:31.000Z | #pragma once
#include <stdint.h>
#include <algorithm>
#include "debug.h"
typedef uint64_t tid_t;
struct thread_cv
{
public:
void diverge_from(thread_cv& other_cv, uint32_t active_mask, uint32_t epoch)
{
release();
// fast path
if (other_cv.b.flags == MODE_BASIC && other_cv.b.warp == 0)
{
b.flags = MODE_BASIC;
b.block = other_cv.b.block;
b.warp = epoch;
return;
}
// slow path
uint32_t mask = 1;
warp_level_cv *wcv = nullptr, *owcv = nullptr;
total_level_cv *tcv = nullptr, *otcv = nullptr;
// XXX: no need to free & release in many cases
switch (other_cv.b.flags)
{
case MODE_BASIC:
wcv = make_wcv();
for (int j = 0; j < WARP_SIZE; ++j, mask <<= 1)
wcv->epochs[j] = (active_mask & mask) ? epoch : other_cv.b.warp;
wcv->block = other_cv.b.block;
break;
case MODE_WARP_CV:
wcv = make_wcv();
owcv = (warp_level_cv*)other_cv.p.ptr;
wcv->block = owcv->block;
for (int j = 0; j < WARP_SIZE; ++j, mask <<= 1)
wcv->epochs[j] = (active_mask & mask) ? epoch : owcv->epochs[j];
break;
case MODE_TOTAL_CV:
tcv = make_tcv();
otcv = (total_level_cv*)other_cv.p.ptr;
tcv->block = otcv->block;
tcv->cv_epochs.insert(otcv->cv_epochs.begin(), otcv->cv_epochs.end());
for (int j = 0; j < WARP_SIZE; ++j, mask <<= 1)
tcv->epochs[j] = (active_mask & mask) ? epoch : otcv->epochs[j];
break;
}
}
void max_of(thread_cv& other)
{
warp_level_cv *wcv = nullptr, *owcv = nullptr;
total_level_cv *tcv = nullptr, *otcv = nullptr;
bool all_same = true;
int last = 0;
switch (other.b.flags)
{
case MODE_BASIC:
switch (b.flags)
{
case MODE_BASIC:
if (b.warp < other.b.warp)
b.warp = other.b.warp;
break;
case MODE_WARP_CV:
wcv = (warp_level_cv*)p.ptr;
for (int i = 0; i < WARP_SIZE; ++i)
{
if (wcv->epochs[i] < other.b.warp)
wcv->epochs[i] = other.b.flags;
if (all_same)
{
if (i > 0)
{
if (last != wcv->epochs[i])
all_same = false;
}
else
last = wcv->epochs[0];
}
}
if (wcv->block < b.block)
wcv->block = b.block;
if (all_same)
make_basic(last);
break;
case MODE_TOTAL_CV:
// XXX: add inflation
tcv = (total_level_cv*)p.ptr;
if (tcv->block < b.block)
tcv->block = b.block;
for (int i = 0; i < WARP_SIZE; ++i)
{
if (tcv->epochs[i] < other.b.warp)
tcv->epochs[i] = other.b.flags;
}
break;
}
break;
case MODE_WARP_CV:
owcv = (warp_level_cv*)other.p.ptr;
switch (b.flags)
{
case MODE_BASIC:
{
basic cb = b;
wcv = make_wcv();
wcv->block = std::max(cb.block, owcv->block);
for (int i = 0; i < WARP_SIZE; ++i)
{
wcv->epochs[i] = (owcv->epochs[i] < cb.warp) ? cb.warp : owcv->epochs[i];
if (all_same)
{
if (i > 0)
{
if (last != wcv->epochs[i])
all_same = false;
}
else
last = wcv->epochs[0];
}
}
if (all_same)
make_basic(last);
}
break;
case MODE_WARP_CV:
wcv = (warp_level_cv*)p.ptr;
wcv->block = std::max(wcv->block, owcv->block);
for (int i = 0; i < WARP_SIZE; ++i)
{
if (wcv->epochs[i] < owcv->epochs[i])
wcv->epochs[i] = owcv->epochs[i];
if (all_same)
{
if (i > 0)
{
if (last != wcv->epochs[i])
all_same = false;
}
else
last = wcv->epochs[0];
}
}
if (all_same)
make_basic(last);
break;
case MODE_TOTAL_CV:
tcv = (total_level_cv*)p.ptr;
tcv->block = std::max(tcv->block, owcv->block);
for (int i = 0; i < WARP_SIZE; ++i)
{
if (tcv->epochs[i] < owcv->epochs[i])
tcv->epochs[i] = owcv->epochs[i];
}
break;
}
break;
case MODE_TOTAL_CV:
otcv = (total_level_cv*)other.p.ptr;
switch (b.flags)
{
case MODE_BASIC:
{
basic cb = b;
tcv = make_tcv();
tcv->block = std::max(cb.block, otcv->block);
memcpy(tcv->epochs, otcv->epochs, sizeof(tcv->epochs));
tcv->cv_epochs.insert(otcv->cv_epochs.begin(), otcv->cv_epochs.end());
for (int i = 0; i < WARP_SIZE; ++i)
tcv->epochs[i] = (otcv->epochs[i] < cb.warp) ? cb.warp : otcv->epochs[i];
}
break;
case MODE_WARP_CV:
wcv = (warp_level_cv*)p.ptr;
make_tcv();
tcv->cv_epochs.insert(otcv->cv_epochs.begin(), otcv->cv_epochs.end());
tcv->block = std::max(wcv->block, otcv->block);
for (int i = 0; i < WARP_SIZE; ++i)
{
if (tcv->epochs[i] < otcv->epochs[i])
tcv->epochs[i] = otcv->epochs[i];
}
delete wcv;
break;
case MODE_TOTAL_CV:
tcv = (total_level_cv*)p.ptr;
tcv->block = std::max(tcv->block, otcv->block);
for (int i = 0; i < WARP_SIZE; ++i)
{
if (tcv->epochs[i] < otcv->epochs[i])
tcv->epochs[i] = otcv->epochs[i];
}
for (auto it = otcv->cv_epochs.begin();
it != otcv->cv_epochs.end();
++it)
{
auto mine = tcv->cv_epochs.find(it->first);
if (mine == tcv->cv_epochs.end())
tcv->cv_epochs.insert(*it);
else
mine->second = std::max(mine->second, it->second);
}
break;
}
break;
}
}
void block_max_of(tid_t my_tid, uint32_t bcv)
{
total_level_cv* tcv;
int my_block;
switch (b.flags)
{
case MODE_BASIC:
SLIM_ASSERT(b.warp <= bcv);
SLIM_ASSERT(b.block <= bcv);
b.block = bcv;
b.warp = bcv;
break;
case MODE_WARP_CV:
release();
b.flags = MODE_BASIC;
b.warp = bcv;
b.block = bcv;
break;
case MODE_TOTAL_CV:
tcv = (total_level_cv*)p.ptr;
my_block = (int)(my_tid >> BLOCK_SHIFT);
bool deflate = true;
for(auto it = tcv->cv_epochs.begin(); it != tcv->cv_epochs.end(); )
{
auto cur = it ++;
int curb = (int)(cur->first >> BLOCK_SHIFT);
if (curb != my_block)
deflate = false;
else
tcv->cv_epochs.erase(cur);
}
if (deflate)
{
release();
b.flags = MODE_BASIC;
b.warp = bcv;
b.block = bcv;
}
else
{
tcv->block = bcv;
for (int i = 0; i < WARP_SIZE; ++i)
{
SLIM_ASSERT(tcv->epochs[i] <= bcv);
tcv->epochs[i] = bcv;
}
}
}
}
enum {
ZERO_EPOCH = 0,
};
uint32_t get_epoch(tid_t mytid, tid_t tid)
{
return get_epoch(mytid, tid, (((mytid >> WARP_SHIFT) == (tid >> WARP_SHIFT))));
}
uint32_t get_epoch(tid_t mytid, tid_t tid, bool in_warp)
{
warp_level_cv *wcv;
total_level_cv* tcv;
switch (b.flags)
{
case MODE_BASIC:
return in_warp ? b.warp : b.block;
case MODE_WARP_CV:
wcv = (warp_level_cv*)p.ptr;
return in_warp ? wcv->epochs[tid & ~((1 << WARP_SHIFT) - 1)] : wcv->block;
case MODE_TOTAL_CV:
tcv = (total_level_cv*)p.ptr;
uint32_t base = 0;
if (mytid >> BLOCK_SHIFT == tid >> BLOCK_SHIFT)
base = tcv->block;
auto it = tcv->cv_epochs.find(tid);
if (it != tcv->cv_epochs.end())
{
uint32_t value = it->second;
if (value > base)
return value;
}
return base;
}
SLIM_ASSERT(false);
return 0;
}
FINLINE void release()
{
warp_level_cv* wcv;
total_level_cv* tcv;
switch (b.flags)
{
case MODE_BASIC:
break;
case MODE_WARP_CV:
wcv = (warp_level_cv*)p.ptr;
delete wcv;
break;
case MODE_TOTAL_CV:
tcv = (total_level_cv*)p.ptr;
delete tcv;
break;
}
}
private:
FINLINE void* get_ptr()
{
return (void*)(uintptr_t)p.ptr;
}
private:
enum { MODE_BASIC = 0 };
enum { MODE_WARP_CV = 1 };
enum { MODE_TOTAL_CV = 2 };
enum { WARP_SIZE = 32 };
struct basic
{
uint32_t warp;
uint32_t block : 30;
uint32_t flags : 2;
};
struct pointer
{
uint64_t ptr : 62;
uint64_t flags : 2;
};
struct warp_level_cv
{
uint32_t block;
uint32_t epochs[WARP_SIZE];
};
struct total_level_cv : public warp_level_cv
{
std::unordered_map<uint64_t, uint32_t> cv_epochs;
};
private:
FINLINE warp_level_cv* get_warp_ptr()
{
return (warp_level_cv*)(uintptr_t)p.ptr;
}
void make_basic(uint32_t warp)
{
release();
b.flags = MODE_BASIC;
b.warp = warp;
}
warp_level_cv *make_wcv()
{
warp_level_cv *wcv = new warp_level_cv();
p.ptr = (uintptr_t)wcv;
p.flags = MODE_WARP_CV;
return wcv;
}
total_level_cv *make_tcv()
{
total_level_cv *tcv = new total_level_cv();
p.ptr = (uintptr_t)tcv;
p.flags = MODE_TOTAL_CV;
return tcv;
}
private:
union
{
basic b;
pointer p;
};
};
| 20.618227 | 81 | 0.575797 | upenn-acg |
827921607fc85590c89c8f2b58bd38e00a518dea | 861 | cpp | C++ | Raven/src/Client/Chunk/ChunkColumn.cpp | IridescentRose/Raven-Client | e39a88eef8d56067387acaaad19ec44ddaab3869 | [
"MIT"
] | 10 | 2020-10-05T23:11:25.000Z | 2022-01-30T13:22:33.000Z | Raven/src/Client/Chunk/ChunkColumn.cpp | IridescentRose/Raven-Client | e39a88eef8d56067387acaaad19ec44ddaab3869 | [
"MIT"
] | 3 | 2020-07-09T16:08:54.000Z | 2020-08-05T19:58:41.000Z | Raven/src/Client/Chunk/ChunkColumn.cpp | NT-Bourgeois-Iridescence-Technologies/Raven-Client | e39a88eef8d56067387acaaad19ec44ddaab3869 | [
"MIT"
] | 2 | 2021-02-06T08:01:26.000Z | 2021-06-19T07:39:59.000Z | #include "ChunkColumn.h"
#include <iostream>
namespace Minecraft::Internal::Chunks {
ChunkColumn::ChunkColumn(int x, int z)
{
cX = x;
cZ = z;
sections.clear();
for (int xx = 0; xx < CHUNK_SECTION_LENGTH; xx++) {
for (int yy = 0; yy < CHUNK_SECTION_LENGTH; yy++) {
biomes[xx][yy] = 1;
}
}
}
ChunkColumn::~ChunkColumn()
{
for (auto chnk : sections) {
delete chnk;
}
}
ChunkSection* ChunkColumn::getSection(uint8_t y)
{
for (auto chnk : sections) {
if (chnk->getY() == y) {
return chnk;
}
}
return NULL;
}
void ChunkColumn::addSection(ChunkSection* chnks)
{
chnks->cX = cX;
chnks->cZ = cZ;
if (chnks->isEmpty()) {
delete chnks;
}
else {
sections.push_back(chnks);
}
}
void ChunkColumn::clearSections()
{
for (auto chnk : sections) {
delete chnk;
}
sections.clear();
}
} | 14.844828 | 54 | 0.598142 | IridescentRose |
82794634d1d2b6b12024c383212b747ad20578c2 | 3,242 | cpp | C++ | test/unit/math/mix/meta/require_generics_test.cpp | christophernhill/math | dc41aba296d592c7099be15eed6ba136d0f140b3 | [
"BSD-3-Clause"
] | null | null | null | test/unit/math/mix/meta/require_generics_test.cpp | christophernhill/math | dc41aba296d592c7099be15eed6ba136d0f140b3 | [
"BSD-3-Clause"
] | null | null | null | test/unit/math/mix/meta/require_generics_test.cpp | christophernhill/math | dc41aba296d592c7099be15eed6ba136d0f140b3 | [
"BSD-3-Clause"
] | null | null | null | #include <stan/math/fwd.hpp>
#include <stan/math/rev.hpp>
#include <stan/math/prim/scal.hpp>
#include <test/unit/math/require_util.hpp>
#include <gtest/gtest.h>
#include <type_traits>
#include <string>
TEST(requires_mix_scal, var_or_fvar_mix_test) {
using stan::math::fvar;
using stan::math::var;
using stan::test::require_scal_checker;
require_scal_checker<stan::require_var_or_fvar_t, var, fvar<double>>::unary();
}
TEST(requires_mix_scal, var_or_fvar_not_mix_test) {
using stan::math::fvar;
using stan::math::var;
using stan::test::require_scal_checker;
require_scal_checker<stan::require_not_var_or_fvar_t, var,
fvar<double>>::not_unary();
}
TEST(requires_mix_scal, var_or_fvar_all_mix_test) {
using stan::math::fvar;
using stan::math::var;
using stan::test::require_scal_checker;
require_scal_checker<stan::require_all_var_or_fvar_t, var,
fvar<double>>::all();
}
TEST(requires_mix_scal, var_or_fvar_all_not_mix_test) {
using stan::math::fvar;
using stan::math::var;
using stan::test::require_scal_checker;
require_scal_checker<stan::require_all_not_var_or_fvar_t, var,
fvar<double>>::all_not();
}
TEST(requires_mix_scal, var_or_fvar_any_mix_test) {
using stan::math::fvar;
using stan::math::var;
using stan::test::require_scal_checker;
require_scal_checker<stan::require_any_var_or_fvar_t, var,
fvar<double>>::any();
}
TEST(requires_mix_scal, var_or_fvar_any_not_mix_test) {
using stan::math::fvar;
using stan::math::var;
using stan::test::require_scal_checker;
require_scal_checker<stan::require_any_not_var_or_fvar_t, var,
fvar<double>>::any_not();
}
TEST(requires_mix_scal, stan_scalar_mix_test) {
using stan::math::fvar;
using stan::math::var;
using stan::test::require_scal_checker;
require_scal_checker<stan::require_stan_scalar_t, var, fvar<double>>::unary();
}
TEST(requires_mix_scal, stan_scalar_not_mix_test) {
using stan::math::fvar;
using stan::math::var;
using stan::test::require_scal_checker;
require_scal_checker<stan::require_not_stan_scalar_t, var,
fvar<double>>::not_unary();
}
TEST(requires_mix_scal, stan_scalar_all_mix_test) {
using stan::math::fvar;
using stan::math::var;
using stan::test::require_scal_checker;
require_scal_checker<stan::require_all_stan_scalar_t, var,
fvar<double>>::all();
}
TEST(requires_mix_scal, stan_scalar_all_not_mix_test) {
using stan::math::fvar;
using stan::math::var;
using stan::test::require_scal_checker;
require_scal_checker<stan::require_all_not_stan_scalar_t, var,
fvar<double>>::all_not();
}
TEST(requires_mix_scal, stan_scalar_any_mix_test) {
using stan::math::fvar;
using stan::math::var;
using stan::test::require_scal_checker;
require_scal_checker<stan::require_any_stan_scalar_t, var,
fvar<double>>::any();
}
TEST(requires_mix_scal, stan_scalar_any_not_mix_test) {
using stan::math::fvar;
using stan::math::var;
using stan::test::require_scal_checker;
require_scal_checker<stan::require_any_not_stan_scalar_t, var,
fvar<double>>::any_not();
}
| 35.23913 | 80 | 0.712832 | christophernhill |
8279c566bca1640475094050f03e8cc448c85851 | 6,252 | cpp | C++ | glsl_compiler/glslang/MachineIndependent/limits.cpp | FAETHER/VEther | 081f0df2c4279c21e1d55bfc336a43bc96b5f1c3 | [
"MIT"
] | 3 | 2019-12-07T23:57:47.000Z | 2019-12-31T19:46:41.000Z | glsl_compiler/glslang/MachineIndependent/limits.cpp | FAETHER/VEther | 081f0df2c4279c21e1d55bfc336a43bc96b5f1c3 | [
"MIT"
] | null | null | null | glsl_compiler/glslang/MachineIndependent/limits.cpp | FAETHER/VEther | 081f0df2c4279c21e1d55bfc336a43bc96b5f1c3 | [
"MIT"
] | null | null | null | //
// Copyright (C) 2013 LunarG, Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDERS 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.
//
//
// Do sub tree walks for
// 1) inductive loop bodies to see if the inductive variable is modified
// 2) array-index expressions to see if they are "constant-index-expression"
//
// These are per Appendix A of ES 2.0:
//
// "Within the body of the loop, the loop index is not statically assigned to nor is it used as the
// argument to a function out or inout parameter."
//
// "The following are constant-index-expressions:
// - Constant expressions
// - Loop indices as defined in section 4
// - Expressions composed of both of the above"
//
// N.B.: assuming the last rule excludes function calls
//
#include "ParseHelper.h"
namespace glslang
{
//
// The inductive loop-body traverser.
//
// Just look at things that might modify the loop index.
//
class TInductiveTraverser : public TIntermTraverser
{
public:
TInductiveTraverser(int id, TSymbolTable& st)
: loopId(id), symbolTable(st), bad(false) { }
virtual bool visitBinary(TVisit, TIntermBinary* node);
virtual bool visitUnary(TVisit, TIntermUnary* node);
virtual bool visitAggregate(TVisit, TIntermAggregate* node);
int loopId; // unique ID of the symbol that's the loop inductive variable
TSymbolTable& symbolTable;
bool bad;
TSourceLoc badLoc;
protected:
TInductiveTraverser(TInductiveTraverser&);
TInductiveTraverser& operator=(TInductiveTraverser&);
};
// check binary operations for those modifying the loop index
bool TInductiveTraverser::visitBinary(TVisit /* visit */, TIntermBinary* node)
{
if (node->modifiesState() && node->getLeft()->getAsSymbolNode() &&
node->getLeft()->getAsSymbolNode()->getId() == loopId)
{
bad = true;
badLoc = node->getLoc();
}
return true;
}
// check unary operations for those modifying the loop index
bool TInductiveTraverser::visitUnary(TVisit /* visit */, TIntermUnary* node)
{
if (node->modifiesState() && node->getOperand()->getAsSymbolNode() &&
node->getOperand()->getAsSymbolNode()->getId() == loopId)
{
bad = true;
badLoc = node->getLoc();
}
return true;
}
// check function calls for arguments modifying the loop index
bool TInductiveTraverser::visitAggregate(TVisit /* visit */, TIntermAggregate* node)
{
if (node->getOp() == EOpFunctionCall)
{
// see if an out or inout argument is the loop index
const TIntermSequence& args = node->getSequence();
for (int i = 0; i < (int)args.size(); ++i)
{
if (args[i]->getAsSymbolNode() && args[i]->getAsSymbolNode()->getId() == loopId)
{
TSymbol* function = symbolTable.find(node->getName());
const TType* type = (*function->getAsFunction())[i].type;
if (type->getQualifier().storage == EvqOut ||
type->getQualifier().storage == EvqInOut)
{
bad = true;
badLoc = node->getLoc();
}
}
}
}
return true;
}
//
// External function to call for loop check.
//
void TParseContext::inductiveLoopBodyCheck(TIntermNode* body, int loopId, TSymbolTable& symbolTable)
{
TInductiveTraverser it(loopId, symbolTable);
if (body == nullptr)
return;
body->traverse(&it);
if (it.bad)
error(it.badLoc, "inductive loop index modified", "limitations", "");
}
//
// The "constant-index-expression" tranverser.
//
// Just look at things that can form an index.
//
class TIndexTraverser : public TIntermTraverser
{
public:
TIndexTraverser(const TIdSetType& ids) : inductiveLoopIds(ids), bad(false) { }
virtual void visitSymbol(TIntermSymbol* symbol);
virtual bool visitAggregate(TVisit, TIntermAggregate* node);
const TIdSetType& inductiveLoopIds;
bool bad;
TSourceLoc badLoc;
protected:
TIndexTraverser(TIndexTraverser&);
TIndexTraverser& operator=(TIndexTraverser&);
};
// make sure symbols are inductive-loop indexes
void TIndexTraverser::visitSymbol(TIntermSymbol* symbol)
{
if (inductiveLoopIds.find(symbol->getId()) == inductiveLoopIds.end())
{
bad = true;
badLoc = symbol->getLoc();
}
}
// check for function calls, assuming they are bad; spec. doesn't really say
bool TIndexTraverser::visitAggregate(TVisit /* visit */, TIntermAggregate* node)
{
if (node->getOp() == EOpFunctionCall)
{
bad = true;
badLoc = node->getLoc();
}
return true;
}
//
// External function to call for loop check.
//
void TParseContext::constantIndexExpressionCheck(TIntermNode* index)
{
TIndexTraverser it(inductiveLoopIds);
index->traverse(&it);
if (it.bad)
error(it.badLoc, "Non-constant-index-expression", "limitations", "");
}
} // end namespace glslang
| 29.771429 | 101 | 0.694658 | FAETHER |
827ee22ddbb4d3456f769040caecaafc771e37bd | 5,307 | cpp | C++ | renderer.cpp | nvpro-samples/vk_device_generated_cmds | 7c4ad63e431f7369a7a76769f92baa968fc7156f | [
"Apache-2.0"
] | 20 | 2020-03-17T23:48:47.000Z | 2022-03-29T04:23:59.000Z | renderer.cpp | nvpro-samples/vk_device_generated_cmds | 7c4ad63e431f7369a7a76769f92baa968fc7156f | [
"Apache-2.0"
] | 1 | 2021-01-10T04:50:40.000Z | 2021-01-10T04:50:40.000Z | renderer.cpp | nvpro-samples/vk_device_generated_cmds | 7c4ad63e431f7369a7a76769f92baa968fc7156f | [
"Apache-2.0"
] | 2 | 2020-07-26T06:05:59.000Z | 2021-01-10T00:29:54.000Z | /*
* Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-FileCopyrightText: Copyright (c) 2019-2021 NVIDIA CORPORATION
* SPDX-License-Identifier: Apache-2.0
*/
#include <assert.h>
#include <algorithm>
#include "renderer.hpp"
#include <nvpwindow.hpp>
#include <nvmath/nvmath_glsltypes.h>
#include "common.h"
#pragma pack(1)
namespace generatedcmds
{
//////////////////////////////////////////////////////////////////////////
static void AddItem(std::vector<Renderer::DrawItem>& drawItems, const Renderer::Config& config, const Renderer::DrawItem& di)
{
if (di.range.count) {
drawItems.push_back(di);
}
}
static void FillCache(std::vector<Renderer::DrawItem>& drawItems, const Renderer::Config& config, const CadScene::Object& obj, const CadScene::Geometry& geo, bool solid, int objectIndex)
{
int begin = 0;
const CadScene::DrawRangeCache &cache = solid ? obj.cacheSolid : obj.cacheWire;
for (size_t s = 0; s < cache.state.size(); s++)
{
const CadScene::DrawStateInfo &state = cache.state[s];
for (int d = 0; d < cache.stateCount[s]; d++) {
// evict
Renderer::DrawItem di;
di.geometryIndex = obj.geometryIndex;
di.matrixIndex = state.matrixIndex;
di.materialIndex = state.materialIndex;
di.shaderIndex = state.materialIndex % config.maxShaders;
di.solid = solid;
di.range.offset = cache.offsets[begin + d];
di.range.count = cache.counts[begin + d];
AddItem(drawItems, config, di);
}
begin += cache.stateCount[s];
}
}
static void FillIndividual( std::vector<Renderer::DrawItem>& drawItems, const Renderer::Config& config, const CadScene::Object& obj, const CadScene::Geometry& geo, bool solid, int objectIndex )
{
for (size_t p = 0; p < obj.parts.size(); p++){
const CadScene::ObjectPart& part = obj.parts[p];
const CadScene::GeometryPart& mesh = geo.parts[p];
if (!part.active) continue;
Renderer::DrawItem di;
di.geometryIndex = obj.geometryIndex;
di.matrixIndex = part.matrixIndex;
di.materialIndex = part.materialIndex;
di.shaderIndex = part.materialIndex % config.maxShaders;
di.solid = solid;
di.range = mesh.indexSolid;
AddItem(drawItems, config, di);
}
}
void Renderer::fillDrawItems( std::vector<DrawItem>& drawItems, const CadScene* NV_RESTRICT scene, const Config& config, Stats& stats )
{
bool solid = true;
bool wire = false;
size_t maxObjects = scene->m_objects.size();
size_t from = std::min(maxObjects - 1, size_t(config.objectFrom));
maxObjects = std::min(maxObjects, from + size_t(config.objectNum));
for (size_t i = from; i < maxObjects; i++){
const CadScene::Object& obj = scene->m_objects[i];
const CadScene::Geometry& geo = scene->m_geometry[obj.geometryIndex];
if (config.strategy == STRATEGY_GROUPS){
if (solid) FillCache(drawItems, config, obj, geo, true, int(i));
if (wire) FillCache(drawItems, config, obj, geo, false, int(i));
}
else if (config.strategy == STRATEGY_INDIVIDUAL) {
if (solid) FillIndividual(drawItems, config, obj, geo, true, int(i));
if (wire) FillIndividual(drawItems, config, obj, geo, false, int(i));
}
}
if(config.sorted)
{
std::sort(drawItems.begin(), drawItems.end(), DrawItem_compare_groups);
}
int shaderIndex = -1;
for (size_t i = 0; i < drawItems.size(); i++) {
stats.drawCalls++;
stats.drawTriangles += drawItems[i].range.count / 3;
if (drawItems[i].shaderIndex != shaderIndex) {
stats.shaderBindings++;
shaderIndex = drawItems[i].shaderIndex;
}
}
}
void Renderer::fillRandomPermutation(uint32_t drawCount, uint32_t* permutation, const DrawItem* drawItems, Stats& stats)
{
srand(634523);
for(uint32_t i = 0; i < drawCount; i++)
{
permutation[i] = i;
}
if(drawCount)
{
// not exactly a good way to generate random 32bit ;)
for(uint32_t i = drawCount - 1; i > 0; i--)
{
uint32_t r = 0;
r |= (rand() & 0xFF) << 0;
r |= (rand() & 0xFF) << 8;
r |= (rand() & 0xFF) << 16;
r |= (rand() & 0xFF) << 24;
uint32_t other = r % (i + 1);
std::swap(permutation[i], permutation[other]);
}
int shaderIndex = -1;
stats.shaderBindings = 0;
for(uint32_t i = 0; i < drawCount; i++)
{
uint32_t idx = permutation[i];
if (drawItems[idx].shaderIndex != shaderIndex) {
stats.shaderBindings++;
shaderIndex = drawItems[idx].shaderIndex;
}
}
}
}
}
| 31.217647 | 195 | 0.621443 | nvpro-samples |
827fd90182e5e0265ec2642470a3d2348f3c654f | 5,278 | hh | C++ | elements/loadbalancers/LoadBalancePPC.hh | ANLAB-KAIST/NBA | a093a72af32ccdc041792a01ae65a699294470cd | [
"MIT"
] | 61 | 2015-03-25T04:49:09.000Z | 2020-11-24T08:36:19.000Z | elements/loadbalancers/LoadBalancePPC.hh | ANLAB-KAIST/NBA | a093a72af32ccdc041792a01ae65a699294470cd | [
"MIT"
] | 32 | 2015-04-29T08:20:39.000Z | 2017-02-09T22:49:37.000Z | elements/loadbalancers/LoadBalancePPC.hh | ANLAB-KAIST/NBA | a093a72af32ccdc041792a01ae65a699294470cd | [
"MIT"
] | 11 | 2015-07-24T22:48:05.000Z | 2020-09-10T11:48:47.000Z | #ifndef __NBA_ELEMENT_LOADBALANCEPPC_HH__
#define __NBA_ELEMENT_LOADBALANCEPPC_HH__
#include <nba/element/element.hh>
#include <nba/element/annotation.hh>
#include <nba/framework/loadbalancer.hh>
#include <nba/framework/logging.hh>
#include <nba/core/queue.hh>
#include <vector>
#include <string>
#include <random>
#include <cmath>
#include <rte_errno.h>
#include <rte_atomic.h>
#define LB_PPC_CPU_RATIO_MULTIPLIER (1000)
#define LB_PPC_CPU_RATIO_DELTA (50)
namespace nba {
class LoadBalancePPC : public SchedulableElement, PerBatchElement {
public:
LoadBalancePPC() : SchedulableElement(), PerBatchElement()
{ }
virtual ~LoadBalancePPC()
{ }
const char *class_name() const { return "LoadBalancePPC"; }
const char *port_count() const { return "1/1"; }
int get_type() const { return SchedulableElement::get_type() | PerBatchElement::get_type(); }
int initialize()
{
local_cpu_ratio = LB_PPC_CPU_RATIO_MULTIPLIER;
delta = LB_PPC_CPU_RATIO_DELTA;
last_estimated_ppc = 0;
rep = 0;
rep_limit = ctx->num_coproc_ppdepth;
initial_converge = true;
offload = false;
cpu_ratio = (rte_atomic64_t *) ctx->node_local_storage->get_alloc("LBPPC.cpu_weight");
return 0;
}
int initialize_global() { return 0; }
int initialize_per_node()
{
ctx->node_local_storage->alloc("LBPPC.cpu_weight", sizeof(rte_atomic64_t));
rte_atomic64_t *node_cpu_ratio = (rte_atomic64_t *)
ctx->node_local_storage->get_alloc("LBPPC.cpu_weight");
assert(node_cpu_ratio != nullptr);
rte_atomic64_set(node_cpu_ratio, 0);
return 0;
}
int configure(comp_thread_context *ctx, std::vector<std::string> &args)
{
Element::configure(ctx, args);
RTE_LOG(INFO, LB, "load balancer mode: Adaptive PPC\n");
return 0;
}
int process_batch(int input_port, PacketBatch *batch)
{
int decision = -1;
const float c = (float) local_cpu_ratio / LB_PPC_CPU_RATIO_MULTIPLIER;
rep ++;
if (offload) {
decision = 0;
if (rep == rep_limit) { // Change to CPU-mode
if (local_cpu_ratio == 0)
rep_limit = 0; // only once for sampling!
else
rep_limit = (unsigned) (c * ctx->num_coproc_ppdepth / (1.0f - c));
rep = 0;
offload = false;
}
} else {
decision = -1;
if (rep == rep_limit) { // Change to GPU-mode
rep_limit = ctx->num_coproc_ppdepth;
rep = 0;
offload = true;
}
}
anno_set(&batch->banno, NBA_BANNO_LB_DECISION, decision);
return 0;
}
int dispatch(uint64_t loop_count, PacketBatch*& out_batch, uint64_t &next_delay)
{
next_delay = 200000; // 0.2sec
if (ctx->loc.local_thread_idx == 0) {
const float ppc_cpu = ctx->inspector->pkt_proc_cycles[0];
const float ppc_gpu = ctx->inspector->pkt_proc_cycles[1];
if (initial_converge) {
if (ppc_cpu != 0 && ppc_gpu != 0) {
int64_t temp_cpu_ratio;
if (ppc_cpu > ppc_gpu) temp_cpu_ratio = 0;
else temp_cpu_ratio = LB_PPC_CPU_RATIO_MULTIPLIER;
printf("[PPC:%d] Initial converge: %ld | CPU %'8.0f GPU %'8.0f\n", ctx->loc.node_id,
temp_cpu_ratio, ppc_cpu, ppc_gpu);
rte_atomic64_set(cpu_ratio, temp_cpu_ratio);
initial_converge = false;
}
} else {
int64_t temp_cpu_ratio = rte_atomic64_read(cpu_ratio);
const float estimated_ppc = (temp_cpu_ratio * ppc_cpu
+ (LB_PPC_CPU_RATIO_MULTIPLIER - temp_cpu_ratio) * ppc_gpu)
/ LB_PPC_CPU_RATIO_MULTIPLIER;
const float c = (float) temp_cpu_ratio / LB_PPC_CPU_RATIO_MULTIPLIER;
if (last_estimated_ppc != 0) {
if (last_estimated_ppc > estimated_ppc) {
// keep direction
} else {
// reverse direction
delta = -delta;
}
temp_cpu_ratio += delta;
}
if (temp_cpu_ratio < 0) temp_cpu_ratio = 0;
if (temp_cpu_ratio > LB_PPC_CPU_RATIO_MULTIPLIER) temp_cpu_ratio = LB_PPC_CPU_RATIO_MULTIPLIER;
last_estimated_ppc = estimated_ppc;
printf("[PPC:%d] CPU %'8.0f GPU %'8.0f PPC %'8.0f CPU-Ratio %.3f\n",
ctx->loc.node_id,
ppc_cpu, ppc_gpu, estimated_ppc, c);
rte_atomic64_set(cpu_ratio, temp_cpu_ratio);
}
}
out_batch = nullptr;
return 0;
}
private:
rte_atomic64_t *cpu_ratio;
float last_estimated_ppc;
int64_t local_cpu_ratio;
int64_t delta;
unsigned rep, rep_limit;
bool initial_converge;
bool offload;
};
EXPORT_ELEMENT(LoadBalancePPC);
}
#endif
// vim: ts=8 sts=4 sw=4 et
| 33.617834 | 111 | 0.568587 | ANLAB-KAIST |
8283a28c98bcdcff9003fe99d38261b11a304f57 | 1,059 | hpp | C++ | include/codegen/include/GlobalNamespace/IRichPresencePlatformHandler.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/GlobalNamespace/IRichPresencePlatformHandler.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/GlobalNamespace/IRichPresencePlatformHandler.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: IRichPresenceData
class IRichPresenceData;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: IRichPresencePlatformHandler
class IRichPresencePlatformHandler {
public:
// public System.Void SetPresence(IRichPresenceData richPresenceData)
// Offset: 0xFFFFFFFF
void SetPresence(GlobalNamespace::IRichPresenceData* richPresenceData);
// public System.Void Clear()
// Offset: 0xFFFFFFFF
void Clear();
}; // IRichPresencePlatformHandler
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::IRichPresencePlatformHandler*, "", "IRichPresencePlatformHandler");
#pragma pack(pop)
| 34.16129 | 107 | 0.721435 | Futuremappermydud |
8287b93b336229e349bec3690ef55932ba439aea | 1,985 | hpp | C++ | Source/wali/include/wali/IMarkable.hpp | jusito/WALi-OpenNWA | 2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99 | [
"MIT"
] | 15 | 2015-03-07T17:25:57.000Z | 2022-02-04T20:17:00.000Z | src/wpds/Source/wali/IMarkable.hpp | ucd-plse/mpi-error-prop | 4367df88bcdc4d82c9a65b181d0e639d04962503 | [
"BSD-3-Clause"
] | 1 | 2018-03-03T05:58:55.000Z | 2018-03-03T12:26:10.000Z | src/wpds/Source/wali/IMarkable.hpp | ucd-plse/mpi-error-prop | 4367df88bcdc4d82c9a65b181d0e639d04962503 | [
"BSD-3-Clause"
] | 15 | 2015-09-25T17:44:35.000Z | 2021-07-18T18:25:38.000Z | #ifndef wali_IMARKABLE_GUARD
#define wali_IMARKABLE_GUARD 1
/*!
* @author Nicholas Kidd
*/
#include "wali/Common.hpp"
namespace wali
{
/*!
* @class IMarkable
*
* IMarkable defines the Markable interface. Markable objects are things
* that need to be placed in a worklist while possibly being in the
* worklist, and/or objects in cyclic or DAG-like data structures that are
* traversed in some fashion.
*
* IMarkable is implemented in the Markable class. The interface has been
* extracted out for allowing "delegate" objects to delegate the mark() and
* unmark() calls to the wrapped object. E.g., the Decorator Pattern.
*
* @see Worklist
*/
class IMarkable
{
public:
/*! Creates a new IMarkable in the unmarked state */
IMarkable() {}
/*!
* This copy constructor actually acts just like the default
* constructor. This input IMarkable m is ignored. Any time a
* IMarkable is created it is "born" in the unmarked state.
*
* @param m is ignored
*/
IMarkable( const IMarkable& m ATTR_UNUSED )
{
(void) m;
}
/*!
* IMarkable::operator= has no effect b/c IMarkable has no fields.
* In general though, the input <b>should be</b> ignored.
* This is because IMarkable specifies that state may only
* be changed via the mark and unmark operations.
*/
IMarkable& operator=( const IMarkable& m ATTR_UNUSED )
{
(void) m;
return *this;
}
/*! Destructor does noting */
virtual ~IMarkable() {}
/*! Mark this */
virtual void mark() const throw() = 0;
/*! Unmark this */
virtual void unmark() const throw() = 0;
/*!
* Check if this is marked.
*
* @return true if this is marked
*/
virtual bool marked() const throw() = 0;
}; // class IMarkable
} // namespace wali
#endif // wali_IMARKABLE_GUARD
| 24.8125 | 77 | 0.611587 | jusito |
8288c168a0b88232a75e7cb1b49b6900d9219dda | 2,409 | cpp | C++ | time_service.cpp | aclement30/bondi | 17753c80f4f6a69b30a10ec2d7f42c29fb1ee0c6 | [
"Apache-2.0"
] | null | null | null | time_service.cpp | aclement30/bondi | 17753c80f4f6a69b30a10ec2d7f42c29fb1ee0c6 | [
"Apache-2.0"
] | null | null | null | time_service.cpp | aclement30/bondi | 17753c80f4f6a69b30a10ec2d7f42c29fb1ee0c6 | [
"Apache-2.0"
] | null | null | null | #include <DS1302RTC.h>
#include <Time.h>
#include "constants.h"
#include "config.h"
#include "string.h"
#include "time_service.h"
TimeService & TimeService::getInstance() {
static TimeService instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
// Returns current UTC time
time_t TimeService::getTime() {
return rtc.get();
}
time_t TimeService::getLocalTimeFromUTC(time_t utcTime) {
signed long timezoneOffset = getTimezoneOffset(utcTime) * 3600;
return utcTime + timezoneOffset;
}
void TimeService::getUTCDateTime(char * date) {
sprintf(date, "%d-%02d-%02d %02d:%02d:%02d", year(), month(), day(), hour(), minute(), second());
}
void TimeService::getLocalDateTime(char * date) {
signed long timezoneOffset = getTimezoneOffset() * 3600;
time_t utcTime = now();
time_t localTime = utcTime + timezoneOffset;
sprintf(date, "%d-%02d-%02d %02d:%02d", year(localTime), month(localTime), day(localTime), hour(localTime), minute(localTime));
}
int TimeService::getLocalMoment() {
signed long timezoneOffset = getTimezoneOffset() * 3600;
time_t utcTime = now();
time_t localTime = utcTime + timezoneOffset;
return (hour(localTime) * 60) + minute(localTime);
}
void TimeService::timestamp(char * date) {
sprintf(date, "%d-%02d-%02dT%02d:%02d:%02dZ", year(), month(), day(), hour(), minute(), second());
}
void TimeService::setDateTime(int hours, int minutes, int seconds, int days, int months, int years) {
tmElements_t tm;
tm.Year = years - 1970;
tm.Month = months;
tm.Day = days;
tm.Hour = hours;
tm.Minute = minutes;
tm.Second = seconds;
time_t localTime = makeTime(tm);
signed long timezoneOffset = getTimezoneOffset(localTime) * 3600;
time_t utcTime = localTime - timezoneOffset;
rtc.set(utcTime);
setTime(utcTime);
}
// PRIVATE
TimeService::TimeService() : rtc(DS1302RTC(RTC_CE_PIN, RTC_IO_PIN, RTC_SCLK_PIN)) {
setSyncProvider(rtc.get);
}
signed long TimeService::getTimezoneOffset(time_t currentTime) {
for (int n = 0; n < 20; n++) {
if (TIMEZONE_OFFSETS[n][0] > currentTime) {
return TIMEZONE_OFFSETS[n-1][1];
break;
}
}
return 0;
}
signed long TimeService::getTimezoneOffset() {
time_t utcTime = now();
return getTimezoneOffset(utcTime);
} | 28.011628 | 131 | 0.660025 | aclement30 |
828ecbf9cabd6e8ef3e35c16fc48b5a7e42b0fd5 | 146 | cpp | C++ | FootCommander.cpp | snir1551/Ex7_C- | bbfb91ddee016b4f729359f5e50038e2267a795e | [
"MIT"
] | 1 | 2021-05-31T13:11:04.000Z | 2021-05-31T13:11:04.000Z | FootCommander.cpp | snir1551/Ex7_C- | bbfb91ddee016b4f729359f5e50038e2267a795e | [
"MIT"
] | null | null | null | FootCommander.cpp | snir1551/Ex7_C- | bbfb91ddee016b4f729359f5e50038e2267a795e | [
"MIT"
] | null | null | null | #include "FootCommander.hpp"
namespace WarGame {
FootCommander::FootCommander(int numPlayer): Soldier(numPlayer,150,20)
{
}
} | 20.857143 | 74 | 0.671233 | snir1551 |
82952d723675f438d4d6ad47072e113f3a7fc7d3 | 51,460 | cpp | C++ | imdexp/src/strip/zappy/CustomArray.cpp | olivierchatry/iri3d | cae98c61d9257546d0fc81e69709297d04a17a14 | [
"MIT"
] | 2 | 2022-01-02T08:12:29.000Z | 2022-02-12T22:15:11.000Z | imdexp/src/strip/zappy/CustomArray.cpp | olivierchatry/iri3d | cae98c61d9257546d0fc81e69709297d04a17a14 | [
"MIT"
] | null | null | null | imdexp/src/strip/zappy/CustomArray.cpp | olivierchatry/iri3d | cae98c61d9257546d0fc81e69709297d04a17a14 | [
"MIT"
] | 1 | 2022-01-02T08:09:51.000Z | 2022-01-02T08:09:51.000Z | ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Source code for "Creating Efficient Triangle Strips"
// (C) 2000, Pierre Terdiman (p.terdiman@wanadoo.fr)
//
// Version is 2.0.
//
// This is a versatile and customized import/export array class I use for a long time.
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Precompiled Header
#include "Stdafx.h"
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Constructor
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CustomArray::CustomArray(unsigned long startsize, void* inputbuffer) : mNbPushedAddies(0), mNbAllocatedAddies(0), mBitCount(0), mBitMask(0), mAddresses(null), mCollapsed(null)
{
// Initialize first export block
NewBlock(null, startsize);
// Keep track of this first cell
mInitCell = mCurrentCell;
// Fill first block with provided buffer, if needed
if(inputbuffer) memcpy(mCurrentCell->Item.Addy, inputbuffer, startsize);
// Initialize mLastAddress so that it won't crash if the first thing you ever do is a PushAddress/PopAddressAndStore!!
mLastAddress = mCurrentCell->Item.Addy;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Constructor
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CustomArray::CustomArray(const char* filename) : mNbPushedAddies(0), mNbAllocatedAddies(0), mBitCount(0), mBitMask(0), mAddresses(null), mCollapsed(null)
{
// Catch the file's size to initialize first block
unsigned long StartSize = FileSize(filename);
if(!StartSize) StartSize=CUSTOMARRAY_BLOCKSIZE;
// Initialize first export block
NewBlock(null, StartSize);
// Keep track of this first cell
mInitCell = mCurrentCell;
// Fill first block with file data
FILE* fp = fopen(filename, "rb");
if(fp)
{
fread(mCurrentCell->Item.Addy, StartSize, 1, fp);
fclose(fp);
}
// Initialize mLastAddress so that it won't crash if the first thing you ever do is a PushAddress/PopAddressAndStore!!
mLastAddress = mCurrentCell->Item.Addy;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Destructor
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CustomArray::~CustomArray()
{
// Free possible collapsed array
RELEASEARRAY(mCollapsed);
// Free possible adress list
RELEASEARRAY(mAddresses);
// Free linked list
CustomCell* CurCell = mInitCell;
while(CurCell)
{
CustomCell* Cell = CurCell;
CurCell = CurCell->NextCustomCell;
RELEASE(Cell);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// MANAGEMENT METHODS
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to create and link a new block to previous ones.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : previouscell = the previous cell, or null if this is the first
// size = #bytes to allocate for the first cell
// Output : -
// Return : self-reference
// Exception: -
// Remark : 'size' is only used if previouscell is null (i.e. for the first cell)
CustomArray& CustomArray::NewBlock(CustomCell* previouscell, unsigned long size)
{
// Create a new cell
CustomCell* Cell = new CustomCell;
// If a previous cell exists, doubles the needed ram, else get default size
Cell->Item.Max = previouscell ? previouscell->Item.Max*2 : size;
// Get some bytes for this cell
Cell->Item.Addy = (void*)new ubyte[Cell->Item.Max];
Cell->Item.Size = 0;
mCurrentCell = Cell;
// Update linked list
if(previouscell) previouscell->NextCustomCell = mCurrentCell;
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to check whether there's enough room in current block for expected datas, or not.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : bytesneeded = #expected bytes
// Output : -
// Return : self-reference
// Exception: -
// Remark : a new block is created if there's no more space left in current block.
CustomArray& CustomArray::CheckArray(unsigned long bytesneeded)
{
unsigned long ExpectedSize = mCurrentCell->Item.Size + bytesneeded;
if(ExpectedSize > mCurrentCell->Item.Max) NewBlock(mCurrentCell);
// I assume there IS enough room in the new block for expected data. It should always be the case since 'bytesneeded' is not supposed to be larger than 8
// (i.e. sizeof(double))
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to export an array to disk.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : filename = the destination file's name.
// Output : -
// Return : true if success
// Exception: -
// Remark : -
bool CustomArray::ExportToDisk(const char* filename)
{
FILE* fp = fopen(filename, "wb");
if(!fp) return false;
ExportToDisk(fp);
fclose(fp);
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to export an array to disk.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : fp = the file pointer.
// Output : -
// Return : true if success
// Exception: -
// Remark : -
bool CustomArray::ExportToDisk(FILE* fp)
{
// Fill possible remaining bits with 0
EndBits();
CustomCell* p = mInitCell;
while(p->NextCustomCell)
{
// Save current cell
if(!SaveCell(p, fp)) return false;
// Go to next cell
p = p->NextCustomCell;
}
// Save last cell
if(!SaveCell(p, fp)) return false;
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to write a single cell to disk.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : p = current cell.
// fp = file pointer.
// Output : -
// Return : true if success
// Exception: -
// Remark : -
bool CustomArray::SaveCell(CustomCell* p, FILE* fp)
{
unsigned long BytesToWrite = p->Item.Size;
if(!BytesToWrite) return true;
if(fwrite(p->Item.Addy, 1, BytesToWrite, fp)!=BytesToWrite) return false;
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to get current #bytes stored.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : -
// Output : -
// Return : unsigned long = #bytes stored
// Exception: -
// Remark : -
unsigned long CustomArray::GetOffset()
{
unsigned long Offset = 0;
CustomCell* p = mInitCell;
while(p->NextCustomCell)
{
// Add offset from current cell
Offset+=p->Item.Size;
// Go to next cell
p = p->NextCustomCell;
}
// Add offset from last cell
Offset+=p->Item.Size;
return(Offset);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to padd offset on a 8 bytes boundary.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : -
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::Padd()
{
// Fill possible remaining bits with 0
EndBits();
unsigned long Offset = GetOffset();
unsigned long NbPadd = Offset - (Offset & 7);
for(unsigned long i=0;i<NbPadd;i++) Store((char)0);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to link 2 arrays.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : array = the array to link
// Output : -
// Return : self-reference
// Exception: -
// Remark : OBSOLETE CODE
CustomArray& CustomArray::LinkTo(CustomArray* array)
{
// ### THIS METHOD NEEDS RECODING & TESTING
/*
CustomCell* p = mInitCell;
char* Addy;
unsigned long i;
while(p->NextCustomCell)
{
// Link current cell
Addy = (char*)p->Item.Addy;
for(i=0;i<p->Item.Size;i++) Store(*Addy++);
// Go to next cell
p = p->NextCustomCell;
}
// Link last cell
Addy = (char*)p->Item.Addy;
for(i=0;i<p->Item.Size;i++) Store(*Addy++);
*/
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to collapse a CustomArray into a single continuous buffer. This invalidates all pushed addies.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : userbuffer = destination buffer (provided or not)
// Output : -
// Return : void* = destination buffer
// Exception: -
// Remark : if you provide your destination buffer original bytes are copied into it, then it's safe using them.
// if you don't, returned address is valid until the array's destructor is called. Beware of memory corruption...
void* CustomArray::Collapse(void* userbuffer)
{
// Fill possible remaining bits with 0
EndBits();
char* Addy;
CustomCell* p = mInitCell;
if(!userbuffer)
{
RELEASEARRAY(mCollapsed); // Free possibly already collapsed array
unsigned long CurrentSize = GetOffset();
mCollapsed = CurrentSize ? new ubyte[CurrentSize] : null;
Addy = (char*)mCollapsed;
}
else
{
Addy = (char*)userbuffer;
}
char* AddyCopy = Addy;
if(Addy)
{
while(p->NextCustomCell)
{
// Collapse current cell
memcpy(Addy, p->Item.Addy, p->Item.Size);
Addy+=p->Item.Size;
// Go to next cell
p = p->NextCustomCell;
}
// Collapse last cell
memcpy(Addy, p->Item.Addy, p->Item.Size);
Addy+=p->Item.Size;
mNbPushedAddies=0;
}
return AddyCopy;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// STORE METHODS
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store a BOOL.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : Bo = BOOL to store
// Output : -
// Return : self-reference
// Exception: -
// Remark : Warning! BOOL actually is an int. Converted to long.
CustomArray& CustomArray::Store(BOOL Bo)
{
// Fill possible remaining bits with 0
EndBits();
long b = (long)Bo;
CheckArray(sizeof(long));
char* CurrentAddy = (char*)mCurrentCell->Item.Addy;
CurrentAddy+=mCurrentCell->Item.Size;
long* Current = (long*)CurrentAddy;
*Current=b;
mLastAddress = (void*)Current;
mCurrentCell->Item.Size+=sizeof(long);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store a bool.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : Bo = bool to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : Converted to char.
CustomArray& CustomArray::Store(bool Bo)
{
// Fill possible remaining bits with 0
EndBits();
char b = Bo ? 1 : 0;
CheckArray(sizeof(char));
char* CurrentAddy = (char*)mCurrentCell->Item.Addy;
CurrentAddy+=mCurrentCell->Item.Size;
char* Current = (char*)CurrentAddy;
*Current=b;
mLastAddress = (void*)Current;
mCurrentCell->Item.Size+=sizeof(char);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store a char.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : b = char to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::Store(char b)
{
// Fill possible remaining bits with 0
EndBits();
CheckArray(sizeof(char));
char* CurrentAddy = (char*)mCurrentCell->Item.Addy;
CurrentAddy+=mCurrentCell->Item.Size;
char* Current = (char*)CurrentAddy;
*Current=b;
mLastAddress = (void*)Current;
mCurrentCell->Item.Size+=sizeof(char);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store an unsigned char.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : b = unsigned char to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::Store(unsigned char b)
{
// Fill possible remaining bits with 0
EndBits();
CheckArray(sizeof(unsigned char));
char* CurrentAddy = (char*)mCurrentCell->Item.Addy;
CurrentAddy+=mCurrentCell->Item.Size;
unsigned char* Current = (unsigned char*)CurrentAddy;
*Current=b;
mLastAddress = (void*)Current;
mCurrentCell->Item.Size+=sizeof(unsigned char);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store a short.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : w = short to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::Store(short w)
{
// Fill possible remaining bits with 0
EndBits();
CheckArray(sizeof(short));
char* CurrentAddy = (char*)mCurrentCell->Item.Addy;
CurrentAddy+=mCurrentCell->Item.Size;
short* Current = (short*)CurrentAddy;
*Current=w;
mLastAddress = (void*)Current;
mCurrentCell->Item.Size+=sizeof(short);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store an unsigned short.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : w = unsigned short to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::Store(unsigned short w)
{
// Fill possible remaining bits with 0
EndBits();
CheckArray(sizeof(unsigned short));
char* CurrentAddy = (char*)mCurrentCell->Item.Addy;
CurrentAddy+=mCurrentCell->Item.Size;
unsigned short* Current = (unsigned short*)CurrentAddy;
*Current=w;
mLastAddress = (void*)Current;
mCurrentCell->Item.Size+=sizeof(unsigned short);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store a long.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : d = long to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::Store(long d)
{
// Fill possible remaining bits with 0
EndBits();
CheckArray(sizeof(long));
char* CurrentAddy = (char*)mCurrentCell->Item.Addy;
CurrentAddy+=mCurrentCell->Item.Size;
long* Current = (long*)CurrentAddy;
*Current=d;
mLastAddress = (void*)Current;
mCurrentCell->Item.Size+=sizeof(long);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store an unsigned long.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : d = unsigned long to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::Store(unsigned long d)
{
// Fill possible remaining bits with 0
EndBits();
CheckArray(sizeof(unsigned long));
char* CurrentAddy = (char*)mCurrentCell->Item.Addy;
CurrentAddy+=mCurrentCell->Item.Size;
unsigned long* Current = (unsigned long*)CurrentAddy;
*Current=d;
mLastAddress = (void*)Current;
mCurrentCell->Item.Size+=sizeof(unsigned long);
return *this;
}
/*
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store an int.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : d = int to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::Store(int d)
{
// Fill possible remaining bits with 0
EndBits();
CheckArray(sizeof(int));
char* CurrentAddy = (char*)mCurrentCell->Item.Addy;
CurrentAddy+=mCurrentCell->Item.Size;
int* Current = (int*)CurrentAddy;
*Current=d;
mLastAddress = (void*)Current;
mCurrentCell->Item.Size+=sizeof(int);
return *this;
}
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store an unsigned int.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : d = unsigned int to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::Store(unsigned int d)
{
// Fill possible remaining bits with 0
EndBits();
CheckArray(sizeof(unsigned int));
char* CurrentAddy = (char*)mCurrentCell->Item.Addy;
CurrentAddy+=mCurrentCell->Item.Size;
unsigned int* Current = (unsigned int*)CurrentAddy;
*Current=d;
mLastAddress = (void*)Current;
mCurrentCell->Item.Size+=sizeof(unsigned int);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store a float.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : f = float to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::Store(float f)
{
// Fill possible remaining bits with 0
EndBits();
CheckArray(sizeof(float));
char* CurrentAddy = (char*)mCurrentCell->Item.Addy;
CurrentAddy+=mCurrentCell->Item.Size;
float* Current = (float*)CurrentAddy;
*Current=f;
mLastAddress = (void*)Current;
mCurrentCell->Item.Size+=sizeof(float);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store a double.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : f = double to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::Store(double f)
{
// Fill possible remaining bits with 0
EndBits();
CheckArray(sizeof(double));
char* CurrentAddy = (char*)mCurrentCell->Item.Addy;
CurrentAddy+=mCurrentCell->Item.Size;
double* Current = (double*)CurrentAddy;
*Current=f;
mLastAddress = (void*)Current;
mCurrentCell->Item.Size+=sizeof(double);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store a string.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : String = the string to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::Store(const char *String)
{
// Fill possible remaining bits with 0
EndBits();
for(unsigned long i=0;i<strlen(String);i++)
{
Store((char)String[i]);
}
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// STOREASCII METHODS
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store an ASCII code.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : Code = input byte
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::StoreASCIICode(char Code)
{
// Fill possible remaining bits with 0
EndBits();
CheckArray(sizeof(char));
char* CurrentAddy = (char*)mCurrentCell->Item.Addy;
CurrentAddy+=mCurrentCell->Item.Size;
char* Current = (char*)CurrentAddy;
*Current=Code;
mCurrentCell->Item.Size+=sizeof(char);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store a BOOL in ASCII.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : Bo = the BOOL to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::StoreASCII(BOOL Bo)
{
char Text[256];
sprintf(Text, "%d", (long)Bo);
StoreASCII((const char*)Text);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store a bool in ASCII.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : Bo = the bool to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::StoreASCII(bool Bo)
{
if(Bo) StoreASCII((const char*)"true");
else StoreASCII((const char*)"false");
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store a char in ASCII.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : b = the char to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::StoreASCII(char b)
{
char Text[256];
sprintf(Text, "%d", b);
StoreASCII((const char*)Text);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store an unsigned char in ASCII.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : b = the unsigned char to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::StoreASCII(unsigned char b)
{
char Text[256];
sprintf(Text, "%u", b);
StoreASCII((const char*)Text);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store a short in ASCII.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : w = the short to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::StoreASCII(short w)
{
char Text[256];
sprintf(Text, "%d", w);
StoreASCII((const char*)Text);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store an unsigned short in ASCII.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : w = the unsigned short to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::StoreASCII(unsigned short w)
{
char Text[256];
sprintf(Text, "%u", w);
StoreASCII((const char*)Text);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store a long in ASCII.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : d = the long to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::StoreASCII(long d)
{
char Text[256];
sprintf(Text, "%d", d);
StoreASCII((const char*)Text);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store an unsigned long in ASCII.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : d = the unsigned long to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::StoreASCII(unsigned long d)
{
char Text[256];
sprintf(Text, "%u", d);
StoreASCII((const char*)Text);
return *this;
}
/*
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store an int in ASCII.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : d = the int to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::StoreASCII(int d)
{
char Text[256];
sprintf(Text, "%d", d);
StoreASCII((const char*)Text);
return *this;
}
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store an unsigned int in ASCII.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : d = the unsigned int to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::StoreASCII(unsigned int d)
{
char Text[256];
sprintf(Text, "%u", d);
StoreASCII((const char*)Text);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store a float in ASCII.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : f = the float to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::StoreASCII(float f)
{
char Text[256];
sprintf(Text, "%f", f);
StoreASCII((const char*)Text);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store a double in ASCII.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : f = the double to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::StoreASCII(double f)
{
char Text[256];
sprintf(Text, "%f", f);
StoreASCII((const char*)Text);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store a string in ASCII.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : String = the string to store.
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::StoreASCII(const char *String)
{
// Fill possible remaining bits with 0
EndBits();
for(unsigned long i=0;i<strlen(String);i++)
{
if(String[i]=='\n')
{
StoreASCIICode((char)0x0d);
StoreASCIICode((char)0x0a);
}
else
StoreASCIICode((char)String[i]);
}
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// PUSH/POP ADDRESS METHODS
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to push current address into the address-stack for later processing.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : -
// Output : -
// Return : true if success, else false
// Exception: -
// Remark : -
bool CustomArray::PushAddress()
{
// Check available space and resize if needed.
if((mNbPushedAddies+1)>mNbAllocatedAddies)
{
// Here we must resize. We get twice as much bytes as already allocated in order to minimize total #resizes.
udword NewSize = mNbAllocatedAddies ? mNbAllocatedAddies * 2 : 1;
// Create new buffer...
void** Addresses = new void*[NewSize];
if(!Addresses) return false;
// ...copy & release old one to new one if old one exists...
if(mNbAllocatedAddies)
{
memcpy(Addresses, mAddresses, mNbAllocatedAddies * sizeof(void*));
RELEASEARRAY(mAddresses);
}
// ...and set new members.
mAddresses = Addresses;
mNbAllocatedAddies = NewSize;
}
// Save last address
mAddresses[mNbPushedAddies++] = mLastAddress;
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to pop an address and store a BOOL where the poped address tells.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : Bo = the BOOL to store
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::PopAddressAndStore(BOOL Bo)
{
if(mNbPushedAddies)
{
BOOL* Addy = (BOOL*)mAddresses[--mNbPushedAddies];
*Addy=Bo;
}
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to pop an address and store a bool where the poped address tells.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : Bo = the bool to store
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::PopAddressAndStore(bool Bo)
{
if(mNbPushedAddies)
{
char* Addy = (char*)mAddresses[--mNbPushedAddies];
*Addy=(char)Bo;
}
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to pop an address and store a char where the poped address tells.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : b = the char to store
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::PopAddressAndStore(char b)
{
if(mNbPushedAddies)
{
char* Addy = (char*)mAddresses[--mNbPushedAddies];
*Addy=b;
}
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to pop an address and store an unsigned char where the poped address tells.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : b = the unsigned char to store
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::PopAddressAndStore(unsigned char b)
{
if(mNbPushedAddies)
{
unsigned char* Addy = (unsigned char*)mAddresses[--mNbPushedAddies];
*Addy=b;
}
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to pop an address and store a short where the poped address tells.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : w = the short to store
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::PopAddressAndStore(short w)
{
if(mNbPushedAddies)
{
short* Addy = (short*)mAddresses[--mNbPushedAddies];
*Addy=w;
}
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to pop an address and store an unsigned short where the poped address tells.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : w = the unsigned short to store
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::PopAddressAndStore(unsigned short w)
{
if(mNbPushedAddies)
{
unsigned short* Addy = (unsigned short*)mAddresses[--mNbPushedAddies];
*Addy=w;
}
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to pop an address and store a long where the poped address tells.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : d = the long to store
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::PopAddressAndStore(long d)
{
if(mNbPushedAddies)
{
long* Addy = (long*)mAddresses[--mNbPushedAddies];
*Addy=d;
}
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to pop an address and store an unsigned long where the poped address tells.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : d = the unsigned long to store
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::PopAddressAndStore(unsigned long d)
{
if(mNbPushedAddies)
{
unsigned long* Addy = (unsigned long*)mAddresses[--mNbPushedAddies];
*Addy=d;
}
return *this;
}
/*
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to pop an address and store an int where the poped address tells.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : d = the int to store
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::PopAddressAndStore(int d)
{
if(mNbPushedAddies)
{
int* Addy = (int*)mAddresses[--mNbPushedAddies];
*Addy=d;
}
return *this;
}
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to pop an address and store an unsigned int where the poped address tells.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : d = the unsigned int to store
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::PopAddressAndStore(unsigned int d)
{
if(mNbPushedAddies)
{
unsigned int* Addy = (unsigned int*)mAddresses[--mNbPushedAddies];
*Addy=d;
}
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to pop an address and store a float where the poped address tells.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : f = the float to store
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::PopAddressAndStore(float f)
{
if(mNbPushedAddies)
{
float* Addy = (float*)mAddresses[--mNbPushedAddies];
*Addy=f;
}
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to pop an address and store a double where the poped address tells.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : f = the double to store
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::PopAddressAndStore(double f)
{
if(mNbPushedAddies)
{
double* Addy = (double*)mAddresses[--mNbPushedAddies];
*Addy=f;
}
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// BIT STORAGE METHODS
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to store a bit.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : bool = the bit to store
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::StoreBit(bool bit)
{
mBitMask<<=1;
if(bit) mBitMask |= 1;
mBitCount++;
if(mBitCount==8)
{
mBitCount = 0;
Store(mBitMask);
mBitMask = 0;
}
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to padd bits on a byte.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : -
// Output : -
// Return : self-reference
// Exception: -
// Remark : -
CustomArray& CustomArray::EndBits()
{
while(mBitCount) StoreBit(false);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// READ METHODS
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
char CustomArray::GetByte()
{
char* CurrentAddy = (char*)mCurrentCell->Item.Addy;
CurrentAddy+=mCurrentCell->Item.Size;
char* Current = (char*)CurrentAddy;
char result = *Current;
mLastAddress = (void*)Current;
mCurrentCell->Item.Size+=sizeof(char);
return result;
}
short CustomArray::GetWord()
{
char* CurrentAddy = (char*)mCurrentCell->Item.Addy;
CurrentAddy+=mCurrentCell->Item.Size;
short* Current = (short*)CurrentAddy;
short result = *Current;
mLastAddress = (void*)Current;
mCurrentCell->Item.Size+=sizeof(short);
return result;
}
long CustomArray::GetDword()
{
char* CurrentAddy = (char*)mCurrentCell->Item.Addy;
CurrentAddy+=mCurrentCell->Item.Size;
long* Current = (long*)CurrentAddy;
long result = *Current;
mLastAddress = (void*)Current;
mCurrentCell->Item.Size+=sizeof(long);
return result;
}
float CustomArray::GetFloat()
{
char* CurrentAddy = (char*)mCurrentCell->Item.Addy;
CurrentAddy+=mCurrentCell->Item.Size;
float* Current = (float*)CurrentAddy;
float result = *Current;
mLastAddress = (void*)Current;
mCurrentCell->Item.Size+=sizeof(float);
return result;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// HELP METHODS
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A method to get a file length.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Input : name = file name
// Output : -
// Return : udword = size in bytes, or 0 if file doesn't exist
// Exception: -
// Remark : -
#ifndef SEEK_END
#define SEEK_END 2
#endif
udword CustomArray::FileSize(const char* name)
{
FILE* File = fopen(name, "rb");
if (!File) return 0;
fseek(File, 0, SEEK_END);
udword eof_ftell = ftell(File);
fclose(File);
return eof_ftell;
}
| 39.46319 | 199 | 0.345297 | olivierchatry |
8298f03ee429b491a588f3582e4a4ebfab09114f | 1,699 | cpp | C++ | solved/u-w/unidirectional-tsp/tsp.cpp | abuasifkhan/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | 13 | 2015-09-30T19:18:04.000Z | 2021-06-26T21:11:30.000Z | solved/u-w/unidirectional-tsp/tsp.cpp | sbmaruf/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | null | null | null | solved/u-w/unidirectional-tsp/tsp.cpp | sbmaruf/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | 13 | 2015-01-04T09:49:54.000Z | 2021-06-03T13:18:44.000Z | #include <cstdio>
#define MAXM 10
#define MAXN 100
int m, n;
int maze[MAXM][MAXN];
// dp[i][j]: minimum cost of path that goes from right to left and ends in
// position (i, j)
int dp[MAXM][MAXN];
// next[i][j]: row of the next position in the best path from (i, j)
int next[MAXM][MAXN];
void print_path(int r)
{
printf("%d", r + 1);
r = next[r][0];
int c = 1;
while (r >= 0) {
printf(" %d", r + 1);
r = next[r][c++];
}
putchar('\n');
}
void solve()
{
for (int i = 0; i < m; ++i) {
dp[i][n - 1] = maze[i][n - 1];
next[i][n - 1] = -1;
}
for (int j = n - 2; j >= 0; --j)
for (int i = 0; i < m; ++i) {
int row = (i - 1 + m) % m;
int best = dp[row][j + 1];
int nrow = row;
if (dp[i][j + 1] < best || (dp[i][j + 1] == best && i < nrow)) {
best = dp[i][j + 1];
nrow = i;
}
row = (i + 1) % m;
if (dp[row][j + 1] < best ||
(dp[row][j + 1] == best && row < nrow)) {
best = dp[row][j + 1];
nrow = row;
}
dp[i][j] = maze[i][j] + best;
next[i][j] = nrow;
}
int best = dp[0][0];
int row = 0;
for (int i = 1; i < m; ++i)
if (dp[i][0] < best) {
best = dp[i][0];
row = i;
}
print_path(row);
printf("%d\n", best);
}
int main()
{
while (true) {
if (scanf("%d%d", &m, &n) != 2) break;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
scanf("%d", &maze[i][j]);
solve();
}
return 0;
}
| 19.528736 | 76 | 0.373161 | abuasifkhan |
8299b457efcec9e166e79c3cf176de3b43648877 | 2,131 | cpp | C++ | libvast/src/detail/line_range.cpp | knapperzbusch/vast | 9d2af995254519b47febe2062adbc55965055cbe | [
"BSD-3-Clause"
] | null | null | null | libvast/src/detail/line_range.cpp | knapperzbusch/vast | 9d2af995254519b47febe2062adbc55965055cbe | [
"BSD-3-Clause"
] | 1 | 2019-11-29T12:43:41.000Z | 2019-11-29T12:43:41.000Z | libvast/src/detail/line_range.cpp | knapperzbusch/vast | 9d2af995254519b47febe2062adbc55965055cbe | [
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include "vast/detail/line_range.hpp"
#include "vast/detail/fdinbuf.hpp"
namespace vast {
namespace detail {
line_range::line_range(std::istream& input) : input_{input} {
next(); // prime the pump
}
const std::string& line_range::get() const {
return line_;
}
void line_range::next() {
VAST_ASSERT(!done());
line_.clear();
if (!input_)
return;
// Get the next non-empty line.
while (line_.empty())
if (std::getline(input_, line_))
++line_number_;
else
break;
}
bool line_range::next_timeout(std::chrono::milliseconds timeout) {
auto* p = dynamic_cast<fdinbuf*>(input_.rdbuf());
if (p)
p->read_timeout() = timeout;
// Try to read next line.
next();
bool timed_out = false;
if (p) {
timed_out = p->timed_out();
p->read_timeout() = std::nullopt;
// Clear error state if the read timed out
if (!input_ && timed_out)
input_.clear();
}
return timed_out;
}
bool line_range::done() const {
return line_.empty() && !input_;
}
std::string& line_range::line() {
return line_;
}
size_t line_range::line_number() const {
return line_number_;
}
} // namespace detail
} // namespace vast
| 29.191781 | 80 | 0.502112 | knapperzbusch |
829b0eaf1c0f63af3e7aac9a614b4a929c2b9639 | 273 | cpp | C++ | SEARCHING/EASY/Valid Perfect Square/Code.cpp | HassanRahim26/LEETCODE | c0ec81b037ff7b2d6e6030ac9835c21ed825100f | [
"MIT"
] | 3 | 2021-08-31T11:02:28.000Z | 2022-01-17T08:07:00.000Z | SEARCHING/EASY/Valid Perfect Square/Code.cpp | HassanRahim26/LEETCODE | c0ec81b037ff7b2d6e6030ac9835c21ed825100f | [
"MIT"
] | null | null | null | SEARCHING/EASY/Valid Perfect Square/Code.cpp | HassanRahim26/LEETCODE | c0ec81b037ff7b2d6e6030ac9835c21ed825100f | [
"MIT"
] | null | null | null | /*
PROBLEM LINK:- https://leetcode.com/problems/valid-perfect-square/
*/
class Solution {
public:
bool isPerfectSquare(int num) {
int i = 1;
while(num > 0)
{
num -= i;
i += 2;
}
return num == 0;
}
};
| 16.058824 | 66 | 0.465201 | HassanRahim26 |
829bb6860abb6c29c2f2d34c434dbe7109246650 | 5,825 | cpp | C++ | libcaf_core/src/config_value.cpp | jsiwek/actor-framework | 06cd2836f4671725cb7eaa22b3cc115687520fc1 | [
"BSL-1.0",
"BSD-3-Clause"
] | 4 | 2019-05-03T05:38:15.000Z | 2020-08-25T15:23:19.000Z | libcaf_core/src/config_value.cpp | jsiwek/actor-framework | 06cd2836f4671725cb7eaa22b3cc115687520fc1 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | libcaf_core/src/config_value.cpp | jsiwek/actor-framework | 06cd2836f4671725cb7eaa22b3cc115687520fc1 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2017 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/config_value.hpp"
#include <ostream>
#include "caf/deep_to_string.hpp"
#include "caf/detail/config_consumer.hpp"
#include "caf/detail/parser/read_config.hpp"
#include "caf/detail/type_traits.hpp"
#include "caf/expected.hpp"
#include "caf/parser_state.hpp"
#include "caf/pec.hpp"
#include "caf/string_view.hpp"
namespace caf {
namespace {
const char* type_names[] {
"integer",
"boolean",
"real",
"timespan",
"uri",
"string",
"list",
"dictionary",
};
} // namespace
// -- constructors, destructors, and assignment operators ----------------------
config_value::~config_value() {
// nop
}
// -- parsing ------------------------------------------------------------------
expected<config_value> config_value::parse(string_view::iterator first,
string_view::iterator last) {
using namespace detail;
auto i = first;
// Sanity check.
if (i == last)
return make_error(pec::unexpected_eof);
// Skip to beginning of the argument.
while (isspace(*i))
if (++i == last)
return make_error(pec::unexpected_eof);
// Dispatch to parser.
detail::config_value_consumer f;
string_parser_state res{i, last};
parser::read_config_value(res, f);
if (res.code == pec::success)
return std::move(f.result);
// Assume an unescaped string unless the first character clearly indicates
// otherwise.
switch (*i) {
case '[':
case '{':
case '"':
case '\'':
return make_error(res.code);
default:
if (isdigit(*i))
return make_error(res.code);
return config_value{std::string{first, last}};
}
}
expected<config_value> config_value::parse(string_view str) {
return parse(str.begin(), str.end());
}
// -- properties ---------------------------------------------------------------
void config_value::convert_to_list() {
if (holds_alternative<list>(data_))
return;
using std::swap;
config_value tmp;
swap(*this, tmp);
data_ = std::vector<config_value>{std::move(tmp)};
}
config_value::list& config_value::as_list() {
convert_to_list();
return get<list>(*this);
}
config_value::dictionary& config_value::as_dictionary() {
if (!holds_alternative<dictionary>(*this))
*this = dictionary{};
return get<dictionary>(*this);
}
void config_value::append(config_value x) {
convert_to_list();
get<list>(data_).emplace_back(std::move(x));
}
const char* config_value::type_name() const noexcept {
return type_name_at_index(data_.index());
}
const char* config_value::type_name_at_index(size_t index) noexcept {
return type_names[index];
}
// -- related free functions ---------------------------------------------------
bool operator<(const config_value& x, const config_value& y) {
return x.get_data() < y.get_data();
}
bool operator==(const config_value& x, const config_value& y) {
return x.get_data() == y.get_data();
}
namespace {
void to_string_impl(std::string& str, const config_value& x);
struct to_string_visitor {
std::string& str;
template <class T>
void operator()(const T& x) {
detail::stringification_inspector f{str};
f.value(x);
}
void operator()(const uri& x) {
auto x_str = x.str();
str.insert(str.end(), x_str.begin(), x_str.end());
}
void operator()(const config_value::list& xs) {
if (xs.empty()) {
str += "[]";
return;
}
str += '[';
auto i = xs.begin();
to_string_impl(str, *i);
for (++i; i != xs.end(); ++i) {
str += ", ";
to_string_impl(str, *i);
}
str += ']';
}
void operator()(const config_value::dictionary& xs) {
if (xs.empty()) {
str += "{}";
return;
}
detail::stringification_inspector f{str};
str += '{';
auto i = xs.begin();
f.value(i->first);
str += " = ";
to_string_impl(str, i->second);
for (++i; i != xs.end(); ++i) {
str += ", ";
f.value(i->first);
str += " = ";
to_string_impl(str, i->second);
}
str += '}';
}
};
void to_string_impl(std::string& str, const config_value& x) {
to_string_visitor f{str};
visit(f, x.get_data());
}
} // namespace
std::string to_string(const config_value& x) {
std::string result;
to_string_impl(result, x);
return result;
}
std::ostream& operator<<(std::ostream& out, const config_value& x) {
return out << to_string(x);
}
} // namespace caf
| 27.606635 | 80 | 0.520172 | jsiwek |
829ed32133c42c44b23c23f75f4f8912812a7bda | 3,816 | cpp | C++ | Crypt/test/src/codec/test_extended_precision.cpp | tmiguelf/crypt | bf921f04b035cecaf2a06970d4aaa9a6a9524007 | [
"MIT"
] | null | null | null | Crypt/test/src/codec/test_extended_precision.cpp | tmiguelf/crypt | bf921f04b035cecaf2a06970d4aaa9a6a9524007 | [
"MIT"
] | null | null | null | Crypt/test/src/codec/test_extended_precision.cpp | tmiguelf/crypt | bf921f04b035cecaf2a06970d4aaa9a6a9524007 | [
"MIT"
] | null | null | null | //======== ======== ======== ======== ======== ======== ======== ========
/// \file
///
/// \copyright
/// Copyright (c) Tiago Miguel Oliveira Freire
///
/// 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 <cstdint>
#include <array>
#include <CoreLib/toPrint/toPrint.hpp>
#include <CoreLib/toPrint/toPrint_std_ostream.hpp>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "../../src/codec/extended_precision.hpp"
TEST(extended_precision, umul)
{
struct TestCase
{
uint64_t var1;
uint64_t var2;
uint64_t res_low;
uint64_t res_high;
};
const std::array cases{
TestCase{.var1 = 0, .var2 = 0, .res_low = 0, .res_high = 0},
TestCase{.var1 = 0xFFFF, .var2 = 0xFFFF, .res_low = 0xFFFE0001, .res_high = 0},
TestCase{.var1 = 0xFFFFFFFF, .var2 = 0xFFFFFFFF, .res_low = 0xFFFFFFFE00000001, .res_high = 0},
TestCase{.var1 = 0xFFFFFFFFFFFFFFFF, .var2 = 0xFFFFFFFFFFFFFFFF, .res_low = 0x01, .res_high = 0xFFFFFFFFFFFFFFFE},
TestCase{.var1 = 0xC9562D608F25D51A, .var2 = 0x6666666666666658, .res_low = 0x798D72918C459CF0, .res_high = 0x5088DEf36C758865},
};
for(const TestCase& tcase : cases)
{
uint64_t res_high = 0;
const uint64_t res_low = crypto::umul(tcase.var1, tcase.var2, &res_high);
ASSERT_EQ(res_low, tcase.res_low) << "\nCase: 0x" << core::toPrint_hex(tcase.var1) << " * 0x" << core::toPrint_hex(tcase.var2);
ASSERT_EQ(res_high, tcase.res_high) << "\nCase: 0x" << core::toPrint_hex(tcase.var1) << " * 0x" << core::toPrint_hex(tcase.var2);
}
}
TEST(extended_precision, udiv)
{
struct TestCase
{
uint64_t num_low;
uint64_t num_high;
uint64_t div;
uint64_t res;
uint64_t rem;
};
const std::array cases{
TestCase{.num_low = 0, .num_high=0, .div = 1, .res = 0, .rem = 0},
TestCase{.num_low = 3, .num_high=0, .div = 2, .res = 1, .rem = 1},
TestCase{.num_low = 0x123456, .num_high=0x123, .div = 0x345, .res = 0x5900EAE56403B126, .rem = 0x318},
TestCase{.num_low = 0x01, .num_high=0xFFFFFFFFFFFFFFFE, .div = 0xFFFFFFFFFFFFFFFF, .res = 0xFFFFFFFFFFFFFFFF, .rem = 0x0},
TestCase{.num_low = 0xFFFFFFFFFFFFFFFF, .num_high=0xFFFFFFFFFFFFFFFE, .div = 0xFFFFFFFFFFFFFFFF, .res = 0xFFFFFFFFFFFFFFFF, .rem = 0xFFFFFFFFFFFFFFFE},
};
for(const TestCase& tcase : cases)
{
uint64_t rem = 0;
const uint64_t res = crypto::udiv(tcase.num_high, tcase.num_low, tcase.div, &rem);
ASSERT_EQ(res, tcase.res) << "\nCase: 0x" << core::toPrint_hex(tcase.num_high) << ' ' << core::toPrint_hex(tcase.num_low) << " / 0x" << core::toPrint_hex(tcase.div);
ASSERT_EQ(rem, tcase.rem) << "\nCase: 0x" << core::toPrint_hex(tcase.num_high) << ' ' << core::toPrint_hex(tcase.num_low) << " / 0x" << core::toPrint_hex(tcase.div);
}
}
| 40.168421 | 168 | 0.675839 | tmiguelf |
82a1a5337a5f2704566cd0e39f46aef9a93b22bf | 1,114 | cpp | C++ | 450/Utkarsh/array/mergeTwoSortedArrays.cpp | stunnerhash/Competitive-Programming | 7ef3e36dd1bf5744fb2edea5e64e851c5a02f631 | [
"MIT"
] | 1 | 2021-07-27T03:54:41.000Z | 2021-07-27T03:54:41.000Z | 450/Utkarsh/array/mergeTwoSortedArrays.cpp | stunnerhash/Competitive-Programming | 7ef3e36dd1bf5744fb2edea5e64e851c5a02f631 | [
"MIT"
] | null | null | null | 450/Utkarsh/array/mergeTwoSortedArrays.cpp | stunnerhash/Competitive-Programming | 7ef3e36dd1bf5744fb2edea5e64e851c5a02f631 | [
"MIT"
] | null | null | null | //https://practice.geeksforgeeks.org/problems/merge-two-sorted-arrays5135/1
#include<bits/stdc++.h>
using namespace std;
// literally 4 lines of code
void merge4LOC(int arr1[], int arr2[], int n, int m){
int j = 0, i = n-1;
while(j < m && i > -1 && arr2[j] < arr1[i])
swap(arr2[j++],arr1[i--]);
sort(arr1,arr1+n);
sort(arr2,arr2+m);
}
// Gap method Or shell sort method
class Solution{
public:
int nextGap(int gap) {
if (gap <= 1) return 0;
return (gap / 2) + (gap % 2);
}
public:
void merge(int arr1[], int arr2[], int n, int m) {
int i, j, gap = n + m;
for (gap = nextGap(gap); gap > 0; gap = nextGap(gap)) {
cout<<gap<<" : \n";
for (i = 0; i + gap < n; i++)
if (arr1[i] > arr1[i + gap]) swap(arr1[i], arr1[i + gap]);
for (j = gap > n ? gap - n : 0; i < n && j < m; i++, j++)
if (arr1[i] > arr2[j]) swap(arr1[i], arr2[j]);
if (j < m) {
for (j = 0; j + gap < m; j++)
if (arr2[j] > arr2[j + gap]) swap(arr2[j], arr2[j + gap]);
}
}
}
};
| 25.318182 | 75 | 0.474865 | stunnerhash |
82a7135643c5ad638ba81a7a09343f34bdd26d2d | 234 | cpp | C++ | Road-of-Gold/Road-of-Gold/Sandglass.cpp | SKN-JP/Road_of_gold | f9646656662f38aa292d8b3cdb5be234eb946212 | [
"MIT"
] | 14 | 2017-07-11T13:59:50.000Z | 2017-09-07T01:06:24.000Z | Road-of-Gold/Road-of-Gold/Sandglass.cpp | SKN-JP/Road_of_gold | f9646656662f38aa292d8b3cdb5be234eb946212 | [
"MIT"
] | 10 | 2017-09-25T12:56:05.000Z | 2017-10-20T07:59:06.000Z | Road-of-Gold/Road-of-Gold/Sandglass.cpp | sknjpn/Road-of-Gold | f9646656662f38aa292d8b3cdb5be234eb946212 | [
"MIT"
] | 3 | 2017-08-11T15:54:21.000Z | 2017-08-30T10:20:42.000Z | #include"Sandglass.h"
#include"Planet.h"
Sandglass::Sandglass(double _timer)
: timer(_timer)
{}
bool Sandglass::update()
{
timer += planet.timeSpeed;
if (int(timer) != int(timer - planet.timeSpeed)) return true;
return false;
} | 16.714286 | 62 | 0.705128 | SKN-JP |
82ad71b569e32bf6b137745abfd8119e18f52eb1 | 2,427 | hpp | C++ | library/ATF/ATL___NoAddRefReleaseOnCComPtr.hpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | library/ATF/ATL___NoAddRefReleaseOnCComPtr.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | library/ATF/ATL___NoAddRefReleaseOnCComPtr.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <IPersistStream.hpp>
START_ATF_NAMESPACE
namespace ATL
{
template<>
struct _NoAddRefReleaseOnCComPtr<IPersistStream> : IPersistStream
{
};
}; // end namespace ATL
END_ATF_NAMESPACE
#include <ITypeInfo.hpp>
START_ATF_NAMESPACE
namespace ATL
{
template<>
struct _NoAddRefReleaseOnCComPtr<ITypeInfo> : ITypeInfo
{
};
}; // end namespace ATL
END_ATF_NAMESPACE
#include <IMalloc.hpp>
START_ATF_NAMESPACE
namespace ATL
{
template<>
struct _NoAddRefReleaseOnCComPtr<IMalloc> : IMalloc
{
};
}; // end namespace ATL
END_ATF_NAMESPACE
#include <IPersist.hpp>
START_ATF_NAMESPACE
namespace ATL
{
template<>
struct _NoAddRefReleaseOnCComPtr<IPersist> : IPersist
{
};
}; // end namespace ATL
END_ATF_NAMESPACE
#include <IUnknown.hpp>
START_ATF_NAMESPACE
namespace ATL
{
template<>
struct _NoAddRefReleaseOnCComPtr<IUnknown> : IUnknown
{
};
}; // end namespace ATL
END_ATF_NAMESPACE
#include <ICreateErrorInfo.hpp>
START_ATF_NAMESPACE
namespace ATL
{
template<>
struct _NoAddRefReleaseOnCComPtr<ICreateErrorInfo> : ICreateErrorInfo
{
};
}; // end namespace ATL
END_ATF_NAMESPACE
#include <IDispatch.hpp>
START_ATF_NAMESPACE
namespace ATL
{
template<>
struct _NoAddRefReleaseOnCComPtr<IDispatch> : IDispatch
{
};
}; // end namespace ATL
END_ATF_NAMESPACE
#include <IProvideClassInfo2.hpp>
START_ATF_NAMESPACE
namespace ATL
{
template<>
struct _NoAddRefReleaseOnCComPtr<IProvideClassInfo2> : IProvideClassInfo2
{
};
}; // end namespace ATL
END_ATF_NAMESPACE
#include <ITypeLib.hpp>
START_ATF_NAMESPACE
namespace ATL
{
template<>
struct _NoAddRefReleaseOnCComPtr<ITypeLib> : ITypeLib
{
};
}; // end namespace ATL
END_ATF_NAMESPACE
#include <ICatRegister.hpp>
START_ATF_NAMESPACE
namespace ATL
{
template<>
struct _NoAddRefReleaseOnCComPtr<ICatRegister> : ICatRegister
{
};
}; // end namespace ATL
END_ATF_NAMESPACE
| 19.416 | 108 | 0.643593 | lemkova |
82aecbf1364f19974512ff0d6c907dbad69e603a | 3,387 | cpp | C++ | oem/ibm/libpldmresponder/file_io_type_cert.cpp | ibmzach/pldm | 1a636b2ce8b97e6ea9378632e96532fcbdcbed87 | [
"Apache-2.0"
] | null | null | null | oem/ibm/libpldmresponder/file_io_type_cert.cpp | ibmzach/pldm | 1a636b2ce8b97e6ea9378632e96532fcbdcbed87 | [
"Apache-2.0"
] | null | null | null | oem/ibm/libpldmresponder/file_io_type_cert.cpp | ibmzach/pldm | 1a636b2ce8b97e6ea9378632e96532fcbdcbed87 | [
"Apache-2.0"
] | null | null | null | #include "file_io_type_cert.hpp"
#include "libpldm/base.h"
#include "oem/ibm/libpldm/file_io.h"
#include "utils.hpp"
#include <stdint.h>
#include <iostream>
namespace pldm
{
namespace responder
{
static constexpr auto csrFilePath = "/var/lib/bmcweb/CSR";
static constexpr auto rootCertPath = "/var/lib/bmcweb/RootCert";
static constexpr auto clientCertPath = "/var/lib/bmcweb/ClientCert";
CertMap CertHandler::certMap;
int CertHandler::writeFromMemory(uint32_t offset, uint32_t length,
uint64_t address)
{
auto it = certMap.find(certType);
if (it == certMap.end())
{
std::cerr << "file for type " << certType << " doesn't exist\n";
return PLDM_ERROR;
}
auto fd = std::get<0>(it->second);
auto& remSize = std::get<1>(it->second);
auto rc = transferFileData(fd, false, offset, length, address);
if (rc == PLDM_SUCCESS)
{
remSize -= length;
if (!remSize)
{
close(fd);
certMap.erase(it);
}
}
return rc;
}
int CertHandler::readIntoMemory(uint32_t offset, uint32_t& length,
uint64_t address)
{
if (certType != PLDM_FILE_TYPE_CERT_SIGNING_REQUEST)
{
return PLDM_ERROR_INVALID_DATA;
}
return transferFileData(csrFilePath, true, offset, length, address);
}
int CertHandler::read(uint32_t offset, uint32_t& length, Response& response)
{
if (certType != PLDM_FILE_TYPE_CERT_SIGNING_REQUEST)
{
return PLDM_ERROR_INVALID_DATA;
}
return readFile(csrFilePath, offset, length, response);
}
int CertHandler::write(const char* buffer, uint32_t offset, uint32_t& length)
{
auto it = certMap.find(certType);
if (it == certMap.end())
{
std::cerr << "file for type " << certType << " doesn't exist\n";
return PLDM_ERROR;
}
auto fd = std::get<0>(it->second);
int rc = lseek(fd, offset, SEEK_SET);
if (rc == -1)
{
std::cerr << "lseek failed, ERROR=" << errno << ", OFFSET=" << offset
<< "\n";
return PLDM_ERROR;
}
rc = ::write(fd, buffer, length);
if (rc == -1)
{
std::cerr << "file write failed, ERROR=" << errno
<< ", LENGTH=" << length << ", OFFSET=" << offset << "\n";
return PLDM_ERROR;
}
length = rc;
auto& remSize = std::get<1>(it->second);
remSize -= length;
if (!remSize)
{
close(fd);
certMap.erase(it);
}
return PLDM_SUCCESS;
}
int CertHandler::newFileAvailable(uint64_t length)
{
static constexpr auto vmiCertPath = "/var/lib/bmcweb";
fs::create_directories(vmiCertPath);
int fileFd = -1;
int flags = O_WRONLY | O_CREAT | O_TRUNC;
if (certType == PLDM_FILE_TYPE_CERT_SIGNING_REQUEST)
{
return PLDM_ERROR_INVALID_DATA;
}
if (certType == PLDM_FILE_TYPE_SIGNED_CERT)
{
fileFd = open(clientCertPath, flags);
}
else if (certType == PLDM_FILE_TYPE_ROOT_CERT)
{
fileFd = open(rootCertPath, flags);
}
if (fileFd == -1)
{
std::cerr << "failed to open file for type " << certType
<< " ERROR=" << errno << "\n";
return PLDM_ERROR;
}
certMap.emplace(certType, std::tuple(fileFd, length));
return PLDM_SUCCESS;
}
} // namespace responder
} // namespace pldm
| 25.466165 | 77 | 0.595807 | ibmzach |
82b0b7d4ab50a9732b82868b87bf942d32715ef6 | 5,873 | hxx | C++ | opencascade/IFSelect_Dispatch.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/IFSelect_Dispatch.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/IFSelect_Dispatch.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | // Created on: 1992-11-17
// Created by: Christian CAILLET
// Copyright (c) 1992-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IFSelect_Dispatch_HeaderFile
#define _IFSelect_Dispatch_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Standard_Transient.hxx>
#include <Standard_Boolean.hxx>
#include <Standard_Integer.hxx>
class TCollection_HAsciiString;
class IFSelect_Selection;
class IFSelect_SelectionIterator;
class TCollection_AsciiString;
class Interface_EntityIterator;
class Interface_Graph;
class IFGraph_SubPartsIterator;
class IFSelect_Dispatch;
DEFINE_STANDARD_HANDLE(IFSelect_Dispatch, Standard_Transient)
//! This class allows to describe how a set of Entities has to be
//! dispatched into resulting Packets : a Packet is a sub-set of
//! the initial set of entities.
//!
//! Thus, it can generate zero, one, or more Packets according
//! input set and criterium of dispatching. And it can let apart
//! some entities : it is the Remainder, which can be recovered
//! by a specific Selection (RemainderFromDispatch).
//!
//! Depending of sub-classes, a Dispatch can potentially generate
//! a limited or not count of packet, and a remainder or none.
//!
//! The input set is read from a specified Selection, attached to
//! the Dispatch : the Final Selection of the Dispatch. The input
//! is the Unique Root Entities list of the Final Selection
class IFSelect_Dispatch : public Standard_Transient
{
public:
//! Sets a Root Name as an HAsciiString
//! To reset it, give a Null Handle (then, a ShareOut will have
//! to define the Default Root Name)
Standard_EXPORT void SetRootName (const Handle(TCollection_HAsciiString)& name);
//! Returns True if a specific Root Name has been set
//! (else, the Default Root Name has to be used)
Standard_EXPORT Standard_Boolean HasRootName() const;
//! Returns the Root Name for files produced by this dispatch
//! It is empty if it has not been set or if it has been reset
Standard_EXPORT const Handle(TCollection_HAsciiString)& RootName() const;
//! Stores (or Changes) the Final Selection for a Dispatch
Standard_EXPORT void SetFinalSelection (const Handle(IFSelect_Selection)& sel);
//! Returns the Final Selection of a Dispatch
//! we 'd like : C++ : return const &
Standard_EXPORT Handle(IFSelect_Selection) FinalSelection() const;
//! Returns the complete list of source Selections (starting
//! from FinalSelection)
Standard_EXPORT IFSelect_SelectionIterator Selections() const;
//! Returns True if a Dispatch can have a Remainder, i.e. if its
//! criterium can let entities apart. It is a potential answer,
//! remainder can be empty at run-time even if answer is True.
//! (to attach a RemainderFromDispatch Selection is not allowed if
//! answer is True).
//! Default answer given here is False (can be redefined)
Standard_EXPORT virtual Standard_Boolean CanHaveRemainder() const;
//! Returns True if a Dispatch generates a count of Packets always
//! less than or equal to a maximum value : it can be computed
//! from the total count of Entities to be dispatched : <nbent>.
//! If answer is False, no limited maximum is expected for account
//! If answer is True, expected maximum is given in argument <max>
//! Default answer given here is False (can be redefined)
Standard_EXPORT virtual Standard_Boolean LimitedMax (const Standard_Integer nbent, Standard_Integer& max) const;
//! Returns a text which defines the way a Dispatch produces
//! packets (which will become files) from its Input
Standard_EXPORT virtual TCollection_AsciiString Label() const = 0;
//! Gets Unique Root Entities from the Final Selection, given an
//! input Graph
//! This the starting step for an Evaluation (Packets - Remainder)
Standard_EXPORT Interface_EntityIterator GetEntities (const Interface_Graph& G) const;
//! Returns the list of produced Packets into argument <pack>.
//! Each Packet corresponds to a Part, the Entities listed are the
//! Roots given by the Selection. Input is given as a Graph.
//! Thus, to create a file from a packet, it suffices to take the
//! entities listed in a Part of Packets (that is, a Packet)
//! without worrying about Shared entities
//! This method can raise an Exception if data are not coherent
Standard_EXPORT virtual void Packets (const Interface_Graph& G, IFGraph_SubPartsIterator& packs) const = 0;
//! Returns the list of all Input Entities (see GetEntities) which
//! are put in a Packet. That is, Entities listed in GetEntities
//! but not in Remainder (see below). Input is given as a Graph.
Standard_EXPORT Interface_EntityIterator Packeted (const Interface_Graph& G) const;
//! Returns Remainder which is a set of Entities. Can be empty.
//! Default evaluation is empty (has to be redefined if
//! CanHaveRemainder is redefined to return True).
Standard_EXPORT virtual Interface_EntityIterator Remainder (const Interface_Graph& G) const;
DEFINE_STANDARD_RTTIEXT(IFSelect_Dispatch,Standard_Transient)
protected:
private:
Handle(TCollection_HAsciiString) thename;
Handle(IFSelect_Selection) thefinal;
};
#endif // _IFSelect_Dispatch_HeaderFile
| 38.385621 | 114 | 0.757194 | mgreminger |
a1135c145f9d46f393f3d3f7a88deda642e6a41f | 5,532 | hpp | C++ | src/i_to_s.hpp | paulora2405/tec-tf | a8ff9afd29489ad570f6de283054ffeb67739d46 | [
"MIT"
] | null | null | null | src/i_to_s.hpp | paulora2405/tec-tf | a8ff9afd29489ad570f6de283054ffeb67739d46 | [
"MIT"
] | null | null | null | src/i_to_s.hpp | paulora2405/tec-tf | a8ff9afd29489ad570f6de283054ffeb67739d46 | [
"MIT"
] | null | null | null | #ifndef I_TO_S_HPP
#define I_TO_S_HPP
#include <iostream>
#include <string>
#include <vector>
#include "s_to_i.hpp"
std::vector<quintuple> i_to_s(std::vector<quintuple> m) {
std::cout << "DI to Sipser" << std::endl;
std::vector<quintuple> m_new;
// primeiro passo é renomear o estado inicial de '0' para '0inicial'
for(auto &q : m) {
if(q[0] == "0") q[0] = "0inicial";
if(q[4] == "0") q[4] = "0inicial";
}
/*
* estados auxiliares para o processo de inserir o
* simbolo 'right_limit' no final do conteudo da fita a direita
* e então deslocar todo o conteudo uma célula a direta,
* até ler 2 _ seguidos, e então inserir o 'left_limit' na primeira célula
*/
m_new.push_back(quintuple{"0", "*", "*", "r", "0"});
m_new.push_back(quintuple{"0", "_", "_", "r", "0aux"});
m_new.push_back(quintuple{"0aux", "_", right_limit, "l", "0aux2"});
m_new.push_back(quintuple{"0aux2", "_", "_", "l", "0aux3"});
m_new.push_back(quintuple{"0aux3", "0", "_", "r", "escreve0"});
m_new.push_back(quintuple{"0aux3", "1", "_", "r", "escreve1"});
m_new.push_back(quintuple{"0aux3", "_", left_limit, "r", "0inicial"});
m_new.push_back(quintuple{"escreve0", "_", "0", "l", "0aux2"});
m_new.push_back(quintuple{"escreve1", "_", "1", "l", "0aux2"});
/*
para toda quintupla com movimento para a direita:
cria-se uma transição do estado de origem desta quint
para um estado auxiliar que:
caso leia o 'right_limit':
acrescenta um branco no final da fita
caso nao:
simula movimento estacionario e vai para o estado de destino
*/
for(auto &q : m) {
if(q[3] == "r" && q[4] != "halt-accept") {
// nomes dos estados auxiliares
std::string q0_q1 = "dir_" + q[0] + "_" + q[4];
std::string push = "pushdir_" + q[0] + "_" + q[4];
std::string aux_p = "stopdir_" + q[0] + "_" + q[4];
// quintupla especifica
quintuple esp1{q[0], q[1], q[2], "r", q0_q1};
// quintuplas gerais
quintuple geral1{q0_q1, right_limit, "_", "r", push};
quintuple geral2{push, "_", right_limit, "l", q0_q1};
quintuple geral3{q0_q1, "*", "*", "l", aux_p};
quintuple geral4{aux_p, "*", "*", "r", q[4]};
m_new.push_back(esp1);
if(!q_already_exists(m_new, geral1)) {
m_new.push_back(geral1);
m_new.push_back(geral2);
m_new.push_back(geral3);
m_new.push_back(geral4);
}
// marca a transição original para nao ser inserida
q.push_back("marcada");
}
}
/*
para toda quintupla com movimento para a esquerda:
cria-se uma transição do estado origem desta quint
para um estado auxiliar que
verifica se o simbolo lido é o 'left_limit'
caso for:
percorre toda fita para a direita até ler o 'right_limit'
faz a operação de deslocar a fita uma célula a direita
volta para a célula a direita do 'left_limit'
continua execução
caso não for:
simula movimento estacionário e vai para o estado de destino
*/
// criamos um alfabeto da fita para saber
// todos os simbolos que podem ser escritos, com exceção dos 'limits'
std::vector<std::string> tape_alphabet{"0", "1"};
for(auto &q : m) {
if(!is_in_alphabet(tape_alphabet, q[2])) {
tape_alphabet.push_back(q[2]);
}
}
for(auto &q : m) {
if(q[3] == "l" && q[4] != "halt-accept") {
std::string q0_q1 = "esq_" + q[0] + "_" + q[4];
std::string aux_p = "stopesq_" + q[0] + "_" + q[4];
std::string desloc = "desloc_" + q[0] + "_" + q[4];
std::string daux = "daux_" + q[0] + "_" + q[4];
std::string daux0 = "daux0_" + q[0] + "_" + q[4];
std::string daux1 = "daux1_" + q[0] + "_" + q[4];
// quintuplas especifica
quintuple esp1{q[0], q[1], q[2], "l", q0_q1};
// quintuplas gerais
quintuple geral1{q0_q1, "*", "*", "r", aux_p};
quintuple geral2{aux_p, "*", "*", "l", q[4]};
quintuple geral3{q0_q1, left_limit, left_limit, "l", desloc};
quintuple geral4{desloc, "*", "*", "r", desloc};
quintuple geral5{desloc, right_limit, "_", "r", daux};
quintuple geral6{daux, "_", right_limit, "l", daux0};
quintuple geral7{daux0, "_", "_", "l", daux1};
quintuple geral8{daux1, "_", "_", "l", daux1};
quintuple geral9{daux1, left_limit, left_limit, "r", q[4]};
// quintuplas gerais dinamicas ao alfabeto da fita
std::vector<quintuple> gerais_alfabeto;
for(auto &s : tape_alphabet) {
if(s == "_") continue;
std::string daux2_s = "daux2_" + q[0] + "_" + q[4] + "_" + s;
quintuple geral_tmp1{daux1, s, "_", "r", daux2_s};
quintuple geral_tmp2{daux2_s, "_", s, "l", daux0};
gerais_alfabeto.push_back(geral_tmp1);
gerais_alfabeto.push_back(geral_tmp2);
}
m_new.push_back(esp1);
if(!q_already_exists(m_new, geral1)) {
m_new.push_back(geral1);
m_new.push_back(geral2);
m_new.push_back(geral3);
m_new.push_back(geral4);
m_new.push_back(geral5);
m_new.push_back(geral6);
m_new.push_back(geral7);
m_new.push_back(geral8);
m_new.push_back(geral9);
for(auto &g : gerais_alfabeto) m_new.push_back(g);
}
// marca a transição original para nao ser inserida
q.push_back("marcada");
}
}
// coloca o resto de m em m_new
for(auto &q : m) {
// insere a quintupla apenas se esta nao estiver marcada
if(q.size() == 5) m_new.push_back(q);
}
return m_new;
}
#endif | 34.148148 | 76 | 0.594541 | paulora2405 |
a11d4e9e4a9a1408a579b56384d2b42aae0267e4 | 3,262 | cpp | C++ | src/dawn_wire/client/Fence.cpp | mingmingtasd/Dawn | 3668d352bc5fe13af27dc178d203f67032537a7f | [
"Apache-2.0"
] | null | null | null | src/dawn_wire/client/Fence.cpp | mingmingtasd/Dawn | 3668d352bc5fe13af27dc178d203f67032537a7f | [
"Apache-2.0"
] | null | null | null | src/dawn_wire/client/Fence.cpp | mingmingtasd/Dawn | 3668d352bc5fe13af27dc178d203f67032537a7f | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 The Dawn 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 "dawn_wire/client/Fence.h"
#include "dawn_wire/client/Client.h"
#include "dawn_wire/client/Device.h"
namespace dawn_wire { namespace client {
Fence::~Fence() {
// Callbacks need to be fired in all cases, as they can handle freeing resources
// so we call them with "Unknown" status.
for (auto& it : mOnCompletionRequests) {
if (it.second.callback) {
it.second.callback(WGPUFenceCompletionStatus_Unknown, it.second.userdata);
}
}
mOnCompletionRequests.clear();
}
void Fence::CancelCallbacksForDisconnect() {
for (auto& it : mOnCompletionRequests) {
if (it.second.callback) {
it.second.callback(WGPUFenceCompletionStatus_DeviceLost, it.second.userdata);
}
}
mOnCompletionRequests.clear();
}
void Fence::Initialize(Queue* queue, const WGPUFenceDescriptor* descriptor) {
mQueue = queue;
mCompletedValue = descriptor != nullptr ? descriptor->initialValue : 0u;
}
void Fence::OnCompletion(uint64_t value,
WGPUFenceOnCompletionCallback callback,
void* userdata) {
if (device->GetClient()->IsDisconnected()) {
return callback(WGPUFenceCompletionStatus_DeviceLost, userdata);
}
uint32_t serial = mOnCompletionRequestSerial++;
ASSERT(mOnCompletionRequests.find(serial) == mOnCompletionRequests.end());
FenceOnCompletionCmd cmd;
cmd.fenceId = this->id;
cmd.value = value;
cmd.requestSerial = serial;
mOnCompletionRequests[serial] = {callback, userdata};
this->device->GetClient()->SerializeCommand(cmd);
}
void Fence::OnUpdateCompletedValueCallback(uint64_t value) {
mCompletedValue = value;
}
bool Fence::OnCompletionCallback(uint64_t requestSerial, WGPUFenceCompletionStatus status) {
auto requestIt = mOnCompletionRequests.find(requestSerial);
if (requestIt == mOnCompletionRequests.end()) {
return false;
}
// Remove the request data so that the callback cannot be called again.
// ex.) inside the callback: if the fence is deleted, all callbacks reject.
OnCompletionData request = std::move(requestIt->second);
mOnCompletionRequests.erase(requestIt);
request.callback(status, request.userdata);
return true;
}
uint64_t Fence::GetCompletedValue() const {
return mCompletedValue;
}
Queue* Fence::GetQueue() const {
return mQueue;
}
}} // namespace dawn_wire::client
| 33.979167 | 96 | 0.656959 | mingmingtasd |
a11e761a543db1775f163000577b5f9fc88201c4 | 1,522 | hpp | C++ | src/sequence.hpp | brohan203/rala | 80f6530fa8f2acd96564313790cc559aceb7154f | [
"MIT"
] | 27 | 2017-12-21T17:10:06.000Z | 2020-04-30T22:15:22.000Z | src/sequence.hpp | brohan203/rala | 80f6530fa8f2acd96564313790cc559aceb7154f | [
"MIT"
] | 3 | 2017-12-21T17:10:51.000Z | 2021-05-20T06:03:56.000Z | src/sequence.hpp | brohan203/rala | 80f6530fa8f2acd96564313790cc559aceb7154f | [
"MIT"
] | 3 | 2017-12-05T21:09:00.000Z | 2019-06-14T08:13:28.000Z | /*!
* @file sequence.hpp
*
* @brief Sequence class header file
*/
#pragma once
#include <stdint.h>
#include <memory>
#include <string>
#include <vector>
namespace bioparser {
template<class T>
class FastaParser;
template<class T>
class FastqParser;
}
namespace rala {
class Sequence;
std::unique_ptr<Sequence> createSequence(const std::string& name,
const std::string& data);
class Sequence {
public:
~Sequence() {};
const std::string& name() const {
return name_;
}
const std::string& data() const {
return data_;
}
const std::string& reverse_complement() {
if (reverse_complement_.size() != data_.size()) {
create_reverse_complement();
}
return reverse_complement_;
}
void trim(uint32_t begin, uint32_t end);
friend std::unique_ptr<Sequence> createSequence(const std::string& name,
const std::string& data);
friend bioparser::FastaParser<Sequence>;
friend bioparser::FastqParser<Sequence>;
private:
Sequence(const char* name, uint32_t name_length, const char* data,
uint32_t data_length);
Sequence(const char* name, uint32_t name_length, const char* data,
uint32_t sequence_length, const char* quality, uint32_t quality_length);
Sequence(const Sequence&) = delete;
const Sequence& operator=(const Sequence&) = delete;
void create_reverse_complement();
std::string name_;
std::string data_;
std::string reverse_complement_;
};
}
| 21.742857 | 80 | 0.666229 | brohan203 |
a120420755f343830d7bf06dde501af5fdc17a8b | 1,214 | hpp | C++ | src/test26.hpp | hdhyy/thrust_offer | 84effbd0f033a796375ebf727bafc7b3964ed2a9 | [
"MIT"
] | null | null | null | src/test26.hpp | hdhyy/thrust_offer | 84effbd0f033a796375ebf727bafc7b3964ed2a9 | [
"MIT"
] | null | null | null | src/test26.hpp | hdhyy/thrust_offer | 84effbd0f033a796375ebf727bafc7b3964ed2a9 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
/**
* 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
*
**/
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution
{
public:
TreeNode *Convert(TreeNode *pRootOfTree)
{
TreeNode *lastNodeInList = nullptr;
recursion(pRootOfTree, lastNodeInList);
while (pRootOfTree != nullptr && pRootOfTree->left != nullptr)
{
pRootOfTree = pRootOfTree->left;
}
return pRootOfTree;
}
void recursion(TreeNode *node, TreeNode *&lastNodeInList)
{
if(node == nullptr)
{
return;
}
TreeNode *currentNode = node;
if(currentNode->left != nullptr)
{
recursion(currentNode->left, lastNodeInList);
}
currentNode->left = lastNodeInList;
if(lastNodeInList != nullptr)
{
lastNodeInList->right = currentNode;
}
lastNodeInList = currentNode;
if (currentNode->right != nullptr)
{
recursion(currentNode->right, lastNodeInList);
}
}
}; | 22.90566 | 70 | 0.578254 | hdhyy |
a12081c0f9af539bf7929dbb85632c56f5dc2d73 | 2,703 | cpp | C++ | c_cpp/api.cpp | dujeonglee/NetworkCodingRev | 5964569af376d8b8f9ee14cd025f74eff9088b2c | [
"MIT"
] | 6 | 2017-03-29T03:17:54.000Z | 2017-12-26T23:36:14.000Z | c_cpp/api.cpp | dujeonglee/NetworkCodingRev | 5964569af376d8b8f9ee14cd025f74eff9088b2c | [
"MIT"
] | 6 | 2017-04-24T12:56:01.000Z | 2018-01-01T13:18:44.000Z | c_cpp/api.cpp | dujeonglee/NetworkCodingRev | 5964569af376d8b8f9ee14cd025f74eff9088b2c | [
"MIT"
] | 2 | 2017-06-08T07:31:09.000Z | 2019-08-05T01:54:58.000Z | #include "api.h"
#include "ncsocket.h"
using namespace NetworkCoding;
void *InitSocket(const char *const local_port, const uint32_t RxTimeout, const uint32_t TxTimeout, const std::function<void(uint8_t *const buffer, const uint16_t length, const void *const sender_addr, const uint32_t sender_addr_len)> cb)
{
return new NCSocket(std::string(local_port), RxTimeout, TxTimeout, cb);
}
bool Connect(void *const handle, const char *const ip, const char *const port, const uint32_t timeout, const uint8_t TransmissionMode, const uint8_t BlockSize, const uint16_t RetransmissionRedundancy)
{
if (TransmissionMode != Parameter::TRANSMISSION_MODE::RELIABLE_TRANSMISSION_MODE &&
TransmissionMode != Parameter::TRANSMISSION_MODE::BEST_EFFORT_TRANSMISSION_MODE)
{
return false;
}
if (BlockSize != Parameter::BLOCK_SIZE::BLOCK_SIZE_04 &&
BlockSize != Parameter::BLOCK_SIZE::BLOCK_SIZE_08 &&
BlockSize != Parameter::BLOCK_SIZE::BLOCK_SIZE_12 &&
BlockSize != Parameter::BLOCK_SIZE::BLOCK_SIZE_16 &&
BlockSize != Parameter::BLOCK_SIZE::BLOCK_SIZE_20 &&
BlockSize != Parameter::BLOCK_SIZE::BLOCK_SIZE_24 &&
BlockSize != Parameter::BLOCK_SIZE::BLOCK_SIZE_28 &&
BlockSize != Parameter::BLOCK_SIZE::BLOCK_SIZE_32 &&
BlockSize != Parameter::BLOCK_SIZE::BLOCK_SIZE_64 &&
BlockSize != Parameter::BLOCK_SIZE::BLOCK_SIZE_128)
{
return false;
}
return ((NCSocket *)handle)->Connect(std::string(ip), std::string(port), timeout, (Parameter::TRANSMISSION_MODE)TransmissionMode, (Parameter::BLOCK_SIZE)BlockSize, RetransmissionRedundancy);
}
void Disconnect(void *const handle, const char *const ip, const char *const port)
{
return ((NCSocket *)handle)->Disconnect(std::string(ip), std::string(port));
}
bool Send(void *const handle, const char *const ip, const char *const port, uint8_t *const buff, const uint16_t size)
{
return ((NCSocket *)handle)->Send(std::string(ip), std::string(port), buff, size);
}
bool Flush(void *const handle, const char *const ip, const char *const port)
{
return ((NCSocket *)handle)->Flush(std::string(ip), std::string(port));
}
void WaitUntilTxIsCompleted(void *const handle, const char *const ip, const char *const port)
{
return ((NCSocket *)handle)->WaitUntilTxIsCompleted(std::string(ip), std::string(port));
}
bool Receive(void *const handle, uint8_t *const buffer, uint16_t *const length, void *const address, uint32_t *const sender_addr_len, uint32_t timeout)
{
return ((NCSocket *)handle)->Receive(buffer, length, (sockaddr *)address, sender_addr_len, timeout);
}
void FreeSocket(void *handle)
{
delete ((NCSocket *)handle);
}
| 42.904762 | 237 | 0.721791 | dujeonglee |
a120d7aedfad4b2c8461ea3d7c89189fb6888ebd | 538 | hpp | C++ | day10/Location.hpp | bcafuk/AoC-2019 | 5ff9b86f8483cd7a6e229d572ae9e34b894eb574 | [
"Zlib"
] | null | null | null | day10/Location.hpp | bcafuk/AoC-2019 | 5ff9b86f8483cd7a6e229d572ae9e34b894eb574 | [
"Zlib"
] | null | null | null | day10/Location.hpp | bcafuk/AoC-2019 | 5ff9b86f8483cd7a6e229d572ae9e34b894eb574 | [
"Zlib"
] | 2 | 2020-11-02T09:24:35.000Z | 2020-12-02T09:46:27.000Z | #ifndef AOC_2019_DAY10_LOCATION_HPP
#define AOC_2019_DAY10_LOCATION_HPP
typedef int coordinate;
struct Location {
coordinate x;
coordinate y;
Location(coordinate x, coordinate y);
void reduce();
double phiAround(const Location &origin) const;
bool operator<(const Location &other) const;
bool operator==(const Location &other) const;
bool insideRect(const Location &topLeft, const Location &bottomRight) const;
Location operator+ (const Location &other) const;
Location operator- (const Location &other) const;
};
#endif
| 22.416667 | 77 | 0.775093 | bcafuk |
a121b24981e2831079debca851e3af84427c6739 | 4,661 | cpp | C++ | src/org/apache/poi/poifs/filesystem/NPOIFSStream_StreamBlockByteBuffer.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/poifs/filesystem/NPOIFSStream_StreamBlockByteBuffer.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/poifs/filesystem/NPOIFSStream_StreamBlockByteBuffer.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /POI/java/org/apache/poi/poifs/filesystem/NPOIFSStream.java
#include <org/apache/poi/poifs/filesystem/NPOIFSStream_StreamBlockByteBuffer.hpp>
#include <java/lang/IndexOutOfBoundsException.hpp>
#include <java/lang/Math.hpp>
#include <java/lang/NullPointerException.hpp>
#include <java/nio/ByteBuffer.hpp>
#include <org/apache/poi/poifs/common/POIFSConstants.hpp>
#include <org/apache/poi/poifs/filesystem/BlockStore_ChainLoopDetector.hpp>
#include <org/apache/poi/poifs/filesystem/BlockStore.hpp>
#include <org/apache/poi/poifs/filesystem/NPOIFSStream.hpp>
#include <Array.hpp>
template<typename T>
static T* npc(T* t)
{
if(!t) throw new ::java::lang::NullPointerException();
return t;
}
poi::poifs::filesystem::NPOIFSStream_StreamBlockByteBuffer::NPOIFSStream_StreamBlockByteBuffer(NPOIFSStream *NPOIFSStream_this, const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
, NPOIFSStream_this(NPOIFSStream_this)
{
clinit();
}
poi::poifs::filesystem::NPOIFSStream_StreamBlockByteBuffer::NPOIFSStream_StreamBlockByteBuffer(NPOIFSStream *NPOIFSStream_this) /* throws(IOException) */
: NPOIFSStream_StreamBlockByteBuffer(NPOIFSStream_this, *static_cast< ::default_init_tag* >(0))
{
ctor();
}
void poi::poifs::filesystem::NPOIFSStream_StreamBlockByteBuffer::init()
{
oneByte = new ::int8_tArray(int32_t(1));
}
void poi::poifs::filesystem::NPOIFSStream_StreamBlockByteBuffer::ctor() /* throws(IOException) */
{
super::ctor();
init();
loopDetector = npc(NPOIFSStream_this->blockStore)->getChainLoopDetector();
prevBlock = ::poi::poifs::common::POIFSConstants::END_OF_CHAIN;
nextBlock = NPOIFSStream_this->startBlock;
}
void poi::poifs::filesystem::NPOIFSStream_StreamBlockByteBuffer::createBlockIfNeeded() /* throws(IOException) */
{
if(buffer != nullptr && npc(buffer)->hasRemaining())
return;
auto thisBlock = nextBlock;
if(thisBlock == ::poi::poifs::common::POIFSConstants::END_OF_CHAIN) {
thisBlock = npc(NPOIFSStream_this->blockStore)->getFreeBlock();
npc(loopDetector)->claim(thisBlock);
nextBlock = ::poi::poifs::common::POIFSConstants::END_OF_CHAIN;
if(prevBlock != ::poi::poifs::common::POIFSConstants::END_OF_CHAIN) {
npc(NPOIFSStream_this->blockStore)->setNextBlock(prevBlock, thisBlock);
}
npc(NPOIFSStream_this->blockStore)->setNextBlock(thisBlock, ::poi::poifs::common::POIFSConstants::END_OF_CHAIN);
if(NPOIFSStream_this->startBlock == ::poi::poifs::common::POIFSConstants::END_OF_CHAIN) {
NPOIFSStream_this->startBlock = thisBlock;
}
} else {
npc(loopDetector)->claim(thisBlock);
nextBlock = npc(NPOIFSStream_this->blockStore)->getNextBlock(thisBlock);
}
buffer = npc(NPOIFSStream_this->blockStore)->createBlockIfNeeded(thisBlock);
prevBlock = thisBlock;
}
void poi::poifs::filesystem::NPOIFSStream_StreamBlockByteBuffer::write(int32_t b) /* throws(IOException) */
{
(*oneByte)[int32_t(0)] = static_cast< int8_t >((b & int32_t(255)));
write(oneByte);
}
void poi::poifs::filesystem::NPOIFSStream_StreamBlockByteBuffer::write(::int8_tArray* b, int32_t off, int32_t len) /* throws(IOException) */
{
if((off < 0) || (off > npc(b)->length) || (len < 0)|| ((off + len) > npc(b)->length)|| ((off + len) < 0)) {
throw new ::java::lang::IndexOutOfBoundsException();
} else if(len == 0) {
return;
}
do {
createBlockIfNeeded();
auto writeBytes = ::java::lang::Math::min(npc(buffer)->remaining(), len);
npc(buffer)->put(b, off, writeBytes);
off += writeBytes;
len -= writeBytes;
} while (len > 0);
}
void poi::poifs::filesystem::NPOIFSStream_StreamBlockByteBuffer::close() /* throws(IOException) */
{
auto toFree = new NPOIFSStream(NPOIFSStream_this->blockStore, nextBlock);
npc(toFree)->free(loopDetector);
if(prevBlock != ::poi::poifs::common::POIFSConstants::END_OF_CHAIN) {
npc(NPOIFSStream_this->blockStore)->setNextBlock(prevBlock, ::poi::poifs::common::POIFSConstants::END_OF_CHAIN);
}
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* poi::poifs::filesystem::NPOIFSStream_StreamBlockByteBuffer::class_()
{
static ::java::lang::Class* c = ::class_(u"org.apache.poi.poifs.filesystem.NPOIFSStream.StreamBlockByteBuffer", 66);
return c;
}
void poi::poifs::filesystem::NPOIFSStream_StreamBlockByteBuffer::write(::int8_tArray* b)
{
super::write(b);
}
java::lang::Class* poi::poifs::filesystem::NPOIFSStream_StreamBlockByteBuffer::getClass0()
{
return class_();
}
| 38.204918 | 154 | 0.708432 | pebble2015 |
a121b71ae46ef022b946edd6336f97ba278ef8b7 | 683 | cpp | C++ | libs/renderer/src/renderer/lock_flags/read.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/renderer/src/renderer/lock_flags/read.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/renderer/src/renderer/lock_flags/read.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <sge/renderer/lock_flags/method.hpp>
#include <sge/renderer/lock_flags/read.hpp>
#include <fcppt/assert/unreachable.hpp>
bool sge::renderer::lock_flags::read(sge::renderer::lock_flags::method const _method)
{
switch (_method)
{
case sge::renderer::lock_flags::method::read:
case sge::renderer::lock_flags::method::readwrite:
return true;
case sge::renderer::lock_flags::method::write:
return false;
}
FCPPT_ASSERT_UNREACHABLE;
}
| 29.695652 | 85 | 0.717423 | cpreh |
a12e874958cae53c82f63bd28b5c88d9da6d7ece | 537 | cpp | C++ | src/algorithms/warmup/compare_the_triplets/compare_the_triplets.cpp | bmgandre/hackerrank-cpp | f4af5777afba233c284790e02c0be7b82108c677 | [
"MIT"
] | null | null | null | src/algorithms/warmup/compare_the_triplets/compare_the_triplets.cpp | bmgandre/hackerrank-cpp | f4af5777afba233c284790e02c0be7b82108c677 | [
"MIT"
] | null | null | null | src/algorithms/warmup/compare_the_triplets/compare_the_triplets.cpp | bmgandre/hackerrank-cpp | f4af5777afba233c284790e02c0be7b82108c677 | [
"MIT"
] | null | null | null | #include "compare_the_triplets.h"
#include <iostream>
#include <string>
#include <regex>
using namespace hackerrank::bmgandre::algorithms::warmup;
/// Practice>Algorithms>Warmup>Compare the Triplets
///
/// https://www.hackerrank.com/challenges/compare-the-triplets
void compare_the_triplets::solve()
{
int a0, a1, a2;
std::cin >> a0 >> a1 >> a2;
int b0, b1, b2;
std::cin >> b0 >> b1 >> b2;
int a = int(a0 > b0) + int(a1 > b1) + int(a2 > b2);
int b = int(b0 > a0) + int(b1 > a1) + int(b2 > a2);
std::cout << a << " " << b;
}
| 22.375 | 62 | 0.627561 | bmgandre |
a13154240fcf3b030de8aa4682cab655638c2eda | 311 | cpp | C++ | offline_compiler/utilities/windows/get_current_dir_windows.cpp | FelipeMLopez/compute-runtime | 3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8 | [
"MIT"
] | null | null | null | offline_compiler/utilities/windows/get_current_dir_windows.cpp | FelipeMLopez/compute-runtime | 3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8 | [
"MIT"
] | null | null | null | offline_compiler/utilities/windows/get_current_dir_windows.cpp | FelipeMLopez/compute-runtime | 3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2019 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "Windows.h"
#include <string>
std::string getCurrentDirectoryOwn(std::string outDirForBuilds) {
char buf[256];
GetCurrentDirectoryA(256, buf);
return std::string(buf) + "\\" + outDirForBuilds + "\\";
}
| 18.294118 | 65 | 0.662379 | FelipeMLopez |
a134300173d0d46dd4f1d85e7ec54132a9015545 | 2,170 | hpp | C++ | d03/ex01/FragTrap.hpp | ncoden/42_CPP_pool | 9f2d9aa030b65e3ad967086bff97e80e23705a29 | [
"Apache-2.0"
] | 5 | 2018-02-10T12:33:53.000Z | 2021-03-28T09:27:05.000Z | d03/ex01/FragTrap.hpp | ncoden/42_CPP_pool | 9f2d9aa030b65e3ad967086bff97e80e23705a29 | [
"Apache-2.0"
] | null | null | null | d03/ex01/FragTrap.hpp | ncoden/42_CPP_pool | 9f2d9aa030b65e3ad967086bff97e80e23705a29 | [
"Apache-2.0"
] | 6 | 2017-11-25T17:34:43.000Z | 2020-12-20T12:00:04.000Z | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* FragTrap.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ncoden <ncoden@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/06/18 11:38:22 by ncoden #+# #+# */
/* Updated: 2015/06/18 17:25:46 by ncoden ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FRAGTRAP_H
# define FRAGTRAP_H
# include <string>
class FragTrap
{
private:
static int _attack_number;
static unsigned int (FragTrap::*_attacks[])(std::string const &target);
static unsigned int const _maxHitPoints;
static unsigned int const _maxEnergyPoints;
static unsigned int const _armorDamageReduction;
public:
static unsigned int const meleeAttackDamage;
static unsigned int const rangedAttackDamage;
private:
std::string _name;
unsigned int _hitPoints;
unsigned int _energyPoints;
unsigned int _level;
public:
FragTrap(std::string name);
~FragTrap(void);
FragTrap(FragTrap const &src);
FragTrap &operator=(FragTrap const &rhs);
void rangedAttack(std::string const &target);
void meleeAttack(std::string const &target);
void takeDamage(unsigned int amount);
void beRepaired(unsigned int amount);
unsigned int vaulthunter_dot_exe(std::string const &target);
unsigned int clapInTheBox(std::string const &target);
unsigned int laserInferno(std::string const &target);
unsigned int torgueFiesta(std::string const &target);
unsigned int pirateShipMode(std::string const &target);
unsigned int oneShotWonder(std::string const &target);
std::string &getName(void);
};
#endif
| 35.57377 | 80 | 0.480184 | ncoden |
a13952e219689ffabcb482681ebd38468543a617 | 3,573 | cpp | C++ | src/tut15/Engine/Engine/graphicsclass.cpp | Scillman/rastertek-dx11-tutorials | 3aee1e19eaf6e4e8e9a44c88a83ac50acdcb05c6 | [
"Unlicense"
] | null | null | null | src/tut15/Engine/Engine/graphicsclass.cpp | Scillman/rastertek-dx11-tutorials | 3aee1e19eaf6e4e8e9a44c88a83ac50acdcb05c6 | [
"Unlicense"
] | null | null | null | src/tut15/Engine/Engine/graphicsclass.cpp | Scillman/rastertek-dx11-tutorials | 3aee1e19eaf6e4e8e9a44c88a83ac50acdcb05c6 | [
"Unlicense"
] | 1 | 2018-06-26T01:29:41.000Z | 2018-06-26T01:29:41.000Z | ////////////////////////////////////////////////////////////////////////////////
// Filename: graphicsclass.cpp
////////////////////////////////////////////////////////////////////////////////
#include "graphicsclass.h"
GraphicsClass::GraphicsClass()
{
m_D3D = 0;
m_Camera = 0;
m_Text = 0;
}
GraphicsClass::GraphicsClass(const GraphicsClass& other)
{
}
GraphicsClass::~GraphicsClass()
{
}
bool GraphicsClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
{
bool result;
D3DXMATRIX baseViewMatrix;
// Create the Direct3D object.
m_D3D = new D3DClass;
if(!m_D3D)
{
return false;
}
// Initialize the Direct3D object.
result = m_D3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR);
if(!result)
{
MessageBox(hwnd, L"Could not initialize Direct3D", L"Error", MB_OK);
return false;
}
// Create the camera object.
m_Camera = new CameraClass;
if(!m_Camera)
{
return false;
}
// Initialize a base view matrix with the camera for 2D user interface rendering.
m_Camera->SetPosition(0.0f, 0.0f, -1.0f);
m_Camera->Render();
m_Camera->GetViewMatrix(baseViewMatrix);
// Create the text object.
m_Text = new TextClass;
if(!m_Text)
{
return false;
}
// Initialize the text object.
result = m_Text->Initialize(m_D3D->GetDevice(), m_D3D->GetDeviceContext(), hwnd, screenWidth, screenHeight, baseViewMatrix);
if(!result)
{
MessageBox(hwnd, L"Could not initialize the text object.", L"Error", MB_OK);
return false;
}
return true;
}
void GraphicsClass::Shutdown()
{
// Release the text object.
if(m_Text)
{
m_Text->Shutdown();
delete m_Text;
m_Text = 0;
}
// Release the camera object.
if(m_Camera)
{
delete m_Camera;
m_Camera = 0;
}
// Release the D3D object.
if(m_D3D)
{
m_D3D->Shutdown();
delete m_D3D;
m_D3D = 0;
}
return;
}
bool GraphicsClass::Frame(int fps, int cpu, float frameTime)
{
bool result;
// Set the frames per second.
result = m_Text->SetFps(fps, m_D3D->GetDeviceContext());
if(!result)
{
return false;
}
// Set the cpu usage.
result = m_Text->SetCpu(cpu, m_D3D->GetDeviceContext());
if(!result)
{
return false;
}
// Set the position of the camera.
m_Camera->SetPosition(0.0f, 0.0f, -10.0f);
return true;
}
bool GraphicsClass::Render()
{
D3DXMATRIX worldMatrix, viewMatrix, projectionMatrix, orthoMatrix;
bool result;
// Clear the buffers to begin the scene.
m_D3D->BeginScene(0.0f, 0.0f, 0.0f, 1.0f);
// Generate the view matrix based on the camera's position.
m_Camera->Render();
// Get the view, projection, and world matrices from the camera and D3D objects.
m_Camera->GetViewMatrix(viewMatrix);
m_D3D->GetWorldMatrix(worldMatrix);
m_D3D->GetProjectionMatrix(projectionMatrix);
m_D3D->GetOrthoMatrix(orthoMatrix);
// Turn off the Z buffer to begin all 2D rendering.
m_D3D->TurnZBufferOff();
// Turn on the alpha blending before rendering the text.
m_D3D->TurnOnAlphaBlending();
// Render the text strings.
result = m_Text->Render(m_D3D->GetDeviceContext(), worldMatrix, orthoMatrix);
if(!result)
{
return false;
}
// Turn off alpha blending after rendering the text.
m_D3D->TurnOffAlphaBlending();
// Turn the Z buffer back on now that all 2D rendering has completed.
m_D3D->TurnZBufferOn();
// Present the rendered scene to the screen.
m_D3D->EndScene();
return true;
} | 20.534483 | 126 | 0.640078 | Scillman |
a13ab89ae6ddc47835f8eb94ed070b882c0572cc | 1,118 | cxx | C++ | src/pre.cxx | asiarabbit/BINGER | f525a7445be1aa3ac3f8fb235f6097c999f25f2d | [
"MIT"
] | 1 | 2017-11-23T14:47:47.000Z | 2017-11-23T14:47:47.000Z | src/pre.cxx | asiarabbit/BINGER | f525a7445be1aa3ac3f8fb235f6097c999f25f2d | [
"MIT"
] | null | null | null | src/pre.cxx | asiarabbit/BINGER | f525a7445be1aa3ac3f8fb235f6097c999f25f2d | [
"MIT"
] | null | null | null | /**
\file pre.C
\example pre.C
\brief Input a PXI and a VME binary raw data file to be decoded and analyzed for Daq evaluation,
detector debugging, or PID output.
\author SUN Yazhou, asia.rabbit@163.com.
\date Created: 2017/12/1 Last revised: 2018/8/18, SUN Yazhou.
\copyright 2017-2018, SUN Yazhou.
*/
#include <iostream>
#include <cstdlib>
#include "TAUI.h"
using std::cout;
using std::endl;
// pion: 0.24835; C16: 1.45; C15: 1.295; C14: 1.20; C12: 0.9535
// unit: Telsa 0-C16 1-C15 2-C14 3-C13, 4-C12 5-O18 6-O18-NOTA
const double B[] = {1.45, 1.295, 1.2006, 1.075, 0.9535, 1.2004, 1.2336};
int main(int argc, char *argv[]){
TAUI *usr = TAUI::Instance();
usr->GetOpt(argc, argv); // parse the user input parameter list
//user options
usr->SetMagneticIntensity(B[0]);
// usr->BunchIdMisAlignCheck();
// usr->Silent(); // don't show TAPopMsg::Info() printings
// usr->CheckChannelId(403); // see channel with channelId
// usr->CoarseFit();
// usr->Verbose(); // DEBUG
usr->Go(); // pattern recognition, track fit, and particle identification
return 0;
} // end of the main function
| 27.95 | 97 | 0.669946 | asiarabbit |
a13ea0dd9f9375ac70e9325f34841dba7ce186f5 | 3,317 | cpp | C++ | MultiSampling/MultiSampling/RenderingEngine.cpp | chunkyguy/EWOGL | 29fd10b37e2e19e5e586c7ca794649200c514b7b | [
"MIT"
] | 2 | 2015-03-25T23:20:33.000Z | 2016-12-03T04:37:46.000Z | MultiSampling/MultiSampling/RenderingEngine.cpp | chunkyguy/EWOGL | 29fd10b37e2e19e5e586c7ca794649200c514b7b | [
"MIT"
] | null | null | null | MultiSampling/MultiSampling/RenderingEngine.cpp | chunkyguy/EWOGL | 29fd10b37e2e19e5e586c7ca794649200c514b7b | [
"MIT"
] | null | null | null | //
// RenderingEngine.cpp
// MultiSampling
//
// Created by Sid on 24/01/14.
// Copyright (c) 2014 whackylabs. All rights reserved.
//
#include "RenderingEngine.h"
#include <cassert>
#include <cstring>
#include <iostream>
#include <GLKit/GLKMath.h>
#include <OpenGLES/ES2/gl.h>
#include <OpenGLES/ES2/glext.h>
#include "Geometry.h"
#include "ShaderProgram.h"
enum {
FBO_Main = 0,
FBO_Multisample
};
enum {
RBO_ColorMain = 0,
#if defined (MSAA_ENABLED)
RBO_ColorMultisample,
RBO_DepthMultisample
#else
RBO_DepthMain,
#endif
};
RenderingEngine::RenderingEngine() :
fbo_(),
rbo_(),
geometry_(NULL),
shader_(NULL),
renderer_(),
bufferWidth_(0),
bufferHeight_(0)
{}
void RenderingEngine::Init(const RenderBufferStorage &renderbufferStorage, void *context)
{
/*create buffers */
glGenFramebuffers(2, fbo_);
glGenRenderbuffers(3, rbo_);
/* bind main framebuffer */
glBindFramebuffer(GL_FRAMEBUFFER, fbo_[FBO_Main]);
/* bind main color renderbuffer */
glBindRenderbuffer(GL_RENDERBUFFER, rbo_[RBO_ColorMain]);
renderbufferStorage(context);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbo_[RBO_ColorMain]);
/* read framebuffer dimension */
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &bufferWidth_);
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &bufferHeight_);
#if !defined (MSAA_ENABLED)
glBindRenderbuffer(GL_RENDERBUFFER, rbo_[RBO_DepthMain]);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, bufferWidth_, bufferHeight_);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbo_[RBO_DepthMain]);
#endif
assert (glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
#if defined (MSAA_ENABLED)
bind_msaa_framebuffer(fbo_[FBO_Multisample], rbo_[RBO_ColorMultisample], rbo_[RBO_DepthMultisample]);
#endif
glViewport(0, 0, bufferWidth_, bufferHeight_);
glEnable(GL_DEPTH_TEST);
}
RenderingEngine::~RenderingEngine()
{
glDeleteFramebuffers(2, fbo_);
glDeleteRenderbuffers(3, rbo_);
}
void RenderingEngine::Draw(size_t width, size_t height, unsigned int dt)
{
assert(shader_);
assert(geometry_);
#if defined (MSAA_ENABLED)
glBindFramebuffer(GL_FRAMEBUFFER, fbo_[FBO_Multisample]);
#else
glBindFramebuffer(GL_FRAMEBUFFER, fbo_[FBO_Main]);
#endif
glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
/* bind shader */
glUseProgram(shader_->GetProgram());
/* create renderer */
renderer_.program = shader_->GetProgram();
renderer_.projection = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(60.0f),
static_cast<float>(width)/height,
0.1f, 100.0f);
/* draw geoemtry */
geometry_->Update(dt);
geometry_->Draw(&renderer_);
resolve_msaa(fbo_[FBO_Multisample], fbo_[FBO_Main]);
glBindRenderbuffer(GL_RENDERBUFFER, rbo_[RBO_ColorMain]);
glDisableVertexAttribArray(kAttribPosition);
glDisableVertexAttribArray(kAttribNormal);
}
void RenderingEngine::BindShader(const ShaderProgram *shader)
{
shader_ = shader;
}
void RenderingEngine::BindGeometry(IGeometry *geometry)
{
geometry_ = geometry;
}
| 24.753731 | 104 | 0.737715 | chunkyguy |
a141c478c2c5847985d741ea919e50b31662f4be | 2,576 | cpp | C++ | cpp/timer_helper.cpp | uniqss/uniqstimer | 7b2da3533a0e33c41b4de6f57193979f1e22bce0 | [
"MIT"
] | 8 | 2020-10-26T01:30:43.000Z | 2022-03-17T11:15:27.000Z | cpp/timer_helper.cpp | uniqss/uniqstimer | 7b2da3533a0e33c41b4de6f57193979f1e22bce0 | [
"MIT"
] | null | null | null | cpp/timer_helper.cpp | uniqss/uniqstimer | 7b2da3533a0e33c41b4de6f57193979f1e22bce0 | [
"MIT"
] | 1 | 2020-11-30T08:29:14.000Z | 2020-11-30T08:29:14.000Z | #include "timer_helper.h"
#include<time.h>
#include<stdexcept>
int UniqsTimerAllocCalled = 0;
int UniqsTimerFreeCalled = 0;
TimerNode* __pFreeTimerHeadMem;
int UniqsTimerFreeCount = 0;
const int UNIQS_TIMER_CACHE_MAX = 4096;
const int UNIQS_TIMER_CACHE_DELETE = UNIQS_TIMER_CACHE_MAX / 2;
TimerNodeIII* __pFreeTimerHeadMemIII;
int UniqsTimerFreeCountIII = 0;
const int UNIQS_TIMER_CACHE_MAXIII = 4096;
const int UNIQS_TIMER_CACHE_DELETEIII = UNIQS_TIMER_CACHE_MAXIII / 2;
TimerNode* AllocObj()
{
UniqsTimerAllocCalled++;
if (__pFreeTimerHeadMem != nullptr)
{
UniqsTimerFreeCount--;
TimerNode* pTimer = __pFreeTimerHeadMem;
__pFreeTimerHeadMem = pTimer->pNext;
pTimer->pNext = nullptr;
return pTimer;
}
auto ret = new TimerNode();
return ret;
}
void FreeObj(TimerNode* pTimer)
{
UniqsTimerFreeCalled++;
UniqsTimerFreeCount++;
if (__pFreeTimerHeadMem == nullptr)
{
__pFreeTimerHeadMem = pTimer;
__pFreeTimerHeadMem->pNext = nullptr;
}
else
{
pTimer->pNext = __pFreeTimerHeadMem;
__pFreeTimerHeadMem = pTimer;
}
if (UniqsTimerFreeCount > UNIQS_TIMER_CACHE_MAX)
{
TimerNode* pDelete = __pFreeTimerHeadMem;
for (int i = 0; i < UNIQS_TIMER_CACHE_DELETE; i++)
{
__pFreeTimerHeadMem = pDelete->pNext;
// free memory
delete pDelete;
pDelete = __pFreeTimerHeadMem;
}
UniqsTimerFreeCount -= UNIQS_TIMER_CACHE_DELETE;
}
}
TimerNodeIII* AllocObjIII()
{
if (__pFreeTimerHeadMemIII != nullptr)
{
UniqsTimerFreeCountIII--;
TimerNodeIII* pTimer = __pFreeTimerHeadMemIII;
__pFreeTimerHeadMemIII = pTimer->pNext;
pTimer->pNext = nullptr;
return pTimer;
}
auto ret = new TimerNodeIII();
return ret;
}
void FreeObjIII(TimerNodeIII* pTimer)
{
UniqsTimerFreeCountIII++;
if (__pFreeTimerHeadMemIII == nullptr)
{
__pFreeTimerHeadMemIII = pTimer;
__pFreeTimerHeadMemIII->pNext = nullptr;
}
else
{
pTimer->pNext = __pFreeTimerHeadMemIII;
__pFreeTimerHeadMemIII = pTimer;
}
if (UniqsTimerFreeCountIII > UNIQS_TIMER_CACHE_MAXIII)
{
TimerNodeIII* pDelete = __pFreeTimerHeadMemIII;
for (int i = 0; i < UNIQS_TIMER_CACHE_DELETEIII; i++)
{
__pFreeTimerHeadMemIII = pDelete->pNext;
// free memory
delete pDelete;
pDelete = __pFreeTimerHeadMemIII;
}
UniqsTimerFreeCountIII -= UNIQS_TIMER_CACHE_DELETEIII;
}
}
TimerMsType UTimerGetCurrentTimeMS(void)
{
return clock();
}
void OnTimerError(const std::string& err)
{
throw std::logic_error("OnTimerError" + err);
}
| 21.647059 | 70 | 0.713509 | uniqss |
a142e0a1cadf4597a9eca2640c6698863c5e4ac0 | 3,043 | hpp | C++ | include/codegen/include/System/Net/Sockets/SocketAsyncEventArgs.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/System/Net/Sockets/SocketAsyncEventArgs.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/System/Net/Sockets/SocketAsyncEventArgs.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:19 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
// Including type: System.EventArgs
#include "System/EventArgs.hpp"
// Including type: System.Net.Sockets.SocketError
#include "System/Net/Sockets/SocketError.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Net
namespace System::Net {
// Forward declaring type: EndPoint
class EndPoint;
}
// Forward declaring namespace: System::Net::Sockets
namespace System::Net::Sockets {
// Forward declaring type: Socket
class Socket;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: EventHandler`1<TEventArgs>
template<typename TEventArgs>
class EventHandler_1;
}
// Completed forward declares
// Type namespace: System.Net.Sockets
namespace System::Net::Sockets {
// Autogenerated type: System.Net.Sockets.SocketAsyncEventArgs
class SocketAsyncEventArgs : public System::EventArgs {
public:
// System.Int32 in_progress
// Offset: 0x10
int in_progress;
// System.Net.EndPoint remote_ep
// Offset: 0x18
System::Net::EndPoint* remote_ep;
// System.Net.Sockets.Socket current_socket
// Offset: 0x20
System::Net::Sockets::Socket* current_socket;
// private System.Net.Sockets.Socket <AcceptSocket>k__BackingField
// Offset: 0x28
System::Net::Sockets::Socket* AcceptSocket;
// private System.Int32 <BytesTransferred>k__BackingField
// Offset: 0x30
int BytesTransferred;
// private System.Net.Sockets.SocketError <SocketError>k__BackingField
// Offset: 0x34
System::Net::Sockets::SocketError SocketError;
// private System.EventHandler`1<System.Net.Sockets.SocketAsyncEventArgs> Completed
// Offset: 0x38
System::EventHandler_1<System::Net::Sockets::SocketAsyncEventArgs*>* Completed;
// public System.Net.Sockets.Socket get_AcceptSocket()
// Offset: 0x11FFDE8
System::Net::Sockets::Socket* get_AcceptSocket();
// public System.Void set_AcceptSocket(System.Net.Sockets.Socket value)
// Offset: 0x11FFDF0
void set_AcceptSocket(System::Net::Sockets::Socket* value);
// System.Void set_BytesTransferred(System.Int32 value)
// Offset: 0x11FFDF8
void set_BytesTransferred(int value);
// public System.Void set_SocketError(System.Net.Sockets.SocketError value)
// Offset: 0x11FFE00
void set_SocketError(System::Net::Sockets::SocketError value);
// System.Void Complete()
// Offset: 0x11FDC58
void Complete();
// protected System.Void OnCompleted(System.Net.Sockets.SocketAsyncEventArgs e)
// Offset: 0x11FFE08
void OnCompleted(System::Net::Sockets::SocketAsyncEventArgs* e);
}; // System.Net.Sockets.SocketAsyncEventArgs
}
DEFINE_IL2CPP_ARG_TYPE(System::Net::Sockets::SocketAsyncEventArgs*, "System.Net.Sockets", "SocketAsyncEventArgs");
#pragma pack(pop)
| 38.518987 | 114 | 0.720013 | Futuremappermydud |
a145bcf8f9c9c066fe1e0a512544cfa3c3e50ea8 | 8,712 | inl | C++ | disc0ver-Engine/disc0ver-Engine/UGM/Interfaces/IMatrix/details/IMatrix.inl | Kpure1000/disc0ver-Engine | e2aeec3984aa6cd8ecbaa0da539bf53e37846602 | [
"MIT"
] | 5 | 2020-09-19T03:34:09.000Z | 2021-04-10T07:39:53.000Z | disc0ver-Engine/disc0ver-Engine/UGM/Interfaces/IMatrix/details/IMatrix.inl | wncka/disc0ver-Engine | 0817df4c9062cb3919164d01ff2b96a563f76437 | [
"MIT"
] | null | null | null | disc0ver-Engine/disc0ver-Engine/UGM/Interfaces/IMatrix/details/IMatrix.inl | wncka/disc0ver-Engine | 0817df4c9062cb3919164d01ff2b96a563f76437 | [
"MIT"
] | 3 | 2020-10-25T10:58:18.000Z | 2021-03-26T01:08:54.000Z | #pragma once
#include "svd3.h"
namespace Ubpa::details::IMatrix_ {
template<typename M, size_t N>
struct eye;
template<typename M>
struct eye<M, 2> {
using F = typename M::F;
inline static const M run() noexcept {
return {
1, 0,
0, 1,
};
}
};
template<typename M>
struct eye<M, 3> {
using F = typename M::F;
inline static const M run() noexcept {
return {
1, 0, 0,
0, 1, 0,
0, 0, 1,
};
}
};
template<typename M>
struct eye<M, 4> {
using F = typename M::F;
inline static const M run() noexcept {
return {
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
};
}
};
// =======================================================
template<size_t N>
struct det;
template<>
struct det<2> {
template<typename M>
inline static typename M::F run(const M& m) noexcept {
using F = typename M::F;
return m(0, 0) * m(1, 1) - m(0, 1) * m(1, 0);
}
};
template<>
struct det<3> {
template<typename M>
inline static typename M::F run(const M& m) noexcept {
using F = typename M::F;
return m[0][0] * (m[1][1] * m[2][2] - m[2][1] * m[1][2])
+ m[1][0] * (m[2][1] * m[0][2] - m[0][1] * m[2][2])
+ m[2][0] * (m[0][1] * m[1][2] - m[1][1] * m[0][2]);
}
};
template<>
struct det<4> {
template<typename M>
inline static typename M::F run(const M& m) noexcept {
using F = typename M::F;
F r00 = m[1][1] * m[2][2] * m[3][3] -
m[1][1] * m[2][3] * m[3][2] -
m[2][1] * m[1][2] * m[3][3] +
m[2][1] * m[1][3] * m[3][2] +
m[3][1] * m[1][2] * m[2][3] -
m[3][1] * m[1][3] * m[2][2];
F r10 = -m[1][0] * m[2][2] * m[3][3] +
m[1][0] * m[2][3] * m[3][2] +
m[2][0] * m[1][2] * m[3][3] -
m[2][0] * m[1][3] * m[3][2] -
m[3][0] * m[1][2] * m[2][3] +
m[3][0] * m[1][3] * m[2][2];
F r20 = m[1][0] * m[2][1] * m[3][3] -
m[1][0] * m[2][3] * m[3][1] -
m[2][0] * m[1][1] * m[3][3] +
m[2][0] * m[1][3] * m[3][1] +
m[3][0] * m[1][1] * m[2][3] -
m[3][0] * m[1][3] * m[2][1];
F r30 = -m[1][0] * m[2][1] * m[3][2] +
m[1][0] * m[2][2] * m[3][1] +
m[2][0] * m[1][1] * m[3][2] -
m[2][0] * m[1][2] * m[3][1] -
m[3][0] * m[1][1] * m[2][2] +
m[3][0] * m[1][2] * m[2][1];
F det = m[0][0] * r00 + m[0][1] * r10 + m[0][2] * r20 + m[0][3] * r30;
}
};
// =======================================================
template<size_t N>
struct transpose;
template<>
struct transpose<2> {
template<typename M>
inline static const M run(const M& m) noexcept {
static_assert(M::N == 2);
return {
m(0,0), m(1,0),
m(0,1), m(1,1),
};
}
};
template<>
struct transpose<3> {
template<typename M>
inline static const M run(const M& m) noexcept {
static_assert(M::N == 3);
return {
m(0,0), m(1,0), m(2,0),
m(0,1), m(1,1), m(2,1),
m(0,2), m(1,2), m(2,2),
};
}
};
template<>
struct transpose<4> {
template<typename M>
inline static const M run(const M& m) noexcept {
static_assert(M::N == 4);
#ifdef UBPA_USE_SIMD
if constexpr (ImplTraits_SupportSIMD<ImplTraits_T<M>>) {
M rst{ m };
_MM_TRANSPOSE4_PS(rst[0], rst[1], rst[2], rst[3]);
return rst;
}
else
#endif // UBPA_USE_SIMD
{
return {
m(0, 0), m(1, 0), m(2, 0), m(3, 0),
m(0, 1), m(1, 1), m(2, 1), m(3, 1),
m(0, 2), m(1, 2), m(2, 2), m(3, 2),
m(0, 3), m(1, 3), m(2, 3), m(3, 3),
};
}
}
};
// =======================================================
template<size_t N>
struct trace;
template<>
struct trace<2> {
template<typename M>
inline static ImplTraits_F<M> run(const M& m) noexcept {
static_assert(M::N == 2);
return m[0][0] + m[1][1];
}
};
template<>
struct trace<3> {
template<typename M>
inline static ImplTraits_F<M> run(const M& m) noexcept {
static_assert(M::N == 3);
return m[0][0] + m[1][1] + m[2][2];
}
};
template<>
struct trace<4> {
template<typename M>
inline static ImplTraits_F<M> run(const M& m) noexcept {
static_assert(M::N == 4);
#ifdef UBPA_USE_SIMD
if constexpr (ImplTraits_SupportSIMD<ImplTraits_T<M>>)
return m[0].get<0>() + m[1].get<1>() + m[2].get<2>() + m[3].get<3>();
else
#endif // UBPA_USE_SIMD
return m[0][0] + m[1][1] + m[2][2] + m[3][3];
}
};
// =======================================================
template<size_t N>
struct init;
template<>
struct init<2> {
template<typename M>
inline static void run(M& m, const std::array<ImplTraits_F<M>, 2 * 2>& data) noexcept {
static_assert(M::N == 2);
memcpy(&m, data.data(), 4 * sizeof(ImplTraits_F<M>));
}
};
template<>
struct init<3> {
template<typename M>
inline static void run(M& m, const std::array<ImplTraits_F<M>, 3 * 3>& data) noexcept {
static_assert(M::N == 3);
memcpy(&m, data.data(), 9 * sizeof(ImplTraits_F<M>));
}
};
template<>
struct init<4> {
template<typename M>
inline static void run(M& m, const std::array<ImplTraits_F<M>, 4 * 4>& data) noexcept {
static_assert(M::N == 4);
#ifdef UBPA_USE_SIMD
if constexpr (ImplTraits_SupportSIMD<ImplTraits_T<M>>) {
m[0] = _mm_loadu_ps(&(data[0]));
m[1] = _mm_loadu_ps(&(data[4]));
m[2] = _mm_loadu_ps(&(data[8]));
m[3] = _mm_loadu_ps(&(data[12]));
}
else
#endif // UBPA_USE_SIMD
{
memcpy(&m, data.data(), 16 * sizeof(ImplTraits_F<M>));
}
}
};
// =======================================================
template<size_t N>
struct zero;
template<>
struct zero<2> {
template<typename M>
inline static M run() noexcept {
static_assert(M::N == 2);
return {
0,0,
0,0,
};
}
};
template<>
struct zero<3> {
template<typename M>
inline static M run() noexcept {
static_assert(M::N == 3);
return {
0,0,0,
0,0,0,
0,0,0
};
}
};
template<>
struct zero<4> {
template<typename M>
inline static M run() noexcept {
static_assert(M::N == 4);
#ifdef UBPA_USE_SIMD
if constexpr (ImplTraits_SupportSIMD<ImplTraits_T<M>>) {
using V = ImplTraits_T<M>;
const __m128 z = _mm_set1_ps(0.f);
return { V{z}, V{z}, V{z}, V{z} };
}
else
#endif // UBPA_USE_SIMD
{
return {
0,0,0,0,
0,0,0,0,
0,0,0,0,
0,0,0,0
};
}
}
};
// =========================
template<size_t N>
struct SVD;
template<>
struct SVD<2> {
template<typename M>
inline static std::tuple<M, M, M> run(const M& m) noexcept {
static_assert(M::N == 2);
using F =ImplTraits_F<M>;
// ref : https://lucidar.me/en/mathematics/singular-value-decomposition-of-a-2x2-matrix/
F a = m(0, 0);
F b = m(0, 1);
F c = m(1, 0);
F d = m(1, 1);
F a2 = pow2(a);
F b2 = pow2(b);
F c2 = pow2(c);
F d2 = pow2(d);
F a2_p_b2 = a2 + b2;
F c2_p_d2 = c2 + d2;
F ac_p_bd = a * c + b * d;
F two_ac_p_bd = 2 * ac_p_bd;
F a2_p_b2_m_c2_m_d2 = a2_p_b2 - c2_p_d2;
F theta = static_cast<F>(0.5) * std::atan2(two_ac_p_bd , a2_p_b2_m_c2_m_d2);
F phi = static_cast<F>(0.5) * std::atan2(2 * (a * b + c * d), a2 - b2 + c2 - d2);
F cos_theta = std::cos(theta);
F sin_theta = std::sin(theta);
F cos_phi = std::cos(phi);
F sin_phi = std::sin(phi);
M U{
cos_theta, -sin_theta,
sin_theta, cos_theta,
};
F S1 = a2_p_b2 + c2_p_d2;
F S2 = std::sqrt(pow2(a2_p_b2_m_c2_m_d2) + pow2(two_ac_p_bd));
F sigma1 = std::sqrt(static_cast<F>(0.5) * (S1 + S2));
F sigma2 = std::sqrt(static_cast<F>(0.5) * (S1 - S2));
M Sigma{
sigma1, 0,
0, sigma2,
};
F s11 = (a * cos_theta + c * sin_theta) * cos_theta + ( b * cos_theta + d * sin_theta) * sin_phi;
F s22 = (a * sin_theta - c * cos_theta) * sin_phi + (-b * sin_theta + d * cos_theta) * cos_phi;
F sign_s11 = static_cast<F>(s11 > 0 ? 1 : (s11 < 0 ? -1 : 0));
F sign_s22 = static_cast<F>(s22 > 0 ? 1 : (s22 < 0 ? -1 : 0));
M V{
sign_s11 * cos_phi, -sign_s22 * sin_phi,
sign_s11 * sin_phi, sign_s22 * cos_phi,
};
return { U, Sigma, V };
}
};
template<>
struct SVD<3> {
template<typename M>
inline static std::tuple<M, M, M> run(const M& m) noexcept {
static_assert(M::N == 3 && std::is_same_v<ImplTraits_F<M>, float>);
// ref : https://github.com/ericjang/svd3
M U, S, V;
EricJang::svd(
// M
m(0, 0), m(0, 1), m(0, 2),
m(1, 0), m(1, 1), m(1, 2),
m(2, 0), m(2, 1), m(2, 2),
// U
U(0, 0), U(0, 1), U(0, 2),
U(1, 0), U(1, 1), U(1, 2),
U(2, 0), U(2, 1), U(2, 2),
// S
S(0, 0), S(0, 1), S(0, 2),
S(1, 0), S(1, 1), S(1, 2),
S(2, 0), S(2, 1), S(2, 2),
// V
V(0, 0), V(0, 1), V(0, 2),
V(1, 0), V(1, 1), V(1, 2),
V(2, 0), V(2, 1), V(2, 2)
);
return { U, S, V };
}
};
}
| 22.055696 | 100 | 0.495523 | Kpure1000 |
a148c20089188cca362add667fc9d30e7d19eb17 | 8,060 | cpp | C++ | src/talker.cpp | nakulpatel94/beginner_tutorials | bb2438721afa59f9715d563ec1438e56ce1672ed | [
"BSD-3-Clause"
] | 1 | 2020-03-11T04:20:41.000Z | 2020-03-11T04:20:41.000Z | src/talker.cpp | nakulpatel94/beginner_tutorials | bb2438721afa59f9715d563ec1438e56ce1672ed | [
"BSD-3-Clause"
] | null | null | null | src/talker.cpp | nakulpatel94/beginner_tutorials | bb2438721afa59f9715d563ec1438e56ce1672ed | [
"BSD-3-Clause"
] | 1 | 2020-03-27T12:59:48.000Z | 2020-03-27T12:59:48.000Z | /**
* BSD 3-Clause License
*
* Copyright (c) 2019, Nakul Patel
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*
*
* @file talker.cpp
*
* @author Nakul Patel
*
* @brief ROS publisher node
*
* @version 1
*
* @date 2019-11-10
*
* @section DESCRIPTION
*
* This is the .cpp file that implements a publisher(talker)
* node which publishes the message to the topic. Here, this node
* will send the custom message over the ROS system.
*
*/
#include <tf/transform_broadcaster.h>
#include <sstream>
#include <string>
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "beginner_tutorials/changeString.h"
/**
* To initialize the baseString appearing on console
*/
struct TopicMessage {
std::string baseString = "This is the basic tutorial for"
" implementing ROS services.";
} msgObj;
/**
* @brief modifies the base string
*
* @param &req- request object containing the input string from client
*
* @param &res- response object for the service
*
* @return bool- indicating success/failure of service call
*
* Service callback function that modifies the baseString variable
* with the inputString from Request object, and also
* set the response data with same inputString.
*/
bool modifyString(beginner_tutorials::changeString::Request &req,
beginner_tutorials::changeString::Response &res) {
if (req.inputString.size() > 0) {
msgObj.baseString = req.inputString;
/// Stuffing the response object data with incoming request data
res.outputString = req.inputString;
/// Log messages for various levels
ROS_INFO_STREAM("Service has been called.");
ROS_DEBUG_STREAM("Output string is:" << res.outputString);
return true;
} else {
ROS_FATAL_STREAM("You must enter non-empty string");
return false;
}
}
/**
* @brief main function for talker node
*
* @param argc-int count of arguments given through terminal
*
* @param argv-char** array of character pointers listing the arguments
*
* @return 0
*
* This function implements the publisher for publishing the message on topic
* alongwith added functionalities of changing the publishing rate of the messages.
* This can be done by passing the value for frequency from the roslaunch command.
*
*/
int main(int argc, char **argv) {
/**
* The ros::init() function needs to see argc and argv so that it can perform
* any ROS arguments and name remapping that were provided at the command line.
* The third argument to init() is the name of the node.
*
* You must call one of the versions of ros::init() before using any other
* part of the ROS system.
*
*/
ros::init(argc, argv, "talker");
/**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully initialize this node, and the last
* NodeHandle destructed will close down the node.
*/
ros::NodeHandle n;
/**
* The advertise() function is how you tell ROS that you want to
* publish on a given topic name. This invokes a call to the ROS
* master node, which keeps a registry of who is publishing and who
* is subscribing. After this advertise() call is made, the master
* node will notify anyone who is trying to subscribe to this topic name,
* and they will in turn negotiate a peer-to-peer connection with this
* node. advertise() returns a Publisher object which allows you to
* publish messages on that topic through a call to publish(). Once
* all copies of the returned Publisher object are destroyed, the topic
* will be automatically unadvertised.
*
* The second parameter to advertise() is the size of the message queue
* used for publishing messages. If messages are published more quickly
* than we can send them, the number here specifies how many messages to
* buffer up before throwing some away.
*/
ros::Publisher chatter_pub = n.advertise < std_msgs::String
> ("chatter", 1000);
/// Variable for setting the publishing frequency/rate
int freq = 10;
/// decision for argument passed from command line
if (argc == 2) {
int clp = atoi(argv[1]);
if (clp > 0) {
freq = clp;
ROS_INFO_STREAM("Input rate is now:" << freq);
} else {
ROS_ERROR_STREAM("Publishing rate is not valid, cannot be negative.");
}
} else {
ROS_DEBUG_STREAM("Default publishing rate of 10 Hz used.");
}
/**
* A ros::Rate object allows you to specify a
* frequency that you would like to loop at.
*/
ros::Rate loop_rate(freq);
/**
* A count of how many messages we have sent. This is used to create
* a unique string for each message.
*/
int count = 0;
/// Creating the service object
ros::ServiceServer service = n.advertiseService("modify_string",
modifyString);
/// creating object of tf::TransformBroadcaster
static tf::TransformBroadcaster br;
tf::Transform transform;
while (ros::ok()) {
/**
* This is a message object. You stuff it with data, and then publish it.
*/
std_msgs::String msg;
/**
* This is stringstream object to contain a sequence of characters.
* This sequence of characters can be accessed directly as a string object,
* using member str.
*/
std::stringstream ss;
ss << msgObj.baseString << count;
msg.data = ss.str();
/**
* Info level Log message that either contains the original baseString or
* the baseString after modification with service call.
*
*/
ROS_INFO_STREAM("Talker says:" << msg.data.c_str());
/**
* The publish() function is how you send messages. The parameter
* is the message object. The type of this object must agree with the type
* given as a template parameter to the advertise<>() call, as was done
* in the constructor above.
*/
chatter_pub.publish(msg);
/// Setting the origin for the tf frame
transform.setOrigin(tf::Vector3(10.0, 20.0, 0.0));
tf::Quaternion q;
/// Setting the rotation for tf frame, with Yaw angle
q.setRPY(0, 0, 30);
transform.setRotation(q);
/// broadcasting the transform object
br.sendTransform(
tf::StampedTransform(transform, ros::Time::now(), "world", "talk"));
ros::spinOnce();
/**
* using the ros::Rate object to sleep for the time remaining to let us
* hit our publish rate.
*/
loop_rate.sleep();
++count;
}
ROS_FATAL_STREAM("ROS node has been terminated.");
return 0;
}
| 32.764228 | 83 | 0.6933 | nakulpatel94 |
a14b4a918987ba9e75059262da500ada855d2b07 | 1,761 | cpp | C++ | src/goto-instrument/points_to.cpp | jimgrundy/cbmc | 8d314eb3448e63d9baf2430ba42326b67f830b92 | [
"BSD-4-Clause"
] | 412 | 2016-04-02T01:14:27.000Z | 2022-03-27T09:24:09.000Z | src/goto-instrument/points_to.cpp | jimgrundy/cbmc | 8d314eb3448e63d9baf2430ba42326b67f830b92 | [
"BSD-4-Clause"
] | 4,671 | 2016-02-25T13:52:16.000Z | 2022-03-31T22:14:46.000Z | src/goto-instrument/points_to.cpp | jimgrundy/cbmc | 8d314eb3448e63d9baf2430ba42326b67f830b92 | [
"BSD-4-Clause"
] | 266 | 2016-02-23T12:48:00.000Z | 2022-03-22T18:15:51.000Z | /*******************************************************************\
Module: Field-sensitive, location-insensitive points-to analysis
Author: Daniel Kroening, kroening@kroening.com
\*******************************************************************/
/// \file
/// Field-sensitive, location-insensitive points-to analysis
#include "points_to.h"
void points_tot::fixedpoint()
{
// this loop iterates until fixed-point
bool added;
do
{
added=false;
for(const auto &instruction_and_entry : cfg.entries())
{
if(transform(cfg[instruction_and_entry.second]))
added=true;
}
}
while(added);
}
void points_tot::output(std::ostream &out) const
{
for(value_mapt::const_iterator
v_it=value_map.begin();
v_it!=value_map.end();
v_it++)
{
out << v_it->first << ":";
for(object_id_sett::const_iterator
o_it=v_it->second.begin();
o_it!=v_it->second.end();
o_it++)
{
out << " " << *o_it;
}
out << '\n';
}
}
bool points_tot::transform(const cfgt::nodet &e)
{
bool result=false;
const goto_programt::instructiont &instruction=*(e.PC);
switch(instruction.type())
{
case SET_RETURN_VALUE:
// TODO
break;
case ASSIGN:
{
// const code_assignt &code_assign=to_code_assign(instruction.code);
}
break;
case FUNCTION_CALL:
// these are like assignments for the arguments
break;
case CATCH:
case THROW:
case GOTO:
case DEAD:
case DECL:
case ATOMIC_BEGIN:
case ATOMIC_END:
case START_THREAD:
case END_THREAD:
case END_FUNCTION:
case LOCATION:
case OTHER:
case SKIP:
case ASSERT:
case ASSUME:
case INCOMPLETE_GOTO:
case NO_INSTRUCTION_TYPE:
break;
}
return result;
}
| 18.154639 | 74 | 0.593413 | jimgrundy |
a14c297ee74d7319a4db1c40894baba8e3aaff4c | 1,993 | cpp | C++ | 2019/0526_ABC128/past/E2.cpp | kazunetakahashi/atcoder | 16ce65829ccc180260b19316e276c2fcf6606c53 | [
"MIT"
] | 7 | 2019-03-24T14:06:29.000Z | 2020-09-17T21:16:36.000Z | 2019/0526_ABC128/past/E2.cpp | kazunetakahashi/atcoder | 16ce65829ccc180260b19316e276c2fcf6606c53 | [
"MIT"
] | null | null | null | 2019/0526_ABC128/past/E2.cpp | kazunetakahashi/atcoder | 16ce65829ccc180260b19316e276c2fcf6606c53 | [
"MIT"
] | 1 | 2020-07-22T17:27:09.000Z | 2020-07-22T17:27:09.000Z | #define DEBUG 1
/**
* File : E2.cpp
* Author : Kazune Takahashi
* Created : 2019-5-27 00:40:23
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int N, Q;
typedef tuple<ll, int, ll> event; // 0: 壁が置かれる。 1: 壁が取り除かれる。 2: 半直線発射
vector<event> V;
multiset<ll> S; // 壁が置かれた座標。
int main()
{
cin >> N >> Q;
for (auto i = 0; i < N; i++)
{
ll s, t, x;
cin >> s >> t >> x;
V.push_back(event(s - x, 0, x));
V.push_back(event(t - x, 1, x));
}
for (auto i = 0; i < Q; i++)
{
ll d;
cin >> d;
V.push_back(event(d, 2, 0));
}
sort(V.begin(), V.end());
for (auto e : V)
{
ll time, dist;
int c;
tie(time, c, dist) = e;
#if DEBUG == 1
cerr << "time = " << time << ", c = " << c << ", dist = " << dist << endl;
#endif
if (c == 0)
{
S.insert(dist);
}
else if (c == 2)
{
if (S.empty())
{
cout << -1 << endl;
}
else
{
cout << *S.begin() << endl;
}
}
else
{
S.erase(S.find(dist));
}
}
} | 21.901099 | 103 | 0.547416 | kazunetakahashi |
a14ce3a80e369ca76162a8203fa21ce14a665607 | 781 | cpp | C++ | Data Structures/FenwickTree2D.cpp | azell003/Algorithms | 6dc755ca0a8b4cf2e0c2a7775b83168d38bcc13d | [
"MIT"
] | null | null | null | Data Structures/FenwickTree2D.cpp | azell003/Algorithms | 6dc755ca0a8b4cf2e0c2a7775b83168d38bcc13d | [
"MIT"
] | null | null | null | Data Structures/FenwickTree2D.cpp | azell003/Algorithms | 6dc755ca0a8b4cf2e0c2a7775b83168d38bcc13d | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
const int N = 105;
int max_x, max_y;
int tree[N][N];
void update(int x, int y, int val)
{
for(int i = x; i <= max_x; i += i & (-i))
for(int j = y; j <= max_y; j += j & (-j))
tree[i][j] += val;
}
int get(int x, int y)
{
int res = 0;
for(int i = x; i > 0; i -= i & (-i))
for(int j = y; j > 0; j -= j & (-j))
res += tree[i][j];
return res;
}
int rsq(int x1, int y1, int x2, int y2)
{
return get(x2, y2) - get(x2, y1 - 1) - get(x1 - 1, y2) + get(x1 - 1, y1 - 1);
}
int main()
{
max_x = max_y = 4;
update(1, 1, 1);
cout << rsq(1, 1, 4, 4) << endl;
update(3, 3, 12);
cout << rsq(3, 3, 3, 3) << endl;
cout << rsq(3, 3, 4, 4) << endl;
cout << rsq(1, 1, 3, 3) << endl;
return 0;
}
| 19.525 | 79 | 0.46863 | azell003 |
a14d70aa12f280e8796685cc84751893c5a6ad4c | 3,590 | cc | C++ | src/ppl/nn/engines/arm/kernels/onnx/pad_kernel.cc | mochiset/ppl.nn | 1fb35b80a0a5df1ada33bc950f44c6080733a2f3 | [
"Apache-2.0"
] | null | null | null | src/ppl/nn/engines/arm/kernels/onnx/pad_kernel.cc | mochiset/ppl.nn | 1fb35b80a0a5df1ada33bc950f44c6080733a2f3 | [
"Apache-2.0"
] | null | null | null | src/ppl/nn/engines/arm/kernels/onnx/pad_kernel.cc | mochiset/ppl.nn | 1fb35b80a0a5df1ada33bc950f44c6080733a2f3 | [
"Apache-2.0"
] | null | null | null | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "ppl/nn/engines/arm/kernels/onnx/pad_kernel.h"
#include "ppl/kernel/arm_server/pad/neon/pad.h"
#include "ppl/kernel/arm_server/common/memory.h"
namespace ppl { namespace nn { namespace arm {
ppl::common::RetCode PadKernel::DoExecute(KernelExecContext* ctx) {
PPLNN_ARM_REQUIRED_INPUT(x, 0);
PPLNN_ARM_REQUIRED_INPUT(pads, 1);
PPLNN_ARM_OPTIONAL_INPUT(constant, 2);
PPLNN_ARM_REQUIRED_OUTPUT(y, 0);
PPLNN_ARM_DEBUG_TRACE("Op: %s\n", GetName().c_str());
PPLNN_ARM_DEBUG_TRACE("Input [x]:\n");
PPL_ARM_TENSOR_PRINT_DEBUG_MSG(x);
PPLNN_ARM_DEBUG_TRACE("Output [y]:\n");
PPL_ARM_TENSOR_PRINT_DEBUG_MSG(y);
PPLNN_ARM_DEBUG_TRACE("pad mode: %d\n", param_->mode);
PPLNN_ARM_DEBUG_TRACE("isa: %u\n", GetISA());
const int dim_count = x->GetShape()->GetDimCount();
auto pads_data = pads->GetBufferPtr<int64_t>();
auto start_pads = pads_data;
auto end_pads = pads_data + dim_count;
if (x->GetShape()->GetElementsExcludingPadding() ==
y->GetShape()->GetElementsExcludingPadding()) { // no padding at all, just copy
if (x->GetEdge()->CalcConsumerCount() == 1 && x->GetType() == TENSORTYPE_NORMAL) {
y->TransferBufferFrom(x);
} else {
ppl::kernel::arm_server::memory_copy(x->GetBufferPtr(), x->GetShape()->GetBytesIncludingPadding(),
y->GetBufferPtr());
}
return ppl::common::RC_SUCCESS;
}
const void* constant_value = constant == nullptr ? nullptr : constant->GetBufferPtr<void>();
switch (param_->mode) {
case ppl::nn::onnx::PadParam::PAD_MODE_CONSTANT:
return ppl::kernel::arm_server::neon::pad_constant(x->GetShape(), y->GetShape(), x->GetBufferPtr<void>(),
start_pads, end_pads, constant_value,
y->GetBufferPtr<void>());
case ppl::nn::onnx::PadParam::PAD_MODE_REFLECT:
return ppl::kernel::arm_server::neon::pad_reflect(x->GetShape(), y->GetShape(), x->GetBufferPtr<void>(),
start_pads, end_pads, constant_value,
y->GetBufferPtr<void>());
case ppl::nn::onnx::PadParam::PAD_MODE_EDGE:
return ppl::kernel::arm_server::neon::pad_edge(x->GetShape(), y->GetShape(), x->GetBufferPtr<void>(),
start_pads, end_pads, constant_value,
y->GetBufferPtr<void>());
default:
break;
}
return ppl::common::RC_UNSUPPORTED;
}
}}} // namespace ppl::nn::arm
| 46.623377 | 117 | 0.611142 | mochiset |
a14df0c3926b603185c4f9b7821d359a2f47a712 | 1,657 | cc | C++ | src/reconstruction.cc | songyuncen/laser-triangulation | 228feda5497533ceac5e433e753f81ff1db38e20 | [
"MIT"
] | 7 | 2021-09-07T08:16:03.000Z | 2022-03-16T05:59:16.000Z | src/reconstruction.cc | songyuncen/laser-triangulation | 228feda5497533ceac5e433e753f81ff1db38e20 | [
"MIT"
] | null | null | null | src/reconstruction.cc | songyuncen/laser-triangulation | 228feda5497533ceac5e433e753f81ff1db38e20 | [
"MIT"
] | 2 | 2021-09-24T06:08:48.000Z | 2021-12-03T02:48:32.000Z | #include "laser_triangulation.h"
#include <sstream>
#include <opencv2/core/utils/filesystem.hpp>
namespace cvfs = cv::utils::fs;
static void ShowLinePoints(cv::Mat &image, std::vector<cv::Point> &pts, int wait);
void Reconstruction(const char *folder, const char *prefix, const char *suffix, int num_width, int n, int threshold,
cv::Mat &intrinsic, cv::Mat &distortion, cv::Vec4f &laser, cv::Vec3f &movement,
std::vector<cv::Point3f> &pts, bool show, int wait) {
pts.clear();
for (int i = 0; i < n; ++i) {
std::ostringstream num;
num << std::setw(num_width) << std::setfill('0') << i + 1;
cv::String file_name = cv::String(prefix) + num.str() + cv::String(suffix);
cv::Mat im = cv::imread(cvfs::join(folder, file_name), cv::IMREAD_GRAYSCALE);
std::vector<cv::Point> img_pts;
ExtractLaserLine(im, threshold, img_pts);
if (show) {
ShowLinePoints(im, img_pts, wait);
}
std::vector<cv::Point2f> src, dst;
cv::Mat(img_pts).copyTo(src);
cv::undistortPoints(src, dst, intrinsic, distortion);
for (size_t j = 0; j < dst.size(); ++j) {
double w = -laser[3] / (laser[0] * dst[j].x + laser[1] * dst[j].y + laser[2]);
cv::Vec3f p(w * dst[j].x, w * dst[j].y, w);
p -= (int)i * movement;
pts.push_back(cv::Point3f(p[0], p[1], p[2]));
}
}
}
void ShowLinePoints(cv::Mat &image, std::vector<cv::Point> &pts, int wait) {
cv::Mat frame;
cv::cvtColor(image, frame, cv::COLOR_GRAY2BGR);
for (size_t i = 0; i < pts.size(); ++i) {
cv::circle(frame, pts[i], 1, { 0, 0, 255 });
}
cv::imshow("Demo", frame);
cv::waitKey(wait);
}
| 33.14 | 116 | 0.598069 | songyuncen |
a15204369eebf187a85dec43420be0bb18ed0fb8 | 6,930 | cpp | C++ | test/src/scale/scale_collection_test.cpp | GeniusVentures/SuperGenius | ae43304f4a2475498ef56c971296175acb88d0ee | [
"MIT"
] | 1 | 2021-07-10T21:25:03.000Z | 2021-07-10T21:25:03.000Z | test/src/scale/scale_collection_test.cpp | GeniusVentures/SuperGenius | ae43304f4a2475498ef56c971296175acb88d0ee | [
"MIT"
] | null | null | null | test/src/scale/scale_collection_test.cpp | GeniusVentures/SuperGenius | ae43304f4a2475498ef56c971296175acb88d0ee | [
"MIT"
] | null | null | null |
#include <gtest/gtest.h>
#include "scale/scale.hpp"
#include "testutil/outcome.hpp"
using sgns::scale::ByteArray;
using sgns::scale::CompactInteger;
using sgns::scale::encode;
using sgns::scale::ScaleDecoderStream;
using sgns::scale::ScaleEncoderStream;
/**
* @given collection of 80 items of type uint8_t
* @when encodeCollection is applied
* @then expected result is obtained: header is 2 byte, items are 1 byte each
*/
TEST(Scale, encodeCollectionOf80) {
// 80 items of value 1
ByteArray collection(80, 1);
auto match = ByteArray{65, 1}; // header
match.insert(match.end(), collection.begin(), collection.end());
ScaleEncoderStream s;
ASSERT_NO_THROW((s << collection));
auto &&out = s.data();
ASSERT_EQ(out.size(), 82);
ASSERT_EQ(out, match);
}
/**
* @given collection of items of type uint16_t
* @when encodeCollection is applied
* @then expected result is obtained
*/
TEST(Scale, encodeCollectionUint16) {
std::vector<uint16_t> collection = {1, 2, 3, 4};
ScaleEncoderStream s;
ASSERT_NO_THROW((s << collection));
auto &&out = s.data();
// clang-format off
ASSERT_EQ(out,
(ByteArray{
16, // header
1, 0, // first item
2, 0, // second item
3, 0, // third item
4, 0 // fourth item
}));
// clang-format on
}
/**
* @given collection of items of type uint32_t
* @when encodeCollection is applied
* @then expected result is obtained
*/
TEST(Scale, encodeCollectionUint32) {
std::vector<uint32_t> collection = {50462976, 117835012, 185207048,
252579084};
ScaleEncoderStream s;
ASSERT_NO_THROW((s << collection));
auto &&out = s.data();
// clang-format off
ASSERT_EQ(out,
(ByteArray{
16, // header
0, 1, 2, 3, // first item
4, 5, 6, 7, // second item
8, 9, 0xA, 0xB, // third item
0xC, 0xD, 0xE, 0xF // fourth item
}));
// clang-format on
}
/**
* @given collection of items of type uint64_t
* @when encodeCollection is applied
* @then expected result is obtained
*/
TEST(Scale, encodeCollectionUint64) {
std::vector<uint64_t> collection = {506097522914230528ull,
1084818905618843912ull};
ScaleEncoderStream s;
ASSERT_NO_THROW((s << collection));
auto &&out = s.data();
// clang-format off
ASSERT_EQ(out,
(ByteArray{
8, // header
0, 1, 2, 3, // first item
4, 5, 6, 7, // second item
8, 9, 0xA, 0xB, // third item
0xC, 0xD, 0xE, 0xF // fourth item
}));
// clang-format on
}
/**
* @given collection of items of type uint16_t containing 2^14 items
* where collection[i] == i % 256
* @when encodeCollection is applied
* @then obtain byte array of length 32772 bytes
* where each second byte == 0 and collection[(i-4)/2] == (i/2) % 256
*/
TEST(Scale, encodeLongCollectionUint16) {
std::vector<uint16_t> collection;
auto length = 16384;
collection.reserve(length);
for (auto i = 0; i < length; ++i) {
collection.push_back(i % 256);
}
ScaleEncoderStream s;
ASSERT_NO_THROW((s << collection));
auto &&out = s.data();
ASSERT_EQ(out.size(), (length * 2 + 4));
// header takes 4 byte,
// first 4 bytes represent le-encoded value 2^16 + 2
// which is compact-encoded value 2^14 = 16384
auto stream = ScaleDecoderStream(gsl::make_span(out));
CompactInteger res{};
ASSERT_NO_THROW(stream >> res);
ASSERT_EQ(res, 16384);
// now only 32768 bytes left in stream
ASSERT_EQ(stream.hasMore(32768), true);
ASSERT_EQ(stream.hasMore(32769), false);
for (auto i = 0; i < length; ++i) {
uint8_t byte = 0u;
ASSERT_NO_THROW(stream >> byte);
ASSERT_EQ(byte, i % 256);
ASSERT_NO_THROW(stream >> byte);
ASSERT_EQ(byte, 0);
}
ASSERT_EQ(stream.hasMore(1), false);
}
/**
* @given very long collection of items of type uint8_t containing 2^20 items
* this number takes ~ 1 Mb of data
* where collection[i] == i % 256
* @when encodeCollection is applied
* @then obtain byte array of length 1048576 + 4 bytes (header) bytes
* where first bytes repreent header, other are data itself
* where each byte after header == i%256
*/
TEST(Scale, encodeVeryLongCollectionUint8) {
auto length = 1048576; // 2^20
std::vector<uint8_t> collection;
collection.reserve(length);
for (auto i = 0; i < length; ++i) {
collection.push_back(i % 256);
}
ScaleEncoderStream s;
ASSERT_NO_THROW((s << collection));
auto &&out = s.data();
ASSERT_EQ(out.size(), (length + 4));
// header takes 4 bytes,
// first byte == (4-4) + 3 = 3,
// which means that number of items requires 4 bytes
// 3 next bytes are 0, and the last 4-th == 2^6 == 64
// which is compact-encoded value 2^14 = 16384
auto stream = ScaleDecoderStream(gsl::make_span(out));
CompactInteger bi{};
ASSERT_NO_THROW(stream >> bi);
ASSERT_EQ(bi, 1048576);
// now only 1048576 bytes left in stream
ASSERT_EQ(stream.hasMore(1048576), true);
ASSERT_EQ(stream.hasMore(1048576 + 1), false);
for (auto i = 0; i < length; ++i) {
uint8_t byte{0u};
ASSERT_NO_THROW((stream >> byte));
ASSERT_EQ(byte, i % 256);
}
ASSERT_EQ(stream.hasMore(1), false);
}
// following test takes too much time, don't run it
/**
* @given very long collection of items of type uint8_t containing 2^30 ==
* 1073741824 items this number takes ~ 1 Gb of data where collection[i] == i %
* 256
* @when encodeCollection is applied
* @then obtain byte array of length 1073741824 + 5 bytes (header) bytes
* where first bytes represent header, other are data itself
* where each byte after header == i%256
*/
TEST(Scale, DISABLED_encodeVeryLongCollectionUint8) {
auto length = 1073741824; // 2^20
std::vector<uint8_t> collection;
collection.reserve(length);
for (auto i = 0; i < length; ++i) {
collection.push_back(i % 256);
}
ScaleEncoderStream s;
ASSERT_NO_THROW((s << collection));
auto &&out = s.data();
ASSERT_EQ(out.size(), (length + 4));
// header takes 4 bytes,
// first byte == (4-4) + 3 = 3, which means that number of items
// requires 4 bytes
// 3 next bytes are 0, and the last 4-th == 2^6 == 64
// which is compact-encoded value 2^14 = 16384
auto stream = ScaleDecoderStream(gsl::make_span(out));
CompactInteger bi{};
ASSERT_NO_THROW(stream >> bi);
ASSERT_EQ(bi, length);
// now only 1048576 bytes left in stream
ASSERT_EQ(stream.hasMore(length), true);
ASSERT_EQ(stream.hasMore(length + 1), false);
for (auto i = 0; i < length; ++i) {
uint8_t byte = 0u;
ASSERT_NO_THROW(stream >> byte);
ASSERT_EQ(byte, i % 256);
}
ASSERT_EQ(stream.hasMore(1), false);
}
| 29.742489 | 80 | 0.625108 | GeniusVentures |
a1553ba2dd3432130ee1250bcc9a2398efdca9aa | 11,603 | cpp | C++ | Systems/WindowsShell/WindowsShell.cpp | RachelWilSingh/ZeroCore | e9a2f82d395e5c89fb98eceac44ce60d016dbff3 | [
"MIT"
] | 52 | 2018-09-11T17:18:35.000Z | 2022-03-13T15:28:21.000Z | Systems/WindowsShell/WindowsShell.cpp | RachelWilSingh/ZeroCore | e9a2f82d395e5c89fb98eceac44ce60d016dbff3 | [
"MIT"
] | 1,409 | 2018-09-19T18:03:43.000Z | 2021-06-09T08:33:33.000Z | Systems/WindowsShell/WindowsShell.cpp | RachelWilSingh/ZeroCore | e9a2f82d395e5c89fb98eceac44ce60d016dbff3 | [
"MIT"
] | 26 | 2018-09-11T17:16:32.000Z | 2021-11-22T06:21:19.000Z | ///////////////////////////////////////////////////////////////////////////////
///
/// Authors: Chris Peters
/// Copyright 2010-2012, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#include "Precompiled.hpp"
namespace Zero
{
//------------------------------------------------------------------ File Dialog
// Documentation says the character limit is 32k limit for ANSI
// http://msdn.microsoft.com/en-us/library/ms646927(v=vs.85).aspx
// only using a fourth of the limit
const int cFileBufferSize = 8192;
void FileDialog(OsHandle windowHandle, FileDialogConfig& config, bool opening)
{
//Create Windows OPENFILENAME structure and zero it
OPENFILENAME fileDialog = {0};
fileDialog.lStructSize = sizeof (OPENFILENAME);
fileDialog.hwndOwner = (HWND)windowHandle;
//Set up buffers.
wchar_t fileName[cFileBufferSize] = {0};
fileDialog.lpstrFile = fileName;
fileDialog.nMaxFile = cFileBufferSize;
wchar_t fileFilter[cFileBufferSize] = {0};
fileDialog.lpstrFilter = fileFilter;
wchar_t* fileFilterPosition = fileFilter;
forRange(FileDialogFilter& fileFilter, config.mSearchFilters.All())
{
WString description = Widen(fileFilter.mDescription);
WString filter = Widen(fileFilter.mFilter);
ZeroStrCpyW(fileFilterPosition, description.Size(), description.c_str());
fileFilterPosition += description.Size();
ZeroStrCpyW(fileFilterPosition, filter.Size(), filter.c_str());
fileFilterPosition += filter.Size();
}
// File filters are double null terminated, so add one more at the end
WString nullChar = Widen("\0");
ZeroStrCpyW(fileFilterPosition, 1, nullChar.c_str());
//Set the default file name
WString defaultFileName = Widen(config.DefaultFileName);
ZeroStrCpyW(fileName, cFileBufferSize, defaultFileName.c_str());
//Object containing the data is needed to properly keep it alive while the dialog is open
WString title = Widen(config.Title);
WString startingDirectory = Widen(config.StartingDirectory);
fileDialog.lpstrFileTitle = NULL;
fileDialog.lpstrInitialDir = startingDirectory.c_str();
fileDialog.lpstrTitle = title.c_str();
//Extensions is ".ext" so skip one character
if (!config.mDefaultSaveExtension.Empty())
{
WString defaultExtension = Widen(config.mDefaultSaveExtension);
fileDialog.lpstrDefExt = defaultExtension.c_str();
}
//Use explorer interface
fileDialog.Flags |= OFN_EXPLORER;
if(config.Flags & FileDialogFlags::Folder)
{
ZeroStrCpyW(fileName, cFileBufferSize, L"Folder");
}
if(config.Flags & FileDialogFlags::MultiSelect)
fileDialog.Flags |= OFN_ALLOWMULTISELECT;
BOOL success = 0;
if(opening)
success = GetOpenFileName(&fileDialog);
else
success = GetSaveFileName(&fileDialog);
OsFileSelection fileEvent;
fileEvent.EventName = config.EventName;
fileEvent.Success = success!=0;
if(success)
{
//If nFileExtension is zero, there is multiple files
//from a multiselect
if(fileDialog.nFileExtension == 0 &&
config.Flags & FileDialogFlags::MultiSelect)
{
//lpstrFile will be a multi null terminated string
//beginning with the directory name then a list of
//files and finally a null terminator. (so two at the end)
wchar_t* current = fileDialog.lpstrFile;
String directoryName;
//Check for null termination
//or double null termination which signals the
//end of the file list
while(*current != '\0')
{
cwstr currentFile = current;
//On the first loop this sets the directory name
if(directoryName.Empty())
directoryName = Narrow(currentFile);
else
{
//Append a full file path Append the file name to the path
fileEvent.Files.PushBack(FilePath::Combine(directoryName, Narrow(currentFile)));
}
//Find null terminator
while(*current != '\0')
++current;
//Skip the terminator
++current;
}
}
else
{
fileEvent.Files.PushBack(Narrow(fileDialog.lpstrFile).c_str());
}
}
//We assume that the first item is the path if we were multi selecting, but if the user
//types in a random string then we can get something that looks like a path (no extension)
//and then get no files. So if we didn't get any files for some reason then mark that we actually failed.
if(fileEvent.Files.Size() == 0)
{
fileEvent.Success = false;
}
if(config.CallbackObject)
{
EventDispatcher* dispatcher = config.CallbackObject->GetDispatcherObject();
dispatcher->Dispatch(config.EventName, &fileEvent);
}
}
//-------------------------------------------------------------------- Clipboard
String ShellGetClipboardText(OsHandle windowHandle)
{
if(!IsClipboardFormatAvailable(CF_UNICODETEXT))
return String();
if(!OpenClipboard((HWND)windowHandle))
return String();
LPWSTR clipboardCstr = NULL;
//Get OS global handle
HGLOBAL globalHandle = GetClipboardData(CF_UNICODETEXT);
if(globalHandle != NULL)
{
clipboardCstr = (LPWSTR)GlobalLock(globalHandle);
if(clipboardCstr != NULL)
{
GlobalUnlock(globalHandle);
}
}
CloseClipboard();
return Narrow(clipboardCstr);
}
void ShellSetClipboardText(OsHandle windowHandle, StringRange text)
{
WString wideText = Widen(text);
if(!OpenClipboard((HWND)windowHandle))
return;
EmptyClipboard();
uint numCharacters = wideText.SizeInBytes();
// Allocate a global memory object for the text.
HGLOBAL hglbCopy = GlobalAlloc(GMEM_MOVEABLE, (numCharacters + 1) * sizeof(wchar_t));
if(hglbCopy == NULL)
{
CloseClipboard();
return;
}
// Lock the handle and copy the text to the buffer.
wchar_t* data = (wchar_t*)GlobalLock(hglbCopy);
memcpy(data, wideText.Data(), wideText.SizeInBytes());
//Null terminate the buffer
data[numCharacters] = (wchar_t)0;
GlobalUnlock(hglbCopy);
// Place the handle on the clipboard.
SetClipboardData(CF_UNICODETEXT, hglbCopy);
CloseClipboard();
}
// Convert bitmap to image. Hdc is hdc bitmap was created in
void ConvertImage(HDC hdc, HBITMAP bitmapHandle, Image* image)
{
BITMAP bmpScreen;
GetObject(bitmapHandle, sizeof(BITMAP), &bmpScreen);
BITMAPINFOHEADER bi;
bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biWidth = bmpScreen.bmWidth;
bi.biHeight = bmpScreen.bmHeight;
bi.biPlanes = 1;
bi.biBitCount = 32;
bi.biCompression = BI_RGB;
bi.biSizeImage = 0;
bi.biXPelsPerMeter = 0;
bi.biYPelsPerMeter = 0;
bi.biClrUsed = 0;
bi.biClrImportant = 0;
// Row size is padded to 32 bits
DWORD dwBmpSize = ((bmpScreen.bmWidth * bi.biBitCount + 31) / 32) * 4 * bmpScreen.bmHeight;
byte* rawBitmapData = (byte*)zAllocate(dwBmpSize) ;
// Gets the "bits" from the bitmap and copies them into a buffer
// which is pointed to by lpbitmap.
GetDIBits(hdc, bitmapHandle, 0,
(UINT)bmpScreen.bmHeight, rawBitmapData,
(BITMAPINFO *)&bi, DIB_RGB_COLORS);
// Allocate the image and copy over pixels
image->Allocate(bmpScreen.bmWidth, bmpScreen.bmHeight);
for(int y=0;y<bmpScreen.bmHeight;++y)
{
for(int x=0;x<bmpScreen.bmWidth;++x)
{
byte* data = rawBitmapData + bmpScreen.bmWidth * 4 * (bmpScreen.bmHeight-y-1) + x * 4;
image->GetPixel(x, y) = ByteColorRGBA(data[2], data[1], data[0], 255);
}
}
}
bool ShellIsClipboardImageAvailable(OsHandle windowHandle)
{
if(!OpenClipboard((HWND)windowHandle))
return false;
bool result = (IsClipboardFormatAvailable(CF_BITMAP) != 0);
CloseClipboard();
return result;
}
bool ShellGetClipboardImage(OsHandle windowHandle, Image* image)
{
if(!OpenClipboard((HWND)windowHandle))
return false;
if(!IsClipboardFormatAvailable(CF_BITMAP))
{
CloseClipboard();
return false;
}
HBITMAP hbmScreen = (HBITMAP)GetClipboardData(CF_BITMAP);
HDC hdcScreen = GetDC(NULL);
ConvertImage(hdcScreen, hbmScreen, image);
CloseClipboard();
return true;
}
bool ShellGetDesktopImage(Image* image)
{
return ShellGetWindowImage(GetDesktopWindow(), image);
}
bool ShellGetWindowImage(OsHandle windowHandle, Image* image)
{
RECT windowRect;
GetWindowRect((HWND)windowHandle, &windowRect);
int width = windowRect.right - windowRect.left;
int height = windowRect.bottom - windowRect.top;
HDC hdcScreen = GetDC(NULL);
HDC hdcDest = CreateCompatibleDC(hdcScreen);
HBITMAP hBitmap = CreateCompatibleBitmap(hdcScreen, width, height);
// Select the compatible bitmap into the compatible memory DC.
HGDIOBJ old = SelectObject(hdcDest, hBitmap);
// Bit block transfer into our compatible memory DC.
if(!BitBlt(hdcDest,
0,
0,
width,
height,
hdcScreen,
windowRect.left, windowRect.top,
SRCCOPY))
{
return false;
}
SelectObject(hdcDest, old);
ConvertImage(hdcScreen, hBitmap, image);
DeleteDC(hdcDest);
ReleaseDC((HWND)windowHandle, hdcScreen);
DeleteObject(hBitmap);
return true;
}
DeclareEnum4(ReturnCode, Continue, DebugBreak, Terminate, Ignore);
bool WindowsErrorProcessHandler(ErrorSignaler::ErrorData& errorData)
{
char commandLine[4096];
char* message = (char*)errorData.Message;
//No message provided
if(message==NULL)
message = "No message";
ZPrint("%s\n", message);
uint msgLength = strlen(message);
//Remove quotes from message
for(uint i = 0; i < msgLength; ++i)
{
if(message[i] == '"')
message[i] = '\'';
}
ZeroSPrintf(commandLine, "ErrorDialog.exe \"%s\" \"%s\" \"%s:%d\" %s",
message, errorData.Expression, errorData.File, errorData.Line,
"Default");
STARTUPINFO startUpInfo;
memset(&startUpInfo, 0, sizeof(startUpInfo));
PROCESS_INFORMATION processInfo;
memset(&processInfo, 0, sizeof(processInfo));
// Start the child process.
CreateProcess(NULL, // No module name (use command line)
(LPTSTR)Widen(commandLine).c_str(), // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
CREATE_NO_WINDOW, // Creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&startUpInfo, // Pointer to STARTUPINFO structure
&processInfo);
DWORD exitCode = 0;
WaitForSingleObject(processInfo.hProcess, INFINITE);
BOOL success = GetExitCodeProcess(processInfo.hProcess, &exitCode);
//Failed debug break
if(!success)
return true;
ReturnCode::Enum returnCode = (ReturnCode::Enum)exitCode;
//Exit code 3 is ignore
switch (returnCode)
{
case ReturnCode::Continue:
return false;
case ReturnCode::DebugBreak:
return true;
case ReturnCode::Terminate:
TerminateProcess(GetCurrentProcess(), 0);
return false;
case ReturnCode::Ignore:
errorData.IgnoreFutureAssert = true;
return false;
}
//Debug break if invalid code
return true;
}
}//namespace Zero
| 29.524173 | 108 | 0.646729 | RachelWilSingh |
a158dec2dbd6ec817182f26729f8b453b3844b13 | 5,511 | cpp | C++ | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcFailureConnectionCondition.cpp | promethe42/ifcplusplus | 1c8b51b1f870f0107538dbea5eaa2755c81f5dca | [
"MIT"
] | null | null | null | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcFailureConnectionCondition.cpp | promethe42/ifcplusplus | 1c8b51b1f870f0107538dbea5eaa2755c81f5dca | [
"MIT"
] | null | null | null | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcFailureConnectionCondition.cpp | promethe42/ifcplusplus | 1c8b51b1f870f0107538dbea5eaa2755c81f5dca | [
"MIT"
] | null | null | null | /* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>
#include "ifcpp/model/AttributeObject.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/model/BuildingGuid.h"
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/IFC4/include/IfcFailureConnectionCondition.h"
#include "ifcpp/IFC4/include/IfcForceMeasure.h"
#include "ifcpp/IFC4/include/IfcLabel.h"
// ENTITY IfcFailureConnectionCondition
IfcFailureConnectionCondition::IfcFailureConnectionCondition() {}
IfcFailureConnectionCondition::IfcFailureConnectionCondition( int id ) { m_entity_id = id; }
IfcFailureConnectionCondition::~IfcFailureConnectionCondition() {}
shared_ptr<BuildingObject> IfcFailureConnectionCondition::getDeepCopy( BuildingCopyOptions& options )
{
shared_ptr<IfcFailureConnectionCondition> copy_self( new IfcFailureConnectionCondition() );
if( m_Name ) { copy_self->m_Name = dynamic_pointer_cast<IfcLabel>( m_Name->getDeepCopy(options) ); }
if( m_TensionFailureX ) { copy_self->m_TensionFailureX = dynamic_pointer_cast<IfcForceMeasure>( m_TensionFailureX->getDeepCopy(options) ); }
if( m_TensionFailureY ) { copy_self->m_TensionFailureY = dynamic_pointer_cast<IfcForceMeasure>( m_TensionFailureY->getDeepCopy(options) ); }
if( m_TensionFailureZ ) { copy_self->m_TensionFailureZ = dynamic_pointer_cast<IfcForceMeasure>( m_TensionFailureZ->getDeepCopy(options) ); }
if( m_CompressionFailureX ) { copy_self->m_CompressionFailureX = dynamic_pointer_cast<IfcForceMeasure>( m_CompressionFailureX->getDeepCopy(options) ); }
if( m_CompressionFailureY ) { copy_self->m_CompressionFailureY = dynamic_pointer_cast<IfcForceMeasure>( m_CompressionFailureY->getDeepCopy(options) ); }
if( m_CompressionFailureZ ) { copy_self->m_CompressionFailureZ = dynamic_pointer_cast<IfcForceMeasure>( m_CompressionFailureZ->getDeepCopy(options) ); }
return copy_self;
}
void IfcFailureConnectionCondition::getStepLine( std::stringstream& stream ) const
{
stream << "#" << m_entity_id << "= IFCFAILURECONNECTIONCONDITION" << "(";
if( m_Name ) { m_Name->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_TensionFailureX ) { m_TensionFailureX->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_TensionFailureY ) { m_TensionFailureY->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_TensionFailureZ ) { m_TensionFailureZ->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_CompressionFailureX ) { m_CompressionFailureX->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_CompressionFailureY ) { m_CompressionFailureY->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_CompressionFailureZ ) { m_CompressionFailureZ->getStepParameter( stream ); } else { stream << "$"; }
stream << ");";
}
void IfcFailureConnectionCondition::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_entity_id; }
const std::wstring IfcFailureConnectionCondition::toString() const { return L"IfcFailureConnectionCondition"; }
void IfcFailureConnectionCondition::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map )
{
const size_t num_args = args.size();
if( num_args != 7 ){ std::stringstream err; err << "Wrong parameter count for entity IfcFailureConnectionCondition, expecting 7, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); }
m_Name = IfcLabel::createObjectFromSTEP( args[0], map );
m_TensionFailureX = IfcForceMeasure::createObjectFromSTEP( args[1], map );
m_TensionFailureY = IfcForceMeasure::createObjectFromSTEP( args[2], map );
m_TensionFailureZ = IfcForceMeasure::createObjectFromSTEP( args[3], map );
m_CompressionFailureX = IfcForceMeasure::createObjectFromSTEP( args[4], map );
m_CompressionFailureY = IfcForceMeasure::createObjectFromSTEP( args[5], map );
m_CompressionFailureZ = IfcForceMeasure::createObjectFromSTEP( args[6], map );
}
void IfcFailureConnectionCondition::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const
{
IfcStructuralConnectionCondition::getAttributes( vec_attributes );
vec_attributes.push_back( std::make_pair( "TensionFailureX", m_TensionFailureX ) );
vec_attributes.push_back( std::make_pair( "TensionFailureY", m_TensionFailureY ) );
vec_attributes.push_back( std::make_pair( "TensionFailureZ", m_TensionFailureZ ) );
vec_attributes.push_back( std::make_pair( "CompressionFailureX", m_CompressionFailureX ) );
vec_attributes.push_back( std::make_pair( "CompressionFailureY", m_CompressionFailureY ) );
vec_attributes.push_back( std::make_pair( "CompressionFailureZ", m_CompressionFailureZ ) );
}
void IfcFailureConnectionCondition::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) const
{
IfcStructuralConnectionCondition::getAttributesInverse( vec_attributes_inverse );
}
void IfcFailureConnectionCondition::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity )
{
IfcStructuralConnectionCondition::setInverseCounterparts( ptr_self_entity );
}
void IfcFailureConnectionCondition::unlinkFromInverseCounterparts()
{
IfcStructuralConnectionCondition::unlinkFromInverseCounterparts();
}
| 65.607143 | 247 | 0.765378 | promethe42 |
a1592fb9dc0abd55ed74255f2655888befe5bdc3 | 1,584 | cpp | C++ | leetcode/Combinations/main.cpp | yylzl/CodingMyWorld | a255e5c1fe3c2c5f0ffce17539b5b5b667511448 | [
"Apache-2.0"
] | null | null | null | leetcode/Combinations/main.cpp | yylzl/CodingMyWorld | a255e5c1fe3c2c5f0ffce17539b5b5b667511448 | [
"Apache-2.0"
] | null | null | null | leetcode/Combinations/main.cpp | yylzl/CodingMyWorld | a255e5c1fe3c2c5f0ffce17539b5b5b667511448 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <cstdint>
#include <climits>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
void combine_backtrace(vector<vector<int> > &res, vector<int> &one, int start, int n, int k)
{
if(k==0)
{
res.push_back(one);
return;
}
for(int i=start;i<=n;++i)
{
one.push_back(i);
combine_backtrace(res, one, i+1, n, k-1);
one.pop_back();
}
}
vector<vector<int> > combine(int n, int k) {
vector<vector<int> > res;
vector<int> one;
combine_backtrace(res, one, 1, n, k);
return res;
}
//avoid push pop op
vector<vector<int> > combine2(int n, int k) {
v.resize(k);
dfs(1, n, k);
return r;
}
private:
vector<vector<int> > r;
vector<int> v;
void dfs(int i, int n, int k) {
while (i <= n) {
v[v.size() - k] = i++;
if (k > 1)
dfs(i, n, k - 1);
else
r.push_back(v);
}
}
};
int main(int argc, char *argv[])
{
Solution *S = new Solution();
vector<vector<int> > v;
v = S->combine(5, 2);
for(int i=0;i<v.size();++i)
{
cout<<"[";
for(int j=0;j<v[i].size();++j)
{
cout<<v[i][j]<<",";
}
cout<<"]"<<endl;
}
return 0;
}
| 22 | 100 | 0.406566 | yylzl |
a15944d86b0d0a5b2717558d71260ed86ebaf66f | 4,073 | cpp | C++ | src/distributenrldata.cpp | bstaber/Trilinos | 12ada5a678338a1da962113a4fad708f93b19e03 | [
"MIT"
] | null | null | null | src/distributenrldata.cpp | bstaber/Trilinos | 12ada5a678338a1da962113a4fad708f93b19e03 | [
"MIT"
] | null | null | null | src/distributenrldata.cpp | bstaber/Trilinos | 12ada5a678338a1da962113a4fad708f93b19e03 | [
"MIT"
] | null | null | null | /*
Brian Staber (brian.staber@gmail.com)
*/
#include "distributenrldata.hpp"
#include <math.h>
distributenrldata::distributenrldata(mesh & Mesh, std::string & path){
retrieve_data(Mesh,path);
}
distributenrldata::~distributenrldata(){
}
void distributenrldata::retrieve_data(mesh & Mesh, std::string & path){
double testx, testy, testz, xi, eta, residual;
unsigned int n_local_faces = Mesh.n_local_faces;
int nvert = Mesh.face_type;
int node, result, e_gid;
Epetra_SerialDenseVector x(nvert), y(nvert), z(nvert);
std::vector<double> data_xyz;
std::vector<double> data_exx, data_eyy, data_exy;
Teuchos::RCP<readnrldata> nrldata = Teuchos::rcp(new readnrldata(true,path));
npoints = nrldata->npoints;
nloads = nrldata->nloads;
boundaryconditions = nrldata->boundaryconditions;
//energy = nrldata->energy;
angles = nrldata->angles;
for (unsigned int p=0; p<npoints; ++p){
testx = nrldata->points(p,0);
testy = nrldata->points(p,1);
testz = nrldata->points(p,2);
for (unsigned int e_lid=0; e_lid<n_local_faces; ++e_lid){
e_gid = Mesh.local_faces[e_lid];
if (Mesh.faces_phases[e_gid]==92 || Mesh.faces_phases[e_gid]==93){
result = -1;
for (unsigned int inode=0; inode<nvert; ++inode){
node = Mesh.faces_nodes[nvert*e_gid+inode];
x(inode) = Mesh.nodes_coord[3*node+0];
y(inode) = Mesh.nodes_coord[3*node+1];
z(inode) = Mesh.nodes_coord[3*node+2];
}
if (z(0)==testz && testx>=0.0 && testx<=50.0 && testy>=0.0 && testy<=25.0){
result = pnpoly(nvert,x,y,testx,testy);
}
if (result==1){
local_id_faces.push_back(e_lid);
global_id_faces.push_back(p);
residual = inverse_isoparametric_mapping(testx,testy,x,y,xi,eta);
local_xi.push_back(xi);
local_eta.push_back(eta);
}
}
}
}
}
double distributenrldata::inverse_isoparametric_mapping(double & testx, double & testy, Epetra_SerialDenseVector & x, Epetra_SerialDenseVector & y, double & xi, double & eta){
Epetra_SerialDenseSolver solver;
double rhs_inf = 1.0;
int nvert = x.Length();;
int iter = 0;
Epetra_SerialDenseVector f(2);
Epetra_SerialDenseVector dxi(2);
Epetra_SerialDenseVector N(nvert);
Epetra_SerialDenseMatrix D(nvert,2);
Epetra_SerialDenseMatrix A(2,2);
Epetra_SerialDenseMatrix mat_x(2,nvert);
for (unsigned int i=0; i<nvert; ++i){
mat_x(0,i) = x(i);
mat_x(1,i) = y(i);
}
xi = 0.0; eta = 0.0;
while (rhs_inf>1e-10){
switch (nvert){
case 3:
tri3::shape_functions(N,xi,eta);
tri3::d_shape_functions(D,xi,eta);
break;
case 4:
quad4::shape_functions(N,xi,eta);
quad4::d_shape_functions(D,xi,eta);
break;
case 6:
tri6::shape_functions(N,xi,eta);
tri6::d_shape_functions(D,xi,eta);
break;
}
f(0) = testx;
f(1) = testy;
f.Multiply('N','N',-1.0,mat_x,N,1.0);
iter++;
if (iter>1){
rhs_inf = f.NormInf();
if (rhs_inf>1e8){
std::cout << "Inverse Isoparametric Mapping: Newton-Raphson failed to converge.\n";
break;
}
}
if (iter>1000){
std::cout << "Inverse Isoparametric Mapping: Iteration number exceeds 1000.\n";
break;
}
A.Multiply('N','N',1.0,mat_x,D,0.0);
solver.SetMatrix(A);
solver.SetVectors(dxi,f);
int error = solver.Solve();
if (error){
std::cout << "Inverse Isoparametric Mapping: Error with Epetra_SerialDenseSolver.\n";
}
xi += dxi(0);
eta += dxi(1);
}
return rhs_inf;
}
| 31.330769 | 175 | 0.555119 | bstaber |
a159ba1c849923a3709d0940061a8239ecb4701f | 277 | hpp | C++ | packets/PKT_S2C_FadeMinions.hpp | HoDANG/OGLeague2 | 21efea8ea480972a6d686c4adefea03d57da5e9d | [
"MIT"
] | 1 | 2022-03-27T10:21:41.000Z | 2022-03-27T10:21:41.000Z | packets/PKT_S2C_FadeMinions.hpp | HoDANG/OGLeague2 | 21efea8ea480972a6d686c4adefea03d57da5e9d | [
"MIT"
] | null | null | null | packets/PKT_S2C_FadeMinions.hpp | HoDANG/OGLeague2 | 21efea8ea480972a6d686c4adefea03d57da5e9d | [
"MIT"
] | 3 | 2019-07-20T03:59:10.000Z | 2022-03-27T10:20:09.000Z | #ifndef HPP_183_PKT_S2C_FadeMinions_HPP
#define HPP_183_PKT_S2C_FadeMinions_HPP
#include "base.hpp"
#pragma pack(push, 1)
struct PKT_S2C_FadeMinions_s : DefaultPacket<PKT_S2C_FadeMinions>
{
char team;
float fadeAmount;
float fadeTime;
};
#pragma pack(pop)
#endif
| 18.466667 | 65 | 0.779783 | HoDANG |
a15a26a119aaaf9bf0ec84c48ea313f94e4c4c34 | 7,550 | cpp | C++ | src/Tungsten/CommandLine.cpp | jebreimo/Tungsten | 792b9a9a63427bd3a98bd89b7e226e3229745743 | [
"BSD-2-Clause"
] | null | null | null | src/Tungsten/CommandLine.cpp | jebreimo/Tungsten | 792b9a9a63427bd3a98bd89b7e226e3229745743 | [
"BSD-2-Clause"
] | null | null | null | src/Tungsten/CommandLine.cpp | jebreimo/Tungsten | 792b9a9a63427bd3a98bd89b7e226e3229745743 | [
"BSD-2-Clause"
] | null | null | null | //****************************************************************************
// Copyright © 2020 Jan Erik Breimo. All rights reserved.
// Created by Jan Erik Breimo on 2020-04-18.
//
// This file is distributed under the BSD License.
// License text is included with the source distribution.
//****************************************************************************
#include "CommandLine.hpp"
#include <iostream>
#include <SDL2/SDL.h>
#include <Argos/ArgumentParser.hpp>
#include <Tungsten/SdlSession.hpp>
#include <Tungsten/SdlApplication.hpp>
namespace Tungsten
{
namespace
{
const char* getPixelFormatName(uint32_t format)
{
switch (format)
{
case SDL_PIXELFORMAT_ABGR1555:
return "ABGR1555";
case SDL_PIXELFORMAT_ABGR4444:
return "ABGR4444";
case SDL_PIXELFORMAT_ABGR8888:
return "ABGR8888";
case SDL_PIXELFORMAT_ARGB1555:
return "ARGB1555";
case SDL_PIXELFORMAT_ARGB2101010:
return "ARGB2101010";
case SDL_PIXELFORMAT_ARGB4444:
return "ARGB4444";
case SDL_PIXELFORMAT_ARGB8888:
return "ARGB8888";
case SDL_PIXELFORMAT_BGR24:
return "BGR24";
case SDL_PIXELFORMAT_BGR555:
return "BGR555";
case SDL_PIXELFORMAT_BGR565:
return "BGR565";
case SDL_PIXELFORMAT_BGR888:
return "BGR888";
case SDL_PIXELFORMAT_BGRA4444:
return "BGRA4444";
case SDL_PIXELFORMAT_BGRA5551:
return "BGRA5551";
case SDL_PIXELFORMAT_BGRA8888:
return "BGRA8888";
case SDL_PIXELFORMAT_BGRX8888:
return "BGRX8888";
case SDL_PIXELFORMAT_INDEX1LSB:
return "INDEX1LSB";
case SDL_PIXELFORMAT_INDEX1MSB:
return "INDEX1MSB";
case SDL_PIXELFORMAT_INDEX4LSB:
return "INDEX4LSB";
case SDL_PIXELFORMAT_INDEX4MSB:
return "INDEX4MSB";
case SDL_PIXELFORMAT_INDEX8:
return "INDEX8";
case SDL_PIXELFORMAT_IYUV:
return "IYUV";
case SDL_PIXELFORMAT_NV12:
return "NV12";
case SDL_PIXELFORMAT_NV21:
return "NV21";
case SDL_PIXELFORMAT_RGB24:
return "RGB24";
case SDL_PIXELFORMAT_RGB332:
return "RGB332";
case SDL_PIXELFORMAT_RGB444:
return "RGB444";
case SDL_PIXELFORMAT_RGB555:
return "RGB555";
case SDL_PIXELFORMAT_RGB565:
return "RGB565";
case SDL_PIXELFORMAT_RGB888:
return "RGB888";
case SDL_PIXELFORMAT_RGBA4444:
return "RGBA4444";
case SDL_PIXELFORMAT_RGBA5551:
return "RGBA5551";
case SDL_PIXELFORMAT_RGBA8888:
return "RGBA8888";
case SDL_PIXELFORMAT_RGBX8888:
return "RGBX8888";
case SDL_PIXELFORMAT_UYVY:
return "UYVY";
case SDL_PIXELFORMAT_YUY2:
return "YUY2";
case SDL_PIXELFORMAT_YV12:
return "YV12";
case SDL_PIXELFORMAT_YVYU:
return "YVYU";
default:
return "UNKNOWN";
}
}
void printDisplayMode(std::ostream& stream,
int displayIndex,
int modeIndex,
const SDL_DisplayMode& mode)
{
stream << "Mode " << displayIndex
<< ":" << modeIndex
<< " " << getPixelFormatName(mode.format)
<< " " << mode.w << "x" << mode.h
<< " " << mode.refresh_rate << "Hz\n";
}
void printDisplayModes(std::ostream& stream)
{
int numDisplays = SDL_GetNumVideoDisplays();
for (int d = 0; d < numDisplays; ++d)
{
if (auto name = SDL_GetDisplayName(d))
stream << "Display " << d << ": " << name << "\n";
int numModes = SDL_GetNumDisplayModes(d);
for (int m = 0; m < numModes; ++m)
{
SDL_DisplayMode mode = {};
if (SDL_GetDisplayMode(d, m, &mode) == 0)
printDisplayMode(stream, d, m, mode);
}
}
}
}
void addCommandLineOptions(argos::ArgumentParser& parser)
{
using namespace argos;
parser.allow_abbreviated_options(true)
.add(Option{"--windowpos"}.argument("<X>,<Y>")
.help("Set the window position (top left corner)."))
.add(Option{"--windowsize"}.argument("<HOR>x<VER>")
.help("Set the window size."))
.add(Option{"--fullscreen"}
.constant("F")
.help("Start program in the default fullscreen mode."))
.add(Option{"--fullscreen="}.argument("<MODE>")
.alias("--fullscreen")
.help("Start program in the given fullscreen mode."
" MODE is a pair of integers separated by a colon,"
" e.g. '0:5'. Use --listmodes to list available"
" modes."))
.add(Option{"--window"}
.alias("--fullscreen").constant("W")
.help("Start program in window mode. (Default)"))
.add(Option{"--listmodes"}.type(OptionType::STOP)
.help("Display a list of the available fullscreen"
" modes and quit."));
}
void readCommandLineOptions(const argos::ParsedArguments& args,
SdlApplication& app)
{
if (args.value("--listmodes").as_bool())
{
SdlSession session(SDL_INIT_VIDEO);
printDisplayModes(std::cout);
exit(0);
}
WindowParameters wp;
if (auto modeArg = args.value("--fullscreen"))
{
if (modeArg.as_string() == "F")
{
wp.sdlFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
}
else if (modeArg.as_string() != "W")
{
auto mode = modeArg.split(':', 2, 2).as_ints();
wp.fullScreenMode = {mode[0], mode[1]};
wp.sdlFlags |= SDL_WINDOW_FULLSCREEN;
}
}
if (auto windowSizeArg = args.value("--windowsize"))
{
auto size = windowSizeArg.split('x', 2, 2).as_ints();
wp.windowSize = {size[0], size[1]};
}
if (auto windowPosArg = args.value("--windowpos"))
{
auto pos = windowPosArg.split(',', 2, 2).as_ints();
wp.windowSize = {pos[0], pos[1]};
}
app.setWindowParameters(wp);
}
void parseCommandLineOptions(int& argc, char**& argv,
SdlApplication& app)
{
using namespace argos;
ArgumentParser parser(app.name());
addCommandLineOptions(parser);
auto args = parser.parse(argc, argv);
readCommandLineOptions(args, app);
}
}
| 36.124402 | 78 | 0.489536 | jebreimo |
a15cf83cdcc0d41348301d05f4d7123ae82f85e6 | 990 | cpp | C++ | test/filter.cpp | ToruNiina/variadic | 34d28880fdffd1ef09ccddb132b8b42a1e7cc829 | [
"MIT"
] | null | null | null | test/filter.cpp | ToruNiina/variadic | 34d28880fdffd1ef09ccddb132b8b42a1e7cc829 | [
"MIT"
] | null | null | null | test/filter.cpp | ToruNiina/variadic | 34d28880fdffd1ef09ccddb132b8b42a1e7cc829 | [
"MIT"
] | 1 | 2021-11-15T18:01:25.000Z | 2021-11-15T18:01:25.000Z | #include "filter.hpp"
#include <type_traits>
static_assert(std::is_same<
filter<std::is_integral, char, int, double, float>::type,
pack<char, int>>::value, "comprehension.is_integral");
template<typename T1, typename T2>
struct Greater : std::integral_constant<bool, (T1::value > T2::value)>{};
template<typename T>
using greater5 = Greater<T, std::integral_constant<int, 5>>;
static_assert(std::is_same<
filter<greater5,
std::integral_constant<int, 5>,
std::integral_constant<int, 1>,
std::integral_constant<int, 9>,
std::integral_constant<int, 4>,
std::integral_constant<int, 6>,
std::integral_constant<int, 7>,
std::integral_constant<int, 3>
>::type,
pack<
std::integral_constant<int, 9>,
std::integral_constant<int, 6>,
std::integral_constant<int, 7>
>>::value, "comprehension.greater");
int main(){return 0;}
| 30 | 73 | 0.610101 | ToruNiina |
a1646045c62bd6d8b28b7b006c391377ba3ca4e6 | 1,059 | cpp | C++ | Love-Babbar-450-In-CPPTest/14_DP/04_LC_subsequences.cpp | harshanu11/Love-Babbar-450-In-CSharp | 0dc3bef3e66e30abbc04f7bbf21c7319b41803e1 | [
"MIT"
] | null | null | null | Love-Babbar-450-In-CPPTest/14_DP/04_LC_subsequences.cpp | harshanu11/Love-Babbar-450-In-CSharp | 0dc3bef3e66e30abbc04f7bbf21c7319b41803e1 | [
"MIT"
] | null | null | null | Love-Babbar-450-In-CPPTest/14_DP/04_LC_subsequences.cpp | harshanu11/Love-Babbar-450-In-CSharp | 0dc3bef3e66e30abbc04f7bbf21c7319b41803e1 | [
"MIT"
] | null | null | null | ///*
// link: https://practice.geeksforgeeks.org/problems/longest-common-subsequence-1587115620/1
//
// refer DP_tut/LCS/implementation
//*/
//
//// ----------------------------------------------------------------------------------------------------------------------- //
//
//// function to find longest common subsequence
//int static memo[1001][1001];
//int lcs(int n, int m, string s1, string s2) {
//
// // your code here
// for (int i = 0;i < n + 1;i++) {
// memo[i][0] = 0;
// }
// for (int j = 0;j < m + 1;j++) {
// memo[0][j] = 0;
// }
// for (int i = 1;i < n + 1;i++) {
// for (int j = 1;j < m + 1;j++) {
// if (s1[i - 1] == s2[j - 1]) {
// memo[i][j] = 1 + memo[i - 1][j - 1];
// }
// else {
// memo[i][j] = max(memo[i - 1][j], memo[i][j - 1]);
// }
// }
// }
// return memo[n][m];
//}
//
//// ----------------------------------------------------------------------------------------------------------------------- // | 32.090909 | 127 | 0.312559 | harshanu11 |
a16a6be2313446308423f97f2d4ad2f1b98366da | 4,474 | cpp | C++ | example/avr/avr-fade-led.e.cpp | martinmoene/kalman-estimator | 87a20cca596c51f85d6ce21f4e1e4a6ddf8ae344 | [
"BSL-1.0"
] | 20 | 2018-07-27T21:49:21.000Z | 2022-03-03T08:59:54.000Z | example/avr/avr-fade-led.e.cpp | YiBo-zhu/kalman-estimator | 87a20cca596c51f85d6ce21f4e1e4a6ddf8ae344 | [
"BSL-1.0"
] | 3 | 2018-07-23T12:52:53.000Z | 2019-08-16T13:32:17.000Z | example/avr/avr-fade-led.e.cpp | YiBo-zhu/kalman-estimator | 87a20cca596c51f85d6ce21f4e1e4a6ddf8ae344 | [
"BSL-1.0"
] | 3 | 2019-09-26T16:09:18.000Z | 2022-01-17T03:37:07.000Z | // Copyright 2018 by Martin Moene
//
// https://github.com/martinmoene/kalman-estimator
//
// 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)
//
// Show fading PWM on LED.
// Connect PD6 (PWM output) to PD0 (sample PWM)
//
//#include <avr/pgmspace.h>
#include <avr/io.h>
//#include <avr/interrupt.h>
#ifndef led_FEATURE_BLINK_MS
# define led_FEATURE_BLINK_MS 200
#endif
#define led_ddr DDRB
#define led_port PORTB
#define led_bit PB5
#define pwm0_ddr DDRD
#define pwm0_port PORTD
#define pwm0_bit PD6
#define pwm0_value OCR0A
#define pwm1_ddr DDRB
#define pwm1_port PORTB
#define pwm1_bita PB1
#define pwm1_bitb PB2
#define pwm1_val_a OCR1A
#define pwm1_val_b OCR1B
#define spl_ddr DDRD
#define spl_port PIND // read pins
#define spl_bit PD0
#define tstbit( sfr, bit ) (0 != bit_is_set( sfr, bit ) )
#define setbit( sfr, bit ) ( sfr |= bitmask(bit) )
#define xorbit( sfr, bit ) ( sfr ^= bitmask(bit) )
#define clrbit( sfr, bit ) ( sfr &= ~bitmask(bit) )
#define tstmsk( sfr, msk ) (0 != (sfr & bit ) )
#define setmsk( sfr, msk ) ( sfr |= msk )
#define xormsk( sfr, msk ) ( sfr ^= msk )
#define clrmsk( sfr, msk ) ( sfr &= ~msk )
template< typename ...Args >
constexpr uint8_t bitmask( Args&&... args )
{
return static_cast<uint8_t>( ((1 << args) | ...) );
}
// Prescaler
// CS0
// 2 1 0 Description
// 0 0 0 No clock source (Timer/Counter stopped)
// 0 0 1 clkI/O/1 (No prescaling)
// 0 1 0 clkI/O/8 (From prescaler)
// 0 1 1 clkI/O/64 (From prescaler)
// 1 0 0 clkI/O/256 (From prescaler)
// 1 0 1 clkI/O/1024 (From prescaler)
// 1 1 0 External clock source on T0 pin. Clock on falling edge.
// 1 1 1 External clock source on T0 pin. Clock on rising edge.
const auto msk_prescaler_t0_0 = 0;
const auto msk_prescaler_t0_1 = bitmask( CS00 );
const auto msk_prescaler_t0_8 = bitmask( CS01 );
const auto msk_prescaler_t0_64 = bitmask( CS01, CS00 );
const auto msk_prescaler_t0_256 = bitmask( CS02 );
const auto msk_prescaler_t0_1024 = bitmask( CS02, CS00 );
const auto msk_prescaler_t0_et0f = bitmask( CS02, CS01 );
const auto msk_prescaler_t0_et0r = bitmask( CS02, CS01, CS00 );
const auto msk_FAST_PWM_MAX = bitmask( WGM01, WGM00 );
void toggle_led()
{
xorbit( led_port, led_bit );
}
void init_led()
{
setbit( led_port, led_bit );
setbit( led_ddr , led_bit );
}
void init_spl()
{
clrbit( spl_ddr, spl_bit );
}
void init_timer0_pwm()
{
// set PWM pin (PD6) as an output:
setbit( pwm0_ddr, pwm0_bit );
// timer configuration:
// set non-inverting mode:
setmsk( TCCR0A, bitmask( COM0A1 ) );
// set Fast PWM mode:
setmsk( TCCR0A, bitmask( WGM01, WGM00 ) );
// set prescaler to 64:
setmsk( TCCR0B, bitmask( CS01, CS00 ) );
}
void init_timer1_pwm()
{
// set PWM pins PB1 and PB2 as output:
setmsk( pwm1_ddr, bitmask( pwm1_bita, pwm1_bitb ) );
// set non-inverting mode:
setmsk( TCCR1A, bitmask( COM1A1, COM1B1 ) );
#if 1
// set 10-bit Fast PWM mode, TOP is 0x3fff (15 kHz)
setmsk( TCCR1A, bitmask( WGM11, WGM10 ) );
setmsk( TCCR1B, bitmask( WGM12 ) );
#else
// set Fast PWM mode using ICR1 as TOP (500 Hz)
setmsk( TCCR1A, bitmask( WGM11 ) );
setmsk( TCCR1B, bitmask( WGM12, WGM13 ) );
#endif
// start the timer with no prescaler
setbit( TCCR1B, CS10 );
}
void delay_ms( uint16_t ms )
{
constexpr auto ms_count = F_CPU_HZ / ( 7 /*instr*/ * 1000 ) / 5 ;
for( auto i = ms; i != 0; --i )
{
for( auto k = ms_count; k != 0; --k )
{
// asm("nop");
if ( tstbit( spl_port, spl_bit ) )
setbit( led_port, led_bit );
else
clrbit( led_port, led_bit );
}
}
}
int main()
{
init_led();
init_timer0_pwm();
init_timer1_pwm();
for(;;)
{
const auto top = 0x3ffu;
// fade up:
for( uint16_t i = 0; i < top; ++i )
{
// set duty cycle value
pwm0_value = i / 4;
pwm1_val_a = i;
pwm1_val_b = top - i;
delay_ms( 2 );
}
// fade down:
for( uint16_t i = top; i > 0; --i )
{
// set duty cycle value
pwm0_value = i / 4;
pwm1_val_a = i;
pwm1_val_b = top - i;
delay_ms( 2 );
}
}
}
| 24.053763 | 86 | 0.602369 | martinmoene |
a16beee60735dbc6d545efe7e8856b2a32bb2bcd | 1,662 | cpp | C++ | src/tcp/connection_utils.cpp | Mvwivs/tp_advanced_cpp_project | 1be9389005d002709920c7f7cc73ebfe6c16c17b | [
"Apache-2.0"
] | 2 | 2020-05-14T12:21:42.000Z | 2020-05-14T12:27:37.000Z | src/tcp/connection_utils.cpp | Mvwivs/tp_advanced_cpp_project | 1be9389005d002709920c7f7cc73ebfe6c16c17b | [
"Apache-2.0"
] | 2 | 2020-03-20T11:09:43.000Z | 2020-05-22T16:50:38.000Z | src/tcp/connection_utils.cpp | Mvwivs/tp_advanced_cpp_project | 1be9389005d002709920c7f7cc73ebfe6c16c17b | [
"Apache-2.0"
] | null | null | null |
#include "tcp/connection_utils.hpp"
#include <stdexcept>
#include <string>
#include <cstdint>
#include <cstring>
#include <arpa/inet.h>
namespace tcp {
using namespace std::string_literals;
ConnectionException::ConnectionException(const std::string& messsage):
std::runtime_error(messsage) {
}
Address::Address(std::uint32_t ip_addr, std::uint16_t port_addr) :
ip(ip_addr),
port(port_addr) {
}
Address::Address(const std::string& ip_addr, std::uint16_t port_addr):
port(port_addr) {
in_addr in{};
int res = inet_pton(AF_INET, ip_addr.c_str(), &in);
if (res != 1) {
throw ConnectionException("Unable to convert ip from string: "s + std::strerror(errno));
}
ip = ntohl(in.s_addr);
}
std::string Address::ip_as_string() const {
in_addr in{};
in.s_addr = htonl(ip);
char str[INET_ADDRSTRLEN];
const char* res = inet_ntop(AF_INET, &in, str, INET_ADDRSTRLEN);
if (!res) {
throw ConnectionException("Unable to convert ip to string: "s + std::strerror(errno));
}
return { str };
}
Address get_source_address(int fd) {
sockaddr_in src{};
socklen_t len = sizeof(src);
int res = getsockname(fd, reinterpret_cast<sockaddr*>(&src), &len);
if (res == -1) {
throw ConnectionException("Unable to get src address: "s + std::strerror(errno));
}
return { ntohl(src.sin_addr.s_addr), ntohs(src.sin_port) };
}
Address get_destination_address(int fd) {
sockaddr_in src{};
socklen_t len = sizeof(src);
int res = getpeername(fd, reinterpret_cast<sockaddr*>(&src), &len);
if (res == -1) {
throw ConnectionException("Unable to get src address: "s + std::strerror(errno));
}
return { ntohl(src.sin_addr.s_addr), ntohs(src.sin_port) };
}
}
| 25.181818 | 90 | 0.703971 | Mvwivs |
a16e947fd3e0942b64acf973d5374c2e7620f4b6 | 371 | cpp | C++ | src/dialog/TextLog.cpp | 311Volt/axxegro | 61d7a1fb48f9bb581e0f4171d58499cf8c543728 | [
"MIT"
] | null | null | null | src/dialog/TextLog.cpp | 311Volt/axxegro | 61d7a1fb48f9bb581e0f4171d58499cf8c543728 | [
"MIT"
] | null | null | null | src/dialog/TextLog.cpp | 311Volt/axxegro | 61d7a1fb48f9bb581e0f4171d58499cf8c543728 | [
"MIT"
] | null | null | null | #define AXXEGRO_TRUSTED
#include <axxegro/dialog/TextLog.hpp>
#include <stdarg.h>
ALLEGRO_EVENT_SOURCE* al::TextLogEventSource::ptr() const
{
return al_get_native_text_log_event_source(tl.ptr());
}
void al::TextLog::write(const std::string& text)
{
writef("%s", text.c_str());
}
void al::TextLog::writeln(const std::string& text)
{
writef("%s\n", text.c_str());
} | 18.55 | 57 | 0.716981 | 311Volt |
a170b6be6cc0cbfcb9339576dfd8aee29fb5abc0 | 3,200 | cpp | C++ | array/289.game-of-life.cpp | yeweili94/leetcode | 900fd11795f760e3d1d646f1f63887d4d22eb46e | [
"MIT"
] | null | null | null | array/289.game-of-life.cpp | yeweili94/leetcode | 900fd11795f760e3d1d646f1f63887d4d22eb46e | [
"MIT"
] | null | null | null | array/289.game-of-life.cpp | yeweili94/leetcode | 900fd11795f760e3d1d646f1f63887d4d22eb46e | [
"MIT"
] | null | null | null | /*
* [289] Game of Life
*
* https://leetcode.com/problems/game-of-life/description/
*
* algorithms
* Medium (39.04%)
* Total Accepted: 78.5K
* Total Submissions: 200.7K
* Testcase Example: '[[0,1,0],[0,0,1],[1,1,1],[0,0,0]]'
*
* According to the Wikipedia's article: "The Game of Life, also known simply
* as Life, is a cellular automaton devised by the British mathematician John
* Horton Conway in 1970."
*
* Given a board with m by n cells, each cell has an initial state live (1) or
* dead (0). Each cell interacts with its eight neighbors (horizontal,
* vertical, diagonal) using the following four rules (taken from the above
* Wikipedia article):
*
*
* Any live cell with fewer than two live neighbors dies, as if caused by
* under-population.
* Any live cell with two or three live neighbors lives on to the next
* generation.
* Any live cell with more than three live neighbors dies, as if by
* over-population..
* Any dead cell with exactly three live neighbors becomes a live cell, as if
* by reproduction.
*
*
* Write a function to compute the next state (after one update) of the board
* given its current state. The next state is created by applying the above
* rules simultaneously to every cell in the current state, where births and
* deaths occur simultaneously.
*
* Example:
*
*
* Input:
* [
* [0,1,0],
* [0,0,1],
* [1,1,1],
* [0,0,0]
* ]
* Output:
* [
* [0,0,0],
* [1,0,1],
* [0,1,1],
* [0,1,0]
* ]
*
*
* Follow up:
*
*
* Could you solve it in-place? Remember that the board needs to be updated at
* the same time: You cannot update some cells first and then use their updated
* values to update other cells.
* In this question, we represent the board using a 2D array. In principle, the
* board is infinite, which would cause problems when the active area
* encroaches the border of the array. How would you address these problems?
*
*
*/
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
int row = board.size();
if (row <= 0) return;
int col = board[0].size();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
int neighbor = caculate_neighbor(board, i, j);
if ((neighbor >= 2) && (neighbor <= 3) && (board[i][j] == 1)) {
board[i][j] = 3;
}
else if ((neighbor == 3) && (board[i][j] == 0)) {
board[i][j] = 2;
}
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
board[i][j] >>= 1;
}
}
}
int caculate_neighbor(const vector<vector<int>>& board, int row, int col) {
int rr = board.size();
int cc = board[0].size();
int sum = 0;
for (int r = row - 1; r <= row + 1; r++) {
for (int c = col - 1; c <= col + 1; c++) {
if (r < 0 || r >= rr || c < 0 || c >= cc) {
continue;
}
sum += (board[r][c]&1);
}
}
return (sum - (board[row][col]&1));
}
};
| 29.906542 | 79 | 0.5475 | yeweili94 |
a175f6507b0ea40e8d2a5573bf9b329dcc30f85c | 4,536 | cpp | C++ | main/net/httpClient.cpp | maroc81/WeatherLily | 9fec01add5552eb3e2ba955ded332704b369738e | [
"MIT"
] | 2 | 2021-12-15T01:10:58.000Z | 2022-02-21T16:49:48.000Z | main/net/httpClient.cpp | maroc81/WeatherLily | 9fec01add5552eb3e2ba955ded332704b369738e | [
"MIT"
] | null | null | null | main/net/httpClient.cpp | maroc81/WeatherLily | 9fec01add5552eb3e2ba955ded332704b369738e | [
"MIT"
] | null | null | null |
#include <cstring>
#include "esp_log.h"
#include "httpClient.hpp"
static const char * TAG = "httpClientT";
//******************************************************************************
//! httpClientT() -- Constructor
//
//!
//******************************************************************************
httpClientT::httpClientT(const char * urlIC) :
configM {
.url = urlIC,
.event_handler = httpClientT::HandleGlobalEvent,
.user_data = this
},
clientM(nullptr),
getCbMP(nullptr)
{
} // end httpClientT() - Constructor
//******************************************************************************
//! httpClientT() -- Constructor
//
//!
//******************************************************************************
httpClientT::httpClientT(const char * hostIC, const char * pathIC) :
configM {
.host = hostIC,
.path = pathIC,
.event_handler = httpClientT::HandleGlobalEvent,
.user_data = this
},
clientM(nullptr),
getCbMP(nullptr)
{
} // end httpClientT() - Constructor
//******************************************************************************
//! HandleGlobalEvent()
//
//! Routes c-style callback to c++ handler
//******************************************************************************
esp_err_t httpClientT::HandleGlobalEvent(esp_http_client_event_t *evt)
{
auto inst = static_cast<httpClientT*>(evt->user_data);
return inst->HandleEvent(evt);
} // end HandleGlobalEvent()
//******************************************************************************
//! HandleEvent()
//
//!
//******************************************************************************
esp_err_t httpClientT::HandleEvent(esp_http_client_event_t *evt)
{
switch(evt->event_id) {
case HTTP_EVENT_ERROR:
ESP_LOGI(TAG, "HTTP_EVENT_ERROR");
break;
case HTTP_EVENT_ON_CONNECTED:
ESP_LOGI(TAG, "HTTP_EVENT_ON_CONNECTED");
break;
case HTTP_EVENT_HEADER_SENT:
ESP_LOGI(TAG, "HTTP_EVENT_HEADER_SENT");
break;
case HTTP_EVENT_ON_HEADER:
ESP_LOGI(TAG, "HTTP_EVENT_ON_HEADER");
printf("%.*s", evt->data_len, (char*)evt->data);
break;
case HTTP_EVENT_ON_DATA:
ESP_LOGI(TAG, "HTTP_EVENT_ON_DATA, len=%d", evt->data_len);
if (!esp_http_client_is_chunked_response(evt->client))
{
//printf("%.*s", evt->data_len, (char*)evt->data);
}
break;
case HTTP_EVENT_ON_FINISH:
ESP_LOGI(TAG, "HTTP_EVENT_ON_FINISH");
break;
case HTTP_EVENT_DISCONNECTED:
ESP_LOGI(TAG, "HTTP_EVENT_DISCONNECTED");
break;
}
if( getCbMP != nullptr )
{
(*getCbMP)(evt);
}
return ESP_OK;
} // end handleEvent()
//******************************************************************************
//! Get()
//
//!
//******************************************************************************
void httpClientT::Get(std::vector<char> & respBufIR)
{
// Create call back to process client response and store in buffer
auto saveResponseCb = [&respBufIR](esp_http_client_event_t *evt)
{
if( evt->event_id == HTTP_EVENT_ON_DATA )
{
// Resize response buffer to hold data and copy in response
const std::size_t curSizeC = respBufIR.size();
const std::size_t dataLenC = evt->data_len;
respBufIR.resize(curSizeC + dataLenC);
memcpy(&respBufIR[curSizeC], evt->data, dataLenC);
}
};
// Perform the query using the above lambda to store the response
Perform(saveResponseCb);
} // end Get()
//******************************************************************************
//! Perform()
//
//! Performs an HTTP query, calling the given function for each HTTP event
//******************************************************************************
void httpClientT::Perform(std::function<void(esp_http_client_event_t *evt)> cb)
{
getCbMP = &cb;
clientM = esp_http_client_init(&configM);
esp_err_t err = esp_http_client_perform(clientM);
if (err == ESP_OK)
{
ESP_LOGI(TAG, "Status = %d, content_length = %d",
esp_http_client_get_status_code(clientM),
esp_http_client_get_content_length(clientM)
);
}
esp_http_client_cleanup(clientM);
getCbMP = nullptr;
} // end Perform()
| 28.89172 | 80 | 0.479938 | maroc81 |
a17a9f852f6b0d021b34587a549302bcdb891582 | 825 | hpp | C++ | thrill/data/fwd.hpp | JonasDann/thrill | c2f4cc8bb4e362bb129c056d16faae602b42cbe7 | [
"BSD-2-Clause"
] | null | null | null | thrill/data/fwd.hpp | JonasDann/thrill | c2f4cc8bb4e362bb129c056d16faae602b42cbe7 | [
"BSD-2-Clause"
] | null | null | null | thrill/data/fwd.hpp | JonasDann/thrill | c2f4cc8bb4e362bb129c056d16faae602b42cbe7 | [
"BSD-2-Clause"
] | null | null | null | /*******************************************************************************
* thrill/data/fwd.hpp
*
* Part of Project Thrill - http://project-thrill.org
*
* Copyright (C) 2019 Jonas Dann <jonas@dann.io>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
#ifndef THRILL_DATA_FWD_HEADER
#define THRILL_DATA_FWD_HEADER
#include <tlx/counting_ptr.hpp>
namespace thrill {
namespace data {
template <typename ItemType>
class SampledFile;
template <typename ItemType>
using SampledFilePtr = tlx::CountingPtr<SampledFile<ItemType> >;
} // namespace data
} // namespace thrill
#endif // !THRILL_DATA_FWD_HEADER
/******************************************************************************/
| 26.612903 | 80 | 0.533333 | JonasDann |
a17b580512cc2f1fa74dcd38d03717157afa1bb6 | 1,619 | cpp | C++ | cpp/04_trees_and_graphs/05_validate_bst/ans1.cpp | zulinx86/cracking-the-coding-interview | fdb1e9f2cb1b06be2012c29d781190907bad9fd6 | [
"MIT"
] | null | null | null | cpp/04_trees_and_graphs/05_validate_bst/ans1.cpp | zulinx86/cracking-the-coding-interview | fdb1e9f2cb1b06be2012c29d781190907bad9fd6 | [
"MIT"
] | null | null | null | cpp/04_trees_and_graphs/05_validate_bst/ans1.cpp | zulinx86/cracking-the-coding-interview | fdb1e9f2cb1b06be2012c29d781190907bad9fd6 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct node {
int val;
struct node *left;
struct node *right;
};
pair<int, int> __check_bst(struct node *n, bool &ans)
{
pair<int, int> left_minmax, right_minmax, ret_minmax;
// left
if (n->left)
left_minmax = __check_bst(n->left, ans);
else
left_minmax = make_pair(n->val, n->val);
// right
if (n->right)
right_minmax = __check_bst(n->right, ans);
else
right_minmax = make_pair(n->val, n->val);
// check
if (n->val < left_minmax.second || right_minmax.first < n->val)
ans = false;
cout << n->val << ": "
<< "left (" << left_minmax.first << ", " << left_minmax.second << "), "
<< "right (" << right_minmax.first << ", " << right_minmax.second << ")" << endl;
ret_minmax.first = min(n->val, min(left_minmax.first, right_minmax.first));
ret_minmax.second = max(n->val, max(left_minmax.second, right_minmax.second));
return ret_minmax;
}
bool check_bst(struct node *n) {
bool ans = true;
__check_bst(n, ans);
return ans;
}
int main(void)
{
int n, i;
cin >> n;
vector<struct node> nodes(n);
for (i = 0; i < n; ++i) {
int v;
cin >> v;
if (v == -1) {
int par = (i - 1) / 2;
if (2 * par + 1 == i) {
nodes[par].left = NULL;
} else if (2 * par + 2 == i) {
nodes[par].right = NULL;
}
} else {
nodes[i].val = v;
if (i < n / 2) {
nodes[i].left = &nodes[2 * i + 1];
nodes[i].right = &nodes[2 * i + 2];
} else {
nodes[i].left = NULL;
nodes[i].right = NULL;
}
}
}
check_bst(&nodes[0], ans);
cout << (ans ? "Yes" : "No") << endl;
return 0;
}
| 19.047059 | 83 | 0.573811 | zulinx86 |
a17fcd00e1cb600e21c203332fdf86b475b17adf | 2,792 | cpp | C++ | ch6/gauss_newton.cpp | zinsmatt/slambook2 | 3648caff838241553d9f3de332068eb0d501a7dc | [
"MIT"
] | null | null | null | ch6/gauss_newton.cpp | zinsmatt/slambook2 | 3648caff838241553d9f3de332068eb0d501a7dc | [
"MIT"
] | null | null | null | ch6/gauss_newton.cpp | zinsmatt/slambook2 | 3648caff838241553d9f3de332068eb0d501a7dc | [
"MIT"
] | null | null | null | #include <iostream>
#include <chrono>
#include <random>
#include <map>
#include <opencv2/opencv.hpp>
#include <Eigen/Core>
#include <Eigen/Dense>
#include "matplotlibcpp.h"
using namespace std;
using namespace Eigen;
namespace plt = matplotlibcpp;
double g(double x, double a, double b, double c)
{
// return a*x*x+b*x+c;
return std::exp(a * x * x + b * x + c);
}
int main(int argc, char **argv) {
std::cout << "Gauss-Newton \n";
double aa = 1.0, bb = 2.0, cc = 1.0;
double a = 2.0, b = -1.0, c = 5.5;
double obs_sigma = 1.0;
std::default_random_engine generator;
std::normal_distribution<double> obs_noise_distrib(0.0, obs_sigma);
int N = 100;
std::vector<double> x_data(N), y_data(N);
for (int i = 0; i < N; ++i)
{
x_data[i] = static_cast<double>(i) / 100.0;
y_data[i] = g(x_data[i], aa, bb, cc) + obs_noise_distrib(generator);
}
chrono::steady_clock::time_point t1 = chrono::steady_clock::now();
// Optimize
int max_iter = 10000;
for (int it = 0; it < max_iter; ++it)
{
// std::cout << "iter " << it << " : ";
// std::cout << "abc = " << a << " " << b << " " << c << "\n";
Eigen::Matrix3d H = Eigen::Matrix3d::Zero();
Eigen::Vector3d e = Eigen::Vector3d::Zero();
double total_err = 0.0;
for (int i = 0; i < N; ++i)
{
double x = x_data[i];
double gx = g(x, a, b, c);
double err = y_data[i] - gx;
total_err += err * err;
// Compute derivative of f(x) (F(x) = 1/2 sum(||f(x)||^2)
Eigen::Vector3d J(0.0, 0.0, 0.0);
J[0] = -x * x * gx; // df/da
J[1] = -x * gx; // df/db
J[2] = -gx; // df/dc
// left part of the normal equation
H += J * J.transpose();
// right part
e += -J * err;
}
// std::cout << "H = " << H << "\n";
// std::cout << "total error: " << total_err << "\n";
// solve Hx = e
Eigen::Vector3d delta_x = H.inverse() * e;
// Eigen::Vector3d delta_x = H.ldlt().solve(e); // second version
// std::cout << "delta_x = " << delta_x.transpose() << "\n";
if (delta_x.norm() < 1e-4)
break;
a += delta_x[0];
b += delta_x[1];
c += delta_x[2];
}
chrono::steady_clock::time_point t2 = chrono::steady_clock::now();
chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);
cout << "solve time cost = " << time_used.count() << " seconds. " << endl;
std::cout << "final = " << a << " " << b << " " << c << "\n";
vector<double> final_y_data(N);
for (int i = 0; i < N; ++i)
{
final_y_data[i] = g(x_data[i], a, b, c);
}
plt::scatter(x_data, y_data);
std::map<std::string, std::string> parameters;
parameters["c"] = "red";
plt::scatter(x_data, final_y_data, 1.0, parameters);
plt::show();
return 0;
}
| 25.851852 | 96 | 0.545487 | zinsmatt |
a183e3c7506abd2efb9dd2eb977d42ece9cc3144 | 15,337 | cpp | C++ | src/scripts/scripts/northrend/naxxramas/boss_gothik.cpp | Subv/diamondcore | e11891587736b6308e554f71cb56e8df1a1812ad | [
"OpenSSL"
] | 1 | 2018-01-17T08:11:17.000Z | 2018-01-17T08:11:17.000Z | src/scripts/scripts/northrend/naxxramas/boss_gothik.cpp | Subv/diamondcore | e11891587736b6308e554f71cb56e8df1a1812ad | [
"OpenSSL"
] | null | null | null | src/scripts/scripts/northrend/naxxramas/boss_gothik.cpp | Subv/diamondcore | e11891587736b6308e554f71cb56e8df1a1812ad | [
"OpenSSL"
] | null | null | null | /* Copyright (C) 2006 - 2010 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: Boss_Gothik
SD%Complete: 60
SDComment: Only base implemented. Todo: control adds at summon. Handle case of raid not splitted in two sides
SDCategory: Naxxramas
EndScriptData */
#include "precompiled.h"
#include "naxxramas.h"
enum
{
SAY_SPEECH_1 = -1533040,
SAY_SPEECH_2 = -1533140,
SAY_SPEECH_3 = -1533141,
SAY_SPEECH_4 = -1533142,
SAY_KILL = -1533041,
SAY_DEATH = -1533042,
SAY_TELEPORT = -1533043,
EMOTE_TO_FRAY = -1533138,
EMOTE_GATE = -1533139,
PHASE_SPEECH = 0,
PHASE_BALCONY = 1,
PHASE_GROUND = 2,
PHASE_END = 3,
MAX_WAVES = 19,
SPELL_TELEPORT_LEFT = 28025, // guesswork
SPELL_TELEPORT_RIGHT = 28026, // could be defined as dead or live side, left or right facing north
SPELL_HARVESTSOUL = 28679,
SPELL_SHADOWBOLT = 29317,
SPELL_SHADOWBOLT_H = 56405,
};
enum eSpellDummy
{
SPELL_A_TO_ANCHOR_1 = 27892,
SPELL_B_TO_ANCHOR_1 = 27928,
SPELL_C_TO_ANCHOR_1 = 27935,
SPELL_A_TO_ANCHOR_2 = 27893,
SPELL_B_TO_ANCHOR_2 = 27929,
SPELL_C_TO_ANCHOR_2 = 27936,
SPELL_A_TO_SKULL = 27915,
SPELL_B_TO_SKULL = 27931,
SPELL_C_TO_SKULL = 27937
};
struct boss_gothikAI : public ScriptedAI
{
boss_gothikAI(Creature* pCreature) : ScriptedAI(pCreature)
{
m_pInstance = (instance_naxxramas*)pCreature->GetInstanceData();
m_bIsRegularMode = pCreature->GetMap()->IsRegularDifficulty();
SetCombatMovement(false);
Reset();
}
instance_naxxramas* m_pInstance;
bool m_bIsRegularMode;
uint8 m_uiPhase;
uint8 m_uiSpeechCount;
uint32 m_uiSpeechTimer;
uint8 m_uiSummonCount;
uint32 m_uiSummonTimer;
uint32 m_uiTeleportTimer;
uint32 m_uiShadowboltTimer;
void Reset()
{
m_uiPhase = PHASE_SPEECH;
m_uiSpeechCount = 0;
m_uiSpeechTimer = 5000;
m_uiSummonCount = 0;
m_uiSummonTimer = 5000;
m_uiTeleportTimer = 15000;
m_uiShadowboltTimer = 2500;
}
void Aggro(Unit* pWho)
{
m_creature->SetInCombatWithZone();
DoScriptText(SAY_SPEECH_1, m_creature);
if (!m_pInstance)
return;
m_pInstance->SetData(TYPE_GOTHIK, IN_PROGRESS);
m_pInstance->SetGothTriggers();
}
bool HasPlayersInLeftSide()
{
Map::PlayerList const& lPlayers = m_pInstance->instance->GetPlayers();
if (lPlayers.isEmpty())
return false;
for(Map::PlayerList::const_iterator itr = lPlayers.begin(); itr != lPlayers.end(); ++itr)
{
if (Player* pPlayer = itr->getSource())
{
if (!m_pInstance->IsInRightSideGothArea(pPlayer))
return true;
}
}
return false;
}
void KilledUnit(Unit* pVictim)
{
if (pVictim->GetTypeId() == TYPEID_PLAYER)
DoScriptText(SAY_KILL, m_creature);
}
void JustDied(Unit* pKiller)
{
DoScriptText(SAY_DEATH, m_creature);
if (m_pInstance)
m_pInstance->SetData(TYPE_GOTHIK, DONE);
}
void JustReachedHome()
{
if (m_pInstance)
m_pInstance->SetData(TYPE_GOTHIK, FAIL);
}
void SummonAdds(bool bRightSide, uint32 uiSummonEntry)
{
std::list<Creature*> lSummonList;
m_pInstance->GetGothSummonPointCreatures(lSummonList, bRightSide);
if (lSummonList.empty())
return;
uint8 uiCount = 2;
switch(uiSummonEntry)
{
case NPC_UNREL_TRAINEE:
lSummonList.sort(ObjectDistanceOrder(m_creature));
break;
case NPC_UNREL_DEATH_KNIGHT:
case NPC_UNREL_RIDER:
uiCount = 1;
lSummonList.sort(ObjectDistanceOrderReversed(m_creature));
break;
}
for(std::list<Creature*>::iterator itr = lSummonList.begin(); itr != lSummonList.end(); ++itr)
{
if (uiCount == 0)
break;
m_creature->SummonCreature(uiSummonEntry, (*itr)->GetPositionX(), (*itr)->GetPositionY(), (*itr)->GetPositionZ(), (*itr)->GetOrientation(), TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000);
--uiCount;
}
}
void SummonedCreatureJustDied(Creature* pSummoned)
{
if (!m_pInstance)
return;
if (Creature* pAnchor = m_pInstance->GetClosestAnchorForGoth(pSummoned, true))
{
switch(pSummoned->GetEntry())
{
// Wrong caster, it expected to be pSummoned.
// DiamondCore deletes the spell event at caster death, so for delayed spell like this
// it's just a workaround. Does not affect other than the visual though (+ spell takes longer to "travel")
case NPC_UNREL_TRAINEE: m_creature->CastSpell(pAnchor, SPELL_A_TO_ANCHOR_1, true, NULL, NULL, pSummoned->GetGUID()); break;
case NPC_UNREL_DEATH_KNIGHT: m_creature->CastSpell(pAnchor, SPELL_B_TO_ANCHOR_1, true, NULL, NULL, pSummoned->GetGUID()); break;
case NPC_UNREL_RIDER: m_creature->CastSpell(pAnchor, SPELL_C_TO_ANCHOR_1, true, NULL, NULL, pSummoned->GetGUID()); break;
}
}
}
void UpdateAI(const uint32 uiDiff)
{
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
return;
switch(m_uiPhase)
{
case PHASE_SPEECH:
{
if (m_uiSpeechTimer < uiDiff)
{
m_uiSpeechTimer = 5000;
++m_uiSpeechCount;
switch(m_uiSpeechCount)
{
case 1: DoScriptText(SAY_SPEECH_2, m_creature); break;
case 2: DoScriptText(SAY_SPEECH_3, m_creature); break;
case 3: DoScriptText(SAY_SPEECH_4, m_creature); break;
case 4: m_uiPhase = PHASE_BALCONY; break;
}
}
else
m_uiSpeechTimer -= uiDiff;
break;
}
case PHASE_BALCONY:
{
if (m_uiSummonTimer < uiDiff)
{
if (m_uiSummonCount >= MAX_WAVES)
{
DoScriptText(SAY_TELEPORT, m_creature);
DoScriptText(EMOTE_TO_FRAY, m_creature);
DoCastSpellIfCan(m_creature, SPELL_TELEPORT_RIGHT);
m_uiPhase = PHASE_GROUND;
return;
}
// npc, npc, npc, timer
static uint32 const auiSummonData[MAX_WAVES][4] =
{
{NPC_UNREL_TRAINEE, 0, 0, 20000},
{NPC_UNREL_TRAINEE, 0, 0, 20000},
{NPC_UNREL_TRAINEE, 0, 0, 10000},
{NPC_UNREL_DEATH_KNIGHT, 0, 0, 10000},
{NPC_UNREL_TRAINEE, 0, 0, 15000},
{NPC_UNREL_DEATH_KNIGHT, 0, 0, 10000},
{NPC_UNREL_TRAINEE, 0, 0, 15000},
{NPC_UNREL_DEATH_KNIGHT, NPC_UNREL_TRAINEE, 0, 10000},
{NPC_UNREL_RIDER, 0, 0, 10000},
{NPC_UNREL_TRAINEE, 0, 0, 5000},
{NPC_UNREL_DEATH_KNIGHT, 0, 0, 15000},
{NPC_UNREL_TRAINEE, NPC_UNREL_RIDER, 0, 10000},
{NPC_UNREL_DEATH_KNIGHT, NPC_UNREL_DEATH_KNIGHT, 0, 10000},
{NPC_UNREL_TRAINEE, 0, 0, 10000},
{NPC_UNREL_RIDER, 0, 0, 5000},
{NPC_UNREL_DEATH_KNIGHT, 0, 0, 5000},
{NPC_UNREL_TRAINEE, 0, 0, 20000},
{NPC_UNREL_RIDER, NPC_UNREL_DEATH_KNIGHT, NPC_UNREL_TRAINEE, 15000},
{NPC_UNREL_TRAINEE, 0, 0, 30000},
};
SummonAdds(true, auiSummonData[m_uiSummonCount][0]);
if (auiSummonData[m_uiSummonCount][1])
SummonAdds(true, auiSummonData[m_uiSummonCount][1]);
if (auiSummonData[m_uiSummonCount][2])
SummonAdds(true, auiSummonData[m_uiSummonCount][2]);
m_uiSummonTimer = auiSummonData[m_uiSummonCount][3];
++m_uiSummonCount;
}
else
m_uiSummonTimer -= uiDiff;
break;
}
case PHASE_GROUND:
case PHASE_END:
{
if (m_uiPhase == PHASE_GROUND)
{
if (m_creature->GetHealthPercent() < 30.0f)
{
if (m_pInstance->IsInRightSideGothArea(m_creature))
{
DoScriptText(EMOTE_GATE, m_creature);
m_pInstance->SetData(TYPE_GOTHIK, SPECIAL);
m_uiPhase = PHASE_END;
m_uiShadowboltTimer = 2000;
return;
}
}
if (m_uiTeleportTimer < uiDiff)
{
uint32 uiTeleportSpell = m_pInstance->IsInRightSideGothArea(m_creature) ? SPELL_TELEPORT_LEFT : SPELL_TELEPORT_RIGHT;
if (DoCastSpellIfCan(m_creature, uiTeleportSpell) == CAST_OK)
{
DoResetThreat();
m_uiTeleportTimer = 15000;
m_uiShadowboltTimer = 2000;
return;
}
}
else
m_uiTeleportTimer -= uiDiff;
}
if (m_uiShadowboltTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature->getVictim(), m_bIsRegularMode ? SPELL_SHADOWBOLT: SPELL_SHADOWBOLT_H) == CAST_OK)
m_uiShadowboltTimer = 1500;
}
else
m_uiShadowboltTimer -= uiDiff;
DoMeleeAttackIfReady(); // possibly no melee at all
break;
}
}
}
};
CreatureAI* GetAI_boss_gothik(Creature* pCreature)
{
return new boss_gothikAI(pCreature);
}
bool EffectDummyCreature_spell_anchor(Unit* pCaster, uint32 uiSpellId, SpellEffectIndex uiEffIndex, Creature* pCreatureTarget)
{
if (uiEffIndex != EFFECT_INDEX_0 || pCreatureTarget->GetEntry() != NPC_SUB_BOSS_TRIGGER)
return true;
instance_naxxramas* pInstance = (instance_naxxramas*)pCreatureTarget->GetInstanceData();
if (!pInstance)
return true;
switch(uiSpellId)
{
case SPELL_A_TO_ANCHOR_1: // trigger mobs at high right side
case SPELL_B_TO_ANCHOR_1:
case SPELL_C_TO_ANCHOR_1:
{
if (Creature* pAnchor2 = pInstance->GetClosestAnchorForGoth(pCreatureTarget, false))
{
uint32 uiTriggered = SPELL_A_TO_ANCHOR_2;
if (uiSpellId == SPELL_B_TO_ANCHOR_1)
uiTriggered = SPELL_B_TO_ANCHOR_2;
else if (uiSpellId == SPELL_C_TO_ANCHOR_1)
uiTriggered = SPELL_C_TO_ANCHOR_2;
pCreatureTarget->CastSpell(pAnchor2, uiTriggered, true);
}
return true;
}
case SPELL_A_TO_ANCHOR_2: // trigger mobs at high left side
case SPELL_B_TO_ANCHOR_2:
case SPELL_C_TO_ANCHOR_2:
{
std::list<Creature*> lTargets;
pInstance->GetGothSummonPointCreatures(lTargets, false);
if (!lTargets.empty())
{
std::list<Creature*>::iterator itr = lTargets.begin();
uint32 uiPosition = urand(0, lTargets.size()-1);
advance(itr, uiPosition);
if (Creature* pTarget = (*itr))
{
uint32 uiTriggered = SPELL_A_TO_SKULL;
if (uiSpellId == SPELL_B_TO_ANCHOR_2)
uiTriggered = SPELL_B_TO_SKULL;
else if (uiSpellId == SPELL_C_TO_ANCHOR_2)
uiTriggered = SPELL_C_TO_SKULL;
pCreatureTarget->CastSpell(pTarget, uiTriggered, true);
}
}
return true;
}
case SPELL_A_TO_SKULL: // final destination trigger mob
case SPELL_B_TO_SKULL:
case SPELL_C_TO_SKULL:
{
if (Creature* pGoth = pInstance->instance->GetCreature(pInstance->GetData64(NPC_GOTHIK)))
{
uint32 uiNpcEntry = NPC_SPECT_TRAINEE;
if (uiSpellId == SPELL_B_TO_SKULL)
uiNpcEntry = NPC_SPECT_DEATH_KNIGTH;
else if (uiSpellId == SPELL_C_TO_SKULL)
uiNpcEntry = NPC_SPECT_RIDER;
pGoth->SummonCreature(uiNpcEntry, pCreatureTarget->GetPositionX(), pCreatureTarget->GetPositionY(), pCreatureTarget->GetPositionZ(), pCreatureTarget->GetOrientation(), TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 20000);
if (uiNpcEntry == NPC_SPECT_RIDER)
pGoth->SummonCreature(NPC_SPECT_HORSE, pCreatureTarget->GetPositionX(), pCreatureTarget->GetPositionY(), pCreatureTarget->GetPositionZ(), pCreatureTarget->GetOrientation(), TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 20000);
}
return true;
}
}
return true;
};
void AddSC_boss_gothik()
{
Script* newscript;
newscript = new Script;
newscript->Name = "boss_gothik";
newscript->GetAI = &GetAI_boss_gothik;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "spell_anchor";
newscript->pEffectDummyCreature = &EffectDummyCreature_spell_anchor;
newscript->RegisterSelf();
}
| 34.620767 | 240 | 0.543522 | Subv |
a18559aacc380518ce383333c91f37268b8276e3 | 4,828 | cpp | C++ | Src/rmsVel.cpp | AMReX-Combustion/PeleAnalysis | 4cbbdb39f56c42d2539eef82bb6cbcc64d2d896b | [
"BSD-3-Clause-LBNL"
] | 4 | 2019-04-24T13:33:35.000Z | 2021-08-24T07:11:22.000Z | Src/rmsVel.cpp | AMReX-Combustion/PeleAnalysis | 4cbbdb39f56c42d2539eef82bb6cbcc64d2d896b | [
"BSD-3-Clause-LBNL"
] | 4 | 2020-02-25T01:58:46.000Z | 2022-02-01T20:22:49.000Z | Src/rmsVel.cpp | AMReX-Combustion/PeleAnalysis | 4cbbdb39f56c42d2539eef82bb6cbcc64d2d896b | [
"BSD-3-Clause-LBNL"
] | 6 | 2018-11-05T11:53:20.000Z | 2021-03-22T10:44:54.000Z | #include <AMReX_ParmParse.H>
#include <AMReX_MultiFab.H>
#include <AMReX_MultiFabUtil.H>
#include <AMReX_DataServices.H>
#include <AMReX_WritePlotFile.H>
using namespace amrex;
int
main (int argc,
char* argv[])
{
Initialize(argc,argv);
{
ParmParse pp;
// Open first plotfile header and create an amrData object pointing into it
int nPlotFiles = pp.countval("infiles");
AMREX_ALWAYS_ASSERT(nPlotFiles>0);
Vector<std::string> plotFileNames; pp.getarr("infiles",plotFileNames,0,nPlotFiles);
int nVars(3);
Vector<std::string> whichVar(nVars);
whichVar[0] = "x_velocity";
whichVar[1] = "y_velocity";
whichVar[2] = "z_velocity";
Vector<int> destFills(nVars);
for (int c=0; c<nVars; c++)
destFills[c] = c;
DataServices::SetBatchMode();
Amrvis::FileType fileType(Amrvis::NEWPLT);
Vector<DataServices *> dataServicesPtrVector(nPlotFiles); // DataServices array for each plot
Vector<AmrData *> amrDataPtrVector(nPlotFiles); // DataPtrVector for each plot
Vector<Real> time(nPlotFiles);
Vector<Real> urms(nPlotFiles);
for(int iPlot = 0; iPlot < nPlotFiles; ++iPlot) {
if (ParallelDescriptor::IOProcessor())
std::cout << "Loading " << plotFileNames[iPlot] << std::endl;
dataServicesPtrVector[iPlot] = new DataServices(plotFileNames[iPlot], fileType); // Populate DataServices array
if( ! dataServicesPtrVector[iPlot]->AmrDataOk()) // Check AmrData ok
DataServices::Dispatch(DataServices::ExitRequest, NULL); // Exit if not
amrDataPtrVector[iPlot] = &(dataServicesPtrVector[iPlot]->AmrDataRef()); // Populate DataPtrVector
time[iPlot] = amrDataPtrVector[iPlot]->Time();
}
for (int iPlot=0; iPlot<nPlotFiles; iPlot++) {
int finestLevel = amrDataPtrVector[iPlot]->FinestLevel();
int inFinestLevel(-1); pp.query("finestLevel",inFinestLevel);
if (inFinestLevel>-1 && inFinestLevel<finestLevel) {
finestLevel = inFinestLevel;
if (ParallelDescriptor::IOProcessor())
std::cout << "Finest level: " << finestLevel << std::endl;
}
Vector<Real> probLo=amrDataPtrVector[iPlot]->ProbLo();
Vector<Real> probHi=amrDataPtrVector[iPlot]->ProbHi();
const Real *dx = amrDataPtrVector[iPlot]->DxLevel()[finestLevel].dataPtr();
Real dxyz = dx[0]*dx[1]*dx[2];
int ngrow(0);
MultiFab mf;
const BoxArray& ba = amrDataPtrVector[iPlot]->boxArray(finestLevel);
DistributionMapping dm(ba);
mf.define(ba, dm, nVars, ngrow);
if (ParallelDescriptor::IOProcessor())
std::cout << "Processing " << iPlot << "/" << nPlotFiles << std::endl;
amrDataPtrVector[iPlot]->FillVar(mf, finestLevel, whichVar, destFills);
for (int n=0; n<nVars; n++)
amrDataPtrVector[iPlot]->FlushGrids(amrDataPtrVector[iPlot]->StateNumber(whichVar[n]));
Real vol(0), uxb(0), uyb(0), uzb(0), ux2(0), uy2(0), uz2(0);
for(MFIter ntmfi(mf); ntmfi.isValid(); ++ntmfi) {
const FArrayBox &myFab = mf[ntmfi];
Vector<const Real *> varPtr(nVars);
for (int v=0; v<nVars; v++)
varPtr[v] = myFab.dataPtr(v);
const Box& vbx = ntmfi.validbox();
const int *lo = vbx.smallEnd().getVect();
const int *hi = vbx.bigEnd().getVect();
int ix = hi[0]-lo[0]+1;
int jx = hi[1]-lo[1]+1;
int kx = hi[2]-lo[2]+1;
for (int k=0; k<kx; k++) {
Real z=probLo[2] + dx[2]*(0.5+(Real)(k+lo[2]));
for (int j=0; j<jx; j++) {
Real y=probLo[1] + dx[1]*(0.5+(Real)(j+lo[1]));
for (int i=0; i<ix; i++) {
Real x=probLo[0] + dx[0]*(0.5+(Real)(i+lo[0]));
int cell = (k*jx+j)*ix+i;
Real ux = varPtr[0][cell];
Real uy = varPtr[1][cell];
Real uz = varPtr[2][cell];
vol += dxyz;
uxb += ux*dxyz;
uyb += uy*dxyz;
uzb += uz*dxyz;
ux2 += ux*ux*dxyz;
uy2 += uy*uy*dxyz;
uz2 += uz*uz*dxyz;
}
}
}
}
ParallelDescriptor::ReduceRealSum(vol);
ParallelDescriptor::ReduceRealSum(uxb);
ParallelDescriptor::ReduceRealSum(uyb);
ParallelDescriptor::ReduceRealSum(uzb);
ParallelDescriptor::ReduceRealSum(ux2);
ParallelDescriptor::ReduceRealSum(uy2);
ParallelDescriptor::ReduceRealSum(uz2);
uxb /= vol; uyb /= vol; uzb /= vol;
ux2 /= vol; uy2 /= vol; uz2 /= vol;
urms[iPlot] = sqrt( ( (ux2-uxb*uxb) + (uy2-uyb*uyb) + (uz2-uzb*uzb) ) / 3. );
}
if (ParallelDescriptor::IOProcessor())
std::cout << " ...done." << std::endl;
if (ParallelDescriptor::IOProcessor()) {
FILE *file = fopen("RmsVel.dat","w");
for (int iPlot=0; iPlot<nPlotFiles; iPlot++)
fprintf(file,"%e %e\n",time[iPlot],urms[iPlot]);
fclose(file);
}
}
Finalize();
return 0;
}
| 33.762238 | 137 | 0.611226 | AMReX-Combustion |
a18e39089c99edcc28a5c12c72135e8edc583164 | 15,293 | cc | C++ | src/json.cc | ZenLibraries/Zen2 | 21fc8583ea65ab178902fa4afc76d0cf01c11336 | [
"Apache-2.0"
] | null | null | null | src/json.cc | ZenLibraries/Zen2 | 21fc8583ea65ab178902fa4afc76d0cf01c11336 | [
"Apache-2.0"
] | 2 | 2021-07-12T08:39:46.000Z | 2021-07-12T08:43:54.000Z | src/json.cc | ZenLibraries/Zen2 | 21fc8583ea65ab178902fa4afc76d0cf01c11336 | [
"Apache-2.0"
] | null | null | null |
#include <cstdlib>
#include <memory>
#include <sstream>
#include <cmath>
#include <stack>
#include <variant>
#include "zen/char.hpp"
#include "zen/config.hpp"
#include "zen/transformer.hpp"
#include "zen/json.hpp"
#include "zen/stream.hpp"
#include "zen/either.hpp"
#include "zen/value.hpp"
ZEN_NAMESPACE_START
static void print_json_string(const string& str, std::ostream& out) {
out << '"';
for (auto ch: str) {
// FIXME This should be UTF-8-encoded
out << ch;
}
out << '"';
}
static void print_impl(const value &v, std::ostream& out, int indent) {
switch (v.get_type()) {
case value_type::array:
{
auto array = v.as_array();
if (array.empty()) {
out << "[]";
break;
}
out << "[\n";
auto curr = array.cbegin();
auto end = array.cend();
if (curr != end) {
auto new_indent = indent + 2;
out << std::string(indent + 2, ' ');
print_impl(*curr, out, new_indent);
curr++;
for (; curr != end; curr++) {
out << ",\n" << std::string(indent + 2, ' ');
print_impl(*curr, out, indent + 2);
}
}
out << "\n" << std::string(indent, ' ') << "]";
break;
}
case value_type::boolean:
out << (v.is_true() ? "true" : "false");
break;
case value_type::string:
print_json_string(v.as_string(), out);
break;
case value_type::null:
out << "null";
break;
case value_type::fractional:
out << v.as_fractional();
break;
case value_type::integer:
out << v.as_integer();
break;
case value_type::object:
{
auto object = v.as_object();
if (object.empty()) {
out << "{}";
break;
}
out << "{\n";
auto curr = object.cbegin();
auto end = object.cend();
if (curr != end) {
auto new_indent = indent + 2;
out << std::string(new_indent, ' ');
print_json_string(curr->first, out);
out << ": ";
print_impl(curr->second, out, new_indent);
curr++;
for (; curr != end; curr++) {
out << ",\n" << std::string(new_indent, ' ');
print_json_string(curr->first, out);
out << ": ";
print_impl(curr->second, out, new_indent);
}
}
out << "\n" << std::string(indent, ' ') << "}";
break;
}
}
}
void print(const value &v, std::ostream& out) {
print_impl(v, out, 0);
}
std::string to_string(const value& v) {
std::ostringstream ss;
print(v, ss);
return ss.str();
}
std::string escape_char(char ch) {
switch (ch) {
case '\"': return "\\\"";
case '\\': return "\\\\";
// case '/': return "\/";
case '\b': return "\\b";
case '\f': return "\\f";
case '\n': return "\\n";
case '\r': return "\\r";
case '\t': return "\\t";
default: return std::string { ch };
}
}
class json_encoder : public transformer {
std::stack<bool> levels;
std::string indentation;
std::ostream& out;
void write_indentation(int count) {
for (auto i = 0; i < count; ++i) {
out << indentation;
}
}
void write_string(const std::string& str) {
out << '"';
for (auto ch: str) {
out << escape_char(ch);
}
out << '"';
}
public:
json_encoder(std::ostream& out, std::string indentation):
indentation(indentation), out(out) {}
void transform(bool& v) override {
out << (v ? "true" : "false");
}
void transform(char& v) override {
out << '"' << escape_char(v) << '"';
}
void transform(short& v) override {
out << v;
}
void transform(int& v) override {
out << v;
}
void transform(long& v) override {
out << v;
}
void transform(long long& v) override {
out << v;
}
void transform(unsigned char& v) override {
out << v;
}
void transform(unsigned short& v) override {
out << v;
}
void transform(unsigned int& v) override {
out << v;
}
void transform(unsigned long& v) override {
out << v;
}
void transform(unsigned long long& v) override {
out << v;
}
void transform(float& v) override {
float integral;
if (std::modf(v, &integral) == 0) {
out << integral << ".0";
} else {
out << v << v;
}
}
void transform(double& v) override {
double integral;
if (std::modf(v, &integral) == 0) {
out << integral << ".0";
} else {
out << v << v;
}
}
void transform(std::string& v) override {
write_string(v);
}
void start_transform_object(const std::string& tag_name) override {
out << "{";
levels.push(true);
}
void end_transform_object() override {
levels.pop();
if (!indentation.empty()) {
out << "\n";
write_indentation(levels.size());
}
out << "}";
}
void start_transform_field(const std::string& name) override {
if (!levels.top()) {
out << ",";
} else {
levels.top() = false;
}
if (!indentation.empty()) {
out << "\n";
write_indentation(levels.size());
}
write_string(name);
out << ":";
if (!indentation.empty()) {
out << " ";
}
}
void end_transform_field() override {
}
void start_transform_element() override {
if (!levels.top()) {
out << ",";
} else {
levels.top() = false;
}
if (!indentation.empty()) {
out << "\n";
write_indentation(levels.size());
}
}
void end_transform_element() override {
// if (!indentation.empty()) {
// out << "\n";
// write_indentation(levels.size());
// }
}
void start_transform_optional() override {
}
void end_transform_optional() override {
}
void start_transform_sequence() override {
levels.push(true);
out << "[";
}
void end_transform_sequence() override {
levels.pop();
if (!indentation.empty()) {
out << "\n";
write_indentation(levels.size());
}
out << "]";
}
void transform_nil() override {
out << "null";
}
void transform_size(std::size_t size) override {
}
~json_encoder() {
}
};
std::unique_ptr<transformer> make_json_encoder(
std::ostream& out,
json_encode_opts opts
) {
return std::make_unique<json_encoder>(out, opts.indentation);
}
static bool is_json_whitespace(char ch) {
switch (ch) {
case ' ':
case '\n':
case '\r':
case '\t':
return true;
default:
return false;
}
}
static bool is_json_digit(char ch) {
switch (ch) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return true;
default:
return false;
}
}
json_parse_result parse_json(std::istream& in) {
value result;
std::optional<string> key;
std::stack<value> building;
for (;;) {
int c0;
#define ZEN_GET_NO_WHITESPACE(ch) \
for (;;) { \
ch = in.get(); \
if (!is_json_whitespace(ch)) { \
break; \
} \
}
#define ZEN_PEEK_NO_WHITESPACE(ch) \
for (;;) { \
ch = in.peek(); \
if (!is_json_whitespace(ch)) { \
break; \
} \
in.get(); \
}
#define ZEN_SCAN_DIGIT(name) \
unsigned char name; \
{ \
auto ch = in.get(); \
if (!is_json_digit(ch)) { \
return zen::left(json_parse_error::unexpected_character); \
} \
name = parse_decimal_digit(ch); \
}
#define ZEN_ASSERT_CHAR(ch, expected) \
{ \
auto temp = ch; \
if (temp != expected) { \
return left(json_parse_error::unexpected_character); \
} \
}
#define ZEN_EXPECT_CHAR(expected) \
ZEN_ASSERT_CHAR(in.get(), expected);
ZEN_GET_NO_WHITESPACE(c0);
switch (c0) {
case '{':
building.push(object {});
continue;
case ']':
case '}':
result = building.top();
building.pop();
break;
case '[':
building.push(array {});
continue;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
bigint x = parse_decimal_digit(c0);
for (;;) {
c0 = in.peek();
switch (c0) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
in.get();
x = x * 10 + parse_decimal_digit(c0);
continue;
case '.':
{
in.get();
fractional e = 1.0;
fractional y = 0.0;
fractional k = 1.0;
for (;;) {
auto c1 = in.peek();
switch (c1) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
in.get();
k /= 10.0;
y += k * parse_decimal_digit(c1);
continue;
case 'e':
case 'E':
{
in.get();
e = 0.0;
for (;;) {
auto c2 = in.peek();
switch (c2) {
case '+':
in.get();
break;
case '-':
in.get();
e *= -1;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
in.get();
e = e * 10.0 + parse_decimal_digit(c2);
break;
case EOF:
case ']':
case '}':
case ',':
case ' ':
case '\t':
case '\r':
case '\n':
goto finish_fractional;
default:
return left(json_parse_error::unexpected_character);
}
}
}
case EOF:
case ']':
case '}':
case ',':
case ' ':
case '\t':
case '\r':
case '\n':
goto finish_fractional;
default:
return left(json_parse_error::unexpected_character);
}
}
finish_fractional:
result = value(std::pow(x + y, e));
goto process_result;
}
case ']':
case '}':
case ',':
case ' ':
case '\t':
case '\r':
case '\n':
case EOF:
goto finish_integer;
default:
return left(json_parse_error::unexpected_character);
}
}
finish_integer:
result = value(x);
break;
}
case '"':
{
string chars;
for (;;) {
auto c1 = in.get();
switch (c1) {
case '"':
goto finish_string;
case '\n':
return left(json_parse_error::unexpected_character);
case '\\':
{
auto c2 = in.get();
switch (c2) {
case '"':
chars.push_back('"');
break;
case '\\':
chars.push_back('\\');
break;
case '/':
chars.push_back('/');
break;
case 'b':
chars.push_back('\b');
break;
case 'f':
chars.push_back('\f');
break;
case 'n':
chars.push_back('\n');
break;
case 'r':
chars.push_back('\r');
break;
case 't':
chars.push_back('\t');
break;
case 'u':
ZEN_SCAN_DIGIT(d0);
ZEN_SCAN_DIGIT(d1);
ZEN_SCAN_DIGIT(d2);
ZEN_SCAN_DIGIT(d3);
chars.push_back(d0 * 1000 + d1 * 100 + d2 * 10 + d3);
break;
default:
return left(json_parse_error::unrecognised_escape_sequence);
}
break;
}
default:
chars.push_back(c1);
break;
}
}
finish_string:
if (!building.empty() && building.top().is_object() && !key.has_value()) {
key = chars;
ZEN_GET_NO_WHITESPACE(c0)
ZEN_ASSERT_CHAR(c0, ':');
continue;
}
result = value(chars);
break;
}
case 'n':
ZEN_EXPECT_CHAR('u');
ZEN_EXPECT_CHAR('l');
ZEN_EXPECT_CHAR('l');
result = value(null {});
break;
case 't':
ZEN_EXPECT_CHAR('r');
ZEN_EXPECT_CHAR('u');
ZEN_EXPECT_CHAR('e');
result = value(true);
break;
case 'f':
ZEN_EXPECT_CHAR('a');
ZEN_EXPECT_CHAR('l');
ZEN_EXPECT_CHAR('s');
ZEN_EXPECT_CHAR('e');
result = value(false);
break;
default:
return left(json_parse_error::unexpected_character);
}
process_result:
if (building.empty()) {
break;
}
auto& top = building.top();
switch (top.get_type()) {
case value_type::object:
top.as_object().emplace(*key, result);
key = {};
break;
case value_type::array:
top.as_array().push_back(result);
break;
default:
ZEN_UNREACHABLE
}
ZEN_PEEK_NO_WHITESPACE(c0)
switch (c0) {
case '}':
case ']':
result = building.top();
building.pop();
goto process_result;
case ',':
in.get();
continue;
default:
return zen::left(json_parse_error::unexpected_character);
}
// We should never be able to get here, as the previous switch-statement
// should have modified the control-flow in all cases.
}
return right(result);
}
json_parse_result parse_json(const std::string& in) {
std::istringstream iss(in);
return parse_json(iss);
}
// std::unique_ptr<transformer> make_json_decoder(
// std::istream& in,
// json_decode_opts opts
// ) {
// return std::make_unique<json_decoder>(in);
// }
ZEN_NAMESPACE_END
| 21.240278 | 82 | 0.444648 | ZenLibraries |
a18f0051de50143d0501b546ff3faffdb8636117 | 774 | cpp | C++ | Cpp/Ch02_02/Ch02_02.cpp | VontineDev/repos | 0e98250a00d3deb0da4907898c3972222f14a5c8 | [
"MIT"
] | null | null | null | Cpp/Ch02_02/Ch02_02.cpp | VontineDev/repos | 0e98250a00d3deb0da4907898c3972222f14a5c8 | [
"MIT"
] | null | null | null | Cpp/Ch02_02/Ch02_02.cpp | VontineDev/repos | 0e98250a00d3deb0da4907898c3972222f14a5c8 | [
"MIT"
] | null | null | null | // Ch02_02.cpp : 이 파일에는 'main' 함수가 포함됩니다. 거기서 프로그램 실행이 시작되고 종료됩니다.
//
#include <iostream>
using namespace std;
//아래 두 함수는 호출하는 동안 어떤 함수가 호출되어야 할지 모호함이 발생한다.
void TestFunc(int a)
{
cout << "TestFunc(int)" << endl;
}
void TestFunc(int a, int b = 10)
{
cout << "TestFunc(int, int)" << endl;
}
int main()
{
cout << TestFunc(10) << endl;
}
// 프로그램 실행: <Ctrl+F5> 또는 [디버그] > [디버깅하지 않고 시작] 메뉴
// 프로그램 디버그: <F5> 키 또는 [디버그] > [디버깅 시작] 메뉴
// 시작을 위한 팁:
// 1. [솔루션 탐색기] 창을 사용하여 파일을 추가/관리합니다.
// 2. [팀 탐색기] 창을 사용하여 소스 제어에 연결합니다.
// 3. [출력] 창을 사용하여 빌드 출력 및 기타 메시지를 확인합니다.
// 4. [오류 목록] 창을 사용하여 오류를 봅니다.
// 5. [프로젝트] > [새 항목 추가]로 이동하여 새 코드 파일을 만들거나, [프로젝트] > [기존 항목 추가]로 이동하여 기존 코드 파일을 프로젝트에 추가합니다.
// 6. 나중에 이 프로젝트를 다시 열려면 [파일] > [열기] > [프로젝트]로 이동하고 .sln 파일을 선택합니다.
| 23.454545 | 96 | 0.583979 | VontineDev |
a18f1d85ec64ab514b5e8337f1c0c8816dfbd737 | 7,844 | cpp | C++ | elderly_care_simulation/src/test/TestCaregiverRobot.cpp | shaykalyan/SE306-ROS | 59f69d835646145f9dab711d170168a26ede347a | [
"MIT"
] | 6 | 2017-06-10T01:37:30.000Z | 2019-10-16T11:58:15.000Z | elderly_care_simulation/src/test/TestCaregiverRobot.cpp | shaykalyan/SE306-ROS | 59f69d835646145f9dab711d170168a26ede347a | [
"MIT"
] | null | null | null | elderly_care_simulation/src/test/TestCaregiverRobot.cpp | shaykalyan/SE306-ROS | 59f69d835646145f9dab711d170168a26ede347a | [
"MIT"
] | null | null | null | #include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
#include "math.h"
#include <vector>
#include "StaticPoiConstants.h"
#include "EventTriggerUtility.h"
#include "PerformTaskConstants.h"
#include "Caregiver.h"
#include "Robot.h"
#include "Poi.h"
#include "StaticPoi.h"
#include "EventNode.h"
#include "elderly_care_simulation/EventTrigger.h"
using namespace elderly_care_simulation;
#include <unistd.h>
#include "gtest/gtest.h"
// Publishers
ros::Publisher eventTriggerPub;
// Subscribers
ros::Subscriber eventTriggerSub;
// Service Clients
ros::ServiceClient performTaskClient;
// Store received messages
std::vector<EventTrigger> receivedEventTriggers;
Caregiver theCaregiver;
class CaregiverRobotTest : public ::testing::Test {
protected:
virtual void SetUp() {
receivedEventTriggers.clear();
theCaregiver.currentLocationState = Caregiver::AT_HOME;
}
};
/**
* Tests that the Caregiver responds correctly to Exercise events
*/
TEST_F(CaregiverRobotTest, caregiverRespondsToExerciseRequests) {
// Send relevant message to Caregiver
EventTrigger msg;
msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST;
msg.event_type = EVENT_TRIGGER_EVENT_TYPE_EXERCISE;
eventTriggerPub.publish(msg);
// Wait until message is received
ros::Rate loop_rate(10);
while (receivedEventTriggers.size() == 0) {
loop_rate.sleep();
ros::spinOnce();
}
ASSERT_EQ(Caregiver::GOING_TO_RESIDENT, theCaregiver.currentLocationState);
}
/**
* Tests that the Caregiver responds correctly to Shower events
*/
TEST_F(CaregiverRobotTest, caregiverRespondsToShowerRequests) {
// Send relevant message to Caregiver
EventTrigger msg;
msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST;
msg.event_type = EVENT_TRIGGER_EVENT_TYPE_SHOWER;
eventTriggerPub.publish(msg);
// Wait until message is received
ros::Rate loop_rate(10);
while (receivedEventTriggers.size() == 0) {
loop_rate.sleep();
ros::spinOnce();
}
ASSERT_EQ(Caregiver::GOING_TO_RESIDENT, theCaregiver.currentLocationState);
}
/**
* Tests that the Caregiver responds correctly to Conversation events
*/
TEST_F(CaregiverRobotTest, caregiverRespondsToConversationRequests) {
// Send relevant message to Caregiver
EventTrigger msg;
msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST;
msg.event_type = EVENT_TRIGGER_EVENT_TYPE_CONVERSATION;
eventTriggerPub.publish(msg);
// Wait until message is received
ros::Rate loop_rate(10);
while (receivedEventTriggers.size() == 0) {
loop_rate.sleep();
ros::spinOnce();
}
ASSERT_EQ(Caregiver::GOING_TO_RESIDENT, theCaregiver.currentLocationState);
}
// *
// * Tests that the Caregiver responds correctly to Moral Support events
TEST_F(CaregiverRobotTest, caregiverRespondsToMoralSupportRequests) {
// Send relevant message to Caregiver
EventTrigger msg;
msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST;
msg.event_type = EVENT_TRIGGER_EVENT_TYPE_MORAL_SUPPORT;
eventTriggerPub.publish(msg);
// Wait until message is received
ros::Rate loop_rate(10);
while (receivedEventTriggers.size() == 0) {
loop_rate.sleep();
ros::spinOnce();
}
ASSERT_EQ(Caregiver::GOING_TO_RESIDENT, theCaregiver.currentLocationState);
}
/**
* Tests that the Caregiver does not respond to non-caregiver events
*/
TEST_F(CaregiverRobotTest,caregiverDoesNotRespondToNonExerciseRequests) {
// Send irrelevant message to Caregiver
EventTrigger msg;
msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST;
msg.event_type = EVENT_TRIGGER_EVENT_TYPE_RELATIVE;
eventTriggerPub.publish(msg);
// Wait until message is received
ros::Rate loop_rate(10);
while (receivedEventTriggers.size() == 0) {
loop_rate.sleep();
ros::spinOnce();
}
ASSERT_EQ(Caregiver::AT_HOME, theCaregiver.currentLocationState);
}
/**
*Tests that the Caregiver get the right reply for CONVERSATION event
**/
TEST_F(CaregiverRobotTest, caregiverSendsCorrectConversationEventReply) {
theCaregiver.MY_TASK = EVENT_TRIGGER_EVENT_TYPE_CONVERSATION;
theCaregiver.eventTriggerReply();
// Wait until message is received
ros::Rate loop_rate(10);
while (receivedEventTriggers.size() == 0) {
loop_rate.sleep();
ros::spinOnce();
}
elderly_care_simulation::EventTrigger msg = receivedEventTriggers[0];
ASSERT_EQ(EVENT_TRIGGER_MSG_TYPE_RESPONSE, msg.msg_type);
ASSERT_EQ(EVENT_TRIGGER_EVENT_TYPE_CONVERSATION, msg.event_type);
ASSERT_EQ(EVENT_TRIGGER_RESULT_SUCCESS, msg.result);
}
/**
*Tests that the Caregiver get the right reply for SHOWER event
**/
TEST_F(CaregiverRobotTest, caregiverSendsCorrectShowerEventReply) {
theCaregiver.MY_TASK = EVENT_TRIGGER_EVENT_TYPE_SHOWER;
theCaregiver.eventTriggerReply();
// Wait until message is received
ros::Rate loop_rate(10);
while (receivedEventTriggers.size() == 0) {
loop_rate.sleep();
ros::spinOnce();
}
elderly_care_simulation::EventTrigger msg = receivedEventTriggers[0];
ASSERT_EQ(EVENT_TRIGGER_MSG_TYPE_RESPONSE, msg.msg_type);
ASSERT_EQ(EVENT_TRIGGER_EVENT_TYPE_SHOWER, msg.event_type);
ASSERT_EQ(EVENT_TRIGGER_RESULT_SUCCESS, msg.result);
}
/**
*Tests that the Caregiver get the right reply for EXERCISE event
**/
TEST_F(CaregiverRobotTest, caregiverSendsCorrecMoralSupportEventReply) {
theCaregiver.MY_TASK = EVENT_TRIGGER_EVENT_TYPE_MORAL_SUPPORT;
theCaregiver.eventTriggerReply();
// Wait until message is received
ros::Rate loop_rate(10);
while (receivedEventTriggers.size() == 0) {
loop_rate.sleep();
ros::spinOnce();
}
elderly_care_simulation::EventTrigger msg = receivedEventTriggers[0];
ASSERT_EQ(EVENT_TRIGGER_MSG_TYPE_RESPONSE, msg.msg_type);
ASSERT_EQ(EVENT_TRIGGER_EVENT_TYPE_MORAL_SUPPORT, msg.event_type);
ASSERT_EQ(EVENT_TRIGGER_RESULT_SUCCESS, msg.result);
}
/**
*Tests that the Caregiver get the right reply for EXERCISE event
**/
TEST_F(CaregiverRobotTest, caregiverSendsCorrectExerciseEventReply) {
theCaregiver.MY_TASK = EVENT_TRIGGER_EVENT_TYPE_EXERCISE;
theCaregiver.eventTriggerReply();
// Wait until message is received
ros::Rate loop_rate(10);
while (receivedEventTriggers.size() == 0) {
loop_rate.sleep();
ros::spinOnce();
}
elderly_care_simulation::EventTrigger msg = receivedEventTriggers[0];
ASSERT_EQ(EVENT_TRIGGER_MSG_TYPE_RESPONSE, msg.msg_type);
ASSERT_EQ(EVENT_TRIGGER_EVENT_TYPE_EXERCISE, msg.event_type);
ASSERT_EQ(EVENT_TRIGGER_RESULT_SUCCESS, msg.result);
}
// Used to wait for msg is received
void eventTriggerCallback(elderly_care_simulation::EventTrigger msg) {
receivedEventTriggers.push_back(msg);
}
// Function wrapper for method
void caregiverEventTriggerCallback(elderly_care_simulation::EventTrigger msg) {
theCaregiver.eventTriggerCallback(msg);
}
int main(int argc, char** argv) {
ros::init(argc, argv, "TestCaregiverRobot");
ros::NodeHandle nodeHandle;
ros::Rate loop_rate(10);
eventTriggerPub = nodeHandle.advertise<elderly_care_simulation::EventTrigger>("event_trigger",1000, true);
eventTriggerSub = nodeHandle.subscribe<elderly_care_simulation::EventTrigger>("event_trigger",1000, eventTriggerCallback);
theCaregiver.eventTriggerPub = nodeHandle.advertise<elderly_care_simulation::EventTrigger>("event_trigger",1000, true);
theCaregiver.eventTriggerSub = nodeHandle.subscribe<elderly_care_simulation::EventTrigger>("event_trigger",1000, caregiverEventTriggerCallback);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 28.31769 | 148 | 0.735849 | shaykalyan |
0846d156d6862bb938a0e8132e5b96ad0a6b2d32 | 9,605 | cpp | C++ | src/cx-tracedebug.cpp | ryanvbissell/cx | 5291d5cb8e622920628343088eaec9996a3b1d44 | [
"BSD-2-Clause"
] | null | null | null | src/cx-tracedebug.cpp | ryanvbissell/cx | 5291d5cb8e622920628343088eaec9996a3b1d44 | [
"BSD-2-Clause"
] | null | null | null | src/cx-tracedebug.cpp | ryanvbissell/cx | 5291d5cb8e622920628343088eaec9996a3b1d44 | [
"BSD-2-Clause"
] | null | null | null | // vim: set tabstop=2 softtabstop=2 shiftwidth=2 expandtab :
/*
* Copyright (c) 1999-2002,2013-2016, Ryan V. Bissell
* All rights reserved.
*
* SPDX-License-Identifier: BSD-2-Clause
* See the enclosed "LICENSE" file for exact license terms.
*/
#include "cx-hackery.hpp"
#define CX_TESTING
#include "cx-tracedebug.hpp"
#include <errno.h>
#include <cstdlib>
#include <cstdarg>
// changing this to a static and wrapping it with get()/set()
// because g++ 4.8.4 didn't seem to be extern'ing the original form
// properly, causing there to be multiple copies in different
// compilation units (leading, ultimately, to a segfault)
static bool g_initialized = false;
static bool g_enabled = true;
static FILE *g_debugfile = nullptr;
static FILE *g_errorfile = nullptr;
static char const *g_topicenv = nullptr;
static char const *g_traceenv = nullptr;
static char const *g_tracefile = nullptr;
#ifdef CX_OPT_TRACING
static U64 g_tracelevel = 0;
static char g_tracetab[256] = "";
#endif
// this has to be defined even when CX_OPT_TRACING is undefined,
// because even then it is still referenced by cx-exceptions
char const *cx_trace_methodname="{{{ unknown method/function }}}";
#ifdef CX_TESTING
char const *
CX::get_topicenv()
{
return g_topicenv;
}
char const *
CX::get_traceenv()
{
return g_traceenv;
}
char const *
CX::get_tracefile()
{
return g_tracefile;
}
#endif
static void
_init_tracefile()
{
if (!g_debugfile)
{
g_tracefile = std::getenv("CX_TRACEFILE");
if (!g_tracefile)
{
// defaults
CX::set_debugfile(stdout);
CX::set_errorfile(stderr);
}
else
{
FILE* file;
errno = 0;
if (!(file = fopen(g_tracefile, "w")))
{
fprintf(stderr, "Unable to open CX_TRACEFILE '%s'\n", g_tracefile);
perror("fopen(3) reports");
fprintf(stderr, "All CX-related debug output is disabled.\n");
g_enabled = false;
}
CX::set_debugfile(file);
CX::set_errorfile(file);
}
}
g_initialized = true;
}
bool
CX::is_enabled()
{
if (!g_initialized)
_init_tracefile();
return g_enabled;
}
void CX::flush()
{
if (g_debugfile) ::fflush(g_debugfile);
if (g_errorfile) ::fflush(g_errorfile);
}
void
CX::set_debugfile(FILE* file)
{
if (g_debugfile) ::fflush(g_debugfile);
if (g_errorfile) ::fflush(g_errorfile);
g_debugfile = file;
}
void
CX::set_errorfile(FILE* file)
{
if (g_debugfile) ::fflush(g_debugfile);
if (g_errorfile) ::fflush(g_errorfile);
g_errorfile = file;
}
static const char *
_init_env_string(const char* name)
{
char* envstr;
if (envstr = std::getenv(name))
envstr = strdup(envstr);
else
envstr = strdup("");
return envstr;
}
static int
_trace_vfprintf_1(bool trace,
FILE* file, char const* format, va_list args)
{
#ifdef CX_OPT_TRACING
if (trace)
fprintf(file, "%s", g_tracetab);
#endif
// TODO: what if the string to be output is multi-lined?
// Maybe we should detect that and insert indentations, somehow...
return ::vfprintf(file, format, args);
}
static int
_trace_vfprintf(bool trace,
FILE* file, char const* format, va_list args)
{
if (file && CX::is_enabled())
return _trace_vfprintf_1(trace, file, format, args);
return 0;
}
static int
_trace_fprintf(bool trace, FILE* file, char const* format, ...)
{
if (file && CX::is_enabled())
{
int ret;
va_list args;
va_start(args, format);
/* TODO: doesn't work with PRIu64, etc? */
ret = _trace_vfprintf_1(trace, file, format, args);
va_end(args);
return ret;
}
return 0;
}
#ifdef CX_OPT_TRACING
static void
_update_trace_tab()
{
U64 i;
// The point is to allow more than 64 levels of trace
// (for robustness,) but to only tab-in for the first
// 64 trace levels (a practical limitation.)
for (i = 0; i < (CX_MIN((U64)g_tracelevel, 64UL)*3); ++i)
g_tracetab[i] = ' ';
g_tracetab[CX_MIN((U64)g_tracelevel, 64UL)*1] = '\x0';
}
U64 CX::get_tracelevel()
{
return g_tracelevel;
}
void CX::set_tracelevel(U64 level)
{
g_tracelevel = level;
_update_trace_tab();
}
void
CX::shift_in()
{
g_tracelevel++;
_update_trace_tab();
}
void
CX::shift_out()
{
if (g_tracelevel)
{
g_tracelevel -= !!g_tracelevel;
g_tracetab[CX_MAX(0, ((long)g_tracelevel))*1] = '\x0';
}
}
bool
CX::is_section_active(const char* section)
{
if (!CX::is_enabled())
return false;
if (!g_traceenv)
g_traceenv = _init_env_string("CX_TRACE");
if (!g_traceenv || !*g_traceenv)
return false; // empty is treated the same as undefined
// TODO: better globbing support
if (strstr(g_traceenv, "*"))
return true; // asterisk in CX_TRACE means "show all trace sections"
// section names present in CX_TRACE are the only ones traced.
const char* found = strstr(g_traceenv, section);
if (!found)
return false;
// filter out partial matches
size_t len = strlen(section);
bool begin = (found == g_traceenv) || (found[-1] == ' ');
bool end = (strlen(found) == len) || (found[len] == ' ');
return (begin && end);
}
void
CX::traceout(char const* section, char const* format, ...)
{
if (!CX::is_enabled())
return;
if (!CX::is_section_active(section))
return;
va_list args;
va_start(args, format);
_trace_vfprintf_1(true, g_debugfile, format, args);
va_end(args);
}
#endif
static const char *
_my_strchrnul(const char* s, int c)
{
if (!s) return nullptr;
while (*s && (*s != c))
++s;
return s;
}
static size_t
_get_next_word(const char** start, size_t len, char* word)
{
while (*start && **start == ' ')
++*start; // skip past leading delims
const char* end = _my_strchrnul(*start, ' ');
len = CX_MIN(len-1, end - *start);
strncpy(word, *start, len);
word[len] = '\0';
*start = *end ? end+1 : nullptr;
return len;
}
static bool
_is_topic_active(const char* topic)
{
if (!g_topicenv)
g_topicenv = _init_env_string("CX_TOPICS");
if (!g_topicenv || !*g_topicenv)
return false;
//g_topicenv "foo:bar" should only match exact topic "foo:bar"
//g_topicenv "foo:" should match any topic beginning with "foo:"
//g_topicenv ":bar" should match any topic ending with ":bar"
//g_topicenv "*" should match any topic [special]
//g_topicenv "foo:bar*" should ONLY match the literal "foo:bar*"
const char* start = g_topicenv;
char word[64];
const char* found;
do
{
size_t len = _get_next_word(&start, sizeof(word), word);
if (len)
{
if ((len ==1) && (*word == '*') && topic && *topic)
return true;
if (found = strstr(/*haystack*/topic, /*needle*/word))
{
// if word didn't match @ the beginning of topic,
// then word needs to start with a colon.
if (found != topic)
return (*word == ':');
// if word didn't match all the way to the end of topic,
// then word needs to end with a colon
if (strlen(found) > len)
return (word[len-1] == ':');
return true;
}
}
} while (start);
return false;
}
void
CX::debugout(char const* format, ...)
{
if (!CX::is_enabled())
return;
int ret;
va_list args;
va_start(args, format);
_trace_vfprintf_1(true, g_debugfile, format, args);
va_end(args);
}
void
CX::warning(bool test, char const* format, ...)
{
if (!test)
return;
if (!CX::is_enabled())
return;
_trace_fprintf(true, g_errorfile, "??? ");
va_list args;
va_start(args, format);
_trace_vfprintf_1(false, g_errorfile, format, args);
va_end(args);
}
void
CX::topicout(char const* topic, char const* format, ...)
{
if (!CX::is_enabled())
return;
if (!_is_topic_active(topic))
return;
_trace_fprintf(true, g_debugfile, "[%s] ", topic);
va_list args;
va_start(args, format);
_trace_vfprintf_1(false, g_debugfile, format, args);
va_end(args);
// TODO: need compile- or runtime-test to enable this flush
// (don't want it always enabled for perf reasons)
#if 0
::fflush(g_debugfile);
#endif
}
void
CX::errorout(bool test, char const* format, ...)
{
if (!test)
return;
va_list args;
va_start(args, format);
if (!CX::is_enabled())
{
// CX output is disabled-- usually because an invalid filename
// was given for $CX_TRACEFILE-- but this is an error message,
// and hence likely important. So, try sending it to stderr
::vfprintf(stderr, format, args);
::fflush(stderr);
}
else
{
// flushing can preserve correct order of output when
// g_debugfile and g_errorfile are not the same streams.
bool same = (g_debugfile == g_errorfile);
if (!same) ::fflush(g_debugfile);
/////_trace_fprintf(true, g_errorfile, "!!! ");
_trace_vfprintf(false, g_errorfile, format, args);
if (!same) ::fflush(g_errorfile);
}
va_end(args);
}
char const* g_assert_messages[] =
{
"DEUS EX MACHINA: a tragedy has occurred, and \n"
" higher powers have been summoned.",
"THUS SPAKE ZARATHUSTRA:\n"
" 'You must be ready to burn yourself in your own flame; \n"
" how could you rise anew if you have not first become ashes?'",
"OZYMANDIAS: 'Look upon my Works, ye Mighty, and despair!'",
"#INCLUDE <HUBRIS> // this code was too clever by half",
"ASSERTION HAIKU: Something you entered\n"
" transcended parameters;\n"
" program aborted.",
};
char const*
CX::get_assert_message()
{
srand(time(nullptr));
int msg = rand() % (sizeof(g_assert_messages) / sizeof(char const*));
return g_assert_messages[msg];
}
| 20.263713 | 75 | 0.643727 | ryanvbissell |
084b1050c930873f3ce059bdf43b5051b928dec4 | 3,399 | cpp | C++ | src/sapi/sapi_limiter.cpp | trappist/Core-Smart | a87b46c911e7e8bddccecd6c3c930d9086759eb7 | [
"MIT"
] | null | null | null | src/sapi/sapi_limiter.cpp | trappist/Core-Smart | a87b46c911e7e8bddccecd6c3c930d9086759eb7 | [
"MIT"
] | null | null | null | src/sapi/sapi_limiter.cpp | trappist/Core-Smart | a87b46c911e7e8bddccecd6c3c930d9086759eb7 | [
"MIT"
] | 1 | 2020-12-15T21:39:45.000Z | 2020-12-15T21:39:45.000Z | // Copyright (c) 2017 - 2018 - The SmartCash Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sapi/sapi.h"
#include "netbase.h"
#include "util.h"
CCriticalSection cs_clients;
static std::map<std::string, SAPI::Limits::Client*> mapClients;
static std::vector<int> vecThrottling = {
10,60,600,3600
};
SAPI::Limits::Client *SAPI::Limits::GetClient(const CService &peer)
{
SAPI::Limits::Client *client;
std::string strIp = peer.ToStringIP(false);
LOCK(cs_clients);
auto it = mapClients.find(strIp);
if( it == mapClients.end() ){
client = new SAPI::Limits::Client();
mapClients.insert(std::make_pair(strIp, client));
}else{
client = it->second;
}
return client;
}
void SAPI::Limits::CheckAndRemove()
{
LOCK(cs_clients);
LogPrintf("SAPI::Limits::CheckAndRemove() - Clients %d\n", mapClients.size());
auto it = mapClients.begin();
while( it != mapClients.end() ){
if( it->second->CheckAndRemove() ){
LogPrintf("SAPI::Limits::CheckAndRemove() - Remove %s\n", it->first);
delete it->second;
it = mapClients.erase(it);
}else{
++it;
}
}
}
void SAPI::Limits::Client::Request()
{
LOCK(cs);
int64_t nTime = GetTimeMillis();
int64_t nTimePassed = nTime - nLastRequestTime;
IsRequestLimited();
nRemainingRequests += (static_cast<double>(nTimePassed * nRequestsPerInterval) / nRequestIntervalMs) - 1.0;
if( nRemainingRequests > nRequestsPerInterval )
nRemainingRequests = nRequestsPerInterval;
LogPrintf("nRemaining before: %f\n", nRemainingRequests);
if(nRemainingRequests <= 0){
if( nThrottling < static_cast<int64_t>(vecThrottling.size() - 1) )
++nThrottling;
int64_t nThrottlingTime = vecThrottling.at(nThrottling);
nRequestsLimitUnlock = nTime + nThrottlingTime * 1000;
nRemainingRequests = nRequestIntervalMs;
}
LogPrintf("nRemaining after: %f, throttling %d\n", nRemainingRequests, nThrottling);
nLastRequestTime = nTime;
}
bool SAPI::Limits::Client::IsRequestLimited()
{
LOCK(cs);
if( nRequestsLimitUnlock < 0 )
return false;
int64_t nTime = GetTimeMillis();
if( nTime > nRequestsLimitUnlock ){
nRequestsLimitUnlock = -1;
nThrottling = -1;
return false;
}
LogPrintf("Request limited: %.2fms\n", nRequestsLimitUnlock - nTime);
return true;
}
bool SAPI::Limits::Client::IsRessourceLimited()
{
return false;
}
bool SAPI::Limits::Client::IsLimited()
{
return IsRequestLimited() || IsRessourceLimited();
}
int64_t SAPI::Limits::Client::GetRequestLockSeconds()
{
if( nRequestsLimitUnlock < 0)
return 0;
return (nRequestsLimitUnlock - GetTimeMillis()) / 1000;
}
int64_t SAPI::Limits::Client::GetRessourceLockSeconds()
{
if( nRessourcesLimitUnlock < 0)
return 0;
return (nRessourcesLimitUnlock - GetTimeMillis()) / 1000;
}
bool SAPI::Limits::Client::CheckAndRemove()
{
// If the client is not limited and was not active for nClientRemovalMs
// we want to remove it from the list.
if( !IsLimited() && ( GetTimeMillis() - nLastRequestTime ) > nClientRemovalMs )
return true;
return false;
}
| 23.769231 | 111 | 0.653133 | trappist |
084f209f97e10e82c254d17d4f954f87d92f630d | 410 | hpp | C++ | include/asllvm/detail/debuginfo.hpp | AsuMagic/angelscript-llvm | 272a7137306473669be1ce80fcbb51a72d87e023 | [
"MIT"
] | 9 | 2020-04-30T09:28:46.000Z | 2022-01-09T14:07:25.000Z | include/asllvm/detail/debuginfo.hpp | AsuMagic/asllvm | 272a7137306473669be1ce80fcbb51a72d87e023 | [
"MIT"
] | 16 | 2020-04-23T12:50:43.000Z | 2020-04-23T12:51:36.000Z | include/asllvm/detail/debuginfo.hpp | AsuMagic/asllvm | 272a7137306473669be1ce80fcbb51a72d87e023 | [
"MIT"
] | null | null | null | #pragma once
#include <asllvm/detail/functioncontext.hpp>
#include <llvm/IR/DebugInfoMetadata.h>
namespace asllvm::detail
{
struct SourceLocation
{
int line, column;
};
SourceLocation get_source_location(FunctionContext context, std::size_t bytecode_offset = 0);
llvm::DebugLoc get_debug_location(FunctionContext context, std::size_t bytecode_offset, llvm::DISubprogram* sp);
} // namespace asllvm::detail
| 25.625 | 112 | 0.797561 | AsuMagic |
084ffa5227640830821510e04367fdaeedd5fe5d | 238 | cpp | C++ | codeforces/52a.123-sequence/52a.cpp | KayvanMazaheri/acm | aeb05074bc9b9c92f35b6a741183da09a08af85d | [
"MIT"
] | 3 | 2018-01-19T14:09:23.000Z | 2018-02-01T00:40:55.000Z | codeforces/52a.123-sequence/52a.cpp | KayvanMazaheri/acm | aeb05074bc9b9c92f35b6a741183da09a08af85d | [
"MIT"
] | null | null | null | codeforces/52a.123-sequence/52a.cpp | KayvanMazaheri/acm | aeb05074bc9b9c92f35b6a741183da09a08af85d | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
using namespace std;
int arr[4];
int main()
{
int n;
cin >> n;
int inp;
for(int i=0; i<n; i++)
{
cin >> inp;
arr[inp] ++;
}
cout << n - *max_element(arr, arr+4) << endl;
return 0;
}
| 11.333333 | 46 | 0.558824 | KayvanMazaheri |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.