hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c99c80a3f6ccc516e2d1cdb8c0a8ce5c393e8d37 | 8,054 | hpp | C++ | src/truth_table.hpp | loic-broyer/BDD | 1d3269050f60c57a90446fa627cea56ab2b41d34 | [
"MIT"
] | null | null | null | src/truth_table.hpp | loic-broyer/BDD | 1d3269050f60c57a90446fa627cea56ab2b41d34 | [
"MIT"
] | null | null | null | src/truth_table.hpp | loic-broyer/BDD | 1d3269050f60c57a90446fa627cea56ab2b41d34 | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <cassert>
#include <vector>
#include <string>
/* helper function for power calculation */
inline int power(int val, int pow){ //OK
if(pow == 0) return 1;
int ret = val;
for(int i=0; i<pow-1;i++) ret *= val;
return ret;
}
/* masks used to filter out unused bits */
inline uint64_t length_mask(uint32_t num_var){ //OK
assert(num_var <= 6);
uint64_t mask = 1;
while(num_var>=1){
for(int i=0; i<power(2, num_var-1); i++){
mask = mask << 1;
mask |= 0x1;
}
num_var--;
}
return mask;
}
/* return i if n == 2^i, 0 otherwise */
inline uint32_t power_two( const uint32_t n ) //OK
{
if(n == 0) return 0;
uint32_t div = n;
uint32_t i = 0;
while(div!=1){
if(div%2 != 0) return 0;
div /= 2;
i++;
}
return i;
}
class Truth_Table
{
public:
Truth_Table( uint32_t num_var ) //OK
: num_var( num_var ), bits( (num_var <6) ? 1u : (1u << (num_var - 6)) )
{
}
Truth_Table( uint32_t num_var, std::vector<uint64_t> _bits ) //OK
: num_var( num_var ), bits( _bits )
{
size_t blocks = (num_var <6) ? 1u : (1u << (num_var - 6));
bits.resize(blocks);
if(num_var < 6) bits[0u] &= length_mask(num_var);
}
Truth_Table( const std::string str ) //OK //WARNING strings have to be of length power 2
: num_var( power_two( str.size() ) ), bits( (power_two( str.size() ) < 6) ? 1u : (1u << (power_two( str.size() ) - 6)) )
{
if ( num_var == 0u )
{
return;
}
for ( auto i = 0u; i < str.size(); ++i )
{
if ( str[i] == '1' )
{
set_bit( str.size() - 1 - i );
}
else
{
assert( str[i] == '0' );
}
}
}
bool get_bit( uint32_t const position ) const //OK
{
assert( position < ( 1 << num_var ) );
uint32_t block = position/64; //Compute the relevant block index
uint32_t block_position = position % 64; //Compute new position in block
return ( ( bits[block] >> block_position ) & 0x1 );
}
void set_bit( uint32_t const position ) //OK
{
assert( position < ( 1 << num_var ) );
uint32_t block = position/64; //Compute the relevant block index
uint32_t block_position = position % 64; //Compute new position in block
bits[block] |= ( uint64_t( 1 ) << block_position );
if(num_var < 6) bits[0u] &= length_mask(num_var);
}
uint32_t n_var() const //OK
{
return num_var;
}
Truth_Table positive_cofactor( uint32_t const var ) const;
Truth_Table negative_cofactor( uint32_t const var ) const;
Truth_Table derivative( uint32_t const var ) const;
Truth_Table consensus( uint32_t const var ) const;
Truth_Table smoothing( uint32_t const var ) const;
public:
uint32_t const num_var; /* number of variables involved in the function */
std::vector<uint64_t> bits; /* the truth table */
};
/* overload std::ostream operator for convenient printing */
inline std::ostream& operator<<( std::ostream& os, Truth_Table const& tt ) //OK
{
for ( auto i = ( 1 << tt.num_var ) - 1; i >= 0; --i )
{
os << ( tt.get_bit( i ) ? '1' : '0' );
}
return os;
}
inline Truth_Table operator<<(Truth_Table const& tt1, int shift){ //OK
std::vector<uint64_t> vec (tt1.bits);
uint64_t save_next;
uint64_t save = 0x0;
for(auto i=0; i<tt1.bits.size(); i++){
save_next = vec[i];
vec[i] = vec[i] << shift;
vec[i] |= (save >> (64-shift));
save = save_next;
}
return Truth_Table(tt1.num_var, vec);
}
inline Truth_Table operator>>(Truth_Table const& tt1, int shift){ //OK
std::vector<uint64_t> vec (tt1.bits);
uint64_t save_next;
uint64_t save = 0x0;
for(auto i=tt1.bits.size()-1; i>=0; i--){
save_next = vec[i];
vec[i] = vec[i] >> shift;
vec[i] |= (save << (64-shift));
save = save_next;
}
return Truth_Table(tt1.num_var, vec);
}
/* bit-wise NOT operation */
inline Truth_Table operator~( Truth_Table const& tt ) //OK
{
std::vector<uint64_t> inv_bits (tt.bits);
for(auto i=0; i<inv_bits.size(); i++) inv_bits[i] = ~inv_bits[i];
return Truth_Table( tt.num_var, inv_bits );
}
/* bit-wise OR operation */
inline Truth_Table operator|( Truth_Table const& tt1, Truth_Table const& tt2 ) //OK
{
assert( tt1.num_var == tt2.num_var );
std::vector<uint64_t> or_bits (tt1.bits);
for(auto i=0; i<or_bits.size(); i++) or_bits[i] |= tt2.bits[i];
return Truth_Table( tt1.num_var, or_bits );
}
/* bit-wise AND operation */
inline Truth_Table operator&( Truth_Table const& tt1, Truth_Table const& tt2 ) //OK
{
assert( tt1.num_var == tt2.num_var );
std::vector<uint64_t> and_bits (tt1.bits);
for(auto i=0; i<and_bits.size(); i++) and_bits[i] &= tt2.bits[i];
return Truth_Table( tt1.num_var, and_bits );
}
/* bit-wise XOR operation */
inline Truth_Table operator^( Truth_Table const& tt1, Truth_Table const& tt2 ) //OK
{
assert( tt1.num_var == tt2.num_var );
std::vector<uint64_t> xor_bits (tt1.bits);
for(auto i=0; i<xor_bits.size(); i++) xor_bits[i] = xor_bits[i]^tt2.bits[i];
return Truth_Table( tt1.num_var, xor_bits);
}
/* check if two truth_tables are the same */
inline bool operator==( Truth_Table const& tt1, Truth_Table const& tt2 ) //OK
{
if ( tt1.num_var != tt2.num_var )
{
return false;
}
bool ret = true;
for(auto i=0; i<tt1.bits.size(); i++) ret &= (tt1.bits[i] == tt2.bits[i]);
return ret;
}
inline bool operator!=( Truth_Table const& tt1, Truth_Table const& tt2 ) //OK
{
return !( tt1 == tt2 );
}
/* masks used to get the bits where a certain variable is 1 */
inline Truth_Table var_mask_pos(uint32_t num_var, uint32_t var){ //OK
assert(var < num_var);
Truth_Table tt = Truth_Table(num_var);
if(var < 6){
int batch_size = power(2, var);
for(auto i=0; i<tt.bits.size(); i++){ //Block iteration
for(auto j=0; j<64; j++){ //Bit iteration
tt.bits[i] = tt.bits[i] >> 1;
tt.bits[i] |= (((j / batch_size) % 2) == 0) ? 0x0 : 0x8000000000000000;
}
}
}else{
int batch_size = power(2, var-6);
for(auto i=0; i<tt.bits.size(); i++){ //Block iteration
tt.bits[i] = (((i / batch_size) % 2) == 0) ? 0x0 : 0xffffffffffffffff;
}
}
return tt;
}
/* masks used to get the bits where a certain variable is 0 */
inline Truth_Table var_mask_neg(uint32_t num_var, uint32_t var){ //OK
assert(var < num_var);
Truth_Table tt = Truth_Table(num_var);
if(var < 6){
int batch_size = power(2, var);
for(auto i=0; i<tt.bits.size(); i++){ //Block iteration
for(auto j=0; j<64; j++){ //Bit iteration
tt.bits[i] = tt.bits[i] >> 1;
tt.bits[i] |= (((j / batch_size) % 2) == 0) ? 0x8000000000000000 : 0x0;
}
}
}else{
int batch_size = power(2, var-6);
for(auto i=0; i<tt.bits.size(); i++){ //Block iteration
tt.bits[i] = (((i / batch_size) % 2) == 0) ? 0xffffffffffffffff : 0x0;
}
}
return tt;
}
inline Truth_Table Truth_Table::positive_cofactor( uint32_t const var ) const
{
assert( var < num_var );
Truth_Table pos = var_mask_pos(num_var, var);
return (*this & pos) | ((*this & pos) >> (1 << var));
}
inline Truth_Table Truth_Table::negative_cofactor( uint32_t const var ) const
{
assert( var < num_var );
Truth_Table neg = var_mask_neg(num_var, var);
return (*this & neg) | ((*this & neg) << (1 << var));
}
inline Truth_Table Truth_Table::derivative( uint32_t const var ) const
{
assert( var < num_var );
return positive_cofactor( var ) ^ negative_cofactor( var );
}
inline Truth_Table Truth_Table::consensus( uint32_t const var ) const
{
assert( var < num_var );
return positive_cofactor( var ) & negative_cofactor( var );
}
inline Truth_Table Truth_Table::smoothing( uint32_t const var ) const
{
assert( var < num_var );
return positive_cofactor( var ) | negative_cofactor( var );
}
/* Returns the truth table of f(x_0, ..., x_num_var) = x_var (or its complement). */
inline Truth_Table create_tt_nth_var( uint32_t const num_var, uint32_t const var, bool const polarity = true )
{
assert ( var < num_var );
return Truth_Table( num_var, polarity ? var_mask_pos(num_var, var).bits : var_mask_neg(num_var, var).bits );
}
| 28.160839 | 123 | 0.629625 | [
"vector"
] |
c99e99dece676f68fa879eb04d4e0e8f969fa479 | 10,180 | cpp | C++ | src/subsume.cpp | Incudine/sat2021 | f56041f50eba1bb89434865f728eaba592ab1f0b | [
"MIT"
] | null | null | null | src/subsume.cpp | Incudine/sat2021 | f56041f50eba1bb89434865f728eaba592ab1f0b | [
"MIT"
] | null | null | null | src/subsume.cpp | Incudine/sat2021 | f56041f50eba1bb89434865f728eaba592ab1f0b | [
"MIT"
] | null | null | null | /*-------------------------------------------------------------------------+
| Copyright (c) 2020, Henrik Cao, henrik.cao@aalto.fi, Espoo, Finland. |
| |
| Permission is hereby granted, free of charge, to any person obtaining a |
| copy of this software and associated documentation files, 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 MERCHANTABI- |
| LITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT |
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BELIABLE 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 "solver.h"
namespace sat {
/*-------------------------------------------------------------------------+
| Our forward subsumption algorithm is based on the one-watcher literal |
| scheme by Zhang (see "On subsumption removal and on-the-fly CNF simpli- |
| fication", 2005) and the cardinality based sorting suggested by Bayardo |
| (see ("Fast algorithms for finding extremal sets", 2011). |
/*-------------------------------------------------------------------------*/
bool CDCL::subsume_forward ( ) {
assert (candsizes.empty ( ));
const bool hash = modes.hash;
/* Start counter */
stats.preprocess_start = std::chrono::high_resolution_clock::now ( );
/* Schedule (sorted) candidates for subsumption */
subsume_candidates ( );
if (hash) init_occrs_hash ( );
else init_occrs ( );
/* Check candidates in increasing order of size */
int candsmarked = 0;
for (std::pair<Clause*,size_t>& cs : candsizes) {
Clause* c = cs.first;
/* Find the smallest occurrence list to watch 'c' */
if (hash) {
if (cs.second > 2) subsume_check_hash (c);
const int lit = subsume_min_occrs_hash (c);
occhash (lit).push_back (OccrsHash (c, c->hash, c->unique));
} else {
if (cs.second > 2) subsume_check (c);
const int lit = subsume_min_occrs (c);
occurs (lit).push_back (c);
}
}
return true;
}
/*-------------------------------------------------------------------------+
| Collect candidates clauses for subsumption and sort. |
/*-------------------------------------------------------------------------*/
void CDCL::subsume_candidates ( ) {
/* Collect candidate clauses and count literal occurrences.
We exclude clauses that are too large; root satisfied. */
subsume_find_candidates (original);
/* Sort candidates by cardinality */
std::sort (candsizes.begin ( ), candsizes.end ( ), Sort_cls_size_subsume ( ));
}
/*-------------------------------------------------------------------------+
| Collect candidates clauses for subsumption from 'clauses'. |
/*-------------------------------------------------------------------------*/
void CDCL::subsume_find_candidates (std::vector<Clause*>& clauses) {
for (Clause* c : clauses)
if (c->size ( ) <= lims.subsume_max_cls_size)
candsizes.push_back (std::pair<Clause*,size_t>(c, c->size ( )));
}
/*-------------------------------------------------------------------------+
| This is the subsumption check of my forward subsumption algorithm. It |
| checks whether 'c' is subsumed by or can be strengthened by some clause |
| in 'occrs' (which at this point only contains smaller than or equally |
| long clauses as 'c'). |
/*-------------------------------------------------------------------------*/
void CDCL::subsume_check (Clause* c) {
/* Mark literals in 'c' */
mark_sign (c);
Clause* sub = 0;
int str = 0;
int checks = 0;
int matches = 0;
/* Check for subsumption and strengthening candidates in the positive
occurrences of literals in 'c' */
for (const int& lit : *c) {
for (Clause* d : occurs (lit)) {
str = subsumed (d); // check if subsumed
if (str) { sub = d; goto found; } // found candidate
}
}
/* Further check for strengthening candidates in the negative
occurrences of literals in 'c' */
for (const int& lit : *c) {
for (Clause* d : occurs (-lit)) {
str = subsumed (d); // check if 'd' strengthens 'c'
if (str) { sub = d; goto found; } // found candidate
}
}
/* Unmark literals in 'c' */
found:;
unmark (c);
/* Check if 'c' can be subsumed or strengthened */
if (str == INT_MIN) ++stats.subsumed; // 'sub' subsumes 'c'
else if (str) ++stats.strengthened; // 'str' strengthens 'c'
}
/*-------------------------------------------------------------------------+
| This is the subsumption check of my forward subsumption algorithm. It |
| checks whether 'c' is subsumed by or can be strengthened by some clause |
| in 'occrs' (which at this point only contains smaller than or equally |
| long clauses as 'c'). I have added the signature-based pre-check from |
| my paper "Hash-based preprocessing and inprocessing techniques in SAT |
| solvers". |
/*-------------------------------------------------------------------------*/
void CDCL::subsume_check_hash (Clause* c) {
/* Mark literals in 'c' */
mark_sign (c);
Clause* sub = 0;
int str = 0;
int checks = 0;
int matches = 0;
const uint64_t chash = ~c->hash;
const uint64_t cunique = ~c->unique;
/* Check for subsumption and strengthening candidates in the positive
occurrences of literals in 'c' */
for (const int& lit : *c) {
for (const OccrsHash& chu : occhash (lit)) {
//++checks;
if (chu.hash & chash) continue;
if (chu.unique & cunique) continue;
//if (chu.hash & chash) { ++matches; continue; }
//if (chu.unique & cunique) { ++matches; continue; }
str = subsumed (chu.c); // check if subsumed
if (str) { sub = chu.c; goto found; } // found candidate
}
}
/* Further check for strengthening candidates in the negative
occurrences of literals in 'c' */
for (const int& lit : *c) {
for (const OccrsHash& chu : occhash (-lit)) {
//++checks;
if (chu.hash & chash) continue;
if (chu.unique & cunique) continue;
//if (chu.hash & chash) { ++matches; continue; }
//if (chu.unique & cunique) { ++matches; continue; }
str = subsumed (chu.c); // check if 'd' strengthens 'c'
if (str) { sub = chu.c; goto found; } // found candidate
}
}
/* Unmark literals in 'c' */
found:;
unmark (c);
//stats.subsume_checks += checks; // statistics
//stats.subsume_hash_matches += matches; // statistics
/* Check if 'c' can be subsumed or strengthened */
if (str == INT_MIN) ++stats.subsumed; // 'sub' subsumes 'c'
else if (str) ++stats.strengthened; // 'str' strengthens 'c'
}
/*-------------------------------------------------------------------------+
| This is the true hot-spot of the subsumption algorithm. In order to che-|
| ck whether 'c' subsumes the exterior (marked) clause, we have to compare|
| the signs of literals in 'c', which involves accessing the mark through |
| 'sign_marked', which merely returns the saved sign. |
| Fuction : |
| Returns INT_MIN if 'c' is subsumed. |
| Returns 'str' (literal to strengthen) if 'str' strengthens 'c'. |
| Otherwise returns 0. |
/*-------------------------------------------------------------------------*/
int CDCL::subsumed (const Clause* c) {
int str = 0;
for (const int& lit : *c) {
const signed char sign = sign_marked (lit);
if (!sign) return 0; // 'lit' unmarked
else if (sign > 0) continue; // 'lit' mark is positive
else if (str) return 0; // two negated literals
else str = lit; // strengthening literal
}
if (!str) return INT_MIN; // subsumption
return str; // strengthen
}
/*-------------------------------------------------------------------------+
| Find the literal in 'c' in the smallest occurrence list. |
/*-------------------------------------------------------------------------*/
int CDCL::subsume_min_occrs (const Clause* c) {
int minlit = 0;
size_t minsize = UINTMAX_MAX;
for (const int& lit : *c) {
const size_t size = occurs (lit).size ( );
if (size >= minsize) continue;
minlit = lit;
minsize = size;
}
return minlit;
}
/*-------------------------------------------------------------------------+
| Find the literal in 'c' in the smallest occurrence list. |
/*-------------------------------------------------------------------------*/
int CDCL::subsume_min_occrs_hash (const Clause* c) {
int minlit = 0;
size_t minsize = UINTMAX_MAX;
for (const int& lit : *c) {
const size_t size = occhash (lit).size ( );
if (size >= minsize) continue;
minlit = lit;
minsize = size;
}
return minlit;
}
} //End namespace sat | 42.416667 | 80 | 0.507957 | [
"vector"
] |
c9a10ff14aa712ddc4d2d43bf015952095a81a7e | 598 | cpp | C++ | algorithms/137.single-number-ii.cpp | huklee/leetcode | 6337dfde618e2bef97c8622494d180973c5014a9 | [
"MIT"
] | 2 | 2017-02-16T04:37:58.000Z | 2017-03-27T14:20:04.000Z | algorithms/137.single-number-ii.cpp | huklee/leetcode | 6337dfde618e2bef97c8622494d180973c5014a9 | [
"MIT"
] | null | null | null | algorithms/137.single-number-ii.cpp | huklee/leetcode | 6337dfde618e2bef97c8622494d180973c5014a9 | [
"MIT"
] | null | null | null | class Solution {
public:
// O(n) solution with 32 bits
int singleNumber(vector<int>& nums) {
// bit summation & mod 3 operations
int bits[32] = {0,};
for (int i=0; i < nums.size(); i++){
for (int j=0; j < 32; j++){
int mask = 1<<j;
int add_bit = (nums[i]&mask) ? 1 : 0;
bits[j] = (bits[j] + add_bit)%3;
}
}
// covert bits -> digial number
int num = 0;
for (int j=0; j < 32; j++)
num += (1 << j)*bits[j];
return num;
}
};
| 27.181818 | 53 | 0.40301 | [
"vector"
] |
c9a2aa510a318373a79ed1d608e5ffce71c08cbf | 4,307 | hpp | C++ | lib/Atom.hpp | atfrank/LarmorD_New | d1d166c699f26be523557a10523be0f37cb188f5 | [
"BSD-4-Clause-UC"
] | 7 | 2021-06-16T00:48:08.000Z | 2022-03-22T11:21:55.000Z | lib/Atom.hpp | atfrank/LarmorD_New | d1d166c699f26be523557a10523be0f37cb188f5 | [
"BSD-4-Clause-UC"
] | 2 | 2022-01-10T09:56:21.000Z | 2022-01-24T13:22:51.000Z | lib/Atom.hpp | atfrank/Metallo | 0bce801cb127fb8557bf2599ae31d2611ebb0256 | [
"BSD-4-Clause-UC"
] | 2 | 2021-08-28T01:48:28.000Z | 2021-11-24T23:05:28.000Z | /*
Copyright University of Michigan.
This file is part of the Larmor software suite and is made available under license.
University of Michigan (UM) TECHtransfer: phone: 734-763-0614 email: techtransfer@umich.edu.
Author: Sean M. Law and Aaron T. Frank
*/
#ifndef ATOM_H
#define ATOM_H
#include "Coor.hpp"
#include <vector>
#include <string>
//Forward declaration
class Chain;
class Residue;
class Atom {
private:
std::string tag;
std::string recname; //Record name: "ATOM ", "HETATM"
int atmnum; //Atom serial number
std::string atmname; //Atom name
std::string atmtype; //Mol2
std::string alt; //Alternate location indicator
Residue* res;
std::string resname; //Residue name
Chain* chn;
std::string chainid; //Chain identifier, modified if realid is duplicated
std::string realid; //Store original chainid
int resid; //Residue sequence number
std::string icode; //Code for insertion of residues
Coor coor; //X, Y, Z Coordinates
double occu; //Occupancy
double bfac; //B-factor or Temperature factor
std::string segid; //Segment identifier
bool sel; //Selection flag
std::string summary; //A:GLY1.CA style summary
std::string ss; //Secondary structure
double mass;
double charge;
std::string elem;
unsigned int atminx; //For easier 2-D lookup tables
std::vector<double> data;
std::vector<Atom*> bonds;
//All additional fields must also be added to Atom::clone(), Atom::dummy() functions!!
public:
Atom(); //Constructor
Atom(int atmnum, std::string atmname, std::string resname, int resnum, Coor vec, std::string seg=0); //Overload constructor
void reset();
void clone(Atom* atmin);
void dummy();
//Get atom info
std::string& getTag();
std::string& getRecName();
int& getAtmNum();
std::string& getAtmName();
std::string& getAtmType();
std::string& getAlt();
Residue* getResidue();
std::string& getResName();
Chain* getChain();
std::string& getChainId();
std::string& getRealId();
int& getResId();
std::string& getICode();
Coor& getCoor ();
double& getX();
double& getY();
double& getZ();
double& getOccu();
double& getBFac();
std::string& getElem();
std::string& getSegId();
bool& getSel();
std::string& getSummary();
std::string& getSS();
double& getMass();
double& getCharge();
std::vector<double>& getData();
double& getDataPoint(const unsigned int element);
unsigned int& getAtmInx();
unsigned int getDataSize();
unsigned int getBondsSize();
std::vector<Atom*>& getBonds();
Atom* getBond(const unsigned int &element);
//Set atom info
void setTag(const std::string& tagin);
void setRecName(const std::string& recnamein);
void setAtmNum(const int& atmnumin);
void setAtmName(const std::string& atmnamein);
void setAtmName(); //Clear
void setAtmType(const std::string& atmtypein);
void setAtmType(); //Clear
void setAlt(const std::string& altin);
void setAlt(); //Clear
void setResidue(); //Clear
void setResidue(Residue* resin=NULL);
void setResName(const std::string& resnamein);
void setResName(); //Clear
void setChain(Chain* chnin=NULL);
void setChainId(const std::string& chainidin);
void setRealId(const std::string& realidin);
void setChainId(); //Clear
void setRealId(); //Clear
void setResId(const int& residin);
void setICode(const std::string& icodein);
void setICode(); //Clear
void setX(const double &xin);
void setY(const double &yin);
void setZ(const double &zin);
void setCoor(const Coor& coorin);
void setOccu(const double& occuin);
void setBFac(const double& bfacin);
void setElem(const std::string& elemin);
void setSegId(const std::string& segidin);
void setSegId(); //Clear
void setSel(const bool selin);
void setSummary(const std::string& summaryin);
void setSS(const std::string& ssin);
void setMass(const double& massin);
void setCharge(const double& chargein);
void setAtmInx(const unsigned int& atminxin);
void addData(const double& din);
void clearData();
void addBond(Atom* atmin);
void clearBonds();
};
#endif
| 30.764286 | 127 | 0.661017 | [
"vector"
] |
c9ae9c88c091f989148a9e3d3c7843a0446b6398 | 2,119 | hpp | C++ | editor/bt_editor/BehaviorTreeNodeModel.hpp | miccol/YARP-Behavior-Trees | 6c4767688c71606283eaf7d702e91c646b4a4036 | [
"MIT"
] | 9 | 2019-01-02T13:58:17.000Z | 2021-03-12T08:28:34.000Z | editor/bt_editor/BehaviorTreeNodeModel.hpp | miccol/YARP-Behavior-Trees | 6c4767688c71606283eaf7d702e91c646b4a4036 | [
"MIT"
] | 1 | 2018-03-01T09:20:36.000Z | 2018-03-01T09:20:36.000Z | editor/bt_editor/BehaviorTreeNodeModel.hpp | miccol/YARP-Behavior-Trees | 6c4767688c71606283eaf7d702e91c646b4a4036 | [
"MIT"
] | 5 | 2018-02-28T16:16:45.000Z | 2020-10-28T00:39:49.000Z | #ifndef BEHAVIORTREENODEMODEL_H
#define BEHAVIORTREENODEMODEL_H
#include <QObject>
#include <QLabel>
#include <QFormLayout>
#include <QComboBox>
#include <QTextEdit>
#include <node_editor/NodeDataModel>
#include <iostream>
#include <memory>
#include <vector>
#include <map>
#include <functional>
#include "NodeFactory.hpp"
using QtNodes::PortType;
using QtNodes::PortIndex;
using QtNodes::NodeData;
using QtNodes::NodeDataType;
using QtNodes::NodeDataModel;
class BehaviorTreeNodeModel : public NodeDataModel
{
Q_OBJECT
public:
BehaviorTreeNodeModel(QString name, const NodeFactory::ParametersModel& parameter_model);
virtual ~BehaviorTreeNodeModel() {}
virtual bool captionVisible() const override
{ return false; }
public:
NodeDataType dataType(PortType portType, PortIndex portIndex) const override
{ return NodeDataType {"", ""}; }
virtual std::shared_ptr<NodeData> outData(PortIndex port) override
{ return nullptr; }
void setInData(std::shared_ptr<NodeData> data, int) override {}
virtual QString caption() const override;
QString type() const;
std::vector<std::pair<QString, QString> > getCurrentParameters() const;
virtual QWidget *embeddedWidget() override { return _main_widget; }
virtual QJsonObject save() const override;
void restore(std::map<QString, QString> attributes);
virtual void restore(QJsonObject const &nodeJson) override;
virtual void lock(bool locked);
QString get_line_edit();
QString get_text_edit();
//bool eventFilter(QObject *object, QEvent *event);
std::string filename();
public slots:
void onCodeUpdated();
private:
QWidget* _main_widget;
QWidget* _params_widget;
QFormLayout *_form_layout;
QLabel* _label;
QComboBox* _ID_selection_combobox;
QString _ID;
QLineEdit* _line_edit;
QTextEdit * _text_edit;
const NodeFactory::ParametersModel& _parameter_model;
private slots:
void onComboBoxUpdated(QString item_text);
void onTextBoxUpdated();
signals:
void adjustSize();
};
//------------------------------------------------
//------------------------------------------------
#endif
| 22.784946 | 91 | 0.719679 | [
"object",
"vector"
] |
c9b91ad0770cc5d796eb6e14572eb98d73b33353 | 9,562 | cpp | C++ | dockerfiles/gaas_tutorial_2/GAAS/software/SLAM/ygz_slam_ros/Thirdparty/PCL/apps/src/pcd_video_player/pcd_video_player.cpp | hddxds/scripts_from_gi | afb8977c001b860335f9062464e600d9115ea56e | [
"Apache-2.0"
] | 2 | 2019-04-10T14:04:52.000Z | 2019-05-29T03:41:58.000Z | software/SLAM/ygz_slam_ros/Thirdparty/PCL/apps/src/pcd_video_player/pcd_video_player.cpp | glider54321/GAAS | 5c3b8c684e72fdf7f62c5731a260021e741069e7 | [
"BSD-3-Clause"
] | null | null | null | software/SLAM/ygz_slam_ros/Thirdparty/PCL/apps/src/pcd_video_player/pcd_video_player.cpp | glider54321/GAAS | 5c3b8c684e72fdf7f62c5731a260021e741069e7 | [
"BSD-3-Clause"
] | 1 | 2021-12-20T06:54:41.000Z | 2021-12-20T06:54:41.000Z | /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2012, Willow Garage, 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 Willow Garage, Inc. 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 OWNER 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.
*
*/
//PCL
#include <pcl/apps/pcd_video_player.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
//STD
#include <iostream>
#include <fstream>
//BOOST
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/property_tree/ptree.hpp>
//QT4
#include <QApplication>
#include <QMutexLocker>
#include <QEvent>
#include <QObject>
#include <QFileDialog>
#include <QGroupBox>
#include <QRadioButton>
#include <QButtonGroup>
// VTK
#include <vtkRenderWindow.h>
#include <vtkRendererCollection.h>
#include <vtkCamera.h>
using namespace pcl;
using namespace std;
//////////////////////////////////////////////////////////////////////////////////////////////////////////
PCDVideoPlayer::PCDVideoPlayer ()
{
cloud_present_ = false;
cloud_modified_ = false;
play_mode_ = false;
speed_counter_ = 0;
speed_value_ = 5;
//Create a timer
vis_timer_ = new QTimer (this);
vis_timer_->start (5);//5ms
connect (vis_timer_, SIGNAL (timeout ()), this, SLOT (timeoutSlot ()));
ui_ = new Ui::MainWindow;
ui_->setupUi (this);
this->setWindowTitle ("PCL PCD Video Player");
// Setup the cloud pointer
cloud_.reset (new pcl::PointCloud<pcl::PointXYZRGBA>);
// Set up the qvtk window
vis_.reset (new pcl::visualization::PCLVisualizer ("", false));
ui_->qvtkWidget->SetRenderWindow (vis_->getRenderWindow ());
vis_->setupInteractor (ui_->qvtkWidget->GetInteractor (), ui_->qvtkWidget->GetRenderWindow ());
vis_->getInteractorStyle ()->setKeyboardModifier (pcl::visualization::INTERACTOR_KB_MOD_SHIFT);
ui_->qvtkWidget->update ();
// Connect all buttons
connect (ui_->playButton, SIGNAL (clicked ()), this, SLOT (playButtonPressed ()));
connect (ui_->stopButton, SIGNAL (clicked ()), this, SLOT (stopButtonPressed ()));
connect (ui_->backButton, SIGNAL (clicked ()), this, SLOT (backButtonPressed ()));
connect (ui_->nextButton, SIGNAL (clicked ()), this, SLOT (nextButtonPressed ()));
connect (ui_->selectFolderButton, SIGNAL (clicked ()), this, SLOT (selectFolderButtonPressed ()));
connect (ui_->selectFilesButton, SIGNAL (clicked ()), this, SLOT (selectFilesButtonPressed ()));
connect (ui_->indexSlider, SIGNAL (valueChanged (int)), this, SLOT (indexSliderValueChanged (int)));
}
void
PCDVideoPlayer::backButtonPressed ()
{
if(current_frame_ == 0) // Already in the beginning
{
PCL_DEBUG ("[PCDVideoPlayer::nextButtonPressed] : reached the end\n");
current_frame_ = nr_of_frames_ - 1; // reset to end
}
else
{
current_frame_--;
cloud_modified_ = true;
ui_->indexSlider->setSliderPosition (current_frame_); // Update the slider position
}
}
void
PCDVideoPlayer::nextButtonPressed ()
{
if (current_frame_ == (nr_of_frames_ - 1)) // Reached the end
{
PCL_DEBUG ("[PCDVideoPlayer::nextButtonPressed] : reached the end\n");
current_frame_ = 0; // reset to beginning
}
else
{
current_frame_++;
cloud_modified_ = true;
ui_->indexSlider->setSliderPosition (current_frame_); // Update the slider position
}
}
void
PCDVideoPlayer::selectFolderButtonPressed ()
{
pcd_files_.clear (); // Clear the std::vector
pcd_paths_.clear (); // Clear the boost filesystem paths
dir_ = QFileDialog::getExistingDirectory (this,
tr("Open Directory"),
"/home",
QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
boost::filesystem::directory_iterator end_itr;
if (boost::filesystem::is_directory (dir_.toStdString ()))
{
for (boost::filesystem::directory_iterator itr (dir_.toStdString ()); itr != end_itr; ++itr)
{
std::string ext = itr->path ().extension ().string ();
if (ext.compare (".pcd") == 0)
{
pcd_files_.push_back (itr->path ().string ());
pcd_paths_.push_back (itr->path ());
}
else
{
// Found non pcd file
PCL_DEBUG ("[PCDVideoPlayer::selectFolderButtonPressed] : found a different file\n");
}
}
}
else
{
PCL_ERROR("Path is not a directory\n");
exit(-1);
}
nr_of_frames_ = pcd_files_.size ();
PCL_DEBUG ("[PCDVideoPlayer::selectFolderButtonPressed] : found %d files\n", nr_of_frames_ );
if (nr_of_frames_ == 0)
{
PCL_ERROR ("Please select valid pcd folder\n");
cloud_present_ = false;
return;
}
else
{
// Reset the Slider
ui_->indexSlider->setValue (0); // set cursor back in the beginning
ui_->indexSlider->setRange (0, nr_of_frames_ - 1); // rescale the slider
current_frame_ = 0;
cloud_present_ = true;
cloud_modified_ = true;
}
}
void
PCDVideoPlayer::selectFilesButtonPressed ()
{
pcd_files_.clear (); // Clear the std::vector
pcd_paths_.clear (); // Clear the boost filesystem paths
QStringList qt_pcd_files = QFileDialog::getOpenFileNames (this,
"Select one or more PCD files to open",
"/home",
"PointClouds (*.pcd)");
nr_of_frames_ = qt_pcd_files.size ();
PCL_INFO ("[PCDVideoPlayer::selectFilesButtonPressed] : selected %ld files\n", nr_of_frames_);
if (nr_of_frames_ == 0)
{
PCL_ERROR ("Please select valid pcd files\n");
cloud_present_ = false;
return;
}
else
{
for(int i = 0; i < qt_pcd_files.size (); i++)
{
pcd_files_.push_back (qt_pcd_files.at (i).toStdString ());
}
current_frame_ = 0;
// Reset the Slider
ui_->indexSlider->setValue (0); // set cursor back in the beginning
ui_->indexSlider->setRange (0, nr_of_frames_ - 1); // rescale the slider
cloud_present_ = true;
cloud_modified_ = true;
}
}
void
PCDVideoPlayer::timeoutSlot ()
{
if (play_mode_)
{
if (speed_counter_ == speed_value_)
{
if (current_frame_ == (nr_of_frames_-1)) // Reached the end
{
current_frame_ = 0; // reset to beginning
}
else
{
current_frame_++;
cloud_modified_ = true;
ui_->indexSlider->setSliderPosition (current_frame_); // Update the slider position
}
}
else
{
speed_counter_++;
}
}
if (cloud_present_ && cloud_modified_)
{
if (pcl::io::loadPCDFile<pcl::PointXYZRGBA> (pcd_files_[current_frame_], *cloud_) == -1) //* load the file
{
PCL_ERROR ("[PCDVideoPlayer::timeoutSlot] : Couldn't read file %s\n");
}
if (!vis_->updatePointCloud(cloud_, "cloud_"))
{
vis_->addPointCloud (cloud_, "cloud_");
vis_->resetCameraViewpoint("cloud_");
}
cloud_modified_ = false;
}
ui_->qvtkWidget->update ();
}
void
PCDVideoPlayer::indexSliderValueChanged (int value)
{
PCL_DEBUG ("[PCDVideoPlayer::indexSliderValueChanged] : (I) : value %d\n", value);
current_frame_ = value;
cloud_modified_ = true;
}
void
print_usage ()
{
PCL_INFO ("PCDVideoPlayer V0.1\n");
PCL_INFO ("-------------------\n");
PCL_INFO ("\tThe slider accepts focus on Tab and provides both a mouse wheel and a keyboard interface. The keyboard interface is the following:\n");
PCL_INFO ("\t Left/Right move a horizontal slider by one single step.\n");
PCL_INFO ("\t Up/Down move a vertical slider by one single step.\n");
PCL_INFO ("\t PageUp moves up one page.\n");
PCL_INFO ("\t PageDown moves down one page.\n");
PCL_INFO ("\t Home moves to the start (minimum).\n");
PCL_INFO ("\t End moves to the end (maximum).\n");
}
int
main (int argc, char** argv)
{
QApplication app (argc, argv);
PCDVideoPlayer VideoPlayer;
VideoPlayer.show ();
return (app.exec ());
}
| 30.549521 | 150 | 0.648714 | [
"vector"
] |
c9bd8df9ebb9c912fab995f33987b8a9aae4b065 | 466 | cpp | C++ | competitive-programming/leetcode/contests/contest/contest-two/counting-words-given-prefix.cpp | dushimsam/deep-dive-in-algorithms | 0c6a04b3115ba789ab4aca68cce51c9a3c3a075a | [
"MIT"
] | null | null | null | competitive-programming/leetcode/contests/contest/contest-two/counting-words-given-prefix.cpp | dushimsam/deep-dive-in-algorithms | 0c6a04b3115ba789ab4aca68cce51c9a3c3a075a | [
"MIT"
] | null | null | null | competitive-programming/leetcode/contests/contest/contest-two/counting-words-given-prefix.cpp | dushimsam/deep-dive-in-algorithms | 0c6a04b3115ba789ab4aca68cce51c9a3c3a075a | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int checkcontains(string pref, string word)
{
for (int i = 0; i < pref.length(); i++)
{
if (pref[i] != word[i])
return false;
}
return true;
}
int countPrefix(string pref, vector<string> words)
{
int count = 0;
for (int i = 0; i < words.size(); i++)
{
if (checkcontains(pref, words[i]))
count++;
}
return count;
}
int main()
{
return 0;
} | 17.259259 | 50 | 0.527897 | [
"vector"
] |
c9be271abf3ebaf581391e1dbcecf869891cdfe7 | 2,488 | cpp | C++ | devmand/gateway/src/devmand/channels/cli/Command.cpp | remo5000/magma | 1d1dd9a23800a8e07b1ce016776d93e12430ec15 | [
"BSD-3-Clause"
] | 2 | 2020-11-05T18:58:26.000Z | 2021-02-09T06:42:49.000Z | devmand/gateway/src/devmand/channels/cli/Command.cpp | remo5000/magma | 1d1dd9a23800a8e07b1ce016776d93e12430ec15 | [
"BSD-3-Clause"
] | 14 | 2019-11-15T12:01:18.000Z | 2019-12-12T14:37:42.000Z | devmand/gateway/src/devmand/channels/cli/Command.cpp | 119Vik/magma-1 | 107a7b374466a837fc0a49b283ba9d6ff1d702e3 | [
"BSD-3-Clause"
] | 3 | 2019-11-15T15:56:25.000Z | 2019-11-21T10:34:59.000Z | // Copyright (c) 2019-present, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include <devmand/channels/cli/Command.h>
namespace devmand {
namespace channels {
namespace cli {
using std::string;
using std::vector;
Command::Command(const std::string _command, int _idx, bool skipCache)
: command(_command), idx(_idx), skipCache_(skipCache) {}
// Factory methods
ReadCommand ReadCommand::create(const std::string& cmd, bool skipCache) {
return ReadCommand(cmd, commandCounter++, skipCache);
}
WriteCommand WriteCommand::create(const std::string& cmd, bool skipCache) {
return WriteCommand(cmd, commandCounter++, skipCache);
}
static const char DELIMITER = '\n';
bool Command::isMultiCommand() {
return command.find(DELIMITER) != std::string::npos;
}
vector<Command> Command::splitMultiCommand() {
string str = command;
vector<Command> commands;
string::size_type pos = 0;
string::size_type prev = 0;
while ((pos = str.find(DELIMITER, prev)) != std::string::npos) {
commands.emplace_back(WriteCommand::create(str.substr(prev, pos - prev)));
prev = pos + 1;
}
commands.emplace_back(ReadCommand::create(str.substr(prev)));
return commands;
}
ReadCommand::ReadCommand(const string& _command, int _idx, bool _skipCache)
: Command(_command, _idx, _skipCache) {}
ReadCommand ReadCommand::create(const Command& cmd) {
return create(cmd.raw(), cmd.skipCache());
}
ReadCommand& ReadCommand::operator=(const ReadCommand& other) {
this->command = other.command;
this->idx = other.idx;
this->skipCache_ = other.skipCache_;
return *this;
}
ReadCommand::ReadCommand(const ReadCommand& rc)
: Command(rc.raw(), rc.idx, rc.skipCache()) {}
WriteCommand::WriteCommand(const string& _command, int _idx, bool _skipCache)
: Command(_command, _idx, _skipCache) {}
WriteCommand WriteCommand::create(const Command& cmd) {
return create(cmd.raw(), cmd.skipCache());
}
WriteCommand::WriteCommand(const WriteCommand& wc)
: Command(wc.raw(), wc.idx, wc.skipCache()) {}
WriteCommand& WriteCommand::operator=(const WriteCommand& other) {
this->command = other.command;
this->idx = other.idx;
this->skipCache_ = other.skipCache_;
return *this;
}
} // namespace cli
} // namespace channels
} // namespace devmand
| 29.619048 | 78 | 0.721865 | [
"vector"
] |
c9c5a9fbe66dfd5c24d7fd829a8f279b43b3505b | 490 | cpp | C++ | solved/easy/1512. Number of Good Pairs/main.cpp | SlaveWilson/leetcode | b762380594908ed44ae278ca1a14e9185eec2f0e | [
"MIT"
] | null | null | null | solved/easy/1512. Number of Good Pairs/main.cpp | SlaveWilson/leetcode | b762380594908ed44ae278ca1a14e9185eec2f0e | [
"MIT"
] | null | null | null | solved/easy/1512. Number of Good Pairs/main.cpp | SlaveWilson/leetcode | b762380594908ed44ae278ca1a14e9185eec2f0e | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
int numIdenticalPairs(vector<int> &nums)
{
int pairs = 0;
for (int i = 0; i < nums.size(); i++)
{
for (int j = 0; j < nums.size(); j++)
{
if (nums[i] == nums[j] && i < j)
pairs++;
}
}
return pairs;
}
};
int main()
{
vector<int> nums{1, 2, 3, 1, 1, 3};
Solution sol;
int output = sol.numIdenticalPairs(nums);
cout << output << endl;
} | 16.333333 | 43 | 0.522449 | [
"vector"
] |
c9c914e9b29d434d58dc28fd117f0cc74dbb0b7f | 12,370 | cpp | C++ | Sources/Internal/Scene2D/GameObject.cpp | Serviak/dava.engine | d51a26173a3e1b36403f846ca3b2e183ac298a1a | [
"BSD-3-Clause"
] | 1 | 2020-11-14T10:18:24.000Z | 2020-11-14T10:18:24.000Z | Sources/Internal/Scene2D/GameObject.cpp | Serviak/dava.engine | d51a26173a3e1b36403f846ca3b2e183ac298a1a | [
"BSD-3-Clause"
] | null | null | null | Sources/Internal/Scene2D/GameObject.cpp | Serviak/dava.engine | d51a26173a3e1b36403f846ca3b2e183ac298a1a | [
"BSD-3-Clause"
] | 1 | 2020-09-05T21:16:17.000Z | 2020-09-05T21:16:17.000Z | #include "Scene2D/GameObject.h"
#include "Animation/AnimationManager.h"
#include "Logger/Logger.h"
#include "Scene2D/GameObjectManager.h"
#include "Animation/LinearAnimation.h"
#include "Animation/BezierSplineAnimation.h"
#include "Collision/CollisionObject2.h"
#include "Animation/KeyframeAnimation.h"
#include "Scene2D/GameObjectAnimations.h"
#include "Render/2D/Systems/RenderSystem2D.h"
#include "Render/RenderHelper.h"
namespace DAVA
{
GameObject* GameObject::Create(const FilePath& _pathToSprite, int32 frame)
{
GameObject* object = new GameObject();
Sprite* sprite = Sprite::Create(_pathToSprite);
object->SetSprite(sprite);
object->SetFrame(frame);
SafeRelease(sprite);
return object;
}
GameObject* GameObject::Create(Sprite* sprite, int32 frame)
{
GameObject* object = new GameObject();
object->SetSprite(sprite);
object->SetFrame(frame);
return object;
}
GameObject::GameObject()
{
//Logger::FrameworkDebug("[GameObject] ctor");
//AnimationManager::Instance()->AddObject(this);
visible = true;
dead = false;
priorityChanged = false;
addedObject = false;
sprite = 0;
manager = 0;
color = Color(1.0f, 1.0f, 1.0f, 1.0f);
blending = BLENDING_ALPHABLEND;
collision = 0;
groupId = 0;
priority = 0;
parent = 0;
userData = 0;
isDebugDraw = false;
nextManager = 0;
}
GameObject::~GameObject()
{
SafeRelease(collision);
SafeRelease(sprite);
//Logger::FrameworkDebug("[GameObject] destructor");
//AnimationManager::Instance()->RemoveObject(this);
}
Animation* GameObject::WaitAnimation(float32 time, int32 track)
{
Animation* animation = new Animation(this, time, Interpolation::LINEAR);
animation->Start(track);
return animation;
}
Animation* GameObject::MoveAnimation(float32 x, float32 y, float32 time, Interpolation::FuncType interpolationFunc, int32 track)
{
LinearAnimation<Vector2>* animation = new LinearAnimation<Vector2>(this, &localDrawState.position, Vector2(x, y), time, interpolationFunc);
animation->Start(track);
return animation;
}
Animation* GameObject::MoveBySplineAnimation(BezierSpline2* spline, float32 time, Interpolation::FuncType interpolationFunc, int32 track)
{
BezierSplineAnimation2* animation = new BezierSplineAnimation2(this, &localDrawState.position, spline, time, interpolationFunc);
animation->Start(track);
return animation;
}
Animation* GameObject::ScaleAnimation(const Vector2& finalScale, float32 time, Interpolation::FuncType interpolationFunc, int32 track)
{
LinearAnimation<Vector2>* animation = new LinearAnimation<Vector2>(this, &localDrawState.scale, finalScale, time, interpolationFunc);
animation->Start(track);
return animation;
}
Animation* GameObject::ColorAnimation(const Color& finalColor, float32 time, Interpolation::FuncType interpolationFunc, int32 track)
{
LinearAnimation<Color>* animation = new LinearAnimation<Color>(this, &color, finalColor, time, interpolationFunc);
animation->Start(track);
return animation;
}
void GameObject::VisibleAnimationCallback(BaseObject* caller, void* param, void* callerData)
{
bool* params = static_cast<bool*>(param);
SetVisible(params[0]);
delete[] params;
}
Animation* GameObject::VisibleAnimation(bool visible, int32 track /* = 0*/)
{
//TODO: change to bool animation - Dizz
Animation* animation = new Animation(this, 0.01f, Interpolation::LINEAR);
bool* params = new bool[1];
params[0] = visible;
animation->AddEvent(Animation::EVENT_ANIMATION_START, Message(this, &GameObject::VisibleAnimationCallback, static_cast<void*>(params)));
animation->Start(track);
return animation;
}
Animation* GameObject::RotateAnimation(float32 newAngle, float32 time, Interpolation::FuncType interpolationFunc, int32 track)
{
LinearAnimation<float32>* animation = new LinearAnimation<float32>(this, &localDrawState.angle, newAngle, time, interpolationFunc);
animation->Start(track);
return animation;
}
Animation* GameObject::FrameInterpolateAnimation(int32 startFrame, int32 endFrame, float32 time, int32 track)
{
KeyframeData* data = new KeyframeData();
data->AddKeyframe(startFrame, 0.0f);
data->AddKeyframe(endFrame, time);
KeyframeAnimation* animation = new KeyframeAnimation(this, &localDrawState.frame, data, time);
SafeRelease(data);
animation->Start(track);
return animation;
}
void GameObject::RemoveFromManagerAnimation(BaseObject* animation, void* userData, void* callerData)
{
if (manager)
manager->RemoveObject(this);
}
Animation* GameObject::RemoveFromManagerAnimation(int32 track)
{
Animation* animation = new Animation(this, 0.001f, Interpolation::LINEAR);
animation->AddEvent(Animation::EVENT_ANIMATION_START, Message(this, &GameObject::RemoveFromManagerAnimation));
animation->Start(track);
return animation;
}
/*
void GameObject::ApplyAnimation(SceneObjectAnimation * _animation)
{
animations.push_back(_animation);
visible = true; // make visible all objects if we started animation
}
void GameObject::ApplyAnimationWithDelay(SceneObjectAnimation * _animation, float32 _delayTime)
{
// animation = _animation;
// if (animation)
// {
// // set public properties of object
// animation->position = position;
// animation->angle = angle;
//
// // start animation
// animation->StartAnimationWithDelay(_animationTime, _delayTime);
// }
}
void GameObject::Update(float32 timeElapsed)
{
if ((!currentAnimationState) && (animations.size() > 0))
{
AnimationState * state = SceneManager::Instance()->NewAnimationState();
state->startPosition = position;
state->startAngle = angle;
state->startFrame = frame;
state->position = &position;
state->angle = ∠
state->frame = &frame;
state->animation = animations.front();
state->animationTimeLength = state->animation->animationTimeLength;
state->interpolationFunc = state->animation->func;
animations.pop_front();
currentAnimationState = state;
// start animation
SceneManager::Instance()->StartAnimationImmediatelly(state);
}
if (currentAnimationState)
if (!currentAnimationState->isAnimating)
{
currentAnimationState->canRemove = true;
currentAnimationState = 0;
}
if ((currentAnimationState == 0) && (animations.size() == 0) && (makeInvisibleAfterAllAnimations))
visible = false;
} */
void GameObject::SetFrame(int32 _frame)
{
localDrawState.frame = _frame;
globalDrawState.frame = _frame;
}
void GameObject::SetPriority(int32 _priority)
{
priority = _priority;
if (manager)
{
manager->MarkToChangeObjectPriority(this);
}
}
void GameObject::SetManager(GameObjectManager* _manager)
{
manager = _manager;
}
void GameObject::FastForward(float32 skipTime, float32 updateTime)
{
DVASSERT(skipTime > 0.0f && updateTime > 0.0f, "FastForward skipTime and updateTime must be greater than 0");
float32 remainingSkipTime = skipTime;
while (remainingSkipTime > 0.0f)
{
Update(updateTime);
remainingSkipTime -= updateTime;
}
}
void GameObject::Update(float32 timeElapsed)
{
if (collision)
collision->Update(globalDrawState);
if (!children.empty())
{
List<GameObject*>::iterator it_end = children.end();
for (List<GameObject*>::iterator t = children.begin(); t != it_end; ++t)
{
GameObject* o = *t;
o->Update(timeElapsed);
}
}
}
void GameObject::RecalcHierarchy(const Sprite::DrawState& parentDrawState)
{
globalDrawState.BuildStateFromParentAndLocal(parentDrawState, localDrawState);
if (!children.empty())
{
List<GameObject*>::iterator it_end = children.end();
for (List<GameObject*>::iterator t = children.begin(); t != it_end; ++t)
{
GameObject* o = *t;
o->RecalcHierarchy(globalDrawState);
}
}
}
void GameObject::CollisionPhase()
{
}
void GameObject::Draw()
{
if (!visible)
return;
if (sprite)
{
RenderSystem2D::Instance()->Draw(sprite, &globalDrawState, color);
// RenderSystem2D::Instance()->SetColor(1.0f, 0.0f, 0.0f, 1.0f);
// RenderManager::Instance()->FillRect(Rect(globalDrawState.position.x - 1, globalDrawState.position.y - 1, 3, 3));
// RenderSystem2D::Instance()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);
}
else
{
// RenderSystem2D::Instance()->SetColor(1.0f, 0.0f, 0.0f, 1.0f);
// RenderManager::Instance()->FillRect(Rect(globalDrawState.position.x, globalDrawState.position.y, 10, 10));
// RenderSystem2D::Instance()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);
}
if (isDebugDraw && collision)
{
collision->DebugDraw();
}
// if (align == ALIGN_LEFTTOP)
// {
// //[sprite drawFrameF:frame atX:position.x atY:position.y];
// }else if (align == ALIGN_CENTER)
// {
// //[sprite drawFrameF:frame atCenterX:position.x atCenterY:position.y];
// }
}
void GameObject::AttachObject(GameObject* gameObject)
{
children.push_back(gameObject);
gameObject->parent = this;
}
void GameObject::DetachObject(GameObject* gameObject)
{
for (List<GameObject*>::iterator t = children.begin(); t != children.end(); ++t)
{
if (*t == gameObject)
{
gameObject->localDrawState = gameObject->globalDrawState;
gameObject->parent = 0;
children.erase(t);
break;
}
}
}
void GameObject::AddObject(GameObject* gameObject)
{
children.push_back(gameObject);
gameObject->parent = this;
//gameObject->needToBeAddedToManager = true;
//manager->changesStack.push_back(gameObject);
if (manager)
gameObject->ChangeManager(manager);
}
void GameObject::RemoveObject(GameObject* gameObject)
{
//std::remove(animations.begin(), animations.end(), animation);
for (List<GameObject*>::iterator t = children.begin(); t != children.end(); ++t)
{
if (*t == gameObject)
{
gameObject->parent = 0;
gameObject->ChangeManager(0);
children.erase(t);
break;
}
}
}
GameObject* GameObject::GetParent() const
{
return parent;
}
void GameObject::ChangeManager(GameObjectManager* newManager)
{
Retain();
if (manager)
{
manager->RemoveObject(this);
}
if (newManager)
{
newManager->AddObject(this);
for (List<GameObject*>::iterator t = children.begin(); t != children.end(); ++t)
{
GameObject* child = *t;
child->ChangeManager(newManager);
}
}
Release();
}
void GameObject::SetPivotPoint(int32 alignFlags)
{ //WTF? Pivot point it's a pivot point. Align it's align. Why function that sets align calls SetPivotPoint!!!!????
if (!sprite)
return;
if (alignFlags & ALIGN_LEFT)
{
localDrawState.pivotPoint.x = 0.0f;
}
else if (alignFlags & ALIGN_HCENTER)
{
localDrawState.pivotPoint.x = sprite->GetWidth() / 2.0f;
}
else if (alignFlags & ALIGN_RIGHT)
{
localDrawState.pivotPoint.x = sprite->GetWidth();
}
if (alignFlags & ALIGN_TOP)
{
localDrawState.pivotPoint.y = 0.0f;
}
else if (alignFlags & ALIGN_VCENTER)
{
localDrawState.pivotPoint.y = sprite->GetHeight() / 2.0f;
}
else if (alignFlags & ALIGN_BOTTOM)
{
localDrawState.pivotPoint.y = sprite->GetHeight();
}
}
bool GameObject::IsCollideWith(GameObject* gameObject)
{
CollisionObject2* collision2 = gameObject->GetCollision();
if (collision && collision2)
{
collision->Update(globalDrawState);
collision2->Update(gameObject->globalDrawState);
return collision->IsCollideWith(collision2);
}
return false;
}
bool GameObject::IsCollideWith(CollisionObject2* collision2)
{
if (collision && collision2)
{
collision->Update(globalDrawState);
//collision2->Update(gameObject->globalDrawState);
return collision->IsCollideWith(collision2);
}
return false;
}
void GameObject::SetCollisionObject(CollisionObject2* obj)
{
SafeRelease(collision);
collision = SafeRetain(obj);
}
List<GameObject*>& GameObject::GetChildren()
{
return children;
}
}; | 27.86036 | 143 | 0.679062 | [
"render",
"object"
] |
c9c94a28cf2fc291e64e25d4a877dc8b63da2bec | 407 | cpp | C++ | CPP STL/vector/vector3.cpp | Jon3sjns/open-source-contribution | b1dc4a90ce3bd5575b74bf2961a9f6867d16aef4 | [
"MIT"
] | 2 | 2022-03-10T17:37:24.000Z | 2022-03-10T17:40:05.000Z | CPP STL/vector/vector3.cpp | Jon3sjns/open-source-contribution | b1dc4a90ce3bd5575b74bf2961a9f6867d16aef4 | [
"MIT"
] | null | null | null | CPP STL/vector/vector3.cpp | Jon3sjns/open-source-contribution | b1dc4a90ce3bd5575b74bf2961a9f6867d16aef4 | [
"MIT"
] | 1 | 2021-12-29T16:13:52.000Z | 2021-12-29T16:13:52.000Z | #include <bits/stdc++.h>
using namespace std;
//#define int long long
int count = 0;
//part:-3 vector initialization, declaration and traversal
int main()
{
int n = 3, x = 10; //n is the size of vector, and x is the element. so the vector will be :- {10,10,10}
vector<int> v(n, x);
for (auto it = v.begin(); it < v.end(); it++)
{
cout << *it << " " << endl;
}
return 0;
} | 21.421053 | 107 | 0.567568 | [
"vector"
] |
c9d2920b418e167bdf54bf3699ab3e149a8b285a | 9,452 | cpp | C++ | training/src/compiler/training/compiler/WorkflowEager.cpp | steelONIONknight/bolt | 9bd3d08f2abb14435ca3ad0179889e48fa7e9b47 | [
"MIT"
] | null | null | null | training/src/compiler/training/compiler/WorkflowEager.cpp | steelONIONknight/bolt | 9bd3d08f2abb14435ca3ad0179889e48fa7e9b47 | [
"MIT"
] | null | null | null | training/src/compiler/training/compiler/WorkflowEager.cpp | steelONIONknight/bolt | 9bd3d08f2abb14435ca3ad0179889e48fa7e9b47 | [
"MIT"
] | null | null | null | // Copyright (C) 2022. Huawei Technologies Co., Ltd. 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 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 <training/base/layers/BasicLayer.h>
#include <training/compiler/Compiler.h>
#include "WorkflowActions.h"
#include "WorkflowDB.h"
#include "WorkflowEager.h"
namespace raul
{
void WorkflowEager::prepareMemoryForTraining()
{
Workflow::prepareMemoryForTraining();
for (auto& layer : mLayers)
{
layer->initNotBSTensors();
}
executePipeline(Workflow::Pipelines::Zero);
}
void WorkflowEager::preparePipelines(Execution)
{
try
{
if (mUseCompiler)
{
if (!mCompiler->isResolved())
{
createImplementations();
}
}
if (mIsForwardCalled)
{
THROW_NONAME("WorkflowEager", "forward called without leading backward");
}
// check same outputs usage globally
{
std::unordered_set<Name> allOutputs;
for (auto& layer : mLayers)
{
for (const auto& output : layer->getOutputs())
{
auto it = allOutputs.find(output);
if (it != allOutputs.end())
{
THROW_NONAME("WorkflowEager", "the workflow is not correct, there are same outputs defined: " + output);
}
else
{
allOutputs.insert(output);
}
}
}
}
// check unique names (inputs, weights) usage per layer
{
for (auto& layer : mLayers)
{
if (!isUniqueNames(layer->getInputs()))
{
THROW_NONAME("WorkflowEager", "the workflow is not correct, there are same inputs defined for layer " + layer->getName());
}
if (!isUniqueNames(layer->getSharedWeights()))
{
THROW_NONAME("WorkflowEager", "the workflow is not correct, there are same weights defined for layer " + layer->getName());
}
}
}
clearPipelines();
createAuxPipelines();
mIsPipelinesPrepared = true;
}
catch (...)
{
THROW_NONAME("WorkflowEager", "Cannot prepare pipelines");
}
}
void WorkflowEager::createAuxPipelines()
{
try
{
// Tensor vs index in mTensorNeeded
std::unordered_map<Name, size_t> uniqueTensors;
std::unordered_set<Name> layers;
for (const auto& layer : mWorkflowDB->getLayersTable())
{
layers.insert(layer.first);
}
// check inequality, fill uniqueTensors
for (const Name& lName : layers)
{
try
{
std::vector<Name> tensors = mWorkflowDB->getSlice(mWorkflowDB->getLayersTable(), lName);
for (const auto& tName : tensors)
{
auto uniqueIt = uniqueTensors.find(tName);
if (uniqueIt != uniqueTensors.end())
{
auto tensorUsage = mWorkflowDB->getCell(mWorkflowDB->getLayersTable(), lName, tName);
if (!mWorkflowDB->isCellElementEmpty(tensorUsage, Usage::Forward))
{
if (mWorkflowDB->getUsage((*uniqueIt).second).isZero || mWorkflowDB->getUsage(tensorUsage[static_cast<size_t>(Usage::Forward)]).isZero)
{
mWorkflowDB->getUsage((*uniqueIt).second).isZero = true;
mWorkflowDB->getUsage(tensorUsage[static_cast<size_t>(Usage::Forward)]).isZero = true;
}
checkAttributesInequality((*uniqueIt).second, tensorUsage[static_cast<size_t>(Usage::Forward)], tName);
}
if (!mWorkflowDB->isCellElementEmpty(tensorUsage, Usage::Backward))
{
if (mWorkflowDB->getUsage((*uniqueIt).second).isZero || mWorkflowDB->getUsage(tensorUsage[static_cast<size_t>(Usage::Backward)]).isZero)
{
mWorkflowDB->getUsage((*uniqueIt).second).isZero = true;
mWorkflowDB->getUsage(tensorUsage[static_cast<size_t>(Usage::Backward)]).isZero = true;
}
checkAttributesInequality((*uniqueIt).second, tensorUsage[static_cast<size_t>(Usage::Backward)], tName);
}
}
else
{
auto tensorUsage = mWorkflowDB->getCell(mWorkflowDB->getLayersTable(), lName, tName);
Usage tUsage = Usage::Backward;
if (!mWorkflowDB->isCellElementEmpty(tensorUsage, Usage::Forward))
{
tUsage = Usage::Forward;
}
if (!mWorkflowDB->isCellElementEmpty(tensorUsage, Usage::Forward) && !mWorkflowDB->isCellElementEmpty(tensorUsage, Usage::Backward))
{
if (mWorkflowDB->getUsage(tensorUsage[static_cast<size_t>(Usage::Forward)]).isZero || mWorkflowDB->getUsage(tensorUsage[static_cast<size_t>(Usage::Backward)]).isZero)
{
mWorkflowDB->getUsage(tensorUsage[static_cast<size_t>(Usage::Forward)]).isZero = true;
mWorkflowDB->getUsage(tensorUsage[static_cast<size_t>(Usage::Backward)]).isZero = true;
}
checkAttributesInequality(tensorUsage[static_cast<size_t>(Usage::Forward)], tensorUsage[static_cast<size_t>(Usage::Backward)], tName);
}
uniqueTensors.insert({ tName, tensorUsage[static_cast<size_t>(tUsage)] });
}
}
}
catch (...)
{
THROW_NONAME("WorkflowEager", "Cannot process layer `" + lName + "`");
}
}
// create pipelines
execTargetCreateAuxPipelines(uniqueTensors);
for (const auto& layer : mLayers)
{
mPipelineCreateBatched.push_back(std::make_shared<UpdateBS>(layer.get(), *this));
}
}
catch (...)
{
THROW_NONAME("WorkflowEager", "Cannot create auxiliary pipelines");
}
}
void WorkflowEager::execTargetCreateAuxPipelines(const std::unordered_map<Name, size_t>& uniqueTensors)
{
for (const auto& uniqueTensor : uniqueTensors)
{
const WorkflowDB::TensorUsage& usage = mWorkflowDB->getUsage(uniqueTensor.second);
if (usage.shape.isBSDependent())
{
mPipelineCreateBatched.push_back(newActionCreateTensor(usage.tensorName, usage.layerExecutionTarget, usage.shape));
mPipelineDeleteBatched.push_back(newActionDeleteTensor(usage.tensorName, usage.layerExecutionTarget));
}
else
{
mPipelineCreateNotBatched.push_back(newActionCreateTensor(usage.tensorName, usage.layerExecutionTarget, usage.shape));
}
if (usage.isZero)
{
mPipelineZeroTensors.push_back(newActionZero(usage.tensorName, usage.layerExecutionTarget));
}
}
}
void WorkflowEager::forwardPassTesting()
{
for (auto& layer : mLayers)
{
layer->forwardCompute(NetworkMode::Test);
}
}
void WorkflowEager::forwardPassTraining(bool)
{
try
{
executePipeline(Workflow::Pipelines::Zero);
}
catch (...)
{
THROW_NONAME("WorkflowEager", "Cannot execute zeroing pipeline");
}
try
{
for (auto& layer : mLayers)
{
layer->forwardCompute(NetworkMode::Train);
}
}
catch (...)
{
THROW_NONAME("WorkflowEager", "Cannot execute forward in training mode");
}
}
void WorkflowEager::backwardPassTraining()
{
try
{
for (auto it = mLayers.rbegin(); it != mLayers.rend(); ++it)
{
(*it)->backwardCompute();
}
}
catch (...)
{
THROW_NONAME("WorkflowEager", "Cannot execute backward");
}
}
} // namespace raul | 35.939163 | 194 | 0.562526 | [
"shape",
"vector"
] |
c9d3c22b1ffec07553230de42aa014622f64764f | 643 | cpp | C++ | problems/codeforces/1513/b-and-sequences/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | 7 | 2020-10-15T22:37:10.000Z | 2022-02-26T17:23:49.000Z | problems/codeforces/1513/b-and-sequences/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | problems/codeforces/1513/b-and-sequences/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
// *****
constexpr unsigned long long MOD = 1e9 + 7;
auto solve() {
int N;
cin >> N;
vector<unsigned> A(N);
for (int i = 0; i < N; i++)
cin >> A[i];
unsigned sum = accumulate(begin(A), end(A), A[0], std::bit_and<unsigned>{});
unsigned long long n = count(begin(A), end(A), sum);
unsigned long long M = n * (n - 1) % MOD;
for (int i = 1; i <= N - 2; i++)
M = (M * i) % MOD;
return M;
}
// *****
int main() {
unsigned T;
cin >> T >> ws;
for (unsigned t = 1; t <= T; ++t) {
cout << solve() << endl;
}
return 0;
}
| 18.911765 | 80 | 0.475894 | [
"vector"
] |
c9d7dbcab025f7a701713a9f30fc499413f887bc | 4,632 | cpp | C++ | core/src/editor/edit_variables.cpp | castle-xyz/castle-client | ad43c91a60b8d9137008bb752fe755a75b2ad61b | [
"MIT"
] | 20 | 2020-09-18T18:45:56.000Z | 2022-02-10T22:29:54.000Z | core/src/editor/edit_variables.cpp | castle-xyz/castle-client | ad43c91a60b8d9137008bb752fe755a75b2ad61b | [
"MIT"
] | 8 | 2021-01-27T01:02:47.000Z | 2022-03-09T16:41:48.000Z | core/src/editor/edit_variables.cpp | castle-xyz/castle-client | ad43c91a60b8d9137008bb752fe755a75b2ad61b | [
"MIT"
] | null | null | null | #include "edit_variables.h"
#include "engine.h"
//
// Read / write
//
void EditVariables::read(Reader &reader) {
variables.clear();
reader.each([&]() {
auto variableIdCStr = reader.str("id");
if (!variableIdCStr) {
return;
}
auto nameCStr = reader.str("name");
if (!nameCStr) {
return;
}
auto name = std::string(*nameCStr);
auto variableId = std::string(*variableIdCStr);
variables.emplace_back(Variable(name, variableId, reader.num("initialValue", 0)));
});
}
void EditVariables::write(Writer &writer) const {
forEach([&](const Variable &variable) {
writer.obj([&]() {
writer.str("id", variable.variableId);
writer.str("name", variable.name);
writer.num("initialValue", variable.initialValue.as<double>());
});
});
}
void EditVariables::update(
const std::string &variableId, std::string name, ExpressionValue initialValue) {
for (auto &variable : variables) {
if (variable.variableId == variableId) {
variable = EditVariables::Variable(std::move(name), variableId, initialValue);
return;
}
}
add(std::move(name), variableId, initialValue);
return;
}
//
// Events
//
struct EditorChangeVariablesReceiver {
inline static const BridgeRegistration<EditorChangeVariablesReceiver> registration {
"EDITOR_CHANGE_VARIABLES"
};
struct Params {
PROP(std::string, action);
PROP(std::string, variableId);
PROP(std::string, name);
PROP(double, initialValue);
} params;
void receive(Engine &engine) {
if (!engine.getIsEditing()) {
return;
}
auto action = params.action();
auto editor = engine.maybeGetEditor();
Commands::Params commandParams;
commandParams.coalesce = true;
commandParams.coalesceLastOnly = false;
auto variableId = params.variableId();
auto name = params.name();
auto initialValue = params.initialValue();
if (action == "add") {
editor->getCommands().execute(
"add variable", commandParams,
[variableId, name, initialValue](Editor &editor, bool) {
editor.getVariables().add(name, variableId, initialValue);
editor.getVariables().sendVariablesData(editor.getBridge(), true);
},
[variableId](Editor &editor, bool) {
editor.getVariables().remove(variableId);
editor.getVariables().sendVariablesData(editor.getBridge(), true);
});
} else if (action == "remove") {
auto existing = editor->getVariables().get(variableId);
if (existing) {
auto oldName = existing->name;
auto oldInitialValue = existing->initialValue;
editor->getCommands().execute(
"remove variable", commandParams,
[variableId](Editor &editor, bool) {
editor.getVariables().remove(variableId);
editor.getVariables().sendVariablesData(editor.getBridge(), true);
},
[variableId, oldName, oldInitialValue](Editor &editor, bool) {
editor.getVariables().add(oldName, variableId, oldInitialValue);
editor.getVariables().sendVariablesData(editor.getBridge(), true);
});
}
} else if (action == "update") {
auto existing = editor->getVariables().get(variableId);
if (existing) {
auto oldName = existing->name;
auto oldInitialValue = existing->initialValue;
editor->getCommands().execute(
"change variable", commandParams,
[variableId, name, initialValue](Editor &editor, bool) {
editor.getVariables().update(variableId, name, initialValue);
editor.getVariables().sendVariablesData(editor.getBridge(), true);
},
[variableId, oldName, oldInitialValue](Editor &editor, bool) {
editor.getVariables().update(variableId, oldName, oldInitialValue);
editor.getVariables().sendVariablesData(editor.getBridge(), true);
});
}
}
}
};
struct EditorVariablesEvent {
struct VariableData {
PROP(std::string, variableId);
PROP(std::string, name);
PROP(double, initialValue);
};
PROP(std::vector<VariableData>, variables);
PROP(bool, isChanged);
};
void EditVariables::sendVariablesData(Bridge &bridge, bool isChanged) {
EditorVariablesEvent ev;
forEach([&](const EditVariables::Variable &elem) {
EditorVariablesEvent::VariableData data { elem.variableId, elem.name,
elem.initialValue.as<double>() };
ev.variables().push_back(data);
});
ev.isChanged = isChanged;
bridge.sendEvent("EDITOR_VARIABLES", ev);
}
| 31.944828 | 86 | 0.636874 | [
"vector"
] |
c9e2b7f4c4f00b6c251f5ccc88a76b27feca7684 | 11,718 | cpp | C++ | test/old_tests/UnitTests/FastInput.cpp | sylveon/cppwinrt | 4d5c5ae3de386ce1f18c3410a27b9ceb40aa524d | [
"MIT"
] | 859 | 2016-10-13T00:11:52.000Z | 2019-05-06T15:45:46.000Z | test/old_tests/UnitTests/FastInput.cpp | shinsetsu/cppwinrt | ae0378373d2318d91448b8697a91d5b65a1fb2e5 | [
"MIT"
] | 655 | 2019-10-08T12:15:16.000Z | 2022-03-31T18:26:40.000Z | test/old_tests/UnitTests/FastInput.cpp | shinsetsu/cppwinrt | ae0378373d2318d91448b8697a91d5b65a1fb2e5 | [
"MIT"
] | 137 | 2016-10-13T04:19:59.000Z | 2018-11-09T05:08:03.000Z | #include "pch.h"
#include "catch.hpp"
#include "winrt/Component.h"
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Component;
TEST_CASE("FastInput")
{
FastInput fast;
{
REQUIRE(fast.String(L"One") == L"One");
REQUIRE(fast.String(std::wstring_view(L"One")) == L"One");
REQUIRE(fast.String(std::wstring(L"One")) == L"One");
REQUIRE(fast.String(hstring(L"One")) == L"One");
}
{
REQUIRE(fast.Array({ L"One",L"Two",L"Three" }) == L"OneTwoThree");
REQUIRE(fast.Array(std::vector<hstring>{ L"One", L"Two", L"Three" }) == L"OneTwoThree");
REQUIRE(fast.Array(std::array<hstring, 3>{ L"One", L"Two", L"Three" }) == L"OneTwoThree");
// TODO: array_view doesn't bind to... wait for it array_view or com_array.
// Need to define com_array without inheriting from array_view.
// Then array_view can bind to com_array for input and symmetry.
}
{
REQUIRE(fast.Iterable({}) == L"");
REQUIRE_THROWS_AS(fast.UseIterable(), hresult_illegal_method_call);
REQUIRE(fast.Iterable({ L"One",L"Two",L"Three" }) == L"OneTwoThree");
REQUIRE_THROWS_AS(fast.UseIterable(), hresult_illegal_method_call);
REQUIRE(fast.Iterable(std::vector<hstring>{ L"One", L"Two", L"Three" }) == L"OneTwoThree");
fast.UseIterable();
std::vector<hstring> vector{ L"One",L"Two",L"Three" };
REQUIRE(fast.Iterable(vector) == L"OneTwoThree");
REQUIRE_THROWS_AS(fast.UseIterable(), hresult_illegal_method_call);
IVector<hstring> convertible = single_threaded_vector<hstring>({ L"One",L"Two",L"Three" });
REQUIRE(fast.Iterable(convertible) == L"OneTwoThree");
fast.UseIterable();
std::array<hstring, 3> range{ L"One",L"Two",L"Three" };
REQUIRE(fast.Iterable({ range.begin(), range.end() }) == L"OneTwoThree");
REQUIRE_THROWS_AS(fast.UseIterable(), hresult_illegal_method_call);
IIterable<hstring> actual = single_threaded_vector<hstring>({ L"One",L"Two",L"Three" });
REQUIRE(fast.Iterable(actual) == L"OneTwoThree");
fast.UseIterable();
REQUIRE(fast.Iterable(nullptr) == L"nullptr");
// The following tests support for convertible initializer_list:
auto param = { L"One",L"Two",L"Three" };
REQUIRE(fast.Iterable(param) == L"OneTwoThree");
REQUIRE_THROWS_AS(fast.UseIterable(), hresult_illegal_method_call);
}
{
REQUIRE(fast.VectorView({}) == L"");
REQUIRE_THROWS_AS(fast.UseIterable(), hresult_illegal_method_call);
REQUIRE(fast.VectorView({ L"One",L"Two",L"Three" }) == L"OneTwoThree");
REQUIRE_THROWS_AS(fast.UseIterable(), hresult_illegal_method_call);
REQUIRE(fast.VectorView(std::vector<hstring>{ L"One", L"Two", L"Three" }) == L"OneTwoThree");
fast.UseIterable();
std::vector<hstring> vector{ L"One",L"Two",L"Three" };
REQUIRE(fast.VectorView(vector) == L"OneTwoThree");
REQUIRE_THROWS_AS(fast.UseIterable(), hresult_illegal_method_call);
FastInputVector convertible({ L"One",L"Two",L"Three" });
REQUIRE(fast.VectorView(convertible) == L"OneTwoThree");
fast.UseIterable();
std::array<hstring, 3> range{ L"One",L"Two",L"Three" };
REQUIRE(fast.VectorView({ range.begin(), range.end() }) == L"OneTwoThree");
REQUIRE_THROWS_AS(fast.UseIterable(), hresult_illegal_method_call);
IVectorView<hstring> actual = single_threaded_vector<hstring>({ L"One",L"Two",L"Three" }).GetView();
REQUIRE(fast.VectorView(actual) == L"OneTwoThree");
fast.UseIterable();
REQUIRE(fast.VectorView(nullptr) == L"nullptr");
// The following tests support for convertible initializer_list:
auto param = { L"One",L"Two",L"Three" };
REQUIRE(fast.VectorView(param) == L"OneTwoThree");
REQUIRE_THROWS_AS(fast.UseIterable(), hresult_illegal_method_call);
}
{
REQUIRE(fast.Vector({ L"One",L"Two",L"Three" }) == L"OneTwoThree");
fast.UseIterable();
REQUIRE(fast.Vector(std::vector<hstring>{ L"One", L"Two", L"Three" }) == L"OneTwoThree");
fast.UseIterable();
FastInputVector convertible({ L"One",L"Two",L"Three" });
REQUIRE(fast.Vector(convertible) == L"OneTwoThree");
fast.UseIterable();
IVector<hstring> actual = single_threaded_vector<hstring>({ L"One",L"Two",L"Three" });
REQUIRE(fast.Vector(actual) == L"OneTwoThree");
fast.UseIterable();
REQUIRE(fast.Vector(nullptr) == L"nullptr");
}
{
REQUIRE(fast.IterablePair({ { L"A",L"a" },{ L"B",L"b" },{ L"C",L"c" } }) == L"AaBbCc");
REQUIRE_THROWS_AS(fast.UseIterablePair(), hresult_illegal_method_call);
REQUIRE(fast.IterablePair(std::map<hstring, hstring>{ { L"A", L"a" }, { L"B",L"b" }, { L"C",L"c" } }) == L"AaBbCc");
fast.UseIterablePair();
REQUIRE(fast.IterablePair(std::unordered_map<hstring, hstring>{ { L"A", L"a" }, { L"B",L"b" }, { L"C",L"c" } }) == L"AaBbCc");
fast.UseIterablePair();
std::map<hstring, hstring> map{ { { L"A", L"a" }, { L"B",L"b" }, { L"C",L"c" } } };
REQUIRE(fast.IterablePair(map) == L"AaBbCc");
REQUIRE_THROWS_AS(fast.UseIterablePair(), hresult_illegal_method_call);
IMap<hstring, hstring> convertible = single_threaded_map<hstring, hstring>(std::map<hstring, hstring>{ { { L"A", L"a" }, { L"B",L"b" }, { L"C",L"c" } } });
REQUIRE(fast.IterablePair(convertible) == L"AaBbCc");
fast.UseIterablePair();
std::unordered_map<hstring, hstring> range{ { { L"A", L"a" }, { L"B",L"b" }, { L"C",L"c" } } };
REQUIRE(fast.IterablePair({ range.begin(), range.end() }) == L"AaBbCc");
REQUIRE_THROWS_AS(fast.UseIterablePair(), hresult_illegal_method_call);
IIterable<IKeyValuePair<hstring, hstring>> actual = single_threaded_map<hstring>(std::map<hstring, hstring>{ { { L"A", L"a" }, { L"B",L"b" }, { L"C",L"c" } } });
REQUIRE(fast.IterablePair(actual) == L"AaBbCc");
fast.UseIterablePair();
REQUIRE(fast.IterablePair(nullptr) == L"nullptr");
}
{
REQUIRE(fast.MapView({ { L"A",L"a" },{ L"B",L"b" },{ L"C",L"c" } }) == L"AaBbCc");
fast.UseIterablePair();
REQUIRE(fast.MapView(std::map<hstring, hstring>{ { L"A", L"a" }, { L"B",L"b" }, { L"C",L"c" } }) == L"AaBbCc");
fast.UseIterablePair();
REQUIRE(fast.MapView(std::unordered_map<hstring, hstring>{ { L"A", L"a" }, { L"B",L"b" }, { L"C",L"c" } }) == L"AaBbCc");
fast.UseIterablePair();
std::map<hstring, hstring> map{ { { L"A", L"a" },{ L"B",L"b" },{ L"C",L"c" } } };
REQUIRE(fast.MapView(map) == L"AaBbCc");
REQUIRE_THROWS_AS(fast.UseIterablePair(), hresult_illegal_method_call);
FastInputMap convertible({ { L"A", L"a" }, { L"B",L"b" }, { L"C",L"c" } });
REQUIRE(fast.MapView(convertible) == L"AaBbCc");
fast.UseIterablePair();
IMapView<hstring, hstring> actual = FastInputMap({ { L"A", L"a" },{ L"B",L"b" },{ L"C",L"c" } });
REQUIRE(fast.MapView(actual) == L"AaBbCc");
fast.UseIterablePair();
REQUIRE(fast.MapView(nullptr) == L"nullptr");
}
{
REQUIRE(fast.Map({ { L"A",L"a" },{ L"B",L"b" },{ L"C",L"c" } }) == L"AaBbCc");
fast.UseIterablePair();
REQUIRE(fast.Map(std::map<hstring, hstring>{ { L"A", L"a" }, { L"B",L"b" }, { L"C",L"c" } }) == L"AaBbCc");
fast.UseIterablePair();
REQUIRE(fast.Map(std::unordered_map<hstring, hstring>{ { L"A", L"a" }, { L"B",L"b" }, { L"C",L"c" } }) == L"AaBbCc");
fast.UseIterablePair();
FastInputMap convertible({ { L"A", L"a" },{ L"B",L"b" },{ L"C",L"c" } });
REQUIRE(fast.Map(convertible) == L"AaBbCc");
fast.UseIterablePair();
IMap<hstring, hstring> actual = FastInputMap({ { L"A", L"a" },{ L"B",L"b" },{ L"C",L"c" } });
REQUIRE(fast.Map(actual) == L"AaBbCc");
fast.UseIterablePair();
REQUIRE(fast.Map(nullptr) == L"nullptr");
}
{
REQUIRE(fast.IterableAsync({ L"One",L"Two",L"Three" }).get() == L"OneTwoThree");
fast.UseIterable();
REQUIRE(fast.IterableAsync(std::vector<hstring>{ L"One", L"Two", L"Three" }).get() == L"OneTwoThree");
fast.UseIterable();
IVector<hstring> convertible = single_threaded_vector<hstring>({ L"One",L"Two",L"Three" });
REQUIRE(fast.IterableAsync(convertible).get() == L"OneTwoThree");
fast.UseIterable();
IIterable<hstring> actual = single_threaded_vector<hstring>({ L"One",L"Two",L"Three" });
REQUIRE(fast.IterableAsync(actual).get() == L"OneTwoThree");
fast.UseIterable();
REQUIRE(fast.IterableAsync(nullptr).get() == L"nullptr");
}
{
REQUIRE(fast.VectorViewAsync({ L"One",L"Two",L"Three" }).get() == L"OneTwoThree");
fast.UseIterable();
REQUIRE(fast.VectorViewAsync(std::vector<hstring>{ L"One", L"Two", L"Three" }).get() == L"OneTwoThree");
fast.UseIterable();
FastInputVector convertible({ L"One",L"Two",L"Three" });
REQUIRE(fast.VectorViewAsync(convertible).get() == L"OneTwoThree");
fast.UseIterable();
IVectorView<hstring> actual = single_threaded_vector<hstring>({ L"One",L"Two",L"Three" }).GetView();
REQUIRE(fast.VectorViewAsync(actual).get() == L"OneTwoThree");
fast.UseIterable();
REQUIRE(fast.VectorViewAsync(nullptr).get() == L"nullptr");
}
{
REQUIRE(fast.IterablePairAsync({ { L"A",L"a" },{ L"B",L"b" },{ L"C",L"c" } }).get() == L"AaBbCc");
fast.UseIterablePair();
REQUIRE(fast.IterablePairAsync(std::map<hstring, hstring>{ { L"A", L"a" }, { L"B",L"b" }, { L"C",L"c" } }).get() == L"AaBbCc");
fast.UseIterablePair();
REQUIRE(fast.IterablePairAsync(std::unordered_map<hstring, hstring>{ { L"A", L"a" }, { L"B",L"b" }, { L"C",L"c" } }).get() == L"AaBbCc");
fast.UseIterablePair();
IMap<hstring, hstring> convertible = single_threaded_map<hstring, hstring>(std::map<hstring, hstring>{ { { L"A", L"a" }, { L"B",L"b" }, { L"C",L"c" } } });
REQUIRE(fast.IterablePairAsync(convertible).get() == L"AaBbCc");
fast.UseIterablePair();
IIterable<IKeyValuePair<hstring, hstring>> actual = single_threaded_map<hstring>(std::map<hstring, hstring>{ { { L"A", L"a" }, { L"B",L"b" }, { L"C",L"c" } } });
REQUIRE(fast.IterablePairAsync(actual).get() == L"AaBbCc");
fast.UseIterablePair();
REQUIRE(fast.IterablePairAsync(nullptr).get() == L"nullptr");
}
{
REQUIRE(fast.MapViewAsync({ { L"A",L"a" },{ L"B",L"b" },{ L"C",L"c" } }).get() == L"AaBbCc");
fast.UseIterablePair();
REQUIRE(fast.MapViewAsync(std::map<hstring, hstring>{ { L"A", L"a" }, { L"B",L"b" }, { L"C",L"c" } }).get() == L"AaBbCc");
fast.UseIterablePair();
REQUIRE(fast.MapViewAsync(std::unordered_map<hstring, hstring>{ { L"A", L"a" }, { L"B",L"b" }, { L"C",L"c" } }).get() == L"AaBbCc");
fast.UseIterablePair();
FastInputMap convertible({ { L"A", L"a" },{ L"B",L"b" },{ L"C",L"c" } });
REQUIRE(fast.MapViewAsync(convertible).get() == L"AaBbCc");
fast.UseIterablePair();
IMapView<hstring, hstring> actual = FastInputMap({ { L"A", L"a" },{ L"B",L"b" },{ L"C",L"c" } });
REQUIRE(fast.MapViewAsync(actual).get() == L"AaBbCc");
fast.UseIterablePair();
REQUIRE(fast.MapViewAsync(nullptr).get() == L"nullptr");
}
}
| 43.4 | 169 | 0.587899 | [
"vector"
] |
5190bb3990acff177c9c5b88551c1273ac311b3b | 1,478 | hpp | C++ | cpp/Containers/DemoVector/aqueue.hpp | ArboreusSystems/arboreus_examples | 17d39e18f4b2511c19f97d4e6c07ec9d7087fae8 | [
"BSD-3-Clause"
] | 17 | 2019-02-19T21:29:22.000Z | 2022-01-29T11:03:45.000Z | cpp/Containers/DemoVector/aqueue.hpp | MbohBless/arboreus_examples | 97f0e25182bbc4b5ffab37c6157514332002aeee | [
"BSD-3-Clause"
] | null | null | null | cpp/Containers/DemoVector/aqueue.hpp | MbohBless/arboreus_examples | 97f0e25182bbc4b5ffab37c6157514332002aeee | [
"BSD-3-Clause"
] | 9 | 2021-02-21T05:32:23.000Z | 2022-02-26T07:51:52.000Z | // ----------------------------------------------------------
/*!
\class AQueue
\title
\brief Template file files/cppheader/file.h
\list
\li @notice Template file classes/file.h
\li @copyright Arboreus (http://arboreus.systems)
\li @author Alexandr Kirilov (http://alexandr.kirilov.me)
\li @created 20/01/2020 at 20:52:27
\endlist
*/
// ----------------------------------------------------------
// Class header
#include "aqueue.h"
using namespace std;
// -----------
/*!
\fn
Doc.
*/
template <class Type>
AQueue<Type>::AQueue(void) {
ALOG << "AQueue created" << endl;
}
// -----------
/*!
\fn
Doc.
*/
template <class Type>
AQueue<Type>::~AQueue(void) {
ALOG << "AQueue deleted" << endl;
}
// -----------
/*!
\fn
Doc.
*/
template <class Type>
Type AQueue<Type>::mGet(void) {
Type oElement = pStorage.back();
pStorage.pop_back();
return oElement;
}
// -----------
/*!
\fn
Doc.
*/
template <class Type>
std::vector<Type> AQueue<Type>::mGetAll(void) {
return pStorage;
}
// -----------
/*!
\fn
Doc.
*/
template <class Type>
void AQueue<Type>::mPut(Type inElement) {
pStorage.insert(pStorage.begin(),inElement);
}
// -----------
/*!
\fn
Doc.
*/
template <class Type>
int AQueue<Type>::mSize(void) {
return static_cast<int>(pStorage.size());
}
// -----------
/*!
\fn
Doc.
*/
template <class Type>
bool AQueue<Type>::mIsEmpty(void) {
if (static_cast<int>(pStorage.size()) == 0) {
return true;
}
return false;
}
| 12.114754 | 61 | 0.541949 | [
"vector"
] |
519187e459d14220d5490ab145a3ffcf22341e0b | 912 | cpp | C++ | avogadro/tooltipfilter.cpp | adityanarayanm095/avogadroapp | 1452c4707e50c7e1c27c610219f0bef955a0572c | [
"BSD-3-Clause"
] | 113 | 2015-01-21T22:39:50.000Z | 2022-03-15T22:02:21.000Z | avogadro/tooltipfilter.cpp | adityanarayanm095/avogadroapp | 1452c4707e50c7e1c27c610219f0bef955a0572c | [
"BSD-3-Clause"
] | 122 | 2015-04-10T17:04:33.000Z | 2022-03-11T21:02:31.000Z | avogadro/tooltipfilter.cpp | adityanarayanm095/avogadroapp | 1452c4707e50c7e1c27c610219f0bef955a0572c | [
"BSD-3-Clause"
] | 61 | 2015-01-29T16:23:59.000Z | 2022-03-10T13:16:41.000Z | /******************************************************************************
This source file is part of the Avogadro project.
This source code is released under the 3-Clause BSD License, (see "LICENSE").
******************************************************************************/
#include "tooltipfilter.h"
#include <QtCore/QEvent>
#include <QtGui/QEnterEvent>
#include <QtWidgets/QToolTip>
#include <QtWidgets/QWidget>
ToolTipFilter::ToolTipFilter(QObject* parent)
: QObject(parent)
{}
bool ToolTipFilter::eventFilter(QObject* object, QEvent* event)
{
// Fire off a toolTip item for an enter event
if (event->type() == QEvent::Enter) {
QWidget* target = qobject_cast<QWidget*>(object);
QEnterEvent* ee = dynamic_cast<QEnterEvent*>(event);
if (target && ee) {
QToolTip::showText(ee->globalPos(), target->toolTip(), target);
return true;
}
}
return false;
}
| 29.419355 | 79 | 0.575658 | [
"object"
] |
5194221e92d7ac40ddc876158e6edf0ebe7df648 | 781 | cpp | C++ | src/nc/core/ir/vars/Variable.cpp | treadstoneproject/tracethreat_nrml | bcf666b01c20f7da4234fed018dad3b2cf4d3d28 | [
"Apache-2.0"
] | 6 | 2016-09-06T02:10:08.000Z | 2021-01-19T09:02:04.000Z | src/nc/core/ir/vars/Variable.cpp | treadstoneproject/tracethreat_nrml | bcf666b01c20f7da4234fed018dad3b2cf4d3d28 | [
"Apache-2.0"
] | null | null | null | src/nc/core/ir/vars/Variable.cpp | treadstoneproject/tracethreat_nrml | bcf666b01c20f7da4234fed018dad3b2cf4d3d28 | [
"Apache-2.0"
] | 6 | 2015-10-02T14:11:45.000Z | 2021-01-19T09:02:07.000Z | /* The file is part of Snowman decompiler. */
/* See doc/licenses.asciidoc for the licensing information. */
#include "Variable.h"
#include <numeric> /* std::accumulate */
namespace nc {
namespace core {
namespace ir {
namespace vars {
Variable::Variable(Scope scope, std::vector<TermAndLocation> termsAndLocations):
scope_(scope), termsAndLocations_(std::move(termsAndLocations))
{
assert(!termsAndLocations_.empty());
memoryLocation_ = std::accumulate(termsAndLocations_.begin(), termsAndLocations_.end(), MemoryLocation(),
[](const MemoryLocation &a, const TermAndLocation &b) {
return MemoryLocation::merge(a, b.location);
});
}
} // namespace vars
} // namespace ir
} // namespace core
} // namespace nc
/* vim:set et sts=4 sw=4: */
| 26.033333 | 109 | 0.697823 | [
"vector"
] |
51978f3e2c80fce43df65c9bc68e4741134cdccb | 12,461 | cpp | C++ | samples/PlatformInfo/FlexiTimer2.cpp | apla/cuwire | a9f9a7ab9cd799415adb8ae7cdcbb985b975578d | [
"Unlicense"
] | 70 | 2015-02-05T09:18:51.000Z | 2021-04-15T19:06:22.000Z | samples/PlatformInfo/FlexiTimer2.cpp | apla/cuwire | a9f9a7ab9cd799415adb8ae7cdcbb985b975578d | [
"Unlicense"
] | 5 | 2015-02-03T21:46:53.000Z | 2015-04-08T01:03:54.000Z | samples/PlatformInfo/FlexiTimer2.cpp | apla/cuwire | a9f9a7ab9cd799415adb8ae7cdcbb985b975578d | [
"Unlicense"
] | 2 | 2015-03-26T08:32:04.000Z | 2022-01-30T08:41:54.000Z | /*
FlexiTimer2.h - Using timer2 with a configurable resolution
Wim Leers <work@wimleers.com>
Based on MsTimer2
Javier Valencia <javiervalencia80@gmail.com>
History:
6/Jun/2014 - Added Teensy 3.0 & 3.1 support
16/Dec/2011 - Added Teensy/Teensy++ support (bperrybap)
note: teensy uses timer4 instead of timer2
25/April/10 - Based on MsTimer2 V0.5 (from 29/May/09)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "FlexiTimer2.h"
unsigned long FlexiTimer2::time_units;
void (*FlexiTimer2::func)();
volatile unsigned long FlexiTimer2::count;
volatile char FlexiTimer2::overflowing;
volatile unsigned int FlexiTimer2::tcnt2;
#if defined(__arm__) && defined(TEENSYDUINO)
static IntervalTimer itimer;
#endif
void FlexiTimer2::set(unsigned long ms, void (*f)()) {
FlexiTimer2::set(ms, 0.001, f);
}
double hzFromSeconds (double seconds) {
return 1.0/seconds;
}
/**
* @param resolution
* 0.001 implies a 1 ms (1/1000s = 0.001s = 1ms) resolution. Therefore,
* 0.0005 implies a 0.5 ms (1/2000s) resolution. And so on.
*/
void FlexiTimer2::set(unsigned long units, double resolution, void (*f)()) {
float prescaler = 0.0;
if (units == 0)
time_units = 1;
else
time_units = units;
func = f;
#if defined (__AVR_ATmega168__) || defined (__AVR_ATmega48__) || defined (__AVR_ATmega88__) || defined (__AVR_ATmega328P__) || defined (__AVR_ATmega1280__) || defined (__AVR_ATmega2560__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
TIMSK2 &= ~(1<<TOIE2);
TCCR2A &= ~((1<<WGM21) | (1<<WGM20));
TCCR2B &= ~(1<<WGM22);
ASSR &= ~(1<<AS2);
TIMSK2 &= ~(1<<OCIE2A);
if ((F_CPU >= 1000000UL) && (F_CPU <= 16000000UL)) { // prescaler set to 64
TCCR2B |= (1<<CS22);
TCCR2B &= ~((1<<CS21) | (1<<CS20));
prescaler = 64.0;
} else if (F_CPU < 1000000UL) { // prescaler set to 8
TCCR2B |= (1<<CS21);
TCCR2B &= ~((1<<CS22) | (1<<CS20));
prescaler = 8.0;
} else { // F_CPU > 16Mhz, prescaler set to 128
TCCR2B |= ((1<<CS22) | (1<<CS20));
TCCR2B &= ~(1<<CS21);
prescaler = 128.0;
}
#elif defined (__AVR_ATmega8__)
TIMSK &= ~(1<<TOIE2);
TCCR2 &= ~((1<<WGM21) | (1<<WGM20));
TIMSK &= ~(1<<OCIE2);
ASSR &= ~(1<<AS2);
if ((F_CPU >= 1000000UL) && (F_CPU <= 16000000UL)) { // prescaler set to 64
TCCR2 |= (1<<CS22);
TCCR2 &= ~((1<<CS21) | (1<<CS20));
prescaler = 64.0;
} else if (F_CPU < 1000000UL) { // prescaler set to 8
TCCR2 |= (1<<CS21);
TCCR2 &= ~((1<<CS22) | (1<<CS20));
prescaler = 8.0;
} else { // F_CPU > 16Mhz, prescaler set to 128
TCCR2 |= ((1<<CS22) && (1<<CS20));
TCCR2 &= ~(1<<CS21);
prescaler = 128.0;
}
#elif defined (__AVR_ATmega128__)
TIMSK &= ~(1<<TOIE2);
TCCR2 &= ~((1<<WGM21) | (1<<WGM20));
TIMSK &= ~(1<<OCIE2);
if ((F_CPU >= 1000000UL) && (F_CPU <= 16000000UL)) { // prescaler set to 64
TCCR2 |= ((1<<CS21) | (1<<CS20));
TCCR2 &= ~(1<<CS22);
prescaler = 64.0;
} else if (F_CPU < 1000000UL) { // prescaler set to 8
TCCR2 |= (1<<CS21);
TCCR2 &= ~((1<<CS22) | (1<<CS20));
prescaler = 8.0;
} else { // F_CPU > 16Mhz, prescaler set to 256
TCCR2 |= (1<<CS22);
TCCR2 &= ~((1<<CS21) | (1<<CS20));
prescaler = 256.0;
}
#elif defined (__AVR_ATmega32U4__)
TCCR4B = 0;
TCCR4A = 0;
TCCR4C = 0;
TCCR4D = 0;
TCCR4E = 0;
if (F_CPU >= 16000000L) {
TCCR4B = (1<<CS43) | (1<<PSR4);
prescaler = 128.0;
} else if (F_CPU >= 8000000L) {
TCCR4B = (1<<CS42) | (1<<CS41) | (1<<CS40) | (1<<PSR4);
prescaler = 64.0;
} else if (F_CPU >= 4000000L) {
TCCR4B = (1<<CS42) | (1<<CS41) | (1<<PSR4);
prescaler = 32.0;
} else if (F_CPU >= 2000000L) {
TCCR4B = (1<<CS42) | (1<<CS40) | (1<<PSR4);
prescaler = 16.0;
} else if (F_CPU >= 1000000L) {
TCCR4B = (1<<CS42) | (1<<PSR4);
prescaler = 8.0;
} else if (F_CPU >= 500000L) {
TCCR4B = (1<<CS41) | (1<<CS40) | (1<<PSR4);
prescaler = 4.0;
} else {
TCCR4B = (1<<CS41) | (1<<PSR4);
prescaler = 2.0;
}
tcnt2 = (int)((float)F_CPU * resolution / prescaler) - 1;
OCR4C = tcnt2;
return;
#elif defined(__arm__) && defined(TEENSYDUINO)
// TODO: should this emulate the limitations and numerical
// range bugs from the versions above?
tcnt2 = resolution * 1000000.0;
return;
#elif defined(__RFduino__)
// http://forum.rfduino.com/index.php?topic=155.0
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Conversion to make cycle calculation easy
// Since the cycle is 32 uS hence to generate cycles in mS we need 1000 uS
// 1000/32 = 31.25 Hence we need a multiplication factor of 31.25 to the required cycle time to achive it
// e.g to get a delay of 10 mS we would do
// NRF_TIMER2->CC[0] = (10*31)+(10/4);
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
unsigned int ms = resolution * 1000.0;
tcnt2 = (ms * 31) + (ms / 4);
#elif defined(__MSP430_CPU__)
// https://kb8ojh.net/msp430/slow_timer.html
// http://homepages.ius.edu/RWISMAN/C335/HTML/msp430Timer.HTM
// we using 12kHz clock
// check 16bit overflow
tcnt2 = resolution*12000; // Count limit (16 bit)
return;
#elif defined(__TIVA__)
ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER0);
ROM_TimerConfigure(TIMER0_BASE, TIMER_CFG_PERIODIC); // 32 bits Timer
double Hz = 1.0/(resolution/10.0); // frequency in Hz
tcnt2 = (SysCtlClockGet() / Hz)/ 2;
tcnt2 = (SysCtlClockGet() / 1)/ 2;
return;
#elif defined(STM32_MCU_SERIES)
tcnt2 = resolution*1000000; // 1MHz clock
#else
#error Unsupported CPU type
#endif
tcnt2 = 256 - (int)((float)F_CPU * resolution / prescaler);
}
void TIMER2_Interrupt(void);
#if defined(STM32_MCU_SERIES)
void timer_handler(void) {
FlexiTimer2::_overflow();
}
#endif
#if defined(__TIVA__)
void Timer0Isr(void) {
ROM_TimerIntClear(TIMER0_BASE, TIMER_TIMA_TIMEOUT); // Clear the timer interrupt
FlexiTimer2::_overflow();
}
#endif
#if defined(__MSP430_CPU__)
#pragma vector=TIMER1_A0_VECTOR // Timer1 A0 interrupt service routine
__interrupt void Timer1_A0 (void) {
FlexiTimer2::_overflow();
}
#endif
void FlexiTimer2::start() {
count = 0;
overflowing = 0;
#if defined (__AVR_ATmega168__) || defined (__AVR_ATmega48__) || defined (__AVR_ATmega88__) || defined (__AVR_ATmega328P__) || defined (__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
TCNT2 = tcnt2;
TIMSK2 |= (1<<TOIE2);
#elif defined (__AVR_ATmega128__)
TCNT2 = tcnt2;
TIMSK |= (1<<TOIE2);
#elif defined (__AVR_ATmega8__)
TCNT2 = tcnt2;
TIMSK |= (1<<TOIE2);
#elif defined (__AVR_ATmega32U4__)
TIFR4 = (1<<TOV4);
TCNT4 = 0;
TIMSK4 = (1<<TOIE4);
#elif defined(__arm__) && defined(TEENSYDUINO)
itimer.begin(FlexiTimer2::_overflow, tcnt2);
#elif defined(__RFduino__)
// http://forum.rfduino.com/index.php?topic=155.0
NRF_TIMER2->TASKS_STOP = 1; // Stop timer
NRF_TIMER2->MODE = TIMER_MODE_MODE_Timer; // sets the timer to TIME mode (doesn't make sense but OK!)
NRF_TIMER2->BITMODE = TIMER_BITMODE_BITMODE_16Bit; // with BLE only Timer 1 and Timer 2 and that too only in 16bit mode
NRF_TIMER2->PRESCALER = 9; // Prescaler 9 produces 31250 Hz timer frequency => t = 1/f => 32 uS
// The figure 31250 Hz is generated by the formula (16M) / (2^n)
// where n is the prescaler value
// hence (16M)/(2^9)=31250
NRF_TIMER2->TASKS_CLEAR = 1; // Clear timer
NRF_TIMER2->CC[0] = tcnt2; //CC[0] register holds interval count value i.e your desired cycle
// Enable COMAPRE0 Interrupt
NRF_TIMER2->INTENSET = TIMER_INTENSET_COMPARE0_Enabled << TIMER_INTENSET_COMPARE0_Pos;
// Count then Complete mode enabled
NRF_TIMER2->SHORTS = (TIMER_SHORTS_COMPARE0_CLEAR_Enabled << TIMER_SHORTS_COMPARE0_CLEAR_Pos);
// also used in variant.cpp in the RFduino2.2 folder to configure the RTC1
attachInterrupt(TIMER2_IRQn, TIMER2_Interrupt);
// Start TIMER
NRF_TIMER2->TASKS_START = 1;
#elif defined(__MSP430_CPU__)
TA1CTL &= ~MC1|MC0; // stop timer A1
TA1CTL |= TACLR; // clear timer A1
// we can use different clock sources:
//TASSEL_0 = TACLK
//TASSEL_1 = ACLK @ 12KHz.
//TASSEL_2 = SMCLK @ 1MHz
//TASSEL_3 = INCLK
TA1CTL = TASSEL_1 + MC_1; // Timer A1 with ACLK, count UP
TA1CCTL0 = 0x10; // Enable Timer A1 interrupts, bit 4=1
TA1CCR0 = tcnt2;
_BIS_SR(LPM0_bits + GIE); // LPM0 (low power mode) interrupts enabled
#elif defined(__TIVA__)
//ROM_SysCtlClockSet(SYSCTL_SYSDIV_2_5|SYSCTL_USE_PLL|SYSCTL_XTAL_16MHZ|SYSCTL_OSC_MAIN);
SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER0);
//TimerIntRegister(TIMER0_BASE, TIMER_A, timer0_interrupt);
TimerConfigure(TIMER0_BASE, TIMER_CFG_PERIODIC); //TIMER_CFG_32_BIT_PER deprecated use CFG_PERIODIC
TimerLoadSet(TIMER0_BASE, TIMER_A, tcnt2 -1);
//IntEnable(INT_TIMER0A);
TimerIntEnable(TIMER0_BASE, TIMER_TIMA_TIMEOUT);
TimerEnable(TIMER0_BASE, TIMER_A);
TimerIntRegister(TIMER0_BASE, TIMER_A, Timer0Isr);
// TimerIntRegister(TIMER0_BASE, TIMER_A, Timer0Isr); // Registering isr
// ROM_TimerEnable(TIMER0_BASE, TIMER_A);
// ROM_IntEnable(INT_TIMER0A);
// ROM_TimerIntEnable(TIMER0_BASE, TIMER_TIMA_TIMEOUT);
// ROM_TimerLoadSet(TIMER0_BASE, TIMER_A, tcnt2);
#elif defined(STM32_MCU_SERIES)
// Setup LED Timer
Timer2.setChannel1Mode(TIMER_OUTPUTCOMPARE);
Timer2.setPeriod(tcnt2); // in microseconds
Timer2.setCompare1(1); // overflow might be small
Timer2.attachCompare1Interrupt(timer_handler);
#endif
}
void FlexiTimer2::stop() {
#if defined (__AVR_ATmega168__) || defined (__AVR_ATmega48__) || defined (__AVR_ATmega88__) || defined (__AVR_ATmega328P__) || defined (__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
TIMSK2 &= ~(1<<TOIE2);
#elif defined (__AVR_ATmega128__)
TIMSK &= ~(1<<TOIE2);
#elif defined (__AVR_ATmega8__)
TIMSK &= ~(1<<TOIE2);
#elif defined (__AVR_ATmega32U4__)
TIMSK4 = 0;
#elif defined(__arm__) && defined(TEENSYDUINO)
itimer.end();
#elif defined(__RFduino__)
NRF_TIMER2->TASKS_STOP = 1; // Stop timer
NRF_TIMER2->TASKS_CLEAR = 1; // Clear timer
// TODO: do i need to do more? detachInterrupt?
#elif defined(__MSP430_CPU__)
TA1CTL &= ~MC1|MC0; // stop timer A1
TA1CTL |= TACLR; // clear timer A1
#elif defined(__TIVA__)
ROM_TimerIntClear(TIMER0_BASE, TIMER_TIMA_TIMEOUT);
#endif
}
void FlexiTimer2::_overflow() {
count += 1;
if (count >= time_units && !overflowing) {
overflowing = 1;
count = count - time_units; // subtract time_uints to catch missed overflows
// set to 0 if you don't want this.
(*func)();
overflowing = 0;
}
}
#if defined (__AVR__)
#if defined (__AVR_ATmega32U4__)
ISR(TIMER4_OVF_vect) {
#else
ISR(TIMER2_OVF_vect) {
#endif
#if defined (__AVR_ATmega168__) || defined (__AVR_ATmega48__) || defined (__AVR_ATmega88__) || defined (__AVR_ATmega328P__) || defined (__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
TCNT2 = FlexiTimer2::tcnt2;
#elif defined (__AVR_ATmega128__)
TCNT2 = FlexiTimer2::tcnt2;
#elif defined (__AVR_ATmega8__)
TCNT2 = FlexiTimer2::tcnt2;
#elif defined (__AVR_ATmega32U4__)
// not necessary on 32u4's high speed timer4
#endif
FlexiTimer2::_overflow();
}
#endif // AVR
#if defined(__RFduino__)
// generate the square wave
void TIMER2_Interrupt(void) {
if (NRF_TIMER2->EVENTS_COMPARE[0] != 0) {
FlexiTimer2::_overflow();
NRF_TIMER2->EVENTS_COMPARE[0] = 0;
}
}
#endif
| 35.101408 | 251 | 0.659096 | [
"vector"
] |
519fcc48e844ed75828ee1efe40fee3241346ddb | 1,599 | cpp | C++ | Source Code/Core/Resources/ConcreteLoaders/Sphere3DLoaderImpl.cpp | IonutCava/trunk | 19dc976bbd7dc637f467785bd0ca15f34bc31ed5 | [
"MIT"
] | null | null | null | Source Code/Core/Resources/ConcreteLoaders/Sphere3DLoaderImpl.cpp | IonutCava/trunk | 19dc976bbd7dc637f467785bd0ca15f34bc31ed5 | [
"MIT"
] | null | null | null | Source Code/Core/Resources/ConcreteLoaders/Sphere3DLoaderImpl.cpp | IonutCava/trunk | 19dc976bbd7dc637f467785bd0ca15f34bc31ed5 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "Core/Headers/PlatformContext.h"
#include "Core/Resources/Headers/ResourceLoader.h"
#include "Core/Resources/Headers/ResourceCache.h"
#include "Geometry/Material/Headers/Material.h"
#include "Geometry/Shapes/Predefined/Headers/Sphere3D.h"
namespace Divide {
CachedResource_ptr ImplResourceLoader<Sphere3D>::operator()() {
constexpr F32 s_minRadius = 0.0001f;
std::shared_ptr<Sphere3D> ptr(MemoryManager_NEW Sphere3D(_context.gfx(),
_cache,
_loadingDescriptorHash,
_descriptor.resourceName(),
std::max(Util::UINT_TO_FLOAT(_descriptor.enumValue()), s_minRadius),
_descriptor.ID() == 0u
? 16u
: _descriptor.ID()),
DeleteResource(_cache));
if (!_descriptor.flag()) {
const ResourceDescriptor matDesc("Material_" + _descriptor.resourceName());
Material_ptr matTemp = CreateResource<Material>(_cache, matDesc);
matTemp->properties().shadingMode(ShadingMode::PBR_MR);
ptr->setMaterialTpl(matTemp);
}
if (!Load(ptr)) {
ptr.reset();
}
return ptr;
}
}
| 41 | 132 | 0.473421 | [
"geometry"
] |
51a98f271392e2188e7ae762af378093274b2403 | 2,314 | cpp | C++ | middleware/domain/unittest/source/manager/test_api.cpp | casualcore/casual | 047a4eaabbba52ad3ce63dc698a9325ad5fcec6d | [
"MIT"
] | null | null | null | middleware/domain/unittest/source/manager/test_api.cpp | casualcore/casual | 047a4eaabbba52ad3ce63dc698a9325ad5fcec6d | [
"MIT"
] | null | null | null | middleware/domain/unittest/source/manager/test_api.cpp | casualcore/casual | 047a4eaabbba52ad3ce63dc698a9325ad5fcec6d | [
"MIT"
] | 1 | 2022-02-21T18:30:25.000Z | 2022-02-21T18:30:25.000Z | //!
//! Copyright (c) 2019, The casual project
//!
//! This software is licensed under the MIT license, https://opensource.org/licenses/MIT
//!
#include "common/unittest.h"
#include "casual/domain/manager/api/internal/transform.h"
#include "domain/manager/admin/server.h"
#include "domain/manager/unittest/process.h"
#include "../../include/unittest/call.h"
namespace casual
{
using namespace common;
namespace domain
{
namespace manager
{
namespace api
{
namespace local
{
namespace
{
auto is_server = []( auto alias)
{
return [alias = std::move( alias)]( auto& server)
{
return server.alias == alias;
};
};
namespace call
{
auto state()
{
// we do the 'hack' call, and transform the result.
return api::internal::transform::state( unittest::call< admin::model::State>( admin::service::name::state));
}
}
} // <unnamed>
} // local
TEST( domain_manager_api, state)
{
common::unittest::Trace trace;
auto then = platform::time::clock::type::now();
constexpr auto configuration = R"(
domain:
name: simple-server
servers:
- path: ./bin/test-simple-server
instances: 1
)";
unittest::Process manager{ { configuration}};
auto state = local::call::state();
auto found = algorithm::find_if( state.servers, local::is_server( "test-simple-server"));
ASSERT_TRUE( found);
ASSERT_TRUE( found->instances.size() == 1);
{
auto& instance = found->instances.at( 0);
EXPECT_TRUE( instance.state == decltype( instance.state)::running);
EXPECT_TRUE( instance.spawnpoint > then);
EXPECT_TRUE( instance.spawnpoint < platform::time::clock::type::now());
}
}
} // api
} // manager
} // domain
} // casual | 27.879518 | 132 | 0.484875 | [
"model",
"transform"
] |
51a9f07ffff3665df1db46f1ae2ff3fe30e0925d | 598 | hpp | C++ | ut/test-contracts/integration_test/integration_test.hpp | fredgrid/bvs | a172d67933ac68ee46aec6db9cc656852e7bcae0 | [
"MIT"
] | 7 | 2019-06-12T01:29:34.000Z | 2022-01-13T17:06:25.000Z | ut/test-contracts/integration_test/integration_test.hpp | fredgrid/bvs | a172d67933ac68ee46aec6db9cc656852e7bcae0 | [
"MIT"
] | null | null | null | ut/test-contracts/integration_test/integration_test.hpp | fredgrid/bvs | a172d67933ac68ee46aec6db9cc656852e7bcae0 | [
"MIT"
] | 1 | 2019-06-10T01:49:49.000Z | 2019-06-10T01:49:49.000Z | /**
* @file
* @copyright defined in bvs/LICENSE
*/
#pragma once
#include <bvsio/bvsio.hpp>
class [[bvsio::contract]] integration_test : public bvsio::contract {
public:
using bvsio::contract::contract;
[[bvsio::action]]
void store( bvsio::name from, bvsio::name to, uint64_t num );
struct [[bvsio::table("payloads")]] payload {
uint64_t key;
std::vector<uint64_t> data;
uint64_t primary_key()const { return key; }
BVSLIB_SERIALIZE( payload, (key)(data) )
};
using payloads_table = bvsio::multi_index< "payloads"_n, payload >;
};
| 21.357143 | 71 | 0.635452 | [
"vector"
] |
51aeceedd1f1d13e09a45254d4e3711e25b61d86 | 2,565 | cpp | C++ | generated-sources/cpp-qt5/mojang-api/client/com.github.asyncmc.mojang.api.cpp.qt5.model/OAISecurityQuestion.cpp | AsyncMC/Mojang-API-Libs | b01bbd2bce44bfa2b9ed705a128cf4ecda077916 | [
"Apache-2.0"
] | null | null | null | generated-sources/cpp-qt5/mojang-api/client/com.github.asyncmc.mojang.api.cpp.qt5.model/OAISecurityQuestion.cpp | AsyncMC/Mojang-API-Libs | b01bbd2bce44bfa2b9ed705a128cf4ecda077916 | [
"Apache-2.0"
] | null | null | null | generated-sources/cpp-qt5/mojang-api/client/com.github.asyncmc.mojang.api.cpp.qt5.model/OAISecurityQuestion.cpp | AsyncMC/Mojang-API-Libs | b01bbd2bce44bfa2b9ed705a128cf4ecda077916 | [
"Apache-2.0"
] | null | null | null | /**
* Mojang API
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* OpenAPI spec version: 2020-06-05
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "OAISecurityQuestion.h"
#include "OAIHelpers.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QObject>
#include <QDebug>
namespace OpenAPI {
OAISecurityQuestion::OAISecurityQuestion(QString json) {
init();
this->fromJson(json);
}
OAISecurityQuestion::OAISecurityQuestion() {
init();
}
OAISecurityQuestion::~OAISecurityQuestion() {
this->cleanup();
}
void
OAISecurityQuestion::init() {
id = 0;
m_id_isSet = false;
question = new QString("");
m_question_isSet = false;
}
void
OAISecurityQuestion::cleanup() {
if(question != nullptr) {
delete question;
}
}
OAISecurityQuestion*
OAISecurityQuestion::fromJson(QString json) {
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
return this;
}
void
OAISecurityQuestion::fromJsonObject(QJsonObject pJson) {
::OpenAPI::setValue(&id, pJson["id"], "qint32", "");
::OpenAPI::setValue(&question, pJson["question"], "QString", "QString");
}
QString
OAISecurityQuestion::asJson ()
{
QJsonObject obj = this->asJsonObject();
QJsonDocument doc(obj);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QJsonObject
OAISecurityQuestion::asJsonObject() {
QJsonObject obj;
if(m_id_isSet){
obj.insert("id", QJsonValue(id));
}
if(question != nullptr && *question != QString("")){
toJsonValue(QString("question"), question, obj, QString("QString"));
}
return obj;
}
qint32
OAISecurityQuestion::getId() {
return id;
}
void
OAISecurityQuestion::setId(qint32 id) {
this->id = id;
this->m_id_isSet = true;
}
QString*
OAISecurityQuestion::getQuestion() {
return question;
}
void
OAISecurityQuestion::setQuestion(QString* question) {
this->question = question;
this->m_question_isSet = true;
}
bool
OAISecurityQuestion::isSet(){
bool isObjectUpdated = false;
do{
if(m_id_isSet){ isObjectUpdated = true; break;}
if(question != nullptr && *question != QString("")){ isObjectUpdated = true; break;}
}while(false);
return isObjectUpdated;
}
}
| 20.52 | 109 | 0.677583 | [
"object"
] |
51af253df68eee581aea286501b29cd9468ba7d9 | 3,806 | hpp | C++ | Source/Compiler/Program.hpp | Cristian-A/Spin | 1d63cdcffa7b41325a77ed40b51930ea8244dfc4 | [
"MIT"
] | 4 | 2019-12-06T20:28:14.000Z | 2020-12-28T20:36:10.000Z | Source/Compiler/Program.hpp | Cristian-A/Spin | 1d63cdcffa7b41325a77ed40b51930ea8244dfc4 | [
"MIT"
] | 6 | 2020-02-02T23:39:44.000Z | 2021-03-10T14:08:09.000Z | Source/Compiler/Program.hpp | Cristian-A/Spin | 1d63cdcffa7b41325a77ed40b51930ea8244dfc4 | [
"MIT"
] | null | null | null |
#include "../Common/Header.hpp"
#ifndef SPIN_PROGRAM_HPP
#define SPIN_PROGRAM_HPP
#include "../Token/Token.hpp"
#include <vector>
#include <unordered_map>
namespace Spin {
// Never change the order of types
// since it's used for type check.
enum Interrupt: UInt8 {
write = 0xA0,
writeln = 0x0A,
read = 0xF0,
readln = 0x0F,
sleep = 0xFF,
clock = 0xC0,
noise = 0xCA,
};
enum Type: UInt8 {
BooleanType,
CharacterType,
ByteType,
NaturalType,
IntegerType,
RealType,
ImaginaryType,
ComplexType,
StringType,
ArrayType,
EmptyArray,
RoutineType,
LamdaType,
VoidType,
};
class CodeUnit {
public:
Array<Token> * tokens;
String * name;
String * contents;
CodeUnit(Array<Token> * tokens,
String * name,
String * contents);
~CodeUnit();
};
enum ErrorCode: UInt8 {
flm, lxr, ppr, syx, typ, lgc, evl
};
enum OPCode: UInt8 {
RST, // rest
PSH, // push constant
STR, // push string
TYP, // push type
LLA, // load lamda address
ULA, // unload lamda address
LAM, // lamda call
GET, // get local
SET, // set local
SSF, // set stack frame
GLF, // get local from stack frame
SLF, // set local from stack frame
CTP, // copy temporary
LTP, // load temporary
SWP, // swap
ADD, // addition
SUB, // subtract
MUL, // multiply
DIV, // divide
MOD, // modulus
NEG, // negate
INV, // bitwise inversion
SGS, // string get subscription
SSS, // string set subscription
AGS, // array get subscription
ASS, // array set subscription
SCN, // string count
ACN, // array count
CCJ, // complex conjugate
VCJ, // vector conjugate
MCJ, // matrix conjugate
PST, // push true
PSF, // push false
PSI, // push infinity
PSU, // push undefined
PEC, // push empty complex
PES, // push empty string
PSA, // push array
PEA, // push empty array
POP, // pop
DHD, // duplicate head
DSK, // decrease stack
JMP, // jump
JIF, // jump if false
JAF, // jump if false, avoid pop
JIT, // jump if true
JAT, // jump if true, avoid pop
EQL, // equal
NEQ, // not equal
GRT, // great
LSS, // less
GEQ, // great equal
LEQ, // less equal
NOT, // boolean not
BWA, // bitwise and
BWO, // bitwise or
BWX, // bitwise xor
BSR, // bitwise shift right
BSL, // bitwise shift left
BRR, // bitwise rotation right
BRL, // bitwise rotation left
CAL, // call
CLL, // call language
RET, // return
CST, // casting
INT, // interrupt
HLT, // halt
// Temporary flags:
TLT, // temporary lamda tag
};
using Types = UInt16;
union Value {
Integer integer;
Pointer pointer;
Real real;
Byte byte;
Boolean boolean;
};
struct ByteCode {
OPCode code = OPCode::RST;
union {
SizeType index;
Value value;
Type type;
Types types;
} as;
};
class Program {
public:
class Error : Exception {
private:
String file;
String message;
UInt32 line;
UInt32 positionStart;
UInt32 positionEnd;
ErrorCode error;
public:
Error(CodeUnit * c, String m, Token t, ErrorCode e);
String getFile() const;
String getMessage() const;
UInt32 getLine() const;
UInt32 getPositionStart() const;
UInt32 getPositionEnd() const;
ErrorCode getErrorValue() const;
String getErrorCode() const;
};
Program() = default;
Array<ByteCode> instructions;
Array<String> strings;
void serialise(String path) const;
static Program * from(String path);
};
class SourceCode {
public:
CodeUnit * main;
Array<CodeUnit *> * wings;
Array<String> * libraries;
SourceCode(CodeUnit * main,
Array<CodeUnit *> * wings,
Array<String> * libraries);
};
enum NativeCodes: UInt16 {
// Array:
// Boolean:
Boolean_random,
Boolean_string,
// String:
};
}
#endif
| 16.264957 | 55 | 0.631372 | [
"vector"
] |
51b67caa1513bf6726ed669e121612b4b90bcf11 | 1,166 | cpp | C++ | cpp/godot-cpp/src/gen/VisualScriptBuiltinFunc.cpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | 1 | 2021-03-16T09:51:00.000Z | 2021-03-16T09:51:00.000Z | cpp/godot-cpp/src/gen/VisualScriptBuiltinFunc.cpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | null | null | null | cpp/godot-cpp/src/gen/VisualScriptBuiltinFunc.cpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | null | null | null | #include "VisualScriptBuiltinFunc.hpp"
#include <core/GodotGlobal.hpp>
#include <core/CoreTypes.hpp>
#include <core/Ref.hpp>
#include <core/Godot.hpp>
#include "__icalls.hpp"
namespace godot {
VisualScriptBuiltinFunc::___method_bindings VisualScriptBuiltinFunc::___mb = {};
void VisualScriptBuiltinFunc::___init_method_bindings() {
___mb.mb_get_func = godot::api->godot_method_bind_get_method("VisualScriptBuiltinFunc", "get_func");
___mb.mb_set_func = godot::api->godot_method_bind_get_method("VisualScriptBuiltinFunc", "set_func");
}
VisualScriptBuiltinFunc *VisualScriptBuiltinFunc::_new()
{
return (VisualScriptBuiltinFunc *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, godot::api->godot_get_class_constructor((char *)"VisualScriptBuiltinFunc")());
}
VisualScriptBuiltinFunc::BuiltinFunc VisualScriptBuiltinFunc::get_func() {
return (VisualScriptBuiltinFunc::BuiltinFunc) ___godot_icall_int(___mb.mb_get_func, (const Object *) this);
}
void VisualScriptBuiltinFunc::set_func(const int64_t which) {
___godot_icall_void_int(___mb.mb_set_func, (const Object *) this, which);
}
} | 32.388889 | 227 | 0.80789 | [
"object"
] |
51b8b3aca58c9494b119cf7c15ef9a6e692bfc5d | 5,121 | cc | C++ | src/decoders/TitleTemplate.cc | b8raoult/magics | eb2c86ec6e392e89c90044128dc671f22283d6ad | [
"ECL-2.0",
"Apache-2.0"
] | 41 | 2018-12-07T23:10:50.000Z | 2022-02-19T03:01:49.000Z | src/decoders/TitleTemplate.cc | b8raoult/magics | eb2c86ec6e392e89c90044128dc671f22283d6ad | [
"ECL-2.0",
"Apache-2.0"
] | 59 | 2019-01-04T15:43:30.000Z | 2022-03-31T09:48:15.000Z | src/decoders/TitleTemplate.cc | b8raoult/magics | eb2c86ec6e392e89c90044128dc671f22283d6ad | [
"ECL-2.0",
"Apache-2.0"
] | 13 | 2019-01-07T14:36:33.000Z | 2021-09-06T14:48:36.000Z | /*
* (C) Copyright 1996-2016 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation nor
* does it submit to any jurisdiction.
*/
/*! \file TitleTemplate.cc
\brief Implementation of the Template class TitleTemplate.
Magics Team - ECMWF 2004
Started: Mon 21-Jun-2004
Changes:
*/
#include "TitleTemplate.h"
#include "Factory.h"
#include "GribDecoder.h"
#include "MagException.h"
#include "TitleMetaField.h"
#include "TitleStringField.h"
#include "MagicsGlobal.h"
#include "expat.h"
using namespace magics;
static bool ignore_space_;
static void XMLCALL startElement(void* userData, const char* name, const char** atts) {
TitleTemplate* object = (TitleTemplate*)userData;
if (string(name) == "title") {
TitleTemplate* title = new TitleTemplate();
while (*atts) {
title->criteria()[*(atts)] = *(atts + 1);
atts += 2;
}
object->top()->push_back(title);
object->push(title);
ignore_space_ = true;
return;
}
if (string(name) == "text")
ignore_space_ = false;
else {
TitleMetaField* meta = new TitleMetaField(name);
while (*atts) {
(*meta)[*(atts)] = *(atts + 1);
atts += 2;
}
object->top()->add(meta);
}
}
static void XMLCALL endElement(void* userData, const char* name) {
if (string(name) == "title") {
TitleTemplate* object = (TitleTemplate*)userData;
object->pop();
ignore_space_ = true;
}
if (string(name) == "text")
ignore_space_ = true;
}
static void XMLCALL character(void* userData, const char* s, int len) {
string data(s, len);
TitleTemplate* object = (TitleTemplate*)userData;
if (data == "\n")
return;
if (ignore_space_ && data.find_first_not_of(" \n\t") == std::string::npos)
return;
object->top()->add(new TitleStringField(data));
}
static void XMLCALL startData(void*) {
MagLog::dev() << "start data"
<< "\n";
}
static void XMLCALL endData(void*) {}
TitleTemplate* TitleTemplate::singleton_ = 0;
TitleTemplate::TitleTemplate() {
if (!singleton_)
decode();
}
void TitleTemplate::decode() {
singleton_ = this;
string filename = buildSharePath(file_);
char buf[BUFSIZ];
ignore_space_ = true;
push(this);
XML_Parser parser = XML_ParserCreate(NULL);
int done;
XML_SetUserData(parser, this);
XML_SetElementHandler(parser, startElement, endElement);
XML_SetCdataSectionHandler(parser, startData, endData);
XML_SetCharacterDataHandler(parser, character);
FILE* in = fopen(filename.c_str(), "r");
if (!in) {
throw CannotOpenFile(filename);
}
do {
size_t len = fread(buf, 1, sizeof(buf), in);
done = len < sizeof(buf);
if (XML_Parse(parser, buf, len, done) == XML_STATUS_ERROR) {
ostringstream s;
s << "XmlMagException : " << XML_ErrorString(XML_GetErrorCode(parser)) << " at line "
<< XML_GetCurrentLineNumber(parser) << ends;
MagLog::error() << "XmlMagException : " << XML_ErrorString(XML_GetErrorCode(parser)) << " at line "
<< XML_GetCurrentLineNumber(parser) << "\n";
throw MagicsException(s.str());
}
} while (!done);
XML_ParserFree(parser);
fclose(in);
}
TitleTemplate::~TitleTemplate() {}
/*!
Class information are given to the output-stream.
*/
void TitleTemplate::print(ostream& out) const {
out << "TitleTemplate[";
for (map<string, string>::const_iterator criter = criteria_.begin(); criter != criteria_.end(); ++criter) {
out << criter->first << " = " << criter->second << ","
<< "\n";
}
for (auto& field : template_)
out << *field;
for (const_iterator child = begin(); child != end(); ++child)
out << *(*child);
out << "]";
}
bool TitleTemplate::verify(const GribDecoder& data) const {
for (map<string, string>::const_iterator criter = criteria_.begin(); criter != criteria_.end(); ++criter) {
try {
MagLog::debug() << "Try to create the MatchCriteria for " << criter->first << "\n";
unique_ptr<MatchCriteria> object(SimpleObjectMaker<MatchCriteria>::create(criter->first));
MagLog::debug() << "Found the MatchCriteria for " << criter->first << "\n";
if (!(*object).verify(data, criter->first, criter->second))
return false;
}
catch (NoFactoryException& e) { // The data do not know how to verify the criter ....
if (MagicsGlobal::strict()) {
throw;
}
MagLog::warning() << "Cannot Create the MatchCriteria for " << criter->first << "\n";
return false;
}
}
return true;
}
| 30.482143 | 112 | 0.599688 | [
"object"
] |
51b9ed4bd919a41d121fa9e190f04e2b7df13925 | 7,993 | hpp | C++ | src/libraries/lagrangian/intermediate/submodels/Thermodynamic/HeatTransferModel/HeatTransferModel/HeatTransferModel.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/lagrangian/intermediate/submodels/Thermodynamic/HeatTransferModel/HeatTransferModel/HeatTransferModel.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/lagrangian/intermediate/submodels/Thermodynamic/HeatTransferModel/HeatTransferModel/HeatTransferModel.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) 2014 Applied CCM
Copyright (C) 2011-2015 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>.
Class
CML::HeatTransferModel
Description
Templated heat transfer model class
SourceFiles
HeatTransferModel.cpp
HeatTransferModelNew.cpp
\*---------------------------------------------------------------------------*/
#ifndef HeatTransferModel_H
#define HeatTransferModel_H
#include "IOdictionary.hpp"
#include "autoPtr.hpp"
#include "runTimeSelectionTables.hpp"
#include "CloudSubModelBase.hpp"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace CML
{
/*---------------------------------------------------------------------------*\
Class HeatTransferModel Declaration
\*---------------------------------------------------------------------------*/
template<class CloudType>
class HeatTransferModel
:
public CloudSubModelBase<CloudType>
{
// Private data
//- Apply Bird's correction to the htc
const Switch BirdCorrection_;
public:
//- Runtime type information
TypeName("heatTransferModel");
//- Declare runtime constructor selection table
declareRunTimeSelectionTable
(
autoPtr,
HeatTransferModel,
dictionary,
(
const dictionary& dict,
CloudType& owner
),
(dict, owner)
);
// Constructors
//- Construct null from owner
HeatTransferModel(CloudType& owner);
//- Construct from dictionary
HeatTransferModel
(
const dictionary& dict,
CloudType& owner,
const word& type
);
//- Construct copy
HeatTransferModel(const HeatTransferModel<CloudType>& htm);
//- Construct and return a clone
virtual autoPtr<HeatTransferModel<CloudType> > clone() const = 0;
//- Destructor
virtual ~HeatTransferModel();
//- Selector
static autoPtr<HeatTransferModel<CloudType> > New
(
const dictionary& dict,
CloudType& owner
);
// Member Functions
// Access
//- Return the Bird htc correction flag
const Switch& BirdCorrection() const;
// Evaluation
//- Nusselt number
virtual scalar Nu
(
const scalar Re,
const scalar Pr
) const = 0;
//- Return heat transfer coefficient
virtual scalar htc
(
const scalar dp,
const scalar Re,
const scalar Pr,
const scalar kappa,
const scalar NCpW
) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace CML
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#define makeHeatTransferModel(CloudType) \
\
typedef CloudType::thermoCloudType thermoCloudType; \
defineNamedTemplateTypeNameAndDebug \
( \
HeatTransferModel<thermoCloudType>, \
0 \
); \
defineTemplateRunTimeSelectionTable \
( \
HeatTransferModel<thermoCloudType>, \
dictionary \
);
#define makeHeatTransferModelType(SS, CloudType) \
\
typedef CloudType::thermoCloudType thermoCloudType; \
defineNamedTemplateTypeNameAndDebug(SS<thermoCloudType>, 0); \
\
HeatTransferModel<thermoCloudType>:: \
adddictionaryConstructorToTable<SS<thermoCloudType> > \
add##SS##CloudType##thermoCloudType##ConstructorToTable_;
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
template<class CloudType>
CML::HeatTransferModel<CloudType>::HeatTransferModel(CloudType& owner)
:
CloudSubModelBase<CloudType>(owner),
BirdCorrection_(false)
{}
template<class CloudType>
CML::HeatTransferModel<CloudType>::HeatTransferModel
(
const dictionary& dict,
CloudType& owner,
const word& type
)
:
CloudSubModelBase<CloudType>(owner, dict, typeName, type),
BirdCorrection_(this->coeffDict().lookup("BirdCorrection"))
{}
template<class CloudType>
CML::HeatTransferModel<CloudType>::HeatTransferModel
(
const HeatTransferModel<CloudType>& htm
)
:
CloudSubModelBase<CloudType>(htm),
BirdCorrection_(htm.BirdCorrection_)
{}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
template<class CloudType>
CML::HeatTransferModel<CloudType>::~HeatTransferModel()
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template<class CloudType>
const CML::Switch& CML::HeatTransferModel<CloudType>::BirdCorrection() const
{
return BirdCorrection_;
}
template<class CloudType>
CML::scalar CML::HeatTransferModel<CloudType>::htc
(
const scalar dp,
const scalar Re,
const scalar Pr,
const scalar kappa,
const scalar NCpW
) const
{
const scalar Nu = this->Nu(Re, Pr);
scalar htc = Nu*kappa/dp;
if (BirdCorrection_ && (mag(htc) > ROOTVSMALL) && (mag(NCpW) > ROOTVSMALL))
{
const scalar phit = min(NCpW/htc, 50);
if (phit > 0.001)
{
htc *= phit/(exp(phit) - 1.0);
}
}
return htc;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
template<class CloudType>
CML::autoPtr<CML::HeatTransferModel<CloudType> >
CML::HeatTransferModel<CloudType>::New
(
const dictionary& dict,
CloudType& owner
)
{
const word modelType(dict.lookup("heatTransferModel"));
Info<< "Selecting heat transfer model " << modelType << endl;
typename dictionaryConstructorTable::iterator cstrIter =
dictionaryConstructorTablePtr_->find(modelType);
if (cstrIter == dictionaryConstructorTablePtr_->end())
{
FatalErrorInFunction
<< "Unknown heat transfer model type "
<< modelType << nl << nl
<< "Valid heat transfer model types are:" << nl
<< dictionaryConstructorTablePtr_->sortedToc()
<< exit(FatalError);
}
return autoPtr<HeatTransferModel<CloudType> >(cstrIter()(dict, owner));
}
#endif
// ************************************************************************* //
| 28.243816 | 80 | 0.495934 | [
"model"
] |
51bf8ea7675b1de7231fb7896b17bb6ccda24b9e | 96,390 | cpp | C++ | src/_scm.cpp | NCAR/rda-gatherxml | afc7d8693ecb259eb54a501a9d09cf5edee5a782 | [
"MIT"
] | null | null | null | src/_scm.cpp | NCAR/rda-gatherxml | afc7d8693ecb259eb54a501a9d09cf5edee5a782 | [
"MIT"
] | null | null | null | src/_scm.cpp | NCAR/rda-gatherxml | afc7d8693ecb259eb54a501a9d09cf5edee5a782 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <thread>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <ftw.h>
#include <signal.h>
#include <pthread.h>
#include <sstream>
#include <regex>
#include <gatherxml.hpp>
#include <mymap.hpp>
#include <strutils.hpp>
#include <utils.hpp>
#include <bsort.hpp>
#include <bitmap.hpp>
#include <xml.hpp>
#include <MySQL.hpp>
#include <tempfile.hpp>
#include <metahelpers.hpp>
#include <xmlutils.hpp>
#include <search.hpp>
#include <timer.hpp>
#include <myerror.hpp>
using MySQL::table_exists;
using metautils::log_error2;
using metautils::log_warning;
using miscutils::this_function_label;
using std::cerr;
using std::cout;
using std::endl;
using std::list;
using std::make_pair;
using std::make_shared;
using std::move;
using std::pair;
using std::regex;
using std::regex_search;
using std::shared_ptr;
using std::sort;
using std::stof;
using std::stoi;
using std::stoll;
using std::string;
using std::stringstream;
using std::unique_ptr;
using std::unordered_map;
using std::unordered_set;
using std::vector;
using strutils::ftos;
using strutils::chop;
using strutils::itos;
using strutils::lltos;
using strutils::replace_all;
using strutils::split;
using strutils::strand;
using strutils::substitute;
using strutils::to_lower;
using strutils::trim;
using strutils::trimmed;
using unixutils::mysystem2;
using unixutils::remote_web_file;
metautils::Directives metautils::directives;
metautils::Args metautils::args;
bool gatherxml::verbose_operation;
extern const string USER = getenv("USER");
string myerror = "";
string mywarning = "";
struct LocalArgs {
LocalArgs() : dsnum2(), summ_type(), file(), temp_directory(),
cmd_directory(), data_format(), gindex_list(), summarize_all(false),
added_variable(false), verbose(false), notify(false), update_graphics(
true), update_db(true), refresh_web(false), refresh_inv(false),
is_web_file(false), summarized_hpss_file(false), summarized_web_file(
false) { }
string dsnum2;
string summ_type;
string file, temp_directory, cmd_directory, data_format;
vector<string> gindex_list;
bool summarize_all;
bool added_variable, verbose, notify;
bool update_graphics, update_db;
bool refresh_web, refresh_inv, is_web_file;
bool summarized_hpss_file, summarized_web_file;
} local_args;
TempDir g_temp_dir;
void parse_args(const char arg_delimiter) {
auto args = split(metautils::args.args_string, string(1, arg_delimiter));
for (size_t n = 0; n < args.size(); ++n) {
if (to_lower(args[n]) == "-wa") {
// need to_lower() because dsarch often uses -WA
if (!local_args.file.empty()) {
cerr << "scm: specify only one of -wa or -wf" << endl;
exit(1);
} else {
local_args.summarize_all = true;
if (n + 1 < args.size() && args[n + 1][0] != '-') {
local_args.summ_type = args[++n];
}
local_args.cmd_directory = "wfmd";
}
} else if (args[n] == "-d") {
metautils::args.dsnum = args[++n];
if (regex_search(metautils::args.dsnum, regex("^ds"))) {
metautils::args.dsnum = metautils::args.dsnum.substr(2);
}
local_args.dsnum2 = strutils::substitute(metautils::args.dsnum, ".", "");
} else if (args[n] == "-wf") {
if (local_args.summarize_all) {
cerr << "scm: specify only one of -wa or -wf" << endl;
exit(1);
} else {
if (n + 1 < args.size()) {
local_args.file = args[++n];
local_args.is_web_file = true;
} else {
cerr << "scm: the -wf flag requires a file name" << endl;
exit(1);
}
}
} else if (args[n] == "-G") {
local_args.update_graphics = false;
} else if (args[n] == "-N") {
local_args.notify = true;
} else if (args[n] == "-rw") {
local_args.refresh_web = true;
if (n + 1 < args.size() && args[n + 1][0] != '-') {
local_args.gindex_list.emplace_back(args[++n]);
}
} else if (args[n] == "-ri") {
local_args.refresh_inv = true;
if (n + 1 < args.size() && args[n + 1][0] != '-') {
local_args.gindex_list.emplace_back(args[++n]);
}
} else if (args[n] == "-S") {
local_args.update_db = false;
} else if (args[n] == "-R") {
metautils::args.regenerate = false;
} else if (args[n] == "-t") {
local_args.temp_directory = args[++n];
} else if (args[n] == "-V") {
local_args.verbose = true;
} else {
myerror = "Terminating - scm: don't understand argument " + args[n];
exit(1);
}
}
if (metautils::args.dsnum.empty()) {
cerr << "scm: no dataset number specified" << endl;
exit(1);
}
if (!local_args.summarize_all && !local_args.is_web_file && !local_args.
refresh_web && !local_args.refresh_inv) {
myerror = "Terminating - scm - nothing to do";
exit(1);
}
if (local_args.update_graphics && !local_args.file.empty() && !regex_search(
local_args.file, regex("(Ob|Fix)ML$"))) {
local_args.update_graphics = false;
}
}
void delete_temporary_directory() {
if (!local_args.temp_directory.empty()) {
stringstream oss, ess;
mysystem2("/bin/rm -rf " + local_args.temp_directory, oss, ess);
if (ess.str().empty()) {
local_args.temp_directory = "";
}
}
}
string table_code(MySQL::Server& srv, string table_name, string
where_conditions, bool do_insert = true) {
// where_conditions must have 'and' specified as 'AND' because it is possible
// that 'and' is in fields in the database tables
static const string F = this_function_label(__func__);
replace_all(where_conditions, " &eq; ", " = ");
MySQL::LocalQuery q;
q.set("code", table_name, where_conditions);
if (q.submit(srv) < 0) {
log_error2("error: '" + q.error() + " from query: '" + q.show() + "'", F,
"scm", USER);
}
if (q.num_rows() == 0) {
if (!do_insert) {
return "";
}
string cols, vals;
auto sp = split(where_conditions, " AND ");
for (size_t n = 0; n < sp.size(); ++n) {
auto sp2 = split(sp[n], " = ");
if (sp2.size() != 2) {
log_error2("error in where_conditions: " + where_conditions + ", " + sp[
n], F, "scm", USER);
}
auto s = sp2[0];
trim(s);
if (!cols.empty()) {
cols += ", ";
}
cols += s;
s = sp2[1];
trim(s);
replace_all(s, " &eq; ", " = ");
if (!vals.empty()) {
vals += ", ";
}
vals += s;
}
string r;
if (srv.command("lock table " + table_name + " write", r) < 0) {
log_error2(srv.error(), F, "scm", USER);
}
if (srv.insert(table_name, cols, vals, "") < 0) {
auto e = srv.error();
if (!regex_search(e, regex("^Duplicate entry"))) {
log_error2("server error: '" + e + "' while inserting (" + cols + ") "
"values(" + vals + ") into " + table_name, F, "scm", USER);
}
}
if (srv.command("unlock tables", r) < 0) {
log_error2(srv.error(), F, "scm", USER);
}
q.submit(srv);
if (q.num_rows() == 0) { // this really should not happen if insert worked
return "";
}
}
MySQL::Row r;
q.fetch_row(r);
return std::move(r[0]);
}
string grid_definition_parameters(const XMLElement& e) {
auto v = e.attribute_value("definition");
if (v == "latLon") {
return e.attribute_value("numX") + ":" + e.attribute_value("numY") + ":" +
e.attribute_value("startLat") + ":" + e.attribute_value("startLon") +
":" + e.attribute_value("endLat") + ":" + e.attribute_value("endLon") +
":" + e.attribute_value("xRes") + ":" + e.attribute_value("yRes");
} else if (v == "gaussLatLon") {
return e.attribute_value("numX") + ":" + e.attribute_value("numY") + ":" +
e.attribute_value("startLat") + ":" + e.attribute_value("startLon") +
":" + e.attribute_value("endLat") + ":" + e.attribute_value("endLon") +
":" + e.attribute_value("xRes") + ":" + e.attribute_value("circles");
} else if (v == "polarStereographic") {
return e.attribute_value("numX") + ":" + e.attribute_value("numY") + ":" +
e.attribute_value("startLat") + ":" + e.attribute_value("startLon") +
":" + e.attribute_value("resLat") + ":" + e.attribute_value("projLon") +
":" + e.attribute_value("pole") + ":" + e.attribute_value("xRes") + ":"
+ e. attribute_value("yRes");
} else if (v == "lambertConformal") {
return e.attribute_value("numX") + ":" + e.attribute_value("numY") + ":" +
e.attribute_value("startLat") + ":" + e.attribute_value("startLon") +
":" + e.attribute_value("resLat") + ":" + e.attribute_value("projLon") +
":" + e.attribute_value("pole") + ":" + e.attribute_value("xRes") + ":"
+ e.attribute_value("yRes") + ":" + e.attribute_value("stdParallel1") +
":" + e.attribute_value("stdParallel2");
}
return "";
}
void open_markup_file(XMLDocument& xdoc, string filename) {
auto f = filename;
if (local_args.temp_directory.empty()) {
f = remote_web_file("https://rda.ucar.edu" + filename, g_temp_dir.name());
if (f.empty()) {
f = remote_web_file("https://rda.ucar.edu" + filename + ".gz", g_temp_dir.
name());
}
}
if (!xdoc.open(f)) {
log_error2("unable to open " + filename, "open_markup_file()", "scm", USER);
}
}
struct MarkupParameters {
MarkupParameters() : markup_type(), xdoc(), element(), data_type(), server(),
database(), file_type(), filename(), format(), file_map(), format_map() { }
string markup_type;
XMLDocument xdoc;
string element, data_type;
MySQL::Server server;
string database, file_type, filename, format;
unordered_map<string, string> file_map, format_map;
};
void initialize_web_file(MarkupParameters *markup_parameters) {
static const string F = this_function_label(__func__);
MySQL::Server mysrv_d(metautils::directives.database_server, metautils::
directives.rdadb_username, metautils::directives.rdadb_password, "dssdb");
if (!mysrv_d) {
log_error2("could not connect to RDADB - error: '" + mysrv_d.error() + "'",
F, "scm", USER);
}
markup_parameters->filename = metautils::relative_web_filename(
markup_parameters->filename);
MySQL::LocalQuery q("tindex", "dssdb.wfile", "wfile = '" + markup_parameters->
filename + "'");
MySQL::Row r;
if (q.submit(mysrv_d) == 0 && q.fetch_row(r) && r[0] != "0") {
local_args.gindex_list.emplace_back(r[0]);
}
markup_parameters->database = "W" + markup_parameters->markup_type;
markup_parameters->file_type = "web";
local_args.summarized_web_file = true;
if (mysrv_d.update("wfile", "meta_link = '" + substitute(markup_parameters->
markup_type, "ML", "") + "'", "dsid = 'ds" + metautils::args.dsnum +
"' and wfile = '" + markup_parameters->filename + "'") < 0) {
log_error2("error: '" + mysrv_d.error() + "' while trying to update "
"'dssdb.wfile'", F, "scm", USER);
}
mysrv_d.disconnect();
}
void initialize_file(MarkupParameters *markup_parameters) {
const static string F = this_function_label(__func__);
markup_parameters->filename = markup_parameters->xdoc.element(
markup_parameters->markup_type).attribute_value("uri");
if (regex_search(markup_parameters->filename, regex(
"^file://MSS:/FS/DECS"))) {
delete_temporary_directory();
myerror = "Terminating - scm no longer works on HPSS files";
exit(1);
} else if (regex_search(markup_parameters->filename, regex(
"^http(s){0,1}://rda\\.ucar\\.edu"))) {
initialize_web_file(markup_parameters);
} else {
log_error2("invalid uri '" + markup_parameters->filename + "' in xml file",
F, "scm", USER);
}
}
void process_data_format(MarkupParameters *markup_parameters) {
static const string F = this_function_label(__func__);
markup_parameters->format = markup_parameters->xdoc.element(
markup_parameters->markup_type).attribute_value("format");
if (markup_parameters->format.empty()) {
log_error2("missing " + markup_parameters->database + " format attribute",
F, "scm", USER);
}
if (markup_parameters->server.insert("search.formats", "keyword, vocabulary, "
"dsid", "'" + markup_parameters->format + "', '" + markup_parameters->
database + "', '" + metautils::args.dsnum + "'", "update dsid = values("
"dsid)") < 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while "
"inserting into search.formats", F, "scm", USER);
}
if (local_args.data_format.empty()) {
local_args.data_format = markup_parameters->format;
} else if (markup_parameters->format != local_args.data_format) {
local_args.data_format = "all";
}
if (markup_parameters->format_map.find(markup_parameters->format) ==
markup_parameters->format_map.end()) {
auto c = table_code(markup_parameters->server, markup_parameters->database +
".formats", "format = '" + markup_parameters->format + "'");
if (c.empty()) {
log_error2("unable to get format code", F, "scm", USER);
}
markup_parameters->format_map.emplace(markup_parameters->format, c);
}
}
void create_grml_tables(MarkupParameters *markup_parameters) {
static const string F = this_function_label(__func__);
auto tb_base = markup_parameters->database + ".ds" + local_args.dsnum2;
string r;
if (markup_parameters->server.command("create table " + tb_base + "_" +
markup_parameters->file_type + "files2 like " + markup_parameters->database
+ "template_" + markup_parameters->file_type + "files2", r) < 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while "
"creating table " + tb_base + "_" + markup_parameters->file_type +
"files2", F, "scm", USER);
}
/*
if (ftyp == "web") {
if (markup_parameters->server.command("alter table "+tb_nam+" add type char(1) not null default 'D' after webID, add dsid varchar(9) not null default 'ds"+metautils::args.dsnum+"' after type, add primary key (webID,type,dsid)",result) < 0) {
metautils::log_error(F + " returned error: "+markup_parameters->server.error()+" while modifying "+tb_nam,"scm",USER);
}
}
*/
if (markup_parameters->server.command("create table " + tb_base +
"_levels like " + markup_parameters->database + ".template_levels", r) <
0) {
log_error2("error: '" + markup_parameters->server.error() + "' while "
"creating table " + tb_base + "_levels", F, "scm", USER);
}
if (markup_parameters->server.command("create table " + tb_base + "_grids "
"like " + markup_parameters->database + ".template_grids", r) < 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while "
"creating table " + tb_base + "_grids", F, "scm", USER);
}
if (markup_parameters->server.command("create table " + tb_base + "_grids2 "
"like " + markup_parameters->database + ".template_grids2", r) < 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while "
"creating table " + tb_base + "_grids2", F, "scm", USER);
}
}
void create_obml_tables(MarkupParameters *markup_parameters) {
static const string F = this_function_label(__func__);
auto tb_base = markup_parameters->database + ".ds" + local_args.dsnum2;
string r;
if (markup_parameters->server.command("create table " + tb_base + "_" +
markup_parameters->file_type + "files2 like " + markup_parameters->database
+ "template_" + markup_parameters->file_type + "files2", r) < 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while "
"creating table " + tb_base + "_" + markup_parameters->file_type +
"files2", F, "scm", USER);
}
if (markup_parameters->server.command("create table " + tb_base + "_locations "
"like " + markup_parameters->database + ".template_locations", r) < 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while "
"creating table " + tb_base + "_locations", F, "scm", USER);
}
if (markup_parameters->server.command("create table " + tb_base +
"_location_names like " + markup_parameters->database +
".template_location_names", r) < 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while "
"creating table " + tb_base + "_location_names", F, "scm", USER);
}
/*
if (markup_parameters->server.command("create table " + tb_base + "_dataTypes like " + markup_parameters->database +
".template_dataTypes", r) < 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while creating table " + tb_base
+ "_dataTypes", F, "scm", USER);
}
*/
if (markup_parameters->server.command("create table " + tb_base +
"_dataTypes2 like " + markup_parameters->database + ".template_dataTypes2",
r) < 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while "
"creating table " + tb_base + "_dataTypes2", F, "scm", USER);
}
if (markup_parameters->server.command("create table " + tb_base +
"_dataTypesList like " + markup_parameters->database +
".template_dataTypesList", r) < 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while "
"creating table " + tb_base + "_dataTypesList", F, "scm", USER);
}
if (markup_parameters->server.command("create table " + tb_base +
"_frequencies like " + markup_parameters->database +
".template_frequencies", r) < 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while "
"creating table " + tb_base + "_frequencies", F, "scm", USER);
}
if (markup_parameters->server.command("create table " + tb_base + "_IDs2 like "
+ markup_parameters->database + ".template_IDs2", r) < 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while "
"creating table " + tb_base + "_IDs2", F, "scm", USER);
}
if (markup_parameters->server.command("create table " + tb_base + "_IDList2 "
"like " + markup_parameters->database + ".template_IDList2", r) < 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while "
"creating table " + tb_base + "_IDList2", F, "scm", USER);
}
if (markup_parameters->server.command("create table " + tb_base + "_geobounds "
"like " + markup_parameters->database + ".template_geobounds", r) < 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while "
"creating table " + tb_base + "_geobounds", F, "scm", USER);
}
/*
if (markup_parameters->server.command("create table " + tb_base + "_ID_dataTypes like " +
markup_parameters->database + ".template_ID_dataTypes", r) < 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while creating table " + tb_base
+ "_ID_dataTypes", F, "scm", USER);
}
*/
}
void create_fixml_tables(MarkupParameters *markup_parameters) {
static const string F = this_function_label(__func__);
auto tb_base = markup_parameters->database + ".ds" + local_args.dsnum2;
string r;
if (markup_parameters->server.command("create table " + tb_base + "_" +
markup_parameters->file_type + "files2 like " + markup_parameters->database
+ "template_" + markup_parameters->file_type + "files2", r) < 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while "
"creating table " + tb_base + "_" + markup_parameters->file_type +
"files2", F, "scm", USER);
}
if (markup_parameters->server.command("create table " + tb_base + "_IDList "
"like " + markup_parameters->database + ".template_IDList", r) < 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while "
"creating table " + tb_base + "_IDList", F, "scm", USER);
}
if (markup_parameters->server.command("create table " + tb_base + "_locations "
"like " + markup_parameters->database + ".template_locations", r) < 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while "
"creating table " + tb_base + "_locations", F, "scm", USER);
}
if (markup_parameters->server.command("create table " + tb_base +
"_location_names like " + markup_parameters->database +
".template_location_names", r) < 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while "
"creating table " + tb_base + "_location_names", F, "scm", USER);
}
if (markup_parameters->server.command("create table " + tb_base +
"_frequencies like " + markup_parameters->database +
".template_frequencies", r) < 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while "
"creating table " + tb_base + "_frequencies", F, "scm", USER);
}
}
void create_tables(MarkupParameters *markup_parameters) {
if (markup_parameters->markup_type == "GrML") {
create_grml_tables(markup_parameters);
} else if (markup_parameters->markup_type == "ObML") {
create_obml_tables(markup_parameters);
} else if (markup_parameters->markup_type == "FixML") {
create_fixml_tables(markup_parameters);
}
}
void insert_filename(MarkupParameters *markup_parameters) {
const static string F = this_function_label(__func__);
if (markup_parameters->file_map.find(markup_parameters->filename) ==
markup_parameters->file_map.end()) {
auto tb_nam = markup_parameters->database + ".ds" + local_args.dsnum2 + "_"
+ markup_parameters->file_type + "files2";
if (!table_exists(markup_parameters->server, tb_nam)) {
create_tables(markup_parameters);
}
auto c = table_code(markup_parameters->server, tb_nam, markup_parameters->
file_type + "ID = '" + markup_parameters->filename + "'", false);
if (c.empty()) {
if (markup_parameters->server.insert(tb_nam, markup_parameters->file_type
+ "ID, format_code, num_" + markup_parameters->data_type + ", "
"start_date, end_date, uflag", "'" + markup_parameters->filename +
"', " + markup_parameters->format_map[markup_parameters->format] +
", 0, 0, 0, '" + strand(5) + "'", "") < 0) {
log_error2("error: '" + markup_parameters->server.error() + " while "
"inserting into " + tb_nam, F, "scm", USER);
}
c = table_code(markup_parameters->server, tb_nam, markup_parameters->
file_type + "ID = '" + markup_parameters->filename + "'", false);
if (c.empty()) {
log_error2("error: unable to retrieve code from '" + tb_nam + "' for "
"value '" + markup_parameters->filename + "'", F, "scm", USER);
}
}
markup_parameters->file_map.emplace(markup_parameters->filename, c);
if (markup_parameters->server.update(tb_nam, "format_code = " +
markup_parameters->format_map[markup_parameters->format], "code = " + c)
< 0) {
log_error2("error: '" + markup_parameters->server.error() + "' while "
"updating " + tb_nam + " with format_code and code", F, "scm", USER);
}
}
}
void clear_grml_tables(MarkupParameters *markup_parameters) {
markup_parameters->server._delete(markup_parameters->database + ".ds" +
local_args.dsnum2 + "_grids", markup_parameters->file_type + "ID_code = "
+ markup_parameters->file_map[markup_parameters->filename]);
markup_parameters->server._delete(markup_parameters->database + ".ds" +
local_args.dsnum2 + "_grids2", markup_parameters->file_type + "ID_code = "
+ markup_parameters->file_map[markup_parameters->filename]);
markup_parameters->server._delete(markup_parameters->database + ".ds" +
local_args.dsnum2 + "_processes", markup_parameters->file_type +
"ID_code = " + markup_parameters->file_map[markup_parameters->filename]);
markup_parameters->server._delete(markup_parameters->database + ".ds" +
local_args.dsnum2 + "_ensembles", markup_parameters->file_type
+ "ID_code = " + markup_parameters->file_map[markup_parameters->
filename]);
}
void clear_obml_tables(MarkupParameters *markup_parameters) {
markup_parameters->server._delete(markup_parameters->database + ".ds" +
local_args.dsnum2 + "_locations", markup_parameters->file_type +
"ID_code = " + markup_parameters->file_map[markup_parameters->filename]);
/*
markup_parameters->server._delete(markup_parameters->database + ".ds" + local_args.dsnum2 + "_dataTypes", markup_parameters->file_type
+ "ID_code = " + markup_parameters->file_map[markup_parameters->filename]);
*/
markup_parameters->server._delete(markup_parameters->database + ".ds" +
local_args.dsnum2 + "_dataTypes2", markup_parameters->file_type +
"ID_code = " + markup_parameters->file_map[markup_parameters->filename]);
markup_parameters->server._delete(markup_parameters->database + ".ds" +
local_args.dsnum2 + "_dataTypesList", markup_parameters->file_type +
"ID_code = " + markup_parameters->file_map[markup_parameters->filename]);
markup_parameters->server._delete(markup_parameters->database + ".ds" +
local_args.dsnum2 + "_IDList2", markup_parameters->file_type +
"ID_code = " + markup_parameters->file_map[markup_parameters->filename]);
/*
markup_parameters->server._delete(markup_parameters->database + ".ds" + local_args.dsnum2 + "_ID_dataTypes",
markup_parameters->file_type + "ID_code = " + file_ID_code);
*/
}
void clear_satml_tables(MarkupParameters *markup_parameters) {
}
void clear_fixml_tables(MarkupParameters *markup_parameters) {
markup_parameters->server._delete(markup_parameters->database + ".ds" +
local_args.dsnum2 + "_locations", markup_parameters->file_type + "ID_code "
"= " + markup_parameters->file_map[markup_parameters->filename]);
markup_parameters->server._delete(markup_parameters->database + ".ds" +
local_args.dsnum2 + "_frequencies", markup_parameters->file_type +
"ID_code = " + markup_parameters->file_map[markup_parameters->filename]);
markup_parameters->server._delete(markup_parameters->database + ".ds" +
local_args.dsnum2 + "_IDList", markup_parameters->file_type + "ID_code = "
+ markup_parameters->file_map[markup_parameters->filename]);
}
void clear_tables(MarkupParameters *markup_parameters) {
if (markup_parameters->markup_type == "GrML") {
clear_grml_tables(markup_parameters);
} else if (markup_parameters->markup_type == "ObML") {
clear_obml_tables(markup_parameters);
} else if (markup_parameters->markup_type == "SatML") {
clear_satml_tables(markup_parameters);
} else if (markup_parameters->markup_type == "FixML") {
clear_fixml_tables(markup_parameters);
}
}
struct GrMLParameters : public MarkupParameters {
GrMLParameters() : prod_set(), summ_lev(false) {
markup_type = "GrML";
element = "grid";
data_type = "grids";
}
unordered_set<string> prod_set;
bool summ_lev;
};
struct ParameterData {
ParameterData() : min_nsteps(0x7fffffff), max_nsteps(0), level_codes(),
level_code_list() { }
size_t min_nsteps, max_nsteps;
unordered_set<size_t> level_codes;
vector<size_t> level_code_list;
};
void process_grml_markup(void *markup_parameters) {
static const string F = this_function_label(__func__);
auto gp = reinterpret_cast<GrMLParameters *>(markup_parameters);
static xmlutils::ParameterMapper PMAP(metautils::directives.
parameter_map_path);
unordered_map<string, string> tr_map, gd_map, lev_map;
unordered_map<string, shared_ptr<ParameterData>> pdmap, pdmap2;
unordered_set<string> p_set;
string mndt = "3000-12-31 23:59 +0000";
string mxdt = "0001-01-01 00:00 +0000";
auto cnt = 0;
auto b = false, b2 = false;
for (const auto& g : gp->xdoc.element_list("GrML/" + gp->element)) {
auto tr = g.attribute_value("timeRange");
auto prod = to_lower(tr);
if (strutils::contains(prod, "forecast")) {
prod = prod.substr(0, prod.find("forecast") + 8);
auto sp = split(prod);
if (sp.size() > 2) {
prod = sp[sp.size() - 2] + " " + sp[sp.size() - 1];
}
}
if (gp->prod_set.find(prod) == gp->prod_set.end()) {
gp->prod_set.emplace(prod);
}
auto def = g.attribute_value("definition");
string defp = "";
for (const auto& a : g.attribute_list()) {
auto n = a.name;
if (n != "timeRange" && n != "definition") {
if (n == "isCell") {
def += "Cell";
} else {
if (!defp.empty()) {
defp += ":";
}
defp += g.attribute_value(n);
}
}
}
if (tr_map.find(tr) == tr_map.end()) {
auto c = table_code(gp->server, gp->database + ".timeRanges",
"timeRange = '" + tr + "'");
if (c.empty()) {
log_error2("unable to get time range code", F, "scm", USER);
}
tr_map.emplace(tr, c);
}
auto gdef = def + ":" + defp;
if (gd_map.find(gdef) == gd_map.end()) {
MySQL::LocalQuery q;
auto c = table_code(gp->server, gp->database + ".gridDefinitions",
"definition = '" + def + "' AND defParams = '" + defp + "'");
if (c.empty()) {
log_error2("unable to get grid definition code", F, "scm", USER);
}
gd_map.emplace(gdef, c);
}
auto nens = g.element_list("ensemble").size();
if (nens == 0) {
nens = 1;
}
pdmap.clear();
pdmap2.clear();
for (const auto& ge : g.element_addresses()) {
auto enam = ge.p->name();
if (enam == "process") {
if (!b) {
if (!table_exists(gp->server, gp->database + ".ds" + local_args.dsnum2 + "_processes")) {
string r;
if (gp->server.command("create table " + gp->database + ".ds" +
local_args.dsnum2 + "_processes like " + gp->database +
".template_processes", r) < 0) {
log_error2("error: '" + gp->server.error() + "' while creating "
"table " + gp->database + ".ds" + local_args.dsnum2 +
"_processes", F, "scm", USER);
}
}
b = true;
}
if (gp->server.insert(gp->database + ".ds" + local_args.dsnum2 +
"_processes", gp->file_map[gp->filename] + ", " + tr_map[tr] + ", "
+ gd_map[gdef] + ", '" + ge.p->attribute_value("value") + "'") <
0) {
if (!strutils::contains(gp->server.error(), "Duplicate entry")) {
log_error2("error: '" + gp->server.error() + "' while inserting "
"into " + gp->database + ".ds" + local_args.dsnum2 +
"_processes", F, "scm", USER);
}
}
} else if (enam == "ensemble") {
if (!b2) {
if (!table_exists(gp->server, gp->database + ".ds" + local_args.
dsnum2 + "_ensembles")) {
string r;
if (gp->server.command("create table " + gp->database + ".ds" +
local_args.dsnum2 + "_ensembles like " + gp->database +
".template_ensembles", r) < 0) {
log_error2("error: '" + gp->server.error() + " while creating "
"table " + gp->database + ".ds" + local_args.dsnum2 +
"_ensembles", F, "scm", USER);
}
}
b2 = true;
}
auto v = ge.p->attribute_value("size");
if (v.empty()) {
v = "0";
}
if (gp->server.insert(gp->database + ".ds" + local_args.dsnum2 +
"_ensembles", gp->file_map[gp->filename] + ", " + tr_map[tr] + ", "
+ gd_map[gdef] + ", '" + ge.p->attribute_value("type") + "', '" +
ge.p->attribute_value("ID") + "', " + v) < 0) {
if (!strutils::contains(gp->server.error(), "Duplicate entry")) {
log_error2("error: '" + gp->server.error() + "' while inserting "
"into " + gp->database + ".ds" + local_args.dsnum2 +
"_ensembles", F, "scm", USER);
}
}
} else if (enam == "level" || enam == "layer") {
auto lm = ge.p->attribute_value("map");
auto lt = ge.p->attribute_value("type");
auto lv = ge.p->attribute_value("value");
if (lv.empty()) {
lv = ge.p ->attribute_value("bottom") + "," + ge.p->attribute_value(
"top");
}
auto ltyp = lm + ":" + lt + ":" + lv;
if (lev_map.find(ltyp) == lev_map.end()) {
auto c = table_code(gp->server, gp->database + ".levels", "map = '" +
lm + "' AND type = '" + lt + "' AND value = '" + lv + "'");
if (c.empty()) {
log_error2("unable to get level code", F, "scm", USER);
}
lev_map.emplace(ltyp, c);
}
if (gp->server.insert(gp->database + ".ds" + local_args.dsnum2 +
"_levels", gp->format_map[gp->format] + ", " + lev_map[ltyp]) < 0) {
if (!strutils::contains(gp->server.error(), "Duplicate entry")) {
log_error2("error: '" + gp->server.error() + "' while inserting "
"into " + gp->database + ".ds" + local_args.dsnum2 + "_levels",
F, "scm", USER);
}
} else {
gp->summ_lev = true;
}
// parameters
for (const auto& e : ge.p->element_addresses()) {
auto lm = e.p->attribute_value("map");
auto lv = e.p->attribute_value("value");
size_t nsteps = stoi(e.p->attribute_value("nsteps"));
cnt += nsteps;
nsteps /= nens;
auto x = e.p->attribute_value("start");
if (x < mndt) {
mndt = x;
}
x = e.p->attribute_value("end");
if (x > mxdt) {
mxdt = x;
}
auto p = lm + ":" + lv + "@" + lt;
if (p[0] == ':') {
p = p.substr(1);
}
if (p_set.find(p) == p_set.end()) {
auto d = PMAP.description(gp->format, p);
replace_all(d, "'", "\\'");
if (gp->server.insert("search.variables", "'" + d + "', 'CMDMAP', '"
+ metautils::args.dsnum + "'") < 0) {
if (!strutils::contains(gp->server.error(), "Duplicate entry")) {
log_error2("error: '" + gp->server.error() + "' while "
"inserting into search.variables", F, "scm", USER);
}
} else {
local_args.added_variable = true;
}
p_set.emplace(p);
}
auto sv = e.p->attribute_value("start").substr(0, 16);
replace_all(sv, "-", "");
replace_all(sv, " ", "");
replace_all(sv, ":", "");
auto ev = e.p->attribute_value("end").substr(0, 16);
replace_all(ev, "-", "");
replace_all(ev, " ", "");
replace_all(ev, ":", "");
if (strutils::contains(p, "@")) {
p = p.substr(0, p.find("@"));
}
p += "<!>" + sv + "<!>" + ev;
auto i = stoi(lev_map[ltyp]);
if (pdmap.find(p) == pdmap.end()) {
pdmap.emplace(p, shared_ptr<ParameterData>(new ParameterData));
}
if (nsteps < pdmap[p]->min_nsteps) {
pdmap[p]->min_nsteps = nsteps;
}
if (nsteps > pdmap[p]->max_nsteps) {
pdmap[p]->max_nsteps = nsteps;
}
if (pdmap[p]->level_codes.find(i) == pdmap[p]->level_codes.end()) {
pdmap[p]->level_codes.emplace(i);
pdmap[p]->level_code_list.emplace_back(i);
}
p += "<!>" + itos(nsteps);
if (pdmap2.find(p) == pdmap2.end()) {
pdmap2.emplace(p, shared_ptr<ParameterData>(new ParameterData));
}
if (pdmap2[p]->level_codes.find(i) == pdmap2[p]->level_codes.
end()) {
pdmap2[p]->level_codes.emplace(i);
pdmap2[p]->level_code_list.emplace_back(i);
}
}
}
}
for (auto& e : pdmap) {
sort(e.second->level_code_list.begin(), e.second->level_code_list.end(),
[](const size_t& left, const size_t& right) -> bool {
if (left <= right) {
return true;
}
return false;
});
string s;
bitmap::compress_values(e.second->level_code_list, s);
auto sp = split(e.first, "<!>");
if (gp->server.insert(gp->database + ".ds" + local_args.dsnum2 + "_grids",
gp->file_type + "ID_code, timeRange_code, gridDefinition_code, "
"parameter, levelType_codes, start_date, end_date, min_nsteps, "
"max_nsteps", gp->file_map[gp->filename] + ", " + tr_map[tr] + ", " +
gd_map[gdef] + ", '" + sp[0] + "', '" + s + "', " + sp[1] + ", " + sp[
2] + ", " + itos(e.second->min_nsteps) + ", " + itos(e.second->
max_nsteps), "") < 0) {
log_error2("error: '" + gp->server.error() + " while inserting into " +
gp->database + ".ds" + local_args.dsnum2 + "_grids", F, "scm",
USER);
}
e.second.reset();
}
if (table_exists(gp->server, gp->database + ".ds" + local_args.dsnum2 +
"_grids2")) {
for (auto& e : pdmap2) {
sort(e.second->level_code_list.begin(), e.second->level_code_list.end(),
[](const size_t& left, const size_t& right) -> bool {
if (left <= right) {
return true;
}
return false;
});
string s;
bitmap::compress_values(e.second->level_code_list, s);
auto sp = split(e.first, "<!>");
if (gp->server.insert(gp->database + ".ds" + local_args.dsnum2 +
"_grids2", gp->file_type + "ID_code, timeRange_code, "
"gridDefinition_code, parameter, levelType_codes, start_date, "
"end_date, nsteps", gp->file_map[gp->filename] + ", " + tr_map[tr] +
", " + gd_map[gdef] + ", '" + sp[0] + "', '" + s + "', " + sp[1] +
", " + sp[2] + ", " + sp[3], "") < 0) {
log_error2("error: '" + gp->server.error() + " while inserting into "
+ gp->database + ".ds" + local_args.dsnum2 + "_grids2", F, "scm",
USER);
}
e.second.reset();
}
}
}
replace_all(mndt, "-", "");
replace_all(mndt, " ", "");
replace_all(mndt, ":", "");
replace_all(mndt, "+0000", "");
replace_all(mxdt, "-", "");
replace_all(mxdt, " ", "");
replace_all(mxdt, ":", "");
replace_all(mxdt, "+0000", "");
auto s = "num_grids = " + itos(cnt) + ", start_date = " + mndt + ", end_date "
"= " + mxdt;
auto tb_nam = gp->database + ".ds" + local_args.dsnum2 + "_" + gp->file_type +
"files2";
if (gp->server.update(tb_nam, s + ", uflag = '" + strand(5) + "'", "code = " +
gp->file_map[gp->filename]) < 0) {
log_error2("error: '" + gp->server.error() + " while updating " + tb_nam, F,
"scm", USER);
}
if (!table_exists(gp->server, gp->database + ".ds" + local_args.dsnum2 +
"_agrids")) {
string r;
if (gp->server.command("create table " + gp->database + ".ds" + local_args.
dsnum2 + "_agrids like " + gp->database + ".template_agrids", r) < 0) {
log_error2("error: '" + gp->server.error() + " while creating table " +
gp->database + ".ds" + local_args.dsnum2 + "_agrids", F, "scm", USER);
}
}
if (!table_exists(gp->server, gp->database + ".ds" + local_args.dsnum2 +
"_agrids2")) {
string r;
if (gp->server.command("create table " + gp->database + ".ds" + local_args.
dsnum2 + "_agrids2 like " + gp->database + ".template_agrids2", r) <
0) {
log_error2("error: '" + gp->server.error() + " while creating table " +
gp->database + ".ds" + local_args.dsnum2 + "_agrids2", F, "scm",
USER);
}
}
if (!table_exists(gp->server, gp->database + ".ds" + local_args.dsnum2 +
"_agrids_cache")) {
string r;
if (gp->server.command("create table " + gp->database + ".ds" + local_args.
dsnum2 + "_agrids_cache like " + gp->database +
".template_agrids_cache", r) < 0) {
log_error2("error: '" + gp->server.error() + " while creating table " +
gp->database + ".ds" + local_args.dsnum2 + "_agrids_cache", F, "scm",
USER);
}
}
if (!table_exists(gp->server, gp->database + ".ds" + local_args.dsnum2 +
"_grid_definitions")) {
string r;
if (gp->server.command("create table " + gp->database + ".ds" + local_args.
dsnum2 + "_grid_definitions like " + gp->database +
".template_grid_definitions", r) < 0) {
log_error2("error: '" + gp->server.error() + " while creating table " +
gp->database + ".ds" + local_args.dsnum2 + "_grid_definitions", F,
"scm", USER);
}
}
}
void *thread_summarize_IDs(void *args) {
static const string F = this_function_label(__func__);
auto &a = *(reinterpret_cast<vector<string> *>(args));
MySQL::Server srv(metautils::directives.database_server, metautils::
directives.metadb_username, metautils::directives.metadb_password, "");;
if (!srv) {
log_error2("could not connect to mysql server - error: '" + srv.error() +
"'", F, "scm", USER);
}
// read in the IDs from the separate XML file
auto f = remote_web_file("https://rda.ucar.edu" + a[0] + a[1], g_temp_dir.
name());
std::ifstream ifs(f.c_str());
if (!ifs.is_open()) {
log_error2("unable to open '" + a[0] + a[1] + "'", F, "scm", USER);
}
char l[32768];
double avgd = 0., navgd = 0., avgm = 0., navgm = 0.;
size_t obs_count = 0;
unordered_map<string, string> id_map;
ifs.getline(l, 32768);
while (!ifs.eof()) {
if (l[2] == '<' && l[3] == 'I' && l[4] == 'D') {
auto s = string(l);
while (l[3] != '/') {
ifs.getline(l, 32768);
s += l;
}
XMLSnippet snippet = s;
auto e = snippet.element("ID");
auto idtyp = e.attribute_value("type");
if (id_map.find(idtyp) == id_map.end()) {
auto c = table_code(srv, a[5] + ".IDTypes", "IDType = '" + idtyp + "'");
if (c.empty()) {
log_error2("unable to get id type code", F, "scm", USER);
}
id_map.emplace(idtyp, c);
}
auto ID = e.attribute_value("value");
replace_all(ID, "\\", "\\\\");
replace_all(ID, "'", "\\'");
replace_all(ID, """, "\"");
replace_all(ID, " = ", " &eq; ");
auto v = e.attribute_value("lat");
string sw_lat, sw_lon, ne_lat, ne_lon;
if (!v.empty()) {
sw_lat = ftos(stof(v) * 10000., 0);
sw_lon = ftos(stof(e.attribute_value("lon")) * 10000., 0);
ne_lat = sw_lat;
ne_lon = sw_lon;
} else {
v = e.attribute_value("cornerSW");
auto sp = split(v, ",");
if (sp.size() != 2) {
log_error2("error in cornerSW attribute for file code " + a[2] + ", '"
+ a[1] + "', '" + v + "'", F, "scm", USER);
}
sw_lat = metatranslations::string_coordinate_to_db(sp[0]);
sw_lon = metatranslations::string_coordinate_to_db(sp[1]);
v = e.attribute_value("cornerNE");
sp = split(v, ",");
if (sp.size() != 2) {
log_error2("error in cornerNE attribute for file code " + a[2], F,
"scm", USER);
}
ne_lat = metatranslations::string_coordinate_to_db(sp[0]);
ne_lon = metatranslations::string_coordinate_to_db(sp[1]);
}
if (sw_lon == "-9990000") {
sw_lon = "-8388608";
}
if (ne_lon == "-9990000") {
ne_lon = "-8388608";
}
auto ID_code = table_code(srv, a[5] + ".ds" + local_args.dsnum2 + "_IDs2",
"IDType_code = " + id_map[idtyp] + " AND ID = '" + ID + "' AND "
"sw_lat = " + sw_lat + " AND sw_lon = " + sw_lon + " AND ne_lat = " +
ne_lat + " AND ne_lon = " + ne_lon);
if (ID_code.empty()) {
log_error2("unable to get id code", F, "scm", USER);
}
v = e.attribute_value("start");
replace_all(v, "-", "");
while (strutils::occurs(v, " ") > 1) {
v = v.substr(0, v.rfind(" "));
}
replace_all(v, " ", "");
replace_all(v, ":", "");
while (v.length() < 14) {
v += "99";
}
DateTime dt1(stoll(v));
v = e.attribute_value("end");
replace_all(v, "-", "");
string tz = "0";
while (strutils::occurs(v, " ") > 1) {
auto idx = v.rfind(" ");
tz = v.substr(idx + 1);
if (tz[0] == '+') {
tz = tz.substr(1);
}
if (tz == "LST") {
tz = "-2400";
} else if (tz == "LT") {
tz = "2400";
}
v = v.substr(0, idx);
}
replace_all(v, " ", "");
replace_all(v, ":", "");
DateTime dt2;
if (v.length() == 8) {
dt2.set(stoll(v + "999999"));
} else {
while (v.length() < 14) {
v += "99";
}
dt2.set(stoll(v));
}
auto nobs = e.attribute_value("numObs");
if (srv.insert(a[5] + ".ds" + local_args.dsnum2 + "_IDList2", "ID_code, "
"observationType_code, platformType_code, " + a[6] + "ID_code, "
"num_observations, start_date, end_date, time_zone", ID_code + ", " +
a[3] + ", " + a[4] + ", " + a[2] + ", " + nobs + ", " + dt1.to_string(
"%Y%m%d%H%MM%SS") + ", " + dt2.to_string("%Y%m%d%H%MM%SS") + ", " +
tz, "") < 0) {
if (!regex_search(srv.error(), regex("Duplicate entry"))) {
log_error2("'" + srv.error() + "' while inserting '" + ID_code + ", "
+ a[3] + ", " + a[4] + ", " + a[2] + ", " + nobs + ", " + dt1.
to_string("%Y%m%d%H%MM%SS") + ", " + dt2.to_string(
"%Y%m%d%H%MM%SS") + ", " + tz + "' into " + a[5] + ".ds" +
local_args.dsnum2 + "_IDList2", F, "scm", USER);
}
}
for (const auto& element : e.element_list("dataType")) {
if (dt2 != dt1 || (dt1.time() == 999999 && dt2.time() == 999999)) {
auto v = element.attribute_value("numObs");
// backward compatibility for content metadata that was generated
// before the number of observations by data type was captured
if (v.empty()) {
v = nobs;
}
auto i = stoi(v);
if (i > 1) {
if (dt2.time() == 999999) {
dt2.add_days(1);
}
double d;
d = dt2.days_since(dt1);
if (d == 0 && dt2.seconds_since(dt1) > 0) {
d = 1;
}
if (d > 0) {
avgd += i / d;
++navgd;
obs_count += i;
}
d = dt2.months_since(dt1);
if (d > 0) {
avgm += i / d;
++navgm;
}
}
}
}
}
ifs.getline(l, 32768);
}
ifs.close();
if (navgd > 0.) {
avgd /= navgd;
}
if (navgm > 0.) {
avgm /= navgm;
}
// srv._delete(t->args[5]+".ds"+local_args.dsnum2+"_frequencies",file_ID_type+"ID_code = "+file_ID_code+" and observationType_code = "+t->args[3]+" and platformType_code = "+t->args[4]);
string u;
if (lround(avgd) >= 1) {
avgd /= 24.;
if (lround(avgd) >= 1) {
avgd /= 60.;
if (lround(avgd) >= 1) {
avgd /= 60.;
if (lround(avgd) >= 1) {
u = "second";
} else {
avgd *= 60.;
u = "minute";
}
} else {
avgd *= 60.;
u = "hour";
}
} else {
avgd *= 24.;
u = "day";
}
} else {
avgd *= 7.;
if (lround(avgd) >= 1) {
u = "week";
} else {
if (lround(avgm) >= 1) {
u = "month";
} else {
avgm *= 12.;
if (lround(avgm) >= 1) {
u = "year";
} else {
avgm *= 10.;
if (lround(avgm) >= 1) {
u = "decade";
}
}
}
}
}
string i, k;
if (lround(avgd) >= 1) {
i = itos(lround(avgd));
k = searchutils::time_resolution_keyword("irregular", lround(avgd), u, "");
} else {
i = itos(lround(avgm));
k = searchutils::time_resolution_keyword("irregular", lround(avgm), u, "");
}
string r;
if (i != "0" && srv.command("insert into " + a[5] + ".ds" + local_args.dsnum2
+ "_frequencies values (" + a[2] + ", " + a[3] + ", " + a[4] + ", " + i +
", " + itos(obs_count) + ", '" + u + "', '" + a[7] + "') on duplicate "
"key update avg_obs_per = values(avg_obs_per), total_obs = values("
"total_obs), uflag = values(uflag)", r) < 0) {
if (!regex_search(srv.error(), regex("Duplicate entry"))) {
log_error2("'" + srv.error() + "' while trying to insert into " + a[5] +
".ds" + local_args.dsnum2 + "_frequencies (" + a[2] + ", " + a[3] +
", " + a[4] + ", " + i + ", " + itos(obs_count) + ", '" + u + "')", F,
"scm", USER);
}
}
if (a[5] == "WObML" && srv.command("insert into " + a[5] + ".ds" + local_args.
dsnum2 + "_geobounds (select i2.webID_code, min(i.sw_lat), "
"min(i.sw_lon), max(i.ne_lat), max(i.ne_lon) from " + a[5] + ".ds" +
local_args.dsnum2 + "_IDList2 as i2 left join " + a[5] + ".ds" +
local_args.dsnum2 + "_IDs2 as i on i.code = i2.ID_code where i2."
"webID_code = " + a[2] + " and i.sw_lat > -990000 and i.sw_lon > "
"-1810000 and i.ne_lat < 990000 and i.ne_lon < 1810000) on duplicate key "
"update min_lat = values(min_lat), max_lat = values(max_lat), min_lon "
"= values(min_lon), max_lon = values(max_lon)", r) < 0) {
log_error2("'" + srv.error() + "' while trying to insert into " + a[5] +
".ds" + local_args.dsnum2 + "_geobounds for webID_code = " + a[2], F,
"scm", USER);
}
srv.disconnect();
return nullptr;
}
void *thread_summarize_file_ID_locations(void *args) {
static const string F = this_function_label(__func__);
static unordered_map<string, vector<string>> lmap;
auto &a = *reinterpret_cast<vector<string> *>(args);
MySQL::Server srv(metautils::directives.database_server, metautils::
directives.metadb_username, metautils::directives.metadb_password, "");;
if (!srv)
log_error2("could not connect to mysql server - error: " + srv.error(), F,
"scm", USER);
if (lmap.size() == 0) {
MySQL::LocalQuery q("box1d_row, box1d_column, keyword", "search."
"locations_by_point");
if (q.submit(srv) < 0)
log_error2("'" + q.error() + "'", F, "scm", USER);
for (const auto& r : q) {
auto k = r["box1d_row"] + "," + r["box1d_column"];
if (lmap.find(k) == lmap.end()) {
lmap.emplace(k, vector<string>());
}
lmap[k].emplace_back(r["keyword"]);
}
}
auto f = remote_web_file("https://rda.ucar.edu" + a[0] + a[1], g_temp_dir.
name());
XMLDocument xdoc;
if (xdoc.open(f)) {
unordered_set<string> lset;
size_t min = 999;
size_t max = 0;
for (const auto& e : xdoc.element_list("locations/box1d")) {
auto b = e.attribute_value("bitmap");
string lb;
if (b.length() == 360) {
lb = "";
for (size_t n = 0; n < 360; n += 3) {
auto l = 0;
for (size_t m = 0; m < 3; ++m) {
if (b[n + m] == '1') {
auto k = e.attribute_value("row") + "," + itos(n + m);
if (lmap.find(k) != lmap.end()) {
for (const auto& e : lmap[k]) {
if (lset.find(e) == lset.end()) {
lset.emplace(e);
}
}
}
l += pow(2., 2 - m);
}
}
lb += itos(l);
}
} else {
lb = b;
}
auto s = a[2] + ", " + a[3];
if (!a[4].empty()) {
s += ", " + a[4];
}
s += ", " + a[5] + ", " + a[6] + ", " + e.attribute_value("row") + ", '" +
lb + "'";
if (srv.insert(a[7] + ".ds" + local_args.dsnum2 + "_locations", s) < 0) {
if (!regex_search(srv.error(), regex("Duplicate entry"))) {
log_error2("'" + srv.error() + "' while trying to insert into " + a[7]
+ ".ds" + local_args.dsnum2 + "_locations (" + s + ") into " + a[
7] + ".ds" + local_args.dsnum2 + "_locations", F, "scm", USER);
}
}
size_t i = stoi(e.attribute_value("row"));
if (min == 999) {
min = i;
max = min;
} else {
if (i < min) {
min = i;
}
if (i > max) {
max = i;
}
}
}
if (lset.size() > 0) {
my::map<gatherxml::summarizeMetadata::ParentLocation> pmap;
vector<string> v;
compress_locations(lset, pmap, v, "scm", USER);
if (a[7] == "WObML") {
srv._delete("WObML.ds" + local_args.dsnum2 + "_location_names",
"webID_code = " + a[2] + " and observationType_code = " + a[3] +
" and platformType_code = " + a[4]);
} else if (a[7] == "WFixML") {
srv._delete("WFixML.ds" + local_args.dsnum2 + "_location_names",
"webID_code = " + a[2] + " and classification_code = " + a[3]);
}
for (const auto& i : v) {
gatherxml::summarizeMetadata::ParentLocation pl;
pmap.found(i, pl);
if (pl.matched_set != nullptr) {
if (pl.matched_set->size() > pl.children_set->size() / 2) {
replace_all(pl.key, "'", "\\'");
string s;
if (!a[4].empty()) {
s = a[2] + ", " + a[3] + ", " + a[4] + ", '" + pl.key + "', 'Y'";
} else {
s = a[2] + ", " + a[3] + ", '" + pl.key + "', 'Y'";
}
if (srv.insert(a[7] + ".ds" + local_args.dsnum2 + "_location_names",
s) < 0) {
log_error2("'" + srv.error() + "' while inserting '" + s +
"' into " + a[7] + ".ds" + local_args.dsnum2 +
"_location_names", F, "scm", USER);
}
for (auto key : *pl.children_set) {
replace_all(key, "'", "\\'");
if (pl.matched_set->find(key) == pl.matched_set->end() && pl.
consolidated_parent_set->find(key) == pl.
consolidated_parent_set->end()) {
if (!a[4].empty()) {
s = a[2] + ", " + a[3] + ", " + a[4] + ", '" + key + "', 'N'";
} else {
s = a[2] + ", " + a[3] + ", '" + key + "', 'N'";
}
if (srv.insert(a[7] + ".ds" + local_args.dsnum2 +
"_location_names", s) < 0) {
log_error2("'" + srv.error() + "' while inserting '" + s +
"' into " + a[7] + ".ds" + local_args.dsnum2 +
"_location_names", F, "scm", USER);
}
}
}
} else {
for (auto key : *pl.matched_set) {
replace_all(key, "'", "\\'");
string s;
if (!a[4].empty()) {
s = a[2] + ", " + a[3] + ", " + a[4] + ", '" + key + "', 'Y'";
} else {
s = a[2] + ", " + a[3] + ", '" + key + "', 'Y'";
}
if (srv.insert(a[7] + ".ds" + local_args.dsnum2 +
"_location_names", s) < 0) {
log_error2("'" + srv.error() + "' while inserting '" + s +
"' into " + a[7] + ".ds" + local_args.dsnum2 +
"_location_names", F, "scm", USER);
}
}
}
pl.matched_set.reset();
}
pl.children_set.reset();
pl.consolidated_parent_set.reset();
}
}
xdoc.close();
} else {
log_error2("unable to open referenced XML document '" + f + "'", F, "scm",
USER);
}
srv.disconnect();
return nullptr;
}
struct ObMLParameters : public MarkupParameters {
ObMLParameters() : metadata_path() {
markup_type = "ObML";
element = "observationType";
data_type = "observations";
}
string metadata_path;
};
void process_obml_markup(void *markup_parameters) {
auto op = reinterpret_cast<ObMLParameters *>(markup_parameters);
static const string F = this_function_label(__func__);
string mndt = "30001231";
string mxdt = "10000101";
auto cnt = 0;
auto uflag = strand(3);
unordered_map<string, string> obs_map, plat_map, dtyp_map;
unordered_set<string> kml_table;
for (const auto& o : op->xdoc.element_list("ObML/" + op->element)) {
auto obs = o.attribute_value("value");
if (obs_map.find(obs) == obs_map.end()) {
auto c = table_code(op->server, op->database + ".obsTypes", "obsType = '"
+ obs + "'");
if (c.empty()) {
log_error2("unable to get observation type code", F, "scm", USER);
}
obs_map.emplace(obs, c);
}
for (const auto& platform : o.element_addresses()) {
auto plat = (platform.p)->attribute_value("type");
if (plat_map.find(plat) == plat_map.end()) {
auto c = table_code(op->server, op->database + ".platformTypes",
"platformType = '" + plat + "'");
if (c.empty()) {
log_error2("unable to get platform code", F, "scm", USER);
}
plat_map.emplace(plat, c);
}
for (const auto& e : (platform.p)->element_list("dataType")) {
auto dtyp = e.attribute_value("map");
if (!dtyp.empty()) {
dtyp += ":";
}
dtyp += e.attribute_value("value");
auto dtyp_k = obs_map[obs] + "|" + plat_map[plat] + "|" + dtyp;
if (dtyp_map.find(dtyp_k) == dtyp_map.end()) {
MySQL::LocalQuery q("code", op->database + ".ds" + local_args.dsnum2 +
"_dataTypesList", "observationType_code = " + obs_map[obs] +
" and platformType_code = " + plat_map[plat] + " and dataType = '"
+ dtyp + "'");
if (q.submit(op->server) < 0) {
log_error2("'" + q.error() + "' while trying to get dataType code "
"(1) for '" + obs_map[obs] + ", " + plat_map[plat] + ", '" +
dtyp + "''", F, "scm", USER);
}
string c;
MySQL::Row r;
if (q.fetch_row(r)) {
c = r[0];
} else {
if (op->server.insert(op->database + ".ds" + local_args.dsnum2 +
"_dataTypesList", obs_map[obs] + ", " + plat_map[plat] + ", '"
+ dtyp + "', NULL") < 0) {
log_error2("'" + op->server.error() + "' while trying to insert '"
+ obs_map[obs] + ", " + plat_map[plat] + ", '" + dtyp +
"'' into " + op->database + ".ds" + local_args.dsnum2 +
"_dataTypesList", F, "scm", USER);
}
auto lid = op->server.last_insert_ID();
if (lid == 0) {
log_error2("'" + q.error() + "' while trying to get dataType "
"code (2) for '" + obs_map[obs] + ", " + plat_map[plat] +
", '" + dtyp + "''", F, "scm", USER);
} else {
c = lltos(lid);
}
}
dtyp_map.emplace(dtyp_k, c);
}
string s = op->file_map[op->filename] + ", " + dtyp_map[dtyp_k];
auto v = e.element("vertical");
if (v.name() == "vertical") {
s += ", " + v.attribute_value("min_altitude") + ", " + v.
attribute_value("max_altitude") + ", '" + v.attribute_value(
"vunits") + "', " + v.attribute_value("avg_nlev") + ", " + v.
attribute_value("avg_vres");
} else {
s += ", 0, 0, NULL, 0, NULL";
}
/*
if (op->server.insert(op->database+".ds"+local_args.dsnum2+"_dataTypes",s) < 0) {
error=op->server.error();
if (!strutils::contains(error,"Duplicate entry")) {
metautils::log_error("summarize_obml() returned error: "+error+" while trying to insert '"+s+"' into "+op->database+".ds"+local_args.dsnum2+"_dataTypes","scm",user,args.args_string);
}
}
*/
if (op->server.insert(op->database + ".ds" + local_args.dsnum2 +
"_dataTypes2", s) < 0) {
log_error2("'" + op->server.error() + "' while trying to insert '" + s
+ "' into " + op->database + ".ds" + local_args.dsnum2 +
"_dataTypes2", F, "scm", USER);
}
}
cnt += stoi((platform.p)->attribute_value("numObs"));
string ts, te;
vector<pthread_t> tv;
list<vector<string>> targs;
for (const auto& e : platform.p->element_addresses()) {
if (e.p->name() == "IDs") {
targs.emplace_back(vector<string>());
targs.back().emplace_back(op->metadata_path);
targs.back().emplace_back(e.p->attribute_value("ref"));
targs.back().emplace_back(op->file_map[op->filename]);
targs.back().emplace_back(obs_map[obs]);
targs.back().emplace_back(plat_map[plat]);
targs.back().emplace_back(op->database);
targs.back().emplace_back(op->file_type);
targs.back().emplace_back(uflag);
pthread_t t;
pthread_create(&t, nullptr, thread_summarize_IDs, &targs.back());
tv.emplace_back(t);
} else if (e.p->name() == "temporal") {
ts = e.p->attribute_value("start");
replace_all(ts, "-", "");
if (ts < mndt) {
mndt = ts;
}
te = e.p->attribute_value("end");
replace_all(te, "-", "");
if (te > mxdt) {
mxdt = te;
}
} else if (e.p->name() == "locations") {
// read in the locations from the separate XML file
targs.emplace_back(vector<string>());
targs.back().emplace_back(op->metadata_path);
targs.back().emplace_back(e.p->attribute_value("ref"));
targs.back().emplace_back(op->file_map[op->filename]);
targs.back().emplace_back(obs_map[obs]);
targs.back().emplace_back(plat_map[plat]);
targs.back().emplace_back(ts);
targs.back().emplace_back(te);
targs.back().emplace_back(op->database);
pthread_t t;
pthread_create(&t, nullptr, thread_summarize_file_ID_locations,
&targs.back());
tv.emplace_back(t);
}
}
for (const auto& t : tv) {
pthread_join(t, nullptr);
}
}
}
op->server._delete(op->database + ".ds" + local_args.dsnum2 + "_frequencies",
op->file_type + "ID_code = " + op->file_map[op->filename] + " and uflag "
"!= '" + uflag + "'");
auto s = "num_observations = " + itos(cnt) + ", start_date = " + mndt + ", "
"end_date = " + mxdt;
auto tb_nam = op->database + ".ds" + local_args.dsnum2 + "_" + op->file_type +
"files2";
if (op->server.update(tb_nam, s + ", uflag = '" + strand(5) + "'", "code = " +
op->file_map[op->filename]) < 0) {
log_error2("error: '" + op->server.error() + "' while updating " + tb_nam +
" with '" + s + "'", F, "scm", USER);
}
}
struct SatMLParameters : public MarkupParameters {
SatMLParameters() {
markup_type = "SatML";
element = "satellite";
data_type = "products";
}
};
void process_satml_markup(void *markup_parameters) {
static const string F = this_function_label(__func__);
auto sp = reinterpret_cast<SatMLParameters *>(markup_parameters);
string mndt = "3000-12-31 23:59:59 +0000";
string mxdt = "1000-01-01 00:00:00 +0000";
string ptyp;
auto cnt = 0;
auto b = false;
for (const auto& sat : sp->xdoc.element_list("SatML/" + sp->element)) {
auto n = 0;
auto ilst = sat.element_list("images");
if (ilst.size() > 0) {
ptyp = "I";
auto e = sat.element("temporal");
if (e.attribute_value("start") < mndt) {
mndt = e.attribute_value("start");
}
if (e.attribute_value("end") > mxdt) {
mxdt = e.attribute_value("end");
}
for (const auto& i : ilst) {
n += stoi(i.attribute_value("num"));
}
cnt += n;
} else {
auto swlst = sat.element_list("swath/data");
ptyp = "S";
for (const auto& s : swlst) {
auto e = s.element("temporal");
if (e.attribute_value("start") < mndt) {
mndt = e.attribute_value("start");
}
if (e.attribute_value("end") > mxdt) {
mxdt = e.attribute_value("end");
}
e = s.element("scanLines");
n = stoi(e.attribute_value("num"));
cnt += n;
}
}
if (!b) {
if (!table_exists(sp->server, sp->database + ".ds" + local_args.dsnum2 + "_products")) {
string r;
if (sp->server.command("create table " + sp->database + ".ds" +
local_args.dsnum2 + "_products like " + sp->database +
".template_products", r) < 0) {
log_error2("error: '" + sp->server.error() + "' while creating table "
+ sp->database + ".ds" + local_args.dsnum2 + "_products", F,
"scm", USER);
}
}
b = true;
}
if (sp->server.insert(sp->database + ".ds" + local_args.dsnum2 +
"_products", sp->file_map[sp->filename] + ", '" + ptyp + "', " + itos(
n)) < 0) {
if (!strutils::contains(sp->server.error(), "Duplicate entry")) {
log_error2("error: '" + sp->server.error() + "' while inserting into " +
sp->database + ".ds" + local_args.dsnum2 + "_products", F, "scm",
USER);
}
}
}
replace_all(mndt, " ", "");
replace_all(mndt, "-", "");
replace_all(mndt, ":", "");
replace_all(mndt, "+0000", "");
replace_all(mxdt, " ", "");
replace_all(mxdt, "-", "");
replace_all(mxdt, ":", "");
replace_all(mxdt, "+0000", "");
auto s = "num_products = " + itos(cnt) + ", start_date = " + mndt + ", "
"end_date = " + mxdt;
auto tb_nam = sp->database + ".ds" + local_args.dsnum2 + "_" + sp->file_type +
"files2";
if (sp->server.update(tb_nam, s + ", uflag = '" + strand(5) + "'", "code = " +
sp->file_map[sp->filename]) < 0) {
log_error2("error: '" + sp->server.error() + "' while updating " + tb_nam +
" with '" + s + "'", F, "scm", USER);
}
}
struct FixMLParameters : public MarkupParameters {
FixMLParameters() : markup_path(), stg_map(), class_map(), freq_map() {
markup_type = "FixML";
element = "feature";
data_type = "fixes";
}
string markup_path;
unordered_map<string, string> stg_map;
unordered_map<string, pair<string, string>> class_map;
unordered_map<string, pair<size_t, size_t>> freq_map;
};
void process_fixml_markup(void *markup_parameters) {
static const string F = this_function_label(__func__);
auto fp = reinterpret_cast<FixMLParameters *>(markup_parameters);
string mndt = "30001231235959";
string mxdt = "10000101000000";
auto cnt = 0;
for (const auto& f : fp->xdoc.element_list("FixML/" + fp->element)) {
for (const auto& _class : f.element_list("classification")) {
auto stg = _class.attribute_value("stage");
if (fp->class_map.find(stg) == fp->class_map.end()) {
fp->class_map.emplace(stg, make_pair("30001231235959",
"10000101000000"));
}
cnt += stoi(_class.attribute_value("nfixes"));
if (fp->stg_map.find(stg) == fp->stg_map.end()) {
auto c = table_code(fp->server, fp->database + ".classifications",
"classification = '" + stg + "'");
if (c.empty()) {
log_error2("unable to get cyclone stage code", F, "scm", USER);
}
fp->stg_map.emplace(stg, c);
}
if (fp->server.insert(fp->database + ".ds" + local_args.dsnum2 +
"_IDList", "'" + f.attribute_value("ID") + "', " + fp->stg_map[stg] +
", " + fp->file_map[fp->filename] + ", " + _class.attribute_value(
"nfixes"), "update num_fixes = num_fixes + " + _class.attribute_value(
"nfixes")) < 0) {
log_error2("error: '" + fp->server.error() + "' while inserting '" +
f.attribute_value("ID") + "', " + fp->stg_map[stg] + ", " + fp->
file_map[fp->filename] + ", " + _class.attribute_value("nfixes") +
"' into " + fp->database + ".ds" + local_args.dsnum2 + "_IDList", F,
"scm", USER);
}
auto e = _class.element("start");
auto v = e.attribute_value("dateTime");
replace_all(v, " ", "");
replace_all(v, "-", "");
replace_all(v, ":", "");
v = v.substr(0, v.length() - 5);
if (v < mndt) {
mndt = v;
}
if (v < fp->class_map[stg].first) {
fp->class_map[stg].first = v;
}
while (v.length() < 14) {
v += "00";
}
auto dt1 = DateTime(stoll(v));
e = _class.element("end");
v = e.attribute_value("dateTime");
replace_all(v, " ", "");
replace_all(v, "-", "");
replace_all(v, ":", "");
v = v.substr(0, v.length() - 5);
if (v > mxdt) {
mxdt = v;
}
if (v > fp->class_map[stg].second) {
fp->class_map[stg].second = v;
}
while (v.length() < 14) {
v += "00";
}
auto dt2 = DateTime(stoll(v));
size_t n = stoi(_class.attribute_value("nfixes"));
if (n > 1) {
n = lroundf(24. / (dt2.hours_since(dt1) / static_cast<float>(n - 1)));
/*
if (n != 4)
cerr << n << " " << dt1.to_string() << " " << dt2.to_string() << endl;
*/
auto k = "day<!>" + fp->stg_map[stg];
if (fp->freq_map.find(k) == fp->freq_map.end()) {
fp->freq_map.emplace(k, make_pair(n, n));
} else {
if (n < fp->freq_map[k].first) {
fp->freq_map[k].first = n;
}
if (n > fp->freq_map[k].second) {
fp->freq_map[k].second = n;
}
}
}
}
}
auto s = "num_fixes = " + itos(cnt) + ", start_date = " + mndt + ", end_date "
"= " + mxdt;
auto tb_nam = fp->database + ".ds" + local_args.dsnum2 + "_" + fp->file_type +
"files2";
if (fp->server.update(tb_nam, s + ", uflag = '" + strand(5) + "'", "code = " +
fp->file_map[fp->filename]) < 0) {
log_error2("error: '" + fp->server.error() + "' while updating " + tb_nam +
" with '" + s + "'", F, "scm", USER);
}
}
void process_markup(MarkupParameters *markup_parameters) {
if (markup_parameters->markup_type == "GrML") {
process_grml_markup(markup_parameters);
} else if (markup_parameters->markup_type == "ObML") {
process_obml_markup(markup_parameters);
} else if (markup_parameters->markup_type == "FixML") {
process_fixml_markup(markup_parameters);
}
}
void update_grml_database(GrMLParameters& grml_parameters) {
gatherxml::summarizeMetadata::aggregate_grids(grml_parameters.database, "scm",
USER, grml_parameters.file_map[grml_parameters.filename]);
if (grml_parameters.database == "WGrML") {
gatherxml::summarizeMetadata::summarize_frequencies("scm", USER,
grml_parameters.file_map[grml_parameters.filename]);
gatherxml::summarizeMetadata::summarize_grid_resolutions("scm", USER,
grml_parameters.file_map[grml_parameters.filename]);
}
gatherxml::summarizeMetadata::summarize_grids(grml_parameters.database, "scm",
USER, grml_parameters.file_map[grml_parameters.filename]);
if (grml_parameters.summ_lev) {
gatherxml::summarizeMetadata::summarize_grid_levels(grml_parameters.
database, "scm", USER);
}
}
void update_obml_database(ObMLParameters& obml_parameters) {
if (obml_parameters.database == "WObML") {
gatherxml::summarizeMetadata::summarize_frequencies("scm", USER,
obml_parameters.file_map[obml_parameters.filename]);
}
}
void update_satml_database(SatMLParameters& satml_parameters) {
gatherxml::summarizeMetadata::summarize_frequencies("scm", USER,
satml_parameters.file_map[satml_parameters.filename]);
}
void update_fixml_database(FixMLParameters& fixml_parameters) {
static const string F = this_function_label(__func__);
for (const auto& e : fixml_parameters.class_map) {
vector<string> args;
args.emplace_back(fixml_parameters.markup_path + "." + e.first +
".locations.xml");
args.emplace_back("");
args.emplace_back(fixml_parameters.file_map[fixml_parameters.filename]);
args.emplace_back(fixml_parameters.stg_map[e.first]);
args.emplace_back("");
auto s = e.second.first;
replace_all(s, "-", "");
replace_all(s, ":", "");
replace_all(s, " ", "");
if (s.length() > 12) {
s = s.substr(0, 12);
}
args.emplace_back(s);
s = e.second.second;
replace_all(s, "-", "");
replace_all(s, ":", "");
replace_all(s, " ", "");
if (s.length() > 12) {
s = s.substr(0, 12);
}
args.emplace_back(s);
args.emplace_back(fixml_parameters.database);
thread_summarize_file_ID_locations(reinterpret_cast<void *>(&args));
}
if (fixml_parameters.database == "WFixML") {
gatherxml::summarizeMetadata::summarize_frequencies("scm", USER,
fixml_parameters.file_map[fixml_parameters.filename]);
}
for (const auto& e : fixml_parameters.freq_map) {
auto sp = split(e.first, "<!>");
if (fixml_parameters.server.insert(fixml_parameters.database + ".ds" +
local_args.dsnum2 + "_frequencies", fixml_parameters.file_map[
fixml_parameters.filename] + ", " + sp[1] + ", " + itos(e.second.first)
+ ", " + itos(e.second.second) + ", '" + sp[0] + "'") < 0) {
log_error2("error: '" + fixml_parameters.server.error() + "' while "
"trying to insert into " + fixml_parameters.database + ".ds" +
local_args.dsnum2 + "_frequencies '" + fixml_parameters.file_map[
fixml_parameters.filename] + ", " + sp[1] + ", " + itos(e.second.
first) + ", " + itos(e.second.second) + ", '" + sp[0] + "''", F,
"scm", USER);
}
if (fixml_parameters.database == "WFixML") {
auto s = searchutils::time_resolution_keyword("irregular", e.second.
first, sp[0], "");
if (fixml_parameters.server.insert("search.time_resolutions", "'" + s +
"', 'GCMD', '" + metautils::args.dsnum + "', 'WFixML'") < 0) {
if (!regex_search(fixml_parameters.server.error(), regex("Duplicate "
"entry"))) {
log_error2("error: '" + fixml_parameters.server.error() + "' while "
"trying to insert into search.time_resolutions ''" + s + "', "
"'GCMD', '" + metautils::args.dsnum + "', 'WFixML''", F, "scm",
USER);
}
}
s = searchutils::time_resolution_keyword("irregular", e.second.second, sp[
0], "");
if (fixml_parameters.server.insert("search.time_resolutions", "'" + s +
"', 'GCMD', '" + metautils::args.dsnum + "', 'WFixML'") < 0) {
if (!regex_search(fixml_parameters.server.error(), regex("Duplicate "
"entry")))
log_error2("error: '" + fixml_parameters.server.error() + "' while "
"trying to insert into search.time_resolutions ''" + s + "', "
"'GCMD', '" + metautils::args.dsnum + "', 'WFixML''", F, "scm",
USER);
}
}
}
}
void update_database(MarkupParameters *markup_parameters) {
if (markup_parameters->markup_type == "GrML") {
update_grml_database(*reinterpret_cast<GrMLParameters *>(
markup_parameters));
} else if (markup_parameters->markup_type == "ObML") {
update_obml_database(*reinterpret_cast<ObMLParameters *>(
markup_parameters));
} else if (markup_parameters->markup_type == "SatML") {
update_satml_database(*reinterpret_cast<SatMLParameters *>(
markup_parameters));
} else if (markup_parameters->markup_type == "FixML") {
update_fixml_database(*reinterpret_cast<FixMLParameters *>(
markup_parameters));
}
}
void summarize_markup(string markup_type, unordered_map<string, vector<
string>>& file_list) {
static const string F = this_function_label(__func__);
vector<string> mtypv;
if (!markup_type.empty()) {
mtypv.emplace_back(markup_type);
} else {
for (const auto& e : file_list) {
mtypv.emplace_back(e.first);
}
}
for (const auto& t : mtypv) {
MarkupParameters *mp = nullptr;
if (t == "GrML") {
mp = new GrMLParameters;
} else if (t == "ObML") {
mp = new ObMLParameters;
} else if (t == "FixML") {
mp = new FixMLParameters;
} else {
log_error2("invalid markup type '" + t + "'", F, "scm", USER);
}
mp->server.connect(metautils::directives.database_server, metautils::
directives.metadb_username, metautils::directives.metadb_password, "");
if (!mp->server) {
log_error2("could not connect to metadata database - error: '" + mp->
server.error() + "'", F, "scm", USER);
}
Timer tm;
for (auto& f : file_list[t]) {
if (local_args.verbose) {
tm.start();
}
open_markup_file(mp->xdoc, f);
initialize_file(mp);
process_data_format(mp);
insert_filename(mp);
clear_tables(mp);
if (t == "ObML") {
reinterpret_cast<ObMLParameters *>(mp)->metadata_path = f.substr(0, f.
rfind("/") + 1);
}
process_markup(mp);
mp->xdoc.close();
if (t == "FixML") {
reinterpret_cast<FixMLParameters *>(mp)->markup_path = f;
}
update_database(mp);
if (local_args.verbose) {
tm.stop();
cout << mp->filename << " summarized in " << tm.elapsed_time() <<
" seconds" << endl;
}
}
mp->server._delete("search.data_types", "dsid = '" + metautils::args.dsnum +
"' and vocabulary = 'dssmm'");
string err;
auto r = regex("Duplicate entry");
if (t == "GrML") {
auto gp = reinterpret_cast<GrMLParameters *>(mp);
for (const auto& p : gp->prod_set) {
if (gp->server.insert("search.data_types", "'grid', '" + p + "', '" +
gp->database + "', '" + metautils::args.dsnum + "'") < 0) {
if (!regex_search(gp->server.error(), r)) {
err = gp->server.error();
break;
}
}
}
} else if (t == "ObML") {
if (mp->server.insert("search.data_types", "'platform_observation', '', '"
+ mp->database + "', '" + metautils::args.dsnum + "'") < 0) {
err = mp->server.error();
}
} else if (t == "SatML") {
if (mp->server.insert("search.data_types", "'satellite', '', '" +
mp->database + "', '" + metautils::args.dsnum + "'") < 0) {
err = mp->server.error();
}
} else if (t == "FixML") {
if (mp->server.insert("search.data_types", "'cyclone_fix', '', '" + mp->
database + "', '" + metautils::args.dsnum + "'") < 0) {
err = mp->server.error();
}
}
if (!err.empty() && !regex_search(err, r)) {
log_error2("'" + err + "' while inserting into search.data_types", F,
"scm", USER);
}
mp->server.disconnect();
}
}
void *thread_generate_detailed_metadata_view(void *args) {
auto &a = *(reinterpret_cast<vector<string> *>(args));
//PROBLEM!!
for (const auto& g : local_args.gindex_list) {
if (g != "0") {
gatherxml::detailedMetadata::generate_group_detailed_metadata_view(g, a[
0], "scm", USER);
}
}
if (local_args.summarized_web_file || local_args.refresh_web) {
gatherxml::detailedMetadata::generate_detailed_metadata_view("scm", USER);
}
return nullptr;
}
void *thread_create_file_list_cache(void *args) {
auto &a = *(reinterpret_cast<vector<string> *>(args));
gatherxml::summarizeMetadata::create_file_list_cache(a[0], "scm", USER, a[1]);
return nullptr;
}
void *thread_summarize_obs_data(void *) {
auto b = gatherxml::summarizeMetadata::summarize_obs_data("scm", USER);
if (b && local_args.update_graphics) {
stringstream oss, ess;
mysystem2(metautils::directives.local_root + "/bin/gsi " + metautils::args.
dsnum, oss, ess);
}
return nullptr;
}
void *thread_summarize_fix_data(void *) {
gatherxml::summarizeMetadata::summarize_fix_data("scm", USER);
if (local_args.update_graphics) {
stringstream oss, ess;
mysystem2(metautils::directives.local_root + "/bin/gsi " + metautils::args.
dsnum, oss, ess);
}
return nullptr;
}
void *thread_index_variables(void *) {
MySQL::Server srv(metautils::directives.database_server, metautils::
directives.metadb_username, metautils::directives.metadb_password, "");
auto e = searchutils::index_variables(srv, metautils::args.dsnum);
if (!e.empty()) {
log_error2(e, "thread_index_variables()", "scm", USER);
}
srv.disconnect();
return nullptr;
}
void *thread_index_locations(void *) {
MySQL::Server srv(metautils::directives.database_server, metautils::
directives.metadb_username, metautils::directives.metadb_password, "");
auto e = searchutils::index_locations(srv, metautils::args.dsnum);
if (!e.empty()) {
log_error2(e, "thread_index_locations()", "scm", USER);
}
srv.disconnect();
return nullptr;
}
void *thread_summarize_dates(void *) {
gatherxml::summarizeMetadata::summarize_dates("scm", USER);
return nullptr;
}
void *thread_summarize_frequencies(void *) {
gatherxml::summarizeMetadata::summarize_frequencies("scm", USER);
return nullptr;
}
void *thread_summarize_grid_resolutions(void *) {
gatherxml::summarizeMetadata::summarize_grid_resolutions("scm", USER);
return nullptr;
}
void *thread_summarize_data_formats(void *) {
gatherxml::summarizeMetadata::summarize_data_formats("scm", USER);
return nullptr;
}
void *thread_aggregate_grids(void *args) {
auto &a = *(reinterpret_cast<vector<string> *>(args));
gatherxml::summarizeMetadata::aggregate_grids(a[0], "scm", USER);
return nullptr;
}
extern "C" void clean_up() {
if (!myerror.empty()) {
delete_temporary_directory();
cerr << myerror << endl;
}
if (!local_args.temp_directory.empty()) {
log_warning("clean_up(): non-empty temporary directory: " + local_args.
temp_directory, "scm", USER);
}
}
extern "C" void segv_handler(int) {
log_error2("segmentation fault", "segv_handler()", "scm", USER);
}
void show_usage() {
cout << "usage: (1) scm -d [ds]<nnn.n> { -rw | -ri } [ <tindex> | all ]" <<
endl;
cout << " or: (2) scm -d [ds]<nnn.n> -wa [ <type> ]" << endl;
cout << " or: (3) scm -d [ds]<nnn.n> [-t <tdir> ] -wf FILE" << endl;
cout << "summarize content metadata - generally, specialists will use (1) or "
"(2) and" << endl;
cout << " other gatherxml utilities will use (3)." << endl;
cout << "\nrequired:" << endl;
cout << " -d <nnn.n> (1), (2), (3): the dataset number, optionally "
"prepended with \"ds\"" << endl;
cout << " -rw | -ri (1): refresh the web or detailed inventory database. "
"If a dataset" << endl;
cout << " has groups, optionally include the top-level index "
"to summarize" << endl;
cout << " that specific group, or optionally include the "
"keyword \"all\" to" << endl;
cout << " summarize all groups." << endl;
cout << " -wa (2): summarize every Web metadata file for the "
"dataset. This can" << endl;
cout << " be restricted to an optional markup type (e.g. "
"\"GrML\", \"ObML\"," << endl;
cout << " etc.)." << endl;
cout << " -wf (3): summarize the markup for a Web file" << endl;
cout << " FILE (3): the relative path for the markup file being "
"summarized" << endl;
cout << "\noptions:" << endl;
cout << " -g/-G generate (default)/don't generate graphics" << endl;
cout << " -k/-K generate (default)/don't generate KML for observations"
<< endl;
cout << " -N notify with a message when scm completes" << endl;
if (USER == "dattore") {
cout << " -F refresh only - use this flag only when the data file " "is unchanged" << endl;
cout << " but additional fields/tables have been added to "
"the database that" << endl;
cout << " need to be populated" << endl;
cout << " -r/-R regenerate (default)/don't regenerate dataset web "
"page" << endl;
cout << " -s/-S summarize (default)/don't summarize date and time "
"resolutions" << endl;
}
cout << " -t <tdir> (3): the name of the temporary directory where FILE is "
"located." << endl;
cout << " Otherwise, the default location is" << endl;
cout << " /data/web/datasets/dsnnn.n/metadata/wfmd on the "
"production web" << endl;
cout << " server." << endl;
cout << " -V verbose mode" << endl;
}
int main(int argc, char **argv) {
static const string F = this_function_label(__func__);
if (argc < 3) {
show_usage();
exit(0);
}
// set exit handlers
signal(SIGSEGV, segv_handler);
atexit(clean_up);
auto ex_stat = 0;
// read the metadata configuration
metautils::read_config("scm", USER);
// parse the arguments to scm
const char ARG_DELIMITER = '`';
metautils::args.args_string = unixutils::unix_args_string(argc, argv,
ARG_DELIMITER);
parse_args(ARG_DELIMITER);
// create the global temporary working directory
if (!g_temp_dir.create(metautils::directives.temp_path)) {
log_error2("unable to create temporary directory", F, "scm", USER);
}
// container to hold thread IDs
vector<pthread_t> tv;
// container to hold thread arguments, since these arguments need to stay in
// scope until the thread is joined - use a list because reallocation doesn't // happen (and addresses don't change) when new elements are emplaced
list<vector<string>> targs;
// start the execution timer
Timer tm;
tm.start();
MySQL::Server mysrv(metautils::directives.database_server, metautils::
directives.metadb_username, metautils::directives.metadb_password, "");
if (!mysrv) {
log_error2("unable to connect to MySQL server at startup", F, "scm", USER);
}
unordered_map<string, vector<string>> mmap{
{ "GrML", vector<string>() },
{ "ObML", vector<string>() },
{ "SatML", vector<string>() },
{ "FixML", vector<string>() },
};
if (local_args.summarize_all) {
stringstream oss, ess;
if (mysystem2("/bin/tcsh -c \"wget -q -O - --post-data='authKey="
"qGNlKijgo9DJ7MN&cmd=listfiles&value=/SERVER_ROOT/web/datasets/ds" +
metautils::args.dsnum + "/metadata/" + local_args.cmd_directory +
"' https://rda.ucar.edu/cgi-bin/dss/remoteRDAServerUtils\"", oss, ess)
!= 0) {
log_error2("unable to get metadata file listing", F, "scm", USER);
}
auto sp = split(oss.str(), "\n");
for (const auto& e : sp) {
auto s = e.substr(e.find("/datasets"));
if (regex_search(s, regex("\\.gz$"))) {
chop(s, 3);
}
auto idx = s.rfind(".");
if (idx != string::npos) {
auto k = s.substr(idx + 1);
if (mmap.find(k) != mmap.end()) {
mmap[k].emplace_back(s);
}
}
}
if ((local_args.summ_type.empty() || local_args.summ_type == "GrML") &&
mmap["GrML"].size() > 0) {
if (local_args.cmd_directory == "wfmd") {
mysrv._delete("WGrML.summary", "dsid = '" + metautils::args.dsnum + "'");
}
}
summarize_markup(local_args.summ_type, mmap);
if ((local_args.summ_type.empty() || local_args.summ_type == "ObML") &&
mmap["ObML"].size() > 0) {
if (local_args.summarized_web_file && local_args.update_db) {
pthread_t t;
pthread_create(&t, nullptr, thread_summarize_obs_data, nullptr);
tv.emplace_back(t);
pthread_create(&t, nullptr, thread_index_locations, nullptr);
tv.emplace_back(t);
}
}
if ((local_args.summ_type.empty() || local_args.summ_type == "FixML") &&
mmap["FixML"].size() > 0) {
if (local_args.update_db) {
pthread_t t;
pthread_create(&t, nullptr, thread_summarize_fix_data, nullptr);
tv.emplace_back(t);
pthread_create(&t, nullptr, thread_index_locations, nullptr);
tv.emplace_back(t);
}
}
} else if (!local_args.file.empty()) {
string s;
if (!local_args.temp_directory.empty()) {
s = local_args.temp_directory + "/" + local_args.file;
} else {
s = "/datasets/ds" + metautils::args.dsnum + "/metadata/wfmd/" +
local_args.file;
}
auto idx = local_args.file.rfind(".");
if (idx != string::npos) {
auto k = local_args.file.substr(idx + 1);
if (mmap.find(k) != mmap.end()) {
mmap[k].emplace_back(s);
}
}
if (mmap["GrML"].size() > 0) {
summarize_markup("GrML", mmap);
} else if (mmap["ObML"].size() > 0) {
summarize_markup("ObML", mmap);
if (local_args.summarized_web_file && local_args.update_db) {
pthread_t t;
pthread_create(&t, nullptr, thread_summarize_obs_data, nullptr);
tv.emplace_back(t);
pthread_create(&t, nullptr, thread_index_locations, nullptr);
tv.emplace_back(t);
}
} else if (mmap["SatML"].size() > 0) {
summarize_markup("SatML", mmap);
} else if (mmap["FixML"].size() > 0) {
summarize_markup("FixML", mmap);
if (local_args.summarized_hpss_file && local_args.update_db) {
pthread_t t;
pthread_create(&t, nullptr, thread_summarize_fix_data, nullptr);
tv.emplace_back(t);
pthread_create(&t, nullptr, thread_index_locations, nullptr);
tv.emplace_back(t);
}
} else {
log_error2("file extension of '" + local_args.file + "' not recognized",
F, "scm", USER);
}
} else if (local_args.refresh_web) {
if (local_args.gindex_list.size() > 0 && local_args.gindex_list.front() !=
"all") {
MySQL::LocalQuery q("gidx", "dssdb.dsgroup", "dsid = 'ds" + metautils::
args.dsnum + "' and gindex = " + local_args.gindex_list.front() +
" and pindex = 0");
if (q.submit(mysrv) < 0) {
log_error2("group check failed", F, "scm", USER);
}
if (q.num_rows() == 0) {
log_error2(local_args.gindex_list.front() + " is not a top-level index "
"for this dataset", F, "scm", USER);
}
}
if (table_exists(mysrv, "WGrML.ds" + local_args.dsnum2 + "_agrids_cache")) {
gatherxml::summarizeMetadata::summarize_grids("WGrML", "scm", USER);
targs.emplace_back(vector<string>());
targs.back().emplace_back("WGrML");
pthread_t t;
pthread_create(&t, nullptr, thread_aggregate_grids, &targs.back());
tv.emplace_back(t);
pthread_create(&t, nullptr, thread_summarize_grid_resolutions, nullptr);
tv.emplace_back(t);
}
pthread_t t;
pthread_create(&t, nullptr, thread_summarize_frequencies, nullptr);
tv.emplace_back(t);
}
if (local_args.summarized_web_file && local_args.added_variable) {
pthread_t t;
pthread_create(&t, nullptr, thread_index_variables, nullptr);
tv.emplace_back(t);
}
// make necessary updates to the metadata databases
if (local_args.update_db) {
if (local_args.summarized_web_file || local_args.refresh_web) {
if (local_args.refresh_web) {
if (table_exists(mysrv, "WGrML.ds" + local_args.dsnum2 +
"_agrids_cache")) {
gatherxml::summarizeMetadata::summarize_grids("WGrML", "scm", USER);
targs.emplace_back(vector<string>());
targs.back().emplace_back("WGrML");
pthread_t t;
pthread_create(&t, nullptr, thread_aggregate_grids, &targs.back());
tv.emplace_back(t);
}
if (table_exists(mysrv, "WObML.ds" + local_args.dsnum2 +
"_locations")) {
gatherxml::summarizeMetadata::summarize_obs_data("scm", USER);
}
if (local_args.gindex_list.size() == 1) {
if (local_args.gindex_list.front() == "all") {
local_args.gindex_list.clear();
MySQL::LocalQuery q("select distinct tindex from dssdb.wfile where "
"dsid = 'ds" + metautils::args.dsnum + "' and type = 'D' and "
"status = 'P'");
if (q.submit(mysrv) < 0) {
log_error2("error getting group indexes: '" + q.error() + "'", F,
"scm", USER);
}
for (const auto& r : q) {
local_args.gindex_list.emplace_back(r[0]);
}
}
}
}
if (local_args.update_graphics) {
stringstream oss, ess;
for (const auto& g : local_args.gindex_list) {
if (mysystem2(metautils::directives.local_root + "/bin/gsi -g " + g +
" " + metautils::args.dsnum, oss, ess) != 0) {
log_warning("scm: main(): gsi -g failed with error '" + trimmed(ess.
str()) + "'", "scm", USER);
}
}
if (mysystem2(metautils::directives.local_root + "/bin/gsi " +
metautils::args.dsnum, oss, ess) != 0) {
log_warning("scm: main(): gsi failed with error '" + trimmed(ess.
str()) + "'", "scm", USER);
}
}
for (const auto& g : local_args.gindex_list) {
gatherxml::summarizeMetadata::create_file_list_cache("Web", "scm", USER,
g);
if (!local_args.summarized_web_file) {
gatherxml::summarizeMetadata::create_file_list_cache("inv", "scm",
USER, g);
}
}
targs.emplace_back(vector<string>());
targs.back().emplace_back("Web");
pthread_t t;
pthread_create(&t, nullptr, thread_generate_detailed_metadata_view,
&targs.back());
tv.emplace_back(t);
pthread_create(&t, nullptr, thread_summarize_dates, nullptr);
tv.emplace_back(t);
pthread_create(&t, nullptr, thread_summarize_data_formats, nullptr);
tv.emplace_back(t);
targs.emplace_back(vector<string>());
targs.back().emplace_back("Web");
targs.back().emplace_back("");
pthread_create(&t, nullptr, thread_create_file_list_cache, &targs.back());
tv.emplace_back(t);
if (!local_args.summarized_web_file) {
targs.emplace_back(vector<string>());
targs.back().emplace_back("inv");
targs.back().emplace_back("");
pthread_create(&t, nullptr, thread_create_file_list_cache, &targs.
back());
tv.emplace_back(t);
}
} else if (local_args.refresh_inv) {
if (local_args.refresh_inv && local_args.gindex_list.size() == 1) {
if (local_args.gindex_list.front() == "all") {
local_args.gindex_list.clear();
MySQL::LocalQuery q("select distinct tindex from dssdb.wfile where "
"dsid = 'ds" + metautils::args.dsnum + "' and type = 'D' and "
"status = 'P'");
if (q.submit(mysrv) < 0) {
log_error2("error getting group indexes: '" + q.error() + "'", F,
"scm", USER);
}
for (const auto& r : q) {
local_args.gindex_list.emplace_back(r[0]);
}
}
}
for (const auto& g : local_args.gindex_list) {
gatherxml::summarizeMetadata::create_file_list_cache("inv", "scm", USER,
g);
}
gatherxml::summarizeMetadata::create_file_list_cache("inv", "scm", USER);
}
}
mysrv.disconnect();
// wait for any still-running threads to complete
for (const auto& t : tv) {
pthread_join(t, nullptr);
}
// if this is not a test run, then clean up the temporary directory
if (metautils::args.dsnum != "test" && !local_args.temp_directory.empty()) {
delete_temporary_directory();
}
// update the dataset description, if necessary
if (metautils::args.regenerate) {
stringstream oss, ess;
if (unixutils::mysystem2(metautils::directives.local_root + "/bin/dsgen " +
metautils::args.dsnum, oss, ess) != 0) {
auto e = "error regenerating the dataset description: '" + trimmed(ess.
str()) + "'";
cerr << e << endl;
metautils::log_info(e, "scm", USER);
ex_stat = 1;
}
}
if (local_args.notify) {
cout << "scm has completed successfully" << endl;
}
// record the execution time
tm.stop();
log_warning("execution time: " + ftos(tm.elapsed_time()) + " seconds",
"scm.time", USER);
return ex_stat;
}
| 39.246743 | 251 | 0.564571 | [
"vector"
] |
51c195d32537cdb1607ba570bd1e6edae4dd8f60 | 10,138 | cpp | C++ | gtsam/geometry/tests/testTriangulation.cpp | ashariati/gtsam-3.2.1 | f880365c259eb7532b9c1d20979ecad2eb04779c | [
"BSD-3-Clause"
] | 75 | 2015-04-02T08:58:57.000Z | 2022-03-18T08:01:42.000Z | gtsam/geometry/tests/testTriangulation.cpp | ashariati/gtsam-3.2.1 | f880365c259eb7532b9c1d20979ecad2eb04779c | [
"BSD-3-Clause"
] | 5 | 2016-07-05T16:21:08.000Z | 2020-05-13T16:50:42.000Z | gtsam/geometry/tests/testTriangulation.cpp | ashariati/gtsam-3.2.1 | f880365c259eb7532b9c1d20979ecad2eb04779c | [
"BSD-3-Clause"
] | 66 | 2015-06-01T11:22:38.000Z | 2022-02-18T11:03:57.000Z | /* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* testTriangulation.cpp
*
* Created on: July 30th, 2013
* Author: cbeall3
*/
#include <gtsam/geometry/triangulation.h>
#include <gtsam/geometry/Cal3Bundler.h>
#include <CppUnitLite/TestHarness.h>
#include <boost/assign.hpp>
#include <boost/assign/std/vector.hpp>
using namespace std;
using namespace gtsam;
using namespace boost::assign;
// Some common constants
static const boost::shared_ptr<Cal3_S2> sharedCal = //
boost::make_shared<Cal3_S2>(1500, 1200, 0, 640, 480);
// Looking along X-axis, 1 meter above ground plane (x-y)
static const Rot3 upright = Rot3::ypr(-M_PI / 2, 0., -M_PI / 2);
static const Pose3 pose1 = Pose3(upright, gtsam::Point3(0, 0, 1));
PinholeCamera<Cal3_S2> camera1(pose1, *sharedCal);
// create second camera 1 meter to the right of first camera
static const Pose3 pose2 = pose1 * Pose3(Rot3(), Point3(1, 0, 0));
PinholeCamera<Cal3_S2> camera2(pose2, *sharedCal);
// landmark ~5 meters infront of camera
static const Point3 landmark(5, 0.5, 1.2);
// 1. Project two landmarks into two cameras and triangulate
Point2 z1 = camera1.project(landmark);
Point2 z2 = camera2.project(landmark);
//******************************************************************************
TEST( triangulation, twoPoses) {
vector<Pose3> poses;
vector<Point2> measurements;
poses += pose1, pose2;
measurements += z1, z2;
bool optimize = true;
double rank_tol = 1e-9;
boost::optional<Point3> triangulated_landmark = triangulatePoint3(poses,
sharedCal, measurements, rank_tol, optimize);
EXPECT(assert_equal(landmark, *triangulated_landmark, 1e-2));
// 2. Add some noise and try again: result should be ~ (4.995, 0.499167, 1.19814)
measurements.at(0) += Point2(0.1, 0.5);
measurements.at(1) += Point2(-0.2, 0.3);
boost::optional<Point3> triangulated_landmark_noise = triangulatePoint3(poses,
sharedCal, measurements, rank_tol, optimize);
EXPECT(assert_equal(landmark, *triangulated_landmark_noise, 1e-2));
}
//******************************************************************************
TEST( triangulation, twoPosesBundler) {
boost::shared_ptr<Cal3Bundler> bundlerCal = //
boost::make_shared<Cal3Bundler>(1500, 0, 0, 640, 480);
PinholeCamera<Cal3Bundler> camera1(pose1, *bundlerCal);
PinholeCamera<Cal3Bundler> camera2(pose2, *bundlerCal);
// 1. Project two landmarks into two cameras and triangulate
Point2 z1 = camera1.project(landmark);
Point2 z2 = camera2.project(landmark);
vector<Pose3> poses;
vector<Point2> measurements;
poses += pose1, pose2;
measurements += z1, z2;
bool optimize = true;
double rank_tol = 1e-9;
boost::optional<Point3> triangulated_landmark = triangulatePoint3(poses,
bundlerCal, measurements, rank_tol, optimize);
EXPECT(assert_equal(landmark, *triangulated_landmark, 1e-2));
// 2. Add some noise and try again: result should be ~ (4.995, 0.499167, 1.19814)
measurements.at(0) += Point2(0.1, 0.5);
measurements.at(1) += Point2(-0.2, 0.3);
boost::optional<Point3> triangulated_landmark_noise = triangulatePoint3(poses,
bundlerCal, measurements, rank_tol, optimize);
EXPECT(assert_equal(landmark, *triangulated_landmark_noise, 1e-2));
}
//******************************************************************************
TEST( triangulation, fourPoses) {
vector<Pose3> poses;
vector<Point2> measurements;
poses += pose1, pose2;
measurements += z1, z2;
boost::optional<Point3> triangulated_landmark = triangulatePoint3(poses,
sharedCal, measurements);
EXPECT(assert_equal(landmark, *triangulated_landmark, 1e-2));
// 2. Add some noise and try again: result should be ~ (4.995, 0.499167, 1.19814)
measurements.at(0) += Point2(0.1, 0.5);
measurements.at(1) += Point2(-0.2, 0.3);
boost::optional<Point3> triangulated_landmark_noise = //
triangulatePoint3(poses, sharedCal, measurements);
EXPECT(assert_equal(landmark, *triangulated_landmark_noise, 1e-2));
// 3. Add a slightly rotated third camera above, again with measurement noise
Pose3 pose3 = pose1 * Pose3(Rot3::ypr(0.1, 0.2, 0.1), Point3(0.1, -2, -.1));
SimpleCamera camera3(pose3, *sharedCal);
Point2 z3 = camera3.project(landmark);
poses += pose3;
measurements += z3 + Point2(0.1, -0.1);
boost::optional<Point3> triangulated_3cameras = //
triangulatePoint3(poses, sharedCal, measurements);
EXPECT(assert_equal(landmark, *triangulated_3cameras, 1e-2));
// Again with nonlinear optimization
boost::optional<Point3> triangulated_3cameras_opt = triangulatePoint3(poses,
sharedCal, measurements, 1e-9, true);
EXPECT(assert_equal(landmark, *triangulated_3cameras_opt, 1e-2));
// 4. Test failure: Add a 4th camera facing the wrong way
Pose3 pose4 = Pose3(Rot3::ypr(M_PI / 2, 0., -M_PI / 2), Point3(0, 0, 1));
SimpleCamera camera4(pose4, *sharedCal);
#ifdef GTSAM_THROW_CHEIRALITY_EXCEPTION
CHECK_EXCEPTION(camera4.project(landmark);, CheiralityException);
poses += pose4;
measurements += Point2(400, 400);
CHECK_EXCEPTION(triangulatePoint3(poses, sharedCal, measurements),
TriangulationCheiralityException);
#endif
}
//******************************************************************************
TEST( triangulation, fourPoses_distinct_Ks) {
Cal3_S2 K1(1500, 1200, 0, 640, 480);
// create first camera. Looking along X-axis, 1 meter above ground plane (x-y)
SimpleCamera camera1(pose1, K1);
// create second camera 1 meter to the right of first camera
Cal3_S2 K2(1600, 1300, 0, 650, 440);
SimpleCamera camera2(pose2, K2);
// 1. Project two landmarks into two cameras and triangulate
Point2 z1 = camera1.project(landmark);
Point2 z2 = camera2.project(landmark);
vector<SimpleCamera> cameras;
vector<Point2> measurements;
cameras += camera1, camera2;
measurements += z1, z2;
boost::optional<Point3> triangulated_landmark = //
triangulatePoint3(cameras, measurements);
EXPECT(assert_equal(landmark, *triangulated_landmark, 1e-2));
// 2. Add some noise and try again: result should be ~ (4.995, 0.499167, 1.19814)
measurements.at(0) += Point2(0.1, 0.5);
measurements.at(1) += Point2(-0.2, 0.3);
boost::optional<Point3> triangulated_landmark_noise = //
triangulatePoint3(cameras, measurements);
EXPECT(assert_equal(landmark, *triangulated_landmark_noise, 1e-2));
// 3. Add a slightly rotated third camera above, again with measurement noise
Pose3 pose3 = pose1 * Pose3(Rot3::ypr(0.1, 0.2, 0.1), Point3(0.1, -2, -.1));
Cal3_S2 K3(700, 500, 0, 640, 480);
SimpleCamera camera3(pose3, K3);
Point2 z3 = camera3.project(landmark);
cameras += camera3;
measurements += z3 + Point2(0.1, -0.1);
boost::optional<Point3> triangulated_3cameras = //
triangulatePoint3(cameras, measurements);
EXPECT(assert_equal(landmark, *triangulated_3cameras, 1e-2));
// Again with nonlinear optimization
boost::optional<Point3> triangulated_3cameras_opt = triangulatePoint3(cameras,
measurements, 1e-9, true);
EXPECT(assert_equal(landmark, *triangulated_3cameras_opt, 1e-2));
// 4. Test failure: Add a 4th camera facing the wrong way
Pose3 pose4 = Pose3(Rot3::ypr(M_PI / 2, 0., -M_PI / 2), Point3(0, 0, 1));
Cal3_S2 K4(700, 500, 0, 640, 480);
SimpleCamera camera4(pose4, K4);
#ifdef GTSAM_THROW_CHEIRALITY_EXCEPTION
CHECK_EXCEPTION(camera4.project(landmark);, CheiralityException);
cameras += camera4;
measurements += Point2(400, 400);
CHECK_EXCEPTION(triangulatePoint3(cameras, measurements),
TriangulationCheiralityException);
#endif
}
//******************************************************************************
TEST( triangulation, twoIdenticalPoses) {
// create first camera. Looking along X-axis, 1 meter above ground plane (x-y)
SimpleCamera camera1(pose1, *sharedCal);
// 1. Project two landmarks into two cameras and triangulate
Point2 z1 = camera1.project(landmark);
vector<Pose3> poses;
vector<Point2> measurements;
poses += pose1, pose1;
measurements += z1, z1;
CHECK_EXCEPTION(triangulatePoint3(poses, sharedCal, measurements),
TriangulationUnderconstrainedException);
}
//******************************************************************************
/*
TEST( triangulation, onePose) {
// we expect this test to fail with a TriangulationUnderconstrainedException
// because there's only one camera observation
Cal3_S2 *sharedCal(1500, 1200, 0, 640, 480);
vector<Pose3> poses;
vector<Point2> measurements;
poses += Pose3();
measurements += Point2();
CHECK_EXCEPTION(triangulatePoint3(poses, measurements, *sharedCal),
TriangulationUnderconstrainedException);
}
*/
//******************************************************************************
TEST( triangulation, TriangulationFactor ) {
// Create the factor with a measurement that is 3 pixels off in x
Key pointKey(1);
SharedNoiseModel model;
typedef TriangulationFactor<> Factor;
Factor factor(camera1, z1, model, pointKey);
// Use the factor to calculate the Jacobians
Matrix HActual;
factor.evaluateError(landmark, HActual);
// Matrix expectedH1 = numericalDerivative11<Pose3>(
// boost::bind(&EssentialMatrixConstraint::evaluateError, &factor, _1, pose2,
// boost::none, boost::none), pose1);
// The expected Jacobian
Matrix HExpected = numericalDerivative11<Point3>(
boost::bind(&Factor::evaluateError, &factor, _1, boost::none), landmark);
// Verify the Jacobians are correct
CHECK(assert_equal(HExpected, HActual, 1e-3));
}
//******************************************************************************
int main() {
TestResult tr;
return TestRegistry::runAllTests(tr);
}
//******************************************************************************
| 34.482993 | 83 | 0.660189 | [
"geometry",
"vector",
"model"
] |
51c1e6af3271ac4b02a045498fd093c6ad9b200c | 11,756 | cpp | C++ | src/TpMMPD/ExoMM_SimulTieP.cpp | kikislater/micmac | 3009dbdad62b3ad906ec882b74b85a3db86ca755 | [
"CECILL-B"
] | 451 | 2016-11-25T09:40:28.000Z | 2022-03-30T04:20:42.000Z | src/TpMMPD/ExoMM_SimulTieP.cpp | kikislater/micmac | 3009dbdad62b3ad906ec882b74b85a3db86ca755 | [
"CECILL-B"
] | 143 | 2016-11-25T20:35:57.000Z | 2022-03-01T11:58:02.000Z | src/TpMMPD/ExoMM_SimulTieP.cpp | kikislater/micmac | 3009dbdad62b3ad906ec882b74b85a3db86ca755 | [
"CECILL-B"
] | 139 | 2016-12-02T10:26:21.000Z | 2022-03-10T19:40:29.000Z | /*Header-MicMac-eLiSe-25/06/2007
MicMac : Multi Image Correspondances par Methodes Automatiques de Correlation
eLiSe : ELements of an Image Software Environnement
www.micmac.ign.fr
Copyright : Institut Geographique National
Author : Marc Pierrot Deseilligny
Contributors : Gregoire Maillet, Didier Boldo.
[1] M. Pierrot-Deseilligny, N. Paparoditis.
"A multiresolution and optimization-based image matching approach:
An application to surface reconstruction from SPOT5-HRS stereo imagery."
In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space
(With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006.
[2] M. Pierrot-Deseilligny, "MicMac, un lociel de mise en correspondance
d'images, adapte au contexte geograhique" to appears in
Bulletin d'information de l'Institut Geographique National, 2007.
Francais :
MicMac est un logiciel de mise en correspondance d'image adapte
au contexte de recherche en information geographique. Il s'appuie sur
la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la
licences Cecill-B. Voir en bas de fichier et http://www.cecill.info.
English :
MicMac is an open source software specialized in image matching
for research in geographic information. MicMac is built on the
eLiSe image library. MicMac is governed by the "Cecill-B licence".
See below and http://www.cecill.info.
Header-MicMac-eLiSe-25/06/2007*/
#include "StdAfx.h"
/********************************************************************/
/* */
/* cExo_SimulTieP */
/* */
/********************************************************************/
class cAppliSimulTieP;
class cIma_TieP;
class cIma_TieP
{
public:
cIma_TieP(cAppliSimulTieP&,tSomAWSI &);
void ProjP(const Pt3dr & aP);
// private :
Pt2dr mCurP;
bool mOkP;
double mCurRR; //current random rank
cAppliSimulTieP & mAppli;
std::string mNameIm;
CamStenope * mCam;
};
class cCmpPtrI // order images depending on their affected rank
{
public :
bool operator () (cIma_TieP * aI1,cIma_TieP * aI2)
{
return aI1->mCurRR < aI2->mCurRR;
}
};
typedef std::pair<cIma_TieP *,cIma_TieP *> tPairIm;
typedef std::map<tPairIm,ElPackHomologue> tMapH;
class cAppliSimulTieP : public cAppliWithSetImage
{
public :
cAppliSimulTieP(int argc, char** argv);
//private :
double mTiePNoise;
std::string mNameMnt;
cElNuage3DMaille * mMNT;
Pt2di mSzMNT;
std::vector<cIma_TieP *> mVIms;
std::map<std::pair<cIma_TieP *,cIma_TieP *> ,ElPackHomologue> mMapH;
};
/********************************************************************/
/* */
/* cAppliSimulTieP */
/* */
/********************************************************************/
cAppliSimulTieP::cAppliSimulTieP(int argc, char** argv): // cAppliWithSetImage is used to initialize the images
cAppliWithSetImage (argc-1,argv+1,0), // it has to be used without the first argument (name of the command)
mTiePNoise (2.0) // default value for the noise in tie points
{
ElInitArgMain
( // initialisation of the arguments
argc,argv,
LArgMain() << EAMC(mEASF.mFullName,"Full Name (Dir+Pattern)") // EAMC = mandatory arguments
<< EAMC(mOri,"Orientation")
<< EAMC(mNameMnt,"Name of DSM"),
LArgMain() << EAM(mTiePNoise,"TPNoise",true,"Noise on Tie Points") // EAM = optionnal argument
);
std::cout << "Nb Image " << mDicIm.size() << "]\n";
for (int aKIm=0 ;aKIm<int(mVSoms.size()) ; aKIm++) // mVSoms = image list
{
mVIms.push_back(new cIma_TieP(*this,*mVSoms[aKIm])); // images loaded in a vector
}
mMNT = cElNuage3DMaille::FromFileIm(mEASF.mDir+mNameMnt); // loading the DSM
std::cout << "Sz Geom " << mMNT->SzGeom() << "\n"; // DSM size
mSzMNT = mMNT->SzGeom();
int aStep = 3; // we will browse the DSM using a box to pick points. aStep defines the size of the box
int aMultMax = 6; // defines the maximum amount of image in which one tie point can be seen
for (int anX0 = 0 ; anX0 <mSzMNT.x ; anX0+=aStep)
{
int anX1 = ElMin(anX0+aStep,mSzMNT.x); // ElMin(a,b) to pick the lowest -> to avoid to pick point outside of the DSM
for (int anY0 = 0 ; anY0 <mSzMNT.y ; anY0 +=aStep) // [anX0,anY0] = lower left corner of the box
{
int anY1 = ElMin(anY0+aStep,mSzMNT.y); // [anX1,anY1] = upper right corner of the box
Box2di aBox(Pt2di(anX0,anY0),Pt2di(anX1,anY1));
Pt2di aPRan = round_ni(aBox.RandomlyGenereInside()); // randomly pick a point in the box
if (mMNT->IndexHasContenu(aPRan)) // if there is a point in the DSM at that place
{
int aNbOk = 0;
Pt3dr aPTer = mMNT->PtOfIndex(aPRan); // get the 3d coordinate (ground geometry) of that point
std::vector<cIma_TieP *> aVSel;
for (int aKIm=0 ;aKIm<int(mVIms.size()) ; aKIm++) // browse the image list
{
cIma_TieP & anI = *(mVIms[aKIm]); // load image
anI.ProjP(aPTer); // project the point in the current image
if (anI.mOkP) // if the 3d point can be projected
{
aNbOk++;
aVSel.push_back(&anI); // list of images in which the current point can be seen
anI.mCurRR = NRrandom3(); // assign a rank to the image (will be used further to randomly simulate hidden parts/undetections)
}
}
if (int(aVSel.size()) >= 2) // if the point is visible in at least 2 images
{
cCmpPtrI aCmp;
std::sort(aVSel.begin(),aVSel.end(),aCmp); // order the list of images (in which the point is seen) by their rank (random order)
int aNbMul = ElMax(2,round_ni(aMultMax * ElSquare(NRrandom3())));
while (int(aVSel.size()) > aNbMul) aVSel.pop_back(); // if the point is seen in too many images, reduce the list
std::cout << "MULTIPLICITE " << aNbOk << " =>" << aVSel.size()<< "\n";
for (int aK1=0 ; aK1<int(aVSel.size()) ; aK1++)
{ // browse the list (reduced) of images in which the point is seen
for (int aK2=0 ; aK2<int(aVSel.size()) ; aK2++)
{
if ((aK1 != aK2) && (NRrandom3() < 0.75)) // for 2 different images, 3 times on 4, build the dictionnary of image names and point coordinates
{
tPairIm aPair; // image pair
aPair.first = aVSel[aK1]; // img1
aPair.second = aVSel[aK2]; // img2
Pt2dr aP1 = aVSel[aK1]->mCurP; // pt_img1
Pt2dr aP2 = aVSel[aK2]->mCurP; // pt_img2
mMapH[aPair].Cple_Add(ElCplePtsHomologues(aP1,aP2)); // save : im1 im2 pt_im1 pt_im2
}
}
}
}
}
}
}
std::string aKey = "NKS-Assoc-CplIm2Hom@Simul@dat"; // association key, here results will be saved in a folder "HomolSimul", as .dat files
for (tMapH::iterator itM=mMapH.begin(); itM!=mMapH.end() ; itM++) // browse the dictionnary
{
cIma_TieP * aIm1 = itM->first.first; // img1
cIma_TieP * aIm2 = itM->first.second; // img2
std::string aNameH = mEASF.mICNM->Assoc1To2(aKey,aIm1->mNameIm,aIm2->mNameIm,true); // name of the file to save ("HomolSimul/Pastis....dat")
itM->second.StdPutInFile(aNameH); // save pt_im1 & pt_im2 in that file
std::cout << aNameH << "\n";
}
}
/********************************************************************/
/* */
/* cIma_TieP */
/* */
/********************************************************************/
cIma_TieP::cIma_TieP(cAppliSimulTieP& anAppli,tSomAWSI & aSom) :
mAppli (anAppli),
mNameIm (aSom.attr().mIma->mNameIm),
mCam (aSom.attr().mIma->CamSNN())
{
}
void cIma_TieP::ProjP(const Pt3dr & aPTer) // function used to project 3d points in the images, and to add noise in the coordinates
{
Pt2dr aNoise(NRrandC(),NRrandC()); // creation of a white noise (centered on [-1;1])
mCurP = mCam->R3toF2(aPTer) + aNoise * mAppli.mTiePNoise; // projection of the point, noise added
mOkP = mCam->IsInZoneUtile(mCurP); // check if the point is in the image
}
/********************************************************************/
/* */
/* Main */
/* */
/********************************************************************/
int ExoSimulTieP_main(int argc, char** argv)
{
cAppliSimulTieP anAppli(argc,argv);
return EXIT_SUCCESS;
}
/*Footer-MicMac-eLiSe-25/06/2007
Ce logiciel est un programme informatique servant \C3 la mise en
correspondances d'images pour la reconstruction du relief.
Ce logiciel est régi par la licence CeCILL-B soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".
En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme, le
titulaire des droits patrimoniaux et les concédants successifs.
A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, \C3 l'utilisation, \C3 la modification et/ou au
développement et \C3 la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe \C3
manipuler et qui le réserve donc \C3 des développeurs et des professionnels
avertis possédant des connaissances informatiques approfondies. Les
utilisateurs sont donc invités \C3 charger et tester l'adéquation du
logiciel \C3 leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
\C3 l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
Le fait que vous puissiez accéder \C3 cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL-B, et que vous en avez accepté les
termes.
Footer-MicMac-eLiSe-25/06/2007*/
| 43.865672 | 171 | 0.549677 | [
"geometry",
"vector",
"3d"
] |
51c2f5842f96c0309b970cfbf30d16b97fa9b806 | 1,792 | hpp | C++ | include/hitbit-common.hpp | NewYaroslav/hitbit-cpp-api | fc214cb9b71a20e167e35c3234eb2d04e8eeb7cb | [
"MIT"
] | null | null | null | include/hitbit-common.hpp | NewYaroslav/hitbit-cpp-api | fc214cb9b71a20e167e35c3234eb2d04e8eeb7cb | [
"MIT"
] | null | null | null | include/hitbit-common.hpp | NewYaroslav/hitbit-cpp-api | fc214cb9b71a20e167e35c3234eb2d04e8eeb7cb | [
"MIT"
] | null | null | null | /*
* hitbit-cpp-api - C ++ API client for hitbit
*
* Copyright (c) 2021 Elektro Yar. Email: git.electroyar@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#ifndef HITBIT_COMMON_HPP_INCLUDED
#define HITBIT_COMMON_HPP_INCLUDED
#include <string>
#include <algorithm>
#include <locale>
namespace hitbit_cpp_api {
namespace common {
/** \brief Приведение строки к верхнему регистру
*/
std::string to_upper_case(const std::string &s){
std::string temp = s;
std::transform(temp.begin(), temp.end(), temp.begin(), [](char ch) {
return std::use_facet<std::ctype<char>>(std::locale()).toupper(ch);
});
return temp;
}
}
}
#endif // HITBIT_COMMON_HPP_INCLUDED
| 37.333333 | 83 | 0.715402 | [
"transform"
] |
51c37a0581542c6ebf3f08653b41cf9e2fd3c0af | 868 | hpp | C++ | windows/CsForFinancialMarketsPart2/Chapters20+21+22+23/Demos - CLI-CS Interop with Excel/CLI GUI/UtilitiesDJD/Geometry/Mesher.hpp | jdm7dv/financial | 673a552d58751643dbca0ba633aeff119eda107d | [
"MIT"
] | 1 | 2020-06-22T06:54:08.000Z | 2020-06-22T06:54:08.000Z | windows/CsForFinancialMarketsPart2/Chapters20+21+22+23/Demos - CLI-CS Interop with Excel/CLI GUI/UtilitiesDJD/Geometry/Mesher.hpp | jdm7dv/financial | 673a552d58751643dbca0ba633aeff119eda107d | [
"MIT"
] | null | null | null | windows/CsForFinancialMarketsPart2/Chapters20+21+22+23/Demos - CLI-CS Interop with Excel/CLI GUI/UtilitiesDJD/Geometry/Mesher.hpp | jdm7dv/financial | 673a552d58751643dbca0ba633aeff119eda107d | [
"MIT"
] | 2 | 2018-09-19T19:27:18.000Z | 2021-01-05T06:26:06.000Z | // Mesher.hpp
//
// A simple mesher on a 1d domain. We divide
// an interval into J+1 mesh points, J-1 of which
// are internal mesh points.
//
// Future projects:
//
// 1. Separate space and time meshing
// 2. Meshing in hypercubes (modelling geometric aspects)
//
// (C) Datasim Education BV 2006
//
#ifndef Mesher_HPP
#define Mesher_HPP
#include "UtilitiesDJD/VectorsAndMatrices/Vector.cpp"
#include "Range.cpp"
class Mesher
{
private:
double a, b; // In space (left, right)
double LT, HT; // In time (low, high)
public:
Mesher();
Mesher (double A, double B, double t=0.0, double T=0.0);
Mesher (const Range<double>& rX, const Range<double>& rT);
Vector<double, long> xarr(int J); // Mesh in direction 1
Vector<double, long> yarr(int N); // Mesh in direction 2
double timeStep(int N);
};
#endif
| 20.186047 | 61 | 0.645161 | [
"mesh",
"vector"
] |
51cbcce02e7dbf2ca20d5329e154cbde12d9fcdc | 907 | cpp | C++ | bld/insertionsortstrategy.cpp | kstrat2001/fun | 84a1222b69e4747834617a2c5aa1cb347cd27fc6 | [
"MIT"
] | null | null | null | bld/insertionsortstrategy.cpp | kstrat2001/fun | 84a1222b69e4747834617a2c5aa1cb347cd27fc6 | [
"MIT"
] | null | null | null | bld/insertionsortstrategy.cpp | kstrat2001/fun | 84a1222b69e4747834617a2c5aa1cb347cd27fc6 | [
"MIT"
] | null | null | null | #include "insertionsortstrategy.h"
#include "icomparable.h"
#include <vector>
#include <iostream>
namespace gfx
{
void InsertionSortStrategy::Sort(
std::vector<IComparable*>& sortVec ) const
{
for( size_t i = 1; i < sortVec.size(); ++i )
{
size_t numShift = 0;
int j = i - 1;
while( j >= 0 && sortVec[i]->Compare( *sortVec[j] ) < 0 )
{
++numShift;
--j;
}
if( numShift > 0 )
{
IComparable* tmp = sortVec[ i ];
// Shift the values greater than temp
for( size_t k = 0; k < numShift; ++k )
{
sortVec[i - k] = sortVec[ i - k - 1];
}
// Insert the temp value
sortVec[ i - numShift ] = tmp;
}
}
}
}
| 22.675 | 69 | 0.411246 | [
"vector"
] |
51ce3a8e4de9755b80bd2bb77d09077e7386040f | 2,535 | cpp | C++ | Il2Native.Logic/NativeImplementations/System.Private.CoreLib/System/StubHelpers/MngdNativeArrayMarshaler.cpp | Vinay1705/cs2cpp | d07d3206fb57edb959df8536562909a4d516e359 | [
"MIT"
] | 192 | 2016-03-23T04:33:24.000Z | 2022-03-28T14:41:06.000Z | Il2Native.Logic/NativeImplementations/System.Private.CoreLib/System/StubHelpers/MngdNativeArrayMarshaler.cpp | Vinay1705/cs2cpp | d07d3206fb57edb959df8536562909a4d516e359 | [
"MIT"
] | 9 | 2017-03-08T14:45:16.000Z | 2021-09-06T09:28:47.000Z | Il2Native.Logic/NativeImplementations/System.Private.CoreLib/System/StubHelpers/MngdNativeArrayMarshaler.cpp | Vinay1705/cs2cpp | d07d3206fb57edb959df8536562909a4d516e359 | [
"MIT"
] | 56 | 2016-03-22T20:37:08.000Z | 2022-03-28T12:20:47.000Z | #include "System.Private.CoreLib.h"
namespace CoreLib { namespace System { namespace StubHelpers {
namespace _ = ::CoreLib::System::StubHelpers;
// Method : System.StubHelpers.MngdNativeArrayMarshaler.CreateMarshaler(System.IntPtr, System.IntPtr, int)
void MngdNativeArrayMarshaler::CreateMarshaler(::CoreLib::System::IntPtr pMarshalState, ::CoreLib::System::IntPtr pMT, int32_t dwFlags)
{
throw 3221274624U;
}
// Method : System.StubHelpers.MngdNativeArrayMarshaler.ConvertSpaceToNative(System.IntPtr, ref object, System.IntPtr)
void MngdNativeArrayMarshaler::ConvertSpaceToNative_Ref(::CoreLib::System::IntPtr pMarshalState, object*& pManagedHome, ::CoreLib::System::IntPtr pNativeHome)
{
throw 3221274624U;
}
// Method : System.StubHelpers.MngdNativeArrayMarshaler.ConvertContentsToNative(System.IntPtr, ref object, System.IntPtr)
void MngdNativeArrayMarshaler::ConvertContentsToNative_Ref(::CoreLib::System::IntPtr pMarshalState, object*& pManagedHome, ::CoreLib::System::IntPtr pNativeHome)
{
throw 3221274624U;
}
// Method : System.StubHelpers.MngdNativeArrayMarshaler.ConvertSpaceToManaged(System.IntPtr, ref object, System.IntPtr, int)
void MngdNativeArrayMarshaler::ConvertSpaceToManaged_Ref(::CoreLib::System::IntPtr pMarshalState, object*& pManagedHome, ::CoreLib::System::IntPtr pNativeHome, int32_t cElements)
{
throw 3221274624U;
}
// Method : System.StubHelpers.MngdNativeArrayMarshaler.ConvertContentsToManaged(System.IntPtr, ref object, System.IntPtr)
void MngdNativeArrayMarshaler::ConvertContentsToManaged_Ref(::CoreLib::System::IntPtr pMarshalState, object*& pManagedHome, ::CoreLib::System::IntPtr pNativeHome)
{
throw 3221274624U;
}
// Method : System.StubHelpers.MngdNativeArrayMarshaler.ClearNative(System.IntPtr, System.IntPtr, int)
void MngdNativeArrayMarshaler::ClearNative(::CoreLib::System::IntPtr pMarshalState, ::CoreLib::System::IntPtr pNativeHome, int32_t cElements)
{
throw 3221274624U;
}
// Method : System.StubHelpers.MngdNativeArrayMarshaler.ClearNativeContents(System.IntPtr, System.IntPtr, int)
void MngdNativeArrayMarshaler::ClearNativeContents(::CoreLib::System::IntPtr pMarshalState, ::CoreLib::System::IntPtr pNativeHome, int32_t cElements)
{
throw 3221274624U;
}
}}}
namespace CoreLib { namespace System { namespace StubHelpers {
namespace _ = ::CoreLib::System::StubHelpers;
}}}
| 48.75 | 182 | 0.746746 | [
"object"
] |
51d47642820dc1dc2b782b2ae58803262be2565a | 24,359 | cpp | C++ | src/libs/fileext/excel/book.cpp | dmryutov/document2html | 753d37a42a7c9e9daeb33183228ac5bf0df87295 | [
"MIT"
] | 7 | 2018-01-18T05:39:53.000Z | 2020-05-25T10:16:44.000Z | src/libs/fileext/excel/book.cpp | dmryutov/document2html | 753d37a42a7c9e9daeb33183228ac5bf0df87295 | [
"MIT"
] | 1 | 2018-02-07T11:04:23.000Z | 2018-02-10T18:16:02.000Z | src/libs/fileext/excel/book.cpp | dmryutov/document2html | 753d37a42a7c9e9daeb33183228ac5bf0df87295 | [
"MIT"
] | 4 | 2018-06-27T23:53:46.000Z | 2021-09-22T05:38:39.000Z | /**
* @brief Excel files (xls/xlsx) into HTML сonverter
* @package excel
* @file book.cpp
* @author dmryutov (dmryutov@gmail.com)
* @copyright python-excel (https://github.com/python-excel/xlrd)
* @date 02.12.2016 -- 29.01.2018
*/
#include <fstream>
#include "../../encoding/encoding.hpp"
#include "../../tools.hpp"
#include "biffh.hpp"
#include "formula.hpp"
#include "sheet.hpp"
#include "book.hpp"
namespace excel {
/** Supbook types */
enum {
SUPBOOK_UNK, ///< Unknown
SUPBOOK_INTERNAL, ///< Internal
SUPBOOK_EXTERNAL, ///< Extarnal
SUPBOOK_ADDIN, ///< Addin
SUPBOOK_DDEOLE ///< DDE OLE
};
const int XL_WORKBOOK_GLOBALS = 0x5;
const int XL_WORKBOOK_GLOBALS_4W = 0x100;
const int XL_WORKSHEET = 0x10;
const int XL_BOUNDSHEET_WORKSHEET = 0x00;
/** BIFF supported versions */
const std::vector<int> SUPPORTED_VERSIONS {80, 70, 50, 45, 40, 30, 21, 20};
/** BOF length list */
const std::unordered_map<int, int> BOF_LENGTH {
{0x0809, 8},
{0x0409, 6},
{0x0209, 6},
{0x0009, 4}
};
/** Get built-in name from code */
const std::unordered_map<std::string, std::string> BUILTIN_NAME_FROM_CODE {
{"Consolidate_Area", "\x00"},
{"Auto_Open", "\x01"},
{"Auto_Close", "\x02"},
{"Extract", "\x03"},
{"Database", "\x04"},
{"Criteria", "\x05"},
{"Print_Area", "\x06"},
{"Print_Titles", "\x07"},
{"Recorder", "\x08"},
{"Data_Form", "\x09"},
{"Auto_Activate", "\x0A"},
{"Auto_Deactivate", "\x0B"},
{"Sheet_Title", "\x0C"},
{"_FilterDatabase", "\x0D"}
};
/** Get encoding from codepage */
const std::unordered_map<int, std::string> ENCODING_FROM_CODEPAGE {
{1200, "UTF-16LE"},
{10000, "MacRoman"},
{10006, "MacGreek"},
{10007, "MacCyrillic"},
{10029, "MacLatin2"},
{10079, "MacIceland"},
{10081, "MacTurkish"},
{32768, "MacRoman"},
{32769, "CP1252"}
};
/** BIFF text version */
const std::unordered_map<int, std::string> BIFF_TEXT {
{0, "(not BIFF)"},
{20, "2.0"},
{21, "2.1"},
{30, "3"},
{40, "4S"},
{45, "4W"},
{50, "5"},
{70, "7"},
{80, "8"},
{85, "8X"}
};
// Book public:
Book::Book(const std::string& fileName, pugi::xml_node& htmlTree, bool addStyle, bool extractImages,
char mergingMode, std::vector<std::pair<std::string, std::string>>& imageList)
: Cfb(fileName), m_htmlTree(htmlTree), m_addStyle(addStyle), m_extractImages(extractImages),
m_mergingMode(mergingMode), m_imageList(imageList) {}
void Book::openWorkbookXls() {
// Read CFB part
Cfb::parse();
m_workBook = getStream("Workbook");
if (m_workBook.empty())
return;
Cfb::clear();
m_biffVersion = getBiffVersion(XL_WORKBOOK_GLOBALS);
if (!m_biffVersion)
throw std::logic_error("Can't determine file's BIFF version");
if (find(SUPPORTED_VERSIONS.begin(), SUPPORTED_VERSIONS.end(), m_biffVersion) ==
SUPPORTED_VERSIONS.end()
)
throw std::invalid_argument("BIFF version "+ BIFF_TEXT.at(m_biffVersion) +" is not supported");
if (m_biffVersion <= 40) {
// No workbook globals, only 1 worksheet
getFakeGlobalsSheet();
}
else if (m_biffVersion == 45) {
// Worksheet(s) embedded in global stream
parseGlobals();
}
else {
parseGlobals();
m_sheetList.clear();
size_t sheetCount = m_sheetNames.size();
for (size_t i = 0; i < sheetCount; ++i)
getSheet(i);
}
m_sheetCount = m_sheetList.size();
// Release resources
m_workBook.clear();
m_sharedStrings.clear();
m_richtextRunlistMap.clear();
m_workBook.shrink_to_fit();
m_sharedStrings.shrink_to_fit();
}
void Book::handleWriteAccess(const std::string& data) {
std::string str;
if (m_biffVersion < 80) {
if (m_encoding.empty()) {
m_isRawUserName = true;
m_userName = data;
return;
}
str = unpackString(data, 0, 1);
}
else
str = unpackUnicode(data, 0, 2);
m_userName = tools::rtrim(str);
}
void Book::getRecordParts(unsigned short& code, unsigned short& length,
std::string& data, int condition)
{
int pos = m_position;
code = readByte<unsigned short>(m_workBook, pos, 2);
length = readByte<unsigned short>(m_workBook, pos+2, 2);
if (condition != -1 && code != condition) {
data = "";
code = 0;
length = 0;
return;
}
pos += 4;
data = m_workBook.substr(pos, length);
m_position = pos + length;
}
void Book::getEncoding() {
if (!m_codePage) {
if (m_biffVersion < 80)
m_encoding = "ascii";
else
m_codePage = 1200; // utf16le
}
else {
if (ENCODING_FROM_CODEPAGE.find(m_codePage) != ENCODING_FROM_CODEPAGE.end())
m_encoding = ENCODING_FROM_CODEPAGE.at(m_codePage);
else if (300 <= m_codePage && m_codePage <= 1999)
m_encoding = "cp" + std::to_string(m_codePage);
else
m_encoding = "unknown_codepage_" + std::to_string(m_codePage);
}
if (m_isRawUserName) {
m_userName = tools::rtrim(unpackString(m_userName, 0, 1));
m_isRawUserName = false;
}
}
std::string Book::unpackString(const std::string& data, int pos, int length) const {
std::string result = data.substr(pos + length, readByte<int>(data, pos, length));
return encoding::decode(result, m_encoding);
}
std::string Book::unpackStringUpdatePos(const std::string& data, int& pos,
int length, int knownLength) const
{
int charCount;
if (knownLength) {
// On a NAME record, the length byte is detached from the front of the string
charCount = knownLength;
}
else {
charCount = readByte<int>(data, pos, length);
pos += length;
}
pos += charCount;
std::string result = data.substr(pos - charCount, charCount);
return encoding::decode(result, m_encoding);
}
std::string Book::unpackUnicode(const std::string& data, int pos, int length) const {
unsigned short charCount = readByte<int>(data, pos, length);
// Ambiguous whether 0-length string should have an "options" byte. Avoid crash if missing
if (!charCount)
return "";
pos += length;
std::string result;
char options = data[pos];
pos += 1;
if (options & 0x08)
pos += 2;
if (options & 0x04)
pos += 4;
if (options & 0x01) {
// Uncompressed UTF-16-LE
result = data.substr(pos, 2*charCount);
result = encoding::decode(result, "UTF-16LE");
}
else {
// Note: this is COMPRESSED (not ASCII) encoding! Merely returning the raw bytes would
// work OK 99.99% of time if local codepage was cp1252 - however this would rapidly go
// pear-shaped for other codepages so return Unicode
result = data.substr(pos, charCount);
result = encoding::decode(result, "ISO-8859-1");
}
return result;
}
std::string Book::unpackUnicodeUpdatePos(const std::string& data, int& pos,
int length, int knownLength) const
{
int charCount;
if (knownLength)
// On a NAME record, the length byte is detached from the front of the string
charCount = knownLength;
else {
charCount = readByte<int>(data, pos, length);
pos += length;
}
// Zero-length string with no options byte
if (!charCount && data.substr(pos).empty())
return "";
std::string result;
unsigned short rt = 0;
char options = data[pos];
char phonetic = options & 0x04;
char richtext = options & 0x08;
int size = 0;
pos += 1;
if (richtext) {
rt = readByte<unsigned short>(data, pos, 2);
pos += 2;
}
if (phonetic) {
size = readByte<int>(data, pos, 4);
pos += 4;
}
if (options & 0x01) {
// Uncompressed UTF-16-LE
result = data.substr(pos, 2*charCount);
result = encoding::decode(result, "UTF-16LE");
pos += 2 * charCount;
}
else {
// Note: this is COMPRESSED (not ASCII!) encoding!!!
result = data.substr(pos, charCount);
result = encoding::decode(result, "ISO-8859-1");
pos += charCount;
}
if (richtext)
pos += 4 * rt;
if (phonetic)
pos += size;
return result;
}
// Book private:
int Book::getBiffVersion(int streamSign) {
unsigned short signature = readByte<unsigned short>(m_workBook, m_position, 2);
unsigned short length = readByte<unsigned short>(m_workBook, m_position + 2, 2);
//int savpos = m_position;
m_position += 4;
if (find(BOF_CODES.begin(), BOF_CODES.end(), signature) == BOF_CODES.end())
throw std::invalid_argument("Unsupported format, or corrupt file: Expected BOF record");
if (length < 4 || length > 20)
throw std::invalid_argument(
"Unsupported format, or corrupt file: Invalid length (" +
std::to_string(length) +") for BOF record type " + std::to_string(signature)
);
std::string padding(std::max(0, BOF_LENGTH.at(signature) - length), '\0');
std::string data = m_workBook.substr(m_position, length);
if (data.size() < length)
throw std::invalid_argument("Unsupported format, or corrupt file: Incomplete BOF record[2]");
m_position += length;
data += padding;
int version = 0;
int version1 = signature >> 8;
unsigned short version2 = readByte<unsigned short>(data, 0, 2);
unsigned short streamType = readByte<unsigned short>(data, 2, 2);
if (version1 == 0x08) {
unsigned short build = readByte<unsigned short>(data, 4, 2);
unsigned short year = readByte<unsigned short>(data, 6, 2);
if (version2 == 0x0600) {
version = 80;
}
else if (version2 == 0x0500) {
if (year < 1994 || (build == 2412 || build == 3218 || build == 3321))
version = 50;
else
version = 70;
}
else {
// Dodgy one, created by a 3rd-party tool
std::unordered_map<int, int> code {
{0x0000, 21}, {0x0007, 21},
{0x0200, 21}, {0x0300, 30},
{0x0400, 40}
};
version = code[version2];
}
}
else if (version1 == 0x04)
version = 40;
else if (version1 == 0x02)
version = 30;
else if (version1 == 0x00)
version = 21;
if (version == 40 && streamType == XL_WORKBOOK_GLOBALS_4W)
version = 45;
bool gotGlobals = (
streamType == XL_WORKBOOK_GLOBALS ||
(version == 45 && streamType == XL_WORKBOOK_GLOBALS_4W)
);
if ((streamSign == XL_WORKBOOK_GLOBALS && gotGlobals) || streamType == streamSign)
return version;
if (version < 50 && streamType == XL_WORKSHEET)
return version;
if (version >= 50 && streamType == 0x0100)
throw std::logic_error("Workspace file -- no spreadsheet data");
throw std::logic_error("BOF not workbook/worksheet");
}
void Book::getFakeGlobalsSheet() {
Formatting formatting(this);
formatting.initializeBook();
// Add sheet information
auto div = m_htmlTree.append_child("div");
div.append_attribute("id") = "tabC1";
auto table = div.append_child("table");
m_sheetNames = {"Sheet 1"};
m_sheetAbsolutePos = {0};
m_sheetVisibility = {0}; // One sheet, visible
m_sheetList.emplace_back(Sheet(this, m_position, "Sheet 1", 0, table));
size_t sheetCount = m_sheetNames.size();
for (size_t i = 0; i < sheetCount; ++i)
getSheet(i);
}
void Book::parseGlobals() {
// No need to position, just start reading (after the BOF)
Formatting formatting(this);
formatting.initializeBook();
while (true) {
unsigned short code;
unsigned short length;
std::string data;
getRecordParts(code, length, data);
if (code == XL_SST)
handleSst(data);
else if (code == XL_FONT || code == XL_FONT_B3B4)
formatting.handleFont(data);
else if (code == XL_FORMAT) // XL_FORMAT2 is BIFF <= 3.0, can't appear in globals
formatting.handleFormat(data);
else if (code == XL_XF)
formatting.handleXf(data);
else if (code == XL_BOUNDSHEET)
handleBoundsheet(data);
else if (code == XL_DATEMODE)
m_dateMode = readByte<unsigned short>(data, 0, 2);
else if (code == XL_CODEPAGE) {
m_codePage = readByte<unsigned short>(data, 0, 2);
getEncoding();
}
else if (code == XL_COUNTRY) {
m_countries = {
readByte<unsigned short>(data, 0, 2),
readByte<unsigned short>(data, 2, 2)
};
}
else if (code == XL_EXTERNNAME)
handleExternalName(data);
else if (code == XL_EXTERNSHEET)
handleExternalSheet(data);
else if (code == XL_WRITEACCESS)
handleWriteAccess(data);
else if (code == XL_SHEETSOFFSET)
m_sheetOffset = readByte<int>(data, 0, 4);
else if (code == XL_SHEETHDR)
handleSheethdr(data);
else if (code == XL_SUPBOOK)
handleSupbook(data);
else if (code == XL_NAME)
handleName(data);
else if (code == XL_PALETTE)
formatting.handlePalette(data);
else if (code == XL_STYLE)
formatting.handleStyle(data);
else if (code == XL_EOF) {
formatting.xfEpilogue();
namesEpilogue();
formatting.paletteEpilogue();
if (m_encoding.empty())
getEncoding();
return;
}
}
}
void Book::getSheet(size_t sheetId, bool shouldUpdatePos) {
if (shouldUpdatePos)
m_position = m_sheetAbsolutePos[sheetId];
getBiffVersion(XL_WORKSHEET);
// Add sheet information
auto div = m_htmlTree.append_child("div");
div.append_attribute("id") = ("tabC"+ std::to_string(sheetId+1)).c_str();
auto table = div.append_child("table");
m_sheetList.emplace_back(Sheet(this, m_position, m_sheetNames[sheetId], sheetId, table));
m_sheetList.back().read();
}
void Book::handleSst(const std::string& data) {
std::vector<std::string> stringList = {data};
while (true) {
unsigned short code;
unsigned short length;
std::string data;
getRecordParts(code, length, data, XL_CONTINUE);
if (!code)
break;
stringList.emplace_back(data);
}
unpackSst(stringList, readByte<int>(data, 4, 4));
}
void Book::handleBoundsheet(const std::string& data) {
getEncoding();
std::string sheetName;
unsigned char visibility;
unsigned char sheetType;
int absolutePos;
if (m_biffVersion == 45) { // BIFF4W
// Not documented in OOo docs. In fact, the only data is the name of the sheet
sheetName = unpackString(data, 0, 1);
visibility = 0;
sheetType = XL_BOUNDSHEET_WORKSHEET;
// Note:
// (a) This won't be used
// (b) It's the position of the SHEETHDR record
// (c) Add 11 to get to the worksheet BOF record
if (m_sheetAbsolutePos.size() == 0)
absolutePos = m_sheetOffset + m_base;
else
absolutePos = -1; // Unknown
}
else {
int offset = readByte<int>(data, 0, 4);
visibility = readByte<unsigned char>(data, 4, 1);
sheetType = readByte<unsigned char>(data, 5, 1);
absolutePos = offset + m_base; // Because global BOF is always at position 0 in the stream
if (m_biffVersion < 80)
sheetName = unpackString(data, 6, 1);
else
sheetName = unpackUnicode(data, 6, 1);
}
if (sheetType != XL_BOUNDSHEET_WORKSHEET)
m_sheetMap.push_back(-1);
else {
int size = static_cast<int>(m_sheetNames.size());
m_sheetMap.push_back(size);
m_sheetNames.push_back(sheetName);
m_sheetAbsolutePos.push_back(absolutePos);
m_sheetVisibility.push_back(visibility);
m_sheetIdFromName[sheetName] = size;
}
}
void Book::handleExternalName(const std::string& data) {
if (m_biffVersion >= 80) {
int pos = 6;
std::string name = unpackUnicodeUpdatePos(data, pos, 1);
if (m_supbookTypes.back() == SUPBOOK_ADDIN)
m_addinFuncNames.push_back(name);
}
}
void Book::handleExternalSheet(std::string& data) {
getEncoding(); // If CODEPAGE record is missing/out of order/wrong
m_externalSheetCount++;
if (m_biffVersion >= 80) {
unsigned short numRefs = readByte<unsigned short>(data, 0, 2);
while (data.size() < numRefs*6 + 2) {
unsigned short code;
unsigned short length;
std::string data2;
getRecordParts(code, length, data2);
if (code != XL_CONTINUE)
throw std::logic_error("Missing CONTINUE after EXTERNSHEET record");
data += data2;
}
int pos = 2;
for (int k = 0; k < numRefs; ++k) {
m_externalSheetInfo.push_back({
readByte<unsigned short>(data, pos, 2),
readByte<unsigned short>(data, pos+2, 2),
readByte<unsigned short>(data, pos+4, 2)
});
pos += 6;
}
}
else {
unsigned char size = readByte<unsigned char>(data, 0, 1);
unsigned char type = readByte<unsigned char>(data, 1, 1);
if (type == 3)
m_externalSheetNameFromId[m_externalSheetCount] = data.substr(2, size);
if (type < 1 || type > 4)
type = 0;
m_externalSheetTypes.push_back(type);
}
}
void Book::handleSheethdr(const std::string& data) {
getEncoding();
int sheetLength = readByte<int>(data, 0, 4);
//std::string sheetName = unpackString(data, 4, 1);
int bofPosition = m_position;
m_sheethdrCount++;
initializeFormatInfo();
getSheet(m_sheethdrCount, false);
m_position = bofPosition + sheetLength;
}
void Book::handleSupbook(const std::string& data) {
m_supbookTypes.push_back(-1);
unsigned short sheetCount = readByte<unsigned short>(data, 0, 2);
m_supbookCount++;
if (data.substr(2, 2) == "\x01\x04") {
m_supbookTypes.back() = SUPBOOK_INTERNAL;
m_supbookLocalIndex = m_supbookCount - 1;
return;
}
if (data.substr(0, 4) == "\x01\x00\x01\x3A") {
m_supbookTypes.back() = SUPBOOK_ADDIN;
m_supbookAddinIndex = m_supbookCount - 1;
return;
}
int pos = 2;
std::string url = unpackUnicodeUpdatePos(data, pos, 2);
if (sheetCount == 0) {
m_supbookTypes.back() = SUPBOOK_DDEOLE;
return;
}
m_supbookTypes.back() = SUPBOOK_EXTERNAL;
std::vector<std::string> sheetNames;
for (int x = 0; x < sheetCount; ++x) {
try {
sheetNames.emplace_back(unpackUnicodeUpdatePos(data, pos, 2));
}
catch (...) {
break;
}
}
}
void Book::handleName(const std::string& data) {
if (m_biffVersion < 50)
return;
getEncoding();
unsigned short optionFlags = readByte<unsigned short>(data, 0, 2);
//unsigned char kbShortcut = readByte<unsigned char>(data, 2, 1);
unsigned char nameLength = readByte<unsigned char>(data, 3, 1);
unsigned short formulaLength = readByte<unsigned short>(data, 4, 2);
unsigned short externalSheetIndex = readByte<unsigned short>(data, 6, 2);
unsigned short sheetIndex = readByte<unsigned short>(data, 8, 2);
//unsigned char menuTextLength = readByte<unsigned char>(data, 10, 1);
//unsigned char descriptionTextLength = readByte<unsigned char>(data, 11, 1);
//unsigned char helpTextLength = readByte<unsigned char>(data, 12, 1);
//unsigned char statusTextLength = readByte<unsigned char>(data, 13, 1);
m_nameObjList.emplace_back(Name(this));
Name& nobj = m_nameObjList.back();
nobj.m_nameIndex = m_nameObjList.size() - 1;
nobj.m_optionFlags = optionFlags;
nobj.m_isHidden = (optionFlags & 1) >> 0;
nobj.m_function = (optionFlags & 2) >> 1;
nobj.m_vbasic = (optionFlags & 4) >> 2;
nobj.m_macro = (optionFlags & 8) >> 3;
nobj.m_isComplex = (optionFlags & 0x10) >> 4;
nobj.m_builtIn = (optionFlags & 0x20) >> 5;
nobj.m_functionGroup = (optionFlags & 0xFC0) >> 6;
nobj.m_isBinary = (optionFlags & 0x1000) >> 12;
nobj.m_externalSheetIndex = externalSheetIndex;
nobj.m_excelSheetIndex = sheetIndex;
nobj.m_basicFormulaLength = formulaLength;
nobj.m_evaluated = 0;
nobj.m_scope = -5; // Patched up in the names_epilogue() method
std::string internalName;
int pos = 14;
if (m_biffVersion < 80)
internalName = unpackStringUpdatePos(data, pos, 1, nameLength);
else
internalName = unpackUnicodeUpdatePos(data, pos, 2, nameLength);
if (!nobj.m_builtIn)
nobj.m_name = internalName;
else if (BUILTIN_NAME_FROM_CODE.find(internalName) == BUILTIN_NAME_FROM_CODE.end())
nobj.m_name = BUILTIN_NAME_FROM_CODE.at(internalName);
else
nobj.m_name = "??Unknown??";
nobj.m_rawFormula = data.substr(pos);
}
void Book::initializeFormatInfo() {
m_formatMap.clear();
m_formatList.clear();
m_xfCount = 0;
m_actualFormatCount = 0; // Number of FORMAT records seen so far
m_xfEpilogueDone = 0;
m_xfIndexXlTypeMap = {{0, XL_CELL_NUMBER}};
m_xfList.clear();
m_fontList.clear();
}
void Book::unpackSst(const std::vector<std::string>& dataTable, int stringCount) {
std::string data = dataTable[0];
int dataIndex = 0;
size_t dataSize = dataTable.size();
size_t dataLength = data.size();
int pos = 8;
m_sharedStrings.clear();
if (m_addStyle)
m_richtextRunlistMap.clear();
for (int i = 0; i < stringCount; ++i) {
unsigned short charCount = readByte<unsigned short>(data, pos, 2);
char options = data[pos + 2];
int richTextCount = 0;
int phoneticSize = 0;
pos += 3;
if (options & 0x08) { // Richtext
richTextCount = readByte<unsigned short>(data, pos, 2);
pos += 2;
}
if (options & 0x04) { // Phonetic
phoneticSize = readByte<int>(data, pos, 4);
pos += 4;
}
std::string result;
int gotChars = 0;
while (true) {
int charsNeed = charCount - gotChars;
int charsAvailable;
if (options & 0x01) {
// Uncompressed UTF-16
charsAvailable = std::min(((int)dataLength - pos) >> 1, charsNeed);
result += data.substr(pos, 2*charsAvailable);
result = encoding::decode(result, "UTF-16LE");
pos += 2*charsAvailable;
}
else {
// Note: this is COMPRESSED (not ASCII!) encoding!!!
charsAvailable = std::min((int)dataLength - pos, charsNeed);
result += data.substr(pos, charsAvailable);
result = encoding::decode(result, "ISO-8859-1");
pos += charsAvailable;
}
gotChars += charsAvailable;
if (gotChars == charCount)
break;
dataIndex += 1;
data = dataTable[dataIndex];
dataLength = data.size();
options = data[0];
pos = 1;
}
if (richTextCount) {
std::vector<std::pair<unsigned short, unsigned short>> runs;
for (int j = 0; j < richTextCount; ++j) {
if (pos == static_cast<int>(dataLength)) {
pos = 0;
dataIndex += 1;
data = dataTable[dataIndex];
dataLength = data.size();
}
runs.emplace_back(readByte<unsigned short>(data, pos, 2),
readByte<unsigned short>(data, pos+2, 2));
pos += 4;
}
if (m_addStyle)
m_richtextRunlistMap[m_sharedStrings.size()] = runs;
}
pos += phoneticSize; // Size of the phonetic stuff to skip
if (pos >= static_cast<int>(dataLength)) {
// Adjust to correct position in next record
pos -= static_cast<int>(dataLength);
dataIndex++;
if (dataIndex < static_cast<int>(dataSize)) {
data = dataTable[dataIndex];
dataLength = data.size();
}
}
m_sharedStrings.push_back(result);
}
}
void Book::namesEpilogue() {
size_t nameCount = m_nameObjList.size();
for (size_t i = 0; i < nameCount; ++i) {
Name& name = m_nameObjList[i];
int internalSheetIndex = -3;
// Convert from excelSheetIndex to scope. Done here because in BIFF7 and earlier
// the BOUNDSHEET records come after the NAME records
if (m_biffVersion >= 80) {
int sheetIndex = name.m_excelSheetIndex;
if (sheetIndex == 0)
internalSheetIndex = -1; // Global
else if (1 <= sheetIndex && sheetIndex <= static_cast<int>(m_sheetMap.size())) {
internalSheetIndex = m_sheetMap[sheetIndex-1];
if (internalSheetIndex == -1) // Maps to a macro or VBA sheet
internalSheetIndex = -2; // Valid sheet reference but not useful
}
else
internalSheetIndex = -3; // Invalid
}
else if (50 <= m_biffVersion && m_biffVersion <= 70) {
int sheetIndex = name.m_externalSheetIndex;
if (sheetIndex == 0)
internalSheetIndex = -1; // Global
else {
std::string sheetName = m_externalSheetNameFromId[sheetIndex];
if (m_sheetIdFromName.find(sheetName) == m_sheetIdFromName.end())
internalSheetIndex = m_sheetIdFromName[sheetName];
else
internalSheetIndex = -2;
}
}
name.m_scope = static_cast<int>(internalSheetIndex);
}
Formula formula(this);
for (int i = 0; i < (int)nameCount; ++i) {
Name& name = m_nameObjList[i];
// Parse the formula
if (name.m_macro || name.m_isBinary || name.m_evaluated)
continue;
formula.evaluateFormula(name, i);
}
// Build some dicts for access to the name objects
m_nameScopeMap.clear();
m_nameMap.clear();
std::map<std::string, std::vector<std::pair<Name, int>>> nameMap;
for (int i = 0; i < (int)nameCount; ++i) {
Name& name = m_nameObjList[i];
std::string nameName = name.m_name;
std::transform(nameName.begin(), nameName.end(), nameName.begin(), ::tolower);
std::pair<std::string, int> key {nameName, name.m_scope};
m_nameScopeMap.erase(key);
m_nameScopeMap.emplace(key, name);
nameMap[nameName].emplace_back(name, i);
}
for (auto & map : nameMap) {
std::sort(map.second.begin(), map.second.end());
for (const auto& obj : map.second)
m_nameMap[map.first].emplace_back(obj.first);
}
}
// Name public:
Name::Name(Book* book)
: m_book(book) {}
bool Name::operator < (const Name& name) const {
return m_scope < name.m_scope;
}
} // End namespace
| 29.597813 | 100 | 0.662958 | [
"vector",
"transform"
] |
51d68abb831d3affee2e10f3661bf8e542477f32 | 1,380 | cpp | C++ | src/graficos/GraficoDeEscenario.cpp | humbertodias/Final-Fight | f5f8983dce599cc68548797d6d992cb34b44c3b2 | [
"MIT"
] | null | null | null | src/graficos/GraficoDeEscenario.cpp | humbertodias/Final-Fight | f5f8983dce599cc68548797d6d992cb34b44c3b2 | [
"MIT"
] | null | null | null | src/graficos/GraficoDeEscenario.cpp | humbertodias/Final-Fight | f5f8983dce599cc68548797d6d992cb34b44c3b2 | [
"MIT"
] | null | null | null | //
// Created by sebas on 10/9/19.
//
#include "GraficoDeEscenario.h"
#include "../servicios/Locator.h"
#include "../modelo/serializables/Posicion.h"
#include <utility>
#include <cmath>
GraficoDeEscenario::GraficoDeEscenario (Entidad * entidad,
vector < SDL_Texture * >sprites,
vector < SDL_Rect > posicionesSprite,
vector < float >distanciasAlFondo,
float escalaHorizontal):
Comportamiento (entidad),
sprites (std::move (sprites)),
escalaHorizontal (escalaHorizontal),
posicionesSprite (std::move (posicionesSprite)),
distanciasAlFondo (std::move (distanciasAlFondo))
{
}
void
GraficoDeEscenario::actualizar ()
{
SDL_Renderer *renderer = Locator::renderer ();
int alto = Locator::configuracion ()->getIntValue ("/resolucion/alto");
int ancho = Locator::configuracion ()->getIntValue ("/resolucion/ancho");
int posicion = entidad->getEstado < Posicion > ("posicion")->getX ();
for (size_t i = 0; i < sprites.size (); ++i)
{
SDL_Texture *sprite = sprites[i];
SDL_Rect posicionSprite = posicionesSprite[i];
posicionSprite.w = int (round ((float) ancho / escalaHorizontal));
posicionSprite.x =
int (round
((float) posicion / escalaHorizontal * distanciasAlFondo[i]));
SDL_Rect posicionEscenario = { 0, 0, ancho, alto };
SDL_RenderCopy (renderer, sprite, &posicionSprite, &posicionEscenario);
}
}
| 30 | 77 | 0.696377 | [
"vector"
] |
51d840a7544caddd4620b0f55219fbf0ecda7c19 | 4,946 | cpp | C++ | app/src/main/cpp/com_xiaowei_ndkcpp_NDKCpp.cpp | sxwn/ndkcpp | 6d778d6e7ad63109473323b2b722dae9dcf0f462 | [
"Apache-2.0"
] | null | null | null | app/src/main/cpp/com_xiaowei_ndkcpp_NDKCpp.cpp | sxwn/ndkcpp | 6d778d6e7ad63109473323b2b722dae9dcf0f462 | [
"Apache-2.0"
] | null | null | null | app/src/main/cpp/com_xiaowei_ndkcpp_NDKCpp.cpp | sxwn/ndkcpp | 6d778d6e7ad63109473323b2b722dae9dcf0f462 | [
"Apache-2.0"
] | null | null | null | //
// Created by Administrator on 2019/12/20.
//
#include "com_xiaowei_ndkcpp_NDKCpp.h"
#include <iostream>
using namespace std;
#include "model/Student.h"
#include "model/StaticClass.h"
#include "model/FriendFunc.h"
#include <android/log.h>
extern "C" {
//C++构造函数
//需求:Teacher类中没有提供无参数的构造函数,在Student类中定义一个Teacher属性变量
//需要初始化
//什么时候析构函数调用?
JNIEXPORT void JNICALL Java_com_xiaowei_ndkcpp_NDKCpp_callCppConstruct
(JNIEnv *env, jobject jobj){
//创建两个Teacher对象,创建一个Student对象
Student student = Student("印度阿三","lisi","wangwu");
//释放
//首先释放析构Student,再释放析构Teacher
//注意:顺序类似于栈的数据结构(先进后出,后进先出)
};
//new delete关键字
JNIEXPORT void JNICALL
Java_com_xiaowei_ndkcpp_NDKCpp_callCppNewOrDelete(JNIEnv *env, jobject jobj){
//基本数据类型
//在堆内存中开辟一块内存空间
// int *p = (int*)(malloc(sizeof(int)));
// *p = 100;
// //释放内存
// free(p);
// p=NULL;
//C++中提供了非常简便的方式(采取new、delete关键字)
//new int 相当于(int*)(malloc(sizeof(int)))
// int *p = new int;
// *p = 100;
//释放内存
// delete p;
// free(p);
// p =NULL;
//数组类型
//在C语言中(动态内存分配)
//返回的p就是数组的首地址,通过指针位移的方式一个个读取
// int *p = (int *)malloc(sizeof(int)*10);
// p[0] = 100;
// free(p);
//C++中
// int *p = new int[10];
// p[0] = 19;
// //注意:释放数组
// delete[] p;
//分配对象
//C++中支持C的混编
// Teacher* teacher = (Teacher*)malloc(sizeof(Teacher)) ;
// teacher->setName("detam");
// //释放内存
// free(teacher);
//直接C++语法
//这个开辟内存是栈内存(自动管理)
// Teacher teacher = Teacher();
//开辟的是堆内存
Teacher* teacher = new Teacher();
teacher->setName("detam");
delete teacher;
};
//C++ static关键字
//static修饰属性 修饰函数
#include "model/StaticClass.h"
//静态属性,需要在函数的外部进行初始化
int StaticClass::age = 100;
JNIEXPORT void JNICALL
Java_com_xiaowei_ndkcpp_NDKCpp_callCppStatic(JNIEnv *env, jobject jobj){
// StaticClass staticClass = StaticClass("Dream");
// staticClass.age = 100;
// __android_log_print(ANDROID_LOG_INFO,"weip","age:%d",StaticClass::age);
//访问静态方法
StaticClass::toString();
};
//C++对象大小
//回想:结构体大小
//结果:objectSizeA大小:8 objectSizeB大小:12 objectSizeC大小;12
//内存分配
//C++类对象的属性和成员函数内存分开存储的
//普通属性:存储在对象中,与结构体存储规则一样
//静态属性:存在静态数据区(内存区:栈、堆、静态区、全局区、代码区)
//成员函数:存储在代码区
//问题:既然成员函数都是放置在代码区,共享,那么函数怎么知道当前访问的是哪一个对象?
//解决方案:this区分
#include "model/ObjectSize.h"
JNIEXPORT void JNICALL
Java_com_xiaowei_ndkcpp_NDKCpp_callCppObjectSize(JNIEnv *env, jobject thiz){
__android_log_print(ANDROID_LOG_INFO,"weip","objectSizeA大小: %d", sizeof(ObjectSizeA));
__android_log_print(ANDROID_LOG_INFO,"weip","objectSizeB大小: %d", sizeof(ObjectSizeB));
__android_log_print(ANDROID_LOG_INFO,"weip","objectSizeC大小: %d", sizeof(ObjectSizeC));
//C++中类的底层实现相当于一个结构体
ObjectSizeC c1;
ObjectSizeC c2;
ObjectSizeC c3;
c1.toString();
c2.toString();
c3.toString();
};
//C++中const修饰函数(常量函数)
//const修饰什么?
//属性不能修改
//总结:const修饰的this指针所指向的内存区域不能够修改
JNIEXPORT void JNICALL
Java_com_xiaowei_ndkcpp_NDKCpp_callCppConstFunc(JNIEnv *env, jobject jobj){
};
//C++中友元函数
//需求:我要访问私有属性
//友元函数实现
//void update_name(FriendFunc *func,char *name){
// func->name = name;
//}
JNIEXPORT void JNICALL
Java_com_xiaowei_ndkcpp_NDKCpp_callCppFriendFunc(JNIEnv *env, jobject jobj){
FriendFunc* friendFunc = new FriendFunc();
// //硬是要访问? 解决访问:友元函数
//这块调取友元函数报错,目前未找到解决方案
// update_name(friendFunc,"Hello");
__android_log_print(ANDROID_LOG_INFO,"weip","值: %s",friendFunc->getName());
};
//c++中友元类
//A类需要访问B类中的私有属性或者函数?
//解决方案:友元类(java反射机制的底层实现)
//注意:A类需要声明B类是我d的友元类,之后B类可以访问A类的任何属性和方法
#include "model/FriendClass.h"
JNIEXPORT void JNICALL
Java_com_xiaowei_ndkcpp_NDKCpp_callCppFriendClass(JNIEnv *env, jobject thiz){
__android_log_print(ANDROID_LOG_INFO,"weip","友元类");
//为什么不能够修改?
//打印结构:A创建了2次,拷贝了1次,析构了3次 b创建了1次,析构了1次
// FriendA friendA;
// friendA.setName("Dream");
// __android_log_print(ANDROID_LOG_INFO,"weip","修改之前的值: %s",friendA.getName());
//A第二次创建,是因为FriendB有一个FriendA的属性调用构造函数(因为对象属性需要初始化)
// FriendB friendB;
//拷贝对象:实参初始化形参,这个时候也会进行对象拷贝
//第一次析构(析构形参):因为形参在update_friendA方法中使用完毕,会立马进行析构形参对象
// friendB.update_friendA(friendA,"jack");
// __android_log_print(ANDROID_LOG_INFO,"weip","修改之后的值: %s",friendA.getName());
//第二次析构:析构friendA
//第三次析构:析构friendB中friendA属性
//那么怎么样才能够实现修改?
//解决方案:传递指针引用
// FriendA* friendA = new FriendA();
// friendA->setName("Dream");
// __android_log_print(ANDROID_LOG_INFO,"weip","修改之前的值: %s",friendA->getName());
// FriendB friendB;
// friendB.update_friendA_name(friendA,"jack");
// __android_log_print(ANDROID_LOG_INFO,"weip","修改之后的值: %s",friendA->getName());
FriendA friendA = FriendA();
friendA.setName("Dream");
__android_log_print(ANDROID_LOG_INFO,"weip","修改之前的值: %s",friendA.getName());
FriendB friendB;
friendB.update_friendA_name(&friendA,"jack");
__android_log_print(ANDROID_LOG_INFO,"weip","修改之后的值: %s",friendA.getName());
};
}
| 28.923977 | 90 | 0.690659 | [
"model"
] |
51db7297bcaa0ff2d942762969cb219b4148ccb1 | 24,575 | cxx | C++ | IO/AMR/vtkAMReXParticlesReader.cxx | forestGzh/VTK | bc98327275bd5cfa95c5825f80a2755a458b6da8 | [
"BSD-3-Clause"
] | 3 | 2015-07-28T18:07:50.000Z | 2018-02-28T20:59:58.000Z | IO/AMR/vtkAMReXParticlesReader.cxx | forestGzh/VTK | bc98327275bd5cfa95c5825f80a2755a458b6da8 | [
"BSD-3-Clause"
] | 4 | 2018-10-25T09:46:11.000Z | 2019-01-17T16:49:17.000Z | IO/AMR/vtkAMReXParticlesReader.cxx | forestGzh/VTK | bc98327275bd5cfa95c5825f80a2755a458b6da8 | [
"BSD-3-Clause"
] | 4 | 2016-09-08T02:11:00.000Z | 2019-08-15T02:38:39.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: vtkAMReXParticlesReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkAMReXParticlesReader.h"
#include "vtkAOSDataArrayTemplate.h"
#include "vtkCellArray.h"
#include "vtkCommand.h"
#include "vtkDataArraySelection.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkMultiPieceDataSet.h"
#include "vtkMultiProcessController.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkSOADataArrayTemplate.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtksys/SystemTools.hxx"
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <sstream>
#include <vector>
using vtksystools = vtksys::SystemTools;
namespace
{
// returns empty string on failure.
std::string ReadAndBroadCastFile(const std::string& filename, vtkMultiProcessController* controller)
{
std::string contents;
if (controller == nullptr || controller->GetLocalProcessId() == 0)
{
std::ifstream stream(filename, std::ios::binary);
if (stream)
{
stream.seekg(0, std::ios::end);
int flength = static_cast<int>(stream.tellg());
stream.seekg(0, std::ios::beg);
if (controller)
{
controller->Broadcast(&flength, 1, 0);
}
char* data = new char[flength + 1 + (flength + 1) % 8]; // padded for better alignment.
stream.read(data, flength);
if (controller)
{
controller->Broadcast(data, flength, 0);
}
data[flength] = '\0';
contents = data;
delete[] data;
data = nullptr;
}
}
else if (controller && controller->GetLocalProcessId() > 0)
{
int flength(0);
controller->Broadcast(&flength, 1, 0);
char* data = new char[flength + 1 + (flength + 1) % 8]; // padded for better alignment.
if (controller)
{
controller->Broadcast(data, flength, 0);
}
data[flength] = '\0';
contents = data;
delete[] data;
data = nullptr;
}
return contents;
}
}
#define AMREX_PRINT(os, indent, var) os << indent << #var << ": " << var << endl
class vtkAMReXParticlesReader::AMReXParticleHeader
{
template <typename RealType, typename IntType>
bool ReadParticles(
vtkPolyData* pd, const int count, istream& ifp, const vtkAMReXParticlesReader* self) const
{
auto selection = self->GetPointDataArraySelection();
// read integer data.
vtkNew<vtkAOSDataArrayTemplate<IntType> > istuff;
if (this->is_checkpoint)
{
istuff->SetNumberOfComponents(this->num_int);
istuff->SetNumberOfTuples(count);
if (!ifp.read(reinterpret_cast<char*>(istuff->GetPointer(0)),
count * this->num_int * sizeof(IntType)))
{
return false;
}
}
// read real data.
vtkNew<vtkAOSDataArrayTemplate<RealType> > rstuff;
rstuff->SetNumberOfComponents(this->num_real);
rstuff->SetNumberOfTuples(count);
if (!ifp.read(reinterpret_cast<char*>(rstuff->GetPointer(0)),
count * this->num_real * sizeof(RealType)))
{
return false;
}
// Split out istuff and rstuff into separate arrays.
if (this->num_int > 0)
{
std::vector<IntType*> iptrs(this->num_int, nullptr);
std::vector<vtkIdType*> idtypeptrs(this->num_int, nullptr);
for (int cc = 0; cc < this->num_int; ++cc)
{
// need to determine is the 1st two array have standard names.
const std::string& name = (cc < this->num_int_base)
? this->int_base_component_names[cc]
: this->int_component_names[cc - this->num_int_base];
if (selection->GetArraySetting(name.c_str()) == 0)
{
continue;
}
// we'll handle "id" array separately.
if (name == "id")
{
vtkNew<vtkIdTypeArray> idarray;
idarray->SetName(name.c_str());
idarray->SetNumberOfComponents(1);
idarray->SetNumberOfTuples(count);
pd->GetPointData()->AddArray(idarray);
idtypeptrs[cc] = idarray->GetPointer(0);
}
else
{
vtkNew<vtkAOSDataArrayTemplate<IntType> > iarray;
iarray->SetName(name.c_str());
iarray->SetNumberOfComponents(1);
iarray->SetNumberOfTuples(count);
pd->GetPointData()->AddArray(iarray);
iptrs[cc] = iarray->GetPointer(0);
}
}
const IntType* isource = istuff->GetPointer(0);
for (int cc = 0; cc < count; ++cc)
{
for (int kk = 0; kk < this->num_int; ++kk, ++isource)
{
if (iptrs[kk] != nullptr)
{
iptrs[kk][cc] = *isource;
}
else if (idtypeptrs[kk] != nullptr)
{
idtypeptrs[kk][cc] = static_cast<vtkIdType>(*isource);
}
}
}
}
if (this->num_real > 0)
{
std::vector<RealType*> rptrs(this->num_real, nullptr);
assert(this->num_real_base == this->dim);
vtkNew<vtkAOSDataArrayTemplate<RealType> > coords;
coords->SetName("Points");
coords->SetNumberOfComponents(3);
coords->SetNumberOfTuples(count);
if (this->num_real_base < 3)
{
// fill with 0, since this->dim may be less than 3.
std::fill_n(coords->GetPointer(0), 3*count, 0.0);
}
vtkNew<vtkPoints> pts;
pts->SetData(coords);
pd->SetPoints(pts);
rptrs[0] = coords->GetPointer(0);
for (int cc = this->num_real_base; cc < this->num_real; ++cc)
{
const auto& name = this->real_component_names[cc - this->num_real_base];
if (selection->GetArraySetting(name.c_str()) == 0)
{
continue;
}
vtkNew<vtkAOSDataArrayTemplate<RealType> > rarray;
rarray->SetName(name.c_str());
rarray->SetNumberOfComponents(1);
rarray->SetNumberOfTuples(count);
pd->GetPointData()->AddArray(rarray);
rptrs[cc] = rarray->GetPointer(0);
}
const RealType* rsource = rstuff->GetPointer(0);
for (int cc = 0; cc < count; ++cc)
{
for (int kk = 0; kk < this->num_real_base; ++kk)
{
rptrs[0][this->num_real_base * cc + kk] = *rsource++;
}
for (int kk = this->num_real_base; kk < this->num_real; ++kk, ++rsource)
{
if (rptrs[kk] != nullptr)
{
rptrs[kk][cc] = *rsource;
}
}
}
}
//// Now build connectivity information.
// vtkNew<vtkCellArray> verts;
// verts->Allocate(verts->EstimateSize(count, 1));
// for (vtkIdType cc=0; cc < count; ++cc)
//{
// verts->InsertNextCell(1, &cc);
//}
// pd->SetVerts(verts);
return true;
}
// seems like the DATA_<filenumber> files can be written with differing number
// of leading zeros. That being the case, we try a few options starting the
// most recent successful match.
// Returns empty string if failed to find a valid filename.
std::string GetDATAFileName(
const std::string& plotfilename, const std::string& ptype, int level, int filenumber) const
{
std::string fname =
this->GetDATAFileName(plotfilename, ptype, level, filenumber, this->DataFormatZeroFill);
if (!fname.empty())
{
return fname;
}
for (int cc = 7; cc >= 0; --cc)
{
fname = this->GetDATAFileName(plotfilename, ptype, level, filenumber, cc);
if (!fname.empty())
{
this->DataFormatZeroFill = cc;
return fname;
}
}
return std::string();
}
// Returns empty string if failed to find a valid filename.
std::string GetDATAFileName(const std::string& plotfilename, const std::string& ptype, int level,
int filenumber, int zerofill) const
{
std::ostringstream str;
str << plotfilename << "/" << ptype << "/Level_" << level << "/DATA_" << std::setfill('0')
<< std::setw(zerofill) << filenumber;
return (vtksys::SystemTools::FileExists(str.str(), /*isFile*/ true)) ? str.str()
: std::string();
}
mutable int DataFormatZeroFill;
public:
struct GridInfo
{
int which;
int count;
vtkTypeInt64 where;
};
// the names are deliberately kept consistent with am
std::vector<std::string> real_component_names;
std::vector<std::string> int_component_names;
std::vector<std::string> int_base_component_names;
size_t int_type;
size_t real_type;
int dim;
int num_int_base;
int num_real_base;
int num_real_extra;
int num_int_extra;
int num_int;
int num_real;
bool is_checkpoint;
vtkIdType num_particles;
vtkIdType max_next_id;
int finest_level;
int num_levels;
std::vector<int> grids_per_level;
std::vector<std::vector<GridInfo> > grids;
AMReXParticleHeader()
: DataFormatZeroFill(5)
, real_component_names()
, int_component_names()
, int_base_component_names()
, int_type(0)
, real_type(0)
, dim(0)
, num_int_base(0)
, num_real_base(0)
, num_real_extra(0)
, num_int_extra(0)
, num_int(0)
, num_real(0)
, is_checkpoint(false)
, num_particles(0)
, max_next_id(0)
, finest_level(0)
, num_levels(0)
, grids_per_level()
, grids()
{
}
void PrintSelf(ostream& os, vtkIndent indent)
{
AMREX_PRINT(os, indent, real_type);
AMREX_PRINT(os, indent, int_type);
AMREX_PRINT(os, indent, dim);
AMREX_PRINT(os, indent, num_int_base);
AMREX_PRINT(os, indent, num_real_base);
AMREX_PRINT(os, indent, num_real_extra);
AMREX_PRINT(os, indent, num_int_extra);
AMREX_PRINT(os, indent, num_int);
AMREX_PRINT(os, indent, num_real);
AMREX_PRINT(os, indent, is_checkpoint);
AMREX_PRINT(os, indent, num_particles);
AMREX_PRINT(os, indent, max_next_id);
AMREX_PRINT(os, indent, finest_level);
AMREX_PRINT(os, indent, num_levels);
os << indent << "grids_per_level: " << endl;
for (const int& gpl : this->grids_per_level)
{
os << indent.GetNextIndent() << gpl << endl;
}
os << indent << "grids: " << endl;
int level = 0;
for (const auto& grids_level : this->grids)
{
os << indent.GetNextIndent() << "level: " << level << endl;
for (const auto& ginfo : grids_level)
{
os << indent.GetNextIndent().GetNextIndent() << "which: " << ginfo.which
<< " count: " << ginfo.count << " where: " << ginfo.where << endl;
}
level++;
}
os << indent << "real_component_names: " << endl;
for (const auto& name : this->real_component_names)
{
os << indent.GetNextIndent() << name << endl;
}
os << indent << "int_component_names: " << endl;
for (const auto& name : this->int_component_names)
{
os << indent.GetNextIndent() << name << endl;
}
}
bool Parse(const std::string& headerData)
{
std::istringstream hstream(headerData);
std::string version;
hstream >> version;
if (version.empty())
{
vtkGenericWarningMacro("Failed to read version string.");
return false;
}
this->int_type = 32;
// What do our version strings mean? (from ParticleContainer::Restart)
// "Version_One_Dot_Zero" -- hard-wired to write out in double precision.
// "Version_One_Dot_One" -- can write out either as either single or double precision.
// Appended to the latter version string are either "_single" or "_double" to
// indicate how the particles were written.
// "Version_Two_Dot_Zero" -- this is the AMReX particle file format
if (version.find("Version_One_Dot_Zero") != std::string::npos)
{
this->real_type = 64;
}
else if (version.find("Version_One_Dot_One") != std::string::npos ||
version.find("Version_Two_Dot_Zero") != std::string::npos)
{
if (version.find("_single") != std::string::npos)
{
this->real_type = 32;
}
else if (version.find("_double") != std::string::npos)
{
this->real_type = 64;
}
else
{
vtkGenericWarningMacro("Bad version string: " << version);
return false;
}
}
else
{
vtkGenericWarningMacro("Bad version string: " << version);
return false;
}
hstream >> this->dim;
if (this->dim != 1 && this->dim != 2 && this->dim != 3)
{
vtkGenericWarningMacro("dim must be 1, 2, or 3.");
return false;
}
this->num_int_base = 2;
this->num_real_base = this->dim;
hstream >> this->num_real_extra;
if (this->num_real_extra < 0 || this->num_real_extra > 1024)
{
vtkGenericWarningMacro("potentially incorrect num_real_extra=" << this->num_real_extra);
return false;
}
this->real_component_names.resize(this->num_real_extra);
for (int cc = 0; cc < this->num_real_extra; ++cc)
{
hstream >> this->real_component_names[cc];
}
hstream >> this->num_int_extra;
if (this->num_int_extra < 0 || this->num_int_extra > 1024)
{
vtkGenericWarningMacro("potentially incorrect num_int_extra=" << this->num_int_extra);
return false;
}
this->int_component_names.resize(this->num_int_extra);
for (int cc = 0; cc < this->num_int_extra; ++cc)
{
hstream >> this->int_component_names[cc];
}
this->num_real = this->num_real_base + this->num_real_extra;
this->num_int = this->num_int_base + this->num_int_extra;
hstream >> this->is_checkpoint;
hstream >> this->num_particles;
if (this->num_particles < 0)
{
vtkGenericWarningMacro("num_particles must be >=0");
return false;
}
hstream >> this->max_next_id;
if (this->max_next_id <= 0)
{
vtkGenericWarningMacro("max_next_id must be > 0");
return false;
}
hstream >> this->finest_level;
if (this->finest_level < 0)
{
vtkGenericWarningMacro("finest_level must be >= 0");
return false;
}
this->num_levels = this->finest_level + 1;
if (!this->is_checkpoint)
{
this->num_int_base = 0;
this->num_int_extra = 0;
this->num_int = 0;
}
else
{
this->int_base_component_names.push_back("id");
this->int_base_component_names.push_back("cpu");
}
this->grids_per_level.resize(this->num_levels, 0);
for (int lev = 0; lev < this->num_levels; ++lev)
{
hstream >> this->grids_per_level[lev];
assert(this->grids_per_level[lev] > 0);
}
this->grids.resize(this->num_levels);
for (int lev = 0; lev < this->num_levels; ++lev)
{
auto& grids_lev = this->grids[lev];
grids_lev.resize(this->grids_per_level[lev]);
for (int grid_num = 0; grid_num < this->grids_per_level[lev]; ++grid_num)
{
hstream >> grids_lev[grid_num].which >> grids_lev[grid_num].count >>
grids_lev[grid_num].where;
}
}
return true;
}
bool ReadGrid(int level, int idx, vtkPolyData* pd, const vtkAMReXParticlesReader* self) const
{
assert(level < this->num_levels && idx < this->grids_per_level[level]);
auto& gridInfo = this->grids[level][idx];
if (gridInfo.count == 0)
{
// empty grid.
return true;
}
const std::string& fname =
this->GetDATAFileName(self->PlotFileName, self->ParticleType, level, gridInfo.which);
std::ifstream ifp(fname, std::ios::binary);
if (!ifp.good())
{
return false;
}
ifp.seekg(gridInfo.where, std::ios::beg);
if (this->real_type == 32 && this->int_type == 32)
{
return this->ReadParticles<float, vtkTypeInt32>(pd, gridInfo.count, ifp, self);
}
else if (this->real_type == 64 && this->int_type == 32)
{
return this->ReadParticles<double, vtkTypeInt32>(pd, gridInfo.count, ifp, self);
}
else
{
return false;
}
}
void PopulatePointArraySelection(vtkDataArraySelection* selection) const
{
for (auto& aname : this->int_base_component_names)
{
selection->AddArray(aname.c_str());
}
for (auto& aname : this->int_component_names)
{
selection->AddArray(aname.c_str());
}
for (auto& aname : this->real_component_names)
{
selection->AddArray(aname.c_str());
}
}
};
vtkStandardNewMacro(vtkAMReXParticlesReader);
vtkCxxSetObjectMacro(vtkAMReXParticlesReader, Controller, vtkMultiProcessController);
//----------------------------------------------------------------------------
vtkAMReXParticlesReader::vtkAMReXParticlesReader()
: Controller(nullptr)
, PlotFileName()
, PlotFileNameMTime()
, MetaDataMTime()
, ParticleType("particles")
, Header(nullptr)
{
this->SetNumberOfInputPorts(0);
this->SetNumberOfOutputPorts(1);
this->SetController(vtkMultiProcessController::GetGlobalController());
this->PointDataArraySelection->AddObserver(
vtkCommand::ModifiedEvent, this, &vtkAMReXParticlesReader::Modified);
}
//----------------------------------------------------------------------------
vtkAMReXParticlesReader::~vtkAMReXParticlesReader()
{
this->SetController(nullptr);
delete this->Header;
}
//----------------------------------------------------------------------------
void vtkAMReXParticlesReader::SetPlotFileName(const char* fname)
{
const std::string filename(fname == nullptr ? "" : fname);
if (this->PlotFileName != filename)
{
this->PlotFileName = filename;
this->PlotFileNameMTime.Modified();
this->Modified();
}
}
//----------------------------------------------------------------------------
void vtkAMReXParticlesReader::SetParticleType(const std::string& str)
{
if (this->ParticleType != str)
{
this->ParticleType = str;
this->PlotFileNameMTime.Modified(); // since we need to re-read metadata.
this->Modified();
}
}
//----------------------------------------------------------------------------
vtkDataArraySelection* vtkAMReXParticlesReader::GetPointDataArraySelection() const
{
return this->PointDataArraySelection;
}
//----------------------------------------------------------------------------
int vtkAMReXParticlesReader::CanReadFile(const char* fname, const char* particleType)
{
if (fname && vtksystools::FileIsDirectory(fname))
{
if (!vtksystools::FileExists(std::string(fname) + "/Header", true))
{
return false;
}
if (particleType == nullptr)
{
// may be should check for existence of subdirectories that could
// potentially contain particles?
return true;
}
// now let's confirm it has "particles" directory.
const std::string particles = std::string(fname) + "/" + particleType;
if (vtksystools::FileIsDirectory(particles))
{
const std::string header(particles + "/Header");
if (vtksystools::FileExists(header, /*isFile*/ true))
{
std::ifstream ifp(header.c_str(), std::ios::binary);
if (ifp)
{
std::string header_line;
if (std::getline(ifp, header_line))
{
return (header_line == "Version_Two_Dot_Zero_double" ||
header_line == "Version_Two_Dot_Zero_float");
}
}
}
}
}
return 0;
}
//----------------------------------------------------------------------------
const char* vtkAMReXParticlesReader::GetPlotFileName() const
{
return (this->PlotFileName.empty() ? nullptr : this->PlotFileName.c_str());
}
//----------------------------------------------------------------------------
void vtkAMReXParticlesReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "PlotFileName: " << this->PlotFileName << endl;
if (this->Header)
{
os << indent << "Header: " << endl;
this->Header->PrintSelf(os, indent.GetNextIndent());
}
else
{
os << indent << "Header: nullptr" << endl;
}
os << indent << "PointDataArraySelection: " << endl;
this->PointDataArraySelection->PrintSelf(os, indent.GetNextIndent());
}
//----------------------------------------------------------------------------
int vtkAMReXParticlesReader::RequestInformation(
vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector)
{
// read meta-data to fill up point array selection information.
if (!this->ReadMetaData())
{
return 0;
}
auto outInfo = outputVector->GetInformationObject(0);
outInfo->Set(CAN_HANDLE_PIECE_REQUEST(), 1);
return this->Superclass::RequestInformation(request, inputVector, outputVector);
}
//----------------------------------------------------------------------------
int vtkAMReXParticlesReader::RequestData(
vtkInformation*, vtkInformationVector**, vtkInformationVector* outputVector)
{
if (!this->ReadMetaData())
{
return 0;
}
assert(this->Header);
// we could use a smarter strategy, but for now, we'll stick to a very simply
// distribution strategy: each level is distributed among requested pieces
// in a contiguous fashion.
auto* outInfo = outputVector->GetInformationObject(0);
using sddp = vtkStreamingDemandDrivenPipeline;
int update_piece = 0, update_num_pieces = 1;
if (outInfo->Has(sddp::UPDATE_PIECE_NUMBER()) && outInfo->Has(sddp::UPDATE_NUMBER_OF_PIECES()))
{
update_piece = outInfo->Get(sddp::UPDATE_PIECE_NUMBER());
update_num_pieces = outInfo->Get(sddp::UPDATE_NUMBER_OF_PIECES());
}
vtkMultiBlockDataSet* output = vtkMultiBlockDataSet::GetData(outputVector, 0);
const auto& header = (*this->Header);
// Let's do as many blocks as levels and distribute each level among pieces.
output->SetNumberOfBlocks(header.num_levels);
for (int cc = 0; cc < header.num_levels; ++cc)
{
vtkNew<vtkMultiPieceDataSet> piece;
output->SetBlock(cc, piece);
output->GetMetaData(cc)->Set(
vtkCompositeDataSet::NAME(), (std::string("Level ") + std::to_string(cc)).c_str());
this->ReadLevel(cc, piece, update_piece, update_num_pieces);
}
return 1;
}
//----------------------------------------------------------------------------
bool vtkAMReXParticlesReader::ReadMetaData()
{
if (this->MetaDataMTime > this->PlotFileNameMTime)
{
return true;
}
delete this->Header;
this->Header = nullptr;
if (this->PlotFileName.empty())
{
vtkErrorMacro("PlotFileName must be specified.");
return false;
}
if (this->ParticleType.empty())
{
vtkErrorMacro("ParticleType must be specified.");
return false;
}
const std::string hdrFileName = this->PlotFileName + "/" + this->ParticleType + "/Header";
const auto headerData = ::ReadAndBroadCastFile(hdrFileName, this->Controller);
if (headerData.empty())
{
return false;
}
auto headerPtr = new AMReXParticleHeader();
if (!headerPtr->Parse(headerData))
{
delete headerPtr;
return false;
}
this->Header = headerPtr;
this->Header->PopulatePointArraySelection(this->PointDataArraySelection);
this->MetaDataMTime.Modified();
return true;
}
//----------------------------------------------------------------------------
bool vtkAMReXParticlesReader::ReadLevel(
const int level, vtkMultiPieceDataSet* levelDS, const int piece_idx, const int num_pieces) const
{
assert(level >= 0 && this->Header != nullptr && piece_idx >= 0 && num_pieces >= 1);
auto& header = (*this->Header);
assert(level < header.num_levels);
const int& num_grids = header.grids_per_level[level];
const int quotient = num_grids / num_pieces;
const int remainder = num_grids % num_pieces;
const int start_grid_idx = (piece_idx * quotient) + ((piece_idx < remainder) ? 1 : 0);
const int grids_count = quotient + ((piece_idx < remainder) ? 1 : 0);
levelDS->SetNumberOfPieces(num_grids);
for (int cc = start_grid_idx; cc < start_grid_idx + grids_count; ++cc)
{
vtkNew<vtkPolyData> pd;
if (header.ReadGrid(level, cc, pd, this) == false)
{
vtkGenericWarningMacro("Failed to read grid for level " << level << ", index " << cc);
return false;
}
levelDS->SetPiece(cc, pd);
}
return true;
}
| 29.933009 | 100 | 0.608383 | [
"vector"
] |
51dd177a66211a651ad722e5e923947daccc861d | 8,876 | cpp | C++ | src/ls.cpp | NK-Nikunj/VFMS | d36ff8148dd1fac679a42a3b6655c5bbc220536d | [
"MIT"
] | 1 | 2018-12-27T20:40:22.000Z | 2018-12-27T20:40:22.000Z | src/ls.cpp | NK-Nikunj/VFMS | d36ff8148dd1fac679a42a3b6655c5bbc220536d | [
"MIT"
] | null | null | null | src/ls.cpp | NK-Nikunj/VFMS | d36ff8148dd1fac679a42a3b6655c5bbc220536d | [
"MIT"
] | null | null | null | #include <VFMS/command/realize_command.hpp>
#include <VFMS/command_map.hpp>
#include <VFMS/vfs.hpp>
#include <vector>
#include <string>
#include <unordered_map>
#include <boost/algorithm/string.hpp>
// #include <VFMS/command/ls.hpp>
namespace vfms
{
namespace assets
{
extern void send_error(std::string error_for);
extern void usage(std::string use_for);
}
extern struct command_line::command_stat* process_args(std::vector<std::string> args);
// Currently we support only l and a for short formats
enum ls_options_short
{
l,
a,
};
// Currently we support only show all files and help formats
enum ls_options_long
{
help,
all,
};
std::unordered_map<std::string, ls_options_short> ls_short_tags =
{
{"l", ls_options_short::l},
{"a", ls_options_short::a},
};
std::unordered_map<std::string, ls_options_long> ls_long_tags =
{
{"all", ls_options_long::all},
{"help", ls_options_long::help},
};
struct ls
{
// store the info related to the command
struct command_line::command_stat* obj;
// Storing current folder
vfs* current_folder;
// short tags
bool is_l;
bool is_a;
// long tags
bool is_all;
bool is_help;
ls(vfs* current_folder, struct command_line::command_stat* obj)
{
this -> obj = obj;
this -> current_folder = current_folder;
is_l = false;
is_a = false;
is_all = false;
is_help = false;
}
// Help user with the command usage
void show_help()
{
std::cout << "ls: usage\n"
"ls [OPTION]... [FILE]...\n"
"List information about the FILEs\n"
"\nOptions:\n"
"\t-a, --all\t\tDo not ignore entries starting with .\n"
"\t-l\t\t\tUse long listing format\n"
"\t--help\t\t\tDisplay help text\n";
return;
}
void write_a_l()
{
if(obj -> dir_name.size() == 0)
{
current_folder -> show_hidden_list_content();
}
else if(obj -> dir_name.size() == 1)
{
vfs* get_to_folder =
current_folder -> go_to(obj -> dir_name.at(0));
// check whether an error is raised
if(get_to_folder != nullptr)
get_to_folder -> show_hidden_list_content();
}
else
{
// The command was not provided correctly
assets::send_error("ls");
assets::usage("ls");
return;
}
}
void write_a()
{
if(obj -> dir_name.size() == 0)
{
current_folder -> show_hidden_content();
}
else if(obj -> dir_name.size() == 1)
{
vfs* get_to_folder =
current_folder -> go_to(obj -> dir_name.at(0));
// check whether an error is raised
if(get_to_folder != nullptr)
get_to_folder -> show_hidden_content();
}
else
{
// The command was not provided correctly
assets::send_error("ls");
assets::usage("ls");
return;
}
}
void write_l()
{
if(obj -> dir_name.size() == 0)
{
current_folder -> show_list_content();
}
else if(obj -> dir_name.size() == 1)
{
vfs* get_to_folder =
current_folder -> go_to(obj -> dir_name.at(0));
// check whether an error is raised
if(get_to_folder != nullptr)
get_to_folder -> show_list_content();
}
else
{
// The command was not provided correctly
assets::send_error("ls");
assets::usage("ls");
return;
}
}
void write()
{
if(obj -> dir_name.size() == 0)
{
current_folder -> show_content();
}
else if(obj -> dir_name.size() == 1)
{
vfs* get_to_folder =
current_folder -> go_to(obj -> dir_name.at(0));
// check whether an error is raised
if(get_to_folder != nullptr)
get_to_folder -> show_content();
}
else
{
// The command was not provided correctly
assets::send_error("ls");
assets::usage("ls");
return;
}
}
void process()
{
if(this -> is_help)
{
this -> show_help();
return;
}
if(this -> is_a || this -> is_all)
{
if(this -> is_l)
{
this -> write_a_l();
}
else
{
this -> write_a();
}
}
else if(this -> is_l)
{
this -> write_l();
}
else
{
this -> write();
}
}
};
std::vector<std::string> get_short_tags(std::string args, struct ls& ls_object)
{
std::vector<std::string> null;
if(args.empty())
return null;
std::vector<std::string> short_args;
std::string single_char;
// split about every character
for(auto&& character: args)
{
single_char = character;
short_args.push_back(single_char);
}
// initializing the enum object
ls_options_short tag;
try
{
for(auto&& arg: short_args)
{
tag = ls_short_tags.at(arg);
switch(tag)
{
case l:
ls_object.is_l = true;
break;
case a:
ls_object.is_a = true;
break;
}
}
} catch(...)
{
std::string command = "ls";
assets::send_error(command);
assets::usage(command);
return null;
}
return short_args;
}
void exec_ls(std::vector<std::string> args, vfs* current_folder)
{
struct command_line::command_stat* obj = process_args(args);
if(obj == nullptr)
{
std::string command = "ls";
assets::send_error(command);
assets::usage(command);
return;
}
struct ls ls_object(current_folder, obj);
if(ls_object.obj == nullptr)
{
// The command was not provided correctly
assets::send_error(args.at(0));
assets::usage(args.at(0));
return;
}
else
{
if(!ls_object.obj -> partial_help_tag.empty())
{
// Some short tags can be used in conjunction. We need
// to distinguish them form each other.
std::vector<std::string> short_tags = get_short_tags(ls_object.obj -> partial_help_tag, std::ref(ls_object));
if(short_tags.empty())
return;
}
// initializing the enum object
ls_options_long tag;
try
{ if(!obj -> complete_help_tag.empty())
{
for(auto&& arg: ls_object.obj -> complete_help_tag)
{
tag = ls_long_tags.at(arg);
switch(tag)
{
case all:
ls_object.is_all = true;
break;
case help:
ls_object.is_help = true;
break;
}
}
}
} catch(...)
{
std::string command = "ls";
assets::send_error(command);
assets::usage(command);
return;
}
ls_object.process();
}
}
} | 26.73494 | 125 | 0.423276 | [
"object",
"vector"
] |
51eb35bcb2cdd90a8a9da0aaf02f94b8e546726f | 3,635 | hpp | C++ | include/MultiLibrary/Common/Process.hpp | danielga/multilibrary | 3d1177dd3affa875e06015f5e3e42dda525f3336 | [
"BSD-3-Clause"
] | 2 | 2018-06-22T12:43:57.000Z | 2019-05-31T21:56:27.000Z | include/MultiLibrary/Common/Process.hpp | danielga/multilibrary | 3d1177dd3affa875e06015f5e3e42dda525f3336 | [
"BSD-3-Clause"
] | 1 | 2017-09-09T01:21:31.000Z | 2017-11-12T17:52:56.000Z | include/MultiLibrary/Common/Process.hpp | danielga/multilibrary | 3d1177dd3affa875e06015f5e3e42dda525f3336 | [
"BSD-3-Clause"
] | 1 | 2022-03-30T18:57:41.000Z | 2022-03-30T18:57:41.000Z | /*************************************************************************
* MultiLibrary - https://danielga.github.io/multilibrary/
* A C++ library that covers multiple low level systems.
*------------------------------------------------------------------------
* Copyright (c) 2014-2022, Daniel Almeida
* 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.
*************************************************************************/
#pragma once
#include <MultiLibrary/Common/Export.hpp>
#include <MultiLibrary/Common/NonCopyable.hpp>
#include <MultiLibrary/Common/Pipe.hpp>
#include <string>
#include <vector>
#include <memory>
namespace MultiLibrary
{
/*!
\brief A class that wraps the operating system's process functionality.
*/
class MULTILIBRARY_COMMON_API Process : public NonCopyable
{
public:
enum class Status
{
Unknown = -1,
Running,
Terminated,
Killed
};
/*!
\brief Constructor.
\param path Executable path.
\param args Arguments to send to the executable.
*/
Process( const std::string &path, const std::vector<std::string> &args = std::vector<std::string>( ) );
/*!
\brief Destructor.
The internal process handles are also destroyed.
*/
~Process( );
/*!
\brief Get process status.
\return status of the process
*/
Status GetStatus( ) const;
/*!
\brief Close this process.
\return true if it succeeds, false if it fails.
*/
bool Close( );
/*!
\brief Kill this process.
\deprecated This function is unsafe. Resources might leak.
*/
void Kill( );
/*!
\brief Close the input pipe.
*/
void CloseInput( );
/*!
\brief Get the input stream.
\return Input stream object.
*/
Pipe &Input( );
/*!
\brief Get the output stream.
\return Output stream object.
*/
Pipe &Output( );
/*!
\brief Get the error output stream.
\return Error output stream object.
*/
Pipe &Error( );
/*!
\brief Return the process exit code.
\return Process exit code.
*/
int32_t ExitCode( ) const;
private:
class Handle;
std::unique_ptr<Handle> process;
int32_t exit_code;
Pipe input_pipe;
Pipe output_pipe;
Pipe error_pipe;
};
} // namespace MultiLibrary
| 25.780142 | 104 | 0.678955 | [
"object",
"vector"
] |
51f4df6a98e870282410e14f19b7ab5eed5bb510 | 3,260 | hpp | C++ | http/HttpHandler.hpp | mateuszb/glutenfree | cefd2be7256a94867fdafbd8330cb4c73c6e3e4e | [
"BSD-4-Clause"
] | 1 | 2018-04-03T07:38:58.000Z | 2018-04-03T07:38:58.000Z | http/HttpHandler.hpp | mateuszb/glutenfree | cefd2be7256a94867fdafbd8330cb4c73c6e3e4e | [
"BSD-4-Clause"
] | null | null | null | http/HttpHandler.hpp | mateuszb/glutenfree | cefd2be7256a94867fdafbd8330cb4c73c6e3e4e | [
"BSD-4-Clause"
] | null | null | null | #pragma once
#include <http/request.hpp>
#include <io/ApplicationHandler.hpp>
#include <io/Dispatcher.hpp>
#include <io/Socket.hpp>
#include <map>
#include <memory>
#include <unordered_set>
namespace http
{
using namespace std;
const string make_header(
const uint16_t code,
const string& reason,
const multimap<string, string>& headers,
const size_t content_size);
unique_ptr<vector<uint8_t>> gzip(const string& input);
enum class HttpCode : uint16_t {
HTTP_OK = 200,
HTTP_CREATED = 201,
HTTP_ACCEPTED = 202,
HTTP_NO_CONTENT = 204,
HTTP_RESET_CONTENT = 205,
HTTP_PARTIAL_CONTENT = 206,
HTTP_MOVED_PERMANENTLY = 301,
HTTP_FOUND = 302,
HTTP_SEE_OTHER = 303,
HTTP_NOT_MODIFIED = 304,
HTTP_TEMPORARY_REDIRECT = 307,
HTTP_PERMANENT_REDIRECT = 308,
HTTP_BAD_REQUEST = 400,
HTTP_UNAUTHORIZED = 401,
HTTP_PAYMENT_REQUIRED = 402,
HTTP_FORBIDDEN = 403,
HTTP_NOT_FOUND = 404,
HTTP_METHOD_NOT_ALLOWED = 405,
HTTP_INTERNAL_SERVER_ERROR = 500,
};
class HttpHandler : public io::ApplicationHandler {
public:
struct HostConfig {
unordered_set<string> static_dirs;
unordered_set<string> dynamic_dirs;
};
HttpHandler(
const std::string& hostname,
const io::net::DispatcherPtr& dispatcher,
const io::net::SocketBasePtr& ptr);
virtual unique_ptr<vector<uint8_t>> HandleEvent(
const uint32_t eventMask,
const vector<uint8_t>& input) override;
void register_url(const string& url);
void register_host(
const string& host,
const HostConfig& cfg);
private:
const size_t MAX_HDR_SIZE = 1024;
const size_t MAX_BODY_SIZE = 8192;
size_t idx;
size_t crlf_count;
unique_ptr<vector<uint8_t>> data;
unique_ptr<vector<uint8_t>> request_data;
unique_ptr<http::request> request;
bool full_hdr;
bool full_msg;
map<string, HostConfig> hostmap;
};
class HttpHandlerFactory {
public:
static io::ApplicationHandlerPtr Make(
const std::string& hostname,
io::net::SocketBasePtr socket);
};
class HttpsRedirectorHandler : public io::ApplicationHandler {
public:
HttpsRedirectorHandler(
const std::string& hostname,
const io::net::DispatcherPtr& dispatcher,
const io::net::SocketBasePtr& ptr)
: ApplicationHandler(dispatcher, ptr), targetHost(hostname) {
}
unique_ptr<vector<uint8_t>> HandleEvent(
const uint32_t eventMask,
const vector<uint8_t>& input) override {
ostringstream hostStream;
hostStream << "https://" << targetHost;
multimap<string, string> defhdrs = {
{ "Host", targetHost },
{ "Connection", "close" },
{ "Location", hostStream.str() }
};
const auto hdr = make_header(
uint32_t(HttpCode::HTTP_MOVED_PERMANENTLY),
"Moved Permanently",
defhdrs,
0);
return make_unique<vector<uint8_t>>(hdr.cbegin(), hdr.cend());
}
private:
const string targetHost;
};
class HttpsRedirectorHandlerFactory {
public:
static io::ApplicationHandlerPtr Make(
const std::string& hostname,
io::net::SocketBasePtr socket);
};
}
| 25.46875 | 70 | 0.66319 | [
"vector"
] |
51f817997571b37a67b16aa10f86e7beb1981998 | 37,744 | cpp | C++ | OnlineDB/EcalCondDB/test/LaserSeqToDB.cpp | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | OnlineDB/EcalCondDB/test/LaserSeqToDB.cpp | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | OnlineDB/EcalCondDB/test/LaserSeqToDB.cpp | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #include <time.h>
#include <stdio.h>
#include <cmath>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <cassert>
using namespace std;
#include <TString.h>
#include <TObjString.h>
#include "OnlineDB/EcalCondDB/interface/EcalCondDBInterface.h"
#include "OnlineDB/EcalCondDB/interface/all_lmf_types.h"
#include "OnlineDB/EcalCondDB/interface/RunDat.h"
#include "OnlineDB/EcalCondDB/interface/RunLaserRunDat.h"
// fixme
#include "OnlineDB/EcalCondDB/interface/LMFSeqDat.h"
#include "OnlineDB/EcalCondDB/interface/LMFLaserPulseDat.h"
#include "OnlineDB/EcalCondDB/interface/LMFPrimDat.h"
#include "OnlineDB/EcalCondDB/interface/LMFPnPrimDat.h"
#include "CalibCalorimetry/EcalLaserAnalyzer/interface/ME.h"
#include "CalibCalorimetry/EcalLaserAnalyzer/interface/MEGeom.h"
#include "CalibCalorimetry/EcalLaserAnalyzer/interface/MEEBGeom.h"
#include "CalibCalorimetry/EcalLaserAnalyzer/interface/MEEEGeom.h"
#include "CalibCalorimetry/EcalLaserAnalyzer/interface/MELaserPrim.h"
class CondDBApp
{
public:
CondDBApp( string sid, string user, string pass ) : _debug(0), _insert(true),_run(0), _seq(0), _type(0), _color(0), _t0(0), _t1(0)
{
_location="P5_Co";
_runtype ="TEST"; //???
_gentag ="default"; //???
try
{
if( _debug>0 )
{
cout << "Making connection..." << endl;
cout << "-> sid=" << sid << endl;
cout << "-> user=" << user << endl;
cout << "-> pass=" << pass << endl;
}
econn = new EcalCondDBInterface( sid, user, pass );
}
catch (runtime_error &e )
{
cerr << e.what() << endl;
exit(-1);
}
}
~CondDBApp()
{
delete econn;
}
void init( int irun, int iseq, int type, int color, time_t t0, time_t t1 )
{
_run = irun;
_seq = iseq;
_type = type;
_color = color;
_t0 = t0;
_t1 = t1;
cout << endl;
cout << "--- Transfering Laser Monitoring data to OMDS ---\n";
cout << "--- for run/seq(t0/t1/Dt) "
<< _run << "/" << _seq << "(" << _t0 << "/" << _t1 << "/" << _t1-_t0 << ")" << endl;
// set the RunIOV
setRun();
// set trigger type and color
setTriggerAndColor();
// set the sequence
setSequence();
// set the map of runIOVs
//setMapOfRunIOV();
}
void setRun()
{
LocationDef locdef;
RunTypeDef rundef;
locdef.setLocation(_location);
rundef.setRunType(_runtype);
_runtag.setLocationDef(locdef);
_runtag.setRunTypeDef(rundef);
_runtag.setGeneralTag(_gentag);
run_t run = _run;
if( _debug>0 ) cout << "Fetching run by tag..." << endl;
_runiov = econn->fetchRunIOV(&_runtag, run);
printRunIOV(_runiov);
// get logic id for all ECAL
ecid_allEcal = econn->getEcalLogicID("ECAL");
//
// Laser Run
//
map< EcalLogicID, RunLaserRunDat > dataset;
econn->fetchDataSet( &dataset, &_runiov );
int n_ = dataset.count( ecid_allEcal );
if( n_==0 )
{
if( _debug>0 ) cout << "RunLaserRunDat -- not created yet: create & insert it" << endl;
RunLaserRunDat rd;
rd.setLaserSequenceType("STANDARD");
rd.setLaserSequenceCond("IN_THE_GAP");
dataset[ecid_allEcal]=rd;
if( _debug>0 ) cout << "Inserting LaserRunDat " << flush;
if( _insert )
{
econn->insertDataSet( &dataset, &_runiov );
if( _debug>0 ) cout << "...dummy..." << endl;
}
if( _debug>0 ) cout << "Done." << endl;
}
else
{
if( _debug>0 ) cout << "RunLaserRunDat -- already inserted" << endl;
}
}
void setTriggerAndColor()
{
// Color id : 0 blue - blue laser (440 nm) or blue led
// Color id : 1 green - green (495 nm)
// Color id : 2 red/orange - red laser (706 nm) or orange led
// Color id : 3 IR - infrared (796 nm)
int colorID = _color;
//Trig id : 0 las - laser
//Trig id : 1 led - led
//Trig id : 2 tp - test pulse
//Trig id : 3 ped - pedestal
int trigID = _type;
// LMF Run tag
int tagID = 1;
{
_lmfcol.setConnection(econn->getEnv(), econn->getConn());
_lmfcol.setColor(colorID);
_lmfcol.dump();
//GO _lmfcol.fetchID();
}
{
_lmftrig.setConnection(econn->getEnv(), econn->getConn());
//GO _lmftrig.setByID(trigID);
_lmftrig.setByID(trigID + 1);
_lmftrig.fetchID();
}
{
_lmftag.setConnection( econn->getEnv(), econn->getConn() );
_lmftag.setByID(tagID);
_lmftag.fetchID();
}
}
void setSequence()
{
_lmfseq.setConnection(econn->getEnv(), econn->getConn());
std::map<int, LMFSeqDat> l = _lmfseq.fetchByRunIOV(_runiov);
cout << "Run has " << l.size() << " sequences in database" << endl;
std::map<int, LMFSeqDat>::const_iterator b = l.begin();
std::map<int, LMFSeqDat>::const_iterator e = l.end();
bool ok_(false);
while( b!=e )
{
_lmfseq = b->second;
int iseq_ = (b->second).getSequenceNumber();
if( iseq_ == _seq )
{
ok_ = true;
break;
}
b++;
}
if( !ok_ )
{
LMFSeqDat seq_;
cout << "Sequence does not exist -- create it " << endl;
// seq_.debug();
seq_.setRunIOV( _runiov );
seq_.setSequenceNumber( _seq );
// run times
Tm startTm;
Tm endTm;
uint64_t microsStart = _t0;
uint64_t microsEnd = _t1;
microsStart *= 1000000;
microsEnd *= 1000000;
startTm.setToMicrosTime(microsStart);
endTm.setToMicrosTime(microsEnd);
seq_.setSequenceStart(startTm);
seq_.setSequenceStop(endTm);
seq_.setVersions(1,1);
if( _insert ) {
econn->insertLmfSeq( &seq_ );
}
_lmfseq = seq_;
}
printLMFSeqDat( _lmfseq );
}
void setMapOfRunIOV()
{
LMFRunIOV lmfiov;
lmfiov.setConnection( econn->getEnv(), econn->getConn() );
std::list< LMFRunIOV > iov_l = lmfiov.fetchBySequence( _lmfseq );
std::list<LMFRunIOV>::const_iterator iov_b = iov_l.begin();
std::list<LMFRunIOV>::const_iterator iov_e = iov_l.end();
while( iov_b != iov_e )
{
if( iov_b->getTriggerType()==_lmftrig && iov_b->getColor()==_lmfcol )
{
int ilmr = iov_b->getLmr();
_lmfRunIOV[ilmr] = *iov_b;
}
iov_b++;
}
}
void storeLaserPrimitive( const char* fname, ME::Header header, ME::Settings settings, time_t dt )
{
LMFRunIOV lmfiov;
lmfiov.setConnection( econn->getEnv(), econn->getConn() );
// // Rustine
TString normStr_ = "APD_OVER_PN";
bool useAPDnorm_ = false;
if( useAPDnorm_ ) normStr_ = "APD_OVER_APD";
int table_id_(0);
int id1_(0);
int id2_(0);
int id3_(EcalLogicID::NULLID);
bool ok_(false);
TString channelViewName_;
int logic_id;
// LMF Tag and IOV
int type = settings.type;
int color = settings.wavelength;
assert( type==_type && color==_color );
time_t t_beg = _t0 + dt;
time_t t_end = _t0 + dt + 5; //!!!GHM!!!
int dcc = header.dcc;
int side = header.side;
int ilmr = ME::lmr( dcc, side );
if( existsLMFRunIOV(ilmr) )
{
lmfiov = _lmfRunIOV[ilmr];
}
else
{
LMFRunIOV lmfiov_;
lmfiov_.setConnection(econn->getEnv(), econn->getConn());
lmfiov_.debug();
lmfiov_.startProfiling();
cout << "LMRunIOV not found -- create it " << endl;
// fill the fields
lmfiov_.setLMFRunTag( _lmftag );
lmfiov_.setSequence( _lmfseq );
lmfiov_.setTriggerType( _lmftrig );
lmfiov_.setColor( _lmfcol );
lmfiov_.setLmr( ilmr );
lmfiov_.setSubRunType("test"); // ?
// run times
Tm startTm;
Tm endTm;
uint64_t microsStart = t_beg;
uint64_t microsEnd = t_end;
microsStart *= 1000000;
microsEnd *= 1000000;
startTm.setToMicrosTime(microsStart);
endTm.setToMicrosTime(microsEnd);
lmfiov_.setSubRunStart(startTm);
lmfiov_.setSubRunEnd(endTm);
// insert
if( _insert )
{
econn->insertLmfRunIOV(&lmfiov_);
}
else
{
cout << "fake insert" << endl;
}
// keep in the map
_lmfRunIOV[ilmr] = lmfiov_;
lmfiov = _lmfRunIOV[ilmr];
}
{
printLMFRunIOV( lmfiov );
}
bool isEB = ME::isBarrel( ilmr );
// econn->fetchDataSet( );
// // datasets
// map< EcalLogicID, LMFLaserPrimDat > dataset_prim;
// map< EcalLogicID, LMFLaserPNPrimDat > dataset_pnprim;
// map< EcalLogicID, LMFLaserPulseDat > dataset_pulse;
// Open the ROOT file
TString rootfile( fname );
TDirectory* f = TFile::Open( rootfile );
if( f==0 )
{
cout << "ERROR -- file=" << rootfile << " not found! " << endl;
// abort(); // this must not happen
return;
}
if( _debug>0 )
cout << "File=" << rootfile << " found. " << endl;
TString sep("__");
TString hname, vname;
TString table;
TH2I* i_h;
// LMF Run
// map< EcalLogicID, LMFRunDat > dataset_lmfrun;
table = "LMF_RUN_DAT";
TTree* lmfrun_t = (TTree*) f->Get(table);
map< TString, unsigned int > lmfrun_i;
vname = "LOGIC_ID"; lmfrun_t->SetBranchAddress( vname, &lmfrun_i[vname] );
vname = "NEVENTS"; lmfrun_t->SetBranchAddress( vname, &lmfrun_i[vname] );
vname = "QUALITY_FLAG"; lmfrun_t->SetBranchAddress( vname, &lmfrun_i[vname] );
lmfrun_t->LoadTree( 0 );
lmfrun_t->GetEntry( 0 );
logic_id = (int) lmfrun_i["LOGIC_ID"];
int nevents = (int) lmfrun_i["NEVENTS"];
int flag = (int) lmfrun_i["QUALITY_FLAG"];
if( _debug>0 )
{
cout << "nevents=" << nevents;
cout << "\tquality flag=" << flag;
cout << endl;
}
// build the logicID for the "fanout"
table_id_ = MELaserPrim::iECAL_LMR;
id1_ = 0;
id2_ = 0;
ok_ = MELaserPrim::getViewIds( logic_id, table_id_, id1_, id2_ );
if( !ok_ )
{
cout << "warning -- inconsistent table_id [1] --> " << table_id_ << endl;
table_id_ = MELaserPrim::iECAL_LMR;
}
if( id1_!=ilmr )
{
cout << "warning -- inconsistent id1/lmr " << id1_ << "/" << ilmr << endl;
id1_ = ilmr;
}
// table_id_ = logic_id/1000000;
// assert( table_id_==MELaserPrim::iECAL_LMR );
// id1_ = (logic_id%1000000)/10000;
// id2_ = 0;
// EcalLogicID ecid_lmfrun = econn->getEcalLogicID( "EB_LM_side", id1_, id2_ );
EcalLogicID ecid_lmfrun = econn->getEcalLogicID( "ECAL_LMR", id1_ );
if( _debug ) cout << ecid_lmfrun.getLogicID() << endl;
{
// Set the data
LMFRunDat lmf_lmfrun(econn);
lmf_lmfrun.setLMFRunIOV( lmfiov );
// DOES NOT WORK
lmf_lmfrun.setEvents( ecid_lmfrun, nevents );
lmf_lmfrun.setQualityFlag( ecid_lmfrun, flag );
// WORKS
// vector< float > data(2);
// data[0] = nevents;
// data[1] = flag;
// lmf_lmfrun.setData( ecid_lmfrun, data );
// DOES NOT WORK
// lmf_lmfrun.setData( ecid_lmfrun, string("NEVENTS"), (float) nevents );
if( _insert )
{
econn->insertLmfDat(&lmf_lmfrun);
}
}
//
// Laser Configuration
//
// map< EcalLogicID, LMFLaserConfigDat > dataset_config;
table = "LMF_LASER_CONFIG_DAT";
TTree* config_t = (TTree*) f->Get(table);
map< TString, unsigned int > config_i;
vname = "LOGIC_ID"; config_t->SetBranchAddress( vname, &config_i[vname] );
vname = "WAVELENGTH"; config_t->SetBranchAddress( vname, &config_i[vname] );
vname = "VFE_GAIN"; config_t->SetBranchAddress( vname, &config_i[vname] );
vname = "PN_GAIN"; config_t->SetBranchAddress( vname, &config_i[vname] );
vname = "LSR_POWER"; config_t->SetBranchAddress( vname, &config_i[vname] );
vname = "LSR_ATTENUATOR"; config_t->SetBranchAddress( vname, &config_i[vname] );
vname = "LSR_CURRENT"; config_t->SetBranchAddress( vname, &config_i[vname] );
vname = "LSR_DELAY_1"; config_t->SetBranchAddress( vname, &config_i[vname] );
vname = "LSR_DELAY_2"; config_t->SetBranchAddress( vname, &config_i[vname] );
config_t->LoadTree( 0 );
config_t->GetEntry( 0 );
assert( logic_id == (int) config_i["LOGIC_ID"] );
EcalLogicID ecid_config = econn->getEcalLogicID( ecid_lmfrun.getLogicID() );
// econn->fetchDataSet( &dataset_config, &lmfiov );
// n_ = dataset_config.size();
// if( n_==0 )
// {
// // Set the data
LMFLaserConfigDat lmf_config(econn);
lmf_config.setLMFRunIOV(lmfiov);
lmf_config.setWavelength( ecid_config, (int) config_i["WAVELENGTH"] );
lmf_config.setVFEGain( ecid_config, (int) config_i["VFE_GAIN"] );
lmf_config.setPNGain( ecid_config, (int) config_i["PN_GAIN"] );
lmf_config.setLSRPower( ecid_config, (int) config_i["LSR_POWER"] );
lmf_config.setLSRAttenuator( ecid_config, (int) config_i["LSR_ATTENUATOR"] );
lmf_config.setLSRCurrent( ecid_config, (int) config_i["LSR_CURRENT"] );
lmf_config.setLSRDelay1( ecid_config, (int) config_i["LSR_DELAY_1"] );
lmf_config.setLSRDelay2( ecid_config, (int) config_i["LSR_DELAY_2"] );
if (_insert) {
econn->insertLmfDat(&lmf_config);
}
//
// Laser MATACQ Primitives
//
table = MELaserPrim::lmfLaserName( ME::iLmfLaserPulse, type, color );
TTree* pulse_t = (TTree*) f->Get(table);
map< TString, unsigned int > pulse_i;
map< TString, float > pulse_f;
vname = "LOGIC_ID"; pulse_t->SetBranchAddress( vname, &pulse_i[vname] );
vname = "FIT_METHOD"; pulse_t->SetBranchAddress( vname, &pulse_i[vname] );
vname = "MTQ_AMPL"; pulse_t->SetBranchAddress( vname, &pulse_f[vname] );
vname = "MTQ_TIME"; pulse_t->SetBranchAddress( vname, &pulse_f[vname] );
vname = "MTQ_RISE"; pulse_t->SetBranchAddress( vname, &pulse_f[vname] );
vname = "MTQ_FWHM"; pulse_t->SetBranchAddress( vname, &pulse_f[vname] );
vname = "MTQ_FW20"; pulse_t->SetBranchAddress( vname, &pulse_f[vname] );
vname = "MTQ_FW80"; pulse_t->SetBranchAddress( vname, &pulse_f[vname] );
vname = "MTQ_SLIDING"; pulse_t->SetBranchAddress( vname, &pulse_f[vname] );
pulse_t->LoadTree( 0 );
pulse_t->GetEntry( 0 );
assert( logic_id == (int) pulse_i["LOGIC_ID"] );
EcalLogicID ecid_pulse = econn->getEcalLogicID( ecid_lmfrun.getLogicID() );
// econn->fetchDataSet( &dataset_pulse, &lmfiov );
// n_ = dataset_pulse.size();
// if( n_==0 )
// {
// // Set the data
// LMFLaserPulseDat::setColor( color ); // set the color
LMFLaserPulseDat lmf_pulse(econn);
lmf_pulse.setColor(color);
lmf_pulse.setLMFRunIOV(lmfiov);
lmf_pulse.setFitMethod( ecid_pulse, 0 );
// lmf_pulse.setAmplitude( ecid_pulse, (float) pulse_f["MTQ_AMPL"] );
lmf_pulse.setMTQTime( ecid_pulse, (float) pulse_f["MTQ_TIME"] );
lmf_pulse.setMTQRise( ecid_pulse, (float) pulse_f["MTQ_RISE"] );
lmf_pulse.setMTQFWHM( ecid_pulse, (float) pulse_f["MTQ_FWHM"] );
lmf_pulse.setMTQFW80( ecid_pulse, (float) pulse_f["MTQ_FW80"] );
lmf_pulse.setMTQFW20( ecid_pulse, (float) pulse_f["MTQ_FW20"] );
lmf_pulse.setMTQSliding( ecid_pulse, (float) pulse_f["MTQ_SLIDING"] );
if (_insert) {
econn->insertLmfDat(&lmf_pulse);
}
// Laser Primitives
//
table = MELaserPrim::lmfLaserName( ME::iLmfLaserPrim, type, color );
map< TString, TH2* > h_;
hname = "LOGIC_ID"; h_[hname] = (TH2*) f->Get(table+sep+hname);
hname = "FLAG"; h_[hname] = (TH2*) f->Get(table+sep+hname);
hname = "MEAN"; h_[hname] = (TH2*) f->Get(table+sep+hname);
hname = "RMS"; h_[hname] = (TH2*) f->Get(table+sep+hname);
hname = "M3"; h_[hname] = (TH2*) f->Get(table+sep+hname);
hname = normStr_+"A_MEAN"; h_[hname] = (TH2*) f->Get(table+sep+hname);
hname = normStr_+"A_RMS"; h_[hname] = (TH2*) f->Get(table+sep+hname);
hname = normStr_+"A_M3"; h_[hname] = (TH2*) f->Get(table+sep+hname);
hname = normStr_+"B_MEAN"; h_[hname] = (TH2*) f->Get(table+sep+hname);
hname = normStr_+"B_RMS"; h_[hname] = (TH2*) f->Get(table+sep+hname);
hname = normStr_+"B_M3"; h_[hname] = (TH2*) f->Get(table+sep+hname);
hname = normStr_+"_MEAN"; h_[hname] = (TH2*) f->Get(table+sep+hname);
hname = normStr_+"_RMS"; h_[hname] = (TH2*) f->Get(table+sep+hname);
hname = normStr_+"_M3"; h_[hname] = (TH2*) f->Get(table+sep+hname);
hname = "ALPHA"; h_[hname] = (TH2*) f->Get(table+sep+hname);
hname = "BETA"; h_[hname] = (TH2*) f->Get(table+sep+hname);
hname = "SHAPE_COR"; h_[hname] = (TH2*) f->Get(table+sep+hname);
i_h = (TH2I*) h_["LOGIC_ID"];
TAxis* ax = i_h->GetXaxis();
TAxis* ay = i_h->GetYaxis();
int ixbmin = ax->GetFirst();
int ixbmax = ax->GetLast();
int iybmin = ay->GetFirst();
int iybmax = ay->GetLast();
// LMFLaserPrimDat::setColor( color ); // set the color
if( _debug>0 ) cout << "Filling laser primitive dataset" << endl;
if( _debug>1 )
{
cout << "ixbmin/ixbmax " << ixbmin << "/" << ixbmax << endl;
cout << "iybmin/iybmax " << iybmin << "/" << iybmax << endl;
}
// OK This is new...
// Fetch an ordered list of crystal EcalLogicIds
vector<EcalLogicID> channels_;
TString view_;
int id1_min =EcalLogicID::NULLID;
int id2_min =EcalLogicID::NULLID;
int id3_min =EcalLogicID::NULLID;
int id1_max =EcalLogicID::NULLID;
int id2_max =EcalLogicID::NULLID;
int id3_max =EcalLogicID::NULLID;
int sm_(0);
if( isEB )
{
view_ = "EB_crystal_number";
sm_ = MEEBGeom::smFromDcc( dcc );
id1_min = sm_;
id1_max = sm_;
id2_min = 1;
id2_max = 1700;
}
else
{
view_ = "EE_crystal_number";
id1_min = 1;
if( ME::ecalRegion( ilmr )==ME::iEEM ) id1_min=-1;
id1_max = id1_min;
id2_min = 0;
id2_max = 101;
id3_min = 0;
id3_max = 101;
}
channels_ = econn->getEcalLogicIDSet( view_.Data(),
id1_min, id1_max,
id2_min, id2_max,
id3_min, id3_max,
view_.Data() );
LMFPrimDat laser_(econn, color, "LASER");
laser_.setLMFRunIOV(lmfiov);
laser_.dump();
for( unsigned ii=0; ii<channels_.size(); ii++ )
{
EcalLogicID ecid_prim = channels_[ii];
logic_id = ecid_prim.getLogicID();
id1_ = ecid_prim.getID1();
id2_ = ecid_prim.getID2();
id3_ = ecid_prim.getID3();
int ix_(0);
int iy_(0);
if( isEB )
{
assert( id1_==sm_ );
MEEBGeom::XYCoord xy_ = MEEBGeom::localCoord( id2_ );
ix_ = xy_.first;
iy_ = xy_.second;
}
else
{
ix_ = id2_;
iy_ = id3_;
}
int ixb = ax->FindBin( ix_ );
int iyb = ay->FindBin( iy_ );
int logic_id_ = (int) i_h->GetCellContent( ixb, iyb );
if( logic_id_<=0 )
{
if( _debug>1 )
{
cout << "LogicID(" << view_ << "," << id1_ << "," << id2_ << "," << id3_ << ")=" << logic_id << " --> no entry " << endl;
}
continue;
}
if( _debug>2 )
{
// sanity check
table_id_ = 0;
int jd1_(0);
int jd2_(0);
int jd3_(0);
MELaserPrim::getViewIds( logic_id_, table_id_, jd1_, jd2_ );
int jx_ = (int)ax->GetBinCenter( ixb );
int jy_ = (int)ay->GetBinCenter( iyb );
//int jx_id_(0), jy_id_(0);
if( isEB )
{
if( table_id_!=MELaserPrim::iEB_crystal_number )
{
// cout << "warning -- inconsistent table_id [2] --> " << table_id_ << endl;
table_id_=MELaserPrim::iEB_crystal_number;
}
assert( jd1_>=1 && jd1_<=36 );
if( sm_!=jd1_ )
{
// // cout << "Warning -- inconsistency in SM numbering "
// << jd1_ << "/" << sm_ << " logic_id/id2=" << logic_id_ << "/" << jd2_ << endl;
}
assert( jd2_>=1 && jd2_<=1700 ); // !!!
// MEEBGeom::XYCoord xy_ = MEEBGeom::localCoord( jd2_ );
//jx_id_ = xy_.first;
//jy_id_ = xy_.second;
jd1_ = sm_;
jd2_ = MEEBGeom::crystal_channel( jx_, jy_ );
jd3_ = EcalLogicID::NULLID;
}
else
{
if( table_id_!=MELaserPrim::iEE_crystal_number )
{
// cout << "warning -- inconsistent table_id [3] --> " << table_id_ << endl;
table_id_=MELaserPrim::iEE_crystal_number;
}
//jx_id_ = jd1_;
//jy_id_ = jd2_;
jd1_ = 1;
if( ME::ecalRegion( ilmr )==ME::iEEM ) jd1_=-1;
jd2_ = jx_;
jd3_ = jy_;
}
// if( jx_!=jx_id_ || jy_!=jy_id_ )
// {
// cout << "Warning inconsistency ix=" << jx_ << "/" << jx_id_
// << " iy=" << jy_ << "/" << jy_id_ << endl;
// }
if( jd1_!=id1_ || jd2_!=id2_ || jd3_!=id3_ )
{
cout << "Warning inconsistency "
<< " -- jd1/id1 " << jd1_ << "/" << id1_
<< " -- jd2/id2 " << jd2_ << "/" << id2_
<< " -- jd3/id3 " << jd3_ << "/" << id3_
<< endl;
}
}
if( _debug>1 )
cout << "LogicID(" << view_ << "," << id1_ << "," << id2_ << "," << id3_ << ")=" << logic_id << " --> val(ixb=" << ixb << ",iyb=" << iyb << ")=" << (float) h_["MEAN"] -> GetCellContent( ixb, iyb ) << endl;
// Set the data
cout << "Filling laser_ for " << ecid_prim.getLogicID() << endl;
laser_.setFlag( ecid_prim, (int) h_["FLAG"] -> GetCellContent( ixb, iyb ) );
cout << "Filling laser_ for " << ecid_prim.getLogicID() << endl;
laser_.setMean( ecid_prim, (float) h_["MEAN"] -> GetCellContent( ixb, iyb ) );
cout << "Filling laser_ for " << ecid_prim.getLogicID() << endl;
laser_.setRMS( ecid_prim, (float) h_["RMS"] -> GetCellContent( ixb, iyb ) );
cout << "Filling laser_ for " << ecid_prim.getLogicID() << endl;
laser_.setM3( ecid_prim, (float) h_["M3"] -> GetCellContent( ixb, iyb ) );
cout << "Filling laser_ for " << ecid_prim.getLogicID() << endl;
laser_.setAPDoverAMean( ecid_prim, (float) h_[normStr_+"A_MEAN"] -> GetCellContent( ixb, iyb ) );
cout << "Filling laser_ for " << ecid_prim.getLogicID() << endl;
laser_.setAPDoverARMS( ecid_prim, (float) h_[normStr_+"A_RMS"] -> GetCellContent( ixb, iyb ) );
cout << "Filling laser_ for " << ecid_prim.getLogicID() << endl;
laser_.setAPDoverAM3( ecid_prim, (float) h_[normStr_+"A_M3"] -> GetCellContent( ixb, iyb ) );
cout << "Filling laser_ for " << ecid_prim.getLogicID() << endl;
laser_.setAPDoverBMean( ecid_prim, (float) h_[normStr_+"B_MEAN"] -> GetCellContent( ixb, iyb ) );
cout << "Filling laser_ for " << ecid_prim.getLogicID() << endl;
laser_.setAPDoverBRMS( ecid_prim, (float) h_[normStr_+"B_RMS"] -> GetCellContent( ixb, iyb ) );
cout << "Filling laser_ for " << ecid_prim.getLogicID() << endl;
laser_.setAPDoverBM3( ecid_prim, (float) h_[normStr_+"B_M3"] -> GetCellContent( ixb, iyb ) );
cout << "Filling laser_ for " << ecid_prim.getLogicID() << endl;
laser_.setAPDoverPnMean( ecid_prim, (float) h_[normStr_+"_MEAN"] -> GetCellContent( ixb, iyb ) );
cout << "Filling laser_ for " << ecid_prim.getLogicID() << endl;
laser_.setAPDoverPnRMS( ecid_prim, (float) h_[normStr_+"_RMS"] -> GetCellContent( ixb, iyb ) );
cout << "Filling laser_ for " << ecid_prim.getLogicID() << endl;
laser_.setAPDoverPnM3( ecid_prim, (float) h_[normStr_+"_M3"] -> GetCellContent( ixb, iyb ) );
cout << "Filling laser_ for " << ecid_prim.getLogicID() << endl;
laser_.setAlpha( ecid_prim, (float) h_["ALPHA"] -> GetCellContent( ixb, iyb ) );
cout << "Filling laser_ for " << ecid_prim.getLogicID() << endl;
laser_.setBeta( ecid_prim, (float) h_["BETA"] -> GetCellContent( ixb, iyb ));
cout << "Filling laser_ for " << ecid_prim.getLogicID() << endl;
// laser_.setShapeCorr( ecid_prim, (float) h_["SHAPE_COR"] -> GetCellContent( ixb, iyb ) );
laser_.setShapeCorr( ecid_prim, 0. );
cout << "---- Filling laser_ for " << ecid_prim.getLogicID() << endl;
// // Fill the dataset
// dataset_prim[ecid_prim] = laser_;
}
if( _debug ) cout << "done. " << endl;
//
// Laser PN Primitives
//
table = MELaserPrim::lmfLaserName( ME::iLmfLaserPnPrim, type, color );
TTree* pn_t = (TTree*) f->Get(table);
map< TString, unsigned int > pn_i;
map< TString, float > pn_f;
vname = "LOGIC_ID"; pn_t->SetBranchAddress( vname, &pn_i[vname] );
vname = "FLAG"; pn_t->SetBranchAddress( vname, &pn_i[vname] );
vname = "MEAN"; pn_t->SetBranchAddress( vname, &pn_f[vname] );
vname = "RMS"; pn_t->SetBranchAddress( vname, &pn_f[vname] );
vname = "M3"; pn_t->SetBranchAddress( vname, &pn_f[vname] );
vname = "PNA_OVER_PNB_MEAN"; pn_t->SetBranchAddress( vname, &pn_f[vname] );
vname = "PNA_OVER_PNB_RMS"; pn_t->SetBranchAddress( vname, &pn_f[vname] );
vname = "PNA_OVER_PNB_M3"; pn_t->SetBranchAddress( vname, &pn_f[vname] );
Long64_t pn_n = pn_t->GetEntries();
// LMFLaserPNPrimDat::setColor( color ); // set the color
LMFPnPrimDat pn_(econn, color, "LASER");
pn_.setLMFRunIOV(lmfiov);
for( Long64_t jj=0; jj<pn_n; jj++ )
{
pn_t->LoadTree( jj );
pn_t->GetEntry( jj );
logic_id = (int) pn_i["LOGIC_ID"];
// EcalLogicID ecid_pn = econn->getEcalLogicID( logic_id );
table_id_ = 0;
id1_ = 0;
id2_ = 0;
MELaserPrim::getViewIds( logic_id, table_id_, id1_, id2_ );
if( isEB )
{
if( table_id_!=MELaserPrim::iEB_LM_PN )
{
// cout << "warning -- inconsistent table_id [4] --> " << table_id_ << endl;
table_id_=MELaserPrim::iEB_LM_PN;
}
}
else
{
if( table_id_!=MELaserPrim::iEE_LM_PN )
{
// cout << "warning -- inconsistent table_id [4] --> " << MELaserPrim::channelViewName( table_id_ ) << endl;
table_id_=MELaserPrim::iEE_LM_PN;
}
}
channelViewName_ = MELaserPrim::channelViewName( table_id_ );
EcalLogicID ecid_pn = econn->getEcalLogicID( channelViewName_.Data(), id1_, id2_ );
if( _debug>1 )
cout << "LogicID(" << channelViewName_ << "," << id1_ << "," << id2_ << "," << id3_ << ")=" << ecid_pn.getLogicID() << " --> " << (float) pn_f["MEAN"] << endl;
// // Set the data
// LMFLaserPNPrimDat pn_;
pn_.setFlag( ecid_pn, (int) pn_i["FLAG"] );
pn_.setMean( ecid_pn, (float) pn_f["MEAN"] );
pn_.setRMS( ecid_pn, (float) pn_f["RMS"] );
pn_.setM3( ecid_pn, (float) pn_f["M3"] );
pn_.setPNAoverBMean( ecid_pn, (float) pn_f["PNA_OVER_PNB_MEAN"] );
pn_.setPNAoverBRMS( ecid_pn, (float) pn_f["PNA_OVER_PNB_RMS "] );
pn_.setPNAoverBM3( ecid_pn, (float) pn_f["PNA_OVER_PNB_M3"] );
// // Fill the dataset
// dataset_pnprim[ecid_pn] = pn_;
}
// // Inserting the dataset, identified by iov
if( _debug>0 )
cout << "Inserting _PRIM_DAT and _PN_PRIM_DAT ..." << flush;
if( _insert )
{
// econn->insertDataSet( &dataset_prim, &lmfiov );
// econn->insertDataSet( &dataset_pnprim, &lmfiov );
laser_.debug();
econn->insertLmfDat(&laser_);
econn->insertLmfDat(&pn_);
}
else
{
if( _debug>0 )
cout << ".... dummy.... " << flush;
}
cout << "Done inserting "
<< fname
<< "." << endl;
//close the root file
f->Close();
};
void debug( int dblevel ) { _debug=dblevel; }
void insert( bool insert ) { _insert=insert; }
private:
CondDBApp(); // hidden default constructor
EcalCondDBInterface* econn;
// uint64_t startmicros;
// uint64_t endmicros;
// run_t startrun;
// run_t endrun;
int _debug;
bool _insert;
RunIOV _runiov;
RunTag _runtag;
int _run;
int _seq;
int _type;
int _color;
time_t _t0;
time_t _t1;
LMFColor _lmfcol;
LMFRunTag _lmftag;
LMFTrigType _lmftrig;
LMFSeqDat _lmfseq;
EcalLogicID ecid_allEcal;
std::string _location;
std::string _runtype;
std::string _gentag;
std::map< int, LMFRunIOV > _lmfRunIOV;
bool existsLMFRunIOV( int ilmr )
{
if( _lmfRunIOV.count( ilmr )!=0 )
{
// printLMFRunIOV( _lmfRunIOV[ilmr] );
return true;
}
return false;
}
LMFSeqDat makeSequence( RunIOV* runiov, int iseq )
{
LMFSeqDat lmfseqdat;
lmfseqdat.setRunIOV(*runiov);
lmfseqdat.setSequenceNumber(iseq);
return lmfseqdat;
}
LMFRunIOV makeLMFRunIOV( int subr,
time_t t_beg, time_t t_end )
{
// trick to get the correct Tm objects (from Francesca Cavalleri)
// t_beg and t_end are in number of seconds since the Unix epoch
// transforms them first in nanoseconds (uint64_int)
uint64_t startMuS = (uint64_t) t_beg*1000000;
Tm startTm( startMuS );
uint64_t endMuS = (uint64_t) t_end*1000000;
Tm endTm( endMuS );
LMFRunTag lmftag;
LMFRunIOV lmfiov;
// lmfiov.setLMFRunTag(lmftag);
// lmfiov.setRunIOV(_runiov);
// lmfiov.setSubRunNumber(subr);
// lmfiov.setSubRunType("Standard");
// lmfiov.setSubRunStart( startTm );
// lmfiov.setSubRunEnd( endTm );
// printLMFRunIOV( lmfiov );
// _lmfRunIOV[subr]=lmfiov;
return lmfiov;
}
void printLMFSeqDat( LMFSeqDat& seq ) const
{
RunIOV runiov = seq.getRunIOV();
// int subr = iov.getSubRunNumber();
Tm tm_start( seq.getSequenceStart().microsTime() );
Tm tm_end( seq.getSequenceStop().microsTime() );
cout
<< "> LMFSequence("
<< runiov.getRunNumber() << "/"
<< seq.getSequenceNumber() << ") ";
cout
<< tm_start.str() << " --> "
<< tm_end.str()
<< endl;
}
void printLMFRunIOV( LMFRunIOV& iov ) const
{
LMFSeqDat seq_ = iov.getSequence();
RunIOV runiov = seq_.getRunIOV();
// int subr = iov.getSubRunNumber();
LMFTrigType trig_ = iov.getTriggerType();
LMFColor col_ = iov.getColor();
Tm tm_start( iov.getSubRunStart().microsTime() );
Tm tm_end( iov.getSubRunEnd().microsTime() );
int ilmr = iov.getLmr();
assert( ilmr>0 && ilmr<=92 );
// int iseq, ilmr, type, color;
// decodeSubRunNumber( subr, iseq, ilmr, type, color );
cout
<< ">> LMFRun("
<< runiov.getRunNumber() << "/"
<< seq_.getSequenceNumber();
cout << "/LMR";
if( ilmr<10 ) cout << "0";
cout << ilmr
<< "[" << ME::smName(ilmr) << "]) ";
cout << trig_.getShortName() << "/" << col_.getShortName() << " ";
cout
<< tm_start.str() << " --> "
<< tm_end.str()
<< endl;
//iov.dump();
}
void printRunIOV( RunIOV& iov ) const
{
RunTag tag = iov.getRunTag();
Tm tm_start( iov.getRunStart().microsTime() );
Tm tm_end( iov.getRunEnd().microsTime() );
cout << "RunIOV("
<< iov.getRunNumber() << "/"
<< tag.getGeneralTag() << "/"
<< tag.getLocationDef().getLocation() << "/"
<< tag.getRunTypeDef().getRunType() << ") "
<< tm_start.str() << " --> "
<< tm_end.str()
<< endl;
}
int subRunNumber( int iseq, int ilmr )
{
return 1000000*iseq + 100*ilmr + 10*_type + _color;
}
void decodeSubRunNumber( int subr, int& iseq, int& ilmr, int& type, int& color ) const
{
int subr_ = subr;
iseq = subr_/1000000;
subr_ -= 1000000*iseq;
ilmr = subr_/100;
subr_ -= 100*ilmr;
type = subr_/10;
subr_ -= 10*type;
color = subr_;
}
};
int main (int argc, char* argv[])
{
string sid;
string user;
string pass;
// sqlplus cms_ecal_cond/XXXXX_XXXX@cms_omds_lb
//GHM sid ="cms_omds_lb";
//GHM user ="cms_ecal_cond";
sid ="cmsdevr_lb";
user ="cms_ecal_cond";
pass ="NONE";
int type = ME::iLaser;
int color = ME::iBlue;
int run = 129909;
int lb = 1;
int seq = -1;
int debug = 0;
bool insert = true;
TString path = "/nfshome0/ecallaser/LaserPrim";
TString period = "CRAFT1";
TString seqstr;
time_t trun(0);
time_t t0(0), t1(0);
int tseq(0);
int dt(0);
int lmr(0);
char c;
while ( (c = getopt( argc, argv, "t:c:R:B:s:S:T:D:L:D:d:p:P:w:n" ) ) != EOF )
{
switch (c)
{
case 't': type = atoi( optarg ); break;
case 'c': color = atoi( optarg ); break;
case 'R': run = atoi( optarg ); break;
case 's': seq = atoi( optarg ); break;
case 'T': trun = atol( optarg ); break;
case 'D': tseq = atoi( optarg ); break;
case 'S': seqstr = TString( optarg ); break;
case 'd': debug = atoi( optarg ); break;
case 'P': period = TString( optarg ); break;
case 'p': path = TString( optarg ); break;
case 'w': pass = string( optarg ); break;
case 'n': insert = false; break;
}
}
if( pass=="NONE" )
{
cout << "--- A DB password (writer) must be provided !" << endl;
cout << "Usage: LaserSeqToDB -p <password>" << endl;
return -1;
}
TString mestore = path;
mestore += "/";
mestore += period;
setenv("MESTORE",mestore.Data(),1);
if( seqstr=="" ) return -1;
try
{
CondDBApp app( sid, user, pass );
app.debug( debug );
app.insert( insert );
vector< int > lmrv;
vector< int > dtv;
TObjArray* array_ = seqstr.Tokenize("-");
TObjString* token_(0);
TString str_;
int nTokens_= array_->GetEntries();
if( nTokens_==0 ) return -1;
for( int iToken=0; iToken<nTokens_; iToken++ )
{
token_ = (TObjString*)array_->operator[](iToken);
str_ = token_->GetString();
TObjArray* dum_ = str_.Tokenize("_");
dt = ((TObjString*)dum_->operator[](1))->GetString().Atoi();
TString lmr_ = ((TObjString*)dum_->operator[](0))->GetString();
lmr_.ReplaceAll("LM","00");
lmr_.Remove(TString::kLeading,'0');
lmr = lmr_.Atoi();
// cout << iToken << "->" << str_ << " lmr=" << lmr << " t=" << dt << endl;
lmrv.push_back( lmr );
dtv.push_back( dt );
}
t0 = trun+tseq;
t1 = t0 + dtv.back() + 5;
app.init( run, seq, type, color, t0, t1 );
size_t lmrv_size = lmrv.size();
// size_t lmrv_size = 0;
for( unsigned int ii=0; ii<lmrv_size; ii++ )
{
bool ok=false;
lmr = lmrv[ii];
dt = dtv[ii];
int reg_(0);
int dcc_(0);
int sect_(0);
int side_(0);
ME::regionAndSector( lmr, reg_, sect_, dcc_, side_ );
TString runlistfile = ME::runListName( lmr, type, color );
FILE *test;
test = fopen( runlistfile, "r" );
if(test)
{
fclose( test );
}
else
{
if( debug>0 )
cout << "File " << runlistfile << " not found." << endl;
return(-1);
}
ifstream fin;
fin.open(runlistfile);
// cout << "GHM-- runListFile " << runlistfile << endl;
while( fin.peek() != EOF )
{
string rundir;
long long tsb, tse;
int rr, bb, mpga , mem, pp, ff, dd, evts;
fin >> rundir;
fin >> rr >> bb >> evts >> tsb >> tse >> mpga >> mem >> pp >> ff >> dd;
if( rr!=run ) continue;
time_t t_beg = ME::time_high( tsb );
time_t t_end = ME::time_high( tse );
// cout << "run " << run << " tbeg/tend " << t_beg << "/" << t_end << endl;
int dt0_end = t_end-t0;
int dt1_end = t_end-t1;
int dt0_beg = t_beg-t0;
int dt1_beg = t_beg-t1;
if( dt0_beg*dt1_beg>0 && dt0_end*dt1_end>0 ) continue;
ok = true;
// if( std::abs(bb-lb_)>3 ) continue;
ME::Header header;
header.rundir = rundir;
header.dcc = dcc_;
header.side = side_;
header.run=rr;
header.lb=lb;
header.ts_beg=tsb;
header.ts_end=tse;
header.events=evts;
ME::Settings settings;
settings.type = type;
settings.wavelength = color;
settings.mgpagain=mpga;
settings.memgain=mem;
settings.power=pp;
settings.filter=ff;
settings.delay=dd;
TString fname = ME::rootFileName( header, settings );
FILE *test;
test = fopen( fname, "r" );
if(test)
{
fclose( test );
}
else
{
continue;
}
cout << "STORING LASER PRIMITIVES" << endl;
app.storeLaserPrimitive( fname, header, settings, dt );
cout << "LASER PRIMITIVES STORED" << endl;
break;
}
if( !ok )
{
cout << "Warning -- " << run << "/" << seq
<< " no primitive file found for lmr/dt "
<< lmr << "[" << ME::smName(lmr) << "]/" << dt << endl;
}
}
} catch (exception &e) {
cout << "ERROR: " << e.what() << endl;
} catch (...) {
cout << "Unknown error caught" << endl;
}
return 0;
}
| 31.61139 | 216 | 0.564143 | [
"vector"
] |
51fb52a7c9ecc760ce76df6a5d1b41e84cf05de0 | 3,026 | cpp | C++ | tests/std/tests/P0024R2_parallel_algorithms_equal/test.cpp | oktonion/STL | e2fce45b9ca899f3887b7fa48e24de95859a7b8e | [
"Apache-2.0"
] | 2 | 2021-01-19T02:43:19.000Z | 2021-11-20T05:21:42.000Z | tests/std/tests/P0024R2_parallel_algorithms_equal/test.cpp | tapaswenipathak/STL | 0d75fc5ab6684d4f6239879a6ec162aad0da860d | [
"Apache-2.0"
] | null | null | null | tests/std/tests/P0024R2_parallel_algorithms_equal/test.cpp | tapaswenipathak/STL | 0d75fc5ab6684d4f6239879a6ec162aad0da860d | [
"Apache-2.0"
] | 4 | 2020-04-24T05:04:54.000Z | 2020-05-17T22:48:58.000Z | // Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include <algorithm>
#include <assert.h>
#include <execution>
#include <forward_list>
#include <iterator>
#include <list>
#include <parallel_algorithms_utilities.hpp>
#include <vector>
using namespace std;
using namespace std::execution;
constexpr char one_char = static_cast<char>(1);
const auto my_not_equal_to = [](auto a, auto b) { return a != b; };
template <class T>
void add_example(forward_list<T>& f, T x) {
f.push_front(x);
}
template <class T>
void add_example(list<T>& l, T x) {
l.push_back(x);
}
template <class T>
void add_example(vector<T>& v, T x) {
v.push_back(x);
}
template <template <class...> class Container>
void test_case_equal_parallel(const size_t testSize) {
Container<char> defaults(testSize);
// test each signature:
{
Container<char> ones(testSize, one_char);
assert(equal(par, defaults.begin(), defaults.end(), defaults.begin()));
assert((testSize == 0) == equal(par, defaults.begin(), defaults.end(), ones.begin()));
assert(equal(par, defaults.begin(), defaults.end(), ones.begin(), my_not_equal_to));
assert((testSize == 0) == equal(par, defaults.begin(), defaults.end(), defaults.begin(), my_not_equal_to));
assert(equal(par, defaults.begin(), defaults.end(), defaults.begin(), defaults.end()));
assert((testSize == 0) == equal(par, defaults.begin(), defaults.end(), ones.begin(), ones.end()));
assert(equal(par, defaults.begin(), defaults.end(), ones.begin(), ones.end(), my_not_equal_to));
assert((testSize == 0)
== equal(par, defaults.begin(), defaults.end(), defaults.begin(), defaults.end(), my_not_equal_to));
// test mismatched lengths
add_example(ones, one_char);
assert(!equal(par, defaults.begin(), defaults.end(), ones.begin(), ones.end(), my_not_equal_to));
assert(!equal(par, ones.begin(), ones.end(), defaults.begin(), defaults.end(), my_not_equal_to));
}
// test counterexample positions:
{
Container<char> tmp(testSize);
// testing every possible combo takes too long
#ifdef EXHAUSTIVE
for (char& b : tmp) {
b = one_char;
assert(!equal(par, defaults.begin(), defaults.end(), tmp.begin(), tmp.end()));
b = {};
}
#else // ^^^ EXHAUSTIVE ^^^ // vvv !EXHAUSTIVE vvv
if (testSize != 0) {
auto middle = tmp.begin();
advance(middle, static_cast<ptrdiff_t>(testSize / 2));
*middle = one_char;
assert(!equal(par, defaults.begin(), defaults.end(), tmp.begin(), tmp.end()));
}
#endif // EXHAUSTIVE
}
}
int main() {
parallel_test_case(test_case_equal_parallel<forward_list>);
parallel_test_case(test_case_equal_parallel<list>);
parallel_test_case(test_case_equal_parallel<vector>);
}
| 35.186047 | 116 | 0.61996 | [
"vector"
] |
a4023c5eb333bc4457971d619de07a084f10e5bd | 317 | hpp | C++ | include/coulombSolver.hpp | qacwnfq/coulombSolver | e99a90a62d4c43fbd6fa9f85608585b204ff7af4 | [
"MIT"
] | null | null | null | include/coulombSolver.hpp | qacwnfq/coulombSolver | e99a90a62d4c43fbd6fa9f85608585b204ff7af4 | [
"MIT"
] | null | null | null | include/coulombSolver.hpp | qacwnfq/coulombSolver | e99a90a62d4c43fbd6fa9f85608585b204ff7af4 | [
"MIT"
] | null | null | null | #ifndef COULOMBSOLVER_INCLUDE_COULOMBSOLVER_INCLUDED
#define COULOMBSOLVER_INCLUDE_COULOMBSOLVER_INCLUDED
#include <utility>
#include <vector>
#include "float_t.hpp"
namespace coulombSolver {
std::vector<std::vector<Float_t>>
forces(const std::vector<std::pair<Float_t, std::vector<Float_t>>> &particles);
}
#endif
| 24.384615 | 79 | 0.804416 | [
"vector"
] |
a40cee00b59c3f070bbb11a565285461933be201 | 6,407 | cc | C++ | libwfc/libwfc.cc | yexf/wfc | 1d3bf6fef0fd780165960928c979683698546e4b | [
"MIT"
] | null | null | null | libwfc/libwfc.cc | yexf/wfc | 1d3bf6fef0fd780165960928c979683698546e4b | [
"MIT"
] | null | null | null | libwfc/libwfc.cc | yexf/wfc | 1d3bf6fef0fd780165960928c979683698546e4b | [
"MIT"
] | null | null | null | // Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include <tchar.h>
#include <io.h>
#include <map>
#include <string>
#include "libwfc.h"
#include "cef_app_handler.h"
#include "cef_client_handler.h"
#include "wfc_client_browser.h"
const TCHAR *psztSubProcPath = _T("wfcweb");
#ifndef F_OK
#define F_OK 0
#endif
unsigned int g_uFlag = NORMAL;
std::map<std::string, wfcClientBrowser*> g_mapClientBrowser;
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
DWORD dwCurProcessId = *((DWORD*)lParam);
DWORD dwProcessId = 0;
GetWindowThreadProcessId(hwnd, &dwProcessId);
if (dwProcessId == dwCurProcessId && GetParent(hwnd) == NULL)
{
*((HWND *)lParam) = hwnd;
return FALSE;
}
return TRUE;
}
HWND GetMainWindow()
{
DWORD dwCurrentProcessId = GetCurrentProcessId();
if (!EnumWindows(EnumWindowsProc, (LPARAM)&dwCurrentProcessId))
{
return (HWND)dwCurrentProcessId;
}
return NULL;
}
void QuitMessageLoop(CefRefPtr<CefClient> pClient)
{
if (g_uFlag & SINGLE_THREAD_MSGLOOP) {
CefQuitMessageLoop();
}
else {
::PostMessage(GetMainWindow(), WM_CLOSE, 0, 0);
}
}
static void ConfigSetting(unsigned int uFlag, CefSettings &settings)
{
settings.single_process = uFlag & SINGLE_PROCESS;
settings.multi_threaded_message_loop = !(uFlag & SINGLE_THREAD_MSGLOOP);
settings.windowless_rendering_enabled = uFlag & WINDOW_LESS;
TCHAR path[MAX_PATH] = {0};
TCHAR drive[MAX_PATH] = {0};
TCHAR dir[MAX_PATH] = {0};
TCHAR fname[MAX_PATH] = {0};
TCHAR ext[MAX_PATH] = {0};
::GetModuleFileName(NULL, path, MAX_PATH);
_tsplitpath(path, drive, dir, fname, ext);
wsprintf(path, _T("%s%s%s"), drive, dir, _T("cache"));
if (_taccess(path, F_OK) == 0)
{
CefString(&settings.cache_path).FromWString(path);
}
wsprintf(path, _T("%s%s%s"), drive, dir, psztSubProcPath);
if (_taccess(path, F_OK) == 0)
{
CefString(&settings.browser_subprocess_path).FromWString(path);
}
wsprintf(path, _T("%s%s%s"), drive, dir, _T("Resources"));
if (_taccess(path, F_OK) == 0)
{
CefString(&settings.resources_dir_path).FromWString(path);
wsprintf(path, _T("%s%s%s"), drive, dir, _T("Resources\\debug.log"));
CefString(&settings.log_file).FromWString(path);
}
wsprintf(path, _T("%s%s%s"), drive, dir, _T("Resources\\locales"));
if (_taccess(path, F_OK) == 0)
{
CefString(&settings.locales_dir_path).FromWString(path);
}
CefString(&settings.locale).FromWString(_T("zh-CN"));
}
static void ConfigPlugins(unsigned int uFlag)
{
TCHAR path[MAX_PATH] = {0};
TCHAR drive[MAX_PATH] = {0};
TCHAR dir[MAX_PATH] = {0};
TCHAR fname[MAX_PATH] = {0};
TCHAR ext[MAX_PATH] = {0};
::GetModuleFileName(NULL, path, MAX_PATH);
_tsplitpath(path, drive, dir, fname, ext);
wsprintf(path, _T("%s%s%s"), drive, dir, _T("plugin\\NPSWF32.dll"));
CefRegisterWebPluginCrash(path);
CefRefreshWebPlugins();
}
static void ConfigMsgLoop(unsigned int uFlag)
{
if (uFlag & SINGLE_THREAD_MSGLOOP)
{
// Run the CEF message loop. This will block until CefQuitMessageLoop() is
// called.
CefRunMessageLoop();
// Shut down CEF.
CefShutdown();
}
}
int InitCef(unsigned int uFlag)
{
// Enable High-DPI support on Windows 7 or newer.
CefEnableHighDPISupport();
void* sandbox_info = NULL;
#if defined(CEF_USE_SANDBOX)
// Manage the life span of the sandbox information object. This is necessary
// for sandbox support on Windows. See cef_sandbox_win.h for complete details.
CefScopedSandboxInfo scoped_sandbox;
sandbox_info = scoped_sandbox.sandbox_info();
#endif
// Provide CEF with command-line arguments.
CefMainArgs main_args(NULL);
// SimpleApp implements application-level callbacks for the browser process.
// It will create the first browser instance in OnContextInitialized() after
// CEF has initialized.
CefRefPtr<CefAppHandler> app(new CefAppHandler);
// CEF applications have multiple sub-processes (render, plugin, GPU, etc)
// that share the same executable. This function checks the command-line and,
// if this is a sub-process, executes the appropriate logic.
int exit_code = CefExecuteProcess(main_args, app, sandbox_info);
if (exit_code >= 0) {
// The sub-process has completed so return here.
return exit_code;
}
// Specify CEF global settings here.
CefSettings settings;
g_uFlag = uFlag;
#if !defined(CEF_USE_SANDBOX)
settings.no_sandbox = true;
#endif
ConfigSetting(uFlag, settings);
// Initialize CEF.
CefInitialize(main_args, settings, app.get(), sandbox_info);
ConfigPlugins(uFlag);
ConfigMsgLoop(uFlag);
return 0;
}
void CoInitializeCef()
{
InitCef(NORMAL);
}
void CoUnInitializeCef()
{
CefShutdown();
}
wfcBrowser *CreateBrowser(void *hWnd, const char *pstrUrl, const char *pstrParam, void *pData)
{
return wfcClientBrowser::CreateBrowser((HWND)hWnd, pstrUrl, pstrParam, pData);
}
void DestoryBrowser()
{
std::map<std::string, wfcClientBrowser*>::iterator iter = g_mapClientBrowser.begin();
while (iter != g_mapClientBrowser.end())
{
wfcClientBrowser *pBrowser = iter->second;
delete pBrowser;
++iter;
}
g_mapClientBrowser.clear();
}
wfcClientBrowser *FindBrowser(CefRefPtr<CefClient> pClient)
{
std::map<std::string, wfcClientBrowser*>::iterator iter = g_mapClientBrowser.begin();
while (iter != g_mapClientBrowser.end())
{
wfcClientBrowser *pBrowser = iter->second;
if (pBrowser->hasClient(pClient))
{
return pBrowser;
}
++iter;
}
return NULL;
}
wfcClientBrowser *FindBrowser(const std::string &brId)
{
if (g_mapClientBrowser.find(brId) != g_mapClientBrowser.end()) {
return g_mapClientBrowser[brId];
}
return NULL;
}
HandleContextInit _set_handler(HandleContextInit handle)
{
static HandleContextInit g_handler = NULL;
if (handle != NULL) {
g_handler = handle;
}
return g_handler;
}
void RegAppHandle(HandleContextInit handle)
{
_set_handler(handle);
}
void RunSingleCef(HandleContextInit handle)
{
_set_handler(handle);
InitCef(SINGLE_THREAD_MSGLOOP);
}
void OnContextInit() {
HandleContextInit handler = _set_handler(NULL);
if (handler)
{
handler();
}
}
| 25.939271 | 95 | 0.69705 | [
"render",
"object"
] |
a41471b9c1815ab1e938f4183e57271537295078 | 20,146 | cpp | C++ | test/cl/CountTest/CountTest.cpp | MattPD/Bolt | ada8cb02fccd9001947ebe592edc1d3a6715b0e7 | [
"BSL-1.0"
] | 2 | 2017-02-25T04:38:03.000Z | 2018-04-07T10:44:48.000Z | test/cl/CountTest/CountTest.cpp | MattPD/Bolt | ada8cb02fccd9001947ebe592edc1d3a6715b0e7 | [
"BSL-1.0"
] | null | null | null | test/cl/CountTest/CountTest.cpp | MattPD/Bolt | ada8cb02fccd9001947ebe592edc1d3a6715b0e7 | [
"BSL-1.0"
] | 1 | 2021-03-01T11:16:46.000Z | 2021-03-01T11:16:46.000Z | /***************************************************************************
* Copyright 2012 - 2013 Advanced Micro Devices, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
#define TEST_DOUBLE 0
#define TEST_DEVICE_VECTOR 1
#define TEST_CPU_DEVICE 0
#define GOOGLE_TEST 1
#if (GOOGLE_TEST == 1)
#include "common/stdafx.h"
#include "common/myocl.h"
#include "bolt/cl/count.h"
#include "bolt/cl/functional.h"
#include "bolt/miniDump.h"
#include "bolt/unicode.h"
#include "bolt/cl/device_vector.h"
#include <gtest/gtest.h>
#include <boost/shared_array.hpp>
#include <array>
#include <algorithm>
class testCountIfFloatWithStdVector: public ::testing::TestWithParam<int>{
protected:
int aSize;
public:
testCountIfFloatWithStdVector():aSize(GetParam()){
}
};
BOLT_TEMPLATE_FUNCTOR4(InRange,int,float,double,__int64,
template<typename T>
// Functor for range checking.
struct InRange {
InRange (T low, T high) {
_low=low;
_high=high;
};
bool operator() (const T& value) {
return (value >= _low) && (value <= _high) ;
};
T _low;
T _high;
};
);
//
//BOLT_CREATE_TYPENAME(InRange<int>);
//BOLT_CREATE_CLCODE(InRange<int>, InRange_CodeString);
//BOLT_CREATE_TYPENAME(InRange<float>);
//BOLT_CREATE_CLCODE(InRange<float>, InRange_CodeString);
//BOLT_CREATE_TYPENAME(InRange<double>);
//BOLT_CREATE_CLCODE(InRange<double>, InRange_CodeString);
//BOLT_CREATE_TYPENAME(InRange<__int64>);
//BOLT_CREATE_CLCODE(InRange<__int64>, InRange_CodeString);
//
TEST_P (testCountIfFloatWithStdVector, countFloatValueInRange)
{
bolt::cl::device_vector<float> A(aSize);
bolt::cl::device_vector<float> B(aSize);
for (int i=0; i < aSize; i++) {
A[i] = static_cast<float> (i+1);
B[i] = A[i];
};
size_t stdCount = std::count_if (A.begin(), A.end(), InRange<float>(6,10)) ;
size_t boltCount = bolt::cl::count_if (B.begin(), B.end(), InRange<float>(6,10)) ;
EXPECT_EQ (stdCount, boltCount)<<"Failed as: STD Count = "<<stdCount<<"\nBolt Count = "<<boltCount<<std::endl;
std::cout<<"STD Count = "<<stdCount<<std::endl<<"bolt Count = "<<boltCount<<std::endl;
}
TEST_P (testCountIfFloatWithStdVector, countFloatValueInRange2)
{
bolt::cl::device_vector<float> A(aSize);
bolt::cl::device_vector<float> B(aSize);
for (int i=0; i < aSize; i++) {
A[i] = static_cast<float> (i+1);
B[i] = A[i];
};
size_t stdCount = std::count_if (A.begin(), A.end(), InRange<float>(1,10)) ;
size_t boltCount = bolt::cl::count_if (B.begin(), B.end(), InRange<float>(1,10)) ;
EXPECT_EQ (stdCount, boltCount)<<"Failed as: STD Count = "<<stdCount<<"\nBolt Count = "<<boltCount<<std::endl;
std::cout<<"STD Count = "<<stdCount<<std::endl<<"bolt Count = "<<boltCount<<std::endl;
}
//
//Test case id: 6 (FAILED)
class countFloatValueOccuranceStdVect :public ::testing::TestWithParam<int>{
protected:
int stdVectSize;
public:
countFloatValueOccuranceStdVect():stdVectSize(GetParam()){}
};
TEST_P(countFloatValueOccuranceStdVect, floatVectSearchWithSameValue){
bolt::cl::device_vector<float> stdVect(stdVectSize);
bolt::cl::device_vector<float> boltVect(stdVectSize);
float myFloatValue = 1.23f;
for (int i =0; i < stdVectSize; i++){
stdVect[i] = myFloatValue;
boltVect[i] = stdVect[i];
}
size_t stdCount = std::count(stdVect.begin(), stdVect.end(), myFloatValue);
size_t boltCount = bolt::cl::count(boltVect.begin(), boltVect.end(), myFloatValue);
EXPECT_EQ(stdCount, boltCount)<<"Failed as: \nSTD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
std::cout<<"STD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
}
TEST_P(countFloatValueOccuranceStdVect, floatVectSearchWithSameValue2){
bolt::cl::device_vector<float> stdVect(stdVectSize);
bolt::cl::device_vector<float> boltVect(stdVectSize);
float myFloatValue2 = 9.87f;
for (int i =0; i < stdVectSize; i++){
stdVect[i] = myFloatValue2;
boltVect[i] = stdVect[i];
}
size_t stdCount = std::count(stdVect.begin(), stdVect.end(), myFloatValue2);
size_t boltCount = bolt::cl::count(boltVect.begin(), boltVect.end(), myFloatValue2);
EXPECT_EQ(stdCount, boltCount)<<"Failed as: \nSTD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
std::cout<<"STD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
}
INSTANTIATE_TEST_CASE_P (useStdVectWithFloatValues, countFloatValueOccuranceStdVect, ::testing::Values(1, 100, 1000, 10000, 100000));
//Test case id: 7 (Failed)
class countDoubleValueUsedASKeyInStdVect :public ::testing::TestWithParam<int>{
protected:
int stdVectSize;
public:
countDoubleValueUsedASKeyInStdVect():stdVectSize(GetParam()){}
};
TEST_P(countDoubleValueUsedASKeyInStdVect, doubleVectSearchWithSameValue){
bolt::cl::device_vector<double> stdVect(stdVectSize);
bolt::cl::device_vector<double> boltVect(stdVectSize);
double myDoubleValueAsKeyValue = 1.23456789l;
for (int i =0; i < stdVectSize; i++){
stdVect[i] = myDoubleValueAsKeyValue;
boltVect[i] = stdVect[i];
}
size_t stdCount = std::count(stdVect.begin(), stdVect.end(), myDoubleValueAsKeyValue);
size_t boltCount = bolt::cl::count(boltVect.begin(), boltVect.end(), myDoubleValueAsKeyValue);
EXPECT_EQ(stdCount, boltCount)<<"Failed as: \nSTD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
std::cout<<"STD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
}
TEST_P(countDoubleValueUsedASKeyInStdVect, doubleVectSearchWithSameValue2){
bolt::cl::device_vector<double> stdVect(stdVectSize);
bolt::cl::device_vector<double> boltVect(stdVectSize);
double myDoubleValueAsKeyValue2 = 9.876543210123456789l;
for (int i =0; i < stdVectSize; i++){
stdVect[i] = myDoubleValueAsKeyValue2;
boltVect[i] = stdVect[i];
}
size_t stdCount = std::count(stdVect.begin(), stdVect.end(), myDoubleValueAsKeyValue2);
size_t boltCount = bolt::cl::count(boltVect.begin(), boltVect.end(), myDoubleValueAsKeyValue2);
EXPECT_EQ(stdCount, boltCount)<<"Failed as: \nSTD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
std::cout<<"STD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
}
//test case: 1, test: 1
TEST (testCountIf, intBtwRange)
{
int aSize = 1024;
bolt::cl::device_vector<int> A(aSize);
for (int i=0; i < aSize; i++) {
A[i] = rand() % 10 + 1;
}
std::iterator_traits<bolt::cl::device_vector<int>::iterator>::difference_type stdInRangeCount = std::count_if (A.begin(), A.end(), InRange<int>(1,10)) ;
std::iterator_traits<bolt::cl::device_vector<int>::iterator>::difference_type boltInRangeCount = bolt::cl::count_if (A.begin(), A.end(), InRange<int>(1, 10)) ;
EXPECT_EQ(stdInRangeCount, boltInRangeCount);
}
BOLT_FUNCTOR(UDD,
struct UDD {
int a;
int b;
bool operator() (const UDD& lhs, const UDD& rhs) {
return ((lhs.a+lhs.b) > (rhs.a+rhs.b));
}
bool operator < (const UDD& other) const {
return ((a+b) < (other.a+other.b));
}
bool operator > (const UDD& other) const {
return ((a+b) > (other.a+other.b));
}
bool operator == (const UDD& other) const {
return ((a+b) == (other.a+other.b));
}
bool operator() (const int &x) {
return (x == a || x == b);
}
UDD operator + (const UDD &rhs) const {
UDD tmp = *this;
tmp.a = tmp.a + rhs.a;
tmp.b = tmp.b + rhs.b;
return tmp;
}
UDD()
: a(0),b(0) { }
UDD(int _in)
: a(_in), b(_in +1) { }
};
);
BOLT_TEMPLATE_REGISTER_NEW_TYPE( bolt::cl::detail::CountIfEqual, int, UDD );
BOLT_TEMPLATE_REGISTER_NEW_ITERATOR( bolt::cl::device_vector, int, UDD );
TEST(countFloatValueOccuranceStdVect, MulticoreCountIntTBB){
const int aSize = 1<<24;
std::vector<int> stdInput(aSize);
std::vector<int> tbbInput(aSize);
//bolt::cl::device_vector<int> stdInput(aSize);
//bolt::cl::device_vector<int> tbbInput(aSize);
int myintValue = 2;
for (int i=0; i < aSize; i++) {
stdInput[i] = rand() % 10 + 1;
tbbInput[i] = stdInput[i];
}
bolt::cl::control ctl = bolt::cl::control::getDefault();
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
size_t stdCount = std::count(stdInput.begin(), stdInput.end(), myintValue);
size_t boltCount = bolt::cl::count(ctl, tbbInput.begin(), tbbInput.end(), myintValue);
EXPECT_EQ(stdCount, boltCount)<<"Failed as: \nSTD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
// std::cout<<"STD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
}
TEST(countFloatValueOccuranceStdVect, MulticoreCountFloatTBB){
const int aSize = 1<<24;
std::vector<float> stdInput(aSize);
std::vector<float> tbbInput(aSize);
//bolt::cl::device_vector<int> stdInput(aSize);
//bolt::cl::device_vector<int> tbbInput(aSize);
float myfloatValue = 9.5f;
for (int i=0; i < aSize; i++) {
stdInput[i] = 9.5f;//rand() % 10 + 1;
tbbInput[i] = stdInput[i];
}
bolt::cl::control ctl = bolt::cl::control::getDefault();
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
size_t stdCount = std::count(stdInput.begin(), stdInput.end(), myfloatValue);
size_t boltCount = bolt::cl::count(ctl, tbbInput.begin(), tbbInput.end(), myfloatValue);
EXPECT_EQ(stdCount, boltCount)<<"Failed as: \nSTD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
//std::cout<<"STD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
}
TEST(countFloatValueOccuranceStdVect, MulticoreCountUDDTBB){
const int aSize = 1<<21;
std::vector<UDD> stdInput(aSize);
std::vector<UDD> tbbInput(aSize);
//bolt::cl::device_vector<int> stdInput(aSize);
//bolt::cl::device_vector<int> tbbInput(aSize);
UDD myUDD;
myUDD.a = 3;
myUDD.b = 5;
for (int i=0; i < aSize; i++) {
stdInput[i].a = rand()%10;
stdInput[i].b = rand()%10;
tbbInput[i].a = stdInput[i].a;
tbbInput[i].b = stdInput[i].b;
}
bolt::cl::control ctl = bolt::cl::control::getDefault();
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
size_t stdCount = std::count(stdInput.begin(), stdInput.end(), myUDD);
size_t boltCount = bolt::cl::count(ctl, tbbInput.begin(), tbbInput.end(), myUDD);
EXPECT_EQ(stdCount, boltCount)<<"Failed as: \nSTD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
std::cout<<"STD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
}
TEST(countFloatValueOccuranceStdVect,DeviceCountUDDTBB){
const int aSize = 1<<21;
std::vector<UDD> stdInput(aSize);
UDD myUDD;
myUDD.a = 3;
myUDD.b = 5;
for (int i=0; i < aSize; i++) {
stdInput[i].a = rand()%10;
stdInput[i].b = rand()%10;
}
bolt::cl::device_vector<UDD> tbbInput(stdInput.begin(),stdInput.end());
bolt::cl::control ctl = bolt::cl::control::getDefault();
size_t stdCount = std::count(stdInput.begin(), stdInput.end(), myUDD);
size_t boltCount = bolt::cl::count(ctl, tbbInput.begin(), tbbInput.end(), myUDD);
EXPECT_EQ(stdCount, boltCount)<<"Failed as: \nSTD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
std::cout<<"STD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
}
TEST(countFloatValueOccuranceStdVect, STDCountUDDTBB){
const int aSize = 1<<21;
std::vector<UDD> stdInput(aSize);
std::vector<UDD> tbbInput(aSize);
UDD myUDD;
myUDD.a = 3;
myUDD.b = 5;
for (int i=0; i < aSize; i++) {
stdInput[i].a = rand()%10;
stdInput[i].b = rand()%10;
tbbInput[i].a = stdInput[i].a;
tbbInput[i].b = stdInput[i].b;
}
bolt::cl::control ctl = bolt::cl::control::getDefault();
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
size_t stdCount = std::count(stdInput.begin(), stdInput.end(), myUDD);
size_t boltCount = bolt::cl::count(ctl, tbbInput.begin(), tbbInput.end(), myUDD);
EXPECT_EQ(stdCount, boltCount)<<"Failed as: \nSTD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
std::cout<<"STD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
}
TEST(countFloatValueOccuranceStdVect, MulticoreCountifIntTBB){
const int aSize = 1<<24;
std::vector<int> stdInput(aSize);
int myintValue = 2;
for (int i=0; i < aSize; i++) {
stdInput[i] = rand() % 10 + 1;
//tbbInput[i] = stdInput[i];
}
bolt::cl::device_vector<int> tbbInput(stdInput.begin(),stdInput.end());
bolt::cl::control ctl = bolt::cl::control::getDefault();
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
size_t stdCount = std::count_if(stdInput.begin(), stdInput.end(), InRange<int>(2,10000));
size_t boltCount = bolt::cl::count_if(ctl, tbbInput.begin(), tbbInput.end(), InRange<int>(2,10000));
EXPECT_EQ(stdCount, boltCount)<<"Failed as: \nSTD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
//std::cout<<"STD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
}
TEST(countFloatValueOccuranceStdVect, MulticoreCountifFloatTBB){
const int aSize = 1<<24;
std::vector<float> stdInput(aSize);
std::vector<float> tbbInput(aSize);
//bolt::cl::device_vector<int> stdInput(aSize);
//bolt::cl::device_vector<int> tbbInput(aSize);
float myfloatValue = 9.5f;
for (int i=0; i < aSize; i++) {
stdInput[i] = (rand() % 10 + 1) * 45.f;
tbbInput[i] = stdInput[i];
}
bolt::cl::control ctl = bolt::cl::control::getDefault();
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
size_t stdCount = std::count_if(stdInput.begin(), stdInput.end(), InRange<float>(5.2f,57.2f));
size_t boltCount = bolt::cl::count_if(ctl, tbbInput.begin(), tbbInput.end(), InRange<float>(5.2f,57.2f));
EXPECT_EQ(stdCount, boltCount)<<"Failed as: \nSTD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
//std::cout<<"STD Count = "<<stdCount<<std::endl<<"Bolt Count = "<<boltCount<<std::endl;
}
INSTANTIATE_TEST_CASE_P (useStdVectWithDoubleValues, countDoubleValueUsedASKeyInStdVect, ::testing::Values(1, 100, 1000, 10000, 100000));
INSTANTIATE_TEST_CASE_P (serialFloatValueWithStdVector, testCountIfFloatWithStdVector, ::testing::Values(10, 100, 1000, 10000, 100000));
int main(int argc, char* argv[])
{
::testing::InitGoogleTest( &argc, &argv[ 0 ] );
// Register our minidump generating logic
bolt::miniDumpSingleton::enableMiniDumps( );
int retVal = RUN_ALL_TESTS( );
// Reflection code to inspect how many tests failed in gTest
::testing::UnitTest& unitTest = *::testing::UnitTest::GetInstance( );
unsigned int failedTests = 0;
for( int i = 0; i < unitTest.total_test_case_count( ); ++i )
{
const ::testing::TestCase& testCase = *unitTest.GetTestCase( i );
for( int j = 0; j < testCase.total_test_count( ); ++j )
{
const ::testing::TestInfo& testInfo = *testCase.GetTestInfo( j );
if( testInfo.result( )->Failed( ) )
++failedTests;
}
}
// Print helpful message at termination if we detect errors, to help users figure out what to do next
if( failedTests )
{
bolt::tout << _T( "\nFailed tests detected in test pass; please run test again with:" ) << std::endl;
bolt::tout << _T( "\t--gtest_filter=<XXX> to select a specific failing test of interest" ) << std::endl;
bolt::tout << _T( "\t--gtest_catch_exceptions=0 to generate minidump of failing test, or" ) << std::endl;
bolt::tout << _T( "\t--gtest_break_on_failure to debug interactively with debugger" ) << std::endl;
bolt::tout << _T( "\t (only on googletest assertion failures, not SEH exceptions)" ) << std::endl;
}
std::cout << "Test Completed. Press Enter to exit.\n .... ";
getchar();
return retVal;
}
#else
#include "stdafx.h"
#include <vector>
#include <algorithm>
#include <bolt/cl/count.h>
//Count with a vector input
void testCount1(int aSize)
{
bolt::cl::device_vector<int> A(aSize);
for (int i=0; i < aSize; i++) {
A[i] = i+1;
};
bolt::cl::count (A.begin(), A.end(), 37);
};
// Count with an array input:
void testCount2()
{
const int aSize = 13;
int A[aSize] = {0, 10, 42, 55, 13, 13, 42, 19, 42, 11, 42, 99, 13};
size_t count42 = bolt::cl::count (A, A+aSize, 42);
size_t count13 = bolt::cl::count (A, A+aSize, 13);
bolt::cl::control::getDefault().debug(bolt::cl::control::debug::Compile);
std::cout << "Count42=" << count42 << std::endl;
std::cout << "Count13=" << count13 << std::endl;
std::cout << "Count7=" << bolt::cl::count (A, A+aSize, 7) << std::endl;
std::cout << "Count10=" << bolt::cl::count (A, A+aSize, 10) << std::endl;
};
// This breaks the BOLT_CODE_STRING macro - need to move to a #include file or replicate the code.
std::string InRange_CodeString =
BOLT_CODE_STRING(
template<typename T>
// Functor for range checking.
struct InRange {
InRange (T low, T high) {
_low=low;
_high=high;
};
bool operator() (const T& value) {
//printf("Val=%4.1f, Range:%4.1f ... %4.1f\n", value, _low, _high);
return (value >= _low) && (value <= _high) ;
};
T _low;
T _high;
};
);
BOLT_CREATE_TYPENAME(InRange<int>);
BOLT_CREATE_CLCODE(InRange<int>, InRange_CodeString);
BOLT_CREATE_TYPENAME(InRange<float>);
BOLT_CREATE_CLCODE(InRange<float>, InRange_CodeString);
void testCountIf(int aSize)
{
bolt::cl::device_vector<float> A(aSize);
bolt::cl::device_vector<float> B(aSize);
for (int i=0; i < aSize; i++) {
A[i] = static_cast<float> (i+1);
B[i] = A[i];
};
std::cout << "STD Count7..15=" << std::count_if (A.begin(), A.end(), InRange<float>(7,15)) << std::endl;
std::cout << "BOLT Count7..15=" << bolt::cl::count_if (B.begin(), B.end(), InRange<float>(7,15)) << std::endl;
}
void test_bug(int aSize)
{
//int aSize = 1024;
bolt::cl::device_vector<int> A(aSize);
bolt::cl::device_vector<int> B(aSize);
for (int i=0; i < aSize; i++) {
A[i] = rand() % 10 + 1;
B[i] = A[i];
}
int stdInRangeCount = std::count_if (A.begin(), A.end(), InRange<int>(1,10)) ;
int boltInRangeCount = bolt::cl::count_if (B.begin(), B.end(), InRange<int>(1, 10)) ;
std:: cout << stdInRangeCount << " " << boltInRangeCount << "\n";
//std::cout << "STD Count7..15=" << std::count_if (A.begin(), A.end(), InRange<float>(7,15)) << std::endl;
//std::cout << "BOLT Count7..15=" << bolt::cl::count_if (A.begin(), A.end(), InRange<float>(7,15), InRange_CodeString) << std::endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
testCount1(100);
testCount2();
testCountIf(1024);
test_bug(1024);
return 0;
}
#endif | 34.030405 | 161 | 0.624342 | [
"vector"
] |
a4160b8709552a807b0eff690f770f1de2698c45 | 1,959 | cpp | C++ | src/atcoder/abc107/abc107_b/main_2.cpp | kzmsh/compete | 5cbe8062689a10bd81c97612b800fd434d93aa3f | [
"MIT"
] | null | null | null | src/atcoder/abc107/abc107_b/main_2.cpp | kzmsh/compete | 5cbe8062689a10bd81c97612b800fd434d93aa3f | [
"MIT"
] | null | null | null | src/atcoder/abc107/abc107_b/main_2.cpp | kzmsh/compete | 5cbe8062689a10bd81c97612b800fd434d93aa3f | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using i32 = int32_t;
using i64 = int64_t;
using u32 = uint32_t;
using u64 = uint64_t;
using f32 = float;
using f64 = double;
template<typename T>
bool choose_min(T &min, const T &value) {
if (min > value) {
min = value;
return true;
}
return false;
}
template<typename T>
bool choose_max(T &max, const T &value) {
if (max < value) {
max = value;
return true;
}
return false;
}
template<typename T, typename = enable_if_t<is_integral_v<T>>>
bool is_prime(const T &integer) {
if (integer == 2) {
return true;
}
if (integer <= 1 || integer % 2 == 0) {
return false;
}
for (int v = 3; v <= sqrt(integer); v += 2) {
if (integer % v == 0) {
return false;
}
}
return true;
}
void run();
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
run();
}
void run() {
i32 H, W;
cin >> H >> W;
vector<vector<char>> f(H, vector<char>(W));
for (i32 i = 0; i < H; i++) {
for (i32 j = 0; j < W; j++) {
cin >> f[i][j];
}
}
map<i32, bool> skip_y, skip_x;
for (i32 i = 0; i < H; i++) {
bool skip = true;
for (i32 j = 0; j < W; j++) {
if (f[i][j] != '.') {
skip = false;
}
}
if (skip) {
skip_y[i] = true;
}
}
for (i32 i = 0; i < W; i++) {
bool skip = true;
for (i32 j = 0; j < H; j++) {
if (f[j][i] != '.') {
skip = false;
}
}
if (skip) {
skip_x[i] = true;
}
}
for (i32 i = 0; i < H; i++) {
if (skip_y[i]) {
continue;
}
for (i32 j = 0; j < W; j++) {
if (skip_x[j]) {
continue;
}
cout << f[i][j];
}
cout << endl;
}
}
| 18.657143 | 62 | 0.416029 | [
"vector"
] |
a41b971a6b39e94d84704046d5e891bde0c1c379 | 2,605 | cpp | C++ | engine/src/math/utils.cpp | olavim/apparitor | b468c49c6d826326d7dfec542a9ed042c60a443a | [
"MIT"
] | null | null | null | engine/src/math/utils.cpp | olavim/apparitor | b468c49c6d826326d7dfec542a9ed042c60a443a | [
"MIT"
] | null | null | null | engine/src/math/utils.cpp | olavim/apparitor | b468c49c6d826326d7dfec542a9ed042c60a443a | [
"MIT"
] | null | null | null | #include <GL/glew.h>
#include <math.h>
#include <stdio.h>
#include "utils.hpp"
namespace apr = apparator;
void apr::printVec(const apr::Vector3 &vec) {
printf("%f, %f, %f\n", vec[0], vec[1], vec[2]);
}
void apr::printVec(const apr::Vector4 &vec) {
printf("%f, %f, %f, %f\n", vec[0], vec[1], vec[2], vec[3]);
}
void apr::printMat(const apr::Matrix4 &mat) {
apr::printVec(apr::Vector4(mat.m[0], mat.m[4], mat.m[8], mat.m[12]));
apr::printVec(apr::Vector4(mat.m[1], mat.m[5], mat.m[9], mat.m[13]));
apr::printVec(apr::Vector4(mat.m[2], mat.m[6], mat.m[10], mat.m[14]));
apr::printVec(apr::Vector4(mat.m[3], mat.m[7], mat.m[11], mat.m[15]));
printf("\n");
}
float apr::radians(const float angle) {
return static_cast<float>(M_PI / 180.0f) * angle;
}
float apr::dot(const apr::Vector3 &a, const apr::Vector3 &b) {
return (a[0] * b[0]) + (a[1] * b[1]) + (a[2] * b[2]);
}
apr::Vector3 apr::cross(const apr::Vector3 &a, const apr::Vector3 &b) {
return apr::Vector3(
(a[1] * b[2]) - (a[2] * b[1]),
(a[2] * b[0]) - (a[0] * b[2]),
(a[0] * b[1]) - (a[1] * b[0])
);
}
apr::Vector4 apr::normalize(const apr::Vector4 &vector) {
float mag = vector.magnitude();
return apr::Vector4(
vector[0] / mag,
vector[1] / mag,
vector[2] / mag,
vector[3] / mag
);
}
apr::Vector3 apr::normalize(const apr::Vector3 &vector) {
float mag = vector.magnitude();
if (mag < 2e-30) {
return apr::Vector3(vector);
}
return apr::Vector3(
vector[0] / mag,
vector[1] / mag,
vector[2] / mag
);
}
apr::Matrix4 apr::perspective(float fov, float aspect, float near, float far) {
return apr::Matrix4(
1 / (aspect * tanf(fov / 2)), 0, 0, 0,
0, 1 / tanf(fov / 2), 0, 0,
0, 0, -(far + near) / (far - near), -1,
0, 0, -(2 * far * near) / (far - near), 0
);
}
apr::Matrix4 apr::ortographic(float left, float right, float bottom, float top, float near, float far) {
return apr::Matrix4(
2 / (right - left), 0, 0, -(right + left) / (right - left),
0, 2 / (top - bottom), 0, -(top + bottom) / (top - bottom),
0, 0, -2 / (far - near), -(far + near) / (far - near),
0, 0, 0, 1
);
}
apr::Matrix4 apr::lookAt(const apr::Vector3 &eye, const apr::Vector3 &target, const apr::Vector3 &up) {
apr::Vector3 zAxis = apr::normalize(eye - target);
apr::Vector3 xAxis = apr::normalize(apr::cross(apr::normalize(up), zAxis));
apr::Vector3 yAxis = apr::cross(zAxis, xAxis);
zAxis *= -1;
return apr::Matrix4(
xAxis[0], yAxis[0], zAxis[0], 0,
xAxis[1], yAxis[1], zAxis[1], 0,
xAxis[2], yAxis[2], zAxis[2], 0,
-apr::dot(xAxis, eye), -apr::dot(yAxis, eye), -apr::dot(zAxis, eye), 1
);
}
| 26.85567 | 104 | 0.585797 | [
"vector"
] |
a421f75b947f38b3c687901376fc3cf4797ab390 | 7,496 | cc | C++ | src/Thread.cc | libinqi/idr-routon | 921f0dc044a0815c3df0a5df6600b5443fc6fd98 | [
"MIT"
] | 4 | 2018-07-13T15:39:09.000Z | 2021-02-26T08:29:07.000Z | src/Thread.cc | libinqi/idr-decard | 28d5993724c8500e70482c2f178cc1a5d7fedc81 | [
"MIT"
] | 3 | 2018-08-05T15:03:51.000Z | 2019-11-10T04:29:59.000Z | src/Thread.cc | libinqi/idr-decard | 28d5993724c8500e70482c2f178cc1a5d7fedc81 | [
"MIT"
] | 3 | 2017-11-27T15:20:38.000Z | 2021-03-13T14:58:36.000Z | #include "Thread.h"
Baton *Thread::baton = NULL;
uv_loop_t *Thread::loop = NULL;
void (*Thread::doExecute)() = NULL;
bool Thread::isWaiting = false;
bool Thread::isRan = false;
bool Thread::isDied = false;
static std::string GBKToUTF8(const std::string &strGBK)
{
static std::string strOutUTF8 = "";
WCHAR *str1;
int n = MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, NULL, 0);
str1 = new WCHAR[n];
MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, str1, n);
n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL);
char *str2 = new char[n];
WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL);
strOutUTF8 = str2;
delete[] str1;
str1 = NULL;
delete[] str2;
str2 = NULL;
return strOutUTF8;
}
static std::string UNICODE_to_UTF8(const WCHAR *pSrc, int stringLength)
{
static std::string strOutUTF8 = "";
char *buffer = new char[stringLength + 1];
WideCharToMultiByte(CP_UTF8, NULL, pSrc, wcslen(pSrc), buffer, stringLength, NULL, NULL);
buffer[stringLength] = '\0';
strOutUTF8 = buffer;
delete[] buffer;
const string &delim = " \t";
string r = strOutUTF8.erase(strOutUTF8.find_last_not_of(delim) + 1);
return r.erase(0, r.find_first_not_of(delim));
}
static std::string base64_encode(unsigned char const *bytes_to_encode, unsigned int in_len)
{
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
while (in_len--)
{
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3)
{
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (i = 0; (i < 4); i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for (j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while ((i++ < 3))
ret += '=';
}
return ret;
}
Local<Value> Thread::getObject(Isolate *isolate, Receiver receiver)
{
Local<Object> data = Object::New(isolate);
data->Set(String::NewFromUtf8(isolate, "cardType"), Number::New(isolate, receiver.type));
switch (baton->receiver.type)
{
case ReceiveType::IDCard:
{
data->Set(String::NewFromUtf8(isolate, "name"), String::NewFromUtf8(isolate, GBKToUTF8(receiver.name).c_str()));
data->Set(String::NewFromUtf8(isolate, "gender"), String::NewFromUtf8(isolate, GBKToUTF8(receiver.gender).c_str()));
data->Set(String::NewFromUtf8(isolate, "folk"), String::NewFromUtf8(isolate, GBKToUTF8(receiver.folk).c_str()));
data->Set(String::NewFromUtf8(isolate, "birthDay"), String::NewFromUtf8(isolate, receiver.birthDay));
data->Set(String::NewFromUtf8(isolate, "code"), String::NewFromUtf8(isolate, receiver.code));
data->Set(String::NewFromUtf8(isolate, "address"), String::NewFromUtf8(isolate, GBKToUTF8(receiver.address).c_str()));
data->Set(String::NewFromUtf8(isolate, "agency"), String::NewFromUtf8(isolate, GBKToUTF8(receiver.agency).c_str()));
data->Set(String::NewFromUtf8(isolate, "expireStart"), String::NewFromUtf8(isolate, receiver.expireStart));
data->Set(String::NewFromUtf8(isolate, "expireEnd"), String::NewFromUtf8(isolate, receiver.expireEnd));
break;
}
case ReceiveType::ICCard:
{
std::string cardIdStr = receiver.code;
cardIdStr = cardIdStr.substr(0, 2) + cardIdStr.substr(2, 2) + cardIdStr.substr(4, 2) + cardIdStr.substr(6, 2);
data->Set(String::NewFromUtf8(isolate, "code"), String::NewFromUtf8(isolate, cardIdStr.c_str()));
break;
}
}
return {data};
}
void Thread::callback(uv_async_t *request, int status)
{
Isolate *isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
Baton *baton = static_cast<Baton *>(request->data);
Local<Value> argv[2];
if (!baton->onReceive.IsEmpty() && (baton->state == 0))
{
// argv[0] = Number::New(isolate, baton->receiver.type);
argv[0] = getObject(isolate, baton->receiver);
// argv[1] = baton->receiver.data.;
Local<Function>::New(isolate, baton->onReceive)->Call(isolate->GetCurrentContext()->Global(), 1, argv);
}
if (!baton->onError.IsEmpty() && (baton->state == 1))
{
argv[0] = Number::New(isolate, baton->error.code);
argv[1] = String::NewFromUtf8(isolate, baton->error.message.c_str());
Local<Function>::New(isolate, baton->onError)->Call(isolate->GetCurrentContext()->Global(), 2, argv);
}
}
Thread::Thread()
{
}
void Thread::run(uv_work_t *request)
{
isDied = false;
while (true)
{
try
{
if (isDied)
{
break;
}
uv_mutex_lock(&baton->mutex);
if (baton->isWaiting)
{
uv_cond_wait(&baton->condvar, &baton->mutex);
baton->isWaiting = false;
}
uv_mutex_unlock(&baton->mutex);
doExecute();
Sleep(10);
}
catch (exception &e)
{
cout << "exception: " << e.what() << endl;
}
}
isDied = true;
}
void Thread::stop(uv_work_t *request, int status)
{
isDied = true;
Baton *baton = static_cast<Baton *>(request->data);
uv_close((uv_handle_t *)&baton->asyncRequest, NULL);
}
void Thread::bind(Isolate *isolate, Local<Function> onReceive, Local<Function> onError)
{
baton = new Baton();
baton->onReceive.Reset(isolate, Persistent<Function>::Persistent(isolate, onReceive));
baton->onError.Reset(isolate, Persistent<Function>::Persistent(isolate, onError));
baton->request.data = baton;
loop = uv_default_loop();
uv_async_init(loop, &baton->asyncRequest, (uv_async_cb)callback);
uv_cond_init(&baton->condvar);
uv_mutex_init(&baton->mutex);
}
void Thread::resume(void)
{
if (!isRan)
{
uv_queue_work(loop, &baton->request, run, stop);
uv_run(loop, UV_RUN_NOWAIT);
isRan = true;
}
uv_mutex_lock(&baton->mutex);
uv_cond_signal(&baton->condvar);
uv_mutex_unlock(&baton->mutex);
}
void Thread::suspend(void)
{
uv_mutex_lock(&baton->mutex);
baton->isWaiting = true;
uv_mutex_unlock(&baton->mutex);
}
void Thread::doReceive(Receiver receiver)
{
baton->state = 0;
baton->receiver = receiver;
baton->asyncRequest.data = baton;
uv_async_send(&baton->asyncRequest);
}
void Thread::doError(int code, string message)
{
baton->state = 1;
baton->error.code = code;
baton->error.message = message;
baton->asyncRequest.data = baton;
uv_async_send(&baton->asyncRequest);
}
Thread::~Thread()
{
uv_mutex_destroy(&baton->mutex);
delete baton;
} | 30.348178 | 121 | 0.612193 | [
"object"
] |
a4306ca4ed5e3bbec633e8febfa98e52621f04b5 | 1,619 | cpp | C++ | emulator/src/mame/video/nes.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | 1 | 2022-01-15T21:38:38.000Z | 2022-01-15T21:38:38.000Z | emulator/src/mame/video/nes.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | emulator/src/mame/video/nes.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | // license:BSD-3-Clause
// copyright-holders:Brad Oliver,Fabio Priuli
/***************************************************************************
video/nes.c
Routines to control the unique NES video hardware/PPU.
***************************************************************************/
#include "emu.h"
#include "includes/nes.h"
void nes_state::video_reset()
{
m_ppu->set_vidaccess_callback(ppu2c0x_device::vidaccess_delegate(FUNC(nes_state::nes_ppu_vidaccess),this));
}
void nes_state::video_start()
{
m_last_frame_flip = 0;
}
PALETTE_INIT_MEMBER(nes_state, nes)
{
m_ppu->init_palette(palette, 0);
}
/***************************************************************************
Display refresh
***************************************************************************/
uint32_t nes_state::screen_update_nes(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
// render the ppu
m_ppu->render(bitmap, 0, 0, 0, 0);
// if this is a disk system game, check for the flip-disk key
if ((m_cartslot && m_cartslot->exists() && (m_cartslot->get_pcb_id() == STD_DISKSYS)) // first scenario = disksys in m_cartslot (= famicom)
|| m_disk) // second scenario = disk via fixed internal disk option (fds & famitwin)
{
if (m_io_disksel)
{
// latch this input so it doesn't go at warp speed
if ((m_io_disksel->read() & 0x01) && (!m_last_frame_flip))
{
if (m_disk)
m_disk->disk_flip_side();
else
m_cartslot->disk_flip_side();
m_last_frame_flip = 1;
}
if (!(m_io_disksel->read() & 0x01))
m_last_frame_flip = 0;
}
}
return 0;
}
| 25.698413 | 142 | 0.56084 | [
"render"
] |
a43247e5b05b963bbc33b1b9dff4f2c75a7649a7 | 9,625 | cc | C++ | repobuild/nodes/java_library.cc | chrisvana/repobuild | 5fb7ee8901eef5bc243abb64898f841d85bd699f | [
"BSD-3-Clause"
] | 73 | 2015-01-17T02:06:49.000Z | 2021-10-13T07:38:24.000Z | repobuild/nodes/java_library.cc | chrisvana/repobuild | 5fb7ee8901eef5bc243abb64898f841d85bd699f | [
"BSD-3-Clause"
] | 2 | 2015-01-31T14:25:58.000Z | 2015-05-07T15:04:24.000Z | repobuild/nodes/java_library.cc | chrisvana/repobuild | 5fb7ee8901eef5bc243abb64898f841d85bd699f | [
"BSD-3-Clause"
] | 8 | 2015-02-02T06:30:37.000Z | 2021-03-02T14:15:14.000Z | // Copyright 2013
// Author: Christopher Van Arsdale
#include <algorithm>
#include <set>
#include <string>
#include <vector>
#include "common/log/log.h"
#include "common/strings/path.h"
#include "common/strings/strutil.h"
#include "repobuild/env/input.h"
#include "repobuild/nodes/java_library.h"
#include "repobuild/nodes/util.h"
#include "repobuild/reader/buildfile.h"
using std::vector;
using std::string;
using std::set;
namespace repobuild {
JavaLibraryNode::JavaLibraryNode(const TargetInfo& t,
const Input& i,
DistSource* s)
: Node(t, i, s) {
}
JavaLibraryNode::~JavaLibraryNode() {}
void JavaLibraryNode::Parse(BuildFile* file, const BuildFileNode& input) {
Node::Parse(file, input);
// java_sources
current_reader()->ParseRepeatedFiles("java_sources", &sources_);
ParseInternal(file, input);
}
void JavaLibraryNode::Set(BuildFile* file,
const BuildFileNode& input,
const vector<Resource>& sources) {
Node::Parse(file, input);
sources_ = sources;
ParseInternal(file, input);
}
void JavaLibraryNode::ParseInternal(BuildFile* file,
const BuildFileNode& input) {
// root dir for output class files, which is also a class path down below,
// see Init().
string java_root = current_reader()->ParseSingleDirectory("java_root");
component_.reset(new ComponentHelper("", java_root));
// classpath info.
vector<Resource> java_classpath_dirs;
current_reader()->ParseRepeatedFiles("java_additional_classpaths",
false, // directory need not exist.
&java_classpath_dirs);
for (const Resource& r : java_classpath_dirs) {
java_classpath_.push_back(r.path());
}
java_classpath_.push_back(java_root);
java_classpath_.push_back(strings::JoinPath(Node::input().genfile_dir(),
StripSpecialDirs(java_root)));
java_classpath_.push_back(strings::JoinPath(Node::input().object_dir(),
StripSpecialDirs(java_root)));
std::sort(java_classpath_.begin(), java_classpath_.end(),
[](const string& a, const string& b) -> bool {
return a.size() > b.size();
});
// javac args
current_reader()->ParseRepeatedString("java_local_compile_args",
&java_local_compile_args_);
current_reader()->ParseRepeatedString("java_compile_args", // inherited.
&java_compile_args_);
// jar args
current_reader()->ParseRepeatedString("java_jar_args",
&java_jar_args_);
// Sanity checks.
for (const Resource& source : sources_) {
CHECK(strings::HasSuffix(source.path(), ".java"))
<< "Invalid java source "
<< source << " in target " << target().full_path();
}
}
void JavaLibraryNode::LocalWriteMakeInternal(bool write_user_target,
Makefile* out) const {
// Figure out the set of input files.
ResourceFileSet input_files;
InputDependencyFiles(JAVA, &input_files);
// Compile all .java files at the same time, for efficiency.
WriteCompile(input_files, out);
// Now write user target (so users can type "make path/to/exec|lib").
if (write_user_target) {
ResourceFileSet targets;
for (const Resource& source : sources_) {
targets.Add(ClassFile(source));
}
WriteBaseUserTarget(targets, out);
}
}
void JavaLibraryNode::WriteCompile(const ResourceFileSet& input_files,
Makefile* out) const {
vector<Resource> obj_files;
set<string> directories;
for (const Resource& source : sources_) {
obj_files.push_back(ClassFile(source));
directories.insert(obj_files.back().dirname());
}
// NB: Make has a bug with multiple output files and parallel execution.
// Thus, we use a touchfile and generate a separate rule for each output file.
Resource touchfile = Touchfile("compile");
Makefile::Rule* rule = out->StartRule(
touchfile.path(),
strings::JoinWith(" ",
strings::JoinAll(input_files.files(), " "),
strings::JoinAll(sources_, " ")));
// Mkdir commands.
for (const string d : directories) {
rule->WriteCommand("mkdir -p " + d);
}
// Compile command.
string compile = "javac";
// Collect class paths.
set<string> java_classpath;
IncludeDirs(JAVA, &java_classpath);
// class path.
string include_dirs = strings::JoinWith(
" ",
"-cp ",
strings::JoinWith(":",
input().root_dir(),
input().genfile_dir(),
input().source_dir(),
strings::JoinPath(input().source_dir(),
input().genfile_dir()),
strings::JoinAll(java_classpath, ":")));
// javac compile args.
set<string> compile_args;
CompileFlags(JAVA, &compile_args);
compile_args.insert(java_local_compile_args_.begin(),
java_local_compile_args_.end());
for (const string& f : input().flags("-JC")) {
compile_args.insert(f);
}
rule->WriteUserEcho("Compiling", target().make_path() + " (java)");
rule->WriteCommand("mkdir -p " + ObjectRoot().path());
rule->WriteCommand(strings::JoinWith(
" ",
compile,
"-d " + ObjectRoot().path(),
"-s " + input().genfile_dir(),
strings::JoinAll(compile_args, " "),
include_dirs,
strings::JoinAll(sources_, " ")));
rule->WriteCommand("mkdir -p " + touchfile.dirname());
rule->WriteCommand("touch " + touchfile.path());
out->FinishRule(rule);
// Secondary rules depend on touchfile and make sure each classfile is in
// place.
for (int i = 0; i < obj_files.size(); ++i) {
const Resource& object_file = obj_files[i];
CHECK(strings::HasPrefix(object_file.path(), ObjectRoot().path() + "/"));
string suffix = object_file.path().substr(ObjectRoot().path().size() + 1);
Makefile::Rule* rule = out->StartRule(object_file.path(), touchfile.path());
// Make sure we actually generated all of the object files, otherwise the
// user may have specified the wrong java_out_root.
rule->WriteCommand("if [ ! -f " + object_file.path() + " ]; then " +
"echo \"Class file not generated: "
+ object_file.path() +
", or it was generated in an unexpected location. Make "
"sure java_root is specified correctly or the "
"package name for the object is: " +
strings::ReplaceAll(suffix, "/", ".") +
"\"; exit 1; fi");
rule->WriteCommand("touch " + object_file.path());
out->FinishRule(rule);
}
// ObjectRoot directory rule
rule = out->StartRule(RootTouchfile().path(), strings::JoinAll(obj_files, " "));
rule->WriteCommand("mkdir -p " + RootTouchfile().dirname());
rule->WriteCommand("touch " + RootTouchfile().path());
out->FinishRule(rule);
}
void JavaLibraryNode::LocalLinkFlags(LanguageType lang,
std::set<std::string>* flags) const {
if (lang == JAVA) {
flags->insert(java_jar_args_.begin(), java_jar_args_.end());
}
}
void JavaLibraryNode::LocalCompileFlags(LanguageType lang,
std::set<std::string>* flags) const {
if (lang == JAVA) {
flags->insert(java_compile_args_.begin(), java_compile_args_.end());
}
}
void JavaLibraryNode::LocalIncludeDirs(LanguageType lang,
std::set<std::string>* dirs) const {
dirs->insert(java_classpath_.begin(), java_classpath_.end());
dirs->insert(ObjectRoot().path());
}
void JavaLibraryNode::LocalObjectFiles(LanguageType lang,
ResourceFileSet* files) const {
Node::LocalObjectFiles(lang, files);
for (const Resource& r : sources_) {
files->Add(ClassFile(r));
}
}
void JavaLibraryNode::LocalObjectRoots(LanguageType lang,
ResourceFileSet* dirs) const {
Node::LocalObjectRoots(lang, dirs);
dirs->Add(RootTouchfile());
}
void JavaLibraryNode::LocalDependencyFiles(LanguageType lang,
ResourceFileSet* files) const {
for (const Resource& r : sources_) {
files->Add(r);
}
// Java also needs class files for dependent javac invocations.
LocalObjectFiles(lang, files);
}
Resource JavaLibraryNode::ClassFile(const Resource& source) const {
CHECK(strings::HasSuffix(source.path(), ".java"));
// Strip our leading directories.
string path = StripSpecialDirs(
source.path().substr(0, source.path().size() - 4)) + "class";
for (const string& classpath : java_classpath_) {
if (strings::HasPrefix(path, classpath + "/")) {
path = path.substr(classpath.size() + 1);
break;
}
}
path = GetComponentHelper(path)->RewriteFile(input(), path);
// This file is going under ObjectRoot();
return Resource::FromLocalPath(ObjectRoot().path(), path);
}
Resource JavaLibraryNode::ObjectRoot() const {
return Resource::FromLocalPath(input().object_dir(),
"lib_" + target().make_path());
}
Resource JavaLibraryNode::RootTouchfile() const {
return Resource::FromLocalPath(ObjectRoot().path(), ".dummy.touch");
}
} // namespace repobuild
| 35.127737 | 82 | 0.609247 | [
"object",
"vector"
] |
a433206415e0d895b4862c48df24280a6eb21967 | 615 | cpp | C++ | LeetCodeSolutions/LeetCode_0303.cpp | lih627/python-algorithm-templates | a61fd583e33a769b44ab758990625d3381793768 | [
"MIT"
] | 24 | 2020-03-28T06:10:25.000Z | 2021-11-23T05:01:29.000Z | LeetCodeSolutions/LeetCode_0303.cpp | lih627/python-algorithm-templates | a61fd583e33a769b44ab758990625d3381793768 | [
"MIT"
] | null | null | null | LeetCodeSolutions/LeetCode_0303.cpp | lih627/python-algorithm-templates | a61fd583e33a769b44ab758990625d3381793768 | [
"MIT"
] | 8 | 2020-05-18T02:43:16.000Z | 2021-05-24T18:11:38.000Z | /*
* @lc app=leetcode.cn id=303 lang=cpp
*
* [303] 区域和检索 - 数组不可变
*/
// @lc code=start
class NumArray {
vector<int> prefix;
public:
NumArray(vector<int>& nums) {
for(auto &num: nums){
if(prefix.empty()) prefix.push_back(num);
else prefix.push_back(prefix.back() + num);
}
}
int sumRange(int i, int j) {
if (i) return prefix[j] - prefix[i - 1];
return prefix[j];
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* int param_1 = obj->sumRange(i,j);
*/
// @lc code=end
| 19.83871 | 64 | 0.565854 | [
"object",
"vector"
] |
a433eca54b26188452a20a624fa5887c154736da | 7,772 | cpp | C++ | src/Ypng/PngWriter.cpp | jebreimo/Ypng | 67c9c521b98c9d3c8240be4566b8e7b7758cdd03 | [
"BSD-2-Clause"
] | null | null | null | src/Ypng/PngWriter.cpp | jebreimo/Ypng | 67c9c521b98c9d3c8240be4566b8e7b7758cdd03 | [
"BSD-2-Clause"
] | null | null | null | src/Ypng/PngWriter.cpp | jebreimo/Ypng | 67c9c521b98c9d3c8240be4566b8e7b7758cdd03 | [
"BSD-2-Clause"
] | null | null | null | //****************************************************************************
// Copyright © 2021 Jan Erik Breimo. All rights reserved.
// Created by Jan Erik Breimo on 2021-01-03.
//
// This file is distributed under the BSD License.
// License text is included with the source distribution.
//****************************************************************************
#include "Ypng/PngWriter.hpp"
#include "Ypng/YpngException.hpp"
#include <ostream>
#include <utility>
#include <fstream>
namespace Ypng
{
namespace
{
size_t getPixelComponents(int colorType)
{
switch (colorType)
{
default:
return 1;
case PNG_COLOR_TYPE_GRAY_ALPHA:
return 2;
case PNG_COLOR_TYPE_RGB:
return 3;
case PNG_COLOR_TYPE_RGB_ALPHA:
return 4;
}
}
size_t getPixelSize(const PngInfo& info,
const PngTransform& transform)
{
if (info.bitDepth() == 0)
YPNG_THROW("Bit depth can not be 0.");
size_t componentCount = getPixelComponents(info.colorType());
size_t componentSize = info.bitDepth();
if (componentSize < 8 && componentCount > 1)
YPNG_THROW("Invalid combination of color type and bit depth.");
if (componentSize < 8)
return transform.pixelPacking() ? 8 : componentSize;
if (transform.pixelFiller() && componentCount % 2 == 1)
componentCount++;
return componentCount * componentSize;
}
size_t getRowSize(const PngInfo& info, const PngTransform& transform)
{
return (info.width() * getPixelSize(info, transform) + 7) / 8;
}
extern "C" {
void user_write_data(png_structp png_ptr,
png_bytep data,
png_size_t length)
{
auto stream = static_cast<std::ostream*>(png_get_io_ptr(png_ptr));
stream->write(reinterpret_cast<const char*>(data),
std::streamsize(length));
}
void user_flush_data(png_structp png_ptr)
{
auto stream = static_cast<std::ostream*>(png_get_io_ptr(png_ptr));
stream->flush();
}
}
}
PngWriter::PngWriter() = default;
PngWriter::PngWriter(std::ostream& stream, PngInfo info, PngTransform transform)
: m_Info(std::move(info)),
m_Transform(transform)
{
m_PngPtr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
if (!m_PngPtr)
YPNG_THROW("Can not create PNG struct.");
m_InfoPtr = png_create_info_struct(m_PngPtr);
if (!m_InfoPtr)
YPNG_THROW("Can not create PNG info struct.");
png_set_write_fn(m_PngPtr, &stream, user_write_data, user_flush_data);
}
PngWriter::PngWriter(PngWriter&& obj) noexcept
: m_Info(std::move(obj.m_Info)),
m_Transform(obj.m_Transform),
m_PngPtr(nullptr),
m_InfoPtr(nullptr)
{
std::swap(m_PngPtr, obj.m_PngPtr);
std::swap(m_InfoPtr, obj.m_InfoPtr);
}
PngWriter::~PngWriter()
{
if (m_PngPtr)
{
png_write_flush(m_PngPtr);
png_destroy_write_struct(&m_PngPtr, &m_InfoPtr);
}
}
PngWriter& PngWriter::operator=(PngWriter&& obj) noexcept
{
if (m_PngPtr)
png_destroy_write_struct(&m_PngPtr, &m_InfoPtr);
m_Info = std::move(obj.m_Info);
m_Transform = obj.m_Transform;
std::swap(m_PngPtr, obj.m_PngPtr);
std::swap(m_InfoPtr, obj.m_InfoPtr);
return *this;
}
PngWriter::operator bool() const
{
return m_PngPtr && m_InfoPtr;
}
void PngWriter::writeInfo()
{
assertIsValid();
if (setjmp(png_jmpbuf(m_PngPtr)))
{
png_destroy_write_struct(&m_PngPtr, &m_InfoPtr);
YPNG_THROW("Error while setting PNG info values.");
}
png_set_IHDR(m_PngPtr, m_InfoPtr, m_Info.width(), m_Info.height(),
m_Info.bitDepth(), m_Info.colorType(),
m_Info.interlaceType(), m_Info.compressionMethod(),
m_Info.filterMethod());
if (m_Info.gamma())
png_set_gAMA(m_PngPtr, m_InfoPtr, *m_Info.gamma());
if (!m_Info.texts().empty())
{
png_set_text(m_PngPtr, m_InfoPtr,
m_Info.texts().data(), int(m_Info.texts().size()));
}
if (m_Transform.invertAlpha())
png_set_invert_alpha(m_PngPtr);
if (setjmp(png_jmpbuf(m_PngPtr)))
{
png_destroy_write_struct(&m_PngPtr, &m_InfoPtr);
YPNG_THROW("Error while writing PNG info.");
}
png_write_info(m_PngPtr, m_InfoPtr);
}
void PngWriter::write(const void* image, size_t size)
{
auto rowSize = getRowSize(m_Info, m_Transform);
if (size != m_Info.height() * rowSize)
YPNG_THROW("Incorrect image size.");
std::vector<unsigned char*> rows;
rows.reserve(m_Info.height());
auto ucImage = static_cast<unsigned char*>(const_cast<void*>(image));
for (size_t i = 0; i < m_Info.height(); ++i)
rows.push_back(ucImage + i * rowSize);
assertIsValid();
if (setjmp(png_jmpbuf(m_PngPtr)))
{
png_destroy_write_struct(&m_PngPtr, &m_InfoPtr);
YPNG_THROW("Error while writing PNG image data.");
}
png_write_image(m_PngPtr, rows.data());
}
void PngWriter::writeRows(const void* rows[], uint32_t count,
size_t rowSize)
{
if (rowSize != getRowSize(m_Info, m_Transform))
YPNG_THROW("Incorrect row size.");
assertIsValid();
if (setjmp(png_jmpbuf(m_PngPtr)))
{
png_destroy_write_struct(&m_PngPtr, &m_InfoPtr);
YPNG_THROW("Error while writing PNG rows.");
}
png_write_rows(
m_PngPtr,
reinterpret_cast<unsigned char**>(const_cast<void**>(rows)),
count);
}
void PngWriter::writeRow(const void* row, size_t size)
{
if (size != getRowSize(m_Info, m_Transform))
YPNG_THROW("Incorrect row size.");
assertIsValid();
if (setjmp(png_jmpbuf(m_PngPtr)))
{
png_destroy_write_struct(&m_PngPtr, &m_InfoPtr);
YPNG_THROW("Error while writing PNG row.");
}
png_write_row(
m_PngPtr,
reinterpret_cast<unsigned char*>(const_cast<void*>(row)));
}
void PngWriter::writeEnd()
{
assertIsValid();
png_write_end(m_PngPtr, nullptr);
}
void PngWriter::assertIsValid() const
{
if (!m_InfoPtr || !m_PngPtr)
YPNG_THROW("");
}
void writePng(std::ostream& stream,
const void* image, size_t imageSize,
PngInfo options, PngTransform transform)
{
PngWriter writer(stream, std::move(options), transform);
writer.writeInfo();
writer.write(image, imageSize);
writer.writeEnd();
}
void writePng(const std::string& fileName,
const void* image, size_t imageSize,
PngInfo options, PngTransform transform)
{
std::ofstream stream(fileName);
if (!stream)
YPNG_THROW("Can not create " + fileName);
writePng(stream, image, imageSize,
std::move(options),
transform);
}
}
| 31.088 | 93 | 0.551724 | [
"vector",
"transform"
] |
bfa17e789d4c76a7cc6f95aea56f437ff2068fc4 | 521 | cpp | C++ | Week3/rotate.cpp | AkashRajpurohit/leetcode-october-2020-challenge | 4bf49f2ac1d51c049d166a0bf07b3ae11552f1e7 | [
"MIT"
] | 1 | 2020-10-29T11:21:58.000Z | 2020-10-29T11:21:58.000Z | Week3/rotate.cpp | AkashRajpurohit/leetcode-october-2020-challenge | 4bf49f2ac1d51c049d166a0bf07b3ae11552f1e7 | [
"MIT"
] | null | null | null | Week3/rotate.cpp | AkashRajpurohit/leetcode-october-2020-challenge | 4bf49f2ac1d51c049d166a0bf07b3ae11552f1e7 | [
"MIT"
] | null | null | null | class Solution {
private:
void reverse(vector<int>& nums, int start, int end) {
int tmp;
while(start < end) {
tmp = nums[start];
nums[start] = nums[end];
nums[end] = tmp;
start++;
end--;
}
}
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
k = k % n;
reverse(nums, 0, n - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, n - 1);
}
}; | 21.708333 | 57 | 0.408829 | [
"vector"
] |
bfa32ab02ea8f85eef26c5983768cbd0c07c1203 | 1,699 | cpp | C++ | CLPERM.cpp | NithinSethumadhavan/Competitive-Programming | 8eb31a795bb3f371b09a3a6f341e8925bb4113e2 | [
"MIT"
] | null | null | null | CLPERM.cpp | NithinSethumadhavan/Competitive-Programming | 8eb31a795bb3f371b09a3a6f341e8925bb4113e2 | [
"MIT"
] | null | null | null | CLPERM.cpp | NithinSethumadhavan/Competitive-Programming | 8eb31a795bb3f371b09a3a6f341e8925bb4113e2 | [
"MIT"
] | 10 | 2019-05-21T05:15:36.000Z | 2019-05-21T05:36:26.000Z | #include<bits/stdc++.h>
#define gc getchar
#define pc putchar
#define maxm 100005
#define si(n) scanf("%d",&n)
#define sc(c) scanf("%c",&c)
#define sll(n) scanf("%lld",&n)
#define print(n) printf("%d",n)
#define printll(n) printf("%lld",n)
#define loop(i,j,n) for(int(i)=(j);(i)<(n);++(i))
#define rep(i,n) for(int(i)=0;(i)<(n);++(i))
#define ll long long
#define vi vector<int>
#define vii vector< pair<int,int> >
#define pii pair<int,int>
#define sz(x) (int)x.size()
#define pn pc('\n')
#define mp make_pair
#define fi first
#define se second
#define pb push_back
#define all(x) x.begin(),x.end()
using namespace std;
int n,k;
vi v,w;
void read()
{
v.clear();
w.clear();
cin >> n >> k;
rep(i,k)
{
int x;
cin >> x;
w.pb(x);
}
loop(i,1,n+1)
v.pb(i);
}
void solve()
{
if(k == 0)
{
ll int sum = (n*(n+1))/2;
sum++;
if(sum%2)
cout << "Chef" << endl;
else
cout << "Mom" << endl;
return;
}
for(int i = 0;i<sz(w);++i)
{
for(int j = 0;j<sz(v);++j)
{
if(v[j] == w[i])
{
v[j] = 0;
break;
}
}
}
int res = 1;
for(int i = 0;i<sz(v) && v[i] <= res;++i)
{
if(v[i] == 0)
continue;
res += v[i];
}
if(res%2)
cout << "Chef" << endl;
else
cout << "Mom" << endl;
}
int main()
{
ios_base::sync_with_stdio(false);
int t;
cin >> t;
while(t--)
{
read();
solve();
}
return 0;
}
| 18.67033 | 50 | 0.422013 | [
"vector"
] |
bfa50bc2f11acb723b2badc87cfaaf608bbf66d1 | 10,730 | cpp | C++ | tests/chain_tests/atomicswap/atomicswap_service_tests.cpp | scorum/scorum | 1da00651f2fa14bcf8292da34e1cbee06250ae78 | [
"MIT"
] | 53 | 2017-10-28T22:10:35.000Z | 2022-02-18T02:20:48.000Z | tests/chain_tests/atomicswap/atomicswap_service_tests.cpp | Scorum/Scorum | fb4aa0b0960119b97828865d7a5b4d0409af7876 | [
"MIT"
] | 38 | 2017-11-25T09:06:51.000Z | 2018-10-31T09:17:22.000Z | tests/chain_tests/atomicswap/atomicswap_service_tests.cpp | Scorum/Scorum | fb4aa0b0960119b97828865d7a5b4d0409af7876 | [
"MIT"
] | 27 | 2018-01-08T19:43:35.000Z | 2022-01-14T10:50:42.000Z | #include <boost/test/unit_test.hpp>
#include <scorum/chain/services/atomicswap.hpp>
#include <scorum/chain/services/account.hpp>
#include <scorum/chain/schema/account_objects.hpp>
#include <scorum/chain/schema/atomicswap_objects.hpp>
#include <sstream>
#include <fc/time.hpp>
#include "database_default_integration.hpp"
using namespace database_fixture;
class atomicswap_service_check_fixture : public database_default_integration_fixture
{
public:
atomicswap_service_check_fixture()
: atomicswap_service(db.obtain_service<dbs_atomicswap>())
, account_service(db.account_service())
, public_key(database_integration_fixture::generate_private_key("user private key").get_public_key())
, alice(account_service.create_account(
"alice", "initdelegate", public_key, "", authority(), authority(), authority(), ASSET_NULL_SCR))
, bob(account_service.create_account(
"bob", "initdelegate", public_key, "", authority(), authority(), authority(), ASSET_NULL_SCR))
{
account_service.increase_balance(alice, ALICE_BALANCE);
account_service.increase_balance(bob, BOB_BALANCE);
for (uint32_t ci = 0; ci < SCORUM_ATOMICSWAP_LIMIT_REQUESTED_CONTRACTS_PER_OWNER + 1; ++ci)
{
std::stringstream store;
store << "man" << ci;
account_name_type next_name = store.str();
const account_object& man = account_service.create_account(
next_name, "initdelegate", public_key, "", authority(), authority(), authority(), ASSET_NULL_SCR);
account_service.increase_balance(man, MAN_BALANCE);
people.push_back(next_name);
}
alice_secret_hash = atomicswap::get_secret_hash(ALICE_SECRET);
}
atomicswap_service_i& atomicswap_service;
account_service_i& account_service;
const public_key_type public_key;
const account_object& alice;
const account_object& bob;
using recipients_type = std::vector<account_name_type>;
recipients_type people;
std::string alice_secret_hash;
const std::string ALICE_SECRET = "ab74c5c5";
const asset ALICE_BALANCE = asset(2 * SCORUM_ATOMICSWAP_LIMIT_REQUESTED_CONTRACTS_PER_OWNER + 1, SCORUM_SYMBOL);
const asset BOB_BALANCE = asset(3 * SCORUM_ATOMICSWAP_LIMIT_REQUESTED_CONTRACTS_PER_OWNER + 1, SCORUM_SYMBOL);
const asset ALICE_SHARE_FOR_BOB = asset(2, SCORUM_SYMBOL);
const asset BOB_SHARE_FOR_ALICE = asset(3, SCORUM_SYMBOL);
const std::string MAN_SECRET = ALICE_SECRET;
const asset MAN_BALANCE = asset(SCORUM_ATOMICSWAP_LIMIT_REQUESTED_CONTRACTS_PER_OWNER + 1, SCORUM_SYMBOL);
const asset MAN_SHARE_FOR_BOB = asset(1, SCORUM_SYMBOL);
};
BOOST_FIXTURE_TEST_SUITE(atomicswap_service_create_initiator_check, atomicswap_service_check_fixture)
SCORUM_TEST_CASE(create_initiator_contract_check_balance)
{
BOOST_REQUIRE_EQUAL(alice.balance, ALICE_BALANCE);
BOOST_REQUIRE_NO_THROW(atomicswap_service.create_contract(
atomicswap_contract_initiator, alice, bob, ALICE_SHARE_FOR_BOB, atomicswap::get_secret_hash(ALICE_SECRET)));
BOOST_REQUIRE_EQUAL(alice.balance, ALICE_BALANCE - ALICE_SHARE_FOR_BOB);
}
SCORUM_TEST_CASE(create_initiator_contract_check_get_contracts)
{
BOOST_REQUIRE(atomicswap_service.get_contracts(alice).empty());
BOOST_REQUIRE_NO_THROW(atomicswap_service.create_contract(
atomicswap_contract_initiator, alice, bob, ALICE_SHARE_FOR_BOB, atomicswap::get_secret_hash(ALICE_SECRET)));
BOOST_REQUIRE_EQUAL(atomicswap_service.get_contracts(alice).size(), (size_t)1);
}
SCORUM_TEST_CASE(create_initiator_contract_check_get_contract)
{
std::string secret_hash = atomicswap::get_secret_hash(ALICE_SECRET);
BOOST_REQUIRE_THROW(atomicswap_service.get_contract(alice, bob, secret_hash), fc::exception);
BOOST_REQUIRE_NO_THROW(atomicswap_service.create_contract(atomicswap_contract_initiator, alice, bob,
ALICE_SHARE_FOR_BOB, secret_hash));
const atomicswap_contract_object& contract = atomicswap_service.get_contract(alice, bob, secret_hash);
BOOST_REQUIRE_EQUAL(fc::microseconds(contract.deadline - contract.created).to_seconds(),
SCORUM_ATOMICSWAP_INITIATOR_REFUND_LOCK_SECS);
}
SCORUM_TEST_CASE(create_initiator_contract_check_double)
{
std::string secret_hash = atomicswap::get_secret_hash(ALICE_SECRET);
BOOST_REQUIRE_NO_THROW(atomicswap_service.create_contract(atomicswap_contract_initiator, alice, bob,
ALICE_SHARE_FOR_BOB, secret_hash));
BOOST_REQUIRE_THROW(
atomicswap_service.create_contract(atomicswap_contract_initiator, alice, bob, ALICE_SHARE_FOR_BOB, secret_hash),
fc::assert_exception);
secret_hash = atomicswap::get_secret_hash(ALICE_SECRET + "2");
BOOST_REQUIRE_NO_THROW(atomicswap_service.create_contract(atomicswap_contract_initiator, alice, bob,
ALICE_SHARE_FOR_BOB, secret_hash));
}
SCORUM_TEST_CASE(create_initiator_contract_check_limit_per_owner)
{
std::string secret_hash = atomicswap::get_secret_hash(ALICE_SECRET);
uint32_t ci = 0;
for (; ci < SCORUM_ATOMICSWAP_LIMIT_REQUESTED_CONTRACTS_PER_OWNER; ++ci)
{
const account_object& man = account_service.get_account(people[ci]);
BOOST_REQUIRE_NO_THROW(atomicswap_service.create_contract(atomicswap_contract_initiator, alice, man,
ALICE_SHARE_FOR_BOB, secret_hash));
std::stringstream data;
data << secret_hash << ci;
secret_hash = atomicswap::get_secret_hash(data.str());
}
BOOST_REQUIRE_EQUAL(atomicswap_service.get_contracts(alice).size(),
(size_t)SCORUM_ATOMICSWAP_LIMIT_REQUESTED_CONTRACTS_PER_OWNER);
BOOST_REQUIRE_THROW(atomicswap_service.create_contract(atomicswap_contract_initiator, alice,
account_service.get_account(people[ci]), ALICE_SHARE_FOR_BOB,
secret_hash),
fc::assert_exception);
}
SCORUM_TEST_CASE(create_initiator_contract_check_limit_per_recipient)
{
std::string secret_hash = atomicswap::get_secret_hash(MAN_SECRET);
uint32_t ci = 0;
for (; ci < SCORUM_ATOMICSWAP_LIMIT_REQUESTED_CONTRACTS_PER_RECIPIENT; ++ci)
{
const account_object& man = account_service.get_account(people[ci]);
BOOST_REQUIRE_NO_THROW(atomicswap_service.create_contract(atomicswap_contract_initiator, man, bob,
MAN_SHARE_FOR_BOB, secret_hash));
std::stringstream data;
data << secret_hash << ci;
secret_hash = atomicswap::get_secret_hash(data.str());
}
BOOST_REQUIRE_THROW(atomicswap_service.create_contract(atomicswap_contract_initiator,
account_service.get_account(people[ci]), bob,
MAN_SHARE_FOR_BOB, secret_hash),
fc::assert_exception);
}
BOOST_AUTO_TEST_SUITE_END()
class atomicswap_service_check_redeem_alice_contract_fixture : public atomicswap_service_check_fixture
{
public:
atomicswap_service_check_redeem_alice_contract_fixture()
{
atomicswap_service.create_contract(atomicswap_contract_initiator, alice, bob, ALICE_SHARE_FOR_BOB,
alice_secret_hash);
}
};
BOOST_FIXTURE_TEST_SUITE(atomicswap_service_redeem_alice_contract_check,
atomicswap_service_check_redeem_alice_contract_fixture)
SCORUM_TEST_CASE(create_redeem_close_contract)
{
BOOST_REQUIRE_EQUAL(atomicswap_service.get_contracts(alice).size(), (size_t)1);
BOOST_REQUIRE_NO_THROW(
atomicswap_service.redeem_contract(atomicswap_service.get_contracts(alice)[0], ALICE_SECRET));
BOOST_REQUIRE(atomicswap_service.get_contracts(alice).empty());
}
SCORUM_TEST_CASE(create_redeem_by_participant_check_balance)
{
const atomicswap_contract_object& contract = atomicswap_service.get_contract(alice, bob, alice_secret_hash);
BOOST_REQUIRE_EQUAL(bob.balance, BOB_BALANCE);
BOOST_REQUIRE_EQUAL(alice.balance, ALICE_BALANCE - ALICE_SHARE_FOR_BOB);
BOOST_REQUIRE_NO_THROW(atomicswap_service.redeem_contract(contract, ALICE_SECRET));
BOOST_REQUIRE_EQUAL(bob.balance, BOB_BALANCE + ALICE_SHARE_FOR_BOB);
BOOST_REQUIRE_EQUAL(alice.balance, ALICE_BALANCE - ALICE_SHARE_FOR_BOB);
BOOST_REQUIRE_THROW(atomicswap_service.get_contract(alice, bob, alice_secret_hash), fc::exception);
}
BOOST_AUTO_TEST_SUITE_END()
class atomicswap_service_check_redeem_bob_contract_fixture : public atomicswap_service_check_fixture
{
public:
atomicswap_service_check_redeem_bob_contract_fixture()
{
atomicswap_service.create_contract(atomicswap_contract_participant, bob, alice, BOB_SHARE_FOR_ALICE,
alice_secret_hash);
}
};
BOOST_FIXTURE_TEST_SUITE(atomicswap_service_redeem_bob_contract_check,
atomicswap_service_check_redeem_bob_contract_fixture)
SCORUM_TEST_CASE(create_redeem_no_close_contract)
{
const atomicswap_contract_object& contract = atomicswap_service.get_contract(bob, alice, alice_secret_hash);
BOOST_REQUIRE_NO_THROW(atomicswap_service.redeem_contract(contract, ALICE_SECRET));
BOOST_REQUIRE_NO_THROW(atomicswap_service.get_contract(bob, alice, alice_secret_hash));
}
SCORUM_TEST_CASE(create_redeem_by_initiator_check_balance)
{
const atomicswap_contract_object& contract = atomicswap_service.get_contract(bob, alice, alice_secret_hash);
BOOST_REQUIRE_EQUAL(bob.balance, BOB_BALANCE - BOB_SHARE_FOR_ALICE);
BOOST_REQUIRE_EQUAL(alice.balance, ALICE_BALANCE);
BOOST_REQUIRE_NO_THROW(atomicswap_service.redeem_contract(contract, ALICE_SECRET));
BOOST_REQUIRE_EQUAL(bob.balance, BOB_BALANCE - BOB_SHARE_FOR_ALICE);
BOOST_REQUIRE_EQUAL(alice.balance, ALICE_BALANCE + BOB_SHARE_FOR_ALICE);
BOOST_REQUIRE_NO_THROW(atomicswap_service.get_contract(bob, alice, alice_secret_hash));
}
SCORUM_TEST_CASE(refund)
{
const atomicswap_contract_object& contract = atomicswap_service.get_contract(bob, alice, alice_secret_hash);
BOOST_REQUIRE_EQUAL(bob.balance, BOB_BALANCE - BOB_SHARE_FOR_ALICE);
BOOST_REQUIRE_NO_THROW(atomicswap_service.refund_contract(contract));
BOOST_REQUIRE_EQUAL(bob.balance, BOB_BALANCE);
}
BOOST_AUTO_TEST_SUITE_END()
| 42.078431 | 120 | 0.734017 | [
"vector"
] |
bfa7f8560f4cd700878a02b9ff9cca17c3118240 | 39,653 | cpp | C++ | runtime.cpp | Vector35/llil_transpiler | 6f6f368d34cb872460ad1634ddcbc4207276feb6 | [
"MIT"
] | 14 | 2019-08-23T13:49:07.000Z | 2021-12-24T20:09:57.000Z | runtime.cpp | Vector35/llil_transpiler | 6f6f368d34cb872460ad1634ddcbc4207276feb6 | [
"MIT"
] | null | null | null | runtime.cpp | Vector35/llil_transpiler | 6f6f368d34cb872460ad1634ddcbc4207276feb6 | [
"MIT"
] | 1 | 2021-12-24T20:10:00.000Z | 2021-12-24T20:10:00.000Z |
#include <string>
#include <vector>
#include <map>
using namespace std;
#include <stdint.h>
#include "runtime.h"
#define DEBUG_RUNTIME_ALL
#define DEBUG_RUNTIME_SETS
#define DEBUG_RUNTIME_STACK
#define debug printf
#if defined(DEBUG_RUNTIME_SETS) || defined(DEBUG_RUNTIME_ALL)
#define debug_set printf
#else
#define debug_set(...) while(0);
#endif
#if defined(DEBUG_RUNTIME_STACK) || defined(DEBUG_RUNTIME_ALL)
#define debug_stack printf
#else
#define debug_stack(...) while(0);
#endif
/* the foo_il.c must export this, else we can't implement PUSH */
extern string stack_reg_name;
extern bool is_link_reg_arch;
extern string link_reg_name;
extern map<string,struct RegisterInfo> reg_infos;
/* VM components */
uint8_t vm_mem[VM_MEM_SZ];
map<string, Storage> vm_regs;
map<string, int> vm_flags;
/*****************************************************************************/
/* register setting/getting */
/*****************************************************************************/
bool is_temp_reg(string reg_name)
{
return reg_name.rfind("temp", 0) == 0;
}
// return the register's storage (possibly in a parent register)
//
Storage reg_get_storage(string reg_name)
{
REGTYPE result;
/* temp registers simply come from the temp regs file */
if(is_temp_reg(reg_name))
return vm_regs[reg_name];
/* otherwise we need to resolve sub-register relationships */
RegisterInfo reg_info = reg_infos[reg_name];
/* full width */
if(reg_info.full_width_reg == reg_name)
return vm_regs[reg_name];
/* sub register */
return vm_regs[reg_info.full_width_reg];
}
// set the register's storage (possibly in a parent register)
void reg_set_storage(string reg_name, Storage store)
{
REGTYPE result;
//printf("setting %s to ", reg_name.c_str());
//for(int i=0; i<16; i++)
// printf("%02X ", store.data[i]&0xFF);
//printf("\n");
if(is_temp_reg(reg_name)) {
vm_regs[reg_name] = store;
return;
}
RegisterInfo reg_info = reg_infos[reg_name];
if(reg_info.full_width_reg == reg_name) {
vm_regs[reg_name] = store;
return;
}
vm_regs[reg_info.full_width_reg] = store;
}
// return the register's offset into storage of its parent register
// eg:
// rax is offset 0 into rax, return 0
// eax is offset 0 into rax, return 1
// ah is offset 1 into rax, return 1
int reg_get_storage_offset(string reg_name)
{
if(is_temp_reg(reg_name))
return 0;
RegisterInfo reg_info = reg_infos[reg_name];
assert((reg_info.full_width_reg != reg_name) || reg_info.offset==0);
return reg_info.offset;
}
/* internal register getters */
float reg_get_float32_nocheck(string name)
{
Storage store = reg_get_storage(name);
int offset = reg_get_storage_offset(name);
return *(float *)(store.data + offset);
}
uint8_t reg_get_uint8(string name)
{
assert(is_temp_reg(name) || reg_infos[name].size == 1);
Storage store = reg_get_storage(name);
int offset = reg_get_storage_offset(name);
return *(uint8_t *)(store.data + offset);
}
uint16_t reg_get_uint16(string name)
{
assert(is_temp_reg(name) || reg_infos[name].size == 2);
Storage store = reg_get_storage(name);
int offset = reg_get_storage_offset(name);
return *(uint16_t *)(store.data + offset);
}
uint32_t reg_get_uint32(string name)
{
assert(is_temp_reg(name) || reg_infos[name].size == 4);
Storage store = reg_get_storage(name);
int offset = reg_get_storage_offset(name);
return *(uint32_t *)(store.data + offset);
}
uint64_t reg_get_uint64(string name)
{
assert(is_temp_reg(name) || reg_infos[name].size == 8);
Storage store = reg_get_storage(name);
int offset = reg_get_storage_offset(name);
return *(uint64_t *)(store.data + offset);
}
__uint128_t reg_get_uint128(string name)
{
assert(is_temp_reg(name) || reg_infos[name].size == 16);
Storage store = reg_get_storage(name);
int offset = reg_get_storage_offset(name);
return *(__uint128_t *)(store.data + offset);
}
float reg_get_float32(string name)
{
assert(is_temp_reg(name) || reg_infos[name].size == 4);
return reg_get_float32_nocheck(name);
}
/* internal register setters */
void reg_set_uint8_nocheck(string name, uint8_t val)
{
Storage store = reg_get_storage(name);
int offset = reg_get_storage_offset(name);
*(uint8_t *)(store.data + offset) = val;
reg_set_storage(name, store);
}
void reg_set_uint16_nocheck(string name, uint16_t val)
{
Storage store = reg_get_storage(name);
int offset = reg_get_storage_offset(name);
*(uint16_t *)(store.data + offset) = val;
reg_set_storage(name, store);
}
void reg_set_uint32_nocheck(string name, uint32_t val)
{
Storage store = reg_get_storage(name);
int offset = reg_get_storage_offset(name);
*(uint32_t *)(store.data + offset) = val;
reg_set_storage(name, store);
}
void reg_set_uint64_nocheck(string name, uint64_t val)
{
Storage store = reg_get_storage(name);
int offset = reg_get_storage_offset(name);
*(uint64_t *)(store.data + offset) = val;
reg_set_storage(name, store);
}
void reg_set_uint128_nocheck(string name, __uint128_t val)
{
Storage store = reg_get_storage(name);
int offset = reg_get_storage_offset(name);
*(__uint128_t *)(store.data + offset) = val;
reg_set_storage(name, store);
}
void reg_set_uint8(string name, uint8_t val)
{
assert(is_temp_reg(name) || reg_infos[name].size == 1);
reg_set_uint8_nocheck(name, val);
}
void reg_set_uint16(string name, uint16_t val)
{
assert(is_temp_reg(name) || reg_infos[name].size == 2);
reg_set_uint16_nocheck(name, val);
}
void reg_set_uint32(string name, uint32_t val)
{
assert(is_temp_reg(name) || reg_infos[name].size == 4);
reg_set_uint32_nocheck(name, val);
}
void reg_set_uint64(string name, uint64_t val)
{
assert(is_temp_reg(name) || reg_infos[name].size == 8);
reg_set_uint64_nocheck(name, val);
}
void reg_set_uint128(string name, __uint128_t val)
{
assert(is_temp_reg(name) || reg_infos[name].size == 16);
reg_set_uint128_nocheck(name, val);
}
void reg_set_float32(string name, float val)
{
// do not force size check: often the low-bits of a floating point register
// are reserved for smaller float types, eg: 128-bit xmm0 can have low 32
// bits for a normal single precision float
//assert(is_temp_reg(name) || reg_infos[name].size == 32);
Storage store = reg_get_storage(name);
int offset = reg_get_storage_offset(name);
*(float *)(store.data + offset) = val;
reg_set_storage(name, store);
}
/*****************************************************************************/
/* operations */
/*****************************************************************************/
/* LowLevelILOperation.LLIL_NOP: [] */
void NOP(void)
{
return;
}
/* LowLevelILOperation.LLIL_REG: [("src", "reg")] */
uint8_t REG8(string name)
{
uint8_t result = reg_get_uint8(name);
debug("REG8 0x%02X (value of %s)\n", result, name.c_str());
return result;
}
uint16_t REG16(string name)
{
uint16_t result = reg_get_uint16(name);
debug("REG16 0x%04X (value of %s)\n", result, name.c_str());
return result;
}
uint32_t REG32(string name)
{
uint32_t result = reg_get_uint32(name);
debug("REG32 0x%08X (value of %s)\n", result, name.c_str());
return result;
}
uint64_t REG64(string name)
{
__uint64_t result = reg_get_uint64(name);
debug("REG64 0x%016llX (value of %s)\n", result, name.c_str());
return result;
}
__uint128_t REG128(string name)
{
__uint128_t result = reg_get_uint128(name);
debug("REG128 0x%016llX%016llX (value of %s)\n", (uint64_t)(result>>64), (uint64_t)result, name.c_str());
return result;
}
uint32_t REG64_D(string name)
{
uint32_t result = (reg_get_uint128(name) & 0xFFFFFFFF);
debug("REG64_D 0x%04X (value of %s)\n", (uint32_t)result, name.c_str());
return result;
}
uint32_t REG128_D(string name)
{
__uint128_t result = (reg_get_uint128(name) & 0xFFFFFFFF);
debug("REG128_D 0x%04X (value of %s)\n", (uint32_t)result, name.c_str());
return result;
}
/* LowLevelILOperation.LLIL_SET_REG: [("dest", "reg"), ("src", "expr")] */
void SET_REG8(string reg_name, uint8_t value)
{
reg_set_uint8(reg_name, value);
debug_set("SET_REG8 %s = 0x%02X\n", reg_name.c_str(), value);
}
void SET_REG16(string reg_name, uint16_t value)
{
reg_set_uint16(reg_name, value);
debug_set("SET_REG16 %s = 0x%04X\n", reg_name.c_str(), value);
}
void SET_REG32(string reg_name, uint32_t value)
{
reg_set_uint32(reg_name, value);
debug_set("SET_REG32 %s = 0x%08X\n", reg_name.c_str(), value);
}
void SET_REG64(string reg_name, uint64_t value)
{
reg_set_uint64(reg_name, value);
debug_set("SET_REG64 %s = 0x%016llX\n", reg_name.c_str(), value);
}
void SET_REG128(string reg_name, __uint128_t value)
{
reg_set_uint128(reg_name, value);
debug_set("SET_REG128 %s = 0x%016llX%016llX\n",
reg_name.c_str(), (uint64_t)(value >> 64), (uint64_t)value);
}
void SET_REG64_D(string reg_name, uint32_t value)
{
assert(is_temp_reg(reg_name) || reg_infos[reg_name].size == 64);
reg_set_uint32_nocheck(reg_name, value);
debug_set("SET_REG64_D %s = 0x%08X\n", reg_name.c_str(), value);
}
void SET_REG128_D(string reg_name, uint32_t value)
{
assert(is_temp_reg(reg_name) || reg_infos[reg_name].size == 16);
reg_set_uint32_nocheck(reg_name, value);
debug_set("SET_REG128_D %s = 0x%08X\n", reg_name.c_str(), value);
}
/* LowLevelILOperation.LLIL_SET_REG_SPLIT: [("hi", "reg"), ("lo", "reg"), ("src", "expr")] */
void SET_REG_SPLIT(string hi, string lo, REGTYPE src_val)
{
REGTYPE dst_val_hi = (REGTYPE) (src_val & REGMASKHIHALF) >> (REGWIDTH/2);
REGTYPE dst_val_lo = (REGTYPE) (src_val & REGMASKLOHALF);
REG_SET_ADDR(hi, dst_val_hi);
REG_SET_ADDR(lo, dst_val_lo);
debug_set("SET_REG_SPLIT " FMT_REG " -> %s = " FMT_REG ", %s = " FMT_REG "\n",
src_val, hi.c_str(), dst_val_hi, lo.c_str(), dst_val_lo);
}
/* LowLevelILOperation.LLIL_REG_SPLIT: [("hi", "reg"), ("lo", "reg")] */
/* better called "join" */
REGTYPE REG_SPLIT(string hi, string lo)
{
REGTYPE src_hi = REG_GET_ADDR(hi);
REGTYPE src_lo = REG_GET_ADDR(lo);
REGTYPE result = (src_hi << (REGWIDTH/2)) | (src_lo & REGMASKLOHALF);
debug("REG_SPLIT " FMT_REG " join " FMT_REG " -> " FMT_REG "\n",
src_hi, src_lo, result);
return result;
}
/* LowLevelILOperation.LLIL_SET_REG_STACK_REL: [("stack", "reg_stack"), ("dest", "expr"), ("src", "expr")] */
/* LowLevelILOperation.LLIL_REG_STACK_PUSH: [("stack", "reg_stack"), ("src", "expr")] */
/* LowLevelILOperation.LLIL_SET_FLAG: [("dest", "flag"), ("src", "expr")] */
void SET_FLAG(string left, bool right)
{
vm_flags[left] = right;
debug_set("SET_FLAG %s = %d\n", left.c_str(), right);
}
/* LowLevelILOperation.LLIL_LOAD: [("src", "expr")] */
uint8_t LOAD8(REGTYPE expr)
{
uint8_t result = vm_mem[expr];
debug("LOAD8 0x%X = mem[" FMT_REG "]\n", result, expr);
return result;
}
uint16_t LOAD16(REGTYPE expr)
{
uint16_t result = *(uint16_t *)(vm_mem + expr);
debug("LOAD16 0x%X = mem[" FMT_REG "]\n", result, expr);
return result;
}
uint32_t LOAD32(REGTYPE expr)
{
uint32_t result = *(uint32_t *)(vm_mem + expr);
debug("LOAD32 0x%X = mem[" FMT_REG "]\n", result, expr);
return result;
}
uint64_t LOAD64(REGTYPE expr)
{
uint32_t result = *(uint64_t *)(vm_mem + expr);
debug("LOAD64 0x%X = mem[" FMT_REG "]\n", result, expr);
return result;
}
__uint128_t LOAD128(REGTYPE expr)
{
__uint128_t result = *(__uint128_t *)(vm_mem + expr);
debug("LOAD128 0x%llX%llX = mem[" FMT_REG "]\n", (uint64_t)(result>>64), (uint64_t)result, expr);
return result;
}
/* LowLevelILOperation.LLIL_STORE: [("dest", "expr"), ("src", "expr")] */
void STORE8(REGTYPE dest, uint8_t src)
{
debug("STORE8 byte[" FMT_REG "] = 0x%02X\n", dest, src);
*(uint8_t *)(vm_mem + dest) = src;
}
void STORE16(REGTYPE dest, uint16_t src)
{
debug("STORE16 word[" FMT_REG "] = 0x%04X\n", dest, src);
*(uint16_t *)(vm_mem + dest) = src;
}
void STORE32(REGTYPE dest, uint32_t src)
{
debug("STORE32 dword[" FMT_REG "] = 0x%08X\n", dest, src);
*(uint32_t *)(vm_mem + dest) = src;
}
void STORE64(REGTYPE dest, uint64_t src)
{
debug("STORE64 qword[" FMT_REG "] = 0x%016llX\n", dest, src);
*(uint64_t *)(vm_mem + dest) = src;
}
/* LowLevelILOperation.LLIL_PUSH: [("src", "expr")] */
void PUSH(REGTYPE src)
{
/* decrement stack pointer */
REG_SET_ADDR(stack_reg_name, REG_GET_ADDR(stack_reg_name) - sizeof(REGTYPE));
/* store on stack */
ADDRTYPE ea = REG_GET_ADDR(stack_reg_name);
debug_stack("PUSH mem[" FMT_REG "] = " FMT_REG "\n", ea, src);
*(REGTYPE *)(vm_mem + ea) = src;
}
/* LowLevelILOperation.LLIL_POP: [] */
REGTYPE POP(void)
{
/* retrieve from stack */
ADDRTYPE ea = REG_GET_ADDR(stack_reg_name);
REGTYPE val = *(ADDRTYPE *)(vm_mem + ea);
debug_stack("POP " FMT_ADDR " = mem[" FMT_ADDR "]\n", val, ea);
/* increment stack pointer */
REG_SET_ADDR(stack_reg_name, REG_GET_ADDR(stack_reg_name) + sizeof(REGTYPE));
return val;
}
/* LowLevelILOperation.LLIL_REG_STACK_REL: [("stack", "reg_stack"), ("src", "expr")] */
/* LowLevelILOperation.LLIL_REG_STACK_POP: [("stack", "reg_stack")] */
/* LowLevelILOperation.LLIL_REG_STACK_FREE_REG: [("dest", "reg")] */
/* LowLevelILOperation.LLIL_REG_STACK_FREE_REL: [("stack", "reg_stack"), ("dest", "expr")] */
/* LowLevelILOperation.LLIL_CONST: [("constant", "int")] */
/* LowLevelILOperation.LLIL_CONST_PTR: [("constant", "int")] */
/* LowLevelILOperation.LLIL_EXTERN_PTR: [("constant", "int"), ("offset", "int")] */
SREGTYPE EXTERN_PTR(SREGTYPE constant, SREGTYPE offset)
{
return constant + offset;
}
/* LowLevelILOperation.LLIL_FLOAT_CONST: [("constant", "float")] */
/* LowLevelILOperation.LLIL_FLAG: [("src", "flag")] */
bool FLAG(string src)
{
bool result = vm_flags[src];
debug("FLAG " "%d = vm_flags[%s]\n", result, src.c_str());
return result;
}
/* LowLevelILOperation.LLIL_FLAG_BIT: [("src", "flag"), ("bit", "int")] */
/* LowLevelILOperation.LLIL_ADD: [("left", "expr"), ("right", "expr")] */
uint8_t ADD8(uint8_t left, uint8_t right)
{
uint8_t result = left + right;
debug("ADD8 0x%02X = 0x%02X + 0x%02X\n", result & 0xFF, left & 0xFF, right & 0xFF);
return result;
}
uint16_t ADD16(uint16_t left, uint16_t right)
{
uint16_t result = left + right;
debug("ADD16 0x%04X = 0x%04X + 0x%04X\n", result & 0xFFFF, left & 0xFFFF, right & 0xFFFF);
return result;
}
uint32_t ADD32(uint32_t left, uint32_t right)
{
uint32_t result = left + right;
debug("ADD32 0x%08X = 0x%08X + 0x%08X\n", result, left, right);
return result;
}
uint64_t ADD64(uint64_t left, uint64_t right)
{
uint64_t result = left + right;
debug("ADD64 0x%016llX = 0x%016llX + 0x%016llX\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_ADC: [("left", "expr"), ("right", "expr"), ("carry", "expr")] */
SREGTYPE ADC(SREGTYPE left, SREGTYPE right, bool carry)
{
SREGTYPE result = left + right + carry;
debug("ADC " FMT_REG " = " FMT_REG " + " FMT_REG " + %d\n", result, left, right, carry);
return result;
}
/* LowLevelILOperation.LLIL_SUB: [("left", "expr"), ("right", "expr")] */
uint8_t SUB8(uint8_t a, uint8_t b)
{
uint8_t result = a - b;
debug("SUB1 0x%02X = 0x%02X - 0x%02X\n", result, a, b);
return result;
}
uint16_t SUB16(uint16_t a, uint16_t b)
{
uint16_t result = a - b;
debug("SUB2 0x%04X = 0x%04X - 0x%04X\n", result, a, b);
return result;
}
uint32_t SUB32(uint32_t a, uint32_t b)
{
uint32_t result = a - b;
debug("SUB4 0x%08X = 0x%08X - 0x%08X\n", result, a, b);
return result;
}
uint64_t SUB64(uint64_t a, uint64_t b)
{
uint64_t result = a - b;
debug("SUB8 0x%016llX = 0x%016llX - 0x%016llX\n", result, a, b);
return result;
}
/* LowLevelILOperation.LLIL_SBB: [("left", "expr"), ("right", "expr"), ("carry", "expr")] */
uint8_t SBB8(uint8_t a, uint8_t b, uint8_t c)
{
uint8_t result = a - b - c;
debug("SBB1 0x%02X = 0x%02X - 0x%02X - %d\n", result, a, b, c);
return result;
}
uint16_t SBB16(uint16_t a, uint16_t b, uint16_t c)
{
uint16_t result = a - b - c;
debug("SBB2 0x%04X = 0x%04X - 0x%04X - %d\n", result, a, b, c);
return result;
}
uint32_t SBB32(uint32_t a, uint32_t b, uint32_t c)
{
uint32_t result = a - b - c;
debug("SBB4 0x%08X = 0x%08X - 0x%08X - %d\n", result, a, b, c);
return result;
}
uint64_t SBB64(uint64_t a, uint64_t b, uint64_t c)
{
uint64_t result = a - b - c;
debug("SBB8 0x%016llX = 0x%016llX - 0x%016llX - %lld\n", result, a, b, c);
return result;
}
/* LowLevelILOperation.LLIL_AND: [("left", "expr"), ("right", "expr")] */
REGTYPE AND(REGTYPE left, REGTYPE right)
{
REGTYPE result = left & right;
debug("AND " FMT_REG " = " FMT_REG " & " FMT_REG "\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_OR: [("left", "expr"), ("right", "expr")] */
REGTYPE OR(REGTYPE left, REGTYPE right)
{
REGTYPE result = left | right;
debug("OR " FMT_REG " = " FMT_REG " | " FMT_REG "\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_XOR: [("left", "expr"), ("right", "expr")] */
REGTYPE XOR(REGTYPE left, REGTYPE right)
{
REGTYPE result = left ^ right;
debug("XOR " FMT_REG " = " FMT_REG " ^ " FMT_REG "\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_LSL: [("left", "expr"), ("right", "expr")] */
REGTYPE LSL(REGTYPE left, REGTYPE right)
{
REGTYPE result = left << right;
debug("LSL " FMT_REG " = " FMT_REG " << " FMT_REG "\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_LSR: [("left", "expr"), ("right", "expr")] */
REGTYPE LSR(REGTYPE left, REGTYPE right)
{
REGTYPE result = left >> right;
debug("LSR " FMT_REG " = " FMT_REG " << " FMT_REG "\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_ASR: [("left", "expr"), ("right", "expr")] */
SREGTYPE ASR(SREGTYPE left, REGTYPE right)
{
/* recall: ARITHMETIC shift preseves sign bit - hope the compiler generates correct code :) */
SREGTYPE result = left >> right;
debug("ASR " FMT_REG " = " FMT_REG " >> " FMT_REG "\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_ROL: [("left", "expr"), ("right", "expr")] */
uint8_t ROL8(uint8_t value, uint8_t amt)
{
amt = amt % 8;
uint8_t result = (value << amt) | (value >> (8-amt));
debug("ROL1 0x%02X = ROL(0x%02X, %d)\n", result, value, amt);
return result;
}
uint16_t ROL16(uint16_t value, uint16_t amt)
{
amt = amt % 16;
uint16_t result = (value << amt) | (value >> (16-amt));
debug("ROL2 0x%04X = ROL(0x%04X, %d)\n", result, value, amt);
return result;
}
uint32_t ROL32(uint32_t value, uint32_t amt)
{
amt = amt % 32;
uint32_t result = (value << amt) | (value >> (8-amt));
debug("ROL4 0x%08X = ROL(0x%08X, %d)\n", result, value, amt);
return result;
}
uint64_t ROL64(uint64_t value, uint64_t amt)
{
amt = amt % 64;
uint64_t result = (value << amt) | (value >> (8-amt));
debug("ROL8 0x%08llX = ROL(0x%016llX, %lld)\n", result, value, amt);
return result;
}
/* LowLevelILOperation.LLIL_RLC: [("left", "expr"), ("right", "expr"), ("carry", "expr")] */
uint8_t RLC8(uint8_t value, uint8_t amt, bool carry)
{
uint8_t result = value;
if(amt) {
amt = amt % 8;
// normal carry
uint8_t a = (value << amt);
uint8_t b = (value >> (8-amt));
// insert c
b = (b >> 1) | (carry << (amt-1));
//
result = a | b;
}
debug("RLC1 0x%X = 0x%X <<< %d and carry = %d\n", result, value, amt, carry);
return result;
}
/* LowLevelILOperation.LLIL_ROR: [("left", "expr"), ("right", "expr")] */
uint8_t ROR8(uint8_t value, uint8_t amt)
{
amt = amt % 8;
uint8_t result = (value >> amt) | (value << (8-amt));
debug("ROR1(0x%02X, %d) returns 0x%02X\n", value, amt, result);
return result;
}
uint16_t ROR16(uint16_t value, uint16_t amt)
{
amt = amt % 16;
uint16_t result = (value >> amt) | (value << (16-amt));
debug("ROR16(0x%04X, %d) returns 0x%04X\n", value, amt, result);
return result;
}
uint32_t ROR32(uint32_t value, uint32_t amt)
{
amt = amt % 32;
uint32_t result = (value >> amt) | (value << (8-amt));
debug("ROR32(0x%08X, %d) returns 0x%08X\n", value, amt, result);
return result;
}
uint64_t ROR64(uint64_t value, uint64_t amt)
{
amt = amt % 64;
uint64_t result = (value >> amt) | (value << (8-amt));
debug("ROR64(0x%016llX, %lld) returns 0x%016llX\n", value, amt, result);
return result;
}
/* LowLevelILOperation.LLIL_RRC: [("left", "expr"), ("right", "expr"), ("carry", "expr")] */
uint8_t RRC8(uint8_t value, uint8_t amt, bool carry)
{
uint8_t result = value;
if(amt) {
amt = amt % 8;
// normal carry
uint8_t a = value >> amt;
uint8_t b = value << (8-amt+1);
uint8_t c = value << (8-amt);
result = a | b | c;
}
debug("RRC8 0x%X = 0x%X >>> %d and carry = %d\n", result, value, amt, carry);
return result;
}
SREGTYPE MUL(SREGTYPE left, SREGTYPE right)
{
SREGTYPE result = left * right;
debug("MUL " FMT_REG " = " FMT_REG " * " FMT_REG "\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_MULU_DP: [("left", "expr"), ("right", "expr")] */
/* LowLevelILOperation.LLIL_MULS_DP: [("left", "expr"), ("right", "expr")] */
/* LowLevelILOperation.LLIL_DIVU: [("left", "expr"), ("right", "expr")] */
/* LowLevelILOperation.LLIL_DIVU_DP: [("left", "expr"), ("right", "expr")] */
/* LowLevelILOperation.LLIL_DIVS: [("left", "expr"), ("right", "expr")] */
SREGTYPE DIVS(SREGTYPE left, SREGTYPE_HALF right)
{
SREGTYPE result = left / right;
debug("DIVS_DP " FMT_SREG " = " FMT_SREG " / " FMT_REG_HALF "\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_DIVS_DP: [("left", "expr"), ("right", "expr")] */
// TODO: figure out "DP"
SREGTYPE DIVS_DP(SREGTYPE left, SREGTYPE_HALF right)
{
SREGTYPE result = left / right;
debug("DIVS_DP " FMT_SREG " = " FMT_SREG " / " FMT_REG_HALF "\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_MODU: [("left", "expr"), ("right", "expr")] */
REGTYPE MODU(REGTYPE left, REGTYPE right)
{
REGTYPE result = left % right;
debug("MODU " FMT_REG " = " FMT_REG " %% " FMT_REG "\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_MODU_DP: [("left", "expr"), ("right", "expr")] */
// TODO: figure out what DP's supposed to do different
REGTYPE MODU_DP(REGTYPE left, REGTYPE right)
{
REGTYPE result = left % right;
debug("MODU_DP " FMT_REG " = " FMT_REG " %% " FMT_REG "\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_MODS: [("left", "expr"), ("right", "expr")] */
SREGTYPE MODS(SREGTYPE left, SREGTYPE right)
{
SREGTYPE result = left % right;
debug("MODS " FMT_SREG " = " FMT_SREG " %% " FMT_SREG "\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_MODS_DP: [("left", "expr"), ("right", "expr")] */
// TODO: figure out what DP's supposed to do different
SREGTYPE MODS_DP(SREGTYPE left, SREGTYPE right)
{
SREGTYPE result = left % right;
debug("MODS_DP " FMT_SREG " = " FMT_SREG " %% " FMT_SREG "\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_NEG: [("src", "expr")] */
uint8_t NEG8(uint8_t src)
{
uint8_t result = (src ^ 0xFF) + 1;
debug("NEG8 0x%02X = neg(0x%02X)\n", result, src);
return result;
}
uint16_t NEG16(uint16_t src)
{
uint16_t result = (src ^ 0xFFFF) + 1;
debug("NEG16 0x%04X = neg(0x%04X)\n", result, src);
return result;
}
uint32_t NEG32(uint32_t src)
{
uint32_t result = (src ^ 0xFFFFFFFF) + 1;
debug("NEG32 0x%08X = neg(0x%08X)\n", result, src);
return result;
}
uint64_t NEG64(uint64_t src)
{
uint64_t result = (src ^ 0xFFFFFFFFFFFFFFFF) + 1;
debug("NEG64 0x%016llX = neg(0x%016llX)\n", result, src);
return result;
}
/* LowLevelILOperation.LLIL_NOT: [("src", "expr")] */
uint8_t NOT0(uint8_t left)
{
/* size 0 is special case which means treat as bool
nonzero -> zero
zero -> 1
*/
uint8_t result = !!(left);
debug("NOT0 0x%02X = 0x%02X ^ 1\n", result, left);
return result;
}
uint8_t NOT8(uint8_t left)
{
uint8_t result = ~left;
debug("NOT8 0x%02X = ~0x%02X\n", result, left);
return result;
}
uint16_t NOT16(uint16_t left)
{
uint16_t result = ~left;
debug("NOT16 0x%04X = ~0x%04X\n", result, left);
return result;
}
uint32_t NOT32(uint32_t left)
{
uint32_t result = ~left;
debug("NOT32 0x%08X = ~0x%08X\n", result, left);
return result;
}
uint64_t NOT64(uint64_t left)
{
uint64_t result = ~left;
debug("NOT64 0x%016llX = ~0x%016llX\n", result, left);
return result;
}
/* LowLevelILOperation.LLIL_SX: [("src", "expr")] */
SREGTYPE SX8(int8_t src)
{
SREGTYPE result = src;
debug("SX8 %d -> " FMT_SREG "\n", src, result);
return result;
}
SREGTYPE SX16(int16_t src)
{
SREGTYPE result = src;
debug("SX16 %d -> " FMT_SREG "\n", src, result);
return result;
}
SREGTYPE SX32(int32_t src)
{
SREGTYPE result = src;
debug("SX32 %d -> " FMT_SREG "\n", src, result);
return result;
}
/* LowLevelILOperation.LLIL_ZX: [("src", "expr")] */
uint32_t ZX32(uint32_t src)
{
uint32_t result = src;
debug("ZX32 0x%08X -> 0x%08X\n", src, result);
return result;
}
uint64_t ZX64(uint64_t src)
{
uint64_t result = src;
debug("ZX64 0x%016llX -> 0x%016llX\n", src, result);
return result;
}
/* LowLevelILOperation.LLIL_LOW_PART: [("src", "expr")] */
uint8_t LOW_PART8(REGTYPE left)
{
uint8_t result = left & 0xFF;
debug("LOW_PART8 " FMT_REG " -> 0x%02X\n", left, result);
return result;
}
uint16_t LOW_PART16(REGTYPE left)
{
uint16_t result = left & 0xFFFF;
debug("LOW_PART16 " FMT_REG " -> 0x%04X\n", left, result);
return result;
}
uint32_t LOW_PART32(REGTYPE left)
{
uint32_t result = left & 0xFFFF;
debug("LOW_PART32 " FMT_REG " -> 0x%08X\n", left, result);
return result;
}
/* LowLevelILOperation.LLIL_JUMP: [("dest", "expr")] */
RETURN_ACTION JUMP(REGTYPE dest)
{
if(dest == RETURN_ADDRESS_CANARY)
return RETURN_TRUE;
printf("ERROR: JUMP to " FMT_REG " is out of LLIL land, something went wrong in transpilation\n", dest);
exit(-1);
return RETURN_FALSE;
}
/* LowLevelILOperation.LLIL_JUMP_TO: [("dest", "expr"), ("targets", "int_list")] */
/* LowLevelILOperation.LLIL_CALL: [("dest", "expr")] */
void CALL(REGTYPE dest, void (*pfunc)(void), const char *func_name)
{
if(is_link_reg_arch) {
/* this is a link register style of architecture, so set the LR */
REG_SET_ADDR(link_reg_name, RETURN_ADDRESS_CANARY);
debug_set("SET %s = " FMT_REG "\n", link_reg_name.c_str(), RETURN_ADDRESS_CANARY);
}
else {
/* this is a push-the-return-address style of architecture
so push a dummy return address */
REG_SET_ADDR(stack_reg_name, REG_GET_ADDR(stack_reg_name) - sizeof(ADDRTYPE));
*(ADDRTYPE *)(vm_mem + REG_GET_ADDR(stack_reg_name)) = RETURN_ADDRESS_CANARY;
debug_stack("CALL " FMT_REG " mem[" FMT_REG "] = " FMT_REG " %s()\n",
dest, REG_GET_ADDR(stack_reg_name), RETURN_ADDRESS_CANARY, func_name);
}
return pfunc();
}
/* LowLevelILOperation.LLIL_CALL_STACK_ADJUST: [("dest", "expr"), ("stack_adjustment", "int"), ("reg_stack_adjustments", "reg_stack_adjust")] */
/* LowLevelILOperation.LLIL_TAILCALL: [("dest", "expr")] */
void TAILCALL(REGTYPE dest, void (*pfunc)(void), const char *func_name)
{
/* dummy push of return address */
debug_stack("TAILCALL " FMT_REG " %s()\n", dest, func_name);
return pfunc();
}
/* LowLevelILOperation.LLIL_RET: [("dest", "expr")] */
void RET(REGTYPE dest)
{
/* IL semantics of RET are _not_ necessarily to pop and jump (but can be)
an x86 style ret will be RET(POP())
an arm style ret might be RET(REG("lr")) */
// DO NOT:
// vm_regs[stack_reg_name] += sizeof(REGTYPE);
debug_stack("RET " FMT_REG "\n", dest);
}
/* LowLevelILOperation.LLIL_NORET: [] */
/* LowLevelILOperation.LLIL_IF: [("condition", "expr"), ("true", "int"), ("false", "int")] */
/* LowLevelILOperation.LLIL_GOTO: [("dest", "int")] */
/* LowLevelILOperation.LLIL_FLAG_COND: [("condition", "cond"), ("semantic_class", "sem_class")] */
/* LowLevelILOperation.LLIL_FLAG_GROUP: [("semantic_group", "sem_group")] */
/* LowLevelILOperation.LLIL_CMP_E: [("left", "expr"), ("right", "expr")] */
bool CMP_E(REGTYPE left, REGTYPE right)
{
bool result = left == right;
debug("CMP_E %d = " FMT_REG " == " FMT_REG "\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_CMP_NE: [("left", "expr"), ("right", "expr")] */
bool CMP_NE(REGTYPE left, REGTYPE right)
{
bool result = left != right;
debug("CMP_NE %d = " FMT_REG " != " FMT_REG "\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_CMP_SLT: [("left", "expr"), ("right", "expr")] */
bool CMP_SLT8(int8_t left, int8_t right)
{
bool result = left < right;
debug("CMP_SLT8 %d = %d < %d\n", result, left, right);
return result;
}
bool CMP_SLT16(int16_t left, int16_t right)
{
bool result = left < right;
debug("CMP_SLT16 %d = %d < %d\n", result, left, right);
return result;
}
bool CMP_SLT32(int32_t left, int32_t right)
{
bool result = left < right;
debug("CMP_SLT32 %d = %d < %d\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_CMP_ULT: [("left", "expr"), ("right", "expr")] */
bool CMP_ULT(REGTYPE left, REGTYPE right)
{
bool result = left < right;
debug("CMP_ULT %d = " FMT_REG " < " FMT_REG "\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_CMP_SLE: [("left", "expr"), ("right", "expr")] */
bool CMP_SLE8(int8_t left, int8_t right)
{
bool result = left <= right;
debug("CMP_SLE8 %d = %d <= %d\n", result, left, right);
return result;
}
bool CMP_SLE16(int16_t left, int16_t right)
{
bool result = left <= right;
debug("CMP_SLE16 %d = %d <= %d\n", result, left, right);
return result;
}
bool CMP_SLE32(int32_t left, int32_t right)
{
bool result = left <= right;
debug("CMP_SLE32 %d = %d <= %d\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_CMP_ULE: [("left", "expr"), ("right", "expr")] */
bool CMP_ULE(REGTYPE left, REGTYPE right)
{
bool result = left <= right;
debug("CMP_ULE %d = " FMT_REG " <= " FMT_REG "\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_CMP_SGE: [("left", "expr"), ("right", "expr")] */
bool CMP_SGE8(int8_t left, int8_t right)
{
bool result = left >= right;
debug("CMP_SGE8 %d = %d >= %d\n", result, left, right);
return result;
}
bool CMP_SGE16(int16_t left, int16_t right)
{
bool result = left >= right;
debug("CMP_SGE16 %d = %d >= %d\n", result, left, right);
return result;
}
bool CMP_SGE32(int32_t left, int32_t right)
{
bool result = left >= right;
debug("CMP_SGE32 %d = %d >= %d\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_CMP_UGE: [("left", "expr"), ("right", "expr")] */
bool CMP_UGE(REGTYPE left, REGTYPE right)
{
bool result = left >= right;
debug("CMP_UGE %d = " FMT_REG " >= " FMT_REG "\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_CMP_SGT: [("left", "expr"), ("right", "expr")] */
bool CMP_SGT8(int8_t left, int8_t right)
{
bool result = left > right;
debug("CMP_SGT8 %d = %d > %d\n", result, left, right);
return result;
}
bool CMP_SGT16(int16_t left, int16_t right)
{
bool result = left > right;
debug("CMP_SGT16 %d = %d > %d\n", result, left, right);
return result;
}
bool CMP_SGT32(int32_t left, int32_t right)
{
bool result = left > right;
debug("CMP_SGT32 %d = %d > %d\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_CMP_UGT: [("left", "expr"), ("right", "expr")] */
bool CMP_UGT(REGTYPE left, REGTYPE right)
{
bool result = left > right;
debug("CMP_UGT %d = " FMT_REG " > " FMT_REG "\n", result, left, right);
return result;
}
/* LowLevelILOperation.LLIL_TEST_BIT: [("left", "expr"), ("right", "expr")] */
bool TEST_BIT(REGTYPE value, REGTYPE mask)
{
bool result = !!(value & mask);
debug("TEST_BIT %d = bool(" FMT_REG " & " FMT_REG ")\n", result, value, mask);
return result;
}
/* LowLevelILOperation.LLIL_BOOL_TO_INT: [("src", "expr")] */
/* LowLevelILOperation.LLIL_ADD_OVERFLOW: [("left", "expr"), ("right", "expr")] */
bool ADD_OVERFLOW8(uint8_t a, uint8_t b)
{
bool result = a >= 256 - b;
debug("ADD_OVERFLOW8 %d (when %d + %d)\n", result, a, b);
return result;
}
bool ADD_OVERFLOW16(uint16_t a, uint16_t b)
{
bool result = a >= 65536 - b;
debug("ADD_OVERFLOW16 %d (when %d + %d)\n", result, a, b);
return result;
}
bool ADD_OVERFLOW32(uint32_t a, uint32_t b)
{
bool result = a >= 4294967296 - b;
debug("ADD_OVERFLOW32 %d (when %d + %d)\n", result, a, b);
return result;
}
/* LowLevelILOperation.LLIL_SYSCALL: [] */
/* LowLevelILOperation.LLIL_INTRINSIC: [("output", "reg_or_flag_list"), ("intrinsic", "intrinsic"), ("param", "expr")] */
/* LowLevelILOperation.LLIL_INTRINSIC_SSA: [("output", "reg_or_flag_ssa_list"), ("intrinsic", "intrinsic"), ("param", "expr")] */
/* LowLevelILOperation.LLIL_BP: [] */
/* LowLevelILOperation.LLIL_TRAP: [("vector", "int")] */
/* LowLevelILOperation.LLIL_UNDEF: [] */
/* LowLevelILOperation.LLIL_UNIMPL: [] */
REGTYPE UNIMPL()
{
debug("UNIMPL");
exit(-1);
return 0;
}
REGTYPE UNIMPL(REGTYPE)
{
debug("UNIMPL");
return 0;
}
/* LowLevelILOperation.LLIL_UNIMPL_MEM: [("src", "expr")] */
/* LowLevelILOperation.LLIL_FADD: [("left", "expr"), ("right", "expr")] */
uint32_t FADD(uint32_t a, uint32_t b)
{
float af = *(float *)&a;
float bf = *(float *)&b;
float cf = af + bf;
debug("FADD %f = %f + %f\n", cf, af, bf);
return *(uint32_t *)&cf;
}
/* LowLevelILOperation.LLIL_FSUB: [("left", "expr"), ("right", "expr")] */
uint32_t FSUB(uint32_t a, uint32_t b)
{
float af = *(float *)&a;
float bf = *(float *)&b;
float cf = af - bf;
debug("FSUB %f = %f - %f\n", cf, af, bf);
return *(uint32_t *)&cf;
}
/* LowLevelILOperation.LLIL_FMUL: [("left", "expr"), ("right", "expr")] */
uint32_t FMUL(uint32_t a, uint32_t b)
{
float af = *(float *)&a;
float bf = *(float *)&b;
float cf = af * bf;
debug("FMUL %f = %f * %f\n", cf, af, bf);
return *(uint32_t *)&cf;
}
/* LowLevelILOperation.LLIL_FDIV: [("left", "expr"), ("right", "expr")] */
uint32_t FDIV(uint32_t a, uint32_t b)
{
float af = *(float *)&a;
float bf = *(float *)&b;
float cf = af / bf;
debug("FDIV %f = %f / %f\n", cf, af, bf);
return *(uint32_t *)&cf;
}
/* LowLevelILOperation.LLIL_FSQRT: [("src", "expr")] */
/* LowLevelILOperation.LLIL_FNEG: [("src", "expr")] */
/* LowLevelILOperation.LLIL_FABS: [("src", "expr")] */
/* LowLevelILOperation.LLIL_FLOAT_TO_INT: [("src", "expr")] */
/* LowLevelILOperation.LLIL_INT_TO_FLOAT: [("src", "expr")] */
/* LowLevelILOperation.LLIL_FLOAT_CONV: [("src", "expr")] */
uint32_t FLOAT_CONV32(uint32_t input)
{
//float result = *(float *)&input;
//debug("FCONV32 %f = 0x%08X\n", result, input);
uint32_t result = input;
debug("FCONV32 0x%08X = 0x%08X\n", result, input);
return result;
}
/* LowLevelILOperation.LLIL_ROUND_TO_INT: [("src", "expr")] */
/* LowLevelILOperation.LLIL_FLOOR: [("src", "expr")] */
/* LowLevelILOperation.LLIL_CEIL: [("src", "expr")] */
/* LowLevelILOperation.LLIL_FTRUNC: [("src", "expr")] */
/* LowLevelILOperation.LLIL_FCMP_E: [("left", "expr"), ("right", "expr")] */
/* LowLevelILOperation.LLIL_FCMP_NE: [("left", "expr"), ("right", "expr")] */
/* LowLevelILOperation.LLIL_FCMP_LT: [("left", "expr"), ("right", "expr")] */
/* LowLevelILOperation.LLIL_FCMP_LE: [("left", "expr"), ("right", "expr")] */
/* LowLevelILOperation.LLIL_FCMP_GE: [("left", "expr"), ("right", "expr")] */
/* LowLevelILOperation.LLIL_FCMP_GT: [("left", "expr"), ("right", "expr")] */
/* LowLevelILOperation.LLIL_FCMP_O: [("left", "expr"), ("right", "expr")] */
/* LowLevelILOperation.LLIL_FCMP_UO: [("left", "expr"), ("right", "expr")] */
/* LowLevelILOperation.LLIL_SET_REG_SSA: [("dest", "reg_ssa"), ("src", "expr")] */
/* LowLevelILOperation.LLIL_SET_REG_SSA_PARTIAL: [("full_reg", "reg_ssa"), ("dest", "reg"), ("src", "expr")] */
/* LowLevelILOperation.LLIL_SET_REG_SPLIT_SSA: [("hi", "expr"), ("lo", "expr"), ("src", "expr")] */
/* LowLevelILOperation.LLIL_SET_REG_STACK_REL_SSA: [("stack", "expr"), ("dest", "expr"), ("top", "expr"), ("src", "expr")] */
/* LowLevelILOperation.LLIL_SET_REG_STACK_ABS_SSA: [("stack", "expr"), ("dest", "reg"), ("src", "expr")] */
/* LowLevelILOperation.LLIL_REG_SPLIT_DEST_SSA: [("dest", "reg_ssa")] */
/* LowLevelILOperation.LLIL_REG_STACK_DEST_SSA: [("src", "reg_stack_ssa_dest_and_src")] */
/* LowLevelILOperation.LLIL_REG_SSA: [("src", "reg_ssa")] */
/* LowLevelILOperation.LLIL_REG_SSA_PARTIAL: [("full_reg", "reg_ssa"), ("src", "reg")] */
/* LowLevelILOperation.LLIL_REG_SPLIT_SSA: [("hi", "reg_ssa"), ("lo", "reg_ssa")] */
/* LowLevelILOperation.LLIL_REG_STACK_REL_SSA: [("stack", "reg_stack_ssa"), ("src", "expr"), ("top", "expr")] */
/* LowLevelILOperation.LLIL_REG_STACK_ABS_SSA: [("stack", "reg_stack_ssa"), ("src", "reg")] */
/* LowLevelILOperation.LLIL_REG_STACK_FREE_REL_SSA: [("stack", "expr"), ("dest", "expr"), ("top", "expr")] */
/* LowLevelILOperation.LLIL_REG_STACK_FREE_ABS_SSA: [("stack", "expr"), ("dest", "reg")] */
/* LowLevelILOperation.LLIL_SET_FLAG_SSA: [("dest", "flag_ssa"), ("src", "expr")] */
/* LowLevelILOperation.LLIL_FLAG_SSA: [("src", "flag_ssa")] */
/* LowLevelILOperation.LLIL_FLAG_BIT_SSA: [("src", "flag_ssa"), ("bit", "int")] */
/* LowLevelILOperation.LLIL_CALL_SSA: [("output", "expr"), ("dest", "expr"), ("stack", "expr"), ("param", "expr")] */
/* LowLevelILOperation.LLIL_SYSCALL_SSA: [("output", "expr"), ("stack", "expr"), ("param", "expr")] */
/* LowLevelILOperation.LLIL_TAILCALL_SSA: [("output", "expr"), ("dest", "expr"), ("stack", "expr"), ("param", "expr")] */
/* LowLevelILOperation.LLIL_CALL_OUTPUT_SSA: [("dest_memory", "int"), ("dest", "reg_ssa_list")] */
/* LowLevelILOperation.LLIL_CALL_STACK_SSA: [("src", "reg_ssa"), ("src_memory", "int")] */
/* LowLevelILOperation.LLIL_CALL_PARAM: [("src", "expr_list")] */
/* LowLevelILOperation.LLIL_LOAD_SSA: [("src", "expr"), ("src_memory", "int")] */
/* LowLevelILOperation.LLIL_STORE_SSA: [("dest", "expr"), ("dest_memory", "int"), ("src_memory", "int"), ("src", "expr")] */
/* LowLevelILOperation.LLIL_REG_PHI: [("dest", "reg_ssa"), ("src", "reg_ssa_list")] */
/* LowLevelILOperation.LLIL_REG_STACK_PHI: [("dest", "reg_stack_ssa"), ("src", "reg_stack_ssa_list")] */
/* LowLevelILOperation.LLIL_FLAG_PHI: [("dest", "flag_ssa"), ("src", "flag_ssa_list")] */
/* LowLevelILOperation.LLIL_MEM_PHI: [("dest_memory", "int"), ("src_memory", "int_list")] */
void runtime_comment(const char *msg)
{
#if defined(DEBUG_RUNTIME_ALL) || defined(DEBUG_RUNTIME_SETS)
//printf("\x1B[36m%s\x1B[0m", msg);
printf("\n%s", msg);
printf("----------------\n");
#endif
}
#ifdef ARCH_ARM
void __aeabi_idiv()
{
SREGTYPE a = reg_get_uint32("r0");
SREGTYPE b = reg_get_uint32("r1");
SREGTYPE result = a / b;
REG_SET_ADDR("r0", result);
debug("__aeabi_idiv() returns " FMT_SREG " = " FMT_SREG " / " FMT_SREG "\n", result, a, b);
}
void __aeabi_idivmod()
{
SREGTYPE a = reg_get_uint32("r0");
SREGTYPE b = reg_get_uint32("r1");
SREGTYPE q = a / b;
SREGTYPE r = a % b;
REG_SET_ADDR("r0", q);
REG_SET_ADDR("r1", r);
debug("__aeabi_idivmod() returns q=" FMT_SREG " r=" FMT_SREG " " FMT_SREG " %% " FMT_SREG "\n",
q, r, a, b);
}
#endif
| 30.085736 | 144 | 0.643154 | [
"vector"
] |
bfb0a3720c813c33aad7aa895125bbfce0878b91 | 2,531 | cpp | C++ | Source/AboutWindow.cpp | sergipa/The-Creator-3D | 69acf8a4ac169f96ef8ed15e6eb1a47c3a372bda | [
"MIT"
] | 6 | 2017-11-24T06:15:40.000Z | 2021-01-05T04:47:21.000Z | Source/AboutWindow.cpp | sergipa/The-Creator-3D | 69acf8a4ac169f96ef8ed15e6eb1a47c3a372bda | [
"MIT"
] | null | null | null | Source/AboutWindow.cpp | sergipa/The-Creator-3D | 69acf8a4ac169f96ef8ed15e6eb1a47c3a372bda | [
"MIT"
] | 3 | 2017-11-21T13:11:47.000Z | 2019-07-01T09:22:49.000Z | #include "AboutWindow.h"
AboutWindow::AboutWindow()
{
active = false;
window_name = "About";
}
AboutWindow::~AboutWindow()
{
}
void AboutWindow::DrawWindow()
{
ImGui::Begin(window_name.c_str(), &active,
ImGuiWindowFlags_AlwaysAutoResize |
ImGuiWindowFlags_NoCollapse |
ImGuiWindowFlags_ShowBorders);
ImGui::SetWindowFontScale(1.1f);
ImGui::Text("The Creator v0.3");
ImGui::SetWindowFontScale(1);
ImGui::Text("The next generation 3D Game Engine");
ImGui::Text("By Adria Martin & Sergi Perez");
ImGui::Spacing();
ImGui::Spacing();
ImGui::Text("3rd Party Libraries used:");
ImGui::BulletText("SDL 2.0.6");
ImGui::BulletText("SDL Mixer 2.0.0");
ImGui::BulletText("Cereal 1.2.2");
ImGui::BulletText("Glew 2.0.0");
ImGui::BulletText("ImGui 1.51");
ImGui::BulletText("MathGeoLib 1.5");
ImGui::BulletText("OpenGL 3.1");
ImGui::BulletText("Assimp 3.1.1");
ImGui::BulletText("Devil 1.7.8");
ImGui::Spacing();
ImGui::Spacing();
ImGui::Text("License:");
ImGui::Spacing();
ImGui::Text("MIT License");
ImGui::Spacing();
ImGui::Spacing();
ImGui::Text("Copyright (c) 2017 Sergi Perez & Adria Martin");
ImGui::Spacing();
ImGui::Spacing();
ImGui::Text("Permission is hereby granted, free of charge, to any person obtaining a copy");
ImGui::Text("of this software and associated documentation files(the 'Software'), to deal");
ImGui::Text("in the Software without restriction, including without limitation the rights");
ImGui::Text("to use, copy, modify, merge, publish, distribute, sublicense, and/or sell");
ImGui::Text("copies of the Software, and to permit persons to whom the Software is");
ImGui::Text("furnished to do so, subject to the following conditions :");
ImGui::Spacing();
ImGui::Spacing();
ImGui::Text("The above copyright notice and this permission notice shall be included in all");
ImGui::Text("copies or substantial portions of the Software.");
ImGui::Spacing();
ImGui::Spacing();
ImGui::Text("THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR");
ImGui::Text("IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,");
ImGui::Text("FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE");
ImGui::Text("AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER");
ImGui::Text("LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,");
ImGui::Text("OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE");
ImGui::Text("SOFTWARE.");
ImGui::End();
}
| 36.681159 | 95 | 0.720664 | [
"3d"
] |
bfb2699c51d2aad821b3448ab808ddf13d7c2636 | 4,025 | cpp | C++ | Algorithms/Recursion/Crossword Puzzle/solution.cpp | kitarp29/ds-algo-solutions | c06effdaec2ff014248ca399268934cd8a639b5a | [
"MIT"
] | 48 | 2020-12-04T17:48:47.000Z | 2022-02-26T17:56:52.000Z | Algorithms/Recursion/Crossword Puzzle/solution.cpp | kitarp29/ds-algo-solutions | c06effdaec2ff014248ca399268934cd8a639b5a | [
"MIT"
] | 465 | 2020-12-04T02:12:56.000Z | 2021-12-07T16:09:51.000Z | Algorithms/Recursion/Crossword Puzzle/solution.cpp | kitarp29/ds-algo-solutions | c06effdaec2ff014248ca399268934cd8a639b5a | [
"MIT"
] | 199 | 2020-12-04T02:39:56.000Z | 2021-12-07T10:10:50.000Z | #include<bits/stdc++.h>
using namespace std;
// checks all positions in the grid where it's possible to place the strings
bool placeString(vector<string>& grid, const string& l) {
int len = l.length();
bool placed = false;
// check the horizontal positions
// checking each row
for (int i = 0; i < 10; i++) {
if (placed)
break;
else
placed = true;
// checking each part of the row
for (int j = 0; j <= (10 - len); j++) {
placed = true;
for (int k = j; k < (len + j); k++) {
// wasn't able to be placed here, break
if (grid[i][k] == '+') {
placed = false;
break;
} else if (grid[i][k] == '-') {
// Continue
} else if (l[k - j] != grid[i][k]) {
// wasn't able to be placed here, break
placed = false;
break;
}
}
// if placed, update grid nd break
if (placed) {
for (int k = j; k < (len + j); k++)
grid[i][k] = l[k - j];
break;
}
}
}
// check the vertical positions
if (!placed) {
// now check each column
for (int i = 0; i < 10; i++) {
if (placed)
break;
else
placed = true;
// check each position in the column
for (int j = 0; j <= (10 - len); j++) {
placed = true;
for (int k = j; k < (len + j); k++) {
if (grid[k][i] == '+') {
placed = false;
break;
} else if (grid[k][i] == '-') {
} else if (l[k - j] != grid[k][i]) {
placed = false;
break;
}
}
if (placed) {
for (int k = j; k < (len + j); k++)
grid[k][i] = l[k - j];
break;
}
}
}
}
return placed;
}
// tries to place the strings in the given order
vector<string> finishGrid(vector<string> grid, vector<string> placesNames) {
vector<string> completedGrid;
int len = placesNames.size();
bool success = true;
for (int i = 0; i < len; i++) {
string l = placesNames[i];
if (!placeString(grid, l)) {
success = false;
completedGrid.push_back("nope");
break;
}
}
if (success)
completedGrid = grid;
return completedGrid;
}
// Driver Code
int main() {
// Input of grid and String of words
vector<string> grid;
string s;
for (int i = 0; i < 10; i++) {
cin >> s;
grid.push_back(s);
}
cin >> s;
vector<string> placesNames;
int len = s.length();
int start = 0;
// find ; as words are seperated by ; only
// initialing word to temp
for (int i = 0; i < len; i++) {
if (s[i] == ';') {
string temp(s.begin() + start, s.begin() + i);
placesNames.push_back(temp);
start = i + 1;
}
}
string temp(s.begin() + start, s.end());
placesNames.push_back(temp);
// sorting the letters of word
sort(placesNames.begin(), placesNames.end());
vector<string> finishedGrid;
// run loop for all permutations
do {
finishedGrid = finishGrid(grid, placesNames);
if (finishedGrid[0] != "nope")
break;
} while (next_permutation(placesNames.begin(), placesNames.end()));
// Display output
for (int i = 0; i < 10; i++)
cout << finishedGrid[i] << endl;
return 0;
}
| 25.314465 | 76 | 0.412919 | [
"vector"
] |
bfb27578fbc482a224d4a84749f4038ecf5d4a08 | 2,270 | hpp | C++ | btcnew/node/voting.hpp | thebitcoinnew/btcnew-node | 59c8e3885ff269befaf3a8f82fe63a0c674cc27b | [
"BSD-2-Clause"
] | null | null | null | btcnew/node/voting.hpp | thebitcoinnew/btcnew-node | 59c8e3885ff269befaf3a8f82fe63a0c674cc27b | [
"BSD-2-Clause"
] | null | null | null | btcnew/node/voting.hpp | thebitcoinnew/btcnew-node | 59c8e3885ff269befaf3a8f82fe63a0c674cc27b | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include <btcnew/lib/config.hpp>
#include <btcnew/lib/numbers.hpp>
#include <btcnew/lib/utility.hpp>
#include <btcnew/secure/common.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/random_access_index.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/thread.hpp>
#include <condition_variable>
#include <deque>
#include <mutex>
namespace btcnew
{
class node;
class vote_generator final
{
public:
vote_generator (btcnew::node &);
void add (btcnew::block_hash const &);
void stop ();
private:
void run ();
void send (btcnew::unique_lock<std::mutex> &);
btcnew::node & node;
std::mutex mutex;
btcnew::condition_variable condition;
std::deque<btcnew::block_hash> hashes;
btcnew::network_params network_params;
bool stopped{ false };
bool started{ false };
boost::thread thread;
friend std::unique_ptr<seq_con_info_component> collect_seq_con_info (vote_generator & vote_generator, const std::string & name);
};
std::unique_ptr<seq_con_info_component> collect_seq_con_info (vote_generator & vote_generator, const std::string & name);
class cached_votes final
{
public:
std::chrono::steady_clock::time_point time;
btcnew::block_hash hash;
std::vector<std::shared_ptr<btcnew::vote>> votes;
};
class votes_cache final
{
public:
void add (std::shared_ptr<btcnew::vote> const &);
std::vector<std::shared_ptr<btcnew::vote>> find (btcnew::block_hash const &);
void remove (btcnew::block_hash const &);
private:
std::mutex cache_mutex;
boost::multi_index_container<
btcnew::cached_votes,
boost::multi_index::indexed_by<
boost::multi_index::ordered_non_unique<boost::multi_index::member<btcnew::cached_votes, std::chrono::steady_clock::time_point, &btcnew::cached_votes::time>>,
boost::multi_index::hashed_unique<boost::multi_index::member<btcnew::cached_votes, btcnew::block_hash, &btcnew::cached_votes::hash>>>>
cache;
btcnew::network_params network_params;
friend std::unique_ptr<seq_con_info_component> collect_seq_con_info (votes_cache & votes_cache, const std::string & name);
};
std::unique_ptr<seq_con_info_component> collect_seq_con_info (votes_cache & votes_cache, const std::string & name);
}
| 31.09589 | 158 | 0.771806 | [
"vector"
] |
bfb2c274a3c17e76317eaa4fa0164ccfc00e2696 | 9,306 | hpp | C++ | include/microlife/detail/parser.hpp | qingl812/microlife-json | 69042e12a7c30941e701e1863e92d450713f216c | [
"MIT"
] | null | null | null | include/microlife/detail/parser.hpp | qingl812/microlife-json | 69042e12a7c30941e701e1863e92d450713f216c | [
"MIT"
] | null | null | null | include/microlife/detail/parser.hpp | qingl812/microlife-json | 69042e12a7c30941e701e1863e92d450713f216c | [
"MIT"
] | null | null | null | #pragma once
#include "macro_scope.hpp" // json_assert()
#include <memory> // std::unique_ptr
#include <stack> // stack
namespace microlife {
namespace detail {
/***
* @brief JSON parser
* @details Parses JSON string and returns a tree of nodes
* @author qingl
* @date 2022_04_09
*/
template <template <typename> class LexerType, typename JsonType>
class parser {
private:
using basic_json = JsonType;
using boolean_t = typename basic_json::boolean_t;
using number_t = typename basic_json::number_t;
using string_t = typename basic_json::string_t;
using array_t = typename basic_json::array_t;
using object_t = typename basic_json::object_t;
using value_t = typename basic_json::value_t;
using lexer = LexerType<basic_json>;
using token_t = ::microlife::detail::token_t;
using stack_token_t = std::stack<std::pair<token_t, basic_json*>>;
private:
lexer m_lexer; // lexer
std::stack<token_t> m_stack_token; // stack for tokens
std::stack<basic_json> m_stack_json; // stack for json values
public:
parser() {}
~parser() {}
bool parse(const string_t& str, basic_json& json) {
m_lexer.init(str.begin(), str.end());
json_assert(m_stack_token.empty());
json_assert(m_stack_json.empty());
auto parse_json = basic_parse();
// clean stacks
while (!m_stack_token.empty())
m_stack_token.pop();
while (!m_stack_json.empty())
m_stack_json.pop();
if (parse_json != nullptr) {
json = std::move(*parse_json);
delete parse_json;
parse_json = nullptr;
return true;
} else
return false;
}
// private
JSON_PRIVATE_UNLESS_TESTED
basic_json* basic_parse() {
// literal_null
// 所有的值类型都是 literal_null
while (true) {
token_t token = m_lexer.scan();
switch (token) {
case token_t::end_of_input: {
if (m_stack_token.size() == 1 &&
m_stack_token.top() == token_t::literal_null &&
m_stack_json.size() == 1) {
return new basic_json(std::move(m_stack_json.top()));
}
return nullptr;
}
case token_t::end_array: {
token = token_t::literal_null;
auto json_array = parse_end_array();
if (json_array == nullptr)
return nullptr;
else {
m_stack_json.push(std::move(*json_array));
delete json_array;
}
break;
}
case token_t::end_object: {
token = token_t::literal_null;
auto json_object = parse_end_object();
if (json_object == nullptr)
return nullptr;
else {
m_stack_json.push(std::move(*json_object));
delete json_object;
}
break;
}
case token_t::literal_null:
token = token_t::literal_null;
m_stack_json.push(std::move(basic_json(nullptr)));
break;
case token_t::literal_true:
token = token_t::literal_null;
m_stack_json.push(std::move(basic_json(true)));
break;
case token_t::literal_false:
token = token_t::literal_null;
m_stack_json.push(std::move(basic_json(false)));
break;
case token_t::value_number:
token = token_t::literal_null;
m_stack_json.push(std::move(basic_json(m_lexer.get_number())));
break;
case token_t::value_string:
token = token_t::literal_null;
m_stack_json.push(std::move(basic_json(m_lexer.get_string())));
break;
case token_t::begin_array:
case token_t::begin_object:
case token_t::value_separator:
case token_t::name_separator:
break;
case token_t::parse_error:
default:
return nullptr;
}
m_stack_token.push(token);
}
}
// token 为值类型时,插入到 array 末尾
#define PUSH_VALUE_TO_ARRAY() \
do { \
m_stack_token.pop(); \
if (m_stack_json.empty()) \
return nullptr; \
array.push_back(std::move(m_stack_json.top())); \
m_stack_json.pop(); \
} while (0)
basic_json* parse_end_array() {
if (m_stack_token.empty())
return nullptr;
// 如果第一个 value
// 剩下的一定是 ,' + value
// 最后则是 '['
array_t array;
if (m_stack_token.top() == token_t::literal_null) {
PUSH_VALUE_TO_ARRAY();
while (m_stack_token.size() >= 2) {
if (m_stack_token.top() == token_t::begin_array)
break;
// ,' + value
if (m_stack_token.top() != token_t::value_separator)
return nullptr;
m_stack_token.pop();
if (m_stack_token.top() != token_t::literal_null)
return nullptr;
PUSH_VALUE_TO_ARRAY();
}
}
// '['
if (m_stack_token.empty() ||
m_stack_token.top() != token_t::begin_array)
return nullptr;
m_stack_token.pop();
return new basic_json(std::move(array));
}
// token 为值类型时,插入到 object 末尾
#define PUSH_VALUE_TO_OBJECT() \
do { \
m_stack_token.pop(); \
if (m_stack_token.top() != token_t::name_separator) \
return nullptr; \
m_stack_token.pop(); \
if (m_stack_token.top() != token_t::literal_null) \
return nullptr; \
m_stack_token.pop(); \
/* value */ \
if (m_stack_json.empty()) \
return nullptr; \
auto value = std::move(m_stack_json.top()); \
m_stack_json.pop(); \
/* key */ \
if (m_stack_json.empty()) \
return nullptr; \
auto key = std::move(m_stack_json.top()); \
m_stack_json.pop(); \
/* key.type == string */ \
if (!key.is_string()) \
return nullptr; \
/* https://stackoverflow.com/questions/7397934/ \
calling-template-function-within-template-class */ \
object.emplace(std::move(key.template get<string_t&>()), \
std::move(value)); \
} while (0)
basic_json* parse_end_object() {
if (m_stack_token.empty())
return nullptr;
// 如果第一个 value : key
// 剩下的一定是 ,' + value : key
// 最后则是 '{'
object_t object;
if (m_stack_token.size() >= 4 &&
m_stack_token.top() == token_t::literal_null) {
PUSH_VALUE_TO_OBJECT();
while (m_stack_token.size() >= 4) {
if (m_stack_token.top() == token_t::begin_object)
break;
// ,' + value : key
if (m_stack_token.top() != token_t::value_separator)
return nullptr;
m_stack_token.pop();
if (m_stack_token.top() != token_t::literal_null)
return nullptr;
PUSH_VALUE_TO_OBJECT();
}
}
// '{'
if (m_stack_token.empty() ||
m_stack_token.top() != token_t::begin_object)
return nullptr;
m_stack_token.pop();
return new basic_json(std::move(object));
}
#undef PUSH_VALUE_TO_ARRAY
#undef PUSH_VALUE_TO_OBJECT
};
} // namespace detail
} // namespace microlife
| 35.655172 | 80 | 0.441651 | [
"object"
] |
bfb5f5e6f4cfabedde4bbd9c963a24dec7ac4212 | 14,504 | cc | C++ | components/document/src/rich_text/common/RTCommonSource.cc | SBKarr/stappler | d9311cba0b0e9362be55feca39a866d7bccd6dff | [
"MIT"
] | 10 | 2015-06-16T16:52:53.000Z | 2021-04-15T09:21:22.000Z | components/document/src/rich_text/common/RTCommonSource.cc | SBKarr/stappler | d9311cba0b0e9362be55feca39a866d7bccd6dff | [
"MIT"
] | 3 | 2015-09-23T10:04:00.000Z | 2020-09-10T15:47:34.000Z | components/document/src/rich_text/common/RTCommonSource.cc | SBKarr/stappler | d9311cba0b0e9362be55feca39a866d7bccd6dff | [
"MIT"
] | 3 | 2018-11-11T00:37:49.000Z | 2020-09-07T03:04:31.000Z | // This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/**
Copyright (c) 2017 Roman Katuntsev <sbkarr@stappler.org>
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 "SPDefine.h"
#include "RTCommonSource.h"
#include "SPFilesystem.h"
#include "SPResource.h"
#include "SPThread.h"
#include "SPString.h"
#include "SPTextureCache.h"
#include "SPAssetLibrary.h"
NS_RT_BEGIN
SP_DECLARE_EVENT(CommonSource, "RichTextSource", onError);
SP_DECLARE_EVENT(CommonSource, "RichTextSource", onDocument);
String CommonSource::getPathForUrl(const String &url) {
auto dir = filesystem::writablePath("Documents");
filesystem::mkdir(dir);
return toString(dir, "/", string::stdlibHashUnsigned(url));
}
CommonSource::~CommonSource() { }
bool CommonSource::init() {
if (!FontController::init(FontFaceMap(), {"fonts/", "common/fonts/"}, [this] (const layout::FontSource *s, const String &str) -> Bytes {
if (str.compare(0, "document://"_len, "document://") == 0) {
auto doc = getDocument();
if (doc) {
return doc->getFileData(str.substr("document://"_len));
}
} else if (str.compare(0, "local://"_len, "local://") == 0) {
auto path = str.substr("local://"_len);
if (filesystem::exists(path)) {
return filesystem::readIntoMemory(path);
} else if (filesystem::exists("fonts/" + path)) {
return filesystem::readIntoMemory("fonts/" + path);
} else if (filesystem::exists("common/fonts/" + path)) {
return filesystem::readIntoMemory("common/fonts/" + path);
}
}
return Bytes();
}, false)) {
return false;
}
_documentAsset.setCallback(std::bind(&CommonSource::onDocumentAssetUpdated, this, std::placeholders::_1));
return true;
}
bool CommonSource::init(SourceAsset *asset, bool enabled) {
if (!init()) {
return false;
}
_enabled = enabled;
onDocumentAsset(asset);
return true;
}
void CommonSource::setHyphens(layout::HyphenMap *map) {
_hyphens = map;
}
layout::HyphenMap *CommonSource::getHyphens() const {
return _hyphens;
}
Document *CommonSource::getDocument() const {
return static_cast<Document *>(_document.get());
}
SourceAsset *CommonSource::getAsset() const {
return _documentAsset;
}
Map<String, CommonSource::AssetMeta> CommonSource::getExternalAssetMeta() const {
Map<String, CommonSource::AssetMeta> ret;
for (auto &it : _networkAssets) {
ret.emplace(it.first, it.second.meta);
}
return ret;
}
const Map<String, CommonSource::AssetData> &CommonSource::getExternalAssets() const {
return _networkAssets;
}
bool CommonSource::isReady() const {
return _document;
}
bool CommonSource::isActual() const {
if (!_document) {
return false;
}
if (!_documentAsset) {
return true;
}
if (_documentLoading) {
return false;
}
if (_loadedAssetMTime >= _documentAsset->getMTime()) {
return true;
} else if (_documentAsset->isUpdateAvailable()) {
return true;
}
return false;
}
bool CommonSource::isDocumentLoading() const {
return _documentLoading;
}
void CommonSource::refresh() {
updateDocument();
}
bool CommonSource::tryReadLock(Ref *ref) {
auto it = _readLocks.find(ref);
if (it != _readLocks.end()) {
if (it->second.acquired) {
++ it->second.count;
return true;
}
return false;
}
auto vec = getAssetsVec();
if (vec.empty()) {
_readLocks.emplace(ref, LockStruct{vec, this, 1, true});
return true;
}
if (SyncRWLock::tryReadLock(ref, vec)) {
_readLocks.emplace(ref, LockStruct{vec, this, 1, true});
return true;
}
return false;
}
void CommonSource::retainReadLock(Ref *ref, const Function<void()> &cb) {
auto it = _readLocks.find(ref);
if (it != _readLocks.end()) {
++ it->second.count;
if (it->second.acquired) {
cb();
} else {
it->second.waiters.emplace_back(cb);
}
return;
}
auto vec = getAssetsVec();
if (vec.empty()) {
_readLocks.emplace(ref, LockStruct{vec, this, 1, true});
cb();
} else {
_readLocks.emplace(ref, LockStruct{vec, this, 1, false, Vector<Function<void()>>{cb}});
SyncRWLock::retainReadLock(ref, vec, [this, ref, vec] {
auto it = _readLocks.find(ref);
if (it == _readLocks.end()) {
SyncRWLock::releaseReadLock(ref, vec);
} else {
it->second.acquired = true;
for (auto &cb : it->second.waiters) {
cb();
}
it->second.waiters.clear();
}
});
}
}
void CommonSource::releaseReadLock(Ref *ref) {
auto it = _readLocks.find(ref);
if (it != _readLocks.end()) {
if (it->second.acquired) {
if (it->second.count == 1) {
SyncRWLock::releaseReadLock(ref, it->second.vec);
_readLocks.erase(it);
} else {
-- it->second.count;
}
}
}
}
void CommonSource::setEnabled(bool val) {
if (_enabled != val) {
_enabled = val;
if (_enabled && _documentAsset) {
onDocumentAssetUpdated(data::Subscription::Flag((uint8_t)Asset::CacheDataUpdated));
}
}
}
bool CommonSource::isEnabled() const {
return _enabled;
}
void CommonSource::onDocumentAsset(SourceAsset *a) {
_documentAsset = a;
if (_documentAsset) {
_loadedAssetMTime = 0;
if (_enabled) {
_documentAsset->download();
}
onDocumentAssetUpdated(data::Subscription::Flag((uint8_t)Asset::FileUpdated));
}
}
void CommonSource::onDocumentAssetUpdated(data::Subscription::Flags f) {
if (f.hasFlag((uint8_t)Asset::DownloadFailed)) {
onError(this, Error::NetworkError);
}
if (_documentAsset->isDownloadAvailable() && !_documentAsset->isDownloadInProgress()) {
if (f.hasFlag((uint8_t)Asset::DownloadFailed)) {
if (isnan(_retryUpdate)) {
_retryUpdate = 20.0f;
}
} else {
if (_enabled) {
_documentAsset->download();
}
onUpdate(this);
}
}
if (_loadedAssetMTime < _documentAsset->getMTime()) {
tryLoadDocument();
} else if ((f.initial() && _loadedAssetMTime == 0) || f.hasFlag((uint8_t)Asset::Update::FileUpdated)) {
_loadedAssetMTime = 0;
tryLoadDocument();
}
if (f.hasFlag((uint8_t)Asset::FileUpdated) || f.hasFlag((uint8_t)Asset::DownloadSuccessful) || f.hasFlag((uint8_t)Asset::DownloadFailed)) {
onDocument(this, _documentAsset.get());
}
}
void CommonSource::tryLoadDocument() {
if (!_enabled) {
return;
}
if (!_documentAsset->tryLockDocument(_loadedAssetMTime)) {
return;
}
auto &thread = TextureCache::thread();
Rc<Document> *doc = new Rc<Document>(nullptr);
Rc<SourceAsset> *asset = new Rc<SourceAsset>(_documentAsset.get());
Set<String> *assets = new Set<String>();
_loadedAssetMTime = _documentAsset->getMTime();
_documentLoading = true;
onUpdate(this);
thread.perform([doc, asset, assets] (const thread::Task &) -> bool {
*doc = asset->get()->openDocument();
if (*doc) {
auto &pages = (*doc)->getContentPages();
for (auto &p_it : pages) {
for (auto &str : p_it.second.assets) {
assets->emplace(str);
}
}
}
return true;
}, [this, doc, asset, assets] (const thread::Task &, bool success) {
if (success && *doc) {
auto l = [this, doc, asset] {
_documentLoading = false;
asset->get()->releaseDocument();
onDocumentLoaded(doc->get());
delete doc;
delete asset;
};
if (onExternalAssets(doc->get(), *assets)) {
l();
} else {
waitForAssets(move(l));
}
}
delete assets;
}, this);
}
void CommonSource::onDocumentLoaded(Document *doc) {
if (_document != doc) {
_document = doc;
if (_document) {
_dirty = true;
_dirtyFlags = DirtyFontFace;
updateSource();
}
onDocument(this);
}
}
void CommonSource::acquireAsset(const String &url, const Function<void(SourceAsset *)> &fn) {
StringView urlView(url);
if (urlView.is("http://") || urlView.is("https://")) {
auto path = getPathForUrl(url);
auto lib = AssetLibrary::getInstance();
auto linkId = retain();
lib->getAsset([this, fn, linkId] (Asset *a) {
fn(Rc<SourceNetworkAsset>::create(a));
release(linkId);
}, url, path, config::getDocumentAssetTtl());
} else {
fn(nullptr);
}
}
bool CommonSource::isExternalAsset(Document *doc, const String &asset) {
bool isDocFile = doc->isFileExists(asset);
if (!isDocFile) {
StringView urlView(asset);
if (urlView.is("http://") || urlView.is("https://")) {
return true;
}
}
return false;
}
bool CommonSource::onExternalAssets(Document *doc, const Set<String> &assets) {
for (auto &it : assets) {
if (isExternalAsset(doc, it)) {
auto n_it = _networkAssets.find(it);
if (n_it == _networkAssets.end()) {
auto a_it = _networkAssets.emplace(it, AssetData{it}).first;
AssetData * data = &a_it->second;
data->asset.setCallback(std::bind(&CommonSource::onExternalAssetUpdated, this, data, std::placeholders::_1));
addAssetRequest(data);
acquireAsset(it, [this, data] (SourceAsset *a) {
if (a) {
data->asset = a;
if (data->asset->isReadAvailable()) {
if (data->asset->tryReadLock()) {
readExternalAsset(*data);
data->asset->releaseReadLock();
}
}
if (data->asset->isDownloadAvailable()) {
data->asset->download();
}
}
removeAssetRequest(data);
});
log::text("External asset", it);
}
}
}
return !hasAssetRequests();
}
void CommonSource::onExternalAssetUpdated(AssetData *a, data::Subscription::Flags f) {
if (f.hasFlag((uint8_t)Asset::Update::FileUpdated)) {
bool updated = false;
if (a->asset->tryReadLock()) {
if (readExternalAsset(*a)) {
updated = true;
}
a->asset->releaseReadLock();
}
if (updated) {
if (_document) {
_dirty = true;
}
onDocument(this);
}
}
}
bool CommonSource::readExternalAsset(AssetData &data) {
data.meta.type = data.asset->getContentType().str();
if (StringView(data.meta.type).starts_with("image/") || data.meta.type.empty()) {
auto tmpImg = data.meta.image;
size_t w = 0, h = 0;
if (data.asset->getImageSize(w, h)) {
data.meta.image.width = w;
data.meta.image.height = h;
}
if (data.meta.image.width != tmpImg.width || data.meta.image.height != tmpImg.height) {
return true;
}
} else if (StringView(data.meta.type).is("text/css")) {
auto d = data.asset->getData();
data.meta.css = Rc<layout::CssDocument>::create(StringView((const char *)d.data(), d.size()));
return true;
}
return false;
}
void CommonSource::updateDocument() {
if (_documentAsset && _loadedAssetMTime > 0) {
_loadedAssetMTime = 0;
}
tryLoadDocument();
}
void CommonSource::onSourceUpdated(FontSource *source) {
FontController::onSourceUpdated(source);
}
Rc<font::FontSource> CommonSource::makeSource(AssetMap && map, bool schedule) {
if (_document) {
FontFaceMap faceMap(_fontFaces);
auto &pages = _document->getContentPages();
for (auto &it : pages) {
font::FontSource::mergeFontFace(faceMap, it.second.fonts);
}
return Rc<font::FontSource>::create(std::move(faceMap), _callback, _scale, SearchDirs(_searchDir), std::move(map), false);
}
return Rc<font::FontSource>::create(FontFaceMap(_fontFaces), _callback, _scale, SearchDirs(_searchDir), std::move(map), false);
}
bool CommonSource::hasAssetRequests() const {
return !_assetRequests.empty();
}
void CommonSource::addAssetRequest(AssetData *data) {
_assetRequests.emplace(data);
}
void CommonSource::removeAssetRequest(AssetData *data) {
if (!_assetRequests.empty()) {
_assetRequests.erase(data);
if (_assetRequests.empty()) {
if (!_assetWaiters.empty()) {
auto w = move(_assetWaiters);
_assetWaiters.clear();
for (auto &it : w) {
it();
}
}
}
}
}
void CommonSource::waitForAssets(Function<void()> &&fn) {
_assetWaiters.emplace_back(move(fn));
}
Vector<SyncRWLock *> CommonSource::getAssetsVec() const {
Vector<SyncRWLock *> ret; ret.reserve(1 + _networkAssets.size());
if (_documentAsset) {
if (auto lock = _documentAsset->getRWLock()) {
ret.emplace_back(lock);
}
}
for (auto &it : _networkAssets) {
if (it.second.asset) {
if (auto lock = it.second.asset->getRWLock()) {
ret.emplace_back(lock);
}
}
}
return ret;
}
bool CommonSource::isFileExists(const StringView &url) const {
auto it = _networkAssets.find(url);
if (it != _networkAssets.end() && it->second.asset && it->second.asset->isReadAvailable()) {
return true;
}
if (_document) {
return _document->isFileExists(url);
}
return false;
}
Pair<uint16_t, uint16_t> CommonSource::getImageSize(const StringView &url) const {
auto it = _networkAssets.find(url);
if (it != _networkAssets.end()) {
if ((StringView(it->second.meta.type).starts_with("image/") || it->second.meta.type.empty()) && it->second.meta.image.width > 0 && it->second.meta.image.height > 0) {
return pair(it->second.meta.image.width, it->second.meta.image.height);
}
}
if (_document) {
return _document->getImageSize(url);
}
return Pair<uint16_t, uint16_t>(0, 0);
}
Bytes CommonSource::getImageData(const StringView &url) const {
auto it = _networkAssets.find(url);
if (it != _networkAssets.end()) {
if ((StringView(it->second.meta.type).starts_with("image/") || it->second.meta.type.empty()) && it->second.meta.image.width > 0 && it->second.meta.image.height > 0) {
return it->second.asset->getData();
}
}
if (_document) {
return _document->getImageData(url);
}
return Bytes();
}
void CommonSource::update(float dt) {
FontController::update(dt);
if (!isnan(_retryUpdate)) {
_retryUpdate -= dt;
if (_retryUpdate <= 0.0f) {
_retryUpdate = nan();
if (_enabled && _documentAsset && _documentAsset->isDownloadAvailable() && !_documentAsset->isDownloadInProgress()) {
_documentAsset->download();
}
}
}
}
NS_RT_END
| 26.612844 | 168 | 0.677675 | [
"vector"
] |
bfc834435de551e786cebe8fcc663413d795767f | 24,681 | cpp | C++ | llvm-5.0.1.src/lib/Target/X86/X86CmovConversion.cpp | ShawnLess/TBD | fc98e93b3462509022fdf403978cd82aa05c2331 | [
"Apache-2.0"
] | 60 | 2017-12-21T06:49:58.000Z | 2022-02-24T09:43:52.000Z | llvm-5.0.1.src/lib/Target/X86/X86CmovConversion.cpp | ShawnLess/TBD | fc98e93b3462509022fdf403978cd82aa05c2331 | [
"Apache-2.0"
] | null | null | null | llvm-5.0.1.src/lib/Target/X86/X86CmovConversion.cpp | ShawnLess/TBD | fc98e93b3462509022fdf403978cd82aa05c2331 | [
"Apache-2.0"
] | 17 | 2017-12-20T09:54:56.000Z | 2021-06-24T05:39:36.000Z | //====-- X86CmovConversion.cpp - Convert Cmov to Branch -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file implements a pass that converts X86 cmov instructions into branch
/// when profitable. This pass is conservative, i.e., it applies transformation
/// if and only if it can gaurantee a gain with high confidence.
///
/// Thus, the optimization applies under the following conditions:
/// 1. Consider as a candidate only CMOV in most inner loop, assuming that
/// most hotspots are represented by these loops.
/// 2. Given a group of CMOV instructions, that are using same EFLAGS def
/// instruction:
/// a. Consider them as candidates only if all have same code condition or
/// opposite one, to prevent generating more than one conditional jump
/// per EFLAGS def instruction.
/// b. Consider them as candidates only if all are profitable to be
/// converted, assuming that one bad conversion may casue a degradation.
/// 3. Apply conversion only for loop that are found profitable and only for
/// CMOV candidates that were found profitable.
/// a. Loop is considered profitable only if conversion will reduce its
/// depth cost by some thrishold.
/// b. CMOV is considered profitable if the cost of its condition is higher
/// than the average cost of its true-value and false-value by 25% of
/// branch-misprediction-penalty, this to assure no degredassion even
/// with 25% branch misprediction.
///
/// Note: This pass is assumed to run on SSA machine code.
//===----------------------------------------------------------------------===//
//
// External interfaces:
// FunctionPass *llvm::createX86CmovConverterPass();
// bool X86CmovConverterPass::runOnMachineFunction(MachineFunction &MF);
//
#include "X86.h"
#include "X86InstrInfo.h"
#include "X86Subtarget.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/TargetSchedule.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
#define DEBUG_TYPE "x86-cmov-converter"
STATISTIC(NumOfSkippedCmovGroups, "Number of unsupported CMOV-groups");
STATISTIC(NumOfCmovGroupCandidate, "Number of CMOV-group candidates");
STATISTIC(NumOfLoopCandidate, "Number of CMOV-conversion profitable loops");
STATISTIC(NumOfOptimizedCmovGroups, "Number of optimized CMOV-groups");
namespace {
// This internal switch can be used to turn off the cmov/branch optimization.
static cl::opt<bool>
EnableCmovConverter("x86-cmov-converter",
cl::desc("Enable the X86 cmov-to-branch optimization."),
cl::init(true), cl::Hidden);
/// Converts X86 cmov instructions into branches when profitable.
class X86CmovConverterPass : public MachineFunctionPass {
public:
X86CmovConverterPass() : MachineFunctionPass(ID) {}
~X86CmovConverterPass() {}
StringRef getPassName() const override { return "X86 cmov Conversion"; }
bool runOnMachineFunction(MachineFunction &MF) override;
void getAnalysisUsage(AnalysisUsage &AU) const override;
private:
/// Pass identification, replacement for typeid.
static char ID;
const MachineRegisterInfo *MRI;
const TargetInstrInfo *TII;
TargetSchedModel TSchedModel;
/// List of consecutive CMOV instructions.
typedef SmallVector<MachineInstr *, 2> CmovGroup;
typedef SmallVector<CmovGroup, 2> CmovGroups;
/// Collect all CMOV-group-candidates in \p CurrLoop and update \p
/// CmovInstGroups accordingly.
///
/// \param CurrLoop Loop being processed.
/// \param CmovInstGroups List of consecutive CMOV instructions in CurrLoop.
/// \returns true iff it found any CMOV-group-candidate.
bool collectCmovCandidates(MachineLoop *CurrLoop, CmovGroups &CmovInstGroups);
/// Check if it is profitable to transform each CMOV-group-candidates into
/// branch. Remove all groups that are not profitable from \p CmovInstGroups.
///
/// \param CurrLoop Loop being processed.
/// \param CmovInstGroups List of consecutive CMOV instructions in CurrLoop.
/// \returns true iff any CMOV-group-candidate remain.
bool checkForProfitableCmovCandidates(MachineLoop *CurrLoop,
CmovGroups &CmovInstGroups);
/// Convert the given list of consecutive CMOV instructions into a branch.
///
/// \param Group Consecutive CMOV instructions to be converted into branch.
void convertCmovInstsToBranches(SmallVectorImpl<MachineInstr *> &Group) const;
};
char X86CmovConverterPass::ID = 0;
void X86CmovConverterPass::getAnalysisUsage(AnalysisUsage &AU) const {
MachineFunctionPass::getAnalysisUsage(AU);
AU.addRequired<MachineLoopInfo>();
}
bool X86CmovConverterPass::runOnMachineFunction(MachineFunction &MF) {
if (skipFunction(*MF.getFunction()))
return false;
if (!EnableCmovConverter)
return false;
DEBUG(dbgs() << "********** " << getPassName() << " : " << MF.getName()
<< "**********\n");
bool Changed = false;
MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
const TargetSubtargetInfo &STI = MF.getSubtarget();
MRI = &MF.getRegInfo();
TII = STI.getInstrInfo();
TSchedModel.init(STI.getSchedModel(), &STI, TII);
//===--------------------------------------------------------------------===//
// Algorithm
// ---------
// For each inner most loop
// collectCmovCandidates() {
// Find all CMOV-group-candidates.
// }
//
// checkForProfitableCmovCandidates() {
// * Calculate both loop-depth and optimized-loop-depth.
// * Use these depth to check for loop transformation profitability.
// * Check for CMOV-group-candidate transformation profitability.
// }
//
// For each profitable CMOV-group-candidate
// convertCmovInstsToBranches() {
// * Create FalseBB, SinkBB, Conditional branch to SinkBB.
// * Replace each CMOV instruction with a PHI instruction in SinkBB.
// }
//
// Note: For more details, see each function description.
//===--------------------------------------------------------------------===//
for (MachineBasicBlock &MBB : MF) {
MachineLoop *CurrLoop = MLI.getLoopFor(&MBB);
// Optimize only inner most loops.
if (!CurrLoop || CurrLoop->getHeader() != &MBB ||
!CurrLoop->getSubLoops().empty())
continue;
// List of consecutive CMOV instructions to be processed.
CmovGroups CmovInstGroups;
if (!collectCmovCandidates(CurrLoop, CmovInstGroups))
continue;
if (!checkForProfitableCmovCandidates(CurrLoop, CmovInstGroups))
continue;
Changed = true;
for (auto &Group : CmovInstGroups)
convertCmovInstsToBranches(Group);
}
return Changed;
}
bool X86CmovConverterPass::collectCmovCandidates(MachineLoop *CurrLoop,
CmovGroups &CmovInstGroups) {
//===--------------------------------------------------------------------===//
// Collect all CMOV-group-candidates and add them into CmovInstGroups.
//
// CMOV-group:
// CMOV instructions, in same MBB, that uses same EFLAGS def instruction.
//
// CMOV-group-candidate:
// CMOV-group where all the CMOV instructions are
// 1. consecutive.
// 2. have same condition code or opposite one.
// 3. have only operand registers (X86::CMOVrr).
//===--------------------------------------------------------------------===//
// List of possible improvement (TODO's):
// --------------------------------------
// TODO: Add support for X86::CMOVrm instructions.
// TODO: Add support for X86::SETcc instructions.
// TODO: Add support for CMOV-groups with non consecutive CMOV instructions.
//===--------------------------------------------------------------------===//
// Current processed CMOV-Group.
CmovGroup Group;
for (auto *MBB : CurrLoop->getBlocks()) {
Group.clear();
// Condition code of first CMOV instruction current processed range and its
// opposite condition code.
X86::CondCode FirstCC, FirstOppCC;
// Indicator of a non CMOVrr instruction in the current processed range.
bool FoundNonCMOVInst = false;
// Indicator for current processed CMOV-group if it should be skipped.
bool SkipGroup = false;
for (auto &I : *MBB) {
X86::CondCode CC = X86::getCondFromCMovOpc(I.getOpcode());
// Check if we found a X86::CMOVrr instruction.
if (CC != X86::COND_INVALID && !I.mayLoad()) {
if (Group.empty()) {
// We found first CMOV in the range, reset flags.
FirstCC = CC;
FirstOppCC = X86::GetOppositeBranchCondition(CC);
FoundNonCMOVInst = false;
SkipGroup = false;
}
Group.push_back(&I);
// Check if it is a non-consecutive CMOV instruction or it has different
// condition code than FirstCC or FirstOppCC.
if (FoundNonCMOVInst || (CC != FirstCC && CC != FirstOppCC))
// Mark the SKipGroup indicator to skip current processed CMOV-Group.
SkipGroup = true;
continue;
}
// If Group is empty, keep looking for first CMOV in the range.
if (Group.empty())
continue;
// We found a non X86::CMOVrr instruction.
FoundNonCMOVInst = true;
// Check if this instruction define EFLAGS, to determine end of processed
// range, as there would be no more instructions using current EFLAGS def.
if (I.definesRegister(X86::EFLAGS)) {
// Check if current processed CMOV-group should not be skipped and add
// it as a CMOV-group-candidate.
if (!SkipGroup)
CmovInstGroups.push_back(Group);
else
++NumOfSkippedCmovGroups;
Group.clear();
}
}
// End of basic block is considered end of range, check if current processed
// CMOV-group should not be skipped and add it as a CMOV-group-candidate.
if (Group.empty())
continue;
if (!SkipGroup)
CmovInstGroups.push_back(Group);
else
++NumOfSkippedCmovGroups;
}
NumOfCmovGroupCandidate += CmovInstGroups.size();
return !CmovInstGroups.empty();
}
/// \returns Depth of CMOV instruction as if it was converted into branch.
/// \param TrueOpDepth depth cost of CMOV true value operand.
/// \param FalseOpDepth depth cost of CMOV false value operand.
static unsigned getDepthOfOptCmov(unsigned TrueOpDepth, unsigned FalseOpDepth) {
//===--------------------------------------------------------------------===//
// With no info about branch weight, we assume 50% for each value operand.
// Thus, depth of optimized CMOV instruction is the rounded up average of
// its True-Operand-Value-Depth and False-Operand-Value-Depth.
//===--------------------------------------------------------------------===//
return (TrueOpDepth + FalseOpDepth + 1) / 2;
}
bool X86CmovConverterPass::checkForProfitableCmovCandidates(
MachineLoop *CurrLoop, CmovGroups &CmovInstGroups) {
struct DepthInfo {
/// Depth of original loop.
unsigned Depth;
/// Depth of optimized loop.
unsigned OptDepth;
};
/// Number of loop iterations to calculate depth for ?!
static const unsigned LoopIterations = 2;
DenseMap<MachineInstr *, DepthInfo> DepthMap;
DepthInfo LoopDepth[LoopIterations] = {{0, 0}, {0, 0}};
enum { PhyRegType = 0, VirRegType = 1, RegTypeNum = 2 };
/// For each register type maps the register to its last def instruction.
DenseMap<unsigned, MachineInstr *> RegDefMaps[RegTypeNum];
/// Maps register operand to its def instruction, which can be nullptr if it
/// is unknown (e.g., operand is defined outside the loop).
DenseMap<MachineOperand *, MachineInstr *> OperandToDefMap;
// Set depth of unknown instruction (i.e., nullptr) to zero.
DepthMap[nullptr] = {0, 0};
SmallPtrSet<MachineInstr *, 4> CmovInstructions;
for (auto &Group : CmovInstGroups)
CmovInstructions.insert(Group.begin(), Group.end());
//===--------------------------------------------------------------------===//
// Step 1: Calculate instruction depth and loop depth.
// Optimized-Loop:
// loop with CMOV-group-candidates converted into branches.
//
// Instruction-Depth:
// instruction latency + max operand depth.
// * For CMOV instruction in optimized loop the depth is calculated as:
// CMOV latency + getDepthOfOptCmov(True-Op-Depth, False-Op-depth)
// TODO: Find a better way to estimate the latency of the branch instruction
// rather than using the CMOV latency.
//
// Loop-Depth:
// max instruction depth of all instructions in the loop.
// Note: instruction with max depth represents the critical-path in the loop.
//
// Loop-Depth[i]:
// Loop-Depth calculated for first `i` iterations.
// Note: it is enough to calculate depth for up to two iterations.
//
// Depth-Diff[i]:
// Number of cycles saved in first 'i` iterations by optimizing the loop.
//===--------------------------------------------------------------------===//
for (unsigned I = 0; I < LoopIterations; ++I) {
DepthInfo &MaxDepth = LoopDepth[I];
for (auto *MBB : CurrLoop->getBlocks()) {
// Clear physical registers Def map.
RegDefMaps[PhyRegType].clear();
for (MachineInstr &MI : *MBB) {
unsigned MIDepth = 0;
unsigned MIDepthOpt = 0;
bool IsCMOV = CmovInstructions.count(&MI);
for (auto &MO : MI.uses()) {
// Checks for "isUse()" as "uses()" returns also implicit definitions.
if (!MO.isReg() || !MO.isUse())
continue;
unsigned Reg = MO.getReg();
auto &RDM = RegDefMaps[TargetRegisterInfo::isVirtualRegister(Reg)];
if (MachineInstr *DefMI = RDM.lookup(Reg)) {
OperandToDefMap[&MO] = DefMI;
DepthInfo Info = DepthMap.lookup(DefMI);
MIDepth = std::max(MIDepth, Info.Depth);
if (!IsCMOV)
MIDepthOpt = std::max(MIDepthOpt, Info.OptDepth);
}
}
if (IsCMOV)
MIDepthOpt = getDepthOfOptCmov(
DepthMap[OperandToDefMap.lookup(&MI.getOperand(1))].OptDepth,
DepthMap[OperandToDefMap.lookup(&MI.getOperand(2))].OptDepth);
// Iterates over all operands to handle implicit definitions as well.
for (auto &MO : MI.operands()) {
if (!MO.isReg() || !MO.isDef())
continue;
unsigned Reg = MO.getReg();
RegDefMaps[TargetRegisterInfo::isVirtualRegister(Reg)][Reg] = &MI;
}
unsigned Latency = TSchedModel.computeInstrLatency(&MI);
DepthMap[&MI] = {MIDepth += Latency, MIDepthOpt += Latency};
MaxDepth.Depth = std::max(MaxDepth.Depth, MIDepth);
MaxDepth.OptDepth = std::max(MaxDepth.OptDepth, MIDepthOpt);
}
}
}
unsigned Diff[LoopIterations] = {LoopDepth[0].Depth - LoopDepth[0].OptDepth,
LoopDepth[1].Depth - LoopDepth[1].OptDepth};
//===--------------------------------------------------------------------===//
// Step 2: Check if Loop worth to be optimized.
// Worth-Optimize-Loop:
// case 1: Diff[1] == Diff[0]
// Critical-path is iteration independent - there is no dependency
// of critical-path instructions on critical-path instructions of
// previous iteration.
// Thus, it is enough to check gain percent of 1st iteration -
// To be conservative, the optimized loop need to have a depth of
// 12.5% cycles less than original loop, per iteration.
//
// case 2: Diff[1] > Diff[0]
// Critical-path is iteration dependent - there is dependency of
// critical-path instructions on critical-path instructions of
// previous iteration.
// Thus, it is required to check the gradient of the gain - the
// change in Depth-Diff compared to the change in Loop-Depth between
// 1st and 2nd iterations.
// To be conservative, the gradient need to be at least 50%.
//
// If loop is not worth optimizing, remove all CMOV-group-candidates.
//===--------------------------------------------------------------------===//
bool WorthOptLoop = false;
if (Diff[1] == Diff[0])
WorthOptLoop = Diff[0] * 8 >= LoopDepth[0].Depth;
else if (Diff[1] > Diff[0])
WorthOptLoop =
(Diff[1] - Diff[0]) * 2 >= (LoopDepth[1].Depth - LoopDepth[0].Depth);
if (!WorthOptLoop)
return false;
++NumOfLoopCandidate;
//===--------------------------------------------------------------------===//
// Step 3: Check for each CMOV-group-candidate if it worth to be optimized.
// Worth-Optimize-Group:
// Iff it worths to optimize all CMOV instructions in the group.
//
// Worth-Optimize-CMOV:
// Predicted branch is faster than CMOV by the difference between depth of
// condition operand and depth of taken (predicted) value operand.
// To be conservative, the gain of such CMOV transformation should cover at
// at least 25% of branch-misprediction-penalty.
//===--------------------------------------------------------------------===//
unsigned MispredictPenalty = TSchedModel.getMCSchedModel()->MispredictPenalty;
CmovGroups TempGroups;
std::swap(TempGroups, CmovInstGroups);
for (auto &Group : TempGroups) {
bool WorthOpGroup = true;
for (auto *MI : Group) {
// Avoid CMOV instruction which value is used as a pointer to load from.
// This is another conservative check to avoid converting CMOV instruction
// used with tree-search like algorithm, where the branch is unpredicted.
auto UIs = MRI->use_instructions(MI->defs().begin()->getReg());
if (UIs.begin() != UIs.end() && ++UIs.begin() == UIs.end()) {
unsigned Op = UIs.begin()->getOpcode();
if (Op == X86::MOV64rm || Op == X86::MOV32rm) {
WorthOpGroup = false;
break;
}
}
unsigned CondCost =
DepthMap[OperandToDefMap.lookup(&MI->getOperand(3))].Depth;
unsigned ValCost = getDepthOfOptCmov(
DepthMap[OperandToDefMap.lookup(&MI->getOperand(1))].Depth,
DepthMap[OperandToDefMap.lookup(&MI->getOperand(2))].Depth);
if (ValCost > CondCost || (CondCost - ValCost) * 4 < MispredictPenalty) {
WorthOpGroup = false;
break;
}
}
if (WorthOpGroup)
CmovInstGroups.push_back(Group);
}
return !CmovInstGroups.empty();
}
static bool checkEFLAGSLive(MachineInstr *MI) {
if (MI->killsRegister(X86::EFLAGS))
return false;
// The EFLAGS operand of MI might be missing a kill marker.
// Figure out whether EFLAGS operand should LIVE after MI instruction.
MachineBasicBlock *BB = MI->getParent();
MachineBasicBlock::iterator ItrMI = MI;
// Scan forward through BB for a use/def of EFLAGS.
for (auto I = std::next(ItrMI), E = BB->end(); I != E; ++I) {
if (I->readsRegister(X86::EFLAGS))
return true;
if (I->definesRegister(X86::EFLAGS))
return false;
}
// We hit the end of the block, check whether EFLAGS is live into a successor.
for (auto I = BB->succ_begin(), E = BB->succ_end(); I != E; ++I) {
if ((*I)->isLiveIn(X86::EFLAGS))
return true;
}
return false;
}
void X86CmovConverterPass::convertCmovInstsToBranches(
SmallVectorImpl<MachineInstr *> &Group) const {
assert(!Group.empty() && "No CMOV instructions to convert");
++NumOfOptimizedCmovGroups;
// To convert a CMOVcc instruction, we actually have to insert the diamond
// control-flow pattern. The incoming instruction knows the destination vreg
// to set, the condition code register to branch on, the true/false values to
// select between, and a branch opcode to use.
// Before
// -----
// MBB:
// cond = cmp ...
// v1 = CMOVge t1, f1, cond
// v2 = CMOVlt t2, f2, cond
// v3 = CMOVge v1, f3, cond
//
// After
// -----
// MBB:
// cond = cmp ...
// jge %SinkMBB
//
// FalseMBB:
// jmp %SinkMBB
//
// SinkMBB:
// %v1 = phi[%f1, %FalseMBB], [%t1, %MBB]
// %v2 = phi[%t2, %FalseMBB], [%f2, %MBB] ; For CMOV with OppCC switch
// ; true-value with false-value
// %v3 = phi[%f3, %FalseMBB], [%t1, %MBB] ; Phi instruction cannot use
// ; previous Phi instruction result
MachineInstr &MI = *Group.front();
MachineInstr *LastCMOV = Group.back();
DebugLoc DL = MI.getDebugLoc();
X86::CondCode CC = X86::CondCode(X86::getCondFromCMovOpc(MI.getOpcode()));
X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
MachineBasicBlock *MBB = MI.getParent();
MachineFunction::iterator It = ++MBB->getIterator();
MachineFunction *F = MBB->getParent();
const BasicBlock *BB = MBB->getBasicBlock();
MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(BB);
MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(BB);
F->insert(It, FalseMBB);
F->insert(It, SinkMBB);
// If the EFLAGS register isn't dead in the terminator, then claim that it's
// live into the sink and copy blocks.
if (checkEFLAGSLive(LastCMOV)) {
FalseMBB->addLiveIn(X86::EFLAGS);
SinkMBB->addLiveIn(X86::EFLAGS);
}
// Transfer the remainder of BB and its successor edges to SinkMBB.
SinkMBB->splice(SinkMBB->begin(), MBB,
std::next(MachineBasicBlock::iterator(LastCMOV)), MBB->end());
SinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
// Add the false and sink blocks as its successors.
MBB->addSuccessor(FalseMBB);
MBB->addSuccessor(SinkMBB);
// Create the conditional branch instruction.
BuildMI(MBB, DL, TII->get(X86::GetCondBranchFromCond(CC))).addMBB(SinkMBB);
// Add the sink block to the false block successors.
FalseMBB->addSuccessor(SinkMBB);
MachineInstrBuilder MIB;
MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
MachineBasicBlock::iterator MIItEnd =
std::next(MachineBasicBlock::iterator(LastCMOV));
MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
// As we are creating the PHIs, we have to be careful if there is more than
// one. Later CMOVs may reference the results of earlier CMOVs, but later
// PHIs have to reference the individual true/false inputs from earlier PHIs.
// That also means that PHI construction must work forward from earlier to
// later, and that the code must maintain a mapping from earlier PHI's
// destination registers, and the registers that went into the PHI.
DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
unsigned DestReg = MIIt->getOperand(0).getReg();
unsigned Op1Reg = MIIt->getOperand(1).getReg();
unsigned Op2Reg = MIIt->getOperand(2).getReg();
// If this CMOV we are processing is the opposite condition from the jump we
// generated, then we have to swap the operands for the PHI that is going to
// be generated.
if (X86::getCondFromCMovOpc(MIIt->getOpcode()) == OppCC)
std::swap(Op1Reg, Op2Reg);
auto Op1Itr = RegRewriteTable.find(Op1Reg);
if (Op1Itr != RegRewriteTable.end())
Op1Reg = Op1Itr->second.first;
auto Op2Itr = RegRewriteTable.find(Op2Reg);
if (Op2Itr != RegRewriteTable.end())
Op2Reg = Op2Itr->second.second;
// SinkMBB:
// %Result = phi [ %FalseValue, FalseMBB ], [ %TrueValue, MBB ]
// ...
MIB = BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(X86::PHI), DestReg)
.addReg(Op1Reg)
.addMBB(FalseMBB)
.addReg(Op2Reg)
.addMBB(MBB);
(void)MIB;
DEBUG(dbgs() << "\tFrom: "; MIIt->dump());
DEBUG(dbgs() << "\tTo: "; MIB->dump());
// Add this PHI to the rewrite table.
RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
}
// Now remove the CMOV(s).
MBB->erase(MIItBegin, MIItEnd);
}
} // End anonymous namespace.
FunctionPass *llvm::createX86CmovConverterPass() {
return new X86CmovConverterPass();
}
| 40.328431 | 80 | 0.631255 | [
"transform"
] |
bfcccb403327a7f3c145b8c5bcb9a176a588830d | 13,101 | cpp | C++ | Hammer/src/Hammer/Scene/Scene.cpp | ZMen9/Hammer | 69284f8f804504ca87d6404250d433fb99156f5a | [
"Apache-2.0"
] | null | null | null | Hammer/src/Hammer/Scene/Scene.cpp | ZMen9/Hammer | 69284f8f804504ca87d6404250d433fb99156f5a | [
"Apache-2.0"
] | null | null | null | Hammer/src/Hammer/Scene/Scene.cpp | ZMen9/Hammer | 69284f8f804504ca87d6404250d433fb99156f5a | [
"Apache-2.0"
] | null | null | null | #include "hmpch.h"
#include "Hammer/Scene/Scene.h"
#include <glm/glm.hpp>
#include "Hammer/Scene/Entity.h"
#include "Hammer/Scene/Components.h"
#include "Hammer/Renderer/Renderer2D.h"
#include "Hammer/Scene/ScriptableEntity.h"
// Box2D phyics
#include <box2d/b2_body.h>
#include <box2d/b2_world.h>
#include <box2d/b2_polygon_shape.h>
#include <box2d/b2_circle_shape.h>
#include <box2d/b2_fixture.h>
// About entt::view and entt::group:
// Views are a non-intrusive tool to access entities and components without
// affecting other functionalities or increasing the memory consumption. Groups
// are an intrusive tool that allows to reach higher performance along critical
// paths but has also a price to pay for that.
namespace hammer {
static b2BodyType Rigidbody2DTypeToBox2DBody(
Rigidbody2DComponent::BodyType body_type) {
switch (body_type) {
case hammer::Rigidbody2DComponent::BodyType::STATIC:
return b2_staticBody;
break;
case hammer::Rigidbody2DComponent::BodyType::DYNAMIC:
return b2_dynamicBody;
break;
case hammer::Rigidbody2DComponent::BodyType::KINEMATIC:
return b2_kinematicBody;
break;
}
HM_CORE_ASSERT(false, "Unknown body type");
return b2_staticBody;
}
Scene::Scene() {}
Scene::~Scene() {
}
Entity Scene::CreateEntity(const std::string& name /*= std::string()*/) {
return CreateEntityWithUUID(UUID(), name);
}
Entity Scene::CreateEntityWithUUID(
UUID uuid, const std::string& name /*= std::string()*/) {
Entity entity{registry_.create(), this};
entity.AddComponent<IDComponent>(uuid);
entity.AddComponent<TransformComponent>();
auto& tag = entity.AddComponent<TagComponent>();
tag.tag = name.empty() ? "Entity" : name;
return entity;
}
void Scene::DestroyEntity(Entity entity) { registry_.destroy(entity);}
void Scene::OnRuntimeStart() {
// b2World(gravity)
physics_world_ = new b2World({0.0f, -9.8f});
auto view = registry_.view<Rigidbody2DComponent>();
for (auto e : view) {
Entity entity{e, this};
auto& transform = entity.GetComponent<TransformComponent>();
// Set Rigidbody
auto& rb2d = entity.GetComponent<Rigidbody2DComponent>();
b2BodyDef body_def;
body_def.type = Rigidbody2DTypeToBox2DBody(rb2d.type);
body_def.position.Set(transform.translation.x, transform.translation.y);
body_def.angle = transform.rotation.z;
b2Body* body = physics_world_->CreateBody(&body_def);
body->SetFixedRotation(rb2d.fixed_rotation);
rb2d.runtime_body = body;
if (entity.HasComponent<BoxCollider2DComponent>()) {
auto& bc2d = entity.GetComponent<BoxCollider2DComponent>();
b2PolygonShape box_shape;
box_shape.SetAsBox(bc2d.size.x * transform.scale.x,
bc2d.size.y * transform.scale.y);
// Set BoxCollider
b2FixtureDef fixture_def;
fixture_def.shape = &box_shape;
fixture_def.density = bc2d.density;
fixture_def.friction = bc2d.friction;
fixture_def.restitution = bc2d.restitution;
fixture_def.restitutionThreshold = bc2d.restitution_threshold;
body->CreateFixture(&fixture_def);
}
if (entity.HasComponent<CircleCollider2DComponent>()) {
auto& cc2d = entity.GetComponent<CircleCollider2DComponent>();
b2CircleShape circleShape;
circleShape.m_p.Set(cc2d.offset.x, cc2d.offset.y);
circleShape.m_radius = transform.scale.x * cc2d.radius;
b2FixtureDef fixtureDef;
fixtureDef.shape = &circleShape;
fixtureDef.density = cc2d.density;
fixtureDef.friction = cc2d.friction;
fixtureDef.restitution = cc2d.restitution;
fixtureDef.restitutionThreshold = cc2d.restitution_threshold;
body->CreateFixture(&fixtureDef);
}
}
}
void Scene::OnRuntimeStop() {
delete physics_world_;
physics_world_ = nullptr;
}
void Scene::OnUpdateRuntime(Timestep ts) {
//Update scripts
{
registry_.view<NativeScriptComponent>().each([=](auto entity, auto& nsc) {
// TODO: Move to Scene::OnScenePlay
if (!nsc.instance) {
nsc.instance = nsc.InstantiateScript();
nsc.instance->entity_ = Entity{entity, this};
nsc.instance->OnCreate();
}
nsc.instance->OnUpdate(ts);
});
}
// Physics
{
constexpr int32_t velocityIterations = 6;
constexpr int32_t positionIterations = 2;
physics_world_->Step(ts, velocityIterations, positionIterations);
// Retrieve transform from Box2D,change the transform by retrieve from rb.
auto view = registry_.view<Rigidbody2DComponent>();
for (auto e : view) {
Entity entity = {e, this};
auto& transform = entity.GetComponent<TransformComponent>();
auto& rb2d = entity.GetComponent<Rigidbody2DComponent>();
b2Body* body = (b2Body*)rb2d.runtime_body;
const auto& position = body->GetPosition();
transform.translation.x = position.x;
transform.translation.y = position.y;
transform.rotation.z = body->GetAngle();
}
}
// Render 2D
Camera* main_camera = nullptr;
glm::mat4 camera_transform;
{
auto view = registry_.view<TransformComponent, CameraComponent>();
for (auto entity : view) {
auto [transform, camera] =
view.get<TransformComponent, CameraComponent>(entity);
if (camera.primary) {
main_camera = &camera.camera;
camera_transform = transform.GetTransform();
break;
}
}
}
if (main_camera) {
Renderer2D::BeginScene(*main_camera, camera_transform);
// Draw sprites
{
auto group = registry_.group<TransformComponent>(
entt::get<SpriteRendererComponent>);
for (auto entity : group) {
auto [transform, sprite] =
group.get<TransformComponent, SpriteRendererComponent>(entity);
Renderer2D::DrawSprite(transform.GetTransform(), sprite, (int)entity);
}
}
// Draw circles
{
auto view =
registry_.view<TransformComponent, CircleRendererComponent>();
for (auto entity : view) {
auto [transform, circle] =
view.get<TransformComponent, CircleRendererComponent>(entity);
Renderer2D::DrawCircle(transform.GetTransform(), circle.color,
circle.thickness, circle.fade, (int)entity);
}
}
Renderer2D::EndScene();
}
}
void Scene::OnUpdateEditor(Timestep ts, EditorCamera& camera) {
// Draw Sprites
{
Renderer2D::BeginScene(camera);
auto group =
registry_.group<TransformComponent>(entt::get<SpriteRendererComponent>);
for (auto entity : group) {
auto [transform, sprite] =
group.get<TransformComponent, SpriteRendererComponent>(entity);
Renderer2D::DrawSprite(transform.GetTransform(), sprite, (int)entity);
}
}
// draw circle
{
auto view = registry_.view<TransformComponent, CircleRendererComponent>();
for (auto entity : view) {
auto [transform, circle] =
view.get<TransformComponent, CircleRendererComponent>(entity);
Renderer2D::DrawCircle(transform.GetTransform(), circle.color,
circle.thickness, circle.fade, (int)entity);
}
}
/*Renderer2D::DrawLine(glm::vec3(2.0f), glm::vec3(5.0f),
glm::vec4(0.2f, 0.1f, 0.5f, 1.0f));
Renderer2D::DrawRect(glm::vec3(0.0f), glm::vec2(5.0f, 7.0f),
glm::vec4(0.2f, 0.1f, 0.5f, 1.0f));*/
Renderer2D::EndScene();
}
void Scene::OnViewportResize(uint32_t width, uint32_t height) {
viewport_width_ = width;
viewport_height_ = height;
// Resize our non-FixedAspectRatio cameras
auto view = registry_.view<CameraComponent>();
for (auto entity : view) {
auto& camera_component = view.get<CameraComponent>(entity);
if (!camera_component.fixed_aspect_ratio)
camera_component.camera.SetViewportSize(width, height);
}
}
Entity Scene::GetPrimaryCameraEntity() {
auto view = registry_.view<CameraComponent>();
for (auto entity : view) {
const auto& camera = view.get<CameraComponent>(entity);
if (camera.primary) return Entity(entity, this);
}
return {};
}
template<typename Component>
static void CopyComponent(entt::registry& dst, entt::registry& src,
const std::unordered_map<UUID, entt::entity>& enttMap) {
auto view = src.view<Component>();
for (auto e : view) {
UUID uuid = src.get<IDComponent>(e).id;
HM_CORE_ASSERT(enttMap.find(uuid) != enttMap.end());
entt::entity dstEnttID = enttMap.at(uuid);
auto& component = src.get<Component>(e);
dst.emplace_or_replace<Component>(dstEnttID, component);
}
}
template <typename Component>
static void CopyComponentIfExists(Entity dst, Entity src) {
if (src.HasComponent<Component>())
dst.AddOrReplaceComponent<Component>(src.GetComponent<Component>());
}
Ref<Scene> Scene::Copy(Ref<Scene> other) {
Ref<Scene> newScene = CreateRef<Scene>();
newScene->viewport_width_ = other->viewport_width_;
newScene->viewport_height_ = other->viewport_height_;
auto& srcSceneRegistry = other->registry_;
auto& dstSceneRegistry = newScene->registry_;
std::unordered_map<UUID, entt::entity> enttMap;
// Create entities in new scene
auto idView = srcSceneRegistry.view<IDComponent>();
for (auto e : idView) {
UUID uuid = srcSceneRegistry.get<IDComponent>(e).id;
const auto& name = srcSceneRegistry.get<TagComponent>(e).tag;
Entity newEntity = newScene->CreateEntityWithUUID(uuid, name);
enttMap[uuid] = (entt::entity)newEntity;
}
// Copy components (except IDComponent and TagComponent)
CopyComponent<TransformComponent>(dstSceneRegistry, srcSceneRegistry,
enttMap);
CopyComponent<SpriteRendererComponent>(dstSceneRegistry, srcSceneRegistry,
enttMap);
CopyComponent<CircleRendererComponent>(dstSceneRegistry, srcSceneRegistry,
enttMap);
CopyComponent<CameraComponent>(dstSceneRegistry, srcSceneRegistry, enttMap);
CopyComponent<NativeScriptComponent>(dstSceneRegistry, srcSceneRegistry,
enttMap);
CopyComponent<Rigidbody2DComponent>(dstSceneRegistry, srcSceneRegistry,
enttMap);
CopyComponent<BoxCollider2DComponent>(dstSceneRegistry, srcSceneRegistry,
enttMap);
CopyComponent<CircleCollider2DComponent>(dstSceneRegistry, srcSceneRegistry,
enttMap);
return newScene;
}
void Scene::DuplicateEntity(Entity entity) {
std::string name = entity.GetName();
Entity new_entity = CreateEntity(name);
CopyComponentIfExists<TransformComponent>(new_entity, entity);
CopyComponentIfExists<SpriteRendererComponent>(new_entity, entity);
CopyComponentIfExists<CircleRendererComponent>(new_entity, entity);
CopyComponentIfExists<CameraComponent>(new_entity, entity);
CopyComponentIfExists<NativeScriptComponent>(new_entity, entity);
CopyComponentIfExists<Rigidbody2DComponent>(new_entity, entity);
CopyComponentIfExists<BoxCollider2DComponent>(new_entity, entity);
CopyComponentIfExists<CircleCollider2DComponent>(new_entity, entity);
}
template <typename T>
void Scene::OnComponentAdded(Entity entity, T& component) {
static_assert(false);
}
template <>
void Scene::OnComponentAdded<IDComponent>(
Entity entity, IDComponent& component) {}
template<>
void Scene::OnComponentAdded<TransformComponent>(
Entity entity, TransformComponent& component) {}
template <>
void Scene::OnComponentAdded<TagComponent>(Entity entity,
TagComponent& component) {}
template <>
void Scene::OnComponentAdded<CameraComponent>(Entity entity,
CameraComponent& component) {
if (viewport_width_ > 0 && viewport_height_ > 0)
component.camera.SetViewportSize(viewport_width_, viewport_height_);
/*entity.AddComponent<SpriteRendererComponent>();
std::filesystem::path texturePath = "resources/icons/CameraFilm.png";
Ref<Texture2D> texture = Texture2D::Create(texturePath.string());
if (texture->IsLoaded()) {
entity.GetComponent<SpriteRendererComponent>().texture = texture;
} else {
HM_WARN("Could not load texture {0}", texturePath.filename().string());
}*/
}
template <>
void Scene::OnComponentAdded<SpriteRendererComponent>(
Entity entity, SpriteRendererComponent& component) {}
template <>
void Scene::OnComponentAdded<CircleRendererComponent>(
Entity entity, CircleRendererComponent& component) {}
template <>
void Scene::OnComponentAdded<NativeScriptComponent>(
Entity entity, NativeScriptComponent& component) {}
template <>
void Scene::OnComponentAdded<Rigidbody2DComponent>(
Entity entity, Rigidbody2DComponent& component) {}
template <>
void Scene::OnComponentAdded<BoxCollider2DComponent>(
Entity entity, BoxCollider2DComponent& component) {}
template <>
void Scene::OnComponentAdded<CircleCollider2DComponent>(
Entity entity, CircleCollider2DComponent& component) {}
} // namespace hammer | 34.385827 | 80 | 0.693459 | [
"render",
"shape",
"transform"
] |
bfce6edb8ee5d8c12e385267c006c8bcfbb8b063 | 762 | cpp | C++ | find_k_closest_elements.cpp | ArnabBir/leetcode-solutions | 31cf1edaa2f39c1f8d0300ad815889999058a0c8 | [
"MIT"
] | null | null | null | find_k_closest_elements.cpp | ArnabBir/leetcode-solutions | 31cf1edaa2f39c1f8d0300ad815889999058a0c8 | [
"MIT"
] | null | null | null | find_k_closest_elements.cpp | ArnabBir/leetcode-solutions | 31cf1edaa2f39c1f8d0300ad815889999058a0c8 | [
"MIT"
] | null | null | null | class Solution {
public:
struct comparator {
bool operator()(pair<long,int> a, pair<long,int> b) {
if(a.first > b.first) return true;
if(a.first < b.first) return false;
return a.second > b.second;
}
};
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
priority_queue<pair<long,int>, vector<pair<long,int>>, comparator> pq;
int n = arr.size();
for(int i = 0; i < n; ++i) {
pq.push(make_pair(abs(arr[i] - x), arr[i]));
}
vector<int> result;
while(k--) {
result.push_back(pq.top().second);
pq.pop();
}
sort(result.begin(), result.end());
return result;
}
};
| 28.222222 | 78 | 0.497375 | [
"vector"
] |
bfcecff561878b7f167ca24d65ec6131bcbb51a3 | 1,614 | cpp | C++ | LiberoEngine/src/RigidbodyComponent.cpp | Kair0z/LiberoEngine2D | 79fb93d7bbb5f5e6b805da6826c64ffa520989c3 | [
"MIT"
] | null | null | null | LiberoEngine/src/RigidbodyComponent.cpp | Kair0z/LiberoEngine2D | 79fb93d7bbb5f5e6b805da6826c64ffa520989c3 | [
"MIT"
] | null | null | null | LiberoEngine/src/RigidbodyComponent.cpp | Kair0z/LiberoEngine2D | 79fb93d7bbb5f5e6b805da6826c64ffa520989c3 | [
"MIT"
] | null | null | null | #include "PCH.h"
#include "RigidbodyComponent.h"
#include "PhysicsMaster.h"
#include "ColliderComponent.h"
namespace Libero
{
RigidbodyComponent::RigidbodyComponent(BodyType type)
: m_pBody{nullptr}
{
b2BodyDef bodyDef{};
switch (type)
{
case BodyType::Dynamic: bodyDef.type = b2BodyType::b2_dynamicBody; break;
case BodyType::Kinematic: bodyDef.type = b2BodyType::b2_kinematicBody; break;
case BodyType::Static: bodyDef.type = b2BodyType::b2_staticBody; break;
}
m_pBody = PhysicsMasterLocator::Locate()->CreateBody(bodyDef);
m_pBody->SetSleepingAllowed(false);
}
RigidbodyComponent::~RigidbodyComponent()
{
// Destroy the physics body
PhysicsMasterLocator::Locate()->DestroyBody(m_pBody);
}
bool RigidbodyComponent::IsSimulated() const
{
return m_pBody->IsEnabled();
}
void RigidbodyComponent::SetSimulated(const bool enable)
{
m_pBody->SetEnabled(enable);
}
bool RigidbodyComponent::GetWeight() const
{
return m_pBody->GetMass();
}
void RigidbodyComponent::SetWeight(const float weight)
{
m_pBody->SetGravityScale(weight);
}
void RigidbodyComponent::AddForce(const Vector2f& force)
{
m_ForceSum += force;
}
b2Body* RigidbodyComponent::GetB2DBody() const
{
return m_pBody;
}
void RigidbodyComponent::AttachCollider(Collider2DComponent* pCollider)
{
b2FixtureDef fixtureDef;
fixtureDef.shape = pCollider->GetShape();
fixtureDef.density = 0.05f;
fixtureDef.friction = 0.0001f;
m_pBody->CreateFixture(&fixtureDef);
}
void RigidbodyComponent::SetTrigger(bool enabled)
{
m_pBody->GetFixtureList()->SetSensor(enabled);
}
}
| 20.961039 | 79 | 0.741636 | [
"shape"
] |
bfdf8c143bddbdb04e153875631e51e1d0983849 | 2,123 | cpp | C++ | interviewbit/math_power_of_two_integer.cpp | qiaotian/CodeInterview | 294c1ba86d8ace41a121c5ada4ba4c3765ccc17d | [
"WTFPL"
] | 5 | 2016-10-29T09:28:11.000Z | 2019-10-19T23:02:48.000Z | interviewbit/math_power_of_two_integer.cpp | qiaotian/CodeInterview | 294c1ba86d8ace41a121c5ada4ba4c3765ccc17d | [
"WTFPL"
] | null | null | null | interviewbit/math_power_of_two_integer.cpp | qiaotian/CodeInterview | 294c1ba86d8ace41a121c5ada4ba4c3765ccc17d | [
"WTFPL"
] | null | null | null | /*
Given a positive integer which fits in a 32 bit signed integer, find if it can be expressed as A^P where P > 1 and A > 0. A and P both should be integers.
Example
Input : 4
Output : True
as 2^2 = 4.
*/
#include <cmath>
#include <iostream>
// solution one: 内存使用异常MLE
//
// for test case "1024000000"
int gcd(int a, int b) {
if(a<b) return gcd(b, a);
if(b==0) return a;
return gcd(b, a%b);
}
bool Solution::isPower(int A) {
if(A<=3) return false;
int maxfactor = sqrt(A);
vector<bool> isPrime(A+1, true);//标记1到A是否为质数
vector<int> numExp; // 按质数分解A,个质数的指数记录在该数组中
// 求出特定范围内的所有质数
isPrime[0] = false;
isPrime[1] = false;
for(int i=2; i<=A; i++) {
if(!isPrime[i]) continue;
if(i*i > A) break;
for(int j=i*i; j<=A; j+=i) {
isPrime[j] = false;
}
}
// 按质数分解整数A
for(int i=2; i<=A; i++) {
if(!isPrime[i]) continue;
int num = 0;
while(A%i==0) {
num++;
A/=i;
}
if(num) numExp.push_back(num);
}
// 计算所有质数的指数的最大公约数
int max_common_divsor = numExp[0];
for(int i=0; i<numExp.size(); i++) {
if(numExp[i]==1) return false;
max_common_divsor = gcd(max_common_divsor, numExp[i]);
}
return max_common_divsor>1;
}
// solution two
//
//
bool Solution::isPower(int A) {
// 考虑到A是32位正整数
// 小于等于A的a^b的形式pair [a, b]数目是有限的
// 遍历求出所有的a^b的值然后和A比对即可
if(A==1) return true;
int maxbase = sqrt(A);
for(int i=2; i<=maxbase; i++) {
for(int j=2; ;j++){
long long tmp = pow(i, j);
if(tmp>A) break;
if(tmp==A) return true;
}
}
return false;
}
// 参考答案
class Solution {
public:
bool isPower(int x) {
if (x <= 1) return true;
for (int base = 2; base < x && base < INT_MAX / base; base++) {
int temp = base;
while (temp <= x && temp < INT_MAX / base) {
temp *= base;
if (temp == x) return true;
}
}
return false;
}
};
| 22.585106 | 154 | 0.505417 | [
"vector"
] |
bfe2e9921d841b102e75e23b7c0b32008fac78c6 | 996 | cpp | C++ | src/processor.cpp | satlawa/ucy_cpp_system_monitor | 7d71783d4f19396a2ac4b405f959fed83858bd95 | [
"MIT"
] | null | null | null | src/processor.cpp | satlawa/ucy_cpp_system_monitor | 7d71783d4f19396a2ac4b405f959fed83858bd95 | [
"MIT"
] | null | null | null | src/processor.cpp | satlawa/ucy_cpp_system_monitor | 7d71783d4f19396a2ac4b405f959fed83858bd95 | [
"MIT"
] | null | null | null | #include <string>
#include <vector>
#include "processor.h"
#include "linux_parser.h"
using std::string;
using std::vector;
Processor::Processor() : oldTotal_(0.0), oldIdle_(0.0) {};
// TODO: Return the aggregate CPU utilization
float Processor::Utilization() {
vector<long> cpuInfo = LinuxParser::CpuUtilization();
// vector = string cpu, user, nice, system, idle,
// ioWait, irq, softIrq, steal, guest, guestNice;
// calculate total work load
float newTotal = cpuInfo[1] + cpuInfo[2] + cpuInfo[3] + cpuInfo[4] +
cpuInfo[5] + cpuInfo[6] + cpuInfo[7] + cpuInfo[8];
// calculate total idle
float newIdle = cpuInfo[4] + cpuInfo[5];
// subtract new values by old values to get a more recent CPU utilisation
float totalDiff = newTotal - oldTotal_;
float idleDiff = newIdle - oldIdle_;
// total CPU utilistion
float percentage = (totalDiff - idleDiff) / totalDiff;
// update old values
oldTotal_ = newTotal;
oldIdle_ = newIdle;
return percentage;
}
| 29.294118 | 75 | 0.687751 | [
"vector"
] |
bfef92dc99bf9ec5cb5d29b568ce24eae1fcdbdc | 1,537 | cpp | C++ | leetcode-cpp/LowestCommonAncestorofaBinarySearchTree_235.cpp | emacslisp/cpp | 8230f81117d6f64adaa1696b0943cdb47505335a | [
"Apache-2.0"
] | null | null | null | leetcode-cpp/LowestCommonAncestorofaBinarySearchTree_235.cpp | emacslisp/cpp | 8230f81117d6f64adaa1696b0943cdb47505335a | [
"Apache-2.0"
] | null | null | null | leetcode-cpp/LowestCommonAncestorofaBinarySearchTree_235.cpp | emacslisp/cpp | 8230f81117d6f64adaa1696b0943cdb47505335a | [
"Apache-2.0"
] | null | null | null | #include <vector>
#include <iostream>
#include <climits>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <math.h>
#include "lib/Tree.h"
using namespace std;
#define ll long long
#define ld long double
#define fora(i, start, end) for(int i=start;i<end;i++)
#define forb(i, start, end) for(int i=end;i>=start;i--)
const double pi=acos(-1.0);
const double eps=1e-11;
const int mod = 1e9+7;
#define mod(n,k) ( ( ((n) % (k)) + (k) ) % (k))
class Solution {
public:
TreeNode* target;
bool dfs(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == NULL) return false;
if(root->val == p->val || root->val == q->val) {
if (dfs(root->left, p, q) || dfs(root->right, p, q)) {
target = root;
}
return true;
}
bool t1 = dfs(root->left, p, q);
bool t2 = dfs(root->right, p, q);
if(t1 && t2) {
target = root;
}
return t1||t2;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
dfs(root, p, q);
return target;
}
};
int main() {
Solution s;
#define null -1
vector<int> c
{
6,2,8,0,4,7,9,null,null,3,5
};
Tree t;
TreeNode * root = t.buildNode(c);
TreeNode * p = t.searchNodeByValue(root, 3);
TreeNode * q = t.searchNodeByValue(root, 5);
string str = "codeleet";
int n = 1804289383;
TreeNode * result = s.lowestCommonAncestor(root, p, q);
cout<<result->val<<endl;
} | 23.287879 | 78 | 0.554327 | [
"vector"
] |
bff2440a83efc83457125d73135cbde0a17f829f | 5,733 | cpp | C++ | main.cpp | Not-Nik/HUE | 645471456ba04378d47302d43645f6280b2cb00d | [
"MIT"
] | 3 | 2020-07-25T10:27:50.000Z | 2021-04-08T12:36:40.000Z | main.cpp | Not-Nik/HUE | 645471456ba04378d47302d43645f6280b2cb00d | [
"MIT"
] | null | null | null | main.cpp | Not-Nik/HUE | 645471456ba04378d47302d43645f6280b2cb00d | [
"MIT"
] | null | null | null | #include <map>
#include <string>
#include <vector>
#include <iostream>
bool Throw(const std::string & s) { throw std::runtime_error(s); }
#define assert(cond) (cond ? true : Throw("Assertion failed; line " + std::to_string(lex_pos.l) + " column " + std::to_string(lex_pos.c)))
#define match(s, r) (assert((r ? read() : t) == s) ? s : "")
#define assert_do(c, d) ((assert(c) ? d : nullptr))
#define loop_exprs(d) for (auto & e : expr.exprs) d
/// Structure used for all expressions
/// This is the stuff the AST is made of
struct Expr {
bool nameless;
std::string x;
std::vector<Expr> exprs;
bool operator==(const Expr & o) const { return nameless == o.nameless and x == o.x and exprs == o.exprs; }
bool operator!=(const Expr & o) const { return !(this->operator==(o)); }
};
typedef std::function<std::string(Expr)> overruling;
/// Everything that causes the lexer to end a token
std::string stoppers = "() \n;";
/// (Lexer internal) current char
char c = ' ';
/// Current token
std::string t;
/// Generated functions (strings of c code)
std::vector<std::string> functions;
/// Overwrites for certain expressions
std::map<std::string, overruling> overrulings;
/// Total count of functions
int function_counter = 0;
struct {
int l;
int c;
} lex_pos;
// -------------------- Lexer --------------------
/// Read character from input file
char readChar() {
char buffer[1];
std::cin.read(buffer, 1);
lex_pos.c++;
if (buffer[0] == '\n') {
lex_pos.c = 0;
lex_pos.l++;
}
return c = (std::cin.gcount() < 1 ? (char) -1 : buffer[0]);
}
/// Read token from input file
std::string read() {
std::string token;
while (c == ' ' or c == '\t' or c == '\n' or c == ';') {
if (c == ';')
while (c != '\n') readChar();
readChar();
}
if (c < 0) return "";
else if (c == '"') {
token += c;
do {
token += readChar();
} while (c != '"');
readChar();
} else
do {
if (stoppers.find(c) == std::string::npos)
token += c;
else {
if (token.empty()) {
token = {c};
readChar();
}
break;
}
} while ((readChar()) >= 0);
return t = token;
}
// -------------------- Parser --------------------
Expr read_instr(bool);
/// Read a value [primitives, strings or (do stuff)]
Expr read_val(bool r) {
if (r) read();
if (t == "(") return read_instr(false);
return Expr {true, t, {}};
}
/// Read an instruction [looks like this: (do stuff)]
Expr read_instr(bool r) {
match("(", r);
Expr expr = {.nameless = false, .x = read()};
while (true) {
read();
if (t != ")") expr.exprs.push_back(read_val(false));
else break;
}
return expr;
}
// -------------------- Code Generator --------------------
/// Generate c code for an expression
std::string gen_expr(Expr expr) {
if (!expr.nameless) {
if (overrulings.count(expr.x))
return overrulings[expr.x](expr);
std::string call_l = expr.x + "(";
loop_exprs(call_l += gen_expr(e) + (e != expr.exprs.back() ? ", " : ""));
return call_l + ")";
} else
return expr.x;
}
#define type_overruling(type) overrulings.emplace(#type, [](Expr expr){ \
return assert_do(expr.exprs.size() == 1, #type" " + expr.exprs[0].x); \
})
#define scope_overruling(name) overrulings.emplace(#name, [](Expr expr){ \
std::string res = #name" (" + gen_expr(expr.exprs[0]) + "){"; \
expr.exprs.erase(expr.exprs.begin()); \
loop_exprs(res += gen_expr(e) + ";\n"); \
return res + "}"; \
})
#define operator_overruling(name, op) overrulings.emplace(#name, [](Expr expr) { \
std::string res; \
loop_exprs(res += e.x + (e != expr.exprs.back() ? #op : "")); \
return res; \
})
int main(int argc, const char ** argv) {
overrulings.emplace("return", [](const Expr & expr) {
std::string res = "return " + gen_expr(assert(expr.exprs.size() == 1) ? expr.exprs[0] : Expr());
return "return " + gen_expr(expr.exprs[0]);
});
overrulings.emplace("set", [](Expr expr) {
return assert_do(expr.exprs.size() == 2, expr.exprs[0].x + "=" + gen_expr(expr.exprs[1]));
});
overrulings.emplace("include", [](Expr expr) {
functions.push_back("#include " + expr.exprs[0].x + "\n");
return assert_do(expr.exprs.size() == 1, "");
});
overrulings.emplace("do", [](Expr expr) {
std::string function_id = std::to_string(++function_counter);
std::string function = assert_do(expr.exprs.size() > 1, expr.exprs[0].x) + " f" + function_id + "() {\n";
expr.exprs.erase(expr.exprs.begin());
loop_exprs(function += gen_expr(e) + ";\n");
functions.push_back(function + "}\n");
return "f" + function_id + "()";
});
operator_overruling(add, +);
operator_overruling(sub, -);
operator_overruling(mul, *);
operator_overruling(div, /);
operator_overruling(mod, %);
scope_overruling(if);
scope_overruling(while);
type_overruling(int);
type_overruling(float);
/// Open input and input file and pipe to stdin/out
freopen(assert(argc >= 2) ? argv[1] : nullptr, "r", stdin);
freopen("out.c", "w", stdout);
/// Read and parse
Expr root = read_instr(true);
/// Write all the functions
std::string e = gen_expr(root);
std::string o;
for (const auto & func : functions)
o += func + "\n";
/// Make sure everything is called and print the code
std::cout << o + "int main(){" + e + ";}" << std::endl;
return 0;
}
| 29.25 | 138 | 0.546136 | [
"vector"
] |
bff3383eda89955155766e483b2acfbcde789c40 | 1,345 | cc | C++ | Distortion.cc | lemrobotry/thesis | 14ad489e8f04cb957707b89c454ee7d81ec672ad | [
"MIT"
] | null | null | null | Distortion.cc | lemrobotry/thesis | 14ad489e8f04cb957707b89c454ee7d81ec672ad | [
"MIT"
] | null | null | null | Distortion.cc | lemrobotry/thesis | 14ad489e8f04cb957707b89c454ee7d81ec672ad | [
"MIT"
] | null | null | null | #include <Fsa/Static.hh>
#include "Distortion.hh"
namespace Permute {
Fsa::ConstAutomatonRef distortion (const Permutation & p, double d) {
// For now, assumes (possibly erroneously) that the tokens in the sentence
// are unique.
Fsa::StaticAutomaton * fsa = new Fsa::StaticAutomaton (Fsa::TypeAcceptor);
fsa -> setSemiring (Fsa::LogSemiring);
fsa -> setInputAlphabet (p.alphabet ());
Fsa::State * initial (new Fsa::State (0));
fsa -> setState (initial);
fsa -> setInitialStateId (0);
// Constructs a bigram model where i -> j with weight d * |j - i - 1|.
for (Permutation::const_iterator i = p.begin (); i != p.end (); ++ i) {
// Creates a state numbered according to position i.
Fsa::State * state (new Fsa::State (* i + 1));
// NOTE: no penalty for ending the sentence anywhere.
state -> setFinal (Fsa::LogSemiring -> one ());
fsa -> setState (state);
// NOTE: penalty for starting the sentence anywhere but zero.
initial -> newArc (state -> id (), Fsa::Weight (d * (* i)), p.label (* i));
for (Permutation::const_iterator j = p.begin (); j != p.end (); ++ j) {
if (j == i) continue;
Fsa::Weight w (d * ::abs (* j - * i - 1));
state -> newArc (* j + 1, w, p.label (* j));
}
}
return Fsa::ConstAutomatonRef (fsa);
}
}
| 34.487179 | 81 | 0.592565 | [
"model"
] |
bff9fcfdde5499b494fa01aead53df3bb89f09d4 | 132,300 | cpp | C++ | Felix/MemoryWindowFrame.cpp | ultimatezen/felix | 5a7ad298ca4dcd5f1def05c60ae3c84519ec54c4 | [
"MIT"
] | null | null | null | Felix/MemoryWindowFrame.cpp | ultimatezen/felix | 5a7ad298ca4dcd5f1def05c60ae3c84519ec54c4 | [
"MIT"
] | null | null | null | Felix/MemoryWindowFrame.cpp | ultimatezen/felix | 5a7ad298ca4dcd5f1def05c60ae3c84519ec54c4 | [
"MIT"
] | null | null | null | /*!
* \date 2007/01/31
* \author Ryan Ginstrom
*
* Detailed description here.
*
* Copyright (C) Ryan Ginstrom.
*/
#include "StdAfx.h"
#include "MemoryWindowFrame.h"
#include "winuser.h"
#include "ConcordanceDialog.h"
#include "aboutdlg.h" // CAboutDlg
#include "PropertiesDlg.h" // CPropertiesDlg
#include "data_importer.h"
#include "data_converter.h"
#include "ImportDialog.h"
#include "ui.h" // windows_ui -- wrapper for common dialog boxes
#include "InputKeyDlg.h" // CInputKeyDlg
#include "Path.h"
#include "RegSettings.h" // CWindowSettings & CReBarSettings
#include "TMXReader.h" // CTMXReader
#include "record_local.h"
#include "Drop.h" // CDrop
#include "HtmlDocColorSetter.h" // CHtmlDocColorSetter
#include "xpmenu/Tools.h" // CWindowRect
#include "HtmlHelp.h"
#pragma comment(lib, "HtmlHelp.lib")
#include "NumberFmt.h"
#include "process.h"
#include "text_templates.h"
#include "ConnectionDlg.h"
#include "QueryMergeDlg.h"
#include "text_templates.h"
#include "FelixMemDocUIHandler.h"
#include "memory_local.h"
#include "memory_remote.h"
#include "FelixModel.h"
#include "CredVault.h"
// file I/O
#include "input_device_file.h"
#include "output_device.h"
#include "system_paths.h"
#include "file_dialog.h"
// QC
#include "qcrules/qc_checker.h"
#include "qcrules/allcaps_check.h"
#include "qcrules/number_check.h"
#include "qcrules/gloss_check.h"
// placement
#include "number_placement.h"
using namespace mem_engine ;
using namespace except ;
using namespace html ;
using namespace placement ;
/** Constructor. Takes model interface.
*/
MemoryWindowFrame::MemoryWindowFrame( model_iface_ptr model, app_props::props_ptr props ) :
m_model(model),
m_props(props),
m_editor(new CEditTransRecordDialog),
m_manager_window(m_props, IDS_SEARCH_MANAGER_TITLE, _T("MemoryMangerWindow"), this),
m_old_manager_window(props),
m_search_window(this),
m_input_device(new InputDeviceFile),
m_output_device(new OutputDeviceFile),
m_silent_memories(props)
{
// assign functions
m_get_window = &get_window_real ;
m_pre_translate_msg = boost::bind(&MemoryWindowFrame::PreTranslateMessage, this, _1) ;
// other props
m_is_active = false ;
initialize_values() ;
m_editor->m_interface = this ;
// Allow drag and drop in Windows 7
ChangeWindowMessageFilter( WM_DROPFILES, 1);
ChangeWindowMessageFilter( WM_COPYDATA , 1);
ChangeWindowMessageFilter( 0x0049, 1);
// initialize min view
m_min_view.set_listener(this) ;
m_min_view.set_matches(&m_trans_matches) ;
// initialize states
this->init_state(&m_view_state_initial) ;
this->init_state(&m_view_state_new) ;
m_view_state_new.set_qc_props(&(m_props->m_qc_props)) ;
this->init_state(&m_view_state_concordance) ;
m_view_state_concordance.set_search_matches(&m_search_matches) ;
// match state
this->init_state(&m_view_state_match) ;
m_view_state_match.set_search_matches(&m_trans_matches) ;
m_view_state_match.set_props(m_props) ;
this->init_state(&m_view_state_review) ;
m_view_state_review.set_search_matches(&m_trans_matches) ;
// display state
set_display_state( INIT_DISPLAY_STATE ) ;
ATLASSERT(m_view_state == &m_view_state_initial) ;
#ifndef UNIT_TEST
m_props->read_from_registry() ;
#endif
const BOOL show_markup = m_props->m_gen_props.m_data.m_show_markup ;
this->m_trans_matches.m_params.m_show_marking = !! show_markup ;
// make sure that the username is reflected!
const wstring user_name = CT2W(m_props->m_gen_props.m_data.m_user_name) ;
set_record_username(user_name) ;
addToMessageLoop();
// register command handlers
this->register_event_listener( WM_CREATE, boost::bind(&MemoryWindowFrame::on_create, this, _1 ) ) ;
this->register_event_listener( WM_DESTROY, boost::bind(&MemoryWindowFrame::on_destroy, this, _1 ) ) ;
this->register_event_listener( WM_CLOSE, boost::bind(&MemoryWindowFrame::on_close, this, _1 ) ) ;
this->register_event_listener( WM_DROPFILES, boost::bind(&MemoryWindowFrame::on_drop, this, _1 ) ) ;
this->register_event_listener( WM_ACTIVATE, boost::bind(&MemoryWindowFrame::on_activate, this, _1 ) ) ;
// user messages
this->register_user_event_listener( USER_LOOKUP_SOURCE, boost::bind(&MemoryWindowFrame::on_user_lookup_source, this, _1 )) ;
this->register_user_event_listener( USER_LOOKUP_TRANS, boost::bind(&MemoryWindowFrame::on_user_lookup_trans, this, _1 )) ;
this->register_user_event_listener( USER_SAVE_MEMORIES, boost::bind(&MemoryWindowFrame::on_user_save, this, _1 )) ;
this->register_user_event_listener( ID_EDIT_FIND, boost::bind(&MemoryWindowFrame::on_user_edit_search, this, _1 )) ;
this->register_user_event_listener( ID_USER_SEARCH, boost::bind(&MemoryWindowFrame::on_user_search, this, _1 )) ;
this->register_user_event_listener( IDC_REPLACE_EDIT_RECORD, boost::bind(&MemoryWindowFrame::on_user_replace_edit_record, this, _1 )) ;
this->register_user_event_listener( ID_EDIT_REPLACE, boost::bind(&MemoryWindowFrame::on_user_edit_replace, this, _1 )) ;
this->register_user_event_listener( IDC_MIN_VIEW_END, boost::bind(&MemoryWindowFrame::on_user_view_min_end, this, _1 )) ;
// commands
this->register_command_event_listener( IDC_DEMO_CHECK_EXCESS, boost::bind(&MemoryWindowFrame::on_demo_check_excess_memories, this, _1 )) ;
this->register_command_event_listener( IDC_STARTUP_CHECKS, boost::bind(&MemoryWindowFrame::on_startup_checks, this, _1 )) ;
this->register_command_event_listener( IDC_SOURCE_CONCORDANCE_SEL, boost::bind(&MemoryWindowFrame::on_source_concordance, this, _1 )) ;
this->register_command_event_listener( IDC_TRANS_CONCORDANCE_SEL, boost::bind(&MemoryWindowFrame::on_trans_concordance, this, _1 )) ;
this->register_command_event_listener( ID_TOOLS_MEMORY_MGR, boost::bind(&MemoryWindowFrame::on_tools_memory_manager, this, _1 )) ;
this->register_command_event_listener( IDC_UNDERLINE, boost::bind(&MemoryWindowFrame::on_underline, this, _1 )) ;
this->register_command_event_listener( IDC_BOLD, boost::bind(&MemoryWindowFrame::on_bold, this, _1 )) ;
this->register_command_event_listener( IDC_ITALIC, boost::bind(&MemoryWindowFrame::on_italic, this, _1 )) ;
this->register_command_event_listener( ID_FORMAT_BGCOLOR, boost::bind(&MemoryWindowFrame::OnFormatBackgroundColor, this, _1 )) ;
this->register_command_event_listener( ID_APP_EXIT, boost::bind(&MemoryWindowFrame::on_file_exit, this, _1 )) ;
this->register_command_event_listener( ID_GLOSSARY_NEW, boost::bind(&MemoryWindowFrame::on_new_glossary, this, _1 )) ;
this->register_command_event_listener( ID_FILE_NEW, boost::bind(&MemoryWindowFrame::on_file_new, this, _1 )) ;
this->register_command_event_listener( ID_FILE_OPEN, boost::bind(&MemoryWindowFrame::on_file_open, this, _1 )) ;
this->register_command_event_listener( ID_FILE_SAVE, boost::bind(&MemoryWindowFrame::on_file_save, this, _1 )) ;
this->register_command_event_listener( ID_FILE_SAVE_AS, boost::bind(&MemoryWindowFrame::on_file_save_as, this, _1 )) ;
this->register_command_event_listener( ID_FILE_SAVE_ALL, boost::bind(&MemoryWindowFrame::on_file_save_all, this, _1 )) ;
this->register_command_event_listener( ID_MEMORY_CLOSE, boost::bind(&MemoryWindowFrame::on_memory_close, this, _1 )) ;
this->register_command_event_listener( IDD_EDIT_ENTRY, boost::bind(&MemoryWindowFrame::on_edit_entry, this, _1 )) ;
this->register_command_event_listener( ID_EDIT_DELETE, boost::bind(&MemoryWindowFrame::on_delete_entry, this, _1 )) ;
this->register_command_event_listener( ID_EDIT_ADD, boost::bind(&MemoryWindowFrame::on_add, this, _1 )) ;
this->register_command_event_listener( ID_EDIT_REGISTER, boost::bind(&MemoryWindowFrame::on_register_gloss, this, _1 )) ;
this->register_command_event_listener( ID_EDIT_FIND, boost::bind(&MemoryWindowFrame::on_new_search, this, _1 )) ;
this->register_command_event_listener( ID_FIND_QUICKSEARCH, boost::bind(&MemoryWindowFrame::on_find, this, _1 )) ;
this->register_command_event_listener( IDD_CONCORDANCE, boost::bind(&MemoryWindowFrame::on_concordance, this, _1 )) ;
this->register_command_event_listener( ID_EDIT_REPLACE, boost::bind(&MemoryWindowFrame::on_edit_replace, this, _1 )) ;
this->register_command_event_listener( ID_VIEW_TOOLBAR, boost::bind(&MemoryWindowFrame::on_view_toolbar, this, _1 )) ;
this->register_command_event_listener( ID_VIEW_STATUS_BAR, boost::bind(&MemoryWindowFrame::on_view_status_bar, this, _1 )) ;
this->register_command_event_listener( ID_VIEW_EDIT_MODE, boost::bind(&MemoryWindowFrame::on_view_edit_mode, this, _1 )) ;
this->register_command_event_listener( ID_VIEW_MATCH, boost::bind(&MemoryWindowFrame::on_view_match, this, _1 )) ;
this->register_command_event_listener( ID_VIEW_SEARCH, boost::bind(&MemoryWindowFrame::on_view_search, this, _1 )) ;
this->register_command_event_listener( ID_VIEW_SWITCH, boost::bind(&MemoryWindowFrame::on_view_switch, this, _1 )) ;
this->register_command_event_listener( IDC_MIN_VIEW_BEGIN, boost::bind(&MemoryWindowFrame::on_view_min_begin, this, _1 )) ;
this->register_command_event_listener( ID_APP_ABOUT, boost::bind(&MemoryWindowFrame::show_about_dialog, this, _1 )) ;
this->register_command_event_listener( ID_HELP, boost::bind(&MemoryWindowFrame::on_help, this, _1 )) ;
this->register_command_event_listener( ID_HELP_FAQ, boost::bind(&MemoryWindowFrame::on_help_faq, this, _1 )) ;
this->register_command_event_listener(ID_HELP_CHECKUPDATES, boost::bind(&MemoryWindowFrame::on_help_check_updates, this, _1 )) ;
this->register_command_event_listener( IDC_SET_GLOSS, boost::bind(&MemoryWindowFrame::on_register_gloss, this, _1 )) ;
this->register_command_event_listener( ID_TOOLS_PREFERENCES, boost::bind(&MemoryWindowFrame::on_tools_preferences, this, _1 )) ;
this->register_command_event_listener( ID_TOOLS_RULEMANAGER, boost::bind(&MemoryWindowFrame::on_tools_rule_manager, this, _1 )) ;
this->register_command_event_listener( ID_TOOLS_LANGUAGE, boost::bind(&MemoryWindowFrame::on_tools_switch_language, this, _1 )) ;
this->register_command_event_listener( ID_TOOLS_LOADPREFERENCES, boost::bind(&MemoryWindowFrame::on_tools_load_preferences, this, _1 )) ;
this->register_command_event_listener( ID_TOOLS_SAVEPREFERENCES, boost::bind(&MemoryWindowFrame::on_tools_save_preferences, this, _1 )) ;
this->register_command_event_listener( IDC_TEST_EXCEPTION, boost::bind(&MemoryWindowFrame::on_test_exception, this, _1 )) ;
this->register_command_event_listener( ID_NEXT_PANE, boost::bind(&MemoryWindowFrame::on_toggle_views, this, _1 )) ;
this->register_command_event_listener( ID_PREV_PANE, boost::bind(&MemoryWindowFrame::on_toggle_views, this, _1 )) ;
this->register_command_event_listener( ID_VIEW_ZOOM, boost::bind(&MemoryWindowFrame::on_view_zoom, this, _1 )) ;
for ( int i=ID_FILE_MRU_FIRST ; i <=ID_FILE_MRU_LAST ; ++i )
{
this->register_command_event_listener( i, boost::bind(&MemoryWindowFrame::on_mru_file_open, this, _1 )) ;
}
}
//! DTOR
MemoryWindowFrame::~MemoryWindowFrame()
{
}
/**************************************************
*
* Windows messaging routines
*
**************************************************/
#define WATCH(var, val) if (var == val) \
{\
ATLTRACE("Got value of " #val " (%d)\n", var) ; \
}
/** We get a crack at messages before the are dispatched.
*/
BOOL MemoryWindowFrame::PreTranslateMessage(MSG* pMsg)
{
WATCH(pMsg->message, WM_DROPFILES) ;
if( m_min_view.IsWindow() && m_min_view.IsWindowVisible() )
{
return m_min_view.PreTranslateMessage( pMsg ) ;
}
// Go through our glossary windows, and see if we need to pass on
// this message to them...
m_glossary_windows.remove_destroyed_gloss_windows() ;
if (m_glossary_windows.pre_translate(pMsg))
{
return TRUE ;
}
ENSURE_ACTIVE
// let the frame window have a try
if( frame_class::PreTranslateMessage( pMsg ) )
{
return TRUE;
}
// prevent the view from eating our menu shortcut keys...
if (is_menu_key_pressed())
{
return FALSE ;
}
return m_view_interface.PreTranslateMessage( pMsg ) ;
}
/** Idle handler.
*/
BOOL MemoryWindowFrame::OnIdle()
{
SENSE("OnIdle") ;
#ifdef UNIT_TEST
return 0L ;
#else
UIUpdateToolBar();
user_feedback(CString(), 2) ;
return FALSE;
#endif
}
//! Gets the background color.
CColorRef MemoryWindowFrame::GetBackColor()
{
return CColorRef( m_view_interface.get_bg_color() ) ;
}
//! Respond to user command to format the background color.
LRESULT MemoryWindowFrame::OnFormatBackgroundColor( WindowsMessage &message )
{
message ;
SENSE("OnFormatBackgroundColor") ;
const CColorRef color = GetBackColor();
SENSE(color.as_string()) ;
#ifdef UNIT_TEST
return 0L ;
#else
CColorDialog dialog( color.as_colorref() ) ; // current color is default
if ( dialog.DoModal() == IDCANCEL )
{
return 0L ;
}
// get the color the user picked
const CColorRef newcolor(dialog.GetColor()) ;
m_props->m_view_props.m_data.m_back_color = (int)newcolor.as_colorref() ;
m_props->m_view_props.write_to_registry() ;
// turn it into an HTML tag
m_view_interface.set_bg_color( newcolor.as_wstring() ) ;
return 0L ;
#endif
}
//! Get the source and target languages for saving current memory as TMX.
void MemoryWindowFrame::set_exporter_src_and_target_langs(CExportDialog &dialog, CTMXWriter &exporter)
{
exporter.set_src_lang( string2wstring( dialog.get_source_plain() ) ) ;
exporter.set_target_lang( string2wstring( dialog.get_trans_plain() ) ) ;
}
//! Export the top memory as a TMX memory.
bool MemoryWindowFrame::export_tmx( const CString &file_name, mem_engine::memory_pointer mem )
{
CExportDialog dialog ;
if ( IDCANCEL == dialog.DoModal() )
{
return false ;
}
CTMXWriter exporter( static_cast< CProgressListener* >( this ),
m_props,
m_props->m_gen_props.get_user_name()) ;
set_exporter_src_and_target_langs(dialog, exporter);
file::CPath path(file_name) ;
path.RemoveExtension() ;
path.AddExtension( _T(".tmx" ) ) ;
mem->set_location( path.Path() ) ;
exporter.write_memory( mem ) ;
return true ;
}
//! Exports the current memory as a trados text file
bool MemoryWindowFrame::export_trados( const CString &file_name, mem_engine::memory_pointer mem )
{
ATLASSERT ( m_model->empty() == false ) ;
ATLASSERT ( ! file_name.IsEmpty() ) ;
CExportDialog dialog ;
if ( IDCANCEL == dialog.DoModal() )
{
return false ;
}
// get a set of the fonts used in our current memory
font_tabulator tabulator ;
mem->tabulate_fonts( tabulator ) ;
file::CPath path(file_name) ;
path.RemoveExtension() ;
path.AddExtension( _T(".txt" ) ) ;
mem->set_location( path.Path() ) ;
// create the exporter
TradosDataExporter exporter( tabulator.get_font_set( ),
static_cast< CProgressListener* >( this ),
this->m_props) ;
if ( ! exporter.open_destination( path.Path() ) )
{
user_feedback( IDS_MSG_EXPORT_FAILED ) ;
THROW_WIN_EXCEPTION( R2T( IDS_MSG_EXPORT_FAILED ) ) ;
}
exporter.set_source( dialog.get_source_plain() ) ;
exporter.set_target( dialog.get_trans_plain() ) ;
exporter.export_trados( mem ) ;
return true ;
}
//! WM_CREATE message handler
LRESULT MemoryWindowFrame::on_create( WindowsMessage &message )
{
message ;
SENSE("on_create") ;
try
{
logging::log_debug("Creating mainframe window") ;
// the global parser object
ATLASSERT( IsWindow() ) ;
// set big icon
SetIcon( LoadIcon( _Module.GetResourceInstance(), MAKEINTRESOURCE( IDR_ICON ) ), TRUE ) ;
// read our properties from the registry
m_appstate.read_from_registry() ;
load_mousewheel_setting();
input_device_ptr input(new InputDeviceFile) ;
output_device_ptr output(new OutputDeviceFile) ;
m_rules.load(input, output) ;
// the view
logging::log_debug("Initializing mainframe view") ;
m_hWndClient = init_view() ;
m_view_interface.set_accel(m_hAccel) ;
ATLASSERT(m_view_state == &m_view_state_initial) ;
set_display_state( INIT_DISPLAY_STATE ) ;
ATLASSERT(m_view_state == &m_view_state_initial) ;
m_view_state->show_content() ;
set_up_recent_docs_list() ;
set_up_command_bars() ;
init_status_bar() ;
// register object for message filtering and idle updates
#ifndef UNIT_TEST
set_up_ui_state() ;
CMessageLoop* pLoop = _Module.GetMessageLoop() ;
ATLASSERT(pLoop != NULL) ;
if (pLoop)
{
pLoop->AddIdleHandler(this) ;
}
#endif
// the glossary window
logging::log_debug("Setting up the glossary window") ;
add_glossary_window(m_props) ;
// set the title
set_window_title() ;
set_up_window_size() ;
UpdateLayout() ; // the toolbar
init_item_colors();
::DragAcceptFiles( m_hWnd, TRUE ) ;
init_background_processor();
SetFocus() ;
::PostMessage( m_hWnd, WM_COMMAND, MAKEWPARAM( IDC_STARTUP_CHECKS, 100 ), 0 ) ;
logging::log_debug("Checking load history") ;
check_load_history() ;
set_bg_color_if_needed() ;
logging::log_debug("Checking command line") ;
const int language = m_props->m_gen_props.m_data.m_preferred_gui_lang ;
commandline_options options(GetCommandLine(), static_cast<WORD>(language)) ;
check_command_line(options, get_input_device()) ;
if (language != options.m_language)
{
SetUILanguage(options.m_language) ;
}
set_doc_ui_handler();
}
catch (CException&)
{
logging::log_error("Failure in mainframe initialization routine") ;
throw ;
}
return 0L;
}
//! Check whether the preferences say to load the previous
//! memories, and load them if so.
void MemoryWindowFrame::check_load_history( )
{
if ( ! m_props->m_gen_props.load_prev_mem_on_startup() )
{
return ;
}
load_history();
}
//! See if the command line has us loading any memories.
void MemoryWindowFrame::check_command_line(commandline_options &options, input_device_ptr input)
{
FOREACH(tstring filename, options.m_tm_files)
{
CString cfilename = filename.c_str() ;
load_felix_memory(false, cfilename);
}
FOREACH(tstring filename, options.m_glossary_files)
{
CString cfilename = filename.c_str() ;
this->get_glossary_window()->load(cfilename, false) ;
}
FOREACH(tstring filename, options.m_xml_files)
{
memory_pointer mem(new memory_local(m_props)) ;
mem->load(filename.c_str()) ;
if (mem->get_memory_info()->is_memory())
{
this->add_memory(mem) ;
}
else
{
this->get_glossary_window()->add_glossary(mem) ;
}
}
FOREACH(tstring filename, options.m_multiterm_files)
{
this->get_glossary_window()->import_multiterm(CString(filename.c_str())) ;
}
FOREACH(tstring filename, options.m_tmx_files)
{
this->import_tmx(CString(filename.c_str()), input) ;
}
FOREACH(tstring filename, options.m_trados_text_files)
{
this->import_trados(CString(filename.c_str())) ;
}
if (! options.m_prefs_file.empty())
{
if (options.m_new_prefs_format)
{
m_props->load_file(options.m_prefs_file) ;
}
else
{
this->load_old_preferences(options.m_prefs_file.c_str()) ;
}
}
}
//! Handle a user exit command
LRESULT MemoryWindowFrame::on_file_exit( WindowsMessage &message )
{
message ;
SENSE("on_file_exit") ;
#ifdef UNIT_TEST
return 0L ;
#else
PostMessage(WM_CLOSE);
return 0L;
#endif
}
/** Deletes the current entry.
*/
LRESULT MemoryWindowFrame::on_delete_entry( WindowsMessage &message )
{
message ;
SENSE("on_delete_entry") ;
#ifdef UNIT_TEST
return 0L ;
#else
if ( m_view_interface.is_edit_mode() )
{
m_view_interface.do_delete() ;
}
else
{
delete_current_translation() ;
}
return 0L;
#endif
}
/** Peform a find.
* We use different dialogs depending on whether we're in edit mode.
*/
LRESULT MemoryWindowFrame::on_find( WindowsMessage &message )
{
message ;
SENSE("on_find") ;
#ifdef UNIT_TEST
return 0L ;
#else
if ( m_view_interface.is_edit_mode() )
{
if ( m_edit_replace.IsWindow() && m_edit_replace.IsWindowVisible() )
{
m_edit_replace.ShowWindow( SW_HIDE ) ;
}
m_edit_find.set_document( m_view_interface.get_document() ) ;
// we will make sure that the edit find window
// is created, and then show it
init_edit_find_window( SW_SHOW ) ;
}
else
{
handle_find() ;
}
return 0L ;
#endif
}
/** The Replace dialog has told us that it's time to do a replace.
* We don't allow this message while not in edit mode.
*/
LRESULT MemoryWindowFrame::on_edit_replace( WindowsMessage &message )
{
message ;
SENSE("on_edit_replace") ;
#ifdef UNIT_TEST
return 0L ;
#else
if ( m_view_interface.is_edit_mode() == false )
{
on_new_search(message) ;
m_search_window.show_replace_page() ;
}
else
{
if ( m_edit_find.IsWindow() && m_edit_find.IsWindowVisible() )
{
m_edit_find.ShowWindow( SW_HIDE ) ;
}
m_edit_replace.set_document( m_view_interface.get_document() ) ;
init_edit_replace_window( SW_RESTORE ) ;
}
return 0L ;
#endif
}
/** The user has chosen to get concordance via the dialog.
* Edit -> Find -> Concordance.
*/
LRESULT MemoryWindowFrame::on_concordance( WindowsMessage &message )
{
message ;
SENSE("on_concordance") ;
#ifdef UNIT_TEST
return 0L ;
#else
CConcordanceDialog dialog ;
if ( IDCANCEL == dialog.DoModal() )
{
return 0L ;
}
const wstring query = string2wstring( dialog.get_text() ) ;
if ( query.length() > 0 )
{
get_concordances( query ) ;
}
return 0L ;
#endif
}
/** Adds a new glossary window.
* File -> New -> Glossary.
*/
LRESULT MemoryWindowFrame::on_new_glossary( WindowsMessage &message )
{
message ;
SENSE("on_new_glossary") ;
add_glossary_window(m_props) ;
return 0L ;
}
/** Adds a new glossary window.
*/
bool MemoryWindowFrame::add_glossary_window(app_props::props_ptr props)
{
const int sw_command = get_gloss_show_command() ;
gloss_window_pointer gloss_window = m_glossary_windows.m_add(props) ;
// we will work a seam into this
#ifndef UNIT_TEST
if(!m_glossary_windows.create(gloss_window, m_hWnd))
{
return false ;
}
#endif
if ( m_glossary_windows.size() == 1 ) // we have just added the only one...
{
gloss_window->m_apply_settings(sw_command) ;
}
#ifndef UNIT_TEST
gloss_window->ShowWindow(sw_command);
#endif
gloss_window->set_listener( static_cast< CGlossaryWinListener* >( this ) ) ;
return true ;
}
/** Handles the new file command. Creates a new memory.
* File -> New -> Memory.
*/
LRESULT MemoryWindowFrame::on_file_new( WindowsMessage &message )
{
message ;
SENSE("on_file_new") ;
memory_pointer mem = m_model->create_memory() ;
add_memory( mem ) ;
user_feedback( IDS_NEW ) ;
return 0L ;
}
/** Handles file open command.
*/
LRESULT MemoryWindowFrame::on_file_open( WindowsMessage &message )
{
message ;
SENSE("on_file_open") ;
#ifdef UNIT_TEST
return 0L ;
#else
// get the file name
file_open_dialog dialog;
dialog.set_title(R2T(IDS_OPEN));
dialog.set_file_filter(get_mem_open_filter());
dialog.allow_multi_select();
if (!m_props->m_history_props.m_memory_location.empty())
{
dialog.set_last_save(m_props->m_history_props.m_memory_location);
}
user_feedback( IDS_OPEN ) ;
if (!dialog.show())
{
user_feedback(IDS_CANCELLED_ACTION);
return 0L;
}
auto filenames = dialog.get_open_destinations();
switch (dialog.get_selected_index())
{
case 1: case 4:
ATLTRACE( "Open Felix memory files.\n" ) ;
break;
case 2:
import_tmx(filenames, get_input_device());
return 0L ;
case 3:
import_trados(filenames);
return 0L ;
default:
ATLASSERT ( FALSE && "Unknown case in switch statement" ) ;
}
// They are regular memory files
for(CString filename: filenames)
{
load(filename) ;
}
set_window_title() ;
return 0L ;
#endif
}
/** Handle the BeforeNavigate2 event from the MSHTML view.
* If a file was dropped, load it.
*/
bool MemoryWindowFrame::OnBeforeNavigate2( _bstr_t url )
{
SENSE("OnBeforeNavigate2") ;
try
{
// "#" is used for JavaScript links.
wstring _url = BSTR2wstring(url) ;
if(boost::ends_with(_url, L"#"))
{
return false ; // don't cancel
}
const CString filename(static_cast< LPCWSTR >( url )) ;
const file::CFileExtension ext(filename) ;
if (ext.is_xml() || ext.equals(_T(".ftm")) || ext.equals(_T(".tmx")) || ext.is_txt())
{
this->load(filename) ;
return true ; // should cancel
}
if (ext.equals(".fprefs"))
{
this->load_old_preferences(filename) ;
return true ;
}
if (ext.equals(".fprefx"))
{
this->m_props->load_file((LPCWSTR)filename) ;
return true ;
}
wstring raw_command = BSTR2wstring( url );
/***********************************************************************
There are two url navigation schemes here:
- destination_parser
- CNavUrl
We've got to consolidate this into one scheme.
Also, the newer components (SearchWindow, ManagerWindow) use the
simpler tokenize-and-parse scheme. I think we should switch to this
for the mainframe and glossary windows, too.
*************************************************************************/
destination_parser parser ;
// will return NULL if fails to parse
const LPMSG pMsg = parser.parse( raw_command ) ;
if ( pMsg )
{
WindowsMessage message( pMsg->hwnd, pMsg->message, pMsg->wParam, pMsg->lParam ) ;
switch( pMsg->wParam )
{
case IDC_NAV:
on_user_nav( pMsg->lParam ) ;
return true ;
case IDC_EDIT:
on_user_edit( message ) ;
return true ;
case IDC_DELETE:
on_user_delete( static_cast<size_t>(pMsg->lParam) ) ;
return true ;
case IDC_ADD_TO_GLOSSARY:
on_user_add_to_glossary( pMsg->lParam ) ;
return true ;
case IDC_REGISTER:
on_user_register( pMsg->lParam ) ;
return true ;
case IDC_TOGGLE_MARK:
on_user_toggle_markup( message ) ;
return true ;
}
}
CNavUrl nav_url (static_cast< CNavInterface* >( this )) ;
nav_url.process_url(url) ;
return nav_url.should_cancel() ;
}
catch (CException& e)
{
logging::log_exception(e) ;
e.notify_user(_T("Failed to process action")) ;
}
catch (_com_error& e)
{
CComException cx(e) ;
logging::log_exception(cx) ;
cx.notify_user(_T("Failed to process action\rAn error occurred connecting to a COM server.")) ;
}
catch (std::exception& e)
{
logging::log_error("Standard library exception (Main Window)") ;
logging::log_exception(e) ;
const UINT msg_flags = MB_OK | MB_ICONSTOP | MB_SETFOREGROUND ;
::MessageBox( m_hWnd, CA2T(e.what()), _T("C Runtime Error in Main Window"), msg_flags ) ;
}
return true ;
}
/** Save the top memory.
* File -> Save.
*/
LRESULT MemoryWindowFrame::on_file_save(WindowsMessage &)
{
SENSE("on_file_save") ;
if ( m_model->empty() )
{
SENSE("empty") ;
return 0L ;
}
memory_pointer mem = m_model->get_first_memory() ;
if ( mem->is_new() )
{
WindowsMessage message ;
on_file_save_as(message) ;
return 0L ;
}
do_save( mem ) ;
return 0L ;
}
/** Perform a file save.
* We already have the location.
*/
void MemoryWindowFrame::do_save( memory_pointer mem )
{
const file::CFileExtension ext = mem->get_location() ;
if ( ext.equals( _T(".txt") ) || ext.equals( _T(".tmx") ) || ext.equals( _T(".xls") ) )
{
handle_foreign_file_save(mem, ext);
}
else
{
save_memory( mem ) ;
}
set_window_title() ;
}
/** Save a memory that was imported from another format.
*/
void MemoryWindowFrame::handle_foreign_file_save(memory_pointer& mem, const file::CFileExtension& ext)
{
switch ( wants_to_save_in_native_format() )
{
case IDYES:
if ( ext.equals( _T(".txt") ) )
{
export_trados( mem->get_location(), mem ) ;
}
else if ( ext.equals( _T(".xls") ) )
{
export_excel(mem->get_location(), mem) ;
}
else
{
export_tmx( mem->get_location(), mem ) ;
}
break ;
case IDNO:
save_memory( mem ) ;
break ;
case IDCANCEL:
return ;
}
}
/** Saves the top memory with a new name.
* File -> Save As.
*/
LRESULT MemoryWindowFrame::on_file_save_as(WindowsMessage &)
{
SENSE("on_file_save_as") ;
#ifdef UNIT_TEST
return 0L ;
#else
if ( m_model->empty() )
{
user_feedback(IDS_NO_MATCHES) ;
::MessageBeep( MB_ICONINFORMATION ) ;
return 0L ;
}
// clearing location won't work, because we want to offer the current location
// as the default file name
memory_pointer mem = m_model->get_first_memory() ;
save_memory_as(mem);
return 0L ;
#endif
}
/** Responds to WM_CLOSE message.
*/
LRESULT MemoryWindowFrame::on_close( WindowsMessage &message )
{
SENSE("on_close") ;
#ifndef UNIT_TEST
// if the user cancels during the save query, then take no action.
if ( IDCANCEL == check_save() )
{
SetMsgHandled( TRUE ) ;
return 1L ;
}
if ( false == gloss_win_shutdown_check() )
{
return 1L ;
}
// do it twice, in case we chose a location that clashes after the check...
if ( false == gloss_win_shutdown_check() )
{
return 1L ;
}
save_settings_close();
#endif
message.notHandled() ;
return 0L;
}
/** Responds to WM_DESTROY message.
*/
LRESULT MemoryWindowFrame::on_destroy( WindowsMessage &message )
{
// let the base window procs get a chance
message.notHandled() ;
SENSE("on_destroy") ;
#ifdef UNIT_TEST
return 0L ;
#else
ATLASSERT( IsWindow() ) ; // we still need to be a window because...
if(m_search_window.IsWindow())
{
m_search_window.DestroyWindow() ;
}
if (m_manager_window.IsWindow())
{
m_manager_window.DestroyWindow() ;
}
save_settings_destroy();
// no longer the first launch
m_props->m_gen_props.set_not_first_launch() ;
m_props->write_to_registry() ;
m_statusbar.release() ;
// unregister message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
if (pLoop)
{
pLoop->RemoveMessageFilter(this);
pLoop->RemoveIdleHandler(this);
}
// if UI is the last thread, no need to wait
if(_Module.GetLockCount() == 1)
{
_Module.m_dwTimeOut = 0L;
_Module.m_dwPause = 0L;
}
_Module.Unlock();
return 0L ;
#endif
}
/** See if we should save our memory/glossary history.
* If so, we'll load the same memories/glossaries on next startup.
*/
void MemoryWindowFrame::record_loaded_memory_history()
{
app_props::properties_loaded_history *history_props = &m_props->m_history_props ;
history_props->m_loaded_mems.clear() ;
history_props->m_loaded_remote_mems.clear() ;
m_model->record_loaded_memories(history_props->m_loaded_mems, history_props->m_loaded_remote_mems) ;
history_props->write_to_registry() ;
}
/** Toggle toolbar visibility.
*/
LRESULT MemoryWindowFrame::on_view_toolbar(WindowsMessage &)
{
SENSE("on_view_toolbar") ;
#ifdef UNIT_TEST
return 0L ;
#else
m_appstate.m_is_toolbar_visible = !m_appstate.m_is_toolbar_visible;
CReBarCtrl rebar = m_hWndToolBar;
const int nBandIndex = rebar.IdToIndex(ATL_IDW_BAND_FIRST + 1); // toolbar is 2nd added band
rebar.ShowBand(nBandIndex, m_appstate.m_is_toolbar_visible);
UISetCheck(ID_VIEW_TOOLBAR, m_appstate.m_is_toolbar_visible);
UpdateLayout();
return 0;
#endif
}
/** Toggle edit mode.
*/
LRESULT MemoryWindowFrame::on_view_edit_mode(WindowsMessage &)
{
SENSE("on_view_edit_mode") ;
#ifdef UNIT_TEST
return 0L ;
#else
const bool edit_mode_enabled = m_view_interface.is_edit_mode() ;
UISetCheck(ID_VIEW_EDIT_MODE, ! edit_mode_enabled );
// swap out the various find dialogs...
SwapFindDialogs(edit_mode_enabled) ;
m_view_state->handle_toggle_edit_mode() ;
return 0L ;
#endif
}
/** Toggle status bar visibility.
*/
LRESULT MemoryWindowFrame::on_view_status_bar( WindowsMessage &message )
{
message ;
SENSE("on_view_status_bar") ;
#ifdef UNIT_TEST
return 0L ;
#else
m_appstate.m_is_statusbar_visible = !::IsWindowVisible(m_hWndStatusBar);
::ShowWindow(m_hWndStatusBar, m_appstate.m_is_statusbar_visible ? SW_SHOWNOACTIVATE : SW_HIDE);
UISetCheck(ID_VIEW_STATUS_BAR, m_appstate.m_is_statusbar_visible );
UpdateLayout();
return 0;
#endif
}
/** Switch to match view.
* View -> Current View -> Match View.
*/
LRESULT MemoryWindowFrame::on_view_match( WindowsMessage &message )
{
message ;
SENSE("on_view_match") ;
#ifdef UNIT_TEST
return 0L ;
#else
// the current match...
if ( ! m_trans_matches.empty() ) // we have 0 matches, just a query
{
recalculate_match(m_trans_matches.current(), m_trans_matches.m_params);
}
set_display_state ( MATCH_DISPLAY_STATE ) ;
show_view_content( ) ;
m_view_interface.set_scroll_pos(0) ;
return 0L ;
#endif
}
/** Switch to search view.
* View -> Current View -> Search View.
*/
LRESULT MemoryWindowFrame::on_view_search( WindowsMessage &message )
{
message ;
SENSE("on_view_search") ;
#ifdef UNIT_TEST
return 0L ;
#else
set_display_state( CONCORDANCE_DISPLAY_STATE ) ;
show_view_content() ;
m_view_interface.set_scroll_pos(0) ;
return 0L ;
#endif
}
// ==================================
// Help Menu Functions
// ==================================
/*!
* Show the About dialog.
*/
LRESULT MemoryWindowFrame::show_about_dialog(WindowsMessage &)
{
SENSE("show_about_dialog") ;
logging::log_debug("Showing the About dialog.") ;
#ifdef UNIT_TEST
return 0L ;
#else
CAboutDialog dlg(cpptempl::get_template_filename(_T("about.html"))) ;
dlg.DoModal();
return 0L ;
#endif
}
/** Help -> Help.
* Show the Felix help.
*/
LRESULT MemoryWindowFrame::on_help(WindowsMessage &)
{
CString filePath = get_help_file_path(get_docs_path()) ;
SENSE("on_help") ;
#ifdef UNIT_TEST
return 0L ;
#else
HINSTANCE result = ::ShellExecute(
m_hWnd, // HWND hwnd,
_T("open"), // LPCTSTR lpOperation,
filePath, // LPCTSTR lpFile,
NULL, // LPCTSTR lpParameters,
NULL, // LPCTSTR lpDirectory,
SW_SHOW // INT nShowCmd
);
check_shell_execute_result((int)result, filePath);
return 0L ;
#endif
}
/** Help -> FAQ.
* Show the FAQ.
*/
LRESULT MemoryWindowFrame::on_help_faq( WindowsMessage &)
{
SENSE("on_help_faq") ;
#ifdef UNIT_TEST
return 0L ;
#else
file::CPath faq_path ;
faq_path.GetModulePath(_Module.GetModuleInstance()) ;
faq_path.Append( _T("Docs\\Felix Help.chm") ) ;
if ( faq_path.FileExists() )
{
CString current_directory = faq_path.Path() ;
current_directory += _T("::/8.html") ;
HtmlHelp(m_hWnd, current_directory, HH_DISPLAY_TOPIC, NULL );
return 0L ;
}
HINSTANCE result = ::ShellExecute(
NULL, // HWND hwnd,
_T("open"), // LPCTSTR lpOperation,
resource_string( IDS_FAQ_PATH ), // LPCTSTR lpFile,
NULL, // LPCTSTR lpParameters,
NULL, // LPCTSTR lpDirectory,
SW_SHOW // INT nShowCmd
);
CString file_path = resource_string( IDS_FAQ_PATH ) ;
check_shell_execute_result((int)result, file_path) ;
return 0L ;
#endif
}
/** Register glossary entries.
* Use the appropriate translation-memory entry as the base
* according to the current state.
*/
LRESULT MemoryWindowFrame::on_register_gloss(WindowsMessage &)
{
switch( get_display_state() )
{
case NEW_RECORD_DISPLAY_STATE:
SENSE("[NEW_RECORD_DISPLAY_STATE]") ;
ATLASSERT(m_view_state == &m_view_state_new) ;
on_user_register( 0 ) ;
return 0L ;
case MATCH_DISPLAY_STATE:
SENSE("[MATCH_DISPLAY_STATE]") ;
on_user_register( m_trans_matches.current_pos() ) ;
return 0L ;
case CONCORDANCE_DISPLAY_STATE:
SENSE("[CONCORDANCE_DISPLAY_STATE]") ;
on_user_register( m_search_matches.current_pos() ) ;
return 0L ;
default:
SENSE("[Other display state]") ;
on_user_register( 0 ) ;
return 0L ;
}
}
/** Get the translation matches.
* Use params as the parameters and put the matches in matches.
*/
void MemoryWindowFrame::get_matches(trans_match_container &matches, search_query_params ¶ms)
{
const double MATCH_THRESHOLD = 0.9999 ;
m_model->find_matches(matches, params) ;
if (!params.m_place_numbers &&
!params.m_place_gloss &&
!params.m_place_rules &&
!params.m_show_gloss_matches)
{
logging::log_debug("no placement options selected; bailing") ;
return ;
}
trans_match_container placed_numbers ;
trans_match_container placed_gloss ;
trans_match_container placed_rules;
FOREACH(search_match_ptr match, matches)
{
if ( match->get_score() < MATCH_THRESHOLD )
{
if (params.m_place_numbers)
{
check_placement_numbers(placed_numbers, match);
}
if (params.m_place_gloss)
{
check_placement_gloss(placed_gloss, match);
}
if (params.m_place_rules)
{
check_placement_rules(placed_rules, match);
}
}
if(params.m_show_gloss_matches)
{
show_gloss_matches(this->m_glossary_windows.get_current_matches(), match);
}
}
// Now place the gloss in the number matches.
// This will get unwieldy with too many more types of
// placement...
// Got to redo this logic!
FOREACH(search_match_ptr match, placed_numbers)
{
check_placement_gloss(placed_gloss, match);
}
// now add in all our placements
FOREACH(search_match_ptr match, placed_numbers)
{
matches.insert(match) ;
if(params.m_show_gloss_matches)
{
show_gloss_matches(this->m_glossary_windows.get_current_matches(), match);
}
}
FOREACH(search_match_ptr match, placed_gloss)
{
matches.insert(match) ;
if(params.m_show_gloss_matches)
{
show_gloss_matches(this->m_glossary_windows.get_current_matches(), match);
}
}
FOREACH(search_match_ptr match, placed_rules)
{
matches.insert(match) ;
if(params.m_show_gloss_matches)
{
show_gloss_matches(this->m_glossary_windows.get_current_matches(), match);
}
}
}
void MemoryWindowFrame::show_gloss_matches(mem_engine::felix_query *query, search_match_ptr match)
{
logging::log_debug("MemoryWindowFrame: showing gloss matches in query") ;
if(!query)
{
logging::log_warn("NULL query received from gloss window collection") ;
return ;
}
pairings_t &pairings = match->match_pairing().get() ;
mem_engine::gloss_match_set gloss_sources ;
for(size_t i = 0 ; i < query->size() ; ++i)
{
search_match_ptr gloss_match = query->at(i) ;
const wstring source = gloss_match->get_record()->get_source_plain() ;
gloss_sources.insert(source) ;
}
mem_engine::placement::mark_up_gloss_matches(pairings, gloss_sources) ;
match->match_pairing().set(pairings) ;
match->get_markup()->SetQuery( match->match_pairing().mark_up_query() ) ;
}
/** Initializes the transaction matches for a new lookup.
*/
void MemoryWindowFrame::init_trans_matches_for_lookup( const wstring query )
{
m_trans_matches.clear() ;
m_trans_matches.set_query( query ) ;
init_lookup_properties(m_props, m_trans_matches.m_params);
}
/** Look up a query string.
*/
bool MemoryWindowFrame::lookup(const wstring query)
{
if ( query.empty() )
{
user_feedback( IDS_EMPTY_QUERY ) ;
::MessageBeep( MB_ICONINFORMATION ) ;
return false ;
}
m_model->set_reverse_lookup(false) ;
// only do searching when edit mode is off
m_view_interface.put_edit_mode( false ) ;
// do glossary lookup as well
m_glossary_windows.look_up( query ) ;
// now do TM lookup
init_trans_matches_for_lookup(query);
trans_match_container matches ;
get_matches(matches, m_trans_matches.m_params);
m_trans_matches.set_matches(matches) ;
// give the user feedback
provide_user_trans_feedback();
set_display_state ( MATCH_DISPLAY_STATE ) ;
show_view_content() ;
return true ;
}
/** Gets the currently displayed translation.
*/
wstring MemoryWindowFrame::get_current_translation()
{
if ( m_trans_matches.empty() )
{
return wstring( ) ;
}
search_match_ptr current = m_trans_matches.current() ;
return get_record_translation(current->get_record());
}
/** Shows the next match.
*/
bool MemoryWindowFrame::next_match()
{
if ( m_trans_matches.empty() )
{
return false ;
}
m_trans_matches.forward() ;
if ( m_model->is_reverse_lookup() )
{
look_up_current_source_in_gloss();
}
show_view_content() ;
return true ;
}
/** Shows the previous match.
*/
bool MemoryWindowFrame::prev_match()
{
if ( m_trans_matches.empty() )
{
return false ;
}
m_trans_matches.back() ;
if ( m_model->is_reverse_lookup() )
{
look_up_current_source_in_gloss();
}
show_view_content() ;
return true ;
}
/** Gets the current query.
*/
wstring MemoryWindowFrame::get_current_query()
{
if ( m_model->is_reverse_lookup() )
{
return m_trans_matches.get_source_rich() ;
}
return m_trans_matches.get_query_rich() ;
}
/** Sets the translation for the current query.
*/
bool MemoryWindowFrame::set_translation( const wstring translation)
{
try
{
TRUE_ENFORCE( ! m_trans_matches.get_query_rich().empty(), IDS_NO_QUERIES ) ;
TRUE_ENFORCE( ! translation.empty(), IDS_EMPTY_TRANSLATION ) ;
if (get_display_state() == NEW_RECORD_DISPLAY_STATE)
{
ATLASSERT(m_view_state == &m_view_state_new) ;
return this->correct_trans(translation) ;
}
record_pointer record(new record_local()) ; // a new record
// the query is the source for our translation
record->set_source( m_trans_matches.get_query_rich() ) ;
// the user has kindly furnished a translation
record->set_trans( translation ) ;
// sanity checking
ATLASSERT( record->get_source_rich().empty() == false ) ;
ATLASSERT( record->get_trans_rich().empty() == false ) ;
if (record->get_source_rich().empty())
{
throw except::CException(IDS_EMPTY_QUERY) ;
}
if (record->get_trans_rich().empty())
{
throw except::CException(IDS_EMPTY_TRANSLATION) ;
}
// it was created now
record->create() ;
add_record_to_memory( record ) ;
// If the max add length is 0, then we don't add the entry to the glossary.
// Made this explicit in the code below.
if ( should_add_record_to_glossary(record))
{
m_glossary_windows.add_record(record) ;
}
// now, set the display content
m_new_record = record ;
set_display_state ( NEW_RECORD_DISPLAY_STATE ) ;
m_view_state = &m_view_state_new ;
show_view_content( ) ;
return true ;
}
catch( CException &e )
{
logging::log_exception(e) ;
e.notify_user( IDS_TRANS_SET_FAILED ) ; // TEXT("Failed to set translation.") ) ;
return false ;
}
}
/*!
* Registers a new glossary entry with the query as source, and trans as the translation.
*/
bool MemoryWindowFrame::register_trans_to_glossary(const wstring trans)
{
if ( m_trans_matches.m_params.get_source_rich().empty() )
{
MessageBox( resource_string( IDS_NO_QUERIES ), resource_string( IDS_INVALID_ACTION ), MB_OK | MB_ICONEXCLAMATION | MB_SETFOREGROUND ) ;
return false ;
}
record_pointer record(new mem_engine::record_local);
record->set_source( m_trans_matches.m_params.get_source_rich() ) ;
record->set_trans( trans ) ;
record->create() ;
m_glossary_windows.add_record(record) ;
// give the user feedback
user_feedback( IDS_MSG_ADDED_GLOSS_ENTRY_TITLE ) ;
return true ;
}
/** Delete the current translation.
*
* Also deletes matching glossary entries.
*
* \todo
* Make undoable.
*/
void MemoryWindowFrame::delete_current_translation()
{
on_user_delete( m_view_state->get_current() ) ;
}
/** Get concordance for query_string.
* Concordances are co-locations of query_string in the source
* fields of memory records.
*/
bool MemoryWindowFrame::get_concordances(const wstring query_string )
{
// an empty string would retrieve everything - probably not what the user wants!
if ( query_string.empty() )
{
user_feedback(IDS_EMPTY_QUERY) ;
return false ;
}
// only do searching when edit mode is off
m_view_interface.put_edit_mode( false ) ;
// remember where we were
// in the future, make an array of states to allow Explorer-style page navigation
set_display_state ( CONCORDANCE_DISPLAY_STATE ) ;
// this will hold our matches
m_search_matches.clear() ;
m_search_matches.set_query( query_string ) ;
m_search_matches.m_params.m_ignore_case = true ;
m_search_matches.m_params.m_ignore_width = !! m_props->m_gloss_props.m_data.m_ignore_width ;
m_search_matches.m_params.m_ignore_hira_kata = !! m_props->m_gloss_props.m_data.m_ignore_hir_kat ;
perform_concordance_search(m_search_matches.m_params);
show_view_content() ;
m_view_interface.set_scroll_pos(0) ;
// give the user feedback
source_concordance_feedback();
return true ;
}
/** Get the glossary entry at index from the main glossary window.
*/
wstring MemoryWindowFrame::get_glossary_entry(short index)
{
return m_glossary_windows.get_glossary_entry(index) ;
}
/** Get the score for a given match.
* If index is -1, returns the score for the current match.
*/
double MemoryWindowFrame::get_score( const short index )
{
if ( m_trans_matches.size() == 0 )
{
return 0.0 ;
}
if ( index < 0 ) // less than 0 means "current match"
{
return m_trans_matches.current()->get_score() ;
}
else
{
if ( static_cast<size_t>( index ) >= m_trans_matches.size() )
{
MessageBeep(MB_ICONEXCLAMATION) ;
user_feedback(IDS_OUT_OF_RANGE) ;
return 0.0 ;
}
return m_trans_matches.at( static_cast<size_t>(index) )->get_score() ;
}
}
/** Callback from glossary window telling us to add a record.
*/
bool MemoryWindowFrame::gloss_add_record( record_pointer rec )
{
add_record(rec) ;
return true ;
}
/** Make sure that we aren't saving the glossary to a filename
* already taken by a memory.
*/
INT_PTR MemoryWindowFrame::gloss_check_save_location( memory_pointer mem )
{
const CString mem_loc = mem->get_location() ;
if (! m_model->has_name_clash(mem_loc))
{
return IDYES ;
}
return prompt_user_for_overwrite(mem->get_location());
}
/** Do a search using the parameters in the find dialog.
* The user has clicked "Find" in the find dialog.
*/
LRESULT MemoryWindowFrame::on_user_search(WindowsMessage &)
{
SENSE("on_user_search") ;
perform_user_search();
show_user_search_results();
// give the user feedback
provide_user_search_feedback() ;
return 0 ;
}
/** Transfers the parameters from the replace dialog to the
* find dialog.
*/
LRESULT MemoryWindowFrame::on_user_edit_replace(WindowsMessage &)
{
SENSE("on_user_edit_replace") ;
m_edit_find.set_search_params( m_edit_replace.get_search_params() ) ;
return 0 ;
}
/** The user has told us to edit an entry.
* If the index is out of range, call up the add record dialog instead.
*/
LRESULT MemoryWindowFrame::on_user_edit(WindowsMessage &message)
{
SENSE("on_user_edit") ;
const size_t num = static_cast<size_t>(message.lParam) ;
m_view_state->set_current(num) ;
m_editor->m_is_add = false ;
m_view_state->on_user_edit() ;
return 0L ;
}
/** Responds to user command to delete memory entry.
*/
LRESULT MemoryWindowFrame::on_user_delete(size_t num )
{
SENSE("on_user_delete") ;
m_view_state->delete_match(num) ;
return 0L ;
}
/** Shows register glossary entry dialog.
*/
LRESULT MemoryWindowFrame::on_user_register(LPARAM num )
{
SENSE("on_user_register") ;
record_pointer rec = get_reg_gloss_record(static_cast<size_t>(num));
m_reg_gloss_dlg.set_record( rec ) ;
if ( m_glossary_windows.empty() )
{
add_glossary_window(m_props) ;
}
ATLASSERT ( m_glossary_windows.empty() == false ) ;
m_reg_gloss_dlg.set_gloss_window(m_glossary_windows.first()) ;
#ifdef UNIT_TEST
return 0 ;
#else
if ( ! m_reg_gloss_dlg.IsWindow() )
{
create_reg_gloss_window();
}
m_reg_gloss_dlg.ShowWindow( SW_SHOW ) ;
wstring selection = m_view_interface.get_selection_text() ;
if (! selection.empty())
{
m_reg_gloss_dlg.set_initial_source(string2BSTR(selection)) ;
}
else
{
m_reg_gloss_dlg.fresh_record_focus() ;
}
return 0L ;
#endif
}
/** Adds a new record to the active memory.
*/
bool MemoryWindowFrame::add_record( const record_pointer record )
{
SENSE("add_record") ;
ATLASSERT( record->is_valid_record() ) ;
add_record_to_memory( record ) ;
m_new_record = record ;
set_display_state ( NEW_RECORD_DISPLAY_STATE ) ;
m_view_state = &m_view_state_new ;
this->show_view_content() ;
return true ;
}
/** Retrieves the active glossary window
*/
gloss_window_pointer MemoryWindowFrame::get_glossary_window()
{
if ( m_glossary_windows.empty() )
{
add_glossary_window(m_props) ;
}
return m_glossary_windows.first() ;
}
/** Show the view content.
*/
void MemoryWindowFrame::show_view_content()
{
if (! IsWindow())
{
logging::log_debug("Window is not created; no content to display.") ;
return ;
}
if ( m_min_view.IsWindow() && m_min_view.IsWindowVisible() )
{
m_min_view.show_content() ;
return ;
}
m_view_state_match.set_gloss_matches(get_glossary_window()->get_current_matches()) ;
m_view_state->show_content() ;
}
/** Check for existing memories loaded.
*
* Check whether the user wants to merge the memories if so.
*/
MemoryWindowFrame::MERGE_CHOICE MemoryWindowFrame::check_empty_on_load()
{
if ( m_model->empty() )
{
return MERGE_CHOICE_SEPARATE ;
}
user_feedback( IDS_MEMORY_OPEN ) ;
memory_pointer mem = m_model->get_first_memory() ;
CQueryMergeDlg dlg(IDS_MERGE_MEM_TITLE,
IDS_MERGE_MEM_TEXT,
file::CPath(mem->get_location()).Path()) ;
return get_merge_choice(dlg, &m_props->m_gen_props);
}
/** Get the translation for the entry at index.
*/
wstring MemoryWindowFrame::get_translation_at(short index)
{
const int CURRENT_INDEX = -1 ;
if ( index == CURRENT_INDEX )
{
return get_current_translation() ;
}
if ( m_trans_matches.empty() )
{
return wstring( ) ;
}
if ( static_cast<size_t>(index) >= m_trans_matches.size() )
{
MessageBeep(MB_ICONEXCLAMATION) ;
user_feedback(IDS_OUT_OF_RANGE) ;
return wstring() ;
}
search_match_ptr current = m_trans_matches.at( index ) ;
return get_record_translation(current->get_record());
}
/** Report how many records we have loaded.
*/
void MemoryWindowFrame::report_memory_after_load(size_t original_num)
{
memory_pointer mem = m_model->get_first_memory() ;
// get number of records loaded
const size_t num_records_after_load = mem->size() ;
const size_t num_records_loaded = num_records_after_load - original_num ;
CString arg1 ;
arg1.Format( _T("%u"), num_records_loaded ) ;
CString message ;
message.FormatMessage( IDS_MSG_ADDED_RECORDS, arg1, file::name( get_location() ).file_name() ) ;
user_feedback( message ) ;
}
/** Handles user navigation.
*/
LRESULT MemoryWindowFrame::on_user_nav(const LPARAM lParam )
{
SENSE("on_user_nav") ;
switch( lParam )
{
case IDC_PREV:
prev_display_state() ;
show_view_content() ;
return 0L ;
case IDC_PREV_MATCH:
prev_match() ;
return 0L ;
case IDC_NEXT_MATCH:
next_match() ;
return 0L ;
case IDC_MORE:
m_is_short_format = false ;
show_view_content() ;
return 0L ;
case IDC_LESS:
m_is_short_format = true ;
show_view_content() ;
return 0L ;
}
ATLASSERT( "We should never get here" && FALSE ) ;
return 0L ;
}
/** Add the entry at index lParam to the glossary.
* If the index is out of range, then give a beep and feedback in the
* status bar (we used to throw an exception).
*/
LRESULT MemoryWindowFrame::on_user_add_to_glossary(const LPARAM lParam )
{
SENSE("on_user_add_to_glossary") ;
const size_t index = static_cast<size_t>(lParam) ;
m_view_state->set_current(index) ;
record_pointer rec = m_view_state->get_current_match()->get_record();
get_glossary_window()->add_record(rec->clone());
return 0L ;
}
//! Exit without showing confirmation dialogs.
bool MemoryWindowFrame::exit_silently()
{
SENSE("exit_silently") ;
m_glossary_windows.exit_silently() ;
memory_list memories ;
m_model->get_memories_needing_saving( memories ) ;
FOREACH(memory_pointer mem, memories)
{
mem->set_saved_flag(true) ;
}
PostMessage(WM_CLOSE);
return true ;
}
/** Clears the active memory.
*/
bool MemoryWindowFrame::clear_memory()
{
if ( ! m_model->empty() )
{
memory_pointer mem = m_model->get_first_memory() ;
mem->clear_memory() ;
}
m_glossary_windows.clear_glossaries() ;
m_view_interface.set_text( wstring() ) ;
check_mousewheel() ;
set_window_title() ;
#ifndef UNIT_TEST
m_view_interface.set_scroll_pos(0) ;
#endif
CString msg ;
msg.FormatMessage( IDS_CLEARED_MEMORY, get_window_type_string() ) ;
user_feedback( msg );
// clear the matches
m_search_matches.clear() ;
m_trans_matches.clear() ;
return true ;
}
//============================
// Message handlers
//============================
LRESULT MemoryWindowFrame::on_tools_rule_manager(WindowsMessage &)
{
SENSE("on_tools_rule_manager") ;
logging::log_debug("Launching Rule Manager dialog.") ;
user_feedback( IDS_MANAGE_RULES );
#ifndef UNIT_TEST
// Call the COM server that will call up the rule manager.
// After it returns, we reload the rules. They may or may not have changed.
try
{
CDispatchWrapper wrapper(L"Felix.Preferences");
CComVariant language = L"English";
CComVariant prog = L"felix" ;
if( m_appstate.m_preferred_gui_lang == LANG_JAPANESE )
{
language = L"Japanese" ;
}
wrapper.method(L"RuleManager", prog, language) ;
wrapper.m_app = NULL ;
input_device_ptr input(new InputDeviceFile) ;
output_device_ptr output(new OutputDeviceFile) ;
m_rules.load(input, output) ;
}
catch (_com_error& err)
{
logging::log_error("Call to rule manager failed") ;
ATLASSERT(FALSE && "Raised exception in file_logger") ;
except::CComException ce(err) ;
logging::log_exception(ce) ;
ce.notify_user(_T("Rule Manager Error")) ;
}
catch(except::CException &e)
{
logging::log_error("Call to rule manager failed") ;
logging::log_exception(e) ;
e.notify_user(_T("Rule Manager Error")) ;
}
user_feedback( IDS_PREFS_REGISTERED ) ;
#endif
return 0L ;
}
/** Responds to Tools > Preferences menu selection.
*/
LRESULT MemoryWindowFrame::on_tools_preferences(WindowsMessage &)
{
SENSE("on_tools_preferences") ;
logging::log_debug("Launching Preferences dialog.") ;
user_feedback( IDS_SETTING_PREFS );
#ifndef UNIT_TEST
m_props->write_to_registry() ;
CPropertiesDlg props ;
INT_PTR result = props.DoModal() ;
if ( IDCANCEL == result || result <= 0 )
{
user_feedback( IDS_MSG_ACTION_CANCELLED ) ;
return 0L ;
}
*m_props = *props.get_properties() ;
m_props->write_to_registry() ;
reflect_preferences() ;
const wstring user_name = CT2W(m_props->m_gen_props.m_data.m_user_name) ;
set_record_username(user_name) ;
user_feedback( IDS_PREFS_REGISTERED ) ;
#endif
return 0L ;
}
/* This generates a divide-by-zero exception for
* testing purposes. It tests the exception logging and reporting
* feature.
*/
LRESULT MemoryWindowFrame::on_test_exception(WindowsMessage &)
{
logging::log_debug("Generating test exception") ;
int x = 3 ;
return (LRESULT)(5 / (x - 3)) ;
}
/** Responds to Tools > Language menu selection.
* Toggles UI language between Japanese and English.
*/
LRESULT MemoryWindowFrame::on_tools_switch_language(WindowsMessage &)
{
SENSE("on_tools_switch_language") ;
#ifdef UNIT_TEST
return 0L ;
#else
ATLASSERT( ! m_min_view.IsWindow() || ! m_min_view.IsWindowVisible() ) ;
switch( m_appstate.m_preferred_gui_lang )
{
case LANG_JAPANESE :
logging::log_debug("Switching UI language to English.") ;
SetUILanguage( LANG_ENGLISH ) ;
break ;
case LANG_ENGLISH :
logging::log_debug("Switching UI language to Japanese.") ;
SetUILanguage( LANG_JAPANESE ) ;
break ;
default:
ATLTRACE("** Unknown gui language: %d\n", m_appstate.m_preferred_gui_lang) ;
SetUILanguage( LANG_ENGLISH ) ;
}
return 0L ;
#endif
}
/** Show the find dialog.
*/
LRESULT MemoryWindowFrame::handle_find()
{
init_find_window( SW_RESTORE, IDS_MEMORY_SEARCH ) ;
return 0L ;
}
/** Edit the current translation match.
*/
LRESULT MemoryWindowFrame::on_edit_entry(WindowsMessage &)
{
SENSE("on_edit_entry") ;
WindowsMessage message( NULL, 0, 0, m_trans_matches.current_pos() ) ;
on_user_edit( message ) ;
return 0L ;
}
/** Show the add entry dialog.
*/
LRESULT MemoryWindowFrame::on_add(WindowsMessage &)
{
SENSE("on_add") ;
m_editor->m_is_add = true ;
show_edit_dialog_for_new_entry( IDS_ADD_ENTRY ) ;
return 0L ;
}
/** Set the window title.
* Complicated, ain't it?
*/
bool MemoryWindowFrame::set_window_title()
{
CString title = resource_string(IDS_MEMORY) +
_T(" [") +
get_active_mem_name() +
_T("]") ;
try
{
if (this->is_demo())
{
title += _T(" - ") ;
title += resource_string( IDS_DEMO_VER ) ;
}
}
catch (...)
{
logging::log_error("Failed to retrieve demo status") ;
ATLASSERT(FALSE && "Error getting demo status") ;
SetWindowText( title ) ;
return false ;
}
// refresh glossary window title as well
this->get_glossary_window()->set_window_title() ;
#ifndef UNIT_TEST
return FALSE != SetWindowText( title ) ;
#else
return true;
#endif
}
/** Reloads the UI text elements after switching GUI languages.
*/
void MemoryWindowFrame::set_ui_to_current_language()
{
logging::log_debug("Setting UI to current language") ;
try
{
refresh_command_bar() ;
set_lang_of_gloss_windows() ;
refresh_windows() ;
refresh_view_content();
// set new window title
set_window_title() ;
m_view_interface.set_accel(m_hAccel) ;
m_view_interface.ensure_document_complete( ) ;
// query user for color
set_bg_color( static_cast< COLORREF >( m_props->m_view_props.m_data.m_back_color ) );
// give user feedback
user_feedback( IDS_CHANGED_LANGUAGES ) ;
}
catch (CException& e)
{
logging::log_error("Failed to set current language") ;
logging::log_exception(e) ;
}
}
/** Sets the translation for the current query.
*/
void MemoryWindowFrame::set_translation_at(short index, const wstring translation )
{
const int CURRENT_INDEX = -1 ;
if ( m_trans_matches.empty() )
{
user_feedback(IDS_OUT_OF_RANGE) ;
return ;
}
search_match_ptr current ;
if ( index == CURRENT_INDEX )
{
current = m_trans_matches.current() ;
}
else
{
if ( static_cast<size_t>( index ) >= m_trans_matches.size() )
{
MessageBeep(MB_ICONEXCLAMATION) ;
user_feedback(IDS_OUT_OF_RANGE) ;
return ;
}
current = m_trans_matches.at( index ) ;
}
current->get_record()->set_trans( translation ) ;
}
/** import a list of tmx files.
*/
bool MemoryWindowFrame::import_tmx(std::vector<CString> import_files, input_device_ptr input)
{
for(CString filename: import_files)
{
import_tmx(filename, input) ;
}
return true ;
}
/** import a single tmx file.
*/
bool MemoryWindowFrame::import_tmx( const CString &file_name, input_device_ptr input )
{
memory_pointer mem = m_model->add_memory() ;
mem->set_is_memory(true) ;
CTMXReader reader( mem, static_cast< CProgressListener* >( this ) ) ;
reader.load_tmx_memory( file_name, input ) ;
// if we failed to load any entries, remove the memory
if ( mem->empty() )
{
m_model->remove_memory_by_id( mem->get_id() ) ;
user_feedback( get_load_failure_msg(file_name) ) ;
return false ;
}
mem->set_location(file_name) ;
// give feedback
feedback_loaded_mem( mem );
m_mru.AddToList( file_name ) ;
mem->set_is_memory(true) ;
mem->set_saved_flag(true) ;
set_window_title() ;
if (! reader.m_errors.empty())
{
CString msg ;
msg.Format(_T("%u errors during import. Check log for details."), reader.m_errors.size()) ;
user_feedback(msg) ;
}
return true ;
}
/** Give feedback for a loaded memory.
*/
void MemoryWindowFrame::feedback_loaded_mem( const memory_pointer mem )
{
const CString file_name = mem->get_location() ;
CString msg ;
msg.FormatMessage( IDS_DONE_LOADING, int_arg(mem->size()), file::name( file_name ).file_name() ) ;
user_feedback( msg ) ;
}
/** Imports a list of Trados memories.
*/
bool MemoryWindowFrame::import_trados(std::vector<CString> import_files)
{
try
{
for(CString filename: import_files)
{
import_trados(filename) ;
}
}
catch( CException &e )
{
logging::log_exception(e) ;
user_feedback( IDS_IMPORT_ABORTED ) ;
e.notify_user( IDS_IMPORT_ABORTED ) ;
return false ;
}
return true ;
}
/** Imports a Trados memory.
*/
bool MemoryWindowFrame::import_trados(const CString &trados_file_name)
{
const int PROGRESS_START = 0 ;
const int PROGRESS_END = 100 ;
trados_data_importer importer( static_cast< CProgressListener* >( this ) ) ;
user_feedback(IDS_RETRIEVING_LANG_CODES) ;
CWaitCursor wait_cursor ;
importer.open_data_source( trados_file_name ) ;
m_statusbar.init_progress_bar(PROGRESS_START, PROGRESS_END) ;
// convert them to internal format
trados_data_importer::language_code_set languages ;
for ( int num_codes = 0 ;
importer.get_language_code( languages ) && num_codes < PROGRESS_END ;
++num_codes)
{
m_statusbar.set_pos( num_codes++ ) ;
}
wait_cursor.Restore() ;
m_statusbar.m_mp_sbar.ProgDestroyWindow() ;
CImportDialog import_dialog ;
import_dialog.set_languages( languages ) ;
if ( import_dialog.DoModal() == IDCANCEL )
{
user_feedback( IDS_IMPORT_ABORTED ) ;
return false ;
}
importer.set_source_language( import_dialog.get_source_plain() ) ;
importer.set_target_language( import_dialog.get_trans_plain() ) ;
memory_pointer mem = m_model->add_memory() ;
mem->set_is_memory(true) ;
MemoryInfo *mem_info = mem->get_memory_info() ;
mem_info->set_creation_tool( L"TradosText" ) ;
mem_info->set_creation_tool_version( L"6.0" ) ;
ATLASSERT ( mem->get_memory_info()->get_creation_tool() == L"TradosText" ) ;
ATLASSERT ( mem->get_memory_info()->get_creation_tool_version() == L"6.0" ) ;
if ( ! importer.load( trados_file_name, mem ) )
{
user_feedback( IDS_MSG_PARSE_FAILED ) ;
return false ;
}
else
{
m_mru.AddToList( trados_file_name ) ;
CString int_arg ;
int_arg.Format( _T("%u"), mem->size() ) ;
CString msg ;
msg.FormatMessage( IDS_DONE_LOADING, int_arg, file::name( trados_file_name ).file_name() ) ;
user_feedback( msg ) ;
mem->set_location( trados_file_name ) ;
mem->set_is_memory(true) ;
mem->set_saved_flag(true) ;
set_window_title() ;
}
return true ;
}
/** Loads a memory.
*/
bool MemoryWindowFrame::load(const CString file_name, const bool check_empty )
{
input_device_ptr input = get_input_device() ;
input->ensure_file_exists(file_name);
// put message in status bar
loading_file_feedback(file_name);
const file::CFileExtension ext = file_name ;
bool success = false ;
if ( ext.equals( _T(".txt") ) )
{
success = import_trados( file_name ) ;
}
else if ( ext.equals( _T(".tmx") ) )
{
success = import_tmx( file_name, input ) ;
}
else
{
success = load_felix_memory(check_empty, file_name);
}
if ( success )
{
set_window_title() ;
m_mru.AddToList( file_name ) ;
m_props->m_history_props.m_memory_location =
static_cast<LPCWSTR>(file_name) ;
return true ;
}
else
{
load_failed_feedback(file_name);
return false ;
}
}
/** Looks up a translation in the memory.
*/
bool MemoryWindowFrame::lookup_trans(const wstring query)
{
if ( query.empty() )
{
user_feedback( IDS_EMPTY_QUERY ) ;
::MessageBeep( MB_ICONINFORMATION ) ;
return false ;
}
// only do searching when edit mode is off
m_view_interface.put_edit_mode( false ) ;
init_trans_matches_for_lookup(query) ;
trans_match_container matches ;
m_model->find_trans_matches( matches, m_trans_matches.m_params ) ;
m_trans_matches.set_matches( matches ) ;
if ( m_trans_matches.empty() == false )
{
m_model->set_reverse_lookup(true) ;
look_up_current_source_in_gloss() ;
}
// give the user feedback
provide_user_trans_feedback() ;
set_display_state ( MATCH_DISPLAY_STATE ) ;
show_view_content() ;
return true ;
}
/** Correct the translation for the current match.
*
* \todo
* Correct any glossary entries with matching source/translation
* - Prompt user?
*/
bool MemoryWindowFrame::correct_trans(const wstring trans)
{
if ( m_model->empty() )
{
user_feedback(IDS_NO_QUERIES) ;
return false ;
}
if (trans.empty())
{
user_feedback(IDS_EMPTY_QUERY) ;
return false ;
}
try
{
if (get_display_state() == TRANS_REVIEW_STATE)
{
memory_pointer mem = m_model->get_memory_by_id(m_review_match->get_memory_id()) ;
record_pointer rec = m_review_match->get_record() ;
mem->erase( rec ) ;
rec->set_trans( trans ) ;
mem->add_record( rec ) ;
show_view_content() ;
user_feedback( IDS_CORRECTED_TRANS ) ;
return true ;
}
// must not be empty!
if (m_trans_matches.get_query_rich().empty())
{
MessageBeep(MB_ICONEXCLAMATION) ;
user_feedback(IDS_NO_QUERIES) ;
return false ;
}
if ( get_display_state() == NEW_RECORD_DISPLAY_STATE )
{
ATLASSERT(m_view_state == &m_view_state_new) ;
memory_pointer mem = m_model->get_first_memory() ;
mem->erase( m_new_record ) ;
m_new_record->set_trans( trans ) ;
mem->add_record( m_new_record ) ;
show_view_content() ;
user_feedback( IDS_CORRECTED_TRANS ) ;
return true ;
}
if (m_trans_matches.empty())
{
MessageBeep(MB_ICONEXCLAMATION) ;
user_feedback(IDS_NO_QUERIES) ;
return false ;
}
// the match
search_match_ptr current = m_trans_matches.current() ;
memory_pointer mem = m_model->get_memory_by_id(current->get_memory_id()) ;
// the record
record_pointer record = current->get_record() ;
mem->erase( record ) ;
record->set_trans( trans ) ;
record->set_refcount( 0 ) ;
record->increment_refcount() ;
mem->add_record( record ) ;
current->set_record(record);
current->set_values_to_record() ;
m_trans_matches.set_query(trans) ;
// show it!
set_display_state( MATCH_DISPLAY_STATE ) ;
user_feedback( IDS_CORRECTED_TRANS ) ;
show_view_content() ;
return true ;
}
catch( CException &e )
{
logging::log_error("Failed to correct translation") ;
logging::log_exception(e) ;
user_feedback(IDS_TRANS_SET_FAILED) ;
e.notify_user( IDS_TRANS_SET_FAILED ) ; // TEXT("Failed to set translation.") ) ;
return false ;
}
}
/** Translation concordance.
*/
bool MemoryWindowFrame::get_translation_concordances(const wstring query_string)
{
// an empty string would retrieve everything - probably not what the user wants!
if ( query_string.empty() )
{
user_feedback(IDS_EMPTY_QUERY) ;
::MessageBeep( MB_ICONINFORMATION ) ;
return false ;
}
// only do searching when edit mode is off
m_view_interface.put_edit_mode( false ) ;
// this will hold our matches
m_search_matches.clear() ;
m_search_matches.set_trans(query_string) ;
m_search_matches.m_params.m_ignore_case = true ;
perform_concordance_search(m_search_matches.m_params) ;
// remember where we were
// in the future, make an array of states to allow Explorer-style page navigation
set_display_state ( CONCORDANCE_DISPLAY_STATE ) ;
show_view_content() ;
m_view_interface.set_scroll_pos(0) ;
// give the user feedback
translation_concordance_feedback();
return true ;
}
/** Alt + C.
* Get concordance in the source fields.
*/
LRESULT MemoryWindowFrame::on_source_concordance(WindowsMessage &)
{
SENSE("on_source_concordance") ;
get_concordances(m_view_interface.get_selection_text()) ;
return 0 ;
}
/** Ctrl + Alt + C.
* Get concordance in the translation fields.
*/
LRESULT MemoryWindowFrame::on_trans_concordance(WindowsMessage &)
{
SENSE("on_trans_concordance") ;
get_translation_concordances(m_view_interface.get_selection_text()) ;
return 0 ;
}
/** Toggle markup (matches) between on and off.
*/
LRESULT MemoryWindowFrame::on_user_toggle_markup(WindowsMessage &)
{
SENSE("on_user_toggle_markup") ;
const BOOL show_markup = m_props->m_gen_props.m_data.m_show_markup ;
if (show_markup)
{
put_show_marking( VARIANT_FALSE ) ;
}
else
{
put_show_marking( VARIANT_TRUE ) ;
}
m_props->m_gen_props.m_data.m_show_markup = ! show_markup ;
m_props->write_to_registry() ;
return 0L ;
}
/** File -> Save.
* The user wants to save the top memory.
*/
LRESULT MemoryWindowFrame::on_user_save(WindowsMessage &message)
{
SENSE("on_user_save") ;
on_file_save(message) ;
m_glossary_windows.on_file_save() ;
return 0L ;
}
/** Respond to dropped files.
*/
LRESULT MemoryWindowFrame::on_drop(WindowsMessage &message)
{
HDROP dropped = (HDROP)message.wParam ;
SENSE("on_drop") ;
if ( ! dropped_in_client( dropped ) )
{
SetMsgHandled( FALSE ) ;
return 0L ;
}
const CDrop drop( dropped ) ;
const UINT num_files = drop.NumDragFiles() ;
if ( ! num_files )
{
#ifndef UNIT_TEST
SetMsgHandled( FALSE ) ;
#endif
return 0L ;
}
for ( UINT current_file=0 ; current_file < num_files ; ++current_file )
{
const CString filename = drop.DragQueryFile( current_file ) ;
const file::CFileExtension ext = filename ;
if (ext.equals(".fprefs"))
{
this->load_old_preferences(filename) ;
return 0L ;
}
else if(ext.equals(".fprefx"))
{
const WORD old_language = m_appstate.m_preferred_gui_lang ;
load_new_preferences(filename, old_language);
return 0L ;
}
load(filename) ;
}
return 0L ;
}
/** Tools -> Manage Memories.
* Shows memory manager dialog.
*/
LRESULT MemoryWindowFrame::on_tools_memory_manager(WindowsMessage &)
{
SENSE("on_tools_memory_manager") ;
if (m_props->m_gen_props.m_data.m_old_mem_mgr)
{
m_old_manager_window.set_memories(this->m_model->get_memories()) ;
m_old_manager_window.DoModal() ;
return 0L ;
}
m_manager_window.set_mem_model( this->get_model() ) ;
m_manager_window.set_gloss_model(this->get_glossary_window()->get_model()) ;
if (! m_manager_window.IsWindow())
{
m_manager_window.Create(*this) ;
}
m_manager_window.ShowWindow(SW_SHOW) ;
m_manager_window.SetWindowPos(HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE) ;
return 0L ;
}
LRESULT MemoryWindowFrame::on_toggle_views(WindowsMessage &)
{
logging::log_debug("Toggling view between match and concordance") ;
if (this->get_display_state() == MATCH_DISPLAY_STATE)
{
this->set_display_state(CONCORDANCE_DISPLAY_STATE) ;
}
else
{
this->set_display_state(MATCH_DISPLAY_STATE) ;
// the current match...
if ( ! m_trans_matches.empty() )
{
recalculate_match(m_trans_matches.current(), m_trans_matches.m_params);
}
else // we have 0 matches, just a query
{
trans_match_container matches ;
if (m_model->is_reverse_lookup())
{
m_model->find_trans_matches( matches, m_trans_matches.m_params ) ;
}
else
{
get_matches(matches, m_trans_matches.m_params);
}
m_trans_matches.set_matches(matches) ;
}
}
this->show_view_content() ;
return 0L ;
}
/** Switches focus to the glossary window.
*/
LRESULT MemoryWindowFrame::on_view_switch(WindowsMessage &)
{
SENSE("on_view_switch") ;
if (m_glossary_windows.empty())
{
return 0L ;
}
m_glossary_windows.first()->SetFocus() ;
return 0L ;
}
/** Loop through the glossary views (which has focus).
*/
void MemoryWindowFrame::gloss_view_switch(HWND child)
{
if (! m_glossary_windows.gloss_view_switch(child))
{
SetFocus() ;
}
}
/** View -> Compact View.
* Hide the min view.
*/
LRESULT MemoryWindowFrame::on_user_view_min_end(WindowsMessage &)
{
SENSE("on_user_view_min_end") ;
ShowWindow( SW_SHOW ) ;
m_glossary_windows.put_visibility(SW_SHOW);
show_view_content() ;
return 0L ;
}
/** View -> Compact View.
* Show the min view.
*/
LRESULT MemoryWindowFrame::on_view_min_begin( WindowsMessage &)
{
const int DEFAULT_SIZE = 100 ;
SENSE("on_view_min_begin") ;
m_glossary_windows.put_visibility(SW_HIDE);
ShowWindow( SW_HIDE ) ;
if( ! m_min_view.IsWindow() )
{
m_min_view.set_parent(*this) ;
m_min_view.Create(*this) ;
}
ATLASSERT( m_min_view.IsWindow() ) ;
CRect rc(DEFAULT_SIZE, DEFAULT_SIZE, DEFAULT_SIZE, DEFAULT_SIZE) ;
m_min_view.ShowWindow( SW_RESTORE ) ;
m_min_view.SetWindowPos( HWND_TOPMOST, &rc, SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOSIZE ) ;
ATLASSERT( m_min_view.IsWindowVisible() ) ;
return 0L ;
}
/** Sets whether the window is visible.
* Also applied to all glossary windows.
*/
void MemoryWindowFrame::put_visible(int visibility)
{
if ( m_min_view.IsWindow() && m_min_view.IsWindowVisible() )
{
m_min_view.ShowWindow( visibility ) ;
}
else
{
ShowWindow( visibility ) ;
}
m_glossary_windows.put_visibility(visibility) ;
}
/** Load the appropriate resource file according to the
* language code.
*/
void MemoryWindowFrame::SetUILanguage(WORD lang_id)
{
logging::log_debug((format("Setting language id to %1%") % lang_id).str()) ;
set_module_library(lang_id);
if (m_appstate.m_preferred_gui_lang != lang_id)
{
m_appstate.m_preferred_gui_lang = lang_id ;
m_props->m_gen_props.m_data.m_preferred_gui_lang = lang_id ;
m_appstate.write_to_registry() ;
m_props->m_gen_props.write_to_registry() ;
}
if ( m_min_view.IsWindow() )
{
m_min_view.DestroyWindow() ;
}
set_ui_to_current_language() ;
}
/** As a WORD (LANG_ENGLISH/LANG_JAPANESE).
*/
WORD MemoryWindowFrame::get_current_gui_language()
{
return m_appstate.m_preferred_gui_lang ;
}
/** Called after the preference dialog is exited with "OK".
*/
void MemoryWindowFrame::reflect_preferences()
{
m_glossary_windows.show_view_content() ;
set_bg_color( static_cast< COLORREF >( m_props->m_view_props.m_data.m_back_color ) );
m_trans_matches.m_query_color = m_props->m_view_props.m_data.m_query_color ;
m_trans_matches.m_source_color = m_props->m_view_props.m_data.m_source_color ;
m_trans_matches.m_trans_color = m_props->m_view_props.m_data.m_trans_color ;
}
void MemoryWindowFrame::reflect_loaded_preferences( const WORD old_language )
{
set_up_ui_state() ;
// set the title
set_window_title() ;
set_up_window_size() ;
init_item_colors();
set_bg_color( static_cast< COLORREF >( m_props->m_view_props.m_data.m_back_color ) ) ;
load_history() ;
load_mousewheel_setting() ;
if (old_language != m_appstate.m_preferred_gui_lang)
{
switch( m_appstate.m_preferred_gui_lang )
{
case LANG_JAPANESE :
SetUILanguage( LANG_JAPANESE ) ;
break ;
default:
SetUILanguage( LANG_ENGLISH ) ;
}
}
if (! m_glossary_windows.empty())
{
gloss_window_pointer gloss = m_glossary_windows.first();
CWindowSettings ws;
if( ws.Load( resource_string(IDS_REG_KEY), _T("MainGlossary") ) )
{
ws.ApplyTo( *gloss ) ;
}
else
{
gloss->set_up_initial_size() ;
}
gloss->load_history() ;
gloss->load_mousewheel_setting() ;
gloss->reflect_sb_vis() ;
gloss->reflect_tb_vis();
gloss->apply_reg_bg_color() ;
gloss->apply_mousewheel_setting() ;
}
// ===============
logging::log_debug("Loaded preferences") ;
user_feedback( IDS_PREFS_LOADED ) ;
}
/** This is called with a PostMessage from OnCreate.
*/
LRESULT MemoryWindowFrame::on_startup_checks(WindowsMessage &)
{
SENSE("on_startup_checks") ;
logging::log_debug("Doing post-launch checks") ;
#ifdef UNIT_TEST
return 0L ;
#else
check_mousewheel_count();
if ( ! IsWindowVisible())
{
return 0L ;
}
// only do this if it is not the first launch
if (! m_props->m_gen_props.is_first_launch())
{
try
{
logging::log_debug("Checking for updates") ;
CDispatchWrapper utilities(L"Felix.Utilities") ;
CComBSTR langcode ;
langcode.LoadStringW(IDS_LANG_CODE) ;
CComVariant arg1(langcode) ;
utilities.method(L"CheckUpdates", arg1) ;
}
catch (_com_error& e)
{
logging::log_error("Failed to auto check for updates") ;
logging::log_exception(e) ;
}
return 0L ;
}
// We should have returned if it's not the first launch.
ATLASSERT(m_props->m_gen_props.is_first_launch()) ;
SetFocus() ;
set_window_title() ;
SetFocus() ;
return 0L ;
#endif
}
/** Adds a memory.
*/
void MemoryWindowFrame::add_memory(memory_pointer mem)
{
m_model->insert_memory( mem ) ;
m_view_interface.set_text( wstring() ) ;
check_mousewheel() ;
m_view_interface.set_scroll_pos(0) ;
set_window_title() ;
}
/** If we don't have a size saved, use the default.
*/
void MemoryWindowFrame::set_up_default_initial_size()
{
const int PADDING = 5 ;
// get dimensions of desktop
const CWindowRect desktop_rect(GetDesktopWindow()) ;
// dimensions of our top glossary window
const CWindowRect dialog_rect(get_glossary_window()->m_hWnd) ;
// get dimensions of the mainframe
CWindowRect frame_window_rect(*this) ;
// calculate dialog size
const int width = ( desktop_rect.Width() ) - (dialog_rect.Width() + PADDING) ;
const int height = dialog_rect.Height() ;
frame_window_rect.right = PADDING + desktop_rect.left + width ;
frame_window_rect.left = PADDING ;
frame_window_rect.top = desktop_rect.top ;
frame_window_rect.bottom = frame_window_rect.top + height ;
// justify window left, place it under parent
ATLVERIFY(MoveWindow( &frame_window_rect, TRUE )) ;
}
/** Add our tool bars and menu.
*/
void MemoryWindowFrame::set_up_command_bars()
{
// Set the 24-bit color images in the toolbar's image list
// SEP_ID is for separators.
std::vector< int > commands ;
add_common_tb_commands(commands) ;
commands +=
ID_TOOLS_PREFERENCES, ID_TOOLS_MEMORY_MGR, SEP_ID,
ID_HELP, ID_APP_ABOUT;
std::vector< int > StdBitmaps ;
add_common_std_bitmaps(StdBitmaps) ;
StdBitmaps +=
IDB_PROPERTIES, IDB_MEM_MGR,
IDB_HELP, IDB_INFORMATION ;
#ifdef UNIT_TEST
return ;
#else
CWindow toolbarWnd = m_stdToolbar.Create24BitToolBarCtrl(*this, commands, FALSE );
m_stdToolbar.SubclassWindow( toolbarWnd, MAKEINTRESOURCE(IDR_MAINFRAME));
m_stdToolbar.SetBitmapSize(BM_SIZE, BM_SIZE) ;
CImageList images ;
create_tb_imagelist(images, StdBitmaps) ;
m_stdToolbar.SetImageList(images) ;
create_command_bar();
// remove old menu
SetMenu(NULL);
// Add menu bitmaps
AddMenuBitmap(IDB_NEW_DOCUMENT, ID_FILE_NEW) ;
AddMenuBitmap(IDB_NETWORK, ID_FILE_CONNECT) ;
AddMenuBitmap(IDB_OPEN, ID_FILE_OPEN) ;
AddMenuBitmap(IDB_SAVE, ID_FILE_SAVE) ;
AddMenuBitmap(IDB_SAVEMANY, ID_FILE_SAVE_ALL) ;
AddMenuBitmap(IDB_MEMORY_CLOSE, ID_MEMORY_CLOSE) ;
AddMenuBitmap(IDB_CUT, ID_EDIT_CUT) ;
AddMenuBitmap(IDB_COPY, ID_EDIT_COPY) ;
AddMenuBitmap(IDB_PASTE, ID_EDIT_PASTE) ;
AddMenuBitmap(IDB_SEARCH, ID_EDIT_FIND) ;
AddMenuBitmap(IDB_SAVE_PREFS, ID_TOOLS_SAVEPREFERENCES) ;
AddMenuBitmap(IDB_OPEN_PREFS, ID_TOOLS_LOADPREFERENCES) ;
AddMenuBitmap(IDB_INFORMATION, ID_APP_ABOUT) ;
AddMenuBitmap(IDB_HELP, ID_HELP) ;
AddMenuBitmap(IDB_MEM_MGR, ID_TOOLS_MEMORY_MGR) ;
AddMenuBitmap(IDB_PROPERTIES, ID_TOOLS_PREFERENCES) ;
AddMenuBitmap(IDB_FONT, ID_FORMAT_FONT) ;
AddMenuBitmap(IDB_FILL_COLOR, ID_FORMAT_BGCOLOR) ;
AddMenuBitmap(IDB_DELETE, ID_EDIT_DELETE) ;
// Create the rebar, and add the menu and toolbar to it.
ATLVERIFY(CreateSimpleReBar(ATL_SIMPLE_REBAR_NOBORDER_STYLE)) ;
AddSimpleReBarBand(m_CmdBar);
AddSimpleReBarBand(m_stdToolbar, NULL, m_appstate.m_rebar_has_linebreak);
SizeSimpleReBarBands() ;
ATLVERIFY(UIAddToolBar(m_stdToolbar)) ;
#endif
}
void MemoryWindowFrame::create_command_bar()
{
// create command bar window
m_CmdBar.Create(m_hWnd, rcDefault, NULL, ATL_SIMPLE_CMDBAR_PANE_STYLE);
m_CmdBar.RemoveAllImages() ;
m_CmdBar.SetImageMaskColor(MAGENTA) ;
m_CmdBar.SetImageSize(BM_SIZE, BM_SIZE) ;
// attach menu
ATLVERIFY(m_CmdBar.AttachMenu(GetMenu())) ;
}
//! Add a bitmap menu item.
void MemoryWindowFrame::AddMenuBitmap( const int BitmapId, const int CmdId )
{
CBitmap bmp ;
bmp.LoadBitmap( BitmapId ) ;
m_CmdBar.AddBitmap( bmp, CmdId ) ;
}
/** Load the MRU.
*/
void MemoryWindowFrame::set_up_recent_docs_list()
{
const int MAX_NUM_ENTRIES = 15 ;
const int MAX_ITEM_LEN = 400 ; // pixels
// init recent documents list
m_mru.SetMenuHandle(::GetSubMenu(GetMenu(), 0 ) ) ;
m_mru.ReadFromRegistry( resource_string( IDS_REG_KEY ) ) ;
m_mru.SetMaxItemLength(MAX_ITEM_LEN) ;
m_mru.SetMaxEntries(MAX_NUM_ENTRIES) ;
}
/** Create the status bar.
*/
void MemoryWindowFrame::init_status_bar()
{
#ifdef UNIT_TEST
return ;
#else
// create the status bar
if(! CreateSimpleStatusBar())
{
logging::log_error("Failed to create status bar in main window.") ;
}
ATLASSERT( ::IsWindow(m_hWndStatusBar) ) ;
ATLVERIFY(m_statusbar.m_mp_sbar.SubclassWindow( m_hWndStatusBar )) ;
ATLASSERT( m_statusbar.m_mp_sbar.IsWindow() ) ;
int arrParts[] =
{
ID_DEFAULT_PANE,
ID_PANE_1,
ID_PANE_2
} ;
ATLVERIFY(m_statusbar.m_mp_sbar.SetPanes(arrParts, sizeof(arrParts) / sizeof(arrParts[0]), false)) ;
CString version_info ;
version_info.Format(_T("Felix v. %s"), string2wstring(VERSION).c_str()) ;
user_feedback(version_info, 1) ;
#endif
}
/** Set up the various menu checkmarks and such.
*/
void MemoryWindowFrame::set_up_ui_state()
{
ATLASSERT( ::IsWindow( m_hWndToolBar ) ) ;
CReBarCtrl rebar = m_hWndToolBar ;
const int nBandIndex = rebar.IdToIndex(ATL_IDW_BAND_FIRST + 1) ; // toolbar is 2nd added band
// toolbar
if( m_appstate.m_is_toolbar_visible )
{
ATLVERIFY(UISetCheck(ID_VIEW_TOOLBAR, TRUE)) ;
ATLVERIFY(rebar.ShowBand(nBandIndex, TRUE)) ;
}
else
{
ATLVERIFY(UISetCheck(ID_VIEW_TOOLBAR, FALSE)) ;
ATLVERIFY(rebar.ShowBand(nBandIndex, FALSE)) ;
}
// status bar
if( m_appstate.m_is_statusbar_visible )
{
::ShowWindow(m_hWndStatusBar, SW_SHOW) ;
ATLVERIFY(UISetCheck(ID_VIEW_STATUS_BAR, TRUE)) ;
}
else
{
::ShowWindow(m_hWndStatusBar, SW_HIDE) ;
ATLVERIFY(UISetCheck(ID_VIEW_STATUS_BAR, FALSE)) ;
}
}
/** Set up the mainframe window size.
If we have already run the app, we will have persisted the app state in the registry.
If not, we will set the window size to the default.
CReBarSettings is used to save/load the command bar settings in the registry.
*/
void MemoryWindowFrame::set_up_window_size()
{
#ifdef UNIT_TEST
return ;
#else
try
{
CWindowSettings ws;
if( ws.Load( resource_string(IDS_REG_KEY), _T("MainFrame") ) )
{
ws.ApplyTo(*this) ;
}
else
{
set_up_default_initial_size() ;
}
CReBarSettings rs;
if(rs.Load( resource_string(IDS_REG_KEY), _T("ReBar") ) )
{
CReBarCtrl rbc = m_hWndToolBar ;
rs.ApplyTo(rbc);
}
}
catch (CException& e)
{
logging::log_error("Failed to initialize Window size") ;
logging::log_exception(e) ;
}
#endif
}
/** Add the record to the top memory, and give feedback.
*/
void MemoryWindowFrame::add_record_to_memory(record_pointer record)
{
memory_pointer mem = m_model->get_first_memory() ;
if ( ! mem->add_record( record ) )
{
if ( mem->is_locked() )
{
user_feedback( IDS_MEMORY_LOCKED ) ;
}
else
{
// Entry already existed. Updated with any new information.
user_feedback( IDS_ENTRY_EXISTED ) ;
}
return ;
}
CNumberFmt fm ;
CString msg ;
msg.FormatMessage( IDS_CURRENT_SIZE, resource_string( IDS_MEMORY ), fm.Format( mem->size() ) ) ;
const CString content = resource_string( IDS_ADDED_TRANSLATION ) + _T(" ") + msg ;
user_feedback( content ) ;
}
/** Perform the lookup again. This is needed after we've edited the record.
*/
void MemoryWindowFrame::redo_lookup( search_match_ptr match, bool do_gloss )
{
match_maker matcher( 0.0 ) ; // show score no matter what
g_cmp_maker.m_ignore_case = m_trans_matches.m_params.m_ignore_case ;
g_cmp_maker.m_ignore_hira_kata = m_trans_matches.m_params.m_ignore_hira_kata ;
g_cmp_maker.m_ignore_width = m_trans_matches.m_params.m_ignore_width ;
const wstring search_segment = m_trans_matches.get_query_rich();
const Segment query(&g_cmp_maker, search_segment) ;
record_pointer rec = match->get_record() ;
int match_algo = m_trans_matches.m_params.m_match_algo ;
if ( match_algo == IDC_ALGO_AUTO )
{
match_algo = detect_match_algo(query.cmp()) ;
}
if ( m_model->is_reverse_lookup() )
{
// look up based on translation
const Segment source(&g_cmp_maker, rec->get_trans_rich()) ;
matcher.get_score_trans(query,
source,
match_algo,
match) ;
}
else
{
// look up normally (using source)
const Segment source(&g_cmp_maker, rec->get_source_rich()) ;
matcher.get_score(query,
source,
match_algo,
match) ;
}
if ( do_gloss )
{
m_glossary_windows.look_up(search_segment) ;
}
}
/** Tell the user how many matches we found.
*/
void MemoryWindowFrame::provide_user_search_feedback()
{
match_count_feedback(m_search_matches.size()) ;
}
/** Provides feedback on found matches.
*/
void MemoryWindowFrame::provide_user_trans_feedback()
{
match_count_feedback(m_trans_matches.size()) ;
}
/** Template: Found x match(es).
*/
void MemoryWindowFrame::match_count_feedback(size_t num)
{
if ( num == 1 )
{
user_feedback(IDS_FOUND_1_MATCH) ;
}
else
{
user_feedback(system_message(IDS_FOUND_X_MATCHES, int_arg(num))) ;
}
}
/** Perform a search on the memories with the parameters from the find
* dialog.
*/
void MemoryWindowFrame::perform_user_search()
{
m_search_matches.clear() ;
m_search_matches.m_params = m_find.get_search_params() ;
perform_concordance_search(m_search_matches.m_params) ;
}
/** This is kind of a useless method, isn't it?
*/
void MemoryWindowFrame::show_user_search_results()
{
set_display_state ( CONCORDANCE_DISPLAY_STATE );
show_view_content() ;
m_view_interface.set_scroll_pos(0) ;
}
/** Refresh the glossary window text after switching GUI languages.
*/
void MemoryWindowFrame::set_lang_of_gloss_windows()
{
m_glossary_windows.set_ui_language() ;
}
/** Reload the menu bar after switching GUI languages.
*/
void MemoryWindowFrame::refresh_command_bar()
{
HINSTANCE h = _Module.GetResourceInstance() ;
HMENU menu = ::LoadMenu( h, MAKEINTRESOURCE( IDR_MAINFRAME ) ) ;
ATLASSERT( menu != NULL ) ;
m_CmdBar.AttachMenu( menu );
refresh_mru_doc_list(menu);
}
/** We need to reload the MRU list after switching GUI languages.
*/
void MemoryWindowFrame::refresh_mru_doc_list(HMENU menu)
{
// write our recent docs
m_mru.WriteToRegistry( resource_string( IDS_REG_KEY ) );
// reset the menu handle for the recent docs list...
m_mru.SetMenuHandle(::GetSubMenu(menu, 0));
// read our doc history back for the new menu
m_mru.ReadFromRegistry( resource_string( IDS_REG_KEY ) );
}
/** Allow the glossary windows to tell us not to shut down.
*/
bool MemoryWindowFrame::gloss_win_shutdown_check()
{
if (m_glossary_windows.pre_shutdown_save_check())
{
return true ;
}
SetMsgHandled( TRUE ) ;
return false ;
}
/** Saves the rebar settings to the register, so we can remember them
* at next startup. (We're just nice that way)
*/
void MemoryWindowFrame::save_rebar_settings()
{
CReBarCtrl rbc = m_hWndToolBar;
ATLASSERT(rbc.IsWindow()) ;
CReBarSettings rs;
rs.GetFrom(rbc);
rs.Save( resource_string(IDS_REG_KEY), _T("ReBar") );
}
/** Sets whether to show markup for matches.
*/
void MemoryWindowFrame::put_show_marking( const VARIANT_BOOL setting )
{
if ( setting == VARIANT_FALSE )
{
m_trans_matches.m_params.m_show_marking = false ;
}
else
{
m_trans_matches.m_params.m_show_marking = true ;
}
m_glossary_windows.put_show_marking(setting) ;
show_view_content() ;
}
/** Returns whether markup is being shown.
*/
VARIANT_BOOL MemoryWindowFrame::get_show_marking()
{
if ( m_trans_matches.m_params.m_show_marking == false )
{
return VARIANT_FALSE ;
}
else
{
return VARIANT_TRUE ;
}
}
/** Set the location of the top memory.
*/
bool MemoryWindowFrame::set_location( const CString &location )
{
memory_pointer mem = m_model->get_first_memory() ;
try
{
mem->set_location( location ) ;
return true ;
}
catch( ... )
{
logging::log_error("Error while setting memory location. Removing memory.") ;
m_model->remove_memory_by_id( mem->get_id() ) ;
}
return false ;
}
/** Get the type string for the memory window (e.g. "Memory").
*/
CString MemoryWindowFrame::get_window_type_string()
{
return resource_string(IDS_MEMORY) ;
}
bool MemoryWindowFrame::is_glossary_window()
{
return false;
}
//! This is our poor-man's multithreading.
void MemoryWindowFrame::init_background_processor()
{
m_background_processor.set_accelerator(m_hAccel) ;
m_background_processor.set_hwnd(*this) ;
}
//! Load color preferences from registry.
void MemoryWindowFrame::init_item_colors()
{
app_props::properties_view::props_data *prop_data = &m_props->m_view_props.m_data ;
m_trans_matches.m_query_color = (COLORREF)prop_data->m_query_color ;
m_trans_matches.m_source_color = (COLORREF)prop_data->m_source_color ;
m_trans_matches.m_trans_color = (COLORREF)prop_data->m_trans_color ;
}
//! See if we want to save our memory/glossary loaded history.
BOOL MemoryWindowFrame::should_save_memory_history()
{
return m_props->m_gen_props.load_prev_mem_on_startup();
}
//! Respond to italic command.
LRESULT MemoryWindowFrame::on_italic(WindowsMessage &)
{
SENSE("on_italic") ;
return CCommonWindowFunctionality::on_italic( ) ;
}
//! Respond to an underline command.
LRESULT MemoryWindowFrame::on_underline(WindowsMessage &)
{
SENSE("on_underline") ;
return CCommonWindowFunctionality::on_underline( ) ;
}
//! Respond to bold command.
LRESULT MemoryWindowFrame::on_bold(WindowsMessage &)
{
SENSE("on_bold") ;
return CCommonWindowFunctionality::on_bold( ) ;
}
//! Save all open memory files.
LRESULT MemoryWindowFrame::on_file_save_all(WindowsMessage &)
{
SENSE("on_file_save_all") ;
return CCommonWindowFunctionality::on_file_save_all( ) ;
}
//! Replace the record with the one beind edited.
LRESULT MemoryWindowFrame::on_user_replace_edit_record(WindowsMessage &)
{
SENSE("on_user_replace_edit_record") ;
return 0L ;
}
//! Make sure that we haven't exceeded the demo constraints.
LRESULT MemoryWindowFrame::on_demo_check_excess_memories(WindowsMessage &)
{
SENSE("on_demo_check_excess_memories") ;
return CCommonWindowFunctionality::on_demo_check_excess_memories( ) ;
}
//! User wants to search in edit mode.
LRESULT MemoryWindowFrame::on_user_edit_search(WindowsMessage &message)
{
SENSE("on_user_edit_search") ;
return CCommonWindowFunctionality::on_user_edit_search( message.lParam ) ;
}
/*
* Get the appropriate record as basis for registering glossary entries.
* If the index is out of range, then just return an empty record.
* The user should be able to register glossary entries without a template record.
*/
mem_engine::record_pointer MemoryWindowFrame::get_reg_gloss_record( const size_t num )
{
return m_view_state->get_specified_record(num) ;
}
//! Open a file from the MRU list
LRESULT MemoryWindowFrame::on_mru_file_open(WindowsMessage &message)
{
SENSE("on_mru_file_open") ;
const int index = static_cast<int>(LOWORD( message.wParam )) ;
CString fname ;
m_mru.GetFromList(index, fname) ;
try
{
if (! this->load(fname))
{
m_mru.RemoveFromList( index ) ;
}
}
catch (...)
{
logging::log_error("Error removing item from MRU list") ;
#ifndef UNIT_TEST
m_mru.RemoveFromList( index ) ;
#endif
throw ;
}
return 0L;
}
//! We got rid of the WTL switch statement style to add flexibility
BOOL MemoryWindowFrame::ProcessWindowMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& lResult, DWORD /*dwMsgMapID*/ /*= 0*/ )
{
try
{
BOOL bHandled = FALSE ;
COMMAND_ID_HANDLER_EX(ID_FILE_CONNECT, on_file_connect)
NOTIFY_CODE_HANDLER(TTN_GETDISPINFOW, OnToolTipTextW)
MESSAGE_HANDLER_EX(WM_MOUSEWHEEL /* 0x020A */, OnMouseWheel)
const messageMapType *theMessageMap = this->get_message_map( uMsg ) ;
const UINT key = this->get_message_key( uMsg, wParam ) ;
messageMapType::const_iterator pos = theMessageMap->find( key ) ;
if ( pos != theMessageMap->end() )
{
SENSE("Found message key") ;
WindowsMessage message( hWnd, uMsg, wParam, lParam ) ;
lResult = (pos->second)( message ) ;
if ( message.isHandled() )
{
return TRUE ;
}
}
// chain to members
if( m_view_interface.ProcessWindowMessage(hWnd, uMsg, wParam, lParam, lResult) )
{
return TRUE;
}
CHAIN_MSG_MAP(CUpdateUI<MemoryWindowFrame>) ;
#ifndef UNIT_TEST
CHAIN_MSG_MAP(frame_class) ;
#endif
}
catch ( CSWException &sw_e )
{
string err_msg = "Felix Window - Structured Windows Exception" ;
report_structured_windows_exception(err_msg, sw_e) ;
return FALSE ;
}
catch ( _com_error &e )
{
logging::log_error("COM Exception") ;
logging::log_exception(e) ;
CString fail_msg( R2T( IDS_MSG_ACTION_FAILED ) ) ;
fail_msg += _T(": COM ERROR") ;
sb_text(m_hWndStatusBar, fail_msg ) ;
return handle_exception( e, fail_msg ) ;
}
catch ( CComException &e )
{
logging::log_error("Application COM Exception") ;
logging::log_exception(e) ;
CString fail_msg( R2T( IDS_MSG_ACTION_FAILED ) ) ;
fail_msg += _T(": COM EXCEPTION") ;
sb_text(m_hWndStatusBar, fail_msg ) ;
return handle_exception( e, fail_msg ) ;
}
catch ( CWinException &e )
{
logging::log_error("Windows Exception") ;
logging::log_exception(e) ;
CString fail_msg( R2T( IDS_MSG_ACTION_FAILED ) ) ;
fail_msg += _T(": WINDOWS ERROR") ;
sb_text(m_hWndStatusBar, fail_msg ) ;
return handle_exception( e, fail_msg ) ;
}
catch ( CException &e )
{
logging::log_error("Application Exception") ;
logging::log_exception(e) ;
CString fail_msg( R2T( IDS_MSG_ACTION_FAILED ) ) ;
fail_msg += _T(": EXCEPTION") ;
sb_text(m_hWndStatusBar, fail_msg ) ;
return handle_exception( e, fail_msg ) ;
}
catch ( std::exception &e )
{
logging::log_error("C++ Library Exception") ;
logging::log_error(e.what()) ;
CString fail_msg( R2T( IDS_MSG_ACTION_FAILED ) ) ;
fail_msg += _T(": RUNTIME ERROR") ;
sb_text(m_hWndStatusBar, fail_msg ) ;
return handle_exception( e, fail_msg ) ;
}
return FALSE;
}
//! Get the correct key to use with the message map
UINT MemoryWindowFrame::get_message_key( UINT message, WPARAM wParam )
{
if ( message == UWM_USER_MESSAGE )
{
return wParam ;
}
if ( message == WM_COMMAND )
{
return LOWORD( wParam ) ;
}
return message ;
}
//! Get the correct message map depending on the message type
std::map< UINT, boost::function< LRESULT( WindowsMessage& ) > > * MemoryWindowFrame::get_message_map( UINT message )
{
if ( message == UWM_USER_MESSAGE )
{
return &this->m_user_message_map ;
}
if ( message == WM_COMMAND )
{
return &this->m_command_message_map ;
}
return &this->m_message_map ;
}
/** Recalculates the match after switching from another view state.
* This is needed because we might have edited the record.
*/
void MemoryWindowFrame::recalculate_match( search_match_ptr match, search_query_params ¶ms )
{
// initialize the match
match->match_pairing().clear() ;
match->set_values_to_record() ;
m_trans_matches.m_params = params ;
this->redo_lookup(match, false) ;
}
//! File -> Connect
LRESULT MemoryWindowFrame::on_file_connect( UINT, int, HWND )
{
CConnectionDlg dlg(m_props) ;
if (IDCANCEL == dlg.DoModal(*this))
{
return 0L ;
}
return add_remote_memory(m_model, dlg.m_memory) ;
}
//! Set the background color unless it's white (the default)
void MemoryWindowFrame::set_bg_color_if_needed()
{
#ifdef UNIT_TEST
return ;
#else
const CColorRef color((COLORREF)m_props->m_view_props.m_data.m_back_color) ;
if (! color.is_white())
{
m_view_interface.set_bg_color(color.as_wstring()) ;
}
#endif
}
/** handle tooltip text ourselves to enable dynamic switching.
* (The default WTL way caches tooltip text)
*/
LRESULT MemoryWindowFrame::OnToolTipTextW( int idCtrl, LPNMHDR pnmh, BOOL& /*bHandled*/ )
{
if( m_toolmap.empty() )
{
init_tooltip_map(m_toolmap);
add_frame_specific_tooltips();
}
handle_tooltip(pnmh, idCtrl, m_toolmap);
return 0L;
}
void MemoryWindowFrame::add_frame_specific_tooltips()
{
m_toolmap[ID_EDIT_FIND] = IDS_SEARCH_TOOLBAR;
m_toolmap[ID_MEMORY_CLOSE] = IDS_MEMORY_CLOSE;
m_toolmap[ID_FILE_SAVE] = IDS_SAVE_MEMORY;
m_toolmap[ID_FILE_SAVE_ALL] = IDS_SAVE_ALL_MEMORIES;
}
//! Tell the user that we failed to load the memory
void MemoryWindowFrame::load_failed_feedback( const CString & file_name )
{
// we failed to load the memory
user_feedback( get_load_failure_msg(file_name) ) ; //
}
//! Tell the user that we're loading a file
void MemoryWindowFrame::loading_file_feedback( const CString & file_name )
{
const file::CPath path( file_name ) ;
user_feedback(system_message( IDS_MSG_LOADING, path.FindFileName()));
}
/** Loads a Felix memory.
*/
bool MemoryWindowFrame::load_felix_memory( bool check_empty, const CString & file_name )
{
memory_pointer mem ;
bool make_dirty = false ;
// merge or add?
MERGE_CHOICE should_merge = MERGE_CHOICE_SEPARATE ;
if ( check_empty )
{
should_merge = check_empty_on_load() ;
if (should_merge == MERGE_CHOICE_CANCEL)
{
return true ;
}
if (should_merge == MERGE_CHOICE_SEPARATE)
{
mem = m_model->add_memory() ;
}
else
{
ATLASSERT(should_merge == MERGE_CHOICE_MERGE) ;
mem = m_model->get_first_memory() ;
make_dirty = true ;
}
}
else
{
mem = m_model->add_memory() ;
}
mem->set_is_memory(true) ;
mem->set_listener( static_cast< CProgressListener* >( this ) ) ;
try
{
const bool success = mem->load( file_name ) ;
if (make_dirty)
{
mem->set_saved_flag(false) ;
}
return success ;
}
catch ( ... )
{
logging::log_error("Failed to load memory") ;
if (should_merge == MERGE_CHOICE_SEPARATE)
{
mem->set_listener(nullptr);
m_model->remove_memory_by_id( mem->get_id() ) ;
}
throw ;
}
}
//! Set search params from registry settings.
void MemoryWindowFrame::init_lookup_properties( const app_props::props_ptr source, search_query_params &dest )
{
dest.m_ignore_case = !! source->m_mem_props.m_data.m_ignore_case ;
dest.m_ignore_width = !! source->m_mem_props.m_data.m_ignore_width ;
dest.m_ignore_hira_kata = !! source->m_mem_props.m_data.m_ignore_hir_kat ;
dest.m_assess_format_penalty = !! source->m_mem_props.m_data.m_assess_format_penalty ;
dest.m_match_algo = source->m_alg_props.m_data.m_match_algo ;
dest.m_place_numbers = !! source->m_mem_props.m_data.m_place_numbers ;
dest.m_place_gloss = !! source->m_mem_props.m_data.m_place_gloss ;
dest.m_place_rules = !! source->m_mem_props.m_data.m_place_rules ;
dest.m_show_gloss_matches = !! source->m_view_props.m_data.m_show_gloss_matches;
}
//! Tell the user that we found x matches for the search string.
void MemoryWindowFrame::source_concordance_feedback()
{
const wstring plain_text = m_search_matches.get_source_plain() ;
concordance_feedback(plain_text, m_search_matches.size()) ;
}
//! Tell the user that we found translation x matches for the search string.
void MemoryWindowFrame::translation_concordance_feedback()
{
const wstring plain_text = m_search_matches.get_trans_plain() ;
concordance_feedback(plain_text, m_search_matches.size()) ;
}
//! Show concordance match count in status bar.
void MemoryWindowFrame::concordance_feedback(const wstring plain_text, size_t num)
{
user_feedback(system_message(IDS_FOUND_X_MATCHES_FOR_STRING,
int_arg(num),
plain_text.c_str())) ;
}
//! Tell the user that we deleted a new record.
void MemoryWindowFrame::deleted_new_record_feedback()
{
const wstring feedback = L"<center><h1>" + resource_string_w( IDS_DELETED_ENTRY ) + L"</h1></center>" ;
m_view_interface.set_text(feedback) ;
user_feedback(IDS_DELETED_ENTRY) ;
check_mousewheel() ;
m_view_interface.set_scroll_pos(0) ;
}
//! See if we can create a placement for this match.
void MemoryWindowFrame::check_placement_numbers( trans_match_container &PlacedMatches,
search_match_ptr match )
{
record_pointer rec = match->get_record() ;
const wstring trans = rec->get_trans_plain() ;
trans_pair Transpair( trans, trans ) ;
match_string_pairing newPairing( match->match_pairing() ) ;
number_placer placer ;
pairings_t &pairings = newPairing.get() ;
if ( placer.place( pairings, Transpair ) )
{
search_match_ptr new_match = create_placement_match(match, Transpair.first);
placement_score(new_match, pairings, match->get_formatting_penalty());
// new query/source
pairing_query_source(new_match, pairings, Transpair.second);
new_match->match_pairing().set(pairings);
PlacedMatches.insert( new_match ) ;
}
}
void MemoryWindowFrame::add_placement_match( search_match_ptr match, trans_pair &trans_segs, pairings_t & pairings, trans_match_container &PlacedMatches )
{
search_match_ptr new_match = create_placement_match(match, trans_segs.first);
set_placement_penalty(new_match, pairings, match->get_formatting_penalty());
wstring newsource = get_new_source(pairings);
new_match->get_record()->set_source(newsource) ;
// new query/source
pairing_query_source(new_match, pairings, trans_segs.second);
new_match->match_pairing().set(pairings);
PlacedMatches.insert( new_match ) ;
}
void MemoryWindowFrame::set_placement_penalty( search_match_ptr new_match, pairings_t & pairings, double format_penalty )
{
const double PLACEMENT_PENALTY = 0.00001 ;
new_match->set_base_score( calc_score_gloss(pairings) - PLACEMENT_PENALTY) ;
new_match->set_formatting_penalty( format_penalty ) ;
}
wstring MemoryWindowFrame::get_new_source( pairings_t & pairings )
{
// This hack obliterates our formatting info
wstring newsource ;
FOREACH(pairing_entity entity, pairings)
{
if(entity.source())
{
newsource += entity.source() ;
}
}
return newsource ;
}
void MemoryWindowFrame::check_placement_gloss( trans_match_container &PlacedMatches,
search_match_ptr match )
{
record_pointer rec = match->get_record() ;
const wstring trans = rec->get_trans_plain() ;
wstring after = rec->get_trans_plain() ;
pairings_t &pairings = match->match_pairing().get() ;
placement::gloss_placer placer(get_glossary_window()->get_model()->get_memories()->get_memories()) ;
trans_pair trans_segs( trans, trans ) ;
hole_pair_t holes ;
hole_finder finder ;
if (! finder.find_hole(pairings, holes))
{
return ;
}
if ( placer.place(pairings, trans_segs, holes) )
{
add_placement_match(match, trans_segs, pairings, PlacedMatches);
}
return ;
}
void MemoryWindowFrame::check_placement_rules( trans_match_container &PlacedMatches, search_match_ptr match)
{
record_pointer rec = match->get_record() ;
const wstring trans = rec->get_trans_plain() ;
wstring after = rec->get_trans_plain() ;
pairings_t &pairings = match->match_pairing().get() ;
placement::rule_placer placer(m_rules) ;
trans_pair trans_segs( trans, trans ) ;
hole_pair_t holes ;
hole_finder finder ;
if (! finder.find_hole(pairings, holes))
{
return ;
}
if ( placer.place(pairings, trans_segs, holes) )
{
add_placement_match(match, trans_segs, pairings, PlacedMatches);
}
return ;
}
mem_engine::search_match_ptr MemoryWindowFrame::create_placement_match( search_match_ptr match, const wstring &trans ) const
{
search_match_ptr new_match(new search_match) ;
new_match->set_memory_id(match->get_memory_id()) ;
new_match->set_memory_location(match->get_memory_location()) ;
// record
record_pointer old_rec = match->get_record() ;
record_pointer new_rec = record_pointer(old_rec->clone()) ;
new_rec->set_validated_off() ;
new_rec->reset_refcount() ;
new_rec->set_trans( trans ) ;
new_match->set_record( new_rec ) ;
new_match->set_values_to_record() ;
return new_match ;
}
void MemoryWindowFrame::pairing_query_source( search_match_ptr new_match, pairings_t &pairings, const wstring after ) const
{
mem_engine::markup_ptr Markup = new_match->get_markup() ;
Markup->SetQuery(mark_up(pairings, QUERY)) ;
Markup->SetSource(mark_up(pairings, SOURCE)) ;
Markup->SetTrans( after ) ;
new_match->set_placement_on() ;
}
void MemoryWindowFrame::placement_score( mem_engine::search_match_ptr new_match, mem_engine::placement::pairings_t &pairings, double fmt_penalty ) const
{
// HACK -- to make sure that the placed matches sort below the non-placed ones
const double PLACEMENT_PENALTY = 0.00001 ;
new_match->set_base_score( calc_score(pairings) - PLACEMENT_PENALTY) ;
new_match->set_formatting_penalty( fmt_penalty ) ;
}
//! Make sure that ShellExecute didn't return an error code.
void MemoryWindowFrame::check_shell_execute_result( int result,
const CString & filePath )
{
const int ERR_THRESHOLD = 32 ;
if ( result <= ERR_THRESHOLD )
{
throw CWinException(system_message(IDS_SHOW_HELP_FAILED, (LPCTSTR)filePath), result ) ;
}
}
void MemoryWindowFrame::OnNavEdit( long index )
{
SENSE("OnNavEdit") ;
WindowsMessage message( NULL, 0, 0, index ) ;
on_user_edit( message ) ;
}
void MemoryWindowFrame::OnNavDelete( long index )
{
SENSE("OnNavDelete") ;
on_user_delete( static_cast<size_t>(index) ) ;
}
//! Register glossary entries based on entry at index.
void MemoryWindowFrame::OnNavAddGloss( long index )
{
SENSE("OnNavAddGloss") ;
on_user_register( index ) ;
}
//! Add the entry at index to the glossary.
void MemoryWindowFrame::OnNavAddToGloss( long index )
{
SENSE("OnNavAddToGloss") ;
on_user_add_to_glossary( index ) ;
}
void MemoryWindowFrame::remove_record_from_mem_id( record_pointer rec, int mem_id )
{
try
{
m_model->get_memory_by_id(mem_id)->erase( rec ) ;
}
catch (CProgramException& e)
{
logging::log_error("Failed to delete record") ;
logging::log_exception(e) ;
e.notify_user("Failed to delete record: memory not found") ;
}
}
void MemoryWindowFrame::remove_match_record( search_match_ptr match )
{
record_pointer rec = match->get_record() ;
remove_record_from_mem_id(rec, match->get_memory_id());
m_glossary_windows.remove_gloss_record(rec) ;
}
void MemoryWindowFrame::view_by_id( size_t recid, wstring source, wstring trans )
{
memory_pointer mem = get_memory_model()->get_memory_by_id(m_review_match->get_memory_id()) ;
m_review_match->set_record(mem->add_by_id(recid, source, trans)) ;
this->set_display_state(TRANS_REVIEW_STATE) ;
this->user_feedback(IDS_SHOW_TRANS) ;
m_view_interface.set_text(get_review_content(mem)) ;
check_mousewheel() ;
m_view_interface.set_scroll_pos(0) ;
}
void MemoryWindowFrame::add_by_id( size_t recid, wstring source, wstring trans )
{
if (source.empty() || trans.empty())
{
logging::log_warn("Source or translation empty in add_by_id") ;
return ;
}
memory_pointer mem = m_model->create_memory() ;
try
{
mem = get_memory_model()->get_first_memory() ;
}
catch (CException& e)
{
logging::log_error("Failed to get review memory") ;
logging::log_exception(e) ;
user_feedback(IDS_TRANS_REVIEW_FAILED) ;
return ;
}
m_review_match->set_record(mem->add_by_id(recid, source, trans)) ;
m_review_match->set_memory_id(mem->get_id()) ;
this->set_display_state(TRANS_REVIEW_STATE) ;
this->user_feedback(IDS_REFLECTED_TRANS) ;
m_view_interface.set_text(get_review_content(mem)) ;
check_mousewheel() ;
m_view_interface.set_scroll_pos(0) ;
}
mem_engine::search_match_ptr MemoryWindowFrame::get_current_match()
{
return m_view_state->get_current_match() ;
}
// Content when using translation history
wstring MemoryWindowFrame::get_review_content( memory_pointer mem )
{
search_match_ptr match(mem->make_match(m_review_match->get_record())) ;
match->set_values_to_record() ;
cpptempl::data_map data ;
m_trans_matches.fill_match_template_params(data, match);
// fill in the template
wstring content ;
if ( m_is_short_format )
{
content = cpptempl::parse(cpptempl::get_template_text(_T("review.txt")), data) ;
}
else
{
content = cpptempl::parse(cpptempl::get_template_text(_T("review_full.txt")), data) ;
}
return content ;
}
// Get the mousewheel setting
void MemoryWindowFrame::load_mousewheel_setting()
{
m_mousewheel_count = m_props->m_view_props.get_mem_mousewheel() ;
}
// Show the zoom dialog.
LRESULT MemoryWindowFrame::on_view_zoom( WindowsMessage & )
{
CZoomDlg dlg(static_cast< CZoomInterface* >( this ), m_mousewheel_count) ;
dlg.DoModal() ;
return 0L ;
}
// Load the translation history.
void MemoryWindowFrame::load_history()
{
this->m_model->clear() ;
app_props::properties_loaded_history *history_props = &m_props->m_history_props ;
auto gen_props = &m_props->m_gen_props;
std::vector<wstring> &loaded_mems = history_props->m_loaded_mems ;
std::vector<wstring> items ;
std::copy(loaded_mems.rbegin(), loaded_mems.rend(), std::back_inserter(items)) ;
FOREACH(wstring filename, items)
{
LOG_VERBOSE(string("Loading from history: ") + string2string(filename)) ;
load( filename.c_str(), false) ;
}
std::vector<wstring> remote_items ;
std::copy(history_props->m_loaded_remote_mems.rbegin(), history_props->m_loaded_remote_mems.rend(), std::back_inserter(remote_items)) ;
FOREACH(wstring filename, remote_items)
{
try
{
LOG_VERBOSE(string("Loading remote from history: ") + string2string(filename)) ;
memory_remote *mem = new memory_remote(m_props) ;
memory_pointer pmem(mem) ;
wstring username, password;
if (gen_props->credential_is_saved(filename))
{
username = gen_props->username_for_connection(filename);
CredentialReader reader(filename);
password = reader.get_password();
}
mem->connect(filename.c_str(), username.c_str(), password.c_str()) ;
this->add_memory(pmem) ;
}
catch (CException& e)
{
logging::log_error("Failed to load remote memory") ;
logging::log_error(string2string(filename)) ;
logging::log_exception(e) ;
this->FlashWindow(FALSE) ;
}
}
set_window_title() ;
}
// Load user preferences
// Todo: restore background color preferences
LRESULT MemoryWindowFrame::on_tools_load_preferences(WindowsMessage &)
{
logging::log_debug("Loading user preferences.") ;
// get the file name
file_open_dialog dialog;
dialog.set_title(R2T(IDS_LOAD_PREFS_TITLE));
dialog.set_file_filter(get_prefs_filter());
user_feedback( IDS_LOAD_PREFS_TITLE ) ;
if (!dialog.show())
{
user_feedback(IDS_CANCELLED_ACTION);
return 0L;
}
const WORD old_language = m_appstate.m_preferred_gui_lang ;
switch (dialog.get_selected_index())
{
case 1:
ATLTRACE( "Load new preferences format\n" ) ;
load_new_preferences(dialog.get_open_destination(), old_language);
break;
case 2:
load_old_preferences(dialog.get_open_destination());
break;
default:
ATLASSERT ( FALSE && "Unknown case in switch statement" ) ;
}
return 0L ;
}
// Serialize preferences to file
LRESULT MemoryWindowFrame::on_tools_save_preferences(WindowsMessage &)
{
logging::log_debug("Saving user preferences.") ;
user_feedback(IDS_SAVE_PREFS_TITLE);
file_save_dialog dialog ;
dialog.set_title(R2T(IDS_SAVE_PREFS_TITLE));
dialog.set_file_filter(get_prefs_filter());
dialog.set_last_save(m_props->m_history_props.m_preferences_location);
dialog.set_default_ext(L"fprefx");
if (!dialog.show())
{
user_feedback(IDS_CANCELLED_ACTION);
return 0L;
}
CString save_as_file_name = dialog.get_save_destination();
m_glossary_windows.save_prefs() ;
save_settings_close() ;
save_settings_destroy() ;
switch (dialog.get_selected_index())
{
case 1:
fileops::add_extension_as_needed(save_as_file_name, _T(".fprefx"));
ATLTRACE( "Save new preferences format\n" ) ;
break;
default:
LOG_VERBOSE("Unknown file type for prefs file. Saving raw filename.") ;
}
m_props->save_file(save_as_file_name);
user_feedback( IDS_PREFS_SAVED ) ;
return 0L ;
}
void MemoryWindowFrame::save_settings_close()
{
save_window_settings(_T("MainFrame"));
save_rebar_settings() ;
CReBarCtrl ReBar = m_hWndToolBar ;
m_appstate.m_rebar_has_linebreak = ReBar.GetRowCount() > 1 ;
m_appstate.write_to_registry() ;
m_props->write_to_registry() ;
}
void MemoryWindowFrame::save_settings_destroy()
{
// write our recent docs
m_mru.WriteToRegistry( resource_string( IDS_REG_KEY ) );
record_loaded_memory_history() ;
}
wstring MemoryWindowFrame::get_record_translation(record_pointer record)
{
return m_view_state->retrieve_record_trans(record,
record_string_prefs( m_props->m_mem_props.is_plaintext())) ;
}
/* Show the updates dialog.
* This is in a separate process, so that in the future we can have this
* process shut us down, and download/install the update automatically.
*/
LRESULT MemoryWindowFrame::on_help_check_updates(WindowsMessage &)
{
logging::log_debug("Checking for updates") ;
file::CPath path ;
path.GetModulePath(_Module.GetModuleInstance()) ;
path.Append(_T("pytools")) ;
path.Append(_T("CheckUpdates.exe")) ;
CString filepath = path.Path() ;
#ifdef _DEBUG
filepath = "D:\\Program Files (x86)\\Assistant Suite\\Felix\\pytools\\CheckUpdates.exe" ;
#endif
HINSTANCE result = ::ShellExecute(
m_hWnd, // HWND hwnd,
_T("open"), // LPCTSTR lpOperation,
filepath, // LPCTSTR lpFile,
NULL, // LPCTSTR lpParameters,
NULL, // LPCTSTR lpDirectory,
SW_SHOW // INT nShowCmd
);
check_shell_execute_result((int)result, filepath);
return 0L ;
}
void MemoryWindowFrame::set_module_library( WORD lang_id )
{
switch( lang_id )
{
case LANG_JAPANESE:
logging::log_debug("Setting UI language to Japanese") ;
if ( _Module.get_library() == _T("lang\\JpnResource.dll") )
{
logging::log_debug("Language is already Japanese") ;
m_appstate.m_preferred_gui_lang = lang_id ;
return ;
}
if ( ! _Module.set_library( _T("lang\\JpnResource.dll") ) )
{
/** @todo Get resource library names dynamically */
CString msg ;
msg.FormatMessage( IDS_SET_LIB_FAILED,
_T("lang\\JpnResource.dll") ) ;
throw except::CException( msg ) ;
}
break ;
case LANG_ENGLISH:
logging::log_debug("Setting UI language to English") ;
if ( _Module.get_library() == _T("lang\\EngResource.dll") )
{
logging::log_debug("Language is already English") ;
m_appstate.m_preferred_gui_lang = lang_id ;
return ;
}
if ( ! _Module.set_library( _T("lang\\EngResource.dll") ) )
{
CString msg ;
msg.FormatMessage( IDS_SET_LIB_FAILED,
_T("lang\\EngResource.dll") ) ;
throw except::CException( msg ) ;
}
break ;
default:
logging::log_warn("Unknown UI language setting") ;
logging::log_debug("Setting UI language to English") ;
ATLASSERT( FALSE && "Unknown language code!") ;
m_appstate.m_preferred_gui_lang = LANG_ENGLISH ;
if ( ! _Module.set_library( _T("lang\\EngResource.dll") ) )
{
CString msg ;
msg.FormatMessage( IDS_SET_LIB_FAILED,
_T("lang\\EngResource.dll") ) ;
throw except::CException( msg ) ;
}
}
}
void MemoryWindowFrame::load_old_preferences( const CString filename )
{
const WORD old_language = m_appstate.m_preferred_gui_lang ;
this->clear_memory() ;
m_model->clear() ;
logging::log_debug("Loading preferences") ;
CString command ;
command.Format(_T("REG IMPORT \"%s\""), static_cast<LPCTSTR>(filename)) ;
CString error_message = _T("Failed to load preferences") ;
// create the process
create_process(command, error_message);
// ==============
// read our properties from the registry
m_appstate.read_from_registry() ;
// get our default properties
m_props->read_from_registry() ;
reflect_loaded_preferences(old_language);
}
LRESULT MemoryWindowFrame::on_new_search( WindowsMessage &)
{
m_search_window.set_mem_window(true) ;
if (! m_search_window.IsWindow())
{
m_search_window.Create(*this) ;
}
m_search_window.set_mem_controller( this->get_model() ) ;
m_search_window.ShowWindow(SW_SHOW) ;
m_search_window.SetWindowPos(HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE) ;
m_search_window.show_search_page() ;
return 0L ;
}
// This lets us override the context menu.
void MemoryWindowFrame::set_doc_ui_handler()
{
#ifdef UNIT_TEST
return ;
#else
logging::log_debug("Setting the doc UI handler") ;
CComObject<CFelixMemDocUIHandler> *pUIH = NULL;
HRESULT hr = CComObject<CFelixMemDocUIHandler>::CreateInstance (&pUIH);
if (SUCCEEDED(hr))
{
pUIH->m_get_menu = boost::bind(&MemoryWindowFrame::show_doc_context_menu, this) ;
// Make our custom DocHostUIHandler the window.external handler
CComQIPtr<IDocHostUIHandlerDispatch> pIUIH = pUIH;
hr = m_view_interface.m_view.SetExternalUIHandler(pIUIH) ;
}
else
{
CComException com_exception(hr) ;
logging::log_error("Failed to set doc UI handler") ;
logging::log_exception(com_exception) ;
}
ATLASSERT(SUCCEEDED(hr)) ;
#endif
}
/* Display the context menu in response to a right click in the browser window.
Todo:
* Dynamic content
* More items
* images?
*/
HRESULT MemoryWindowFrame::show_doc_context_menu()
{
BANNER("CMainFrame::show_doc_context_menu") ;
CMenu menu ;
menu.CreatePopupMenu() ;
MenuWrapper wrapper(menu, m_hWnd) ;
wrapper.add_item(ID_EDIT_COPY, R2S(IDS_POPUP_COPY)) ;
wrapper.add_separator() ;
wrapper.add_item(ID_NEXT_PANE, R2S(IDS_POPUP_SWITCH_VIEWS)) ;
wrapper.add_item(ID_EDIT_REGISTER, R2S(IDS_POPUP_REGISTER_GLOSS)) ;
wrapper.add_separator() ;
wrapper.add_item(IDC_SOURCE_CONCORDANCE_SEL, R2S(IDS_SOURCE_CONCORDANCE)) ;
wrapper.add_item(IDC_TRANS_CONCORDANCE_SEL, R2S(IDS_TRANS_CONCORDANCE)) ;
wrapper.add_separator() ;
wrapper.add_item(ID_EDIT_DELETE, R2S(IDS_POPUP_DELETE)) ;
// Show the menu at the cursor position
wrapper.show() ;
return S_OK ;
}
/*
Close the top memory on the stack, if any.
Change window title to reflect new top memory, if any.
*/
LRESULT MemoryWindowFrame::on_memory_close(WindowsMessage &)
{
BANNER("CMainFrame::on_memory_close") ;
// base case -- there are no memories
if (m_model->empty())
{
return 0L ;
}
// See if the top memory needs saving
memory_pointer mem = this->get_memory_model()->get_first_memory() ;
if (! mem->is_saved())
{
if (check_save_memory(mem) == IDCANCEL)
{
return 0L ;
}
}
// Now remove it.
remove_memory(mem, IDS_CLOSED_MEMORY);
return 0L ;
}
void MemoryWindowFrame::addToMessageLoop()
{
#ifndef UNIT_TEST
// register object for message filtering
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
if (pLoop)
{
pLoop->AddMessageFilter(this);
}
#endif
}
CString MemoryWindowFrame::get_active_mem_name()
{
if ( ! m_model->empty() )
{
memory_pointer mem = m_model->get_first_memory() ;
if (! mem->is_local())
{
return mem->get_location() ;
}
else
{
const file::name fname = mem->get_location() ;
return fname.file_name_part() ;
}
}
return resource_string( IDS_NEW ) ;
}
LRESULT MemoryWindowFrame::on_user_lookup_source( WindowsMessage& )
{
SENSE("CMainFrame::on_user_lookup_source") ;
if (m_deferred_query.empty())
{
return 0L ;
}
this->lookup(m_deferred_query) ;
m_deferred_query.clear() ;
ATLASSERT(m_deferred_query.empty()) ;
return 0L ;
}
LRESULT MemoryWindowFrame::on_user_lookup_trans( WindowsMessage& )
{
SENSE("CMainFrame::on_user_lookup_trans") ;
if (m_deferred_query.empty())
{
return 0L ;
}
this->lookup_trans(m_deferred_query) ;
m_deferred_query.clear() ;
ATLASSERT(m_deferred_query.empty()) ;
return 0L ;
}
void MemoryWindowFrame::set_display_state( DISPLAY_STATE new_state )
{
switch(new_state)
{
case NEW_RECORD_DISPLAY_STATE:
m_view_state = &m_view_state_new ;
break ;
case INIT_DISPLAY_STATE:
m_view_state = &m_view_state_initial ;
break ;
case TRANS_REVIEW_STATE:
m_view_state = &m_view_state_review;
break ;
case MATCH_DISPLAY_STATE:
m_view_state = &m_view_state_match;
break ;
case CONCORDANCE_DISPLAY_STATE:
m_view_state = &m_view_state_concordance;
break ;
}
m_display_state = new_state ;
m_view_state->activate() ;
}
edit_record_dlg_ptr MemoryWindowFrame::get_editor()
{
return m_editor ;
}
bool MemoryWindowFrame::is_short_format()
{
return m_is_short_format ;
}
bool MemoryWindowFrame::is_single_page()
{
return !! m_props->m_view_props.m_data.m_single_screen_matches ;
}
void MemoryWindowFrame::set_menu_checkmark( int item_id, bool is_checked )
{
if (! this->IsWindow())
{
logging::log_debug("Window is not visible; ignoring menu checkmark.") ;
return ;
}
UISetCheck(item_id, !! is_checked);
UpdateLayout( FALSE ) ;
}
void MemoryWindowFrame::perform_concordance_search(mem_engine::search_query_params ¶ms)
{
search_match_container matches ;
m_model->perform_search( matches, params ) ;
m_search_matches.set_matches( matches ) ;
}
void MemoryWindowFrame::create_reg_gloss_window()
{
_Module.AddCreateWndData( &m_reg_gloss_dlg.m_thunk.cd, (CDialogImplBaseT< CWindow >*)&m_reg_gloss_dlg);
DLGPROC lpDialogProc = (DLGPROC)m_reg_gloss_dlg.StartDialogProc ;
instantiate_dlg(IDD_ADD_GLOSS, lpDialogProc) ;
ATLASSERT( m_reg_gloss_dlg.IsWindow() ) ;
if ( ! m_reg_gloss_dlg.IsWindow() )
{
throw except::CException( R2T( IDS_MSG_EDIT_REC_FAILED ) ) ;
}
}
void MemoryWindowFrame::save_memory_as( memory_pointer mem )
{
CString original_file_name;
if (mem->is_new() == false)
{
original_file_name = mem->get_fullpath();
}
CString dialog_title;
dialog_title.FormatMessage(IDS_SAVE, resource_string(IDS_MEMORY));
file_save_dialog dialog;
dialog.set_title(dialog_title);
dialog.set_file_filter(get_mem_save_filter());
dialog.set_filename(original_file_name);
dialog.set_last_save(m_props->m_history_props.m_memory_location);
dialog.set_default_ext(L"ftm");
if (!dialog.show())
{
user_feedback(IDS_CANCELLED_ACTION);
return;
}
CString save_as_file_name = dialog.get_save_destination();
switch (dialog.get_selected_index())
{
case 1: case 7:
logging::log_debug("Saving memory as ftm file") ;
fileops::add_extension_as_needed(save_as_file_name, _T(".ftm"));
break;
case 2:
logging::log_debug("Saving memory as xml file") ;
fileops::add_extension_as_needed(save_as_file_name, _T(".xml"));
break;
case 3:
logging::log_debug("Saving memory as tmx file") ;
fileops::add_extension_as_needed(save_as_file_name, _T(".tmx"));
export_tmx(save_as_file_name, mem);
return ;
case 4:
logging::log_debug("Saving memory as Trados text file") ;
fileops::add_extension_as_needed(save_as_file_name, _T(".txt"));
export_trados(save_as_file_name, mem);
return ;
case 5:
{
export_excel(save_as_file_name, mem);
return ;
}
case 6:
{
export_tabbed_text(save_as_file_name, mem);
return ;
}
default:
logging::log_warn("Unknown case in switch statement") ;
ATLASSERT ( FALSE && "Unknown case in switch statement" ) ;
logging::log_debug("Saving memory as tmx file") ;
fileops::add_extension_as_needed(save_as_file_name, _T(".tmx"));
export_tmx(save_as_file_name, mem);
break;
}
// If the name changes, then we make the current user into the creator
const CString old_location = mem->get_location() ;
mem->set_location(save_as_file_name);
save_memory( mem ) ;
m_props->m_history_props.m_memory_location =
static_cast<LPCWSTR>(save_as_file_name);
if (0 != old_location.CompareNoCase(save_as_file_name))
{
mem->set_creator_to_current_user( ) ;
}
set_window_title() ;
}
void MemoryWindowFrame::get_qc_messages( mem_engine::record_pointer record, std::vector<wstring> &messages )
{
app_props::properties_qc *props = &(m_props->m_qc_props) ;
if (! props->qc_enabled())
{
return ;
}
std::vector<qc::rule_ptr> rules ;
if (props->check_all_caps())
{
rules.push_back(qc::rule_ptr(new qc::AllCapsCheckRule)) ;
}
if (props->check_numbers())
{
rules.push_back(qc::rule_ptr(new qc::NumberCheckRule)) ;
}
if (props->check_gloss())
{
search_query_params params ;
params.m_ignore_case = !! m_props->m_gloss_props.m_data.m_ignore_case ;
params.m_ignore_width = !! m_props->m_gloss_props.m_data.m_ignore_width ;
params.m_ignore_hira_kata = !! m_props->m_gloss_props.m_data.m_ignore_hir_kat ;
params.set_source(record->get_source_rich()) ;
std::shared_ptr<memory_model> memories = get_glossary_window()->get_memory_model()->get_memories() ;
search_match_container matches ;
for(size_t i = 0 ; i < memories->size() ; ++i)
{
mem_engine::memory_pointer mem = memories->get_memory_at(i) ;
if (props->check_gloss_name(static_cast<LPCWSTR>(mem->get_fullpath())))
{
mem->get_glossary_matches(matches, params) ;
}
}
std::vector<qc::gloss_pair> gloss_matches ;
FOREACH(match_ptr match, matches)
{
record_pointer rec = match->get_record() ;
gloss_matches.push_back(qc::gloss_pair(rec->get_source_plain(), rec->get_trans_plain())) ;
}
rules.push_back(qc::rule_ptr(new qc::GlossCheckRule(gloss_matches))) ;
}
qc::QcChecker checker(rules) ;
checker.check(record->get_source_plain(), record->get_trans_plain()) ;
checker.get_error_msgs(messages) ;
}
INT_PTR MemoryWindowFrame::check_save_memory( mem_engine::memory_pointer mem )
{
switch( user_wants_to_save( mem->get_location() ) )
{
case IDNO :
mem->set_saved_flag( true ) ;
return IDNO;
case IDYES :
if ( IDCANCEL == LetUserSaveMemory(mem) )
{
return IDCANCEL ;
}
return IDYES ;
case IDCANCEL :
return IDCANCEL ;
default :
ATLASSERT( "Unknown response!" && FALSE ) ;
return IDCANCEL ;
}
}
void MemoryWindowFrame::save_old_prefs_file( CString filename )
{
CString command ;
command.Format(_T("REG EXPORT hkcu\\software\\assistantsuite\\felix \"%s\""), static_cast<LPCTSTR>(filename)) ;
if(is_vista_or_later())
{
command += _T(" /y") ;
}
CString error_message = _T("Failed to save preferences") ;
// create the process
create_process(command, error_message);
}
void MemoryWindowFrame::check_mousewheel_count()
{
if (m_mousewheel_count)
{
set_zoom_level(m_mousewheel_count) ;
}
}
mem_engine::placement::regex_rules * MemoryWindowFrame::get_regex_rules()
{
return &m_rules ;
}
int MemoryWindowFrame::get_gloss_show_command()
{
return m_glossary_windows.get_show_command(is_window());
}
bool MemoryWindowFrame::should_add_record_to_glossary( record_pointer record )
{
return record->get_source_plain().length() <= m_props->m_gloss_props.get_max_add()
&& m_props->m_gloss_props.get_max_add() > 0;
}
// Gets the glossary matches from the active glossary. NULL if there are no glossaries.
mem_engine::felix_query * MemoryWindowFrame::get_current_gloss_matches()
{
return m_glossary_windows.get_current_matches() ;
}
void MemoryWindowFrame::look_up_current_source_in_gloss()
{
search_match_ptr match = m_trans_matches.current() ;
record_pointer rec = match->get_record() ;
wstring entry_source = rec->get_source_plain() ;
m_glossary_windows.look_up( entry_source ) ;
}
input_device_ptr MemoryWindowFrame::get_input_device()
{
return m_input_device ;
}
output_device_ptr MemoryWindowFrame::get_output_device()
{
return m_output_device ;
}
model_iface_ptr MemoryWindowFrame::get_model()
{
return m_model ;
}
app_props::properties_general* MemoryWindowFrame::get_props_general()
{
return &(m_props->m_gen_props) ;
}
app_props::props_ptr MemoryWindowFrame::get_properties()
{
return m_props ;
}
void MemoryWindowFrame::register_event_listener( UINT id, boost::function< LRESULT( WindowsMessage& ) > listenerFunction )
{
this->m_message_map[id] = listenerFunction ;
}
void MemoryWindowFrame::register_user_event_listener( UINT id, boost::function< LRESULT( WindowsMessage& ) > listenerFunction )
{
this->m_user_message_map[id] = listenerFunction ;
}
void MemoryWindowFrame::register_command_event_listener( UINT id, boost::function< LRESULT( WindowsMessage& ) > listenerFunction )
{
this->m_command_message_map[id] = listenerFunction ;
}
long MemoryWindowFrame::get_num_matches()
{
return m_trans_matches.size() ;
}
void MemoryWindowFrame::add_edit_record( mem_engine::record_pointer new_record, LPARAM display_state )
{
set_display_state( static_cast< DISPLAY_STATE >( display_state ) ) ;
ATLASSERT( get_display_state() == display_state ) ;
SENSE("add_edit_record") ;
ATLASSERT( m_editor->get_memory_id() > 0 ) ;
m_view_state->retrieve_edit_record(m_editor->get_memory_id(),
new_record,
true) ;
#ifdef UNIT_TEST
return ;
#else
show_view_content() ;
#endif
}
void MemoryWindowFrame::edit_edit_record( mem_engine::record_pointer new_record, LPARAM display_state )
{
set_display_state( static_cast< DISPLAY_STATE >( display_state ) ) ;
ATLASSERT( get_display_state() == display_state ) ;
SENSE("edit_edit_record") ;
ATLASSERT( m_editor->get_memory_id() > 0 ) ;
m_view_state->retrieve_edit_record(m_editor->get_memory_id(),
new_record,
false) ;
#ifdef UNIT_TEST
return ;
#else
show_view_content() ;
#endif
}
BOOL MemoryWindowFrame::handle_sw_exception( except::CSWException &e, const CString &failure_message )
{
return CCommonWindowFunctionality::handle_sw_exception(e, failure_message) ;
}
bool MemoryWindowFrame::check_for_clashes( memory_type mem )
{
if (m_glossary_windows.has_clashes(mem->get_location()))
{
return IDCANCEL != prompt_user_for_overwrite( mem->get_location() ) ;
}
return true ;
}
model_iface_ptr MemoryWindowFrame::get_memory_model()
{
return m_model ;
}
mem_engine::felix_query * MemoryWindowFrame::get_current_matches()
{
return &m_trans_matches ;
}
| 25.764362 | 155 | 0.703893 | [
"object",
"vector",
"model"
] |
87041c11a22d38efb91a936ff54e0dcdf584df16 | 17,919 | cc | C++ | chrome/browser/ui/ash/launcher/arc_app_launcher_browsertest.cc | xzhan96/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-01-07T18:51:03.000Z | 2021-01-07T18:51:03.000Z | chrome/browser/ui/ash/launcher/arc_app_launcher_browsertest.cc | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/ash/launcher/arc_app_launcher_browsertest.cc | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 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.
#include "ash/common/shelf/shelf_delegate.h"
#include "ash/common/wm_shell.h"
#include "ash/wm/window_util.h"
#include "base/macros.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/ui/app_list/app_list_service.h"
#include "chrome/browser/ui/app_list/app_list_syncable_service.h"
#include "chrome/browser/ui/app_list/app_list_syncable_service_factory.h"
#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h"
#include "chrome/browser/ui/app_list/arc/arc_app_utils.h"
#include "chrome/browser/ui/ash/launcher/arc_app_deferred_launcher_controller.h"
#include "chrome/browser/ui/ash/launcher/arc_app_window_launcher_controller.h"
#include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h"
#include "chrome/browser/ui/ash/launcher/launcher_item_controller.h"
#include "chromeos/chromeos_switches.h"
#include "content/public/test/browser_test_utils.h"
#include "mojo/common/common_type_converters.h"
#include "ui/events/event_constants.h"
namespace mojo {
template <>
struct TypeConverter<arc::mojom::AppInfoPtr, arc::mojom::AppInfo> {
static arc::mojom::AppInfoPtr Convert(const arc::mojom::AppInfo& app_info) {
return app_info.Clone();
}
};
template <>
struct TypeConverter<arc::mojom::ArcPackageInfoPtr,
arc::mojom::ArcPackageInfo> {
static arc::mojom::ArcPackageInfoPtr Convert(
const arc::mojom::ArcPackageInfo& package_info) {
return package_info.Clone();
}
};
template <>
struct TypeConverter<arc::mojom::ShortcutInfoPtr, arc::mojom::ShortcutInfo> {
static arc::mojom::ShortcutInfoPtr Convert(
const arc::mojom::ShortcutInfo& shortcut_info) {
return shortcut_info.Clone();
}
};
} // namespace mojo
namespace {
constexpr char kTestAppName[] = "Test Arc App";
constexpr char kTestAppName2[] = "Test Arc App 2";
constexpr char kTestShortcutName[] = "Test Shortcut";
constexpr char kTestShortcutName2[] = "Test Shortcut 2";
constexpr char kTestAppPackage[] = "test.arc.app.package";
constexpr char kTestAppActivity[] = "test.arc.app.package.activity";
constexpr char kTestAppActivity2[] = "test.arc.gitapp.package.activity2";
constexpr char kTestShelfGroup[] = "shelf_group";
constexpr char kTestShelfGroup2[] = "shelf_group_2";
constexpr char kTestShelfGroup3[] = "shelf_group_3";
constexpr int kAppAnimatedThresholdMs = 100;
std::string GetTestApp1Id() {
return ArcAppListPrefs::GetAppId(kTestAppPackage, kTestAppActivity);
}
std::string GetTestApp2Id() {
return ArcAppListPrefs::GetAppId(kTestAppPackage, kTestAppActivity2);
}
std::vector<arc::mojom::AppInfoPtr> GetTestAppsList(bool multi_app) {
std::vector<arc::mojom::AppInfoPtr> apps;
arc::mojom::AppInfoPtr app(arc::mojom::AppInfo::New());
app->name = kTestAppName;
app->package_name = kTestAppPackage;
app->activity = kTestAppActivity;
app->sticky = false;
apps.push_back(std::move(app));
if (multi_app) {
app = arc::mojom::AppInfo::New();
app->name = kTestAppName2;
app->package_name = kTestAppPackage;
app->activity = kTestAppActivity2;
app->sticky = false;
apps.push_back(std::move(app));
}
return apps;
}
ChromeLauncherController* chrome_controller() {
return ChromeLauncherController::instance();
}
ash::ShelfDelegate* shelf_delegate() {
return ash::WmShell::Get()->shelf_delegate();
}
class AppAnimatedWaiter {
public:
explicit AppAnimatedWaiter(const std::string& app_id) : app_id_(app_id) {}
void Wait() {
const base::TimeDelta threshold =
base::TimeDelta::FromMilliseconds(kAppAnimatedThresholdMs);
ArcAppDeferredLauncherController* controller =
chrome_controller()->GetArcDeferredLauncher();
while (controller->GetActiveTime(app_id_) < threshold) {
base::RunLoop().RunUntilIdle();
}
}
private:
const std::string app_id_;
};
enum TestAction {
TEST_ACTION_START, // Start app on app appears.
TEST_ACTION_EXIT, // Exit Chrome during animation.
TEST_ACTION_CLOSE, // Close item during animation.
};
// Test parameters include TestAction and pin/unpin state.
typedef std::tr1::tuple<TestAction, bool> TestParameter;
TestParameter build_test_parameter[] = {
TestParameter(TEST_ACTION_START, false),
TestParameter(TEST_ACTION_EXIT, false),
TestParameter(TEST_ACTION_CLOSE, false),
TestParameter(TEST_ACTION_START, true),
};
std::string CreateIntentUriWithShelfGroup(const std::string& shelf_group_id) {
return base::StringPrintf("#Intent;S.org.chromium.arc.shelf_group_id=%s;end",
shelf_group_id.c_str());
}
} // namespace
class ArcAppLauncherBrowserTest : public ExtensionBrowserTest {
public:
ArcAppLauncherBrowserTest() {}
~ArcAppLauncherBrowserTest() override {}
protected:
// content::BrowserTestBase:
void SetUpCommandLine(base::CommandLine* command_line) override {
ExtensionBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(chromeos::switches::kEnableArc);
}
void SetUpInProcessBrowserTestFixture() override {
ExtensionBrowserTest::SetUpInProcessBrowserTestFixture();
arc::ArcAuthService::DisableUIForTesting();
}
void SetUpOnMainThread() override { arc::ArcAuthService::Get()->EnableArc(); }
void InstallTestApps(bool multi_app) {
app_host()->OnAppListRefreshed(GetTestAppsList(multi_app));
std::unique_ptr<ArcAppListPrefs::AppInfo> app_info =
app_prefs()->GetApp(GetTestApp1Id());
ASSERT_TRUE(app_info);
EXPECT_TRUE(app_info->ready);
if (multi_app) {
std::unique_ptr<ArcAppListPrefs::AppInfo> app_info2 =
app_prefs()->GetApp(GetTestApp2Id());
ASSERT_TRUE(app_info2);
EXPECT_TRUE(app_info2->ready);
}
}
std::string InstallShortcut(const std::string& name,
const std::string& shelf_group) {
arc::mojom::ShortcutInfo shortcut;
shortcut.name = name;
shortcut.package_name = kTestAppPackage;
shortcut.intent_uri = CreateIntentUriWithShelfGroup(shelf_group);
const std::string shortcut_id =
ArcAppListPrefs::GetAppId(shortcut.package_name, shortcut.intent_uri);
app_host()->OnInstallShortcut(arc::mojom::ShortcutInfo::From(shortcut));
base::RunLoop().RunUntilIdle();
std::unique_ptr<ArcAppListPrefs::AppInfo> shortcut_info =
app_prefs()->GetApp(shortcut_id);
CHECK(shortcut_info);
EXPECT_TRUE(shortcut_info->shortcut);
EXPECT_EQ(kTestAppPackage, shortcut_info->package_name);
EXPECT_EQ(shortcut.intent_uri, shortcut_info->intent_uri);
return shortcut_id;
}
void SendPackageAdded(bool package_synced) {
arc::mojom::ArcPackageInfo package_info;
package_info.package_name = kTestAppPackage;
package_info.package_version = 1;
package_info.last_backup_android_id = 1;
package_info.last_backup_time = 1;
package_info.sync = package_synced;
package_info.system = false;
app_host()->OnPackageAdded(arc::mojom::ArcPackageInfo::From(package_info));
base::RunLoop().RunUntilIdle();
}
void SendPackageUpdated(bool multi_app) {
app_host()->OnPackageAppListRefreshed(kTestAppPackage,
GetTestAppsList(multi_app));
}
void SendPackageRemoved() { app_host()->OnPackageRemoved(kTestAppPackage); }
void StartInstance() {
if (auth_service()->profile() != profile())
auth_service()->OnPrimaryUserProfilePrepared(profile());
app_instance_observer()->OnInstanceReady();
}
void StopInstance() {
auth_service()->Shutdown();
app_instance_observer()->OnInstanceClosed();
}
LauncherItemController* GetAppItemController(const std::string& id) {
const ash::ShelfID shelf_id = shelf_delegate()->GetShelfIDForAppID(id);
if (!shelf_id)
return nullptr;
LauncherItemController* controller =
chrome_controller()->GetLauncherItemController(shelf_id);
if (!controller)
return nullptr;
DCHECK_EQ(LauncherItemController::TYPE_APP, controller->type());
return controller;
}
ArcAppListPrefs* app_prefs() { return ArcAppListPrefs::Get(profile()); }
// Returns as AppHost interface in order to access to private implementation
// of the interface.
arc::mojom::AppHost* app_host() { return app_prefs(); }
// Returns as AppInstance observer interface in order to access to private
// implementation of the interface.
arc::InstanceHolder<arc::mojom::AppInstance>::Observer*
app_instance_observer() {
return app_prefs();
}
arc::ArcAuthService* auth_service() { return arc::ArcAuthService::Get(); }
private:
DISALLOW_COPY_AND_ASSIGN(ArcAppLauncherBrowserTest);
};
class ArcAppDeferredLauncherBrowserTest
: public ArcAppLauncherBrowserTest,
public testing::WithParamInterface<TestParameter> {
public:
ArcAppDeferredLauncherBrowserTest() {}
~ArcAppDeferredLauncherBrowserTest() override {}
protected:
bool is_pinned() const { return std::tr1::get<1>(GetParam()); }
TestAction test_action() const { return std::tr1::get<0>(GetParam()); }
private:
DISALLOW_COPY_AND_ASSIGN(ArcAppDeferredLauncherBrowserTest);
};
// This tests simulates normal workflow for starting Arc app in deferred mode.
IN_PROC_BROWSER_TEST_P(ArcAppDeferredLauncherBrowserTest, StartAppDeferred) {
// Install app to remember existing apps.
StartInstance();
InstallTestApps(false);
SendPackageAdded(false);
const std::string app_id = GetTestApp1Id();
if (is_pinned()) {
shelf_delegate()->PinAppWithID(app_id);
EXPECT_TRUE(shelf_delegate()->GetShelfIDForAppID(app_id));
} else {
EXPECT_FALSE(shelf_delegate()->GetShelfIDForAppID(app_id));
}
StopInstance();
std::unique_ptr<ArcAppListPrefs::AppInfo> app_info =
app_prefs()->GetApp(app_id);
EXPECT_FALSE(app_info);
// Restart instance. App should be taken from prefs but its state is non-ready
// currently.
StartInstance();
app_info = app_prefs()->GetApp(app_id);
ASSERT_TRUE(app_info);
EXPECT_FALSE(app_info->ready);
if (is_pinned())
EXPECT_TRUE(shelf_delegate()->GetShelfIDForAppID(app_id));
else
EXPECT_FALSE(shelf_delegate()->GetShelfIDForAppID(app_id));
// Launching non-ready Arc app creates item on shelf and spinning animation.
arc::LaunchApp(profile(), app_id, ui::EF_LEFT_MOUSE_BUTTON);
EXPECT_TRUE(shelf_delegate()->GetShelfIDForAppID(app_id));
AppAnimatedWaiter(app_id).Wait();
switch (test_action()) {
case TEST_ACTION_START:
// Now simulates that Arc is started and app list is refreshed. This
// should stop animation and delete icon from the shelf.
InstallTestApps(false);
SendPackageAdded(false);
EXPECT_TRUE(chrome_controller()
->GetArcDeferredLauncher()
->GetActiveTime(app_id)
.is_zero());
if (is_pinned())
EXPECT_TRUE(shelf_delegate()->GetShelfIDForAppID(app_id));
else
EXPECT_FALSE(shelf_delegate()->GetShelfIDForAppID(app_id));
break;
case TEST_ACTION_EXIT:
// Just exist Chrome.
break;
case TEST_ACTION_CLOSE:
// Close item during animation.
{
LauncherItemController* controller = GetAppItemController(app_id);
ASSERT_TRUE(controller);
controller->Close();
EXPECT_TRUE(chrome_controller()
->GetArcDeferredLauncher()
->GetActiveTime(app_id)
.is_zero());
if (is_pinned())
EXPECT_TRUE(shelf_delegate()->GetShelfIDForAppID(app_id));
else
EXPECT_FALSE(shelf_delegate()->GetShelfIDForAppID(app_id));
}
break;
}
}
INSTANTIATE_TEST_CASE_P(ArcAppDeferredLauncherBrowserTestInstance,
ArcAppDeferredLauncherBrowserTest,
::testing::ValuesIn(build_test_parameter));
// This tests validates pin state on package update and remove.
IN_PROC_BROWSER_TEST_F(ArcAppLauncherBrowserTest, PinOnPackageUpdateAndRemove) {
StartInstance();
// Make use app list sync service is started. Normally it is started when
// sycing is initialized.
app_list::AppListSyncableServiceFactory::GetForProfile(profile())->GetModel();
InstallTestApps(true);
SendPackageAdded(false);
const std::string app_id1 = GetTestApp1Id();
const std::string app_id2 = GetTestApp2Id();
shelf_delegate()->PinAppWithID(app_id1);
shelf_delegate()->PinAppWithID(app_id2);
const ash::ShelfID shelf_id1_before =
shelf_delegate()->GetShelfIDForAppID(app_id1);
EXPECT_TRUE(shelf_id1_before);
EXPECT_TRUE(shelf_delegate()->GetShelfIDForAppID(app_id2));
// Package contains only one app. App list is not shown for updated package.
SendPackageUpdated(false);
// Second pin should gone.
EXPECT_EQ(shelf_id1_before, shelf_delegate()->GetShelfIDForAppID(app_id1));
EXPECT_FALSE(shelf_delegate()->GetShelfIDForAppID(app_id2));
// Package contains two apps. App list is not shown for updated package.
SendPackageUpdated(true);
// Second pin should not appear.
EXPECT_EQ(shelf_id1_before, shelf_delegate()->GetShelfIDForAppID(app_id1));
EXPECT_FALSE(shelf_delegate()->GetShelfIDForAppID(app_id2));
// Package removed.
SendPackageRemoved();
// No pin is expected.
EXPECT_FALSE(shelf_delegate()->GetShelfIDForAppID(app_id1));
EXPECT_FALSE(shelf_delegate()->GetShelfIDForAppID(app_id2));
}
// This test validates that app list is shown on new package and not shown
// on package update.
IN_PROC_BROWSER_TEST_F(ArcAppLauncherBrowserTest, AppListShown) {
StartInstance();
AppListService* app_list_service = AppListService::Get();
ASSERT_TRUE(app_list_service);
EXPECT_FALSE(app_list_service->IsAppListVisible());
// New package is available. Show app list.
InstallTestApps(false);
SendPackageAdded(true);
EXPECT_TRUE(app_list_service->IsAppListVisible());
app_list_service->DismissAppList();
EXPECT_FALSE(app_list_service->IsAppListVisible());
// Send package update event. App list is not shown.
SendPackageAdded(true);
EXPECT_FALSE(app_list_service->IsAppListVisible());
}
// Test AppListControllerDelegate::IsAppOpen for Arc apps.
IN_PROC_BROWSER_TEST_F(ArcAppLauncherBrowserTest, IsAppOpen) {
StartInstance();
InstallTestApps(false);
SendPackageAdded(true);
const std::string app_id = GetTestApp1Id();
AppListService* service = AppListService::Get();
AppListControllerDelegate* delegate = service->GetControllerDelegate();
EXPECT_FALSE(delegate->IsAppOpen(app_id));
arc::LaunchApp(profile(), app_id, ui::EF_LEFT_MOUSE_BUTTON);
EXPECT_FALSE(delegate->IsAppOpen(app_id));
// Simulate task creation so the app is marked as running/open.
std::unique_ptr<ArcAppListPrefs::AppInfo> info = app_prefs()->GetApp(app_id);
app_host()->OnTaskCreated(0, info->package_name, info->activity, info->name,
info->intent_uri);
EXPECT_TRUE(delegate->IsAppOpen(app_id));
}
// Test Shelf Groups
IN_PROC_BROWSER_TEST_F(ArcAppLauncherBrowserTest, ShelfGroup) {
StartInstance();
InstallTestApps(false);
SendPackageAdded(true);
const std::string shorcut_id1 =
InstallShortcut(kTestShortcutName, kTestShelfGroup);
const std::string shorcut_id2 =
InstallShortcut(kTestShortcutName2, kTestShelfGroup2);
const std::string app_id = GetTestApp1Id();
std::unique_ptr<ArcAppListPrefs::AppInfo> info = app_prefs()->GetApp(app_id);
ASSERT_TRUE(info);
const std::string shelf_id1 =
arc::ArcAppShelfId(kTestShelfGroup, app_id).ToString();
const std::string shelf_id2 =
arc::ArcAppShelfId(kTestShelfGroup2, app_id).ToString();
const std::string shelf_id3 =
arc::ArcAppShelfId(kTestShelfGroup3, app_id).ToString();
// 1 task for group 1
app_host()->OnTaskCreated(1, info->package_name, info->activity, info->name,
CreateIntentUriWithShelfGroup(kTestShelfGroup));
LauncherItemController* controller1 = GetAppItemController(shelf_id1);
ASSERT_TRUE(controller1);
// 2 tasks for group 2
app_host()->OnTaskCreated(2, info->package_name, info->activity, info->name,
CreateIntentUriWithShelfGroup(kTestShelfGroup2));
LauncherItemController* controller2 = GetAppItemController(shelf_id2);
ASSERT_TRUE(controller2);
ASSERT_NE(controller1, controller2);
app_host()->OnTaskCreated(3, info->package_name, info->activity, info->name,
CreateIntentUriWithShelfGroup(kTestShelfGroup2));
ASSERT_EQ(controller2, GetAppItemController(shelf_id2));
// 2 tasks for group 3 which does not have shortcut.
app_host()->OnTaskCreated(4, info->package_name, info->activity, info->name,
CreateIntentUriWithShelfGroup(kTestShelfGroup3));
LauncherItemController* controller3 = GetAppItemController(shelf_id3);
ASSERT_TRUE(controller3);
ASSERT_NE(controller1, controller3);
ASSERT_NE(controller2, controller3);
app_host()->OnTaskCreated(5, info->package_name, info->activity, info->name,
CreateIntentUriWithShelfGroup(kTestShelfGroup3));
ASSERT_EQ(controller3, GetAppItemController(shelf_id3));
// Destroy task #0, this kills shelf group 1
app_host()->OnTaskDestroyed(1);
EXPECT_FALSE(GetAppItemController(shelf_id1));
// Destroy task #1, shelf group 2 is still alive
app_host()->OnTaskDestroyed(2);
EXPECT_EQ(controller2, GetAppItemController(shelf_id2));
// Destroy task #2, this kills shelf group 2
app_host()->OnTaskDestroyed(3);
EXPECT_FALSE(GetAppItemController(shelf_id2));
// Disable Arc, this removes app and as result kills shelf group 3.
arc::ArcAuthService::Get()->DisableArc();
EXPECT_FALSE(GetAppItemController(shelf_id3));
}
| 35.343195 | 80 | 0.729338 | [
"vector"
] |
870684e9bfa58efef25333e164f43fd29b3503c1 | 2,844 | cpp | C++ | third_party/spirv-tools/test/ext_inst.non_semantic_test.cpp | Alan-love/filament | 87ee5783b7f72bb5b045d9334d719ea2de9f5247 | [
"Apache-2.0"
] | 13,885 | 2018-08-03T17:46:24.000Z | 2022-03-31T14:26:19.000Z | test/ext_inst.non_semantic_test.cpp | indrarahul2013/SPIRV-Tools | 636f449e1529a10d259eb7dc37d97192cf2820f8 | [
"Apache-2.0"
] | 3,533 | 2015-11-16T15:43:09.000Z | 2022-03-31T17:42:38.000Z | test/ext_inst.non_semantic_test.cpp | indrarahul2013/SPIRV-Tools | 636f449e1529a10d259eb7dc37d97192cf2820f8 | [
"Apache-2.0"
] | 1,500 | 2018-08-03T23:34:27.000Z | 2022-03-30T13:43:10.000Z | // Copyright (c) 2015-2016 The Khronos Group Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Assembler tests for non-semantic extended instructions
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "test/test_fixture.h"
#include "test/unit_spirv.h"
using ::testing::Eq;
namespace spvtools {
namespace {
using NonSemanticRoundTripTest = RoundTripTest;
using NonSemanticTextToBinaryTest = spvtest::TextToBinaryTest;
TEST_F(NonSemanticRoundTripTest, NonSemanticInsts) {
std::string spirv = R"(OpExtension "SPV_KHR_non_semantic_info"
%1 = OpExtInstImport "NonSemantic.Testing.ExtInst"
%2 = OpTypeVoid
%3 = OpExtInst %2 %1 132384681 %2
%4 = OpTypeInt 32 0
%5 = OpConstant %4 123
%6 = OpString "Test string"
%7 = OpExtInst %4 %1 82198732 %5 %6
%8 = OpExtInstImport "NonSemantic.Testing.AnotherUnknownExtInstSet"
%9 = OpExtInst %4 %8 613874321 %7 %5 %6
)";
std::string disassembly = EncodeAndDecodeSuccessfully(
spirv, SPV_BINARY_TO_TEXT_OPTION_NONE, SPV_ENV_UNIVERSAL_1_0);
EXPECT_THAT(disassembly, Eq(spirv));
}
TEST_F(NonSemanticTextToBinaryTest, InvalidExtInstSetName) {
std::string spirv = R"(OpExtension "SPV_KHR_non_semantic_info"
%1 = OpExtInstImport "NonSemantic_Testing_ExtInst"
)";
EXPECT_THAT(
CompileFailure(spirv),
Eq("Invalid extended instruction import 'NonSemantic_Testing_ExtInst'"));
}
TEST_F(NonSemanticTextToBinaryTest, NonSemanticIntParameter) {
std::string spirv = R"(OpExtension "SPV_KHR_non_semantic_info"
%1 = OpExtInstImport "NonSemantic.Testing.ExtInst"
%2 = OpTypeVoid
%3 = OpExtInst %2 %1 1 99999
)";
EXPECT_THAT(CompileFailure(spirv), Eq("Expected id to start with %."));
}
TEST_F(NonSemanticTextToBinaryTest, NonSemanticFloatParameter) {
std::string spirv = R"(OpExtension "SPV_KHR_non_semantic_info"
%1 = OpExtInstImport "NonSemantic.Testing.ExtInst"
%2 = OpTypeVoid
%3 = OpExtInst %2 %1 1 3.141592
)";
EXPECT_THAT(CompileFailure(spirv), Eq("Expected id to start with %."));
}
TEST_F(NonSemanticTextToBinaryTest, NonSemanticStringParameter) {
std::string spirv = R"(OpExtension "SPV_KHR_non_semantic_info"
%1 = OpExtInstImport "NonSemantic.Testing.ExtInst"
%2 = OpTypeVoid
%3 = OpExtInst %2 %1 1 "foobar"
)";
EXPECT_THAT(CompileFailure(spirv), Eq("Expected id to start with %."));
}
} // namespace
} // namespace spvtools
| 31.252747 | 79 | 0.753868 | [
"vector"
] |
8708b657396c6e6a3b6ba0308f41ef672b8fc203 | 5,079 | hpp | C++ | src/Engine/Manager/ResourceManager.hpp | Chainsawkitten/test-dev | 7b2e1bf4bac48b17a92c2ef60a56d0248947ee83 | [
"MIT"
] | 10 | 2019-01-13T05:51:54.000Z | 2022-02-02T14:34:47.000Z | src/Engine/Manager/ResourceManager.hpp | Chainsawkitten/test-dev | 7b2e1bf4bac48b17a92c2ef60a56d0248947ee83 | [
"MIT"
] | 46 | 2016-12-30T11:14:25.000Z | 2021-09-04T12:50:40.000Z | src/Engine/Manager/ResourceManager.hpp | Chainsawkitten/test-dev | 7b2e1bf4bac48b17a92c2ef60a56d0248947ee83 | [
"MIT"
] | 4 | 2017-09-28T09:00:58.000Z | 2019-10-22T05:28:32.000Z | #pragma once
#include <map>
#include <string>
namespace Video {
class Renderer;
class LowLevelRenderer;
class Texture2D;
namespace Geometry {
class Rectangle;
}
} // namespace Video
namespace Geometry {
class Cube;
class Model;
} // namespace Geometry
namespace Audio {
class SoundFile;
class AudioMaterial;
} // namespace Audio
class TextureAsset;
class ScriptFile;
/// Handles all resources.
class ResourceManager {
friend class Hub;
public:
/// Constructor
/**
* @param renderer The renderer.
*/
explicit ResourceManager(Video::Renderer* renderer);
/// Destructor.
~ResourceManager();
/// Create a model if it doesn't already exist.
/**
* @param name Name of model.
* @return The model instance
*/
Geometry::Model* CreateModel(const std::string& name);
/// Free the reference to the model.
/**
* @param model %Model to dereference.
*/
void FreeModel(Geometry::Model* model);
/// Create a 2D texture if it doesn't already exist.
/**
* @param data Image file data.
* @param dataLength Length of the image file data.
* @return The %Texture2D instance
*/
Video::Texture2D* CreateTexture2D(const char* data, int dataLength);
/// Free the reference to the 2D texture.
/**
* Deletes the instance if no more references exist.
* @param texture %Texture to dereference.
*/
void FreeTexture2D(Video::Texture2D* texture);
/// Create a texture asset if it doesn't already exist.
/**
* @param name The name of the texture asset.
* @return The %TextureAsset instance
*/
TextureAsset* CreateTextureAsset(const std::string& name);
/// Free the reference to the texture asset.
/**
* Deletes the instance if no more references exist.
* @param textureAsset %TextureAsset to dereference.
*/
void FreeTextureAsset(TextureAsset* textureAsset);
/// Get the number of instances of a texture asset.
/**
* @param textureAsset The texture asset to check.
* @return How many instances of the texture asset currently exist.
*/
int GetTextureAssetInstanceCount(TextureAsset* textureAsset);
/// Create a sound if it doesn't already exist.
/**
* @param name Name of the sound.
* @return The %SoundBuffer instance.
*/
Audio::SoundFile* CreateSound(const std::string& name);
/// Free the reference to the sound.
/**
* Deletes the instance if no more references exist.
* @param soundFile %SoundFile to dereference.
*/
void FreeSound(Audio::SoundFile* soundFile);
/// Create a script file if it doesn't already exist.
/**
* @param name Name of the script file.
* @return The %ScriptFile instance.
*/
ScriptFile* CreateScriptFile(const std::string& name);
/// Free the reference to the script file.
/**
* Deletes the instance if no more references exist.
* @param scriptFile %ScriptFile to dereference.
*/
void FreeScriptFile(ScriptFile* scriptFile);
/// Get the default albedo texture.
/**
* @return The default albedo texture.
*/
TextureAsset* GetDefaultAlbedo();
/// Get the default normal map.
/**
* @return The default normal map.
*/
TextureAsset* GetDefaultNormal();
/// Get the default roughness-metallic texture.
/**
* @return The default roughness-metallic texture.
*/
TextureAsset* GetDefaultRoughnessMetallic();
private:
ResourceManager(ResourceManager const&) = delete;
void operator=(ResourceManager const&) = delete;
Video::LowLevelRenderer* lowLevelRenderer;
// Rectangle
Video::Geometry::Rectangle* rectangle = nullptr;
int rectangleCount = 0;
// Cube
Geometry::Cube* cube = nullptr;
int cubeCount = 0;
// Model.
struct ModelInstance {
Geometry::Model* model;
int count;
};
std::map<std::string, ModelInstance> models;
std::map<Geometry::Model*, std::string> modelsInverse;
// Texture2D.
struct Texture2DInstance {
Video::Texture2D* texture;
int count;
};
std::map<const char*, Texture2DInstance> textures;
std::map<Video::Texture2D*, const char*> texturesInverse;
// Texture asset.
struct TextureAssetInstance {
TextureAsset* textureAsset;
int count;
};
std::map<std::string, TextureAssetInstance> textureAssets;
std::map<TextureAsset*, std::string> textureAssetsInverse;
// Sound.
struct SoundInstance {
Audio::SoundFile* sound;
int count;
};
std::map<std::string, SoundInstance> sounds;
std::map<Audio::SoundFile*, std::string> soundsInverse;
// ScriptFile.
struct ScriptFileInstance {
ScriptFile* scriptFile;
int count;
};
std::map<std::string, ScriptFileInstance> scriptFiles;
std::map<ScriptFile*, std::string> scriptFilesInverse;
TextureAsset* defaultAlbedo;
TextureAsset* defaultNormal;
TextureAsset* defaultRoughnessMetallic;
};
| 26.180412 | 72 | 0.653672 | [
"geometry",
"model"
] |
8708bc3f271513f1af18e2dcf035767258980f1e | 7,915 | hpp | C++ | include/la/matrix_engine.hpp | abakfja/linear-algebra | 024974bc537f3c1aa86bd011e5821e6e4465aa49 | [
"MIT"
] | null | null | null | include/la/matrix_engine.hpp | abakfja/linear-algebra | 024974bc537f3c1aa86bd011e5821e6e4465aa49 | [
"MIT"
] | null | null | null | include/la/matrix_engine.hpp | abakfja/linear-algebra | 024974bc537f3c1aa86bd011e5821e6e4465aa49 | [
"MIT"
] | null | null | null | //
// Copyright (c) 2021 Kannav Mehta
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef LA_MATRIX_ENGINE_H
#define LA_MATRIX_ENGINE_H
#include <cstddef>
#include <array>
#include <vector>
#include <tuple>
#include <cassert>
#include <la/detail/helper.hpp>
#include <la/traits/storage_traits.hpp>
#include <la/traits/engine_traits.hpp>
namespace la {
template<typename T, std::size_t R, std::size_t C>
struct fixed_matrix_engine {
static_assert(std::is_object<T>::value,
"A matrix's value_type must be an object type (not a "
"reference type or void)");
using array_type = std::array<T, R * C>;
using storage_traits_type = storage_traits<array_type>;
using size_type = typename storage_traits_type::size_type;
using size_tuple = std::pair<size_type, size_type>;
using difference_type = typename storage_traits_type::difference_type;
using value_type = typename storage_traits_type::value_type;
using reference = typename storage_traits_type::reference;
using const_reference = typename storage_traits_type::const_reference;
using pointer = typename storage_traits_type::pointer;
using const_pointer = typename storage_traits_type::const_pointer;
using iterator = typename storage_traits_type::iterator;
using const_iterator = typename storage_traits_type::const_iterator;
using reverse_iterator = typename storage_traits_type::reverse_iterator;
using const_reverse_iterator = typename storage_traits_type::const_reverse_iterator;
using storage_tag = typename storage_traits_type::storage_tag;
using self_type = fixed_matrix_engine<T, R, C>;
using transpose_type = fixed_matrix_engine<T, C, R>;
~fixed_matrix_engine() noexcept = default;
fixed_matrix_engine() = default;
fixed_matrix_engine(const self_type &other) = default;
fixed_matrix_engine(self_type &&other) noexcept = default;
template<class Engine2>
constexpr fixed_matrix_engine(const Engine2 &other): m_data() {
detail::check_engine_size(other, rows(), cols());
detail::copy_matrix_engine(*this, other);
}
fixed_matrix_engine(std::initializer_list<std::initializer_list<value_type>> lst) {
detail::check_init_list(lst, rows(), cols());
detail::copy_matrix_engine(*this, lst);
}
// for compatibility
constexpr explicit fixed_matrix_engine(size_type r, size_type c) : m_data() {
if (r != m_rows || c != m_cols) {
throw std::runtime_error("Cannot reshape a fixed vector, use dynamic vector");
}
}
constexpr fixed_matrix_engine &operator=(fixed_matrix_engine &&) noexcept = default;
constexpr fixed_matrix_engine &operator=(fixed_matrix_engine const &) = default;
constexpr reference operator[](size_type idx) {
return m_data[idx]; // no bound checking here
}
constexpr const_reference operator[](size_type idx) const {
return m_data[idx]; // no bound checking here
}
constexpr reference operator()(size_type r, size_type c) {
return m_data[c + r * cols()];
}
constexpr const_reference operator()(size_type r, size_type c) const {
return m_data[c + r * cols()];
}
[[nodiscard]] constexpr size_type rows() const {
return m_rows;
}
[[nodiscard]] constexpr size_type cols() const {
return m_cols;
}
[[nodiscard]] constexpr size_type data_size() noexcept {
return m_data.size();
}
[[nodiscard]] constexpr bool empty() const {
return m_data.empty();
}
static constexpr size_type m_rows{R};
static constexpr size_type m_cols{C};
array_type m_data;
};
template<typename T>
struct dynamic_matrix_engine {
static_assert(std::is_object<T>::value,
"A vector's value_type must be an object type (not a "
"reference type or void)");
using scalar_type = T;
using array_type = std::vector<scalar_type>;
using storage_traits_type = storage_traits<array_type>;
using size_type = typename storage_traits_type::size_type;
using size_tuple = std::pair<size_type, size_type>;
using difference_type = typename storage_traits_type::difference_type;
using value_type = typename storage_traits_type::value_type;
using reference = typename storage_traits_type::reference;
using const_reference = typename storage_traits_type::const_reference;
using pointer = typename storage_traits_type::pointer;
using const_pointer = typename storage_traits_type::const_pointer;
using iterator = typename storage_traits_type::iterator;
using const_iterator = typename storage_traits_type::const_iterator;
using reverse_iterator = typename storage_traits_type::reverse_iterator;
using const_reverse_iterator = typename storage_traits_type::const_reverse_iterator;
using storage_tag = typename storage_traits_type::storage_tag;
using self_type = dynamic_matrix_engine<T>;
using transpose_type = self_type;
~dynamic_matrix_engine() noexcept = default;
dynamic_matrix_engine() = default;
dynamic_matrix_engine(const self_type &other) = default;
dynamic_matrix_engine(self_type &&other) noexcept = default;
template<class Engine2>
constexpr
dynamic_matrix_engine(const Engine2 &other) : m_rows{other.rows()}, m_cols{other.cols()},
m_data(m_rows * m_cols) {
detail::copy_matrix_engine(*this, other);
}
template<typename U>
dynamic_matrix_engine(const std::initializer_list<std::initializer_list<U>> &lst) :
m_rows{lst.size()},
m_cols{lst.begin()->size()},
m_data(m_rows * m_cols) {
detail::check_init_list(lst);
detail::copy_matrix_engine(*this, lst);
}
explicit dynamic_matrix_engine(size_type r, size_type c) : m_rows{r}, m_cols{c},
m_data(r * c) {}
constexpr dynamic_matrix_engine &operator=(dynamic_matrix_engine &&) noexcept = default;
constexpr dynamic_matrix_engine &operator=(dynamic_matrix_engine const &) = default;
template<typename Engine2>
dynamic_matrix_engine &operator=(const Engine2 &other) {
detail::check_engine_size(other, rows(), cols());
detail::copy_matrix_engine(*this, other);
return *this;
}
size_type rows() const noexcept {
return m_rows;
}
size_type cols() const noexcept {
return m_cols;
}
reference operator[](size_type idx) noexcept {
return m_data[idx]; // no bound checking here
}
const_reference operator[](size_type idx) const noexcept {
return m_data[idx]; // no bound checking here
}
reference operator()(size_type r, size_type c) noexcept {
return m_data[c + r * cols()];
}
const_reference operator()(size_type r, size_type c) const noexcept {
return m_data[c + r * cols()];
}
[[nodiscard]] size_tuple size() const noexcept {
return std::make_pair(m_rows, m_cols);
}
[[nodiscard]] size_type data_size() const noexcept {
return m_data.size();
}
void resize(size_type r, size_type c) {
m_data.resize(r * c);
m_rows = r;
m_cols = c;
}
[[nodiscard]] constexpr bool empty() const {
return m_data.empty();
}
size_type m_rows;
size_type m_cols;
array_type m_data;
};
namespace detail {
template<typename T, std::size_t R, std::size_t C>
struct is_static<fixed_matrix_engine<T, R, C>> : std::true_type {
};
template<typename T>
struct is_dynamic<dynamic_matrix_engine<T>> : std::true_type {
};
} // detail
} // namespace la
#endif // LA_MATRIX_ENGINE_H | 30.917969 | 93 | 0.683007 | [
"object",
"vector"
] |
871400f5ab1fde94bb1d2213912c9819ba5f8f08 | 1,829 | cpp | C++ | Backtracking/N-Queens-2-52-brute.cpp | devangi2000/Data-Structures-Algorithms-Handbook | ce0f00de89af5da7f986e65089402dc6908a09b5 | [
"MIT"
] | 38 | 2021-10-14T09:36:53.000Z | 2022-01-27T02:36:19.000Z | Backtracking/N-Queens-2-52-brute.cpp | devangi2000/Data-Structures-Algorithms-Handbook | ce0f00de89af5da7f986e65089402dc6908a09b5 | [
"MIT"
] | null | null | null | Backtracking/N-Queens-2-52-brute.cpp | devangi2000/Data-Structures-Algorithms-Handbook | ce0f00de89af5da7f986e65089402dc6908a09b5 | [
"MIT"
] | 4 | 2021-12-06T15:47:12.000Z | 2022-02-04T04:25:00.000Z | // The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
// Given an integer n, return the number of distinct solutions to the n-queens puzzle.
// Example 1:
// Input: n = 4
// Output: 2
// Explanation: There are two distinct solutions to the 4-queens puzzle as shown.
// Example 2:
// Input: n = 1
// Output: 1
class Solution {
public:
bool isSafe(int row, int col, vector<string> board, int n){
// checking upper diagonal
int temprow = row;
int tempcol = col;
while(row >= 0 && col >= 0){
if(board[row][col] == 'Q') return false;
row--;
col--;
}
col = tempcol;
row = temprow;
while(col >= 0){
if(board[row][col] == 'Q') return false;
col--;
}
col = tempcol;
row = temprow;
while(row<n && col>=0){
if(board[row][col] == 'Q') return false;
row++;
col--;
}
return true;
}
void solve(int col, vector<string> &board, vector<vector<string>> &ans, int n){
if(col == n){
ans.push_back(board);
return;
}
for(int row=0; row<n; row++){
if(isSafe(row, col, board, n)){
board[row][col] = 'Q';
solve(col+1, board, ans, n);
board[row][col] = '.';
}
}
}
int totalNQueens(int n) {
vector<vector<string>> ans;
vector<string> board(n);
string s(n, '.');
for(int i=0; i<n; i++){
board[i] = s;
}
solve(0, board, ans, n);
return ans.size();
}
};
| 26.507246 | 124 | 0.4538 | [
"vector"
] |
871a0b94dca1a11f48e3de3add1f1df8fad6ff7b | 1,992 | cpp | C++ | CppSTL/Chapter1/io/append_to_file.cpp | SebastianTirado/Cpp-Learning-Archive | fb83379d0cc3f9b2390cef00119464ec946753f4 | [
"MIT"
] | 19 | 2019-09-15T12:23:51.000Z | 2020-06-18T08:31:26.000Z | CppSTL/Chapter1/io/append_to_file.cpp | SebastianTirado/Cpp-Learning-Archive | fb83379d0cc3f9b2390cef00119464ec946753f4 | [
"MIT"
] | 15 | 2021-12-07T06:46:03.000Z | 2022-01-31T07:55:32.000Z | CppSTL/Chapter1/io/append_to_file.cpp | SebastianTirado/Cpp-Learning-Archive | fb83379d0cc3f9b2390cef00119464ec946753f4 | [
"MIT"
] | 13 | 2019-06-29T02:58:27.000Z | 2020-05-07T08:52:22.000Z | #include <iostream>
#include <fstream>
#include <vector>
using namespace std;
#define FAIL 1
#define SUCCESS 0
#define FILENAME "/home/diman91/Documents/Cpp-STL-Examples/Firewall.txt"
bool cat_file(const char* filename)
{
char ch;
ifstream in_file;
in_file.open(filename);
if(!in_file.is_open()) {
cout << "File was not opened! ERROR! Aborting...\n";
return FAIL;
}
do {
in_file.get(ch);
if(!in_file.eof() && ( in_file.fail() || in_file.bad() )) {
cout << "ERROR! Aborting ...";
in_file.close();
return FAIL;
}
if(!in_file.eof())
cout << ch;
} while(!in_file.eof());
in_file.clear(); // needed for eof and fail
in_file.close();
if(!in_file.good()){
cout << "ERROR! ... in closing file ... Aborting ...";
return FAIL;
}
return SUCCESS;
}
// Function to write contents to a file
bool write_file(const char* filename, const char* content)
{
ofstream out_file;
out_file.open(filename, ios::out | ios::app);
if(!out_file.is_open()) {
cout << "File was not opened! ERROR! Aborting...\n";
return FAIL;
}
out_file << content << endl;
out_file.close();
if(!out_file.good()){
cout << "ERROR! Aborting ...";
return FAIL;
}
return SUCCESS;
}
int main()
{
vector<const char*> commands = {"iptables -A INPUT -p tcp -s 192.168.16.0/16 --dport 24 -j ACCEPT",
"iptables -A INPUT -p tcp -s 192.168.17.0/16 --dport 24 -j ACCEPT",
"iptables -A INPUT -p tcp -s 192.168.16.0/16 --dport 21 -j ACCEPT",
"iptables -A INPUT -p tcp -s 192.168.17.0/16 --dport 21 -j ACCEPT",
"iptables -A INPUT -j DROP"
};
vector<const char*>::iterator itr = commands.begin();
while(itr != commands.end()) {
//cout << *itr << endl;
write_file(FILENAME, *itr);
itr++;
}
cat_file(FILENAME);
return 0;
}
| 21.652174 | 101 | 0.558735 | [
"vector"
] |
871a761b1a33ae53173596d17fec8a2173e200ac | 3,018 | cpp | C++ | tests/validation/reference/ReductionOperation.cpp | hemantbits/ComputeLibrary | 389335e60b96926761ee64974e1330194a3b69fb | [
"MIT"
] | 2 | 2020-07-25T20:27:14.000Z | 2021-08-22T17:20:59.000Z | tests/validation/reference/ReductionOperation.cpp | hemantbits/ComputeLibrary | 389335e60b96926761ee64974e1330194a3b69fb | [
"MIT"
] | null | null | null | tests/validation/reference/ReductionOperation.cpp | hemantbits/ComputeLibrary | 389335e60b96926761ee64974e1330194a3b69fb | [
"MIT"
] | 1 | 2021-08-22T17:09:09.000Z | 2021-08-22T17:09:09.000Z | /*
* Copyright (c) 2017-2018 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.
*/
#include "ReductionOperation.h"
#include "tests/validation/Helpers.h"
#include <algorithm>
#include <cmath>
namespace arm_compute
{
namespace test
{
namespace validation
{
namespace reference
{
namespace
{
template <typename T>
struct square
{
T operator()(const T &lhs, const T &rhs) const
{
return (lhs + rhs * rhs);
}
};
template <typename T>
T reduce_operation(T *ptr, int reduce_elements, ReductionOperation op)
{
switch(op)
{
case ReductionOperation::SUM_SQUARE:
return std::accumulate(ptr, ptr + reduce_elements, static_cast<T>(0), square<T>());
default:
ARM_COMPUTE_ERROR("Unsupported reduction operation");
}
}
} // namespace
template <typename T>
SimpleTensor<T> reduction_operation(const SimpleTensor<T> &src, const TensorShape &dst_shape, unsigned int axis, ReductionOperation op)
{
// Create reference
SimpleTensor<T> dst{ dst_shape, src.data_type() };
// Compute reference
const int reduce_elems = src.shape()[axis];
const int upper_dims = src.shape().total_size_upper(axis + 1);
for(int du = 0; du < upper_dims; ++du)
{
if(axis == 0)
{
const T *src_row_ptr = src.data() + du * reduce_elems;
dst[du] = reduce_operation(src_row_ptr, reduce_elems, op);
}
else
{
ARM_COMPUTE_ERROR("Unsupported reduction axis");
}
}
return dst;
}
template SimpleTensor<float> reduction_operation(const SimpleTensor<float> &src, const TensorShape &dst_shape, unsigned int axis, ReductionOperation op);
template SimpleTensor<half> reduction_operation(const SimpleTensor<half> &src, const TensorShape &dst_shape, unsigned int axis, ReductionOperation op);
} // namespace reference
} // namespace validation
} // namespace test
} // namespace arm_compute
| 31.768421 | 153 | 0.70444 | [
"shape"
] |
26b5bd84c59a08fab14308c813bc67db61aba791 | 14,604 | cpp | C++ | ConsoleApplication2/overlay.cpp | freshertm/WinOpenGLLiveWallpaper | 924793d3b1cdad3216d7bac6fc93e5a85e20f87f | [
"MIT"
] | 2 | 2020-06-22T13:28:41.000Z | 2021-11-17T01:29:25.000Z | ConsoleApplication2/overlay.cpp | freshertm/WinOpenGLLiveWallpaper | 924793d3b1cdad3216d7bac6fc93e5a85e20f87f | [
"MIT"
] | null | null | null | ConsoleApplication2/overlay.cpp | freshertm/WinOpenGLLiveWallpaper | 924793d3b1cdad3216d7bac6fc93e5a85e20f87f | [
"MIT"
] | null | null | null | #include "overlay.h"
#include <stdexcept>
DXOverlay::DXOverlay(UINT32 width, UINT32 height, DWORD keyColor) : width(width), height(height), keyColor(keyColor)
{
// Initialize DirectDraw
if( InitDDraw() < 0 )
throw std::logic_error("Failed to initialize DirectDraw.");
// Check overlay support
if( CheckOverlaySupport() < 0 )
throw std::logic_error("Your hardware doesn't support the overlay surfaces we are trying to create.");
// Create the overlay surface
if( CreateOverlay() < 0 )
throw std::logic_error("Failed to create the overlay surface.");
// Show the overlay surface
if( ShowOverlay() < 0 )
throw std::logic_error("Failed to show the overlay surface");
}
DXOverlay::~DXOverlay()
{
DestroyOverlay();
UninitDDraw();
}
int DXOverlay::InitDDraw()
{
HRESULT hr;
// Create the DirectDraw object
hr = DirectDrawCreateEx(NULL, (VOID**)&ddraw, IID_IDirectDraw7, NULL);
if (FAILED(hr))
goto ErrorOut;
// Since we aren't going fullscreen we should not use exclusive mode
// For NORMAL cooperative level we don't need to provide a HWND.
hr = ddraw->SetCooperativeLevel(NULL, DDSCL_NORMAL);
if (FAILED(hr))
goto ErrorOut;
// Obtain a reference for the primary surface that represents
// the entire screen.
hr = CreatePrimarySurface();
if (FAILED(hr))
goto ErrorOut;
return 0;
ErrorOut:
UninitDDraw();
return -1;
}
void DXOverlay::UninitDDraw()
{
if (primary)
{
primary->Release();
primary = 0;
}
if (ddraw)
{
ddraw->Release();
ddraw = 0;
}
}
HRESULT DXOverlay::CreatePrimarySurface()
{
DDSURFACEDESC2 ddsd;
HRESULT hr;
if (!ddraw)
return E_FAIL;
// Create the primary surface which is the entire screen.
// In this demo we will not draw on this surface directly,
// but we still need it for reference.
memset(&ddsd, 0, sizeof(ddsd));
ddsd.dwSize = sizeof(ddsd);
ddsd.dwFlags = DDSD_CAPS;
ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
hr = ddraw->CreateSurface(&ddsd, &primary, 0);
return hr;
}
int DXOverlay::CheckOverlaySupport()
{
DDCAPS capsDrv;
HRESULT hr;
// Get driver capabilities to determine overlay support.
memset(&capsDrv, 0, sizeof(capsDrv));
capsDrv.dwSize = sizeof(capsDrv);
hr = ddraw->GetCaps(&capsDrv, 0);
if (FAILED(hr))
return -1;
// Does the driver support overlays in the current mode?
if (!(capsDrv.dwCaps & DDCAPS_OVERLAY))
return -2;
// Make sure support for stretching is available
if (!(capsDrv.dwCaps & DDCAPS_OVERLAYSTRETCH))
return -3;
// Make sure the hardware is able to stretch the overlay
// to the size of the screen. The stretch capabilities may
// vary with resolution and refresh rate. Only the x axis
// must be verified. The stretch factor is multiplied with
// 1000 to keep three decimal digits
UINT stretch = GetSystemMetrics(SM_CXSCREEN) * 1000 / width;
if (capsDrv.dwMinOverlayStretch > stretch)
return -4;
if (capsDrv.dwMaxOverlayStretch < stretch)
return -5;
// Check alignment restrictions (only x axis needed)
// Src rect (0, 0, IMG_W, IMG_H)
// Dst rect (0, 0, screenW, screenH)
// if( capsDrv.dwCaps & DDCAPS_ALIGNBOUNDARYDEST && 0 % capsDrv.dwAlignBoundaryDest != 0 )
// if( capsDrv.dwCaps & DDCAPS_ALIGNBOUNDARYSRC && 0 % capsDrv.dwAlignBoundarySrc != 0 )
if (capsDrv.dwCaps & DDCAPS_ALIGNSIZEDEST && GetSystemMetrics(SM_CXSCREEN) % capsDrv.dwAlignSizeDest != 0)
return -6;
if (capsDrv.dwCaps & DDCAPS_ALIGNSIZESRC && width % capsDrv.dwAlignSizeSrc != 0)
return -7;
// Does the overlay hardware support dest color-keying? We will
// use destination color keying to mask out the background
// behind the windows.
if (!(capsDrv.dwCKeyCaps & DDCKEYCAPS_DESTOVERLAY))
return -8;
return 0;
}
int DXOverlay::CreateOverlay()
{
if (ddraw == 0 || primary == 0)
return -1;
// It is not possible to enumerate supported pixel format so we
// will have to just try one by one until we find a working one
// These are the formats we support. For overlay surfaces we
// should support at least these formats. Some video accelerators
// don't support YUV formats, but others support only YUV formats.
DDPIXELFORMAT formats[] =
{ { sizeof(DDPIXELFORMAT), DDPF_RGB, 0, 16, 0xF800, 0x07e0, 0x001F, 0 }, // 16-bit RGB 5:6:5
{ sizeof(DDPIXELFORMAT), DDPF_RGB, 0, 16, 0x7C00, 0x03e0, 0x001F, 0 }, // 16-bit RGB 5:5:5
{ sizeof(DDPIXELFORMAT), DDPF_FOURCC, MAKEFOURCC('U', 'Y', 'V', 'Y'), 0, 0, 0, 0, 0 }, // UYVY
{ sizeof(DDPIXELFORMAT), DDPF_FOURCC, MAKEFOURCC('Y', 'U', 'Y', '2'), 0, 0, 0, 0, 0 } }; // YUY2
// The surface must be placed in video memory as the video
// accelerator must have the memory at hand when it sends the
// signal to the monitor.
// We will try to create it with one backbuffer for smoother
// animations, this will normally work unless we are asking for
// too much memory.
DDSURFACEDESC2 ddsdOverlay;
memset(&ddsdOverlay, 0, sizeof(ddsdOverlay));
ddsdOverlay.dwSize = sizeof(ddsdOverlay);
ddsdOverlay.ddsCaps.dwCaps = DDSCAPS_OVERLAY | DDSCAPS_FLIP | DDSCAPS_COMPLEX | DDSCAPS_VIDEOMEMORY;
ddsdOverlay.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_BACKBUFFERCOUNT | DDSD_PIXELFORMAT;
ddsdOverlay.dwWidth = width;
ddsdOverlay.dwHeight = height;
ddsdOverlay.dwBackBufferCount = 1;
HRESULT hr;
for (int n = 0; n < 4; n++)
{
ddsdOverlay.ddpfPixelFormat = formats[n];
hr = ddraw->CreateSurface(&ddsdOverlay, &overlay, 0);
if (SUCCEEDED(hr))
break;
}
// We weren't able to create a flippable overlay surface
// we could try to create a non-flippable surface, but I'll
// leave that as an exercise to the interested developer
if (FAILED(hr))
return -1;
// Get a pointer to the backbuffer that we will later draw to
DDSCAPS2 caps;
caps.dwCaps = DDSCAPS_BACKBUFFER;
caps.dwCaps2 = caps.dwCaps3 = caps.dwCaps4 = 0;
hr = overlay->GetAttachedSurface(&caps, &backbuffer);
if (FAILED(hr))
return -1;
// Initialize the front buffer
/* hr = CopyImageToSurface(overlay);
if (FAILED(hr))
return -1;*/
return 0;
}
int DXOverlay::CopyImageToSurface(const UINT8 *pimage)
{
DDSURFACEDESC2 ddsd;
HRESULT hr;
const DWORD *image = (const DWORD*)pimage;
// Lock the surface so that we can write to it
memset(&ddsd, 0, sizeof(ddsd));
ddsd.dwSize = sizeof(ddsd);
hr = backbuffer->Lock(0, &ddsd, DDLOCK_SURFACEMEMORYPTR | DDLOCK_WAIT, 0);
if (FAILED(hr))
return -1;
// Check surface format
if (ddsd.ddpfPixelFormat.dwFlags == DDPF_FOURCC)
{
// The surface is in one of the YUV formats we specified.
// These YUV formats have three components Y, U and V, where
// Y is sampled for every pixel and U and V is sampled only
// every second pixel, thus every pair of pixels share U and V
// values.
int w = ddsd.dwWidth;
int h = ddsd.dwHeight;
int pitch = ddsd.lPitch;
BYTE *dest = (BYTE*)ddsd.lpSurface;
for (int y = 0; y < h; y++)
{
// We'll update two pixels at a time
for (int x = 0; x < w; x += 2)
{
// NOTE: The values used for the conversion between
// RGB and YUV are probably not the exact values, but
// for this sample app they are good enough
// We are using pure grayscale image which would allow
// for plenty of optimizations but I'll show the complete
// formula for those interested in showing color images
DWORD clr = image[x + y*width];
BYTE r = GetRValue(clr);
BYTE g = GetGValue(clr);
BYTE b = GetBValue(clr);
if (r > 0)
{
printf("qweqw");
}
// red green blue
BYTE Y0 = (BYTE)( 0.29*r + 0.59*g + 0.14*b);
BYTE U0 = (BYTE)(128.0 - 0.14*r - 0.29*g + 0.43*b);
BYTE V0 = (BYTE)(128.0 + 0.36*r - 0.29*g - 0.07*b);
clr = image[x + 1 + y*width];
r = GetRValue(clr);
g = GetGValue(clr);
b = GetBValue(clr);
BYTE Y1 = (BYTE)( 0.29*r + 0.57*g + 0.14*b);
BYTE U1 = (BYTE)(128.0 - 0.14*r - 0.29*g + 0.43*b);
BYTE V1 = (BYTE)(128.0 + 0.36*r - 0.29*g - 0.07*b);
if (ddsd.ddpfPixelFormat.dwFourCC == MAKEFOURCC('Y', 'U', 'Y', '2'))
{
*dest++ = Y0;
*dest++ = (U0 + U1) / 2;
*dest++ = Y1;
*dest++ = (V0 + V1) / 2;
}
else
{
*dest++ = (U0 + U1) / 2;
*dest++ = Y0;
*dest++ = (V0 + V1) / 2;
*dest++ = Y1;
}
}
dest += (pitch - w * 2);
}
}
else
{
// The surface is in normal 16bit RGB format
int w = ddsd.dwWidth;
int h = ddsd.dwHeight;
int pitch = ddsd.lPitch / 2;
WORD *dest = (WORD*)ddsd.lpSurface;
WORD pixel;
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
// Simple gray scale value
DWORD clr = image[x + y*width];
BYTE r = GetRValue(clr);
BYTE g = GetGValue(clr);
BYTE b = GetBValue(clr);
// red green blue
if (ddsd.ddpfPixelFormat.dwGBitMask == 0x03e0)
// RGB 5:5:5
pixel = WORD(((r >> 3) << 10) + ((g >> 3) << 5) + (b >> 3));
else
// RGB 5:6:5
pixel = WORD(((r >> 3) << 11) + ((g >> 2) << 5) + (b >> 3));
*dest++ = pixel;
}
dest += (pitch - w);
}
}
backbuffer->Unlock(0);
return 0;
}
void DXOverlay::DestroyOverlay()
{
// Release the backbuffer
if (backbuffer != 0)
{
backbuffer->Release();
backbuffer = 0;
}
// Release the overlay surface
if (overlay)
{
// Use UpdateOverlay() with the DDOVER_HIDE flag
// to remove an overlay from the display.
overlay->UpdateOverlay(0, primary, 0, DDOVER_HIDE, 0);
overlay->Release();
overlay = 0;
}
}
DWORD DXOverlay::GetPixelValue(IDirectDrawSurface7 *surface, COLORREF rgb)
{
COLORREF oldPixel;
HDC dc;
DWORD pixel = CLR_INVALID;
DDSURFACEDESC2 ddsd;
HRESULT hr;
if (rgb == CLR_INVALID)
return CLR_INVALID;
// We will use GDI to put a pixel of the wanted color on the
// surface as GDI automatically transforms the color into one
// that exists in the palette.
hr = surface->GetDC(&dc);
if (SUCCEEDED(hr))
{
// Save current pixel value
oldPixel = GetPixel(dc, 0, 0);
// Set our value
SetPixel(dc, 0, 0, rgb);
surface->ReleaseDC(dc);
}
// Now lock the surface so we can read back the converted color
ddsd.dwSize = sizeof(ddsd);
hr = surface->Lock(0, &ddsd, DDLOCK_SURFACEMEMORYPTR | DDLOCK_WAIT, 0);
if (SUCCEEDED(hr))
{
// Read a DWORD from the surface
pixel = *(DWORD *)ddsd.lpSurface;
// Mask out bits that are not part of the pixel
if (ddsd.ddpfPixelFormat.dwRGBBitCount < 32)
pixel &= (1 << ddsd.ddpfPixelFormat.dwRGBBitCount) - 1;
surface->Unlock(NULL);
}
// Restore the original pixel
hr = surface->GetDC(&dc);
if (SUCCEEDED(hr))
{
SetPixel(dc, 0, 0, oldPixel);
surface->ReleaseDC(dc);
}
return pixel;
}
int DXOverlay::ShowOverlay()
{
if (ddraw == 0 || primary == 0 || overlay == 0)
return -1;
// Destination rectangle is the full screen
RECT rcDst;
rcDst.left = 0;
rcDst.top = 0;
rcDst.right = GetSystemMetrics(SM_CXSCREEN);
rcDst.bottom = GetSystemMetrics(SM_CYSCREEN);
// Source rectangle is the full overlay surface
RECT rcSrc;
rcSrc.left = 0;
rcSrc.top = 0;
rcSrc.right = width;
rcSrc.bottom = height;
// Set the destination color key. Note that the value
// must have the same pixelformat as the destination surface
DDOVERLAYFX fx;
memset(&fx, 0, sizeof(fx));
fx.dwSize = sizeof(fx);
fx.dckDestColorkey.dwColorSpaceLowValue = GetPixelValue(primary, keyColor);
fx.dckDestColorkey.dwColorSpaceHighValue = GetPixelValue(primary, keyColor);
DWORD flags = DDOVER_SHOW | DDOVER_DDFX | DDOVER_KEYDESTOVERRIDE;
// Show the overlay surface
HRESULT hr;
hr = overlay->UpdateOverlay(&rcSrc, primary, &rcDst, flags, &fx);
if (FAILED(hr))
return -1;
return 0;
}
int DXOverlay::UpdateOverlay(const UINT8 *pimage)
{
// Make sure we haven't lost the surface
if (primary == 0 || primary->IsLost() != DD_OK)
{
// Lost the primary surface, which normally means another
// application stole it from us. If we loose the primary
// surface we might as well assume we've lost the overlay
// surface too. At this moment we could try to recreate
// the surface, or tell the application to try again later.
return -1;
}
// Copy the image to the backbuffer
CopyImageToSurface(pimage);
// Show the backbuffer
HRESULT hr = overlay->Flip(NULL, DDFLIP_WAIT);
if (FAILED(hr))
return -1;
return 0;
} | 31.61039 | 117 | 0.556902 | [
"object"
] |
26bc2e707f2c78e79e70f74524e6bdd0c335fbed | 2,888 | cpp | C++ | Tudat/External/SpiceInterface/spiceRotationalEphemeris.cpp | sebranchett/tudat | 24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44 | [
"BSD-3-Clause"
] | null | null | null | Tudat/External/SpiceInterface/spiceRotationalEphemeris.cpp | sebranchett/tudat | 24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44 | [
"BSD-3-Clause"
] | null | null | null | Tudat/External/SpiceInterface/spiceRotationalEphemeris.cpp | sebranchett/tudat | 24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2010-2019, Delft University of Technology
* All rigths reserved
*
* This file is part of the Tudat. Redistribution and use in source and
* binary forms, with or without modification, are permitted exclusively
* under the terms of the Modified BSD license. You should have received
* a copy of the license with this file. If not, please or visit:
* http://tudat.tudelft.nl/LICENSE.
*/
#include <stdexcept>
#include "Tudat/Astrodynamics/BasicAstrodynamics/physicalConstants.h"
#include "Tudat/Astrodynamics/BasicAstrodynamics/timeConversions.h"
#include "Tudat/External/SpiceInterface/spiceInterface.h"
#include "Tudat/External/SpiceInterface/spiceRotationalEphemeris.h"
namespace tudat
{
namespace ephemerides
{
//! Function to calculate the rotation quaternion from target frame to original frame.
Eigen::Quaterniond SpiceRotationalEphemeris::getRotationToBaseFrame(
const double secondsSinceEpoch )
{
// Get rotational quaternion from spice wrapper function
return spice_interface::computeRotationQuaternionBetweenFrames(
targetFrameOrientation_, baseFrameOrientation_, secondsSinceEpoch + referenceDayOffSet_ );
}
//! Function to calculate the derivative of the rotation matrix from target frame to original
//! frame.
Eigen::Matrix3d SpiceRotationalEphemeris::getDerivativeOfRotationToBaseFrame(
const double secondsSinceEpoch )
{
// Get rotation matrix derivative from spice wrapper function
return spice_interface::computeRotationMatrixDerivativeBetweenFrames(
targetFrameOrientation_, baseFrameOrientation_, secondsSinceEpoch + referenceDayOffSet_ );
}
//! Function to calculate the full rotational state at given time
void SpiceRotationalEphemeris::getFullRotationalQuantitiesToTargetFrame(
Eigen::Quaterniond& currentRotationToLocalFrame,
Eigen::Matrix3d& currentRotationToLocalFrameDerivative,
Eigen::Vector3d& currentAngularVelocityVectorInGlobalFrame,
const double secondsSinceEpoch)
{
// Calculate rotation (and its time derivative) directly from spice.
std::pair< Eigen::Quaterniond, Eigen::Matrix3d > fullRotation =
spice_interface::computeRotationQuaternionAndRotationMatrixDerivativeBetweenFrames(
baseFrameOrientation_, targetFrameOrientation_, secondsSinceEpoch + referenceDayOffSet_ );
currentRotationToLocalFrame = fullRotation.first;
currentRotationToLocalFrameDerivative = fullRotation.second;
// Calculate angular velocity vector.
currentAngularVelocityVectorInGlobalFrame = getRotationalVelocityVectorInBaseFrameFromMatrices(
Eigen::Matrix3d( currentRotationToLocalFrame ), currentRotationToLocalFrameDerivative.transpose( ) );
}
} // namespace ephemerides
} // namespace tudat
| 43.757576 | 118 | 0.762465 | [
"vector"
] |
26c06e5b73ad884704a80a115117e827bd25bb58 | 6,081 | cpp | C++ | day5/src/p1.cpp | aeden/aoc2021 | ca0e796169d5ca86f899e72d0754914445aacfb0 | [
"MIT"
] | 1 | 2021-12-01T13:08:14.000Z | 2021-12-01T13:08:14.000Z | day5/src/p1.cpp | aeden/aoc2021 | ca0e796169d5ca86f899e72d0754914445aacfb0 | [
"MIT"
] | null | null | null | day5/src/p1.cpp | aeden/aoc2021 | ca0e796169d5ca86f899e72d0754914445aacfb0 | [
"MIT"
] | 1 | 2021-12-07T21:12:57.000Z | 2021-12-07T21:12:57.000Z | #include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <map>
#include "lib/io.h"
using namespace std;
const string SEGMENT_DELIMITER = " -> ";
const string COORDINATE_DELIMITER = ",";
class Coordinates {
public:
int x;
int y;
Coordinates() {
x = 0;
y = 0;
}
Coordinates(int x, int y) {
this->x = x;
this->y = y;
}
bool operator== ( Coordinates const& rhs) const {
return rhs.x == x && rhs.y == y;
}
bool operator< ( const Coordinates& rhs) const {
return (y < rhs.y || (y == rhs.y && x < rhs.x));
}
string to_string() {
return std::to_string(x) + COORDINATE_DELIMITER + std::to_string(y);
}
};
void print_coordinates(vector<Coordinates> coordinates) {
for (int i = 0; i < coordinates.size(); i++) {
cout << coordinates[i].to_string() << endl;
}
}
class Line {
public:
Coordinates start;
Coordinates end;
Line(string data) {
int pos;
pos = data.find(SEGMENT_DELIMITER);
string start_str = data.substr(0, pos);
data.erase(0, pos + SEGMENT_DELIMITER.length());
string end_str = data;
pos = start_str.find(COORDINATE_DELIMITER);
string start_x = start_str.substr(0, pos);
start_str.erase(0, pos + COORDINATE_DELIMITER.length());
string start_y = start_str;
start = Coordinates(stoi(start_x), stoi(start_y));
pos = end_str.find(COORDINATE_DELIMITER);
string end_x = end_str.substr(0, pos);
end_str.erase(0, pos + COORDINATE_DELIMITER.length());
string end_y = end_str;
end = Coordinates(stoi(end_x), stoi(end_y));
}
bool is_diagonal() {
return !(start.x == end.x || start.y == end.y);
}
// Returns all points covered by the line.
vector<Coordinates> points() {
vector <Coordinates> points;
if (start.x == end.x) {
int x = start.x;
if (start.y > end.y) {
for (int i = end.y; i < start.y + 1; i++) {
points.push_back(Coordinates(x, i));
}
} else {
for (int i = start.y; i < end.y + 1; i++) {
points.push_back(Coordinates(x, i));
}
}
} else {
int y = start.y;
if (start.x > end.x) {
for (int i = end.x; i < start.x + 1; i++) {
points.push_back(Coordinates(i, y));
}
} else {
for (int i = start.x; i < end.x + 1; i++) {
points.push_back(Coordinates(i, y));
}
}
}
return points;
}
string to_string() {
return start.to_string() + SEGMENT_DELIMITER + end.to_string();
}
};
class Diagram {
public:
vector<Line> lines;
Coordinates top_left;
Coordinates bottom_right;
Diagram(vector<string> data) {
for (int i = 0; i < data.size(); i++) {
Line line = Line(data[i]);
lines.push_back(line);
vector<Coordinates> points = line.points();
for (int j = 0; j < points.size(); j++) {
if (points[j].x < top_left.x) top_left.x = points[j].x;
if (points[j].x > bottom_right.x) bottom_right.x = points[j].x;
if (points[j].y < top_left.x) top_left.y = points[j].y;
if (points[j].y > bottom_right.y) bottom_right.y = points[j].y;
}
}
}
vector<Coordinates> covered_points() {
vector<Coordinates> covered_points;
for (int i = 0; i < lines.size(); i++) {
if (lines[i].is_diagonal()) continue;
vector<Coordinates> points = lines[i].points();
for (int j = 0; j < points.size(); j++) {
covered_points.push_back(points[j]);
}
}
return covered_points;
}
int covered_count(Coordinates point) {
int count = 0;
vector<Coordinates> points = covered_points();
for (int i = 0; i < points.size(); i++) {
if (points[i] == point) {
count += 1;
}
}
return count;
}
vector<Coordinates> overlapping_points() {
map<Coordinates,int> overlap;
vector<Coordinates> overlapping;
vector<Coordinates> points = covered_points();
for (vector<Coordinates>::iterator it = points.begin(); it != points.end(); it++) {
Coordinates p = *it;
if (overlap.find(p) == overlap.end()) {
overlap[p] = 1;
} else {
overlap[p] = overlap[p] + 1;
}
}
for (map<Coordinates,int>::iterator iter = overlap.begin(); iter != overlap.end(); iter++) {
Coordinates p = iter->first;
int count = iter->second;
if (count >= 2) {
overlapping.push_back(p);
}
}
return overlapping;
}
string to_string() {
stringbuf buffer;
ostream os (&buffer);
for (int i = top_left.y; i <= bottom_right.y; i++) {
for (int j = top_left.x; j <= bottom_right.x; j++) {
Coordinates current = Coordinates(j, i);
int count = covered_count(current);
if (count == 0) {
os << ".";
} else {
os << count;
}
}
os << endl;
}
return buffer.str();
}
string to_data_string() {
stringbuf buffer;
ostream os (&buffer);
for (int i = 0; i < lines.size(); i++) {
os << lines[i].to_string();
if (i < lines.size() - 1) os << endl;
}
return buffer.str();
}
};
int main (int argc, char** argv) {
string filename;
if (argc != 2) {
cout << "Usage: " << argv[0] << " datafile" << endl;
return 1;
} else {
filename = argv[1];
}
vector<string> data = read_data(filename);
cout << "Loaded " << data.size() << " data lines" << endl;
Diagram diagram = Diagram(data);
cout << "Top left: " << diagram.top_left.to_string() << endl;
cout << "Bottom right: " << diagram.bottom_right.to_string() << endl;
cout << "Number of overlapping points: " << diagram.overlapping_points().size() << endl;
cout << "Done" << endl;
}
| 26.211207 | 98 | 0.534123 | [
"vector"
] |
26c1e76867b731b104c308f7159d056ab1aa82f3 | 8,791 | cpp | C++ | src/DisciplesGL/MidRenderer.cpp | Verokster/DisciplesGL | dfe07126835f14282bc9894f739cce07b33c8f78 | [
"MIT"
] | 38 | 2019-03-04T11:05:45.000Z | 2022-01-27T23:53:36.000Z | src/DisciplesGL/MidRenderer.cpp | Verokster/DisciplesGL | dfe07126835f14282bc9894f739cce07b33c8f78 | [
"MIT"
] | 5 | 2019-07-08T15:58:21.000Z | 2021-02-23T22:25:23.000Z | src/DisciplesGL/MidRenderer.cpp | Verokster/DisciplesGL | dfe07126835f14282bc9894f739cce07b33c8f78 | [
"MIT"
] | 1 | 2021-02-28T13:23:57.000Z | 2021-02-28T13:23:57.000Z | /*
MIT License
Copyright (c) 2020 Oleksiy Ryabchun
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 "StdAfx.h"
#include "MidRenderer.h"
#include "OpenDraw.h"
#include "Config.h"
#include "Main.h"
#include "Resource.h"
MidRenderer::MidRenderer(OpenDraw* ddraw)
: OGLRenderer(ddraw)
{
}
VOID MidRenderer::Begin()
{
config.zoom.glallow = TRUE;
PostMessage(this->ddraw->hWnd, config.msgMenu, NULL, NULL);
this->isTrueColor = config.mode->bpp != 16 || config.bpp32Hooked;
this->maxTexSize = GetPow2(config.mode->width > config.mode->height ? config.mode->width : config.mode->height);
FLOAT texWidth = config.mode->width == this->maxTexSize ? 1.0f : (FLOAT)config.mode->width / this->maxTexSize;
FLOAT texHeight = config.mode->height == this->maxTexSize ? 1.0f : (FLOAT)config.mode->height / this->maxTexSize;
this->texSize = (this->maxTexSize & 0xFFFF) | (this->maxTexSize << 16);
this->shaders = {
new ShaderGroup(GLSL_VER_1_10, IDR_LINEAR_VERTEX, IDR_LINEAR_FRAGMENT, SHADER_DOUBLE | SHADER_LEVELS),
new ShaderGroup(GLSL_VER_1_10, IDR_HERMITE_VERTEX, IDR_HERMITE_FRAGMENT, SHADER_TEXSIZE | SHADER_DOUBLE | SHADER_LEVELS),
new ShaderGroup(GLSL_VER_1_10, IDR_CUBIC_VERTEX, IDR_CUBIC_FRAGMENT, SHADER_TEXSIZE | SHADER_DOUBLE | SHADER_LEVELS),
new ShaderGroup(GLSL_VER_1_10, IDR_LANCZOS_VERTEX, IDR_LANCZOS_FRAGMENT, SHADER_TEXSIZE | SHADER_DOUBLE | SHADER_LEVELS)
};
{
GLGenBuffers(1, &this->bufferName);
{
GLBindBuffer(GL_ARRAY_BUFFER, this->bufferName);
{
FLOAT bf[4][8] = {
{ 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f },
{ (FLOAT)config.mode->width, 0.0f, 0.0f, 1.0f, texWidth, 0.0f, texWidth, 0.0f },
{ (FLOAT)config.mode->width, (FLOAT)config.mode->height, 0.0f, 1.0f, texWidth, texHeight, texWidth, texHeight },
{ 0.0f, (FLOAT)config.mode->height, 0.0f, 1.0f, 0.0f, texHeight, 0.0f, texHeight }
};
MemoryCopy(this->buffer, bf, sizeof(this->buffer));
{
FLOAT mvp[4][4] = {
{ FLOAT(2.0f / config.mode->width), 0.0f, 0.0f, 0.0f },
{ 0.0f, FLOAT(-2.0f / config.mode->height), 0.0f, 0.0f },
{ 0.0f, 0.0f, 2.0f, 0.0f },
{ -1.0f, 1.0f, -1.0f, 1.0f }
};
for (DWORD i = 0; i < 4; ++i)
{
FLOAT* vector = &this->buffer[i][0];
for (DWORD j = 0; j < 4; ++j)
{
FLOAT sum = 0.0f;
for (DWORD v = 0; v < 4; ++v)
sum += mvp[v][j] * vector[v];
vector[j] = sum;
}
}
GLBufferData(GL_ARRAY_BUFFER, sizeof(this->buffer) << 1, NULL, GL_STATIC_DRAW);
GLBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(this->buffer), this->buffer);
GLBufferSubData(GL_ARRAY_BUFFER, sizeof(this->buffer), sizeof(this->buffer), this->buffer);
}
{
GLEnableVertexAttribArray(0);
GLVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 32, (GLvoid*)0);
GLEnableVertexAttribArray(1);
GLVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 32, (GLvoid*)16);
}
GLGenTextures(config.background.allowed ? 2 : 1, this->textureId);
{
if (config.background.allowed)
{
GLActiveTexture(GL_TEXTURE1);
GLBindTexParameter(this->textureId[1], GL_LINEAR);
DWORD length = config.mode->width * config.mode->height * sizeof(DWORD);
VOID* tempBuffer = MemoryAlloc(length);
{
MemoryZero(tempBuffer, length);
Main::LoadBack(tempBuffer, config.mode->width, config.mode->height);
GLTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, this->maxTexSize, this->maxTexSize, GL_NONE, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
GLTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, config.mode->width, config.mode->height, GL_RGBA, GL_UNSIGNED_BYTE, tempBuffer);
}
MemoryFree(tempBuffer);
}
{
GLActiveTexture(GL_TEXTURE0);
GLBindTexParameter(this->textureId[0], GL_LINEAR);
if (this->isTrueColor)
GLTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, this->maxTexSize, this->maxTexSize, GL_NONE, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
else
GLTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, this->maxTexSize, this->maxTexSize, GL_NONE, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, NULL);
}
this->pixelBuffer = new PixelBuffer(this->isTrueColor);
{
GLClearColor(0.0f, 0.0f, 0.0f, 1.0f);
this->program = NULL;
this->borderStatus = FALSE;
this->backStatus = FALSE;
this->zoomStatus = FALSE;
this->zoomSize = { 0, 0 };
this->isVSync = config.image.vSync;
if (WGLSwapInterval)
WGLSwapInterval(this->isVSync);
}
}
}
}
}
}
VOID MidRenderer::End()
{
{
{
{
{
delete this->pixelBuffer;
}
GLDeleteTextures(config.background.allowed ? 2 : 1, this->textureId);
}
GLBindBuffer(GL_ARRAY_BUFFER, NULL);
}
GLDeleteBuffers(1, &this->bufferName);
}
GLUseProgram(NULL);
ShaderGroup** shader = (ShaderGroup**)&this->shaders;
DWORD count = sizeof(this->shaders) / sizeof(ShaderGroup*);
do
delete *shader++;
while (--count);
}
BOOL MidRenderer::RenderInner(BOOL ready, BOOL force, StateBufferAligned** lpStateBuffer)
{
StateBufferAligned* stateBuffer = *lpStateBuffer;
Size frameSize = stateBuffer->size;
BOOL stateChanged = this->borderStatus != stateBuffer->borders || this->backStatus != stateBuffer->isBack || this->zoomStatus != stateBuffer->isZoomed;
FilterState state = this->ddraw->filterState;
if (pixelBuffer->Update(lpStateBuffer, ready) || state.flags || stateChanged)
{
if (this->isVSync != config.image.vSync)
{
this->isVSync = config.image.vSync;
if (WGLSwapInterval)
WGLSwapInterval(this->isVSync);
}
if (this->CheckView(TRUE))
GLViewport(this->ddraw->viewport.rectangle.x, this->ddraw->viewport.rectangle.y + this->ddraw->viewport.offset, this->ddraw->viewport.rectangle.width, this->ddraw->viewport.rectangle.height);
if (state.interpolation > InterpolateLinear && frameSize.width == this->ddraw->viewport.rectangle.width && frameSize.height == this->ddraw->viewport.rectangle.height)
{
state.interpolation = InterpolateLinear;
if (this->program != this->shaders.linear)
state.flags = TRUE;
}
if (force || state.flags || stateChanged)
{
switch (state.interpolation)
{
case InterpolateHermite:
this->program = this->shaders.hermite;
break;
case InterpolateCubic:
this->program = this->shaders.cubic;
break;
case InterpolateLanczos:
this->program = this->shaders.lanczos;
break;
default:
this->program = this->shaders.linear;
break;
}
this->program->Use(this->texSize, stateBuffer->isBack);
if (state.flags || this->backStatus != stateBuffer->isBack)
{
this->ddraw->filterState.flags = FALSE;
if (stateBuffer->isBack)
{
GLActiveTexture(GL_TEXTURE1);
GLBindTexFilter(this->textureId[1], state.interpolation != InterpolateNearest ? GL_LINEAR : GL_NEAREST);
}
GLActiveTexture(GL_TEXTURE0);
GLBindTexFilter(this->textureId[0], state.interpolation == InterpolateLinear || state.interpolation == InterpolateHermite ? GL_LINEAR : GL_NEAREST);
}
this->borderStatus = stateBuffer->borders;
this->backStatus = stateBuffer->isBack;
this->zoomStatus = stateBuffer->isZoomed;
}
if (stateBuffer->isZoomed)
{
if (this->zoomSize.width != frameSize.width || this->zoomSize.height != frameSize.height)
{
this->zoomSize = frameSize;
FLOAT tw = (FLOAT)frameSize.width / this->maxTexSize;
FLOAT th = (FLOAT)frameSize.height / this->maxTexSize;
this->buffer[1][4] = tw;
this->buffer[2][4] = tw;
this->buffer[2][5] = th;
this->buffer[3][5] = th;
GLBufferSubData(GL_ARRAY_BUFFER, 5 * 8 * sizeof(FLOAT), 3 * 8 * sizeof(FLOAT), &this->buffer[1]);
}
GLDrawArrays(GL_TRIANGLE_FAN, 4, 4);
}
else
GLDrawArrays(GL_TRIANGLE_FAN, 0, 4);
return TRUE;
}
return FALSE;
}
| 33.048872 | 194 | 0.679672 | [
"vector"
] |
26c30c843b63ca3989b183031be751ecf1458429 | 33,995 | hpp | C++ | c++/include/serial/impl/stltypes.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 31 | 2016-12-09T04:56:59.000Z | 2021-12-31T17:19:10.000Z | c++/include/serial/impl/stltypes.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 6 | 2017-03-10T17:25:13.000Z | 2021-09-22T15:49:49.000Z | c++/include/serial/impl/stltypes.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 20 | 2015-01-04T02:15:17.000Z | 2021-12-03T02:31:43.000Z | #ifndef STLTYPES__HPP
#define STLTYPES__HPP
/* $Id: stltypes.hpp 354590 2012-02-28 16:30:13Z ucko $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Eugene Vasilchenko
*
* File Description:
* !!! PUT YOUR DESCRIPTION HERE !!!
*/
#include <corelib/ncbistd.hpp>
#include <corelib/ncbiobj.hpp>
#include <corelib/ncbiutil.hpp>
#include <set>
#include <map>
#include <list>
#include <vector>
#include <memory>
#include <serial/serialutil.hpp>
#include <serial/impl/stltypesimpl.hpp>
#include <serial/impl/ptrinfo.hpp>
#include <serial/objistr.hpp>
/** @addtogroup TypeInfoCPP
*
* @{
*/
BEGIN_NCBI_SCOPE
template<typename Data>
class CStlClassInfo_auto_ptr
{
public:
typedef Data TDataType;
typedef auto_ptr<TDataType> TObjectType;
static TTypeInfo GetTypeInfo(TTypeInfo dataType)
{
return CStlClassInfoUtil::Get_auto_ptr(dataType, &CreateTypeInfo);
}
static CTypeInfo* CreateTypeInfo(TTypeInfo dataType)
{
CPointerTypeInfo* typeInfo =
new CPointerTypeInfo(sizeof(TObjectType), dataType);
typeInfo->SetFunctions(&GetData, &SetData);
return typeInfo;
}
protected:
static TObjectPtr GetData(const CPointerTypeInfo* /*objectType*/,
TObjectPtr objectPtr)
{
return CTypeConverter<TObjectType>::Get(objectPtr).get();
}
static void SetData(const CPointerTypeInfo* /*objectType*/,
TObjectPtr objectPtr,
TObjectPtr dataPtr)
{
CTypeConverter<TObjectType>::Get(objectPtr).
reset(&CTypeConverter<TDataType>::Get(dataPtr));
}
};
template<typename Data>
class CRefTypeInfo
{
public:
typedef Data TDataType;
typedef CRef<TDataType> TObjectType;
static TTypeInfo GetTypeInfo(TTypeInfo dataType)
{
return CStlClassInfoUtil::Get_CRef(dataType, &CreateTypeInfo);
}
static CTypeInfo* CreateTypeInfo(TTypeInfo dataType)
{
CPointerTypeInfo* typeInfo =
new CPointerTypeInfo(sizeof(TObjectType), dataType);
typeInfo->SetFunctions(&GetData, &SetData);
return typeInfo;
}
protected:
static TObjectPtr GetData(const CPointerTypeInfo* /*objectType*/,
TObjectPtr objectPtr)
{
return CTypeConverter<TObjectType>::Get(objectPtr).GetPointer();
}
static void SetData(const CPointerTypeInfo* /*objectType*/,
TObjectPtr objectPtr,
TObjectPtr dataPtr)
{
CTypeConverter<TObjectType>::Get(objectPtr).
Reset(&CTypeConverter<TDataType>::Get(dataPtr));
}
};
template<typename Data>
class CConstRefTypeInfo
{
public:
typedef Data TDataType;
typedef CConstRef<TDataType> TObjectType;
static TTypeInfo GetTypeInfo(TTypeInfo dataType)
{
return CStlClassInfoUtil::Get_CConstRef(dataType, &CreateTypeInfo);
}
static CTypeInfo* CreateTypeInfo(TTypeInfo dataType)
{
CPointerTypeInfo* typeInfo =
new CPointerTypeInfo(sizeof(TObjectType), dataType);
typeInfo->SetFunctions(&GetData, &SetData);
return typeInfo;
}
protected:
static TObjectPtr GetData(const CPointerTypeInfo* /*objectType*/,
TObjectPtr objectPtr)
{
// Bleh. Need to return a void* rather than a const Data*
return const_cast<TDataType*>
(CTypeConverter<TObjectType>::Get(objectPtr).GetPointer());
}
static void SetData(const CPointerTypeInfo* /*objectType*/,
TObjectPtr objectPtr,
TObjectPtr dataPtr)
{
CTypeConverter<TObjectType>::Get(objectPtr).
Reset(&CTypeConverter<TDataType>::Get(dataPtr));
}
};
template<typename Data>
class CAutoPtrTypeInfo
{
public:
typedef Data TDataType;
typedef AutoPtr<TDataType> TObjectType;
static TTypeInfo GetTypeInfo(TTypeInfo dataType)
{
return CStlClassInfoUtil::Get_AutoPtr(dataType, &CreateTypeInfo);
}
static CTypeInfo* CreateTypeInfo(TTypeInfo dataType)
{
CPointerTypeInfo* typeInfo =
new CPointerTypeInfo(sizeof(TObjectType), dataType);
typeInfo->SetFunctions(&GetData, &SetData);
return typeInfo;
}
protected:
static TObjectPtr GetData(const CPointerTypeInfo* /*objectType*/,
TObjectPtr objectPtr)
{
return CTypeConverter<TObjectType>::Get(objectPtr).get();
}
static void SetData(const CPointerTypeInfo* /*objectType*/,
TObjectPtr objectPtr,
TObjectPtr dataPtr)
{
CTypeConverter<TObjectType>::Get(objectPtr).
reset(&CTypeConverter<TDataType>::Get(dataPtr));
}
};
template<class Container>
class CStlClassInfoFunctions
{
public:
typedef Container TObjectType;
typedef typename TObjectType::value_type TElementType;
static TObjectType& Get(TObjectPtr objectPtr)
{
return CTypeConverter<TObjectType>::Get(objectPtr);
}
static const TObjectType& Get(TConstObjectPtr objectPtr)
{
return CTypeConverter<TObjectType>::Get(objectPtr);
}
static TObjectPtr CreateContainer(TTypeInfo /*objectType*/,
CObjectMemoryPool* /*memoryPool*/)
{
return new TObjectType();
}
static bool IsDefault(TConstObjectPtr objectPtr)
{
return Get(objectPtr).empty();
}
static void SetDefault(TObjectPtr objectPtr)
{
Get(objectPtr).clear();
}
static TObjectPtr AddElement(const CContainerTypeInfo* containerType,
TObjectPtr containerPtr,
TConstObjectPtr elementPtr,
ESerialRecursionMode how = eRecursive)
{
TObjectType& container = Get(containerPtr);
#if defined(_RWSTD_VER) && !defined(_RWSTD_STRICT_ANSI)
container.allocation_size(container.size());
#endif
if ( elementPtr ) {
TElementType elm;
containerType->GetElementType()->Assign
(&elm, &CTypeConverter<TElementType>::Get(elementPtr), how);
container.push_back(elm);
}
else {
container.push_back(TElementType());
}
return &container.back();
}
static TObjectPtr AddElementIn(const CContainerTypeInfo* containerType,
TObjectPtr containerPtr,
CObjectIStream& in)
{
TObjectType& container = Get(containerPtr);
#if defined(_RWSTD_VER) && !defined(_RWSTD_STRICT_ANSI)
container.allocation_size(container.size());
#endif
container.push_back(TElementType());
containerType->GetElementType()->ReadData(in, &container.back());
if (in.GetDiscardCurrObject()) {
container.pop_back();
in.SetDiscardCurrObject(false);
return 0;
}
return &container.back();
}
static size_t GetElementCount(const CContainerTypeInfo*,
TConstObjectPtr containerPtr)
{
const TObjectType& container = Get(containerPtr);
return container.size();
}
static void SetMemFunctions(CStlOneArgTemplate* info)
{
info->SetMemFunctions(&CreateContainer, &IsDefault, &SetDefault);
}
static void SetAddElementFunctions(CStlOneArgTemplate* info)
{
info->SetAddElementFunctions(&AddElement, &AddElementIn);
}
static void SetCountFunctions(CStlOneArgTemplate* info)
{
info->SetCountFunctions(&GetElementCount);
}
};
template<class Container>
class CStlClassInfoFunctions_vec : public CStlClassInfoFunctions<Container>
{
typedef CStlClassInfoFunctions<Container> CParent;
public:
typedef typename CParent::TObjectType TObjectType;
typedef typename TObjectType::value_type TElementType;
static void ReserveElements(const CContainerTypeInfo*,
TObjectPtr containerPtr, size_t count)
{
TObjectType& container = CParent::Get(containerPtr);
container.reserve(count);
}
static void SetCountFunctions(CStlOneArgTemplate* info)
{
info->SetCountFunctions(&CParent::GetElementCount,
&ReserveElements);
}
};
template<class Container>
class CStlClassInfoFunctions_set : public CStlClassInfoFunctions<Container>
{
typedef CStlClassInfoFunctions<Container> CParent;
public:
typedef typename CParent::TObjectType TObjectType;
typedef typename TObjectType::value_type TElementType;
static void InsertElement(TObjectPtr containerPtr,
const TElementType& element)
{
TObjectType& container = CParent::Get(containerPtr);
#if defined(_RWSTD_VER) && !defined(_RWSTD_STRICT_ANSI)
container.allocation_size(container.size());
#endif
if ( !container.insert(element).second )
CStlClassInfoUtil::ThrowDuplicateElementError();
}
static TObjectPtr AddElement(const CContainerTypeInfo* /*containerType*/,
TObjectPtr containerPtr,
TConstObjectPtr elementPtr,
ESerialRecursionMode /* how = eRecursive */)
{
InsertElement(containerPtr,
CTypeConverter<TElementType>::Get(elementPtr));
return 0;
}
// this structure is required to initialize pointers by null before reading
struct SInitializer
{
SInitializer() : data() {}
TElementType data;
};
static TObjectPtr AddElementIn(const CContainerTypeInfo* containerType,
TObjectPtr containerPtr,
CObjectIStream& in)
{
SInitializer data;
containerType->GetElementType()->ReadData(in, &data.data);
InsertElement(containerPtr, data.data);
return 0;
}
static void SetAddElementFunctions(CStlOneArgTemplate* info)
{
info->SetAddElementFunctions(&AddElement, &AddElementIn);
}
};
template<class Container>
class CStlClassInfoFunctions_multiset :
public CStlClassInfoFunctions<Container>
{
typedef CStlClassInfoFunctions<Container> CParent;
public:
typedef typename CParent::TObjectType TObjectType;
typedef typename TObjectType::value_type TElementType;
static void InsertElement(TObjectPtr containerPtr,
const TElementType& element)
{
TObjectType& container = CParent::Get(containerPtr);
#if defined(_RWSTD_VER) && !defined(_RWSTD_STRICT_ANSI)
container.allocation_size(container.size());
#endif
container.insert(element);
}
static TObjectPtr AddElement(const CContainerTypeInfo* /*containerType*/,
TObjectPtr containerPtr,
TConstObjectPtr elementPtr,
ESerialRecursionMode how = eRecursive)
{
InsertElement(containerPtr,
CTypeConverter<TElementType>::Get(elementPtr));
return 0;
}
// this structure is required to initialize pointers by null before reading
struct SInitializer
{
SInitializer() : data() {}
TElementType data;
};
static TObjectPtr AddElementIn(const CContainerTypeInfo* containerType,
TObjectPtr containerPtr,
CObjectIStream& in)
{
SInitializer data;
containerType->GetElementType()->ReadData(in, &data.data);
InsertElement(containerPtr, data.data);
return 0;
}
static void SetAddElementFunctions(CStlOneArgTemplate* info)
{
info->SetAddElementFunctions(&AddElement, &AddElementIn);
}
};
template<class Container, class StlIterator,
typename ContainerPtr, typename ElementRef,
class TypeInfoIterator>
class CStlClassInfoFunctionsIBase :
public CStlClassInfoFunctions<Container>
{
public:
typedef StlIterator TStlIterator;
typedef TypeInfoIterator TTypeInfoIterator;
typedef typename TTypeInfoIterator::TObjectPtr TObjectPtr;
typedef CStlClassInfoFunctions<Container> CParent;
static TStlIterator& It(TTypeInfoIterator& iter)
{
if ( sizeof(TStlIterator) <= sizeof(iter.m_IteratorData) ) {
void* data = &iter.m_IteratorData;
return *static_cast<TStlIterator*>(data);
}
else {
void* data = iter.m_IteratorData;
return *static_cast<TStlIterator*>(data);
}
}
static const TStlIterator& It(const TTypeInfoIterator& iter)
{
if ( sizeof(TStlIterator) <= sizeof(iter.m_IteratorData) ) {
const void* data = &iter.m_IteratorData;
return *static_cast<const TStlIterator*>(data);
}
else {
const void* data = iter.m_IteratorData;
return *static_cast<const TStlIterator*>(data);
}
}
static bool InitIterator(TTypeInfoIterator& iter)
{
TStlIterator stl_iter
= CParent::Get(iter.GetContainerPtr()).begin();
if ( sizeof(TStlIterator) <= sizeof(iter.m_IteratorData) ) {
void* data = &iter.m_IteratorData;
new (data) TStlIterator(stl_iter);
}
else {
iter.m_IteratorData = new TStlIterator(stl_iter);
}
return stl_iter != CParent::Get(iter.GetContainerPtr()).end();
}
static void ReleaseIterator(TTypeInfoIterator& iter)
{
if ( sizeof(TStlIterator) <= sizeof(iter.m_IteratorData) ) {
void* data = &iter.m_IteratorData;
static_cast<TStlIterator*>(data)->~StlIterator();
}
else {
void* data = iter.m_IteratorData;
delete static_cast<TStlIterator*>(data);
}
}
static void CopyIterator(TTypeInfoIterator& dst,
const TTypeInfoIterator& src)
{
It(dst) = It(src);
}
static bool NextElement(TTypeInfoIterator& iter)
{
return ++It(iter) != CParent::Get(iter.GetContainerPtr()).end();
}
static TObjectPtr GetElementPtr(const TTypeInfoIterator& iter)
{
ElementRef e= *It(iter);
return &e;
}
};
template<class Container>
class CStlClassInfoFunctionsCI :
public CStlClassInfoFunctionsIBase<Container, typename Container::const_iterator, const Container*, const typename Container::value_type&, CContainerTypeInfo::CConstIterator>
{
typedef CStlClassInfoFunctionsIBase<Container, typename Container::const_iterator, const Container*, const typename Container::value_type&, CContainerTypeInfo::CConstIterator> CParent;
public:
static void SetIteratorFunctions(CStlOneArgTemplate* info)
{
info->SetConstIteratorFunctions(&CParent::InitIterator,
&CParent::ReleaseIterator,
&CParent::CopyIterator,
&CParent::NextElement,
&CParent::GetElementPtr);
}
};
template<class Container>
class CStlClassInfoFunctionsI :
public CStlClassInfoFunctionsIBase<Container, typename Container::iterator, Container*, typename Container::value_type&, CContainerTypeInfo::CIterator>
{
typedef CStlClassInfoFunctionsIBase<Container, typename Container::iterator, Container*, typename Container::value_type&, CContainerTypeInfo::CIterator> CParent;
public:
typedef typename CParent::TStlIterator TStlIterator;
typedef typename CParent::TTypeInfoIterator TTypeInfoIterator;
typedef typename CParent::TObjectPtr TObjectPtr;
static bool EraseElement(TTypeInfoIterator& iter)
{
TStlIterator& it = CParent::It(iter);
Container* c = static_cast<Container*>(iter.GetContainerPtr());
it = c->erase(it);
return it != c->end();
}
static void EraseAllElements(TTypeInfoIterator& iter)
{
Container* c = static_cast<Container*>(iter.GetContainerPtr());
c->erase(CParent::It(iter), c->end());
}
static void SetIteratorFunctions(CStlOneArgTemplate* info)
{
info->SetIteratorFunctions(&CParent::InitIterator,
&CParent::ReleaseIterator,
&CParent::CopyIterator,
&CParent::NextElement,
&CParent::GetElementPtr,
&EraseElement, &EraseAllElements);
}
};
template<class Container>
class CStlClassInfoFunctionsI_set :
public CStlClassInfoFunctionsIBase<Container, typename Container::iterator, Container*, typename Container::value_type&, CContainerTypeInfo::CIterator>
{
typedef CStlClassInfoFunctionsIBase<Container, typename Container::iterator, Container*, typename Container::value_type&, CContainerTypeInfo::CIterator> CParent;
public:
typedef typename CParent::TStlIterator TStlIterator;
typedef typename CParent::TTypeInfoIterator TTypeInfoIterator;
typedef typename CParent::TObjectPtr TObjectPtr;
static TObjectPtr GetElementPtr(const TTypeInfoIterator& /*data*/)
{
CStlClassInfoUtil::CannotGetElementOfSet();
return 0;
}
static bool EraseElement(TTypeInfoIterator& iter)
{
TStlIterator& it = CParent::It(iter);
Container* c = static_cast<Container*>(iter.GetContainerPtr());
TStlIterator erase = it++;
c->erase(erase);
return it != c->end();
}
static void EraseAllElements(TTypeInfoIterator& iter)
{
Container* c = static_cast<Container*>(iter.GetContainerPtr());
c->erase(CParent::It(iter), c->end());
}
static void SetIteratorFunctions(CStlOneArgTemplate* info)
{
info->SetIteratorFunctions(&CParent::InitIterator,
&CParent::ReleaseIterator,
&CParent::CopyIterator,
&CParent::NextElement,
&GetElementPtr,
&EraseElement, &EraseAllElements);
}
};
template<typename Data>
class CStlClassInfo_list
{
public:
typedef list<Data> TObjectType;
static TTypeInfo GetTypeInfo(TTypeInfo elementType)
{
return CStlClassInfoUtil::Get_list(elementType, &CreateTypeInfo);
}
static CTypeInfo* CreateTypeInfo(TTypeInfo elementType)
{
CStlOneArgTemplate* info =
new CStlOneArgTemplate(sizeof(TObjectType), elementType,
false);
SetFunctions(info);
return info;
}
static CTypeInfo* CreateTypeInfo(TTypeInfo elementType, const string& name)
{
CStlOneArgTemplate* info =
new CStlOneArgTemplate(sizeof(TObjectType), elementType,
false, name);
SetFunctions(info);
return info;
}
static TTypeInfo GetSetTypeInfo(TTypeInfo elementType)
{
return CStlClassInfoUtil::GetSet_list(elementType,
&CreateSetTypeInfo);
}
static CTypeInfo* CreateSetTypeInfo(TTypeInfo elementType)
{
CStlOneArgTemplate* info =
new CStlOneArgTemplate(sizeof(TObjectType), elementType,
true);
SetFunctions(info);
return info;
}
static CTypeInfo* CreateSetTypeInfo(TTypeInfo elementType, const string& name)
{
CStlOneArgTemplate* info =
new CStlOneArgTemplate(sizeof(TObjectType), elementType,
true, name);
SetFunctions(info);
return info;
}
static void SetFunctions(CStlOneArgTemplate* info)
{
CStlClassInfoFunctions<TObjectType>::SetMemFunctions(info);
CStlClassInfoFunctions<TObjectType>::SetAddElementFunctions(info);
CStlClassInfoFunctions<TObjectType>::SetCountFunctions(info);
CStlClassInfoFunctionsCI<TObjectType>::SetIteratorFunctions(info);
CStlClassInfoFunctionsI<TObjectType>::SetIteratorFunctions(info);
}
};
template<typename Data>
class CStlClassInfo_vector
{
public:
typedef vector<Data> TObjectType;
static TTypeInfo GetTypeInfo(TTypeInfo elementType)
{
return CStlClassInfoUtil::Get_vector(elementType,
&CreateTypeInfo);
}
static CTypeInfo* CreateTypeInfo(TTypeInfo elementType)
{
CStlOneArgTemplate* info =
new CStlOneArgTemplate(sizeof(TObjectType), elementType,
false);
SetFunctions(info);
return info;
}
static TTypeInfo GetSetTypeInfo(TTypeInfo elementType)
{
return CStlClassInfoUtil::GetSet_vector(elementType,
&CreateSetTypeInfo);
}
static CTypeInfo* CreateSetTypeInfo(TTypeInfo elementType)
{
CStlOneArgTemplate* info =
new CStlOneArgTemplate(sizeof(TObjectType), elementType,
true);
SetFunctions(info);
return info;
}
static void SetFunctions(CStlOneArgTemplate* info)
{
CStlClassInfoFunctions<TObjectType>::SetMemFunctions(info);
CStlClassInfoFunctions<TObjectType>::SetAddElementFunctions(info);
CStlClassInfoFunctions_vec<TObjectType>::SetCountFunctions(info);
CStlClassInfoFunctionsCI<TObjectType>::SetIteratorFunctions(info);
CStlClassInfoFunctionsI<TObjectType>::SetIteratorFunctions(info);
}
};
template<typename Data>
class CStlClassInfo_set
{
public:
typedef set<Data> TObjectType;
static TTypeInfo GetTypeInfo(TTypeInfo elementType)
{
return CStlClassInfoUtil::Get_set(elementType, &CreateTypeInfo);
}
static CTypeInfo* CreateTypeInfo(TTypeInfo elementType)
{
CStlOneArgTemplate* info =
new CStlOneArgTemplate(sizeof(TObjectType), elementType,
true);
CStlClassInfoFunctions<TObjectType>::SetMemFunctions(info);
CStlClassInfoFunctions_set<TObjectType>::SetAddElementFunctions(info);
CStlClassInfoFunctions<TObjectType>::SetCountFunctions(info);
CStlClassInfoFunctionsCI<TObjectType>::SetIteratorFunctions(info);
CStlClassInfoFunctionsI_set<TObjectType>::SetIteratorFunctions(info);
return info;
}
};
template<typename Data>
class CStlClassInfo_multiset
{
public:
typedef multiset<Data> TObjectType;
static TTypeInfo GetTypeInfo(TTypeInfo elementType)
{
return CStlClassInfoUtil::Get_multiset(elementType,
&CreateTypeInfo);
}
static CTypeInfo* CreateTypeInfo(TTypeInfo elementType)
{
CStlOneArgTemplate* info =
new CStlOneArgTemplate(sizeof(TObjectType), elementType,
true);
CStlClassInfoFunctions<TObjectType>::SetMemFunctions(info);
CStlClassInfoFunctions_multiset<TObjectType>::SetAddElementFunctions(info);
CStlClassInfoFunctions<TObjectType>::SetCountFunctions(info);
CStlClassInfoFunctionsCI<TObjectType>::SetIteratorFunctions(info);
CStlClassInfoFunctionsI_set<TObjectType>::SetIteratorFunctions(info);
return info;
}
};
template<typename Data, typename Comparator>
class CStlClassInfo_set2
{
public:
typedef set<Data, Comparator> TObjectType;
static TTypeInfo GetTypeInfo(TTypeInfo elementType)
{
static TTypeInfo info = 0;
return CStlClassInfoUtil::GetInfo(info,
elementType,
&CreateTypeInfo);
}
static CTypeInfo* CreateTypeInfo(TTypeInfo elementType)
{
CStlOneArgTemplate* info =
new CStlOneArgTemplate(sizeof(TObjectType), elementType,
true);
CStlClassInfoFunctions<TObjectType>::SetMemFunctions(info);
CStlClassInfoFunctions_set<TObjectType>::SetAddElementFunctions(info);
CStlClassInfoFunctions<TObjectType>::SetCountFunctions(info);
CStlClassInfoFunctionsCI<TObjectType>::SetIteratorFunctions(info);
CStlClassInfoFunctionsI_set<TObjectType>::SetIteratorFunctions(info);
return info;
}
};
template<typename Data, typename Comparator>
class CStlClassInfo_multiset2
{
public:
typedef multiset<Data, Comparator> TObjectType;
static TTypeInfo GetTypeInfo(TTypeInfo elementType)
{
static TTypeInfo info = 0;
return CStlClassInfoUtil::GetInfo(info,
elementType,
&CreateTypeInfo);
}
static CTypeInfo* CreateTypeInfo(TTypeInfo elementType)
{
CStlOneArgTemplate* info =
new CStlOneArgTemplate(sizeof(TObjectType), elementType,
true);
CStlClassInfoFunctions<TObjectType>::SetMemFunctions(info);
CStlClassInfoFunctions_multiset<TObjectType>::SetAddElementFunctions(info);
CStlClassInfoFunctions<TObjectType>::SetCountFunctions(info);
CStlClassInfoFunctionsCI<TObjectType>::SetIteratorFunctions(info);
CStlClassInfoFunctionsI_set<TObjectType>::SetIteratorFunctions(info);
return info;
}
};
template<typename Key, typename Value>
class CStlClassInfo_map
{
public:
typedef map<Key, Value> TObjectType;
typedef typename TObjectType::value_type TElementType;
static TTypeInfo GetTypeInfo(TTypeInfo keyType, TTypeInfo valueType)
{
return CStlClassInfoUtil::Get_map(keyType, valueType,
&CreateTypeInfo);
}
static CTypeInfo* CreateTypeInfo(TTypeInfo keyType, TTypeInfo valueType)
{
TElementType* dummy = 0;
CStlTwoArgsTemplate* info =
new CStlTwoArgsTemplate
(sizeof(TObjectType),
keyType,
reinterpret_cast<TPointerOffsetType>(&dummy->first),
valueType,
reinterpret_cast<TPointerOffsetType>(&dummy->second),
true);
CStlClassInfoFunctions<TObjectType>::SetMemFunctions(info);
CStlClassInfoFunctions_set<TObjectType>::SetAddElementFunctions(info);
CStlClassInfoFunctions<TObjectType>::SetCountFunctions(info);
CStlClassInfoFunctionsCI<TObjectType>::SetIteratorFunctions(info);
CStlClassInfoFunctionsI_set<TObjectType>::SetIteratorFunctions(info);
return info;
}
};
template<typename Key, typename Value>
class CStlClassInfo_multimap
{
public:
typedef multimap<Key, Value> TObjectType;
typedef typename TObjectType::value_type TElementType;
static TTypeInfo GetTypeInfo(TTypeInfo keyType, TTypeInfo valueType)
{
return CStlClassInfoUtil::Get_multimap(keyType, valueType,
&CreateTypeInfo);
}
static CTypeInfo* CreateTypeInfo(TTypeInfo keyType, TTypeInfo valueType)
{
TElementType* dummy = 0;
CStlTwoArgsTemplate* info =
new CStlTwoArgsTemplate
(sizeof(TObjectType),
keyType,
reinterpret_cast<TPointerOffsetType>(&dummy->first),
valueType,
reinterpret_cast<TPointerOffsetType>(&dummy->second),
true);
CStlClassInfoFunctions<TObjectType>::SetMemFunctions(info);
CStlClassInfoFunctions_multiset<TObjectType>::SetAddElementFunctions(info);
CStlClassInfoFunctions<TObjectType>::SetCountFunctions(info);
CStlClassInfoFunctionsCI<TObjectType>::SetIteratorFunctions(info);
CStlClassInfoFunctionsI_set<TObjectType>::SetIteratorFunctions(info);
return info;
}
};
template<typename Key, typename Value, typename Comparator>
class CStlClassInfo_map3
{
public:
typedef map<Key, Value, Comparator> TObjectType;
typedef typename TObjectType::value_type TElementType;
static TTypeInfo GetTypeInfo(TTypeInfo keyType, TTypeInfo valueType)
{
static TTypeInfo info = 0;
return CStlClassInfoUtil::GetInfo(info,
keyType, valueType,
&CreateTypeInfo);
}
static CTypeInfo* CreateTypeInfo(TTypeInfo keyType, TTypeInfo valueType)
{
TElementType* dummy = 0;
CStlTwoArgsTemplate* info =
new CStlTwoArgsTemplate
(sizeof(TObjectType),
keyType,
reinterpret_cast<TPointerOffsetType>(&dummy->first),
valueType,
reinterpret_cast<TPointerOffsetType>(&dummy->second),
true);
CStlClassInfoFunctions<TObjectType>::SetMemFunctions(info);
CStlClassInfoFunctions_set<TObjectType>::SetAddElementFunctions(info);
CStlClassInfoFunctions<TObjectType>::SetCountFunctions(info);
CStlClassInfoFunctionsCI<TObjectType>::SetIteratorFunctions(info);
CStlClassInfoFunctionsI_set<TObjectType>::SetIteratorFunctions(info);
return info;
}
};
template<typename Key, typename Value, typename Comparator>
class CStlClassInfo_multimap3
{
public:
typedef multimap<Key, Value, Comparator> TObjectType;
typedef typename TObjectType::value_type TElementType;
static TTypeInfo GetTypeInfo(TTypeInfo keyType, TTypeInfo valueType)
{
static TTypeInfo info = 0;
return CStlClassInfoUtil::GetInfo(info,
keyType, valueType,
&CreateTypeInfo);
}
static CTypeInfo* CreateTypeInfo(TTypeInfo keyType, TTypeInfo valueType)
{
TElementType* dummy = 0;
CStlTwoArgsTemplate* info =
new CStlTwoArgsTemplate
(sizeof(TObjectType),
keyType,
reinterpret_cast<TPointerOffsetType>(&dummy->first),
valueType,
reinterpret_cast<TPointerOffsetType>(&dummy->second),
true);
CStlClassInfoFunctions<TObjectType>::SetMemFunctions(info);
CStlClassInfoFunctions_multiset<TObjectType>::SetAddElementFunctions(info);
CStlClassInfoFunctions<TObjectType>::SetCountFunctions(info);
CStlClassInfoFunctionsCI<TObjectType>::SetIteratorFunctions(info);
CStlClassInfoFunctionsI_set<TObjectType>::SetIteratorFunctions(info);
return info;
}
};
END_NCBI_SCOPE
/* @} */
#endif /* STLTYPES__HPP */
| 36.397216 | 188 | 0.604707 | [
"vector"
] |
26ca7f3a6a036b669ddd9e1e1b46ea10f88746cd | 3,114 | cpp | C++ | src/State.cpp | MartinsLucas/Jogos | e72ac454d19557d3a45211a57e0695bb6c3f104a | [
"MIT"
] | null | null | null | src/State.cpp | MartinsLucas/Jogos | e72ac454d19557d3a45211a57e0695bb6c3f104a | [
"MIT"
] | 7 | 2019-06-06T17:39:10.000Z | 2019-07-17T07:37:55.000Z | src/State.cpp | MartinsLucas/Jogos | e72ac454d19557d3a45211a57e0695bb6c3f104a | [
"MIT"
] | null | null | null | #include "State.h"
#include "Alien.h"
#include "Camera.h"
#include "CameraFollower.h"
#include <memory>
State::State() : music("assets/audio/stageState.ogg") {
this->quitRequested = false;
this->started = false;
// this->music.Play(-1);
this->objectArray = std::vector<std::shared_ptr<GameObject>>();
}
void State::LoadEnemies() {
GameObject *alienGameObject = new GameObject();
alienGameObject->AddComponent(new Alien(*alienGameObject, 6));
alienGameObject->box.SetCenter(Vec2(512.0, 300.0));
this->AddObject(alienGameObject);
Camera::Follow(alienGameObject);
}
void State::Start() {
this->LoadAssets();
this->LoadEnemies();
for(auto &object : this->objectArray) {
object->Start();
}
this->started = true;
}
State::~State() {
for (int index = this->objectArray.size() - 1 ; index >= 0 ; --index) {
delete this->objectArray[index].get();
}
this->objectArray.clear();
}
void State::Render() {
for(auto &object : this->objectArray) {
object->Render();
}
}
void State::LoadAssets() {
GameObject *spriteObject = new GameObject();
Sprite *backgroundSprite = new Sprite(*spriteObject, "assets/img/ocean.jpg");
CameraFollower *background = new CameraFollower(*spriteObject);
spriteObject->box.x = 0;
spriteObject->box.y = 0;
spriteObject->box.width = backgroundSprite->GetWidth();
spriteObject->box.height = backgroundSprite->GetHeight();
spriteObject->AddComponent(backgroundSprite);
spriteObject->AddComponent(background);
this->AddObject(spriteObject);
GameObject *tileMapObject = new GameObject();
TileSet *tileSet = new TileSet(64, 64, "assets/img/tileset.png");
TileMap *tileMap = new TileMap(*tileMapObject, "assets/map/tileMap.txt", tileSet);
tileMapObject->box.x = 0;
tileMapObject->box.y = 0;
tileMapObject->AddComponent(tileMap);
this->AddObject(tileMapObject);
}
void State::Update(float dt) {
if(
InputManager::GetInstance().QuitRequested() ||
InputManager::GetInstance().KeyPress(ESCAPE_KEY)
) {
this->quitRequested = true;
}
Camera::Update(dt);
for(auto &object : this->objectArray) {
object->Update(dt);
}
for(unsigned int index = 0 ; (index < this->objectArray.size()) ; index++) {
if (this->objectArray[index].get()->IsDead()) {
this->objectArray.erase(this->objectArray.begin() + index);
}
}
}
std::weak_ptr<GameObject> State::AddObject(GameObject *gameObject) {
std::shared_ptr<GameObject> sharedGameObject = std::shared_ptr<GameObject>(gameObject);
this->objectArray.push_back(sharedGameObject);
if (this->started) {
sharedGameObject->Start();
}
return(std::weak_ptr<GameObject>(sharedGameObject));
}
std::weak_ptr<GameObject> State::GetObjectPtr(GameObject *gameObject) {
std::weak_ptr<GameObject> weakGameObject = std::weak_ptr<GameObject>();
for (unsigned i = 0; i < this->objectArray.size(); i++) {
if (this->objectArray[i].get() == gameObject) {
weakGameObject = std::weak_ptr<GameObject>(this->objectArray[i]);
}
}
return(weakGameObject);
}
bool State::QuitRequested() {
return(this->quitRequested);
}
| 26.389831 | 89 | 0.68754 | [
"render",
"object",
"vector"
] |
26caa05204d61fdb25eea46977a0449cca2d5fef | 1,093 | hpp | C++ | stan/math/prim/arr/fun/rep_array.hpp | christophernhill/math | dc41aba296d592c7099be15eed6ba136d0f140b3 | [
"BSD-3-Clause"
] | null | null | null | stan/math/prim/arr/fun/rep_array.hpp | christophernhill/math | dc41aba296d592c7099be15eed6ba136d0f140b3 | [
"BSD-3-Clause"
] | null | null | null | stan/math/prim/arr/fun/rep_array.hpp | christophernhill/math | dc41aba296d592c7099be15eed6ba136d0f140b3 | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_MATH_PRIM_ARR_FUN_REP_ARRAY_HPP
#define STAN_MATH_PRIM_ARR_FUN_REP_ARRAY_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <vector>
namespace stan {
namespace math {
template <typename T>
inline std::vector<T> rep_array(const T& x, int n) {
check_nonnegative("rep_array", "n", n);
return std::vector<T>(n, x);
}
template <typename T>
inline std::vector<std::vector<T> > rep_array(const T& x, int m, int n) {
using std::vector;
check_nonnegative("rep_array", "rows", m);
check_nonnegative("rep_array", "cols", n);
return vector<vector<T> >(m, vector<T>(n, x));
}
template <typename T>
inline std::vector<std::vector<std::vector<T> > > rep_array(const T& x, int k,
int m, int n) {
using std::vector;
check_nonnegative("rep_array", "shelfs", k);
check_nonnegative("rep_array", "rows", m);
check_nonnegative("rep_array", "cols", n);
return vector<vector<vector<T> > >(k, vector<vector<T> >(m, vector<T>(n, x)));
}
} // namespace math
} // namespace stan
#endif
| 28.025641 | 80 | 0.651418 | [
"vector"
] |
26d17b1a9aedf724371a5589132da100ad174df7 | 5,599 | cpp | C++ | kernel/thor/system/acpi/pm-interface.cpp | Apache-HB/managarm | df922a987167948369ea1d0e675925126bb5fdad | [
"MIT"
] | null | null | null | kernel/thor/system/acpi/pm-interface.cpp | Apache-HB/managarm | df922a987167948369ea1d0e675925126bb5fdad | [
"MIT"
] | null | null | null | kernel/thor/system/acpi/pm-interface.cpp | Apache-HB/managarm | df922a987167948369ea1d0e675925126bb5fdad | [
"MIT"
] | null | null | null |
#ifdef __x86_64__
#include <arch/io_space.hpp>
#include <thor-internal/arch/hpet.hpp>
#endif
#include <thor-internal/fiber.hpp>
#include <thor-internal/io.hpp>
#include <thor-internal/kernel_heap.hpp>
#include <thor-internal/acpi/pm-interface.hpp>
#include <hw.frigg_bragi.hpp>
#include <mbus.frigg_pb.hpp>
#include <bragi/helpers-all.hpp>
#include <bragi/helpers-frigg.hpp>
#include <lai/helpers/pm.h>
namespace thor {
// TODO: Move this to a header file.
extern frg::manual_box<LaneHandle> mbusClient;
}
namespace thor::acpi {
#ifdef __x86_64__
inline constexpr arch::scalar_register<uint8_t> ps2Command(0x64);
constexpr uint8_t ps2Reset = 0xFE;
void issuePs2Reset() {
arch::io_space space;
space.store(ps2Command, ps2Reset);
pollSleepNano(100'000'000); // 100ms should be long enough to actually reset.
}
#endif
namespace {
coroutine<bool> handleReq(LaneHandle lane) {
auto [acceptError, conversation] = co_await AcceptSender{lane};
if(acceptError == Error::endOfLane)
co_return false;
// TODO: improve error handling here.
assert(acceptError == Error::success);
auto [reqError, reqBuffer] = co_await RecvBufferSender{conversation};
// TODO: improve error handling here.
assert(reqError == Error::success);
auto preamble = bragi::read_preamble(reqBuffer);
assert(!preamble.error());
if(preamble.id() == bragi::message_id<managarm::hw::PmResetRequest>) {
auto req = bragi::parse_head_only<managarm::hw::PmResetRequest>(reqBuffer, *kernelAlloc);
if (!req) {
infoLogger() << "thor: Closing lane due to illegal HW request." << frg::endlog;
co_return true;
}
if(lai_acpi_reset())
infoLogger() << "thor: ACPI reset failed" << frg::endlog;
#ifdef __x86_64__
issuePs2Reset();
infoLogger() << "thor: Reset using PS/2 controller failed" << frg::endlog;
#endif
panicLogger() << "thor: We do not know how to reset" << frg::endlog;
}else{
infoLogger() << "thor: Dismissing conversation due to illegal HW request." << frg::endlog;
co_await DismissSender{conversation};
}
co_return true;
}
// ------------------------------------------------------------------------
// mbus object creation and management.
// ------------------------------------------------------------------------
coroutine<LaneHandle> createObject(LaneHandle mbusLane) {
auto [offerError, conversation] = co_await OfferSender{mbusLane};
// TODO: improve error handling here.
assert(offerError == Error::success);
managarm::mbus::Property<KernelAlloc> cls_prop(*kernelAlloc);
cls_prop.set_name(frg::string<KernelAlloc>(*kernelAlloc, "class"));
auto &cls_item = cls_prop.mutable_item().mutable_string_item();
cls_item.set_value(frg::string<KernelAlloc>(*kernelAlloc, "pm-interface"));
managarm::mbus::CntRequest<KernelAlloc> req(*kernelAlloc);
req.set_req_type(managarm::mbus::CntReqType::CREATE_OBJECT);
req.set_parent_id(1);
req.add_properties(std::move(cls_prop));
frg::string<KernelAlloc> ser(*kernelAlloc);
req.SerializeToString(&ser);
frg::unique_memory<KernelAlloc> reqBuffer{*kernelAlloc, ser.size()};
memcpy(reqBuffer.data(), ser.data(), ser.size());
auto reqError = co_await SendBufferSender{conversation, std::move(reqBuffer)};
// TODO: improve error handling here.
assert(reqError == Error::success);
auto [respError, respBuffer] = co_await RecvBufferSender{conversation};
// TODO: improve error handling here.
assert(respError == Error::success);
managarm::mbus::SvrResponse<KernelAlloc> resp(*kernelAlloc);
resp.ParseFromArray(respBuffer.data(), respBuffer.size());
assert(resp.error() == managarm::mbus::Error::SUCCESS);
auto [descError, descriptor] = co_await PullDescriptorSender{conversation};
// TODO: improve error handling here.
assert(descError == Error::success);
assert(descriptor.is<LaneDescriptor>());
co_return descriptor.get<LaneDescriptor>().handle;
}
coroutine<void> handleBind(LaneHandle objectLane) {
auto [acceptError, conversation] = co_await AcceptSender{objectLane};
// TODO: improve error handling here.
assert(acceptError == Error::success);
auto [reqError, reqBuffer] = co_await RecvBufferSender{conversation};
// TODO: improve error handling here.
assert(reqError == Error::success);
managarm::mbus::SvrRequest<KernelAlloc> req(*kernelAlloc);
req.ParseFromArray(reqBuffer.data(), reqBuffer.size());
assert(req.req_type() == managarm::mbus::SvrReqType::BIND);
managarm::mbus::CntResponse<KernelAlloc> resp(*kernelAlloc);
resp.set_error(managarm::mbus::Error::SUCCESS);
frg::string<KernelAlloc> ser(*kernelAlloc);
resp.SerializeToString(&ser);
frg::unique_memory<KernelAlloc> respBuffer{*kernelAlloc, ser.size()};
memcpy(respBuffer.data(), ser.data(), ser.size());
auto respError = co_await SendBufferSender{conversation, std::move(respBuffer)};
// TODO: improve error handling here.
assert(respError == Error::success);
auto stream = createStream();
auto descError = co_await PushDescriptorSender{conversation,
LaneDescriptor{stream.get<1>()}};
// TODO: improve error handling here.
assert(descError == Error::success);
async::detach_with_allocator(*kernelAlloc, [] (LaneHandle lane) -> coroutine<void> {
while(true) {
if(!(co_await handleReq(lane)))
break;
}
}(std::move(stream.get<0>())));
}
} // anonymous namespace
void initializePmInterface() {
// Create a fiber to manage requests to the RTC mbus object.
KernelFiber::run([=] {
async::detach_with_allocator(*kernelAlloc, [] () -> coroutine<void> {
auto objectLane = co_await createObject(*mbusClient);
while(true)
co_await handleBind(objectLane);
}());
});
}
} // namespace thor::acpi
| 33.130178 | 92 | 0.716914 | [
"object"
] |
26ee8ba2ed7eb3d28dfab58767205b7e70d1c250 | 7,424 | cpp | C++ | gm_dotnet_native/dotnethelper-src/LuaAPIExposure.cpp | SupinePandora43/GmodDotNet | 515af9dd012f2a07184c71fd229ca50f9982c987 | [
"MIT"
] | null | null | null | gm_dotnet_native/dotnethelper-src/LuaAPIExposure.cpp | SupinePandora43/GmodDotNet | 515af9dd012f2a07184c71fd229ca50f9982c987 | [
"MIT"
] | null | null | null | gm_dotnet_native/dotnethelper-src/LuaAPIExposure.cpp | SupinePandora43/GmodDotNet | 515af9dd012f2a07184c71fd229ca50f9982c987 | [
"MIT"
] | null | null | null | //
// Created by Gleb Krasilich on 06.10.2019.
//
#include "LuaAPIExposure.h"
#include <GarrysMod/Lua/Interface.h>
#include <GarrysMod/Lua/LuaBase.h>
#include <string>
#include <cstring>
using namespace std;
using namespace GarrysMod;
using namespace GarrysMod::Lua;
int export_top(ILuaBase * lua)
{
return lua->Top();
}
void export_push(ILuaBase * lua, int iStackPos)
{
lua->Push(iStackPos);
}
void export_pop(ILuaBase * lua, int IAmt)
{
lua->Pop(IAmt);
}
void export_get_field(ILuaBase * lua, int iStackPos, const char * key)
{
lua->GetField(iStackPos, key);
}
void export_set_field(ILuaBase * lua, int iStackPos, const char * key)
{
lua->SetField(iStackPos, key);
}
void export_create_table(ILuaBase * lua)
{
lua->CreateTable();
}
void export_set_metatable(ILuaBase * lua, int iStackPos)
{
lua->SetMetaTable(iStackPos);
}
int export_get_metatable(ILuaBase * lua, int iStackPos)
{
bool tmp_ret = lua->GetMetaTable(iStackPos);
if(tmp_ret)
{
return 1;
}
else
{
return 0;
}
}
void export_call(ILuaBase * lua, int IArgs, int iResults)
{
lua->Call(IArgs, iResults);
}
int export_p_call(ILuaBase * lua, int IArgs, int IResults, int ErrorFunc)
{
return lua->PCall(IArgs, IResults, ErrorFunc);
}
int exports_equal(ILuaBase * lua, int iA, int iB)
{
return lua->Equal(iA, iB);
}
int export_raw_equal(ILuaBase * lua, int iA, int iB)
{
return lua->RawEqual(iA, iB);
}
void export_insert(ILuaBase * lua, int iStackPos)
{
lua->Insert(iStackPos);
}
void export_remove(ILuaBase * lua, int iStackPos)
{
lua->Remove(iStackPos);
}
int export_next(ILuaBase * lua, int iStackPos)
{
return lua->Next(iStackPos);
}
void export_throw_error(ILuaBase * lua, const char * error_msg)
{
lua->ThrowError(error_msg);
}
void export_check_type(ILuaBase * lua, int iStackPos, int IType)
{
lua->CheckType(iStackPos, IType);
}
void export_arg_error(ILuaBase * lua, int iArgNum, const char * error_msg)
{
lua->ArgError(iArgNum, error_msg);
}
const char * export_get_string(ILuaBase * lua, int iStackPos, unsigned int * iOutLength)
{
return lua->GetString(iStackPos, iOutLength);
}
double export_get_number(ILuaBase * lua, int iStackPos)
{
return lua->GetNumber(iStackPos);
}
int export_get_bool (ILuaBase * lua, int iStackPos)
{
bool tmp_ret = lua->GetBool(iStackPos);
if(tmp_ret)
{
return 1;
}
else
{
return 0;
}
}
CFunc export_get_c_function(ILuaBase * lua, int iStackPos)
{
return lua->GetCFunction(iStackPos);
}
void export_push_nil(ILuaBase * lua)
{
lua->PushNil();
}
void export_push_string(ILuaBase * lua, const char * string, unsigned int len)
{
lua->PushString(string, len);
}
void export_push_number(ILuaBase * lua, double val)
{
lua->PushNumber(val);
}
void export_push_bool(ILuaBase * lua, int val)
{
bool tmp;
if(val == 0)
{
tmp = false;
}
else
{
tmp = true;
}
lua->PushBool(tmp);
}
void export_push_c_function(ILuaBase * lua, CFunc val)
{
lua->PushCFunction(val);
}
void export_push_c_closure(ILuaBase * lua, CFunc val, int iVars)
{
lua->PushCClosure(val, iVars);
}
int export_reference_create(ILuaBase * lua)
{
return lua->ReferenceCreate();
}
void export_reference_free(ILuaBase * lua, int reference)
{
lua->ReferenceFree(reference);
}
void export_reference_push(ILuaBase * lua, int reference)
{
lua->ReferencePush(reference);
}
void export_push_special(ILuaBase * lua, int table_type_number)
{
lua->PushSpecial(table_type_number);
}
int export_is_type(ILuaBase * lua, int iStackPos, int iType)
{
bool tmp = lua->IsType(iStackPos, iType);
if(tmp)
{
return 1;
}
else
{
return 0;
}
}
int export_get_type(ILuaBase * lua, int iStackPos)
{
return lua->GetType(iStackPos);
}
const char * export_get_type_name(ILuaBase * lua, int iType, int * out_name_len)
{
const char * ptr = lua->GetTypeName(iType);
int tmp_len = strlen(ptr);
*out_name_len = tmp_len;
return ptr;
}
int export_obj_len(ILuaBase * lua, int iStackPos)
{
return lua->ObjLen(iStackPos);
}
void export_get_angle(ILuaBase * lua, float * out_angle_components, int iStackPos)
{
const QAngle& tmp = lua->GetAngle(iStackPos);
out_angle_components[0] = tmp.x;
out_angle_components[1] = tmp.y;
out_angle_components[2] = tmp.z;
}
void export_get_vector(ILuaBase * lua, float * out_vector_components, int iStackPos)
{
const Vector& tmp = lua->GetVector(iStackPos);
out_vector_components[0] = tmp.x;
out_vector_components[1] = tmp.y;
out_vector_components[2] = tmp.z;
}
void export_push_angle(ILuaBase * lua, float x, float y, float z)
{
QAngle tmp;
tmp.x = x;
tmp.y = y;
tmp.z = z;
lua->PushAngle(tmp);
}
void export_push_vector(ILuaBase * lua, float x, float y, float z)
{
Vector tmp;
tmp.x = x;
tmp.y = y;
tmp.z = z;
lua->PushVector(tmp);
}
void export_set_state(ILuaBase * lua, lua_State * state)
{
lua->SetState(state);
}
int export_create_metatable(ILuaBase * lua, const char * name)
{
return lua->CreateMetaTable(name);
}
int export_push_metatable(ILuaBase * lua, int iType)
{
bool tmp = lua->PushMetaTable(iType);
if(tmp)
{
return 1;
}
else
{
return 0;
}
}
void export_push_user_type(ILuaBase * lua, void * data, int iType)
{
lua->PushUserType(data, iType);
}
void export_set_user_type(ILuaBase * lua, int iStackPos, void * data)
{
lua->SetUserType(iStackPos, data);
}
void * export_get_user_type(ILuaBase * lua, int iStackPos, int iType)
{
return lua->GetUserType<void*>(iStackPos, iType);
}
ILuaBase * export_get_iluabase_from_the_lua_state(lua_State * state)
{
return state->luabase;
}
void export_get_table(ILuaBase * lua, int iStackPos)
{
lua->GetTable(iStackPos);
}
void export_set_table(ILuaBase * lua, int iStackPos)
{
lua->SetTable(iStackPos);
}
void export_raw_get(ILuaBase * lua, int iStackPos)
{
lua->RawGet(iStackPos);
}
void export_raw_set(ILuaBase * lua, int iStackPos)
{
lua->RawSet(iStackPos);
}
void export_push_user_data(ILuaBase * lua, void * data)
{
lua->PushUserdata(data);
}
const char * export_check_string(ILuaBase * lua, int iStackPos, int * output_string_length)
{
const char * tmp = lua->CheckString(iStackPos);
if(tmp == nullptr)
{
return nullptr;
}
*output_string_length = strlen(tmp);
return tmp;
}
double export_check_number(ILuaBase * lua, int iStackPos)
{
return lua->CheckNumber(iStackPos);
}
// ClosureSafeWrapper is used internally in export_push_c_function_safe
int ClosureSafeWrapper(lua_State * luaState)
{
ILuaBase * lua = luaState->luabase;
//Get actual function pointer form upvalue pseudoindex
CFunc func_ptr = lua->GetCFunction(-10003);
//Call func_ptr
int arg_ret_num = func_ptr(luaState);
if(arg_ret_num < 0)
{
const char * error_msg = lua->GetString(-1);
lua->ThrowError(error_msg);
return 0;
}
else
{
return arg_ret_num;
}
}
void export_push_c_function_safe(GarrysMod::Lua::ILuaBase * lua, GarrysMod::Lua::CFunc safe_wrapper, GarrysMod::Lua::CFunc val)
{
lua->PushCFunction(safe_wrapper);
lua->PushCFunction(val);
lua->PushCClosure(ClosureSafeWrapper, 2);
}
| 18.890585 | 127 | 0.675512 | [
"vector"
] |
26fc6579ac4c61618386f6d648f567181bc27932 | 5,287 | cpp | C++ | odevice/app/src/main/jni/ParallelME/runtime/src/parallelme/Buffer.cpp | rcarvs/android-ocr | f8760afd378607ced0beca0b2c1beda14ea4ab49 | [
"MIT"
] | 5 | 2016-08-09T17:09:46.000Z | 2020-12-12T21:17:33.000Z | src/parallelme/Buffer.cpp | ParallelME/runtime | 80c3104c88e8efe9e4d746aa2976702c84f6302d | [
"Apache-2.0"
] | 12 | 2016-04-07T19:42:02.000Z | 2017-06-12T13:37:50.000Z | src/parallelme/Buffer.cpp | ParallelME/runtime | 80c3104c88e8efe9e4d746aa2976702c84f6302d | [
"Apache-2.0"
] | 2 | 2017-04-07T20:31:10.000Z | 2021-04-19T23:24:38.000Z | /* _ __ ____
* _ __ ___ _____ ___ __ __ ___ __ / | / / __/
* | _ \/ _ | _ | / _ | / / / / / __/ / / | / / /__
* | __/ __ | ___|/ __ |/ /_/ /__/ __/ /__ / / v / /__
* |_| /_/ |_|_|\_\/_/ |_/____/___/___/____/ /_/ /_/____/
*
*/
#include <parallelme/Buffer.hpp>
#include <parallelme/Device.hpp>
#include <parallelme/Runtime.hpp>
#include <string>
#include <android/bitmap.h>
#include <jni.h>
#include "dynloader/dynLoader.h"
using namespace parallelme;
Buffer::Buffer(size_t size) : _size(size), _mem(nullptr), _device(nullptr),
_copyPtr(nullptr), _copyArray(nullptr), _copyBitmap(nullptr) {
}
Buffer::~Buffer() {
if(_mem) {
clReleaseMemObject(_mem);
_mem = nullptr;
}
}
void Buffer::setJArraySource(JNIEnv *env, jarray array) {
releaseCopySources(env);
_copyArray = (jarray) env->NewGlobalRef(array);
if(!_copyArray)
throw BufferCopyError("Failed to create a new jarray global ref.");
}
void Buffer::setAndroidBitmapSource(JNIEnv *env, jobject bitmap) {
releaseCopySources(env);
_copyBitmap = env->NewGlobalRef(bitmap);
if(!_copyBitmap)
throw BufferCopyError("Failed to create a new bitmap global ref.");
}
void Buffer::setSource(void *host) {
// Other copy sources will be released when calling makeCopy().
_copyPtr = host;
}
void Buffer::copyToJArray(JNIEnv *env, jarray array) {
void *ptr = env->GetPrimitiveArrayCritical(array, nullptr);
if(!ptr)
throw BufferCopyError("Failed to get primitive array.");
copyTo(ptr);
env->ReleasePrimitiveArrayCritical(array, ptr, 0);
}
void Buffer::copyToAndroidBitmap(JNIEnv *env, jobject bitmap) {
void *ptr;
int err = AndroidBitmap_lockPixels(env, bitmap, &ptr);
if(err < 0)
throw BufferCopyError(std::to_string(err));
copyTo(ptr);
AndroidBitmap_unlockPixels(env, bitmap);
}
void Buffer::copyTo(void *host) {
auto mem = clMem(_device);
int err;
void *data = clEnqueueMapBuffer(_device->clQueue(), mem, CL_TRUE,
CL_MAP_READ, 0, _size, 0, nullptr, nullptr, &err);
if(err < 0)
throw BufferCopyError(std::to_string(err));
memcpy(host, data, _size);
clEnqueueUnmapMemObject(_device->clQueue(), mem, data, 0, nullptr, nullptr);
}
_cl_mem *Buffer::clMem(std::shared_ptr<Device> device) {
if(_device != device)
createMemoryObject(device, !hasCopySource());
if(hasCopySource())
makeCopy(_device->JNIEnv());
return _mem;
}
void Buffer::createMemoryObject(std::shared_ptr<Device> newDevice, bool copyOld) {
int err;
auto newMem = clCreateBuffer(newDevice->clContext(), CL_MEM_READ_WRITE,
_size, nullptr, &err);
if(err < 0)
throw BufferConstructionError(std::to_string(err));
// If there is a memory object already, do a copy and delete the old mem.
if(copyOld && _mem) {
void *oldData = clEnqueueMapBuffer(_device->clQueue(), _mem, CL_TRUE,
CL_MAP_READ, 0, _size, 0, nullptr, nullptr, &err);
if(err < 0)
throw BufferCopyError(std::to_string(err));
void *newData = clEnqueueMapBuffer(newDevice->clQueue(), newMem, CL_TRUE,
CL_MAP_WRITE, 0, _size, 0, nullptr, nullptr, &err);
if(err < 0)
throw BufferCopyError(std::to_string(err));
memcpy(newData, oldData, _size);
clEnqueueUnmapMemObject(_device->clQueue(), _mem, oldData, 0, nullptr, nullptr);
_device->finish();
clEnqueueUnmapMemObject(newDevice->clQueue(), newMem, newData, 0, nullptr, nullptr);
clReleaseMemObject(_mem);
}
_mem = newMem;
_device = newDevice;
}
void Buffer::releaseCopySources(JNIEnv *env) {
if(_copyPtr) {
_copyPtr = nullptr;
}
if(_copyArray) {
env->DeleteGlobalRef(_copyArray);
_copyArray = nullptr;
}
if(_copyBitmap) {
env->DeleteGlobalRef(_copyBitmap);
_copyBitmap = nullptr;
}
}
void Buffer::makeCopy(JNIEnv *env) {
// _copyPtr has preference because copyFrom() doesn't call releaseCopySources(),
// so _copyArray and _copyBitmap may still have references to clear.
if(_copyPtr) {
makeCopyFrom(_copyPtr);
}
else if(_copyArray) {
void *ptr = env->GetPrimitiveArrayCritical(_copyArray, nullptr);
if(!ptr)
throw BufferCopyError("Failed to get primitive array.");
makeCopyFrom(ptr);
env->ReleasePrimitiveArrayCritical(_copyArray, ptr, 0);
}
else { // _copyBitmap
void *ptr;
int err = AndroidBitmap_lockPixels(env, _copyBitmap, &ptr);
if(err < 0)
throw BufferCopyError("Failed to lock android bitmap's pixels.");
makeCopyFrom(ptr);
AndroidBitmap_unlockPixels(env, _copyBitmap);
}
releaseCopySources(env);
}
void Buffer::makeCopyFrom(void *host) {
int err;
void *data = clEnqueueMapBuffer(_device->clQueue(), _mem, CL_TRUE,
CL_MAP_WRITE, 0, _size, 0, nullptr, nullptr, &err);
if(err < 0)
throw BufferCopyError(std::to_string(err));
memcpy(data, host, _size);
clEnqueueUnmapMemObject(_device->clQueue(), _mem, data, 0, nullptr, nullptr);
}
| 29.536313 | 92 | 0.631171 | [
"object"
] |
f8049cdb35e74a6c9ee1219bece7e5cf652cac6d | 2,554 | cpp | C++ | samples/snippets/cpp/VS_Snippets_CLR_System/system.Collections.Specialized.NameObjectCollectionBase.IsReadOnly/CPP/nocb_isreadonly.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 421 | 2018-04-01T01:57:50.000Z | 2022-03-28T15:24:42.000Z | samples/snippets/cpp/VS_Snippets_CLR_System/system.Collections.Specialized.NameObjectCollectionBase.IsReadOnly/CPP/nocb_isreadonly.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 5,797 | 2018-04-02T21:12:23.000Z | 2022-03-31T23:54:38.000Z | samples/snippets/cpp/VS_Snippets_CLR_System/system.Collections.Specialized.NameObjectCollectionBase.IsReadOnly/CPP/nocb_isreadonly.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 1,482 | 2018-03-31T11:26:20.000Z | 2022-03-30T22:36:45.000Z | // The following example creates a read-only collection.
// For an expanded version of this example, see the NameObjectCollectionBase class topic.
// <snippet1>
#using <System.dll>
using namespace System;
using namespace System::Collections;
using namespace System::Collections::Specialized;
public ref class MyCollection : public NameObjectCollectionBase {
private:
DictionaryEntry^ _de;
// Gets a key-and-value pair (DictionaryEntry) using an index.
public:
property DictionaryEntry^ default[ int ] {
DictionaryEntry^ get( int index ) {
_de->Key = this->BaseGetKey( index );
_de->Value = this->BaseGet( index );
return( _de );
}
}
// Adds elements from an IDictionary into the new collection.
MyCollection( IDictionary^ d, Boolean bReadOnly ) {
_de = gcnew DictionaryEntry();
for each ( DictionaryEntry^ de in d ) {
this->BaseAdd( (String^) de->Key, de->Value );
}
this->IsReadOnly = bReadOnly;
}
// Adds an entry to the collection.
void Add( String^ key, Object^ value ) {
this->BaseAdd( key, value );
}
};
public ref class SamplesNameObjectCollectionBase {
public:
static void Main() {
// Creates and initializes a new MyCollection that is read-only.
IDictionary^ d = gcnew ListDictionary();
d->Add( "red", "apple" );
d->Add( "yellow", "banana" );
d->Add( "green", "pear" );
MyCollection^ myROCol = gcnew MyCollection( d, true );
// Tries to add a new item.
try {
myROCol->Add( "blue", "sky" );
}
catch ( NotSupportedException^ e ) {
Console::WriteLine( e->ToString() );
}
// Displays the keys and values of the MyCollection.
Console::WriteLine( "Read-Only Collection:" );
PrintKeysAndValues( myROCol );
}
static void PrintKeysAndValues( MyCollection^ myCol ) {
for ( int i = 0; i < myCol->Count; i++ ) {
Console::WriteLine( "[{0}] : {1}, {2}", i, myCol[i]->Key, myCol[i]->Value );
}
}
};
int main()
{
SamplesNameObjectCollectionBase::Main();
}
/*
This code produces the following output.
System.NotSupportedException: Collection is read-only.
at System.Collections.Specialized.NameObjectCollectionBase.BaseAdd(String name, Object value)
at SamplesNameObjectCollectionBase.Main()
Read-Only Collection:
[0] : red, apple
[1] : yellow, banana
[2] : green, pear
*/
// </snippet1>
| 27.76087 | 97 | 0.615114 | [
"object"
] |
f80bc9eb48ced907adbdc991c1c0e53bb8dcf694 | 766 | cpp | C++ | Algorithms/0970.Powerful_Integers.cpp | metehkaya/LeetCode | 52f4a1497758c6f996d515ced151e8783ae4d4d2 | [
"MIT"
] | 2 | 2020-07-20T06:40:22.000Z | 2021-11-20T01:23:26.000Z | Problems/LeetCode/Problems/0970.Powerful_Integers.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | Problems/LeetCode/Problems/0970.Powerful_Integers.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> getVec(int x , int lim) {
vector<int> v(1,1);
if(x > 1)
while(v.back()*x <= lim) {
int add = v.back()*x;
v.push_back(add);
}
return v;
}
vector<int> powerfulIntegers(int x, int y, int lim) {
vector<int> ans;
if(lim < 2)
return ans;
vector<int> a = getVec(x,lim);
vector<int> b = getVec(y,lim);
set<int> s;
for( int i = 0 ; i < a.size() ; i++ )
for( int j = 0 ; j < b.size() ; j++ )
if(a[i] + b[j] <= lim)
s.insert(a[i]+b[j]);
ans.resize(s.size());
copy(s.begin(),s.end(),ans.begin());
return ans;
}
}; | 28.37037 | 57 | 0.409922 | [
"vector"
] |
f80e2b07400b983fc7bb5618be298fb75f5ca254 | 3,478 | cpp | C++ | src/qsspropertyblock.cpp | ajax-crypto/libqss | e8f24319e587640b6748202bc645589c2b6a5a9a | [
"MIT"
] | 2 | 2020-12-14T15:40:06.000Z | 2021-09-22T02:34:18.000Z | src/qsspropertyblock.cpp | ajax-crypto/libqss | e8f24319e587640b6748202bc645589c2b6a5a9a | [
"MIT"
] | null | null | null | src/qsspropertyblock.cpp | ajax-crypto/libqss | e8f24319e587640b6748202bc645589c2b6a5a9a | [
"MIT"
] | null | null | null | #include "../include/qsspropertyblock.h"
qss::PropertyBlock::PropertyBlock(const QString & str)
{
parse(str);
}
qss::PropertyBlock& qss::PropertyBlock::operator=(const PropertyBlock &block)
{
m_params = block.m_params;
return *this;
}
qss::PropertyBlock& qss::PropertyBlock::addParam(const QString &key, const QString &value)
{
auto tkey = key.trimmed();
m_params[tkey].first = value.trimmed();
m_params[tkey].second = true;
return *this;
}
qss::PropertyBlock& qss::PropertyBlock::addParam(const QStringPairs ¶ms)
{
for (const auto& param : params)
{
auto tkey = param.first.trimmed();
m_params[tkey].first = param.second.trimmed();
m_params[tkey].second = true;
}
return *this;
}
qss::PropertyBlock& qss::PropertyBlock::enableParam(const QString &key, bool enable)
{
auto tkey = key.trimmed();
auto itr = m_params.find(tkey);
if (itr != m_params.cend())
{
m_params[tkey].second = enable;
}
return *this;
}
qss::PropertyBlock& qss::PropertyBlock::toggleParam(const QString &key)
{
auto tkey = key.trimmed();
auto itr = m_params.find(tkey);
if (itr != m_params.cend())
{
m_params[tkey].second = !itr->second.second;
}
return *this;
}
qss::PropertyBlock& qss::PropertyBlock::remove(const QString &key)
{
if (m_params.count(key))
{
m_params.erase(key);
}
return *this;
}
qss::PropertyBlock& qss::PropertyBlock::remove(const std::vector<QString> &keys)
{
for (auto const& key : keys)
{
remove(key);
}
return *this;
}
qss::PropertyBlock& qss::PropertyBlock::operator+=(const PropertyBlock & block)
{
for (const auto& pair : block.m_params)
{
m_params[pair.first] = pair.second;
}
return *this;
}
qss::PropertyBlock& qss::PropertyBlock::operator+=(const QString & block)
{
return this->operator+=(PropertyBlock{ block });
}
void qss::PropertyBlock::parse(const QString &input)
{
auto str = input.trimmed();
if (str.size() > 0)
{
auto parts = str.split(Delimiters.at(QSS_STATEMENT_END_DELIMITER), QString::SplitBehavior::SkipEmptyParts);
for (auto const& part : parts)
{
auto line = part.split(Delimiters.at(QSS_PSEUDO_CLASS_DELIMITER), QString::SplitBehavior::SkipEmptyParts);
if (line.size() == 2)
{
auto key = line[0].trimmed();
auto value = line[1].trimmed();
m_params[key].first = value;
m_params[key].second = true;
}
else
{
throw Exception{ Exception::BLOCK_PARAM_INVALID, part };
}
}
}
}
QString qss::PropertyBlock::toString() const
{
QString result;
for (auto const& pair : m_params)
{
if (pair.second.second)
{
result += "\t" + pair.first + Delimiters.at(QSS_PSEUDO_CLASS_DELIMITER);
result += " " + pair.second.first + Delimiters.at(QSS_STATEMENT_END_DELIMITER) + "\n";
}
}
return result;
}
std::size_t qss::PropertyBlock::size() const noexcept
{
return m_params.size();
}
bool qss::operator==(const PropertyBlock & lhs, const PropertyBlock & rhs)
{
return lhs.toString() == rhs.toString();
}
qss::PropertyBlock qss::operator+(const PropertyBlock & lhs, const PropertyBlock & rhs)
{
PropertyBlock sum = lhs;
sum += rhs;
return sum;
}
| 22.584416 | 118 | 0.610983 | [
"vector"
] |
f8136f6299f50e15b45f47ef96b7f4de1661794d | 1,572 | cpp | C++ | test_case/main.cpp | Ji-Yuhang/pat_cpp | 100525878db4119eaa4be25ef192af9a3b9543bd | [
"MIT"
] | null | null | null | test_case/main.cpp | Ji-Yuhang/pat_cpp | 100525878db4119eaa4be25ef192af9a3b9543bd | [
"MIT"
] | null | null | null | test_case/main.cpp | Ji-Yuhang/pat_cpp | 100525878db4119eaa4be25ef192af9a3b9543bd | [
"MIT"
] | null | null | null | #include <iostream>
#include <map>
#include <vector>
#include <algorithm>
#include <assert.h>
#include <queue>
#include <cstdlib>
#include <ctime>
using namespace std;
void test_case()
{
std::srand(std::time(0)); //use current time as seed for random generator
queue<int> Q;
vector<int> G[101];
int s_id = 1;
int mod = rand() % 3 + 1;
//Node root;
Q.push(s_id);
while (!Q.empty()) {
//s_id++;
int id = Q.front();
if (id >= 100) break;
Q.pop();
int size = rand() % 3;
mod--;
if (mod <= 1) mod = 10;
int actual_size = 0;
for (int i = 0; i < size; i++) {
if (s_id < 100) {
s_id++;
G[id].push_back(s_id);
Q.push(s_id);
//cout <<s_id <<" ";
actual_size++;
}
}
// cout << id << " " << actual_size << " ";
// for (auto c_id: G[id]){
// cout <<c_id <<" ";
// }
//
// cout << "\n";
}
int n = s_id;
int m = 0;
for (int i = 0; i <= s_id; i++) {
if (!G[i].empty()) m++;
}
cout << n << " " << m << "\n";
for (int i = 0; i <= s_id; i++) {
if (!G[i].empty()) {
auto children = G[i];
cout << i << " " << children.size() << " ";
for (auto id : children) {
cout << id << " ";
}
cout << "\n";
}
}
}
int main()
{
test_case();
return 0;
}
| 20.415584 | 77 | 0.379135 | [
"vector"
] |
f814f8502d4b76918675c2cff1f1cf13b692a70c | 5,255 | cpp | C++ | RayTracer/RayTracer.cpp | yiyaowen/RayTracer | cf600fae714d78c1617b5043430fe2c4d4f5d99c | [
"MIT"
] | null | null | null | RayTracer/RayTracer.cpp | yiyaowen/RayTracer | cf600fae714d78c1617b5043430fe2c4d4f5d99c | [
"MIT"
] | null | null | null | RayTracer/RayTracer.cpp | yiyaowen/RayTracer | cf600fae714d78c1617b5043430fe2c4d4f5d99c | [
"MIT"
] | null | null | null | /*
* Ray Tracer @ https://github.com/yiyaowen/RayTracer
*
* yiyaowen 2021 (c) All Rights Reserved.
*
* Also see tutorial: Ray Tracing in One Weekend by Peter Shirley.
* Web URL: https://raytracing.github.io/books/RayTracingInOneWeekend.html
*/
#include <functional>
#include <future>
#include <thread>
#include "Exporter/ExporterManager.h"
#include "Concurrency/PartialProcessor.h"
#include "Scene/Scene.h"
#include "RayTracer.h"
std::default_random_engine defaultRandomEngine;
int main(int argc, char* argv[]) {
try {
// Init random engine.
defaultRandomEngine = std::default_random_engine(std::chrono::system_clock::now().time_since_epoch().count());
// Image
const double aspectRatio = 16.0 / 9.0;
const int imageWidth = 800;
const int imageHeight = static_cast<int>(imageWidth / aspectRatio);
const int maxDepth = 50;
const int sampleCount = 100;
/* Build scene start */
auto buildSceneStart = std::chrono::high_resolution_clock::now();
// Camera
auto camera = randomBallsCamera(aspectRatio);
// Scene
auto shapeList = randomBallsScene();
/* Build scene end */
auto buildSceneEnd = std::chrono::high_resolution_clock::now();
auto buildSceneCost = buildSceneEnd - buildSceneStart;
auto buildSceneCostMs = std::chrono::duration_cast<std::chrono::milliseconds>(buildSceneCost).count();
auto buildSceneCostUs = std::chrono::duration_cast<std::chrono::microseconds>(buildSceneCost).count();
/* Render scene start */
auto renderSceneStart = std::chrono::high_resolution_clock::now();
// Render
ExporterManager em = {};
em.startWrite(imageWidth, imageHeight);
// Split the image to take advantage of multithreading to accelerate rendering.
PartialSceneInfo sceneInfo(shapeList);
sceneInfo.fullSize = { imageWidth, imageHeight };
sceneInfo.camera = camera;
sceneInfo.maxDepth = maxDepth;
sceneInfo.sampleCount = sampleCount;
int dispatchCountX = 16;
int dispatchCountY = 16;
int partialWidth = imageWidth / dispatchCountX;
int partialHeight = imageHeight / dispatchCountY;
std::vector<PartialProcessor> partials;
partials.reserve((dispatchCountX + 1) * (dispatchCountY + 1));
std::vector<std::future<void>> tasks;
tasks.reserve((dispatchCountX + 1) * (dispatchCountY + 1));
std::cout << "Building partial processors..." << std::endl;
int partialID = 0;
for (int i = 0; i <= dispatchCountX; ++i) {
for (int j = 0; j <= dispatchCountY; ++j) {
sceneInfo.widthRange = {partialWidth * i, partialWidth * (i + 1) - 1 };
if (sceneInfo.widthRange.second >= imageWidth) {
if (sceneInfo.widthRange.first >= imageWidth) continue;
sceneInfo.widthRange.second = imageWidth - 1;
}
sceneInfo.heightRange = {partialHeight * j, partialHeight * (j + 1) - 1 };
if (sceneInfo.heightRange.second >= imageHeight) {
if (sceneInfo.heightRange.first >= imageHeight) continue;
sceneInfo.heightRange.second = imageHeight - 1;
}
partials.emplace_back(sceneInfo, partialID);
tasks.emplace_back(std::async([&,partialID] { partials[partialID].process(); }));
++partialID;
}
}
size_t totalCount = tasks.size();
size_t lastFinished = 0, currFinished = 0;
std::function<size_t()> finishedCount = [&]() -> size_t {
return std::count_if(tasks.begin(), tasks.end(), [&](const std::future<void>& task) {
return task.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
});
};
while ((currFinished = finishedCount()) != totalCount) {
if (currFinished > lastFinished) {
std::cout << "Finished partial count " << currFinished << " / " << totalCount << std::endl;
lastFinished = currFinished;
}
std::this_thread::yield();
}
std::cout << "Writing partial images to final full image...\n";
for (const auto& partial : partials) {
partial.writeToFullImage(em.buffer());
}
std::cout << "Generating render result...\n";
em.endWrite("../Z Render Result/test.png", ExporterManager::PNG);
/* Render scene end */
auto renderSceneEnd = std::chrono::high_resolution_clock::now();
auto renderSceneCost = renderSceneEnd - renderSceneStart;
auto renderSceneCostMin = std::chrono::duration_cast<std::chrono::minutes>(renderSceneCost).count();
auto renderSceneCostSec = std::chrono::duration_cast<std::chrono::seconds>(renderSceneCost).count();
std::cout << "Build finished in " << buildSceneCostMs << " ms, " << buildSceneCostUs << " us. " <<
"Render finished in " << renderSceneCostMin << " min, " << renderSceneCostSec << " sec.\n";
}
catch (const std::exception& e) {
std::cout << e.what() << '\n';
}
} | 41.377953 | 118 | 0.60628 | [
"render",
"vector"
] |
f818fa23e21e1190a537e423f7eda8164f6985a1 | 5,197 | cpp | C++ | VSSimDB/VSEventSupplierOneTableCommon.cpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | 1 | 2018-04-17T14:03:36.000Z | 2018-04-17T14:03:36.000Z | VSSimDB/VSEventSupplierOneTableCommon.cpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | null | null | null | VSSimDB/VSEventSupplierOneTableCommon.cpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | null | null | null | //-*-mode:c++; mode:font-lock;-*-
/*! \file VSEventSupplierOneTableCommon.cpp
Input of event from single table from simulations dataCommon
\author Stephen Fegan \n
UCLA \n
sfegan@astro.ucla.edu \n
\version 0.1
\date 07/08/2006
\note
*/
#include <cassert>
#include "VSEventSupplierOneTableCommon.hpp"
using namespace VERITAS;
VSEventSupplierOneTableCommon::
VSEventSupplierOneTableCommon(const std::string& table_name,
VSSimDB* sim_db, uint32_t max_buffer_size)
: VSEventSupplier(), fSimDB(sim_db), fTableName(table_name),
fTableParam(), fMaxEventNum(), fEventNumBuffer(),
fMaxBufferSize(max_buffer_size),
fNextEventNum(fEventNumBuffer.end()), fLastEventNum(0),
fNEventToSupply(), fZEventToSupply(), fICompleteEvent()
{
fMaxEventNum = fSimDB->getMaxEventNumByName(table_name);
fNEventToSupply =
fSimDB->getCompleteEventCountByName(table_name, fMaxEventNum);
setTableParam(table_name);
}
VSEventSupplierOneTableCommon::
VSEventSupplierOneTableCommon(const std::string& table_name,
VSSimDB* sim_db,
uint32_t nevent_to_supply,
double ievent_to_start_fraction,
uint32_t max_buffer_size)
: VSEventSupplier(), fSimDB(sim_db), fTableName(table_name),
fTableParam(), fMaxEventNum(), fEventNumBuffer(),
fMaxBufferSize(max_buffer_size),
fNextEventNum(fEventNumBuffer.end()), fLastEventNum(0),
fNEventToSupply(), fZEventToSupply(), fICompleteEvent()
{
fMaxEventNum = fSimDB->getMaxEventNumByName(table_name);
setStartEventAndCount(table_name,nevent_to_supply,ievent_to_start_fraction);
setTableParam(table_name);
}
VSEventSupplierOneTableCommon::
VSEventSupplierOneTableCommon(const std::string& table_name,
VSSimDB* sim_db)
: VSEventSupplier(), fSimDB(sim_db), fTableName(table_name),
fTableParam(), fMaxEventNum(), fEventNumBuffer(),
fMaxBufferSize(), fNextEventNum(fEventNumBuffer.end()), fLastEventNum(0),
fNEventToSupply(), fZEventToSupply(), fICompleteEvent()
{
fNEventToSupply = fSimDB->getCompleteEventCountByName(table_name);
setTableParam(table_name);
}
VSEventSupplierOneTableCommon::
VSEventSupplierOneTableCommon(const std::string& table_name,
VSSimDB* sim_db,
uint32_t nevent_to_supply,
double ievent_to_start_fraction)
: VSEventSupplier(), fSimDB(sim_db), fTableName(table_name),
fTableParam(), fMaxEventNum(), fEventNumBuffer(),
fMaxBufferSize(), fNextEventNum(fEventNumBuffer.end()), fLastEventNum(0),
fNEventToSupply(), fZEventToSupply(), fICompleteEvent()
{
setStartEventAndCount(table_name,nevent_to_supply,ievent_to_start_fraction);
setTableParam(table_name);
}
void VSEventSupplierOneTableCommon::
setTableParam(const std::string& table_name)
{
VSSimDBTableParam* table = fSimDB->getDataTableByName(table_name);
assert(table);
fTableParam = SimParam(*table,fNEventToSupply);
delete table;
}
void VSEventSupplierOneTableCommon::
setStartEventAndCount(const std::string& table_name,
uint32_t nevent, double fraction)
{
uint32_t nevent_complete =
fSimDB->getCompleteEventCountByName(table_name, fMaxEventNum);
if(nevent < nevent_complete)
{
fNEventToSupply = nevent;
if(fraction<=0.0)
fICompleteEvent = 0;
else if(fraction>=1.0)
fICompleteEvent = nevent_complete-fNEventToSupply;
else
{
double ievent = double(nevent_complete-fNEventToSupply+1)*fraction;
fICompleteEvent = uint32_t(ievent);
#warning TEMPORARY ASSERTION
assert(fICompleteEvent <= (nevent_complete-fNEventToSupply));
}
fZEventToSupply = fICompleteEvent;
}
else
{
fNEventToSupply = nevent_complete;
fZEventToSupply = 0;
}
}
VSEventSupplierOneTableCommon::~VSEventSupplierOneTableCommon()
{
// nothing to see here
}
bool VSEventSupplierOneTableCommon::nextEvent()
{
if(fICompleteEvent>=fNEventToSupply+fZEventToSupply)return false;
fICompleteEvent += 1;
return true;
}
uint32_t VSEventSupplierOneTableCommon::getNextEventNum()
{
if(!nextEvent())
{
if(!fEventNumBuffer.empty())
{
fEventNumBuffer.clear();
fNextEventNum=fEventNumBuffer.end();
}
return 0;
}
if(fNextEventNum==fEventNumBuffer.end())
{
fEventNumBuffer.clear();
while((fEventNumBuffer.empty())&&(fLastEventNum<fMaxEventNum))
{
uint32_t min_event_num = fLastEventNum;
uint32_t max_event_num = fLastEventNum+fMaxBufferSize;
if(max_event_num>fMaxEventNum)max_event_num=fMaxEventNum;
fSimDB->getLimitedCompleteEventNums(fTableName,
min_event_num, max_event_num,
fEventNumBuffer);
if(fEventNumBuffer.empty())fLastEventNum=max_event_num;
}
fNextEventNum=fEventNumBuffer.begin();
}
assert(fNextEventNum!=fEventNumBuffer.end());
fLastEventNum = *fNextEventNum;
fNextEventNum++;
return fLastEventNum;
}
std::vector<VSEventSupplier::SimParam>
VSEventSupplierOneTableCommon::getSimParam()
{
std::vector<SimParam> tpvec;
tpvec.push_back(fTableParam);
return tpvec;
}
uint32_t VSEventSupplierOneTableCommon::getNumEvents()
{
return fNEventToSupply;
}
| 29.196629 | 78 | 0.734077 | [
"vector"
] |
f819c6e47a19d72ba0ea24d1bda86ea7874a5e58 | 12,686 | cpp | C++ | DebugLoop.cpp | devinacker/UnrealKey | 591c4ae8d4ccad0031af0fc5fa042e4d45512a5e | [
"MIT"
] | 22 | 2021-05-04T00:59:54.000Z | 2022-03-05T11:55:43.000Z | DebugLoop.cpp | LievreAI/UnrealKey | 591c4ae8d4ccad0031af0fc5fa042e4d45512a5e | [
"MIT"
] | 13 | 2021-10-31T03:11:36.000Z | 2022-03-02T01:50:55.000Z | DebugLoop.cpp | LievreAI/UnrealKey | 591c4ae8d4ccad0031af0fc5fa042e4d45512a5e | [
"MIT"
] | 3 | 2021-12-22T21:19:43.000Z | 2022-02-25T00:51:03.000Z | #include <cstdio>
#include <vector>
#include <string>
#include "Breakpoint.h"
#include "DebugLoop.h"
#include "common.h"
extern "C"
{
#include "aes.h"
}
#define PID_DEBUG(fmt, pid, ...) printf("[%5d] " fmt, pid, __VA_ARGS__)
static union
{
WCHAR g_pathw[1024];
CHAR g_path[1024];
};
struct FoundKey
{
std::wstring fileName;
UCHAR key[AES_KEYLEN];
};
static std::vector<FoundKey> g_foundKeys;
static std::vector<HANDLE> g_namedPipes;
static PipeMessage g_indexData;
static bool g_running;
// ----------------------------------------------------------------------------
static void HandleNewProcess(DWORD pid, LPCWSTR filePath)
{
bool ok = false;
HANDLE hFile = INVALID_HANDLE_VALUE;
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
snprintf(g_path, sizeof(g_path), PIPE_NAME, pid);
HANDLE hPipe = CreateNamedPipeA(g_path, PIPE_ACCESS_INBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_NOWAIT, 1,
0, sizeof(PipeMessage), 0, NULL);
if (hPipe == INVALID_HANDLE_VALUE)
{
PID_DEBUG("couldn't open named pipe (error 0x%x)\n", pid, GetLastError());
}
else
{
g_namedPipes.push_back(hPipe);
PID_DEBUG("Starting %ws\n", pid, filePath);
GetCurrentDirectoryW(MAX_PATH, g_pathw);
std::wstring currentDir(g_pathw);
GetModuleFileNameW(NULL, g_pathw, MAX_PATH);
wcsrchr(g_pathw, L'\\')[1] = 0;
SetCurrentDirectoryW(g_pathw);
WIN32_FIND_DATAW findData = { 0 };
hFile = FindFirstFileW(L".\\UnrealKey64.dll", &findData);
wcscat_s(g_pathw, findData.cFileName);
SetCurrentDirectoryW(currentDir.c_str());
}
if (hFile != INVALID_HANDLE_VALUE)
{
// got DLL path, load it in the remote process
LPVOID procMem = VirtualAllocEx(hProcess, NULL, sizeof(g_pathw), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (WriteProcessMemory(hProcess, procMem, g_pathw, sizeof(g_pathw), NULL))
{
HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0,
(LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandleA("kernel32"), "LoadLibraryW"),
procMem, 0, NULL);
if (hThread)
{
WaitForSingleObject(hThread, INFINITE);
DWORD exitCode;
if (GetExitCodeThread(hThread, &exitCode) && exitCode)
{
ok = true;
}
else
{
PID_DEBUG("Remote thread init error\n", pid);
}
CloseHandle(hThread);
}
else
{
PID_DEBUG("Couldn't start remote thread (error 0x%x)\n", pid, GetLastError());
}
}
else
{
PID_DEBUG("Couldn't write to process memory (error 0x%x)\n", pid, GetLastError());
}
FindClose(hFile);
}
else
{
PID_DEBUG("Couldn't find UnrealKey64.dll\n", pid);
}
if (!ok)
{
// can't do anything useful here, just leave
TerminateProcess(hProcess, 1);
}
CloseHandle(hProcess);
}
// ----------------------------------------------------------------------------
static void DebugOutputEvent(const DEBUG_EVENT& event)
{
WORD len = min(sizeof(g_pathw), event.u.DebugString.nDebugStringLength);
HANDLE hProcess = OpenProcess(PROCESS_VM_READ, FALSE, event.dwProcessId);
memset(g_pathw, 0, sizeof(g_pathw));
if (ReadProcessMemory(hProcess, event.u.DebugString.lpDebugStringData, g_pathw, event.u.DebugString.nDebugStringLength, NULL))
{
if (event.u.DebugString.fUnicode)
{
PID_DEBUG("%ws", event.dwProcessId, g_pathw);
}
else
{
PID_DEBUG("%s", event.dwProcessId, g_path);
}
}
CloseHandle(hProcess);
}
// ----------------------------------------------------------------------------
static void HandleIndexDataMessage(const PipeMessage& message)
{
g_indexData = message;
// Start debugging the remote process now
if (DebugActiveProcess(message.pid))
{
// Set a hardware breakpoint on the first byte of index data that we're watching,
// so that when it's copied out of the buffer into the actual index, we can
// find out where the index is, and then put another breakpoint on that later.
g_indexData.msgIndex.breakpoint = new Breakpoint(message.tid, message.msgIndex.indexAddr, Breakpoint::ReadWrite);
}
else
{
PID_DEBUG("Couldn't attach to process (error 0x%x)\n", message.pid, GetLastError());
}
}
// ----------------------------------------------------------------------------
static bool HandleSteamAppIDMessage(const PipeMessage& message)
{
if (GetEnvironmentVariableA("SteamAppID", g_path, sizeof(g_path)) > 0)
{
PID_DEBUG("Already tried to restart with SteamAppID once, aborting...\n", message.pid);
PID_DEBUG("Make sure Steam is actually running.\n", message.pid);
return false;
}
snprintf(g_path, sizeof(g_path), "%u", message.msgUInt);
if (SetEnvironmentVariableA("SteamAppID", g_path))
{
PID_DEBUG("Set SteamAppID successfully, app will restart...\n", message.pid);
return true;
}
PID_DEBUG("Couldn't set SteamAppID (error 0x%x)\n", message.pid, GetLastError());
return false;
}
// ----------------------------------------------------------------------------
static bool BreakpointEvent(const DEBUG_EVENT& event, bool &detach)
{
if (event.dwProcessId != g_indexData.pid
|| event.dwThreadId != g_indexData.tid)
{
return false;
}
HANDLE hThread = g_indexData.msgIndex.breakpoint->thread();
CONTEXT ctx = { 0 };
ctx.ContextFlags = CONTEXT_INTEGER | CONTEXT_CONTROL; // get RIP, RSP, RSI and RDI
GetThreadContext(hThread, &ctx);
if (g_indexData.msgIndex.breakpoint->access() == Breakpoint::ReadWrite)
{
// Data should be getting memmove'd out of the buffer into the real index now.
// Check the source/dest registers and make sure we can determine where it's going,
// then put a new breakpoint in the destination somewhere
auto indexAddr = (DWORD64)g_indexData.msgIndex.indexAddr;
if (ctx.Rsi >= indexAddr
&& ctx.Rsi < indexAddr + g_indexData.msgIndex.readBufSize)
{
g_indexData.msgIndex.indexAddr = (void*)(ctx.Rdi - (ctx.Rsi - indexAddr));
g_indexData.msgIndex.breakpoint->set((CHAR*)g_indexData.msgIndex.indexAddr + AES_BLOCKLEN - 1, Breakpoint::Write);
PID_DEBUG("Detected buffer->index copy successfully\n", event.dwProcessId);
}
else
{
PID_DEBUG("Unexpected read out of buffer!\n", event.dwProcessId);
PID_DEBUG("\tRIP=0x%p, RSI=0x%p, RDI=0x%p, buf=%p\n", event.dwProcessId,
(void*)ctx.Rip, (void*)ctx.Rsi, (void*)ctx.Rdi, g_indexData.msgIndex.indexAddr);
}
}
else if (g_indexData.msgIndex.breakpoint->access() == Breakpoint::Write)
{
// One full block of data in the index buffer has been decrypted now.
// We have both the encrypted and decrypted data, and the key should be on the stack
PID_DEBUG("Detected index decryption successfully, finding key now...\n", event.dwProcessId);
UCHAR decrypted[AES_BLOCKLEN];
HANDLE hProcess = OpenProcess(PROCESS_VM_READ, FALSE, event.dwProcessId);
if (ReadProcessMemory(hProcess, g_indexData.msgIndex.indexAddr, decrypted, sizeof(decrypted), NULL))
{
UCHAR encrypted[AES_BLOCKLEN];
UCHAR possibleKey[AES_KEYLEN];
AES_ctx aes;
// start crawling the stack and see if we find anything good
bool foundKey = false;
for (auto sp = ctx.Rsp; !foundKey && sp < ctx.Rsp + 0x200; sp += sizeof(void*))
{
memcpy(encrypted, g_indexData.msgIndex.indexData, AES_BLOCKLEN);
ReadProcessMemory(hProcess, (void*)sp, possibleKey, AES_KEYLEN, NULL);
AES_init_ctx(&aes, possibleKey);
AES_ECB_decrypt(&aes, encrypted);
if (!memcmp(encrypted, decrypted, AES_BLOCKLEN))
{
PID_DEBUG("Key: 0x", event.dwProcessId);
for (int i = 0; i < AES_KEYLEN; i++)
{
printf("%02X", possibleKey[i]);
}
printf("\n");
foundKey = true;
auto &key = *g_foundKeys.insert(g_foundKeys.end(), FoundKey());
key.fileName = g_indexData.msgIndex.filePath;
memcpy(key.key, possibleKey, AES_KEYLEN);
}
}
if (!foundKey)
{
PID_DEBUG("Couldn't find a valid key.\n", event.dwProcessId);
}
}
else
{
PID_DEBUG("Reading process memory at %p failed!\n", event.dwProcessId, g_indexData.msgIndex.indexAddr);
}
CloseHandle(hProcess);
// we're done, no more breakpoints
delete g_indexData.msgIndex.breakpoint;
g_indexData.msgIndex.breakpoint = NULL;
g_indexData.pid = g_indexData.tid = 0;
detach = true;
}
else
{
// ???
return false;
}
return true;
}
// ----------------------------------------------------------------------------
static BOOL WINAPI CtrlHandler(DWORD type)
{
if (type == CTRL_C_EVENT)
{
printf("Ctrl-C received, stopping...\n");
g_running = false;
return TRUE;
}
return FALSE;
}
// ----------------------------------------------------------------------------
static bool StartProcess(LPCWSTR appPath, HANDLE hJob, PROCESS_INFORMATION& pi)
{
STARTUPINFO si = { 0 };
si.cb = sizeof(si);
if (!CreateProcessW(appPath, NULL, NULL, NULL, FALSE,
CREATE_SUSPENDED | CREATE_BREAKAWAY_FROM_JOB, NULL, NULL, &si, &pi))
{
printf("couldn't launch %ws (error 0x%x)\n", appPath, GetLastError());
return false;
}
HandleNewProcess(pi.dwProcessId, appPath);
AssignProcessToJobObject(hJob, pi.hProcess);
ResumeThread(pi.hThread);
CloseHandle(pi.hThread);
return true;
}
// ----------------------------------------------------------------------------
int DebugLoop(LPCWSTR appPath)
{
JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobInfo = { 0 };
HANDLE hJob = CreateJobObjectW(NULL, NULL);
jobInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
SetInformationJobObject(hJob, JobObjectExtendedLimitInformation, &jobInfo, sizeof(jobInfo));
PROCESS_INFORMATION pi = { 0 };
printf("Starting the game now.\nClose the game or press Ctrl-C to stop.\n\n");
if (!StartProcess(appPath, hJob, pi))
return 1;
g_running = true;
int rc = 0;
bool restart = false;
DEBUG_EVENT event;
PipeMessage message;
DWORD dwTemp;
SetConsoleCtrlHandler(CtrlHandler, TRUE);
while (g_running)
{
if (GetExitCodeProcess(pi.hProcess, &dwTemp)
&& dwTemp != STILL_ACTIVE)
{
PID_DEBUG("process exited with code 0x%x\n", pi.dwProcessId, dwTemp);
// if we want to try to restart with a Steam App ID set (or something), do that now
if (restart)
{
restart = false;
if (StartProcess(appPath, hJob, pi))
continue;
else
rc = 1;
}
g_running = false;
break;
}
for (int i = 0; i < g_namedPipes.size(); i++)
{
if (ReadFile(g_namedPipes[i], &message, sizeof(message), &dwTemp, NULL))
{
switch (message.msgType)
{
case StringMessage:
PID_DEBUG("%ws\n", message.pid, message.msgString);
break;
case NewProcessMessage:
HandleNewProcess(message.msgProcess.pid, message.msgProcess.filePath);
break;
case IndexDataMessage:
HandleIndexDataMessage(message);
break;
case SteamAppIDMessage:
restart = HandleSteamAppIDMessage(message);
break;
}
HANDLE hThread = OpenThread(THREAD_SUSPEND_RESUME, FALSE, message.tid);
ResumeThread(hThread);
CloseHandle(hThread);
}
else if (GetLastError() == ERROR_BROKEN_PIPE)
{
CloseHandle(g_namedPipes[i]);
g_namedPipes[i] = g_namedPipes.back();
g_namedPipes.pop_back();
i--;
}
}
while (WaitForDebugEvent(&event, 50))
{
bool handled = false;
bool detach = false;
switch (event.dwDebugEventCode)
{
case CREATE_PROCESS_DEBUG_EVENT:
handled = true;
CloseHandle(event.u.CreateProcessInfo.hFile);
break;
case LOAD_DLL_DEBUG_EVENT:
handled = true;
CloseHandle(event.u.LoadDll.hFile);
break;
#ifdef HANDLE_DEBUG_OUT
case OUTPUT_DEBUG_STRING_EVENT:
handled = true;
DebugOutputEvent(event);
break;
#endif
case EXCEPTION_DEBUG_EVENT:
switch (event.u.Exception.ExceptionRecord.ExceptionCode)
{
case EXCEPTION_BREAKPOINT:
case 0x406d1388: // thread rename notification
handled = true;
break;
case EXCEPTION_SINGLE_STEP:
handled = BreakpointEvent(event, detach);
default:
break;
}
break;
case EXIT_PROCESS_DEBUG_EVENT:
handled = true;
PID_DEBUG("process exited with code 0x%x\n", event.dwProcessId, event.u.ExitProcess.dwExitCode);
break;
default:
break;
}
ContinueDebugEvent(event.dwProcessId, event.dwThreadId, handled ? DBG_CONTINUE : DBG_EXCEPTION_NOT_HANDLED);
if (detach)
DebugActiveProcessStop(event.dwProcessId);
}
}
// Clean up and show any keys that were found
CloseHandle(pi.hProcess);
CloseHandle(hJob);
printf("\nSummary:\n--------\n\n");
if (g_foundKeys.empty())
{
printf("No valid keys were found.\n");
}
else for (auto &key : g_foundKeys)
{
printf("File: %ws\n", key.fileName.c_str());
printf("Key: 0x");
for (int i = 0; i < AES_KEYLEN; i++)
{
printf("%02X", key.key[i]);
}
printf("\n\n");
}
return rc;
}
| 26.319502 | 127 | 0.662463 | [
"vector"
] |
f81be673b8d1e838336e2f32988289e9c57e0877 | 819 | cpp | C++ | Visual Studio 2010/Projects/bjarneStroustrupC++PartIV/bjarneStroustrupC++PartIV/Chapter26Drill4.cpp | Ziezi/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | 9 | 2018-10-24T15:16:47.000Z | 2021-12-14T13:53:50.000Z | Visual Studio 2010/Projects/bjarneStroustrupC++PartIV/bjarneStroustrupC++PartIV/Chapter26Drill4.cpp | ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | null | null | null | Visual Studio 2010/Projects/bjarneStroustrupC++PartIV/bjarneStroustrupC++PartIV/Chapter26Drill4.cpp | ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | 7 | 2018-10-29T15:30:37.000Z | 2021-01-18T15:15:09.000Z | /*
TITLE Test Binary_search with strings Chapter26Drill4.cpp
COMMENT
Objective: Repeat the tests with sequence of strings
such as: { Bohr , Darwin , Einstein , Lavoisier , Newton , Turing }
Input: -
Output: -
Author: Chris B. Kirov
Date: 31.05.2017
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "Chapter26Drill4TestedCode.h"
int main()
{
try
{
std::string ifile("Chapter26Drill4Tests.txt");
std::ifstream ifs(ifile.c_str());
if (!ifs)
{
throw std::runtime_error("Can't open file!\n");
}
if (test_all<std::string>(ifs, std::cout))
{
std::cout <<"All tests passed successfully.\n";
}
else
{
std::cout <<"Tests NOT passed !\n";
}
}
catch (std::exception& e)
{
std::cerr << e.what();
}
getchar();
}
| 18.2 | 74 | 0.623932 | [
"vector"
] |
f822aacc7e5686ea42cdae8930b07b061221df4b | 5,430 | cpp | C++ | cbits/python/bind_operator.cpp | twesterhout/nqs-playground | 9fbb65a0631f2a0898effe5bfb1bbb41966cce65 | [
"BSD-3-Clause"
] | 10 | 2019-12-19T07:37:52.000Z | 2021-05-23T11:02:31.000Z | cbits/python/bind_operator.cpp | twesterhout/nqs-playground | 9fbb65a0631f2a0898effe5bfb1bbb41966cce65 | [
"BSD-3-Clause"
] | 4 | 2018-12-05T21:03:15.000Z | 2021-04-09T14:32:55.000Z | cbits/python/bind_operator.cpp | twesterhout/nqs-playground | 9fbb65a0631f2a0898effe5bfb1bbb41966cce65 | [
"BSD-3-Clause"
] | 6 | 2018-10-11T08:03:53.000Z | 2020-04-29T12:24:20.000Z | #include "bind_operator.hpp"
#include "../operator.hpp"
#include "../trim.hpp"
#include <fmt/format.h>
#include <pybind11/complex.h>
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <torch/extension.h>
TCM_NAMESPACE_BEGIN
namespace {
template <class T> auto make_call_function()
{
namespace py = pybind11;
return [](Operator const& self, py::array_t<T, py::array::c_style> x,
std::optional<py::array_t<T, py::array::c_style>> y) {
TCM_CHECK(
x.ndim() == 1, std::domain_error,
fmt::format("x has invalid shape: [{}]; expected a vector",
fmt::join(x.shape(), x.shape() + x.ndim(), ", ")));
auto src =
gsl::span<T const>{x.data(), static_cast<size_t>(x.shape()[0])};
auto out = [&y, n = src.size()]() {
if (y.has_value()) {
TCM_CHECK(
y->ndim() == 1, std::domain_error,
fmt::format(
"y has invalid shape: [{}]; expected a vector",
fmt::join(y->shape(), y->shape() + y->ndim(), ", ")));
return std::move(*y);
}
return py::array_t<T, py::array::c_style>{n};
}();
auto dst = gsl::span<T>{out.mutable_data(),
static_cast<size_t>(out.shape()[0])};
self(src, dst);
return out;
};
}
} // namespace
auto bind_operator(PyObject* _module) -> void
{
namespace py = pybind11;
auto m = py::module{py::reinterpret_borrow<py::object>(_module)};
py::options options;
options.disable_function_signatures();
std::vector<std::string> keep_alive;
#define DOC(str) trim(keep_alive, str)
py::class_<Interaction>(m, "Interaction")
.def(py::init<std::array<std::array<complex_type, 4>, 4>,
std::vector<Interaction::edge_type>>())
.def_property_readonly("is_real", &Interaction::is_real)
.def_property_readonly("max_index", &Interaction::max_index)
.def_property_readonly(
"matrix",
[](Interaction const& self) {
return py::array_t<complex_type, py::array::f_style>{
/*shape=*/{4, 4}, /*data=*/self.matrix()};
})
.def_property_readonly("edges",
[](Interaction const& self) {
using std::begin, std::end;
auto const edges = self.edges();
return std::vector<Interaction::edge_type>{
begin(edges), end(edges)};
})
.def("diag", [](Interaction const& self, bits512 const& spin) {
return self.diag(spin);
});
#if 1
py::class_<Operator, std::shared_ptr<Operator>>(m, "Operator")
.def(py::init<std::vector<Interaction>,
std::shared_ptr<BasisBase const>>())
.def_property_readonly(
"interactions",
[](Operator const& self) {
using std::begin, std::end;
auto is = self.interactions();
return std::vector<Interaction>{begin(is), end(is)};
},
DOC(R"EOF(Returns the list of 'Interaction's)EOF"))
.def_property_readonly("basis", &Operator::basis, DOC(R"EOF(
Returns the Hilbert space basis on which the Operator is defined.)EOF"))
.def_property_readonly("is_real", &Operator::is_real, DOC(R"EOF(
Returns whether the Operator is real.)EOF"))
.def("__call__", make_call_function<float>(), py::arg{"x"}.noconvert(),
py::arg{"y"}.noconvert() = py::none())
.def("__call__", make_call_function<double>(), py::arg{"x"}.noconvert(),
py::arg{"y"}.noconvert() = py::none())
.def("__call__", make_call_function<std::complex<float>>(),
py::arg{"x"}.noconvert(), py::arg{"y"}.noconvert() = py::none())
.def("__call__", make_call_function<std::complex<double>>(),
py::arg{"x"}.noconvert(), py::arg{"y"}.noconvert() = py::none())
.def("to_csr", [](Operator const& self) {
auto [values, indices] = self._to_sparse<double>();
auto const n = values.size(0);
auto const csr_matrix =
py::module::import("scipy.sparse").attr("csr_matrix");
auto data = py::cast(values).attr("numpy")();
auto row_indices =
py::cast(torch::narrow(indices, /*dim=*/1, /*start=*/0,
/*length=*/1))
.attr("squeeze")()
.attr("numpy")();
auto col_indices =
py::cast(torch::narrow(indices, /*dim=*/1, /*start=*/1,
/*length=*/1))
.attr("squeeze")()
.attr("numpy")();
auto const* basis =
static_cast<SmallSpinBasis const*>(self.basis().get());
return csr_matrix(
std::make_tuple(data,
std::make_tuple(row_indices, col_indices)),
std::make_tuple(basis->number_states(),
basis->number_states()));
});
#endif
#undef DOC
}
TCM_NAMESPACE_END
| 41.136364 | 84 | 0.505525 | [
"object",
"shape",
"vector"
] |
f82884f68cea1e963a43e0eb76aac85934cf367a | 7,705 | cpp | C++ | test/compliance.cpp | ningfei/charls | 071958cd855c76ed9b5831b116aa9c07ebf0fd2b | [
"BSD-3-Clause"
] | null | null | null | test/compliance.cpp | ningfei/charls | 071958cd855c76ed9b5831b116aa9c07ebf0fd2b | [
"BSD-3-Clause"
] | null | null | null | test/compliance.cpp | ningfei/charls | 071958cd855c76ed9b5831b116aa9c07ebf0fd2b | [
"BSD-3-Clause"
] | null | null | null | //
// (C) Jan de Vaan 2007-2010, all rights reserved. See the accompanying "License.txt" for licensed use.
//
#include "compliance.h"
#include "util.h"
#include "../src/charls.h"
#include <iostream>
#include <vector>
#include <cstring>
using namespace charls;
namespace
{
void Triplet2Planar(std::vector<uint8_t>& rgbyte, Size size)
{
std::vector<uint8_t> rgbytePlanar(rgbyte.size());
const size_t cbytePlane = static_cast<size_t>(size.cx) * size.cy;
for (size_t index = 0; index < cbytePlane; index++)
{
rgbytePlanar[index] = rgbyte[index * 3 + 0];
rgbytePlanar[index + 1 * cbytePlane] = rgbyte[index * 3 + 1];
rgbytePlanar[index + 2 * cbytePlane] = rgbyte[index * 3 + 2];
}
std::swap(rgbyte, rgbytePlanar);
}
bool VerifyEncodedBytes(const void* uncompressedData, size_t uncompressedLength, const void* compressedData, size_t compressedLength)
{
JlsParameters info = JlsParameters();
auto error = JpegLsReadHeader(compressedData, compressedLength, &info, nullptr);
if (error != ApiResult::OK)
return false;
std::vector<uint8_t> ourEncodedBytes(compressedLength + 16);
size_t bytesWriten;
error = JpegLsEncode(ourEncodedBytes.data(), ourEncodedBytes.size(), &bytesWriten, uncompressedData, uncompressedLength, &info, nullptr);
if (error != ApiResult::OK)
return false;
for (size_t i = 0; i < compressedLength; ++i)
{
if (static_cast<const uint8_t*>(compressedData)[i] != ourEncodedBytes[i])
{
return false;
}
}
return true;
}
void TestCompliance(const uint8_t* compressedBytes, size_t compressedLength, const uint8_t* rgbyteRaw, size_t cbyteRaw, bool bcheckEncode)
{
JlsParameters info{};
auto err = JpegLsReadHeader(compressedBytes, compressedLength, &info, nullptr);
Assert::IsTrue(err == ApiResult::OK);
if (bcheckEncode)
{
Assert::IsTrue(VerifyEncodedBytes(rgbyteRaw, cbyteRaw, compressedBytes, compressedLength));
}
std::vector<uint8_t> rgbyteOut(static_cast<size_t>(info.height) *info.width * ((info.bitsPerSample + 7) / 8) * info.components);
err = JpegLsDecode(rgbyteOut.data(), rgbyteOut.size(), compressedBytes, compressedLength, nullptr, nullptr);
Assert::IsTrue(err == ApiResult::OK);
if (info.allowedLossyError == 0)
{
for (size_t i = 0; i < cbyteRaw; ++i)
{
if (rgbyteRaw[i] != rgbyteOut[i])
{
Assert::IsTrue(false);
break;
}
}
}
}
void DecompressFile(const char* strNameEncoded, const char* strNameRaw, int ioffs, bool bcheckEncode = true)
{
std::cout << "Conformance test:" << strNameEncoded << "\n\r";
std::vector<uint8_t> rgbyteFile;
if (!ReadFile(strNameEncoded, &rgbyteFile))
return;
JlsParameters params{};
if (JpegLsReadHeader(rgbyteFile.data(), rgbyteFile.size(), ¶ms, nullptr) != ApiResult::OK)
{
Assert::IsTrue(false);
return;
}
std::vector<uint8_t> rgbyteRaw;
if (!ReadFile(strNameRaw, &rgbyteRaw, ioffs))
return;
if (params.bitsPerSample > 8)
{
FixEndian(&rgbyteRaw, false);
}
if (params.interleaveMode == InterleaveMode::None && params.components == 3)
{
Triplet2Planar(rgbyteRaw, Size(params.width, params.height));
}
TestCompliance(rgbyteFile.data(), rgbyteFile.size(), rgbyteRaw.data(), rgbyteRaw.size(), bcheckEncode);
}
////uint8_t palettisedDataH10[] = {
//// 0xFF, 0xD8, //Start of image (SOI) marker
//// 0xFF, 0xF7, //Start of JPEG-LS frame (SOF 55) marker – marker segment follows
//// 0x00, 0x0B, //Length of marker segment = 11 bytes including the length field
//// 0x02, //P = Precision = 2 bits per sample
//// 0x00, 0x04, //Y = Number of lines = 4
//// 0x00, 0x03, //X = Number of columns = 3
//// 0x01, //Nf = Number of components in the frame = 1
//// 0x01, //C1 = Component ID = 1 (first and only component)
//// 0x11, //Sub-sampling: H1 = 1, V1 = 1
//// 0x00, //Tq1 = 0 (this field is always 0)
////
//// 0xFF, 0xF8, //LSE – JPEG-LS preset parameters marker
//// 0x00, 0x11, //Length of marker segment = 17 bytes including the length field
//// 0x02, //ID = 2, mapping table
//// 0x05, //TID = 5 Table identifier (arbitrary)
//// 0x03, //Wt = 3 Width of table entry
//// 0xFF, 0xFF, 0xFF, //Entry for index 0
//// 0xFF, 0x00, 0x00, //Entry for index 1
//// 0x00, 0xFF, 0x00, //Entry for index 2
//// 0x00, 0x00, 0xFF, //Entry for index 3
////
//// 0xFF, 0xDA, //Start of scan (SOS) marker
//// 0x00, 0x08, //Length of marker segment = 8 bytes including the length field
//// 0x01, //Ns = Number of components for this scan = 1
//// 0x01, //C1 = Component ID = 1
//// 0x05, //Tm 1 = Mapping table identifier = 5
//// 0x00, //NEAR = 0 (near-lossless max error)
//// 0x00, //ILV = 0 (interleave mode = non-interleaved)
//// 0x00, //Al = 0, Ah = 0 (no point transform)
//// 0xDB, 0x95, 0xF0, //3 bytes of compressed image data
//// 0xFF, 0xD9 //End of image (EOI) marker
////};
const uint8_t rgbyte[] = { 0, 0, 90, 74,
68, 50, 43, 205,
64, 145, 145, 145,
100, 145, 145, 145};
////const uint8_t rgbyteComp[] = { 0xFF, 0xD8, 0xFF, 0xF7, 0x00, 0x0B, 0x08, 0x00, 0x04, 0x00, 0x04, 0x01, 0x01, 0x11, 0x00, 0xFF, 0xDA, 0x00, 0x08, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00,
////0xC0, 0x00, 0x00, 0x6C, 0x80, 0x20, 0x8E,
////0x01, 0xC0, 0x00, 0x00, 0x57, 0x40, 0x00, 0x00, 0x6E, 0xE6, 0x00, 0x00, 0x01, 0xBC, 0x18, 0x00,
////0x00, 0x05, 0xD8, 0x00, 0x00, 0x91, 0x60, 0xFF, 0xD9};
} // namespace
void TestSampleAnnexH3()
{
////Size size = Size(4,4);
std::vector<uint8_t> vecRaw(16);
memcpy(vecRaw.data(), rgbyte, 16);
//// TestJls(vecRaw, size, 8, 1, ILV_NONE, rgbyteComp, sizeof(rgbyteComp), false);
}
void TestColorTransforms_HpImages()
{
DecompressFile("test/jlsimage/banny_normal.jls", "test/jlsimage/banny.ppm", 38, false);
DecompressFile("test/jlsimage/banny_HP1.jls", "test/jlsimage/banny.ppm", 38, false);
DecompressFile("test/jlsimage/banny_HP2.jls", "test/jlsimage/banny.ppm", 38, false);
DecompressFile("test/jlsimage/banny_HP3.jls", "test/jlsimage/banny.ppm", 38, false);
}
void TestConformance()
{
// Test 1
DecompressFile("test/conformance/T8C0E0.JLS", "test/conformance/TEST8.PPM",15);
// Test 2
DecompressFile("test/conformance/T8C1E0.JLS", "test/conformance/TEST8.PPM",15);
// Test 3
DecompressFile("test/conformance/T8C2E0.JLS", "test/conformance/TEST8.PPM", 15);
// Test 4
DecompressFile("test/conformance/T8C0E3.JLS", "test/conformance/TEST8.PPM",15);
// Test 5
DecompressFile("test/conformance/T8C1E3.JLS", "test/conformance/TEST8.PPM",15);
// Test 6
DecompressFile("test/conformance/T8C2E3.JLS", "test/conformance/TEST8.PPM",15);
// Test 7
// Test 8
// Test 9
DecompressFile("test/conformance/T8NDE0.JLS", "test/conformance/TEST8BS2.PGM",15);
// Test 10
DecompressFile("test/conformance/T8NDE3.JLS", "test/conformance/TEST8BS2.PGM",15);
// Test 11
DecompressFile("test/conformance/T16E0.JLS", "test/conformance/TEST16.PGM",16);
// Test 12
DecompressFile("test/conformance/T16E3.JLS", "test/conformance/TEST16.PGM",16);
// additional, Lena compressed with other codec (UBC?), vfy with CharLS
DecompressFile("test/lena8b.jls", "test/lena8b.raw",0);
}
| 34.397321 | 189 | 0.623491 | [
"vector",
"transform"
] |
f82c181f42f4b44a16a9c2f71cd69350ca7a3d5c | 5,826 | hpp | C++ | Support/Modules/PropertyOperations/DynamicBuiltInPropertyDefinitionContainer.hpp | graphisoft-python/TextEngine | 20c2ff53877b20fdfe2cd51ce7abdab1ff676a70 | [
"Apache-2.0"
] | 3 | 2019-07-15T10:54:54.000Z | 2020-01-25T08:24:51.000Z | Support/Modules/PropertyOperations/DynamicBuiltInPropertyDefinitionContainer.hpp | graphisoft-python/GSRoot | 008fac2c6bf601ca96e7096705e25b10ba4d3e75 | [
"Apache-2.0"
] | null | null | null | Support/Modules/PropertyOperations/DynamicBuiltInPropertyDefinitionContainer.hpp | graphisoft-python/GSRoot | 008fac2c6bf601ca96e7096705e25b10ba4d3e75 | [
"Apache-2.0"
] | 1 | 2020-09-26T03:17:22.000Z | 2020-09-26T03:17:22.000Z | // Contact person: KiP
#ifndef DYNAMIC_BUILTIN_PROPERTY_DEFINITION_CONTAINER_HPP
#define DYNAMIC_BUILTIN_PROPERTY_DEFINITION_CONTAINER_HPP
#pragma once
// === Includes ========================================================================================================
// from Property"
#include "OrderedAssociationIterator.hpp"
// form PropertyOperations
#include "PropertyOperationsExport.hpp"
#include "PropertyOperationsTypes.hpp"
// from VBElements
#include "ProjectTypes.hpp"
// =====================================================================================================================
namespace Property {
class PROPERTY_OPERATIONS_DLL_EXPORT DynamicBuiltInPropertyDefinitionContainer : public ODB::Object
{
DECLARE_DYNAMIC_CLASS_INFO (DynamicBuiltInPropertyDefinitionContainer)
private:
class PROPERTY_OPERATIONS_DLL_EXPORT IsolatedState : public ODB::Object::IsolatedState
{
public:
virtual ~IsolatedState ();
};
// ... iterator ....................................................................................................
public:
typedef OrderedAssociationConstIterator<DynamicBuiltInPropertyDefinitionGroup> ConstIterator;
typedef OrderedAssociationIterator<DynamicBuiltInPropertyDefinitionGroup> Iterator;
ConstIterator Begin () const;
Iterator Begin ();
// ... constructors and destructor .................................................................................
public:
DynamicBuiltInPropertyDefinitionContainer ();
virtual ~DynamicBuiltInPropertyDefinitionContainer ();
virtual DynamicBuiltInPropertyDefinitionContainer* Clone () const override;
// ... query methods ...............................................................................................
public:
bool IsEmpty () const;
bool ContainsGroup (const GS::Guid& guid) const;
bool ContainsGroup (const PropertyDefinitionGroupUserId& userId) const;
bool ContainsDefinition (const GS::Guid& guid) const;
bool ContainsDefinition (const PropertyDefinitionUserId& userId) const;
DynamicBuiltInPropertyDefinitionGroupConstRef GetPropertyDefinitionGroup (const GS::Guid& guid) const;
DynamicBuiltInPropertyDefinitionGroupConstRef GetPropertyDefinitionGroup (const PropertyDefinitionGroupUserId& userId) const;
DynamicBuiltInPropertyDefinitionConstPtr GetPropertyDefinition (const GS::Guid& guid) const;
DynamicBuiltInPropertyDefinitionConstPtr GetPropertyDefinition (const PropertyDefinitionUserId& userId) const;
void EnumerateGroups (const std::function<void (const DynamicBuiltInPropertyDefinitionGroupConstRef&)>& processor) const;
void EnumerateDefinitions (const std::function<void (const DynamicBuiltInPropertyDefinitionConstPtr&)>& processor) const;
// ... modify container ............................................................................................
public:
void AddPropertyDefinitionGroup (const DynamicBuiltInPropertyDefinitionGroupRef& groupToAdd);
// ... static helper methods to access associations ................................................................
public:
static bool HasContainer (const DynamicBuiltInPropertyDefinitionGroupConstRef& propertyDefinitionGroup);
static DynamicBuiltInPropertyDefinitionContainerConstRef GetConstContainer (const DynamicBuiltInPropertyDefinitionGroupConstRef& propertyDefinitionGroup);
static DynamicBuiltInPropertyDefinitionContainerRef GetContainer (const DynamicBuiltInPropertyDefinitionGroupRef& propertyDefinitionGroup);
static DynamicBuiltInPropertyDefinitionContainerConstRef GetConstContainer (const EDB::ProjectConstRef& project);
static EDB::ProjectConstRef GetConstProject (const DynamicBuiltInPropertyDefinitionContainerConstRef& container);
static void InitializeContainer (const EDB::ProjectRef& project, const std::function<void (DynamicBuiltInPropertyDefinitionContainerRef&)>& createAdditionalGroups);
// ... read / write methods (Object interface) .....................................................................
public:
virtual GSErrCode Read (GS::IChannel& ic) override;
virtual GSErrCode Write (GS::OChannel& oc) const override;
virtual GSErrCode ReadXML (GS::XMLIChannel& ic) override;
virtual GSErrCode WriteXML (GS::XMLOChannel& oc) const override;
// ... transaction management methods ..............................................................................
public:
virtual GSErrCode StoreIsolatedState (ODB::Object::IsolatedState* isolatedState) const override;
virtual GSErrCode RestoreIsolatedState (const ODB::Object::IsolatedState* isolatedState) override;
virtual void Isolate () override;
virtual ODB::Object::IsolatedState* CreateIsolatedState () const override;
virtual USize GetIsolatedSize () const override;
virtual GSErrCode ReadIsolatedState (GS::IChannel& ic) override;
virtual GSErrCode WriteIsolatedState (GS::OChannel& oc) const override;
private:
GSErrCode ReadIsolatedStateVersion1 (GS::IChannel& ic, const GS::InputFrame& frame);
GSErrCode WriteIsolatedStateVersion1 (GS::OChannel& oc, const GS::OutputFrame& frame) const;
// ... disabled methods ............................................................................................
private:
DynamicBuiltInPropertyDefinitionContainer (const DynamicBuiltInPropertyDefinitionContainer&);
DynamicBuiltInPropertyDefinitionContainer& operator= (const DynamicBuiltInPropertyDefinitionContainer&);
};
PROPERTY_OPERATIONS_DLL_EXPORT
PropertyDefinitionContainerConstPtr CreateAdapter (const DynamicBuiltInPropertyDefinitionContainerConstRef& container);
}
#endif
| 52.486486 | 176 | 0.662547 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.