blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c0d3a7b7beeb10984df7217084d3ff0c47e77fd9 | e3e6c28a67233c54ec5bde4cc066d30cba78b71e | /course_cpp_ternsorrt/course3/13.func_pass_pointer.cpp | 9631c652005649b78e81e4606efadd509d368949 | [] | no_license | scchy/My_Learn | 9c10d25ab95fd5d893383ad13ec367924144c36a | 122c43776c2b10bd5f9b9a299bdbf9739173ad46 | refs/heads/master | 2023-08-17T03:48:59.356663 | 2023-08-08T02:14:25 | 2023-08-08T02:14:25 | 225,583,289 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 402 | cpp | #include <iostream>
#include <vector>
#include <string>
using namespace std;
void double_data(int *int_ptr);
int main(){
int v {20};
cout << "V = " << v << endl;
double_data(&v);
cout << "V = " << v << endl;
int *int_ptr {nullptr};
int_ptr = &v;
double_data(int_ptr);
cout << "V = " << v << endl;
return 0;
}
void double_data(int *int_ptr){
*int_ptr *= 2;
} | [
"296294812@qq.com"
] | 296294812@qq.com |
209865eb429800b6bfc5cf7c965fe25e970490fa | c0e4bb4c2f2a37ed5c48ce1a78f858f9bc68b948 | /src/Serialize/JsonParser.h | d939c85cef3b3088d7dde3a5aedf54b1bf7ab8d6 | [
"LicenseRef-scancode-public-domain"
] | permissive | SeanGo/ThorsSerializer | 7774bea0416ffe44e744316aada9afcf4950c09b | b90e31a68b3db5a706f3d87937fe1251cc522894 | refs/heads/master | 2021-01-21T10:29:58.908733 | 2017-01-22T09:46:36 | 2017-01-22T09:46:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,521 | h | #ifndef THORS_ANVIL_SERIALIZE_JSON_PARSER_H
#define THORS_ANVIL_SERIALIZE_JSON_PARSER_H
/*
* JsonParser<T>
* This is used in conjunction with JsonPrinter<T>
*
* Together these provide an implementation of:
* the ParserInterface for type T
* and PrinterInterface for type T
*
* These Interfaces are used by Serializer and DeSerializer (see Serialize.h)
*
* It uses ThorsAnvil::Serialize::Traits<T> to know what objects to pull from the stream.
* For arrays order is important.
* For Objects the order of elements is not important. It looks up the key in the Traits<T>
* information to understand which member is being de-serialized but unspecified elements
* will not cause an error.
*/
#include "Serialize.h"
#include "JsonLexer.h"
#include <istream>
#include <string>
#include <vector>
namespace ThorsAnvil
{
namespace Serialize
{
class JsonParser: public ParserInterface
{
enum State {Error, Init, OpenM, Key, Colon, ValueM, CommaM, CloseM, OpenA, ValueA, CommaA, CloseA, ValueD, Done};
JsonLexerFlexLexer lexer;
std::vector<State> parrentState;
State currentEnd;
State currentState;
bool started;
std::string getString();
template<typename T>
T scan();
public:
JsonParser(std::istream& stream);
virtual ParserToken getNextToken() override;
virtual std::string getKey() override;
virtual void getValue(short int& value) override;
virtual void getValue(int& value) override;
virtual void getValue(long int& value) override;
virtual void getValue(long long int& value) override;
virtual void getValue(unsigned short int& value) override;
virtual void getValue(unsigned int& value) override;
virtual void getValue(unsigned long int& value) override;
virtual void getValue(unsigned long long int& value) override;
virtual void getValue(float& value) override;
virtual void getValue(double& value) override;
virtual void getValue(long double& value) override;
virtual void getValue(bool& value) override;
virtual void getValue(std::string& value) override;
};
}
}
#endif
| [
"Loki.Astari@gmail.com"
] | Loki.Astari@gmail.com |
0f17eaeb1d4e5e7b02630dac7e72a67c849ac711 | 2c8044db6c97ab2e98ba45269ed8d24e0984ae18 | /AlgorithmsandDataStructures/8thLab/G(2Sat).cpp | a391ee12e5d332ffd654e1c3ce717f0a4445ae57 | [
"MIT"
] | permissive | Retnirps/ITMO | 1b2f5363b99a69f518d03e03c8d1099e97b1d65f | 29db54d96afef0558550471c58f695c962e1f747 | refs/heads/master | 2023-05-26T23:06:53.533352 | 2021-06-14T21:31:18 | 2021-06-14T21:31:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,634 | cpp | #include <iostream>
#include <vector>
#include <map>
int n, m, amount;
std::vector <std::vector <int>> a;
std::vector <std::vector <int>> c;
std::vector <int> ans, came;
std::vector <std::string> revb;
std::map <std::string, int> b;
void dfs(int i)
{
came[i] = 1;
for (auto j : a[i])
{
if (!came[j])
{
dfs(j);
}
}
ans.push_back(i);
}
void dfs2(int i)
{
came[i] = amount;
for (auto j : c[i])
{
if (came[j] == 0)
{
dfs2(j);
}
}
}
int main()
{
std::cin >> n >> m;
a.resize(2 * n);
revb.resize(n);
c.resize(2 * n);
came.resize(2 * n, 0);
for (int i = 0; i < n; ++i)
{
std::string name;
std::cin >> name;
b[name] = i;
revb[i] = name;
}
for (int i = 0; i < m; ++i)
{
std::string first, temp, second;
std::cin >> first >> temp >> second;
bool sign1 = 1, sign2 = 1;
if (first[0] == '-')
{
sign1 = 0;
}
first.erase(first.begin());
if (second[0] == '-')
{
sign2 = 0;
}
second.erase(second.begin());
if (sign1)
{
if (sign2)
{
a[b[first]].push_back(b[second]);
a[b[second] + n].push_back(b[first] + n);
c[b[second]].push_back(b[first]);
c[b[first] + n].push_back(b[second] + n);
} else
{
a[b[first]].push_back(b[second] + n);
a[b[second]].push_back(b[first] + n);
c[b[second] + n].push_back(b[first]);
c[b[first] + n].push_back(b[second]);
}
} else if (sign2)
{
a[b[first] + n].push_back(b[second]);
a[b[second] + n].push_back(b[first]);
c[b[second]].push_back(b[first] + n);
c[b[first]].push_back(b[second] + n);
} else
{
a[b[first] + n].push_back(b[second] + n);
a[b[second]].push_back(b[first]);
c[b[first]].push_back(b[second]);
c[b[second] + n].push_back(b[first] + n);
}
}
/*for (int i = 0; i < 2 * n; ++i)
{
std::cout << i << ": ";
for (auto j : a[i])
{
std::cout << j << ' ';
}
std::cout << '\n';
}
for (int i = 0; i < 2 * n; ++i)
{
std::cout << i << ": ";
for (auto j : c[i])
{
std::cout << j << ' ';
}
std::cout << '\n';
}*/
for (int i = 0; i < 2 * n; ++i)
{
if (!came[i])
{
dfs(i);
}
}
/*for (int i = 0; i < 2 * n; ++i)
{
std::cout << ans[i] << ' ';
}
std::cout << '\n';*/
came.assign(2 * n, 0);
amount = 0;
for (int i = 2 * n - 1; i >= 0; --i)
{
if (came[ans[i]] == 0)
{
++amount;
dfs2(ans[i]);
}
}
amount = 0;
ans.clear();
for (int i = 0; i < n; ++i)
{
if (came[i] > came[i + n])
{
++amount;
ans.push_back(i);
} else if (came[i] == came[i + n])
{
std::cout << -1 << '\n';
return 0;
}
}
std::cout << amount << '\n';
for (auto i : ans)
{
std::cout << revb[i] << '\n';
}
}
| [
"mihpihnaty@yandex.com"
] | mihpihnaty@yandex.com |
626ab942ea35647780587013fd1384d513705b54 | 9b1ebfac9e2a1ec0991691347973b9eb8c5962de | /assignment6/appoitments.cpp | 5e88a55cae55f0e078bb637a8520cc0ce5d4bf13 | [] | no_license | YashRathore-los/CP_CIPHERSCHOOLS | 4c73080d5a091b2a6e2a9149c71580ad6f361565 | 75e1a54acd9813d821cebf5ac32dd2e0968f0212 | refs/heads/main | 2023-03-09T20:00:03.400771 | 2021-02-23T17:24:32 | 2021-02-23T17:24:32 | 338,598,571 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 532 | cpp | class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>>& v) {
if (v.size() < 2) return 0;
int count = 0;
sort(v.begin(), v.end(), [&](vector<int> &a, vector<int> &b) {
return a[1] < b[1];
});
int i = 0, j = 1;
while (j < v.size()) {
if (v[i][1] <= v[j][0]) {
i = j;
}
else {
count++;
}
j++;
}
return count;
}
}; | [
"noreply@github.com"
] | noreply@github.com |
3b81a4c7b953750b7745febfcd7a4f3a1369b725 | 03807da4b5a9f2cc232e5be57e8b21ff9a292748 | /.history/helloworld_20210409013840.cpp | ae765f30039cab00775ebf6c486e35aebb7b7b61 | [] | no_license | damiancyk/ShipGame | 701f788fbd12c86f2f334d03f522826e9fc21a6b | 4c27eeae93c33c8ebcc4e208bbb7d034f2c8f40a | refs/heads/main | 2023-04-16T12:55:42.746231 | 2021-04-09T00:23:15 | 2021-04-09T01:35:52 | 356,084,794 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 821 | cpp | #include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef uint32_t coord;
struct position
{
coord x;
coord y;
};
struct ship
{
struct position start; /* punkt statku o najmniejszych współrzędnych */
unsigned int size; /* długość statku */
int direction; /* orientacja pionowa lub pozioma*/
};
char line[100];
void readData();
int main()
{
cout << "-==STATKI==-" << endl;
readData();
}
void readData()
{
FILE *filePointer;
int bufferLength = 255;
char buffer[bufferLength];
filePointer = fopen("ship-1.txt", "r");
while (fgets(buffer, bufferLength, filePointer))
{
printf("%s\n", buffer);
}
fclose(filePointer);
}
ship readShip(char line[])
{
ship s;
return s;
}
void displayBoard()
{
} | [
"damiancyk@gmail.com"
] | damiancyk@gmail.com |
cfb1c73602725c44947e4f73c26b03eb15ce850a | ef1ae7410cc520bdfb9e056799115692769d6910 | /RDKIT_CSource/GraphMol/DistGeomHelpers/BoundsMatrixBuilder.cpp | e9feba79b950396edda73fcf5f54836c82cfb798 | [] | no_license | hjkulik/rdklol | b6ad7cb1db52851a75ea97046e2b90e39077eab3 | 362b14b7232de9e3db4f6595767505468fc16ff9 | refs/heads/master | 2020-04-15T22:50:05.219584 | 2015-07-09T15:51:31 | 2015-07-09T15:51:31 | 30,101,567 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 59,299 | cpp | // $Id$
//
// Copyright (C) 2004-2009 Greg Landrum and Rational Discovery LLC
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include <GraphMol/RDKitBase.h>
#include <DistGeom/BoundsMatrix.h>
#include "BoundsMatrixBuilder.h"
#include <GraphMol/ForceFieldHelpers/UFF/AtomTyper.h>
#include <ForceField/UFF/BondStretch.h>
#include <Geometry/Utils.h>
#include <RDGeneral/utils.h>
#include <RDGeneral/RDLog.h>
#include <RDBoost/Exceptions.h>
#include <Numerics/SymmMatrix.h>
#include <DistGeom/TriangleSmooth.h>
#include <boost/dynamic_bitset.hpp>
#include <algorithm>
const double DIST12_DELTA = 0.01;
const double ANGLE_DELTA = 0.0837;
const double RANGLE_DELTA = 0.0837; // tolerance for bond angles
const double TANGLE_DELTA = 0.0837; // tolerance for torsion angle
const double DIST13_TOL = 0.04;
const double GEN_DIST_TOL = 0.06; // a general distance tolerance
const double DIST15_TOL = 0.08;
const double VDW_SCALE_15 = 0.7;
const double MAX_UPPER = 1000.0;
#include <map>
namespace RDKit {
namespace DGeomHelpers {
// forward declarations:
typedef boost::shared_ptr<RDNumeric::IntSymmMatrix> SymmIntMatPtr;
typedef boost::shared_ptr<RDNumeric::DoubleSymmMatrix> SymmDoubleMatPtr;
typedef boost::dynamic_bitset<> BIT_SET;
//! Bunch of functions to set distance bound based on topology
typedef std::map<int, double> INT_DOUBLE_MAP;
typedef INT_DOUBLE_MAP::const_iterator INT_DOUBLE_MAP_CI;
typedef std::vector<long int> LINT_VECT;
//! A structure used to store planar 14 paths - cis/trans
struct Path14Configuration {
unsigned int bid1, bid2, bid3;
typedef enum {
CIS = 0,
TRANS,
OTHER,
} Path14Type;
Path14Type type;
};
typedef std::vector<Path14Configuration> PATH14_VECT;
typedef PATH14_VECT::iterator PATH14_VECT_I;
typedef PATH14_VECT::const_iterator PATH14_VECT_CI;
class ComputedData {
public:
ComputedData(unsigned int nAtoms, unsigned int nBonds) {
bondLengths.resize(nBonds);
RDNumeric::IntSymmMatrix *bAdj = new RDNumeric::IntSymmMatrix(nBonds, -1);
bondAdj.reset(bAdj);
RDNumeric::DoubleSymmMatrix *bAngles = new RDNumeric::DoubleSymmMatrix(nBonds, -1.0);
bondAngles.reset(bAngles);
cisPaths.resize(nBonds*nBonds*nBonds);
transPaths.resize(nBonds*nBonds*nBonds);
set15Atoms.resize(nAtoms*nAtoms);
}
~ComputedData(){}
DOUBLE_VECT bondLengths;
SymmIntMatPtr bondAdj; // bond adjacency matrix
SymmDoubleMatPtr bondAngles;
PATH14_VECT paths14;
BIT_SET cisPaths;
BIT_SET transPaths;
BIT_SET set15Atoms;
};
//! Set 1-2 distance bounds for between atoms in a molecule
/*!
These are mostly bond lengths obtained from UFF parameters and then
adjusted by a small tolerance to set the upper and lower limits
\param mol The molecule of interest
\param mmat Bounds matrix to which the bounds are written
\param accumData Used to store the data that have been calculated so far
about the molecule
*/
void set12Bounds(const ROMol &mol, DistGeom::BoundsMatPtr mmat,
ComputedData &accumData);
//! Set 1-3 distance bounds for atoms in a molecule
/*!
These are computed using bond angles and bond lengths. There are special
cases here, in particular for 3, 4, and 5 membered rings. Special attention
is also paid to fused ring ring systems, when setting bounds on atoms that
have an atom between that is shared by multiple rings.
\param mol Molecule of interest
\param mmat Bounds matrix to which the bounds are written
\param accumData Used to store the data that have been calculated so far
about the molecule
<b>Procedure</b>
All 1-3 distances within all simple rings are first dealt with, while keeping track of
any atoms that are visited twice; these are the atoms that are part of multiple simple rings.
Then all other 1-3 distance are set while treating 1-3 atoms that have a ring atom in
between differently from those that have a non-ring atom in between.
*/
void set13Bounds(const ROMol &mol, DistGeom::BoundsMatPtr mmat,
ComputedData &accumData);
//! Set 1-4 distance bounds for atoms in a molecule
/*!
These are computed using the range of allowed torsion angles. There are several
special casses and the rest are computed using 0 and 180 deg as the min.
and max. torsion angles. The special cases deal with ring systems, double bonds
with cis-trans specifications, and a few special sub-structures
\param mol Molecule of interest
\param mmat Bounds matrix to which the bounds are written
\param accumData Used to store the data that have been calculated so far
about the molecule
<b>Procedure</b>
As in the case of 1-3 distances 1-4 distance that are part of simple rings are
first dealt with. The remaining 1-4 cases are dealt with while paying attention
to the special cases.
*/
void set14Bounds(const ROMol &mol, DistGeom::BoundsMatPtr mmat,
ComputedData &accumData);
//! Set 1-5 distance bounds for atoms in a molecule
/*!
This is an optional call that recognizes a variety of special cases.
\param mol Molecule of interest
\param mmat Bounds matrix to which the bounds are written
\param accumData Used to store the data that have been calculated so far
about the molecule
*/
void set15Bounds(const ROMol &mol, DistGeom::BoundsMatPtr mmat,
ComputedData &accumData,double *distMatrix);
//! Set lower distance bounds based on VDW radii for atoms that are not covered by
//! other bounds (1-2, 1-3, 1-4, or 1-5)
/*!
\param mol Molecule of interest
\param mmat Bounds matrix to which the bounds are written
\param useTopolScaling If true scale the sum of the vdW radii while setting lower bounds
so that a smaller value (0.7*(vdw1 + vdw2) ) is used for paths
that are less 5 bonds apart.
*/
void setLowerBoundVDW(const ROMol &mol, DistGeom::BoundsMatPtr mmat, bool useTopolScaling=true);
}
}
namespace RDKit {
namespace DGeomHelpers {
void _checkAndSetBounds(unsigned int i, unsigned int j,
double lb, double ub,
DistGeom::BoundsMatPtr mmat) {
// get the exisiting bounds
double clb = mmat->getLowerBound(i, j);
double cub = mmat->getUpperBound(i, j);
CHECK_INVARIANT(ub>lb, "upper bound not greater than lower bound");
CHECK_INVARIANT(lb>DIST12_DELTA || clb>DIST12_DELTA, "bad lower bound");
if (clb <= DIST12_DELTA) {
mmat->setLowerBound(i, j, lb);
} else {
if ((lb < clb) && (lb > DIST12_DELTA) ){
mmat->setLowerBound(i, j, lb); // conservative bound setting
}
}
if (cub >= MAX_UPPER) { //FIX this
mmat->setUpperBound(i, j, ub);
} else {
if ((ub > cub) && (ub < MAX_UPPER)) {
mmat->setUpperBound(i, j, ub);
}
}
}
void set12Bounds(const ROMol &mol, DistGeom::BoundsMatPtr mmat, ComputedData &accumData) {
unsigned int npt = mmat->numRows();
CHECK_INVARIANT(npt == mol.getNumAtoms(), "Wrong size metric matrix");
CHECK_INVARIANT(accumData.bondLengths.size() >= mol.getNumBonds(), "Wrong size accumData");
bool foundAll;
UFF::AtomicParamVect atomParams;
boost::tie(atomParams,foundAll)= UFF::getAtomTypes(mol);
CHECK_INVARIANT(atomParams.size()==mol.getNumAtoms(),"parameter vector size mismatch");
ROMol::ConstBondIterator bi;
unsigned int begId, endId;
double bl;
for (bi = mol.beginBonds(); bi != mol.endBonds(); bi++) {
begId = (*bi)->getBeginAtomIdx();
endId = (*bi)->getEndAtomIdx();
if(atomParams[begId] && atomParams[endId]){
bl = ForceFields::UFF::Utils::calcBondRestLength((*bi)->getBondTypeAsDouble(),
atomParams[begId], atomParams[endId]);
accumData.bondLengths[(*bi)->getIdx()] = bl;
mmat->setUpperBound(begId, endId, bl + DIST12_DELTA);
mmat->setLowerBound(begId, endId, bl - DIST12_DELTA);
} else {
// we don't have parameters for one of the atoms... so we're forced to use
// very crude bounds:
double vw1 = PeriodicTable::getTable()->getRvdw(mol.getAtomWithIdx(begId)->getAtomicNum());
double vw2 = PeriodicTable::getTable()->getRvdw(mol.getAtomWithIdx(endId)->getAtomicNum());
double bl=(vw1+vw2)/2;
accumData.bondLengths[(*bi)->getIdx()] = bl;
mmat->setUpperBound(begId, endId, 1.5*bl);
mmat->setLowerBound(begId, endId, .5*bl );
}
}
}
void setLowerBoundVDW(const ROMol &mol, DistGeom::BoundsMatPtr mmat, bool useTopolScaling,
double *dmat) {
unsigned int npt = mmat->numRows();
PRECONDITION(npt == mol.getNumAtoms(), "Wrong size metric matrix");
unsigned int i, j;
double vw1, vw2;
for (i = 1; i < npt; i++) {
vw1 = PeriodicTable::getTable()->getRvdw(mol.getAtomWithIdx(i)->getAtomicNum());
for (j = 0; j < i; j++) {
vw2 = PeriodicTable::getTable()->getRvdw(mol.getAtomWithIdx(j)->getAtomicNum());
if (mmat->getLowerBound(i,j) < DIST12_DELTA) {
// ok this is what we are going to do
// - for atoms that are 4 or 5 bonds apart (15 or 16 distances), we will scale
// the sum of the VDW radii so that the atoms can get closer
// For 15 we will use VDW_SCALE_15 and for 16 we will use 1 - 0.5*VDW_SCALE_15
// - for all other pairs of atoms more than 5 bonds apart we use the sum of the VDW radii
// as the lower bound
if (dmat[i*npt + j] == 4.0) {
mmat->setLowerBound(i,j, VDW_SCALE_15*(vw1+vw2));
} else if (dmat[i*npt + j] == 5.0) {
mmat->setLowerBound(i,j, (VDW_SCALE_15 + 0.5*(1.0-VDW_SCALE_15))*(vw1+vw2));
} else {
mmat->setLowerBound(i,j, (vw1+vw2));
}
}
}
}
}
void _set13BoundsHelper(unsigned int aid1, unsigned int aid, unsigned int aid3,
double angle, const ComputedData &accumData, DistGeom::BoundsMatPtr mmat,
const ROMol &mol) {
unsigned int bid1 = mol.getBondBetweenAtoms(aid1, aid)->getIdx();
unsigned int bid2 = mol.getBondBetweenAtoms(aid, aid3)->getIdx();
double dl = RDGeom::compute13Dist(accumData.bondLengths[bid1], accumData.bondLengths[bid2],
angle);
double du = dl + DIST13_TOL;
dl -= DIST13_TOL;
_checkAndSetBounds(aid1, aid3, dl, du, mmat);
}
void _setRingAngle(Atom::HybridizationType aHyb, unsigned int ringSize,
double &angle) {
// NOTE: this assumes that all angles in a ring are equal. This is
// certainly not always the case, particular in aromatic rings with heteroatoms
// like s1cncc1. This led to GitHub55, which was fixed elsewhere.
if ((aHyb == Atom::SP2) || (ringSize==3) || (ringSize==4)) {
angle = M_PI*(1 - 2.0/ringSize);
} else if (aHyb == Atom::SP3) {
if (ringSize == 5) {
angle = 104*M_PI/180;
} else {
angle = 109.5*M_PI/180;
}
} else if (aHyb == Atom::SP3D) {
angle = 105.0*M_PI/180;
} else if (aHyb == Atom::SP3D2) {
angle = 90.0*M_PI/180;
} else {
angle = 120*M_PI/180;
}
}
struct lessVector : public std::binary_function<INT_VECT,INT_VECT,bool> {
bool operator()(const INT_VECT &v1, const INT_VECT &v2) const {
return v1.size() < v2.size();
}
};
void set13Bounds(const ROMol &mol, DistGeom::BoundsMatPtr mmat, ComputedData &accumData) {
unsigned int npt = mmat->numRows();
CHECK_INVARIANT(npt == mol.getNumAtoms(), "Wrong size metric matrix");
CHECK_INVARIANT(accumData.bondAngles->numRows() == mol.getNumBonds(), "Wrong size bond angle matrix");
CHECK_INVARIANT(accumData.bondAdj->numRows() == mol.getNumBonds(), "Wrong size bond adjacency matrix");
// Since most of the special cases arise out of ring system, we will do the following here:
// - Loop over all the rings and set the 13 distances between atoms in these rings.
// While doing this keep track of the ring atoms that have already been used as the center atom.
// - Set the 13 distance between atoms that have a ring atom in between; these can be either non-ring atoms,
// or a ring atom and a non-ring atom, or ring atoms that belong to different simple rings
// - finally set all other 13 distances
const RingInfo *rinfo = mol.getRingInfo();
CHECK_INVARIANT(rinfo, "");
ROMol::OEDGE_ITER beg1, beg2, end1, end2;
unsigned int aid2, aid1, aid3, bid1, bid2;
double angle;
VECT_INT_VECT atomRings = rinfo->atomRings();
std::sort(atomRings.begin(), atomRings.end(), lessVector());
// sort the rings based on the ring size
VECT_INT_VECT_CI rii;
INT_VECT visited(npt, 0);
DOUBLE_VECT angleTaken(npt, 0.0);
unsigned int i;
unsigned int nb = mol.getNumBonds();
BIT_SET donePaths(nb*nb);
// first deal with all rings and atoms in them
unsigned int id1, id2;
for (rii = atomRings.begin(); rii != atomRings.end(); rii++) {
unsigned int rSize = rii->size();
aid1 = (*rii)[rSize-1];
for (i = 0; i < rSize; i++) {
aid2 = (*rii)[i];
if (i == rSize-1) {
aid3 = (*rii)[0];
} else {
aid3 = (*rii)[i+1];
}
const Bond *b1=mol.getBondBetweenAtoms(aid1, aid2);
const Bond *b2=mol.getBondBetweenAtoms(aid2, aid3);
CHECK_INVARIANT(b1,"no bond found");
CHECK_INVARIANT(b2,"no bond found");
bid1 = b1->getIdx();
bid2 = b2->getIdx();
id1 = nb*bid1 + bid2;
id2 = nb*bid2 + bid1;
if ((!donePaths[id1]) && (!donePaths[id2])) {
// this invar stuff is to deal with bridged systems (Issue 215). In bridged
// systems we may be covering the same 13 (ring) paths multiple times and unnecssarily
// increasing the angleTaken at the central atom.
_setRingAngle(mol.getAtomWithIdx(aid2)->getHybridization(), rSize, angle);
_set13BoundsHelper(aid1, aid2, aid3, angle, accumData, mmat, mol);
accumData.bondAngles->setVal(bid1, bid2, angle);
accumData.bondAdj->setVal(bid1, bid2, aid2);
visited[aid2] += 1;
angleTaken[aid2] += angle;
donePaths[id1] = 1;
donePaths[id2] = 1;
//donePaths.push_back(invar);
}
aid1 = aid2;
}
}
// now deal with the remaining atoms
for (aid2 = 0; aid2 < npt; aid2++) {
const Atom *atom = mol.getAtomWithIdx(aid2);
unsigned int deg = atom->getDegree();
unsigned int n13 = deg*(deg-1)/2;
if (n13 == static_cast<unsigned int>(visited[aid2])) {
// we are done with this atoms
continue;
}
Atom::HybridizationType ahyb = atom->getHybridization();
boost::tie(beg1,end1) = mol.getAtomBonds(atom);
if (visited[aid2] >= 1) {
// deal with atoms that we already visited; i.e. ring atoms. Set 13 distances for one of following cases:
// 1) Non-ring atoms that have a ring atom in-between
// 2) Non-ring atom and a ring atom that have a ring atom in between
// 3) Ring atoms that belong to different rings (that are part of a fused system
while (beg1 != end1) {
const BOND_SPTR bnd1 = mol[*beg1];
bid1 = bnd1->getIdx();
aid1 = bnd1->getOtherAtomIdx(aid2);
boost::tie(beg2,end2) = mol.getAtomBonds(atom);
while (beg2 != beg1) {
const BOND_SPTR bnd2 = mol[*beg2];
bid2 = bnd2->getIdx();
//invar = firstThousandPrimes[bid1]*firstThousandPrimes[bid2];
if (accumData.bondAngles->getVal(bid1, bid2) < 0.0) {
//if (bondAngles.find(invar) == bondAngles.end()) {
// if we haven't dealt with these two bonds before
// if we have a sp2 atom things are planar - we simply divide the remaining angle among the
// remaining 13 configurations (and there should only be one)
if (ahyb == Atom::SP2) {
angle = (2*M_PI - angleTaken[aid2])/(n13-visited[aid2]);
} else if (ahyb == Atom::SP3) {
// in the case of sp3 we will use the tetrahedral angle mostly - but
// but with some special cases
angle = 109.5*M_PI/180;
// we will special-case a little bit here for 3, 4 members ring atoms that are sp3 hybirdized
// beyond that the angle reasonably close to the tetrahedral angle
if (rinfo->isAtomInRingOfSize(aid2, 3)) {
angle = 116.0*M_PI/180;
} else if (rinfo->isAtomInRingOfSize(aid2, 4)) {
angle = 112.0*M_PI/180;
}
} else {
// other options we will simply based things on the number of substituent
if (deg == 5) {
angle = 105.0*M_PI/180;
} else if (deg == 6) {
angle = 135.0*M_PI/180;
} else {
angle = 120.0*M_PI/180; // FIX: this default is probably not the best we can do here
}
}
aid3 = bnd2->getOtherAtomIdx(aid2);
_set13BoundsHelper(aid1, aid2, aid3, angle, accumData, mmat, mol);
accumData.bondAngles->setVal(bid1, bid2, angle);
accumData.bondAdj->setVal(bid1, bid2, aid2);
angleTaken[aid2] += angle;
visited[aid2] += 1;
}
++beg2;
} // while loop over the second bond
++beg1;
} // while loop over the first bond
} else if (visited[aid2] == 0) {
// non-ring atoms - we will simply use angles based on hydridization
while (beg1 != end1) {
const BOND_SPTR bnd1 = mol[*beg1];
bid1 = bnd1->getIdx();
aid1 = bnd1->getOtherAtomIdx(aid2);
boost::tie(beg2,end2) = mol.getAtomBonds(atom);
while (beg2 != beg1) {
const BOND_SPTR bnd2 = mol[*beg2];
bid2 = bnd2->getIdx();
if (ahyb == Atom::SP) {
angle = M_PI;
} else if (ahyb == Atom::SP2) {
angle = 2*M_PI/3;
} else if (ahyb == Atom::SP3) {
angle = 109.5*M_PI/180;
} else if (ahyb == Atom::SP3D){
//FIX: this and the remaining two hybirdization states below should probably be special
// cased. These defaults below are probably not the best we can do particularly when
// stereo chemistry is know
angle = 105.0*M_PI/180;
} else if (ahyb == Atom::SP3D2){
angle = 135.0*M_PI/180;
} else {
angle = 120.0*M_PI/180;
}
aid3 = bnd2->getOtherAtomIdx(aid2);
_set13BoundsHelper(aid1, aid2, aid3, angle, accumData, mmat, mol);
accumData.bondAngles->setVal(bid1, bid2, angle);
accumData.bondAdj->setVal(bid1, bid2, aid2);
angleTaken[aid2] += angle;
visited[aid2] += 1;
++beg2;
} // while loop over second bond
++beg1;
} // while loop over first bond
} // done with non-ring atoms
} // done with all atoms
} // done with 13 distance setting
Bond::BondStereo _getAtomStereo(const Bond *bnd, unsigned int aid1,
unsigned int aid4) {
Bond::BondStereo stype = bnd->getStereo();
if (stype > Bond::STEREOANY ) {
const INT_VECT &stAtoms = bnd->getStereoAtoms();
if ((static_cast<unsigned int>(stAtoms[0]) != aid1) ^
(static_cast<unsigned int>(stAtoms[1]) != aid4)) {
if (stype == Bond::STEREOZ) {
stype = Bond::STEREOE;
} else if (stype == Bond::STEREOE) {
stype = Bond::STEREOZ;
}
}
}
return stype;
}
void _setInRing14Bounds(const ROMol &mol, const Bond* bnd1, const Bond* bnd2, const Bond* bnd3,
ComputedData &accumData, DistGeom::BoundsMatPtr mmat,double *dmat) {
PRECONDITION(bnd1, "");
PRECONDITION(bnd2, "");
PRECONDITION(bnd3, "");
unsigned int bid1, bid2, bid3;
bid1 = bnd1->getIdx();
bid2 = bnd2->getIdx();
bid3 = bnd3->getIdx();
const Atom *atm2 = mol.getAtomWithIdx(accumData.bondAdj->getVal(bid1, bid2));
PRECONDITION(atm2, "");
Atom::HybridizationType ahyb2 = atm2->getHybridization();
const Atom *atm3 = mol.getAtomWithIdx(accumData.bondAdj->getVal(bid2, bid3));
PRECONDITION(atm3, "");
Atom::HybridizationType ahyb3 = atm3->getHybridization();
unsigned int aid1 = bnd1->getOtherAtomIdx(atm2->getIdx());
unsigned int aid4 = bnd3->getOtherAtomIdx(atm3->getIdx());
// check that this actually is a 1-4 contact:
if(dmat[std::max(aid1,aid4)*mmat->numRows()+std::min(aid1,aid4)]<2.9){
//std::cerr<<"skip: "<<aid1<<"-"<<aid4<<" because d="<<dmat[std::max(aid1,aid4)*mmat->numRows()+std::min(aid1,aid4)]<<std::endl;
return;
}
double bl1 = accumData.bondLengths[bid1];
double bl2 = accumData.bondLengths[bid2];
double bl3 = accumData.bondLengths[bid3];
double ba12 = accumData.bondAngles->getVal(bid1, bid2);
double ba23 = accumData.bondAngles->getVal(bid2, bid3);
CHECK_INVARIANT(ba12 > 0.0, "");
CHECK_INVARIANT(ba23 > 0.0, "");
double dl, du;
unsigned int nb = mol.getNumBonds();
//several special cases here
Path14Configuration path14;
path14.bid1 = bid1; path14.bid2 = bid2; path14.bid3 = bid3;
Bond::BondStereo stype = _getAtomStereo(bnd2, aid1, aid4);
if ((ahyb2 == Atom::SP2) && (ahyb3 == Atom::SP2)
&& (stype != Bond::STEREOE)) {
dl = RDGeom::compute14DistCis(bl1, bl2, bl3, ba12, ba23) - GEN_DIST_TOL;
du = dl + 2*GEN_DIST_TOL;
path14.type = Path14Configuration::CIS;
accumData.cisPaths[bid1*nb*nb + bid2*nb + bid3] = 1;
accumData.cisPaths[bid3*nb*nb + bid2*nb + bid1] = 1;
} else {
// basically we will assume 0 to 180 allowed
dl = RDGeom::compute14DistCis(bl1, bl2, bl3, ba12, ba23);
du = RDGeom::compute14DistTrans(bl1, bl2, bl3, ba12, ba23);
if(du<dl) std::swap(du,dl);
if (fabs(du-dl) < DIST12_DELTA) {
dl -= GEN_DIST_TOL;
du += GEN_DIST_TOL;
}
path14.type = Path14Configuration::OTHER;
}
//std::cerr<<"7: "<<aid1<<"-"<<aid4<<std::endl;
_checkAndSetBounds(aid1, aid4, dl , du, mmat);
accumData.paths14.push_back(path14);
}
void _setTwoInSameRing14Bounds(const ROMol &mol, const Bond *bnd1, const Bond *bnd2,
const Bond *bnd3, ComputedData &accumData,
DistGeom::BoundsMatPtr mmat,double *dmat) {
PRECONDITION(bnd1, "");
PRECONDITION(bnd2, "");
PRECONDITION(bnd3, "");
unsigned int bid1, bid2, bid3;
bid1 = bnd1->getIdx();
bid2 = bnd2->getIdx();
bid3 = bnd3->getIdx();
const Atom *atm2 = mol.getAtomWithIdx(accumData.bondAdj->getVal(bid1, bid2));
PRECONDITION(atm2, "");
const Atom *atm3 = mol.getAtomWithIdx(accumData.bondAdj->getVal(bid2, bid3));
PRECONDITION(atm3, "");
unsigned int aid1 = bnd1->getOtherAtomIdx(atm2->getIdx());
unsigned int aid4 = bnd3->getOtherAtomIdx(atm3->getIdx());
// check that this actually is a 1-4 contact:
if(dmat[std::max(aid1,aid4)*mmat->numRows()+std::min(aid1,aid4)]<2.9){
//std::cerr<<"skip: "<<aid1<<"-"<<aid4<<" because d="<<dmat[std::max(aid1,aid4)*mmat->numRows()+std::min(aid1,aid4)]<<std::endl;
return;
}
// when we have fused rings, it can happen that this isn't actually a 1-4 contact,
// (this was the cause of sf.net bug 2835784) check that now:
if(mol.getBondBetweenAtoms(aid1,atm3->getIdx()) ||
mol.getBondBetweenAtoms(aid4,atm2->getIdx())) {
return;
}
Atom::HybridizationType ahyb3 = atm3->getHybridization();
Atom::HybridizationType ahyb2 = atm2->getHybridization();
double bl1 = accumData.bondLengths[bid1];
double bl2 = accumData.bondLengths[bid2];
double bl3 = accumData.bondLengths[bid3];
double ba12 = accumData.bondAngles->getVal(bid1, bid2);
double ba23 = accumData.bondAngles->getVal(bid2, bid3);
CHECK_INVARIANT(ba12 > 0.0, "");
CHECK_INVARIANT(ba23 > 0.0, "");
double dl, du;
Path14Configuration path14;
unsigned int nb = mol.getNumBonds();
path14.bid1 = bid1; path14.bid2 = bid2; path14.bid3 = bid3;
if ((ahyb2 == Atom::SP2) && (ahyb3 == Atom::SP2)) { // FIX: check for trans
// here we will assume 180 degrees: basically flat ring with an external substituent
dl = RDGeom::compute14DistTrans(bl1, bl2, bl3, ba12, ba23);
du = dl;
dl -= GEN_DIST_TOL;
du += GEN_DIST_TOL;
path14.type = Path14Configuration::TRANS;
accumData.transPaths[bid1*nb*nb + bid2*nb + bid3] = 1;
accumData.transPaths[bid3*nb*nb + bid2*nb + bid1] = 1;
} else {
// here we will assume anything is possible
dl = RDGeom::compute14DistCis(bl1, bl2, bl3, ba12, ba23);
du = RDGeom::compute14DistTrans(bl1, bl2, bl3, ba12, ba23);
// in highly-strained situations these can get mixed up:
if(du<dl){
double tmpD=dl;
dl=du;
du=tmpD;
}
if (fabs(du-dl) < DIST12_DELTA) {
dl -= GEN_DIST_TOL;
du += GEN_DIST_TOL;
}
path14.type = Path14Configuration::OTHER;
}
//std::cerr<<"1: "<<aid1<<"-"<<aid4<<": "<<dl<<" -> "<<du<<std::endl;
_checkAndSetBounds(aid1, aid4, dl ,du, mmat);
accumData.paths14.push_back(path14);
}
void _setTwoInDiffRing14Bounds(const ROMol &mol, const Bond *bnd1, const Bond *bnd2,
const Bond *bnd3, ComputedData &accumData,
DistGeom::BoundsMatPtr mmat,double *dmat) {
// this turns out to be very similar to all bonds in the same ring situation.
// There is probably some fine tuning that can be done when the atoms a2 and a3 are not sp2 hybridized,
// but we will not worry about that now; simple use 0-180 deg for non-sp2 cases.
_setInRing14Bounds(mol, bnd1, bnd2, bnd3, accumData, mmat,dmat);
}
void _setShareRingBond14Bounds(const ROMol &mol, const Bond *bnd1, const Bond *bnd2,
const Bond *bnd3, ComputedData &accumData,
DistGeom::BoundsMatPtr mmat,double *dmat) {
// once this turns out to be similar to bonds in the same ring
_setInRing14Bounds(mol, bnd1, bnd2, bnd3, accumData, mmat,dmat);
}
bool _checkH2NX3H1OX2(const Atom *atm) {
if ((atm->getAtomicNum() == 6) && ( atm->getTotalNumHs() == 2) ) {
// CH2
return true;
} else if ((atm->getAtomicNum() == 8) && (atm->getTotalNumHs() == 0) ) {
// OX2
return true;
} else if ((atm->getAtomicNum() == 7) && (atm->getDegree() == 3) &&
(atm->getTotalNumHs() == 1)) {
// FIX: assumming hydrogen is not in the graph
// this si NX3H1 situation
return true;
}
return false;
}
bool _checkNhChChNh(const Atom *atm1, const Atom *atm2, const Atom *atm3,
const Atom *atm4) {
//checking for [!#1]~$ch!@$ch~[!#1], where ch = [CH2,NX3H1,OX2] situation
if ((atm1->getAtomicNum() != 1) && (atm4->getAtomicNum() != 1) ) {
// end atom not hydrogens
if ( (_checkH2NX3H1OX2(atm2)) && (_checkH2NX3H1OX2(atm3)) ) {
return true;
}
}
return false;
}
// here we look for something like this:
// It's an amide or ester:
//
// 4 <- 4 is the O
// | <- That's the double bond
// 1 3
// \ / \ T.S.I.Left Blank
// 2 5 <- 2 is an oxygen/nitrogen
bool _checkAmideEster14(const Bond *bnd1, const Bond *bnd3, const Atom *atm1,
const Atom *atm2, const Atom *atm3, const Atom *atm4) {
unsigned int a1Num = atm1->getAtomicNum();
unsigned int a2Num = atm2->getAtomicNum();
unsigned int a3Num = atm3->getAtomicNum();
unsigned int a4Num = atm4->getAtomicNum();
if ( a1Num != 1 && a3Num==6 &&
bnd3->getBondType()==Bond::DOUBLE &&
(a4Num==8 || a4Num==7) &&
bnd1->getBondType()==Bond::SINGLE &&
(a2Num==8 || (a2Num==7 && atm2->getTotalNumHs()==1)) ){
return true;
}
return false;
}
bool _isCarbonyl(const ROMol &mol,const Atom *at){
PRECONDITION(at,"bad atom");
if(at->getAtomicNum()==6 && at->getDegree()>2 ){
ROMol::ADJ_ITER nbrIdx,endNbrs;
boost::tie(nbrIdx,endNbrs) = mol.getAtomNeighbors(at);
while(nbrIdx!=endNbrs){
unsigned int atNum=mol.getAtomWithIdx(*nbrIdx)->getAtomicNum();
if( (atNum==8 || atNum==7) &&
mol.getBondBetweenAtoms(at->getIdx(),*nbrIdx)->getBondType()==Bond::DOUBLE) {
return true;
}
++nbrIdx;
}
}
return false;
}
bool _checkAmideEster15(const ROMol &mol,
const Bond *bnd1, const Bond *bnd3, const Atom *atm1,
const Atom *atm2, const Atom *atm3, const Atom *atm4) {
unsigned int a2Num = atm2->getAtomicNum();
if ( (a2Num == 8) ||
((a2Num == 7) && (atm2->getTotalNumHs() == 1)) ) {
if ((atm1->getAtomicNum() != 1) && (bnd1->getBondType() == Bond::SINGLE)) {
if ((atm3->getAtomicNum() == 6) &&
(bnd3->getBondType() == Bond::SINGLE) &&
_isCarbonyl(mol,atm3)
) {
return true;
}
}
}
return false;
}
void _setChain14Bounds(const ROMol &mol, const Bond *bnd1, const Bond *bnd2, const Bond *bnd3,
ComputedData &accumData,
DistGeom::BoundsMatPtr mmat,double *dmat){
PRECONDITION(bnd1, "");
PRECONDITION(bnd2, "");
PRECONDITION(bnd3, "");
unsigned int bid1, bid2, bid3;
bid1 = bnd1->getIdx();
bid2 = bnd2->getIdx();
bid3 = bnd3->getIdx();
const Atom *atm2 = mol.getAtomWithIdx(accumData.bondAdj->getVal(bid1, bid2));
PRECONDITION(atm2, "");
const Atom *atm3 = mol.getAtomWithIdx(accumData.bondAdj->getVal(bid2, bid3));
PRECONDITION(atm3, "");
unsigned int aid1 = bnd1->getOtherAtomIdx(atm2->getIdx());
unsigned int aid4 = bnd3->getOtherAtomIdx(atm3->getIdx());
const Atom *atm1 = mol.getAtomWithIdx(aid1);
const Atom *atm4 = mol.getAtomWithIdx(aid4);
double bl1 = accumData.bondLengths[bid1];
double bl2 = accumData.bondLengths[bid2];
double bl3 = accumData.bondLengths[bid3];
double ba12 = accumData.bondAngles->getVal(bid1, bid2);
double ba23 = accumData.bondAngles->getVal(bid2, bid3);
CHECK_INVARIANT(ba12 > 0.0, "");
CHECK_INVARIANT(ba23 > 0.0, "");
bool setTheBound=true;
double dl=0.0, du=0.0;
// if the middle bond is double
Path14Configuration path14;
path14.bid1 = bid1; path14.bid2 = bid2; path14.bid3 = bid3;
unsigned int nb = mol.getNumBonds();
switch(bnd2->getBondType()) {
case Bond::DOUBLE :
// if any of the other bonds are double - the torsion angle is zero
// this is CC=C=C situation
if ((bnd1->getBondType() == Bond::DOUBLE) || (bnd3->getBondType() == Bond::DOUBLE)) {
dl = RDGeom::compute14DistCis(bl1, bl2, bl3, ba12, ba23) - GEN_DIST_TOL;
du = dl + 2*GEN_DIST_TOL;
path14.type = Path14Configuration::CIS;
accumData.cisPaths[bid1*nb*nb + bid2*nb + bid3] = 1;
accumData.cisPaths[bid3*nb*nb + bid2*nb + bid1] = 1;
//BOOST_LOG(rdDebugLog) << "Special 5 " << aid1 << " " << aid4 << "\n";
} else if (bnd2->getStereo() > Bond::STEREOANY) {
Bond::BondStereo stype = _getAtomStereo(bnd2, aid1, aid4);
if (stype == Bond::STEREOZ) {
dl = RDGeom::compute14DistCis(bl1, bl2, bl3, ba12, ba23) - GEN_DIST_TOL;
du = dl + 2*GEN_DIST_TOL;
path14.type = Path14Configuration::CIS;
//BOOST_LOG(rdDebugLog) << "Special 6 " << aid1 << " " << aid4 << "\n";
accumData.cisPaths[bid1*nb*nb + bid2*nb + bid3] = 1;
accumData.cisPaths[bid3*nb*nb + bid2*nb + bid1] = 1;
} else {
//BOOST_LOG(rdDebugLog) << "Special 7 " << aid1 << " " << aid4 << "\n";
du = RDGeom::compute14DistTrans(bl1, bl2, bl3, ba12, ba23);
dl = du;
dl -= GEN_DIST_TOL;
du += GEN_DIST_TOL;
path14.type = Path14Configuration::TRANS;
accumData.transPaths[bid1*nb*nb + bid2*nb + bid3] = 1;
accumData.transPaths[bid3*nb*nb + bid2*nb + bid1] = 1;
}
} else {
// double bond with no stereo setting can be 0 or 180
dl = RDGeom::compute14DistCis(bl1, bl2, bl3, ba12, ba23);
du = RDGeom::compute14DistTrans(bl1, bl2, bl3, ba12, ba23);
if (fabs(du-dl) < DIST12_DELTA) {
dl -= GEN_DIST_TOL;
du += GEN_DIST_TOL;
}
path14.type = Path14Configuration::OTHER;
}
break;
case Bond::SINGLE :
// Commenting out the following if block to fix issue 235, we may want to later provide
// the user with an option to invoke this special case
#if 0
if ( (_checkNhChChNh(atm1, atm2, atm3, atm4)) ||
((bnd1->getBondType() == Bond::DOUBLE) && (bnd3->getBondType() == Bond::DOUBLE) ) ) {
// this is either
// 1. [!#1]~$ch!@$ch~[!#1] situation where ch = [CH2,NX3H1,OX2] or
// 2. *=*-*=* situation
// Both case cases we use 180 deg for torsion
du = RDGeom::compute14DistTrans(bl1, bl2, bl3, ba12, ba23);
dl = du;
dl -= GEN_DIST_TOL;
du += GEN_DIST_TOL;
path14.type = Path14Configuration::TRANS;
transPaths[bid1*nb*nb + bid2*nb + bid3] = 1;
transPaths[bid3*nb*nb + bid2*nb + bid1] = 1;
} else
#endif
if ((atm2->getAtomicNum() == 16) && (atm3->getAtomicNum() == 16)) {
// this is *S-S* situation
//FIX: this cannot be right is sulfur has more than two coordinated
// the torsion angle is 90 deg
dl = RDGeom::compute14Dist3D(bl1, bl2, bl3, ba12, ba23, M_PI/2) - GEN_DIST_TOL;
du = dl + 2*GEN_DIST_TOL;
path14.type = Path14Configuration::OTHER;
//BOOST_LOG(rdDebugLog) << "Special 9 " << aid1 << " " << aid4 << "\n";
} else if (( _checkAmideEster14(bnd1, bnd3, atm1, atm2, atm3, atm4)) ||
( _checkAmideEster14(bnd3, bnd1, atm4, atm3, atm2, atm1))) {
// It's an amide or ester:
//
// 4 <- 4 is the O
// | <- That's the double bond
// 1 3
// \ / \ T.S.I.Left Blank
// 2 5 <- 2 is an oxygen/nitrogen
//
// Here we set the distance between atoms 1 and 4,
// we'll handle atoms 1 and 5 below.
// fix for issue 251 - we were marking this as a cis configuration earlier
// -------------------------------------------------------
// Issue284:
// As this code originally stood, we forced amide bonds to be trans. This is
// convenient a lot of the time for generating nice-looking structures, but is
// unfortunately totally bogus. So here we'll allow the distance to
// roam from cis to trans and hope that the force field planarizes things later.
//
// What we'd really like to be able to do is specify multiple possible ranges
// for the distances, but a single bounds matrix doesn't support this kind
// of fanciness.
//
#ifdef FORCE_TRANS_AMIDES
dl = RDGeom::compute14DistTrans(bl1, bl2, bl3, ba12, ba23);
path14.type = Path14Configuration::TRANS;
accumData.transPaths[bid1*nb*nb + bid2*nb + bid3] = 1;
accumData.transPaths[bid3*nb*nb + bid2*nb + bid1] = 1;
#else
if(atm2->getAtomicNum()==7 && atm2->getDegree()==3 &&
atm1->getAtomicNum()==1 && atm2->getTotalNumHs(true)==1){
// secondary amide, this is the H
setTheBound=false;
} else {
// force the amide to be cis:
dl = RDGeom::compute14DistCis(bl1, bl2, bl3, ba12, ba23);
path14.type = Path14Configuration::CIS;
accumData.cisPaths[bid1*nb*nb + bid2*nb + bid3] = 1;
accumData.cisPaths[bid3*nb*nb + bid2*nb + bid1] = 1;
}
#endif
du = dl;
dl -= GEN_DIST_TOL;
du += GEN_DIST_TOL;
//BOOST_LOG(rdDebugLog) << " amide: " << aid1 << " " << aid4 << ": " << dl << "->" << du << "\n";
} else if (( _checkAmideEster15(mol, bnd1, bnd3, atm1, atm2, atm3, atm4)) ||
( _checkAmideEster15(mol, bnd3, bnd1, atm4, atm3, atm2, atm1))) {
// it's an amide or ester.
//
// 4 <- 4 is the O
// | <- That's the double bond
// 1 3
// \ / \ T.S.I.Left Blank
// 2 5 <- 2 is oxygen or nitrogen
//
// we set the 1-4 contact above.
// If we're going to have a hope of getting good geometries
// out of here we need to set some reasonably smart bounds between 1
// and 5 (ref Issue355):
// NOTE THAT WE REVERSE THE ORDER HERE:
#ifdef FORCE_TRANS_AMIDES
// amide is trans, we're cis:
dl = RDGeom::compute14DistCis(bl1, bl2, bl3, ba12, ba23);
path14.type = Path14Configuration::CIS;
accumData.cisPaths[bid1*nb*nb + bid2*nb + bid3] = 1;
accumData.cisPaths[bid3*nb*nb + bid2*nb + bid1] = 1;
#else
// amide is cis, we're trans:
if(atm2->getAtomicNum()==7 && atm2->getDegree()==3 &&
atm1->getAtomicNum()==1 && atm2->getTotalNumHs(true)==1){
// secondary amide, this is the H
setTheBound=false;
} else {
dl = RDGeom::compute14DistTrans(bl1, bl2, bl3, ba12, ba23);
path14.type = Path14Configuration::TRANS;
accumData.transPaths[bid1*nb*nb + bid2*nb + bid3] = 1;
accumData.transPaths[bid3*nb*nb + bid2*nb + bid1] = 1;
}
#endif
du = dl;
dl -= GEN_DIST_TOL;
du += GEN_DIST_TOL;
//BOOST_LOG(rdDebugLog) << " amide neighbor: " << aid1 << " " << aid4 << ": " << dl << "->" << du << "\n";
} else {
dl = RDGeom::compute14DistCis(bl1, bl2, bl3, ba12, ba23);
du = RDGeom::compute14DistTrans(bl1, bl2, bl3, ba12, ba23);
path14.type = Path14Configuration::OTHER;
}
break;
default:
//BOOST_LOG(rdDebugLog) << "Special 12 " << aid1 << " " << aid4 << "\n";
dl = RDGeom::compute14DistCis(bl1, bl2, bl3, ba12, ba23);
du = RDGeom::compute14DistTrans(bl1, bl2, bl3, ba12, ba23);
path14.type = Path14Configuration::OTHER;
}
if(setTheBound){
if (fabs(du-dl) < DIST12_DELTA) {
dl -= GEN_DIST_TOL;
du += GEN_DIST_TOL;
}
//std::cerr<<"2: "<<aid1<<"-"<<aid4<<std::endl;
_checkAndSetBounds(aid1, aid4, dl, du, mmat);
accumData.paths14.push_back(path14);
}
}
void _record14Path(const ROMol &mol, unsigned int bid1, unsigned int bid2,
unsigned int bid3, ComputedData &accumData) {
const Atom *atm2 = mol.getAtomWithIdx(accumData.bondAdj->getVal(bid1, bid2));
PRECONDITION(atm2, "");
Atom::HybridizationType ahyb2 = atm2->getHybridization();
const Atom *atm3 = mol.getAtomWithIdx(accumData.bondAdj->getVal(bid2, bid3));
PRECONDITION(atm3, "");
Atom::HybridizationType ahyb3 = atm3->getHybridization();
unsigned int nb = mol.getNumBonds();
Path14Configuration path14;
path14.bid1 = bid1; path14.bid2 = bid2; path14.bid3 = bid3;
if ((ahyb2 == Atom::SP2) && (ahyb3 == Atom::SP2)) { // FIX: check for trans
path14.type = Path14Configuration::CIS;
accumData.cisPaths[bid1*nb*nb + bid2*nb + bid3] = 1;
accumData.cisPaths[bid3*nb*nb + bid2*nb + bid1] = 1;
} else {
path14.type = Path14Configuration::OTHER;
}
accumData.paths14.push_back(path14);
}
void set14Bounds(const ROMol &mol, DistGeom::BoundsMatPtr mmat,
ComputedData &accumData,double *distMatrix) {
unsigned int npt = mmat->numRows();
CHECK_INVARIANT(npt == mol.getNumAtoms(), "Wrong size metric matrix");
const RingInfo *rinfo = mol.getRingInfo(); // FIX: make sure we have ring info
CHECK_INVARIANT(rinfo, "");
const VECT_INT_VECT &bondRings = rinfo->bondRings();
VECT_INT_VECT_CI rii;
unsigned int i, aid2, aid3;
unsigned int bid1, bid2, bid3;
ROMol::OEDGE_ITER beg1, beg2, end1, end2;
ROMol::ConstBondIterator bi;
unsigned int nb = mol.getNumBonds();
BIT_SET ringBondPairs(nb*nb), donePaths(nb*nb*nb);
unsigned int id1, id2, pid1, pid2, pid3, pid4;
// first we will deal with 1-4 atoms that belong to the same ring
for (rii = bondRings.begin(); rii != bondRings.end(); rii++) {
// we don't need deal with 3 membered rings
unsigned int rSize = rii->size();
bid1 = (*rii)[rSize-1];
for (i = 0; i < rSize; i++) {
bid2 = (*rii)[i];
if (i == rSize-1){
bid3 = (*rii)[0];
} else {
bid3 = (*rii)[i+1];
}
pid1 = bid1*nb + bid2;
pid2 = bid2*nb + bid1;
id1 = bid1*nb*nb + bid2*nb + bid3;
id2 = bid3*nb*nb + bid2*nb + bid1;
ringBondPairs[pid1] = 1;
ringBondPairs[pid2] = 1;
donePaths[id1] = 1;
donePaths[id2] = 1;
if (rSize > 5) {
_setInRing14Bounds(mol, mol.getBondWithIdx(bid1),
mol.getBondWithIdx(bid2), mol.getBondWithIdx(bid3),
accumData, mmat, distMatrix);
} else {
_record14Path(mol, bid1, bid2, bid3, accumData);
}
bid1 = bid2;
} // loop over bonds in the ring
} // end of all rings
for (bi = mol.beginBonds(); bi != mol.endBonds(); bi++) {
bid2 = (*bi)->getIdx();
aid2 = (*bi)->getBeginAtomIdx();
aid3 = (*bi)->getEndAtomIdx();
boost::tie(beg1,end1) = mol.getAtomBonds(mol.getAtomWithIdx(aid2));
while (beg1 != end1) {
const Bond *bnd1 = mol[*beg1].get();
bid1 = bnd1->getIdx();
if (bid1 != bid2) {
boost::tie(beg2,end2) = mol.getAtomBonds(mol.getAtomWithIdx(aid3));
while (beg2 != end2) {
const Bond *bnd3 = mol[*beg2].get();
bid3 = bnd3->getIdx();
if (bid3 != bid2) {
id1 = nb*nb*bid1 + nb*bid2 + bid3;
id2 = nb*nb*bid3 + nb*bid2 + bid1;
if ((!donePaths[id1]) && (!donePaths[id2])) {
// we haven't dealt with this path before
pid1 = bid1*nb + bid2;
pid2 = bid2*nb + bid1;
pid3 = bid2*nb + bid3;
pid4 = bid3*nb + bid2;
if (ringBondPairs[pid1] || ringBondPairs[pid2]
|| ringBondPairs[pid3] || ringBondPairs[pid4]) {
// either (bid1, bid2) or (bid2, bid3) are in the
// same ring (note all three cannot be in the same
// ring; we dealt with that before)
_setTwoInSameRing14Bounds(mol, bnd1, (*bi), bnd3, accumData, mmat, distMatrix);
} else if ( ((rinfo->numBondRings(bid1) > 0) && (rinfo->numBondRings(bid2) > 0)) ||
((rinfo->numBondRings(bid2) > 0) && (rinfo->numBondRings(bid3) > 0)) ) {
// (bid1, bid2) or (bid2, bid3) are ring bonds but
// belong to different rings. Note that the third
// bond will not belong to either of these two
// rings (if it does, we would have taken care of
// it in the previous if block); i.e. if bid1 and
// bid2 are ring bonds that belong to ring r1 and
// r2, then bid3 is either an external bond or
// belongs to a third ring r3.
_setTwoInDiffRing14Bounds(mol, bnd1, (*bi), bnd3, accumData, mmat, distMatrix);
} else if (rinfo->numBondRings(bid2) > 0) {
// the middle bond is a ring bond and the other
// two do not belong to the same ring or are
// non-ring bonds
_setShareRingBond14Bounds(mol, bnd1, (*bi), bnd3, accumData, mmat, distMatrix);
} else {
// middle bond not a ring
_setChain14Bounds(mol, bnd1, (*bi), bnd3, accumData, mmat, distMatrix);
}
}
}
++beg2;
}
}
++beg1;
}
}
}
void initBoundsMat(DistGeom::BoundsMatrix *mmat,double defaultMin,
double defaultMax){
unsigned int npt = mmat->numRows();
for (unsigned int i = 1; i < npt; i++) {
for (unsigned int j = 0; j < i; j++) {
mmat->setUpperBound(i,j,defaultMax);
mmat->setLowerBound(i,j,defaultMin);
}
}
}
void initBoundsMat(DistGeom::BoundsMatPtr mmat,double defaultMin,
double defaultMax){
initBoundsMat(mmat.get(),defaultMin,defaultMax);
};
void setTopolBounds(const ROMol &mol, DistGeom::BoundsMatPtr mmat,
bool set15bounds, bool scaleVDW) {
PRECONDITION(mmat.get(),"bad pointer");
unsigned int nb = mol.getNumBonds();
unsigned int na = mol.getNumAtoms();
if(!na){
throw ValueErrorException("molecule has no atoms");
}
ComputedData accumData(na, nb);
double *distMatrix=0;
distMatrix = MolOps::getDistanceMat(mol);
set12Bounds(mol, mmat, accumData);
set13Bounds(mol, mmat, accumData);
set14Bounds(mol, mmat, accumData,distMatrix);
if (set15bounds) {
set15Bounds(mol, mmat, accumData,distMatrix);
}
setLowerBoundVDW(mol, mmat, scaleVDW,distMatrix);
}
// some helper functions to set 15 distances
/*
compute the lower and upper bounds for the distance between 15 atoms give than the first
four atoms are in cis configuration. The 15 limits are computed assuming the following
configuration
5
\
1 4
\ /
2-3
ARGUMENTS:
d1 - distance between 1 and 2
d2 - distance between 2 and 3
d3 - distance between 3 and 4
d4 - distance between 4 and 5
ang12 - angle(123)
ang23 - angle(234)
and34 - angle(345)
dl - storage for lower 15 bound
du - storage for upper 15 bound
*/
double _compute15DistsCisCis(double d1, double d2, double d3, double d4,
double ang12, double ang23, double ang34) {
double dx14 = d2 - d3*cos(ang23) - d1*cos(ang12);
double dy14 = d3*sin(ang23) - d1*sin(ang12);
double d14 = sqrt(dx14*dx14 + dy14*dy14);
double cval = (d3 - d2*cos(ang23) + d1*cos(ang12 + ang23))/d14;
if (cval > 1.0) {
cval = 1.0;
} else if (cval < -1.0) {
cval = -1.0;
}
double ang143 = acos(cval);
double ang145 = ang34 - ang143;
double res = RDGeom::compute13Dist(d14, d4, ang145);
return res;
}
/*
compute the lower and upper bounds for the distance between 15 atoms give than the first
four atoms are in cis configuration. The 15 limits are computed assuming the following
configuration
1 4-5
\ /
2-3
ARGUMENTS:
d1 - distance between 1 and 2
d2 - distance between 2 and 3
d3 - distance between 3 and 4
d4 - distance between 4 and 5
ang12 - angle(123)
ang23 - angle(234)
and34 - angle(345)
dl - storage for lower 15 bound
du - storage for upper 15 bound
*/
double _compute15DistsCisTrans(double d1, double d2, double d3, double d4,
double ang12, double ang23, double ang34) {
double dx14 = d2 - d3*cos(ang23) - d1*cos(ang12);
double dy14 = d3*sin(ang23) - d1*sin(ang12);
double d14 = sqrt(dx14*dx14 + dy14*dy14);
double cval = (d3 - d2*cos(ang23) + d1*cos(ang12 + ang23))/d14;
if (cval > 1.0) {
cval = 1.0;
} else if (cval < -1.0) {
cval = -1.0;
}
double ang143 = acos(cval);
double ang145 = ang34 + ang143;
return RDGeom::compute13Dist(d14, d4, ang145);
}
/*
compute the lower and upper bounds for the dsitance between 15 atoms given than the first
four atoms are in trans configuration. The 15 limits are computed assuming the following
configuration
1
\
2-3
\
4-5
ARGUMENTS:
d1 - distance between 1 and 2
d2 - distance between 2 and 3
d3 - distance between 3 and 4
d4 - distance between 4 and 5
ang12 - angle(123)
ang23 - angle(234)
and34 - angle(345)
dl - storage for lower 15 bound
du - storage for upper 15 bound
*/
double _compute15DistsTransTrans(double d1, double d2, double d3, double d4, double ang12,
double ang23, double ang34) {
double dx14 = d2 - d3*cos(ang23) - d1*cos(ang12);
double dy14 = d3*sin(ang23) + d1*sin(ang12);
double d14 = sqrt(dx14*dx14 + dy14*dy14);
double cval = (d3 - d2*cos(ang23) + d1*cos(ang12 - ang23))/d14;
if (cval > 1.0) {
cval = 1.0;
} else if (cval < -1.0) {
cval = -1.0;
}
double ang143 = acos(cval);
double ang145 = ang34 + ang143;
return RDGeom::compute13Dist(d14, d4, ang145);
}
/*
compute the lower and upper bounds for the dsitance between 15 atoms given than the first
four atoms are in trans configuration. The 15 limits are computed assuming the following
configuration
1
\
2-3
\
4
/
5
ARGUMENTS:
d1 - distance between 1 and 2
d2 - distance between 2 and 3
d3 - distance between 3 and 4
d4 - distance between 4 and 5
ang12 - angle(123)
ang23 - angle(234)
and34 - angle(345)
dl - storage for lower 15 bound
du - storage for upper 15 bound
*/
double _compute15DistsTransCis(double d1, double d2, double d3, double d4,
double ang12, double ang23, double ang34) {
double dx14 = d2 - d3*cos(ang23) - d1*cos(ang12);
double dy14 = d3*sin(ang23) + d1*sin(ang12);
double d14 = sqrt(dx14*dx14 + dy14*dy14);
double cval = (d3 - d2*cos(ang23) + d1*cos(ang12 - ang23))/d14;
if (cval > 1.0) {
cval = 1.0;
} else if (cval < -1.0) {
cval = -1.0;
}
double ang143 = acos(cval);
double ang145 = ang34 - ang143;
return RDGeom::compute13Dist(d14, d4, ang145);
}
void _set15BoundsHelper(const ROMol &mol, unsigned int bid1, unsigned int bid2, unsigned int bid3,
unsigned int type, ComputedData &accumData,
DistGeom::BoundsMatPtr mmat, double *dmat) {
unsigned int i, aid1, aid2, aid3, aid4, aid5;
double d1, d2, d3, d4, ang12, ang23, ang34, du, dl, vw1, vw5;
unsigned int nb = mol.getNumBonds();
unsigned int na = mol.getNumAtoms();
aid2 = accumData.bondAdj->getVal(bid1, bid2);
aid1 = mol.getBondWithIdx(bid1)->getOtherAtomIdx(aid2);
aid3 = accumData.bondAdj->getVal(bid2, bid3);
aid4 = mol.getBondWithIdx(bid3)->getOtherAtomIdx(aid3);
d1 = accumData.bondLengths[bid1];
d2 = accumData.bondLengths[bid2];
d3 = accumData.bondLengths[bid3];
ang12 = accumData.bondAngles->getVal(bid1, bid2);
ang23 = accumData.bondAngles->getVal(bid2, bid3);
for (i = 0; i < nb; i++) {
du = -1.0;
dl = 0.0;
if (accumData.bondAdj->getVal(bid3, i) == static_cast<int>(aid4)) {
aid5 = mol.getBondWithIdx(i)->getOtherAtomIdx(aid4);
// make sure we did not com back to the first atom in the path - possible with 4 membered rings
// this is a fix for Issue 244
// check that this actually is a 1-5 contact:
if(dmat[std::max(aid1,aid5)*mmat->numRows()+std::min(aid1,aid5)]<3.9){
//std::cerr<<"skip: "<<aid1<<"-"<<aid5<<" because d="<<dmat[std::max(aid1,aid5)*mmat->numRows()+std::min(aid1,aid5)]<<std::endl;
continue;
}
if (aid1 != aid5) { //FIX: do we need this
unsigned int pid1 = aid1*na + aid5;
unsigned int pid2 = aid5*na + aid1;
if ((mmat->getLowerBound(aid1, aid5) < DIST12_DELTA) ||
(accumData.set15Atoms[pid1]) || (accumData.set15Atoms[pid2])) {
d4 = accumData.bondLengths[i];
ang34 = accumData.bondAngles->getVal(bid3, i);
unsigned int pathId = (bid2)*nb*nb + (bid3)*nb + i;
if (type == 0) {
if (accumData.cisPaths[pathId]) {
dl = _compute15DistsCisCis(d1, d2, d3, d4, ang12, ang23, ang34);
du = dl + DIST15_TOL;
dl -= DIST15_TOL;
} else if (accumData.transPaths[pathId]) {
dl = _compute15DistsCisTrans(d1, d2, d3, d4, ang12, ang23, ang34);
du = dl + DIST15_TOL;
dl -= DIST15_TOL;
} else {
dl = _compute15DistsCisCis(d1, d2, d3, d4, ang12, ang23, ang34) - DIST15_TOL;
du = _compute15DistsCisTrans(d1, d2, d3, d4, ang12, ang23, ang34) + DIST15_TOL;
}
} else if (type == 1) {
if (accumData.cisPaths[pathId]) {
dl = _compute15DistsTransCis(d1, d2, d3, d4, ang12, ang23, ang34);
du = dl + DIST15_TOL;
dl -= DIST15_TOL;
} else if (accumData.transPaths[pathId]) {
dl = _compute15DistsTransTrans(d1, d2, d3, d4, ang12, ang23, ang34);
du = dl + DIST15_TOL;
dl -= DIST15_TOL;
} else {
dl = _compute15DistsTransCis(d1, d2, d3, d4, ang12, ang23, ang34) - DIST15_TOL;
du = _compute15DistsTransTrans(d1, d2, d3, d4, ang12, ang23, ang34) + DIST15_TOL;
}
} else {
if (accumData.cisPaths[pathId]) {
dl = _compute15DistsCisCis(d4, d3, d2, d1, ang34, ang23, ang12) - DIST15_TOL;
du = _compute15DistsCisTrans(d4, d3, d2, d1, ang34, ang23, ang12) + DIST15_TOL;
} else if (accumData.transPaths[pathId]) {
dl = _compute15DistsTransCis(d4, d3, d2, d1, ang34, ang23, ang12) - DIST15_TOL;
du = _compute15DistsTransTrans(d4, d3, d2, d1, ang34, ang23, ang12) + DIST15_TOL;
} else {
vw1 = PeriodicTable::getTable()->getRvdw(mol.getAtomWithIdx(aid1)->getAtomicNum());
vw5 = PeriodicTable::getTable()->getRvdw(mol.getAtomWithIdx(aid5)->getAtomicNum());
dl = VDW_SCALE_15*(vw1+vw5);
}
}
if (du < 0.0) {
du = MAX_UPPER;
}
//std::cerr<<"3: "<<aid1<<"-"<<aid5<<std::endl;
_checkAndSetBounds(aid1, aid5, dl, du, mmat);
accumData.set15Atoms[aid1*na + aid5] = 1;
accumData.set15Atoms[aid5*na + aid1] = 1;
}
}
}
}
}
// set the 15 distance bounds
void set15Bounds(const ROMol &mol, DistGeom::BoundsMatPtr mmat,
ComputedData &accumData,double *distMatrix) {
PATH14_VECT_CI pti;
unsigned int bid1, bid2, bid3, type;
for (pti = accumData.paths14.begin(); pti != accumData.paths14.end(); pti++) {
bid1 = pti->bid1;
bid2 = pti->bid2;
bid3 = pti->bid3;
type = pti->type;
// 15 distances going one way with with 14 paths
_set15BoundsHelper(mol, bid1, bid2, bid3, type, accumData, mmat, distMatrix);
// goign the other way - reverse the 14 path
_set15BoundsHelper(mol, bid3, bid2, bid1, type, accumData, mmat, distMatrix);
}
}
}
}
| [
"hjkulik@mit.edu"
] | hjkulik@mit.edu |
add1ab62f1f233a7d0d4f6b9a7307929a5d5282b | e1ac3d9b7a05552f0370c05b58a5a4d64a76cdc8 | /1036b.cpp | 1c8f18902131c6508e5d951a14e232fcffae1971 | [] | no_license | Carlineos/Uri-Iniciante | 0571c8d19e5e6a0069a1c2b332c540a39fec23af | 21fd856bc8afffe67732d45f7950ef792bdf1ff5 | refs/heads/main | 2023-05-10T15:32:56.260164 | 2021-06-15T18:08:16 | 2021-06-15T18:08:16 | 377,251,604 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 425 | cpp | #include <stdio.h>
#include <math.h>
int main()
{
double A, B, C, R1, R2, delta;
scanf("%lf", &A);
scanf("%lf", &B);
scanf("%lf", &C);
delta = (pow(B,2) - 4 * A * C);
if (delta < 0 || A == 0)
printf("Impossivel Calcular\n");
else
{
R1 = (- B + sqrt(delta)) / (2 * A);
R2 = (- B - sqrt(delta)) / (2 * A );
printf("R1 = %.5lf\n", R1);
printf("R2 = %.5lf\n", R2);
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
252fe0cf4982f0e4d512e3fe1c9b8f2e85a4e0aa | 0d81a7d80fab4609263439fcdda179fd2ace6c4b | /Source/NekoRun/Neko.h | c48c8a692e7cca8e9cf9b4fce3b5719696170d6e | [
"MIT"
] | permissive | SaiBalaji-PSS/Neko-Runner | 8ca21d693d979c1e531175a7e29599457e598ca0 | 1dba4313b5d4f27e3c57e0d9a4da4c2344031f6e | refs/heads/main | 2023-02-20T16:11:28.490522 | 2020-11-12T08:16:55 | 2020-11-12T08:16:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 780 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "PaperCharacter.h"
#include "Neko.generated.h"
/**
*
*/
UCLASS()
class NEKORUN_API ANeko : public APaperCharacter
{
GENERATED_BODY()
public:
ANeko();
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, meta = (AllowPrivateAccess = true))
bool IsPlayerDead;
protected:
// This function is from ACharacter class which is the parent of this class Parent
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
virtual void Tick(float DeltaTime) override;
virtual void BeginPlay() override;
private:
void SlideDown();
AActor* Player;
void SlideUp();
};
| [
"noreply@github.com"
] | noreply@github.com |
5100d03940a43e458679e79f5284e41e6caa43c2 | 7491e96c4dc532b3ed7a1e6cb1a900892d182f1e | /Number Theory/GCD.cpp | fdac2532606236e98b20ec2f8f8eca4404deea60 | [] | no_license | parvezaalam786/Placement-Preparation | b4312364d06d9e01118bd872da73f72dc4f6c64e | 948f546443c0d535bb1ee40bc68ed438125a6cf4 | refs/heads/master | 2023-01-19T17:51:46.914941 | 2020-11-11T11:28:14 | 2020-11-11T11:28:14 | 282,716,681 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 278 | cpp | #include<bits/stdc++.h>
using namespace std;
int gcd(int a,int b)
{
if(b==0)
return a;
return gcd(b,a%b);
}
int lcm(int a,int b)
{
return (a*b)/gcd(a,b);
}
int main()
{
cout<<gcd(16,20)<<endl;
cout<<gcd(25,20)<<endl;
cout<<lcm(25,20)<<endl;
} | [
"parvezaalam786.p@gmail.com"
] | parvezaalam786.p@gmail.com |
fa677be9abce861d2b2a70c7de0ee64de2427fab | 3776846dbe9ce5af8fdef7489258c7be89c7e958 | /SampleProject/02_GUI/GUISample.cpp | 394112a00fd864ee0e2141f294ea9b51944e931a | [] | no_license | bmjoy/Auto3D | fcdda8b3bcd07d69f9678fe5e2bff3ac3106041f | 345714eeac915e8efbeb4ad38de5e1afce83cc66 | refs/heads/master | 2020-12-12T04:11:53.137321 | 2020-01-15T04:01:23 | 2020-01-15T04:01:23 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 6,413 | cpp | #include "GUISample.h"
#include <imgui.h>
#include <imgui_user/imgui_user.h>
void GUISample::Init()
{
Super::Init();
auto* graphics = GModuleManager::Get().GraphicsModule();
graphics->RenderWindow()->SetTitle("GUI Sample");
}
void GUISample::Start()
{
Super::Start();
FResourceModule* cache = GModuleManager::Get().CacheModule();
FUIModule* ui = GModuleManager::Get().UiModule();
AFont* msyh = cache->LoadResource<AFont>("Font/msyh.ttc");
ui->AddFont(msyh, 26, "Msyh_26");
ui->AddFont(msyh, 48, "Msyh_48", EUIFontLanguage::CN);
ui->AddFont(msyh, 15, "Msyh_15");
ui->AddFont(msyh, 20, "Msyh_20");
imgTexture = cache->LoadResource<ATexture>("Texture/flower.png");
}
void GUISample::Update()
{
Super::Update();
}
void GUISample::UIDraw()
{
static bool simpleOverlayWindow = true;
static bool logWindow = true;
static bool layoutWindow = true;
static float f = 0.0f;
static int counter = 0;
GUI::Begin("Hello, world!");
GUI::PushFont("Msyh_48");
GUI::Text(u8"ÖÐÎIJâÊÔ");
GUI::Image(imgTexture, TVector2F(imgTexture->GetWidth(), imgTexture->GetHeight())); GUI::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
if (GUI::Button("Button"))
counter++;
GUI::SameLine();
GUI::Text("counter = %d", counter);
GUI::PopFont();
GUI::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
GUI::End();
if (simpleOverlayWindow) ShowExampleAppSimpleOverlay(&simpleOverlayWindow);
if (logWindow) ShowExampleAppLog(&logWindow);
if (layoutWindow) ShowExampleAppLayout(&layoutWindow);
}
void GUISample::Stop()
{
Super::Stop();
}
void GUISample::ShowExampleAppSimpleOverlay(bool* open)
{
const float DISTANCE = 10.0f;
static int corner = 0;
GUI::IO& io = GUI::GetIO();
if (corner != -1)
{
TVector2F window_pos = TVector2F((corner & 1) ? io.DisplaySize.x - DISTANCE : DISTANCE, (corner & 2) ? io.DisplaySize.y - DISTANCE : DISTANCE);
TVector2F window_pos_pivot = TVector2F((corner & 1) ? 1.0f : 0.0f, (corner & 2) ? 1.0f : 0.0f);
GUI::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot);
}
GUI::SetNextWindowBgAlpha(0.35f); // Transparent background
if (GUI::Begin("Example: Simple overlay", open, (corner != -1 ? ImGuiWindowFlags_NoMove : 0) | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav))
{
GUI::PushFont("Msyh_15");
if (GUI::IsMousePosValid())
GUI::Text("Mouse Position:\n (%.1f,%.1f)", io.MousePos.x, io.MousePos.y);
else
GUI::Text("Mouse Position: <invalid>");
if (GUI::BeginPopupContextWindow())
{
if (GUI::MenuItem("Custom", NULL, corner == -1)) corner = -1;
if (GUI::MenuItem("Top-left", NULL, corner == 0)) corner = 0;
if (GUI::MenuItem("Top-right", NULL, corner == 1)) corner = 1;
if (GUI::MenuItem("Bottom-left", NULL, corner == 2)) corner = 2;
if (GUI::MenuItem("Bottom-right", NULL, corner == 3)) corner = 3;
if (open && GUI::MenuItem("Close")) *open = false;
GUI::EndPopup();
}
GUI::Separator();
static int count = 10;
static float fps = 0;
static float currentFps = 0;
if (!count--)
{
count = 5;
currentFps = GModuleManager::Get().TimeModule()->GetFramesPerSecond();
}
if (Abs(fps - currentFps) > 0.2f)
{
fps = currentFps;
}
GUI::Text("FPS: %.1f", fps);
GUI::PopFont();
}
GUI::End();
}
void GUISample::ShowExampleAppLog(bool* open)
{
static FUILog log;
// For the demo: add a debug button _BEFORE_ the normal log window contents
// We take advantage of a rarely used feature: multiple calls to Begin()/End() are appending to the _same_ window.
// Most of the contents of the window will be added by the log.Draw() call.
auto window = GModuleManager::Get().GraphicsModule()->RenderWindow();
GUI::SetNextWindowPos(TVector2F(0, window->GetHeight() * 0.7f), ImGuiCond_Always);
GUI::SetNextWindowSize(TVector2F(window->GetWidth(), window->GetHeight() * 0.3f), ImGuiCond_Always);
GUI::WindowFlags windowFlags =
ImGuiWindowFlags_NoMove |
ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoBackground;
GUI::PushFont("Msyh_20");
GUI::Begin("Log", open, windowFlags);
if (GUI::SmallButton("[Debug] Add 5 entries"))
{
static int counter = 0;
for (int n = 0; n < 5; n++)
{
const char* categories[3] = { "info", "warn", "error" };
const char* words[] = { "Bumfuzzled", "Cattywampus", "Snickersnee", "Abibliophobia", "Absquatulate", "Nincompoop", "Pauciloquent" };
log.AddLog("[%05d] [%s] Hello, current time is %.1f, here's a word: '%s'\n",
GUI::GetFrameCount(), categories[counter % IM_ARRAYSIZE(categories)], GUI::GetTime(), words[counter % IM_ARRAYSIZE(words)]);
counter++;
}
}
GUI::End();
GUI::PopFont();
// Actually call in the regular Log helper (which will Begin() into the same window as we just did)
log.Draw("Log", open);
}
void GUISample::ShowExampleAppLayout(bool* open)
{
GUI::SetNextWindowSize(TVector2F(500, 440), ImGuiCond_FirstUseEver);
if (GUI::Begin("Example: Simple layout", open, ImGuiWindowFlags_MenuBar))
{
if (GUI::BeginMenuBar())
{
if (GUI::BeginMenu("File"))
{
if (GUI::MenuItem("Close")) *open = false;
GUI::EndMenu();
}
GUI::EndMenuBar();
}
// left
static int selected = 0;
GUI::BeginChild("left pane", TVector2F(150, 0), true);
for (int i = 0; i < 100; i++)
{
char label[128];
sprintf(label, "MyObject %d", i);
if (GUI::Selectable(label, selected == i))
selected = i;
}
GUI::EndChild();
GUI::SameLine();
// right
GUI::BeginGroup();
GUI::BeginChild("item view", TVector2F(0, -GUI::GetFrameHeightWithSpacing())); // Leave room for 1 line below us
GUI::Text("MyObject: %d", selected);
GUI::Separator();
if (GUI::BeginTabBar("##Tabs", ImGuiTabBarFlags_None))
{
if (GUI::BeginTabItem("Description"))
{
GUI::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ");
GUI::EndTabItem();
}
if (GUI::BeginTabItem("Details"))
{
GUI::Text("ID: 0123456789");
GUI::EndTabItem();
}
GUI::EndTabBar();
}
GUI::EndChild();
if (GUI::Button("Revert")) {}
GUI::SameLine();
if (GUI::Button("Save")) {}
GUI::EndGroup();
}
GUI::End();
}
AUTO_APPLICATION_MAIN(GUISample) | [
"421698843@qq.com"
] | 421698843@qq.com |
44310faba3b128e309664cb6f0e11b3fa5fe4281 | 66a851aff4c314731323b1b7f96416d6136a46d4 | /Abstract_Factory/WindowsWindow.h | 5a39ca1f6ff9f231114d0cd5ba4e9f3725d601f1 | [] | no_license | joseff01/AED2-TE2-DesignPatterns | 92a12b6e096995d95f32fdbf0f6a4a7f6fd4cd7a | 1f6bd5f71be420a53028d88ff7d760ee8936d88d | refs/heads/main | 2023-04-02T18:26:04.949964 | 2021-03-27T03:31:21 | 2021-03-27T03:31:21 | 350,414,480 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 285 | h | #ifndef ABSTRACT_FACTORY_WINDOWSWINDOW_H
#define ABSTRACT_FACTORY_WINDOWSWINDOW_H
#include "Window.h"
#include "Textbox.h"
class WindowsWindow : public Window{
public:
WindowsWindow();
Textbox* FactoryMethod() const override;
};
#endif //ABSTRACT_FACTORY_WINDOWSWINDOW_H
| [
"joseantonioretanacorrales@gmail.com"
] | joseantonioretanacorrales@gmail.com |
59de0c64c970fd911f670fe95f8a6e87178400b5 | 2244e7f6a4a4068a033df44e2d902a02679f2f92 | /Kanpsack01.cpp | 781b10eb5cafce38c9f8d6afeb65ac2c0615e0a2 | [] | no_license | pravsin/DPAlgorithms | 37d01da244efad87ca207f16a0dc01b286b99a2c | 579af75dabe86fec11bbff9f2f39166460c4ddc4 | refs/heads/master | 2021-01-10T04:39:26.133601 | 2015-10-17T20:16:45 | 2015-10-17T20:16:45 | 44,067,041 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 662 | cpp | #include<bits/stdc++.h>
using namespace std;
long knapsack(vector<int> itemswt, vector<int> itemvalue, long capacity) {
vector<int> row(capacity + 1);
vector<vector<int>> dp(itemswt.size()+1, row);
for (int i = 0; i <= itemswt.size(); ++i) {
for (int j = 0; j <=capacity ; ++j) {
if(i==0||j==0) {
dp[i][j] = 0;
continue;
}
if(j- itemswt[i-1] >=0){
dp[i][j]=max(dp[i-1][j],dp[i-1][j-itemswt[i-1]]+itemvalue[i-1]);
}
else{
dp[i][j]= dp[i-1][j];
}
}
}
return dp[itemswt.size()][capacity];
} | [
"praveensingh.iitk@gmail.com"
] | praveensingh.iitk@gmail.com |
9233a8342ceb386e7fb6644a2a74cbbaa711d261 | 9b4b0c3faa5f3002ed85c3054164e0b9fb427f56 | /Codes/15600/15650.cpp | 3ffe0258030c5f15af3748ba7785ace991bf7828 | [] | no_license | calofmijuck/BOJ | 246ae31b830d448c777878a90e1d658b7cdf27f4 | 4b29e0c7f487aac3186661176d2795f85f0ab21b | refs/heads/master | 2023-04-27T04:47:11.205041 | 2023-04-17T01:53:03 | 2023-04-17T01:53:03 | 155,859,002 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 632 | cpp | #include <iostream>
using namespace std;
bool visited[10];
int arr[10];
int m, n;
void solve(int cnt) {
if(cnt == m) {
for(int i = 0; i < m; ++i) cout << arr[i] + 1 << ' ';
cout << '\n';
return;
}
for(int i = 0; i < n; ++i) {
if(!visited[i]) {
visited[i] = true;
arr[cnt] = i;
if(cnt != 0 && arr[cnt - 1] < arr[cnt]) solve(cnt + 1);
if(cnt == 0) solve(cnt + 1);
visited[i] = false;
}
}
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
cin >> n >> m;
solve(0);
return 0;
}
| [
"calofmijuck@snu.ac.kr"
] | calofmijuck@snu.ac.kr |
eed1d81e569878c743d3db705479947b554de8fb | a5fc5d3385b67ba9bd7f2540d24d09ee40cc6ff4 | /src/SyCamera.cpp | d85d76d87ecbb63ffe9c0fcbf1403ae03d949315 | [
"MIT"
] | permissive | bottyburp/sylens | c3d15b1001e2015a090a77f3ac7137af9a8e0f34 | 41843bb01b33aab3e74a0ea27159752e9ab11b76 | refs/heads/master | 2021-01-24T03:08:32.161306 | 2013-01-24T11:12:05 | 2013-01-24T11:12:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,887 | cpp | /*
This node implements the second part of the workflow described here
http://forums.thefoundry.co.uk/phpBB2/viewtopic.php?p=1915&sid=497b22394ab62d0bf8bd7a35fa229913
*/
static const char* const CLASS = "SyCamera";
static const char* const HELP = "Camera with Syntheyes lens distortion built in. Contact me@julik.nl if you need help with the plugin.";
#include "VERSION.h"
#include "DDImage/CameraOp.h"
#include "DDImage/Scene.h"
#include "DDImage/Knob.h"
#include "DDImage/Knobs.h"
#include "DDImage/Format.h"
#include <sstream>
// for our friend printf
extern "C" {
#include <stdio.h>
}
#include "SyDistorter.cpp"
using namespace DD::Image;
class SyCamera : public CameraOp
{
private:
double max_corner_u_, max_corner_v_;
bool distortion_enabled;
double _obsolete_aspect;
public:
static const Description description;
SyDistorter distorter;
const char* Class() const
{
return CLASS;
}
const char* node_help() const
{
return HELP;
}
SyCamera(Node* node) : CameraOp(node)
{
distortion_enabled = 1;
}
void append(Hash& hash)
{
hash.append(VERSION);
hash.append(distorter.compute_hash());
CameraOp::append(hash);
}
void _validate(bool for_real)
{
CameraOp::_validate(for_real);
// Avoid recomputing things when not necessary
if(0 == distortion_enabled) return;
// Set the distortion aspect based on haperture/vaperture correlation.
// For this to work haperture/vaperture must be set correctly
double asp = film_width() / film_height();
debug("Disto autoaspect (haperture/vaperture) %0.5f", asp);
distorter.set_aspect(asp);
distorter.recompute_if_needed();
update_distortion_limits();
}
/* This is a virtual method on every CameraOp made exactly for this purpose, it's called from within
the standard knobs() */
void lens_knobs(Knob_Callback f)
{
Tab_knob(f, "SyLens");
distorter.knobs(f);
// Allow bypass
Knob* k_bypass = Bool_knob( f, &distortion_enabled, "disto_enabled");
k_bypass->label("enable distortion");
k_bypass->tooltip("You can deactivate this to suppress redistortion (if you want to use SyCamera without any distortion but do not want to change the parameters)");
Divider(f, 0);
Text_knob(f, "Make sure that your haperture/vaperture are set to the correct aspect!");
Divider(f, 0);
std::ostringstream ver;
ver << "SyCamera v." << VERSION;
Text_knob(f, ver.str().c_str());
// TODO: to be removed in SyLens 4.
// For compatibility with older scripts, add an "aspect" knob
Knob* k_obsolete_aspect = Float_knob(f, &_obsolete_aspect, "aspect");
// ...do not show it
k_obsolete_aspect->set_flag(Knob::INVISIBLE);
// ...and make it disappear when copy-pasted or saved out.
k_obsolete_aspect->set_flag(Knob::DO_NOT_WRITE);
}
/*
Distortion applies to TOTALLY everything in the scene, isolated
by an XY plane at the camera's eye (only vertices in the front of the cam
are processed). This means vertices far outside the frustum
might bend so extremely that they come back into the image!.
So what we will do is culling away all
the vertices that are too far out of the camera frustum.
A non-scientific but efficient way to do it is to compute where the extremes will be (u1v1)
at the corners and add 1 to it, and limit our distortion to the coordinates lying inside that limit.
This way we capture enough points and prevent the rollaround from occuring.
We also cache these limits based on the distortion
kappas. Note that for EXTREME fisheyes wraparound can still occur but
we consider it a corner case at the moment.
What is actually needed is finding a critical point of the distortion function
where the F(r2) changes sign, but we'll do that later.
Maybe.
*/
void update_distortion_limits()
{
distorter.recompute_if_needed();
Vector2 max_corner(distorter.aspect(), 1.0f);
distorter.apply_disto(max_corner);
max_corner_u_ = max_corner.x + 1.0f;
max_corner_v_ = max_corner.y + 1.0f;
}
// Distort a point in clip space. It's almost like a UV point (with embedded W)
// but it's already in the right Syntheyes coordinate system
void distort_p(Vector4& pt)
{
// Divide out the W coordinate
Vector2 uv(pt.x / pt.w, pt.y / pt.w);
if(fabs(uv.x) < max_corner_u_ && fabs(uv.y) < max_corner_v_) {
// Apply the distortion since the vector is ALREADY in the -1..1 space.
distorter.apply_disto(uv);
}
// And assign to the referenced vector multiplying by w.
pt.x = uv.x * pt.w;
pt.y = uv.y * pt.w;
}
/* The vertex shader that does lens disto.
By default it does this (using the point-local PL vector, which is 3-dimensional)
Note that we go from PL (point-local) to P (point-global)
for (int i=0; i < n; ++i) {
Vector4 p_clip = transforms->matrix(LOCAL_TO_CLIP).transform(v[i].PL());
v[i].P() = transforms->matrix(CLIP_TO_TO_SCREEN).transform(p_clip);
}
*/
static void sy_camera_nlens_func(Scene* scene, CameraOp* cam, MatrixArray* transforms, VArray* v, int n, void*)
{
SyCamera* sy_cam = dynamic_cast<SyCamera*>(cam);
for (int i=0; i < n; ++i) {
// We need to apply distortion in clip space, so do that. We will perform it on
// point local values, not on P because we want our Z and W to be computed out
// correctly for the motion vectors
Vector4 ps = transforms->matrix(LOCAL_TO_CLIP).transform(v[i].PL(), 1);
// Perform the disto magic
sy_cam->distort_p(ps);
// and transform to screen space, assign to position
Vector4 ps_screen = transforms->matrix(CLIP_TO_SCREEN).transform(ps);
v[i].P() = ps_screen;
}
}
LensNFunc* lensNfunction(int mode) const
{
if (mode == LENS_PERSPECTIVE && distortion_enabled) {
return sy_camera_nlens_func;
}
return CameraOp::lensNfunction(mode);
}
};
static Op* build(Node* node)
{
return new SyCamera(node);
}
const Op::Description SyCamera::description(CLASS, build);
| [
"me@julik.nl"
] | me@julik.nl |
50e2e494d7fb6c860702c049437dab0a90ed53d6 | ace29d0aa2c1b974c030bf782a47f2a3883533c5 | /codeforces/archived/B_Queue_at_the_School.cpp | 5b13118111000f702b32c3bcf075526a07c7772d | [
"MIT"
] | permissive | st3v3nmw/competitive-programming | 08c3fc60638fa059638352d01bde1f33effad62a | 581d36c1c128e0e3ee3a0b52628e932ab43821d4 | refs/heads/master | 2023-02-02T02:20:43.786278 | 2020-12-18T14:45:13 | 2020-12-18T14:45:13 | 284,418,965 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,496 | cpp | #include <bits/stdc++.h>
using namespace std;
#define eol "\n"
#define _(x) #x << "=" << to_str(x) << ", "
#define debug(x) { ostringstream stream; stream << x; string s = stream.str(); cout << s.substr(0, s.length() - 2) << eol; }
string to_string(basic_string<char>& x) { return "\"" + x + "\""; }
string to_string(char x) { string r = ""; r += x; return "\'" + r + "\'";}
string to_string(bool x) { return x ? "true" : "false"; }
template <typename T> string to_str(T x) { return to_string(x); }
template <typename T1, typename T2> string to_str(pair<T1, T2> x) { return "(" + to_str(x.first) + ", " + to_str(x.second) + ")"; }
template <typename T> string to_str(vector<T> x) { string r = "{"; for (auto t : x) r += to_str(t) + ", "; return r.substr(0, r.length() - 2) + "}"; }
template <typename T1, typename T2> string to_str(map<T1, T2> x) { string r = "{"; for (auto t : x) r += to_str(t.first) + ": " + to_str(t.second) + ", "; return r.substr(0, r.length() - 2) + "}"; }
#define ll long long
#define ull unsigned ll
const ull MOD = 1e9 + 7;
int main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int g, n;
cin >> g >> n;
vector<char> v(g);
for (int t = 0; t < g; t++)
cin >> v[t];
while (n--) {
for (int i = 0; i < g; i++) {
if (v[i] == 'B' && v[i + 1] == 'G') {
swap(v[i], v[i + 1]);
i++;
}
}
}
for (char c : v)
cout << c;
cout << eol;
} | [
"st3v3n.mw@gmail.com"
] | st3v3n.mw@gmail.com |
5135d23a3ee344070f74f7b039a29b6c6ea88db6 | dd80a584130ef1a0333429ba76c1cee0eb40df73 | /ndk/sources/cxx-stl/llvm-libc++/libcxx/test/re/re.alg/re.alg.search/ecma.pass.cpp | 8149157f28e69758dc76523835a241cff5272a41 | [
"MIT",
"NCSA"
] | permissive | karunmatharu/Android-4.4-Pay-by-Data | 466f4e169ede13c5835424c78e8c30ce58f885c1 | fcb778e92d4aad525ef7a995660580f948d40bc9 | refs/heads/master | 2021-03-24T13:33:01.721868 | 2017-02-18T17:48:49 | 2017-02-18T17:48:49 | 81,847,777 | 0 | 2 | MIT | 2020-03-09T00:02:12 | 2017-02-13T16:47:00 | null | UTF-8 | C++ | false | false | 56,153 | cpp | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <regex>
// template <class BidirectionalIterator, class Allocator, class charT, class traits>
// bool
// regex_search(BidirectionalIterator first, BidirectionalIterator last,
// match_results<BidirectionalIterator, Allocator>& m,
// const basic_regex<charT, traits>& e,
// regex_constants::match_flag_type flags = regex_constants::match_default);
#include <regex>
#include <cassert>
#include "test_iterators.h"
int main()
{
{
std::cmatch m;
const char s[] = "a";
assert(std::regex_search(s, m, std::regex("a")));
assert(m.size() == 1);
assert(!m.empty());
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+1);
assert(m.length(0) == 1);
assert(m.position(0) == 0);
assert(m.str(0) == "a");
}
{
std::cmatch m;
const char s[] = "ab";
assert(std::regex_search(s, m, std::regex("ab")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+2);
assert(m.length(0) == 2);
assert(m.position(0) == 0);
assert(m.str(0) == "ab");
}
{
std::cmatch m;
const char s[] = "ab";
assert(!std::regex_search(s, m, std::regex("ba")));
assert(m.size() == 0);
assert(m.empty());
}
{
std::cmatch m;
const char s[] = "aab";
assert(std::regex_search(s, m, std::regex("ab")));
assert(m.size() == 1);
assert(m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+3);
assert(m.length(0) == 2);
assert(m.position(0) == 1);
assert(m.str(0) == "ab");
}
{
std::cmatch m;
const char s[] = "aab";
assert(!std::regex_search(s, m, std::regex("ab"),
std::regex_constants::match_continuous));
assert(m.size() == 0);
}
{
std::cmatch m;
const char s[] = "abcd";
assert(std::regex_search(s, m, std::regex("bc")));
assert(m.size() == 1);
assert(m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+4);
assert(m.length(0) == 2);
assert(m.position(0) == 1);
assert(m.str(0) == "bc");
}
{
std::cmatch m;
const char s[] = "abbc";
assert(std::regex_search(s, m, std::regex("ab*c")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+4);
assert(m.length(0) == 4);
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "ababc";
assert(std::regex_search(s, m, std::regex("(ab)*c")));
assert(m.size() == 2);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+5);
assert(m.length(0) == 5);
assert(m.position(0) == 0);
assert(m.str(0) == s);
assert(m.length(1) == 2);
assert(m.position(1) == 2);
assert(m.str(1) == "ab");
}
{
std::cmatch m;
const char s[] = "abcdefghijk";
assert(std::regex_search(s, m, std::regex("cd((e)fg)hi")));
assert(m.size() == 3);
assert(m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+std::regex_traits<char>::length(s));
assert(m.length(0) == 7);
assert(m.position(0) == 2);
assert(m.str(0) == "cdefghi");
assert(m.length(1) == 3);
assert(m.position(1) == 4);
assert(m.str(1) == "efg");
assert(m.length(2) == 1);
assert(m.position(2) == 4);
assert(m.str(2) == "e");
}
{
std::cmatch m;
const char s[] = "abc";
assert(std::regex_search(s, m, std::regex("^abc")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+3);
assert(m.length(0) == 3);
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "abcd";
assert(std::regex_search(s, m, std::regex("^abc")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+4);
assert(m.length(0) == 3);
assert(m.position(0) == 0);
assert(m.str(0) == "abc");
}
{
std::cmatch m;
const char s[] = "aabc";
assert(!std::regex_search(s, m, std::regex("^abc")));
assert(m.size() == 0);
}
{
std::cmatch m;
const char s[] = "abc";
assert(std::regex_search(s, m, std::regex("abc$")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+3);
assert(m.length(0) == 3);
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "efabc";
assert(std::regex_search(s, m, std::regex("abc$")));
assert(m.size() == 1);
assert(m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+5);
assert(m.length(0) == 3);
assert(m.position(0) == 2);
assert(m.str(0) == s+2);
}
{
std::cmatch m;
const char s[] = "efabcg";
assert(!std::regex_search(s, m, std::regex("abc$")));
assert(m.size() == 0);
}
{
std::cmatch m;
const char s[] = "abc";
assert(std::regex_search(s, m, std::regex("a.c")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+3);
assert(m.length(0) == 3);
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "acc";
assert(std::regex_search(s, m, std::regex("a.c")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+3);
assert(m.length(0) == 3);
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "acc";
assert(std::regex_search(s, m, std::regex("a.c")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+3);
assert(m.length(0) == 3);
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "abcdef";
assert(std::regex_search(s, m, std::regex("(.*).*")));
assert(m.size() == 2);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+6);
assert(m.length(0) == 6);
assert(m.position(0) == 0);
assert(m.str(0) == s);
assert(m.length(1) == 6);
assert(m.position(1) == 0);
assert(m.str(1) == s);
}
{
std::cmatch m;
const char s[] = "bc";
assert(std::regex_search(s, m, std::regex("(a*)*")));
assert(m.size() == 2);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+2);
assert(m.length(0) == 0);
assert(m.position(0) == 0);
assert(m.str(0) == "");
assert(m.length(1) == 0);
assert(m.position(1) == 0);
assert(m.str(1) == "");
}
{
std::cmatch m;
const char s[] = "abbc";
assert(!std::regex_search(s, m, std::regex("ab{3,5}c")));
assert(m.size() == 0);
}
{
std::cmatch m;
const char s[] = "abbbc";
assert(std::regex_search(s, m, std::regex("ab{3,5}c")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<char>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "abbbbc";
assert(std::regex_search(s, m, std::regex("ab{3,5}c")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<char>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "abbbbbc";
assert(std::regex_search(s, m, std::regex("ab{3,5}c")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<char>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "adefc";
assert(!std::regex_search(s, m, std::regex("ab{3,5}c")));
assert(m.size() == 0);
}
{
std::cmatch m;
const char s[] = "abbbbbbc";
assert(!std::regex_search(s, m, std::regex("ab{3,5}c")));
assert(m.size() == 0);
}
{
std::cmatch m;
const char s[] = "adec";
assert(!std::regex_search(s, m, std::regex("a.{3,5}c")));
assert(m.size() == 0);
}
{
std::cmatch m;
const char s[] = "adefc";
assert(std::regex_search(s, m, std::regex("a.{3,5}c")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<char>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "adefgc";
assert(std::regex_search(s, m, std::regex("a.{3,5}c")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<char>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "adefghc";
assert(std::regex_search(s, m, std::regex("a.{3,5}c")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<char>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "adefghic";
assert(!std::regex_search(s, m, std::regex("a.{3,5}c")));
assert(m.size() == 0);
}
{
std::cmatch m;
const char s[] = "tournament";
assert(std::regex_search(s, m, std::regex("tour|to|tournament")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s + std::char_traits<char>::length(s));
assert(m.length(0) == 4);
assert(m.position(0) == 0);
assert(m.str(0) == "tour");
}
{
std::cmatch m;
const char s[] = "tournamenttotour";
assert(std::regex_search(s, m, std::regex("(tour|to|tournament)+",
std::regex_constants::nosubs)));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s + std::char_traits<char>::length(s));
assert(m.length(0) == 4);
assert(m.position(0) == 0);
assert(m.str(0) == "tour");
}
{
std::cmatch m;
const char s[] = "ttotour";
assert(std::regex_search(s, m, std::regex("(tour|to|t)+")));
assert(m.size() == 2);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<char>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
assert(m.length(1) == 4);
assert(m.position(1) == 3);
assert(m.str(1) == "tour");
}
{
std::cmatch m;
const char s[] = "-ab,ab-";
assert(!std::regex_search(s, m, std::regex("-(.*),\1-")));
assert(m.size() == 0);
}
{
std::cmatch m;
const char s[] = "-ab,ab-";
assert(std::regex_search(s, m, std::regex("-.*,.*-")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<char>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "a";
assert(std::regex_search(s, m, std::regex("^[a]$")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == 1);
assert(m.position(0) == 0);
assert(m.str(0) == "a");
}
{
std::cmatch m;
const char s[] = "a";
assert(std::regex_search(s, m, std::regex("^[ab]$")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == 1);
assert(m.position(0) == 0);
assert(m.str(0) == "a");
}
{
std::cmatch m;
const char s[] = "c";
assert(std::regex_search(s, m, std::regex("^[a-f]$")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == 1);
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "g";
assert(!std::regex_search(s, m, std::regex("^[a-f]$")));
assert(m.size() == 0);
}
{
std::cmatch m;
const char s[] = "Iraqi";
assert(std::regex_search(s, m, std::regex("q[^u]")));
assert(m.size() == 1);
assert(m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == 2);
assert(m.position(0) == 3);
assert(m.str(0) == "qi");
}
{
std::cmatch m;
const char s[] = "Iraq";
assert(!std::regex_search(s, m, std::regex("q[^u]")));
assert(m.size() == 0);
}
{
std::cmatch m;
const char s[] = "AmB";
assert(std::regex_search(s, m, std::regex("A[[:lower:]]B")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<char>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "AMB";
assert(!std::regex_search(s, m, std::regex("A[[:lower:]]B")));
assert(m.size() == 0);
}
{
std::cmatch m;
const char s[] = "AMB";
assert(std::regex_search(s, m, std::regex("A[^[:lower:]]B")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<char>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "AmB";
assert(!std::regex_search(s, m, std::regex("A[^[:lower:]]B")));
assert(m.size() == 0);
}
{
std::cmatch m;
const char s[] = "A5B";
assert(!std::regex_search(s, m, std::regex("A[^[:lower:]0-9]B")));
assert(m.size() == 0);
}
{
std::cmatch m;
const char s[] = "A?B";
assert(std::regex_search(s, m, std::regex("A[^[:lower:]0-9]B")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<char>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "-";
assert(std::regex_search(s, m, std::regex("[a[.hyphen.]z]")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<char>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "z";
assert(std::regex_search(s, m, std::regex("[a[.hyphen.]z]")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<char>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "m";
assert(!std::regex_search(s, m, std::regex("[a[.hyphen.]z]")));
assert(m.size() == 0);
}
std::locale::global(std::locale("cs_CZ.ISO8859-2"));
{
std::cmatch m;
const char s[] = "m";
assert(std::regex_search(s, m, std::regex("[a[=M=]z]")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<char>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "Ch";
assert(std::regex_search(s, m, std::regex("[a[.ch.]z]",
std::regex_constants::icase)));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<char>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
std::locale::global(std::locale("C"));
{
std::cmatch m;
const char s[] = "m";
assert(!std::regex_search(s, m, std::regex("[a[=M=]z]")));
assert(m.size() == 0);
}
{
std::cmatch m;
const char s[] = "01a45cef9";
assert(std::regex_search(s, m, std::regex("[ace1-9]*")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s + std::char_traits<char>::length(s));
assert(m.length(0) == 0);
assert(m.position(0) == 0);
assert(m.str(0) == "");
}
{
std::cmatch m;
const char s[] = "01a45cef9";
assert(std::regex_search(s, m, std::regex("[ace1-9]+")));
assert(m.size() == 1);
assert(m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s + std::char_traits<char>::length(s));
assert(m.length(0) == 6);
assert(m.position(0) == 1);
assert(m.str(0) == "1a45ce");
}
{
const char r[] = "^[-+]?[0-9]+[CF]$";
std::ptrdiff_t sr = std::char_traits<char>::length(r);
typedef forward_iterator<const char*> FI;
typedef bidirectional_iterator<const char*> BI;
std::regex regex(FI(r), FI(r+sr));
std::match_results<BI> m;
const char s[] = "-40C";
std::ptrdiff_t ss = std::char_traits<char>::length(s);
assert(std::regex_search(BI(s), BI(s+ss), m, regex));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == BI(s));
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == 4);
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::cmatch m;
const char s[] = "Jeff Jeffs ";
assert(std::regex_search(s, m, std::regex("Jeff(?=s\\b)")));
assert(m.size() == 1);
assert(m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s + std::char_traits<char>::length(s));
assert(m.length(0) == 4);
assert(m.position(0) == 5);
assert(m.str(0) == "Jeff");
}
{
std::cmatch m;
const char s[] = "Jeffs Jeff";
assert(std::regex_search(s, m, std::regex("Jeff(?!s\\b)")));
assert(m.size() == 1);
assert(m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s + std::char_traits<char>::length(s));
assert(m.length(0) == 4);
assert(m.position(0) == 6);
assert(m.str(0) == "Jeff");
}
{
std::cmatch m;
const char s[] = "5%k";
assert(std::regex_search(s, m, std::regex("\\d[\\W]k")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s + std::char_traits<char>::length(s));
assert(m.length(0) == std::char_traits<char>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"a";
assert(std::regex_search(s, m, std::wregex(L"a")));
assert(m.size() == 1);
assert(!m.empty());
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+1);
assert(m.length(0) == 1);
assert(m.position(0) == 0);
assert(m.str(0) == L"a");
}
{
std::wcmatch m;
const wchar_t s[] = L"ab";
assert(std::regex_search(s, m, std::wregex(L"ab")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+2);
assert(m.length(0) == 2);
assert(m.position(0) == 0);
assert(m.str(0) == L"ab");
}
{
std::wcmatch m;
const wchar_t s[] = L"ab";
assert(!std::regex_search(s, m, std::wregex(L"ba")));
assert(m.size() == 0);
assert(m.empty());
}
{
std::wcmatch m;
const wchar_t s[] = L"aab";
assert(std::regex_search(s, m, std::wregex(L"ab")));
assert(m.size() == 1);
assert(m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+3);
assert(m.length(0) == 2);
assert(m.position(0) == 1);
assert(m.str(0) == L"ab");
}
{
std::wcmatch m;
const wchar_t s[] = L"aab";
assert(!std::regex_search(s, m, std::wregex(L"ab"),
std::regex_constants::match_continuous));
assert(m.size() == 0);
}
{
std::wcmatch m;
const wchar_t s[] = L"abcd";
assert(std::regex_search(s, m, std::wregex(L"bc")));
assert(m.size() == 1);
assert(m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+4);
assert(m.length(0) == 2);
assert(m.position(0) == 1);
assert(m.str(0) == L"bc");
}
{
std::wcmatch m;
const wchar_t s[] = L"abbc";
assert(std::regex_search(s, m, std::wregex(L"ab*c")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+4);
assert(m.length(0) == 4);
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"ababc";
assert(std::regex_search(s, m, std::wregex(L"(ab)*c")));
assert(m.size() == 2);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+5);
assert(m.length(0) == 5);
assert(m.position(0) == 0);
assert(m.str(0) == s);
assert(m.length(1) == 2);
assert(m.position(1) == 2);
assert(m.str(1) == L"ab");
}
{
std::wcmatch m;
const wchar_t s[] = L"abcdefghijk";
assert(std::regex_search(s, m, std::wregex(L"cd((e)fg)hi")));
assert(m.size() == 3);
assert(m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+std::regex_traits<wchar_t>::length(s));
assert(m.length(0) == 7);
assert(m.position(0) == 2);
assert(m.str(0) == L"cdefghi");
assert(m.length(1) == 3);
assert(m.position(1) == 4);
assert(m.str(1) == L"efg");
assert(m.length(2) == 1);
assert(m.position(2) == 4);
assert(m.str(2) == L"e");
}
{
std::wcmatch m;
const wchar_t s[] = L"abc";
assert(std::regex_search(s, m, std::wregex(L"^abc")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+3);
assert(m.length(0) == 3);
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"abcd";
assert(std::regex_search(s, m, std::wregex(L"^abc")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+4);
assert(m.length(0) == 3);
assert(m.position(0) == 0);
assert(m.str(0) == L"abc");
}
{
std::wcmatch m;
const wchar_t s[] = L"aabc";
assert(!std::regex_search(s, m, std::wregex(L"^abc")));
assert(m.size() == 0);
}
{
std::wcmatch m;
const wchar_t s[] = L"abc";
assert(std::regex_search(s, m, std::wregex(L"abc$")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+3);
assert(m.length(0) == 3);
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"efabc";
assert(std::regex_search(s, m, std::wregex(L"abc$")));
assert(m.size() == 1);
assert(m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+5);
assert(m.length(0) == 3);
assert(m.position(0) == 2);
assert(m.str(0) == s+2);
}
{
std::wcmatch m;
const wchar_t s[] = L"efabcg";
assert(!std::regex_search(s, m, std::wregex(L"abc$")));
assert(m.size() == 0);
}
{
std::wcmatch m;
const wchar_t s[] = L"abc";
assert(std::regex_search(s, m, std::wregex(L"a.c")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+3);
assert(m.length(0) == 3);
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"acc";
assert(std::regex_search(s, m, std::wregex(L"a.c")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+3);
assert(m.length(0) == 3);
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"acc";
assert(std::regex_search(s, m, std::wregex(L"a.c")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+3);
assert(m.length(0) == 3);
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"abcdef";
assert(std::regex_search(s, m, std::wregex(L"(.*).*")));
assert(m.size() == 2);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+6);
assert(m.length(0) == 6);
assert(m.position(0) == 0);
assert(m.str(0) == s);
assert(m.length(1) == 6);
assert(m.position(1) == 0);
assert(m.str(1) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"bc";
assert(std::regex_search(s, m, std::wregex(L"(a*)*")));
assert(m.size() == 2);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s+2);
assert(m.length(0) == 0);
assert(m.position(0) == 0);
assert(m.str(0) == L"");
assert(m.length(1) == 0);
assert(m.position(1) == 0);
assert(m.str(1) == L"");
}
{
std::wcmatch m;
const wchar_t s[] = L"abbc";
assert(!std::regex_search(s, m, std::wregex(L"ab{3,5}c")));
assert(m.size() == 0);
}
{
std::wcmatch m;
const wchar_t s[] = L"abbbc";
assert(std::regex_search(s, m, std::wregex(L"ab{3,5}c")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<wchar_t>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"abbbbc";
assert(std::regex_search(s, m, std::wregex(L"ab{3,5}c")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<wchar_t>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"abbbbbc";
assert(std::regex_search(s, m, std::wregex(L"ab{3,5}c")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<wchar_t>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"adefc";
assert(!std::regex_search(s, m, std::wregex(L"ab{3,5}c")));
assert(m.size() == 0);
}
{
std::wcmatch m;
const wchar_t s[] = L"abbbbbbc";
assert(!std::regex_search(s, m, std::wregex(L"ab{3,5}c")));
assert(m.size() == 0);
}
{
std::wcmatch m;
const wchar_t s[] = L"adec";
assert(!std::regex_search(s, m, std::wregex(L"a.{3,5}c")));
assert(m.size() == 0);
}
{
std::wcmatch m;
const wchar_t s[] = L"adefc";
assert(std::regex_search(s, m, std::wregex(L"a.{3,5}c")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<wchar_t>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"adefgc";
assert(std::regex_search(s, m, std::wregex(L"a.{3,5}c")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<wchar_t>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"adefghc";
assert(std::regex_search(s, m, std::wregex(L"a.{3,5}c")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<wchar_t>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"adefghic";
assert(!std::regex_search(s, m, std::wregex(L"a.{3,5}c")));
assert(m.size() == 0);
}
{
std::wcmatch m;
const wchar_t s[] = L"tournament";
assert(std::regex_search(s, m, std::wregex(L"tour|to|tournament")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s + std::char_traits<wchar_t>::length(s));
assert(m.length(0) == 4);
assert(m.position(0) == 0);
assert(m.str(0) == L"tour");
}
{
std::wcmatch m;
const wchar_t s[] = L"tournamenttotour";
assert(std::regex_search(s, m, std::wregex(L"(tour|to|tournament)+",
std::regex_constants::nosubs)));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s + std::char_traits<wchar_t>::length(s));
assert(m.length(0) == 4);
assert(m.position(0) == 0);
assert(m.str(0) == L"tour");
}
{
std::wcmatch m;
const wchar_t s[] = L"ttotour";
assert(std::regex_search(s, m, std::wregex(L"(tour|to|t)+")));
assert(m.size() == 2);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<wchar_t>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
assert(m.length(1) == 4);
assert(m.position(1) == 3);
assert(m.str(1) == L"tour");
}
{
std::wcmatch m;
const wchar_t s[] = L"-ab,ab-";
assert(!std::regex_search(s, m, std::wregex(L"-(.*),\1-")));
assert(m.size() == 0);
}
{
std::wcmatch m;
const wchar_t s[] = L"-ab,ab-";
assert(std::regex_search(s, m, std::wregex(L"-.*,.*-")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<wchar_t>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"a";
assert(std::regex_search(s, m, std::wregex(L"^[a]$")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == 1);
assert(m.position(0) == 0);
assert(m.str(0) == L"a");
}
{
std::wcmatch m;
const wchar_t s[] = L"a";
assert(std::regex_search(s, m, std::wregex(L"^[ab]$")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == 1);
assert(m.position(0) == 0);
assert(m.str(0) == L"a");
}
{
std::wcmatch m;
const wchar_t s[] = L"c";
assert(std::regex_search(s, m, std::wregex(L"^[a-f]$")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == 1);
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"g";
assert(!std::regex_search(s, m, std::wregex(L"^[a-f]$")));
assert(m.size() == 0);
}
{
std::wcmatch m;
const wchar_t s[] = L"Iraqi";
assert(std::regex_search(s, m, std::wregex(L"q[^u]")));
assert(m.size() == 1);
assert(m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == 2);
assert(m.position(0) == 3);
assert(m.str(0) == L"qi");
}
{
std::wcmatch m;
const wchar_t s[] = L"Iraq";
assert(!std::regex_search(s, m, std::wregex(L"q[^u]")));
assert(m.size() == 0);
}
{
std::wcmatch m;
const wchar_t s[] = L"AmB";
assert(std::regex_search(s, m, std::wregex(L"A[[:lower:]]B")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<wchar_t>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"AMB";
assert(!std::regex_search(s, m, std::wregex(L"A[[:lower:]]B")));
assert(m.size() == 0);
}
{
std::wcmatch m;
const wchar_t s[] = L"AMB";
assert(std::regex_search(s, m, std::wregex(L"A[^[:lower:]]B")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<wchar_t>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"AmB";
assert(!std::regex_search(s, m, std::wregex(L"A[^[:lower:]]B")));
assert(m.size() == 0);
}
{
std::wcmatch m;
const wchar_t s[] = L"A5B";
assert(!std::regex_search(s, m, std::wregex(L"A[^[:lower:]0-9]B")));
assert(m.size() == 0);
}
{
std::wcmatch m;
const wchar_t s[] = L"A?B";
assert(std::regex_search(s, m, std::wregex(L"A[^[:lower:]0-9]B")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<wchar_t>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"-";
assert(std::regex_search(s, m, std::wregex(L"[a[.hyphen.]z]")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<wchar_t>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"z";
assert(std::regex_search(s, m, std::wregex(L"[a[.hyphen.]z]")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<wchar_t>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"m";
assert(!std::regex_search(s, m, std::wregex(L"[a[.hyphen.]z]")));
assert(m.size() == 0);
}
std::locale::global(std::locale("cs_CZ.ISO8859-2"));
{
std::wcmatch m;
const wchar_t s[] = L"m";
assert(std::regex_search(s, m, std::wregex(L"[a[=M=]z]")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<wchar_t>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"Ch";
assert(std::regex_search(s, m, std::wregex(L"[a[.ch.]z]",
std::regex_constants::icase)));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == std::char_traits<wchar_t>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
std::locale::global(std::locale("C"));
{
std::wcmatch m;
const wchar_t s[] = L"m";
assert(!std::regex_search(s, m, std::wregex(L"[a[=M=]z]")));
assert(m.size() == 0);
}
{
std::wcmatch m;
const wchar_t s[] = L"01a45cef9";
assert(std::regex_search(s, m, std::wregex(L"[ace1-9]*")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s + std::char_traits<wchar_t>::length(s));
assert(m.length(0) == 0);
assert(m.position(0) == 0);
assert(m.str(0) == L"");
}
{
std::wcmatch m;
const wchar_t s[] = L"01a45cef9";
assert(std::regex_search(s, m, std::wregex(L"[ace1-9]+")));
assert(m.size() == 1);
assert(m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s + std::char_traits<wchar_t>::length(s));
assert(m.length(0) == 6);
assert(m.position(0) == 1);
assert(m.str(0) == L"1a45ce");
}
{
const wchar_t r[] = L"^[-+]?[0-9]+[CF]$";
std::ptrdiff_t sr = std::char_traits<wchar_t>::length(r);
typedef forward_iterator<const wchar_t*> FI;
typedef bidirectional_iterator<const wchar_t*> BI;
std::wregex regex(FI(r), FI(r+sr));
std::match_results<BI> m;
const wchar_t s[] = L"-40C";
std::ptrdiff_t ss = std::char_traits<wchar_t>::length(s);
assert(std::regex_search(BI(s), BI(s+ss), m, regex));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == BI(s));
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == m[0].second);
assert(m.length(0) == 4);
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
{
std::wcmatch m;
const wchar_t s[] = L"Jeff Jeffs ";
assert(std::regex_search(s, m, std::wregex(L"Jeff(?=s\\b)")));
assert(m.size() == 1);
assert(m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s + std::char_traits<wchar_t>::length(s));
assert(m.length(0) == 4);
assert(m.position(0) == 5);
assert(m.str(0) == L"Jeff");
}
{
std::wcmatch m;
const wchar_t s[] = L"Jeffs Jeff";
assert(std::regex_search(s, m, std::wregex(L"Jeff(?!s\\b)")));
assert(m.size() == 1);
assert(m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s + std::char_traits<wchar_t>::length(s));
assert(m.length(0) == 4);
assert(m.position(0) == 6);
assert(m.str(0) == L"Jeff");
}
{
std::wcmatch m;
const wchar_t s[] = L"5%k";
assert(std::regex_search(s, m, std::wregex(L"\\d[\\W]k")));
assert(m.size() == 1);
assert(!m.prefix().matched);
assert(m.prefix().first == s);
assert(m.prefix().second == m[0].first);
assert(!m.suffix().matched);
assert(m.suffix().first == m[0].second);
assert(m.suffix().second == s + std::char_traits<wchar_t>::length(s));
assert(m.length(0) == std::char_traits<wchar_t>::length(s));
assert(m.position(0) == 0);
assert(m.str(0) == s);
}
}
| [
"karun.matharu@gmail.com"
] | karun.matharu@gmail.com |
aff03b97c41982330419a5300e24e32f4af7148f | c6885cb056876cf02998e71c70ecf756506798ff | /MemoryAllocator/BitArray.h | 435805ceb5f3dc19ea851351905b0172f0d42f35 | [] | no_license | Frankjaamy/ParkingLord-GameEngine- | 1d0a355138b7586effd4ebc4dbece84b209ae550 | 785d5be30bb7dd42890684530b3dbaee9ce98909 | refs/heads/master | 2021-05-15T10:46:37.735233 | 2017-10-25T00:58:13 | 2017-10-25T00:58:13 | 108,200,128 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,291 | h | #pragma once
#include<stdint.h>
#include <cstring>
#ifdef _WIN64
#define ALLSET 0xFFFFFFFFFFFFFFFF
#define EMPTY 0x0000000000000000
typedef uint64_t bit_array_type;
const size_t UnitSize = 64;
#else
#define ALLSET 0xFFFFFFFF
#define EMPTY 0x00000000
typedef uint32_t bit_array_type;
const size_t UnitSize = 32;
#endif // _WIN64
class BitArray {
public:
static BitArray * create(size_t bitsWanted);
~BitArray();
void setBit(const size_t indexOfArray);
void clearBit(const size_t indexOfArray);
bool isBitSet(const size_t indexOfArray);
bool isBitClear(const size_t indexOfArray);
bool getFirstSetBit(size_t & o_bitPosition) const;
bool getFirstClearBit(size_t & o_bitPosition) const;
inline void clearAll() {memset(bitArray, 0x00, (totalSize / BitArrayUnitSize) * sizeof(bit_array_type));}
inline void setAll() { memset(bitArray, 0xFF, (totalSize / BitArrayUnitSize) * sizeof(bit_array_type));}
bool areAllClear() const;
bool areAllSet()const;
BitArray(size_t totalBitsWanted, void * memory, bool setBitArray);
inline const size_t getCurrentBitUnitSize() const { return BitArrayUnitSize; }
inline const size_t getTotalSize() const { return totalSize; }
const static size_t BitArrayUnitSize = UnitSize;
private:
bit_array_type * bitArray;
size_t totalSize;
}; | [
"u1072146@ad.utah.edu"
] | u1072146@ad.utah.edu |
ddef8debe8d030196b5cab7d52e22dbc836d5aac | 21a880dcdf84fd0c812f8506763a689fde297ba7 | /src/main/cme_exchange/server/server_application.cc | 029f5eba784bab955aa785983a837fabb2ace062 | [] | no_license | chenlucan/fix_handler | 91df9037eeb675b0c7ea6f22d541da74b220092f | 765462ff1a85567f43f63e04c29dbc9546a6c2e1 | refs/heads/master | 2021-03-22T02:07:39.016551 | 2017-08-01T02:02:20 | 2017-08-01T02:02:20 | 84,138,943 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 9,028 | cc |
#include <boost/algorithm/string.hpp>
#include <quickfix/fix42/TestRequest.h>
#include <quickfix/fix42/ExecutionReport.h>
#include <quickfix/fix42/OrderCancelReject.h>
#include "server_application.h"
#include "cme/exchange/message/OrderMassActionReport.h"
void Application::onLogon( const FIX::SessionID& sessionID )
{
std::cout << "on logon" << std::endl;
// send test request
auto id = FIX::TestReqID("Test-request-id-100");
FIX42::TestRequest testRequest(id);
FIX::Session::sendToTarget( testRequest, sessionID.getSenderCompID(), sessionID.getTargetCompID() );
// std::this_thread::sleep_for(std::chrono::milliseconds(5000));
// // send gap fill message
// auto no = FIX::NewSeqNo(50);
// auto f = FIX::GapFillFlag("Y");
// FIX42::SequenceReset reset(no);
// reset.set(f);
// FIX::Session::sendToTarget( reset, sessionID.getSenderCompID(), sessionID.getTargetCompID() );
// 测试发送 Order Mass Action Report
fh::cme::exchange::message::OrderMassActionReport report;
report.setField(FIX::FIELD::ClOrdID, "xyz");
FIX::Session::sendToTarget( report, sessionID.getSenderCompID(), sessionID.getTargetCompID() );
}
void Application::onLogout( const FIX::SessionID& sessionID ) {}
void Application::fromApp( const FIX::Message& message,
const FIX::SessionID& sessionID )
throw( FIX::FieldNotFound, FIX::IncorrectDataFormat, FIX::IncorrectTagValue, FIX::UnsupportedMessageType )
{
crack( message, sessionID );
std::cout << "from app: " << boost::replace_all_copy(message.toString(), "\001", " ") << std::endl;
}
void Application::fromAdmin( const FIX::Message& message, const FIX::SessionID& sessionID)
throw( FIX::FieldNotFound, FIX::IncorrectDataFormat, FIX::IncorrectTagValue, FIX::RejectLogon )
{
crack( message, sessionID );
std::cout << "from admin: " << boost::replace_all_copy(message.toString(), "\001", " ") << std::endl;
}
void Application::onMessage( const FIX42::NewOrderSingle& message, const FIX::SessionID& )
{
FIX::SenderCompID senderCompID;
FIX::TargetCompID targetCompID;
FIX::ClOrdID clOrdID;
FIX::Symbol symbol;
FIX::Side side;
FIX::OrdType ordType;
FIX::Price price;
FIX::OrderQty orderQty;
FIX::TimeInForce timeInForce( FIX::TimeInForce_DAY );
message.getHeader().get( senderCompID );
message.getHeader().get( targetCompID );
message.get( clOrdID );
message.get( symbol );
message.get( side );
message.get( ordType );
if ( ordType == FIX::OrdType_LIMIT )
message.get( price );
message.get( orderQty );
message.getFieldIfSet( timeInForce );
try
{
if ( timeInForce != FIX::TimeInForce_DAY )
throw std::logic_error( "Unsupported TIF, use Day" );
Order order( clOrdID, symbol, senderCompID, targetCompID,
convert( side ), convert( ordType ),
price, (long)orderQty );
processOrder( order );
}
catch ( std::exception & e )
{
rejectOrder( senderCompID, targetCompID, clOrdID, symbol, side, e.what() );
}
}
void Application::onMessage( const FIX42::OrderCancelRequest& message, const FIX::SessionID& )
{
FIX::OrigClOrdID origClOrdID;
FIX::Symbol symbol;
FIX::Side side;
message.get( origClOrdID );
message.get( symbol );
message.get( side );
try
{
processCancel( origClOrdID, symbol, convert( side ) );
}
catch ( std::exception& ) {}
}
void Application::onMessage( const FIX42::OrderCancelReplaceRequest& message, const FIX::SessionID& )
{
std::cout << "OrderCancelReplaceRequest: " << message << std::endl;
}
void Application::onMessage( const FIX42::OrderStatusRequest& message, const FIX::SessionID& session )
{
std::cout << "OrderStatusRequest: " << message << std::endl;
FIX42::OrderCancelReject ocr;
ocr.set(FIX::Account("yyc-back"));
ocr.set(FIX::ClOrdID("Client-order-1"));
//ocr.set(FIX::ExecID("fill-id-1"));
ocr.set(FIX::OrderID("server-order-1"));
ocr.set(FIX::OrdStatus('U'));
ocr.set(FIX::TransactTime(true));
//ocr.set(FIX::CancelRejResponseTo('2'));
//ocr.set(FIX::CorrelationClOrdID("Client-order-1"));
ocr.set(FIX::Text("something rejected"));
FIX::Session::sendToTarget( ocr, session.getSenderCompID(), session.getTargetCompID() );
}
//void Application::onMessage( const FIX42::Logon& message, const FIX::SessionID& )
//{
// std::cout << "Logon: " << message << std::endl;
//}
//void Application::onMessage( const FIX42::MarketDataRequest& message, const FIX::SessionID& )
//{
// FIX::MDReqID mdReqID;
// FIX::SubscriptionRequestType subscriptionRequestType;
// FIX::MarketDepth marketDepth;
// FIX::NoRelatedSym noRelatedSym;
// FIX42::MarketDataRequest::NoRelatedSym noRelatedSymGroup;
//
// message.get( mdReqID );
// message.get( subscriptionRequestType );
// if ( subscriptionRequestType != FIX::SubscriptionRequestType_SNAPSHOT )
// throw( FIX::IncorrectTagValue( subscriptionRequestType.getField() ) );
// message.get( marketDepth );
// message.get( noRelatedSym );
//
// for ( int i = 1; i <= noRelatedSym; ++i )
// {
// FIX::Symbol symbol;
// message.getGroup( i, noRelatedSymGroup );
// noRelatedSymGroup.get( symbol );
// }
//}
//void Application::onMessage( const FIX43::MarketDataRequest& message, const FIX::SessionID& )
//{
// std::cout << message.toXML() << std::endl;
//}
void Application::updateOrder( const Order& order, char status )
{
FIX::TargetCompID targetCompID( order.getOwner() );
FIX::SenderCompID senderCompID( order.getTarget() );
FIX42::ExecutionReport fixOrder
( FIX::OrderID ( order.getClientID() ),
FIX::ExecID ( m_generator.genExecutionID() ),
FIX::ExecTransType ( FIX::ExecTransType_NEW ),
FIX::ExecType ( status ),
FIX::OrdStatus ( status ),
FIX::Symbol ( order.getSymbol() ),
FIX::Side ( convert( order.getSide() ) ),
FIX::LeavesQty ( order.getOpenQuantity() ),
FIX::CumQty ( order.getExecutedQuantity() ),
FIX::AvgPx ( order.getAvgExecutedPrice() ) );
fixOrder.set( FIX::ClOrdID( order.getClientID() ) );
fixOrder.set( FIX::OrderQty( order.getQuantity() ) );
fixOrder.set(FIX::Account("yyc-back"));
if ( status == FIX::OrdStatus_FILLED ||
status == FIX::OrdStatus_PARTIALLY_FILLED )
{
fixOrder.set( FIX::LastShares( order.getLastExecutedQuantity() ) );
fixOrder.set( FIX::LastPx( order.getLastExecutedPrice() ) );
}
try
{
FIX::Session::sendToTarget( fixOrder, senderCompID, targetCompID );
}
catch ( FIX::SessionNotFound& ) {}}
void Application::rejectOrder
( const FIX::SenderCompID& sender, const FIX::TargetCompID& target,
const FIX::ClOrdID& clOrdID, const FIX::Symbol& symbol,
const FIX::Side& side, const std::string& message )
{
FIX::TargetCompID targetCompID( sender.getValue() );
FIX::SenderCompID senderCompID( target.getValue() );
FIX42::ExecutionReport fixOrder
( FIX::OrderID ( clOrdID.getValue() ),
FIX::ExecID ( m_generator.genExecutionID() ),
FIX::ExecTransType ( FIX::ExecTransType_NEW ),
FIX::ExecType ( FIX::ExecType_REJECTED ),
FIX::OrdStatus ( FIX::ExecType_REJECTED ),
symbol, side, FIX::LeavesQty( 0 ), FIX::CumQty( 0 ), FIX::AvgPx( 0 ) );
fixOrder.set( clOrdID );
fixOrder.set( FIX::Text( message ) );
fixOrder.set(FIX::Account("yyc-back"));
try
{
FIX::Session::sendToTarget( fixOrder, senderCompID, targetCompID );
}
catch ( FIX::SessionNotFound& ) {}}
void Application::processOrder( const Order& order )
{
if ( m_orderMatcher.insert( order ) )
{
acceptOrder( order );
std::queue < Order > orders;
m_orderMatcher.match( order.getSymbol(), orders );
while ( orders.size() )
{
fillOrder( orders.front() );
orders.pop();
}
}
else
rejectOrder( order );
}
void Application::processCancel( const std::string& id,
const std::string& symbol, Order::Side side )
{
Order & order = m_orderMatcher.find( symbol, side, id );
order.cancel();
cancelOrder( order );
m_orderMatcher.erase( order );
}
Order::Side Application::convert( const FIX::Side& side )
{
switch ( side )
{
case FIX::Side_BUY: return Order::buy;
case FIX::Side_SELL: return Order::sell;
default: throw std::logic_error( "Unsupported Side, use buy or sell" );
}
}
Order::Type Application::convert( const FIX::OrdType& ordType )
{
switch ( ordType )
{
case FIX::OrdType_LIMIT: return Order::limit;
default: throw std::logic_error( "Unsupported Order Type, use limit" );
}
}
FIX::Side Application::convert( Order::Side side )
{
switch ( side )
{
case Order::buy: return FIX::Side( FIX::Side_BUY );
case Order::sell: return FIX::Side( FIX::Side_SELL );
default: throw std::logic_error( "Unsupported Side, use buy or sell" );
}
}
FIX::OrdType Application::convert( Order::Type type )
{
switch ( type )
{
case Order::limit: return FIX::OrdType( FIX::OrdType_LIMIT );
default: throw std::logic_error( "Unsupported Order Type, use limit" );
}
}
| [
"ycyang77@hotmail.com"
] | ycyang77@hotmail.com |
f70e270e157c9fb6546a1820690dd073173579fd | 3dd0c8191bd68742cfc454ce46fc807d65642eba | /src/random_test_direct.cpp | d0666b3e521e3593ddff7d50f1e58c7dde2c0bfa | [
"BSD-3-Clause"
] | permissive | Ju-Yeon/cpp-lru-cache | ecd14ad655a3c94fdb0efdd69572604230da8c7e | 379096cc0317f908f3e3d37986ee148ef0fa16c9 | refs/heads/master | 2020-08-29T23:58:37.460772 | 2019-11-14T06:11:21 | 2019-11-14T06:11:21 | 218,208,461 | 0 | 0 | BSD-3-Clause | 2019-10-29T05:07:59 | 2019-10-29T05:07:59 | null | UTF-8 | C++ | false | false | 1,037 | cpp | #include <iostream>
#include <stdlib.h>
#include <ctime>
#include "lrucache_direct.hpp"
#include "gtest/gtest.h"
const int NUM_OF_TEST1_RECORDS = 100;
const int NUM_OF_TEST2_RECORDS = 1000000;
const int TEST2_CACHE_CAPACITY = 500000;
TEST(CacheTest1, KeepsAllValuesWithinCapacity) {
cache::lru_cache<int, int> cache_lru(TEST2_CACHE_CAPACITY);
int num;
for (int i = 0; i < NUM_OF_TEST2_RECORDS; ++i) {
num = (int)rand()%NUM_OF_TEST2_RECORDS;
cache_lru.put(num, num);
}
int count_t = 0;
int count_f = 0;
for (int i = 0; i < NUM_OF_TEST2_RECORDS; ++i) {
num = (int)rand()%NUM_OF_TEST2_RECORDS;
if(cache_lru.exists(num))
count_t++;
else count_f++;
}
EXPECT_EQ(count_t, count_f)<< "hit : "<<count_t << ", miss : "<< count_f;
}
int main(int argc, char **argv) {
srand((unsigned int)time(NULL));
::testing::InitGoogleTest(&argc, argv);
int ret = RUN_ALL_TESTS();
return ret;
}
| [
"pjuyeon25@gmail.com"
] | pjuyeon25@gmail.com |
a84ab318a6de1e006fa020adcbe94aaf1d940d10 | d5fdeaa6900f7bfc3aa7d3048fb803bb43b400a5 | /GCLDProject2/.svn/pristine/64/644bf7cf045a5e284091b525cf67ce65e7b421c6.svn-base | 6cfd891749ef371b6f8a962df21ae1250ff65b67 | [] | no_license | liu-jack/cxx_sth | 52e1f0b190fe23fb16890cadd9efa15de59e70d0 | 986a0782d88405af83ae68ef124ff8cf19ada765 | refs/heads/master | 2020-05-07T13:53:03.555884 | 2017-11-17T02:26:55 | 2017-11-17T02:26:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 925 | #pragma once
#include "structDef.h"
namespace pb{
class GxDB_World_Achievement_Info;
}
//set byte alignment
#pragma pack(push,1)
struct WorldFightAchievementTable : public BaseStruct {
public:
INIT_GAMEDATA(WorldFightAchievementTable);
static const bool HasIndex(){ return true; }
const Key GetKey(void) const{ return id; }
uint32 GetLogicalKey(void) const{ return city_id; }
void SetDbIncreaseId(const IdType& id_){ id = id_; }
static const char* GetDbIncreaseIdName(){ return "id"; }
static const char* GetLogicalKeyName(void){ return "city_id"; }
static const char* GetTableName(){ return "world_fight_achievement"; }
static const char* GetFormat()
{
return "bbuuu";
}
void SaveTo(pb::GxDB_World_Achievement_Info& msg);
void LoadFrom(const pb::GxDB_World_Achievement_Info& msg);
public:
IdType id;
uint64 player_id;
uint32 city_id;
uint32 type;
uint32 state;
};
#pragma pack(pop) | [
"zhoulunhao@hotmail.com"
] | zhoulunhao@hotmail.com | |
9db33d19de1a929babb8a8e51ab53ced384ea79e | 8e0cdf324e67daa61f64ca916acac0f809e6a0db | /1223B.cpp | 27054121234c8ffefec0aa8b86824b069de81e63 | [] | no_license | ayushme53/CodeforcesSolutions | b99c99590a2d1da0a89ede204c7cedee135574b8 | 2661e5cbff1a735fdfcf341d497eb90fcda56c33 | refs/heads/master | 2022-12-23T18:29:09.567107 | 2020-09-30T18:00:28 | 2020-09-30T18:00:28 | 257,911,434 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 717 | cpp | #include <bits/stdc++.h>
using namespace std;
#define faster ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL)
#define mp make_pair
#define mod 1000000007
#define qmod 998244353
#define endl "\n"
#define pb push_back
#define ff first
#define ss second
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
const int MOD = 1e9 + 7;
const int INF = 1e9 + 5;
const ll LINF = LLONG_MAX;
int main(){
int t;
cin>>t;
while(t--){
string s,x;
cin>>s>>x;
bool c=0;
for(int i=0;i<s.size();i++){
for(int j=0;j<s.size();j++){
if(s[i]==x[j])
c=1;
}
}
if(c)
cout<<"YES\n";
else
cout<<"NO\n";
}
} | [
"ayushme53@gmail.com"
] | ayushme53@gmail.com |
8c3686c94813417677ff2831d8e94bf17943ec55 | 4ef962706479e36b2726d6127484d3e37437b8ba | /Source/Csmith/src/Type.cpp | df89a73ab89dc24c5e39d610dd1652a761a904f7 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | tamiraviv/Csmith-plus-plus | a2e411c5e54997bb64664959e279b67953b5f7df | 47a5d9c60ddfc1adad67ab59f5ca0482bad1497d | refs/heads/master | 2021-08-23T06:19:33.685471 | 2017-12-03T21:29:01 | 2017-12-03T21:29:01 | 112,965,309 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 74,590 | cpp | // -*- mode: C++ -*-
//
// Copyright (c) 2007, 2008, 2010, 2011, 2013, 2014 The University of Utah
// All rights reserved.
//
// This file is part of `csmith', a random generator of C programs.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
//
// This file was derived from a random program generator written by Bryan
// Turner. The attributions in that file was:
//
// Random Program Generator
// Bryan Turner (bryan.turner@pobox.com)
// July, 2005
//
#include "Type.h"
#include <sstream>
#include <cassert>
#include <cmath>
#include "Common.h"
#include "CGOptions.h"
#include "random.h"
#include "Filter.h"
#include "Error.h"
#include "util.h"
#include "Bookkeeper.h"
#include "Probabilities.h"
#include "DepthSpec.h"
#include "Enumerator.h"
#include "Function.h"
using namespace std;
///////////////////////////////////////////////////////////////////////////////
/*
*
*/
const Type *Type::simple_types[MAX_SIMPLE_TYPES];
Type *Type::void_type = NULL;
int SubObjectTree::SubObjectNode::subObjectlastId = 0;
// ---------------------------------------------------------------------
// List of all types used in the program
static vector<Type *> AllTypes;
static vector<Type *> derived_types;
//////////////////////////////////////////////////////////////////////
class NonVoidTypeFilter : public Filter
{
public:
NonVoidTypeFilter();
virtual ~NonVoidTypeFilter();
virtual bool filter(int v) const;
Type *get_type();
private:
mutable Type *typ_;
};
NonVoidTypeFilter::NonVoidTypeFilter()
: typ_(NULL)
{
}
NonVoidTypeFilter::~NonVoidTypeFilter()
{
}
bool
NonVoidTypeFilter::filter(int v) const
{
assert(static_cast<unsigned int>(v) < AllTypes.size());
Type *type = AllTypes[v];
if (type->eType == eSimple && type->simple_type == eVoid)
return true;
if (!type->used) {
Bookkeeper::record_type_with_bitfields(type);
type->used = true;
}
typ_ = type;
if (type->eType == eSimple) {
Filter *filter = SIMPLE_TYPES_PROB_FILTER;
return filter->filter(typ_->simple_type);
}
return false;
}
Type *
NonVoidTypeFilter::get_type()
{
assert(typ_);
return typ_;
}
class NonVoidNonVolatileTypeFilter : public Filter
{
public:
NonVoidNonVolatileTypeFilter();
virtual ~NonVoidNonVolatileTypeFilter();
virtual bool filter(int v) const;
Type *get_type();
private:
mutable Type *typ_;
};
NonVoidNonVolatileTypeFilter::NonVoidNonVolatileTypeFilter()
: typ_(NULL)
{
}
NonVoidNonVolatileTypeFilter::~NonVoidNonVolatileTypeFilter()
{
}
bool
NonVoidNonVolatileTypeFilter::filter(int v) const
{
assert(static_cast<unsigned int>(v) < AllTypes.size());
Type *type = AllTypes[v];
if (type->eType == eSimple && type->simple_type == eVoid)
return true;
if (type->is_aggregate() && type->is_volatile_struct_union())
return true;
if ((type->eType == eStruct) && (!CGOptions::arg_structs())) {
return true;
}
if ((type->eType == eUnion) && (!CGOptions::arg_unions())) {
return true;
}
if (!type->used) {
Bookkeeper::record_type_with_bitfields(type);
type->used = true;
}
typ_ = type;
if (type->eType == eSimple) {
Filter *filter = SIMPLE_TYPES_PROB_FILTER;
return filter->filter(typ_->simple_type);
}
return false;
}
Type *
NonVoidNonVolatileTypeFilter::get_type()
{
assert(typ_);
return typ_;
}
class ChooseRandomTypeFilter : public Filter
{
public:
ChooseRandomTypeFilter(bool for_field_var, bool struct_has_assign_ops = false);
virtual ~ChooseRandomTypeFilter();
virtual bool filter(int v) const;
Type *get_type();
bool for_field_var_;
bool struct_has_assign_ops_;
private:
mutable Type *typ_;
};
ChooseRandomTypeFilter::ChooseRandomTypeFilter(bool for_field_var, bool struct_has_assign_ops)
: for_field_var_(for_field_var),
struct_has_assign_ops_(struct_has_assign_ops),
typ_(NULL)
{
}
ChooseRandomTypeFilter::~ChooseRandomTypeFilter()
{
}
bool
ChooseRandomTypeFilter::filter(int v) const
{
assert((v >= 0) && (static_cast<unsigned int>(v) < AllTypes.size()));
typ_ = AllTypes[v];
assert(typ_);
if (typ_->eType == eSimple) {
Filter *filter = SIMPLE_TYPES_PROB_FILTER;
return filter->filter(typ_->simple_type);
}
else if ((typ_->eType == eStruct) && (!CGOptions::return_structs())) {
return true;
}
// Struct without assignment ops can not be made a field of a struct with assign ops
// with current implementation of these ops
if (for_field_var_ && struct_has_assign_ops_ && !typ_->has_assign_ops()) {
assert(CGOptions::lang_cpp());
return true;
}
if (for_field_var_ && typ_->get_struct_depth() >= CGOptions::max_nested_struct_level()) {
return true;
}
return false;
}
Type *
ChooseRandomTypeFilter::get_type()
{
assert(typ_);
return typ_;
}
///////////////////////////////////////////////////////////////////////////////
// Helper functions
///////////////////////////////////////////////////////////////////////////////
static bool checkImplicitNontrivialAssignOps(vector<const Type*> fields)
{
if (!CGOptions::lang_cpp()) return false;
for (size_t i = 0; i < fields.size(); ++i) {
const Type* field = fields[i];
if (field->has_implicit_nontrivial_assign_ops()) {
assert((field->eType == eStruct) || (field->eType == eUnion));
return true;
}
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// --------------------------------------------------------------
/* constructor for simple types
********************************************************/
Type::Type(eSimpleType simple_type) :
eType(eSimple),
ptr_type(0),
simple_type(simple_type),
sid(0), // not used for simple types
used(false),
printed(false),
packed_(false),
has_assign_ops_(false),
has_implicit_nontrivial_assign_ops_(false)
{
// Nothing else to do.
}
// --------------------------------------------------------------
/* constructor for struct or union types
*******************************************************/
Type::Type(vector<const Type*>& struct_fields,
bool isStruct,
bool packed,
vector<CVQualifiers> &qfers,
vector<int> &fields_length,
bool hasAssignOps,
bool hasImplicitNontrivialAssignOps,
const vector<Type*> _base_classes,
vector<eAccess> _base_classes_access,
const vector<bool> _isVirtualBaseClasses,
vector<Constant*> &_fields_init,
const vector<string> &_fields_name, vector<eAccess> &_fields_access, vector<Type*> _friend_classes) :
ptr_type(0),
simple_type(MAX_SIMPLE_TYPES), // not a valid simple type
fields(struct_fields),
used(false),
printed(false),
packed_(packed),
has_assign_ops_(hasAssignOps),
has_implicit_nontrivial_assign_ops_(hasImplicitNontrivialAssignOps),
qfers_(qfers),
bitfields_length_(fields_length),
base_classes(_base_classes),
base_classes_access(_base_classes_access),
isVirtualBaseClasses(_isVirtualBaseClasses),
fields_init(_fields_init),
fields_name(_fields_name),
fields_access(_fields_access),
friend_classes(_friend_classes)
{
static unsigned int sequence = 0;
if (isStruct)
eType = eStruct;
else
eType = eUnion;
sid = sequence++;
sub_object_tree.buildTree(this);
}
// --------------------------------------------------------------
/* constructor for pointers
*******************************************************/
Type::Type(const Type* t) :
eType(ePointer),
ptr_type(t),
simple_type(MAX_SIMPLE_TYPES), // not a valid simple type
used(false),
printed(false),
packed_(false),
has_assign_ops_(false),
has_implicit_nontrivial_assign_ops_(false)
{
// Nothing else to do.
}
// --------------------------------------------------------------
Type::~Type(void)
{
// Nothing to do.
}
// --------------------------------------------------------------
#if 0
Type &
Type::operator=(const Type& t)
{
if (this == &t) {
return *this;
}
eType = t.eType;
simple_type = t.simple_type;
dimensions = t.dimensions;
fields = t.fields;
return *this;
}
#endif
// ---------------------------------------------------------------------
const Type &
Type::get_simple_type(eSimpleType st)
{
static bool inited = false;
assert(st != MAX_SIMPLE_TYPES);
if (!inited) {
for (int i = 0; i < MAX_SIMPLE_TYPES; ++i) {
Type::simple_types[i] = 0;
}
inited = true;
}
if (Type::simple_types[st] == 0) {
// find if type is in the allTypes already (most likely only "eVoid" is not there)
for (size_t i = 0; i < AllTypes.size(); i++) {
Type* tt = AllTypes[i];
if (tt->eType == eSimple && tt->simple_type == st) {
Type::simple_types[st] = tt;
}
}
if (Type::simple_types[st] == 0) {
Type *t = new Type(st);
Type::simple_types[st] = t;
AllTypes.push_back(t);
}
}
return *Type::simple_types[st];
}
const Type *
Type::get_type_from_string(const string &type_string)
{
if (type_string == "Void") {
return Type::void_type;
}
else if (type_string == "Char") {
return &Type::get_simple_type(eChar);
}
else if (type_string == "UChar") {
return &Type::get_simple_type(eUChar);
}
else if (type_string == "Short") {
return &Type::get_simple_type(eShort);
}
else if (type_string == "UShort") {
return &Type::get_simple_type(eUShort);
}
else if (type_string == "Int") {
return &Type::get_simple_type(eInt);
}
else if (type_string == "UInt") {
return &Type::get_simple_type(eUInt);
}
else if (type_string == "Long") {
return &Type::get_simple_type(eLong);
}
else if (type_string == "ULong") {
return &Type::get_simple_type(eULong);
}
else if (type_string == "Longlong") {
return &Type::get_simple_type(eLongLong);
}
else if (type_string == "ULonglong") {
return &Type::get_simple_type(eULongLong);
}
else if (type_string == "Float") {
return &Type::get_simple_type(eFloat);
}
assert(0 && "Unsupported type string!");
return NULL;
}
// ---------------------------------------------------------------------
/* return the most commonly used type - integer
*************************************************************/
const Type *
get_int_type()
{
return &Type::get_simple_type(eInt);
}
Type*
Type::find_type(const Type* t)
{
for (size_t i = 0; i < AllTypes.size(); i++) {
if (AllTypes[i] == t) {
return AllTypes[i];
}
}
return 0;
}
// ---------------------------------------------------------------------
/* find the pointer type to the given type in existing types,
* return 0 if not found
*************************************************************/
Type*
Type::find_pointer_type(const Type* t, bool add)
{
for (size_t i = 0; i < derived_types.size(); i++) {
if (derived_types[i]->ptr_type == t) {
return derived_types[i];
}
}
if (add) {
Type* ptr_type = new Type(t);
derived_types.push_back(ptr_type);
return ptr_type;
}
return 0;
}
bool
Type::is_const_struct_union() const
{
if (!is_aggregate()) return false;
assert(fields.size() == qfers_.size());
for (size_t i = 0; i < fields.size(); ++i) {
const Type *field = fields[i];
if (field->is_const_struct_union()) {
return true;
}
const CVQualifiers& cf = qfers_[i];
if (cf.is_const()) return true;
}
return false;
}
bool
Type::is_volatile_struct_union() const
{
if (!is_aggregate()) return false;
assert(fields.size() == qfers_.size());
for (size_t i = 0; i < fields.size(); ++i) {
const Type *field = fields[i];
if (field->is_volatile_struct_union()) {
return true;
}
const CVQualifiers& cf = qfers_[i];
if (cf.is_volatile())
return true;
}
return false;
}
bool
Type::has_int_field() const
{
if (is_int()) return true;
for (size_t i = 0; i < fields.size(); ++i) {
const Type* t = fields[i];
if (t->has_int_field()) return true;
}
return false;
}
bool
Type::signed_overflow_possible() const
{
return eType == eSimple && is_signed() && ((int)SizeInBytes()) >= CGOptions::int_size();
}
eAccess Type::choose_random_access(const Type * currentType, const Type * targetType)
{
vector<eAccess> valid_access;
eAccess access = Type::get_min_access(currentType, targetType);
valid_access.push_back(ePublic);
if (access <= eProtected)
valid_access.push_back(eProtected);
if (access <= ePrivate)
valid_access.push_back(ePrivate);
int index = pure_rnd_upto(valid_access.size());
return valid_access[index];
}
eAccess Type::get_min_access(const Type * currentType, const Type * targetType)
{
if (currentType != nullptr)
{
if (currentType == targetType)
return ePrivate;
for (size_t i = 0; i < currentType->friend_classes.size(); i++)
{
if (currentType->friend_classes[i] == targetType)
return ePrivate;
}
/*for (size_t i = 0; i < currentType->unambiguous_base_classes.size(); i++)
{
if (currentType->unambiguous_base_classes[i] == targetType)
return eProtected;
}*/
}
return ePublic;
}
string Type::get_access_name(eAccess access)
{
switch (access)
{
case ePrivate:
return "private";
case eProtected:
return "protected";
case ePublic:
return "public";
}
return "";
}
vector<Function*> Type::get_func_list_by_target_type(const Type * targetType)
{
vector<Function*> func_list_by_target_type;
eAccess access = get_min_access(this, targetType);
for (size_t i = 0; i < func_list.size(); i++)
{
if (access <= func_list_access[i])
func_list_by_target_type.push_back(func_list[i]);
}
return func_list_by_target_type;
}
void make_random_accesses(size_t field_cnt, vector<eAccess> &accesses)
{
vector<eAccess> valid_access;
valid_access.push_back(ePrivate);
valid_access.push_back(eProtected);
valid_access.push_back(ePublic);
valid_access.push_back(ePublic);
for (size_t i = 0; i < field_cnt; i++)
{
int index = pure_rnd_upto(valid_access.size());
accesses.push_back(valid_access[index]);
}
}
void
Type::get_all_ok_struct_union_types(vector<Type *> &ok_types, bool no_const, bool no_volatile, bool need_int_field, bool bStruct)
{
vector<Type *>::iterator i;
for (i = AllTypes.begin(); i != AllTypes.end(); ++i) {
Type* t = (*i);
if (bStruct && t->eType != eStruct) continue;
if (!bStruct && t->eType != eUnion) continue;
if ((no_const && t->is_const_struct_union()) ||
(no_volatile && t->is_volatile_struct_union()) ||
(need_int_field && (!t->has_int_field()))) {
continue;
}
ok_types.push_back(t);
}
}
bool
Type::if_struct_will_have_assign_ops()
{
// randomly choose if the struct will have assign operators (for C++):
if (!CGOptions::lang_cpp())
return false;
return rnd_flipcoin(RegularVolatileProb);
}
// To have volatile unions in C++. I am not sure if we need those
// (If not, will be enough to return false here)
bool
Type::if_union_will_have_assign_ops()
{
// randomly choose if the union will have assign operators (for C++):
if (!CGOptions::lang_cpp())
return false;
return rnd_flipcoin(RegularVolatileProb);
}
Type*
Type::choose_random_struct_union_type(vector<Type *> &ok_types)
{
size_t sz = ok_types.size();
assert(sz > 0);
int index = rnd_upto(ok_types.size());
ERROR_GUARD(0);
assert(index >= 0);
Type *rv_type = ok_types[index];
if (!rv_type->used) {
Bookkeeper::record_type_with_bitfields(rv_type);
rv_type->used = true;
}
return rv_type;
}
const Type*
Type::choose_random_pointer_type(void)
{
unsigned int index = rnd_upto(derived_types.size());
ERROR_GUARD(NULL);
return derived_types[index];
}
bool
Type::has_pointer_type(void)
{
return derived_types.size() > 0;
}
/* for exhaustive mode only */
const Type*
Type::choose_random_struct_from_type(const Type* type, bool no_volatile)
{
if (!type)
return NULL;
const Type* t = type;
vector<Type *> ok_struct_types;
get_all_ok_struct_union_types(ok_struct_types, no_volatile, false, true, true);
if (ok_struct_types.size() > 0) {
DEPTH_GUARD_BY_DEPTH_RETURN(1, NULL);
t = Type::choose_random_struct_union_type(ok_struct_types);
ERROR_GUARD(NULL);
}
return t;
}
void Type::choose_random_struct(vector<Type*> &_base_classes,unsigned int limit)
{
vector<Type *> ok_struct_types;
get_all_ok_struct_union_types(ok_struct_types, false, false, false, true);
if (ok_struct_types.size() > 0)
{
int numOfBaseClasses = rnd_upto(min(ok_struct_types.size(), limit));
while (numOfBaseClasses > 0)
{
DEPTH_GUARD_BY_DEPTH_NORETURN(1);
Type* t = Type::choose_random_struct_union_type(ok_struct_types);
ERROR_RETURN();
_base_classes.push_back(t);
ok_struct_types.erase(std::find(ok_struct_types.begin(), ok_struct_types.end(), t));
numOfBaseClasses--;
}
}
}
Type* Type::choose_random_struct(void)
{
vector<Type *> ok_struct_types;
get_all_ok_struct_union_types(ok_struct_types, false, false, false, true);
if (ok_struct_types.size() > 0)
{
return Type::choose_random_struct_union_type(ok_struct_types);
}
return nullptr;
}
const Type*
Type::random_type_from_type(const Type* type, bool no_volatile, bool strict_simple_type)
{
const Type* t = type;
DEPTH_GUARD_BY_TYPE_RETURN(dtRandomTypeFromType, NULL);
if (type == 0) {
t = no_volatile ? choose_random_nonvoid_nonvolatile() : choose_random_nonvoid();
ERROR_GUARD(NULL);
}
if (type->eType == eSimple && !strict_simple_type) {
t = choose_random_simple();
ERROR_GUARD(NULL);
}
if (t->eType == eSimple) {
assert(t->simple_type != eVoid);
}
if (t->eType == ePointer || t->eType == eStruct) {
if (rnd_flipcoin(50))
{
int indirect_level = type->get_indirect_level();
if (indirect_level <= 1)
{
const Type* base_type = type->get_base_type();
if (!base_type->unambiguous_base_classes.empty())
{
int index = rnd_upto(base_type->unambiguous_base_classes.size());
const Type* t = base_type->unambiguous_base_classes[index];
for (int i = 0; i < indirect_level; i++)
{
t = find_pointer_type(t, true);
}
}
}
}
}
return t;
}
const Type*
Type::random_derive_type_from_type(const Type* type)
{
const Type* t = type;
if (rnd_flipcoin(50))
{
int indirect_level = type->get_indirect_level();
if (indirect_level <= 1)
{
const Type* base_type = type->get_base_type();
if (!base_type->unambiguous_derive_classes.empty())
{
int index = rnd_upto(base_type->unambiguous_derive_classes.size());
const Type* t = base_type->unambiguous_derive_classes[index];
for (int i = 0; i < indirect_level; i++)
{
t = find_pointer_type(t, true);
}
}
}
}
return t;
}
// ---------------------------------------------------------------------
static bool
MoreTypesProbability(void)
{
if (CGOptions::lang_cpp()) // 29.07 Ilya: cpp programs should be more object oriented and therefore have more types
{
// Always have at least 17 types in the program.
if (AllTypes.size() < 17)
return true;
}
else
{
// Always have at least 10 types in the program.
if (AllTypes.size() < 10)
return true;
}
// by default 80% probability for each additional struct or union type.
return rnd_flipcoin(MoreStructUnionTypeProb);
}
// ---------------------------------------------------------------------
eSimpleType
Type::choose_random_nonvoid_simple(void)
{
eSimpleType simple_type;
#if 0
vector<unsigned int> vs;
vs.push_back(eVoid);
if (!CGOptions::allow_int64()) {
vs.push_back(eLongLong);
vs.push_back(eULongLong);
}
VectorFilter filter(vs);
#endif
simple_type = (eSimpleType)rnd_upto(MAX_SIMPLE_TYPES, SIMPLE_TYPES_PROB_FILTER);
return simple_type;
}
void
Type::make_one_bitfield(vector<const Type*> &random_fields, vector<CVQualifiers> &qualifiers,
vector<int> &fields_length)
{
int max_length = CGOptions::int_size() * 8;
bool sign = rnd_flipcoin(BitFieldsSignedProb);
ERROR_RETURN();
const Type *type = sign ? &Type::get_simple_type(eInt) : &Type::get_simple_type(eUInt);
random_fields.push_back(type);
CVQualifiers qual = CVQualifiers::random_qualifiers(type, FieldConstProb, FieldVolatileProb);
ERROR_RETURN();
qualifiers.push_back(qual);
int length = rnd_upto(max_length);
ERROR_RETURN();
bool no_zero_len = fields_length.empty() || (fields_length.back() == 0);
// force length to be non-zero is required
if (length == 0 && no_zero_len) {
if (max_length <= 2) length = 1;
else length = rnd_upto(max_length - 1) + 1;
}
ERROR_RETURN();
fields_length.push_back(length);
}
// ---------------------------------------------------------------------
void
Type::make_full_bitfields_struct_fields(size_t field_cnt, vector<const Type*> &random_fields,
vector<CVQualifiers> &qualifiers,
vector<int> &fields_length,
vector<Constant*> &fields_init,
bool structHasAssignOps)
{
for (size_t i = 0; i < field_cnt; i++) {
bool is_non_bitfield = rnd_flipcoin(ScalarFieldInFullBitFieldsProb);
if (is_non_bitfield) {
make_one_struct_field(random_fields, qualifiers, fields_length, structHasAssignOps);
}
else {
make_one_bitfield(random_fields, qualifiers, fields_length);
}
if (random_fields.back()->eType == eTypeDesc::eSimple)
{
if (is_non_bitfield)
fields_init.push_back(Constant::make_random(random_fields.back()));
else
fields_init.push_back(Constant::make_random_in_range(random_fields.back(), fields_length.back()));
}
else
{
fields_init.push_back(nullptr);
}
}
}
void
Type::make_one_struct_field(vector<const Type*> &random_fields,
vector<CVQualifiers> &qualifiers,
vector<int> &fields_length,
bool structHasAssignOps)
{
ChooseRandomTypeFilter f(/*for_field_var*/true, structHasAssignOps);
unsigned int i = rnd_upto(AllTypes.size(), &f);
ERROR_RETURN();
const Type* type = AllTypes[i];
random_fields.push_back(type);
CVQualifiers qual = CVQualifiers::random_qualifiers(type, FieldConstProb, FieldVolatileProb);
ERROR_RETURN();
qualifiers.push_back(qual);
fields_length.push_back(-1);
}
void
Type::make_one_union_field(vector<const Type*> &fields, vector<CVQualifiers> &qfers, vector<int> &lens)
{
bool is_bitfield = CGOptions::bitfields() && !CGOptions::ccomp() && rnd_flipcoin(BitFieldInNormalStructProb);
if (is_bitfield) {
make_one_bitfield(fields, qfers, lens);
}
else {
size_t i;
vector<Type*> ok_nonstruct_types;
vector<Type*> struct_types;
for (i = 0; i < AllTypes.size(); i++) {
if ((AllTypes[i]->eType != eStruct) && (AllTypes[i]->eType != eUnion)) {
ok_nonstruct_types.push_back(AllTypes[i]);
continue;
}
// filter out structs and unions containing bit-fields. Their layout is implementation
// defined, we don't want to mess with them in unions for now
if (AllTypes[i]->has_bitfields())
continue;
// filter out structs/unions with assign operators (C++ only)
if (AllTypes[i]->has_implicit_nontrivial_assign_ops())
continue;
if (AllTypes[i]->eType == eStruct) {
struct_types.push_back(AllTypes[i]);
}
else { // union
// no union in union currently
}
}
const Type* type = NULL;
do {
// 15% chance to be struct field
if (!struct_types.empty() && pure_rnd_flipcoin(15)) {
type = struct_types[pure_rnd_upto(struct_types.size())];
assert(type->eType == eStruct);
}
// 10% chance to be char* if pointer is allowed
else if (CGOptions::pointers() && CGOptions::int8() && pure_rnd_flipcoin(10)) {
type = find_pointer_type(&get_simple_type(eChar), true);
}
else {
unsigned int i = pure_rnd_upto(ok_nonstruct_types.size());
const Type* t = ok_nonstruct_types[i];
if (t->eType == eSimple && SIMPLE_TYPES_PROB_FILTER->filter(t->simple_type)) {
continue;
}
type = t;
}
} while (type == NULL);
fields.push_back(type);
CVQualifiers qual = CVQualifiers::random_qualifiers(type, FieldConstProb, FieldVolatileProb);
ERROR_RETURN();
qfers.push_back(qual);
lens.push_back(-1);
}
}
void
Type::make_normal_struct_fields(size_t field_cnt, vector<const Type*> &random_fields,
vector<CVQualifiers> &qualifiers,
vector<int> &fields_length,
vector<Constant*> &fields_init,
bool structHasAssignOps)
{
for (size_t i = 0; i < field_cnt; i++)
{
bool is_bitfield = CGOptions::bitfields() && rnd_flipcoin(BitFieldInNormalStructProb);
if (is_bitfield) {
make_one_bitfield(random_fields, qualifiers, fields_length);
}
else {
make_one_struct_field(random_fields, qualifiers, fields_length, structHasAssignOps);
}
if (random_fields.back()->eType == eTypeDesc::eSimple)
{
if (is_bitfield)
fields_init.push_back(Constant::make_random_in_range(random_fields.back(), fields_length.back()));
else
fields_init.push_back(Constant::make_random(random_fields.back()));
}
else
{
fields_init.push_back(nullptr);
}
}
}
#define ZERO_BITFIELD 0
#define RANDOM_BITFIELD 1
//#define MAX_BITFIELD 2
#define ENUM_BITFIELD_SIZE 2
void
Type::init_is_bitfield_enumerator(Enumerator<string> &enumerator, int bitfield_prob)
{
int field_cnt = CGOptions::max_struct_fields();
for (int i = 0; i < field_cnt; ++i) {
std::ostringstream ss;
ss << "bitfield" << i;
if (CGOptions::bitfields()) {
enumerator.add_bool_elem(ss.str(), bitfield_prob);
}
else {
enumerator.add_bool_elem(ss.str(), 0);
}
}
}
void
Type::init_fields_enumerator(Enumerator<string> &enumerator,
Enumerator<string> &bitfield_enumerator,
int type_bound, int qual_bound,
int bitfield_qual_bound)
{
int field_cnt = CGOptions::max_struct_fields();
for (int i = 0; i < field_cnt; ++i) {
std::ostringstream ss;
ss << "bitfield" << i;
bool is_bitfield = bitfield_enumerator.get_elem(ss.str()) != 0;
if (is_bitfield) {
std::ostringstream ss1, ss2, ss3;
ss1 << "bitfield_sign" << i;
ss2 << "bitfield_qualifier" << i;
ss3 << "bitfield_length" << i;
enumerator.add_bool_elem_of_bool(ss1.str(), false);
enumerator.add_elem(ss2.str(), bitfield_qual_bound);
enumerator.add_elem(ss3.str(), ENUM_BITFIELD_SIZE);
}
else {
std::ostringstream ss1, ss2;
ss1 << "field" << i;
ss2 << "qualifier" << i;
enumerator.add_elem(ss1.str(), type_bound);
enumerator.add_elem(ss2.str(), qual_bound);
}
}
enumerator.add_bool_elem_of_bool("packed", CGOptions::packed_struct());
}
int
Type::get_bitfield_length(int length_flag)
{
int max_length = CGOptions::int_size() * 8;
assert(max_length > 0);
int length = 0;
switch (length_flag) {
case ZERO_BITFIELD:
length = 0;
break;
#if 0
case MAX_BITFIELD:
length = max_length;
break;
#endif
case RANDOM_BITFIELD:
length = pure_rnd_upto(max_length);
break;
default:
assert(0);
break;
}
return length;
}
bool
Type::make_one_bitfield_by_enum(Enumerator<string> &enumerator,
vector<CVQualifiers> &all_bitfield_quals,
vector<const Type*> &random_fields,
vector<CVQualifiers> &qualifiers,
vector<int> &fields_length,
int index, bool &last_is_zero)
{
std::ostringstream ss1, ss2, ss3;
ss1 << "bitfield_sign" << index;
ss2 << "bitfield_qualifier" << index;
ss3 << "bitfield_length" << index;
bool sign = enumerator.get_elem(ss1.str()) != 0;
// we cannot allow too many structs,
// so randomly choose the sign of fields.
if (pure_rnd_flipcoin(50))
sign = true;
const Type *type = sign ? &Type::get_simple_type(eInt) : &Type::get_simple_type(eUInt);
random_fields.push_back(type);
int qual_index = enumerator.get_elem(ss2.str());
assert((qual_index >= 0) && ((static_cast<unsigned int>(qual_index)) < all_bitfield_quals.size()));
CVQualifiers qual = all_bitfield_quals[qual_index];
qualifiers.push_back(qual);
int length_flag = enumerator.get_elem(ss3.str());
int length = get_bitfield_length(length_flag);
if ((index == 0 || last_is_zero) && (length == 0)) {
return false;
}
last_is_zero = (length == 0) ? true : false;
fields_length.push_back(length);
return true;
}
bool
Type::make_one_normal_field_by_enum(Enumerator<string> &enumerator, vector<const Type*> &all_types,
vector<CVQualifiers> &all_quals, vector<const Type*> &fields,
vector<CVQualifiers> &quals, vector<int> &fields_length, int i)
{
int types_size = all_types.size();
int quals_size = all_quals.size();
Filter *filter = SIMPLE_TYPES_PROB_FILTER;
std::ostringstream ss1, ss2;
ss1 << "field" << i;
int typ_index = enumerator.get_elem(ss1.str());
assert(typ_index >= 0 && typ_index < types_size);
Type *typ = const_cast<Type*>(all_types[typ_index]);
if (typ->eType == eSimple) {
assert(typ->simple_type != eVoid);
if (filter->filter(typ->simple_type))
return false;
}
assert(typ != NULL);
fields.push_back(typ);
ss2 << "qualifier" << i;
int qual_index = enumerator.get_elem(ss2.str());
assert(qual_index >= 0 && qual_index < quals_size);
CVQualifiers qual = all_quals[qual_index];
quals.push_back(qual);
fields_length.push_back(-1);
return true;
}
void
Type::make_all_struct_types_(Enumerator<string> &bitfields_enumerator, vector<const Type*> &accum_types,
vector<const Type*> &all_types, vector<CVQualifiers> &all_quals,
vector<CVQualifiers> &all_bitfield_quals)
{
Enumerator<string> fields_enumerator;
init_fields_enumerator(fields_enumerator, bitfields_enumerator, all_types.size(),
all_quals.size(), all_bitfield_quals.size());
Enumerator<string> *i;
for (i = fields_enumerator.begin(); i != fields_enumerator.end(); i = i->next()) {
make_all_struct_types_with_bitfields(*i, bitfields_enumerator, accum_types, all_types, all_quals, all_bitfield_quals);
}
}
void make_random_member_names(size_t field_cnt, vector<string> &members_names)
{
size_t highest_letter_number = std::min(field_cnt * 2, (unsigned int)('z' - 'a'));
int rand_letter;
while (field_cnt != 0)
{
rand_letter = rnd_upto(highest_letter_number);
char temp = (char)rand_letter + 'a';
string new_member_name;
new_member_name += temp;
if (find(members_names.begin(), members_names.end(), new_member_name) == members_names.end())
{
members_names.push_back(new_member_name);
field_cnt--;
}
}
}
void
Type::make_all_struct_types_with_bitfields(Enumerator<string> &enumerator,
Enumerator<string> &bitfields_enumerator, vector<const Type*> &accum_types,
vector<const Type*> &all_types, vector<CVQualifiers> &all_quals,
vector<CVQualifiers> &all_bitfield_quals)
{
vector<const Type*> fields;
vector<CVQualifiers> quals;
vector<int> fields_length;
int field_cnt = CGOptions::max_struct_fields();
bool last_is_zero = false;
int bitfields_cnt = 0;
int normal_fields_cnt = 0;
for (int i = 0; i < field_cnt; ++i) {
std::ostringstream ss;
ss << "bitfield" << i;
bool is_bitfield = bitfields_enumerator.get_elem(ss.str()) != 0;
bool rv = false;
if (is_bitfield) {
rv = make_one_bitfield_by_enum(enumerator, all_bitfield_quals, fields, quals, fields_length, i, last_is_zero);
bitfields_cnt++;
}
else {
rv = make_one_normal_field_by_enum(enumerator, all_types, all_quals, fields, quals, fields_length, i);
last_is_zero = rv ? false : last_is_zero;
normal_fields_cnt++;
}
if (!rv)
return;
}
if ((ExhaustiveBitFieldsProb > 0) && (ExhaustiveBitFieldsProb < 100) &&
((bitfields_cnt == field_cnt) || (normal_fields_cnt == field_cnt)))
return;
bool packed = enumerator.get_elem("packed") != 0;
bool hasAssignOps = if_struct_will_have_assign_ops();
bool hasImplicitNontrivialAssignOps = hasAssignOps || checkImplicitNontrivialAssignOps(fields);
vector<Constant*> fields_init;
vector<string> fields_name;
vector<eAccess> fields_accesses;
make_random_member_names(field_cnt, fields_name);
make_random_accesses(fields_name.size(), fields_accesses);
Type* new_type = new Type(fields, true, packed, quals, fields_length, hasAssignOps, hasImplicitNontrivialAssignOps, vector< Type*>(), vector<eAccess>(), vector<bool>(), fields_init, fields_name, fields_accesses, vector< Type*>());
new_type->used = true;
accum_types.push_back(new_type);
}
/*
* level control's the nested level of struct
*/
void
Type::copy_all_fields_types(vector<const Type*> &dest_types, vector<const Type*> &src_types)
{
vector<const Type*>::const_iterator i;
for (i = src_types.begin(); i != src_types.end(); ++i)
dest_types.push_back(*i);
}
void
Type::reset_accum_types(vector<const Type*> &accum_types)
{
accum_types.clear();
vector<Type*>::const_iterator i;
for (i = AllTypes.begin(); i != AllTypes.end(); ++i)
accum_types.push_back(*i);
}
void
Type::delete_useless_structs(vector<const Type*> &all_types, vector<const Type*> &accum_types)
{
assert(all_types.size() <= accum_types.size());
for (size_t i = 0; i < all_types.size(); ++i) {
const Type *t = all_types[i];
if (t->eType == eStruct) {
const Type *t1 = accum_types[i];
delete t1;
accum_types[i] = t;
}
}
}
void
Type::make_all_struct_types(int level, vector<const Type*> &accum_types)
{
if (level > 0) {
make_all_struct_types(level - 1, accum_types);
}
vector<const Type*> all_types;
copy_all_fields_types(all_types, accum_types);
reset_accum_types(accum_types);
vector<CVQualifiers> all_quals;
CVQualifiers::get_all_qualifiers(all_quals, RegularConstProb, RegularVolatileProb);
vector<CVQualifiers> all_bitfield_quals;
CVQualifiers::get_all_qualifiers(all_bitfield_quals, FieldConstProb, FieldVolatileProb);
Enumerator<string> fields_enumerator;
init_is_bitfield_enumerator(fields_enumerator, ExhaustiveBitFieldsProb);
Enumerator<string> *i;
for (i = fields_enumerator.begin(); i != fields_enumerator.end(); i = i->next()) {
make_all_struct_types_(*i, accum_types, all_types, all_quals, all_bitfield_quals);
}
delete_useless_structs(all_types, accum_types);
}
void
Type::make_all_struct_union_types(void)
{
int level = CGOptions::max_nested_struct_level();
if (CGOptions::dfs_exhaustive()) {
vector<const Type*> accum_types;
reset_accum_types(accum_types);
make_all_struct_types(level, accum_types);
assert(accum_types.size() >= AllTypes.size());
for (size_t i = AllTypes.size(); i < accum_types.size(); ++i)
AllTypes.push_back(const_cast<Type*>(accum_types[i]));
}
}
bool
Type::has_aggregate_field(const vector<const Type *> &fields)
{
for (vector<const Type *>::const_iterator iter = fields.begin(),
iter_end = fields.end(); iter != iter_end; ++iter) {
if ((*iter)->is_aggregate())
return true;
}
return false;
}
bool
Type::has_longlong_field(const vector<const Type *> &fields)
{
for (vector<const Type *>::const_iterator iter = fields.begin(),
iter_end = fields.end(); iter != iter_end; ++iter) {
if ((*iter)->is_long_long())
return true;
}
return false;
}
Type*
Type::make_random_struct_type(void)
{
size_t field_cnt = 0;
size_t max_cnt = CGOptions::max_struct_fields();
if (CGOptions::fixed_struct_fields())
field_cnt = max_cnt;
else
field_cnt = rnd_upto(max_cnt) + 1;
ERROR_GUARD(NULL);
// choose random structs to inherit from
vector<Type*> _base_clasees;
vector<eAccess> _base_clasees_access;
choose_random_struct(_base_clasees,5);
make_random_accesses(_base_clasees.size(), _base_clasees_access);
vector<bool> _isVirtualBaseClasses(_base_clasees.size());
for (size_t i = 0; i < _base_clasees.size(); i++)
{
if (rnd_flipcoin(50))
{
_isVirtualBaseClasses[i] = true; // this base class is virtual
}
else
{
_isVirtualBaseClasses[i] = false; // // this base class is not virtual
}
}
vector<Type*> _friend_clasees;
if (rnd_flipcoin(10))
choose_random_struct(_friend_clasees,2);
ERROR_GUARD(NULL);
vector<const Type*> random_fields;
vector<CVQualifiers> qualifiers;
vector<int> fields_length;
vector<Constant*> fields_init;
bool is_bitfields = CGOptions::bitfields() && rnd_flipcoin(BitFieldsCreationProb);
ERROR_GUARD(NULL);
bool hasAssignOps = if_struct_will_have_assign_ops();
//if (CGOptions::bitfields())
if (is_bitfields)
make_full_bitfields_struct_fields(field_cnt, random_fields, qualifiers, fields_length, fields_init, hasAssignOps);
else
make_normal_struct_fields(field_cnt, random_fields, qualifiers, fields_length, fields_init, hasAssignOps);
ERROR_GUARD(NULL);
vector<string> members_names;
vector<eAccess> members_access;
make_random_member_names(field_cnt, members_names);
make_random_accesses(members_names.size(), members_access);
// for now, no union type
bool packed = false;
if (CGOptions::packed_struct()) {
if (CGOptions::ccomp() && (has_aggregate_field(random_fields) || has_longlong_field(random_fields))) {
// Nothing to do
}
else {
packed = rnd_flipcoin(10);
ERROR_GUARD(NULL);
}
}
bool hasImplicitNontrivialAssignOps = hasAssignOps || checkImplicitNontrivialAssignOps(random_fields);
Type* new_type = new Type(random_fields, true, packed, qualifiers, fields_length, hasAssignOps, hasImplicitNontrivialAssignOps, _base_clasees, _base_clasees_access, _isVirtualBaseClasses, fields_init, members_names, members_access, _friend_clasees);
// update child classes
for (Type * base_class : _base_clasees)
{
base_class->child_classes.push_back(new_type);
}
return new_type;
}
Type*
Type::make_random_union_type(void)
{
size_t max_cnt = CGOptions::max_union_fields();
size_t field_cnt = rnd_upto(max_cnt) + 1;
ERROR_GUARD(NULL);
vector<const Type*> fields;
vector<CVQualifiers> qfers;
vector<int> lens;
for (size_t i = 0; i < field_cnt; i++) {
make_one_union_field(fields, qfers, lens);
assert(!fields.back()->has_bitfields());
}
bool hasAssignOps = if_union_will_have_assign_ops();
bool hasImplicitNontrivialAssignOps = hasAssignOps || checkImplicitNontrivialAssignOps(fields);
vector<Constant*> fields_init(fields.size(), nullptr);
vector<string> members_names;
vector<eAccess> members_access;
make_random_member_names(field_cnt, members_names);
make_random_accesses(members_names.size(), members_access);
Type* new_type = new Type(fields, false, false, qfers, lens, hasAssignOps, hasImplicitNontrivialAssignOps, vector< Type*>(), vector<eAccess>(), vector<bool>(), fields_init, members_names, members_access, vector< Type*>());
return new_type;
}
// ---------------------------------------------------------------------
Type*
Type::make_random_pointer_type(void)
{
//Type* new_type = 0;
//Type* ptr_type = 0;
// occasionally choose pointer to pointers
if (rnd_flipcoin(20)) {
ERROR_GUARD(NULL);
if (derived_types.size() > 0) {
unsigned int rnd_num = rnd_upto(derived_types.size());
ERROR_GUARD(NULL);
const Type* t = derived_types[rnd_num];
if (t->get_indirect_level() < CGOptions::max_indirect_level()) {
return find_pointer_type(t, true);
}
}
}
// choose a pointer to basic/aggregate types
const Type* t = choose_random();
ERROR_GUARD(NULL);
// consolidate all integer pointer types into "int*", hopefully this increase
// chance of pointer assignments and dereferences
if (t->eType == eSimple) {
t = get_int_type();
ERROR_GUARD(NULL);
}
return find_pointer_type(t, true);
}
// ---------------------------------------------------------------------
void
Type::GenerateSimpleTypes(void)
{
unsigned int st;
for (st = eChar; st < MAX_SIMPLE_TYPES; st++)
{
AllTypes.push_back(new Type((enum eSimpleType)st));
}
Type::void_type = new Type((enum eSimpleType)eVoid);
}
// ---------------------------------------------------------------------
void
GenerateAllTypes(void)
{
// In the exhaustive mode, we want to generate all type first.
// We don't support struct for now
if (CGOptions::dfs_exhaustive()) {
Type::GenerateSimpleTypes();
if (CGOptions::use_struct() && CGOptions::expand_struct())
Type::make_all_struct_union_types();
return;
}
Type::GenerateSimpleTypes();
if (CGOptions::use_struct()) {
while (MoreTypesProbability()) {
Type *ty = Type::make_random_struct_type();
AllTypes.push_back(ty);
}
}
if (CGOptions::use_union()) {
while (MoreTypesProbability()) {
Type *ty = Type::make_random_union_type();
AllTypes.push_back(ty);
}
}
}
// ---------------------------------------------------------------------
const Type *
Type::choose_random()
{
ChooseRandomTypeFilter f(/*for_field_var*/false);
rnd_upto(AllTypes.size(), &f);
ERROR_GUARD(NULL);
Type *rv_type = f.get_type();
if (!rv_type->used) {
Bookkeeper::record_type_with_bitfields(rv_type);
rv_type->used = true;
}
return rv_type;
}
const Type *
Type::choose_random_nonvoid(void)
{
DEPTH_GUARD_BY_DEPTH_RETURN(1, NULL);
NonVoidTypeFilter f;
rnd_upto(AllTypes.size(), &f);
ERROR_GUARD(NULL);
Type *typ = f.get_type();
assert(typ);
return typ;
}
const Type *
Type::choose_random_nonvoid_nonvolatile(void)
{
DEPTH_GUARD_BY_DEPTH_RETURN(1, NULL);
NonVoidNonVolatileTypeFilter f;
rnd_upto(AllTypes.size(), &f);
ERROR_GUARD(NULL);
Type *typ = f.get_type();
assert(typ);
return typ;
}
// ---------------------------------------------------------------------
const Type *
Type::choose_random_simple(void)
{
DEPTH_GUARD_BY_TYPE_RETURN(dtTypeChooseSimple, NULL);
eSimpleType ty = choose_random_nonvoid_simple();
ERROR_GUARD(NULL);
assert(ty != eVoid);
return &get_simple_type(ty);
}
// ---------------------------------------------------------------------
int
Type::get_indirect_level() const
{
int level = 0;
const Type* pt = ptr_type;
while (pt != 0) {
level++;
pt = pt->ptr_type;
}
return level;
}
// ---------------------------------------------------------------------
int
Type::get_struct_depth() const
{
int depth = 0;
if (eType == eStruct) {
depth++;
int max_depth = 0;
for (size_t i = 0; i < fields.size(); i++) {
int field_depth = fields[i]->get_struct_depth();
if (field_depth > max_depth) {
max_depth = field_depth;
}
}
depth += max_depth;
}
return depth;
}
bool
Type::is_unamed_padding(size_t index) const
{
size_t sz = bitfields_length_.size();
if (sz == 0)
return false;
assert(index < sz);
return (bitfields_length_[index] == 0);
}
bool
Type::is_bitfield(size_t index) const
{
assert(index < bitfields_length_.size());
return (bitfields_length_[index] >= 0);
}
bool
Type::has_bitfields() const
{
for (size_t i = 0; i < fields.size(); i++) {
if (bitfields_length_[i] >= 0) {
return true;
}
if (fields[i]->eType == eStruct && fields[i]->has_bitfields()) {
return true;
}
}
return false;
}
// conservatively assume padding is present in all unpacked structures
// or whenever there is bitfields
bool
Type::has_padding(void) const
{
if (eType == eStruct && !packed_) return true;
for (size_t i = 0; i < fields.size(); i++) {
if (is_bitfield(i) || fields[i]->has_padding()) {
return true;
}
}
return false;
}
bool
Type::is_full_bitfields_struct() const
{
if (eType != eStruct) return false;
size_t i;
for (i = 0; i < bitfields_length_.size(); ++i) {
if (bitfields_length_[i] < 0)
return false;
}
return true;
}
bool
Type::is_signed(void) const
{
switch (eType) {
default:
return false;
case eSimple:
switch (simple_type) {
case eUChar:
case eUInt:
case eUShort:
case eULong:
case eULongLong:
return false;
break;
default:
break;
}
break;
}
return true;
}
const Type*
Type::to_unsigned(void) const
{
if (eType == eSimple) {
switch (simple_type) {
case eUChar:
case eUInt:
case eUShort:
case eULong:
case eULongLong:
return this;
case eChar: return &get_simple_type(eUChar);
case eInt: return &get_simple_type(eUInt);
case eShort: return &get_simple_type(eUShort);
case eLong: return &get_simple_type(eULong);
case eLongLong: return &get_simple_type(eULongLong);
default:
break;
}
}
return NULL;
}
const Type*
Type::get_base_type(void) const
{
const Type* tmp = this;
while (tmp->ptr_type != 0) {
tmp = tmp->ptr_type;
}
return tmp;
}
bool
Type::is_promotable(const Type* t) const
{
if (eType == eSimple && t->eType == eSimple) {
eSimpleType t2 = t->simple_type;
switch (simple_type) {
case eChar:
case eUChar: return (t2 != eVoid);
case eShort:
case eUShort: return (t2 != eVoid && t2 != eChar && t2 != eUChar);
case eInt:
case eUInt: return (t2 != eVoid && t2 != eChar && t2 != eUChar && t2 != eShort && t2 != eUShort);
case eLong:
case eULong: return (t2 == eLong || t2 == eULong || t2 == eLongLong || t2 == eULongLong);
case eLongLong:
case eULongLong: return (t2 == eLongLong || t2 == eULongLong);
case eFloat: return (t2 != eVoid);
default: break;
}
}
return false;
}
// ---------------------------------------------------------------------
/* generally integer types can be converted to any other interger types
* void / struct / union / array types are not. Pointers depend on the
* type they point to. (unsigned int*) is convertable to (int*), etc
*************************************************************/
bool
Type::is_convertable(const Type* t) const
{
if (this == t)
return true;
if (eType == eSimple && t->eType == eSimple) {
// forbiden conversion from float to int
if (t->is_float() && !is_float())
return false;
if ((simple_type != eVoid && t->simple_type != eVoid) ||
simple_type == t->simple_type)
return true;
}
else if (eType == ePointer && t->eType == ePointer) {
if (ptr_type == t->ptr_type) {
return true;
}
if (ptr_type->eType == eSimple && t->ptr_type->eType == eSimple) {
if (ptr_type->simple_type == t->ptr_type->simple_type)
return true;
else if (CGOptions::strict_float() &&
((ptr_type->simple_type == eFloat && t->ptr_type->simple_type != eFloat) ||
(ptr_type->simple_type != eFloat && t->ptr_type->simple_type == eFloat)))
return false;
else if (CGOptions::lang_cpp())
return false; // or we need an explicit cast here
else
return ptr_type->SizeInBytes() == t->ptr_type->SizeInBytes();
}
/*else if (ptr_type->eType == eStruct&& t->ptr_type->eType == eStruct)
{
return ptr_type->is_struct_convertable(t->ptr_type);
}*/
}
/*else if (eType == eStruct && t->eType == eStruct) {
return is_struct_convertable(t);
}*/
return false;
}
bool
Type::is_struct_convertable(const Type* t) const
{
if (this == t)
return true;
for (size_t i = 0; i < unambiguous_derive_classes.size(); i++)
{
if (unambiguous_derive_classes[i] == t)
return true;
}
return false;
}
// eLong & eInt, eULong & eUInt are equivalent
bool
Type::is_equivalent(const Type* t) const
{
if (this == t)
return true;
if (eType == eSimple) {
return (is_signed() == t->is_signed()) && (SizeInBytes() == t->SizeInBytes());
}
return false;
}
bool
Type::needs_cast(const Type* t) const
{
return (eType == ePointer) && !get_base_type()->is_equivalent(t->get_base_type());
}
bool
Type::match(const Type* t, enum eMatchType mt) const
{
switch (mt) {
case eExact: return (this == t);
case eConvert: return is_convertable(t);
case eDereference: return is_dereferenced_from(t);
case eDerefExact: return (t == this || is_dereferenced_from(t));
case eFlexible: return is_derivable(t);
default: break;
}
return false;
}
// ---------------------------------------------------------------------
/* return true if this type can be derived from the given type
* by dereferencing
*************************************************************/
bool
Type::is_dereferenced_from(const Type* t) const
{
if (t->eType == ePointer) {
const Type* pt = t->ptr_type;
while (pt) {
if (pt == this) {
return true;
}
pt = pt->ptr_type;
}
}
return false;
}
// ---------------------------------------------------------------------
/* return true if this type can be derived from the given type
* by taking address(one level) or dereferencing (multi-level)
* question: allow interger conversion? i.e. char* p = &(int)i?
*************************************************************/
bool
Type::is_derivable(const Type* t) const
{
if (this == t) {
return true;
}
return is_convertable(t) || is_dereferenced_from(t) || (ptr_type == t);
}
unsigned long
Type::SizeInBytes(void) const
{
size_t i;
switch (eType) {
default: break;
case eSimple:
switch (simple_type) {
case eVoid: return 0;
case eInt: return 4;
case eShort: return 2;
case eChar: return 1;
case eLong: return 4;
case eLongLong: return 8;
case eUChar: return 1;
case eUInt: return 4;
case eUShort: return 2;
case eULong: return 4;
case eULongLong:return 8;
case eFloat: return 4;
// case eDouble: return 8;
}
break;
case eUnion: {
unsigned int max_size = 0;
for (i = 0; i < fields.size(); i++) {
unsigned int sz = 0;
if (is_bitfield(i)) {
assert(i < bitfields_length_.size());
sz = (int)(ceil(bitfields_length_[i] / 8.0) * 8);
}
else {
sz = fields[i]->SizeInBytes();
}
if (sz == SIZE_UNKNOWN) return sz;
if (sz > max_size) {
max_size = sz;
}
}
return max_size;
}
case eStruct: {
if (!this->packed_) return SIZE_UNKNOWN;
// give up if there are bitfields, too much compiler-dependence and machine-dependence
if (this->has_bitfields()) return SIZE_UNKNOWN;
unsigned int total_size = 0;
for (i = 0; i < fields.size(); i++) {
unsigned int sz = fields[i]->SizeInBytes();
if (sz == SIZE_UNKNOWN) return sz;
total_size += sz;
}
return total_size;
}
case ePointer:
CGOptions::pointer_size();
break;
}
return 0;
}
// --------------------------------------------------------------
/* Select a left hand type for assignments
************************************************************/
const Type *
Type::SelectLType(bool no_volatile, eAssignOps op)
{
const Type* type = NULL;
// occasionally we want to play with pointers
// We haven't implemented pointer arith,
// so choose pointer types iff we create simple assignment
// (see Statement::make_random)
if (op == eSimpleAssign && rnd_flipcoin(PointerAsLTypeProb)) {
ERROR_GUARD(NULL);
type = Type::make_random_pointer_type();
}
ERROR_GUARD(NULL);
// choose a struct type as LHS type
if (!type && (op == eSimpleAssign)) {
vector<Type *> ok_struct_types;
get_all_ok_struct_union_types(ok_struct_types, true, no_volatile, false, true);
if ((ok_struct_types.size() > 0) && rnd_flipcoin(StructAsLTypeProb)) {
type = Type::choose_random_struct_union_type(ok_struct_types);
}
}
// choose float as LHS type
if (!type) {
if (StatementAssign::AssignOpWorksForFloat(op) && rnd_flipcoin(FloatAsLTypeProb)) {
type = &Type::get_simple_type(eFloat);
}
}
// default is any integer type
if (!type) {
type = get_int_type();
}
return type;
}
void
Type::get_int_subfield_names(string prefix, vector<string>& names, const vector<int>& excluded_fields) const
{
if (eType == eSimple) {
names.push_back(prefix);
}
else if (is_aggregate()) {
size_t i;
size_t j = 0;
for (i = 0; i < sub_object_tree.unambiguousMembers.size(); i++) {
if (sub_object_tree.unambiguousMembersAccess[i] == eNoAccess) {
j++;
continue;
}
// skip excluded fields
if (std::find(excluded_fields.begin(), excluded_fields.end(), j) != excluded_fields.end()) {
j++;
continue;
}
const Type *memberInType = sub_object_tree.unambiguousMembers[j].first->type;
int memberIndex = sub_object_tree.unambiguousMembers[j].second;
j++;
if (memberInType->is_unamed_padding(memberIndex)) continue; // skip 0 length bitfields
ostringstream oss;
oss << prefix << "." << memberInType->fields_name[memberIndex];
vector<int> empty;
memberInType->fields[memberIndex]->get_int_subfield_names(oss.str(), names, empty);
}
}
}
bool
Type::contain_pointer_field(void) const
{
if (eType == ePointer) return true;
if (eType == eStruct || eType == eUnion) {
for (size_t i = 0; i < fields.size(); i++) {
if (fields[i]->contain_pointer_field()) {
return true;
}
}
}
return false;
}
// ---------------------------------------------------------------------
void
Type::Output(std::ostream &out, bool use_elaborated_type_specifier) const
{
switch (eType) {
case eSimple:
if (this->simple_type == eVoid) {
out << "void";
}
else if (this->simple_type == eFloat) {
out << "float";
}
else {
out << (is_signed() ? "int" : "uint");
out << (SizeInBytes() * 8);
out << "_t";
}
break;
case ePointer: ptr_type->Output(out); out << "*"; break;
case eUnion:
if (use_elaborated_type_specifier) out << "union U" << sid;
else out << "U" << sid;
break;
case eStruct:
if (use_elaborated_type_specifier) out << "class S" << sid;
else out << "::S" << sid;
break;
}
}
void
Type::get_type_sizeof_string(std::string &s) const
{
ostringstream ss;
ss << "sizeof(";
Output(ss);
ss << ")";
s = ss.str();
}
// If this is C++, create assign operators for volatile structs:
// Semantically this should work, though for bit fields it's probably not what was intended.
//volatile struct S0& operator=(const volatile struct S0& val) volatile {
// if (this == &val) {
// return *this;
// }
// f0 = val.f0;
// f1 = val.f1;
// return *this;
//}
// As a result of generating this, have to generate 'default' assignment operator as well
void OutputStructAssignOp(Type* type, std::ostream &out, bool vol)
{
if (CGOptions::lang_cpp()) {
if (type->has_assign_ops() && (type->eType == eStruct)) {
out << " ";
if (vol) {
out << "volatile ";
}
type->Output(out); out << "& operator=(const ";
if (vol) {
out << "volatile ";
}
type->Output(out); out << "& val) ";
if (vol) {
out << "volatile ";
}
out << "{"; really_outputln(out);
out << " if (this == &val) {"; really_outputln(out);
out << " return *this;"; really_outputln(out);
out << " }"; really_outputln(out);
for (size_t i = 0; i < type->base_classes.size(); i++)
{
if (type->base_classes_access[i] == ePublic)
{
out << " ";
type->base_classes[i]->Output(out);
out << "::operator=(val);";
really_outputln(out);
}
}
// for all fields:
for (size_t i = 0; i < type->sub_object_tree.unambiguousMembers.size(); i++) {
if (type->sub_object_tree.unambiguousMembersAccess[i] != eNoAccess)
{
const Type *memberInType = type->sub_object_tree.unambiguousMembers[i].first->type;
int memberIndex = type->sub_object_tree.unambiguousMembers[i].second;
out << " ";
out << " " << memberInType->fields_name[memberIndex] << "= val." << memberInType->fields_name[memberIndex] << ";";
really_outputln(out);
}
}
out << " return *this;"; really_outputln(out);
out << " }"; really_outputln(out);
}
}
}
// To have volatile unions in C++ they need assignment operators:
//union U1& operator=(const union U1& val){
// if (this == &val) {
// return *this;
// }
// memcpy(this, &val, sizeof(union U1));
// return *this;
//}
//volatile union U1& operator=(const volatile union U1& val) volatile {
// if (this == &val) {
// return *this;
// }
// memcpy((union U1*)this, (const union U1*)(&val), sizeof(union U1));
// return *this;
//}
void OutputUnionAssignOps(Type* type, std::ostream &out, bool vol)
{
if (CGOptions::lang_cpp()) {
if (type->has_assign_ops() && (type->eType == eUnion)) {
out << " ";
if (vol) {
out << "volatile ";
}
type->Output(out); out << "& operator=(const ";
if (vol) {
out << "volatile ";
}
type->Output(out); out << "& val) ";
if (vol) {
out << "volatile ";
}
out << "{"; really_outputln(out);
out << " if (this == &val) {"; really_outputln(out);
out << " return *this;"; really_outputln(out);
out << " }"; really_outputln(out);
out << " memcpy((";
type->Output(out);
out << "*)this, (const ";
type->Output(out);
out << "*)(&val), sizeof(";
type->Output(out);
out << ")); "; really_outputln(out);
out << " return *this;"; really_outputln(out);
out << " }"; really_outputln(out);
}
}
}
void OutputDefaultCtor(Type* type, std::ostream &out)
{
out << " ";
out << "S" << type->sid;
out << "() {}";
really_outputln(out);
}
void OutputMainFriend(std::ostream &out)
{
out << " ";
out << "friend int main (int argc, char* argv[]);";
really_outputln(out);
}
void OutputFriends(Type* type, std::ostream &out)
{
for (size_t i = 0; i < type->friend_classes.size(); i++)
{
really_outputln(out);
out << " ";
out << "friend ";
type->friend_classes[i]->Output(out);
out << ";";
}
really_outputln(out);
}
// ---------------------------------------------------------------------
/* print struct definition (fields etc)
*************************************************************/
void OutputStructUnion(Type* type, std::ostream &out)
{
size_t i;
// sanity check
assert(type->is_aggregate());
if (!type->printed) {
// output dependent structs, if any
for (i = 0; i < type->fields.size(); i++) {
if (type->fields[i]->is_aggregate()) {
OutputStructUnion((Type*)type->fields[i], out);
}
}
// output myself
if (type->packed_) {
if (!CGOptions::ccomp()) {
out << "#pragma pack(push)";
really_outputln(out);
}
out << "#pragma pack(1)";
really_outputln(out);
}
type->Output(out, true);
if (type->base_classes.size() != 0)
{
out << ": ";
for (size_t i = 0; i < type->base_classes.size(); i++)
{
out << Type::get_access_name(type->base_classes_access[i]) << " ";
if (type->isVirtualBaseClasses[i] == true)
{
out << "virtual ";
}
out << "S" << type->base_classes[i]->sid;
if (i != type->base_classes.size() - 1)
{
out << ", ";
}
}
}
out << " {";
if (type->eType == eStruct)
{
OutputFriends(type, out);
}
really_outputln(out);
OutputStructInAccess(type, out, ePrivate);
OutputStructInAccess(type, out, eProtected);
OutputAccessSpecifier(out, ePublic);
OutputStructFieldsInAccess(type, out, ePublic);
OutputStructFuncInAccess(type, out, ePublic);
if (type->eType == eStruct) {
OutputDefaultCtor(type, out);
//OutputStructAssignOp(type, out, false);
//OutputStructAssignOp(type, out, true);
OutputMainFriend(out);
}
else {
OutputUnionAssignOps(type, out, false);
OutputUnionAssignOps(type, out, true);
}
out << "};";
really_outputln(out);
if (type->packed_) {
if (CGOptions::ccomp()) {
out << "#pragma pack()";
}
else {
out << "#pragma pack(pop)";
}
really_outputln(out);
}
type->printed = true;
really_outputln(out);
}
}
bool TypeHasAccess(Type* type, eAccess access)
{
for (size_t i = 0; i < type->fields.size(); i++) {
if (type->fields_access[i] == access)
return true;
}
for (size_t i = 0; i < type->func_list.size(); i++) {
if (type->func_list_access[i] == access)
return true;
}
return false;
}
void Type::getAllBaseClassesFunctions(set<Function*> &functionSet, bool includeThisClass)
{
if (includeThisClass)
for (Function* memberFunc : this->func_list)
functionSet.insert(memberFunc);
for (Type* baseClass : this->base_classes)
baseClass->getAllBaseClassesFunctions(functionSet, true);
}
void Type::getAllChildClassesFunctions(set<Function*> &functionSet, bool includeThisClass)
{
if (includeThisClass)
for (Function* memberFunc : this->func_list)
functionSet.insert(memberFunc);
for (Type* childClass : this->child_classes)
childClass->getAllChildClassesFunctions(functionSet, true);
}
void OutputStructInAccess(Type* type, std::ostream &out, eAccess access)
{
if (TypeHasAccess(type, access))
{
OutputAccessSpecifier(out, access);
OutputStructFieldsInAccess(type, out, access);
OutputStructFuncInAccess(type, out, access);
}
}
void OutputAccessSpecifier(std::ostream &out, eAccess access)
{
out << Type::get_access_name(access) << ":";
}
void OutputStructFieldsInAccess(Type* type, std::ostream &out, eAccess access)
{
really_outputln(out);
assert(type->fields.size() == type->qfers_.size());
unsigned int j = 0;
for (size_t i = 0; i < type->fields.size(); i++) {
if (type->fields_access[i] != access)
continue;
out << " ";
const Type *field = type->fields[i];
bool is_bitfield = type->is_bitfield(i);
if (is_bitfield) {
assert(field->eType == eSimple);
type->qfers_[i].OutputFirstQuals(out);
if (field->simple_type == eInt)
out << "signed";
else if (field->simple_type == eUInt)
out << "unsigned";
else
assert(0);
int length = type->bitfields_length_[i];
assert(length >= 0);
if (length == 0)
{
out << " : ";
out << length << ";";
}
else
{
out << " " << type->fields_name[j++] << " : ";
out << length;
if (type->fields_init.size() > i && type->fields_init[i] != nullptr)
{
out << " = ";
type->fields_init[i]->Output(out);
}
out << ";";
}
}
else {
type->qfers_[i].output_qualified_type(field, out);
out << " " << type->fields_name[i];
if (type->fields_init.size() > i && type->fields_init[i] != nullptr)
{
out << " = ";
type->fields_init[i]->Output(out);
}
out << ";";
}
really_outputln(out);
}
}
void OutputStructFuncInAccess(Type* type, std::ostream &out, eAccess access)
{
really_outputln(out);
for (size_t i = 0; i < type->func_list.size(); i++) {
if (type->func_list_access[i] != access)
continue;
out << " ";
Function* func = type->func_list[i];
func->OutputHeader(out, true);
out << ";";
really_outputln(out);
}
}
// ---------------------------------------------------------------------
/* print all struct definitions (fields etc)
*************************************************************/
void
OutputStructUnionDeclarations(std::ostream &out)
{
size_t i;
really_outputln(out);
output_comment_line(out, "--- Class Declarations ---");
for (i = 0; i < AllTypes.size(); i++)
{
Type* t = AllTypes[i];
if (t->used && (t->eType == eStruct || t->eType == eUnion)) {
really_outputln(out);
out << "class S" << t->sid << ";";
}
}
really_outputln(out);
output_comment_line(out, "--- Class Definitions ---");
for (i = 0; i < AllTypes.size(); i++)
{
Type* t = AllTypes[i];
if (t->used && (t->eType == eStruct || t->eType == eUnion)) {
OutputStructUnion(AllTypes[i], out);
}
}
}
/*
* return the printf directive string for the type. for example, int -> "%d"
*/
std::string
Type::printf_directive(void) const
{
string ret;
size_t i;
switch (eType) {
case eSimple:
if (SizeInBytes() >= 8) {
ret = is_signed() ? "%lld" : "%llu";
}
else {
ret = is_signed() ? "%d" : "%u";
}
break;
case ePointer:
ret = "0x%0x";
break;
case eUnion:
case eStruct:
ret = "{";
for (i = 0; i < fields.size(); i++) {
if (i > 0) ret += ", ";
ret += fields[i]->printf_directive();
}
ret += "}";
break;
}
return ret;
}
bool Type::runFinalOverridersCheckForAllTypes()
{
for (Type * type : AllTypes)
if (type->eType == eTypeDesc::eStruct)
if (!type->sub_object_tree.runFinalOverridersCheck())
return false;
return true;
}
/*
*
*/
void
Type::doFinalization(void)
{
vector<Type *>::iterator j;
for (j = AllTypes.begin(); j != AllTypes.end(); ++j)
delete (*j);
AllTypes.clear();
for (j = derived_types.begin(); j != derived_types.end(); ++j)
delete (*j);
derived_types.clear();
}
SubObjectTree::SubObjectNode::SubObjectNode(const Type *_type) : subObjectId(++subObjectlastId), type(_type), type_access(ePrivate)
{
// nothing else to do
}
bool SubObjectTree::SubObjectNode::isBaseClassSubObjectOf(const SubObjectNode &potentialSuperObject)
{
for (auto directSubObject : potentialSuperObject.directBaseSubObjects)
{
if (*directSubObject == *this)
return true;
}
for (auto directSubObject : potentialSuperObject.directBaseSubObjects)
{
if (this->isBaseClassSubObjectOf(*directSubObject))
return true;
}
return false;
}
bool SubObjectTree::SubObjectNode::operator==(const SubObjectNode &other)
{
return this->subObjectId == other.subObjectId;
}
bool SubObjectTree::SubObjectNode::isValid(string memberName)
{
return memberNameToSMapping[memberName].isValid;
}
void SubObjectTree::buildTreeRecursion(shared_ptr<SubObjectNode> node, eAccess access)
{
for (size_t i = 0; i < node->type->base_classes.size(); i++)
{
Type* base_class = node->type->base_classes[i];
eAccess base_access = node->type->base_classes_access[i];
const bool isVirtualBaseClass = node->type->isVirtualBaseClasses[i];
bool isNew = true;
shared_ptr<SubObjectNode> baseClassNode;
if (isVirtualBaseClass)
{
if (typeToVirtualSubObjectMapping.find(base_class) != typeToVirtualSubObjectMapping.end())
{
baseClassNode = typeToVirtualSubObjectMapping[base_class];
isNew = false;
}
else
{
baseClassNode = make_shared<SubObjectNode>(base_class);
typeToVirtualSubObjectMapping[base_class] = baseClassNode;
}
}
else
{
baseClassNode = make_shared<SubObjectNode>(base_class);
}
if (typeToUnambiguousData.find(base_class) == typeToUnambiguousData.end())
{
typeToUnambiguousData[base_class] = UnambiguousData(isVirtualBaseClass, min(base_access, access));
}
else
{
// type is Unambiguous
if (typeToUnambiguousData[base_class].isValid)
{
// if the one of base classes is not virtual
if (!typeToUnambiguousData[base_class].isVirtual || !isVirtualBaseClass)
typeToUnambiguousData[base_class].isValid = false;
}
typeToUnambiguousData[base_class].access = max(typeToUnambiguousData[base_class].access, min(base_access, access));
}
node->directBaseSubObjects.push_back(baseClassNode);
if (isNew)
buildTreeRecursion(baseClassNode, min(base_access, access));
switch (base_access)
{
case ePrivate:
node->private_set.insert(baseClassNode->protected_set.begin(), baseClassNode->protected_set.end());
node->private_set.insert(baseClassNode->public_set.begin(), baseClassNode->public_set.end());
break;
case eProtected:
node->protected_set.insert(baseClassNode->protected_set.begin(), baseClassNode->protected_set.end());
node->protected_set.insert(baseClassNode->public_set.begin(), baseClassNode->public_set.end());
break;
case ePublic:
node->protected_set.insert(baseClassNode->protected_set.begin(), baseClassNode->protected_set.end());
node->public_set.insert(baseClassNode->public_set.begin(), baseClassNode->public_set.end());
break;
}
}
for (size_t i = 0; i < node->type->fields.size(); i++)
{
switch (node->type->fields_access[i])
{
case ePrivate:
node->private_set.insert({ node, i });
break;
case eProtected:
node->protected_set.insert({ node, i });
break;
case ePublic:
node->public_set.insert({ node, i });
break;
}
}
}
SubObjectTree::SubObjectTree() {}
void SubObjectTree::buildTree(Type* _root)
{
root = make_shared<SubObjectNode>(_root);
root->type_access = ePublic;
buildTreeRecursion(root);
updateUnambiguousDeriveClasses(_root);
calculateMembers(root);
for (auto &memberNameSPair : root->memberNameToSMapping)
{
const string &memberName = memberNameSPair.first;
const auto S = memberNameSPair.second;
for (auto &member : S.declaration_set)
if (S.isValid)
{
this->unambiguousMembers.push_back(member);
this->unambiguousMembersAccess.push_back(getUnambiguousMembersAccess(member));
}
}
}
eAccess SubObjectTree::getUnambiguousMembersAccess(std::pair<shared_ptr<SubObjectNode>, int> member)
{
if (root->public_set.find(member) != root->public_set.end())
return ePublic;
if (root->protected_set.find(member) != root->protected_set.end())
return eProtected;
if (root->private_set.find(member) != root->private_set.end())
return ePrivate;
return eNoAccess;
}
void SubObjectTree::updateUnambiguousDeriveClasses(Type* _root)
{
for (auto data : typeToUnambiguousData)
{
//is type Unambiguous
if (data.second.isValid && data.second.access == ePublic)
{
data.first->unambiguous_derive_classes.push_back(_root);
_root->unambiguous_base_classes.push_back(data.first);
}
}
}
bool SubObjectTree::areDeclarationSetsEqual(const SubObjectNode::S &s1, const SubObjectNode::S &s2)
{
if (!s1.isValid || !s2.isValid) // an invalid declaration set is considered different from any other
return false;
return s1.declaration_set == s2.declaration_set;
}
/*
* Check whether each member in s1 is a base class subobject of at least one of the members is s2
* Note: argument order matters
*/
bool SubObjectTree::subObjectSetComparison(const unordered_set<shared_ptr<SubObjectNode>> &set1, const unordered_set<shared_ptr<SubObjectNode>> &set2)
{
for (auto firstSubObject : set1)
{
bool isBaseClassSubObject = false;
for (auto secondSubObject : set2)
{
if (firstSubObject->isBaseClassSubObjectOf(*secondSubObject))
{
isBaseClassSubObject = true;
break;
}
}
if (!isBaseClassSubObject)
return false;
}
return true;
}
void SubObjectTree::calculateMembers(shared_ptr<SubObjectNode> node)
{
auto& myMemberNameToSMapping = node->memberNameToSMapping;
// add all this sets members to corresponding S set
for (size_t i = 0; i < node->type->fields_name.size(); i++)
{
myMemberNameToSMapping[node->type->fields_name[i]].declaration_set.insert({ node, i });
myMemberNameToSMapping[node->type->fields_name[i]].subobject_set.insert(node);
}
// end of adding members
for (shared_ptr<SubObjectNode> subObject : node->directBaseSubObjects)
{
calculateMembers(subObject); // recursevly calculate direct base sub objects member name to S mapping
auto& otherMemberNameToSMapping = subObject->memberNameToSMapping;
for (auto& it : otherMemberNameToSMapping) // go over others S sets and merge them to mine
{
const string& memberName = it.first;
const auto& otherMemberS = it.second;
{// check whether this set already has this member name, if so, continue to next name
bool condition = false;
for (size_t i = 0; i < node->type->fields_name.size(); i++) {
if (memberName == node->type->fields_name[i]) {
condition = true;
break;
}
}
if (condition) // leave S uncahnged and continue
continue;
}// end of last check
{// check if I dont have a S set for this member name, if so copy others set and continue to next name
if (myMemberNameToSMapping.find(memberName) == myMemberNameToSMapping.end())
{
myMemberNameToSMapping[memberName] = otherMemberNameToSMapping[memberName];
continue;
}
}// end of last check
auto& myMemberS = myMemberNameToSMapping[memberName];
{// check whether each member in other subobject set is a base class subobject of at least one of the members is my sub object set
bool condition = subObjectSetComparison(otherMemberS.subobject_set, myMemberS.subobject_set);
if (condition) // leave S unchanged and continue
continue;
}// end of last check
{// check whether each member in my subobject set is a base class subobject of at least one of the members is other subobject set
bool condition = subObjectSetComparison(myMemberS.subobject_set, otherMemberS.subobject_set);
if (condition) // copy others set and continue
{
myMemberNameToSMapping[memberName] = otherMemberNameToSMapping[memberName];
continue;
}
}// end of last check
{// check whether declaration sets differ, if so merge is ambiguous
bool condition = areDeclarationSetsEqual(myMemberS, otherMemberS);
if (!condition)
{
// declaration set is now invalid, and subobject set is now union of the two subobject sets
myMemberS.isValid = false;
myMemberS.subobject_set.insert(otherMemberS.subobject_set.begin(), otherMemberS.subobject_set.end());
continue;
}
}// end of last check
{// otherwise, the new set is a lookup set with the shared set of declarations and the union of the subobject sets
myMemberS.subobject_set.insert(otherMemberS.subobject_set.begin(), otherMemberS.subobject_set.end());
continue;
}// end of last check
}
}
}
SubObjectTree::UnambiguousData::UnambiguousData(bool _isVirtual, eAccess _access) : isValid(true), isVirtual(_isVirtual), access(_access) {
}
bool SubObjectTree::runFinalOverridersCheck()
{
// clear data from previuos calculatations
functionToFinalOverridersMapping.clear();
culculateFinalOverridersRecursion(this->root);
for (auto &funcAndOverridesPair : functionToFinalOverridersMapping)
if (funcAndOverridesPair.second.size() >= 2)
return false;
return true;
}
void SubObjectTree::culculateFinalOverridersRecursion(shared_ptr<SubObjectNode> node)
{
for (shared_ptr<SubObjectNode> subObj : node->directBaseSubObjects)
culculateFinalOverridersRecursion(subObj);
unordered_set<SubObjectMemberFunction, SubObjectMemberFunction::hash> subObjectsFunctions;
for (shared_ptr<SubObjectNode> subObj : node->directBaseSubObjects)
{
for (const SubObjectMemberFunction &subObjFunc : subObj->allSubTreeFunctions)
{
subObjectsFunctions.insert(subObjFunc);
}
}
for (const SubObjectMemberFunction &subObjFunc : subObjectsFunctions)
{
if (subObjFunc.func->is_marked_as_virtual)
{
for (Function* myFunc : node->type->func_list)
{
if (Function::compare_signature(*subObjFunc.func, *myFunc)) // if ovveride occurs
{
myFunc->is_virtual_candidate = true;
for (auto itr = functionToFinalOverridersMapping[subObjFunc].begin(); itr != functionToFinalOverridersMapping[subObjFunc].end();)
{
if (subObjectsFunctions.find(*itr) != subObjectsFunctions.end())
itr = functionToFinalOverridersMapping[subObjFunc].erase(itr);
else
itr++;
}
// insert self
functionToFinalOverridersMapping[subObjFunc].insert(SubObjectMemberFunction(node, myFunc));
}
}
}
}
node->allSubTreeFunctions.insert(subObjectsFunctions.begin(), subObjectsFunctions.end());
for (Function *myFunc : node->type->func_list)
{
node->allSubTreeFunctions.insert({ node, myFunc });
if (myFunc->is_marked_as_virtual)
myFunc->is_virtual_candidate = true;
}
}
///////////////////////////////////////////////////////////////////////////////
// Local Variables:
// c-basic-offset: 4
// tab-width: 4
// End:
// End of file. | [
"tamiraviv@users.noreply.github.com"
] | tamiraviv@users.noreply.github.com |
90081a6cba4632867decaba1cf70e3de411cbb31 | 0b2db9b65f3cc4b817ce509f83d5045eb7624ee8 | /source/godot_bindings/include/gen/AudioEffectEQ10.hpp | 0fc9a4af182dd7c3fdfcd141dd71ee120c26b9a3 | [] | no_license | Specialsaucewc/HackathonGodot | 00800865c6d3c8073e9dec83b1cf7dd7ae5136af | 0a8be6592906c83c3b648e6f79371b35b76a080d | refs/heads/master | 2023-02-01T18:55:14.195672 | 2020-12-17T05:07:12 | 2020-12-17T05:07:12 | 321,496,228 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,033 | hpp | #ifndef GODOT_CPP_AUDIOEFFECTEQ10_HPP
#define GODOT_CPP_AUDIOEFFECTEQ10_HPP
#include <gdnative_api_struct.gen.h>
#include <stdint.h>
#include <core/CoreTypes.hpp>
#include <core/Ref.hpp>
#include "AudioEffectEQ.hpp"
namespace godot {
class AudioEffectEQ10 : public AudioEffectEQ {
struct ___method_bindings {
};
static ___method_bindings ___mb;
static void *_detail_class_tag;
public:
static void ___init_method_bindings();
inline static size_t ___get_id() { return (size_t)_detail_class_tag; }
static inline const char *___get_class_name() { return (const char *) "AudioEffectEQ10"; }
static inline const char *___get_godot_class_name() { return (const char *) "AudioEffectEQ10"; }
static inline Object *___get_from_variant(Variant a) { godot_object *o = (godot_object*) a; return (o) ? (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, o) : nullptr; }
// enums
// constants
static AudioEffectEQ10 *_new();
// methods
};
}
#endif | [
"specialsaucewc@gmail.com"
] | specialsaucewc@gmail.com |
489e4b854cf3ffb9df5d049a1d40111a9ec2ba20 | 511a8b98bbcb2e6003068588481e53a3fe194a26 | /Cave.h | 51d53654beb53bc38a0eebee99b87e3ccdce1ec1 | [] | no_license | sparshkumar14/Fish_Game | 2d070783629a248face22426b7c5986f9d4aad63 | c6086979909976b03afa27965dbac38590831619 | refs/heads/master | 2021-01-19T14:56:22.566968 | 2015-01-07T17:22:21 | 2015-01-07T17:22:21 | 28,925,000 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 489 | h | #ifndef __Cave__
#define __Cave__
#include "GameObject.h"
#include "CartPoint.h"
#include "Fish.h"
class Fish;
class Model;
using namespace std;
class Cave: public GameObject
{
public:
bool hide_fish(Fish* fish_to_hide);
bool release_fish(Fish* fish_to_release);
bool update();
void show_status();
Cave();
Cave(int in_id, CartPoint in_loc, Model * world);
~Cave();
double get_space();
void save(ofstream& file);
private:
double space;
protected:
Model*world;
};
#endif
| [
"sparshkumar@aol.com"
] | sparshkumar@aol.com |
9c99cac4d3b0e79494d69d301188e2eb018f0389 | 5bb277d676944b89bd6d5e7ba6a4bc6635cd1845 | /SRM 452/EggCartons.cpp | cd74df16b3544d3f1683fe23d1aadbbfa8bebe0d | [] | no_license | tanmesh/topcoder_code | 6b63f7176322daf0e0d19bef849bffae4f2cec74 | 0cc1cf1861ed56d8c7d79f7e4e975d5045438ca6 | refs/heads/master | 2020-05-22T01:06:12.100903 | 2018-07-26T06:29:39 | 2018-07-26T06:29:39 | 62,441,732 | 1 | 0 | null | 2018-07-29T10:49:55 | 2016-07-02T08:30:19 | C++ | UTF-8 | C++ | false | false | 3,046 | cpp | #include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <sstream>
#include <typeinfo>
#include <fstream>
using namespace std;
class EggCartons {
public:
int minCartons(int n) {
int i=0,sum=-1,min=101;
while(8*i <= n){
float tmp = (n-(8*i))/6.0;
if((int)tmp == tmp && min > sum){
sum=i+tmp;
}
++i;
}
return sum;
}
};
// CUT begin
ifstream data("EggCartons.sample");
string next_line() {
string s;
getline(data, s);
return s;
}
template <typename T> void from_stream(T &t) {
stringstream ss(next_line());
ss >> t;
}
void from_stream(string &s) {
s = next_line();
}
template <typename T>
string to_string(T t) {
stringstream s;
s << t;
return s.str();
}
string to_string(string t) {
return "\"" + t + "\"";
}
bool do_test(int n, int __expected) {
time_t startClock = clock();
EggCartons *instance = new EggCartons();
int __result = instance->minCartons(n);
double elapsed = (double)(clock() - startClock) / CLOCKS_PER_SEC;
delete instance;
if (__result == __expected) {
cout << "PASSED!" << " (" << elapsed << " seconds)" << endl;
return true;
}
else {
cout << "FAILED!" << " (" << elapsed << " seconds)" << endl;
cout << " Expected: " << to_string(__expected) << endl;
cout << " Received: " << to_string(__result) << endl;
return false;
}
}
int run_test(bool mainProcess, const set<int> &case_set, const string command) {
int cases = 0, passed = 0;
while (true) {
if (next_line().find("--") != 0)
break;
int n;
from_stream(n);
next_line();
int __answer;
from_stream(__answer);
cases++;
if (case_set.size() > 0 && case_set.find(cases - 1) == case_set.end())
continue;
cout << " Testcase #" << cases - 1 << " ... ";
if ( do_test(n, __answer)) {
passed++;
}
}
if (mainProcess) {
cout << endl << "Passed : " << passed << "/" << cases << " cases" << endl;
int T = time(NULL) - 1492200978;
double PT = T / 60.0, TT = 75.0;
cout << "Time : " << T / 60 << " minutes " << T % 60 << " secs" << endl;
cout << "Score : " << 250 * (0.3 + (0.7 * TT * TT) / (10.0 * PT * PT + TT * TT)) << " points" << endl;
}
return 0;
}
int main(int argc, char *argv[]) {
cout.setf(ios::fixed, ios::floatfield);
cout.precision(2);
set<int> cases;
bool mainProcess = true;
for (int i = 1; i < argc; ++i) {
if ( string(argv[i]) == "-") {
mainProcess = false;
} else {
cases.insert(atoi(argv[i]));
}
}
if (mainProcess) {
cout << "EggCartons (250 Points)" << endl << endl;
}
return run_test(mainProcess, cases, argv[0]);
}
// CUT end
| [
"tanmeshnm@gmail.com"
] | tanmeshnm@gmail.com |
85e9e9666f7ba2759263a58bd6c1c533a7511051 | 026ee4a8bcbd438ec14de04c7b3516c462fa35c0 | /rosbuild_ws/src/controllers/include/za_arm_planner/astar.h | 1136d375b733c444c43f811186ef8efce61d9116 | [
"BSD-3-Clause"
] | permissive | Boberito25/ButlerBot | 147fee6763863a8988d1969d7144cc8a17c7510b | 959f961bbc8c43be0ccb533dd2e2af5c55b0cc2a | refs/heads/master | 2021-01-23T00:10:01.907481 | 2014-05-05T18:03:34 | 2014-05-05T18:03:34 | 11,519,861 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 886 | h | #ifndef ASTAR_H
#define ASTAR_H
#include <iostream>
#include <stdio.h>
#include <queue> // std::priority_queue
#include <deque> // std::vector
#include <functional> // std::greater
#include "za_arm_planner/forward_kinematics.h"
class Astar {
public:
Astar();
std::vector<PState*> run(int* start, double* target);
int numticks;
private:
double obj_mass;
double time_step;
/* Space Matrix */
State*** space;
/* Frontier Set */
typedef std::priority_queue
<PState*,std::deque<PState*>,pstate_comp> statepq;
void expand_frontier(int is,int js, int ks);
double cost(State* s1, State* s2);
double heuristic(State* s);
bool inbounds(int i, int j, int k);
statepq frontier;
/* Constants */
double dist_threshold;
double angle_threshold;
double* target;
void compute_fk(int i, int j, int k);
bool will_continue(State* current);
};
#endif
| [
"vsunder@Jeeves.(none)"
] | vsunder@Jeeves.(none) |
3f88c59495e08d7b5a49a8482b250167be946215 | 9a3b9d80afd88e1fa9a24303877d6e130ce22702 | /src/Providers/UNIXProviders/AdvancedStorageSetting/UNIX_AdvancedStorageSetting_FREEBSD.hxx | e959ee0a2607322e172ebb29a9503f042fbfb2d6 | [
"MIT"
] | permissive | brunolauze/openpegasus-providers | 3244b76d075bc66a77e4ed135893437a66dd769f | f24c56acab2c4c210a8d165bb499cd1b3a12f222 | refs/heads/master | 2020-04-17T04:27:14.970917 | 2015-01-04T22:08:09 | 2015-01-04T22:08:09 | 19,707,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,831 | hxx | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#ifdef PEGASUS_OS_FREEBSD
#ifndef __UNIX_ADVANCEDSTORAGESETTING_PRIVATE_H
#define __UNIX_ADVANCEDSTORAGESETTING_PRIVATE_H
#endif
#endif
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
55867c904f93f0188d686ddcbed555f0124bbaaa | 6f3ca80c0bcf1ba68a4a76fe9e7890670c7cb9b9 | /Pasja informatyki/The Fibonacci Sequence/main.cpp | 39eb50217c818379d07e85c7e65ae8c0563e880f | [] | no_license | VKiNGpl/Cpp-projects | 5977ce9696d7f859f6e7b220c45bb87864475295 | 3dbfeba1ec1c8fcf382a75d00cc6ba3311f690ae | refs/heads/master | 2022-09-21T06:48:15.309868 | 2020-06-03T04:31:39 | 2020-06-03T04:31:39 | 197,949,676 | 0 | 0 | null | 2019-07-22T00:06:33 | 2019-07-20T15:38:14 | C++ | UTF-8 | C++ | false | false | 573 | cpp | #include <iostream>
#include <iomanip>
using namespace std;
long double fib[100000];int n;
int main()
{
cout<<"How many Fibonacci numbers would you like to extrapolate: ";
cin>>n;
cout<<endl;
fib[0]=1;
fib[1]=1;
for (int i=2; i<n; i++)
{
fib[i] = fib[i-1]+ fib[i-2];
}
cout<<setprecision(10000);
//for (int i=0; i<n; i++)
//{
// cout<<endl<<i+1<<" Fibonacci number: "<<fib[i];
//}
//cout<<endl<<n<<" Fibonacci number: "<<fib[n-1];
cout<<"Golden ratio: "<<fib[n-1]/fib[n-2]<<endl;
return 0;
}
| [
"krystianspiewak@gmail.com"
] | krystianspiewak@gmail.com |
7b07d14971290c2630a75944cadb01f70f25e9bb | 31406f420f019a191a74b9288a6e37dcd89e8e82 | /include/hermes/IR/IRVisitor.h | 4d4bd4ed301255c87d2e8a79cb5508fa9eedf489 | [
"MIT"
] | permissive | facebook/hermes | b1bf3cb60b5946450c7c9a421ac8dad7a675e0f5 | 440578b31ecce46fcc5ba2ad745ffd5712d63a35 | refs/heads/main | 2023-09-06T04:16:02.263184 | 2023-09-05T20:12:54 | 2023-09-05T20:12:54 | 154,201,259 | 8,449 | 593 | MIT | 2023-09-14T21:25:56 | 2018-10-22T19:13:00 | C++ | UTF-8 | C++ | false | false | 2,853 | h | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#ifndef HERMES_IR_IRVISITOR_H
#define HERMES_IR_IRVISITOR_H
#include "hermes/IR/IR.h"
#include "hermes/IR/Instrs.h"
#define INCLUDE_ALL_INSTRS
namespace hermes {
/// IRVisitorBase - This is a simple visitor class for Hermes IR nodes, allowing
/// clients to walk over entire IR functions, blocks, or instructions.
template <typename ImplClass, typename ValueRetTy = void>
class IRVisitorBase {
public:
ImplClass &asImpl() {
return static_cast<ImplClass &>(*this);
}
/// Top level visitor.
ValueRetTy visitValue(const Value &V) {
return ValueRetTy();
}
/// Define default IR implementations, chaining to parent nodes.
/// Use ValueKinds.def to automatically generate them.
#define DEF_VALUE(CLASS, PARENT) \
ValueRetTy visit##CLASS(const CLASS &I) { \
return asImpl().visit##PARENT(I); \
}
#include "hermes/IR/ValueKinds.def"
};
/// IRVisitor - This is a simple visitor class for Hermes IR nodes.
/// allowing clients to walk over hermes IRNodes of different types.
template <typename ImplClass, typename ValueRetTy = void>
class IRVisitor : public IRVisitorBase<ImplClass, ValueRetTy> {
public:
ImplClass &asImpl() {
return static_cast<ImplClass &>(*this);
}
/// Visit IR nodes.
ValueRetTy visit(const Value &V) {
switch (V.getKind()) {
default:
llvm_unreachable("Invalid kind");
#define DEF_VALUE(CLASS, PARENT) \
case ValueKind::CLASS##Kind: \
return asImpl().visit##CLASS(*llvh::cast<CLASS>(&V));
#include "hermes/IR/ValueKinds.def"
}
llvm_unreachable("Not reachable, all cases handled");
}
};
/// InstrVisitor - This is a simple visitor class for Hermes IR instructions,
/// allowing clients to walk over hermes Instructions of different types.
template <typename ImplClass, typename ValueRetTy = void>
class InstructionVisitor : public IRVisitorBase<ImplClass, ValueRetTy> {
public:
ImplClass &asImpl() {
return static_cast<ImplClass &>(*this);
}
// Perform any required pre-processing before visiting.
// Sub-classes can reimplement it to provide their custom
// pre-processing steps.
void beforeVisitInstruction(const Instruction &V) {}
/// Visit Instruction.
ValueRetTy visit(const Instruction &Inst) {
asImpl().beforeVisitInstruction(Inst);
switch (Inst.getKind()) {
default:
llvm_unreachable("Invalid kind");
#define DEF_VALUE(CLASS, PARENT) \
case ValueKind::CLASS##Kind: \
return asImpl().visit##CLASS(*llvh::cast<CLASS>(&Inst));
#include "hermes/IR/Instrs.def"
}
llvm_unreachable("Not reachable, all cases handled");
}
};
} // end namespace hermes
#undef INCLUDE_ALL_INSTRS
#endif
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
d1d91bda773bbcfcfddf8be6d68dc533ca12e5be | 0159867d6c7bf81f39befdace9ddad25c6f8a78e | /src/utilmoneystr.cpp | 313db59e0656d232eb6766d670c6882a1409f4cf | [
"MIT"
] | permissive | Shitcoin-beta/shitcoin-sc | be8cea893b6f8e14440f1250db4104dda243a129 | 050d1ba00a65827f60a0c9a1d88ac78d96ca61d8 | refs/heads/master | 2022-10-16T19:09:40.249282 | 2020-06-16T21:15:17 | 2020-06-16T21:15:17 | 272,813,689 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,084 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Copyright (c) 2020 The Shitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <utilmoneystr.h>
#include <primitives/transaction.h>
#include <tinyformat.h>
#include <utilstrencodings.h>
std::string FormatMoney(const CAmount& n)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
int64_t n_abs = (n > 0 ? n : -n);
int64_t quotient = n_abs/COIN;
int64_t remainder = n_abs%COIN;
std::string str = strprintf("%d.%08d", quotient, remainder);
// Right-trim excess zeros before the decimal point:
int nTrim = 0;
for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
++nTrim;
if (nTrim)
str.erase(str.size()-nTrim, nTrim);
if (n < 0)
str.insert((unsigned int)0, 1, '-');
return str;
}
bool ParseMoney(const std::string& str, CAmount& nRet)
{
return ParseMoney(str.c_str(), nRet);
}
bool ParseMoney(const char* pszIn, CAmount& nRet)
{
std::string strWhole;
int64_t nUnits = 0;
const char* p = pszIn;
while (isspace(*p))
p++;
for (; *p; p++)
{
if (*p == '.')
{
p++;
int64_t nMult = CENT*10;
while (isdigit(*p) && (nMult > 0))
{
nUnits += nMult * (*p++ - '0');
nMult /= 10;
}
break;
}
if (isspace(*p))
break;
if (!isdigit(*p))
return false;
strWhole.insert(strWhole.end(), *p);
}
for (; *p; p++)
if (!isspace(*p))
return false;
if (strWhole.size() > 10) // guard against 63 bit overflow
return false;
if (nUnits < 0 || nUnits > COIN)
return false;
int64_t nWhole = atoi64(strWhole);
CAmount nValue = nWhole*COIN + nUnits;
nRet = nValue;
return true;
}
| [
"66981424+Shitcoin-beta@users.noreply.github.com"
] | 66981424+Shitcoin-beta@users.noreply.github.com |
2bdf708a93dcb25ad273a1eff791a8b01890bc72 | c45520a4af85a14d519020fee698728c42073b9f | /proj.win32/main.cpp | 74eb5883799b3d21138c5627495395e5673698e9 | [] | no_license | Scorpioni4e/Game1 | bb1d7677d2c22a0864a33c206150c646c5bd01e4 | 11691c566f2494788581909aaefe5524a0ecaed5 | refs/heads/master | 2020-03-30T01:24:38.280740 | 2018-09-26T13:32:08 | 2018-09-26T13:32:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,650 | cpp | /****************************************************************************
Copyright (c) team1
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 "main.h"
#include "AppDelegate.h"
#include "cocos2d.h"
USING_NS_CC;
int WINAPI _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// create the application instance
AppDelegate app;
return Application::getInstance()->run();
}
| [
"dr.light2215@gmail.com"
] | dr.light2215@gmail.com |
3dad7daa17844759d262d044ed220c52d36dd90b | f4d8531a987bc53adfab365ac262357f34413db6 | /mrpt-1.4.0/apps/RawLogViewer/CIniEditor.h | 4ef5097d075907e0bdf0e7629c66ac8aea29ee37 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | saurabhd14/Mytest | 5f5b4232df9a0725ca722ff97a1037f31a9bb9ca | 4b8c4653384fd5a7f5104c5ec0977a64f703eecb | refs/heads/master | 2021-01-20T05:43:32.427329 | 2017-04-30T15:24:18 | 2017-04-30T15:24:18 | 89,801,996 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,439 | h | /* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2016, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#ifndef CINIEDITOR_H
#define CINIEDITOR_H
//(*Headers(CIniEditor)
#include <wx/sizer.h>
#include <wx/textctrl.h>
#include <wx/button.h>
#include <wx/dialog.h>
//*)
class CIniEditor: public wxDialog
{
public:
CIniEditor(wxWindow* parent,wxWindowID id=wxID_ANY,const wxPoint& pos=wxDefaultPosition,const wxSize& size=wxDefaultSize);
virtual ~CIniEditor();
//(*Declarations(CIniEditor)
wxButton* btnCancel;
wxTextCtrl* edText;
wxButton* btnOK;
//*)
protected:
//(*Identifiers(CIniEditor)
static const long ID_BUTTON1;
static const long ID_BUTTON2;
static const long ID_TEXTCTRL1;
//*)
private:
//(*Handlers(CIniEditor)
void OnbtnCancelClick(wxCommandEvent& event);
void OnbtnOKClick(wxCommandEvent& event);
//*)
DECLARE_EVENT_TABLE()
};
#endif
| [
"saurabhd14@gmail.com"
] | saurabhd14@gmail.com |
4e59d2ce9d61d96ad9aa447a815e9aa9bbee4242 | aab332ff58af14e949737462efd498f45ace9e01 | /simulation_ws/devel/include/simulation_control/GetQuadcopterData.h | 14223098a5739a976efe51b864bf62838cb6d8ed | [] | no_license | GhadeerElmkaiel/Quadcopter-swarms | 28019bacdfa125b4376c89b89755a4b52c072549 | 2b5b25b3fd7fab0fe0f197c627dfe8eeb830a7c7 | refs/heads/master | 2021-05-17T14:43:54.302024 | 2020-03-28T16:38:58 | 2020-03-28T16:38:58 | 250,826,123 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,182 | h | // Generated by gencpp from file simulation_control/GetQuadcopterData.msg
// DO NOT EDIT!
#ifndef SIMULATION_CONTROL_MESSAGE_GETQUADCOPTERDATA_H
#define SIMULATION_CONTROL_MESSAGE_GETQUADCOPTERDATA_H
#include <ros/service_traits.h>
#include <simulation_control/GetQuadcopterDataRequest.h>
#include <simulation_control/GetQuadcopterDataResponse.h>
namespace simulation_control
{
struct GetQuadcopterData
{
typedef GetQuadcopterDataRequest Request;
typedef GetQuadcopterDataResponse Response;
Request request;
Response response;
typedef Request RequestType;
typedef Response ResponseType;
}; // struct GetQuadcopterData
} // namespace simulation_control
namespace ros
{
namespace service_traits
{
template<>
struct MD5Sum< ::simulation_control::GetQuadcopterData > {
static const char* value()
{
return "bda7fb9bcb992692c1da67536514aeb3";
}
static const char* value(const ::simulation_control::GetQuadcopterData&) { return value(); }
};
template<>
struct DataType< ::simulation_control::GetQuadcopterData > {
static const char* value()
{
return "simulation_control/GetQuadcopterData";
}
static const char* value(const ::simulation_control::GetQuadcopterData&) { return value(); }
};
// service_traits::MD5Sum< ::simulation_control::GetQuadcopterDataRequest> should match
// service_traits::MD5Sum< ::simulation_control::GetQuadcopterData >
template<>
struct MD5Sum< ::simulation_control::GetQuadcopterDataRequest>
{
static const char* value()
{
return MD5Sum< ::simulation_control::GetQuadcopterData >::value();
}
static const char* value(const ::simulation_control::GetQuadcopterDataRequest&)
{
return value();
}
};
// service_traits::DataType< ::simulation_control::GetQuadcopterDataRequest> should match
// service_traits::DataType< ::simulation_control::GetQuadcopterData >
template<>
struct DataType< ::simulation_control::GetQuadcopterDataRequest>
{
static const char* value()
{
return DataType< ::simulation_control::GetQuadcopterData >::value();
}
static const char* value(const ::simulation_control::GetQuadcopterDataRequest&)
{
return value();
}
};
// service_traits::MD5Sum< ::simulation_control::GetQuadcopterDataResponse> should match
// service_traits::MD5Sum< ::simulation_control::GetQuadcopterData >
template<>
struct MD5Sum< ::simulation_control::GetQuadcopterDataResponse>
{
static const char* value()
{
return MD5Sum< ::simulation_control::GetQuadcopterData >::value();
}
static const char* value(const ::simulation_control::GetQuadcopterDataResponse&)
{
return value();
}
};
// service_traits::DataType< ::simulation_control::GetQuadcopterDataResponse> should match
// service_traits::DataType< ::simulation_control::GetQuadcopterData >
template<>
struct DataType< ::simulation_control::GetQuadcopterDataResponse>
{
static const char* value()
{
return DataType< ::simulation_control::GetQuadcopterData >::value();
}
static const char* value(const ::simulation_control::GetQuadcopterDataResponse&)
{
return value();
}
};
} // namespace service_traits
} // namespace ros
#endif // SIMULATION_CONTROL_MESSAGE_GETQUADCOPTERDATA_H
| [
"ghadeer.elmkaiel@gmail.com"
] | ghadeer.elmkaiel@gmail.com |
3986bf8921d514516b4c0574f15c63713217bf10 | 157fd7fe5e541c8ef7559b212078eb7a6dbf51c6 | /TRiAS/TRiAS/TRiAS02/DLLBIND.CXX | cde1538473494ec595b1cd7dcf9e68c02b4ebb94 | [] | no_license | 15831944/TRiAS | d2bab6fd129a86fc2f06f2103d8bcd08237c49af | 840946b85dcefb34efc219446240e21f51d2c60d | refs/heads/master | 2020-09-05T05:56:39.624150 | 2012-11-11T02:24:49 | 2012-11-11T02:24:49 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,921 | cxx | // Funktionen für dynamisches Binden der DLL ----------------------------------
// File: DLLBIND.CXX
#include "trias02p.hxx"
#if !defined(WIN16)
#define LOADLIBRARY_FAILED(x) (x == 0)
#else
#define LOADLIBRARY_FAILED(x) (x <= HINSTANCE_ERROR)
#endif
EXPORT02 DLLBind::DLLBind (const char *pcDLLName, DWORD dwFlags)
{
// ParameterTest
if (NULL == pcDLLName) {
_hLib = NULL;
return;
}
m_strName = pcDLLName;
// WindowsFehlerMeldung unterdrücken
unsigned int oldErrMode = SetErrorMode (SEM_NOOPENFILEERRORBOX);
#if !defined(WIN16)
// #HK990620 work around WinNT4 LoadProcess bug
char szModuleShort[_MAX_PATH];
int cbShortName = GetShortPathName (m_strName.c_str(), szModuleShort, _MAX_PATH);
LPCSTR pcModule = NULL;
if (cbShortName == _MAX_PATH)
return;
pcModule = (cbShortName == 0 || cbShortName == ERROR_INVALID_PARAMETER) ? m_strName.c_str() : szModuleShort;
_hLib = LoadLibraryEx (pcModule, NULL, dwFlags);
#else
_hLib = LoadLibrary ((char *)m_strName.c_str());
#endif
if (LOADLIBRARY_FAILED(_hLib)) // Fehler: kann DLL nicht laden
_hLib = NULL;
// vorherigen Zustand wieder einstellen
SetErrorMode (oldErrMode);
}
EXPORT02 DLLBind::~DLLBind (void)
{ // DLL wieder freigeben
if (_hLib != NULL)
FreeLibrary (_hLib);
}
DLLBind *EXPORT02 DLLBind::CreateInstance (const char *pDLLName, DWORD dwFlags)
{
DLLBind *pDLL = NULL;
TX_TRY(pDLL = new DLLBind (pDLLName, dwFlags));
if (pDLL == NULL || pDLL -> hLib() == NULL) {
DELETE_OBJ (pDLL);
return NULL;
}
return pDLL;
}
// Memberfunktionen -----------------------------------------------------------
FARPROC EXPORT02 DLLBind::GetProcAddress (const char *FunctionName)
{
if (_hLib != NULL)
return ::GetProcAddress (_hLib, FunctionName);
else
return NULL; // Fehler
}
LPCSTR EXPORT02 DLLBind::GetName (void)
{
return m_strName.c_str();
}
| [
"Windows Live ID\\hkaiser@cct.lsu.edu"
] | Windows Live ID\hkaiser@cct.lsu.edu |
9e5adc8ce3e8e2ba6f6e1a6769f75add63dbb461 | d35b0bd401bcc2089fcabb1d0d2fd298b8cc1941 | /GDAL/include/xercesc/dom/DOMXPathEvaluator.hpp | e1308b31b586daa0dc0965942e462a8c7fb53c0c | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"Zlib"
] | permissive | hex-hex/ZxLib | 9bad09c8190d4458a84279c02b6e5070201a9c7b | 286d4f48217b38920cf81404774617915ea99874 | refs/heads/master | 2021-07-23T04:28:29.255180 | 2016-10-17T07:41:01 | 2016-10-17T07:41:01 | 71,088,540 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,979 | hpp | #ifndef DOMXPathEvaluator_HEADER_GUARD_
#define DOMXPathEvaluator_HEADER_GUARD_
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <xercesc/util/XercesDefs.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class DOMXPathNSResolver;
class DOMXPathExpression;
class DOMNode;
/**
* The evaluation of XPath expressions is provided by <code>DOMXPathEvaluator</code>.
* In a DOM implementation which supports the XPath 3.0 feature, the <code>DOMXPathEvaluator</code>
* interface will be implemented on the same object which implements the Document interface permitting
* it to be obtained by casting or by using the DOM Level 3 getInterface method. In this case the
* implementation obtained from the Document supports the XPath DOM module and is compatible
* with the XPath 1.0 specification.
* Evaluation of expressions with specialized extension functions or variables may not
* work in all implementations and is, therefore, not portable. XPathEvaluator implementations
* may be available from other sources that could provide specific support for specialized extension
* functions or variables as would be defined by other specifications.
* @since DOM Level 3
*/
class CDOM_EXPORT DOMXPathEvaluator
{
protected:
// -----------------------------------------------------------------------
// Hidden constructors
// -----------------------------------------------------------------------
/** @name Hidden constructors */
//@{
DOMXPathEvaluator() {};
//@}
private:
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
/** @name Unimplemented constructors and operators */
//@{
DOMXPathEvaluator(const DOMXPathEvaluator &);
DOMXPathEvaluator& operator = (const DOMXPathEvaluator&);
//@}
public:
// -----------------------------------------------------------------------
// All constructors are hidden, just the destructor is available
// -----------------------------------------------------------------------
/** @name Destructor */
//@{
/**
* Destructor
*
*/
virtual ~DOMXPathEvaluator() {};
//@}
// -----------------------------------------------------------------------
// Virtual DOMDocument interface
// -----------------------------------------------------------------------
/** @name Functions introduced in DOM Level 3 */
//@{
/**
* Creates a parsed XPath expression with resolved namespaces. This is useful
* when an expression will be reused in an application since it makes it
* possible to compile the expression string into a more efficient internal
* form and preresolve all namespace prefixes which occur within the expression.
* @param expression of type XMLCh - The XPath expression string to be parsed.
* @param resolver of type <code>XPathNSResolver</code> - The resolver permits
* translation of all prefixes, including the xml namespace prefix, within the XPath expression
* into appropriate namespace URIs. If this is specified as null, any namespace
* prefix within the expression will result in <code>DOMException</code> being thrown with the
* code NAMESPACE_ERR.
* @return <code>XPathExpression</code> The compiled form of the XPath expression.
* @exception <code>XPathException</code>
* INVALID_EXPRESSION_ERR: Raised if the expression is not legal according to the
* rules of the <code>DOMXPathEvaluator</code>.
* @exception DOMException
* NAMESPACE_ERR: Raised if the expression contains namespace prefixes which cannot
* be resolved by the specified <code>XPathNSResolver</code>.
* @since DOM Level 3
*/
virtual const DOMXPathExpression* createExpression(const XMLCh *expression, const DOMXPathNSResolver *resolver) = 0;
/** Adapts any DOM node to resolve namespaces so that an XPath expression can be
* easily evaluated relative to the context of the node where it appeared within
* the document. This adapter works like the DOM Level 3 method lookupNamespaceURI
* on nodes in resolving the namespaceURI from a given prefix using the current
* information available in the node's hierarchy at the time lookupNamespaceURI
* is called. also correctly resolving the implicit xml prefix.
* @param nodeResolver of type <code>DOMNode</code> The node to be used as a context
* for namespace resolution.
* @return <code>XPathNSResolver</code> <code>XPathNSResolver</code> which resolves namespaces
* with respect to the definitions in scope for a specified node.
*/
virtual const DOMXPathNSResolver* createNSResolver(DOMNode *nodeResolver) = 0;
/**
* Evaluates an XPath expression string and returns a result of the specified
* type if possible.
* @param expression of type XMLCh The XPath expression string to be parsed
* and evaluated.
* @param contextNode of type <code>DOMNode</code> The context is context node
* for the evaluation
* of this XPath expression. If the <code>DOMXPathEvaluator</code> was obtained by
* casting the <code>DOMDocument</code> then this must be owned by the same
* document and must be a <code>DOMDocument</code>, <code>DOMElement</code>,
* <code>DOMAttribute</code>, <code>DOMText</code>, <code>DOMCDATASection</code>,
* <code>DOMComment</code>, <code>DOMProcessingInstruction</code>, or
* <code>XPathNamespace</code> node. If the context node is a <code>DOMText</code> or
* a <code>DOMCDATASection</code>, then the context is interpreted as the whole
* logical text node as seen by XPath, unless the node is empty in which case it
* may not serve as the XPath context.
* @param resolver of type <code>XPathNSResolver</code> The resolver permits
* translation of all prefixes, including the xml namespace prefix, within
* the XPath expression into appropriate namespace URIs. If this is specified
* as null, any namespace prefix within the expression will result in
* <code>DOMException</code> being thrown with the code NAMESPACE_ERR.
* @param type of type unsigned short - If a specific type is specified, then
* the result will be returned as the corresponding type.
* For XPath 1.0 results, this must be one of the codes of the <code>XPathResult</code>
* interface.
* @param result of type void* - The result specifies a specific result object
* which may be reused and returned by this method. If this is specified as
* null or the implementation does not reuse the specified result, a new result
* object will be constructed and returned.
* For XPath 1.0 results, this object will be of type <code>XPathResult</code>.
* @return void* The result of the evaluation of the XPath expression.
* For XPath 1.0 results, this object will be of type <code>XPathResult</code>.
* @exception <code>XPathException</code>
* INVALID_EXPRESSION_ERR: Raised if the expression is not legal
* according to the rules of the <code>DOMXPathEvaluator</code>
* TYPE_ERR: Raised if the result cannot be converted to return the specified type.
* @exception DOMException
* NAMESPACE_ERR: Raised if the expression contains namespace prefixes
* which cannot be resolved by the specified <code>XPathNSResolver</code>.
* WRONG_DOCUMENT_ERR: The Node is from a document that is not supported
* by this <code>DOMXPathEvaluator</code>.
* NOT_SUPPORTED_ERR: The Node is not a type permitted as an XPath context
* node or the request type is not permitted by this <code>DOMXPathEvaluator</code>.
*/
virtual void* evaluate(const XMLCh *expression, DOMNode *contextNode, const DOMXPathNSResolver *resolver,
unsigned short type, void* result) = 0;
//@}
};
XERCES_CPP_NAMESPACE_END
#endif
| [
"noreply@github.com"
] | noreply@github.com |
d9154513b2c9a10885a3e38a8c1f4db0760b5e2b | 94804944d737f321d5163ea998bd69c25461059b | /Hook/Hook.cpp | 9ad4428cca14ad55cbf18aea3c169361c0ae7bb9 | [] | no_license | Espboxx/C-C- | 76f3cc651170bf2cab93b2379a4f8466b730be48 | 1be721d6d8f25dc4664abf52ac52ceb737301d3c | refs/heads/master | 2022-11-11T03:17:16.724390 | 2020-06-23T03:53:49 | 2020-06-23T03:53:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,578 | cpp | #include <d3d11.h>
#include <iostream>
#pragma comment(lib, "d3d11.lib")
DWORD_PTR* pSwapChainVtable = NULL;
DWORD_PTR* pContextVTable = NULL;
DWORD_PTR* pDeviceVTable = NULL;
ID3D11Device *pDevice = NULL;
ID3D11DeviceContext *pContext = NULL;
const int MultisampleCount = 1;
LRESULT CALLBACK DXGIMsgProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { return DefWindowProc(hwnd, uMsg, wParam, lParam); }
DWORD __stdcall InitializeHook(LPVOID)
{
//Sleep(5000);
HMODULE hDXGIDLL = 0;
do
{
hDXGIDLL = GetModuleHandleA ("dxgi.dll");
Sleep(80);
} while (!hDXGIDLL);
Sleep(100);
IDXGISwapChain* pSwapChain;
WNDCLASSEXA wc = { sizeof(WNDCLASSEX), CS_CLASSDC, DXGIMsgProc, 0L, 0L, GetModuleHandleA(NULL), NULL, NULL, NULL, NULL, "DX", NULL };
RegisterClassExA(&wc);
HWND hWnd = CreateWindowA("DX", NULL, WS_OVERLAPPEDWINDOW, 100, 100, 300, 300, NULL, NULL, wc.hInstance, NULL);
D3D_FEATURE_LEVEL requestedLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1 };
D3D_FEATURE_LEVEL obtainedLevel;
ID3D11Device* d3dDevice = nullptr;
ID3D11DeviceContext* d3dContext = nullptr;
DXGI_SWAP_CHAIN_DESC scd;
ZeroMemory(&scd, sizeof(scd));
scd.BufferCount = 1;
scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
scd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
scd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
scd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
scd.OutputWindow = hWnd;
scd.SampleDesc.Count = MultisampleCount;
scd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
scd.Windowed = ((GetWindowLongPtr(hWnd, GWL_STYLE) & WS_POPUP) != 0) ? false : true;
scd.BufferDesc.Width = 1;
scd.BufferDesc.Height = 1;
scd.BufferDesc.RefreshRate.Numerator = 0;
scd.BufferDesc.RefreshRate.Denominator = 1;
UINT createFlags = 0;
IDXGISwapChain* d3dSwapChain = 0;
if (FAILED(D3D11CreateDeviceAndSwapChain(
nullptr,
D3D_DRIVER_TYPE_HARDWARE,
nullptr,
createFlags,
requestedLevels,
sizeof(requestedLevels) / sizeof(D3D_FEATURE_LEVEL),
D3D11_SDK_VERSION,
&scd,
&pSwapChain,
&pDevice,
&obtainedLevel,
&pContext)))
{
MessageBoxA (hWnd, "Failed to create directX device and swapchain!", "Error", MB_ICONERROR);
return NULL;
}
pSwapChainVtable = (DWORD_PTR*)pSwapChain;
pSwapChainVtable = (DWORD_PTR*)pSwapChainVtable[0];
pContextVTable = (DWORD_PTR*)pContext;
pContextVTable = (DWORD_PTR*)pContextVTable[0];
pDeviceVTable = (DWORD_PTR*)pDevice;
pDeviceVTable = (DWORD_PTR*)pDeviceVTable[0];
DWORD hmap;
DWORD hevent;
DWORD pbuffer;
hmap = (DWORD)CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 256, "Trans");
if (hmap != NULL)
{
pbuffer = (DWORD)MapViewOfFile ((HANDLE)hmap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
}
DWORD TSwapChainVtable;
TSwapChainVtable = pbuffer + 30;
*(DWORD*)TSwapChainVtable = (DWORD)pSwapChainVtable;
DWORD TContextVTable;
TContextVTable = pbuffer + 40;
*(DWORD*)TContextVTable = (DWORD)pContextVTable;
DWORD TDeviceVTable;
TDeviceVTable = pbuffer + 50;
*(DWORD*)TDeviceVTable = (DWORD)pDeviceVTable;
}
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
DisableThreadLibraryCalls(hModule);
CreateThread(NULL, NULL, reinterpret_cast<LPTHREAD_START_ROUTINE>(InitializeHook), NULL, NULL, NULL);
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
} | [
"noreply@github.com"
] | noreply@github.com |
e2d9937237ad3ac716e8922e7916722735195331 | f0c94c033598bbe5673d4ba4c7b2a8a79cb58d87 | /Metaballs/metaballs_src/window.h | 02c7c9ece6949906eb0085d10300e5b083df35ba | [] | no_license | gbarnes12/ProjectOrigami | f9784b63ead0920f4fa2960d981e5e7f123563ff | bf1971b063b0394e534a6a5dbb9e6cb468e52349 | refs/heads/master | 2021-05-31T12:45:14.376452 | 2015-12-01T17:35:59 | 2015-12-01T17:35:59 | 33,608,742 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,144 | h | //-----------------------------------------------------------------------------
// CWindow
//
// This class is an interface for the operative system's windows.
//
// To compile with this class you must link with:
// user32.lib gdi32.lib
//
// Copyright (c) 2001 Andreas Jönsson
//-----------------------------------------------------------------------------
#ifndef WINDOW_H
#define WINDOW_H
#define STRICT // Enable strict type checking
#define WIN32_LEAN_AND_MEAN // Don't include stuff that are rarely used
#include <windows.h>
class CApplication;
class CWindow
{
public:
struct SParameters
{
HINSTANCE m_hInstance;
bool m_bFullscreen;
int m_nWidth;
int m_nHeight;
char *m_sTitle;
};
CWindow();
HRESULT Initialize(SParameters &Params);
bool CheckMessage(bool bWait);
void SetDefault(SParameters *pParams);
HWND GetHandle();
protected:
virtual LRESULT MsgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
HWND m_hWnd;
CApplication *m_pApplication;
bool m_bFullscreen;
private:
static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
};
#endif | [
"lee_yujin@hotmail.de"
] | lee_yujin@hotmail.de |
b607f1f5c590f2f43bb8bb7b5e189a9b0e0a586f | 1081c5759a407498a66a3da512f4a2d9aeb7d668 | /utility.h | 0c09e9a933a848376d6e0070fbb0b6d4f1c13482 | [] | no_license | brycesandlund/PrimeHarmonicSums | 08abe0968385d823232a522d9fcd39a57e07eea5 | b1480af758a08dd412d70be36257550d09f393b6 | refs/heads/master | 2020-12-24T17:26:01.114544 | 2018-10-04T16:21:40 | 2018-10-04T16:21:40 | 32,773,715 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,752 | h | #ifndef _UTILITY
#define _UTILITY
#define DEBUG 0
#define DEBUG_BS 1
#define DEBUG_SP 0
#define DEBUG_OD 0
#define DEBUG_S2 0
#define DEBUG_EG 1
#define EP 1e-20
#include <cstdio>
#include <NTL/quad_float.h>
//#include <NTL/RR.h> // If using RR. Changing functions here applies to all files
using namespace std;
using namespace NTL;
typedef quad_float ftype;
ftype to_ftype(long long n)
{
char s[30];
sprintf(s,"%lld%c",n,0);
return to_quad_float(s);
}
ftype to_ftype(double n) {
return to_quad_float(n);
}
ftype to_ftype(int n) {
return to_quad_float(n);
}
ftype to_ftype(const char* n) {
return to_quad_float(n);
}
ftype to_ftype(long n) {
return to_ftype((long long)n);
}
typedef long long T;
T mult_mod(T a, T b, T m) {
T q;
T r;
asm(
"mulq %3;"
"divq %4;"
: "=a"(q), "=d"(r)
: "a"(a), "rm"(b), "rm"(m));
return r;
}
/* Computes a^b mod m. Assumes 1 <= m <= 2^62-1 and 0^0=1.
* The return value will always be in [0, m) regardless of the sign of a.
*/
T pow_mod(T a, T b, T m) {
if (b == 0) return 1 % m;
if (b == 1) return a < 0 ? a % m + m : a % m;
T t = pow_mod(a, b / 2, m);
t = mult_mod(t, t, m);
if (b % 2) t = mult_mod(t, a, m);
return t >= 0 ? t : t + m;
}
/* A deterministic implementation of Miller-Rabin primality test.
* This implementation is guaranteed to give the correct result for n < 2^64
* by using a 7-number magic base.
* Alternatively, the base can be replaced with the first 12 prime numbers
* (prime numbers <= 37) and still work correctly.
*/
bool is_prime(T n) {
T small_primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37};
for (int i = 0; i < 12; ++i)
if (n > small_primes[i] && n % small_primes[i] == 0)
return false;
T base[] = {2, 325, 9375, 28178, 450775, 9780504, 1795265022};
T d = n - 1;
int s = 0;
for (; d % 2 == 0; d /= 2, ++s);
for (int i = 0; i < 7; ++i) {
T a = base[i] % n;
if (a == 0) continue;
T t = pow_mod(a, d, n);
if (t == 1 || t == n - 1) continue;
bool found = false;
for (int r = 1; r < s; ++r) {
t = pow_mod(t, 2, n);
if (t == n - 1) {
found = true;
break;
}
}
if (!found)
return false;
}
return true;
}
bool * get_primes(long long x) {
bool *prime = new bool[x+1];
memset(prime, true, (x+1)*sizeof(bool));
prime[0] = false;
prime[1] = false;
for (long long i = 2; i*i <= x; ++i) {
if (prime[i]) {
for (long long j = i*i; j <= x; j+=i) {
prime[j] = false;
}
}
}
return prime;
}
#endif
| [
"bcsandlund@gmail.com"
] | bcsandlund@gmail.com |
000c23e9bd22e94ab761791ee06a40c614977ca4 | 350af7c9ac5a05beaeb72aaf4c17ab56bdbef16b | /lab3/5_9_seq.cc | 092c35df6d4455e82ad250d7819e1b725501dc8f | [] | no_license | vihowe/course_parallel | 803bf00832085ab865dcebfdab31eb0211a02a1d | c53323afa0149526294f410e1dbc2d7b87007c08 | refs/heads/master | 2023-04-11T16:13:01.384629 | 2021-04-26T17:00:43 | 2021-04-26T17:00:43 | 355,067,571 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,024 | cc | #include <cmath>
#include <iostream>
#include <chrono>
#include <ctime>
bool is_prime(int n)
{
for (int i = 2; i <= (int)sqrt(n); ++i)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
int main(int argc, char** argv)
{
int n = atoi(argv[1]);
bool marked[n-1] {0};
auto start_time = std::chrono::high_resolution_clock::now();
for(int i = 0; i < n-1; ++i)
{
if(!marked[i])
{
int k = i+2;
for(int j = i+k; j < n-1; j += k)
{
marked[j] = 1;
}
}
}
int cnt = 0;
for (int i = 0; i < n-1; ++i)
{
if (!marked[i])
{
cnt++;
}
}
auto end_time = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
std::cout << cnt << std::endl;
std::cout << "Time consuming: " << duration.count() << "ms" << std::endl;
} | [
"vihowe@qq.com"
] | vihowe@qq.com |
b1400d63631718833bd076eebd31090e75e854f8 | 062fe73aef5bd087e88320f0f8ce2023c0981713 | /RyujinrokuMobile/RyujinrokuMobile.NativeActivity/src/ShineLine.h | a52c0b62b6d68524143f12bd9c88c0e988734c50 | [] | no_license | remicalsoft/RyujinrokuMobile | 762c1bc94ab2baf5ebb71ae392f2e1e75c9e9601 | c3bff61dbce2298890954b8bba32da4946c085f9 | refs/heads/master | 2021-05-17T07:39:42.961357 | 2020-04-01T14:42:27 | 2020-04-01T14:42:27 | 250,699,354 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 327 | h | #pragma once
class ShineLine {
protected:
float _x1, _y1, _x2, _y2;
float _angle, _v;
int _alfa;
int _counter;
bool _isEndMove, _isStartMove;
int _color;
public:
ShineLine(float x, float y){
_x1 = _x2 = x;
_y1 = _y2 = y;
}
virtual ~ShineLine(){}
virtual bool update(){
return true;
}
virtual void draw();
};
| [
"remicalsoft@gmail.com"
] | remicalsoft@gmail.com |
cb9afaaab4c8d55423d647011c07a07cf3caf2c6 | 1a91ae6d762056cd7f4a3239101d94e0c32dfee0 | /subprojects/harfbuzz/src/hb-blob.cc | 8ebedca78876be03e60d150f63a519ae7828e03d | [
"Unlicense",
"MIT",
"LicenseRef-scancode-unicode",
"LGPL-2.1-or-later",
"BSD-3-Clause",
"MPL-1.0",
"OFL-1.1",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-other-permissive",
"MIT-Modern-Variant",
"LicenseRef-scancode-unknown-license-reference",
"Zlib",
"Libpng"
] | permissive | mrezai/godot_tl | 6c0b7d2ec2f056be312ee792e882d1fb40a803e7 | 87e81e741828e56620e308e34635fdbe418c821c | refs/heads/master | 2020-05-05T03:59:31.026389 | 2019-04-04T15:37:17 | 2019-04-04T15:37:17 | 179,693,309 | 0 | 0 | Unlicense | 2019-04-05T14:06:16 | 2019-04-05T14:06:16 | null | UTF-8 | C++ | false | false | 16,519 | cc | /*
* Copyright © 2009 Red Hat, Inc.
* Copyright © 2018 Ebrahim Byagowi
*
* This is part of HarfBuzz, a text shaping library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* Red Hat Author(s): Behdad Esfahbod
*/
#include "hb.hh"
#include "hb-blob.hh"
#ifdef HAVE_SYS_MMAN_H
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif /* HAVE_UNISTD_H */
#include <sys/mman.h>
#endif /* HAVE_SYS_MMAN_H */
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
/**
* SECTION: hb-blob
* @title: hb-blob
* @short_description: Binary data containers
* @include: hb.h
*
* Blobs wrap a chunk of binary data to handle lifecycle management of data
* while it is passed between client and HarfBuzz. Blobs are primarily used
* to create font faces, but also to access font face tables, as well as
* pass around other binary data.
**/
/**
* hb_blob_create: (skip)
* @data: Pointer to blob data.
* @length: Length of @data in bytes.
* @mode: Memory mode for @data.
* @user_data: Data parameter to pass to @destroy.
* @destroy: Callback to call when @data is not needed anymore.
*
* Creates a new "blob" object wrapping @data. The @mode parameter is used
* to negotiate ownership and lifecycle of @data.
*
* Return value: New blob, or the empty blob if something failed or if @length is
* zero. Destroy with hb_blob_destroy().
*
* Since: 0.9.2
**/
hb_blob_t *
hb_blob_create (const char *data,
unsigned int length,
hb_memory_mode_t mode,
void *user_data,
hb_destroy_func_t destroy)
{
hb_blob_t *blob;
if (!length ||
length >= 1u << 31 ||
!(blob = hb_object_create<hb_blob_t> ())) {
if (destroy)
destroy (user_data);
return hb_blob_get_empty ();
}
blob->data = data;
blob->length = length;
blob->mode = mode;
blob->user_data = user_data;
blob->destroy = destroy;
if (blob->mode == HB_MEMORY_MODE_DUPLICATE) {
blob->mode = HB_MEMORY_MODE_READONLY;
if (!blob->try_make_writable ()) {
hb_blob_destroy (blob);
return hb_blob_get_empty ();
}
}
return blob;
}
static void
_hb_blob_destroy (void *data)
{
hb_blob_destroy ((hb_blob_t *) data);
}
/**
* hb_blob_create_sub_blob:
* @parent: Parent blob.
* @offset: Start offset of sub-blob within @parent, in bytes.
* @length: Length of sub-blob.
*
* Returns a blob that represents a range of bytes in @parent. The new
* blob is always created with %HB_MEMORY_MODE_READONLY, meaning that it
* will never modify data in the parent blob. The parent data is not
* expected to be modified, and will result in undefined behavior if it
* is.
*
* Makes @parent immutable.
*
* Return value: New blob, or the empty blob if something failed or if
* @length is zero or @offset is beyond the end of @parent's data. Destroy
* with hb_blob_destroy().
*
* Since: 0.9.2
**/
hb_blob_t *
hb_blob_create_sub_blob (hb_blob_t *parent,
unsigned int offset,
unsigned int length)
{
hb_blob_t *blob;
if (!length || !parent || offset >= parent->length)
return hb_blob_get_empty ();
hb_blob_make_immutable (parent);
blob = hb_blob_create (parent->data + offset,
MIN (length, parent->length - offset),
HB_MEMORY_MODE_READONLY,
hb_blob_reference (parent),
_hb_blob_destroy);
return blob;
}
/**
* hb_blob_copy_writable_or_fail:
* @blob: A blob.
*
* Makes a writable copy of @blob.
*
* Return value: New blob, or nullptr if allocation failed.
*
* Since: 1.8.0
**/
hb_blob_t *
hb_blob_copy_writable_or_fail (hb_blob_t *blob)
{
blob = hb_blob_create (blob->data,
blob->length,
HB_MEMORY_MODE_DUPLICATE,
nullptr,
nullptr);
if (unlikely (blob == hb_blob_get_empty ()))
blob = nullptr;
return blob;
}
/**
* hb_blob_get_empty:
*
* Returns the singleton empty blob.
*
* See TODO:link object types for more information.
*
* Return value: (transfer full): the empty blob.
*
* Since: 0.9.2
**/
hb_blob_t *
hb_blob_get_empty (void)
{
return const_cast<hb_blob_t *> (&Null(hb_blob_t));
}
/**
* hb_blob_reference: (skip)
* @blob: a blob.
*
* Increases the reference count on @blob.
*
* See TODO:link object types for more information.
*
* Return value: @blob.
*
* Since: 0.9.2
**/
hb_blob_t *
hb_blob_reference (hb_blob_t *blob)
{
return hb_object_reference (blob);
}
/**
* hb_blob_destroy: (skip)
* @blob: a blob.
*
* Decreases the reference count on @blob, and if it reaches zero, destroys
* @blob, freeing all memory, possibly calling the destroy-callback the blob
* was created for if it has not been called already.
*
* See TODO:link object types for more information.
*
* Since: 0.9.2
**/
void
hb_blob_destroy (hb_blob_t *blob)
{
if (!hb_object_destroy (blob)) return;
blob->fini_shallow ();
free (blob);
}
/**
* hb_blob_set_user_data: (skip)
* @blob: a blob.
* @key: key for data to set.
* @data: data to set.
* @destroy: callback to call when @data is not needed anymore.
* @replace: whether to replace an existing data with the same key.
*
* Return value:
*
* Since: 0.9.2
**/
hb_bool_t
hb_blob_set_user_data (hb_blob_t *blob,
hb_user_data_key_t *key,
void * data,
hb_destroy_func_t destroy,
hb_bool_t replace)
{
return hb_object_set_user_data (blob, key, data, destroy, replace);
}
/**
* hb_blob_get_user_data: (skip)
* @blob: a blob.
* @key: key for data to get.
*
*
*
* Return value: (transfer none):
*
* Since: 0.9.2
**/
void *
hb_blob_get_user_data (hb_blob_t *blob,
hb_user_data_key_t *key)
{
return hb_object_get_user_data (blob, key);
}
/**
* hb_blob_make_immutable:
* @blob: a blob.
*
*
*
* Since: 0.9.2
**/
void
hb_blob_make_immutable (hb_blob_t *blob)
{
if (hb_object_is_immutable (blob))
return;
hb_object_make_immutable (blob);
}
/**
* hb_blob_is_immutable:
* @blob: a blob.
*
*
*
* Return value: TODO
*
* Since: 0.9.2
**/
hb_bool_t
hb_blob_is_immutable (hb_blob_t *blob)
{
return hb_object_is_immutable (blob);
}
/**
* hb_blob_get_length:
* @blob: a blob.
*
*
*
* Return value: the length of blob data in bytes.
*
* Since: 0.9.2
**/
unsigned int
hb_blob_get_length (hb_blob_t *blob)
{
return blob->length;
}
/**
* hb_blob_get_data:
* @blob: a blob.
* @length: (out):
*
*
*
* Returns: (transfer none) (array length=length):
*
* Since: 0.9.2
**/
const char *
hb_blob_get_data (hb_blob_t *blob, unsigned int *length)
{
if (length)
*length = blob->length;
return blob->data;
}
/**
* hb_blob_get_data_writable:
* @blob: a blob.
* @length: (out): output length of the writable data.
*
* Tries to make blob data writable (possibly copying it) and
* return pointer to data.
*
* Fails if blob has been made immutable, or if memory allocation
* fails.
*
* Returns: (transfer none) (array length=length): Writable blob data,
* or %NULL if failed.
*
* Since: 0.9.2
**/
char *
hb_blob_get_data_writable (hb_blob_t *blob, unsigned int *length)
{
if (!blob->try_make_writable ()) {
if (length)
*length = 0;
return nullptr;
}
if (length)
*length = blob->length;
return const_cast<char *> (blob->data);
}
bool
hb_blob_t::try_make_writable_inplace_unix (void)
{
#if defined(HAVE_SYS_MMAN_H) && defined(HAVE_MPROTECT)
uintptr_t pagesize = -1, mask, length;
const char *addr;
#if defined(HAVE_SYSCONF) && defined(_SC_PAGE_SIZE)
pagesize = (uintptr_t) sysconf (_SC_PAGE_SIZE);
#elif defined(HAVE_SYSCONF) && defined(_SC_PAGESIZE)
pagesize = (uintptr_t) sysconf (_SC_PAGESIZE);
#elif defined(HAVE_GETPAGESIZE)
pagesize = (uintptr_t) getpagesize ();
#endif
if ((uintptr_t) -1L == pagesize) {
DEBUG_MSG_FUNC (BLOB, this, "failed to get pagesize: %s", strerror (errno));
return false;
}
DEBUG_MSG_FUNC (BLOB, this, "pagesize is %lu", (unsigned long) pagesize);
mask = ~(pagesize-1);
addr = (const char *) (((uintptr_t) this->data) & mask);
length = (const char *) (((uintptr_t) this->data + this->length + pagesize-1) & mask) - addr;
DEBUG_MSG_FUNC (BLOB, this,
"calling mprotect on [%p..%p] (%lu bytes)",
addr, addr+length, (unsigned long) length);
if (-1 == mprotect ((void *) addr, length, PROT_READ | PROT_WRITE)) {
DEBUG_MSG_FUNC (BLOB, this, "mprotect failed: %s", strerror (errno));
return false;
}
this->mode = HB_MEMORY_MODE_WRITABLE;
DEBUG_MSG_FUNC (BLOB, this,
"successfully made [%p..%p] (%lu bytes) writable\n",
addr, addr+length, (unsigned long) length);
return true;
#else
return false;
#endif
}
bool
hb_blob_t::try_make_writable_inplace (void)
{
DEBUG_MSG_FUNC (BLOB, this, "making writable inplace\n");
if (this->try_make_writable_inplace_unix ())
return true;
DEBUG_MSG_FUNC (BLOB, this, "making writable -> FAILED\n");
/* Failed to make writable inplace, mark that */
this->mode = HB_MEMORY_MODE_READONLY;
return false;
}
bool
hb_blob_t::try_make_writable (void)
{
if (hb_object_is_immutable (this))
return false;
if (this->mode == HB_MEMORY_MODE_WRITABLE)
return true;
if (this->mode == HB_MEMORY_MODE_READONLY_MAY_MAKE_WRITABLE && this->try_make_writable_inplace ())
return true;
if (this->mode == HB_MEMORY_MODE_WRITABLE)
return true;
DEBUG_MSG_FUNC (BLOB, this, "current data is -> %p\n", this->data);
char *new_data;
new_data = (char *) malloc (this->length);
if (unlikely (!new_data))
return false;
DEBUG_MSG_FUNC (BLOB, this, "dupped successfully -> %p\n", this->data);
memcpy (new_data, this->data, this->length);
this->destroy_user_data ();
this->mode = HB_MEMORY_MODE_WRITABLE;
this->data = new_data;
this->user_data = new_data;
this->destroy = free;
return true;
}
/*
* Mmap
*/
#ifdef HAVE_MMAP
# include <sys/types.h>
# include <sys/stat.h>
# include <fcntl.h>
#endif
#ifdef _WIN32
# include <windows.h>
#else
# ifndef O_BINARY
# define O_BINARY 0
# endif
#endif
#ifndef MAP_NORESERVE
# define MAP_NORESERVE 0
#endif
struct hb_mapped_file_t
{
char *contents;
unsigned long length;
#ifdef _WIN32
HANDLE mapping;
#endif
};
#if (defined(HAVE_MMAP) || defined(_WIN32)) && !defined(HB_NO_MMAP)
static void
_hb_mapped_file_destroy (void *file_)
{
hb_mapped_file_t *file = (hb_mapped_file_t *) file_;
#ifdef HAVE_MMAP
munmap (file->contents, file->length);
#elif defined(_WIN32)
UnmapViewOfFile (file->contents);
CloseHandle (file->mapping);
#else
assert (0); // If we don't have mmap we shouldn't reach here
#endif
free (file);
}
#endif
/**
* hb_blob_create_from_file:
* @file_name: font filename.
*
* Returns: A hb_blob_t pointer with the content of the file
*
* Since: 1.7.7
**/
hb_blob_t *
hb_blob_create_from_file (const char *file_name)
{
/* Adopted from glib's gmappedfile.c with Matthias Clasen and
Allison Lortie permission but changed a lot to suit our need. */
#if defined(HAVE_MMAP) && !defined(HB_NO_MMAP)
hb_mapped_file_t *file = (hb_mapped_file_t *) calloc (1, sizeof (hb_mapped_file_t));
if (unlikely (!file)) return hb_blob_get_empty ();
int fd = open (file_name, O_RDONLY | O_BINARY, 0);
if (unlikely (fd == -1)) goto fail_without_close;
struct stat st;
if (unlikely (fstat (fd, &st) == -1)) goto fail;
file->length = (unsigned long) st.st_size;
file->contents = (char *) mmap (nullptr, file->length, PROT_READ,
MAP_PRIVATE | MAP_NORESERVE, fd, 0);
if (unlikely (file->contents == MAP_FAILED)) goto fail;
close (fd);
return hb_blob_create (file->contents, file->length,
HB_MEMORY_MODE_READONLY_MAY_MAKE_WRITABLE, (void *) file,
(hb_destroy_func_t) _hb_mapped_file_destroy);
fail:
close (fd);
fail_without_close:
free (file);
#elif defined(_WIN32) && !defined(HB_NO_MMAP)
hb_mapped_file_t *file = (hb_mapped_file_t *) calloc (1, sizeof (hb_mapped_file_t));
if (unlikely (!file)) return hb_blob_get_empty ();
HANDLE fd;
unsigned int size = strlen (file_name) + 1;
wchar_t * wchar_file_name = (wchar_t *) malloc (sizeof (wchar_t) * size);
if (unlikely (wchar_file_name == nullptr)) goto fail_without_close;
mbstowcs (wchar_file_name, file_name, size);
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY==WINAPI_FAMILY_PC_APP || WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP)
{
CREATEFILE2_EXTENDED_PARAMETERS ceparams = { 0 };
ceparams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
ceparams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED & 0xFFFF;
ceparams.dwFileFlags = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED & 0xFFF00000;
ceparams.dwSecurityQosFlags = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED & 0x000F0000;
ceparams.lpSecurityAttributes = nullptr;
ceparams.hTemplateFile = nullptr;
fd = CreateFile2 (wchar_file_name, GENERIC_READ, FILE_SHARE_READ,
OPEN_EXISTING, &ceparams);
}
#else
fd = CreateFileW (wchar_file_name, GENERIC_READ, FILE_SHARE_READ, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,
nullptr);
#endif
free (wchar_file_name);
if (unlikely (fd == INVALID_HANDLE_VALUE)) goto fail_without_close;
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY==WINAPI_FAMILY_PC_APP || WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP)
{
LARGE_INTEGER length;
GetFileSizeEx (fd, &length);
file->length = length.LowPart;
file->mapping = CreateFileMappingFromApp (fd, nullptr, PAGE_READONLY, length.QuadPart, nullptr);
}
#else
file->length = (unsigned long) GetFileSize (fd, nullptr);
file->mapping = CreateFileMapping (fd, nullptr, PAGE_READONLY, 0, 0, nullptr);
#endif
if (unlikely (file->mapping == nullptr)) goto fail;
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY==WINAPI_FAMILY_PC_APP || WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP)
file->contents = (char *) MapViewOfFileFromApp (file->mapping, FILE_MAP_READ, 0, 0);
#else
file->contents = (char *) MapViewOfFile (file->mapping, FILE_MAP_READ, 0, 0, 0);
#endif
if (unlikely (file->contents == nullptr)) goto fail;
CloseHandle (fd);
return hb_blob_create (file->contents, file->length,
HB_MEMORY_MODE_READONLY_MAY_MAKE_WRITABLE, (void *) file,
(hb_destroy_func_t) _hb_mapped_file_destroy);
fail:
CloseHandle (fd);
fail_without_close:
free (file);
#endif
/* The following tries to read a file without knowing its size beforehand
It's used as a fallback for systems without mmap or to read from pipes */
unsigned long len = 0, allocated = BUFSIZ * 16;
char *data = (char *) malloc (allocated);
if (unlikely (data == nullptr)) return hb_blob_get_empty ();
FILE *fp = fopen (file_name, "rb");
if (unlikely (fp == nullptr)) goto fread_fail_without_close;
while (!feof (fp))
{
if (allocated - len < BUFSIZ)
{
allocated *= 2;
/* Don't allocate and go more than ~536MB, our mmap reader still
can cover files like that but lets limit our fallback reader */
if (unlikely (allocated > (2 << 28))) goto fread_fail;
char *new_data = (char *) realloc (data, allocated);
if (unlikely (new_data == nullptr)) goto fread_fail;
data = new_data;
}
unsigned long addition = fread (data + len, 1, allocated - len, fp);
int err = ferror (fp);
#ifdef EINTR // armcc doesn't have it
if (unlikely (err == EINTR)) continue;
#endif
if (unlikely (err)) goto fread_fail;
len += addition;
}
return hb_blob_create (data, len, HB_MEMORY_MODE_WRITABLE, data,
(hb_destroy_func_t) free);
fread_fail:
fclose (fp);
fread_fail_without_close:
free (data);
return hb_blob_get_empty ();
}
| [
"7645683+bruvzg@users.noreply.github.com"
] | 7645683+bruvzg@users.noreply.github.com |
de02d369de38e989ebcd021e44a2ffe0f217df49 | 1d703cd163635d4be41703be4fc81fe824ce94eb | /H264OutputPin.cpp | 353053ddc42adbfb01af31ce187c18a0bfda2693 | [
"BSD-3-Clause"
] | permissive | CSIR-RTVC/H264Source | 02259c958e67eec7666abca875b66a09c3b091f8 | 513b3d3dd728748e89a85754807fc0ad1d1b2743 | refs/heads/master | 2020-07-25T11:45:55.420145 | 2019-09-17T20:42:06 | 2019-09-17T20:42:06 | 208,278,620 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,100 | cpp | /** @file
MODULE : H264
FILE NAME : H264OutputPin.cpp
DESCRIPTION : H.264 source filter output pin implementation
LICENSE: Software License Agreement (BSD License)
Copyright (c) 2014, CSIR
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the CSIR 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.
===========================================================================
*/
#include "stdafx.h"
#include "H264OutputPin.h"
#include "H264Source.h"
#include <dvdmedia.h>
#include <wmcodecdsp.h>
H264OutputPin::H264OutputPin(HRESULT *phr, H264SourceFilter* pFilter)
: CSourceStream(NAME("CSIR RTVC H264 Source"), phr, pFilter, L"Out"),
m_pFilter(pFilter),
m_iCurrentFrame(0),
m_rtFrameLength(FPS_30)
{
}
H264OutputPin::~H264OutputPin()
{
}
// GetMediaType: This method tells the downstream pin what types we support.
HRESULT H264OutputPin::GetMediaType(CMediaType *pMediaType)
{
CAutoLock cAutoLock(m_pFilter->pStateLock());
CheckPointer(pMediaType, E_POINTER);
if (!m_pFilter->m_bUseRtvcH264)
{
pMediaType->InitMediaType();
pMediaType->SetType(&MEDIATYPE_Video);
pMediaType->SetSubtype(&MEDIASUBTYPE_H264);
pMediaType->SetFormatType(&FORMAT_VideoInfo2);
// Our H.264 codec only supports baseline, we can't extract
// width and height for other .264 sources. In this case
// the value will still be 0. Hence just set any value.
unsigned uiWidth = (m_pFilter->m_iWidth == 0) ? 352 : m_pFilter->m_iWidth;
unsigned uiHeight = (m_pFilter->m_iHeight == 0) ? 288 : m_pFilter->m_iHeight;
VIDEOINFOHEADER2* pvi2 = (VIDEOINFOHEADER2*)pMediaType->AllocFormatBuffer(sizeof(VIDEOINFOHEADER2));
ZeroMemory(pvi2, sizeof(VIDEOINFOHEADER2));
pvi2->bmiHeader.biBitCount = 24;
pvi2->bmiHeader.biSize = 40;
pvi2->bmiHeader.biPlanes = 1;
pvi2->bmiHeader.biWidth = uiWidth;
pvi2->bmiHeader.biHeight = uiHeight;
pvi2->bmiHeader.biSize = uiWidth * uiHeight * 3;
pvi2->bmiHeader.biSizeImage = DIBSIZE(pvi2->bmiHeader);
pvi2->bmiHeader.biCompression = DWORD('1cva');
//pvi2->AvgTimePerFrame = m_tFrame;
//pvi2->AvgTimePerFrame = 1000000;
const REFERENCE_TIME FPS_25 = UNITS / 25;
pvi2->AvgTimePerFrame = FPS_25;
//SetRect(&pvi2->rcSource, 0, 0, m_cx, m_cy);
SetRect(&pvi2->rcSource, 0, 0, uiWidth, uiHeight);
pvi2->rcTarget = pvi2->rcSource;
pvi2->dwPictAspectRatioX = uiWidth;
pvi2->dwPictAspectRatioY = uiHeight;
}
else
{
// Allocate enough room for the VIDEOINFOHEADER
VIDEOINFOHEADER *pvi = (VIDEOINFOHEADER*)pMediaType->AllocFormatBuffer( sizeof(VIDEOINFOHEADER) );
if (pvi == 0)
return(E_OUTOFMEMORY);
ZeroMemory(pvi, pMediaType->cbFormat);
pvi->AvgTimePerFrame = m_rtFrameLength;
//pvi->dwBitRate = ((int)(m_pFilter->m_iFramesPerSecond * m_pFilter->m_iFrameSize * m_pFilter->m_dBitsPerPixel)) << 3;
pvi->bmiHeader.biBitCount = 12;
pvi->bmiHeader.biCompression = DWORD('1cva');
pvi->bmiHeader.biClrImportant = 0;
pvi->bmiHeader.biClrUsed = 0;
pvi->bmiHeader.biPlanes = 1;
pvi->bmiHeader.biXPelsPerMeter = 0;
pvi->bmiHeader.biYPelsPerMeter = 0;
pvi->bmiHeader.biWidth = m_pFilter->m_iWidth;
pvi->bmiHeader.biHeight = m_pFilter->m_iHeight;
unsigned uiFramesize = m_pFilter->m_iWidth * m_pFilter->m_iHeight * 3;
pvi->bmiHeader.biSizeImage = uiFramesize;
pvi->bmiHeader.biSize = 40;
// Clear source and target rectangles
SetRectEmpty(&(pvi->rcSource)); // we want the whole image area rendered
SetRectEmpty(&(pvi->rcTarget)); // no particular destination rectangle
pMediaType->SetType(&MEDIATYPE_Video);
pMediaType->SetFormatType(&FORMAT_VideoInfo);
pMediaType->SetTemporalCompression(FALSE);
static const GUID MEDIASUBTYPE_H264M =
{ 0xbdf25152, 0x46b, 0x4509, { 0x8e, 0x55, 0x6c, 0x73, 0x83, 0x1c, 0x8d, 0xc4 } };
pMediaType->SetSubtype(&MEDIASUBTYPE_H264M);
pMediaType->SetSampleSize( uiFramesize );
// Add SPS and PPS to the media type
// Store SPS and PPS in media format header
int nCurrentFormatBlockSize = pMediaType->cbFormat;
if (m_pFilter->m_uiSeqParamSetLen + m_pFilter->m_uiPicParamSetLen > 0)
{
// old size + one int to store size of SPS/PPS + SPS/PPS/prepended by start codes
int iAdditionalLength = sizeof(int) + m_pFilter->m_uiSeqParamSetLen + m_pFilter->m_uiPicParamSetLen;
int nNewSize = nCurrentFormatBlockSize + iAdditionalLength;
pMediaType->ReallocFormatBuffer(nNewSize);
BYTE* pFormat = pMediaType->Format();
BYTE* pStartPos = &(pFormat[nCurrentFormatBlockSize]);
// copy SPS
memcpy(pStartPos, m_pFilter->m_pSeqParamSet, m_pFilter->m_uiSeqParamSetLen);
pStartPos += m_pFilter->m_uiSeqParamSetLen;
// copy PPS
memcpy(pStartPos, m_pFilter->m_pPicParamSet, m_pFilter->m_uiPicParamSetLen);
pStartPos += m_pFilter->m_uiPicParamSetLen;
// Copy additional header size
memcpy(pStartPos, &iAdditionalLength, sizeof(int));
}
else
{
// not configured: just copy in size of 0
pMediaType->ReallocFormatBuffer(nCurrentFormatBlockSize + sizeof(int));
BYTE* pFormat = pMediaType->Format();
memset(pFormat + nCurrentFormatBlockSize, 0, sizeof(int));
}
}
return S_OK;
}
HRESULT H264OutputPin::DecideBufferSize(IMemAllocator *pAlloc, ALLOCATOR_PROPERTIES *pRequest)
{
HRESULT hr;
CAutoLock cAutoLock(m_pFilter->pStateLock());
CheckPointer(pAlloc, E_POINTER);
CheckPointer(pRequest, E_POINTER);
// Ensure a minimum number of buffers
if (pRequest->cBuffers == 0)
{
pRequest->cBuffers = 1;
}
unsigned uiWidth = (m_pFilter->m_iWidth == 0) ? 352 : m_pFilter->m_iWidth;
unsigned uiHeight = (m_pFilter->m_iHeight == 0) ? 288 : m_pFilter->m_iHeight;
pRequest->cbBuffer = uiWidth * uiHeight * 3;
ALLOCATOR_PROPERTIES Actual;
hr = pAlloc->SetProperties(pRequest, &Actual);
if (FAILED(hr))
{
return hr;
}
// Is this allocator unsuitable?
if (Actual.cbBuffer < pRequest->cbBuffer)
{
return E_FAIL;
}
return S_OK;
}
// This is where we insert the H264 NAL units into the video stream.
// FillBuffer is called once for every sample in the stream.
HRESULT H264OutputPin::FillBuffer(IMediaSample *pSample)
{
BYTE *pData;
long cbData;
CheckPointer(pSample, E_POINTER);
CAutoLock cAutoLockShared(&m_cSharedState);
if (!m_pFilter->readNalUnit())
return S_FALSE;
// Access the sample's data buffer
pSample->GetPointer(&pData);
cbData = pSample->GetSize();
// Check that we're still using video
ASSERT(m_mt.formattype == FORMAT_VideoInfo2 || m_mt.formattype == FORMAT_VideoInfo);
VIDEOINFOHEADER *pVih = (VIDEOINFOHEADER*)m_mt.pbFormat;
ASSERT(m_pFilter->m_uiCurrentNalUnitSize > 0);
memcpy( pData, m_pFilter->m_pBuffer, m_pFilter->m_uiCurrentNalUnitSize );
#if 0
// BUG: we need to parse the NAL units to find out if we have to increment the timestamp
if (!m_pFilter->isParameterSet(m_pFilter->m_pBuffer[m_pFilter->m_uiCurrentStartCodeSize]))
{
// TODO: non VLC NAL units should not increment the timestamp
REFERENCE_TIME rtStart = m_iCurrentFrame * m_rtFrameLength;
REFERENCE_TIME rtStop = rtStart + m_rtFrameLength;
pSample->SetTime( &rtStart, &rtStop );
++m_iCurrentFrame;
}
else
{
pSample->SetTime( NULL, NULL );
}
#else
// setting timestamps to NULL until we can parse the NAL units to check the type
pSample->SetTime( NULL, NULL );
#endif
if (m_pFilter->isIdrFrame(m_pFilter->m_pBuffer[4]))
{
pSample->SetSyncPoint(TRUE);
}
else
{
pSample->SetSyncPoint(false);
}
pSample->SetActualDataLength(m_pFilter->m_uiCurrentNalUnitSize);
return S_OK;
}
| [
"rglobisch@csir.co.za"
] | rglobisch@csir.co.za |
53463d7138d04486f35eca1cba7f4ddb9b51f5da | 550cc359cf65118b288064ef7b8d2c30c79194e7 | /src/text.cpp | 72ff860846e735cd982836b086390860077764cb | [
"Apache-2.0"
] | permissive | kraj/egt | c86f46159a41451f8b7fbd0a3a3aae67af4edd06 | 7065fd97e8bc61b0b0555bd48461ac9b2160ac7a | refs/heads/master | 2022-05-20T09:35:13.565249 | 2019-12-13T16:46:39 | 2019-12-13T16:54:18 | 226,118,135 | 0 | 0 | Apache-2.0 | 2019-12-05T14:16:05 | 2019-12-05T14:16:04 | null | UTF-8 | C++ | false | false | 10,855 | cpp | /*
* Copyright (C) 2018 Microchip Technology Inc. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "detail/utf8text.h"
#include "egt/canvas.h"
#include "egt/detail/alignment.h"
#include "egt/detail/layout.h"
#include "egt/detail/string.h"
#include "egt/frame.h"
#include "egt/input.h"
#include "egt/painter.h"
#include "egt/text.h"
#include "egt/virtualkeyboard.h"
using namespace egt::detail;
namespace egt
{
inline namespace v1
{
const alignmask TextBox::default_align = alignmask::expand;
TextBox::TextBox(const std::string& text,
alignmask text_align,
const flags_type& flags) noexcept
: TextBox(text, {}, text_align, flags)
{}
TextBox::TextBox(const std::string& text,
const Rect& rect,
alignmask text_align,
const flags_type& flags) noexcept
: TextWidget(text, rect, text_align),
m_timer(std::chrono::seconds(1)),
m_text_flags(flags)
{
set_name("TextBox" + std::to_string(m_widgetid));
set_border(theme().default_border());
set_boxtype(Theme::boxtype::fill_rounded);
set_padding(5);
m_timer.on_timeout([this]() { cursor_timeout(); });
cursor_set_end();
}
TextBox::TextBox(Frame& parent,
const std::string& text,
alignmask text_align,
const flags_type& flags) noexcept
: TextBox(text, Rect(), text_align, flags)
{
parent.add(*this);
}
TextBox::TextBox(Frame& parent,
const std::string& text,
const Rect& rect,
alignmask text_align,
const flags_type& flags) noexcept
: TextBox(text, rect, text_align, flags)
{
parent.add(*this);
}
void TextBox::handle(Event& event)
{
Widget::handle(event);
switch (event.id())
{
case eventid::on_gain_focus:
show_cursor();
break;
case eventid::on_lost_focus:
hide_cursor();
if (!text_flags().is_set(flag::no_virt_keyboard))
if (popup_virtual_keyboard())
popup_virtual_keyboard()->hide();
break;
case eventid::pointer_click:
keyboard_focus(this);
if (!text_flags().is_set(flag::no_virt_keyboard))
if (popup_virtual_keyboard())
popup_virtual_keyboard()->show();
break;
case eventid::keyboard_down:
handle_key(event.key());
event.stop();
default:
break;
}
}
void TextBox::handle_key(const Key& key)
{
switch (key.keycode)
{
case EKEY_ESCAPE:
// do nothing
break;
case EKEY_BACKSPACE:
{
if (cursor())
{
set_selection(cursor() - 1, 1);
delete_selection();
}
break;
}
case EKEY_DELETE:
{
set_selection(cursor(), 1);
delete_selection();
break;
}
case EKEY_ENTER:
{
if (text_flags().is_set(flag::multiline))
insert("\n");
break;
}
case EKEY_LEFT:
{
cursor_backward();
break;
}
case EKEY_RIGHT:
{
cursor_forward();
break;
}
case EKEY_UP:
{
if (text_flags().is_set(flag::multiline))
{
// TODO
}
break;
}
case EKEY_DOWN:
{
if (text_flags().is_set(flag::multiline))
{
// TODO
}
break;
}
case EKEY_END:
{
// TODO
break;
}
case EKEY_HOME:
{
// TODO
break;
}
default:
{
if (key.unicode)
{
std::string tmp;
utf8::append(key.unicode, std::back_inserter(tmp));
insert(tmp);
}
break;
}
}
}
auto CURSOR_Y_OFFSET = 2.;
void TextBox::draw(Painter& painter, const Rect&)
{
// box
draw_box(painter, Palette::ColorId::bg, Palette::ColorId::border);
// function to draw the cursor
auto draw_cursor = [&](const Point & offset, size_t height)
{
if (focus() && m_cursor_state)
{
painter.set(color(Palette::ColorId::cursor).color());
painter.set_line_width(2);
painter.draw(offset + Point(0, -CURSOR_Y_OFFSET),
offset + Point(0, height) + Point(0, CURSOR_Y_OFFSET));
painter.stroke();
}
};
detail::draw_text(painter,
content_area(),
m_text,
font(),
text_flags(),
text_align(),
justification::start,
color(Palette::ColorId::text).color(),
draw_cursor,
m_cursor_pos,
color(Palette::ColorId::text_highlight).color(),
m_select_start,
m_select_len);
}
void TextBox::set_text(const std::string& str)
{
clear_selection();
clear();
insert(str);
}
void TextBox::clear()
{
clear_selection();
cursor_set_begin();
TextWidget::clear();
}
void TextBox::set_max_length(size_t len)
{
if (detail::change_if_diff<>(m_max_len, len))
{
if (m_max_len)
{
auto len = utf8len(m_text);
if (len > m_max_len)
{
auto i = m_text.begin();
utf8::advance(i, m_max_len, m_text.end());
m_text.erase(i, m_text.end());
}
}
damage();
}
}
size_t TextBox::append(const std::string& str)
{
cursor_set_end();
return insert(str);
}
size_t TextBox::width_to_len(const std::string& text) const
{
auto b = content_area();
Canvas canvas(Size(100, 100));
auto cr = canvas.context();
Painter painter(cr);
painter.set(font());
size_t len = 0;
float total = 0;
for (utf8_const_iterator ch(text.begin(), m_text.begin(), m_text.end());
ch != utf8_const_iterator(text.end(), m_text.begin(), m_text.end()); ++ch)
{
auto txt = utf8_char_to_string(ch.base(), m_text.cend());
cairo_text_extents_t te;
cairo_text_extents(cr.get(), txt.c_str(), &te);
if (total + te.x_advance > b.width())
{
return len;
}
total += te.x_advance;
len++;
}
return len;
}
size_t TextBox::insert(const std::string& str)
{
if (str.empty())
return 0;
auto current_len = utf8len(m_text);
auto len = utf8len(str);
if (m_max_len)
{
if (current_len + len > m_max_len)
len = m_max_len - current_len;
}
if (!text_flags().is_set(flag::multiline) &&
text_flags().is_set(flag::fit_to_width))
{
/*
* Have to go through the motions and build the expected string at this
* point to see what will fit.
*/
// insert at cursor position
auto text = m_text;
auto i = text.begin();
utf8::advance(i, m_cursor_pos, text.end());
auto end = str.begin();
utf8::advance(end, len, str.end());
text.insert(i, str.begin(), end);
auto maxlen = width_to_len(text);
if (current_len + len > maxlen)
len = maxlen - current_len;
}
if (m_validate_input)
if (!validate_input(str))
return 0;
if (len)
{
// insert at cursor position
auto i = m_text.begin();
utf8::advance(i, m_cursor_pos, m_text.end());
auto end = str.begin();
utf8::advance(end, len, str.end());
m_text.insert(i, str.begin(), end);
cursor_forward(len);
clear_selection();
invoke_handlers(eventid::property_changed);
damage();
}
return len;
}
size_t TextBox::cursor() const
{
return m_cursor_pos;
}
void TextBox::cursor_set_begin()
{
cursor_set(0);
}
void TextBox::cursor_set_end()
{
// one past end
cursor_set(utf8len(m_text));
}
void TextBox::cursor_forward(size_t count)
{
cursor_set(m_cursor_pos + count);
}
void TextBox::cursor_backward(size_t count)
{
if (m_cursor_pos > count)
cursor_set(m_cursor_pos - count);
else
cursor_set(0);
}
void TextBox::cursor_set(size_t pos)
{
if (pos > utf8len(m_text))
pos = utf8len(m_text);
if (m_cursor_pos != pos)
{
m_cursor_pos = pos;
damage();
}
show_cursor();
}
void TextBox::set_selection_all()
{
set_selection(0, utf8len(m_text));
}
void TextBox::set_selection(size_t pos, size_t length)
{
if (pos > utf8len(m_text))
pos = utf8len(m_text);
auto i = m_text.begin();
utf8::advance(i, pos, m_text.end());
size_t d = utf8::distance(i, m_text.end());
if (length > d)
length = d;
if (pos != m_select_start || length != m_select_len)
{
m_select_start = pos;
m_select_len = length;
damage();
}
}
void TextBox::clear_selection()
{
if (m_select_len)
{
m_select_len = 0;
damage();
}
}
std::string TextBox::selected_text() const
{
if (m_select_len)
{
auto i = m_text.begin();
utf8::advance(i, m_select_start, m_text.end());
auto l = i;
utf8::advance(l, m_select_len, m_text.end());
return m_text.substr(std::distance(m_text.begin(), i),
std::distance(i, l));
}
return std::string();
}
void TextBox::delete_selection()
{
if (m_select_len)
{
auto i = m_text.begin();
utf8::advance(i, m_select_start, m_text.end());
auto l = i;
utf8::advance(l, m_select_len, m_text.end());
size_t p = utf8::distance(m_text.begin(), i);
m_text.erase(i, l);
cursor_set(p);
clear_selection();
invoke_handlers(eventid::property_changed);
damage();
}
}
void TextBox::set_input_validation_enabled(bool enabled)
{
m_validate_input = enabled;
}
void TextBox::add_validator_function(validator_callback_t callback)
{
m_validator_callbacks.emplace_back(std::move(callback));
}
bool TextBox::validate_input(const std::string& str)
{
for (auto& callback : m_validator_callbacks)
{
auto valid = callback(str);
if (!valid)
return false;
}
return true;
}
void TextBox::cursor_timeout()
{
m_cursor_state = !m_cursor_state;
damage();
}
void TextBox::show_cursor()
{
m_cursor_state = true;
m_timer.start();
damage();
}
void TextBox::hide_cursor()
{
m_timer.cancel();
m_cursor_state = false;
damage();
}
Size TextBox::min_size_hint() const
{
auto text = m_text;
if (text.empty())
text = "Hello World";
auto s = text_size(text);
s += Widget::min_size_hint() + Size(0, CURSOR_Y_OFFSET * 2.);
return s;
}
}
}
| [
"joshua.henderson@microchip.com"
] | joshua.henderson@microchip.com |
359d29178955d7556e111dd84b6ddd9b926eb576 | 0da7fec56f63012180d848b1e72bada9f6984ef3 | /PocketDjVu_root/libdjvu/DjVuNavDir.h | 18a795598c70cde039cfa0de14e362198280e5a1 | [] | no_license | UIKit0/pocketdjvu | a34fb2b8ac724d25fab7a0298942db1755098b25 | 4c0c761e6a3d3628440fb4fb0a9c54e5594807d9 | refs/heads/master | 2021-01-20T12:01:16.947853 | 2010-05-03T12:29:44 | 2010-05-03T12:29:44 | 32,293,688 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,676 | h | //C- -*- C++ -*-
//C- -------------------------------------------------------------------
//C- DjVuLibre-3.5
//C- Copyright (c) 2002 Leon Bottou and Yann Le Cun.
//C- Copyright (c) 2001 AT&T
//C-
//C- This software is subject to, and may be distributed under, the
//C- GNU General Public License, Version 2. The license should have
//C- accompanied the software or you may obtain a copy of the license
//C- from the Free Software Foundation at http://www.fsf.org .
//C-
//C- This program is distributed in the hope that it will be useful,
//C- but WITHOUT ANY WARRANTY; without even the implied warranty of
//C- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//C- GNU General Public License for more details.
//C-
//C- DjVuLibre-3.5 is derived from the DjVu(r) Reference Library
//C- distributed by Lizardtech Software. On July 19th 2002, Lizardtech
//C- Software authorized us to replace the original DjVu(r) Reference
//C- Library notice by the following text (see doc/lizard2002.djvu):
//C-
//C- ------------------------------------------------------------------
//C- | DjVu (r) Reference Library (v. 3.5)
//C- | Copyright (c) 1999-2001 LizardTech, Inc. All Rights Reserved.
//C- | The DjVu Reference Library is protected by U.S. Pat. No.
//C- | 6,058,214 and patents pending.
//C- |
//C- | This software is subject to, and may be distributed under, the
//C- | GNU General Public License, Version 2. The license should have
//C- | accompanied the software or you may obtain a copy of the license
//C- | from the Free Software Foundation at http://www.fsf.org .
//C- |
//C- | The computer code originally released by LizardTech under this
//C- | license and unmodified by other parties is deemed "the LIZARDTECH
//C- | ORIGINAL CODE." Subject to any third party intellectual property
//C- | claims, LizardTech grants recipient a worldwide, royalty-free,
//C- | non-exclusive license to make, use, sell, or otherwise dispose of
//C- | the LIZARDTECH ORIGINAL CODE or of programs derived from the
//C- | LIZARDTECH ORIGINAL CODE in compliance with the terms of the GNU
//C- | General Public License. This grant only confers the right to
//C- | infringe patent claims underlying the LIZARDTECH ORIGINAL CODE to
//C- | the extent such infringement is reasonably necessary to enable
//C- | recipient to make, have made, practice, sell, or otherwise dispose
//C- | of the LIZARDTECH ORIGINAL CODE (or portions thereof) and not to
//C- | any greater extent that may be necessary to utilize further
//C- | modifications or combinations.
//C- |
//C- | The LIZARDTECH ORIGINAL CODE is provided "AS IS" WITHOUT WARRANTY
//C- | OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
//C- | TO ANY WARRANTY OF NON-INFRINGEMENT, OR ANY IMPLIED WARRANTY OF
//C- | MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
//C- +------------------------------------------------------------------
//
// $Id: DjVuNavDir.h,v 1.8 2003/11/07 22:08:21 leonb Exp $
// $Name: release_3_5_17 $
#ifndef _DJVUNAVDIR_H
#define _DJVUNAVDIR_H
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#if NEED_GNUG_PRAGMAS
# pragma interface
#endif
#include "GString.h"
#include "GThreads.h"
#include "GURL.h"
#ifdef HAVE_NAMESPACES
namespace DJVU {
# ifdef NOT_DEFINED // Just to fool emacs c++ mode
}
#endif
#endif
class ByteStream;
/** @name DjVuNavDir.h
Files #"DjVuNavDir.h"# and #"DjVuNavDir.cpp"# contain implementation of the
multipage DjVu navigation directory. This directory lists all the pages,
that a given document is composed of. The navigation (switching from page
to page in the plugin) is not possible before this directory is decoded.
Refer to the \Ref{DjVuNavDir} class description for greater details.
@memo DjVu Navigation Directory
@author Andrei Erofeev <eaf@geocities.com>
@version #$Id: DjVuNavDir.h,v 1.8 2003/11/07 22:08:21 leonb Exp $#
*/
//@{
//*****************************************************************************
//********************* Note: this class is thread-safe ***********************
//*****************************************************************************
/** DjVu Navigation Directory.
This class implements the {\em navigation directory} of a multipage
DjVu document - basically a list of pages that this document is composed
of. We would like to emphasize, that this is the list of namely
{\bf pages}, not {\bf files}. Any page may include any
number of additional files. When you've got an all-in-one-file multipage
DjVu document (DjVm archive) you may get the files list from \Ref{DjVmDir0}
class.
The \Ref{DjVuNavDir} class can decode and encode the navigation directory
from {\bf NDIR} IFF chunk. It's normally created by the library during
decoding procedure and can be accessed like any other component of
the \Ref{DjVuImage} being decoded.
In a typical multipage DjVu document the navigation directory is stored
in a separate IFF file containing only one chunk: {\bf NDIR} chunk.
This file should be included (by means of the {\bf INCL} chunk) into
every page of the document to enable the navigation. */
class DjVuNavDir : public GPEnabled
{
private:
GCriticalSection lock;
GURL baseURL;
GArray<GUTF8String> page2name;
GMap<GUTF8String, int> name2page;
GMap<GURL, int> url2page;
protected:
DjVuNavDir(const GURL &dir_url);
DjVuNavDir(ByteStream & str, const GURL &dir_url);
public:
int get_memory_usage(void) const { return 1024; };
/** Creates a #DjVuNavDir# object. #dir_url# is the URL of the file
containing the directory source data. It will be used later
in translation by functions like \Ref{url_to_page}() and
\Ref{page_to_url}() */
static GP<DjVuNavDir> create(const GURL &dir_url)
{return new DjVuNavDir(dir_url);}
/** Creates #DjVuNavDir# object by decoding its contents from
the stream. #dir_url# is the URL of the file containing the
directory source data. */
static GP<DjVuNavDir> create(ByteStream & str, const GURL &dir_url)
{ return new DjVuNavDir(str,dir_url); }
virtual ~DjVuNavDir(void) {};
/// Decodes the directory contents from the given \Ref{ByteStream}
void decode(ByteStream & str);
/// Encodes the directory contents into the given \Ref{ByteStream}
void encode(ByteStream & str);
/** Inserts a new page at position #where# pointing to a file
with name #name#.
@param where The position where the page should be inserted.
#-1# means to append.
@param name The name of the file corresponding to this page.
The name may not contain slashes. The file may include
other files. */
void insert_page(int where, const char * name);
/// Deletes page with number #page_num# from the directory.
void delete_page(int page_num);
/// Returns the number of pages in the directory.
int get_pages_num(void) const;
/** Converts the #url# to page number. Returns #-1# if the #url#
does not correspond to anything in the directory. */
int url_to_page(const GURL & url) const;
/** Converts file name #name# to page number. Returns #-1# if file
with given name cannot be found. */
int name_to_page(const char * name) const;
/** Converts given #page# to URL. Throws an exception if page number
is invalid. */
GURL page_to_url(int page) const;
/** Converts given #page# to URL. Throws an exception if page number
is invalid. */
GUTF8String page_to_name(int page) const;
};
//@}
#ifdef HAVE_NAMESPACES
}
# ifndef NOT_USING_DJVU_NAMESPACE
using namespace DJVU;
# endif
#endif
#endif
| [
"Igor.Solovyov@84cd470b-3125-0410-acc3-039690e87181"
] | Igor.Solovyov@84cd470b-3125-0410-acc3-039690e87181 |
69e97a728a4f2078a4b55ba0cdaf50e21a31c8ac | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE762_Mismatched_Memory_Management_Routines/s07/CWE762_Mismatched_Memory_Management_Routines__new_free_wchar_t_84a.cpp | aa6240e15ed92a553c04d5d189046d38d277e433 | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 2,851 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__new_free_wchar_t_84a.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_free.label.xml
Template File: sources-sinks-84a.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: Allocate data using new
* GoodSource: Allocate data using malloc()
* Sinks:
* GoodSink: Deallocate data using delete
* BadSink : Deallocate data using free()
* Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
*
* */
#include "std_testcase.h"
#include "CWE762_Mismatched_Memory_Management_Routines__new_free_wchar_t_84.h"
namespace CWE762_Mismatched_Memory_Management_Routines__new_free_wchar_t_84
{
#ifndef OMITBAD
void bad()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
CWE762_Mismatched_Memory_Management_Routines__new_free_wchar_t_84_bad * badObject = new CWE762_Mismatched_Memory_Management_Routines__new_free_wchar_t_84_bad(data);
delete badObject;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
CWE762_Mismatched_Memory_Management_Routines__new_free_wchar_t_84_goodG2B * goodG2BObject = new CWE762_Mismatched_Memory_Management_Routines__new_free_wchar_t_84_goodG2B(data);
delete goodG2BObject;
}
/* goodG2B uses the BadSource with the GoodSink */
static void goodB2G()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
CWE762_Mismatched_Memory_Management_Routines__new_free_wchar_t_84_goodB2G * goodB2GObject = new CWE762_Mismatched_Memory_Management_Routines__new_free_wchar_t_84_goodB2G(data);
delete goodB2GObject;
}
void good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE762_Mismatched_Memory_Management_Routines__new_free_wchar_t_84; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"yzhang0701@gmail.com"
] | yzhang0701@gmail.com |
80f35291cae5b3546636912ba2c645e03a4df39a | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/PhysicsAnalysis/TauID/TauHistUtils/src/BDTinputPlots.cxx | 5beccf0dd1a8df3e13d25cd765beac26694b8a92 | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,832 | cxx | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
#include "TauHistUtils/BDTinputPlots.h"
namespace Tau{
BDTinputPlots::BDTinputPlots(PlotBase* pParent, std::string sDir, std::string sTauJetContainerName):
PlotBase(pParent, sDir),
m_id_BDTJetScore(nullptr),
m_id_BDTEleScore(nullptr),
m_pt_eleBDTloose(nullptr),
m_pt_eleBDTmed(nullptr),
m_pt_eleBDTtight(nullptr),
m_pt_jetBDTloose(nullptr),
m_pt_jetBDTmed(nullptr),
m_pt_jetBDTtight(nullptr),
m_sTauJetContainerName(sTauJetContainerName)
{
}
BDTinputPlots::~BDTinputPlots()
{
}
void BDTinputPlots::initializePlots(){
/*+++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++BDT OUTPUT+++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++*/
m_id_BDTJetScore = Book1D("id_BDTJetScore",m_sTauJetContainerName + " BDTJetScore ; BDTJetScore; # Tau",10,-1.01,1.01);
m_id_BDTEleScore = Book1D("id_BDTEleScore",m_sTauJetContainerName + " BDTEleScore ; BDTEleScore; # Tau",10,0.,1.01);
m_pt_eleBDTloose = Book1D("Pt_eleBDTloose",m_sTauJetContainerName + " Tau pt; pt; # Taus",20,0.,300.);
m_pt_eleBDTmed = Book1D("Pt_eleBDTmed",m_sTauJetContainerName + " Tau pt; pt; # Taus",20,0.,300.);
m_pt_eleBDTtight = Book1D("Pt_eleBDTtight",m_sTauJetContainerName + " Tau pt; pt; # Taus",20,0.,300.);
m_pt_jetBDTloose = Book1D("Pt_jetBDTloose",m_sTauJetContainerName + " Tau pt; pt; # Taus",20,0.,300.);
m_pt_jetBDTmed = Book1D("Pt_jetBDTmed",m_sTauJetContainerName + " Tau pt; pt; # Taus",20,0.,300.);
m_pt_jetBDTtight = Book1D("Pt_jetBDTtigth",m_sTauJetContainerName + " Tau pt; pt; # Taus",20,0.,300.);
}
void BDTinputPlots::fill(const xAOD::TauJet& thisTau) {
/*+++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++BDT OUTPUT+++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++*/
if( thisTau.hasDiscriminant(xAOD::TauJetParameters::BDTJetScore) )m_id_BDTJetScore->Fill(thisTau.discriminant(xAOD::TauJetParameters::BDTJetScore));
if( thisTau.hasDiscriminant(xAOD::TauJetParameters::BDTEleScore) )m_id_BDTEleScore->Fill(thisTau.discriminant(xAOD::TauJetParameters::BDTEleScore));
if(thisTau.isTau(xAOD::TauJetParameters::JetBDTSigLoose)) m_pt_eleBDTloose->Fill( thisTau.pt()/1000,1);
if(thisTau.isTau(xAOD::TauJetParameters::JetBDTSigMedium)) m_pt_eleBDTmed ->Fill( thisTau.pt()/1000,1);
if(thisTau.isTau(xAOD::TauJetParameters::JetBDTSigTight)) m_pt_eleBDTtight->Fill( thisTau.pt()/1000,1);
if(thisTau.isTau(xAOD::TauJetParameters::EleBDTLoose)) m_pt_jetBDTloose->Fill( thisTau.pt()/1000,1);
if(thisTau.isTau(xAOD::TauJetParameters::EleBDTMedium)) m_pt_jetBDTmed ->Fill( thisTau.pt()/1000,1);
if(thisTau.isTau(xAOD::TauJetParameters::EleBDTTight)) m_pt_jetBDTtight->Fill( thisTau.pt()/1000,1);
}
}
| [
"rushioda@lxplus754.cern.ch"
] | rushioda@lxplus754.cern.ch |
66852a4b4594178f5c5090956dbe1948c7c53e0f | 739c0df7e6a024b5243faabae737f02f83087269 | /Uebungsblatt_9/vorlagen_matrix_/matrix_double.cc | 5dcab1415cf83b6292ffabe1384fdd3f849f437c | [] | no_license | donald74/Wissenschaftlisches_Rechnen_SS2019 | 7b8ccb219e9543b9b93a6fb3727f346cc0fc28c1 | 04a3f95743e59c35897e03d82959987caec41fa9 | refs/heads/master | 2022-03-20T09:58:10.530424 | 2019-11-13T07:21:26 | 2019-11-13T07:21:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,982 | cc | #include "matrix_double.h"
#include <iomanip>
#include <iostream>
#include <stdexcept>
// Set number of matrix rows and columns and
// initialize matrix elements with a given double value
// template <class T>
// void MatrixClass<T>::resize(size_t numRows, size_t numCols, const T &value)
// {
// if ((numRows+numCols>0) && (numRows*numCols==0)) {
// numRows=0;
// numCols=0;
// }
// a_.release();
// numRows_=numRows;
// numCols_=numCols;
// a_=std::unique_ptr<T[]>(new T[numRows_*numCols_]);
// for (size_t i=0;i<numRows_*numCols_;++i)
// a_[i]=value;
// }
// // Access matrix element at position (i,j)
// template <class T>
// T &MatrixClass<T>::operator()(size_t i, size_t j)
// {
// if ((i<0)||(i>=numRows_)) {
// std::string err;
// err.append("Illegal row index ");
// err.append(std::to_string(i));
// err.append(" valid range is (0: ");
// err.append(std::to_string(numRows_ - 1));
// err.append(")");
// throw std::out_of_range(err);
// exit(EXIT_FAILURE);
// }
// if ((j<0)||(j>=numCols_))
// {
// std::string err;
// err.append("Illegal column index ");
// err.append(std::to_string(j));
// err.append(" valid range is (0: ");
// err.append(std::to_string(numCols_ - 1));
// err.append(")");
// throw std::out_of_range(err);
// exit(EXIT_FAILURE);
// }
// return a_[i*numCols_+j];
// }
// // Access matrix element at position (i,j)
// template <class T>
// T MatrixClass<T>::operator()(size_t i, size_t j) const
// {
// if ((i<0)||(i>=numRows_))
// {
// std::string err;
// err.append("Illegal row index ");
// err.append(std::to_string(i));
// err.append(" valid range is (0: ");
// err.append(std::to_string(numRows_ - 1));
// err.append(")");
// throw std::out_of_range(err);
// exit(EXIT_FAILURE);
// }
// if ((j<0)||(j>=numCols_))
// {
// std::string err;
// err.append("Illegal column index ");
// err.append(std::to_string(j));
// err.append(" valid range is (0: ");
// err.append(std::to_string(numCols_ - 1));
// err.append(")");
// throw std::out_of_range(err);
// exit(EXIT_FAILURE);
// }
// return a_[i*numCols_+j];
// }
// // Output matrix content
// template <class T>
// void MatrixClass<T>::print() const
// {
// std::cout << "(" << numRows_ << "x";
// std::cout << numCols_ << ") matrix:\n";
// for (size_t i=0;i<numRows_;++i) {
// std::cout << std::setprecision(3);
// for (size_t j=0;j<numCols_;++j)
// std::cout << std::setw(5) << a_[i*numCols_+j] << " ";
// std::cout << "\n";
// }
// std::cout << "\n";
// }
// Arithmetic functions
// Multiplication by value x
template <class T>
MatrixClass<T> &MatrixClass<T>::operator*=(T x)
{
for (size_t i=0;i<numRows_*numCols_;++i)
a_[i]*=x;
return *this;
}
// Addition
template <class T>
MatrixClass<T> &MatrixClass<T>::operator+=(const MatrixClass<T> &x)
{
if ((x.numRows_!=numRows_)||(x.numCols_!=numCols_))
{
std::string err;
err.append("Dimensions of matrix a (");
err.append(std::to_string(numRows_));
err.append(" x ");
err.append(std::to_string(numCols_));
err.append(") and matrix x (");
err.append(std::to_string(numRows_));
err.append(" x ");
err.append(std::to_string(numCols_));
err.append(") do not match!");
throw std::out_of_range(err);
exit(EXIT_FAILURE);
}
for (size_t i=0;i<numRows_*numCols_;++i)
a_[i]+=x.a_[i];
return *this;
}
// More arithmetic functions
template <class T>
MatrixClass<T> operator*(const MatrixClass<T> &a, T x)
{
MatrixClass<T> temp(a);
temp *= x;
return temp;
}
template <class T>
MatrixClass<T> operator*(T x, const MatrixClass<T> &a)
{
MatrixClass<T> temp(a);
temp *= x;
return temp;
}
// Concatenate
template <class T>
MatrixClass<T> operator+(const MatrixClass<T> &a, const MatrixClass<T> &b)
{
MatrixClass<T> temp(a);
temp += b;
return temp;
}
| [
"kamdoumloich@yahoo.fr"
] | kamdoumloich@yahoo.fr |
f8d68c6832378590ec3ce913e114b4bd8140f777 | 829272424f78f81b96baf48e6609e369cea576b8 | /File System Shell - Assignment 3/AVLTree.h | d7c01a584d53a798bb603fe3815b34007242d5c0 | [] | no_license | amerfarooq/Data-Structure---FAST | 6aff36df52872cda10bf977661d4181a826b73a8 | 8451d5e7bef3d9dccb963aabb691b8713d8d6089 | refs/heads/master | 2021-08-22T06:31:05.808098 | 2017-11-29T14:34:05 | 2017-11-29T14:34:05 | 112,482,336 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,197 | h | #pragma once
#include "NAryTree.h"
using namespace std;
struct AVLNode {
AVLNode* right;
AVLNode* left;
int height;
char key;
vector<pair<string, string>> files; // pair<fileName, filePath>
AVLNode(char key = '\0', string fileName = "", string filePath = "")
: right(nullptr),
left(nullptr),
height(0),
key(key)
{
insertFile(fileName, filePath);
}
void insertFile(string fileName, string filePath) {
files.push_back(make_pair(fileName, filePath));
}
const vector<string> getPaths(const string fileName) const {
vector<string> possiblePaths;
for (const auto p : files) {
if (p.first == fileName) {
possiblePaths.push_back(p.second);
}
}
return possiblePaths;
}
bool replacePath(const string originalPath, const string newPath) {
for (auto& p : files) {
if (p.second == originalPath) {
p.second = newPath;
return true;
}
}
return false;
}
void deletePath(const string originalPath, const string fileName) {
remove(files.begin(), files.end(), make_pair(fileName, originalPath));
}
void displayPaths() const {
for (const auto& p : files) {
cout << p.second << endl;
}
}
} ;
class AVLTree {
public:
pair<vector<string>, bool> searchFile(string fileName) {
char searchKey = tolower(fileName.at(0));
AVLNode* foundNode = searchAVLNode(searchKey);
if (foundNode) {
vector<string> paths = foundNode->getPaths(fileName);
if (paths.size() == 0) {
return make_pair(vector<string>(), false);
}
return make_pair(paths, true);
}
else {
return make_pair(vector<string>(), false);
}
}
void insert(string fileName, string filePath) {
char searchKey = tolower(fileName.at(0));
AVLNode* foundNode = searchAVLNode(searchKey);
if (!foundNode) {
root = insert(searchKey, root, fileName, filePath);
}
else {
foundNode->insertFile(fileName, filePath);
}
}
void inOrder() {
inOrder(root);
}
void preOrder() {
preOrder(root);
}
void displayPaths() {
displayPaths(root);
}
void replacePaths(const string originalPath, const string newPath, const string fileName) {
AVLNode* pathNode = searchAVLNode(fileName.at(0));
if (!pathNode->replacePath(originalPath, newPath))
throw("Path could not be replaced!");
}
void removePath(const string originalPath, const string fileName) {
AVLNode* pathNode = searchAVLNode(fileName.at(0));
pathNode->deletePath(originalPath, fileName);
}
~AVLTree() {
makeDeletion(root);
}
private:
AVLNode* root = nullptr;
void remove(char key) {
root = remove(root, key);
}
AVLNode* searchAVLNode(const char key) {
AVLNode* iterator = root;
while (iterator) {
if (key < iterator->key) {
iterator = iterator->left;
}
else if (key > iterator->key) {
iterator = iterator->right;
}
else {
return iterator;
}
}
return nullptr;
}
AVLNode* leftRotation(AVLNode*& node) {
AVLNode* newPosition = node->right;
node->right = newPosition->left;
newPosition->left = node;
node->height = max(getHeight(node->left), getHeight(node->right)) + 1;
newPosition->height = max(getHeight(newPosition->right), node->height) + 1;
return newPosition;
}
AVLNode* rightRotation(AVLNode*& node) {
AVLNode* newPosition = node->left;
node->left = newPosition->right;
newPosition->right = node;
node->height = max(getHeight(node->left), getHeight(node->right)) + 1;
newPosition->height = max(getHeight(newPosition->left), node->height) + 1;
return newPosition;
}
AVLNode* leftRightRotation(AVLNode*& node) {
node->right = rightRotation(node->right);
return leftRotation(node);
}
AVLNode* rightLeftRotation(AVLNode*& node) {
node->left = leftRotation(node->left);
return rightRotation(node);
}
AVLNode* insert(char key, AVLNode*& node, string fileName, string filePath) {
if (node == nullptr) {
node = new AVLNode(key, fileName, filePath);
}
else if (key < node->key) {
node->left = insert(key, node->left, fileName, filePath);
if (getHeight(node->left) - getHeight(node->right) == 2) {
if (key < node->left->key)
node = rightRotation(node);
else
node = rightLeftRotation(node);
}
}
else if (key > node->key) {
node->right = insert(key, node->right, fileName, filePath);
if (getHeight(node->right) - getHeight(node->left) == 2) {
if (key > node->right->key)
node = leftRotation(node);
else
node = leftRightRotation(node);
}
}
node->height = max(getHeight(node->left), getHeight(node->right)) + 1;
return node;
}
AVLNode* remove(AVLNode* node, char key)
{
if (!node) return node;
if (key < node->key)
node->left = remove(node->left, key);
else if (key > node->key)
node->right = remove(node->right, key);
else {
if ((!node->left ) || (!node->right)) {
AVLNode* temp = node->left ? node->left : node->right;
if (!temp){
temp = node;
node = nullptr;
}
else
*node = *temp;
delete(temp);
}
else {
AVLNode* temp = findMin(node->right);
node->key = temp->key;
node->right = remove(node->right, temp->key);
}
}
if (!node) return node;
node->height = 1 + max(getHeight(node->left), getHeight(node->right));
int balance = getBalance(node);
if (balance > 1 && getBalance(node->left) >= 0) {
return rightRotation(node);
}
if (balance > 1 && getBalance(node->left) < 0) {
node->left = leftRotation(node->left);
return rightRotation(node);
}
if (balance < -1 && getBalance(node->right) <= 0) {
return leftRotation(node);
}
if (balance < -1 && getBalance(node->right) > 0) {
node->right = rightRotation(node->right);
return leftRotation(node);
}
return node;
}
AVLNode* findMin(AVLNode* node)
{
if (!node) return nullptr;
else if (!node->left) return node;
else return findMin(node->left);
}
AVLNode* findMax(AVLNode* node)
{
if (!node) return nullptr;
else if (!node->right) return node;
else return findMax(node->right);
}
void inOrder(const AVLNode* node) {
if (!node) return;
else {
inOrder(node->left);
cout << node->key << endl;
inOrder(node->right);
}
}
void preOrder(const AVLNode* node) {
if (!node) return;
else {
cout << node->key << endl;
preOrder(node->left);
preOrder(node->right);
}
}
void displayPaths(const AVLNode* node) {
if (!node) return;
else {
cout << node->key << endl;
node->displayPaths();
displayPaths(node->right);
displayPaths(node->left);
}
}
int getBalance(const AVLNode* node)
{
if (!node) return 0;
else return getHeight(node->left) - getHeight(node->right);
}
int getHeight(const AVLNode* node) {
return node == nullptr ? -1 : node->height;
}
void makeDeletion(AVLNode* node) {
if (!node)
return;
else {
makeDeletion(node->right);
makeDeletion(node->left);
delete node;
}
}
}; | [
"noreply@github.com"
] | noreply@github.com |
617741231ac1f1e535d350dcce1f608ca19114d3 | 8aee93ee0dc09c6cf9df91a215713fa957fa883b | /test/messages/error_block_start_rules.re | 03f73702b8a71905e1a097b19456b1813499d544 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain"
] | permissive | trofi/re2c | 7bbe5a3ffa6398c69d3e48886fcd2c38f88296c6 | 51c3d5f5acd18da6aea9d3deebc855776344fe8f | refs/heads/master | 2022-07-11T21:33:43.253548 | 2022-07-03T08:24:37 | 2022-07-03T08:24:37 | 270,314,465 | 0 | 0 | NOASSERTION | 2020-06-07T13:25:47 | 2020-06-07T13:25:46 | null | UTF-8 | C++ | false | false | 350 | re | // re2c $INPUT -o $OUTPUT
/*!rules:re2c*/ // ok, end of block
/*!rules:re2c:_Yx1*/ // ok, end of block
/*!rules:re2c */ // ok, space
/*!rules:re2c:Yx1 */ // ok, space
/*!rules:re2c */ // ok, space
/*!rules:re2c:yX1_ */ // ok, space
/*!rules:re2c
*/ // ok, newline
/*!rules:re2c:_
*/ // ok, newline
/*!rules:re2c:1Yx */ // bad, name starts with digit
| [
"skvadrik@gmail.com"
] | skvadrik@gmail.com |
764ece3609e42668b6d520ead3e0d3a95df5be56 | 9b588ef20d240f93c9aa2e02b763d667ba4e9bda | /TwoStringsSubsequence/TwoStringsSubsequence/main.cpp | 961bc162e6b2e4363f30a652f008b22de41ebf47 | [] | no_license | anassaeed72/GeeksForGeeks | 4c53fd6e3a7b28d58db97a6bc5ae07dafb574bd2 | 44d8e4970c8a8be12b80b44033c0d702e1e873a5 | refs/heads/master | 2021-01-10T18:54:42.048600 | 2015-12-16T18:22:02 | 2015-12-16T18:22:02 | 32,166,755 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 840 | cpp | //
// main.cpp
// TwoStringsSubsequence
//
// Created by Anas Saeed on 10/12/14.
// Copyright (c) 2014 Anas Saeed. All rights reserved.
//
#include <iostream>
int main(int argc, const char * argv[])
{
std::string one,two;
std::cout <<"Please enter the first string\n";
std::cin >> one;
std::cout <<"Now enter the other string\n";
std::cin >> two;
unsigned int index = 0;
int charactersTrue = 0;
for (auto x :two){
for (int i = index; index < one.length(); index++) {
if (x == one[index]) {
charactersTrue++;
break;
}
}
}
if (charactersTrue == two.length()) {
std::cout << "Yes\n";
} else {
std::cout <<"NO\n";
}
// insert code here...
std::cout << "Hello, World!\n";
return 0;
}
| [
"anassaeed72@gmail.com"
] | anassaeed72@gmail.com |
9d9d74a9059333c95816b80a30d0ad812c9ab22c | 95a43c10c75b16595c30bdf6db4a1c2af2e4765d | /codecrawler/_code/hdu5402/16216803.cpp | 63e7ad8c5c05997b9cdd61cd088e81a198e6fd75 | [] | no_license | kunhuicho/crawl-tools | 945e8c40261dfa51fb13088163f0a7bece85fc9d | 8eb8c4192d39919c64b84e0a817c65da0effad2d | refs/heads/master | 2021-01-21T01:05:54.638395 | 2016-08-28T17:01:37 | 2016-08-28T17:01:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,984 | cpp | #pragma comment(linker, "/STACK:1024000000,1024000000")
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<cmath>
#include<cstdio>
#include<vector>
#include<string>
#include<cstring>
#include<algorithm>
#include<functional>
using namespace std;
typedef long long LL;
const LL base = 1e9 + 7;
const int maxn = 105;
LL T, n, m, a[maxn][maxn], sum, x, y;
inline void read(int &x)
{
char ch;
while ((ch = getchar())<'0' || ch>'9');
x = ch - '0';
while ((ch = getchar()) >= '0' && ch <= '9') x = x * 10 + ch - '0';
}
void get()
{
x = 1; y = 2;
for (int i = 1; i <= n;i++)
for (int j = 1; j <= m; j++)
if (((i + j) & 1) && a[x][y] > a[i][j]) x = i, y = j;
}
int main()
{
while (scanf("%lld%lld", &n, &m) !=EOF)
{
sum = 0;
for (int i = 1; i <= n;i++)
for (int j = 1; j <= m; j++)
{
scanf("%lld", &a[i][j]);
sum += a[i][j];
}
if (n & 1 || m & 1)
{
printf("%lld\n", sum);
if (n & 1)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j < m; j++)
if (i & 1) printf("R"); else printf("L");
if (i < n) printf("D"); else printf("\n");
}
}
else
{
for (int i = 1; i <= m; i++)
{
for (int j = 1; j < n; j++)
if (i & 1) printf("D"); else printf("U");
if (i < m) printf("R"); else printf("\n");
}
}
}
else
{
get();
printf("%lld\n", sum - a[x][y]);
for (int i = 1; i <= n; i += 2)
{
if (x == i || x == i + 1)
{
for (int j = 1; j < y; j++)
{
if (j & 1) printf("D"); else printf("U");
printf("R");
}
if (y < m) printf("R");
for (int j = y + 1; j <= m; j++)
{
if (j & 1) printf("U"); else printf("D");
if (j < m) printf("R");
}
if (i < n - 1) printf("D");
}
else if (i < x)
{
for (int j = 1; j < m; j++) printf("R");
printf("D");
for (int j = 1; j < m; j++) printf("L");
printf("D");
}
else
{
for (int j = 1; j < m; j++) printf("L");
printf("D");
for (int j = 1; j < m; j++) printf("R");
if (i < n - 1) printf("D");
}
}
printf("\n");
}
}
return 0;
} | [
"zhouhai02@meituan.com"
] | zhouhai02@meituan.com |
f8a521f33eacffd4d947649784260b0affa24596 | f1bc129debaca67dd206d20bddf3cbac2aff235a | /contests/Test 8 [Combinatorics, Math Focus] [CSE 2013-2014] [10-12-2016]/D.cpp | 8904f6f46c536ea96b9c76f9b7017faa35a4010c | [] | no_license | ovis96/coding-practice | a848b0b869b8001a69770464c46e4cfe1ba69164 | 7214383be1e3a2030aa05ff99666b9ee038ae207 | refs/heads/master | 2022-05-28T14:13:17.517562 | 2022-05-21T14:16:04 | 2022-05-21T14:16:04 | 70,779,713 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 401 | cpp | /*
OVISHEK PAUL, CSE - 15, SUST
*/
#include<bits/stdc++.h>
#define pf printf
#define sf scanf
int main()
{
int t, tst = 1;
int n, m;
while(sf("%d %d",&n, &m)){
if(n==0 && m==0) return 0;
double ans = 0, a = n, b = m;
if(n<m) a = n;
if(n>m) ans = 0;
else ans = (b-a+1)/(b+1);
pf("%.6lf\n", ans);
}
return 0;
}
| [
"ovishek.private@gmail.com"
] | ovishek.private@gmail.com |
4339f61a49a6e96ab99a022f054a14d14c920940 | 1a66a41ea7b1ffe1ce2f01b7067271d6995b3de8 | /src/BDConnector.cpp | 27ab6b56ab8538b6aca7f80f85a257cc4b5099b1 | [
"MIT"
] | permissive | DAOLEZ/ObjectifCanapi | be0ca6c06c4526362a44f74949e76e0c0c472615 | f5fddafb5a6f14810bd97b66138b76dcd324768c | refs/heads/master | 2021-01-18T17:12:05.020227 | 2014-11-08T17:30:48 | 2014-11-08T17:30:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,381 | cpp | /*!
* \file BDConnector.cpp
* \brief Fichier contenant l'implémentation de la classe BDConnector
* \author Camille Le Luët
* \author Thomas Minier
* \date ?
*/
#include "BDConnector.hpp"
#include <iostream>
using namespace std;
//--------------------------------------------------
/*!
* \brief Constructeur de base
* \param fichier_db NOm du fichier contenant la base de données
*/
BDConnector::BDConnector(string fichier_db) {
int rc;
//connexion à la base de données
rc = sqlite3_open((char*)fichier_db.c_str(), &db);
if( rc ) { //si la connexion a échouée
cout << "Erreur : impossible de se connecter à la base de données " << fichier_db << endl;
}
}
//--------------------------------------------------
/*!
* \brief Destructeur
*/
BDConnector::~BDConnector() {
//fermeture de la connexion à la base
sqlite3_close(this->db);
}
//--------------------------------------------------
/*!
* \brief Méthode qui permet de changer d'utilisateur
* \param fichier_db Nom du nouveau fichier contenant la base de données
*/
void BDConnector::swapUser(string fichier_db) {
int rc;
//fermeture de la connexion à la base actuelle
sqlite3_close(this->db);
//connexion à la nouvelle base de données
rc = sqlite3_open((char*)fichier_db.c_str(), &db);
if( rc ) { //si la connexion a échouée
cout << "Erreur : impossible de se connecter à la base de données " << fichier_db << endl;
}
}
//--------------------------------------------------
/*!
* \brief Méthode qui crée une nouvelle base de donnée pour un nouvel utilisateur
* \param user Nom du nouvel utlisateur
*/
void BDConnector::creerNewBD(string user) {
string nom_fichier = user + ".db";
string commande = "cp database/default.db database/" + nom_fichier;
system((char*)commande.c_str());
}
//--------------------------------------------------
/*!
* \brief Méthode qui exécute la requête SQL passée en en paramètre
* \param sql_query Requête SQL à exécuter
* \return Table correspondant à la requête SQL passée en paramètre
*/
vector<vector<string> > BDConnector::query(string sql_query) {
sqlite3_stmt *statement;
vector<vector<string> > results;
char * requete = (char*)sql_query.c_str();
int ind;
//exécution de la requête & vérification que tout s'est bien passé
if( sqlite3_prepare_v2(this->db, requete, -1, &statement, 0) == SQLITE_OK) {
//on récupère le nombre de colonnes
int nb_cols = sqlite3_column_count(statement);
//on récupère la 1ère ligne
int result = sqlite3_step(statement);
//tant qu'il reste des lignes à traiter
while(result == SQLITE_ROW) {
//liste temporaire contenant la ligne courante
vector<string> temp;
//on insère toutes les valeurs de la ligne dans la liste temporaire
for(ind = 0; ind < nb_cols; ind++) {
string val((char*)sqlite3_column_text(statement, ind));
temp.push_back(val);
}
//on ajoute la liste temporaire à la liste des résultats
results.push_back(temp);
//on avance à la ligne suivante
result = sqlite3_step(statement);
}
sqlite3_finalize(statement);
} else {
cout << sqlite3_errmsg(this->db) << endl;
}
return results;
}
//--------------------------------------------------
/*!
* \brief Méthode qui compte le nombre de lignes dans une table de la base de données
* \param nom_table Nom de la table sur laquelle effectuer l'opération
* \return Nombre de lignes présentes dans la table
*/
int BDConnector::count(string nom_table) {
//on fait la requête pour récupérer le nombre de lignes dans la table
vector<vector<string> > table = this->query("SELECT COUNT(*) FROM " + nom_table + ";");
int res = atoi(table[0][0].c_str()); //conversion de la string en int
return res;
}
//--------------------------------------------------
/*!
* \brief Méthode qui renvoie l'id de la dernière ligne de la table. L'i d de cette dernière doit être de type INTEGER
* \param nom_id Nom de l'identifiant de la table
* \param nom_table Nom de la table dont on veut récupérer le dernier id
* \return Id de la dernière ligne de la table
*/
int BDConnector::lastId(string nom_id, string nom_table) {
//on fait la requête pour récupérer les id de la table classés par ordre décroissant
vector<vector<string> > table = this->query("SELECT " + nom_id + " FROM " + nom_table + " ORDER BY " + nom_id + " DESC;");
int res = atoi(table[0][0].c_str()); //conversion de la string en int
return res;
}
//--------------------------------------------------
/*!
* \brief Méthode qui renvoie le prochain id à insérer dans la table. L'id de cette dernière doit être de type INTEGER
* \param nom_id Nom de l'identifiant de la table
* \param nom_table Nom de la table dont on veut récupérer le prochain id à insérer
* \return Le prochain id à insérer dans la table
*/
int BDConnector::nextIdToInsert(string nom_id, string nom_table) {
return this->lastId(nom_id, nom_table) + 1;
}
//--------------------------------------------------
/*!
* \brief Méthode qui vérifie si une requête renvoie une table vide
* \param sql_query La requête à tester
* \return Si la table renvoyée par la requête est vide ou non
*/
bool BDConnector::isQueryEmpty(string sql_query) {
//on récupère la table liée à la requête et on teste si elle ne contient aucun élément
vector<vector<string> > table = this->query(sql_query);
return (table.size() == 0);
}
| [
"tminier01@gmail.com"
] | tminier01@gmail.com |
200f407b9467375ac4a920c940164d6ac55a4516 | 806735c91d9fac50ac6a0e0b44c68ac438b9ecb6 | /iitk interview/night-fury/goldman-sachs/H.cpp | 1e407ee394d4d3f3de75481a8c1474a923c61ad3 | [] | no_license | v-pratap/cp | a04119a5c42853b5ae5bb3535deaa726a23b113d | 28ba7e27cd7b065800954445497642b852e20160 | refs/heads/main | 2023-06-05T03:46:55.685212 | 2021-06-28T05:56:06 | 2021-06-28T05:56:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,178 | cpp | //VIRUS
#include <bits/stdc++.h>
typedef long long ll;
typedef long double ld;
#define f(i,a,b) for(int i = a;i<b;i++)
#define rep(i,a,b) for(int i = a;i<=b;i++)
#define fd(i,a,b) for(int i = a;i>b;i--)
#define repd(i,a,b) for(int i = a;i>=b;i--)
#define pii pair<int,int>
#define pll pair<ll,ll>
#define fi first
#define se second
#define pb push_back
#define sz(x) (int) (x).size()
#define all(x) x.begin(),x.end()
#define endl '\n'
using namespace std;
const int mod = 1000000007;
const int maxn = 10001;
vector<int> adj[maxn];
vector<int> boost(maxn);
int dfs(int u){
int ans = INT_MIN;
for(auto &v:adj[u])
ans = max(ans,dfs(v));
cout<<ans<<endl;
return max(boost[u],boost[u]+ans);
}
int main(){
int n;
cin>>n;
vector<int> pre0;
f(i,0,n){
cin>>boost[i];
int t,x;
cin>>t;
if(t==0) pre0.pb(i);
f(j,0,t){
cin>>x;
--x;
adj[x].pb(j);
}
}
cout<<endl;
f(i,0,n){
for(auto &v:adj[i]) cout<<v<<' ';
cout<<endl;
}
/*int ans = INT_MIN;
for(auto &x:pre0)
ans = max(ans,dfs(x));
cout<<ans<<endl;*/
} | [
"raunakmaken1999@gmail.com"
] | raunakmaken1999@gmail.com |
4830ea289dfcaf94cd1d95902d5cf38871d2f43f | db86c0cac4e1c1b0fbc4d81cdc33ab9445899bc0 | /Apate/src/APpch.h | 713bc3b6bb83773e3d5a404e891d6a3144667567 | [
"Apache-2.0"
] | permissive | TheUnicum/Apate | f51bc60d5b615528d80b9c9493b88d3876c494c1 | fdd050aa30c6575229cd6bf736616f0494e26742 | refs/heads/master | 2020-06-23T03:58:33.406193 | 2019-08-06T19:47:31 | 2019-08-06T19:47:31 | 198,502,660 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 301 | h | #pragma once
#include <iostream>
#include <memory>
#include <utility>
#include <algorithm>
#include <functional>
#include <string>
#include <sstream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include "Apate/Log.h"
#ifdef AP_PLATFORM_WINDOWS
#include <Windows.h>
#endif
| [
"tia_ben@tin.it"
] | tia_ben@tin.it |
3995eff1e4dc88518012ada49455905c86dbc6d4 | 515a28f08f58aaab7e277c90c7902c21bc8f4125 | /src/lipservice/ERRORR/DummyMF33/Card2/Nout/test/Nout.test.cpp | 46ca28048bb637663fd42bff25624c01efd1c8c1 | [
"BSD-2-Clause"
] | permissive | njoy/lipservice | e3bf4c8c07d79a46c13a88976f22ee07e416f4a6 | 1efa5e9452384a7bfc278fde57979c4d91e312c0 | refs/heads/master | 2023-08-04T11:01:04.411539 | 2021-01-20T22:24:17 | 2021-01-20T22:24:17 | 146,359,436 | 0 | 2 | NOASSERTION | 2023-07-25T19:41:10 | 2018-08-27T22:05:50 | C++ | UTF-8 | C++ | false | false | 1,599 | cpp | #define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "lipservice.hpp"
using namespace njoy::njoy21::lipservice;
SCENARIO( "ERRORR, DummyMF33, Card2, Nout",
"[ERRORR] [DummyMF33] [Card2] [Nout]" ){
const int nin = 47;
GIVEN( "valid inputs" ){
for( auto i : {-99, -44, -20, 20, 92, 99} ){
std::string situ( "valid input " + std::to_string(i) + " is provided." );
WHEN( situ.c_str() ){
iRecordStream<char> iss( std::istringstream( std::to_string( i ) ) );
THEN( "the value can be verified" ){
REQUIRE( i == argument::extract< ERRORR::DummyMF33::Card2::Nout >(
iss, nin ).value );
}
} // WHEN
}
} // GIVEN
GIVEN( "invalid inputs" ){
WHEN( "no value is provided" ){
iRecordStream<char> iss( std::istringstream( " /" ) );
THEN( "an exception is thrown" ){
REQUIRE_THROWS( argument::extract< ERRORR::DummyMF33::Card2::Nout >(
iss, nin ) );
}
} // WHEN
for( auto i : {-100, -47, -19, 0, 19, 47, 100} ){
std::string situ( "invalid input " + std::to_string(i) + " is provided.");
WHEN( situ.c_str() ){
iRecordStream<char> iss( std::istringstream( std::to_string( i ) ) );
THEN( "an exception is thrown" ){
REQUIRE_THROWS( argument::extract< ERRORR::DummyMF33::Card2::Nout >(
iss, nin ) );
}
} // WHEN
}
} // GIVEN
} // SCENARIO
| [
"jlconlin@lanl.gov"
] | jlconlin@lanl.gov |
dcbb9c65f6fa564cf42d90e6476e9a1f8e3c5f22 | 41495754cf8b951b23cece87b5c79a726748cff7 | /Solutions/UVA/644.cpp | 37ff7451f2bd52d5a7232ea09d2f757728ccd2af | [] | no_license | PedroAngeli/Competitive-Programming | 86ad490eced6980d7bc3376a49744832e470c639 | ff64a092023987d5e3fdd720f56c62b99ad175a6 | refs/heads/master | 2021-10-23T04:49:51.508166 | 2021-10-13T21:39:21 | 2021-10-13T21:39:21 | 198,916,501 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,863 | cpp | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define endl '\n'
#define f first
#define s second
#define ub upper_bound
#define lb lower_bound
#define pb push_back
#define all(c) (c).begin(), (c).end()
#define sz(x) (int)(x).size()
#define ordered_set tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>
#define fbo find_by_order
#define ook order_of_key
#define fastio ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define debug(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
cerr << "[" << name << " : " << arg1 << "]" << endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
const char* comma = strchr(names + 1, ',');cerr << "[";
cerr.write(names, comma - names) << " : " << arg1<<"] | ";__f(comma+1, args...);
}
using ld = long double;
using ll = long long;
using pii = pair <int,int>;
using pll = pair <ll,ll>;
using vi = vector <int>;
using vll = vector <ll>;
using vpii = vector <pii>;
using vpll = vector<pll>;
using vs = vector <string>;
bool prefix(string& a, string &b){
if(sz(a) > sz(b)) return false;
for(int i=0;i<sz(a);i++) if(a[i] != b[i]) return false;
return true;
}
int main(){
fastio;
string code;
int ncase = 1;
while(cin >> code){
vs codes;
codes.pb(code);
while(cin >> code && code != "9") codes.pb(code);
int n = sz(codes);
bool can = true;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
if(i != j)
can = (can and !prefix(codes[i], codes[j]));
if(can) cout << "Set " << ncase++ << " is immediately decodable" << endl;
else cout << "Set " << ncase++ << " is not immediately decodable" << endl;
}
return 0;
} | [
"pedroans.angeli@hotmail.com"
] | pedroans.angeli@hotmail.com |
a5e37e8aa762279a1c724af56cb0a2e8b43fba21 | 6a861cb9e6e7f88e88aa274c9ced9a81d06431dd | /src/gba/remote.cpp | 97304d4e934f570a814839591b0084266af78db4 | [] | no_license | Adam-Petersen/PokeAI-vba-m | 247bf05da2894f78c4708e8e3baf126ea9b2cc00 | 05ffe5685c4fa5d298bacf5667742773726e8aa4 | refs/heads/master | 2023-07-31T05:02:15.089585 | 2021-10-02T00:09:55 | 2021-10-02T00:09:55 | 269,192,746 | 0 | 0 | null | 2021-10-01T19:57:51 | 2020-06-03T20:55:17 | C++ | UTF-8 | C++ | false | false | 127,097 | cpp | #ifndef __LIBRETRO__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iosfwd>
#include <sstream>
#include <vector>
#ifndef _WIN32
#include <netdb.h>
#include <sys/socket.h>
#include <unistd.h>
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif // HAVE_NETINET_IN_H
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#else // ! HAVE_ARPA_INET_H
#define socklen_t int
#endif // ! HAVE_ARPA_INET_H
#define SOCKET int
#else // _WIN32
#include <io.h>
#include <winsock.h>
#define socklen_t int
#define close closesocket
#define read _read
#define write _write
#define strdup _strdup
#endif // _WIN32
#include "BreakpointStructures.h"
#include "GBA.h"
#include "elf.h"
#include "remote.h"
#include <iomanip>
#include <iostream>
extern bool debugger;
extern int emulating;
extern void CPUUpdateCPSR();
int remotePort = 0;
int remoteSignal = 5;
SOCKET remoteSocket = -1;
SOCKET remoteListenSocket = -1;
bool remoteConnected = false;
bool remoteResumed = false;
int (*remoteSendFnc)(char*, int) = NULL;
int (*remoteRecvFnc)(char*, int) = NULL;
bool (*remoteInitFnc)() = NULL;
void (*remoteCleanUpFnc)() = NULL;
#ifndef SDL
void remoteSetSockets(SOCKET l, SOCKET r)
{
remoteSocket = r;
remoteListenSocket = l;
}
#endif
#define debuggerReadMemory(addr) \
(*(uint32_t*)&map[(addr) >> 24].address[(addr)&map[(addr) >> 24].mask])
#define debuggerReadHalfWord(addr) \
(*(uint16_t*)&map[(addr) >> 24].address[(addr)&map[(addr) >> 24].mask])
#define debuggerReadByte(addr) \
map[(addr) >> 24].address[(addr)&map[(addr) >> 24].mask]
#define debuggerWriteMemory(addr, value) \
*(uint32_t*)&map[(addr) >> 24].address[(addr)&map[(addr) >> 24].mask] = (value)
#define debuggerWriteHalfWord(addr, value) \
*(uint16_t*)&map[(addr) >> 24].address[(addr)&map[(addr) >> 24].mask] = (value)
#define debuggerWriteByte(addr, value) \
map[(addr) >> 24].address[(addr)&map[(addr) >> 24].mask] = (value)
bool dontBreakNow = false;
int debuggerNumOfDontBreak = 0;
int debuggerRadix = 0;
#define NUMBEROFDB 1000
uint32_t debuggerNoBreakpointList[NUMBEROFDB];
const char* cmdAliasTable[] = { "help", "?", "h", "?", "continue", "c", "next", "n",
"cpyb", "copyb", "cpyh", "copyh", "cpyw", "copyw",
"exe", "execute", "exec", "execute",
NULL, NULL };
struct DebuggerCommand {
const char* name;
void (*function)(int, char**);
const char* help;
const char* syntax;
};
char monbuf[1000];
void monprintf(std::string line);
std::string StringToHex(std::string& cmd);
std::string HexToString(char* p);
void debuggerUsage(const char* cmd);
void debuggerHelp(int n, char** args);
void printFlagHelp();
void dbgExecute(std::string& cmd);
extern bool debuggerBreakOnWrite(uint32_t, uint32_t, int);
extern bool debuggerBreakOnRegisterCondition(uint8_t, uint32_t, uint32_t, uint8_t);
extern bool debuggerBreakOnExecution(uint32_t, uint8_t);
regBreak* breakRegList[16];
uint8_t lowRegBreakCounter[4]; //(r0-r3)
uint8_t medRegBreakCounter[4]; //(r4-r7)
uint8_t highRegBreakCounter[4]; //(r8-r11)
uint8_t statusRegBreakCounter[4]; //(r12-r15)
uint8_t* regBreakCounter[4] = {
&lowRegBreakCounter[0],
&medRegBreakCounter[0],
&highRegBreakCounter[0],
&statusRegBreakCounter[0]
};
uint32_t lastWasBranch = 0;
struct regBreak* getFromBreakRegList(uint8_t regnum, int location)
{
if (location > regBreakCounter[regnum >> 2][regnum & 3])
return NULL;
struct regBreak* ans = breakRegList[regnum];
for (int i = 0; i < location && ans; i++) {
ans = ans->next;
}
return ans;
}
bool enableRegBreak = false;
reg_pair oldReg[16];
uint32_t regDiff[16];
void breakReg_check(int i)
{
struct regBreak* brkR = breakRegList[i];
bool notFound = true;
uint8_t counter = regBreakCounter[i >> 2][i & 3];
for (int bri = 0; (bri < counter) && notFound; bri++) {
if (!brkR) {
regBreakCounter[i >> 2][i & 3] = (uint8_t)bri;
break;
} else {
if (brkR->flags != 0) {
uint32_t regVal = (i == 15 ? (armState ? reg[15].I - 4 : reg[15].I - 2) : reg[i].I);
if ((brkR->flags & 0x1) && (regVal == brkR->intVal)) {
debuggerBreakOnRegisterCondition(i, brkR->intVal, regVal, 1);
notFound = false;
}
if ((brkR->flags & 0x8)) {
if ((brkR->flags & 0x4) && ((int)regVal < (int)brkR->intVal)) {
debuggerBreakOnRegisterCondition(i, brkR->intVal, regVal, 4);
notFound = false;
}
if ((brkR->flags & 0x2) && ((int)regVal > (int)brkR->intVal)) {
debuggerBreakOnRegisterCondition(i, brkR->intVal, regVal, 5);
notFound = false;
}
}
if ((brkR->flags & 0x4) && (regVal < brkR->intVal)) {
debuggerBreakOnRegisterCondition(i, brkR->intVal, regVal, 2);
notFound = false;
}
if ((brkR->flags & 0x2) && (regVal > brkR->intVal)) {
debuggerBreakOnRegisterCondition(i, brkR->intVal, regVal, 3);
notFound = false;
}
}
brkR = brkR->next;
}
}
if (!notFound) {
//CPU_BREAK_LOOP_2;
}
}
void clearParticularRegListBreaks(int regNum)
{
while (breakRegList[regNum]) {
struct regBreak* ans = breakRegList[regNum]->next;
free(breakRegList[regNum]);
breakRegList[regNum] = ans;
}
regBreakCounter[regNum >> 2][regNum & 3] = 0;
}
void clearBreakRegList()
{
for (int i = 0; i < 16; i++) {
clearParticularRegListBreaks(i);
}
}
void deleteFromBreakRegList(uint8_t regNum, int num)
{
int counter = regBreakCounter[regNum >> 2][regNum & 3];
if (num >= counter) {
return;
}
struct regBreak* ans = breakRegList[regNum];
struct regBreak* prev = NULL;
for (int i = 0; i < num; i++) {
prev = ans;
ans = ans->next;
}
if (prev) {
prev->next = ans->next;
} else {
breakRegList[regNum] = ans->next;
}
free(ans);
regBreakCounter[regNum >> 2][regNum & 3]--;
}
void addBreakRegToList(uint8_t regnum, uint8_t flags, uint32_t value)
{
struct regBreak* ans = (struct regBreak*)malloc(sizeof(struct regBreak));
ans->flags = flags;
ans->intVal = value;
ans->next = breakRegList[regnum];
breakRegList[regnum] = ans;
regBreakCounter[regnum >> 2][regnum & 3]++;
}
void printBreakRegList(bool verbose)
{
const char* flagsToOP[] = { "never", "==", ">", ">=", "<", "<=", "!=", "always" };
bool anyPrint = false;
for (int i = 0; i < 4; i++) {
for (int k = 0; k < 4; k++) {
if (regBreakCounter[i][k]) {
if (!anyPrint) {
{
sprintf(monbuf, "Register breakpoint list:\n");
monprintf(monbuf);
}
{
sprintf(monbuf, "-------------------------\n");
monprintf(monbuf);
}
anyPrint = true;
}
struct regBreak* tmp = breakRegList[i * 4 + k];
for (int j = 0; j < regBreakCounter[i][k]; j++) {
if (tmp->flags & 8) {
sprintf(monbuf, "No. %d:\tBreak if (signed)%s %08x\n", j, flagsToOP[tmp->flags & 7], tmp->intVal);
monprintf(monbuf);
} else {
sprintf(monbuf, "No. %d:\tBreak if %s %08x\n", j, flagsToOP[tmp->flags], tmp->intVal);
monprintf(monbuf);
}
tmp = tmp->next;
}
{
sprintf(monbuf, "-------------------------\n");
monprintf(monbuf);
}
} else {
if (verbose) {
if (!anyPrint) {
{
sprintf(monbuf, "Register breakpoint list:\n");
monprintf(monbuf);
}
{
sprintf(monbuf, "-------------------------\n");
monprintf(monbuf);
}
anyPrint = true;
}
{
sprintf(monbuf, "No breaks on r%d.\n", i);
monprintf(monbuf);
}
{
sprintf(monbuf, "-------------------------\n");
monprintf(monbuf);
}
}
}
}
}
if (!verbose && !anyPrint) {
{
sprintf(monbuf, "No Register breaks found.\n");
monprintf(monbuf);
}
}
}
void debuggerOutput(const char* s, uint32_t addr)
{
if (s)
printf("%s", s);
else {
char c;
c = debuggerReadByte(addr);
addr++;
while (c) {
putchar(c);
c = debuggerReadByte(addr);
addr++;
}
}
}
// checks that the given address is in the DB list
bool debuggerInDB(uint32_t address)
{
for (int i = 0; i < debuggerNumOfDontBreak; i++) {
if (debuggerNoBreakpointList[i] == address)
return true;
}
return false;
}
void debuggerDontBreak(int n, char** args)
{
if (n == 2) {
uint32_t address = 0;
sscanf(args[1], "%x", &address);
int i = debuggerNumOfDontBreak;
if (i > NUMBEROFDB) {
monprintf("Can't have this many DB entries");
return;
}
debuggerNoBreakpointList[i] = address;
debuggerNumOfDontBreak++;
{
sprintf(monbuf, "Added Don't Break at %08x\n", address);
monprintf(monbuf);
}
} else
debuggerUsage("db");
}
void debuggerDontBreakClear(int n, char** args)
{
(void)args; // unused params
if (n == 1) {
debuggerNumOfDontBreak = 0;
{
sprintf(monbuf, "Cleared Don't Break list.\n");
monprintf(monbuf);
}
} else
debuggerUsage("dbc");
}
void debuggerDumpLoad(int n, char** args)
{
uint32_t address;
char* file;
FILE* f;
int c;
if (n == 3) {
file = args[1];
if (!dexp_eval(args[2], &address)) {
{
sprintf(monbuf, "Invalid expression in address.\n");
monprintf(monbuf);
}
return;
}
f = fopen(file, "rb");
if (f == NULL) {
{
sprintf(monbuf, "Error opening file.\n");
monprintf(monbuf);
}
return;
}
fseek(f, 0, SEEK_END);
int size = ftell(f);
fseek(f, 0, SEEK_SET);
for (int i = 0; i < size; i++) {
c = fgetc(f);
if (c == -1)
break;
debuggerWriteByte(address, c);
address++;
}
fclose(f);
} else
debuggerUsage("dload");
}
void debuggerDumpSave(int n, char** args)
{
uint32_t address;
uint32_t size;
char* file;
FILE* f;
if (n == 4) {
file = args[1];
if (!dexp_eval(args[2], &address)) {
{
sprintf(monbuf, "Invalid expression in address.\n");
monprintf(monbuf);
}
return;
}
if (!dexp_eval(args[3], &size)) {
{
sprintf(monbuf, "Invalid expression in size");
monprintf(monbuf);
}
return;
}
f = fopen(file, "wb");
if (f == NULL) {
{
sprintf(monbuf, "Error opening file.\n");
monprintf(monbuf);
}
return;
}
for (uint32_t i = 0; i < size; i++) {
fputc(debuggerReadByte(address), f);
address++;
}
fclose(f);
} else
debuggerUsage("dsave");
}
void debuggerEditByte(int n, char** args)
{
if (n >= 3) {
uint32_t address;
uint32_t value;
if (!dexp_eval(args[1], &address)) {
{
sprintf(monbuf, "Invalid expression in address.\n");
monprintf(monbuf);
}
return;
}
for (int i = 2; i < n; i++) {
if (!dexp_eval(args[i], &value)) {
{
sprintf(monbuf, "Invalid expression in %d value.Ignored.\n", (i - 1));
monprintf(monbuf);
}
}
debuggerWriteByte(address, (uint16_t)value);
address++;
}
} else
debuggerUsage("eb");
}
void debuggerEditHalfWord(int n, char** args)
{
if (n >= 3) {
uint32_t address;
uint32_t value;
if (!dexp_eval(args[1], &address)) {
{
sprintf(monbuf, "Invalid expression in address.\n");
monprintf(monbuf);
}
return;
}
if (address & 1) {
{
sprintf(monbuf, "Error: address must be half-word aligned\n");
monprintf(monbuf);
}
return;
}
for (int i = 2; i < n; i++) {
if (!dexp_eval(args[i], &value)) {
{
sprintf(monbuf, "Invalid expression in %d value.Ignored.\n", (i - 1));
monprintf(monbuf);
}
}
debuggerWriteHalfWord(address, (uint16_t)value);
address += 2;
}
} else
debuggerUsage("eh");
}
void debuggerEditWord(int n, char** args)
{
if (n >= 3) {
uint32_t address;
uint32_t value;
if (!dexp_eval(args[1], &address)) {
{
sprintf(monbuf, "Invalid expression in address.\n");
monprintf(monbuf);
}
return;
}
if (address & 3) {
{
sprintf(monbuf, "Error: address must be word aligned\n");
monprintf(monbuf);
}
return;
}
for (int i = 2; i < n; i++) {
if (!dexp_eval(args[i], &value)) {
{
sprintf(monbuf, "Invalid expression in %d value.Ignored.\n", (i - 1));
monprintf(monbuf);
}
}
debuggerWriteMemory(address, (uint32_t)value);
address += 4;
}
} else
debuggerUsage("ew");
}
bool debuggerBreakOnRegisterCondition(uint8_t registerName, uint32_t compareVal, uint32_t regVal, uint8_t type)
{
const char* typeName;
switch (type) {
case 1:
typeName = "equal to";
break;
case 2:
typeName = "greater (unsigned) than";
break;
case 3:
typeName = "smaller (unsigned) than";
break;
case 4:
typeName = "greater (signed) than";
break;
case 5:
typeName = "smaller (signed) than";
break;
default:
typeName = "unknown";
}
{
sprintf(monbuf, "Breakpoint on R%02d : %08x is %s register content (%08x)\n", registerName, compareVal, typeName, regVal);
monprintf(monbuf);
}
if (debuggerInDB(armState ? reg[15].I - 4 : reg[15].I - 2)) {
{
sprintf(monbuf, "But this address is marked not to break, so skipped\n");
monprintf(monbuf);
}
return false;
}
debugger = true;
return true;
}
void debuggerBreakRegisterList(bool verbose)
{
printBreakRegList(verbose);
}
int getRegisterNumber(char* regName)
{
int r = -1;
if (toupper(regName[0]) == 'P' && toupper(regName[1]) == 'C') {
r = 15;
} else if (toupper(regName[0]) == 'L' && toupper(regName[1]) == 'R') {
r = 14;
} else if (toupper(regName[0]) == 'S' && toupper(regName[1]) == 'P') {
r = 13;
} else if (toupper(regName[0]) == 'R') {
sscanf((char*)(regName + 1), "%d", &r);
} else {
sscanf(regName, "%d", &r);
}
return r;
}
void debuggerEditRegister(int n, char** args)
{
if (n == 3) {
int r = getRegisterNumber(args[1]);
uint32_t val;
if (r > 16) {
{
sprintf(monbuf, "Error: Register must be valid (0-16)\n");
monprintf(monbuf);
}
return;
}
if (!dexp_eval(args[2], &val)) {
{
sprintf(monbuf, "Invalid expression in value.\n");
monprintf(monbuf);
}
return;
}
reg[r].I = val;
{
sprintf(monbuf, "R%02d=%08X\n", r, val);
monprintf(monbuf);
}
} else
debuggerUsage("er");
}
void debuggerEval(int n, char** args)
{
if (n == 2) {
uint32_t result = 0;
if (dexp_eval(args[1], &result)) {
{
sprintf(monbuf, " =$%08X\n", result);
monprintf(monbuf);
}
} else {
{
sprintf(monbuf, "Invalid expression\n");
monprintf(monbuf);
}
}
} else
debuggerUsage("eval");
}
void debuggerFillByte(int n, char** args)
{
if (n == 4) {
uint32_t address;
uint32_t value;
uint32_t reps;
if (!dexp_eval(args[1], &address)) {
{
sprintf(monbuf, "Invalid expression in address.\n");
monprintf(monbuf);
}
return;
}
if (!dexp_eval(args[2], &value)) {
{
sprintf(monbuf, "Invalid expression in value.\n");
monprintf(monbuf);
}
}
if (!dexp_eval(args[3], &reps)) {
{
sprintf(monbuf, "Invalid expression in repetition number.\n");
monprintf(monbuf);
}
}
for (uint32_t i = 0; i < reps; i++) {
debuggerWriteByte(address, (uint8_t)value);
address++;
}
} else
debuggerUsage("fillb");
}
void debuggerFillHalfWord(int n, char** args)
{
if (n == 4) {
uint32_t address;
uint32_t value;
uint32_t reps;
if (!dexp_eval(args[1], &address)) {
{
sprintf(monbuf, "Invalid expression in address.\n");
monprintf(monbuf);
}
return;
} /*
if(address & 1) {
{ sprintf(monbuf, "Error: address must be halfword aligned\n"); monprintf(monbuf); }
return;
}*/
if (!dexp_eval(args[2], &value)) {
{
sprintf(monbuf, "Invalid expression in value.\n");
monprintf(monbuf);
}
}
if (!dexp_eval(args[3], &reps)) {
{
sprintf(monbuf, "Invalid expression in repetition number.\n");
monprintf(monbuf);
}
}
for (uint32_t i = 0; i < reps; i++) {
debuggerWriteHalfWord(address, (uint16_t)value);
address += 2;
}
} else
debuggerUsage("fillh");
}
void debuggerFillWord(int n, char** args)
{
if (n == 4) {
uint32_t address;
uint32_t value;
uint32_t reps;
if (!dexp_eval(args[1], &address)) {
{
sprintf(monbuf, "Invalid expression in address.\n");
monprintf(monbuf);
}
return;
} /*
if(address & 3) {
{ sprintf(monbuf, "Error: address must be word aligned\n"); monprintf(monbuf); }
return;
}*/
if (!dexp_eval(args[2], &value)) {
{
sprintf(monbuf, "Invalid expression in value.\n");
monprintf(monbuf);
}
}
if (!dexp_eval(args[3], &reps)) {
{
sprintf(monbuf, "Invalid expression in repetition number.\n");
monprintf(monbuf);
}
}
for (uint32_t i = 0; i < reps; i++) {
debuggerWriteMemory(address, (uint32_t)value);
address += 4;
}
} else
debuggerUsage("fillw");
}
unsigned int SearchStart = 0xFFFFFFFF;
unsigned int SearchMaxMatches = 5;
uint8_t SearchData[64]; // It actually doesn't make much sense to search for more than 64 bytes, does it?
unsigned int SearchLength = 0;
unsigned int SearchResults;
unsigned int AddressToGBA(uint8_t* mem)
{
if (mem >= &bios[0] && mem <= &bios[0x3fff])
return 0x00000000 + (mem - &bios[0]);
else if (mem >= &workRAM[0] && mem <= &workRAM[0x3ffff])
return 0x02000000 + (mem - &workRAM[0]);
else if (mem >= &internalRAM[0] && mem <= &internalRAM[0x7fff])
return 0x03000000 + (mem - &internalRAM[0]);
else if (mem >= &ioMem[0] && mem <= &ioMem[0x3ff])
return 0x04000000 + (mem - &ioMem[0]);
else if (mem >= &paletteRAM[0] && mem <= &paletteRAM[0x3ff])
return 0x05000000 + (mem - &paletteRAM[0]);
else if (mem >= &vram[0] && mem <= &vram[0x1ffff])
return 0x06000000 + (mem - &vram[0]);
else if (mem >= &oam[0] && mem <= &oam[0x3ff])
return 0x07000000 + (mem - &oam[0]);
else if (mem >= &rom[0] && mem <= &rom[0x1ffffff])
return 0x08000000 + (mem - &rom[0]);
else
return 0xFFFFFFFF;
};
void debuggerDoSearch()
{
unsigned int count = 0;
while (true) {
unsigned int final = SearchStart + SearchLength - 1;
uint8_t* end;
uint8_t* start;
switch (SearchStart >> 24) {
case 0:
if (final > 0x00003FFF) {
SearchStart = 0x02000000;
continue;
} else {
start = bios + (SearchStart & 0x3FFF);
end = bios + 0x3FFF;
break;
};
case 2:
if (final > 0x0203FFFF) {
SearchStart = 0x03000000;
continue;
} else {
start = workRAM + (SearchStart & 0x3FFFF);
end = workRAM + 0x3FFFF;
break;
};
case 3:
if (final > 0x03007FFF) {
SearchStart = 0x04000000;
continue;
} else {
start = internalRAM + (SearchStart & 0x7FFF);
end = internalRAM + 0x7FFF;
break;
};
case 4:
if (final > 0x040003FF) {
SearchStart = 0x05000000;
continue;
} else {
start = ioMem + (SearchStart & 0x3FF);
end = ioMem + 0x3FF;
break;
};
case 5:
if (final > 0x050003FF) {
SearchStart = 0x06000000;
continue;
} else {
start = paletteRAM + (SearchStart & 0x3FF);
end = paletteRAM + 0x3FF;
break;
};
case 6:
if (final > 0x0601FFFF) {
SearchStart = 0x07000000;
continue;
} else {
start = vram + (SearchStart & 0x1FFFF);
end = vram + 0x1FFFF;
break;
};
case 7:
if (final > 0x070003FF) {
SearchStart = 0x08000000;
continue;
} else {
start = oam + (SearchStart & 0x3FF);
end = oam + 0x3FF;
break;
};
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
if (final <= 0x09FFFFFF) {
start = rom + (SearchStart & 0x01FFFFFF);
end = rom + 0x01FFFFFF;
break;
};
default: {
sprintf(monbuf, "Search completed.\n");
monprintf(monbuf);
}
SearchLength = 0;
return;
};
end -= SearchLength - 1;
uint8_t firstbyte = SearchData[0];
while (start <= end) {
while ((start <= end) && (*start != firstbyte))
start++;
if (start > end)
break;
unsigned int p = 1;
while ((start[p] == SearchData[p]) && (p < SearchLength))
p++;
if (p == SearchLength) {
{
sprintf(monbuf, "Search result (%d): %08x\n", count + SearchResults, AddressToGBA(start));
monprintf(monbuf);
}
count++;
if (count == SearchMaxMatches) {
SearchStart = AddressToGBA(start + p);
SearchResults += count;
return;
};
start += p; // assume areas don't overlap; alternative: start++;
} else
start++;
};
SearchStart = AddressToGBA(end + SearchLength - 1) + 1;
};
};
void debuggerFindText(int n, char** args)
{
if ((n == 4) || (n == 3)) {
SearchResults = 0;
if (!dexp_eval(args[1], &SearchStart)) {
{
sprintf(monbuf, "Invalid expression.\n");
monprintf(monbuf);
}
return;
}
if (n == 4) {
sscanf(args[2], "%u", &SearchMaxMatches);
strncpy((char*)SearchData, args[3], 64);
SearchLength = strlen(args[3]);
} else if (n == 3) {
strncpy((char*)SearchData, args[2], 64);
SearchLength = strlen(args[2]);
};
if (SearchLength > 64) {
{
sprintf(monbuf, "Entered string (length: %d) is longer than 64 bytes and was cut.\n", SearchLength);
monprintf(monbuf);
}
SearchLength = 64;
};
debuggerDoSearch();
} else
debuggerUsage("ft");
};
void debuggerFindHex(int n, char** args)
{
if ((n == 4) || (n == 3)) {
SearchResults = 0;
if (!dexp_eval(args[1], &SearchStart)) {
{
sprintf(monbuf, "Invalid expression.\n");
monprintf(monbuf);
}
return;
}
char SearchHex[128];
if (n == 4) {
sscanf(args[2], "%u", &SearchMaxMatches);
strncpy(SearchHex, args[3], 128);
SearchLength = strlen(args[3]);
} else if (n == 3) {
strncpy(SearchHex, args[2], 128);
SearchLength = strlen(args[2]);
};
if (SearchLength & 1) {
sprintf(monbuf, "Unaligned bytecount: %d,5. Last digit (%c) cut.\n", SearchLength / 2, SearchHex[SearchLength - 1]);
monprintf(monbuf);
}
SearchLength /= 2;
if (SearchLength > 64) {
{
sprintf(monbuf, "Entered string (length: %d) is longer than 64 bytes and was cut.\n", SearchLength);
monprintf(monbuf);
}
SearchLength = 64;
};
for (unsigned int i = 0; i < SearchLength; i++) {
unsigned int cbuf = 0;
sscanf(&SearchHex[i << 1], "%02x", &cbuf);
SearchData[i] = cbuf;
};
debuggerDoSearch();
} else
debuggerUsage("fh");
};
void debuggerFindResume(int n, char** args)
{
if ((n == 1) || (n == 2)) {
if (SearchLength == 0) {
{
sprintf(monbuf, "Error: No search in progress. Start a search with ft or fh.\n");
monprintf(monbuf);
}
debuggerUsage("fr");
return;
};
if (n == 2)
sscanf(args[1], "%u", &SearchMaxMatches);
debuggerDoSearch();
} else
debuggerUsage("fr");
};
void debuggerCopyByte(int n, char** args)
{
uint32_t source;
uint32_t dest;
uint32_t number = 1;
uint32_t reps = 1;
if (n > 5 || n < 3) {
debuggerUsage("copyb");
}
if (n == 5) {
if (!dexp_eval(args[4], &reps)) {
{
sprintf(monbuf, "Invalid expression in repetition number.\n");
monprintf(monbuf);
}
}
}
if (n > 3) {
if (!dexp_eval(args[3], &number)) {
{
sprintf(monbuf, "Invalid expression in number of copy units.\n");
monprintf(monbuf);
}
}
}
if (!dexp_eval(args[1], &source)) {
{
sprintf(monbuf, "Invalid expression in source address.\n");
monprintf(monbuf);
}
return;
}
if (!dexp_eval(args[2], &dest)) {
{
sprintf(monbuf, "Invalid expression in destination address.\n");
monprintf(monbuf);
}
}
for (uint32_t j = 0; j < reps; j++) {
for (uint32_t i = 0; i < number; i++) {
debuggerWriteByte(dest + i, debuggerReadByte(source + i));
}
dest += number;
}
}
void debuggerCopyHalfWord(int n, char** args)
{
uint32_t source;
uint32_t dest;
uint32_t number = 2;
uint32_t reps = 1;
if (n > 5 || n < 3) {
debuggerUsage("copyh");
}
if (n == 5) {
if (!dexp_eval(args[4], &reps)) {
{
sprintf(monbuf, "Invalid expression in repetition number.\n");
monprintf(monbuf);
}
}
}
if (n > 3) {
if (!dexp_eval(args[3], &number)) {
{
sprintf(monbuf, "Invalid expression in number of copy units.\n");
monprintf(monbuf);
}
}
number = number << 1;
}
if (!dexp_eval(args[1], &source)) {
{
sprintf(monbuf, "Invalid expression in source address.\n");
monprintf(monbuf);
}
return;
}
if (!dexp_eval(args[2], &dest)) {
{
sprintf(monbuf, "Invalid expression in destination address.\n");
monprintf(monbuf);
}
}
for (uint32_t j = 0; j < reps; j++) {
for (uint32_t i = 0; i < number; i += 2) {
debuggerWriteHalfWord(dest + i, debuggerReadHalfWord(source + i));
}
dest += number;
}
}
void debuggerCopyWord(int n, char** args)
{
uint32_t source;
uint32_t dest;
uint32_t number = 4;
uint32_t reps = 1;
if (n > 5 || n < 3) {
debuggerUsage("copyw");
}
if (n == 5) {
if (!dexp_eval(args[4], &reps)) {
{
sprintf(monbuf, "Invalid expression in repetition number.\n");
monprintf(monbuf);
}
}
}
if (n > 3) {
if (!dexp_eval(args[3], &number)) {
{
sprintf(monbuf, "Invalid expression in number of copy units.\n");
monprintf(monbuf);
}
}
number = number << 2;
}
if (!dexp_eval(args[1], &source)) {
{
sprintf(monbuf, "Invalid expression in source address.\n");
monprintf(monbuf);
}
return;
}
if (!dexp_eval(args[2], &dest)) {
{
sprintf(monbuf, "Invalid expression in destination address.\n");
monprintf(monbuf);
}
}
for (uint32_t j = 0; j < reps; j++) {
for (uint32_t i = 0; i < number; i += 4) {
debuggerWriteMemory(dest + i, debuggerReadMemory(source + i));
}
dest += number;
}
}
void debuggerIoVideo()
{
{
sprintf(monbuf, "DISPCNT = %04x\n", DISPCNT);
monprintf(monbuf);
}
{
sprintf(monbuf, "DISPSTAT = %04x\n", DISPSTAT);
monprintf(monbuf);
}
{
sprintf(monbuf, "VCOUNT = %04x\n", VCOUNT);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG0CNT = %04x\n", BG0CNT);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG1CNT = %04x\n", BG1CNT);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG2CNT = %04x\n", BG2CNT);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG3CNT = %04x\n", BG3CNT);
monprintf(monbuf);
}
{
sprintf(monbuf, "WIN0H = %04x\n", WIN0H);
monprintf(monbuf);
}
{
sprintf(monbuf, "WIN0V = %04x\n", WIN0V);
monprintf(monbuf);
}
{
sprintf(monbuf, "WIN1H = %04x\n", WIN1H);
monprintf(monbuf);
}
{
sprintf(monbuf, "WIN1V = %04x\n", WIN1V);
monprintf(monbuf);
}
{
sprintf(monbuf, "WININ = %04x\n", WININ);
monprintf(monbuf);
}
{
sprintf(monbuf, "WINOUT = %04x\n", WINOUT);
monprintf(monbuf);
}
{
sprintf(monbuf, "MOSAIC = %04x\n", MOSAIC);
monprintf(monbuf);
}
{
sprintf(monbuf, "BLDMOD = %04x\n", BLDMOD);
monprintf(monbuf);
}
{
sprintf(monbuf, "COLEV = %04x\n", COLEV);
monprintf(monbuf);
}
{
sprintf(monbuf, "COLY = %04x\n", COLY);
monprintf(monbuf);
}
}
void debuggerIoVideo2()
{
{
sprintf(monbuf, "BG0HOFS = %04x\n", BG0HOFS);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG0VOFS = %04x\n", BG0VOFS);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG1HOFS = %04x\n", BG1HOFS);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG1VOFS = %04x\n", BG1VOFS);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG2HOFS = %04x\n", BG2HOFS);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG2VOFS = %04x\n", BG2VOFS);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG3HOFS = %04x\n", BG3HOFS);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG3VOFS = %04x\n", BG3VOFS);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG2PA = %04x\n", BG2PA);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG2PB = %04x\n", BG2PB);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG2PC = %04x\n", BG2PC);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG2PD = %04x\n", BG2PD);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG2X = %08x\n", (BG2X_H << 16) | BG2X_L);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG2Y = %08x\n", (BG2Y_H << 16) | BG2Y_L);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG3PA = %04x\n", BG3PA);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG3PB = %04x\n", BG3PB);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG3PC = %04x\n", BG3PC);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG3PD = %04x\n", BG3PD);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG3X = %08x\n", (BG3X_H << 16) | BG3X_L);
monprintf(monbuf);
}
{
sprintf(monbuf, "BG3Y = %08x\n", (BG3Y_H << 16) | BG3Y_L);
monprintf(monbuf);
}
}
void debuggerIoDMA()
{
{
sprintf(monbuf, "DM0SAD = %08x\n", (DM0SAD_H << 16) | DM0SAD_L);
monprintf(monbuf);
}
{
sprintf(monbuf, "DM0DAD = %08x\n", (DM0DAD_H << 16) | DM0DAD_L);
monprintf(monbuf);
}
{
sprintf(monbuf, "DM0CNT = %08x\n", (DM0CNT_H << 16) | DM0CNT_L);
monprintf(monbuf);
}
{
sprintf(monbuf, "DM1SAD = %08x\n", (DM1SAD_H << 16) | DM1SAD_L);
monprintf(monbuf);
}
{
sprintf(monbuf, "DM1DAD = %08x\n", (DM1DAD_H << 16) | DM1DAD_L);
monprintf(monbuf);
}
{
sprintf(monbuf, "DM1CNT = %08x\n", (DM1CNT_H << 16) | DM1CNT_L);
monprintf(monbuf);
}
{
sprintf(monbuf, "DM2SAD = %08x\n", (DM2SAD_H << 16) | DM2SAD_L);
monprintf(monbuf);
}
{
sprintf(monbuf, "DM2DAD = %08x\n", (DM2DAD_H << 16) | DM2DAD_L);
monprintf(monbuf);
}
{
sprintf(monbuf, "DM2CNT = %08x\n", (DM2CNT_H << 16) | DM2CNT_L);
monprintf(monbuf);
}
{
sprintf(monbuf, "DM3SAD = %08x\n", (DM3SAD_H << 16) | DM3SAD_L);
monprintf(monbuf);
}
{
sprintf(monbuf, "DM3DAD = %08x\n", (DM3DAD_H << 16) | DM3DAD_L);
monprintf(monbuf);
}
{
sprintf(monbuf, "DM3CNT = %08x\n", (DM3CNT_H << 16) | DM3CNT_L);
monprintf(monbuf);
}
}
void debuggerIoTimer()
{
{
sprintf(monbuf, "TM0D = %04x\n", TM0D);
monprintf(monbuf);
}
{
sprintf(monbuf, "TM0CNT = %04x\n", TM0CNT);
monprintf(monbuf);
}
{
sprintf(monbuf, "TM1D = %04x\n", TM1D);
monprintf(monbuf);
}
{
sprintf(monbuf, "TM1CNT = %04x\n", TM1CNT);
monprintf(monbuf);
}
{
sprintf(monbuf, "TM2D = %04x\n", TM2D);
monprintf(monbuf);
}
{
sprintf(monbuf, "TM2CNT = %04x\n", TM2CNT);
monprintf(monbuf);
}
{
sprintf(monbuf, "TM3D = %04x\n", TM3D);
monprintf(monbuf);
}
{
sprintf(monbuf, "TM3CNT = %04x\n", TM3CNT);
monprintf(monbuf);
}
}
void debuggerIoMisc()
{
{
sprintf(monbuf, "P1 = %04x\n", P1);
monprintf(monbuf);
}
{
sprintf(monbuf, "IE = %04x\n", IE);
monprintf(monbuf);
}
{
sprintf(monbuf, "IF = %04x\n", IF);
monprintf(monbuf);
}
{
sprintf(monbuf, "IME = %04x\n", IME);
monprintf(monbuf);
}
}
void debuggerIo(int n, char** args)
{
if (n == 1) {
debuggerIoVideo();
return;
}
if (!strcmp(args[1], "video"))
debuggerIoVideo();
else if (!strcmp(args[1], "video2"))
debuggerIoVideo2();
else if (!strcmp(args[1], "dma"))
debuggerIoDMA();
else if (!strcmp(args[1], "timer"))
debuggerIoTimer();
else if (!strcmp(args[1], "misc"))
debuggerIoMisc();
else {
sprintf(monbuf, "Unrecognized option %s\n", args[1]);
monprintf(monbuf);
}
}
#define ASCII(c) (c)<32 ? '.' : (c)> 127 ? '.' : (c)
bool canUseTbl = true;
bool useWordSymbol = false;
bool thereIsATable = false;
char** wordSymbol;
bool isTerminator[256];
bool isNewline[256];
bool isTab[256];
uint8_t largestSymbol = 1;
void freeWordSymbolContents()
{
for (int i = 0; i < 256; i++) {
if (wordSymbol[i])
free(wordSymbol[i]);
wordSymbol[i] = NULL;
isTerminator[i] = false;
isNewline[i] = false;
isTab[i] = false;
}
}
void freeWordSymbol()
{
useWordSymbol = false;
thereIsATable = false;
free(wordSymbol);
largestSymbol = 1;
}
void debuggerReadCharTable(int n, char** args)
{
if (n == 2) {
if (!canUseTbl) {
{
sprintf(monbuf, "Cannot operate over character table, as it was disabled.\n");
monprintf(monbuf);
}
return;
}
if (strcmp(args[1], "none") == 0) {
freeWordSymbol();
{
sprintf(monbuf, "Cleared table. Reverted to ASCII.\n");
monprintf(monbuf);
}
return;
}
FILE* tlb = fopen(args[1], "r");
if (!tlb) {
{
sprintf(monbuf, "Could not open specified file. Abort.\n");
monprintf(monbuf);
}
return;
}
char buffer[30];
uint32_t slot;
char* character = (char*)calloc(10, sizeof(char));
wordSymbol = (char**)calloc(256, sizeof(char*));
while (fgets(buffer, 30, tlb)) {
sscanf(buffer, "%02x=%s", &slot, character);
if (character[0]) {
if (strlen(character) == 4) {
if ((character[0] == '<') && (character[1] == '\\') && (character[3] == '>')) {
if (character[2] == '0') {
isTerminator[slot] = true;
}
if (character[2] == 'n') {
isNewline[slot] = true;
}
if (character[2] == 't') {
isTab[slot] = true;
}
continue;
} else
wordSymbol[slot] = character;
} else
wordSymbol[slot] = character;
} else
wordSymbol[slot] = (char*)' ';
if (largestSymbol < strlen(character))
largestSymbol = strlen(character);
character = (char*)malloc(10);
}
useWordSymbol = true;
thereIsATable = true;
} else {
debuggerUsage("tbl");
}
}
void printCharGroup(uint32_t addr, bool useAscii)
{
for (int i = 0; i < 16; i++) {
if (useWordSymbol && !useAscii) {
char* c = wordSymbol[debuggerReadByte(addr + i)];
int j;
if (c) {
{
sprintf(monbuf, "%s", c);
monprintf(monbuf);
}
j = strlen(c);
} else {
j = 0;
}
while (j < largestSymbol) {
{
sprintf(monbuf, " ");
monprintf(monbuf);
}
j++;
}
} else {
{
sprintf(monbuf, "%c", ASCII(debuggerReadByte(addr + i)));
monprintf(monbuf);
}
}
}
}
void debuggerMemoryByte(int n, char** args)
{
if (n == 2) {
uint32_t addr = 0;
if (!dexp_eval(args[1], &addr)) {
{
sprintf(monbuf, "Invalid expression\n");
monprintf(monbuf);
}
return;
}
for (int loop = 0; loop < 16; loop++) {
{
sprintf(monbuf, "%08x ", addr);
monprintf(monbuf);
}
for (int j = 0; j < 16; j++) {
{
sprintf(monbuf, "%02x ", debuggerReadByte(addr + j));
monprintf(monbuf);
}
}
printCharGroup(addr, true);
{
sprintf(monbuf, "\n");
monprintf(monbuf);
}
addr += 16;
}
} else
debuggerUsage("mb");
}
void debuggerMemoryHalfWord(int n, char** args)
{
if (n == 2) {
uint32_t addr = 0;
if (!dexp_eval(args[1], &addr)) {
{
sprintf(monbuf, "Invalid expression\n");
monprintf(monbuf);
}
return;
}
addr = addr & 0xfffffffe;
for (int loop = 0; loop < 16; loop++) {
{
sprintf(monbuf, "%08x ", addr);
monprintf(monbuf);
}
for (int j = 0; j < 16; j += 2) {
{
sprintf(monbuf, "%02x%02x ", debuggerReadByte(addr + j + 1), debuggerReadByte(addr + j));
monprintf(monbuf);
}
}
printCharGroup(addr, true);
{
sprintf(monbuf, "\n");
monprintf(monbuf);
}
addr += 16;
}
} else
debuggerUsage("mh");
}
void debuggerMemoryWord(int n, char** args)
{
if (n == 2) {
uint32_t addr = 0;
if (!dexp_eval(args[1], &addr)) {
{
sprintf(monbuf, "Invalid expression\n");
monprintf(monbuf);
}
return;
}
addr = addr & 0xfffffffc;
for (int loop = 0; loop < 16; loop++) {
{
sprintf(monbuf, "%08x ", addr);
monprintf(monbuf);
}
for (int j = 0; j < 16; j += 4) {
{
sprintf(monbuf, "%02x%02x%02x%02x ", debuggerReadByte(addr + j + 3), debuggerReadByte(addr + j + 2), debuggerReadByte(addr + j + 1), debuggerReadByte(addr + j));
monprintf(monbuf);
}
}
printCharGroup(addr, true);
{
sprintf(monbuf, "\n");
monprintf(monbuf);
}
addr += 16;
}
} else
debuggerUsage("mw");
}
void debuggerStringRead(int n, char** args)
{
if (n == 2) {
uint32_t addr = 0;
if (!dexp_eval(args[1], &addr)) {
{
sprintf(monbuf, "Invalid expression\n");
monprintf(monbuf);
}
return;
}
for (int i = 0; i < 512; i++) {
uint8_t slot = debuggerReadByte(addr + i);
if (useWordSymbol) {
if (isTerminator[slot]) {
{
sprintf(monbuf, "\n");
monprintf(monbuf);
}
return;
} else if (isNewline[slot]) {
{
sprintf(monbuf, "\n");
monprintf(monbuf);
}
} else if (isTab[slot]) {
{
sprintf(monbuf, "\t");
monprintf(monbuf);
}
} else {
if (wordSymbol[slot]) {
{
sprintf(monbuf, "%s", wordSymbol[slot]);
monprintf(monbuf);
}
}
}
} else {
{
sprintf(monbuf, "%c", ASCII(slot));
monprintf(monbuf);
}
}
}
} else
debuggerUsage("ms");
}
void debuggerRegisters(int, char**)
{
{
sprintf(monbuf, "R00=%08x R04=%08x R08=%08x R12=%08x\n", reg[0].I, reg[4].I, reg[8].I, reg[12].I);
monprintf(monbuf);
}
{
sprintf(monbuf, "R01=%08x R05=%08x R09=%08x R13=%08x\n", reg[1].I, reg[5].I, reg[9].I, reg[13].I);
monprintf(monbuf);
}
{
sprintf(monbuf, "R02=%08x R06=%08x R10=%08x R14=%08x\n", reg[2].I, reg[6].I, reg[10].I, reg[14].I);
monprintf(monbuf);
}
{
sprintf(monbuf, "R03=%08x R07=%08x R11=%08x R15=%08x\n", reg[3].I, reg[7].I, reg[11].I, reg[15].I);
monprintf(monbuf);
}
{
sprintf(monbuf, "CPSR=%08x (%c%c%c%c%c%c%c Mode: %02x)\n",
reg[16].I,
(N_FLAG ? 'N' : '.'),
(Z_FLAG ? 'Z' : '.'),
(C_FLAG ? 'C' : '.'),
(V_FLAG ? 'V' : '.'),
(armIrqEnable ? '.' : 'I'),
((!(reg[16].I & 0x40)) ? '.' : 'F'),
(armState ? '.' : 'T'),
armMode);
monprintf(monbuf);
}
}
void debuggerExecuteCommands(int n, char** args)
{
if (n == 1) {
{
sprintf(monbuf, "%s requires at least one pathname to execute.", args[0]);
monprintf(monbuf);
}
return;
} else {
char buffer[4096];
n--;
args++;
while (n) {
FILE* toExec = fopen(args[0], "r");
if (toExec) {
while (fgets(buffer, 4096, toExec)) {
std::string buf(buffer);
dbgExecute(buf);
if (!debugger || !emulating) {
return;
}
}
} else {
sprintf(monbuf, "Could not open %s. Will not be executed.\n", args[0]);
monprintf(monbuf);
}
args++;
n--;
}
}
}
void debuggerSetRadix(int argc, char** argv)
{
if (argc != 2)
debuggerUsage(argv[0]);
else {
int r = atoi(argv[1]);
bool error = false;
switch (r) {
case 10:
debuggerRadix = 0;
break;
case 8:
debuggerRadix = 2;
break;
case 16:
debuggerRadix = 1;
break;
default:
error = true;
{
sprintf(monbuf, "Unknown radix %d. Valid values are 8, 10 and 16.\n", r);
monprintf(monbuf);
}
break;
}
if (!error) {
sprintf(monbuf, "Radix set to %d\n", r);
monprintf(monbuf);
}
}
}
void debuggerSymbols(int argc, char** argv)
{
int i = 0;
uint32_t value;
uint32_t size;
int type;
bool match = false;
int matchSize = 0;
char* matchStr = NULL;
if (argc == 2) {
match = true;
matchSize = strlen(argv[1]);
matchStr = argv[1];
}
{
sprintf(monbuf, "Symbol Value Size Type \n");
monprintf(monbuf);
}
{
sprintf(monbuf, "-------------------- ------- -------- -------\n");
monprintf(monbuf);
}
const char* s = NULL;
while ((s = elfGetSymbol(i, &value, &size, &type))) {
if (*s) {
if (match) {
if (strncmp(s, matchStr, matchSize) != 0) {
i++;
continue;
}
}
const char* ts = "?";
switch (type) {
case 2:
ts = "ARM";
break;
case 0x0d:
ts = "THUMB";
break;
case 1:
ts = "DATA";
break;
}
{
sprintf(monbuf, "%-20s %08x %08x %-7s\n", s, value, size, ts);
monprintf(monbuf);
}
}
i++;
}
}
void debuggerWhere(int n, char** args)
{
(void)n; // unused params
(void)args; // unused params
void elfPrintCallChain(uint32_t);
elfPrintCallChain(armNextPC);
}
void debuggerVar(int n, char** args)
{
uint32_t val;
if (n < 2) {
dexp_listVars();
return;
}
if (strcmp(args[1], "set") == 0) {
if (n < 4) {
{
sprintf(monbuf, "No expression specified.\n");
monprintf(monbuf);
}
return;
}
if (!dexp_eval(args[3], &val)) {
{
sprintf(monbuf, "Invalid expression.\n");
monprintf(monbuf);
}
return;
}
dexp_setVar(args[2], val);
{
sprintf(monbuf, "%s = $%08x\n", args[2], val);
monprintf(monbuf);
}
return;
}
if (strcmp(args[1], "list") == 0) {
dexp_listVars();
return;
}
if (strcmp(args[1], "save") == 0) {
if (n < 3) {
{
sprintf(monbuf, "No file specified.\n");
monprintf(monbuf);
}
return;
}
dexp_saveVars(args[2]);
return;
}
if (strcmp(args[1], "load") == 0) {
if (n < 3) {
{
sprintf(monbuf, "No file specified.\n");
monprintf(monbuf);
}
return;
}
dexp_loadVars(args[2]);
return;
}
{
sprintf(monbuf, "Unrecognized sub-command.\n");
monprintf(monbuf);
}
}
bool debuggerBreakOnExecution(uint32_t address, uint8_t state)
{
(void)state; // unused params
if (dontBreakNow)
return false;
if (debuggerInDB(address))
return false;
if (!doesBreak(address, armState ? 0x44 : 0x88))
return false;
{
sprintf(monbuf, "Breakpoint (on %s) address %08x\n", (armState ? "ARM" : "Thumb"), address);
monprintf(monbuf);
}
debugger = true;
return true;
}
bool debuggerBreakOnRead(uint32_t address, int size)
{
(void)size; // unused params
if (dontBreakNow)
return false;
if (debuggerInDB(armState ? reg[15].I - 4 : reg[15].I - 2))
return false;
if (!doesBreak(address, 0x22))
return false;
//if (size == 2)
// monprintf("Breakpoint (on read) address %08x value:%08x\n",
// address, debuggerReadMemory(address));
//else if (size == 1)
// monprintf("Breakpoint (on read) address %08x value:%04x\n",
// address, debuggerReadHalfWord(address));
//else
// monprintf("Breakpoint (on read) address %08x value:%02x\n",
// address, debuggerReadByte(address));
debugger = true;
return true;
}
bool debuggerBreakOnWrite(uint32_t address, uint32_t value, int size)
{
(void)value; // unused params
(void)size; // unused params
if (dontBreakNow)
return false;
if (debuggerInDB(armState ? reg[15].I - 4 : reg[15].I - 2))
return false;
if (!doesBreak(address, 0x11))
return false;
//uint32_t lastValue;
//dexp_eval("old_value", &lastValue);
//if (size == 2)
// monprintf("Breakpoint (on write) address %08x old:%08x new:%08x\n",
// address, lastValue, value);
//else if (size == 1)
// monprintf("Breakpoint (on write) address %08x old:%04x new:%04x\n",
// address, (uint16_t)lastValue, (uint16_t)value);
//else
// monprintf("Breakpoint (on write) address %08x old:%02x new:%02x\n",
// address, (uint8_t)lastValue, (uint8_t)value);
debugger = true;
return true;
}
void debuggerBreakOnWrite(uint32_t address, uint32_t oldvalue, uint32_t value, int size, int t)
{
(void)oldvalue; // unused params
(void)t; // unused params
debuggerBreakOnWrite(address, value, size);
//uint32_t lastValue;
//dexp_eval("old_value", &lastValue);
//const char *type = "write";
//if (t == 2)
// type = "change";
//if (size == 2)
// monprintf("Breakpoint (on %s) address %08x old:%08x new:%08x\n",
// type, address, oldvalue, value);
//else if (size == 1)
// monprintf("Breakpoint (on %s) address %08x old:%04x new:%04x\n",
// type, address, (uint16_t)oldvalue, (uint16_t)value);
//else
// monprintf("Breakpoint (on %s) address %08x old:%02x new:%02x\n",
// type, address, (uint8_t)oldvalue, (uint8_t)value);
//debugger = true;
}
uint8_t getFlags(char* flagName)
{
for (int i = 0; flagName[i] != '\0'; i++) {
flagName[i] = toupper(flagName[i]);
}
if (strcmp(flagName, "ALWAYS") == 0) {
return 0x7;
}
if (strcmp(flagName, "NEVER") == 0) {
return 0x0;
}
uint8_t flag = 0;
bool negate_flag = false;
for (int i = 0; flagName[i] != '\0'; i++) {
switch (flagName[i]) {
case 'E':
flag |= 1;
break;
case 'G':
flag |= 2;
break;
case 'L':
flag |= 4;
break;
case 'S':
flag |= 8;
break;
case 'U':
flag &= 7;
break;
case 'N':
negate_flag = (!negate_flag);
break;
}
}
if (negate_flag) {
flag = ((flag & 8) | ((~flag) & 7));
}
return flag;
}
void debuggerBreakRegister(int n, char** args)
{
if (n != 3) {
{
sprintf(monbuf, "Incorrect usage of breg. Correct usage is breg <register> {flag} {value}\n");
monprintf(monbuf);
}
printFlagHelp();
return;
}
uint8_t reg = (uint8_t)getRegisterNumber(args[0]);
uint8_t flag = getFlags(args[1]);
uint32_t value;
if (!dexp_eval(args[2], &value)) {
{
sprintf(monbuf, "Invalid expression.\n");
monprintf(monbuf);
}
return;
}
if (flag != 0) {
addBreakRegToList(reg, flag, value);
{
sprintf(monbuf, "Added breakpoint on register R%02d, value %08x\n", reg, value);
monprintf(monbuf);
}
}
return;
}
void debuggerBreakRegisterClear(int n, char** args)
{
if (n > 0) {
int r = getRegisterNumber(args[0]);
if (r >= 0) {
clearParticularRegListBreaks(r);
{
sprintf(monbuf, "Cleared all Register breakpoints for %s.\n", args[0]);
monprintf(monbuf);
}
}
} else {
clearBreakRegList();
{
sprintf(monbuf, "Cleared all Register breakpoints.\n");
monprintf(monbuf);
}
}
}
void debuggerBreakRegisterDelete(int n, char** args)
{
if (n < 2) {
{
sprintf(monbuf, "Illegal use of Break register delete:\n Correct usage requires <register> <breakpointNo>.\n");
monprintf(monbuf);
}
return;
}
int r = getRegisterNumber(args[0]);
if ((r < 0) || (r > 16)) {
{
sprintf(monbuf, "Could not find a correct register number:\n Correct usage requires <register> <breakpointNo>.\n");
monprintf(monbuf);
}
return;
}
uint32_t num;
if (!dexp_eval(args[1], &num)) {
{
sprintf(monbuf, "Could not parse the breakpoint number:\n Correct usage requires <register> <breakpointNo>.\n");
monprintf(monbuf);
}
return;
}
deleteFromBreakRegList(r, num);
{
sprintf(monbuf, "Deleted Breakpoint %d of regsiter %s.\n", num, args[0]);
monprintf(monbuf);
}
}
//WARNING: Some old particle to new code conversion may convert a single command
//into two or more words. Such words are separated by space, so a new tokenizer can
//find them.
const char* replaceAlias(const char* lower_cmd, const char** aliasTable)
{
for (int i = 0; aliasTable[i]; i = i + 2) {
if (strcmp(lower_cmd, aliasTable[i]) == 0) {
return aliasTable[i + 1];
}
}
return lower_cmd;
}
const char* breakAliasTable[] = {
//actual beginning
"break", "b 0 0",
"breakpoint", "b 0 0",
"bp", "b 0 0",
"b", "b 0 0",
//break types
"thumb", "t",
"arm", "a",
"execution", "x",
"exec", "x",
"e", "x",
"exe", "x",
"x", "x",
"read", "r",
"write", "w",
"access", "i",
"acc", "i",
"io", "i",
"register", "g",
"reg", "g",
"any", "*",
//code modifiers
"clear", "c",
"clean", "c",
"cls", "c",
"list", "l",
"lst", "l",
"delete", "d",
"del", "d",
"make", "m",
/*
//old parts made to look like the new code parts
"bt", "b t m",
"ba", "b a m",
"bd", "b * d",
"bl", "b * l",
"bpr","b r m",
"bprc","b r c",
"bpw", "b w m",
"bpwc", "b w c",
"bt", "b t m",
*/
//and new parts made to look like old parts
"breg", "b g m",
"bregc", "b g c",
"bregd", "b g d",
"bregl", "b g l",
"blist", "b * l",
/*
"btc", "b t c",
"btd", "b t d",
"btl", "b t l",
"bac", "b a c",
"bad", "b a d",
"bal", "b a l",
"bx", "b x m",
"bxc", "b x c",
"bxd", "b x d",
"bxl", "b x l",
"bw", "b w m",
"bwc", "b w c",
"bwd", "b w d",
"bwl", "b w l",
"br", "b r m",
"brc", "b r c",
"brd", "b r d",
"brl", "b r l",
*/
"bio", "b i m",
"bioc", "b i c",
"biod", "b i d",
"biol", "b i l",
"bpio", "b i m",
"bpioc", "b i c",
"bpiod", "b i d",
"bpiol", "b i l",
/*
"bprd", "b r d",
"bprl", "b r l",
"bpwd", "b w d",
"bpwl", "b w l",
*/
NULL, NULL
};
char* breakSymbolCombo(char* command, int* length)
{
char* res = (char*)malloc(6);
res[0] = 'b';
res[1] = ' ';
res[2] = '0';
res[3] = ' ';
res[4] = '0';
int i = 1;
if (command[1] == 'p') {
i++;
}
while (i < *length) {
switch (command[i]) {
case 'l':
case 'c':
case 'd':
case 'm':
if (res[4] == '0')
res[4] = command[i];
else {
free(res);
return command;
}
break;
case '*':
case 't':
case 'a':
case 'x':
case 'r':
case 'w':
case 'i':
if (res[2] == '0')
res[2] = command[i];
else {
free(res);
return command;
}
break;
default:
free(res);
return command;
}
i++;
}
if (res[2] == '0')
res[2] = '*';
if (res[4] == '0')
res[4] = 'm';
*length = 5;
return res;
}
const char* typeMapping[] = { "'uint8_t", "'uint16_t", "'uint32_t", "'uint32_t", "'int8_t", "'int16_t", "'int32_t", "'int32_t" };
const char* compareFlagMapping[] = { "Never", "==", ">", ">=", "<", "<=", "!=", "<=>" };
struct intToString {
int value;
const char mapping[20];
};
struct intToString breakFlagMapping[] = {
{ 0x80, "Thumb" },
{ 0x40, "ARM" },
{ 0x20, "Read" },
{ 0x10, "Write" },
{ 0x8, "Thumb" },
{ 0x4, "ARM" },
{ 0x2, "Read" },
{ 0x1, "Write" },
{ 0x0, "None" }
};
//printers
void printCondition(struct ConditionalBreakNode* toPrint)
{
if (toPrint) {
const char* firstType = typeMapping[toPrint->exp_type_flags & 0x7];
const char* secondType = typeMapping[(toPrint->exp_type_flags >> 4) & 0x7];
const char* operand = compareFlagMapping[toPrint->cond_flags & 0x7];
{
sprintf(monbuf, "%s %s %s%s %s %s", firstType, toPrint->address,
((toPrint->cond_flags & 8) ? "s" : ""), operand,
secondType, toPrint->value);
monprintf(monbuf);
}
if (toPrint->next) {
{
sprintf(monbuf, " &&\n\t\t");
monprintf(monbuf);
}
printCondition(toPrint->next);
} else {
{
sprintf(monbuf, "\n");
monprintf(monbuf);
}
return;
}
}
}
void printConditionalBreak(struct ConditionalBreak* toPrint, bool printAddress)
{
if (toPrint) {
if (printAddress) {
sprintf(monbuf, "At %08x, ", toPrint->break_address);
monprintf(monbuf);
}
if (toPrint->type_flags & 0xf0) {
sprintf(monbuf, "Break Always on");
monprintf(monbuf);
}
bool hasPrevCond = false;
uint8_t flgs = 0x80;
while (flgs != 0) {
if (toPrint->type_flags & flgs) {
if (hasPrevCond) {
sprintf(monbuf, ",");
monprintf(monbuf);
}
for (int i = 0; i < 9; i++) {
if (breakFlagMapping[i].value == flgs) {
{
sprintf(monbuf, "\t%s", breakFlagMapping[i].mapping);
monprintf(monbuf);
}
hasPrevCond = true;
}
}
}
flgs = flgs >> 1;
if ((flgs == 0x8) && (toPrint->type_flags & 0xf)) {
{
sprintf(monbuf, "\n\t\tBreak conditional on");
monprintf(monbuf);
}
hasPrevCond = false;
}
}
{
sprintf(monbuf, "\n");
monprintf(monbuf);
}
if (toPrint->type_flags & 0xf && toPrint->firstCond) {
{
sprintf(monbuf, "With conditions:\n\t\t");
monprintf(monbuf);
}
printCondition(toPrint->firstCond);
} else if (toPrint->type_flags & 0xf) {
//should not happen
{
sprintf(monbuf, "No conditions detected, but conditional. Assumed always by default.\n");
monprintf(monbuf);
}
}
}
}
void printAllConditionals()
{
for (int i = 0; i < 16; i++) {
if (conditionals[i] != NULL) {
{
sprintf(monbuf, "Address range 0x%02x000000 breaks:\n", i);
monprintf(monbuf);
}
{
sprintf(monbuf, "-------------------------\n");
monprintf(monbuf);
}
struct ConditionalBreak* base = conditionals[i];
int count = 1;
uint32_t lastAddress = base->break_address;
{
sprintf(monbuf, "Address %08x\n-------------------------\n", lastAddress);
monprintf(monbuf);
}
while (base) {
if (lastAddress != base->break_address) {
lastAddress = base->break_address;
count = 1;
{
sprintf(monbuf, "-------------------------\n");
monprintf(monbuf);
}
{
sprintf(monbuf, "Address %08x\n-------------------------\n", lastAddress);
monprintf(monbuf);
}
}
{
sprintf(monbuf, "No.%d\t-->\t", count);
monprintf(monbuf);
}
printConditionalBreak(base, false);
count++;
base = base->next;
}
}
}
}
uint8_t printConditionalsFromAddress(uint32_t address)
{
uint8_t count = 1;
if (conditionals[address >> 24] != NULL) {
struct ConditionalBreak* base = conditionals[address >> 24];
while (base) {
if (address == base->break_address) {
if (count == 1) {
{
sprintf(monbuf, "Address %08x\n-------------------------\n", address);
monprintf(monbuf);
}
}
{
sprintf(monbuf, "No.%d\t-->\t", count);
monprintf(monbuf);
}
printConditionalBreak(base, false);
count++;
}
if (address < base->break_address)
break;
base = base->next;
}
}
if (count == 1) {
{
sprintf(monbuf, "None\n");
monprintf(monbuf);
}
}
return count;
}
void printAllFlagConditionals(uint8_t flag, bool orMode)
{
int count = 1;
int actualCount = 1;
for (int i = 0; i < 16; i++) {
if (conditionals[i] != NULL) {
bool isCondStart = true;
struct ConditionalBreak* base = conditionals[i];
uint32_t lastAddress = base->break_address;
while (base) {
if (lastAddress != base->break_address) {
lastAddress = base->break_address;
count = 1;
actualCount = 1;
}
if (((base->type_flags & flag) == base->type_flags) || (orMode && (base->type_flags & flag))) {
if (actualCount == 1) {
if (isCondStart) {
{
sprintf(monbuf, "Address range 0x%02x000000 breaks:\n", i);
monprintf(monbuf);
}
{
sprintf(monbuf, "-------------------------\n");
monprintf(monbuf);
}
isCondStart = false;
}
{
sprintf(monbuf, "Address %08x\n-------------------------\n", lastAddress);
monprintf(monbuf);
}
}
{
sprintf(monbuf, "No.%d\t-->\t", count);
monprintf(monbuf);
}
printConditionalBreak(base, false);
actualCount++;
}
base = base->next;
count++;
}
}
}
}
void printAllFlagConditionalsWithAddress(uint32_t address, uint8_t flag, bool orMode)
{
int count = 1;
int actualCount = 1;
for (int i = 0; i < 16; i++) {
if (conditionals[i] != NULL) {
bool isCondStart = true;
struct ConditionalBreak* base = conditionals[i];
uint32_t lastAddress = base->break_address;
while (base) {
if (lastAddress != base->break_address) {
lastAddress = base->break_address;
count = 1;
actualCount = 1;
}
if ((lastAddress == address) && (((base->type_flags & flag) == base->type_flags) || (orMode && (base->type_flags & flag)))) {
if (actualCount == 1) {
if (isCondStart) {
{
sprintf(monbuf, "Address range 0x%02x000000 breaks:\n", i);
monprintf(monbuf);
}
{
sprintf(monbuf, "-------------------------\n");
monprintf(monbuf);
}
isCondStart = false;
}
{
sprintf(monbuf, "Address %08x\n-------------------------\n", lastAddress);
monprintf(monbuf);
}
}
{
sprintf(monbuf, "No.%d\t-->\t", count);
monprintf(monbuf);
}
printConditionalBreak(base, false);
actualCount++;
}
base = base->next;
count++;
}
}
}
}
void makeBreak(uint32_t address, uint8_t flags, char** expression, int n)
{
if (n >= 1) {
if (tolower(expression[0][0]) == 'i' && tolower(expression[0][1]) == 'f') {
expression = expression + 1;
n--;
if (n != 0) {
parseAndCreateConditionalBreaks(address, flags, expression, n);
return;
}
}
} else {
flags = flags << 0x4;
printConditionalBreak(addConditionalBreak(address, flags), true);
return;
}
}
void deleteBreak(uint32_t address, uint8_t flags, char** expression, int howToDelete)
{
bool applyOr = true;
if (howToDelete > 0) {
if (((expression[0][0] == '&') && !expression[0][1]) || ((tolower(expression[0][0]) == 'o') && (tolower(expression[0][1]) == 'n')) || ((tolower(expression[0][0]) == 'l') && (tolower(expression[0][1]) == 'y'))) {
applyOr = false;
howToDelete--;
expression++;
}
if (howToDelete > 0) {
uint32_t number = 0;
if (!dexp_eval(expression[0], &number)) {
{
sprintf(monbuf, "Invalid expression for number format.\n");
monprintf(monbuf);
}
return;
}
removeFlagFromConditionalBreakNo(address, (uint8_t)number, (flags | (flags >> 4)));
{
sprintf(monbuf, "Removed all specified breaks from %08x.\n", address);
monprintf(monbuf);
}
return;
}
removeConditionalWithAddressAndFlag(address, flags, applyOr);
removeConditionalWithAddressAndFlag(address, flags << 4, applyOr);
{
sprintf(monbuf, "Removed all specified breaks from %08x.\n", address);
monprintf(monbuf);
}
} else {
removeConditionalWithAddressAndFlag(address, flags, applyOr);
removeConditionalWithAddressAndFlag(address, flags << 4, applyOr);
{
sprintf(monbuf, "Removed all specified breaks from %08x.\n", address);
monprintf(monbuf);
}
}
return;
}
void clearBreaks(uint32_t address, uint8_t flags, char** expression, int howToClear)
{
(void)address; // unused params
(void)expression; // unused params
if (howToClear == 2) {
removeConditionalWithFlag(flags, true);
removeConditionalWithFlag(flags << 4, true);
} else {
removeConditionalWithFlag(flags, false);
removeConditionalWithFlag(flags << 4, false);
}
{
sprintf(monbuf, "Cleared all requested breaks.\n");
monprintf(monbuf);
}
}
void listBreaks(uint32_t address, uint8_t flags, char** expression, int howToList)
{
(void)expression; // unused params
flags |= (flags << 4);
if (howToList) {
printAllFlagConditionalsWithAddress(address, flags, true);
} else {
printAllFlagConditionals(flags, true);
}
{
sprintf(monbuf, "\n");
monprintf(monbuf);
}
}
void executeBreakCommands(int n, char** cmd)
{
char* command = cmd[0];
int len = strlen(command);
bool changed = false;
if (len <= 4) {
command = breakSymbolCombo(command, &len);
changed = (len == 5);
}
if (!changed) {
command = strdup(replaceAlias(cmd[0], breakAliasTable));
changed = (strcmp(cmd[0], command));
}
if (!changed) {
cmd[0][0] = '!';
return;
}
cmd++;
n--;
void (*operation)(uint32_t, uint8_t, char**, int) = &makeBreak; //the function to be called
uint8_t flag = 0;
uint32_t address = 0;
//if(strlen(command) == 1){
//Cannot happen, that would mean cmd[0] != b
//}
char target;
char ope;
if (command[2] == '0') {
if (n <= 0) {
{
sprintf(monbuf, "Invalid break command.\n");
monprintf(monbuf);
}
free(command);
return;
}
for (int i = 0; cmd[0][i]; i++) {
cmd[0][i] = tolower(cmd[0][i]);
}
const char* replaced = replaceAlias(cmd[0], breakAliasTable);
if (replaced == cmd[0]) {
target = '*';
} else {
target = replaced[0];
if ((target == 'c') || (target == 'd') || (target == 'l') || (target == 'm')) {
command[4] = target;
target = '*';
}
cmd++;
n--;
}
command[2] = target;
}
if (command[4] == '0') {
if (n <= 0) {
{
sprintf(monbuf, "Invalid break command.\n");
monprintf(monbuf);
}
free(command);
return;
}
for (int i = 0; cmd[0][i]; i++) {
cmd[0][i] = tolower(cmd[0][i]);
}
ope = replaceAlias(cmd[0], breakAliasTable)[0];
if ((ope == 'c') || (ope == 'd') || (ope == 'l') || (ope == 'm')) {
command[4] = ope;
cmd++;
n--;
} else {
command[4] = 'm';
}
}
switch (command[4]) {
case 'l':
operation = &listBreaks;
break;
case 'c':
operation = &clearBreaks;
break;
case 'd':
operation = &deleteBreak;
break;
case 'm':
default:
operation = &makeBreak;
};
switch (command[2]) {
case 'g':
switch (command[4]) {
case 'l':
debuggerBreakRegisterList((n > 0) && (tolower(cmd[0][0]) == 'v'));
return;
case 'c':
debuggerBreakRegisterClear(n, cmd);
return;
case 'd':
debuggerBreakRegisterDelete(n, cmd);
return;
case 'm':
debuggerBreakRegister(n, cmd);
default:
return;
};
return;
case '*':
flag = 0xf;
break;
case 't':
flag = 0x8;
break;
case 'a':
flag = 0x4;
break;
case 'x':
flag = 0xC;
break;
case 'r':
flag = 0x2;
break;
case 'w':
flag = 0x1;
break;
case 'i':
flag = 0x3;
break;
default:
free(command);
return;
};
free(command);
bool hasAddress = false;
if ((n >= 1) && (operation != clearBreaks)) {
if (!dexp_eval(cmd[0], &address)) {
{
sprintf(monbuf, "Invalid expression for address format.\n");
monprintf(monbuf);
}
return;
}
hasAddress = true;
}
if (operation == listBreaks) {
operation(address, flag, NULL, hasAddress);
return;
} else if (operation == clearBreaks) {
if (!hasAddress && (n >= 1)) {
if ((cmd[0][0] == '|' && cmd[0][1] == '|') || ((cmd[0][0] == 'O' || cmd[0][0] == 'o') && (cmd[0][1] == 'R' || cmd[0][1] == 'r'))) {
operation(address, flag, NULL, 2);
} else {
operation(address, flag, NULL, 0);
}
} else {
operation(address, flag, NULL, 0);
}
} else if (!hasAddress && (operation == deleteBreak)) {
{
sprintf(monbuf, "Delete breakpoint operation requires at least one address;\n");
monprintf(monbuf);
}
{
sprintf(monbuf, "Usage: break [type] delete [address] no.[number] --> Deletes breakpoint [number] of [address].\n");
monprintf(monbuf);
}
//{ sprintf(monbuf, "Usage: [delete Operand] [address] End [address] --> Deletes range between [address] and [end]\n"); monprintf(monbuf); }
{
sprintf(monbuf, "Usage: break [type] delete [address]\n --> Deletes all breakpoints of [type] on [address].");
monprintf(monbuf);
}
return;
} else if (!hasAddress && (operation == makeBreak)) {
{
sprintf(monbuf, "Can only create breakpoints if an address is provided");
monprintf(monbuf);
}
//print usage here
return;
} else {
operation(address, flag, cmd + 1, n - 1);
return;
}
//brkcmd_special_register:
switch (command[4]) {
case 'l':
debuggerBreakRegisterList((n > 0) && (tolower(cmd[0][0]) == 'v'));
return;
case 'c':
debuggerBreakRegisterClear(n, cmd);
return;
case 'd':
debuggerBreakRegisterDelete(n, cmd);
return;
case 'm':
debuggerBreakRegister(n, cmd);
default:
return;
};
return;
}
void debuggerDisable(int n, char** args)
{
if (n >= 3) {
debuggerUsage("disable");
return;
}
while (n > 1) {
int i = 0;
while (args[3 - n][i]) {
args[3 - n][i] = tolower(args[2 - n][i]);
i++;
}
if (strcmp(args[3 - n], "breg")) {
enableRegBreak = false;
{
sprintf(monbuf, "Break on register disabled.\n");
monprintf(monbuf);
}
} else if (strcmp(args[3 - n], "tbl")) {
canUseTbl = false;
useWordSymbol = false;
{
sprintf(monbuf, "Symbol table disabled.\n");
monprintf(monbuf);
}
} else {
{
sprintf(monbuf, "Invalid command. Only tbl and breg are accepted as commands\n");
monprintf(monbuf);
}
return;
}
n--;
}
}
void debuggerEnable(int n, char** args)
{
if (n >= 3) {
debuggerUsage("enable");
return;
}
while (n > 1) {
int i = 0;
while (args[3 - n][i]) {
args[3 - n][i] = tolower(args[2 - n][i]);
i++;
}
if (strcmp(args[3 - n], "breg")) {
enableRegBreak = true;
{
sprintf(monbuf, "Break on register enabled.\n");
monprintf(monbuf);
}
} else if (strcmp(args[3 - n], "tbl")) {
canUseTbl = true;
useWordSymbol = thereIsATable;
{
sprintf(monbuf, "Symbol table enabled.\n");
monprintf(monbuf);
}
} else {
{
sprintf(monbuf, "Invalid command. Only tbl and breg are accepted as commands\n");
monprintf(monbuf);
}
return;
}
n--;
}
}
DebuggerCommand debuggerCommands[] = {
//simple commands
{ "?", debuggerHelp, "Shows this help information. Type ? <command> for command help. Alias 'help', 'h'.", "[<command>]" },
// { "n", debuggerNext, "Executes the next instruction.", "[<count>]" },
// { "c", debuggerContinue, "Continues execution", NULL },
// // Hello command, shows Hello on the board
//{ "br", debuggerBreakRead, "Break on read", "{address} {size}" },
//{ "bw", debuggerBreakWrite, "Break on write", "{address} {size}" },
//{ "bt", debuggerBreakWrite, "Break on write", "{address} {size}" },
//{ "ba", debuggerBreakArm, "Adds an ARM breakpoint", "{address}" },
//{ "bd", debuggerBreakDelete, "Deletes a breakpoint", "<number>" },
//{ "bl", debuggerBreakList, "Lists breakpoints" },
//{ "bpr", debuggerBreakRead, "Break on read", "{address} {size}" },
//{ "bprc", debuggerBreakReadClear, "Clear break on read", NULL },
//{ "bpw", debuggerBreakWrite, "Break on write", "{address} {size}" },
//{ "bpwc", debuggerBreakWriteClear, "Clear break on write", NULL },
{ "breg", debuggerBreakRegister, "Breaks on a register specified value", "<register_number> {flag} {value}" },
{ "bregc", debuggerBreakRegisterClear, "Clears all break on register", "<register_number> {flag} {value}" },
//{ "bt", debuggerBreakThumb, "Adds a THUMB breakpoint", "{address}" }
// //diassemble commands
// { "d", debuggerDisassemble, "Disassembles instructions", "[<address> [<number>]]" },
// { "da", debuggerDisassembleArm, "Disassembles ARM instructions", "[{address} [{number}]]" },
// { "dt", debuggerDisassembleThumb, "Disassembles Thumb instructions", "[{address} [{number}]]" },
{ "db", debuggerDontBreak, "Don't break at the following address.", "[{address} [{number}]]" },
{ "dbc", debuggerDontBreakClear, "Clear the Don't Break list.", NULL },
{ "dload", debuggerDumpLoad, "Load raw data dump from file", "<file> {address}" },
{ "dsave", debuggerDumpSave, "Dump raw data to file", "<file> {address} {size}" },
// { "dn", debuggerDisassembleNear, "Disassembles instructions near PC", "[{number}]" },
{ "disable", debuggerDisable, "Disables operations.", "tbl|breg" },
{ "enable", debuggerEnable, "Enables operations.", "tbl|breg" },
{ "eb", debuggerEditByte, "Modify memory location (byte)", "{address} {value}*" },
{ "eh", debuggerEditHalfWord, "Modify memory location (half-word)", "{address} {value}*" },
{ "ew", debuggerEditWord, "Modify memory location (word)", "{address} {value}*" },
{ "er", debuggerEditRegister, "Modify register", "<register number> {value}" },
{ "eval", debuggerEval, "Evaluate expression", "{expression}" },
{ "fillb", debuggerFillByte, "Fills memory location (byte)", "{address} {value} {number of times}" },
{ "fillh", debuggerFillHalfWord, "Fills memory location (half-word)", "{address} {value} {number of times}" },
{ "fillw", debuggerFillWord, "Fills memory location (word)", "{address} {value} {number of times}" },
{ "copyb", debuggerCopyByte, "Copies memory content (byte)", "{address} {second address} {size} optional{repeat}" },
{ "copyh", debuggerCopyHalfWord, "Copies memory content (half-word)", "{address} {second address} {size} optional{repeat}" },
{ "copyw", debuggerCopyWord, "Copies memory content (word)", "{address} {second address} {size} optional{repeat}" },
{ "ft", debuggerFindText, "Search memory for ASCII-string.", "<start> [<max-result>] <string>" },
{ "fh", debuggerFindHex, "Search memory for hex-string.", "<start> [<max-result>] <hex-string>" },
{ "fr", debuggerFindResume, "Resume current search.", "[<max-result>]" },
{ "io", debuggerIo, "Show I/O registers status", "[video|video2|dma|timer|misc]" },
// { "load", debuggerReadState, "Loads a Fx type savegame", "<number>" },
{ "mb", debuggerMemoryByte, "Shows memory contents (bytes)", "{address}" },
{ "mh", debuggerMemoryHalfWord, "Shows memory contents (half-words)", "{address}" },
{ "mw", debuggerMemoryWord, "Shows memory contents (words)", "{address}" },
{ "ms", debuggerStringRead, "Shows memory contents (table string)", "{address}" },
{ "r", debuggerRegisters, "Shows ARM registers", NULL },
// { "rt", debuggerRunTo, "Run to address", "{address}" },
// { "rta", debuggerRunToArm, "Run to address (ARM)", "{address}" },
// { "rtt", debuggerRunToThumb, "Run to address (Thumb)", "{address}" },
// { "reset", debuggerResetSystem, "Resets the system", NULL },
// { "reload", debuggerReloadRom, "Reloads the ROM", "optional {rom path}" },
{ "execute", debuggerExecuteCommands, "Executes commands from a text file", "{file path}" },
// { "save", debuggerWriteState, "Creates a Fx type savegame", "<number>" },
// { "sbreak", debuggerBreak, "Adds a breakpoint on the given function", "<function>|<line>|<file:line>" },
{ "sradix", debuggerSetRadix, "Sets the print radix", "<radix>" },
// { "sprint", debuggerPrint, "Print the value of a expression (if known)", "[/x|/o|/d] <expression>" },
{ "ssymbols", debuggerSymbols, "List symbols", "[<symbol>]" },
//#ifndef FINAL_VERSION
// { "strace", debuggerDebug, "Sets the trace level", "<value>" },
//#endif
//#ifdef DEV_VERSION
// { "sverbose", debuggerVerbose, "Change verbose setting", "<value>" },
//#endif
{ "swhere", debuggerWhere, "Shows call chain", NULL },
{ "tbl", debuggerReadCharTable, "Loads a character table", "<file>" },
// { "trace", debuggerTrace, "Control tracer", "start|stop|file <file>" },
{ "var", debuggerVar, "Define variables", "<name> {variable}" },
{ NULL, NULL, NULL, NULL } // end marker
};
void printFlagHelp()
{
monprintf("Flags are combinations of six distinct characters:\n");
monprintf("\t\te --> Equal to;\n");
monprintf("\t\tg --> Greater than;\n");
monprintf("\t\tl --> Less than;\n");
monprintf("\t\ts --> signed;\n");
monprintf("\t\tu --> unsigned (assumed by ommision);\n");
monprintf("\t\tn --> not;\n");
monprintf("Ex: ge -> greater or equal; ne -> not equal; lg --> less or greater (same as not equal);\n");
monprintf("s and u parts cannot be used in the same line, and are not negated by n;\n");
monprintf("Special flags: always(all true), never(all false).\n");
}
void debuggerUsage(const char* cmd)
{
if (!strcmp(cmd, "break")) {
monprintf("Break command, composed of three parts:\n");
monprintf("Break (b, bp or break): Indicates a break command;\n");
monprintf("Type of break: Indicates the type of break the command applies to;\n");
monprintf("Command: Indicates the type of command to be applied.\n");
monprintf("Type Flags:\n\tt (thumb): The Thumb execution mode.\n");
monprintf("\ta (ARM): The ARM execution mode.\n");
monprintf("\tx (execution, exe, exec, e): Any execution mode.\n");
monprintf("\tr (read): When a read occurs.\n");
monprintf("\tw (write): When a write occurs.\n");
monprintf("\ti (io, access,acc): When memory access (read or write) occurs.\n");
monprintf("\tg (register, reg): Special On Register value change break.\n");
monprintf("\t* (any): On any occasion (except register change).Omission value.\n");
monprintf("Cmd Flags:\n\tm (make): Create a breakpoint.Default omission value.\n");
monprintf("\tl (list,lst): Lists all existing breakpoints of the specified type.\n");
monprintf("\td (delete,del): Deletes a specific breakpoint of the specified type.\n");
monprintf("\tc (clear, clean, cls): Erases all breakpoints of the specified type.\n");
monprintf("\n");
monprintf("All those flags can be combined in order to access the several break functions\n");
monprintf("EX: btc clears all breaks; bx, bxm creates a breakpoint on any type of execution.\n");
monprintf("All commands can be built by using [b|bp][TypeFlag][CommandFlag];\n");
monprintf("All commands can be built by using [b|bp|break] [TypeFlag|alias] [CommandFlag|alias];\n");
monprintf("Each command has separate arguments from each other.\nFor more details, use help b[reg|m|d|c|l]\n");
return;
}
if (!strcmp(cmd, "breg")) {
monprintf("Break on register command, special case of the break command.\n");
monprintf("It allows the user to break when a certain value is inside a register.\n");
monprintf("All register breaks are conditional.\n");
monprintf("Usage: breg [regName] [condition] [Expression].\n");
monprintf("regName is between r0 and r15 (PC, LR and SP included);\n");
monprintf("expression is an evaluatable expression whose value determines when to break;\n");
monprintf("condition is the condition to be evaluated in typeFlags.\n");
printFlagHelp();
monprintf("---------!!!WARNING!!!---------\n");
monprintf("Register checking and breaking is extremely expensive for the computer.\n");
monprintf("On one of the test machines, a maximum value of 600% for speedup collapsed\n");
monprintf("to 350% just from having them enabled.\n");
monprintf("If (or while) not needed, you can have a speedup by disabling them, using\n");
monprintf("disable breg.\n");
monprintf("Breg is disabled by default. Re-enable them using enable breg.\n");
monprintf("Use example: breg r0 ne 0x0 --> Breaks as soon as r0 is not 0.\n");
return;
}
if (!strcmp(cmd, "bm")) {
monprintf("Create breakpoint command. Used to place a breakpoint on a given address.\n");
monprintf("It allows for breaks on execution(any processor mode) and on access(r/w).\n");
monprintf("Breaks can be Conditional or Inconditional.\n\n");
monprintf("Inconditional breaks:\nUsage: [breakTag] [address]\n");
monprintf("Simplest of the two, the old type of breaks. Creates a breakpoint that, when\n");
monprintf("the given type flag occurs (like a read, or a run when in thumb mode), halts;\n\n");
monprintf("Conditional breaks:\n");
monprintf("Usage:\n\t[breakTag] [address] if {'<type> [expr] [cond] '<type> [expr] <&&,||>}\n");
monprintf("Where <> elements are optional, {} are repeateable;\n");
monprintf("[expression] are evaluatable expressions, in the usual VBA format\n(that is, eval acceptable);\n");
monprintf("type is the type of that expression. Uses C-like names. Omission means integer.\n");
monprintf("cond is the condition to be evaluated.\n");
monprintf("If && or || are not present, the chain of evaluation stops.\n");
monprintf("&& states the next condition must happen with the previous one, or the break\nfails.\n");
monprintf("|| states the next condition is independent from the last one, and break\nseparately.\n\n");
monprintf("Type can be:\n");
monprintf(" [uint8_t, b, byte],[uint16_t, h, hword, halfword],[uint32_t,w, word]\n");
monprintf(" [int8_t, sb, sbyte],[int16_t, sh, shword, short, shalfword],[int32_t, int, sw, word]\n");
monprintf("Types have to be preceded by a ' ex: 'int, 'uint8_t\n\n");
monprintf("Conditions may be:\n");
monprintf("C-like:\t\t[<], [<=], [>], [>=] , [==], [!= or <>]\n");
monprintf("ASM-like:\t[lt], [le], [gt], [ge] , [eq], [ne]\n\n");
monprintf("EX: bw 0x03005008 if old_value == 'uint32_t [0x03005008]\n");
monprintf("Breaks on write from 0x03005008, when the old_value variable, that is assigned\n");
monprintf("as the previous memory value when a write is performed, is equal to the new\ncontents of 0x03005008.\n\n");
monprintf("EX: bx 0x08000500 if r0 == 1 || r0 > 1 && r2 == 0 || 'uint8_t [r7] == 5\n");
monprintf("Breaks in either thumb or arm execution of 0x08000500, if r0's contents are 1,\n");
monprintf("or if r0's contents are bigger than 1 and r2 is equal to 0, or the content of\nthe address at r7(as byte) is equal to 5.\n");
monprintf("It will not break if r0 > 1 and r2 != 0.\n");
return;
}
if (!strcmp(cmd, "bl")) {
monprintf("List breakpoints command. Used to view breakpoints.\n");
monprintf("Usage: [breakTag] <address> <v>\n");
monprintf("It will list all breaks on the specified type (read, write..).\n");
monprintf("If (optional) address is included, it will try and list all breaks of that type\n");
monprintf("for that address.\n");
monprintf("The numbers shown on that list (No.) are the ones needed to delete it directly.\n");
monprintf("v option lists all requested values, even if empty.\n");
return;
}
if (!strcmp(cmd, "bc")) {
monprintf("Clear breakpoints command. Clears all specified breakpoints.\n");
monprintf("Usage: [breakTag] <or,||>\n");
monprintf("It will delete all breaks on all addresses for the specified type.\n");
monprintf("If (optional) or is included, it will try and delete all breaks associated with\n");
monprintf("the flags. EX: bic or --> Deletes all breaks on read and all on write.\n");
return;
}
if (!strcmp(cmd, "bd")) {
monprintf("Delete breakpoint command. Clears the specified breakpoint.\n");
monprintf("Usage: [breakTag] [address] <only> [number]\n");
monprintf("It will delete the numbered break on that addresses for the specified type.\n");
monprintf("If only is included, it will delete only breaks with the specified flag.\n");
monprintf("EX: bxd 0x8000000 only -->Deletes all breaks on 0x08000000 that break on both\n");
monprintf("arm and thumb modes. Thumb only or ARM only are unnafected.\n");
monprintf("EX: btd 0x8000000 5 -->Deletes the thumb break from the 5th break on 0x8000000.\n");
monprintf("---------!!!WARNING!!!---------\n");
monprintf("Break numbers are volatile, and may change at any time. before deleting any one\n");
monprintf("breakpoint, list them to see if the number hasn't changed. The numbers may\n");
monprintf("change only when you add or delete a breakpoint to that address. Numbers are \n");
monprintf("internal to each address.\n");
return;
}
for (int i = 0;; i++) {
if (debuggerCommands[i].name) {
if (!strcmp(debuggerCommands[i].name, cmd)) {
sprintf(monbuf, "%s %s\t%s\n",
debuggerCommands[i].name,
debuggerCommands[i].syntax ? debuggerCommands[i].syntax : "",
debuggerCommands[i].help);
monprintf(monbuf);
break;
}
} else {
{
sprintf(monbuf, "Unrecognized command '%s'.", cmd);
monprintf(monbuf);
}
break;
}
}
}
void debuggerHelp(int n, char** args)
{
if (n == 2) {
debuggerUsage(args[1]);
} else {
for (int i = 0;; i++) {
if (debuggerCommands[i].name) {
{
sprintf(monbuf, "%-10s%s\n", debuggerCommands[i].name, debuggerCommands[i].help);
monprintf(monbuf);
}
} else
break;
}
{
sprintf(monbuf, "%-10s%s\n", "break", "Breakpoint commands");
monprintf(monbuf);
}
}
}
char* strqtok(char* string, const char* ctrl)
{
static char* nexttoken = NULL;
char* str;
if (string != NULL)
str = string;
else {
if (nexttoken == NULL)
return NULL;
str = nexttoken;
};
char deli[32];
memset(deli, 0, 32 * sizeof(char));
while (*ctrl) {
deli[*ctrl >> 3] |= (1 << (*ctrl & 7));
ctrl++;
};
// can't allow to be set
deli['"' >> 3] &= ~(1 << ('"' & 7));
// jump over leading delimiters
while ((deli[*str >> 3] & (1 << (*str & 7))) && *str)
str++;
if (*str == '"') {
string = ++str;
// only break if another quote or end of string is found
while ((*str != '"') && *str)
str++;
} else {
string = str;
// break on delimiter
while (!(deli[*str >> 3] & (1 << (*str & 7))) && *str)
str++;
};
if (string == str) {
nexttoken = NULL;
return NULL;
} else {
if (*str) {
*str = 0;
nexttoken = str + 1;
} else
nexttoken = NULL;
return string;
};
};
void dbgExecute(char* toRun)
{
char* commands[40];
int commandCount = 0;
commands[0] = strqtok(toRun, " \t\n");
if (commands[0] == NULL)
return;
commandCount++;
while ((commands[commandCount] = strqtok(NULL, " \t\n"))) {
commandCount++;
if (commandCount == 40)
break;
}
//from here on, new algorithm.
// due to the division of functions, some steps have to be made
//first, convert the command name to a standart lowercase form
//if more lowercasing needed, do it on the caller.
for (int i = 0; commands[0][i]; i++) {
commands[0][i] = tolower(commands[0][i]);
}
// checks if it is a quit command, if so quits.
//if (isQuitCommand(commands[0])){
// if (quitConfirm()){
// debugger = false;
// emulating = false;
// }
// return;
//}
commands[0] = (char*)replaceAlias(commands[0], cmdAliasTable);
if (commands[0][0] == 'b') {
executeBreakCommands(commandCount, commands);
if (commands[0][0] == '!')
commands[0][0] = 'b';
else
return;
}
//although it mights seem weird, the old step is the last one to be executed.
for (int j = 0;; j++) {
if (debuggerCommands[j].name == NULL) {
{
sprintf(monbuf, "Unrecognized command %s. Type h for help.\n", commands[0]);
monprintf(monbuf);
}
return;
}
if (!strcmp(commands[0], debuggerCommands[j].name)) {
debuggerCommands[j].function(commandCount, commands);
return;
}
}
}
void dbgExecute(std::string& cmd)
{
char* dbgCmd = new char[cmd.length() + 1];
strcpy(dbgCmd, cmd.c_str());
dbgExecute(dbgCmd);
delete[] dbgCmd;
}
int remoteTcpSend(char* data, int len)
{
return send(remoteSocket, data, len, 0);
}
int remoteTcpRecv(char* data, int len)
{
return recv(remoteSocket, data, len, 0);
}
bool remoteTcpInit()
{
if (remoteSocket == -1) {
#ifdef _WIN32
WSADATA wsaData;
int error = WSAStartup(MAKEWORD(1, 1), &wsaData);
#endif // _WIN32
SOCKET s = socket(PF_INET, SOCK_STREAM, 0);
remoteListenSocket = s;
if (s < 0) {
fprintf(stderr, "Error opening socket\n");
exit(-1);
}
int tmp = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&tmp, sizeof(tmp));
// char hostname[256];
// gethostname(hostname, 256);
// hostent *ent = gethostbyname(hostname);
// unsigned long a = *((unsigned long *)ent->h_addr);
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(remotePort);
addr.sin_addr.s_addr = htonl(0);
int count = 0;
while (count < 3) {
if (bind(s, (sockaddr*)&addr, sizeof(addr))) {
addr.sin_port = htons(ntohs(addr.sin_port) + 1);
} else
break;
}
if (count == 3) {
fprintf(stderr, "Error binding \n");
exit(-1);
}
fprintf(stderr, "Listening for a connection at port %d\n",
ntohs(addr.sin_port));
if (listen(s, 1)) {
fprintf(stderr, "Error listening\n");
exit(-1);
}
socklen_t len = sizeof(addr);
#ifdef _WIN32
int flag = 0;
ioctlsocket(s, FIONBIO, (unsigned long*)&flag);
#endif // _WIN32
SOCKET s2 = accept(s, (sockaddr*)&addr, &len);
if (s2 > 0) {
fprintf(stderr, "Got a connection from %s %d\n",
inet_ntoa((in_addr)addr.sin_addr),
ntohs(addr.sin_port));
} else {
#ifdef _WIN32
int error = WSAGetLastError();
#endif // _WIN32
}
//char dummy;
//recv(s2, &dummy, 1, 0);
//if(dummy != '+') {
// fprintf(stderr, "ACK not received\n");
// exit(-1);
//}
remoteSocket = s2;
// close(s);
}
return true;
}
void remoteTcpCleanUp()
{
if (remoteSocket > 0) {
fprintf(stderr, "Closing remote socket\n");
close(remoteSocket);
remoteSocket = -1;
}
if (remoteListenSocket > 0) {
fprintf(stderr, "Closing listen socket\n");
close(remoteListenSocket);
remoteListenSocket = -1;
}
}
int remotePipeSend(char* data, int len)
{
int res = write(1, data, len);
return res;
}
int remotePipeRecv(char* data, int len)
{
int res = read(0, data, len);
return res;
}
bool remotePipeInit()
{
// char dummy;
// if (read(0, &dummy, 1) == 1)
// {
// if(dummy != '+') {
// fprintf(stderr, "ACK not received\n");
// exit(-1);
// }
// }
return true;
}
void remotePipeCleanUp()
{
}
void remoteSetPort(int port)
{
remotePort = port;
}
void remoteSetProtocol(int p)
{
if (p == 0) {
remoteSendFnc = remoteTcpSend;
remoteRecvFnc = remoteTcpRecv;
remoteInitFnc = remoteTcpInit;
remoteCleanUpFnc = remoteTcpCleanUp;
} else {
remoteSendFnc = remotePipeSend;
remoteRecvFnc = remotePipeRecv;
remoteInitFnc = remotePipeInit;
remoteCleanUpFnc = remotePipeCleanUp;
}
}
void remoteInit()
{
if (remoteInitFnc)
remoteInitFnc();
}
void remotePutPacket(const char* packet)
{
const char* hex = "0123456789abcdef";
size_t count = strlen(packet);
char* buffer = new char[count + 5];
unsigned char csum = 0;
char* p = buffer;
*p++ = '$';
for (size_t i = 0; i < count; i++) {
csum += packet[i];
*p++ = packet[i];
}
*p++ = '#';
*p++ = hex[csum >> 4];
*p++ = hex[csum & 15];
*p++ = 0;
//log("send: %s\n", buffer);
char c = 0;
while (c != '+') {
remoteSendFnc(buffer, (int)count + 4);
if (remoteRecvFnc(&c, 1) < 0) {
delete[] buffer;
return;
}
// fprintf(stderr,"sent:%s recieved:%c\n",buffer,c);
}
delete[] buffer;
}
void remoteOutput(const char* s, uint32_t addr)
{
char buffer[16384];
char* d = buffer;
*d++ = 'O';
if (s) {
char c = *s++;
while (c) {
sprintf(d, "%02x", c);
d += 2;
c = *s++;
}
} else {
char c = debuggerReadByte(addr);
addr++;
while (c) {
sprintf(d, "%02x", c);
d += 2;
c = debuggerReadByte(addr);
addr++;
}
}
remotePutPacket(buffer);
// fprintf(stderr, "Output sent %s\n", buffer);
}
void remoteSendSignal()
{
char buffer[1024];
sprintf(buffer, "S%02x", remoteSignal);
remotePutPacket(buffer);
}
void remoteSendStatus()
{
char buffer[1024];
sprintf(buffer, "T%02x", remoteSignal);
char* s = buffer;
s += 3;
for (int i = 0; i < 15; i++) {
uint32_t v = reg[i].I;
sprintf(s, "%02x:%02x%02x%02x%02x;", i,
(v & 255),
(v >> 8) & 255,
(v >> 16) & 255,
(v >> 24) & 255);
s += 12;
}
uint32_t v = armNextPC;
sprintf(s, "0f:%02x%02x%02x%02x;", (v & 255),
(v >> 8) & 255,
(v >> 16) & 255,
(v >> 24) & 255);
s += 12;
CPUUpdateCPSR();
v = reg[16].I;
sprintf(s, "19:%02x%02x%02x%02x;", (v & 255),
(v >> 8) & 255,
(v >> 16) & 255,
(v >> 24) & 255);
s += 12;
*s = 0;
//log("Sending %s\n", buffer);
remotePutPacket(buffer);
}
void remoteBinaryWrite(char* p)
{
uint32_t address;
int count;
sscanf(p, "%x,%x:", &address, &count);
// monprintf("Binary write for %08x %d\n", address, count);
p = strchr(p, ':');
p++;
for (int i = 0; i < count; i++) {
uint8_t b = *p++;
switch (b) {
case 0x7d:
b = *p++;
debuggerWriteByte(address, (b ^ 0x20));
address++;
break;
default:
debuggerWriteByte(address, b);
address++;
break;
}
}
// monprintf("ROM is %08x\n", debuggerReadMemory(0x8000254));
remotePutPacket("OK");
}
void remoteMemoryWrite(char* p)
{
uint32_t address;
int count;
sscanf(p, "%x,%x:", &address, &count);
// monprintf("Memory write for %08x %d\n", address, count);
p = strchr(p, ':');
p++;
for (int i = 0; i < count; i++) {
uint8_t v = 0;
char c = *p++;
if (c <= '9')
v = (c - '0') << 4;
else
v = (c + 10 - 'a') << 4;
c = *p++;
if (c <= '9')
v += (c - '0');
else
v += (c + 10 - 'a');
debuggerWriteByte(address, v);
address++;
}
// monprintf("ROM is %08x\n", debuggerReadMemory(0x8000254));
remotePutPacket("OK");
}
void remoteMemoryRead(char* p)
{
uint32_t address;
int count;
sscanf(p, "%x,%x:", &address, &count);
// monprintf("Memory read for %08x %d\n", address, count);
char* buffer = new char[(count*2)+1];
char* s = buffer;
for (int i = 0; i < count; i++) {
uint8_t b = debuggerReadByte(address);
sprintf(s, "%02x", b);
address++;
s += 2;
}
*s = 0;
remotePutPacket(buffer);
delete[] buffer;
}
void remoteQuery(char* p)
{
if (!strncmp(p, "fThreadInfo", 11)) {
remotePutPacket("m1");
} else if (!strncmp(p, "sThreadInfo", 11)) {
remotePutPacket("l");
} else if (!strncmp(p, "Supported", 9)) {
remotePutPacket("PacketSize=1000");
} else if (!strncmp(p, "HostInfo", 8)) {
remotePutPacket("cputype:12;cpusubtype:5;ostype:unknown;vendor:nintendo;endian:little;ptrsize:4;");
} else if (!strncmp(p, "C", 1)) {
remotePutPacket("QC1");
} else if (!strncmp(p, "Attached", 8)) {
remotePutPacket("1");
} else if (!strncmp(p, "Symbol", 6)) {
remotePutPacket("OK");
} else if (!strncmp(p, "Rcmd,", 5)) {
p += 5;
std::string cmd = HexToString(p);
dbgExecute(cmd);
remotePutPacket("OK");
} else {
fprintf(stderr, "Unknown packet %s\n", --p);
remotePutPacket("");
}
}
void remoteStepOverRange(char* p)
{
uint32_t address;
uint32_t final;
sscanf(p, "%x,%x", &address, & final);
remotePutPacket("OK");
remoteResumed = true;
do {
CPULoop(1);
if (debugger)
break;
} while (armNextPC >= address && armNextPC < final);
remoteResumed = false;
remoteSendStatus();
}
void remoteSetBreakPoint(char* p)
{
uint32_t address;
int count;
sscanf(p, ",%x,%x#", &address, &count);
for (int n = 0; n < count; n += 4)
addConditionalBreak(address + n, armState ? 0x04 : 0x08);
// Out of bounds memory checks
//if (address < 0x2000000 || address > 0x3007fff) {
// remotePutPacket("E01");
// return;
//}
//if (address > 0x203ffff && address < 0x3000000) {
// remotePutPacket("E01");
// return;
//}
//uint32_t final = address + count;
//if (address < 0x2040000 && final > 0x2040000) {
// remotePutPacket("E01");
// return;
//}
//else if (address < 0x3008000 && final > 0x3008000) {
// remotePutPacket("E01");
// return;
//}
remotePutPacket("OK");
}
void remoteClearBreakPoint(char* p)
{
int result = 0;
uint32_t address;
int count;
sscanf(p, ",%x,%x#", &address, &count);
for (int n = 0; n < count; n += 4)
result = removeConditionalWithAddressAndFlag(address + n, armState ? 0x04 : 0x08, true);
if (result != -2)
remotePutPacket("OK");
else
remotePutPacket("");
}
void remoteSetMemoryReadBreakPoint(char* p)
{
uint32_t address;
int count;
sscanf(p, ",%x,%x#", &address, &count);
for (int n = 0; n < count; n++)
addConditionalBreak(address + n, 0x02);
// Out of bounds memory checks
//if (address < 0x2000000 || address > 0x3007fff) {
// remotePutPacket("E01");
// return;
//}
//if (address > 0x203ffff && address < 0x3000000) {
// remotePutPacket("E01");
// return;
//}
//uint32_t final = address + count;
//if (address < 0x2040000 && final > 0x2040000) {
// remotePutPacket("E01");
// return;
//}
//else if (address < 0x3008000 && final > 0x3008000) {
// remotePutPacket("E01");
// return;
//}
remotePutPacket("OK");
}
void remoteClearMemoryReadBreakPoint(char* p)
{
bool error = false;
int result;
uint32_t address;
int count;
sscanf(p, ",%x,%x#", &address, &count);
for (int n = 0; n < count; n++) {
result = removeConditionalWithAddressAndFlag(address + n, 0x02, true);
if (result == -2)
error = true;
}
if (!error)
remotePutPacket("OK");
else
remotePutPacket("");
}
void remoteSetMemoryAccessBreakPoint(char* p)
{
uint32_t address;
int count;
sscanf(p, ",%x,%x#", &address, &count);
for (int n = 0; n < count; n++)
addConditionalBreak(address + n, 0x03);
// Out of bounds memory checks
//if (address < 0x2000000 || address > 0x3007fff) {
// remotePutPacket("E01");
// return;
//}
//if (address > 0x203ffff && address < 0x3000000) {
// remotePutPacket("E01");
// return;
//}
//uint32_t final = address + count;
//if (address < 0x2040000 && final > 0x2040000) {
// remotePutPacket("E01");
// return;
//}
//else if (address < 0x3008000 && final > 0x3008000) {
// remotePutPacket("E01");
// return;
//}
remotePutPacket("OK");
}
void remoteClearMemoryAccessBreakPoint(char* p)
{
bool error = false;
int result;
uint32_t address;
int count;
sscanf(p, ",%x,%x#", &address, &count);
for (int n = 0; n < count; n++) {
result = removeConditionalWithAddressAndFlag(address + n, 0x03, true);
if (result == -2)
error = true;
}
if (!error)
remotePutPacket("OK");
else
remotePutPacket("");
}
void remoteWriteWatch(char* p, bool active)
{
uint32_t address;
int count;
sscanf(p, ",%x,%x#", &address, &count);
if (active) {
for (int n = 0; n < count; n++)
addConditionalBreak(address + n, 0x01);
} else {
for (int n = 0; n < count; n++)
removeConditionalWithAddressAndFlag(address + n, 0x01, true);
}
// Out of bounds memory check
//fprintf(stderr, "Write watch for %08x %d\n", address, count);
//if(address < 0x2000000 || address > 0x3007fff) {
// remotePutPacket("E01");
// return;
//}
//if(address > 0x203ffff && address < 0x3000000) {
// remotePutPacket("E01");
// return;
//}
// uint32_t final = address + count;
//if(address < 0x2040000 && final > 0x2040000) {
// remotePutPacket("E01");
// return;
//} else if(address < 0x3008000 && final > 0x3008000) {
// remotePutPacket("E01");
// return;
//}
#ifdef BKPT_SUPPORT
for (int i = 0; i < count; i++) {
if ((address >> 24) == 2)
freezeWorkRAM[address & 0x3ffff] = active;
else
freezeInternalRAM[address & 0x7fff] = active;
address++;
}
#endif
remotePutPacket("OK");
}
void remoteReadRegister(char* p)
{
int r;
sscanf(p, "%x", &r);
if(r < 0 || r > 15)
{
remotePutPacket("E 00");
return;
}
char buffer[1024];
char* s = buffer;
uint32_t v = reg[r].I;
sprintf(s, "%02x%02x%02x%02x", v & 255, (v >> 8) & 255,
(v >> 16) & 255, (v >> 24) & 255);
remotePutPacket(buffer);
}
void remoteReadRegisters(char* p)
{
(void)p; // unused params
char buffer[1024];
char* s = buffer;
int i;
// regular registers
for (i = 0; i < 15; i++) {
uint32_t v = reg[i].I;
sprintf(s, "%02x%02x%02x%02x", v & 255, (v >> 8) & 255,
(v >> 16) & 255, (v >> 24) & 255);
s += 8;
}
// PC
uint32_t pc = armNextPC;
sprintf(s, "%02x%02x%02x%02x", pc & 255, (pc >> 8) & 255,
(pc >> 16) & 255, (pc >> 24) & 255);
s += 8;
// floating point registers (24-bit)
for (i = 0; i < 8; i++) {
sprintf(s, "000000000000000000000000");
s += 24;
}
// FP status register
sprintf(s, "00000000");
s += 8;
// CPSR
CPUUpdateCPSR();
uint32_t v = reg[16].I;
sprintf(s, "%02x%02x%02x%02x", v & 255, (v >> 8) & 255,
(v >> 16) & 255, (v >> 24) & 255);
s += 8;
*s = 0;
remotePutPacket(buffer);
}
void remoteWriteRegister(char* p)
{
int r;
sscanf(p, "%x=", &r);
if(r < 0 || r > 15)
{
remotePutPacket("E 00");
return;
}
p = strchr(p, '=');
p++;
char c = *p++;
uint32_t v = 0;
uint8_t data[4] = { 0, 0, 0, 0 };
int i = 0;
while (i < 4) {
uint8_t b = 0;
if (c <= '9')
b = (c - '0') << 4;
else
b = (c + 10 - 'a') << 4;
c = *p++;
if (c <= '9')
b += (c - '0');
else
b += (c + 10 - 'a');
data[i++] = b;
c = *p++;
}
v = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
// monprintf("Write register %d=%08x\n", r, v);
reg[r].I = v;
if (r == 15) {
armNextPC = v;
if (armState)
reg[15].I = v + 4;
else
reg[15].I = v + 2;
}
remotePutPacket("OK");
}
void remoteStubMain()
{
if (!debugger)
return;
if (remoteResumed) {
remoteSendStatus();
remoteResumed = false;
}
const char* hex = "0123456789abcdef";
while (1) {
char ack;
char buffer[1024];
int res = remoteRecvFnc(buffer, 1024);
if (res == -1) {
fprintf(stderr, "GDB connection lost\n");
debugger = false;
break;
} else if (res == -2)
break;
if (res < 1024) {
buffer[res] = 0;
} else {
fprintf(stderr, "res=%d\n", res);
}
// fprintf(stderr, "res=%d Received %s\n",res, buffer);
char c = buffer[0];
char* p = &buffer[0];
int i = 0;
unsigned char csum = 0;
while (i < res) {
if (buffer[i] == '$') {
i++;
csum = 0;
c = buffer[i];
p = &buffer[i + 1];
while ((i < res) && (buffer[i] != '#')) {
csum += buffer[i];
i++;
}
} else if (buffer[i] == '#') {
buffer[i] = 0;
if ((i + 2) < res) {
if ((buffer[i + 1] == hex[csum >> 4]) && (buffer[i + 2] == hex[csum & 0xf])) {
ack = '+';
remoteSendFnc(&ack, 1);
//fprintf(stderr, "SentACK c=%c\n",c);
//process message...
char type;
switch (c) {
case '?':
remoteSendSignal();
break;
case 'D':
remotePutPacket("OK");
remoteResumed = true;
debugger = false;
return;
case 'e':
remoteStepOverRange(p);
break;
case 'k':
remotePutPacket("OK");
debugger = false;
emulating = false;
return;
case 'C':
remoteResumed = true;
debugger = false;
return;
case 'c':
remoteResumed = true;
debugger = false;
return;
case 's':
remoteResumed = true;
remoteSignal = 5;
CPULoop(1);
if (remoteResumed) {
remoteResumed = false;
remoteSendStatus();
}
break;
case 'g':
remoteReadRegisters(p);
break;
case 'p':
remoteReadRegister(p);
break;
case 'P':
remoteWriteRegister(p);
break;
case 'M':
remoteMemoryWrite(p);
break;
case 'm':
remoteMemoryRead(p);
break;
case 'X':
remoteBinaryWrite(p);
break;
case 'H':
remotePutPacket("OK");
break;
case 'q':
remoteQuery(p);
break;
case 'Z':
type = *p++;
if (type == '0') {
remoteSetBreakPoint(p);
} else if (type == '1') {
remoteSetBreakPoint(p);
} else if (type == '2') {
remoteWriteWatch(p, true);
} else if (type == '3') {
remoteSetMemoryReadBreakPoint(p);
} else if (type == '4') {
remoteSetMemoryAccessBreakPoint(p);
} else {
remotePutPacket("");
}
break;
case 'z':
type = *p++;
if (type == '0') {
remoteClearBreakPoint(p);
} else if (type == '1') {
remoteClearBreakPoint(p);
} else if (type == '2') {
remoteWriteWatch(p, false);
} else if (type == '3') {
remoteClearMemoryReadBreakPoint(p);
} else if (type == '4') {
remoteClearMemoryAccessBreakPoint(p);
} else {
remotePutPacket("");
}
break;
default: {
fprintf(stderr, "Unknown packet %s\n", --p);
remotePutPacket("");
} break;
}
} else {
fprintf(stderr, "bad chksum csum=%x msg=%c%c\n", csum, buffer[i + 1], buffer[i + 2]);
ack = '-';
remoteSendFnc(&ack, 1);
fprintf(stderr, "SentNACK\n");
} //if
i += 3;
} else {
fprintf(stderr, "didn't receive chksum i=%d res=%d\n", i, res);
i++;
} //if
} else {
if (buffer[i] != '+') { //ingnore ACKs
fprintf(stderr, "not sure what to do with:%c i=%d res=%d\n", buffer[i], i, res);
}
i++;
} //if
} //while
}
}
void remoteStubSignal(int sig, int number)
{
(void)number; // unused params
remoteSignal = sig;
remoteResumed = false;
remoteSendStatus();
debugger = true;
}
void remoteCleanUp()
{
if (remoteCleanUpFnc)
remoteCleanUpFnc();
}
std::string HexToString(char* p)
{
std::string hex(p);
std::string cmd;
std::stringstream ss;
uint32_t offset = 0;
while (offset < hex.length()) {
unsigned int buffer = 0;
ss.clear();
ss << std::hex << hex.substr(offset, 2);
ss >> std::hex >> buffer;
cmd.push_back(static_cast<unsigned char>(buffer));
offset += 2;
}
return cmd;
}
std::string StringToHex(std::string& cmd)
{
std::stringstream ss;
ss << std::hex;
for (uint32_t i = 0; i < cmd.length(); ++i)
ss << std::setw(2) << std::setfill('0') << (int)cmd.c_str()[i];
return ss.str();
}
void monprintf(std::string line)
{
std::string output = "O";
line = StringToHex(line);
output += line;
if (output.length() <= 1000) {
char dbgReply[1000];
strcpy(dbgReply, output.c_str());
remotePutPacket(dbgReply);
}
}
#endif
| [
"adampetersenzzz@gmail.com"
] | adampetersenzzz@gmail.com |
283c205f562ade6f2dbf1adb835f292b28b7eff7 | 62e9946ef2007a05abab6b69dd2aa5421a6edbeb | /OSI/Red.h | 0c2dbced691da993e39782934fbc1444f8f5f613 | [] | no_license | jonabtc/redes | c0f238fa63d63ba3399bd41e2de650358c287bd5 | 263514c01398f02eda0ea69ce3d42f594e921d67 | refs/heads/master | 2020-12-03T22:17:08.595081 | 2020-01-03T03:18:47 | 2020-01-03T03:18:47 | 231,503,761 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 292 | h | #ifndef RED_H
#define RED_H
#include <string>
#include "Transporte.h"
#include "Enlace.h"
class Red{
private:
string mensaje;
public:
Red();
void setMensaje(string mensaje);
string getMensaje();
void doProcess(Transporte transporte);
void doProcess(Enlace enlace);
};
#endif
| [
"oclesjo@gmail.com"
] | oclesjo@gmail.com |
1c70f36282e0f5a29ce8b0db09bd9f03fbc83f2b | 882238b7118ba2f7c2f8eb36212508203d0466a4 | /runtimes/cc/runtime/org/labcrypto/hottentot/utf8_string.h | 878d8899702ee7e9673ed0ccedc242a47402ebd7 | [
"MIT"
] | permissive | alisharifi01/hottentot | 32c0184c9aa2248047eb03ca13d68dc8557b962b | e578a2185c473301076ece5634113ab663996a3e | refs/heads/master | 2020-03-27T10:19:17.074850 | 2016-11-13T07:58:08 | 2016-11-13T07:58:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,236 | h | /* The MIT License (MIT)
*
* Copyright (c) 2015 LabCrypto 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.
*/
#ifndef _ORG_LABCRYPTO_HOTTENTOT__UTF8_STRING_H_
#define _ORG_LABCRYPTO_HOTTENTOT__UTF8_STRING_H_
#include <iostream>
#include <stdexcept>
#include <string.h>
#ifdef __WIN32__
typedef __int8 int8_t;
typedef unsigned __int8 uint8_t;
typedef __int16 int16_t;
typedef unsigned __int16 uint16_t;
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else
#include <stdint.h>
#endif
#include "serializable.h"
namespace org {
namespace labcrypto {
namespace hottentot {
class Utf8String : public Serializable {
public:
Utf8String(const char *data = 0)
: data_(0),
chars_(0),
length_(0) {
if (data) {
FromByteArray(data);
}
}
Utf8String(std::string str)
: data_(0),
chars_(0),
length_(0) {
FromByteArray(str.c_str());
}
Utf8String(const Utf8String &utf8String)
: data_(0),
chars_(0),
length_(0) {
if (utf8String.data_) {
FromByteArray(utf8String.data_);
}
}
virtual ~Utf8String() {
if (data_) {
delete [] data_;
}
if (chars_) {
delete [] chars_;
}
}
public:
uint32_t Length() const {
return length_;
}
uint16_t CharAt(uint32_t index) const {
return chars_[index];
}
std::string ToStdString() {
const char *data = (const char*)Serialize(NULL);
std::string str(data);
delete [] data;
return str;
}
std::wstring ToStdWString() {
// TODO
return std::wstring();
}
public:
inline Utf8String& operator =(const char *str) {
FromByteArray(str);
return *this;
}
inline Utf8String& operator =(const Utf8String &other) {
FromByteArray(other.data_);
return *this;
}
friend std::ostream& operator <<(std::ostream& out, const Utf8String& obj) {
out << obj.data_;
return out;
}
public:
inline virtual unsigned char * Serialize(uint32_t *length_ptr) {
if (!data_) {
unsigned char *data = new unsigned char[1];
data[0] = 0;
*length_ptr = 1;
return data;
}
uint32_t byteLength = strlen(data_);
unsigned char *data = new unsigned char[byteLength + 1];
for (uint32_t i = 0; i < byteLength; i++) {
data[i] = data_[i];
}
data[byteLength] = 0;
if (length_ptr) {
*length_ptr = byteLength + 1;
}
return data;
}
inline virtual void Deserialize(unsigned char *data,
uint32_t length) {
if (length == 0) {
FromByteArray(0);
return;
}
FromByteArray((const char *)data);
}
protected:
inline void FromByteArray(const char *data) {
if (!data) {
if (data_) {
delete [] data_;
}
data_ = 0;
length_ = 0;
return;
}
uint32_t byteLength = strlen(data);
if (data_) {
delete [] data_;
}
data_ = new char[byteLength + 1];
for (uint32_t i = 0; i < byteLength; i++) {
data_[i] = data[i];
}
data_[byteLength] = 0;
length_ = 0;
for (uint32_t i = 0; i < byteLength; i++) {
if ((data_[i] & 0x80) == 0x00) {
length_++;
} else {
if ((data_[i] & 0x40) == 0x40 && (data_[i] & 0x20) == 0x00) {
length_++;
}
}
}
uint32_t c = 0;
chars_ = new uint16_t[length_ + 1];
for (uint32_t i = 0; i < byteLength; i++) {
if ((data_[i] & 0x80) == 0x00) {
chars_[c++] = data_[i];
} else {
if ((data_[i] & 0x40) == 0x40 && (data_[i] & 0x20) == 0x00) {
uint16_t left = data_[i] & 0x1f;
uint16_t right = data_[i + 1] & 0x3f;
uint16_t result = right | (left << 6);
chars_[c++] = result;
}
}
}
chars_[c] = 0;
}
private:
char *data_;
uint16_t *chars_;
uint32_t length_;
};
}
}
}
#endif | [
"kam.cpp@gmail.com"
] | kam.cpp@gmail.com |
af22ea565affdb9dac3b964a4f14efea7c545141 | e9e387a1b649cbce1260caa61c76854b4e8b543b | /industrial_calibration/src/intrinsic_example_mh3.cpp | 9d2d1dfca4682da8c2838ef9841ed77fb3a54d8b | [
"Apache-2.0"
] | permissive | jdlangs/IC2 | 02fca706b4fd0a76c1c3b3b4ff7ea91817877dae | 10535cc5cd41d67dbae347750b01493c62d86344 | refs/heads/master | 2021-05-11T00:26:28.158822 | 2018-01-15T21:01:16 | 2018-01-15T21:01:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,511 | cpp | #include <ros/ros.h>
#include <yaml-cpp/yaml.h>
#include <opencv2/highgui/highgui.hpp>
#include <industrial_calibration_libs/industrial_calibration_libs.h>
#include <industrial_calibration/helper_functions.h>
int main(int argc, char** argv)
{
ros::init(argc, argv, "intrinsic example");
ros::NodeHandle pnh("~");
std::string data_path;
pnh.getParam("data_path", data_path);
// Load Target Data
industrial_calibration_libs::Target target(data_path +
"mcircles_9x12/mcircles_9x12.yaml");
// Load Calibration Images
const std::size_t num_images = 7;
std::vector<cv::Mat> calibration_images;
calibration_images.reserve(num_images);
std::string cal_image_path = data_path + "mcircles_9x12/intrinsic_mh3/images/";
for (std::size_t i = 0; i < num_images; i++)
{
std::string image_path = cal_image_path + std::to_string(i) + ".png";
cv::Mat image = cv::imread(image_path, CV_LOAD_IMAGE_COLOR);
calibration_images.push_back(image);
}
// Extract Observations and get Observation Data
industrial_calibration_libs::ObservationExtractor observation_extractor(target);
int num_success = observation_extractor.extractObservations(calibration_images);
if (num_success != num_images)
{
ROS_ERROR_STREAM("Unable to extract all observations");
return 0;
}
industrial_calibration_libs::ObservationData observation_data =
observation_extractor.getObservationData();
// Load link data
std::vector<LinkData> link_data;
link_data.reserve(num_images);
for (std::size_t i = 0; i < num_images; i++)
{
LinkData temp_link_data;
loadLinkData(data_path + "mcircles_9x12/intrinsic_mh3/tf/" + std::to_string(i) + ".yaml",
&temp_link_data, "base_to_tool0");
link_data.push_back(temp_link_data);
}
// Set initial target pose seed
double distance_to_target = 0.1778; // meters
double qx, qy, qz, qw;
getQuaternion(distance_to_target, qx, qy, qz, qw);
industrial_calibration_libs::Pose6D target_pose;
target_pose.setQuaternion(qx, qy, qz, qw);
target_pose.setOrigin(0.0089, 0.127, 0.1778); // meters
// Load camera_info from YAML.
std::string camera_info_path = data_path + "mcircles_9x12/intrinsic_mh3/camera_info.yaml";
double camera_info[9];
loadCameraInfo(camera_info_path, camera_info);
// Set your calibration parameters to be passed to the calibration object.
industrial_calibration_libs::CameraOnWristIntrinsicParams params;
// Seed intrinsic parameters
params.intrinsics = industrial_calibration_libs::IntrinsicsFull(camera_info);
// Seed target pose
params.target_to_camera = industrial_calibration_libs::Extrinsics(target_pose);
// Robot tool positions for every calibration image.
convertToPose6D(link_data, ¶ms.base_to_tool);
// Create calibration object and run
industrial_calibration_libs::CameraOnWristIntrinsic calibration(
observation_data, target, params);
calibration.setOutput(true); // Enable output to console.
calibration.runCalibration();
calibration.displayCovariance();
// Print out results.
industrial_calibration_libs::CameraOnWristIntrinsic::Result results = calibration.getResults();
ROS_INFO_STREAM("Intrinsic Parameters");
ROS_INFO_STREAM("----------------------------------------");
ROS_INFO_STREAM("Focal Length x: " << results.intrinsics[0]);
ROS_INFO_STREAM("Focal Length y: " << results.intrinsics[1]);
ROS_INFO_STREAM("Optical Center x: " << results.intrinsics[2]);
ROS_INFO_STREAM("Optical Center y: " << results.intrinsics[3]);
ROS_INFO_STREAM("Distortion k1: " << results.intrinsics[4]);
ROS_INFO_STREAM("Distortion k2: " << results.intrinsics[5]);
ROS_INFO_STREAM("Distortion k3: " << results.intrinsics[6]);
ROS_INFO_STREAM("Distortion p1: " << results.intrinsics[7]);
ROS_INFO_STREAM("Distortion p2: " << results.intrinsics[8]);
ROS_INFO_STREAM("Target Pose");
ROS_INFO_STREAM("----------------------------------------");
ROS_INFO_STREAM("Translation x: " << results.target_to_camera[3]);
ROS_INFO_STREAM("Translation y: " << results.target_to_camera[4]);
ROS_INFO_STREAM("Translation z: " << results.target_to_camera[5]);
ROS_INFO_STREAM("Angle Axis x: " << results.target_to_camera[0]);
ROS_INFO_STREAM("Angle Axis y: " << results.target_to_camera[1]);
ROS_INFO_STREAM("Angle Axis z: " << results.target_to_camera[2]);
ROS_INFO_STREAM("----------------------------------------");
ROS_INFO_STREAM("Initial Cost: " << calibration.getInitialCost());
ROS_INFO_STREAM("Final Cost: " << calibration.getFinalCost());
// Use these results to verify a calibration. This is done by taking
// two images that are furthest away from each other and calculating the
// target pose. If the distance moved for the target matches the distance
// moved for the robot tool, your calibration should be accurate.
// In this case we will (temporarily) use the same data that was used to solve
// for the intrinsics. I will take new images in the future to verify. (gChiou).
// This is passing in:
// 1] First observation image data
// 2] Pose at first observation image
// 3] Second observation image data
// 4] Pose at second observation
// 5] Results of intrinsic calibration
// 6] Initial guess for target position
industrial_calibration_libs::IntrinsicsVerification verification
= calibration.verifyIntrinsics(observation_data[0], params.base_to_tool[0],
observation_data[num_images-1], params.base_to_tool[num_images-1],
results.intrinsics, params.target_to_camera.data);
ROS_INFO_STREAM("x Direction:");
ROS_INFO_STREAM("Target (Pose_1 - Pose_2) x: " << verification.target_diff_x << " m");
ROS_INFO_STREAM("Tool Diff (Pose_1 - Pose_2) x: " << verification.tool_diff_x << " m");
ROS_INFO_STREAM("Absolute Error (Tool - Target) x: " << verification.absolute_error_x << " m");
ROS_INFO_STREAM("y Direction:");
ROS_INFO_STREAM("Target Diff (Pose_1 - Pose_2) y: " << verification.target_diff_y << " m");
ROS_INFO_STREAM("Tool Diff (Pose_1 - Pose_2) y: " << verification.tool_diff_y << " m");
ROS_INFO_STREAM("Absolute Error (Tool - Target) y: " << verification.absolute_error_y << " m");
ROS_INFO_STREAM("z Direction:");
ROS_INFO_STREAM("Target Diff (Pose_1 - Pose_2) z: " << verification.target_diff_z << " m");
ROS_INFO_STREAM("Tool Diff (Pose_1 - Pose_2) z: " << verification.tool_diff_z << " m");
ROS_INFO_STREAM("Absolute Error (Tool - Target) z: " << verification.absolute_error_z << " m");
return 0;
}
| [
"geoffrey.chiou@gmail.com"
] | geoffrey.chiou@gmail.com |
bc61798011fd84ef06292dcc3024e26431a0af66 | 49b878b65e9eb00232490243ccb9aea9760a4a6d | /ash/public/cpp/holding_space/holding_space_test_api.h | 41dd17551f015f58acca0d3ccb6d1c4d105ecec6 | [
"BSD-3-Clause"
] | permissive | romanzes/chromium | 5a46f234a233b3e113891a5d643a79667eaf2ffb | 12893215d9efc3b0b4d427fc60f5369c6bf6b938 | refs/heads/master | 2022-12-28T00:20:03.524839 | 2020-10-08T21:01:52 | 2020-10-08T21:01:52 | 302,470,347 | 0 | 0 | BSD-3-Clause | 2020-10-08T22:10:22 | 2020-10-08T21:54:38 | null | UTF-8 | C++ | false | false | 2,113 | h | // Copyright 2020 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.
#ifndef ASH_PUBLIC_CPP_HOLDING_SPACE_HOLDING_SPACE_TEST_API_H_
#define ASH_PUBLIC_CPP_HOLDING_SPACE_HOLDING_SPACE_TEST_API_H_
#include <vector>
#include "ash/ash_export.h"
namespace aura {
class Window;
} // namespace aura
namespace views {
class View;
} // namespace views
namespace ash {
class HoldingSpaceTray;
// Utility class to facilitate easier testing of holding space. This API mainly
// exists to workaround //ash dependency restrictions in browser tests.
class ASH_EXPORT HoldingSpaceTestApi {
public:
HoldingSpaceTestApi();
HoldingSpaceTestApi(const HoldingSpaceTestApi&) = delete;
HoldingSpaceTestApi& operator=(const HoldingSpaceTestApi&) = delete;
~HoldingSpaceTestApi();
// Returns the root window that newly created windows should be added to.
static aura::Window* GetRootWindowForNewWindows();
// Shows holding space UI. This is a no-op if it's already showing.
void Show();
// Closes holding space UI. This is a no-op if it's already closed.
void Close();
// Returns true if holding space UI is showing, false otherwise.
bool IsShowing();
// Returns true if the holding space tray is showing in the shelf, false
// otherwise.
bool IsShowingInShelf();
// Returns the collection of download chips in holding space UI.
// If holding space UI is not visible, an empty collection is returned.
std::vector<views::View*> GetDownloadChips();
// Returns the collection of pinned file chips in holding space UI.
// If holding space UI is not visible, an empty collection is returned.
std::vector<views::View*> GetPinnedFileChips();
// Returns the collection of screenshot views in holding space UI.
// If holding space UI is not visible, an empty collection is returned.
std::vector<views::View*> GetScreenshotViews();
private:
HoldingSpaceTray* holding_space_tray_ = nullptr;
};
} // namespace ash
#endif // ASH_PUBLIC_CPP_HOLDING_SPACE_HOLDING_SPACE_TEST_API_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
357b748fccfb515ecf3e0b7b99cc60d5f0754c9d | 979c4ad764501298f72a945a1778c4ce57929480 | /src/uint256.h | 3e477441711c12bcbaaaa8aa8b38d8435b505c82 | [
"MIT"
] | permissive | buntheun/electrum | 97409933943b7870a49b5ded11d617ed7981cd44 | 58b233d0ae8c7aa2791765ab0dadfbf46c53f0ab | refs/heads/master | 2021-06-13T04:21:31.261183 | 2017-02-25T06:15:39 | 2017-02-25T06:15:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,222 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef ELECTRUM_UINT256_H
#define ELECTRUM_UINT256_H
#include <assert.h>
#include <cstring>
#include <stdexcept>
#include <stdint.h>
#include <string>
#include <vector>
#include "crypto/common.h"
/** Template base class for fixed-sized opaque blobs. */
template<unsigned int BITS>
class base_blob
{
protected:
enum { WIDTH=BITS/8 };
uint8_t data[WIDTH];
public:
base_blob()
{
memset(data, 0, sizeof(data));
}
explicit base_blob(const std::vector<unsigned char>& vch);
bool IsNull() const
{
for (int i = 0; i < WIDTH; i++)
if (data[i] != 0)
return false;
return true;
}
void SetNull()
{
memset(data, 0, sizeof(data));
}
friend inline bool operator==(const base_blob& a, const base_blob& b) { return memcmp(a.data, b.data, sizeof(a.data)) == 0; }
friend inline bool operator!=(const base_blob& a, const base_blob& b) { return memcmp(a.data, b.data, sizeof(a.data)) != 0; }
friend inline bool operator<(const base_blob& a, const base_blob& b) { return memcmp(a.data, b.data, sizeof(a.data)) < 0; }
std::string GetHex() const;
void SetHex(const char* psz);
void SetHex(const std::string& str);
std::string ToString() const;
unsigned char* begin()
{
return &data[0];
}
unsigned char* end()
{
return &data[WIDTH];
}
const unsigned char* begin() const
{
return &data[0];
}
const unsigned char* end() const
{
return &data[WIDTH];
}
unsigned int size() const
{
return sizeof(data);
}
unsigned int GetSerializeSize(int nType, int nVersion) const
{
return sizeof(data);
}
template<typename Stream>
void Serialize(Stream& s, int nType, int nVersion) const
{
s.write((char*)data, sizeof(data));
}
template<typename Stream>
void Unserialize(Stream& s, int nType, int nVersion)
{
s.read((char*)data, sizeof(data));
}
};
/** 160-bit opaque blob.
* @note This type is called uint160 for historical reasons only. It is an opaque
* blob of 160 bits and has no integer operations.
*/
class uint160 : public base_blob<160> {
public:
uint160() {}
uint160(const base_blob<160>& b) : base_blob<160>(b) {}
explicit uint160(const std::vector<unsigned char>& vch) : base_blob<160>(vch) {}
};
/** 256-bit opaque blob.
* @note This type is called uint256 for historical reasons only. It is an
* opaque blob of 256 bits and has no integer operations. Use arith_uint256 if
* those are required.
*/
class uint256 : public base_blob<256> {
public:
uint256() {}
uint256(const base_blob<256>& b) : base_blob<256>(b) {}
explicit uint256(const std::vector<unsigned char>& vch) : base_blob<256>(vch) {}
/** A cheap hash function that just returns 64 bits from the result, it can be
* used when the contents are considered uniformly random. It is not appropriate
* when the value can easily be influenced from outside as e.g. a network adversary could
* provide values to trigger worst-case behavior.
*/
uint64_t GetCheapHash() const
{
return ReadLE64(data);
}
/** A more secure, salted hash function.
* @note This hash is not stable between little and big endian.
*/
uint64_t GetHash(const uint256& salt) const;
};
/* uint256 from const char *.
* This is a separate function because the constructor uint256(const char*) can result
* in dangerously catching uint256(0).
*/
inline uint256 uint256S(const char *str)
{
uint256 rv;
rv.SetHex(str);
return rv;
}
/* uint256 from std::string.
* This is a separate function because the constructor uint256(const std::string &str) can result
* in dangerously catching uint256(0) via std::string(const char*).
*/
inline uint256 uint256S(const std::string& str)
{
uint256 rv;
rv.SetHex(str);
return rv;
}
#endif // ELECTRUM_UINT256_H
| [
"sinraf96@gmail.com"
] | sinraf96@gmail.com |
50aa9f035ce6dc6a88aed4b4133221809af26731 | fedc1c2fbdf2f00b250f6ed6f7b6fd8b8ef3bb39 | /test_cpp/test_patterns/cmd_pattern/StockAgent.hpp | 135570e5fd9458f0378ae6dd1979dfd7ee676fb3 | [] | no_license | t8534/test_cpp_repo | 9fd938bd01febca399222722d72c6fcab9e3bea3 | 1bb2418c4bb90054479d26932b615de3842d042f | refs/heads/master | 2021-01-10T23:38:07.297728 | 2016-10-10T13:41:22 | 2016-10-10T13:41:22 | 70,415,309 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 267 | hpp | /*
* StockAgent.hpp
*
* Created on: Jun 30, 2016
* Author: liberdaa
*/
#ifndef CMD_PATTERN_STOCKAGENT_HPP_
#define CMD_PATTERN_STOCKAGENT_HPP_
class StockAgent {
public:
StockAgent();
virtual ~StockAgent();
};
#endif /* CMD_PATTERN_STOCKAGENT_HPP_ */
| [
"arkadiusz.liberda@trw.com"
] | arkadiusz.liberda@trw.com |
7d6393c5217e3355553b4d9a6d0aada96277ac38 | bdf42290c1e3208c2b675bab0562054adbda63bd | /base/containers/adapters.h | cc151fc2468bfd630f80e959437fe95fb2d3724b | [
"BSD-3-Clause"
] | permissive | mockingbirdnest/chromium | 245a60c0c99b8c2eb2b43c104d82981070ba459d | e5eff7e6629d0e80dcef392166651e863af2d2fb | refs/heads/master | 2023-05-25T01:25:21.964034 | 2023-05-14T16:49:08 | 2023-05-14T16:49:08 | 372,263,533 | 0 | 0 | BSD-3-Clause | 2023-05-14T16:49:09 | 2021-05-30T16:28:29 | C++ | UTF-8 | C++ | false | false | 1,226 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_CONTAINERS_ADAPTERS_H_
#define BASE_CONTAINERS_ADAPTERS_H_
#include "base/macros.h"
namespace base {
namespace internal {
// Internal adapter class for implementing base::Reversed.
template <typename T>
class ReversedAdapter {
public:
typedef decltype(static_cast<T*>(nullptr)->rbegin()) Iterator;
explicit ReversedAdapter(T& t) : t_(t) {}
ReversedAdapter(const ReversedAdapter& ra) : t_(ra.t_) {}
Iterator begin() const { return t_.rbegin(); }
Iterator end() const { return t_.rend(); }
private:
T& t_;
DISALLOW_ASSIGN(ReversedAdapter);
};
} // namespace internal
// Reversed returns a container adapter usable in a range-based "for" statement
// for iterating a reversible container in reverse order.
//
// Example:
//
// std::vector<int> v = ...;
// for (int i : base::Reversed(v)) {
// // iterates through v from back to front
// }
template <typename T>
internal::ReversedAdapter<T> Reversed(T& t) {
return internal::ReversedAdapter<T>(t);
}
} // namespace base
#endif // BASE_CONTAINERS_ADAPTERS_H_
| [
"egg.robin.leroy@gmail.com"
] | egg.robin.leroy@gmail.com |
f6ef655caeea2e4413a92e17c4726528e3bccb0d | bf62d32b39db42c8f19e08e5b5ae9662258511ba | /editor/cn/447.number-of-boomerangs.h | dad1e515b4584b274c457091480e0c612fe86feb | [] | no_license | TimKingNF/leetcode | 8b00cbe57228eafc01e35c5ae1a1c9f2e2013b48 | f52115691d5b773ffb047565362d7df098705709 | refs/heads/master | 2023-03-23T08:27:39.214954 | 2021-03-19T14:00:25 | 2021-03-19T14:00:25 | 278,283,079 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,875 | h | //给定平面上 n 对不同的点,“回旋镖” 是由点表示的元组 (i, j, k) ,其中 i 和 j 之间的距离和 i 和 k 之间的距离相等(需要考虑元组的顺
//序)。
//
// 找到所有回旋镖的数量。你可以假设 n 最大为 500,所有点的坐标在闭区间 [-10000, 10000] 中。
//
// 示例:
//
//
//输入:
//[[0,0],[1,0],[2,0]]
//
//输出:
//2
//
//解释:
//两个回旋镖为 [[1,0],[0,0],[2,0]] 和 [[1,0],[2,0],[0,0]]
//
// Related Topics 哈希表
#include "header.h"
namespace LeetCode447 {
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public:
int numberOfBoomerangs(vector<vector<int>>& points) {
return solution1(points);
}
int solution1(vector<vector<int>>& points) {
int n = points.size();
// key 是两点之间的距离,value 是记录组的点
unordered_map<int, vector<pair<int, int>>> dict;
int ans = 0;
// 因为回旋镖相同座标位置不同也算不同,所以只需计算一半矩阵即可, 而且需要去掉边界线
for (int i = 0; i <= n - 2; ++i) {
for (int j = i + 1; j <= n - 1; ++j) {
int x_diff = points[i][0] - points[j][0];
int y_diff = points[i][1] - points[j][1];
int distance = x_diff * x_diff + y_diff * y_diff;
if (dict.count(distance)) {
for (auto v : dict[distance]) {
// 满足两组点之间有一个点相同
if (v.first == i || v.second == i || v.first == j || v.second == j) ++ans;
}
dict[distance].push_back({i, j});
} else {
dict[distance] = {{i, j}};
}
}
}
return ans * 2; // 上图的矩阵只计算了一半,所以需要 * 2
}
};
//leetcode submit region end(Prohibit modification and deletion)
} | [
"timking"
] | timking |
70cee226435a33c9392dc596f746f4b7fe014c02 | 2b5567af9f26c66ca9071c554642ab422dcc6d19 | /kafka_deals_server/include/db_mysql.h | e747762b786f5ef130755f19d4781b99605363fd | [] | no_license | gnuser/exchange_engine | 6eb9c52a82a04f19542a471a09e4f13ac62a62d2 | 6991ed765c4a928cee6f2b6ed79f64af14d1ee5b | refs/heads/master | 2020-12-05T13:18:49.109200 | 2020-01-10T03:27:18 | 2020-01-10T03:27:18 | 232,122,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,422 | h | #ifndef DB_MYSQL_H
#define DB_MYSQL_H
#include <string>
#include <mysql/mysql.h>
class DBMysql
{
public:
DBMysql();
~DBMysql();
struct MysqlConnect
{
std::string url;
int port;
std::string user_name;
std::string user_pass;
std::string use_db;
};
bool OpenDB();
void CloseDB();
void SetConnect(MysqlConnect*connect);
void GetConnect(MysqlConnect*connect);
void InsertData(const std::string&insert_sql);
bool DoSqlQuery(const std::string& sql_query,const std::string& query_type,int task_id);
bool GetDataFromSql(const std::string& select_sql, std::string&data_response);
void TransferData(const std::string&sql_select, const std::string&rpc_url,const std::string&rpc_data);
void TransferDataMutil(const std::string&sql_select, const std::string&rpc_url,const std::string&rpc_method, int thread_count,int init_id);
void CheckDataMutil(const std::string&sql_select, const std::string&rpc_url,const std::string&rpc_method, int thread_count,int init_id);
void CheckData(const std::string&sql_select, const std::string&rpc_url,const std::string&rpc_method, int thread_count,int init_id);
uint64_t GetMaxOffset(const std::string&sql_select);
void GetFeeRateFrom(const std::string& stock, const std::string& money,const uint64_t& time,std::string& ask_fee_rate,std::string& bid_fee_rate);
private:
MYSQL mysql_;
MysqlConnect* connect_;
};
extern DBMysql* g_db_mysql;
#endif
| [
"chenfei0929@gmail.com"
] | chenfei0929@gmail.com |
2b54e96a9c5d06e12f001c008c3c80083fbae7e6 | 4a30b76b361450688b7458ef00de2516310d5a47 | /src/Pals2.cpp | db9a3858bc0d97d6968ab0e62a5893886cca6932 | [] | no_license | sherylll/PALS2-Proximity-Sensor-Beta | 6061bc55a00ae1f6dfd36acbdf0f48824f68a932 | f1d91ecd9cf3c8b6a8875dc68ced57f180857347 | refs/heads/master | 2020-03-22T07:36:37.451526 | 2018-09-11T11:59:16 | 2018-09-11T11:59:16 | 139,711,589 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,949 | cpp | /**
* @file Pals2.cpp
* @brief Arduino library to control the proximity and ambient light sensor PALS2 from Infineon (packaged by Vishay as VCNL4135X01)
* @author Yuxi Sun
* @bug no Blue-PD value updates -> getIlluminance() not working;
* @bug update very slow (1 measurement/s) when periodic measurement is enabled, changing measurement rates in config register has no effect
* @bug in register 83h sensor measurement freezes if IRED output is not default(0): due to missing IREDs?
*/
#include "Pals2.h"
#include <math.h>
Pals2::Pals2() {
}
void Pals2::begin(void) {
Wire.begin();
//reset sensor
resetSensor();
//enables periodic measurement (stand-by)
enablePeriodicMeasurements();
}
void Pals2::updateData(void) {
uint8_t highByte = 0, lowByte = 0;
Wire.requestFrom(SLAVE_ADDRESS, 1, COMMAND_REGISTER,
PALS2_REG_SIZE, 0);
uint8_t result = Wire.read();
Wire.endTransmission();
//ready bits
bool als_ready = (result & 0x40) >> 6;
bool prox_ready = (result & 0x20) >> 5;
if ((!als_ready) && (!prox_ready))
return;
if (prox_ready) {
Wire.requestFrom(SLAVE_ADDRESS, 2, PROXIMITY_HIGH_BYTE,
PALS2_REG_SIZE, 0);
highByte = Wire.read();
lowByte = Wire.read();
rawProximity = concatResults(highByte, lowByte);
}
if (als_ready) {
Wire.requestFrom(SLAVE_ADDRESS, 2, ALS_HIGH_BYTE,
PALS2_REG_SIZE, 0);
highByte = Wire.read();
lowByte = Wire.read();
rawAmbientLight = concatResults(highByte, lowByte);
}
if (colorCompensationEnabled) {
Wire.requestFrom(SLAVE_ADDRESS, 4,
BLUE1_HIGH_BYTE, PALS2_REG_SIZE, 0);
highByte = Wire.read();
lowByte = Wire.read();
blue1PD = concatResults(highByte, lowByte);
highByte = Wire.read();
lowByte = Wire.read();
blue2PD = concatResults(highByte, lowByte);
}
Wire.endTransmission();
}
float Pals2::getIlluminance(void) {
return rawAmbientLight / 100; //according to Fig. 9, how to make of the formulas on Page 6?
}
uint16_t Pals2::getRawProximity(void) {
return rawProximity;
}
uint16_t Pals2::getRawAmbientLight(void) {
return rawAmbientLight;
}
void Pals2::resetSensor(void) {
writeOut(PROXIMITY_CONFIG, 0x00);
writeOut(IRED_CONFIG, 0x00);
writeOut(ALS_CONFIG, 0x00);
writeOut(ALS_COMPENSATION, 0x00);
writeOut(INTERRUPT_CONFIG, 0x00);
}
void Pals2::enablePeriodicMeasurements(void) {
writeOut(COMMAND_REGISTER, 0x07);
}
void Pals2::enableProximityOffsetCompensation(void) {
proximityConfig |= 0x08;
writeOut(PROXIMITY_CONFIG, proximityConfig);
}
void Pals2::disableProximityOffsetCompensation(void) {
proximityConfig &= ~0x08;
writeOut(PROXIMITY_CONFIG, proximityConfig);
}
void Pals2::setProximityMeasurementRate(uint16_t rate) {
if (rate > 256)
rate = 256;
//clear the bits for measurement rate
proximityConfig &= ~0x07;
//prx_rate = ld(rate) - 1
uint8_t prx_rate = -1;
while (rate >>= 1)
prx_rate++;
proximityConfig |= prx_rate;
writeOut(PROXIMITY_CONFIG, proximityConfig);
}
void Pals2::setInterruptPersistence(uint8_t persistence) {
uint8_t counts = persistence;
if (persistence > 128)
counts = 128;
//clear the highest 3 bits
interruptConfig &= ~(0x07 << 5);
//find the highest set bit
uint8_t i = 0;
while (counts >>= 1)
i++;
//set the highest 3 bits
interruptConfig |= (i << 5);
writeOut(INTERRUPT_CONFIG, interruptConfig);
}
void Pals2::enableProximityInterrupt(uint16_t topThreshold,
uint16_t bottomThreshold) {
//interrupt on exceeding both top & bottom thresholds
interruptConfig |= (0x03 << 3);
writeOut(INTERRUPT_CONFIG, interruptConfig);
writeOut(PROX_INT_BOT_HB, bottomThreshold & (0xFF << 8));
writeOut(PROX_INT_BOT_LB, bottomThreshold & 0xFF);
writeOut(PROX_INT_TOP_HB, topThreshold & (0xFF << 8));
writeOut(PROX_INT_TOP_LB, topThreshold & 0xFF);
}
void Pals2::disableProximityInterrupt(void) {
//disables both top & bottom thresholds
interruptConfig &= ~(0x03 << 3);
writeOut(INTERRUPT_CONFIG, interruptConfig);
}
void Pals2::enableAmbientLightInterrupt(uint16_t topThreshold,
uint16_t bottomThreshold) {
//interrupt on exceeding both top & bottom thresholds
interruptConfig |= (0x03 << 1);
writeOut(INTERRUPT_CONFIG, interruptConfig);
writeOut(ALS_INT_BOT_HB, bottomThreshold & (0xFF << 8));
writeOut(ALS_INT_BOT_LB, bottomThreshold & 0xFF);
writeOut(ALS_INT_TOP_HB, topThreshold & (0xFF << 8));
writeOut(ALS_INT_TOP_LB, topThreshold & 0xFF);
}
void Pals2::disableAmbientLightInterrupt(void) {
interruptConfig |= (0x03 << 1);
writeOut(INTERRUPT_CONFIG, interruptConfig);
}
void Pals2::enableColorCompensation(bool colorCompPeriod) {
writeOut(ALS_COMPENSATION, 0x01 + 0x02 * colorCompPeriod);
colorCompensationEnabled = true;
}
float Pals2::getBlueRatio(void) {
//TODO: check why always zero
return (blue1PD - blue2PD) / blue1PD;
}
uint16_t Pals2::concatResults(uint8_t upperByte, uint8_t lowerByte) {
uint16_t value = 0x0000;
value = (uint16_t) upperByte << 8;
value |= (uint16_t) lowerByte;
return value;
}
void Pals2::setADCGain(uint16_t adcGain) {
//clears bits 3,4
ambientLightConfig &= ~(0x03 << 3);
//default ADC gain is 200 fA (bits 3, 4 = 0)
switch (adcGain) {
case 800:
gainFactor = 22.17;
ambientLightConfig |= 0x01 << 3;
break;
case 3200:
gainFactor = 6.02;
ambientLightConfig |= 0x10 << 3;
break;
case 25600:
gainFactor = 0.75;
ambientLightConfig |= 0x11 << 3;
break;
default:
gainFactor = 81.79;
break;
}
writeOut(ALS_CONFIG, ambientLightConfig);
}
void Pals2::setAmbientLightMeasurementRate(uint8_t alsRate) {
//max. rate is 8 measurements/s
if (alsRate > 8)
alsRate = 8;
ambientLightConfig &= ~0x07;
ambientLightConfig |= (alsRate - 1);
writeOut(ALS_CONFIG, ambientLightConfig);
}
uint16_t Pals2::getRawProximityOnDemand(void) {
enableOnDemandReading();
Wire.beginTransmission(SLAVE_ADDRESS);
Wire.requestFrom(SLAVE_ADDRESS, 2, PROXIMITY_HIGH_BYTE,
PALS2_REG_SIZE, 0);
uint8_t upperByte = Wire.read();
uint8_t lowerByte = Wire.read();
Wire.endTransmission();
return concatResults(upperByte, lowerByte);
}
uint16_t Pals2::getRawAmbientLightOnDemand(void) {
enableOnDemandReading();
Wire.beginTransmission(SLAVE_ADDRESS);
Wire.requestFrom(SLAVE_ADDRESS, 2, ALS_HIGH_BYTE,
PALS2_REG_SIZE, 0);
uint8_t upperByte = Wire.read();
uint8_t lowerByte = Wire.read();
Wire.endTransmission();
return concatResults(upperByte, lowerByte);
}
void Pals2::enableOnDemandReading(void) {
//set als_od, prox_od and standby_en
writeOut(COMMAND_REGISTER, 0x19);
bool ready = false;
unsigned long start = millis();
//busy waiting
while (!ready) {
Wire.beginTransmission(SLAVE_ADDRESS);
Wire.requestFrom(SLAVE_ADDRESS, 1, COMMAND_REGISTER,
PALS2_REG_SIZE, 0);
ready = (Wire.read() & 0x40) >> 6;
Wire.endTransmission();
//set time out in case sensor gets stuck
if (millis() - start > 1000)
break;
}
}
void Pals2::writeOut(uint16_t regNum, uint16_t val) {
Wire.beginTransmission(SLAVE_ADDRESS);
Wire.write(regNum);
Wire.write(val);
Wire.endTransmission();
}
| [
"Yuxi.Sun@infineon.com"
] | Yuxi.Sun@infineon.com |
39f5bb04be7e4533ed9db74f5f3816aca4944171 | fb1fc28ddce9e0092ecdce00340bbbc3f66b6ec5 | /d03/ex03/srcs/ScavTrap.cpp | de63541b7253ebedf45b92d6d320fdda670c2259 | [] | no_license | anstadnik/CPP_pool | a20b020433ea317938b3291b313444ca0303b6a3 | 0af45b506764fbadf8856b3562f66f8553d21fd7 | refs/heads/master | 2023-09-05T05:29:34.038747 | 2018-04-17T08:49:33 | 2018-04-17T08:49:33 | 428,276,607 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,369 | cpp | #include "ScavTrap.hpp"
#include <iostream>
#include <stdlib.h>
ScavTrap::ScavTrap()
{
this->hp = 100;
this->max_hp = 100;
this->energy = 50;
this->max_energy = 50;
this->lvl = 1;
this->name = "unnamed";
this->melee = 20;
this->ranged = 15;
this->armor = 3;
std::cout << "Recompiling my combat code!(btw I'm a Scav)" << std::endl;
}
ScavTrap::ScavTrap(std::string name)
{
this->hp = 100;
this->max_hp = 100;
this->energy = 100;
this->max_energy = 100;
this->lvl = 1;
this->name = name;
this->melee = 30;
this->ranged = 20;
this->armor = 5;
std::cout << this->name << " is here to fight(as a Scav of course)" << std::endl;
}
ScavTrap::ScavTrap(const ScavTrap &src)
{
this->hp = src.hp;
this->max_hp = src.max_hp;
this->energy = src.energy;
this->max_energy = src.max_energy;
this->lvl = src.lvl;
this->name = src.name;
this->melee = src.melee;
this->ranged = src.ranged;
this->armor = src.armor;
std::cout << "Copying my combat code!(From a Scav, FYI)" << std::endl;
}
ScavTrap::~ScavTrap()
{
std::cout << "This could've gone better!(Scav died. Because I am a Scav. I died... Ah, just forget)" << std::endl;
}
void ScavTrap::challengeNewcomer(void)
{
std::string sarr[4] = {"Give the one from the right of u a hug", "Do a backflip",
"Tell ur intra password", "Do a lemin in 3 days"};
std::cout << sarr[rand() % 4] << std::endl;
}
| [
"astadnik@student.unit.ua"
] | astadnik@student.unit.ua |
e71cde743ed4da1abbc8847d030af1fc6cf352f9 | f09dafd714e1a0fa7130c3cf5658ac14b285193c | /TenMilManUI/TenMilManUI/UserInputs/MultiInput.cpp | 0c8bd8f6cd2430aee9ceb9dcd8d21f9090a7f226 | [] | no_license | pingjiang/10ui | 94feae916d76391d2598987454cc8eb34d76ae70 | e82e801270003f8c45f1addbddab6d97b372c207 | refs/heads/master | 2021-01-25T07:27:59.936560 | 2008-01-08T18:52:27 | 2008-01-08T18:52:27 | 39,576,338 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 107 | cpp | #include "MultiInput.h"
namespace TenUI
{
MultiInput::MultiInput()
{
}
MultiInput::~MultiInput()
{
}
}
| [
"rob.g.evans@0e52ec8f-463b-0410-b89e-d778e79482b9"
] | rob.g.evans@0e52ec8f-463b-0410-b89e-d778e79482b9 |
f7de98066217251ac38048103183266611e7f893 | c3e9d7d0a099ca1975c61bff3c2e9796acdbadae | /toltec/nodes/attributeConnector.cpp | 3ed0ecf43ab1b3c1fd034a0e5c2e036df83e6a22 | [] | no_license | QtOpenGL/toltec | f3ee149b6f86c1e389adb62c477299b6bc3dc559 | 0cd8b3c55a22aa86731fe8fc8cc6b5ea0bf80780 | refs/heads/master | 2021-01-20T05:47:34.836741 | 2017-08-21T09:47:52 | 2017-08-21T09:47:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,884 | cpp | /*-----------------------------------------------------------------------------
* CREATED:
* 21 VIII 2017
* CONTRIBUTORS:
* Piotr Makal
*-----------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------------
* IMPORTS
*-----------------------------------------------------------------------------*/
#include "attributeConnector.hpp"
#include "nodes/abstractAttribute.hpp"
/*-----------------------------------------------------------------------------
* NAMESPACE: CORE
*-----------------------------------------------------------------------------*/
namespace core
{
/*-----------------------------------------------------------------------------
* NAMESPACE: NODES
*-----------------------------------------------------------------------------*/
namespace nodes
{
/*-----------------------------------------------------------------------------
* CONSTRUCTOR
*-----------------------------------------------------------------------------*/
AttributeConnector::AttributeConnector(
AbstractAttribute* p_inputAttribute,
AbstractAttribute* p_outputAttribute,
AttributeConnector::ConnectionType connectionType)
:
mp_inputAttribute(p_inputAttribute),
mp_outputAttribute(p_outputAttribute),
m_connectionType(connectionType)
{
//SETUP
mp_inputAttribute->setOutputConnection(this);
mp_outputAttribute->setInputConnection(this);
}
/*-----------------------------------------------------------------------------
* DESTRUCTOR
*-----------------------------------------------------------------------------*/
AttributeConnector::~AttributeConnector()
{
mp_inputAttribute->setOutputConnection(nullptr);
mp_outputAttribute->setInputConnection(nullptr);
}
} //NAMESPACE: NODES
} //NAMESPACE: CORE
| [
"piotr.makal@gmail.com"
] | piotr.makal@gmail.com |
59195f952c0eaa64b46a8e92dce433c2c8b910b9 | 58fb545b57f8825e1450cab02a11446550101142 | /Cubemap/Skybox.cpp | 9957efff9e2b38ead84b343e21df1694566081dd | [] | no_license | Sounne/OpenGL | a51dabdf861c2fcac54dacc76772c78439f56561 | 27b3b4e7a3099ccf6bb5cecd25f014f7cb9d2a77 | refs/heads/master | 2021-01-11T14:43:43.373636 | 2017-02-02T11:58:21 | 2017-02-02T11:58:21 | 80,200,152 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,293 | cpp | #include "Skybox.h"
#include "stb/stb_image.h"
#include "Vertices.h"
Skybox::Skybox()
{
}
Skybox::~Skybox()
{
}
auto Skybox::Init() -> void
{
this->faces.push_back("../Skybox/back.jpg");
this->faces.push_back("../Skybox/front.jpg");
this->faces.push_back("../Skybox/bottom.jpg");
this->faces.push_back("../Skybox/top.jpg");
this->faces.push_back("../Skybox/left.jpg");
this->faces.push_back("../Skybox/right.jpg");
}
auto Skybox::LoadCubeMap(int _width, int _height) -> GLuint
{
GLuint texture_id;
glGenTextures(1, &texture_id);
glBindTexture(GL_TEXTURE_CUBE_MAP, texture_id);
unsigned char * image;
for (GLuint i = 0; i < this->faces.size(); ++i)
{
image = stbi_load(this->faces[i], &_width, &_height, 0, GL_RGB);
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, _width, _height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
return texture_id;
}
| [
"e.sounou@student.isartdigital.com"
] | e.sounou@student.isartdigital.com |
94093f5e9c49d7bce4a140b2a24f1fdb1135228c | 98dda92b42c7b7d87fafedfb492f8b229e0f6f48 | /src/ImGui/ImGuiWrapper.cpp | 2b242d966059624d7d53f4e35b473fb2cda34aed | [
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | WoW55QQ/sgl | abbca8022a53dc5f7735ee711456803af986f769 | 7952fa5949abff4e3c763ffa0fd0fcd6a3091b31 | refs/heads/master | 2023-01-22T12:29:42.384051 | 2020-11-21T02:00:35 | 2020-11-21T02:00:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,256 | cpp | //
// Created by christoph on 13.09.18.
//
#include <Utils/AppSettings.hpp>
#include <SDL/SDLWindow.hpp>
#include <SDL/HiDPI.hpp>
#include <Graphics/OpenGL/SystemGL.hpp>
#include "imgui.h"
#include "imgui_impl_opengl3.h"
#include "imgui_impl_sdl.h"
#include "ImGuiWrapper.hpp"
namespace sgl
{
void ImGuiWrapper::initialize(
const ImWchar* fontRangesData, bool useDocking, bool useMultiViewport, float uiScaleFactor) {
float scaleFactorHiDPI = getHighDPIScaleFactor();
this->uiScaleFactor = uiScaleFactor;
uiScaleFactor = scaleFactorHiDPI * uiScaleFactor;
float fontScaleFactor = uiScaleFactor;
// --- Code from here on partly taken from ImGui usage example ---
// Setup Dear ImGui binding
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO &io = ImGui::GetIO();
if (useDocking) {
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
}
if (useMultiViewport) {
io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;
}
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
//io.FontGlobalScale = fontScaleFactor*2.0f;
SDLWindow *window = static_cast<SDLWindow*>(AppSettings::get()->getMainWindow());
SDL_GLContext context = window->getGLContext();
ImGui_ImplSDL2_InitForOpenGL(window->getSDLWindow(), context);
const char* glsl_version = "#version 430";
if (!SystemGL::get()->openglVersionMinimum(4,3)) {
glsl_version = NULL; // Use standard
}
ImGui_ImplOpenGL3_Init(glsl_version);
// Setup style
ImGui::StyleColorsDark();
//ImGui::StyleColorsClassic();
//ImGui::StyleColorsLight();
ImGuiStyle &style = ImGui::GetStyle();
style.ScaleAllSizes(uiScaleFactor); // HiDPI scaling
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) {
style.WindowRounding = 0.0f;
style.Colors[ImGuiCol_WindowBg].w = 1.0f;
}
// Load fonts with specified range.
ImVector<ImWchar> fontRanges;
ImFontGlyphRangesBuilder builder;
builder.AddRanges(io.Fonts->GetGlyphRangesDefault());
//builder.AddRanges(io.Fonts->GetGlyphRangesJapanese());
if (fontRangesData != nullptr) {
builder.AddRanges(fontRangesData);
}
builder.BuildRanges(&fontRanges);
/*for (int i = 0; i < fontRanges.size(); i++) {
std::cout << fontRanges[i] << std::endl;
}*/
ImFont *fontTest = io.Fonts->AddFontFromFileTTF(
"Data/Fonts/DroidSans.ttf", 16.0f*fontScaleFactor, nullptr, fontRanges.Data);
// For support of more Unicode characters (e.g., also Japanese).
//ImFont *fontTest = io.Fonts->AddFontFromFileTTF(
// "Data/Fonts/DroidSansFallback.ttf", 16.0f*fontScaleFactor, nullptr, fontRanges.Data);
assert(fontTest != nullptr);
io.Fonts->Build();
}
void ImGuiWrapper::shutdown()
{
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplSDL2_Shutdown();
ImGui::DestroyContext();
}
void ImGuiWrapper::processSDLEvent(const SDL_Event &event)
{
ImGui_ImplSDL2_ProcessEvent(&event);
}
void ImGuiWrapper::renderStart()
{
SDLWindow *window = static_cast<SDLWindow*>(AppSettings::get()->getMainWindow());
// Start the Dear ImGui frame
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame(window->getSDLWindow());
ImGui::NewFrame();
}
void ImGuiWrapper::renderEnd()
{
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
ImGuiIO &io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) {
SDLWindow *sdlWindow = (SDLWindow*)AppSettings::get()->getMainWindow();
ImGui::UpdatePlatformWindows();
ImGui::RenderPlatformWindowsDefault();
SDL_GL_MakeCurrent(sdlWindow->getSDLWindow(), sdlWindow->getGLContext());
}
}
void ImGuiWrapper::renderDemoWindow()
{
static bool show_demo_window = true;
if (show_demo_window)
ImGui::ShowDemoWindow(&show_demo_window);
}
void ImGuiWrapper::showHelpMarker(const char* desc)
{
ImGui::TextDisabled("(?)");
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
ImGui::TextUnformatted(desc);
ImGui::PopTextWrapPos();
ImGui::EndTooltip();
}
}
} | [
"c.a.neuhauser@gmail.com"
] | c.a.neuhauser@gmail.com |
50093da644dd6f5719e7b04f2c47653ac683feb8 | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/webrtc/api/video_codecs/video_codec.cc | c6122d3f6ac3056ebcc654e1c268923f6057a738 | [
"BSD-3-Clause",
"LicenseRef-scancode-google-patent-license-webrtc",
"LicenseRef-scancode-google-patent-license-webm",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 4,689 | cc | /*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "api/video_codecs/video_codec.h"
#include <string.h>
#include <string>
#include "absl/strings/match.h"
#include "rtc_base/checks.h"
namespace webrtc {
namespace {
constexpr char kPayloadNameVp8[] = "VP8";
constexpr char kPayloadNameVp9[] = "VP9";
constexpr char kPayloadNameAv1[] = "AV1";
// TODO(bugs.webrtc.org/13166): Remove AV1X when backwards compatibility is not
// needed.
constexpr char kPayloadNameAv1x[] = "AV1X";
constexpr char kPayloadNameH264[] = "H264";
constexpr char kPayloadNameGeneric[] = "Generic";
constexpr char kPayloadNameMultiplex[] = "Multiplex";
} // namespace
bool VideoCodecVP8::operator==(const VideoCodecVP8& other) const {
return (numberOfTemporalLayers == other.numberOfTemporalLayers &&
denoisingOn == other.denoisingOn &&
automaticResizeOn == other.automaticResizeOn &&
keyFrameInterval == other.keyFrameInterval);
}
bool VideoCodecVP9::operator==(const VideoCodecVP9& other) const {
return (numberOfTemporalLayers == other.numberOfTemporalLayers &&
denoisingOn == other.denoisingOn &&
keyFrameInterval == other.keyFrameInterval &&
adaptiveQpMode == other.adaptiveQpMode &&
automaticResizeOn == other.automaticResizeOn &&
numberOfSpatialLayers == other.numberOfSpatialLayers &&
flexibleMode == other.flexibleMode);
}
bool VideoCodecH264::operator==(const VideoCodecH264& other) const {
return (keyFrameInterval == other.keyFrameInterval &&
numberOfTemporalLayers == other.numberOfTemporalLayers);
}
VideoCodec::VideoCodec()
: codecType(kVideoCodecGeneric),
width(0),
height(0),
startBitrate(0),
maxBitrate(0),
minBitrate(0),
maxFramerate(0),
active(true),
qpMax(0),
numberOfSimulcastStreams(0),
simulcastStream(),
spatialLayers(),
mode(VideoCodecMode::kRealtimeVideo),
expect_encode_from_texture(false),
timing_frame_thresholds({0, 0}),
legacy_conference_mode(false),
codec_specific_(),
complexity_(VideoCodecComplexity::kComplexityNormal) {}
VideoCodecVP8* VideoCodec::VP8() {
RTC_DCHECK_EQ(codecType, kVideoCodecVP8);
return &codec_specific_.VP8;
}
const VideoCodecVP8& VideoCodec::VP8() const {
RTC_DCHECK_EQ(codecType, kVideoCodecVP8);
return codec_specific_.VP8;
}
VideoCodecVP9* VideoCodec::VP9() {
RTC_DCHECK_EQ(codecType, kVideoCodecVP9);
return &codec_specific_.VP9;
}
const VideoCodecVP9& VideoCodec::VP9() const {
RTC_DCHECK_EQ(codecType, kVideoCodecVP9);
return codec_specific_.VP9;
}
VideoCodecH264* VideoCodec::H264() {
RTC_DCHECK_EQ(codecType, kVideoCodecH264);
return &codec_specific_.H264;
}
const VideoCodecH264& VideoCodec::H264() const {
RTC_DCHECK_EQ(codecType, kVideoCodecH264);
return codec_specific_.H264;
}
const char* CodecTypeToPayloadString(VideoCodecType type) {
switch (type) {
case kVideoCodecVP8:
return kPayloadNameVp8;
case kVideoCodecVP9:
return kPayloadNameVp9;
case kVideoCodecAV1:
return kPayloadNameAv1;
case kVideoCodecH264:
return kPayloadNameH264;
case kVideoCodecMultiplex:
return kPayloadNameMultiplex;
case kVideoCodecGeneric:
return kPayloadNameGeneric;
}
RTC_CHECK_NOTREACHED();
}
VideoCodecType PayloadStringToCodecType(const std::string& name) {
if (absl::EqualsIgnoreCase(name, kPayloadNameVp8))
return kVideoCodecVP8;
if (absl::EqualsIgnoreCase(name, kPayloadNameVp9))
return kVideoCodecVP9;
if (absl::EqualsIgnoreCase(name, kPayloadNameAv1) ||
absl::EqualsIgnoreCase(name, kPayloadNameAv1x))
return kVideoCodecAV1;
if (absl::EqualsIgnoreCase(name, kPayloadNameH264))
return kVideoCodecH264;
if (absl::EqualsIgnoreCase(name, kPayloadNameMultiplex))
return kVideoCodecMultiplex;
return kVideoCodecGeneric;
}
VideoCodecComplexity VideoCodec::GetVideoEncoderComplexity() const {
return complexity_;
}
void VideoCodec::SetVideoEncoderComplexity(
VideoCodecComplexity complexity_setting) {
complexity_ = complexity_setting;
}
bool VideoCodec::GetFrameDropEnabled() const {
return frame_drop_enabled_;
}
void VideoCodec::SetFrameDropEnabled(bool enabled) {
frame_drop_enabled_ = enabled;
}
} // namespace webrtc
| [
"jengelh@inai.de"
] | jengelh@inai.de |
d629abbf41d6ac64d58e7402b5a7e767f39b2e94 | 8cd0b2d7a4bb274175186f4b56525dabc7df06c2 | /NEngine/Source/Runtime/Graphics/World.h | abd00161ae823eefb7c01e46da7bf8179fbf8cfb | [] | no_license | giovgiac/NEngine | d8437ef597614a19489f4507d122fce196b7e3c7 | b276a33b0dea177d7df35bc85dbb720c46a4eed5 | refs/heads/master | 2021-01-20T15:44:25.253891 | 2017-11-25T23:50:59 | 2017-11-25T23:50:59 | 90,791,570 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,763 | h | /**
* World.h
*
* Copyright (c) Giovanni Giacomo. All Rights Reserved.
*
*/
#pragma once
#include <Core/Object.h>
#include <Collections/Array.h>
#include <Graphics/Renderer.h>
#include <Graphics/Scene.h>
#include <Math/Transform.h>
namespace Newton {
/**
* NWorld
*
* This class is responsible for creating a world, the entity that renders a scene.
*
*/
class NWorld : public NObject {
private:
NArray<class NActor*> Actors;
NArray<NRenderable> Renderables;
NArray<GLuint> Arrays;
NArray<GLuint> Buffers;
NRenderer Renderer;
NScene Scene;
public:
/**
* NWorld Constructor
*
* This default constructor initializes a new world.
*
*/
NWorld(void);
/**
* NWorld Draw
*
* This method calls upon the renderer to draw the current scene.
*
*/
void Draw(void);
/**
* NWorld LoadScene
*
* This method loads a new scene into the world and the GPU.
*
* @param NScene& InScene: The scene to load.
*
*/
void LoadScene(const NScene& InScene);
/**
* NWorld UnloadScene
*
* This method unloads the previously loaded scene from world and GPU.
*
*/
void UnloadScene(void);
inline const NArray<class NActor*>& GetActors() const { return Actors; }
/**
* NWorld GetScene
*
* This method returns the current scene.
*
* @return const NScene&: The current scene.
*
*/
inline const NScene& GetScene() const { return Scene; }
template<typename T>
T* SpawnActor(NTransform Transform)
{
NActor* Actor = Cast<NActor>(new T());
if (Actor)
{
// Set Transform
AddActor(Actor);
return Actor;
}
return nullptr;
}
private:
void AddActor(class NActor* InActor);
inline void ConstructObject(void) { }
};
} | [
"giovanni@unitool.com.br"
] | giovanni@unitool.com.br |
70000406f0d8d26b49889bc2849dd1788367a709 | c43616930ca17ebc971e9efc37ce7345dfa7013e | /sum.cpp | 0d6dd4921dadd3521554f1c045c548c1c11ba69a | [] | no_license | RdoD2/sum-test | b59870cd00c8ff4b5f9b94ffaa3d4ffbc3908633 | a868f37335f3b2925fd001a33b7204b99336c8c3 | refs/heads/master | 2023-06-10T07:43:32.408612 | 2021-07-07T07:48:55 | 2021-07-07T07:48:55 | 383,712,502 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 104 | cpp | #include "sum.h"
int sum(int n) {
int res =0;
for (int i = 1; i <=n; ++i)
res += i;
return res;
}
| [
"rdod205@gmail.com"
] | rdod205@gmail.com |
e3751dc6a20a06ad713d1e8d489b94fbfe8392d4 | 22a5d5b013e856b714b526f1b166881c38253a98 | /BattleCity/PowerUpSpawner.h | 6f130babcfe92fbdf6d31e9165464c14a73e4a40 | [] | no_license | teo3fl/Battle-City | 8e3ba7f0b5c51c5b6237fa1792de23bc27c8fda9 | 921f51a9a2d3648394bdfc0528f3ad4efd272a04 | refs/heads/main | 2023-07-10T09:49:48.172968 | 2020-01-21T13:03:29 | 2020-01-21T13:03:29 | 399,222,430 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 359 | h | #pragma once
#include "Spawner.h"
#include "PowerUp.h"
class PowerUpSpawner :
public Spawner<PowerUp>
{
public:
PowerUpSpawner(const uint8_t& numberOfPowerUps);
void GeneratePowerUps();
private:
PowerUp* CreatePowerUp(uint8_t powerUpType, uint8_t spawnLocation);
virtual uint8_t GetCurrentSpawningPoint() override;
void SetSpawnPoints() override;
};
| [
"teo.rockgirl@yahoo.com"
] | teo.rockgirl@yahoo.com |
1c5426e22061d592e770cfcad5187c7ef6453eb3 | 970eec1dd1b6db308a40970659bdfbe7b122fc31 | /content_handler_impl.h | d292cf4b3d47e12acc7e7a66ba091a431b2ddf2c | [
"BSD-3-Clause"
] | permissive | pulisul/dart_content_handler | e6476f150b6ff06b63f7e4e5b1e2d7314d90ba60 | adbd17d80fb64f9ec803a0166e1e8685dfe0e9fa | refs/heads/master | 2021-01-14T14:16:59.062102 | 2016-08-12T14:59:57 | 2016-08-12T14:59:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 897 | h | // Copyright 2016 The Fuchsia 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 "lib/ftl/macros.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "mojo/services/content_handler/interfaces/content_handler.mojom.h"
namespace dart_content_handler {
class ContentHandlerImpl : public mojo::ContentHandler {
public:
explicit ContentHandlerImpl(
mojo::InterfaceRequest<mojo::ContentHandler> request);
~ContentHandlerImpl() override;
private:
// |mojo::ContentHandler| implementation:
void StartApplication(mojo::InterfaceRequest<mojo::Application> application,
mojo::URLResponsePtr response) override;
mojo::StrongBinding<mojo::ContentHandler> binding_;
FTL_DISALLOW_COPY_AND_ASSIGN(ContentHandlerImpl);
};
} // namespace dart_content_handler
| [
"abarth@chromium.org"
] | abarth@chromium.org |
71cbef96cd2ec4d1e5ddfc38baf7f6e6beeb9b37 | 7f4ffa7b49096aedf6bf397e7729f1eb80c9b7c2 | /d3d11/DX11FontManager.h | 6b98778a48561e6c585ad72301ad42171a2e1046 | [] | no_license | tuccio/mye | 99e8c6016eb4929669a845fc38743763e691af21 | dc38ef7ee6192a301645e7bb6f8587557dfdf61d | refs/heads/master | 2021-01-10T02:24:42.410134 | 2015-12-13T21:04:59 | 2015-12-13T21:04:59 | 48,071,471 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 526 | h | #pragma once
#include "DX11Font.h"
#include <mye/core/ResourceManager.h>
namespace mye
{
namespace dx11
{
class DX11FontManager :
public mye::core::ResourceManager
{
public:
DX11FontManager(void);
~DX11FontManager(void);
protected:
DX11Font * CreateImpl(const mye::core::String & name,
mye::core::ManualResourceLoader * manual,
const mye::core::Parameters & params);
void FreeImpl(mye::core::Resource * resource);
};
}
}
| [
"d.tuccilli@gmail.com"
] | d.tuccilli@gmail.com |
35759744b6f972b5ef06a6bf6fe0dcc7d92e316c | 3dbec36a6c62cad3e5c6ec767b13f4038baa5f79 | /cpp-lang/primer/ch14/solutions/strvec/tests/test_strvec.cpp | f1d898c307f62fd2633df6e94c569e8a2a5dd660 | [] | no_license | reposhelf/playground | 50a2e54436e77e7e6cad3a44fd74c0acc22a553a | 47ddd204a05ec269e4816c2d45a13e5bc6d3e73a | refs/heads/master | 2022-04-22T13:50:24.222822 | 2020-04-10T15:59:30 | 2020-04-10T15:59:30 | 254,675,772 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,539 | cpp | #include "CppUTest/TestHarness.h"
#include "strvec.h"
#include <string>
#include <vector>
using namespace std;
TEST_GROUP(test_strvec)
{
};
TEST(test_strvec, def_constr)
{
StrVec strvec;
UNSIGNED_LONGS_EQUAL(0, strvec.size());
UNSIGNED_LONGS_EQUAL(0, strvec.capacity());
CHECK(strvec.begin() == nullptr);
CHECK(strvec.end() == nullptr);
}
TEST(test_strvec, init_list_constr)
{
StrVec strvec({"one", "two", "three"});
UNSIGNED_LONGS_EQUAL(3, strvec.size());
UNSIGNED_LONGS_EQUAL(3, strvec.capacity());
CHECK_EQUAL(string("one"), *(strvec.begin()));
CHECK_EQUAL(string("two"), *(strvec.begin() + 1));
CHECK_EQUAL(string("three"), *(strvec.begin() + 2));
}
TEST(test_strvec, copy_constr)
{
StrVec strvec({"one", "two", "three"});
StrVec strvec_copy(strvec);
UNSIGNED_LONGS_EQUAL(strvec.size(), strvec_copy.size());
UNSIGNED_LONGS_EQUAL(strvec.capacity(), strvec_copy.capacity());
CHECK_EQUAL(*(strvec_copy.begin()), *(strvec.begin()));
CHECK_EQUAL(*(strvec_copy.begin() + 1), *(strvec.begin() + 1));
CHECK_EQUAL(*(strvec_copy.begin() + 2), *(strvec.begin() + 2));
}
TEST(test_strvec, assignment)
{
StrVec strvec({"one", "two", "three"});
StrVec strvec_copy;
strvec_copy = strvec;
UNSIGNED_LONGS_EQUAL(strvec.size(), strvec_copy.size());
UNSIGNED_LONGS_EQUAL(strvec.capacity(), strvec_copy.capacity());
CHECK_EQUAL(*(strvec_copy.begin()), *(strvec.begin()));
CHECK_EQUAL(*(strvec_copy.begin() + 1), *(strvec.begin() + 1));
CHECK_EQUAL(*(strvec_copy.begin() + 2), *(strvec.begin() + 2));
}
TEST(test_strvec, push_back)
{
StrVec strvec;
strvec.push_back("one");
strvec.push_back("two");
strvec.push_back("three");
UNSIGNED_LONGS_EQUAL(3, strvec.size());
UNSIGNED_LONGS_EQUAL(4, strvec.capacity());
CHECK_EQUAL(string("one"), *(strvec.begin()));
CHECK_EQUAL(string("two"), *(strvec.begin() + 1));
CHECK_EQUAL(string("three"), *(strvec.begin() + 2));
strvec.push_back("four");
strvec.push_back("five");
UNSIGNED_LONGS_EQUAL(5, strvec.size());
UNSIGNED_LONGS_EQUAL(8, strvec.capacity());
CHECK_EQUAL(string("one"), *(strvec.begin()));
CHECK_EQUAL(string("two"), *(strvec.begin() + 1));
CHECK_EQUAL(string("three"), *(strvec.begin() + 2));
CHECK_EQUAL(string("four"), *(strvec.begin() + 3));
CHECK_EQUAL(string("five"), *(strvec.begin() + 4));
}
TEST(test_strvec, resize)
{
StrVec strvec({"one", "two", "three"});
vector<string> vec({"one", "two", "three"});
strvec.resize(6);
vec.resize(6);
UNSIGNED_LONGS_EQUAL(vec.size(), strvec.size());
UNSIGNED_LONGS_EQUAL(vec.capacity(), strvec.capacity());
strvec.resize(1);
vec.resize(1);
UNSIGNED_LONGS_EQUAL(vec.size(), strvec.size());
UNSIGNED_LONGS_EQUAL(vec.capacity(), strvec.capacity());
}
TEST(test_strvec, reserve)
{
StrVec strvec({"one", "two", "three"});
vector<string> vec({"one", "two", "three"});
strvec.reserve(6);
vec.reserve(6);
UNSIGNED_LONGS_EQUAL(vec.size(), strvec.size());
UNSIGNED_LONGS_EQUAL(vec.capacity(), strvec.capacity());
strvec.reserve(1);
vec.reserve(1);
UNSIGNED_LONGS_EQUAL(vec.size(), strvec.size());
UNSIGNED_LONGS_EQUAL(vec.capacity(), strvec.capacity());
}
TEST(test_strvec, equal_test)
{
StrVec sv1({"Hello", "world"});
StrVec sv2({"Hello", "world"});
CHECK(sv1 == sv2);
sv2.push_back("!");
CHECK(sv1 != sv2);
}
TEST(test_strvec, less)
{
StrVec sv1{"Hello",};
StrVec sv2{"Hello", "world"};
CHECK(sv1 < sv2);
sv1 = {"absurd"};
sv2 = {"accord"};
CHECK(sv1 < sv2);
}
TEST(test_strvec, greater)
{
StrVec sv1{"Hello", "world"};
StrVec sv2{"Hello"};
CHECK(sv1 > sv2);
sv1 = {"accord"};
sv2 = {"absurd"};
CHECK(sv1 > sv2);
}
TEST(test_strvec, less_equal)
{
StrVec sv1{"Hello",};
StrVec sv2{"Hello", "world"};
CHECK(sv1 <= sv2);
sv1 = {"accord"};
sv2 = {"accord"};
CHECK(sv1 <= sv2);
}
TEST(test_strvec, greater_equal)
{
StrVec sv1{"Hello", "world"};
StrVec sv2{"Hello"};
CHECK(sv1 >= sv2);
sv1 = {"absurd"};
sv2 = {"absurd"};
CHECK(sv1 >= sv2);
}
TEST(test_strvec, init_list)
{
StrVec sv{"Chupa", "Chups"};
StrVec sv1{"Chupa", "Chups"};
StrVec sv2{"Beep", "Jeep"};
CHECK(sv == sv1);
sv = {"Beep", "Jeep"};
CHECK(sv == sv2);
}
TEST(test_strvec, indecies)
{
StrVec sv{"Chupa", "Chups"};
CHECK(sv[0] == "Chupa");
CHECK(sv[1] == "Chups");
}
| [
"vladimironiuk@gmail.com"
] | vladimironiuk@gmail.com |
b5dc0c79992d945eac9ea54fed36bdba8576881d | 8d651712a7f897dfd0104b25d92ce3fe5857c009 | /src/ChainConnector.h | 90c909443537a9c0a20699e3fd560b6a600e3732 | [] | no_license | 8JupiterMoll8/Strategy-Pattern-Teensy-Audio | 6811cf593e0d83ff25909d3e45d13a2ea97138da | 7e977595df9dd5605f4fce5c974b7b80120d6bac | refs/heads/master | 2021-02-17T21:44:51.645519 | 2020-03-05T11:12:29 | 2020-03-05T11:12:29 | 245,129,404 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 301 | h | #ifndef CHAINCONNECTOR
#define CHAINCONNECTOR
class ChainConnector
{
public:
~ChainConnector(){}
virtual void connect() =0;
virtual void disconnect()=0;
//virtual void init()=0;
//virtual void update()=0;
};
#endif /* CHAINCONNECTOR */
| [
"bautista@gmx.de"
] | bautista@gmx.de |
de87d1eb6a565dc8792599d235cfb5731205d811 | f3c43108ef8f33267e173a7ab856f3e21d8d5a95 | /ConsoleApplication1/ConsoleApplication1/ConsoleApplication1.cpp | d7ce3ed1522b53da970dc3ffc30be399cc2cba2f | [] | no_license | manognach/.NetPractice | 000ff352af2bbe886f3f21962dab2554db7a7f2c | d3f9805e9e62ab6c1c1a1be66b3488eea0a81f32 | refs/heads/master | 2021-01-19T21:45:06.117228 | 2017-02-13T01:47:56 | 2017-02-13T01:47:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 446 | cpp | // ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
int main()
{
std::cout << "Hello World!";
std::cout << "This is my first C++ program";
std::cout << "Let's add two numbers!";
std::cout << "Enter two numbers:";
int num1;
int num2;
std::cin >> num1;
std::cin >> num2;
int sum = num1 + num2;
std::cout << sum;
int pause;
std::cin >> pause;
return 0;
}
| [
"Christopher Floyd"
] | Christopher Floyd |
b26e1a04b3056228124993fea1d7534c81d7a68d | d69ad7c590853d98e336280f6f1d820509942f19 | /project.cpp | 2c5970a890b5f7f81ccf3e3dec388a98a085b3df | [] | no_license | shubh1357/3D-Gears | fd9ec1776117b0e3199c13cc0801022da64dd2fb | 19d408ff32f47a06506ce3d06bc9256b177264c5 | refs/heads/master | 2020-06-01T00:37:58.485808 | 2019-06-06T10:28:19 | 2019-06-06T10:28:19 | 190,562,040 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,912 | cpp | #include <math.h>
#include <stdlib.h>
#include <GL/glut.h>
#ifndef M_PI
#define M_PI 3.14159265
#endif
/**
Input: inner_radius - radius of hole at center
outer_radius - radius at center of teeth
width - width of gear
teeth - number of teeth
tooth_depth - depth of tooth
**/
static void gear(GLfloat inner_radius, GLfloat outer_radius, GLfloat width,
GLint teeth, GLfloat tooth_depth)
{
GLint i;
GLfloat r0, r1, r2;
GLfloat angle, da;
GLfloat u, v, len;
r0 = inner_radius;
r1 = outer_radius - tooth_depth / 2.0;
r2 = outer_radius + tooth_depth / 2.0;
da = 2.0 * M_PI / teeth / 4.0;
glShadeModel(GL_FLAT);
glNormal3f(0.0, 0.0, 1.0);
/* draw front face */
glBegin(GL_QUAD_STRIP);
for (i = 0; i <= teeth; i++) {
angle = i * 2.0 * M_PI / teeth;
glVertex3f(r0 * cos(angle), r0 * sin(angle), width * 0.5);
glVertex3f(r1 * cos(angle), r1 * sin(angle), width * 0.5);
glVertex3f(r0 * cos(angle), r0 * sin(angle), width * 0.5);
glVertex3f(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), width * 0.5);
}
glEnd();
/* draw front sides of teeth */
glBegin(GL_QUADS);
da = 2.0 * M_PI / teeth / 4.0;
for (i = 0; i < teeth; i++) {
angle = i * 2.0 * M_PI / teeth;
glVertex3f(r1 * cos(angle), r1 * sin(angle), width * 0.5);
glVertex3f(r2 * cos(angle + da), r2 * sin(angle + da), width * 0.5);
glVertex3f(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), width * 0.5);
glVertex3f(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), width * 0.5);
}
glEnd();
glNormal3f(0.0, 0.0, -1.0);
/* draw back face */
glBegin(GL_QUAD_STRIP);
for (i = 0; i <= teeth; i++) {
angle = i * 2.0 * M_PI / teeth;
glVertex3f(r1 * cos(angle), r1 * sin(angle), -width * 0.5);
glVertex3f(r0 * cos(angle), r0 * sin(angle), -width * 0.5);
glVertex3f(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), -width * 0.5);
glVertex3f(r0 * cos(angle), r0 * sin(angle), -width * 0.5);
}
glEnd();
/* draw back sides of teeth */
glBegin(GL_QUADS);
da = 2.0 * M_PI / teeth / 4.0;
for (i = 0; i < teeth; i++) {
angle = i * 2.0 * M_PI / teeth;
glVertex3f(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), -width * 0.5);
glVertex3f(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), -width * 0.5);
glVertex3f(r2 * cos(angle + da), r2 * sin(angle + da), -width * 0.5);
glVertex3f(r1 * cos(angle), r1 * sin(angle), -width * 0.5);
}
glEnd();
/* draw outward faces of teeth */
glBegin(GL_QUAD_STRIP);
for (i = 0; i < teeth; i++) {
angle = i * 2.0 * M_PI / teeth;
glVertex3f(r1 * cos(angle), r1 * sin(angle), width * 0.5);
glVertex3f(r1 * cos(angle), r1 * sin(angle), -width * 0.5);
u = r2 * cos(angle + da) - r1 * cos(angle);
v = r2 * sin(angle + da) - r1 * sin(angle);
len = sqrt(u * u + v * v);
u /= len;
v /= len;
glNormal3f(v, -u, 0.0);
glVertex3f(r2 * cos(angle + da), r2 * sin(angle + da), width * 0.5);
glVertex3f(r2 * cos(angle + da), r2 * sin(angle + da), -width * 0.5);
glNormal3f(cos(angle), sin(angle), 0.0);
glVertex3f(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), width * 0.5);
glVertex3f(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), -width * 0.5);
u = r1 * cos(angle + 3 * da) - r2 * cos(angle + 2 * da);
v = r1 * sin(angle + 3 * da) - r2 * sin(angle + 2 * da);
glNormal3f(v, -u, 0.0);
glVertex3f(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), width * 0.5);
glVertex3f(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), -width * 0.5);
glNormal3f(cos(angle), sin(angle), 0.0);
}
glVertex3f(r1 * cos(0), r1 * sin(0), width * 0.5);
glVertex3f(r1 * cos(0), r1 * sin(0), -width * 0.5);
glEnd();
glShadeModel(GL_SMOOTH);
/* draw inside radius cylinder */
glBegin(GL_QUAD_STRIP);
for (i = 0; i <= teeth; i++) {
angle = i * 2.0 * M_PI / teeth;
glNormal3f(-cos(angle), -sin(angle), 0.0);
glVertex3f(r0 * cos(angle), r0 * sin(angle), -width * 0.5);
glVertex3f(r0 * cos(angle), r0 * sin(angle), width * 0.5);
}
glEnd();
}
static GLfloat view_rotx = 20.0, view_roty = 30.0, view_rotz = 0.0;
static GLint gear1, gear2, gear3;
static GLfloat angle = 0.0;
static GLuint limit;
static GLuint count = 1;
static void draw(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glRotatef(view_rotx, 1.0, 0.0, 0.0);
glRotatef(view_roty, 0.0, 1.0, 0.0);
glRotatef(view_rotz, 0.0, 0.0, 1.0);
glPushMatrix();
glTranslatef(-3.0, -2.0, 0.0);
glRotatef(angle, 0.0, 0.0, 1.0);
glCallList(gear1);
glPopMatrix();
glPushMatrix();
glTranslatef(3.1, -2.0, 0.0);
glRotatef(-2.0 * angle - 9.0, 0.0, 0.0, 1.0);
glCallList(gear2);
glPopMatrix();
glPushMatrix();
glTranslatef(-3.1, 4.2, 0.0);
glRotatef(-2.0 * angle - 25.0, 0.0, 0.0, 1.0);
glCallList(gear3);
glPopMatrix();
glPopMatrix();
glutSwapBuffers();
count++;
if (count == limit) {
exit(0);
}
}
static void idle(void)
{
angle += 2.0;
glutPostRedisplay();
}
/* change view angle, exit upon ESC */
static void key(unsigned char k, int x, int y)
{
switch (k) {
case 'z':
view_rotz += 5.0;
break;
case 'Z':
view_rotz -= 5.0;
break;
case 27: /* Escape */
exit(0);
break;
default:
return;
}
glutPostRedisplay();
}
/* change view angle */
static void special(int k, int x, int y)
{
switch (k) {
case GLUT_KEY_UP:
view_rotx += 5.0;
break;
case GLUT_KEY_DOWN:
view_rotx -= 5.0;
break;
case GLUT_KEY_LEFT:
view_roty += 5.0;
break;
case GLUT_KEY_RIGHT:
view_roty -= 5.0;
break;
default:
return;
}
glutPostRedisplay();
}
/* new window size or exposure */
static void reshape(int width, int height)
{
GLfloat h = (GLfloat)height / (GLfloat)width;
glViewport(0, 0, (GLint)width, (GLint)height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-1.0, 1.0, -h, h, 5.0, 60.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0, 0.0, -40.0);
}
static void init(void)
{
static GLfloat pos[4] =
{ 5.0, 5.0, 10.0, 0.0 };
static GLfloat red[4] =
{ 0.8, 0.1, 0.0, 1.0 };
static GLfloat green[4] =
{ 0.0, 0.8, 0.2, 1.0 };
static GLfloat blue[4] =
{ 0.2, 0.2, 1.0, 1.0 };
glLightfv(GL_LIGHT0, GL_POSITION, pos);
glEnable(GL_CULL_FACE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
/* make the gears */
gear1 = glGenLists(1);
glNewList(gear1, GL_COMPILE);
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, red);
gear(1.0, 4.0, 1.0, 20, 0.7);
glEndList();
gear2 = glGenLists(1);
glNewList(gear2, GL_COMPILE);
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, green);
gear(0.5, 2.0, 2.0, 10, 0.7);
glEndList();
gear3 = glGenLists(1);
glNewList(gear3, GL_COMPILE);
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, blue);
gear(1.3, 2.0, 0.5, 10, 0.7);
glEndList();
glEnable(GL_NORMALIZE);
}
void visible(int vis)
{
if (vis == GLUT_VISIBLE)
glutIdleFunc(idle);
else
glutIdleFunc(NULL);
}
int main(int argc, char **argv)
{
glutInit(&argc,argv);
if (argc > 1) {
/* do 'n' frames then exit */
limit = atoi(argv[1]) + 1;
}
else {
limit = 0;
}
glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
glutCreateWindow("Gears");
init();
glutDisplayFunc(draw);
glutReshapeFunc(reshape);
glutKeyboardFunc(key);
glutSpecialFunc(special);
glutVisibilityFunc(visible);
glutMainLoop();
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
4253f0605cb665bf63cd612bb18995b2980c7361 | ad97da91d042cbce41e6af35875a6a2eecd682a1 | /git_code/inorder_to_tree.cpp | e110cc3ac98c9359d7f13b6b7d09a2d64bdd79c5 | [] | no_license | gigacode/practise_code | d9098e0e9c70b2daee5b0c0358415912637ab8b4 | d6ffd70261ed4be9fa182a4a00bf633945ce2834 | refs/heads/master | 2021-01-01T06:10:17.923082 | 2016-01-17T17:45:03 | 2016-01-17T17:45:03 | 23,029,151 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 779 | cpp | #include <iostream>
#include <vector>
using namespace std;
typedef struct node {
int val;
struct node* left;
struct node* right;
}Node;
Node* inorderToTree(int array[], int low, int high) {
if(high < low)
return NULL;
int index = (low + high)/2;
Node *new_node = new Node;
new_node->val = array[index];
new_node->left = inorderToTree(array, low, index-1);
new_node->right = inorderToTree(array, index+1, high);
return new_node;
}
void printTree(Node* root) {
if (root == NULL)
return;
printTree(root->left);
cout << root->val;
printTree(root->right);
}
int main(int argc, char** argv) {
int array[] = {4, 2, 5, 1, 6, 3, 7};
Node *root = inorderToTree(array, 0, 6);
printTree(root);
}
| [
"pragathi.agar@gmail.com"
] | pragathi.agar@gmail.com |
350a73793c1ccc8b3a146597689398aba9ea7099 | d676d75f5cd97953ac843e0143e2be8685a88fbf | /Client/Structure.cpp | 1d176a442058deb9ecfed2f73799a0b65521e906 | [] | no_license | ZSQ15310164272/Video4Linux_methods | e0537a5d0c20d3de5d9cedfba5491de56a9b7dfa | 082526d90ba7ab95b06056c0f8961c77afb3ac67 | refs/heads/master | 2020-03-24T18:55:53.168416 | 2018-07-30T17:05:16 | 2018-07-30T17:05:16 | 142,903,862 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,994 | cpp | //
// Created by parallels on 4/27/17.
//
#include "Structure.h"
FILE *flog;
struct shared_package *shared_package_ptr=NULL;
using namespace std;
using namespace cv;
long long frame_count_last=0;
uint8_t image_buffer[307200];
int image_buffer_len;
struct shared_package * get_shared_package(){
int shmid;
shmid = shmget(307200, sizeof(struct shared_package), 0666 | IPC_CREAT);
struct shared_package * s = (struct shared_package *) shmat(shmid, NULL, 0);
printf("shmid:%d, p:%lx\n", shmid, s);
return s;
}
uint8_t getImageFromMemory(Mat &image){
if(shared_package_ptr==NULL)shared_package_ptr=get_shared_package();
//pthread_rwlock_rdlock(&shared_package_ptr->image_lock);
int nowsize = shared_package_ptr->image_size;
vector<char> img_data(shared_package_ptr->image_data, shared_package_ptr->image_data + nowsize);
long long frame_count_now=shared_package_ptr->count;
//pthread_rwlock_unlock(&shared_package_ptr->image_lock);
if(nowsize==0)return -1;
if(frame_count_now==frame_count_last)return -2;
try{
image = imdecode(Mat(img_data), CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_COLOR);
if(image.size().width<=0||image.size().height<=0)return -1;
frame_count_last=frame_count_now;
}catch (cv::Exception& e){
return -1;
}
return 0;
}
uint8_t getImageFromMemory(){
if(shared_package_ptr==NULL)shared_package_ptr=get_shared_package();
image_buffer_len = shared_package_ptr->image_size;
int frame_count_now=shared_package_ptr->count;
memcpy(image_buffer,shared_package_ptr->image_data,image_buffer_len);
if(image_buffer_len==0)return 1;
if(frame_count_now==frame_count_last)return 2;
frame_count_last=frame_count_now;
return 0;
}
void printlog(const char *format,...)
{
va_list args;
va_start(args ,format);
vprintf(format ,args);
va_end(args);
va_start(args, format);
vfprintf(flog, format, args);
va_end(args);
fflush(flog);
}
| [
"sqzhai1993@163.com"
] | sqzhai1993@163.com |
3016d1632cc3bc3df3515833d7489ea85ad4a4b2 | 73221e5fa1241e161ce61973006c8036d2750b9d | /core/math/sse/uInt16x8.h | 77256303e29ea650978e2a86a4c5908590882746 | [] | no_license | kv59piaoxue/ad-census-prototype | 054a6db5b880102c7fbab4fbc7e333c928055e8d | 1aadf09a0f3947785e1bd040edec45d2afcc3296 | refs/heads/master | 2021-04-14T00:44:02.957956 | 2016-08-12T09:55:05 | 2016-08-12T09:55:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,350 | h | #ifndef UINT16X8_H
#define UINT16X8_H
/**
* \file uInt16x8.h
* \brief
*
* \ingroup cppcorefiles
* \date Sept 2, 2012
* \author: apimenov
*/
#include <emmintrin.h>
#include <stdint.h>
#include "global.h"
#include "fixedVector.h"
#include "intBase16x8.h"
namespace corecvs {
class ALIGN_DATA(16) UInt16x8 : public IntBase16x8<UInt16x8>
{
public:
/* Shortcut for the base type */
typedef IntBase16x8<UInt16x8> BaseClass;
/* Constructors */
UInt16x8() {}
/**
* Copy constructor
**/
UInt16x8(const UInt16x8 &other) : BaseClass(other) {}
// explicit UInt16x8(const BaseClass &other) : BaseClass(other) {}
template<class Sibling>
explicit UInt16x8(const IntBase16x8<Sibling> &other) : BaseClass(other) {}
template<class Sibling>
explicit UInt16x8(IntBase16x8<Sibling> &other) : BaseClass(other) {}
/**
* Create SSE integer vector from integer constant
**/
UInt16x8(const __m128i &_data) :
BaseClass(_data) {}
explicit UInt16x8(uint16_t constant) :
BaseClass(int16_t(constant)){}
explicit UInt16x8(uint16_t c0, uint16_t c1, uint16_t c2, uint16_t c3,
uint16_t c4, uint16_t c5, uint16_t c6, uint16_t c7) :
BaseClass(int16_t(c0), int16_t(c1), int16_t(c2), int16_t(c3), int16_t(c4), int16_t(c5), int16_t(c6), int16_t(c7)) {}
explicit UInt16x8(const uint16_t * const data_ptr) :
BaseClass((const int16_t* )data_ptr) {}
explicit inline UInt16x8(const FixedVector<uint16_t,8> input) :
BaseClass((const int16_t*) &(input[0])) {}
/** Load unaligned. Not safe to use until you exactly know what you are doing */
static UInt16x8 load(const uint16_t data[8])
{
return BaseClass::load((const int16_t*) data);
}
/** Load aligned. Not safe to use until you exactly know what you are doing */
static UInt16x8 loadAligned(const uint16_t data[8])
{
return BaseClass::loadAligned((const int16_t*) data);
}
void save(uint16_t data[8]) const
{
BaseClass::save((int16_t*)data);
}
/** Save aligned. Not safe to use until you exactly know what you are doing */
void saveAligned(uint16_t data[8]) const
{
BaseClass::saveAligned((int16_t*) data);
}
/** Stream aligned. Not safe to use until you exactly know what you are doing */
void streamAligned(uint16_t data[8]) const
{
BaseClass::streamAligned((int16_t*) data);
}
/* Immediate shift operations */
friend UInt16x8 operator >> (const UInt16x8 &left, uint32_t count);
friend UInt16x8 operator >>= (UInt16x8 &left, uint32_t count);
/* Shift operations */
friend UInt16x8 operator >> (const UInt16x8 &left, const UInt16x8 &right);
friend UInt16x8 operator >>= (UInt16x8 &left, const UInt16x8 &right);
/* Comparison */
friend UInt16x8 operator < (const UInt16x8 &left, const UInt16x8 &right);
friend UInt16x8 operator > (const UInt16x8 &left, const UInt16x8 &right);
/* Multiplication beware - overrun is possible*/
friend UInt16x8 productHigherPart (const UInt16x8 &left, const UInt16x8 &right);
/*Print to stream helper */
friend ostream & operator << (ostream &out, const UInt16x8 &vector);
};
FORCE_INLINE UInt16x8 operator >> (const UInt16x8 &left, uint32_t count) {
return UInt16x8(_mm_srli_epi16(left.data, count));
}
FORCE_INLINE UInt16x8 operator >>= (UInt16x8 &left, uint32_t count) {
left.data = _mm_srli_epi16(left.data, count);
return left;
}
FORCE_INLINE UInt16x8 operator >> (const UInt16x8 &left, const UInt16x8 &right) {
return UInt16x8(_mm_srl_epi16(left.data, right.data));
}
FORCE_INLINE UInt16x8 operator >>= (UInt16x8 &left, const UInt16x8 &right) {
left.data = _mm_srl_epi16(left.data, right.data);
return left;
}
FORCE_INLINE UInt16x8 operator < (const UInt16x8 &left, const UInt16x8 &right) {
return UInt16x8(_mm_cmplt_epi16(left.data, right.data));
}
FORCE_INLINE UInt16x8 operator > (const UInt16x8 &left, const UInt16x8 &right) {
return UInt16x8(_mm_cmpgt_epi16(left.data, right.data));
}
FORCE_INLINE UInt16x8 productHigherPart (const UInt16x8 &left, const UInt16x8 &right) {
return UInt16x8(_mm_mulhi_epu16(left.data, right.data));
}
} //namespace corecvs
#endif // UINT16X8_H
| [
"contact.aldrog@gmail.com"
] | contact.aldrog@gmail.com |
95514e83149c7447a58e1a64c926de913779bed2 | c2768612fa8f777352297d69519c17063f96d773 | /oxygine-framework/oxygine/src/math/Vector2.h | b5c4e1ffb81d92a7ac9460e1ef70882fb74dd536 | [
"MIT"
] | permissive | phpdaddy/darts | 01a9c36af1187f85b471f2d95c492cac42b27e7f | 6d9a11845795064ae4172ee78b78c0256e944fd4 | refs/heads/master | 2022-11-27T08:30:53.715133 | 2020-08-10T16:24:19 | 2020-08-10T16:24:19 | 286,524,466 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,622 | h | #pragma once
#include "oxygine_include.h"
#include "ScalarMath.h"
//#include "math/vector3.h"
namespace oxygine
{
template <class T>
class VectorT2
{
typedef VectorT2<T> vector2;
public:
typedef T type;
//////////////
VectorT2();
VectorT2(T, T);
VectorT2& operator+=(const VectorT2&);
VectorT2& operator-=(const VectorT2&);
VectorT2 operator + (const VectorT2&) const;
VectorT2 operator - (const VectorT2&) const;
VectorT2 operator - () const;
void set(T x_, T y_) {x = x_; y = y_;}
void setZero() {x = 0; y = 0;}
template <class R>
VectorT2 operator * (R s) const {VectorT2 r(*this); r.x = type(r.x * s); r.y = type(r.y * s); return r;}
template <class R>
VectorT2 operator / (R s) const {VectorT2 r(*this); r.x /= s; r.y /= s; return r;}
template <class R>
VectorT2 operator *= (R s) {x *= s; y *= s; return (*this);}
template <class R>
VectorT2 operator /= (R s) {x /= s; y /= s; return (*this);}
VectorT2 mult(const VectorT2& r) const {return VectorT2(x * r.x, y * r.y);}
VectorT2 div(const VectorT2& r) const {return VectorT2(x / r.x, y / r.y);}
operator VectorT2<float> () const {return this->cast< VectorT2<float> >();}
template<typename R>
R cast() const
{
typedef R vec2;
typedef typename R::type vec2type;
return vec2(vec2type(x), vec2type(y));
}
bool operator == (const VectorT2& r) const;
bool operator != (const VectorT2& r) const;
//inline T &operator[](int i){return m[i];}
//inline const T &operator[](int i)const{return m[i];}
T length() const {return (T)scalar::sqrt(x * x + y * y);}
T sqlength() const {return dot(*this);}
void normalize() { normalize(*this, *this); }
void normalizeTo(T len) { normalize(); *this *= len; }
VectorT2 normalized() const {VectorT2 t = *this; t.normalize(); return t;}
float distance(const VectorT2& v) const { return VectorT2(x - v.x, y - v.y).length();}
T dot(const VectorT2& vr) const {return dot(*this, vr);}
static T dot(const VectorT2& v1, const VectorT2& v2);
static VectorT2& normalize(VectorT2& out, const VectorT2& v);
struct
{
T x, y;
};
};
/*
template<class T>
VectorT2<T>::operator VectorT2<float> ()const
{
return VectorT2<float>(float(x), float(y));
}
*/
template<class T>
bool VectorT2<T>::operator == (const VectorT2<T>& r) const
{
if (x == r.x && y == r.y)
return true;
return false;
}
template<class T>
bool VectorT2<T>::operator != (const VectorT2<T>& r) const
{
if (x != r.x || y != r.y)
return true;
return false;
}
template <class T>
VectorT2<T>::VectorT2(): x(0), y(0)
{}
template <class T>
VectorT2<T>::VectorT2(T X, T Y):
x(X), y(Y)
{
}
template <class T>
VectorT2<T>& VectorT2<T>::operator+=(const VectorT2& v)
{
x += v.x; y += v.y; return (*this);
}
template <class T>
VectorT2<T>& VectorT2<T>::operator-=(const VectorT2& v)
{
x -= v.x; y -= v.y; return (*this);
}
template <class T>
VectorT2<T> VectorT2<T>::operator + (const VectorT2& v) const
{
return VectorT2(x + v.x, y + v.y);
}
template <class T>
VectorT2<T> VectorT2<T>::operator - (const VectorT2& v) const
{
return VectorT2(x - v.x, y - v.y);
}
template <class T>
VectorT2<T> VectorT2<T>::operator - () const
{
return VectorT2<T>(-x, -y);
}
template <class T>
inline T VectorT2<T>::dot(const VectorT2& v1, const VectorT2& v2)
{
return v1.x * v2.x + v1.y * v2.y;
}
template <class T>
inline VectorT2<T>& VectorT2<T>::normalize(VectorT2<T>& out, const VectorT2<T>& v)
{
T norm = T(1.0) / scalar::sqrt(v.x * v.x + v.y * v.y);
out = v;
/*
if (norm < 0.0001)
{
return out;
}
*/
out.x *= norm;
out.y *= norm;
return out;
}
typedef VectorT2<float> Vector2;
typedef VectorT2<double> VectorD2;
typedef VectorT2<int> Point;
typedef VectorT2<short> PointS;
}
| [
"m.prysiazhnyi@gmail.com"
] | m.prysiazhnyi@gmail.com |
4a7f99b40874cc6ceb120658f5b18fc48419b826 | b748c41bd36f5f69c81e5318e77151e2c6fa3f31 | /firmware/PeopleInService.h | ecc02dc4696b9720305ee6ca4aba0b8805075c71 | [
"MIT"
] | permissive | mahbubiftekhar/IOT_ROOM_OCCUPANCY | 019c1113b6707d7412ae649d74e60bf9586bb72d | bf4ba430d0d8bc44ecc002d5c73aa59480625344 | refs/heads/master | 2020-04-11T19:49:56.127422 | 2019-08-11T23:41:35 | 2019-08-11T23:41:35 | 162,048,700 | 0 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,635 | h | /* mbed Microcontroller Library
* Copyright (c) 2006-2013 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __PEOPLE_IN_SERVICE_H__
#define __PEOPLE_IN_SERVICE_H__
class PeopleInService {
public:
const static uint16_t PEOPLE_IN_SERVICE_UUID = 0xA000;
const static uint16_t PEOPLE_IN_CHARACTERISTIC_UUID = 0xA001;
PeopleInService(BLE &_ble, bool buttonPressedInitial) :
ble(_ble), buttonState(PEOPLE_IN_CHARACTERISTIC_UUID, &buttonPressedInitial, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY)
{
GattCharacteristic *charTable[] = {&buttonState};
GattService PeopleInService(PeopleInService::PEOPLE_IN_SERVICE_UUID, charTable, sizeof(charTable) / sizeof(GattCharacteristic *));
ble.gattServer().addService(PeopleInService);
}
void updateButtonState(bool newState) {
ble.gattServer().write(buttonState.getValueHandle(), (uint8_t *)&newState, sizeof(bool));
}
private:
BLE &ble;
ReadOnlyGattCharacteristic<bool> buttonState;
};
#endif /* #ifndef __PEOPLE_IN_SERVICE_H__ */
| [
"rusab36@gmail.com"
] | rusab36@gmail.com |
5fc0787b3b0199769656cb947b12f986d4841778 | d820e4f69e243bb6db792377ef1014d1f85dd833 | /UX/cJSON/cJSON.cpp | 26f28cea54a1244ad02773e2d7c04b9d7a47140a | [
"MIT"
] | permissive | UberSnipUX/UXBlumIO | d2de8e3c8507b18d66ced96b467f80d7ef740266 | 01b89b8a15799baf172a597d52d2dfb617df7845 | refs/heads/master | 2021-01-10T15:25:02.444841 | 2016-03-31T11:15:09 | 2016-03-31T11:15:09 | 54,929,304 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,635 | cpp | /*
Copyright (c) 2009 Dave Gamble
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.
*/
/* cJSON */
/* JSON parser in C. */
#pragma warning(disable:4996)
#define _CRT_SECURE_NO_WARNINGS 1
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
#include <limits.h>
#include <ctype.h>
#include "pch.h"
#include "cJSON.h"
static const char *ep;
const char *cJSON_GetErrorPtr(void) {return ep;}
static int cJSON_strcasecmp(const char *s1,const char *s2)
{
if (!s1) return (s1==s2)?0:1;if (!s2) return 1;
for(; tolower(*s1) == tolower(*s2); ++s1, ++s2) if(*s1 == 0) return 0;
return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2);
}
static void *(*cJSON_malloc)(size_t sz) = malloc;
static void (*cJSON_free)(void *ptr) = free;
static char* cJSON_strdup(const char* str)
{
size_t len;
char* copy;
len = strlen(str) + 1;
if (!(copy = (char*)cJSON_malloc(len))) return 0;
memcpy(copy,str,len);
return copy;
}
void cJSON_InitHooks(cJSON_Hooks* hooks)
{
if (!hooks) { /* Reset hooks */
cJSON_malloc = malloc;
cJSON_free = free;
return;
}
cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc;
cJSON_free = (hooks->free_fn)?hooks->free_fn:free;
}
/* Internal constructor. */
static cJSON *cJSON_New_Item(void)
{
cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON));
if (node) memset(node,0,sizeof(cJSON));
return node;
}
/* Delete a cJSON structure. */
void cJSON_Delete(cJSON *c)
{
cJSON *next;
while (c)
{
next=c->next;
if (!(c->type&cJSON_IsReference) && c->child) cJSON_Delete(c->child);
if (!(c->type&cJSON_IsReference) && c->valuestring) cJSON_free(c->valuestring);
if (!(c->type&cJSON_StringIsConst) && c->string) cJSON_free(c->string);
cJSON_free(c);
c=next;
}
}
/* Parse the input text to generate a number, and populate the result into item. */
static const char *parse_number(cJSON *item,const char *num)
{
double n=0,sign=1,scale=0;int subscale=0,signsubscale=1;
if (*num=='-') sign=-1,num++; /* Has sign? */
if (*num=='0') num++; /* is zero */
if (*num>='1' && *num<='9') do n=(n*10.0)+(*num++ -'0'); while (*num>='0' && *num<='9'); /* Number? */
if (*num=='.' && num[1]>='0' && num[1]<='9') {num++; do n=(n*10.0)+(*num++ -'0'),scale--; while (*num>='0' && *num<='9');} /* Fractional part? */
if (*num=='e' || *num=='E') /* Exponent? */
{ num++;if (*num=='+') num++; else if (*num=='-') signsubscale=-1,num++; /* With sign? */
while (*num>='0' && *num<='9') subscale=(subscale*10)+(*num++ - '0'); /* Number? */
}
n=sign*n*pow(10.0,(scale+subscale*signsubscale)); /* number = +/- number.fraction * 10^+/- exponent */
item->valuedouble=n;
item->valueint=(int)n;
item->type=cJSON_Number;
return num;
}
static int pow2gt (int x) { --x; x|=x>>1; x|=x>>2; x|=x>>4; x|=x>>8; x|=x>>16; return x+1; }
typedef struct {char *buffer; int length; int offset; } printbuffer;
static char* ensure(printbuffer *p,int needed)
{
char *newbuffer;int newsize;
if (!p || !p->buffer) return 0;
needed+=p->offset;
if (needed<=p->length) return p->buffer+p->offset;
newsize=pow2gt(needed);
newbuffer=(char*)cJSON_malloc(newsize);
if (!newbuffer) {cJSON_free(p->buffer);p->length=0,p->buffer=0;return 0;}
if (newbuffer) memcpy(newbuffer,p->buffer,p->length);
cJSON_free(p->buffer);
p->length=newsize;
p->buffer=newbuffer;
return newbuffer+p->offset;
}
static int update(printbuffer *p)
{
char *str;
if (!p || !p->buffer) return 0;
str=p->buffer+p->offset;
return p->offset+strlen(str);
}
/* Render the number nicely from the given item into a string. */
static char *print_number(cJSON *item,printbuffer *p)
{
char *str=0;
double d=item->valuedouble;
if (d==0)
{
if (p) str=ensure(p,2);
else str=(char*)cJSON_malloc(2); /* special case for 0. */
if (str) strcpy(str,"0");
}
else if (fabs(((double)item->valueint)-d)<=DBL_EPSILON && d<=INT_MAX && d>=INT_MIN)
{
if (p) str=ensure(p,21);
else str=(char*)cJSON_malloc(21); /* 2^64+1 can be represented in 21 chars. */
if (str) sprintf(str,"%d",item->valueint);
}
else
{
if (p) str=ensure(p,64);
else str=(char*)cJSON_malloc(64); /* This is a nice tradeoff. */
if (str)
{
if (fabs(floor(d)-d)<=DBL_EPSILON && fabs(d)<1.0e60)sprintf(str,"%.0f",d);
else if (fabs(d)<1.0e-6 || fabs(d)>1.0e9) sprintf(str,"%e",d);
else sprintf(str,"%f",d);
}
}
return str;
}
static unsigned parse_hex4(const char *str)
{
unsigned h=0;
if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0;
h=h<<4;str++;
if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0;
h=h<<4;str++;
if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0;
h=h<<4;str++;
if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0;
return h;
}
/* Parse the input text into an unescaped cstring, and populate item. */
static const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
static const char *parse_string(cJSON *item,const char *str)
{
const char *ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2;
if (*str!='\"') {ep=str;return 0;} /* not a string! */
while (*ptr!='\"' && *ptr && ++len) if (*ptr++ == '\\') ptr++; /* Skip escaped quotes. */
out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */
if (!out) return 0;
ptr=str+1;ptr2=out;
while (*ptr!='\"' && *ptr)
{
if (*ptr!='\\') *ptr2++=*ptr++;
else
{
ptr++;
switch (*ptr)
{
case 'b': *ptr2++='\b'; break;
case 'f': *ptr2++='\f'; break;
case 'n': *ptr2++='\n'; break;
case 'r': *ptr2++='\r'; break;
case 't': *ptr2++='\t'; break;
case 'u': /* transcode utf16 to utf8. */
uc=parse_hex4(ptr+1);ptr+=4; /* get the unicode char. */
if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) break; /* check for invalid. */
if (uc>=0xD800 && uc<=0xDBFF) /* UTF16 surrogate pairs. */
{
if (ptr[1]!='\\' || ptr[2]!='u') break; /* missing second-half of surrogate. */
uc2=parse_hex4(ptr+3);ptr+=6;
if (uc2<0xDC00 || uc2>0xDFFF) break; /* invalid second-half of surrogate. */
uc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF));
}
len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len;
switch (len) {
case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 1: *--ptr2 =(uc | firstByteMark[len]);
}
ptr2+=len;
break;
default: *ptr2++=*ptr; break;
}
ptr++;
}
}
*ptr2=0;
if (*ptr=='\"') ptr++;
item->valuestring=out;
item->type=cJSON_String;
return ptr;
}
/* Render the cstring provided to an escaped version that can be printed. */
static char *print_string_ptr(const char *str,printbuffer *p)
{
const char *ptr;char *ptr2,*out;int len=0,flag=0;unsigned char token;
for (ptr=str;*ptr;ptr++) flag|=((*ptr>0 && *ptr<32)||(*ptr=='\"')||(*ptr=='\\'))?1:0;
if (!flag)
{
len=ptr-str;
if (p) out=ensure(p,len+3);
else out=(char*)cJSON_malloc(len+3);
if (!out) return 0;
ptr2=out;*ptr2++='\"';
strcpy(ptr2,str);
ptr2[len]='\"';
ptr2[len+1]=0;
return out;
}
if (!str)
{
if (p) out=ensure(p,3);
else out=(char*)cJSON_malloc(3);
if (!out) return 0;
strcpy(out,"\"\"");
return out;
}
ptr=str;while ((token=*ptr) && ++len) {if (strchr("\"\\\b\f\n\r\t",token)) len++; else if (token<32) len+=5;ptr++;}
if (p) out=ensure(p,len+3);
else out=(char*)cJSON_malloc(len+3);
if (!out) return 0;
ptr2=out;ptr=str;
*ptr2++='\"';
while (*ptr)
{
if ((unsigned char)*ptr>31 && *ptr!='\"' && *ptr!='\\') *ptr2++=*ptr++;
else
{
*ptr2++='\\';
switch (token=*ptr++)
{
case '\\': *ptr2++='\\'; break;
case '\"': *ptr2++='\"'; break;
case '\b': *ptr2++='b'; break;
case '\f': *ptr2++='f'; break;
case '\n': *ptr2++='n'; break;
case '\r': *ptr2++='r'; break;
case '\t': *ptr2++='t'; break;
default: sprintf(ptr2,"u%04x",token);ptr2+=5; break; /* escape and print */
}
}
}
*ptr2++='\"';*ptr2++=0;
return out;
}
/* Invote print_string_ptr (which is useful) on an item. */
static char *print_string(cJSON *item,printbuffer *p) {return print_string_ptr(item->valuestring,p);}
/* Predeclare these prototypes. */
static const char *parse_value(cJSON *item,const char *value);
static char *print_value(cJSON *item,int depth,int fmt,printbuffer *p);
static const char *parse_array(cJSON *item,const char *value);
static char *print_array(cJSON *item,int depth,int fmt,printbuffer *p);
static const char *parse_object(cJSON *item,const char *value);
static char *print_object(cJSON *item,int depth,int fmt,printbuffer *p);
/* Utility to jump whitespace and cr/lf */
static const char *skip(const char *in) {while (in && *in && (unsigned char)*in<=32) in++; return in;}
/* Parse an object - create a new root, and populate. */
cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated)
{
const char *end=0;
cJSON *c=cJSON_New_Item();
ep=0;
if (!c) return 0; /* memory fail */
end=parse_value(c,skip(value));
if (!end) {cJSON_Delete(c);return 0;} /* parse failure. ep is set. */
/* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
if (require_null_terminated) {end=skip(end);if (*end) {cJSON_Delete(c);ep=end;return 0;}}
if (return_parse_end) *return_parse_end=end;
return c;
}
/* Default options for cJSON_Parse */
cJSON *cJSON_Parse(const char *value) {return cJSON_ParseWithOpts(value,0,0);}
/* Render a cJSON item/entity/structure to text. */
char *cJSON_Print(cJSON *item) {return print_value(item,0,1,0);}
char *cJSON_PrintUnformatted(cJSON *item) {return print_value(item,0,0,0);}
char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt)
{
printbuffer p;
p.buffer=(char*)cJSON_malloc(prebuffer);
p.length=prebuffer;
p.offset=0;
return print_value(item,0,fmt,&p);
return p.buffer;
}
/* Parser core - when encountering text, process appropriately. */
static const char *parse_value(cJSON *item,const char *value)
{
if (!value) return 0; /* Fail on null. */
if (!strncmp(value,"null",4)) { item->type=cJSON_NULL; return value+4; }
if (!strncmp(value,"false",5)) { item->type=cJSON_False; return value+5; }
if (!strncmp(value,"true",4)) { item->type=cJSON_True; item->valueint=1; return value+4; }
if (*value=='\"') { return parse_string(item,value); }
if (*value=='-' || (*value>='0' && *value<='9')) { return parse_number(item,value); }
if (*value=='[') { return parse_array(item,value); }
if (*value=='{') { return parse_object(item,value); }
ep=value;return 0; /* failure. */
}
/* Render a value to text. */
static char *print_value(cJSON *item,int depth,int fmt,printbuffer *p)
{
char *out=0;
if (!item) return 0;
if (p)
{
switch ((item->type)&255)
{
case cJSON_NULL: {out=ensure(p,5); if (out) strcpy(out,"null"); break;}
case cJSON_False: {out=ensure(p,6); if (out) strcpy(out,"false"); break;}
case cJSON_True: {out=ensure(p,5); if (out) strcpy(out,"true"); break;}
case cJSON_Number: out=print_number(item,p);break;
case cJSON_String: out=print_string(item,p);break;
case cJSON_Array: out=print_array(item,depth,fmt,p);break;
case cJSON_Object: out=print_object(item,depth,fmt,p);break;
}
}
else
{
switch ((item->type)&255)
{
case cJSON_NULL: out=cJSON_strdup("null"); break;
case cJSON_False: out=cJSON_strdup("false");break;
case cJSON_True: out=cJSON_strdup("true"); break;
case cJSON_Number: out=print_number(item,0);break;
case cJSON_String: out=print_string(item,0);break;
case cJSON_Array: out=print_array(item,depth,fmt,0);break;
case cJSON_Object: out=print_object(item,depth,fmt,0);break;
}
}
return out;
}
/* Build an array from input text. */
static const char *parse_array(cJSON *item,const char *value)
{
cJSON *child;
if (*value!='[') {ep=value;return 0;} /* not an array! */
item->type=cJSON_Array;
value=skip(value+1);
if (*value==']') return value+1; /* empty array. */
item->child=child=cJSON_New_Item();
if (!item->child) return 0; /* memory fail */
value=skip(parse_value(child,skip(value))); /* skip any spacing, get the value. */
if (!value) return 0;
while (*value==',')
{
cJSON *new_item;
if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */
child->next=new_item;new_item->prev=child;child=new_item;
value=skip(parse_value(child,skip(value+1)));
if (!value) return 0; /* memory fail */
}
if (*value==']') return value+1; /* end of array */
ep=value;return 0; /* malformed. */
}
/* Render an array to text */
static char *print_array(cJSON *item,int depth,int fmt,printbuffer *p)
{
char **entries;
char *out=0,*ptr,*ret;int len=5;
cJSON *child=item->child;
int numentries=0,i=0,fail=0;
size_t tmplen=0;
/* How many entries in the array? */
while (child) numentries++,child=child->next;
/* Explicitly handle numentries==0 */
if (!numentries)
{
if (p) out=ensure(p,3);
else out=(char*)cJSON_malloc(3);
if (out) strcpy(out,"[]");
return out;
}
if (p)
{
/* Compose the output array. */
i=p->offset;
ptr=ensure(p,1);if (!ptr) return 0; *ptr='['; p->offset++;
child=item->child;
while (child && !fail)
{
print_value(child,depth+1,fmt,p);
p->offset=update(p);
if (child->next) {len=fmt?2:1;ptr=ensure(p,len+1);if (!ptr) return 0;*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;p->offset+=len;}
child=child->next;
}
ptr=ensure(p,2);if (!ptr) return 0; *ptr++=']';*ptr=0;
out=(p->buffer)+i;
}
else
{
/* Allocate an array to hold the values for each */
entries=(char**)cJSON_malloc(numentries*sizeof(char*));
if (!entries) return 0;
memset(entries,0,numentries*sizeof(char*));
/* Retrieve all the results: */
child=item->child;
while (child && !fail)
{
ret=print_value(child,depth+1,fmt,0);
entries[i++]=ret;
if (ret) len+=strlen(ret)+2+(fmt?1:0); else fail=1;
child=child->next;
}
/* If we didn't fail, try to malloc the output string */
if (!fail) out=(char*)cJSON_malloc(len);
/* If that fails, we fail. */
if (!out) fail=1;
/* Handle failure. */
if (fail)
{
for (i=0;i<numentries;i++) if (entries[i]) cJSON_free(entries[i]);
cJSON_free(entries);
return 0;
}
/* Compose the output array. */
*out='[';
ptr=out+1;*ptr=0;
for (i=0;i<numentries;i++)
{
tmplen=strlen(entries[i]);memcpy(ptr,entries[i],tmplen);ptr+=tmplen;
if (i!=numentries-1) {*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;}
cJSON_free(entries[i]);
}
cJSON_free(entries);
*ptr++=']';*ptr++=0;
}
return out;
}
/* Build an object from the text. */
static const char *parse_object(cJSON *item,const char *value)
{
cJSON *child;
if (*value!='{') {ep=value;return 0;} /* not an object! */
item->type=cJSON_Object;
value=skip(value+1);
if (*value=='}') return value+1; /* empty array. */
item->child=child=cJSON_New_Item();
if (!item->child) return 0;
value=skip(parse_string(child,skip(value)));
if (!value) return 0;
child->string=child->valuestring;child->valuestring=0;
if (*value!=':') {ep=value;return 0;} /* fail! */
value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */
if (!value) return 0;
while (*value==',')
{
cJSON *new_item;
if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */
child->next=new_item;new_item->prev=child;child=new_item;
value=skip(parse_string(child,skip(value+1)));
if (!value) return 0;
child->string=child->valuestring;child->valuestring=0;
if (*value!=':') {ep=value;return 0;} /* fail! */
value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */
if (!value) return 0;
}
if (*value=='}') return value+1; /* end of array */
ep=value;return 0; /* malformed. */
}
/* Render an object to text. */
static char *print_object(cJSON *item,int depth,int fmt,printbuffer *p)
{
char **entries=0,**names=0;
char *out=0,*ptr,*ret,*str;int len=7,i=0,j;
cJSON *child=item->child;
int numentries=0,fail=0;
size_t tmplen=0;
/* Count the number of entries. */
while (child) numentries++,child=child->next;
/* Explicitly handle empty object case */
if (!numentries)
{
if (p) out=ensure(p,fmt?depth+4:3);
else out=(char*)cJSON_malloc(fmt?depth+4:3);
if (!out) return 0;
ptr=out;*ptr++='{';
if (fmt) {*ptr++='\n';for (i=0;i<depth-1;i++) *ptr++='\t';}
*ptr++='}';*ptr++=0;
return out;
}
if (p)
{
/* Compose the output: */
i=p->offset;
len=fmt?2:1; ptr=ensure(p,len+1); if (!ptr) return 0;
*ptr++='{'; if (fmt) *ptr++='\n'; *ptr=0; p->offset+=len;
child=item->child;depth++;
while (child)
{
if (fmt)
{
ptr=ensure(p,depth); if (!ptr) return 0;
for (j=0;j<depth;j++) *ptr++='\t';
p->offset+=depth;
}
print_string_ptr(child->string,p);
p->offset=update(p);
len=fmt?2:1;
ptr=ensure(p,len); if (!ptr) return 0;
*ptr++=':';if (fmt) *ptr++='\t';
p->offset+=len;
print_value(child,depth,fmt,p);
p->offset=update(p);
len=(fmt?1:0)+(child->next?1:0);
ptr=ensure(p,len+1); if (!ptr) return 0;
if (child->next) *ptr++=',';
if (fmt) *ptr++='\n';*ptr=0;
p->offset+=len;
child=child->next;
}
ptr=ensure(p,fmt?(depth+1):2); if (!ptr) return 0;
if (fmt) for (i=0;i<depth-1;i++) *ptr++='\t';
*ptr++='}';*ptr=0;
out=(p->buffer)+i;
}
else
{
/* Allocate space for the names and the objects */
entries=(char**)cJSON_malloc(numentries*sizeof(char*));
if (!entries) return 0;
names=(char**)cJSON_malloc(numentries*sizeof(char*));
if (!names) {cJSON_free(entries);return 0;}
memset(entries,0,sizeof(char*)*numentries);
memset(names,0,sizeof(char*)*numentries);
/* Collect all the results into our arrays: */
child=item->child;depth++;if (fmt) len+=depth;
while (child)
{
names[i]=str=print_string_ptr(child->string,0);
entries[i++]=ret=print_value(child,depth,fmt,0);
if (str && ret) len+=strlen(ret)+strlen(str)+2+(fmt?2+depth:0); else fail=1;
child=child->next;
}
/* Try to allocate the output string */
if (!fail) out=(char*)cJSON_malloc(len);
if (!out) fail=1;
/* Handle failure */
if (fail)
{
for (i=0;i<numentries;i++) {if (names[i]) cJSON_free(names[i]);if (entries[i]) cJSON_free(entries[i]);}
cJSON_free(names);cJSON_free(entries);
return 0;
}
/* Compose the output: */
*out='{';ptr=out+1;if (fmt)*ptr++='\n';*ptr=0;
for (i=0;i<numentries;i++)
{
if (fmt) for (j=0;j<depth;j++) *ptr++='\t';
tmplen=strlen(names[i]);memcpy(ptr,names[i],tmplen);ptr+=tmplen;
*ptr++=':';if (fmt) *ptr++='\t';
strcpy(ptr,entries[i]);ptr+=strlen(entries[i]);
if (i!=numentries-1) *ptr++=',';
if (fmt) *ptr++='\n';*ptr=0;
cJSON_free(names[i]);cJSON_free(entries[i]);
}
cJSON_free(names);cJSON_free(entries);
if (fmt) for (i=0;i<depth-1;i++) *ptr++='\t';
*ptr++='}';*ptr++=0;
}
return out;
}
/* Get Array size/item / object item. */
int cJSON_GetArraySize(cJSON *array) {cJSON *c=array->child;int i=0;while(c)i++,c=c->next;return i;}
cJSON *cJSON_GetArrayItem(cJSON *array,int item) {cJSON *c=array->child; while (c && item>0) item--,c=c->next; return c;}
cJSON *cJSON_GetObjectItem(cJSON *object,const char *string) {cJSON *c=object->child; while (c && cJSON_strcasecmp(c->string,string)) c=c->next; return c;}
/* Utility for array list handling. */
static void suffix_object(cJSON *prev,cJSON *item) {prev->next=item;item->prev=prev;}
/* Utility for handling references. */
static cJSON *create_reference(cJSON *item) {cJSON *ref=cJSON_New_Item();if (!ref) return 0;memcpy(ref,item,sizeof(cJSON));ref->string=0;ref->type|=cJSON_IsReference;ref->next=ref->prev=0;return ref;}
/* Add item to array/object. */
void cJSON_AddItemToArray(cJSON *array, cJSON *item) {cJSON *c=array->child;if (!item) return; if (!c) {array->child=item;} else {while (c && c->next) c=c->next; suffix_object(c,item);}}
void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (item->string) cJSON_free(item->string);item->string=cJSON_strdup(string);cJSON_AddItemToArray(object,item);}
void cJSON_AddItemToObjectCS(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (!(item->type&cJSON_StringIsConst) && item->string) cJSON_free(item->string);item->string=(char*)string;item->type|=cJSON_StringIsConst;cJSON_AddItemToArray(object,item);}
void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) {cJSON_AddItemToArray(array,create_reference(item));}
void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item) {cJSON_AddItemToObject(object,string,create_reference(item));}
cJSON *cJSON_DetachItemFromArray(cJSON *array,int which) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return 0;
if (c->prev) c->prev->next=c->next;if (c->next) c->next->prev=c->prev;if (c==array->child) array->child=c->next;c->prev=c->next=0;return c;}
void cJSON_DeleteItemFromArray(cJSON *array,int which) {cJSON_Delete(cJSON_DetachItemFromArray(array,which));}
cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string) {int i=0;cJSON *c=object->child;while (c && cJSON_strcasecmp(c->string,string)) i++,c=c->next;if (c) return cJSON_DetachItemFromArray(object,i);return 0;}
void cJSON_DeleteItemFromObject(cJSON *object,const char *string) {cJSON_Delete(cJSON_DetachItemFromObject(object,string));}
/* Replace array/object items with new ones. */
void cJSON_InsertItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) {cJSON_AddItemToArray(array,newitem);return;}
newitem->next=c;newitem->prev=c->prev;c->prev=newitem;if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;}
void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return;
newitem->next=c->next;newitem->prev=c->prev;if (newitem->next) newitem->next->prev=newitem;
if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;c->next=c->prev=0;cJSON_Delete(c);}
void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem){int i=0;cJSON *c=object->child;while(c && cJSON_strcasecmp(c->string,string))i++,c=c->next;if(c){newitem->string=cJSON_strdup(string);cJSON_ReplaceItemInArray(object,i,newitem);}}
/* Create basic types: */
cJSON *cJSON_CreateNull(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_NULL;return item;}
cJSON *cJSON_CreateTrue(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_True;return item;}
cJSON *cJSON_CreateFalse(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_False;return item;}
cJSON *cJSON_CreateBool(int b) {cJSON *item=cJSON_New_Item();if(item)item->type=b?cJSON_True:cJSON_False;return item;}
cJSON *cJSON_CreateNumber(double num) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_Number;item->valuedouble=num;item->valueint=(int)num;}return item;}
cJSON *cJSON_CreateString(const char *string) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_String;item->valuestring=cJSON_strdup(string);}return item;}
cJSON *cJSON_CreateArray(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Array;return item;}
cJSON *cJSON_CreateObject(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Object;return item;}
/* Create Arrays: */
cJSON *cJSON_CreateIntArray(const int *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
cJSON *cJSON_CreateFloatArray(const float *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
cJSON *cJSON_CreateDoubleArray(const double *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
cJSON *cJSON_CreateStringArray(const char **strings,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateString(strings[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
/* Duplication */
cJSON *cJSON_Duplicate(cJSON *item,int recurse)
{
cJSON *newitem,*cptr,*nptr=0,*newchild;
/* Bail on bad ptr */
if (!item) return 0;
/* Create new item */
newitem=cJSON_New_Item();
if (!newitem) return 0;
/* Copy over all vars */
newitem->type=item->type&(~cJSON_IsReference),newitem->valueint=item->valueint,newitem->valuedouble=item->valuedouble;
if (item->valuestring) {newitem->valuestring=cJSON_strdup(item->valuestring); if (!newitem->valuestring) {cJSON_Delete(newitem);return 0;}}
if (item->string) {newitem->string=cJSON_strdup(item->string); if (!newitem->string) {cJSON_Delete(newitem);return 0;}}
/* If non-recursive, then we're done! */
if (!recurse) return newitem;
/* Walk the ->next chain for the child. */
cptr=item->child;
while (cptr)
{
newchild=cJSON_Duplicate(cptr,1); /* Duplicate (with recurse) each item in the ->next chain */
if (!newchild) {cJSON_Delete(newitem);return 0;}
if (nptr) {nptr->next=newchild,newchild->prev=nptr;nptr=newchild;} /* If newitem->child already set, then crosswire ->prev and ->next and move on */
else {newitem->child=newchild;nptr=newchild;} /* Set newitem->child and move to it */
cptr=cptr->next;
}
return newitem;
}
void cJSON_Minify(char *json)
{
char *into=json;
while (*json)
{
if (*json==' ') json++;
else if (*json=='\t') json++; /* Whitespace characters. */
else if (*json=='\r') json++;
else if (*json=='\n') json++;
else if (*json=='/' && json[1]=='/') while (*json && *json!='\n') json++; /* double-slash comments, to end of line. */
else if (*json=='/' && json[1]=='*') {while (*json && !(*json=='*' && json[1]=='/')) json++;json+=2;} /* multiline comments. */
else if (*json=='\"'){*into++=*json++;while (*json && *json!='\"'){if (*json=='\\') *into++=*json++;*into++=*json++;}*into++=*json++;} /* string literals, which are \" sensitive. */
else *into++=*json++; /* All other characters. */
}
*into=0; /* and null-terminate. */
}
| [
"developers@ubersnip.com"
] | developers@ubersnip.com |
12aef1e5035abb15cc25ab3b9857f89cd988606b | d1caf0c064786a878a292fe12bf457a1fb50df25 | /CommObjectRecognitionObjects/smartsoft/src/CommObjectRecognitionObjects/SimpleObjectEventState.hh | 7a9c36af177925ac6b795e2e185753149ae4ab33 | [
"BSD-3-Clause"
] | permissive | Servicerobotics-Ulm/DomainModelsRepositories | 8dc395bf62fe386564ba56d8b52f7e5ee90f8d5e | f4d83111d435510a79f69acb78f14a23d2af5539 | refs/heads/master | 2022-05-19T00:55:15.782791 | 2022-05-04T16:14:21 | 2022-05-04T16:14:21 | 122,947,911 | 0 | 8 | BSD-3-Clause | 2021-02-10T11:54:39 | 2018-02-26T09:44:24 | C++ | UTF-8 | C++ | false | false | 2,108 | hh | //--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain
// The SmartSoft Toolchain has been developed by:
//
// Service Robotics Research Center
// University of Applied Sciences Ulm
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// This file is generated once. Modify this file to your needs.
// If you want the toolchain to re-generate this file, please
// delete it before running the code generator.
//--------------------------------------------------------------------------
#ifndef COMMOBJECTRECOGNITIONOBJECTS_SIMPLEOBJECTEVENTSTATE_H_
#define COMMOBJECTRECOGNITIONOBJECTS_SIMPLEOBJECTEVENTSTATE_H_
#include "CommObjectRecognitionObjects/SimpleObjectEventStateCore.hh"
namespace CommObjectRecognitionObjects {
class SimpleObjectEventState : public SimpleObjectEventStateCore {
public:
// default constructors
SimpleObjectEventState();
/**
* Constructor to set all values.
* NOTE that you have to keep this constructor consistent with the model!
* Use at your own choice.
*
* The preferred way to set values for initialization is:
* CommRepository::MyCommObject obj;
* obj.setX(1).setY(2).setZ(3)...;
*/
// SimpleObjectEventState(const CommObjectRecognitionObjects::SimpleObjectState &newState, const int &x, const int &y);
SimpleObjectEventState(const SimpleObjectEventStateCore &simpleObjectEventState);
SimpleObjectEventState(const DATATYPE &simpleObjectEventState);
virtual ~SimpleObjectEventState();
// use framework specific getter and setter methods from core (base) class
using SimpleObjectEventStateCore::get;
using SimpleObjectEventStateCore::set;
//
// feel free to add customized methods here
//
};
inline std::ostream &operator<<(std::ostream &os, const SimpleObjectEventState &co)
{
co.to_ostream(os);
return os;
}
} /* namespace CommObjectRecognitionObjects */
#endif /* COMMOBJECTRECOGNITIONOBJECTS_SIMPLEOBJECTEVENTSTATE_H_ */
| [
"lotz@hs-ulm.de"
] | lotz@hs-ulm.de |
494c93e33b6d9f74852ea8e42d9a0c7ec04692bc | fad392b7b1533103a0ddcc18e059fcd2e85c0fda | /build/px4_msgs/rosidl_typesupport_introspection_cpp/px4_msgs/msg/gimbal_manager_status__type_support.cpp | cde0cfe91b61459d3622186ff3046716fae98e29 | [] | no_license | adamdai/px4_ros_com_ros2 | bee6ef27559a3a157d10c250a45818a5c75f2eff | bcd7a1bd13c318d69994a64215f256b9ec7ae2bb | refs/heads/master | 2023-07-24T18:09:24.817561 | 2021-08-23T21:47:18 | 2021-08-23T21:47:18 | 399,255,215 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,119 | cpp | // generated from rosidl_typesupport_introspection_cpp/resource/idl__type_support.cpp.em
// with input from px4_msgs:msg/GimbalManagerStatus.idl
// generated code does not contain a copyright notice
#include "array"
#include "cstddef"
#include "string"
#include "vector"
#include "rosidl_generator_c/message_type_support_struct.h"
#include "rosidl_typesupport_cpp/message_type_support.hpp"
#include "rosidl_typesupport_interface/macros.h"
#include "px4_msgs/msg/gimbal_manager_status__struct.hpp"
#include "rosidl_typesupport_introspection_cpp/field_types.hpp"
#include "rosidl_typesupport_introspection_cpp/identifier.hpp"
#include "rosidl_typesupport_introspection_cpp/message_introspection.hpp"
#include "rosidl_typesupport_introspection_cpp/message_type_support_decl.hpp"
#include "rosidl_typesupport_introspection_cpp/visibility_control.h"
namespace px4_msgs
{
namespace msg
{
namespace rosidl_typesupport_introspection_cpp
{
void GimbalManagerStatus_init_function(
void * message_memory, rosidl_generator_cpp::MessageInitialization _init)
{
new (message_memory) px4_msgs::msg::GimbalManagerStatus(_init);
}
void GimbalManagerStatus_fini_function(void * message_memory)
{
auto typed_message = static_cast<px4_msgs::msg::GimbalManagerStatus *>(message_memory);
typed_message->~GimbalManagerStatus();
}
static const ::rosidl_typesupport_introspection_cpp::MessageMember GimbalManagerStatus_message_member_array[7] = {
{
"timestamp", // name
::rosidl_typesupport_introspection_cpp::ROS_TYPE_UINT64, // type
0, // upper bound of string
nullptr, // members of sub message
false, // is array
0, // array size
false, // is upper bound
offsetof(px4_msgs::msg::GimbalManagerStatus, timestamp), // bytes offset in struct
nullptr, // default value
nullptr, // size() function pointer
nullptr, // get_const(index) function pointer
nullptr, // get(index) function pointer
nullptr // resize(index) function pointer
},
{
"flags", // name
::rosidl_typesupport_introspection_cpp::ROS_TYPE_UINT32, // type
0, // upper bound of string
nullptr, // members of sub message
false, // is array
0, // array size
false, // is upper bound
offsetof(px4_msgs::msg::GimbalManagerStatus, flags), // bytes offset in struct
nullptr, // default value
nullptr, // size() function pointer
nullptr, // get_const(index) function pointer
nullptr, // get(index) function pointer
nullptr // resize(index) function pointer
},
{
"gimbal_device_id", // name
::rosidl_typesupport_introspection_cpp::ROS_TYPE_UINT8, // type
0, // upper bound of string
nullptr, // members of sub message
false, // is array
0, // array size
false, // is upper bound
offsetof(px4_msgs::msg::GimbalManagerStatus, gimbal_device_id), // bytes offset in struct
nullptr, // default value
nullptr, // size() function pointer
nullptr, // get_const(index) function pointer
nullptr, // get(index) function pointer
nullptr // resize(index) function pointer
},
{
"primary_control_sysid", // name
::rosidl_typesupport_introspection_cpp::ROS_TYPE_UINT8, // type
0, // upper bound of string
nullptr, // members of sub message
false, // is array
0, // array size
false, // is upper bound
offsetof(px4_msgs::msg::GimbalManagerStatus, primary_control_sysid), // bytes offset in struct
nullptr, // default value
nullptr, // size() function pointer
nullptr, // get_const(index) function pointer
nullptr, // get(index) function pointer
nullptr // resize(index) function pointer
},
{
"primary_control_compid", // name
::rosidl_typesupport_introspection_cpp::ROS_TYPE_UINT8, // type
0, // upper bound of string
nullptr, // members of sub message
false, // is array
0, // array size
false, // is upper bound
offsetof(px4_msgs::msg::GimbalManagerStatus, primary_control_compid), // bytes offset in struct
nullptr, // default value
nullptr, // size() function pointer
nullptr, // get_const(index) function pointer
nullptr, // get(index) function pointer
nullptr // resize(index) function pointer
},
{
"secondary_control_sysid", // name
::rosidl_typesupport_introspection_cpp::ROS_TYPE_UINT8, // type
0, // upper bound of string
nullptr, // members of sub message
false, // is array
0, // array size
false, // is upper bound
offsetof(px4_msgs::msg::GimbalManagerStatus, secondary_control_sysid), // bytes offset in struct
nullptr, // default value
nullptr, // size() function pointer
nullptr, // get_const(index) function pointer
nullptr, // get(index) function pointer
nullptr // resize(index) function pointer
},
{
"secondary_control_compid", // name
::rosidl_typesupport_introspection_cpp::ROS_TYPE_UINT8, // type
0, // upper bound of string
nullptr, // members of sub message
false, // is array
0, // array size
false, // is upper bound
offsetof(px4_msgs::msg::GimbalManagerStatus, secondary_control_compid), // bytes offset in struct
nullptr, // default value
nullptr, // size() function pointer
nullptr, // get_const(index) function pointer
nullptr, // get(index) function pointer
nullptr // resize(index) function pointer
}
};
static const ::rosidl_typesupport_introspection_cpp::MessageMembers GimbalManagerStatus_message_members = {
"px4_msgs::msg", // message namespace
"GimbalManagerStatus", // message name
7, // number of fields
sizeof(px4_msgs::msg::GimbalManagerStatus),
GimbalManagerStatus_message_member_array, // message members
GimbalManagerStatus_init_function, // function to initialize message memory (memory has to be allocated)
GimbalManagerStatus_fini_function // function to terminate message instance (will not free memory)
};
static const rosidl_message_type_support_t GimbalManagerStatus_message_type_support_handle = {
::rosidl_typesupport_introspection_cpp::typesupport_identifier,
&GimbalManagerStatus_message_members,
get_message_typesupport_handle_function,
};
} // namespace rosidl_typesupport_introspection_cpp
} // namespace msg
} // namespace px4_msgs
namespace rosidl_typesupport_introspection_cpp
{
template<>
ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC
const rosidl_message_type_support_t *
get_message_type_support_handle<px4_msgs::msg::GimbalManagerStatus>()
{
return &::px4_msgs::msg::rosidl_typesupport_introspection_cpp::GimbalManagerStatus_message_type_support_handle;
}
} // namespace rosidl_typesupport_introspection_cpp
#ifdef __cplusplus
extern "C"
{
#endif
ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC
const rosidl_message_type_support_t *
ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_introspection_cpp, px4_msgs, msg, GimbalManagerStatus)() {
return &::px4_msgs::msg::rosidl_typesupport_introspection_cpp::GimbalManagerStatus_message_type_support_handle;
}
#ifdef __cplusplus
}
#endif
| [
"adamdai97@gmail.com"
] | adamdai97@gmail.com |
0ea753f0630bdc1c0b5c990cd614f7ef248dfcd6 | fe50fca386dc79ff7ad75185903209f07bcdab30 | /Assignments/dupChar.cpp | 5458e188b2e711d261ff9e56d8a031a0d90e08f8 | [] | no_license | sainiak009/cpp_practice_codes | a5163e146b2851d8d7342fb440b508ea315410ce | 5c4fb23678f1f664abccfc490e6484368023d60d | refs/heads/master | 2020-03-20T18:20:39.397907 | 2018-06-16T13:49:49 | 2018-06-16T13:49:49 | 137,583,722 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 483 | cpp | // Ankit Saini - sainiak009@gmail.com
#include <iostream>
#include <cstring>
using namespace std;
void dupChar(char str[], int be, int en){
if(str[be+1] == '\0') return;
if(str[be] == str[be+1]){
for(int i=en; i>=be+1; --i){
str[i+1] = str[i];
}
str[be+1] = '*';
++en;
str[en+1] = '\0';
}else{
dupChar(str, ++be, en);
}
}
int main(){
char str[10000];
cin.getline(str,10000);
int high = strlen(str)-1;
dupChar(str, 0, high);
cout << str;
return 0;
}
| [
"sainiak009@gmail.com"
] | sainiak009@gmail.com |
947a32dd4cf9367b927f72920e9fba1c568d6beb | e6b5d019e565ce55b2febfbe21b82c2a21723385 | /TheWaySoFar-Training/2015-03-31/K.cpp | 9c75c016572fa511a1908ac6061182257668f65b | [] | no_license | Sd-Invol/shoka | a628f7e8544d8eb110014316ab16ef3aed7b7433 | 1281cb43501d9ef127a2c67aebfba1905229502b | refs/heads/master | 2023-06-06T07:23:09.496837 | 2023-05-13T14:46:23 | 2023-05-13T14:46:23 | 13,319,608 | 37 | 17 | null | null | null | null | UTF-8 | C++ | false | false | 1,612 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 200005;
int n , fa , fb;
struct pro {
int id;
int a , b;
LL t;
bool operator < (const pro& R) const {
return make_pair(t , b) < make_pair(R.t , R.b);
}
}p[N];
LL late[N];
int res[N << 1];
bool check(LL T) {
int i , j , x , y;
for (i = 0 ; i < n ; ++ i)
late[i] = p[i].t + T - p[i].b;
for (i = n - 2 ; i >= 0 ; -- i) {
late[i] = min(late[i] , late[i + 1] - p[i].b);
}
T = 0;
int cnt = 0;
i = 0 , j = 0;
while (j < n) {
x = res[cnt] < 0 ? 0 : fa;
y = res[cnt] > 0 ? 0 : fb;
if (i < n && T + x + p[i].a + fb <= late[j]) {
T += x + p[i].a;
res[++ cnt] = -p[i].id;
i ++;
} else {
if (i <= j)
return 0;
T += y + p[j].b;
res[++ cnt] = p[j].id;
j ++;
while (j < i) {
T += p[j].b;
res[++ cnt] = p[j].id;
++ j;
}
}
}
return 1;
}
int main() {
int i , j , x , y;
scanf("%d%d%d",&n,&fa,&fb);
for (i = 0 ; i < n ; ++ i) {
scanf("%d%d%lld" , &p[i].a , &p[i].b , &p[i].t);
p[i].id = i + 1;
}
sort(p , p + n);
LL l = 0 , r = 1e15 , m;
while (l < r) {
m = l + r >> 1;
if (check(m))
r = m;
else
l = m + 1;
}
check(r);
cout << r << endl;
for (i = 1 ; i <= n + n ; ++ i)
printf("%d%c" , res[i] , " \n"[i == n + n]);
}
| [
"Sd.Invol@gmail.com"
] | Sd.Invol@gmail.com |
ca6c26df5a0821b2d8481d82e1e64d080e67cc20 | e4910797da1edcefa87d9f088c92b6637dfae5a7 | /CPP/etc/Platinum IV/3747.cpp | a2a1901821025bc82e457143a62484b6d73aebaf | [] | no_license | VSFe/Algorithm | b9fb4241636d74291b7a6b3e2e86270f6a5039b8 | 6270f7147f4c29c5d83628b54fc043f99ec0cb31 | refs/heads/master | 2023-07-28T01:33:57.114279 | 2021-09-13T05:55:22 | 2021-09-13T05:55:22 | 224,992,253 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,050 | cpp | /*
Problem: 완벽한 선거! (3747)
Tier: Platinum 4
Detail: N어떤 나라에서는 (뭔 나라인지는 기억이 안 나지만), 후보 {1, 2 ... N}이 나와서 국회의원 선거를 치루고 있다.
여론조사에서는 사람들마다 "만약 두 후보 i, j에 대해서, 그 두 후보의 선거 결과가 어떻게 나오면 행복할 것 같으세요?" 라고 물어봤다.
이 질문에 대한 가능한 답변은 밑의 표에 나와있고, i와 j가 동일할 수도 있다.
우리는 M개의 가능한 답변의 리스트를 가지고 있고, 이 M개의 답변 중 비슷하거나 동일한 것이 있을 수도 있다.
만약에 이 M개의 답변을 동시에 만족하는 선거 결과가 있다면, 이 선거 결과를 완벽하다고 한다. (다만, 후보 {1, 2 ... N}이 모두 당선되거나 모두 낙선될 수도 있고, 이 중 일부만 당선될 수도 있다!)
우리가 할 일은 M개의 답변에 대해서 완벽한 선거 결과가 있으면 1을, 아니면 0을 출력하는 것이다.
나는 i와 j 둘 중 한 명은 당선되었으면 좋겠어. +i +j
난 i랑 j 둘 중 한 명은 떨어졌으면 좋겠어. -i -j
난 i가 붙거나 j가 떨어지거나, 둘 다 만족했음 좋겠어. +i -j
난 j가 붙거나 i가 떨어지거나, 둘 다 만족했음 좋겠어. -i +j
Comment: 정말 정말 평범한 2-SAT 문제인데??
*/
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
#include <cstring>
using namespace std;
vector<int> graph[2001];
int dfs_num[2001], dfs_low[2001], finished[2001];
int cnt = 1, SC = 1, V, E;
bool is_error = false;
stack<int> st;
const int stand = 1000;
void dfs(int idx, int prev) {
dfs_num[idx] = dfs_low[idx] = cnt++;
st.push(idx);
for(auto next : graph[idx]) {
if(!dfs_num[next]) dfs(next, idx);
if(!finished[next]) dfs_low[idx] = min(dfs_low[idx], dfs_low[next]);
}
if(dfs_num[idx] == dfs_low[idx]) {
while(1) {
int t = st.top();
finished[t] = SC;
st.pop();
if(t == idx) break;
} SC++;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
while(cin >> V >> E) {
is_error = false; cnt = 1, SC = 1;
memset(finished, 0, sizeof(finished));
memset(dfs_num, 0, sizeof(dfs_num));
memset(dfs_low, 0, sizeof(dfs_low));
for(int i = 0; i < 2001; i++) graph[i].clear();
for(int i = 0; i < E; i++) {
int x, y; cin >> x >> y;
graph[stand - x].push_back(stand + y);
graph[stand - y].push_back(stand + x);
}
for(int i = 1; i <= V; i++) {
if(!dfs_num[stand + i]) dfs(stand + i, 0);
if(!dfs_num[stand - i]) dfs(stand - i, 0);
}
for(int i = 1; i <= V; i++) {
if(finished[stand + i] == finished[stand - i]) {
is_error = true;
i = V + 1;
}
}
if(is_error) cout << "0" << '\n';
else cout << "1" << '\n';
}
} | [
"klm03025@gmail.com"
] | klm03025@gmail.com |
8b9fb41ec1f086d375e3f4e12a0f6d21bea4f782 | bac2a002957c370fee48e470a54cea8812934174 | /src/dsp/oscillator.cpp | 10aba973c2c688d1219bd22e09ac7e76fb231734 | [
"CC0-1.0"
] | permissive | djoulz22/DjZ_osc1 | 170927dda974ddc5820429b5df2e1c47497130b9 | ed6e536696c0acdde6972840fbb8d5693a6870ad | refs/heads/main | 2023-01-15T20:30:05.835804 | 2020-11-25T21:19:58 | 2020-11-25T21:19:58 | 315,311,845 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,781 | cpp |
#include "oscillator.hpp"
using namespace djoulz::dsp;
void Phasor::setSampleWidth(float sw) {
if (sw < 0.0f) {
sw = 0.0f;
}
else if (sw > maxSampleWidth) {
sw = maxSampleWidth;
}
if (_sampleWidth != sw) {
_sampleWidth = sw;
if (_sampleWidth > 0.001f) {
_samplePhase = _sampleWidth * (float)maxPhase;
}
else {
_samplePhase = 0;
}
}
}
void Phasor::resetPhase() {
_phase = 0;
}
void Phasor::setPhase(float radians) {
_phase = radiansToPhase(radians);
}
void Phasor::syncPhase(const Phasor& phasor) {
_phase = phasor._phase;
}
float Phasor::nextFromPhasor(const Phasor& phasor, phase_delta_t offset) {
offset += phasor._phase;
if (_samplePhase > 0) {
offset -= offset % _samplePhase;
}
return _nextForPhase(offset);
}
void Phasor::_update() {
_delta = ((phase_delta_t)((_frequency / _sampleRate) * maxPhase)) % maxPhase;
}
float Phasor::_next() {
advancePhase();
if (_samplePhase > 0) {
return _nextForPhase(_phase - (_phase % _samplePhase));
}
return _nextForPhase(_phase);
}
float Phasor::_nextForPhase(phase_t phase) {
return phase;
}
float TablePhasor::_nextForPhase(phase_t phase) {
if (_tableLength >= 1024) {
int i = (((((uint64_t)phase) << 16) / maxPhase) * _tableLength) >> 16;
if (i >= _tableLength) {
i %= _tableLength;
}
return _table.value(i);
}
float fi = (phase / (float)maxPhase) * _tableLength;
int i = (int)fi;
if (i >= _tableLength) {
i %= _tableLength;
}
float v1 = _table.value(i);
float v2 = _table.value(i + 1 == _tableLength ? 0 : i + 1);
return v1 + (fi - i)*(v2 - v1);
}
// A New Recursive Quadrature Oscillator, Martin Vicanek, 2015 - http://vicanek.de/articles/QuadOsc.pdf
void SineOscillator::setPhase(double phase) {
_x = cos(phase);
_y = sin(phase);
}
void SineOscillator::update() {
double w = (_frequency / _sampleRate) * 2.0 * M_PI;
_k1 = tan(w / 2.0);
_k2 = 2.0 * _k1 / (1 + _k1*_k1);
}
float SineOscillator::_next() {
double t = _x - _k1*_y;
_y = _y + _k2*t;
_x = t - _k1*_y;
return _y;
}
float SawOscillator::_nextForPhase(phase_t phase) {
return (phase / (float)maxPhase) * 2.0f - 1.0f;
}
void SaturatingSawOscillator::setSaturation(float saturation) {
if (_saturation != saturation) {
assert(saturation >= 0.0f);
_saturation = saturation;
if (_saturation >= 0.1f) {
if (_saturation < 1.0f) {
_saturationNormalization = 1.0f / tanhf(_saturation * M_PI);
}
else {
_saturationNormalization = 1.0f;
}
}
}
}
float SaturatingSawOscillator::_nextForPhase(phase_t phase) {
float sample = SawOscillator::_nextForPhase(phase);
if (_saturation >= 0.1f) {
sample = _tanhf.value(sample * _saturation * M_PI) * _saturationNormalization;
}
return sample;
}
void BandLimitedSawOscillator::setQuality(int quality) {
if (_quality != quality) {
assert(quality >= 0);
_quality = quality;
_update();
}
}
void BandLimitedSawOscillator::_update() {
Phasor::_update();
int q = std::min(_quality, (int)(0.5f * (_sampleRate / _frequency)));
_qd = q * _delta;
}
float BandLimitedSawOscillator::_nextForPhase(phase_t phase) {
float sample = SaturatingSawOscillator::_nextForPhase(phase);
if (phase > maxPhase - _qd) {
float i = (maxPhase - phase) / (float)_qd;
i = (1.0f - i) * _halfTableLen;
sample -= _table.value((int)i);
}
else if (phase < _qd) {
float i = phase / (float)_qd;
i *= _halfTableLen - 1;
i += _halfTableLen;
sample -= _table.value((int)i);
}
return sample;
}
void SquareOscillator::setPulseWidth(float pw) {
if (_pulseWidthInput == pw) {
return;
}
_pulseWidthInput = pw;
if (pw >= maxPulseWidth) {
pw = maxPulseWidth;
}
else if (pw <= minPulseWidth) {
pw = minPulseWidth;
}
_pulseWidth = maxPhase * pw;
}
float SquareOscillator::_nextForPhase(phase_t phase) {
if (positive) {
if (phase >= _pulseWidth) {
positive = false;
return -1.0f;
}
return 1.0f;
}
if (phase < _pulseWidth) {
positive = true;
return 1.0f;
}
return -1.0f;
}
void BandLimitedSquareOscillator::setPulseWidth(float pw) {
if (_pulseWidthInput == pw) {
return;
}
_pulseWidthInput = pw;
if (pw >= maxPulseWidth) {
pw = maxPulseWidth;
}
else if (pw <= minPulseWidth) {
pw = minPulseWidth;
}
_pulseWidth = maxPhase * pw;
if (pw > 0.5) {
_offset = 2.0f * pw - 1.0f;
}
else {
_offset = -(1.0f - 2.0f * pw);
}
}
float BandLimitedSquareOscillator::_nextForPhase(phase_t phase) {
float sample = -BandLimitedSawOscillator::_nextForPhase(phase);
sample += BandLimitedSawOscillator::_nextForPhase(phase - _pulseWidth);
return sample + _offset;
}
float TriangleOscillator::_nextForPhase(phase_t phase) {
float p = (phase / (float)maxPhase) * 4.0f;
if (phase < quarterMaxPhase) {
return p;
}
if (phase < threeQuartersMaxPhase) {
return 2.0f - p;
}
return p - 4.0f;
}
void SineBankOscillator::setPartial(int i, float frequencyRatio, float amplitude) {
setPartialFrequencyRatio(i, frequencyRatio);
setPartialAmplitude(i, amplitude);
}
bool SineBankOscillator::setPartialFrequencyRatio(int i, float frequencyRatio) {
if (i <= (int)_partials.size()) {
Partial& p = _partials[i - 1];
p.frequencyRatio = frequencyRatio;
double f = (double)_frequency * (double)frequencyRatio;
p.frequency = f;
p.sine.setFrequency(f);
return f < _maxPartialFrequency;
}
return false;
}
void SineBankOscillator::setPartialAmplitude(int i, float amplitude, bool envelope) {
if (i <= (int)_partials.size()) {
Partial& p = _partials[i - 1];
if (envelope) {
p.amplitudeTarget = amplitude;
p.amplitudeStepDelta = (amplitude - p.amplitude) / (float)_amplitudeEnvelopeSamples;
p.amplitudeSteps = _amplitudeEnvelopeSamples;
}
else if (p.amplitudeSteps > 0) {
p.amplitudeTarget = amplitude;
p.amplitudeStepDelta = (amplitude - p.amplitude) / (float)p.amplitudeSteps;
}
else {
p.amplitude = amplitude;
}
}
}
void SineBankOscillator::syncToPhase(float phase) {
for (Partial& p : _partials) {
p.sine.setPhase(phase);
}
}
void SineBankOscillator::syncTo(const SineBankOscillator& other) {
for (int i = 0, n = std::min(_partials.size(), other._partials.size()); i < n; ++i) {
_partials[i].sine.syncPhase(other._partials[i].sine);
}
}
void SineBankOscillator::_sampleRateChanged() {
_maxPartialFrequency = _maxPartialFrequencySRRatio * _sampleRate;
_amplitudeEnvelopeSamples = _sampleRate * (_amplitudeEnvelopeMS / 1000.0f);
for (Partial& p : _partials) {
p.sine.setSampleRate(_sampleRate);
}
}
void SineBankOscillator::_frequencyChanged() {
for (Partial& p : _partials) {
p.frequency = _frequency * p.frequencyRatio;
p.sine.setFrequency(_frequency * p.frequencyRatio);
}
}
float SineBankOscillator::next(Phasor::phase_t phaseOffset) {
float next = 0.0;
for (Partial& p : _partials) {
p.sine.advancePhase();
if (p.frequency < _maxPartialFrequency && (p.amplitude > 0.001 || p.amplitude < -0.001 || p.amplitudeSteps > 0)) {
if (p.amplitudeSteps > 0) {
if (p.amplitudeSteps == 1) {
p.amplitude = p.amplitudeTarget;
}
else {
p.amplitude += p.amplitudeStepDelta;
}
--p.amplitudeSteps;
}
next += p.sine.nextFromPhasor(p.sine, phaseOffset) * p.amplitude;
}
}
return next;
}
constexpr float ChirpOscillator::minFrequency;
constexpr float ChirpOscillator::minTimeSeconds;
void ChirpOscillator::setParams(float frequency1, float frequency2, float time, bool linear) {
frequency1 = std::max(minFrequency, std::min(frequency1, 0.99f * 0.5f * _sampleRate));
frequency2 = std::max(minFrequency, std::min(frequency2, 0.99f * 0.5f * _sampleRate));
assert(time >= minTimeSeconds);
if (_f1 != frequency1 || _f2 != frequency2 || _Time != time || _linear != linear) {
_f1 = frequency1;
_f2 = frequency2;
_Time = time;
_linear = linear;
_k = pow((double)(_f2 / _f1), 1.0f / (double)_Time);
}
}
void ChirpOscillator::_sampleRateChanged() {
_oscillator.setSampleRate(_sampleRate);
_sampleTime = 1.0f / _sampleRate;
}
float ChirpOscillator::_next() {
_complete = false;
if (_time > _Time) {
_time = 0.0f;
_complete = true;
}
else {
_time += _sampleTime;
}
if (_linear) {
_oscillator.setFrequency(_f1 + (_time / _Time) * (_f2 - _f1));
}
else {
_oscillator.setFrequency((double)_f1 * pow(_k, (double)_time));
}
return _oscillator.next();
}
void ChirpOscillator::reset() {
_time = 0.0f;
_oscillator.resetPhase();
}
constexpr float PureChirpOscillator::minFrequency;
constexpr float PureChirpOscillator::minTimeSeconds;
void PureChirpOscillator::setParams(float frequency1, float frequency2, double time, bool linear) {
frequency1 = std::max(minFrequency, std::min(frequency1, 0.99f * 0.5f * _sampleRate));
frequency2 = std::max(minFrequency, std::min(frequency2, 0.99f * 0.5f * _sampleRate));
assert(time >= minTimeSeconds);
if (_f1 != frequency1 || _f2 != frequency2 || _Time != time || _linear != linear) {
_f1 = frequency1;
_f2 = frequency2;
_Time = time;
_linear = linear;
update();
}
}
void PureChirpOscillator::_sampleRateChanged() {
_sampleTime = 1.0 / (double)_sampleRate;
update();
}
void PureChirpOscillator::update() {
_Time = std::max(2.0f * _sampleTime, _Time);
_c = (double)(_f2 - _f1) / (double)_Time;
_k = pow((double)(_f2 / _f1), 1.0f / (double)_Time);
_invlogk = 1.0 / log(_k);
}
float PureChirpOscillator::_next() {
// formulas from https://en.wikipedia.org/wiki/Chirp
double phase = 0.0f;
if (_linear) {
phase = 2.0 * M_PI * (0.5 * _c * (double)(_time * _time) + (double)(_f1 * _time));
}
else {
phase = 2.0 * M_PI * (double)_f1 * ((pow(_k, (double)_time) - 1.0) * _invlogk);
}
_complete = false;
if (_Time - _time < _sampleTime) {
_time = 0.0f;
_complete = true;
}
else {
_time += _sampleTime;
}
return sin(phase);
}
void PureChirpOscillator::reset() {
_time = 0.0f;
}
| [
"juc@silico.fr"
] | juc@silico.fr |
d981e9452607ceaae73ae13c80fc1b3d762940c5 | 1c20bf25898a591b2369190e184c7a6bf3855306 | /world/world.cpp | f22d44f0c7d8b9c570fc7860025ca520de5a1ea9 | [] | no_license | JRevel/src | 3ec740907132b9ba8eddb0fc9053b29cba889c0a | aa56dfb18aa0912dc73b1230505643aae43e8e4c | refs/heads/master | 2021-01-25T04:58:00.312166 | 2014-01-15T08:21:50 | 2014-01-15T08:21:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,501 | cpp | #include <SFML/Graphics.hpp>
#include "world.h"
#include "../graphic/counter.h"
#include "../entity/movement_manager.h"
World::World(Vec dim) : m_dim(dim)
{
m_colHandler = new CollisionHandler(*this, 10, 10);
}
World::~World()
{
delete m_colHandler;
}
void World::update()
{
m_movements.update();
m_colHandler->update();
}
void World::draw(sf::RenderTarget &render) const
{
sf::RectangleShape rect = sf::RectangleShape(sf::Vector2f(m_dim.x, m_dim.y));
rect.setFillColor(sf::Color::Transparent);
rect.setOutlineColor(sf::Color::Red);
rect.setOutlineThickness(5);
render.draw(rect);
}
void World::addEntity(Entity *entity)
{
entity->setWorld(this);
m_colHandler->addEntity(entity);
}
std::vector<Entity*> World::getEntitiesInRect(Vec A, Vec B)
{
return m_colHandler->getEntitiesInRect(A, B);
}
Vec World::getDim() const
{
return m_dim;
}
void World::remove(Entity *toRemove)
{
m_colHandler->erase(toRemove);
}
void World::stopMovement(Ball *ball)
{
m_movements.stopMovement(ball);
}
void World::addMovement(MovementHandler *movement)
{
m_movements.addMovement(movement);
}
std::vector<Entity*> World::selectEntitiesInRect(const Player *player, Vec A, Vec B)
{
return m_colHandler->selectEntitiesInRect(player, A, B);
}
void World::updateTarget(Ball* ball, Vec target)
{
m_movements.updateTarget(ball, target);
}
std::vector<Entity*> World::getEntitiesAt(Vec A) const
{
return m_colHandler->getEntitiesAt(A);
}
| [
"doubi125@hotmail.fr"
] | doubi125@hotmail.fr |
ca0cc29aa117d406388ba469d5bc5856dd636e21 | 42d981b9ac42ad12577865115228b3744aad6e6b | /bachelors/year2/semestre2/HomeTasks/6/sss.cpp | 336b5984706e9ca7bdafbb92b2b3144075272f6e | [] | no_license | Witalia008/university_courses | bcd7683ac3abbfb8f5474c0d114ed01cbc15eab6 | 8bdfb3b5f8ce44680dde530e4eabc28141013bd0 | refs/heads/main | 2023-04-11T11:16:59.444067 | 2021-04-01T01:31:02 | 2021-04-01T01:31:02 | 350,045,497 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,742 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <cstdlib>
#include <iostream>
#include <set>
#include <algorithm>
#include <vector>
#include <string>
#include <memory.h>
#include <map>
#define _USE_MATH_DEFINES
#include <math.h>
#include <list>
#include <fstream>
#include <time.h>
#include <iomanip>
#include <queue>
#include <stack>
#include <complex>
#include <limits.h>
#include <cassert>
#include <chrono>
#include <regex>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <unordered_map>
#include <unordered_set>
#include <random>
#include <valarray>
using namespace std;
using namespace std::chrono;
typedef long long ll;
const int N = 100005;
const int K = 505;
const ll InfL = 1000000000000000000LL;
const int MOD = 1000000007;
class A
{
public:
virtual ~A() {}
string Name() {
return DoName();
}
private:
virtual string DoName() {
return "A";
}
};
template<class T = A>
class B1 : virtual public T {
string DoName() override {
return "B1";
}
};
template<class T = A>
class B2 : virtual public T {
string DoName() override {
return "B2";
}
};
class D : public B2<B1<>> {
string DoName() {
return "D";
}
};
#define ONLINE_JUDGE
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
A* a = new D;
D* d = new D;
B2<B1<A>> *b1 = new D;
B1<> *b2 = new D;
cout << d->Name() << endl;
cout << a->Name() << endl;
cout << b1->Name() << endl;
cout << b2->Name() << endl;
system("pause");
return 0;
} | [
"kojvitalij@gmail.com"
] | kojvitalij@gmail.com |
de25c43458232f4d38e2667f8997faf4f8d86268 | 2001d14621bde954b6108d180645a893b6f47f6a | /src/ircommon-test/src/IRUtilsTest.cpp | 35b5c5299964fb237ce7263870d4b3f25d57194f | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | interlockledger/interlockrecord | 408810b20ec00da73be1fc6628b723d77ab8ed1b | e8336d421b101df50c3a84d0aedb3768a8851baa | refs/heads/master | 2021-01-25T13:41:19.356054 | 2018-08-26T02:12:46 | 2018-08-26T02:12:46 | 123,603,853 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,251 | cpp | /*
* Copyright (c) 2017-2018 InterlockLedger Network
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "IRUtilsTest.h"
#include <ircommon/irutils.h>
#include <cstdint>
#include <cstring>
using namespace std;
using namespace ircommon;
//==============================================================================
// class IRUtilsTest
//------------------------------------------------------------------------------
IRUtilsTest::IRUtilsTest() {
}
//------------------------------------------------------------------------------
IRUtilsTest::~IRUtilsTest() {
}
//------------------------------------------------------------------------------
void IRUtilsTest::SetUp() {
}
//------------------------------------------------------------------------------
void IRUtilsTest::TearDown() {
}
//------------------------------------------------------------------------------
TEST_F(IRUtilsTest, getPaddingSizeUInt64) {
uint64_t blockSize;
blockSize = 16;
ASSERT_EQ(blockSize, IRUtils::getPaddingSize(uint64_t(0), blockSize));
for (uint64_t v = 1; v < blockSize; v++) {
ASSERT_EQ(blockSize - (v % blockSize), IRUtils::getPaddingSize(v, blockSize));
}
}
//------------------------------------------------------------------------------
TEST_F(IRUtilsTest, getPaddingSizeUInt32) {
uint32_t blockSize;
blockSize = 13;
ASSERT_EQ(blockSize, IRUtils::getPaddingSize(uint32_t(0), blockSize));
for (uint32_t v = 1; v < blockSize; v++) {
ASSERT_EQ(blockSize - (v % blockSize), IRUtils::getPaddingSize(v, blockSize));
}
}
//------------------------------------------------------------------------------
TEST_F(IRUtilsTest, getPaddedSizeUInt64) {
uint64_t blockSize;
blockSize = 16;
for (uint64_t v = 0; v <= blockSize * 4; v++) {
ASSERT_EQ(
blockSize * ((v / blockSize) + 1),
IRUtils::getPaddedSize(v, blockSize));
}
}
//------------------------------------------------------------------------------
TEST_F(IRUtilsTest, getPaddedSizeUInt32) {
uint32_t blockSize;
blockSize = 13;
for (uint32_t v = 0; v <= blockSize * 4; v++) {
ASSERT_EQ(
blockSize * ((v / blockSize) + 1),
IRUtils::getPaddedSize(v, blockSize));
}
}
//------------------------------------------------------------------------------
TEST_F(IRUtilsTest, getPaddedSizeBestFitUInt64) {
uint64_t blockSize;
blockSize = 16;
for (uint64_t v = 0; v <= blockSize * 4; v++) {
int add = std::min(v % blockSize, uint64_t(1));
ASSERT_EQ(
blockSize * ((v / blockSize) + add),
IRUtils::getPaddedSizeBestFit(v, blockSize));
}
}
//------------------------------------------------------------------------------
TEST_F(IRUtilsTest, getPaddedSizeBestFitUInt32) {
uint32_t blockSize;
blockSize = 13;
for (uint32_t v = 0; v <= blockSize * 4; v++) {
int add = std::min(v % blockSize, uint32_t(1));
ASSERT_EQ(
blockSize * ((v / blockSize) + add),
IRUtils::getPaddedSizeBestFit(v, blockSize));
}
}
//------------------------------------------------------------------------------
const static std::uint8_t BE_SAMPLE[8] = {
0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF};
TEST_F(IRUtilsTest, BE2Int16) {
uint16_t v;
IRUtils::BE2Int(BE_SAMPLE, v);
ASSERT_EQ(0x0123, v);
}
//------------------------------------------------------------------------------
TEST_F(IRUtilsTest, BE2IntU16) {
int16_t v;
IRUtils::BE2Int(BE_SAMPLE, v);
ASSERT_EQ(0x0123, v);
}
//------------------------------------------------------------------------------
TEST_F(IRUtilsTest, BE2Int32) {
uint32_t v;
IRUtils::BE2Int(BE_SAMPLE, v);
ASSERT_EQ(0x01234567, v);
}
//------------------------------------------------------------------------------
TEST_F(IRUtilsTest, BE2IntU32) {
int32_t v;
IRUtils::BE2Int(BE_SAMPLE, v);
ASSERT_EQ(0x01234567, v);
}
//------------------------------------------------------------------------------
TEST_F(IRUtilsTest, BE2Int64) {
uint64_t v;
IRUtils::BE2Int(BE_SAMPLE, v);
ASSERT_EQ(0x0123456789ABCDEFll, v);
}
//------------------------------------------------------------------------------
TEST_F(IRUtilsTest, BE2IntU64) {
int64_t v;
IRUtils::BE2Int(BE_SAMPLE, v);
ASSERT_EQ(0x0123456789ABCDEFll, v);
}
//------------------------------------------------------------------------------
TEST_F(IRUtilsTest, Int2BE16) {
uint8_t * buff;
int16_t v;
v = 0x0123;
buff = new uint8_t[sizeof(v)];
IRUtils::int2BE(v, buff);
ASSERT_EQ(0, memcmp(buff, BE_SAMPLE, sizeof(v)));
delete [] buff;
}
//------------------------------------------------------------------------------
TEST_F(IRUtilsTest, Int2BEU16) {
uint8_t * buff;
uint16_t v;
v = 0x0123;
buff = new uint8_t[sizeof(v)];
IRUtils::int2BE(v, buff);
ASSERT_EQ(0, memcmp(buff, BE_SAMPLE, sizeof(v)));
delete [] buff;
}
//------------------------------------------------------------------------------
TEST_F(IRUtilsTest, Int2BE32) {
uint8_t * buff;
int32_t v;
v = 0x01234567;
buff = new uint8_t[sizeof(v)];
IRUtils::int2BE(v, buff);
ASSERT_EQ(0, memcmp(buff, BE_SAMPLE, sizeof(v)));
delete [] buff;
}
//------------------------------------------------------------------------------
TEST_F(IRUtilsTest, Int2BEU32) {
uint8_t * buff;
uint32_t v;
v = 0x01234567;
buff = new uint8_t[sizeof(v)];
IRUtils::int2BE(v, buff);
ASSERT_EQ(0, memcmp(buff, BE_SAMPLE, sizeof(v)));
delete [] buff;
}
//------------------------------------------------------------------------------
TEST_F(IRUtilsTest, Int2BE64) {
uint8_t * buff;
int64_t v;
v = 0x0123456789ABCDEFll;
buff = new uint8_t[sizeof(v)];
IRUtils::int2BE(v, buff);
ASSERT_EQ(0, memcmp(buff, BE_SAMPLE, sizeof(v)));
delete [] buff;
}
//------------------------------------------------------------------------------
TEST_F(IRUtilsTest, Int2BEU64) {
uint8_t * buff;
uint64_t v;
v = 0x0123456789ABCDEFll;
buff = new uint8_t[sizeof(v)];
IRUtils::int2BE(v, buff);
ASSERT_EQ(0, memcmp(buff, BE_SAMPLE, sizeof(v)));
delete [] buff;
}
//------------------------------------------------------------------------------
TEST_F(IRUtilsTest, clearMemory) {
std::uint8_t * buff;
int size;
size = 32;
buff = new std::uint8_t[size];
for (int i = 0; i < size; i++) {
buff[i] = 0xFF;
}
IRUtils::clearMemory(buff, size);
for (int i = 0; i < size; i++) {
ASSERT_EQ(0, buff[i]);
}
delete [] buff;
buff = nullptr;
IRUtils::clearMemory(buff, size);
}
//------------------------------------------------------------------------------
TEST_F(IRUtilsTest, lockUnlockMemory) {
std::uint8_t * buff;
int size;
size = 32;
buff = new std::uint8_t[size];
ASSERT_TRUE(IRUtils::lockMemory(buff, size));
ASSERT_TRUE(IRUtils::unlockMemory(buff, size));
delete [] buff;
}
//------------------------------------------------------------------------------
| [
"fchino@opencs.com.br"
] | fchino@opencs.com.br |
f51f42f0a68dc76afa348de9d7dc2709e9702f88 | da70bfd6e1c81271d3efa02d3e397a6ea5493f4b | /dfd/include/consensus/contract_engine/ContractEngine.hpp | 456bd499ef049b72d4a72c17e4ca07722a3faa06 | [
"MIT"
] | permissive | dfdchain/dfd_project | c9e21cd63b4c4c4f4d207f38325232d1982249a4 | 77a5cf59e6882575b9948d93cefbb556d857fd32 | refs/heads/master | 2023-01-13T06:46:17.145659 | 2020-11-23T05:33:51 | 2020-11-23T05:33:51 | 288,371,401 | 2 | 1 | null | null | null | null | GB18030 | C++ | false | false | 1,781 | hpp | #pragma once
#include <stdint.h>
#include <string>
#include <memory>
#include <uvm/uvm_lib.h>
namespace dfdcore
{
namespace consensus
{
namespace contract_engine
{
typedef UvmModuleByteStream VMModuleByteStream;
// 抽象的合约虚拟机
class ContractEngine
{
private:
public:
virtual ~ContractEngine();
virtual bool has_gas_limit() const = 0;
virtual int64_t gas_limit() const = 0;
virtual int64_t gas_used() const = 0;
virtual void set_gas_limit(int64_t gas_limit) = 0;
virtual void set_no_gas_limit() = 0;
virtual void set_gas_used(int64_t gas_used) = 0;
virtual void add_gas_used(int64_t delta_used) = 0;
virtual void stop() = 0;
// @throws exception
virtual void compilefile_to_stream(std::string filename, void *stream) = 0;
virtual void add_global_bool_variable(std::string name, bool value) = 0;
virtual void add_global_int_variable(std::string name, int64_t value) = 0;
virtual void add_global_string_variable(std::string name, std::string value) = 0;
virtual void set_caller(std::string caller, std::string caller_address) = 0;
virtual void set_state_pointer_value(std::string name, void *addr) = 0;
virtual void clear_exceptions() = 0;
// @throws exception
virtual void execute_contract_api_by_address(std::string contract_id, std::string method, std::string argument, std::string *result_json_string) = 0;
// @throws exception
virtual void execute_contract_init_by_address(std::string contract_id, std::string argument, std::string *result_json_string) = 0;
virtual void load_and_run_stream(void *stream) = 0;
virtual std::shared_ptr<VMModuleByteStream> get_bytestream_from_code(const uvm::blockchain::Code& code) = 0;
};
}
}
}
| [
"dfdchain@etfsoption.com"
] | dfdchain@etfsoption.com |
2fa88337bdaae26528321553dd2163a24daf1f68 | 44157527c4e18bf21f8a175d34bc3a1a9d9da7c2 | /GUI/SpaceCollisionSystem/qparticle2d.cpp | 717408c398a06a22d3a600f66eea1917bf538352 | [] | no_license | sock-lobster/CollisionDetection | 3dc775cf790a1f6ee3c7849d6760e319c613b76d | 76a461a34f538ddb74d39fc999db2ecab13a6369 | refs/heads/master | 2020-03-25T22:49:40.355086 | 2018-08-10T06:20:28 | 2018-08-10T06:20:28 | 144,244,356 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,344 | cpp | #include "qparticle2d.h"
#include "constants.h"
#include <QMutex>
#include <iostream>
QParticle2D::QParticle2D(Particle* p)
{
particle = p;
radius = p->getRadius() * SIZE_MULTIPLIER_2D;
diameter = radius*2;
color = QColor(0, 200, 0);
timestep = 0;
collisionTimestep = -1;
setPosition(p->getCurPos());
}
QParticle2D::~QParticle2D() {}
QRectF QParticle2D::boundingRect() const {
return QRectF(x(), y(), diameter * 2, diameter * 2);
}
void QParticle2D::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
painter->setBrush(color);
painter->setPen(color);
painter->drawEllipse(x(), y(), diameter * 2, diameter * 2);
}
void QParticle2D::advance(int step) {
if (step == 1){
if (collisionTimestep >= timestep) {
int red = 200;
color = QColor(red, 0, 0);
}
else {
color = QColor(0, 200, 0);
}
}
}
Particle* QParticle2D::getParticle() {
return particle;
}
void QParticle2D::setPosition(Position* position) {
std::valarray<double> temp = position->getPos() * SIZE_MULTIPLIER_2D;
setPos(temp[X_DIMENSION] - radius, temp[Y_DIMENSION] - radius);
}
void QParticle2D::setCollisionTimestep(int t) {
collisionTimestep = t;
}
void QParticle2D::incrementTimestep() {
timestep++;
}
| [
"dbarter4@gmail.com"
] | dbarter4@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.