blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d9fdb30a5c20bd1238f1b470f996c83518c35467 | 2fdbf2ba994ba3ed64f0e2dc75cd2dfce4936583 | /spectre/commandlist/abstractcommand.cpp | c1e6f721bb923ca356f220fcd45539325da1045e | [] | no_license | TERRANZ/terragraph | 36219a4e512e15a925769512a6b60637d39830bf | ea8c36070f532ad0a4af08e46b19f4ee1b85f279 | refs/heads/master | 2020-05-25T10:31:26.994233 | 2011-01-29T21:23:04 | 2011-01-29T21:23:04 | 1,047,237 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 302 | cpp | abstractcommand.cpp | #include "abstractcommand.h"
AbstractCommand::AbstractCommand()
{
}
AbstractCommand::~AbstractCommand()
{
}
bool AbstractCommand::execute()
{
return true;
}
void AbstractCommand::undo()
{
}
string AbstractCommand::text() const
{
return "Нет действия.";
}
|
9d95a33a91ffa55a1b9bf030c5142c4bcda57f71 | cc4b7ca3978816bdd7a6de8a37af8b67caa019da | /include/CreateTree.hh | 0e1cd7bcdfc05ad5bbcefe8bc3937bfef5850737 | [] | no_license | marco-toli/TB_timing | 961853fd34b97584dfa5cf6d1d9bdb3f1f7cb42a | 6a08c862251533d7a443dd9525c351182804fa43 | refs/heads/master | 2021-06-03T22:11:59.088634 | 2018-04-05T13:30:16 | 2018-04-05T13:30:16 | 32,146,872 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,237 | hh | CreateTree.hh | #ifndef CreateTree_H
#define CreateTree_H 1
#include <iostream>
#include <vector>
#include "TString.h"
#include "TH2F.h"
#include "TH3F.h"
#include "TFile.h"
#include "TTree.h"
#include "TNtuple.h"
class CreateTree
{
private:
TTree* ftree ;
TString fname ;
public:
CreateTree (TString name);
~CreateTree () ;
TTree* GetTree() const { return ftree; };
TString GetName() const { return fname; };
void AddEnergyDeposit(int index, float deposit);
void AddScintillationPhoton(int index);
void AddCerenkovPhoton(int index);
int Fill();
bool Write(TFile *);
void Clear() ;
static CreateTree* Instance() { return fInstance; } ;
static CreateTree* fInstance;
int Event;
std::vector<float>* inputMomentum ; // Px Py Pz E
std::vector<float>* inputInitialPosition ; // x, y, z
std::vector<float> E_dep_f;
std::vector<float> E_dep_time_f;
std::vector<float> E_dep_r;
std::vector<float> E_dep_time_r;
std::vector<float> time_ext_scint;
std::vector<float> time_ext_cher;
std::vector<float> time_prod_scint;
std::vector<float> time_prod_cher;
std::vector<float> lambda_ext_scint;
std::vector<float> lambda_ext_cher;
std::vector<float> lambda_prod_scint;
std::vector<float> lambda_prod_cher;
std::vector<float> time_ext_scint_ref;
std::vector<float> time_ext_cher_ref;
std::vector<float> time_prod_scint_ref;
std::vector<float> time_prod_cher_ref;
float depositedEnergyTotal;
float depositedEnergyCore_f;
float depositedEnergyCore_r;
float depositedEnergyCapillary;
float depositedEnergyCladding;
float depositedEnergyWorld;
int tot_phot_sci;
int tot_phot_cer;
int tot_latGap_phot_sci;
int tot_latGap_phot_cer;
int tot_gap_phot_sci;
int tot_gap_phot_cer;
int tot_det_phot_sci;
int tot_det_phot_cer;
TH1F* h_phot_sci_lambda;
TH1F* h_phot_sci_E;
TH1F* h_phot_sci_time;
TH1F* h_phot_sci_angleAtProduction;
TH1F* h_phot_cer_lambda;
TH1F* h_phot_cer_E;
TH1F* h_phot_cer_time;
TH1F* h_phot_cer_angleAtProduction;
TH1F* h_phot_sci_latGap_lambda;
TH1F* h_phot_sci_latGap_E;
TH1F* h_phot_sci_latGap_time;
TH1F* h_phot_sci_latGap_angleAtProduction;
TH1F* h_phot_sci_latGap_angleWithSurfNormal;
TH1F* h_phot_cer_latGap_lambda;
TH1F* h_phot_cer_latGap_E;
TH1F* h_phot_cer_latGap_time;
TH1F* h_phot_cer_latGap_angleAtProduction;
TH1F* h_phot_cer_latGap_angleWithSurfNormal;
TH1F* h_phot_sci_gap_lambda;
TH1F* h_phot_sci_gap_E;
TH1F* h_phot_sci_gap_time;
TH1F* h_phot_sci_gap_angleAtProduction;
TH1F* h_phot_sci_gap_angleWithSurfNormal;
TH1F* h_phot_cer_gap_lambda;
TH1F* h_phot_cer_gap_E;
TH1F* h_phot_cer_gap_time;
TH1F* h_phot_cer_gap_angleAtProduction;
TH1F* h_phot_cer_gap_angleWithSurfNormal;
TH1F* h_phot_sci_det_lambda;
TH1F* h_phot_sci_det_E;
TH1F* h_phot_sci_det_time;
TH1F* h_phot_sci_det_angleAtProduction;
TH1F* h_phot_sci_det_angleWithSurfNormal;
TH1F* h_phot_cer_det_lambda;
TH1F* h_phot_cer_det_E;
TH1F* h_phot_cer_det_time;
TH1F* h_phot_cer_det_angleAtProduction;
TH1F* h_phot_cer_det_angleWithSurfNormal;
};
#endif
|
0feb9953b874afa369664d4ce20da62d0e47bb24 | a6d9abf3e5de8ce5f0347d10f1d14ce767a78e38 | /yuki/yuki_explicit_markup.h | 0fa6203a52d12c96cc053e140330eabdd321dc9c | [] | no_license | Tecyle/yuki | 59b5dfc61cb863421c4ff3a444f584110c5628cf | 0ec1c333e374c5e4c82cbd298775f0e7e3253b23 | refs/heads/master | 2021-01-22T18:37:43.701425 | 2017-11-04T03:38:43 | 2017-11-04T03:38:43 | 100,765,626 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,297 | h | yuki_explicit_markup.h | #pragma once
/*
显式标记块识别要点:
1. 以 ``..`` 打头,后面至少跟一个空格或者回车
2. 遇到相对于 ``..`` 标记非缩进的行认为显式标记块结束
以下结构均为显式标记块的具体实例:
1. 脚注。
2. 引用标注。
3. 超链接目标。
4. 替换目标定义。
5. 指令。
6. 注释。
识别的依据为:
1. 遇到第一个字符,如果为 ``[``,判断是否为脚注和引用标注,否则为注释。
2. 遇到第一个字符,如果为 ``_``,判断是否为超链接目标,否则为注释。
3. 遇到第一个字符,如果为 ``|``,判断是否为替换目标定义,否则为注释。
4. 遇到第一个字符,如果是换行符或者空行,直接为注释。
5. 如果第一行内遇到了 ``::``,识别为指令,否则为注释。
6. 其它情况全都为注释。
这个解析器只是一个中转路由,本身不会产生节点。
*/
class yuki_explicit_markup : public yuki_structure_parser
{
public:
yuki_explicit_markup(yuki_session* globalData) : yuki_structure_parser(globalData) {}
virtual ~yuki_explicit_markup() {}
public:
virtual bool parse(yuki_node* parentNode, const yuki_region* region) override;
virtual bool match() override;
virtual bool matchNoBackward();
}; |
d22d23e4b300015bc1d5d0bb6c637efd353cf207 | 0e782c46fd93da70ce3bfc6ea7ff763225b31afd | /inc/SpriteHandler.h | 0babf62ba785dcd3632b2c810dd7fb2a97201724 | [] | no_license | dupesnduds/Mp | 58940e12b42ce6169222ce863e6257f5d22726b9 | 4854ba197a8e4701d8fc3cdddbe45636225c555f | refs/heads/master | 2021-05-26T20:09:00.285677 | 2011-09-19T00:50:36 | 2011-09-19T00:50:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 986 | h | SpriteHandler.h | /*
============================================================================
Name : SpriteHandler.h
Author : Cleave Pokotea
Version :
Copyright : 2006 - 2007
Description : SpriteHandler.h - header file
============================================================================
*/
#ifndef SPRITEHANDLER_H
#define SPRITEHANDLER_H
#include <e32std.h>
#include "commondata.h"
#include "PngLoader.h"
/**
* Stores the sprite bitmaps and handles their references.
*/
class CSpriteHandler {
public:
static CSpriteHandler* NewL();
void ConstructL();
CSpriteHandler();
~CSpriteHandler();
/**
* Returns a reference to the specified sprite bitmap.
*/
inline CFbsBitmap* GetSprite(MpowerShared::TSpriteIds aSpriteId);
private:
/**
* Stores all sprite bitmaps.
*/
TFixedArray<CFbsBitmap*, MpowerShared::ENumSprites> iSprites;
};
inline CFbsBitmap* CSpriteHandler::GetSprite(MpowerShared::TSpriteIds aSpriteId)
{
return iSprites[aSpriteId];
}
#endif
|
65c2acb1201a49ea5f350bc1ee8ca1cd9d7f6d05 | 0bc0903fc444257398798e286d96b3ff3fca2901 | /src/common/protocol/Errors.h | faf98cc1612516c01c19f123cad643d63cb1e8b7 | [
"Apache-2.0"
] | permissive | smartdu/kafkaclient-cpp | 675bdc7f9ab6a0e7d98511364f85e4932762782b | 03d108808a50a13d7a26e63461a1ac27c5bc141c | refs/heads/master | 2020-05-18T00:14:17.062934 | 2019-05-15T03:43:33 | 2019-05-15T03:43:33 | 184,055,595 | 5 | 1 | Apache-2.0 | 2019-05-13T08:11:57 | 2019-04-29T11:07:51 | C++ | UTF-8 | C++ | false | false | 4,126 | h | Errors.h | #ifndef __KFK_ERRORS_H__
#define __KFK_ERRORS_H__
#pragma once
#include <map>
#include "Object.h"
#include "ApiException.h"
class Errors
: public Object
{
public:
static Errors* UNKNOWN_SERVER_ERROR;
static Errors* NONE;
static Errors* OFFSET_OUT_OF_RANGE;
static Errors* CORRUPT_MESSAGE;
static Errors* UNKNOWN_TOPIC_OR_PARTITION;
static Errors* INVALID_FETCH_SIZE;
static Errors* LEADER_NOT_AVAILABLE;
static Errors* NOT_LEADER_FOR_PARTITION;
static Errors* REQUEST_TIMED_OUT;
static Errors* BROKER_NOT_AVAILABLE;
static Errors* REPLICA_NOT_AVAILABLE;
static Errors* MESSAGE_TOO_LARGE;
static Errors* STALE_CONTROLLER_EPOCH;
static Errors* OFFSET_METADATA_TOO_LARGE;
static Errors* NETWORK_EXCEPTION;
static Errors* COORDINATOR_LOAD_IN_PROGRESS;
static Errors* COORDINATOR_NOT_AVAILABLE;
static Errors* NOT_COORDINATOR;
static Errors* INVALID_TOPIC_EXCEPTION;
static Errors* RECORD_LIST_TOO_LARGE;
static Errors* NOT_ENOUGH_REPLICAS;
static Errors* NOT_ENOUGH_REPLICAS_AFTER_APPEND;
static Errors* INVALID_REQUIRED_ACKS;
static Errors* ILLEGAL_GENERATION;
static Errors* INCONSISTENT_GROUP_PROTOCOL;
static Errors* INVALID_GROUP_ID;
static Errors* UNKNOWN_MEMBER_ID;
static Errors* INVALID_SESSION_TIMEOUT;
static Errors* REBALANCE_IN_PROGRESS;
static Errors* INVALID_COMMIT_OFFSET_SIZE;
static Errors* TOPIC_AUTHORIZATION_FAILED;
static Errors* GROUP_AUTHORIZATION_FAILED;
static Errors* CLUSTER_AUTHORIZATION_FAILED;
static Errors* INVALID_TIMESTAMP;
static Errors* UNSUPPORTED_SASL_MECHANISM;
static Errors* ILLEGAL_SASL_STATE;
static Errors* UNSUPPORTED_VERSION;
static Errors* TOPIC_ALREADY_EXISTS;
static Errors* INVALID_PARTITIONS;
static Errors* INVALID_REPLICATION_FACTOR;
static Errors* INVALID_REPLICA_ASSIGNMENT;
static Errors* INVALID_CONFIG;
static Errors* NOT_CONTROLLER;
static Errors* INVALID_REQUEST;
static Errors* UNSUPPORTED_FOR_MESSAGE_FORMAT;
static Errors* POLICY_VIOLATION;
static Errors* OUT_OF_ORDER_SEQUENCE_NUMBER;
static Errors* DUPLICATE_SEQUENCE_NUMBER;
static Errors* INVALID_PRODUCER_EPOCH;
static Errors* INVALID_TXN_STATE;
static Errors* INVALID_PRODUCER_ID_MAPPING;
static Errors* INVALID_TRANSACTION_TIMEOUT;
static Errors* CONCURRENT_TRANSACTIONS;
static Errors* TRANSACTION_COORDINATOR_FENCED;
static Errors* TRANSACTIONAL_ID_AUTHORIZATION_FAILED;
static Errors* SECURITY_DISABLED;
static Errors* OPERATION_NOT_ATTEMPTED;
static Errors* KAFKA_STORAGE_ERROR;
static Errors* LOG_DIR_NOT_FOUND;
static Errors* SASL_AUTHENTICATION_FAILED;
static Errors* UNKNOWN_PRODUCER_ID;
static Errors* REASSIGNMENT_IN_PROGRESS;
static Errors* DELEGATION_TOKEN_AUTH_DISABLED;
static Errors* DELEGATION_TOKEN_NOT_FOUND;
static Errors* DELEGATION_TOKEN_OWNER_MISMATCH;
static Errors* DELEGATION_TOKEN_REQUEST_NOT_ALLOWED;
static Errors* DELEGATION_TOKEN_AUTHORIZATION_FAILED;
static Errors* DELEGATION_TOKEN_EXPIRED;
static Errors* INVALID_PRINCIPAL_TYPE;
static Errors* NON_EMPTY_GROUP;
static Errors* GROUP_ID_NOT_FOUND;
static Errors* FETCH_SESSION_ID_NOT_FOUND;
static Errors* INVALID_FETCH_SESSION_EPOCH;
static Errors* LISTENER_NOT_FOUND;
static Errors* TOPIC_DELETION_DISABLED;
static Errors* FENCED_LEADER_EPOCH;
static Errors* UNKNOWN_LEADER_EPOCH;
static Errors* UNSUPPORTED_COMPRESSION_TYPE;
static Errors* STALE_BROKER_EPOCH;
static Errors* OFFSET_NOT_AVAILABLE;
static Errors* MEMBER_ID_REQUIRED;
static Errors* PREFERRED_LEADER_NOT_AVAILABLE;
static Errors* GROUP_MAX_SIZE_REACHED;
Errors(int code, const char *defaultExceptionString, ApiException *exception = NULL);
virtual ~Errors();
static Errors* forCode(short code);
short code();
ApiException* exception()
{
return exception_;
}
ApiException* exception(const char *message)
{
if (message == NULL)
return exception_;
exception_->message(message);
return exception_;
}
static Errors* forException(ApiException *t);
static void destroy();
private:
short code_;
ApiException *exception_;
};
#endif // !__KFK_ERRORS_H__
|
dcb4299319c54f6f69317d80240dfdacbd1d6672 | 4a5f17a5ecf1ffdb326634dbcc0b6bcacefcda3f | /RegexSplitter.h | 30785f8f7a8851f4a05e66ad55846a6f9ee347f1 | [] | no_license | F-Bergemann/RegexSplitter | e2a39994dabff10df1c5b5b02054f885a346a9fc | 613c3948c74f451b98e5e19bfabfd20e5bbdf7af | refs/heads/master | 2023-03-01T22:20:59.881793 | 2021-02-04T15:02:26 | 2021-02-04T15:02:26 | 330,185,286 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,935 | h | RegexSplitter.h | /*
* RegexSplitter.h
*
* Created on: Jan 9, 2020
* Author: frank
*/
#ifndef REGEX_SPLITTER_H_
#define REGEX_SPLITTER_H_
#include <string>
#include <vector>
#include <map>
#include <iostream>
#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;
// for testing parser only, without AST construction
#undef PARSER_ONLY
namespace RegexSplitter
{
class MyString;
}
std::ostream & operator<<(
std::ostream & os,
RegexSplitter::MyString const & val);
namespace RegexSplitter
{
class MyString
{
public:
typedef enum
{
UNDEFINED_c = 0,
BREAKABLE_c = 1,
UNBREAKABLE_c = 2,
} Type;
MyString()
: fStr(),
fType(UNDEFINED_c)
{ }
MyString (
std::string const & str,
Type const type)
: fStr(str),
fType(type)
{ }
~MyString()
{ }
// other standard functions: compiler generated
std::string const &
GetStr(void) const
{
return fStr;
}
Type const &
GetType(void) const
{
return fType;
}
static std::string const
TypeStr(Type const & type);
private:
std::string fStr;
Type fType;
static std::map<Type, std::string> const sType2String;
};
class ASTNode
{
public:
typedef enum
{
COLLECTION_c = 1,
BREAKABLE_c = 2,
UNBREAKABLE_c = 3,
TEST_c = 4,
} Type;
// TODO: use Type 1st and vargs next for c'tors? And dispatch to value-templates? to have a unique function structure
// COLLECTION_c
ASTNode(
ASTNode const * first,
std::vector<ASTNode *> & others,
Type const type);
// BREAKABLE_c
ASTNode(
std::string & data,
Type const type);
// UNBREAKABLE_c
template < class FUSION >
ASTNode(
FUSION & fusion,
Type const type);
#if 0
// TEST_c, used for debugging
ASTNode(
char const,
Type const type);
#endif
ASTNode(ASTNode const &rhs) = delete;
ASTNode & operator=(ASTNode const &rhs) = delete;
void print(
int indent = 0);
static std::string const
TypeStr(
Type const & type);
std::string
GetString(void) const;
MyString::Type
TypeToDataType(
Type type);
virtual ~ASTNode();
private:
// TODO: don't use blob -> sub-class
MyString fString;
std::vector<MyString> fStrings;
Type fType;
static std::map<Type, std::string> const sType2String;
};
using ASTNodePtr = ASTNode*;
#ifdef PARSER_ONLY
class Grammar : public qi::grammar<std::string::const_iterator>
#else
class Grammar : public qi::grammar<std::string::const_iterator, ASTNode*>
#endif
{
public:
using Iterator = std::string::const_iterator;
Grammar();
#ifdef PARSER_ONLY
qi::rule<Iterator>
#else
qi::rule<Iterator, ASTNode*>
#endif
tok_RE,
tok_TL_elements, tok_TL_element, tok_TL_group, tok_TL_nongroup,
tok_nested_elements, tok_nested_element, tok_nested_group, tok_nested_nongroup,
tok_set;
// no AST nodes required for these
qi::rule<Iterator, std::string()> tok_positive_set, tok_negative_set, tok_set_items, tok_set_item, tok_range, tok_char;
};
} // RegexSplitter
#endif /* REGEX_SPLITTER_H_ */
|
b42f1fcb1902654681b5f0e5179bcb7bd7e708a9 | 50618ddcbf1357623c11c442dac7247163eada5e | /SQF/Alternative Files/database_loot/dayz_code/Configs/CfgRPG/CfgEXP.hpp | e4d7c4c92c275c72a885c61f7a9aa2822f129d0d | [] | no_license | DevVault/DayZUnleashed | 24c574a28a1c543c5d696012077ebc33034032ed | ae7753e36ac9c90e9fc235582478827ee83a3d73 | refs/heads/master | 2021-05-30T00:35:14.875976 | 2015-10-31T02:59:21 | 2015-10-31T02:59:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,095 | hpp | CfgEXP.hpp | //[player,"Generic_Survival"] call DZU_fnc_giveEXP;
class CfgEXP{
class Default {
Name=""; //value of %2
Description="";
Image="";
Message="You were awarded %1 %2 experience.";
Experience=1; //value of %1
MiniumGain=1;
};
class Generic: Default{
Name="Generic";
Experience=10;
};
class Generic_limited: Generic{
MiniumGain=0;
};
class Refuel_5l: Generic{
MiniumGain=0;
};
class Refuel_Object_5l: Refuel_5l{
Experience=5;
};
class Refuel_20l: Generic{
Experience=40;
MiniumGain=0;
};
class Refuel_Object_20l: Refuel_20l{
Experience=20;
};
class Generic_Engineering: Generic{
Name="Engineering";
};
class Generic_Hunting: Generic{
Name="Wilderness";
};
class Generic_Medical: Generic{
Name="Medical";
};
class Generic_Combat: Generic{
Name="Combat";
};
class Generic_Survival: Generic{
Name="Survivalist";
};
class Build: Generic_Engineering{
Experience=25;
MiniumGain=0;
};
class Build_med: Build{
Experience=50;
};
class Build_large: Build{
Experience=100;
};
class Repair: Generic_Engineering{};
class Craft: Generic_Engineering{};
class Boil: Generic_Hunting{};
class Cook: Generic_Hunting{};
class Gut: Generic_Hunting{};
class ChopWood: Generic_Hunting{};
class Trap: Generic_Hunting{};
class Blood_Self: Generic_Medical{};
class Blood_Other: Generic_Medical{
Experience=20;
};
class Blood_Bag: Generic_Medical{ //Blood Bag crafting exp
Experience=30;
};
class Bandage_Self: Generic_Medical{};
//class Bandage_Other: Generic_Medical{};
class Combat_Player: Generic_Combat{};
class Combat_NPC: Generic_Combat{};
class Combat_Zed: Generic_Combat{};
class Find_Loot: Generic_Survival{};
}; |
e2916eb8337644910f4ea1d22c4dd39188ef4bbe | cbd7f17ec8e983e3f302aa3c9a4c5bd676789bef | /code/steps/source/model/sg_models/exciter_model/CSEET2_test.cpp | 722aea0b5479caff24bb7c7dbe7b8e336444420f | [
"MIT"
] | permissive | yuanzy97/steps | 477bce28a11c8e5890f27bb56490f3b80b343048 | 139193a9c84ad15e342f632ac29afac909802b78 | refs/heads/master | 2023-04-29T10:00:13.987075 | 2022-04-13T13:08:17 | 2022-04-13T13:08:17 | 256,682,978 | 0 | 0 | MIT | 2020-04-18T06:13:20 | 2020-04-18T06:13:20 | null | UTF-8 | C++ | false | false | 6,923 | cpp | CSEET2_test.cpp | #include "header/basic/test_macro.h"
#include "header/model/sg_models/exciter_model/CSEET2_test.h"
#include "header/basic/utility.h"
#include "header/steps_namespace.h"
#ifdef ENABLE_STEPS_TEST
using namespace std;
CSEET2_TEST::CSEET2_TEST() : EXCITER_MODEL_TEST()
{
TEST_ADD(CSEET2_TEST::test_get_model_name);
TEST_ADD(CSEET2_TEST::test_set_get_parameters);
TEST_ADD(CSEET2_TEST::test_initialize);
TEST_ADD(CSEET2_TEST::test_step_response_SEPARATE_EXCIATION_and_stabilizer_AT_VOLTAGE_ERROR);
TEST_ADD(CSEET2_TEST::test_step_response_SEPARATE_EXCIATION_and_stabilizer_AT_REGULATOR);
TEST_ADD(CSEET2_TEST::test_step_response_SELF_EXCIATION_and_stabilizer_AT_VOLTAGE_ERROR);
TEST_ADD(CSEET2_TEST::test_step_response_SELF_EXCIATION_and_stabilizer_AT_REGULATOR);
}
void CSEET2_TEST::setup()
{
EXCITER_MODEL_TEST::setup();
GENERATOR* genptr = get_test_generator();
CSEET2 model(default_toolkit);
DYNAMIC_MODEL_DATABASE& dmdb = default_toolkit.get_dynamic_model_database();
model.set_device_id(genptr->get_device_id());
model.set_excitation_source(SELF_EXCITATION);
model.set_stabilizer_slot(AT_VOLTAGE_ERROR);
model.set_tuner_type(SERIAL_TUNER);
model.set_TR_in_s(0.02);
model.set_serial_tuner_KV(true);
model.set_serial_tuner_K(25);
model.set_serial_tuner_T1_in_s(1.0);
model.set_serial_tuner_T2_in_s(10.0);
model.set_serial_tuner_VA1max_in_pu(5.0);
model.set_serial_tuner_VA1min_in_pu(-5.0);
model.set_serial_tuner_T3_in_s(0.3);
model.set_serial_tuner_T4_in_s(0.03);
model.set_KA(1.0);
model.set_TA_in_s(0.03);
model.set_VAmax_in_pu(10.0);
model.set_VAmin_in_pu(-10.0);
model.set_KF(1.0);
model.set_TF_in_s(1.0);
model.set_VRmax_in_pu(20.0);
model.set_VRmin_in_pu(-15.0);
model.set_KC(0.1);
dmdb.add_model(&model);
}
void CSEET2_TEST::tear_down()
{
EXCITER_MODEL_TEST::tear_down();
DYNAMIC_MODEL_DATABASE& dmdb = default_toolkit.get_dynamic_model_database();
dmdb.remove_the_last_model();
}
void CSEET2_TEST::test_get_model_name()
{
show_test_information_for_function_of_class(__FUNCTION__,"CSEET2_TEST");
EXCITER_MODEL* model = get_test_exciter_model();
TEST_ASSERT(model->get_model_name()=="CSEET2");
}
void CSEET2_TEST::test_set_get_parameters()
{
show_test_information_for_function_of_class(__FUNCTION__,"CSEET2_TEST");
CSEET2* model = (CSEET2*) get_test_exciter_model();
TEST_ASSERT(model->get_excitation_source()==SELF_EXCITATION);
TEST_ASSERT(model->get_stabilizer_slot()==AT_VOLTAGE_ERROR);
TEST_ASSERT(model->get_tuner_type()==SERIAL_TUNER);
TEST_ASSERT(fabs(model->get_TR_in_s()-0.02)<FLOAT_EPSILON);
TEST_ASSERT(model->get_serial_tuner_KV()==true);
TEST_ASSERT(fabs(model->get_serial_tuner_K()-25)<FLOAT_EPSILON);
TEST_ASSERT(fabs(model->get_serial_tuner_T1_in_s()-1.0)<FLOAT_EPSILON);
TEST_ASSERT(fabs(model->get_serial_tuner_T2_in_s()-10.0)<FLOAT_EPSILON);
TEST_ASSERT(fabs(model->get_serial_tuner_VA1max_in_pu()-5.0)<FLOAT_EPSILON);
TEST_ASSERT(fabs(model->get_serial_tuner_VA1min_in_pu()-(-5.0))<FLOAT_EPSILON);
TEST_ASSERT(fabs(model->get_serial_tuner_T3_in_s()-0.3)<FLOAT_EPSILON);
TEST_ASSERT(fabs(model->get_serial_tuner_T4_in_s()-0.03)<FLOAT_EPSILON);
TEST_ASSERT(fabs(model->get_KA()-1.0)<FLOAT_EPSILON);
TEST_ASSERT(fabs(model->get_TA_in_s()-0.03)<FLOAT_EPSILON);
TEST_ASSERT(fabs(model->get_VAmax_in_pu()-10.0)<FLOAT_EPSILON);
TEST_ASSERT(fabs(model->get_VAmin_in_pu()-(-10.0))<FLOAT_EPSILON);
TEST_ASSERT(fabs(model->get_KF()-1.0)<FLOAT_EPSILON);
TEST_ASSERT(fabs(model->get_TF_in_s()-1.0)<FLOAT_EPSILON);
TEST_ASSERT(fabs(model->get_VRmax_in_pu()-20.0)<FLOAT_EPSILON);
TEST_ASSERT(fabs(model->get_VRmin_in_pu()-(-15.0))<FLOAT_EPSILON);
TEST_ASSERT(fabs(model->get_KC()-0.1)<FLOAT_EPSILON);
}
void CSEET2_TEST::test_initialize()
{
show_test_information_for_function_of_class(__FUNCTION__,"CSEET2_TEST");
GENERATOR* genptr = get_test_generator();
SYNC_GENERATOR_MODEL* genmodel = genptr->get_sync_generator_model();
genmodel->initialize();
CSEET2* model = (CSEET2*) get_test_exciter_model();
double Efd0 = genmodel->get_initial_excitation_voltage_in_pu();
double Ecomp = model->get_compensated_voltage_in_pu();
double Ifd = genmodel->get_field_current_in_pu_based_on_mbase();
double Kc = model->get_KC();
model->initialize();
TEST_ASSERT(fabs(model->get_excitation_voltage_in_pu()-Efd0)<FLOAT_EPSILON);
double Vref;
if(model->get_serial_tuner_KV()==true)
{
double Vr = Efd0+Kc*Ifd;
Vr = Vr/model->get_KA();
Vr = Vr/model->get_serial_tuner_K();
Vref = Ecomp+Vr;
}
else
Vref = Ecomp;
TEST_ASSERT(fabs(model->get_voltage_reference_in_pu()-Vref)<FLOAT_EPSILON);
TEST_ASSERT(fabs(model->get_stabilizing_signal_in_pu()-0.0)<FLOAT_EPSILON);
}
void CSEET2_TEST::test_step_response_SEPARATE_EXCIATION_and_stabilizer_AT_VOLTAGE_ERROR()
{
show_test_information_for_function_of_class(__FUNCTION__,"CSEET2_TEST");
CSEET2* model = (CSEET2*) get_test_exciter_model();
model->set_excitation_source(SEPARATE_EXCITATION);
model->set_stabilizer_slot(AT_VOLTAGE_ERROR);
default_toolkit.open_log_file("test_log/step_response_of_CSEET2_model_1.txt");
run_step_response_of_exciter_model();
default_toolkit.close_log_file();
}
void CSEET2_TEST::test_step_response_SEPARATE_EXCIATION_and_stabilizer_AT_REGULATOR()
{
show_test_information_for_function_of_class(__FUNCTION__,"CSEET2_TEST");
CSEET2* model = (CSEET2*) get_test_exciter_model();
model->set_excitation_source(SEPARATE_EXCITATION);
model->set_stabilizer_slot(AT_REGULATOR);
default_toolkit.open_log_file("test_log/step_response_of_CSEET2_model_2.txt");
run_step_response_of_exciter_model();
default_toolkit.close_log_file();
}
void CSEET2_TEST::test_step_response_SELF_EXCIATION_and_stabilizer_AT_VOLTAGE_ERROR()
{
show_test_information_for_function_of_class(__FUNCTION__,"CSEET2_TEST");
CSEET2* model = (CSEET2*) get_test_exciter_model();
model->set_excitation_source(SELF_EXCITATION);
model->set_stabilizer_slot(AT_VOLTAGE_ERROR);
default_toolkit.open_log_file("test_log/step_response_of_CSEET2_model_3.txt");
run_step_response_of_exciter_model();
default_toolkit.close_log_file();
}
void CSEET2_TEST::test_step_response_SELF_EXCIATION_and_stabilizer_AT_REGULATOR()
{
show_test_information_for_function_of_class(__FUNCTION__,"CSEET2_TEST");
CSEET2* model = (CSEET2*) get_test_exciter_model();
model->set_excitation_source(SELF_EXCITATION);
model->set_stabilizer_slot(AT_REGULATOR);
default_toolkit.open_log_file("test_log/step_response_of_CSEET2_model_4.txt");
run_step_response_of_exciter_model();
default_toolkit.close_log_file();
}
#endif
|
4a912e6069e47afa48598740335cb6c0c3661470 | 8ba095c9000f17ebd673388f02782e6a1ab53261 | /final project 2021/ScheduleMatch.cpp | 3093339a6f41482333068b4bc48e4da2fd673893 | [] | no_license | saadzafar649/cricbuzz | aea37f2538569299dc154d8fa29368f369ecec6f | 0b35cb120c370c8b6a58a29ca0bbbbfcab5cbbdc | refs/heads/main | 2023-07-27T09:21:01.734287 | 2021-09-13T17:56:03 | 2021-09-13T17:56:03 | 406,071,987 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27 | cpp | ScheduleMatch.cpp | #include "ScheduleMatch.h"
|
f63bf76adee2fd36f7516dd2acbacbf55bfa2b2d | 7cfca3ef1787866b534d23135b2c35112af4b41a | /Game/PlayerBullet.h | 2822ae8ed396fe7115bd2cb90bd22d3e3d5deeb3 | [] | no_license | LaraCTimm/ShapeInvaders | 1bc42a7345f91043719e8ac706e484b5d82e51dc | 530c0a9aa7e7ccdea2d15ccc787d8be2ea09cafc | refs/heads/master | 2021-07-12T06:27:55.503084 | 2017-10-17T09:31:35 | 2017-10-17T09:31:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 408 | h | PlayerBullet.h | #ifndef PLAYER_BULLET_H
#define PLAYER_BULLET_H
#include "GameObject.h"
#include "Game.h"
#include "Player.h"
/**
* @class PlayerBullet
* @brief Represents the bullet belonging to the player
*
* Inherited from the GameObject Class.
*/
class PlayerBullet : public GameObject
{
public:
PlayerBullet(float xCoord, float yCoord, vector<float> pathVector, float angle);
private:
};
#endif |
65a0123292c7f9ffdcf4c04ac9c75c6e15975143 | d153a62031abc47079f3bd60890d1bde11148d31 | /src/CubeAsset.cc | c6fdcd8419512f27632bc352127a03302045e503 | [
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | markgosling/3D_Platformer | 5d7186ff29e0dab08950fffa2de9ec46547d606f | 8a56960fc1c562c80a8b5ec221b776cff812020b | refs/heads/master | 2021-01-21T13:43:59.318809 | 2016-04-24T23:47:16 | 2016-04-24T23:47:16 | 51,597,208 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,044 | cc | CubeAsset.cc | #include "CubeAsset.h"
/**
* @file CubeAsset.cc
* @version 1.1
*
* @section Description
*
* CubeAsset extends GameAsset with variables and methods which
* are used to draw a cube object on screen. It also stores the
* bounding box for the cube, sets the asset type and passes the
* vertices to the GPU.
*/
/**
* Constructor which sets the position of each of the vertices required to create the cube,
* stores them in a buffer then transfers them to the GPU. It also stores the type of asset
* and the size of the bounding box.
*
* @param x_position - float - The center X position of the asset.
* @param y_position - float - The center Y position of the asset.
* @param z_position - float - The center Z position of the asset.
* @param scale - float - The amount to scale the asset by.
* @param x_rotation - float - The starting rotation amount around the X axis.
* @param y_rotation - float - The starting rotation amount around the Y axis.
* @param z_rotation - float - The starting rotation amount around the Z axis.
*/
CubeAsset::CubeAsset(float x_position, float y_position, float z_position, float scale,
float x_rotation, float y_rotation, float z_rotation) : GameAsset(x_position, y_position, z_position, scale,
x_rotation, y_rotation, z_rotation) {
//Model coordinates with origin at centre.
GLfloat vertex_buffer_data [] {
//Position of vertices for the front of the cube.
-0.5, -0.5, 0.5, //0
-0.5, 0.5, 0.5, //1
0.5, -0.5, 0.5, //2
0.5, 0.5, 0.5, //3
//Position of vertices for the back of the cube.
-0.5, -0.5, -0.5, //4
-0.5, 0.5, -0.5, //5
0.5, -0.5, -0.5, //6
0.5, 0.5, -0.5, //7
};
element_buffer_length = 36;
GLuint element_buffer [] {
//Put cube front vertices in element buffer.
0, 1, 2, //Triangle 1.
1, 3, 2, //Triangle 2.
//Put cube back vertices in element buffer.
4, 5, 6,
5, 7, 6,
//Put cube top vertices in element buffer.
1, 3, 5,
3, 7, 5,
//Put cube bottom vertices in element buffer.
0, 2, 4,
2, 6, 4,
//Put cube left side vertices in element buffer.
1, 0, 5,
0, 4, 5,
//Put cube right side vertices in element buffer.
3, 2, 7,
2, 7, 6
};
//Transfer buffers to the GPU.
//Create buffer.
glGenBuffers(1, &vertex_buffer_token);
//Immediately bind the buffers and transfer the data.
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_token);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 24, vertex_buffer_data, GL_STATIC_DRAW);
glGenBuffers(1, &element_buffer_token);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, element_buffer_token);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * element_buffer_length, element_buffer, GL_STATIC_DRAW);
///Set the asset type. This is required to determine the object type
//when deciding which shader program to use to colour the object.
assetType = CUBE;
}
/**
* Unused destructor.
*/
CubeAsset::~CubeAsset() {
}
|
b976732ba74ccf55e25d35e0202887ce073fa9b8 | 0141361f7c4d276f471ac278580479fa15bc4296 | /Ordered Map/fallingSquares.cpp | bd01a8eb012709823a5bfefac69d9261434815c2 | [] | no_license | tr1503/LeetCode | a7f2f1801c9424aa96d3cde497290ac1f7992f58 | 6d361cad2821248350f1d8432fdfef86895ca281 | refs/heads/master | 2021-06-24T19:03:08.681432 | 2020-10-09T23:53:22 | 2020-10-09T23:53:22 | 146,689,171 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,311 | cpp | fallingSquares.cpp | // Use C++'s ordered map's method upper_bound to keep tracing the max value and put the max value to result vector
// time is O(nlogn), space is O(n)
class Solution {
public:
vector<int> fallingSquares(vector<vector<int>>& positions) {
vector<int> res;
map<pair<int, int>, int> m;
int curMax = 0;
for (auto &pos : positions) {
vector<vector<int>> t;
int len = pos[1];
int start = pos[0];
int end = start + len;
int h = 0;
auto iter = m.upper_bound({start, start});
if (iter != m.begin() && (--iter)->first.second <= start)
++iter;
while (iter != m.end() && iter->first.first < end) {
if (start > iter->first.first)
t.push_back({iter->first.first, start, iter->second});
if (end < iter->first.second)
t.push_back({end, iter->first.second, iter->second});
h = max(h, iter->second);
iter = m.erase(iter);
}
m[{start, end}] = h + len;
for (auto &a : t) {
m[{a[0], a[1]}] = a[2];
}
curMax = max(curMax, h + len);
res.push_back(curMax);
}
return res;
}
};
|
e48cff4ad3d12ce3a757878bb0d592834dfb75d1 | 73912a45e71170a07ed20e229faf6e1f48ab1a04 | /DirectUI/provider.h | c0d9ac974d263cfba9df7d9e1be4678a6b160730 | [
"MIT"
] | permissive | yang123vc/DirectUI-2 | 623122efdd317c5a7cda24b99c8d3cebc0381219 | 0f8fb02646468c6f65ef3aa6c75cfe4b5b9d6399 | refs/heads/master | 2020-04-18T05:48:52.733179 | 2018-10-06T03:08:06 | 2018-10-06T03:08:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 640 | h | provider.h | #pragma once
namespace DirectUI
{
class UILIB_API XResourceProvider
{
public:
XResourceProvider();
XResourceProvider( const XResourceProvider& );
XResourceProvider& operator=( const XResourceProvider& );
static long WINAPI Create(XResourceProvider**pOut);
static long WINAPI Create(HINSTANCE, UCString, UCString, UCString, XResourceProvider**pOut );
long Initialize(HINSTANCE h, UCString s1, UCString s2, UCString s3);
//1
virtual long CreateDUICP(HWNDElement*, HWND, HWND, Element**, class DUIXmlParser**);
//2
virtual long CreateParserCP(class DUIXmlParser**pOut);
//3
virtual void DestroyCP();
};
} |
5d5bedf43a5d51738a7f71b3248da3fc0b7d1489 | 1835bc57373845971613cda3f66b88813c139fc2 | /examples/THINSPIN/tracker.cc | 646664fe4d55d79b68f683f2ac45e3d230d611ac | [] | no_license | jtalman/ual-sandbox_SL7.4Plus | 4cf8037a0b289d9a29b9e8918ca15e40d4eca8a4 | decdce8e9e42b51be4ced1174811bcb14427353a | refs/heads/master | 2020-03-09T19:36:51.464651 | 2019-11-12T12:57:52 | 2019-11-12T12:57:52 | 128,962,122 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,681 | cc | tracker.cc | #include <iostream>
#include <fstream>
#include <iomanip>
#include <stdio.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include "UAL/APDF/APDF_Builder.hh"
#include "PAC/Beam/Position.hh"
#include "SMF/PacSmf.h"
#include "PAC/Beam/Bunch.hh"
#include "Main/Teapot.h"
#include "UAL/UI/Shell.hh"
#include "PAC/Beam/Particle.hh"
#include "PAC/Beam/Spin.hh"
#include "UAL/SMF/AcceleratorNodeFinder.hh"
#include "TEAPOT/Integrator/DipoleData.hh"
#include "TEAPOT/Integrator/MagnetData.hh"
#include "timer.h"
#include "positionPrinter.hh"
#include "threeVector.hh"
#include "fourVector.hh"
#include "fourTensor.hh"
#include "lorentzTransformForTracker.cc"
#include "globalBlock.cc"
using namespace UAL;
int main(int argc,char * argv[]){
// Input parameters
// ************************************************************************
std::cout << "\nEcho input parameters." << std::endl;
// ************************************************************************
if(argc < 3) {
std::cout << "Usage : ./tracker <InputFile, e.g. muon0.13_R5m-mod> <BendSplit, e.g. 1> <QuadSplit, e.g. 4>" << std::endl;
std::cout << "All units are M.K.S. except ee which is in GeV" << std::endl;
exit(1);
}
std::string variantName = argv[1]; // std::string sxfInputFile = "../sxf/muon0.13_R5m.sxf";
int bendsplit = atof(argv[2]); // std::integer bendslit = 1;
int quadsplit = atof(argv[3]); // std::integer quadsplit = 4;
UAL::Shell shell;
// ************************************************************************
std::cout << "\nDefine the space of Taylor maps." << std::endl;
// ************************************************************************
shell.setMapAttributes(UAL::Args() << UAL::Arg("order", 5));
// ************************************************************************
std::cout << "\nBuild lattice." << std::endl;
// ************************************************************************
std::string sxfFile = "./sxf/";
sxfFile += variantName;
sxfFile += ".sxf";
shell.readSXF(UAL::Args() << UAL::Arg("file", sxfFile.c_str()));
// ************************************************************************
std::cout << "\nAdd split ." << std::endl;
// ************************************************************************
shell.addSplit(UAL::Args() << UAL::Arg("lattice", "ring") << UAL::Arg("types", "Sbend")
<< UAL::Arg("ir", bendsplit));
shell.addSplit(UAL::Args() << UAL::Arg("lattice", "ring") << UAL::Arg("types", "Quadrupole")
<< UAL::Arg("ir", quadsplit));
// ************************************************************************
std::cout << "Select lattice." << std::endl;
// ************************************************************************
shell.use(UAL::Args() << UAL::Arg("lattice", "ring"));
// ************************************************************************
std::cout << "\nWrite SXF file ." << std::endl;
// ************************************************************************
std::string outputFile = "./out/cpp/";
outputFile += variantName;
outputFile += ".sxf";
shell.writeSXF(UAL::Args() << UAL::Arg("file", outputFile.c_str()));
// ************************************************************************
std::cout << "\nDefine beam parameters." << std::endl;
// ************************************************************************
double mass = 0.10578404; // muon rest mass
m0 = 0.10578404;
p0 = .1;
e0 = sqrt(m0*m0 + p0*p0);
c0 = 1.60193E-19;
shell.setBeamAttributes(UAL::Args() << UAL::Arg("mass", m0));
shell.setBeamAttributes(UAL::Args() << UAL::Arg("energy", e0) << UAL::Arg("charge", c0));
PAC::BeamAttributes& ba = shell.getBeamAttributes();
ba.setG(0.0011659230); // adds muon G factor
G0 = ba.getG();
std::cout << "m0 = " << m0 << "\n";
std::cout << "p0 = " << p0 << "\n";
std::cout << "e0 = " << e0 << "\n";
std::cout << "c0 = " << c0 << "\n";
std::cout << "G0 = " << G0 << "\n";
// ************************************************************************
std::cout << "\nLinear analysis." << std::endl;
// ************************************************************************
// Make linear matrix
std::string mapFile = "./out/cpp/";
mapFile += variantName;
mapFile += ".map1";
std::cout << " matrix" << std::endl;
shell.map(UAL::Args() << UAL::Arg("order", 1) << UAL::Arg("print", mapFile.c_str()));
// Calculate twiss
std::string twissFile = "./out/cpp/";
twissFile += variantName;
twissFile += ".twiss";
std::cout << " twiss (ring )" << std::endl;
shell.twiss(UAL::Args() << UAL::Arg("print", twissFile.c_str()));
std::cout << " calculate suml" << std::endl;
shell.analysis(UAL::Args());
// ************************************************************************
std::cout << "\nAlgorithm Part. " << std::endl;
// ************************************************************************
//std::string apdfFile = argv[1];
std::string apdfFile = "./apdf/thinspin.apdf";
UAL::APDF_Builder apBuilder;
apBuilder.setBeamAttributes(ba);
UAL::AcceleratorPropagator* ap = apBuilder.parse(apdfFile);
if(ap == 0) {
std::cout << "Accelerator Propagator has not been created " << std::endl;
return 1;
}
std::cout << "\n SXF_TRACKER tracker, ";
std::cout << "size : " << ap->getRootNode().size() << " propagators " << endl;
// ************************************************************************
std::cout << "\nBunch Part." << std::endl;
// ************************************************************************
PAC::Bunch bunch(1); // bunch with one particle
bunch.setBeamAttributes(ba);
//gsl_rng *r = gsl_rng_alloc(gsl_rng_default);
gsl_rng *r;
const gsl_rng_type * T;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc(T);
std::cout << "generator type: " << gsl_rng_name(r) << "\n";
std::cout << "seed: " << gsl_rng_default_seed << "\n";
std::cout << "first value: " << gsl_rng_get(r) << "\n";
float theta, phi;
for(int ip=0; ip < bunch.size(); ip ++){
bunch[ip].getPosition().set(0.0, 0.0, 0.0, 1.0E-3, 0.0, 0.0);
// bunch[ip].getPosition().set(0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
const PAC::Position pos = bunch[ip].getPosition();
#include "set_betal.cc"
std::cout << "gamma " << gamma << "\n";
std::cout << "beta " << beta << "\n";
theta=gsl_ran_flat(r,0,M_PI);
phi =gsl_ran_flat(r,0,2*M_PI);
std::cout << "theta " << theta << "\n";
std::cout << "phi " << phi << "\n";
theta=gsl_ran_flat(r,0,M_PI);
phi =gsl_ran_flat(r,0,2*M_PI);
std::cout << "theta " << theta << "\n";
std::cout << "phi " << phi << "\n";
spin.setSX(sin(theta)*cos(phi));
spin.setSY(sin(theta)*sin(phi));
spin.setSZ(cos(theta));
bunch[ip].setSpin(spin);
SR[ip].set0(0);
SR[ip].set1(spin.getSX());
SR[ip].set2(spin.getSY());
SR[ip].set3(spin.getSZ());
// SR[ip].set(sr0,sr1,sr2,sr3);
lorentzTransformForTracker(SR[ip], betal*=(-1), gamma, SL[ip]);
std::cout << "SR: SR0 " << SR[ip].get0() << " SR1 " << SR[ip].get1() << " SR2 " << SR[ip].get2() << " SR3 " << SR[ip].get3() << "\n";
std::cout << "SL: SR0 " << SL[ip].get0() << " SL1 " << SL[ip].get1() << " SL2 " << SL[ip].get2() << " SL3 " << SL[ip].get3() << "\n";
}
/*
sr.set(sr0,sr1,sr2,sr3); // sr0 == 0 !!!
const PAC::Position pos = bunch[0].getPosition();
#include "set_betal.cc"
std::cout << "gamma " << gamma << "\n";
std::cout << "beta " << beta << "\n";
lorentzTransformForTracker(sr, betal*=(-1), gamma, sl);
sl0 = sl.get0();
sl1 = sl.get1();
sl2 = sl.get2();
sl3 = sl.get3();
std::cout << "sl: sl0 " << sl0 << " sl1 " << sl1 << " sl2 " << sl2 << " sl3 " << sl3 << "\n";
//sl.set(spin0,spin1,spin2,spin3);
*/
ul.set(0,0,0,0);
pl.set(0,0,0,0);
// ************************************************************************
std::cout << "\nTracking. " << std::endl;
// ************************************************************************
double t; // time variable
int turns = 10;
std::string orbitFile = "./out/cpp/";
orbitFile += variantName;
orbitFile += ".orbit";
positionPrinter pP;
pP.open(orbitFile.c_str());
ba.setElapsedTime(0.0);
start_ms();
for(int iturn = 1; iturn <= turns; iturn++){
std::cout << "turn loop: turn # " << iturn << "\n";
ap -> propagate(bunch);
for(int ip=0; ip < bunch.size(); ip++){
pP.write(iturn, ip, bunch);
}
}
t = (end_ms());
std::cout << "time = " << t << " ms" << endl;
pP.close();
return 1;
}
|
a26221f02bb65607b4a72a83862f9c6063ca07c0 | 4a187d26db80a7a6bbe5a433b44bce21ef783ce3 | /WarpSolve/SExp.h | f199458ebe779a096698418e661b38b14f9b18de | [] | no_license | kumoyuki/WarpSolve | 5832c13a6367404011ab7b060bd4f3bf0ea4b1a7 | 5f917ec597261ec87927e93bcb9c8322d5bbea56 | refs/heads/master | 2016-09-06T17:25:50.420741 | 2013-09-15T20:19:12 | 2013-09-15T20:19:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,673 | h | SExp.h | // -*- c++ -*-
// (C) 2013 David Richard Rush and Heureka Software
// http://cyber-rush.org.drr
// mailto:kumoyuki@gmail.com
//
// Permission to use is freely granted along with the inclusion of
// this copyright notice in all derivative works.
//
#pragma once
#include <memory>
#include <string>
#include <list>
#include <locale>
#include <stdio.h>
#include <vector>
#define BEGIN_HEUREKA namespace Heureka {
#define END_HEUREKA }
BEGIN_HEUREKA;
struct List;
struct Atom;
struct String;
struct Symbol;
struct Num;
struct Exact;
struct Inexact;
struct Fixnum;
struct Flonum;
struct Timestamp;
struct Datum
{
struct Reader
{
struct Error
{
size_t Line;
size_t Column;
std::string Message;
Error();
Error(const Error& e);
Error(size_t line, size_t col, const std::string msg);
Error& operator= (const Error& e);
};
static std::unique_ptr<Reader> Read(const std::string& text);
std::locale Locale;
std::unique_ptr<Datum> Red;
std::string::const_iterator Cursor;
std::string::const_iterator End;
size_t Line;
size_t Column;
std::list<Error> Errors;
Reader(const std::string& s);
void AddError(std::string m);
void Deblank();
bool Parse(void (Reader::* reader)());
std::unique_ptr<Datum> ReadAtom();
std::string ReadAtomicText();
void ReadList();
bool ReadNext();
void ReadNumber();
long long ReadNumberComponent();
std::string ReadQuoted(char q);
void ReadString();
void ReadSymbol();
void ReadTimestamp();
std::pair<bool, long> ReadTimestampComponent(char delim, const char* what);
};
template <typename FROM> static std::unique_ptr<Datum> AsDatum(const FROM from);
static std::unique_ptr<Datum> Read(const std::string& text);
mutable std::string Text;
virtual ~Datum();
std::string AsString() const;
virtual std::string BuildString() const =0;
virtual Datum* DeepCopy() const =0;
virtual bool IsAtom() const;
virtual bool IsList() const;
virtual bool IsNumber() const;
virtual bool IsString() const;
virtual bool IsTimestamp() const;
};
template <> std::unique_ptr<Datum> Datum::AsDatum(const double from);
template <> std::unique_ptr<Datum> Datum::AsDatum(const long from);
template <> std::unique_ptr<Datum> Datum::AsDatum(const std::string from);
template <> std::unique_ptr<Datum> Datum::AsDatum(FILE* from);
struct List : public Datum
{
std::vector<Datum*> Data;
~List();
std::vector<Datum*>::const_iterator begin() const;
std::string BuildString() const;
Datum* DeepCopy() const;
std::vector<Datum*>::const_iterator end() const;
bool IsList() const;
size_t Length() const;
Datum* Raw(size_t n) const;
const Datum& Ref(size_t n) const;
void Set(size_t at, Datum& d);
};
struct Atom : public Datum
{
bool IsAtom() const;
};
struct Num : public Atom
{
virtual long double Fraction() const =0;
virtual bool IsExact() const;
virtual bool IsInexact() const;
bool IsNumber() const;
virtual long long Truncate() const =0;
};
struct Exact : public Num
{
bool IsExact() const;
};
struct Fixnum : public Exact
{
long long Value;
Fixnum(long long val);
std::string BuildString() const;
Datum* DeepCopy() const;
long double Fraction() const;
long long Truncate() const;
};
struct Inexact : public Num
{
bool IsInexact() const;
};
struct Flonum : public Inexact
{
long double Value;
Flonum(long double val);
std::string BuildString() const;
Datum* DeepCopy() const;
long double Fraction() const;
long long Truncate() const;
};
struct String : public Atom
{
std::string Value;
String(const std::string& s);
std::string BuildString() const;
Datum* DeepCopy() const;
bool IsString() const;
};
struct Symbol : public String
{
Symbol(const std::string& s);
std::string BuildString() const;
};
struct Timestamp : public Exact
{
static Timestamp* Parse(const String& s);
long Year;
long Month;
long Day;
long Hour;
long Minute;
long Second;
double Frac;
Timestamp();
Timestamp(long y, long m, long d, long h, long min, long s, double f);
Timestamp& operator= (const Timestamp& other);
std::string BuildString() const;
Datum* DeepCopy() const;
long double Fraction() const;
bool IsTimestamp() const;
long long Truncate() const;
};
END_HEUREKA;
|
604a704f15d29145035c73a4aeff6c748a53eaa4 | f5d5356e629ee8704993136dac098dec2fd228ef | /sdk/master_board_sdk/include/master_board_sdk/ESPNOW_manager.h | 9d959992ea55b578b860eca7befd635459fb6e22 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | open-dynamic-robot-initiative/master-board | 3466929a27485d79f1d5b82d48b4bad95ba0a737 | 361f44689c1223a00426a96b2f7d1bcaf5b2bed2 | refs/heads/master | 2023-07-21T08:46:31.783111 | 2023-06-27T08:49:56 | 2023-06-27T08:49:56 | 198,817,879 | 104 | 41 | BSD-2-Clause | 2023-09-11T19:02:19 | 2019-07-25T11:22:35 | C++ | UTF-8 | C++ | false | false | 1,279 | h | ESPNOW_manager.h | #ifndef ESPNOW_manager_H
#define ESPNOW_manager_H
#include <linux/filter.h>
#include "master_board_sdk/Link_manager.h"
#include "master_board_sdk/ESPNOW_types.h"
class ESPNOW_manager : public LINK_manager {
public:
ESPNOW_manager() : LINK_manager(&myWiFipacket) {}
ESPNOW_manager(const std::string& interface) : LINK_manager(&myWiFipacket, interface) {}
ESPNOW_manager(const std::string& interface, uint8_t datarate, uint16_t channel_freq, uint8_t src_mac[6], uint8_t dst_mac[6], bool filterOn)
: LINK_manager(&myWiFipacket, interface) {
set_channel(channel_freq);
set_datarate(datarate);
set_src_mac(src_mac);
set_dst_mac(dst_mac);
bpf.filter = NULL;
bpf.len = 0;
if(filterOn) {
set_filter(dst_mac, src_mac);
} else {
set_filter(NULL, NULL);
}
}
~ESPNOW_manager();
void set_filter(uint8_t *src_mac, uint8_t *dst_mac);
void unset_filter();
void bind_filter();
void stop() override;
void set_channel(uint16_t channel_freq) { myWiFipacket.set_channel(channel_freq); }
uint16_t get_channel() { return myWiFipacket.data.radiotap.channel_freq; }
void set_datarate(uint8_t datarate) { myWiFipacket.set_datarate(datarate); }
private:
struct sock_fprog bpf;
ESPNOW_packet myWiFipacket;
};
#endif
|
e89216b22866af250017c32a2b2287de36192510 | ceed8ee18ab314b40b3e5b170dceb9adedc39b1e | /android/bootable/recovery/multi_ir.cpp | 2bb2add6cba96c253cc81385006ee15fd79691c9 | [
"Apache-2.0"
] | permissive | BPI-SINOVOIP/BPI-H3-New-Android7 | c9906db06010ed6b86df53afb6e25f506ad3917c | 111cb59a0770d080de7b30eb8b6398a545497080 | refs/heads/master | 2023-02-28T20:15:21.191551 | 2018-10-08T06:51:44 | 2018-10-08T06:51:44 | 132,708,249 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,844 | cpp | multi_ir.cpp | #include "multi_ir.h"
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <utils/Log.h>
#include <linux/input.h>
static void keymap_init(struct keymap_t *map)
{
int i;
for (i=0; i<KEYCODE_CNT; i++, map++) {
map->keycode = RESERVE_CODE;
strcpy(map->name, RESERVE_NAME);
}
}
#ifdef DEBUG
static void dump_keymap(struct keymap_t *map)
{
int i;
for (i=0; i<KEYCODE_CNT; i++, map++) {
if (!strlen(map->name)) continue;
printf("key\t%d\t%s\n", map->keycode, map->name);
}
}
static void dump_mapping_table(struct mapping_table_t *table, struct keymap_t *def)
{
int i;
printf("+ identity: 0x%04x\n", table->identity);
for (i=0; i<KEYCODE_CNT; i++) {
printf("\t[%3d] --> { %3d, %-20s }\n", i, table->value[i],
(def + table->value[i])->name);
}
}
#endif
/**
* @brief: create a keymap form keylayout file(*.kl)
* @param: path - path to the target file
* @param: map - store the result
* @return:
*/
static int create_keymap_from_file(const char *path, struct keymap_t *map)
{
int ret = 0;
FILE *kl_fd = NULL;
char buf[1024], lable[32], name[MAX_NAME_LEN];
int keycode;
char *p;
struct keymap_t *des;
kl_fd = fopen(path, "r");
if (!kl_fd) {
fprintf(stderr, "open '%s' fail, %s\n", path, strerror(errno));
return -1;
}
while (fgets(buf, 1024, kl_fd)) {
p = buf;
while (*p==' ') p++;
if (*p=='#') continue;
if (sscanf(buf, "%s %d %s", lable, &keycode, name)!=3) continue;
if (strcmp(lable, "key")!=0 || keycode < KEYCODE_MIN || keycode > KEYCODE_MAX) continue;
des = (struct keymap_t *)(map + keycode);
des->keycode = keycode;
strcpy(des->name, name);
}
if (!feof(kl_fd)) {
fprintf(stderr, "reading '%s' error, %s\n", path, strerror(errno));
ret = -1;
}
fclose(kl_fd);
return ret;
}
/**
* @brief: make a mapping from src to des, the result is store at @table,
* the mapping will set to ir driver through ioctl syscall.
* @param: src
* @param: des
* @param: table
*/
static void generate_mapping_table(struct keymap_t* src, struct keymap_t *des, struct mapping_table_t *table)
{
int i, j;
struct keymap_t *p;
memset(table, 0, sizeof(struct mapping_table_t));
for (i=0; i<KEYCODE_CNT; i++, src++) {
if (src->keycode==RESERVE_CODE) continue;
p = des;
for (j=0; j<KEYCODE_CNT; j++, p++) {
if (p->keycode!=-1 && strcmp(src->name, p->name)==0) {
table->value[p->keycode] = src->keycode;
if (table->powerkey==0 && strcmp(src->name, "POWER")==0) {
table->powerkey = p->keycode;
}
p->keycode = -1;
break;
}
}
}
}
/**
* @brief: filter out the valid kaylaout file.
* @param: name
* @return: -1 means something error, else the identity.
*/
static int kl_filename_verify(const char *name)
{
char *p;
int i, identity;
/* filename prefix filter */
if (strncmp(name, FILENAME_PREFIX, strlen(FILENAME_PREFIX)))
return -1;
/* filename extensiion filter */
p = (char *)name + strlen(FILENAME_PREFIX) + 4;
if (strcmp(p, FILENAME_EXTENSION))
return -1;
/* identity filter, 4 hexadecimal number */
p = (char *)name + strlen(FILENAME_PREFIX);
for (i=0; i<4; i++) {
if (isxdigit(*(p+i))==0)
return -1;
}
identity = strtol(p, &p, 16);
return identity;
}
int multi_ir_init(const char* defaultLayoutPath, const char* layoutsPath)
{
int dev_fd, ret = 0;
char kl_path[512] = {0};
DIR *dir;
struct dirent *dirent;
int identity;
struct mapping_table_t *mapping_table;
int pos = 0;
mapping_tables = (struct mapping_table_t **)calloc(32,sizeof(struct mapping_table_t *));
if (mapping_tables == NULL) {
return -1;
}
table_size = 32;
/* create default key map */
keymap_init(default_keys);
if (create_keymap_from_file(defaultLayoutPath, default_keys)!=0) {
return -1;
}
#ifdef DEBUG
dump_keymap(default_keys);
#endif
dir = opendir(layoutsPath);
if (!dir) {
fprintf(stderr, "Open directory '%s' error, %s\n",
layoutsPath, strerror(errno));
return -1;
}
while ((dirent=readdir(dir))!=NULL) {
identity = kl_filename_verify(dirent->d_name);
if (identity!=-1) {
sprintf(kl_path, "%s/%s", layoutsPath, dirent->d_name);
memset(customer_keys, 0, sizeof(struct keymap_t)*(KEYCODE_CNT));
create_keymap_from_file(kl_path, customer_keys);
mapping_table = (struct mapping_table_t *)malloc(sizeof(struct mapping_table_t));
if (mapping_table == NULL) {
return -1;
}
generate_mapping_table(default_keys, customer_keys, mapping_table);
mapping_table->identity = identity;
#ifdef DEBUG
dump_mapping_table(mapping_table, default_keys);
#endif
if (invalid_table_size == table_size) {
mapping_tables = (struct mapping_table_t **)realloc(mapping_tables,sizeof(struct mapping_table_t *)*(table_size + 8));
if (mapping_tables == NULL) {
return -1;
}
table_size += 8;
}
if (invalid_table_size < table_size) {
mapping_tables[invalid_table_size] = mapping_table;
invalid_table_size ++;
}
}
}
closedir(dir);
return ret;
}
int convertKey(struct input_event* event) {
int address = (event->value >> 8) & 0xffff;
int keycode = event->value & 0xff;
if (invalid_table_size == 0 || mapping_tables == NULL) {
return -1;
}
int i = 0;
for (i = 0; i < invalid_table_size;i++) {
int pos = (table_pos + i) % invalid_table_size;
if (address == mapping_tables[pos]->identity ) {
table_pos = pos;
return mapping_tables[pos]->value[keycode];
}
}
return -1;
}
|
886a2fbffcdb510f58193ced305c2ff0d22ba3ef | 4207610c48cbb9021f4420791a9c9d07550b72d9 | /Source/Lua/CtrlrLuaAudioConverter.h | 6fa2a1d9b9ad0fc235a25fccd6c1fd06991f6e3a | [
"GPL-2.0-only",
"BSD-3-Clause"
] | permissive | RomanKubiak/ctrlr | d98a910eb46f6cf4324da3fc3ae664cc7dd5aec9 | 8aa00d82127acda42ad9ac9b7b479461e9436aa4 | refs/heads/master | 2023-02-13T00:21:04.546585 | 2022-06-24T10:53:16 | 2022-06-24T10:53:16 | 14,671,067 | 435 | 82 | BSD-3-Clause | 2022-05-31T18:18:23 | 2013-11-24T22:53:11 | C++ | UTF-8 | C++ | false | false | 4,692 | h | CtrlrLuaAudioConverter.h | #ifndef CTRLR_LUA_AUDIO_CONVERTER
#define CTRLR_LUA_AUDIO_CONVERTER
#ifdef _WIN32
#pragma warning(disable:4100)
#endif // _WIN32
#include "CtrlrMacros.h"
#include "JuceClasses/LMemoryBlock.h"
//==============================================================================
/** @brief A class for holding audio samples
*
*/
class CtrlrLuaAudioConverter
{
public:
CtrlrLuaAudioConverter();
~CtrlrLuaAudioConverter();
/** @brief Convert a block of data in the format of 8bit (1 byte) signed data, to a floating point AudioSampleBuffer
@param sourceData a MemoryBlock of data that holds the raw samples
@param destination the destination AudioSampleBuffer to write samples to
@param numSamples how many samples to convert
@param numChannels how many audio channels to convert
@param interleaved if there is more then 1 audio channel, this tells the converter if the samples are interleaved or not
*/
void convertInt8 (MemoryBlock &sourceData, AudioSampleBuffer &destination, const int numSamples, const int numChannels=1, const bool interleaved=false);
/** @brief Convert a block of data in the format of 8bit (1 byte) unsigned data, to a floating point AudioSampleBuffer
@param sourceData a MemoryBlock of data that holds the raw samples
@param destination the destination AudioSampleBuffer to write samples to
@param numSamples how many samples to convert
@param numChannels how many audio channels to convert
@param interleaved if there is more then 1 audio channel, this tells the converter if the samples are interleaved or not
*/
void convertUInt8 (MemoryBlock &sourceData, AudioSampleBuffer &destination, const int numSamples, const int numChannels=1, const bool interleaved=false);
/** @brief Convert a block of data in the format of 16bit (2 bytes) signed data, to a floating point AudioSampleBuffer
@param sourceData a MemoryBlock of data that holds the raw samples
@param destination the destination AudioSampleBuffer to write samples to
@param numSamples how many samples to convert
@param numChannels how many audio channels to convert
@param interleaved if there is more then 1 audio channel, this tells the converter if the samples are interleaved or not
*/
void convertInt16 (MemoryBlock &sourceData, AudioSampleBuffer &destination, const int numSamples, const int numChannels=1, const bool interleaved=false);
/** @brief Convert a block of data in the format of 16bit (2 bytes) unsigned data, to a floating point AudioSampleBuffer
@param sourceData a MemoryBlock of data that holds the raw samples
@param destination the destination AudioSampleBuffer to write samples to
@param numSamples how many samples to convert
@param numChannels how many audio channels to convert
@param interleaved if there is more then 1 audio channel, this tells the converter if the samples are interleaved or not
*/
void convertUInt16 (MemoryBlock &sourceData, AudioSampleBuffer &destination, const int numSamples, const int numChannels=1, const bool interleaved=false);
/** @brief Convert a block of data in the format of 24bit (3 bytes) signed data, to a floating point AudioSampleBuffer
@param sourceData a MemoryBlock of data that holds the raw samples
@param destination the destination AudioSampleBuffer to write samples to
@param numSamples how many samples to convert
@param numChannels how many audio channels to convert
@param interleaved if there is more then 1 audio channel, this tells the converter if the samples are interleaved or not
*/
void convertInt24 (MemoryBlock &sourceData, AudioSampleBuffer &destination, const int numSamples, const int numChannels=1, const bool interleaved=false);
/** @brief Convert a block of data in the format of 32bit (4 bytes) signed data, to a floating point AudioSampleBuffer
@param sourceData a MemoryBlock of data that holds the raw samples
@param destination the destination AudioSampleBuffer to write samples to
@param numSamples how many samples to convert
@param numChannels how many audio channels to convert
@param interleaved if there is more then 1 audio channel, this tells the converter if the samples are interleaved or not
*/
void convertInt32 (MemoryBlock &sourceData, AudioSampleBuffer &destination, const int numSamples, const int numChannels=1, const bool interleaved=false);
LMemoryBlock convertToUInt8 (AudioFormatReader *sourceFormatReader, const int numSamples, const int sampleOffset, const int channel, const bool sourceIsInterleaved);
static void wrapForLua(lua_State *L);
};
#endif
|
282509beb3befdd0466712cd20656923ef296c3c | 39eac74fa6a244d15a01873623d05f480f45e079 | /CachedData.cpp | 0bc15d1d535b6b70b0bd1b87f2a4bfee70dfa04b | [] | no_license | 15831944/Practice | a8ac8416b32df82395bb1a4b000b35a0326c0897 | ae2cde9c8f2fb6ab63bd7d8cd58701bd3513ec94 | refs/heads/master | 2021-06-15T12:10:18.730367 | 2016-11-30T15:13:53 | 2016-11-30T15:13:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,346 | cpp | CachedData.cpp | #include "stdafx.h"
#include "CachedData.h"
#include <NxAlgorithm.h> // Ensure boost will pick up our CString-aware hash_value() function
#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
using namespace ADODB;
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// (b.cardillo 2015-05-06 00:06) - PLID 65951 - Framework for loading and checking for the existence
// of certain values efficiently.
// (b.cardillo 2015-05-07 08:48) - PLID 65951 (supplemental) - Just fixed some comments and
// implemented an as-yet-unused function for completeness.
// (b.cardillo 2015-05-07 14:21) - PLID 65951 (supplemental) - Made it right-trim all strings to be
// consistent with sql; also some efficiency and template improvements.
// (b.cardillo 2015-05-10 08:35) - PLID 65951 (supplemental) - Added support for multisets and further templated.
// (b.cardillo 2015-07-16 22:04) - PLID 65951 (supplemental) - Make case insensitive. If we ever
// use this class for some purpose that demands case sensitivity, we can easily template it.
///////////
// First some local utilities
///////////
namespace {
// Templated VarT() functions
template<typename T> inline T VarTypedForCaching(const VARIANT &val) {
// No default implementation.
// If you get a compile error here it means you are calling Var<T>() for something other
// than a known implementation below. You either need to add another implementation below
// or reconsider the calling code to call one of the existing functions.
}
// Explicit implementations. Notice the string-typed one trims right; that's so we have the
// same behavior as sql text comparison (default collation) when looking up values in the cache.
template<> inline long VarTypedForCaching(const VARIANT &val) { return VarLong(val); }
template<> inline CString VarTypedForCaching(const VARIANT &val) { return VarString(val).TrimRight(); }
template<> inline CiString VarTypedForCaching(const VARIANT &val) { return VarString(val).TrimRight(); }
// Templated insert of values to avoid repeating this little code snippet all over
template<typename H>
inline void InsertNonNullTrimRight(H &hash, const VARIANT &val) {
if (val.vt != VT_NULL) {
hash.insert(VarTypedForCaching<H::key_type>(val));
} else {
// Nothing matches NULL, so don't store an entry in the hash for VT_NULL values
}
}
// (b.cardillo 2015-05-08 10:12) - PLID 65988 - Added support for maps (we already had sets)
template<typename H>
inline void InsertNonNullTrimRight(H &hash, const VARIANT &key, const VARIANT &val) {
if (key.vt != VT_NULL) {
hash.insert({ VarTypedForCaching<H::key_type>(key), VarTypedForCaching<H::mapped_type>(val) });
} else {
// Nothing matches NULL, so don't store an entry in the hash for VT_NULL values
}
}
// Returns a reference to the existing value from a map for the given key, or, if the key
// doesn't exist in the map yet, inserts a new default value for that key and returns the
// reference to the value.
template <class K, class T, class H, class P, class A>
inline T &FindOrCreate(boost::unordered_map<K, T, H, P, A> &map, const typename boost::unordered_map<K, T, H, P, A>::key_type &key)
{
// See if there's already an element
boost::unordered_map<K, T, H, P, A>::iterator iter = map.find(key);
if (iter != map.end()) {
// Found it, return a reference to the value of the entry we just found
return iter->second;
} else {
// We don't have a value for this key yet, so create one and return a reference to it
T val;
return map.insert({ key, val }).first->second;
}
}
// Returns a right-trimmed version of the given string. This never modifies the original string
// (obviously, since the original is const), yet thanks to CString's reference counting, it will
// only allocate a new copy of the string if the original had trailing whitespace. Otherwise,
// this will do nothing and just return a reference to the original.
inline CString TrimRight(const CString &str)
{
CString ans(str);
ans.TrimRight();
return ans;
}
inline CiString TrimRight(const CiString &str)
{
CiString ans(str);
ans.TrimRight();
return ans;
}
// These two classes each encapsulate a "context" concept for caching of different sources of
// data. They implement an instance function called "Fill" that populates the hash. By having
// this concept, we can template callers to unify calling logic into templated functions.
// Datalist-related implementation of the "context" concept. This takes the two context-
// identifying parameters (datalist and column) and provides the logic for inserting the values
// from that column of that datalist into the hash.
class CCachedDataContext_DatalistColumn
{
public:
CCachedDataContext_DatalistColumn(NXDATALIST2Lib::_DNxDataList *pDatalist, int nColumn)
: m_pDatalist(pDatalist), m_nColumn(nColumn) { }
protected:
NXDATALIST2Lib::_DNxDataListPtr m_pDatalist;
int m_nColumn;
public:
// Our one job: populate the hash
template<typename H>
void Fill(H &hash) const {
// Core logic of this class: loop through the datalist, add the values from the column
// of interest to the given hash
for (NXDATALIST2Lib::IRowSettingsPtr pRow = this->m_pDatalist->GetFirstRow(); pRow != NULL; pRow = pRow->GetNextRow()) {
Insert(hash, pRow);
}
}
protected:
// We're the only one who knows how insert our kind of entry into a hash. For now we only
// implement inserting into a set (or multi-set). We could add maps later if needed.
template<typename H>
inline void Insert(H &hash, NXDATALIST2Lib::IRowSettingsPtr pRow) const
{
InsertNonNullTrimRight(hash, pRow->GetValue(this->m_nColumn));
}
};
// Query-related implementation of the "context" concept. This takes the one context-
// identifying parameter (the sql query) and provides the Fill_Impl() logic for running that
// query and looping through that results, inserting the value from that field into the hash.
class CCachedDataContext_Query
{
public:
CCachedDataContext_Query(const CString &sqlPopulateCache)
: m_sqlPopulateCache(sqlPopulateCache) { }
protected:
const CString &m_sqlPopulateCache;
public:
// Our one job: populate the hash
template<typename H>
void Fill(H &hash) {
// Core logic of this class: run the recordset, loop through the results, add the values
// to the hash
for (_RecordsetPtr prs = CreateRecordsetStd(this->m_sqlPopulateCache); !prs->eof; prs->MoveNext()) {
Insert(hash, prs);
}
}
protected:
// We're the only one who knows how insert our kind of entry into a hash.
template<typename H>
static void Insert(H &hash, _RecordsetPtr prs)
{
InsertNonNullTrimRight(hash, prs->GetCollect((long)0));
}
// (b.cardillo 2015-05-08 10:12) - PLID 65988 - Added support for maps (we already had sets)
template<typename K, typename T>
static void Insert(boost::unordered_map<K, T> &hash, _RecordsetPtr prs)
{
InsertNonNullTrimRight(hash, prs->GetCollect((long)0), prs->GetCollect((long)1));
}
};
}
//////////
// CCachedData implementation
//////////
CCachedData::CCachedData()
{
}
// For hashsets or hashmultisets of any type key for any context
template<typename H>
template<typename C>
int CCachedData::CCacheContainer<H>::Count(C &context, const typename H::key_type &valToLookUp)
{
// Make sure our hash set is populated
if (!this->isPopulated) {
context.Fill(this->hash);
this->isPopulated = true;
}
// Look up the value the caller wants to check
return this->hash.count(valToLookUp);
}
// For hashsets or hashmultisets of any type key for any context
template<typename H>
template<typename C>
bool CCachedData::CCacheContainer<H>::Set(C &context, const typename H::key_type &valToSet)
{
// Make sure our hash set is populated
if (!this->isPopulated) {
context.Fill(this->hash);
this->isPopulated = true;
}
// Insert the value the caller wants to insert, and return true if we inserted it, false if it
// was already there so we didn't insert it
return this->hash.insert(valToSet).second;
}
// (b.cardillo 2015-05-08 10:12) - PLID 65988 - Added support for maps (we already had sets)
// For hashmaps or hashmultimaps (returns first entry) of any type key/value for any context
template<typename H>
template<typename C, typename T>
bool CCachedData::CCacheContainer<H>::LookUp(C &context, const typename H::key_type &keyToLookUp, T &valToRetrieve)
{
// Make sure our hash set is populated
if (!this->isPopulated) {
context.Fill(this->hash);
this->isPopulated = true;
}
// Look up the value the caller wants to check
auto iter = this->hash.find(keyToLookUp);
if (iter != this->hash.end()) {
// Found it, return true and a copy of the value of the entry we just found
valToRetrieve = iter->second;
return true;
} else {
// Wasn't found
return false;
}
}
// Hash any COM smart pointer using its IUnknown pointer to ensure object identity. (An object might
// have different pointer values for different COM interfaces, but for any given object you'll always
// get the same IUnknown pointer.)
template<typename ComPtrType>
std::size_t hash_value(const _com_ptr_t<ComPtrType>& p)
{
return std::hash_value(IUnknownPtr(p).GetInterfacePtr());
}
namespace {
// Convenience function PickDatalistCacheSet() to make sure the pointer isn't null and then
// cleanly retrieve the correct CCacheContainer object based on that datalist and column.
template <class K, class T, class H, class P, class A>
inline typename boost::unordered_map<K, T, H, P, A>::mapped_type::mapped_type &PickDatalistCacheSet(boost::unordered_map<K, T, H, P, A> &map, NXDATALIST2Lib::_DNxDataList *pDatalist, int nColumn)
{
if (pDatalist == NULL) {
// It would never make sense to call this with a NULL datalist pointer because it would mean
// you don't have a control you're searching. If there were ever such calling code, it is
// surely a flaw in that code. But if not, then the caller can just check for NULL and not
// call us in that case.
ASSERT(FALSE);
ThrowNxException("CCachedData::Exists_DatalistValueInColumn() cannot search a NULL datalist.");
}
// The inner FindOrCreate() finds the map associated with the DATALIST, and then the outer
// FindOrCreate() looks in that map to find the CCacheContainer associated with the given COLUMN.
return FindOrCreate(FindOrCreate(map, IUnknownPtr(pDatalist)), nColumn);
}
}
bool CCachedData::Exists_DatalistValueInColumn(NXDATALIST2Lib::_DNxDataList *pDatalist, int nColumn, const string_key_type &valToLookup)
{
// Call the standard Count() on the appropriate CCacheContainer. The appropriate CCacheContainer
// is the one that's associated with the requested COLUMN of the requested DATALIST.
return PickDatalistCacheSet(m_datalistColumnSets, pDatalist, nColumn)
.Count(CCachedDataContext_DatalistColumn(pDatalist, nColumn), TrimRight(valToLookup)) ? true : false;
}
int CCachedData::Count_DatalistValueInColumn(NXDATALIST2Lib::_DNxDataList *pDatalist, int nColumn, const string_key_type &valToLookup)
{
// Call the standard Count() on the appropriate CCacheContainer. The appropriate CCacheContainer
// is the one that's associated with the requested COLUMN of the requested DATALIST.
return PickDatalistCacheSet(m_datalistColumnMultiSets, pDatalist, nColumn)
.Count(CCachedDataContext_DatalistColumn(pDatalist, nColumn), TrimRight(valToLookup));
}
bool CCachedData::Set_DatalistValueInColumn(NXDATALIST2Lib::_DNxDataList *pDatalist, int nColumn, const string_key_type &valToSet)
{
// Call the standard Set() on the appropriate CCacheContainer. The appropriate CCacheContainer
// is the one that's associated with the requested COLUMN of the requested DATALIST.
return PickDatalistCacheSet(m_datalistColumnSets, pDatalist, nColumn)
.Set(CCachedDataContext_DatalistColumn(pDatalist, nColumn), TrimRight(valToSet));
}
bool CCachedData::Exists_QueryValue(const CString &sqlQuery, const string_key_type &valToLookup)
{
// Call the standard Count() on the appropriate CCacheContainer. The appropriate CCacheContainer
// is the one of type T that's associated with the requested query string.
return FindOrCreate(this->m_queryCacheSets_CString, sqlQuery)
.Count(CCachedDataContext_Query(sqlQuery), TrimRight(valToLookup)) ? true : false;
}
bool CCachedData::Exists_QueryValue(const CString &sqlQuery, const long &valToLookup)
{
// Call the standard Count() on the appropriate CCacheContainer. The appropriate CCacheContainer
// is the one of type T that's associated with the requested query string.
return FindOrCreate(this->m_queryCacheSets_long, sqlQuery)
.Count(CCachedDataContext_Query(sqlQuery), valToLookup) ? true : false;
}
// (b.cardillo 2015-05-08 10:12) - PLID 65988 - Added support for maps (we already had sets)
bool CCachedData::GetValue_Query(const CString &sqlQuery, const string_key_type &keyToLookup, long &valToRetrieve)
{
// Call the standard LookUp() on the appropriate CCacheContainer. The appropriate CCacheContainer
// is the one of type T that's associated with the requested query string.
return FindOrCreate(this->m_queryCacheMaps_CString_long, sqlQuery)
.LookUp(CCachedDataContext_Query(sqlQuery), TrimRight(keyToLookup), valToRetrieve);
}
|
7d99217fcfeb6b97cf1e075a649a824e641da538 | a809904038582234e3b8f16930ffe572d9a5688f | /kadanes_maxi_contigous_subarray.cpp | 35224d0a564fad861700549bc180e2e4c3316706 | [] | no_license | 7566565794/array_gfg | 497bbac6e1497409fc2c75b3669ae644a69a9e37 | c5e0f61c5effd47a9462d1dd7367df1c2e13e61f | refs/heads/master | 2020-05-30T22:07:48.471587 | 2019-08-21T18:47:26 | 2019-08-21T18:47:26 | 189,987,833 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 638 | cpp | kadanes_maxi_contigous_subarray.cpp | #include <iostream>
#include<bits/stdc++.h>
using namespace std;
int max_sum(int arr[],int n){
int max_so_far=0;
int max_ending_here=0;
for(int i=0;i<n;i++){
max_ending_here=max_ending_here+arr[i];
if(max_ending_here<0){
max_ending_here=0;
}
if(max_so_far<max_ending_here){
max_so_far=max_ending_here;
}
}
if(max_so_far==0){
return arr[0];
}
return max_so_far;
}
int main() {
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
cout<<max_sum(arr,n)<<endl;
}
return 0;
}
|
c99e7c1dfad4fe03911a4ced39131c805fd9a690 | 83f57d38e34d767126c7a3c99fa89499fdf8940a | /Abstract_VM/src/main.cpp | 54286428d371e8b39d59522f97e34bde02fa6d68 | [] | no_license | atlekbai/School42Projects | d4d2b418d6dff5718e40912173496a4d5f187421 | c3684393b8bb84b62cfb73674751e520f1746e0e | refs/heads/master | 2020-04-09T02:20:04.928479 | 2018-12-11T10:10:21 | 2018-12-11T10:10:21 | 159,936,817 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,694 | cpp | main.cpp | // ************************************************************************** //
// //
// ::: :::::::: //
// main.cpp :+: :+: :+: //
// +:+ +:+ +:+ //
// By: atlekbai <marvin@42.fr> +#+ +:+ +#+ //
// +#+#+#+#+#+ +#+ //
// Created: 2018/07/08 16:55:16 by atlekbai #+# #+# //
// Updated: 2018/07/08 16:55:16 by atlekbai ### ########.fr //
// //
// ************************************************************************** //
#include "Operand.class.hpp"
#include "Factory.class.hpp"
#include "AbstractVM.class.hpp"
#include <fstream>
#include <vector>
void valid(AbstractVM &vm, std::string const &line)
{
try
{
vm.validate(line);
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
}
void proc(AbstractVM &vm, std::string const &line)
{
try
{
vm.process(line);
}
catch (std::exception &e)
{
vm.toggleExit();
std::cout << e.what() << std::endl;
}
}
int main(int ac, char **av)
{
AbstractVM vm;
std::string line;
if (ac == 2)
{
std::ifstream ifs(av[1]);
if (!ifs)
std::cout << "File Error" << std::endl;
else
{
while (std::getline(ifs, line))
valid(vm, line);
try
{
if (!vm.getHasError())
{
ifs.clear(), ifs.seekg(0, ifs.beg);
vm.defaultIter();
while (std::getline(ifs, line) && !vm.getExit())
proc(vm, line);
}
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
ifs.close();
}
}
else if (ac == 1)
{
std::vector<std::string> v;
int i = 1;
while (1)
{
std::cout << i++ << ". ";
std::getline(std::cin, line);
(!std::cin) ? exit(0) : (void)NULL;
if (line == ";;")
break;
v.push_back(line);
}
for(size_t i = 0; i < v.size(); i++)
valid(vm, v[i]);
try
{
if (!vm.getHasError())
{
vm.defaultIter();
for(size_t i = 0; i < v.size() && !vm.getExit(); i++)
proc(vm, v[i]);
}
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
}
else
{
std::cout << "Usage: ./avm [<no parameters>|<filename>]" << std::endl;
std::cout << "No parameters:" << std::endl << "\texecute from stdin" << std::endl;
std::cout << "File given:" << std::endl << "\texecute from a file" << std::endl;
}
return (0);
} |
2ad957734c849c9955e01971e1115ec0944f92f2 | 1a305cda5098c2337f4be1d710d4218e8029a4e8 | /core/wasm/main.cc | b0a486f5c1d5186f0e3983adf4adf146b0e2b274 | [
"ISC"
] | permissive | asterick/minimon.js | 682530619dd21c24a34775e0d27f573d1841c1e5 | c1c65738388775bd044eafdb13ffde5289685511 | refs/heads/master | 2023-04-06T07:36:33.522593 | 2022-08-06T00:27:51 | 2022-08-06T00:27:51 | 180,250,530 | 7 | 0 | ISC | 2023-03-15T03:33:24 | 2019-04-08T23:55:24 | C++ | UTF-8 | C++ | false | false | 9,860 | cc | main.cc | /*
ISC License
Copyright (c) 2019, Bryon Vandiver
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdint.h>
#include <stddef.h>
#include "machine.h"
#include "debug.h"
enum FieldType : uint32_t {
TYPE_END = 0,
TYPE_STRUCT,
TYPE_UINT8,
TYPE_UINT16,
TYPE_UINT32,
TYPE_INT8,
TYPE_INT16,
TYPE_INT32,
TYPE_BOOL
};
struct FieldDecl;
struct StructDecl {
uint32_t size;
const FieldDecl* fields;
};
struct FieldDecl {
FieldType type;
const char* name;
uint32_t offset;
const StructDecl* def;
const int* sizes;
};
#define FIELD(n, s, f, t, ...) { t, n, offsetof(s, f), NULL, __VA_ARGS__ }
#define STRUCT(n, s, f, def, ...) { TYPE_STRUCT, n, offsetof(s, f), &def, __VA_ARGS__ }
#define SIZE(...) ((const int[]){ __VA_ARGS__, -1 })
extern "C" Machine::State* const get_machine() {
static Machine::State machine_state;
return &machine_state;
}
static const StructDecl CpuState = {
sizeof(CPU::State),
(const FieldDecl[]) {
FIELD("sc", CPU::State, sc, TYPE_UINT8),
FIELD("cc", CPU::State, cc, TYPE_UINT8),
FIELD("br", CPU::State, br, TYPE_UINT8),
FIELD("ep", CPU::State, ep, TYPE_UINT8),
FIELD("xp", CPU::State, xp, TYPE_UINT8),
FIELD("yp", CPU::State, yp, TYPE_UINT8),
FIELD("cb", CPU::State, cb, TYPE_UINT8),
FIELD("nb", CPU::State, nb, TYPE_UINT8),
FIELD( "a", CPU::State, a, TYPE_UINT8),
FIELD( "b", CPU::State, b, TYPE_UINT8),
FIELD( "l", CPU::State, l, TYPE_UINT8),
FIELD( "h", CPU::State, h, TYPE_UINT8),
FIELD("ba", CPU::State, ba, TYPE_UINT16),
FIELD("hl", CPU::State, hl, TYPE_UINT16),
FIELD("pc", CPU::State, pc, TYPE_UINT16),
FIELD("sp", CPU::State, sp, TYPE_UINT16),
FIELD("ix", CPU::State, ix, TYPE_UINT16),
FIELD("iy", CPU::State, iy, TYPE_UINT16),
{ TYPE_END }
}
};
static const StructDecl IrqState = {
sizeof(IRQ::State),
(const FieldDecl[]) {
FIELD("enable", IRQ::State, enable, TYPE_BOOL),
FIELD("active", IRQ::State, active, TYPE_BOOL),
FIELD("priorty", IRQ::State, priority, TYPE_UINT8, SIZE(IRQ::TOTAL_HARDWARE_IRQS)),
FIELD("next_priority", IRQ::State, next_priority, TYPE_INT32),
FIELD("next_irq", IRQ::State, next_irq, TYPE_INT8),
{ TYPE_END }
}
};
static const StructDecl Tim256State = {
sizeof(TIM256::State),
(const FieldDecl[]) {
FIELD("running", TIM256::State, running, TYPE_BOOL),
FIELD("value", TIM256::State, value, TYPE_UINT16),
{ TYPE_END }
}
};
static const StructDecl RtcState = {
sizeof(RTC::State),
(const FieldDecl[]) {
FIELD("running", RTC::State, running, TYPE_BOOL),
FIELD("value", RTC::State, value, TYPE_UINT32),
FIELD("prescale", RTC::State, prescale, TYPE_UINT16),
{ TYPE_END }
}
};
static const StructDecl ControlState = {
sizeof(Control::State),
(const FieldDecl[]) {
FIELD("data", Control::State, data, TYPE_UINT8, SIZE(3)),
{ TYPE_END }
}
};
static const StructDecl EepromState = {
sizeof(EEPROM::State),
(const FieldDecl[]) {
FIELD("data", EEPROM::State, data, TYPE_UINT8, SIZE(0x2000)),
FIELD("data_in", EEPROM::State, data_in, TYPE_UINT8),
FIELD("data_out", EEPROM::State, data_out, TYPE_UINT8),
FIELD("clock_in", EEPROM::State, clock_in, TYPE_UINT8),
FIELD("address", EEPROM::State, address, TYPE_UINT16),
FIELD("mode", EEPROM::State, mode, TYPE_UINT8),
FIELD("shift", EEPROM::State, shift, TYPE_UINT8),
FIELD("bit", EEPROM::State, bit, TYPE_INT8),
{ TYPE_END }
}
};
static const StructDecl GpioState = {
sizeof(GPIO::State),
(const FieldDecl[]) {
FIELD("output", GPIO::State, output, TYPE_UINT8),
FIELD("direction", GPIO::State, direction, TYPE_UINT8),
STRUCT("eeprom", GPIO::State, eeprom, EepromState),
{ TYPE_END }
}
};
static const StructDecl LcdState = {
sizeof(LCD::State),
(const FieldDecl[]) {
FIELD("gddram", LCD::State, gddram, TYPE_UINT8, SIZE(9, 132)),
FIELD("read_buffer", LCD::State, read_buffer, TYPE_UINT8),
FIELD("volume", LCD::State, volume, TYPE_UINT8),
FIELD("column_address", LCD::State, column_address, TYPE_UINT8),
FIELD("page_address", LCD::State, page_address, TYPE_UINT8),
FIELD("start_address", LCD::State, start_address, TYPE_UINT8),
FIELD("rmw_mode", LCD::State, rmw_mode, TYPE_BOOL),
FIELD("adc_select", LCD::State, adc_select, TYPE_BOOL),
FIELD("setting_volume", LCD::State, setting_volume, TYPE_BOOL),
FIELD("display_enable", LCD::State, display_enable, TYPE_BOOL),
FIELD("reverse_display", LCD::State, reverse_display, TYPE_BOOL),
FIELD("all_on", LCD::State, all_on, TYPE_BOOL),
FIELD("reverse_com_scan", LCD::State, reverse_com_scan, TYPE_BOOL),
FIELD("static_indicator", LCD::State, static_indicator, TYPE_BOOL),
FIELD("lcd_bias", LCD::State, lcd_bias, TYPE_BOOL),
FIELD("resistor_ratio", LCD::State, resistor_ratio, TYPE_UINT8),
FIELD("operating_mode", LCD::State, operating_mode, TYPE_UINT8),
FIELD("scanline", LCD::State, scanline, TYPE_UINT8),
FIELD("overflow", LCD::State, overflow, TYPE_INT32),
{ TYPE_END }
}
};
static const StructDecl InputState = {
sizeof(Input::State),
(const FieldDecl[]) {
FIELD("bytes", Input::State, bytes, TYPE_UINT8, SIZE(6)),
FIELD("interrupt_direction", Input::State, bytes[0], TYPE_UINT16),
FIELD("input_state", Input::State, bytes[2], TYPE_UINT16),
FIELD("dejitter", Input::State, bytes[4], TYPE_UINT16),
{ TYPE_END }
}
};
static const StructDecl BlitterState = {
sizeof(Blitter::State),
(const FieldDecl[]) {
FIELD("enables", Blitter::State, enables, TYPE_UINT8),
FIELD("rate_control", Blitter::State, rate_control, TYPE_UINT8),
FIELD("map_base", Blitter::State, map_base, TYPE_UINT32),
FIELD("sprite_base", Blitter::State, sprite_base, TYPE_UINT32),
FIELD("scroll_x", Blitter::State, scroll_x, TYPE_UINT8),
FIELD("scroll_y", Blitter::State, scroll_y, TYPE_UINT8),
FIELD("divider", Blitter::State, divider, TYPE_UINT8),
{ TYPE_END }
}
};
static const StructDecl BlitterSprite = {
sizeof(Blitter::Sprite),
(const FieldDecl[]) {
FIELD("x", Blitter::Sprite, bytes[0], TYPE_UINT8),
FIELD("y", Blitter::Sprite, bytes[1], TYPE_UINT8),
FIELD("tile", Blitter::Sprite, bytes[2], TYPE_UINT8),
FIELD("flags", Blitter::Sprite, bytes[3], TYPE_UINT8),
{ TYPE_END }
}
};
static const StructDecl BlitterOverlay = {
sizeof(Blitter::Overlay),
(const FieldDecl[]) {
FIELD("framebuffer", Blitter::Overlay, framebuffer, TYPE_UINT8, SIZE(8, 96)),
STRUCT("oam", Blitter::Overlay, oam, BlitterSprite, SIZE(24)),
FIELD("map", Blitter::Overlay, framebuffer, TYPE_UINT8, SIZE(384)),
{ TYPE_END }
}
};
static const StructDecl TimerInstance = {
sizeof(Timers::Timer),
(const FieldDecl[]) {
FIELD("hi_flags", Timers::Timer, bytes[0], TYPE_BOOL),
FIELD("lo_flags", Timers::Timer, bytes[1], TYPE_BOOL),
FIELD("preset", Timers::Timer, preset, TYPE_UINT16),
FIELD("compare", Timers::Timer, compare, TYPE_UINT16),
FIELD("count", Timers::Timer, count, TYPE_UINT16),
FIELD("lo_clock_ratio", Timers::Timer, lo_clock_ratio, TYPE_INT32),
FIELD("lo_clock_ctrl", Timers::Timer, lo_clock_ctrl, TYPE_BOOL),
FIELD("lo_clock_source", Timers::Timer, lo_clock_source, TYPE_BOOL),
FIELD("hi_clock_ratio", Timers::Timer, hi_clock_ratio, TYPE_INT32),
FIELD("hi_clock_ctrl", Timers::Timer, hi_clock_ctrl, TYPE_BOOL),
FIELD("hi_clock_source", Timers::Timer, hi_clock_source, TYPE_BOOL),
{ TYPE_END }
}
};
static const StructDecl TimersState = {
sizeof(Timers::State),
(const FieldDecl[]) {
STRUCT("timer", Timers::State, timer[3], TimerInstance, SIZE(3)),
FIELD("osc1_enable", Timers::State, osc1_enable, TYPE_BOOL),
FIELD("osc3_enable", Timers::State, osc3_enable, TYPE_BOOL),
FIELD("osc1_prescale", Timers::State, osc1_prescale, TYPE_UINT32),
FIELD("osc3_prescale", Timers::State, osc3_prescale, TYPE_UINT32),
{ TYPE_END }
}
};
static const StructDecl MachineState = {
sizeof(Machine::State),
(const FieldDecl[]) {
STRUCT("cpu", Machine::State, reg, CpuState),
STRUCT("ctrl", Machine::State, ctrl, ControlState),
STRUCT("gpio", Machine::State, gpio, GpioState),
STRUCT("rtc", Machine::State, rtc, RtcState),
STRUCT("irq", Machine::State, irq, IrqState),
STRUCT("tim256", Machine::State, tim256, Tim256State),
FIELD("ram", Machine::State, ram, TYPE_UINT8, SIZE(0x1000)),
FIELD("cartridge", Machine::State, cartridge, TYPE_UINT8, SIZE(0x200000)),
STRUCT("lcd", Machine::State, lcd, LcdState),
STRUCT("input", Machine::State, input, InputState),
STRUCT("blitter", Machine::State, blitter, BlitterState),
STRUCT("overlay", Machine::State, overlay, BlitterOverlay),
STRUCT("timers", Machine::State, timers, TimersState),
FIELD("bus_cap", Machine::State, bus_cap, TYPE_UINT8),
FIELD("clocks", Machine::State, clocks, TYPE_INT32),
FIELD("osc1_overflow", Machine::State, osc1_overflow, TYPE_INT32),
FIELD("status", Machine::State, status, TYPE_UINT8),
{ TYPE_END }
}
};
extern "C" const StructDecl* get_description() {
return &MachineState;
}
|
b591a543bda708f39e5d19acdd9233970834e7c6 | b4101f2c6108cbe2b264df5f66e8cfa6aa2d01b2 | /Package.cpp | 39de3cc408ab75055116cfa2ef0cd695650c4304 | [] | no_license | double128/assignment4-oop | 77dacc40b154212fff73e3cfe01035fe0a27a240 | 00336660a443a5a527bdb0c73ae0788e322d5f6b | refs/heads/master | 2021-01-18T06:33:24.761767 | 2017-03-08T05:57:40 | 2017-03-08T05:57:40 | 84,283,755 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,830 | cpp | Package.cpp | #include "Package.h"
Package::Package
(const std::string& _sName, const std::string& _sAddress, const std::string& _sCity, const std::string& _sProvince, const std::string& _sPostalCode, // sender
const std::string& _rName, const std::string& _rAddress, const std::string& _rCity, const std::string& _rProvince, const std::string& _rPostalCode, // recipient
double _weight, double _costPerKilo)
:
sName(_sName), sAddress(_sAddress), sCity(_sCity), sProvince(_sProvince), sPostalCode(_sPostalCode),
rName(_rName), rAddress(_rAddress), rCity(_rCity), rProvince(_rProvince), rPostalCode(_rPostalCode)
{
setWeight(_weight);
setCostPerKilo(_costPerKilo);
}
// sender setter and getter definitions
void Package::setSenderName(const std::string& n)
{
sName = n;
}
std::string Package::getSenderName() const
{
return sName;
}
void Package::setSenderAddress(const std::string& a)
{
sAddress = a;
}
std::string Package::getSenderAddress() const
{
return sAddress;
}
void Package::setSenderCity(const std::string& c)
{
sCity = c;
}
std::string Package::getSenderCity() const
{
return sCity;
}
void Package::setSenderProvince(const std::string& p)
{
sProvince = p;
}
std::string Package::getSenderProvince() const
{
return sProvince;
}
void Package::setSenderPostalCode(const std::string& pc)
{
sPostalCode = pc;
}
std::string Package::getSenderPostalCode() const
{
return sPostalCode;
}
// recipient setter and getter definitions
void Package::setRecipientName(const std::string& n)
{
rName = n;
}
std::string Package::getRecipientName() const
{
return rName;
}
void Package::setRecipientAddress(const std::string& a)
{
rAddress = a;
}
std::string Package::getRecipientAddress() const
{
return rAddress;
}
void Package::setRecipientCity(const std::string& c)
{
rCity = c;
}
std::string Package::getRecipientCity() const
{
return rCity;
}
void Package::setRecipientProvince(const std::string& p)
{
rProvince = p;
}
std::string Package::getRecipientProvince() const
{
return rProvince;
}
void Package::setRecipientPostalCode(const std::string& pc)
{
rPostalCode = pc;
}
std::string Package::getRecipientPostalCode() const
{
return rPostalCode;
}
// member function defintions
void Package::setWeight(double w)
{
if (w < 0.0) { std::cout << "Invalid weight entry." << std::endl; weight = 0.0; }
else weight = w;
}
double Package::getWeight() const
{
return weight;
}
void Package::setCostPerKilo(double c)
{
if (c < 0.0) { std::cout << "Invalid cost entry." << std::endl; costPerKilo = 0.0; }
else costPerKilo = c;
}
double Package::getCostPerKilo() const
{
return costPerKilo;
}
double Package::calculateCost() const
{
return getWeight() * getCostPerKilo();
}
|
2b2ffa18a2b0c1127e5f00206d173689ec3beabe | b9b50107cae005e227eb4fbeb4831b3a63a8f5c4 | /src/graphics/opengl/opengl_context.cpp | a5694fe24ac24f132f53bd51799c61d8f7143d6f | [
"MIT"
] | permissive | Shtille/scythe | 1d043a8fdd27442e97bfcea5c2055a69b8b579be | b5ddafa3a25d78af34cb6ff00f433988789023d9 | refs/heads/master | 2022-10-22T08:33:31.669363 | 2022-10-05T12:04:24 | 2022-10-05T12:04:24 | 145,037,537 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,868 | cpp | opengl_context.cpp | #include "opengl_context.h"
#include "opengl_include.h"
namespace scythe {
OpenGlContext::OpenGlContext()
{
FillTables();
}
OpenGlContext::~OpenGlContext()
{
}
void OpenGlContext::FillTables()
{
primitive_type_map_[PrimitiveType::kLines] = GL_LINES;
primitive_type_map_[PrimitiveType::kLineStrip] = GL_LINE_STRIP;
primitive_type_map_[PrimitiveType::kTriangles] = GL_TRIANGLES;
primitive_type_map_[PrimitiveType::kTriangleStrip] = GL_TRIANGLE_STRIP;
primitive_type_map_[PrimitiveType::kQuads] = GL_QUADS;
assert(primitive_type_map_.size() == (size_t)PrimitiveType::kCount);
data_type_map_[DataType::kUnsignedShort] = GL_UNSIGNED_SHORT;
data_type_map_[DataType::kUnsignedInt] = GL_UNSIGNED_INT;
data_type_map_[DataType::kFloat] = GL_FLOAT;
assert(data_type_map_.size() == (size_t)DataType::kCount);
data_access_map_[DataAccessType::kRead] = GL_READ_ONLY;
data_access_map_[DataAccessType::kWrite] = GL_WRITE_ONLY;
data_access_map_[DataAccessType::kReadWrite] = GL_READ_WRITE;
assert(data_access_map_.size() == (size_t)DataAccessType::kCount);
buffer_usage_map_[BufferUsage::kStaticDraw] = GL_STATIC_DRAW;
buffer_usage_map_[BufferUsage::kStaticRead] = GL_STATIC_READ;
buffer_usage_map_[BufferUsage::kStaticCopy] = GL_STATIC_COPY;
buffer_usage_map_[BufferUsage::kDynamicDraw] = GL_DYNAMIC_DRAW;
buffer_usage_map_[BufferUsage::kDynamicRead] = GL_DYNAMIC_READ;
buffer_usage_map_[BufferUsage::kDynamicCopy] = GL_DYNAMIC_COPY;
buffer_usage_map_[BufferUsage::kStreamDraw] = GL_STREAM_DRAW;
buffer_usage_map_[BufferUsage::kStreamRead] = GL_STREAM_READ;
buffer_usage_map_[BufferUsage::kStreamCopy] = GL_STREAM_COPY;
assert(buffer_usage_map_.size() == (size_t)BufferUsage::kCount);
cull_face_map_[CullFaceType::kBack] = GL_BACK;
cull_face_map_[CullFaceType::kFront] = GL_FRONT;
assert(cull_face_map_.size() == (size_t)CullFaceType::kCount);
}
bool OpenGlContext::CheckForErrors()
{
#if defined(_DEBUG) || defined(DEBUG)
int error = glGetError();
if (error != GL_NO_ERROR){
if (error == GL_INVALID_ENUM)
{
ErrorHandler("GL_INVALID_ENUM");
}
else if (error == GL_INVALID_VALUE){
ErrorHandler("GL_INVALID_VALUE");
}
else if (error == GL_INVALID_OPERATION){
ErrorHandler("GL_INVALID_OPERATION");
}
else if (error == GL_OUT_OF_MEMORY){
ErrorHandler("GL_OUT_OF_MEMORY");
}
else if (error == GL_INVALID_FRAMEBUFFER_OPERATION_EXT){
ErrorHandler("GL_INVALID_FRAMEBUFFER_OPERATION_EXT");
}
else {
char str[32];
sprintf(str, "Unknown OpenGL error: %d", error);
ErrorHandler(str);
}
return true;
}
#endif
return false;
}
bool OpenGlContext::CheckFrameBufferStatus()
{
#if defined(_DEBUG) || defined(DEBUG)
GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
switch (status){
case GL_FRAMEBUFFER_COMPLETE_EXT:
return true;
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
ErrorHandler("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT");
return false;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
ErrorHandler("GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT");
return false;
case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
ErrorHandler("GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT");
return false;
case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
ErrorHandler("GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT");
return false;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
ErrorHandler("GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT");
return false;
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT:
ErrorHandler("GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT");
return false;
case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
ErrorHandler("GL_FRAMEBUFFER_UNSUPPORTED_EXT");
return false;
default:
ErrorHandler("Unknown FBO error");
return false;
}
#else
return true;
#endif
}
void OpenGlContext::ClearColor(float r, float g, float b, float a)
{
glClearColor(r, g, b, a);
}
void OpenGlContext::ClearColorBuffer()
{
glClear(GL_COLOR_BUFFER_BIT);
}
void OpenGlContext::ClearDepthBuffer()
{
glClear(GL_DEPTH_BUFFER_BIT);
}
void OpenGlContext::ClearColorAndDepthBuffers()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void OpenGlContext::ClearStencil(int value)
{
glClearStencil(value);
}
void OpenGlContext::ClearStencilBuffer()
{
glClear(GL_STENCIL_BUFFER_BIT);
}
void OpenGlContext::Viewport(int w, int h)
{
glViewport(0, 0, w, h);
}
void OpenGlContext::EnableBlend()
{
glEnable(GL_BLEND);
}
void OpenGlContext::DisableBlend()
{
glDisable(GL_BLEND);
}
void OpenGlContext::EnableDepthTest()
{
glEnable(GL_DEPTH_TEST);
}
void OpenGlContext::DisableDepthTest()
{
glDisable(GL_DEPTH_TEST);
}
void OpenGlContext::EnableDepthWrite()
{
glDepthMask(GL_TRUE);
}
void OpenGlContext::DisableDepthWrite()
{
glDepthMask(GL_FALSE);
}
void OpenGlContext::EnableStencilTest()
{
glEnable(GL_STENCIL_TEST);
}
void OpenGlContext::DisableStencilTest()
{
glDisable(GL_STENCIL_TEST);
}
void OpenGlContext::StencilMask(U32 mask)
{
glStencilMask(mask);
}
void OpenGlContext::EnableWireframeMode()
{
glPolygonMode(GL_FRONT, GL_LINE);
}
void OpenGlContext::DisableWireframeMode()
{
glPolygonMode(GL_FRONT, GL_FILL);
}
void OpenGlContext::CullFace(CullFaceType mode)
{
U32 cull_face = cull_face_map_[mode];
glCullFace(cull_face);
}
void OpenGlContext::DrawArrays(PrimitiveType mode, int first, U32 count)
{
U32 primitive_type = primitive_type_map_[mode];
glDrawArrays(primitive_type, first, count);
}
void OpenGlContext::DrawElements(PrimitiveType mode, U32 num_indices, DataType index_type)
{
U32 primitive_type = primitive_type_map_[mode];
U32 data_type = data_type_map_[index_type];
glDrawElements(primitive_type, num_indices, data_type, 0);
}
void OpenGlContext::GenVertexArrayObject(U32 &obj)
{
glGenVertexArrays(1, &obj);
}
void OpenGlContext::DeleteVertexArrayObject(U32 &obj)
{
glDeleteVertexArrays(1, &obj);
}
void OpenGlContext::BindVertexArrayObject(U32 obj)
{
glBindVertexArray(obj);
}
void OpenGlContext::GenVertexBuffer(U32& obj)
{
glGenBuffers(1, &obj);
}
void OpenGlContext::DeleteVertexBuffer(U32& obj)
{
glDeleteBuffers(1, &obj);
}
void OpenGlContext::BindVertexBuffer(U32 obj)
{
glBindBuffer(GL_ARRAY_BUFFER, obj);
}
void OpenGlContext::VertexBufferData(U32 size, const void *data, BufferUsage usage)
{
U32 usage_type = buffer_usage_map_[usage];
glBufferData(GL_ARRAY_BUFFER, size, data, usage_type);
}
void OpenGlContext::VertexBufferSubData(U32 size, const void *data)
{
glBufferSubData(GL_ARRAY_BUFFER, 0, size, data);
}
void* OpenGlContext::MapVertexBufferData(DataAccessType access)
{
U32 access_type = data_access_map_[access];
return glMapBuffer(GL_ARRAY_BUFFER, access_type);
}
void OpenGlContext::UnmapVertexBufferData()
{
glUnmapBuffer(GL_ARRAY_BUFFER);
}
void OpenGlContext::GenIndexBuffer(U32& obj)
{
glGenBuffers(1, &obj);
}
void OpenGlContext::DeleteIndexBuffer(U32& obj)
{
glDeleteBuffers(1, &obj);
}
void OpenGlContext::BindIndexBuffer(U32 obj)
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, obj);
}
void OpenGlContext::IndexBufferData(U32 size, const void *data, BufferUsage usage)
{
U32 usage_type = buffer_usage_map_[usage];
glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, usage_type);
}
void OpenGlContext::IndexBufferSubData(U32 size, const void *data)
{
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, size, data);
}
void* OpenGlContext::MapIndexBufferData(DataAccessType access)
{
U32 access_type = data_access_map_[access];
return glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, access_type);
}
void OpenGlContext::UnmapIndexBufferData()
{
glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
}
void OpenGlContext::VertexAttribPointer(U32 index, int size, DataType type, U32 stride, const void* ptr)
{
U32 data_type = data_type_map_[type];
glVertexAttribPointer(index, size, data_type, GL_FALSE, stride, ptr);
}
void OpenGlContext::EnableVertexAttribArray(U32 index)
{
glEnableVertexAttribArray(index);
}
void OpenGlContext::DeleteProgram(U32 program)
{
glDeleteProgram(program);
}
void OpenGlContext::BindProgram(U32 program)
{
glUseProgram(program);
}
void OpenGlContext::BindAttribLocation(U32 program, const char *name)
{
GLint ind = glGetAttribLocation(program, name);
assert(ind != -1);
glBindAttribLocation(program, ind, name);
}
void OpenGlContext::Uniform1i(U32 program, const char *name, int x)
{
GLint location = glGetUniformLocation(program, name);
assert(location != -1);
glUniform1i(location, x);
}
void OpenGlContext::Uniform1iv(U32 program, const char *name, const int *v, int n)
{
GLint location = glGetUniformLocation(program, name);
assert(location != -1);
glUniform1iv(location, n, v);
}
void OpenGlContext::Uniform2i(U32 program, const char *name, int x, int y)
{
GLint location = glGetUniformLocation(program, name);
assert(location != -1);
glUniform2i(location, x, y);
}
void OpenGlContext::Uniform3i(U32 program, const char *name, int x, int y, int z)
{
GLint location = glGetUniformLocation(program, name);
assert(location != -1);
glUniform3i(location, x, y, z);
}
void OpenGlContext::Uniform4i(U32 program, const char *name, int x, int y, int z, int w)
{
GLint location = glGetUniformLocation(program, name);
assert(location != -1);
glUniform4i(location, x, y, z, w);
}
void OpenGlContext::Uniform1f(U32 program, const char *name, float x)
{
GLint location = glGetUniformLocation(program, name);
assert(location != -1);
glUniform1f(location, x);
}
void OpenGlContext::Uniform2f(U32 program, const char *name, float x, float y)
{
GLint location = glGetUniformLocation(program, name);
assert(location != -1);
glUniform2f(location, x, y);
}
void OpenGlContext::Uniform3f(U32 program, const char *name, float x, float y, float z)
{
GLint location = glGetUniformLocation(program, name);
assert(location != -1);
glUniform3f(location, x, y, z);
}
void OpenGlContext::Uniform4f(U32 program, const char *name, float x, float y, float z, float w)
{
GLint location = glGetUniformLocation(program, name);
assert(location != -1);
glUniform4f(location, x, y, z, w);
}
void OpenGlContext::Uniform1fv(U32 program, const char *name, const float *v, int n)
{
GLint location = glGetUniformLocation(program, name);
assert(location != -1);
glUniform1fv(location, n, v);
}
void OpenGlContext::Uniform2fv(U32 program, const char *name, const float *v, int n)
{
GLint location = glGetUniformLocation(program, name);
assert(location != -1);
glUniform2fv(location, n, v);
}
void OpenGlContext::Uniform3fv(U32 program, const char *name, const float *v, int n)
{
GLint location = glGetUniformLocation(program, name);
assert(location != -1);
glUniform3fv(location, n, v);
}
void OpenGlContext::Uniform4fv(U32 program, const char *name, const float *v, int n)
{
GLint location = glGetUniformLocation(program, name);
assert(location != -1);
glUniform4fv(location, n, v);
}
void OpenGlContext::UniformMatrix2fv(U32 program, const char *name, const float *v, bool trans, int n)
{
GLint location = glGetUniformLocation(program, name);
assert(location != -1);
glUniformMatrix2fv(location, n, trans, v);
}
void OpenGlContext::UniformMatrix3fv(U32 program, const char *name, const float *v, bool trans, int n)
{
GLint location = glGetUniformLocation(program, name);
assert(location != -1);
glUniformMatrix3fv(location, n, trans, v);
}
void OpenGlContext::UniformMatrix4fv(U32 program, const char *name, const float *v, bool trans, int n)
{
GLint location = glGetUniformLocation(program, name);
assert(location != -1);
glUniformMatrix4fv(location, n, trans, v);
}
} // namespace scythe |
d1c0bc369b2082fe6f722d87c4b4ef658e4f5fc7 | e07e25bc29baf02b56f7397f7a174cbc2cfc5b6d | /src/cpp/array-pascal-triangle-rows/array.cpp | 0f7f5f410681c94f95385747e450004018d26f90 | [] | no_license | ANARCYPHER/coding-interview-solutions | a12848be333457725a45fe723551723776ef1d8f | 68452ab2bf7de438c3e4986dcd44502b1c0b69f6 | refs/heads/master | 2023-02-08T09:58:00.174509 | 2019-08-29T19:16:39 | 2019-08-29T19:16:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,475 | cpp | array.cpp | /**
* Given numRows, generate the first numRows of Pascal’s triangle.
* Pascal’s triangle : To generate A[C] in row R, sum up A’[C] and A’[C-1] from
* previous row R - 1.
*
* Example:
* Given numRows = 5,
*
* Return
*
* [
* [1],
* [1,1],
* [1,2,1],
* [1,3,3,1],
* [1,4,6,4,1]
* ]
*
* Explanation: the first and last elements of every row are always one. The
* others you just calculate using the above formula. Just the first row that
* is [1] needs to be placed manually in your answer, so start with it and then
* use the formula.
*/
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> generate(int n) {
vector<vector<int>> ans;
if (n >= 1) {
vector<int> row(1, 1);
ans.push_back(row);
}
for (int i = 1; i < n; i++) {
vector<int> row;
row.push_back(1);
for (int j = 1; j <= i - 1; j++) {
row.push_back(ans[i - 1][j] + ans[i - 1][j - 1]);
}
row.push_back(1);
ans.push_back(row);
}
return ans;
}
int main() {
int a = 22;
vector<vector<int>> r = generate(a);
cout << "Answer: " << endl;
for (int i = 0; i < r.size(); i++) {
for (int j = 0; j < r[i].size(); j++) {
cout << r[i][j] << " ";
}
cout << endl;
}
cout << endl;
cout << "Last line sum:" << endl;
int sum = 0;
for (int i = 0; i < r[r.size() - 1].size(); i++) {
sum += r[r.size() - 1][i];
}
cout << sum << endl;
return 0;
} |
88bbbd77e07d6338600c10561c1d8bf04bb22e9f | 77bfb7914b7981beddab79aa42e124be13ed36c0 | /cpp/cppsyntax/namespace/t1.cpp | bb33f057daca231a63126613797affd86e03e66c | [] | no_license | WarrenWFu/Testing-Programs | 538339c55b891f7066a05ea663003b74fac18dbc | d99dddc314fb695faff5f610615103baa525e2c4 | refs/heads/master | 2021-06-11T03:25:07.980400 | 2020-03-07T03:16:02 | 2020-03-07T03:17:53 | 90,715,555 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,075 | cpp | t1.cpp | /*******************************************************************************
*
* author:Warren Fu
* date:
* description:匿名命名空间中的变量可以被同一编译单元中的命名空间使用,但是不能
* 被其它编译单元中的函数使用和static一样,两者最大的却别是后者不能修饰class或
* struct的声明,基本可以将匿名命名空间看成是static修饰的全局变量
*
*******************************************************************************/
#include <iostream>
using namespace std;
extern void foo4();
//static class Foo//这句会报错,因为无法为一个声明在数据区分配空间
class Foo
{
public:
int num3;
};
namespace
{
string str1;
int num1 = 0;
Foo foo1;
class Foo5
{
public:
int num3;
};
}
static int num = 1;
static Foo foo2;
namespace UPP
{
int foo()
{
std::cout << "nothing" << std::endl;
std::cout << "from anonymous num:" << num << std::endl;
return 0;
}
}
int main()
{
using namespace UPP;
foo();
foo1.num3 = 1;
foo2.num3 = 2;
return 0;
}
|
df25f39a33201ca2a0aec92e9726e67c59d40c9e | 2f557f60fc609c03fbb42badf2c4f41ef2e60227 | /TrackingTools/Records/interface/TrackingComponentsRecord.h | 9f91ee274b079c8ec050ffc6b2c74dd5a82d6734 | [
"Apache-2.0"
] | permissive | CMS-TMTT/cmssw | 91d70fc40a7110832a2ceb2dc08c15b5a299bd3b | 80cb3a25c0d63594fe6455b837f7c3cbe3cf42d7 | refs/heads/TMTT_1060 | 2020-03-24T07:49:39.440996 | 2020-03-04T17:21:36 | 2020-03-04T17:21:36 | 142,576,342 | 3 | 5 | Apache-2.0 | 2019-12-05T21:16:34 | 2018-07-27T12:48:13 | C++ | UTF-8 | C++ | false | false | 708 | h | TrackingComponentsRecord.h | #ifndef RecoTracker_Record_TrackingComponentsRecord_h
#define RecoTracker_Record_TrackingComponentsRecord_h
#include "FWCore/Framework/interface/EventSetupRecordImplementation.h"
#include "FWCore/Framework/interface/DependentRecordImplementation.h"
#include "Geometry/Records/interface/GlobalTrackingGeometryRecord.h"
//#include "Geometry/Records/interface/IdealGeometryRecord.h"
#include "MagneticField/Records/interface/IdealMagneticFieldRecord.h"
#include "boost/mpl/vector.hpp"
class TrackingComponentsRecord: public edm::eventsetup::DependentRecordImplementation<TrackingComponentsRecord,
boost::mpl::vector<IdealMagneticFieldRecord, GlobalTrackingGeometryRecord> > {};
#endif
|
18bda702f24714f664275be79b247917300d551a | 7a02968aec8ae0a98f4e870fb802c6e550eab927 | /Algoritmen II/Labo04-Quadtrees/src/quad_tree.h | b923125b1871f7e25f165ff8cdc57d8e703f7c32 | [] | no_license | simong/Algoritmen | cc061bf00bcea2ad177b5d002f886f8ef998c202 | cc24e6fba01862a1222c518db77a5d40c9971f10 | refs/heads/master | 2020-12-30T10:12:48.733658 | 2011-12-07T20:48:26 | 2011-12-07T20:48:26 | 1,821,119 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,747 | h | quad_tree.h | #ifndef quad_tree_h
#define quad_tree_h
#include<vector>
#include<iostream>
struct point {
double x;
double y;
/*
point() : x(0), y(0){
}
point(double x, double y)
: x(x), y(y) {
}
*/
};
struct vertex {
point p;
/*
* -----------------------
* | | |
* | q2 | q1 |
* | | |
* | | |
* |-----------------------
* | | |
* | q3 | q4 |
* | | |
* -----------------------
*
*/
vertex *q1;
vertex *q2;
vertex *q3;
vertex *q4;
};
class quad_tree {
private:
vertex *root;
unsigned int max_depth;
public:
quad_tree() {
root = 0;
max_depth = 0;
}
// Voeg een punt toe aan de boom.
// Returned true als het punt werd toegevoegd, false als het er al in zat.
bool add(const point &p);
bool remove(const point &p);
// De hoogte van deze boom. (Dus het langst mogelijke pad).
unsigned int height();
void write();
private:
void depth_first(vertex* v, std::vector<point>& points);
void write(vertex *v);
};
bool quad_tree::add(const point &p) {
// We houden bij hoe diep we in de quadtree afdalen als we een
// punt toevoegen. (Voor de max diepte later in O(1) te kunnen bepalen.
unsigned int height = 0;
// We gebruiken een pointer naar pointer.
// Op deze manier kunnen we simpel met pointers schuiven.
vertex **v = &root;
// Zolang onze pointer nog altijd naar een bestaande pointer wijst,
// zit er een punt en moeten we verder opdelen.
while (*v != 0) {
// We dalen af in de boom.
height++;
// Kijk welke regio we moeten nemen.
if (p.x > (*v)->p.x && p.y > (*v)->p.y) {
v = &((*v)->q1);
}
else if (p.x < (*v)->p.x && p.y > (*v)->p.y) {
v = &((*v)->q2);
}
else if (p.x < (*v)->p.x && p.y < (*v)->p.y) {
v = &((*v)->q3);
}
else if (p.x > (*v)->p.x && p.y < (*v)->p.y) {
v = &((*v)->q4);
}
// Dit punt zit al in de tree.
// We returnen gewoon false.
else {
return false;
}
}
// We gaan een nieuwe knoop toevoegen.
// De padlengte vergroot met 1.
height++;
// Misschien is dit de maximum diepte van de boom
if (height > max_depth)
max_depth = height;
// Creer een nieuwe knoop.
*v = new vertex();
(*v)->p = p;
return true;
}
bool quad_tree::remove(const point &p) {
vertex **v = &root;
// 1. We gaan eerst op zoek naar de knoop die het punt bevat.
// 2. We zetten de vertex pointer die hier naar verwijst op 0
// 3. We voegen alle punten opnieuw toe.
// 1. De knoop zoeken.
while (*v != 0 && ((*v)->p.x != p.x && (*v)->p.y != p.y)) {
// We dalen af in de boom.
// Kijk welke regio we moeten nemen.
if (p.x > (*v)->p.x && p.y > (*v)->p.y) {
v = &((*v)->q1);
}
else if (p.x < (*v)->p.x && p.y > (*v)->p.y) {
v = &((*v)->q2);
}
else if (p.x < (*v)->p.x && p.y < (*v)->p.y) {
v = &((*v)->q3);
}
else if (p.x > (*v)->p.x && p.y < (*v)->p.y) {
v = &((*v)->q4);
}
}
// Als v == 0 dan zit het punt niet in de boom
if (*v == 0 || ((*v)->p.x != p.x && (*v)->p.y != p.y)) {
return false;
}
// We hebben de knoop gevonden. en *v wijst ernaar.
// 'v' is dus een pointer naar de pointer die naar de knoop wijst die het punt bevat.
// Kopieer de pointer
vertex* copy = *v;
// 2. We verwijderen de knoop.
*v = 0;
// 3. Alles onder deze knoop opnieuw toevoegen.
// In order
std::vector<point> points;
depth_first(copy->q1, points);
depth_first(copy->q2, points);
depth_first(copy->q3, points);
depth_first(copy->q4, points);
for (unsigned int i = 0; i < points.size(); i++) {
add(points[i]);
}
return true;
}
void quad_tree::write() {
if (root != 0) {
write(root);
}
}
void quad_tree::write(vertex* v) {
if (v != 0) {
std::cout << v->p.x << "," << v->p.y << std::endl;
write(v->q1);
write(v->q2);
write(v->q3);
write(v->q4);
}
}
void quad_tree::depth_first(vertex* v, std::vector<point>& points) {
if (v != 0) {
points.push_back(v->p);
depth_first(v->q1, points);
depth_first(v->q2, points);
depth_first(v->q3, points);
depth_first(v->q4, points);
}
}
unsigned int quad_tree::height() {
return max_depth;
}
#endif
|
09062c804c3a6101a1001091cce8f1b93389fadd | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-pipes/source/model/StartPipeResult.cpp | 016a1ef97113a4be52a69091af45f95fb4f19cd3 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 1,982 | cpp | StartPipeResult.cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/pipes/model/StartPipeResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::Pipes::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
StartPipeResult::StartPipeResult() :
m_currentState(PipeState::NOT_SET),
m_desiredState(RequestedPipeState::NOT_SET)
{
}
StartPipeResult::StartPipeResult(const Aws::AmazonWebServiceResult<JsonValue>& result) :
m_currentState(PipeState::NOT_SET),
m_desiredState(RequestedPipeState::NOT_SET)
{
*this = result;
}
StartPipeResult& StartPipeResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("Arn"))
{
m_arn = jsonValue.GetString("Arn");
}
if(jsonValue.ValueExists("CreationTime"))
{
m_creationTime = jsonValue.GetDouble("CreationTime");
}
if(jsonValue.ValueExists("CurrentState"))
{
m_currentState = PipeStateMapper::GetPipeStateForName(jsonValue.GetString("CurrentState"));
}
if(jsonValue.ValueExists("DesiredState"))
{
m_desiredState = RequestedPipeStateMapper::GetRequestedPipeStateForName(jsonValue.GetString("DesiredState"));
}
if(jsonValue.ValueExists("LastModifiedTime"))
{
m_lastModifiedTime = jsonValue.GetDouble("LastModifiedTime");
}
if(jsonValue.ValueExists("Name"))
{
m_name = jsonValue.GetString("Name");
}
const auto& headers = result.GetHeaderValueCollection();
const auto& requestIdIter = headers.find("x-amzn-requestid");
if(requestIdIter != headers.end())
{
m_requestId = requestIdIter->second;
}
return *this;
}
|
eac4f3b1a69a908e77185888cb4107d67e60193d | e06389fa0f80b61f717989d0fd6ee37cb96dd657 | /Client/include/Parser.hpp | 48ccf25b8ac8917a016701b3d3505012511aeef1 | [
"Apache-2.0"
] | permissive | uThings/Study-and-development-of-communication-protocol-between-an-aircraft-and-an-IoT-platform | 9ffb924e7a27d1a39e0de9722d6bb01a191ba9e5 | d6e47c7c0793a5feeb79ec970f5c4cba8f993ab2 | refs/heads/master | 2020-06-23T10:12:49.861122 | 2019-09-05T13:46:49 | 2019-09-05T13:46:49 | 198,593,782 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,084 | hpp | Parser.hpp | /****************************************
* Universita' degli Studi di Udine *
* Ingegneria Elettronica *
* Tesi di Laurea Triennale *
* Giacomo Andrioli - 133047 *
* File: Parser.hpp *
****************************************/
#ifndef PARSER
#define PARSER
#include <map>
#include <vector>
#include <exception>
#include <string>
#include <iostream>
#include <ctime>
#include "json.h"
namespace Parser
{
/*
* UTILITY (parser-utility.cpp)
*
* Classi enum:
* - Schema
* - Type
* - ControlType
* - SignalType
* Classi:
* - ParserException
* - Signal
* - Program
* Altro:
* - typedef
* - funzioni per timestamps
*/
typedef std::vector<std::pair<std::string,std::vector<std::string>>> SensorData;
typedef std::vector<std::pair<std::string,std::string>> StringStringMapVector;
enum class Schema { Undefined, Sensor, Action, Catalogue, Error};
std::ostream& operator<< (std::ostream& , const Schema&);
std::string SchemaToString(const Schema &);
Schema StringToSchema(const std::string &);
enum class Type { Undefined, Request, Response};
std::ostream& operator<< (std::ostream& , const Type&);
std::string TypeToString(const Type&);
Type StringToType(const std::string&);
enum class ControlType { Undefined, Signal, Program};
std::ostream& operator<< (std::ostream& , const ControlType&);
std::string ControlTypeToString(ControlType);
ControlType StringToControlType(std::string);
enum class SignalType { Undefined, Impulse, Step, Rect, Ramp, Triangle};
std::ostream& operator<< (std::ostream& , const SignalType&);
std::string SignalTypeToString(SignalType);
SignalType StringToSignalType(std::string);
// Timestamp utilities
std::string TimestampString();
std::string TimestampToString (const std::time_t&);
time_t StringToTimestamp (const std::string &);
class ParserException : public std::exception
{
friend std::ostream& operator<< (std::ostream & os, const ParserException& e);
private:
std::string message;
std::string where;
std::string error_code;
public:
ParserException(std::string what, std::string at = "", std::string code = "");
const char* what() const noexcept;
std::string at() const;
std::string code() const;
};
std::ostream& operator<< (std::ostream & os, const Parser::ParserException& e);
class Signal {
friend std::ostream& operator<< (std::ostream& os, const Signal& s);
private:
SignalType sig_type;
double sig_peak;
double sig_delay;
double sig_duration;
double sig_offset;
public:
// Costruttori
Signal();
Signal(const Json::Value& data);
// Selettori
SignalType GetSignalType() const;
double Peak() const;
double Delay() const;
double Duration() const;
double Offset() const;
void SetUndefined();
void SetImpulse(double peak, double delay);
void SetStep(double peak, double delay);
void SetRect(double peak, double delay, double duration);
void SetRamp(double peak, double delay, double duration, double offset);
void SetTriangle(double peak, double delay, double duration, double offset);
};
std::ostream& operator<< (std::ostream& os, const Parser::Signal& s);
class Program {
friend std::ostream& operator<<(std::ostream&, const Program&);
private:
unsigned int program_id;
StringStringMapVector parameter_list;
public:
// Costruttore
Program(unsigned int id = 0);
Program(const Json::Value& data);
// Selettori
unsigned int ProgramId();
StringStringMapVector ParameterList();
void ProgramId(unsigned int);
void ParameterList(const StringStringMapVector&);
};
std::ostream& operator<<(std::ostream&, const Program&);
/*
* (parser-message.cpp)
* - class Message
* - class MessageBody
*/
class Message {
friend std::ostream& operator<<(std::ostream & os, const Message & m);
protected:
std::string version;
Schema schema;
Type type;
std::string timestamp;
Json::Value body;
public:
// Metodi statici
static Type GetMessageType(const std::string&);
// Costruttori
Message();
Message(const std::string&);
// Selettori
std::string Version() const;
std::string Body() const;
Schema GetSchema() const;
Type GetType() const;
std::string Timestamp() const;
void Version(const std::string&);
void Body(const std::string&);
void SetSchema(const Schema&);
void SetType(const Type&);
void Timestamp(const std::string&);
// Metodi
bool IsHeaderParsed();
void ParseHeader(const std::string&);
std::string ToString() const;
};
std::ostream& operator<<(std::ostream& os, const Message& m);
/*
* Classe astratta per il body dei messaggi
*/
class MessageBody
{
public:
virtual ~MessageBody();
virtual void Parse(const Json::Value&);
virtual Json::Value ToJsonValue() const;
};
/*
* REQUESTS (parser-request.cpp)
*
* Classi:
* - SensorRequest
* - ActionRequest
* - CatalogueRequest: UNIMPLEMENTED
* - Request
*
*/
class SensorRequest : MessageBody
{
private:
unsigned int sensor_id;
unsigned int samples;
float frequency;
public:
// Costruttori
SensorRequest();
SensorRequest(const Json::Value& body);
SensorRequest(const std::string& body);
// Selettori
unsigned int SensorId();
unsigned int Samples();
float Frequency();
void SensorId(unsigned int);
void Samples(unsigned int);
void Frequency(float);
// Metodi
void Parse(const Json::Value&) override;
Json::Value ToJsonValue() const override;
};
class ActionRequest : MessageBody
{
private:
std::string subject;
std::string function;
ControlType control_type;
Signal* signal;
Program* program;
float expiration;
bool feedback;
public:
// Costruttori
ActionRequest();
ActionRequest(const Json::Value& body);
ActionRequest(const std::string& body);
// Selettori
std::string Subject() const;
std::string Function() const;
ControlType GetControlType() const;
Signal* GetSignal();
Program* GetProgram();
float Expiration() const;
bool Feedback() const;
void Subject(const std::string&);
void Function(const std::string&);
void SetControlType(const ControlType&);
void SetSignal(Signal*);
void SetProgram(Program*);
void Expiration(float);
void Feedback(bool);
// Metodi
void Parse(const Json::Value&) override;
Json::Value ToJsonValue() const override;
};
class CatalogueRequest : MessageBody {
// UNIMPLEMENTED
public:
CatalogueRequest();
};
class Request : public Message {
private:
SensorRequest* sensor;
ActionRequest* action;
CatalogueRequest* catalogue;
void CleanParsing();
public:
// Operatori
Request& operator=(const Request&);
// Costruttori, distruttori
Request();
Request(const std::string& message);
Request(const Request& request);
~Request();
// Selettori
SensorRequest& GetSensorRequest();
ActionRequest& GetActionRequest();
CatalogueRequest& GetCatalogueRequest();
void SetType(const Type&); // TODO
void SetSensorRequest(const SensorRequest&);
void SetActionRequest(const ActionRequest&);
void SetCatalogueRequest(const CatalogueRequest&);
// Metodi
bool IsBodyParsed();
void ParseFromBody();
void Parse(const std::string&);
};
/*
* RESPONSE (parser-response.cpp)
*
* Classi:
* - ErrorResponse
* - ActionResponse
* - SensorResponse
* - CatalogueResponse: UNIMPLEMENTED
* - Response
*
*/
class ErrorResponse : MessageBody {
private:
std::string code;
std::string error_type;
std::string at;
std::string what;
public:
// Costruttori
ErrorResponse();
ErrorResponse(const Json::Value& body);
ErrorResponse(const std::string& body);
// Selettori
std::string Code() const;
std::string ErrorType() const;
std::string At() const;
std::string What() const;
// Metodi set
void Code(const std::string&);
void ErrorType(const std::string&);
void At(const std::string&);
void What(const std::string&);
// Metodi
void Parse(const Json::Value&) override;
Json::Value ToJsonValue() const override;
};
class ActionResponse : MessageBody
{
private:
std::string subject;
std::string function;
ControlType control_type;
bool success;
bool expired;
std::string req_timestamp;
public:
// Costruttori
ActionResponse();
ActionResponse(const Json::Value& body);
ActionResponse(const std::string& body);
// Selettori
std::string Subject() const;
std::string Function() const;
ControlType GetControlType() const;
bool Success() const;
bool Expired() const;
std::string RequestTimestamp() const;
// Metodi set
void Subject(std::string);
void Function(const std::string&);
void SetControlType(ControlType);
void Success(bool);
void Expired(bool);
void RequestTimestamp(const std::string&);
// Metodi
void Parse(const Json::Value&) override;
Json::Value ToJsonValue() const override;
};
class SensorResponse : MessageBody
{
private:
unsigned int sensor_id;
unsigned int samples;
float frequency;
std::vector<std::pair<std::string,std::vector<std::string>>> data;
public:
// Costruttori
SensorResponse();
SensorResponse(unsigned int sensor_id);
SensorResponse(const Json::Value& body);
// Selettori
unsigned int SensorId() const;
unsigned int Samples() const;
float Frequency() const;
std::vector<std::pair<std::string,std::vector<std::string>>> Data() const;
void SensorId(unsigned int);
void Samples(unsigned int);
void Frequency(float);
void Data(const std::vector<std::pair<std::string,std::vector<std::string>>>&);
// Metodi
void Parse(const Json::Value&) override;
Json::Value ToJsonValue() const override;
};
class CatalogueResponse {
// UNIMPLEMENTED
public:
CatalogueResponse();
};
class Response : public Message {
private:
SensorResponse* sensor;
ActionResponse* action;
CatalogueResponse* catalogue;
ErrorResponse* error;
void CleanParsing();
public:
// Operatori
Response& operator=(const Response&);
// Costruttori, distruttori
Response();
Response(const std::string& message);
Response(const Response& response);
~Response();
// Selettori
SensorResponse& GetSensorResponse();
ActionResponse& GetActionResponse();
CatalogueResponse& GetCatalogueResponse();
ErrorResponse& GetErrorResponse();
void SetType(const Type&);
void SetSensorResponse(const SensorResponse&);
void SetActionResponse(const ActionResponse&);
void SetCatalogueResponse(const CatalogueResponse&);
void SetErrorResponse(const ErrorResponse&);
// Metodi
bool IsBodyParsed();
void ParseFromBody();
void Parse(const std::string&);
};
} // end namespace Parser
#endif |
41867af4d1d588ddfabf0f9a5e4cfa672f1c2e8f | ddb2b470f408769200d7d85df1dab94b9fc3eca9 | /02/w6/[01]/Project1/Project1/database.h | 02d716d3137eb67dbf3d1e7c82fe89bc79ad978f | [] | no_license | Enzzo/courcera | 39d7e896ac3142a2a94f9e853c81efebf684016d | 8c248c1169f81e82fc0b3a69fde7c93dc7128684 | refs/heads/master | 2022-12-23T00:25:32.372012 | 2020-10-01T19:48:48 | 2020-10-01T19:48:48 | 281,314,153 | 0 | 0 | null | 2020-07-30T01:36:20 | 2020-07-21T06:27:07 | C++ | UTF-8 | C++ | false | false | 756 | h | database.h | #pragma once
#include "date.h"
#include <string>
#include <map>
#include <vector>
#include <iostream>
#include <algorithm>
class WrongCommandException {
public:
WrongCommandException(const std::string& m) {
message += m;
}
const std::string what()const {
return message;
}
private:
std::string message = "Unknown command: ";
};
class Database {
public:
void Add(const Date&, const std::string&);
void Print(std::ostream&) const;
template<typename UnaryPredicate>
int RemoveIf(UnaryPredicate);
template<typename UnaryPredicate>
std::map<Date, std::vector<std::string>> FindIf(UnaryPredicate);
std::string Last(const Date&);
private:
std::map<Date, std::vector<std::string>> table;
}; |
9570cbe82aeec571f0879bc41bbcb0a06aab3c5d | a3c2787f52301dee40a9064e084bb8a157967e83 | /c++/上机/第六次上机/sort 实现选择法排序.cpp | 40cfa936ea641bddac98faccb655cb2d1e438646 | [] | no_license | welkin-qing/C | 509ea3807d84fe983be38c8c1c178bc7370008f7 | a812e1e1688b421a36f5645c1c1e37166bf5210c | refs/heads/master | 2020-03-17T20:49:34.799686 | 2018-07-17T06:35:50 | 2018-07-17T06:35:50 | 133,930,240 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 714 | cpp | sort 实现选择法排序.cpp | #include<iostream>
using namespace std;
// 你提交的代码将嵌入到这里
template <class T>
void Sort(T *p, int len)
{
int i,j;
T m=*p;
T t;
for(i=0;i<len-1;i++)
{
for(j=i;j<len;j++)
{
if(p[i]>p[j])
{
t=p[i];
p[i]=p[j];
p[j]=t;
}
}
}
for(i=0;i<len;i++)
{
cout<<p[i]<<"\t";
}
cout<<"\n";
}
int main( )
{
int n,m,*pn,i=0;
cin>>n;
pn=new int[n];
do{
cin>>pn[i];
i++;
}while(i<n);
double *pd;
i=0;
cin>>m;
pd=new double[m];
do{
cin>>pd[i];
i++;
}while(i<m);
Sort(pn,n);
Sort(pd,m);
delete [ ] pn;
delete [ ] pd;
return 0;
}
|
a97066b78988e38beec2df8c87fc8a5736527f7f | 0c8aed455ed1fc97ae001c2d9f4de5a81b1cf3be | /src/point.cc | c44dc5367f266a7d37393000a92fccd783feaaaa | [] | no_license | drichardson/opengl_examples | ecf7f65e133c3688c9636bbc75176d0053e8aa45 | 8fca1dc3cf1d116ff12d3842e3a8d18469fc1bcc | refs/heads/master | 2021-01-10T12:22:35.704124 | 2016-04-01T16:23:47 | 2016-04-01T16:23:47 | 55,087,206 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,337 | cc | point.cc | #include "shaders.h"
#include "window.h"
#include <GL/gl3w.h>
#include <cstdlib>
#include <iostream>
const char* vertex_shader_source =
"#version 410 core \n"
"void main() \n"
"{ \n"
" gl_Position = vec4(0, 0, 0, 1.0); \n"
"}\n";
const char* fragment_shader_source =
"#version 410 core\n"
"out vec4 color;\n"
"void main()\n"
"{\n"
" color = vec4(1, 0, 0, 1);\n"
"}\n";
int main()
{
common::Window* window = common::Window::CreateWindow();
window->LoadOpenGLCoreProfile();
window->MakeContextCurrent();
glViewport(0, 0, window->getWidth(), window->getHeight());
GLuint program = glCreateProgram();
bool ok = common::LinkProgram(program, vertex_shader_source, fragment_shader_source);
if (!ok)
{
std::cerr << "Error linking shaders.\n";
std::exit(1);
}
// The values in the vertex array are ignored by the vertex shader, but is required to get it to render a point.
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
auto render = [program]() {
constexpr GLfloat white[] = {1.0f, 1.0f, 1.0f, 1.0f};
glClearBufferfv(GL_COLOR, 0, white);
glUseProgram(program);
glPointSize(40.0f);
glDrawArrays(GL_POINTS, 0, 1);
};
window->RunLoop(render);
glDeleteVertexArrays(1, &vao);
return 0;
}
|
5b3661ef22830fc128e78112b6df8029d4b1563c | d81a9ef64fcccd532dcc0dae3235b709a2ff4ebe | /UVa/231/main.cpp | 1e6d238923c35f38a8be8dd09e9de886ce75061b | [] | no_license | Rodrigo61/GUAXINIM | 6d52b0b29dd736ce40295f7e7b3f7dd4c1d2396d | 696d1077bf69bcff10cb5c07bb68dd3452952228 | refs/heads/master | 2021-04-09T14:29:54.226309 | 2020-11-17T01:18:21 | 2020-11-17T01:18:21 | 125,520,161 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,125 | cpp | main.cpp | using namespace std;
bool debug = true;
//<editor-fold desc="GUAXINIM TEMPLATE">
/******** All Required Header Files ********/
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <queue>
#include <deque>
#include <bitset>
#include <iterator>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <numeric>
#include <utility>
#include <limits>
#include <time.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
using namespace std;
#define all(container) container.begin(), container.end()
#define mp(i,j) make_pair(i,j)
#define space " "
typedef pair<int,int> pii;
typedef vector<int> vi;
/// Debug Start
template<class T1> void deb(T1 e1)
{
if(debug) {
cout << "[DEBUG]";
cout << e1 << endl;
}
}
template<class T1,class T2> void deb(T1 e1, T2 e2)
{
if(debug) {
cout << "[DEBUG]";
cout << e1 << space << e2 << endl;
}
}
template<class T1,class T2,class T3> void deb(T1 e1, T2 e2, T3 e3)
{
if(debug) {
cout << "[DEBUG]";
cout << e1 << space << e2 << space << e3 << endl;
}
}
template<class T1,class T2,class T3,class T4> void deb(T1 e1, T2 e2, T3 e3, T4 e4)
{
if(debug) {
cout << "[DEBUG]";
cout << e1 << space << e2 << space << e3 << space << e4 << endl;
}
}
template<class T1,class T2,class T3,class T4,class T5> void deb(T1 e1, T2 e2, T3 e3, T4 e4, T5 e5)
{
if(debug) {
cout << "[DEBUG]";
cout << e1 << space << e2 << space << e3 << space << e4 << space << e5 << endl;
}
}
template<class T1,class T2,class T3,class T4,class T5,class T6> void deb(T1 e1, T2 e2, T3 e3, T4 e4 ,T5 e5, T6 e6)
{
if(debug) {
cout << "[DEBUG]";
cout << e1 << space << e2 << space << e3 << space << e4 << space << e5 << space << e6 << endl;
}
}
template<typename T>
void print_vector_debug(const T& t) {
if(debug) {
cout << "[DEBUG] VECTOR:";
for (auto i = t.cbegin(); i != t.cend(); ++i) {
if ((i + 1) != t.cend()) {
cout << *i << " ";
} else {
cout << *i << endl;
}
}
}
}
template<typename T>
void print_array_debug(const T arr, int size){
if(debug) {
cout << "[DEBUG] VECTOR:";
for (int i = 0; i < size; ++i) {
cout << arr[i] << space;
}
cout << endl;
}
}
template<typename T>
void print_2Darray_debug(const T arr, int rows, int cols){
if(debug) {
cout << "[DEBUG] Matrix:" << endl;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cout << arr[i][j] << space;
}
cout << endl;
}
cout << endl;
}
}
template<typename T>
void print_matrix_debug(const T& t) {
if(debug) {
cout << "[DEBUG] MATRIX:" << endl;
for (auto i = t.cbegin(); i != t.cend(); ++i) {
for(auto j = i->cbegin(); j != i->cend(); ++j){
cout << *j << " ";
}
cout << endl;
}
}
}
//</editor-fold desc="GUAXINIM TEMPLATE">
int LDS(vi &vet){
vi dp(vet.size());
dp[0] = 1;
int max_len = 0;
for (int i = 1; i < vet.size(); ++i) {
dp[i] = 1;
for (int j = i-1; j >= 0; --j) {
if(vet[j] >= vet[i]){
dp[i] = max(dp[i], dp[j]+1);
}
}
max_len = max(max_len, dp[i]);
}
return max_len;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
int height;
int test_count = 0;
bool first = true;
while(cin >> height, height != -1){
if(first){
first = false;
}else{
cout << endl;
}
vi heights;
do{
heights.push_back(height);
cin >> height;
}while(height != -1);
cout << "Test #" << ++test_count << ":" << endl;
cout << " maximum possible interceptions: " << LDS(heights) << endl;
}
return 0;
} |
22cd6309681fe0af0d0d9f1e655efbd143ec51c3 | 983cd7f4b325262789e07aad3e65ddace0f784f0 | /tron_coms/src/tron/coms/ComsChannel.h | f7bbc920e39f41a175866af341de55f4ffa0b7c5 | [] | no_license | albarral/tron | 0e3c27077a86f7b1a3f16c800b8f6baba472a5d4 | b2ce95ef5792dcf1e55e832af035d1686e63257d | refs/heads/master | 2021-07-16T13:41:58.408506 | 2018-11-30T13:40:37 | 2018-11-30T13:40:37 | 105,746,828 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,089 | h | ComsChannel.h | #ifndef __TRON_COMS_COMSCHANNEL_H
#define __TRON_COMS_COMSCHANNEL_H
/***************************************************************************
* Copyright (C) 2018 by Migtron Robotics *
* albarral@migtron.com *
***************************************************************************/
#include <string>
#include <log4cxx/logger.h>
#include <ignition/transport.hh>
namespace tron
{
// Base class for communication channel classes.
// A channel has an associated topic (an ignition transport concept) of the form: node/section/type/channel.
class ComsChannel
{
protected:
static log4cxx::LoggerPtr logger;
std::string topic; // topic name
bool bconnected; // channel is connected (has a registered publisher or subscriber)
public:
ComsChannel();
//~ComsChannel();
std::string getTopic() {return topic;};
void setTopic(std::string value) {topic = value;}
// connect channel
virtual bool connect(ignition::transport::Node& oNode) = 0;
bool isConnected() {return bconnected;};
};
}
#endif
|
f1c7c77894028eab71710f3c92a7e1add8bc3ee7 | 4197bd076ece04534b2f98053fc97458293fe8fa | /pqueue-doublylinkedlist.cpp | 31bc1e69dfe6fdbff769352c95fe7dc1c8e56db9 | [] | no_license | RSkhirtladze/PriorityQueue | 686c66958731a688a85abb4af4557ba4787c1d7c | f97063b67d0de7f1f7d26075a71bfc6353d06080 | refs/heads/main | 2023-03-12T23:47:14.413809 | 2021-03-05T14:25:41 | 2021-03-05T14:25:41 | 344,834,852 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,729 | cpp | pqueue-doublylinkedlist.cpp | /*************************************************************
* File: pqueue-doublylinkedlist.cpp
*
* Implementation file for the DoublyLinkedListPriorityQueue
* class.
*/
#include "pqueue-doublylinkedlist.h"
#include "error.h"
DoublyLinkedListPriorityQueue::DoublyLinkedListPriorityQueue() {
currSize = 0;
head = new Node;
tail = new Node;
head->next = tail;
head->prev = NULL;
tail->next = NULL;
tail->prev = tail;
}
DoublyLinkedListPriorityQueue::~DoublyLinkedListPriorityQueue() {
Node* ptr = head;
while (ptr != NULL) {
Node* tmp = ptr;
ptr = ptr -> next;
delete tmp;
}
}
int DoublyLinkedListPriorityQueue::size() {
return currSize;
}
bool DoublyLinkedListPriorityQueue::isEmpty() {
if (currSize == 0) return true;
return false;
}
void DoublyLinkedListPriorityQueue::enqueue(string value) {
Node* newNode = new Node;
newNode->str = value;
newNode->prev = head;
newNode->next = head->next;
newNode->next->prev = newNode;
head->next = newNode;
currSize++;
}
string DoublyLinkedListPriorityQueue::peek() {
Node* temp = new Node;
findMinStrNode(temp);
return temp->str;
}
string DoublyLinkedListPriorityQueue::dequeueMin() {
Node* temp = new Node;
findMinStrNode(temp);
string answer = temp->str;
temp->prev->next = temp->next;
temp->next->prev = temp->prev;
delete temp;
currSize--;
return answer;
}
void DoublyLinkedListPriorityQueue::findMinStrNode(Node* &minStrNode){
if (currSize == 0) error("index out of bounds");
minStrNode = head ->next;
Node* temp = head ->next;
while (temp != tail){
if (minStrNode->str > temp->str) minStrNode = temp;
temp = temp -> next;
}
}
|
95de8eb1c548a70408c682fa9da5f36a0203329d | 432e2a8da6db306a26d549028c19570aa3a3191c | /SeaWar/Bark.cpp | 2b9dcf0c38f429d98d8ba9c6f30a6df3588f5bf6 | [] | no_license | EvgeniyHolovko/SeaWar | 9641157ed06b4e950fc70f455a06e84d9248d4ec | f836f04e8c8facaa1f20d5d5dc17c809e98aa41a | refs/heads/master | 2021-01-11T13:41:48.510664 | 2018-09-14T18:12:46 | 2018-09-14T18:12:46 | 94,898,434 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 462 | cpp | Bark.cpp | #include "Bark.h"
#include "Mast.h"
using namespace std;
Bark::Bark(const Coordinate &coord, const Orientation orient)
{
for (int n = 0; n < AMOUNT_OF_BARK_MASTS; n++)
{
if (orient == HORIZONTAL)
{
masts_.push_back(new Mast(*new Coordinate(coord.getX() + n, coord.getY())));
}
else
{
masts_.push_back(new Mast(*new Coordinate(coord.getX(), coord.getY() + n)));
}
}
}
Bark::~Bark()
{
for (Mast* mast:masts_)
{
delete mast;
}
}
|
178474f00b8c308f1f15d75f5901eecd5f3ef834 | 54743e192abeb34f3cc3c110c03c33b3bdd0abe7 | /gamefinal/ConsoleApplication1/ConsoleApplication1/Main.cpp | eea73b010f738255090a843e5768672a3bb49b7d | [] | no_license | zaoad/1-2-project-serving-car-game- | 4a8e6dd51a158de9ce07eff838095b8709c2443a | 49c1f47aad4a913fdc06460445797196190e01c6 | refs/heads/master | 2020-03-14T16:07:21.712019 | 2019-12-12T08:03:49 | 2019-12-12T08:03:49 | 131,691,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 42,553 | cpp | Main.cpp | #include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <iostream>
#include <SFML/System.hpp>
#include <Windows.h>
#include "time.h"
#include <sstream>
#include <string.h>
#include <fstream>
#include "HighScore.h"
#include <random>
using namespace std;
using namespace sf;
int ppp;
int c = 0;
int zz = 1;
int cr = 1;
int j = 1;
int lev1 = 1;
int lev2= 2;
int lev3 = 3;
bool game = true;
bool release = true;
int main()
{
j = 1;
cr = 1;
srand(time(0));
sf::RenderWindow window(sf::VideoMode(1370, 680), "Survivor");
window.setVerticalSyncEnabled(true);
int count = 0;
static int flag=0;
//////sound/////
/* sf::SoundBuffer buffer0,buffer1,buffer2;
sf::Sound gari,horn,crash ;
if (!buffer0.loadFromFile("car1.wav"))
{
std::cout << "Error" << std::endl;
}
gari.setBuffer(buffer0);
gari.setVolume(60);
if (!buffer1.loadFromFile("horn.wav"))
{
std::cout << "Error" << std::endl;
}
horn.setBuffer(buffer1);
horn.setVolume(80);
if (!buffer2.loadFromFile("crash.wav"))
{
std::cout << "Error" << std::endl;
}
crash.setBuffer(buffer2);
crash.setVolume(80);
*/
goto main_menu;
main_menu:{
///////////main menu image//////////////////////
count = 0;
zz = 1;
j = 1;
cr = 1;
sf::Texture main_menu;
main_menu.loadFromFile("front.jpg");
sf::Sprite menu;
menu.setTexture(main_menu);
////////////////////////////////////////////////
sf::Music music, music1;
music.openFromFile("menusound.wav");
music.setVolume(40);
music1.openFromFile("highscoremusic.wav");
music1.setVolume(50);
////////////////////////////////////////////////////////////
music.play();
//////////////////////main menu//////////////////////////////
sf::Font title;
title.loadFromFile("text.ttf");
sf::Text ttl("Surviving Car", title, 90);
ttl.setStyle(sf::Text::Bold);
ttl.setColor(sf::Color::Black);
ttl.setPosition(900 / 2 - ttl.getGlobalBounds().width / 2, 150);
sf::Mouse::setPosition(sf::Vector2i(10, 100), window);
sf::Text menu_text[4];
window.draw(menu);
window.draw(ttl);
string str[] = { "New Game", "High Score", "Credit", "Exit" };
int k;
for (k = 0; k < 4; k++)
{
menu_text[k].setFont(title);
menu_text[k].setCharacterSize(45);
menu_text[k].setString(str[k]);
menu_text[k].setColor(sf::Color::Red);
menu_text[k].setPosition(550, 300 + k * 100);
window.draw(menu_text[k]);
}
while (window.isOpen())
{
sf::Event event;
sf::Vector2f mouse(sf::Mouse::getPosition(window));
while (window.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
window.close();
break;
case sf::Event::MouseButtonPressed:
if (release && (menu_text[0].getGlobalBounds().contains(mouse)))
goto level;
if (release && (menu_text[1].getGlobalBounds().contains(mouse)))
{
music.stop();
music1.play();
HighScore h;
HighScore HighScore();
h.draw(window);
goto main_menu;
}
if (release && (menu_text[2].getGlobalBounds().contains(mouse))){
goto credit_game;
}
if (release && (menu_text[3].getGlobalBounds().contains(mouse)))
goto exit_game;
release = false;
break;
case sf::Event::MouseButtonReleased:
release = true;
break;
}
}
window.draw(menu);
window.draw(ttl);
if (menu_text[0].getGlobalBounds().contains(mouse))
{
menu_text[0].setColor(sf::Color::Blue);
menu_text[0].setCharacterSize(55);
}
else
{
menu_text[0].setColor(sf::Color::Red);
menu_text[0].setCharacterSize(45);
}
if (menu_text[1].getGlobalBounds().contains(mouse))
{
menu_text[1].setColor(sf::Color::Green);
menu_text[1].setCharacterSize(55);
}
else
{
menu_text[1].setColor(sf::Color::Red);
menu_text[1].setCharacterSize(45);
}
if (menu_text[2].getGlobalBounds().contains(mouse))
{
menu_text[2].setColor(sf::Color::Cyan);
menu_text[2].setCharacterSize(55);
}
else
{
menu_text[2].setColor(sf::Color::Red);
menu_text[2].setCharacterSize(45);
}
if (menu_text[3].getGlobalBounds().contains(mouse))
{
menu_text[3].setColor(sf::Color::Magenta);
menu_text[3].setCharacterSize(55);
}
else
{
menu_text[3].setColor(sf::Color::Red);
menu_text[3].setCharacterSize(45);
}
window.draw(menu_text[0]);
window.draw(menu_text[1]);
window.draw(menu_text[2]);
window.draw(menu_text[3]);
window.display();
}
}
level:{
///////////main menu image//////////////////////
count = 0;
zz = 1;
sf::Texture level;
level.loadFromFile("front.jpg");
sf::Sprite level0;
level0.setTexture(level);
////////////////////////////////////////////////
sf::Music music, music1;
music.openFromFile("menusound.wav");
music.setVolume(40);
music1.openFromFile("highscoremusic.wav");
music1.setVolume(50);
////////////////////////////////////////////////////////////
music.play();
//////////////////////main menu//////////////////////////////
sf::Font title;
title.loadFromFile("text.ttf");
sf::Text ttl("LEVEL", title, 90);
ttl.setStyle(sf::Text::Bold);
ttl.setColor(sf::Color::Black);
ttl.setPosition(900 / 2 - ttl.getGlobalBounds().width / 2, 150);
sf::Mouse::setPosition(sf::Vector2i(10, 100), window);
sf::Text level_text[3];
window.draw(level0);
window.draw(ttl);
string str[] = { "Level 1", "Level 2", "Level 3" };
int k;
for (k = 0; k < 3; k++)
{
level_text[k].setFont(title);
level_text[k].setCharacterSize(45);
level_text[k].setString(str[k]);
level_text[k].setColor(sf::Color::Red);
level_text[k].setPosition(550, 300 + k * 100);
window.draw(level_text[k]);
}
while (window.isOpen())
{
sf::Event event;
sf::Vector2f mouse(sf::Mouse::getPosition(window));
while (window.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
window.close();
break;
case sf::Event::MouseButtonPressed:
if (release && (level_text[0].getGlobalBounds().contains(mouse)))
{
count = 0;
goto game1;
lev1 = 2;
}
if (release && (level_text[1].getGlobalBounds().contains(mouse)))
{
count = 51;
goto game1;
lev2 = 2;
}
if (release && (level_text[2].getGlobalBounds().contains(mouse)))
{
count = 95;
goto game1;
lev3 = 2;
}
release = false;
break;
case sf::Event::MouseButtonReleased:
release = true;
break;
}
}
window.draw(level0);
window.draw(ttl);
if (level_text[0].getGlobalBounds().contains(mouse))
{
level_text[0].setColor(sf::Color::Cyan);
level_text[0].setCharacterSize(55);
}
else
{
level_text[0].setColor(sf::Color::Red);
level_text[0].setCharacterSize(45);
}
if (level_text[1].getGlobalBounds().contains(mouse))
{
level_text[1].setColor(sf::Color::Green);
level_text[1].setCharacterSize(55);
}
else
{
level_text[1].setColor(sf::Color::Red);
level_text[1].setCharacterSize(45);
}
if (level_text[2].getGlobalBounds().contains(mouse))
{
level_text[2].setColor(sf::Color::Magenta);
level_text[2].setCharacterSize(55);
}
else
{
level_text[2].setColor(sf::Color::Red);
level_text[2].setCharacterSize(45);
}
window.draw(level_text[0]);
window.draw(level_text[1]);
window.draw(level_text[2]);
window.display();
}
}
credit_game:
{
sf::RenderWindow window(sf::VideoMode(1370, 690), "Moving a shape");
Texture t50,t51;
sf::Music music2;
music2.openFromFile("highscoremusic.wav");
music2.setVolume(50);
music2.play();
if (!t50.loadFromFile("credit.jpg"))
cout << "error" << endl;
t51.loadFromFile("zk.png");
Sprite Capture(t50),capture1(t51);
Capture.setPosition(0, 0);
capture1.setPosition(400, 250);
while (window.isOpen()){
sf::Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
window.close();
break;
}
}
if (sf::Keyboard::isKeyPressed)
{
if (event.key.code == sf::Keyboard::Escape)
goto main_menu;
}
window.clear();
window.draw(Capture);
window.draw(capture1);
window.display();
}
}
game1:
{
Texture t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t30, t31, t32, t33;
Texture t15, t16, t17, t18, t19, t20, t21, t22, t23, t24, t25, t26, t27, t28, t34,t35;
Texture t36, t37, t38,t39;
t15.loadFromFile("hgrass.png");
t30.loadFromFile("go.png");
t16.loadFromFile("carcanfly.png");
t1.loadFromFile("mcar1.png");
t2.loadFromFile("road1.png");
t3.loadFromFile("roadrun.png");
t4.loadFromFile("roadrun.png");
t5.loadFromFile("polz.png");
t6.loadFromFile("truckb.png");
t7.loadFromFile("road1.png");
t8.loadFromFile("race.png");
t9.loadFromFile("sondorz.png");
t10.loadFromFile("road1.png");
t11.loadFromFile("lalcarz.png");
t12.loadFromFile("taxib.png");
t13.loadFromFile("bluebb.png");
t14.loadFromFile("redbb.png");
t17.loadFromFile("sidewalk.png");
t18.loadFromFile("sidewalk.png");
t31.loadFromFile("firet.png");
t19.loadFromFile("mcar2.png");
t20.loadFromFile("mcar3.png");
t21.loadFromFile("mcar4.png");
t22.loadFromFile("bons.png");
t23.loadFromFile("b.png");
t24.loadFromFile("back3.png");
t25.loadFromFile("grass.png");
t26.loadFromFile("rasta.png");
t27.loadFromFile("hgrass.png");
t32.loadFromFile("back1.png");
t33.loadFromFile("ladeywlk.png");
t34.loadFromFile("baby.png");
t35.loadFromFile("countline.png");
t36.loadFromFile("scoreback.png");
t37.loadFromFile("scoreback.png");
t38.loadFromFile("scoreback.png");
t39.loadFromFile("scoreback.png");
Sprite car1(t1), ima(t2), border(t3), border1(t4), fish2(t5), fish3(t6), ima1(t7), truck1(t8), ambulance(t9);
Sprite race1(t11), race2(t12), race3(t13), race4(t14), side1(t17), side2(t18), grass(t25);
Sprite h1(t15), carfly(t16), car2(t19), car3(t20), car4(t21), bonus(t22), policeb(t23), sidebackground(t24), h0(t26), hf(t27), fire(t31), sidebackground1(t32);
Sprite lady(t33), baby(t34),line(t35),sback(t36),grasso(t37),h1o(t38),hfo(t39);
ima.setTexture(t2);
ima1.setTexture(t7);
//////////music/////
sf::Music musicc;
musicc.openFromFile("garirawaj.wav");
musicc.setVolume(60);
musicc.setLoop(true);
musicc.play();
sf::SoundBuffer buffer1,buffer2;
sf::Sound horn,crash;
if (!buffer1.loadFromFile("jumpsong.wav"))
{
std::cout << "Error" << std::endl;
}
horn.setBuffer(buffer1);
horn.setVolume(80);
if (!buffer2.loadFromFile("crash1.wav"))
{
std::cout << "Error" << std::endl;
}
crash.setBuffer(buffer2);
crash.setVolume(80);
if (zz == 1){
game = true;
cout << "zz 1" << endl;
}
else {
game = false;
}
int walk = 0;
int lal = 1;
int c = 1;
int bby = 1;
int ldy = 1;
int po = 1;
int fly = 30;
int car = 0;
int r3 = 1;
int r2 = 1;
int hol = 1;
int r1 = 1;
int blu = 1;
int am = 4;
int tr = 3;
int f3 = 2;
int f2 = 1;
int r4 = 1;
int beg = 1;
int num = 3;
int jump = 3, delay = 50;
int kk = 1;
int pol = 1;
int trk = 1; int fis2 = 1; int fis3 = 1; int ambu = 1; int r1st ; int r2nd = 1; int r3rd = 1; int r4th = 1;
while (window.isOpen()){
sf::Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
window.close();
break;
}
}
window.clear();
if (game){
cout << "zz 1" << endl;
c++;
fly++;
car++;
delay--;
r1++;
po++;
if (fly > 24){
if (car1.getGlobalBounds().intersects(truck1.getGlobalBounds()) || car1.getGlobalBounds().intersects(race1.getGlobalBounds()) || car1.getGlobalBounds().intersects(race2.getGlobalBounds()) || car1.getGlobalBounds().intersects(race3.getGlobalBounds()) || car1.getGlobalBounds().intersects(race4.getGlobalBounds()) || car1.getGlobalBounds().intersects(fish2.getGlobalBounds()) || car1.getGlobalBounds().intersects(fish3.getGlobalBounds()) || car1.getGlobalBounds().intersects(ambulance.getGlobalBounds()) || car1.getGlobalBounds().intersects(policeb.getGlobalBounds()) || car1.getGlobalBounds().intersects(lady.getGlobalBounds()) || car1.getGlobalBounds().intersects(baby.getGlobalBounds()))
{
j = j+1;
cout << "j=2" << endl;
//goto gameovr;
}
}
if (j == 2){//carmove
if (event.type == sf::Event::KeyPressed){
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)){
if (car1.getPosition().y > -600){
car1.move(0, -5);
car2.move(0, -5);
car3.move(0, -5);
car4.move(0, -5);
fire.move(0, -5);
}
Sleep(1);
}
}
if (event.type == sf::Event::KeyPressed){
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)){
if (car1.getPosition().y < 0){
car1.move(0, 5);
car2.move(0, 5);
car3.move(0, 5);
car4.move(0, 5);
fire.move(0, 5);
}
Sleep(1);
}
}
if (event.type == sf::Event::KeyPressed){
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)){
if (car1.getPosition().x > -47){
car1.move(-5, 0);
car2.move(-5, 0);
car3.move(-5, 0);
car4.move(-5, 0);
fire.move(-5, 0);
}
Sleep(1);
}
}
if (event.type == sf::Event::KeyPressed){
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)){
if (car1.getPosition().x < 260){
car1.move(5, 0);
car2.move(5, 0);
car3.move(5, 0);
car4.move(5, 0);
fire.move(5, 0);
}
Sleep(1);
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::LShift)){
horn.play();
}
//fly car
if (delay < 70){
if (event.type == sf::Event::KeyPressed){
if (sf::Keyboard::isKeyPressed(sf::Keyboard::LShift)){
if (jump > 0){
carfly.setPosition(car1.getPosition().x, car1.getPosition().y);
//car1.setPosition(100,100 );
car1.move(0, -4);
car2.move(0, -4);
car3.move(0, -4);
car4.move(0, -4);
fire.move(0, -4);
fly = 0;
jump = jump - 1;
delay = 100;
}
}
}
}
}
//vehiles stand still when people walk over
if (fly < 25)
{
carfly.move(0, -4);
}
if (fly == 24){
car1.move(0, -96);
car2.move(0, -96);
car3.move(0, -96);
car4.move(0, -96);
fire.move(0, -96);
}
//jump bonus
if (border.getPosition().y > 45){
border.setPosition(0, 0);
}
if (border1.getPosition().y > 45){
border1.setPosition(0, 0);
}
//car return
//////////////////////////********************************leval1***********************************///////////
if (count <= 50)
{
if (c % 500 == 499&&fish2.getPosition().y>750){
fis2 = 1;
int xx = rand() % 4;
if (xx == 0)
{
fish2.setPosition(0, 0);
}
if (xx == 1)
{
fish2.setPosition(100, 0);
}
if (xx == 2)
{
fish2.setPosition(190, 0);
}
if (xx == 3)
{
fish2.setPosition(270, 0);
}
}
if (c % 450 == 449 && fish3.getPosition().y>750)
{
fis3 = 1;
int xy = rand() % 4;
if (xy == 0)
{
fish3.setPosition(0, 0);
}
if (xy == 1)
{
fish3.setPosition(-90, 0);
}
if (xy == 2)
{
fish3.setPosition(90, 0);
}
if (xy == 3)
{
fish3.setPosition(180, 0);
}
}
if (c % 480 == 479 && truck1.getPosition().y>750)
{
trk = 1;
int xy = rand() % 4;
if (xy == 0)
{
truck1.setPosition(0, 0);
}
if (xy == 1)
{
truck1.setPosition(-90, 0);
}
if (xy == 2)
{
truck1.setPosition(-180, 0);
}
if (xy == 3)
{
truck1.setPosition(95, 0);
}
}
//bonusmove
if (c % 1000 == 900)
{
int xy = rand() % 4;
if (xy == 0)
bonus.setPosition(0, 0);
if (xy == 1)
bonus.setPosition(-90, 0);
if (xy == 2)
bonus.setPosition(-180, 0);
if (xy == 3)
bonus.setPosition(95, 0);
}
if (c % 600 == 599 && ambulance.getPosition().y>750)
{
ambu = 1;
int xy = rand() % 4;
ambulance.setPosition(0, 0);
if (xy == 0)
{
ambulance.setPosition(-270, 0);
}
if (xy == 1)
{
ambulance.setPosition(-190, 0);
}
if (xy == 2)
{
ambulance.setPosition(-90, 0);
}
if (xy == 3)
{
ambulance.setPosition(0, 0);
}
}
if (r1 % 600 == 590 && race1.getPosition().y>810){
//r1st = 1;
int xy = rand() % 4;
if (xy == 0){
race1.setPosition(0, 0);
}
if (xy == 1){
race1.setPosition(100, 0);
}
if (xy == 2){
race1.setPosition(190, 0);
}
if (xy == 3)
{
race1.setPosition(270, 0);
}
}
if (c % 700 == 669 && race2.getPosition().y>810){
int xy = rand() % 4;
r2nd = 1;
if (xy == 0){
race2.setPosition(0, 0);
}
if (xy == 1)
{
race2.setPosition(-90, 0);
}
if (xy == 2)
{
race2.setPosition(180, 0);
}
if (xy == 3)
{
race2.setPosition(95, 0);
}
}
if (c % 680 == 620 && race3.getPosition().y>810){
r3rd = 1;
int xy = rand() % 4;
if (xy == 0)
{
race3.setPosition(0, 0);
}
if (xy == 1)
{
race3.setPosition(-90, 0);
}
if (xy == 2)
{
race3.setPosition(-180, 0);
}
if (xy == 3)
{
race3.setPosition(95, 0);
}
}
if (c % 760 == 700 && race4.getPosition().y>810){
r4th = 1;
int xy = rand() % 4;
if (xy == 0)
{
race4.setPosition(0, 0);
}
if (xy == 1)
{
race4.setPosition(-90, 0);
}
if (xy == 2)
{
race4.setPosition(-175, 0);
}
if (xy == 3)
{
race4.setPosition(-275, 0);
}
}
}
////////////////////////////////*******************lavel2*********************?/////////////////////
if (count > 50 && count <= 100)
{
if (c % 410 == 400){
fis2 = 1;
int xx = rand() % 4;
if (xx == 0)
{
fish2.setPosition(0, 0);
}
if (xx == 1)
{
fish2.setPosition(100, 0);
}
if (xx == 2)
{
fish2.setPosition(190, 0);
}
if (xx == 3)
{
fish2.setPosition(270, 0);
}
}
if (c % 400 == 399)
{
fis3 = 1;
int xy = rand() % 4;
if (xy == 0)
{
fish3.setPosition(0, 0);
}
if (xy == 1)
{
fish3.setPosition(-90, 0);
}
if (xy == 2)
{
fish3.setPosition(90, 0);
}
if (xy == 3)
{
fish3.setPosition(180, 0);
}
}
if (c % 430 == 429)
{
trk = 1;
int xy = rand() % 4;
if (xy == 0)
{
truck1.setPosition(0, 0);
}
if (xy == 1)
{
truck1.setPosition(-90, 0);
}
if (xy == 2)
{
truck1.setPosition(-180, 0);
}
if (xy == 3)
{
truck1.setPosition(95, 0);
}
}
//bonusmove
if (c % 900 == 800)
{
int xy = rand() % 4;
if (xy == 0)
bonus.setPosition(0, 0);
if (xy == 1)
bonus.setPosition(-90, 0);
if (xy == 2)
bonus.setPosition(-180, 0);
if (xy == 3)
bonus.setPosition(95, 0);
}
if (c % 480 == 450)
{
ambu = 1;
int xy = rand() % 4;
ambulance.setPosition(0, 0);
if (xy == 0)
{
ambulance.setPosition(-270, 0);
}
if (xy == 1)
{
ambulance.setPosition(-190, 0);
}
if (xy == 2)
{
ambulance.setPosition(-90, 0);
}
if (xy == 3)
{
ambulance.setPosition(0, 0);
}
}
if (r1 % 510 == 500){
//r1st = 1;
int xy = rand() % 4;
if (xy == 0){
race1.setPosition(0, 0);
}
if (xy == 1){
race1.setPosition(100, 0);
}
if (xy == 2){
race1.setPosition(190, 0);
}
if (xy == 3)
{
race1.setPosition(270, 0);
}
}
if (c % 430 == 410){
int xy = rand() % 4;
r2nd = 1;
if (xy == 0){
race2.setPosition(0, 0);
}
if (xy == 1)
{
race2.setPosition(-90, 0);
}
if (xy == 2)
{
race2.setPosition(180, 0);
}
if (xy == 3)
{
race2.setPosition(95, 0);
}
}
if (c % 460 == 459){
r3rd = 1;
int xy = rand() % 4;
if (xy == 0)
{
race3.setPosition(0, 0);
}
if (xy == 1)
{
race3.setPosition(-90, 0);
}
if (xy == 2)
{
race3.setPosition(-180, 0);
}
if (xy == 3)
{
race3.setPosition(95, 0);
}
}
if (c % 530 == 500){
r4th = 1;
int xy = rand() % 4;
if (xy == 0)
{
race4.setPosition(0, 0);
}
if (xy == 1)
{
race4.setPosition(-90, 0);
}
if (xy == 2)
{
race4.setPosition(-175, 0);
}
if (xy == 3)
{
race4.setPosition(-275, 0);
}
}
}
//////////////////////////88888888*****level3******/////////////////////////
if (count > 100)
{
if (c % 380 == 379){
fis2 = 1;
int xx = rand() % 4;
if (xx == 0)
{
fish2.setPosition(0, 0);
}
if (xx == 1)
{
fish2.setPosition(100, 0);
}
if (xx == 2)
{
fish2.setPosition(190, 0);
}
if (xx == 3)
{
fish2.setPosition(270, 0);
}
}
if (c % 360 == 350)
{
fis3 = 1;
int xy = rand() % 4;
if (xy == 0)
{
fish3.setPosition(0, 0);
}
if (xy == 1)
{
fish3.setPosition(-90, 0);
}
if (xy == 2)
{
fish3.setPosition(90, 0);
}
if (xy == 3)
{
fish3.setPosition(180, 0);
}
}
if (c % 340 == 339)
{
trk = 1;
int xy = rand() % 4;
if (xy == 0)
{
truck1.setPosition(0, 0);
}
if (xy == 1)
{
truck1.setPosition(-90, 0);
}
if (xy == 2)
{
truck1.setPosition(-180, 0);
}
if (xy == 3)
{
truck1.setPosition(95, 0);
}
}
//bonusmove
if (c % 1100 == 1000)
{
int xy = rand() % 4;
if (xy == 0)
bonus.setPosition(0, 0);
if (xy == 1)
bonus.setPosition(-90, 0);
if (xy == 2)
bonus.setPosition(-180, 0);
if (xy == 3)
bonus.setPosition(95, 0);
}
if (c % 460 == 459)
{
ambu = 1;
int xy = rand() % 4;
ambulance.setPosition(0, 0);
if (xy == 0)
{
ambulance.setPosition(-270, 0);
}
if (xy == 1)
{
ambulance.setPosition(-190, 0);
}
if (xy == 2)
{
ambulance.setPosition(-90, 0);
}
if (xy == 3)
{
ambulance.setPosition(0, 0);
}
}
if (r1 % 375 == 370){
//r1st = 1;
int xy = rand() % 4;
if (xy == 0){
race1.setPosition(0, 0);
}
if (xy == 1){
race1.setPosition(100, 0);
}
if (xy == 2){
race1.setPosition(190, 0);
}
if (xy == 3)
{
race1.setPosition(270, 0);
}
}
if (c % 380 == 370){
int xy = rand() % 4;
r2nd = 1;
if (xy == 0){
race2.setPosition(0, 0);
}
if (xy == 1)
{
race2.setPosition(-90, 0);
}
if (xy == 2)
{
race2.setPosition(180, 0);
}
if (xy == 3)
{
race2.setPosition(95, 0);
}
}
if (c % 300 == 290){
r3rd = 1;
int xy = rand() % 4;
if (xy == 0)
{
race3.setPosition(0, 0);
}
if (xy == 1)
{
race3.setPosition(-90, 0);
}
if (xy == 2)
{
race3.setPosition(-180, 0);
}
if (xy == 3)
{
race3.setPosition(95, 0);
}
}
if (c % 330 == 320){
r4th = 1;
int xy = rand() % 4;
if (xy == 0)
{
race4.setPosition(0, 0);
}
if (xy == 1)
{
race4.setPosition(-90, 0);
}
if (xy == 2)
{
race4.setPosition(-175, 0);
}
if (xy == 3)
{
race4.setPosition(-275, 0);
}
}
}
//policebarricades move
if (policeb.getPosition().y>950)
{
//count++;
int xy = rand() % 2;
if (xy == 0)
policeb.setPosition(0, 0);
if (xy == 1)
policeb.setPosition(170, 0);
}
//people walker
lady.move(-2, .08);
walk++;
if (walk % 32 == 0){
walk++;
}
lady.setTextureRect(sf::IntRect(((walk % 32) / 8) * 27, 0, 25, 35));
if (lady.getPosition().x <= -630)
{
int xy = rand() % 5;
if (xy == 0)
{
lady.setPosition(0, 0);
}
if (xy == 1)
{
lady.setPosition(0, 100);
}
if (xy == 2)
{
lady.setPosition(0, 200);
}
if (xy == 3)
{
lady.setPosition(0, 300);
}
if (xy == 4)
{
lady.setPosition(0, 400);
}
}
if (lady.getGlobalBounds().intersects(race1.getGlobalBounds()))
race1.move(0, -2);
if (lady.getGlobalBounds().intersects(race2.getGlobalBounds()))
race2.move(0, -3);
if (lady.getGlobalBounds().intersects(race3.getGlobalBounds()))
race3.move(0, -4);
if (lady.getGlobalBounds().intersects(race4.getGlobalBounds()))
race4.move(0, -3);
if (lady.getGlobalBounds().intersects(fish2.getGlobalBounds()))
fish2.move(0, -3);
if (lady.getGlobalBounds().intersects(fish3.getGlobalBounds()))
fish3.move(0, -4);
if (lady.getGlobalBounds().intersects(truck1.getGlobalBounds()))
truck1.move(0, -2);
if (lady.getGlobalBounds().intersects(ambulance.getGlobalBounds()))
ambulance.move(0, -5);
baby.move(1.7, -.05);
walk++;
if (walk % 21 == 0){
walk++;
}
baby.setTextureRect(sf::IntRect(((walk % 21) / 7) * 30, 0, 30, 35));
if (baby.getPosition().x >= 699)
{
int xy = rand() % 5;
if (xy == 0)
{
baby.setPosition(0, 0);
}
if (xy == 1)
{
baby.setPosition(0,-200 );
}
if (xy == 2)
{
baby.setPosition(0, -110);
}
if (xy == 3)
{
baby.setPosition(0, 80);
}
if (xy == 4)
{
baby.setPosition(0, -510);
}
}
if (baby.getGlobalBounds().intersects(race1.getGlobalBounds()))
race1.move(0, -2);
if (baby.getGlobalBounds().intersects(race2.getGlobalBounds()))
race2.move(0, -3);
if (baby.getGlobalBounds().intersects(race3.getGlobalBounds()))
race3.move(0, -4);
if (baby.getGlobalBounds().intersects(race4.getGlobalBounds()))
race4.move(0, -3);
if (baby.getGlobalBounds().intersects(fish2.getGlobalBounds()))
fish2.move(0, -3);
if (baby.getGlobalBounds().intersects(fish3.getGlobalBounds()))
fish3.move(0, -4);
if (baby.getGlobalBounds().intersects(truck1.getGlobalBounds()))
truck1.move(0, -2);
if (baby.getGlobalBounds().intersects(ambulance.getGlobalBounds()))
ambulance.move(0, -2);
if (car1.getGlobalBounds().intersects(bonus.getGlobalBounds()))
{
jump = jump + 2;
bonus.setPosition(-1000, 0);
}
}
if (game)
{
fish2.move(0, 3.8);
fish3.move(0, 4.8);
truck1.move(0, 3);
ambulance.move(0, 5.5);
if (c > 300)
race1.move(0, 2.5);
if (c > 250)
race2.move(0, 4);
if (c > 350)
race3.move(0, 4.8);
if (c > 400)
race4.move(0, 3.9);
bonus.move(0, 2);
policeb.move(0, 3.2);
border.move(0, 2.5);
border1.move(0, 2.5);
hf.move(0, 4);
h0.move(0, 4);
h1.move(0, 4);
hfo.move(0, 4);
sback.move(0, 4);
h1o.move(0, 4);
//bonus not intersect with vehicles
if (bonus.getGlobalBounds().intersects(race1.getGlobalBounds()) || bonus.getGlobalBounds().intersects(truck1.getGlobalBounds()))
{
bonus.move(0, -5);
}
if (bonus.getGlobalBounds().intersects(fish2.getGlobalBounds()) || bonus.getGlobalBounds().intersects(race2.getGlobalBounds()) || bonus.getGlobalBounds().intersects(race4.getGlobalBounds()))
{
bonus.move(0, -3);
}
//vehicles not crush with each other
if (truck1.getGlobalBounds().intersects(race1.getGlobalBounds()))
{
truck1.move(0, -5);
}
if (truck1.getGlobalBounds().intersects(fish2.getGlobalBounds()) || truck1.getGlobalBounds().intersects(race2.getGlobalBounds()) || truck1.getGlobalBounds().intersects(race4.getGlobalBounds()))
{
truck1.move(0, -3);
}
if (race1.getGlobalBounds().intersects(fish2.getGlobalBounds()) || race1.getGlobalBounds().intersects(race2.getGlobalBounds()) || race1.getGlobalBounds().intersects(race4.getGlobalBounds()))
{
race1.move(0, -3);
}
//3 move vehicles not crush
if (fish2.getGlobalBounds().intersects(race2.getGlobalBounds()) || fish2.getGlobalBounds().intersects(race4.getGlobalBounds()))
{
fish2.move(0, -5);
}
if (fish2.getGlobalBounds().intersects(race3.getGlobalBounds()) || fish2.getGlobalBounds().intersects(fish3.getGlobalBounds()))
{
fish2.move(0, -2);
}
if (race2.getGlobalBounds().intersects(race4.getGlobalBounds()))
{
race2.move(0, -5);
}
if (race2.getGlobalBounds().intersects(race3.getGlobalBounds()) || race2.getGlobalBounds().intersects(fish3.getGlobalBounds()))
{
race2.move(0, -2);
}
if (race4.getGlobalBounds().intersects(race3.getGlobalBounds()) || race4.getGlobalBounds().intersects(fish3.getGlobalBounds()))
{
race4.move(0, -2);
}
//4 move vehicles not crush
if (fish3.getGlobalBounds().intersects(race3.getGlobalBounds()))
{
fish3.move(0, -5);
}
if (fish3.getGlobalBounds().intersects(ambulance.getGlobalBounds()))
{
fish3.move(0, -2);
}
if (race3.getGlobalBounds().intersects(ambulance.getGlobalBounds()))
{
race3.move(0, -2);
}
if (race1.getGlobalBounds().intersects(race2.getGlobalBounds()) || race1.getGlobalBounds().intersects(race3.getGlobalBounds()) || race1.getGlobalBounds().intersects(race4.getGlobalBounds()) || race1.getGlobalBounds().intersects(fish2.getGlobalBounds()) || race1.getGlobalBounds().intersects(fish3.getGlobalBounds()) || race1.getGlobalBounds().intersects(ambulance.getGlobalBounds()))
{
race1.move(0, -15);
}
if (j == 3)
{
game = FALSE;
flag = 1;
zz = 2;
}
if (h1.getPosition().y > 1900)
h1.setPosition(0, 0);
if (h0.getPosition().y > 1900)
h0.setPosition(0, 0);
if (hf.getPosition().y > 1900)
hf.setPosition(0, 0);
if (h1o.getPosition().y > 1900)
h1o.setPosition(0, 0);
if (sback.getPosition().y >1900)
sback.setPosition(0, 0);
if (hfo.getPosition().y > 1900)
hfo.setPosition(0, 0);
line.setPosition(400, 750);
side1.setPosition(495, 0);
side2.setPosition(864, 0);
h0.setOrigin(-408, 1180);
sback.setOrigin(-880, 1180);
h1.setOrigin(-408, 70);
h1o.setOrigin(-880, 70);
bonus.setOrigin(-690, 500);
hf.setOrigin(-408, 1830);
hfo.setOrigin(-880, 1830);
car1.setOrigin(-560, -600);
car2.setOrigin(-560, -600);
car3.setOrigin(-560, -600);
car4.setOrigin(-560, -600);
carfly.setOrigin(-560, -600);
ima.setPosition(510, 0);
grass.setPosition(410, 0);
grasso.setPosition(880, 0);
ima1.setPosition(510, 320);
border.setOrigin(-586, 0);
border1.setOrigin(-776, 0);
fish2.setOrigin(-527, 70);
fish3.setOrigin(-600, 70);
truck1.setOrigin(-700, 110);
ambulance.setOrigin(-790, 70);
if (c > 200)
{
race1.setOrigin(-530, 100);
if (lal == 1)
{
r1 = 1;
race1.setPosition(0, 0);
lal = 2;
}
}
if (c > 350)
{
race2.setOrigin(-610, 100);
if (blu == 1)
{
r2 = 1;
race1.setPosition(0, 0);
blu = 2;
}
}
if (c > 150)
{
race3.setOrigin(-700, 100);
if (hol == 1)
{
r3 = 1;
race3.setPosition(0, 0);
hol = 2;
}
}
if (c > 100)
{
race4.setOrigin(-790, 100);
if (beg == 1)
{
r4 = 1;
race1.setPosition(0, 0);
beg = 2;
}
}
fire.setOrigin(-530, -575);
sidebackground.setPosition(0, 0);
sidebackground1.setPosition(880, 0);
///////////9483*********counttttttttttttttttttttttttt/////////////////////////////////////
if (race1.getGlobalBounds().intersects(line.getGlobalBounds()))
{
count++;
race1.move(0,200);
}
if (race2.getGlobalBounds().intersects(line.getGlobalBounds()))
{
count++;
race2.move(0, 200);
}
if (race3.getGlobalBounds().intersects(line.getGlobalBounds()))
{
count++;
race3.move(0, 200);
}
if (race4.getGlobalBounds().intersects(line.getGlobalBounds()))
{
count++;
race4.move(0,200);
}
if (fish2.getGlobalBounds().intersects(line.getGlobalBounds()))
{
count++;
fish2.move(0,200);
}
if (fish3.getGlobalBounds().intersects(line.getGlobalBounds()))
{
count++;
fish3.move(0,200);
}
if (truck1.getGlobalBounds().intersects(line.getGlobalBounds()))
{
count++;
truck1.move(0,200);
}
if (ambulance.getGlobalBounds().intersects(line.getGlobalBounds()))
{
count++;
ambulance.move(0,200);
}
//********************************level2*****************************************/////////////////////////
if (count > 50 && j == 2){
policeb.setOrigin(-530, 200);
cout << "shhhhhhhhooootttttttt" << endl;
if (pol == 1)
{
policeb.setPosition(0, 0);
pol = 2;
}
fish2.move(0, 1.7);
fish3.move(0, 1.7);
truck1.move(0, 1.7);
ambulance.move(0, 1.7);
race1.move(0, 1.7);
race2.move(0, 1.7);
race3.move(0, 1.7);
race4.move(0, 1.7);
bonus.move(0, 1.7);
border.move(0, .5);
border1.move(0, .5);
hf.move(0, 1.5);
h0.move(0, 1.5);
h1.move(0, 1.5);
hfo.move(0, 1.5);
sback.move(0, 1.5);
h1o.move(0, 1.5);
}
/*********************************level3**************************//////////////////////////////
if (count > 100 && j == 2){
baby.setOrigin(-450, -400);
if (bby == 1)
{
baby.setPosition(0, 0);
bby = 2;
}
cout << "fuvkkkkkkkkk" << endl;
lady.setOrigin(-900, -200);
if (ldy == 1)
{
lady.setPosition(0, 0);
ldy = 2;
}
fish2.move(0, 1.9);
fish3.move(0, 1.9);
truck1.move(0, 1.9);
ambulance.move(0, 1.9);
race1.move(0, 1.9);
race2.move(0, 1.9);
race3.move(0, 1.9);
race4.move(0, 1.9);
bonus.move(0, 1.9);
policeb.move(0, 2);
border.move(0, 2);
border1.move(0, 2);
hf.move(0, 2);
h0.move(0, 2);
h1.move(0, 2);
hfo.move(0, 2);
sback.move(0, 2);
h1o.move(0, 2);
}
}
window.draw(ima);
window.draw(ima1);
window.draw(border);
window.draw(border1);
window.draw(policeb);
window.draw(fish2);
window.draw(fish3);
window.draw(truck1);
window.draw(ambulance);
window.draw(race1);
window.draw(race2);
window.draw(race3);
window.draw(race4);
window.draw(side1);
window.draw(side2);
window.draw(lady);
if (count>90)
window.draw(baby);
window.draw(sidebackground);
window.draw(sidebackground1);
window.draw(grass);
window.draw(grasso);
window.draw(hf);
window.draw(hfo);
window.draw(h1);
window.draw(h1o);
window.draw(h0);
window.draw(sback);
window.draw(bonus);
window.draw(ambulance);
window.draw(line);
if (fly >= 24 && car % 40 <= 10)
window.draw(car1);
if (fly >= 24 && car % 40 >= 10 && car % 40 <= 20)
window.draw(car2);
if (fly >= 24 && car % 40 >= 20 && car % 40 <= 30)
window.draw(car3);
if (fly >= 24 && car % 40 >= 30 && car % 40 < 40)
window.draw(car4);
if (fly < 25)
window.draw(carfly);
sf::Text text, text1;
sf::Font font, font1;
font.loadFromFile("text2.ttf");
font1.loadFromFile("text2.ttf");
text.setFont(font);
text1.setFont(font1);
char ch[20], ch1[20];
//nt count=10;
sprintf(ch, "Your Score:\n\n %d\n", count);
sprintf(ch1, "jump: %d", jump);
text.setString(ch);
text.setCharacterSize(20);
text.setPosition(890, 100);
text.setColor(sf::Color::Black);
window.draw(text);
text1.setString(ch1);
text1.setCharacterSize(20);
text1.setPosition(890, 300);
text1.setColor(sf::Color::Black);
// gari.play();
window.draw(text1);
if (!game&&c>70)
{
/*if (event.type == sf::Event::KeyPressed){
if (sf::Keyboard::isKeyPressed(sf::Keyboard::RShift))
{
cout << "key is pressed" << endl;
goto high_score;
}
}*/
// crash.play();
// gari.stop();
musicc.stop();
while(cr == 1){
crash.play();
cout << "k=1" << endl;
cr=2;
}
c--;
fish2.move(0, 0);
fish3.move(0, 0);
truck1.move(0, 0);
ambulance.move(0, 0);
race1.move(0, 0);
race2.move(0, 0);
race3.move(0, 0);
race4.move(0, 0);
bonus.move(0, 0);
policeb.move(0, 0);
border.move(0, 0);
border1.move(0, 0);
hf.move(0, 0);
h0.move(0, 0);
h1.move(0, 0);
//lady.move(2, -0.08);
//baby.move(-1.7, 0.05);
window.draw(car2);
window.draw(fire);
Texture t30;
t30.loadFromFile("go.png");
Sprite gameover(t30);
gameover.setPosition(500, 240);
//window.draw(gameover);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Return))
{
musicc.stop();
HighScore h;
ppp = h.score();
if (count > ppp)
{
goto scoring;
}
else goto main_menu;
}
else
{
musicc.stop();
sf::Font scre;
scre.loadFromFile("Lobster_1.3.otf");
std::stringstream sss;
sss << "Your Score: " << count;
sf::Text pp;
pp.setCharacterSize(70);
pp.setColor(sf::Color::Red);
pp.setFont(scre);
pp.setString(sss.str());
pp.setPosition(500,300);
/////////////////////////////////////////////
sf::Font fontt;
fontt.loadFromFile("Pacifico.ttf");
sf::Text textt;
textt.setFont(fontt);
textt.setString("Press ENTER to continue");
textt.setColor(sf::Color::Blue);
textt.setCharacterSize(40);
textt.setPosition(450, 550);
sf::Font fonttt;
fonttt.loadFromFile("Lobster_1.3.otf");
sf::Text texttt;
texttt.setFont(fonttt);
texttt.setString("gameover!");
texttt.setColor(sf::Color::Red);
texttt.setCharacterSize(70);
texttt.setPosition(530, 200);
// window.clear();
// crash.stop();
// gari.stop();
//window.draw(gameover);
window.draw(pp);
window.draw(textt);
window.draw(texttt);
//window.display();
//count = 0;
//goto main_menu;
}
}
window.display();
}
printf("%d", count);
}
scoring:
{
int xx = 1;
string name;
int aa;
bool flagg = false;
int ccc = count;
count = 0;
while (window.isOpen())
{
window.setFramerateLimit(300);
sf::Texture g_over;
g_over.loadFromFile("score.jpg");
sf::Sprite gover;
gover.setTexture(g_over);
gover.setPosition(0, 0);
sf::Font fnt;
fnt.loadFromFile("Pacifico.ttf");
sf::Text txt;
txt.setFont(fnt);
txt.setString("Enter your name & Press Enter key to save");
txt.setColor(sf::Color::Black);
txt.setCharacterSize(45);
txt.setPosition(900 / 2 - txt.getGlobalBounds().width / 2, 200);
sf::RectangleShape rct(sf::Vector2f(3, 40));
rct.setFillColor(sf::Color::Black);
rct.setPosition(900 / 2 - txt.getGlobalBounds().width / 2, 400);
rct.setScale(xx, xx);
bool br = 1;
sf::Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
window.close();
break;
case sf::Event::TextEntered:
if (event.text.unicode != 13 && event.text.unicode != 8)
{
name.push_back((char)event.text.unicode);
}
else if (event.text.unicode == 8)
{
if (!name.empty())
name.pop_back();
}
else
{
br = 0;
}
break;
break;
}
}
if (!br)
{
std::ofstream ofs("example.txt", std::ofstream::out);
ofs << name;
ofs << "\n";
ofs << ccc;
ofs.close();
}
sf::Font font;
font.loadFromFile("high.ttf");
sf::Text text;
text.setFont(font);
text.setString(name);
text.setColor(sf::Color::Black);
text.setCharacterSize(45);
text.setPosition(900 / 2 - text.getGlobalBounds().width / 2, 300);
// sf::Font xt;
// xt.loadFromFile("high.ttf");
sf::Text txtt;
txtt.setFont(font);
txtt.setString("Press ESCAPE key for the Main Menu");
txtt.setColor(sf::Color::Black);
txtt.setStyle(sf::Text::Bold);
txtt.setCharacterSize(50);
txtt.setPosition(900 / 2 - txtt.getGlobalBounds().width / 2, 650);
if (sf::Keyboard::isKeyPressed)
{
if (event.key.code == sf::Keyboard::Escape)
goto main_menu;
}
window.clear();
window.draw(gover);
window.draw(txt);
window.draw(txtt);
window.draw(text);
window.display();
}
}
exit_game:
{
return EXIT_SUCCESS;
}
}
|
03cc9bc4ab5ab956bd530010e86c42364543fae1 | d55aca34e55028f9ac7685ae583f5b20184722d5 | /skyrim_framework/MySkseExtension/MyPapyrusObjectReference.cpp | 9038088d62e1059ec437bcc2424e4c4dd2590769 | [] | no_license | rethesda/skse_framework-lampuiho | 076503fbdf39f5fa591bfb02d8546b45e6d53d59 | ddb467813bb1bf55fe108278ca09bbb6dc1f923b | refs/heads/master | 2023-03-16T14:04:00.540710 | 2016-02-07T06:34:53 | 2016-02-07T06:34:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,603 | cpp | MyPapyrusObjectReference.cpp | #include "MyPapyrusObjectReference.h"
#include "skse/GameRTTI.h"
#include <algorithm>
namespace papyrusObjectReference
{
void Container_for_each(TESObjectREFR* obj, std::function<void(TESForm*, UInt32)> del){
ContainerForEach iterator(obj, del);
return iterator();
}
ContainerForEach::ContainerForEach(TESObjectREFR* obj, std::function<void(TESForm*, UInt32)> del) : pObj(obj), pDel(del){}
void ContainerForEach::operator()(){
TESContainer* pContainer = DYNAMIC_CAST(pObj->baseForm, TESForm, TESContainer);
if (pContainer){
entries.reserve(pContainer->numEntries);
pContainer->Visit(*this);
}
ExtraContainerChanges* pXContainerChanges = static_cast<ExtraContainerChanges*>(pObj->extraData.GetByType(kExtraData_ContainerChanges));
if (pXContainerChanges && pXContainerChanges->data->objList)
pXContainerChanges->data->objList->Visit(*this);
}
bool ContainerForEach::Accept(TESContainer::Entry* pEntry){
if (pEntry)
if (pEntry->form && !DYNAMIC_CAST(pEntry->form, TESForm, TESLevItem))
entries.insert({ pEntry->form, pEntry->count });
return true;
}
bool ContainerForEach::Accept(InventoryEntryData* pEntry){
if (pEntry)
if (pEntry->type && !DYNAMIC_CAST(pEntry->type, TESForm, TESLevItem)){
SInt32 count = pEntry->countDelta;
auto it = entries.find(pEntry->type);
if (it != entries.end())
count += it->second;
if (count > 0)
if (pDel)
pDel(pEntry->type, count);
#ifdef _DEBUG
else
std::cout << "ContainerForEach:: pDel is empty. Cannot call delegate function." << std::endl;
#endif
}
return true;
}
}
|
3ff650e5d1c2beb491b7ff570420bbb1faa48718 | c26db506037704131aad29c0b45343e4407b9680 | /String/TASHIFT.cpp | 705b05d985d1a6319308804c128bc32f2da12046 | [] | no_license | lalitc375/Data-Structure-And-Algorithms | b9d805cc903f91da9b5e57f21320cea617d8a8ce | fc0f1e3a204aaec96ba721fb6bb239c5a6e5ae0e | refs/heads/master | 2021-01-17T02:25:58.108189 | 2017-04-14T05:35:08 | 2017-04-14T05:35:08 | 49,047,685 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,142 | cpp | TASHIFT.cpp | #include<bits/stdc++.h>
using namespace std;
void computeLPS(char * Patt,int M,int * LPS)
{
int len=0; //Length of Previous Longest Prefix Suffix
LPS[0]=0;
int i=1;
while(i<M)
{
if(Patt[i]==Patt[len])
{
++len;
LPS[i]=len;
++i;
}
else
{
if(len!=0)
{
len=LPS[len-1];
}
else
{
LPS[i]=0;
++i;
}
}
}
}
int main()
{
long N;
scanf("%ld",&N);
string A,B;
cin>>A;
cin>>B;
B+=B;
cout<<A<<endl;
cout<<B;
char * a=(char *)A.c_str();
char * b=(char *)B.c_str();
int M[N+2];
computeLPS(a,N,M);
long i=0,j=0;
while (i < N)
{
if (B[j] == A[i])
{
j++;
i++;
}
// mismatch after j matches
else if (i < N && B[j] != A[i])
{
// Do not match lps[0..lps[j-1]] characters,
// they will match anyway
if (j != 0)
j = M[j-1];
else
i = i+1;
}
}
return 0;
}
|
33b3754487cced074947464325a9f54d497dd3b5 | d07aa6846cb3b16a3ec8f4a3d9f2af597b3f0dae | /RDBMS_TeamE/RDBMS_TeamE/Tokenizer.cpp | 62b05798fbeec5438ffb86df28bde7b626c52a66 | [] | no_license | lancewest/CSCE315-RDBMS-TeamE | 7e6d13df809ca8cd410c78aa20a55253ba26a79d | 902659a1137334180bd3c89b72c186ce73f85e32 | refs/heads/master | 2020-12-06T17:20:25.482306 | 2014-07-26T20:12:22 | 2014-07-26T20:12:22 | 16,330,783 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,108 | cpp | Tokenizer.cpp | #include "Tokenizer.h"
#include <iostream>
Tokenizer::Tokenizer(){}
//For Rolling back transactions
void Tokenizer::checkpoint()
{
this->point = this->index;
}
//Useing in conjunction with checkpoint to roll back
void Tokenizer::back_Up()
{
this->index = this->point;
}
bool Tokenizer::consume_Token(string in)
{
if(this->index == this->tokens.size()) {
return false;
}
if(in == tokens[index].get_Value()) {
index++;
return true;
}
return false;
}
//Return token without consuming
Token Tokenizer::get_Token()
{
if(this->index == this->tokens.size()) {
return Token("", "");
}
return tokens[index];
}
/*First step to parse a command, this breaks it into tokens (simply strings) and puts
them in order in the tokenizer vector for the parse to parse from*/
Tokenizer::Tokenizer(string* text) : position(0), index(0), point(0)
{
vector<Token> possible_tokens;
possible_tokens.push_back(Token("OPEN", "command"));
possible_tokens.push_back(Token("CLOSE", "command"));
possible_tokens.push_back(Token("WRITE", "command"));
possible_tokens.push_back(Token("EXIT", "command"));
possible_tokens.push_back(Token("SHOW", "command"));
possible_tokens.push_back(Token("CREATE TABLE", "command"));
possible_tokens.push_back(Token("PRIMARY KEY", "keyword"));
possible_tokens.push_back(Token("UPDATE", "command"));
possible_tokens.push_back(Token("SET", "keyword"));
possible_tokens.push_back(Token("WHERE", "keyword"));
possible_tokens.push_back(Token("INSERT INTO", "command"));
possible_tokens.push_back(Token("VALUES FROM RELATION", "keyword"));
possible_tokens.push_back(Token("VALUES FROM", "keyword"));
possible_tokens.push_back(Token("select", "query"));
possible_tokens.push_back(Token("project", "query"));;
possible_tokens.push_back(Token("rename", "query"));
possible_tokens.push_back(Token("DELETE FROM", "command"));
possible_tokens.push_back(Token("VARCHAR", "literal"));
possible_tokens.push_back(Token("INTEGER", "literal"));
//operators
possible_tokens.push_back(Token("==", "condition operator"));
possible_tokens.push_back(Token("<-", "query operator"));
possible_tokens.push_back(Token("!=", "condition operator"));
possible_tokens.push_back(Token("<=", "condition operator"));
possible_tokens.push_back(Token(">=", "condition operator"));
possible_tokens.push_back(Token("<", "condition operator"));
possible_tokens.push_back(Token(">", "condition operator"));
possible_tokens.push_back(Token("+", "operator"));
possible_tokens.push_back(Token("-", "operator"));
possible_tokens.push_back(Token("JOIN", "operator"));
possible_tokens.push_back(Token("*", "operator"));
possible_tokens.push_back(Token("(", "opening parenthesis"));
possible_tokens.push_back(Token(")", "closing parenthesis"));
possible_tokens.push_back(Token("||", "conjunction"));
possible_tokens.push_back(Token(",", "comma"));
possible_tokens.push_back(Token("&&", "conjunction"));
possible_tokens.push_back(Token("\"", "quotes"));
possible_tokens.push_back(Token(";", "semicolon"));
//literals: VARCHAR INTEGER
while(this->position < text->size()) {
bool found_command = false;
for(Token& i: possible_tokens) {
if(this->match(text, position, i.get_Value())) {
this->tokens.push_back(i);
this->position += i.get_Value().size();
found_command = true;
break;
}
}
if(found_command == true) {
continue;
}
char c = (*text)[position];
if(isdigit(c)) {
Token temp(this->get_Integer(text, position), "digit");
this->tokens.push_back(temp);
this->position += temp.get_Value().size();
continue;
}
if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c == '_')) {
Token temp(this->get_Varchar(text, position), "relation name");
this->tokens.push_back(temp);
this->position += temp.get_Value().size();
continue;
}
//ignore everything else
else {
position++;
continue;
}
}
/*for(string& i: this->tokens) {
cout << i << " ";
}
*/
}
bool Tokenizer::match(string *text, int position, string exp)
{
string substring = text->substr(position, exp.size());
if (substring == exp) {
return true;
}
return false;
}
string Tokenizer::get_Integer(string* text, int position)
{
char c = (*text)[position];
string integer;
while(isdigit(c)) {
integer.push_back(c);
position++;
c = (*text)[position];
}
return integer;
}
string Tokenizer::get_Varchar(string* text, int position)
{
char c = (*text)[position];
string varchar;
while(isalnum(c) || (c == '_')) {
varchar.push_back(c);
position++;
c = (*text)[position];
}
return varchar;
}
void Tokenizer::increase_Index(int addend)
{
this->index += addend;
}
bool Tokenizer::is_One_Valid_Line()
{
int count = 0;
for(Token t : tokens) {
if( (t.get_Kind() == "command" || t.get_Kind() == "query operator"))
count++;
}
return count < 2;
}
|
466e3e99830cdf45d24565b4393d8cb7239640f9 | 7d271763ac289e075ae834dbae8bcc95ab710761 | /Expr_Command_Factory.h | 789d417bcbd5b661f949ab4f9f32a12e53350741 | [] | no_license | arvindnair/aooadassign5 | 6e1a407fb32092ede3d12ffc5b99abc3dbce6344 | 12fbce92e22eeba36be2f04c05f8c0674b10f005 | refs/heads/master | 2020-04-18T00:24:03.042381 | 2016-08-31T23:53:03 | 2016-08-31T23:53:03 | 67,081,779 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,092 | h | Expr_Command_Factory.h | //==============================================================================
/**
* Honor Pledge:
*
* I pledge that I have neither given nor received any help
* on this assignment.
*/
//==============================================================================
#ifndef _EXPR_COMMAND_FACTORY_H_
#define _EXPR_COMMAND_FACTORY_H_
#include <string>
#include <iostream>
#include <stdexcept>
#include <cstring>
#include <exception>
#include <cstdlib>
#include "Expr_Command.h" // for Expression Command.
#include "Num_Command.h" // for Number Command.
#include "Add_Command.h" // for Add Command.
#include "Subtract_Command.h" // for Subtract Command.
#include "Multiply_Command.h" // for Multiply Command.
#include "Divide_Command.h" // for Divide Command.
#include "Modulus_Command.h" // for Modulus Command.
#include "Left_Parenthesis_Command.h" // for Left Parenthesis Command.
#include "Right_Parenthesis_Command.h" // for Right Parenthesis Command.
#include "Binary_Command.h" // for Binary Command.
/**
* @class Expr_Command_Factory
*
* Implementation of Expression Factory Command.
*/
class Expr_Command_Factory
{
public:
/// Default constructor.
Expr_Command_Factory (void);
/// Destructor.
virtual ~Expr_Command_Factory (void) = 0;
/**
* Creates and returns a new Number Command object.
*
* @return New Number Command object.
*/
virtual Num_Command * create_num_command (int num) = 0;
/**
* Creates and returns a new Addition Command object.
*
* @return New Addition Command object.
*/
virtual Add_Command * create_add_command (void) = 0;
/**
* Creates and returns a new Subtract Command object.
*
* @return New Subtraction Command object.
*/
virtual Subtract_Command * create_subtract_command (void) = 0;
/**
* Creates and returns a new Multiply Command object.
*
* @return New Multiply Command object.
*/
virtual Multiply_Command * create_multiply_command (void) = 0;
/**
* Creates and returns a new Divide Command object.
*
* @return New Divide Command object.
*/
virtual Divide_Command * create_divide_command (void) = 0;
/**
* Creates and returns a new Modulus Command object.
*
* @return New Modulus Command object.
*/
virtual Modulus_Command * create_modulus_command (void) = 0;
/**
* Creates and returns a new Left Parenthesis Command object.
*
* @return New Left Parenthesis Command object.
*/
virtual Left_Parenthesis_Command * create_left_parenthesis_command (void) = 0;
/**
* Creates and returns a new Right Parenthesis Command object.
*
* @return New Right Parenthesis Command object.
*/
virtual Right_Parenthesis_Command * create_right_parenthesis_command (void) = 0;
private:
/// Copy Constructor.
Expr_Command_Factory (const Expr_Command_Factory &);
/// Assignment Operator.
const Expr_Command_Factory & operator = (const Expr_Command_Factory &);
};
#endif // !_EXPR_COMMAND_FACTORY_H_
|
b71349724a77e990f49040161c6a4467be276ee0 | 2a1bd24f4d4e0e1683d232c81f47800fbc59ee5d | /Seeed_TMG3993.h | 8bd2b4ba38f03582f3649cb359ed997f06574f3a | [
"MIT"
] | permissive | Seeed-Studio/Seeed_TMG3993 | 3f41c581c44515ccf2f0cdb15f9bdcf64aaa95d0 | 90a485c36546c2d92c5d7285ad637c77e9097a4a | refs/heads/master | 2021-06-20T17:47:36.592793 | 2020-12-14T00:30:08 | 2020-12-14T00:30:08 | 137,311,999 | 1 | 1 | MIT | 2020-12-14T00:30:09 | 2018-06-14T05:50:09 | C++ | UTF-8 | C++ | false | false | 5,299 | h | Seeed_TMG3993.h | /*
A library for Grove - Light&Gesture&Color&Proximity Sensor
Copyright (c) 2018 seeed technology co., ltd.
Author : Jack Shao
Create Time: June 2018
Change Log :
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef __SEEED_TMG3993_H__
#define __SEEED_TMG3993_H__
#if (ARDUINO >= 100)
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include <Wire.h>
#define TMG3993_DEFAULT_ADDRESS 0x39
//Register addresses
#define REG_RAM 0x00 //~0X7F
#define REG_ENABLE 0x80
#define REG_ATIME 0x81
#define REG_WTIME 0x83
#define REG_ALS_IT 0x84 //~0X87
#define REG_PROX_IT_L 0x89
#define REG_PROX_IT_H 0x8B
#define REG_IT_PERS 0x8C
#define REG_CONFIG1 0x8D
#define REG_PPULSE 0x8E
#define REG_CONTROL 0x8F
#define REG_CONFIG2 0x90
#define REG_REVID 0x91
#define REG_ID 0x92
#define REG_STATUS 0x93
#define REG_RGBC_DATA 0x94 //~9B
#define REG_PROX_DATA 0x9C
#define REG_POFFSET_NE 0x9D
#define REG_POFFSET_SW 0x9E
#define REG_CONFIG3 0x9F
//The following CONFIG registers have different definations under different modes
#define REG_CONFIG_A0 0xA0
#define REG_CONFIG_A1 0xA1
#define REG_CONFIG_A2 0xA2
#define REG_CONFIG_A3 0xA3
#define REG_CONFIG_A4 0xA4
#define REG_CONFIG_A5 0xA5
#define REG_CONFIG_A6 0xA6
#define REG_CONFIG_A7 0xA7
#define REG_CONFIG_A8 0xA8
#define REG_CONFIG_A9 0xA9
#define REG_CONFIG_AA 0xAA
#define REG_CONFIG_AB 0xAB
#define REG_CONFIG_AC 0xAC
#define REG_CONFIG_AE 0xAE
#define REG_CONFIG_AF 0xAF
#define REG_PBCLEAR 0xE3
#define REG_IFORCE 0xE4
#define REG_PICLEAR 0xE5
#define REG_CICLEAR 0xE6
#define REG_AICLEAR 0xE7
#define REG_GFIFO_N 0xFC
#define REG_GFIFO_S 0xFD
#define REG_GFIFO_W 0xFE
#define REG_GFIFO_E 0xFF
//Enable bits
#define ENABLE_PON 0x01
#define ENABLE_AEN 0x02
#define ENABLE_PEN 0x04
#define ENABLE_WEN 0x08
#define ENABLE_AIEN 0x10
#define ENABLE_PIEN 0x20
#define ENABLE_GEN 0x40
#define ENABLE_PBEN 0x80
//Status bits
#define STATUS_AVALID (1)
#define STATUS_PVALID (1<<1)
#define STATUS_GINT (1<<2)
#define STATUS_PBINT (1<<3)
#define STATUS_AINT (1<<4)
#define STATUS_PINT (1<<5)
#define STATUS_PGSAT (1<<6)
#define STATUS_CPSAT (1<<7)
class TMG3993 {
public:
TMG3993(uint8_t i2c_addr = TMG3993_DEFAULT_ADDRESS);
bool initialize(void) ;
//common
uint8_t getDeviceID(void) ;
void enableEngines(uint8_t enable_bits);
void setADCIntegrationTime(uint8_t atime);
void setWaitTime(uint8_t wtime);
void enableWaitTime12xFactor(bool enable); //CONFIG1 register
uint8_t getInterruptPersistenceReg();
void setInterruptPersistenceReg(uint8_t pers);
uint8_t getControlReg();
void setControlReg(uint8_t control);
uint8_t getCONFIG2();
void setCONFIG2(uint8_t config);
uint8_t getCONFIG3();
void setCONFIG3(uint8_t config);
uint8_t getSTATUS();
void clearPatternBurstInterrupts();
void forceAssertINTPin();
void clearProximityInterrupts();
void clearALSInterrupts();
void clearAllInterrupts();
//proximity
void setupRecommendedConfigForProximity();
void setProximityInterruptThreshold(uint8_t low, uint8_t high);
void setProximityPulseCntLen(uint8_t cnt, uint8_t len);
uint8_t getProximityRaw();
// if you have glasses on the sensor, then you should adjust the offset
// void setProximityOffsetNE(uint8_t offset);
// void setProximityOffsetSW(uint8_t offset);
//Color and ALS (Light)
void setALSInterruptThreshold(uint16_t low, uint16_t high);
void getRGBCRaw(uint16_t* R, uint16_t* G, uint16_t* B, uint16_t* C);
int32_t getLux(uint16_t R, uint16_t G, uint16_t B, uint16_t C);
int32_t getLux();
//Correlated Color Temperature (CCT)
int32_t getCCT(uint16_t R, uint16_t G, uint16_t B, uint16_t C);
int32_t getCCT();
//Gesture
//Gesture needs algorithm, which is pending on AMS's delievery.
//Will update this library as soon as we get the alglrithm from AMS.
private:
TwoWire* m_i2c;
uint8_t m_addr;
int readRegs(int addr, uint8_t* data, int len);
int writeRegs(uint8_t* data, int len);
};
#endif
|
27594a301baab8d9839495e48862a0c93a3b006a | ab654f701e67953c2d95afc224b0bfdc87cb947f | /ObjectRenderHandler.h | 77160e67bf80db8b8cd09964770cf1f198486ef0 | [] | no_license | TheFlyingPandaa/BitFrost | d22ff6e48176044d826d97417201d8a7daabdea5 | da01714d4d53232bd53cb71295b33be8ca9fc9ba | refs/heads/master | 2018-09-04T10:59:28.205924 | 2018-06-04T09:53:23 | 2018-06-04T09:53:23 | 117,720,970 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 976 | h | ObjectRenderHandler.h | #ifndef ORH_H
#define ORH_H
#include "RenderObject.h"
#include <functional>
#include <algorithm>
using namespace std::placeholders;
class ObjectRenderHandler
{
std::string objectFile;
std::vector<RenderObject*> renderObjects;
std::vector<RenderObject*> objectsToRender;
std::wstring * objNames;
std::wstring * textureNames;
DirectX::XMFLOAT3 * camPos;
void sortByDistance(const DirectX::XMVECTOR & camPos);
void removeBehind(const DirectX::XMVECTOR & camPos, const DirectX::XMVECTOR & lookAt);
//bool closes(RenderObject * a, RenderObject * b);
public:
ObjectRenderHandler();
ObjectRenderHandler(const char * objectFile);
~ObjectRenderHandler();
void loadObjects();
void loadBuffert(ID3D11Device *& device);
void setCamPosition(const DirectX::XMVECTOR & camPos, const DirectX::XMVECTOR & lookAt);
void setMatrix(const DirectX::XMMATRIX & view, const DirectX::XMMATRIX & proj);
void render(ID3D11DeviceContext *& gDevice);
};
#endif // !ORH_H
|
9d1dcd5d6b8dcd2a41f2f75c7d0e4faf33fe1e63 | 1036371595e16a40fc83c04526a8508f40eff57d | /Engine/Core/EngineCore.cpp | 1934bf02f49bf7a6f71fd05d8f694509d309f163 | [] | no_license | asocha/Engine | 5acc9a6ebcd64900b93afaabe33bdc836ac000bf | 38211e0cabb0248252a40b38e6b8707f82be4acd | refs/heads/master | 2021-01-10T14:00:58.431156 | 2016-02-15T19:49:04 | 2016-02-15T19:49:04 | 50,062,272 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,867 | cpp | EngineCore.cpp | //=====================================================
// EngineCore.cpp
// by Andrew Socha
//=====================================================
#include "EngineCore.hpp"
#include "Engine/Core/SignpostMemoryManager.hpp"
#ifndef NDEBUG
#undef new
const unsigned int TOTAL_MEMORY = 1 << 23;
void* operator new(size_t numBytes){
if (s_theMemoryManager == nullptr){
SignpostMemoryManager* memoryManager = (SignpostMemoryManager*)malloc(sizeof(SignpostMemoryManager));
new(memoryManager) SignpostMemoryManager(TOTAL_MEMORY);
}
return s_theMemoryManager->Alloc(numBytes, false, "Unknown File", 0);
}
void operator delete(void* ptr){
s_theMemoryManager->FreeObject(ptr);
}
void* operator new[](size_t numBytes){
return s_theMemoryManager->Alloc(numBytes, false, "Unknown File", 0);
}
void operator delete[](void* ptr){
s_theMemoryManager->FreeObject(ptr);
}
void* operator new(size_t numBytes, const char* file, unsigned int line){
if (s_theMemoryManager == nullptr){
SignpostMemoryManager* memoryManager = (SignpostMemoryManager*)malloc(sizeof(SignpostMemoryManager));
new(memoryManager) SignpostMemoryManager(TOTAL_MEMORY);
}
return s_theMemoryManager->Alloc(numBytes, true, file, line);
}
void operator delete(void* ptr, const char* /*file*/, unsigned int /*line*/){
s_theMemoryManager->FreeObject(ptr);
}
void* operator new[](size_t numBytes, const char* file, unsigned int line){
return s_theMemoryManager->Alloc(numBytes, true, file, line);
}
void operator delete[](void* ptr, const char* /*file*/, unsigned int /*line*/){
s_theMemoryManager->FreeObject(ptr);
}
#endif
void* operator new(size_t /*numBytes*/, void* buffer, const char* /*file*/, unsigned int /*line*/){
return buffer;
}
void operator delete(void* ptr, void* /*buffer*/, const char* /*file*/, unsigned int /*line*/){
SignpostMemoryManager::DestructObject(ptr);
} |
f92d16a709a09c9b25f7058e9bf458227f40a018 | 7aaad6a8642f53468b75b21f1f0c7892832b7b62 | /elastic-circuits/examples/matrix_power.cpp | 38e683ba5b53719a98232bffef657bfed953264a | [
"MIT"
] | permissive | lana555/dynamatic | a932459fe6e76242baa34c7dbe830bb91eef33a4 | 9930d2eba15b4b1f904911ff97e413ee9a415989 | refs/heads/master | 2023-08-09T23:38:10.623259 | 2023-07-24T14:39:14 | 2023-07-24T14:39:14 | 214,463,815 | 87 | 39 | MIT | 2020-05-12T17:12:21 | 2019-10-11T14:59:15 | C++ | UTF-8 | C++ | false | false | 384 | cpp | matrix_power.cpp | //========================================================================
// Matrix Power
//========================================================================
void matrix_power(int x[20][20], int row[20], int col[20], int a[20]) {
for (int k = 1; k < 20; k++) {
for (int p = 0; p < 20; p++) {
x[k][row[p]] += a[p] * x[k - 1][col[p]];
}
}
}
|
4ddae78faa140274c7298507732cab716814e654 | c48192f69e97858c344bf6d7f36824b5efc8e435 | /src/ThresholdsWidget.h | 908987698b140a00c695b0273a1c1aca2ac359ba | [] | no_license | zhaoshuguan/Wavelet-Denoising | cef5488b70f030c049be54849bd13c515704458e | 2ed3e37f8cea0f6884631836ab6907591595d7e1 | refs/heads/master | 2021-10-26T22:13:33.028537 | 2019-04-14T11:22:21 | 2019-04-14T11:22:21 | 106,982,462 | 0 | 0 | null | 2017-10-15T04:04:47 | 2017-10-15T04:04:47 | null | UTF-8 | C++ | false | false | 1,313 | h | ThresholdsWidget.h | #pragma once
#include <QWidget>
#include <src/AudioSignal.h>
#include <src/PlotManager.h>
namespace Ui { class ThresholdsWidget; }
class ThresholdsWidget : public QWidget
{
Q_OBJECT
public:
using SignalSource = AudioSignal::SignalSource;
explicit ThresholdsWidget(QWidget *parent = 0);
~ThresholdsWidget();
SignalSource signalSource() const;
void setSignalSource(const SignalSource &signalSource);
double maxThreshold() const;
void setMaxThreshold(double maxThreshold);
double threshold() const;
void setThreshold(double threshold);
signals:
void signalChanged(const SignalSource &signalSource);
void maxThresholdChanged(double maxThreshold);
void thresholdChanged(double threshold);
private slots:
void on_vsThresholdsLevel_valueChanged(int value);
void on_sbThresholdsLevel_valueChanged(int arg1);
private:
void replotSignal();
void replotThreshold();
void replotAverage();
void replotDensity();
SignalSource m_signalSource;
double m_maxThreshold;
double m_threshold = 0.0;
SignalSource m_signalDensity;
SignalSource m_signalAverage;
PlotManager::PlotData m_signalPlotData;
PlotManager::PlotData m_densityPlotData;
PlotManager::PlotData m_averagePlotData;
Ui::ThresholdsWidget *ui;
};
|
8950793935b6f1a915a7d188097daf87d6f69748 | 7e3c474bcb4daf3f651115b0dcf3ef7a86643186 | /scripts/ScriptZoneGameObjDef.h | f1aef656cb3ff2423cc0fa37a7cbcfc87173ce2f | [
"Apache-2.0",
"GPL-2.0-only"
] | permissive | TheUnstoppable/RenSharp | 0b5930722378fe0d1e6a814f5f7c226ed938a77f | 2a123c6018c18f3fc73501737d600e291ac3afa7 | refs/heads/master | 2022-12-22T08:16:33.958177 | 2020-09-30T08:58:04 | 2020-09-30T08:58:04 | 299,528,055 | 1 | 0 | Apache-2.0 | 2020-09-29T06:44:26 | 2020-09-29T06:44:26 | null | UTF-8 | C++ | false | false | 1,915 | h | ScriptZoneGameObjDef.h | /* Renegade Scripts.dll
Copyright 2017 Tiberian Technologies
This file is part of the Renegade scripts.dll
The Renegade scripts.dll 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, or (at your option) any later
version. See the file COPYING for more details.
In addition, an exemption is given to allow Run Time Dynamic Linking of this code with any closed source module that does not contain code covered by this licence.
Only the source code to the module(s) containing the licenced code has to be released.
*/
#ifndef TT_INCLUDE_SCRIPTZONEGAMEOBJDEF_H
#define TT_INCLUDE_SCRIPTZONEGAMEOBJDEF_H
#include "ScriptableGameObjDef.h"
namespace ZoneConstants
{
enum ZoneType {
TYPE_DEFAULT = 0,
TYPE_CTF,
TYPE_VEHICLE_CONSTRUCTION,
TYPE_VEHICLE_REPAIR,
TYPE_TIBERIUM_FIELD,
TYPE_BEACON,
TYPE_GDI_TIB_FIELD,
TYPE_NOD_TIB_FIELD,
TYPE_NAVAL_SPAWN,
};
};
class ScriptZoneGameObjDef : public ScriptableGameObjDef {
public:
ScriptZoneGameObjDef();
~ScriptZoneGameObjDef() {};
const PersistFactoryClass &Get_Factory() const;
bool Save(ChunkSaveClass &csave);
bool Load(ChunkLoadClass &cload);
uint32 Get_Class_ID() const;
PersistClass *Create() const;
bool Is_Valid_Config(StringClass& oError) {return true;}
const Vector3 &Get_Color() const {return Color;}
ZoneConstants::ZoneType Get_Type() const {return ZoneType;}
int Get_Preset_ID() const {return PresetID;}
#ifdef DDBEDIT
virtual void Dump (FileClass &file);
#endif
DECLARE_EDITABLE (ScriptZoneGameObjDef, ScriptableGameObjDef);
//protected: //DA
ZoneConstants::ZoneType ZoneType;
Vector3 Color;
bool unk;
bool CheckStarsOnly;
bool IsEnvironmentZone;
bool CheckC4;
int PresetID;
StringClass ModelName;
friend class ScriptZoneGameObj;
friend class PresetDump;
};
#endif |
85ee139ab16e07717cb5f2011ff0276111af4e80 | 284047fb958e867033fac5eb9893d0fce503d1cf | /chapter12/page424/main.cpp | d5702b9894229aebde42c6c3239e93199f1acccb | [] | no_license | liuxinyu123/cpp-primer | d8bbc4c209e077187221d6bdb12c1f88a0002cfb | 5f27e737de13df705fb7f5a57a4a5ac07cb24200 | refs/heads/master | 2021-01-13T16:42:45.948833 | 2017-02-22T15:01:32 | 2017-02-22T15:01:32 | 77,421,962 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 698 | cpp | main.cpp | #include <iostream>
#include <string>
#include <new>
using namespace std;
int main (int argc, char *argv[])
{
int *pia1 = new int[10];
int *pia2 = new int[10] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int *pia3 = new int[10] ();
string *psa1 = new string[10];
string *psa2 = new string[10] {"a", "an", "the", string (3, 'x')};
for (int i = 0; i < 10; ++i)
cout << *pia1++ << " ";
cout << endl;
for (int i = 0; i < 10; ++i)
cout << *pia2++ << " ";
cout << endl;
for (int i = 0; i < 10; ++i)
cout << *pia3++ << " ";
cout << endl;
for (int i = 0; i < 10; ++i)
cout << *psa1++ << " ";
cout << endl;
for (int i = 0; i < 10; ++i)
cout << *psa2++ << " ";
cout << endl;
return 0;
}
|
3bf06d286b75afaca19593633c086d7054ae50c6 | e6401526ee75b8cc1c1a4146ffc365a966398b42 | /Client/main.cpp | 9f45797321721e8857486a71b1c5e7ae9425c169 | [
"MIT"
] | permissive | sppmacd/sppmsg | a8bfa14adfae05f03fb697d0b8f4426b188153e3 | e570caa55fcd0a816794b6212cee281881b119db | refs/heads/master | 2022-09-03T04:56:03.775344 | 2020-05-31T10:17:42 | 2020-05-31T10:17:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,828 | cpp | main.cpp | #include "config.hpp"
using namespace sf;
using namespace std;
bool appRunning = true;
bool running = true;
vector<sf::String> logstr;
vector<sf::String> logstrTmp;
sf::String chatString;
TcpSocket sck;
vector<sf::String> issuedCommands;
int cmdIndex = -1;
sf::Mutex mutex;
View wndView(FloatRect(0.f, 0.f, 500.f, 500.f));
RenderWindow wnd;
Font font;
int caretPos = 0;
void updateLogStr();
void appendLogStr(sf::String str)
{
if(str.isEmpty())
return;
logstrTmp.push_back(str);
updateLogStr();
}
// called on resize or new log entry
// keep only 100 latest strings now
// TODO: implement scrolling back
void updateLogStr()
{
/*
std::vector<sf::String> newLogStr;
for(int j = logstrTmp.size() - min(logstrTmp.size(), (size_t)100); j < logstrTmp.size(); j++)
{
sf::String& str = logstrTmp[j];
sf::Text text(str, font, 16);
for(int i = 0; i < str.getSize(); i++)
{
size_t s1 = text.findCharacterPos(i + 1).x;
size_t s2 = wndView.getSize().x;
if(s1 > s2 || str[i] == '\n')
{
newLogStr.push_back(str);
str = str.substring(i + 1);
i = 0;
}
}
if(!str.isEmpty())
newLogStr.push_back(str);
}
*/
logstr = logstrTmp;
}
void send()
{
sf::Lock lock(mutex);
if(chatString == "\\\\")
{
running = false;
sck.disconnect();
}
else
{
Packet packet;
packet << chatString;
Socket::Status status1 = sck.send(packet);
if(status1 == Socket::Disconnected)
appendLogStr("Server closed!\n");
else if(status1 == Socket::Error)
appendLogStr("Unexpected error while sending data!\n");
}
}
void network()
{
while(running)
{
Packet packet2;
if(sck.receive(packet2) == Socket::Done)
{
sf::Lock lock(mutex);
sf::String text;
if(packet2 >> text)
{
appendLogStr(text + "\n");
wndView = View(FloatRect(0.f, 0.f, wnd.getSize().x, wnd.getSize().y));
updateLogStr();
}
}
else
{
running = false;
sck.disconnect();
}
}
}
void loop()
{
wnd.create(VideoMode(500, 500), "SPPMsg Client");
wnd.setFramerateLimit(60);
font.loadFromFile("font.ttf");
wnd.setView(wndView);
wnd.setKeyRepeatEnabled(true);
View guiView(FloatRect(0.f, 0.f, 500.f, 500.f));
while(running && wnd.isOpen())
{
Event e;
while(wnd.pollEvent(e))
{
if(e.type == Event::Closed)
running = false;
if(e.type == Event::Resized)
{
wndView.reset(FloatRect(0.f, 0.f, e.size.width, e.size.height));
guiView.reset(FloatRect(0.f, 0.f, e.size.width, e.size.height));
updateLogStr();
}
if(e.type == Event::KeyPressed && e.key.code == Keyboard::Return)
{
send();
issuedCommands.push_back(chatString);
chatString = "";
caretPos = 0;
}
else if(e.type == Event::TextEntered)
{
if(e.text.unicode == 8)
{
if(caretPos > 0)
{
chatString.erase(caretPos - 1);
caretPos--;
}
}
else if(e.text.unicode > 0x1F)
{
chatString.insert(caretPos, e.text.unicode);
caretPos += 1;
}
cmdIndex = -1;
}
if(e.type == Event::KeyPressed)
{
if(e.key.code == Keyboard::Up)
{
if(!issuedCommands.empty())
{
if(cmdIndex == -1)
{
cmdIndex = issuedCommands.size()-1;
chatString = issuedCommands[cmdIndex];
caretPos = chatString.getSize();
}
else
{
if(cmdIndex != 0)
cmdIndex--;
chatString = issuedCommands[cmdIndex];
caretPos = chatString.getSize();
}
}
}
else if(e.key.code == Keyboard::Down)
{
if(!issuedCommands.empty())
{
if(cmdIndex < issuedCommands.size()-1)
{
cmdIndex++;
chatString = issuedCommands[cmdIndex];
caretPos = chatString.getSize();
}
else
{
cmdIndex = -1;
chatString = "";
caretPos = 0;
}
}
}
else if(e.key.code == Keyboard::Left)
{
if(caretPos > 0)
caretPos--;
}
else if(e.key.code == Keyboard::Right)
{
if(caretPos <= chatString.getSize())
caretPos++;
}
}
}
{
sf::Lock lock(mutex);
wnd.clear(Color::White);
wnd.setView(wndView);
for(int i = 0; i < logstr.size(); i++)
{
Text tx(logstr[logstr.size() - i - 1], font, 16);
tx.setPosition(2, (wnd.getView().getSize().y - tx.getLocalBounds().height - 50.f - 20.f * i));
tx.setFillColor(Color::Black);
wnd.draw(tx);
}
}
wnd.setView(guiView);
RectangleShape rs(Vector2f(wnd.getView().getSize().x, 50.f));
rs.setPosition(0.f, wnd.getView().getSize().y-50.f);
rs.setFillColor(Color(200,200,200));
wnd.draw(rs);
Text tx2(chatString, font, 20);
tx2.setPosition(5, wnd.getView().getSize().y-50.f);
tx2.setFillColor(Color::Black);
tx2.setStyle(Text::Underlined);
wnd.draw(tx2);
RectangleShape rs2(Vector2f(3.f, 25.f));
rs2.setPosition(tx2.findCharacterPos(caretPos));
rs2.setFillColor(time(NULL) % 2 == 0 ? Color::Transparent : Color::Black);
wnd.draw(rs2);
wnd.display();
}
}
int main(int argc, char* argv[])
{
cout << "Starting SPPMsg Client..." << endl;
while(appRunning)
{
int port;
do
{
cin.clear();
cout << "Select port to connect (0 to exit app):" << endl;
cin >> port;
cin.ignore(100,'\n');
} while(cin.fail());
if(port == 0)
{
appRunning = false;
break;
}
cout << "Select Username: " << endl;
string username;
cin >> username;
cout << "Select Server IP: " << endl;
string ip;
cin >> ip;
bool attemptConnect = true;
bool skipConnect = false;
do
{
Socket::Status status;
if(!skipConnect)
status = sck.connect(ip, port);
if(status != Socket::Done)
{
cout << "Error: " << ((status==Socket::Disconnected ? "Disconnected" :
(status==Socket::Error ? ("Error" + to_string(errno)) : ("Unexpected error: "
+ to_string(status))))) << ". Do you want to try again? (Y/N)" << endl;
string str;
cin >> str;
if(str == "Y")
{
skipConnect = false;
continue;
}
else if(str == "N")
{
attemptConnect = false;
running = false;
}
else
{
cout << "Invalid String!" << endl;
skipConnect = true;
}
}
else
attemptConnect = false;
} while(attemptConnect);
Thread guiThread(loop);
guiThread.launch();
Thread networkThread(network);
networkThread.launch();
Packet packet1;
packet1 << sf::String("/username " + username);
sck.send(packet1);
guiThread.wait();
}
return 0;
}
|
d7e8f1729dc44999d095062a7f40c7f887a4b009 | 418aa6c4486e255f482b6c9bee12a08cda829503 | /Graphic11/importer/parallelloader.cpp | f66ce2942367fafacaf8e8e54a259c256c0d84b3 | [
"MIT"
] | permissive | jjuiddong/Common | b21c9a98474fc45aa30b316808498381c2030ad3 | 3097b60988464000e2885a07cdd6e433e43de386 | refs/heads/master | 2023-08-31T07:35:31.425468 | 2023-08-29T11:38:29 | 2023-08-29T11:38:29 | 77,737,521 | 3 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 51 | cpp | parallelloader.cpp |
#include "stdafx.h"
#include "parallelloader.h"
|
31bcc874e48cf459175d3581556b791665a2bd84 | 002ea88912f32010770099045102c1e91f327de1 | /二进制枚举.cpp | efe927fd2e840c133782f7a6fe1764f29e61777d | [] | no_license | Haut-Stone/algorithm | 2c95a2ce5ba186ce34efa311e6a0eb3aa5f82b6a | 92d28d32faa13a4fc024b9087b88d9cff31126c5 | refs/heads/master | 2020-12-24T06:47:17.654946 | 2018-02-26T13:17:51 | 2018-02-26T13:17:51 | 73,398,865 | 6 | 1 | null | 2018-02-26T13:17:52 | 2016-11-10T16:12:32 | C++ | UTF-8 | C++ | false | false | 598 | cpp | 二进制枚举.cpp | /*
* Created by ShiJiahuan(li) in haut.
* for more please visit www.shallweitalk.com
*
* Copyright 2017 SJH. All rights reserved.
*
* @Author: Haut-Stone
* @Date: 2017-06-08 14:02:34
* @Last Modified by: Haut-Stone
* @Last Modified time: 2017-10-18 12:30:47
*/
//简介的二进制枚举方式,在搜索中比较好用。。
//
#include <iostream>
using namespace std;
int n;
int a[20];
int main(void)
{
//简单形式的二进制枚举方式
for(int i=0;i< 1<<n;i++){
for(int j=0;j<n;j++){
a[n-j-1] = i>>j&1;//这里从右向左,依次填充a[i]的状态
}
}
return 0;
} |
7b2fb46566aac5be0dcb5db896a9b21098befd36 | 1f74553b050b88a3484f6d3d93fa09f8aaa9a826 | /Homework/bai179_sothuannguyento.cpp | b58dce12a9b4f4e1f3c57e64e09f27b85ee63ce2 | [] | no_license | dattocngan/THCS2_PTIT | 2e970942ee28a87b0c66d31667185b1c1e58e340 | edbf6b944a0f3cf0065b02c49ed83b7c39c1526a | refs/heads/main | 2023-04-29T06:36:45.770537 | 2021-05-19T16:35:24 | 2021-05-19T16:35:24 | 345,918,636 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 678 | cpp | bai179_sothuannguyento.cpp | #include<stdio.h>
#include<math.h>
int checkPrime(int n){
if( n <= 1 ) return 0;
if( n == 2 ) return 1;
int i;
for( i = 2 ; i <= sqrt(n) ; i++ ){
if( n % i == 0 ) return 0;
}
return 1;
}
int tongChuSo(int n){
int sum = 0;
while(n != 0){
int a = n % 10;
if(checkPrime(a) == 0) return 0;
sum += a;
n/=10;
}
if(checkPrime(sum) == 1) return 1;
return 0;
}
int main(){
int t;
scanf("%d",&t);
while(t--){
int a,b;
scanf("%d%d",&a,&b);
if(a > b){
int temp = a;
a = b;
b = temp;
}
int count = 0;
for(int i = a; i <= b ; i++){
if(tongChuSo(i) == 1){
if(checkPrime(i) == 1) count++;
}
}
printf("%d\n",count);
}
return 0;
}
|
21dfd2cdf4e91996f1e18925c5078dae5c98907f | 52e389503307fd16c76b9f297d64ed715051ac29 | /1080.cpp | 3b2096dc0c00a940cbee74a5f1a58b21c3fb1f95 | [] | no_license | KWONDU/BOJ | 7fe50f8d577d2f2e578861307dd19e42fbd58ada | e2371e2e4e5da3a406467820a77a0b8ed2196714 | refs/heads/main | 2023-07-17T06:13:12.993379 | 2021-08-24T10:50:14 | 2021-08-24T10:50:14 | 393,856,300 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,210 | cpp | 1080.cpp | #include <iostream>
#include <string>
using namespace std;
int main () {
ios_base::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int n, m;
cin >> n >> m;
char a[50][50], b[50][50];
for (int i = 0; i < n; i++) {
string tempstr;
cin >> tempstr;
for (int j = 0; j < m; j++)
a[i][j] = tempstr[j];
}
for (int i = 0; i < n; i++) {
string tempstr;
cin >> tempstr;
for (int j = 0; j < m; j++)
b[i][j] = tempstr[j];
}
int cnt = 0;
for (int i = 0; i <= n - 3; i++) {
for (int j = 0; j <= m - 3; j++) {
if (a[i][j] == b[i][j])
continue;
cnt++;
for (int x = i; x < i + 3; x++)
for (int y = j; y < j + 3; y++) {
if (a[x][y] == '0')
a[x][y] = '1';
else
a[x][y] = '0';
}
}
}
for (int x = 0; x < n; x++) {
for (int y = 0; y < m; y++)
if (a[x][y] != b[x][y]) {
cout << "-1";
return 0;
}
}
cout << cnt;
return 0;
} |
afda7705071672b746654a106de193dd8f6d21f3 | 9a185924bcb1e70eff953a10e7754a443d1254b1 | /main.cpp | 5fc0d475b405de5fc21ca862454b514f19c9707f | [] | no_license | ubelian/OpenGL3 | 8ed77980d10a76a1719b1117d624182a73c9cc9f | a70c9f48e8fa4da6e5acec5d50212e6654c759d9 | refs/heads/master | 2020-03-26T00:05:09.006627 | 2018-08-10T16:02:35 | 2018-08-10T16:02:35 | 144,305,775 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,128 | cpp | main.cpp | #include "main.h"
OglRenderer app;
void keyCallback(GLFWwindow *window, int key, int scancode, int action, int mode);
int main() {
glfwSetTime(0);
app.addRectangle(-0.1f, 0.0f, 0.0f, -0.1f);
app.getCurrentObject(0).translate(glm::vec3(0.0f, 0.1f, 0.0f));
app.run();
}
void keyCallback(GLFWwindow *window, int key, int scancode, int action, int mode) {
static GLfloat zBuffer = 0.0f;
switch (key) {
case GLFW_KEY_ESCAPE:
if(action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
break;
case GLFW_KEY_UP:
if (action != GLFW_RELEASE) {
app.getCurrentObject(0).translate(0.0f, 0.1f, 0.0f);
//app.getCurrentObject(0).translate(0.0f, 0.1f, 0.0f);
}
break;
case GLFW_KEY_DOWN:
if (action != GLFW_RELEASE) {
app.getCurrentObject(0).translate(0.0f,-0.1f, 0.0f);
//app.getCurrentObject(0).translate(0.0f, -0.1f, 0.0f);
}
break;
case GLFW_KEY_LEFT:
if (action != GLFW_RELEASE) {
//app.getCurrentObject(1).translate(-0.1f, 0.0f, 0.0f);
app.getCurrentObject(0).translate(-0.1f, 0.0f, 0.0f);
}
break;
case GLFW_KEY_RIGHT:
if (action != GLFW_RELEASE) {
//app.getCurrentObject(1).translate(0.1f, 0.0f, 0.0f);
app.getCurrentObject(0).translate(0.1f, 0.0f, 0.0f);
}
break;
case GLFW_KEY_KP_0:
if (action == GLFW_PRESS) {
zBuffer = zBuffer - 0.1f;
std::cout << "z buffer = " << zBuffer << std::endl;
app.getCurrentObject(0).translate(0.0f, 0.0f, -0.1f);
}
break;
case GLFW_KEY_KP_1:
if (action == GLFW_PRESS) {
zBuffer = zBuffer + 0.1f;
std::cout << "z buffer = " << zBuffer << std::endl;
app.getCurrentObject(0).translate(0.0f, 0.0f, 0.1f);
}
break;
case GLFW_KEY_KP_2:
if (action == GLFW_PRESS) {
zBuffer = zBuffer - 1.0f;
std::cout << "z buffer = " << zBuffer << std::endl;
app.getCurrentObject(0).translate(0.0f, 0.0f, -1.0f);
}
break;
case GLFW_KEY_KP_5:
if (action == GLFW_PRESS) {
zBuffer = zBuffer + 1.0f;
std::cout << "z buffer = " << zBuffer << std::endl;
app.getCurrentObject(0).translate(0.0f, 0.0f, 1.0f);
}
break;
case GLFW_KEY_1:
system("pause");
break;
default:
break;
}
} |
c01bac618d7c09e20a874a21e7b91f4f7087255a | 134634a752c899d2fd0b6375b8794ae78e5abc90 | /acceptance/main.cpp | 82fa3014138281d530740e0e6c16107d7800b7c8 | [] | no_license | sggrigoriev/pelopia | 7b6ad0b9608f81d8667e68cf2e8bcb7346f66370 | da829c8027dff54c05c25ae696eab792adf7de7e | refs/heads/master | 2021-01-10T04:55:56.110364 | 2016-01-11T19:47:27 | 2016-01-11T19:47:27 | 51,612,894 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,500 | cpp | main.cpp | #include <iostream>
#define CATCH_CONFIG_RUNNER
#include <test/catch.hpp>
#include <pelopia/Dataset.h>
#include <pelopia/GeocodeJSON.h>
using namespace Mapzen::Pelopia;
using namespace std;
TEST_CASE("one term, no location")
{
Dataset ds("./input/1.json");
SECTION ("found 10 or more")
{
const string Term = "Warwickshire";
const size_t ExpectedCount = 10;
const Response& resp = ds.Search ( Term . c_str () );
REQUIRE ( DefaultResults == resp . Count () );
for (unsigned int i = 0; i < resp.Count(); ++i)
{
Id id = resp.Get(i);
const GeocodeJSON::Feature& place = ds.Place(id);
REQUIRE ( string ( place . Label () ) . find ( Term ) != string :: npos );
}
}
SECTION ( "found less than 10" )
{
const string Term = "Bermuda";
const Response& resp = ds.Search ( Term . c_str () );
REQUIRE ( 6 == resp . Count () );
for (unsigned int i = 0; i < resp.Count(); ++i)
{
Id id = resp.Get(i);
const GeocodeJSON::Feature& place = ds.Place(id);
REQUIRE ( string ( place . Label () ) . find ( Term ) != string :: npos );
}
}
SECTION ( "found none" )
{
const Response& resp = ds.Search ( "Salisbury" );
REQUIRE ( 0 == resp . Count () );
}
}
int
main( int argc, char* argv[] )
{
return Catch::Session().run( argc, argv );
}
|
1f4899ab553b65da0343491ca9e3d5c5354f74e1 | a87741221c8e6501028fba7797f4d891d9cfb2e3 | /Chess Board 6-19-21 11:00PM.cpp | 713c7e51e59c4f3416d02f8bc2a968c09565701a | [] | no_license | tpate0562/Chess-Board-Final | 3d0d0bfd42f8bc4f1428e6736b107cf29c33d91e | 55053cb7848872b434e2bd9cc5781c7f45c3ca86 | refs/heads/main | 2023-05-31T04:24:54.142592 | 2021-06-20T06:01:15 | 2021-06-20T06:01:15 | 378,570,504 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,290 | cpp | Chess Board 6-19-21 11:00PM.cpp | //******************************************************************
// Chessboard program - chessboard.cpp
// This program prints a chessboard pattern that is built up from
// basic strings of white and black characters.
//******************************************************************
#include <iostream>
#include <string>
using namespace std;
const string blackFill = "%%%%%%%%%%%"; // Define a line of a black upper/lower filled line
const string blackEmpty = "% %"; // Define a line of a black border
const string whiteSquareRow = " "; //Defines a white square's row
int main ()
{
string blackFillRow; // A row beginning with a white square
string blackEmptyRow; // A row beginning with a black square
string whiteFillRow; //A white row with blackFill border squares fro black squares
string whiteEmptyRow; //A white row with blackEmpty borders for black squares
// Create a white-black row by concatenating the basic strings
blackEmptyRow = whiteSquareRow + blackEmpty + whiteSquareRow + blackEmpty + whiteSquareRow + blackEmpty + whiteSquareRow + blackEmpty;
// Create a black-white row by concatenating the basic strings
blackFillRow = whiteSquareRow + blackFill + whiteSquareRow + blackFill + whiteSquareRow + blackFill + whiteSquareRow + blackFill;
//White start row with black empty pattern
whiteEmptyRow = whiteSquareRow + blackEmpty + whiteSquareRow + blackEmpty + whiteSquareRow + blackEmpty + whiteSquareRow + blackEmpty;
// Print five white-black rows
cout << whiteEmptyRow << endl;
cout << whiteEmptyRow << endl;
cout << whiteEmptyRow << endl;
cout << whiteEmptyRow << endl;
cout << whiteEmptyRow << endl;
// Print five black-white rows
cout << blackFillRow << endl;
cout << blackEmptyRow << endl;
cout << blackEmptyRow << endl;
cout << blackEmptyRow << endl;
cout << blackEmptyRow << endl;
cout << blackEmptyRow << endl;
cout << blackFillRow << endl;
// Print five white-black rows
cout << whiteEmptyRow << endl;
cout << whiteEmptyRow << endl;
cout << whiteEmptyRow << endl;
cout << whiteEmptyRow << endl;
cout << whiteEmptyRow << endl;
// Print five black-white rows
cout << blackFillRow << endl;
cout << blackEmptyRow << endl;
cout << blackEmptyRow << endl;
cout << blackEmptyRow << endl;
cout << blackEmptyRow << endl;
cout << blackEmptyRow << endl;
cout << blackFillRow << endl;
// Print five white-black rows
cout << whiteEmptyRow << endl;
cout << whiteEmptyRow << endl;
cout << whiteEmptyRow << endl;
cout << whiteEmptyRow << endl;
cout << whiteEmptyRow << endl;
// Print five black-white rows
cout << blackFillRow << endl;
cout << blackEmptyRow << endl;
cout << blackEmptyRow << endl;
cout << blackEmptyRow << endl;
cout << blackEmptyRow << endl;
cout << blackEmptyRow << endl;
cout << blackFillRow << endl;
// Print five white-black rows
cout << whiteEmptyRow << endl;
cout << whiteEmptyRow << endl;
cout << whiteEmptyRow << endl;
cout << whiteEmptyRow << endl;
cout << whiteEmptyRow << endl;
// Print five black-white rows
cout << blackFillRow << endl;
cout << blackEmptyRow << endl;
cout << blackEmptyRow << endl;
cout << blackEmptyRow << endl;
cout << blackEmptyRow << endl;
cout << blackEmptyRow << endl;
cout << blackFillRow << endl;
// system("PAUSE"); //Maybe needed by a few compilers to pause the console output
return 0;
}
|
0b92957d98132e2b474a4e164f9eae98d71abb00 | 65a9b36c2540e236718d1d5c485ecdddebabcd5e | /back/riscv/emit_riscv.hpp | 6787e2f6db8dd874b5454e8daea5ebff5f0a3528 | [] | no_license | lhydave/SysYCompilerLab | 420daeadc7dffd8c6c08f2492dbde2cbcf03c457 | 89ae528df5c39b1012f67c0cc428c31c5ae85328 | refs/heads/master | 2023-04-24T18:13:42.232797 | 2021-05-14T06:30:13 | 2021-05-14T06:30:13 | 362,852,244 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,056 | hpp | emit_riscv.hpp | /* emit risc-v by direct mapping tigger to risc-v */
#ifndef __EMIT_RISCV_H__
#define __EMIT_RISCV_H__
#include "tigger_seq.hpp"
#include <memory>
#include <sstream>
#include <string>
using std::string;
extern std::ostringstream riscv_dst;
extern vector<shared_ptr<tigger::stmt>> tigger::seq;
namespace riscv {
void gen_code();
void emit_func_begin(const shared_ptr<tigger::func_begin> &stmt);
void emit_func_end(const shared_ptr<tigger::func_end> &stmt);
void emit_global_var(const shared_ptr<tigger::global_var> &stmt);
void emit_assign(const shared_ptr<tigger::assign_stmt> &stmt);
void emit_goto(const shared_ptr<tigger::goto_stmt> &stmt);
void emit_label(const shared_ptr<tigger::label_stmt> &stmt);
void emit_call(const shared_ptr<tigger::call_stmt> &stmt);
void emit_ret(const shared_ptr<tigger::ret_stmt> &stmt);
void emit_store(const shared_ptr<tigger::store_stmt> &stmt);
void emit_load(const shared_ptr<tigger::load_stmt> &stmt);
void emit_loadaddr(const shared_ptr<tigger::loadaddr_stmt> &stmt);
} // namespace riscv
#endif // __EMIT_RISCV_H__ |
fb33ae3e876a7199dd2d4c83ab4f6f21d296b2d8 | 96823ccc717c9bd6580916e4dacbec7525f49ffc | /parser.cpp | 329d9b33ee0fd3de11e5ff4f9697c1c24f87b19e | [] | no_license | Ramseyyj/TinyCompiler | 32873ded2f696ebec5bd01491e7559c005cb2b43 | ecd952ed52dd9e74ac02d09a34cdf03b6de69c9f | refs/heads/master | 2020-03-29T10:21:03.203168 | 2014-12-05T06:01:50 | 2014-12-05T06:01:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 262 | cpp | parser.cpp | //
// parser.cpp
// TinyCompiler
//
// Created by lms on 12/2/14.
// Copyright (c) 2014 lms. All rights reserved.
//
#include "parser.h"
namespace tinyCompiler{
Parser::Parser(const std::string &srcfileName):scanner_(Scanner(srcfileName)){}
} |
3ea5686a99fb07a33c07f0732476b8d0050c32b0 | 0abb6765c4fe79141f517f28786b6190c99aed76 | /codechef/WSITES01.cpp | 7e234b798f3dd2583205f34a5c036aaa3bc3bd84 | [] | no_license | BlitW0/cp-codes | 26b3492997a6c6e613fd38b30846391773784bb2 | 16c7c5cc47a6ad8e2e69035d470e6aa2b47ff33a | refs/heads/master | 2020-07-16T04:00:01.467520 | 2019-09-01T18:18:08 | 2019-09-01T18:18:08 | 205,714,218 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,715 | cpp | WSITES01.cpp | #include <bits/stdc++.h>
using namespace std;
#define pb push_back
typedef long long ll;
struct node {
node* pres[26];
bool end;
};
node* make() {
node* x = (node*) malloc(sizeof(node));
for(ll i = 0; i < 26; i++)
x->pres[i] = NULL;
x->end = 0;
return x;
}
void insert(node* root, string s) {
for(ll i = 0; i < s.length(); i++) {
if(root->pres[s[i] - 'a'] == NULL) {
node* tmp = make();
root->pres[s[i] - 'a'] = tmp;
}
root = root->pres[s[i] - 'a'];
}
root->end = 1;
}
ll search(node* root, string s) {
ll i = 0; bool mismatch = 0;
for(; i < s.length(); i++) {
if(root->pres[s[i] - 'a'] == NULL) {
mismatch = 1;
break;
}
else root = root->pres[s[i] - 'a'];
}
if(mismatch)
return i;
else return -1;
}
int main() {
ios_base :: sync_with_stdio(false);
cin.tie(NULL), cout.tie(NULL);
vector <string> neg;
ll n; cin >> n;
node* root = make();
for(ll i = 0; i < n; i++) {
char type; string s;
cin >> type >> s;
(type == '+') ? insert(root, s) : neg.pb(s);
}
set <string> ans; bool ok = 1;
for(ll i = 0; i < neg.size(); i++) {
ll lim = search(root, neg[i]);
if(lim != -1)
ans.insert(neg[i].substr(0, lim + 1));
else {
ok = 0;
break;
}
}
if(!ok) {
cout << -1 << '\n';
} else {
cout << ans.size() << '\n';
for(; !ans.empty(); ans.erase(ans.begin()))
cout << *(ans.begin()) << '\n';
}
return 0;
} |
e8e080aa452a9bf72ee4730f2fe500008de05dc2 | 832a7813c8459353d5ae5bdc867275e0eb3fe07c | /MetroTank/Bullet.cpp | adc987e41f8996b24870236c25e353e2ca85f7a7 | [] | no_license | ngoaho91/MetroTank | 6c2c6b76f12b3b79782cbbf2b497443ba9de9277 | dc9df4fc840b502f1bb46ebab80861c8cdf52769 | refs/heads/master | 2021-01-13T14:00:21.650263 | 2013-11-19T04:18:11 | 2013-11-19T04:18:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 681 | cpp | Bullet.cpp | #include "pch.h"
#include "Bullet.h"
#include "math.h"
Bullet::Bullet(int type)
{
m_BulletModel = new BaseModel();
m_BulletModel->SetTexture(L"images\\bullet.png");
m_BulletModel->SetOriginal(12,12);
m_BulletModel->SetPosition(700,600);
m_X = 700;
m_Y = 600;
m_Velocity = 0;
m_Angle = 0;
m_Type = type;
}
void Bullet::Render(SpriteBatch* spriteBatch)
{
m_BulletModel->Render(spriteBatch);
}
void Bullet::Update()
{
float c = cos(m_Angle);
float s = sin(m_Angle);
m_X += -c*m_Velocity;
m_Y += -s*m_Velocity;
m_BulletModel->SetPosition(m_X,m_Y);
}
bool Bullet::OffScreen()
{
if((m_X+12<0 && m_Y+12<0) ||(m_X-12 > 1366 && m_Y-12 > 768)) return true;
return false;
} |
34cff65a6f76686d85d9d8d3e01bae988960f2d9 | 13a32b92b1ba8ffb07e810dcc8ccdf1b8b1671ab | /home--tommy--mypy/mypy/lib/python2.7/site-packages/pystan/stan/src/test/unit/lang/parser/lkj_cov_deprecation_test.cpp | 09500dc7bc7268b27338c93c33cdd8c2e7c97af0 | [
"Unlicense"
] | permissive | tommybutler/mlearnpy2 | 8ec52bcd03208c9771d8d02ede8eaa91a95bda30 | 9e5d377d0242ac5eb1e82a357e6701095a8ca1ff | refs/heads/master | 2022-10-24T23:30:18.705329 | 2022-10-17T15:41:37 | 2022-10-17T15:41:37 | 118,529,175 | 0 | 2 | Unlicense | 2022-10-15T23:32:18 | 2018-01-22T23:27:10 | Python | UTF-8 | C++ | false | false | 391 | cpp | lkj_cov_deprecation_test.cpp | #include <gtest/gtest.h>
#include <test/unit/lang/utility.hpp>
TEST(langParser, lkjCovDeprecationSampling) {
test_warning("lkj_cov_deprecation1",
"Warning: the lkj_cov_log() sampling distribution is deprecated.");
}
TEST(langParser, lkjCovDeprecationFunction) {
test_warning("lkj_cov_deprecation2",
"Warning: the lkj_cov_log() function is deprecated.");
}
|
a51e966c20e4e942444b9b75b213347fd45d04a1 | 82a43b7a2ffd8cb3232bc6ab6ad563173d597cff | /libvast/vast/detail/stack_vector.hpp | 660912b7a813a953283a5639d43a8f2ce3ec885a | [
"BSD-3-Clause"
] | permissive | cjolivier01/vast | 9fd52c7124f65b679ceceed86a4a8cdc2d3011f4 | 1a8aa2eda2a34450507f48385825e73381ce3b3a | refs/heads/master | 2021-06-25T17:57:59.593575 | 2017-08-15T05:08:03 | 2017-08-15T05:08:03 | 105,785,573 | 1 | 0 | null | 2017-10-04T15:33:44 | 2017-10-04T15:33:38 | C++ | UTF-8 | C++ | false | false | 2,090 | hpp | stack_vector.hpp | #ifndef VAST_DETAIL_STACK_VECTOR
#define VAST_DETAIL_STACK_VECTOR
#include <vector>
#include <scoped_allocator>
#include "vast/detail/short_alloc.hpp"
namespace vast {
namespace detail {
// This base class exists to bind the lifetime of the corresponding container
// to the arena, such that the allocator will never outlive the the stack-based
// container.
template <class T, size_t N>
struct stack_container {
using allocator_type = short_alloc<T, N>;
using arena_type = typename allocator_type::arena_type;
arena_type arena_;
};
/// A std::vector operating with short_alloc as allocator.
template <class T, size_t N>
using short_vector =
std::vector<T, std::scoped_allocator_adaptor<short_alloc<T, N>>>;
/// A stack-based vector.
/// @tparam T The element type of the vector.
/// @tparam N The number of bytes to be keep on the stack before moving to the
/// heap.
template <class T, size_t N>
struct stack_vector : private stack_container<T, N>, short_vector<T, N> {
using vector_type = short_vector<T, N>;
stack_vector() : vector_type(this->arena_) {
}
stack_vector(size_t n, T const& x) : vector_type(n, x, this->arena_) {
}
explicit stack_vector(size_t n) : vector_type(n, this->arena_) {
}
stack_vector(std::initializer_list<T> init)
: vector_type(std::move(init), this->arena_) {
}
template <class Iterator>
stack_vector(Iterator first, Iterator last)
: vector_type(first, last, this->arena_) {
}
stack_vector(stack_vector const& other)
: vector_type(other, this->arena_) {
}
stack_vector(stack_vector&& other)
noexcept(std::is_nothrow_move_constructible<vector_type>::value)
: vector_type(std::move(other), this->arena_) {
}
stack_vector& operator=(stack_vector const& other) {
static_cast<vector_type&>(*this) = other;
return *this;
}
stack_vector& operator=(stack_vector&& other)
noexcept(std::is_nothrow_move_assignable<vector_type>::value) {
static_cast<vector_type&>(*this) = std::move(other);
return *this;
}
};
} // namespace detail
} // namespace vast
#endif
|
fdd3adc977970be7168fa4bd4175571be457303b | 9e3e66b753f223917825a78145dccbf2e9ae3db0 | /06/SIMD.cpp | d3ba1a03e85088e277d9ec8b434f75b16ff15c56 | [] | no_license | Ian95Song/DIP-Homework | 52380f4e167cafa8bb805672859b2d349877b11a | e1e44c302df4e5458132d64018aa2697fa521fcf | refs/heads/master | 2022-04-13T07:29:36.915690 | 2020-04-12T11:54:15 | 2020-04-12T11:54:15 | 255,066,004 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 188 | cpp | SIMD.cpp | /**
* Copyright 2019/2020 Andreas Ley
* Written for Digital Image Processing of TU Berlin
* For internal use in the course only
*/
#include "SIMD.h"
namespace dip6 {
}
|
ee2e059dbc932169da28e624e13799eba796d981 | 824f7a0d6f94bff5be6dd52d654121656cde3701 | /Source/testing/BaseWeapon.h | aa45c441a51406578b121d6778c77dc1035ceabe | [
"MIT",
"LicenseRef-scancode-public-domain"
] | permissive | e-sushi/SMLabs | 894d2c3a1e25f4706832dffd65fdf35faa9ca948 | bbf55f4fb20a18500a92ad6ce0d7672505f321fc | refs/heads/master | 2023-02-21T18:42:08.032657 | 2021-01-27T01:56:51 | 2021-01-27T01:56:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,338 | h | BaseWeapon.h |
//The actual weapons themselves are set up in blueprint form,
//as it is easier to manipulate their meshes there and
//they are simple enough to be kept as blueprints.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "BaseWeapon.generated.h"
UENUM()
enum DamageType {
//placeholder values for now.
Physical UMETA(DisplayName = "Physical"),
Electric UMETA(DisplayName = "Electric"),
Burn UMETA(DisplayName = "Burn"),
};
namespace EWeaponState
{
enum Type
{
Idle,
Firing,
Reloading,
Equipping,
};
}
UCLASS()
class TESTING_API ABaseWeapon : public AActor
{
GENERATED_BODY()
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
/** current weapon state */
EWeaponState::Type CurrentState;
/** is weapon fire active? */
bool bWantsToFire = false;
/** pawn owner */
UPROPERTY(Transient, ReplicatedUsing = OnRep_MyPawn)
class ASMPlayerCharacter* MyPawn;
UFUNCTION()
void OnRep_MyPawn();
public:
// Sets default values for this actor's properties
ABaseWeapon();
virtual void Tick(float DeltaTime) override;
//Replicate variables on server
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty> & OutLifetimeProps) const override;
//////////////////////////////////////////////////////////////////////////
// Pawn Ownership stuff
/** set the weapon's owning pawn */
void SetOwningPawn(ASMPlayerCharacter* NewOwner);
/** [server] weapon was added to pawn's inventory */
virtual void OnEnterInventory(ASMPlayerCharacter* NewOwner);
/** [server] weapon was removed from pawn's inventory */
virtual void OnLeaveInventory();
//////////////////////////////////////////////////////////////////////////
// Weapon usage
/** [local + server] start weapon fire */
virtual void StartFire();
UFUNCTION(Server, Reliable, WithValidation)
void ServerStartFire();
void ServerStartFire_Implementation();
bool ServerStartFire_Validate();
/** [local + server] stop weapon fire */
virtual void StopFire();
UFUNCTION(Server, Reliable, WithValidation)
void ServerStopFire();
void ServerStopFire_Implementation();
bool ServerStopFire_Validate();
/** [local + server] handle weapon fire */
void HandleFiring();
UFUNCTION(Server, Reliable, WithValidation)
void ServerHandleFiring();
void ServerHandleFiring_Implementation();
bool ServerHandleFiring_Validate();
/** [local] weapon specific fire implementation */
virtual void FireWeapon();
/** server notified of hit from client to verify */
UFUNCTION(Server, Reliable, WithValidation)
void ServerNotifyHit(const FHitResult& fireTarget);
void ServerNotifyHit_Implementation(const FHitResult& fireTarget);
bool ServerNotifyHit_Validate(const FHitResult& fireTarget);
/** actually deals the damage to target */
void HitConfirmed(const FHitResult& fireTarget);
UFUNCTION(BlueprintCallable)
void Reload();
UFUNCTION(BlueprintCallable)
void toggleVis();
UFUNCTION(BlueprintImplementableEvent)
void onFire();
UFUNCTION(BlueprintImplementableEvent)
void onReload();
/** consume a number of bullets */
int32 UseAmmo(int32 ammoToUse);
//////////////////////////////////////////////////////////////////////////
// Weapon properties
UPROPERTY(Replicated, VisibleAnywhere, BlueprintReadWrite);
int ammo;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite);
int ammoPerShot;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite);
int maxAmmo;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite);
int bulletSpread;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite);
int fireRate;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite);
int damage;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite);
int reloadSpeed;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite);
int weaponRange;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite);
int weight;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite);
int maxRange;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite);
uint8 weaponID;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite);
TEnumAsByte<DamageType> damageType;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite);
USkeletalMeshComponent* skeleMesh;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = Animation);
TArray<UAnimMontage*> montage;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = Animation);
UAnimMontage* FireAnim;
};
|
d18a0e8cf7964d35dbe03066489ce77651095a2f | fece94b0e6aba6765afbc7d7256aca9ae23efd0d | /SIMProcessor.h | 48c03f0b48effa54a0b3aed362f2f3e5b6a876b4 | [] | no_license | AyaElAkhras/nSIM-Machine | 2fe23722077bf41898656e5dbdb5d38f8a6a23ac | 179ae9cd4592f40fc184953352dbeb31ca4f3464 | refs/heads/master | 2020-11-27T23:15:23.962836 | 2019-12-22T23:12:54 | 2019-12-22T23:12:54 | 229,643,195 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,176 | h | SIMProcessor.h | #ifndef SIMPROCESSOR_H
#define SIMPROCESSOR_H
// This is the microprocessor that contains 1 DataMemory Bank and 1 InstructionFactory and N cores
// Each core has its own PC and executes instructions from its instruction_memory
// in its constructor, it takes the number of cores N, and an array of files containing N file names
#include <thread>
#include <vector>
#include "InstrFactory.h"
#include "Core.h"
using namespace std;
class SIMProcessor {
public:
SIMProcessor(int N, string file_names[], int number_of_files);
~SIMProcessor(); // calls the destructors of all objects
void exec(); // starts executing all its cores concurrently
void printDataMem(int index); // prints the contents of the DataMemory up to a specific index
private:
InstrFactory instr_factory; // object will be passed one of the .txt files and should return Array of pointers to instructions
DataMemory data_memory; // a single DataMemory object is going to be shared among multiple Cores
string* file_names;
int number_of_cores;
vector<thread> threads; // create a vector of N threads corresponding to the number_of_cores
};
#endif |
82267580e9f617c63263ae45c24ea93cb48db44d | 8237d08ea9dd0d1f9202aced9a85dea5082f708c | /geometry/line.cpp | 546d7423c5111c56d1214ca3749de434df9978af | [] | no_license | rnetuka/adventofcode2019 | 58f98fafdc53cf74b4cf6fe5f0612584b7f30a6f | aae468c2edbe4a9e3231534f3d5053ed380b560d | refs/heads/master | 2020-09-21T03:13:33.815747 | 2020-01-20T09:32:41 | 2020-01-20T09:32:41 | 224,661,863 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,276 | cpp | line.cpp | //
// Created by rnetuka on 09.01.20.
//
#include<cmath>
#include "line.h"
#include "vector.h"
using namespace std;
namespace geom {
line::line(const vector& u) : u { u } {
}
double line::angle_with(const line& other) const {
vector u = this->u;
vector v = other.u;
return cos(abs(u * v) / u.length() * v.length());
}
line_segment::line_segment(point A, point B) : A { A }, B { B } {
}
vector line_segment::direction_vector() const {
return { B - A };
}
bool line_segment::contains_point(const point& p) const
{
if (A == p || B == p)
return true;
// P = A + t * u
// -> t * u = P - A
// -> t1, t2 = (P - A) / u
vector u = direction_vector();
vector v = p - A;
double t1 = v.dx / u.dx;
double t2 = v.dy / u.dy;
if (u.dx == 0 && v.dx == 0)
if (t2 > 0 && t2 < 1)
return true;
if (u.dy == 0 && v.dy == 0)
if (t1 > 0 && t1 < 1)
return true;
if (t1 == t2 && t1 > 0 && t1 < 1)
return true;
return false;
}
double line_segment::length() const {
vector u = B - A;
return u.length();
}
} |
4a0cc51459bfac3864adf1ab67e71267a9724736 | e272d18a042e6b6808bc615917b1783d53607870 | /done/1352.cpp | 1545f84264ae8832c7dd55953692fcbad57a0e36 | [] | no_license | chessdroid/morbidel-timus | 58656c7a62132aaae71289a20ee77baeca4ba554 | b079bf3ae716d4eeb54722037ac55066f9e9da7c | refs/heads/master | 2020-07-10T02:20:08.032088 | 2013-04-11T20:48:39 | 2013-04-11T20:48:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 527 | cpp | 1352.cpp | /*
* ACM Timus Online
* Mersenne primes - Problem 1352
*/
#include <stdio.h>
long Array[42] = {0, 2, 3, 5, 7, 13, 17, 19, 31, 61, 89,107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423,
9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433,
1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583};
int N, T;
int main()
{
for (scanf("%d", &T); T--; )
{
scanf("%d", &N);
printf("%d\n", Array[N]);
}
return 0;
}
|
fc4b27758fc6a74b1fcf7cabad2e6f64ec6f56c9 | 63ef43e75ce8fb701b0428f3b9933c29bc2a2fa8 | /bumbel.ino | 32d8767762add8464c675bd7c95c8de0eb461112 | [
"BSD-2-Clause"
] | permissive | knilch0r/bumbel | 9aaf27d9dfd9d767b07ee77a664db35a6cdbd4d4 | a515dae9559346cdc6e3008acee2e8b464281608 | refs/heads/master | 2020-07-05T05:58:59.155704 | 2019-08-16T07:37:19 | 2019-08-16T07:37:19 | 202,546,170 | 0 | 0 | null | 2019-08-15T13:32:07 | 2019-08-15T13:29:03 | C++ | UTF-8 | C++ | false | false | 3,672 | ino | bumbel.ino |
#include <Adafruit_NeoPixel.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#define PIN 21
#define SZX 6
#define SZY 6
#define LPP 6
#define NUMPIXELS (SZX*SZY*LPP)
#define DELAYVAL 333
#include "wifi_pass.h"
#ifndef SSID
const char *ssid = "ssid";
const char *password = "pass";
#else
const char *ssid = SSID;
const char *password = PASS;
#endif
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRBW + NEO_KHZ800);
WebServer server(80);
const int led = 17;
#define LED_OFF() do { digitalWrite(led, 1); } while (0)
#define LED_ON() do { digitalWrite(led, 0); } while (0)
void handleRoot() {
LED_ON();
char temp[400];
unsigned long sec = millis() / 1000;
unsigned long min = sec / 60;
unsigned long hr = min / 60;
snprintf(temp, 400,
"<html>\
<head>\
<meta http-equiv='refresh' content='5'/>\
<title>Test0r</title>\
<style>\
body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }\
</style>\
</head>\
<body>\
<h1>Hello from ESP32!</h1>\
<p>Uptime: %02lu:%02lu:%02lu</p>\
</body>\
</html>",
hr, min % 60, sec % 60
);
server.send(200, "text/html", temp);
Serial.println("[index.html]");
LED_OFF();
}
void handleNotFound() {
digitalWrite(led, 1);
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
Serial.println("[404]");
digitalWrite(led, 0);
}
void setup(void) {
pinMode(led, OUTPUT);
LED_OFF();
Serial.begin(115200);
WiFi.mode(WIFI_STA);
Serial.println("");
pixels.begin();
pixels.clear();
Serial.println("pixels ready for the show");
pixels.show();
Serial.print("Connecting to ");
Serial.print(ssid);
Serial.println("...");
WiFi.begin(ssid, password);
// Wait for connection
int w=0;
while (WiFi.status() != WL_CONNECTED) {
digitalWrite(led, w++ & 1);
delay(500);
Serial.print(".");
for (int i=0; i < SZY; i++)
setpixel(i, 0, ((w&(1<<(SZY-1-i)))?pixels.Color(0,0,0,42):pixels.Color(0,0,0,0)));
pixels.show();
}
LED_OFF();
Serial.println("");
Serial.println("Connected.");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (MDNS.begin("bumbel")) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void setpixel(unsigned x, unsigned y, uint32_t color){
// odd rows gow top-> bottom, even rows go the other way
if (x & 1) y = LPP-1-y;
// we let our y run from top to bottom as it was intended by the prophecy
// both x and y run from 0 to SZX-1/ SZY-1
// only fools check their input values for errors
int s = (x*LPP + y) * LPP;
#ifdef USE_ALL
for (int i = s; i < s+LPP; i++)
#else
int i=s+(LPP/2);
#endif
pixels.setPixelColor(i, color);
}
unsigned long last = 0;
void loop(void) {
static int x=5, y=5;
server.handleClient();
// always remember, uint32_t rgbcolor = strip.gamma32(strip.ColorHSV(hue, sat, val));
if (millis() > last + DELAYVAL) {
last = millis();
setpixel(x, y, pixels.Color(0,0,0,42));
x++;
if (x >= SZX) {
x = 0;
y++;
if (y >= SZY) y = 0;
}
setpixel(x,y, pixels.Color(23,0,0,0));
pixels.show();
}
}
|
3cff3732f746893eb76c6598e72a46eb6fa79f0e | 8f50c262f89d3dc4f15f2f67eb76e686b8f808f5 | /Database/PersistentDataModelTPCnv/PersistentDataModelTPCnv/DataHeader_p6.h | f2b8cb80b2ed81b0e6ea7e541aafeab44fc3a116 | [
"Apache-2.0"
] | permissive | strigazi/athena | 2d099e6aab4a94ab8b636ae681736da4e13ac5c9 | 354f92551294f7be678aebcd7b9d67d2c4448176 | refs/heads/master | 2022-12-09T02:05:30.632208 | 2020-09-03T14:03:18 | 2020-09-03T14:03:18 | 292,587,480 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,411 | h | DataHeader_p6.h | /*
Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
*/
#ifndef PERSISTENTDATAMODELTPCNV_DATAHEADER_P6_H
#define PERSISTENTDATAMODELTPCNV_DATAHEADER_P6_H
/** @file DataHeader_p6.h
* @brief This file contains the class definitions for the
* DataHeader_p6 and DataHeaderForm_p6
* @author Peter van Gemmeren <gemmeren@anl.gov>, Marcin Nowak
**/
#include "PersistentDataModel/Guid.h"
#include <vector>
#include <set>
#include <string>
class Token;
/** @class DataHeaderForm_p6
* @brief This class provides storage for the constant fields of the persistent DataHeader class.
**/
class DataHeaderForm_p6 {
friend class DataHeaderCnv_p6;
public:
struct DbRecord {
Guid fid; unsigned tech;
DbRecord() {}
DbRecord( const Guid& f, unsigned t) : fid(f), tech(t) {}
bool operator==(const DbRecord& rhs) const { return fid==rhs.fid && tech==rhs.tech; }
};
struct ObjRecord {
Guid guid; std::string key; unsigned clid; long long oid1;
ObjRecord() {}
ObjRecord( const Guid& g, const std::string& k, unsigned id, long long o)
: guid(g), key(k), clid(id), oid1(o) {}
bool operator==(const ObjRecord& rhs) const
{ return clid == rhs.clid && key == rhs.key && oid1 == rhs.oid1; }
};
public: // Constructor and Destructor
DataHeaderForm_p6() {}
DataHeaderForm_p6(const DataHeaderForm_p6& rhs);
DataHeaderForm_p6& operator=(const DataHeaderForm_p6& rhs);
~DataHeaderForm_p6();
unsigned int insertDb(const DbRecord& rec);
std::size_t sizeDb() const;
Guid getDbGuid(unsigned int index) const;
unsigned int getDbTech(unsigned int index) const;
unsigned int insertObj(const ObjRecord& rec,
const std::set<std::string>& alias = std::set<std::string>(),
const std::set<unsigned int>& symLinks = std::set<unsigned int>(),
const std::vector<unsigned int>& hashes = std::vector<unsigned int>());
std::size_t sizeObj() const;
std::string getObjKey(unsigned int index) const;
unsigned int getObjType(unsigned int index) const;
Guid getObjClassId(unsigned int index) const;
long long getObjOid1(unsigned int index) const { return m_objRecords[index].oid1; }
std::set<std::string> getObjAlias(unsigned int index) const;
std::set<unsigned int> getObjSymLinks(unsigned int index) const;
std::vector<unsigned int> getObjHashes(unsigned int index) const;
std::string calculateMdx();
bool wasModified() const;
void clearModified();
void setToken(const std::string& tok);
const std::string& getToken() const;
void resize(unsigned int size);
private:
std::vector<DbRecord> m_dbRecords;
std::vector<ObjRecord> m_objRecords;
std::vector<std::vector<std::string> > m_objAlias;
std::vector<std::vector<unsigned int> > m_objSymLinks;
std::vector<std::vector<unsigned int> > m_objHashes;
/// In case we need ot handle encoding changes later
unsigned m_version { 600 };
// transient members
/// indicates that the last event was somehow different and a new DHForm needs to be written
bool m_modified { true };
/// Reference to self in the persistent storage
std::string m_token;
};
/** @class DataHeader_p6
* @brief This class provides a persistent representation for the DataHeader class.
Version P6 optimized FOR references pointing to the same OID2 in the same Database
**/
class DataHeader_p6
{
friend class DataHeaderCnv_p6;
public:
struct FullElement {
FullElement() : oid2(0), dbIdx(0), objIdx(0) {}
FullElement(unsigned long long o2, unsigned db, unsigned obj) : oid2(o2), dbIdx(db), objIdx(obj) {}
unsigned long long oid2;
unsigned int dbIdx; // index to DHForm entry with DB GUID & technology
unsigned int objIdx; // index to DHForm entry with object data
};
DataHeader_p6() {};
const std::string& dhFormToken() const;
void setDhFormToken(const std::string& formToken);
private:
/// common DB entry index used by all short DH elements
unsigned m_commonDbIndex;
unsigned long long m_commonOID2;
std::vector<int> m_shortElements;
std::vector<FullElement> m_fullElements;
unsigned int m_provenanceSize;
std::string m_dhFormToken;
};
#endif
|
e3588cb83ca20433b73e413038711e82a91a4153 | 803a9e4f825231491651dddda38431e327627792 | /utils/PrimitiveTypes/Object.cpp | a52e270172d0385d6a74d5f7fe9b39fb92228b85 | [] | no_license | Thrynk/JavaOwn | ab61347dcfc233b7df48f046ef729ddc6f51f303 | 5ee04f2a8df0258ec080ded93d07533ed0353541 | refs/heads/master | 2020-09-14T12:49:04.571702 | 2019-12-11T20:31:32 | 2019-12-11T20:31:32 | 223,131,463 | 0 | 0 | null | 2019-12-11T19:20:12 | 2019-11-21T09:00:32 | Yacc | UTF-8 | C++ | false | false | 625 | cpp | Object.cpp | #include "Object.h"
#include "../Variable.h"
Object::Object() {}
Object::Object(map<string, Variable>& attributes){
for(auto pair : attributes){
this->attributes[pair.first] = pair.second;
}
}
void Object::setValue(map<string, Variable>& attributes){
for(auto pair : attributes){
this->attributes[pair.first] = pair.second;
}
}
string Object::toJSON(){
string json = "{ ";
for(auto e : this->attributes){
json = json + e.first + " : " + e.second.toString() + ", ";
}
json = json + "}";
return json;
}
Variable Object::get(string s){
return attributes[s];
} |
7640404c0630119d302303b8af9679f41956c7ce | 43f79f4920beca05280c6b08ebfb5677e7748542 | /src/tools.cpp | d9b016e601ffdd205acf922eac23f67bf0005075 | [] | no_license | SiRi13/CarND-Unscented-Kalman-Filter-Project | 951ad65ff346eb2f17cb46522b74bc5ee66a34ac | e013a716a39dc4ca627705132a11550dffcaf70d | refs/heads/master | 2021-01-21T23:20:14.966745 | 2017-06-26T14:23:24 | 2017-06-26T14:23:24 | 95,226,254 | 0 | 0 | null | 2017-06-23T14:11:19 | 2017-06-23T14:11:19 | null | UTF-8 | C++ | false | false | 1,192 | cpp | tools.cpp | #include "tools.h"
#include <iostream>
#include "Eigen/Dense"
using Eigen::VectorXd;
using Eigen::MatrixXd;
using Eigen::Ref;
using std::vector;
Tools::Tools() {}
Tools::~Tools() {}
VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations,
const vector<VectorXd> &ground_truth) {
/**
* Calculate the RMSE here.
*/
VectorXd rmse = VectorXd::Zero(4);
// check the validity of the following inputs:
// * the estimation vector size should not be zero
// * the estimation vector size should equal ground truth vector size
if (estimations.size() != ground_truth.size() || estimations.size() == 0) {
cout << "Either Sizes don't match or size == 0" << endl;
return rmse;
}
// accumulate squared residuals
for (unsigned i = 0; i < estimations.size(); ++i) {
VectorXd tmp = estimations[i] - ground_truth[i];
tmp = tmp.array() * tmp.array();
rmse += tmp;
}
// calculate the mean
rmse = rmse / estimations.size();
// calculate the squared root
rmse = rmse.array().sqrt();
// return the result
return rmse;
}
void Tools::NormalizeAngle(double &angle) {
angle = atan2(sin(angle), cos(angle));
}
|
556b1ac3d72a6b7ed74b0c9285e6805dbc940705 | 7ab7d64890a67c8c3931cb96dd49bb065e5fe63e | /examples/cpp/dqlib.rpcz.h | 6b5c25e3274e8e3779713b9d802c78fccc9ef56b | [
"Apache-2.0"
] | permissive | gitgoready/rpcz | f57c1a90e981a9be530edc552a81058f04b6ac1e | 3c33d095e07a5fddd659805c1d351ab54a0d774d | refs/heads/master | 2021-01-13T13:19:20.638404 | 2017-04-11T12:40:37 | 2017-04-11T12:40:37 | 78,593,686 | 0 | 1 | null | 2017-01-11T02:10:36 | 2017-01-11T02:10:36 | null | UTF-8 | C++ | false | true | 2,645 | h | dqlib.rpcz.h | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: dqlib.proto
#ifndef RPCZ_dqlib_2eproto__INCLUDED
#define RPCZ_dqlib_2eproto__INCLUDED
#include <string>
#include <rpcz/service.hpp>
namespace google {
namespace protobuf {
class ServiceDescriptor;
class MethodDescriptor;
} // namespace protobuf
} // namespace google
namespace rpcz {
class rpc;
class closure;
class rpc_channel;
} //namesacpe rpcz
#include "dqlib.pb.h"
namespace examples {
void rpcz_protobuf_AssignDesc_dqlib_2eproto();
void rpcz_protobuf_ShutdownFile_dqlib_2eproto();
class DQService_Stub;
class DQService : public rpcz::service {
protected:
// This class should be treated as an abstract interface.
inline DQService() {};
public:
virtual ~DQService();
typedef DQService_Stub Stub;
static const ::google::protobuf::ServiceDescriptor* descriptor();
virtual void CLAService(const ::examples::MvoAssetAllocationInput& request,
::rpcz::reply< ::examples::MvoAssetAllocationOutput> response);
// implements Service ----------------------------------------------
const ::google::protobuf::ServiceDescriptor* GetDescriptor();
void call_method(const ::google::protobuf::MethodDescriptor* method,
const ::google::protobuf::Message& request,
::rpcz::server_channel* channel);
const ::google::protobuf::Message& GetRequestPrototype(
const ::google::protobuf::MethodDescriptor* method) const;
const ::google::protobuf::Message& GetResponsePrototype(
const ::google::protobuf::MethodDescriptor* method) const;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DQService);
};
class DQService_Stub {
public:
DQService_Stub(::rpcz::rpc_channel* channel,
bool owns_channel=false);
DQService_Stub(::rpcz::rpc_channel* channel,
const ::std::string& service_name,
bool owns_channel=false);
~DQService_Stub();
inline ::rpcz::rpc_channel* channel() { return channel_; }
void CLAService(const ::examples::MvoAssetAllocationInput& request,
::examples::MvoAssetAllocationOutput* response,
::rpcz::rpc* rpc, ::rpcz::closure* done);
void CLAService(const ::examples::MvoAssetAllocationInput& request,
::examples::MvoAssetAllocationOutput* response,
long deadline_ms = -1);
private:
::rpcz::rpc_channel* channel_;
::std::string service_name_;
bool owns_channel_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DQService_Stub);
};
} // namespace examples
#endif // RPCZ_dqlib_2eproto__INCLUDED
|
1aa7467e70374562a03a9ca323f347b395f7419e | 06bed8ad5fd60e5bba6297e9870a264bfa91a71d | /JavaQt/defaultlistselectionmodel.cpp | 43f765e63576a7f9ab272e6d904c7a69e1408ce4 | [] | no_license | allenck/DecoderPro_app | 43aeb9561fe3fe9753684f7d6d76146097d78e88 | 226c7f245aeb6951528d970f773776d50ae2c1dc | refs/heads/master | 2023-05-12T07:36:18.153909 | 2023-05-10T21:17:40 | 2023-05-10T21:17:40 | 61,044,197 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 33,207 | cpp | defaultlistselectionmodel.cpp | #include "defaultlistselectionmodel.h"
#include "bitset.h"
#include "listselectionevent.h"
#include <QSortFilterProxyModel>
DefaultListSelectionModel::DefaultListSelectionModel(QObject */*parent*/) :
QItemSelectionModel()
{
selectionMode = MULTIPLE_INTERVAL_SELECTION;
minIndex = MAX;
maxIndex = MIN;
anchorIndex = -1;
leadIndex = -1;
firstAdjustedIndex = MAX;
lastAdjustedIndex = MIN;
isAdjusting = false;
firstChangedIndex = MAX;
lastChangedIndex = MIN;
value = new BitSet(32);
leadAnchorNotificationEnabled = true;
listenerList = QVector<ListSelectionListener*>();
connect(this, SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(onSelectionChanged(QItemSelection,QItemSelection)));
}
/**
* Default data model for list selections.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Philip Milne
* @author Hans Muller
* @see ListSelectionModel
*/
///*public*/ class DefaultListSelectionModel implements ListSelectionModel, Cloneable, Serializable
//{
/** {@inheritDoc} */
/*public*/ int DefaultListSelectionModel::getMinSelectionIndex() { return isSelectionEmpty() ? -1 : minIndex; }
/** {@inheritDoc} */
/*public*/ int DefaultListSelectionModel::getMaxSelectionIndex() { return maxIndex; }
/** {@inheritDoc} */
/*public*/ bool DefaultListSelectionModel::getValueIsAdjusting() { return isAdjusting; }
/** {@inheritDoc} */
/*public*/ int DefaultListSelectionModel::getSelectionMode() { return selectionMode; }
/**
* {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
/*public*/ void DefaultListSelectionModel::setSelectionMode(int selectionMode) {
switch (selectionMode) {
case SINGLE_SELECTION:
case SINGLE_INTERVAL_SELECTION:
case MULTIPLE_INTERVAL_SELECTION:
this->selectionMode = selectionMode;
break;
default:
throw new IllegalArgumentException("invalid selectionMode");
}
}
/** {@inheritDoc} */
/*public*/ bool DefaultListSelectionModel::isSelectedIndex(int index) {
return ((index < minIndex) || (index > maxIndex)) ? false : value->get(index);
}
/** {@inheritDoc} */
/*public*/ bool DefaultListSelectionModel::isSelectionEmpty() {
return (minIndex > maxIndex);
}
/** {@inheritDoc} */
/*public*/ void DefaultListSelectionModel::addListSelectionListener(ListSelectionListener* l) {
//listenerList.append("ListSelectionListener", l);
listenerList.append(l);
//connect(this, SIGNAL(listSelectionChanged(ListSelectionEvent*)), l->self(), SLOT(valueChanged(ListSelectionEvent*)));
}
/** {@inheritDoc} */
/*public*/ void DefaultListSelectionModel::removeListSelectionListener(ListSelectionListener* l) {
//listenerList.remove(ListSelectionListener.class, l);
listenerList.removeOne(l);
}
/**
* Returns an array of all the list selection listeners
* registered on this <code>DefaultListSelectionModel</code>.
*
* @return all of this model's <code>ListSelectionListener</code>s
* or an empty
* array if no list selection listeners are currently registered
*
* @see #addListSelectionListener
* @see #removeListSelectionListener
*
* @since 1.4
*/
/*public*/ QVector<ListSelectionListener*> DefaultListSelectionModel::getListSelectionListeners() {
//return listenerList.getListeners(ListSelectionListener.class);
return listenerList;
}
/**
* Notifies listeners that we have ended a series of adjustments.
*/
/*protected*/ void DefaultListSelectionModel::fireValueChanged(bool isAdjusting) {
if (lastChangedIndex == MIN) {
return;
}
/* Change the values before sending the event to the
* listeners in case the event causes a listener to make
* another change to the selection.
*/
int oldFirstChangedIndex = firstChangedIndex;
int oldLastChangedIndex = lastChangedIndex;
firstChangedIndex = MAX;
lastChangedIndex = MIN;
fireValueChanged(oldFirstChangedIndex, oldLastChangedIndex, isAdjusting);
emit listSelectionChanged(new ListSelectionEvent(this, firstChangedIndex, lastChangedIndex, isAdjusting ));
}
/**
* Notifies <code>ListSelectionListeners</code> that the value
* of the selection, in the closed interval <code>firstIndex</code>,
* <code>lastIndex</code>, has changed.
*/
/*protected*/ void DefaultListSelectionModel::fireValueChanged(int firstIndex, int lastIndex) {
fireValueChanged(firstIndex, lastIndex, getValueIsAdjusting());
}
/**
* @param firstIndex the first index in the interval
* @param lastIndex the last index in the interval
* @param isAdjusting true if this is the final change in a series of
* adjustments
* @see EventListenerList
*/
/*protected*/ void DefaultListSelectionModel::fireValueChanged(int firstIndex, int lastIndex, bool isAdjusting)
{
#if 1
//Object[] listeners = listenerList.getListenerList();
ListSelectionEvent* e = nullptr;
for (int i = listenerList.length() - 2; i >= 0; i -= 2) {
// if (listeners[i] == ListSelectionListener.class) {
// if (e == null) {
e = new ListSelectionEvent(this, firstIndex, lastIndex, isAdjusting);
// }
//((ListSelectionListener)listeners[i+1]).valueChanged(e);
// }
}
emit listSelectionChanged(e);
#endif
}
/*private*/ void DefaultListSelectionModel::fireValueChanged() {
if (lastAdjustedIndex == MIN) {
return;
}
/* If getValueAdjusting() is true, (eg. during a drag opereration)
* record the bounds of the changes so that, when the drag finishes (and
* setValueAdjusting(false) is called) we can post a single event
* with bounds covering all of these individual adjustments.
*/
if (getValueIsAdjusting()) {
firstChangedIndex = qMin(firstChangedIndex, firstAdjustedIndex);
lastChangedIndex = qMax(lastChangedIndex, lastAdjustedIndex);
}
/* Change the values before sending the event to the
* listeners in case the event causes a listener to make
* another change to the selection.
*/
int oldFirstAdjustedIndex = firstAdjustedIndex;
int oldLastAdjustedIndex = lastAdjustedIndex;
firstAdjustedIndex = MAX;
lastAdjustedIndex = MIN;
fireValueChanged(oldFirstAdjustedIndex, oldLastAdjustedIndex);
}
/**
* Returns an array of all the objects currently registered as
* <code><em>Foo</em>Listener</code>s
* upon this model.
* <code><em>Foo</em>Listener</code>s
* are registered using the <code>add<em>Foo</em>Listener</code> method.
* <p>
* You can specify the <code>listenerType</code> argument
* with a class literal, such as <code><em>Foo</em>Listener.class</code>.
* For example, you can query a <code>DefaultListSelectionModel</code>
* instance <code>m</code>
* for its list selection listeners
* with the following code:
*
* <pre>ListSelectionListener[] lsls = (ListSelectionListener[])(m.getListeners(ListSelectionListener.class));</pre>
*
* If no such listeners exist,
* this method returns an empty array.
*
* @param listenerType the type of listeners requested;
* this parameter should specify an interface
* that descends from <code>java.util.EventListener</code>
* @return an array of all objects registered as
* <code><em>Foo</em>Listener</code>s
* on this model,
* or an empty array if no such
* listeners have been added
* @exception ClassCastException if <code>listenerType</code> doesn't
* specify a class or interface that implements
* <code>java.util.EventListener</code>
*
* @see #getListSelectionListeners
*
* @since 1.3
*/
// /*public*/ <T extends EventListener> T[] getListeners(Class<T> listenerType) {
// return listenerList.getListeners(listenerType);
// }
// Updates first and last change indices
/*private*/ void DefaultListSelectionModel::markAsDirty(int r) {
if (r == -1) {
return;
}
firstAdjustedIndex = qMin(firstAdjustedIndex, r);
lastAdjustedIndex = qMax(lastAdjustedIndex, r);
}
// Sets the state at this index and update all relevant state.
/*private*/ void DefaultListSelectionModel::set(int r) {
if (value->get(r)) {
return;
}
value->set(r);
markAsDirty(r);
// Update minimum and maximum indices
minIndex = qMin(minIndex, r);
maxIndex = qMax(maxIndex, r);
}
// Clears the state at this index and update all relevant state.
/*private*/ void DefaultListSelectionModel::clear(int r) {
if (!value->get(r)) {
return;
}
value->clear(r);
markAsDirty(r);
// Update minimum and maximum indices
/*
If (r > minIndex) the minimum has not changed.
The case (r < minIndex) is not possible because r'th value was set.
We only need to check for the case when lowest entry has been cleared,
and in this case we need to search for the first value set above it.
*/
if (r == minIndex) {
for(minIndex = minIndex + 1; minIndex <= maxIndex; minIndex++) {
if (value->get(minIndex)) {
break;
}
}
}
/*
If (r < maxIndex) the maximum has not changed.
The case (r > maxIndex) is not possible because r'th value was set.
We only need to check for the case when highest entry has been cleared,
and in this case we need to search for the first value set below it.
*/
if (r == maxIndex) {
for(maxIndex = maxIndex - 1; minIndex <= maxIndex; maxIndex--) {
if (value->get(maxIndex)) {
break;
}
}
}
/* Performance note: This method is called from inside a loop in
changeSelection() but we will only iterate in the loops
above on the basis of one iteration per deselected cell - in total.
Ie. the next time this method is called the work of the previous
deselection will not be repeated.
We also don't need to worry about the case when the min and max
values are in their unassigned states. This cannot happen because
this method's initial check ensures that the selection was not empty
and therefore that the minIndex and maxIndex had 'real' values.
If we have cleared the whole selection, set the minIndex and maxIndex
to their cannonical values so that the next set command always works
just by using qMin and qMax.
*/
if (isSelectionEmpty()) {
minIndex = MAX;
maxIndex = MIN;
}
}
/**
* Sets the value of the leadAnchorNotificationEnabled flag.
* @see #isLeadAnchorNotificationEnabled()
*/
/*public*/ void DefaultListSelectionModel::setLeadAnchorNotificationEnabled(bool flag) {
leadAnchorNotificationEnabled = flag;
}
/**
* Returns the value of the <code>leadAnchorNotificationEnabled</code> flag.
* When <code>leadAnchorNotificationEnabled</code> is true the model
* generates notification events with bounds that cover all the changes to
* the selection plus the changes to the lead and anchor indices.
* Setting the flag to false causes a narrowing of the event's bounds to
* include only the elements that have been selected or deselected since
* the last change. Either way, the model continues to maintain the lead
* and anchor variables internally. The default is true.
* <p>
* Note: It is possible for the lead or anchor to be changed without a
* change to the selection. Notification of these changes is often
* important, such as when the new lead or anchor needs to be updated in
* the view. Therefore, caution is urged when changing the default value.
*
* @return the value of the <code>leadAnchorNotificationEnabled</code> flag
* @see #setLeadAnchorNotificationEnabled(bool)
*/
/*public*/ bool DefaultListSelectionModel::isLeadAnchorNotificationEnabled() {
return leadAnchorNotificationEnabled;
}
/*private*/ void DefaultListSelectionModel::updateLeadAnchorIndices(int anchorIndex, int leadIndex) {
if (leadAnchorNotificationEnabled) {
if (this->anchorIndex != anchorIndex) {
markAsDirty(this->anchorIndex);
markAsDirty(anchorIndex);
}
if (this->leadIndex != leadIndex) {
markAsDirty(this->leadIndex);
markAsDirty(leadIndex);
}
}
this->anchorIndex = anchorIndex;
this->leadIndex = leadIndex;
}
/*private*/ bool DefaultListSelectionModel::contains(int a, int b, int i) {
return (i >= a) && (i <= b);
}
/*private*/ void DefaultListSelectionModel::changeSelection(int clearMin, int clearMax,
int setMin, int setMax, bool clearFirst) {
for(int i = qMin(setMin, clearMin); i <= qMax(setMax, clearMax); i++) {
bool shouldClear = contains(clearMin, clearMax, i);
bool shouldSet = contains(setMin, setMax, i);
if (shouldSet && shouldClear) {
if (clearFirst) {
shouldClear = false;
}
else {
shouldSet = false;
}
}
if (shouldSet) {
set(i);
}
if (shouldClear) {
clear(i);
}
}
fireValueChanged();
}
/**
* Change the selection with the effect of first clearing the values
* in the inclusive range [clearMin, clearMax] then setting the values
* in the inclusive range [setMin, setMax]. Do this in one pass so
* that no values are cleared if they would later be set.
*/
/*private*/ void DefaultListSelectionModel::changeSelection(int clearMin, int clearMax, int setMin, int setMax) {
changeSelection(clearMin, clearMax, setMin, setMax, true);
}
/** {@inheritDoc} */
/*public*/ void DefaultListSelectionModel::clearSelection() {
removeSelectionIntervalImpl(minIndex, maxIndex, false);
}
/**
* Changes the selection to be between {@code index0} and {@code index1}
* inclusive. {@code index0} doesn't have to be less than or equal to
* {@code index1}.
* <p>
* In {@code SINGLE_SELECTION} selection mode, only the second index
* is used.
* <p>
* If this represents a change to the current selection, then each
* {@code ListSelectionListener} is notified of the change.
* <p>
* If either index is {@code -1}, this method does nothing and returns
* without exception. Otherwise, if either index is less than {@code -1},
* an {@code IndexOutOfBoundsException} is thrown.
*
* @param index0 one end of the interval.
* @param index1 other end of the interval
* @throws IndexOutOfBoundsException if either index is less than {@code -1}
* (and neither index is {@code -1})
* @see #addListSelectionListener
*/
/*public*/ void DefaultListSelectionModel::setSelectionInterval(int index0, int index1) {
if (index0 == -1 || index1 == -1) {
return;
}
if (getSelectionMode() == SINGLE_SELECTION) {
index0 = index1;
}
//select(itemSelectionModel-> model()->index(index0, 0),QItemSelectionModel::Select);
updateLeadAnchorIndices(index0, index1);
int clearMin = minIndex;
int clearMax = maxIndex;
int setMin = qMin(index0, index1);
int setMax = qMax(index0, index1);
changeSelection(clearMin, clearMax, setMin, setMax);
}
/**
* Changes the selection to be the set union of the current selection
* and the indices between {@code index0} and {@code index1} inclusive.
* <p>
* In {@code SINGLE_SELECTION} selection mode, this is equivalent
* to calling {@code setSelectionInterval}, and only the second index
* is used. In {@code SINGLE_INTERVAL_SELECTION} selection mode, this
* method behaves like {@code setSelectionInterval}, unless the given
* interval is immediately adjacent to or overlaps the existing selection,
* and can therefore be used to grow it.
* <p>
* If this represents a change to the current selection, then each
* {@code ListSelectionListener} is notified of the change. Note that
* {@code index0} doesn't have to be less than or equal to {@code index1}.
* <p>
* If either index is {@code -1}, this method does nothing and returns
* without exception. Otherwise, if either index is less than {@code -1},
* an {@code IndexOutOfBoundsException} is thrown.
*
* @param index0 one end of the interval.
* @param index1 other end of the interval
* @throws IndexOutOfBoundsException if either index is less than {@code -1}
* (and neither index is {@code -1})
* @see #addListSelectionListener
* @see #setSelectionInterval
*/
/*public*/ void DefaultListSelectionModel::addSelectionInterval(int index0, int index1)
{
if (index0 == -1 || index1 == -1) {
return;
}
// If we only allow a single selection, channel through
// setSelectionInterval() to enforce the rule.
if (getSelectionMode() == SINGLE_SELECTION) {
setSelectionInterval(index0, index1);
return;
}
updateLeadAnchorIndices(index0, index1);
int clearMin = MAX;
int clearMax = MIN;
int setMin = qMin(index0, index1);
int setMax = qMax(index0, index1);
// If we only allow a single interval and this would result
// in multiple intervals, then set the selection to be just
// the new range.
if (getSelectionMode() == SINGLE_INTERVAL_SELECTION &&
(setMax < minIndex - 1 || setMin > maxIndex + 1)) {
setSelectionInterval(index0, index1);
return;
}
changeSelection(clearMin, clearMax, setMin, setMax);
}
/**
* Changes the selection to be the set difference of the current selection
* and the indices between {@code index0} and {@code index1} inclusive.
* {@code index0} doesn't have to be less than or equal to {@code index1}.
* <p>
* In {@code SINGLE_INTERVAL_SELECTION} selection mode, if the removal
* would produce two disjoint selections, the removal is extended through
* the greater end of the selection. For example, if the selection is
* {@code 0-10} and you supply indices {@code 5,6} (in any order) the
* resulting selection is {@code 0-4}.
* <p>
* If this represents a change to the current selection, then each
* {@code ListSelectionListener} is notified of the change.
* <p>
* If either index is {@code -1}, this method does nothing and returns
* without exception. Otherwise, if either index is less than {@code -1},
* an {@code IndexOutOfBoundsException} is thrown.
*
* @param index0 one end of the interval
* @param index1 other end of the interval
* @throws IndexOutOfBoundsException if either index is less than {@code -1}
* (and neither index is {@code -1})
* @see #addListSelectionListener
*/
/*public*/ void DefaultListSelectionModel::removeSelectionInterval(int index0, int index1)
{
removeSelectionIntervalImpl(index0, index1, true);
}
// /*private*/ implementation allowing the selection interval
// to be removed without affecting the lead and anchor
/*private*/ void DefaultListSelectionModel::removeSelectionIntervalImpl(int index0, int index1,
bool changeLeadAnchor) {
if (index0 == -1 || index1 == -1) {
return;
}
if (changeLeadAnchor) {
updateLeadAnchorIndices(index0, index1);
}
int clearMin = qMin(index0, index1);
int clearMax = qMax(index0, index1);
int setMin = MAX;
int setMax = MIN;
// If the removal would produce to two disjoint selections in a mode
// that only allows one, extend the removal to the end of the selection.
if (getSelectionMode() != MULTIPLE_INTERVAL_SELECTION &&
clearMin > minIndex && clearMax < maxIndex) {
clearMax = maxIndex;
}
changeSelection(clearMin, clearMax, setMin, setMax);
}
/*private*/ void DefaultListSelectionModel::setState(int index, bool state) {
if (state) {
set(index);
}
else {
clear(index);
}
}
/**
* Insert length indices beginning before/after index. If the value
* at index is itself selected and the selection mode is not
* SINGLE_SELECTION, set all of the newly inserted items as selected.
* Otherwise leave them unselected. This method is typically
* called to sync the selection model with a corresponding change
* in the data model.
*/
/*public*/ void DefaultListSelectionModel::insertIndexInterval(int index, int length, bool before)
{
/* The first new index will appear at insMinIndex and the last
* one will appear at insMaxIndex
*/
int insMinIndex = (before) ? index : index + 1;
int insMaxIndex = (insMinIndex + length) - 1;
/* Right shift the entire bitset by length, beginning with
* index-1 if before is true, index+1 if it's false (i.e. with
* insMinIndex).
*/
for(int i = maxIndex; i >= insMinIndex; i--) {
setState(i + length, value->get(i));
}
/* Initialize the newly inserted indices.
*/
bool setInsertedValues = ((getSelectionMode() == SINGLE_SELECTION) ?
false : value->get(index));
for(int i = insMinIndex; i <= insMaxIndex; i++) {
setState(i, setInsertedValues);
}
int leadIndex = this->leadIndex;
if (leadIndex > index || (before && leadIndex == index)) {
leadIndex = this->leadIndex + length;
}
int anchorIndex = this->anchorIndex;
if (anchorIndex > index || (before && anchorIndex == index)) {
anchorIndex = this->anchorIndex + length;
}
if (leadIndex != this->leadIndex || anchorIndex != this->anchorIndex) {
updateLeadAnchorIndices(anchorIndex, leadIndex);
}
fireValueChanged();
}
/**
* Remove the indices in the interval index0,index1 (inclusive) from
* the selection model. This is typically called to sync the selection
* model width a corresponding change in the data model. Note
* that (as always) index0 need not be <= index1.
*/
/*public*/ void DefaultListSelectionModel::removeIndexInterval(int index0, int index1)
{
int rmMinIndex = qMin(index0, index1);
int rmMaxIndex = qMax(index0, index1);
int gapLength = (rmMaxIndex - rmMinIndex) + 1;
/* Shift the entire bitset to the left to close the index0, index1
* gap.
*/
for(int i = rmMinIndex; i <= maxIndex; i++) {
setState(i, value->get(i + gapLength));
}
int leadIndex = this->leadIndex;
if (leadIndex == 0 && rmMinIndex == 0) {
// do nothing
} else if (leadIndex > rmMaxIndex) {
leadIndex = this->leadIndex - gapLength;
} else if (leadIndex >= rmMinIndex) {
leadIndex = rmMinIndex - 1;
}
int anchorIndex = this->anchorIndex;
if (anchorIndex == 0 && rmMinIndex == 0) {
// do nothing
} else if (anchorIndex > rmMaxIndex) {
anchorIndex = this->anchorIndex - gapLength;
} else if (anchorIndex >= rmMinIndex) {
anchorIndex = rmMinIndex - 1;
}
if (leadIndex != this->leadIndex || anchorIndex != this->anchorIndex) {
updateLeadAnchorIndices(anchorIndex, leadIndex);
}
fireValueChanged();
}
/** {@inheritDoc} */
/*public*/ void DefaultListSelectionModel::setValueIsAdjusting(bool isAdjusting) {
if (isAdjusting != this->isAdjusting) {
this->isAdjusting = isAdjusting;
this->fireValueChanged(isAdjusting);
}
}
/**
* Returns a string that displays and identifies this
* object's properties.
*
* @return a <code>String</code> representation of this object
*/
/*public*/ QString DefaultListSelectionModel::toString() {
QString s = ((getValueIsAdjusting()) ? "~" : "=") + value->toString();
return /*getClass().getName()*/QString(metaObject()->className()) + " " + /*QString::number(hashCode()) +*/ " " + s;
}
/**
* Returns a clone of this selection model with the same selection.
* <code>listenerLists</code> are not duplicated.
*
* @exception CloneNotSupportedException if the selection model does not
* both (a) implement the Cloneable interface and (b) define a
* <code>clone</code> method.
*/
/*public*/ QObject* DefaultListSelectionModel::clone() /*throw (CloneNotSupportedException)*/ {
#if 0
DefaultListSelectionModel* clone = (DefaultListSelectionModel*)super.clone();
clone->value = (BitSet*)value->clone();
clone->listenerList = new EventListenerList();
return (QObject*)clone;
#else
return NULL;
#endif
}
/** {@inheritDoc} */
//@Transient
/*public*/ int DefaultListSelectionModel::getAnchorSelectionIndex() {
return anchorIndex;
}
/** {@inheritDoc} */
//@Transient
/*public*/ int DefaultListSelectionModel::getLeadSelectionIndex() {
return leadIndex;
}
/**
* Set the anchor selection index, leaving all selection values unchanged.
* If leadAnchorNotificationEnabled is true, send a notification covering
* the old and new anchor cells.
*
* @see #getAnchorSelectionIndex
* @see #setLeadSelectionIndex
*/
/*public*/ void DefaultListSelectionModel::setAnchorSelectionIndex(int anchorIndex) {
updateLeadAnchorIndices(anchorIndex, this->leadIndex);
fireValueChanged();
}
/**
* Set the lead selection index, leaving all selection values unchanged.
* If leadAnchorNotificationEnabled is true, send a notification covering
* the old and new lead cells.
*
* @param leadIndex the new lead selection index
*
* @see #setAnchorSelectionIndex
* @see #setLeadSelectionIndex
* @see #getLeadSelectionIndex
*
* @since 1.5
*/
/*public*/ void DefaultListSelectionModel::moveLeadSelectionIndex(int leadIndex) {
// disallow a -1 lead unless the anchor is already -1
if (leadIndex == -1) {
if (this->anchorIndex != -1) {
return;
}
/* PENDING(shannonh) - The following check is nice, to be consistent with
setLeadSelectionIndex. However, it is not absolutely
necessary: One could work around it by setting the anchor
to something valid, modifying the lead, and then moving
the anchor back to -1. For this reason, there's no sense
in adding it at this time, as that would require
updating the spec and officially committing to it.
// otherwise, don't do anything if the anchor is -1
} else if (this->anchorIndex == -1) {
return;
*/
}
updateLeadAnchorIndices(this->anchorIndex, leadIndex);
fireValueChanged();
}
/**
* Sets the lead selection index, ensuring that values between the
* anchor and the new lead are either all selected or all deselected.
* If the value at the anchor index is selected, first clear all the
* values in the range [anchor, oldLeadIndex], then select all the values
* values in the range [anchor, newLeadIndex], where oldLeadIndex is the old
* leadIndex and newLeadIndex is the new one.
* <p>
* If the value at the anchor index is not selected, do the same thing in
* reverse selecting values in the old range and deslecting values in the
* new one.
* <p>
* Generate a single event for this change and notify all listeners.
* For the purposes of generating minimal bounds in this event, do the
* operation in a single pass; that way the first and last index inside the
* ListSelectionEvent that is broadcast will refer to cells that actually
* changed value because of this method. If, instead, this operation were
* done in two steps the effect on the selection state would be the same
* but two events would be generated and the bounds around the changed
* values would be wider, including cells that had been first cleared only
* to later be set.
* <p>
* This method can be used in the <code>mouseDragged</code> method
* of a UI class to extend a selection.
*
* @see #getLeadSelectionIndex
* @see #setAnchorSelectionIndex
*/
/*public*/ void DefaultListSelectionModel::setLeadSelectionIndex(int leadIndex) {
int anchorIndex = this->anchorIndex;
// only allow a -1 lead if the anchor is already -1
if (leadIndex == -1) {
if (anchorIndex == -1) {
updateLeadAnchorIndices(anchorIndex, leadIndex);
fireValueChanged();
}
return;
// otherwise, don't do anything if the anchor is -1
} else if (anchorIndex == -1) {
return;
}
if (this->leadIndex == -1) {
this->leadIndex = leadIndex;
}
bool shouldSelect = value->get(this->anchorIndex);
if (getSelectionMode() == SINGLE_SELECTION) {
anchorIndex = leadIndex;
shouldSelect = true;
}
int oldMin = qMin(this->anchorIndex, this->leadIndex);
int oldMax = qMax(this->anchorIndex, this->leadIndex);
int newMin = qMin(anchorIndex, leadIndex);
int newMax = qMax(anchorIndex, leadIndex);
updateLeadAnchorIndices(anchorIndex, leadIndex);
if (shouldSelect) {
changeSelection(oldMin, oldMax, newMin, newMax);
}
else {
changeSelection(newMin, newMax, oldMin, oldMax, false);
}
}
void DefaultListSelectionModel::onSelectionChanged(QItemSelection selected, QItemSelection deselected)
{
int min = MAX;
int max = MIN;
int minNew = MAX;
int maxNew = MIN;
foreach (QModelIndex ix, mapSelections(deselected).indexes()) {
min = qMin(ix.row(), min);
max = qMax(ix.row(), max);
}
foreach (QModelIndex ix, mapSelections(selected).indexes()) {
minNew = qMin(ix.row(), minNew);
maxNew = qMax(ix.row(), maxNew);
}
//changeSelection(min, max, minNew, maxNew);
setSelectionInterval(minNew, maxNew);
}
// if table model is a sort, we need to re-map the model indexes.
/*private*/ QItemSelection DefaultListSelectionModel::mapSelections(QItemSelection selections)
{
if(selections.count()== 0)
return selections;
const QAbstractItemModel* m = selections.at(0).model();
if((QSortFilterProxyModel*)(m))
{
return ((QSortFilterProxyModel*)m)->mapSelectionToSource(selections);
}
else
return selections;
}
#if 0
/*public*/ QItemSelectionModel* DefaultListSelectionModel::getItemSelectionModel()
{
return itemSelectionModel;
}
/*public*/ void DefaultListSelectionModel::setItemSelectionModel(QItemSelectionModel *itemSelectionModel)
{
this->itemSelectionModel = itemSelectionModel;
connect(itemSelectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(onSelectionChanged(QItemSelection,QItemSelection)));
}
#endif
|
dd8a7fa60617ebd8bb5c6c2c24ed39524d356fc2 | c871059fd202d07644f4fea92dbd3645b213427d | /Game2D/Classes/JniHelper.cpp | eee9e6635af439692160671cc7deeb0e99f89d46 | [] | no_license | doncc/android-game2d | 5c339afc8dad8444779a35ddc1b067d897830153 | b61a1d765f714637f8812705f869dd55c1839122 | refs/heads/master | 2020-12-25T15:50:48.624118 | 2015-09-08T03:45:50 | 2015-09-08T03:45:50 | 42,088,791 | 1 | 0 | null | 2015-09-08T03:50:14 | 2015-09-08T03:50:11 | null | UTF-8 | C++ | false | false | 399 | cpp | JniHelper.cpp | //
// Created by plter on 8/28/15.
//
#include "JniHelper.h"
#include <platform/android/jni/JniHelper.h>
void game2d::JniHelper::callStaticVoidMethod(std::string className, std::string methodName) {
cocos2d::JniMethodInfo minfo;
cocos2d::JniHelper::getStaticMethodInfo(minfo,className.c_str(),methodName.c_str(),"()V");
minfo.env->CallStaticVoidMethod(minfo.classID,minfo.methodID);
}
|
ea9430ca20e8deb3f4aff43b448af2a58461bc3c | d8616934aa17479aa596b6dced4c4b9ffac40b42 | /Raiden/A_Enemy.cpp | d14cb94a6df3b9422ffe7de1b2b6a5950787082c | [] | no_license | SwordofMorning/Raiden | 64d5d4ade1b9300c02676ebf4e34e9aa348c87d3 | 51f38564ba3d4eecb3e8c45b92bdf7f8a17811ff | refs/heads/master | 2023-06-07T13:38:21.868172 | 2021-06-27T02:37:09 | 2021-06-27T02:37:09 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,417 | cpp | A_Enemy.cpp | #include "A_Enemy.h"
A_Enemy::A_Enemy(std::string p_path,
const int& p_height, const int& p_width,
const int& p_HeightLowerLimit, const int& p_HeightUpperLimit,
const int& p_WidthLowerLimit, const int& p_WidthUpperLimit) :
A_Actor(p_path, p_height, p_width, p_HeightLowerLimit, p_HeightUpperLimit, p_WidthLowerLimit, p_WidthUpperLimit)
{
m_Alive = true;
}
//析构函数
A_Enemy::~A_Enemy()
{
}
bool A_Enemy::Segmentation(cv::Mat& segBackGround)
{
bool re(false);
cv::Vec3b Black{ 0, 0, 0 };
//绘制敌人
for (int i(0); i < this->GetImg().size().height; ++i)
{
for (int j(0); j < this->GetImg().size().width; ++j)
{
Black == this->GetImg().at<cv::Vec3b>(i, j) ?
segBackGround.at<cv::Vec3b>(i + this->GetPos().first, j + this->GetPos().second) : //do nothing
segBackGround.at<cv::Vec3b>(i + this->GetPos().first, j + this->GetPos().second) = this->GetImg().at<cv::Vec3b>(i, j);
//以(first, second)为原点将this拷贝到seg
}
}
//绘制敌人子弹
if (!this->m_BulletObjList.empty())
{
for (auto i : m_BulletObjList)
{
i.Segmentation(segBackGround);
}
}
re = true;
return re;
}
//敌人移动
void A_Enemy::EnemyAutoMovie()
{
int para_height = 10;
int para_width = 0;
//向下移动
/*--- 移动时开火 ---*/
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 10);
int num = dis(gen);
// 1/10的几率开火 且一次最多1发
if (num == 1 && m_BulletObjList.size() < 2)
{
this->EnemyFire();
}
//移动
this->MovePos(para_height, para_width);
}
//自我销毁函数(对象碰撞游戏边界时发生)
bool A_Enemy::DestoryObj()
{
bool re(false);
if (this->GetPos().first >= this->GetHeightUpperLimit()) //到达下界
{
this->~A_Enemy();
re = true;
}
return re;
}
//敌人开火
void A_Enemy::EnemyFire()
{
//在FIghter前方生存炮弹
int BulletParaX = this->GetPos().second + this->GetImg().size().width / 2; //width居中
int BulletParaY = this->GetPos().first + this->GetImg().size().height; //height - BulletScale.height(160)
A_EnemyBullets newBullet(".\\Source\\Re_EnemyBullets\\EnemyHit.png",
BulletParaY, BulletParaX);
if (!(newBullet.GetPos().first > newBullet.GetHeightUpperLimit()))
{
//不大于上界则合法
m_BulletObjList.push_back(newBullet);
}
}
//敌人子弹移动
bool A_Enemy::EnemyBulletMove()
{
if (!this->m_BulletObjList.empty())
{
//子弹移动
for (auto it = m_BulletObjList.begin(); it != m_BulletObjList.end(); ++it)
{
it->MovePos((it->GetBulletMoveSpeed()), 0);
}
}
//子弹删除
for (std::vector<A_EnemyBullets>::iterator it = m_BulletObjList.begin(); it != m_BulletObjList.end(); ++it)
{
if (it->DestoryObj())
{
m_BulletObjList.erase(std::remove(m_BulletObjList.begin(), m_BulletObjList.end(), *it), m_BulletObjList.end());
}
break;
/*--- 这里break是因为一次只删一个 ---*/
}
/*--- 已知bug:必须从头到尾删除 ---*/
return true;
}
//获取子弹信息
std::vector<A_EnemyBullets> A_Enemy::GetBulletObj()
{
return m_BulletObjList;
}
//设置子弹信息
void A_Enemy::SetBulletObj(std::vector<A_EnemyBullets> para)
{
m_BulletObjList = para;
}
//检测:玩家 碰 敌人子弹
bool A_Enemy::CollionEnemyBulletWithPlayer(A_PlayerFighter Target)
{
bool re(false);
for (auto i : this->m_BulletObjList)
{
re = i.RectangleCollision(Target);
}
return re;
}
|
ec5944d72e5dd44be1e0f75099a0de53e542fa20 | b71168dbe920e7f8d1c67427dd320d2c888c6599 | /src/machinery/module.cc | dd76ecbe18a7d4c081fb4eeeef96157bf579af7d | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | permissive | drycpp/machinery | 122bb92e72fb954538ef39287f564ddf425f4b39 | d52d575a222d7b41cac7c4b8c47b1b256af99f4a | refs/heads/master | 2020-04-09T20:08:50.849287 | 2014-11-03T02:07:20 | 2014-11-03T02:07:20 | 12,908,417 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 376 | cc | module.cc | /* This is free and unencumbered software released into the public domain. */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "module.h"
static const char* const module_names[] = {
#ifndef DISABLE_ARM
"arm",
#endif
#ifndef DISABLE_IR
"ir",
#endif
#ifndef DISABLE_JIT
"jit",
#endif
#ifndef DISABLE_MIPS
"mips",
#endif
#ifndef DISABLE_X86
"x86",
#endif
};
|
0b1d564b06d49cf51128870badcfe7a0ab79a037 | 7734e3e1f4affb37809b7ea2bec5fcd60d992d24 | /LedMatrixAnimations/LedMatrixAnimations.cpp | f70d90455a3d01ea601bde579eaae4a91fdc76d7 | [] | no_license | LuisDiazUgena/LedMatrixAnimations | 196988a413c6d9b0367c6b238e8ee0352b5f4898 | 9cd8db38643866fe74dc665e9e208a774c3213db | refs/heads/master | 2016-09-05T23:13:21.460049 | 2015-06-05T09:27:51 | 2015-06-05T09:27:51 | 36,807,452 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,254 | cpp | LedMatrixAnimations.cpp | #include "LedMatrixAnimations.h"
#include "LedControl.h"
LedMatrixAnimations::LedMatrixAnimations(){
ledMatrix = LedControl(11, 13, 12, 1);
}
LedMatrixAnimations::~LedMatrixAnimations(){
//Nothing to destruct
}
void LedMatrixAnimations::lookUp(){
ledMatrix.setLed(0, 2, 3, false);
ledMatrix.setLed(0, 2, 4, false);
ledMatrix.setLed(0, 3, 3, false);
ledMatrix.setLed(0, 3, 4, false);
ledMatrix.setLed(0, 1, 3, true);
ledMatrix.setLed(0, 1, 4, true);
ledMatrix.setLed(0, 2, 2, true);
ledMatrix.setLed(0, 2, 5, true);
ledMatrix.setLed(0, 3, 1, true);
ledMatrix.setLed(0, 3, 2, true);
ledMatrix.setLed(0, 3, 5, true);
ledMatrix.setLed(0, 3, 6, true);
ledMatrix.setLed(0, 4, 1, true);
ledMatrix.setLed(0, 4, 2, true);
ledMatrix.setLed(0, 4, 3, true);
ledMatrix.setLed(0, 4, 4, true);
ledMatrix.setLed(0, 4, 5, true);
ledMatrix.setLed(0, 4, 6, true);
ledMatrix.setLed(0, 5, 2, true);
ledMatrix.setLed(0, 5, 3, true);
ledMatrix.setLed(0, 5, 4, true);
ledMatrix.setLed(0, 5, 5, true);
ledMatrix.setLed(0, 6, 3, true);
ledMatrix.setLed(0, 6, 4, true);
}
void LedMatrixAnimations::lookDown(){
ledMatrix.setLed(0, 3, 3, false);
ledMatrix.setLed(0, 3, 4, false);
ledMatrix.setLed(0, 5, 3, false);
ledMatrix.setLed(0, 5, 4, false);
ledMatrix.setLed(0, 1, 3, true);
ledMatrix.setLed(0, 1, 4, true);
ledMatrix.setLed(0, 2, 2, true);
ledMatrix.setLed(0, 2, 3, true);
ledMatrix.setLed(0, 2, 4, true);
ledMatrix.setLed(0, 2, 5, true);
ledMatrix.setLed(0, 3, 1, true);
ledMatrix.setLed(0, 3, 2, true);
ledMatrix.setLed(0, 3, 3, true);
ledMatrix.setLed(0, 3, 4, true);
ledMatrix.setLed(0, 3, 5, true);
ledMatrix.setLed(0, 3, 6, true);
ledMatrix.setLed(0, 4, 1, true);
ledMatrix.setLed(0, 4, 2, true);
ledMatrix.setLed(0, 4, 5, true);
ledMatrix.setLed(0, 4, 6, true);
ledMatrix.setLed(0, 5, 2, true);
ledMatrix.setLed(0, 5, 5, true);
ledMatrix.setLed(0, 6, 3, true);
ledMatrix.setLed(0, 6, 4, true);
}
void LedMatrixAnimations::lookLeft(){
ledMatrix.setLed(0, 3, 4, false);
ledMatrix.setLed(0, 3, 5, false);
ledMatrix.setLed(0, 4, 4, false);
ledMatrix.setLed(0, 4, 5, false);
ledMatrix.setLed(0, 1, 3, true);
ledMatrix.setLed(0, 1, 4, true);
ledMatrix.setLed(0, 2, 2, true);
ledMatrix.setLed(0, 2, 3, true);
ledMatrix.setLed(0, 2, 4, true);
ledMatrix.setLed(0, 2, 5, true);
ledMatrix.setLed(0, 3, 1, true);
ledMatrix.setLed(0, 3, 2, true);
ledMatrix.setLed(0, 3, 3, true);
ledMatrix.setLed(0, 3, 6, true);
ledMatrix.setLed(0, 4, 1, true);
ledMatrix.setLed(0, 4, 2, true);
ledMatrix.setLed(0, 4, 3, true);
ledMatrix.setLed(0, 4, 6, true);
ledMatrix.setLed(0, 5, 2, true);
ledMatrix.setLed(0, 5, 3, true);
ledMatrix.setLed(0, 5, 4, true);
ledMatrix.setLed(0, 5, 5, true);
ledMatrix.setLed(0, 6, 3, true);
ledMatrix.setLed(0, 6, 4, true);
}
void LedMatrixAnimations::lookRight(){
ledMatrix.setLed(0, 3, 2, false);
ledMatrix.setLed(0, 3, 3, false);
ledMatrix.setLed(0, 4, 2, false);
ledMatrix.setLed(0, 4, 3, false);
ledMatrix.setLed(0, 1, 3, true);
ledMatrix.setLed(0, 1, 4, true);
ledMatrix.setLed(0, 2, 2, true);
ledMatrix.setLed(0, 2, 3, true);
ledMatrix.setLed(0, 2, 4, true);
ledMatrix.setLed(0, 2, 5, true);
ledMatrix.setLed(0, 3, 1, true);
ledMatrix.setLed(0, 3, 4, true);
ledMatrix.setLed(0, 3, 5, true);
ledMatrix.setLed(0, 3, 6, true);
ledMatrix.setLed(0, 4, 1, true);
ledMatrix.setLed(0, 4, 4, true);
ledMatrix.setLed(0, 4, 5, true);
ledMatrix.setLed(0, 4, 6, true);
ledMatrix.setLed(0, 5, 2, true);
ledMatrix.setLed(0, 5, 3, true);
ledMatrix.setLed(0, 5, 4, true);
ledMatrix.setLed(0, 5, 5, true);
ledMatrix.setLed(0, 6, 3, true);
ledMatrix.setLed(0, 6, 4, true);
}
void LedMatrixAnimations::lookCenter(){
ledMatrix.setLed(0, 3, 3, false);
ledMatrix.setLed(0, 3, 4, false);
ledMatrix.setLed(0, 4, 3, false);
ledMatrix.setLed(0, 4, 4, false);
ledMatrix.setLed(0, 1, 3, true);
ledMatrix.setLed(0, 1, 4, true);
ledMatrix.setLed(0, 2, 2, true);
ledMatrix.setLed(0, 2, 3, true);
ledMatrix.setLed(0, 2, 4, true);
ledMatrix.setLed(0, 2, 5, true);
ledMatrix.setLed(0, 3, 1, true);
ledMatrix.setLed(0, 3, 2, true);
ledMatrix.setLed(0, 3, 5, true);
ledMatrix.setLed(0, 3, 6, true);
ledMatrix.setLed(0, 4, 1, true);
ledMatrix.setLed(0, 4, 2, true);
ledMatrix.setLed(0, 4, 5, true);
ledMatrix.setLed(0, 4, 6, true);
ledMatrix.setLed(0, 5, 2, true);
ledMatrix.setLed(0, 5, 3, true);
ledMatrix.setLed(0, 5, 4, true);
ledMatrix.setLed(0, 5, 5, true);
ledMatrix.setLed(0, 6, 3, true);
ledMatrix.setLed(0, 6, 4, true);
}
void LedMatrixAnimations::fullBlink(int timeClosed, int delayBlink){
blinkClose(delayBlink);
delay(timeClosed);
blinkOpen(delayBlink);
}
void LedMatrixAnimations::blinkClose(int delayBlink){
ledMatrix.setLed(0,1,3,false);
ledMatrix.setLed(0,1,4,false);
ledMatrix.setLed(0,6,3,false);
ledMatrix.setLed(0,6,4,false);
//delay(delayBlink);
ledMatrix.setLed(0,2,2,false);
ledMatrix.setLed(0,2,3,false);
ledMatrix.setLed(0,2,4,false);
ledMatrix.setLed(0,2,5,false);
ledMatrix.setLed(0,5,2,false);
ledMatrix.setLed(0,5,3,false);
ledMatrix.setLed(0,5,4,false);
ledMatrix.setLed(0,5,5,false);
//delay(delayBlink);
ledMatrix.setLed(0,3,1,false);
ledMatrix.setLed(0,3,2,false);
ledMatrix.setLed(0,3,5,false);
ledMatrix.setLed(0,3,6,false);
ledMatrix.setLed(0,4,3,true);
ledMatrix.setLed(0,4,4,true);
delay(delayBlink*3);
}
void LedMatrixAnimations::blinkOpen(int delayBlink){
ledMatrix.setLed(0,4,3,false);
ledMatrix.setLed(0,4,4,false);
ledMatrix.setLed(0,3,1,true);
ledMatrix.setLed(0,3,2,true);
ledMatrix.setLed(0,3,5,true);
ledMatrix.setLed(0,3,6,true);
//delay(delayBlink);
ledMatrix.setLed(0,2,2,true);
ledMatrix.setLed(0,2,3,true);
ledMatrix.setLed(0,2,4,true);
ledMatrix.setLed(0,2,5,true);
ledMatrix.setLed(0,5,2,true);
ledMatrix.setLed(0,5,3,true);
ledMatrix.setLed(0,5,4,true);
ledMatrix.setLed(0,5,5,true);
//delay(delayBlink);
ledMatrix.setLed(0,1,3,true);
ledMatrix.setLed(0,1,4,true);
ledMatrix.setLed(0,6,3,true);
ledMatrix.setLed(0,6,4,true);
delay(delayBlink);
} |
e6d1a7b34cfdf327de42a3a09d6ee0505d36aa6b | 21a466dfebd3cd3e8593ead8f70485c0f7460f0d | /is_integral.cxx | 22dac26e7c84889a349749886991f4a0325255e8 | [
"MIT"
] | permissive | cmbrandt/std-type-traits | e2045e93dfaf48b6510c019bd23b69c3321c2663 | 2a9c536840ba0f0a48e172b3b2527510cdfd7073 | refs/heads/main | 2023-03-29T18:25:47.223540 | 2021-04-04T05:42:40 | 2021-04-04T05:42:40 | 328,254,986 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 303 | cxx | is_integral.cxx | #include <iostream>
#include <type_traits.hxx>
int main()
{
std::cout << "cmb::is_integral<void>::value = "
<< cmb::is_integral<void>::value // = 0
<< "\ncmb::is_integral_v<int> = "
<< cmb::is_integral_v<int> // = 1
<< std::endl;
} |
113e451b620c23af855087bdf199109063a70db2 | 73c7fe37bf6af775cac65f58b81d2284dae117f2 | /LeetCode/56. Merge Intervals.cpp | 07fbfa5896785c2c914287648343e749101c7263 | [] | no_license | atique7465/Competetive_programming | 9ad03427682270e889f751b8a8e2e9ab3b309be2 | 840b8b9133f5b993730ecde186ef4d4fdfca9c46 | refs/heads/master | 2023-08-03T15:16:47.582253 | 2023-07-25T04:07:01 | 2023-07-25T04:07:01 | 186,138,178 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 672 | cpp | 56. Merge Intervals.cpp | class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
vector<vector<int>> res;
vector<int> range(10010, -1);
for(int i = 0; i < intervals.size(); i++)
range[intervals[i][0]] = max(range[intervals[i][0]], intervals[i][1]);
int i = 0;
while(i < 10001){
if(range[i] != -1){
int l = i, mx = range[i], j = i;
while(j+1 <= mx) mx = max(mx, range[++j]);
res.push_back({l, j});
i = j + 1;
}else{
i++;
}
}
return res;
}
}; |
1af2f09dc169c7686e12a2af82ae9df23851d7dc | 6c2fb919ca100ff4f7a8400b2e5fd385ada410b1 | /Dijkstra.cpp | a45c264231d73dd9a017370665625aee2781ea24 | [] | no_license | Katya-p/Treasure-Hunt | 8c708fc1b5761af5d3112284db9bbc0c3a03be08 | c426f8f4225b3d52a7ec6952ceecfae07e01b944 | refs/heads/master | 2020-04-20T06:02:16.991768 | 2019-02-01T09:22:39 | 2019-02-01T09:22:39 | 168,672,253 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,312 | cpp | Dijkstra.cpp | #include "Dijkstra.h"
int get_result(int ** matrix, size_t size, size_t amount_of_outer_walls)
{
//Dijkstra's algorithm
size_t treasure = 0;
std::vector<int> distance; //vector of minimal distances between treasure and other vertexes
std::vector<bool> visited; //vector of visited vertexes
for (size_t i = 0; i < size; i++)
{
distance.push_back(INT_MAX);
visited.push_back(false);
}
distance.at(treasure) = 0;
size_t index;
for (size_t count = 0; count < size - 1; count++)
{
int min = INT_MAX;
for (size_t i = 0; i < size; i++) {
if (!visited.at(i) && distance.at(i) <= min)
{
min = distance.at(i);
index = i;
}
}
visited.at(index) = true;
for (size_t i = 0; i < size; i++)
if (!visited.at(i) && matrix[index][i] && distance[index] != INT_MAX && distance[index] + matrix[index][i] < distance.at(i)) {
distance.at(i) = distance.at(index) + matrix[index][i];
}
}
//finding minimal distance between treasure and midpoints of outer walls
//it is known that outer vertexes are at the end of vector of walls, amount of outer walls is calculated
int result = INT_MAX;
for (size_t i = size - amount_of_outer_walls; i != size; i++) {
if (distance.at(i) < result) {
result = distance.at(i);
}
}
return result;
} |
be588b202662bae44371c0c74f931afd6fdeb44a | 30a3e10673b3244206abe0611ced13e714e1bff5 | /DesignMode/AdapterMode/ElectricAdapter.cpp | d205a5ccd85dfae94ff25693a04692f1240abdeb | [] | no_license | fhLiu/MyProject | c68f31923ee41fd797041c6e346691361c16af01 | 620730ddb9f0caf630d7a20cf6a6f6c84f96baf2 | refs/heads/master | 2021-12-23T06:57:18.769690 | 2021-12-13T11:50:55 | 2021-12-13T11:50:55 | 158,992,520 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 157 | cpp | ElectricAdapter.cpp | #include "ElectricAdapter.h"
ElectricAdapter::ElectricAdapter(ElectricMotor * em):p_em(em)
{
}
void ElectricAdapter::Drive()
{
p_em->ElecticDrive();
} |
ba5a567d5b83faed2dd3b611655b2d829fafdf42 | 5cee480c663873932a004aae7f599f3510b3cb34 | /Football/Football/main.cpp | df0e4b124439f8e7dff1e804ed6a9a0108ae2ea4 | [] | no_license | Verterax/CodeEval_Solutions | 692b70d53536b7e673b17839ef7d9e951769ed97 | 880df0ca1407c538b07ba19008efac2b67f67dcf | refs/heads/master | 2020-08-31T23:24:14.640315 | 2019-10-31T16:40:46 | 2019-10-31T16:40:46 | 218,812,004 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,471 | cpp | main.cpp | // By Christopher Caldwell
// chris@codehadouken.com
// Challenge 230
// Football
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
#pragma region Defaults
//Reads a file, and returns the
//contents as a vector of strings
vector<string> GetLines(string fileName)
{
string line;
vector<string> lines;
ifstream file(fileName);
if (file.is_open())
{
while (getline(file, line))
{
if (line.length() > 0)
lines.push_back(line);
}
}
else
{
cout << "Unable to open file.\n";
}
file.close();
return lines;
}
//Parses tokens out of a string
//Using a specified char as the delimiter.
vector<string> GetTokens(string line, char delim)
{
vector<string> tokens;
string token;
stringstream stream(line);
while (std::getline(stream, token, delim))
{
tokens.push_back(token);
}
return tokens;
}
//Parses numeric tokens out of a string
//using the specified char as the delimiter.
//Returns a vector of ints
vector<int> GetInts(string line, char delim)
{
vector<int> tokens;
string token;
stringstream stream(line);
while (std::getline(stream, token, delim))
{
int n = atoi(token.c_str());
if (n != 0)
tokens.push_back(n);
}
return tokens;
}
//Takes a string by reference and removes
//matching chars found in the chars[] array.
void RemChars(string& str, const char chars[], int charLen)
{
int i;
int strLen = str.size();
string::iterator iter = str.begin();
bool didErase = false;
while (iter != str.end())
{
didErase = false;
for (i = 0; i < charLen; i++)
if ((*iter) == chars[i])
{
str.erase(iter);
didErase = true;
break;
}
if (!didErase) iter++;
}
}
//country(teams)
// Input -> 1 2 3 4 | 3 1 | 4 1
// Output-> 1:1,2,3; 2:1; 3:1,2; 4:1,3;
class Team
{
public:
Team(){}
Team(int teamID){ this->teamID = teamID; }
int teamID;
vector<int> countryIDs;
};
//Template function set to run on each
//line read from the text file.
void PrintFans(string line)
{
//Code goes here.
vector<string> countries = GetTokens(line, '|');
map<int, Team> teamMap;
vector<int> teamIDs;
//Load teams for each country.
for (int c = 0; c < countries.size(); c++)
{
vector<int> teams = GetInts(countries[c], ' ');
for (int t = 0; t < teams.size(); t++)
{
if (teamMap.find(teams[t]) == teamMap.end())
{
Team newTeam(teams[t]);
newTeam.countryIDs.push_back(c+1);
teamMap.emplace(teams[t], newTeam);
teamIDs.push_back(teams[t]);
}
else
{
teamMap[teams[t]].countryIDs.push_back(c+1);
}
}
}
sort(teamIDs.begin(), teamIDs.end());
for (int i = 0; i < teamIDs.size(); i++)
{
cout << teamIDs[i] << ":";
sort(teamMap[teamIDs[i]].countryIDs.begin(), teamMap[teamIDs[i]].countryIDs.end());
for (int c = 0; c < teamMap[teamIDs[i]].countryIDs.size(); c++)
{
cout << teamMap[teamIDs[i]].countryIDs[c];
cout << ((c == teamMap[teamIDs[i]].countryIDs.size() - 1) ? ';' : ',');
}
if (i != teamIDs.size() - 1) cout << ' ';
}
cout << endl;
}
int main(int argc, char* argv[])
{
if (argc == 1) { cout << "No file\n" << endl; return 0; }
//Reads text-file lines into vector of strings.
vector<string> lines = GetLines(argv[1]);
int lineCount = lines.size();
if (lineCount == 0) { cout << "No lines\n"; return 0; }
for (int i = 0; i < lineCount; i++)
{
//Evaluate lines.
PrintFans(lines[i]);
}
return 0;
}
#pragma endregion |
79939bfe6601ecf81892febe6a8d427ef42973dc | b13efe596569967ba8f32f055f54b8315f55a9a5 | /main.cpp | 4b7ce4229f7ac1f7926dad93090a72d64095d9ba | [] | no_license | av-novikov/msh-neighbor | da9c91b519c503a8769a09e0e244bbe7c2393ae1 | e204244709e924f49195c3980b9178e6e8a4b599 | refs/heads/master | 2023-02-11T14:35:39.020105 | 2018-01-14T22:45:19 | 2018-01-14T22:45:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 308 | cpp | main.cpp | #include <iostream>
#include <memory>
#include "src/MshReader.hpp"
using namespace std;
int main()
{
mshreader::MshReader reader;
std::shared_ptr<grid::Mesh> mesh = make_shared<grid::Mesh>(*reader.read("attempt4.msh"));
mesh->process_geometry();
reader.write(mesh.get(), "attempt4.nebr");
return 0;
} |
6d30c33694c52f603ad6a1b71e09284caa2b8cf8 | 011006ca59cfe75fb3dd84a50b6c0ef6427a7dc3 | /codeforces/round423/C_DNA_Evolution.cpp | 37e05397c6cc45af32e9ab31b94d61c2c28e3138 | [] | no_license | ay2306/Competitive-Programming | 34f35367de2e8623da0006135cf21ba6aec34049 | 8cc9d953b09212ab32b513acf874dba4fa1d2848 | refs/heads/master | 2021-06-26T16:46:28.179504 | 2021-01-24T15:32:57 | 2021-01-24T15:32:57 | 205,185,905 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 7,208 | cpp | C_DNA_Evolution.cpp | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
const long long mod = 1e9+7;
// const long long mod = 998244353;
const long long int special_prime = 982451653;
using namespace std;
// DEBUGGER
// *
vector<string> vec_splitter(string s) {
s += ',';
vector<string> res;
while(!s.empty()) {
res.push_back(s.substr(0, s.find(',')));
s = s.substr(s.find(',') + 1);
}
return res;
}
void debug_out(
vector<string> __attribute__ ((unused)) args,
__attribute__ ((unused)) int idx,
__attribute__ ((unused)) int LINE_NUM) { cerr << endl; }
template <typename Head, typename... Tail>
void debug_out(vector<string> args, int idx, int LINE_NUM, Head H, Tail... T) {
if(idx > 0) cerr << ", "; else cerr << "Line(" << LINE_NUM << ") ";
stringstream ss; ss << H;
cerr << args[idx] << " = " << ss.str();
debug_out(args, idx + 1, LINE_NUM, T...);
}
#ifdef LOCAL
#define debug(...) debug_out(vec_splitter(#__VA_ARGS__), 0, __LINE__, __VA_ARGS__)
#else
#define debug(...) 42
#endif
// *
// DEBUGGER
#define test int t; cin>>t; while(t--)
#define init(arr,val) memset(arr,val,sizeof(arr))
#define loop(i,a,b) for(int i=a;i<b;i++)
#define loopr(i,a,b) for(int i=a;i>=b;i--)
#define loops(i,a,b,step) for(int i=a;i<b;i+=step)
#define looprs(i,a,b,step) for(int i=a;i>=b;i-=step)
#define ull unsigned long long int
#define ll long long int
#define P pair
#define PLL pair<long long, long long>
#define PII pair<int, int>
#define PUU pair<unsigned long long int, unsigned long long int>
#define L list
#define V vector
#define D deque
#define ST set
#define MS multiset
#define mp make_pair
#define pb emplace_back
#define pf push_front
#define MM multimap
#define F first
#define S second
#define IT iterator
#define RIT reverse_iterator
#define FAST ios_base::sync_with_stdio(false);cin.tie();cout.tie();
#define FILE_READ_IN freopen("input.txt","r",stdin);
#define FILE_READ_OUT freopen("output.txt","w",stdout);
#define all(a) a.begin(),a.end()
#define ld long double
#define sz(x) (int)((x).size())
#define square(x) ((x)*(x))
#define cube(x) ((x)*(x)*(x))
#define distance(a,b,c,d) ((a-c)*1LL*(a-c)+(b-d)*1LL*(b-d))
#define range(i,x,y) ((x <= i) && (i <= y))
#define SUM(a) accumulate(a.begin(),a.end(),0LL)
#define lb lower_bound
#define ub upper_bound
#define REV reverse
#define seive(N) int pr[N]; void preSieve(){for(int i = 2; i < N; ++i){if(!pr[i])for(int j = i; j < N; j+=i)pr[j]=i;}}
#define modInv(N) ll inv[N]; void preModInv(){inv[0]=0;inv[1]=1;for(int i = 2; i < N; ++i)inv[i] = mod-mod/i*inv[mod%i]%mod;}
#define fact(N) ll fact[N]; void preFact(){fact[0] = 1,fact[1] = 1; for(int i = 2; i < N; ++i)fact[i]=fact[i-1]*i%mod;}
#define inFact(N) ll ifact[N]; void preiFact(){ifact[1] = 1; for(int i = 2; i < N; ++i)ifact[i]=ifact[i-1]*inv[i]%mod;}
// Randomization
// pair operation
template<class T, class U>istream& operator>>(istream& in, pair<T,U> &rhs){in >> rhs.first;in >> rhs.second;return in;}
template<class T, class U>ostream& operator<<(ostream& out,const pair<T,U> &rhs){out << rhs.first;out << " ";out << rhs.second;return out;}
template<class T, class U>pair<T,U> operator+(pair<T,U> &a, pair<T,U> &b){return pair<T,U>(a.first+b.first,a.second+b.second);}
template<class T, class U>pair<T,U> operator-(pair<T,U> &a, pair<T,U> &b){return pair<T,U>(a.first-b.first,a.second-b.second);}
// Linear STL
// VECTOR
template<class T>istream& operator>>(istream& in, vector<T> &a){for(auto &i: a)cin >> i;return in;}
template<class T>ostream& operator<<(ostream& out, const vector<T> &a){for(auto &i: a)cout << i << " ";return out;}
// SET
template<class T>ostream& operator<<(ostream& out, const set<T> &a){for(auto &i: a)cout << i << " ";return out;}
template<class T>ostream& operator<<(ostream& out, const unordered_set<T> &a){for(auto &i: a)cout << i << " ";return out;}
template<class T>ostream& operator<<(ostream& out, const multiset<T> &a){for(auto &i: a)cout << i << " ";return out;}
// MAP
template<class T,class U>ostream& operator<<(ostream& out, const map<T,U> &a){for(auto &i: a)cout << "(" << i.first << ", " << i.second << ")\n";return out;}
template<class T,class U>ostream& operator<<(ostream& out, const unordered_map<T,U> &a){for(auto &i: a)cout << "(" << i.first << ", " << i.second << ")\n";return out;}
const long long N = 1e5 + 10;
const long long inf = 1e9;
const long double pi = acos(-1);
int val(char c){
if(c == 'A')return 0;
if(c == 'T')return 1;
if(c == 'G')return 2;
return 3;
}
struct Node{
int cnt[4];
Node(char s = ' '){
memset(cnt,0,sizeof(cnt));
if(s != ' ')cnt[val(s)]++;
}
Node operator+(const Node &r){
Node a;
loop(i,0,4){
a.cnt[i] = cnt[i] + r.cnt[i];
}
return a;
}
};
struct segmentTree{
Node tree[(N+10)<<2];
void update(int id, char s,int node = 1, int start = 1, int end = N){
if(start == end){
memset(tree[node].cnt,0,sizeof(tree[node].cnt));
tree[node].cnt[val(s)]++;
return;
}
int mid = start + end >> 1;
if(id <= mid)update(id,s,node<<1,start,mid);
else update(id,s,node<<1|1,mid+1,end);
tree[node] = tree[node << 1] + tree[node << 1 | 1];
}
Node query(int l, int r, int node = 1, int start = 1, int end = N){
if(r < l || l > end || r < start)return Node();
if(l <= start && end <= r)
return tree[node];
int mid = start + end >> 1;
return query(l,r,node << 1, start, mid)+query(l,r,node << 1 | 1, mid+1, end);
}
};
struct query{
string a;
int t, l, r, x;
char p;
query(){}
query(int t, int x, char p):t(t),x(x),p(p){}
query(int t, int l, int r, string a):t(t),l(l),r(r),a(a){}
};
void solve(int test_case){
string st;
cin >> st;
int q;
cin >> q;
vector<query> Q;
int idx = 0;
loop(j,0,q){
int t;
cin >> t;
if(t == 1){
int x;
char p;
cin >> x >> p;
Q.pb(1,x,p);
continue;
}else{
idx++;
string a;
int l,r;
cin >> l >> r;
cin >> a;
Q.pb(2,l,r,a);
}
}
vector<int> ans(idx);
loop(md,1,11){
idx = -1;
segmentTree *s = new segmentTree[md];
loop(i,0,st.size()){
s[(i+1)%md].update(i+1,st[i]);
}
loop(qu,0,q){
if(Q[qu].t ==1){
s[Q[qu].x%md].update(Q[qu].x,Q[qu].p);
continue;
}
idx++;
int n = Q[qu].a.size();
if(n != md)continue;
loop(i,0,n){
if(Q[qu].l + i > Q[qu].r)break;
ans[idx] += s[(Q[qu].l+i)%n].query(Q[qu].l,Q[qu].r).cnt[val(Q[qu].a[i])];
}
}
delete[] s;
}
for(int i : ans)cout << i << "\n";
}
int main(){
FAST
auto clk = clock();
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int t = 1;
//cin >> t;
loop(i,1,t+1)solve(i);
#ifdef LOCAL
cout << "\n\nTIME ELAPSED : " << double(clock() - clk)/CLOCKS_PER_SEC * 1000.0 << " ms.\n";
#endif
}
|
73b961a6bd7471f3d568ecfa44a4e38bf3054ded | 15e79f904954c6456eebfad1eb109a3c29d61c5a | /src/libConfigurationManagement/src-exe/WebControlPanelPasswordTool.cpp | 8621c5a031648bc5b98bad4bb06e1353a6e21f7e | [] | no_license | Darksider7/terkos | e8ded3f2f45e7132c2f74a1936b6879bce92f668 | 593ad04a31fd09c10776337c847e9a171212e80d | refs/heads/master | 2016-09-06T11:51:53.588709 | 2013-01-21T06:58:31 | 2013-01-21T06:58:31 | 37,706,130 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,178 | cpp | WebControlPanelPasswordTool.cpp | //
// This file is part of Terk and TerkOS.
//
// All Terk and TerkOS source code is provided under the terms of the
// GNU General Public License v2 (http://www.gnu.org/licenses/gpl-2.0.html).
// Those wishing to use Terk and TerkOS source code, software and/or
// technologies under different licensing terms should contact us at
// telepresencerobotkit@cs.cmu.edu. Such licensing terms are available for
// all portions of the Terk and TerkOS codebase presented here.
//
/*
* Simple program for resetting the web control panel password via the command line.
* Note that the web server is not restarted, so changes won't take effect until it
* is restarted.
*
* To reset the password, call the program with a "--reset" argument. The program
* will print "1" if the reset was successful and "0" otherwise.
*
* Chris Bartley (bartley@cmu.edu)
*/
#include <json/json.h>
#include <WebControlPanelPasswordManager.h>
using namespace std;
int main(int argc, char** argv)
{
if (argc > 1)
{
if (strcmp(argv[1], "--reset") == 0)
{
cout << WebControlPanelPasswordManager::revertToDefault() << endl;
}
}
return 0;
}
|
22ab3dd0965fd19ae2c394b6614ad107eb48b574 | 3157d25e573dc6ad770a07f24b77841db174cb98 | /Source/SG/Core/SGName.cpp | 14e985c11f5e56ff4b71466b32500faf275b7b35 | [
"MIT"
] | permissive | bazhi/SG | 882b4744b59a8ef2fdca0ef15a0b86e9c4c784f0 | d84f39b91b468f1f72ab7ee33e4ca44a9cb9c4e7 | refs/heads/main | 2023-02-27T01:21:14.242333 | 2021-02-09T08:55:52 | 2021-02-09T08:55:52 | 318,170,008 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21 | cpp | SGName.cpp | #include "SGName.h"
|
535660bb31d73b9109be48113f115f90eacc9ccf | 8ee5416ec56b9cc1d9ad2ce48cf690fa012c5ce4 | /PhysX.Net-3/Source/ConstraintDesc.h | db9c00ee020731a159de72b755e8610dcc39fb07 | [] | no_license | HalcyonGrid/PhysX.net | a573e0ceb9153c3777e71cb9d1434c5d74589df6 | 2a4bfc7a6619091bb3be20cb058f65306e4d8bac | refs/heads/master | 2020-03-26T12:30:31.701484 | 2015-09-10T04:24:00 | 2015-09-10T04:24:00 | 144,896,344 | 3 | 2 | null | 2018-08-15T19:44:31 | 2018-08-15T19:44:30 | null | UTF-8 | C++ | false | false | 105 | h | ConstraintDesc.h | #pragma once
namespace PhysX
{
public ref class ConstraintDesc
{
public:
ConstraintDesc();
};
}; |
5bd349c012e9f3bbcee41ef0f344dcc87bf5b102 | ba9f189b7b5a977e878729f3e8f05caca20b0d66 | /Models/colorprocessor.h | ebbe5e52e843cdb3069a1a11ebb3819356ac2919 | [] | no_license | mortalis13/Qt-Color-Picker-Qt | e8db29b9048ee3a8287c6b284e6e5b9ed16a7ec7 | 0704202bf22576b41d22b536eeb0dfbdfa3e506f | refs/heads/master | 2023-01-28T00:58:45.339092 | 2023-01-19T09:21:39 | 2023-01-19T09:21:39 | 36,451,229 | 13 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,085 | h | colorprocessor.h | #ifndef COLORPROCESSOR_H
#define COLORPROCESSOR_H
#include <QtCore>
#include <QColor>
#include <QObject>
#include <QClipboard>
#include "Widgets/ColorWidgets/hselector.h"
#include "Widgets/ColorWidgets/svselector.h"
#include "Service/vars.h"
class ColorProcessor : public QObject
{
Q_OBJECT
public:
explicit ColorProcessor(HSelector* hSelector, SVSelector* svSelector, QObject* parent=0);
QString getHSV(QColor color);
QString getRGB(QColor color);
QString getCMYK(QColor color);
QString getHex(QColor color);
QColor getColorHSV(QString HSV_Text);
QColor getColorRGB(QString RGB_Text);
QColor getColorCMYK(QString CMYK_Text);
QColor getColorHex(QString Hex_Text);
void updateColorHSV(QString HSV);
void updateColorRGB(QString RGB);
void updateColorCMYK(QString CMYK);
void updateColorHex(QString Hex);
void updateColor(QColor color);
void copyText(QString text);
QString pasteText();
signals:
void updateFinished();
private:
HSelector* hSelector;
SVSelector* svSelector;
QClipboard* clip;
};
#endif // COLORPROCESSOR_H
|
ec02180f3e04554f03f34c5df9e32ff3ab13eebc | d055d59b235c9f83c27ce6fc83e21b1209e4e072 | /Pointers/PointersToArray2.cpp | f185cd961c88b9faceee84cbe93b3360bf1948b2 | [] | no_license | bmegha98/Cpp-Basics | c8674b100ac19b8c9d17f6fd0ba70dd6341607d0 | 791fb05ccf7322585b1b163c993cada62e060bb4 | refs/heads/master | 2022-12-24T16:13:02.117888 | 2020-10-03T05:39:33 | 2020-10-03T05:39:33 | 195,042,766 | 0 | 0 | null | 2020-10-03T05:39:34 | 2019-07-03T11:45:23 | C++ | UTF-8 | C++ | false | false | 500 | cpp | PointersToArray2.cpp | #include<iostream>
using namespace std;
int main()
{
int A[][4] = {{ 10, 11, 12, 13 },
{ 20, 21, 22, 23 },
{ 30, 31, 32, 33 }
};
//(arr + i) = arr[i] - Base address of ith 1-D array -> Points to 0th element of ith 1-D array
for(int i =0;i<3;i++)
{
cout<<"Address of "<<i<<"th array : "<<A[i]<<"\t"<<*(A+i)<<endl;
for(int j =0;j<4;j++)
{
cout<<"A["<<i<<"]["<<j<<"] : "<<*(A+i)+j<<"\t"<<*(*(A+i)+j)<<endl;
}
}
return 0;
}
|
00642728cce430d60d594d8c31aef3c67f588153 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /components/optimization_guide/content/browser/page_content_annotations_web_contents_observer.cc | d62f9f2af31dc8c9f1f033471bb8f2d9cdad57e1 | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 3,217 | cc | page_content_annotations_web_contents_observer.cc | // Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/optimization_guide/content/browser/page_content_annotations_web_contents_observer.h"
#include "base/functional/bind.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/utf_string_conversions.h"
#include "components/google/core/common/google_util.h"
#include "components/no_state_prefetch/browser/no_state_prefetch_manager.h"
#include "components/optimization_guide/content/browser/page_content_annotations_service.h"
#include "components/optimization_guide/core/optimization_guide_features.h"
#include "components/optimization_guide/core/optimization_guide_logger.h"
#include "components/optimization_guide/core/optimization_guide_switches.h"
#include "components/search_engines/template_url_service.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/page_user_data.h"
#include "third_party/blink/public/mojom/opengraph/metadata.mojom.h"
namespace optimization_guide {
namespace {
// Creates a HistoryVisit based on the current state of |web_contents|.
HistoryVisit CreateHistoryVisitFromWebContents(
content::WebContents* web_contents) {
HistoryVisit visit(
web_contents->GetController().GetLastCommittedEntry()->GetTimestamp(),
web_contents->GetLastCommittedURL());
return visit;
}
} // namespace
PageContentAnnotationsWebContentsObserver::
PageContentAnnotationsWebContentsObserver(
content::WebContents* web_contents,
PageContentAnnotationsService* page_content_annotations_service,
TemplateURLService* template_url_service,
prerender::NoStatePrefetchManager* no_state_prefetch_manager)
: content::WebContentsObserver(web_contents),
content::WebContentsUserData<PageContentAnnotationsWebContentsObserver>(
*web_contents),
page_content_annotations_service_(page_content_annotations_service),
salient_image_retriever_(
page_content_annotations_service_->optimization_guide_logger()),
template_url_service_(template_url_service),
no_state_prefetch_manager_(no_state_prefetch_manager) {
DCHECK(page_content_annotations_service_);
}
PageContentAnnotationsWebContentsObserver::
~PageContentAnnotationsWebContentsObserver() = default;
void PageContentAnnotationsWebContentsObserver::DidStopLoading() {
salient_image_retriever_.GetOgImage(web_contents());
}
void PageContentAnnotationsWebContentsObserver::
DocumentOnLoadCompletedInPrimaryMainFrame() {
if (!optimization_guide::features::ShouldExtractRelatedSearches()) {
return;
}
if (!google_util::IsGoogleSearchUrl(web_contents()->GetLastCommittedURL())) {
return;
}
optimization_guide::HistoryVisit history_visit =
CreateHistoryVisitFromWebContents(web_contents());
page_content_annotations_service_->ExtractRelatedSearches(history_visit,
web_contents());
}
WEB_CONTENTS_USER_DATA_KEY_IMPL(PageContentAnnotationsWebContentsObserver);
} // namespace optimization_guide
|
ce25c2e06ca1b90b5efba8ec5844fbf1696f8f42 | 6e140dcde0a63b02f18a51c6a82903e00e10bdd5 | /source/AlgebraGemetrica.cpp | 2d86afe366e079e469893781fecc8f991788691f | [] | no_license | altobellibm/geometric_algebra | 6ce05672a734fb578898d660b1dfd86896955603 | 346236b8f74526bae3e16d2cb72c5965ec427116 | refs/heads/master | 2021-01-12T14:09:19.712430 | 2016-12-14T10:35:36 | 2016-12-14T10:35:36 | 69,759,711 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,731 | cpp | AlgebraGemetrica.cpp | // AlgebraGemetrica.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <string>
#include "Multivector.h"
typedef std::vector<Multivector<int>> BASE_BLADE;
typedef std::vector<std::vector<Multivector<int>>> CLIFFORD_TABLE;
enum class OPERATION { GP, SCP, LCONST, RCONST, OUTP };
/*
void createCliffordTable(const BASE_BLADE& _bladesBase, OPERATION _type, CLIFFORD_TABLE& _table, const Orthonormal* ortonormal = NULL ){
if ((OPERATION::GP == _type || OPERATION::SCP == _type || OPERATION::LCONST == _type || OPERATION::RCONST == _type) && (ortonormal == NULL)) {
std::cout << "Must pass metric matrix!" << std::endl;
return;
}
_table.resize(_bladesBase.size(), std::vector<Multivector<int>>(_bladesBase.size()));
for(BASE_BLADE::size_type i = 0; i < _bladesBase.size(); i++)
for(BASE_BLADE::size_type j = 0; j < _bladesBase.size(); j++){
switch (_type) {
case OPERATION::GP: _table[i][j] = GP(_bladesBase[i], _bladesBase[j],*ortonormal); break;
case OPERATION::SCP:
{
Multivector<int> A = (e(0)*SCP(_bladesBase[i], _bladesBase[j],*ortonormal));
_table[i][j] = A;
break;
}
case OPERATION::LCONST: _table[i][j] = LConst(_bladesBase[i], _bladesBase[j],*ortonormal); break;
case OPERATION::RCONST: _table[i][j] = RConst(_bladesBase[i], _bladesBase[j],*ortonormal); break;
case OPERATION::OUTP: _table[i][j] = _bladesBase[i] ^ _bladesBase[j]; break;
default:
break;
}
}
}
void printTableBladeBase(const std::string& _title, const BASE_BLADE& _bladesBase, const CLIFFORD_TABLE& _table) {
if (_table.size() != _bladesBase.size())
return;
std::cout << _title << std::endl << std::endl;
for (BASE_BLADE::size_type i = 0; i < _bladesBase.size(); i++){
std::cout << "Blade reference = " << _bladesBase[i] << std::endl << std::endl;
for (BASE_BLADE::size_type j = 0; j < _bladesBase.size(); j++)
std::cout << _bladesBase[i] << " " << _bladesBase[j] << " = " << _table[i][j] << std::endl;
std::cout << std::endl;
}
}
*/
int main(int , char** )
{
std::cout << (e(20)) << std::endl;
std::cout << (e(3)) << std::endl;;
// Exercício 1
/*std::cout << "Question 1." << std::endl;
std::cout << "Item a) " << std::endl;
std::cout << ((e(1)+e(2))^(e(3)+e(2))) << std::endl << std::endl;
std::cout << "Item b) " << std::endl;
std::cout << ((e(2) - e(1)) ^ (e(1) - 2.0*e(3))) << std::endl << std::endl;
std::cout << "Item c) " << std::endl;
std::cout << ((4.0*e(1) + e(2) + e(3)) ^ (3.0*e(1))) << std::endl << std::endl;
std::cout << "Item d) " << std::endl;
std::cout << ((e(2) + e(3)) ^ ((1.0/2.0)*e(1) + e(2) + (3.0/2.0)*e(3))) << std::endl << std::endl;
std::cout << "Item e) " << std::endl;
std::cout << ((e(1) + e(2)) ^ ((e(2)^e(1)) + (e(3)^e(2)))) << std::endl << std::endl;
// Exercício 2
std::cout << std::endl;
std::cout << "Question 2." << std::endl;
std::cout << "Item a) " << std::endl;
std::cout << (e(1) ^ (e(1) ^ (e(2) + 2 * e(3)) ^ e(4))) << std::endl << std::endl;
std::cout << "Item b) " << std::endl;
std::cout << ((e(1) - 3 * e(4)) ^ (e(1) ^ (e(2) + 2 * e(3)) ^ e(4))) << std::endl << std::endl;
std::cout << "Item c) " << std::endl;
std::cout << ((e(2) + e(3)) ^ (e(1) ^ (e(2) + 2 * e(3)) ^ e(4))) << std::endl << std::endl;
// Exercício 3
std::cout << std::endl;
std::cout << "Question 3." << std::endl;
std::cout << ( (2*e(2) + e(3)) ^ (e(2) - 1*e(3)) ) << std::endl;
// Exercício 4
Orthonormal ortonormal(3);
Multivector<int> a = (e(1) + e(3));
Multivector<int> b = (e(1) + e(2));
std::cout << std::endl;
std::cout << "Question 4." << std::endl;
std::cout << "Item a) " << std::endl;
std::cout << SCP(a, b, ortonormal) << std::endl << std::endl;
std::cout << "Item b) " << std::endl;
std::cout << LConst((e(3)),b, ortonormal) << std::endl << std::endl;
std::cout << "Item c) " << std::endl;
std::cout << LConst((e(3)),(a^b),ortonormal) << std::endl << std::endl;
std::cout << "Item d) " << std::endl;
std::cout << LConst((a^b),(e(1)),ortonormal) << std::endl << std::endl;
std::cout << "Item e) " << std::endl;
std::cout << SCP((2*a + b),(a+b),ortonormal) << std::endl << std::endl;
std::cout << "Item f) " << std::endl;
std::cout << RConst((e(1)^e(2)^e(3)),b,ortonormal) << std::endl << std::endl;
// Exercício 5
// dúvida
// Exercício 6
// dúvida
// Exercício 7
std::cout << std::endl;
std::cout << "Question 7." << std::endl;
BASE_BLADE bladesBase = {(e(0)),(e(1)),(e(2)),(e(3)), (e(1)^e(2)), (e(1)^e(3)), (e(2)^e(3)),(e(1)^e(2)^e(3))};
CLIFFORD_TABLE tableGP;
createCliffordTable(bladesBase, OPERATION::GP, tableGP, &ortonormal);
std::cout << std::endl;
printTableBladeBase("Geometric product of blade!", bladesBase ,tableGP);
CLIFFORD_TABLE tableSCP;
createCliffordTable(bladesBase, OPERATION::SCP, tableSCP, &ortonormal);
std::cout << std::endl;
printTableBladeBase("Scalar product of blade!", bladesBase, tableSCP);
CLIFFORD_TABLE tableLCONST;
createCliffordTable(bladesBase, OPERATION::LCONST, tableLCONST, &ortonormal );
std::cout << std::endl;
printTableBladeBase("Left contraction of blade!", bladesBase, tableLCONST);
CLIFFORD_TABLE tableOUTP;
createCliffordTable(bladesBase, OPERATION::OUTP, tableOUTP);
std::cout << std::endl;
printTableBladeBase("Outer product!", bladesBase, tableOUTP);
// Exercício 8
*/
return 0;
}
|
9ccda26c5416b3d2011f2474846ed19e059a98c6 | 069567c7d9a298c9838fbd07b0baf8b300f9e722 | /play_me/particle_system.cpp | b68f9ed3b353b59df9973e4243ce05ba3edd77b0 | [] | no_license | miha1994/play_me | 992c4122f01c9f16762882db96e17aca5fa01f81 | c383a7f90f6ef1f24bd721b44fb5e04ea2366ecf | refs/heads/master | 2021-01-20T20:35:40.525773 | 2016-07-26T09:56:48 | 2016-07-26T09:56:48 | 60,350,588 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,248 | cpp | particle_system.cpp | #include "particle_system.h"
#include "core.h"
#include "Renderer.h"
void particle_sys_1::add_elem (rgba_array *tex, v2f start_position, v2f velocity_direction, float len1, float len2, float len3, float time_of_all_moving) {
elem el;
el.tex = tex;
el.pos = start_position;
float whole_len = len1 + len2 + len3;
el.vel = velocity_direction * (whole_len / time_of_all_moving / length (velocity_direction));
el.tm[0] = (len1 / whole_len) * time_of_all_moving;
el.tm[1] = (len2 / whole_len) * time_of_all_moving;
el.tm[2] = (len3 / whole_len) * time_of_all_moving;
el.phase = 0;
el.alpha1 = 0;
m_particles.push_back (el);
}
void particle_sys_1::upd (float dt) {
forstl_no_inc (p, m_particles) {
p->time += dt;
if (p->time > p->tm[p->phase]) {
if (p->phase == 2) {
p = m_particles.erase (p);
continue;
}
p->time -= p->tm[p->phase];
++ p->phase;
}
switch (p->phase) {
case 0:
p->alpha1 = p->time / p->tm[p->phase];
break;
case 1:
p->alpha1 = 1;
break;
case 2:
p->alpha1 = 1 - p->time / p->tm[p->phase];
break;
}
p->pos += p->vel * dt;
++p;
}
}
void particle_sys_1::render (v2f cam_pos) {
forstl (p, m_particles) {
D_ADD_SPRITE_ALPHA (*p->tex, p->pos - cam_pos, p->alpha1);
}
} |
728451bee388cbf2e6475079216df3d2425d0a1f | 34009a302872244c82934749694aef330835ebc8 | /src/functions/Arrays.hpp | 8cd1e4ec18d64bb26cb441d177fd6c1c88e04667 | [] | no_license | Kingmidas74/DataMining | 0229e345350da5af16c3017c0350710adb6d0003 | 70d9d23302cd16c9c6c36f1ab75875b80f054906 | refs/heads/master | 2021-08-22T17:42:39.243166 | 2021-06-21T19:48:51 | 2021-06-21T19:48:51 | 56,978,617 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 324 | hpp | Arrays.hpp | #pragma once
/**
Allocators.hpp
Purpose: Alignment allocators for XeonPhi.
@author Suleymanov D.
@version 0.0.0.1 9/17/2016
*/
namespace DataMining
{
using namespace std;
template <typename Type>
inline void copyArray(const Type * const from, Type * to, const size_t length)
{
copy(from, from+length, to);
}
}
|
e3f8ce5d58abb6ec58f2d7e22d07c87c128df2ed | fa391c1affe497abbde266e6ec70710f7c676b94 | /HardwarePlugins/PluginPxiSystem/NiToQ.cpp | efe4125ac5eae2822d9adb9177a8520b483d0bae | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | GaelReinaudi/LabExe-UserPlugins | d936d94271e946a2e8b0ebd998f287b30e22f6aa | 3f9de085115947bf9362a7c6f46fd89d5c0f8daa | refs/heads/master | 2021-01-18T21:34:54.755432 | 2017-11-29T04:50:49 | 2017-11-29T04:50:53 | 10,351,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 399 | cpp | NiToQ.cpp | #include "NiToQ.h"
QString NiToQString(CNiString strrr) {
QString newstr(strrr);
return newstr;
}
QStringList NiToQString(CNiStringVector list) {
QStringList newlist;
for(unsigned long i = 0; i < list.GetSize(); i++)
newlist.append(NiToQString(list[i]));
return newlist;
}
CNiDAQmxDevice PxiDaqDevice( QString &NiDeviceName )
{
return CNiDAQmxSystem::LoadDevice(NiDeviceName.toAscii());
} |
b35f4636a942534c9c0a852ced790080ce8fb724 | c5a768f229335b3bcd6a540d84a0ec501924f95c | /tests/cmake/include/fibonacci_test/main.cpp | f63346920d00aab03864a1eccaecbe7b915ba841 | [] | no_license | 2LoC/tl_base_ci | af2868f339d3776c80f15b9364dd122a694aba25 | 5eb5b0dba2f7a19bbe4228d98269328cebcb102c | refs/heads/master | 2021-09-13T00:03:21.130228 | 2018-04-22T23:04:39 | 2018-04-22T23:04:39 | 110,491,967 | 0 | 1 | null | 2017-11-14T23:56:11 | 2017-11-13T02:47:19 | CMake | UTF-8 | C++ | false | false | 642 | cpp | main.cpp | #include <fibonacci_test/main.h>
#include <cassert>
template <typename T>
void test_fib()
{
using tl_base_ci_tests::fibonacci;
assert(fibonacci(T(0)) == T(0));
assert(fibonacci(T(1)) == T(1));
assert(fibonacci(T(2)) == T(1));
assert(fibonacci(T(3)) == T(2));
assert(fibonacci(T(4)) == T(3));
assert(fibonacci(T(5)) == T(5));
assert(fibonacci(T(6)) == T(8));
assert(fibonacci(T(7)) == T(13));
assert(fibonacci(T(8)) == T(21));
assert(fibonacci(T(9)) == T(34));
assert(fibonacci(T(10)) == T(55));
}
int main()
{
test_fib<int>();
test_fib<float>();
test_fib<double>();
test_fib<long double>();
return 0;
}
|
b68d8a92fd23ed71c5a8d9872820c15623f55249 | 15a92aca70e6d9d7c477c5306ca44a6e0decef04 | /src/shared/state/Player.cpp | a9a07e408dd85a183690cefe54f92cb45551628f | [] | no_license | haomingtian/plt | 70e85ed033175bc45ce29825cee9992d66619e7c | d68099ec603928dfe654424d7b6bfaa91776c94c | refs/heads/master | 2020-07-28T03:39:58.453046 | 2020-01-06T13:47:37 | 2020-01-06T13:47:37 | 209,295,929 | 0 | 0 | null | 2019-09-18T11:51:59 | 2019-09-18T11:51:58 | null | UTF-8 | C++ | false | false | 495 | cpp | Player.cpp | #include <iostream>
#include "Player.h"
using namespace std;
namespace state {
Player::Player(std::string n_name){
name=n_name;
}
std::string Player:: getName (){
return name;
}
int Player::getNbCasle (){
return castle;
}
void Player::setNbCastle (int n_nb_castle){
castle=n_nb_castle;
}
int Player::getNbGold (){
return gold;
}
void Player::setNbGold (int n_nb_gold){
gold=n_nb_gold;
}
std::vector<UnityArmy> Player::getUnityArmy (){
return list_pions;
}
}
|
deceb14a326b1bc873e27c0e9c724e58fda15d03 | 1de7d2e5ed2f9e3d43a432cdd3095d20cb307eea | /data2vdf/vapor/vdfcreate.h | 8c4b3f4354588a3967eb364f11c89d4d326d238d | [] | no_license | schroederdewitt/mpdata-1 | 4fdae40ba73ec5ff473160966b7dbd25728a7628 | b6194fc6eab2f2e21cfa55760c82d2a4243e6c59 | refs/heads/master | 2021-06-18T09:04:31.198462 | 2017-05-18T08:05:03 | 2017-05-18T08:05:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,039 | h | vdfcreate.h | #ifndef VDFCREATE_H
#define VDFCREATE_H
#include <iostream>
#include <cstdio>
#include <vapor/OptionParser.h>
#include <vapor/MetadataVDC.h>
#include <vapor/DCReader.h>
#include <vapor/VDCFactory.h>
namespace VAPoR {
class VDF_API vdfcreate : public VetsUtil::MyBase {
public:
vdfcreate();
~vdfcreate();
int launchVdfCreate(int argc, char **argv, string NetCDFtype);
private:
string _progname;
//
// command line options passed to launchVdfCreate
//
vector <string> _vars;
VetsUtil::OptionParser::Boolean_T _help;
VetsUtil::OptionParser::Boolean_T _quiet;
VetsUtil::OptionParser::Boolean_T _debug;
int _numTS;
void Usage(VetsUtil::OptionParser &op, const char * msg);
void populateVariables(std::vector<std::string> vars,
std::vector<std::string> candidate_vars,
MetadataVDC *file,
int (MetadataVDC::*SetVarFunction)(const std::vector<std::string>&)
);
void writeToScreen(DCReader *DCdata, MetadataVDC *file);
MetadataVDC *CreateMetadataVDC(const VDCFactory &vdcf,
const DCReader *DCdata);
};
};
#endif
|
f3fb6d4c04802f47e29b43320c82ed79324b31db | 41177f9862aa322ee7177f7bf6769c7d84832fde | /Sprint2/Greedy/GreedyBursa.cpp | e6bdba28ffe941f04855a48e8f05963205eadfe4 | [] | no_license | gutovsky/Exsercises | efd2ef9206a09c1e368ca77ef048f43d5a7f0978 | 2620948b8d67df41eebbb50d9844f7d3cc52ce7a | refs/heads/main | 2023-02-04T23:16:49.790444 | 2020-12-22T08:05:53 | 2020-12-22T08:05:53 | 306,318,271 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,470 | cpp | GreedyBursa.cpp | #include iostream
#include string
#include vector
using namespace std;
void ParseStr(const string& to_parse, vectorint& to_save);
int CalcIncome(const vectorint& prices);
int main()
{
string buffer;
getline(cin, buffer);
int days_num = stol(buffer, nullptr, 10);
vectorint prices;
getline(cin, buffer);
ParseStr(buffer, prices);
cout CalcIncome(prices) endl;
}
void ParseStr(const string& to_parse, vectorint& to_save) {
string word;
for (const char c to_parse) {
if (c == ' ') {
if (!word.empty()) {
to_save.push_back(stol(word, nullptr, 10));
word.clear();
}
}
else {
word += c;
}
}
if (!word.empty()) {
to_save.push_back(stol(word, nullptr, 10));
}
}
int CalcIncome(const vectorint& prices) {
auto buy_price = prices.begin();
int income = 0;
while (buy_price != prices.end() - 1 && buy_price != prices.end()) {
auto sell_price = buy_price + 1;
int curr_income = sell_price - buy_price;
int max_curr_income = 0;
while (sell_price != prices.end()) {
curr_income = sell_price - buy_price;
if (max_curr_income curr_income) {
break;
}
max_curr_income = curr_income;
sell_price++;
}
income += max_curr_income;
buy_price = sell_price;
}
return income;
}
|
3f032a5dc605189e5906bb3b3e8833d59c0cd41e | 44ab57520bb1a9b48045cb1ee9baee8816b44a5b | /EngineTesting/Code/System/SystemTesting/HelperSuite/OpenGL/GlUtilityMacro/GlUtilityPreviouslyBodyTesting.h | 91403d66a2b61533a7118bd2a7a071c410afe65b | [
"BSD-3-Clause"
] | permissive | WuyangPeng/Engine | d5d81fd4ec18795679ce99552ab9809f3b205409 | 738fde5660449e87ccd4f4878f7bf2a443ae9f1f | refs/heads/master | 2023-08-17T17:01:41.765963 | 2023-08-16T07:27:05 | 2023-08-16T07:27:05 | 246,266,843 | 10 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,418 | h | GlUtilityPreviouslyBodyTesting.h | /// Copyright (c) 2010-2022
/// Threading Core Render Engine
///
/// 作者:彭武阳,彭晔恩,彭晔泽
/// 联系作者:94458936@qq.com
///
/// 标准:std:c++20
/// 引擎测试版本:0.8.1.5 (2022/12/18 13:00)
#ifndef SYSTEM_TESTING_HELPER_SUITE_GL_UTILITY_PREVIOUSLY_BODY_TESTING_H
#define SYSTEM_TESTING_HELPER_SUITE_GL_UTILITY_PREVIOUSLY_BODY_TESTING_H
#include "CoreTools/UnitTestSuite/UnitTest.h"
namespace System
{
class GlUtilityPreviouslyBodyTesting final : public CoreTools::UnitTest
{
public:
using ClassType = GlUtilityPreviouslyBodyTesting;
using ParentType = UnitTest;
public:
explicit GlUtilityPreviouslyBodyTesting(const OStreamShared& stream);
CLASS_INVARIANT_FINAL_DECLARE;
private:
void DoRunUnitTest() final;
void MainTest();
void PreviouslyBody0Test() noexcept;
void PreviouslyBody1Test() noexcept;
void PreviouslyBody2Test() noexcept;
void PreviouslyBody3Test() noexcept;
void PreviouslyBody4Test() noexcept;
void PreviouslyBody5Test() noexcept;
void PreviouslyBody6Test() noexcept;
void PreviouslyBody7Test() noexcept;
void PreviouslyBody8Test() noexcept;
void PreviouslyBody9Test() noexcept;
void PreviouslyBody10Test() noexcept;
};
}
#endif // SYSTEM_TESTING_HELPER_SUITE_GL_UTILITY_PREVIOUSLY_BODY_TESTING_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.