blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 122 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2623eb63d63a3e17483d949bbfce6c35869f37e3 | c425cf8f7324ea1de1b63d0ea02d4367c5d958be | /Login/login.cpp | 0e5e3fa7ec66494e07424c5f0a0e990764e55db3 | [] | no_license | pandaandbun/QA-Phase-3 | e90d273284c967dd4107971fba5736a886ffa8ef | e18972b87c0651b20d2b47cb1a6ef55c2ebc9e7f | refs/heads/main | 2023-03-31T18:34:12.014747 | 2021-04-07T01:05:20 | 2021-04-07T01:05:20 | 343,461,253 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,417 | cpp | #include "login.h"
//Comparison function checking if the name string matches a predefined regex for account names
int User::isValidName(string name)
{
// Check if name is not null or empty string
if (name.empty() || name.compare("") == 0)
{
return 0;
}
// Check if name is at most 20 characters long and at least 1 character long
if (name.length() > 20)
{
return 0;
}
// Check if name does not contain digits or illegal characters
regex regexName("[^\\t\\n\\r\\f\\v0-9\\[\\]!@#$%^&*()_+{}|\\:;\"\'<,>.?/~`]+");
if (!regex_match(name, regexName))
{
return 0;
}
return 1;
}
int User::isValidAccountNumber(int accNumber)
{
// Check if number is larger then 5 digits or a negative number
if (accNumber < 0 || accNumber >= 99999)
{
return 0;
}
return 1;
}
// ----------------------------------------
// 0 - Error
// 1 - Success
// Central function that runs all login methods
int Login::RunLogin()
{
int session = SelectSession();
if (!session)
{
return 0;
}
if (!isAdmin)
{
if (StandardName())
{
// Standard Validated
cout << "Hi " << accountHolderName << endl;
return 1;
}
cout << "Name not valid" << endl;
}
else
{
// Admin Validated
return 1;
}
return 0;
}
// Selecting session where
// admin
// standard
int Login::SelectSession()
{
string type;
cout << "Enter session type: (admin / standard)\n";
cin >> type;
if (type == "admin" || type == "standard")
{
cout << "Login Accepted!\n";
if (type == "admin")
{
isAdmin = 1;
}
else if (type == "standard")
{
isAdmin = 0;
}
return 1;
}
return 0;
}
// Ask for standard user name
int Login::StandardName()
{
string name;
User user_check;
cout << "Enter Your Name:" << endl;
getline(cin >> ws, name);
// Check if name is valid
if (user_check.isValidName(name))
{
accountHolderName = name;
return 1;
}
// Name not valid
return 0;
}
// Save login info into a User Class that is then used by other transaction
User Login::saveUserInfo()
{
User user;
user.isAdmin = isAdmin;
user.userName = accountHolderName;
return user;
} | [
"trantienanh.ta@protonmail.com"
] | trantienanh.ta@protonmail.com |
aada3f7f56da7ae0ccbb0e54cf8388f36e0a4429 | 5ec06dab1409d790496ce082dacb321392b32fe9 | /clients/cpp-tizen/generated/src/ComAdobeCqSocialCommonsMaintainanceImplDeleteTempUGCImageUploadInfo.h | 6c3fa53ddc7e681d44a90ac0d1158e5480b19cc3 | [
"Apache-2.0"
] | permissive | shinesolutions/swagger-aem-osgi | e9d2385f44bee70e5bbdc0d577e99a9f2525266f | c2f6e076971d2592c1cbd3f70695c679e807396b | refs/heads/master | 2022-10-29T13:07:40.422092 | 2021-04-09T07:46:03 | 2021-04-09T07:46:03 | 190,217,155 | 3 | 3 | Apache-2.0 | 2022-10-05T03:26:20 | 2019-06-04T14:23:28 | null | UTF-8 | C++ | false | false | 2,069 | h | /*
* ComAdobeCqSocialCommonsMaintainanceImplDeleteTempUGCImageUploadInfo.h
*
*
*/
#ifndef _ComAdobeCqSocialCommonsMaintainanceImplDeleteTempUGCImageUploadInfo_H_
#define _ComAdobeCqSocialCommonsMaintainanceImplDeleteTempUGCImageUploadInfo_H_
#include <string>
#include "ComAdobeCqSocialCommonsMaintainanceImplDeleteTempUGCImageUploadProperties.h"
#include "Object.h"
/** \defgroup Models Data Structures for API
* Classes containing all the Data Structures needed for calling/returned by API endpoints
*
*/
namespace Tizen {
namespace ArtikCloud {
/*! \brief
*
* \ingroup Models
*
*/
class ComAdobeCqSocialCommonsMaintainanceImplDeleteTempUGCImageUploadInfo : public Object {
public:
/*! \brief Constructor.
*/
ComAdobeCqSocialCommonsMaintainanceImplDeleteTempUGCImageUploadInfo();
ComAdobeCqSocialCommonsMaintainanceImplDeleteTempUGCImageUploadInfo(char* str);
/*! \brief Destructor.
*/
virtual ~ComAdobeCqSocialCommonsMaintainanceImplDeleteTempUGCImageUploadInfo();
/*! \brief Retrieve a string JSON representation of this class.
*/
char* toJson();
/*! \brief Fills in members of this class from JSON string representing it.
*/
void fromJson(char* jsonStr);
/*! \brief Get
*/
std::string getPid();
/*! \brief Set
*/
void setPid(std::string pid);
/*! \brief Get
*/
std::string getTitle();
/*! \brief Set
*/
void setTitle(std::string title);
/*! \brief Get
*/
std::string getDescription();
/*! \brief Set
*/
void setDescription(std::string description);
/*! \brief Get
*/
ComAdobeCqSocialCommonsMaintainanceImplDeleteTempUGCImageUploadProperties getProperties();
/*! \brief Set
*/
void setProperties(ComAdobeCqSocialCommonsMaintainanceImplDeleteTempUGCImageUploadProperties properties);
private:
std::string pid;
std::string title;
std::string description;
ComAdobeCqSocialCommonsMaintainanceImplDeleteTempUGCImageUploadProperties properties;
void __init();
void __cleanup();
};
}
}
#endif /* _ComAdobeCqSocialCommonsMaintainanceImplDeleteTempUGCImageUploadInfo_H_ */
| [
"cliffano@gmail.com"
] | cliffano@gmail.com |
dfee821f966e64afb7cd30d3472f9282389ecc17 | 119b39b4df1c861d01bc5df95e9abda3e38fb6a5 | /src/geneticalgorithm.cpp | 719e2519f795c7aba3acda7225ffd2a50458aaec | [] | no_license | rainwaffles/neurons | 971b5d369eff87d0e0496d2554570b8f6ab61728 | ff48e54fea392511838223e49a255a9ce3ecc013 | refs/heads/master | 2021-01-10T05:39:26.173970 | 2016-04-08T16:55:59 | 2016-04-08T16:55:59 | 49,180,263 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,521 | cpp | #include "geneticalgorithm.hpp"
void Genome::fillrand(int numweights)
{
for(int i = 0; i < numweights; i++)
{
weights.push_back((rand()/(RAND_MAX + 1.0))*2 - 1);
}
}
GenAlg::GenAlg(int popsize_, double mutationrate_, double crossrate_, int chromolen_)
: popsize(popsize_), mutationrate(mutationrate_), crossrate(crossrate_), chromolen(chromolen_),
totalfit(0), highestfit(0), averagefit(0), lowestfit(999999), fittest(0), generation(0)
{
srand(time(NULL));
for(int i = 0; i < popsize; i++)
{
pop.push_back(Genome());
pop[i].fillrand(chromolen);
}
}
std::vector<Genome> GenAlg::epoch(std::vector<Genome> &pop_)
{
pop = pop_;
reset();
std::sort(pop.begin(), pop.end());
calcstats();
std::vector<Genome> newpop;
best(4, 1, newpop);
while(newpop.size() < popsize)
{
Genome p1 = getchromo();
Genome p2 = getchromo();
std::vector<double> b1, b2;
crossover(p1.weights, p2.weights, b1, b2);
mutate(b1); mutate(b2);
newpop.push_back(Genome(b1, 0));
newpop.push_back(Genome(b2, 0));
}
pop = newpop;
return pop;
}
void GenAlg::mutate(std::vector<double> chromo)
{
for(int i = 0; i < chromo.size(); i++)
{
if(rand()/(RAND_MAX + 1.0) < mutationrate)
{
chromo[i] += rand()/(RAND_MAX + 1.0)*0.3;
}
}
}
void GenAlg::crossover(const std::vector<double> &p1, const std::vector<double> &p2,
std::vector<double> &b1, std::vector<double> &b2)
{
if(rand()/(RAND_MAX + 1.0) > crossrate || p1 == p2)
{
b1 = p1; b2 = p2;
return;
}
int cp = rand()%chromolen;
for(int i = 0; i < chromolen; i++)
{
b1.push_back((i < cp)? p1[i] : p2[i]);
b2.push_back((i < cp)? p2[i] : p1[i]);
}
return;
}
Genome GenAlg::getchromo()
{
double fitn = rand()/(RAND_MAX + 1.0)*totalfit;
double cumfit = 0;
for(int i = 0; i < popsize; i++)
{
cumfit += pop[i].fitness;
if(cumfit >= fitn){return pop[i];}
}
return pop[popsize-1];
}
void GenAlg::best(int n, const int copies, std::vector<Genome> &pop_)
{
while(n--)
{
for(int i = 0; i < copies; i++)
{
pop_.push_back(pop[popsize - 1 - n]);
}
}
}
void GenAlg::calcstats()
{
totalfit = 0;
double curhigh = 0, curlow = 999999;
for(int i = 0; i < popsize; i++)
{
if(pop[i].fitness > curhigh)
{
curhigh = pop[i].fitness;
fittest = i; highestfit = curhigh;
}
if(pop[i].fitness < curlow)
{
curlow = pop[i].fitness;
lowestfit = curlow;
}
totalfit += pop[i].fitness;
}
averagefit = totalfit / popsize;
}
void GenAlg::reset()
{
totalfit = highestfit = averagefit = 0;
lowestfit = 999999;
}
| [
"evanmcneil1999@gmail.com"
] | evanmcneil1999@gmail.com |
88f115600c747fb13061a37836eaf802faa1f10b | fd1f9d46644adef7a96b462220d676fa71119383 | /util.cpp | 28673cffc71b86b125807e616335e93c77baad9c | [] | no_license | beston91/RayTracer | 6467c756c401e99de3ff325bb3fdbbf8360630dc | 12164a3aba61493adedb2fee3233cfb2f4623090 | refs/heads/master | 2021-07-13T08:02:08.695400 | 2020-06-12T01:02:51 | 2020-06-12T01:02:51 | 157,776,552 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,928 | cpp | /***********************************************************
Starter code for Assignment 3
Implementations of util.h
***********************************************************/
#include "util.h"
Point3D::Point3D() {
m_data[0] = 0.0;
m_data[1] = 0.0;
m_data[2] = 0.0;
}
Point3D::Point3D(double x, double y, double z) {
m_data[0] = x;
m_data[1] = y;
m_data[2] = z;
}
Point3D::Point3D(const Point3D& other) {
m_data[0] = other.m_data[0];
m_data[1] = other.m_data[1];
m_data[2] = other.m_data[2];
}
Point3D& Point3D::operator =(const Point3D& other) {
m_data[0] = other.m_data[0];
m_data[1] = other.m_data[1];
m_data[2] = other.m_data[2];
return *this;
}
double& Point3D::operator[](int i) {
return m_data[i];
}
double Point3D::operator[](int i) const {
return m_data[i];
}
Vector3D Point3D::ToVector() {
return Vector3D(m_data[0], m_data[1], m_data[2]);
}
Vector3D::Vector3D() {
m_data[0] = 0.0;
m_data[1] = 0.0;
m_data[2] = 0.0;
}
Vector3D::Vector3D(double x, double y, double z) {
m_data[0] = x;
m_data[1] = y;
m_data[2] = z;
}
Vector3D::Vector3D(const Vector3D& other) {
m_data[0] = other.m_data[0];
m_data[1] = other.m_data[1];
m_data[2] = other.m_data[2];
}
Vector3D& Vector3D::operator =(const Vector3D& other) {
m_data[0] = other.m_data[0];
m_data[1] = other.m_data[1];
m_data[2] = other.m_data[2];
return *this;
}
double& Vector3D::operator[](int i) {
return m_data[i];
}
double Vector3D::operator[](int i) const {
return m_data[i];
}
double Vector3D::length() const
{
return sqrt(dot(*this));
}
double Vector3D::normalize() {
double denom = 1.0;
double x = (m_data[0] > 0.0) ? m_data[0] : -m_data[0];
double y = (m_data[1] > 0.0) ? m_data[1] : -m_data[1];
double z = (m_data[2] > 0.0) ? m_data[2] : -m_data[2];
if(x > y) {
if(x > z) {
if(1.0 + x > 1.0) {
y = y / x;
z = z / x;
denom = 1.0 / (x * sqrt(1.0 + y*y + z*z));
}
} else { /* z > x > y */
if(1.0 + z > 1.0) {
y = y / z;
x = x / z;
denom = 1.0 / (z * sqrt(1.0 + y*y + x*x));
}
}
} else {
if(y > z) {
if(1.0 + y > 1.0) {
z = z / y;
x = x / y;
denom = 1.0 / (y * sqrt(1.0 + z*z + x*x));
}
} else { /* x < y < z */
if(1.0 + z > 1.0) {
y = y / z;
x = x / z;
denom = 1.0 / (z * sqrt(1.0 + y*y + x*x));
}
}
}
if(1.0 + x + y + z > 1.0) {
m_data[0] *= denom;
m_data[1] *= denom;
m_data[2] *= denom;
return 1.0 / denom;
}
return 0.0;
}
double Vector3D::dot(const Vector3D& other) const
{
return m_data[0]*other.m_data[0] +
m_data[1]*other.m_data[1] +
m_data[2]*other.m_data[2];
}
Vector3D Vector3D::cross(const Vector3D& other) const
{
return Vector3D(
m_data[1]*other[2] - m_data[2]*other[1],
m_data[2]*other[0] - m_data[0]*other[2],
m_data[0]*other[1] - m_data[1]*other[0]);
}
Vector3D operator *(double s, const Vector3D& v)
{
return Vector3D(s*v[0], s*v[1], s*v[2]);
}
Vector3D operator +(const Vector3D& u, const Vector3D& v)
{
return Vector3D(u[0]+v[0], u[1]+v[1], u[2]+v[2]);
}
Point3D operator +(const Point3D& u, const Vector3D& v)
{
return Point3D(u[0]+v[0], u[1]+v[1], u[2]+v[2]);
}
Vector3D operator -(const Point3D& u, const Point3D& v)
{
return Vector3D(u[0]-v[0], u[1]-v[1], u[2]-v[2]);
}
Vector3D operator -(const Vector3D& u, const Vector3D& v)
{
return Vector3D(u[0]-v[0], u[1]-v[1], u[2]-v[2]);
}
Vector3D operator -(const Vector3D& u)
{
return Vector3D(-u[0], -u[1], -u[2]);
}
Point3D operator -(const Point3D& u, const Vector3D& v)
{
return Point3D(u[0]-v[0], u[1]-v[1], u[2]-v[2]);
}
Vector3D cross(const Vector3D& u, const Vector3D& v)
{
return u.cross(v);
}
std::ostream& operator <<(std::ostream& s, const Point3D& p)
{
return s << "p(" << p[0] << "," << p[1] << "," << p[2] << ")";
}
std::ostream& operator <<(std::ostream& s, const Vector3D& v)
{
return s << "v(" << v[0] << "," << v[1] << "," << v[2] << ")";
}
Color::Color() {
m_data[0] = 0.0;
m_data[1] = 0.0;
m_data[2] = 0.0;
}
Color::Color(double r, double g, double b) {
m_data[0] = r;
m_data[1] = g;
m_data[2] = b;
}
Color::Color(const Color& other) {
m_data[0] = other.m_data[0];
m_data[1] = other.m_data[1];
m_data[2] = other.m_data[2];
}
Color& Color::operator =(const Color& other) {
m_data[0] = other.m_data[0];
m_data[1] = other.m_data[1];
m_data[2] = other.m_data[2];
return *this;
}
Color Color::operator *(const Color& other) {
return Color(m_data[0]*other.m_data[0],
m_data[1]*other.m_data[1],
m_data[2]*other.m_data[2]);
}
double& Color::operator[](int i) {
return m_data[i];
}
double Color::operator[](int i) const {
return m_data[i];
}
void Color::clamp() {
for (int i = 0; i < 3; i++) {
if (std::isnan(m_data[i])) m_data[i] = 0.0;
if (m_data[i] > 1.0) m_data[i] = 1.0;
if (m_data[i] < 0.0) m_data[i] = 0.0;
}
}
Color operator *(double s, const Color& c)
{
return Color(s*c[0], s*c[1], s*c[2]);
}
Color operator +(const Color& u, const Color& v)
{
return Color(u[0]+v[0], u[1]+v[1], u[2]+v[2]);
}
std::ostream& operator <<(std::ostream& s, const Color& c)
{
return s << "c(" << c[0] << "," << c[1] << "," << c[2] << ")";
}
Vector4D::Vector4D() {
m_data[0] = 0.0;
m_data[1] = 0.0;
m_data[2] = 0.0;
m_data[3] = 0.0;
}
Vector4D::Vector4D(double w, double x, double y, double z) {
m_data[0] = w;
m_data[1] = x;
m_data[2] = y;
m_data[3] = z;
}
Vector4D::Vector4D(const Vector4D& other) {
m_data[0] = other.m_data[0];
m_data[1] = other.m_data[1];
m_data[2] = other.m_data[2];
m_data[3] = other.m_data[3];
}
Vector4D& Vector4D::operator =(const Vector4D& other) {
m_data[0] = other.m_data[0];
m_data[1] = other.m_data[1];
m_data[2] = other.m_data[2];
m_data[3] = other.m_data[3];
return *this;
}
double& Vector4D::operator[](int i) {
return m_data[i];
}
double Vector4D::operator[](int i) const {
return m_data[i];
}
Matrix4x4::Matrix4x4() {
for (int i = 0; i < 16; i++)
m_data[i] = 0.0;
m_data[0] = 1.0;
m_data[5] = 1.0;
m_data[10] = 1.0;
m_data[15] = 1.0;
}
Matrix4x4::Matrix4x4(const Matrix4x4& other) {
for (int i = 0; i < 16; i++)
m_data[i] = other.m_data[i];
}
Matrix4x4& Matrix4x4::operator=(const Matrix4x4& other) {
for (int i = 0; i < 16; i++)
m_data[i] = other.m_data[i];
return *this;
}
Vector4D Matrix4x4::getRow(int row) const {
return Vector4D(m_data[4*row], m_data[4*row+1], m_data[4*row+2],
m_data[4*row+3]);
}
double* Matrix4x4::getRow(int row) {
return (double*)m_data + 4*row;
}
Vector4D Matrix4x4::getColumn(int col) const {
return Vector4D(m_data[col], m_data[4+col], m_data[8+col],
m_data[12+col]);
}
Vector4D Matrix4x4::operator[](int row) const {
return getRow(row);
}
double* Matrix4x4::operator[](int row) {
return getRow(row);
}
Matrix4x4 Matrix4x4::transpose() const {
Matrix4x4 M;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
M[i][j] = (*this)[j][i];
}
}
return M;
}
Matrix4x4 operator *(const Matrix4x4& a, const Matrix4x4& b) {
Matrix4x4 ret;
for(size_t i = 0; i < 4; ++i) {
Vector4D row = a.getRow(i);
for(size_t j = 0; j < 4; ++j) {
ret[i][j] = row[0] * b[0][j] + row[1] * b[1][j] +
row[2] * b[2][j] + row[3] * b[3][j];
}
}
return ret;
}
Vector3D operator *(const Matrix4x4& M, const Vector3D& v) {
return Vector3D(
v[0] * M[0][0] + v[1] * M[0][1] + v[2] * M[0][2],
v[0] * M[1][0] + v[1] * M[1][1] + v[2] * M[1][2],
v[0] * M[2][0] + v[1] * M[2][1] + v[2] * M[2][2]);
}
Point3D operator *(const Matrix4x4& M, const Point3D& p) {
return Point3D(
p[0] * M[0][0] + p[1] * M[0][1] + p[2] * M[0][2] + M[0][3],
p[0] * M[1][0] + p[1] * M[1][1] + p[2] * M[1][2] + M[1][3],
p[0] * M[2][0] + p[1] * M[2][1] + p[2] * M[2][2] + M[2][3]);
}
Vector3D transNorm(const Matrix4x4& M, const Vector3D& n) {
return Vector3D(
n[0] * M[0][0] + n[1] * M[1][0] + n[2] * M[2][0],
n[0] * M[0][1] + n[1] * M[1][1] + n[2] * M[2][1],
n[0] * M[0][2] + n[1] * M[1][2] + n[2] * M[2][2]);
}
std::ostream& operator <<(std::ostream& os, const Matrix4x4& M) {
return os << "[" << M[0][0] << " " << M[0][1] << " "
<< M[0][2] << " " << M[0][3] << "]" << std::endl
<< "[" << M[1][0] << " " << M[1][1] << " "
<< M[1][2] << " " << M[1][3] << "]" << std::endl
<< "[" << M[2][0] << " " << M[2][1] << " "
<< M[2][2] << " " << M[2][3] << "]" << std::endl
<< "[" << M[3][0] << " " << M[3][1] << " "
<< M[3][2] << " " << M[3][3] << "]";
}
int SolveQuadratic(double a, double b, double c, double *intersections) {
double thing = (b*b) - (4.0 * a * c);
if (thing < 0)
return 0;
if (thing > -QUADRATIC_EPSILON && thing < QUADRATIC_EPSILON) {
intersections[0] = (-b) / (2.0 * a);
return 1;
}
intersections[0] = (-b + sqrt(thing))/ (2.0 * a);
intersections[1] = (-b - sqrt(thing))/ (2.0 * a);
return 2;
}
/*
* Light direction is from the intersection point to the light
* Eye direction is from the eye to the point.
*/
Color Phong(Vector3D& _lightDirection, Vector3D& _normal, Vector3D _eyeDirection,
Material* mat, Color& col_ambient, Color& col_diffuse, Color& col_specular) {
_lightDirection.normalize();
double diffuseIntensity =
std::max(0.0, _normal.dot(_lightDirection));
Vector3D mirrorRay = (
(2.0 * _normal.dot(_lightDirection) * _normal)
- _lightDirection
);
mirrorRay.normalize();
// Just in case
_eyeDirection.normalize();
double specularIntensity = pow(
std::max(0.0, _eyeDirection.dot(-1 * mirrorRay)),
mat -> specular_exp
);
Color diffuseColor = diffuseIntensity * col_diffuse;
diffuseColor.clamp();
Color specularColor = specularIntensity * col_specular;
specularColor.clamp();
Color c(
(col_ambient * mat -> ambient) +
(diffuseColor * mat -> diffuse) +
(specularColor * mat -> specular)
);
c.clamp();
return c;
}
int Vector3D::isZero() const {
return (this -> m_data[0] < EPSILON &&
this -> m_data[1] < EPSILON &&
this -> m_data[2] < EPSILON);
}
Vector3D GetArbitraryTangentFromNorm(Vector3D& n) {
Vector3D test(1.0, 1.0, 1.0);
Vector3D crossRes = n.cross(test);
if (crossRes.isZero()) {
test[0] = 0.0;
crossRes = n.cross(test);
}
crossRes.normalize();
return crossRes;
}
unsigned char* readBMP(char* filename) {
/*
* Note that this is taken from StackOverflow @9296059 as a helper class for
* loading bitmaps.
*
*/
FILE* f = fopen(filename, "rb");
unsigned char info[122];
fread(info, sizeof(unsigned char), 122, f); // Read 122-byte header.
// This might be sketchy since the header size could change.
// TODO make this static.
int width = *(int*)&info[18];
int height = *(int*)&info[22];
int size = 3 * width * height; // 24 bit color depth
unsigned char* data = new unsigned char[size];
fread(data, sizeof(unsigned char), size, f);
fclose(f);
/*
* Convert from BGR to RGB?
*/
for (int i = 0; i < size; i += 3) {
unsigned char tmp = data[i];
data[i] = data[i+2];
data[i + 2] = tmp;
}
return data;
}
| [
"beston@modiface.com"
] | beston@modiface.com |
bba89a2e024143352bfa157c835c1ec6cc71f1f9 | fb913f54c5082cf25c15c905b339188f22b5750c | /pawndialog.cpp | 3ca037f82fa3ff3fd4ba95b01f36da9b389dd18b | [] | no_license | THUzxj/Qt-Homework-Tcp-Chess-Game | 67f53f4b854e4f48ab26c2cda80d1116ac2fa760 | 95cea01c97458a2a91e205898f85b5c15523ce6e | refs/heads/master | 2020-07-22T03:08:56.403106 | 2020-06-12T10:01:32 | 2020-06-12T10:01:32 | 207,056,760 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,714 | cpp | #include "pawndialog.h"
#include "ui_pawndialog.h"
PawnDialog::PawnDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::PawnDialog)
{
ui->setupUi(this);
/* connect(ui->pushButton,&QPushButton::clicked,[&](){_value = 1;});
connect(ui->pushButton_2,&QPushButton::clicked,[&](){_value = 2;});
connect(ui->pushButton_3,&QPushButton::clicked,[&](){_value = 3;});
connect(ui->pushButton_4,&QPushButton::clicked,[&](){_value = 4;});
connect(ui->pushButton,&QPushButton::clicked,this,&PawnDialog::close);
connect(ui->pushButton_2,&QPushButton::clicked,this,&PawnDialog::close);
connect(ui->pushButton_3,&QPushButton::clicked,this,&PawnDialog::close);
connect(ui->pushButton_4,&QPushButton::clicked,this,&PawnDialog::close);*/
//设置扩展属性
ui->pushButton->setProperty("value",1);
ui->pushButton_2->setProperty("value",2);
ui->pushButton_3->setProperty("value",3);
ui->pushButton_4->setProperty("value",4);
connect(ui->pushButton,&QPushButton::clicked,this,&PawnDialog::accept);
connect(ui->pushButton_2,&QPushButton::clicked,this,&PawnDialog::accept);
connect(ui->pushButton_3,&QPushButton::clicked,this,&PawnDialog::accept);
connect(ui->pushButton_4,&QPushButton::clicked,this,&PawnDialog::accept);
}
PawnDialog::~PawnDialog()
{
delete ui;
}
int PawnDialog::value(){
return _value;
}
void PawnDialog::accept(){
// 获取信号发送者
QPushButton *button = qobject_cast<QPushButton *>(sender());
// 设置返回值
if (button)
{
_value = button->property("value").toInt();
}
// 向下传递
QDialog::accept();
}
| [
"1312144019@qq.com"
] | 1312144019@qq.com |
8f021fbb0de8c7cff4938812eacd496500407569 | 52489fb9b1217a06f5e9b9946e888c85fae7fab7 | /Arduino/velo/Lights.h | 6d0e404e6e82b96de4be005359fadf149ba96b5b | [] | no_license | basilstotz/arduino-plunder | 046a01241ba1a149d69ebd5ed7b5fa3ced4e9e81 | f10a32c57893f715fd404186942ad49cd6a45f08 | refs/heads/main | 2023-04-06T21:26:34.809326 | 2021-04-13T08:04:24 | 2021-04-13T08:04:24 | 357,471,297 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,132 | h |
#ifndef Lights_h
#define Lights_h
#include <Adafruit_NeoPixel.h>
#define LIGHT_PIN 0
#define LED_PIN 13
#define LED_BLOCK (ledCount/6)
#define LED0 (0*LED_BLOCK)
#define LED1 (1*LED_BLOCK)
#define LED2 (2*LED_BLOCK)
#define LED3 (3*LED_BLOCK)
#define LED4 (4*LED_BLOCK)
#define LED5 (5*LED_BLOCK)
#define LED6 (6*LED_BLOCK)
#define ON true
#define OFF false
#define RIGHT true
#define LEFT false
#define BLINK_MODE_0 0
#define BLINK_MODE_1 1
#define BLINK_MODE_2 2
#define LIGHT_MEAN 1
//value=(r0/(r+r0))*1023
// _____ _____
// gnd ---|_r0__|---|__r__|----5v
// |
// |
// a0
//
// with r0=5.0k, r0=10K
#define AMB_HIGH (931*LIGHT_MEAN) //1k 931, 930
#define AMB_MIDH (850*LIGHT_MEAN) //2k 731, 850
#define AMB_MIDL (170*LIGHT_MEAN)
#define AMB_LOW (20*LIGHT_MEAN) //50k 96, 170
#define LIGHT_AUTO 0
#define LIGHT_OFF 1
#define LIGHT_ON 2
#define LIGHT_FULL 3
#define DELAY 10
// in 100mW units. eg 100 -> 10W
#define MAX_POWER 100
// in 100mW units. eg 3 -> 300mW
#define LED_POWER 3
#define MAX_BRIGHT 255
class Lights {
public:
Lights(int _ledCount, int _pin);
void left(boolean state);
void right(boolean state);
void brake(boolean state);
void front(boolean state);
void side(boolean state);
void back(boolean state);
void warn(boolean state);
void rainbow(boolean state);
void illum(boolean state);
void phare(boolean state);
void torch(boolean state);
boolean left();
boolean right();
boolean brake();
boolean front();
boolean side();
boolean back();
boolean warn();
boolean phare();
boolean rainbow();
boolean torch();
boolean illum();
void resetSpecial();
void nextSpecial();
void resetLight();
void nextLight();
void draw();
void blinkParam(int _blinkPeriod, int _blinkAnimation, int _blinkMode);
private:
Adafruit_NeoPixel *strip;
int pin;
int ledCount;
uint32_t frameCounter;
long firstPixelHue;
//light measurement
int ambientLight;
int lightMode;
int lightState;
int oldLightState;
int leftPhase;
int rightPhase;
int brakePhase;
int frontPhase;
int sidePhase;
int backPhase;
int warnPhase;
int blinkPeriod;
int blinkAnimation;
int blinkMode;
int brakeAnimation;
boolean leftState;
boolean rightState;
boolean brakeState;
boolean frontState;
boolean sideState;
boolean backState;
boolean warnState;
boolean rainbowState;
boolean illumState;
boolean phareState;
boolean torchState;
boolean leftIntState;
boolean rightIntState;
boolean warnIntState;
boolean sideIntState;
boolean phareIntState;
boolean frontIntState;
boolean backIntState;
void fill(int start, int stop, uint32_t color);
void fill(int start, int stop, uint32_t color, boolean what, boolean dir, int phase );
uint32_t white;
uint32_t orange;
uint32_t red;
uint32_t off;
int brightness;
};
#endif
| [
"basil.stotz@gmail.com"
] | basil.stotz@gmail.com |
f1e7f8a3c1930a2853c7a59b2752acdaba8eb71e | 508510d10ddcb009fc4fb53a26d897bc462039c0 | /PUBG/SDK/PUBG_ListBaseGroupWidget_functions.cpp | 002d6881e4074a652ff566749cab6c6e602bf38a | [] | no_license | Avatarchik/PUBG-SDK | ed6e0aa27eac646e557272bbf1607b7351905c8c | 07639ddf96bc0f57fb4b1be0a9b29d5446fcc5da | refs/heads/master | 2021-06-21T07:51:37.309095 | 2017-08-10T08:15:56 | 2017-08-10T08:15:56 | 100,607,141 | 1 | 1 | null | 2017-08-17T13:36:40 | 2017-08-17T13:36:40 | null | UTF-8 | C++ | false | false | 3,533 | cpp | // PLAYERUNKNOWN BattleGrounds () SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace Classes
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function ListBaseGroupWidget.ListBaseGroupWidget_C.GetChilderenCount
// (FUNC_Public, FUNC_HasOutParms, FUNC_BlueprintCallable, FUNC_BlueprintEvent, FUNC_BlueprintPure, FUNC_Const)
// Parameters:
// int Count (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData)
void UListBaseGroupWidget_C::GetChilderenCount(int* Count)
{
static auto fn = UObject::FindObject<UFunction>("Function ListBaseGroupWidget.ListBaseGroupWidget_C.GetChilderenCount");
UListBaseGroupWidget_C_GetChilderenCount_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (Count != nullptr)
*Count = params.Count;
}
// Function ListBaseGroupWidget.ListBaseGroupWidget_C.AddChild
// (FUNC_Public, FUNC_HasOutParms, FUNC_BlueprintCallable, FUNC_BlueprintEvent)
// Parameters:
// class UWidget* Content (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReferenceParm, CPF_IsPlainOldData)
void UListBaseGroupWidget_C::AddChild(class UWidget** Content)
{
static auto fn = UObject::FindObject<UFunction>("Function ListBaseGroupWidget.ListBaseGroupWidget_C.AddChild");
UListBaseGroupWidget_C_AddChild_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (Content != nullptr)
*Content = params.Content;
}
// Function ListBaseGroupWidget.ListBaseGroupWidget_C.Clear
// (FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintEvent)
void UListBaseGroupWidget_C::Clear()
{
static auto fn = UObject::FindObject<UFunction>("Function ListBaseGroupWidget.ListBaseGroupWidget_C.Clear");
UListBaseGroupWidget_C_Clear_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ListBaseGroupWidget.ListBaseGroupWidget_C.On_List_Prepass_1
// (FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintEvent)
// Parameters:
// class UWidget* BoundWidget (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
void UListBaseGroupWidget_C::On_List_Prepass_1(class UWidget* BoundWidget)
{
static auto fn = UObject::FindObject<UFunction>("Function ListBaseGroupWidget.ListBaseGroupWidget_C.On_List_Prepass_1");
UListBaseGroupWidget_C_On_List_Prepass_1_Params params;
params.BoundWidget = BoundWidget;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ListBaseGroupWidget.ListBaseGroupWidget_C.AddCategoryGroup
// (FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintEvent)
// Parameters:
// class UCategoryGroupWidget_C* CategoryGroup (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
void UListBaseGroupWidget_C::AddCategoryGroup(class UCategoryGroupWidget_C* CategoryGroup)
{
static auto fn = UObject::FindObject<UFunction>("Function ListBaseGroupWidget.ListBaseGroupWidget_C.AddCategoryGroup");
UListBaseGroupWidget_C_AddCategoryGroup_Params params;
params.CategoryGroup = CategoryGroup;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"jl2378@cornell.edu"
] | jl2378@cornell.edu |
8495af0594640a5a082b54980fc7ba8fc23b54b1 | 0ea462269dffaa39c3f15948290e198e3f142d6a | /KLObject.cpp | 6bde434aa4d4106392b053f7b8d4194d0c871916 | [] | no_license | MichaelIbrahim-GaTech/AGV-Liveness | 5f49e8cd4ff46487d47e71091971ded6016a8d7b | 3ef53692265ec4ec0225ce5f7e8b624923d7cb54 | refs/heads/master | 2023-03-12T06:15:11.751271 | 2021-02-16T15:42:19 | 2021-02-16T15:42:19 | 274,229,630 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 529 | cpp | #include "KLObject.h"
KLObject::KLObject()
{
K = -1;
L = -1;
AssociatedEdge = -1;
Considered = false;
prev = NULL;
}
KLObject::KLObject(const KLObject& _kl)
{
K = _kl.K;
L = _kl.L;
AssociatedEdge = _kl.AssociatedEdge;
Considered = _kl.Considered;
prev = _kl.prev;
}
bool operator < (const KLObject& lhs, const KLObject& rhs)
{
return ((lhs.K <= rhs.K) && (lhs.L <= rhs.L));
}
bool operator > (const KLObject& lhs, const KLObject& rhs)
{
return ((lhs.K >= rhs.K) && (lhs.L >= rhs.L));
} | [
"noreply@github.com"
] | MichaelIbrahim-GaTech.noreply@github.com |
bf10b71ef6fef3e18267dfa3e4299b01d0f46272 | 12c1a1aea54ad751db5c9c698be147a5a7a0999a | /fun.cpp | 183eb22219fa8a31b8dcd71b2a51fc5ca7d4d623 | [] | no_license | Jou1703/OPENGL | 0b11c5ad1c81d1fefe7a0b472b0a9104401c21ec | bc5d97885ecd55080e45a55321e5c4765bdc9b00 | refs/heads/master | 2021-01-12T17:42:28.503799 | 2017-09-20T09:35:34 | 2017-09-20T09:35:34 | 71,625,868 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,700 | cpp | #include "includes.h"
#include <pthread.h>
#include "fun.h"
#include <ctype.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <dirent.h>
#include <stdarg.h>
#include "all_path.h"
#include "option.h"
#include "conf.h"
extern TSysData gSysData;
#define JOY_RUN 1
#define JOY_STOP 0
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int joy_status = JOY_RUN;
int GetUid()
{
return getuid();
}
int GetUUid()
{
return geteuid();
}
void ThreadMutex()
{
pthread_mutex_lock(&mut);
while (!joy_status)
{
pthread_cond_wait(&cond, &mut);
}
pthread_mutex_unlock(&mut);
}
void JoyThreadResume()
{
if (joy_status == JOY_STOP)
{
pthread_mutex_lock(&mut);
joy_status = JOY_RUN;
pthread_cond_signal(&cond);
printf("pthread run!\n");
pthread_mutex_unlock(&mut);
}
else
{
printf("pthread run already\n");
}
}
void JoyThreadPause()
{
if (joy_status == JOY_RUN)
{
pthread_mutex_lock(&mut);
joy_status = JOY_STOP;
printf("thread stop!\n");
pthread_mutex_unlock(&mut);
}
else
{
printf("pthread pause already\n");
}
}
pthread_t* thread_create(void*(*func)(void*),void *arg)
{
int ret;
pthread_t *thread;
thread = (pthread_t *)malloc(sizeof(pthread_t));
if (thread == NULL)
return NULL;
ret = pthread_create(thread,NULL,func,(void*)arg);
if (ret !=0)
return NULL;
return thread;
}
void ThreadExit(void)
{
pthread_exit(NULL);
}
int SystemEx(const char* cmd_string)
{
int status = 0;
int child_pid = -1;
if (cmd_string == NULL)
return -1;
child_pid = vfork();
if (child_pid == 0)
{
execl("/bin/sh","sh","-c",cmd_string,(char*)0);
}
else if (child_pid >0)
{
waitpid(child_pid, &status, 0);
}
else if (child_pid <0)
return -1;
return 0;
}
int SystemExSu(const char* cmd_string)
{
int status = 0;
int child_pid = -1;
if (cmd_string == NULL)
return -1;
child_pid = vfork();
if (child_pid == 0)
{
printf("uid = %d euid = %d\n",GetUid(),GetUUid());
setuid(0);
printf("uid = %d euid = %d\n",GetUid(),GetUUid());
execl("/bin/sh","sh","-c",cmd_string,(char*)0);
}
else if (child_pid >0)
{
waitpid(child_pid, &status, 0);
}
else if (child_pid <0)
return -1;
return 0;
}
int IsFileExist(const char *file_path)
{
return (!access(file_path,F_OK));
}
int IsDirExist(const char *dir_path)
{
DIR *dp;
if ((dp=opendir(dir_path))==NULL)
{
LOG_ERR("dir not exist");
return 0;
}
closedir(dp);
return 1;
}
int ChmodFile(const char* file,int mod)
{
if(chmod(file,mod)==-1)
{
LOG_ERR("chmod err");
return -1;
}
return 0;
}
int ChownFile(const char *pathname,uid_t owner,gid_t group)
{
if( chown(pathname,owner,group)==-1)
{
LOG_ERR("chown err");
return -1;
}
return 0;
}
char const *str_xrandr[10]=
{
"1920x1080",
"1680x1050",
"1600x1200",
"1440x900",
"1280x1024",
"1280x800",
"1280x768",
"1280x720",
"1152x864",
"1024x768"
};
GLuint wxrandr[10]={1920,1680,1600,1440,1280,1280,1280,1280,1152,1024};
GLuint hxrandr[10]={1080,1050,1200,900, 1024,800, 768, 720, 864, 768};
extern char text_xrandr[100];
int GetResolutionPos(int width, int height)
{
char resolution[64] = {0};
sprintf(resolution,"%dx%d",width,height);
for(int i=0;i<10;++i)
{
if (strcmp(resolution,str_xrandr[i]) ==0)
return i+1;
}
return 1;
}
int GetGraphicsCards()
{
char card960[128] = "GeForce GTX 960";
char card730[128] = "GeForce GT 730";
int card=0;
FILE *fp;
char buf[128]={0};
fp = popen("/usr/sbin/hwinfo --gfxcard | grep Model", "r");
if(NULL == fp)
{
LOG_ERR("popen error");
return 0;
}
while(1)
{
memset(buf,0,sizeof(buf));
if(fgets(buf, sizeof(buf), fp) != NULL)
{
if(strstr(buf,card960))
{
card++;
LOG_INFO("card%d:%s found",card,card960);
}
else if(strstr(buf,card730))
{
card++;
LOG_INFO("card%d:%s found",card,card730);
}
}
else
{
break;
}
}
if(card < 2)
return -1;
else
return 0;
return -1;
}
int GetBiosKey()
{
char bios_key[128] = "Shimmerfcgame+";
FILE *fp;
char buf[128]={0};
fp = popen("/usr/sbin/dmidecode -t12", "r");
if(NULL == fp)
{
LOG_ERR("popen error");
return 0;
}
while(1)
{
memset(buf,0,sizeof(buf));
if(fgets(buf, sizeof(buf), fp) != NULL)
{
if(strstr(buf,bios_key))
{
LOG_INFO("bios key found");
return 0;
}
}
else
{
break;
}
}
return -1;
}
int SetSndPort(int n)
{
FILE *fp = NULL;
char buf[128] = {0};
char c = n+48;
int f=0;
if((fp = fopen("/usr/share/alsa/alsa.conf","r+"))==NULL)
{
LOG_ERR("fopen err");
return -1;
}
while(1)
{
memset(buf,0,sizeof(buf));
if(fgets(buf,sizeof(buf),fp) != NULL)
{
if(strstr(buf,"defaults.pcm.device")!=NULL)
{
f=1;
break;
}
}
else
{
fclose(fp);
return -1;
}
}
fseek(fp, -2, SEEK_CUR);
fwrite(&c,1,1,fp);
fclose(fp);
return 0;
}
int GetSndPort(const char *eld)
{
FILE *fp;
char buf[128]={0};
char cmd[128]={0};
sprintf(cmd,"cat /proc/asound/card1/%s",eld);
fp = popen(cmd, "r");
if(NULL == fp)
{
LOG_ERR("popen error");
return 0;
}
if(fgets(buf, sizeof(buf), fp) != NULL)
{
if(buf[17] == '1')
{
LOG_INFO("hw:1,7");
SetSndPort(7);
}
else
{
LOG_INFO("hw:1,8");
SetSndPort(8);
}
}
return 0;
}
int getxrandr(const char* find_str)
{
FILE *fp;
char buf[128]={0};
char *result;
fp = popen("xrandr", "r");
if(NULL == fp)
{
LOG_ERR("popen error");
return 0;
}
while(1)
{
if(fgets(buf, sizeof(buf), fp) != NULL)
{
result = strstr(buf,find_str);
if (result == NULL)
{
continue;
}
else
{
pclose(fp);
return 1;
}
}
else
break;
}
pclose(fp);
return 0;
}
void InitResolution()
{
char cmd[128]={0};
ReadConfStr("resolution",gSysData.set_resolution);
sprintf(cmd,"xrandr -s %s",gSysData.set_resolution);
SystemEx(cmd);
}
int SetXrandr(GLbyte res,int *width, int *height)
{
char cmd[128]={0};
*width = wxrandr[res];
*height = hxrandr[res];
if (!getxrandr(str_xrandr[res]))
{
LOG_ERR("no res found");
return 0;
}
sprintf(cmd,"xrandr -s %s",str_xrandr[res]);
LOG_INFO("set xrandr:%s",cmd);
SystemEx(cmd);
memcpy(gSysData.set_resolution,str_xrandr[res],sizeof(str_xrandr[res])+1);
WriteConfStr("resolution",gSysData.set_resolution);
execl("/bin/sh","sh","-c",STEAMUI_PATH,(char*)0);
return 1;
}
void WriteLog(const char* string)
{
FILE *log_fp;
struct stat statbuf;
char run_file[60] = RUN_PATH;
stat(run_file,&statbuf);
if (statbuf.st_size <1024*1024*20)
{
log_fp = fopen(run_file,"at+");
if(log_fp!= NULL)
{
fwrite(string,1,strlen(string),log_fp);
}
fclose(log_fp);
}
else
{
log_fp = fopen(run_file,"at+");
if(log_fp!= NULL)
{
int fd = fileno(log_fp);
ftruncate(fd,0);
}
fclose(log_fp);
}
}
void GetTimeNow(char *time_str)
{
time_t tm;
struct tm *ptm;
time(&tm);
ptm=localtime(&tm);
sprintf(time_str,"%04d%02d%02d-%02d%02d%02d",1900+ptm->tm_year,1+ptm->tm_mon,ptm->tm_mday,
ptm->tm_hour,ptm->tm_min,ptm->tm_sec);
}
void Log(PRIN_TYPE type,const char* file,const char* func, int line,const char* format,...)
{
char log_str[128] = {0};
char log[256] = {0};
va_list va;
va_start(va, format);
vsnprintf(log_str,128,format,va);
va_end(va);
sprintf(log,"%s %s %d %s\n",file,func,line,log_str);
printf(log);
if(type == L_ERR | type == L_INFO)
{
char tm_str[16] = {0};
GetTimeNow(tm_str);
WriteLog(tm_str);
WriteLog(log);
}
}
| [
"noreply@github.com"
] | Jou1703.noreply@github.com |
631cd6165f84d2c99f110720b9209d7835551828 | 917f134cbfff5f7dcb8bf1c7c332f647a11f6b4d | /include/ParticleSystem.h | ee8c9c483e339a179a3f527378fa1557e5e5aed3 | [] | no_license | izayacity/ParticleSystems | cc9fad29e8e6c26bc0667692cfeb5bfbafde10ff | c643ddc6447232af8bd3f79daaaa6cdb54818cac | refs/heads/master | 2021-06-20T08:28:13.087822 | 2017-07-14T13:54:01 | 2017-07-14T13:54:01 | 87,395,953 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,686 | h | #pragma once
#include <SFML/Graphics.hpp>
#include <cassert>
#include <vector>
#include <memory>
#include <iostream>
#include "Particle.h"
#include "Repeller.h"
class ParticleSystem : public sf::Drawable, public sf::Transformable {
private:
std::vector<ParticlePtr> m_particles;
std::map<int, sf::Texture> tex_map;
// default initial count of particles
const int COUNT = 100;
// count of particles
unsigned int m_count;
// gravity
float m_gravity;
// emit angle
unsigned int m_emitAngle;
// emit start angel
float m_emitStart;
// min speed
float m_speed;
// radius/size of particle/sprite
float m_size;
// Life time of particles
sf::Time m_lifetime;
// Emitter position
sf::Vector2f m_emitter;
// render states to load texture
sf::Texture m_texture;
// pixel width of texture image
float t_width;
// pixel height of texture image
float t_height;
// Move the particle after respawning each time by the initial velocity and angle
void resetParticle (ParticlePtr particle) {
// give a random velocity and lifetime to the particle
float angle = (std::rand () % m_emitAngle) * 3.14f / 180.f + m_emitStart;
float speed = (std::rand () % 50) + m_speed;
particle->velocity = sf::Vector2f (std::cos (angle) * speed, std::sin (angle) * speed);
particle->lifetime = sf::milliseconds ((std::rand () % (m_lifetime.asMilliseconds () / 2)) + m_lifetime.asMilliseconds () / 2);
particle->history.resize (0);
// reset the position of the corresponding vertex
particle->vertices[0].position = m_emitter;
particle->vertices[1].position = m_emitter + sf::Vector2f (-m_size, -m_size);
particle->vertices[2].position = m_emitter + sf::Vector2f (m_size, -m_size);
particle->vertices[3].position = m_emitter + sf::Vector2f (-m_size, m_size);
particle->vertices[4].position = m_emitter + sf::Vector2f (m_size, m_size);
}
// initialize texture of a particle
void initTex (ParticlePtr p) {
p->vertices.setPrimitiveType (sf::PrimitiveType::Quads);
p->vertices.resize (5);
p->vertices[1].texCoords = sf::Vector2f (0, 0);
p->vertices[2].texCoords = sf::Vector2f (t_width, 0);
p->vertices[3].texCoords = sf::Vector2f (t_width, t_height);
p->vertices[4].texCoords = sf::Vector2f (0, t_height);
}
// Apply the transform and draw the vertext array
virtual void draw (sf::RenderTarget& target, sf::RenderStates states) const {
states.transform *= getTransform ();
states.texture = NULL;
for (auto p : m_particles) {
target.draw (p->vertices, &m_texture);
target.draw (p->history, states);
}
}
public:
ParticleSystem () :
m_lifetime (sf::seconds (3)),
m_emitter (0, 0),
m_count (COUNT),
m_gravity (0.f),
m_emitAngle (360),
m_emitStart (0.f),
m_speed (50.f),
m_size (0.f) {
}
~ParticleSystem () {
m_particles.clear ();
}
// Set the max life time of the particles
void setLifetime (float lifetime) {
m_lifetime = sf::seconds (lifetime);
}
// Set the location of the emitter
void setEmitter (sf::Vector2f position) {
m_emitter = position;
}
// Set the gravity of particles
void setGravity (float gravity) {
m_gravity = gravity;
}
// Set the emit start angle of particles
void setEmitStart (float emitStart) {
m_emitStart = emitStart;
}
// Set the range of emit angle of particles
void setEmitAngle (int emitAngle) {
m_emitAngle = emitAngle;
}
// Set the min speed of particles
void setSpeed (float speed) {
m_speed = speed;
}
// Set particle/sprite size
void setSize (float size) {
m_size = size;
}
// Update the lifetime, position, color, etc of the particles
void update (sf::Time elapsed) {
for (auto p : m_particles) {
p->lifetime -= elapsed;
// if the particle is dead, respawn it
if (p->lifetime <= sf::Time::Zero) {
resetParticle (p);
return;
}
// store the history positions and life time of a particle
float prevVelocity = p->velocity.y;
sf::Vertex *vertex = new sf::Vertex ();
vertex->color = sf::Color::Color (std::rand () % 255, std::rand () % 255, std::rand () % 255, std::rand () % 255);
vertex->position = p->vertices[0].position;
p->history.append (*vertex);
p->h_time.push_back (p->lifetime);
// update the position of the corresponding vertex
p->velocity.y += m_gravity * elapsed.asSeconds ();
p->vertices[0].position.x += p->velocity.x * elapsed.asSeconds ();
p->vertices[0].position.y += (p->velocity.y + prevVelocity) / 2 * elapsed.asSeconds ();
// update surrending vertices of shape
sf::Vector2f m_pos = p->vertices[0].position;
p->vertices[1].position = m_pos + sf::Vector2f (-m_size, -m_size);
p->vertices[2].position = m_pos + sf::Vector2f (m_size, -m_size);
p->vertices[3].position = m_pos + sf::Vector2f (-m_size, m_size);
p->vertices[4].position = m_pos + sf::Vector2f (m_size, m_size);
}
}
// get the count of particles
int getCount () {
return m_count;
}
// get the emitter positin of particles
sf::Vector2f getEmitter () {
return m_emitter;
}
// add the count of particles by 100 each time
void addCount () {
int diff = 100;
if (m_count >= UINT_MAX - 1) {
diff = 0;
} else if (m_count + 100 >= UINT_MAX) {
diff = UINT_MAX - 1 - m_count;
}
// update particles and vertice
while (diff > 0) {
ParticlePtr particle = new Particle ();
if (particle != nullptr) {
initTex (particle);
resetParticle (ParticlePtr(particle));
m_particles.push_back (ParticlePtr (particle));
m_count++;
diff--;
} else {
throw std::runtime_error ("Failed to add particle");
}
}
}
// reduce the count of particles by 100 each time
void reduceCount () {
int diff = 100;
if (m_count <= 0) {
diff = 0;
} else if (m_count - 100 <= 0) {
diff = m_count;
}
// update particles and vertice
m_particles.resize (m_count - diff);
m_count = m_particles.size ();
}
// initialize texture map and build the sprite/quad vertices around the particle
void init (int id) {
sf::Texture temp;
assert (temp.loadFromFile ("static/image/smokeparticle.png"));
tex_map[1] = temp;
assert (temp.loadFromFile ("static/image/dollar.png"));
tex_map[2] = temp;
m_texture = tex_map[id];
m_texture.setSmooth (true);
t_width = m_texture.getSize ().x + 0.f;
t_height = m_texture.getSize ().y + 0.f;
for (int i = 0; i < m_count; ++i) {
ParticlePtr particle = new Particle ();
m_particles.push_back (ParticlePtr(particle));
initTex (particle);
}
}
// apply force to particles
void applyRepeller (Repeller repeller, sf::Time elapsed) {
for (auto p : m_particles) {
sf::Vector2f force = repeller.repel (p);
p->velocity += force * elapsed.asSeconds ();
}
}
}; | [
"xyang42@ucsc.edu"
] | xyang42@ucsc.edu |
41b3b8ec7eee28ecd63bc8889e7224004d490851 | 9ad1a00cec16ad7f51b2eaf854662a1a69835d57 | /xmt_zlib.c++ | d6a2b06fbaebd763cf7f422794fea0153b15cfad | [] | no_license | sterink/e-mag-reader | 182a3024257cfbbd2ca29f975a159ad034923016 | 3ab8717639a608fccec027c0a31cb50c19b8a295 | refs/heads/master | 2020-12-24T13:28:05.813645 | 2011-03-23T08:14:13 | 2011-03-23T08:14:13 | 1,420,162 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,132 | /*
Version 1.1, February 14h, 2010
sample part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications of Unzip for Zip64
Copyright (C) 2007-2008 Even Rouault
Modifications for Zip64 support on both zip and unzip
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
*/
#ifndef _WIN32
#ifndef __USE_FILE_OFFSET64
#define __USE_FILE_OFFSET64
#endif
#ifndef __USE_LARGEFILE64
#define __USE_LARGEFILE64
#endif
#ifndef _LARGEFILE64_SOURCE
#define _LARGEFILE64_SOURCE
#endif
#ifndef _FILE_OFFSET_BIT
#define _FILE_OFFSET_BIT 64
#endif
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
# include <unistd.h>
# include <utime.h>
# include <sys/stat.h>
#include "unzip.h"
#define WRITEBUFFERSIZE (8192)
/* change_file_date : change the date/time of a file
filename : the filename of the file where date/time must be modified
dosdate : the new date at the MSDos format (4 bytes)
tmu_date : the SAME new date at the tm_unz format */
static void change_file_date(const char *filename, uLong dosdate, tm_unz tmu_date)
{
struct utimbuf ut;
struct tm newdate;
newdate.tm_sec = tmu_date.tm_sec;
newdate.tm_min=tmu_date.tm_min;
newdate.tm_hour=tmu_date.tm_hour;
newdate.tm_mday=tmu_date.tm_mday;
newdate.tm_mon=tmu_date.tm_mon;
if (tmu_date.tm_year > 1900)
newdate.tm_year=tmu_date.tm_year - 1900;
else
newdate.tm_year=tmu_date.tm_year ;
newdate.tm_isdst=-1;
ut.actime=ut.modtime=mktime(&newdate);
utime(filename,&ut);
}
static int makedir (const char *newdir)
{
char *buffer ;
char *p;
int len = (int)strlen(newdir);
if (len <= 0)
return 0;
buffer = (char*)malloc(len+1);
if (buffer==NULL)
{
printf("Error allocating memory\n");
return UNZ_INTERNALERROR;
}
strcpy(buffer,newdir);
if (buffer[len-1] == '/') {
buffer[len-1] = '\0';
}
if (mkdir(buffer, 0775) == 0)
{
free(buffer);
return 1;
}
p = buffer+1;
while (1)
{
char hold;
while(*p && *p != '\\' && *p != '/')
p++;
hold = *p;
*p = 0;
if ((mkdir(buffer, 0775) == -1) && (errno == ENOENT))
{
printf("couldn't create directory %s\n",buffer);
free(buffer);
return 0;
}
if (hold == 0)
break;
*p++ = hold;
}
free(buffer);
return 1;
}
static int do_extract_currentfile(unzFile uf, const int* popt_extract_without_path, int* popt_overwrite, const char* password)
{
char filename_inzip[256];
char* filename_withoutpath;
char* p;
int err=UNZ_OK;
FILE *fout=NULL;
void* buf;
uInt size_buf;
unz_file_info64 file_info;
uLong ratio=0;
err = unzGetCurrentFileInfo64(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzGetCurrentFileInfo\n",err);
return err;
}
size_buf = WRITEBUFFERSIZE;
buf = (void*)malloc(size_buf);
if (buf==NULL)
{
printf("Error allocating memory\n");
return UNZ_INTERNALERROR;
}
p = filename_withoutpath = filename_inzip;
while ((*p) != '\0')
{
if (((*p)=='/') || ((*p)=='\\'))
filename_withoutpath = p+1;
p++;
}
if ((*filename_withoutpath)=='\0')
{
if ((*popt_extract_without_path)==0)
{
printf("creating directory: %s\n",filename_inzip);
mkdir(filename_inzip, 0775);
}
}
else
{
const char* write_filename;
int skip=0;
if ((*popt_extract_without_path)==0)
write_filename = filename_inzip;
else
write_filename = filename_withoutpath;
err = unzOpenCurrentFilePassword(uf,password);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzOpenCurrentFilePassword\n",err);
}
if (((*popt_overwrite)==0) && (err==UNZ_OK))
{
char rep=0;
FILE* ftestexist;
ftestexist = fopen64(write_filename,"rb");
if (ftestexist!=NULL)
{
fclose(ftestexist);
do
{
char answer[128];
int ret;
printf("The file %s exists. Overwrite ? [y]es, [n]o, [A]ll: ",write_filename);
ret = scanf("%1s",answer);
if (ret != 1)
{
exit(EXIT_FAILURE);
}
rep = answer[0] ;
if ((rep>='a') && (rep<='z'))
rep -= 0x20;
}
while ((rep!='Y') && (rep!='N') && (rep!='A'));
}
if (rep == 'N')
skip = 1;
if (rep == 'A')
*popt_overwrite=1;
}
if ((skip==0) && (err==UNZ_OK))
{
fout=fopen64(write_filename,"wb");
/* some zipfile don't contain directory alone before file */
if ((fout==NULL) && ((*popt_extract_without_path)==0) &&
(filename_withoutpath!=(char*)filename_inzip))
{
char c=*(filename_withoutpath-1);
*(filename_withoutpath-1)='\0';
makedir(write_filename);
*(filename_withoutpath-1)=c;
fout=fopen64(write_filename,"wb");
}
if (fout==NULL)
{
printf("error opening %s\n",write_filename);
}
}
if (fout!=NULL)
{
printf(" extracting: %s\n",write_filename);
do
{
err = unzReadCurrentFile(uf,buf,size_buf);
if (err<0)
{
printf("error %d with zipfile in unzReadCurrentFile\n",err);
break;
}
if (err>0)
if (fwrite(buf,err,1,fout)!=1)
{
printf("error in writing extracted file\n");
err=UNZ_ERRNO;
break;
}
}
while (err>0);
if (fout)
fclose(fout);
if (err==0)
change_file_date(write_filename,file_info.dosDate,
file_info.tmu_date);
}
if (err==UNZ_OK)
{
err = unzCloseCurrentFile (uf);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzCloseCurrentFile\n",err);
}
}
else
unzCloseCurrentFile(uf); /* don't lose the error */
}
free(buf);
return err;
}
static int do_extract(unzFile uf, int opt_extract_without_path, int opt_overwrite, const char* password)
{
uLong i;
unz_global_info64 gi;
int err;
FILE* fout=NULL;
err = unzGetGlobalInfo64(uf,&gi);
if (err!=UNZ_OK)
printf("error %d with zipfile in unzGetGlobalInfo \n",err);
for (i=0;i<gi.number_entry;i++)
{
if (do_extract_currentfile(uf,&opt_extract_without_path,
&opt_overwrite,
password) != UNZ_OK)
break;
if ((i+1)<gi.number_entry)
{
err = unzGoToNextFile(uf);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzGoToNextFile\n",err);
break;
}
}
}
return 0;
}
int my_zip_extract(const char *zipfilename, const char *passwd){
int i;
int ret_value=0;
int opt_do_extract_withoutpath=0;
int opt_overwrite=1;
unzFile uf=NULL;
uf = unzOpen64(zipfilename);
ret_value = do_extract(uf, opt_do_extract_withoutpath, opt_overwrite, passwd);
unzClose(uf);
return ret_value;
}
| [
"yaothinker@hotmail.com"
] | yaothinker@hotmail.com | |
1229b39a5830f3fc3531beec5b591e2495897c2a | 68e8f6bf9ea4f5c2b1e5c99b61911b69c546db60 | /include/RE/BSTCaseInsensitiveStringMap.h | 6871cfdcd004a40d3d123d3d4aec2f3f09301562 | [
"MIT"
] | permissive | FruitsBerriesMelons123/CommonLibSSE | aaa2d4cd66d39f7cb4d25f076735ef4b0187353e | 7ae21d11b9e9c86b0596fc1cfa58b6993a568125 | refs/heads/master | 2021-01-16T12:36:20.612433 | 2020-02-25T09:58:05 | 2020-02-25T09:58:05 | 243,124,317 | 0 | 0 | MIT | 2020-02-25T23:24:47 | 2020-02-25T23:24:47 | null | UTF-8 | C++ | false | false | 481 | h | #pragma once
#include "RE/NiTStringMap.h"
namespace RE
{
// 28
template <class T>
class BSTCaseInsensitiveStringMap : public NiTStringMap<T>
{
private:
using base = NiTStringMap<T>;
public:
using key_type = base::key_type;
virtual ~BSTCaseInsensitiveStringMap(); // 00
// override (NiTStringMap<T>)
virtual UInt32 hash_function(key_type a_key) const override; // 01
virtual bool key_eq(key_type a_lhs, key_type a_rhs) const override; // 02
};
}
| [
"ryan__mckenzie@hotmail.com"
] | ryan__mckenzie@hotmail.com |
599971918609dac19f5b56d6a7acc9b5ccda89a7 | 09711d09c5945acd3d0ff8282f56217d0d5c4758 | /samples/Matrix.h | 21366cb81a965cbdce35a88de5904612928ae2e6 | [] | no_license | tiger1013/Translator | eff464e47bb2c0b4721727ae6d0be0e928cc8155 | 44da460df90a4dc1a24d451df4e08bcdc6347097 | refs/heads/master | 2020-12-24T05:50:03.422646 | 2016-11-11T05:21:41 | 2016-11-11T05:21:41 | 73,447,082 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 783 | h | #ifndef MATRIX_H
#define MATRIX_H
#include <stdlib.h>
#include <iostream>
#include <fstream>
class matrix {
public:
matrix(int _rows, int _cols) ;
matrix (const matrix& m) ;
int numRows ( ) ;
int numCols ( ) ;
float *access(const int i, const int j) const ;
friend std::ostream& operator<<(std::ostream &os, matrix &m) ;
static matrix matrixRead ( std::string filename ) ;
private:
matrix() { }
int rows ;
int cols ;
/* Your implementation of "data" may vary. There are ways in
which data can be an array of arrays and thus simplify the
access method, at the cost of complicating the process of
allocating space for data. The choice is entirely up to
you. */
float **data ;
} ;
#endif // MATRIX_H
| [
"tiger12055@gmail.com"
] | tiger12055@gmail.com |
6fbac2b563c5c52f08f64431c6261fd9e6e044f2 | 51c53c52531821168af4bc3e2ce0db03f6796754 | /Algorithm-CPP/Q43-BinarySearchTreeFromSortedArray.h | 979d9378edd40f4c9372e4e5027b9b83fb320d22 | [] | no_license | arvi0312/Algorithm-Linux | 46b3571e047f55b27ac8eadcc48bf4f6380c39bb | 3c04148389fc0c7e39a9165fbd8d0304957aecf4 | refs/heads/master | 2021-01-01T08:13:15.940864 | 2017-01-12T22:44:13 | 2017-01-12T22:44:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 592 | h | //
// Q43-BinarySearchTreeFromSortedArray.h
// Algorithm-Linux
//
// Created by Sanqiang Zhao on 12/11/12.
// Copyright (c) 2012 Sanqiang Zhao. All rights reserved.
//
#ifndef __Algorithm_Linux__Q43_BinarySearchTreeFromSortedArray__
#define __Algorithm_Linux__Q43_BinarySearchTreeFromSortedArray__
#include <iostream>
#include "Entity.h"
BinaryTreeNode<int> * buildBinarySearchTreeFromSortedArray(int arr[], int length);
BinaryTreeNode<int> * buildBinarySearchTreeFromSortedArray(int arr[], int s, int e);
#endif
/* defined(__Algorithm_Linux__Q43_BinarySearchTreeFromSortedArray__) */
| [
"zhaosanqiang916@gmail.com"
] | zhaosanqiang916@gmail.com |
3c5d2ed775d93e516b5eb9d7bb94c513382316a4 | 1ff1943949855c2b878fad442acb189ce84c1b95 | /llvm-3.7.0.src/lib/Target/LEG/LEGISelDAGToDAG.cpp | deeea06155d52164262eb6d96487048d63045fbc | [
"NCSA"
] | permissive | kumailxp/tricore_llvm | 2291de9b13ba8cce7ac7c85950b2b268c39c2998 | e3c3cd5785538190c1d9a61f7c692c7008822628 | refs/heads/master | 2021-01-21T13:49:36.782121 | 2016-05-17T06:43:44 | 2016-05-17T06:43:44 | 43,948,618 | 11 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,716 | cpp | //===-- LEGISelDAGToDAG.cpp - A dag to dag inst selector for LEG ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines an instruction selector for the LEG target.
//
//===----------------------------------------------------------------------===//
#include "LEG.h"
#include "LEGTargetMachine.h"
#include "llvm/CodeGen/SelectionDAGISel.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "LEGInstrInfo.h"
using namespace llvm;
/// LEGDAGToDAGISel - LEG specific code to select LEG machine
/// instructions for SelectionDAG operations.
///
namespace {
class LEGDAGToDAGISel : public SelectionDAGISel {
const LEGSubtarget &Subtarget;
public:
explicit LEGDAGToDAGISel(LEGTargetMachine &TM, CodeGenOpt::Level OptLevel)
: SelectionDAGISel(TM, OptLevel), Subtarget(*TM.getSubtargetImpl()) {}
SDNode *Select(SDNode *N);
bool SelectAddr(SDValue Addr, SDValue &Base, SDValue &Offset);
virtual const char *getPassName() const {
return "LEG DAG->DAG Pattern Instruction Selection";
}
private:
SDNode *SelectMoveImmediate(SDNode *N);
SDNode *SelectConditionalBranch(SDNode *N);
SDNode *SelectConditionalBranchForTriCore(SDNode *N);
// Include the pieces autogenerated from the target description.
#include "LEGGenDAGISel.inc"
};
} // end anonymous namespace
bool LEGDAGToDAGISel::SelectAddr(SDValue Addr, SDValue &Base, SDValue &Offset) {
if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
EVT PtrVT = getTargetLowering()->getPointerTy(*TM.getDataLayout());
Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), PtrVT);
Offset = CurDAG->getTargetConstant(0, Addr, MVT::i32);
return true;
}
if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
Addr.getOpcode() == ISD::TargetGlobalAddress ||
Addr.getOpcode() == ISD::TargetGlobalTLSAddress) {
return false; // direct calls.
}
Base = Addr;
Offset = CurDAG->getTargetConstant(0, Addr, MVT::i32);
return true;
}
SDNode *LEGDAGToDAGISel::SelectMoveImmediate(SDNode *N) {
// Make sure the immediate size is supported.
ConstantSDNode *ConstVal = cast<ConstantSDNode>(N);
uint64_t ImmVal = ConstVal->getZExtValue();
//outs() <<"ImmVal: "<< ImmVal << "\n.";
uint64_t SupportedMask = 0xfffffffff;
if ((ImmVal & SupportedMask) != ImmVal) {
outs() <<" LEG : Immediate size not supported!\n";
return SelectCode(N);
}
// Select the low part of the immediate move.
uint64_t LoMask = 0xffff;
uint64_t HiMask = 0xffff0000;
uint64_t ImmLo = (ImmVal & LoMask);
uint64_t ImmHi = (ImmVal & HiMask);
SDValue ConstLo = CurDAG->getTargetConstant(ImmLo, N, MVT::i32);
MachineSDNode *Move =
CurDAG->getMachineNode(LEG::MOVLOi16, N, MVT::i32, ConstLo);
// Select the low part of the immediate move, if needed.
if (ImmHi) {
SDValue ConstHi = CurDAG->getTargetConstant(ImmHi >> 16, N, MVT::i32);
Move = CurDAG->getMachineNode(LEG::MOVHIi16, N, MVT::i32, SDValue(Move, 0),
ConstHi);
}
return Move;
}
static StringRef printCondCode(ISD::CondCode e) {
switch(e){
default: return "unknown";
case ISD::SETEQ: return "SETEQ";
case ISD::SETGT: return "SETGT";
case ISD::SETGE: return "SETGE";
case ISD::SETLT: return "SETLT";
case ISD::SETLE: return "SETLE";
case ISD::SETNE: return "SETNE";
case ISD::SETTRUE2: return "SETTRUE2";
}
}
SDNode *LEGDAGToDAGISel::SelectConditionalBranch(SDNode *N) {
//return SelectConditionalBranchForTriCore(N);
SDValue Chain = N->getOperand(0);
SDValue Cond = N->getOperand(1);
SDValue LHS = N->getOperand(2);
SDValue RHS = N->getOperand(3);
SDValue Target = N->getOperand(4);
// Generate a comparison instruction.
EVT CompareTys[] = { MVT::Other, MVT::Glue };
//EVT CompareTys[] = { MVT::Other };
SDVTList CompareVT = CurDAG->getVTList(CompareTys);
SDValue CompareOps[] = {LHS, RHS, Chain};
SDNode *Compare = CurDAG->getMachineNode(LEG::CMP, N, CompareVT, CompareOps);
//SDNode *Compare = CurDAG->getMachineNode(LEG::CMP, N, MVT::Glue, LHS, RHS, Chain);
// Generate a predicated branch instruction.
CondCodeSDNode *CC = cast<CondCodeSDNode>(Cond.getNode());
SDValue CCVal = CurDAG->getTargetConstant(CC->get(), N, MVT::i32);
SDValue BranchOps[] = {CCVal, Target, SDValue(Compare, 0),
SDValue(Compare, 1)};
MachineSDNode *branchInst = CurDAG->getMachineNode(LEG::Bcc, N, MVT::Other, BranchOps);
return branchInst;
}
SDNode *LEGDAGToDAGISel::Select(SDNode *N) {
SDLoc dl(N);
switch (N->getOpcode()) {
case ISD::Constant:
return SelectMoveImmediate(N);
case ISD::BR_CC:
return SelectConditionalBranch(N);
case ISD::FrameIndex: {
outs() <<"N getNumValues: "<< N->getNumValues()<< "\n";
outs() <<"N type: "<< N->getValueType(0).getEVTString()<< "\n";
int FI = cast<FrameIndexSDNode>(N)->getIndex();
SDValue TFI = CurDAG->getTargetFrameIndex(FI, MVT::i32);
return CurDAG->getMachineNode(LEG::ADDri, dl, MVT::i32, TFI,
CurDAG->getTargetConstant(0, dl, MVT::i32));
}
}
return SelectCode(N);
}
/// createLEGISelDag - This pass converts a legalized DAG into a
/// LEG-specific DAG, ready for instruction scheduling.
///
FunctionPass *llvm::createLEGISelDag(LEGTargetMachine &TM,
CodeGenOpt::Level OptLevel) {
return new LEGDAGToDAGISel(TM, OptLevel);
}
| [
"kumail89@gmail.com"
] | kumail89@gmail.com |
c2b2a4c26d7c29e9d8a255fa31afdfa96e38020e | 967e44c33fc3765197b602a5492c39d399830868 | /lib/tagged_burst_to_pdu_impl.cc | bfae3f293aa66895ccea756666d050f91a786b61 | [] | no_license | learning-lte/gr-iridium | 90f873b75f9e5e8c901ad1d4a9bca58623b26e8c | eeaf8157dd78d5394bd7feefa3a1a5dd67af8037 | refs/heads/master | 2020-12-09T07:26:09.663430 | 2019-07-22T09:03:31 | 2019-07-22T09:03:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,685 | cc | /* -*- c++ -*- */
/*
* Copyright 2016 Free Software Foundation, Inc
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <gnuradio/io_signature.h>
#include "tagged_burst_to_pdu_impl.h"
#include <unistd.h>
#include <inttypes.h>
namespace gr {
namespace iridium {
tagged_burst_to_pdu::sptr
tagged_burst_to_pdu::make(int max_burst_size, float relative_center_frequency, float relative_span,
float d_relative_sample_rate, int outstanding_limit, bool drop_overflow)
{
return gnuradio::get_initial_sptr
(new tagged_burst_to_pdu_impl(max_burst_size, relative_center_frequency, relative_span,
d_relative_sample_rate, outstanding_limit, drop_overflow));
}
/*
* The private constructor
*/
tagged_burst_to_pdu_impl::tagged_burst_to_pdu_impl(int max_burst_size, float relative_center_frequency, float relative_span,
float d_relative_sample_rate, int outstanding_limit, bool drop_overflow)
: gr::sync_block("tagged_burst_to_pdu",
gr::io_signature::make(1, 1, sizeof(gr_complex)),
gr::io_signature::make(0, 0, 0)),
d_debug(false),
d_relative_center_frequency(relative_center_frequency),
d_relative_span(relative_span),
d_relative_sample_rate(d_relative_sample_rate),
d_max_burst_size(max_burst_size),
d_outstanding(0),
d_max_outstanding(0),
d_outstanding_limit(outstanding_limit),
d_n_dropped_bursts(0),
d_drop_overflow(drop_overflow),
d_blocked(false)
{
d_lower_border = relative_center_frequency - relative_span / 2;
d_upper_border = relative_center_frequency + relative_span / 2;
message_port_register_out(pmt::mp("cpdus"));
message_port_register_in(pmt::mp("burst_handled"));
set_msg_handler(pmt::mp("burst_handled"), boost::bind(&tagged_burst_to_pdu_impl::burst_handled, this, _1));
}
/*
* Our virtual destructor.
*/
tagged_burst_to_pdu_impl::~tagged_burst_to_pdu_impl()
{
}
void
tagged_burst_to_pdu_impl::burst_handled(pmt::pmt_t msg)
{
d_outstanding--;
}
void
tagged_burst_to_pdu_impl::append_to_burst(burst_data &burst, const gr_complex * data, size_t n)
{
// If the burst really gets longer than this, we can just throw away the data
if(burst.len + n <= d_max_burst_size) {
memcpy(burst.data + burst.len, data, n * sizeof(gr_complex));
burst.len += n;
}
}
void
tagged_burst_to_pdu_impl::publish_burst(burst_data &burst)
{
pmt::pmt_t d_pdu_meta = pmt::make_dict();
pmt::pmt_t d_pdu_vector = pmt::init_c32vector(burst.len, burst.data);
d_pdu_meta = pmt::dict_add(d_pdu_meta, pmt::mp("id"), pmt::mp(burst.id));
d_pdu_meta = pmt::dict_add(d_pdu_meta, pmt::mp("offset"), pmt::mp(burst.offset));
d_pdu_meta = pmt::dict_add(d_pdu_meta, pmt::mp("magnitude"), pmt::mp(burst.magnitude));
d_pdu_meta = pmt::dict_add(d_pdu_meta, pmt::mp("relative_frequency"), pmt::mp(burst.relative_frequency));
d_pdu_meta = pmt::dict_add(d_pdu_meta, pmt::mp("center_frequency"), pmt::mp(burst.center_frequency));
d_pdu_meta = pmt::dict_add(d_pdu_meta, pmt::mp("sample_rate"), pmt::mp(burst.sample_rate));
pmt::pmt_t msg = pmt::cons(d_pdu_meta,
d_pdu_vector);
d_outstanding++;
if(d_outstanding >= d_outstanding_limit) {
d_blocked = true;
}
if(d_outstanding > d_max_outstanding) {
d_max_outstanding = d_outstanding;
}
message_port_pub(pmt::mp("cpdus"), msg);
}
void
tagged_burst_to_pdu_impl::create_new_bursts(int noutput_items,
const gr_complex * in)
{
std::vector<tag_t> new_bursts;
get_tags_in_window(new_bursts, 0, 0, noutput_items, pmt::mp("new_burst"));
for(tag_t tag : new_bursts) {
float relative_frequency = pmt::to_float(pmt::dict_ref(tag.value, pmt::mp("relative_frequency"), pmt::PMT_NIL));
if(d_lower_border < relative_frequency && relative_frequency <= d_upper_border) {
uint64_t id = pmt::to_uint64(pmt::dict_ref(tag.value, pmt::mp("id"), pmt::PMT_NIL));
float magnitude = pmt::to_float(pmt::dict_ref(tag.value, pmt::mp("magnitude"), pmt::PMT_NIL));
float center_frequency = pmt::to_float(pmt::dict_ref(tag.value, pmt::mp("center_frequency"), pmt::PMT_NIL));
float sample_rate = pmt::to_float(pmt::dict_ref(tag.value, pmt::mp("sample_rate"), pmt::PMT_NIL));
float relative_frequency = pmt::to_float(pmt::dict_ref(tag.value, pmt::mp("relative_frequency"), pmt::PMT_NIL));
// Adjust the values based on our position behind a potential filter bank
center_frequency += d_relative_center_frequency * sample_rate;
sample_rate = sample_rate * d_relative_sample_rate;
relative_frequency = (relative_frequency - d_relative_center_frequency) / d_relative_sample_rate;
burst_data burst = {id, tag.offset, magnitude, relative_frequency,
center_frequency, sample_rate, 0};
burst.data = (gr_complex *) malloc(sizeof(gr_complex) * d_max_burst_size);
if(burst.data != NULL) {
d_bursts[id] = burst;
int relative_offset = burst.offset - nitems_read(0);
int to_copy = noutput_items - relative_offset;
append_to_burst(d_bursts[id], &in[relative_offset], to_copy);
if(d_debug) {
printf("New burst: offset=%" PRIu64 ", id=%" PRIu64 ", relative_frequency=%f, magnitude=%f\n", tag.offset, id, relative_frequency, magnitude);
}
} else {
printf("Error, malloc failed\n");
}
}
}
}
void
tagged_burst_to_pdu_impl::publish_and_remove_old_bursts(int noutput_items, const gr_complex * in)
{
std::vector<tag_t> gone_bursts;
get_tags_in_window(gone_bursts, 0, 0, noutput_items, pmt::mp("gone_burst"));
for(tag_t tag : gone_bursts) {
uint64_t id = pmt::to_uint64(pmt::dict_ref(tag.value, pmt::mp("id"), pmt::PMT_NIL));
if(d_bursts.count(id)) {
burst_data &burst = d_bursts[id];
int relative_offset = tag.offset - nitems_read(0);
append_to_burst(burst, in, relative_offset);
if(d_debug) {
printf("gone burst: %" PRIu64 " %zu\n", id, burst.len);
}
publish_burst(burst);
free(d_bursts[id].data);
d_bursts.erase(id);
}
}
}
void
tagged_burst_to_pdu_impl::update_current_bursts(int noutput_items, const gr_complex * in)
{
for(auto& kv : d_bursts) {
append_to_burst(kv.second, in, noutput_items);
}
}
uint64_t
tagged_burst_to_pdu_impl::get_n_dropped_bursts()
{
return d_n_dropped_bursts;
}
int
tagged_burst_to_pdu_impl::get_output_queue_size()
{
return d_outstanding;
}
int
tagged_burst_to_pdu_impl::get_output_max_queue_size()
{
int tmp = d_max_outstanding;
d_max_outstanding = 0;
return tmp;
}
int
tagged_burst_to_pdu_impl::work(int noutput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items)
{
const gr_complex *in = (const gr_complex *) input_items[0];
if(d_outstanding_limit && d_blocked && d_outstanding > d_outstanding_limit / 2) {
if(d_drop_overflow) {
uint64_t n_dropped_bursts = 0;
auto b = std::begin(d_bursts);
while (b != std::end(d_bursts)) {
n_dropped_bursts++;
free(b->second.data);
b = d_bursts.erase(b);
}
std::vector<tag_t> new_bursts;
get_tags_in_window(new_bursts, 0, 0, noutput_items, pmt::mp("new_burst"));
n_dropped_bursts += new_bursts.size();
//fprintf(stderr, "tagged_burst_to_pdu: Queue full. Dropped %d samples. Dropped %" PRIu64 " bursts.\n", noutput_items, n_dropped_bursts);
if(n_dropped_bursts) {
fprintf(stderr, "tagged_burst_to_pdu: Queue full. Dropped %" PRIu64 " bursts.\n", n_dropped_bursts);
}
d_n_dropped_bursts += n_dropped_bursts;
return noutput_items;
} else {
// Sleep a bit until our bursts have been processed
usleep(100000);
// Tell the scheduler that we have not consumed any input
return 0;
}
}
d_blocked = false;
publish_and_remove_old_bursts(noutput_items, in);
update_current_bursts(noutput_items, in);
create_new_bursts(noutput_items, in);
// Not sure if this makes sense in a sink block
return noutput_items;
}
} /* namespace iridium */
} /* namespace gr */
| [
"schneider@blinkenlichts.net"
] | schneider@blinkenlichts.net |
d8d0704c9db46500fe58c09ab66725d8277c4878 | 1f9af884b520fabc92807cb8aecd1d422be05b8d | /libraries/LowPower/LowPower.cpp | 694b23991b0bff94fcafe437fbf394b4f06d49d6 | [
"MIT"
] | permissive | 0hotpotman0/1.0.0 | c29a9bf12c62ea7a90caad401b5fab8669554cfc | 398a2864708fa42aa4bfb8d4ffab72960ed78b73 | refs/heads/main | 2023-04-02T11:20:26.980883 | 2021-04-15T11:12:12 | 2021-04-15T11:12:12 | 352,008,978 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,766 | cpp |
#include "LowPower.h"
void LowPower::begin(unsigned int inter_pin, voidFuncPtr callback, unsigned int pin_mode)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA | RCC_AHBPeriph_GPIOB | RCC_AHBPeriph_GPIOC |
RCC_AHBPeriph_GPIOD , ENABLE);
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
// GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_All;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_Init(GPIOC, &GPIO_InitStructure);
GPIO_Init(GPIOD, &GPIO_InitStructure);
// GPIO_Init(GPIOF, &GPIO_InitStructure);
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA |RCC_AHBPeriph_GPIOB | RCC_AHBPeriph_GPIOC |
RCC_AHBPeriph_GPIOD , DISABLE);
attachInterrupt(inter_pin, callback, pin_mode, INPUT_PULLUP);
}
void LowPower::standby(bool flag)
{
ADC_Cmd(ADC1, DISABLE);
PWR_EnterSTOPMode(PWR_Regulator_LowPower, PWR_STOPEntry_WFI);
// After wake-up from STOP reconfigure the system clock
if(flag)
{
// Enable HSE
RCC_HSEConfig(RCC_HSE_ON);
// Wait till HSE is ready
while(RCC_GetFlagStatus(RCC_FLAG_HSERDY) == RESET){}
}
else
{
// Enable HSI
RCC_HSICmd(ENABLE);
// Wait till HSI is ready
while(RCC_GetFlagStatus(RCC_FLAG_HSIRDY) == RESET){}
}
// Enable PLL
// RCC_PLLCmd(ENABLE);
// Wait till PLL is ready
// while(RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET){}
// Select PLL as system clock source
// RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
// Wait till PLL is used as system clock source
while(RCC_GetSYSCLKSource() != 0x08){}
// Enable ADC
ADC_Cmd(ADC1, ENABLE);
}
| [
"fenyishi0@gmail.com"
] | fenyishi0@gmail.com |
d9e3b36f51b00f736b8d9a677bea483ed91779a9 | e79481238227ea51b26cd0c5003d7e6cc14aa201 | /src/m2cr_sqp.cc | 48a34027243cb2a68af6488d4a7fa244571fcba6 | [] | no_license | cbpark/YAM2-analysis | 9d3733a8e0b9461954f0e923c3401a4809211846 | 5b7c27e08738cf6e8dfe18359533979ae0a226cc | refs/heads/master | 2022-12-10T13:06:39.931584 | 2020-07-31T02:28:58 | 2020-07-31T02:28:58 | 277,790,272 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,817 | cc | #include "blsystem.h"
#include "yam2.h"
#include <lhef/lhef.h>
#include <fstream>
#include <iomanip>
#include <iostream>
using std::cout;
const double MNU = 0.0;
const double MW = 80.379;
const double TOL = 1.0e-3;
void writeNullOutput(std::ofstream &outfile) {
outfile << std::setw(12) << std::setprecision(7) << -1.0 << '\t' << -1
<< '\n';
}
int main(int argc, char *argv[]) {
if (argc != 3) {
std::cerr << "Usage: m2cr_sqp.exe input output\n"
<< " - input: Input file in "
<< "Les Houches Event File format\n"
<< " - output: output file.\n";
return 1;
}
std::ifstream infile(argv[1]);
if (!infile) {
std::cerr << "-- Cannot open input file \"" << argv[1] << "\".\n";
return 1;
} else {
cout << "-- Processing \"" << argv[1] << "\" ...\n";
}
std::ofstream outfile(argv[2]);
outfile << "# M2, number of evals\n";
auto ev = lhef::parseEvent(&infile);
int num_eve = 0;
for (; !ev.empty(); ev = lhef::parseEvent(&infile), ++num_eve) {
// for (; num_eve < 10; ev = lhef::parseEvent(&infile), ++num_eve) {
const auto input = mkInputForBL(selectP(ev), MNU, MW);
if (!input) {
writeNullOutput(outfile);
continue;
}
// cout << input.value() << '\n';
auto m2sol = yam2::m2CRSQP(input.value(), TOL);
if (!m2sol || m2sol.value().m2() <= 0.0) {
writeNullOutput(outfile);
continue;
}
// cout << m2sol.value() << '\n';
outfile << std::setw(12) << std::setprecision(7) << m2sol.value().m2()
<< '\t' << m2sol.value().neval_objf() << '\n';
}
cout << "-- " << num_eve << " events processed.\n";
infile.close();
}
| [
"cbpark@gmail.com"
] | cbpark@gmail.com |
3832ef5c23aedd5c0c86ff684dcd817255e3f13c | 5d948c0126c0c4a24073d7f34c6aefd63adff8dc | /src/tlib/tapi32u8.cpp | d0d5a9d3a48c386841ea8a2e2023f0f6829155d3 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | j-dc/fastcopy | 3a520cf72a467b2109954fddef8f38ce61f49e0d | 7c2763b26ba69c4afc49fc721d1729f1e970f256 | refs/heads/master | 2020-05-05T02:28:30.695136 | 2019-04-05T10:36:02 | 2019-04-05T10:36:02 | 179,639,094 | 0 | 0 | null | 2019-04-05T07:43:58 | 2019-04-05T07:43:58 | null | SHIFT_JIS | C++ | false | false | 13,648 | cpp | static char *tap32u8_id =
"@(#)Copyright (C) 1996-2010 H.Shirouzu tap32u8.cpp Ver0.99";
/* ========================================================================
Project Name : Win32 Lightweight Class Library Test
Module Name : Application Frame Class
Create : 1996-06-01(Sat)
Update : 2010-05-09(Sun)
Copyright : H.Shirouzu
Reference :
======================================================================== */
#include "tlib.h"
#include "tapi32u8.h"
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
HWND CreateWindowU8(const char *class_name, const char *window_name, DWORD style,
int x, int y, int width, int height, HWND hParent, HMENU hMenu, HINSTANCE hInst, void *param)
{
Wstr class_name_w(class_name), window_name_w(window_name);
return ::CreateWindowW(class_name_w, window_name_w, style, x, y, width, height,
hParent, hMenu, hInst, param);
}
HWND FindWindowU8(const char *class_name, const char *window_name)
{
Wstr class_name_w(class_name), window_name_w(window_name);
return ::FindWindowW(class_name_w, window_name_w);
}
BOOL AppendMenuU8(HMENU hMenu, UINT flags, UINT idItem, const char *item_str)
{
Wstr item_str_w(item_str);
return ::AppendMenuW(hMenu, flags, idItem, item_str_w);
}
BOOL InsertMenuU8(HMENU hMenu, UINT idItem, UINT flags, UINT idNewItem, const char *item_str)
{
Wstr item_str_w(item_str);
return ::InsertMenuW(hMenu, idItem, flags, idNewItem, item_str_w);
}
BOOL ModifyMenuU8(HMENU hMenu, UINT idItem, UINT flags, UINT idNewItem, const char *item_str)
{
Wstr item_str_w(item_str);
return ::ModifyMenuW(hMenu, idItem, flags, idNewItem, item_str_w);
}
UINT DragQueryFileU8(HDROP hDrop, UINT iFile, char *buf, UINT cb)
{
Wstr wbuf(cb);
UINT ret = ::DragQueryFileW(hDrop, iFile, wbuf.Buf(), cb);
if (ret > 0 && buf) {
ret = WtoU8(wbuf, buf, cb);
}
return ret;
}
void WIN32_FIND_DATA_WtoU8(const WIN32_FIND_DATAW *fdat_w, WIN32_FIND_DATA_U8 *fdat_u8,
BOOL include_fname)
{
memcpy(fdat_u8, fdat_w, offsetof(WIN32_FIND_DATAW, cFileName));
if (include_fname) {
WtoU8(fdat_w->cFileName, fdat_u8->cFileName, sizeof(fdat_u8->cFileName));
WtoU8(fdat_w->cAlternateFileName, fdat_u8->cAlternateFileName,
sizeof(fdat_u8->cAlternateFileName));
}
}
HANDLE FindFirstFileU8(const char *path, WIN32_FIND_DATA_U8 *fdat)
{
Wstr wpath(path);
WIN32_FIND_DATAW fdat_w;
HANDLE ret;
if ((ret = ::FindFirstFileW(wpath, &fdat_w)) != INVALID_HANDLE_VALUE) {
WIN32_FIND_DATA_WtoU8(&fdat_w, fdat);
}
return ret;
}
BOOL FindNextFileU8(HANDLE hDir, WIN32_FIND_DATA_U8 *fdat)
{
WIN32_FIND_DATAW fdat_w;
BOOL ret;
if ((ret = ::FindNextFileW(hDir, &fdat_w))) {
WIN32_FIND_DATA_WtoU8(&fdat_w, fdat);
}
return ret;
}
HANDLE CreateFileU8(const char *path, DWORD access_flg, DWORD share_flg, SECURITY_ATTRIBUTES *sa,
DWORD create_flg, DWORD attr_flg, HANDLE hTemplate)
{
Wstr wpath(path);
return ::CreateFileW(wpath, access_flg, share_flg, sa, create_flg, attr_flg, hTemplate);
}
BOOL DeleteFileU8(const char *path)
{
Wstr wpath(path);
return ::DeleteFileW(wpath);
}
BOOL CreateDirectoryU8(const char *path, SECURITY_ATTRIBUTES *lsa)
{
Wstr wpath(path);
return ::CreateDirectoryW(wpath, lsa);
}
BOOL RemoveDirectoryU8(const char *path)
{
Wstr wpath(path);
return ::RemoveDirectoryW(wpath);
}
DWORD GetFullPathNameU8(const char *path, DWORD size, char *buf, char **fname)
{
Wstr wpath(path), wbuf(size);
WCHAR *wfname=NULL;
DWORD ret = ::GetFullPathNameW(wpath, size, wbuf.Buf(), &wfname);
if (ret == 0 || ret > size)
return ret;
int fname_len = wfname ? WtoU8(wfname, buf, size) : 0;
int path_len = WtoU8(wbuf, buf, size);
*fname = wfname ? (buf + path_len - fname_len) : NULL;
return ret;
}
DWORD GetFileAttributesU8(const char *path)
{
Wstr wpath(path);
return ::GetFileAttributesW(wpath);
}
BOOL SetFileAttributesU8(const char *path, DWORD attr)
{
Wstr wpath(path);
return ::SetFileAttributesW(wpath, attr);
}
HINSTANCE ShellExecuteU8(HWND hWnd, LPCSTR op, LPCSTR file, LPSTR params, LPCSTR dir, int nShow)
{
Wstr op_w(op), file_w(file), params_w(params), dir_w(dir);
return ::ShellExecuteW(hWnd, op_w, file_w, params_w, dir_w, nShow);
}
BOOL ShellExecuteExU8(SHELLEXECUTEINFO *info)
{
SHELLEXECUTEINFOW info_w;
memcpy(&info_w, info, sizeof(SHELLEXECUTEINFO));
Wstr verb_w(info->lpVerb), file_w(info->lpFile), param_w(info->lpParameters),
dir_w(info->lpDirectory), class_w(info->lpClass);
info_w.lpVerb = verb_w;
info_w.lpFile = file_w;
info_w.lpParameters = param_w;
info_w.lpDirectory = dir_w;
info_w.lpClass = class_w;
BOOL ret = ::ShellExecuteExW(&info_w);
info_w.lpFile = (WCHAR *)info->lpFile;
info_w.lpParameters = (WCHAR *)info->lpParameters;
info_w.lpDirectory = (WCHAR *)info->lpDirectory;
info_w.lpClass = (WCHAR *)info->lpClass;
memcpy(info, &info_w, sizeof(SHELLEXECUTEINFO));
return ret;
}
DWORD GetCurrentDirectoryU8(DWORD size, char *dir)
{
Wstr dir_w(size);
DWORD ret = ::GetCurrentDirectoryW(size, dir_w.Buf());
if (ret > 0) {
ret = WtoU8(dir_w, dir, size);
}
return ret;
}
DWORD GetWindowsDirectoryU8(char *dir, DWORD size)
{
Wstr dir_w(size);
DWORD ret = ::GetWindowsDirectoryW(dir_w.Buf(), size);
if (ret > 0) {
ret = WtoU8(dir_w, dir, size);
}
return ret;
}
BOOL SetCurrentDirectoryU8(char *dir)
{
Wstr dir_w(dir);
return ::SetCurrentDirectoryW(dir_w);
}
BOOL GetOpenFileNameU8Core(LPOPENFILENAME ofn, BOOL (WINAPI *ofn_func)(OPENFILENAMEW*))
{
OPENFILENAMEW ofn_w;
Wstr filter_w(MAX_PATH), cfilter_w(ofn->nMaxCustFilter),
file_w(ofn->nMaxFile), ftitle_w(ofn->nMaxFileTitle),
idir_w(MAX_PATH), title_w(MAX_PATH), defext_w(MAX_PATH), template_w(MAX_PATH);
memcpy(&ofn_w, ofn, sizeof(OPENFILENAME));
WCHAR *wp=filter_w.Buf();
for (const char *p=ofn->lpstrFilter; p && *p; p+=strlen(p)+1) {
wp += U8toW(p, wp, MAX_PATH);
}
*wp = 0;
U8toW(ofn->lpstrCustomFilter, cfilter_w.Buf(), ofn->nMaxCustFilter);
U8toW(ofn->lpstrFile, file_w.Buf(), ofn->nMaxFile);
U8toW(ofn->lpstrFileTitle, ftitle_w.Buf(), ofn->nMaxFileTitle);
U8toW(ofn->lpstrInitialDir, idir_w.Buf(), MAX_PATH);
U8toW(ofn->lpstrTitle, title_w.Buf(), MAX_PATH);
U8toW(ofn->lpstrDefExt, defext_w.Buf(), MAX_PATH);
U8toW(ofn->lpTemplateName, template_w.Buf(), MAX_PATH);
if (ofn->lpstrFilter) ofn_w.lpstrFilter = filter_w;
if (ofn->lpstrCustomFilter) ofn_w.lpstrCustomFilter = cfilter_w.Buf();
if (ofn->lpstrFile) ofn_w.lpstrFile = file_w.Buf();
if (ofn->lpstrFileTitle) ofn_w.lpstrFileTitle = ftitle_w.Buf();
if (ofn->lpstrInitialDir) ofn_w.lpstrInitialDir = idir_w;
if (ofn->lpstrTitle) ofn_w.lpstrTitle = title_w;
if (ofn->lpstrDefExt) ofn_w.lpstrDefExt = defext_w;
if (ofn->lpTemplateName) ofn_w.lpTemplateName = template_w;
BOOL ret = ofn_func(&ofn_w);
if (ofn->lpstrCustomFilter) WtoU8(cfilter_w, ofn->lpstrCustomFilter, MAX_PATH_U8);
if (ofn->lpstrFileTitle) WtoU8(ftitle_w, ofn->lpstrFileTitle, MAX_PATH_U8);
if (ofn->lpstrFile) {
if (ofn_w.Flags & OFN_ALLOWMULTISELECT) {
const WCHAR *wp=file_w;
char *p;
for (p=ofn->lpstrFile; wp && *wp; wp+=wcslen(wp)+1) {
p += WtoU8(wp, p, MAX_PATH_U8);
}
*p = 0;
}
else {
WtoU8(file_w, ofn->lpstrFile, MAX_PATH_U8);
}
}
// if (ofn_w.lpstrFile[ofn_w.nFileOffset])
ofn->nFileOffset = ::WideCharToMultiByte(CP_UTF8, 0, ofn_w.lpstrFile, ofn_w.nFileOffset,
0, 0, 0, 0);
return ret;
}
BOOL GetOpenFileNameU8(LPOPENFILENAME ofn)
{
return GetOpenFileNameU8Core(ofn, GetOpenFileNameW);
}
BOOL GetSaveFileNameU8(LPOPENFILENAME ofn)
{
return GetOpenFileNameU8Core(ofn, GetSaveFileNameW);
}
/*
リンクの解決
あらかじめ、CoInitialize(NULL); を実行しておくこと
*/
BOOL ReadLinkU8(LPCSTR src, LPSTR dest, LPSTR arg)
{
IShellLink *shellLink;
IPersistFile *persistFile;
WCHAR wbuf[MAX_PATH];
BOOL ret = FALSE;
if (SUCCEEDED(CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLinkW,
(void **)&shellLink)))
{
if (SUCCEEDED(shellLink->QueryInterface(IID_IPersistFile, (void **)&persistFile)))
{
U8toW(src, wbuf, MAX_PATH);
if (SUCCEEDED(persistFile->Load(wbuf, STGM_READ)))
{
if (SUCCEEDED(shellLink->GetPath((char *)wbuf, MAX_PATH, NULL, SLGP_SHORTPATH)))
{
WtoU8(wbuf, dest, MAX_PATH_U8);
shellLink->GetArguments((char *)wbuf, MAX_PATH);
WtoU8(wbuf, arg, MAX_PATH_U8);
ret = TRUE;
}
}
persistFile->Release();
}
shellLink->Release();
}
return ret;
}
BOOL PlaySoundU8(const char *path, HMODULE hmod, DWORD flg)
{
Wstr path_w(path);
return ::PlaySoundW(path_w, hmod, flg);
}
/*=========================================================================
Win32(W) API UTF8 wrapper
=========================================================================*/
BOOL GetMenuStringU8(HMENU hMenu, UINT uItem, char *buf, int bufsize, UINT flags)
{
WCHAR *wbuf = new WCHAR [bufsize];
BOOL ret = ::GetMenuStringW(hMenu, uItem, wbuf, bufsize, flags);
if (ret) {
WtoU8(wbuf, buf, bufsize);
}
delete wbuf;
return ret;
}
DWORD GetModuleFileNameU8(HMODULE hModule, char *buf, DWORD bufsize)
{
WCHAR *wbuf = new WCHAR [bufsize];
DWORD ret = ::GetModuleFileNameW(hModule, wbuf, bufsize);
if (ret) {
WtoU8(wbuf, buf, bufsize);
}
delete wbuf;
return ret;
}
UINT GetDriveTypeU8(const char *path)
{
Wstr wpath(path);
return ::GetDriveTypeW(wpath);
}
LPSTR GetLoadStrU8(UINT resId, HINSTANCE hI)
{
extern HINSTANCE defaultStrInstance;
static TResHash *hash;
if (hash == NULL) {
hash = new TResHash(100);
}
WCHAR buf[1024];
TResHashObj *obj;
if ((obj = hash->Search(resId)) == NULL) {
if (::LoadStringW(hI ? hI : defaultStrInstance, resId, buf, sizeof(buf) / sizeof(WCHAR))
>= 0) {
U8str buf_u8(buf);
obj = new TResHashObj(resId, strdup(buf_u8));
hash->Register(obj);
}
}
return obj ? (char *)obj->val : NULL;
}
/*=========================================================================
UCS2(W) - UTF-8(U8) - ANSI(A) 相互変換
=========================================================================*/
WCHAR *U8toW(const char *src, BOOL noStatic) {
static WCHAR *_wbuf = NULL;
WCHAR *wtmp = NULL;
WCHAR *&wbuf = noStatic ? wtmp : _wbuf;
if (wbuf) {
delete [] wbuf;
wbuf = NULL;
}
int len;
if ((len = U8toW(src, NULL, 0)) > 0) {
wbuf = new WCHAR [len + 1];
U8toW(src, wbuf, len);
}
return wbuf;
}
char *WtoU8(const WCHAR *src, BOOL noStatic) {
static char *_buf = NULL;
char *tmp = NULL;
char *&buf = noStatic ? tmp : _buf;
if (buf) {
delete [] buf;
buf = NULL;
}
int len;
if ((len = WtoU8(src, NULL, 0)) > 0) {
buf = new char [len + 1];
WtoU8(src, buf, len);
}
return buf;
}
char *WtoA(const WCHAR *src, BOOL noStatic) {
static char *_buf = NULL;
char *tmp = NULL;
char *&buf = noStatic ? tmp : _buf;
if (buf) {
delete [] buf;
buf = NULL;
}
int len;
if ((len = WtoA(src, NULL, 0)) > 0) {
buf = new char [len + 1];
WtoA(src, buf, len);
}
return buf;
}
char *toA(const void *src, BOOL noStatic) {
if (IS_WINNT_V) {
return WtoA((WCHAR *)src, noStatic);
}
return noStatic ? strdupNew((char *)src) : (char *)src;
}
WCHAR *toW(const void *src, BOOL noStatic) {
if (!IS_WINNT_V) {
return AtoW((char *)src, noStatic);
}
return noStatic ? wcsdupNew((WCHAR *)src) : (WCHAR *)src;
}
void *toV(const char *src, BOOL noStatic) {
if (IS_WINNT_V) {
return AtoW(src, noStatic);
}
return noStatic ? strdupNew(src) : (char *)src;
}
void *toV(const WCHAR *src, BOOL noStatic) {
if (!IS_WINNT_V) {
return WtoA(src, noStatic);
}
return noStatic ? wcsdupNew(src) : (void *)src;
}
char *AtoU8(const char *src, BOOL noStatic) {
static char *_buf = NULL;
char *tmp = NULL;
char *&buf = noStatic ? tmp : _buf;
if (buf) {
delete [] buf;
buf = NULL;
}
WCHAR *wsrc = AtoW(src, TRUE);
if (wsrc) {
buf = WtoU8(wsrc, TRUE);
}
delete [] wsrc;
return buf;
}
char *U8toA(const char *src, BOOL noStatic) {
static char *_buf = NULL;
char *tmp = NULL;
char *&buf = noStatic ? tmp : _buf;
if (buf) {
delete [] buf;
buf = NULL;
}
WCHAR *wsrc = U8toW(src, TRUE);
if (wsrc) {
buf = WtoA(wsrc, TRUE);
}
delete [] wsrc;
return buf;
}
BOOL IsUTF8(const char *_s)
{
const u_char *s = (const u_char *)_s;
while (*s) {
if (*s <= 0x7f) {
}
else if (*s <= 0xdf) {
if ((*++s & 0xc0) != 0x80) return FALSE;
}
else if (*s <= 0xef) {
if ((*++s & 0xc0) != 0x80) return FALSE;
if ((*++s & 0xc0) != 0x80) return FALSE;
}
else if (*s <= 0xf7) {
if ((*++s & 0xc0) != 0x80) return FALSE;
if ((*++s & 0xc0) != 0x80) return FALSE;
if ((*++s & 0xc0) != 0x80) return FALSE;
}
else if (*s <= 0xfb) {
if ((*++s & 0xc0) != 0x80) return FALSE;
if ((*++s & 0xc0) != 0x80) return FALSE;
if ((*++s & 0xc0) != 0x80) return FALSE;
if ((*++s & 0xc0) != 0x80) return FALSE;
}
else if (*s <= 0xfd) {
if ((*++s & 0xc0) != 0x80) return FALSE;
if ((*++s & 0xc0) != 0x80) return FALSE;
if ((*++s & 0xc0) != 0x80) return FALSE;
if ((*++s & 0xc0) != 0x80) return FALSE;
if ((*++s & 0xc0) != 0x80) return FALSE;
}
s++;
}
return TRUE;
}
| [
"laurent@cozic.net"
] | laurent@cozic.net |
440bdf3574f71e0cfa0d0293a61f8e8d08a7f431 | a8f050eaf5019ac7f6b5399563d276c637e32984 | /src/qt/bitcoinunits.cpp | 8c31f73d74d80696343389995aaf79c46417ff0c | [
"MIT"
] | permissive | CryptoDev-Project/Betty-Coin | f51076d351f6182a03e21d50578e36e0572c0ecb | 7cb745da7f1c70165b7a84b3abe9124464e489b0 | refs/heads/master | 2020-05-29T17:24:54.357319 | 2019-05-14T11:30:14 | 2019-05-14T11:30:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,151 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The BETTY developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bitcoinunits.h"
#include "chainparams.h"
#include "primitives/transaction.h"
#include <QSettings>
#include <QStringList>
BitcoinUnits::BitcoinUnits(QObject* parent) : QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
QList<BitcoinUnits::Unit> unitlist;
unitlist.append(BETTY);
unitlist.append(mBETTY);
unitlist.append(uBETTY);
return unitlist;
}
bool BitcoinUnits::valid(int unit)
{
switch (unit) {
case BETTY:
case mBETTY:
case uBETTY:
return true;
default:
return false;
}
}
QString BitcoinUnits::id(int unit)
{
switch (unit) {
case BETTY:
return QString("betty");
case mBETTY:
return QString("mbetty");
case uBETTY:
return QString::fromUtf8("ubetty");
default:
return QString("???");
}
}
QString BitcoinUnits::name(int unit)
{
if (Params().NetworkID() == CBaseChainParams::MAIN) {
switch (unit) {
case BETTY:
return QString("BETTY");
case mBETTY:
return QString("mBETTY");
case uBETTY:
return QString::fromUtf8("μBETTY");
default:
return QString("???");
}
} else {
switch (unit) {
case BETTY:
return QString("tBETTY");
case mBETTY:
return QString("mtBETTY");
case uBETTY:
return QString::fromUtf8("μtBETTY");
default:
return QString("???");
}
}
}
QString BitcoinUnits::description(int unit)
{
if (Params().NetworkID() == CBaseChainParams::MAIN) {
switch (unit) {
case BETTY:
return QString("BETTY");
case mBETTY:
return QString("Milli-BETTY (1 / 1" THIN_SP_UTF8 "000)");
case uBETTY:
return QString("Micro-BETTY (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)");
default:
return QString("???");
}
} else {
switch (unit) {
case BETTY:
return QString("TestBETTY");
case mBETTY:
return QString("Milli-TestBETTY (1 / 1" THIN_SP_UTF8 "000)");
case uBETTY:
return QString("Micro-TestBETTY (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)");
default:
return QString("???");
}
}
}
qint64 BitcoinUnits::factor(int unit)
{
switch (unit) {
case BETTY:
return 100000000;
case mBETTY:
return 100000;
case uBETTY:
return 100;
default:
return 100000000;
}
}
int BitcoinUnits::decimals(int unit)
{
switch (unit) {
case BETTY:
return 8;
case mBETTY:
return 5;
case uBETTY:
return 2;
default:
return 0;
}
}
QString BitcoinUnits::format(int unit, const CAmount& nIn, bool fPlus, SeparatorStyle separators)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
if (!valid(unit))
return QString(); // Refuse to format invalid unit
qint64 n = (qint64)nIn;
qint64 coin = factor(unit);
int num_decimals = decimals(unit);
qint64 n_abs = (n > 0 ? n : -n);
qint64 quotient = n_abs / coin;
qint64 remainder = n_abs % coin;
QString quotient_str = QString::number(quotient);
QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');
// Use SI-style thin space separators as these are locale independent and can't be
// confused with the decimal marker.
QChar thin_sp(THIN_SP_CP);
int q_size = quotient_str.size();
if (separators == separatorAlways || (separators == separatorStandard && q_size > 4))
for (int i = 3; i < q_size; i += 3)
quotient_str.insert(q_size - i, thin_sp);
if (n < 0)
quotient_str.insert(0, '-');
else if (fPlus && n > 0)
quotient_str.insert(0, '+');
if (num_decimals <= 0)
return quotient_str;
return quotient_str + QString(".") + remainder_str;
}
// TODO: Review all remaining calls to BitcoinUnits::formatWithUnit to
// TODO: determine whether the output is used in a plain text context
// TODO: or an HTML context (and replace with
// TODO: BtcoinUnits::formatHtmlWithUnit in the latter case). Hopefully
// TODO: there aren't instances where the result could be used in
// TODO: either context.
// NOTE: Using formatWithUnit in an HTML context risks wrapping
// quantities at the thousands separator. More subtly, it also results
// in a standard space rather than a thin space, due to a bug in Qt's
// XML whitespace canonicalisation
//
// Please take care to use formatHtmlWithUnit instead, when
// appropriate.
QString BitcoinUnits::formatWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
return format(unit, amount, plussign, separators) + QString(" ") + name(unit);
}
QString BitcoinUnits::formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
QString str(formatWithUnit(unit, amount, plussign, separators));
str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML));
return QString("<span style='white-space: nowrap;'>%1</span>").arg(str);
}
QString BitcoinUnits::floorWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
QSettings settings;
int digits = settings.value("digits").toInt();
QString result = format(unit, amount, plussign, separators);
if (decimals(unit) > digits) result.chop(decimals(unit) - digits);
return result + QString(" ") + name(unit);
}
QString BitcoinUnits::floorHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
QString str(floorWithUnit(unit, amount, plussign, separators));
str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML));
return QString("<span style='white-space: nowrap;'>%1</span>").arg(str);
}
bool BitcoinUnits::parse(int unit, const QString& value, CAmount* val_out)
{
if (!valid(unit) || value.isEmpty())
return false; // Refuse to parse invalid unit or empty string
int num_decimals = decimals(unit);
// Ignore spaces and thin spaces when parsing
QStringList parts = removeSpaces(value).split(".");
if (parts.size() > 2) {
return false; // More than one dot
}
QString whole = parts[0];
QString decimals;
if (parts.size() > 1) {
decimals = parts[1];
}
if (decimals.size() > num_decimals) {
return false; // Exceeds max precision
}
bool ok = false;
QString str = whole + decimals.leftJustified(num_decimals, '0');
if (str.size() > 18) {
return false; // Longer numbers will exceed 63 bits
}
CAmount retvalue(str.toLongLong(&ok));
if (val_out) {
*val_out = retvalue;
}
return ok;
}
QString BitcoinUnits::getAmountColumnTitle(int unit)
{
QString amountTitle = QObject::tr("Amount");
if (BitcoinUnits::valid(unit)) {
amountTitle += " (" + BitcoinUnits::name(unit) + ")";
}
return amountTitle;
}
int BitcoinUnits::rowCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant BitcoinUnits::data(const QModelIndex& index, int role) const
{
int row = index.row();
if (row >= 0 && row < unitlist.size()) {
Unit unit = unitlist.at(row);
switch (role) {
case Qt::EditRole:
case Qt::DisplayRole:
return QVariant(name(unit));
case Qt::ToolTipRole:
return QVariant(description(unit));
case UnitRole:
return QVariant(static_cast<int>(unit));
}
}
return QVariant();
}
CAmount BitcoinUnits::maxMoney()
{
return Params().MaxMoneyOut();
}
| [
"50576811+BETTYCOIN@users.noreply.github.com"
] | 50576811+BETTYCOIN@users.noreply.github.com |
3f9aa2ffb88d3758bddb87d5b175c66deabfce19 | bca341cb6a19b0eb2c5ed127097572418fca3cec | /src/protocol.h | 24416a7d7885bd1e004d5a99063ae771fdfb0e9b | [
"MIT"
] | permissive | neutcoin-project/neutcoin | bbc22f7d7191154a33ca22734b88beb677d009cb | eefc6e25640a639f45f97a86fc8ffcd77027cb05 | refs/heads/master | 2021-09-10T07:05:35.369839 | 2018-01-15T14:57:13 | 2018-01-15T14:57:13 | 115,464,625 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,719 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef __cplusplus
# error This header can only be compiled as C++.
#endif
#ifndef __INCLUDED_PROTOCOL_H__
#define __INCLUDED_PROTOCOL_H__
#include "serialize.h"
#include "netbase.h"
#include <string>
#include "uint256.h"
extern bool fTestNet;
static inline unsigned short GetDefaultPort(const bool testnet = fTestNet)
{
return testnet ? 19333 : 3000;
}
extern unsigned char pchMessageStart[4];
/** Message header.
* (4) message start.
* (12) command.
* (4) size.
* (4) checksum.
*/
class CMessageHeader
{
public:
CMessageHeader();
CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn);
std::string GetCommand() const;
bool IsValid() const;
IMPLEMENT_SERIALIZE
(
READWRITE(FLATDATA(pchMessageStart));
READWRITE(FLATDATA(pchCommand));
READWRITE(nMessageSize);
READWRITE(nChecksum);
)
// TODO: make private (improves encapsulation)
public:
enum {
MESSAGE_START_SIZE=sizeof(::pchMessageStart),
COMMAND_SIZE=12,
MESSAGE_SIZE_SIZE=sizeof(int),
CHECKSUM_SIZE=sizeof(int),
MESSAGE_SIZE_OFFSET=MESSAGE_START_SIZE+COMMAND_SIZE,
CHECKSUM_OFFSET=MESSAGE_SIZE_OFFSET+MESSAGE_SIZE_SIZE,
HEADER_SIZE=MESSAGE_START_SIZE+COMMAND_SIZE+MESSAGE_SIZE_SIZE+CHECKSUM_SIZE
};
char pchMessageStart[MESSAGE_START_SIZE];
char pchCommand[COMMAND_SIZE];
unsigned int nMessageSize;
unsigned int nChecksum;
};
/** nServices flags */
enum
{
NODE_NETWORK = (1 << 0),
NODE_BLOOM = (1 << 1),
};
/** A CService with information about it as peer */
class CAddress : public CService
{
public:
CAddress();
explicit CAddress(CService ipIn, uint64 nServicesIn=NODE_NETWORK);
void Init();
IMPLEMENT_SERIALIZE
(
CAddress* pthis = const_cast<CAddress*>(this);
CService* pip = (CService*)pthis;
if (fRead)
pthis->Init();
if (nType & SER_DISK)
READWRITE(nVersion);
if ((nType & SER_DISK) ||
(nVersion >= CADDR_TIME_VERSION && !(nType & SER_GETHASH)))
READWRITE(nTime);
READWRITE(nServices);
READWRITE(*pip);
)
void print() const;
// TODO: make private (improves encapsulation)
public:
uint64 nServices;
// disk and network only
unsigned int nTime;
// memory only
int64 nLastTry;
};
/** inv message data */
class CInv
{
public:
CInv();
CInv(int typeIn, const uint256& hashIn);
CInv(const std::string& strType, const uint256& hashIn);
IMPLEMENT_SERIALIZE
(
READWRITE(type);
READWRITE(hash);
)
friend bool operator<(const CInv& a, const CInv& b);
bool IsKnownType() const;
const char* GetCommand() const;
std::string ToString() const;
void print() const;
// TODO: make private (improves encapsulation)
public:
int type;
uint256 hash;
};
enum
{
MSG_TX = 1,
MSG_BLOCK,
// Nodes may always request a MSG_FILTERED_BLOCK in a getdata, however,
// MSG_FILTERED_BLOCK should not appear in any invs except as a part of getdata.
MSG_FILTERED_BLOCK,
};
#endif // __INCLUDED_PROTOCOL_H__
| [
"noreply@github.com"
] | neutcoin-project.noreply@github.com |
c59de285328359d756b867f0ccc38546f2d45f35 | c1b03b59b3974058e3dc4e3aa7a46a7ab9cc3b29 | /src/module-wx.new/generated/Class_wx_RichTextPlainTextHandler.h | dd22984b6176abd5906078e4a675914ce6ee7470 | [] | no_license | gura-lang/gura | 972725895c93c22e0ec87c17166df4d15bdbe338 | 03aff5e2b7fe4f761a16400ae7cc6fa7fec73a47 | refs/heads/master | 2021-01-25T08:04:38.269289 | 2020-05-09T12:42:23 | 2020-05-09T12:42:23 | 7,141,465 | 25 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,036 | h | //----------------------------------------------------------------------------
// wxRichTextPlainTextHandler
//----------------------------------------------------------------------------
#ifndef __CLASS_WX_RICHTEXTPLAINTEXTHANDLER_H__
#define __CLASS_WX_RICHTEXTPLAINTEXTHANDLER_H__
#include <wx/richtext/richtextbuffer.h>
Gura_BeginModuleScope(wx)
//----------------------------------------------------------------------------
// Class declaration for wxRichTextPlainTextHandler
//----------------------------------------------------------------------------
Gura_DeclareUserClass(wx_RichTextPlainTextHandler);
//----------------------------------------------------------------------------
// Object declaration for wxRichTextPlainTextHandler
//----------------------------------------------------------------------------
class Object_wx_RichTextPlainTextHandler : public Object_wx_RichTextFileHandler {
public:
Gura_DeclareObjectAccessor(wx_RichTextPlainTextHandler)
public:
inline Object_wx_RichTextPlainTextHandler(wxRichTextPlainTextHandler *pEntity, GuraObjectObserver *pObserver, bool ownerFlag) :
Object_wx_RichTextFileHandler(Gura_UserClass(wx_RichTextPlainTextHandler), pEntity, pObserver, ownerFlag) {}
inline Object_wx_RichTextPlainTextHandler(Class *pClass, wxRichTextPlainTextHandler *pEntity, GuraObjectObserver *pObserver, bool ownerFlag) :
Object_wx_RichTextFileHandler(pClass, pEntity, pObserver, ownerFlag) {}
virtual ~Object_wx_RichTextPlainTextHandler();
virtual Object *Clone() const;
virtual String ToString(bool exprFlag);
inline wxRichTextPlainTextHandler *GetEntity() {
return static_cast<wxRichTextPlainTextHandler *>(_pEntity);
}
inline wxRichTextPlainTextHandler *ReleaseEntity() {
wxRichTextPlainTextHandler *pEntity = GetEntity();
InvalidateEntity();
return pEntity;
}
inline bool IsInvalid(Environment &env) const {
if (_pEntity != nullptr) return false;
SetError_InvalidWxObject(env, "wxRichTextPlainTextHandler");
return true;
}
};
Gura_EndModuleScope(wx)
#endif
| [
"ypsitau@nifty.com"
] | ypsitau@nifty.com |
25a7cac6f1dd06f313f9c559d3140dd767ca4b71 | cebc7a8d159835cb027c413cb5016202e662fa82 | /clams/frame_projector.h | 981c4710beb50e607d71d191d412c82ea1748c6e | [] | no_license | caomw/clams | 75fc8bac61d67b8874419189233172633cdd0059 | d583e675bff2627cce0d58a44ac6ddc23eed559b | refs/heads/master | 2021-01-17T21:58:54.080608 | 2015-07-09T11:59:40 | 2015-07-09T11:59:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,477 | h | #pragma once
#include <pcl/common/transforms.h>
#include <pcl/common/distances.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "slick/datatypes.h"
#include "slick/scene/poli_camera.h"
#include "clams/common/typedefs.h"
#include "clams/cam_calib.h"
namespace clams {
//! "Projective" point comes from the OpenNI terminology, and refers to (u, v,
//z), i.e.
//! pixel id and depth value. Here I've added color, too, so that this
//represents everything
//! that is known about a pixel in an RBGD camera.
struct ProjectivePoint {
int u;
int v;
//! In millimeters, same as the raw depth image from the primesense device.
unsigned short z;
unsigned char r;
unsigned char g;
unsigned char b;
// for serialization
template <class Archive>
void serialize(Archive &ar, const unsigned int version);
};
// Frame =======================================================================
struct Frame {
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
Frame() {
prefix = "clams-frame";
timestamp = 0.0;
depth_offset = 0;
}
void FilterFringe();
cv::Mat3b ColorImage() const { return img; }
cv::Mat3b DepthImage() const;
std::string FilenamePrefix() const {
return prefix + "-" + std::to_string(timestamp);
}
protected:
cv::Vec3b colorize(double depth, double min_range, double max_range) const;
public:
std::string prefix;
double timestamp;
cv::Mat3b img;
cv::Mat_<uint16_t> depth;
float depth_offset; /// milimeters, average depth offset to calibration target
CenterLocPairVec measurements; // world_point-pixel_location pairs
slick::SE3d target2cam; // calibration target to camera pose
Eigen::Vector4d target_plane; // in camera coordinate
// for serialization
template <class Archive>
void serialize(Archive &ar, const unsigned int version);
};
// FrameProjector ==============================================================
//! This is essentially a pinhole camera model for an RGBD sensor, with
//! some extra functions added on for use during calibration.
class FrameProjector {
public:
// For storing z values in meters. This is not Euclidean distance.
using RangeIndex = std::vector<std::vector<std::vector<double>>>;
using IndexMap = Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>;
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
FrameProjector();
static void ReestimatePoseAndPlane(Frame &frame,
const slick::PoliCamera<double>& poli_cam,
const Eigen::Vector4d &target_plane);
//! max_range in meters
void
FrameToCloud(const Frame &frame, Cloud *pcd,
double max_range = std::numeric_limits<double>::max()) const;
void CloudToFrame(const Cloud &pcd, Frame *frame,
IndexMap *indexmap = NULL) const;
void CloudToRangeIndex(const Cloud &pcd, RangeIndex *rindex) const;
//! transform is applied to the map, then projected into a depth index.
//! The best depth estimate from the map corresponding to the measurement
//depth frame
//! will be returned.
void EstimateMapDepth(const Cloud &map, const Eigen::Affine3f &transform,
Frame &measurement, DepthMat& estimate) const;
//! transform is applied to the map, then projected into a depth index.
//! The best depth estimate from the map corresponding to the measurement
//depth frame
//! will be returned.
void EstimateDepthFromPlanarPattern(const Eigen::Vector4d& target_plane,
Frame &measurement, DepthMat& estimate) const;
std::vector<float> EstimateDepthOffsets(Frame &measurement) const;
ProjectivePoint Project(const Point& pt) const;
Point UnProject(const ProjectivePoint &ppt) const;
bool Initialized() const;
std::string Status(const std::string &prefix = "") const;
slick::PoliCamera<double>& poli_cam() { return poli_cam_; }
const slick::PoliCamera<double>& poli_cam() const { return poli_cam_; }
int width() const { return poli_cam_.ImageSize()[0]; }
int height() const { return poli_cam_.ImageSize()[1]; }
protected:
bool ConeFit(const DepthMat &naive_mapdepth, const RangeIndex &rindex, int uc,
int vc, double radius, double measurement_depth, double *mean,
double *stdev) const;
slick::PoliCamera<double> poli_cam_;
public:
// for serialization
template <class Archive>
void serialize(Archive &ar, const unsigned int version);
};
} // namespace clams | [
"william.mccohen@gmail.com"
] | william.mccohen@gmail.com |
a06d97139ec3a0e4226231d306960c87a00255ff | 4ad462e2b7d198a380993fa88a4c7f047b1cb2ee | /DirectXBasicGame/Main.cpp | 9012720a880d40c64f1cba1d37cf9a35176e3f70 | [] | no_license | nitvic793/basic-dx-game | aefc6452f141c341d37a258307f846ee16f4cceb | 30ee7698a0f4d39c90a7002c683298f7a669e2ab | refs/heads/master | 2020-03-29T19:05:01.989579 | 2015-05-05T06:52:29 | 2015-05-05T06:52:29 | 34,738,875 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,748 | cpp | //
// Main.cpp -
//
#include "pch.h"
#include "Game.h"
using namespace DirectX;
namespace
{
std::unique_ptr<Game> g_game;
};
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
// Entry point
int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
HRESULT hr = CoInitializeEx(nullptr, COINITBASE_MULTITHREADED);
if (FAILED(hr))
return 1;
g_game.reset( new Game() );
// Register class and create window
{
// Register class
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, L"IDI_ICON");
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
wcex.lpszMenuName = nullptr;
wcex.lpszClassName = L"DirectXBasicGameWindowClass";
wcex.hIconSm = LoadIcon(wcex.hInstance, L"IDI_ICON");
if (!RegisterClassEx(&wcex))
return 1;
// Create window
size_t w, h;
g_game->GetDefaultSize( w, h );
RECT rc;
rc.top = 0;
rc.left = 0;
rc.right = static_cast<LONG>( w );
rc.bottom = static_cast<LONG>( h );
HWND hwnd = CreateWindow(L"DirectXBasicGameWindowClass", L"DirectXBasicGame", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, nullptr, nullptr, hInstance,
nullptr);
if (!hwnd)
return 1;
ShowWindow(hwnd, nCmdShow);
SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(g_game.get()) );
g_game->Initialize( hwnd );
}
// Main message loop
MSG msg = { 0 };
while (WM_QUIT != msg.message)
{
if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
g_game->Tick();
}
}
g_game.reset();
CoUninitialize();
return (int) msg.wParam;
}
// Windows procedure
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
static bool s_in_sizemove = false;
static bool s_in_suspend = false;
static bool s_minimized = false;
auto game = reinterpret_cast<Game*>( GetWindowLongPtr(hWnd, GWLP_USERDATA) );
switch (message)
{
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
break;
case WM_SIZE:
if (wParam == SIZE_MINIMIZED)
{
if (!s_minimized)
{
s_minimized = true;
if (!s_in_suspend && game)
game->OnSuspending();
s_in_suspend = true;
}
}
else if (s_minimized)
{
s_minimized = false;
if (s_in_suspend && game)
game->OnResuming();
s_in_suspend = false;
}
else if ( !s_in_sizemove && game )
game->OnWindowSizeChanged();
break;
case WM_ENTERSIZEMOVE:
s_in_sizemove = true;
break;
case WM_EXITSIZEMOVE:
s_in_sizemove = false;
if (game)
game->OnWindowSizeChanged();
break;
case WM_GETMINMAXINFO:
{
auto info = reinterpret_cast<MINMAXINFO*>(lParam);
info->ptMinTrackSize.x = 320;
info->ptMinTrackSize.y = 200;
}
break;
case WM_ACTIVATEAPP:
if (game)
{
if (wParam)
{
game->OnActivated();
}
else
{
game->OnDeactivated();
}
}
break;
case WM_POWERBROADCAST:
switch (wParam)
{
case PBT_APMQUERYSUSPEND:
if (!s_in_suspend && game)
game->OnSuspending();
s_in_suspend = true;
return true;
case PBT_APMRESUMESUSPEND:
if (!s_minimized)
{
if (s_in_suspend && game)
game->OnResuming();
s_in_suspend = false;
}
return true;
}
break;
case WM_KEYDOWN:
if (!s_minimized && game)
{
game->ProcessInput(wParam);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
} | [
"nithishvictor@gmail.com"
] | nithishvictor@gmail.com |
5765b821aaba1bb076d9c8ff21b4c4d60c63ed70 | 8cf32b4cbca07bd39341e1d0a29428e420b492a6 | /libraries/fc/include/fc/crypto/sha512.hpp | 008d5e16f8c08707f8637d45355b9187d39908c6 | [
"MIT"
] | permissive | cubetrain/CubeTrain | e1cd516d5dbca77082258948d3c7fc70ebd50fdc | b930a3e88e941225c2c54219267f743c790e388f | refs/heads/master | 2020-04-11T23:00:50.245442 | 2018-12-17T16:07:16 | 2018-12-17T16:07:16 | 156,970,178 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,991 | hpp | #pragma once
#include <fc/fwd.hpp>
#include <fc/string.hpp>
namespace fc
{
class sha512
{
public:
sha512();
explicit sha512( const string& hex_str );
string str()const;
operator string()const;
char* data()const;
size_t data_size()const { return 512 / 8; }
static sha512 hash( const char* d, uint32_t dlen );
static sha512 hash( const string& );
template<typename T>
static sha512 hash( const T& t )
{
sha512::encoder e;
e << t;
return e.result();
}
class encoder
{
public:
encoder();
~encoder();
void write( const char* d, uint32_t dlen );
void put( char c ) { write( &c, 1 ); }
void reset();
sha512 result();
private:
struct impl;
fc::fwd<impl,216> my;
};
template<typename T>
inline friend T& operator<<( T& ds, const sha512& ep ) {
ds.write( ep.data(), sizeof(ep) );
return ds;
}
template<typename T>
inline friend T& operator>>( T& ds, sha512& ep ) {
ds.read( ep.data(), sizeof(ep) );
return ds;
}
friend sha512 operator << ( const sha512& h1, uint32_t i );
friend bool operator == ( const sha512& h1, const sha512& h2 );
friend bool operator != ( const sha512& h1, const sha512& h2 );
friend sha512 operator ^ ( const sha512& h1, const sha512& h2 );
friend bool operator >= ( const sha512& h1, const sha512& h2 );
friend bool operator > ( const sha512& h1, const sha512& h2 );
friend bool operator < ( const sha512& h1, const sha512& h2 );
uint64_t _hash[8];
};
typedef fc::sha512 uint512;
class variant;
void to_variant( const sha512& bi, variant& v );
void from_variant( const variant& v, sha512& bi );
} // fc
#include <fc/reflect/reflect.hpp>
FC_REFLECT_TYPENAME( fc::sha512 )
| [
"1848@shanchain.com"
] | 1848@shanchain.com |
8c5de5f18e11ff9db12c299cc9f795227f44f274 | 4cab1104c22312ebee91fa041031cc3d251635d3 | /Source/Level.cpp | f53eeefff78e0c62374b36ce7213964aacffc081 | [] | no_license | thearusable/Tanks | 7956887595611280dac7af7f0fbd43fd4e29ee69 | 0204f7061adb75baf48c7fd47867bfeb404fdca7 | refs/heads/master | 2021-08-28T11:32:41.161561 | 2021-08-10T21:20:01 | 2021-08-10T21:20:01 | 28,541,939 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,935 | cpp | #include "Level.h"
extern DataBase DATABASE;
Level::Level(void) :elementy(), mEdge(), background() {
//pozycja mapy
mapPosition.x = 30;
mapPosition.y = 25;
//
background.setFillColor(sf::Color::Black);
background.setSize(sf::Vector2f(13 * 54.f, 13 * 48.f));
background.setPosition(mapPosition);
for (int i = 0; i < 4; i++) {
mEdge[i].setSize(sf::Vector2f(15 * 54.f, 50.f));
mEdge[i].setTexture(arus::Textures::brick);
mEdge[i].setOrigin(0.f, 0.f);
}
mEdge[0].setPosition(0.f, mapPosition.y + 24 - mEdge[0].getLocalBounds().height); //top - ready
mEdge[1].setPosition(0.f, mapPosition.y + 24 + 13 * 48.f); //bot - ready
mEdge[2].setRotation(90.f);
mEdge[2].setPosition(mapPosition.x + 24 - 50.f, mapPosition.y); //left - ready
mEdge[3].setRotation(90.f);
mEdge[3].setPosition(mapPosition.x + 24 + 13 * 54.f, mapPosition.y); //right
elementy[0] = RenderElement(arus::Textures::empty, sf::Vector2f(0.f, 0.f));
elementy[1].setTextureAndRect(arus::Textures::brick, sf::IntRect(0, 0, 54, 48));
elementy[2].setTextureAndRect(arus::Textures::brick, sf::IntRect(0, 0, 27, 48));
elementy[3].setTextureAndRect(arus::Textures::brick, sf::IntRect(27, 0, 27, 48));
elementy[4].setTextureAndRect(arus::Textures::brick, sf::IntRect(0, 0, 54, 24));
elementy[5].setTextureAndRect(arus::Textures::brick, sf::IntRect(0, 24, 54, 24));
//steel
elementy[6].setTextureAndRect(arus::Textures::steel, sf::IntRect(0, 0, 54, 48));
elementy[7].setTextureAndRect(arus::Textures::steel, sf::IntRect(0, 0, 27, 48));
elementy[8].setTextureAndRect(arus::Textures::steel, sf::IntRect(27, 0, 27, 48));
elementy[9].setTextureAndRect(arus::Textures::steel, sf::IntRect(0, 0, 54, 24));
elementy[10].setTextureAndRect(arus::Textures::steel, sf::IntRect(0, 24, 54, 24));
//reszta
elementy[11].setTexture(arus::Textures::water); //water
elementy[12].setTexture(arus::Textures::ice); //ice
elementy[13].setTexture(arus::Textures::grass); //grass
elementy[14].setTexture(arus::Textures::eagle); //eagle
this->clearMap();
}
void Level::operator>(MyWindow& target) { //wszystko poza zielenia
target.draw(background);
for (unsigned int i = 0; i < 13; i++)
for (unsigned int j = 0; j < 13; j++) {
arus::Textures t = mTiledMap[i][j].getTextureID();
if (t != arus::Textures::empty && t != arus::Textures::grass)
mTiledMap[i][j] >> target;
}
}
void Level::operator>>(MyWindow& target) {// rysowanie zieleni
for (unsigned int i = 0; i < 13; i++)
for (unsigned int j = 0; j < 13; j++)
if (mTiledMap[i][j].getTextureID() == arus::Textures::grass)
mTiledMap[i][j] >> target;
}
void Level::destroyElementOfMap(unsigned int x, unsigned int y) {
mTiledMap[x][y] = elementy[0];
}
void Level::clearMap() {
for (int i = 0; i < 13; i++)
for (int j = 0; j < 13; j++) {
mTiledMap[i][j] = elementy[0];
mTiledMap[i][j].setPosition(i * 54.f + 30.f + 27.f, j * 48.f + 25.f + 24.f);
}
}
void Level::loadMap(unsigned int x) {
this->clearMap();
std::fstream file;
unsigned int xx = x;
while (true) {
try {
std::string sciezka = "Data/Levels/" + std::to_string(xx) + ".txt";
file.open(sciezka, std::ios::in);
if (!file.good()) {
throw "!!!";
}
break;
}
catch (const char *) {
xx = 1;
DATABASE.getStats().currLevel = 1;
}
}
int a = 0, b = 0, tempX, tempY, posX, posY, id;
while (file.good()) {
if (file >> tempY) {
file >> tempX >> id >> posX >> posY;
mTiledMap[tempX][tempY] = elementy[id];
mTiledMap[tempX][tempY].setPosition(float(posX + 27), float(posY + 24));
if (id == 13 || id == 12) mTiledMap[tempX][tempY].setColliderWithTank(false);
else mTiledMap[tempX][tempY].setColliderWithTank(true);
if (id == 13 || id == 12 || id == 11) mTiledMap[tempX][tempY].setColliderWithBullet(false);
else mTiledMap[tempX][tempY].setColliderWithBullet(true);
}
}
file.close();
}
MapElement& Level::getMapElement(int x, int y) {
return mTiledMap[x][y];
} | [
"arek.szczepkowicz@gmail.com"
] | arek.szczepkowicz@gmail.com |
74a63b2fd0b77261834daa25b3741d7a80b71f3e | 52d0d17a92d90a1c05f3a58637ca2b1178fa5e9c | /doodlejump6.cpp | 32c736d51f50bec7e0ea7f6364341f606dfb380c | [] | no_license | MinaTahaei/ProjectDOODLEJUMP | 38b5e4b9a5778e9da6f7d5c3ece325e8f13f98c3 | c4eaa2bee309c09cba52366fd5815163938b2416 | refs/heads/master | 2021-09-06T21:31:41.947042 | 2018-02-11T16:27:12 | 2018-02-11T16:27:12 | 116,121,451 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,015 | cpp | #include<iostream>
#include"SDL/SDL.h"
#include"SDL/SDL_image.h"
#include<SDL/SDL_gfxPrimitives.h>
#include"SDL/SDL_ttf.h"
#include<cstdlib>
#include<ctime>
#include<math.h>
#include<sstream>
#include <string>
using namespace std;
struct boards
{
float x;
float y;
int type;
int len;
float vy;
float vx;
int w;
int h;
};
const float vmax = 10;
const float g = -0.25;
struct Doodle
{
float x = 300;
float y = 599;
float vy = vmax;
int width = 100;
int height = 100;
};
Doodle doodle;
const int board_n = 15;
boards board[board_n];
//boards type
const int broken = 1;
const int stable = 2;
const int movable = 3;
const int spring = 4;
const int jet = 5;
const int monster1 = 6;
const int monster2 = 7;
const int monster3 = 8;
const int empty = 9;
const int mirror = 10;
const int brokenbroken = 11;
const int completlybroken = 12;
const int spring2 = 13;
int score;
int highscore;
void show_score(SDL_Surface * screen, TTF_Font* font)
{
stringstream scoreString;
SDL_Surface * shown_score;
SDL_Color color={0,130,255};
scoreString<<"score : "<<score;
shown_score = TTF_RenderText_Solid(font,scoreString.str().c_str(),color);
SDL_Rect position;
position.x = 50;
position.y = 50;
SDL_BlitSurface(shown_score,NULL,screen,&position);
SDL_Flip(screen);
}
void show_highscore(SDL_Surface * screen , TTF_Font* font )
{
stringstream highscoreString;
SDL_Surface * shown_highscore;
SDL_Color color={130,0,130};
highscoreString<<"highscore : "<<highscore;
shown_highscore = TTF_RenderText_Solid(font,highscoreString.str().c_str(),color);
SDL_Rect position;
position.x = 100;
position.y = 100;
SDL_BlitSurface(shown_highscore,NULL,screen,&position);
SDL_Flip(screen);
}
int showmenu_start(SDL_Surface* screen , TTF_Font* font , TTF_Font* titlefont ) //{ "play","exit"};0,1
{
int x,y;
const int menunumber=2;
const char* menuitem[menunumber]={ "play","exit"};//0,1
SDL_Surface* menu[menunumber]={NULL};
bool selected_item[menunumber]={0,0};
SDL_Color color[3]={{255,255,255},{255,0,0},{80,210,30}};
SDL_Surface* title=TTF_RenderText_Solid(titlefont,"doodle jump",color[2]);
SDL_Rect positiontitle;
positiontitle.x=300;
positiontitle.y=50;
menu[0]=TTF_RenderText_Solid(font,menuitem[0],color[0]);
menu[1]=TTF_RenderText_Solid(font,menuitem[1],color[0]);
SDL_Rect position[menunumber];
position[0].x=300;
position[0].y=200;
position[0].w=100;
position[0].h=200;
position[1].x=300;
position[1].y=450;
position[1].w=100;
position[1].h=200;
position[1].x=300;
position[1].y=450;
position[1].w=100;
position[1].h=200;
SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 00, 00, 00 ) );
SDL_Event event;
while(true)
{
for(int i=0;i<menunumber;i++)
SDL_BlitSurface(menu[i],NULL,screen,&position[i]);
SDL_BlitSurface(title,NULL,screen,&positiontitle);
while(SDL_PollEvent(&event))
{
switch(event.type)
{
case(SDL_QUIT):
{
SDL_FreeSurface(title);
for(int i=0;i<menunumber;i++)
SDL_FreeSurface(menu[i]);
return 1;
break;
}
case(SDL_MOUSEMOTION):
{
x=event.motion.x;
y=event.motion.y;
for(int i=0; i<menunumber;i++)
{
if( x>=position[i].x && x<=position[i].x+position[i].w && y>=position[i].y && y<=position[i].y+position[i].h )
{
if(selected_item[i]!=1)
{
SDL_FreeSurface(menu[i]);
menu[i]=TTF_RenderText_Solid(font,menuitem[i],color[1]);
selected_item[i]=1;
}
}
else
{
if(selected_item[i]==1)
{
SDL_FreeSurface(menu[i]);
menu[i]=TTF_RenderText_Solid(font,menuitem[i],color[0]);
selected_item[i]=0;
}
}
}
break;
}
case(SDL_MOUSEBUTTONDOWN):
{
if(event.button.button=SDL_BUTTON_LEFT)
{
x=event.button.x;
y=event.button.y;
for(int i=0;i<menunumber;i++)
{
if(x>=position[i].x && x<=position[i].x + position[i].w && y>=position[i].y && y<=position[i].y + position[i].h)
{
// SDL_Delay(500);
SDL_FreeSurface(title);
for(int j=0;j<menunumber;j++)
SDL_FreeSurface( menu[j]);
return i;
}
}
}
break;
}
}
}
SDL_Flip(screen);
}
}
int showmenu_pause(SDL_Surface* screen , TTF_Font* font , TTF_Font* titlefont ) //{ "continue", "play again" , "exit"};0,1,2
{
int x,y;
const int menunumber=3;
const char* menuitem[menunumber]={ "continue", "play again" , "exit"};//0,1,2
SDL_Surface* menu[menunumber]={NULL};
bool selected_item[menunumber]={0,0,0};
SDL_Color color[3]={{255,255,255},{255,0,0},{255,160,0}};
SDL_Surface* title=TTF_RenderText_Solid(titlefont,"pause",color[2]);
SDL_Rect positiontitle;
positiontitle.x=300;
positiontitle.y=50;
menu[0]=TTF_RenderText_Solid(font,menuitem[0],color[0]);
menu[1]=TTF_RenderText_Solid(font,menuitem[1],color[0]);
menu[2]=TTF_RenderText_Solid(font,menuitem[2],color[0]);
SDL_Rect position[menunumber];
position[0].x=300;
position[0].y=200;
position[0].w=100;
position[0].h=150;
position[1].x=300;
position[1].y=300;
position[1].w=100;
position[1].h=150;
position[2].x=300;
position[2].y=500;
position[2].w=100;
position[2].h=150;
SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 00, 00, 00 ) );
SDL_Event event;
while(1)
{
for(int i=0;i<menunumber;i++)
SDL_BlitSurface(menu[i],NULL,screen,&position[i]);
SDL_BlitSurface(title,NULL,screen,&positiontitle);
while(SDL_PollEvent(&event))
{
switch(event.type)
{
case(SDL_QUIT):
{
SDL_FreeSurface(title);
for(int i=0;i<menunumber;i++)
SDL_FreeSurface(menu[i]);
return 2;
break;
}
case(SDL_MOUSEMOTION):
{
x=event.motion.x;
y=event.motion.y;
for(int i=0; i<menunumber;i++)
{
if( x>=position[i].x && x<=position[i].x+position[i].w && y>=position[i].y && y<=position[i].y+position[i].h )
{
if(selected_item[i]!=1)// !selected_item[i]
{
SDL_FreeSurface(menu[i]);
menu[i]=TTF_RenderText_Solid(font,menuitem[i],color[1]);
selected_item[i]=1;
}
}
else
{
if(selected_item[i]==1)// selected_item[i]
{
SDL_FreeSurface(menu[i]);
menu[i]=TTF_RenderText_Solid(font,menuitem[i],color[0]);
selected_item[i]=0;
}
}
}
break;
}
case(SDL_MOUSEBUTTONDOWN):
{
if(event.button.button=SDL_BUTTON_LEFT)
{
x=event.button.x;
y=event.button.y;
for(int i=0;i<menunumber;i++)
{
if(x>=position[i].x && x<=position[i].x + position[i].w && y>=position[i].y && y<=position[i].y + position[i].h)
{
// SDL_Delay(500);
SDL_FreeSurface(title);
for(int j=0;j<menunumber;j++)
SDL_FreeSurface( menu[j]);
return i;
}
}
}
break;
}
case(SDL_KEYDOWN):
{
if(event.key.keysym.sym==SDLK_ESCAPE)
{
// SDL_Delay(500);
SDL_FreeSurface(title);
for(int i=0;i<menunumber;i++)
SDL_FreeSurface( menu[i]);
return 0;
}
break;
}
}
}
SDL_Flip(screen);
SDL_Delay(20);
}
}
int showmenu_gameover(SDL_Surface* screen , TTF_Font* font , TTF_Font* titlefont ) //{ "play again","exit"};0,1
{
show_score(screen, font);
show_highscore(screen, font);
int x,y;
const int menunumber=2;
const char* menuitem[menunumber]={ "play again","exit"};//0,1
SDL_Surface* menu[menunumber]={NULL};
bool selected_item[menunumber]={0,0};
SDL_Color color[3]={{255,255,255},{0,130,255},{255,0,0}};
SDL_Surface* title=TTF_RenderText_Solid(titlefont,"game over!!",color[2]);
SDL_Rect positiontitle;
positiontitle.x=300;
positiontitle.y=50;
menu[0]=TTF_RenderText_Solid(font,menuitem[0],color[0]);
menu[1]=TTF_RenderText_Solid(font,menuitem[1],color[0]);
SDL_Rect position[menunumber];
position[0].x=300;
position[0].y=200;
position[0].w=100;
position[0].h=200;
position[1].x=300;
position[1].y=450;
position[1].w=100;
position[1].h=200;
SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 00, 00, 00 ) );
SDL_Event event;
while(1)
{
for(int i=0;i<menunumber;i++)
SDL_BlitSurface(menu[i],NULL,screen,&position[i]);
SDL_BlitSurface(title,NULL,screen,&positiontitle);
while(SDL_PollEvent(&event))
{
switch(event.type)
{
case(SDL_QUIT):
{
SDL_FreeSurface(title);
for(int i=0;i<menunumber;i++)
SDL_FreeSurface(menu[i]);
return 1;
break;
}
case(SDL_MOUSEMOTION):
{
x=event.motion.x;
y=event.motion.y;
for(int i=0; i<menunumber;i++)
{
if( x>=position[i].x && x<=position[i].x+position[i].w && y>=position[i].y && y<=position[i].y+position[i].h )
{
if(selected_item[i]!=1)
{
SDL_FreeSurface(menu[i]);
menu[i]=TTF_RenderText_Solid(font,menuitem[i],color[1]);
selected_item[i]=1;
}
}
else
{
if(selected_item[i]==1)
{
SDL_FreeSurface(menu[i]);
menu[i]=TTF_RenderText_Solid(font,menuitem[i],color[0]);
selected_item[i]=0;
}
}
}
break;
}
case(SDL_MOUSEBUTTONDOWN):
{
if(event.button.button=SDL_BUTTON_LEFT)
{
x=event.button.x;
y=event.button.y;
for(int i=0;i<menunumber;i++)
{
if(x>=position[i].x && x<=position[i].x + position[i].w && y>=position[i].y && y<=position[i].y + position[i].h)
{
// SDL_Delay(500);
SDL_FreeSurface(title);
for(int j=0;j<menunumber;j++)
SDL_FreeSurface( menu[j]);
return i;
}
}
}
break;
}
}
}
SDL_Flip(screen);
}
}
int loadIMG( SDL_Surface *screen , SDL_Surface *image , int image_x , int image_y )
{
SDL_Rect src, dest;
//Construct the source rectangle for our blit
src.x = 0;
src.y = 0;
src.w = image->w; //Use imagew to display the entire width of the image
src.h = image->h; //Use imageh to display the entire height of the image
//Construct the destination rectangle for our blit
dest.x = image_x; //Display the image at the (X,Y) coordinates (100,100)
dest.y = image_y;
dest.w = image->w; //Ensure the destination is large enough for the image's entire width/height
dest.h = image->h;
SDL_BlitSurface(image, &src, screen, &dest);
return 0;
}
void print_board(SDL_Surface *screen,SDL_Surface *stableS,SDL_Surface *brokenS,SDL_Surface *movableS,SDL_Surface *monster1S,SDL_Surface *monster2S,SDL_Surface *monster3S,SDL_Surface *jetS,SDL_Surface *mirrorS,SDL_Surface *springS,SDL_Surface *spring2S,SDL_Surface *brokenbrokenS,SDL_Surface *completlybrokenS)
{
for ( int i=0 ; i<board_n ; i++)
{
switch ( board[i].type )
{
case stable :
loadIMG(screen, stableS, board[i].x, board[i].y);
break;
case broken :
loadIMG(screen, brokenS, board[i].x, board[i].y);
break;
case movable :
loadIMG(screen,movableS, board[i].x, board[i].y);
break;
case spring :
loadIMG(screen, springS,board[i].x, board[i].y-17);
break;
case spring2:
loadIMG(screen, spring2S,board[i].x, board[i].y-34);
break;
case jet:
loadIMG(screen, jetS ,board[i].x, board[i].y-30);
loadIMG(screen, stableS, board[i].x , board[i].y);
break;
case monster1:
loadIMG(screen, monster1S,board[i].x, board[i].y-100);
loadIMG(screen, stableS, board[i].x, board[i].y);
break;
case monster2:
loadIMG(screen, monster2S,board[i].x, board[i].y-100);
loadIMG(screen, stableS, board[i].x, board[i].y);
break;
case monster3:
loadIMG(screen, monster3S,board[i].x, board[i].y-100);
loadIMG(screen, stableS, board[i].x, board[i].y);
break;
case mirror:
if(board[i].x<300)
{
loadIMG(screen, mirrorS,450, board[i].y-50);
board[i].x = 100;
loadIMG(screen, stableS,100, board[i].y);
}
else
{
loadIMG(screen, mirrorS,50, board[i].y-50);
board[i].x = 500;
loadIMG(screen, stableS,500, board[i].y);
}
break;
case brokenbroken:
loadIMG(screen,brokenbrokenS,board[i].x,board[i].y);
break;
case completlybroken:
loadIMG(screen,completlybrokenS,board[i].x,board[i].y);
break;
}
}
}
void init_board()
{
score=0;
for( int i=0 ; i<board_n ; i++)
{
board[i].x = rand()%560+20;
board[i].y = (700/board_n)*i;
board[i].len = 700/board_n;
board[i].vx = 0;
int x=rand()%100;
if( x<20 )
{
if( board[i-1].type!= broken || board[i-2].type!= broken )
{
board[i].type = broken;
}
else
{
board[i].type = stable;
}
}
else
{
if (x<40)
{
board[i].type = spring;
}
else
{
board[i].type = stable;
}
}
if(i == board_n-1 || i == board_n-2)
{
board[i].type = stable;
}
}
}
void move_board (int v)
{
score+=v;
for( int i=board_n ; i>=0 ; i-- )
{
board[i].y+=v;
board[i].x+=board[i].vx;
if (board[i].type==completlybroken)
{
board[i].type = empty;
}
if ( board[i].x<20 || board[i].x>580 )
{
board[i].vx*=-1;
}
int h = 0;
for( int j=0 ; j<=i ; j++)
{
h+=board[j].len;
}
if( board[i].y>=h )
{
board[i+1].x = board[i].x;
board[i+1].y = board[i].y;
board[i+1].type = board[i].type;
board[i+1].len = board[i].len;
board[i+1].vx = board[i].vx;
//board[i].type = empty;
if ( i==0 )
{
board[i].x = rand()%560+20;
board[i].y = 0;
if(board[i].len<60)
board[i].len +=1;
int x=rand()%100;
if( x<15 )
{
if( board[i+1].type!= broken || board[i+2].type!= broken )
{
board[i].type = broken;
board[i].vx = 0;
}
else
{
board[i].type = stable;
board[i].vx = 0;
}
}
else
{
if(x<20)
{
board[i].type = mirror;
board[i].vx = 0;
}
else
{
if( x<40 )
{
board[i].type = movable;
board[i].vx = rand()%5+1;
}
else
{
if ( x<55 )
{
board[i].type = spring;
board[i].vx = 0;
}
else
{
if(x<60)
{
board[i].type = jet;
board[i].vx = 0;
}
else
{
if( x<65 )
{
int a = rand()%3;
switch (a)
{
case 0 :
board[i].type = monster1;
board[i].vx = 0;
break;
case 1 :
board[i].type = monster2;
board[i].vx = 0;
break;
case 2 :
board[i].type = monster3;
board[i].vx = 0;
break;
}
}
else
{
board[i].type = stable;
board[i].vx = 0;
}
}
}
}
}
}
}
}
if (board[i].type==brokenbroken)
{
board[i].type = completlybroken;
}
}
}
void jetmove(SDL_Surface *screen,SDL_Surface *backgroundS,SDL_Surface *doodlejetS,SDL_Surface *stableS,SDL_Surface *brokenS,SDL_Surface *movableS,SDL_Surface *monster1S,SDL_Surface *monster2S,SDL_Surface *monster3S,SDL_Surface *jetS,SDL_Surface *mirrorS,SDL_Surface *springS,SDL_Surface *spring2S,SDL_Surface *brokenbrokenS,SDL_Surface *completlybrokenS)
{
for(int i=0;i<100;i++)
{
loadIMG(screen,backgroundS,0,0);
print_board(screen,stableS,brokenS,movableS,monster1S,monster2S,monster3S,jetS,mirrorS,springS,spring2S,brokenbrokenS,completlybrokenS);
loadIMG(screen,doodlejetS,200,156);
SDL_Flip(screen);
move_board(10);
}
}
bool collision_check(int i,int depth=0)
{
if(doodle.x + doodle.width/4 < board[i].x + board[i].w && doodle.x + doodle.width*3/4 > board[i].x && doodle.y + doodle.height > board[i].y - board[i].h && doodle.y + doodle.height < board[i].y + depth )
{
return true;
}
else
{
return false;
}
}
bool collision(SDL_Surface *screen,SDL_Surface *backgroundS,SDL_Surface *doodlejetS,SDL_Surface *stableS,SDL_Surface *brokenS,SDL_Surface *movableS,SDL_Surface *monster1S,SDL_Surface *monster2S,SDL_Surface *monster3S,SDL_Surface *jetS,SDL_Surface *mirrorS,SDL_Surface *springS,SDL_Surface *spring2S,SDL_Surface *brokenbrokenS,SDL_Surface *completlybrokenS)
{
for (int i = 0; i < board_n; i++)
{
switch (board[i].type)
{
case broken:
board[i].w = 100;
board[i].h = 0;
if(doodle.vy<0)
{
if ( collision_check(i,23))
{
board[i].type = brokenbroken;
}
}
break;
case movable:
case stable:
if(doodle.vy<0)
{
board[i].w = 100;
board[i].h = 0;
if ( collision_check(i,23))
{
doodle.vy = vmax;
}
}
break;
case spring:
if (doodle.vy<0)
{
board[i].w = 100;
board[i].h = 0;
if (collision_check(i,23))
{
doodle.vy = 2*vmax;
board[i].type = spring2;
}
}
break;
case jet:
//count the stable
board[i].w = 25;
board[i].h = 35;
if (collision_check(i,100))
{
jetmove(screen,backgroundS,doodlejetS,stableS,brokenS,movableS,monster1S,monster2S,monster3S,jetS,mirrorS,springS,spring2S,brokenbrokenS,completlybrokenS);
doodle.vy = vmax/2;
doodle.x = 300;
doodle.y = 200;
}
board[i].w = 100;
if (collision_check(i,23))
{
jetmove(screen,backgroundS,doodlejetS,stableS,brokenS,movableS,monster1S,monster2S,monster3S,jetS,mirrorS,springS,spring2S,brokenbrokenS,completlybrokenS);
doodle.vy = vmax/2;
doodle.x = 300;
doodle.y = 200;
}
break;
case monster1:
case monster2:
case monster3:
board[i].w = 100;
board[i].h = 100;
if (collision_check(i,123))
{
if (doodle.vy >= 0)
{
return false;
}
if (doodle.vy < 0);
{
board[i].type = stable;
doodle.vy = vmax;
}
}
break;
case mirror:
board[i].w = 100;
board[i].h = 0;
if (collision_check(i,23))
{
doodle.vy = vmax;
}
if (board[i].x == 100)
{
if(doodle.x + doodle.width/4 < 525 && doodle.x + doodle.width*3/4 > 450 && doodle.y + doodle.height > board[i].y - 50 && doodle.y + doodle.height < board[i].y + 150 )
{
return false;
}
}
if(board[i].x == 500)
{
if(doodle.x + doodle.width/4 < 125 && doodle.x + doodle.width*3/4 > 50 && doodle.y + doodle.height > board[i].y - 50 && doodle.y + doodle.height < board[i].y + 150 )
{
return false;
}
}
break;
}
}
if(doodle.y >700 )
return false;
return true;
}
bool doodle_move(SDL_Surface *screen,SDL_Surface *backgroundS,SDL_Surface *doodlejetS,SDL_Surface *stableS,SDL_Surface *brokenS,SDL_Surface *movableS,SDL_Surface *monster1S,SDL_Surface *monster2S,SDL_Surface *monster3S,SDL_Surface *jetS,SDL_Surface *mirrorS,SDL_Surface *springS,SDL_Surface *spring2S,SDL_Surface *brokenbrokenS,SDL_Surface *completlybrokenS)
{
// jumping up
if (doodle.y < 100 && doodle.vy > 0)
{
move_board(doodle.vy);
}
// jumping down
else
{
move_board(0);
doodle.y -= doodle.vy;
}
if (collision(screen,backgroundS,doodlejetS,stableS,brokenS,movableS,monster1S,monster2S,monster3S,jetS,mirrorS,springS,spring2S,brokenbrokenS,completlybrokenS)==false)
{
return false;
}
doodle.vy += g;
return true;
}
SDL_Surface *init_surface(string filename)
{
bool flag = true;
SDL_Surface *image;
SDL_Surface *temp; //This pointer will temporarily reference our bitmap sprite
SDL_Rect src, dest; //These rectangles will describe the source and destination regions of our blit
//When this program exits, SDL_Quit must be called
atexit(SDL_Quit);
temp = SDL_LoadBMP(filename.c_str());
if (temp == NULL)
{
flag=false;
return NULL;
}
image = SDL_DisplayFormat(temp);
Uint32 colorkey = SDL_MapRGB( image->format, 0xFF, 0xFF, 0xFF );
SDL_SetColorKey( image , SDL_SRCCOLORKEY, colorkey );
SDL_FreeSurface(temp);
return image;
}
int main(int argc, char *argv[])
{
srand(time(0));
bool running ;
SDL_Init(SDL_INIT_EVERYTHING);
TTF_Init();
TTF_Font* font=TTF_OpenFont("zachary.ttf",30);
TTF_Font* titlefont=TTF_OpenFont("zachary.ttf",50);
if (SDL_Init(SDL_INIT_EVERYTHING)!= 0)
{
running = false;
return 1;
}
SDL_Surface *screen;
screen = SDL_SetVideoMode(700 , 700 , 32 , SDL_DOUBLEBUF);
if (screen == NULL)
{
running=false;
return 1;
}
init_board();
SDL_Surface *backgroundS = init_surface("background.bmp");
SDL_Surface *brokenS = init_surface("broken.bmp");
SDL_Surface *stableS = init_surface("stable.bmp");
SDL_Surface *movableS = init_surface("movable.bmp");
SDL_Surface *monster1S = init_surface("monster1.bmp");
SDL_Surface *monster2S = init_surface("monster2.bmp");
SDL_Surface *monster3S = init_surface("monster3.bmp");
SDL_Surface *doodleRS = init_surface("doodle.bmp");
SDL_Surface *doodleLS = init_surface("doodleL.bmp");
SDL_Surface *doodleS = doodleRS;
SDL_Surface *jetS = init_surface("jet.bmp");
SDL_Surface *mirrorS = init_surface("mirror.bmp");
SDL_Surface *springS = init_surface("spring.bmp");
SDL_Surface *spring2S = init_surface("spring2.bmp");
SDL_Surface *brokenbrokenS = init_surface("brokenbroken.bmp");
SDL_Surface *completlybrokenS = init_surface("completelybroken.bmp");
SDL_Surface *doodlejetS = init_surface("doodlejet.bmp");
Uint8 * keystates = SDL_GetKeyState ( NULL );
ifstream readFile;
readFile.open( "doodle/highscore.txt" );
if( readFile.is_open() )
{
while ( !readFile.eof() )
readFile >> highscore;
}
readFile.close( );
SDL_Event occur;
int i=showmenu_start (screen,font,titlefont);
if(i==0)
running=true;
else if(i==1)
{
running=false;
SDL_FreeSurface(screen);
return 1;
}
while(running == true)
{
if ( !SDL_PollEvent ( &occur ) )
{
if ( occur.type == SDL_KEYDOWN )
{
if ( keystates [ SDLK_ESCAPE ] )
{
i=showmenu_pause(screen,font,titlefont);
/* if(i==0) //continue
{
}
*/ if(i==1) //play agian
{
// play again and set everything again
init_board();
running=true;
}
if(i==2) //exit
{
running=false;
SDL_FreeSurface(screen);
return 1;
}
}
if ( keystates [ SDLK_RIGHT ] )
{
doodle.x+=5;
doodleS = doodleRS;
}
if ( keystates [ SDLK_LEFT ] )
{
doodle.x-=5;
doodleS = doodleLS;
}
if(doodle.x>600)
doodle.x=0;
if(doodle.x<0)
doodle.x=600;
}
}
loadIMG(screen , backgroundS , 0 , 0);
print_board(screen,stableS,brokenS,movableS,monster1S,monster2S,monster3S,jetS,mirrorS,springS,spring2S,brokenbrokenS,completlybrokenS);
loadIMG(screen , doodleS , doodle.x , doodle.y);
SDL_Flip(screen);
ofstream writeFile ( "highscore.txt" );
if ( writeFile.is_open() )
{
if (score > highscore)
highscore = score;
writeFile << highscore;
}
writeFile.close();
if(doodle_move(screen,backgroundS,doodlejetS,stableS,brokenS,movableS,monster1S,monster2S,monster3S,jetS,mirrorS,springS,spring2S,brokenbrokenS,completlybrokenS)==false)
{
i=showmenu_gameover(screen,font,titlefont);
if(i==0)
{
// play again and set everything again
init_board();
running=true;
}
if(i==1)
{
running=false;
SDL_FreeSurface(screen);
return 1;
}
}
//SDL_PollEvent(&occur);
if(occur.type==SDL_QUIT)
{
running=false;
SDL_FreeSurface(screen);
return 1;
}
}
TTF_CloseFont(font);
TTF_CloseFont(titlefont);
TTF_Quit();
// SDL_Quit();
SDL_QUIT;
return 0;
}
| [
"noreply@github.com"
] | MinaTahaei.noreply@github.com |
bf36a40120a0e741309355f3598aa9e49335f95b | 440f814f122cfec91152f7889f1f72e2865686ce | /src/game_server/server/extension/welfare/condition.h | ea3a28c4b3fbdd69f66d79bbe6a4c65488ba4392 | [] | no_license | hackerlank/buzz-server | af329efc839634d19686be2fbeb700b6562493b9 | f76de1d9718b31c95c0627fd728aba89c641eb1c | refs/heads/master | 2020-06-12T11:56:06.469620 | 2015-12-05T08:03:25 | 2015-12-05T08:03:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,478 | h | #ifndef __GAME__SERVER__WELFARE__CONDITION__H
#define __GAME__SERVER__WELFARE__CONDITION__H
#include "core/base/noncopyable.h"
#include "core/base/types.h"
#include "entity/achieve_types.h"
#include "game_server/server/event/game_event_types.h"
#include "game_server/server/extension/welfare/achieve_imp_event.h"
namespace game {
namespace server {
namespace welfare {
class Task;
class Condition : public core::Noncopyable {
public:
friend class AchieveImpEvent;
Condition();
virtual ~Condition();
bool Initialize(Task *task, entity::AchieveConditionType::type type, core::uint32 param1, core::uint32 param2,
core::uint32 param3, core::uint32 value = 0);
void Finalize();
// 导出条件变量
bool ExportConditionVar(core::int32 param1, core::int32 ¶m2, core::int32 &value);
entity::AchieveConditionType::type GetType() {
return this->type_;
}
core::int32 GetValue() {
return (core::int32)this->value_;
}
void Clear();
// 条件检测
bool CheckCondition();
// 得到任务对象
Task *GetTask();
// 事件回调
void OnEvent(event::EventType::type type,
const void *data, size_t size);
private:
Task *task_;
AchieveImpEvent imp_;
entity::AchieveConditionType::type type_;
core::uint32 param1_;
core::uint32 param2_;
core::uint32 param3_;
core::uint32 value_;
};
} // namespace welfare
} // namespace server
} // namespace game
#endif // __GAME__SERVER__WELFARE__CONDITION__H
| [
"251729465@qq.com"
] | 251729465@qq.com |
cf61cb09203d4e590f6052c6b424a5388caff6e4 | 1e04bb4c9a4e76d91f068945a2247773d509c472 | /pre/local/include/Inventor/engines/SoElapsedTime.h | 4eb687d551d46132e55b533c2ab76a5cfe5c19f7 | [] | no_license | fuyunfei/deltaba | 9e106a5462782df4fa96776db9aa0a43a6d4490b | 06c65c1ac1a0cf3e532607d9ef9a39a4188ac2bc | refs/heads/master | 2021-01-17T16:19:17.018573 | 2016-09-29T09:03:28 | 2016-09-29T09:03:28 | 68,900,885 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,976 | h | /**************************************************************************\
*
* This file is part of the Coin 3D visualization library.
* Copyright (C) 1998-2006 by Systems in Motion. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* ("GPL") version 2 as published by the Free Software Foundation.
* See the file LICENSE.GPL at the root directory of this source
* distribution for additional information about the GNU GPL.
*
* For using Coin with software that can not be combined with the GNU
* GPL, and for taking advantage of the additional benefits of our
* support services, please contact Systems in Motion about acquiring
* a Coin Professional Edition License.
*
* See http://www.coin3d.org/ for more information.
*
* Systems in Motion, Postboks 1283, Pirsenteret, 7462 Trondheim, NORWAY.
* http://www.sim.no/ sales@sim.no coin-support@coin3d.org
*
\**************************************************************************/
#ifndef COIN_SOELAPSEDTIME_H
#define COIN_SOELAPSEDTIME_H
#include <Inventor/engines/SoSubEngine.h>
#include <Inventor/engines/SoEngineOutput.h>
#include <Inventor/fields/SoSFTime.h>
#include <Inventor/fields/SoSFFloat.h>
#include <Inventor/fields/SoSFBool.h>
#include <Inventor/fields/SoSFTrigger.h>
class COIN_DLL_API SoElapsedTime : public SoEngine {
typedef SoEngine inherited;
SO_ENGINE_HEADER(SoElapsedTime);
public:
static void initClass(void);
SoElapsedTime(void);
SoSFTime timeIn;
SoSFFloat speed;
SoSFBool on;
SoSFBool pause;
SoSFTrigger reset;
SoEngineOutput timeOut; // SoSFTime
protected:
~SoElapsedTime();
virtual void writeInstance(SoOutput * out);
private:
virtual void evaluate(void);
virtual void inputChanged(SoField * which);
SbTime pausetime, lasttime, currtime;
enum {RUNNING, STOPPED, PAUSED} status;
};
#endif // !COIN_SOELAPSEDTIME_H
| [
"fuyunfei1991@gmail.com"
] | fuyunfei1991@gmail.com |
b81c2cd62cfcc9db72a5874138895f68d77fcb0c | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/31/161d3cf8c6a9d4/main.cpp | c7eb82004fc0a88913e7822695854bfce125f2d0 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 411 | cpp | #include <utility>
#include <iostream>
#include <vector>
template<class T> using MyTemplateType = std::vector<T>;
template<class MC>
class MyOtherClass {
public:
template<class T> using MyTType = MyTemplateType<T>;
auto print() {
MyTType<int> myVec = {42};
std::cout << myVec[0] << "\n";
}
};
int main()
{
MyOtherClass<int> x;
x.print();
} | [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
c1944e7652f09d52a2eae0e26b27e6eb72a191ca | 30e2714f4e87e35d2b7ee3d0d0b903da1d4fc6b3 | /src/bitcoinrpc.cpp | 9cc86873033c8a3db70959c251fcca86a0a89c58 | [
"MIT"
] | permissive | CryptorClub/GreenCoin | c715ec6b3ab8c5c81e0631045f0bbb7854ce6554 | 61c2040a4e96a9fdc79191ea22e17f9d0645071d | refs/heads/master | 2021-01-24T13:14:46.267432 | 2018-10-01T19:13:25 | 2018-10-01T19:13:25 | 123,166,654 | 9 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 47,891 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The GreenCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "init.h"
#include "util.h"
#include "sync.h"
#include "ui_interface.h"
#include "base58.h"
#include "bitcoinrpc.h"
#include "db.h"
#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include <list>
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
static std::string strRPCUserColonPass;
// These are created by StartRPCThreads, destroyed in StopRPCThreads
static asio::io_service* rpc_io_service = NULL;
static map<string, boost::shared_ptr<deadline_timer> > deadlineTimers;
static ssl::context* rpc_ssl_context = NULL;
static boost::thread_group* rpc_worker_group = NULL;
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected,
bool fAllowNull)
{
unsigned int i = 0;
BOOST_FOREACH(Value_type t, typesExpected)
{
if (params.size() <= i)
break;
const Value& v = params[i];
if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s, got %s",
Value_type_name[t], Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
i++;
}
}
void RPCTypeCheck(const Object& o,
const map<string, Value_type>& typesExpected,
bool fAllowNull)
{
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
{
const Value& v = find_value(o, t.first);
if (!fAllowNull && v.type() == null_type)
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s for %s, got %s",
Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
}
int64 AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > 21000000.0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
int64 nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64 amount)
{
return (double)amount / (double)COIN;
}
std::string HexBits(unsigned int nBits)
{
union {
int32_t nBits;
char cBits[4];
} uBits;
uBits.nBits = htonl((int32_t)nBits);
return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
}
///
/// Note: This interface may still be subject to change.
///
string CRPCTable::help(string strCommand) const
{
string strRet;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod.find("label") != string::npos)
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
try
{
Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
return tableRPC.help(strCommand);
}
Value stop(const Array& params, bool fHelp)
{
// Accept the deprecated and ignored 'detach' boolean argument
if (fHelp || params.size() > 1)
throw runtime_error(
"stop\n"
"Stop GreenCoin server.");
// Shutdown will take long enough that the response should get back
StartShutdown();
return "GreenCoin server stopping";
}
//
// Call Table
//
static const CRPCCommand vRPCCommands[] =
{ // name actor (function) okSafeMode threadSafe
// ------------------------ ----------------------- ---------- ----------
{ "help", &help, true, true },
{ "stop", &stop, true, true },
{ "getblockcount", &getblockcount, true, false },
{ "getbestblockhash", &getbestblockhash, true, false },
{ "getconnectioncount", &getconnectioncount, true, false },
{ "getpeerinfo", &getpeerinfo, true, false },
{ "addnode", &addnode, true, true },
{ "getaddednodeinfo", &getaddednodeinfo, true, true },
{ "getdifficulty", &getdifficulty, true, false },
{ "getgenerate", &getgenerate, true, false },
{ "setgenerate", &setgenerate, true, false },
{ "gethashespersec", &gethashespersec, true, false },
{ "getinfo", &getinfo, true, false },
{ "getmininginfo", &getmininginfo, true, false },
{ "getnewaddress", &getnewaddress, true, false },
{ "getaccountaddress", &getaccountaddress, true, false },
{ "setaccount", &setaccount, true, false },
{ "getaccount", &getaccount, false, false },
{ "getaddressesbyaccount", &getaddressesbyaccount, true, false },
{ "sendtoaddress", &sendtoaddress, false, false },
{ "getreceivedbyaddress", &getreceivedbyaddress, false, false },
{ "getreceivedbyaccount", &getreceivedbyaccount, false, false },
{ "listreceivedbyaddress", &listreceivedbyaddress, false, false },
{ "listreceivedbyaccount", &listreceivedbyaccount, false, false },
{ "backupwallet", &backupwallet, true, false },
{ "keypoolrefill", &keypoolrefill, true, false },
{ "walletpassphrase", &walletpassphrase, true, false },
{ "walletpassphrasechange", &walletpassphrasechange, false, false },
{ "walletlock", &walletlock, true, false },
{ "encryptwallet", &encryptwallet, false, false },
{ "validateaddress", &validateaddress, true, false },
{ "getbalance", &getbalance, false, false },
{ "move", &movecmd, false, false },
{ "sendfrom", &sendfrom, false, false },
{ "sendmany", &sendmany, false, false },
{ "addmultisigaddress", &addmultisigaddress, false, false },
{ "createmultisig", &createmultisig, true, true },
{ "getrawmempool", &getrawmempool, true, false },
{ "getblock", &getblock, false, false },
{ "getblockhash", &getblockhash, false, false },
{ "gettransaction", &gettransaction, false, false },
{ "listtransactions", &listtransactions, false, false },
{ "listaddressgroupings", &listaddressgroupings, false, false },
{ "signmessage", &signmessage, false, false },
{ "verifymessage", &verifymessage, false, false },
{ "getwork", &getwork, true, false },
{ "listaccounts", &listaccounts, false, false },
{ "settxfee", &settxfee, false, false },
{ "getblocktemplate", &getblocktemplate, true, false },
{ "submitblock", &submitblock, false, false },
{ "listsinceblock", &listsinceblock, false, false },
{ "dumpprivkey", &dumpprivkey, true, false },
{ "dumpwallet", &dumpwallet, true, false },
{ "importprivkey", &importprivkey, false, false },
{ "importwallet", &importwallet, false, false },
{ "listunspent", &listunspent, false, false },
{ "getrawtransaction", &getrawtransaction, false, false },
{ "createrawtransaction", &createrawtransaction, false, false },
{ "decoderawtransaction", &decoderawtransaction, false, false },
{ "signrawtransaction", &signrawtransaction, false, false },
{ "sendrawtransaction", &sendrawtransaction, false, false },
{ "gettxoutsetinfo", &gettxoutsetinfo, true, false },
{ "gettxout", &gettxout, true, false },
{ "lockunspent", &lockunspent, false, false },
{ "listlockunspent", &listlockunspent, false, false },
{ "verifychain", &verifychain, true, false },
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
}
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: greencoin-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: greencoin-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
const char *cStatus;
if (nStatus == HTTP_OK) cStatus = "OK";
else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %"PRIszu"\r\n"
"Content-Type: application/json\r\n"
"Server: greencoin-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time().c_str(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
FormatFullVersion().c_str(),
strMsg.c_str());
}
bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto,
string& http_method, string& http_uri)
{
string str;
getline(stream, str);
// HTTP request line is space-delimited
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return false;
// HTTP methods permitted: GET, POST
http_method = vWords[0];
if (http_method != "GET" && http_method != "POST")
return false;
// HTTP URI must be an absolute path, relative to current host
http_uri = vWords[1];
if (http_uri.size() == 0 || http_uri[0] != '/')
return false;
// parse proto, if present
string strProto = "";
if (vWords.size() > 2)
strProto = vWords[2];
proto = 0;
const char *ver = strstr(strProto.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return true;
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
while (true)
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTPMessage(std::basic_istream<char>& stream, map<string,
string>& mapHeadersRet, string& strMessageRet,
int nProto)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read header
int nLen = ReadHTTPHeaders(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return HTTP_INTERNAL_SERVER_ERROR;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return HTTP_OK;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
return TimingResistantEqual(strUserPass, strRPCUserColonPass);
}
//
// JSON-RPC protocol. GreenCoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
int code = find_value(objError, "code").get_int();
if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
bool ClientAllowed(const boost::asio::ip::address& address)
{
// Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
if (address.is_v6()
&& (address.to_v6().is_v4_compatible()
|| address.to_v6().is_v4_mapped()))
return ClientAllowed(address.to_v6().to_v4());
if (address == asio::ip::address_v4::loopback()
|| address == asio::ip::address_v6::loopback()
|| (address.is_v4()
// Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
return true;
const string strAddress = address.to_string();
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
//
// IOStream device that speaks SSL but can also speak non-SSL
//
template <typename Protocol>
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
public:
SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
stream.handshake(role);
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(stream.get_io_service());
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
stream.lowest_layer().connect(*endpoint_iterator++, error);
}
if (error)
return false;
return true;
}
private:
bool fNeedHandshake;
bool fUseSSL;
asio::ssl::stream<typename Protocol::socket>& stream;
};
class AcceptedConnection
{
public:
virtual ~AcceptedConnection() {}
virtual std::iostream& stream() = 0;
virtual std::string peer_address_to_string() const = 0;
virtual void close() = 0;
};
template <typename Protocol>
class AcceptedConnectionImpl : public AcceptedConnection
{
public:
AcceptedConnectionImpl(
asio::io_service& io_service,
ssl::context &context,
bool fUseSSL) :
sslStream(io_service, context),
_d(sslStream, fUseSSL),
_stream(_d)
{
}
virtual std::iostream& stream()
{
return _stream;
}
virtual std::string peer_address_to_string() const
{
return peer.address().to_string();
}
virtual void close()
{
_stream.close();
}
typename Protocol::endpoint peer;
asio::ssl::stream<typename Protocol::socket> sslStream;
private:
SSLIOStreamDevice<Protocol> _d;
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
};
void ServiceConnection(AcceptedConnection *conn);
// Forward declaration required for RPCListen
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error);
/**
* Sets up I/O resources to accept and handle a new connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL)
{
// Accept connection
AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
acceptor->async_accept(
conn->sslStream.lowest_layer(),
conn->peer,
boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
acceptor,
boost::ref(context),
fUseSSL,
conn,
boost::asio::placeholders::error));
}
/**
* Accept and handle incoming connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error)
{
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
if (error != asio::error::operation_aborted && acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
// TODO: Actually handle errors
if (error)
{
delete conn;
}
// Restrict callers by IP. It is important to
// do this before starting client thread, to filter out
// certain DoS and misbehaving clients.
else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
delete conn;
}
else {
ServiceConnection(conn);
conn->close();
delete conn;
}
}
void StartRPCThreads()
{
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if (((mapArgs["-rpcpassword"] == "") ||
(mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) && Params().RequireRPCPassword())
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use greencoind";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
uiInterface.ThreadSafeMessageBox(strprintf(
_("%s, you must set a rpcpassword in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=greencoinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"GreenCoin Alert\" admin@foo.com\n"),
strWhatAmI.c_str(),
GetConfigFile().string().c_str(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
assert(rpc_io_service == NULL);
rpc_io_service = new asio::io_service();
rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23);
const bool fUseSSL = GetBoolArg("-rpcssl", false);
if (fUseSSL)
{
rpc_ssl_context->set_options(ssl::context::no_sslv2);
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string());
else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem);
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str());
}
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
const bool loopback = !mapArgs.count("-rpcallowip");
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", Params().RPCPort()));
boost::system::error_code v6_only_error;
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
bool fListening = false;
std::string strerr;
try
{
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
// Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what());
}
try {
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
if (!fListening || loopback || v6_only_error)
{
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
endpoint.address(bindAddress);
acceptor.reset(new ip::tcp::acceptor(*rpc_io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
}
if (!fListening) {
uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
rpc_worker_group = new boost::thread_group();
for (int i = 0; i < GetArg("-rpcthreads", 4); i++)
rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
}
void StopRPCThreads()
{
if (rpc_io_service == NULL) return;
deadlineTimers.clear();
rpc_io_service->stop();
rpc_worker_group->join_all();
delete rpc_worker_group; rpc_worker_group = NULL;
delete rpc_ssl_context; rpc_ssl_context = NULL;
delete rpc_io_service; rpc_io_service = NULL;
}
void RPCRunHandler(const boost::system::error_code& err, boost::function<void(void)> func)
{
if (!err)
func();
}
void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64 nSeconds)
{
assert(rpc_io_service != NULL);
if (deadlineTimers.count(name) == 0)
{
deadlineTimers.insert(make_pair(name,
boost::shared_ptr<deadline_timer>(new deadline_timer(*rpc_io_service))));
}
deadlineTimers[name]->expires_from_now(posix_time::seconds(nSeconds));
deadlineTimers[name]->async_wait(boost::bind(RPCRunHandler, _1, func));
}
class JSONRequest
{
public:
Value id;
string strMethod;
Array params;
JSONRequest() { id = Value::null; }
void parse(const Value& valRequest);
};
void JSONRequest::parse(const Value& valRequest)
{
// Parse request
if (valRequest.type() != obj_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
const Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getblocktemplate")
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(request, "params");
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
}
static Object JSONRPCExecOne(const Value& req)
{
Object rpc_result;
JSONRequest jreq;
try {
jreq.parse(req);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
}
catch (Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null,
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
{
Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
}
void ServiceConnection(AcceptedConnection *conn)
{
bool fRun = true;
while (fRun)
{
int nProto = 0;
map<string, string> mapHeaders;
string strRequest, strMethod, strURI;
// Read HTTP request line
if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI))
break;
// Read HTTP message headers and body
ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto);
if (strURI != "/") {
conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush;
break;
}
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (!HTTPAuthorized(mapHeaders))
{
printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
/* Deter brute-forcing short passwords.
If this results in a DOS the user really
shouldn't have their RPC port exposed.*/
if (mapArgs["-rpcpassword"].size() < 20)
MilliSleep(250);
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (mapHeaders["connection"] == "close")
fRun = false;
JSONRequest jreq;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
string strReply;
// singleton request
if (valRequest.type() == obj_type) {
jreq.parse(valRequest);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, Value::null, jreq.id);
// array of requests
} else if (valRequest.type() == array_type)
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
}
catch (Object& objError)
{
ErrorReply(conn->stream(), objError, jreq.id);
break;
}
catch (std::exception& e)
{
ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
break;
}
}
}
json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
{
// Find method
const CRPCCommand *pcmd = tableRPC[strMethod];
if (!pcmd)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode", false) &&
!pcmd->okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
{
if (pcmd->threadSafe)
result = pcmd->actor(params, false);
else {
LOCK2(cs_main, pwalletMain->cs_wallet);
result = pcmd->actor(params, false);
}
}
return result;
}
catch (std::exception& e)
{
throw JSONRPCError(RPC_MISC_ERROR, e.what());
}
}
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl", false);
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(Params().RPCPort()))))
throw runtime_error("couldn't connect to server");
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive HTTP reply status
int nProto = 0;
int nStatus = ReadHTTPStatus(stream, nProto);
// Receive HTTP reply message headers and body
map<string, string> mapHeaders;
string strReply;
ReadHTTPMessage(stream, mapHeaders, strReply, nProto);
if (nStatus == HTTP_UNAUTHORIZED)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
{
if (fAllowNull && value.type() == null_type)
return;
if (value.type() == str_type)
{
// reinterpret string as unquoted json value
Value value2;
string strJSON = value.get_str();
if (!read_string(strJSON, value2))
throw runtime_error(string("Error parsing JSON:")+strJSON);
ConvertTo<T>(value2, fAllowNull);
value = value2;
}
else
{
value = value.get_value<T>();
}
}
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
BOOST_FOREACH(const std::string ¶m, strParams)
params.push_back(param);
int n = params.size();
//
// Special case non-string parameter types
//
if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
if (strMethod == "gettxout" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "verifychain" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "verifychain" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "keypoolrefill" && n > 0) ConvertTo<boost::int64_t>(params[0]);
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...) {
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
#ifdef TEST
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
try
{
if (argc >= 2 && string(argv[1]) == "-server")
{
printf("server ready\n");
ThreadRPCServer(NULL);
}
else
{
return CommandLineRPC(argc, argv);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
PrintException(&e, "main()");
} catch (...) {
PrintException(NULL, "main()");
}
return 0;
}
#endif
const CRPCTable tableRPC;
| [
"belvederskij@gmail.com"
] | belvederskij@gmail.com |
b1b62389489267aea722c819829efc3e55540105 | d229621f907e1bbe255ac32d42eeeabfef70801f | /SPOJ/CHOCOLATE/main.cpp | c2d1e76420b7ee0ddd7b1f04d79e7be7497adb00 | [] | no_license | geekswaroop/Competitive-Coding-Solutions | df8f8dafedab0aac1d081a6fcb6c099395b47765 | 25124a3ce58b081c6f54c1442855489038315e78 | refs/heads/master | 2020-05-14T15:08:29.659499 | 2019-11-04T11:55:49 | 2019-11-04T11:55:49 | 181,846,111 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 477 | cpp | #include <iostream>
using namespace std;
int main()
{
int t,m,n,sum_x,sum_y,i,temp;
cin>>t;
while(t--)
{ sum_x=0;sum_y=0;
cin>>m>>n;
for(i=0;i<m-1;i++)
{
cin>>temp;
sum_x+=temp;
}
for(i=0;i<n-1;i++)
{
cin>>temp;
sum_y+=temp;
}
int ans1=(sum_y+n*sum_x);
int ans2=(sum_x+m*sum_y);
cout<<min(ans1,ans2)<<endl;
}
return 0;
}
| [
"kkrishnaswaroop99@gmail.com"
] | kkrishnaswaroop99@gmail.com |
da51487de2ee18c7712a496f648eff8eb0e3caf7 | 8681c91756b2941035db515b621e32480d35ec11 | /xr_3da/xrGame/script_game_object2.cpp | d63126bd81867f5c0146ce245b0cee912206aac3 | [] | no_license | MaoZeDongXiJinping/xray-2212 | 1f3206c803c5fbc506114606424e2e834ffc51c0 | e143f01368c67b997f4be0dcdafb22f792bf485c | refs/heads/main | 2023-07-17T09:53:01.301852 | 2021-09-06T17:00:23 | 2021-09-06T17:00:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,632 | cpp | ////////////////////////////////////////////////////////////////////////////
// Module : script_game_object_script2.cpp
// Created : 17.11.2004
// Modified : 17.11.2004
// Author : Dmitriy Iassenev
// Description : Script game object class script export
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "script_game_object.h"
#include "script_game_object_impl.h"
#include "ai_space.h"
#include "script_engine.h"
#include "explosive.h"
#include "script_zone.h"
#include "object_handler.h"
#include "script_hit.h"
#include "../skeletoncustom.h"
#include "pda.h"
#include "InfoPortion.h"
#include "memory_manager.h"
#include "ai_phrasedialogmanager.h"
#include "net_utils.h"
#include "xrMessages.h"
#include "custommonster.h"
#include "memory_manager.h"
#include "visual_memory_manager.h"
#include "sound_memory_manager.h"
#include "hit_memory_manager.h"
#include "enemy_manager.h"
#include "item_manager.h"
#include "memory_space.h"
void CScriptGameObject::explode (u32 level_time)
{
CExplosive *explosive = smart_cast<CExplosive*>(&object());
if (object().H_Parent())
{
ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CExplosive : cannot explode object wiht parent!");
return;
}
if (!explosive)
ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CExplosive : cannot access class member explode!");
else {
Fvector normal;
explosive->FindNormal(normal);
explosive->SetCurrentParentID(object().ID());
explosive->GenExplodeEvent(object().Position(), normal);
}
}
bool CScriptGameObject::active_zone_contact (u16 id)
{
CScriptZone *script_zone = smart_cast<CScriptZone*>(&object());
if (!script_zone) {
ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CScriptZone : cannot access class member active_zone_contact!");
return (false);
}
return (script_zone->active_contact(id));
}
CScriptGameObject *CScriptGameObject::best_weapon()
{
CObjectHandler *object_handler = smart_cast<CObjectHandler*>(&object());
if (!object_handler) {
ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CScriptEntity : cannot access class member best_weapon!");
return (0);
}
else {
CGameObject *game_object = object_handler->best_weapon() ? &object_handler->best_weapon()->object() : 0;
return (game_object ? game_object->lua_game_object() : 0);
}
}
void CScriptGameObject::set_item (MonsterSpace::EObjectAction object_action)
{
CObjectHandler *object_handler = smart_cast<CObjectHandler*>(&object());
if (!object_handler)
ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CObjectHandler : cannot access class member set_item!");
else
object_handler->set_goal(object_action);
}
void CScriptGameObject::set_item (MonsterSpace::EObjectAction object_action, CScriptGameObject *lua_game_object)
{
CObjectHandler *object_handler = smart_cast<CObjectHandler*>(&object());
if (!object_handler)
ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CObjectHandler : cannot access class member set_item!");
else
object_handler->set_goal(object_action,lua_game_object ? &lua_game_object->object() : 0);
}
void CScriptGameObject::set_item(MonsterSpace::EObjectAction object_action, CScriptGameObject *lua_game_object, u32 queue_size)
{
CObjectHandler *object_handler = smart_cast<CObjectHandler*>(&object());
if (!object_handler)
ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CObjectHandler : cannot access class member set_item!");
else
object_handler->set_goal(object_action,lua_game_object ? &lua_game_object->object() : 0, queue_size);
}
void CScriptGameObject::set_item(MonsterSpace::EObjectAction object_action, CScriptGameObject *lua_game_object, u32 queue_size, u32 queue_interval)
{
CObjectHandler *object_handler = smart_cast<CObjectHandler*>(&object());
if (!object_handler)
ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CObjectHandler : cannot access class member set_item!");
else
object_handler->set_goal(object_action,lua_game_object ? &lua_game_object->object() : 0, queue_size, queue_interval);
}
void CScriptGameObject::Hit(CScriptHit *tpLuaHit)
{
CScriptHit &tLuaHit = *tpLuaHit;
NET_Packet P;
object().u_EventGen(P,GE_HIT,object().ID());
P.w_u16 (u16(tLuaHit.m_tpDraftsman->ID()));
P.w_u16 (0);
P.w_dir (tLuaHit.m_tDirection);
P.w_float (tLuaHit.m_fPower);
CKinematics *V = smart_cast<CKinematics*>(object().Visual());
VERIFY (V);
if (xr_strlen (tLuaHit.m_caBoneName))
P.w_s16 (V->LL_BoneID(tLuaHit.m_caBoneName));
else
P.w_s16 (s16(0));
P.w_vec3 (Fvector().set(0,0,0));
P.w_float (tLuaHit.m_fImpulse);
P.w_u16 (u16(tLuaHit.m_tHitType));
object().u_EventSend(P);
}
#pragma todo("Dima to Dima : find out why user defined conversion operators work incorrect")
CScriptGameObject::operator CObject*()
{
return (&object());
}
void CScriptGameObject::set_character_pda_info (LPCSTR info_id)
{
CInventoryOwner *pInventoryOwner = smart_cast<CInventoryOwner*>(&object()); VERIFY(pInventoryOwner);
CPda* pda = pInventoryOwner->GetPDA(); VERIFY(pda);
pda->SetInfoPortion(CInfoPortion::IdToIndex(info_id));
}
LPCSTR CScriptGameObject::get_character_pda_info ()
{
CInventoryOwner *pInventoryOwner = smart_cast<CInventoryOwner*>(&object()); VERIFY(pInventoryOwner);
CPda* pda = pInventoryOwner->GetPDA(); VERIFY(pda);
return *CInfoPortion::IndexToId(pda->GetInfoPortion());
}
void CScriptGameObject::set_pda_info (LPCSTR info_id)
{
CPda* pda = smart_cast<CPda*>(&object()); VERIFY(pda);
pda->SetInfoPortion(CInfoPortion::IdToIndex(info_id));
}
LPCSTR CScriptGameObject::get_pda_info ()
{
CPda* pda = smart_cast<CPda*>(&object()); VERIFY(pda);
return *CInfoPortion::IndexToId(pda->GetInfoPortion());
}
const MemorySpace::CHitObject *CScriptGameObject::GetBestHit () const
{
const CCustomMonster *monster = smart_cast<const CCustomMonster*>(&object());
if (!monster)
return (0);
return (monster->memory().hit().hit());
}
const MemorySpace::CSoundObject *CScriptGameObject::GetBestSound () const
{
const CCustomMonster *monster = smart_cast<const CCustomMonster*>(&object());
if (!monster)
return (0);
return (monster->memory().sound().sound());
}
CScriptGameObject *CScriptGameObject::GetBestEnemy()
{
const CCustomMonster *monster = smart_cast<const CCustomMonster*>(&object());
if (!monster)
return (0);
if (monster->memory().enemy().selected())
return (monster->memory().enemy().selected()->lua_game_object());
return (0);
}
CScriptGameObject *CScriptGameObject::GetBestItem()
{
const CCustomMonster *monster = smart_cast<const CCustomMonster*>(&object());
if (!monster)
return (0);
if (monster->memory().item().selected())
return (monster->memory().item().selected()->lua_game_object());
return (0);
}
MemorySpace::CMemoryInfo *CScriptGameObject::memory(const CScriptGameObject &lua_game_object)
{
CCustomMonster *monster = smart_cast<CCustomMonster*>(&object());
if (!monster) {
ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CScriptEntity : cannot access class member memory!");
return (0);
}
else
return (xr_new<MemorySpace::CMemoryInfo>(monster->memory().memory(&lua_game_object.object())));
}
void CScriptGameObject::enable_memory_object (CScriptGameObject *game_object, bool enable)
{
CCustomMonster *monster = smart_cast<CCustomMonster*>(&object());
if (!monster)
ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CGameObject : cannot access class member enable_memory_object!");
else
monster->memory().enable (&game_object->object(),enable);
}
const xr_vector<CNotYetVisibleObject> &CScriptGameObject::not_yet_visible_objects() const
{
CCustomMonster *monster = smart_cast<CCustomMonster*>(&object());
if (!monster) {
ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CGameObject : cannot access class member not_yet_visible_objects!");
NODEFAULT;
}
return (monster->memory().visual().not_yet_visible_objects());
}
float CScriptGameObject::visibility_threshold () const
{
CCustomMonster *monster = smart_cast<CCustomMonster*>(&object());
if (!monster) {
ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CGameObject : cannot access class member visibility_threshold!");
NODEFAULT;
}
return (monster->memory().visual().visibility_threshold());
}
void CScriptGameObject::enable_vision (bool value)
{
CCustomMonster *monster = smart_cast<CCustomMonster*>(&object());
if (!monster) {
ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CVisualMemoryManager : cannot access class member enable_vision!");
return;
}
monster->memory().visual().enable (value);
}
bool CScriptGameObject::vision_enabled () const
{
CCustomMonster *monster = smart_cast<CCustomMonster*>(&object());
if (!monster) {
ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CVisualMemoryManager : cannot access class member vision_enabled!");
return (false);
}
return (monster->memory().visual().enabled());
}
void CScriptGameObject::set_sound_threshold (float value)
{
CCustomMonster *monster = smart_cast<CCustomMonster*>(&object());
if (!monster) {
ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CSoundMemoryManager : cannot access class member set_sound_threshold!");
return;
}
monster->memory().sound().set_threshold (value);
}
void CScriptGameObject::restore_sound_threshold ()
{
CCustomMonster *monster = smart_cast<CCustomMonster*>(&object());
if (!monster) {
ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeError,"CSoundMemoryManager : cannot access class member restore_sound_threshold!");
return;
}
monster->memory().sound().restore_threshold ();
}
void CScriptGameObject::SetStartDialog(LPCSTR dialog_id)
{
CAI_PhraseDialogManager* pDialogManager = smart_cast<CAI_PhraseDialogManager*>(&object());
if(!pDialogManager) return;
pDialogManager->SetStartDialog(dialog_id);
}
void CScriptGameObject::GetStartDialog ()
{
CAI_PhraseDialogManager* pDialogManager = smart_cast<CAI_PhraseDialogManager*>(&object());
if(!pDialogManager) return;
pDialogManager->GetStartDialog();
}
void CScriptGameObject::RestoreDefaultStartDialog()
{
CAI_PhraseDialogManager* pDialogManager = smart_cast<CAI_PhraseDialogManager*>(&object());
if(!pDialogManager) return;
pDialogManager->RestoreDefaultStartDialog();
} | [
"47507219+ugozapad@users.noreply.github.com"
] | 47507219+ugozapad@users.noreply.github.com |
d8ddaf5004982e7a5a371966b4c6ce1cf6fd8002 | bef7d0477a5cac485b4b3921a718394d5c2cf700 | /nanobots/src/demo/entity/EntityManager.h | 2165091a42211829d0ed9e50d837149aebea3165 | [
"MIT"
] | permissive | TomLeeLive/aras-p-dingus | ed91127790a604e0813cd4704acba742d3485400 | 22ef90c2bf01afd53c0b5b045f4dd0b59fe83009 | refs/heads/master | 2023-04-19T20:45:14.410448 | 2011-10-04T10:51:13 | 2011-10-04T10:51:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,705 | h | #ifndef __ENTITY_MANAGER_H
#define __ENTITY_MANAGER_H
#include "ActorEntity.h"
#include "PointEntity.h"
#include "StreamEntity.h"
#include "../game/GameState.h"
#include <dingus/math/Line3.h>
class CAttackEntityManager;
namespace dingus {
class CUIDialog;
};
class CEntityManager {
public:
typedef std::map<int,CActorEntity*> TActorEntityMap;
public:
CEntityManager();
~CEntityManager();
void update( const SLine3& mouseRay, float timeAlpha );
void render( eRenderMode rm, bool entityBlobs, bool thirdPerson, float timeAlpha );
void renderMinimap();
void onMouseClick();
void renderLabels( CUIDialog& dlg );
int getSelectedEntityID() const { return mSelectedEntityID; }
void setSelectedEntityID( int i ) { mSelectedEntityID = i; }
const CActorEntity* getActorEntityByID( int id ) const {
if( id == -1 )
return NULL;
TActorEntityMap::const_iterator it = mActorEntities.find( id );
return (it==mActorEntities.end()) ? NULL : it->second;
}
CActorEntity* getActorEntityByID( int id ) {
if( id == -1 )
return NULL;
TActorEntityMap::iterator it = mActorEntities.find( id );
return (it==mActorEntities.end()) ? NULL : it->second;
}
void onNewGameEntity( const CGameEntity& e );
void onNewInjectionPoint( const CGameMap::SPoint& pt );
void onHideInjectionPoint( const CGameMap::SPoint& pt );
private:
int getCollidedEntityID( const SLine3& ray ) const;
private:
TActorEntityMap mActorEntities;
std::vector<CPointEntity*> mPointEntities;
std::vector<CStreamEntity*> mStreamEntities;
CAttackEntityManager* mAttackManager;
int mLastMouseEntityID;
int mSelectedEntityID;
};
#endif
| [
"aras@unity3d.com"
] | aras@unity3d.com |
f07fd9f2e449037de36699c85b9dbc0efee589a1 | 77170cbcd2c87952763f770d50abd2d8b671f9d2 | /aws-cpp-sdk-rds/source/model/DescribeOptionGroupOptionsRequest.cpp | 36937c8e3138ccdcaca43a2db102a3732408d820 | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | bittorrent/aws-sdk-cpp | 795f1cdffb92f6fccb4396d8f885f7bf99829ce7 | 3f84fee22a0f4d5926aadf8d3303ea15a76421fd | refs/heads/master | 2020-12-03T00:41:12.194688 | 2016-03-04T01:41:51 | 2016-03-04T01:41:51 | 53,150,048 | 1 | 1 | null | 2016-03-04T16:43:12 | 2016-03-04T16:43:12 | null | UTF-8 | C++ | false | false | 1,909 | cpp | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/rds/model/DescribeOptionGroupOptionsRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
using namespace Aws::RDS::Model;
using namespace Aws::Utils;
DescribeOptionGroupOptionsRequest::DescribeOptionGroupOptionsRequest() :
m_engineNameHasBeenSet(false),
m_majorEngineVersionHasBeenSet(false),
m_filtersHasBeenSet(false),
m_maxRecords(0),
m_maxRecordsHasBeenSet(false),
m_markerHasBeenSet(false)
{
}
Aws::String DescribeOptionGroupOptionsRequest::SerializePayload() const
{
Aws::StringStream ss;
ss << "Action=DescribeOptionGroupOptions&";
if(m_engineNameHasBeenSet)
{
ss << "EngineName=" << StringUtils::URLEncode(m_engineName.c_str()) << "&";
}
if(m_majorEngineVersionHasBeenSet)
{
ss << "MajorEngineVersion=" << StringUtils::URLEncode(m_majorEngineVersion.c_str()) << "&";
}
if(m_filtersHasBeenSet)
{
unsigned filtersCount = 1;
for(auto& item : m_filters)
{
item.OutputToStream(ss, "Filters.member.", filtersCount, "");
filtersCount++;
}
}
if(m_maxRecordsHasBeenSet)
{
ss << "MaxRecords=" << m_maxRecords << "&";
}
if(m_markerHasBeenSet)
{
ss << "Marker=" << StringUtils::URLEncode(m_marker.c_str()) << "&";
}
ss << "Version=2014-10-31";
return ss.str();
}
| [
"henso@amazon.com"
] | henso@amazon.com |
a5fad3eeecc30c3ba0a0eb813d9955af7b57a3e5 | fd07d0fe9801f30642e034f31f67674fd6c13efa | /DragHandler.cpp | 09594afb5bdeb8f5c3e9fefb679121048df0869d | [] | no_license | kmichalk/LSystemGenerator | 2d28818d4fa1805ee54289d744bbaa2c3cee853d | 6627e86636544c1d197ffb4924e8c60bbb790db1 | refs/heads/master | 2021-04-15T16:34:18.666339 | 2018-03-25T20:59:03 | 2018-03-25T20:59:03 | 126,738,279 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 699 | cpp | #include "DragHandler.h"
#include "Plot.h"
DragHandler::DragHandler(Plot* parent):
parent(parent),
grabOffset(0,0),
grabMousePos(0,0),
prevShape(),
dragging(false)
{
}
///////////////////////////////////////////////////////////////////////////////////////////////
DragHandler::~DragHandler() {
}
///////////////////////////////////////////////////////////////////////////////////////////////
void DragHandler::grab() {
grabOffset = parent->getOrigin();
grabMousePos = QCursor::pos();
dragging = true;
}
///////////////////////////////////////////////////////////////////////////////////////////////
void DragHandler::release() {
dragging = false;
}
| [
"noreply@github.com"
] | kmichalk.noreply@github.com |
b62d3b56cc2ff39a4fa3c3f3bb417631d3b600ea | b6a7de66ab585eca660a032f23b05abf299a5628 | /include/helpers/file.hpp | 7191ba49475143ca3cb1f35a145719b2ef286588 | [
"MIT"
] | permissive | ladevieq/dadengine | 6ca641eaa6cff6eb7dd9ad93eeb9e1ec22af2621 | 1e97e86996571c8ba1efec72b0f0e914d86533d3 | refs/heads/master | 2023-01-15T01:12:37.219547 | 2020-11-17T16:49:17 | 2020-11-17T16:49:17 | 102,177,636 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 167 | hpp | #pragma once
#include <cstdint>
#include <filesystem>
#include <vector>
namespace DadEngine
{
std::vector<uint8_t> ReadFile(std::filesystem::path _fullpath);
}
| [
"ladevie.quentin@gmail.com"
] | ladevie.quentin@gmail.com |
cbce16f3041e49dcc1ed5f5e8e55ed8c4e233313 | 510749e749d86c5586d44a890df595228b573454 | /Attendance management system/Attendance management system/Attendance management system.cpp | fe4c53d8d73c7380b581b849ca20061f34947f29 | [] | no_license | hieuhdh/Attendance-management-system | 26d8d4cc44732e938d88e2c22935eaa15e1b847b | 1d6e6abba5f97692784cde6891cd1a00fa91e229 | refs/heads/master | 2023-06-23T06:14:36.866430 | 2021-07-20T17:03:37 | 2021-07-20T17:03:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 59 | cpp | #include"manage.h"
int main() {
manage MN;
MN.run();
} | [
"hoangdinhhieupk@gmail.com"
] | hoangdinhhieupk@gmail.com |
d545194dd906eee3273469fbf0b273144bbe5110 | a869b9816760f1426513f3a5c27c103ab0772eea | /3/Vowel3.cpp | 31ec976a2ceca9ecd0fddb9289814c3c2801ec26 | [] | no_license | notrangerjoe/cppclass | 0b9968573b23cfdaca5b6a5b23538593dafd4fbe | ad8766ed3cdbdcaafa83c1dd19194c64d3c2f16e | refs/heads/master | 2021-01-02T09:38:11.788022 | 2015-02-10T20:00:41 | 2015-02-10T20:00:41 | 30,611,567 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,838 | cpp | /************************************************************************
* Name: Mark Neves CSC 155
* Date: 1/30/2015 Lab 3
*************************************************************************
* Statement: Determine and display the number of characters and number of
vowels in a string
* Specifications:
* Input - String
* Output - Input string, number of characters in the string, number of
each vowel in the string
************************************************************************/
#include <iostream>
#include <string>
using namespace std;
int main()
{
//declartion of variables
string input_string;
int a_count, e_count, i_count, o_count, u_count, char_count;
//set int values to 0
a_count = e_count = i_count = o_count = u_count = char_count = 0;
//descriptive message
cout << "This program asks the user for a sentence," << endl
<< "searches the sentence for all vowels," << endl
<< "and displays the number of times each" << endl
<< "vowel appears in the sentence." << endl;
//input
cout << "Enter a sentence to search: ";
//put input into variable
getline(cin, input_string);
//get length of input_string and store it
char_count = input_string.length();
//find the number of each vowel in input_string
for (int i=0; i < char_count; i++)
{
switch(input_string[i])
{
case 'a':
case 'A':
a_count++;
break;
case 'e':
case 'E':
e_count++;
break;
case 'i':
case 'I':
i_count++;
break;
case 'o':
case 'O':
o_count++;
break;
case 'u':
case 'U':
u_count++;
break;
}
}
/***********
Begin output
***********/
/* output:
input_string
has char_count character(s)
*/
cout << endl << input_string << endl << endl
<< "has " << char_count << " character";
if (char_count != 1)//exception for 1 character
cout << "s.";
else
cout << '.';
cout << endl << endl;
/* output:
There is/are
a_count a('s),
e_count e('s),
etc.
*/
if (a_count != 1)//exception for singular vs plural
cout << "There are" << endl;
else
cout << "There is" << endl;
//number of vowels with singular exceptions
//a
cout << a_count;
if (a_count != 1)
cout << " a's," << endl;
else
cout << " a," << endl;
//e
cout << e_count;
if (e_count != 1)
cout << " e's," << endl;
else
cout << " e," << endl;
//i
cout << i_count;
if (i_count != 1)
cout << " i's," << endl;
else
cout << " i," << endl;
//o
cout << o_count;
if (o_count != 1)
cout << " o's, and" << endl;
else
cout << " o, and" << endl;
//u
cout << u_count;
if (u_count != 1)
cout << " u's." << endl;
else
cout << " u." << endl;
}
/* I hate exceptions with numbers, this always feels lazy to me
cout << "There are" << endl
<< a_count << " a's," << endl
<< e_count << " e's," << endl
<< i_count << " i's," << endl
<< o_count << " o's, and" << endl
<< u_count << " u's." << endl;
*/
/* Also to_string() wouldn't compile so...
string output_string = "";
//number of a's
output_string += to_string(a_count);
if (a_count != 1)
output_string += " a's,";
else
output_string += " a,";
//number of e's
output_string += to_string(e_count);
if (e_count != 1)
output_string += " e's,\n";
else
output_string += " e,\n";
//number of i's
output_string += to_string(i_count);
if (a_count != 1)
output_string += " i's,\n";
else
output_string += " i,\n";
//number of o's
output_string += to_string(o_count);
if (a_count != 1)
output_string += " o's, and\n";
else
output_string += " o, and\n";
//number of u's
output_string += to_string(u_count);
if (a_count != 1)
output_string += " u's,\n";
else
output_string += " u,\n";
cout << output_string << endl;
*/
| [
"notrangerjoe@gmail.com"
] | notrangerjoe@gmail.com |
b542b861efccae223844e2d7e4863f1e40dbf9a8 | 4aa72e41c9a968ba61fa040fc0bfbdcff274d3b9 | /NavigationAndReporting_9/src/urn_jaus_jss_mobility_LocalPoseSensor_1_0/LocalPoseSensorService.cpp | 4c1ae1aae49e6b26cbb7ef3fc9dada05079f4e62 | [] | no_license | unmanned-ground-vehicle/IOP | 6619d40ccab3efe5c97ec5e8d88fdec35d7018c6 | 6fb2dc43e5b7d87709538372607f8e29e0437384 | refs/heads/master | 2020-04-13T16:11:30.993729 | 2019-04-15T16:23:18 | 2019-04-15T16:23:18 | 163,314,978 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,127 | cpp |
#include "urn_jaus_jss_mobility_LocalPoseSensor_1_0/LocalPoseSensorService.h"
using namespace JTS;
namespace urn_jaus_jss_mobility_LocalPoseSensor_1_0
{
LocalPoseSensorService::LocalPoseSensorService(JTS::JausRouter* jausRouter ) : Service()
{
jausRouter->setTransportType(JausRouter::Version_1_0);
pLocalPoseSensor_LocalPoseSensorProtocol = new LocalPoseSensor_LocalPoseSensorProtocol();
pLocalPoseSensor_LocalPoseSensorProtocol->setHandlers(ieHandler, jausRouter);
pLocalPoseSensor_LocalPoseSensorProtocol->setupNotifications();
}
LocalPoseSensorService::~LocalPoseSensorService()
{
delete pLocalPoseSensor_LocalPoseSensorProtocol;
}
/**
* This is the function that will actually be run by the thread at start-up.
* We override it from EventReceiver in order to handle any entry
* actions defined by the initial state.
*/
void LocalPoseSensorService::run()
{
/// Perform any entry actions specified by the start state.
/// Kick-off the receive loop...
EventReceiver::run();
}
/**
* This is the function that will process an event either generated
* by the service, sent to it by another service on the same component,
* or as a message sent by a different component.
*/
bool LocalPoseSensorService::processTransitions(InternalEvent* ie)
{
bool done = false;
// Since this function can be called from multiple threads,
// we use a mutex to ensure only one state transition is
// active at a time.
mutex.lock();
// Invoke the FSM transition for this event.
try
{
if ((done == false) && (ie->getName().compare("Receive") == 0))
{
Receive* casted_ie = (Receive*) ie;
unsigned short id = *((unsigned short*) casted_ie->getBody()->getReceiveRec()->getMessagePayload()->getData());
if ((id != QueryLocalPose::ID))
goto leave;
}
} catch (...) {}
try
{
if ((done == false) && ie->getName().compare("Receive") == 0 && (ie->getSource().compare("LocalPoseSensor_LocalPoseSensorProtocol") != 0))
{
Receive* casted_ie = (Receive*) ie;
unsigned short id = *((unsigned short*) casted_ie->getBody()->getReceiveRec()->getMessagePayload()->getData());
id = JSIDL_v_1_0::correctEndianness(id);
if ( id == QueryLocalPose::ID)
{
QueryLocalPose msg;
msg.decode(casted_ie->getBody()->getReceiveRec()->getMessagePayload()->getData());
// Unique identifier used to replace previous edits upon regeneration, do not delete this comment:e9d4f6bf-53af-3ff9-a33c-557f071eba02
unsigned int sender = (casted_ie->getBody()->getReceiveRec()->getSrcSubsystemID() << 16) +
(casted_ie->getBody()->getReceiveRec()->getSrcNodeID() << 8) +
(casted_ie->getBody()->getReceiveRec()->getSrcComponentID());
pLocalPoseSensor_LocalPoseSensorProtocol->context->QueryLocalPoseTransition(msg, sender);
done = true;
goto leave;
}
}
} catch (...) {}
leave:
mutex.unlock();
return done;
}
/**
* This is the function that will check for default transitions if
* no other transitions were satisfied.
*/
bool LocalPoseSensorService::defaultTransitions(InternalEvent* ie)
{
bool done = false;
// Since this function can be called from multiple threads,
// we use a mutex to ensure only one state transition is
// active at a time.
mutex.lock();
// Invoke the FSM transition for this event.
try
{
if ((done == false) && ie->getName().compare("Receive") == 0 && (ie->getSource().compare("LocalPoseSensor_LocalPoseSensorProtocol") != 0))
{
Receive* casted_ie = (Receive*) ie;
unsigned short id = *((unsigned short*) casted_ie->getBody()->getReceiveRec()->getMessagePayload()->getData());
id = JSIDL_v_1_0::correctEndianness(id);
if ( id == QueryLocalPose::ID)
{
QueryLocalPose msg;
msg.decode(casted_ie->getBody()->getReceiveRec()->getMessagePayload()->getData());
pLocalPoseSensor_LocalPoseSensorProtocol->context->QueryLocalPoseTransition();
done = true;
goto leave;
}
}
} catch (...) {}
leave:
mutex.unlock();
return done;
}
};
| [
"sudshek01@gmail.com"
] | sudshek01@gmail.com |
13be4fe15b6d7741b0462367e1d2a1e13a89fe4d | 9b7964822100a804450fadfe3cd7ea72180eadcb | /src/validationinterface.h | 65acad4999c6cebbdffcdf7f824843694cead614 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | thnass/adeptio | 7415d6300e0aec964e2223c4c7b19ea51b173816 | 65aad9209588e62a3e58d6187a88253d3d5f04b1 | refs/heads/master | 2020-08-04T03:40:56.444722 | 2019-10-01T01:28:09 | 2019-10-01T01:28:09 | 211,990,234 | 0 | 0 | MIT | 2019-10-01T01:25:17 | 2019-10-01T01:25:16 | null | UTF-8 | C++ | false | false | 4,039 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2017-2019 The Adeptio developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_VALIDATIONINTERFACE_H
#define BITCOIN_VALIDATIONINTERFACE_H
#include <boost/signals2/signal.hpp>
#include <boost/shared_ptr.hpp>
class CBlock;
struct CBlockLocator;
class CBlockIndex;
class CReserveScript;
class CTransaction;
class CValidationInterface;
class CValidationState;
class uint256;
// These functions dispatch to one or all registered wallets
/** Register a wallet to receive updates from core */
void RegisterValidationInterface(CValidationInterface* pwalletIn);
/** Unregister a wallet from core */
void UnregisterValidationInterface(CValidationInterface* pwalletIn);
/** Unregister all wallets from core */
void UnregisterAllValidationInterfaces();
/** Push an updated transaction to all registered wallets */
void SyncWithWallets(const CTransaction& tx, const CBlock* pblock);
class CValidationInterface {
protected:
// XX42 virtual void EraseFromWallet(const uint256& hash){};
virtual void UpdatedBlockTip(const CBlockIndex *pindex) {}
virtual void SyncTransaction(const CTransaction &tx, const CBlock *pblock) {}
virtual void NotifyTransactionLock(const CTransaction &tx) {}
virtual void SetBestChain(const CBlockLocator &locator) {}
virtual bool UpdatedTransaction(const uint256 &hash) { return false;}
virtual void Inventory(const uint256 &hash) {}
// XX42 virtual void ResendWalletTransactions(int64_t nBestBlockTime) {}
virtual void ResendWalletTransactions() {}
virtual void BlockChecked(const CBlock&, const CValidationState&) {}
// XX42 virtual void GetScriptForMining(boost::shared_ptr<CReserveScript>&) {};
virtual void ResetRequestCount(const uint256 &hash) {};
friend void ::RegisterValidationInterface(CValidationInterface*);
friend void ::UnregisterValidationInterface(CValidationInterface*);
friend void ::UnregisterAllValidationInterfaces();
};
struct CMainSignals {
// XX42 boost::signals2::signal<void(const uint256&)> EraseTransaction;
/** Notifies listeners of updated block chain tip */
boost::signals2::signal<void (const CBlockIndex *)> UpdatedBlockTip;
/** Notifies listeners of updated transaction data (transaction, and optionally the block it is found in. */
boost::signals2::signal<void (const CTransaction &, const CBlock *)> SyncTransaction;
/** Notifies listeners of an updated transaction lock without new data. */
boost::signals2::signal<void (const CTransaction &)> NotifyTransactionLock;
/** Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible). */
boost::signals2::signal<bool (const uint256 &)> UpdatedTransaction;
/** Notifies listeners of a new active block chain. */
boost::signals2::signal<void (const CBlockLocator &)> SetBestChain;
/** Notifies listeners about an inventory item being seen on the network. */
boost::signals2::signal<void (const uint256 &)> Inventory;
/** Tells listeners to broadcast their data. */
// XX42 boost::signals2::signal<void (int64_t nBestBlockTime)> Broadcast;
boost::signals2::signal<void ()> Broadcast;
/** Notifies listeners of a block validation result */
boost::signals2::signal<void (const CBlock&, const CValidationState&)> BlockChecked;
/** Notifies listeners that a key for mining is required (coinbase) */
// XX42 boost::signals2::signal<void (boost::shared_ptr<CReserveScript>&)> ScriptForMining;
/** Notifies listeners that a block has been successfully mined */
boost::signals2::signal<void (const uint256 &)> BlockFound;
};
CMainSignals& GetMainSignals();
#endif // BITCOIN_VALIDATIONINTERFACE_H
| [
"38818888+adeptio-project@users.noreply.github.com"
] | 38818888+adeptio-project@users.noreply.github.com |
de4c7b92f86563b7066b50f1a56d33f532d94b43 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function13872/function13872_schedule_31/function13872_schedule_31.cpp | 53a3a55f5b207bcc711b07e78793d7dacf95b562 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 763 | cpp | #include <tiramisu/tiramisu.h>
using namespace tiramisu;
int main(int argc, char **argv){
tiramisu::init("function13872_schedule_31");
constant c0("c0", 64), c1("c1", 64), c2("c2", 64), c3("c3", 128);
var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i3("i3", 0, c3), i01("i01"), i02("i02"), i03("i03"), i04("i04"), i05("i05"), i06("i06");
computation comp0("comp0", {i0, i1, i2, i3}, 3 + 3 * 9);
comp0.tile(i0, i1, i2, 64, 64, 64, i01, i02, i03, i04, i05, i06);
comp0.parallelize(i01);
buffer buf0("buf0", {64, 64, 64, 128}, p_int32, a_output);
comp0.store_in(&buf0);
tiramisu::codegen({&buf0}, "../data/programs/function13872/function13872_schedule_31/function13872_schedule_31.o");
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
b4eca89a81487aed30a9c2f18e45178a955a72c9 | 46f596af05f000408fd6932e5b96dbf124af49f8 | /homework/Kulagin/02/main.cpp | 97712ce64968aba4ddb2d89a71045d2434ffe9e1 | [
"MIT"
] | permissive | fsatka/msu_cpp_spring_2018 | 157d5e56587e53b441126fd5e793f93db6bc211b | b5d84447f9b8c7f3615b421c51cf4192f1b90342 | refs/heads/master | 2020-03-29T12:47:11.411708 | 2018-06-25T22:06:53 | 2018-06-25T22:06:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 828 | cpp | #include <iostream>
#include <vector>
#include <cmath>
#include "numbers.dat"
using namespace std;
int main(int argc, char** argv) {
if (argc < 3 || argc % 2 == 0) {
return -1;
}
int k1, k2;
int n = 0;
for (int a = 1; a < argc; a += 2) {
k1 = atoi(argv[a]);
k2 = atoi(argv[a + 1]);
if (k1 > k2) {
printf("0");
return 0;
}
n = max(n, k2);
}
vector<bool> prime(n, true);
prime[0] = prime[1] = false;
for (int i = 2; i * i <= n; i++)
if (prime[i])
for (int j = i + i; j <= n; j += i)
prime[j] = false;
int prime_cnt;
int i;
for (int a = 1; a < argc; a += 2) {
k1 = atoi(argv[a]);
k2 = atoi(argv[a + 1]);
prime_cnt = 0;
i = 0;
for (i = 0; Data[i] < k1; i++);
while (Data[i] < k2)
prime_cnt += prime[ Data[i++]];
printf("%d\n", prime_cnt);
}
return 0;
}
| [
"alexfmsu@mail.ru"
] | alexfmsu@mail.ru |
dcd87954365fe032ae0402424ba1835fcf3dd39b | 177f3b84e69cd7496ead2e7d15a33f1f5fadd988 | /EventTree_ggNtuplizer_V07_04_09_01.cc | cdefd08062461e89f1fb32464131ff79d6f7c4da | [] | no_license | vuko-brigljevic/WZRun2Analysis | 75ba0063b0888b1562827d505ddfd1a8716b3391 | 064d371bc77e1d869225e9f5ad6348c72d0dd91b | refs/heads/master | 2021-01-10T01:33:04.189482 | 2015-09-25T11:38:18 | 2015-09-25T11:38:18 | 36,926,080 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,578 | cc | #define EventTree_ggNtuplizer_V07_04_09_01_cxx
#include "EventTree_ggNtuplizer_V07_04_09_01.h"
#include <TH2.h>
#include <TStyle.h>
#include <TCanvas.h>
void EventTree_ggNtuplizer_V07_04_09_01::Loop()
{
// In a ROOT session, you can do:
// root> .L EventTree_ggNtuplizer_V07_04_09_01.C
// root> EventTree_ggNtuplizer_V07_04_09_01 t
// root> t.GetEntry(12); // Fill t data members with entry number 12
// root> t.Show(); // Show values of entry 12
// root> t.Show(16); // Read and show values of entry 16
// root> t.Loop(); // Loop on all entries
//
// This is the loop skeleton where:
// jentry is the global entry number in the chain
// ientry is the entry number in the current Tree
// Note that the argument to GetEntry must be:
// jentry for TChain::GetEntry
// ientry for TTree::GetEntry and TBranch::GetEntry
//
// To read only selected branches, Insert statements like:
// METHOD1:
// fChain->SetBranchStatus("*",0); // disable all branches
// fChain->SetBranchStatus("branchname",1); // activate branchname
// METHOD2: replace line
// fChain->GetEntry(jentry); //read all branches
//by b_branchname->GetEntry(ientry); //read only this branch
if (fChain == 0) return;
Long64_t nentries = fChain->GetEntriesFast();
Long64_t nbytes = 0, nb = 0;
for (Long64_t jentry=0; jentry<nentries;jentry++) {
Long64_t ientry = LoadTree(jentry);
if (ientry < 0) break;
nb = fChain->GetEntry(jentry); nbytes += nb;
// if (Cut(ientry) < 0) continue;
}
}
| [
"smicanov@cern.ch"
] | smicanov@cern.ch |
bb238bb5dd5e9d1f5046bf54fc839147ae1f93dd | 1799cfc0de84499fafb5c083d6944d14246c72a4 | /src/google/protobuf/compiler/cpp/cpp_field.h | df8fff0cc3faa2055b26d0e01091edc736ef9d16 | [
"LicenseRef-scancode-protobuf"
] | permissive | saadware/protobuf-cppbuilder | 01698d2cca879b43cf49ac53834221269c7d4903 | 576073e8e2666c9d704239348b21fa0571bb7bb1 | refs/heads/master | 2021-01-22T05:06:34.225773 | 2015-05-02T01:00:47 | 2015-05-02T01:00:47 | 2,490,021 | 1 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 7,017 | h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_FIELD_H__
#define GOOGLE_PROTOBUF_COMPILER_CPP_FIELD_H__
#include <map>
#include <string>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/descriptor.h>
namespace google {
namespace protobuf {
namespace io {
class Printer; // printer.h
}
}
namespace protobuf {
namespace compiler {
namespace cpp {
// Helper function: set variables in the map that are the same for all
// field code generators.
// ['name', 'index', 'number', 'classname', 'declared_type', 'tag_size',
// 'deprecation'].
void SetCommonFieldVariables(const FieldDescriptor* descriptor,
std::map<std::string, std::string>* variables);
class FieldGenerator {
public:
FieldGenerator() {}
virtual ~FieldGenerator();
// Generate lines of code declaring members fields of the message class
// needed to represent this field. These are placed inside the message
// class.
virtual void GeneratePrivateMembers(io::Printer* printer) const = 0;
// Generate prototypes for all of the accessor functions related to this
// field. These are placed inside the class definition.
virtual void GenerateAccessorDeclarations(io::Printer* printer) const = 0;
// Generate inline definitions of accessor functions for this field.
// These are placed inside the header after all class definitions.
virtual void GenerateInlineAccessorDefinitions(
io::Printer* printer) const = 0;
// Generate definitions of accessors that aren't inlined. These are
// placed somewhere in the .cc file.
// Most field types don't need this, so the default implementation is empty.
virtual void GenerateNonInlineAccessorDefinitions(
io::Printer* printer) const {}
// Generate lines of code (statements, not declarations) which clear the
// field. This is used to define the clear_$name$() method as well as
// the Clear() method for the whole message.
virtual void GenerateClearingCode(io::Printer* printer) const = 0;
// Generate lines of code (statements, not declarations) which merges the
// contents of the field from the current message to the target message,
// which is stored in the generated code variable "from".
// This is used to fill in the MergeFrom method for the whole message.
// Details of this usage can be found in message.cc under the
// GenerateMergeFrom method.
virtual void GenerateMergingCode(io::Printer* printer) const = 0;
// Generate lines of code (statements, not declarations) which swaps
// this field and the corresponding field of another message, which
// is stored in the generated code variable "other". This is used to
// define the Swap method. Details of usage can be found in
// message.cc under the GenerateSwap method.
virtual void GenerateSwappingCode(io::Printer* printer) const = 0;
// Generate initialization code for private members declared by
// GeneratePrivateMembers(). These go into the message class's SharedCtor()
// method, invoked by each of the generated constructors.
virtual void GenerateConstructorCode(io::Printer* printer) const = 0;
// Generate any code that needs to go in the class's SharedDtor() method,
// invoked by the destructor.
// Most field types don't need this, so the default implementation is empty.
virtual void GenerateDestructorCode(io::Printer* printer) const {}
// Generate lines to decode this field, which will be placed inside the
// message's MergeFromCodedStream() method.
virtual void GenerateMergeFromCodedStream(io::Printer* printer) const = 0;
// Generate lines to decode this field from a packed value, which will be
// placed inside the message's MergeFromCodedStream() method.
virtual void GenerateMergeFromCodedStreamWithPacking(io::Printer* printer)
const;
// Generate lines to serialize this field, which are placed within the
// message's SerializeWithCachedSizes() method.
virtual void GenerateSerializeWithCachedSizes(io::Printer* printer) const = 0;
// Generate lines to serialize this field directly to the array "target",
// which are placed within the message's SerializeWithCachedSizesToArray()
// method. This must also advance "target" past the written bytes.
virtual void GenerateSerializeWithCachedSizesToArray(
io::Printer* printer) const = 0;
// Generate lines to compute the serialized size of this field, which
// are placed in the message's ByteSize() method.
virtual void GenerateByteSize(io::Printer* printer) const = 0;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator);
};
// Convenience class which constructs FieldGenerators for a Descriptor.
class FieldGeneratorMap {
public:
explicit FieldGeneratorMap(const Descriptor* descriptor);
~FieldGeneratorMap();
const FieldGenerator& get(const FieldDescriptor* field) const;
private:
const Descriptor* descriptor_;
scoped_array<scoped_ptr<FieldGenerator> > field_generators_;
static FieldGenerator* MakeGenerator(const FieldDescriptor* field);
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap);
};
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_FIELD_H__
| [
"saadsj@gmail.com"
] | saadsj@gmail.com |
71818ba0f92a1615c7ed9ec193ab1525de24ec40 | a1a82c79a8ffb4f5e3badaf81dc8347c53e10669 | /Tree Data Structure/order_of_people_heights.cpp | 516494a601d13800552b3d7eba97aeeed5b63e57 | [] | no_license | adityarg/InterviewBit | 67a7275ae6af0d34eda0420ec3c51cbfe9520966 | f8d2cf69e4fe92220d73c52a8547fda34c21406f | refs/heads/master | 2022-12-27T17:00:25.873465 | 2020-10-08T04:50:20 | 2020-10-08T04:50:20 | 281,244,836 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,475 | cpp | TreeNode *build_st(int ss,int se,int value){
if(ss==se){
return new TreeNode(value);
}
TreeNode *node=new TreeNode(value);
int mid=(ss+se)/2;
TreeNode *le,*ri;
le=build_st(ss,mid,value);
ri=build_st(mid+1,se,value);
node->val=le->val+ri->val;
node->left=le;
node->right=ri;
return node;
}
int query(TreeNode *node,int ss,int se,int pos){
if(ss==se){
return ss;
}
int mid=(ss+se)/2;
if(node->left->val>=pos){
return query(node->left,ss,mid,pos);
}
else{
pos=pos-node->left->val;
return query(node->right,mid+1,se,pos);
}
}
void update(TreeNode *node,int ss,int se,int pos){
if(node==NULL){
return;
}
if(pos<ss || pos>se){
return;
}
if(ss==se){
node->val--;
return;
}
int mid=(ss+se)/2;
update(node->left,ss,mid,pos);
update(node->right,mid+1,se,pos);
node->val--;
return;
}
vector<int> Solution::order(vector<int> &A, vector<int> &B) {
int n=A.size();
TreeNode *root;
root=build_st(0,n-1,1);
vector<int> ans(n);
map<int,int> m;
for(int i=0;i<n;i++){
m[A[i]]=B[i];
}
for(auto it:m){
int pos=query(root,0,n-1,it.second+1);
// cout<<pos<<" "<<it.first<<" "<<it.second<<"\n";
ans[pos]=it.first;
update(root,0,n-1,pos);
}
return ans;
} | [
"adiraghuwanshi23@gmail.com"
] | adiraghuwanshi23@gmail.com |
cc85f78545e3f493cf96697756157e828ee85f5a | 35060c0a15ae390e25ca9b463b2639ca842eb186 | /filter/AnisotropyMeasure/vtkTensorNorm.cxx | 66cc7076183b896529cf6d4a2e4ed75050b7a05c | [] | no_license | mbussler/paraview | 1be7840961b2e846c2356b0ea5efc18078cf97f6 | 00a113a5a41bbd7c6902f55fc0ff233328350bd2 | refs/heads/master | 2020-03-29T07:14:41.837894 | 2018-09-20T19:51:54 | 2018-09-20T19:51:54 | 149,658,349 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,808 | cxx | /*=========================================================================
Program: Visualization Toolkit
Module: vtkTensorNorm.h
Copyright (c) Michael Bußler
=========================================================================*/
#include "vtkTensorNorm.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkCell.h"
#include "vtkCellArray.h"
#include "vtkDataSet.h"
#include "vtkExecutive.h"
#include "vtkFloatArray.h"
#include "vtkDoubleArray.h"
#include "vtkMath.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkUnstructuredGrid.h"
#include "vtkTransform.h"
#include "vtkSmartPointer.h"
#include "linalg.h"
vtkStandardNewMacro(vtkTensorNorm);
//==============================================================================
vtkTensorNorm::vtkTensorNorm()
{
this->SetNumberOfInputPorts(1);
// by default, process active point tensors
this->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS,
vtkDataSetAttributes::TENSORS);
}
//==============================================================================
vtkTensorNorm::~vtkTensorNorm()
{
// clean up
}
//==============================================================================
int vtkTensorNorm::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and output
vtkDataSet *input = vtkDataSet::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkDataSet *output = vtkDataSet::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkDataArray *inTensor;
double tensor[9];
vtkIdType numPts, inPtId, ptIncr, i;
int j;
vtkDebugMacro(<<"Calculating TensorNorm");
vtkPointData *outPD = output->GetPointData();
inTensor = this->GetInputArrayToProcess(0, inputVector);
numPts = input->GetNumberOfPoints();
if ( !inTensor || numPts < 1 )
{
vtkErrorMacro(<<"No data!");
return 1;
}
if ( inTensor->GetNumberOfComponents() != 9 )
{
vtkErrorMacro("Input array must be a gradient tensor with 9 components.");
return 0;
}
// allocate mem for output data arrays
vtkSmartPointer<vtkDoubleArray> normArray = vtkSmartPointer<vtkDoubleArray>::New();
normArray->SetName("Spektralnorm");
normArray->SetNumberOfComponents(1);
normArray->SetNumberOfTuples(numPts);
//
// Traverse all Input points, calculate and store symmetric and antisymmetric tensors
//
for (inPtId=0; inPtId < numPts; inPtId++)
{
inTensor->GetTuple(inPtId, tensor);
mat3 m;
for (j=0; j<3; j++)
{
for (i=0; i<3; i++)
{
// compute A' * A
m[i][j] = tensor[j+3*i] * tensor[i+3*j];
}
}
vec3 lambda;
mat3eigenvalues(m, lambda);
double lambdaMax = std::max<double>( lambda[0], std::max<double>( lambda[1], lambda[2]));
//copy tensors
normArray->SetTupleValue(inPtId, &lambdaMax );
}
vtkDebugMacro(<<"Calculated " << numPts <<" tensor norm values");
//
// Update output and release memory
//
output->ShallowCopy(input);
vtkPointData *pd = output->GetPointData();
pd->AddArray(normArray);
output->Squeeze();
return 1;
}
//==============================================================================
void vtkTensorNorm::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
| [
"michael.bussler@gmail.com"
] | michael.bussler@gmail.com |
8d7f1a648153620a59185fc55ede79c6974c8e74 | 5e8313d4a988226f4a184aa381acc900d92d51c4 | /3DSoftRender/LibGraphics/SceneGraph/VisualEffect.cpp | 94db41825a1a81d2676ca2699e5451e0490ecff4 | [] | no_license | GGBone/3DSoftRender | f0aaec57ddfe7f9c224422dc1056b76a970f41ca | c24f16867486e5c26d7d8b613f139a16d221574f | refs/heads/master | 2021-01-11T23:07:16.207565 | 2019-03-17T14:28:22 | 2019-03-17T14:28:22 | 78,545,735 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 815 | cpp | #include <GraphicsPCH.h>
#include <Graphics.h>
#include "VisualEffect.h"
using namespace Hikari;
VisualEffect::VisualEffect()
: m_EffectName("Default")
{
}
VisualEffect::~VisualEffect()
{
ClearTechiniques();
}
void VisualEffect::ClearTechiniques()
{
auto iter = mTechniques.begin();
for (; iter != mTechniques.end(); ++iter)
{
(*iter).reset();
}
mTechniques.clear();
}
void VisualEffect::InsertTechnique(std::shared_ptr<VisualTechnique> technique)
{
if (technique != nullptr)
{
mTechniques.push_back(technique);
}
}
size_t VisualEffect::GetTechniqueSize() const
{
return mTechniques.size();
}
std::shared_ptr<VisualTechnique> VisualEffect::GetTechnique(int techIndex)
{
return mTechniques[techIndex];
}
VisualEffect::VisualEffect(const std::string& name, int mode)
: m_EffectName(name)
{
}
| [
"z652137200@gmail.com"
] | z652137200@gmail.com |
de50464adc84c414e2cc4bf403c01f4eee84072c | d2f5e0b43885cd080a4c5026ce133e288482f8d0 | /Juez EDA/EDA_Juez2_7.2/EDA_Juez2_7.2/Source.cpp | d4f22fb8cfdc1721d3db01df85592939ddf549b3 | [] | no_license | tito-kimbo/Online-Judge-Solutions | fb0ea2f2b9d8724a4b1f914a8be02294f1664135 | 1207e95365fb6f2691de077beaf2cbe7f0724c11 | refs/heads/master | 2020-06-03T04:18:32.970773 | 2019-06-11T19:12:52 | 2019-06-11T19:12:52 | 191,435,206 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 301 | cpp | #include "Hora.h"
#include "operable_queue.h"
void solve(int n) {
Hora h;
operable_queue<Hora> q;
for (int i = 0; i < n; i++) {
std::cin >> h;
q.push(h);
}
q.removeLower();
std::cout << q << '\n';
}
int main() {
int n;
std::cin >> n;
while (n > 0) {
solve(n);
std::cin >> n;
}
} | [
"eduriver@ucm.es"
] | eduriver@ucm.es |
058a6669142acfaa01398a0147c8bb99c8942bda | 966dc17abfc38c3a11e4d4798813350448f25dd5 | /0101-0200/0102.cpp | a9b9d54c08c19bc2c37a0f24f8c75a5126f1a353 | [] | no_license | superlb/MyLeetcode | fa8b041339c1f803b4f0432fe6bd593a2f4e8949 | ae617c7e858636b026ba3c323f37972dda64b87e | refs/heads/master | 2021-08-04T02:43:16.049436 | 2021-07-24T14:03:05 | 2021-07-24T14:03:05 | 205,500,460 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,078 | cpp | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue< pair<TreeNode*,int> > q;
vector<vector<int>> v;
if(root==NULL) return v;
q.push(make_pair(root,1));
int nowi = 1;
vector<int> tmpv;
while(!q.empty())
{
pair<TreeNode*,int> tmp = q.front();
q.pop();
if(tmp.second != nowi)
{
v.push_back(tmpv);
tmpv.clear();
++nowi;
}
tmpv.push_back((tmp.first)->val);
if((tmp.first)->left != NULL)
q.push(make_pair((tmp.first)->left,tmp.second+1));
if((tmp.first)->right != NULL)
q.push(make_pair((tmp.first)->right,tmp.second+1));
}
if(!tmpv.empty())
v.push_back(tmpv);
return v;
}
}; | [
"liaowuyao@gmail.com"
] | liaowuyao@gmail.com |
86c15c41856c078d28b7ffda7ec4254f22e2ccdf | fce783289eb4359c43cfa411336c43fca7d449a5 | /toi12_weakpoint.cpp | 2c0d3d2c14e3de1b98b0a93799ba2f65e7f94151 | [] | no_license | Autoratch/Thailand-Olympiad-in-Informatics | deceffc7707630b865e9e2a8b2e37486b6698d62 | 00efcb5fe3e6397a582713c50e8521d6f3e36626 | refs/heads/master | 2022-06-21T21:34:13.671761 | 2022-06-19T03:51:40 | 2022-06-19T03:51:40 | 123,771,446 | 21 | 12 | null | 2022-06-19T03:51:41 | 2018-03-04T08:45:09 | C++ | UTF-8 | C++ | false | false | 3,190 | cpp | #include <vector>
#include <queue>
#include <iostream>
#include <limits.h>
#include <algorithm>
using namespace std;
#define endl '\n'
#define MOD 1e9 + 7
int n,k,st;
vector<vector<int> > adj;
vector<int> cycle;
vector<bool> incy;
vector<bool> visited,visit;
bool fic,cy,fin;
bool findcycle(int p,int pr)
{
visit[p] = true;
for(int i = 0;i < adj[p].size();i++)
{
if(!visit[adj[p][i]])
{
if(findcycle(adj[p][i],p))
{
if(adj[p][i]==st or fin){ fin = true; return true; }
else{ cycle.push_back(adj[p][i]); incy[adj[p][i]] = true; return true; }
}
else if(fin or fic) return false;
}
else if(pr==p) continue;
else if(adj[p][i]!=pr)
{
fic = true;
st = adj[p][i];
cycle.push_back(st);
if(st==k) cy = true;
incy[st] = true;
return true;
}
}
return false;
}
int solve1(int x)
{
queue<int> q;
q.push(x);
visited[x] = true;
int ans = 0;
while(!q.empty())
{
int p = q.front();
q.pop();
ans++;
for(int i = 0;i < adj[p].size();i++)
{
if(visited[adj[p][i]]) continue;
if(incy[adj[p][i]]) continue;
visited[adj[p][i]] = true;
q.push(adj[p][i]);
}
}
return ans-1;
}
int solve2(int x)
{
queue<int> q;
q.push(x);
visited[x] = true;
int ans = 0;
while(!q.empty())
{
int p = q.front();
q.pop();
ans++;
for(int i = 0;i < adj[p].size();i++)
{
if(visited[adj[p][i]]) continue;
if(adj[p][i]==k) continue;
visited[adj[p][i]] = true;
q.push(adj[p][i]);
}
}
return ans-1;
}
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> n >> k;
adj.resize(n); incy.resize(n); visited.resize(n); visit.resize(n);
k--;
for(int i = 0;i < n;i++)
{
int a,b;
cin >> a >> b;
a--; b--;
adj[a].push_back(b);
adj[b].push_back(a);
}
findcycle(k,k);
int mx = 0,idx = INT_MAX;
if(cy)
{
for(int i = 0;i < adj[k].size();i++)
{
if(incy[adj[k][i]]) continue;
int tmp = solve1(adj[k][i]);
if(tmp>mx)
{
mx = tmp;
idx = adj[k][i];
}
else if(tmp==mx) idx = min(idx,adj[k][i]);
}
for(int i = 0;i < cycle.size();i++)
{
if(cycle[i]==k) continue;
int tmp = solve1(cycle[i]);
if(tmp>mx)
{
mx = tmp;
idx = cycle[i];
}
else if(tmp==mx) idx = min(idx,cycle[i]);
}
}
else
{
for(int i = 0;i < adj[k].size();i++)
{
int tmp = solve2(adj[k][i]);
if(tmp>mx)
{
mx = tmp;
idx = adj[k][i];
}
else if(tmp==mx) idx = min(idx,adj[k][i]);
}
}
cout << idx+1 << endl << mx << endl;
}
| [
"noreply@github.com"
] | Autoratch.noreply@github.com |
1a99ee7da6af9f8058a591d6bc795ad84fecb0df | b6967a88a776ff1217471c73cf63ab67658c24fa | /CoppeliaSim_Edu_V4_1_0_Ubuntu18_04/programming/bluezero/include/spotify-json/test/src/test_encoded_value.cpp | a3ab438048b1ff049d0502884727b1e2bb5eaa04 | [
"JSON",
"BSD-3-Clause",
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | YueErro/ModernRobotics | 35048b04571799a4c5237f48750a4c5f7041d4a7 | 82345c04157c1322b24553bf00abd1f2b03281a5 | refs/heads/master | 2020-08-12T20:02:30.933484 | 2020-07-29T19:55:39 | 2020-07-29T19:55:39 | 214,834,024 | 0 | 0 | MIT | 2019-10-13T14:24:01 | 2019-10-13T14:24:01 | null | UTF-8 | C++ | false | false | 7,660 | cpp | /*
* Copyright (c) 2016 Spotify AB
*
* 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 <cstring>
#include <limits>
#include <sstream>
#include <boost/mpl/list.hpp>
#include <boost/test/unit_test.hpp>
#include <spotify/json/decode_exception.hpp>
#include <spotify/json/encoded_value.hpp>
BOOST_AUTO_TEST_SUITE(spotify)
BOOST_AUTO_TEST_SUITE(json)
namespace {
std::string value_to_string(const encoded_value_ref &value_ref) {
return std::string(value_ref.data(), value_ref.size());
}
using encoded_value_types = boost::mpl::list<encoded_value_ref, encoded_value>;
} // namespace
/*
* json::encoded_value_ref & json::encoded_value
*/
BOOST_AUTO_TEST_CASE_TEMPLATE(
json_encoded_value_should_default_construct,
encoded_value_type,
encoded_value_types) {
encoded_value_type value;
BOOST_CHECK_EQUAL(value_to_string(value), "null");
}
BOOST_AUTO_TEST_CASE_TEMPLATE(
json_encoded_value_should_validate_given_json_for_cstr,
encoded_value_type,
encoded_value_types) {
encoded_value_type("[ null, 1234 ]");
BOOST_CHECK_THROW(encoded_value_type("{ null, 1234 }"), decode_exception);
BOOST_CHECK_THROW(encoded_value_type("[ null, 123 ] "), decode_exception);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(
json_encoded_value_should_validate_given_json_for_data_size,
encoded_value_type,
encoded_value_types) {
encoded_value_type("[ null, 1234 ]", 14);
BOOST_CHECK_THROW(encoded_value_type("{ null, 1234 }", 14), decode_exception);
BOOST_CHECK_THROW(encoded_value_type("[ null, 123 ] ", 14), decode_exception);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(
json_encoded_value_should_validate_given_json_for_std_string,
encoded_value_type,
encoded_value_types) {
encoded_value_type(std::string("[ null, 1234 ]"));
BOOST_CHECK_THROW(encoded_value_type(std::string("{ null, 1234 }")), decode_exception);
BOOST_CHECK_THROW(encoded_value_type(std::string("[ null, 123 ] ")), decode_exception);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(
json_encoded_value_should_not_validate_unsafe_unchecked,
encoded_value_type,
encoded_value_types) {
encoded_value_type("nil", encoded_value::unsafe_unchecked());
encoded_value_type("nil", 3, encoded_value::unsafe_unchecked());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(
json_encoded_value_should_write_to_ostream,
encoded_value_type,
encoded_value_types) {
encoded_value_type value("1234");
std::stringstream ss;
ss << "[" << value << "]";
BOOST_CHECK_EQUAL(ss.str(), "[1234]");
}
BOOST_AUTO_TEST_CASE_TEMPLATE(
json_encoded_value_should_swap,
encoded_value_type,
encoded_value_types) {
encoded_value_type a("nil", encoded_value::unsafe_unchecked());
encoded_value_type b("nul", encoded_value::unsafe_unchecked());
a.swap(b);
BOOST_CHECK_EQUAL(value_to_string(a), "nul");
BOOST_CHECK_EQUAL(value_to_string(b), "nil");
}
BOOST_AUTO_TEST_CASE_TEMPLATE(
json_encoded_value_should_compare_for_equality,
encoded_value_type,
encoded_value_types) {
encoded_value_type a("null");
encoded_value_type b("1");
BOOST_CHECK(a == a);
BOOST_CHECK(!(a == b));
BOOST_CHECK(!(a != a));
BOOST_CHECK(a != b);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(
json_encoded_value_should_compare_for_equality_not_pointer_equality,
encoded_value_type,
encoded_value_types) {
char buf_1[] = { '1', '\0' };
char buf_2[] = { '1', '\0' };
encoded_value_type a(static_cast<const char *>(buf_1));
encoded_value_type b(static_cast<const char *>(buf_2));
BOOST_CHECK(a == b);
BOOST_CHECK(!(a != b));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(
json_encoded_value_should_compare_with_other_type,
encoded_value_type,
encoded_value_types) {
using other_value_type = typename std::conditional<
std::is_same<encoded_value_type, encoded_value>::value,
encoded_value_ref,
encoded_value>::type;
encoded_value_type a("null");
other_value_type b("1");
BOOST_CHECK(a == a);
BOOST_CHECK(!(a == b));
BOOST_CHECK(!(a != a));
BOOST_CHECK(a != b);
}
/*
* json::encoded_value_ref
*/
BOOST_AUTO_TEST_CASE(json_encoded_value_ref_should_copy_construct) {
const auto a = encoded_value_ref{"1234"};
const auto b = encoded_value_ref{a};
BOOST_CHECK(a.data() == b.data());
BOOST_CHECK(a.size() == b.size());
}
BOOST_AUTO_TEST_CASE(json_encoded_value_ref_should_move_construct) {
auto a = encoded_value_ref{"1234"};
const auto b = encoded_value_ref{std::move(a)};
BOOST_CHECK(a.data() == b.data());
BOOST_CHECK(a.size() == b.size());
}
BOOST_AUTO_TEST_CASE(json_encoded_value_ref_should_assign_from_encoded_value_ref) {
encoded_value_ref a("nil", encoded_value_ref::unsafe_unchecked());
encoded_value_ref b;
encoded_value_ref c;
b = a;
c = std::move(a);
BOOST_CHECK_EQUAL(value_to_string(a), "nil");
BOOST_CHECK_EQUAL(value_to_string(b), "nil");
BOOST_CHECK_EQUAL(value_to_string(c), "nil");
}
BOOST_AUTO_TEST_CASE(json_encoded_value_ref_should_assign_from_encoded_value) {
encoded_value a("nil", encoded_value::unsafe_unchecked());
encoded_value_ref b;
encoded_value_ref c;
b = a;
c = std::move(a);
BOOST_CHECK_EQUAL(value_to_string(a), "nil");
BOOST_CHECK_EQUAL(value_to_string(b), "nil");
BOOST_CHECK_EQUAL(value_to_string(c), "nil");
}
/*
* json::encoded_value
*/
BOOST_AUTO_TEST_CASE(json_encoded_value_should_copy_construct) {
const auto a = encoded_value{"1234"};
const auto b = encoded_value{a};
BOOST_CHECK_EQUAL(value_to_string(a), "1234");
BOOST_CHECK_EQUAL(value_to_string(b), "1234");
}
BOOST_AUTO_TEST_CASE(json_encoded_value_should_move_construct) {
auto a = encoded_value{"1234"};
const auto b = encoded_value{std::move(a)};
BOOST_CHECK_EQUAL(value_to_string(a), "null");
BOOST_CHECK_EQUAL(value_to_string(b), "1234");
}
BOOST_AUTO_TEST_CASE(json_encoded_value_should_move_construct_with_context) {
encode_context context;
context.append("{}", 2);
const auto value = encoded_value{std::move(context)};
BOOST_CHECK_EQUAL(value_to_string(value), "{}");
BOOST_CHECK_EQUAL(context.size(), 0);
}
BOOST_AUTO_TEST_CASE(json_encoded_value_should_move_construct_with_context_unchecked) {
encode_context context;
context.append("{}", 2);
const auto value = encoded_value{std::move(context), encoded_value::unsafe_unchecked()};
BOOST_CHECK_EQUAL(value_to_string(value), "{}");
BOOST_CHECK_EQUAL(context.size(), 0);
}
BOOST_AUTO_TEST_CASE(json_encoded_value_should_assign_from_encoded_value_ref) {
encoded_value_ref a("nil", encoded_value_ref::unsafe_unchecked());
encoded_value b;
encoded_value c;
b = a;
c = std::move(a);
BOOST_CHECK_EQUAL(value_to_string(a), "nil");
BOOST_CHECK_EQUAL(value_to_string(b), "nil");
BOOST_CHECK_EQUAL(value_to_string(c), "nil");
}
BOOST_AUTO_TEST_CASE(json_encoded_value_should_assign_from_encoded_value) {
encoded_value a("nil", encoded_value::unsafe_unchecked());
encoded_value b;
encoded_value c;
b = a;
c = std::move(a);
BOOST_CHECK_EQUAL(value_to_string(a), "null");
BOOST_CHECK_EQUAL(value_to_string(b), "nil");
BOOST_CHECK_EQUAL(value_to_string(c), "nil");
}
BOOST_AUTO_TEST_SUITE_END() // json
BOOST_AUTO_TEST_SUITE_END() // spotify
| [
"yue.trbj@gmail.com"
] | yue.trbj@gmail.com |
f575277fb015e87179e3e3e03b1e3a6552b74802 | 38ae1a64ba59b2d4cd8ba7a7fc4cff97dbb75a3f | /src/GameObjects/World.h | 3aeee153e94bbbcefdd2369686a78026c7d139fc | [] | no_license | kubaceg/dragonGame | 0b38f38448214011b3c9d1ac93cb1a45f652fbf9 | cc8ecd4f74be64f60b48072b9bb8b2c795cb8f60 | refs/heads/master | 2020-05-17T15:39:32.298349 | 2015-10-19T20:22:59 | 2015-10-19T20:22:59 | 25,095,597 | 0 | 0 | null | 2015-10-19T20:22:59 | 2014-10-11T21:15:43 | C++ | UTF-8 | C++ | false | false | 266 | h | #ifndef __WORLD_H__
#define __WORLD_H__
#include "SDL.h"
#include "Clouds.h"
class World {
private:
SDL_Surface *screen;
SDL_Surface *background;
SDL_Rect bgPosition;
int frameCount;
public:
void draw();
World(SDL_Surface *sc);
};
#endif | [
"kuba.ceg@gmail.com"
] | kuba.ceg@gmail.com |
10d1f7e4d9dde6071b63f356dd82c46aca8ec6c4 | 60ea3637fe65bd27a14d36d9626e1033b0144dd4 | /syntheticSample/cryptopp/src/pp_twofish.cpp | 5c3f01dd27b07ba6dd436291edfe381da24f7405 | [] | no_license | plestrin/bacs | e30938d9b0a016dff841b48fe68aca8d36f1e272 | 73b32d09fe0b488e7eec67ae25898449c33b7dbf | refs/heads/master | 2020-12-30T16:39:59.281360 | 2018-04-04T17:20:17 | 2018-04-04T17:20:17 | 90,999,093 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,114 | cpp | #include <iostream>
#include <iomanip>
#include <cryptopp/modes.h>
#include <cryptopp/twofish.h>
static void print_raw_buffer(byte* buffer, size_t buffer_length){
size_t i;
for (i = 0; i < buffer_length; i++){
if (buffer[i] & 0xf0){
std::cout << std::hex << (buffer[i] & 0xff);
}
else{
std::cout << "0" << std::hex << (buffer[i] & 0xff);
}
}
}
int main(void){
byte key128[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
byte key192[24] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17};
byte key256[32] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f};
byte pt[16] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff};
byte ct[sizeof pt];
byte vt[sizeof ct];
/* TWOFISH 128 */
CryptoPP::ECB_Mode<CryptoPP::Twofish>::Encryption ecb_enc_twofish128(key128, sizeof key128);
ecb_enc_twofish128.ProcessData(ct, pt, sizeof pt);
std::cout << "Plaintext: ";
print_raw_buffer(pt, sizeof pt);
std::cout << std::endl << "Key 128: ";
print_raw_buffer(key128, sizeof key128);
std::cout << std::endl << "Ciphertext 128: ";
print_raw_buffer(ct, sizeof ct);
CryptoPP::ECB_Mode<CryptoPP::Twofish>::Decryption ecb_dec_twofish128(key128, sizeof key128);
ecb_dec_twofish128.ProcessData(vt, ct, sizeof ct);
if (memcmp(pt, vt, sizeof pt)){
std::cout << std::endl << "Recovery 128: FAIL" << std::endl;
return EXIT_FAILURE;
}
std::cout << std::endl << "Recovery 128: OK" << std::endl;
/* TWOFISH 192 */
CryptoPP::ECB_Mode<CryptoPP::Twofish>::Encryption ecb_enc_twofish192(key192, sizeof key192);
ecb_enc_twofish192.ProcessData(ct, pt, sizeof pt);
std::cout << "Key 192: ";
print_raw_buffer(key192, sizeof key192);
std::cout << std::endl << "Ciphertext 192: ";
print_raw_buffer(ct, sizeof ct);
CryptoPP::ECB_Mode<CryptoPP::Twofish>::Decryption ecb_dec_twofish192(key192, sizeof key192);
ecb_dec_twofish192.ProcessData(vt, ct, sizeof ct);
if (memcmp(pt, vt, sizeof pt)){
std::cout << std::endl << "Recovery 192: FAIL" << std::endl;
return EXIT_FAILURE;
}
std::cout << std::endl << "Recovery 192: OK" << std::endl;
/* TWOFISH 256 */
CryptoPP::ECB_Mode<CryptoPP::Twofish>::Encryption ecb_enc_twofish256(key256, sizeof key256);
ecb_enc_twofish256.ProcessData(ct, pt, sizeof pt);
std::cout << "Key 256: ";
print_raw_buffer(key256, sizeof key256);
std::cout << std::endl << "Ciphertext 256: ";
print_raw_buffer(ct, sizeof ct);
CryptoPP::ECB_Mode<CryptoPP::Twofish>::Decryption ecb_dec_twofish256(key256, sizeof key256);
ecb_dec_twofish256.ProcessData(vt, ct, sizeof ct);
if (memcmp(pt, vt, sizeof pt)){
std::cout << std::endl << "Recovery 256: FAIL" << std::endl;
return EXIT_FAILURE;
}
std::cout << std::endl << "Recovery 256: OK" << std::endl;
return EXIT_SUCCESS;
}
| [
"pierre.lestringant@gmail.com"
] | pierre.lestringant@gmail.com |
41cf447a2938f60730d24422263e92d9dee7b6ad | 2b5fbd62812f10cfd41c37bb223bbaca8ce1dfe2 | /doc_guide/usage/chrono/datetime.hpp | ead4074a27d42dc8ec90b154c4fabbf19993afc2 | [
"Apache-2.0"
] | permissive | Better-Idea/Mix-C | 5e6adaa2399cc94437a18d2962ebbca016bc6e71 | 71f34a5fc8c17a516cf99bc397289d046364a82e | refs/heads/master | 2021-12-10T04:59:17.280741 | 2021-09-30T13:36:05 | 2021-09-30T13:36:05 | 208,288,799 | 45 | 9 | Apache-2.0 | 2021-01-05T07:08:29 | 2019-09-13T15:06:16 | C++ | UTF-8 | C++ | false | false | 10,150 | hpp | #define xuser mixc::powerful_cat
#include"chrono/day.hpp"
#include"chrono/datetime.hpp"
#include"chrono/time.hpp"
#include"chrono/now.hpp"
#include"mixc.hpp"
#include"utils/counter.hpp"
xinit(xuser::the_main){
using namespace xuser;
counter demo = 0;
auto show = [](auto d){
xhint(
d.year(),
d.month(),
d.day(),
d.hour(),
d.minute(),
d.second(),
d.milisecond()
);
};
// 演示:获取当前日期时间
{
xhint(demo);
// 获取当前日期时间
datetime<> date_now = now;
show(date_now);
}
// 演示:推荐的初始化日期方法
{
xhint(demo);
datetime<> d;
// 通过链式调用设置日期属性
// 创建日期
d.year(2020).month(12).day(6).hour(10).minute(28).second(59).milisecond(998);
show(d);
}
// 演示:判断日期是否合法
{
xhint(demo);
datetime<> d;
// 通过链式调用设置日期属性
// 创建日期
d.year(2020).month(12).day(6);
xhint(d.is_valid(), d.year(), d.month(), d.day());
// year 必须大于 0
// 该日期不合法
d.year(zero).month(12).day(6);
xhint(d.is_valid(), d.year(), d.month(), d.day());
// month 必须大于 0
// 该日期不合法
d.year(2020).month(zero).day(6);
xhint(d.is_valid(), d.year(), d.month(), d.day());
// month 必须小于等于 12
// 该日期不合法
d.year(2020).month(13).day(6);
xhint(d.is_valid(), d.year(), d.month(), d.day());
// day 必须大于 0
// 该日期不合法
d.year(2020).month(12).day(zero);
xhint(d.is_valid(), d.year(), d.month(), d.day());
// day 必须小于等于当月最大的天数
// day 溢出
// 该日期不合法
d.year(2020).month(12).day(32);
xhint(d.is_valid(), d.year(), d.month(), d.day());
// 因为 2020 年是闰年,所以 2 月有 29 天
// 该日期合法
d.year(2020).month(2).day(29);
xhint(d.is_valid(), d.year(), d.month(), d.day());
// 因为 2019 年是平年,所以 2 月只有 28 天
// 该日期不合法
d.year(2019).month(2).day(29);
xhint(d.is_valid(), d.year(), d.month(), d.day());
// 设置时间部分 ================================================================
d.year(2021).month(1).day(1);
// 对于 datetime,time 和 date 是一个整体
// 所以 hour 不能大于 23
d.hour(24).minute(zero).second(zero).milisecond(zero);
xhint(d.is_valid(), d.hour(), d.minute(), d.second(), d.milisecond());
// minute 不能大于 59
d.hour(zero).minute(59).second(zero).milisecond(zero);
xhint(d.is_valid(), d.hour(), d.minute(), d.second(), d.milisecond());
d.minute(60);
xhint(d.is_valid(), d.hour(), d.minute(), d.second(), d.milisecond());
// second 不能大于 59
d.minute(59).second(59);
xhint(d.is_valid(), d.hour(), d.minute(), d.second(), d.milisecond());
d.second(60);
xhint(d.is_valid(), d.hour(), d.minute(), d.second(), d.milisecond());
// 当允许润秒时 second 最大可以为 60
xhint(d.is_valid(allow_leap_second), d.hour(), d.minute(), d.second(), d.milisecond());
// 但不能超过 60
d.second(61);
xhint(d.is_valid(allow_leap_second), d.hour(), d.minute(), d.second(), d.milisecond());
// milisecond 不能大于 999
d.second(zero).milisecond(999);
xhint(d.is_valid(), d.hour(), d.minute(), d.second(), d.milisecond());
d.milisecond(1000);
xhint(d.is_valid(), d.hour(), d.minute(), d.second(), d.milisecond());
}
// 演示:判断当前年份是否是闰年
{
xhint(demo);
datetime<> d;
// 2003 不能被 4 整除,所以不是闰年
xhint(d.year(2003).is_leap());
// 1900 年由于能被 100 整除所以不是闰年
xhint(d.year(1900).is_leap());
// 2000 年是虽然能被 100 整除,由于也能被 400 整除,所以是闰年
xhint(d.year(2000).is_leap());
// 2004 年是闰年
xhint(d.year(2004).is_leap());
}
// 演示:计算明天对应的日期
{
xhint(demo);
datetime<> d;
d.year(2020).month(2).day(28);
// 明天是 2020/2/29
d = d.tomorrow();
xhint(d.year(), d.month(), d.day());
// 明天是 2020/3/1
d = d.tomorrow();
xhint(d.year(), d.month(), d.day());
// 明天是 2020/12/31
d.year(2020).month(12).day(30);
d = d.tomorrow();
xhint(d.year(), d.month(), d.day());
// 明天是 2021/1/1
d = d.tomorrow();
xhint(d.year(), d.month(), d.day());
// 注意:
// year 能表示的范围为[0, 2^23),所以一直迭代计算 tomorrow 会溢出,如果必要需要做边界处理
}
// 演示:计算昨天对应的日期
{
xhint(demo);
datetime<> d;
d.year(2020).month(3).day(2);
// 昨天是 2020/3/1
d = d.yesterday();
xhint(d.year(), d.month(), d.day());
// 昨天是 2020/2/29
d = d.yesterday();
xhint(d.year(), d.month(), d.day());
// 昨天是 2020/1/1
d.year(2020).month(1).day(2);
d = d.yesterday();
xhint(d.year(), d.month(), d.day());
// 昨天是 2019/12/31
d = d.yesterday();
xhint(d.year(), d.month(), d.day());
// 注意:
// year 能表示的范围为[0, 2^23),所以一直迭代计算 yesterday 会溢出,如果必要需要做边界处理
}
// 演示:日期减法
{
xhint(demo);
datetime<> d;
datetime<> old_date;
// 2 天前是 2020/2/29
d.year(2020).month(3).day(2);
d = d - day{2};
xhint(d.year(), d.month(), d.day());
// 1 年前是 2019/2/28
d = d - day{366}; /*2020 年全年 366 天*/
xhint(d.year(), d.month(), d.day());
old_date.year(2020).month(1).day(1);
d.year(2021).month(1).day(1);
// 注意:
// datetime 减法包括 time 部分的运算,所以最终结果的单位是 ms 毫秒
// 2020 年一共有 31‘622’400‘000ms
i64 diff = d - old_date;
xhint(diff);
}
// 演示:日期加法
{
xhint(demo);
datetime<> d;
datetime<> old_date;
// 27 天后是 2020/2/28
d.year(2020).month(2).day(1);
d = d + day{27};
xhint(d.year(), d.month(), d.day());
// 1 年后是 2021/2/28
d = d + day{366}; /*2020 年全年 366 天*/
xhint(d.year(), d.month(), d.day());
// 注意该日期是元年第一天
// 也就是所谓的第 0 日
old_date.year(1).month(1).day(1);
d.year(2021).month(1).day(1);
// 日期的相加就和指针的乘法一样并没有什么太大的意义
// 我们并没有提供显式的日期之间的加法,而是日期可以转成 day 类型
// 而 datetime 实现的是日期加减天数的运算重载
d = d + old_date/*隐式转成 day 类型*/;
// 由于加的是第 0 日,所以日期不变
xhint(d.year(), d.month(), d.day());
}
// 演示:今天是星期几
{
xhint(demo);
datetime<> today = now;
asciis day_of_week;
asciis lut[] = {
"sunday",
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
};
day_of_week = lut[(uxx)today.day_of_week()];
xhint(today.year(), today.month(), today.day(), day_of_week);
// 2020/2/29 是星期六
today.year(2020).month(2).day(29);
day_of_week = lut[(uxx)today.day_of_week()];
xhint(today.year(), today.month(), today.day(), day_of_week);
// 2019/2/28 是星期四
today.year(2019).month(2).day(28);
day_of_week = lut[(uxx)today.day_of_week()];
xhint(today.year(), today.month(), today.day(), day_of_week);
}
// 演示:今天是今年第几天
{
xhint(demo);
datetime<> today = now;
datetime<> d;
xhint(today.year(), today.month(), today.day(), today.day_of_year(), today.day_index_of_year());
// 第 1 天,索引 0
d.year(2020).month(1).day(1);
xhint(d.year(), d.month(), d.day(), d.day_of_year(), d.day_index_of_year());
// +31
// 第 32 天,索引 31
d.year(2020).month(2).day(1);
xhint(d.year(), d.month(), d.day(), d.day_of_year(), d.day_index_of_year());
d.year(2019).month(2).day(1);
xhint(d.year(), d.month(), d.day(), d.day_of_year(), d.day_index_of_year());
// +29
// 第 61 天,索引 60
d.year(2020).month(3).day(1);
xhint(d.year(), d.month(), d.day(), d.day_of_year(), d.day_index_of_year());
// +28
// 第 60 天,索引 59
d.year(2019).month(3).day(1);
xhint(d.year(), d.month(), d.day(), d.day_of_year(), d.day_index_of_year());
}
// 演示:计算总毫秒数
{
xhint(demo);
// 创建时间
datetime<> d;
u64 total_ms;
d.year(2020).month(12).day(6).hour(1).minute(2).second(3).milisecond(4);
total_ms = d.total_milisecond();
xhint(total_ms);
}
// 演示:比较两个日期
{
xhint(demo);
datetime<> a;
datetime<> b;
a.year(2020).month(1).day(2).hour(3).minute(4).second(5).milisecond(6);
b.year(2020).month(1).day(3).hour(3).minute(4).second(5).milisecond(6);
xhint(a == a, a == b, a > b, a >= b, a < b, a <= b);
}
};
| [
"x4495@outlook.com"
] | x4495@outlook.com |
c246b0367b9a1214a02c4ce04bf3441794edd343 | 395d1860e82bc75ccc04b91c4b9a8fa46276d9bb | /Source/Physics2012/Vehicle/Manager/hkpVehicleManager.h | 81c0e56b653a7331334ed2c98a96f4c9a257ac07 | [] | no_license | Hakhyun-Kim/projectanarchy | 28ba7370050000a12e4305faa11d5deb77c330a1 | ccea719afcb03967a68a169730b59e8a8a6c45f8 | refs/heads/master | 2021-06-03T04:41:22.814866 | 2013-11-07T07:21:03 | 2013-11-07T07:21:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,003 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_VEHICLE_MANAGER_H
#define HK_VEHICLE_MANAGER_H
#include <Physics2012/Dynamics/World/Listener/hkpWorldPostSimulationListener.h>
extern const class hkClass hkpVehicleManagerClass;
class hkpVehicleInstance;
/// A VehicleManager offers a way to simulate a set of vehicles together, and provides an alternative
/// to using actions.
/// It is intended that subclasses will multithread parts of the vehicle simulation, particularly wheel
/// collision detection.
///
/// The following property is assumed to be true of the vehicles in the manager:
/// EITHER ( all the vehicles' chassis and phantoms are added to the world )
/// OR ( none of the vehicles' chassis and phantoms are added to the world ).
class hkpVehicleManager : public hkReferencedObject
{
public:
HK_DECLARE_CLASS_ALLOCATOR( HK_MEMORY_CLASS_VEHICLE );
HK_DECLARE_REFLECTION();
hkpVehicleManager() { }
virtual ~hkpVehicleManager();
/// Register a vehicle with the manager.
/// \param vehicle the vehicle to be added.
virtual void addVehicle( hkpVehicleInstance* vehicle );
/// Remove a vehicle which has been registered with the manager.
/// \param vehicle the vehicle to be removed.
virtual void removeVehicle( hkpVehicleInstance* vehicle );
/// Build array of active vehicles from vehicles registered with the manager.
/// Inactive vehicles should not be stepped.
void getActiveVehicles( hkArray< hkpVehicleInstance* >& activeVehicles ) const;
//
// Singlethreaded simulation.
//
/// Update and simulate all registered vehicles.
/// The stepInfo must be updated for the current step in order to correctly
/// calculate vehicles' centers of mass
virtual void stepVehicles( const hkStepInfo& updatedStepInfo );
static void stepVehicleArray( hkArray<hkpVehicleInstance*>& activeVehicles, const hkStepInfo& updatedStepInfo );
//
// Simple accessors to the array.
//
/// Returns the number of registered vehicles.
inline int getNumVehicles() const;
/// Read/write access to the vehicle at the specified index.
inline hkpVehicleInstance& getVehicle( int index );
/// Read-only access to the vehicle at the specified index.
inline const hkpVehicleInstance& getVehicle( int index ) const;
//
// Adding and removing vehicles to and from the world.
//
/// Add the chassis and phantoms of all registered vehicles to the world.
void addToWorld( hkpWorld* world );
/// Remove the chassis and phantoms of all registered vehicles from the world.
void removeFromWorld();
public:
/// The array of currently registered vehicles.
hkArray<hkpVehicleInstance*> m_registeredVehicles;
hkpVehicleManager( hkFinishLoadedObjectFlag f ) : hkReferencedObject(f), m_registeredVehicles(f) { }
};
#include<Physics2012/Vehicle/Manager/hkpVehicleManager.inl>
#endif // HK_VEHICLE_MANAGER_H
/*
* Havok SDK - Base file, BUILD(#20131019)
*
* Confidential Information of Havok. (C) Copyright 1999-2013
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available from salesteam@havok.com.
*
*/
| [
"joel.van.eenwyk@havok.com"
] | joel.van.eenwyk@havok.com |
9663f1a8a47465756d8669bc3b26814c6b61d755 | 09f7c34a1f770e816daca2c49fe76bf1b79ff6fe | /problema_5/q2(2).cpp | 592e27135484c25ce87fe37e3ed9ed7340d5fb8d | [] | no_license | binaks/LP1 | 9b43aef481f7ee8b0d6a1c83e21ea4860db188b8 | 4f6c36f1f45ebfb9ff3f42def6d1cf65abe657f7 | refs/heads/master | 2021-01-01T19:27:10.711113 | 2017-09-28T23:12:40 | 2017-09-28T23:12:40 | 84,261,367 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,452 | cpp | #include <iostream>
using namespace std;
template<class T>
class conjunto
{
public:
conjunto(int n){
n_ = n;
v_ = new T[n];
}
conjunto() = default;
void n(int n);
void ler_conjunto();
void escrever_conjunto();
conjunto<T> diferenca_conjunto(conjunto<T> const& cB);
private:
int n_;
int na_=0;
T* v_;
};
template<class T>
void conjunto<T>::n(int n)
{
n_ = n;
}
template<class T>
void conjunto<T>::ler_conjunto()
{
for (int i = 0; i < n_; i++)
{
cout<<"Element "<<i+1<<": ";
cin>>v_[i];
for (int j = 0; j < n_; j++)
{
if(v_[i]==v_[j])
na_ = n_-1;
}
}
}
template<class T>
void conjunto<T>::escrever_conjunto()
{
cout<<"{";
for (int i = 0; i < n_; i++)
{
cout<<v_[i];
if(i<n_-1)
cout<<", ";
}
cout<<"}";
}
template<class T>
conjunto<T> conjunto<T>::diferenca_conjunto(conjunto<T> const& cB)
{
conjunto cC{n_};
for (int i = 0; i < n_; i++)
{
for (int j = i; j < cB.n_; j++)
{
if(v_[i] != cB.v_[j]){
cC.v_[i] = v_[i];
cC.na_ += 1;
break;
}
}
}
}
int main()
{
int a, b;
cout<<"Cardinalidade de A: ";
cin>>a;
cout<<"Cardinalidade de B: ";
cin>>b;
conjunto<int> cA{a}, cB{b}, cC{1};
cout<<"Informe elementos de A: \n";
cA.ler_conjunto();
cout<<"Informe elementos de B: \n";
cB.ler_conjunto();
cout<<"A = ";
cA.escrever_conjunto();
cout<<"B = ";
cB.escrever_conjunto();
cout<<"Difereça: ";
cC = cA.diferenca_conjunto(cB,cC);
cC.escrever_conjunto();
return 0;
} | [
"noreply@github.com"
] | binaks.noreply@github.com |
99e81d9e6ed3670d1f8ad45d6d30c1f03c8e9344 | b783b4d558ad4669428a478c98911450c6fcf20a | /ooid/gui/gooid.cpp | 7606dc11d59eafd7d14f2167ce85538bca4c01e8 | [
"Apache-2.0",
"BSL-1.0"
] | permissive | HalcyonGrid/whip-server | 5b12025888470be7128834ca04c38b32cee51a02 | 2b80d01b0029d93a4bfcc2fc2c0900002bedbfb3 | refs/heads/master | 2020-03-26T12:30:27.704163 | 2018-11-15T02:28:04 | 2018-11-15T02:28:04 | 144,896,262 | 2 | 5 | Apache-2.0 | 2018-08-19T07:32:37 | 2018-08-15T19:43:43 | C | UTF-8 | C++ | false | false | 795 | cpp | /********************************************************************\
* gooid.cpp -- UUID GUI *
* *
* Copyright (C) 2009 Kenneth Laskoski *
* *
\********************************************************************/
/** @file gooid.cpp
@brief graphical user interface to UUIDs defined by RFC 4122
@author Copyright (C) 2009 Kenneth Laskoski
Use, modification, and distribution are subject
to the Boost Software License, Version 1.0. (See accompanying file
LICENSE_1_0.txt or a copy at <http://www.boost.org/LICENSE_1_0.txt>.)
*/
#include "app.h"
IMPLEMENT_APP(App)
| [
"david.daeschler@gmail.com"
] | david.daeschler@gmail.com |
a6dbd90a0890d76d8fe212eef572e2912287a5eb | 5ed707de9f3de6044543886ea91bde39879bfae6 | /ASFantasy/Shared/Source/ASFantasyObjectBuilder.cpp | ec4a158222a1c1f13cc12b29904084f2addad40a | [] | no_license | grtvd/asifantasysports | 9e472632bedeec0f2d734aa798b7ff00148e7f19 | 76df32c77c76a76078152c77e582faa097f127a8 | refs/heads/master | 2020-03-19T02:25:23.901618 | 1999-12-31T16:00:00 | 2018-05-31T19:48:19 | 135,627,290 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,393 | cpp | /* ASFantasyObjectBuilder.cpp */
/******************************************************************************/
/******************************************************************************/
#include "CBldVCL.h"
#pragma hdrstop
#include "ASFantasyObjectBuilder.h"
#include "ASFantasyType.h"
using namespace asfantasy;
/******************************************************************************/
/******************************************************************************/
void* ASFantasyObjectBuilder::newInstance(const char* type)
{
if(fobt_TLeague == type)
return(new TLeague);
if(fobt_TProfTeam == type)
return(new TProfTeam);
if(fobt_TPlayer == type)
return(new TPlayer);
if(fobt_TDraftOrder == type)
return(new TDraftOrder);
if(fobt_TDraftRanking == type)
return(new TDraftRanking);
if(fobt_TDraftResult == type)
return(new TDraftResult);
if(fobt_TScheduleDay == type)
return(new TScheduleDay);
if(fobt_TGameResult == type)
return(new TGameResult);
if(fobt_TFreeAgentClaim == type)
return(new TFreeAgentClaim);
if(fobt_TTrade == type)
return(new TTrade);
return(ASMemberObjectBuilder::newInstance(type));
}
/******************************************************************************/
/******************************************************************************/
| [
"grtvd@users.noreply.github.com"
] | grtvd@users.noreply.github.com |
022ffcf82fe43173dba634851e5c4d6fbfe1f689 | be3167504c0e32d7708e7d13725c2dbc9232f2cb | /mameppk/src/mame/includes/spiders.h | bda39fea52d2bcffb782f550d5dea74d411b70fc | [] | no_license | sysfce2/MAME-Plus-Plus-Kaillera | 83b52085dda65045d9f5e8a0b6f3977d75179e78 | 9692743849af5a808e217470abc46e813c9068a5 | refs/heads/master | 2023-08-10T06:12:47.451039 | 2016-08-01T09:44:21 | 2016-08-01T09:44:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,752 | h | // license:BSD-3-Clause
// copyright-holders:Zsolt Vasvari
/***************************************************************************
Sigma Spiders hardware
***************************************************************************/
#include "sound/discrete.h"
#include "video/mc6845.h"
class spiders_state : public driver_device
{
public:
spiders_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag),
m_ram(*this, "ram"),
m_discrete(*this, "discrete"),
m_maincpu(*this, "maincpu"),
m_palette(*this, "palette"),
m_audiocpu(*this, "audiocpu") { }
required_shared_ptr<UINT8> m_ram;
required_device<discrete_device> m_discrete;
UINT8 m_flipscreen;
UINT16 m_gfx_rom_address;
UINT8 m_gfx_rom_ctrl_mode;
UINT8 m_gfx_rom_ctrl_latch;
UINT8 m_gfx_rom_ctrl_data;
DECLARE_WRITE_LINE_MEMBER(main_cpu_irq);
DECLARE_WRITE_LINE_MEMBER(main_cpu_firq);
DECLARE_WRITE_LINE_MEMBER(audio_cpu_irq);
DECLARE_WRITE_LINE_MEMBER(flipscreen_w);
DECLARE_WRITE_LINE_MEMBER(display_enable_changed);
DECLARE_WRITE8_MEMBER(gfx_rom_intf_w);
DECLARE_READ8_MEMBER(gfx_rom_r);
virtual void machine_start();
INTERRUPT_GEN_MEMBER(update_pia_1);
DECLARE_WRITE8_MEMBER(ic60_74123_output_changed);
DECLARE_WRITE8_MEMBER(spiders_audio_command_w);
DECLARE_WRITE8_MEMBER(spiders_audio_a_w);
DECLARE_WRITE8_MEMBER(spiders_audio_b_w);
DECLARE_WRITE8_MEMBER(spiders_audio_ctrl_w);
MC6845_UPDATE_ROW(crtc_update_row);
required_device<cpu_device> m_maincpu;
required_device<palette_device> m_palette;
required_device<cpu_device> m_audiocpu;
};
/*----------- defined in audio/spiders.c -----------*/
MACHINE_CONFIG_EXTERN( spiders_audio );
| [
"mameppk@199a702f-54f1-4ac0-8451-560dfe28270b"
] | mameppk@199a702f-54f1-4ac0-8451-560dfe28270b |
6852484504fc94bcb57b2ca97086a904b89f11cb | d766203f49613ed78e4a607c124d21073507a0f8 | /src/settingsadhoccommand.cpp | 00aacece68095a389c86cd22b7317e1b9131e47a | [
"BSL-1.0"
] | permissive | mdonoughe/libtransport | 22fac71199d0ae10ad717d73457228d0b1192d76 | c7e2635dde99a7b461c370ac87994059fcc12dd4 | refs/heads/master | 2021-01-15T19:39:37.438367 | 2012-08-10T12:29:13 | 2012-08-10T12:29:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,346 | cpp | /**
* XMPP - libpurple transport
*
* Copyright (C) 2012, Jan Kaluza <hanzz@soc.pidgin.im>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA
*/
#include "transport/settingsadhoccommand.h"
#include "transport/conversation.h"
#include "transport/usermanager.h"
#include "transport/buddy.h"
#include "transport/factory.h"
#include "transport/user.h"
#include "transport/logging.h"
namespace Transport {
DEFINE_LOGGER(logger, "SettingsAdHocCommand");
SettingsAdHocCommand::SettingsAdHocCommand(Component *component, const Swift::JID &initiator, const Swift::JID &to) : AdHocCommand(component, initiator, to) {
m_state = Init;
}
SettingsAdHocCommand::~SettingsAdHocCommand() {
}
boost::shared_ptr<Swift::Command> SettingsAdHocCommand::getForm() {
boost::shared_ptr<Swift::Command> response(new Swift::Command("settings", m_id, Swift::Command::Executing));
boost::shared_ptr<Swift::Form> form(new Swift::Form());
BOOST_FOREACH(Swift::FormField::ref field, m_fields) {
form->addField(field);
}
response->setForm(form);
return response;
}
boost::shared_ptr<Swift::Command> SettingsAdHocCommand::handleResponse(boost::shared_ptr<Swift::Command> payload) {
boost::shared_ptr<Swift::Command> response;
response->setStatus(Swift::Command::Completed);
return response;
}
boost::shared_ptr<Swift::Command> SettingsAdHocCommand::handleRequest(boost::shared_ptr<Swift::Command> payload) {
boost::shared_ptr<Swift::Command> response;
switch (m_state) {
case Init:
response = getForm();
m_state = WaitingForResponse;
break;
case WaitingForResponse:
response = handleResponse(payload);
break;
default:
break;
}
return response;
}
}
| [
"hanzz.k@gmail.com"
] | hanzz.k@gmail.com |
55e0eab4bf393999c62b59aa84bef56e216ed078 | 4c05eb220a3ae5b1cd0197f2f4d33759f26d9451 | /samod2/samod2/MTA10/game_sa/CWaterManagerSA.cpp | f60a998f8e629542dbf8fd1f5b3a2dfb488e6dc5 | [] | no_license | grasmanek94/PAWN-4-SinglePlayer-GTA-SA | 6276633ca3ad95d98d2d0302b160c3e68537c067 | 279569a3a5a257a36bcdc6ccb88a41ba76f62ae9 | refs/heads/master | 2020-12-24T20:52:25.112355 | 2016-04-25T23:48:14 | 2016-04-25T23:48:14 | 57,083,608 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,289 | cpp | /*****************************************************************************
*
* PROJECT: Multi Theft Auto v1.0
* LICENSE: See LICENSE in the top level directory
* FILE: game_sa/CWaterManagerSA.cpp
* PURPOSE: Control the lakes and seas
* DEVELOPERS: arc_
*
* Multi Theft Auto is available from http://www.multitheftauto.com/
*
*****************************************************************************/
#include "StdInc.h"
extern int ms_iNumNonDefaultAndNonZeroVertices;
using namespace std;
#define POLYENTRY_TYPE(entry) ( (entry)->m_wValue >> 14 )
#define POLYENTRY_ID(entry) ( (entry)->m_wValue & 0x3FFF )
#define MAKE_POLYENTRY(type, id) (WORD)( ((type) << 14) | (id) )
// These are code references in SA to the various data pools. We relocate these pools
// to our own buffers to have more space, and thus have to update all references.
DWORD CWaterManagerSA::m_VertexXrefs[] = {
0x6E5B6E, 0x6E5BC3, 0x6E5BF7, 0x6E5EA3, 0x6E5ED7, 0x6E5F84, 0x6E5F8B, 0x6E6487,
0x6E64A7, 0x6E65E4, 0x6E6608, 0x6E7B9B, 0x6E7BBC, 0x6E7C51, 0x6E7C73, 0x6E7E11,
0x6E7E18, 0x6E7E3A, 0x6E7E41, 0x6E7E5A, 0x6E7E61, 0x6E811C, 0x6E8127, 0x6E8143,
0x6E814E, 0x6E9E2F, 0x6E9E63, 0x6EA00A, 0x6EA04C, 0x6EA08E, 0x6EFC1F, 0x6EFC5E,
0x6EFC95, 0x6EFDF9, 0x6EFE31, 0x6E5B36, 0x6E5B75, 0x6E5C15, 0x6E5C45, 0x6E5EFC,
0x6E5F06, 0x6E64BF, 0x6E64E0, 0x6E6624, 0x6E6649, 0x6E7BDC, 0x6E7BF6, 0x6E7C58,
0x6E7C8E, 0x6E7DF8, 0x6E7E08, 0x6E7E31, 0x6E801C, 0x6E8029, 0x6E804B, 0x6E8060,
0x6E807B, 0x6E8088, 0x6E809A, 0x6E80BF, 0x6E80D8, 0x6E80FD, 0x6E9E8D, 0x6E9EC1,
0x6E9FFF, 0x6EA03D, 0x6EA07F, 0x6EFC18, 0x6EFC57, 0x6EFC8E, 0x6EFDCB, 0x6EFE2A,
0x6E5863, 0x6E58B7, 0x6E5945, 0x6E598F, 0x6E5B7B, 0x6E5CA9, 0x6E5CB3, 0x6E5CBB,
0x6E5CC7, 0x6E5CD3, 0x6E5D83, 0x6E5D8E, 0x6E5D96, 0x6E5DA3, 0x6E5DAE, 0x6E5FC4,
0x6E5FD0, 0x6E5FDE, 0x6E5FE4, 0x6E5FF0, 0x6E60AE, 0x6E60BA, 0x6E60C4, 0x6E60CA,
0x6E60D4, 0x6E9FC7, 0x6EFBF6, 0x6EFC35, 0x6EFC6C, 0x6EFD90, 0x6EFDC2, 0x6EFDF0,
0x6EFE1E, 0x6E5CEF, 0x6E5CFD, 0x6E5D06, 0x6E5D0D, 0x6E5D1A, 0x6E5DCB, 0x6E5DD9,
0x6E5DE2, 0x6E5DE9, 0x6E5DF4, 0x6E600C, 0x6E601A, 0x6E6025, 0x6E602C, 0x6E6039,
0x6E60F0, 0x6E60FE, 0x6E6107, 0x6E610E, 0x6E611B, 0x6E9F09, 0x6E9F41, 0x6E9F71,
0x6E9FA1, 0x6E5D30, 0x6E5D3E, 0x6E5D47, 0x6E5D4E, 0x6E5D5B, 0x6E5E0B, 0x6E5E19,
0x6E5E22, 0x6E5E29, 0x6E5E34, 0x6E604F, 0x6E605D, 0x6E6068, 0x6E606F, 0x6E607C,
0x6E6131, 0x6E613F, 0x6E6148, 0x6E614F, 0x6E615C, 0x6E9F20, 0x6E9F54, 0x6E9F84,
0x6E9FB4, 0x6EA0EE, 0x6EA149, 0x6EA193, 0x6EA1CB, 0x6EA0F5, 0x6EA150, 0x6EA19A,
0x6EA1D2, 0x000000
};
DWORD CWaterManagerSA::m_QuadXrefs[] = {
0x6E5859, 0x6E5985, 0x6E63C8, 0x6E652B, 0x6E7B88, 0x6E816A, 0x6E8635, 0x6E8709,
0x6E9E1D, 0x6E8171, 0x6E8178, 0x6EFCCF, 0x6E817F, 0x6E5849, 0x6E588A, 0x6E5979,
0x6E59B0, 0x6E8185, 0x6E8199, 0x6E81AD, 0x6E81B5, 0x6E81CB, 0x000000
};
DWORD CWaterManagerSA::m_TriangleXrefs[] = {
0x6E58AD, 0x6E593B, 0x6E7C44, 0x6E7E7F, 0x6E8673, 0x6E86E4, 0x6EFC27, 0x6E7C64,
0x6E7E8B, 0x6EFBEA, 0x6E7C7F, 0x6E7E93, 0x6EFBE2, 0x6E589D, 0x6E58DE, 0x6E592F,
0x6E5966, 0x6E7E9A, 0x6E7EA8, 0x6E7EBD, 0x6E7EC6, 0x6E7EDA, 0x6EFBD3, 0x6EFCA3,
0x000000
};
DWORD CWaterManagerSA::m_ZonePolyXrefs[] = {
0x6E57B2, 0x6E57AA, 0x6E57C8, 0x6E58F2, 0x6E638F, 0x6E86A1, 0x6E6387, 0x6E8699,
0x6E57DE, 0x6E57E8, 0x000000
};
CWaterManagerSA* g_pWaterManager = NULL;
// -----------------------------------------------------
// Water zone iterator (iterates over polys in a zone)
CWaterZoneSA::iterator::iterator ()
{
m_pCurrent = NULL;
m_pFirst = NULL;
m_bSinglePoly = false;
}
CWaterZoneSA::iterator::iterator ( CWaterZoneSA* pZone )
{
if ( POLYENTRY_TYPE ( pZone->GetInterface () ) == WATER_POLY_LIST )
{
m_pCurrent = &g_pWaterManager->m_ZonePolyPool [ POLYENTRY_ID ( pZone->GetInterface () ) ];
m_bSinglePoly = false;
}
else
{
m_pCurrent = pZone->GetInterface ();
m_bSinglePoly = true;
}
m_pFirst = m_pCurrent;
}
CWaterZoneSA::iterator::iterator ( const CWaterZoneSA::iterator& other )
{
operator= ( other );
}
CWaterZoneSA::iterator& CWaterZoneSA::iterator::operator= ( const CWaterZoneSA::iterator& other )
{
m_pCurrent = other.m_pCurrent;
m_pFirst = other.m_pFirst;
m_bSinglePoly = other.m_bSinglePoly;
return *this;
}
void CWaterZoneSA::iterator::operator++ ()
{
m_pCurrent++;
}
void CWaterZoneSA::iterator::operator-- ()
{
m_pCurrent--;
}
CWaterZoneSA::iterator CWaterZoneSA::iterator::operator+ ( int n )
{
iterator it ( *this );
it.m_pCurrent += n;
return it;
}
CWaterZoneSA::iterator CWaterZoneSA::iterator::operator- ( int n )
{
iterator it ( *this );
it.m_pCurrent -= n;
return it;
}
int CWaterZoneSA::iterator::operator- ( CWaterZoneSA::iterator& other )
{
return other.m_pCurrent - m_pCurrent;
}
bool CWaterZoneSA::iterator::operator== ( const CWaterZoneSA::iterator& other )
{
return m_pCurrent == other.m_pCurrent;
}
bool CWaterZoneSA::iterator::operator!= ( const CWaterZoneSA::iterator& other )
{
return m_pCurrent != other.m_pCurrent;
}
CWaterPolySA* CWaterZoneSA::iterator::operator* ()
{
if ( (m_bSinglePoly && m_pCurrent != m_pFirst) || m_pCurrent->m_wValue == 0 )
return NULL;
if ( POLYENTRY_TYPE ( m_pCurrent ) == WATER_POLY_QUAD )
{
return &g_pWaterManager->m_Quads [ POLYENTRY_ID ( m_pCurrent ) ];
}
else if ( POLYENTRY_TYPE ( m_pCurrent ) == WATER_POLY_TRIANGLE )
{
return &g_pWaterManager->m_Triangles [ POLYENTRY_ID ( m_pCurrent ) ];
}
return NULL;
}
CWaterZoneSA::iterator::operator CWaterPolyEntrySAInterface* ()
{
return m_pCurrent;
}
CWaterZoneSA::iterator CWaterZoneSA::begin ()
{
return iterator ( this );
}
CWaterZoneSA::iterator CWaterZoneSA::end ()
{
iterator it ( this );
while ( *it )
++it;
return it;
}
// -----------------------------------------------------
// Water zones
// SA divides the world in 500x500 squares, each of these squares is called a "zone"
// here. These zones are used for quickly finding the water polygons near a given
// point (e.g. the player for swimming, the camera for underwater post effects)
// Each zone has a list of water polygons that partially or completely overlap it.
CWaterPolyEntrySAInterface* CWaterZoneSA::AddPoly ( CWaterPoly* pPoly )
{
return AddPoly ( pPoly->GetType (), pPoly->GetID () );
}
CWaterPolyEntrySAInterface* CWaterZoneSA::AddPoly ( EWaterPolyType type, WORD wID )
{
if ( m_pInterface->m_wValue == 0 )
{
m_pInterface->m_wValue = MAKE_POLYENTRY ( type, wID );
return m_pInterface;
}
else if ( POLYENTRY_TYPE ( m_pInterface ) != WATER_POLY_LIST )
{
if ( *(DWORD *)VAR_NumWaterZonePolys + 3 > NUM_NewWaterZonePolys )
return NULL;
WORD wOffset = *(WORD *)VAR_NumWaterZonePolys;
g_pWaterManager->m_ZonePolyPool [ wOffset ].m_wValue = MAKE_POLYENTRY ( type, wID );
g_pWaterManager->m_ZonePolyPool [ wOffset + 1 ].m_wValue = m_pInterface->m_wValue;
g_pWaterManager->m_ZonePolyPool [ wOffset + 2 ].m_wValue = 0;
m_pInterface->m_wValue = MAKE_POLYENTRY ( WATER_POLY_LIST, wOffset );
MemAddFast < DWORD > ( VAR_NumWaterZonePolys, 3 );
return &g_pWaterManager->m_ZonePolyPool [ wOffset + 1 ];
}
else
{
if ( *(DWORD *)VAR_NumWaterZonePolys + 1 > NUM_NewWaterZonePolys )
return NULL;
CWaterPolyEntrySAInterface* pZoneStart = (CWaterPolyEntrySAInterface *)begin ();
CWaterPolyEntrySAInterface* pEntry = &g_pWaterManager->m_ZonePolyPool [ *(DWORD *)VAR_NumWaterZonePolys ];
while ( pEntry > pZoneStart )
{
pEntry->m_wValue = (pEntry - 1)->m_wValue;
pEntry--;
}
pZoneStart->m_wValue = MAKE_POLYENTRY ( type, wID );
WORD wZoneStartOffset = pZoneStart - g_pWaterManager->m_ZonePolyPool;
CWaterPolyEntrySAInterface* pZoneInterface = (CWaterPolyEntrySAInterface *)ARRAY_WaterZones;
for ( ; pZoneInterface != &((CWaterPolyEntrySAInterface *)ARRAY_WaterZones) [ NUM_WaterZones ]; pZoneInterface++ )
{
if ( POLYENTRY_TYPE ( pZoneInterface ) == WATER_POLY_LIST &&
POLYENTRY_ID ( pZoneInterface ) > wZoneStartOffset )
pZoneInterface->m_wValue++;
}
(*(DWORD *)VAR_NumWaterZonePolys)++;
return pZoneStart;
}
}
bool CWaterZoneSA::RemovePoly ( CWaterPoly* pPoly )
{
return RemovePoly ( pPoly->GetType (), pPoly->GetID () );
}
bool CWaterZoneSA::RemovePoly ( EWaterPolyType type, WORD wID )
{
if ( m_pInterface->m_wValue == 0 )
{
return false;
}
else if ( POLYENTRY_TYPE ( m_pInterface ) != WATER_POLY_LIST )
{
if ( POLYENTRY_ID ( m_pInterface ) == wID )
{
m_pInterface->m_wValue = 0;
return true;
}
else
{
return false;
}
}
else
{
CWaterPolyEntrySAInterface* pEntries = (CWaterPolyEntrySAInterface *)begin ();
CWaterPolyEntrySAInterface* pEnd = &g_pWaterManager->m_ZonePolyPool [ *(DWORD *)VAR_NumWaterZonePolys ];
WORD wOffset = pEntries - g_pWaterManager->m_ZonePolyPool;
if ( end () - begin () == 2 )
{
if ( pEntries [ 0 ].m_wValue == MAKE_POLYENTRY ( type, wID ) ||
pEntries [ 1 ].m_wValue == MAKE_POLYENTRY ( type, wID ) )
{
if ( pEntries [ 0 ].m_wValue == MAKE_POLYENTRY ( type, wID ) )
m_pInterface->m_wValue = pEntries [ 1 ].m_wValue;
else
m_pInterface->m_wValue = pEntries [ 0 ].m_wValue;
CWaterPolyEntrySAInterface* pEntry = pEntries + 3;
for ( ; pEntry < pEnd; pEntry++ )
(pEntry - 3)->m_wValue = pEntry->m_wValue;
CWaterPolyEntrySAInterface* pZoneInterface = (CWaterPolyEntrySAInterface *)ARRAY_WaterZones;
for ( ; pZoneInterface < &((CWaterPolyEntrySAInterface *)ARRAY_WaterZones) [ NUM_WaterZones ]; pZoneInterface++ )
{
if ( POLYENTRY_TYPE ( pZoneInterface ) == WATER_POLY_LIST &&
POLYENTRY_ID ( pZoneInterface ) > wOffset )
pZoneInterface->m_wValue -= 3;
}
MemSubFast < DWORD > ( VAR_NumWaterZonePolys, 3 );
return true;
}
else
{
return false;
}
}
else
{
for ( iterator it = begin (); *it; ++it )
{
if ( (*it)->GetType () == type && (*it)->GetID () == wID )
{
CWaterPolyEntrySAInterface* pEntry = (CWaterPolyEntrySAInterface *)it + 1;
for ( ; pEntry < pEnd; pEntry++ )
(pEntry - 1)->m_wValue = pEntry->m_wValue;
CWaterPolyEntrySAInterface* pZoneInterface = (CWaterPolyEntrySAInterface *)ARRAY_WaterZones;;
for ( ; pZoneInterface < &((CWaterPolyEntrySAInterface *)ARRAY_WaterZones) [ NUM_WaterZones ]; pZoneInterface++ )
{
if ( POLYENTRY_TYPE ( pZoneInterface ) == WATER_POLY_LIST &&
POLYENTRY_ID ( pZoneInterface ) > wOffset )
pZoneInterface->m_wValue--;
}
(*(DWORD *)VAR_NumWaterZonePolys)--;
return true;
}
}
return false;
}
}
}
// -----------------------------------------------------
// Change trackkeepers
void CWaterChangeVertexMove::Undo ( void* pChangedObject )
{
((CWaterVertexSA *)pChangedObject)->SetPosition ( m_vecOriginalPosition );
}
// -----------------------------------------------------
// Manager
CWaterManagerSA::CWaterManagerSA ()
{
g_pWaterManager = this;
m_bInitializedVertices = false;
m_bAltRenderOrder = false;
m_iActivePolyCount = 0;
m_bWaterDrawnLast = true;
RelocatePools ();
InstallHooks ();
for ( DWORD i = 0; i < NUM_WaterZones; i++ )
m_Zones [ i ].SetInterface ( &((CWaterPolyEntrySAInterface *)ARRAY_WaterZones) [ i ] );
for ( DWORD i = 0; i < NUM_NewWaterVertices; i++ )
m_Vertices [ i ].SetInterface ( &m_VertexPool [ i ] );
for ( DWORD i = 0; i < NUM_NewWaterQuads; i++ )
m_Quads [ i ].SetInterface ( &m_QuadPool [ i ] );
for ( DWORD i = 0; i < NUM_NewWaterTriangles; i++ )
m_Triangles [ i ].SetInterface ( &m_TrianglePool [ i ] );
}
CWaterManagerSA::~CWaterManagerSA ()
{
UndoChanges ();
g_pWaterManager = NULL;
}
void CWaterManagerSA::RelocatePools ()
{
DWORD* pXrefGroups[] = { m_VertexXrefs, m_QuadXrefs, m_TriangleXrefs, m_ZonePolyXrefs, 0 };
void* pNewPools[] = { m_VertexPool, m_QuadPool, m_TrianglePool, m_ZonePolyPool, 0 };
DWORD** pXrefGroup = NULL;
void* pNewPool = NULL;
for ( int i = 0; pXrefGroup = (DWORD **)pXrefGroups [ i ]; i++ )
{
pNewPool = pNewPools [ i ];
DWORD dwDelta = (DWORD)pNewPool - *pXrefGroup [ 0 ];
for ( DWORD** ppXref = pXrefGroup; *ppXref; ppXref++ )
{
MemAdd < DWORD > ( *ppXref, dwDelta );
}
}
//
// Fix outside world water blocks disappearing when using long draw distances
//
// GTA default is 70 blocks. We increase this to 512 which is 2^9
#define OUTSIDE_WORLD_BLOCKS_BITS 9
static short ms_BlocksToBeRenderedOutsideWorldX[ 1 << OUTSIDE_WORLD_BLOCKS_BITS ];
static short ms_BlocksToBeRenderedOutsideWorldY[ 1 << OUTSIDE_WORLD_BLOCKS_BITS ];
BYTE part1[] = { 0xC1, 0xF8, OUTSIDE_WORLD_BLOCKS_BITS + 1, // sar eax,13 = 2^(10-1) = 512
0x7A, 0x19 }; // jp part2 Effectively jump always
BYTE part2[] = { 0x72, 0xFB, // jc exit Jump if at limit
0xA1, 0xEC, 0x15, 0xC2, 0x00, // mov eax,NumBlocks Restore eax
0x73, 0xDE }; // jnc dothing Effectively jump always
MemCpy ( (void*)0x6E6CE9, part1, sizeof ( part1 ) );
MemCpy ( (void*)0x6E6D07, part2, sizeof ( part2 ) );
MemPut < uint > ( 0x6E6CF2, (uint)&ms_BlocksToBeRenderedOutsideWorldX );
MemPut < uint > ( 0x6E6CFA, (uint)&ms_BlocksToBeRenderedOutsideWorldY );
MemPut < uint > ( 0x6EF6E4, (uint)&ms_BlocksToBeRenderedOutsideWorldX );
MemPut < uint > ( 0x6EF6EC, (uint)&ms_BlocksToBeRenderedOutsideWorldY );
MemPut < uint > ( 0x6EFE86, (uint)&ms_BlocksToBeRenderedOutsideWorldX );
MemPut < uint > ( 0x6EFE99, (uint)&ms_BlocksToBeRenderedOutsideWorldY );
MemPut < uint > ( 0x6EFEB3, (uint)&ms_BlocksToBeRenderedOutsideWorldY );
}
// The following hooks change the way SA iterates over water polygons.
// Normally it simply iterates over the first NumPolies slots in the
// pool; however in MTA, we can dynamically delete water polys,
// creating gaps. These hooks make SA skip empty pool slots.
DWORD dwHook6E9E23continue = 0x6E9E29;
void __declspec(naked) Hook6E9E23 ()
{
__asm
{
check:
mov eax, dword ptr [edi]
test eax, eax
jnz cont
add edi, 0xA // sizeof(CWaterQuadSAInterface)
jmp check
cont:
movsx eax, word ptr [edi]
lea ebx, [eax+4*eax]
jmp dwHook6E9E23continue
}
}
DWORD dwHook6EFCD7continue = 0x6EFCDD;
DWORD dwHook6EFCD7skip = 0x6EFE5E;
void __declspec(naked) Hook6EFCD7 ()
{
__asm
{
mov eax, dword ptr [esi-4]
test eax, eax
jz check
jmp dwHook6EFCD7skip
check:
add esi, 0xA // sizeof(CWaterQuadSAInterface)
mov eax, dword ptr [esi-4]
test eax, eax
jz check
jmp dwHook6EFCD7continue
}
}
DWORD dwHook6EFBD8continue = 0x6EFBDE;
void __declspec(naked) Hook6EFBD8 ()
{
__asm
{
check:
mov eax, 0x6EFC27
mov eax, dword ptr [eax]
mov eax, dword ptr [eax+8*esi]
test eax, eax
jnz cont
inc esi
jmp check
cont:
jmp dwHook6EFBD8continue
}
}
void CWaterManagerSA::InstallHooks ()
{
HookInstall ( 0x6E9E23, (DWORD)Hook6E9E23, 6 );
MemPut < DWORD > ( 0x6EFCD9, (DWORD)Hook6EFCD7 - 0x6EFCDD );
MemPut < DWORD > ( 0x6EFBC7, 0x05EBED33 );
MemPut < DWORD > ( 0x6EFBCB, 0x90909090 );
MemPut < BYTE > ( 0x6EFBCF, 0x46 );
MemPut < DWORD > ( 0x6EFBDA, (DWORD)Hook6EFBD8 - 0x6EFBDE );
MemPut < BYTE > ( 0x6EFBFB, 0x17 );
MemPut < BYTE > ( 0x6EFC02, 0x13 );
MemPut < BYTE > ( 0x6EFC04, 0x57 );
MemPut < BYTE > ( 0x6EFC07, 0x53 );
MemPut < BYTE > ( 0x6EFC0A, 0x57 );
MemPut < BYTE > ( 0x6EFC10, 0x53 );
MemPut < BYTE > ( 0x6EFCB2, 0x45 );
MemPut < BYTE > ( 0x6EFCB4, 0xE8 );
MemPut < BYTE > ( 0x6EFCB7, 0x14 );
}
CWaterZoneSA* CWaterManagerSA::GetZoneContaining ( float fX, float fY )
{
if ( fX < -3000.0f || fX > 3000.0f || fY < -3000.0f || fY > 3000.0f )
return NULL;
if ( fX == 3000.0f )
fX = 2999.0f;
if ( fY == 3000.0f )
fY = 2999.0f;
int zoneID = 12*((int)(fX + 3000.0f) / 500) + (int)(fY + 3000.0f) / 500;
return &m_Zones [ zoneID ];
}
void CWaterManagerSA::GetZonesContaining ( CWaterPoly* pPoly, std::vector < CWaterZoneSA* >& out )
{
CVector v1;
CVector v2;
CVector v3;
pPoly->GetVertex ( 0 )->GetPosition ( v1 );
pPoly->GetVertex ( 1 )->GetPosition ( v2 );
pPoly->GetVertex ( 2 )->GetPosition ( v3 );
GetZonesContaining ( v1, v2, v3, out );
}
void CWaterManagerSA::GetZonesContaining ( const CVector& v1, const CVector& v2, const CVector& v3, std::vector < CWaterZoneSA* >& out )
{
out.clear ();
float fColumnLeft = -3000.0f;
for ( int column = 0; column < 12; column++ )
{
float fRowBottom = -3000.0f;
for ( int row = 0; row < 12; row++ )
{
if ( v2.fX >= fColumnLeft && v1.fX < fColumnLeft + 500.0f && std::max<float>(v1.fY, v3.fY) >= fRowBottom && std::min<float>(v1.fY, v3.fY) < fRowBottom + 500.0f )
out.push_back ( &m_Zones [ column*12 + row ] );
fRowBottom += 500.0f;
}
fColumnLeft += 500.0f;
}
}
CWaterVertex* CWaterManagerSA::CreateVertex ( const CVector& vecPosition )
{
WORD wID = ( (CreateWaterVertex_t) FUNC_CreateWaterVertex )( (long)vecPosition.fX & ~1, (long)vecPosition.fY & ~1, vecPosition.fZ, 0.2f, 0.1f, 0 );
return &m_Vertices [ wID ];
}
CWaterPoly* CWaterManagerSA::GetPolyAtPoint ( const CVector& vecPosition )
{
if ( vecPosition.fX < -3000.0f || vecPosition.fX > 3000.0f || vecPosition.fY < -3000.0f || vecPosition.fY > 3000.0f )
return NULL;
CWaterZoneSA* pZone = GetZoneContaining ( vecPosition.fX, vecPosition.fY );
if ( !pZone )
return NULL;
CWaterZoneSA::iterator it;
for ( it = pZone->begin (); *it; ++it )
{
if ( (*it)->ContainsPoint ( vecPosition.fX, vecPosition.fY ) )
{
return *it;
}
}
return NULL;
}
CWaterPoly* CWaterManagerSA::CreateQuad ( const CVector& vecBL, const CVector& vecBR, const CVector& vecTL, const CVector& vecTR, bool bShallow )
{
if ( *(DWORD *)VAR_NumWaterQuads >= NUM_NewWaterQuads )
return NULL;
if ( vecTL.fX >= vecTR.fX || vecBL.fX >= vecBR.fX ||
vecTL.fY <= vecBL.fY || vecTR.fY <= vecBR.fY ||
vecTL.fX < -3000.0f || vecTL.fX > 3000.0f || vecTL.fY < -3000.0f || vecTL.fY > 3000.0f ||
vecTR.fX < -3000.0f || vecTR.fX > 3000.0f || vecTR.fY < -3000.0f || vecTR.fY > 3000.0f ||
vecBL.fX < -3000.0f || vecBL.fX > 3000.0f || vecBL.fY < -3000.0f || vecBL.fY > 3000.0f ||
vecBR.fX < -3000.0f || vecBR.fX > 3000.0f || vecBR.fY < -3000.0f || vecBR.fY > 3000.0f )
return NULL;
if ( *(DWORD *)VAR_NumWaterVertices + 4 > NUM_NewWaterVertices ||
*(DWORD *)VAR_NumWaterQuads + 1 > NUM_NewWaterQuads ||
*(DWORD *)VAR_NumWaterZonePolys + 2 > NUM_NewWaterZonePolys )
return NULL;
std::vector < CWaterZoneSA* > zones;
g_pWaterManager->GetZonesContaining ( vecBL, vecBR, vecTL, zones );
if ( zones.empty () )
return NULL;
CWaterVertex* pV1 = CreateVertex ( vecBL );
CWaterVertex* pV2 = CreateVertex ( vecBR );
CWaterVertex* pV3 = CreateVertex ( vecTL );
CWaterVertex* pV4 = CreateVertex ( vecTR );
CWaterQuadSAInterface* pInterface = g_pWaterManager->m_QuadPool;
while ( *(DWORD *)&pInterface->m_wVertexIDs != 0 )
pInterface++;
pInterface->m_wVertexIDs [ 0 ] = pV1->GetID ();
pInterface->m_wVertexIDs [ 1 ] = pV2->GetID ();
pInterface->m_wVertexIDs [ 2 ] = pV3->GetID ();
pInterface->m_wVertexIDs [ 3 ] = pV4->GetID ();
pInterface->m_wFlags = WATER_VISIBLE;
if ( bShallow )
pInterface->m_wFlags |= WATER_SHALLOW;
WORD wID = (WORD)(pInterface - g_pWaterManager->m_QuadPool);
std::vector < CWaterZoneSA* >::iterator it;
for ( it = zones.begin (); it != zones.end (); it++)
(*it)->AddPoly ( WATER_POLY_QUAD, wID );
(*(DWORD *)VAR_NumWaterQuads)++;
CWaterQuadSA* pPoly = &g_pWaterManager->m_Quads [ wID ];
m_iActivePolyCount++;
UpdateRenderOrderRequirement ();
return pPoly;
}
CWaterPoly* CWaterManagerSA::CreateTriangle ( const CVector& vec1, const CVector& vec2, const CVector& vec3, bool bShallow )
{
if ( *(DWORD *)VAR_NumWaterVertices >= NUM_NewWaterVertices )
return NULL;
if ( vec1.fX >= vec2.fX || vec1.fY == vec3.fY || vec2.fY == vec3.fY ||
(vec1.fY < vec3.fY) != (vec2.fY < vec3.fY) ||
vec1.fX < -3000.0f || vec1.fX > 3000.0f || vec1.fY < -3000.0f || vec1.fY > 3000.0f ||
vec2.fX < -3000.0f || vec2.fX > 3000.0f || vec2.fY < -3000.0f || vec2.fY > 3000.0f ||
vec3.fX < -3000.0f || vec3.fX > 3000.0f || vec3.fY < -3000.0f || vec3.fY > 3000.0f )
return NULL;
if ( *(DWORD *)VAR_NumWaterVertices + 4 > NUM_NewWaterVertices ||
*(DWORD *)VAR_NumWaterTriangles + 1 > NUM_NewWaterTriangles ||
*(DWORD *)VAR_NumWaterZonePolys + 2 > NUM_NewWaterZonePolys )
return NULL;
std::vector < CWaterZoneSA* > zones;
g_pWaterManager->GetZonesContaining ( vec1, vec2, vec3, zones );
if ( zones.empty () )
return NULL;
CWaterVertex* pV1 = CreateVertex ( vec1 );
CWaterVertex* pV2 = CreateVertex ( vec2 );
CWaterVertex* pV3 = CreateVertex ( vec3 );
CWaterTriangleSAInterface* pInterface = g_pWaterManager->m_TrianglePool;
while ( *(DWORD *)&pInterface->m_wVertexIDs != 0 )
pInterface++;
pInterface->m_wVertexIDs [ 0 ] = pV1->GetID ();
pInterface->m_wVertexIDs [ 1 ] = pV2->GetID ();
pInterface->m_wVertexIDs [ 2 ] = pV3->GetID ();
pInterface->m_wFlags = WATER_VISIBLE;
if ( bShallow )
pInterface->m_wFlags |= WATER_SHALLOW;
WORD wID = (WORD)(pInterface - g_pWaterManager->m_TrianglePool);
std::vector < CWaterZoneSA* >::iterator it;
for ( it = zones.begin (); it != zones.end (); it++)
(*it)->AddPoly ( WATER_POLY_TRIANGLE, wID );
(*(DWORD *)VAR_NumWaterTriangles)++;
CWaterTriangleSA* pPoly = &g_pWaterManager->m_Triangles [ wID ];
m_iActivePolyCount++;
UpdateRenderOrderRequirement ();
return pPoly;
}
bool CWaterManagerSA::DeletePoly ( CWaterPoly* pPoly )
{
std::vector < CWaterZoneSA* > zones;
GetZonesContaining ( pPoly, zones );
if ( zones.empty () )
return false;
std::vector < CWaterZoneSA* >::iterator it;
for ( it = zones.begin (); it != zones.end (); it++ )
(*it)->RemovePoly ( pPoly );
if ( pPoly->GetType () == WATER_POLY_QUAD )
{
MemSetFast ( ((CWaterQuadSA *)pPoly)->GetInterface (), 0, sizeof ( CWaterQuadSAInterface ) );
(*(DWORD *)VAR_NumWaterQuads)--;
}
else
{
MemSetFast ( ((CWaterTriangleSA *)pPoly)->GetInterface (), 0, sizeof ( CWaterTriangleSAInterface ) );
(*(DWORD *)VAR_NumWaterTriangles)--;
}
m_iActivePolyCount--;
UpdateRenderOrderRequirement ();
return true;
}
bool CWaterManagerSA::GetWaterLevel ( const CVector& vecPosition, float* pfLevel, bool bCheckWaves, CVector* pvecUnknown )
{
return ( (GetWaterLevel_t) FUNC_GetWaterLevel )
( vecPosition.fX, vecPosition.fY, vecPosition.fZ, pfLevel, bCheckWaves, pvecUnknown );
}
bool CWaterManagerSA::SetPositionWaterLevel ( const CVector& vecPosition, float fLevel, void* pChangeSource )
{
// Specific water poly
CWaterPoly* pPoly = GetPolyAtPoint ( vecPosition );
if ( !pPoly )
return false;
return SetPolyWaterLevel ( pPoly, fLevel, pChangeSource );
}
bool CWaterManagerSA::SetWorldWaterLevel ( float fLevel, void* pChangeSource, bool bIncludeWorldNonSeaLevel )
{
assert ( m_bInitializedVertices );
CVector vecVertexPos;
for ( DWORD i = 0; i < NUM_DefWaterVertices; i++ )
{
m_Vertices [ i ].GetPosition ( vecVertexPos );
if ( bIncludeWorldNonSeaLevel || !m_Vertices [ i ].IsWorldNonSeaLevel () )
vecVertexPos.fZ = fLevel;
m_Vertices [ i ].SetPosition ( vecVertexPos, pChangeSource );
}
return true;
}
bool CWaterManagerSA::SetPolyWaterLevel ( CWaterPoly* pPoly, float fLevel, void* pChangeSource )
{
CVector vecVertexPos;
for ( int i = 0; i < pPoly->GetNumVertices (); i++ )
{
pPoly->GetVertex ( i )->GetPosition ( vecVertexPos );
vecVertexPos.fZ = fLevel;
pPoly->GetVertex ( i )->SetPosition ( vecVertexPos, pChangeSource );
}
return true;
}
float CWaterManagerSA::GetWaveLevel ()
{
return *(float *)VAR_WaveLevel;
}
void CWaterManagerSA::SetWaveLevel ( float fWaveLevel )
{
if ( fWaveLevel >= 0.0f )
{
// DISABLE the game resetting the wave level
MemPut < BYTE > ( 0x72C665, 0xDD );
MemPut < BYTE > ( 0x72C666, 0xD8 );
MemSet ( (void*)0x72C667, 0x90, 4 );
MemSet ( (void*)0x72C659, 0x90, 10 );
MemPutFast < float > ( VAR_WaveLevel, fWaveLevel );
}
else
{
MemPut < BYTE > ( 0x72C665, 0xD9 );
MemPut < BYTE > ( 0x72C666, 0x1D );
MemPut < BYTE > ( 0x72C667, 0xE8 );
MemPut < BYTE > ( 0x72C668, 0x12 );
MemPut < BYTE > ( 0x72C669, 0xC8 );
MemPut < BYTE > ( 0x72C66A, 0x00 );
MemPut < BYTE > ( 0x72C659, 0xC7 );
MemPut < BYTE > ( 0x72C65A, 0x05 );
MemPut < BYTE > ( 0x72C65B, 0xE8 );
MemPut < BYTE > ( 0x72C65C, 0x12 );
MemPut < BYTE > ( 0x72C65D, 0xC8 );
MemPut < BYTE > ( 0x72C65E, 0x00 );
MemPut < BYTE > ( 0x72C65F, 0x00 );
MemPut < BYTE > ( 0x72C660, 0x00 );
MemPut < BYTE > ( 0x72C661, 0x80 );
MemPut < BYTE > ( 0x72C662, 0x3F );
MemPutFast < float > ( VAR_WaveLevel, 0.6f );
}
}
bool CWaterManagerSA::TestLineAgainstWater ( const CVector& vecStart, const CVector& vecEnd, CVector* vecCollision )
{
return ( (TestLineAgainstWater_t) FUNC_TestLineAgainstWater )
( vecEnd.fX, vecEnd.fY, vecEnd.fZ, vecStart.fX, vecStart.fY, vecStart.fZ, vecCollision );
}
void CWaterManagerSA::AddChange ( void *pChangeSource, void* pChangedObject, CWaterChange* pChange )
{
if ( !pChangeSource )
{
delete pChange;
return;
}
std::map < void*, std::map < void*, CWaterChange* > >::iterator sourceIt = m_Changes.find ( pChangeSource );
if ( sourceIt == m_Changes.end () )
sourceIt = m_Changes.insert ( make_pair ( pChangeSource, std::map < void*, CWaterChange* > () ) ).first;
std::map < void*, CWaterChange* >::iterator changeIt = sourceIt->second.find ( pChangedObject );
if ( changeIt == sourceIt->second.end () )
{
sourceIt->second.insert ( make_pair ( pChangedObject, pChange ) );
}
else
{
delete pChange;
}
}
void CWaterManagerSA::UndoChanges ( void* pChangeSource )
{
if ( pChangeSource == NULL )
{
while ( !m_Changes.empty () )
{
if ( m_Changes.begin ()->first )
UndoChanges ( m_Changes.begin ()->first );
else
m_Changes.erase ( m_Changes.begin () );
}
}
else
{
std::map < void*, std::map < void*, CWaterChange* > >::iterator sourceIt = m_Changes.find ( pChangeSource );
if ( sourceIt == m_Changes.end () )
return;
std::map < void*, CWaterChange* >::iterator changeIt = sourceIt->second.begin ();
for ( ; changeIt != sourceIt->second.end (); changeIt++ )
{
changeIt->second->Undo ( changeIt->first );
delete changeIt->second;
}
m_Changes.erase ( sourceIt );
}
}
void CWaterManagerSA::RebuildIndex ()
{
// Rebuilds the list of polygons of each zone
MemSetFast ( (void *)ARRAY_WaterZones, 0, NUM_WaterZones * sizeof ( CWaterPolyEntrySAInterface ) );
MemPutFast < DWORD > ( VAR_NumWaterZonePolys, 0 );
( (BuildWaterIndex_t) FUNC_BuildWaterIndex ) ();
}
void CWaterManagerSA::ResetWorldWaterLevel ()
{
if ( m_bInitializedVertices )
for ( DWORD i = 0; i < NUM_DefWaterVertices; i++ )
m_Vertices [ i ].Reset ();
}
void CWaterManagerSA::Reset ()
{
// Resets all water to the original single player configuration
UndoChanges ();
MemSetFast ( m_QuadPool, 0, sizeof ( m_QuadPool ) );
MemSetFast ( m_TrianglePool, 0, sizeof ( m_TrianglePool ) );
( (ReadWaterConfiguration_t) FUNC_ReadWaterConfiguration )();
SetWaveLevel ( DEFAULT_WAVE_LEVEL );
for ( DWORD i = 0; i < NUM_NewWaterVertices; i++ )
m_Vertices [ i ].Init ( i < NUM_DefWaterVertices );
ms_iNumNonDefaultAndNonZeroVertices = 0;
m_bInitializedVertices = true;
}
// Dynamically hook/unhook water rendering when required
void CWaterManagerSA::UpdateRenderOrderRequirement ( void )
{
bool bAltRenderOrderRequired = ms_iNumNonDefaultAndNonZeroVertices != 0 || m_iActivePolyCount > 0 || m_bWaterDrawnLast;
if ( m_bAltRenderOrder != bAltRenderOrderRequired )
{
OutputDebugLine ( SString ( "[Water] SetAltWaterOrderEnabled: %d (ms_iNumNonDefaultAndNonZeroVertices:%d m_bWaterDrawnLast:%d m_Changes:%d m_iActivePolyCount:%d"
, bAltRenderOrderRequired
, ms_iNumNonDefaultAndNonZeroVertices
, m_bWaterDrawnLast
, m_Changes.size ()
, m_iActivePolyCount
));
m_bAltRenderOrder = bAltRenderOrderRequired;
//?SetAltWaterOrderEnabled
}
}
void CWaterManagerSA::SetWaterDrawnLast ( bool bEnable )
{
m_bWaterDrawnLast = bEnable;
UpdateRenderOrderRequirement ();
}
bool CWaterManagerSA::IsWaterDrawnLast ( void )
{
return m_bWaterDrawnLast;
}
| [
"grasmanek94@gmail.com"
] | grasmanek94@gmail.com |
d8d2ff72c2f71e41e77636909607e9f81e999bc8 | a0b64e46333663e7ce84af2f5a05482a96d64792 | /main.cpp | 90cfa2a9579465bba745915d0f679ff1085b8831 | [] | no_license | f26401004/The-Art-Of-War | 7fc7c05874603be6361c3dde715c5fb4015af2d1 | e6a6ed909c21479f142f686a828b725cd5e5f802 | refs/heads/master | 2020-05-01T07:51:47.411685 | 2019-03-24T02:29:36 | 2019-03-24T02:29:36 | 177,362,010 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 232 | cpp | #include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// create the window.
MainWindow win;
// show the window.
win.show();
return app.exec();
}
| [
"f26401004@gmail.com"
] | f26401004@gmail.com |
44600c91d06e88158e90f042cf6ceae853710c8d | 5795150f1d7fd799a94245b28e852ff472fcd4db | /cubegui-4.4-TP3/src/GUI-qt/plugins/AdvancedColorMaps/maps/CubehelixColorMap.h | f02d17d9d4773ff5e996e210c1112491e8fe3961 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | simbadSid/julich_testAssignment_cubePlugin | 59a5d328b8dedc2d6f2c2aa59246df5b93c43d29 | 0b126b80295ade4f4f22f7c55c67efe8e5386ff2 | refs/heads/master | 2020-06-21T14:37:36.769644 | 2016-12-08T19:11:02 | 2016-12-08T19:11:02 | 74,790,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,445 | h | /****************************************************************************
** CUBE http://www.scalasca.org/ **
*****************************************************************************
** Copyright (c) 1998-2016 **
** Forschungszentrum Juelich GmbH, Juelich Supercomputing Centre **
** **
** This software may be modified and distributed under the terms of **
** a BSD-style license. See the COPYING file in the package base **
** directory for details. **
****************************************************************************/
#ifndef SRC_GUI_QT_PLUGINS_ADVANCEDCOLORMAPS_MAPS_CUBEHELIXCOLORMAP_H_
#define SRC_GUI_QT_PLUGINS_ADVANCEDCOLORMAPS_MAPS_CUBEHELIXCOLORMAP_H_
#include <QVBoxLayout>
#include <QFormLayout>
#include <QLineEdit>
#include <QDoubleValidator>
#include <QLabel>
#include "ColorMapExtended.h"
/**
* @class CubehelixColorMap
* @author Marcin Copik (m.copik@fz-juelich.de)
* @date March 2015
* @brief Implementation of color map 'Cubehelix' - fancy algorithm based
* on rotations of RGB curves in space
* Source:
* Green, D. A., 2011, `A colour scheme for the display of astronomical intensity images',
* Bulletin of the Astronomical Society of India, 39, 289.
*
* https://www.mrao.cam.ac.uk/~dag/CUBEHELIX/
*/
class CubehelixColorMap : public ColorMapExtended
{
Q_OBJECT
public:
CubehelixColorMap();
~CubehelixColorMap();
const QString&
getColorMapDescription() const;
ColorMapWidget*
getConfigurationPanel();
QColor
getColor( double value,
double minValue,
double maxValue,
bool whiteForZero ) const;
QString
getMapName() const;
void
saveGlobalSettings( QSettings& settings );
void
loadGlobalSettings( QSettings& settings );
/**
* Cubehelix parameters.
*/
enum Parameters
{
START_COLOR = 0, // !< Starting color for map
NUMBER_OF_ROTATIONS, // !< Number of R/G/B rotations from start to the end
HUE_PARAMETER, // !< Hue parameter for the colors
GAMMA_FACTOR // !< Gamma parameter used for emphasizing (low intensity, gamma < 1)
};
/**
* @param param
* @return current value of map parameter 'param'
*/
double
getMapParameter( Parameters param ) const;
/**
* Set new value 'val' of map parameter 'param'
* @param param
* @param val
*/
void
setMapParameter( Parameters param,
double val );
private:
/**
* Starting color for map.
*/
double parameterValues[ 4 ];
/**
* Default values for map parameters.
*/
static const double DEFAULT_VALUES[ 4 ];
/**
* Matrix 3x2 used in computation of colormap values.
*/
static const double MAP_MATRIX[ 3 ][ 2 ];
static const QString COLOR_MAP_DESCRIPTION;
};
/**
* @class CubehelixPlot
* @author Marcin Copik (m.copik@fz-juelich.de)
* @date March 2015
* @brief GUI widget for CubehelixColorMapWidget - display curves
*/
class CubehelixPlot : public QWidget
{
Q_OBJECT
public:
CubehelixPlot( int w,
int h,
ColorMapPlot* plot,
CubehelixColorMap& parent );
/**
* Force redraw of plot.
*/
void
repaint();
protected:
/**
* Map object.
*/
CubehelixColorMap& parentObject;
/**
* Overloaded paint event - draw plot.
* @param event
*/
void
paintEvent( QPaintEvent* event );
/**
* Truncate value outside min and max.
* @param val
* @param min
* @param max
* @return value fitted into [min, max]
*/
double
minmax( double val,
double min_,
double max_ );
protected slots:
void markerChanged( ColorMapPlot::MarkersPositions::Position, double );
};
/**
* @class CubehelixColorMapWidget
* @author Marcin Copik (m.copik@fz-juelich.de)
* @date March 2015
* @brief GUI widget for CubehelixColorMap - configure coloring and display plot of
*/
class CubehelixColorMapWidget : public ColorMapWidget
{
Q_OBJECT
public:
/**
* @param map which will be 'served' by this widget
*/
CubehelixColorMapWidget( CubehelixColorMap& map );
~CubehelixColorMapWidget();
/**
* Overridden from parent.
*/
CubehelixColorMap&
getParent() const;
void
parentUpdated();
void
revertChanges();
void
applyChanges();
protected:
/**
* Cached parameteres of Cubehelix.
*/
double cachedParameterValues[ 4 ];
/**
* Main layout for widget.
*/
QVBoxLayout layout;
/**
* Map configuration.
*/
QWidget configurationPanel;
/**
* Layout for map configuration.
*/
QFormLayout configurationPanelLayout;
/**
* Parameters edits.
*/
QLineEdit parametersEdit[ 4 ];
/**
* Description of parameters.
*/
QLabel parametersEditLabels[ 4 ];
/**
* Validator for parameters edits.
*/
QDoubleValidator* parametersValidators[ 4 ];
/**
* Curves plot.
*/
CubehelixPlot plot;
/**
* Plot name.
*/
QLabel plotLabel;
protected slots:
/**
* Slot - one of edit labels has been changed.
*/
void
parameterChanged( const QString& );
private:
/**
* Names of all parameters.
*/
static const QString PARAMETERS_EDIT_LABEL[ 4 ];
/**
* "Hints" with parameter description.
*/
static const QString PARAMETERS_HINT[ 4 ];
/**
* Start colour - between 0.0 and 3.0
* Number of rotations - each double value
* Hue, gammma - non-negative value (although value 0 may doesn't make any sense),
* but still it will generate some colormap.
*/
static const double PARAMETERS_VALIDATORS_DATA[ 4 ][ 2 ];
/**
* Height of plot - fixed.
*/
static const int PLOT_DEFAULT_HEIGHT;
/**
* Width of plot - fixed.
*/
static const int PLOT_DEFAULT_WIDTH;
};
#endif /* SRC_GUI_QT_PLUGINS_ADVANCEDCOLORMAPS_MAPS_CUBEHELIXCOLORMAP_H_ */
| [
"kassuskley@localhost.localdomain"
] | kassuskley@localhost.localdomain |
fcbc1aa0a98618e6d3b84bf4605eabc08774611b | ecb19b88596264b96a7aafd85825291ce49d968b | /src/protos/cnn_params.pb.h | 6ed883744c704f4dfe03bd927a0ba226645a8ca1 | [] | no_license | wakanapo/cnn_library | f74f464681bd462f2db4677e98abf45de1916303 | 2cc080e29d1ff51f11f8e793ed9b8dca0d7ce35e | refs/heads/master | 2021-03-27T20:00:14.181146 | 2018-04-12T02:10:40 | 2018-04-12T02:10:40 | 114,589,081 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 17,305 | h | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: cnn_params.proto
#ifndef PROTOBUF_cnn_5fparams_2eproto__INCLUDED
#define PROTOBUF_cnn_5fparams_2eproto__INCLUDED
#include <string>
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 3004000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3004000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
namespace CnnProto {
class Bias;
class BiasDefaultTypeInternal;
extern BiasDefaultTypeInternal _Bias_default_instance_;
class Params;
class ParamsDefaultTypeInternal;
extern ParamsDefaultTypeInternal _Params_default_instance_;
class Weight;
class WeightDefaultTypeInternal;
extern WeightDefaultTypeInternal _Weight_default_instance_;
} // namespace CnnProto
namespace CnnProto {
namespace protobuf_cnn_5fparams_2eproto {
// Internal implementation detail -- do not call these.
struct TableStruct {
static const ::google::protobuf::internal::ParseTableField entries[];
static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
static const ::google::protobuf::internal::ParseTable schema[];
static const ::google::protobuf::uint32 offsets[];
static const ::google::protobuf::internal::FieldMetadata field_metadata[];
static const ::google::protobuf::internal::SerializationTable serialization_table[];
static void InitDefaultsImpl();
};
void AddDescriptors();
void InitDefaults();
} // namespace protobuf_cnn_5fparams_2eproto
// ===================================================================
class Weight : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:CnnProto.Weight) */ {
public:
Weight();
virtual ~Weight();
Weight(const Weight& from);
inline Weight& operator=(const Weight& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
Weight(Weight&& from) noexcept
: Weight() {
*this = ::std::move(from);
}
inline Weight& operator=(Weight&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
static const ::google::protobuf::Descriptor* descriptor();
static const Weight& default_instance();
static inline const Weight* internal_default_instance() {
return reinterpret_cast<const Weight*>(
&_Weight_default_instance_);
}
static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
0;
void Swap(Weight* other);
friend void swap(Weight& a, Weight& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
inline Weight* New() const PROTOBUF_FINAL { return New(NULL); }
Weight* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void CopyFrom(const Weight& from);
void MergeFrom(const Weight& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
size_t ByteSizeLong() const PROTOBUF_FINAL;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(Weight* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// repeated float w = 1 [packed = true];
int w_size() const;
void clear_w();
static const int kWFieldNumber = 1;
float w(int index) const;
void set_w(int index, float value);
void add_w(float value);
const ::google::protobuf::RepeatedField< float >&
w() const;
::google::protobuf::RepeatedField< float >*
mutable_w();
// @@protoc_insertion_point(class_scope:CnnProto.Weight)
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::RepeatedField< float > w_;
mutable int _w_cached_byte_size_;
mutable int _cached_size_;
friend struct protobuf_cnn_5fparams_2eproto::TableStruct;
};
// -------------------------------------------------------------------
class Bias : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:CnnProto.Bias) */ {
public:
Bias();
virtual ~Bias();
Bias(const Bias& from);
inline Bias& operator=(const Bias& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
Bias(Bias&& from) noexcept
: Bias() {
*this = ::std::move(from);
}
inline Bias& operator=(Bias&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
static const ::google::protobuf::Descriptor* descriptor();
static const Bias& default_instance();
static inline const Bias* internal_default_instance() {
return reinterpret_cast<const Bias*>(
&_Bias_default_instance_);
}
static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
1;
void Swap(Bias* other);
friend void swap(Bias& a, Bias& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
inline Bias* New() const PROTOBUF_FINAL { return New(NULL); }
Bias* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void CopyFrom(const Bias& from);
void MergeFrom(const Bias& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
size_t ByteSizeLong() const PROTOBUF_FINAL;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(Bias* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// repeated float b = 1 [packed = true];
int b_size() const;
void clear_b();
static const int kBFieldNumber = 1;
float b(int index) const;
void set_b(int index, float value);
void add_b(float value);
const ::google::protobuf::RepeatedField< float >&
b() const;
::google::protobuf::RepeatedField< float >*
mutable_b();
// @@protoc_insertion_point(class_scope:CnnProto.Bias)
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::RepeatedField< float > b_;
mutable int _b_cached_byte_size_;
mutable int _cached_size_;
friend struct protobuf_cnn_5fparams_2eproto::TableStruct;
};
// -------------------------------------------------------------------
class Params : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:CnnProto.Params) */ {
public:
Params();
virtual ~Params();
Params(const Params& from);
inline Params& operator=(const Params& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
Params(Params&& from) noexcept
: Params() {
*this = ::std::move(from);
}
inline Params& operator=(Params&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
static const ::google::protobuf::Descriptor* descriptor();
static const Params& default_instance();
static inline const Params* internal_default_instance() {
return reinterpret_cast<const Params*>(
&_Params_default_instance_);
}
static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
2;
void Swap(Params* other);
friend void swap(Params& a, Params& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
inline Params* New() const PROTOBUF_FINAL { return New(NULL); }
Params* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void CopyFrom(const Params& from);
void MergeFrom(const Params& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
size_t ByteSizeLong() const PROTOBUF_FINAL;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(Params* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// repeated .CnnProto.Weight weights = 1;
int weights_size() const;
void clear_weights();
static const int kWeightsFieldNumber = 1;
const ::CnnProto::Weight& weights(int index) const;
::CnnProto::Weight* mutable_weights(int index);
::CnnProto::Weight* add_weights();
::google::protobuf::RepeatedPtrField< ::CnnProto::Weight >*
mutable_weights();
const ::google::protobuf::RepeatedPtrField< ::CnnProto::Weight >&
weights() const;
// repeated .CnnProto.Bias biases = 2;
int biases_size() const;
void clear_biases();
static const int kBiasesFieldNumber = 2;
const ::CnnProto::Bias& biases(int index) const;
::CnnProto::Bias* mutable_biases(int index);
::CnnProto::Bias* add_biases();
::google::protobuf::RepeatedPtrField< ::CnnProto::Bias >*
mutable_biases();
const ::google::protobuf::RepeatedPtrField< ::CnnProto::Bias >&
biases() const;
// @@protoc_insertion_point(class_scope:CnnProto.Params)
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::RepeatedPtrField< ::CnnProto::Weight > weights_;
::google::protobuf::RepeatedPtrField< ::CnnProto::Bias > biases_;
mutable int _cached_size_;
friend struct protobuf_cnn_5fparams_2eproto::TableStruct;
};
// ===================================================================
// ===================================================================
#if !PROTOBUF_INLINE_NOT_IN_HEADERS
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// Weight
// repeated float w = 1 [packed = true];
inline int Weight::w_size() const {
return w_.size();
}
inline void Weight::clear_w() {
w_.Clear();
}
inline float Weight::w(int index) const {
// @@protoc_insertion_point(field_get:CnnProto.Weight.w)
return w_.Get(index);
}
inline void Weight::set_w(int index, float value) {
w_.Set(index, value);
// @@protoc_insertion_point(field_set:CnnProto.Weight.w)
}
inline void Weight::add_w(float value) {
w_.Add(value);
// @@protoc_insertion_point(field_add:CnnProto.Weight.w)
}
inline const ::google::protobuf::RepeatedField< float >&
Weight::w() const {
// @@protoc_insertion_point(field_list:CnnProto.Weight.w)
return w_;
}
inline ::google::protobuf::RepeatedField< float >*
Weight::mutable_w() {
// @@protoc_insertion_point(field_mutable_list:CnnProto.Weight.w)
return &w_;
}
// -------------------------------------------------------------------
// Bias
// repeated float b = 1 [packed = true];
inline int Bias::b_size() const {
return b_.size();
}
inline void Bias::clear_b() {
b_.Clear();
}
inline float Bias::b(int index) const {
// @@protoc_insertion_point(field_get:CnnProto.Bias.b)
return b_.Get(index);
}
inline void Bias::set_b(int index, float value) {
b_.Set(index, value);
// @@protoc_insertion_point(field_set:CnnProto.Bias.b)
}
inline void Bias::add_b(float value) {
b_.Add(value);
// @@protoc_insertion_point(field_add:CnnProto.Bias.b)
}
inline const ::google::protobuf::RepeatedField< float >&
Bias::b() const {
// @@protoc_insertion_point(field_list:CnnProto.Bias.b)
return b_;
}
inline ::google::protobuf::RepeatedField< float >*
Bias::mutable_b() {
// @@protoc_insertion_point(field_mutable_list:CnnProto.Bias.b)
return &b_;
}
// -------------------------------------------------------------------
// Params
// repeated .CnnProto.Weight weights = 1;
inline int Params::weights_size() const {
return weights_.size();
}
inline void Params::clear_weights() {
weights_.Clear();
}
inline const ::CnnProto::Weight& Params::weights(int index) const {
// @@protoc_insertion_point(field_get:CnnProto.Params.weights)
return weights_.Get(index);
}
inline ::CnnProto::Weight* Params::mutable_weights(int index) {
// @@protoc_insertion_point(field_mutable:CnnProto.Params.weights)
return weights_.Mutable(index);
}
inline ::CnnProto::Weight* Params::add_weights() {
// @@protoc_insertion_point(field_add:CnnProto.Params.weights)
return weights_.Add();
}
inline ::google::protobuf::RepeatedPtrField< ::CnnProto::Weight >*
Params::mutable_weights() {
// @@protoc_insertion_point(field_mutable_list:CnnProto.Params.weights)
return &weights_;
}
inline const ::google::protobuf::RepeatedPtrField< ::CnnProto::Weight >&
Params::weights() const {
// @@protoc_insertion_point(field_list:CnnProto.Params.weights)
return weights_;
}
// repeated .CnnProto.Bias biases = 2;
inline int Params::biases_size() const {
return biases_.size();
}
inline void Params::clear_biases() {
biases_.Clear();
}
inline const ::CnnProto::Bias& Params::biases(int index) const {
// @@protoc_insertion_point(field_get:CnnProto.Params.biases)
return biases_.Get(index);
}
inline ::CnnProto::Bias* Params::mutable_biases(int index) {
// @@protoc_insertion_point(field_mutable:CnnProto.Params.biases)
return biases_.Mutable(index);
}
inline ::CnnProto::Bias* Params::add_biases() {
// @@protoc_insertion_point(field_add:CnnProto.Params.biases)
return biases_.Add();
}
inline ::google::protobuf::RepeatedPtrField< ::CnnProto::Bias >*
Params::mutable_biases() {
// @@protoc_insertion_point(field_mutable_list:CnnProto.Params.biases)
return &biases_;
}
inline const ::google::protobuf::RepeatedPtrField< ::CnnProto::Bias >&
Params::biases() const {
// @@protoc_insertion_point(field_list:CnnProto.Params.biases)
return biases_;
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// @@protoc_insertion_point(namespace_scope)
} // namespace CnnProto
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_cnn_5fparams_2eproto__INCLUDED
| [
"noreply@github.com"
] | wakanapo.noreply@github.com |
f8efa3c003c0587b9a31cf2599d68802b01b9dc4 | 9ca0b052645100eaf2be8fd7f1a2a49c65c639e7 | /2D Array/New Year Chaos.cpp | 91b146c9fd0b1b83bf6530c74812a7954dcf9af8 | [] | no_license | PSDent/PS_HackerRank | a07e6c30d9c4c7f6649c058f7ad49a8bd4b635b7 | 26ad696cb4934340a33a5ae6348e0abe57be3eba | refs/heads/master | 2020-04-29T11:15:33.745663 | 2019-04-08T23:10:07 | 2019-04-08T23:10:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,206 | cpp | #include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
int cnt[100001];
// Complete the minimumBribes function below.
void minimumBribes(vector<int> q) {
memset(cnt, 0, sizeof(cnt));
int bribedCnt = 0;
for(int i = 0; i < q.size();)
{
bool a = false;
if(cnt[q[i]] > 2 || (i > 0 && cnt[q[i - 1]] > 2) || ( (i + 1) < q.size() && cnt[q[i + 1]] > 2))
break;
if (cnt[q[i]] < 2 && i > 0 && cnt[q[i - 1]] < 2 && q[i] < q[i - 1]) {
++cnt[q[i]];
int temp = q[i - 1];
q[i - 1] = q[i];
q[i] = temp;
++bribedCnt;
--i;
}
else if(cnt[q[i]] < 2 && (i + 1) < q.size() && cnt[q[i + 1]] < 2 && q[i] > q[i + 1])
{
++cnt[q[i]];
int temp = q[i + 1];
q[i + 1] = q[i];
q[i] = temp;
++bribedCnt;
if(i > 0)
--i;
}
else ++i;
}
bool clear = true;
for(int i = 0; i < q.size(); ++i)
if(q[i] != (i + 1)) { clear = false; break; }
if(clear)
std::cout << bribedCnt << '\n';
else
std::cout << "Too chaotic" << '\n';
}
| [
"mnsan1004@gmail.com"
] | mnsan1004@gmail.com |
1559478ba1e7df4fbea8f650b5e649aacd361d10 | 54f352a242a8ad6ff5516703e91da61e08d9a9e6 | /Source Codes/AtCoder/abc018/B/4291886.cpp | 079529cf08c5a3a80fe3c7c8604918d74f4b78f6 | [] | no_license | Kawser-nerd/CLCDSA | 5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb | aee32551795763b54acb26856ab239370cac4e75 | refs/heads/master | 2022-02-09T11:08:56.588303 | 2022-01-26T18:53:40 | 2022-01-26T18:53:40 | 211,783,197 | 23 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 652 | cpp | #include <algorithm>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <iterator>
#include <map>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <vector>
using namespace std;
using ull = unsigned long long;
using P = pair<int, int>;
ull E = 1000000007;
const double pi = 3.14159265359;
int main() {
string S;
cin >> S;
int N;
cin >> N;
for (int i = 0; i < N; ++i) {
int l, r;
cin >> l >> r;
--l; --r;
for (int p = 0; p <= (r - l) / 2; ++p) {
swap(S[l + p], S[r - p]);
}
}
cout << S << endl;
} | [
"kwnafi@yahoo.com"
] | kwnafi@yahoo.com |
0738d98385a9f502eaef4eeb1fe401ec00072871 | 33ce14af28db7b11914a388e0d5bda7ceeb6e518 | /logdevice/common/protocol/STORE_Message.h | 2f8d54d20bebecb8c799540085bd6ed87bb2937b | [
"BSD-3-Clause"
] | permissive | WolfgangBai/LogDevice | e1c025617c3efe06e67738f3c8143db290990b93 | c51c4fadbbf03bf6291628f240a009bf66943200 | refs/heads/master | 2020-03-28T23:05:49.187012 | 2018-09-18T09:57:48 | 2018-09-18T10:13:20 | 149,276,107 | 1 | 0 | null | 2018-09-18T11:18:40 | 2018-09-18T11:18:40 | null | UTF-8 | C++ | false | false | 17,948 | h | /**
* Copyright (c) 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <array>
#include <cstdlib>
#include <memory>
#include <string>
#include <tuple>
#include <vector>
#include <folly/Optional.h>
#include <folly/small_vector.h>
#include "logdevice/common/ClientID.h"
#include "logdevice/common/settings/Durability.h"
#include "logdevice/common/NodeID.h"
#include "logdevice/common/PayloadHolder.h"
#include "logdevice/common/RecordID.h"
#include "logdevice/common/Seal.h"
#include "logdevice/common/ShardID.h"
#include "logdevice/common/configuration/TrafficClass.h"
#include "logdevice/common/protocol/Message.h"
#include "logdevice/common/types_internal.h"
#include "logdevice/include/Record.h"
namespace facebook { namespace logdevice {
// a StoreChainLink describes one link in a message delivery chain
struct StoreChainLink {
// Shard to which a STORE is to be delivered.
ShardID destination;
// id of the "client" connection on the destination node whose remote end
// (from the point of view of that node) is the sender of this message.
// The destination server uses this ClientID to send a reply to the message
// directly to the sender.
ClientID origin;
bool operator==(const StoreChainLink& other) const {
return destination == other.destination && origin == other.origin;
}
std::string toString() const;
};
struct STORE_Header {
RecordID rid; // unique ID of record being stored, includes log id and LSN
uint64_t timestamp; // Record timestamp in milliseconds since 1970.
// highest esn in this record's epoch such that at the time this message
// was originally sent by a sequencer all records with this and lower ESNs
// in this epoch were known to the sequencer to be fully stored on R nodes
esn_t last_known_good;
// Appender sends STORE messages in waves, generating a new copyset
// for each wave. All STORE messages in the same wave share the same
// copyset. This is the id of wave to which this STORE belongs
uint32_t wave;
STORE_flags_t flags; // a bitset of flag constants defined below
copyset_size_t nsync; // if chain-sending, number of copies that must be
// synced to disk before acknowledging
copyset_off_t copyset_offset; // Offset of the recipient of this message in
// the copyset. Incremented when forwarding.
copyset_size_t copyset_size; // total number of node ids in the copyset
// to follow this header
uint32_t timeout_ms; // store timeout in milliseconds
// the store node should skip handling this
// message if it hasn't started to store it
// timeout_ms milliseconds after received it.
// 0 means no timeout
NodeID sequencer_node_id;
// followed by an array of .copyset_size StoreChainLink structs. If CHAIN
// flag is not set in .flags, StoreChainLink::origin fields of those structs
// are ignored
// if set in .flags, the node that will receive this message is
// instructed to forward it to the next node in the replication
// list. Otherwise destination will do no forwarding.
static const STORE_flags_t CHAIN = 1 << 0; //=1
// If set in .flags, the storage node should sync the write before
// replying.
static const STORE_flags_t SYNC = 1 << 1; //=2
// If set in .flags, the payload is prefixed with a checksum. The length of
// the checksum depends on the CHECKSUM_64BIT flag; if it is set, the
// checksum is 64 bits, otherwise 32 bits.
static const STORE_flags_t CHECKSUM = 1 << 2; //=4
static const STORE_flags_t CHECKSUM_64BIT = 1 << 3; //=8
// XNOR of the other two checksum bits. Ensures that single-bit corruptions
// in the checksum bits (or flags getting zeroed out) get detected.
static const STORE_flags_t CHECKSUM_PARITY = 1 << 4; //=16
// This message is a part of log recovery procedure and is to
// perform a mutation of a previously sealed epoch. When this flag
// is set, the header is immediately followed by a 4-byte epoch
// number of the epoch through which the recovery procedure has
// sealed the log. When the recipient does its preemption check on
// the STORE, it must use that epoch number instead of rid.epoch.
// TODO 11866467: currently serve the same purpose as WRITTEN_BY_RECOVERY.
// This is going to be deprecated, stop using this flag.
static const STORE_flags_t RECOVERY = 1 << 5; //=32
// The record being stored is a plug for a hole in the numbering sequence.
// There is no payload. RECOVERY must also be set.
static const STORE_flags_t HOLE = 1 << 6; //=64
// Record contains a blob composed by BufferedWriter
static const STORE_flags_t BUFFERED_WRITER_BLOB = 1 << 7; //=128
// The record is being re-replicated to this node as part of rebuilding.
static const STORE_flags_t REBUILDING = 1 << 8; //=256
// Amend metadata (e.g., copyset, flags) of existing record.
// The message doesn't contain payload.
static const STORE_flags_t AMEND = 1 << 9; //=512
// The store is issued by a sequencer draining its appenders during
// graceful reactivation/migration, and should not be preempted by
// soft seals
static const STORE_flags_t DRAINING = 1 << 10; //=1024
// Copyset directory entry should be written for this record.
// Record contains the starting LSN of the block or LSN_INVALID if this
// record is out-of-block.
static const STORE_flags_t STICKY_COPYSET = 1 << 11; //=2048
// The message has information about how many bytes have been written to the
// epoch so far.
static const STORE_flags_t OFFSET_WITHIN_EPOCH = 1 << 12; //=4096
// the record is written or overwritten by epoch recovery and the wave is
// repurposed to be the `sequencer epoch' of the log recovery
// TODO 11866467: currently serve the same purpose as RECOVERY. Will
// eventually replace the RECOVERY flag.
static const STORE_flags_t WRITTEN_BY_RECOVERY = 1 << 13; //=8192
// The message contains a custom key provided by the client for this record.
static const STORE_flags_t CUSTOM_KEY = 1 << 14; //=16384
// The record being stored is a special hole indicating the end of an epoch.
// There is no payload. WRITTEN_BY_RECOVERY and HOLE must also be set.
static const STORE_flags_t BRIDGE = 1 << 15; //=32768
// The record being stored is the first record in the epoch. It is safe to
// assume that no record is stored before the ESN of this record in the
// epoch of the record.
static const STORE_flags_t EPOCH_BEGIN = 1 << 16; //=65536
// used to know weather we should expect e2e tracing information or not
static const STORE_flags_t E2E_TRACING_ON = 1u << 17; //=131072
// NOTE: Reserved to match the same bit in RECORD_Header. Should never
// be set on a STORE. Used for asserts.
static const STORE_flags_t DRAINED = 1u << 19; //=524288
// Please update STORE_Message::flagsToString() when adding flags.
} __attribute__((__packed__));
/**
* Optional extra information that may be passed along with STORE_Message
* such as rebuilding, recovery or byte offset.
*/
struct STORE_Extra {
// Number which uniquely identifies the recovery machine responsible for
// sending this message. Used only if STORE_Header::RECOVERY flag is set.
recovery_id_t recovery_id = recovery_id_t(0);
// An epoch number through which the recovery procedure has sealed the log.
// Used only if STORE_Header::RECOVERY flag is set, in which case it is
// guaranteed to be a valid epoch number.
epoch_t recovery_epoch = EPOCH_INVALID;
// If this STORE message is for rebuilding (REBUILDING flag is set), the
// rebuilding version is sent along. This version will be passed back in the
// STORED reply so that the RecordRebuilding state machine can detect that it
// is a stale response in case the rebuilding version changed.
lsn_t rebuilding_version = LSN_INVALID;
uint32_t rebuilding_wave = 0;
// With protocol version REBUILDING_WITHOUT_WAL_2, if this
// STORE message is for rebuilding, the rebuilding_id which uniquely
// identifies a run of the LogRebuilding state machine where this store
// originated from, is sent along. This version will be passed back in the
// STORED reply.
log_rebuilding_id_t rebuilding_id = LOG_REBUILDING_ID_INVALID;
// If this STORE message include byte offset (BYTE_OFFSET flag is set), the
// amount of bytes were written in epoch (to which this message belongs)
// before record of this message is going to be sent along.
// Not all STORE message will have this info. This info is sent along with
// store header every X bytes being appended.
uint64_t offset_within_epoch = BYTE_OFFSET_INVALID;
// Serialized when wave > 1.
// If flags.CHAIN is set and copyset_offset >= first_amendable_offset, the
// AMEND flag is expected to be set. The STORE is sent without the payload
// because all remaining nodes in the copyset already have the record.
// Storage nodes should maintain this implication when forwarding (note that
// `copyset_offset' increments so the condition can become true later in the
// chain).
copyset_size_t first_amendable_offset = COPYSET_SIZE_MAX;
bool operator==(const STORE_Extra& other) const {
auto as_tuple = [](const STORE_Extra& r) {
return std::tie(r.recovery_id,
r.recovery_epoch,
r.rebuilding_version,
r.rebuilding_wave,
r.rebuilding_id,
r.offset_within_epoch);
};
return as_tuple(*this) == as_tuple(other);
}
};
class STORE_Message : public Message {
public:
/**
* Appender and Mutator use this constructor when composing STORE messages to
* send to destinations.
*
* @param header header to copy into header_. The .flags field is
* ignored and is instead copied from the _flags_ parameter.
* @param copyset the copyset of the wave of STORE messages to which
* this message belongs. Its size is in the header.
* @param copyset_offset copied into header_.copyset_offset
* @param additional_flags OR-d into set header_.flags
* @param extra optional extra infrmation to be passed along with message
* @param optional_keys keys provided by client on appending a record
* @param payload payload of the STORE message
* @param appender_context if true, double-check that the Appender still
* exists before serializing over the wire
*/
STORE_Message(const STORE_Header& header,
const StoreChainLink copyset[],
copyset_off_t copyset_offset,
STORE_flags_t additional_flags,
STORE_Extra extra,
std::map<KeyType, std::string> optional_keys,
std::shared_ptr<PayloadHolder> payload,
bool appender_context = false,
std::string e2e_tracing_context = "");
// Movable but not copyable
STORE_Message(STORE_Message&&) = default;
STORE_Message& operator=(STORE_Message&&) = default;
STORE_Message(const STORE_Message&) = delete;
STORE_Message& operator=(const STORE_Message&) = delete;
static TrafficClass calcTrafficClass(const STORE_Header& header) {
TrafficClass tc;
if (header.flags & STORE_Header::RECOVERY) {
tc = TrafficClass::RECOVERY;
} else if (header.flags & STORE_Header::REBUILDING) {
tc = TrafficClass::REBUILD;
} else {
tc = TrafficClass::APPEND;
}
return tc;
}
// see Message.h
bool cancelled() const override;
void serialize(ProtocolWriter& writer) const override;
void onSent(Status st, const Address& to) const override;
Disposition onReceived(const Address&) override {
// Receipt handler lives in StoreStateMachine::onReceived(); this should
// never get called.
std::abort();
}
static Message::deserializer_t deserialize;
// Overload of deserialize that does not need to run in an EventLoop
// context
static MessageReadResult deserialize(ProtocolReader&,
size_t max_payload_inline);
/**
* @return a human-readable representation of copyset_
*/
std::string printableCopyset();
// see docs in checkIfPreempted()
enum class PreemptResult {
NOT_PREEMPTED,
PREEMPTED_NORMAL,
PREEMPTED_SOFT_ONLY
};
/**
* A helper method used to check if the storage node shouldn't process a
* STORE message because the log was sealed up to a certain epoch.
*
* @param record_id record being stored
* @param recovery_epoch if STORE is part of the recovery process (RECOVERY
* flag is set in the header), the sequencer sending
* this STORE message performs recovery up to this
* epoch
* @param normal_seal Seal value from the SEAL messages sent by log
* recovery
* @param soft_seal Seal value obtained from STORE messages
* @param drain indicate if the STORE is for sequencer draining, if
* true, soft seals will be ignored
*
* @return a pair of <PreemptResult, Seal>, in which
* PreemptResult can be:
* NOT_PREEMTPED STORE is not preempted
* PREEMPTED_NORMAL STORE is preempted by a normal
* seal or both normal and soft
* seals
* PREEMPTED_SOFT_ONLY STORE is preempted only by
* soft seal
* if PreemptResult is PREEMPTED_NORMAL or
* PREEMPTED_SOFT_ONLY, Seal will set to
* the Seal that effectively preempts the
* STORE. otherwise Seal will be invalid.
*/
static std::pair<STORE_Message::PreemptResult, Seal>
checkIfPreempted(const RecordID& record_id,
epoch_t recovery_epoch,
Seal normal_seal,
Seal soft_seal,
bool drain = false);
const STORE_Header& getHeader() const {
return header_;
}
const STORE_Extra& getExtra() const {
return extra_;
}
const folly::small_vector<StoreChainLink, 6>& getCopyset() const {
return copyset_;
}
const PayloadHolder* getPayloadHolder() const {
return payload_.get();
}
/**
* A method to set the first LSN of the block that the record belongs to.
*
* @param lsn the block starting LSN
*/
void setBlockStartingLSN(lsn_t lsn);
/**
* Pretty-prints flags.
*/
static std::string flagsToString(STORE_flags_t flags);
virtual std::vector<std::pair<std::string, folly::dynamic>>
getDebugInfo() const override;
private:
/**
* deserialize() uses this constructor when it reads a STORE message from
* the input buffer of a bufferevent.
*/
STORE_Message(const STORE_Header& header,
std::shared_ptr<PayloadHolder>&& payload);
// Convenience wrapper for STORED_Message::createAndSend
void sendReply(Status status,
Seal seal = Seal(),
ShardID rebuildingRecipient = ShardID()) const;
/**
* Called when a storage node fails to forward this message along
* a delivery chain.
*
* @param st error code reported by Sender::sendMessage() or
* STORE_Message::onSent()
*/
void onForwardingFailure(Status st) const;
STORE_Header header_;
STORE_Extra extra_;
// If true, STORE_Message::cancelled() checks that the Appender still
// exists before allowing the message to be serialized onto the wire
bool appender_context_{false};
// Nullptr means empty payload. The payload is also not serialized when the
// AMEND flag is set, so on the receiving side it will always be empty for
// amends.
std::shared_ptr<PayloadHolder> payload_;
// identities of all nodes on which this record is stored
folly::small_vector<StoreChainLink, 6> copyset_;
// the starting LSN of the block to which the record belongs (issued by the
// sticky copyset selector), or LSN_INVALID if this is a single record.
// If the value is unassigned, copyset directory will not be written for this
// store
folly::Optional<lsn_t> block_starting_lsn_;
// The (optional) keys provided by the client in the append() operation.
// See @Record.h for details
std::map<KeyType, std::string> optional_keys_;
// This field is used only if the message was received from the
// wire. StoreStateMachine::onReceived() sets this to the offset in
// copyset_[] of the node that received the message (and may need to forward
// it down the chain). If we are in the sequencer context and the object was
// not received, but rather was created locally by an Appender, this field
// is set to -1.
copyset_off_t my_pos_in_copyset_;
// Where to send a reply once the write is done. Calculated by
// StoreStateMachine::onReceived() and used in sendReply().
ClientID reply_to_;
// if true, indicate that the STORE is preempted by only by a soft seal
bool soft_preempted_only_{false};
// tracing context containing information about the parent context of future
// spans references
std::string e2e_tracing_context_;
friend class StoreStateMachine;
friend class MutatorTest;
friend class AppenderTest;
friend class TestAppender;
friend class MessageSerializationTest;
friend class E2ETracingSerializationTest;
};
}} // namespace facebook::logdevice
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
dda0c198d453a1703c4be649c3c59ddf0c6071a6 | 2a1365c24292ee4ea235301a1ead0403062f4645 | /他人代码_港/lab13-Greedy/main.cpp | 9e30580919c556d4d0360789b0d55788d0f2deab | [] | no_license | trialley/DataStructuresLabs | 0a10f5bb8afe63585b111a820cf8d3b552018bd1 | 0d2cf9931175b96190a317d1ea14dd18793faf76 | refs/heads/master | 2020-09-27T10:16:31.437406 | 2019-12-31T07:32:11 | 2019-12-31T07:32:11 | 226,492,210 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 228 | cpp | #include<iostream>
#include"baseGraph.h"
using namespace std;
int main() {
uniGraph<arrGraph<int>,int> g(10);
g.SetNodeDate(0, 0);
g.SetLinkValue(0, 0, 0);
cout << g.GetNodeDate(0)<<" "<<g.GetLinkValue(0,0);
return 0;
} | [
"1203732857@qq.com"
] | 1203732857@qq.com |
bcf13906c0d3daf2643abd25cfe741a6a152256b | a41e29c8724677261433907c470adab81e35d9a3 | /opengl.cpp | 9229a5991bf7b2db19d3ba205e433f04abed229d | [] | no_license | bqqbarbhg/test-3d | bdf77b7c9d39443afedb76227904ee82780fd9f1 | c1ecd814c01aa2ad9d7ad3d16f333b41561507bb | refs/heads/master | 2021-01-10T14:21:00.496004 | 2016-03-19T17:02:53 | 2016-03-19T17:02:53 | 53,335,837 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,729 | cpp |
struct Shader_Define
{
const char *name;
int value;
};
void shader_source_defines(GLint shader, const char *source, int size, const Shader_Define *defines, size_t define_count)
{
char prefix[2048], *prefix_ptr = prefix;
for (size_t i = 0; i < define_count; i++) {
const Shader_Define *d = &defines[i];
prefix_ptr += sprintf(prefix_ptr, "#define %s %d\n", d->name, d->value);
}
const GLchar* sources[2] = { (const GLchar*)prefix, (const GLchar*)source };
GLint lengths[2] = { (GLint)(prefix_ptr - prefix), (GLint)size };
glShaderSource(shader, 2, sources, lengths);
}
bool debug_compile_shader(GLint shader)
{
glCompileShader(shader);
GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status != GL_TRUE) {
char info_log[2048];
glGetShaderInfoLog(shader, Count(info_log), 0, info_log);
fprintf(stderr, "%s\n", info_log);
return false;
}
return true;
}
bool debug_link_program(GLint program)
{
glLinkProgram(program);
GLint status;
glGetProgramiv(program, GL_LINK_STATUS, &status);
if (status != GL_TRUE) {
char info_log[2048];
glGetProgramInfoLog(program, Count(info_log), 0, info_log);
fprintf(stderr, "%s\n", info_log);
return false;
}
return true;
}
char* debug_read_file(const char *path)
{
FILE *file = fopen(path, "rb");
fseek(file, 0, SEEK_END);
size_t size = ftell(file);
fseek(file, 0, SEEK_SET);
char *buffer = (char*)malloc(size + 1);
fread(buffer, size, 1, file);
buffer[size] = '\0';
fclose(file);
return buffer;
}
#define GL_MAX_BONES 20
const char *GLSL_NUM_BONES = "NUM_BONES";
const char *GLSL_NUM_WEIGHTS = "NUM_WEIGHTS";
GLint skinned_frag_shader;
struct Skinned_Shader
{
GLuint vert_shader;
GLuint program;
GLint uViewProjection;
GLint uBones;
GLint uBonesIT;
GLint aVertex;
GLint aNormal;
GLint aTexCoord;
GLint aBoneIndex;
GLint aBoneWeight;
};
Skinned_Shader skinned_shaders[5];
bool generate_shaders()
{
char *skinned_vert_src = debug_read_file("data/shader/skinned_mesh.vert");
char *skinned_frag_src = debug_read_file("data/shader/skinned_mesh.frag");
skinned_frag_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(skinned_frag_shader, 1, &skinned_frag_src, 0);
if (!debug_compile_shader(skinned_frag_shader))
return false;
for (int weightI = 0; weightI < 5; weightI++) {
Shader_Define defines[] = {
{ GLSL_NUM_BONES, GL_MAX_BONES },
{ GLSL_NUM_WEIGHTS, weightI },
};
Skinned_Shader *s = &skinned_shaders[weightI];
GLuint vert_shader = glCreateShader(GL_VERTEX_SHADER);
s->vert_shader = vert_shader;
shader_source_defines(vert_shader, skinned_vert_src, -1, defines, Count(defines));
if (!debug_compile_shader(vert_shader))
return false;
GLint program = glCreateProgram();
s->program = program;
glAttachShader(program, vert_shader);
glAttachShader(program, skinned_frag_shader);
if (!debug_link_program(program))
return false;
s->uViewProjection = glGetUniformLocation(program, "uViewProjection");
s->uBones = glGetUniformLocation(program, "uBones");
s->uBonesIT = glGetUniformLocation(program, "uBonesIT");
s->aVertex = glGetAttribLocation(program, "aVertex");
s->aNormal = glGetAttribLocation(program, "aNormal");
s->aTexCoord = glGetAttribLocation(program, "aTexCoord");
s->aBoneIndex = glGetAttribLocation(program, "aBoneIndex");
s->aBoneWeight = glGetAttribLocation(program, "aBoneWeight");
}
free(skinned_vert_src);
free(skinned_frag_src);
return true;
}
const U32 skinned_vertex_size = 3 + 3 + 2 + 1 + 1;
struct GL_Skinned_Mesh
{
GLuint vertex_buffer, index_buffer;
void *vertices, *indices;
U32 vertex_count;
U32 index_count;
GLint index_type;
U32 bone_count;
U32 weight_count;
};
int gl_type_size(GLint type)
{
switch (type) {
case GL_BYTE:
case GL_UNSIGNED_BYTE:
return 1;
case GL_SHORT:
case GL_UNSIGNED_SHORT:
return 2;
case GL_INT:
case GL_UNSIGNED_INT:
return 4;
default:
assert(0 && "Unexpected type");
return 0;
}
}
void do_load_skinned_mesh_to_gl(GL_Skinned_Mesh *mesh)
{
assert(mesh->vertices != 0);
assert(mesh->indices != 0);
assert(mesh->vertex_buffer == 0);
assert(mesh->index_buffer == 0);
glGenBuffers(1, &mesh->vertex_buffer);
glGenBuffers(1, &mesh->index_buffer);
glBindBuffer(GL_ARRAY_BUFFER, mesh->vertex_buffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->index_buffer);
GLsizei vertex_size = sizeof(float) * skinned_vertex_size * mesh->vertex_count;
glBufferData(GL_ARRAY_BUFFER, vertex_size, mesh->vertices, GL_STATIC_DRAW);
GLsizei index_size = gl_type_size(mesh->index_type) * mesh->index_count;
glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_size, mesh->indices, GL_STATIC_DRAW);
}
void load_skinned_mesh_to_gl(GL_Skinned_Mesh *mesh)
{
do_load_skinned_mesh_to_gl(mesh);
free(mesh->vertices);
free(mesh->indices);
mesh->vertices = 0;
mesh->indices = 0;
}
void write_skinned_mesh(Out_Stream *s, GL_Skinned_Mesh *mesh)
{
stream_write(s, &mesh->vertex_count, sizeof(U32));
stream_write(s, &mesh->index_count, sizeof(U32));
stream_write(s, &mesh->index_type, sizeof(GLint));
stream_write(s, &mesh->bone_count, sizeof(U32));
stream_write(s, &mesh->weight_count, sizeof(U32));
stream_write(s, mesh->vertices, skinned_vertex_size * sizeof(float), mesh->vertex_count);
stream_write(s, mesh->indices, gl_type_size(mesh->index_type), mesh->index_count);
}
void read_skinned_mesh_to_gl(In_Stream *s, GL_Skinned_Mesh *mesh)
{
stream_read(s, &mesh->vertex_count, sizeof(U32));
stream_read(s, &mesh->index_count, sizeof(U32));
stream_read(s, &mesh->index_type, sizeof(GLint));
stream_read(s, &mesh->bone_count, sizeof(U32));
stream_read(s, &mesh->weight_count, sizeof(U32));
mesh->vertices = stream_skip(s, skinned_vertex_size * sizeof(float), mesh->vertex_count);
mesh->indices = stream_skip(s, gl_type_size(mesh->index_type), mesh->index_count);
do_load_skinned_mesh_to_gl(mesh);
mesh->vertices = 0;
mesh->indices = 0;
}
void draw_skinned_mesh(GL_Skinned_Mesh *mesh, const Mat44& viewProjection, const Mat44 *transforms)
{
Skinned_Shader *s = &skinned_shaders[mesh->weight_count];
glUseProgram(s->program);
if (s->uViewProjection >= 0)
glUniformMatrix4fv(s->uViewProjection, 1, GL_FALSE, (const GLfloat*)&viewProjection);
if (s->uBones >= 0)
glUniformMatrix4fv(s->uBones, mesh->bone_count, GL_FALSE, (const GLfloat*)transforms);
if (s->uBonesIT >= 0) {
Mat44 transIt[GL_MAX_BONES];
for (U32 i = 0; i < mesh->bone_count; i++)
transIt[i] = transpose(inverse(transforms[i]));
glUniformMatrix4fv(s->uBonesIT, mesh->bone_count, GL_FALSE, (const GLfloat*)transIt);
}
glBindBuffer(GL_ARRAY_BUFFER, mesh->vertex_buffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->index_buffer);
GLuint sz = skinned_vertex_size * sizeof(float);
if (s->aVertex >= 0) {
glEnableVertexAttribArray(s->aVertex);
glVertexAttribPointer(s->aVertex, 3, GL_FLOAT, GL_FALSE, sz, (const GLvoid*)(0 * sizeof(float)));
}
if (s->aNormal >= 0) {
glEnableVertexAttribArray(s->aNormal);
glVertexAttribPointer(s->aNormal, 3, GL_FLOAT, GL_FALSE, sz, (const GLvoid*)(3 * sizeof(float)));
}
if (s->aTexCoord >= 0) {
glEnableVertexAttribArray(s->aTexCoord);
glVertexAttribPointer(s->aTexCoord, 2, GL_FLOAT, GL_FALSE, sz, (const GLvoid*)(6 * sizeof(float)));
}
if (s->aBoneIndex >= 0) {
glEnableVertexAttribArray(s->aBoneIndex);
glVertexAttribPointer(s->aBoneIndex, 4, GL_UNSIGNED_BYTE, GL_FALSE, sz, (const GLvoid*)(8 * sizeof(float)));
}
if (s->aBoneWeight >= 0) {
glEnableVertexAttribArray(s->aBoneWeight);
glVertexAttribPointer(s->aBoneWeight, 4, GL_UNSIGNED_BYTE, GL_TRUE, sz, (const GLvoid*)(9 * sizeof(float)));
}
glDrawElements(GL_TRIANGLES, mesh->index_count, mesh->index_type, (const GLvoid*)0);
}
| [
"samuli.1995@hotmail.com"
] | samuli.1995@hotmail.com |
c9ed5f7d04685e6cea2854d27eef5e33172f9dd0 | cd421faf75252d0595e9e0c64a2d38e5a1d0f66f | /cpp/src/Stack.tpp | 7676e47da2f3d6e2659b1002360626fa6bc01c14 | [
"MIT"
] | permissive | MinecraftXwinP/HW-Calculator | 01bc93de1767e5f6c4944412242ac6563bc8081c | 04445b76cafb95461938b4b023fb85715ac29d25 | refs/heads/master | 2020-06-08T19:06:41.360136 | 2014-10-22T17:22:00 | 2014-10-22T17:22:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,597 | tpp | #include <iostream>
using namespace std;
template<class T>
Stack<T>::Stack()
{
init(_DEFAULT_INIT_SIZE_,_DEFAULT_INTERVAL_);
}
template<class T>
Stack<T>::Stack(int initSize,int interval)
{
init(initSize,interval);
}
template<class T>
Stack<T>::~Stack()
{
delete [] data;
}
template<class T>
void Stack<T>::init(int initSize,int interval)
{
m_elementSize = sizeof(T);
m_interval = interval;
m_top = -1;
m_arraySize = initSize;
data = new T[initSize];
}
template<class T>
void Stack<T>::setInterval(int i)
{
m_interval = i;
}
template<class T>
void Stack<T>::arangeArray()
{
cout << "arranging" << endl;
T* newly = new T[m_arraySize + m_interval];
for (int i = 0;i < m_arraySize; i++)
{
newly[i] = data[i];
}
m_arraySize += m_interval;
delete [] data;
data = newly;
cout << "top: " << m_top << endl;
cout << "new size: " << m_arraySize << endl;
}
template<class T>
void Stack<T>::put(T element)
{
while (true)
{
if (m_top >= m_arraySize -1)
{
arangeArray();
continue;
} else
{
data[++m_top] = element;
break;
}
}
}
template<class T>
T Stack<T>::pop()
{
T t = data[m_top--];
return t;
}
template<class T>
void Stack<T>::clear()
{
m_top = -1;
}
template<class T>
bool Stack<T>::hasNext()
{
if (m_top < 0)
{
return false;
} else
{
return true;
}
}
template<class T>
const T Stack<T>::peek()
{
return data[m_top];
}
template<class T>
int Stack<T>::getCapability()
{
return m_top;
}
| [
"tony84727@gmail.com"
] | tony84727@gmail.com |
479b789da06533212c6de439b3641c27f03953cc | cc573bec6fb691176e8409038fc60edf73940921 | /GLTexture.h | 46f4a6d79d9f9db05b4e72b169780bce0e288010 | [] | no_license | tekken98/glStudio | 08e89abbec206cbd73d05c84f5be20b4bf916d09 | 8a464d7aebcb8d3ce3a6700a2116a72d9b1d6769 | refs/heads/master | 2020-05-16T05:01:42.142525 | 2019-04-30T16:33:13 | 2019-04-30T16:33:13 | 182,799,738 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 534 | h | #ifndef GLTEXTURE_H
#define GLTEXTURE_H
#include <map>
#include "common.h"
class GLTexture
{
private:
map<const char * , GLuint> d_texture;
public:
//constructor
GLTexture();
GLTexture(const GLTexture& s);
GLTexture& operator=(const GLTexture& s);
~GLTexture();
public:
//maniulator
void loadTexture(const char * filename,const char* key);
//accessor
GLuint getTexture(const char * key);
void setTexture(const char * key);
};
#endif
| [
"bao19411@eyou.com"
] | bao19411@eyou.com |
748aea68675d44f4e4186a8bcc18871b5ba29201 | d0ceb8e9a5e132e0a31d1e1639d45a0b6a8d049f | /src/main/cpp/exbisim/gen/gen.hpp | 2304f17f68973641a7dc84ad06d415dc55a915c7 | [
"BSD-2-Clause"
] | permissive | sshyran/graphene | 100e6117271052785eeb4026daede877d5f5a857 | 0f9a881ac5363ffe26d4b4bc63c70f484d1d1aa6 | refs/heads/master | 2023-04-16T00:45:55.236730 | 2014-11-13T21:50:00 | 2014-11-13T21:50:00 | 272,573,216 | 0 | 0 | null | 2023-04-04T01:40:04 | 2020-06-16T00:35:03 | null | UTF-8 | C++ | false | false | 2,332 | hpp | /**
* gen.hpp - Generate random trees and DAGs.
*
* Copyright (c) 2011 Jelle Hellings <exbisim@jhellings.nl>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY JELLE HELLINGS ``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 FOUNDATION 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.
*/
#ifndef INCLUDE_GEN_HPP_
#define INCLUDE_GEN_HPP_
#include "common/types.hpp"
/**
* Check if a value is in the range [0..100]. If not then throw an exception.
*
* @param value The value to check.
* @throws const char[] an error message when value is not in [0..100].
*/
void check_is_percentage(const std::uint8_t value);
/**
* Check if a minimum value is not greater then a maximum value.
*
* @param min The minimum value to check.
* @param max The maximum value to check.
* @throws const char[] an error message min > max.
*/
void check_min_max(const uint min, const uint max);
/**
* Check if a value is not zero. If value is zero then throw an exception.
*
* @param value The value to check.
* @throws const char[] an error message when value is zero.
*/
void check_not_zero(const uint value);
#endif | [
"lgreg.meredith@biosimilarity.com"
] | lgreg.meredith@biosimilarity.com |
385d4f7e2ea133668ed0599b29c9eec584db89df | 2d381bb9e80ba5b4ca4b0556eacca705d90fde01 | /c++/switch.cpp | 7e1d96ae64aa397c17ae76e0cac4446d9a436869 | [] | no_license | apurvarawal/Cpp-notes-with-examples | 298a388651d29a5fa340aa888af8651cbe402698 | 7abbf6e9492d09191fce9806cd4fedfb510b4a4a | refs/heads/master | 2023-08-20T08:55:50.552052 | 2021-09-19T05:44:57 | 2021-09-19T05:44:57 | 408,043,928 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 295 | cpp | #include<iostream>
using namespace std;
int main(){
int age;
cout<<"Enter your age."<<endl;
cin>>age;
switch (age)
{
case 18:
cout<<"You are 18."<<endl;
break;
default:
cout<<"You are not 18."<<endl;
break;
}
return 0;
} | [
"apurva2928@gmail.com"
] | apurva2928@gmail.com |
7699b6df6cf61a22136045a0b67ee0dd4fbcef71 | 641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2 | /components/offline_pages/background/request_queue_store_sql.h | 0be2eb5700e73b3a2ab7100ed6480ff13da13ec5 | [
"BSD-3-Clause"
] | permissive | massnetwork/mass-browser | 7de0dfc541cbac00ffa7308541394bac1e945b76 | 67526da9358734698c067b7775be491423884339 | refs/heads/master | 2022-12-07T09:01:31.027715 | 2017-01-19T14:29:18 | 2017-01-19T14:29:18 | 73,799,690 | 4 | 4 | BSD-3-Clause | 2022-11-26T11:53:23 | 2016-11-15T09:49:29 | null | UTF-8 | C++ | false | false | 2,709 | h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_OFFLINE_PAGES_BACKGROUND_REQUEST_QUEUE_STORE_SQL_H_
#define COMPONENTS_OFFLINE_PAGES_BACKGROUND_REQUEST_QUEUE_STORE_SQL_H_
#include <stdint.h>
#include <memory>
#include <vector>
#include "base/files/file_path.h"
#include "base/memory/weak_ptr.h"
#include "components/offline_pages/background/request_queue_store.h"
namespace base {
class SequencedTaskRunner;
}
namespace sql {
class Connection;
}
namespace offline_pages {
// SQLite implementation of RequestQueueStore.
class RequestQueueStoreSQL : public RequestQueueStore {
public:
RequestQueueStoreSQL(
scoped_refptr<base::SequencedTaskRunner> background_task_runner,
const base::FilePath& database_dir);
~RequestQueueStoreSQL() override;
// RequestQueueStore implementation.
void GetRequests(const GetRequestsCallback& callback) override;
// Note: current implementation of this method makes a SQL query per ID. This
// is OK as long as number of IDs stays low, which is a typical case.
// Implementation should be revisited in case that presumption changes.
void GetRequestsByIds(const std::vector<int64_t>& request_ids,
const UpdateCallback& callback) override;
void AddRequest(const SavePageRequest& offline_page,
const AddCallback& callback) override;
void UpdateRequests(const std::vector<SavePageRequest>& requests,
const UpdateCallback& callback) override;
void RemoveRequests(const std::vector<int64_t>& request_ids,
const UpdateCallback& callback) override;
void Reset(const ResetCallback& callback) override;
StoreState state() const override;
private:
// Helper functions to return immediately if no database is found.
bool CheckDb(const base::Closure& callback);
// Used to initialize DB connection.
void OpenConnection();
void OnOpenConnectionDone(StoreState state);
// Used to finalize connection reset.
void OnResetDone(const ResetCallback& callback, StoreState state);
// Background thread where all SQL access should be run.
scoped_refptr<base::SequencedTaskRunner> background_task_runner_;
// Path to the database on disk.
base::FilePath db_file_path_;
// Database connection.
std::unique_ptr<sql::Connection> db_;
// State of the store.
StoreState state_;
base::WeakPtrFactory<RequestQueueStoreSQL> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(RequestQueueStoreSQL);
};
} // namespace offline_pages
#endif // COMPONENTS_OFFLINE_PAGES_BACKGROUND_REQUEST_QUEUE_STORE_SQL_H_
| [
"xElvis89x@gmail.com"
] | xElvis89x@gmail.com |
5e21b106d59f46705a1fb235efe77cba92a8eaff | 607fbf14d39d972b293bce2fa9924076a50c99c2 | /src/ofxShutdown.h | 8f5ac7cc2eaaacbe2f81395381c4ac30df94bee6 | [
"MIT"
] | permissive | wasawi/ofxShutdown | eab69cdacdf5fdfeaaa39ed5216221d6765a2262 | 2c13e62ba5d8c78bcb5657cd7bcf6c772fd20b2c | refs/heads/master | 2021-06-05T15:41:18.373017 | 2017-06-23T05:15:20 | 2017-06-23T05:15:20 | 22,604,331 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,357 | h | /***********************************************************************
Copyright (c) 2009, Jordi Puig, www.wasawi.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************/
/*
This addon uses a countdown to shutdown your computer.
If the user running the application is not an admin you will receive this message:
"[USER]is not in the sudoers file. This incident will be reported."
To fix it, log in as admin and run in terminal the following:
sudo nano /private/etc/sudoers
then enter a new line:
[the username you want to give access] ALL=(ALL) ALL
Example:
myUser ALL=(ALL) ALL
Then close nano saving changes:
crtl+x [enter]
y [enter]
then use:
shutdown();
*/
#pragma once
#include "ofMain.h"
class ofxShutdown{
public:
ofxShutdown();
~ofxShutdown();
// SETTERS
void setParams(string _shutdownParams) {shutdownParams = _shutdownParams;}
void setUserIsAdmin(bool _isAdmin, string _password){isAdmin = _isAdmin;
password = _password;}
void setDelay(float _delaySeconds) {delay = _delaySeconds;}
void setDrawMessage(bool _drawMessage) {bDrawMessage= _drawMessage;}
void exitOFAfterShutdownCommand(bool _exit) {bexitAfterCommand= _exit;}
// call this to initiate shutdown countdown
void shutdownExecute();
private:
void update(ofEventArgs &e);
void draw(ofEventArgs &e);
bool bRestarting;
bool bWaitingToShutdown;
float countdown; // time left
float elapsedTime;
float startTime; // when did the stopwatch start
// params
string shutdownParams;
bool isAdmin;
string password;
float delay; // fixed time before restart
bool bDrawMessage;
bool bexitAfterCommand;
void shutDown();
};
| [
"criccrec@gmailc.com"
] | criccrec@gmailc.com |
cc0381936ca5512e19d74c8911cf2bf779c0befe | 816992a0dcc35fb9e19bf5e4dd974ab8a2a353e2 | /kpu/algorithm_final/3_joy_stick.cpp | a4e0f748952a61bb87747ab23d2446a3ce5429e1 | [] | no_license | gowoonsori/algorithm-problem-solve | e066f8f13124ba339c72ea9bec48a0673a3351e2 | 68a077728be929cd04a56c2954f8082087c929e5 | refs/heads/master | 2023-05-31T13:30:41.087070 | 2021-06-19T12:46:01 | 2021-06-19T12:46:01 | 275,135,901 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 981 | cpp | #include <string>
#include <vector>
#include <iostream>
using namespace std;
int solution(string name) {
int answer = 0;
int i=0;
string tmp(name.length(),'A');
while(1){
tmp[i] = name[i];
answer += (name[i] <= 'M') ? (name[i] - 'A') : ('Z' - name[i] + 1) ;
if(!tmp.compare(name)) break;
for(int mov = 1; mov < name.length() ; mov++){
if(name [(i + mov) % name.length()] != tmp[(i + mov) % name.length()]){
i = (i + mov) % name.length();
answer += mov;
break;
}
else if(name [(i + name.length() - mov) % name.length()] != tmp[(i + name.length() - mov)% name.length()]){
i = ( i + name.length() - mov ) % name.length();
answer += mov;
break;
}
}
}
return answer;
}
int main(){
string input;
cin >> input;
cout << solution(input);
return 0;
} | [
"gowoonsori97@naver.com"
] | gowoonsori97@naver.com |
4415a13279e75884a5680fce8df8dbac1cc7e4e3 | 5089966150f3716e1acb3516fb1cecfe8cb4675c | /src/renderer/resource_managers/texture.h | 95584d8a64ddcb4969eac8aa1370771be27ee1ad | [
"MIT"
] | permissive | JakubLukas/NewEngine | 84356d3251c15fd2d87bd252b25243176229c630 | 38ea585a37347ec0630673b9d4a7f948e4dc1477 | refs/heads/master | 2021-06-04T18:01:57.325798 | 2020-10-24T21:06:47 | 2020-10-24T21:06:47 | 104,794,610 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 468 | h | #pragma once
#include "core/resource/resource.h"
namespace Veng
{
enum class textureRenderHandle : u32 {};
const textureRenderHandle INVALID_TEXTURE_RENDER_HANDLE = (textureRenderHandle)0;
struct Texture : public Resource
{
static ResourceType RESOURCE_TYPE;
Texture() : Resource(ResourceType("texture")) {}
u32 width = 0;
u32 height = 0;
u32 channels = 0;
textureRenderHandle renderDataHandle = INVALID_TEXTURE_RENDER_HANDLE;
u8* data = nullptr;
};
} | [
"lukasik.lukasik@gmail.com"
] | lukasik.lukasik@gmail.com |
71aef43597bcc3cad61ddf1d76de5a332fa32402 | 560090526e32e009e2e9331e8a2b4f1e7861a5e8 | /Compiled/blaze-3.2/blazetest/blazetest/mathtest/creator/DynamicHermitian.h | 88d06168a3ca5011c797d950c1ac0c1d246b282a | [
"BSD-3-Clause"
] | permissive | jcd1994/MatlabTools | 9a4c1f8190b5ceda102201799cc6c483c0a7b6f7 | 2cc7eac920b8c066338b1a0ac495f0dbdb4c75c1 | refs/heads/master | 2021-01-18T03:05:19.351404 | 2018-02-14T02:17:07 | 2018-02-14T02:17:07 | 84,264,330 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,632 | h | //=================================================================================================
/*!
// \file blazetest/mathtest/creator/DynamicHermitian.h
// \brief Specialization of the Creator class template for HermitianMatrix<DynamicMatrix>
//
// Copyright (C) 2012-2017 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
#ifndef _BLAZETEST_MATHTEST_CREATOR_DYNAMICHERMITIAN_H_
#define _BLAZETEST_MATHTEST_CREATOR_DYNAMICHERMITIAN_H_
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/HermitianMatrix.h>
#include <blaze/math/shims/Real.h>
#include <blazetest/mathtest/creator/Default.h>
#include <blazetest/mathtest/creator/Policies.h>
#include <blazetest/system/Types.h>
namespace blazetest {
//=================================================================================================
//
// CLASS DEFINITION
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Specialization of the Creator class template for Hermitian dynamic matrices.
//
// This specialization of the Creator class template is able to create random Hermitian dynamic
// matrices.
*/
template< typename T // Element type of the dynamic matrix
, bool SO > // Storage order of the dynamic matrix
class Creator< blaze::HermitianMatrix< blaze::DynamicMatrix<T,SO> > >
{
public:
//**Type definitions****************************************************************************
//! Type to be created by the Creator.
typedef blaze::HermitianMatrix< blaze::DynamicMatrix<T,SO> > Type;
//**********************************************************************************************
//**Constructors********************************************************************************
/*!\name Constructors */
//@{
explicit inline Creator( const Creator<T>& elementCreator = Creator<T>() );
explicit inline Creator( size_t n, const Creator<T>& elementCreator = Creator<T>() );
// No explicitly declared copy constructor.
//@}
//**********************************************************************************************
//**Destructor**********************************************************************************
// No explicitly declared destructor.
//**********************************************************************************************
//**Operators***********************************************************************************
/*!\name Operators */
//@{
// No explicitly declared copy assignment operator.
const blaze::HermitianMatrix< blaze::DynamicMatrix<T,SO> > operator()() const;
template< typename CP >
const blaze::HermitianMatrix< blaze::DynamicMatrix<T,SO> > operator()( const CP& policy ) const;
//@}
//**********************************************************************************************
private:
//**Member variables****************************************************************************
/*!\name Member variables */
//@{
size_t n_; //!< The number of rows and columns of the Hermitian dynamic matrix.
Creator<T> ec_; //!< Creator for the elements of the Hermitian dynamic matrix.
//@}
//**********************************************************************************************
};
//*************************************************************************************************
//=================================================================================================
//
// CONSTRUCTORS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Constructor for the creator specialization for HermitianMatrix<DynamicMatrix>.
//
// \param elementCreator The creator for the elements of the Hermitian dynamic matrix.
*/
template< typename T // Element type of the dynamic matrix
, bool SO > // Storage order of the dynamic matrix
inline Creator< blaze::HermitianMatrix< blaze::DynamicMatrix<T,SO> > >::Creator( const Creator<T>& elementCreator )
: n_( 3UL ) // The number of rows and columns of the Hermitian dynamic matrix
, ec_( elementCreator ) // Creator for the elements of the Hermitian dynamic matrix
{}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Constructor for the creator specialization for HermitianMatrix<DynamicMatrix>.
//
// \param n The number of rows and columns of the Hermitian dynamic matrix.
// \param elementCreator The creator for the elements of the Hermitian dynamic matrix.
*/
template< typename T // Element type of the dynamic matrix
, bool SO > // Storage order of the dynamic matrix
inline Creator< blaze::HermitianMatrix< blaze::DynamicMatrix<T,SO> > >::Creator( size_t n, const Creator<T>& elementCreator )
: n_( n ) // The number of rows and columns of the Hermitian dynamic matrix
, ec_( elementCreator ) // Creator for the elements of the Hermitian dynamic matrix
{}
//*************************************************************************************************
//=================================================================================================
//
// OPERATORS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Returns a randomly created Hermitian dynamic matrix.
//
// \return The randomly generated Hermitian dynamic matrix.
*/
template< typename T // Element type of the dynamic matrix
, bool SO > // Storage order of the dynamic matrix
inline const blaze::HermitianMatrix< blaze::DynamicMatrix<T,SO> >
Creator< blaze::HermitianMatrix< blaze::DynamicMatrix<T,SO> > >::operator()() const
{
return (*this)( Default() );
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Returns a randomly created Hermitian dynamic matrix.
//
// \param policy The creation policy for the elements of fundamental data type.
// \return The randomly generated Hermitian dynamic matrix.
*/
template< typename T // Element type of the dynamic matrix
, bool SO > // Storage order of the dynamic matrix
template< typename CP > // Creation policy
inline const blaze::HermitianMatrix< blaze::DynamicMatrix<T,SO> >
Creator< blaze::HermitianMatrix< blaze::DynamicMatrix<T,SO> > >::operator()( const CP& policy ) const
{
using blaze::real;
blaze::HermitianMatrix< blaze::DynamicMatrix<T,SO> > matrix( n_ );
// Initialization of a column-major matrix
if( SO ) {
for( size_t j=0UL; j<n_; ++j ) {
for( size_t i=0UL; i<j; ++i )
matrix(i,j) = ec_();
matrix(j,j) = real( ec_( policy ) );
}
}
// Initialization of a row-major matrix
else {
for( size_t i=0UL; i<n_; ++i ) {
for( size_t j=0UL; j<i; ++j )
matrix(i,j) = ec_();
matrix(i,i) = real( ec_( policy ) );
}
}
return matrix;
}
//*************************************************************************************************
} // namespace blazetest
#endif
| [
"jonathan.doucette@alumni.ubc.ca"
] | jonathan.doucette@alumni.ubc.ca |
6357aa99caa6e07a94d0df675378b919c10acb11 | c78d8bfd9148524976d8366d9b0c6e81afec13d9 | /src/worker_thread.cpp | 1c5eda47a0e529b3a9a23c128c48f41c4a7ea3ab | [] | no_license | caetanosauer/finelog | 9e76d7f3bc85cde8c7ea8a524989e289cb908869 | ca7b3e273c3367ad6e5c06968fde426b6c848b31 | refs/heads/master | 2020-03-14T23:34:15.023397 | 2018-05-23T20:07:50 | 2018-05-23T20:07:50 | 131,848,174 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,993 | cpp | #include "worker_thread.h"
worker_thread_t::worker_thread_t(int interval_ms)
:
interval_msec(interval_ms),
stop_requested(false),
wakeup_requested(false),
worker_busy(false),
rounds_completed(0)
{
}
worker_thread_t::~worker_thread_t()
{
}
void worker_thread_t::wakeup(bool wait, int rounds_to_wait)
{
long this_round = 0;
{
std::unique_lock<std::mutex> lck(cond_mutex);
if (wait) {
// Capture current round number before wakeup
this_round = rounds_completed + rounds_to_wait;
if (worker_busy) { this_round++; }
}
// Send wake-up signal
wakeup_requested = true;
wakeup_condvar.notify_one();
}
if (wait) {
wait_for_round(this_round);
}
}
void worker_thread_t::wait_for_round(long round)
{
std::unique_lock<std::mutex> lck(cond_mutex);
if (round == 0) { round = rounds_completed + 1; }
auto predicate = [this, round]
{
return should_exit() || rounds_completed >= round;
};
done_condvar.wait(lck, predicate);
}
void worker_thread_t::stop()
{
stop_requested = true;
wakeup();
join();
}
void worker_thread_t::quit()
{
stop_requested = true;
}
void worker_thread_t::run()
{
auto predicate = [this] { return wakeup_requested || should_exit(); };
auto timeout = std::chrono::milliseconds(interval_msec);
while (true) {
if (stop_requested) { break; }
{
std::unique_lock<std::mutex> lck(cond_mutex);
if (interval_msec < 0) {
// Only activate upon recieving a wakeup signal
wakeup_condvar.wait(lck, predicate);
}
else if (interval_msec > 0) {
// Activate on either signal or interval timeout; whatever
// comes first
wakeup_condvar.wait_for(lck, timeout, predicate);
}
if (stop_requested) { break; }
wakeup_requested = false;
worker_busy = true;
}
do_work();
{
// Notify waiting threads that we are done with this round
std::lock_guard<std::mutex> lck(cond_mutex);
rounds_completed++;
worker_busy = false;
done_condvar.notify_all();
}
}
}
void worker_thread_t::notify_one()
{
std::lock_guard<std::mutex> lck(cond_mutex);
done_condvar.notify_one();
}
void worker_thread_t::notify_all()
{
std::lock_guard<std::mutex> lck(cond_mutex);
done_condvar.notify_all();
}
void log_worker_thread_t::wakeup_until_lsn(lsn_t lsn, bool wait, int rounds_to_wait)
{
// Only change endLSN if it's increasing
while (true) {
lsn_t curr = endLSN;
if (lsn < curr) { break; }
if (endLSN.compare_exchange_strong(curr, lsn))
{
break;
}
}
// Now send wakeup signal. No need to set LSN while holding mutex.
wakeup(wait, rounds_to_wait);
}
| [
"csauer@cs.uni-kl.de"
] | csauer@cs.uni-kl.de |
9cc53e1eba3ffb9aa4835cb0371e2b45aa07c673 | 54f352a242a8ad6ff5516703e91da61e08d9a9e6 | /Source Codes/CodeJamData/15/12/17.cpp | 8efef072e3e2b93cf2b59a4a97c3457a9a165f78 | [] | no_license | Kawser-nerd/CLCDSA | 5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb | aee32551795763b54acb26856ab239370cac4e75 | refs/heads/master | 2022-02-09T11:08:56.588303 | 2022-01-26T18:53:40 | 2022-01-26T18:53:40 | 211,783,197 | 23 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 891 | cpp | #include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long ll;
const ll INF = (ll)1e18;
const int N = 1010;
int n;
ll m;
ll a[N];
ll check(ll x)
{
ll res = 0;
for (int i = 0; i < n; i++)
res = min(INF, res + (x + a[i] - 1) / a[i]);
return res;
}
void solve()
{
scanf("%d%lld", &n, &m);
for (int i = 0; i < n; i++)
scanf("%lld", &a[i]);
ll l = 0, r = INF;
while(r - l > 1)
{
ll x = (l + r) / 2;
ll st = check(x);
if (st < m)
l = x;
else
r = x;
}
ll cnt = m - check(l);
for (int i = 0; i < n; i++)
{
if (l % a[i] != 0) continue;
if (cnt == 1)
{
printf("%d\n", i + 1);
return;
}
else
cnt--;
}
throw;
}
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int t;
scanf("%d", &t);
for (int i = 1; i <= t; i++)
{
printf("Case #%d: ", i);
solve();
}
return 0;
}
| [
"kwnafi@yahoo.com"
] | kwnafi@yahoo.com |
5f590ed197e411f11edb731e219817e03de97825 | 65b335db03ef3d2977bc0cbdce8bae42e5ebfa2f | /main.cpp | 997f569121bd19d2e02ac8279d2a8777ca8130c6 | [
"ISC"
] | permissive | berezovskyi/cpptran-play | 50c3210977a6662589398b9384231d4629441aac | 6154d9d73a68c0d97da1433262a8bb44b2923ef9 | refs/heads/master | 2020-12-24T06:01:17.023217 | 2018-11-25T12:59:54 | 2018-11-25T12:59:54 | 73,240,363 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 425 | cpp | // This illustrates how a Fortran routine may be
// called from a main program in C++, and a char[] string passed
#include <iostream>
#include <string.h>
extern "C" {
void fr1_(int *, int *, char *);// __attribute__ ((stdcall));
}
int main()
{
int n = 10, nSq;
char szCtest[20];
strcpy(szCtest, "teststring");
fr1_(&n, &nSq, szCtest);
std::cout << "The square is:" << nSq << std::endl;
return 0;
} | [
"andriib@kth.se"
] | andriib@kth.se |
84abfe2505457d36d45ff7813ad8235e9ec7f917 | 3575bcb346aafc7d3309afa47268cd9930261399 | /src/expressions/new_array.h | 5ffbc781c6d59c7164fc32bf45bdb704e93845ac | [] | no_license | alexa0o/MiniJavaCompiler | 5818f4d8181b74f7e08432b9d76d4d8ee266fe10 | 1ac525eceee056234c27b8651af9ba234dc1804f | refs/heads/main | 2023-04-11T06:00:48.802934 | 2021-02-28T20:03:18 | 2021-02-28T20:03:18 | 342,803,929 | 0 | 0 | null | 2021-04-13T19:03:15 | 2021-02-27T08:07:57 | C++ | UTF-8 | C++ | false | false | 278 | h | #pragma once
#include <string>
#include "type.h"
#include "expression.h"
class NewArrayExpression: public Expression {
public:
NewArrayExpression(Type type, Expression* size);
void accept(Visitor* visitor) override;
private:
Type type_;
Expression* size_;
}; | [
"haaa@1c.ru"
] | haaa@1c.ru |
421791bf38bce33d111df7db9adcde73bdeb2afb | 7e1844a174e8dfd087dfca47863f0b0e29f3b72b | /codes/intervalproduct.cpp | f91ed2b0793672cf58f1e405c598fbce87f4447f | [] | no_license | matheusmso/mac0499 | e266c5abebdc3a0cd124c02d728c61fd2d0d640c | 72fbb97a83c07a01e419f5078fcbcb202ea509bf | refs/heads/master | 2021-09-30T23:42:06.121107 | 2018-11-26T02:21:59 | 2018-11-26T02:21:59 | 113,798,725 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,362 | cpp | #include <bits/stdc++.h>
using namespace std;
#define debug(args...) fprintf(stderr,args)
typedef long long lint;
const int INF = 0x3f3f3f3f;
const lint LINF = 0x3f3f3f3f3f3f3f3f;
const int NEUTRAL = 0;
const int N = (int)1e5+7;
int n, k, v[N], segz[4*N], segn[4*N];
int join(int a, int b) {
return a + b;
}
void build(int node = 1, int l = 0, int r = n) {
if (l + 1 == r) {
if (v[l] == 0)
segz[node] = 1;
else if (v[l] < 0)
segn[node] = 1;
else
segz[node] = segn[node] = 0;
return;
}
int mid = (l + r)/2;
build(2*node, l, mid);
build(2*node+1, mid, r);
segn[node] = join(segn[2*node], segn[2*node+1]);
segz[node] = join(segz[2*node], segz[2*node+1]);
}
void update(int pos, int value, int node = 1, int l = 0, int r = n) {
if (value > 0) {
segn[node] -= v[pos] < 0;
segz[node] -= v[pos] == 0;
}
else if (value < 0) {
segn[node] += v[pos] >= 0;
segz[node] -= v[pos] == 0;
}
else {
segn[node] -= v[pos] < 0;
segz[node] += v[pos] != 0;
}
if (l + 1 == r) {
v[pos] = value;
return;
}
int mid = (l + r)/2;
if (pos < mid)
update(pos, value, 2*node, l, mid);
else
update(pos, value, 2*node+1, mid, r);
segz[node] = join(segz[2*node], segz[2*node+1]);
segn[node] = join(segn[2*node], segn[2*node+1]);
}
int queryz(int x, int y, int node = 1, int l = 0, int r = n) {
if (x >= r || y <= l) return NEUTRAL;
if (x <= l && y >= r) return segz[node];
int mid = (l + r)/2;
return join(queryz(x, y, 2*node, l, mid), queryz(x, y, 2*node+1, mid, r));
}
int queryn(int x, int y, int node = 1, int l = 0, int r = n) {
if (x >= r || y <= l) return NEUTRAL;
if (x <= l && y >= r) return segn[node];
int mid = (l + r)/2;
return join(queryn(x, y, 2*node, l, mid), queryn(x, y, 2*node+1, mid, r));
}
int main() {
while (scanf(" %d %d", &n, &k) != EOF) {
for (int i = 0; i < n; i++) {
scanf(" %d", v + i);
}
memset(segz, 0, sizeof(segz));
memset(segn, 0, sizeof(segn));
build();
while (k--) {
int x, y;
char c;
scanf(" %c %d %d", &c, &x, &y);
if (c == 'C') update(x - 1, y);
else {
int z = queryz(x - 1, y);
int neg = queryn(x - 1, y);
if (z) printf("0");
else printf("%s", neg % 2 == 0 ? "+" : "-");
}
}
printf("\n");
}
return 0;
}
| [
"matheusmso@fb.com"
] | matheusmso@fb.com |
2f038e27b649a1a7f5164b63e6a7b65cb6274108 | 4a41e5b7e93d39386055ce8648e6c3354f97c61e | /dbDemo/hello/main.cpp | 2a18124f3f328302ed89ae7e00ace65ad0357aa9 | [] | no_license | lianaipeng/demos | 52c78eed35f7921b2c425dc6c8443478d80a3061 | 6692aa6537ab56f56e5b6e374d16654dc17091c1 | refs/heads/master | 2021-01-17T12:00:12.192250 | 2017-07-19T09:12:37 | 2017-07-19T09:12:37 | 47,742,913 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,536 | cpp |
#include <stdio.h>
#include "acl_cpp/lib_acl.hpp"
#include "mysql/mysql.h"
////////////////////////////////////////////////////////////////////////////////
/**
* 从数据库中查询表数据
* @param db {acl::db_handle&} acl 中的数据库连接句柄引用
*/
static void tbl_select(acl::db_handle& db)
{
// 创建 sql 查询语句
const char* sql = "SELECT * FROM `statistics_oplog` LIMIT 10;";
// 查询数据库
if (db.sql_select(sql) == false) {
printf("select sql: %s error\r\n", sql);
return;
}
printf("\r\n---------------------------------------------------\r\n");
// 列出查询结果方法一:从数据库句柄中获得查询结果集合
const acl::db_rows* result = db.get_result();
if (result) {
// 遍历查询结果集
const std::vector<acl::db_row*>& rows = result->get_rows();
for (size_t i = 0; i < rows.size(); i++) {
const acl::db_row* row = rows[i];
// 打印一行结果中的所有结果
for (size_t j = 0; j < row->length(); j++)
printf("%s, ", (*row)[j]);
printf("\r\n");
}
}
/*
// 列出查询结果方法二:根据数组下标遍历数据库句柄的查询结果集
for (size_t i = 0; i < db.length(); i++) {
const acl::db_row* row = db[i];
// 取出该行记录中某个字段的值
const char* ptr = (*row)["group_name"];
if (ptr == NULL) {
printf("error, no group name\r\n");
continue;
}
printf("group_name=%s: ", ptr);
for (size_t j = 0; j < row->length(); j++)
printf("%s, ", (*row)[j]);
printf("\r\n");
}
// 列出查询结果方法三:直接从数据库句柄中获得结果数组
const std::vector<acl::db_row*>* rows = db.get_rows();
if (rows) {
std::vector<acl::db_row*>::const_iterator cit = rows->begin();
for (; cit != rows->end(); cit++) {
const acl::db_row* row = *cit;
for (size_t j = 0; j < row->length(); j++)
printf("%s, ", (*row)[j]);
printf("\r\n");
}
}
*/
// 必须释放查询结果
db.free_result();
}
////////////////////////////////////////////////////////////////////////////////
/**
* 打开 mysql 数据库连接句柄
* @return {acl::db_handle*} 返回值为 NULL 表示连接数据库失败
*/
static acl::db_handle* open_mysql(void)
{
const char* dbaddr = "192.168.1.249:3307";
const char* dbname = "customer";
const char* dbuser = "beta";
const char* dbpass = "f0cf2a92516045024a0c99147b28f05b";
printf("adaddr:%s,dbname:%s,dbuser:%s,dbpass:%s\n",dbaddr,dbname,dbuser,dbpass);
acl::acl_cpp_init();
acl::log::stdout_open(true);
acl::db_handle* db = new acl::db_mysql(dbaddr, dbname, dbuser, dbpass);
printf("asdfasdfasdfasdf\n");
if (db->open() == false) {
printf("open mysql db error\r\n");
delete db;
return NULL;
}
return db;
}
int main(){
acl::db_handle* db;
// 操作 mysql 数据库过程
db = open_mysql();
if( db ) {
tbl_select(*db);
delete db;
}
/*
// 操作 sqlite 数据库过程
db = open_sqlite();
if (db) {
tbl_select(*db);
delete db;
}
*/
return 0;
}
| [
"lianaipeng@hichao.com"
] | lianaipeng@hichao.com |
9b557f159fd8ba4ba2c59cbed2bc0d0d553c1e76 | f2ed4254f0f9631ae6beff247604d5a8a43dca7c | /System/Src/Include/action_stopProgramScan.h | c9f733f98cd9f8a4e556eec7a7a6a42f794cb3c7 | [] | no_license | imptz/ABMI.00058-01 | 77e769f90b126e5e6dd79c100b40ec97b3b46a44 | 5789c6cc7668502120576585993aabae898a52d9 | refs/heads/master | 2021-01-17T11:54:53.810372 | 2013-11-29T10:06:48 | 2013-11-29T10:06:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 484 | h | #ifndef ACTION_STOP_PROGRAM_SCAN_H
#define ACTION_STOP_PROGRAM_SCAN_H
#include "action.h"
class ActionStopProgramScan : public Action{
private:
virtual void timerHandler();
ActionStopProgramScan();
public:
ActionStopProgramScan(unsigned char _deviceAddress);
virtual ~ActionStopProgramScan();
virtual void step();
private:
enum PHASE{
PHASE_COMMAND,
PHASE_COMMAND_WAIT,
PHASE_STOP
};
PHASE phase;
void error();
void finish();
};
#endif
| [
"ilja@ptz.com"
] | ilja@ptz.com |
641564f2224f90cc4fddc7459c3ec52be57bea0d | 2a40e7ded842e2000be6f824e5951561b6bdadc8 | /MainClass.cpp | f2375ef937c267f8298e806fe47abfc417944cce | [] | no_license | javeme/stc | 60484e3635f90fb9d8866cb268a81da1ff3048a7 | c8a364c1b18f8e57921888ded3627380c472c2e8 | refs/heads/master | 2020-12-25T02:02:21.373570 | 2016-07-12T18:10:05 | 2016-07-12T18:10:05 | 63,180,878 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,459 | cpp | #include "SuffixTree.h"
#include "time.h"
#include "File.h"
using namespace bluemeiIO;
#include <iostream>
using namespace std;
class MainClass
{
public:
void start();
};
void MainClass::start()
{
cout<<"bluemei提示您:请把测试文本放入test.txt中."<<endl;
File file("test.txt");
//file.readAll();
SuffixTree st("");
String line="ABABABC"; st.addText(line);/*
cout<<"正在构造后缀树,请稍后..."<<endl;
float percent,length=0;
long total=file.getSize();
time_t oldTime,currentTime,costTime;
time(&oldTime);
while(file.readLine(line)>0)
{
percent=100*length/total;
length+=line.length();
cout<<"正在构造: (done:"<<percent<<"%)"<<endl<<line<<endl;
st.addText(line);
}
time(¤tTime);
costTime=currentTime-oldTime;
//difftime(currentTime,oldTime)
char time[20];
sprintf(time,"%d小时%d分%d秒",costTime/60/60,costTime/60%60,costTime%60);
cout<<endl<<"-------------------构造完毕(耗时:"<<time<<")-------------------"<<endl<<endl;//*/
String s;
char buffer[100];
while(s!="exit")
{
cout<<"请输入要查找字符串(exit退出):"<<endl;
//scanf("%s",buffer);
cin>>buffer;
if(cin.fail())
{
break;//如何重来clear flush ignore?
}
s=String(buffer,strlen(buffer));
cout<<"index of '"<<s<<"': "<<st.positionOfSubstring(s)<<endl<<endl;
}
st.printTree();
}
int main()
{
MainClass app;
try{
app.start();
}catch(Exception e)
{
e.printException();
}
return 0;
}
| [
"javaloveme@gmail.com"
] | javaloveme@gmail.com |
db12ccdfca952bad0672f35d707a837ccf6e47a5 | ee110fc0433ff57e05582dea6b38f5d15ab90fb5 | /SimpleExample/src/ofApp.h | 270f478cf6b07440b2fe0a01a4be610ecc5d4704 | [] | no_license | NickHardeman/ofxBullet | bd3e221c2b318f641c398c7122f4f6b7c19e6cff | 8b75a2dcf807c7bf0df677858371bc7e0a8c2340 | refs/heads/master | 2023-06-25T08:22:58.775212 | 2023-06-16T14:29:33 | 2023-06-16T14:29:33 | 2,019,013 | 107 | 36 | null | 2023-06-16T14:29:34 | 2011-07-08T17:25:15 | C++ | UTF-8 | C++ | false | false | 707 | h | #pragma once
#include "ofMain.h"
#include "ofxBullet.h"
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void keyPressed (int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
ofxBulletWorldRigid world;
ofxBulletBox ground;
ofxBulletSphere* sphere;
ofxBulletBox* box;
ofxBulletCone* cone;
ofxBulletCapsule* capsule;
ofxBulletCylinder* cylinder;
ofCamera camera;
};
| [
"nickhardeman@gmail.com"
] | nickhardeman@gmail.com |
3b497be3438195f79261619d215161b4087a5cd6 | 0a4653fe762283a08daba1aca84c03abf81655ad | /Leetcode Daily Challenge/January-2021/17. Count Sorted Vowel Strings.cpp | 27cbc0d32c192c6f09afdfd45127afbdb45fc6fe | [
"MIT"
] | permissive | VanshikaSingh10/DataStructures-Algorithms | d532d4ffaa1599b5af8c9971c366352de1a379ff | ded6796e7fb8520e8e8eb4342e534f370d9c9e9e | refs/heads/master | 2023-08-02T18:28:02.099995 | 2021-10-05T10:49:20 | 2021-10-05T10:49:20 | 413,772,801 | 0 | 0 | MIT | 2021-10-05T10:35:45 | 2021-10-05T10:35:45 | null | UTF-8 | C++ | false | false | 1,634 | cpp | /*
Count Sorted Vowel Strings
==========================
Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted.
A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet.
Example 1:
Input: n = 1
Output: 5
Explanation: The 5 sorted strings that consist of vowels only are ["a","e","i","o","u"].
Example 2:
Input: n = 2
Output: 15
Explanation: The 15 sorted strings that consist of vowels only are
["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"].
Note that "ea" is not a valid string since 'e' comes after 'a' in the alphabet.
Example 3:
Input: n = 33
Output: 66045
Constraints:
1 <= n <= 50
Hint #1
For each character, its possible values will depend on the value of its previous character, because it needs to be not smaller than it.
Hint #2
Think backtracking. Build a recursive function count(n, last_character) that counts the number of valid strings of length n and whose first characters are not less than last_character.
Hint #3
In this recursive function, iterate on the possible characters for the first character, which will be all the vowels not less than last_character, and for each possible value c, increase the answer by count(n-1, c).
*/
class Solution
{
public:
int countVowelStrings(int n)
{
vector<int> dp(5, 1);
for (int i = 2; i <= n; ++i)
{
for (int j = 3; j >= 0; --j)
{
dp[j] += dp[j + 1];
}
}
int ans = 0;
for (auto &i : dp)
ans += i;
return ans;
}
};
| [
"sachinverma53121@gmail.com"
] | sachinverma53121@gmail.com |
252da5850e71bcccafd07e7d3078fbc51b9195ac | 48ef819fa3526351615fdcaef9267bb842eb7c42 | /SDK/build/arduino/watch5_mini/cubos/cubos.ino | e906974cf40230ceade0a6d4a49c911f36bb7f60 | [] | no_license | yacubovvs/CubOS_01b | fa2cb67e669d26598e0c240168ea4bd86f59cbd2 | 15add5d1c47fff1c23fc4d12fdece40964f52499 | refs/heads/master | 2023-06-26T06:06:12.765510 | 2021-07-28T17:40:48 | 2021-07-28T17:40:48 | 197,984,057 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,082 | ino | /*
############################################################################################
# #
# WATCH4 SETTINGS #
# #
############################################################################################
*/
/*
### # ## # ## ## ##
# # # # # # # # # # # # #
### ### ## ### # # ## #####
# # # # # # # # # # #
# # # # # # # # # ##
*/
#define SCREEN_WIDTH 128 // Note: x-coordinates go wide
#define SCREEN_HEIGHT 64 // Note: y-coordinates go high
#define SCREEN_SSD1306
#define FONT_CHAR_WIDTH 6 // Font letter size width
#define FONT_CHAR_HEIGHT 8 // Font letter size height
#define useNativeMenu // Using default app_menu.ino
#define conf_watch5_mini // Name of Mconfiguration
#define platform_stm // Platform
#define hasHardwareButtons // Conf of controls with hardware btns
#define control_buttons_count 4
#define control_buttons_pins {PB10, PB0, PA7, PA6}
#define control_has_backbtn
#define control_buttons_on_side
//#define control_buttons_on_LOW_level
//#define device_has_barometer
//#define barometer_power_pin 3
//#define device_has_accelerometer
//#define accelerometer_power_pin 4
//#define device_has_magnitometer
//#define magnitometer_power_pin 14
//#define magnitometr_invert
#define device_has_bluetooth
#define device_bluetooth_serial Serial1
//#define device_bluetooth_power_pin 27
//#define device_bluetooth_stat_pin 23
#define display_invert_y
//#define display_power_pin 26
// #####################################
// ## POWER CONTROL
//#define device_has_power_manager
//#define device_can_sleep
#define device_has_backlight_control
#define backlight_init 10
#define backlight_fade_init 2
//#define device_can_cpu_prescale
//#define isTouchScreen // Conf of controls
//#define tabletView // View
//#define tabletView_statusBarHeight 24 // Height of status bar at top of screen
//#define colorScreen // Screen is colored
//#define noAnimation // Caurse of framebuffer type
#define os_MAINMENU_APP_COUNT 9 // How much apps in menu
//#define mainMenu_iconsInRow 3 // Count of apps in row in tabview in mainMenu
//#define frame_selected_app_padding 10 // Padding of frame on hardware buttons navigate in menu
//#define mainMenu_scrollSize 16 // Size of scrollbar at right of screen
//#define mainMenu_icon_element_size ((SCREEN_WIDTH-1)/mainMenu_iconsInRow - mainMenu_scrollSize/mainMenu_iconsInRow)
//#define appArea_margin_top tabletView_statusBarHeight
// Max ram for apllications runs from TFCard
//#define MAX_RAM_SIZE_FOR_B_APPS 255 //in bytes
#define draw_statusBar
#define device_has_vibro
#define device_vibro_pin 22
/*
### # ## # ## ## ##
# # # # # # # # # # # #
### ### ## ### # # ## #####
# # # # # # # # # #
# # # # # # # # # ##
*/#define SCREEN_CENTER_X (SCREEN_WIDTH/2)
#define SCREEN_CENTER_Y (SCREEN_HEIGHT/2)
#ifdef platform_avr
#ifndef conf_atm64_watch4
#include "libs_h/CyberLib/CyberLib.h"
#endif
#include "libs_h/avr/power.h"
#endif
unsigned int dtime = 0;
/*
**************************************
* *
* APPLICATIONS + *
* *
**************************************
*/
/*
* # # # # # # # # # # # #
* # ICONS #
* # # # # # # # # # # # #
*/
#define ICON_ARROW_RIGHT 0x01
#define ICON_ARROW_LEFT 0x02
#define ICON_ARROW_UP 0x03
#define ICON_ARROW_DOWN 0x04
#define BATTERY_UNKNOWN 0x05
#define BATTERY_100 0x06
#define BATTERY_90 0x07
#define BATTERY_80 0x08
#define BATTERY_70 0x09
#define BATTERY_60 0x0A
#define BATTERY_50 0x0B
#define BATTERY_40 0x0C
#define BATTERY_30 0x0D
#define BATTERY_20 0x0E
#define BATTERY_10 0x0F
#define BATTERY_0 0x10
#define WIFI_CONNECTED 0x11
#define WIFI_NOTCONNECTED 0x12
#define WI_FI_IMG_OFF 0x13
#define BT_CONNECTED 0x14
#define BT_NOTCONNECTED 0x15
#define BT_OFF 0x16
#define SETTINGS_BRIGHTNESS 0x17
#define SETTINGS_FADEBRIGHTNESS 0x18
#define SETTINGS_FADEIN 0x19
#define SETTINGS_SCREENSAVERIN 0x1A
#define SETTINGS_LOCKSCREENIN 0x1B
#define SETTINGS_SCREEN 0x1C
#define SETTINGS_BACK 0x1D
#define SETTINGS_TIME 0x1E
#define PARAM_TYPE_ICON 0x01
#define PARAM_TYPE_NAME 0x02
/////////////////////////////////////
// APPLICATION CLASS
#ifndef do_Not_use_native_apps
class Application{
public:
#ifdef tabletView
boolean showStatusBar = false;
#endif
int scroll_x = 0;
int scroll_y = 0;
int scroll_to_x = 0;
int scroll_to_y = 0;
virtual void loop() = 0;
void loop_app(){
loop();
#ifdef noAnimation
scroll_x = scroll_to_x;
scroll_y = scroll_to_y;
#else
int dy=0; int dx =0;
if(scroll_x!=scroll_to_x){
dx = abs(scroll_x-scroll_to_x)/5 + 2;
if(scroll_x>scroll_to_x) dx *= -1;
scroll_x+=dx;
if (abs(scroll_x-scroll_to_x)<abs(dx)) scroll_to_x=scroll_x;
}
if(scroll_y!=scroll_to_y){
dy = abs(scroll_y-scroll_to_y)/5 + 2;
if(scroll_y>scroll_to_y) dy *= -1;
scroll_y+=dy;
if (abs(scroll_y-scroll_to_y)<abs(dy)) scroll_y=scroll_to_y;
}
//Serial.println(scroll_to_y);
#endif
}
Application(){};
};
Application* currentApp;
#else
int scroll_x = 0;
int scroll_y = 0;
int scroll_to_x = 0;
int scroll_to_y = 0;
void appsetup(){
no_native_apps_SETUP();
}
void apploop(){
no_native_apps_LOOP();
}
#endif
//
/////////////////////////////////////
#ifdef useNativeMenu
Application *getApp(byte i);
////////////////////////////////////
void os_switch_to_app(byte app_numm){
delete currentApp;
#ifdef colorScreen
// for correct drawing background
driver_clearScreen();
#endif
#ifdef device_has_power_manager
set_prevent_displayoff_flag(false);
set_prevent_backlightlow_flag(false);
#endif
currentApp = getApp(app_numm);
}
#endif
/*
**************************************
* *
* APPLICATIONS - *
* *
**************************************
*/
#ifdef platform_avr
#include <avr/sleep.h>
#endif
void setup(){
#ifdef conf_atm64_watch4
setup_redifined_millis();
#endif
#ifdef debug
Serial.begin(115200);
#endif
#ifdef DeviceSerial
#ifndef DeviceSerialSpeed
#define DeviceSerialSpeed 9600
#endif
DeviceSerial.begin(DeviceSerialSpeed);
#endif
#ifdef platform_avr
//set_sleep_mode(SLEEP_MODE_PWR_DOWN);
//sleep_enable();
//MCUCR = bit (BODS) | bit (BODSE);
//MCUCR = bit (BODS);
//sleep_cpu();
#endif
#ifdef device_has_power_manager
power_manager_setup();
#endif
setup_displayDriver();
os_control_setup();
//setup_os_menu();
#ifndef do_Not_use_native_apps
#ifdef BOOT_FUNC
BOOT_FUNC();
#else
app_mainmenu_start(); // Start first app
#endif
#else
no_native_apps_SETUP();
#endif
#ifdef device_has_barometer
//barometer_setup();
#endif
#ifndef device_has_power_manager
#ifdef device_has_accelerometer
accelerometer_setup();
#endif
#else
// if device_has_power_manager define - start accelerometer then need
#endif
#ifdef device_has_vibro
driver_vibro_setup();
#endif
#ifdef device_has_magnitometer
driver_magnitometer_setup();
#endif
}
void loop(){
dtime = os_clock_update();
clearscreen_displayDriver();
#ifdef tabletView
if (currentApp->showStatusBar) os_draw_statusbar();
#endif
os_control_loop(); // Check buttons
#ifndef do_Not_use_native_apps
currentApp->loop_app();
#else
no_native_apps_LOOP();
#endif
////////////////////////////////////////////////////////////////////
// Debug string data
#ifdef colorScreen
setDrawColor_background();
drawRect(0,310, 30, 320, true);
#endif
//showFreeMemory(); // show free memory
//drawDebugString(dtime, 0); // show time needed for 1 loop
//drawDebugString(1000/dtime, 10); // FPS
//drawDebugString(_millis()/1000, 55); // Timer (if you want to know is os freezing)
#ifdef colorScreen
setDrawColor_contrast();
#endif
//
////////////////////////////////////////////////////////////////////
#ifdef device_can_sleep
device_powermanager_sleep_loop();
#endif
updatescreen_displayDriver();
} | [
"mac@MacBook-Air-mac-230.local"
] | mac@MacBook-Air-mac-230.local |
779666200b8b10fb185e14bb1204a3d42f33fa74 | e1916d879a7a7d560b5dbb39cb81dc1ae0f4078f | /gigapixel-app/include/ApiController.h | 7d4ec26fbf87d9d481ded3369a598f088aa7554e | [] | no_license | Gigapixel-Mines/gigapixel-app | 6ad181ae5d44841e2345bf1fb0e75eec38e727d1 | 602b905a3dcd5f4c0d5107311eced2f781d28697 | refs/heads/master | 2021-01-23T16:26:13.196381 | 2017-09-22T16:13:29 | 2017-09-22T16:13:29 | 102,738,593 | 0 | 0 | null | 2017-09-11T21:11:30 | 2017-09-07T13:12:47 | C++ | UTF-8 | C++ | false | false | 5,463 | h | /*=============================================================================
Copyright (C) 2012 - 2016 Allied Vision Technologies. All Rights Reserved.
Redistribution of this file, in original or modified form, without
prior written consent of Allied Vision Technologies is prohibited.
-------------------------------------------------------------------------------
File: ApiController.h
Description: Implementation file for the ApiController helper class that
demonstrates how to implement an asynchronous, continuous image
acquisition with VimbaCPP.
-------------------------------------------------------------------------------
THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF TITLE,
NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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.
=============================================================================*/
#ifndef AVT_VMBAPI_EXAMPLES_APICONTROLLER
#define AVT_VMBAPI_EXAMPLES_APICONTROLLER
#include "CameraObserver.h"
#include "FrameObserver.h"
#include <VimbaCPP/Include/VimbaCPP.h>
#include <QFile>
#include <QTextStream>
#include <string>
namespace AVT {
namespace VmbAPI {
namespace Examples {
class ApiController
{
public:
ApiController();
~ApiController();
//
// Starts the Vimba API and loads all transport layers
//
// Returns:
// An API status code
//
VmbErrorType StartUp();
//
// Shuts down the API
//
void ShutDown();
//
// Opens the given camera
// Sets the maximum possible Ethernet packet size
// Adjusts the image format
// Sets up the observer that will be notified on every incoming frame
// Calls the API convenience function to start image acquisition
// Closes the camera in case of failure
//
// Parameters:
// [in] rStrCameraID The ID of the camera to open as reported by Vimba
//
// Returns:
// An API status code
//
VmbErrorType StartContinuousImageAcquisition(const std::string &rStrCameraID);
//
// Calls the API convenience function to stop image acquisition
// Closes the camera
//
// Returns:
// An API status code
//
VmbErrorType StopContinuousImageAcquisition();
//
// Gets the width of a frame
//
// Returns:
// The width as integer
//
int GetWidth() const;
//
// Gets the height of a frame
//
// Returns:
// The height as integer
//
int GetHeight() const;
//
// Gets the pixel format of a frame
//
// Returns:
// The pixel format as enum
//
VmbPixelFormatType GetPixelFormat() const;
//
// Gets all cameras known to Vimba
//
// Returns:
// A vector of camera shared pointers
//
CameraPtrVector GetCameraList();
//
// Gets the oldest frame that has not been picked up yet
//
// Returns:
// A frame shared pointer
//
FramePtr GetFrame();
//
// Queues a given frame to be filled by the API
//
// Parameters:
// [in] pFrame The frame to queue
//
// Returns:
// An API status code
//
VmbErrorType QueueFrame(FramePtr pFrame);
//
// Clears all remaining frames that have not been picked up
//
void ClearFrameQueue();
//
// Returns the camera observer as QObject pointer to connect their signals to the view's slots
//
QObject* GetCameraObserver();
//
// Returns the frame observer as QObject pointer to connect their signals to the view's slots
//
QObject* GetFrameObserver();
//
// Translates Vimba error codes to readable error messages
//
// Parameters:
// [in] eErr The error code to be converted to string
//
// Returns:
// A descriptive string representation of the error code
//
std::string ErrorCodeToMessage(VmbErrorType eErr) const;
//
// Gets the version of the Vimba API
//
// Returns:
// The version as string
//
std::string GetVersion() const;
void Log(std::string strMsg);
private:
// A reference to our Vimba singleton
VimbaSystem& m_system;
// The currently streaming camera
CameraPtr m_pCamera;
// Every camera has its own frame observer
IFrameObserverPtr m_pFrameObserver;
// Our camera observer
ICameraListObserverPtr m_pCameraObserver;
// The current pixel format
VmbInt64_t m_nPixelFormat;
// The current width
VmbInt64_t m_nWidth;
// The current height
VmbInt64_t m_nHeight;
};
}
}
} // namespace AVT::VmbAPI::Examples
#endif
| [
"31733890+Gigapixel-Mines@users.noreply.github.com"
] | 31733890+Gigapixel-Mines@users.noreply.github.com |
e0803bf5bc0b73e0af6371572feb79e03b3e3525 | 5181e2dd87941613b74be655fd621c13c1032d31 | /1. Nhap mon lap trinh _ chuong01/bai051.cpp | 0a1fcf4cf01ebe5529e43a1f6f033ef4069c663c | [] | no_license | my-hoang-huu/My-hh | 36c57bcc0ff2a6f09d1404af502a63c94dfd7b92 | 176a0ec629438260ef1a44db82fe1a99a59c809f | refs/heads/main | 2023-06-05T03:03:18.421699 | 2021-05-07T00:36:26 | 2021-05-07T00:36:26 | 342,750,649 | 0 | 0 | null | 2021-05-07T00:36:27 | 2021-02-27T02:18:47 | C++ | UTF-8 | C++ | false | false | 279 | cpp | #include<iostream>
using namespace std;
int main()
{
int n;
cout << "nhap n: ";
cin >> n;
int t = 1;
int i = 1;
while (i <= n)
{
if (n % i == 0)
t = t * i;
i = i + 1;
}
cout << "tich cac uoc so cua " << n << " la: " << t << endl;
system("pause");
return 1;
} | [
"hhmy1995@gmail.com"
] | hhmy1995@gmail.com |
422d520fd03d10bc8bb4e81bcceb62fe8d6b7a2b | e09dfcc817c731587fd756f7611aacb19b17018a | /FilterLog/src/FilterLogDoc.cpp | f23bc6d11db580520cbb6efdec3bad0321bc62a5 | [] | no_license | jweitzen/analogqct | cb77f50f2682ee46325cafd738fcf1299d2710aa | 535bcf32fd615815d640b06c860cfec9acb7f983 | refs/heads/master | 2021-01-10T09:31:14.808743 | 2009-06-12T16:46:03 | 2009-06-12T16:46:03 | 50,674,838 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,602 | cpp | // FilterLogDoc.cpp : implementation of the CFilterLogDoc class
//
#include "stdafx.h"
#include "FilterLog.h"
#include "FilterLogDoc.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CFilterLogDoc
IMPLEMENT_DYNCREATE(CFilterLogDoc, CDocument)
BEGIN_MESSAGE_MAP(CFilterLogDoc, CDocument)
//{{AFX_MSG_MAP(CFilterLogDoc)
ON_COMMAND(ID_VIEW_FILTERINFORMATION, OnViewFilterinformation)
ON_UPDATE_COMMAND_UI(ID_FILE_NEW, OnUpdateFileNew)
ON_UPDATE_COMMAND_UI(ID_FILE_OPEN, OnUpdateFileOpen)
ON_UPDATE_COMMAND_UI(ID_FILE_SAVE, OnUpdateFileSave)
ON_UPDATE_COMMAND_UI(ID_FILE_SAVE_AS, OnUpdateFileSaveAs)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CFilterLogDoc construction/destruction
CFilterLogDoc::CFilterLogDoc()
{
//Define the day of expiry of the program
m_DayOfExpiry = "2009/06/21";
m_DisableProgram = false;
CTime Today = CTime::GetCurrentTime(); //Get today's date
CString TodayString = Today.Format("%Y/%m/%d");
if (TodayString > m_DayOfExpiry)
{
m_DisableProgram = true; //Disale program if license expired
CString ExpiryNotice = "Hi,\n\nthis program has expired. If you intend to keep using it in\nthe future please contact me at:\n\ngiulio2000@bifgoot.com\n\nCiao,\nGiulio";
AfxMessageBox(ExpiryNotice);
PostQuitMessage(0);
}
//This variable is set to true when the UpdateView() function is called in order to
// disbale OnItemChanged in the view during view updating
m_Updating = false;
//Use GetModuleFileName in prder to get the full path to this program
char modulename[_MAX_PATH] ;
GetModuleFileName(NULL, modulename, MAX_PATH) ;
m_ExecutablePath = modulename; //This is the full path to this program
m_ExecutablePath.Replace("FilterLog.exe",""); //remove the program name so that only the path is left
//Open the colour codes file and load the colours and the code in a MAP array
ifstream InColorCodes(m_ExecutablePath + "ColourCodes.txt");
char InString[StringLength];
while(!InColorCodes.eof())
{
InColorCodes.getline(InString,StringLength);
CString str1 = InString;
if (!str1.IsEmpty())
{
CString str2 = str1.Left(str1.Find(" CODE:"));
str1.Replace(str2 + " CODE:","");
m_ColorMap.SetAt(str2,str1); //load the color name and codes in a MAP structure
m_CodeMap.SetAt(str1,str2); //load the color name and codes in a MAP structure
}
}
InColorCodes.close();
m_FilterInfo.SetSize(NoFilterInfoElements,1);
}
CFilterLogDoc::~CFilterLogDoc()
{
}
BOOL CFilterLogDoc::OnNewDocument()
{
if (!CDocument::OnNewDocument())
return FALSE;
FilterData.RemoveAll();
m_FilterInfo.RemoveAll();
m_FilterInfo.SetSize(NoFilterInfoElements,1);
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CFilterLogDoc serialization
void CFilterLogDoc::Serialize(CArchive& ar)
{
if (m_DisableProgram) //If license has expired log analysis is disabled
{
return;
}
if (ar.IsStoring())
{
CString FilterListStart = "\n\nSTRING LIST STARTS HERE\n";
CString str, value;
int NoItems = FilterData.GetSize();
m_FilterInfo.Serialize(ar);
ar << NoItems;
ar << FilterListStart;
for (int i = 0; i < NoItems; i++)
{
CStringArray *Temp = reinterpret_cast<CStringArray *>(FilterData[i]);
m_ColorMap.Lookup(Temp->GetAt(2),value);
str.Format(_T("STRING:%s STATE:%s COL:%s COM:%s REPLACE:%s WITH:%s ENDOFLINE\n"), Temp->GetAt(1), Temp->GetAt(0), value, Temp->GetAt(3), Temp->GetAt(4), Temp->GetAt(5));
ar << str;
}
}
else
{
FilterData.RemoveAll();
int NoItems;
CString str1, value;
m_FilterInfo.Serialize(ar);
ar >> NoItems;
ar >> str1;
for (int i = 0; i < NoItems; i++)
{
ar >> str1;
CStringArray *Row = new CStringArray;
str1.Replace("STRING:","");
Row->SetSize(NoStringArrayElements,1);
CString str2 = str1.Left(str1.Find(" STATE:"));
Row->SetAt(1,str2);
str1.Replace(str2 + " STATE:","");
str2 = str1.Left(str1.Find(" COL:"));
Row->SetAt(0,str2);
str1.Replace(str2 + " COL:","");
str2 = str1.Left(str1.Find(" COM:"));
m_CodeMap.Lookup(str2,value);
Row->SetAt(2,value);
str1.Replace(str2 + " COM:","");
str2 = str1.Left(str1.Find(" REPLACE:"));
Row->SetAt(3,str2);
str1.Replace(str2 + " REPLACE:","");
str2 = str1.Left(str1.Find(" WITH:"));
Row->SetAt(4,str2);
str1.Replace(str2 + " WITH:","");
str2 = str1.Left(str1.Find(" ENDOFLINE"));
Row->SetAt(5,str2);
FilterData.Add(Row);
}
}
}
/////////////////////////////////////////////////////////////////////////////
// CFilterLogDoc diagnostics
#ifdef _DEBUG
void CFilterLogDoc::AssertValid() const
{
CDocument::AssertValid();
}
void CFilterLogDoc::Dump(CDumpContext& dc) const
{
CDocument::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CFilterLogDoc commands
void CFilterLogDoc::OnViewFilterinformation()
{
CFilterInfo FilterInfoDlg;
FilterInfoDlg.m_FilterName = m_FilterInfo[0];
FilterInfoDlg.m_Chipset = m_FilterInfo[1];
FilterInfoDlg.m_PhoneModel = m_FilterInfo[2];
FilterInfoDlg.m_SWVersion = m_FilterInfo[3];
FilterInfoDlg.m_Author = m_FilterInfo[4];
FilterInfoDlg.m_DateModified = m_FilterInfo[5];
FilterInfoDlg.m_QCATFilters = m_FilterInfo[6];
FilterInfoDlg.m_Comments = m_FilterInfo[7];
if( FilterInfoDlg.DoModal() == IDOK )
{
m_FilterInfo[0] = FilterInfoDlg.m_FilterName;
m_FilterInfo[1] = FilterInfoDlg.m_Chipset;
m_FilterInfo[2] = FilterInfoDlg.m_PhoneModel;
m_FilterInfo[3] = FilterInfoDlg.m_SWVersion;
m_FilterInfo[4] = FilterInfoDlg.m_Author;
m_FilterInfo[5] = FilterInfoDlg.m_DateModified;
m_FilterInfo[6] = FilterInfoDlg.m_QCATFilters;
m_FilterInfo[7] = FilterInfoDlg.m_Comments;
SetModifiedFlag();
}
}
void CFilterLogDoc::OnUpdateFileNew(CCmdUI* pCmdUI)
{
if (m_DisableProgram)
{
pCmdUI->Enable(false);
}
}
void CFilterLogDoc::OnUpdateFileOpen(CCmdUI* pCmdUI)
{
if (m_DisableProgram)
{
pCmdUI->Enable(false);
}
}
void CFilterLogDoc::OnUpdateFileSave(CCmdUI* pCmdUI)
{
if (m_DisableProgram)
{
pCmdUI->Enable(false);
}
}
void CFilterLogDoc::OnUpdateFileSaveAs(CCmdUI* pCmdUI)
{
if (m_DisableProgram)
{
pCmdUI->Enable(false);
}
}
| [
"giulio.inbox@6d061dfa-575b-11de-9a1b-6103e4980ab8"
] | giulio.inbox@6d061dfa-575b-11de-9a1b-6103e4980ab8 |
cac4647ab7da5c957ac79e98dd2e36b8a2e20b3d | a3919540792560dbb9fb01ef3bf4f9298fa8dd42 | /header/Object.h | dbe482a6a1b4f6c50c14a6fb16e53dc4fa53f2ea | [
"MIT"
] | permissive | nicovanbentum/Scatter | f6cc305e3637488219e82a5c8aa198fbd5e28bab | 72fc7386767d8c058c55fbe15055ea9397d018e1 | refs/heads/master | 2023-06-15T14:20:01.337914 | 2021-07-15T15:25:43 | 2021-07-15T15:25:43 | 291,949,802 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 293 | h | #pragma once
#include "Vertex.h"
namespace scatter {
struct Object {
std::vector<Vertex> vertices;
std::vector<uint16_t> indices;
uint32_t indexOffset = 0;
uint32_t vertexOffset = 0;
glm::mat4 model = glm::mat4(1.0f);
void createSphere(const float radius);
};
}
| [
"niico0708@gmail.com"
] | niico0708@gmail.com |
f77e7b74bb5122b4869fb351e13aa8546075c738 | 6af17fd2cdd4958d01692abd217328468d0b3a9b | /BMLauncher/BMLauncher/BMLauncher.cpp | fb6bd6b11693c7f020865ccac0559e160f1e1b82 | [] | no_license | scriptkitz/bmloginsvr | c3ad5e44ca34c11f4bb46c21fd45dbb49bc4b668 | cbcc4a97d3adac621eda232ad57340591f78be0e | refs/heads/master | 2021-06-03T10:16:14.947463 | 2016-09-03T06:14:53 | 2016-09-03T06:14:53 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,350 | cpp | // BMLauncher.cpp : 定义应用程序的类行为。
//
#include "stdafx.h"
#include "BMLauncher.h"
#include "BMLauncherDlg.h"
#include "CDuiDialog.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////////
using namespace DuiLib;
// CBMLauncherApp
BEGIN_MESSAGE_MAP(CBMLauncherApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CBMLauncherApp 构造
CBMLauncherApp::CBMLauncherApp()
{
// TODO: 在此处添加构造代码,
// 将所有重要的初始化放置在 InitInstance 中
}
// 唯一的一个 CBMLauncherApp 对象
CBMLauncherApp theApp;
// CBMLauncherApp 初始化
BOOL CBMLauncherApp::InitInstance()
{
// 如果一个运行在 Windows XP 上的应用程序清单指定要
// 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式,
//则需要 InitCommonControlsEx()。否则,将无法创建窗口。
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// 将它设置为包括所有要在应用程序中使用的
// 公共控件类。
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
AfxEnableControlContainer();
// 标准初始化
// 如果未使用这些功能并希望减小
// 最终可执行文件的大小,则应移除下列
// 不需要的特定初始化例程
// 更改用于存储设置的注册表项
// TODO: 应适当修改该字符串,
// 例如修改为公司或组织名
SetRegistryKey(_T("应用程序向导生成的本地应用程序"));
//////////////////////////////////////////////////////////////////////////
CPaintManagerUI::SetInstance(AfxGetInstanceHandle());
CPaintManagerUI::SetResourcePath(CPaintManagerUI::GetInstancePath() + "\\UI\\launcher");
CBMLauncherDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: 在此放置处理何时用
// “确定”来关闭对话框的代码
}
else if (nResponse == IDCANCEL)
{
// TODO: 在此放置处理何时用
// “取消”来关闭对话框的代码
}
// 由于对话框已关闭,所以将返回 FALSE 以便退出应用程序,
// 而不是启动应用程序的消息泵。
return FALSE;
}
| [
"sryan@qq.com"
] | sryan@qq.com |
12d66cc520666265d397ffd163ecbd02cfbbee67 | ad5b72656f0da99443003984c1e646cb6b3e67ea | /src/tests/functional/plugin/gpu/shared_tests_instances/low_precision_transformations/prelu_transformation.cpp | 515c9f90584a9ab36205d86d8881c371168d58c7 | [
"Apache-2.0"
] | permissive | novakale/openvino | 9dfc89f2bc7ee0c9b4d899b4086d262f9205c4ae | 544c1acd2be086c35e9f84a7b4359439515a0892 | refs/heads/master | 2022-12-31T08:04:48.124183 | 2022-12-16T09:05:34 | 2022-12-16T09:05:34 | 569,671,261 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,226 | cpp | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <vector>
#include "low_precision_transformations/prelu_transformation.hpp"
#include "common_test_utils/test_constants.hpp"
using namespace LayerTestsDefinitions;
using namespace InferenceEngine::details;
namespace {
const std::vector<ngraph::element::Type> precisions = {
ngraph::element::f32,
ngraph::element::f16
};
std::vector<PReluTestValues> testValues = {
{ {}, false},
{ { 256ul, ngraph::Shape({}), {0.f}, {25.5f}, {0.f}, {25.5f} }, false },
{ { 256ul, ngraph::Shape({}), {-12.8f}, {12.7f}, {-12.8f}, {12.7f} }, true },
{ { 256ul, ngraph::Shape({}), {12.75f}, {25.5f}, {12.75f}, {25.5f} }, true },
{ { 256ul, ngraph::Shape({}), {-12.8f / 2.f}, {12.7f}, {-12.8f / 2.f}, {12.7f} }, true }
};
// PRelu in low precision is not supported in GPU
INSTANTIATE_TEST_SUITE_P(DISABLED_LPT, PReluTransformation,
::testing::Combine(
::testing::ValuesIn(precisions),
::testing::Values(ngraph::PartialShape({ 1, 3, 16, 16 })),
::testing::Values(CommonTestUtils::DEVICE_GPU),
::testing::ValuesIn(testValues)),
PReluTransformation::getTestCaseName);
} // namespace
| [
"noreply@github.com"
] | novakale.noreply@github.com |
ede64c1698ddeb392daabf9fc954d639e77af122 | 645379b56fc1468d52cd27ce4ded3895fd0f1fa1 | /Cadriciel/Commun/Utilitaire/CompteurAffichage.cpp | 4d66d7fad3dffee2e2ce0c71cefc59e73ee148b4 | [] | no_license | kiwistaki/AsteroidShooter | 7faba3dff36d124b42b8ac51bc361d236fdcc574 | 32f5ab9a73a5ef0c9b5a312cb0a3f0ddcb0ac7cd | refs/heads/master | 2021-01-20T02:53:44.476126 | 2017-05-05T23:39:51 | 2017-05-05T23:39:51 | 83,821,917 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,230 | cpp | //////////////////////////////////////////////////////////////////////////////
/// @file CompteurAffichage.cpp
/// @author Martin Bisson
/// @date 2007-03-09
/// @version 1.0
///
/// @addtogroup utilitaire Utilitaire
/// @{
//////////////////////////////////////////////////////////////////////////////
#include "CompteurAffichage.h"
#include <windows.h>
namespace utilitaire {
/// Pointeur vers l'instance unique de la classe.
CompteurAffichage* CompteurAffichage::instance_ = 0;
////////////////////////////////////////////////////////////////////////
///
/// @fn CompteurAffichage* CompteurAffichage::obtenirInstance()
///
/// Cette fonction retourne un pointeur vers l'instance unique de la
/// classe. Si cette instance n'a pas ete creee, elle la cree. Cette
/// creation n'est toutefois pas necessairement "thread-safe", car
/// aucun verrou n'est pris entre le test pour savoir si l'instance
/// existe et le moment de sa creation.
///
/// @return Un pointeur vers l'instance unique de cette classe.
///
////////////////////////////////////////////////////////////////////////
CompteurAffichage* CompteurAffichage::obtenirInstance()
{
if (instance_ == 0)
instance_ = new CompteurAffichage;
return instance_;
}
////////////////////////////////////////////////////////////////////////
///
/// @fn void CompteurAffichage::libererInstance()
///
/// Cette fonction libere l'instance unique de cette classe.
///
/// @return Aucune.
///
////////////////////////////////////////////////////////////////////////
void CompteurAffichage::libererInstance()
{
delete instance_;
instance_ = 0;
}
////////////////////////////////////////////////////////////////////////
///
/// @fn void CompteurAffichage::signalerAffichage()
///
/// Cette fonction effectue le traitement necessaire lorsqu'un affichage
/// est signalee, c'est-a-dire qu'elle incremente le compte et verifie
/// si la limite de temps pour la mise a jour est depassee.
///
/// @return Aucune.
///
////////////////////////////////////////////////////////////////////////
void CompteurAffichage::signalerAffichage()
{
compte_++;
const int difference = GetTickCount() - derniereLecture_;
if (difference >= TEMPS_RAFRAICHISSEMENT) {
const float compte = (1000.0f * compte_) / ((float) difference);
nbAffichagesSeconde_ = static_cast<int>(compte);
derniereLecture_ += difference;
compte_ = 0;
}
}
////////////////////////////////////////////////////////////////////////
///
/// @fn void CompteurAffichage::reinitialiser()
///
/// Cette fonction reinitialise le compteur d'affichage a son etat
/// initiale.
///
/// @return Aucune.
///
////////////////////////////////////////////////////////////////////////
void CompteurAffichage::reinitialiser()
{
nbAffichagesSeconde_ = 0;
derniereLecture_ = GetTickCount();
compte_ = 0;
}
////////////////////////////////////////////////////////////////////////
///
/// @fn CompteurAffichage::CompteurAffichage()
///
/// Ce constructeur par defaut ne fait qu'initialiser les membres de
/// du compteur.
///
/// @return Aucune (constructeur).
///
////////////////////////////////////////////////////////////////////////
CompteurAffichage::CompteurAffichage()
{
reinitialiser();
}
////////////////////////////////////////////////////////////////////////
///
/// @fn CompteurAffichage::~CompteurAffichage()
///
/// Ce destructeur ne fait rien, mais est quand meme declare afin de
/// pouvoir etre declare prive pour l'implantation du patron singleton.
///
/// @return Aucune (destructeur).
///
////////////////////////////////////////////////////////////////////////
CompteurAffichage::~CompteurAffichage()
{
}
} // Fin de l'espace de nom utilitaire.
///////////////////////////////////////////////////////////////////////////////
/// @}
///////////////////////////////////////////////////////////////////////////////
| [
"paquet.alex@gmail.com"
] | paquet.alex@gmail.com |
daceec07068cc19817f18c100a83a1a38c9e1abb | b17a2b520a0ca029598e78df7d3edec37a7a6dcf | /fraction.h | b6aeaf125e37f46cbb0316dfedefb9082fdc49e0 | [] | no_license | hoc081098/102160045_16T1_BT02 | ead6e95709f20a8a17fcfae14d8063c5b4787ccf | c3b4cf7219bbd332960e2a73cee9d635094d06b7 | refs/heads/master | 2020-04-08T01:33:41.216383 | 2018-11-24T03:45:14 | 2018-11-24T03:45:14 | 154,682,803 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,708 | h | //
// Created by Peter Hoc on 10/18/2018.
//
#ifndef BAITAPOOP02_FRACTION_H
#define BAITAPOOP02_FRACTION_H
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <cmath>
using namespace std;
class Fraction {
private:
int numerator; // tu so
int denominator; // mau so
void initialize(int numerator, int denominator);
void increment();
void decrement();
static int gcd(int a, int b);
static int int_pow(int base, std::size_t exp);
public:
explicit Fraction(int numerator = 0, int denominator = 1);
explicit Fraction(const std::string &s); // take string parameter of the form of "numerator/denominator" or "numerator"
int get_numerator() const;
void set_numerator(int numerator);
int get_denominator() const;
void set_denominator(int denominator);
Fraction &operator+=(const Fraction &rhs);
Fraction &operator-=(const Fraction &rhs);
Fraction &operator*=(const Fraction &rhs);
Fraction &operator/=(const Fraction &rhs);
friend Fraction operator+(Fraction lhs, const Fraction &rhs);
friend Fraction operator+(Fraction lhs, const int &rhs);
friend Fraction operator-(Fraction lhs, const Fraction &rhs);
friend Fraction operator-(Fraction lhs, const int &rhs);
friend Fraction operator*(Fraction lhs, const Fraction &rhs);
friend Fraction operator*(Fraction lhs, const int &rhs);
friend Fraction operator/(Fraction lhs, const Fraction &rhs);
friend Fraction operator/(Fraction lhs, const int &rhs);
bool operator<(const Fraction &rhs) const;
bool operator>(const Fraction &rhs) const;
bool operator<=(const Fraction &rhs) const;
bool operator>=(const Fraction &rhs) const;
bool operator==(const Fraction &rhs) const;
bool operator!=(const Fraction &rhs) const;
Fraction operator-() const;
Fraction &operator++();
const Fraction operator++(int);
Fraction &operator--();
const Fraction operator--(int);
friend ostream &operator<<(ostream &os, const Fraction &fraction);
friend istream &operator>>(istream &is, Fraction &fraction);
static void *operator new(std::size_t sz);
static void *operator new[](std::size_t sz);
static void operator delete(void *ptr, std::size_t sz);
static void operator delete[](void *ptr, std::size_t sz);
int &operator[](std::size_t idx);
const int &operator[](std::size_t idx) const;
void operator()();
void operator,(const Fraction &other);
Fraction operator^(int n) const;
Fraction &operator^=(int n);
Fraction operator<<(std::size_t pos) const;
Fraction &operator<<=(std::size_t pos);
Fraction operator>>(std::size_t pos) const;
Fraction &operator>>=(std::size_t pos);
};
#endif //BAITAPOOP02_FRACTION_H
| [
"hoc081098@gmail.com"
] | hoc081098@gmail.com |
dba5e30ef929668fe18d39d55e3b98ee959c76c5 | 3448a43cf0635866b25e5d513dd60fb003f47e29 | /src/xrEngine/editor_environment_levels_manager.cpp | 1580e442264c863e2356729e9445664102856569 | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | permissive | xrLil-Batya/cordisproject | 49632acc5e68bea9847d001d82fb049703d223c2 | 24275a382fec62a4e58d11579bf497b894f220ba | refs/heads/master | 2023-03-19T01:17:25.170059 | 2020-11-17T14:22:06 | 2020-11-17T14:22:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,721 | cpp | ////////////////////////////////////////////////////////////////////////////
// Module : editor_environment_levels_manager.cpp
// Created : 28.12.2007
// Modified : 28.12.2007
// Author : Dmitriy Iassenev
// Description : editor environment levels manager class
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "editor_environment_levels_manager.hpp"
#include "editor_environment_weathers_manager.hpp"
#include "Include/editor/property_holder_base.hpp"
#include "Include/editor/ide.hpp"
#include "ide.hpp"
using editor::environment::levels::manager;
static pcstr s_default_weather_id = "[default]";
static pcstr s_level_section_id = "levels";
manager::manager(::editor::environment::weathers::manager* weathers) : m_weathers(*weathers), m_property_holder(0) {}
manager::~manager()
{
VERIFY(m_config_single);
CInifile::Destroy(m_config_single);
m_config_single = 0;
VERIFY(m_config_mp);
CInifile::Destroy(m_config_mp);
m_config_mp = 0;
if (!Device.editor())
return;
::ide().destroy(m_property_holder);
}
void manager::fill_levels(CInifile& config, pcstr section, pcstr category)
{
for (const auto &i : config.r_section(section).Data)
{
if (i.first.empty() == false)
continue;
VERIFY(config.section_exist(i.first.c_str()));
if (!config.line_exist(i.first.c_str(), "weathers"))
{
m_levels.insert(std::make_pair(i.first.c_str(), std::make_pair(category, s_default_weather_id)));
continue;
}
pcstr weather_id = config.r_string(i.first.c_str(), "weathers");
m_levels.insert(std::make_pair(i.first.c_str(), std::make_pair(category, weather_id)));
}
}
void manager::load()
{
string_path file_name;
// Обратите внимание: данные файлы будут перезаписаны при закрытии.
// Также: комментарии будут удалены и все секции отсортированы.
m_config_single = CInifile::Create(FS.update_path(file_name, "$game_config$", "game_maps_single.ltx"), false);
m_config_mp = CInifile::Create(FS.update_path(file_name, "$game_config$", "game_maps_mp.ltx" ), false);
VERIFY(m_levels.empty());
fill_levels(*m_config_single, "level_maps_single", "single");
fill_levels(*m_config_mp , "level_maps_mp" , "multiplayer");
}
pcstr const* manager::collection() { return (&*m_weathers.weather_ids().begin()); }
u32 manager::collection_size() { return (m_weathers.weather_ids().size()); }
void manager::fill()
{
VERIFY(!m_property_holder);
m_property_holder = ::ide().create_property_holder("levels");
typedef XRay::Editor::property_holder_base::string_collection_getter_type collection_getter_type;
collection_getter_type collection_getter;
collection_getter.bind(this, &manager::collection);
typedef XRay::Editor::property_holder_base::string_collection_size_getter_type collection_size_getter_type;
collection_size_getter_type collection_size_getter;
collection_size_getter.bind(this, &manager::collection_size);
for (auto &i : m_levels)
{
string_path description;
xr_strcpy(description, "weather for level ");
xr_strcat(description, i.first.c_str());
m_property_holder->add_property(i.first.c_str(), i.second.first, description, i.second.second.c_str(),
i.second.second, collection_getter, collection_size_getter,
XRay::Editor::property_holder_base::value_editor_combo_box, XRay::Editor::property_holder_base::cannot_enter_text);
}
::ide().environment_levels(m_property_holder);
}
| [
"phantom1020@yandex.ru"
] | phantom1020@yandex.ru |
d4921cbf1e19a5b205a9d34602a80b5262cb1c76 | 61e4bb86d6877890010cb3aa916fb60a51e38e0f | /ixbots/ixbots/IXStatsdClient.h | 7a75ca62e736b26b5c9694f4da902a116db8a6f4 | [
"BSD-3-Clause"
] | permissive | mattparks/IXWebSocket | 9914b6372576e89e77ac927eac1ecee0d8bada36 | dffa759f71f647f449d965a71dbe733c2deb0e3e | refs/heads/master | 2023-08-31T02:04:58.768138 | 2020-03-25T03:53:25 | 2020-03-25T03:53:25 | 232,356,048 | 0 | 0 | BSD-3-Clause | 2020-01-07T15:36:32 | 2020-01-07T15:36:31 | null | UTF-8 | C++ | false | false | 1,513 | h | /*
* IXStatsdClient.h
* Author: Benjamin Sergeant
* Copyright (c) 2020 Machine Zone, Inc. All rights reserved.
*/
#pragma once
#include <ixwebsocket/IXUdpSocket.h>
#include <string>
#include <thread>
#include <deque>
#include <mutex>
#include <atomic>
namespace ix
{
class StatsdClient
{
public:
StatsdClient(const std::string& host="127.0.0.1",
int port=8125,
const std::string& prefix = "");
~StatsdClient();
bool init(std::string& errMsg);
int inc(const std::string& key);
int dec(const std::string& key);
int count(const std::string& key, size_t value);
int gauge(const std::string& key, size_t value);
int timing(const std::string& key, size_t ms);
private:
/**
* (Low Level Api) manually send a message
* which might be composed of several lines.
*/
int send(const std::string& message);
/* (Low Level Api) manually send a message
* type = "c", "g" or "ms"
*/
int send(std::string key, size_t value, const std::string& type);
void cleanup(std::string& key);
UdpSocket _socket;
std::string _host;
int _port;
std::string _prefix;
std::atomic<bool> _stop;
std::thread _thread;
std::mutex _mutex; // for the queue
std::deque<std::string> _queue;
static const uint64_t _maxQueueSize;
};
} // end namespace ix
| [
"bsergean@gmail.com"
] | bsergean@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.